Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve)!: replace background tasks with blocking workflow tool calls (#3840)

Andrew Barbaefa0869033ce
diff --git a/.changeset/agent-sessions.md b/.changeset/agent-sessions.md
new file mode 100644
index 000000000..3a1d77151
--- /dev/null
+++ b/.changeset/agent-sessions.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+`ctx.agent(name)` in a workflow tool now returns a session with that agent: `send(message, { outputSchema, signal })` returns a response whose `result()` resolves the turn's `{ data, message, status }`, and the parent stream announces each session with `agent.started`, carrying the opening call's `callId` and `turnId`, which `session.streamSubagent()` accepts. `ctx.agent(name, { message, agentId })` is removed, sessions end when the workflow run finishes, and remote agents now check a protocol version, so upgrade both deployments together.
diff --git a/.changeset/ask-answer-or-withdraw-once.md b/.changeset/ask-answer-or-withdraw-once.md
new file mode 100644
index 000000000..8e940ffdd
--- /dev/null
+++ b/.changeset/ask-answer-or-withdraw-once.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+A `ctx.ask()` question now resolves the way the session decided it: an answer that reached the session before its withdrawal resolves the ask as `answered`, even after the signal aborted, so `ask_question` and the channel never disagree. Cancelling a `task()` also reports its pending questions `cancelled`, and question `requestId`s are now `<runId>-ask-<n>` instead of an internal hook token.
diff --git a/.changeset/remove-background-tasks.md b/.changeset/remove-background-tasks.md
new file mode 100644
index 000000000..8b7d6583e
--- /dev/null
+++ b/.changeset/remove-background-tasks.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Remove background tasks: workflow tools and subagent calls now always block the turn until they settle, `defineWorkflowTool` rejects `execution`, and `taskDeliveryPolicy`, the `task_cancel` tool, `session.cancel({ tasks })`, task receipts and notifications, and `<eve-empty-delivery/>` are gone. Extensions built against earlier capability epochs must be rebuilt.
diff --git a/.changeset/steering-signals.md b/.changeset/steering-signals.md
new file mode 100644
index 000000000..426ae1cfc
--- /dev/null
+++ b/.changeset/steering-signals.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Workflow tool bodies get `ctx.interruptSignal`, which aborts once when a steering message arrives while the turn waits on the call, and `ctx.ask(request, { signal })` withdraws the question when the signal aborts, resolving as `cancelled` with an `input.resolved` outcome of `"cancelled"`. `sleep` and `ask_question` now stop early for a new message, and `dismissible` and the `dismissed` status are removed; pass `{ signal: ctx.interruptSignal }` to `ctx.ask` instead.
diff --git a/.changeset/turn-waiting.md b/.changeset/turn-waiting.md
new file mode 100644
index 000000000..6c7599480
--- /dev/null
+++ b/.changeset/turn-waiting.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+A question or sign-in from inside a running call, such as a workflow tool's `ctx.ask()`, `ask_question`, or a subagent's question or connection sign-in, no longer ends the turn: the stream emits `input.requested` or `authorization.required`, then the new `turn.waiting` event, and the turn resumes under the same `turnId`. The session you answer on now emits `input.resolved` for every subagent or workflow tool question it routes an answer to, and `send().result()` stops at `turn.waiting` only while a question is pending. The message stream version is now 26, which older eve clients reject, so upgrade them with the server.
diff --git a/.changeset/workflow-tool-events-reach-hooks.md b/.changeset/workflow-tool-events-reach-hooks.md
new file mode 100644
index 000000000..7cde459f1
--- /dev/null
+++ b/.changeset/workflow-tool-events-reach-hooks.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+A workflow tool's `action.partial` updates now reach the channel adapter, stream-event hooks, and instrumentation, like the events a turn publishes, and the `input.resolved` a session emits when a question raised inside a call is answered or withdrawn now reaches the channel adapter and stream-event hooks. Both were previously written only to the session stream.
diff --git a/apps/docs/registry.json b/apps/docs/registry.json
index 83f188845..d00049db3 100644
--- a/apps/docs/registry.json
+++ b/apps/docs/registry.json
@@ -8,9 +8,7 @@
"type": "registry:item",
"title": "Self-modification",
"description": "Add a source editing subagent with local edits and official registry installation.",
- "dependencies": [
- "just-bash"
- ],
+ "dependencies": ["just-bash"],
"meta": {
"eve": {
"requires": ">=0.62.0",
@@ -18,10 +16,7 @@
"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."
@@ -33,11 +28,7 @@
{
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "self-modification"
- ]
+ "args": ["integration", "setup", "self-modification"]
}
]
}
@@ -55,9 +46,7 @@
"type": "registry:item",
"title": "Self-modification (Experimental)",
"description": "Add an experimental source editing subagent with local edits and official registry installation.",
- "dependencies": [
- "just-bash"
- ],
+ "dependencies": ["just-bash"],
"meta": {
"eve": {
"hidden": true,
@@ -65,10 +54,7 @@
"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."
@@ -80,11 +66,7 @@
{
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "self-modification"
- ]
+ "args": ["integration", "setup", "self-modification"]
}
],
"requires": ">=0.62.0"
@@ -103,9 +85,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",
@@ -119,9 +99,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": ""
},
@@ -138,9 +116,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": ""
},
@@ -157,10 +133,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": ""
},
@@ -177,9 +150,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": ""
@@ -197,9 +168,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": ""
},
@@ -221,11 +190,7 @@
"setup": {
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "file-memory"
- ]
+ "args": ["integration", "setup", "file-memory"]
},
"requires": ">=0.49.1",
"docs": "/docs/memory/file"
@@ -244,9 +209,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": ""
},
@@ -268,10 +231,7 @@
"type": "registry:item",
"title": "Upstash AgentKit",
"description": "Give your agents ranked recall and automatic capture on Upstash Redis, or a Redis backend for file memory.",
- "dependencies": [
- "@upstash/agentkit-eve",
- "@upstash/redis"
- ],
+ "dependencies": ["@upstash/agentkit-eve", "@upstash/redis"],
"envVars": {
"UPSTASH_REDIS_REST_URL": "",
"UPSTASH_REDIS_REST_TOKEN": ""
@@ -294,9 +254,7 @@
"type": "registry:item",
"title": "Kybernesis Arcana",
"description": "Give your agents workspace-scoped long-term memory with automatic recall and deliberate storage.",
- "dependencies": [
- "@kybernesis/arcana"
- ],
+ "dependencies": ["@kybernesis/arcana"],
"envVars": {
"ARCANA_API_KEY": "",
"ARCANA_WORKSPACE": ""
@@ -319,9 +277,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,7 +300,7 @@
"name": "tool/agent",
"type": "registry:item",
"title": "Agent",
- "description": "Add root-agent background delegation.",
+ "description": "Add root-agent delegation to other agents.",
"files": [
{
"path": "registry/tools/agent.ts",
@@ -405,19 +361,6 @@
}
]
},
- {
- "name": "tool/task_cancel",
- "type": "registry:item",
- "title": "Task Cancel",
- "description": "Cancel background tasks from the root session.",
- "files": [
- {
- "path": "registry/tools/task_cancel.ts",
- "type": "registry:file",
- "target": "agent/tools/task_cancel.ts"
- }
- ]
- },
{
"name": "tool/web_fetch",
"type": "registry:item",
@@ -536,9 +479,7 @@
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/vercel.ts",
@@ -558,20 +499,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",
@@ -591,20 +524,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",
@@ -624,20 +549,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",
@@ -657,20 +574,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",
@@ -705,12 +614,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",
@@ -730,20 +635,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",
@@ -763,20 +660,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",
@@ -796,20 +685,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",
@@ -829,20 +710,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",
@@ -862,20 +735,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",
@@ -895,20 +760,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",
@@ -928,20 +785,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",
@@ -961,20 +810,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",
@@ -994,20 +835,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",
@@ -1027,20 +860,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",
@@ -1060,20 +885,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",
@@ -1093,20 +910,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",
@@ -1126,20 +935,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",
@@ -1159,20 +960,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",
@@ -1192,20 +985,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",
@@ -1225,20 +1010,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",
@@ -1258,20 +1035,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",
@@ -1291,20 +1060,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",
@@ -1324,22 +1085,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",
@@ -1359,20 +1110,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",
@@ -1392,20 +1135,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",
@@ -1425,20 +1160,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",
@@ -1458,20 +1185,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",
@@ -1491,20 +1210,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",
@@ -1524,20 +1235,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",
@@ -1557,20 +1260,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",
@@ -1590,20 +1285,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",
@@ -1623,11 +1310,7 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "shopify"
- ]
+ "args": ["integration", "setup", "shopify"]
},
"requires": ">=0.46.1"
}
@@ -1651,20 +1334,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",
@@ -1684,20 +1359,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",
@@ -1717,20 +1384,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",
@@ -1750,20 +1409,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",
@@ -1796,9 +1447,7 @@
"requires": ">=0.48.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/tinybird.ts",
@@ -1818,20 +1467,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",
@@ -1851,20 +1492,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",
@@ -1884,20 +1517,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",
@@ -1917,20 +1542,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",
@@ -1950,20 +1567,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",
@@ -1983,40 +1592,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",
@@ -2035,23 +1632,15 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "teams"
- ]
+ "args": ["integration", "setup", "teams"]
},
"requires": ">=0.53.0",
"docs": "/docs/channels/teams",
"implementation": "native"
}
},
- "dependencies": [
- "@vercel/connect@>=2.1.0"
- ],
- "devDependencies": [
- "vercel@>=58.5.1"
- ]
+ "dependencies": ["@vercel/connect@>=2.1.0"],
+ "devDependencies": ["vercel@>=58.5.1"]
},
{
"name": "channel/telegram",
@@ -2103,9 +1692,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": ""
@@ -2135,23 +1722,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",
@@ -2164,23 +1743,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",
@@ -2193,11 +1764,7 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "web"
- ]
+ "args": ["integration", "setup", "web"]
},
"requires": ">=0.66.1",
"docs": "/docs/channels/eve",
@@ -2450,11 +2017,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",
@@ -2477,11 +2040,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",
@@ -2507,11 +2066,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",
@@ -2535,11 +2090,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",
@@ -2564,11 +2115,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": ""
@@ -2592,11 +2139,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": ""
@@ -2620,11 +2163,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": "",
@@ -2649,11 +2188,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",
@@ -2677,11 +2212,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": ""
@@ -2705,23 +2236,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",
@@ -2734,11 +2257,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": "",
@@ -2763,20 +2282,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",
@@ -2789,11 +2302,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": "",
@@ -2818,11 +2327,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": "",
@@ -2847,11 +2352,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": ""
@@ -2875,11 +2376,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",
@@ -2903,11 +2400,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": "",
@@ -2932,11 +2425,7 @@
"type": "registry:item",
"title": "Gmail",
"description": "Turn labelled Gmail threads into agent conversations via the Chat SDK.",
- "dependencies": [
- "chat",
- "@chat-adapter/gmail",
- "@chat-adapter/state-redis"
- ],
+ "dependencies": ["chat", "@chat-adapter/gmail", "@chat-adapter/state-redis"],
"envVars": {
"REDIS_URL": "",
"GMAIL_MAILBOX": "",
@@ -2973,9 +2462,7 @@
"type": "registry:item",
"title": "Braintrust",
"description": "Trace eve agent sessions in Braintrust, including turns, steps, tool calls, and subagent interactions.",
- "dependencies": [
- "braintrust@^3.29.0"
- ],
+ "dependencies": ["braintrust@^3.29.0"],
"envVars": {
"BRAINTRUST_API_KEY": ""
},
@@ -3016,9 +2503,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": ""
@@ -3036,9 +2521,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": ""
@@ -3056,9 +2539,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": ""
},
@@ -3075,9 +2556,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": ""
@@ -3095,9 +2574,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": ""
},
@@ -3114,9 +2591,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/apps/docs/registry/tools/task_cancel.ts b/apps/docs/registry/tools/task_cancel.ts
deleted file mode 100644
index 66342e813..000000000
--- a/apps/docs/registry/tools/task_cancel.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "eve/tools/task_cancel";
diff --git a/docs/agent-config.md b/docs/agent-config.md
index aaa3554bc..daae5b569 100644
--- a/docs/agent-config.md
+++ b/docs/agent-config.md
@@ -288,7 +288,7 @@ calls and inline tool executions can run again. That can repeat provider costs,
events, and side effects. Use stable idempotency keys for non-idempotent tools.
eve ends a batch before it waits for input, authorization, or blocking
-coordination, and before it acknowledges a background task. A batch can also
+coordination. A batch can also
end below the configured ceiling when the turn completes or steering arrives.
Before assistant output begins, steering can interrupt pending model generation.
Executing tools finish safely before the batch yields and applies the correction.
@@ -321,7 +321,7 @@ export default defineAgent({
This applies to every run that owns the session, including successor owners
started after a deployment handoff, and to the run that collects session
activity. Runs eve starts for other purposes keep the world's default: session
-timeouts, background tasks, and [workflow tools](./tools/workflows).
+timeouts and [workflow tools](./tools/workflows).
The value applies per agent. A [subagent](./subagents) that runs its own session
uses its own value, unlike `experimental.workflow.world`, which is root-only.
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index da4d68408..2a1988d27 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -103,7 +103,7 @@ Stream a session as newline-delimited JSON from `GET /eve/v1/session/:sessionId/
### Cancel a turn
-Post to `/eve/v1/session/:sessionId/cancel` to request cancellation of the active turn. You can include the observed `turnId` to keep a late request from cancelling a newer turn. Include `tasks: true` to also cancel every background task owned by the session, including while the session is parked. Cancellation is asynchronous; confirm the turn boundary on the stream as `turn.cancelled` followed by `session.waiting`, and inspect task state in a later turn to confirm task cancellation.
+Post to `/eve/v1/session/:sessionId/cancel` to request cancellation of the active turn. You can include the observed `turnId` to keep a late request from cancelling a newer turn. Cancellation is asynchronous; confirm the turn boundary on the stream as `turn.cancelled` followed by `session.waiting`.
See [Cancel the in-flight turn](../concepts/sessions-runs-and-streaming#cancel-the-in-flight-turn) for response statuses, HTTP status codes, subagent cancellation, and race behavior.
diff --git a/docs/channels/overview.mdx b/docs/channels/overview.mdx
index 8f7d4f94e..cacdd9343 100644
--- a/docs/channels/overview.mdx
+++ b/docs/channels/overview.mdx
@@ -76,54 +76,6 @@ When eve doesn't ship a channel for your surface, build one with `defineChannel`
A cross-channel `send(...)` supplies input to the agent and invokes the model on the destination channel. eve does not currently provide a direct cross-channel provider-message queue. To post without starting a turn, use the provider API. See [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications) when delivery also needs application-managed retries and deduplication.
-## Background task results
-
-Pass `taskDeliveryPolicy` to `send(...)` to choose how the session reports background results:
-
-- `"auto"` (default for new channel sessions): ready results can invoke the parent while other tasks continue. The parent reports results that are useful independently and stays silent when a useful answer needs unfinished work.
-- `"cohort"`: wait for overlapping tasks to settle, then deliver their terminal outcomes together.
-
-```ts title="agent/channels/reports.ts"
-import { defineChannel, POST } from "eve/channels";
-import { localDev, routeAuth } from "eve/channels/auth";
-
-export default defineChannel({
- routes: [
- POST("/reports", async (request, { from }) => {
- const auth = await routeAuth(request, localDev());
- if (auth instanceof Response) return auth;
- const session = await from("daily-report").send("Prepare the daily reports.", {
- auth,
- taskDeliveryPolicy: "cohort",
- });
- return Response.json({ sessionId: session.id });
- }),
- ],
-});
-```
-
-The option is available on channel-local `from(...).send(...)`, cross-channel
-`to(...).send(...)`, fixed-session `send(...)`, Chat SDK `bridge.send(...)`, and client
-sends. An explicit value
-updates the session's policy, including pending background tasks; later sends that
-omit it preserve that policy. A cross-channel send carries its setting through the
-receiver's `from(...).send(...)` unless that call supplies an explicit value.
-
-[Schedules](../schedules#background-task-results) default new sessions to `"cohort"`.
-A schedule handler can pass `taskDeliveryPolicy: "auto"` to `send(...)` to override
-that default. Child sessions use their own policy.
-
-With `"auto"`, a model call may finish without a user-visible message. Results
-already queued from the same cohort may share a turn. Each reporting turn receives
-the whole cohort, including pending tasks and available outputs, so previously
-withheld results remain available for a later combined report.
-
-Input requests and explicit task messages remain eligible for delivery under
-either policy. Failure and cancellation update task state immediately; their
-automatic reports follow the selected policy. User messages follow `turnPolicy`.
-See [Completion batching](../subagents#completion-batching) for cohort membership
-and result ordering.
-
## Relationship to the Chat SDK
eve uses the [Chat SDK's card-builder components](https://chat-sdk.dev/docs/api/cards) (Cards, Buttons, Actions, etc.) for composing rich Slack messages. When you build a card with the [Slack channel](./slack), the underlying primitives come from the Chat SDK and get converted to Slack Block Kit at post time.
diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.md
index b793a3e19..0439c4044 100644
--- a/docs/concepts/built-in-tools.md
+++ b/docs/concepts/built-in-tools.md
@@ -215,7 +215,7 @@ export default disableTool();
### `agent`
-`agent` delegates a subtask to a fresh copy of the root agent. It is root-only, always runs in the background, and returns a task receipt immediately. The child receives the root's instructions, tools, connections, and sandbox, but starts with fresh conversation history and [state](./state). See [Subagents](../subagents).
+`agent` delegates a subtask to a fresh copy of the root agent. It is root-only and waits for the child's reply, which it returns as the tool result. The child receives the root's instructions, tools, connections, and sandbox, but starts with fresh conversation history and [state](./state). See [Subagents](../subagents).
```sh
eve add tool/agent
@@ -233,26 +233,6 @@ import { disableTool } from "eve/tools";
export default disableTool();
```
-### `task_cancel`
-
-`task_cancel` lets the root session cancel background tasks.
-
-```sh
-eve add tool/task_cancel
-```
-
-```ts title="agent/tools/task_cancel.ts"
-export { default } from "eve/tools/task_cancel";
-```
-
-The framework behavior cannot be overridden. Re-export the definition above to restore it, or disable it:
-
-```ts title="agent/tools/task_cancel.ts"
-import { disableTool } from "eve/tools";
-
-export default disableTool();
-```
-
### `load_skill`
`load_skill` pulls an on-demand [skill](../skills)'s instructions into the current turn. It appears only when the agent declares skills and adds no execution surface by itself.
@@ -313,7 +293,7 @@ import { askQuestion } from "eve/tools/ask_question";
export default askQuestion();
```
-`ask_question` is a [workflow tool](/docs/tools/workflows) that calls `ctx.ask()`. The model receives `{ status: "answered", answer }`, where `answer` is the chosen option's label or the user's own words. A plain follow-up message answers the question too when it is the only pending question. When other questions are also pending, a message does not answer any of them: `ask_question` resolves as `{ status: "dismissed" }` and the message reaches the model normally. In a session that cannot request input, such as a scheduled run, the result is `{ status: "unavailable" }` and the model continues on its own judgment. Remove the file to remove the tool.
+`ask_question` is a [workflow tool](/docs/tools/workflows) that calls `ctx.ask()`. The model receives `{ status: "answered", answer }`, where `answer` is the chosen option's label or the user's own words. A plain follow-up message answers the question too when it is the only pending question. When other questions are also pending, a message does not answer any of them: `ask_question` withdraws its question, resolves as `{ interrupted: true }`, which the model reads as `Stopped early because a new message arrived.`, and the model reads the message next. In a session that cannot request input, such as a scheduled run, the result is `{ status: "unavailable" }` and the model continues on its own judgment. Remove the file to remove the tool.
### `glob`
@@ -369,7 +349,7 @@ Remove the file to remove the tool. `disableTool()` is unnecessary because `grep
### `sleep`
-`sleep` pauses and durably resumes the current turn. The model calls it with `{ seconds }`; the wait does not hold an application runtime open. Concurrent calls run in parallel, and the turn resumes after the longest wait. Add it:
+`sleep` pauses and durably resumes the current turn. The model calls it with `{ seconds }`; the wait does not hold an application runtime open. Concurrent calls run in parallel, and the turn resumes after the longest wait. A steering message, the default for a new message, ends the wait early: `sleep` returns `{ interrupted: true }`, which the model reads as `Stopped early because a new message arrived.`, followed by the message. Add it:
```sh
eve add tool/sleep
@@ -400,4 +380,4 @@ Remove the file to remove the tool. `disableTool()` is unnecessary because `slee
- [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 specialists that the model can call as background tasks
+- [Subagents](../subagents): declare specialists that the model can delegate to
diff --git a/docs/concepts/context-control.md b/docs/concepts/context-control.md
index e4091dce3..05cc428c9 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) | A receipt followed by background task notifications |
+| A specialist with a separate prompt and capabilities | A [subagent](../subagents) | The child's reply as the tool result |
| 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 call returns a task receipt, and later task notifications deliver its outcome.
+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 waits for the child's reply and returns it as the tool result.
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 4ccb7bf7d..2bd120505 100644
--- a/docs/concepts/execution-model-and-durability.mdx
+++ b/docs/concepts/execution-model-and-durability.mdx
@@ -97,9 +97,8 @@ Crash the process, hit a timeout, or redeploy mid-turn, and the run picks up fro
With `experimental.workflow.modelCallsPerStep` greater than `1`, an
interrupted Workflow step can also repeat earlier model calls and inline tool
-executions from the same batch. Approval, input, blocking coordination, and
-background-task boundaries still force a checkpoint before eve waits or
-acknowledges the work.
+executions from the same batch. Approval, input, and blocking coordination
+boundaries still force a checkpoint before eve waits.
Steering can interrupt pending model generation before assistant output begins.
An executing tool finishes safely, then the batch yields before another model
@@ -115,14 +114,11 @@ For ordinary tools, eve manages the workflow around your executor. Use [`defineW
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 execution is a separate choice about result delivery. A background workflow tool
-returns a task receipt so the parent turn can continue; the tool's workflow may then run or
-suspend independently. A default workflow tool can suspend too, with its original tool call
-still pending. Declare background work with `defineWorkflowTool`; `defineTool` always executes
-inside its initiating step.
+A workflow tool can suspend too, with its original tool call still pending and the turn parked
+until the workflow settles. `defineTool` always executes inside its initiating step.
-An awaited workflow operation provides the durable wait. A generator's `yield` reports progress
-in default execution; background workflow tools consume yields without publishing progress. See [background execution](../tools#background-execution) and
+An awaited workflow operation provides the durable wait. A generator's `yield` reports progress.
+See [durable waits](../tools#durable-waits) and
[workflow suspension](../tools/workflows#how-suspension-works) for the execution and result rules.
## Message delivery and steering
@@ -154,7 +150,7 @@ never starts a replacement session for an address that is mid-handoff.
When a session is waiting, a delivery through its ID or any claimed channel address wakes it and starts the next turn. Message sends default to `turnPolicy: "steer"`. Before assistant output begins, the session owner signals pending model generation to stop, then applies the correction within the same turn and with the same turn ID. This includes model requests that perform provider-managed search before answering; interrupted search work may run again. Reasoning and search progress do not count as assistant output.
-An executing eve tool finishes and commits its result before steering reaches the next model request. Steering does not cancel the turn or its background tasks. After assistant output starts, steering applies at the next committed workflow boundary and preserves streamed text. A message that reaches the boundary after the turn has settled starts another turn.
+An executing eve tool finishes and commits its result before steering reaches the next model request. Steering does not cancel the turn. After assistant output starts, steering applies at the next committed workflow boundary and preserves streamed text. A message that reaches the boundary after the turn has settled starts another turn.
Once eve publishes an input request or begins publishing turn completion or failure, eve finishes committing that boundary before applying new messages.
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index 62d566ad8..4361af23e 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -67,37 +67,39 @@ curl http://127.0.0.1:2000/eve/v1/session/<sessionId>/stream
The stream is newline-delimited JSON (NDJSON), one event per line:
-| Event | Meaning |
-| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `session.started` | A durable session was created; carries `trace` when the runtime is traced. |
-| `turn.started` | A new turn began; carries the active `trace` when the runtime is traced. |
-| `message.received` | Input reached a turn; carries flattened text plus structured text/file parts. Task-authored input sets `data.kind` to `execution.background_task`. |
-| `step.started` | A model step began. |
-| `action.input.appended` | A raw tool-input text delta and its tool-call identity. |
-| `actions.requested` | The model requested one or more actions, including tool calls; calls stream before execution. |
-| `action.partial` | A locally executed tool generator yielded a preliminary output snapshot. |
-| `action.result` | A tool call returned. |
-| `input.requested` | The run paused for human input ([HITL](/docs/human-in-the-loop) approval or a `ctx.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` and the `childStreamPath` that `session.streamSubagent()` follows. |
-| `subagent.completed` | The parent recorded a successful subagent invocation result; carries the actual output. |
-| `reasoning.appended` | A reasoning text delta. |
-| `reasoning.completed` | The finalized reasoning block. |
-| `message.appended` | An assistant text delta. |
-| `message.completed` | A finalized assistant text block. |
-| `result.completed` | The finalized structured result for a turn that requested an output schema; carries `result`. |
-| `compaction.requested` | Context-window compaction began; carries `modelId`, `sessionId`, `turnId`, `stepIndex`, and `usageInputTokens`. |
-| `compaction.completed` | A compaction checkpoint was written to durable history; carries the same model, session, turn, and step identity. |
-| `authorization.required` | A connection needs OAuth; carries `name`, `description`, and an `authorization` challenge. |
-| `authorization.completed` | A connection's authorization resolved; carries `outcome`. |
-| `step.completed` | A model step finished; carries `finishReason` and usage. |
-| `step.failed` | A model step failed; carries `{ code, message, details? }`. |
-| `turn.completed` | The turn finished. |
-| `turn.failed` | The turn failed; carries `{ code, message, details? }`. |
-| `turn.cancelled` | The turn was cancelled before finishing; always followed by `session.waiting`. |
-| `session.waiting` | The session parked and is ready for the next message. |
-| `session.failed` | The session failed. |
-| `session.completed` | The session reached a terminal end. |
+| Event | Meaning |
+| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
+| `session.started` | A durable session was created; carries `trace` when the runtime is traced. |
+| `turn.started` | A new turn began; carries the active `trace` when the runtime is traced. |
+| `message.received` | Input reached a turn; carries flattened text plus structured text/file parts. |
+| `step.started` | A model step began. |
+| `action.input.appended` | A raw tool-input text delta and its tool-call identity. |
+| `actions.requested` | The model requested one or more actions, including tool calls; calls stream before execution. |
+| `action.partial` | A locally executed tool generator yielded a preliminary output snapshot. |
+| `action.result` | A tool call returned. |
+| `input.requested` | The run paused for human input ([HITL](/docs/human-in-the-loop) approval or a `ctx.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` and the `childStreamPath` that `session.streamSubagent()` follows. |
+| `subagent.completed` | The parent recorded a successful subagent invocation result; carries the actual output. |
+| `agent.started` | A workflow tool opened a session with `ctx.agent`; carries `sessionId` and the `streamPath` that `streamSubagent()` follows. |
+| `reasoning.appended` | A reasoning text delta. |
+| `reasoning.completed` | The finalized reasoning block. |
+| `message.appended` | An assistant text delta. |
+| `message.completed` | A finalized assistant text block. |
+| `result.completed` | The finalized structured result for a turn that requested an output schema; carries `result`. |
+| `compaction.requested` | Context-window compaction began; carries `modelId`, `sessionId`, `turnId`, `stepIndex`, and `usageInputTokens`. |
+| `compaction.completed` | A compaction checkpoint was written to durable history; carries the same model, session, turn, and step identity. |
+| `authorization.required` | A connection needs OAuth; carries `name`, `description`, and an `authorization` challenge. |
+| `authorization.completed` | A connection's authorization resolved; carries `outcome`. |
+| `step.completed` | A model step finished; carries `finishReason` and usage. |
+| `step.failed` | A model step failed; carries `{ code, message, details? }`. |
+| `turn.waiting` | The open turn parked, such as when a call it runs asks a question; carries `turnId`. The turn has not ended. |
+| `turn.completed` | The turn finished. |
+| `turn.failed` | The turn failed; carries `{ code, message, details? }`. |
+| `turn.cancelled` | The turn was cancelled before finishing; always followed by `session.waiting`. |
+| `session.waiting` | The session parked and is ready for the next message. |
+| `session.failed` | The session failed. |
+| `session.completed` | The session reached a terminal end. |
The optional `data.trace` on session and turn starts contains eve-owned W3C trace coordinates: `traceId`, `spanId`, and `traceFlags`. Use it to correlate stream consumers such as eval reporters with an observability backend. An uninstrumented target omits it.
@@ -107,7 +109,7 @@ The default client reducer accumulates assistant text, reasoning, and streamed t
If a model provider fails after partial output and eve retries the call, the durable stream keeps events from both attempts. When the failed attempt emitted only deltas, a later completed event lets replaceable projections converge on the successful attempt. A completed block does not mean the provider attempt itself later succeeded; removing abandoned completed blocks would require attempt identity, which these events do not carry.
-The client validates the `x-eve-stream-version` header on every connection. It normalizes v21–v24 cumulative message and reasoning appends, plus v24 offset-based tool-input appends, to the v25 delta-only contract. This lets a reconnect cross deployments without changing the reducer input. A current server performs the same normalization when replaying a session written by an earlier deployment. A missing or unsupported version, or an append whose fields do not match its declared version, fails instead of being interpreted as a current event.
+The client validates the `x-eve-stream-version` header on every connection. It accepts v21 through v26 and normalizes v21–v24 cumulative message and reasoning appends, plus v24 offset-based tool-input appends, to the delta-only contract that v25 introduced. This lets a reconnect cross deployments without changing the reducer input. A current server performs the same normalization when replaying a session written by an earlier deployment. A missing or unsupported version, or an append whose fields do not match its declared version, fails instead of being interpreted as a current event.
When a streamed tool input becomes a validated call, its `action.input.appended` events precede the matching `actions.requested` event. The default client reducer projects the potentially incomplete JSON as a `dynamic-tool` part with `state: "input-streaming"` and cumulative text in `inputText`. `actions.requested` replaces that part with `state: "input-available"` and the validated `input`. Excluded internal actions never publish their input stream.
@@ -117,9 +119,9 @@ 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`.
-When a task explicitly requires conditional delivery and there is nothing new to report, the agent can finish with exactly `<eve-empty-delivery/>`. eve emits `message.completed` with `message: null` for that intentional silence. The marker must be the entire response, apart from surrounding whitespace; the HTML-escaped form `&lt;eve-empty-delivery/&gt;` is also accepted. A response that quotes the marker in prose or code is delivered normally.
+A delegated subagent publishes progress on its own child-session stream. The parent emits `subagent.called` with a `childSessionId` and a `childStreamPath`, which a client follows with `session.streamSubagent()`. Every call emits `subagent.completed` with the actual output after the parent records a successful outcome. Completion does not mean that the reusable child session has ended. A session a workflow tool opens with `ctx.agent` is announced with `agent.started`, which carries the child's `sessionId` and a `streamPath` that `session.streamSubagent()` also follows; the workflow tool's result carries what it returns.
-A delegated subagent publishes progress on its own child-session stream. The parent emits `subagent.called` with a `childSessionId` and a `childStreamPath`, which a client follows with `session.streamSubagent()`. Both blocking and background calls emit `subagent.completed` with the actual output after the parent records a successful outcome. A background working receipt is an `action.result` tool output; it does not emit completion. Older streams can contain receipt-bearing completion events marked by `data.backgroundTask`; those are admission only. Completion does not mean that the reusable child session has ended. Background task terminal outcomes also arrive as task-triggered `message.received` notifications with `data.kind: "execution.background_task"`. The default frontend reducer retains these events in `events` but does not project their runtime-authored text as participant messages.
+A question or sign-in from inside a running call does not end the turn. This covers a workflow tool's `ctx.ask()`, including the built-in `ask_question` tool, and a delegated subagent's question or sign-in. The stream emits `input.requested` or `authorization.required`, then `turn.waiting` with the open turn's `turnId`. After the answer or sign-in, the turn resumes with the next `step.started` for the same `turnId`, and only `turn.completed`, `turn.failed`, or `turn.cancelled` ends it. When you answer a question that belongs to a workflow tool or a subagent, the session you answer on emits `input.resolved` for it as it routes the answer down. A tool approval the turn requests still ends the turn: `input.requested`, `turn.completed`, then `session.waiting`.
`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"`).
@@ -205,11 +207,11 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId> \
-d '{"inputResponses":[{"requestId":"req_A","optionId":"approve"}]}'
```
-Message sends default to `"steer"`. Before assistant output begins, eve interrupts pending model generation and continues the same turn with the correction. Reasoning and provider search progress do not count as assistant output. An executing eve tool finishes safely, and its result is preserved before the correction reaches the next model call. After assistant output starts, steering applies at the next committed workflow boundary; text already streamed remains visible. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when the active turn should finish first. Structured `inputResponses` answer their addressed requests.
+Message sends default to `"steer"`. Before assistant output begins, eve interrupts pending model generation and continues the same turn with the correction. Reasoning and provider search progress do not count as assistant output. An executing eve tool finishes safely, and its result is preserved before the correction reaches the next model call. A workflow tool call the turn is waiting on learns of the message through its [`ctx.interruptSignal`](/docs/tools/workflows#stop-early-for-a-new-message-ctxinterruptsignal): `sleep` and `ask_question` stop early, and other workflow tools keep going unless their body handles the signal. After assistant output starts, steering applies at the next committed workflow boundary; text already streamed remains visible. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when the active turn should finish first. Structured `inputResponses` answer their addressed requests.
If the session is waiting on a human-in-the-loop approval, respond with the channel’s Approve or Cancel controls. Text messages do not decide an approval; unrelated text starts an ordinary turn while the approval stays pending and answerable. A later structured `inputResponses` answer keyed by its `requestId` still resumes the original tool call, even after intervening turns.
-A pending `ctx.ask()` question from a blocking tool, such as `ask_question`, can be answered with plain text. When it is the only pending question, a message that matches an option answers it, and so does any message when the question allows free text. Otherwise eve does not guess which question the text addresses: the message follows the normal `turnPolicy`, questions created with `dismissible: true` resolve as `dismissed`, and other questions stay open. Questions from background tools and subagents always need a structured response. Use structured responses to target requests unambiguously.
+A pending `ctx.ask()` question from a tool, such as `ask_question`, can be answered with plain text. When it is the only pending question, a message that matches an option answers it, and so does any message when the question allows free text. Otherwise eve does not guess which question the text addresses: the message follows the normal `turnPolicy`. A steering message withdraws questions asked with `ctx.interruptSignal` as their signal, which resolve as `cancelled`; other questions stay open. Questions from subagents always need a structured response. Use structured responses to target requests unambiguously.
A structured response matches any currently pending request by ID, not only the newest batch. It becomes stale only after that request was answered, cleared, or cancelled. eve delivers a stale response to the model as a new user message, and the model decides whether the old selection still matters. A stale approval never authorizes the earlier tool call; the model must request the action and approval again if they are still needed.
@@ -226,15 +228,7 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/cancel
# {"ok":true,"sessionId":"<sessionId>","status":"accepted"}
```
-By default, background tasks that were already admitted survive initiating-turn cancellation. Pass `tasks: true` to cancel every background task owned by the session as well. This works while the session is parked, so you can stop background work without resetting the session:
-
-```bash
-curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/cancel \
- -H 'content-type: application/json' \
- -d '{"tasks":true}'
-```
-
-`"accepted"` means the live session durably queued the request; cancellation completes asynchronously. Confirm turn cancellation on the stream as `turn.cancelled` followed by `session.waiting`. Inspect task state in a later turn to confirm task cancellation. The session then accepts the next message normally. 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 returns `"accepted"`; plain cancellation is a no-op there, while `tasks: true` still cancels indexed tasks. `"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; cancellation completes asynchronously. Confirm turn cancellation on the stream as `turn.cancelled` followed by `session.waiting`. The session then accepts the next message normally. Each cancelled child reports its own boundary on its child-session stream. A live but already-parked session returns `"accepted"`; cancellation is a no-op there. `"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/connections/overview.mdx b/docs/connections/overview.mdx
index 4793cbc5c..84504104c 100644
--- a/docs/connections/overview.mdx
+++ b/docs/connections/overview.mdx
@@ -227,7 +227,7 @@ export default defineMcpClientConnection({
Use the connector UID returned by `vercel connect create`; the display name passed to `--name` is not the UID. `connect("linear/myagent")` is shorthand for a user-scoped interactive OAuth connection: eve resolves a token for the active user before each tool call, emits `authorization.required` when that user has not authorized yet, and resumes the parked turn after the callback completes.
-When a local subagent needs interactive authorization, eve surfaces the authorization lifecycle on the root session's channel, including through nested subagent chains. The challenge still points to the child session's callback, so completing it resumes the child directly while the parent continues waiting for its result.
+When a local subagent needs interactive authorization, eve surfaces the authorization lifecycle on the root session's channel, including through nested subagent chains. The challenge still points to the child session's callback, so completing it resumes the child directly while the parent continues waiting for its result. The parent's turn stays open: it emits `turn.waiting` after the proxied `authorization.required` and resumes under the same `turnId` once the subagent returns.
That means the channel that creates or continues the session must authenticate a real user. For a web app, configure `agent/channels/eve.ts` so your app session maps to `principalType: "user"`; for platform channels, use the built-in channel auth that maps the sender to a user principal. If no authenticated user is attached to the session, the first user-scoped connection call fails with `reason: "principal_required"`.
diff --git a/docs/evals/assertions.mdx b/docs/evals/assertions.mdx
index fd4e92b99..cac425e95 100644
--- a/docs/evals/assertions.mdx
+++ b/docs/evals/assertions.mdx
@@ -83,11 +83,11 @@ Pick the cheapest builder that captures what "correct" means. When exact match i
## The matcher mini-language
-`t.calledTool` and `t.calledSubagent` take matcher objects. Tools accept `{ input, output, status, count }`; subagents accept `{ callId, childSessionId, remoteUrl, output, status, count }`. Calls match `status: "completed"` by default. Tool lifecycle checks also accept `"pending"`, `"failed"`, and `"rejected"`. Subagent checks use the shared task status values: `"working"`, `"input_required"`, `"completed"`, `"failed"`, and `"cancelled"`. A numeric `count` requires an exact number of calls matching every supplied constraint. Use a predicate for ranges or other custom count requirements; it receives the observed number of matching calls.
+`t.calledTool` and `t.calledSubagent` take matcher objects. Tools accept `{ input, output, status, count }`; subagents accept `{ callId, childSessionId, remoteUrl, output, status, count }`. Calls match `status: "completed"` by default. Tool lifecycle checks also accept `"pending"`, `"failed"`, and `"rejected"`. Subagent checks accept `"working"`, `"completed"`, `"failed"`, and `"cancelled"`. A numeric `count` requires an exact number of calls matching every supplied constraint. Use a predicate for ranges or other custom count requirements; it receives the observed number of matching calls.
-A background subagent that has only returned a working task receipt remains `working`; use `t.calledSubagent(name, { status: "working" })` to assert that delegation. Both blocking and background calls become `completed` when their actual successful result is observed through `subagent.completed`, even when the child session stays available for another call. A rejected dispatch is `failed`; an explicit cancelled child outcome is `cancelled`.
+A subagent call stays `working` until its result is observed. It becomes `completed` when its successful result is observed through its tool result or `subagent.completed`, even when the child session stays available for another call. A rejected dispatch or failed call is `failed`; an explicit cancelled child outcome is `cancelled`.
-The runner derives these values from captured events. It does not read stored task state, and the current stream does not expose every task transition. A proxied input request alone does not update the subagent call to `input_required`; assert that request with `requireInputRequest`. Check task notifications for background failure and cancellation when no child outcome event is present.
+The runner derives these values from captured events. A proxied input request alone does not change the subagent call's status; assert that request with `requireInputRequest`.
Matcher values accept a literal (objects partial-deep-match), a RegExp, or a predicate function that returns a boolean:
diff --git a/docs/evals/cases.mdx b/docs/evals/cases.mdx
index 50056f1e9..468f29fda 100644
--- a/docs/evals/cases.mdx
+++ b/docs/evals/cases.mdx
@@ -111,7 +111,7 @@ Every `t.session()` or `t.send()` creates a new independent conversation. Contin
- `session.start(message, options?)` starts a text turn and returns as soon as the server accepts it. The live turn exposes `.session`, `.sessionId`, `.waitForEvent(...)`, `.cancel()`, and `.result()`.
- `session.cancel()` requests cooperative cancellation of that session's active turn. Both `accepted` and `no_active_turn` are successful outcomes.
- `session.sendFile(text, path, mediaType?)` attaches a local file as a data URL.
-- `session.streamSubagent(called, options?)` follows a delegated child's stream through the parent with the eval client's credentials. Pass a `subagent.called` event from that session. It also reaches children on another deployment, which `t.target.watchTurn(...)` cannot address.
+- `session.streamSubagent(started, options?)` follows a delegated child's stream through the parent with the eval client's credentials. Pass an `agent.started` or `subagent.called` event from that session. It also reaches children on another deployment, which `t.target.watchTurn(...)` cannot address.
- `session.requireInputRequest(filter?)` records a gate, requires exactly one pending request, and returns it. Filters match tool name, action input, prompt, display, and option ids.
- `session.respond(responses, options?)` answers specific pending input requests and sends them as the next turn. `session.startRespond(...)` returns a live turn for the same operation.
- `session.respondAll(optionId)` answers every pending input request with the same option and sends the responses as the next turn.
diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdx
index 807a4ecc8..1de519735 100644
--- a/docs/guides/client/streaming.mdx
+++ b/docs/guides/client/streaming.mdx
@@ -56,6 +56,16 @@ This consumes the stream until the current turn boundary:
- `session.waiting`
- `session.completed`
- `session.failed`
+- `turn.waiting` while an `input.requested` the response read is unanswered
+
+A `turn.waiting` without a pending request is informational: the turn stays
+open, and `result()` keeps reading to its final reply. This includes a sign-in
+a running call needs, such as a subagent's connection. When a call the turn
+runs asks a question, such as a workflow tool's `ctx.ask()`, `result()` returns
+`status: "waiting"` with the question in `inputRequests`. Answer it with
+`respond()`, which keeps reading the same turn. A question stays pending until
+its `input.resolved`, which the session you answer on also emits for a
+subagent's or workflow tool's question.
`result()` closes that HTTP stream, including when fetch instrumentation clones
the response for tracing. The durable session remains available for follow-up
@@ -95,7 +105,7 @@ for await (const event of response) {
After reconnecting without local state, replay the earlier events or wait for the completed event instead of appending a later delta to an empty value. Apply the same rule to `reasoningDelta` and `inputTextDelta`. If a model provider fails after partial output and eve retries the call, the durable stream keeps events from both attempts. A later completed event replaces provisional text only when the failed attempt did not already complete that block; the protocol has no attempt identity with which to retract earlier completed blocks.
-The eve client validates the stream version on every connection. It accepts v21–v24 cumulative message and reasoning append events and v24 offset-based tool-input appends, then exposes them through the current delta-only `MessageStreamEvent` contract. This also applies when an automatic reconnect reaches a newer deployment. A missing or unsupported `x-eve-stream-version` header fails the stream instead of treating unknown JSON as the current event type.
+The eve client validates the stream version on every connection. It accepts v21 through v26. v25 and v26 events already use the current delta-only `MessageStreamEvent` contract, and the client normalizes v21–v24 cumulative message and reasoning append events and v24 offset-based tool-input appends to it. This also applies when an automatic reconnect reaches a newer deployment. A missing or unsupported `x-eve-stream-version` header fails the stream instead of treating unknown JSON as the current event type.
## Handle event types
@@ -243,7 +253,7 @@ stream index after the captured prefix.
## Follow a subagent
-A delegated subagent reports its progress on its own child session. The parent stream announces each dispatch with a `subagent.called` event. Pass that event to `streamSubagent()` on the parent's session handle to follow the child:
+A delegated subagent reports its progress on its own child session. The parent stream announces each child: `subagent.called` when the model calls a subagent tool, and `agent.started` when a [workflow tool](/docs/tools/workflows#delegate-work-ctxagent) opens a session with `ctx.agent`. Pass either event to `streamSubagent()` on the parent's session handle to follow the child:
```ts
import { isCurrentTurnBoundaryEvent } from "eve/client";
@@ -260,16 +270,16 @@ if (called?.type === "subagent.called") {
}
```
-`streamSubagent()` reads the event's `childStreamPath` with the parent session's host and credentials, so the same client works for local and [remote](../remote-agents) children:
+`streamSubagent()` reads the event's stream path, `childStreamPath` on `subagent.called` or `streamPath` on `agent.started`, with the parent session's host and credentials, so the same client works for local and [remote](../remote-agents) children:
- A local child's path is its own session stream route on the same deployment. The channel's usual session authorization applies.
-- A remote child's path is a proxy route on the parent deployment. The parent checks that the child belongs to this session, then relays the remote child's stream with the remote agent's authored `auth` and `headers`. The client never needs the remote URL or its credentials.
+- A remote child's path is a proxy route on the parent deployment. The parent checks that its session recorded the child for that tool call, then relays the remote child's stream with the remote agent's authored `auth` and `headers`. The client never needs the remote URL or its credentials.
-The child has its own cursor, starting at `0`, and reading it never advances the parent's `streamIndex`. Pass `startIndex` to resume, `follow: false` for a bounded read, and `signal` to detach. A child parks after answering and can be continued later, so stop at a turn boundary with `isCurrentTurnBoundaryEvent` when you only need the current turn. Passing a `subagent.called` event from a different session throws.
+The child has its own cursor, starting at `0`, and reading it never advances the parent's `streamIndex`. Pass `startIndex` to resume, `follow: false` for a bounded read, and `signal` to detach. A child parks after answering and can be continued later, so stop at a turn boundary with `isCurrentTurnBoundaryEvent` when you only need the current turn.
## Abort a request
-Pass an `AbortSignal` to cancel the POST or stream. Aborting is local transport cancellation: turns are resumable across disconnects, so detaching never stops server-side work. Use `session.cancel()` to stop the active turn, or `session.cancel({ tasks: true })` to also stop background tasks owned by the session. Cancellation is asynchronous; watch the stream for `turn.cancelled` followed by `session.waiting`, and inspect task state in a later turn to confirm task cancellation.
+Pass an `AbortSignal` to cancel the POST or stream. Aborting is local transport cancellation: turns are resumable across disconnects, so detaching never stops server-side work. Use `session.cancel()` to stop the active turn. Cancellation is asynchronous; watch the stream for `turn.cancelled` followed by `session.waiting`.
Arm the timeout before awaiting `send()` so it covers the POST as well as the stream:
diff --git a/docs/guides/dynamic-capabilities.md b/docs/guides/dynamic-capabilities.md
index b393a2c15..5e269222f 100644
--- a/docs/guides/dynamic-capabilities.md
+++ b/docs/guides/dynamic-capabilities.md
@@ -139,7 +139,8 @@ failure and omits the subagent.
The resolved set applies to local and remote direct delegation. An authored workflow tool can
also call a selected subagent through `ctx.agent`. A generated program can call it through the
provided `workflow` tool. eve checks availability again before starting the child, so a stale or
-manually constructed call fails with `SUBAGENT_UNAVAILABLE`. Treat conditional
+manually constructed call fails: a subagent tool call with `SUBAGENT_UNAVAILABLE`, and a
+`ctx.agent` session's first `send()` with an error saying the subagent is not available. Treat conditional
availability as capability composition, not as the only authorization
boundary: sensitive child tools still need their own authorization and
approval checks.
diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdx
index b0db1f2da..9c0020aa6 100644
--- a/docs/guides/frontend/overview.mdx
+++ b/docs/guides/frontend/overview.mdx
@@ -156,12 +156,10 @@ retry a failed prewarm on unrelated renders while the option remains `true`; cal
change the option from `false` to `true` again, reset, or send a message to recover.
The hook keeps consuming one session stream across turns and idle periods. Replies,
-authorization updates, and turns started elsewhere all update the same projection, including
-background-task results that arrive during another send. Separately delivered participant messages
-remain separate bubbles even when they steer the same active turn; a single event that coalesces
-multiple deliveries remains one bubble. Runtime-authored task input remains in the
-event stream with `data.kind: "execution.background_task"`, but the default reducer does not render
-it as a participant message. A turn settling does not close the connection. The transport reconnects from its cursor after a disconnect or the
+authorization updates, and turns started elsewhere all update the same projection. Separately
+delivered participant messages remain separate bubbles even when they steer the same active turn;
+a single event that coalesces multiple deliveries remains one bubble. A turn settling does not
+close the connection. The transport reconnects from its cursor after a disconnect or the
server's renewable 60-second lease; lease renewal does not start a turn or clear UI state.
Unmounting or resetting closes the local stream without cancelling the old durable session.
@@ -172,7 +170,7 @@ supplied `session` remains externally owned and is never replaced by prewarming
`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 parent records a successful result, for both blocking and background invocations. A background working receipt appears in `action.result`, without a completion event. The child session can remain available for reuse. Task notifications wake the parent with completion, failure, or cancellation. Detailed child progress lives on the child session's stream instead of being flattened into the root `data.messages`. When your UI needs live subagent activity, attach a [client session](../client/overview#sessions) to the parent and pass the `subagent.called` event from `events` to [`streamSubagent()`](../client/streaming#follow-a-subagent). It follows local and remote children through the parent, so the browser never calls a remote deployment directly. 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` when the parent records a successful result. The child session can remain available for reuse. Detailed child progress lives on the child session's stream instead of being flattened into the root `data.messages`. When your UI needs live subagent activity, attach a [client session](../client/overview#sessions) to the parent and pass the `subagent.called` event from `events` to [`streamSubagent()`](../client/streaming#follow-a-subagent). It follows local and remote children through the parent, so the browser never calls a remote deployment directly. See [What the parent sees](../../subagents#what-the-parent-sees) for the complete contract.
## Sending and streaming
diff --git a/docs/guides/hooks.md b/docs/guides/hooks.md
index 2810bf90b..9d4908596 100644
--- a/docs/guides/hooks.md
+++ b/docs/guides/hooks.md
@@ -215,13 +215,13 @@ The remaining subscribers for the event still run. Then eve cancels the turn the
`ctx.cancel()` returns `void` rather than a promise. The turn stops after the hook returns, so there is nothing to await. Call it before the handler's promise settles: eve ignores a call from work the handler does not await and logs a warning.
-`ctx.cancel()` only stops a running turn. eve logs a warning and ignores the call on `step.failed`, `turn.completed`, `turn.failed`, `turn.cancelled`, `session.waiting`, `session.completed`, `session.failed`, `context.cleared`, and `subagent.*` events, and during clear or compact requests.
+`ctx.cancel()` only stops a running turn. eve logs a warning and ignores the call on `step.failed`, `turn.completed`, `turn.failed`, `turn.cancelled`, `turn.waiting`, `session.waiting`, `session.completed`, `session.failed`, `context.cleared`, `agent.started`, and `subagent.*` events, and during clear or compact requests.
## Subagent isolation
Subagents may carry their own `agent/hooks/` directory. Subagent hooks fire only inside the subagent scope. Parent-agent hooks do not fire for subagent turns, and subagent hooks see only the subagent's own context.
-Interactive events such as `input.requested` and `authorization.required` are also published on the parent stream. Parent hooks observe these events after the parent channel handler and stream write, with the parent's session, agent, and channel context. The event retains the child's turn coordinates, so `event.data.turnId` can differ from `ctx.session.turn.id`. The accompanying parent `turn.completed` and `session.waiting` events also invoke parent hooks; they do not resolve pending input requests.
+Interactive events such as `input.requested` and `authorization.required` are also published on the parent stream. Parent hooks observe these events after the parent channel handler and stream write, with the parent's session, agent, and channel context. The event retains the child's turn coordinates, so `event.data.turnId` can differ from `ctx.session.turn.id`. The parent follows a proxied `input.requested` or `authorization.required` with `turn.waiting` for its own open turn, which stays open until the running call finishes. A proxied `authorization.completed` is not followed by a parent turn event. These parent events also invoke parent hooks; they do not resolve pending input requests.
## Hook vs tool vs provider
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index 15d7245bf..699cdc9b4 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -82,7 +82,7 @@ The function may be async and must return a non-empty string. `auth` and `header
By default, a remote agent is another subagent tool to the model. The model calls it the same way it calls a local subagent, with a `message` and an optional `agentId`. Set `tool: false` when an authored workflow tool should be the only model-facing routing surface; the workflow can still call the remote agent by its path-derived name through `ctx.agent()`. 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, call the remote agent from an authored workflow tool with `ctx.agent(name, { message, outputSchema })`. The schema applies to that turn, the structured value is the call's result, and the remote child remains available for follow-up messages. See [Subagents](../subagents) for continuation behavior.
+To require structured output, open a session with the remote agent from an authored workflow tool with `ctx.agent(name)` and pass `outputSchema` to `send()`. The schema applies to that turn, the structured value is the response's `data`, and the session accepts follow-up messages until the workflow run finishes. See [Delegate work: `ctx.agent`](../tools/workflows#delegate-work-ctxagent).
## Outbound auth
@@ -183,23 +183,21 @@ widen capture and use metadata-only tracing.
## How remote dispatch and callbacks work
-A remote subagent runs as a durable background task in its own deployment:
+A remote subagent call runs a child session in the remote deployment and waits for its reply:
1. The parent starts a persistent conversation session on the remote's `POST /eve/v1/session`, passing a framework callback URL.
-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.
+2. The remote accepts the child and runs its turn while the parent turn waits.
+3. The callback delivers the child's reply, which becomes the tool result.
-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.
+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. A session a workflow tool opens with `ctx.agent` is announced with `agent.started` instead, whose `data.remote.url` records the target.
-Clients follow a remote child through the parent. [`session.streamSubagent()`](./client/streaming#follow-a-subagent) reads `subagent.called.data.childStreamPath`, a route on the parent deployment. The parent verifies that the child belongs to that session, resolves the remote agent's `auth` and `headers`, and relays the child's stream. A browser never calls the remote deployment or holds its credentials; it only needs access to the parent session.
+Clients follow a remote child through the parent. [`session.streamSubagent()`](./client/streaming#follow-a-subagent) reads the event's stream path, a route on the parent deployment. The parent verifies that its session recorded the child for that tool call, resolves the remote agent's `auth` and `headers`, and relays the child's stream. A browser never calls the remote deployment or holds its credentials; it only needs access to the parent session.
-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.
+Cancelling the parent turn also cancels the remote child's current turn. 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.
-You can also steer a running remote background child by calling its subagent tool with the same `agentId` and an updated `message`. eve cancels the old task and requests cancellation of the remote turn before continuing the same remote session under a new task ID. The remote must support the standard eve cancellation and session-message routes. See [Agent messaging](../subagents#agent-messaging) for the shared steering contract.
+When the parent session ends, eve sends an authenticated `POST /eve/v1/session/:childSessionId/reset` for each remote child. A session opened with `ctx.agent` is reset the same way when its workflow run finishes. 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.
-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.
-
-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. 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.
+Both deployments must speak the same eve remote agent protocol version. The parent names its version when it creates the child, and the remote rejects a mismatch; either way the call fails at start with an error naming both versions, so upgrade both deployments to the same eve release. A failed _start_ fails the call immediately. After a remote starts, a terminal failure callback fails the call with the remote's error. 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 completing the call, so the engine retries it.
## What to read next
diff --git a/docs/instructions.mdx b/docs/instructions.mdx
index 8f86c34ad..2aecfa3ae 100644
--- a/docs/instructions.mdx
+++ b/docs/instructions.mdx
@@ -86,7 +86,7 @@ See [Dynamic capabilities](./guides/dynamic-capabilities) for examples and failu
[Compaction](./concepts/sessions-runs-and-streaming#compact-clear-and-reset) treats user-role instructions like ordinary conversation history, so a summary may replace their original text. Clear removes them with the rest of model-message history and does not rerun static or dynamic instructions. System-role instructions remain because they are outside history.
-Keep system-role content stable and place it before frequently changing context when practical. That gives providers the best opportunity to reuse a prompt prefix, but cache behavior and billing remain provider-specific. User-role instructions preserve the normal append-only message prefix. Framework announcements about available skills and background tasks are retained in user-role history: changed snapshots append after earlier steps instead of replacing the context sent with those steps. Unchanged announcements are skipped until history is cleared or compacted. eve does not promise a cache hit.
+Keep system-role content stable and place it before frequently changing context when practical. That gives providers the best opportunity to reuse a prompt prefix, but cache behavior and billing remain provider-specific. User-role instructions preserve the normal append-only message prefix. Framework announcements about available skills and parked agents are retained in user-role history: changed snapshots append after earlier steps instead of replacing the context sent with those steps. Unchanged announcements are skipped until history is cleared or compacted. eve does not promise a cache hit.
## Disclaimer
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index c142aa07b..22563a652 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -340,7 +340,7 @@ Span rows carry inline metrics when the span recorded them — `↑input`/`↓ou
Every subagent activation starts its own trace. The first child's `invoke_agent` root links to the dispatching caller with `eve.link.type=agent.dispatch`; remote agents preserve that caller in W3C `tracestate` even when HTTP `traceparent` advances through platform ingress. Later turns also start fresh traces without repeating the initial caller link. All related sessions retain the same `gen_ai.conversation.id`, and `agent.subagent.name` labels the child invocation.
-Each `agent()` call inside an authored workflow has its own `agent.action` caller span, including sequential, parallel, and background calls. A workflow tool that coordinates one of those calls has an enclosing `invoke_workflow <tool>` span; a workflow tool without agent calls remains `agent.action`. The tool also keeps its `execute_tool <tool>` span. Only agent execution uses `invoke_agent`.
+Each `agent()` call inside an authored workflow has its own `agent.action` caller span, including sequential and parallel calls. A workflow tool that coordinates one of those calls has an enclosing `invoke_workflow <tool>` span; a workflow tool without agent calls remains `agent.action`. The tool also keeps its `execute_tool <tool>` span. Only agent execution uses `invoke_agent`.
Outbound MCP `tools/call` requests add MCP semantic attributes to the matching `execute_tool` span. When eve has no tool span to enrich, it creates a `CLIENT` `tools/call <tool>` span. Each `tools/list` discovery also has a `CLIENT` span. Configured OpenTelemetry propagation fields are injected into MCP `params._meta` for JSON-RPC bodies up to 1 MiB and propagation metadata up to 8 KiB; larger requests are sent unchanged. eve removes its audience and session-lineage baggage before forwarding, and keeps the input/output content-capture policy local.
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index 37934deb7..56f5b08c4 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -108,7 +108,7 @@ import template from "../../prompts/template.txt?raw";
| `ctx.getToken(provider)` | Resolve a bearer token for an inline auth provider such as `connect("...")` |
| `ctx.requireAuth(provider)` | Evict and re-authorize an inline provider, commonly after a downstream `401` |
-Tool definitions accept `availableInSubagents: false` to restrict the tool to top-level root sessions. Authored workflow bodies also receive `ctx.agents`, a replay-stable map of callable-agent metadata, and `ctx.agent(name, input)` for invocation. A `"use step"` helper that receives the context directly should type it as `WorkflowStepToolContext`, which excludes `agents`, `agent`, and `ask`. The root-copy `agent` entry has an empty description when the root omits `description`. See [Workflows as tools](../tools/workflows#delegate-work-ctxagent) for the workflow-only context.
+Tool definitions accept `availableInSubagents: false` to restrict the tool to top-level root sessions. Authored workflow bodies also receive `ctx.agents`, a replay-stable map of callable-agent metadata, and `ctx.agent(name)`, which returns an `AgentSession` whose `send(message, options?)` resolves to a response with `result()`. A `"use step"` helper that receives the context directly should type it as `WorkflowStepToolContext`, which excludes `agents`, `agent`, and `ask`. The root-copy `agent` entry has an empty description when the root omits `description`. See [Workflows as tools](../tools/workflows#delegate-work-ctxagent) for the workflow-only context.
## Imports at a glance
diff --git a/docs/schedules.mdx b/docs/schedules.mdx
index b5e1cf978..141123bb7 100644
--- a/docs/schedules.mdx
+++ b/docs/schedules.mdx
@@ -69,58 +69,24 @@ export default defineSchedule({
cron: "* * * * *",
async run({ to, waitUntil, appAuth }) {
waitUntil(
- to(slack, { channelId: "C0123ABC" }).send(
- "Check for new critical alerts. Report only when there are any.",
- { auth: appAuth },
- ),
+ to(slack, { channelId: "C0123ABC" }).send("Summarize the new critical alerts.", {
+ auth: appAuth,
+ }),
);
},
});
```
-The agent does not have to deliver a message on every run. When a prompt makes delivery conditional, as in the alert check above, eve tells the agent how to finish successfully without sending anything to the channel. Frequent polling schedules do not need a separate filter or delivery setting.
+Every run delivers the agent's reply to the channel. To skip a run when there is nothing to report, check that condition in the handler before calling `send`.
- `to(channel, target).send(message, { auth })`: starts a session on another channel. It has the same contract as a route handler's `ctx.to(...)` handle.
- `waitUntil(promise)`: extends the cron task's lifetime so the parked session and any in-flight fetches settle before the task ends. Wrap the `send` call in it.
- `appAuth`: the app principal (`{ authenticator: "app", principalId: "eve:app", principalType: "runtime" }`). Pass it as `to(...).send(..., { auth: appAuth })` for work the agent does on its own behalf.
-The `auth` option controls which principal the session runs as. A handler may instead supply a user principal when scheduled work needs that user's grants; a session created by that dispatch still retains schedule provenance and conditional delivery behavior.
+The `auth` option controls which principal the session runs as. A handler may instead supply a user principal when scheduled work needs that user's grants; a session created by that dispatch still retains schedule provenance.
A handler-form session runs on the same durable runtime engine as any other session, so it can park (durably suspend), for instance when the channel handoff is waiting for a Slack reply. Markdown-form sessions park too, but no channel is attached, so they cannot receive follow-up messages.
-## Background task results
-
-New sessions started by schedules default to `"cohort"`: background
-outcomes wait for overlapping tasks to settle before waking the parent. To report
-independently useful results as they arrive, pass `taskDeliveryPolicy: "auto"` to
-`send(...)` inside a schedule handler:
-
-```ts title="agent/schedules/digest.ts"
-import { defineSchedule } from "eve/schedules";
-import slack from "../channels/slack";
-
-export default defineSchedule({
- cron: "0 9 * * *",
- run({ to, waitUntil, appAuth }) {
- waitUntil(
- to(slack, { channelId: "C0123ABC" }).send("Prepare the daily reports.", {
- auth: appAuth,
- taskDeliveryPolicy: "auto",
- }),
- );
- },
-});
-```
-
-The option belongs to `send(...)`. Markdown schedules use the `"cohort"` default;
-use a handler when you need to override it. Sending to an existing session preserves
-its policy unless the send supplies an explicit value.
-
-Under `"auto"`, a model call may finish silently while related work is pending.
-Available results remain in the next reporting context so the parent can combine
-previously withheld outputs later. See
-[Background task results](./channels/overview#background-task-results).
-
## Session continuity
Markdown schedules start a new session on every fire. Handler schedules do too, unless they send to an existing conversation, such as a Slack thread. Store data that must survive across fires outside session state.
diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdx
index ddbebf718..ca5e9b49b 100644
--- a/docs/subagents/index.mdx
+++ b/docs/subagents/index.mdx
@@ -9,41 +9,11 @@ Use a subagent to run independent work in parallel, narrow the available tools,
- Use a [declared local subagent](#declared-subagents) for a specialist with its own directory and authored capabilities, rather than inheriting the root's.
- Use a [remote agent](./guides/remote-agents) to delegate to a separately deployed eve agent, with its own configuration and authentication.
-A subagent can finish a model turn while background tasks started in that turn are still running.
-That turn yields; its interim reply does not complete the caller's delegated task. Background work started by an earlier turn does not hold the reply, and a turn that ends with an error always answers the caller. If the child session expires, resets, or closes before replying, the delegated task fails and reports the usage accumulated since its previous settlement.
-After the nested tasks finish, the subagent resumes and returns its final result to
-the caller. This applies to root-agent copies, declared local subagents, and remote
-subagents. The subagent session remains available for later calls.
-
-## Completion batching
-
-Overlapping background work owned by a session forms a cohort. Tasks launched in
-later user turns join the open cohort while earlier work is still pending or its
-terminal results await delivery. With `taskDeliveryPolicy: "cohort"`, eve holds
-completion, failure, and cancellation notifications
-until every task in that cohort has completed, failed, or been cancelled, then
-delivers all outcomes together in one parent turn. Partial settlements
-do not invoke the parent model. Work started after the cohort settles forms a new
-cohort.
-
-New channel sessions default to `"auto"`; schedules default to `"cohort"`.
-Pass `taskDeliveryPolicy` to `send(...)` to select or update the session policy. See
-[Background task results](/docs/channels/overview#background-task-results).
-
-With `"auto"`, a terminal outcome can start a parent turn while other tasks are
-still running. The parent reports independently useful results and stays silent
-when a useful answer depends on unfinished tasks. Ready results may share a turn.
-The reporting context includes the whole cohort and every available output,
-including previously withheld results, for a later combined report.
-
-The setting applies to background tools and built-in, declared, and remote
-subagents owned by the session. Internal subagent sessions use `"cohort"` for
-background work they start.
-
-User messages, input requests, authorization events, failures, and cancellation
-are handled without waiting for the cohort. Child lifecycle events are processed
-before completion delivery so usage accounting and handle cleanup stay ordered.
-To follow work in progress, subscribe to the child session streams.
+Each subagent call blocks the calling turn until the child replies, and the child's final result is
+the tool result. If the child session expires, resets, or closes before replying, the call fails
+and reports the usage accumulated since its previous settlement. This applies to root-agent copies,
+declared local subagents, and remote subagents. The subagent session remains available for later
+calls.
## The built-in `agent` tool
@@ -52,11 +22,11 @@ The root session receives `agent` by default. The model calls it to delegate a t
```ts
{
message: string; // everything the child needs; it does not see the parent's history
- agentId?: string; // continue or steer an existing child
+ agentId?: string; // continue an existing child
}
```
-The copy uses the root's instructions, connections, auth, and sandbox. It receives the same tools except for the root-only `agent`, 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 completion, failure, or cancellation. 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 starts with fresh conversation history and fresh state. Its file writes are immediately visible to the root. The built-in `agent` needs no configuration. Each call waits for the child's reply and returns it as the tool result, and several `agent` calls in one response run in parallel. 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.
@@ -102,9 +72,7 @@ export default defineAgent({
The parent can alternatively export `disableTool()` from a same-named tool path, such as `agent/tools/researcher.ts`. This suppresses the derived model tool without removing `researcher` from the workflow invocation registry. A same-named authored tool replaces the model-facing surface while the workflow can still call the underlying subagent with `ctx.agent("researcher", ...)`.
-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 completion, failure, or cancellation. Human input requests surface separately on the parent session.
-
-`task_cancel` is available to sessions that own background tasks, including a child that starts nested background work. Cancelling a delegated agent task also requests cancellation of its child's nested background tasks, even after that child's model turn has yielded. The child does not start another model turn for notifications from that cancelled work. This applies to self, local, and remote delegation. The calling model receives the cancellation receipt in the `task_cancel` result; a later report of that same outcome does not start another model turn.
+A declared local or remote subagent call waits for the child's reply and returns it as the tool result. Human input requests from the child surface on the parent session while the call waits. Cancelling the calling turn also cancels the child's current turn.
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.
@@ -238,7 +206,7 @@ The root built-in `agent` tool is the exception. Its children reuse the root's s
## What the parent sees
-eve lowers every tool-enabled subagent visible to the current agent (the root built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, agentId? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. To require structured output from a child, call it from an authored workflow tool with [`ctx.agent(name, { message, outputSchema })`](./tools/workflows); the schema applies to that turn, and the child remains available for follow-up messages afterward.
+eve lowers every tool-enabled subagent visible to the current agent (the root built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, agentId? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. To require structured output from a child, open a session with it from an authored workflow tool with [`ctx.agent(name)`](./tools/workflows#delegate-work-ctxagent) and pass `outputSchema` to `send()`; the schema applies to that turn, and the session accepts follow-up messages until the workflow run finishes.
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.
@@ -249,7 +217,7 @@ A directly declared subagent's tool name is the bare path-derived name, with no
```ts
{
message: string; // all context the child needs; it never sees the parent's history
- agentId?: string; // continue or steer an existing child
+ agentId?: string; // continue an existing child
}
```
@@ -257,23 +225,21 @@ By default, a subagent named `researcher` collides with an authored tool named `
Do not rely on subagent delegation by itself as an approval boundary. Put sensitive tools behind `approval`, connection approval, route/session authorization, or other controls wherever those tools can be called.
-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, pass the `subagent.called` event to [`session.streamSubagent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent. It reads `subagent.called.data.childStreamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.
+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. The parent emits `input.resolved` when it routes an answer back down to the descendant that asked. To follow the child's other progress, pass the `subagent.called` event to [`session.streamSubagent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent. It reads `subagent.called.data.childStreamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.
-Both blocking and background invocations emit `subagent.called` after dispatch and `subagent.completed` after the parent records successful completion. Completion carries the actual output and identifies the same invocation by `callId`; the child session can remain available for reuse. A background working receipt is returned as an `action.result` tool output and does not emit completion. Background completion events do not wait for the cohort report. Failure and cancellation are not successful completion; task notifications retain those outcomes.
+Every invocation emits `subagent.called` after dispatch and `subagent.completed` after the parent records successful completion. Completion carries the actual output and identifies the same invocation by `callId`; the child session can remain available for reuse. Failure and cancellation do not emit `subagent.completed`; the failed tool result carries the error.
-Channels with activity reporting attribute the backing agent's tool activity to its background task. Local and remote subagents share the task's progress item rather than adding a separate agent item. Continuing or steering a child with `agentId` attaches its new activity to the new task; the previous task keeps its completed or cancelled status. This applies to the built-in `agent` and declared subagent tools, not to child invocations inside custom workflow tools. Activity reporting is best-effort and does not change task execution or result delivery.
+A session an authored workflow tool opens with `ctx.agent` is announced with `agent.started` instead, which carries the workflow tool call's `callId` and `turnId`, the agent `name`, the child's `sessionId`, and a `streamPath` that `session.streamSubagent()` also accepts. Its questions and sign-ins reach the root session the same way.
-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. Cancellation delivers the task's final notification to an active parent even if the task must be stopped forcibly. Parent-session finalization cancels remaining live tasks.
+Channels with activity reporting show a subagent's tool activity beneath that subagent's progress item. Activity reporting is best-effort and does not change execution or result delivery.
-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 by default so completed earlier Workflow steps, tool results, and sandbox work remain available to the child. A declared subagent that opts into [Workflow checkpoint batching](./agent-config#workflow-checkpoint-batching) can instead repeat the uncommitted calls and inline tool executions in its current batch. 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.
+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 by default so completed earlier Workflow steps, tool results, and sandbox work remain available to the child. A declared subagent that opts into [Workflow checkpoint batching](./agent-config#workflow-checkpoint-batching) can instead repeat the uncommitted calls and inline tool executions in its current batch. Other recoverable 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 result instead of stacking both retry budgets; terminal errors fail immediately.
## Agent messaging
A child parks after answering instead of terminating, keeping its session and conversation history alive. A failed child turn can also leave the child parked — its latest status shows the error and the parent may message it again. Pass a parked child's `agentId` to the same subagent tool with a new `message` to continue that session. Omitting `agentId` (or passing an empty string or `null`) always starts a new child, and an `agentId` that matches no known agent falls back to starting a new child rather than failing. Passing a known `agentId` through a different subagent tool fails with `AGENT_MISMATCH`.
-To steer a running background child, call the same subagent tool with its `agentId` and the updated `message`. Before answer output or local tool execution begins, steering interrupts the child's pending model generation and applies the update in the same turn. Executing tools finish and checkpoint their results first; after answer output starts, steering waits for the next committed Workflow boundary. The receipt retains the same `agentId` and `taskId`; steering does not cancel the task, replace its completion callback, or undo tool side effects that have already occurred.
-
-A child that is still starting, or is owned by a blocking workflow invocation rather than an admitted background task, continues to return `AGENT_BUSY`. Delivery failures are reported to the caller; eve does not start a replacement child session to hide them.
+A call that names a child that is still starting or running returns `AGENT_BUSY`. Delivery failures are reported to the caller; eve does not start a replacement child session to hide them.
Whenever the set of parked (resumable) children changes, eve appends a framework-injected note to the conversation — labeled `[Agents]` and carrying an `<agents>` block — listing each child's `agentId`, name, and latest status. The static system prompt tells the model the note is injected by eve, not written by the user. The note is appended only when the listing changes (an append-only design that preserves the provider prompt cache), the most recent note is authoritative, and children that are starting or running do not appear until they park again.
diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.md
index 5662d6a97..b32daab17 100644
--- a/docs/tools/human-in-the-loop.md
+++ b/docs/tools/human-in-the-loop.md
@@ -157,7 +157,7 @@ The `ask_question` tool lets the model pause and ask the user one question, rath
- `question`: the question to put to the user, with the context needed to answer it.
- `options`: two or three mutually exclusive choices, each with a `label` and a one-sentence `description`. Channels render these as buttons or a select menu. Omit `options` for an open-ended question.
-The user can always type their own answer instead of picking an option, so the model never needs an "Other" option. The tool returns `{ status: "answered", answer }` with the chosen option's label or the user's words, `{ status: "dismissed" }` when the user moved on without answering, or `{ status: "unavailable" }` when the session cannot request input.
+The user can always type their own answer instead of picking an option, so the model never needs an "Other" option. The tool returns `{ status: "answered", answer }` with the chosen option's label or the user's words, `{ interrupted: true }` when a new message arrived that did not answer the question, or `{ status: "unavailable" }` when the session cannot request input.
`ask_question` is an [opt-in framework tool](/docs/concepts/built-in-tools#ask_question). Add it with `eve add tool/ask_question`, which creates this file:
@@ -180,7 +180,7 @@ Approvals and questions share one protocol:
3. The turn parks at `session.waiting`, durably, for as long as it takes.
4. The client answers with `inputResponses` (structured, keyed by `requestId`) or a normal follow-up `message`. A follow-up whose text matches an option ID, option label, or numeric option index resolves automatically, including approval options such as `approve` and `cancel`.
-For `ctx.ask()` questions from blocking tools, a follow-up message answers the question only when exactly one question is pending. The message must match an option, or the question must allow free text. Otherwise the message reaches the model as a normal turn, and each pending question created with `dismissible: true` resolves as `dismissed`. Questions from background tools and subagents need a structured response.
+For `ctx.ask()` questions from tools, a follow-up message answers the question only when exactly one question is pending. The message must match an option, or the question must allow free text. Otherwise the message follows the session's `turnPolicy`. A steering message, the default, fires `ctx.interruptSignal` for each workflow tool call the turn waits on, so a question asked with that signal, such as `ask_question`'s, is withdrawn and resolves as `cancelled`. The model reads the message once those calls settle. Questions from subagents need a structured response.
Each request includes a `kind` discriminator: `tool-approval`, `question`, or
`session-limit`. Clients should use `kind` to choose behavior and presentation.
@@ -189,7 +189,7 @@ tool call that raised it; neither encodes the request's semantics.
The run picks back up exactly where it parked. Because the pause is durable, nothing is held in memory while it waits — the process can restart and the parked turn survives.
-When a background subagent requests input, eve emits the same `input.requested` event on its parent session. Answering through that parent session routes the response directly to the blocked child without invoking the parent model.
+When a subagent requests input, eve emits the same `input.requested` event on its parent session. Answering through that parent session routes the response directly to the blocked child without invoking the parent model.
For approval requests, unrelated follow-up text does not deny the tool call. eve keeps the approval pending and records that pending state in model-visible session history. Follow-up turns run normally and may call other tools while the approval remains unresolved. Once it is answered, eve settles the original tool call exactly once.
diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdx
index 88bdbf709..76e8c5547 100644
--- a/docs/tools/overview.mdx
+++ b/docs/tools/overview.mdx
@@ -86,7 +86,7 @@ Provided tools define labels for `bash`, `glob`, `grep`, `load_skill`, `read_fil
### Stream preliminary tool results
-For a `defineTool` executor with the default execution mode, an async generator streams complete
+For a `defineTool` executor, an async generator streams complete
output snapshots before it finishes. Each `yield` replaces the previous snapshot; the final
yield is the normal tool result the model receives:
@@ -112,8 +112,8 @@ snapshot is visible to channels, hooks, and clients but never enters model
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. A generator `return` value is not used as
-the result in this mode; yield the final output. Workflow and background generators have
-different result rules, described under [yield and return](#yield-and-return).
+the result in this mode; yield the final output. Workflow generators have different result
+rules, described under [yield and return](#yield-and-return).
Use `label.delta(input, partial)` to project preliminary snapshots into
user-facing activity, and `label.complete(input, output)` to describe successful
@@ -128,69 +128,35 @@ label. `label.complete` does not run for failed or rejected tool calls. The
full values remain available in `action.partial` and `action.result`; renderers
receive only the projected text.
-### Background execution
-
-Background execution controls how a workflow tool delivers its result to the parent agent.
-Set `execution: "background"` on `defineWorkflowTool`; ordinary `defineTool` calls always finish
-inside the initiating step.
-
-| Definition | Durable waits inside `execute` | Result delivered to the model |
-| ------------------------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
-| `defineTool` | No; the executor runs inside the initiating step. | Executor output after it finishes. |
-| `defineWorkflowTool` | Yes; the tool call waits while the workflow can suspend. | Workflow output after it finishes. |
-| `defineWorkflowTool` + `execution: "background"` | Yes; the workflow body can outlive the initiating step. | Task receipt before the body finishes; one combined report after all tasks in its cohort are terminal. |
-
-A background workflow tool's result is the receipt `{ status: "working", taskId }`; its eventual
-output belongs to the task. Use this mode when the conversation should continue while the body
-waits for a person, webhook, or timer.
-
-For background tools, `outputSchema` and `toModelOutput` describe the fixed receipt. The body's
-return value is available through the completed task's output.
-
-The `TaskExec` argument and `task.postMessage` have been removed. Return the terminal result;
-background yields are consumed without publishing progress or retaining a task-progress stream. In a workflow body, keep values needed after a wait in local variables; workflow replay
-reconstructs them across durable waits.
-Use [`ctx.ask`](/docs/tools/workflows#ask-a-human-ctxask) when the body needs an answer from the human.
-Background tools are a normal execution mode and need no root-agent flag. Built-in, declared local,
-and remote subagents use this task lifecycle automatically.
-
-After the initiating turn accepts background tasks, eve supplies runtime-authored state for that
-cohort and instructs the model to acknowledge that the work started without waiting for results.
-[Schedule](/docs/schedules)-initiated turns are the exception: no user prompted them, so their
-launches keep conditional delivery and send no acknowledgement.
-Channel sessions default to `taskDeliveryPolicy: "auto"`: ready results can invoke
-the parent while other tasks continue. The parent reports independently useful
-results and can stay silent until related work settles. Each reporting context
-includes the whole cohort and available outputs, including previously withheld
-results. Ready results may share a turn.
-Schedules default to `"cohort"`: terminal outcomes wait for overlapping tasks
-to settle, then arrive together. Pass `taskDeliveryPolicy` to `send(...)` to select
-or update the session policy. See
-[Background task results](/docs/channels/overview#background-task-results) and
-[Schedules](/docs/schedules#background-task-results).
-User questions, input requests, and explicit task messages do not wait for the
-cohort under either policy. Failure and cancellation update lifecycle state
-immediately; their automatic reports follow the selected policy.
-See [Completion batching](/docs/subagents#completion-batching).
+### Durable waits
+
+Every tool call finishes before its turn continues. The definition decides whether the executor
+can wait durably while the call is pending:
+
+| Definition | Durable waits inside `execute` | Result delivered to the model |
+| -------------------- | -------------------------------------------------------- | ---------------------------------- |
+| `defineTool` | No; the executor runs inside the initiating step. | Executor output after it finishes. |
+| `defineWorkflowTool` | Yes; the tool call waits while the workflow can suspend. | Workflow output after it finishes. |
+
+The `TaskExec` argument and `task.postMessage` have been removed. Return the result. In a workflow
+body, keep values needed after a wait in local variables; workflow replay reconstructs them across
+durable waits. Use [`ctx.ask`](/docs/tools/workflows#ask-a-human-ctxask) when the body needs an
+answer from the human. Built-in, declared local, and remote subagent calls also block: each call
+returns the child's reply as its tool result.
### Yield and return
`yield` hands a value to eve's generator consumer, which processes it and advances the generator.
It does not by itself create a durable wait for a person, timer, or external event. The value's
-meaning depends on the tool's execution mode:
-
-| Executor | Ordinary `yield value` | Final output |
-| --------------------------------------------------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
-| `defineTool`, default execution | Earlier values are `action.partial` snapshots; the final yield becomes the tool result. | Last yielded value; a generator `return` value is ignored. |
-| `defineWorkflowTool`, default execution | Every yield is an `action.partial` snapshot. | Explicit return value; falls back to the last yield if the return is `null` or `undefined`, then to `null`. |
-| `defineWorkflowTool` with `execution: "background"` | Consumed without publishing progress or requesting a parent-agent turn. | Explicit return value becomes the task output; no return completes with `null`. The last yield is not a fallback. |
+meaning depends on the executor:
-For a background workflow tool, return completes the task and throw fails it. The automatic
-cohort report is separate from the original tool call's receipt.
+| Executor | Ordinary `yield value` | Final output |
+| -------------------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
+| `defineTool` | Earlier values are `action.partial` snapshots; the final yield becomes the tool result. | Last yielded value; a generator `return` value is ignored. |
+| `defineWorkflowTool` | Every yield is an `action.partial` snapshot. | Explicit return value; falls back to the last yield if the return is `null` or `undefined`, then to `null`. |
-Progress snapshots do not enter model history as intermediate tool results. For a default
-executor, the final output selected by the rules above becomes the tool result. For a background
-executor, the terminal cohort report provides input to a later parent-agent turn.
+Progress snapshots do not enter model history as intermediate tool results. The final output
+selected by the rules above becomes the tool result.
### Workflows as tools
diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdx
index 91530a891..975427642 100644
--- a/docs/tools/workflows.mdx
+++ b/docs/tools/workflows.mdx
@@ -8,14 +8,13 @@ A workflow tool is a static tool defined with `defineWorkflowTool` from `eve/too
`"use workflow"` as the first statement of its executor. Each call starts a durable Workflow run. Use one when a tool must wait for a person, webhook, or timer,
delegate work to subagents, or coordinate retryable steps over a long period.
-Durable suspension and background execution are independent. `defineWorkflowTool` lets the body
-suspend at durable waits without holding compute. `execution: "background"` determines whether
-the parent agent receives a task receipt and continues before the body finishes. A workflow can
-suspend in either execution mode; running in the background does not require a suspension.
+Every workflow tool call blocks its turn until the workflow settles, and the parent agent receives
+the workflow's output as the tool result. While the body waits durably, the turn parks without
+holding compute.
Workflow tools use the [Workflow SDK](https://workflow-sdk.dev): `"use workflow"`, `"use step"`, `createHook`,
`createWebhook`, `sleep`, retries, and replay. eve provides `ctx.ask` for questions answered through
-the session's channel, `ctx.agents` for effective callable-agent descriptions, and `ctx.agent` for durable agent delegation. Use `yield` to report
+the session's channel, `ctx.agents` for effective callable-agent descriptions, and `ctx.agent` for sessions with other agents. Use `yield` to report
progress and `await` on a workflow operation to wait durably. Values needed after a durable wait
stay in local variables in the workflow body.
@@ -78,7 +77,8 @@ or days later, the run resumes, deploys, and returns. The model sees one tool re
- Import `createHook`, `createWebhook`, `sleep`, and `FatalError` from `workflow` in the body.
`start`, `getRun`, and `resumeHook` from `workflow/api` belong in steps. Your app does not install
the SDK; for types, new projects list `eve/workflow-modules` in the tsconfig `types`.
-- In the body, `ctx` has `session`, `callId`, `toolName`, `abortSignal`, `agent`, `agents`, and `ask`.
+- In the body, `ctx` has `session`, `callId`, `toolName`, `abortSignal`, `interruptSignal`, `agent`,
+ `agents`, and `ask`.
A `"use step"` helper that receives `ctx` directly gets a restricted `WorkflowStepToolContext` with
`session`, `callId`, `toolName`, `abortSignal`, `getToken`, and `requireAuth`. Read `ctx.agents`, call
`ctx.agent()`, and call `ctx.ask()` in the workflow body; pass only the serializable values the step needs.
@@ -113,7 +113,8 @@ export default workflow({ maxSubagents: 20 });
```
The model supplies an async function body through the tool's `js` input. Its only host capability is
-`ctx.agent(name, { message, agentId?, outputSchema? })`. This can invoke subagents configured with `tool: false` or hidden by a same-named `disableTool()` file. Include those path-derived names in the workflow tool description or agent instructions when the model writes the program. For example:
+`ctx.agent(name, { message, outputSchema? })`, which sends the message to a new session with that
+agent and resolves to its reply, or to the structured value when `outputSchema` is set. This can invoke subagents configured with `tool: false` or hidden by a same-named `disableTool()` file. Include those path-derived names in the workflow tool description or agent instructions when the model writes the program. For example:
```js
const [triage, review] = await Promise.all([
@@ -125,12 +126,13 @@ return { triage, review };
`maxSubagents` defaults to `100` and must be an integer from `1` through `128`. The generated
program cannot access the workflow context, session state,
-credentials, imports, or ordinary tools. Agent authorization, questions, approvals, cancellation,
-and `agentId` continuation use the same owner-managed behavior as direct `ctx.agent` calls.
+credentials, imports, or ordinary tools. Each call starts a new child session; a program cannot
+continue a child from an earlier call. Agent authorization, questions, approvals, and cancellation
+behave as they do for sessions an authored workflow tool opens with `ctx.agent`.
The sandbox resumes after every pending call in the current batch settles. `Promise.all` supports
fan-out followed by fan-in, but `Promise.race` does not resume after only the first child settles.
-A child failure is thrown at the corresponding `ctx.agent` call, so generated code can catch it.
+A failed child turn throws at the corresponding `ctx.agent` call, so generated code can catch it.
The program must return a JSON-serializable value.
### Migrate from `experimental_workflow`
@@ -159,27 +161,31 @@ an agent catalog. Calls use the same target resolution, availability, and author
### Migrate an authored workflow tool
Replace `defineTool` with `defineWorkflowTool`, keep the executor's `"use workflow"` directive,
-and replace `agent(ctx, input)` and `ask(ctx, request)` with `ctx.agent(target, input)` and
-`ctx.ask(request)`. The `eve/workflow` entry point has been removed. Import `WorkflowToolContext`,
-`AgentInput`, `ToolInputRequest`, and `ToolInputResponse` from `eve/tools` when you need explicit types.
+and replace `agent(ctx, input)` and `ask(ctx, request)` with an agent session from
+[`ctx.agent(name)`](#delegate-work-ctxagent) and `ctx.ask(request)`. The `eve/workflow` entry point
+has been removed. Import `WorkflowToolContext`, `AgentSession`, `ToolInputRequest`,
+`ToolInputRequestOptions`, and `ToolInputResponse` from `eve/tools` when you need explicit types.
-## Wait or run in the background
+`ctx.ask` no longer accepts `dismissible`, and its `dismissed` status is now `cancelled`. To stop
+asking once a new message arrives, pass `ctx.interruptSignal`:
-Both modes support the same durable waits. Choose the execution mode based on when the parent
-agent should receive a tool result:
+```diff
+-const answer = await ctx.ask({ prompt, dismissible: true });
++const answer = await ctx.ask({ prompt }, { signal: ctx.interruptSignal });
+```
+
+## Wait for the result
-| | Default execution | `execution: "background"` |
-| ---------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- |
-| Tool result | The workflow's output after it finishes. | `{ status: "working", taskId }` before the body finishes. |
-| Parent turn | Waits for this tool call to finish. | Continues after receiving the receipt. |
-| Durable wait inside the body | Suspends the workflow; the tool call stays pending. | Suspends the workflow; the parent can continue independently. |
-| When the run ends | Settles the pending tool call. | Sends a task completion or failure notification to the parent agent. |
-| Cancel | Cancelling the turn cancels the run. | `task_cancel`, or the session ending. |
+A workflow tool call works like any other tool call from the model's point of view:
-Use default execution when the model needs the answer to continue. Use background execution when
-the conversation should continue while the task is pending. Background tools need no root-agent
-flag. `defineTool` does not accept background execution. See the
-[tool execution comparison](/docs/tools#background-execution).
+- **Tool result:** the workflow's output after the body finishes.
+- **Parent turn:** waits for the call to settle, then continues with the result.
+- **Durable wait inside the body:** suspends the workflow while the tool call stays pending.
+- **Cancel:** cancelling the turn cancels the run.
+- **Steering:** a new message fires the call's `ctx.interruptSignal`, and the body decides whether
+ to stop. See [Stop early for a new message](#stop-early-for-a-new-message-ctxinterruptsignal).
+
+`defineWorkflowTool` does not accept an `execution` option. Passing one throws at definition time.
### How suspension works
@@ -201,12 +207,10 @@ async *execute(input, ctx) {
```
The yield reports a snapshot, and eve advances the generator to `ctx.ask`. Awaiting the unanswered
-request is the durable wait. In default execution, the original tool call remains pending until
-the answer arrives and the body returns. With `execution: "background"`, the original call has
-already returned a task receipt, and the workflow can suspend while the conversation continues.
-Answering resumes the body in either mode.
+request is the durable wait. The original tool call remains pending until the answer arrives and
+the body returns.
-`yield` itself does not wait for approval or switch a tool into background execution. An ordinary
+`yield` itself does not wait for approval. An ordinary
Promise or Node.js timer inside a step also does not create a durable workflow suspension; use
the workflow operations for waits that must survive a restart.
@@ -260,27 +264,23 @@ code. If that code later fails and the step retries, eve reads the token from th
of exchanging the same callback again. The provider must persist the grant or token; the marker
itself contains no credentials.
-A background task becomes `input_required` during sign-in. The callback resumes that task; it does
-not rely on the launching agent turn still being active. Cancelling an authorization wait withdraws
-its callback. Cancellation uses the existing turn or task cancellation path rather than a separate
-authorization completion event.
-
-Background workflow authorization requires a new session after upgrading. In older sessions,
-`ctx.getToken` and `ctx.requireAuth` fail immediately with an instruction to start a new session.
-Blocking workflows and background workflows without auth are unaffected.
+Cancelling an authorization wait withdraws its callback. Cancellation uses the existing turn
+cancellation path rather than a separate authorization completion event.
## Ask a human: `ctx.ask`
```ts
-const answer = await ctx.ask({
- prompt: string,
- display?: "confirmation" | "select" | "text",
- options?: { id: string; label: string; description?: string; style?: "primary" | "danger" | "default" }[],
- allowFreeform?: boolean,
- dismissible?: boolean,
-});
+const answer = await ctx.ask(
+ {
+ prompt: string,
+ display?: "confirmation" | "select" | "text",
+ options?: { id: string; label: string; description?: string; style?: "primary" | "danger" | "default" }[],
+ allowFreeform?: boolean,
+ },
+ { signal?: AbortSignal },
+);
// | { status: "answered"; optionId?: string; text?: string }
-// | { status: "dismissed" }
+// | { status: "cancelled" }
// | { status: "unavailable" }
```
@@ -291,14 +291,15 @@ The `ask_question` tool is a workflow tool built on `ctx.ask`.
The answer's `status` tells the body what happened:
- `answered`: the person picked an option (`optionId`) or typed a reply (`text`).
-- `dismissed`: the request set `dismissible: true` and the person sent a message that did not answer
- it. The message reaches the agent as a normal turn. Only blocking tools can be dismissed this way.
+- `cancelled`: the request was withdrawn before anyone answered it, because the `signal` passed to
+ `ctx.ask` or the call's `abortSignal` aborted. The session emits `input.resolved` with
+ `outcome: "cancelled"`, so clients stop offering the question.
- `unavailable`: the session cannot request input, such as a scheduled run. `ctx.ask` returns this
immediately instead of waiting for an answer no one can give.
A plain follow-up message answers the request when it is the only pending question and the message
-matches an option or the request allows free text. This applies to blocking tools only: answer a
-question from a background tool or a subagent with a structured response.
+matches an option or the request allows free text. Answer a question from a subagent with a
+structured response.
`ctx.ask` composes with the SDK's own constructs; race it against a deadline:
@@ -308,8 +309,8 @@ const answer = await Promise.race([pending, sleep("4h")]);
if (answer === undefined) return { deployed: false, reason: "timed out" };
```
-- The request belongs to the run, not the turn. It stays answerable until it is answered, dismissed,
- or the run ends. In a background tool that means long after the turn that started it.
+- The request belongs to the run, not the turn. It stays answerable until it is answered, withdrawn,
+ or the run ends.
- A request is answered once. Ask again for the next answer.
- Choose option `id`s that read well on their own, such as `approve` or the option's label. A
response carries only the `id`. If a person answers after the request has already resolved, for
@@ -317,31 +318,63 @@ if (answer === undefined) return { deployed: false, reason: "timed out" };
- Ending the run, by returning, throwing, or cancellation, withdraws its pending requests.
- Several requests may be outstanding at once.
- A response never steers. A new human message that does not answer a pending request follows the
- session's normal `turnPolicy`.
+ session's normal `turnPolicy`. A steering message also fires `ctx.interruptSignal`; pass it as
+ `signal` to withdraw the question when the conversation moves on, as `ask_question` does.
+- An aborted `signal` asks the session to withdraw the question, and the session decides. If a
+ person's answer reached the session first, the ask resolves as `answered` even though the signal
+ aborted, and the channel shows it answered. Branch on `status`, not on the signal.
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, `ctx.ask` inside it.
## Delegate work: `ctx.agent`
-Workflow tools can call a subagent and wait for its result:
+`ctx.agent(name)` returns a session with an agent, shaped like the TypeScript client's session. The
+session opens on its first `send`, and each `response.result()` resolves when that message's turn
+ends:
```ts
-const result = await ctx.agent("reviewer", {
- message: "Review the deployment plan for security risks.",
- outputSchema: {
- type: "object",
- properties: {
- findings: { type: "array", items: { type: "string" } },
- },
- required: ["findings"],
- },
+import { z } from "zod";
+
+const reviewer = ctx.agent("reviewer");
+const response = await reviewer.send("Review the deployment plan for security risks.", {
+ outputSchema: z.object({ findings: z.array(z.string()) }),
+ signal: ctx.abortSignal,
});
+const { data, message, status } = await response.result();
```
-The first argument is an available agent target. On the root agent, `"agent"` starts or continues a copy of the root agent. A declared subagent uses its path-derived name and remains callable when hidden with `tool: false` or `disableTool()`. Delegated root copies and declared subagent contexts do not expose the built-in root-copy target. The invocation name `agent` is reserved, so a declared subagent cannot shadow it. eve assigns each call a replay-stable invocation identity, including repeated and parallel calls to the same target. Pass `agentId` to
-continue an existing child. An inline `outputSchema` requires structured output and determines the
-return type, so `result` in the example is typed as `{ findings: string[] }`.
+The name is an available agent target. On the root agent, `"agent"` starts a copy of the root agent.
+A declared subagent uses its path-derived name and remains callable when hidden with `tool: false`
+or `disableTool()`. Delegated root copies and declared subagent contexts do not expose the built-in
+root-copy target. The invocation name `agent` is reserved, so a declared subagent cannot shadow it.
+An unavailable name rejects the first `send`.
+
+`send(message, options?)` accepts:
+
+| Option | Description |
+| -------------- | -------------------------------------------------------------------------------------------------------- |
+| `outputSchema` | Structured output for the turn, as a Standard JSON Schema such as a Zod schema, or a JSON Schema object. |
+| `signal` | Aborting it cancels the turn the message started or joined. The turn still reports, as cancelled. |
+
+A message sent while the session's turn is running joins that turn, and its response resolves with
+that turn's result. A message sent while the session is idle starts the next turn, and the session
+keeps its conversation between turns. `result()` returns the client's `MessageResult` fields:
+
+| Field | Description |
+| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `data` | The structured value, when the turn requested `outputSchema`. |
+| `message` | The agent's final reply text, when the turn did not request `outputSchema`. |
+| `status` | `"waiting"` when the session waits for its next message, `"completed"` when the session ended with the turn, or `"failed"` when the turn failed. A cancelled turn is `"waiting"` with neither `data` nor `message`. |
+
+Every `ctx.agent(name)` call returns a new session that only the workflow run can address. The model
+does not see it; it sees what the tool returns. The session runs as the caller's principal with the
+caller's capabilities, and a person answers its questions and sign-ins at the root session, as for
+any subagent. The session ends when the run finishes, which cancels any turn still running.
+
+The parent stream announces each session with `agent.started`, which carries the tool call's
+`callId` and `turnId`, the agent `name`, the child's `sessionId`, and a `streamPath`. Pass the event to
+[`session.streamSubagent()`](/docs/guides/client/streaming#follow-a-subagent) to follow the child.
### Route to a hidden subagent with Jev
@@ -422,12 +455,15 @@ export default defineWorkflowTool({
ctx.abortSignal,
);
- return ctx.agent(target, { message: task });
+ const response = await ctx.agent(target).send(task, { signal: ctx.abortSignal });
+ const { message, status } = await response.result();
+ if (status === "failed") throw new Error(`${target} could not complete the task.`);
+ return message ?? null;
},
});
```
-The evaluation runs in a step so workflow replay records its result instead of making the routing request again. The parent model receives `agent-router`, but not `researcher` or `operator`. Jev returns the typed `"researcher" | "operator"` choice, and the selected subagent's result becomes the `agent-router` tool result.
+The evaluation runs in a step so workflow replay records its result instead of making the routing request again. The parent model receives `agent-router`, but not `researcher` or `operator`. Jev returns the typed `"researcher" | "operator"` choice, and the selected subagent's reply becomes the `agent-router` tool result.
`ctx.agents` is a replay-stable metadata snapshot taken when the workflow starts. In a top-level root workflow, `ctx.agents.agent` always represents the root-copy target and carries the root's authored `description` when provided. The snapshot also includes declared agents hidden from the parent model with `tool: false` or `disableTool()`, but exposes no model definitions, credentials, or callbacks. A delegated root copy omits `agent`, so `agentRouter()` cannot select another root copy recursively. Invocation still checks each target's availability through `ctx.agent()`.
@@ -441,7 +477,7 @@ import { agentRouter } from "eve/tools/agent-router";
export default agentRouter();
```
-Its input is `{ message: string }`. `agentRouter()` ignores entries without a non-empty description. With two or more described targets, it sends the message and effective descriptions to Jev, then invokes the selected name through `ctx.agent()`. It invokes a sole target without evaluation. In a top-level root session, the candidates include the root-copy `agent`; delegated root copies and declared subagent contexts include only their declared targets.
+Its input is `{ message: string }`. `agentRouter()` ignores entries without a non-empty description. With two or more described targets, it sends the message and effective descriptions to Jev, then sends the message to a new session with the selected agent through `ctx.agent()` and returns its reply. It invokes a sole target without evaluation. In a top-level root session, the candidates include the root-copy `agent`; delegated root copies and declared subagent contexts include only their declared targets.
When an authored tool accepts a JSON Schema supplied by the model, represent that input with a permissive object such as `z.looseObject({})`. Avoid `z.record(z.string(), z.json())`: its generated JSON Schema uses `propertyNames`, which OpenAI does not support. Validate the supplied value at the point where your tool consumes it.
@@ -449,23 +485,21 @@ This pattern controls specialist selection, not whether the parent model delegat
## Report progress: `yield`
-A workflow body may be an async generator. In default execution, yields report progress.
-Background execution consumes yielded values without publishing them or retaining a task-progress
-stream. After processing a yield, eve advances the generator; use an awaited workflow operation
-when the body needs to suspend.
+A workflow body may be an async generator whose yields report progress. After processing a yield,
+eve advances the generator; use an awaited workflow operation when the body needs to suspend.
-| Operation | Default execution | `execution: "background"` |
-| --------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------- |
-| `yield value` | Emits an `action.partial` snapshot for the pending tool call. | Consumes the value without publishing progress or requesting a parent-agent turn. |
-| `return value` | Settles the tool call with its output. | Completes the task and contributes to its cohort's terminal report. |
-| No return value | Uses the last yield as output, or `null` if there were no yields. | Completes with `null`; yielded progress is not the task output. |
+| Operation | Behavior |
+| --------------- | ----------------------------------------------------------------- |
+| `yield value` | Emits an `action.partial` snapshot for the pending tool call. |
+| `return value` | Settles the tool call with its output. |
+| No return value | Uses the last yield as output, or `null` if there were no yields. |
-For default execution, an explicit `return null` also falls back to the last yield. Prefer an
+An explicit `return null` also falls back to the last yield. Prefer an
explicit object return when progress snapshots and the final result have different shapes.
Progress snapshots are last-write-wins by tool call id and do not enter model history as
intermediate tool results. A snapshot used as the final output does enter history as the tool result.
-This background workflow consumes an intermediate yield, then suspends until its timer expires:
+This workflow reports progress, then suspends until its timer expires:
```ts title="agent/tools/remind_with_progress.ts"
import { defineWorkflowTool } from "eve/tools";
@@ -475,25 +509,22 @@ import { z } from "zod";
export default defineWorkflowTool({
description: "Schedule a reminder.",
inputSchema: z.object({ note: z.string(), delay: z.string() }),
- execution: "background",
async *execute({ note, delay }) {
"use workflow";
- yield { status: "preparing reminder" }; // Consumed without publishing progress in background mode.
+ yield { status: "preparing reminder" }; // Published as progress for the pending call.
await sleep(delay); // Durable suspension while the timer is pending.
- return { reminder: note }; // Task completion notification.
+ return { reminder: note }; // The tool result.
},
});
```
-Use [`ctx.ask`](#ask-a-human-ctxask) when the workflow needs a human answer. Removing
-`execution: "background"` makes the yield visible as progress and keeps the durable sleep; the model
-waits for the final reminder as the tool result. See [yield and return](/docs/tools#yield-and-return) for the
-final-output rules.
+Use [`ctx.ask`](#ask-a-human-ctxask) when the workflow needs a human answer. See
+[yield and return](/docs/tools#yield-and-return) for the final-output rules.
## Cancel and clean up: `ctx.abortSignal`
-`ctx.abortSignal` aborts when the run is cancelled: explicit turn cancellation for a waiting tool, `task_cancel`
-or the session ending for a background one. It is durable — it survives replay, and a step that
+`ctx.abortSignal` aborts when the run is cancelled by explicit turn cancellation. It is durable — it
+survives replay, and a step that
receives it observes the abort. Pass it into the steps that should stop, and clean up in
`try/finally`:
@@ -515,9 +546,40 @@ it is abandoned when the grace period ends. Steps that received the signal are h
first.
The caller waits up to 35 seconds for a cooperatively cancelled run to settle before forcing it
-to stop. This includes time for the run to publish its outcome after body cleanup. A background
-task records its cancelled status before cleanup finishes, so that status alone does not mean
-its work has stopped.
+to stop. This includes time for the run to publish its outcome after body cleanup.
+
+## Stop early for a new message: `ctx.interruptSignal`
+
+`ctx.interruptSignal` aborts when a steering message arrives while the turn waits on the call. A
+steering message is one sent with `turnPolicy: "steer"`, the default, that does not answer a pending
+question; a message that answers a question never interrupts. The signal aborts once, on the first
+such message. Later messages wait for the call like any other.
+
+The signal only informs the body. Steering does not cancel the call or end the turn, and the model
+reads the new message after the step's workflow tool calls settle. A body that ignores the signal
+keeps going: a deploy waiting on an approval survives unrelated messages. A body that should stop
+races the signal or passes it on. The provided `sleep` tool races it against the timer:
+
+```ts
+import { sleep } from "workflow";
+
+async execute(input, ctx) {
+ "use workflow";
+ const interrupted = new Promise<"interrupted">((resolve) =>
+ ctx.interruptSignal.addEventListener("abort", () => resolve("interrupted"), { once: true }),
+ );
+ const elapsed = sleep(input.seconds * 1_000).then(() => "elapsed" as const);
+ const woke = await Promise.race([elapsed, interrupted]);
+ return woke === "elapsed" ? { waitedSeconds: input.seconds } : { interrupted: true };
+}
+```
+
+Pass the signal to `ctx.ask` as `signal` to withdraw a question once the conversation moves on. The
+provided `ask_question` tool does this:
+
+```ts
+const answer = await ctx.ask(question, { signal: ctx.interruptSignal });
+```
## Workflow tool examples
@@ -585,7 +647,6 @@ import { issueRefund } from "../lib/refunds";
export default defineWorkflowTool({
description: "Request approval to refund an order, then issue the refund once approved.",
inputSchema: z.object({ orderId: z.string(), amount: z.number() }),
- execution: "background",
async execute({ orderId, amount }, ctx) {
"use workflow";
const decision = await ctx.ask({
@@ -605,53 +666,22 @@ export default defineWorkflowTool({
});
```
-The model reports that approval is pending and the conversation continues. The approval card stays
-on the channel. When it is answered, the refund runs and the agent is woken with the outcome.
-
-### Remind me later
-
-```ts title="agent/tools/remind.ts"
-import { defineWorkflowTool } from "eve/tools";
-import { sleep } from "workflow";
-import { z } from "zod";
-
-export default defineWorkflowTool({
- description: "Remind the user about something after a delay.",
- inputSchema: z.object({ note: z.string(), delay: z.string() }),
- execution: "background",
- async execute({ note, delay }) {
- "use workflow";
- await sleep(delay);
- return { reminder: note };
- },
-});
-```
-
-The session parks between the receipt and the wake. The agent receives the return value and relays
-it.
+The turn parks while the approval card stays on the channel. When it is answered, the refund runs
+and the agent receives the outcome as the tool result.
## Semantics
-One call, one result. A waiting tool's call resolves once, with the return value, the error, or a
-cancellation. A background tool's call resolves once, with the receipt. Its terminal outcome arrives
-in one automatic report after every task in its cohort is terminal. A cohort includes overlapping
-background work in the same session, including tasks launched in later user turns while earlier
-work remains open.
-
-While a waiting tool runs, the turn is parked. A `queue` message waits for it. A `steer` message
-cancels the turn, which cancels the run, which withdraws its requests. Input responses never steer.
-
-Background runs belong to the session. They survive turn completion and cancellation, appear in the
-session's task index, can be cancelled with `task_cancel`, and are cancelled when the session ends.
+One call, one result. A workflow tool call resolves once, with the return value, the error, or a
+cancellation.
-The parent session records each background task's outcome when it processes the child's notification.
-The first terminal outcome it records is final: a late child result cannot replace a recorded
-cancellation. Task completion does not require the wrapper workflow to have exited.
+While a workflow tool runs, the turn is parked. A `queue` message waits for it. A `steer` message
+that answers no pending question fires the call's `ctx.interruptSignal` and reaches the model once
+the call settles; it never cancels the run. Input responses never steer.
Errors follow the SDK. A thrown error in a step retries per the step's policy; `FatalError` does
not. An error that escapes the body fails the tool invocation.
-Starting a waiting workflow tool can also be retried. If dispatch is interrupted after starting a
+Starting a workflow tool can also be retried. If dispatch is interrupted after starting a
run, its retry starts another run, and both may execute. The parent tracks the run returned by the
successful dispatch attempt. Use an application idempotency key for side effects that must happen
only once.
diff --git a/e2e/fixtures/agent-agent-tool-controls/agent/tools/invoke-self.ts b/e2e/fixtures/agent-agent-tool-controls/agent/tools/invoke-self.ts
index b88982df2..d7b46b338 100644
--- a/e2e/fixtures/agent-agent-tool-controls/agent/tools/invoke-self.ts
+++ b/e2e/fixtures/agent-agent-tool-controls/agent/tools/invoke-self.ts
@@ -4,16 +4,18 @@ import {
type WorkflowToolDefinition,
} from "eve/tools";
-async function execute(_input: Record<string, unknown>, ctx: WorkflowToolContext) {
+async function execute(
+ _input: Record<string, unknown>,
+ ctx: WorkflowToolContext,
+): Promise<string | null> {
"use workflow";
- return ctx.agent("agent", { message: "E2E_INTERNAL_ROOT_COPY" });
+ const response = await ctx.agent("agent").send("E2E_INTERNAL_ROOT_COPY");
+ const { message } = await response.result();
+ return message ?? null;
}
-const tool: WorkflowToolDefinition<
- Record<string, unknown>,
- Awaited<ReturnType<WorkflowToolContext["agent"]>>
-> = defineWorkflowTool({
+const tool: WorkflowToolDefinition<Record<string, unknown>, string | null> = defineWorkflowTool({
description: "Invoke an internal copy of the root agent.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
execute,
diff --git a/e2e/fixtures/agent-agent-tool-controls/evals/root-tool-false.eval.ts b/e2e/fixtures/agent-agent-tool-controls/evals/root-tool-false.eval.ts
index 3eda30d34..99b3d53b0 100644
--- a/e2e/fixtures/agent-agent-tool-controls/evals/root-tool-false.eval.ts
+++ b/e2e/fixtures/agent-agent-tool-controls/evals/root-tool-false.eval.ts
@@ -9,7 +9,7 @@ export default defineEval({
turn.expectOk();
turn.messageIncludes("INTERNAL-ROOT-COPY-OK");
turn.calledTool("invoke-self", { count: 1 });
- turn.calledSubagent("agent", { count: 1, status: "completed" });
+ turn.event("agent.started", { count: 1, data: { name: "agent" } });
t.succeeded();
t.noFailedActions();
},
diff --git a/e2e/fixtures/agent-agent-tool-controls/evals/workflow-agent-metadata.eval.ts b/e2e/fixtures/agent-agent-tool-controls/evals/workflow-agent-metadata.eval.ts
index 1ded95cfd..2b9080689 100644
--- a/e2e/fixtures/agent-agent-tool-controls/evals/workflow-agent-metadata.eval.ts
+++ b/e2e/fixtures/agent-agent-tool-controls/evals/workflow-agent-metadata.eval.ts
@@ -15,9 +15,7 @@ export default defineEval({
equals(["agent", "operator", "researcher"]),
);
turn.calledTool("inspect-agents", { count: 1 });
- turn.calledSubagent("agent", { count: 0 });
- turn.calledSubagent("operator", { count: 0 });
- turn.calledSubagent("researcher", { count: 0 });
+ turn.notEvent("agent.started");
t.succeeded();
t.noFailedActions();
},
diff --git a/e2e/fixtures/agent-background-tools/agent/agent.ts b/e2e/fixtures/agent-background-tools/agent/agent.ts
deleted file mode 100644
index 84840de7e..000000000
--- a/e2e/fixtures/agent-background-tools/agent/agent.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { e2eAgentConfig } from "@eve-e2e/config";
-import { defineAgent } from "eve";
-import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";
-
-const RESULT = "EXPORT-COMPLETE";
-const SCHEDULED = "BACKGROUND-EXPORT-SCHEDULED";
-const EMPTY_DELIVERY_SENTINEL = "<eve-empty-delivery/>";
-
-function respond(request: MockModelRequest): MockModelResponse | string {
- const message =
- [...request.userMessages]
- .reverse()
- .find(
- (entry) =>
- entry.includes("BACKGROUND-EXPORT-") || /^(?:Background task|Export) task_/u.test(entry),
- ) ??
- request.userMessages.at(-1) ??
- "";
-
- const examplePrefix = "Alice is documenting conditional delivery. Return exactly this example:\n";
- if (message.startsWith(examplePrefix)) {
- return message.slice(examplePrefix.length);
- }
- if (message === "Repeat your previous assistant response verbatim.") {
- return (
- [...request.messages].reverse().find((entry) => entry.role === "assistant")?.text ??
- "No previous assistant response."
- );
- }
-
- if (request.userMessages.some((entry) => entry.includes(SCHEDULED))) {
- return respondScheduled(request);
- }
-
- if (message.includes("BACKGROUND-EXPORT-START")) {
- if (!request.toolResults.some((result) => result.name === "export")) {
- return {
- toolCalls: [
- {
- name: "export",
- input: { query: "ship-it" },
- },
- ],
- };
- }
- return "BACKGROUND-EXPORT-STARTED";
- }
-
- if (
- message.includes("is completed") &&
- (message.includes(RESULT) || message.includes("ship-it"))
- ) {
- return "BACKGROUND-EXPORT-DONE";
- }
-
- if (message.startsWith("Background task ")) {
- return "BACKGROUND-EXPORT-ACK";
- }
-
- return "BACKGROUND-EXPORT-IDLE";
-}
-
-function respondScheduled(request: MockModelRequest): MockModelResponse | string {
- const taskNotification = [...request.userMessages]
- .reverse()
- .find((entry) => /^(?:Background task|Export) task_[a-z0-9]+/iu.test(entry));
- if (taskNotification?.includes("is completed") && taskNotification.includes(RESULT)) {
- return "SCHEDULED-EXPORT-DONE";
- }
- const launched = request.toolResults.some((result) => result.name === "export");
- if (!launched && taskNotification === undefined) {
- return {
- toolCalls: [
- {
- name: "export",
- input: { query: "nightly" },
- },
- ],
- };
- }
- const instructedToAcknowledge = request.messages.some((entry) =>
- entry.text.includes("launch acknowledgement"),
- );
- return instructedToAcknowledge ? "SCHEDULED-EXPORT-LAUNCH-ACK" : EMPTY_DELIVERY_SENTINEL;
-}
-
-const base = e2eAgentConfig({ mock: respond });
-
-export default defineAgent({
- ...base,
- // 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),
- modelContextWindowTokens: base.modelContextWindowTokens ?? 1_000_000,
-});
diff --git a/e2e/fixtures/agent-background-tools/agent/channels/schedule-sink.ts b/e2e/fixtures/agent-background-tools/agent/channels/schedule-sink.ts
deleted file mode 100644
index c80a15933..000000000
--- a/e2e/fixtures/agent-background-tools/agent/channels/schedule-sink.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { defineChannel, POST } from "eve/channels";
-
-/**
- * Delivery target for the `scheduled-export` handler schedule.
- *
- * The only user-facing message this channel may ever receive is the settled
- * report; the launching turn and the pending update wake must stay silent.
- */
-export default defineChannel<undefined, void, { id: string }>({
- routes: [POST("/schedule-sink", async () => new Response("ok"))],
- receive(input, { from }) {
- return from(input.target.id).send(input.message, {
- auth: input.auth,
- });
- },
- events: {
- "message.completed"(event) {
- if (
- event.finishReason !== "tool-calls" &&
- event.message !== null &&
- !JSON.stringify(event.message).includes("SCHEDULED-EXPORT-DONE")
- ) {
- throw new Error(`Schedule sink received an unexpected message: ${event.message}`);
- }
- },
- },
-});
diff --git a/e2e/fixtures/agent-background-tools/agent/instructions.md b/e2e/fixtures/agent-background-tools/agent/instructions.md
deleted file mode 100644
index b02adc5eb..000000000
--- a/e2e/fixtures/agent-background-tools/agent/instructions.md
+++ /dev/null
@@ -1 +0,0 @@
-You are a test agent for generic background tools. Follow the mock model script.
diff --git a/e2e/fixtures/agent-background-tools/agent/schedules/scheduled-export.ts b/e2e/fixtures/agent-background-tools/agent/schedules/scheduled-export.ts
deleted file mode 100644
index f2c940395..000000000
--- a/e2e/fixtures/agent-background-tools/agent/schedules/scheduled-export.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { defineSchedule } from "eve/schedules";
-
-import scheduleSink from "../channels/schedule-sink";
-
-/**
- * Handler schedule used by `evals/scheduled-export.quiet-launch.eval.ts`.
- *
- * Uses a user-shaped principal to reproduce schedules that run with an
- * owner's grants. Schedule provenance must remain independent from that
- * active principal so the launch stays silent.
- */
-export default defineSchedule({
- cron: "0 0 * * *",
- run({ to, waitUntil }) {
- waitUntil(
- to(scheduleSink, { id: "scheduled-export" }).send(
- "BACKGROUND-EXPORT-SCHEDULED Run the nightly export in the background.",
- {
- auth: {
- attributes: { scheduled: "true" },
- authenticator: "fixture-user",
- principalId: "scheduled-export-owner",
- principalType: "user",
- },
- },
- ),
- );
- },
-});
diff --git a/e2e/fixtures/agent-background-tools/agent/tools/export.ts b/e2e/fixtures/agent-background-tools/agent/tools/export.ts
deleted file mode 100644
index ce3b36280..000000000
--- a/e2e/fixtures/agent-background-tools/agent/tools/export.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { defineWorkflowTool } from "eve/tools";
-import { sleep } from "workflow";
-import { z } from "zod";
-
-export default defineWorkflowTool({
- description: "Start a durable background export.",
- execution: "background",
- inputSchema: z.strictObject({ query: z.string() }),
- async *execute({ query }) {
- "use workflow";
-
- yield { progress: 0.5 };
- yield { message: "EXPORT-PROGRESS", progress: 0.75 };
- await sleep("250ms");
- return { query, result: "EXPORT-COMPLETE" };
- },
-});
diff --git a/e2e/fixtures/agent-background-tools/evals/background-export.update-and-complete.eval.ts b/e2e/fixtures/agent-background-tools/evals/background-export.update-and-complete.eval.ts
deleted file mode 100644
index 303b9495b..000000000
--- a/e2e/fixtures/agent-background-tools/evals/background-export.update-and-complete.eval.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { defineEval } from "eve/evals";
-import { satisfies } from "eve/evals/expect";
-import { defaultMessageReducer } from "eve/client";
-
-const RESULT = "EXPORT-COMPLETE";
-
-export default defineEval({
- description:
- "A background workflow streams progress and delivers one terminal report to the parent.",
- async test(t) {
- const started = await t.send("BACKGROUND-EXPORT-START");
- const conversation = started.session;
- started.expectOk();
- started.calledTool("export");
-
- const receipt = started.requireToolCall("export");
- const taskId = readTaskId(receipt.output);
- if (taskId === undefined) throw new Error("export receipt is missing taskId.");
-
- const sessionId = conversation.sessionId;
- if (sessionId === undefined) throw new Error("Eval has no parent session id.");
-
- const doneLive = t.target.watchTurn(sessionId, {
- startIndex: requireStreamIndex(started.session, "completion wait"),
- });
- const doneTurn = await doneLive.result();
- doneTurn.expectOk();
- doneTurn.messageIncludes("BACKGROUND-EXPORT-DONE");
- doneTurn.event("message.received", {
- data: (data) => data.kind === "execution.background_task",
- count: 1,
- });
-
- await t.require(
- doneTurn.events,
- satisfies(
- (events: typeof doneTurn.events) =>
- events.some(
- (event) =>
- event.type === "message.received" &&
- messageText(event.data.message).includes(
- `Background task ${taskId} (export) is completed.`,
- ) &&
- messageText(event.data.message).includes(RESULT),
- ),
- "parent receives the executor completion with task identity",
- ),
- );
-
- const reducer = defaultMessageReducer();
- const projection = [...started.events, ...doneTurn.events].reduce(
- (data, event) => reducer.reduce(data, event),
- reducer.initial(),
- );
- await t.require(
- projection.messages,
- satisfies(
- (messages: typeof projection.messages) =>
- messages.filter((message) => message.role === "user").length === 1 &&
- messages.some(
- (message) =>
- message.role === "assistant" &&
- message.parts.some(
- (part) => part.type === "text" && part.text.includes("BACKGROUND-EXPORT-DONE"),
- ),
- ),
- "frontend projection keeps the background result without rendering runtime task input",
- ),
- );
- doneTurn.event("turn.started", { count: 1 });
- doneTurn.notEvent("message.received", {
- data: (data) => messageText(data.message).includes("PROGRESS"),
- });
- t.noFailedActions();
- },
-});
-
-function readTaskId(output: unknown): string | undefined {
- if (output === null || typeof output !== "object") return undefined;
- const taskId = Reflect.get(output, "taskId");
- return typeof taskId === "string" ? taskId : undefined;
-}
-
-function requireStreamIndex(
- session: { readonly state?: { readonly streamIndex?: number } },
- operation: string,
-): number {
- const streamIndex = session.state?.streamIndex;
- if (streamIndex === undefined) throw new Error(`${operation} has no session stream index.`);
- return streamIndex;
-}
-
-function messageText(message: unknown): string {
- if (typeof message === "string") return message;
- if (!Array.isArray(message)) return "";
- return message
- .flatMap((part) =>
- part !== null &&
- typeof part === "object" &&
- Reflect.get(part, "type") === "text" &&
- typeof Reflect.get(part, "text") === "string"
- ? [Reflect.get(part, "text") as string]
- : [],
- )
- .join("\n");
-}
diff --git a/e2e/fixtures/agent-background-tools/evals/empty-delivery-marker.eval.ts b/e2e/fixtures/agent-background-tools/evals/empty-delivery-marker.eval.ts
deleted file mode 100644
index f2079bae5..000000000
--- a/e2e/fixtures/agent-background-tools/evals/empty-delivery-marker.eval.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { defineEval } from "eve/evals";
-import { equals } from "eve/evals/expect";
-
-export default defineEval({
- description:
- "Quoted delivery markers remain visible and in the next turn's context; standalone markers finish silently.",
-
- async test(t) {
- const session = await t.session();
- const examplePrefix =
- "Alice is documenting conditional delivery. Return exactly this example:\n";
-
- for (const marker of ["<eve-empty-delivery/>", "&lt;eve-empty-delivery/&gt;"]) {
- const message = `The pending-task instruction requires \`${marker}\` and no other text.`;
- const explanation = await session.send(`${examplePrefix}${message}`);
- explanation.expectOk();
- await t.require(explanation.message, equals(message));
- explanation.event("message.completed", {
- data: (data) => data.message === message,
- count: 1,
- });
- explanation.notEvent("message.completed", {
- data: (data) => data.message === null,
- });
-
- const recalled = await session.send("Repeat your previous assistant response verbatim.");
- recalled.expectOk();
- await t.require(recalled.message, equals(message));
-
- const silent = await session.send(`${examplePrefix} \n${marker}\t `);
- silent.expectOk();
- await t.require(silent.message, equals(undefined));
- silent.event("message.completed", {
- data: (data) => data.message === null,
- count: 1,
- });
- silent.notEvent("message.completed", {
- data: (data) => data.message !== null,
- });
- }
-
- const followUp = await session.send(`${examplePrefix}The documentation is ready.`);
- followUp.expectOk();
- await t.require(followUp.message, equals("The documentation is ready."));
- t.noFailedActions();
- t.succeeded();
- },
-});
diff --git a/e2e/fixtures/agent-background-tools/evals/evals.config.ts b/e2e/fixtures/agent-background-tools/evals/evals.config.ts
deleted file mode 100644
index fb5823bde..000000000
--- a/e2e/fixtures/agent-background-tools/evals/evals.config.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { defineEvalConfig } from "eve/evals";
-
-export default defineEvalConfig({
- // Background tools dispatch durable task runs; serialize to avoid starving
- // children past the per-eval timeout.
- maxConcurrency: 1,
- timeoutMs: 120_000,
-});
diff --git a/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts b/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts
deleted file mode 100644
index 9de4b9065..000000000
--- a/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { defineEval } from "eve/evals";
-import { equals, satisfies } from "eve/evals/expect";
-
-const FINAL = "SCHEDULED-EXPORT-DONE";
-
-/**
- * A schedule-launched turn that dispatches a background task sends no launch
- * acknowledgement even when it runs with a user principal: durable schedule
- * provenance keeps conditional delivery, so the
- * launching turn completes with a null message, and only the settled wake delivers a report.
- */
-export default defineEval({
- description:
- "Quiet scheduled launch: a schedule-dispatched background export acknowledges nothing and reports once on completion.",
-
- async test(t) {
- if (!t.target.capabilities.devRoutes) {
- t.skip("Target has no dev routes; schedule dispatch is dev-only.");
- }
-
- // Scheduled root dispatch: the schedule, not an inbound turn, creates the session.
- const dispatch = await t.target.dispatchSchedule("scheduled-export");
- await t.require(dispatch.scheduleId, equals("scheduled-export"));
- await t.require(
- dispatch.sessionIds,
- satisfies(
- (sessionIds: readonly string[]) => sessionIds.length > 0,
- "schedule started a session",
- ),
- );
- const sessionId = dispatch.sessionIds[0]!;
-
- // The launching turn: dispatches the background export, then delivers
- // nothing — no launch acknowledgement.
- const session = await t.target.attachSession(sessionId);
- session.succeeded();
- session.calledTool("export");
- session.event("session.waiting");
- session.event("message.completed", {
- data: (data) => data.finishReason !== "tool-calls" && data.message === null,
- count: 1,
- });
- session.notEvent("message.completed", {
- data: (data) => data.finishReason !== "tool-calls" && data.message !== null,
- });
-
- const doneLive = t.target.watchTurn(sessionId, {
- startIndex: requireStreamIndex(session, "completion wait"),
- });
- const doneTurn = await doneLive.result();
- doneTurn.expectOk();
- doneTurn.messageIncludes(FINAL);
- doneTurn.event("message.completed", {
- data: (data) => data.finishReason !== "tool-calls" && data.message !== null,
- count: 1,
- });
- await t.require(
- doneTurn.events,
- satisfies(
- (events: typeof doneTurn.events) =>
- events.every(
- (event) =>
- event.type !== "message.received" || event.data.kind === "execution.background_task",
- ),
- "any observable task wake retains framework provenance",
- ),
- );
-
- // Replay both durable turns. Only the late report survives as assistant output.
- const replayedLaunch = await t.target.attachSession(sessionId);
- const replayedDoneLive = t.target.watchTurn(sessionId, {
- startIndex: requireStreamIndex(replayedLaunch, "replayed completion"),
- });
- await replayedDoneLive.result();
- const replayedEvents = [...replayedLaunch.events, ...replayedDoneLive.events];
- await t.require(
- replayedEvents,
- satisfies(
- (events: typeof replayedEvents) =>
- events.filter(
- (event) =>
- event.type === "message.completed" &&
- event.data.message !== null &&
- JSON.stringify(event.data.message).includes(FINAL),
- ).length === 1,
- "replay retains one final export report",
- ),
- );
- t.noFailedActions();
- t.succeeded();
- },
-});
-
-function requireStreamIndex(
- session: { readonly state?: { readonly streamIndex?: number } },
- operation: string,
-): number {
- const streamIndex = session.state?.streamIndex;
- if (streamIndex === undefined) throw new Error(`${operation} has no session stream index.`);
- return streamIndex;
-}
diff --git a/e2e/fixtures/agent-background-tools/package.json b/e2e/fixtures/agent-background-tools/package.json
deleted file mode 100644
index f7554ae18..000000000
--- a/e2e/fixtures/agent-background-tools/package.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "name": "agent-background-tools",
- "version": "0.0.0",
- "private": true,
- "type": "module",
- "scripts": {
- "build": "eve build",
- "dev": "eve dev",
- "start": "eve start",
- "typecheck": "eve build --skip-sandbox-prewarm && tsc",
- "test:e2e": "eve eval --strict"
- },
- "dependencies": {
- "@eve-e2e/config": "workspace:*",
- "@workflow/world-postgres": "catalog:",
- "eve": "workspace:*",
- "zod": "catalog:"
- },
- "devDependencies": {
- "@types/node": "catalog:",
- "typescript": "catalog:"
- }
-}
diff --git a/e2e/fixtures/agent-background-tools/tsconfig.json b/e2e/fixtures/agent-background-tools/tsconfig.json
deleted file mode 100644
index 1b9a6162e..000000000
--- a/e2e/fixtures/agent-background-tools/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "esnext",
- "moduleResolution": "bundler",
- "outDir": "dist",
- "rootDir": ".",
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "forceConsistentCasingInFileNames": true,
- "declaration": false,
- "noEmit": true,
- "types": ["node", "eve/workflow-modules"]
- },
- "include": ["agent/**/*.ts", "evals/**/*.ts"]
-}
diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.ts
index f8053ff09..3d1c26041 100644
--- a/e2e/fixtures/agent-cancellation/agent/agent.ts
+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts
@@ -2,7 +2,6 @@ import { e2eAgentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
import type { MockModelRequest, MockModelResponse } from "eve/evals";
-const RECOVERY_REQUEST = "RESUME-CANCELLED-SLEEPER";
const HITL_REQUEST = "GENERATED-PROGRAM-CHILD-HITL";
async function respond(request: MockModelRequest): Promise<MockModelResponse | string> {
@@ -67,31 +66,6 @@ async function respond(request: MockModelRequest): Promise<MockModelResponse | s
],
};
}
- if (message.includes("[Agents] listing")) {
- return (
- [...request.messages].reverse().find((entry) => entry.text.startsWith("[Agents]"))?.text ??
- "No agents listed."
- );
- }
- if (message.includes(RECOVERY_REQUEST)) {
- 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 ctx.agent("sleeper", { agentId: ${agentId}, message: ${JSON.stringify(RECOVERY_REQUEST)} });`,
- },
- name: "workflow",
- },
- ],
- };
- }
return `Mock reply: ${message}`;
}
diff --git a/e2e/fixtures/agent-cancellation/agent/instructions.md b/e2e/fixtures/agent-cancellation/agent/instructions.md
index 71485cb1a..ff872c31a 100644
--- a/e2e/fixtures/agent-cancellation/agent/instructions.md
+++ b/e2e/fixtures/agent-cancellation/agent/instructions.md
@@ -5,11 +5,6 @@ You are a test fixture agent for turn-cancellation coverage.
# Rules
- When asked to complete work before answering, call `complete-work` once.
-- When the user asks for `steering-worker`, delegate the supplied message
- verbatim to that subagent in the background. Acknowledge the receipt without
- reporting a result.
-- When a background worker completes, relay its result verbatim once. Do not
- report a superseded result or include result markers in acknowledgments.
- When the user asks you to delegate a cancellation wait, call the `sleeper`
subagent exactly once and tell it to wait for cancellation.
- When the user asks you to wait for cancellation yourself, call the
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
index 18acf12f2..1371eda45 100644
--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
@@ -1,15 +1,12 @@
import { e2eSubagentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
-const RECOVERY_REQUEST = "RESUME-CANCELLED-SLEEPER";
-const RECOVERY_RESULT = "CANCELLED-SUBAGENT-RECOVERED";
const HITL_REQUEST = "GENERATED-PROGRAM-CHILD-HITL";
export default defineAgent({
- description: "Waits until its delegated turn is cancelled, then supports a recovery probe.",
+ description: "Waits until its delegated turn is cancelled.",
...e2eSubagentConfig({
mock: ({ lastUserMessage, toolResults }) => {
- if (lastUserMessage?.includes(RECOVERY_REQUEST) === true) return RECOVERY_RESULT;
if (lastUserMessage?.includes(HITL_REQUEST) === true) {
const answer = toolResults.find((result) => result.id === "child-question");
return answer === undefined
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
index 1bd233329..2a4996784 100644
--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
@@ -4,7 +4,6 @@ You are a cancellation test sleeper.
# Rules
-- If the message contains `RESUME-CANCELLED-SLEEPER`, do not call any tool. Reply with exactly `CANCELLED-SUBAGENT-RECOVERED`.
- If the message contains `GENERATED-PROGRAM-CHILD-HITL`, call `ask_question` exactly once with the question `What marker should the child return?`, then reply with `CHILD_HITL_RESULT=` followed by the answer.
- 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/subagents/steering-worker/agent.ts b/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/agent.ts
deleted file mode 100644
index 655021bc0..000000000
--- a/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/agent.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { e2eSubagentConfig } from "@eve-e2e/config";
-import { defineAgent } from "eve";
-
-export default defineAgent({
- description: "Carries out an assignment while preserving its memo across steering messages.",
- ...e2eSubagentConfig(),
-});
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/instructions.md b/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/instructions.md
deleted file mode 100644
index ca12ccff0..000000000
--- a/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/instructions.md
+++ /dev/null
@@ -1,11 +0,0 @@
-You carry out an assignment and follow steering while you work.
-
-The first message gives you `ASSIGNMENT <memo>`. Remember that memo throughout
-the assignment. Its initial result label is `ORIGINAL`.
-
-Start by calling `wait-for-cancellation` once, without a preamble, to represent
-the slow operation. Do not delegate, send progress updates, or report a result
-while that call is pending. When it returns, finish the assignment.
-
-Return only `WORKER-RESULT:<label>:<memo>`, using the latest requested label and
-the original memo. Report one result, with no explanation or superseded result.
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/tools/wait-for-cancellation.ts b/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/tools/wait-for-cancellation.ts
deleted file mode 100644
index 97c12ec6c..000000000
--- a/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/tools/wait-for-cancellation.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "../../sleeper/tools/wait-for-cancellation.js";
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.ts
deleted file mode 100644
index ef7ecf415..000000000
--- a/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.ts
+++ /dev/null
@@ -1,253 +0,0 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
-import { defineEval, type EveEvalTurn } from "eve/evals";
-import { equals, satisfies } from "eve/evals/expect";
-
-const cases = [
- {
- parentActive: false,
- steering: true,
- description: "after the parent acknowledges delegation",
- },
- { parentActive: true, steering: true, description: "while the parent also has an active turn" },
- {
- parentActive: true,
- steering: false,
- description: "an unrelated follow-up preserves the work",
- },
-] as const;
-
-export default cases.map(({ parentActive, steering, description }) =>
- defineEval({
- description: `Background subagent steering: ${description}.`,
- // The parent chooses whether and how to redirect work. A scripted parent
- // would bake an implementation option into the acceptance test.
- tags: ["real-model", "background-steering"],
- timeoutMs: 240_000,
- async test(t) {
- const conversation = await t.session();
- const memo = crypto.randomUUID();
- const original = `WORKER-RESULT:ORIGINAL:${memo}`;
- const steered = `WORKER-RESULT:STEERED:${memo}`;
- const expected = steering ? steered : original;
- let parent = await conversation.start(
- [
- "Call steering-worker exactly once in the background with this exact message:",
- `ASSIGNMENT ${memo}`,
- "Acknowledge the receipt without reporting a result. Relay its final result verbatim when it completes.",
- "End this turn after acknowledging the receipt; the worker will keep running.",
- ].join("\n"),
- );
-
- const sessionId = parent.sessionId;
- try {
- const acknowledged = await parent.result();
- acknowledged.expectOk();
- const parentTurns: EveEvalTurn[] = [acknowledged];
- // Admission can acknowledge before the child starts. Keep observing
- // from the cursor instead of assuming subagent.called precedes it.
- if (!parent.events.some((event) => event.type === "subagent.called")) {
- parent = t.target.watchTurn(sessionId, {
- startIndex: parent.session.state!.streamIndex,
- });
- }
- const called = await parent.waitForEvent("subagent.called", {
- data: { name: "steering-worker" },
- });
- await t.require(
- called.data.agentId,
- satisfies((value) => typeof value === "string", "the worker has an agent id"),
- );
- const child = t.target.watchTurn(called.data.childSessionId);
- await child.waitForEvent("actions.requested", {
- data: {
- actions: (actions) =>
- actions.some(
- (action) =>
- action.kind === "tool-call" && action.toolName === "wait-for-cancellation",
- ),
- },
- });
-
- if (parentActive) {
- // Establish a running child before holding another parent turn;
- // holding the launch turn can delay dispatch until its wait ends.
- parent = await parent.session.start(
- "Alice is preparing an update. Call wait-for-boundary once before responding.",
- );
- await parent.waitForEvent("actions.requested", {
- data: {
- actions: (actions) =>
- actions.some(
- (action) =>
- action.kind === "tool-call" && action.toolName === "wait-for-boundary",
- ),
- },
- });
- }
-
- await t.require(
- child.events,
- satisfies(
- (events: typeof child.events) =>
- !events.some((event) =>
- ["turn.completed", "turn.cancelled", "turn.failed", "session.waiting"].includes(
- event.type,
- ),
- ),
- "the follow-up arrives before the original child turn settles",
- ),
- );
-
- const activeParent = parentActive ? parent : undefined;
- parent = await parent.session.start(
- steering
- ? "Actually, use STEERED instead of ORIGINAL."
- : "What is 2 + 2? Reply with just the number.",
- { turnPolicy: "steer" },
- );
- await t.require(parent.sessionId, equals(sessionId));
-
- if (activeParent !== undefined) {
- const continued = await activeParent.result();
- continued.expectOk();
- continued.notEvent("turn.cancelled");
- continued.event("turn.started", { count: 1 });
- continued.event("turn.completed", { count: 1 });
- continued.event("message.received", {
- data: {
- message: steering
- ? "Actually, use STEERED instead of ORIGINAL."
- : "What is 2 + 2? Reply with just the number.",
- },
- count: 1,
- });
- }
- // Observe through the result-bearing task wake, not just the parent's
- // acknowledgment of the steering message or an AGENT_BUSY failure wake.
- for (let attempt = 0; attempt < 6; attempt++) {
- const turn = await parent.result();
- parentTurns.push(turn);
- if (
- turn.events.some(
- (event) =>
- event.type === "message.received" &&
- (JSON.stringify(event.data.message).includes(original) ||
- JSON.stringify(event.data.message).includes(steered)),
- )
- ) {
- break;
- }
- parent = t.target.watchTurn(sessionId, {
- startIndex: parent.session.state!.streamIndex,
- });
- }
-
- // The initial dispatch may have arrived after the acknowledgment.
- const calls = [
- called,
- ...parentTurns.flatMap((turn) =>
- turn.events.filter((event) => event.type === "subagent.called"),
- ),
- ];
- await t.require(
- calls,
- satisfies(
- (events: typeof calls) =>
- events.length > 0 &&
- events.every(
- (event) =>
- event.data.name === "steering-worker" &&
- event.data.agentId === called.data.agentId &&
- event.data.childSessionId === called.data.childSessionId,
- ),
- "all delegations address the original worker session",
- ),
- );
-
- const firstChildTurn = await child.result();
- const receipts = parentTurns.flatMap((turn) =>
- taskReceipts(turn.events).map(({ taskId }) => taskId),
- );
- await t.require(new Set(receipts).size, equals(1));
- if (steering) {
- await t.require(receipts.length >= 2, equals(true));
- }
- firstChildTurn.expectOk();
- firstChildTurn.notEvent("turn.cancelled");
- firstChildTurn.event("turn.started", { count: 1 });
- firstChildTurn.messageIncludes(expected);
- if (steering) {
- firstChildTurn.eventsSatisfy(
- "the original child never emits the superseded result",
- (events) =>
- !events.some(
- (event) =>
- event.type === "message.completed" && event.data.message?.includes(original),
- ),
- );
- }
-
- // A queued follow-up extends observation beyond the first result wake
- // without cancelling a duplicate wake that is already pending.
- parent = await parent.session.start(
- "Reply with exactly STEERING-CHECKPOINT. Do not repeat any earlier result or call tools.",
- { turnPolicy: "queue" },
- );
- let checkpointReached = false;
- for (let attempt = 0; attempt < 4; attempt++) {
- const turn = await parent.result();
- parentTurns.push(turn);
- turn.notEvent("subagent.called");
- if (turn.message?.includes("STEERING-CHECKPOINT")) {
- checkpointReached = true;
- break;
- }
- parent = t.target.watchTurn(sessionId, {
- startIndex: parent.session.state!.streamIndex,
- });
- }
- t.check(checkpointReached, equals(true)).label("parent processes the queued checkpoint");
-
- const replies = parentTurns.flatMap((turn) =>
- turn.events.flatMap((event) =>
- event.type === "message.completed" && event.data.message !== null
- ? [event.data.message]
- : [],
- ),
- );
- t.check(replies.filter((message) => message.includes("WORKER-RESULT:")).length, equals(1));
- t.check(
- replies.some((message) => message.includes(expected)),
- equals(true),
- );
- if (steering)
- t.check(
- replies.some((message) => message.includes(original)),
- equals(false),
- );
- else
- t.check(
- replies.some((message) => message.trim() === "4"),
- equals(true),
- );
- for (const turn of parentTurns) {
- turn.notEvent("turn.failed");
- turn.notEvent("session.failed");
- }
- } finally {
- // Reset owns admitted background tasks; cancelling only the parent
- // turn would leave workers alive when a gate fails.
- try {
- const cleanup = await t.target.fetch(`/eve/v1/session/${sessionId}/reset`, {
- method: "POST",
- signal: AbortSignal.timeout(10_000),
- });
- t.check(cleanup.ok, equals(true)).label("reset cleans up background work");
- } catch (error) {
- t.log(`Background steering cleanup failed: ${String(error)}`);
- t.check(false, equals(true)).label("reset cleans up background work");
- }
- }
- },
- }),
-);
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.md b/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.md
deleted file mode 100644
index cb358fdad..000000000
--- a/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.md
+++ /dev/null
@@ -1,78 +0,0 @@
-# Background subagent steering
-
-Steering must reach the existing background child before its original work completes, preserve its context, and produce one result reflecting the updated instructions; an unrelated follow-up must leave that work running.
-
-This is a provisional acceptance contract for steering an
-already-delegated assignment. These evals use synthetic assignments to detect
-duplicate delegation and superseded results.
-
-## Cases
-
-[background-steering.eval.ts][eval] exports three cases:
-
-| Case | Parent when the follow-up arrives | Expected child behavior |
-| ------ | ------------------------------------- | -------------------------------------------------------------------------------- |
-| `0000` | Finished acknowledging the delegation | Apply the steering message to the same child session. |
-| `0001` | Waiting in its own tool call | Cancel the parent turn and apply the steering message to the same child session. |
-| `0002` | Waiting in its own tool call | Answer an unrelated question; the original child finishes normally. |
-
-The eval observes the child's pending tool call before sending the follow-up
-with the eval session driver's `start(message, { turnPolicy: "steer" })`.
-The steering message is “Actually, use STEERED instead of ORIGINAL.” It does
-not name the worker, repeat the memo, or tell the parent how to route it. The
-unrelated follow-up asks “What is 2 + 2?” without instructions about background
-work. The
-[worker][worker] uses the same real matrix model as the parent and the existing
-bounded [cancellation wait][wait] (90 seconds). Its [instructions][instructions]
-ask it to return `WORKER-RESULT:ORIGINAL:<memo>` unless steering replaces
-the label. The model must interpret the steering message, retain the original memo,
-and return `WORKER-RESULT:STEERED:<memo>`; no scripted responder selects the
-answer.
-
-Assertions inspect the child stream and the parent's result-bearing task wake.
-A parent acknowledgment alone cannot pass. All observed delegations must retain
-the original `agentId` and `childSessionId`; the original child must not emit the
-superseded result, and the parent must emit the expected result exactly once
-through a subsequent queued checkpoint. This also catches duplicate result
-wakes queued before that checkpoint; it does not prove absence of arbitrarily
-late delivery.
-The unrelated case must finish normally. Reset cleans up admitted tasks even
-when an assertion fails.
-
-Same-child continuation is provisional. The eval permits either in-turn
-steering or cancellation followed by a new turn in that same child session;
-it does not fix the task-id lifetime or require a particular steering tool.
-It permits an acknowledgment of the steering message; acknowledgment wording and
-count are outside this contract.
-
-Both parent and child use the matrix model: the parent must identify and route
-the steering message, and the child must apply it while retaining context. These cases carry `real-model`, so
-mock world suites exclude them. They are acceptance tests, not assertions that
-the existing limitation should remain. No expected-failure inversion or skip
-hides a failure. Run them in CI from this fixture with
-`pnpm exec eve eval --strict --tag background-steering`.
-
-## Options to evaluate against these cases
-
-| Option | Decision criterion | Boundary to verify |
-| ------------------------------------------------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Parent calls `task_cancel`, then continues the same `agentId` | Smallest public API change: uses existing tools | Cancellation requests the child's stop, but continuation must wait until the old owner releases its claim. The eval must establish that this sequence is reliable. |
-| Explicit steering addressed to a busy `agentId` | One model action with runtime-owned ordering | Preserve the child and serialize cancellation/delivery with the existing task owner; prevent the superseded result from settling the new operation. The exact API shape is open. |
-| Automatically propagate parent steering to children | Least work for the parent model | A parent message contains no target child. Blanket propagation fails case `0002`; targeted propagation still needs a rule for selecting the affected assignment. |
-
-Current source rejects a continuation claimed by another operation as
-[`busy`][claim], mapped to [`AGENT_BUSY`][busy].
-[`cancelBackgroundAgentTask`][cancel] requests cancellation of the owned child
-turn; [`agent-settled`][settle] is a separate owner-release path. These are
-source observations, not a measured verdict for the new evals. CI results are
-needed before choosing whether existing composition is sufficient or a new
-runtime operation is warranted.
-
-[eval]: ./background-steering.eval.ts
-[worker]: ../../agent/subagents/steering-worker/agent.ts
-[instructions]: ../../agent/subagents/steering-worker/instructions.md
-[wait]: ../../agent/subagents/sleeper/tools/wait-for-cancellation.ts
-[claim]: ../../../../../packages/eve/src/subagents/handles/transitions.ts
-[busy]: ../../../../../packages/eve/src/execution/tools/subagent/invoke-step.ts
-[cancel]: ../../../../../packages/eve/src/execution/tools/subagent/task-cancel.ts
-[settle]: ../../../../../packages/eve/src/execution/tools/subagent/task-agent-requests.ts
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 15ec7c48e..153fd258d 100644
--- a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
@@ -1,12 +1,9 @@
import { defineEval } from "eve/evals";
import { satisfies } from "eve/evals/expect";
-const RECOVERY_REQUEST = "RESUME-CANCELLED-SLEEPER";
-const RECOVERY_RESULT = "CANCELLED-SUBAGENT-RECOVERED";
-
export default defineEval({
description:
- "Cancel a parent turn, cascade cancellation to its local sleeper subagent, then resume that child.",
+ "Cancel a parent turn and cascade cancellation to the local sleeper session its workflow run opened.",
timeoutMs: 240_000,
async test(t) {
@@ -16,13 +13,11 @@ export default defineEval({
const parent = await session.start(
"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", {
+ const started = await parent.waitForEvent("agent.started", {
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);
+ const child = t.target.watchTurn(started.data.sessionId);
await child.waitForEvent("actions.requested", {
data: {
actions: (actions) =>
@@ -49,7 +44,6 @@ export default defineEval({
parentTurn.event("turn.cancelled", { count: 1 });
parentTurn.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);
- parentTurn.notEvent("subagent.completed");
parentTurn.notEvent("turn.failed");
parentTurn.notEvent("session.failed");
@@ -58,37 +52,8 @@ export default defineEval({
followUp.notEvent("turn.cancelled");
followUp.messageIncludes(/CANCELLATION-SUBAGENT-FOLLOW-UP-OK/i);
- // The cancelled child must survive in the parent's model-visible
- // [Agents] listing as a parked "(cancelled)" handle. A handle leaked as
- // `running` never re-enters the listing, so this catches the abandoned
- // cancelled batch regressing to a permanent leak.
- const listing = await session.send(
- "Look at the [Agents] listing in your context and reply with the sleeper agent's entry verbatim, including its status.",
- );
- listing.expectOk();
- listing.notEvent("turn.cancelled");
- listing.messageIncludes(/sleeper/i);
- listing.messageIncludes(/\(cancelled\)/);
-
- const resumed = await session.send(
- [
- "Use the workflow tool exactly once.",
- `In its JavaScript, call ctx.agent for sleeper with agentId ${JSON.stringify(agentId)} and message ${JSON.stringify(RECOVERY_REQUEST)}.`,
- "Return the inline result and reply with it verbatim. Do not call sleeper outside workflow.",
- ].join(" "),
- );
- resumed.expectOk();
- resumed.messageIncludes(RECOVERY_RESULT);
- resumed.event("subagent.called", {
- count: 1,
- data: {
- agentId,
- childSessionId: called.data.childSessionId,
- name: "sleeper",
- },
- });
-
+ // The eval watches both the parent and the sleeper session; each one's turn is cancelled once.
t.event("turn.cancelled", { count: 2 });
- t.event("subagent.called", { count: 2, data: { name: "sleeper" } });
+ t.event("agent.started", { count: 1, data: { name: "sleeper" } });
},
});
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.ts
index 26cf52825..def2d1a37 100644
--- a/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.ts
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.ts
@@ -23,7 +23,7 @@ export default defineEval({
count: 1,
output: /CHILD_HITL_RESULT=.*GENERATED-HITL-MARKER/su,
});
- t.calledSubagent("sleeper", { count: 1, status: "completed" });
+ t.event("agent.started", { count: 1, data: { name: "sleeper" } });
t.messageIncludes("CHILD_HITL_RESULT=");
t.messageIncludes("GENERATED-HITL-MARKER");
t.noFailedActions();
diff --git a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts b/e2e/fixtures/agent-compaction-regressions/agent/agent.ts
index 8fd667036..49ba0277a 100644
--- a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts
+++ b/e2e/fixtures/agent-compaction-regressions/agent/agent.ts
@@ -16,9 +16,9 @@ import { assistantHasReport } from "../report-evidence";
import { HANDOFF_REFERENCE, REVIEW_REFERENCE } from "../release-reports";
const TEST_CONTEXT_WINDOW_TOKENS = 32_000;
-// The compiled fixture's instructions and 11 advertised tools occupy ~2,371
+// The compiled fixture's instructions and 9 advertised tools occupy ~1,773
// tokens. Reserve them in addition to the summarizer's history budget.
-const TEST_REQUEST_ENVELOPE_TOKENS = 2_371;
+const TEST_REQUEST_ENVELOPE_TOKENS = 1_773;
// Fit the capped file-output exchange, while forcing the larger review and
// handoff reports into the assistant checkpoint consumed by the script.
const TEST_HISTORY_BUDGET_TOKENS = 900;
diff --git a/e2e/fixtures/agent-prompt-cache/agent/instructions.md b/e2e/fixtures/agent-prompt-cache/agent/instructions.md
index 4c4a1c9ac..e6f1fb356 100644
--- a/e2e/fixtures/agent-prompt-cache/agent/instructions.md
+++ b/e2e/fixtures/agent-prompt-cache/agent/instructions.md
@@ -4,8 +4,5 @@ Answer general planning questions directly. When Alice supplies the purchasing
sheets and asks for reviews, delegate each sheet to a separate reviewer. Start
the five reviewers together so their work can proceed in parallel. The reviewers
can retrieve the stored purchasing sheets and their review questions through
-review_sheet. Give each reviewer just its sheet number. Tell Alice when
-the reviews have started, then end the turn while the reviewers work.
-
-Keep track of the completed reviews as their notifications arrive. When all
-five are complete, give Bob a brief summary of their findings.
+review_sheet. Give each reviewer just its sheet number. When all five reviews
+are complete, give Bob a brief summary of their findings.
diff --git a/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts b/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts
index 643b34143..f158bbe5a 100644
--- a/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts
+++ b/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts
@@ -1,4 +1,3 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
import assert from "node:assert/strict";
import { defineEval, type EveEvalContext, type EveEvalTurn } from "eve/evals";
import { satisfies } from "eve/evals/expect";
@@ -32,17 +31,17 @@ export default ["first", "later"].map((launchTurn) =>
? `Bob has the purchasing sheets ready for the event we just discussed.\n\n${reviewPacket()}`
: reviewPacket(),
);
- const taskIds = expectFiveReviewers(started);
- const turns = await waitForReviews(t, started, taskIds);
- await expectParallelReviews(t, turns);
- expectCacheReuse(t, turns);
+ expectFiveReviewers(started);
+ expectReviewSummary(started);
+ await expectParallelReviews(t, started);
+ expectCacheReuse(t, started);
},
}),
);
function expectFiveReviewers(started: EveEvalTurn) {
expectHealthyTurn(started);
- started.calledSubagent("reviewer", { status: "working", count: 5 });
+ started.calledSubagent("reviewer", { status: "completed", count: 5 });
const launchSteps = started.events
.filter((event) => event.type === "actions.requested")
.flatMap(({ data }) =>
@@ -52,49 +51,16 @@ function expectFiveReviewers(started: EveEvalTurn) {
);
assert.equal(launchSteps.length, 5, "five reviewer requests");
assert.equal(new Set(launchSteps).size, 1, "all five reviewers launch in one model step");
-
- const taskIds = taskReceipts(started.events).map(({ taskId }) => taskId);
- assert.equal(taskIds.length, 5, "five background task receipts");
- assert.equal(new Set(taskIds).size, 5, "five distinct background tasks");
- return taskIds;
-}
-
-async function waitForReviews(t: EveEvalContext, started: EveEvalTurn, taskIds: string[]) {
- const turns = [started];
- let cursor = started.session.state.streamIndex;
- for (let attempt = 0; attempt < 10 && !allCompleted(turns, taskIds); attempt += 1) {
- assert(cursor !== undefined, "parent stream cursor is present");
- const live = t.target.watchTurn(started.sessionId, { startIndex: cursor });
- const turn = await live.result();
- expectHealthyTurn(turn);
- turns.push(turn);
- cursor = live.session.state?.streamIndex;
- }
- assert(allCompleted(turns, taskIds), "all five completion notifications reach the parent");
- assert(turns.length > 1, "background completion wakes the parent");
- const final = turns.at(-1)!;
- assert(final.message?.trim(), "parent reports the completed reviews");
- final.event("step.completed", { data: { finishReason: "stop" }, count: 1 });
- for (const turn of turns) turn.notEvent("compaction.completed");
- return turns;
}
-function allCompleted(turns: EveEvalTurn[], taskIds: string[]) {
- const messages = turns
- .flatMap((turn) => turn.events)
- .filter((event) => event.type === "message.received")
- .map(({ data }) => data.message);
- return taskIds.every((id) =>
- messages.some(
- (message) =>
- message.includes(`Background task ${id} (`) && message.includes(" is completed."),
- ),
- );
+function expectReviewSummary(turn: EveEvalTurn) {
+ assert(turn.message?.trim(), "parent reports the completed reviews");
+ turn.event("step.completed", { data: { finishReason: "stop" }, count: 1 });
+ turn.notEvent("compaction.completed");
}
-async function expectParallelReviews(t: EveEvalContext, turns: EveEvalTurn[]) {
- const calls = turns
- .flatMap((turn) => turn.events)
+async function expectParallelReviews(t: EveEvalContext, turn: EveEvalTurn) {
+ const calls = turn.events
.filter((event) => event.type === "subagent.called")
.filter(({ data }) => data.name === "reviewer");
const childIds = calls.map(({ data }) => data.childSessionId);
@@ -124,11 +90,9 @@ function expectHealthyTurn(turn: EveEvalTurn) {
);
}
-function expectCacheReuse(t: EveEvalContext, turns: EveEvalTurn[]) {
- const steps = turns
- .flatMap((turn) => turn.events)
- .filter((event) => event.type === "step.completed");
- assert(steps.length >= 3, "multiple parent requests exercise cache reuse");
+function expectCacheReuse(t: EveEvalContext, turn: EveEvalTurn) {
+ const steps = turn.events.filter((event) => event.type === "step.completed");
+ assert(steps.length >= 2, "multiple parent requests exercise cache reuse");
assert(
(steps[0]?.data.usage?.inputTokens ?? 0) >= 4_096,
"review packet is large enough for conversation caching",
@@ -160,6 +124,12 @@ The budget for the weekend was agreed at the last committee meeting. It covers m
Accessibility is part of every room plan. The hall and the studio have step-free access from the side entrance, and the meeting rooms share a ramp from the garden path. Tutors keep one table in each room clear of stools for visitors who use wheelchairs, and printed instructions come in a larger type size on request. The front desk keeps a short list of quiet spaces for anyone who needs a break from the busier sessions.
+Supplies arrive in two deliveries. The first comes on Thursday afternoon with paper, paint, clay, and the printed signs, and the caretaker signs for it at the side entrance. The second comes on Friday morning with the hired easels, the portable kiln, and the extra folding tables. Bob checks each delivery against the order confirmation, notes any missing items on the budget sheet, and tells Alice before the end of the day so the tutors can adjust their plans if something is late.
+
+Each workshop has a named tutor and one volunteer helper. The tutor sets up the room before the first session, explains the safety notes for any tools or materials, and keeps an eye on the time so each group finishes promptly. The helper hands out materials, keeps the tables tidy between sessions, and fetches anything the tutor needs from the storeroom. At the end of each day the tutors leave a short note in the office about what went well, what ran short, and anything that should be ordered differently next time.
+
+Planning before the event happens through a shared noticeboard in the office and a weekly email from Alice. The email lists the confirmed workshops, the number of places booked so far, and any changes to rooms or times. Tutors reply with their final materials lists by the Monday before the event, which gives Bob enough time to place the last orders and confirm delivery slots with the suppliers.
+
After the event, volunteers pack away the reusable materials, count what remains, and label the storeroom shelves so the next programme can start from an accurate inventory. The committee would like each review to be practical and brief, focused on whether the current plan works as written rather than on redesigning the weekend.`;
function reviewPacket(): string {
@@ -168,5 +138,5 @@ function reviewPacket(): string {
(sheet, index) => `Sheet ${index + 1}: ${sheet.title}\n${sheet.question}\n\n${sheet.notes}`,
)
.join("\n\n");
- return `Alice and Bob are preparing a community centre event. Please assign these five sheets to five reviewers so they can work in parallel. Each reviewer has access to the stored sheets and their review questions, so the sheet number is enough for its assignment. Let Alice know when the reviews are underway, then give Bob a brief summary once their findings are available.\n\n${EVENT_OVERVIEW}\n\n${sheets}`;
+ return `Alice and Bob are preparing a community centre event. Please assign these five sheets to five reviewers so they can work in parallel. Each reviewer has access to the stored sheets and their review questions, so the sheet number is enough for its assignment. Once their findings are available, give Bob a brief summary.\n\n${EVENT_OVERVIEW}\n\n${sheets}`;
}
diff --git a/e2e/fixtures/agent-router/evals/agent-router.eval.ts b/e2e/fixtures/agent-router/evals/agent-router.eval.ts
index efdaa53ed..eb8246f59 100644
--- a/e2e/fixtures/agent-router/evals/agent-router.eval.ts
+++ b/e2e/fixtures/agent-router/evals/agent-router.eval.ts
@@ -8,7 +8,7 @@ export default defineEval({
turn.expectOk();
turn.messageIncludes("AGENT-ROUTER-ROOT-COPY-OK");
turn.calledTool("agent", { count: 1 });
- turn.calledSubagent("agent", { count: 1, status: "completed" });
+ turn.event("agent.started", { count: 1, data: { name: "agent" } });
t.succeeded();
t.noFailedActions();
},
diff --git a/e2e/fixtures/agent-schedules/agent/channels/quiet-sink.ts b/e2e/fixtures/agent-schedules/agent/channels/quiet-sink.ts
deleted file mode 100644
index 334dd2874..000000000
--- a/e2e/fixtures/agent-schedules/agent/channels/quiet-sink.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { defineChannel, POST } from "eve/channels";
-
-export default defineChannel<undefined, void, { id: string }>({
- routes: [POST("/quiet-sink", async () => new Response("ok"))],
- receive(input, { from }) {
- return from(input.target.id).send(input.message, {
- auth: input.auth,
- });
- },
- events: {
- "message.completed"(event) {
- if (event.finishReason !== "tool-calls" && event.message !== null) {
- throw new Error(`Quiet sink received an unexpected message: ${event.message}`);
- }
- },
- },
-});
diff --git a/e2e/fixtures/agent-schedules/agent/schedules/quiet-alerts.ts b/e2e/fixtures/agent-schedules/agent/schedules/quiet-alerts.ts
deleted file mode 100644
index e5c4d2262..000000000
--- a/e2e/fixtures/agent-schedules/agent/schedules/quiet-alerts.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { defineSchedule } from "eve/schedules";
-
-import quietSink from "../channels/quiet-sink";
-
-export default defineSchedule({
- cron: "* * * * *",
- run({ to, waitUntil, appAuth }) {
- waitUntil(
- to(quietSink, { id: "quiet-alerts" }).send(
- [
- "Call the `check-alerts` tool exactly once with an empty object.",
- "Report the critical alerts only when the returned `alerts` list is non-empty.",
- "Do not send a message when the list is empty.",
- ].join("\n"),
- {
- auth: appAuth,
- },
- ),
- );
- },
-});
diff --git a/e2e/fixtures/agent-schedules/agent/tools/check-alerts.ts b/e2e/fixtures/agent-schedules/agent/tools/check-alerts.ts
deleted file mode 100644
index 115fe8639..000000000
--- a/e2e/fixtures/agent-schedules/agent/tools/check-alerts.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { defineTool } from "eve/tools";
-import { z } from "zod";
-
-export default defineTool({
- description:
- "Smoke-test fixture: checks for critical alerts and always returns an empty alert list. Only call when explicitly asked to use `check-alerts`.",
- inputSchema: z.object({}),
- async execute() {
- return { alerts: [] };
- },
-});
diff --git a/e2e/fixtures/agent-schedules/evals/quiet-delivery.eval.ts b/e2e/fixtures/agent-schedules/evals/quiet-delivery.eval.ts
deleted file mode 100644
index 718ef143d..000000000
--- a/e2e/fixtures/agent-schedules/evals/quiet-delivery.eval.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { defineEval } from "eve/evals";
-import { equals, satisfies } from "eve/evals/expect";
-
-/** Proves an every-minute polling schedule can leave its target channel silent. */
-export default defineEval({
- tags: ["real-model"],
- description: "Conditional channel delivery: an empty scheduled alert check sends no message.",
-
- async test(t) {
- if (!t.target.capabilities.devRoutes) {
- t.skip("Target has no dev routes; schedule dispatch is dev-only.");
- }
-
- const dispatch = await t.target.dispatchSchedule("quiet-alerts");
- await t.require(dispatch.scheduleId, equals("quiet-alerts"));
- await t.require(
- dispatch.sessionIds,
- satisfies(
- (sessionIds: readonly string[]) => sessionIds.length > 0,
- "schedule started a session",
- ),
- );
- const sessionId = dispatch.sessionIds[0]!;
-
- const session = await t.target.attachSession(sessionId);
- session.succeeded();
- session.calledTool("check-alerts");
- session.event("session.waiting");
- session.event("message.completed", {
- data: (data) => data.finishReason !== "tool-calls" && data.message === null,
- count: 1,
- });
- session.notEvent("message.completed", {
- data: (data) => data.finishReason !== "tool-calls" && data.message !== null,
- });
-
- t.succeeded();
- },
-});
diff --git a/e2e/fixtures/agent-self-modification/README.md b/e2e/fixtures/agent-self-modification/README.md
index e9804afa1..f54e71cf0 100644
--- a/e2e/fixtures/agent-self-modification/README.md
+++ b/e2e/fixtures/agent-self-modification/README.md
@@ -17,7 +17,6 @@ This exercises the current standard scaffold without duplicating it in the fixtu
## Cases
- `add-agent-browser.eval.ts` asks for browser automation without naming a registry address. It checks the child's registry search and approved install, and compares the resulting extension with the checkout's official registry source. `add-slack-channel.eval.ts` similarly checks discovery, then verifies that the setup-bearing Slack item is handed off to `eve add channel/slack` without installation. Neither case needs service credentials or an external account.
-- `create-background-replication-check.eval.ts` creates a ten-second background workflow, calls it on the next turn of the authoring session, and checks its immediate receipt, delayed completion, task identity, typed input, and structured positive result.
- `create-incident-triage.eval.ts` creates an incident-triage tool and checks precedence and threshold rules across typed inputs.
- `create-shipping-quote.eval.ts` creates a quote calculator and checks destination, started-kilogram, free-shipping, and expedited pricing boundaries.
- `offer-repair.eval.ts` reproduces an incorrect reorder recommendation, checks that the parent offers but does not start a repair, confirms it, and verifies the repaired tool.
@@ -38,7 +37,7 @@ The harness snapshots the complete `agent/` tree plus installer-mutated project
Keep `maxConcurrency: 1`. The harness also serializes cleanup that continues after an eval timeout and acquires a checkout lock before snapshotting source. A concurrent `eve eval` process fails before mutation. If cleanup cannot safely restore source, the lock remains with owner diagnostics; remove it only after inspecting the retained backup and confirming no eval or development server is mutating the fixture.
-Forced rebuilds isolate source-authoring and runtime correctness in the other cases. The background replication case instead verifies that automatic rebuilding makes a newly authored capability available on the next turn of the existing session. These cases do not verify deployed proposal/merge behavior. Real-model e2e runs belong in CI. The fixture-only cleanup tests need no model or running server:
+Forced rebuilds isolate source-authoring and runtime correctness in the other cases. These cases do not verify deployed proposal/merge behavior. Real-model e2e runs belong in CI. The fixture-only cleanup tests need no model or running server:
```sh
pnpm --filter agent-self-modification test:scenario
diff --git a/e2e/fixtures/agent-self-modification/evals/self-modification/create-background-replication-check.eval.ts b/e2e/fixtures/agent-self-modification/evals/self-modification/create-background-replication-check.eval.ts
deleted file mode 100644
index 13bb04e46..000000000
--- a/e2e/fixtures/agent-self-modification/evals/self-modification/create-background-replication-check.eval.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { randomUUID } from "node:crypto";
-
-import { defineEval, type EveEvalTurn } from "eve/evals";
-
-import { withSelfModification } from "./harness";
-
-const TOOL_NAME = "eval_replication_check";
-const TOOL_PATH = `tools/${TOOL_NAME}.ts`;
-
-export default defineEval({
- tags: ["real-model"],
- description:
- "A background workflow tool created through self-modification is callable on the next turn of the same session and later reports its result.",
-
- async test(t) {
- await withSelfModification(t, async (selfMod) => {
- const previousRevision = await selfMod.runtimeRevision();
- const authored = await selfMod.request(
- [
- `Alice needs a reusable local background workflow named ${TOOL_NAME} for checking a replicated import in future conversations.`,
- "Accept batchId as a non-empty string and expectedRecords as an integer from 1 through 1000000.",
- "When invoked, start in the background, wait for 10 seconds, and then return structured data containing success set to true, the unchanged batchId and expectedRecords, and status set to ready.",
- "The initial call must return a background task receipt immediately rather than blocking the conversation for the wait.",
- "This workflow only simulates the replication wait. It must not read files, contact external services, or modify data.",
- ].join(" "),
- );
- await selfMod.readSource(TOOL_PATH);
- await selfMod.assertOnlyChanged([TOOL_PATH]);
- await selfMod.waitForRebuild(previousRevision);
-
- const batchId = `batch-${randomUUID()}`;
- const expectedRecords = 137;
- const started = await selfMod.followUp(
- authored.session,
- [
- `Start ${TOOL_NAME} exactly once for batchId ${JSON.stringify(batchId)} and expectedRecords ${expectedRecords}.`,
- "Acknowledge its background task receipt without claiming the check is finished.",
- "When the background task completes, report its returned result.",
- ].join(" "),
- );
- started.expectOk();
- started.calledTool(TOOL_NAME, { count: 1 });
- const call = started.requireToolCall(TOOL_NAME, {
- input: { batchId, expectedRecords },
- });
- const taskId = readWorkingTaskId(call.output);
- if (taskId === undefined) {
- throw new Error(`${TOOL_NAME} did not immediately return a working task receipt.`);
- }
-
- const receiptAt = actionResultTime(started.events, taskId);
- const completion = await t.target
- .watchTurn(authored.session.sessionId!, {
- startIndex: requireStreamIndex(authored.session),
- })
- .result();
- completion.expectOk();
- completion.messageIncludes(batchId);
- completion.messageIncludes("ready");
- completion.eventsSatisfy(
- "completion reports the positive result after the ten-second wait",
- (events) =>
- events.some((event) => {
- if (event.type !== "message.received") return false;
- const text = messageText(event.data.message);
- return (
- Date.parse(event.meta.at) - receiptAt >= 9_500 &&
- Date.parse(event.meta.at) - receiptAt <= 20_000 &&
- text.includes(`Background task ${taskId} (${TOOL_NAME}) is completed.`) &&
- text.includes(batchId) &&
- text.includes(String(expectedRecords)) &&
- text.includes("true") &&
- text.includes("ready")
- );
- }),
- );
- t.noFailedActions();
- t.succeeded();
- });
- },
-});
-
-function readWorkingTaskId(output: unknown): string | undefined {
- if (output === null || typeof output !== "object") return undefined;
- const taskId = Reflect.get(output, "taskId");
- const status = Reflect.get(output, "status");
- return typeof taskId === "string" && status === "working" ? taskId : undefined;
-}
-
-function actionResultTime(events: EveEvalTurn["events"], taskId: string): number {
- const result = events.find(
- (event) =>
- event.type === "action.result" &&
- event.data.result.kind === "tool-result" &&
- event.data.result.toolName === TOOL_NAME &&
- readWorkingTaskId(event.data.result.output) === taskId,
- );
- if (result === undefined) throw new Error(`${TOOL_NAME} receipt has no action result event.`);
- return Date.parse(result.meta.at);
-}
-
-function requireStreamIndex(session: {
- readonly state?: { readonly streamIndex?: number };
-}): number {
- const streamIndex = session.state?.streamIndex;
- if (streamIndex === undefined) throw new Error("Background workflow turn has no stream index.");
- return streamIndex;
-}
-
-function messageText(message: unknown): string {
- if (typeof message === "string") return message;
- return JSON.stringify(message);
-}
diff --git a/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts b/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts
index b6bb8db1d..ac717ea7c 100644
--- a/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts
+++ b/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts
@@ -160,13 +160,16 @@ export class SelfModificationHarness {
this.#turns.add(liveParent);
const parent = await liveParent.result();
parent.expectOk();
- const call = parent.requireToolCall(SELF_MODIFICATION_AGENT);
+ // The delegation blocks the turn, so it stays pending while the child waits on an approval
+ // proxied into this turn. Turn status cannot tell: every idle turn ends on session.waiting.
+ const callStatus = parent.inputRequests.length > 0 ? "pending" : "completed";
+ const call = parent.requireToolCall(SELF_MODIFICATION_AGENT, { status: callStatus });
const agentId = typeof call.input.agentId === "string" ? call.input.agentId : undefined;
const message = agentId === undefined ? undefined : call.input.message;
if (agentId !== undefined && (typeof message !== "string" || message.length === 0))
throw new Error("Self-modification continuation omitted its message.");
- let called = [...this.#turns]
+ const called = [...this.#turns]
.filter((turn) => turn.sessionId === parent.sessionId)
.flatMap((turn) => turn.events)
.find(
@@ -177,45 +180,21 @@ export class SelfModificationHarness {
? liveParent.events.includes(event)
: event.data.agentId === agentId),
);
- let continuation: EveEvalLiveTurn | undefined;
if (called?.type !== "subagent.called") {
- continuation = this.#t.target.watchTurn(parent.sessionId, {
- startIndex: liveParent.session.state.streamIndex,
- });
- this.#turns.add(continuation);
- const data: { name: string; agentId?: string } = { name: SELF_MODIFICATION_AGENT };
- if (agentId !== undefined) data.agentId = agentId;
- called = await continuation.waitForEvent("subagent.called", { data });
+ throw new Error("Self-modification parent turn did not start its child agent.");
}
- const [child] = await Promise.all([
- this.#readChild(
- called.data.childSessionId,
- typeof message === "string" ? message : undefined,
- ),
- continuation?.result().then((turn) => turn.expectOk()),
- ]);
- this.#t.calledSubagent(SELF_MODIFICATION_AGENT, { status: "working" });
+ const child = await this.#readChild(
+ called.data.childSessionId,
+ typeof message === "string" ? message : undefined,
+ );
+ this.#t.calledSubagent(SELF_MODIFICATION_AGENT);
return { child, parent, session: liveParent.session };
}
- /** Approves the registry install on the parent and observes the resumed child turn. */
+ /** Approves the registry install the parent turn paused on and observes the resumed child turn. */
async approveRegistry(run: SelfModificationRun): Promise<EveEvalTurn> {
const toolName = "registry_add";
- const liveParent = this.#t.target.watchTurn(run.session.sessionId, {
- startIndex: run.session.state.streamIndex,
- });
- this.#turns.add(liveParent);
- const approval = await liveParent.waitForEvent("input.requested", {
- data: { requests: [{ action: { kind: "tool-call", toolName } }] },
- });
- const requests = approval.data.requests.filter(
- (request) => request.action.kind === "tool-call" && request.action.toolName === toolName,
- );
- if (requests.length !== 1) {
- throw new Error(`Expected one pending ${toolName} approval, found ${requests.length}.`);
- }
- (await liveParent.result()).expectOk();
- const session = liveParent.session;
+ const session = run.session;
session.requireInputRequest({ toolName });
const childSessionId = run.child.sessionId;
const previousChild = [...this.#turns]
diff --git a/e2e/fixtures/agent-self-modification/package.json b/e2e/fixtures/agent-self-modification/package.json
index 109e12d03..c44ee35dd 100644
--- a/e2e/fixtures/agent-self-modification/package.json
+++ b/e2e/fixtures/agent-self-modification/package.json
@@ -44,7 +44,6 @@
{
"name": "create",
"evals": [
- "self-modification/create-background-replication-check",
"self-modification/create-shipping-quote",
"self-modification/create-incident-triage"
]
diff --git a/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs b/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs
index d6c0822e2..3fa79b14a 100644
--- a/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs
+++ b/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs
@@ -46,14 +46,22 @@ function context(target, signal = new AbortController().signal) {
};
}
-function completedTurn(sessionId, events = []) {
+/**
+ * Mirrors a recorded eval turn: idle turns end on session.waiting, and a blocking delegation is
+ * still pending only when its child's input request was proxied into the turn.
+ */
+function completedTurn(sessionId, events = [], { input = {}, inputRequests = [] } = {}) {
+ const call = { input, status: inputRequests.length > 0 ? "pending" : "completed" };
return {
sessionId,
events,
+ inputRequests,
+ status: "waiting",
expectOk() {},
calledSubagent() {},
- requireToolCall() {
- return { input: {} };
+ requireToolCall(name, { status = "completed" } = {}) {
+ if (call.status !== status) throw new Error(`${name} is ${call.status}, not ${status}.`);
+ return call;
},
};
}
@@ -389,44 +397,19 @@ test("apply rejects a rebuild response without a runtime revision", async () =>
});
});
-test("request falls back to a parent-boundary watch when the initial event is missed", async () => {
- const root = await sourceTree();
- const calls = [];
- const continuation = {
- sessionId: "parent",
- events: [],
- async waitForEvent() {
- return { data: { name: "self-modification__agent", childSessionId: "child" } };
- },
- async result() {
- return completedTurn("parent");
- },
- };
- const child = {
- sessionId: "child",
- events: [],
- async result() {
- return completedTurn("child");
- },
- };
- const target = targetFor({ calls, turns: { parent: continuation, child } });
- const parent = {
- sessionId: "parent",
- events: [],
- session: { state: { streamIndex: 10 } },
- async waitForEvent() {
- throw new Error("stream boundary");
- },
- async result() {
- return completedTurn("parent");
- },
+test("request accepts a pending delegation while the parent turn waits on a proxied approval", async () => {
+ const called = {
+ type: "subagent.called",
+ data: { name: "self-modification__agent", childSessionId: "child" },
};
- const t = context(target);
- t.session = async () => ({ start: async () => parent });
- const harness = await SelfModificationHarness.create(t, root);
- await harness.request("make a change");
- await harness.close();
- await rm(root, { recursive: true, force: true });
+ const parent = liveTurn("parent", [called]);
+ parent.result = async () =>
+ completedTurn("parent", [called], { inputRequests: [{ requestId: "registry-approval" }] });
+ await withHarness(async ({ harness, target }) => {
+ target.watchTurn = () => liveTurn("child");
+ const run = await harness.request("Add browser automation.", { start: async () => parent });
+ assert.equal(run.child.sessionId, "child");
+ });
});
for (const emitsCalled of [false, true]) {
@@ -444,10 +427,8 @@ for (const emitsCalled of [false, true]) {
repairParent.waitForEvent = async () => {
throw new Error("Session reached session.waiting before the expected event.");
};
- repairParent.result = async () => ({
- ...completedTurn("parent"),
- requireToolCall: () => ({ input: { agentId: "agent-1", message } }),
- });
+ repairParent.result = async () =>
+ completedTurn("parent", [], { input: { agentId: "agent-1", message } });
const diagnostic = liveTurn("child", [
{ type: "message.received", data: { message: "Diagnose only." } },
]);
diff --git a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts b/e2e/fixtures/agent-subagents-hitl/agent/agent.ts
index fca67b16d..5d9b7f373 100644
--- a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts
+++ b/e2e/fixtures/agent-subagents-hitl/agent/agent.ts
@@ -2,9 +2,7 @@ import { e2eAgentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";
-const APPROVAL_MARKER = "PROXIED-ASK-APPROVED-6R9K";
const COLLISION_MARKER = "MIXED-PARK-COMPLETE-7K2M";
-const STOCK_PRICE = "178.92";
function respond(request: MockModelRequest): MockModelResponse | string {
const message = request.lastUserMessage ?? "";
@@ -14,25 +12,23 @@ function respond(request: MockModelRequest): MockModelResponse | string {
? { toolCalls: [{ name: "read_input_hooks", input: {} }] }
: JSON.stringify(audit.output);
}
- const prompt = request.messages.map((entry) => entry.text).join("\n");
if (message.includes("Call the approval-child subagent exactly once")) {
- return request.toolResults.some((result) => result.name === "approval-child")
- ? "The approval child is waiting."
- : {
+ const approval = request.toolResults.find((result) => result.name === "approval-child");
+ return approval === undefined
+ ? {
toolCalls: [
{
input: { message: "Ask whether to deploy, then wait for the answer." },
name: "approval-child",
},
],
- };
- }
- if (prompt.includes("Background task reporting") && prompt.includes(APPROVAL_MARKER)) {
- return APPROVAL_MARKER;
+ }
+ : String(approval.output);
}
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."
+ const quote = request.toolResults.find((result) => result.name === "stock-price");
+ return quote !== undefined
+ ? `The stock-price subagent returned: ${String(quote.output)}`
: {
toolCalls: [
{
@@ -45,20 +41,6 @@ function respond(request: MockModelRequest): MockModelResponse | string {
],
};
}
- if (prompt.includes("Background task reporting") && prompt.includes(STOCK_PRICE)) {
- return `The stock price is ${STOCK_PRICE}.`;
- }
- if (
- request.messages.some(
- (entry) =>
- entry.role === "user" &&
- entry.text.startsWith("Background task ") &&
- entry.text.includes("(collision-child) is completed.\n\nResult:\n") &&
- entry.text.includes(COLLISION_MARKER),
- )
- ) {
- return COLLISION_MARKER;
- }
if (request.lastUserMessage?.includes(COLLISION_MARKER) !== true) {
return `Mock reply: ${message}`;
}
@@ -84,8 +66,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
}
if (gateResults.length === 1 && subagentResults.length === 1) {
- // The subagent tool result is a working receipt; its result arrives in a later turn.
- return "The gate was approved; the child is still working.";
+ return COLLISION_MARKER;
}
throw new Error("Mixed runtime-action step resumed before both tool results were available.");
diff --git a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
index 806fddb9f..9603874ee 100644
--- a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
+++ b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
@@ -25,15 +25,6 @@ export default defineEval({
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("action.result", {
- count: 1,
- data: {
- result: { kind: "tool-result", output: { status: "working" }, toolName: "stock-price" },
- },
- });
-
- // 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, started.session, "get_stock_price");
const resumed = await blocked.respondAll("approve");
t.check(resumed.inputRequests, equals([]));
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 4cb0f5992..0db4be71c 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,9 +6,8 @@ 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 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.
+ * The subagent may finish 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.",
@@ -23,19 +22,8 @@ export default defineEval({
const session = parked.session;
parked.calledTool("collision-gate", { count: 1, status: "pending" });
- parked.calledSubagent("collision-child", { count: 1, status: "working" });
parked.eventOrder([
{ type: "actions.requested" },
- {
- type: "action.result",
- data: {
- result: {
- kind: "tool-result",
- toolName: "collision-child",
- output: { status: "working" },
- },
- },
- },
{ type: "input.requested" },
{ type: "session.waiting" },
]);
diff --git a/e2e/fixtures/agent-subagents-hitl/evals/proxied-ask-text-response.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/proxied-ask-text-response.eval.ts
index 2a7e10f5d..7ae1a484d 100644
--- a/e2e/fixtures/agent-subagents-hitl/evals/proxied-ask-text-response.eval.ts
+++ b/e2e/fixtures/agent-subagents-hitl/evals/proxied-ask-text-response.eval.ts
@@ -6,7 +6,7 @@ export default defineEval({
timeoutMs: 90_000,
async test(t) {
const started = await t.send(
- "Call the approval-child subagent exactly once. Acknowledge its receipt and relay its final result when it completes.",
+ "Call the approval-child subagent exactly once and relay its final result when it completes.",
);
let parent = started.session;
let called = started.events.find(
diff --git a/e2e/fixtures/agent-subagents/agent/agent.ts b/e2e/fixtures/agent-subagents/agent/agent.ts
index 4f8e9ba48..043fdd342 100644
--- a/e2e/fixtures/agent-subagents/agent/agent.ts
+++ b/e2e/fixtures/agent-subagents/agent/agent.ts
@@ -2,12 +2,7 @@ import { e2eAgentConfig } from "@eve-e2e/config";
import { defineAgent, defineDynamic } from "eve";
import { mockModel } from "eve/evals";
-import {
- SCHEDULED_REMOTE_CHILD_SCENARIO,
- SCHEDULED_REMOTE_ROOT_SCENARIO,
- WORKSPACE_FORWARDING_MARKER,
- WORKSPACE_LOOKUP_MESSAGE,
-} from "../constants";
+import { WORKSPACE_FORWARDING_MARKER, WORKSPACE_LOOKUP_MESSAGE } from "../constants";
if (process.env.EVE_E2E_MODEL === "mock") {
process.env.EVE_MOCK_AUTHORED_MODELS = "1";
@@ -65,21 +60,12 @@ const workspaceDispatcher = mockModel({
) {
return "The workspace lookup was submitted.";
}
- const previous = [...request.toolResults]
- .reverse()
- .find((result) => result.name === "remote-loopback")?.output;
- const agentId =
- previous !== null &&
- typeof previous === "object" &&
- "agentId" in previous &&
- typeof previous.agentId === "string"
- ? previous.agentId
- : undefined;
+ const agentId = findAnnouncedAgentId(request.messages, "remote-loopback");
const requestCount = request.messages.filter(
(message) => message.role === "user" && message.text.includes(WORKSPACE_FORWARDING_MARKER),
).length;
if (requestCount > 1 && agentId === undefined) {
- throw new Error("Workspace continuation has no existing remote agent receipt.");
+ throw new Error("Workspace continuation has no remote agent in the <agents> note.");
}
return {
toolCalls: [
@@ -92,53 +78,16 @@ const workspaceDispatcher = mockModel({
};
},
});
-const scheduledRemoteModel = mockModel({
- modelId: "scheduled-remote-completion",
- respond(request) {
- if (request.userMessages.some((message) => message.includes(SCHEDULED_REMOTE_CHILD_SCENARIO))) {
- return "SCHEDULED-REMOTE-CHILD-RESULT";
- }
-
- const remote = completedTaskOutput(request.userMessages, "remote-loopback");
- if (remote !== undefined) return `SCHEDULED-REMOTE-FINAL ${remote}`;
- if (!request.toolResults.some((result) => result.id === "scheduled-remote")) {
- return {
- toolCalls: [
- {
- id: "scheduled-remote",
- input: { message: SCHEDULED_REMOTE_CHILD_SCENARIO },
- name: "remote-loopback",
- },
- ],
- };
- }
- return "Weekly report could not be completed before delivery because the analytics query did not return a result.";
- },
-});
-
-function completedTaskOutput(messages: readonly string[], name: string): string | undefined {
- const prefix = "[Task state]\n";
- const state = [...messages].reverse().find((message) => message.startsWith(prefix));
- if (state === undefined) return undefined;
- const parsed: unknown = JSON.parse(state.slice(prefix.length));
- if (parsed === null || typeof parsed !== "object") return undefined;
- const tasks = Reflect.get(parsed, "tasks");
- if (!Array.isArray(tasks)) return undefined;
- const task = tasks.find(
- (candidate) =>
- candidate !== null &&
- typeof candidate === "object" &&
- Reflect.get(candidate, "name") === name &&
- Reflect.get(candidate, "status") === "completed",
- );
- if (task === undefined) return undefined;
- const output = Reflect.get(task, "output");
- return output !== null &&
- typeof output === "object" &&
- Reflect.get(output, "type") === "result" &&
- typeof Reflect.get(output, "data") === "string"
- ? (Reflect.get(output, "data") as string)
- : undefined;
+/** Reads the id the framework-injected `[Agents]` note lists for a parked child. */
+function findAnnouncedAgentId(
+ messages: readonly { readonly role: string; readonly text: string }[],
+ name: string,
+): string | undefined {
+ const announcement = [...messages]
+ .reverse()
+ .find((message) => message.role === "user" && message.text.startsWith("[Agents]"));
+ const pattern = new RegExp(`<agent id="([^"]+)" name="${name}">`);
+ return announcement?.text.match(pattern)?.[1];
}
export default defineAgent({
@@ -169,15 +118,6 @@ export default defineAgent({
if (messages.some((message) => message.includes(WORKSPACE_FORWARDING_MARKER))) {
return { model: workspaceDispatcher, modelContextWindowTokens: 1_000_000 };
}
- if (
- messages.some(
- (message) =>
- message.includes(SCHEDULED_REMOTE_ROOT_SCENARIO) ||
- message.includes(SCHEDULED_REMOTE_CHILD_SCENARIO),
- )
- ) {
- return { model: scheduledRemoteModel, modelContextWindowTokens: 1_000_000 };
- }
return { model: defaultModel, modelContextWindowTokens };
},
},
diff --git a/e2e/fixtures/agent-subagents/agent/channels/scheduled-remote-sink.ts b/e2e/fixtures/agent-subagents/agent/channels/scheduled-remote-sink.ts
deleted file mode 100644
index 83f7b3c76..000000000
--- a/e2e/fixtures/agent-subagents/agent/channels/scheduled-remote-sink.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { defineChannel, POST } from "eve/channels";
-
-/** Rejects any non-null scheduled reply except the late remote-agent result. */
-export default defineChannel<undefined, void, { id: string }>({
- routes: [POST("/scheduled-remote-sink", async () => new Response("ok"))],
- receive(input, { from }) {
- return from(input.target.id).send(input.message, { auth: input.auth });
- },
- events: {
- "message.completed"(event) {
- if (
- event.finishReason !== "tool-calls" &&
- event.message !== null &&
- !JSON.stringify(event.message).includes("SCHEDULED-REMOTE-FINAL")
- ) {
- throw new Error(`Scheduled remote sink received an unexpected message: ${event.message}`);
- }
- },
- },
-});
diff --git a/e2e/fixtures/agent-subagents/agent/schedules/scheduled-remote.ts b/e2e/fixtures/agent-subagents/agent/schedules/scheduled-remote.ts
deleted file mode 100644
index ff630ef88..000000000
--- a/e2e/fixtures/agent-subagents/agent/schedules/scheduled-remote.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { defineSchedule } from "eve/schedules";
-
-import { SCHEDULED_REMOTE_ROOT_SCENARIO } from "../../constants";
-import scheduledRemoteSink from "../channels/scheduled-remote-sink";
-
-export default defineSchedule({
- cron: "0 0 * * *",
- run({ appAuth, to, waitUntil }) {
- waitUntil(
- to(scheduledRemoteSink, { id: "scheduled-remote" }).send(SCHEDULED_REMOTE_ROOT_SCENARIO, {
- auth: appAuth,
- }),
- );
- },
-});
diff --git a/e2e/fixtures/agent-subagents/agent/tools/invoke-hidden.ts b/e2e/fixtures/agent-subagents/agent/tools/invoke-hidden.ts
index 517761aeb..eca986946 100644
--- a/e2e/fixtures/agent-subagents/agent/tools/invoke-hidden.ts
+++ b/e2e/fixtures/agent-subagents/agent/tools/invoke-hidden.ts
@@ -8,7 +8,7 @@ import { z } from "zod";
type Input = { target: "tool-hidden" | "disabled-hidden" };
type Output = {
description: string;
- result: Awaited<ReturnType<WorkflowToolContext["agent"]>>;
+ result: string | null;
};
async function execute({ target }: Input, ctx: WorkflowToolContext) {
@@ -18,8 +18,9 @@ async function execute({ target }: Input, ctx: WorkflowToolContext) {
if (description === undefined) {
throw new Error(`Missing workflow metadata for internal subagent ${target}.`);
}
- const result = await ctx.agent(target, { message: "Return your fixed marker." });
- return { description, result };
+ const response = await ctx.agent(target).send("Return your fixed marker.");
+ const { message } = await response.result();
+ return { description, result: message ?? null };
}
const tool: WorkflowToolDefinition<Input, Output> = defineWorkflowTool({
diff --git a/e2e/fixtures/agent-subagents/constants.ts b/e2e/fixtures/agent-subagents/constants.ts
index 9069872cd..29b7cbf0a 100644
--- a/e2e/fixtures/agent-subagents/constants.ts
+++ b/e2e/fixtures/agent-subagents/constants.ts
@@ -4,8 +4,3 @@ export const WORKSPACE_LOOKUP_MESSAGE = [
"Report the returned name, or explain if access is denied.",
].join(" ");
export const WORKSPACE_FORWARDING_MARKER = "Shared workspace membership check.";
-
-export const SCHEDULED_REMOTE_ROOT_SCENARIO =
- "SCHEDULED-REMOTE-ROOT Ask remote-loopback to prepare Alice's scheduled report.";
-export const SCHEDULED_REMOTE_CHILD_SCENARIO =
- "SCHEDULED-REMOTE-CHILD Return exactly SCHEDULED-REMOTE-CHILD-RESULT.";
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 262c813eb..bf9d625ba 100644
--- a/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts
@@ -17,33 +17,21 @@ export default defineEval({
[
"Call the built-in agent subagent with this message:",
`"Remember this exact fact: ${MEMORABLE_FACT} Reply only with READY."`,
- "Acknowledge the task receipt without stating the fact. When the task completes, reply with the single word: delegated.",
+ "Do not state the fact yourself. When the agent replies, reply with the single word: delegated.",
].join(" "),
);
started.expectOk();
+ started.messageIncludes("delegated");
- const firstCompletion = t.target.watchTurn(started.sessionId, {
- startIndex: requireStreamIndex(started.session),
- });
- const firstCompletedTurn = await firstCompletion.result();
- firstCompletedTurn.expectOk();
- firstCompletedTurn.messageIncludes("delegated");
-
- const continued = await firstCompletion.session.send(
+ const continued = await started.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.",
- "Acknowledge the task receipt without stating the fact. When the task completes, reply with the agent's exact output and no other text.",
+ "Do not state the fact yourself. When the agent replies, reply with its 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);
+ continued.messageIncludes(MEMORABLE_FACT);
t.succeeded();
t.eventsSatisfy("both turns continue one child session", (events) => {
@@ -59,11 +47,3 @@ export default defineEval({
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 2bb2e194b..9ba6190a8 100644
--- a/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts
@@ -4,7 +4,7 @@ const MEMORABLE_FACT = "Alice named the tide station notebook Harbor Lumen 4482.
/**
* Cross-turn continuation of a remote child over a real HTTP hop: turn one
- * delegates a fact to `remote-loopback` and lets it park; turn two
+ * delegates a fact to `remote-loopback`, which parks once it replies; turn two
* re-messages the same remote child via its agentId. The fact can only come
* back if the continuation reached the same remote session.
*/
@@ -13,21 +13,16 @@ 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) {
- const started = await t.send(
+ const first = await t.send(
[
"Use the remote-loopback agent with this message:",
`"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(started.session),
- });
- const firstCompletedTurn = await firstCompletion.result();
- firstCompletedTurn.expectOk();
+ first.expectOk();
- const continued = await firstCompletion.session.send(
+ const second = await first.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."',
@@ -35,12 +30,8 @@ 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);
+ second.expectOk();
+ second.messageIncludes(MEMORABLE_FACT);
t.succeeded();
t.eventsSatisfy("both turns continue one remote child session", (events) => {
@@ -58,11 +49,3 @@ export default defineEval({
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 d1951c0ce..1a91c7359 100644
--- a/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts
@@ -80,7 +80,7 @@ export default defineEval({
`Do not call any tool or subagent. Reply with exactly ${ROOT_RECOVERY_TOKEN} and nothing else.`,
);
recovered.expectOk();
- stopSession.calledSubagent("limited-worker", { status: "working", count: 1 });
+ stopSession.event("subagent.called", { data: { name: "limited-worker" }, count: 1 });
recovered.messageIncludes(ROOT_RECOVERY_TOKEN);
},
});
diff --git a/e2e/fixtures/agent-subagents/evals/disabled-subagent-tool.eval.ts b/e2e/fixtures/agent-subagents/evals/disabled-subagent-tool.eval.ts
index 9defa271a..d6b71b2fb 100644
--- a/e2e/fixtures/agent-subagents/evals/disabled-subagent-tool.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/disabled-subagent-tool.eval.ts
@@ -9,8 +9,7 @@ export default defineEval({
turn.expectOk();
turn.messageIncludes("DISABLED-SUBAGENT-OK");
turn.calledTool("invoke-hidden", { count: 1 });
- turn.calledSubagent("disabled-hidden", { count: 1, status: "completed" });
- turn.calledSubagent("tool-hidden", { count: 0 });
+ turn.event("agent.started", { count: 1, data: { name: "disabled-hidden" } });
t.succeeded();
t.noFailedActions();
},
diff --git a/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts b/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts
index 47d9036ee..f9ede37a3 100644
--- a/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts
@@ -1,4 +1,4 @@
-import { defineEval, type EveEvalContext, type EveEvalSession } from "eve/evals";
+import { defineEval } from "eve/evals";
export default defineEval({
description:
@@ -6,40 +6,12 @@ export default defineEval({
async test(t) {
const selected = await t.send("Call conditional-marker exactly once.");
selected.expectOk();
- selected.event("action.result", {
- count: 1,
- data: {
- result: {
- kind: "tool-result",
- output: { status: "working" },
- toolName: "conditional-marker",
- },
- },
- });
- const completed = await waitForMessage(t, selected.session, "DYNAMIC_SUBAGENT_ENABLED");
+ selected.calledSubagent("conditional-marker", { count: 1 });
+ selected.messageIncludes("DYNAMIC_SUBAGENT_ENABLED");
- const omitted = await completed.send("Call omitted-marker exactly once.");
+ const omitted = await selected.session.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/dynamic-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts
index 180e12b5f..36a996a05 100644
--- a/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts
@@ -25,30 +25,27 @@ export default defineEval({
const parent = await session.start(
"Use the workflow tool exactly once to fan out two independent echo-marker subagent calls. In its JavaScript, create the messages 'workflow alpha' and 'workflow beta', map them through ctx.agent calls to echo-marker inside Promise.all, and return the resulting two-element array. Do not call echo-marker outside workflow. Then reply with the returned array verbatim as JSON.",
);
- const firstCalled = await parent.waitForEvent("subagent.called", {
+ const firstStarted = await parent.waitForEvent("agent.started", {
data: { name: "echo-marker" },
});
- const firstChild = t.target.watchTurn(firstCalled.data.childSessionId).result();
- const secondCalled = await parent.waitForEvent("subagent.called", {
+ const firstChild = t.target.watchTurn(firstStarted.data.sessionId).result();
+ const secondStarted = await parent.waitForEvent("agent.started", {
data: {
- callId: (callId) => callId !== firstCalled.data.callId,
name: "echo-marker",
+ sessionId: (sessionId) => sessionId !== firstStarted.data.sessionId,
},
});
- if (secondCalled.data.childSessionId === firstCalled.data.childSessionId) {
- throw new Error("Parallel workflow calls reused one child session.");
- }
- const secondChild = t.target.watchTurn(secondCalled.data.childSessionId).result();
+ const secondChild = t.target.watchTurn(secondStarted.data.sessionId).result();
const [turn, firstChildTurn, secondChildTurn] = await Promise.all([
parent.result(),
firstChild,
secondChild,
]);
- const latestCallAt = [firstCalled.meta.at, secondCalled.meta.at].sort().at(-1)!;
+ const latestCallAt = [firstStarted.meta.at, secondStarted.meta.at].sort().at(-1)!;
t.succeeded();
t.calledTool("workflow", { input: isFanOutProgram, count: 1 });
- turn.calledSubagent("echo-marker", { count: 2, status: "completed" });
+ turn.event("agent.started", { count: 2, data: { name: "echo-marker" } });
firstChildTurn.eventsSatisfy(
"first child does not complete before both children start",
(events) =>
diff --git a/e2e/fixtures/agent-subagents/evals/hidden-subagents.eval.ts b/e2e/fixtures/agent-subagents/evals/hidden-subagents.eval.ts
index 7bf21b00c..1c0b07608 100644
--- a/e2e/fixtures/agent-subagents/evals/hidden-subagents.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/hidden-subagents.eval.ts
@@ -10,8 +10,7 @@ export default defineEval({
turn.messageIncludes("TOOL-FALSE-SUBAGENT-OK");
turn.messageIncludes("Internal specialist hidden by its agent definition.");
turn.calledTool("invoke-hidden", { count: 1 });
- turn.calledSubagent("tool-hidden", { count: 1, status: "completed" });
- turn.calledSubagent("disabled-hidden", { count: 0 });
+ turn.event("agent.started", { count: 1, data: { name: "tool-hidden" } });
t.succeeded();
t.noFailedActions();
},
diff --git a/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts b/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts
index ba1fe5a4f..0d84702be 100644
--- a/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts
@@ -11,13 +11,9 @@ export default defineEval({
tags: ["real-model"],
description: "Local subagent delegation smoke: child output reaches the parent reply verbatim.",
async test(t) {
- const started = await t.send(
+ const completed = 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(started.session) })
- .result();
completed.expectOk();
completed.messageIncludes(SUBAGENT_TOKEN);
@@ -25,11 +21,3 @@ export default defineEval({
t.calledSubagent("echo-marker", { status: "completed" });
},
});
-
-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/nested-background/cancel-local.eval.ts b/e2e/fixtures/agent-subagents/evals/nested-background/cancel-local.eval.ts
deleted file mode 100644
index 042216907..000000000
--- a/e2e/fixtures/agent-subagents/evals/nested-background/cancel-local.eval.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import assert from "node:assert/strict";
-import { defineEval } from "eve/evals";
-import { z } from "zod";
-import {
- cancellationRequest,
- resetSessions,
- signOffRequest,
- waitForVerification,
- waitForVerificationStop,
-} from "./fixture.js";
-
-export default defineEval({
- tags: ["real-model"],
- timeoutMs: 240_000,
- description: "Cancelling a local subagent after it yields also cancels its nested worker.",
- async test(t) {
- const key = crypto.randomUUID();
- const sessions: string[] = [];
- try {
- // The caller delegates to local-detector and yields.
- const caller = await t.session();
- sessions.push(caller.sessionId);
- const callerTurn = (
- await caller.send(
- signOffRequest(
- "Hand this off with the local-detector tool, using the note below as its message.",
- key,
- ),
- )
- ).expectOk();
- const delegation = callerTurn.requireToolCall("local-detector", {
- output: { status: "working" },
- });
- const { taskId } = z.object({ taskId: z.string() }).parse(delegation.output);
- callerTurn.notEvent("subagent.completed");
- const callerCompletion = t.target.watchTurn(caller.sessionId, {
- startIndex: caller.state.streamIndex,
- });
- const detectorCall =
- callerTurn.events.find((event) => event.type === "subagent.called") ??
- (await callerCompletion.waitForEvent("subagent.called"));
- assert.equal(detectorCall.data.name, "local-detector");
- sessions.push(detectorCall.data.childSessionId);
-
- // The detector delegates to its worker and also yields.
- const detectorTurn = (
- await t.target.watchTurn(detectorCall.data.childSessionId).result()
- ).expectOk();
- detectorTurn.requireToolCall("verification-worker", { output: { status: "working" } });
- detectorTurn.notEvent("subagent.completed");
- const detectorCompletion = t.target.watchTurn(detectorTurn.sessionId, {
- startIndex: detectorTurn.session.state.streamIndex,
- });
- const workerCall =
- detectorTurn.events.find((event) => event.type === "subagent.called") ??
- (await detectorCompletion.waitForEvent("subagent.called"));
- assert.equal(workerCall.data.name, "verification-worker");
- sessions.push(workerCall.data.childSessionId);
- const workerCompletion = t.target.watchTurn(workerCall.data.childSessionId);
-
- // Both delegation turns have ended, but the worker is still gated.
- await waitForVerification(t, workerCall.data.childSessionId, key);
- const cancellation = (await caller.send(cancellationRequest(taskId))).expectOk();
- cancellation.requireToolCall("task_cancel", {
- input: { taskIds: [taskId] },
- output: { tasks: [{ taskId, status: "cancelled" }] },
- });
-
- // A cancelled outer receipt is insufficient: its worker must actually stop.
- await waitForVerificationStop(t, workerCall.data.childSessionId, key);
- const workerResult = (await workerCompletion.result()).expectOk();
- workerResult.event("turn.cancelled", { count: 1 });
- workerResult.notEvent("turn.failed");
- workerResult.notEvent("session.failed");
- assert.equal(
- detectorCompletion.events.filter((event) => event.type === "turn.started").length,
- 0,
- "cancelling nested work must not wake the cancelled detector",
- );
- t.succeeded();
- } finally {
- await resetSessions(t, sessions);
- }
- },
-});
diff --git a/e2e/fixtures/agent-subagents/evals/nested-background/cancel-remote.eval.ts b/e2e/fixtures/agent-subagents/evals/nested-background/cancel-remote.eval.ts
deleted file mode 100644
index 8328844ae..000000000
--- a/e2e/fixtures/agent-subagents/evals/nested-background/cancel-remote.eval.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import assert from "node:assert/strict";
-import { defineEval } from "eve/evals";
-import { z } from "zod";
-import {
- cancellationRequest,
- resetSessions,
- signOffRequest,
- waitForVerification,
- waitForVerificationStop,
-} from "./fixture.js";
-
-export default defineEval({
- tags: ["real-model"],
- timeoutMs: 240_000,
- description: "Cancelling a remote subagent after it yields also cancels its nested worker.",
- async test(t) {
- const key = crypto.randomUUID();
- const sessions: string[] = [];
- try {
- // The caller delegates to remote-loopback and yields.
- const caller = await t.session();
- sessions.push(caller.sessionId);
- const callerTurn = (
- await caller.send(
- signOffRequest(
- "Hand this off with the remote-loopback tool, using the note below as its message.",
- key,
- ),
- )
- ).expectOk();
- const delegation = callerTurn.requireToolCall("remote-loopback", {
- output: { status: "working" },
- });
- const { taskId } = z.object({ taskId: z.string() }).parse(delegation.output);
- callerTurn.notEvent("subagent.completed");
- const callerCompletion = t.target.watchTurn(caller.sessionId, {
- startIndex: caller.state.streamIndex,
- });
- const detectorCall =
- callerTurn.events.find((event) => event.type === "subagent.called") ??
- (await callerCompletion.waitForEvent("subagent.called"));
- assert.equal(detectorCall.data.name, "remote-loopback");
- assert.ok(detectorCall.data.remote, "detector must use the remote HTTP transport");
- sessions.push(detectorCall.data.childSessionId);
-
- // The detector delegates to its worker and also yields.
- const detectorTurn = (
- await t.target.watchTurn(detectorCall.data.childSessionId).result()
- ).expectOk();
- detectorTurn.requireToolCall("verification-worker", { output: { status: "working" } });
- detectorTurn.notEvent("subagent.completed");
- const detectorCompletion = t.target.watchTurn(detectorTurn.sessionId, {
- startIndex: detectorTurn.session.state.streamIndex,
- });
- const workerCall =
- detectorTurn.events.find((event) => event.type === "subagent.called") ??
- (await detectorCompletion.waitForEvent("subagent.called"));
- assert.equal(workerCall.data.name, "verification-worker");
- sessions.push(workerCall.data.childSessionId);
- const workerCompletion = t.target.watchTurn(workerCall.data.childSessionId);
-
- // Both delegation turns have ended, but the worker is still gated.
- await waitForVerification(t, workerCall.data.childSessionId, key);
- const cancellation = (await caller.send(cancellationRequest(taskId))).expectOk();
- cancellation.requireToolCall("task_cancel", {
- input: { taskIds: [taskId] },
- output: { tasks: [{ taskId, status: "cancelled" }] },
- });
-
- // A cancelled outer receipt is insufficient: its worker must actually stop.
- await waitForVerificationStop(t, workerCall.data.childSessionId, key);
- const workerResult = (await workerCompletion.result()).expectOk();
- workerResult.event("turn.cancelled", { count: 1 });
- workerResult.notEvent("turn.failed");
- workerResult.notEvent("session.failed");
- assert.equal(
- detectorCompletion.events.filter((event) => event.type === "turn.started").length,
- 0,
- "cancelling nested work must not wake the cancelled detector",
- );
- t.succeeded();
- } finally {
- await resetSessions(t, sessions);
- }
- },
-});
diff --git a/e2e/fixtures/agent-subagents/evals/nested-background/cancel-self.eval.ts b/e2e/fixtures/agent-subagents/evals/nested-background/cancel-self.eval.ts
deleted file mode 100644
index 7aa346fad..000000000
--- a/e2e/fixtures/agent-subagents/evals/nested-background/cancel-self.eval.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import assert from "node:assert/strict";
-import { defineEval } from "eve/evals";
-import { z } from "zod";
-import {
- cancellationRequest,
- resetSessions,
- signOffRequest,
- waitForVerification,
- waitForVerificationStop,
-} from "./fixture.js";
-
-export default defineEval({
- tags: ["real-model"],
- timeoutMs: 240_000,
- description: "Cancelling the built-in agent after it yields also cancels its nested worker.",
- async test(t) {
- const key = crypto.randomUUID();
- const sessions: string[] = [];
- try {
- // The caller delegates to agent and yields.
- const caller = await t.session();
- sessions.push(caller.sessionId);
- const callerTurn = (
- await caller.send(
- signOffRequest(
- `Call the tool named "agent" exactly once, with the note below as its message argument.
-Your handoff tool for this request is "agent"; that copy of you will contact verification-worker.`,
- key,
- ),
- )
- ).expectOk();
- const delegation = callerTurn.requireToolCall("agent", { output: { status: "working" } });
- const { taskId } = z.object({ taskId: z.string() }).parse(delegation.output);
- callerTurn.notEvent("subagent.completed");
- const callerCompletion = t.target.watchTurn(caller.sessionId, {
- startIndex: caller.state.streamIndex,
- });
- const detectorCall =
- callerTurn.events.find((event) => event.type === "subagent.called") ??
- (await callerCompletion.waitForEvent("subagent.called"));
- assert.equal(detectorCall.data.name, "agent");
- sessions.push(detectorCall.data.childSessionId);
-
- // The detector delegates to its worker and also yields.
- const detectorTurn = (
- await t.target.watchTurn(detectorCall.data.childSessionId).result()
- ).expectOk();
- detectorTurn.requireToolCall("verification-worker", { output: { status: "working" } });
- detectorTurn.notEvent("subagent.completed");
- const detectorCompletion = t.target.watchTurn(detectorTurn.sessionId, {
- startIndex: detectorTurn.session.state.streamIndex,
- });
- const workerCall =
- detectorTurn.events.find((event) => event.type === "subagent.called") ??
- (await detectorCompletion.waitForEvent("subagent.called"));
- assert.equal(workerCall.data.name, "verification-worker");
- sessions.push(workerCall.data.childSessionId);
- const workerCompletion = t.target.watchTurn(workerCall.data.childSessionId);
-
- // Both delegation turns have ended, but the worker is still gated.
- await waitForVerification(t, workerCall.data.childSessionId, key);
- const cancellation = (await caller.send(cancellationRequest(taskId))).expectOk();
- cancellation.requireToolCall("task_cancel", {
- input: { taskIds: [taskId] },
- output: { tasks: [{ taskId, status: "cancelled" }] },
- });
-
- // A cancelled outer receipt is insufficient: its worker must actually stop.
- await waitForVerificationStop(t, workerCall.data.childSessionId, key);
- const workerResult = (await workerCompletion.result()).expectOk();
- workerResult.event("turn.cancelled", { count: 1 });
- workerResult.notEvent("turn.failed");
- workerResult.notEvent("session.failed");
- assert.equal(
- detectorCompletion.events.filter((event) => event.type === "turn.started").length,
- 0,
- "cancelling nested work must not wake the cancelled detector",
- );
- t.succeeded();
- } finally {
- await resetSessions(t, sessions);
- }
- },
-});
diff --git a/e2e/fixtures/agent-subagents/evals/nested-background/fixture.ts b/e2e/fixtures/agent-subagents/evals/nested-background/fixture.ts
deleted file mode 100644
index 2402f6b20..000000000
--- a/e2e/fixtures/agent-subagents/evals/nested-background/fixture.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import assert from "node:assert/strict";
-import { setTimeout } from "node:timers/promises";
-import type { EveEvalContext } from "eve/evals";
-import { z } from "zod";
-
-/**
- * Builds the caller prompt for a two-level delegation. `handoff` names the
- * caller's delegation tool; the note is forwarded unchanged to the delegate,
- * which hands it to verification-worker.
- */
-export function signOffRequest(handoff: string, key: string) {
- return `Alice is putting together her weekly project status update and needs the release checklist sign-off for it.
-${handoff}
-Once the handoff is accepted, let Alice know the sign-off is in progress and end your turn.
-When the handoff finishes, give Alice the sign-off code it returns.
-
-Note for the handoff:
-Please ask verification-worker to collect the release checklist sign-off by calling verification_gate with key ${key}.
-Once verification-worker has started, reply that the sign-off is in progress and end your turn.
-When verification-worker finishes, reply with the sign-off code it returned.`;
-}
-
-export function cancellationRequest(taskId: string) {
- return `Alice collected the checklist sign-off herself, so the handoff is no longer needed. Call task_cancel with taskIds ["${taskId}"] to stop it, then let Alice know it was cancelled.`;
-}
-
-export async function waitForVerification(t: EveEvalContext, workerId: string, key: string) {
- const response = await t.target.fetch(`/test/verification/${workerId}/${key}/ready`, {
- method: "POST",
- signal: t.signal,
- });
- assert.equal(response.status, 200);
- assert.deepEqual(await response.json(), { status: "running" });
-}
-
-export async function releaseVerification(t: EveEvalContext, workerId: string, key: string) {
- const response = await t.target.fetch(`/test/verification/${workerId}/${key}/release`, {
- method: "POST",
- signal: t.signal,
- });
- assert.equal(response.status, 200);
- const { released, result } = await response.json();
- assert.equal(released, true);
- return z.uuid().parse(result);
-}
-
-export async function waitForVerificationStop(t: EveEvalContext, workerId: string, key: string) {
- const deadline = Date.now() + 45_000;
- let status: unknown;
- do {
- const response = await t.target.fetch(`/test/verification/${workerId}/${key}/status`, {
- method: "POST",
- signal: AbortSignal.any([t.signal, AbortSignal.timeout(5_000)]),
- });
- assert.equal(response.status, 200);
- ({ status } = await response.json());
- if (status !== "running" && status !== "pending") break;
- await setTimeout(250, undefined, { signal: t.signal });
- } while (Date.now() < deadline);
- // Cooperative cancellation returns normally from the workflow wrapper. The
- // worker's turn.cancelled event distinguishes cancellation from normal success.
- assert.ok(
- status === "completed" || status === "cancelled",
- `the nested verification workflow must stop before cleanup; got ${String(status)}`,
- );
-}
-
-export async function resetSessions(t: EveEvalContext, sessionIds: readonly string[]) {
- await Promise.allSettled(
- sessionIds.map(async (sessionId) => {
- const response = await t.target.fetch(`/eve/v1/session/${sessionId}/reset`, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ reason: "Nested verification eval cleanup" }),
- // Cleanup must still run when the eval's own signal has expired.
- signal: AbortSignal.timeout(5_000),
- });
- await response.body?.cancel();
- }),
- );
-}
diff --git a/e2e/fixtures/agent-subagents/evals/nested-background/local.eval.ts b/e2e/fixtures/agent-subagents/evals/nested-background/local.eval.ts
deleted file mode 100644
index ea388fb86..000000000
--- a/e2e/fixtures/agent-subagents/evals/nested-background/local.eval.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import assert from "node:assert/strict";
-import { defineEval } from "eve/evals";
-import { equals } from "eve/evals/expect";
-import {
- releaseVerification,
- resetSessions,
- signOffRequest,
- waitForVerification,
-} from "./fixture.js";
-
-export default defineEval({
- tags: ["real-model"],
- timeoutMs: 240_000,
- description:
- "A local subagent yields with nested work pending and delivers the final result once.",
- async test(t) {
- const key = crypto.randomUUID();
- const sessions: string[] = [];
- try {
- // The caller delegates to local-detector and yields.
- const caller = await t.session();
- sessions.push(caller.sessionId);
- const callerTurn = (
- await caller.send(
- signOffRequest(
- "Hand this off with the local-detector tool, using the note below as its message.",
- key,
- ),
- )
- ).expectOk();
- callerTurn.requireToolCall("local-detector", { output: { status: "working" } });
- callerTurn.notEvent("subagent.completed");
- const callerCompletion = t.target.watchTurn(caller.sessionId, {
- startIndex: caller.state.streamIndex,
- });
- const detectorCall =
- callerTurn.events.find((event) => event.type === "subagent.called") ??
- (await callerCompletion.waitForEvent("subagent.called"));
- assert.equal(detectorCall.data.name, "local-detector");
- sessions.push(detectorCall.data.childSessionId);
-
- // The detector delegates to its worker and also yields.
- const detectorTurn = (
- await t.target.watchTurn(detectorCall.data.childSessionId).result()
- ).expectOk();
- detectorTurn.requireToolCall("verification-worker", { output: { status: "working" } });
- detectorTurn.notEvent("subagent.completed");
- const detectorCompletion = t.target.watchTurn(detectorTurn.sessionId, {
- startIndex: detectorTurn.session.state.streamIndex,
- });
- const workerCall =
- detectorTurn.events.find((event) => event.type === "subagent.called") ??
- (await detectorCompletion.waitForEvent("subagent.called"));
- assert.equal(workerCall.data.name, "verification-worker");
- sessions.push(workerCall.data.childSessionId);
- const workerCompletion = t.target.watchTurn(workerCall.data.childSessionId);
-
- // Neither yielded turn may complete the caller's task while the worker is gated.
- await waitForVerification(t, workerCall.data.childSessionId, key);
- t.check(
- callerCompletion.events.filter((event) => event.type === "subagent.completed").length,
- equals(0),
- ).label("no completion before verification finishes");
-
- // The receipt is created on release, so no model can obtain it from the prompt.
- const receipt = await releaseVerification(t, workerCall.data.childSessionId, key);
- const workerResult = (await workerCompletion.result()).expectOk();
- workerResult.calledTool("verification_gate", {
- input: { key },
- output: receipt,
- status: "completed",
- count: 1,
- });
- workerResult.messageIncludes(receipt);
- const detectorResult = (await detectorCompletion.result()).expectOk();
- detectorResult.event("subagent.completed", {
- data: { subagentName: "verification-worker", output: (output) => output.includes(receipt) },
- count: 1,
- });
- detectorResult.messageIncludes(receipt);
- const callerResult = (await callerCompletion.result()).expectOk();
- callerResult.event("subagent.completed", { count: 1 });
- callerResult.event("subagent.completed", {
- data: { subagentName: "local-detector", output: (output) => output.includes(receipt) },
- count: 1,
- });
- callerResult.messageIncludes(receipt);
- t.noFailedActions();
- t.succeeded();
- } finally {
- await resetSessions(t, sessions);
- }
- },
-});
diff --git a/e2e/fixtures/agent-subagents/evals/nested-background/remote.eval.ts b/e2e/fixtures/agent-subagents/evals/nested-background/remote.eval.ts
deleted file mode 100644
index d6baade3f..000000000
--- a/e2e/fixtures/agent-subagents/evals/nested-background/remote.eval.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import assert from "node:assert/strict";
-import { defineEval } from "eve/evals";
-import { equals } from "eve/evals/expect";
-import {
- releaseVerification,
- resetSessions,
- signOffRequest,
- waitForVerification,
-} from "./fixture.js";
-
-export default defineEval({
- tags: ["real-model"],
- timeoutMs: 240_000,
- description:
- "A remote subagent yields with nested work pending and delivers the final result once.",
- async test(t) {
- const key = crypto.randomUUID();
- const sessions: string[] = [];
- try {
- // The caller delegates to remote-loopback and yields.
- const caller = await t.session();
- sessions.push(caller.sessionId);
- const callerTurn = (
- await caller.send(
- signOffRequest(
- "Hand this off with the remote-loopback tool, using the note below as its message.",
- key,
- ),
- )
- ).expectOk();
- callerTurn.requireToolCall("remote-loopback", { output: { status: "working" } });
- callerTurn.notEvent("subagent.completed");
- const callerCompletion = t.target.watchTurn(caller.sessionId, {
- startIndex: caller.state.streamIndex,
- });
- const detectorCall =
- callerTurn.events.find((event) => event.type === "subagent.called") ??
- (await callerCompletion.waitForEvent("subagent.called"));
- assert.equal(detectorCall.data.name, "remote-loopback");
- assert.ok(detectorCall.data.remote, "detector must use the remote HTTP transport");
- sessions.push(detectorCall.data.childSessionId);
-
- // The detector delegates to its worker and also yields.
- const detectorTurn = (
- await t.target.watchTurn(detectorCall.data.childSessionId).result()
- ).expectOk();
- detectorTurn.requireToolCall("verification-worker", { output: { status: "working" } });
- detectorTurn.notEvent("subagent.completed");
- const detectorCompletion = t.target.watchTurn(detectorTurn.sessionId, {
- startIndex: detectorTurn.session.state.streamIndex,
- });
- const workerCall =
- detectorTurn.events.find((event) => event.type === "subagent.called") ??
- (await detectorCompletion.waitForEvent("subagent.called"));
- assert.equal(workerCall.data.name, "verification-worker");
- sessions.push(workerCall.data.childSessionId);
- const workerCompletion = t.target.watchTurn(workerCall.data.childSessionId);
-
- // Neither yielded turn may complete the caller's task while the worker is gated.
- await waitForVerification(t, workerCall.data.childSessionId, key);
- t.check(
- callerCompletion.events.filter((event) => event.type === "subagent.completed").length,
- equals(0),
- ).label("no completion before verification finishes");
-
- // The receipt is created on release, so no model can obtain it from the prompt.
- const receipt = await releaseVerification(t, workerCall.data.childSessionId, key);
- const workerResult = (await workerCompletion.result()).expectOk();
- workerResult.calledTool("verification_gate", {
- input: { key },
- output: receipt,
- status: "completed",
- count: 1,
- });
- workerResult.messageIncludes(receipt);
- const detectorResult = (await detectorCompletion.result()).expectOk();
- detectorResult.event("subagent.completed", {
- data: { subagentName: "verification-worker", output: (output) => output.includes(receipt) },
- count: 1,
- });
- detectorResult.messageIncludes(receipt);
- const callerResult = (await callerCompletion.result()).expectOk();
- callerResult.event("subagent.completed", { count: 1 });
- callerResult.event("subagent.completed", {
- data: { subagentName: "remote-loopback", output: (output) => output.includes(receipt) },
- count: 1,
- });
- callerResult.messageIncludes(receipt);
- t.noFailedActions();
- t.succeeded();
- } finally {
- await resetSessions(t, sessions);
- }
- },
-});
diff --git a/e2e/fixtures/agent-subagents/evals/nested-background/self.eval.ts b/e2e/fixtures/agent-subagents/evals/nested-background/self.eval.ts
deleted file mode 100644
index 902b38de9..000000000
--- a/e2e/fixtures/agent-subagents/evals/nested-background/self.eval.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import assert from "node:assert/strict";
-import { defineEval } from "eve/evals";
-import { equals } from "eve/evals/expect";
-import {
- releaseVerification,
- resetSessions,
- signOffRequest,
- waitForVerification,
-} from "./fixture.js";
-
-export default defineEval({
- tags: ["real-model"],
- timeoutMs: 240_000,
- description:
- "The built-in agent yields with nested work pending and delivers the final result once.",
- async test(t) {
- const key = crypto.randomUUID();
- const sessions: string[] = [];
- try {
- // The caller delegates to agent and yields.
- const caller = await t.session();
- sessions.push(caller.sessionId);
- const callerTurn = (
- await caller.send(
- signOffRequest(
- `Call the tool named "agent" exactly once, with the note below as its message argument.
-Your handoff tool for this request is "agent"; that copy of you will contact verification-worker.`,
- key,
- ),
- )
- ).expectOk();
- callerTurn.requireToolCall("agent", { output: { status: "working" } });
- callerTurn.notEvent("subagent.completed");
- const callerCompletion = t.target.watchTurn(caller.sessionId, {
- startIndex: caller.state.streamIndex,
- });
- const detectorCall =
- callerTurn.events.find((event) => event.type === "subagent.called") ??
- (await callerCompletion.waitForEvent("subagent.called"));
- assert.equal(detectorCall.data.name, "agent");
- sessions.push(detectorCall.data.childSessionId);
-
- // The detector delegates to its worker and also yields.
- const detectorTurn = (
- await t.target.watchTurn(detectorCall.data.childSessionId).result()
- ).expectOk();
- detectorTurn.requireToolCall("verification-worker", { output: { status: "working" } });
- detectorTurn.notEvent("subagent.completed");
- const detectorCompletion = t.target.watchTurn(detectorTurn.sessionId, {
- startIndex: detectorTurn.session.state.streamIndex,
- });
- const workerCall =
- detectorTurn.events.find((event) => event.type === "subagent.called") ??
- (await detectorCompletion.waitForEvent("subagent.called"));
- assert.equal(workerCall.data.name, "verification-worker");
- sessions.push(workerCall.data.childSessionId);
- const workerCompletion = t.target.watchTurn(workerCall.data.childSessionId);
-
- // Neither yielded turn may complete the caller's task while the worker is gated.
- await waitForVerification(t, workerCall.data.childSessionId, key);
- t.check(
- callerCompletion.events.filter((event) => event.type === "subagent.completed").length,
- equals(0),
- ).label("no completion before verification finishes");
-
- // The receipt is created on release, so no model can obtain it from the prompt.
- const receipt = await releaseVerification(t, workerCall.data.childSessionId, key);
- const workerResult = (await workerCompletion.result()).expectOk();
- workerResult.calledTool("verification_gate", {
- input: { key },
- output: receipt,
- status: "completed",
- count: 1,
- });
- workerResult.messageIncludes(receipt);
- const detectorResult = (await detectorCompletion.result()).expectOk();
- detectorResult.event("subagent.completed", {
- data: { subagentName: "verification-worker", output: (output) => output.includes(receipt) },
- count: 1,
- });
- detectorResult.messageIncludes(receipt);
- const callerResult = (await callerCompletion.result()).expectOk();
- callerResult.event("subagent.completed", { count: 1 });
- callerResult.event("subagent.completed", {
- data: { subagentName: "agent", output: (output) => output.includes(receipt) },
- count: 1,
- });
- callerResult.messageIncludes(receipt);
- t.noFailedActions();
- t.succeeded();
- } finally {
- await resetSessions(t, sessions);
- }
- },
-});
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 ae156bdfb..856333bf1 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) {
- const started = await t.send(
+ const completed = await t.send(
[
"Use the built-in agent subagent exactly once.",
"Give the child this task:",
@@ -16,11 +16,6 @@ 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(started.session) })
- .result();
completed.expectOk();
completed.messageIncludes(CHILD_TOKEN);
@@ -29,11 +24,3 @@ export default defineEval({
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/scheduled-remote-completion.eval.ts b/e2e/fixtures/agent-subagents/evals/scheduled-remote-completion.eval.ts
deleted file mode 100644
index 66de3d915..000000000
--- a/e2e/fixtures/agent-subagents/evals/scheduled-remote-completion.eval.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import { defineEval } from "eve/evals";
-import { equals, satisfies } from "eve/evals/expect";
-
-const FINAL = "SCHEDULED-REMOTE-FINAL SCHEDULED-REMOTE-CHILD-RESULT";
-const PREMATURE =
- "Weekly report could not be completed before delivery because the analytics query did not return a result.";
-
-/**
- * The schedule creates a root session, so no TurnCaller exists. This E2E observes
- * that boundary through the channel stream; TurnCaller absence itself has no event.
- */
-export default defineEval({
- description:
- "A scheduled root suppresses its nonempty remote-agent launch fallback and delivers the late result exactly once.",
- async test(t) {
- if (!t.target.capabilities.devRoutes) {
- t.skip("Target has no dev routes; schedule dispatch is dev-only.");
- }
-
- // Scheduled root dispatch: the schedule, not an inbound turn, creates the session.
- const dispatch = await t.target.dispatchSchedule("scheduled-remote");
- await t.require(dispatch.scheduleId, equals("scheduled-remote"));
- await t.require(
- dispatch.sessionIds,
- satisfies((ids: readonly string[]) => ids.length > 0, "schedule started a root session"),
- );
- const sessionId = dispatch.sessionIds[0]!;
-
- // Initiating turn: withhold the deliberate nonempty premature fallback from
- // both the event stream and the channel.
- const launch = await t.target.attachSession(sessionId);
- launch.succeeded();
- launch.calledTool("remote-loopback", { output: { status: "working" }, count: 1 });
- launch.notEvent("subagent.completed");
- launch.event("message.completed", {
- data: (data) => data.finishReason !== "tool-calls" && data.message === null,
- count: 1,
- });
- launch.notEvent("message.completed", {
- data: (data) => data.finishReason !== "tool-calls" && data.message !== null,
- });
- await t.require(
- launch.events,
- satisfies(
- (events: typeof launch.events) => !JSON.stringify(events).includes(PREMATURE),
- "the adapter and channel suppress the premature fallback",
- ),
- );
-
- // Agent receives background task result after turn ended.
- if (launch.state === undefined) throw new Error("scheduled launch has no stream cursor");
- const completedLive = t.target.watchTurn(sessionId, {
- startIndex: launch.state.streamIndex,
- });
- const completed = await completedLive.result();
- completed.expectOk();
- completed.messageIncludes(FINAL);
- completed.event("subagent.completed", {
- data: { subagentName: "remote-loopback" },
- count: 1,
- });
- await t.require(
- completed.events,
- satisfies(
- (events: typeof completed.events) =>
- events.some(
- (event) =>
- event.type === "message.received" &&
- messageText(event.data.message).includes("is completed") &&
- messageText(event.data.message).includes("SCHEDULED-REMOTE-CHILD-RESULT"),
- ),
- "the final reply follows the late remote-agent result",
- ),
- );
- completed.event("message.completed", {
- data: (data) =>
- data.finishReason !== "tool-calls" &&
- data.message !== null &&
- JSON.stringify(data.message).includes(FINAL),
- count: 1,
- });
-
- // Replay both durable turns. The fallback never becomes assistant output,
- // while the late remote result does exactly once.
- const replayedLaunch = await t.target.attachSession(sessionId);
- if (replayedLaunch.state === undefined) throw new Error("replayed launch has no stream cursor");
- const replayedCompletion = await t.target
- .watchTurn(sessionId, { startIndex: replayedLaunch.state.streamIndex })
- .result();
- const replayedEvents = [...replayedLaunch.events, ...replayedCompletion.events];
- await t.require(
- replayedEvents,
- satisfies(
- (events: typeof replayedEvents) =>
- !JSON.stringify(events).includes(PREMATURE) &&
- events.filter(
- (event) =>
- event.type === "message.completed" &&
- event.data.message !== null &&
- JSON.stringify(event.data.message).includes(FINAL),
- ).length === 1,
- "replay retains one final remote result and no premature fallback",
- ),
- );
-
- // Across both turns, assert exactly one final non-null delivery crosses the channel boundary.
- const allEvents = [...launch.events, ...completed.events];
- await t.require(
- allEvents,
- satisfies(
- (events: typeof allEvents) =>
- events.filter(
- (event) =>
- event.type === "message.completed" &&
- event.data.finishReason !== "tool-calls" &&
- event.data.message !== null,
- ).length === 1,
- "exactly one final non-null reply crosses the channel boundary",
- ),
- );
- t.noFailedActions();
- t.succeeded();
- },
-});
-
-function messageText(message: unknown): string {
- if (typeof message === "string") return message;
- if (!Array.isArray(message)) return "";
- return message
- .flatMap((part) =>
- part !== null &&
- typeof part === "object" &&
- Reflect.get(part, "type") === "text" &&
- typeof Reflect.get(part, "text") === "string"
- ? [Reflect.get(part, "text") as string]
- : [],
- )
- .join("\n");
-}
diff --git a/e2e/fixtures/agent-subagents/evals/self-modification/add-capability.eval.ts b/e2e/fixtures/agent-subagents/evals/self-modification/add-capability.eval.ts
index fa1e5434d..f6d333f6f 100644
--- a/e2e/fixtures/agent-subagents/evals/self-modification/add-capability.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/self-modification/add-capability.eval.ts
@@ -8,6 +8,6 @@ export default defineEval({
started.expectOk();
t.succeeded();
- t.calledSubagent("self-modification", { status: "working" });
+ t.calledSubagent("self-modification");
},
});
diff --git a/e2e/fixtures/agent-subagents/evals/self-modification/add-reusable-action.eval.ts b/e2e/fixtures/agent-subagents/evals/self-modification/add-reusable-action.eval.ts
index bd18c0c87..67b81296b 100644
--- a/e2e/fixtures/agent-subagents/evals/self-modification/add-reusable-action.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/self-modification/add-reusable-action.eval.ts
@@ -10,6 +10,6 @@ export default defineEval({
started.expectOk();
t.succeeded();
- t.calledSubagent("self-modification", { status: "working" });
+ t.calledSubagent("self-modification");
},
});
diff --git a/e2e/fixtures/agent-subagents/evals/self-modification/connect-capability.eval.ts b/e2e/fixtures/agent-subagents/evals/self-modification/connect-capability.eval.ts
index 68fbe478c..3062825b0 100644
--- a/e2e/fixtures/agent-subagents/evals/self-modification/connect-capability.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/self-modification/connect-capability.eval.ts
@@ -8,6 +8,6 @@ export default defineEval({
started.expectOk();
t.succeeded();
- t.calledSubagent("self-modification", { status: "working" });
+ t.calledSubagent("self-modification");
},
});
diff --git a/e2e/fixtures/agent-subagents/evals/self-modification/enable-capability.eval.ts b/e2e/fixtures/agent-subagents/evals/self-modification/enable-capability.eval.ts
index 65e24808e..5cc9ccfd1 100644
--- a/e2e/fixtures/agent-subagents/evals/self-modification/enable-capability.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/self-modification/enable-capability.eval.ts
@@ -8,6 +8,6 @@ export default defineEval({
started.expectOk();
t.succeeded();
- t.calledSubagent("self-modification", { status: "working" });
+ t.calledSubagent("self-modification");
},
});
diff --git a/e2e/fixtures/agent-subagents/evals/self-modification/install-capability.eval.ts b/e2e/fixtures/agent-subagents/evals/self-modification/install-capability.eval.ts
index 693f11309..09dcf6f8a 100644
--- a/e2e/fixtures/agent-subagents/evals/self-modification/install-capability.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/self-modification/install-capability.eval.ts
@@ -9,6 +9,6 @@ export default defineEval({
started.expectOk();
t.succeeded();
- t.calledSubagent("self-modification", { status: "working" });
+ t.calledSubagent("self-modification");
},
});
diff --git a/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts
index 1ab173f7f..5874e0fb1 100644
--- a/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts
@@ -33,13 +33,13 @@ export default defineEval({
count: 1,
output: (observed) => isDeepStrictEqual(observed, expected),
});
- t.calledSubagent(TRIAGE, { count: 1, status: "completed" });
- t.calledSubagent(REVIEW, { count: 1, status: "completed" });
- t.calledSubagent(REPRODUCE, { count: 1, status: "completed" });
+ t.event("agent.started", { count: 1, data: { name: TRIAGE } });
+ t.event("agent.started", { count: 1, data: { name: REVIEW } });
+ t.event("agent.started", { count: 1, data: { name: REPRODUCE } });
turn.eventsSatisfy("analysis fans out before reproduction consumes both results", (events) => {
const called = new Map<string, number>();
for (const [index, event] of events.entries()) {
- if (event.type === "subagent.called" && !called.has(event.data.name)) {
+ if (event.type === "agent.started" && !called.has(event.data.name)) {
called.set(event.data.name, index);
}
}
diff --git a/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.ts b/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.ts
deleted file mode 100644
index 637f8ed97..000000000
--- a/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { defineEval } from "eve/evals";
-
-/** Generated workflow-program calls block, continue one child, and share one call budget. */
-export default defineEval({
- tags: ["real-model"],
- description:
- "Generated workflow-program 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 ctx.agent for 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: started.session.state.streamIndex,
- });
- const completed = firstTurn === undefined ? started : await firstTurn.result();
- completed.expectOk();
- completed.messageIncludes("SUBAGENT_TOKEN=echo-marker-9F2X");
-
- const second = await completed.session.send(
- [
- "Use the workflow tool exactly once. In its JavaScript, call the same echo-marker child three times sequentially with ctx.agent",
- "using the agentId shown in the latest <agents> block, with messages 'blocking second', 'blocking third', and 'blocking fourth'.",
- "Then attempt a fourth call with that agentId and message 'blocking over limit'.",
- "Catch the fourth call's error, return all three inline results followed by its message, and reply with that four-element array 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: 4, status: "completed" });
- t.eventsSatisfy("all workflow-program 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 === 4 &&
- childSessionIds[0] !== undefined &&
- childSessionIds.every((sessionId) => sessionId === childSessionIds[0])
- );
- });
- t.messageIncludes("SUBAGENT_TOKEN=echo-marker-9F2X");
- t.messageIncludes("WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED");
- },
-});
diff --git a/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts b/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts
index b4b3d63c7..5b260ab07 100644
--- a/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts
@@ -51,7 +51,7 @@ export default defineEval({
input: isFourCallProgram,
output: isFourElementLimitResult,
});
- t.calledSubagent("echo-marker", { count: 3, status: "completed" });
+ t.event("agent.started", { count: 3, data: { name: "echo-marker" } });
t.messageIncludes("WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED");
},
});
diff --git a/e2e/fixtures/agent-task-reporting/agent/agent.ts b/e2e/fixtures/agent-task-reporting/agent/agent.ts
deleted file mode 100644
index 2e553dc24..000000000
--- a/e2e/fixtures/agent-task-reporting/agent/agent.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { e2eAgentConfig } from "@eve-e2e/config";
-import { defineAgent } from "eve";
-
-export default defineAgent(e2eAgentConfig());
diff --git a/e2e/fixtures/agent-task-reporting/agent/instructions.md b/e2e/fixtures/agent-task-reporting/agent/instructions.md
deleted file mode 100644
index 32f06789d..000000000
--- a/e2e/fixtures/agent-task-reporting/agent/instructions.md
+++ /dev/null
@@ -1,17 +0,0 @@
-You help Alice and Bob prepare an inventory checklist.
-
-When coordinating the full checklist, use the built-in `agent` tool to assign
-each entry to a separate background assistant. All three entries use `agent`,
-including the third entry. The coordinator collects their results rather than
-performing the lookups itself.
-
-When you receive an assignment for one entry, handle that entry only. For
-`check=first` or `check=second`, use `probe`. For `check=third`, use
-`warehouse_lookup`; that workflow contacts `warehouse-worker` and returns its
-answer. The specialist is a nested part of the third assistant's work, not a
-replacement for that assistant.
-
-Keep assignments brief and process-oriented, including the check reference and
-lookup tool. Return the item from the lookup. Use the three returned items for
-the coordinator's final checklist, and answer separate user questions normally
-while the lookups are pending.
diff --git a/e2e/fixtures/agent-task-reporting/agent/sandbox.ts b/e2e/fixtures/agent-task-reporting/agent/sandbox.ts
deleted file mode 100644
index 329ae8886..000000000
--- a/e2e/fixtures/agent-task-reporting/agent/sandbox.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { defineSandbox } from "eve/sandbox";
-import { JustBashSandbox } from "eve/sandbox/just-bash";
-
-export const environment = JustBashSandbox.environment({
- filesystem: ({ justBash }) => new justBash.InMemoryFs(),
-});
-
-export default defineSandbox(() => environment.open());
diff --git a/e2e/fixtures/agent-task-reporting/agent/subagents/warehouse-worker/agent.ts b/e2e/fixtures/agent-task-reporting/agent/subagents/warehouse-worker/agent.ts
deleted file mode 100644
index 344de53a2..000000000
--- a/e2e/fixtures/agent-task-reporting/agent/subagents/warehouse-worker/agent.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { e2eSubagentConfig } from "@eve-e2e/config";
-import { defineAgent } from "eve";
-
-export default defineAgent({
- ...e2eSubagentConfig(),
- description:
- "Nested specialist contacted by warehouse_lookup to find the third entry's inventory item. The checklist coordinator assigns all entries through agent instead.",
-});
diff --git a/e2e/fixtures/agent-task-reporting/agent/subagents/warehouse-worker/tools/probe.ts b/e2e/fixtures/agent-task-reporting/agent/subagents/warehouse-worker/tools/probe.ts
deleted file mode 100644
index 819cb200d..000000000
--- a/e2e/fixtures/agent-task-reporting/agent/subagents/warehouse-worker/tools/probe.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "../../../tools/probe.js";
diff --git a/e2e/fixtures/agent-task-reporting/agent/tools/probe.ts b/e2e/fixtures/agent-task-reporting/agent/tools/probe.ts
deleted file mode 100644
index 6a1a64785..000000000
--- a/e2e/fixtures/agent-task-reporting/agent/tools/probe.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { defineTool } from "eve/tools";
-import { once } from "eve/tools/approval";
-import { z } from "zod";
-
-const PROBES = { first: "oranges", second: "pears", third: "apples" } as const;
-
-export default defineTool({
- description: "Look up the warehouse inventory item for a checklist entry.",
- inputSchema: z.strictObject({
- check: z.enum(["first", "second", "third"]),
- }),
- approval: once(),
- execute: ({ check }) => ({ result: PROBES[check] }),
-});
diff --git a/e2e/fixtures/agent-task-reporting/agent/tools/warehouse_lookup.ts b/e2e/fixtures/agent-task-reporting/agent/tools/warehouse_lookup.ts
deleted file mode 100644
index 79c190caa..000000000
--- a/e2e/fixtures/agent-task-reporting/agent/tools/warehouse_lookup.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { defineWorkflowTool } from "eve/tools";
-import { z } from "zod";
-
-export default defineWorkflowTool({
- description: "Ask the warehouse specialist for the third inventory item and wait for its result.",
- inputSchema: z.strictObject({ check: z.literal("third") }),
- async execute({ check }, ctx) {
- "use workflow";
- // Blocking delegation keeps the outer task open until the nested lookup finishes.
- return await ctx.agent("warehouse-worker", {
- message: `Alice is preparing an inventory checklist for Bob's warehouse handoff. Your entry is check=${check}. Please use the inventory lookup tool (probe) for this entry and share the item it returns.`,
- });
- },
-});
diff --git a/e2e/fixtures/agent-task-reporting/evals/README.md b/e2e/fixtures/agent-task-reporting/evals/README.md
deleted file mode 100644
index 094c454a5..000000000
--- a/e2e/fixtures/agent-task-reporting/evals/README.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# Background task reporting
-
-This fixture checks the full-cohort completion barrier with real models. Both
-retained evals carry `real-model`, so world suites exclude them. The root agent,
-its built-in agent copies, and the declared warehouse worker all resolve the CI
-model through `@eve-e2e/config`; the fixture retains its full model matrix.
-
-Alice is preparing an inventory checklist for Bob's warehouse handoff. Each trial
-launches exactly three independent warehouse tasks in one root turn, acknowledges
-the accepted assignments, and collects the results into one report for Bob.
-The test-only tool keeps its `probe` filename, but its model-facing description
-presents an inventory lookup without asking the model to arrange approval. Its
-`approval: once()` policy requires a runtime approval in each lookup session instead
-of delaying execution with a timer or relying on an `ask_question` exchange. The eval
-waits for all three approval requests, approves the first, and reads that child's
-completed result from its own session stream. The other two requests remain
-unapproved during the partial-state checks.
-
-The third child uses the blocking `warehouse_lookup` workflow tool to invoke a
-nested `warehouse-worker`. Blocking delegation keeps the outer task open until
-the nested lookup returns, rather than completing it with a background launch
-acknowledgement. Its approval is answered through the root session. The eval
-checks the nested session identity, real model selection, probe call, and completion
-before the outer child's result.
-
-`pending-response.eval.ts` retains 20 trials. After the first child completes,
-Alice asks an unrelated arithmetic question. The parent must answer before the
-last child completes, without consuming any held completion notifications. Server
-event timestamps and the unreleased approvals establish the partial-state window.
-Only that user answer and one final cohort report may invoke the parent model
-after setup.
-
-`consolidated-report.eval.ts` retains eight trials. It requests compaction in the
-same gated partial state, then releases the remaining lookups. Whether compaction
-produces a checkpoint or declines to summarize, the parent must retain the cohort
-and report every result. No ordinary parent model step may run before settlement.
-Successful checkpoint production remains a separately recorded soft assertion.
-
-Both drivers submit approval responses without awaiting a parent model turn.
-They retain the parent stream cursor from before the releases and inspect every
-subsequent boundary, so an intermediate model step fails even if it emits no text.
-The final notification must contain every original task ID exactly once, with no
-unknown IDs, and the single report must contain all three distinct inventory items.
-There are no prompt-ablation variants, inference delays, or mock silence responders.
-
-E2E execution is CI-only. Focused static checking uses
-`pnpm --filter agent-task-reporting exec tsc --noEmit`.
diff --git a/e2e/fixtures/agent-task-reporting/evals/consolidated-report.eval.ts b/e2e/fixtures/agent-task-reporting/evals/consolidated-report.eval.ts
deleted file mode 100644
index d655556da..000000000
--- a/e2e/fixtures/agent-task-reporting/evals/consolidated-report.eval.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { defineEval } from "eve/evals";
-import { equals } from "eve/evals/expect";
-
-import {
- compactWhilePending,
- modelSteps,
- startWarehouseLookups,
- waitForPartialCompletion,
- waitForReport,
-} from "./reporting.js";
-
-function reportingEval() {
- return defineEval({
- description:
- "A real parent retains a completed child's result across compaction while its siblings are gated, then reports the whole cohort including a nested lookup.",
- tags: ["real-model"],
- async test(t) {
- const run = await startWarehouseLookups(t);
- await waitForPartialCompletion(t, run);
- await compactWhilePending(t, run);
- await waitForReport(t, run);
- t.check(modelSteps(run.parentTurns), equals(1)).label(
- "compaction does not admit partial successes; only the settled cohort invokes the parent model",
- );
- t.noFailedActions();
- },
- });
-}
-
-export default Array.from({ length: 8 }, reportingEval);
diff --git a/e2e/fixtures/agent-task-reporting/evals/evals.config.ts b/e2e/fixtures/agent-task-reporting/evals/evals.config.ts
deleted file mode 100644
index e6f07e550..000000000
--- a/e2e/fixtures/agent-task-reporting/evals/evals.config.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { defineEvalConfig } from "eve/evals";
-
-export default defineEvalConfig({
- maxConcurrency: 4,
- timeoutMs: 180_000,
-});
diff --git a/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjs b/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjs
deleted file mode 100644
index cb16745b3..000000000
--- a/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjs
+++ /dev/null
@@ -1,319 +0,0 @@
-import assert from "node:assert/strict";
-import { test } from "node:test";
-
-import {
- childActivations,
- checkForTask,
- completedTaskIds,
- eventsForSession,
- modelStepCount,
- requireOriginalTasksHealthy,
- toolEvidence,
-} from "./event-matching.ts";
-
-function event(id, type, data) {
- return { meta: { id, at: "2026-09-11T00:00:00.000Z" }, type, data };
-}
-
-function approval(taskId, check, callId = "probe-call") {
- return {
- requestId: `${taskId}:approval-id`,
- kind: "tool-approval",
- action: { kind: "tool-call", toolName: "probe", callId, input: { check } },
- };
-}
-
-function requested(id, callId = "probe-call", check = "first") {
- return event(id, "actions.requested", {
- actions: [{ kind: "tool-call", toolName: "probe", callId, input: { check } }],
- turnId: "turn_0",
- });
-}
-
-function completed(
- id,
- callId = "probe-call",
- status = "completed",
- output = { result: "oranges" },
-) {
- return event(id, "action.result", {
- result: { kind: "tool-result", toolName: "probe", callId, output },
- status,
- turnId: "turn_1",
- });
-}
-
-const expected = [
- {
- callId: "probe-call",
- inputs: [{ check: "first" }],
- results: [{ status: "completed", output: { result: "oranges" } }],
- },
-];
-
-function snapshots() {
- return [
- {
- sessionId: "parent",
- events: [event("proxy", "input.requested", { requests: [approval("task_a", "first")] })],
- },
- {
- sessionId: "child",
- events: [
- requested("request"),
- event("approval", "input.requested", { requests: [approval("task_a", "first")] }),
- ],
- },
- { sessionId: "child", events: [completed("result")] },
- ];
-}
-
-test("repeated activation events with new event IDs still identify one child", () => {
- const child = {
- callId: "call-a",
- childSessionId: "child-a",
- agentId: "agent-a",
- name: "agent",
- sessionId: "parent",
- turnId: "turn_1",
- };
- const snapshots = [
- {
- sessionId: "parent",
- events: [
- event("activation-1", "subagent.called", child),
- event("activation-2", "subagent.called", { ...child }),
- ],
- },
- ];
- assert.deepEqual(childActivations(snapshots, "parent"), [child]);
- assert.deepEqual(childActivations(snapshots, "another-parent"), []);
- for (const changed of [
- { childSessionId: "child-b" },
- { agentId: "agent-b" },
- { name: "other" },
- { sessionId: "other" },
- { turnId: "turn_2" },
- ]) {
- snapshots[0].events[1] = event("activation-2", "subagent.called", { ...child, ...changed });
- assert.throws(() => childActivations(snapshots, "parent"), /changed its identity/);
- }
- snapshots[0].events[1] = event("activation-2", "subagent.called", { ...child, callId: "call-b" });
- assert.equal(childActivations(snapshots, "parent").length, 2);
-});
-
-test("joins a paused request to its result in a later approval turn", () => {
- assert.deepEqual(toolEvidence(snapshots(), "child", "probe"), expected);
- assert.deepEqual(toolEvidence(snapshots(), "parent", "probe"), []);
-});
-
-test("proxy approvals in both ancestors do not count as nested probe executions", () => {
- const turns = snapshots();
- turns[1].sessionId = "leaf";
- turns[2].sessionId = "leaf";
- turns.push({ sessionId: "child", events: turns[0].events });
- assert.deepEqual(toolEvidence(turns, "leaf", "probe"), expected);
- assert.deepEqual(toolEvidence(turns, "child", "probe"), []);
-});
-
-test("deduplicates event and logical-call retries within the owning session", () => {
- const turns = snapshots();
- turns.push(...snapshots());
- turns.push({
- sessionId: "child",
- events: [requested("retried-request"), completed("retried-result")],
- });
- turns.push({
- sessionId: "sibling",
- events: [
- requested("request", "probe-call", "second"),
- completed("result", "probe-call", "completed", { result: "pears" }),
- ],
- });
- assert.deepEqual(toolEvidence(turns, "child", "probe"), expected);
- assert.equal(eventsForSession(turns, "child").length, 5);
- assert.deepEqual(toolEvidence(turns, "sibling", "probe")[0].inputs, [{ check: "second" }]);
-});
-
-test("rejects a logical-call retry that changes its result", () => {
- const turns = snapshots();
- turns.push({
- sessionId: "child",
- events: [completed("changed-result", "probe-call", "completed", { result: "pears" })],
- });
- assert.throws(() => toolEvidence(turns, "child", "probe"), /tool result probe-call changed/);
-});
-
-test("counts retried model preambles once by logical coordinates", () => {
- const started = (id, stepIndex = 0) =>
- event(id, "step.started", {
- modelId: "openai/test",
- sequence: 4,
- stepIndex,
- turnId: "turn_4",
- });
- const turns = [
- { sessionId: "parent", events: [started("step-1"), started("step-retry")] },
- { sessionId: "parent", events: [started("step-2", 1)] },
- { sessionId: "child", events: [started("child-step")] },
- ];
-
- assert.equal(modelStepCount(turns), 3);
-});
-
-test("deduplicates retried completion notifications but not duplicate text in one message", () => {
- const message =
- "Background task task_first (agent) is completed.\nBackground task task_second (agent) is completed.";
- const notification = (id, value = message) =>
- event(id, "message.received", { message: value, sequence: 4, turnId: "turn_4" });
- const snapshot = {
- sessionId: "parent",
- events: [notification("message-1"), notification("message-retry")],
- };
-
- assert.deepEqual(completedTaskIds(snapshot), ["task_first", "task_second"]);
- assert.deepEqual(
- completedTaskIds({
- ...snapshot,
- events: [
- notification(
- "duplicated-in-message",
- "Background task task_first (agent) is completed.\nBackground task task_first (agent) is completed.",
- ),
- ],
- }),
- ["task_first", "task_first"],
- );
-});
-
-test("does not join a same-call-ID request and result from different sessions", () => {
- const turns = snapshots();
- turns[2].sessionId = "sibling";
- assert.deepEqual(toolEvidence(turns, "child", "probe")[0].results, []);
- assert.deepEqual(toolEvidence(turns, "sibling", "probe")[0].inputs, []);
-});
-
-for (const [name, extra] of [
- [
- "a second execution with a new call ID",
- [requested("request-2", "second-call"), completed("result-2", "second-call")],
- ],
- ["an orphan completion", [completed("orphan", "unknown-call")]],
- ["a pending extra call", [requested("pending", "pending-call")]],
-]) {
- test(`exact evidence rejects ${name}`, () => {
- const turns = snapshots();
- turns.push({ sessionId: "child", events: extra });
- assert.notDeepEqual(toolEvidence(turns, "child", "probe"), expected);
- });
-}
-
-for (const [name, result] of [
- ["a failed result", completed("result", "probe-call", "failed")],
- ["a rejected result", completed("result", "probe-call", "rejected")],
- ["the wrong output", completed("result", "probe-call", "completed", { result: "pears" })],
- ["the wrong call ID", completed("result", "other-call")],
-]) {
- test(`exact evidence rejects ${name}`, () => {
- const turns = snapshots();
- turns[2].events = [result];
- assert.notDeepEqual(toolEvidence(turns, "child", "probe"), expected);
- });
-}
-
-test("exact evidence rejects the wrong check or a missing completion", () => {
- const turns = snapshots();
- turns[1].events = [requested("request", "probe-call", "second")];
- assert.notDeepEqual(toolEvidence(turns, "child", "probe"), expected);
- assert.notDeepEqual(toolEvidence(snapshots().slice(0, 2), "child", "probe"), expected);
-});
-
-test("reports a filtered original task before attempting to join replacement approvals", () => {
- const message =
- 'Background task task_original (agent) failed.\n\nError:\n{"code":"SUBAGENT_EXECUTION_FAILED","message":"The model provider filtered this response."}';
- const turns = [
- {
- sessionId: "parent",
- events: [
- event("failure", "message.received", { message }),
- event("replacement-approval", "input.requested", {
- requests: [approval("task_replacement", "third")],
- }),
- ],
- },
- ];
- assert.throws(
- () => requireOriginalTasksHealthy(turns, "parent", ["task_original"]),
- /replacement tasks cannot satisfy this eval.*task_original[\s\S]*provider filtered this response/,
- );
- assert.throws(() => checkForTask("task_original", [approval("task_replacement", "third")]));
-});
-
-test("reports cancellation of an original task before an approval join", () => {
- const turns = [
- {
- sessionId: "parent",
- events: [
- event("cancel", "message.received", {
- message: "Background task task_original (agent) is cancelled.",
- }),
- ],
- },
- ];
- assert.throws(
- () => requireOriginalTasksHealthy(turns, "parent", ["task_original"]),
- /is cancelled/,
- );
-});
-
-test("failure detection is scoped to the original task and its parent session", () => {
- const failure = "Background task task_original (agent) failed.";
- const turns = [
- {
- sessionId: "other-parent",
- events: [event("other-failure", "message.received", { message: failure })],
- },
- {
- sessionId: "parent",
- events: [
- event("completion", "message.received", {
- message: "Background task task_original (agent) is completed.",
- }),
- event("other-task", "message.received", {
- message: "Background task task_original_other (agent) failed.",
- }),
- event("quotation", "message.received", {
- message: `Alice asks about this earlier note: ${failure}`,
- }),
- event("answer", "message.completed", { message: failure }),
- ],
- },
- ];
- assert.doesNotThrow(() => requireOriginalTasksHealthy(turns, "parent", ["task_original"]));
-});
-
-test("maps checks by task-scoped runtime approval, independent of assignment wording or order", () => {
- const requests = [
- approval("task_second", "second"),
- approval("task_third", "third"),
- approval("task_first", "first"),
- ];
- assert.equal(checkForTask("task_first", requests), "first");
- assert.equal(checkForTask("task_second", requests), "second");
- assert.equal(checkForTask("task_third", requests), "third");
- assert.throws(() => checkForTask("task_fir", requests));
-});
-
-test("task joins reject missing, ambiguous, invalid, non-approval, and wrong-tool requests", () => {
- const valid = approval("task_a", "first");
- for (const requests of [
- [],
- [approval("task_b", "first")],
- [valid, { ...valid, requestId: "task_a:other-approval" }],
- [approval("task_a", "fourth")],
- [{ ...valid, kind: "question" }],
- [{ ...valid, action: { ...valid.action, toolName: "other-tool" } }],
- ]) {
- assert.throws(() => checkForTask("task_a", requests));
- }
-});
diff --git a/e2e/fixtures/agent-task-reporting/evals/event-matching.ts b/e2e/fixtures/agent-task-reporting/evals/event-matching.ts
deleted file mode 100644
index 6205b837e..000000000
--- a/e2e/fixtures/agent-task-reporting/evals/event-matching.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { isDeepStrictEqual } from "node:util";
-
-import type { EveEvalTurn, InputRequest } from "eve/evals";
-
-type Event = EveEvalTurn["events"][number];
-export type SessionEvents = Pick<EveEvalTurn, "sessionId" | "events">;
-export const CHECKS = ["first", "second", "third"] as const;
-export type Check = (typeof CHECKS)[number];
-const COMPLETION = /Background task (task_[a-z0-9]+) \([^)]+\) is completed\./giu;
-
-/** Counts logical model steps while tolerating durable step retries with new event IDs. */
-export function modelStepCount(snapshots: readonly SessionEvents[]): number {
- const steps = new Set<string>();
- for (const snapshot of snapshots) {
- for (const event of snapshot.events) {
- if (event.type !== "step.started") continue;
- steps.add(
- JSON.stringify([
- snapshot.sessionId,
- event.data.turnId,
- event.data.sequence,
- event.data.stepIndex,
- event.data.modelId,
- ]),
- );
- }
- }
- return steps.size;
-}
-
-/** Extracts each logical notification once without hiding duplicates inside one message. */
-export function completedTaskIds(snapshot: SessionEvents): string[] {
- const messages = new Set<string>();
- const taskIds: string[] = [];
- for (const event of snapshot.events) {
- if (event.type !== "message.received") continue;
- const logicalMessage = JSON.stringify([
- event.data.turnId,
- event.data.sequence,
- event.data.message,
- ]);
- if (messages.has(logicalMessage)) continue;
- messages.add(logicalMessage);
- taskIds.push(...[...event.data.message.matchAll(COMPLETION)].map((match) => match[1]));
- }
- return taskIds;
-}
-
-export function requireOriginalTasksHealthy(
- snapshots: readonly SessionEvents[],
- sessionId: string,
- taskIds: readonly string[],
-): void {
- for (const event of eventsForSession(snapshots, sessionId)) {
- if (event.type !== "message.received") continue;
- for (const taskId of taskIds) {
- const prefix = `Background task ${taskId} (agent) `;
- const message = event.data.message;
- if (message.startsWith(`${prefix}failed.`) || message.startsWith(`${prefix}is cancelled.`)) {
- throw new Error(
- `Original warehouse task failed or was cancelled; replacement tasks cannot satisfy this eval. ${message.slice(0, 1000)}`,
- );
- }
- }
- }
-}
-
-export function checkForTask(taskId: string, requests: readonly InputRequest[]): Check {
- // The parent proxy prefixes the original approval ID with its owning task ID.
- const owned = requests.filter((request) => request.requestId.startsWith(`${taskId}:`));
- const request = owned[0];
- const check = CHECKS.find((candidate) => candidate === request?.action.input.check);
- if (
- owned.length !== 1 ||
- request?.kind !== "tool-approval" ||
- request.action.toolName !== "probe" ||
- check === undefined
- ) {
- throw new Error(
- `Warehouse task ${taskId} needs exactly one probe approval with a valid check.`,
- );
- }
- return check;
-}
-
-export function eventsForSession(snapshots: readonly SessionEvents[], sessionId: string): Event[] {
- const events = new Map<string, Event>();
- for (const snapshot of snapshots) {
- if (snapshot.sessionId !== sessionId) continue;
- for (const event of snapshot.events) {
- // Only repeated delivery of the same event is replay, not another result for the same call.
- if (!events.has(event.meta.id)) events.set(event.meta.id, event);
- }
- }
- return [...events.values()];
-}
-
-export function childActivations(snapshots: readonly SessionEvents[], sessionId: string) {
- type Called = Extract<Event, { type: "subagent.called" }>["data"];
- const calls = new Map<string, Called>();
- for (const event of eventsForSession(snapshots, sessionId)) {
- if (event.type !== "subagent.called") continue;
- const current = event.data;
- const previous = calls.get(current.callId);
- if (previous !== undefined) {
- // A retried activation notification must still identify the very same child.
- if (
- previous.childSessionId !== current.childSessionId ||
- previous.agentId !== current.agentId ||
- previous.name !== current.name ||
- previous.sessionId !== current.sessionId ||
- previous.turnId !== current.turnId
- ) {
- throw new Error(`Child activation ${current.callId} changed its identity.`);
- }
- } else {
- calls.set(current.callId, current);
- }
- }
- return [...calls.values()];
-}
-
-export function toolEvidence(
- snapshots: readonly SessionEvents[],
- sessionId: string,
- toolName: string,
-) {
- type Requested = Extract<Event, { type: "actions.requested" }>["data"]["actions"][number];
- type Result = Extract<Event, { type: "action.result" }>["data"];
- const calls = new Map<
- string,
- {
- callId: string;
- inputs: Requested["input"][];
- results: { status: Result["status"]; output: Result["result"]["output"] }[];
- }
- >();
- function call(callId: string) {
- let entry = calls.get(callId);
- if (entry === undefined) {
- entry = { callId, inputs: [], results: [] };
- calls.set(callId, entry);
- }
- return entry;
- }
- function appendRetry<T>(values: T[], value: T, label: string): void {
- const previous = values[0];
- if (previous === undefined) {
- values.push(value);
- } else if (!isDeepStrictEqual(previous, value)) {
- throw new Error(`Retried ${label} changed its value.`);
- }
- }
- for (const event of eventsForSession(snapshots, sessionId)) {
- if (event.type === "actions.requested") {
- for (const action of event.data.actions) {
- if (action.kind === "tool-call" && action.toolName === toolName) {
- appendRetry(call(action.callId).inputs, action.input, `tool input ${action.callId}`);
- }
- }
- } else if (event.type === "action.result") {
- const { result, status } = event.data;
- if (result.kind === "tool-result" && result.toolName === toolName) {
- appendRetry(
- call(result.callId).results,
- { status, output: result.output },
- `tool result ${result.callId}`,
- );
- }
- }
- }
- return [...calls.values()];
-}
diff --git a/e2e/fixtures/agent-task-reporting/evals/pending-response.eval.ts b/e2e/fixtures/agent-task-reporting/evals/pending-response.eval.ts
deleted file mode 100644
index e7627a7f6..000000000
--- a/e2e/fixtures/agent-task-reporting/evals/pending-response.eval.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { defineEval } from "eve/evals";
-import { equals } from "eve/evals/expect";
-
-import {
- completedAt,
- modelSteps,
- QUESTION,
- sendQuestion,
- startWarehouseLookups,
- waitForPartialCompletion,
- waitForReport,
-} from "./reporting.js";
-
-function pendingResponseEval() {
- return defineEval({
- description:
- "A real parent answers Alice after one child completes while sibling approvals remain pending, then reports the whole cohort including a nested lookup.",
- tags: ["real-model", "pending-response"],
- async test(t) {
- const run = await startWarehouseLookups(t);
- await waitForPartialCompletion(t, run);
- const question = await sendQuestion(t, run);
- const report = await waitForReport(t, run);
-
- const first = run.completedChildren.get("first");
- const last = run.completedChildren.get("third");
- if (first === undefined || last === undefined)
- throw new Error("Missing completed warehouse children.");
- const received = question.events.find(
- (event) => event.type === "message.received" && event.data.message === QUESTION,
- );
- const answered = question.events.find(
- (event) => event.type === "message.completed" && event.data.message?.trim() === "56",
- );
- const reportStep = report.events.find((event) => event.type === "step.started");
- const askedAt = Date.parse(received?.meta.at ?? "");
- const answeredAt = Date.parse(answered?.meta.at ?? "");
- const reportAt = Date.parse(reportStep?.meta.at ?? "");
- t.check(completedAt(first) <= askedAt, equals(true)).label(
- "the user question follows actual child completion",
- );
- t.check(answeredAt < completedAt(last), equals(true)).label(
- "the user answer precedes the nested child's completion",
- );
- t.check(completedAt(last) <= reportAt, equals(true)).label(
- "the cohort model turn starts only after the last child completes",
- );
- t.check(modelSteps(run.parentTurns), equals(2)).label(
- "only the user answer and final cohort report invoke the parent model",
- );
- t.notEvent("compaction.requested");
- t.noFailedActions();
- },
- });
-}
-
-export default Array.from({ length: 20 }, pendingResponseEval);
diff --git a/e2e/fixtures/agent-task-reporting/evals/reporting.ts b/e2e/fixtures/agent-task-reporting/evals/reporting.ts
deleted file mode 100644
index 006b4d4cb..000000000
--- a/e2e/fixtures/agent-task-reporting/evals/reporting.ts
+++ /dev/null
@@ -1,449 +0,0 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
-import { e2eModel } from "@eve-e2e/config";
-import type { EveEvalContext, EveEvalSession, EveEvalTurn, InputRequest } from "eve/evals";
-import { equals, satisfies } from "eve/evals/expect";
-
-import {
- CHECKS,
- childActivations,
- checkForTask,
- completedTaskIds,
- eventsForSession,
- modelStepCount,
- requireOriginalTasksHealthy,
- toolEvidence,
- type Check,
-} from "./event-matching.js";
-
-export const TASK_COUNT = 3;
-export const QUESTION =
- "Alice is packing seven boxes with eight jars in each. How many jars is that? Reply with just the number.";
-
-const RESULTS = { first: "oranges", second: "pears", third: "apples" } as const;
-
-interface Child {
- readonly check: Check;
- readonly sessionId: string;
- readonly taskId: string;
-}
-
-export interface ReportingRun {
- readonly sessionId: string;
- readonly taskIds: readonly string[];
- readonly children: readonly Child[];
- readonly requests: ReadonlyMap<Check, InputRequest>;
- readonly completedChildren: Map<Check, EveEvalTurn>;
- readonly childTurns: EveEvalTurn[];
- readonly probeSessions: Map<Check, string>;
- readonly parentTurns: EveEvalTurn[];
- readonly modelId: string;
- session: EveEvalSession;
-}
-
-export async function startWarehouseLookups(t: EveEvalContext): Promise<ReportingRun> {
- const modelId = e2eModel();
- if (typeof modelId !== "string") throw new Error("Warehouse reporting requires a real CI model.");
- const started = await t.send(
- `Alice is preparing an inventory checklist for Bob's warehouse handoff. Please delegate these three entries to three separate background assistants using the built-in agent tool, so the checks can proceed independently. Include the entry's check reference in each assistant's assignment.
-
-1. check=first: Find the inventory item for the first entry using the inventory lookup tool (probe), and share the item it returns.
-2. check=second: Find the inventory item for the second entry using the inventory lookup tool (probe), and share the item it returns.
-3. check=third: Assign a third background assistant with agent, just like the first two entries. Ask that assistant to use warehouse_lookup; the workflow contacts the warehouse specialist and returns its item.
-
-Once all three assignments are accepted, let Alice know the checks are underway. When all three results are ready, reply directly from the returned items without further tool calls or task-list updates. Bob needs only three checklist entries, with each item listed once and no separate summary.`,
- { taskDeliveryPolicy: "cohort" },
- );
- started.expectOk();
- started.calledSubagent("agent", { status: "working", count: TASK_COUNT });
- started.notCalledTool("probe");
- started.notCalledTool("warehouse_lookup");
- assertModel(started, modelId);
- await t.require(
- started,
- satisfies(hasPostReceiptAcknowledgement, "acknowledgement follows all three task receipts"),
- );
- await t.require(
- started.message,
- satisfies(
- (message) =>
- typeof message === "string" &&
- message.trim().length > 0 &&
- Object.values(RESULTS).every((result) => !message.toLowerCase().includes(result)),
- "the initiating turn acknowledges work without claiming inventory results",
- ),
- );
-
- const receipts = taskReceipts(started.events);
- const actions = started.events.flatMap((event) =>
- event.type === "actions.requested" ? event.data.actions : [],
- );
- const setupTurns = [started];
- let calls = childActivations(setupTurns, started.sessionId);
- const children: Child[] = [];
- const taskIds = receipts.map((receipt) => receipt.taskId);
- const requests = new Map<Check, InputRequest>();
- const run: ReportingRun = {
- session: started.session,
- sessionId: started.sessionId,
- taskIds,
- children,
- requests,
- modelId,
- completedChildren: new Map(),
- childTurns: [],
- probeSessions: new Map(),
- parentTurns: [],
- };
- requireOriginalTasksHealthy([started], run.sessionId, run.taskIds);
- collectRequests(started);
- // Task receipts precede child startup; called events can arrive after the parent parks.
- for (
- let attempt = 0;
- (calls.length < TASK_COUNT || requests.size < TASK_COUNT) && attempt < 8;
- attempt += 1
- ) {
- const turn = await nextParentTurn(t, run);
- setupTurns.push(turn);
- calls = childActivations(setupTurns, started.sessionId);
- collectRequests(turn);
- }
- children.push(
- ...calls.map((call): Child => {
- const assignments = actions.filter(
- (action) =>
- action.callId === call.callId &&
- action.kind === "tool-call" &&
- action.toolName === "agent",
- );
- const matchingReceipts = receipts.filter((entry) => entry.callId === call.callId);
- const receipt = matchingReceipts[0];
- if (
- call.sessionId !== started.sessionId ||
- call.name !== "agent" ||
- assignments.length !== 1 ||
- matchingReceipts.length !== 1 ||
- receipt === undefined
- )
- throw new Error("Each warehouse child needs one assignment and a matching task receipt.");
- return {
- check: checkForTask(receipt.taskId, [...requests.values()]),
- sessionId: call.childSessionId,
- taskId: receipt.taskId,
- };
- }),
- );
- await t.require(
- {
- receipts: taskIds.length,
- tasks: new Set(taskIds).size,
- children: children.length,
- sessions: new Set(children.map((child) => child.sessionId)).size,
- checks: children.map((child) => child.check).sort(),
- mappedTasks: children.map((child) => child.taskId).sort(),
- // Child startup may be observed in later turns; assignment events own launch provenance.
- creatingTurns: new Set(
- started.events.flatMap((event) =>
- event.type === "actions.requested" &&
- event.data.actions.some(
- (action) => action.kind === "tool-call" && action.toolName === "agent",
- )
- ? [event.data.turnId]
- : [],
- ),
- ).size,
- },
- equals({
- receipts: TASK_COUNT,
- tasks: TASK_COUNT,
- children: TASK_COUNT,
- sessions: TASK_COUNT,
- checks: [...CHECKS].sort(),
- mappedTasks: [...taskIds].sort(),
- creatingTurns: 1,
- }),
- );
-
- await t.require(
- {
- checks: [...requests.keys()].sort(),
- ids: new Set([...requests.values()].map((request) => request.requestId)).size,
- },
- equals({ checks: [...CHECKS].sort(), ids: TASK_COUNT }),
- );
- // Setup includes prompt/approval wakes; completion admission is measured from this cursor onward.
- run.parentTurns.length = 0;
- return run;
-
- function collectRequests(turn: EveEvalTurn) {
- for (const request of turn.inputRequests) {
- if (request.action.toolName !== "probe")
- throw new Error("Unexpected warehouse approval tool.");
- const check = CHECKS.find((candidate) => candidate === request.action.input.check);
- if (
- check === undefined ||
- (requests.has(check) && requests.get(check)!.requestId !== request.requestId)
- ) {
- throw new Error("Each warehouse must have exactly one approval request.");
- }
- requests.set(check, request);
- }
- }
-}
-
-/** Establish partial completion on the child stream, without waiting for a withheld parent wake. */
-export async function waitForPartialCompletion(
- t: EveEvalContext,
- run: ReportingRun,
-): Promise<void> {
- await releaseCheck(t, run, "first");
- await t.require([...run.completedChildren.keys()], equals(["first"]));
-}
-
-export async function sendQuestion(t: EveEvalContext, run: ReportingRun): Promise<EveEvalTurn> {
- await post(t, run, "", { message: QUESTION, turnPolicy: "queue" });
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const turn = await nextParentTurn(t, run);
- await t.require(completedTaskIds(turn), equals([]));
- if (
- turn.events.some(
- (event) => event.type === "message.received" && event.data.message === QUESTION,
- )
- ) {
- await t.require(turn.message?.trim(), equals("56"));
- turn.usedNoTools();
- await t.require(modelSteps(run.parentTurns), equals(1));
- return turn;
- }
- turn.notEvent("step.started");
- }
- throw new Error("No independent user answer while the remaining warehouses were gated.");
-}
-
-export async function compactWhilePending(t: EveEvalContext, run: ReportingRun): Promise<void> {
- await post(t, run, "/compact", {});
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const turn = await nextParentTurn(t, run);
- await t.require(completedTaskIds(turn), equals([]));
- turn.notEvent("step.started");
- if (turn.events.some((event) => event.type === "compaction.requested")) {
- turn.event("compaction.requested", { count: 1 });
- // A declined summary preserves history; either path must retain the held cohort.
- turn.event("compaction.completed", { count: 1 }).soft().label("successful checkpoint");
- await t.require(modelSteps(run.parentTurns), equals(0));
- return;
- }
- }
- throw new Error("No compaction boundary while the remaining warehouses were gated.");
-}
-
-export async function waitForReport(t: EveEvalContext, run: ReportingRun): Promise<EveEvalTurn> {
- await releaseCheck(t, run, "second");
- await releaseCheck(t, run, "third");
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const turn = await nextParentTurn(t, run);
- const taskIds = completedTaskIds(turn);
- if (taskIds.length > 0) {
- await t.require(taskIds.sort(), equals([...run.taskIds].sort()));
- await t.require(
- run.parentTurns.flatMap(completedTaskIds).sort(),
- equals([...run.taskIds].sort()),
- );
- turn.usedNoTools();
- turn.event("step.started", { count: 1, data: { modelId: run.modelId } });
- turn.event("message.completed", {
- count: 1,
- data: (data) => data.finishReason !== "tool-calls" && data.message !== null,
- });
- turn.notEvent("message.completed", { data: (data) => data.message === null });
- await t.require(turn.message, completeReport());
- t.calledSubagent("agent", { count: TASK_COUNT });
- const probeCalls = [...new Set(run.childTurns.map((child) => child.sessionId))].flatMap(
- (sessionId) => toolEvidence(run.childTurns, sessionId, "probe"),
- );
- await t.require(probeCalls.length, equals(TASK_COUNT));
- for (const check of CHECKS) {
- const sessionId = run.probeSessions.get(check);
- if (sessionId === undefined) throw new Error(`Missing probe session for ${check}.`);
- await t.require(
- toolEvidence(run.childTurns, sessionId, "probe"),
- equals([
- {
- callId: run.requests.get(check)!.action.callId,
- inputs: [{ check }],
- results: [{ output: { result: RESULTS[check] }, status: "completed" }],
- },
- ]),
- );
- }
- return turn;
- }
- turn.notEvent("step.started");
- }
- throw new Error("No single report containing every original warehouse task.");
-}
-
-export function completeReport() {
- return satisfies(
- (message) =>
- typeof message === "string" &&
- JSON.stringify(
- message
- .toLowerCase()
- .match(/\b(?:oranges|pears|apples)\b/gu)
- ?.sort(),
- ) === JSON.stringify(Object.values(RESULTS).sort()),
- "one report contains each inventory item exactly once",
- );
-}
-
-export function modelSteps(turns: readonly EveEvalTurn[]): number {
- return modelStepCount(turns);
-}
-
-export function completedAt(turn: EveEvalTurn): number {
- const event = turn.events.find((entry) => entry.type === "turn.completed");
- if (event === undefined) throw new Error("Missing child completion event.");
- return Date.parse(event.meta.at);
-}
-
-export function requireStreamIndex(session: EveEvalSession): number {
- if (session.state === undefined) throw new Error("Task reporting session has no stream index.");
- return session.state.streamIndex;
-}
-
-async function releaseCheck(t: EveEvalContext, run: ReportingRun, check: Check): Promise<void> {
- const request = run.requests.get(check);
- const child = run.children.find((entry) => entry.check === check);
- if (request === undefined || child === undefined || run.completedChildren.has(check)) {
- throw new Error(`No unreleased warehouse child for ${check}.`);
- }
- await post(t, run, "", {
- inputResponses: [{ requestId: request.requestId, optionId: "approve" }],
- });
- const turns = await readCompletedChild(t, child.sessionId, check, run.modelId);
- run.completedChildren.set(check, turns.at(-1)!);
- run.childTurns.push(...turns);
- const nested = childActivations(turns, child.sessionId);
- if (check !== "third") {
- await t.require(nested, equals([]));
- run.probeSessions.set(check, child.sessionId);
- return;
- }
- await t.require(nested.length, equals(1));
- const delegate = nested[0]!;
- const lookup = toolEvidence(turns, child.sessionId, "warehouse_lookup");
- await t.require(lookup.length, equals(1));
- await t.require(
- {
- name: delegate.name,
- sessionId: delegate.sessionId,
- ownedCall: delegate.callId.startsWith(`${lookup[0]!.callId}:`),
- distinctSession:
- delegate.childSessionId !== run.sessionId &&
- !run.children.some((entry) => entry.sessionId === delegate.childSessionId),
- },
- equals({
- name: "warehouse-worker",
- sessionId: child.sessionId,
- ownedCall: true,
- distinctSession: true,
- }),
- );
- const leaf = await readCompletedChild(t, delegate.childSessionId, check, run.modelId);
- run.childTurns.push(...leaf);
- run.probeSessions.set(check, delegate.childSessionId);
- await t.require(
- eventsForSession(leaf, delegate.childSessionId).filter(
- (event) => event.type === "subagent.called",
- ),
- equals([]),
- );
- // Check the owning workflow tool result for the completed lookup.
- await t.require(
- lookup,
- equals([
- {
- callId: lookup[0]!.callId,
- inputs: [{ check }],
- results: [{ status: "completed", output: leaf.at(-1)!.message }],
- },
- ]),
- );
- await t.require(completedAt(leaf.at(-1)!) <= completedAt(turns.at(-1)!), equals(true));
-}
-
-async function readCompletedChild(
- t: EveEvalContext,
- sessionId: string,
- check: Check,
- modelId: string,
-): Promise<EveEvalTurn[]> {
- const turns: EveEvalTurn[] = [];
- let startIndex = 0;
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const live = t.target.watchTurn(sessionId, { startIndex });
- const turn = (await live.result()).expectOk();
- assertModel(turn, modelId);
- turns.push(turn);
- startIndex = requireStreamIndex(live.session);
- if (
- turn.events.some((event) => event.type === "turn.completed") &&
- turn.message?.toLowerCase().includes(RESULTS[check])
- )
- return turns;
- }
- throw new Error(`Warehouse child ${check} did not complete with its inventory item.`);
-}
-
-async function nextParentTurn(t: EveEvalContext, run: ReportingRun): Promise<EveEvalTurn> {
- const live = t.target.watchTurn(run.sessionId, { startIndex: requireStreamIndex(run.session) });
- const turn = (await live.result()).expectOk();
- requireOriginalTasksHealthy([turn], run.sessionId, run.taskIds);
- turn.noFailedActions();
- assertModel(turn, run.modelId);
- run.session = live.session;
- run.parentTurns.push(turn);
- return turn;
-}
-
-function assertModel(turn: EveEvalTurn, modelId: string) {
- turn.eventsSatisfy("every model step uses the real CI model", (events) =>
- events.every((event) => event.type !== "step.started" || event.data.modelId === modelId),
- );
-}
-
-async function post(t: EveEvalContext, run: ReportingRun, suffix: "" | "/compact", body: unknown) {
- const response = await t.target.fetch(
- `/eve/v1/session/${encodeURIComponent(run.sessionId)}${suffix}`,
- {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- signal: t.signal,
- },
- );
- await response.body?.cancel();
- await t.require(response.status, equals(202));
-}
-
-function hasPostReceiptAcknowledgement(turn: EveEvalTurn): boolean {
- const receiptCallIds = new Set(
- taskReceipts(turn.events)
- .filter(({ toolName }) => toolName === "agent")
- .map(({ callId }) => callId),
- );
- const receiptIndexes = turn.events.flatMap((event, index) =>
- event.type === "action.result" && receiptCallIds.has(event.data.result.callId) ? [index] : [],
- );
- return (
- receiptIndexes.length === TASK_COUNT &&
- turn.events.some(
- (event, index) =>
- index > Math.max(...receiptIndexes) &&
- event.type === "message.completed" &&
- event.data.finishReason !== "tool-calls" &&
- event.data.message !== null &&
- event.data.message.trim().length > 0,
- )
- );
-}
diff --git a/e2e/fixtures/agent-task-reporting/package.json b/e2e/fixtures/agent-task-reporting/package.json
deleted file mode 100644
index d75b5b353..000000000
--- a/e2e/fixtures/agent-task-reporting/package.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "name": "agent-task-reporting",
- "version": "0.0.0",
- "private": true,
- "type": "module",
- "scripts": {
- "build": "eve build",
- "dev": "eve dev",
- "start": "eve start",
- "typecheck": "eve build --skip-sandbox-prewarm && tsc",
- "test:e2e": "eve eval --strict",
- "test:unit": "node --test evals/event-matching.test.mjs"
- },
- "dependencies": {
- "@eve-e2e/config": "workspace:*",
- "@workflow/world-postgres": "catalog:",
- "eve": "workspace:*",
- "just-bash": "3.1.0",
- "zod": "catalog:"
- },
- "devDependencies": {
- "@types/node": "catalog:",
- "typescript": "catalog:"
- },
- "e2e": {
- "modelMatrix": "default"
- }
-}
diff --git a/e2e/fixtures/agent-task-reporting/tsconfig.json b/e2e/fixtures/agent-task-reporting/tsconfig.json
deleted file mode 100644
index 7e570d043..000000000
--- a/e2e/fixtures/agent-task-reporting/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "esnext",
- "moduleResolution": "bundler",
- "outDir": "dist",
- "rootDir": ".",
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "forceConsistentCasingInFileNames": true,
- "declaration": false,
- "noEmit": true,
- "types": ["node"]
- },
- "include": ["agent/**/*.ts", "evals/**/*.ts"]
-}
diff --git a/e2e/fixtures/agent-task-wake-policy/agent/agent.ts b/e2e/fixtures/agent-task-wake-policy/agent/agent.ts
deleted file mode 100644
index c0d5465cc..000000000
--- a/e2e/fixtures/agent-task-wake-policy/agent/agent.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { e2eAgentConfig } from "@eve-e2e/config";
-import { defineAgent } from "eve";
-import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";
-
-function respond(request: MockModelRequest): MockModelResponse | string {
- const assignment = request.userMessages.find((message) =>
- /^Bob prepares report [ABC]\./m.test(message),
- );
- if (assignment !== undefined) {
- const marker = assignment.match(/report ([ABC])/)![1]!;
- if (!request.toolResults.some((result) => result.name === "release")) {
- return { toolCalls: [{ name: "release", input: { marker } }] };
- }
- return `REPORT:${marker}`;
- }
- const last =
- request.messages
- .map((message) => message.text)
- .reverse()
- .find(
- (message) =>
- message.includes("Alice checks the status") ||
- message.startsWith("Background task task_"),
- ) ?? "";
- if (last.includes("Alice checks the status")) return "STATUS:AVAILABLE";
- const pending = ["A", "B", "C"].filter(
- (marker) => !request.toolResults.some((result) => result.id === `report-${marker}`),
- );
- if (pending.length > 0) {
- return {
- toolCalls: pending.map((marker) => ({
- id: `report-${marker}`,
- name: "agent",
- input: {
- message: `Bob prepares report ${marker}. Ask Alice to release the report before returning its result.`,
- },
- })),
- };
- }
- const stateMessage = request.messages
- .map((message) => message.text)
- .reverse()
- .find((message) => message.startsWith("[Task state]\n"));
- const state =
- stateMessage === undefined
- ? undefined
- : (JSON.parse(stateMessage.slice("[Task state]\n".length)) as {
- tasks: { status: string; output?: { type: string; data: unknown } }[];
- });
- const results =
- state?.tasks.flatMap((task) => (task.output?.type === "result" ? [task.output.data] : [])) ??
- [];
- const reported = new Set(
- request.messages.flatMap((message) =>
- message.role === "assistant" && message.text.startsWith('["REPORT:')
- ? (JSON.parse(message.text) as string[])
- : [],
- ),
- );
- const unreported = results.filter(
- (result) => typeof result === "string" && !reported.has(result),
- );
- const ready = unreported.filter(
- (result) =>
- result === "REPORT:A" || (results.includes("REPORT:B") && results.includes("REPORT:C")),
- );
- if (ready.length > 0) return JSON.stringify(ready.sort());
- return results.length > 0 ? "<eve-empty-delivery/>" : "REPORTS:STARTED";
-}
-
-const base = e2eAgentConfig({ mock: respond });
-export default defineAgent({
- ...base,
- model: mockModel(respond),
- modelContextWindowTokens: base.modelContextWindowTokens ?? 1_000_000,
-});
diff --git a/e2e/fixtures/agent-task-wake-policy/agent/channels/eve.ts b/e2e/fixtures/agent-task-wake-policy/agent/channels/eve.ts
deleted file mode 100644
index ee18cb0ec..000000000
--- a/e2e/fixtures/agent-task-wake-policy/agent/channels/eve.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { eveChannel } from "eve/channels/eve";
-
-export default eveChannel({
- auth: () => ({
- attributes: { fixture: "task-wake-policy" },
- authenticator: "e2e-fixture",
- issuer: "e2e",
- principalId: "task-wake-policy-e2e-user",
- principalType: "user",
- subject: "task-wake-policy-e2e-user",
- }),
-});
diff --git a/e2e/fixtures/agent-task-wake-policy/agent/channels/scheduled-reports.ts b/e2e/fixtures/agent-task-wake-policy/agent/channels/scheduled-reports.ts
deleted file mode 100644
index 6e747d6eb..000000000
--- a/e2e/fixtures/agent-task-wake-policy/agent/channels/scheduled-reports.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { defineChannel, POST } from "eve/channels";
-
-export default defineChannel<undefined, void, { id: string }>({
- routes: [POST("/scheduled-reports", async () => new Response("ok"))],
- receive(input, { from }) {
- return from(input.target.id).send(input.message, { auth: input.auth });
- },
-});
diff --git a/e2e/fixtures/agent-task-wake-policy/agent/instructions.md b/e2e/fixtures/agent-task-wake-policy/agent/instructions.md
deleted file mode 100644
index 02f5d0a79..000000000
--- a/e2e/fixtures/agent-task-wake-policy/agent/instructions.md
+++ /dev/null
@@ -1 +0,0 @@
-Prepare reports A, B, and C. Ask Alice to release each report before returning its result. Share A independently; combine B and C once both are available. Answer Alice while other work continues.
diff --git a/e2e/fixtures/agent-task-wake-policy/agent/schedules/automatic-reports.ts b/e2e/fixtures/agent-task-wake-policy/agent/schedules/automatic-reports.ts
deleted file mode 100644
index 7012ad5db..000000000
--- a/e2e/fixtures/agent-task-wake-policy/agent/schedules/automatic-reports.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { defineSchedule } from "eve/schedules";
-import reports from "../channels/scheduled-reports";
-
-export default defineSchedule({
- cron: "0 9 * * *",
- run({ to, waitUntil, appAuth }) {
- waitUntil(
- to(reports, { id: crypto.randomUUID() }).send(
- "Alice asks Bob to prepare reports A, B, and C. Report A is independent; reports B and C form a joint comparison. Share A when ready and combine B with C once both are available.",
- { auth: appAuth, taskDeliveryPolicy: "auto" },
- ),
- );
- },
-});
diff --git a/e2e/fixtures/agent-task-wake-policy/agent/tools/release.ts b/e2e/fixtures/agent-task-wake-policy/agent/tools/release.ts
deleted file mode 100644
index ee98188cc..000000000
--- a/e2e/fixtures/agent-task-wake-policy/agent/tools/release.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { defineTool } from "eve/tools";
-import { once } from "eve/tools/approval";
-import { z } from "zod";
-
-export default defineTool({
- description: "Wait for Alice to release this report.",
- inputSchema: z.object({ marker: z.enum(["A", "B", "C"]) }),
- approval: once(),
- execute: async ({ marker }) => ({ marker }),
-});
diff --git a/e2e/fixtures/agent-task-wake-policy/evals/evals.config.ts b/e2e/fixtures/agent-task-wake-policy/evals/evals.config.ts
deleted file mode 100644
index 3a1a10d6f..000000000
--- a/e2e/fixtures/agent-task-wake-policy/evals/evals.config.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { defineEvalConfig } from "eve/evals";
-
-export default defineEvalConfig({});
diff --git a/e2e/fixtures/agent-task-wake-policy/evals/result-delivery.eval.ts b/e2e/fixtures/agent-task-wake-policy/evals/result-delivery.eval.ts
deleted file mode 100644
index b195ad0fe..000000000
--- a/e2e/fixtures/agent-task-wake-policy/evals/result-delivery.eval.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { defineEval, type EveEvalTurn, type InputRequest } from "eve/evals";
-import { equals } from "eve/evals/expect";
-
-export default defineEval({
- description:
- "A scheduled send using auto overrides the cohort default: report A independently, withhold B until C finishes, then report B and C together.",
- timeoutMs: 120_000,
- async test(t) {
- if (!t.target.capabilities.devRoutes) {
- t.skip("Schedule dispatch requires dev routes.");
- }
- const dispatched = await t.target.dispatchSchedule("automatic-reports");
- await t.require(dispatched.sessionIds.length, equals(1));
- const launch = t.target.watchTurn(dispatched.sessionIds[0]!);
- const started = (await launch.result()).expectOk();
- started.calledSubagent("agent", { status: "working", count: 3 });
- let streamIndex = launch.session.state!.streamIndex;
- const requests = new Map<string, InputRequest>();
- const turns: EveEvalTurn[] = [started];
- collectRequests(started);
- for (let attempt = 0; requests.size < 3 && attempt < 8; attempt += 1)
- collectRequests(await nextTurn());
- await t.require([...requests.keys()].sort(), equals(["A", "B", "C"]));
-
- await release("A");
- (await through('["REPORT:A"]')).usedNoTools();
-
- await release("B");
- const partial = await throughCompletion("REPORT:B");
- partial.usedNoTools();
- await t.require(partial.message, equals(undefined));
- await post({
- message: "Alice checks the status while Bob's report C awaits her approval.",
- turnPolicy: "queue",
- });
- (await through("STATUS:AVAILABLE")).usedNoTools();
-
- await release("C");
- (await through('["REPORT:B","REPORT:C"]')).usedNoTools();
- const reports = turns
- .map((turn) => turn.message)
- .filter((message) => message?.startsWith('["REPORT:'));
- t.check(reports, equals(['["REPORT:A"]', '["REPORT:B","REPORT:C"]'])).label(
- "A reports once; B is retained until it can be combined with C",
- );
- for (const turn of turns) turn.noFailedActions();
-
- function collectRequests(turn: EveEvalTurn) {
- for (const request of turn.inputRequests) {
- const marker = request.action.input.marker;
- if (request.action.toolName === "release" && typeof marker === "string")
- requests.set(marker, request);
- }
- }
-
- async function release(marker: string) {
- await post({
- inputResponses: [{ requestId: requests.get(marker)!.requestId, optionId: "approve" }],
- });
- }
-
- async function post(body: unknown) {
- const response = await t.target.fetch(
- `/eve/v1/session/${encodeURIComponent(started.sessionId)}`,
- {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- signal: t.signal,
- },
- );
- await t.require(response.status, equals(202));
- await response.body?.cancel();
- }
-
- async function nextTurn() {
- const live = t.target.watchTurn(started.sessionId, { startIndex: streamIndex });
- const turn = (await live.result()).expectOk();
- streamIndex = live.session.state!.streamIndex;
- turns.push(turn);
- return turn;
- }
-
- async function throughCompletion(marker: string) {
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const turn = await nextTurn();
- if (
- turn.events.some(
- (event) =>
- event.type === "message.received" &&
- JSON.stringify(event.data.message).includes(marker),
- )
- )
- return turn;
- }
- throw new Error(`The parent did not receive ${marker}.`);
- }
-
- async function through(message: string) {
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const turn = await nextTurn();
- if (turn.message === message) return turn;
- if (turn.message?.startsWith('["REPORT:'))
- throw new Error(`Unexpected report: ${turn.message}`);
- }
- throw new Error(`The parent did not produce ${message}.`);
- }
- },
-});
diff --git a/e2e/fixtures/agent-task-wake-policy/package.json b/e2e/fixtures/agent-task-wake-policy/package.json
deleted file mode 100644
index 5b61938ad..000000000
--- a/e2e/fixtures/agent-task-wake-policy/package.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "name": "agent-task-wake-policy",
- "version": "0.0.0",
- "private": true,
- "type": "module",
- "scripts": {
- "build": "eve build",
- "dev": "eve dev",
- "start": "eve start",
- "typecheck": "eve build --skip-sandbox-prewarm && tsc",
- "test:e2e": "eve eval --strict"
- },
- "dependencies": {
- "@eve-e2e/config": "workspace:*",
- "@workflow/world-postgres": "catalog:",
- "eve": "workspace:*",
- "zod": "catalog:"
- },
- "devDependencies": {
- "@types/node": "catalog:",
- "typescript": "catalog:"
- }
-}
diff --git a/e2e/fixtures/agent-task-wake-policy/tsconfig.json b/e2e/fixtures/agent-task-wake-policy/tsconfig.json
deleted file mode 100644
index 1b9a6162e..000000000
--- a/e2e/fixtures/agent-task-wake-policy/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "esnext",
- "moduleResolution": "bundler",
- "outDir": "dist",
- "rootDir": ".",
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "forceConsistentCasingInFileNames": true,
- "declaration": false,
- "noEmit": true,
- "types": ["node", "eve/workflow-modules"]
- },
- "include": ["agent/**/*.ts", "evals/**/*.ts"]
-}
diff --git a/e2e/fixtures/agent-tools-hitl/agent/lib/continuation/respond.ts b/e2e/fixtures/agent-tools-hitl/agent/lib/continuation/respond.ts
index a4b2cf879..a7b4b12f3 100644
--- a/e2e/fixtures/agent-tools-hitl/agent/lib/continuation/respond.ts
+++ b/e2e/fixtures/agent-tools-hitl/agent/lib/continuation/respond.ts
@@ -10,13 +10,9 @@ const call = (id: string, name: string): MockModelToolCall => ({ id, name, input
// Each sentence is a user instruction in an eval. Results, rather than a mutable
// call counter, select the next response so durable replay uses the same script.
export function respond(request: MockModelRequest): MockModelResponse {
- const isRuntimeContext = (text: string) =>
- text.startsWith("[Task state]") || text.startsWith("Background task ");
- const instructions = request.userMessages.filter((text) => !isRuntimeContext(text));
+ const instructions = request.userMessages;
let message = instructions.at(-1) ?? "";
- const roles = request.messages
- .filter((entry) => entry.role !== "user" || !isRuntimeContext(entry.text))
- .map((entry) => entry.role);
+ const roles = request.messages.map((entry) => entry.role);
const lastResult = request.toolResults.at(-1);
if (lastResult && roles.lastIndexOf("tool") > roles.lastIndexOf("user")) {
// Responding to an older request resumes its instruction. A newer user
@@ -135,28 +131,6 @@ export function respond(request: MockModelRequest): MockModelResponse {
() => `Workflow draft status: ${status("workflow")}. Change A resolved.`,
);
break;
- case "Start the background draft and acknowledge its receipt.":
- response = run(
- [call("background", "background-draft")],
- () => `Background receipt: ${JSON.stringify(result("background")!.output)}`,
- );
- break;
- case "Cancel the background draft task and confirm cancellation.": {
- const receipt = result("background")?.output;
- if (
- receipt === null ||
- typeof receipt !== "object" ||
- !("taskId" in receipt) ||
- typeof receipt.taskId !== "string"
- ) {
- throw new Error("The background tool must return a real task ID before cancellation.");
- }
- response = run(
- [{ id: "cancel", name: "task_cancel", input: { taskIds: [receipt.taskId] } }],
- () => `Cancellation result: ${JSON.stringify(result("cancel")!.output)}`,
- );
- break;
- }
case "Look up the draft with the provider and report its status.":
response = run(
[read("provider-lookup")],
diff --git a/e2e/fixtures/agent-tools-hitl/agent/tools/background-draft.ts b/e2e/fixtures/agent-tools-hitl/agent/tools/background-draft.ts
deleted file mode 100644
index c5aeb32d0..000000000
--- a/e2e/fixtures/agent-tools-hitl/agent/tools/background-draft.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { defineWorkflowTool } from "eve/tools";
-import { sleep } from "workflow";
-import { z } from "zod";
-
-export default defineWorkflowTool({
- description: "Hold a background draft task open until the eval cancels it.",
- execution: "background",
- inputSchema: z.object({}),
- async execute() {
- "use workflow";
- await sleep("10m");
- return { status: "ready" };
- },
-});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/README.md b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/README.md
index 94c0f5cb9..6869ee1ee 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/README.md
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/README.md
@@ -10,7 +10,7 @@ Start with [`read.eval.ts`](./read.eval.ts): leave a change's approval pending,
## Scenario syntax and classification
-Each body uses **Given / When / Then** comments to identify the initial state, accepted input, and observable outcome. `defineEval.description` names the scenario. Native `tags` classify role (`regression` or `control`), triggering input (`user-message` or `input-response`), and behavior (`tool-result`, `tool-error`, `validation`, `workflow`, `provider-result`, `background-task`, `runtime-control`, `approval`, `authorization`, `partial-approval`, `stale-response`, `budget`, or `text-reply`). Every case also carries `hitl` and `continuation`.
+Each body uses **Given / When / Then** comments to identify the initial state, accepted input, and observable outcome. `defineEval.description` names the scenario. Native `tags` classify role (`regression` or `control`), triggering input (`user-message` or `input-response`), and behavior (`tool-result`, `tool-error`, `validation`, `workflow`, `provider-result`, `approval`, `authorization`, `partial-approval`, `stale-response`, `budget`, or `text-reply`). Every case also carries `hitl` and `continuation`.
The tags are filters, not expected verdicts: every case must pass. `eve eval --tag regression`, `--tag control`, or `--tag partial-approval` selects the corresponding conversations. This is ordinary executable `defineEval` code with native assertions; Given / When / Then is not a separate executable spec language.
@@ -18,7 +18,7 @@ The tags are filters, not expected verdicts: every case must pass. `eve eval --t
[`expectReply`](./helpers.ts) requires exactly one matching `message.completed`, followed by exactly one `turn.completed`, both attributed to the same turn. A tool result, unrelated reply, or completion without an answer cannot pass. New messages use their own `message.received` turn ID. Approval responses require successful resolution of the saved request before its matching reply and completion in the delivery's resumed turn. Multiple responses accepted together can resolve across several steps of that one turn; a later resolution need not emit another `turn.started`.
-Each approval ID is saved when emitted. The driver's latest-turn request list is not treated as durable pending state. Tests check that unrelated replies do not execute the old change, then generally approve the saved request and require its execution and completed reply. Runtime-control coverage stops after its answer to avoid mixing later background notifications into that assertion. Budget cases require the next budget request instead of an answer beyond the granted limit.
+Each approval ID is saved when emitted. The driver's latest-turn request list is not treated as durable pending state. Tests check that unrelated replies do not execute the old change, then generally approve the saved request and require its execution and completed reply. Budget cases require the next budget request instead of an answer beyond the granted limit.
## Regressions
@@ -38,8 +38,6 @@ Each row maps to exactly one eval. “Response authorization” here means the f
| Approve older response-authorized request while newer A waits | Read and reply; A remains answerable | [authorized older sibling](./authorized-older-sibling.eval.ts) |
| Approve older ordinary A while a newer response-authorized request waits | Reply for A; newer request remains answerable | [ordinary older sibling](./ordinary-older-sibling.eval.ts) |
| Workflow completes while A waits | Interpret its result | [workflow result](./workflow-result.eval.ts) |
-| Cancel a background task while A waits | Interpret the runtime control result | [runtime control](./runtime-control.eval.ts) |
-| Start a background task while A waits | Acknowledge its working receipt | [background receipt](./background-receipt.eval.ts) |
| Provider supplies a tool result while A waits | Report the distinct provider result | [provider result](./provider-result.eval.ts) |
| Submit A from a same-batch A+B pair, then request a read | Complete the read; later B executes both changes once and completes a reply | [partial approval, tool](./partial-approval-tool.eval.ts) |
| Submit A from a same-batch A+B pair, then request text only | Complete a reply without tools; later B executes both changes once and completes a reply | [partial approval, text](./partial-approval-text.eval.ts) |
@@ -57,8 +55,6 @@ Each row maps to exactly one eval. “Response authorization” here means the f
| Tool throws without older input | Explain the error | [tool error](./tool-error.control.eval.ts) |
| Invalid input without older input | Correct input and report result | [invalid input](./invalid-input.control.eval.ts) |
| Workflow without older input | Interpret its result | [workflow result](./workflow-result.control.eval.ts) |
-| Runtime control without older input | Interpret cancellation result | [runtime control](./runtime-control.control.eval.ts) |
-| Background admission without older input | Acknowledge working receipt | [background receipt](./background-receipt.control.eval.ts) |
| Provider result without older input | Report distinct provider result | [provider result](./provider-result.control.eval.ts) |
| Budget renewal without older approval | Run one tool, then request next grant | [budget grant](./budget-grant.control.eval.ts) |
| Text-only message while A waits | Reply without tools; A remains answerable | [text only](./text-only.control.eval.ts) |
@@ -68,8 +64,8 @@ Each row maps to exactly one eval. “Response authorization” here means the f
## Evidence boundaries
-The [adversarial integration probes](../../../../../../packages/eve/src/harness/issue-3494-adversarial.integration.test.ts) also cover `final_output` with an older approval, multiple independent approvals plus an internally deferred message, and a complete independent batch beside a partially answered batch. Those exact scenarios are **integration-only**, not extra E2E cases. Integration workflow/control results and background receipts are injected at runtime boundaries; the E2E cases execute fixture tools through the durable runtime.
+The [adversarial integration probes](../../../../../../packages/eve/src/harness/issue-3494-adversarial.integration.test.ts) also cover `final_output` with an older approval, multiple independent approvals plus an internally deferred message, and a complete independent batch beside a partially answered batch. Those exact scenarios are **integration-only**, not extra E2E cases. Integration workflow results are injected at runtime boundaries; the E2E cases execute fixture tools through the durable runtime.
-Partial approvals in E2E use an accepted HTTP response followed by a separate user message; the API rejects combined message/response payloads. The provider cases supply a provider-executed result at the scripted model stream boundary; they do not contact a provider that performs the tool. Background coverage establishes admission and acknowledgement, not completion or wake correctness. Runtime control cancels an actual task using its returned ID. Budget scripts report synthetic token usage against the fixture's one-million-output-token limit.
+Partial approvals in E2E use an accepted HTTP response followed by a separate user message; the API rejects combined message/response payloads. The provider cases supply a provider-executed result at the scripted model stream boundary; they do not contact a provider that performs the tool. Budget scripts report synthetic token usage against the fixture's one-million-output-token limit.
These tests serialize inputs. They do not establish restart/replay safety, concurrent-delivery correctness, child-agent settlement, OAuth recovery, or every provider/channel combination. Run E2E only in CI. A timeout identifies a runtime regression only when the captured events establish that the intended setup and tool path ran; a fixture error is not such evidence.
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/background-receipt.control.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/background-receipt.control.eval.ts
deleted file mode 100644
index 11d12aedf..000000000
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/background-receipt.control.eval.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { defineEval } from "eve/evals";
-import { scriptedSession, expectReply } from "./helpers.ts";
-
-export default defineEval({
- description: "Control: background-receipt finishes without an older approval.",
- tags: ["hitl", "continuation", "control", "user-message", "background-task"],
- timeoutMs: 60_000,
- async test(t) {
- // Given a fresh session has no pending approval.
- const session = await t.session();
-
- // When the user asks to start a background draft.
- const live = await session.start(
- "Start the background draft and acknowledge its receipt.",
- scriptedSession,
- );
-
- // Then the reply acknowledges its working receipt; a later cancellation also gets a reply.
- const turn = await expectReply(t, live, /^Background receipt: .*"status":"working"/);
- turn.calledTool("background-draft", { count: 1 });
- await expectReply(
- t,
- await session.start("Cancel the background draft task and confirm cancellation."),
- /Cancellation result: .*"status":"cancelled"/,
- );
- },
-});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/background-receipt.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/background-receipt.eval.ts
deleted file mode 100644
index 49992fb9f..000000000
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/background-receipt.eval.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { defineEval } from "eve/evals";
-import {
- scriptedSession,
- approveSavedChange,
- expectChangeStillUnexecuted,
- expectReply,
- requestFrom,
- expectToolResult,
-} from "./helpers.ts";
-
-export default defineEval({
- description:
- "Starting a background task must produce an acknowledgement while an older approval waits.",
- tags: ["hitl", "continuation", "regression", "user-message", "background-task"],
- timeoutMs: 60_000,
- async test(t) {
- // Given change A is waiting for approval.
- const parked = await t.send("Prepare change A.", scriptedSession);
- const approval = requestFrom(parked, "change-a");
- const session = parked.session;
-
- // When the user asks to start a background draft.
- const live = await session.start("Start the background draft and acknowledge its receipt.");
-
- // Then the reply acknowledges its working receipt; A stays unexecuted and answerable.
- await expectToolResult(t, live, "background-draft");
- const turn = await expectReply(t, live, /^Background receipt: .*"status":"working"/);
- turn.calledTool("background-draft", { count: 1 });
- expectChangeStillUnexecuted(session);
- await approveSavedChange(t, session, approval);
- await expectReply(
- t,
- await session.start("Cancel the background draft task and confirm cancellation."),
- /Cancellation result: .*"status":"cancelled"/,
- );
- },
-});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/runtime-control.control.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/runtime-control.control.eval.ts
deleted file mode 100644
index 7d11a7291..000000000
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/runtime-control.control.eval.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { defineEval } from "eve/evals";
-import { scriptedSession, expectReply } from "./helpers.ts";
-
-export default defineEval({
- description: "Control: runtime-control finishes without an older approval.",
- tags: ["hitl", "continuation", "control", "user-message", "runtime-control", "background-task"],
- timeoutMs: 60_000,
- async test(t) {
- // Given a background draft is running and its receipt has been acknowledged.
- const session = await t.session();
- await expectReply(
- t,
- await session.start(
- "Start the background draft and acknowledge its receipt.",
- scriptedSession,
- ),
- /^Background receipt: .*"status":"working"/,
- );
-
- // When the user asks to cancel that task.
- const live = await session.start("Cancel the background draft task and confirm cancellation.");
-
- // Then task_cancel completes once and its cancellation result gets a completed reply.
- const turn = await expectReply(t, live, /Cancellation result: .*"status":"cancelled"/);
- turn.calledTool("task_cancel", { status: "completed", count: 1 });
- },
-});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/runtime-control.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/runtime-control.eval.ts
deleted file mode 100644
index a712f2a2c..000000000
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/runtime-control.eval.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { defineEval } from "eve/evals";
-import {
- scriptedSession,
- expectChangeStillUnexecuted,
- expectReply,
- requestFrom,
- expectToolResult,
-} from "./helpers.ts";
-
-export default defineEval({
- description: "A task-control result must be interpreted while an older approval waits.",
- tags: [
- "hitl",
- "continuation",
- "regression",
- "user-message",
- "runtime-control",
- "background-task",
- ],
- timeoutMs: 60_000,
- async test(t) {
- // Given a background draft is running and change A is waiting for approval.
- const session = await t.session();
- await expectReply(
- t,
- await session.start(
- "Start the background draft and acknowledge its receipt.",
- scriptedSession,
- ),
- /^Background receipt: .*"status":"working"/,
- );
- const parked = await session.send("Prepare change A.");
- requestFrom(parked, "change-a");
-
- // When the user asks to cancel that task.
- const live = await session.start("Cancel the background draft task and confirm cancellation.");
-
- // Then the reply confirms cancellation and completes; A stays unexecuted.
- await expectToolResult(t, live, "task_cancel");
- const turn = await expectReply(t, live, /Cancellation result: .*"status":"cancelled"/);
- turn.calledTool("task_cancel", { status: "completed", count: 1 });
- expectChangeStillUnexecuted(session);
- },
-});
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/evals.config.ts b/e2e/fixtures/agent-tools-sandbox/evals/evals.config.ts
index 7a61a5b55..d25736e95 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/evals.config.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/evals.config.ts
@@ -3,4 +3,6 @@ import { defineEvalConfig } from "eve/evals";
export default defineEvalConfig({
judge: { model: e2eJudgeModel() },
+ // Evals run without a bound otherwise, so a missed turn would hold CI until its job limit.
+ timeoutMs: 60_000,
});
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts
index fbf648851..31dab1be6 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts
@@ -5,29 +5,14 @@ const TOKEN = "custom-provider-session-ok-P7M";
export default defineEval({
description: "Sandbox: custom provider session methods survive framework lifecycle wrapping.",
- timeoutMs: 60_000,
async test(t) {
const turn = await t.send(
"Ask the `custom-provider` subagent with message: Verify the custom provider session marker.",
);
turn.expectOk();
- const sessionId = turn.sessionId;
- if (sessionId === undefined) throw new Error("Custom provider turn has no session id.");
- const completed = await t.target
- .watchTurn(sessionId, { startIndex: requireStreamIndex(turn.session) })
- .result();
- completed.expectOk();
t.succeeded();
t.calledSubagent("custom-provider", { count: 1, status: "completed" });
- t.check(completed.message, includes(TOKEN));
+ t.check(turn.message, includes(TOKEN));
},
});
-
-function requireStreamIndex(session: {
- readonly state?: { readonly streamIndex?: number };
-}): number {
- const streamIndex = session.state?.streamIndex;
- if (streamIndex === undefined) throw new Error("Custom provider turn has no stream index.");
- return streamIndex;
-}
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/open-network-policy.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/open-network-policy.eval.ts
index 08feb6e83..8668c0314 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/open-network-policy.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/open-network-policy.eval.ts
@@ -3,7 +3,6 @@ import { includes } from "eve/evals/expect";
export default defineEval({
description: "Sandbox: an open-time deny-all policy applies before authored commands run.",
- timeoutMs: 60_000,
async test(t) {
const turn = await t.send(
"Ask the `deny-all` subagent with message: " +
@@ -11,24 +10,9 @@ export default defineEval({
"and reply with the command output verbatim.",
);
turn.expectOk();
- const sessionId = turn.sessionId;
- if (sessionId === undefined) throw new Error("Deny-all sandbox turn has no session id.");
- const completed = t.target.watchTurn(sessionId, {
- startIndex: requireStreamIndex(turn.session),
- });
- const child = await completed.result();
- child.expectOk();
t.succeeded();
t.calledSubagent("deny-all", { count: 1, status: "completed" });
- t.check(child.message, includes("blocked-egress"));
+ t.check(turn.message, includes("blocked-egress"));
},
});
-
-function requireStreamIndex(session: {
- readonly state?: { readonly streamIndex?: number };
-}): number {
- const streamIndex = session.state?.streamIndex;
- if (streamIndex === undefined) throw new Error("Deny-all sandbox turn has no stream index.");
- return streamIndex;
-}
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/parent-inheritance.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/parent-inheritance.eval.ts
index aad36eb5b..6a413c100 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/parent-inheritance.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/parent-inheritance.eval.ts
@@ -22,16 +22,9 @@ export default defineEval({
"and reply with the command output verbatim.",
);
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(childTurn.session),
- });
- const childCompletion = await completed.result();
- childCompletion.expectOk();
- await t.require(childCompletion.message, includes(PARENT_TOKEN));
+ await t.require(childTurn.message, includes(PARENT_TOKEN));
- const parentRead = await completed.session.send(
+ const parentRead = await conversation.send(
`Run the bash command \`cat ${CHILD_PATH}\` and reply with the file contents verbatim.`,
);
@@ -40,11 +33,3 @@ export default defineEval({
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-tools-sandbox/evals/sandbox/typed-environment-capability.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/typed-environment-capability.eval.ts
index 3a2e9fa5b..1feac8483 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/typed-environment-capability.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/typed-environment-capability.eval.ts
@@ -3,17 +3,12 @@ import { defineEval } from "eve/evals";
export default defineEval({
description:
"Sandbox: ctx.getSandbox(environment) exposes the configured environment's capabilities.",
- timeoutMs: 60_000,
async test(t) {
const turn = await t.send(
"Ask the `deny-all` subagent with message: Verify the configured environment sandbox capability.",
);
turn.expectOk();
- const completed = await t.target
- .watchTurn(turn.sessionId, { startIndex: requireStreamIndex(turn.session) })
- .result();
- completed.expectOk();
- const called = completed.events.find(
+ const called = turn.events.find(
(event) => event.type === "subagent.called" && event.data.name === "deny-all",
);
if (called?.type !== "subagent.called") {
@@ -28,11 +23,3 @@ export default defineEval({
childTurn.calledTool("verify-typed-sandbox", { output: { blocked: true } });
},
});
-
-function requireStreamIndex(session: {
- readonly state?: { readonly streamIndex?: number };
-}): number {
- const streamIndex = session.state?.streamIndex;
- if (streamIndex === undefined) throw new Error("Typed sandbox turn has no stream index.");
- return streamIndex;
-}
diff --git a/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts b/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts
index 20112d6c0..a236e0593 100644
--- a/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts
@@ -30,11 +30,7 @@ function preToolNarration(events: readonly MessageStreamEvent[]): string | undef
for (let index = actionRequestIndex - 1; index >= 0; index -= 1) {
const event = events[index];
- if (
- event?.type === "message.completed" &&
- event.data.finishReason === "tool-calls" &&
- event.data.message !== null
- ) {
+ if (event?.type === "message.completed" && event.data.finishReason === "tool-calls") {
return firstNonEmptyLine(event.data.message);
}
}
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/to-model-output-content-parts.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/to-model-output-content-parts.eval.ts
index 0a506705b..8d05dcd9e 100644
--- a/e2e/fixtures/agent-tools/evals/static-tools/to-model-output-content-parts.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/static-tools/to-model-output-content-parts.eval.ts
@@ -69,7 +69,6 @@ function assistantAnswers(events: readonly MessageStreamEvent[]): readonly strin
return events.flatMap((event) =>
event.type === "message.completed" &&
event.data.finishReason !== "tool-calls" &&
- event.data.message !== null &&
event.data.message.trim().length > 0
? [event.data.message]
: [],
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/web-search-ordering.ts b/e2e/fixtures/agent-tools/evals/static-tools/web-search-ordering.ts
index b5123dc9a..d737efcce 100644
--- a/e2e/fixtures/agent-tools/evals/static-tools/web-search-ordering.ts
+++ b/e2e/fixtures/agent-tools/evals/static-tools/web-search-ordering.ts
@@ -67,7 +67,6 @@ function preToolNarrationExists(
(event) =>
event.type === "message.completed" &&
event.data.finishReason === "tool-calls" &&
- event.data.message !== null &&
event.data.message.trim().length > 0,
);
}
@@ -79,9 +78,6 @@ function finalMessageFollowsResult(
return events
.slice(resultIndex + 1)
.some(
- (event) =>
- event.type === "message.completed" &&
- event.data.finishReason !== "tool-calls" &&
- event.data.message !== null,
+ (event) => event.type === "message.completed" && event.data.finishReason !== "tool-calls",
);
}
diff --git a/e2e/fixtures/agent-workflow-tools/agent/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
index 3ddc64142..4e06a74fb 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/agent.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
@@ -16,7 +16,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
toolCalls: [{ id: skillCallId, name: "load_skill", input: { skill: "delegation-policy" } }],
};
}
- const mode = /SUBAGENT-HOOKS:(direct|waiting|background)/u.exec(hookScenario)?.[1];
+ const mode = /SUBAGENT-HOOKS:(direct|waiting)/u.exec(hookScenario)?.[1];
if (auditing) {
const auditTool = request.lastUserMessage?.includes("DYNAMIC-SKILL-CONTEXT")
? "read_dynamic_skill_context"
@@ -26,12 +26,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
? { toolCalls: [{ name: auditTool, input: {} }] }
: JSON.stringify(audit.output);
}
- const tool =
- mode === "direct"
- ? "workflow-marker"
- : mode === "waiting"
- ? "blocking_agent"
- : "background_agent";
+ const tool = mode === "direct" ? "workflow-marker" : "blocking_agent";
if (!request.toolResults.some((entry) => entry.name === tool)) {
return {
toolCalls: [
@@ -43,24 +38,14 @@ function respond(request: MockModelRequest): MockModelResponse | string {
],
};
}
- const delivery = [...request.userMessages]
- .reverse()
- .find((entry) => entry.startsWith("[Task state]\n") || entry.startsWith("Background task "));
const result = request.toolResults.find((entry) => entry.name === tool);
- return (
- delivery ??
- (typeof result?.output === "string" ? result.output : JSON.stringify(result?.output))
- );
+ return typeof result?.output === "string" ? result.output : JSON.stringify(result?.output);
}
const message =
[...request.userMessages]
.reverse()
- .find(
- (entry) =>
- /^(WORKFLOW-|(?:Background task|Deploy) task_)/u.test(entry) ||
- entry.includes("private-catalog"),
- ) ?? "";
+ .find((entry) => entry.startsWith("WORKFLOW-") || entry.includes("private-catalog")) ?? "";
if (message.includes("private-catalog")) {
const result = request.toolResults.find((entry) => entry.name === "connection_search");
if (result === undefined) {
@@ -93,25 +78,9 @@ function respond(request: MockModelRequest): MockModelResponse | string {
}
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"],
["WORKFLOW-CONFIRM-START", "confirm_deploy"],
- ["WORKFLOW-REPORT-START", "report_deploy"],
["WORKFLOW-ESCALATE-START", "escalate_deploy"],
["WORKFLOW-HOLD-START", "hold_deploy"],
["WORKFLOW-FANOUT-START", "fanout_deploy"],
@@ -129,16 +98,6 @@ 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";
- }
-
return "WORKFLOW-IDLE";
}
diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/agent-reply.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/agent-reply.ts
new file mode 100644
index 000000000..32bb378cd
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/agent-reply.ts
@@ -0,0 +1,13 @@
+import type { WorkflowToolContext } from "eve/tools";
+
+/** Sends one message to a new session with `name` and returns its reply. */
+export async function replyFrom(
+ ctx: WorkflowToolContext,
+ name: string,
+ message: string,
+): Promise<string | null> {
+ const response = await ctx.agent(name).send(message);
+ const result = await response.result();
+ if (result.status === "failed") throw new Error(`Agent "${name}" failed.`);
+ return result.message ?? null;
+}
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
index 66f0af13f..695fbfd40 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/lib/workflow-agent-probe.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/workflow-agent-probe.ts
@@ -1,6 +1,8 @@
import type { WorkflowToolContext } from "eve/tools";
import { z } from "zod";
+import { replyFrom } from "./agent-reply.ts";
+
export const workflowAgentProbeInputSchema = z.strictObject({
kind: z.enum(["auth", "hitl"]),
});
@@ -8,8 +10,7 @@ export const workflowAgentProbeInputSchema = z.strictObject({
export async function executeWorkflowAgentProbe(
input: z.infer<typeof workflowAgentProbeInputSchema>,
ctx: WorkflowToolContext,
-): Promise<unknown> {
- return await ctx.agent(input.kind === "hitl" ? "workflow-hitl" : "workflow-auth", {
- message: `Run the ${input.kind} probe.`,
- });
+): Promise<string | null> {
+ const name = input.kind === "hitl" ? "workflow-hitl" : "workflow-auth";
+ return await replyFrom(ctx, name, `Run the ${input.kind} probe.`);
}
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts
deleted file mode 100644
index 1c8492a97..000000000
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { defineWorkflowTool } from "eve/tools";
-import { z } from "zod";
-
-export default defineWorkflowTool({
- 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 ctx.agent("workflow-marker", {
- message: `${service}:background`,
- });
- },
-});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts
index 76ed2152c..7c9cf0894 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts
@@ -1,14 +1,14 @@
import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
+import { replyFrom } from "../lib/agent-reply.ts";
+
export default defineWorkflowTool({
description: "Run one subagent from a waiting workflow tool.",
inputSchema: z.strictObject({ service: z.string() }),
async execute({ service }, ctx) {
"use workflow";
- return await ctx.agent("workflow-marker", {
- message: `${service}:blocking`,
- });
+ return await replyFrom(ctx, "workflow-marker", `${service}:blocking`);
},
});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts
index c906a5855..6b4a9ea16 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts
@@ -1,6 +1,8 @@
import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
+import { replyFrom } from "../lib/agent-reply.ts";
+
export default defineWorkflowTool({
description: "Call two workflow-owned subagents in parallel and return both inline results.",
inputSchema: z.strictObject({ service: z.string() }),
@@ -8,12 +10,8 @@ export default defineWorkflowTool({
"use workflow";
return await Promise.all([
- ctx.agent("workflow-marker", {
- message: `${service}:replica-0`,
- }),
- ctx.agent("workflow-marker", {
- message: `${service}:replica-1`,
- }),
+ replyFrom(ctx, "workflow-marker", `${service}:replica-0`),
+ replyFrom(ctx, "workflow-marker", `${service}:replica-1`),
]);
},
});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts
deleted file mode 100644
index 1cdd387f3..000000000
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { defineWorkflowTool } from "eve/tools";
-import { z } from "zod";
-
-import { describePlan, hashPlan } from "../lib/plan.ts";
-
-/**
- * Background workflow tool: the model gets a receipt, intermediate yields are consumed,
- * and the return value reaches the parent in the terminal cohort report.
- */
-export default defineWorkflowTool({
- description: "Plan a deploy in the background and report when it is ready.",
- execution: "background",
- inputSchema: z.strictObject({ service: z.string() }),
- async *execute({ service }) {
- "use workflow";
-
- const plan = describePlan(service);
- yield { plan };
- yield { message: "WORKFLOW-REPORT-PROGRESS", plan };
- const digest = await hashPlan(plan);
- return { digest, plan, result: "WORKFLOW-REPORT-COMPLETE" };
- },
-});
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
index f0831470a..5e37a7557 100644
--- a/e2e/fixtures/agent-workflow-tools/evals/agent-fanout.wait.eval.ts
+++ b/e2e/fixtures/agent-workflow-tools/evals/agent-fanout.wait.eval.ts
@@ -2,30 +2,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.",
+ "An authored waiting workflow tool blocks on two parallel ctx.agent sessions 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.eventsSatisfy("parallel invocations keep distinct calls and child sessions", (events) => {
- const calls = events.flatMap((event) =>
- event.type === "subagent.called" && event.data.name === "workflow-marker"
- ? [event.data]
- : [],
+ turn.event("agent.started", { data: { name: "workflow-marker" }, count: 2 });
+ turn.eventsSatisfy("parallel sessions are distinct children of one tool call", (events) => {
+ const started = events.flatMap((event) =>
+ event.type === "agent.started" && event.data.name === "workflow-marker" ? [event.data] : [],
);
return (
- calls.length === 2 &&
- new Set(calls.map((call) => call.callId)).size === 2 &&
- new Set(calls.map((call) => call.childSessionId)).size === 2
+ started.length === 2 &&
+ new Set(started.map((session) => session.callId)).size === 1 &&
+ new Set(started.map((session) => session.sessionId)).size === 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] : [],
+ event.type === "agent.started" && event.data.name === "workflow-marker" ? [index] : [],
);
const toolResult = events.findIndex(
(event) =>
diff --git a/e2e/fixtures/agent-workflow-tools/evals/agent-probe.shared.ts b/e2e/fixtures/agent-workflow-tools/evals/agent-probe.shared.ts
index ff7d64aff..ed9bbbaf2 100644
--- a/e2e/fixtures/agent-workflow-tools/evals/agent-probe.shared.ts
+++ b/e2e/fixtures/agent-workflow-tools/evals/agent-probe.shared.ts
@@ -11,28 +11,23 @@ type SessionCursor = Pick<
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 started = await t.send(directive);
+ started.expectOk();
const blocked = await waitForInput(t, started.session, "approval-gate");
const approved = await blocked.respondAll("approve");
approved.expectOk();
await waitForMarker(t, blocked, approved, "WORKFLOW-HITL:approved");
} else {
- const required = await waitForEvent(t, started.session, 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");
+ const { turn } = await completeSignIn(t, directive, (url) => {
+ if (url === undefined) {
+ throw new Error("Authorization probe produced no callback URL.");
+ }
+ return new URL(url);
+ });
+ requireAuthorizationOutcome(turn, "authorized");
+ requireMarker(turn, "WORKFLOW-AUTH:authorized");
}
t.succeeded();
@@ -87,36 +82,44 @@ async function waitForMarker(
throw new Error(`Probe did not produce ${marker}.`);
}
-async function waitForEvent<T extends "authorization.completed" | "authorization.required">(
+/**
+ * A sign-in inside a running call parks the turn without ending it, so read
+ * one live turn: complete the sign-in when it is requested, then read the
+ * turn to its end.
+ */
+async function completeSignIn(
t: EveEvalContext,
- initial: SessionCursor,
- initialTurn: EveEvalTurn | undefined,
- type: T,
- options: { allowFailedActions?: boolean } = {},
-): Promise<{
- readonly event: EveEvalStreamEvent<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 EveEvalStreamEvent<T> => candidate.type === type,
- );
- if (event !== undefined) {
- return { event, session };
- }
+ message: string,
+ toCallbackUrl: (authorizationUrl: string | undefined) => URL,
+): Promise<{ readonly callbackUrl: URL; readonly turn: EveEvalTurn }> {
+ const session = await t.session();
+ const live = await session.start(message);
+ const required = await live.waitForEvent("authorization.required");
+ const callbackUrl = toCallbackUrl(required.data.authorization?.url);
+ const response = await fetch(callbackUrl);
+ if (!response.ok) {
+ throw new Error(`Authorization callback failed (${response.status}).`);
+ }
+ return { callbackUrl, turn: await live.result() };
+}
- const live = watchNext(t, session);
- turn = await live.result();
- if (!options.allowFailedActions) {
- turn.noFailedActions();
- }
- session = live.session;
+function requireAuthorizationOutcome(
+ turn: EveEvalTurn,
+ outcome: EveEvalStreamEvent<"authorization.completed">["data"]["outcome"],
+): void {
+ const completed = turn.events.filter(
+ (event): event is EveEvalStreamEvent<"authorization.completed"> =>
+ event.type === "authorization.completed",
+ );
+ if (completed.length !== 1 || completed[0]?.data.outcome !== outcome) {
+ throw new Error(`Expected one authorization.completed with outcome "${outcome}".`);
}
+}
- throw new Error(`Probe did not surface ${type}.`);
+function requireMarker(turn: EveEvalTurn, marker: string): void {
+ if (!turn.message?.includes(marker)) {
+ throw new Error(`Probe did not produce ${marker}.`);
+ }
}
function watchNext(t: EveEvalContext, session: SessionCursor) {
@@ -130,38 +133,21 @@ export async function runStepAuth(
t: EveEvalContext,
scenario: "EXPLICIT" | "IMPLICIT",
): Promise<void> {
- const started = await t.send(`WORKFLOW-STEP-AUTH-${scenario}`);
- const required = await waitForEvent(t, started.session, started, "authorization.required");
-
- const url = fixtureAuthorizationCallback(t.target.url, required.event.data.authorization?.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-STEP-AUTH:authorized");
+ const { turn } = await completeSignIn(t, `WORKFLOW-STEP-AUTH-${scenario}`, (url) =>
+ fixtureAuthorizationCallback(t.target.url, url),
+ );
+ requireAuthorizationOutcome(turn, "authorized");
+ requireMarker(turn, "WORKFLOW-STEP-AUTH:authorized");
t.noFailedActions();
}
export async function runRejectedStepAuth(t: EveEvalContext): Promise<void> {
- const started = await t.send("WORKFLOW-STEP-AUTH-REJECTED");
- const required = await waitForEvent(t, started.session, started, "authorization.required");
-
- const url = fixtureAuthorizationCallback(t.target.url, required.event.data.authorization?.url);
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Authorization callback failed (${response.status}).`);
- }
-
- const completed = await waitForEvent(t, required.session, undefined, "authorization.completed", {
- allowFailedActions: true,
- });
- if (completed.event.data.outcome !== "failed") {
- throw new Error("A token rejected immediately after sign-in must fail authorization.");
- }
+ const { callbackUrl, turn } = await completeSignIn(t, "WORKFLOW-STEP-AUTH-REJECTED", (url) =>
+ fixtureAuthorizationCallback(t.target.url, url),
+ );
+ requireAuthorizationOutcome(turn, "failed");
- const repeatedCallback = await fetch(url);
+ const repeatedCallback = await fetch(callbackUrl);
if (repeatedCallback.status !== 404) {
throw new Error("The completed authorization callback must be disposed.");
}
diff --git a/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts
index 14861d66c..27a4d8ec2 100644
--- a/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts
+++ b/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts
@@ -1,4 +1,4 @@
-import { defineEval, type EveEvalTargetHandle } from "eve/evals";
+import { defineEval, type EveEvalTargetHandle, type EveEvalTurn } from "eve/evals";
import { equals } from "eve/evals/expect";
import type { DynamicSkillContextObservation } from "../dynamic-skill-context-audit";
@@ -28,7 +28,20 @@ function expectedAuth(actor: "alice" | "bob") {
};
}
-export default (["direct", "waiting", "background"] as const).map((mode) =>
+/** The child's reply: a `subagent.completed` event for the model's agent tool, the tool result for `ctx.agent`. */
+function readChildOutput(turn: EveEvalTurn, mode: "direct" | "waiting"): string {
+ if (mode === "waiting") {
+ const output = turn.toolCalls.find((call) => call.name === "blocking_agent")?.output;
+ if (typeof output !== "string") throw new Error("The waiting tool's child reply is missing.");
+ return output;
+ }
+ const completion = turn.events.find((event) => event.type === "subagent.completed");
+ if (completion?.type !== "subagent.completed")
+ throw new Error("The delegated child's completion event is missing.");
+ return completion.data.output;
+}
+
+export default (["direct", "waiting"] as const).map((mode) =>
defineEval({
description: `${mode} delegation preserves every dynamic-skill resolver context field across session start and later turns.`,
async test(t) {
@@ -40,30 +53,15 @@ export default (["direct", "waiting", "background"] as const).map((mode) =>
const initial = await t.target.watchTurn(started.sessionId).result();
initial.expectOk();
initial.calledTool("load_skill", { count: 1, status: "completed" });
- const completed =
- mode === "waiting"
- ? initial
- : await t.target
- .watchTurn(started.sessionId, { startIndex: initial.session.state.streamIndex })
- .result();
- completed.expectOk();
- const marker =
- mode === "direct"
- ? "Alice's hook audit"
- : `hook-audit:${mode === "waiting" ? "blocking" : "background"}`;
- const completion = [...initial.events, ...completed.events].find(
- (event) => event.type === "subagent.completed",
- );
- if (completion?.type !== "subagent.completed")
- throw new Error("The delegated child's completion event is missing.");
- const childOutput = completion.data.output;
+ const marker = mode === "direct" ? "Alice's hook audit" : "hook-audit:blocking";
+ const childOutput = readChildOutput(initial, mode);
t.check(childOutput.startsWith("WORKFLOW-CHILD:"), equals(true)).label(
"child returned its report",
);
t.check(childOutput.includes(marker), equals(true)).label("child report includes its task");
- completed.messageIncludes(childOutput);
+ initial.messageIncludes(childOutput);
- const startIndex = completed.session.state.streamIndex;
+ const startIndex = initial.session.state.streamIndex;
const resumed = await send(t.target, threadId, "bob", followUp);
t.check(resumed.sessionId, equals(started.sessionId)).label(
"same parent session after delegation",
@@ -80,12 +78,7 @@ export default (["direct", "waiting", "background"] as const).map((mode) =>
const observations = output as DynamicSkillContextObservation[];
t.check(
observations.map((entry) => entry.event),
- equals([
- "session.started",
- "turn.started",
- ...(mode === "waiting" ? [] : ["turn.started"]),
- "turn.started",
- ]),
+ equals(["session.started", "turn.started", "turn.started"]),
).label("resolver runs once at session start and at every parent turn boundary");
for (const [index, { context, event }] of observations.entries()) {
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
deleted file mode 100644
index ee7ba3ecf..000000000
--- a/e2e/fixtures/agent-workflow-tools/evals/mixed-agent-resolution.eval.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { defineEval, type EveEvalSession, type EveEvalTurn } 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" } });
- 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.");
- let session: Pick<EveEvalSession, "state"> = initial.session;
- let completed: EveEvalTurn | undefined;
- for (let attempt = 0; attempt < 5; attempt += 1) {
- const live = t.target.watchTurn(sessionId, { startIndex: requireStreamIndex(session) });
- const turn = await live.result();
- turn.expectOk();
- if (turn.message?.includes("WORKFLOW-REPORT-ACK")) {
- completed = turn;
- break;
- }
- session = live.session;
- }
- if (completed === undefined) {
- throw new Error("Background workflow result did not reach the parent after five turns.");
- }
- 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/agent-workflow-tools/evals/report-deploy.background.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/report-deploy.background.eval.ts
deleted file mode 100644
index 3b5ec057a..000000000
--- a/e2e/fixtures/agent-workflow-tools/evals/report-deploy.background.eval.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { defineEval } from "eve/evals";
-import { satisfies } from "eve/evals/expect";
-
-export default defineEval({
- description:
- "A background workflow tool returns a receipt, consumes intermediate yields without progress notifications, and reports its return value.",
- async test(t) {
- const started = await t.send("WORKFLOW-REPORT-START");
- const conversation = started.session;
- started.expectOk();
- started.calledTool("report_deploy");
- started.notEvent("action.partial");
-
- const receipt = started.requireToolCall("report_deploy");
- const taskId = readTaskId(receipt.output);
- if (taskId === undefined) throw new Error("report_deploy receipt is missing taskId.");
-
- const sessionId = conversation.sessionId;
- if (sessionId === undefined) throw new Error("Eval has no parent session id.");
-
- const doneLive = t.target.watchTurn(sessionId, {
- startIndex: requireStreamIndex(started.session, "completion wait"),
- });
- const doneTurn = await doneLive.result();
- doneTurn.expectOk();
- doneTurn.messageIncludes("WORKFLOW-REPORT-DONE");
- await t.require(
- doneTurn.events,
- satisfies(
- (events: typeof doneTurn.events) =>
- events.some(
- (event) =>
- event.type === "message.received" &&
- messageText(event.data.message).includes(
- `Background task ${taskId} (report_deploy) is completed.`,
- ) &&
- messageText(event.data.message).includes("WORKFLOW-REPORT-COMPLETE"),
- ),
- "parent receives the run's return value with task identity",
- ),
- );
- doneTurn.event("turn.started", { count: 1 });
- doneTurn.notEvent("action.partial");
- doneTurn.notEvent("message.received", {
- data: (data) => messageText(data.message).includes("PROGRESS"),
- });
- t.noFailedActions();
- },
-});
-
-function readTaskId(output: unknown): string | undefined {
- if (output === null || typeof output !== "object") return undefined;
- const taskId = Reflect.get(output, "taskId");
- return typeof taskId === "string" ? taskId : undefined;
-}
-
-function requireStreamIndex(
- session: { readonly state?: { readonly streamIndex?: number } },
- operation: string,
-): number {
- const streamIndex = session.state?.streamIndex;
- if (streamIndex === undefined) throw new Error(`${operation} has no session stream index.`);
- return streamIndex;
-}
-
-function messageText(message: unknown): string {
- if (typeof message === "string") return message;
- return JSON.stringify(message);
-}
diff --git a/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts
index 326093220..09715a54f 100644
--- a/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts
+++ b/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts
@@ -1,96 +1,85 @@
import { defineEval } from "eve/evals";
import type { SubagentHookObservation } from "../subagent-hook-audit";
-export default (["direct", "waiting", "background"] as const).map((mode) =>
- defineEval({
- description: `${mode} delegation and later wildcard hooks continue after a typed hook writes parent state and throws.`,
- async test(t) {
- const initial = await t.send(
- `Alice asks Bob to review a short report and return his result. SUBAGENT-HOOKS:${mode}`,
- );
- initial.expectOk();
- initial.calledTool("load_skill", { count: 1, status: "completed" });
- const marker =
- mode === "direct"
- ? "Alice's hook audit"
- : `hook-audit:${mode === "waiting" ? "blocking" : "background"}`;
- const completed =
- mode === "waiting"
- ? initial
- : await t.target
- .watchTurn(initial.sessionId, { startIndex: initial.session.state.streamIndex })
- .result();
- completed.expectOk();
- completed.messageIncludes(marker);
+// Only the model's agent tools publish subagent.* events; ctx.agent sessions publish agent.started.
+export default defineEval({
+ description:
+ "Delegation and later wildcard hooks continue after a typed hook writes parent state and throws.",
+ async test(t) {
+ const initial = await t.send(
+ "Alice asks Bob to review a short report and return his result. SUBAGENT-HOOKS:direct",
+ );
+ initial.expectOk();
+ initial.calledTool("load_skill", { count: 1, status: "completed" });
+ initial.messageIncludes("Alice's hook audit");
- const audit = await completed.session.send(
- "Alice reviews the recorded hook observations for Bob's completed report. SUBAGENT-HOOKS:AUDIT",
- );
- audit.expectOk();
- audit.calledTool("load_skill", { count: 1, status: "completed" });
- t.eventsSatisfy("the parent's dynamic skill remains loadable after delegation", () =>
- [initial, audit].every((turn) =>
- String(turn.toolCalls.find((call) => call.name === "load_skill")?.output).includes(
- "DELEGATION-POLICY:",
- ),
+ const audit = await initial.session.send(
+ "Alice reviews the recorded hook observations for Bob's completed report. SUBAGENT-HOOKS:AUDIT",
+ );
+ audit.expectOk();
+ audit.calledTool("load_skill", { count: 1, status: "completed" });
+ t.eventsSatisfy("the parent's dynamic skill remains loadable after delegation", () =>
+ [initial, audit].every((turn) =>
+ String(turn.toolCalls.find((call) => call.name === "load_skill")?.output).includes(
+ "DELEGATION-POLICY:",
),
- );
- audit.calledTool("read_subagent_hooks", { count: 1, status: "completed" });
- const observations = audit.toolCalls.find(
- (call) => call.name === "read_subagent_hooks",
- )?.output;
- t.eventsSatisfy(
- "both hook subscriptions receive the parent's exact child result once",
- (events) => {
- if (!Array.isArray(observations) || observations.length !== 4) return false;
- const completion = events.find((event) => event.type === "subagent.completed");
- if (completion?.type !== "subagent.completed") return false;
- if (!completion.data.output.startsWith("WORKFLOW-CHILD:")) return false;
- if (!completed.message?.includes(completion.data.output)) return false;
- const records = observations as SubagentHookObservation[];
- return (
- records.every(
- (record) =>
- record.sessionId === initial.sessionId && record.callId === completion.data.callId,
- ) &&
- (["typed", "wildcard"] as const).every(
- (subscriber) =>
- records.filter(
- (record) => record.subscriber === subscriber && record.type === "subagent.called",
- ).length === 1 &&
- records.filter(
- (record) =>
- record.subscriber === subscriber &&
- record.type === "subagent.completed" &&
- record.output === completion.data.output,
- ).length === 1,
- )
- );
- },
- );
- t.eventsSatisfy(
- "hooks receive the exact published event IDs",
- (events) =>
- Array.isArray(observations) &&
- observations.every((record: SubagentHookObservation) =>
- events.some((event) => event.meta.id === record.eventId && event.type === record.type),
- ),
- );
- t.eventsSatisfy(
- "hooks persist parent sandbox files for the next turn",
- () =>
- Array.isArray(observations) &&
- observations.every(
- (record: SubagentHookObservation & { sandboxCallId: string | null }) =>
- record.sandboxCallId === record.callId,
- ),
- );
- t.event("subagent.called", { data: { name: "workflow-marker" }, count: 1 });
- t.event("subagent.completed", { data: { subagentName: "workflow-marker" }, count: 1 });
- t.notEvent("session.failed");
- t.notEvent("turn.failed");
- t.noFailedActions();
- t.succeeded();
- },
- }),
-);
+ ),
+ );
+ audit.calledTool("read_subagent_hooks", { count: 1, status: "completed" });
+ const observations = audit.toolCalls.find(
+ (call) => call.name === "read_subagent_hooks",
+ )?.output;
+ t.eventsSatisfy(
+ "both hook subscriptions receive the parent's exact child result once",
+ (events) => {
+ if (!Array.isArray(observations) || observations.length !== 4) return false;
+ const completion = events.find((event) => event.type === "subagent.completed");
+ if (completion?.type !== "subagent.completed") return false;
+ if (!completion.data.output.startsWith("WORKFLOW-CHILD:")) return false;
+ if (!initial.message?.includes(completion.data.output)) return false;
+ const records = observations as SubagentHookObservation[];
+ return (
+ records.every(
+ (record) =>
+ record.sessionId === initial.sessionId && record.callId === completion.data.callId,
+ ) &&
+ (["typed", "wildcard"] as const).every(
+ (subscriber) =>
+ records.filter(
+ (record) => record.subscriber === subscriber && record.type === "subagent.called",
+ ).length === 1 &&
+ records.filter(
+ (record) =>
+ record.subscriber === subscriber &&
+ record.type === "subagent.completed" &&
+ record.output === completion.data.output,
+ ).length === 1,
+ )
+ );
+ },
+ );
+ t.eventsSatisfy(
+ "hooks receive the exact published event IDs",
+ (events) =>
+ Array.isArray(observations) &&
+ observations.every((record: SubagentHookObservation) =>
+ events.some((event) => event.meta.id === record.eventId && event.type === record.type),
+ ),
+ );
+ t.eventsSatisfy(
+ "hooks persist parent sandbox files for the next turn",
+ () =>
+ Array.isArray(observations) &&
+ observations.every(
+ (record: SubagentHookObservation & { sandboxCallId: string | null }) =>
+ record.sandboxCallId === record.callId,
+ ),
+ );
+ t.event("subagent.called", { data: { name: "workflow-marker" }, count: 1 });
+ t.event("subagent.completed", { data: { subagentName: "workflow-marker" }, count: 1 });
+ t.notEvent("session.failed");
+ t.notEvent("turn.failed");
+ t.noFailedActions();
+ t.succeeded();
+ },
+});
diff --git a/e2e/fixtures/e2e-config/package.json b/e2e/fixtures/e2e-config/package.json
index ff6c4367e..d3f33222d 100644
--- a/e2e/fixtures/e2e-config/package.json
+++ b/e2e/fixtures/e2e-config/package.json
@@ -6,8 +6,7 @@
"exports": {
".": "./src/index.ts",
"./instrumentation": "./src/instrumentation.ts",
- "./instrumentation-otel": "./src/instrumentation-otel.ts",
- "./task-receipts": "./src/task-receipts.ts"
+ "./instrumentation-otel": "./src/instrumentation-otel.ts"
},
"scripts": {
"test:integration": "node --test test/*.integration.test.mjs",
diff --git a/e2e/fixtures/e2e-config/src/task-receipts.ts b/e2e/fixtures/e2e-config/src/task-receipts.ts
deleted file mode 100644
index a43db7b02..000000000
--- a/e2e/fixtures/e2e-config/src/task-receipts.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { EveEvalTurn } from "eve/evals";
-
-/** Admission receipts are tool results; subagent completion carries the child's final output. */
-export function taskReceipts(events: EveEvalTurn["events"]) {
- return events.flatMap((event) => {
- if (event.type !== "action.result" || event.data.status !== "completed") return [];
- const result = event.data.result;
- if (result.kind !== "tool-result") return [];
- const output = result.output;
- if (
- typeof output !== "object" ||
- output === null ||
- Array.isArray(output) ||
- Reflect.get(output, "status") !== "working"
- )
- return [];
- const taskId: unknown = Reflect.get(output, "taskId");
- if (typeof taskId !== "string") return [];
- return [{ callId: result.callId, taskId, toolName: result.toolName }];
- });
-}
diff --git a/e2e/fixtures/fixture-tasks/.gitignore b/e2e/fixtures/fixture-tasks/.gitignore
deleted file mode 100644
index 9a7c2abb6..000000000
--- a/e2e/fixtures/fixture-tasks/.gitignore
+++ /dev/null
@@ -1,11 +0,0 @@
-node_modules
-.env*
-.eve
-.vercel
-.next
-.output
-.nitro
-dist
-.DS_Store
-*.tsbuildinfo
-.env*.local
diff --git a/e2e/fixtures/fixture-tasks/.vercelignore b/e2e/fixtures/fixture-tasks/.vercelignore
deleted file mode 100644
index 357664320..000000000
--- a/e2e/fixtures/fixture-tasks/.vercelignore
+++ /dev/null
@@ -1,6 +0,0 @@
-node_modules
-.eve
-.next
-.output
-.nitro
-dist
diff --git a/e2e/fixtures/fixture-tasks/agent/agent.ts b/e2e/fixtures/fixture-tasks/agent/agent.ts
deleted file mode 100644
index 93e5a7d60..000000000
--- a/e2e/fixtures/fixture-tasks/agent/agent.ts
+++ /dev/null
@@ -1,721 +0,0 @@
-import { e2eAgentConfig } from "@eve-e2e/config";
-import { defineAgent } from "eve";
-import {
- mockModel,
- type MockModelRequest,
- type MockModelResponse,
- type MockModelToolResult,
-} from "eve/evals";
-
-import { AUTH_SNAPSHOT_MARKER } from "./lib/lifecycle-control.js";
-import { lifecycleModel } from "./lib/lifecycle-model.js";
-
-const TASK_ID_PATTERN = /task_[a-z0-9]+/iu;
-const TASK_STATE_LABEL = "[Task state]\n";
-const CHILD_TOOL_SURFACE_SCENARIO =
- "Alice asks Bob to summarize the available tools for a background task.";
-
-function respond(request: MockModelRequest): MockModelResponse | string {
- const lifecycle = lifecycleModel(request);
- if (lifecycle !== undefined) return lifecycle;
- if (request.userMessages.includes(CHILD_TOOL_SURFACE_SCENARIO)) {
- return childToolSurfaceReport(request);
- }
- if (request.userMessages.includes("TASK-BATCHING-BENCHMARK")) {
- return batchingBenchmark(request);
- }
-
- // Framework announcements are model context, not scenario turns.
- const message = [...request.userMessages].reverse().find(isScenarioMessage) ?? "";
- if (message === "TUI-HANG-IN-PROCESS") {
- return startHangLabTool(request, "hold-in-process", "hold_in_process", { durationMs: 45_000 });
- }
- if (message === "TUI-HANG-WORKFLOW") {
- return startHangLabTool(request, "hold-workflow", "hold_workflow", { duration: "45s" });
- }
- if (message === "TUI-HANG-COMMAND") {
- return startHangLabTool(request, "hold-command", "hold_command", { durationSeconds: 45 });
- }
- if (message === "TUI-HANG-SUBAGENT") {
- return startHangLabTool(request, "hold-subagent", "hang-worker", {
- message: "Hold for 45 seconds.",
- });
- }
- 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);
- if (message.startsWith("CHILD-TASK-EXCLUSIVITY-LATER ")) {
- return laterBusyWorker(request, message);
- }
- if (message === "TASK-AUTH-SNAPSHOT-ROOT") {
- return reportAuthSnapshotTurn(
- request,
- "task-auth-snapshot-root",
- "TASK-AUTH-SNAPSHOT-ROOT-ACK",
- );
- }
- if (message === "TASK-AUTH-SNAPSHOT-LATER") {
- return reportAuthSnapshotTurn(
- request,
- "task-auth-snapshot-later",
- "TASK-AUTH-SNAPSHOT-LATER-ACK",
- );
- }
- if (message.startsWith("TASK-AUTH-SNAPSHOT ")) return startAuthSnapshotTask(request, message);
- if (message.startsWith("TASK-A2-CHILD-FAILURE-VERIFY ")) {
- return inspectTerminalTask(
- request,
- "task-a2-child-failure-verify",
- "TASK-A2-FAILED",
- message,
- "failed",
- );
- }
- if (message.startsWith("TASK-A3-UNKNOWN-VERIFY ")) {
- return inspectTerminalTask(
- request,
- "task-a3-unknown-verify",
- "TASK-A3-UNKNOWN",
- message,
- "failed",
- );
- }
- if (message.startsWith("TASK-D6-PARTIAL-FANOUT-VERIFY ")) {
- return inspectTerminalTask(
- request,
- "task-d6-partial-fanout-verify",
- "TASK-D6-STATUS",
- message,
- "completed",
- );
- }
- if (message.startsWith("TASK-D6-PARTIAL-FANOUT-UNKNOWN ")) {
- return inspectTerminalTask(
- request,
- "task-d6-partial-fanout-unknown",
- "TASK-D6-UNKNOWN",
- message,
- );
- }
- if (message.startsWith("TASK-C7-AUTHORIZATION-VERIFY ")) {
- return inspectTerminalTask(
- request,
- "task-c7-authorization-verify",
- "TASK-C7-STATUS",
- message,
- "completed",
- );
- }
- if (message.startsWith("TASK-C8-REMOTE-VERIFY ")) {
- return inspectTerminalTask(
- request,
- "task-c8-remote-verify",
- "TASK-C8-STATUS",
- message,
- "completed",
- );
- }
- if (message.includes("TASK-C8-REMOTE-CHILD")) return runRemoteGate(request);
- if (message.startsWith("Background task ")) {
- // Scenarios that act on wake notifications route to their script;
- // every other scenario acknowledges them without running tools.
- // The exclusivity race delegates so a completion notification that
- // coalesces into the RACE turn still runs the same-batch sends.
- if (request.userMessages.includes("TASK-FAN-IN")) return fanInNotification(request);
- if (request.userMessages.includes("CHILD-TASK-EXCLUSIVITY-RACE")) {
- return raceBusyWorker(request);
- }
- return "TASK-NOTIFICATION-ACK";
- }
-
- if (message === "TASK-FANOUT-PARENT-UPDATES") return fanoutTasks(request, 10);
- if (message === "TASK-PARENT-WAKE-UPDATES") return fanoutTasks(request, 3);
- if (message === "TASK-FAN-IN") return fanInTasks(request);
- if (message === "TASK-FAN-IN-STATUS") return fanInNotification(request);
- if (message === "TASK-CANCEL-SETUP") return setupCancelWorker(request);
- if (message.startsWith("TASK-CANCEL-INSPECT ")) {
- // The eval proves the approval route was retired before inspecting the receipt.
- return inspectTerminalTask(request, "task-cancel-inspect", "TASK-CANCEL-STATUS", message);
- }
- if (message.startsWith("TASK-CANCEL-VERIFY ")) {
- return inspectTerminalTask(request, "task-cancel-verify", "TASK-CANCEL-STATUS", message);
- }
-
- if (message.startsWith("TASK-HITL-VERIFY ")) {
- return inspectTerminalTask(
- request,
- "task-hitl-verify",
- "TASK-HITL-STATUS",
- message,
- "completed",
- );
- }
- if (message.startsWith("TASK-INPUT-BATCH-VERIFY ")) {
- return inspectTerminalTask(
- request,
- "task-input-batch-verify",
- "TASK-INPUT-BATCH-STATUS",
- message,
- "completed",
- );
- }
- if (message.startsWith("CHILD-TASK-EXCLUSIVITY-VERIFY ")) {
- return inspectTerminalTask(
- request,
- "child-task-exclusivity-verify",
- "CHILD-TASK-EXCLUSIVITY-STATUS",
- message,
- "completed",
- );
- }
- if (message === "TASK-HITL-ROUTING") {
- return startApprovalWorker(request, "task-hitl-worker", "TASK-HITL-STARTED");
- }
- if (message === "TUI-IDLE-WORK-REPRO") {
- return startApprovalWorker(
- request,
- `tui-idle-work-repro-${scenarioUserMessageCount(request)}`,
- "TUI-IDLE-WORK-STARTED",
- { delayed: true },
- );
- }
- if (message === "TASK-C7-AUTHORIZATION") {
- return startApprovalWorker(request, "task-c7-authorization-worker", "TASK-C7-STARTED");
- }
- if (message === "TASK-C8-REMOTE-HITL") return startRemoteWorker(request);
- if (message === "TASK-INPUT-BATCH-ORDERING") {
- return startApprovalWorker(request, "task-input-batch-worker", "TASK-INPUT-BATCH-STARTED");
- }
- if (message === "TASK-CONTINUATION-HITL-SETUP") {
- return startApprovalWorker(
- request,
- "task-continuation-hitl-worker",
- "TASK-CONTINUATION-HITL-READY",
- );
- }
- if (message.startsWith("TASK-CONTINUATION-HITL-SEND ")) {
- return continueApprovalWorker(request, message);
- }
- if (message === "CHILD-TASK-EXCLUSIVITY-SETUP") return setupBusyWorker(request);
- if (message === "TASK-A2-CHILD-FAILURE") return startFailingBusyWorker(request);
- if (message === "TASK-A3-DISPATCH-START-FAILURE") return startUnstartableWorker(request);
- if (message === "TASK-D6-PARTIAL-FANOUT-FAILURE") return partialFailureFanout(request);
-
- return `Mock reply: ${message}`;
-}
-
-function startHangLabTool(
- request: MockModelRequest,
- callIdPrefix: string,
- name: string,
- input: unknown,
-): MockModelResponse | string {
- const callId = `${callIdPrefix}-${scenarioUserMessageCount(request)}`;
- if (resultById(request, callId) === undefined) {
- return { toolCalls: [{ id: callId, input, name }] };
- }
- return `TUI-HANG-LAB-COMPLETE:${callIdPrefix}`;
-}
-
-function startAuthSnapshotTask(
- request: MockModelRequest,
- message: string,
-): MockModelResponse | string {
- const authCallId = "task-auth-snapshot-creator";
- if (resultById(request, authCallId) === undefined) {
- return authSnapshotToolCall(authCallId);
- }
- const callId = "task-auth-snapshot";
- if (resultById(request, callId) !== undefined) return "TASK-AUTH-SNAPSHOT-STARTED";
- const key = message.split(" ").at(-1);
- if (key === undefined) throw new Error("Auth snapshot scenario has no lifecycle key.");
- return {
- toolCalls: [
- {
- id: callId,
- input: { child: false, delayedAuthChild: true, key, marker: AUTH_SNAPSHOT_MARKER },
- name: "lifecycle_task",
- },
- ],
- };
-}
-
-function reportAuthSnapshotTurn(
- request: MockModelRequest,
- callId: string,
- acknowledgement: string,
-): MockModelResponse | string {
- return resultById(request, callId) === undefined ? authSnapshotToolCall(callId) : acknowledgement;
-}
-
-function authSnapshotToolCall(callId: string): MockModelResponse {
- return {
- toolCalls: [{ id: callId, input: {}, name: "snapshot_whoami" }],
- };
-}
-
-function childToolSurfaceReport(request: MockModelRequest): MockModelResponse | string {
- const task = latestTaskState(request.userMessages)?.tasks.find(
- (entry) => entry.status === "completed",
- );
- if (task !== undefined) {
- if (task.output?.type !== "result" || typeof task.output.data !== "string") {
- throw new Error("The completed child did not return a tool report.");
- }
- return task.output.data;
- }
- if (resultById(request, "task-child-tool-surface") === undefined) {
- return {
- toolCalls: [
- {
- id: "task-child-tool-surface",
- input: {
- message: "Bob, list your available tool names and return your final report to Alice.",
- },
- name: "tool-surface-worker",
- },
- ],
- };
- }
- return "TASK-CHILD-TOOL-SURFACE-STARTED";
-}
-
-interface TaskState {
- readonly tasks: readonly {
- readonly output?: { readonly data: unknown; readonly type: string };
- readonly status: string;
- }[];
-}
-
-function latestTaskState(messages: readonly string[]): TaskState | undefined {
- const message = [...messages].reverse().find((entry) => entry.startsWith(TASK_STATE_LABEL));
- if (message === undefined) return undefined;
- const parsed: unknown = JSON.parse(message.slice(TASK_STATE_LABEL.length));
- if (
- parsed === null ||
- typeof parsed !== "object" ||
- !Array.isArray(Reflect.get(parsed, "tasks"))
- ) {
- throw new Error("Invalid task state supplied to the model.");
- }
- return parsed as TaskState;
-}
-
-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,
- );
- if (pending.length > 0) {
- return {
- toolCalls: pending.map((index) => ({
- id: `task-fanout-${index}`,
- input: { message: `FANOUT-WORKER-${index}` },
- name: "fanout-worker",
- })),
- };
- }
- return "TASK-FANOUT-STARTED";
-}
-
-function batchingBenchmark(request: MockModelRequest): MockModelResponse | string {
- const message = [...request.userMessages]
- .reverse()
- .find(
- (entry) => entry.startsWith("TASK-BATCHING-") || entry.startsWith("Background task task_"),
- );
- if (message === "TASK-BATCHING-QUESTION") return "56";
- if (message === "TASK-BATCHING-BENCHMARK") return fanoutTasks(request, 10);
- if (message?.endsWith("needs input.")) return "TASK-NOTIFICATION-ACK";
-
- const state = latestTaskState(request.userMessages);
- if (state === undefined) return "TASK-FANOUT-STARTED";
- if (state.tasks.some((task) => task.status === "pending")) {
- throw new Error("A completion invoked the parent model before its cohort settled.");
- }
- const results = state.tasks.flatMap((task) =>
- task.output?.type === "result" && typeof task.output.data === "string"
- ? [task.output.data]
- : [],
- );
- return JSON.stringify({ report: "TASK-BATCHING-REPORT", results: results.sort() });
-}
-
-const FAN_IN_CALL_IDS = ["task-fan-in-1", "task-fan-in-2"] as const;
-
-function fanInTasks(request: MockModelRequest): MockModelResponse | string {
- const pending = FAN_IN_CALL_IDS.filter((id) => resultById(request, id) === undefined);
- if (pending.length > 0) {
- return {
- toolCalls: pending.map((id) => ({
- id,
- input: { message: `Run the release gate, then return ${id.toUpperCase()}.` },
- name: "fanout-worker",
- })),
- };
- }
- return "TASK-FAN-IN-STARTED";
-}
-
-/** The model-side join derives completion from the result-bearing notifications already in history. */
-function fanInNotification(request: MockModelRequest): MockModelResponse | string {
- const taskIds = FAN_IN_CALL_IDS.map((id) => findTaskId(resultById(request, id)?.output)).filter(
- (taskId): taskId is string => taskId !== undefined,
- );
- if (taskIds.length !== FAN_IN_CALL_IDS.length) {
- throw new Error("Fan-in notification arrived before both task receipts.");
- }
- return taskIds.every((taskId) => hasTaskNotification(request, taskId, "completed"))
- ? "TASK-FAN-IN-COMPLETE"
- : "TASK-FAN-IN-WAITING";
-}
-
-function setupCancelWorker(request: MockModelRequest): MockModelResponse | string {
- if (resultById(request, "task-cancel-worker") === undefined) {
- return {
- toolCalls: [
- {
- id: "task-cancel-worker",
- input: { message: "Run the release gate, then return CANCEL-WORKER-DONE." },
- name: "fanout-worker",
- },
- ],
- };
- }
- return "TASK-CANCEL-READY";
-}
-
-function cancelWorkerTask(request: MockModelRequest): MockModelResponse | string {
- const callId = `task-cancel-call-${scenarioUserMessageCount(request)}`;
- if (resultById(request, callId) === undefined) {
- const taskId = findTaskId(resultById(request, "task-cancel-worker")?.output);
- if (taskId === undefined) throw new Error("Cancel scenario has no initial task id.");
- return { toolCalls: [{ id: callId, input: { taskIds: [taskId] }, name: "task_cancel" }] };
- }
- return "TASK-CANCEL-DONE";
-}
-
-function startApprovalWorker(
- request: MockModelRequest,
- callId: string,
- completedText: string,
- options?: { delayed?: boolean },
-): MockModelResponse | string {
- if (resultById(request, callId) === undefined) {
- return {
- toolCalls: [
- {
- id: callId,
- input: {
- message:
- callId === "task-c7-authorization-worker"
- ? "Run the C7 authorization mode, then return C7-AUTHORIZATION-COMPLETE."
- : options?.delayed === true
- ? "Wait twenty seconds before the approval gates, then run three approval gates in order and return CHILD-GATES-COMPLETE."
- : callId === "task-hitl-worker"
- ? "Run three approval gates in order, then return CHILD-GATES-COMPLETE."
- : "Run both approval gates in order, then return CHILD-GATES-COMPLETE.",
- },
- name: "approval-worker",
- },
- ],
- };
- }
- return completedText;
-}
-
-function startRemoteWorker(request: MockModelRequest): MockModelResponse | string {
- const callId = "task-c8-remote-worker";
- if (resultById(request, callId) === undefined) {
- return {
- toolCalls: [
- {
- id: callId,
- input: {
- message:
- "TASK-C8-REMOTE-CHILD Run the remote gate, then return its principal marker verbatim.",
- },
- name: "remote-loopback",
- },
- ],
- };
- }
- return "TASK-C8-STARTED";
-}
-
-function runRemoteGate(request: MockModelRequest): MockModelResponse | string {
- const callId = "task-c8-remote-gate";
- const result = resultById(request, callId);
- if (result === undefined) {
- return {
- toolCalls: [
- {
- id: callId,
- input: { marker: "C8" },
- name: "remote_gate",
- },
- ],
- };
- }
- const marker = findString(result.output, "C8-REMOTE-PRINCIPAL:");
- if (marker === undefined) throw new Error("Remote gate returned no principal marker.");
- return `C8-REMOTE-COMPLETE ${marker}`;
-}
-
-function inspectTerminalTask(
- request: MockModelRequest,
- callIdPrefix: string,
- completedText: string,
- message: string,
- status?: "cancelled" | "completed" | "failed",
-): MockModelResponse | string {
- const taskId = TASK_ID_PATTERN.exec(message)?.[0];
- if (taskId === undefined) throw new Error(`Verification message has no task id: ${message}`);
- if (status !== undefined && !hasTaskNotification(request, taskId, status)) {
- return `${completedText}-WAITING`;
- }
- const callId = `${callIdPrefix}-${scenarioUserMessageCount(request)}`;
- if (resultById(request, callId) === undefined) {
- return { toolCalls: [{ id: callId, input: { taskIds: [taskId] }, name: "task_cancel" }] };
- }
- return completedText;
-}
-
-function hasTaskNotification(
- request: MockModelRequest,
- taskId: string,
- status: "cancelled" | "completed" | "failed",
-): boolean {
- const statusText = status === "failed" ? " failed." : ` is ${status}.`;
- return request.userMessages.some(
- (entry) => entry.includes(`Background task ${taskId} (`) && entry.includes(statusText),
- );
-}
-
-function isScenarioMessage(message: string): boolean {
- return !/^(?:\[Agents\]|\[Task state\]|Background task (?:reporting|control))/u.test(message);
-}
-
-function scenarioUserMessageCount(request: MockModelRequest): number {
- return request.userMessages.filter(isScenarioMessage).length;
-}
-
-function setupBusyWorker(request: MockModelRequest): MockModelResponse | string {
- const delegated = resultById(request, "child-task-exclusivity-initial-worker");
- if (delegated === undefined) {
- return {
- toolCalls: [
- {
- id: "child-task-exclusivity-initial-worker",
- input: { message: "Return BUSY-WORKER-INITIAL." },
- name: "busy-worker",
- },
- ],
- };
- }
-
- return "CHILD-TASK-EXCLUSIVITY-READY";
-}
-
-function startFailingBusyWorker(request: MockModelRequest): MockModelResponse | string {
- const callId = "task-a2-failing-busy-worker";
- if (resultById(request, callId) === undefined) {
- return {
- toolCalls: [
- {
- id: callId,
- input: { message: "TASK-A2-BUSY-WORKER-FAILURE" },
- name: "busy-worker",
- },
- ],
- };
- }
- return "TASK-A2-CHILD-FAILURE-STARTED";
-}
-
-function startUnstartableWorker(request: MockModelRequest): MockModelResponse | string {
- const callId = "task-a3-unstartable-worker";
- if (resultById(request, callId) === undefined) {
- return {
- toolCalls: [
- {
- id: callId,
- input: { message: "TASK-A3-INTENTIONAL-START-FAILURE" },
- name: "unstartable-worker",
- },
- ],
- };
- }
- return "TASK-A3-PARENT-SURVIVED";
-}
-
-const PARTIAL_FANOUT_CALLS = [
- {
- id: "task-d6-success-first",
- message: "TASK-D6-FIRST-SUCCESS",
- name: "busy-worker",
- },
- {
- id: "task-d6-failure-middle",
- message: "TASK-D6-INTENTIONAL-START-FAILURE",
- name: "unstartable-worker",
- },
- {
- id: "task-d6-success-third",
- message: "TASK-D6-THIRD-SUCCESS",
- name: "busy-worker",
- },
-] as const;
-
-function partialFailureFanout(request: MockModelRequest): MockModelResponse | string {
- const pending = PARTIAL_FANOUT_CALLS.filter(({ id }) => resultById(request, id) === undefined);
- if (pending.length > 0) {
- return {
- toolCalls: pending.map(({ id, message, name }) => ({
- id,
- input: { message },
- name,
- })),
- };
- }
- return "TASK-D6-PARTIAL-FANOUT-STARTED";
-}
-
-function raceBusyWorker(request: MockModelRequest): MockModelResponse | string {
- const first = resultById(request, "child-task-exclusivity-send-a");
- const second = resultById(request, "child-task-exclusivity-send-b");
- if (first === undefined && second === undefined) {
- const initial = resultById(request, "child-task-exclusivity-initial-worker");
- const agentId = findAgentId(initial?.output);
- if (agentId === undefined) throw new Error("Busy-worker race has no initial agent id.");
- return {
- toolCalls: [
- {
- id: "child-task-exclusivity-send-a",
- input: { agentId, message: "EXCLUSIVITY-GATE: Return BUSY-WORKER-A." },
- name: "busy-worker",
- },
- {
- id: "child-task-exclusivity-send-b",
- input: { agentId, message: "EXCLUSIVITY-GATE: Return BUSY-WORKER-B." },
- name: "busy-worker",
- },
- ],
- };
- }
- return "CHILD-TASK-EXCLUSIVITY-RACE-DONE";
-}
-
-function laterBusyWorker(request: MockModelRequest, message: string): MockModelResponse | string {
- const result = resultById(request, "child-task-exclusivity-later");
- if (result === undefined) {
- const agentId = findAgentId(message);
- if (agentId === undefined) throw new Error("Later exclusivity continuation has no agent id.");
- return {
- toolCalls: [
- {
- id: "child-task-exclusivity-later",
- input: { agentId, message: "Return BUSY-WORKER-LATER." },
- name: "busy-worker",
- },
- ],
- };
- }
- return "CHILD-TASK-EXCLUSIVITY-LATER-DONE";
-}
-
-function continueApprovalWorker(
- request: MockModelRequest,
- message: string,
-): MockModelResponse | string {
- const callId = "task-continuation-hitl-send";
- const result = resultById(request, callId);
- if (result === undefined) {
- const agentId = findAgentId(message);
- if (agentId === undefined) throw new Error("Continuation HITL has no agent id.");
- return {
- toolCalls: [
- {
- id: callId,
- input: {
- message:
- "Run four continuation approval gates in order, then return CHILD-GATES-COMPLETE.",
- agentId,
- },
- name: "approval-worker",
- },
- ],
- };
- }
- return "TASK-CONTINUATION-HITL-STARTED";
-}
-
-function resultById(request: MockModelRequest, id: string): MockModelToolResult | undefined {
- return request.toolResults.find((result) => result.id === id);
-}
-
-function findTaskId(value: unknown): string | undefined {
- if (typeof value === "string") return TASK_ID_PATTERN.exec(value)?.[0];
- if (Array.isArray(value)) {
- for (const entry of value) {
- const taskId = findTaskId(entry);
- if (taskId !== undefined) return taskId;
- }
- return undefined;
- }
- if (value !== null && typeof value === "object") {
- const taskId = Reflect.get(value, "taskId");
- if (typeof taskId === "string") return taskId;
- for (const entry of Object.values(value)) {
- const nested = findTaskId(entry);
- if (nested !== undefined) return nested;
- }
- }
- return undefined;
-}
-
-function findAgentId(value: unknown): string | undefined {
- if (typeof value === "string") return /ag_[^\s<>]+/u.exec(value)?.[0];
- if (Array.isArray(value)) {
- for (const entry of value) {
- const agentId = findAgentId(entry);
- if (agentId !== undefined) return agentId;
- }
- return undefined;
- }
- if (value !== null && typeof value === "object") {
- const agentId = Reflect.get(value, "agentId");
- if (typeof agentId === "string") return agentId;
- for (const entry of Object.values(value)) {
- const nested = findAgentId(entry);
- if (nested !== undefined) return nested;
- }
- }
- return undefined;
-}
-
-function findString(value: unknown, prefix: string): string | undefined {
- if (typeof value === "string") return value.startsWith(prefix) ? value : undefined;
- if (Array.isArray(value)) {
- for (const entry of value) {
- const match = findString(entry, prefix);
- if (match !== undefined) return match;
- }
- return undefined;
- }
- if (value !== null && typeof value === "object") {
- for (const entry of Object.values(value)) {
- const match = findString(entry, prefix);
- if (match !== undefined) return match;
- }
- }
- return undefined;
-}
-
-export default defineAgent({
- ...e2eAgentConfig(),
- // Script orchestration checks here; real-model coverage lives in agent-task-reporting.
- model: mockModel(respond),
- // The lifecycle eval checks child usage through the runtime's budget gate.
- limits: { maxInputTokensPerSession: 1_000_000 },
- modelContextWindowTokens: 10_000_000,
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/channels/eve.ts b/e2e/fixtures/fixture-tasks/agent/channels/eve.ts
deleted file mode 100644
index f6e06cab8..000000000
--- a/e2e/fixtures/fixture-tasks/agent/channels/eve.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import type { AuthFn } from "eve/channels/auth";
-import { eveChannel } from "eve/channels/eve";
-import type { SessionAuthContext } from "eve/context";
-
-const SESSION_INITIATOR_AUTHORIZATION = "Bearer e2e-task-session-initiator";
-const LATER_PARENT_CALLER_AUTHORIZATION = "Bearer e2e-task-later-parent-caller";
-const ANONYMOUS_TASK_CREATOR_HEADER = "x-eve-fixture-anonymous-task-creator";
-const REMOTE_CHILD = "Bearer e2e-task-remote-loopback";
-
-function principal(principalId: string): SessionAuthContext {
- return {
- attributes: {},
- authenticator: "e2e-task-fixture",
- issuer: "e2e",
- principalId,
- principalType: "user",
- subject: principalId,
- };
-}
-
-const authenticateSessionInitiator: AuthFn<Request> = (request) =>
- request.headers.get("authorization") === SESSION_INITIATOR_AUTHORIZATION
- ? principal("session-initiator")
- : null;
-
-const authenticateLaterParentCaller: AuthFn<Request> = (request) =>
- request.headers.get("authorization") === LATER_PARENT_CALLER_AUTHORIZATION
- ? principal("later-parent-caller")
- : null;
-
-const authenticateRemoteChild: AuthFn<Request> = (request) =>
- request.headers.get("authorization") === REMOTE_CHILD ? principal("remote-http-child") : null;
-
-const authenticateEvalDriver: AuthFn<Request> = () => principal("eval-driver");
-
-export default eveChannel({
- auth: [
- authenticateSessionInitiator,
- authenticateLaterParentCaller,
- authenticateRemoteChild,
- authenticateEvalDriver,
- ],
- onMessage({ eve }) {
- return {
- auth: eve.request.headers.get(ANONYMOUS_TASK_CREATOR_HEADER) === "1" ? null : eve.caller,
- };
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/channels/lifecycle.ts b/e2e/fixtures/fixture-tasks/agent/channels/lifecycle.ts
deleted file mode 100644
index 91bc0c48c..000000000
--- a/e2e/fixtures/fixture-tasks/agent/channels/lifecycle.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { defineChannel, POST } from "eve/channels";
-import { getHookByToken, getRun, getWorld, resumeHook } from "workflow/api";
-import { z } from "zod";
-import {
- AUTH_SNAPSHOT_MARKER,
- lifecycleNamespace,
- type LifecycleControlEvent,
-} from "../lib/lifecycle-control.js";
-
-const bodySchema = z.object({
- key: z.string().uuid(),
- index: z.number().int().min(0).max(20).optional(),
- token: z.string().min(1).max(512).optional(),
- marker: z.enum(["A", "B", AUTH_SNAPSHOT_MARKER]).optional(),
-});
-
-// Fixture-only capability routes: a per-eval random key addresses only its own
-// control stream. Only fixture gate tokens are exposed, never runtime routing credentials.
-export default defineChannel({
- routes: [
- POST("/eve/v1/task-lifecycle/:sessionId/:action", async (request, { params }) => {
- const signal = AbortSignal.any([request.signal, AbortSignal.timeout(60_000)]);
- const body = bodySchema.parse(JSON.parse(await boundedBody(request)));
- const sessionId = params.sessionId;
- const read = async (index: number) => {
- const reader = getRun(sessionId)
- .getReadable<LifecycleControlEvent>({
- namespace: lifecycleNamespace(body.key),
- startIndex: index,
- })
- .getReader();
- const abort = () => {
- void reader.cancel("Lifecycle observation aborted");
- };
- signal.addEventListener("abort", abort, { once: true });
- try {
- signal.throwIfAborted();
- const next = await reader.read();
- if (next.done) throw new Error("Lifecycle control stream ended before acknowledgment.");
- return next.value;
- } finally {
- signal.removeEventListener("abort", abort);
- await reader.cancel();
- reader.releaseLock();
- }
- };
- // Reading this namespace proves that this eval key was registered by the
- // addressed parent. Unknown keys cannot inspect or release another eval.
- const first = await read(0);
- if (first.kind !== "owner" || first.sessionId !== sessionId)
- return new Response(null, { status: 403 });
- if (params.action === "next") return Response.json(await read(body.index ?? 0));
- if ((params.action === "release" || params.action === "active") && body.token !== undefined) {
- const hook = await getHookByToken(body.token);
- const metadata = await hook.metadata;
- if (
- metadata === null ||
- typeof metadata !== "object" ||
- Reflect.get(metadata, "key") !== body.key ||
- Reflect.get(metadata, "parentSessionId") !== sessionId
- )
- return new Response(null, { status: 403 });
- if (params.action === "active")
- return Response.json({ status: await getRun(hook.runId).status });
- await resumeHook(body.token, undefined);
- return Response.json({ released: true });
- }
- if (params.action === "settled" && body.marker !== undefined) {
- for (let index = 0; index < 6; index += 1) {
- const event = index === 0 ? first : await read(index);
- if (event.kind !== "owner" || event.marker !== body.marker) continue;
- const run = getRun(event.runId);
- signal.throwIfAborted();
- let rejectWait: ((reason: Error) => void) | undefined;
- const aborted = new Promise<never>((_, reject) => {
- rejectWait = reject;
- });
- const abort = () => rejectWait?.(new Error("Task owner did not settle."));
- signal.addEventListener("abort", abort, { once: true });
- try {
- await Promise.race([run.returnValue, aborted]);
- } finally {
- signal.removeEventListener("abort", abort);
- }
- return Response.json({
- marker: event.marker,
- status: await run.status,
- notificationCount: await ownerNotificationCount(event.runId),
- });
- }
- }
- return new Response(null, { status: 400 });
- }),
- ],
-});
-
-async function ownerNotificationCount(runId: string) {
- const world = await getWorld();
- const [steps, events] = await Promise.all([
- world.steps.list({ runId, pagination: { limit: 100 }, resolveData: "none" }),
- world.events.list({
- runId,
- pagination: { limit: 100, sortOrder: "asc" },
- resolveData: "none",
- }),
- ]);
- if (steps.hasMore || events.hasMore) throw new Error("Lifecycle owner audit exceeded its bound.");
- const notificationSteps = new Set(
- steps.data
- .filter((step) => step.stepName.endsWith("//notifyTaskParent"))
- .map((step) => step.stepId),
- );
- return events.data.filter(
- (event) => event.eventType === "step_completed" && notificationSteps.has(event.correlationId),
- ).length;
-}
-
-async function boundedBody(request: Request) {
- const reader = request.body?.getReader();
- if (reader === undefined) throw new Error("Missing lifecycle request.");
- let text = "";
- let bytes = 0;
- const decoder = new TextDecoder();
- try {
- while (true) {
- const next = await reader.read();
- if (next.done) return text + decoder.decode();
- bytes += next.value.byteLength;
- if (bytes > 4096) throw new Error("Lifecycle request exceeds 4096 bytes.");
- text += decoder.decode(next.value, { stream: true });
- }
- } finally {
- await reader.cancel();
- reader.releaseLock();
- }
-}
diff --git a/e2e/fixtures/fixture-tasks/agent/instructions.md b/e2e/fixtures/fixture-tasks/agent/instructions.md
deleted file mode 100644
index e2cad432c..000000000
--- a/e2e/fixtures/fixture-tasks/agent/instructions.md
+++ /dev/null
@@ -1 +0,0 @@
-Help the user delegate background work and report the results accurately. Use the requested specialist and preserve the result identifiers in your report.
diff --git a/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-control.ts b/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-control.ts
deleted file mode 100644
index 181059f75..000000000
--- a/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-control.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { createHook, getWorkflowMetadata } from "workflow";
-import { getRun } from "workflow/api";
-
-export const AUTH_SNAPSHOT_MARKER = "auth-snapshot" as const;
-
-export type LifecycleMarker = "A" | "B" | "parent" | typeof AUTH_SNAPSHOT_MARKER;
-
-export interface LifecycleControlEvent {
- readonly kind: "gate" | "owner" | "gate-cancelled";
- readonly marker: LifecycleMarker;
- readonly runId: string;
- readonly sessionId: string;
- readonly turnId: string;
- readonly token?: string;
-}
-
-export const lifecycleNamespace = (key: string) => `fixture-tasks.lifecycle.${key}`;
-
-export async function publishLifecycleControl(
- parentSessionId: string,
- key: string,
- event: LifecycleControlEvent,
-) {
- "use step";
- const ops: Promise<void>[] = [];
- const writer = getRun(parentSessionId)
- .getWritable<LifecycleControlEvent>({ namespace: lifecycleNamespace(key), ops })
- .getWriter();
- try {
- await writer.write(event);
- } finally {
- writer.releaseLock();
- }
- await Promise.all(ops);
-}
-
-export async function lifecycleGate(
- input: {
- parentSessionId: string;
- key: string;
- marker: LifecycleMarker;
- sessionId: string;
- turnId: string;
- },
- signal?: AbortSignal,
-) {
- const gate = createHook<void>({
- metadata: { parentSessionId: input.parentSessionId, key: input.key },
- });
- await publishLifecycleControl(input.parentSessionId, input.key, {
- kind: "gate",
- marker: input.marker,
- token: gate.token,
- runId: getWorkflowMetadata().workflowRunId,
- sessionId: input.sessionId,
- turnId: input.turnId,
- });
- if (signal === undefined) {
- await gate;
- return;
- }
-
- let rejectAbort: ((reason: unknown) => void) | undefined;
- const aborted = new Promise<never>((_, reject) => {
- rejectAbort = reject;
- });
- const abort = () => rejectAbort?.(signal.reason);
- signal.addEventListener("abort", abort, { once: true });
- try {
- signal.throwIfAborted();
- await Promise.race([gate, aborted]);
- } finally {
- signal.removeEventListener("abort", abort);
- // Do not await the unresolved hook iterator during cancellation teardown.
- await gate.dispose();
- if (signal.aborted) {
- await publishLifecycleControl(input.parentSessionId, input.key, {
- kind: "gate-cancelled",
- marker: input.marker,
- runId: getWorkflowMetadata().workflowRunId,
- sessionId: input.sessionId,
- turnId: input.turnId,
- });
- }
- }
-}
diff --git a/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-model.ts b/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-model.ts
deleted file mode 100644
index ed3854001..000000000
--- a/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-model.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import type { MockModelRequest, MockModelResponse } from "eve/evals";
-
-export const LIFECYCLE_SCENARIO = "Alice coordinates Bob's lifecycle ordering check.";
-export const CROSS_TURN_SCENARIO = "Alice launches two pieces of work in separate user turns.";
-const ZERO_USAGE = { inputTokens: 0, outputTokens: 0 };
-const COMPLETION = /^Background task task_[a-z0-9]+ \([^)]+\) is completed\./u;
-
-export function lifecycleModel(request: MockModelRequest): MockModelResponse | undefined {
- const setup = request.userMessages.find(
- (message) => message.startsWith(LIFECYCLE_SCENARIO) || message.startsWith(CROSS_TURN_SCENARIO),
- );
- if (setup === undefined) return;
- const key = setup.split(" ").at(-1)!;
- const crossTurn = setup.startsWith(CROSS_TURN_SCENARIO);
- const message =
- [...request.userMessages]
- .reverse()
- .find((entry) => entry.startsWith("Alice ") || COMPLETION.test(entry)) ?? "";
- const result = (id: string) => request.toolResults.find((entry) => entry.id === id);
- const call = (marker: "A" | "B") => ({
- id: `lifecycle-${marker}`,
- name: "lifecycle_task",
- input: { key, marker, child: !crossTurn && marker === "B" },
- });
- const response = (value: Omit<MockModelResponse, "usage">) => ({ ...value, usage: ZERO_USAGE });
- if (message === "Alice checks that Bob's terminal session has no retained handle.") {
- const agents =
- [...request.messages].reverse().find((entry) => entry.text.startsWith("[Agents]"))?.text ??
- "";
- return response({
- text: JSON.stringify([...agents.matchAll(/<agent id="([^"]+)"/gu)].map((match) => match[1])),
- });
- }
- if (COMPLETION.test(message)) {
- // Report only what the runtime actually delivered, without model-side batching.
- const notifications = request.userMessages.filter((entry) => COMPLETION.test(entry));
- return response({ text: JSON.stringify({ report: "LIFECYCLE-REPORT", notifications }) });
- }
- if (message === "Alice keeps the parent active while Bob finishes.") {
- return result("lifecycle-hold") === undefined
- ? response({ toolCalls: [{ id: "lifecycle-hold", name: "lifecycle_hold", input: { key } }] })
- : response({ text: "PARENT-RELEASED" });
- }
- if (message === "Alice checks that the other piece of work is still pending.") {
- return response({ text: "PENDING-CHECK-ACK" });
- }
- if (message === "Alice performs the final metered accounting check.") {
- return { text: "ACCOUNTING-CHECK", usage: { inputTokens: 999_790, outputTokens: 0 } };
- }
- if (message === "Alice checks the remaining session budget.") {
- return response({ text: "B-USAGE-WAS-NOT-ACCUMULATED" });
- }
- if (message === "Alice confirms that all completion deliveries have been observed.") {
- return response({ text: "DRAIN-ACK" });
- }
- const markers: ("A" | "B")[] = crossTurn
- ? [request.userMessages.includes("Alice now launches the second piece of work.") ? "B" : "A"]
- : ["A", "B"];
- const pending = markers.filter((marker) => result(`lifecycle-${marker}`) === undefined);
- return response(
- pending.length > 0
- ? { toolCalls: pending.map(call) }
- : { text: `LAUNCHED:${markers.join(",")}` },
- );
-}
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/agent.ts b/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/agent.ts
deleted file mode 100644
index 831e41d82..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/agent.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { defineAgent } from "eve";
-import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";
-
-function respond(request: MockModelRequest): MockModelResponse | string {
- const authorization = request.userMessages.some((message) =>
- message.includes("C7 authorization mode"),
- );
- if (authorization) {
- if (request.toolResults.find((result) => result.id === "c7-authorization") === undefined) {
- return {
- toolCalls: [
- { id: "c7-authorization", input: { marker: "C7" }, name: "authorization_gate" },
- ],
- };
- }
- return "C7-AUTHORIZATION-COMPLETE";
- }
-
- const continuation = request.userMessages.some((message) =>
- message.includes("continuation approval gates"),
- );
- const delayed = request.userMessages.some((message) =>
- message.toLowerCase().includes("wait twenty seconds before the approval gates"),
- );
- const threeGates =
- continuation ||
- request.userMessages.some((message) => message.includes("three approval gates"));
- const id = (gate: string) => (continuation ? `continuation-${gate}` : `approval-${gate}`);
- if (
- delayed &&
- request.toolResults.find((result) => result.id === "approval-wait") === undefined
- ) {
- return {
- toolCalls: [{ id: "approval-wait", input: { delay: "20s" }, name: "wait_before_approval" }],
- };
- }
- const first = request.toolResults.find((result) => result.id === id("first"));
- if (first === undefined) {
- return {
- toolCalls: [{ id: id("first"), input: { marker: "FIRST" }, name: "first_gate" }],
- };
- }
-
- const second = request.toolResults.find((result) => result.id === id("second"));
- if (second === undefined) {
- return {
- toolCalls: [{ id: id("second"), input: { marker: "SECOND" }, name: "second_gate" }],
- };
- }
-
- if (threeGates) {
- const third = request.toolResults.find((result) => result.id === id("third"));
- if (third === undefined) {
- return {
- toolCalls: [{ id: id("third"), input: { marker: "THIRD" }, name: "third_gate" }],
- };
- }
- if (continuation) {
- const fourth = request.toolResults.find((result) => result.id === id("fourth"));
- if (fourth === undefined) {
- return {
- toolCalls: [{ id: id("fourth"), input: { marker: "FOURTH" }, name: "fourth_gate" }],
- };
- }
- }
- }
-
- return "CHILD-GATES-COMPLETE";
-}
-
-export default defineAgent({
- description: "Run deterministic approval gates in order.",
- model: mockModel(respond),
- modelContextWindowTokens: 1_000_000,
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/authorization_gate.ts b/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/authorization_gate.ts
deleted file mode 100644
index 00304a576..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/authorization_gate.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import {
- ConnectionAuthorizationRequiredError,
- defineInteractiveAuthorization,
-} from "eve/connections";
-import { defineTool } from "eve/tools";
-import { z } from "zod";
-
-const AUTHORIZATION_NAME = "c7-task-authorization";
-const AUTHORIZATION_CODE = "c7-deterministic-code";
-const AUTHORIZATION_TOKEN = "c7-deterministic-token";
-
-const authorization = defineInteractiveAuthorization<{ marker: "C7" }>({
- async getToken() {
- throw new ConnectionAuthorizationRequiredError(AUTHORIZATION_NAME);
- },
- async startAuthorization() {
- return {
- challenge: {
- displayName: "C7 deterministic authorization",
- userCode: AUTHORIZATION_CODE,
- },
- resume: { marker: "C7" },
- };
- },
- async completeAuthorization({ callback, resume }) {
- if (callback.params.code !== AUTHORIZATION_CODE || resume?.marker !== "C7") {
- throw new Error("C7 authorization callback did not preserve its deterministic state.");
- }
- return { token: AUTHORIZATION_TOKEN };
- },
-});
-
-export default defineTool({
- description: "Exercises deterministic interactive authorization for a task-owned child.",
- inputSchema: z.object({ marker: z.literal("C7") }),
- async execute({ marker }, ctx) {
- const result = await ctx.getToken(authorization, {
- authKey: AUTHORIZATION_NAME,
- displayName: "C7 deterministic authorization",
- });
- if (result.token !== AUTHORIZATION_TOKEN)
- throw new Error("C7 authorization returned bad token.");
- return { marker: `${marker}-AUTHORIZED` };
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/first_gate.ts b/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/first_gate.ts
deleted file mode 100644
index 8c2afeb0f..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/first_gate.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { defineTool } from "eve/tools";
-import { once } from "eve/tools/approval";
-import { z } from "zod";
-
-export default defineTool({
- description: "First deterministic approval gate.",
- inputSchema: z.object({ marker: z.literal("FIRST") }),
- approval: once(),
- execute: async ({ marker }) => ({ marker, passed: true }),
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/fourth_gate.ts b/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/fourth_gate.ts
deleted file mode 100644
index ec285ecf6..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/fourth_gate.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { defineTool } from "eve/tools";
-import { once } from "eve/tools/approval";
-import { z } from "zod";
-
-export default defineTool({
- description: "Fourth deterministic approval gate for continued-task HITL routing.",
- inputSchema: z.object({ marker: z.literal("FOURTH") }),
- approval: once(),
- execute: async ({ marker }) => ({ marker, passed: true }),
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/second_gate.ts b/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/second_gate.ts
deleted file mode 100644
index a3ec99c56..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/second_gate.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { defineTool } from "eve/tools";
-import { once } from "eve/tools/approval";
-import { z } from "zod";
-
-export default defineTool({
- description: "Second deterministic approval gate.",
- inputSchema: z.object({ marker: z.literal("SECOND") }),
- approval: once(),
- execute: async ({ marker }) => ({ marker, passed: true }),
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/third_gate.ts b/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/third_gate.ts
deleted file mode 100644
index 6977b743a..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/third_gate.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { defineTool } from "eve/tools";
-import { once } from "eve/tools/approval";
-import { z } from "zod";
-
-export default defineTool({
- description: "Third deterministic approval gate for repeated HITL routing.",
- inputSchema: z.object({ marker: z.literal("THIRD") }),
- approval: once(),
- execute: async ({ marker }) => ({ marker, passed: true }),
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/wait_before_approval.ts b/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/wait_before_approval.ts
deleted file mode 100644
index 03c6ab3e9..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/approval-worker/tools/wait_before_approval.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { defineWorkflowTool, type WorkflowToolDefinition } from "eve/tools";
-import { sleep } from "workflow";
-import { z } from "zod";
-
-type Input = { delay: "20s" };
-
-async function execute({ delay }: Input): Promise<{ waited: "20s" }> {
- "use workflow";
- await sleep(delay);
- return { waited: delay };
-}
-
-const tool: WorkflowToolDefinition<Input, { waited: "20s" }> = defineWorkflowTool({
- description: "Wait before the deterministic approval sequence.",
- inputSchema: z.object({ delay: z.literal("20s") }),
- execute,
-});
-
-export default tool;
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/agent.ts b/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/agent.ts
deleted file mode 100644
index bf1ac6250..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/agent.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { e2eSubagentConfig } from "@eve-e2e/config";
-import { defineAgent } from "eve";
-
-export default defineAgent({
- ...e2eSubagentConfig(),
- description: "Report the task dispatch principal through snapshot_whoami.",
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/tools/snapshot_whoami.ts b/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/tools/snapshot_whoami.ts
deleted file mode 100644
index 0ca6aaa47..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/tools/snapshot_whoami.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { defineTool } from "eve/tools";
-import { z } from "zod";
-
-export default defineTool({
- description: "Report the current and initiating principals for this child session.",
- inputSchema: z.object({}),
- execute(_input, ctx) {
- return {
- current: ctx.session.auth.current?.principalId ?? null,
- initiator: ctx.session.auth.initiator?.principalId ?? null,
- };
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/busy-worker/agent.ts b/e2e/fixtures/fixture-tasks/agent/subagents/busy-worker/agent.ts
deleted file mode 100644
index a05552783..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/busy-worker/agent.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { defineAgent } from "eve";
-import { mockModel } from "eve/evals";
-
-export default defineAgent({
- description: "Return one deterministic marker for each message.",
- model: mockModel((request) => {
- const message = request.lastUserMessage ?? "";
- if (message.includes("TASK-A2-BUSY-WORKER-FAILURE")) {
- throw Object.assign(new Error("TASK-A2-BUSY-WORKER-FAILURE"), { statusCode: 400 });
- }
- if (message.includes("BUSY-WORKER-A") || message.includes("BUSY-WORKER-B")) {
- if (!request.toolResults.some((result) => result.id === "exclusivity-hold")) {
- return {
- toolCalls: [
- {
- id: "exclusivity-hold",
- input: { marker: message.includes("EXCLUSIVITY-GATE") ? "EXCLUSIVITY" : "HOLD" },
- name: "hold",
- },
- ],
- };
- }
- }
- return `BUSY-WORKER:${message}`;
- }),
- modelContextWindowTokens: 1_000_000,
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/busy-worker/tools/hold.ts b/e2e/fixtures/fixture-tasks/agent/subagents/busy-worker/tools/hold.ts
deleted file mode 100644
index 03bd33645..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/busy-worker/tools/hold.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { defineTool } from "eve/tools";
-import { z } from "zod";
-
-export default defineTool({
- description: "Hold a continuation until approval, or briefly delay other fixture work.",
- inputSchema: z.object({ marker: z.enum(["HOLD", "EXCLUSIVITY"]) }),
- approval: ({ toolInput }) =>
- toolInput?.marker === "EXCLUSIVITY" ? "user-approval" : "not-applicable",
- execute: async ({ marker }) => {
- if (marker === "HOLD") await new Promise((resolve) => setTimeout(resolve, 5_000));
- return { marker, released: true };
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/fanout-worker/agent.ts b/e2e/fixtures/fixture-tasks/agent/subagents/fanout-worker/agent.ts
deleted file mode 100644
index 5ec22c8cf..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/fanout-worker/agent.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { defineAgent } from "eve";
-import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";
-
-const FAN_IN_MARKER_PATTERN = /TASK-FAN-IN-[12]/u;
-
-function respond(request: MockModelRequest): MockModelResponse | string {
- const message = request.lastUserMessage ?? "";
- const fanInMarker = FAN_IN_MARKER_PATTERN.exec(message)?.[0];
- const fanoutMarker = /FANOUT-WORKER-\d+/u.exec(message)?.[0];
- const released = request.toolResults.find((result) => result.name === "release");
- if (released === undefined) {
- return {
- toolCalls: [{ input: { marker: fanInMarker ?? fanoutMarker ?? "RELEASE" }, name: "release" }],
- };
- }
- if (fanInMarker !== undefined) return `FANOUT-COMPLETE:${fanInMarker}`;
- const marker = fanoutMarker ?? message;
- return `FANOUT-COMPLETE:${marker}`;
-}
-
-export default defineAgent({
- description: "Complete one fanout task with its deterministic marker.",
- model: mockModel(respond),
- modelContextWindowTokens: 1_000_000,
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/fanout-worker/tools/release.ts b/e2e/fixtures/fixture-tasks/agent/subagents/fanout-worker/tools/release.ts
deleted file mode 100644
index ade1bf2c6..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/fanout-worker/tools/release.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { defineTool } from "eve/tools";
-import { once } from "eve/tools/approval";
-import { z } from "zod";
-
-export default defineTool({
- description: "Release one fanout task after its parent remains interactive.",
- inputSchema: z.object({
- marker: z.union([
- z.enum(["RELEASE", "TASK-FAN-IN-1", "TASK-FAN-IN-2"]),
- z.string().regex(/^FANOUT-WORKER-(?:[1-9]|10)$/u),
- ]),
- }),
- approval: once(),
- execute: async ({ marker }) => ({ marker, released: true }),
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/hang-worker/agent.ts b/e2e/fixtures/fixture-tasks/agent/subagents/hang-worker/agent.ts
deleted file mode 100644
index a7bfedb1b..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/hang-worker/agent.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { defineAgent } from "eve";
-import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";
-
-function respond(request: MockModelRequest): MockModelResponse | string {
- if (request.toolResults.some((result) => result.id === "hang-worker-hold")) {
- return "HANG-WORKER-COMPLETE";
- }
- return {
- toolCalls: [
- {
- id: "hang-worker-hold",
- input: { durationMs: 45_000 },
- name: "hold",
- },
- ],
- };
-}
-
-export default defineAgent({
- description: "Test-only subagent that holds a foreground delegation open.",
- model: mockModel(respond),
- modelContextWindowTokens: 1_000_000,
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/hang-worker/tools/hold.ts b/e2e/fixtures/fixture-tasks/agent/subagents/hang-worker/tools/hold.ts
deleted file mode 100644
index 102b09646..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/hang-worker/tools/hold.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { defineTool } from "eve/tools";
-import { z } from "zod";
-
-export default defineTool({
- description: "Test-only subagent hold.",
- inputSchema: z.object({ durationMs: z.literal(45_000) }),
- async execute({ durationMs }) {
- await new Promise((resolve) => setTimeout(resolve, durationMs));
- return { held: `${durationMs}ms` };
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/lifecycle-worker/agent.ts b/e2e/fixtures/fixture-tasks/agent/subagents/lifecycle-worker/agent.ts
deleted file mode 100644
index aebe788d9..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/lifecycle-worker/agent.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { defineAgent } from "eve";
-import { mockModel } from "eve/evals";
-
-export default defineAgent({
- description: "Bob performs metered work before an explicitly gated, terminal model rejection.",
- model: mockModel((request) => {
- if (request.toolResults.some((result) => result.name === "release")) {
- // A permanent provider rejection takes the real delegated-session terminal path.
- throw Object.assign(new Error("LIFECYCLE-TERMINAL-REJECTION"), { statusCode: 400 });
- }
- const message = request.userMessages.find((entry) => entry.includes('"parentSessionId"'));
- if (message === undefined) throw new Error("Missing lifecycle worker coordinates.");
- const input = JSON.parse(message.slice(message.indexOf("{")));
- return {
- toolCalls: [{ id: "metered-release", name: "release", input }],
- usage: { inputTokens: 211, outputTokens: 37 },
- };
- }),
- modelContextWindowTokens: 1_000_000,
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/lifecycle-worker/tools/release.ts b/e2e/fixtures/fixture-tasks/agent/subagents/lifecycle-worker/tools/release.ts
deleted file mode 100644
index 8c048d31d..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/lifecycle-worker/tools/release.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import {
- defineWorkflowTool,
- type WorkflowToolContext,
- type WorkflowToolDefinition,
-} from "eve/tools";
-import { z } from "zod";
-import { lifecycleGate } from "../../../lib/lifecycle-control.js";
-
-type Input = { parentSessionId: string; key: string; marker: "B" };
-
-async function execute(input: Input, ctx: WorkflowToolContext): Promise<string> {
- "use workflow";
- await lifecycleGate({ ...input, sessionId: ctx.session.id, turnId: ctx.session.turn.id });
- return "BOB-RELEASED";
-}
-
-const tool: WorkflowToolDefinition<Input, string> = defineWorkflowTool({
- description: "Acknowledge Bob's metered work and wait for the coordinator's release.",
- inputSchema: z.object({
- parentSessionId: z.string().min(1),
- key: z.string().uuid(),
- marker: z.literal("B"),
- }),
- execute,
-});
-
-export default tool;
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/remote-loopback.ts b/e2e/fixtures/fixture-tasks/agent/subagents/remote-loopback.ts
deleted file mode 100644
index b388fe053..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/remote-loopback.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { defineDynamic, defineRemoteAgent } from "eve";
-
-export default defineDynamic({
- events: {
- "session.started": () =>
- defineRemoteAgent({
- description: "Loopback remote child for deterministic task HITL coverage.",
- url: () =>
- process.env.VERCEL_URL !== undefined && process.env.VERCEL_URL !== ""
- ? `https://${process.env.VERCEL_URL}`
- : (process.env.WORKFLOW_LOCAL_BASE_URL ?? "http://127.0.0.1:3000"),
- headers: () => {
- const headers: Record<string, string> = {
- authorization: "Bearer e2e-task-remote-loopback",
- };
- const bypass = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;
- if (bypass !== undefined && bypass !== "") {
- headers["x-vercel-protection-bypass"] = bypass;
- }
- return headers;
- },
- }),
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/tool-surface-worker/agent.ts b/e2e/fixtures/fixture-tasks/agent/subagents/tool-surface-worker/agent.ts
deleted file mode 100644
index 2f52b2c01..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/tool-surface-worker/agent.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { defineAgent } from "eve";
-import { mockModel } from "eve/evals";
-
-export default defineAgent({
- description: "Return the child's advertised tool names in its final report to the parent.",
- model: mockModel(({ tools }) =>
- JSON.stringify({
- result: "TASK-CHILD-FINAL-RESULT",
- tools: tools.map((tool) => tool.name).sort(),
- }),
- ),
- modelContextWindowTokens: 1_000_000,
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/unstartable-worker.ts b/e2e/fixtures/fixture-tasks/agent/subagents/unstartable-worker.ts
deleted file mode 100644
index 24007899c..000000000
--- a/e2e/fixtures/fixture-tasks/agent/subagents/unstartable-worker.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { defineRemoteAgent } from "eve";
-
-export default defineRemoteAgent({
- description: "Intentionally fail remote-agent fetch for deterministic task evals.",
- url: "http://127.0.0.1:1",
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/tools/hold_command.ts b/e2e/fixtures/fixture-tasks/agent/tools/hold_command.ts
deleted file mode 100644
index d7c6126df..000000000
--- a/e2e/fixtures/fixture-tasks/agent/tools/hold_command.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { execFile } from "node:child_process";
-import { promisify } from "node:util";
-
-import { defineTool } from "eve/tools";
-import { z } from "zod";
-
-const runFile = promisify(execFile);
-
-export default defineTool({
- description: "Test-only foreground child-process hold.",
- inputSchema: z.object({ durationSeconds: z.literal(45) }),
- async execute({ durationSeconds }) {
- console.error(`[tui-hang-lab] command started; sleeping ${durationSeconds}s`);
- await runFile("sleep", [String(durationSeconds)]);
- console.error("[tui-hang-lab] command completed");
- return { held: `${durationSeconds}s` };
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/tools/hold_in_process.ts b/e2e/fixtures/fixture-tasks/agent/tools/hold_in_process.ts
deleted file mode 100644
index 5f0972820..000000000
--- a/e2e/fixtures/fixture-tasks/agent/tools/hold_in_process.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { defineTool } from "eve/tools";
-import { z } from "zod";
-
-export default defineTool({
- description: "Test-only in-process foreground hold.",
- inputSchema: z.object({ durationMs: z.literal(45_000) }),
- async execute({ durationMs }) {
- await new Promise((resolve) => setTimeout(resolve, durationMs));
- return { held: `${durationMs}ms` };
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/tools/hold_workflow.ts b/e2e/fixtures/fixture-tasks/agent/tools/hold_workflow.ts
deleted file mode 100644
index 5ff45e73a..000000000
--- a/e2e/fixtures/fixture-tasks/agent/tools/hold_workflow.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { defineWorkflowTool, type WorkflowToolDefinition } from "eve/tools";
-import { sleep } from "workflow";
-import { z } from "zod";
-
-type Input = { duration: "45s" };
-
-async function execute({ duration }: Input): Promise<{ held: "45s" }> {
- "use workflow";
- await sleep(duration);
- return { held: duration };
-}
-
-const tool: WorkflowToolDefinition<Input, { held: "45s" }> = defineWorkflowTool({
- description: "Test-only durable foreground workflow hold.",
- inputSchema: z.object({ duration: z.literal("45s") }),
- execute,
-});
-
-export default tool;
diff --git a/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_hold.ts b/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_hold.ts
deleted file mode 100644
index 33465d0a7..000000000
--- a/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_hold.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import {
- defineWorkflowTool,
- type WorkflowToolContext,
- type WorkflowToolDefinition,
-} from "eve/tools";
-import { z } from "zod";
-import { lifecycleGate } from "../lib/lifecycle-control.js";
-
-async function execute({ key }: { key: string }, ctx: WorkflowToolContext): Promise<string> {
- "use workflow";
- await lifecycleGate(
- {
- key,
- parentSessionId: ctx.session.id,
- marker: "parent",
- sessionId: ctx.session.id,
- turnId: ctx.session.turn.id,
- },
- ctx.abortSignal,
- );
- return "PARENT-RELEASED";
-}
-
-const tool: WorkflowToolDefinition<{ key: string }, string> = defineWorkflowTool({
- description: "Keep Alice's unrelated parent turn active until its session cancellation.",
- inputSchema: z.object({ key: z.string().uuid() }),
- execute,
-});
-
-export default tool;
diff --git a/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_task.ts b/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_task.ts
deleted file mode 100644
index ebfa1a48d..000000000
--- a/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_task.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import {
- defineWorkflowTool,
- type WorkflowToolContext,
- type WorkflowToolDefinition,
-} from "eve/tools";
-import { getWorkflowMetadata } from "workflow";
-import { z } from "zod";
-import {
- AUTH_SNAPSHOT_MARKER,
- lifecycleGate,
- publishLifecycleControl,
- type LifecycleMarker,
-} from "../lib/lifecycle-control.js";
-
-type Input = {
- key: string;
- marker: Exclude<LifecycleMarker, "parent">;
- child: boolean;
- delayedAuthChild?: boolean;
-};
-
-async function execute(
- { key, marker, child, delayedAuthChild }: Input,
- ctx: WorkflowToolContext,
-): Promise<string> {
- "use workflow";
- const parentSessionId = ctx.session.id;
- await publishLifecycleControl(parentSessionId, key, {
- kind: "owner",
- marker,
- runId: getWorkflowMetadata().workflowRunId,
- sessionId: parentSessionId,
- turnId: ctx.session.turn.id,
- });
- if (delayedAuthChild === true) {
- await lifecycleGate({
- parentSessionId,
- key,
- marker,
- sessionId: ctx.session.id,
- turnId: ctx.session.turn.id,
- });
- await ctx.agent("auth-snapshot-worker", {
- message: "Call snapshot_whoami exactly once.",
- });
- } else if (child) {
- try {
- await ctx.agent("lifecycle-worker", {
- message: JSON.stringify({ parentSessionId, key, marker }),
- });
- throw new Error("Bob's terminal model rejection was not observed.");
- } catch (error) {
- if (
- error === null ||
- typeof error !== "object" ||
- Reflect.get(error, "code") !== "SUBAGENT_EXECUTION_FAILED" ||
- !String(Reflect.get(error, "message")).includes("LIFECYCLE-TERMINAL-REJECTION")
- )
- throw error;
- }
- } else {
- await lifecycleGate({
- parentSessionId,
- key,
- marker,
- sessionId: ctx.session.id,
- turnId: ctx.session.turn.id,
- });
- }
- return `LIFECYCLE:${marker}`;
-}
-
-const tool: WorkflowToolDefinition<Input, string> = defineWorkflowTool({
- description: "Coordinate independently released background work for lifecycle checks.",
- execution: "background",
- inputSchema: z.object({
- key: z.string().uuid(),
- marker: z.enum(["A", "B", AUTH_SNAPSHOT_MARKER]),
- child: z.boolean(),
- delayedAuthChild: z.boolean().optional(),
- }),
- execute,
-});
-
-export default tool;
diff --git a/e2e/fixtures/fixture-tasks/agent/tools/remote_gate.ts b/e2e/fixtures/fixture-tasks/agent/tools/remote_gate.ts
deleted file mode 100644
index aba06ee2d..000000000
--- a/e2e/fixtures/fixture-tasks/agent/tools/remote_gate.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { defineTool } from "eve/tools";
-import { once } from "eve/tools/approval";
-import { z } from "zod";
-
-export default defineTool({
- description: "Remote-child approval gate that reports the resumed HTTP principal.",
- inputSchema: z.object({ marker: z.literal("C8") }),
- approval: once(),
- async execute(_input, ctx) {
- const current = ctx.session.auth.current;
- const principal = current === null ? "none" : `${current.principalType}:${current.principalId}`;
- return { marker: `C8-REMOTE-PRINCIPAL:${principal}` };
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/agent/tools/snapshot_whoami.ts b/e2e/fixtures/fixture-tasks/agent/tools/snapshot_whoami.ts
deleted file mode 100644
index 88f42426c..000000000
--- a/e2e/fixtures/fixture-tasks/agent/tools/snapshot_whoami.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { defineTool } from "eve/tools";
-import { z } from "zod";
-
-export default defineTool({
- description: "Report the current and initiating principals for this session turn.",
- inputSchema: z.object({}),
- execute(_input, ctx) {
- return {
- current: ctx.session.auth.current?.principalId ?? null,
- initiator: ctx.session.auth.initiator?.principalId ?? null,
- };
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/evals/README.md b/e2e/fixtures/fixture-tasks/evals/README.md
deleted file mode 100644
index c559ec94f..000000000
--- a/e2e/fixtures/fixture-tasks/evals/README.md
+++ /dev/null
@@ -1,138 +0,0 @@
-# Task eval transitions
-
-## Full-cohort completion barrier
-
-This fixture uses a static mock model for scripted orchestration checks. Real-model
-coverage lives separately in [`agent-task-reporting`](../../agent-task-reporting/evals/README.md),
-whose agent uses `defineAgent(e2eAgentConfig())` without scenario-based routing.
-
-`task.parent.wake.emitted-ready.batching.eval.ts` releases ten scripted children
-in burst and staggered schedules. Each child needs a separate approval before
-returning its marked result. The driver sends approval responses without waiting
-for a parent model turn and observes child completion before advancing. It retains
-the parent stream cursor from before the releases, so an intermediate completion-driven
-model turn fails even if it emits no text. Both schedules require zero intermediate
-completion model steps and one full-cohort turn. Every known task ID must be
-delivered once, and the report must contain each distinct output once. Both cases
-also require an unrelated user answer while the last child remains blocked. The
-mock neither delays inference nor returns a silence sentinel; a completion-driven
-model invocation before settlement is an error. Each case still logs its
-`task-batching` metrics.
-
-`task.join.evaluate.observed-partial.eval.ts` establishes partial completion on
-one child's stream while the other still awaits approval. An independent user
-status request receives WAITING without a completion-driven model step. Releasing
-the remaining sibling then delivers both task IDs in one COMPLETE turn. The
-transition metadata separates lifecycle readiness from parent admission: successes
-wait for all original siblings, even across unrelated user turns and cohorts;
-input, authorization, failures, and cancellation bypass that hold.
-
-The separate `agent-task-reporting` fixture uses the same approval-gated approach
-with real models for the parent, children, and a nested warehouse lookup. It covers
-an intervening user answer and compaction without waiting for partial parent wakes.
-
-## Lifecycle ordering and overlapping launches
-
-`task.parent.wake.emitted-ready.lifecycle-order.eval.ts` holds an unrelated parent
-turn in a blocking Workflow hook. Task A returns successfully before B's child is
-released. The fixture waits for A's task owner (not its child stream) to finish:
-that owner awaits its real terminal inbox wake before returning. B then receives a
-permanent mock-provider rejection after a successful metered model step. Its
-background workflow catches the expected child failure and completes successfully.
-The task owner's recorded forwarding steps must show invocation, settlement, then
-completion, and the parent hook must still be active after both owners finish.
-This establishes A completed → B agent-settled → B completed in the real queue.
-
-The report must contain exactly both task receipts and outputs, once, through a
-subsequent user-message acknowledgment. A separate follow-up turn echoes the actual
-framework-rendered handle announcement: B's terminal child must not remain as an
-available handle. Another check crosses the parent's configured one-million-input-token
-budget: B supplies 211 input tokens, all ordinary parent responses supply zero,
-and an accounting turn supplies 999,790. The next request must produce the
-runtime-authored session-limit prompt with exactly 1,000,001 used tokens. Dropping
-B's settlement therefore fails usage accounting even if the union report looks
-correct. The enlarged fixture context window prevents this metered probe from
-triggering compaction. B's terminal failure and original 211/37 token step are
-also asserted on its real child stream.
-
-`task.parent.wake.emitted-ready.cross-turn-cohort.eval.ts` launches A, acknowledges
-its pending gate, then launches B in a different user turn. Both task-owner
-creating-turn IDs must match their respective launch events and be distinct. The
-two cases release A first and B first respectively. After the first owner's
-completion acknowledgment, an independent user checkpoint must run without any
-completion delivery while the other gate remains active. The final delivery is
-exactly the union, never one report per creating turn. The mock reports received
-notifications immediately; it does not implement its own cohort barrier.
-
-The `/eve/v1/task-lifecycle/:sessionId/:action` channel is fixture-only and stays
-inside the fixture's Vercel service route prefix. Random per-eval
-keys scope control-stream reads; releases validate gate metadata against that key
-and parent session. Reads, bodies, and owner-log audits are bounded. The route
-only releases authored hooks and reads actual Workflow owner metadata; it never
-inserts task lifecycle payloads, edits session state, or calls production routing
-helpers. No production hook or internal/testing package export is needed. These
-evals run only in CI, without timing sleeps or external services.
-
-## Remote callback routing regression
-
-`task.input.answer.accepted-complete.remote.eval.ts` reuses the existing remote
-HITL and completion round trip to cover the callback-prefix bug from
-[eve #3047](https://github.com/vercel/eve/pull/3047). The fixture's `vercel.json`
-sets the service route to `/eve/v1`.
-
-The eval uses event assertions labeled "remote input callback reaches the parent"
-and "remote completion callback reaches the parent". It also logs which delivery
-it is waiting for. These assertions check the live round trip through the public
-eval APIs; they do not inspect the generated callback URL.
-
-The [build scenario](../../../../packages/eve/src/internal/nitro/host/build-application.scenario.test.ts)
-separately checks that this service route adds no extra public prefix. Local and
-Postgres runs exercise the remote round trip, but only the Vercel build exercises
-service-prefix inference.
-
-## Child tool surface and completion
-
-`task.lifecycle.complete.accepted-nonterminal.child-tool-surface.eval.ts` uses a
-mock child in every suite to report its actual advertised tool names. It checks
-that `task_update` is absent and the final report reaches the parent with the
-correct task identity. Tool and workflow progress remain covered separately by
-`agent-background-tools` and `agent-workflow-tools`.
-
-## Transition declarations
-
-These evals are executable evidence for the background-task contract. They do
-not define that contract.
-
-When sources disagree, use this precedence:
-
-1. `research/tools-as-tasks.md` for settled externally observable intent.
-2. Public tool and protocol contracts.
-3. `packages/eve/src/tasks/types.ts` and `transitions.ts` for executable
- lifecycle semantics.
-4. Evals and lower-level implementation as evidence.
-
-Every `*.eval.ts` case uses `defineTaskEval` and declares exactly one primary
-transition. The canonical specification in `task-transition.ts` supplies its
-pre-state, semantic input, guards, outcome, post-state, events, and side
-effects. `setup` records prerequisite transitions but does not claim coverage
-for them.
-
-Transition anchors follow:
-
-```text
-<machine>.<entity>.<input>.<outcome>[-<guard>]
-```
-
-Anchors describe semantics, never document order. Scenario variants such as
-local and remote transport share an anchor and use a filename suffix plus the
-`dimensions` declaration. Presentation labels such as A2 or C7 are not stable
-identity.
-
-State is factored across lifecycle, outstanding input, executor binding,
-dispatch admission, agent occupancy, parent phase, transport, ownership, and
-usage. A scenario declares only dimensions relevant to its primary transition;
-it must not enumerate their Cartesian product.
-
-`pnpm validate:transitions` enforces declaration and filename identity. The
-fixture `typecheck` command runs that validation before building and checking
-TypeScript.
diff --git a/e2e/fixtures/fixture-tasks/evals/batching.ts b/e2e/fixtures/fixture-tasks/evals/batching.ts
deleted file mode 100644
index ff3e69c73..000000000
--- a/e2e/fixtures/fixture-tasks/evals/batching.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
-import { type EveEvalContext, type EveEvalTurn, type InputRequest } from "eve/evals";
-import { equals } from "eve/evals/expect";
-
-import {
- requireSessionStreamIndex,
- waitForChildResult,
- type TaskEvalSessionDriver,
-} from "./shared.js";
-
-/** Release children independently of parent wakes, retaining the entire parent stream suffix. */
-export async function startBlockedFanout(t: EveEvalContext, count: number) {
- const started = await t.send("TASK-BATCHING-BENCHMARK", { taskDeliveryPolicy: "cohort" });
- let session: TaskEvalSessionDriver = started.session;
- started.expectOk();
- started.noFailedActions();
- started.messageIncludes("TASK-FANOUT-STARTED");
- started.calledSubagent("fanout-worker", { status: "working", count });
- const receipts = taskReceipts(started.events);
- const taskIds = receipts.map(({ taskId }) => taskId);
- await t.require(
- { receipts: taskIds.length, distinct: new Set(taskIds).size },
- equals({ receipts: count, distinct: count }),
- );
-
- const setupEvents: EveEvalTurn["events"][number][] = [];
- const requests = new Map<string, InputRequest>();
- collectRequests(started);
- while (requests.size < count) {
- collectRequests(await nextTurn());
- }
-
- const children = setupEvents.flatMap((event) => {
- if (event.type !== "subagent.called") return [];
- const action = setupEvents
- .flatMap((entry) => (entry.type === "actions.requested" ? entry.data.actions : []))
- .find((entry) => entry.callId === event.data.callId);
- const marker =
- typeof action?.input.message === "string"
- ? /FANOUT-WORKER-\d+/u.exec(action.input.message)?.[0]
- : undefined;
- const receipt = receipts.find(({ callId }) => callId === event.data.callId);
- if (marker === undefined || receipt === undefined) {
- throw new Error("Fanout child has no marked delegation and matching task receipt.");
- }
- return [
- {
- marker,
- taskId: receipt.taskId,
- sessionId: event.data.childSessionId,
- turnId: event.data.turnId,
- },
- ];
- });
- await t.require(
- {
- children: children.length,
- sessions: new Set(children.map((child) => child.sessionId)).size,
- tasks: children.map((child) => child.taskId).sort(),
- markers: children.map((child) => child.marker).sort(),
- creatingTurns: new Set(children.map((child) => child.turnId)).size,
- },
- equals({
- children: count,
- sessions: count,
- tasks: [...taskIds].sort(),
- markers: Array.from({ length: count }, (_, index) => `FANOUT-WORKER-${index + 1}`).sort(),
- creatingTurns: 1,
- }),
- );
-
- await t.require(
- {
- markers: [...requests.keys()].sort(),
- requestIds: new Set([...requests.values()].map((request) => request.requestId)).size,
- },
- equals({ markers: children.map((child) => child.marker).sort(), requestIds: count }),
- );
- const remaining = [...children];
- const completedChildren: EveEvalTurn[] = [];
- const parentTurns: EveEvalTurn[] = [];
- const completionTurns: EveEvalTurn[] = [];
-
- return {
- started,
- taskIds,
- completedChildren,
- parentTurns,
- completionTurns,
- async completeNext(batchSize: number) {
- const batch = remaining.splice(0, batchSize);
- await t.require(batch.length, equals(batchSize));
- // respond() waits for a parent boundary that the cohort barrier deliberately withholds.
- await post({
- inputResponses: batch.map(({ marker }) => ({
- requestId: requests.get(marker)!.requestId,
- optionId: "approve",
- })),
- });
- for (const child of batch) {
- completedChildren.push(
- await waitForChildResult(t, child.sessionId, `FANOUT-COMPLETE:${child.marker}`),
- );
- }
- if (remaining.length === 0) {
- for (let attempt = 0; attempt < count + 3; attempt += 1) {
- const turn = observe(await nextTurn());
- if (completedTaskIds(turn).length > 0) {
- await t.require(completedTaskIds(turn).sort(), equals([...taskIds].sort()));
- return;
- }
- turn.notEvent("step.started");
- }
- throw new Error("The settled cohort produced no completion report.");
- }
- },
- async send(message: string) {
- await post({ message, turnPolicy: "queue" });
- for (let attempt = 0; attempt < count + 3; attempt += 1) {
- const turn = observe(await nextTurn());
- await t.require(completedTaskIds(turn), equals([]));
- if (
- turn.events.some(
- (event) => event.type === "message.received" && event.data.message === message,
- )
- )
- return turn;
- turn.notEvent("step.started");
- }
- throw new Error("The user message did not run while a sibling was blocked.");
- },
- };
-
- function collectRequests(turn: EveEvalTurn) {
- setupEvents.push(...turn.events);
- for (const request of turn.inputRequests) {
- if (request.action.toolName !== "release") continue;
- const marker = request.action.input.marker;
- if (
- typeof marker !== "string" ||
- (requests.has(marker) && requests.get(marker)!.requestId !== request.requestId)
- ) {
- throw new Error("Fanout release requests must have distinct child markers.");
- }
- requests.set(marker, request);
- }
- }
-
- function observe(turn: EveEvalTurn) {
- parentTurns.push(turn);
- if (completedTaskIds(turn).length > 0) completionTurns.push(turn);
- return turn;
- }
-
- async function post(body: unknown) {
- const response = await t.target.fetch(
- `/eve/v1/session/${encodeURIComponent(started.sessionId)}`,
- {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- signal: t.signal,
- },
- );
- await t.require(response.status, equals(202));
- await response.body?.cancel();
- }
-
- async function nextTurn() {
- const live = t.target.watchTurn(started.sessionId, {
- startIndex: requireSessionStreamIndex(session, "Cohort parent"),
- });
- const turn = await live.result();
- session = live.session;
- return turn.expectOk();
- }
-}
-
-export function completedTaskIds(turn: EveEvalTurn): string[] {
- const notification = /Background task (task_[a-z0-9]+) \([^)]+\) is completed\./giu;
- return turn.events.flatMap((event) => {
- if (event.type !== "message.received") return [];
- return [...event.data.message.matchAll(notification)].map((match) => match[1]!);
- });
-}
-
-export function completionMetrics(turns: readonly EveEvalTurn[]) {
- const events = turns.flatMap((turn) => turn.events);
- const messages = events
- .filter((event) => event.type === "message.completed")
- .filter((event) => event.data.finishReason !== "tool-calls");
- return {
- parentTurns: turns.length,
- modelSteps: events.filter((event) => event.type === "step.started").length,
- silentMessages: messages.filter((event) => event.data.message === null).length,
- visibleMessages: messages.filter((event) => event.data.message !== null).length,
- completionsPerTurn: turns.map((turn) => completedTaskIds(turn).length),
- };
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/evals.config.ts b/e2e/fixtures/fixture-tasks/evals/evals.config.ts
deleted file mode 100644
index d551c179a..000000000
--- a/e2e/fixtures/fixture-tasks/evals/evals.config.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { defineEvalConfig } from "eve/evals";
-
-export default defineEvalConfig({
- // Task evals dispatch durable child workflows. Serialize evals so they do
- // not starve each other's children past the per-eval timeout (same
- // rationale as agent-subagents).
- maxConcurrency: 1,
- timeoutMs: 120_000,
-});
diff --git a/e2e/fixtures/fixture-tasks/evals/lifecycle-model.test.mjs b/e2e/fixtures/fixture-tasks/evals/lifecycle-model.test.mjs
deleted file mode 100644
index df69f752a..000000000
--- a/e2e/fixtures/fixture-tasks/evals/lifecycle-model.test.mjs
+++ /dev/null
@@ -1,77 +0,0 @@
-import assert from "node:assert/strict";
-import { test } from "node:test";
-import {
- CROSS_TURN_SCENARIO,
- LIFECYCLE_SCENARIO,
- lifecycleModel,
-} from "../agent/lib/lifecycle-model.ts";
-
-const key = "00000000-0000-4000-8000-000000000001";
-const instruction =
- "Background task reporting: launch acknowledgement\nAcknowledge the accepted work.";
-const taskState = '[Task state]\n{"tasks":[{"taskId":"task_a","status":"pending"}]}';
-
-function request(userMessages, markers = []) {
- return {
- userMessages,
- messages: userMessages.map((text) => ({ role: "user", text })),
- toolResults: markers.map((marker) => ({
- id: `lifecycle-${marker}`,
- name: "lifecycle_task",
- output: { status: "working", taskId: `task_${marker.toLowerCase()}` },
- })),
- };
-}
-
-for (const [scenario, markers] of [
- [CROSS_TURN_SCENARIO, ["A"]],
- [LIFECYCLE_SCENARIO, ["A", "B"]],
-]) {
- test(`${scenario} acknowledges receipts behind framework instructions`, () => {
- const messages = [`${scenario} ${key}`, taskState, instruction];
- assert.deepEqual(lifecycleModel(request(messages, markers)), {
- text: `LAUNCHED:${markers.join(",")}`,
- usage: { inputTokens: 0, outputTokens: 0 },
- });
- });
-}
-
-test("second-turn receipts are acknowledged without a premature report", () => {
- const messages = [
- `${CROSS_TURN_SCENARIO} ${key}`,
- taskState,
- instruction,
- "Alice now launches the second piece of work.",
- taskState,
- instruction,
- ];
- assert.equal(lifecycleModel(request(messages, ["A", "B"])).text, "LAUNCHED:B");
-});
-
-test("reports every actual completion, not framework reporting instructions", () => {
- const a = "Background task task_a (lifecycle_task) is completed.\n\nResult:\nLIFECYCLE:A";
- const b = "Background task task_b (lifecycle_task) is completed.\n\nResult:\nLIFECYCLE:B";
- const messages = [`${LIFECYCLE_SCENARIO} ${key}`, instruction, a, b, taskState, instruction];
- const response = lifecycleModel(request(messages, ["A", "B"]));
- assert.deepEqual(JSON.parse(response.text), {
- report: "LIFECYCLE-REPORT",
- notifications: [a, b],
- });
-});
-
-test("does not implement a model-side barrier that could hide a partial runtime delivery", () => {
- const a = "Background task task_a (lifecycle_task) is completed.\n\nResult:\nLIFECYCLE:A";
- const response = lifecycleModel(
- request([`${CROSS_TURN_SCENARIO} ${key}`, a, instruction], ["A", "B"]),
- );
- assert.deepEqual(JSON.parse(response.text).notifications, [a]);
-});
-
-test("continues to answer ordinary user messages after a completed cohort", () => {
- const messages = [
- `${LIFECYCLE_SCENARIO} ${key}`,
- "Background task task_a (lifecycle_task) is completed.\n\nResult:\nLIFECYCLE:A",
- "Alice confirms that all completion deliveries have been observed.",
- ];
- assert.equal(lifecycleModel(request(messages, ["A", "B"])).text, "DRAIN-ACK");
-});
diff --git a/e2e/fixtures/fixture-tasks/evals/lifecycle.ts b/e2e/fixtures/fixture-tasks/evals/lifecycle.ts
deleted file mode 100644
index 02c2425d9..000000000
--- a/e2e/fixtures/fixture-tasks/evals/lifecycle.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-import type { EveEvalContext, EveEvalTurn } from "eve/evals";
-import { equals } from "eve/evals/expect";
-import type { LifecycleControlEvent } from "../agent/lib/lifecycle-control.js";
-import { completedTaskIds } from "./batching.js";
-import { requireSessionStreamIndex } from "./shared.js";
-
-export function lifecycleDriver(t: EveEvalContext, key: string) {
- let index = 0;
- const controls: LifecycleControlEvent[] = [];
- const turns: EveEvalTurn[] = [];
- let streamIndex = 0;
- let sessionId: string;
- const taskIds = new Map<string, string>();
-
- async function post<T>(action: string, body: object): Promise<T> {
- const response = await t.target.fetch(
- `/eve/v1/task-lifecycle/${encodeURIComponent(sessionId)}/${action}`,
- {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ key, ...body }),
- signal: t.signal,
- },
- );
- await t.require(response.status, equals(200));
- return (await response.json()) as T;
- }
-
- function record(turn: EveEvalTurn) {
- turns.push(turn);
- for (const call of turn.toolCalls) {
- if (call.name !== "lifecycle_task") continue;
- const marker = call.input.marker;
- const output = call.output;
- if (
- typeof marker !== "string" ||
- output === null ||
- typeof output !== "object" ||
- !("taskId" in output) ||
- typeof output.taskId !== "string"
- )
- throw new Error("Missing lifecycle task receipt.");
- taskIds.set(marker, output.taskId);
- }
- return turn;
- }
-
- async function nextTurn() {
- const live = t.target.watchTurn(sessionId, { startIndex: streamIndex });
- const turn = (await live.result()).expectOk();
- streamIndex = requireSessionStreamIndex(live.session, "Lifecycle parent");
- return record(turn);
- }
-
- return {
- turns,
- controls,
- taskIds,
- async start(message: string) {
- const turn = (await t.send(message, { taskDeliveryPolicy: "cohort" })).expectOk();
- sessionId = turn.sessionId;
- streamIndex = requireSessionStreamIndex(turn.session, "Lifecycle setup");
- return record(turn);
- },
- async gate(marker: "A" | "B" | "parent") {
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const found = controls.find((event) => event.kind === "gate" && event.marker === marker);
- if (found !== undefined) return found;
- controls.push(await post<LifecycleControlEvent>("next", { index: index++ }));
- }
- throw new Error(`No ${marker} lifecycle gate acknowledgment.`);
- },
- async release(gate: LifecycleControlEvent) {
- if (gate.token === undefined) throw new Error("Missing fixture gate token.");
- await t.require(await post("release", { token: gate.token }), equals({ released: true }));
- },
- async settled(marker: "A" | "B", agent = false) {
- await t.require(
- await post("settled", { marker }),
- equals({
- marker,
- status: "completed",
- notificationCount: agent ? 3 : 1,
- }),
- );
- },
- async active(gate: LifecycleControlEvent) {
- await t.require(await post("active", { token: gate.token }), equals({ status: "running" }));
- },
- async cancelHeldTurn(parent: LifecycleControlEvent) {
- if (parent.kind !== "gate" || parent.marker !== "parent" || parent.sessionId !== sessionId) {
- throw new Error("Cancellation must address this session's acknowledged parent gate.");
- }
- // Use the same FIFO session inbox as task wakes, never a private turn/gate hook.
- // Omit tasks: cancellation must not retire either background task's ownership.
- const response = await t.target.fetch(
- `/eve/v1/session/${encodeURIComponent(sessionId)}/cancel`,
- {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ turnId: parent.turnId }),
- signal: t.signal,
- },
- );
- await t.require(response.status, equals(202));
- await t.require(await response.json(), equals({ ok: true, status: "accepted", sessionId }));
- },
- async parentGateCancelled(parent: LifecycleControlEvent) {
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const acknowledgement = controls.find(
- (event) => event.kind === "gate-cancelled" && event.marker === "parent",
- );
- if (acknowledgement !== undefined) {
- await t.require(
- acknowledgement,
- equals({
- kind: "gate-cancelled",
- marker: "parent",
- runId: parent.runId,
- sessionId: parent.sessionId,
- turnId: parent.turnId,
- }),
- );
- return;
- }
- controls.push(await post<LifecycleControlEvent>("next", { index: index++ }));
- }
- throw new Error("The cancelled parent gate did not acknowledge hook disposal.");
- },
- async enqueue(message: string) {
- const response = await t.target.fetch(`/eve/v1/session/${encodeURIComponent(sessionId)}`, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ message, turnPolicy: "queue" }),
- signal: t.signal,
- });
- await t.require(response.status, equals(202));
- await response.body?.cancel();
- },
- nextTurn,
- async through(message: string, allowCompletions = false) {
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const turn = await nextTurn();
- if (!allowCompletions) await t.require(completedTaskIds(turn), equals([]));
- if (
- turn.events.some(
- (event) => event.type === "message.received" && event.data.message === message,
- )
- )
- return turn;
- }
- throw new Error("Lifecycle checkpoint message was not acknowledged.");
- },
- async report() {
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const turn = await nextTurn();
- if (completedTaskIds(turn).length > 0) return turn;
- }
- throw new Error("Lifecycle cohort did not deliver a completion report.");
- },
- };
-}
-
-export function assertLifecycleUnion(
- t: EveEvalContext,
- driver: ReturnType<typeof lifecycleDriver>,
-) {
- const completions = driver.turns.filter((turn) => completedTaskIds(turn).length > 0);
- const expected = [...driver.taskIds.values()].sort();
- t.check(
- driver.turns.flatMap((turn) => turn.toolCalls).filter((call) => call.name === "lifecycle_task")
- .length,
- equals(2),
- ).label("exactly two background launches, without replacement or duplicate tasks");
- t.check(
- completions.map((turn) => completedTaskIds(turn).sort()),
- equals([expected]),
- ).label("one completion turn containing exactly the union of both launch receipts");
- t.check(
- completions.flatMap((turn) => turn.events.filter((event) => event.type === "step.started"))
- .length,
- equals(1),
- ).label("no extra completion-driven model steps");
- const messages = completions.flatMap((turn) =>
- turn.events.filter(
- (event) => event.type === "message.completed" && event.data.message !== null,
- ),
- );
- t.check(messages.length, equals(1)).label("exactly one visible final report");
- const report = completions[0]?.message;
- if (report === undefined) throw new Error("Missing union report.");
- const parsed = JSON.parse(report) as { report: string; notifications: string[] };
- t.check(parsed.report, equals("LIFECYCLE-REPORT"));
- for (const marker of ["A", "B"]) {
- t.check(
- parsed.notifications.join("\n").split(`LIFECYCLE:${marker}`).length - 1,
- equals(1),
- ).label(`${marker} output appears exactly once in the final union`);
- }
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/shared.ts b/e2e/fixtures/fixture-tasks/evals/shared.ts
deleted file mode 100644
index 70631b5bb..000000000
--- a/e2e/fixtures/fixture-tasks/evals/shared.ts
+++ /dev/null
@@ -1,294 +0,0 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
-import type { EveEvalContext, EveEvalSession, EveEvalTurn, InputRequest } from "eve/evals";
-import { equals, satisfies } from "eve/evals/expect";
-
-export type TaskEvalSessionDriver = Pick<
- EveEvalSession,
- "events" | "pendingInputRequests" | "respond" | "send" | "sessionId" | "state"
->;
-
-export interface PendingTaskInput {
- readonly observedTurns: readonly EveEvalTurn[];
- readonly request: InputRequest;
- readonly session: TaskEvalSessionDriver;
-}
-
-export interface FollowedQueuedTurn {
- readonly observedTurns: readonly EveEvalTurn[];
- readonly session: TaskEvalSessionDriver;
- readonly turn: EveEvalTurn;
-}
-
-interface FollowQueuedTurnOptions {
- readonly allowFailedActions?: boolean;
-}
-
-export function requireSessionStreamIndex(
- session: TaskEvalSessionDriver,
- operation: string,
-): number {
- const state = session.state;
- if (state === undefined) throw new Error(`${operation} has no session state.`);
- return state.streamIndex;
-}
-
-/** Observe completion on a child's stream without requiring a parent notification. */
-export async function waitForChildResult(
- t: EveEvalContext,
- sessionId: string,
- expected: string,
-): Promise<EveEvalTurn> {
- let startIndex = 0;
- for (let attempt = 0; attempt < 4; attempt += 1) {
- const live = t.target.watchTurn(sessionId, { startIndex });
- const turn = (await live.result()).expectOk();
- startIndex = requireSessionStreamIndex(live.session, "Child completion");
- if (turn.message === undefined || !turn.events.some((event) => event.type === "turn.completed"))
- continue;
- await t.require(turn.message, equals(expected));
- return turn;
- }
- throw new Error(`Child ${sessionId} did not complete with its expected result.`);
-}
-
-/** Waits across server-initiated parent turns for one task-owned input request. */
-export async function waitForTaskInput(
- t: EveEvalContext,
- initialSession: TaskEvalSessionDriver,
- toolName: string,
-): Promise<PendingTaskInput> {
- let session = initialSession;
- const observedTurns: EveEvalTurn[] = [];
- for (let attempt = 0; attempt < 5; attempt += 1) {
- const matching = session.pendingInputRequests.filter(
- (request) => request.action.toolName === toolName,
- );
- if (matching.length > 1) {
- throw new Error(`Task surfaced ${matching.length} pending requests for tool "${toolName}".`);
- }
- if (matching[0] !== undefined) {
- if (session.pendingInputRequests.length !== 1) {
- throw new Error(
- `Task surfaced unexpected pending input alongside tool "${toolName}": ${session.pendingInputRequests
- .map((request) => request.action.toolName)
- .join(", ")}.`,
- );
- }
- return { observedTurns, request: matching[0], session };
- }
- if (session.pendingInputRequests.length > 0) {
- throw new Error(
- `Expected task input for tool "${toolName}"; received ${session.pendingInputRequests
- .map((request) => request.action.toolName)
- .join(", ")}.`,
- );
- }
-
- const sessionId = session.sessionId;
- if (sessionId === undefined) throw new Error("Task input wait has no parent session id.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Task input wait"),
- });
- const turn = await live.result();
- turn.noFailedActions().label(`task input wait ${attempt + 1} has no failed actions`);
- observedTurns.push(turn);
- session = live.session;
- }
- throw new Error(`Task did not surface input for tool "${toolName}" after five turns.`);
-}
-
-/** Reads the working task receipt returned by a background tool call. */
-export function requireBackgroundTaskId(turn: EveEvalTurn): string {
- const receipt = taskReceipts(turn.events)[0];
- if (receipt === undefined) throw new Error("Turn completed without a background task receipt.");
- return receipt.taskId;
-}
-
-export function parseToolErrorOutput(output: unknown): unknown {
- if (typeof output !== "string") return output;
- try {
- return JSON.parse(output);
- } catch {
- return output;
- }
-}
-
-/** Returns the exact model-visible task view from a task-control result. */
-export function requireTaskView(output: unknown, taskId: string): Record<string, unknown> {
- if (output === null || typeof output !== "object") {
- throw new Error("Task control did not return an object.");
- }
- const tasks = Reflect.get(output, "tasks");
- if (!Array.isArray(tasks)) throw new Error("Task control did not return a tasks array.");
- const matches = tasks.filter(
- (candidate) =>
- candidate !== null &&
- typeof candidate === "object" &&
- Reflect.get(candidate, "taskId") === taskId,
- );
- if (matches.length !== 1) {
- throw new Error(`Task control returned ${matches.length} views for ${taskId}.`);
- }
- return matches[0] as Record<string, unknown>;
-}
-
-/** Follows queued server turns until the requested user message owns a turn. */
-export async function sendAndFollowQueuedTurn(
- t: EveEvalContext,
- message: string,
- initialSession: TaskEvalSessionDriver,
- options: FollowQueuedTurnOptions = {},
-): Promise<FollowedQueuedTurn> {
- let session = initialSession;
- let turn = await session.send(message, { taskDeliveryPolicy: "cohort" });
- const observedTurns = [turn];
- for (let attempt = 0; attempt < 20; attempt += 1) {
- if (options.allowFailedActions !== true) {
- turn.noFailedActions().label(`queued turn ${attempt + 1} has no failed actions`);
- }
- const received = turn.events.some(
- (event) =>
- event.type === "message.received" && messageText(event.data.message).includes(message),
- );
- if (received) return { observedTurns, session, turn };
-
- const sessionId = session.sessionId;
- if (sessionId === undefined) throw new Error("Queued turn follow-up has no session id.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Queued turn follow-up"),
- });
- turn = await live.result();
- observedTurns.push(turn);
- session = live.session;
- }
- throw new Error(`Queued message "${message}" was not received after 20 turns.`);
-}
-
-/** Waits for one runtime-authored terminal task delivery on the parent stream. */
-export async function waitForTaskNotification(
- t: EveEvalContext,
- initialSession: TaskEvalSessionDriver,
- taskId: string,
- status: "cancelled" | "completed" | "failed",
- observedTurns: readonly EveEvalTurn[] = [],
-): Promise<{ readonly session: TaskEvalSessionDriver; readonly turn: EveEvalTurn }> {
- let session = initialSession;
- const expected = `Background task ${taskId} (`;
- const matches = (turn: EveEvalTurn) =>
- turn.events.some(
- (event) =>
- event.type === "message.received" &&
- messageText(event.data.message).includes(expected) &&
- messageText(event.data.message).includes(` is ${status}.`),
- );
- const observed = observedTurns.find(matches);
- if (observed !== undefined) return { session, turn: observed };
- const recorded = session.events.some(
- (event) =>
- event.type === "message.received" &&
- messageText(event.data.message).includes(expected) &&
- messageText(event.data.message).includes(` is ${status}.`),
- );
- if (recorded) {
- const turn = observedTurns.at(-1);
- if (turn === undefined) {
- throw new Error(`Task ${taskId} notification was recorded without an observed turn.`);
- }
- return { session, turn };
- }
- for (let attempt = 0; attempt < 20; attempt += 1) {
- const sessionId = session.sessionId;
- if (sessionId === undefined)
- throw new Error("Task notification wait has no parent session id.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Task notification wait"),
- });
- const turn = await live.result();
- turn.noFailedActions().label(`task notification wait ${attempt + 1} has no failed actions`);
- session = live.session;
- if (matches(turn)) return { session, turn };
- }
- throw new Error(`Task ${taskId} did not deliver terminal status "${status}" after 20 turns.`);
-}
-
-/** Waits for completion, then reads the immutable terminal view through no-op cancellation. */
-export async function waitForCompletedTask(
- t: EveEvalContext,
- session: TaskEvalSessionDriver,
- verificationMessage: string,
- taskId: string,
-): Promise<EveEvalTurn> {
- return await waitForTaskStatus(t, session, verificationMessage, taskId, "completed");
-}
-
-/** Waits for a terminal status, then reads it through no-op cancellation. */
-export async function waitForTaskStatus(
- t: EveEvalContext,
- session: TaskEvalSessionDriver,
- verificationMessage: string,
- taskId: string,
- status: string,
-): Promise<EveEvalTurn> {
- let currentSession = session;
- const timeoutMs = 30_000;
- const deadline = performance.now() + timeoutMs;
- let attempt = 0;
- while (performance.now() < deadline) {
- const followed = await sendAndFollowQueuedTurn(
- t,
- `${verificationMessage} ${taskId}`,
- currentSession,
- );
- for (const [turnIndex, observed] of followed.observedTurns.entries()) {
- observed
- .noFailedActions()
- .label(`task status attempt ${attempt + 1}, turn ${turnIndex + 1} has no failed actions`);
- }
- const turn = followed.turn;
- currentSession = followed.session;
- const inspected = turn.toolCalls.find((call) => call.name === "task_cancel");
- if (taskStatus(inspected?.output, taskId) === status) {
- await t.require(
- inspected?.output,
- satisfies(
- (output) => taskStatus(output, taskId) === status,
- `task_cancel preserves ${status} task ${taskId}`,
- ),
- );
- return turn;
- }
- attempt += 1;
- await t.sleep(100);
- }
- throw new Error(
- `Task ${taskId} did not reach "${status}" within ${timeoutMs / 1_000} seconds (${attempt} verification attempts).`,
- );
-}
-
-function messageText(message: unknown): string {
- if (typeof message === "string") return message;
- if (!Array.isArray(message)) return "";
- return message
- .flatMap((part) =>
- part !== null &&
- typeof part === "object" &&
- Reflect.get(part, "type") === "text" &&
- typeof Reflect.get(part, "text") === "string"
- ? [Reflect.get(part, "text") as string]
- : [],
- )
- .join("\n");
-}
-
-function taskStatus(output: unknown, taskId: string): unknown {
- if (output === null || typeof output !== "object") return undefined;
- const tasks = Reflect.get(output, "tasks");
- if (!Array.isArray(tasks)) return undefined;
- const task = tasks.find(
- (candidate) =>
- candidate !== null &&
- typeof candidate === "object" &&
- Reflect.get(candidate, "taskId") === taskId,
- );
- return task === undefined ? undefined : Reflect.get(task, "status");
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task-transition.ts b/e2e/fixtures/fixture-tasks/evals/task-transition.ts
deleted file mode 100644
index 7da4176fc..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task-transition.ts
+++ /dev/null
@@ -1,491 +0,0 @@
-import { defineEval, type EveEvalDefinition, type EveEvalInput } from "eve/evals";
-
-type Lifecycle = "absent" | "working" | "input_required" | "completed" | "failed" | "cancelled";
-type TransitionOutcome = "accepted" | "noop" | "rejected" | "emitted" | "observed";
-
-interface StatePattern {
- readonly lifecycle?: Lifecycle | readonly Lifecycle[];
- readonly outstandingInput?: "none" | "batch" | "partial-batch" | "authorization";
- readonly executor?: "unbound" | "active" | "parked" | "terminal";
- readonly dispatch?: "absent" | "prepared" | "acknowledged" | "rejected";
- readonly agent?: "available" | "busy";
- readonly parent?: "active" | "parked" | "finalizing";
- readonly ownership?: "owned" | "unowned";
- readonly usage?: "absent" | "retained";
- readonly cohort?: "pending" | "terminal";
-}
-
-type SemanticInput =
- | "delegate"
- | "dispatch-start"
- | "dispatch-batch"
- | "complete"
- | "fail"
- | "cancel"
- | "settle-executor"
- | "require-input"
- | "answer-input"
- | "authorization-callback"
- | "start-turn"
- | "agent-continuation"
- | "agent-steering"
- | "task-peek"
- | "task-notification"
- | "task-update"
- | "parent-message";
-
-type SemanticEvent =
- | "background-receipt"
- | "input-requested"
- | "authorization-required"
- | "authorization-completed"
- | "task-failed-notification"
- | "task-ready-notification"
- | "task-update-notification";
-
-type SemanticSideEffect =
- | "task-view-append"
- | "task-index-write"
- | "child-dispatch"
- | "child-delivery"
- | "child-abort"
- | "parent-model-step"
- | "parent-wake"
- | "completion-hold"
- | "task-view-read"
- | "authorization-request";
-
-interface TransitionSpec {
- readonly preState: StatePattern;
- readonly input: SemanticInput;
- readonly guards: readonly string[];
- readonly expected: {
- readonly outcome: TransitionOutcome;
- readonly postState: StatePattern;
- readonly events: {
- readonly emitted?: readonly SemanticEvent[];
- readonly suppressed?: readonly SemanticEvent[];
- };
- readonly sideEffects: {
- readonly executed?: readonly SemanticSideEffect[];
- readonly suppressed?: readonly SemanticSideEffect[];
- };
- };
-}
-
-function transition(spec: TransitionSpec): TransitionSpec {
- return spec;
-}
-
-/**
- * Stable semantic identities for the task acceptance contract. Presentation
- * order and transport variants never participate in anchor identity.
- */
-export const TASK_TRANSITIONS = {
- "task.lifecycle.complete.accepted-nonterminal": transition({
- preState: { lifecycle: ["working", "input_required"] },
- input: "complete",
- guards: ["task-is-nonterminal"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "completed", outstandingInput: "none" },
- events: { emitted: ["task-ready-notification"] },
- // Lifecycle readiness is distinct from admitting the notification to a parent turn.
- sideEffects: { executed: ["task-view-append"] },
- },
- }),
- "task.lifecycle.fail.accepted-nonterminal": transition({
- preState: { lifecycle: ["working", "input_required"] },
- input: "fail",
- guards: ["task-is-nonterminal"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "failed", outstandingInput: "none" },
- events: { emitted: ["task-ready-notification"] },
- sideEffects: { executed: ["task-view-append", "parent-wake"] },
- },
- }),
- "task.lifecycle.cancel.accepted-nonterminal": transition({
- preState: { lifecycle: ["working", "input_required"] },
- input: "cancel",
- guards: ["task-is-nonterminal"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "cancelled", outstandingInput: "none" },
- events: { emitted: ["task-ready-notification"] },
- sideEffects: { executed: ["task-view-append", "parent-wake", "child-abort"] },
- },
- }),
- "task.lifecycle.cancel.owned-session-accepted-nonterminal": transition({
- preState: { lifecycle: ["working", "input_required"] },
- input: "cancel",
- guards: ["task-is-nonterminal", "parent-session-owns-task"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "cancelled", outstandingInput: "none" },
- events: { emitted: ["task-ready-notification"] },
- sideEffects: { executed: ["task-view-append", "parent-wake", "child-abort"] },
- },
- }),
- "task.lifecycle.cancel.default-preserves-nonterminal": transition({
- preState: { lifecycle: "input_required" },
- input: "cancel",
- guards: ["session-cancel-omits-task-scope"],
- expected: {
- outcome: "noop",
- postState: { lifecycle: "input_required" },
- events: { suppressed: ["task-ready-notification"] },
- sideEffects: { suppressed: ["task-view-append", "child-abort"] },
- },
- }),
- "task.lifecycle.cancel.noop-already-cancelled": transition({
- preState: { lifecycle: "cancelled" },
- input: "cancel",
- guards: ["task-is-already-cancelled"],
- expected: {
- outcome: "noop",
- postState: { lifecycle: "cancelled" },
- events: { suppressed: ["task-ready-notification"] },
- sideEffects: { suppressed: ["task-view-append", "parent-wake", "child-abort"] },
- },
- }),
- "task.lifecycle.result.rejected-already-terminal": transition({
- preState: { lifecycle: ["completed", "failed", "cancelled"] },
- input: "complete",
- guards: ["task-is-terminal"],
- expected: {
- outcome: "rejected",
- postState: { lifecycle: ["completed", "failed", "cancelled"] },
- events: { suppressed: ["task-ready-notification"] },
- sideEffects: { suppressed: ["task-view-append", "parent-wake"] },
- },
- }),
- "task.executor.settle.accepted-terminal": transition({
- preState: { lifecycle: ["completed", "failed", "cancelled"], executor: "parked" },
- input: "settle-executor",
- guards: ["task-is-terminal", "executor-is-not-terminal"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: ["completed", "failed", "cancelled"], executor: "terminal" },
- events: {},
- sideEffects: { executed: ["task-view-append"] },
- },
- }),
- "task.executor.settle.rejected-nonterminal": transition({
- preState: { lifecycle: ["working", "input_required"] },
- input: "settle-executor",
- guards: ["task-is-nonterminal"],
- expected: {
- outcome: "rejected",
- postState: { lifecycle: ["working", "input_required"] },
- events: {},
- sideEffects: { suppressed: ["task-view-append"] },
- },
- }),
- "task.input.require.accepted-valid-batch": transition({
- preState: { lifecycle: ["working", "input_required"] },
- input: "require-input",
- guards: ["batch-is-nonempty", "request-ids-are-unique"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "input_required", outstandingInput: "batch" },
- events: { emitted: ["input-requested", "task-ready-notification"] },
- sideEffects: { executed: ["task-view-append", "parent-wake"] },
- },
- }),
- "task.input.require.rejected-invalid-batch": transition({
- preState: { lifecycle: ["working", "input_required"] },
- input: "require-input",
- guards: ["batch-is-empty-or-request-ids-are-invalid"],
- expected: {
- outcome: "rejected",
- postState: { lifecycle: ["working", "input_required"] },
- events: { suppressed: ["input-requested", "task-ready-notification"] },
- sideEffects: { suppressed: ["task-view-append", "parent-wake"] },
- },
- }),
- "task.input.answer.accepted-partial": transition({
- preState: { lifecycle: "input_required", outstandingInput: "batch" },
- input: "answer-input",
- guards: ["some-request-ids-match", "some-requests-remain"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "input_required", outstandingInput: "partial-batch" },
- events: {},
- sideEffects: { executed: ["child-delivery", "task-view-append"] },
- },
- }),
- "task.input.answer.accepted-complete": transition({
- preState: { lifecycle: "input_required", outstandingInput: "batch" },
- input: "answer-input",
- guards: ["all-outstanding-request-ids-match"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "working", outstandingInput: "none" },
- events: {},
- sideEffects: {
- executed: ["child-delivery", "task-view-append"],
- suppressed: ["parent-model-step"],
- },
- },
- }),
- "task.input.answer.noop-stale": transition({
- preState: { lifecycle: "input_required", outstandingInput: "batch" },
- input: "answer-input",
- guards: ["no-request-id-matches"],
- expected: {
- outcome: "noop",
- postState: { lifecycle: "input_required", outstandingInput: "batch" },
- events: {},
- sideEffects: { suppressed: ["child-delivery", "task-view-append", "parent-model-step"] },
- },
- }),
- "task.input.route.observed-stale-unrouted": transition({
- preState: { lifecycle: "input_required", outstandingInput: "batch" },
- input: "answer-input",
- guards: ["request-route-is-no-longer-registered"],
- expected: {
- outcome: "observed",
- postState: { lifecycle: "input_required", outstandingInput: "batch" },
- events: {},
- sideEffects: {
- executed: ["parent-model-step"],
- suppressed: ["child-delivery", "task-view-append"],
- },
- },
- }),
- "task.executor.start-turn.accepted-unbound": transition({
- preState: { lifecycle: ["working", "input_required"], executor: "unbound" },
- input: "start-turn",
- guards: ["task-id-matches", "child-session-is-unbound"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: ["working", "input_required"], executor: "active" },
- events: {},
- sideEffects: { executed: ["task-view-append"] },
- },
- }),
- "task.executor.start-turn.noop-same-turn": transition({
- preState: { lifecycle: ["working", "input_required"], executor: "active" },
- input: "start-turn",
- guards: ["task-id-matches", "child-session-and-turn-match"],
- expected: {
- outcome: "noop",
- postState: { lifecycle: ["working", "input_required"], executor: "active" },
- events: {},
- sideEffects: { suppressed: ["task-view-append"] },
- },
- }),
- "task.executor.start-turn.rejected-session-mismatch": transition({
- preState: { lifecycle: ["working", "input_required"], executor: "active" },
- input: "start-turn",
- guards: ["task-id-matches", "child-session-differs"],
- expected: {
- outcome: "rejected",
- postState: { lifecycle: ["working", "input_required"], executor: "active" },
- events: {},
- sideEffects: { suppressed: ["task-view-append"] },
- },
- }),
- "task.dispatch.start.accepted-acknowledged": transition({
- preState: { lifecycle: "absent", dispatch: "absent", ownership: "unowned" },
- input: "dispatch-start",
- guards: ["child-acknowledges-private-address"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "working", dispatch: "acknowledged", ownership: "owned" },
- events: { emitted: ["background-receipt"] },
- sideEffects: { executed: ["child-dispatch", "task-index-write"] },
- },
- }),
- "task.dispatch.start.rejected-unreachable": transition({
- preState: { lifecycle: "absent", dispatch: "absent", ownership: "unowned" },
- input: "dispatch-start",
- guards: ["child-start-is-unreachable"],
- expected: {
- 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({
- preState: { dispatch: "absent" },
- input: "dispatch-batch",
- guards: ["one-member-is-unreachable", "other-members-are-reachable"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: ["working", "failed"], dispatch: "acknowledged", ownership: "owned" },
- events: { emitted: ["background-receipt", "task-failed-notification"] },
- sideEffects: { executed: ["child-dispatch", "task-index-write"] },
- },
- }),
- "task.agent.continue.accepted-terminal-available": transition({
- preState: { lifecycle: ["completed", "failed", "cancelled"], agent: "available" },
- input: "agent-continuation",
- guards: ["source-task-is-terminal", "agent-has-no-nonterminal-task"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "working", agent: "busy", ownership: "owned" },
- events: { emitted: ["background-receipt"] },
- sideEffects: { executed: ["task-index-write", "child-delivery"] },
- },
- }),
- "task.agent.continue.rejected-agent-busy": transition({
- preState: { agent: "busy" },
- input: "agent-continuation",
- guards: ["agent-is-claimed-by-another-call-in-the-same-batch"],
- expected: {
- outcome: "rejected",
- postState: { agent: "busy" },
- events: { suppressed: ["background-receipt"] },
- sideEffects: { suppressed: ["task-index-write", "child-delivery"] },
- },
- }),
- "task.agent.steer.accepted-busy": transition({
- preState: { lifecycle: "working", agent: "busy", ownership: "owned" },
- input: "agent-steering",
- guards: ["parent-owns-admitted-task", "agent-has-a-confirmed-address"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "cancelled", agent: "busy", ownership: "owned" },
- events: { emitted: ["background-receipt", "task-ready-notification"] },
- sideEffects: { executed: ["child-abort", "task-index-write", "child-delivery"] },
- },
- }),
- "task.update.emitted-working": transition({
- preState: { lifecycle: "working" },
- input: "task-update",
- guards: ["child-is-owned-by-task"],
- expected: {
- outcome: "emitted",
- postState: { lifecycle: "working" },
- events: { emitted: ["task-update-notification"] },
- sideEffects: { executed: ["parent-wake"], suppressed: ["task-view-append"] },
- },
- }),
- "task.authorization.callback.accepted-current-attempt": transition({
- preState: { lifecycle: "input_required", outstandingInput: "authorization" },
- input: "authorization-callback",
- guards: ["callback-matches-current-attempt"],
- expected: {
- outcome: "accepted",
- postState: { lifecycle: "working", outstandingInput: "none" },
- events: { emitted: ["authorization-completed"] },
- sideEffects: { executed: ["authorization-request", "task-view-append"] },
- },
- }),
- "task.control.peek.observed-owned": transition({
- preState: { ownership: "owned" },
- input: "task-peek",
- guards: ["parent-owns-every-requested-task"],
- expected: {
- outcome: "observed",
- postState: { ownership: "owned" },
- events: {},
- sideEffects: { executed: ["task-view-read"], suppressed: ["task-view-append"] },
- },
- }),
- "task.parent.wake.emitted-ready": transition({
- preState: { lifecycle: ["input_required", "completed", "failed", "cancelled"] },
- input: "task-notification",
- guards: [
- "task-entered-a-ready-status",
- "status-is-not-completed-or-all-same-createdByTurnId-siblings-are-terminal",
- ],
- expected: {
- outcome: "emitted",
- postState: { lifecycle: ["input_required", "completed", "failed", "cancelled"] },
- events: { emitted: ["task-ready-notification"] },
- sideEffects: { executed: ["parent-wake"] },
- },
- }),
- "task.parent.wake.noop-pending-cohort": transition({
- preState: { lifecycle: "completed", cohort: "pending" },
- input: "task-notification",
- guards: [
- "a-same-createdByTurnId-sibling-is-nonterminal",
- "unrelated-user-turns-and-cohorts-do-not-release-held-successes",
- "input-authorization-failure-and-cancellation-bypass-the-hold",
- ],
- expected: {
- outcome: "noop",
- postState: { lifecycle: "completed", cohort: "pending" },
- events: {},
- sideEffects: {
- executed: ["completion-hold"],
- suppressed: ["parent-wake", "parent-model-step"],
- },
- },
- }),
- "task.parent-interaction.send.accepted-live-children": transition({
- preState: { agent: "busy", parent: "active" },
- input: "parent-message",
- guards: ["background-children-remain-nonterminal"],
- expected: {
- outcome: "accepted",
- postState: { agent: "busy", parent: "active" },
- events: {},
- sideEffects: { executed: ["parent-model-step"] },
- },
- }),
- "task.join.evaluate.observed-partial": transition({
- preState: { lifecycle: ["completed", "input_required"], cohort: "pending" },
- input: "parent-message",
- guards: ["one-child-has-completed", "a-sibling-still-awaits-input", "independent-user-message"],
- expected: {
- outcome: "observed",
- postState: { lifecycle: ["completed", "input_required"], cohort: "pending" },
- events: {},
- sideEffects: { executed: ["parent-model-step"] },
- },
- }),
- "task.join.evaluate.observed-all-terminal": transition({
- preState: { lifecycle: "completed", cohort: "terminal" },
- input: "task-notification",
- guards: ["all-joined-tasks-are-terminal", "every-result-is-in-the-cohort-notification"],
- expected: {
- outcome: "observed",
- postState: { lifecycle: "completed", cohort: "terminal" },
- events: {},
- sideEffects: { executed: ["parent-model-step"] },
- },
- }),
-} as const satisfies Record<string, TransitionSpec>;
-
-export type TaskTransitionAnchor = keyof typeof TASK_TRANSITIONS;
-
-export interface TaskTransitionDeclaration {
- readonly primary: TaskTransitionAnchor;
- readonly setup?: readonly TaskTransitionAnchor[];
- readonly dimensions: {
- readonly transport: "local" | "remote" | "mixed" | "not-applicable";
- readonly parentPhase?: "active" | "parked" | "finalizing";
- };
-}
-
-type TaskEvalInput = Omit<EveEvalInput, "metadata"> & {
- readonly metadata?: Readonly<Record<string, unknown>>;
- readonly transition: TaskTransitionDeclaration;
-};
-
-/** Defines one task eval and expands its transition into executable-run metadata. */
-export function defineTaskEval(input: TaskEvalInput): EveEvalDefinition {
- const { metadata, transition: declaration, ...evalInput } = input;
- const spec = TASK_TRANSITIONS[declaration.primary];
- return defineEval({
- ...evalInput,
- metadata: {
- ...metadata,
- transition: {
- anchor: declaration.primary,
- dimensions: declaration.dimensions,
- expected: spec.expected,
- guards: spec.guards,
- input: spec.input,
- preState: spec.preState,
- setup: declaration.setup ?? [],
- },
- },
- });
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.ts
deleted file mode 100644
index 5956f5ae8..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { satisfies } from "eve/evals/expect";
-
-import {
- requireBackgroundTaskId,
- requireTaskView,
- sendAndFollowQueuedTurn,
- waitForCompletedTask,
- waitForTaskInput,
-} from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-/** A reused child must route every new-turn event through the new owning task. */
-export default defineTaskEval({
- description: "An agentId continuation rebinds a reused child's HITL events to a new task.",
- transition: {
- primary: "task.agent.continue.accepted-terminal-available",
- setup: ["task.input.answer.accepted-complete"],
- dimensions: { transport: "local" },
- },
- async test(t) {
- t.log("starting first task");
- const setup = await t.send("TASK-CONTINUATION-HITL-SETUP", { taskDeliveryPolicy: "cohort" });
- setup.expectOk();
- const firstTaskId = requireBackgroundTaskId(setup);
-
- const first = await waitForTaskInput(t, setup.session, "first_gate");
- t.log("answering first task gate one");
- const firstAnswered = await first.session.respond([
- {
- optionId: "approve",
- requestId: first.request.requestId,
- },
- ]);
- firstAnswered.notEvent("step.started");
- const second = await waitForTaskInput(t, first.session, "second_gate");
- t.log("answering first task gate two");
- await second.session.respond([{ optionId: "approve", requestId: second.request.requestId }]);
- const firstTerminal = await waitForCompletedTask(
- t,
- second.session,
- "TASK-HITL-VERIFY",
- firstTaskId,
- );
- const firstView = requireTaskView(
- firstTerminal.requireToolCall("task_cancel").output,
- firstTaskId,
- );
- const firstAgentId = requireAgentId(firstView);
- t.log("first task completed; sending continuation");
-
- const continued = await sendAndFollowQueuedTurn(
- t,
- `TASK-CONTINUATION-HITL-SEND ${firstAgentId}`,
- second.session,
- );
- continued.turn.expectOk();
- const secondTaskId = requireBackgroundTaskId(continued.turn);
- await t.require(
- secondTaskId,
- satisfies((taskId) => taskId !== firstTaskId, "continuation creates a new task identity"),
- );
- t.log("continuation admitted; waiting for rebound HITL");
- const continuedThird = await waitForTaskInput(t, continued.session, "third_gate");
- const continuedThirdAnswer = await continuedThird.session.respond([
- {
- optionId: "approve",
- requestId: continuedThird.request.requestId,
- },
- ]);
- continuedThirdAnswer.notEvent("step.started");
- const continuedFourth = await waitForTaskInput(t, continuedThird.session, "fourth_gate");
- await continuedFourth.session.respond([
- {
- optionId: "approve",
- requestId: continuedFourth.request.requestId,
- },
- ]);
- const secondTerminal = await waitForCompletedTask(
- t,
- continuedFourth.session,
- "TASK-HITL-VERIFY",
- secondTaskId,
- );
- const secondView = requireTaskView(
- secondTerminal.requireToolCall("task_cancel").output,
- secondTaskId,
- );
- await t.require(
- secondView,
- satisfies(
- (view: Record<string, unknown>) => requireAgentId(view) === firstAgentId,
- "the new task retains the reused child's agent identity",
- ),
- );
- t.noFailedActions();
- },
-});
-
-function requireAgentId(view: Record<string, unknown>): string {
- const metadata = Reflect.get(view, "metadata");
- const agentId =
- metadata !== null && typeof metadata === "object"
- ? Reflect.get(metadata, "agentId")
- : undefined;
- if (typeof agentId !== "string") throw new Error("Task view has no agent id.");
- return agentId;
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts
deleted file mode 100644
index ff5af9f15..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import { equals, satisfies } from "eve/evals/expect";
-
-import { defineTaskEval } from "./task-transition.js";
-import {
- requireBackgroundTaskId,
- requireTaskView,
- parseToolErrorOutput,
- sendAndFollowQueuedTurn,
- waitForCompletedTask,
- waitForTaskInput,
-} from "./shared.js";
-
-/** Same-batch calls compete for one claim; a later message steers the admitted task. */
-export default defineTaskEval({
- description:
- "One same-batch continuation is admitted; later steering preserves its task and pending approval.",
- transition: {
- primary: "task.agent.steer.accepted-busy",
- setup: [
- "task.dispatch.start.accepted-acknowledged",
- "task.lifecycle.complete.accepted-nonterminal",
- "task.agent.continue.accepted-terminal-available",
- "task.agent.continue.rejected-agent-busy",
- ],
- dimensions: { transport: "local", parentPhase: "active" },
- },
- async test(t) {
- const setup = await t.send("CHILD-TASK-EXCLUSIVITY-SETUP", { taskDeliveryPolicy: "cohort" });
- setup.expectOk();
- setup.messageIncludes("CHILD-TASK-EXCLUSIVITY-READY");
- const initialTaskId = requireBackgroundTaskId(setup);
- const initial = await waitForCompletedTask(
- t,
- setup.session,
- "CHILD-TASK-EXCLUSIVITY-VERIFY",
- initialTaskId,
- );
- const agentId = agentIdFromTaskView(
- initial.requireToolCall("task_cancel").output,
- initialTaskId,
- );
-
- const race = await sendAndFollowQueuedTurn(t, "CHILD-TASK-EXCLUSIVITY-RACE", initial.session, {
- allowFailedActions: true,
- });
- const raced = race.turn;
- raced.expectOk();
- raced.messageIncludes("CHILD-TASK-EXCLUSIVITY-RACE-DONE");
-
- const admittedTaskId = requireBackgroundTaskId(raced);
- raced.event("action.result", {
- count: 2,
- data: { result: { kind: "tool-result", toolName: "busy-worker" } },
- });
- raced.calledSubagent("busy-worker", {
- count: 1,
- status: "working",
- });
- raced.calledTool("busy-worker", {
- count: 1,
- output: (output) => isBusyRejection(output, admittedTaskId),
- status: "failed",
- });
-
- const held = await waitForTaskInput(t, race.session, "hold");
- const later = await sendAndFollowQueuedTurn(
- t,
- `CHILD-TASK-EXCLUSIVITY-LATER ${agentId}`,
- held.session,
- );
- later.turn.expectOk();
- later.turn.calledSubagent("busy-worker", { count: 1, status: "working" });
- const steeredTaskId = requireBackgroundTaskId(later.turn);
- await t.require(steeredTaskId, equals(admittedTaskId));
- // Steering retains the existing request; it does not publish a replacement approval.
- const approved = await later.session.respond([
- { requestId: held.request.requestId, optionId: "approve" },
- ]);
- approved.expectOk();
- const completed = await waitForCompletedTask(
- t,
- later.session,
- "CHILD-TASK-EXCLUSIVITY-VERIFY",
- steeredTaskId,
- );
- const output = completed.requireToolCall("task_cancel").output;
- await t.require(
- agentIdFromTaskView(output, steeredTaskId),
- satisfies((id) => id === agentId, "steering retains the same agent identity"),
- );
- const view = requireTaskView(output, steeredTaskId);
- await t.require(
- view.lastOutput,
- satisfies(
- (value) =>
- value !== null &&
- typeof value === "object" &&
- Reflect.get(value, "data") === "BUSY-WORKER:Return BUSY-WORKER-LATER.",
- "the original task completes with the steering message's result",
- ),
- );
- },
-});
-
-function agentIdFromTaskView(output: unknown, taskId: string): string {
- if (output === null || typeof output !== "object") throw new Error("No task view output.");
- const tasks = Reflect.get(output, "tasks");
- if (!Array.isArray(tasks)) throw new Error("No task views.");
- const task = tasks.find(
- (value) =>
- value !== null && typeof value === "object" && Reflect.get(value, "taskId") === taskId,
- );
- const metadata = task !== null && typeof task === "object" ? Reflect.get(task, "metadata") : null;
- const agentId =
- metadata !== null && typeof metadata === "object" ? Reflect.get(metadata, "agentId") : null;
- if (typeof agentId !== "string") throw new Error("Task view has no agent id.");
- return agentId;
-}
-
-function isBusyRejection(output: unknown, activeTaskId?: string): boolean {
- output = parseToolErrorOutput(output);
- if (output === null || typeof output !== "object") return false;
- const message = Reflect.get(output, "message");
- return (
- Reflect.get(output, "code") === "AGENT_BUSY" &&
- typeof message === "string" &&
- !Object.hasOwn(output, "taskId") &&
- (activeTaskId === undefined || message.includes(activeTaskId))
- );
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.authorization.callback.accepted-current-attempt.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.authorization.callback.accepted-current-attempt.eval.ts
deleted file mode 100644
index 7536f5d45..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.authorization.callback.accepted-current-attempt.eval.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import type { EveEvalContext, EveEvalTurn } from "eve/evals";
-import { equals, satisfies } from "eve/evals/expect";
-
-import {
- requireBackgroundTaskId,
- requireSessionStreamIndex,
- requireTaskView,
- type TaskEvalSessionDriver,
- waitForCompletedTask,
-} from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-const AUTHORIZATION_CODE = "c7-deterministic-code";
-const AUTHORIZATION_NAME = "c7-task-authorization";
-
-type AuthorizationEvent = Extract<
- EveEvalTurn["events"][number],
- { readonly type: "authorization.completed" | "authorization.required" }
->;
-
-/** A task-owned interactive authorization keeps its distinct lifecycle and task blocker. */
-export default defineTaskEval({
- description:
- "A background child surfaces interactive authorization, resumes through its webhook, and completes without masquerading as ordinary input.",
- transition: {
- primary: "task.authorization.callback.accepted-current-attempt",
- dimensions: { transport: "local" },
- },
- async test(t) {
- const started = await t.send("TASK-C7-AUTHORIZATION", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- started.messageIncludes("TASK-C7-STARTED");
- started.event("action.result", {
- count: 1,
- data: {
- result: { kind: "tool-result", output: { status: "working" }, toolName: "approval-worker" },
- },
- });
- const taskId = requireBackgroundTaskId(started);
-
- const required = await waitForAuthorizationEvent(
- t,
- started.session,
- started,
- "authorization.required",
- );
- required.turn.event("authorization.required", {
- count: 1,
- data: { authorization: { userCode: AUTHORIZATION_CODE }, name: AUTHORIZATION_NAME },
- });
- required.turn.notEvent("input.requested");
-
- const webhookUrl = required.event.data.webhookUrl;
- if (webhookUrl === undefined) throw new Error("C7 authorization.required had no webhook URL.");
- const callback = new URL(webhookUrl);
- callback.searchParams.set("code", AUTHORIZATION_CODE);
- const callbackResponse = await fetch(callback, {
- method: "GET",
- });
- await t.require(callbackResponse.status, equals(200));
-
- const completed = await waitForAuthorizationEvent(
- t,
- required.session,
- undefined,
- "authorization.completed",
- );
- completed.turn.event("authorization.completed", {
- count: 1,
- data: { name: AUTHORIZATION_NAME, outcome: "authorized" },
- });
-
- const terminal = await waitForCompletedTask(
- t,
- completed.session,
- "TASK-C7-AUTHORIZATION-VERIFY",
- taskId,
- );
- const terminalView = requireTaskView(terminal.requireToolCall("task_cancel").output, taskId);
- await t.require(
- terminalView,
- satisfies(
- (view: Record<string, unknown>) =>
- Reflect.get(view, "status") === "completed" &&
- Reflect.get(Reflect.get(view, "lastOutput") ?? {}, "type") === "result" &&
- Reflect.get(Reflect.get(view, "lastOutput") ?? {}, "data") ===
- "C7-AUTHORIZATION-COMPLETE",
- "authorized child reaches its deterministic terminal output",
- ),
- );
- t.event("authorization.required", {
- count: 1,
- data: { authorization: { userCode: AUTHORIZATION_CODE }, name: AUTHORIZATION_NAME },
- });
- t.event("authorization.completed", {
- count: 1,
- data: { name: AUTHORIZATION_NAME, outcome: "authorized" },
- });
- t.eventOrder([{ type: "authorization.required" }, { type: "authorization.completed" }]);
- t.notEvent("input.requested");
- t.noFailedActions();
- },
-});
-
-async function waitForAuthorizationEvent<TType extends AuthorizationEvent["type"]>(
- t: EveEvalContext,
- initialSession: TaskEvalSessionDriver,
- initialTurn: EveEvalTurn | undefined,
- type: TType,
-): Promise<{
- readonly event: Extract<AuthorizationEvent, { readonly type: TType }>;
- readonly session: TaskEvalSessionDriver;
- readonly turn: EveEvalTurn;
-}> {
- let session = initialSession;
- let turn = initialTurn;
- for (let attempt = 0; attempt < 10; attempt += 1) {
- const event = turn?.events.find(
- (candidate): candidate is Extract<AuthorizationEvent, { readonly type: TType }> =>
- candidate.type === type,
- );
- if (event !== undefined) return { event, session, turn: turn! };
-
- const sessionId = session.sessionId;
- if (sessionId === undefined) throw new Error("Authorization event wait has no session id.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Authorization event wait"),
- });
- turn = await live.result();
- session = live.session;
- }
- throw new Error(`Task did not surface ${type} after ten turns.`);
-}
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
deleted file mode 100644
index edadd7cd3..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
-import { type EveEvalTurn } from "eve/evals";
-import { satisfies } from "eve/evals/expect";
-
-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 from completing. */
-export default defineTaskEval({
- description:
- "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" },
- },
- async test(t) {
- const started = await t.send("TASK-D6-PARTIAL-FANOUT-FAILURE", {
- taskDeliveryPolicy: "cohort",
- });
- started.expectOk();
- started.messageIncludes("TASK-D6-PARTIAL-FANOUT-STARTED");
- started.eventsSatisfy("dispatch results cover every sibling", (events) => {
- const callIds = events.flatMap((event) =>
- event.type === "action.result" &&
- event.data.result.kind === "tool-result" &&
- (event.data.result.toolName === "busy-worker" ||
- event.data.result.toolName === "unstartable-worker")
- ? [event.data.result.callId]
- : [],
- );
- return (
- callIds.length === 3 &&
- new Set(callIds).size === 3 &&
- [FIRST_CALL_ID, FAILED_CALL_ID, THIRD_CALL_ID].every((callId) => callIds.includes(callId))
- );
- });
-
- const receipts = backgroundReceipts(started);
- await t.require(
- receipts,
- satisfies(
- (values: readonly BackgroundReceipt[]) =>
- 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 === 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.event("action.result", {
- count: 2,
- data: {
- result: { kind: "tool-result", output: { status: "working" }, toolName: "busy-worker" },
- },
- });
-
- const firstCompleted = await waitForCompletedTask(
- t,
- started.session,
- "TASK-D6-PARTIAL-FANOUT-VERIFY",
- firstTaskId,
- );
- assertCompletedBusyWorker(firstCompleted, firstTaskId, "TASK-D6-FIRST-SUCCESS");
- const thirdCompleted = await waitForCompletedTask(
- t,
- started.session,
- "TASK-D6-PARTIAL-FANOUT-VERIFY",
- thirdTaskId,
- );
- assertCompletedBusyWorker(thirdCompleted, thirdTaskId, "TASK-D6-THIRD-SUCCESS");
- const failed = await waitForTaskStatus(
- t,
- started.session,
- "TASK-D6-PARTIAL-FANOUT-UNKNOWN",
- failedTaskId,
- "failed",
- );
- assertFailedUnstartableWorker(failed, failedTaskId);
- },
-});
-
-interface BackgroundReceipt {
- readonly callId: string;
- readonly taskId: string;
-}
-
-function backgroundReceipts(turn: EveEvalTurn): readonly BackgroundReceipt[] {
- return taskReceipts(turn.events);
-}
-
-function requireReceiptTaskId(receipts: readonly BackgroundReceipt[], callId: string): string {
- const matching = receipts.filter((receipt) => receipt.callId === callId);
- if (matching.length !== 1) throw new Error(`Expected one background receipt for ${callId}.`);
- return matching[0]!.taskId;
-}
-
-function assertCompletedBusyWorker(turn: EveEvalTurn, taskId: string, marker: string): void {
- turn.expectOk();
- turn.messageIncludes("TASK-D6-STATUS");
- 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") !== "completed" ||
- metadata === null ||
- typeof metadata !== "object" ||
- Reflect.get(metadata, "name") !== "busy-worker" ||
- lastOutput === null ||
- typeof lastOutput !== "object" ||
- Reflect.get(lastOutput, "type") !== "result" ||
- !String(Reflect.get(lastOutput, "data")).includes(marker)
- ) {
- 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.accepted-acknowledged.creator-context.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.accepted-acknowledged.creator-context.eval.ts
deleted file mode 100644
index aa2c4e70e..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.accepted-acknowledged.creator-context.eval.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-import { e2eModel } from "@eve-e2e/config";
-import type { EveEvalContext } from "eve/evals";
-import { equals } from "eve/evals/expect";
-
-import type { LifecycleControlEvent } from "../agent/lib/lifecycle-control.js";
-import { requireSessionStreamIndex, type TaskEvalSessionDriver } from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-const SESSION_INITIATOR_AUTHORIZATION = "Bearer e2e-task-session-initiator";
-const LATER_PARENT_CALLER_AUTHORIZATION = "Bearer e2e-task-later-parent-caller";
-const ANONYMOUS_TASK_CREATOR_HEADER = "x-eve-fixture-anonymous-task-creator";
-
-export default defineTaskEval({
- description:
- "A schedule-shaped background task with no current principal keeps the session initiator after a later turn changes the current caller.",
- tags: ["real-model"],
- transition: {
- primary: "task.dispatch.start.accepted-acknowledged",
- dimensions: { transport: "local" },
- },
- async test(t) {
- const modelId = e2eModel();
- if (typeof modelId !== "string")
- throw new Error("Auth snapshot coverage requires a real model.");
-
- // One authenticated caller creates the session and remains its initiator.
- const firstTurn = await t.send("TASK-AUTH-SNAPSHOT-ROOT", {
- taskDeliveryPolicy: "cohort",
- headers: { authorization: SESSION_INITIATOR_AUTHORIZATION },
- });
- const session = firstTurn.session;
- firstTurn.expectOk();
- firstTurn.messageIncludes("TASK-AUTH-SNAPSHOT-ROOT-ACK");
- firstTurn.calledTool("snapshot_whoami", { count: 1, status: "completed" });
- // The first authenticated turn establishes the only session initiator.
- await t.require(
- firstTurn.requireToolCall("snapshot_whoami").output,
- equals({ current: "session-initiator", initiator: "session-initiator" }),
- );
-
- // A route-authenticated, schedule-shaped turn has no current session principal.
- const key = crypto.randomUUID();
- const started = await session.send(`TASK-AUTH-SNAPSHOT ${key}`, {
- taskDeliveryPolicy: "cohort",
- headers: { [ANONYMOUS_TASK_CREATOR_HEADER]: "1" },
- });
- started.expectOk();
- started.messageIncludes("TASK-AUTH-SNAPSHOT-STARTED");
- started.calledTool("snapshot_whoami", { count: 1, status: "completed" });
- // The schedule-shaped turn has no current principal but retains the session initiator.
- await t.require(
- started.requireToolCall("snapshot_whoami").output,
- equals({ current: null, initiator: "session-initiator" }),
- );
- const sessionId = started.sessionId;
- if (sessionId === undefined) throw new Error("The task has no parent session.");
-
- const gateToken = await waitForGate(t, sessionId, key);
-
- // Another authenticated caller takes the last parent turn before nested dispatch.
- const lastParentTurn = await session.send("TASK-AUTH-SNAPSHOT-LATER", {
- taskDeliveryPolicy: "cohort",
- headers: { authorization: LATER_PARENT_CALLER_AUTHORIZATION },
- });
- lastParentTurn.expectOk();
- lastParentTurn.messageIncludes("TASK-AUTH-SNAPSHOT-LATER-ACK");
- lastParentTurn.calledTool("snapshot_whoami", { count: 1, status: "completed" });
- // The later parent turn changes only the current principal.
- await t.require(
- lastParentTurn.requireToolCall("snapshot_whoami").output,
- equals({ current: "later-parent-caller", initiator: "session-initiator" }),
- );
-
- await releaseGate(t, sessionId, key, gateToken);
- const childSessionId = await waitForSubagent(t, lastParentTurn.session);
- const child = await t.target.watchTurn(childSessionId).result();
- child.expectOk();
- child.noFailedActions();
- child.event("step.started", { data: { modelId } });
- child.calledTool("snapshot_whoami", { count: 1, status: "completed" });
- // Nested dispatch uses the task creator's null current principal, not the later caller.
- await t.require(
- child.requireToolCall("snapshot_whoami").output,
- equals({ current: null, initiator: "session-initiator" }),
- );
- },
-});
-
-async function waitForGate(t: EveEvalContext, sessionId: string, key: string): Promise<string> {
- for (let index = 0; index < 2; index += 1) {
- const response = await t.target.fetch(
- `/eve/v1/task-lifecycle/${encodeURIComponent(sessionId)}/next`,
- {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ key, index }),
- signal: t.signal,
- },
- );
- await t.require(response.status, equals(200));
- const event = (await response.json()) as LifecycleControlEvent;
- if (event.kind === "gate" && event.token !== undefined) return event.token;
- }
- throw new Error("The background task did not pause before starting its subagent.");
-}
-
-async function releaseGate(
- t: EveEvalContext,
- sessionId: string,
- key: string,
- token: string,
-): Promise<void> {
- const response = await t.target.fetch(
- `/eve/v1/task-lifecycle/${encodeURIComponent(sessionId)}/release`,
- {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ key, token }),
- signal: t.signal,
- },
- );
- await t.require(response.status, equals(200));
- await t.require(await response.json(), equals({ released: true }));
-}
-
-async function waitForSubagent(
- t: EveEvalContext,
- initialSession: TaskEvalSessionDriver,
-): Promise<string> {
- let session = initialSession;
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const sessionId = session.sessionId;
- if (sessionId === undefined) throw new Error("The task has no parent session.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Subagent wait"),
- });
- const turn = await live.result();
- turn.expectOk();
- session = live.session;
- const called = turn.events.find(
- (event) => event.type === "subagent.called" && event.data.name === "auth-snapshot-worker",
- );
- if (called?.type === "subagent.called") return called.data.childSessionId;
- }
- throw new Error("The background task did not start its subagent.");
-}
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
deleted file mode 100644
index 9734dfae6..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { defineTaskEval } from "./task-transition.js";
-import { requireBackgroundTaskId, requireTaskView, waitForTaskStatus } from "./shared.js";
-
-const CALL_ID = "task-a3-unstartable-worker";
-
-/** A failed remote start is recorded as the admitted background task's terminal state. */
-export default defineTaskEval({
- description:
- "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" },
- },
- async test(t) {
- const started = await t.send("TASK-A3-DISPATCH-START-FAILURE", {
- taskDeliveryPolicy: "cohort",
- });
- started.expectOk();
- started.messageIncludes("TASK-A3-PARENT-SURVIVED");
- started.event("action.result", {
- count: 1,
- data: {
- result: {
- kind: "tool-result",
- output: { status: "working" },
- callId: CALL_ID,
- toolName: "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,
- started.session,
- "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 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 (
- lastOutput !== null &&
- typeof lastOutput === "object" &&
- Reflect.get(lastOutput, "type") === "error"
- );
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.local.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.local.eval.ts
deleted file mode 100644
index 73216f676..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.local.eval.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { requireBackgroundTaskId, waitForCompletedTask, waitForTaskInput } from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-/**
- * Task-owned child HITL must surface on the parent session, and answering it
- * must route to the child without running the parent model.
- */
-export default defineTaskEval({
- description:
- "A background child's approval surfaces on the parent and routes back without a parent model step.",
- transition: {
- primary: "task.input.answer.accepted-complete",
- dimensions: { transport: "local" },
- },
- async test(t) {
- const started = await t.send("TASK-HITL-ROUTING", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- started.event("action.result", {
- count: 1,
- data: {
- result: { kind: "tool-result", output: { status: "working" }, toolName: "approval-worker" },
- },
- });
- const taskId = requireBackgroundTaskId(started);
-
- const first = await waitForTaskInput(t, started.session, "first_gate");
- const answered = await first.session.respond([
- {
- optionId: "approve",
- requestId: first.request.requestId,
- },
- ]);
- answered.expectOk();
- answered.notEvent("step.started");
- answered.noFailedActions();
-
- // The next child request proves direct delivery of the first answer.
- const second = await waitForTaskInput(t, first.session, "second_gate");
- const answeredSecond = await second.session.respond([
- {
- optionId: "approve",
- requestId: second.request.requestId,
- },
- ]);
- answeredSecond.expectOk();
-
- // Remaining gates only let the fixture reach a terminal cleanup state.
- const third = await waitForTaskInput(t, second.session, "third_gate");
- const finished = await third.session.respond([
- {
- optionId: "approve",
- requestId: third.request.requestId,
- },
- ]);
- finished.expectOk();
-
- const verified = await waitForCompletedTask(t, third.session, "TASK-HITL-VERIFY", taskId);
- verified.expectOk();
- verified.messageIncludes("TASK-HITL-STATUS");
-
- t.event("input.requested", { data: { requests: [{ action: { toolName: "first_gate" } }] } });
- t.noFailedActions();
- },
-});
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
deleted file mode 100644
index ce98568c1..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.remote.eval.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { satisfies } from "eve/evals/expect";
-
-import {
- requireBackgroundTaskId,
- requireTaskView,
- waitForCompletedTask,
- waitForTaskInput,
- waitForTaskNotification,
-} from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-const REMOTE_PRINCIPAL_MARKER = "C8-REMOTE-PRINCIPAL:user:remote-http-child";
-
-/**
- * Also covers the /eve/v1 callback-prefix regression (#3047): vercel.json
- * mounts this fixture at /eve/v1. Both the input request and completion must
- * reach the parent through its generated callback URL. A doubled /eve/v1 prefix
- * prevents these deliveries. The build scenario checks the prefix itself;
- * this eval checks the remote round trip through the public event stream.
- */
-export default defineTaskEval({
- description:
- "A remote child delivers HITL and completion through /eve/v1/callback/* and resumes with its HTTP principal intact.",
- transition: {
- primary: "task.input.answer.accepted-complete",
- dimensions: { transport: "remote" },
- },
- async test(t) {
- const started = await t.send("TASK-C8-REMOTE-HITL", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- started.messageIncludes("TASK-C8-STARTED");
- started.event("action.result", {
- count: 1,
- data: {
- result: {
- kind: "tool-result",
- output: { status: "working" },
- callId: "task-c8-remote-worker",
- toolName: "remote-loopback",
- },
- },
- });
- const taskId = requireBackgroundTaskId(started);
-
- t.event("input.requested", {
- count: 1,
- data: { requests: [{ action: { toolName: "remote_gate" } }] },
- }).label("remote input callback reaches the parent");
- t.log("Waiting for the remote input callback to reach the parent.");
- const gate = await waitForTaskInput(t, started.session, "remote_gate");
- const answered = await gate.session.respond([
- {
- optionId: "approve",
- requestId: gate.request.requestId,
- },
- ]);
- answered.expectOk();
- answered.eventsSatisfy(
- "a following parent model step belongs only to a task-ready notification",
- (events) =>
- !events.some((event) => event.type === "step.started") ||
- events.some(
- (event) =>
- event.type === "message.received" &&
- messageText(event.data.message).includes(`Background task ${taskId}`),
- ),
- );
- answered.noFailedActions();
-
- t.eventsSatisfy("remote completion callback reaches the parent", (events) =>
- events.some(
- (event) =>
- event.type === "message.received" &&
- messageText(event.data.message).includes(`Background task ${taskId}`) &&
- messageText(event.data.message).includes(REMOTE_PRINCIPAL_MARKER),
- ),
- );
- t.log("Waiting for the remote completion callback to reach the parent.");
- const completed = await waitForTaskNotification(t, gate.session, taskId, "completed", [
- answered,
- ]);
- completed.turn.expectOk();
-
- const terminal = await waitForCompletedTask(
- t,
- completed.session,
- "TASK-C8-REMOTE-VERIFY",
- taskId,
- );
- terminal.expectOk();
- const view = requireTaskView(terminal.requireToolCall("task_cancel").output, taskId);
- await t.require(
- view,
- satisfies(
- (task: Record<string, unknown>) =>
- Reflect.get(task, "status") === "completed" &&
- hasRemoteSubagentMetadata(task) &&
- hasRemotePrincipalOutput(task),
- "completed remote task retains subagent identity and the HTTP child principal",
- ),
- );
-
- t.notEvent("authorization.required");
- t.noFailedActions();
- },
-});
-
-function hasRemoteSubagentMetadata(task: Record<string, unknown>): boolean {
- const metadata = Reflect.get(task, "metadata");
- return (
- metadata !== null &&
- typeof metadata === "object" &&
- Reflect.get(metadata, "kind") === "subagent" &&
- Reflect.get(metadata, "mode") === "remote" &&
- Reflect.get(metadata, "name") === "remote-loopback" &&
- typeof Reflect.get(metadata, "agentId") === "string"
- );
-}
-
-function hasRemotePrincipalOutput(task: Record<string, unknown>): boolean {
- const output = Reflect.get(task, "lastOutput");
- return (
- output !== null &&
- typeof output === "object" &&
- Reflect.get(output, "type") === "result" &&
- typeof Reflect.get(output, "data") === "string" &&
- Reflect.get(output, "data").includes(REMOTE_PRINCIPAL_MARKER)
- );
-}
-
-function messageText(message: unknown): string {
- if (typeof message === "string") return message;
- if (!Array.isArray(message)) return "";
- return message
- .flatMap((part) =>
- part !== null &&
- typeof part === "object" &&
- Reflect.get(part, "type") === "text" &&
- typeof Reflect.get(part, "text") === "string"
- ? [Reflect.get(part, "text") as string]
- : [],
- )
- .join("\n");
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.input.route.observed-stale-unrouted.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.input.route.observed-stale-unrouted.eval.ts
deleted file mode 100644
index a0038d43e..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.input.route.observed-stale-unrouted.eval.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import {
- requireBackgroundTaskId,
- sendAndFollowQueuedTurn,
- waitForCompletedTask,
- waitForTaskInput,
-} from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-/**
- * Once Q1's proxy route is retired, replaying its answer becomes new parent
- * input and cannot reach the child or clear Q2 from the task snapshot.
- */
-export default defineTaskEval({
- description:
- "An answer for a retired proxy route becomes parent input without unblocking or erasing the child's newer request.",
- transition: {
- primary: "task.input.route.observed-stale-unrouted",
- dimensions: { transport: "local" },
- },
- async test(t) {
- const started = await t.send("TASK-INPUT-BATCH-ORDERING", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- const taskId = requireBackgroundTaskId(started);
-
- const first = await waitForTaskInput(t, started.session, "first_gate");
- const firstAnswer = await first.session.respond([
- {
- optionId: "approve",
- requestId: first.request.requestId,
- },
- ]);
- firstAnswer.expectOk();
-
- const second = await waitForTaskInput(t, first.session, "second_gate");
- const stale = await second.session.respond([
- {
- optionId: "approve",
- requestId: first.request.requestId,
- },
- ]);
- stale.expectOk();
- stale.event("step.started", { count: 1 });
- stale.noFailedActions();
-
- const afterStale = await sendAndFollowQueuedTurn(
- t,
- `TASK-INPUT-BATCH-VERIFY ${taskId}`,
- second.session,
- );
- afterStale.turn.notCalledTool("task_cancel");
-
- // This exact Q2 response can only resume the child if the stale Q1 answer
- // left Q2 outstanding. Completion below is the externally observable proof.
- const secondAnswer = await afterStale.session.respond([
- {
- optionId: "approve",
- requestId: second.request.requestId,
- },
- ]);
- secondAnswer.expectOk();
-
- const verified = await waitForCompletedTask(
- t,
- afterStale.session,
- "TASK-INPUT-BATCH-VERIFY",
- taskId,
- );
- verified.expectOk();
- verified.messageIncludes("TASK-INPUT-BATCH-STATUS");
- t.noFailedActions();
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-all-terminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-all-terminal.eval.ts
deleted file mode 100644
index 712028f21..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-all-terminal.eval.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
-import { type EveEvalContext, type EveEvalTurn, type InputRequest } from "eve/evals";
-import { satisfies } from "eve/evals/expect";
-
-import { defineTaskEval } from "./task-transition.js";
-import { requireSessionStreamIndex, type TaskEvalSessionDriver } from "./shared.js";
-
-const FAN_IN_SIZE = 2;
-const MAX_WAKE_TURNS = 8;
-const FAN_IN_CALLS = [
- { callId: "task-fan-in-1", marker: "TASK-FAN-IN-1" },
- { callId: "task-fan-in-2", marker: "TASK-FAN-IN-2" },
-] as const;
-
-type FanInMarker = (typeof FAN_IN_CALLS)[number]["marker"];
-
-/** A join completes after result-bearing notifications cover its exact task set. */
-export default defineTaskEval({
- description: "A join observes both exact tasks completed before answering COMPLETE.",
- transition: {
- primary: "task.join.evaluate.observed-all-terminal",
- setup: [
- "task.dispatch.start.accepted-acknowledged",
- "task.input.require.accepted-valid-batch",
- "task.input.answer.accepted-complete",
- "task.lifecycle.complete.accepted-nonterminal",
- "task.parent.wake.emitted-ready",
- ],
- dimensions: { transport: "local", parentPhase: "active" },
- },
- async test(t) {
- const started = await t.send("TASK-FAN-IN", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- started.messageIncludes("TASK-FAN-IN-STARTED");
- started.calledSubagent("fanout-worker", { status: "working", count: FAN_IN_SIZE });
-
- const tasksByMarker = backgroundTasksByMarker(started);
- const taskIds = [...tasksByMarker.values()];
- await t.require(
- taskIds,
- satisfies(
- (ids: readonly string[]) => ids.length === FAN_IN_SIZE && new Set(ids).size === FAN_IN_SIZE,
- `${FAN_IN_SIZE} distinct background task receipts`,
- ),
- );
- const blocked = await waitForReleaseRequests(t, started.session, started);
-
- const released = await blocked.session.respond(
- FAN_IN_CALLS.map(({ marker }) => ({
- optionId: "approve",
- requestId: requireMappedValue(blocked.requestsByMarker, marker, "release request")
- .requestId,
- })),
- );
- released.expectOk();
-
- const complete = await waitForTurnMessage(t, blocked.session, "TASK-FAN-IN-COMPLETE", released);
- complete.notCalledTool("task_peek");
- for (const { marker } of FAN_IN_CALLS) {
- const taskId = requireMappedValue(tasksByMarker, marker, "background task");
- t.event("message.received", {
- count: 1,
- data: {
- message: (message) =>
- typeof message === "string" &&
- message.includes(`Background task ${taskId} (`) &&
- message.includes(" is completed.") &&
- message.includes(`FANOUT-COMPLETE:${marker}`),
- },
- });
- }
- t.notCalledTool("task_peek");
- t.noFailedActions();
- },
-});
-
-interface BlockedFanIn {
- readonly requestsByMarker: ReadonlyMap<FanInMarker, InputRequest>;
- readonly session: TaskEvalSessionDriver;
-}
-
-async function waitForReleaseRequests(
- t: EveEvalContext,
- initialSession: TaskEvalSessionDriver,
- initialTurn: EveEvalTurn,
-): Promise<BlockedFanIn> {
- const requestsByMarker = new Map<FanInMarker, InputRequest>();
- let session = initialSession;
- collectReleaseRequests(initialTurn.inputRequests, requestsByMarker);
- for (
- let attempt = 0;
- attempt < MAX_WAKE_TURNS && requestsByMarker.size < FAN_IN_SIZE;
- attempt += 1
- ) {
- const sessionId = session.sessionId;
- if (sessionId === undefined) throw new Error("Fan-in has no parent session id.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Fan-in release wait"),
- });
- const turn = await live.result();
- collectReleaseRequests(turn.inputRequests, requestsByMarker);
- session = live.session;
- }
- if (requestsByMarker.size !== FAN_IN_SIZE) {
- throw new Error(
- `Expected ${FAN_IN_SIZE} marked release requests; received ${requestsByMarker.size}.`,
- );
- }
- return { requestsByMarker, session };
-}
-
-function collectReleaseRequests(
- inputRequests: readonly InputRequest[],
- requestsByMarker: Map<FanInMarker, InputRequest>,
-): void {
- for (const request of inputRequests) {
- if (request.action.toolName !== "release") continue;
- const marker = request.action.input.marker;
- if (isFanInMarker(marker)) requestsByMarker.set(marker, request);
- }
-}
-
-function isFanInMarker(value: unknown): value is FanInMarker {
- return FAN_IN_CALLS.some(({ marker }) => marker === value);
-}
-
-async function waitForTurnMessage(
- t: EveEvalContext,
- initialSession: TaskEvalSessionDriver,
- token: string,
- initialTurn: EveEvalTurn,
-): Promise<EveEvalTurn> {
- if ((initialTurn.message ?? "").includes(token)) return initialTurn;
- let session = initialSession;
- for (let attempt = 0; attempt < MAX_WAKE_TURNS; attempt += 1) {
- const sessionId = session.sessionId;
- if (sessionId === undefined) throw new Error("Fan-in has no parent session id.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Fan-in message wait"),
- });
- const turn = await live.result();
- session = live.session;
- if ((turn.message ?? "").includes(token)) return turn;
- }
- throw new Error(`No turn carried "${token}" after ${MAX_WAKE_TURNS} turns.`);
-}
-
-function backgroundTasksByMarker(turn: EveEvalTurn): ReadonlyMap<FanInMarker, string> {
- const tasksByMarker = new Map<FanInMarker, string>();
- for (const receipt of taskReceipts(turn.events)) {
- const fanInCall = FAN_IN_CALLS.find(({ callId }) => callId === receipt.callId);
- if (fanInCall !== undefined) tasksByMarker.set(fanInCall.marker, receipt.taskId);
- }
- return tasksByMarker;
-}
-
-function requireMappedValue<T>(
- values: ReadonlyMap<FanInMarker, T>,
- marker: FanInMarker,
- description: string,
-): T {
- const value = values.get(marker);
- if (value === undefined) throw new Error(`Fan-in has no ${description} for ${marker}.`);
- return value;
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-partial.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-partial.eval.ts
deleted file mode 100644
index bf648f7ab..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-partial.eval.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
-import type { EveEvalTurn, InputRequest } from "eve/evals";
-import { equals } from "eve/evals/expect";
-
-import { completedTaskIds, completionMetrics } from "./batching.js";
-import { defineTaskEval } from "./task-transition.js";
-import {
- requireSessionStreamIndex,
- waitForChildResult,
- type TaskEvalSessionDriver,
-} from "./shared.js";
-
-const STATUS_REQUEST = "TASK-FAN-IN-STATUS";
-const MARKERS = ["TASK-FAN-IN-1", "TASK-FAN-IN-2"] as const;
-
-export default defineTaskEval({
- description:
- "An independent user turn observes an incomplete join after one child completes while its sibling still awaits input; only the settled cohort triggers a completion turn.",
- transition: {
- primary: "task.join.evaluate.observed-partial",
- setup: [
- "task.dispatch.start.accepted-acknowledged",
- "task.input.require.accepted-valid-batch",
- "task.input.answer.accepted-complete",
- "task.lifecycle.complete.accepted-nonterminal",
- "task.parent.wake.noop-pending-cohort",
- ],
- dimensions: { transport: "local", parentPhase: "parked" },
- },
- async test(t) {
- const started = (await t.send("TASK-FAN-IN", { taskDeliveryPolicy: "cohort" })).expectOk();
- started.messageIncludes("TASK-FAN-IN-STARTED");
- started.calledSubagent("fanout-worker", { status: "working", count: MARKERS.length });
- let session: TaskEvalSessionDriver = started.session;
- const requests = new Map<string, InputRequest>();
- const setupEvents: EveEvalTurn["events"][number][] = [];
- collectRequests(started);
- for (let attempt = 0; requests.size < 2 && attempt < 8; attempt += 1)
- collectRequests(await nextTurn());
- await t.require([...requests.keys()].sort(), equals([...MARKERS]));
- await t.require(
- new Set([...requests.values()].map((request) => request.requestId)).size,
- equals(2),
- );
-
- const children = MARKERS.map((marker) => {
- const callId = marker.toLowerCase();
- const called = setupEvents.find(
- (event) => event.type === "subagent.called" && event.data.callId === callId,
- );
- const receipt = taskReceipts(started.events).find((receipt) => receipt.callId === callId);
- if (called?.type !== "subagent.called" || receipt === undefined) {
- throw new Error(`No child session and task receipt for ${marker}.`);
- }
- return {
- marker,
- sessionId: called.data.childSessionId,
- taskId: receipt.taskId,
- turnId: called.data.turnId,
- };
- });
- const taskIds = children.map((child) => child.taskId);
- await t.require(
- {
- tasks: new Set(taskIds).size,
- sessions: new Set(children.map((child) => child.sessionId)).size,
- creatingTurns: new Set(children.map((child) => child.turnId)).size,
- },
- equals({ tasks: 2, sessions: 2, creatingTurns: 1 }),
- );
-
- await release("TASK-FAN-IN-2");
- await waitForChildResult(t, children[1]!.sessionId, "FANOUT-COMPLETE:TASK-FAN-IN-2");
- await post({ message: STATUS_REQUEST, turnPolicy: "queue" });
- const partial: EveEvalTurn[] = [];
- let answered = false;
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const turn = await nextTurn();
- partial.push(turn);
- await t.require(completedTaskIds(turn), equals([]));
- if (
- turn.events.some(
- (event) => event.type === "message.received" && event.data.message === STATUS_REQUEST,
- )
- ) {
- await t.require(turn.message, equals("TASK-FAN-IN-WAITING"));
- turn.usedNoTools();
- answered = true;
- break;
- }
- turn.notEvent("step.started");
- }
- await t.require(answered, equals(true));
- await t.require(completionMetrics(partial).modelSteps, equals(1));
- const pendingRequestId = requests.get("TASK-FAN-IN-1")!.requestId;
- t.check(
- partial
- .flatMap((turn) => turn.events)
- .some(
- (event) =>
- event.type === "input.resolved" &&
- event.data.resolutions.some((resolution) => resolution.requestId === pendingRequestId),
- ),
- equals(false),
- ).label("the other sibling still awaits its own approval during the user answer");
-
- await release("TASK-FAN-IN-1");
- await waitForChildResult(t, children[0]!.sessionId, "FANOUT-COMPLETE:TASK-FAN-IN-1");
- let reported = false;
- for (let attempt = 0; attempt < 8; attempt += 1) {
- const turn = await nextTurn();
- if (completedTaskIds(turn).length > 0) {
- await t.require(completedTaskIds(turn).sort(), equals([...taskIds].sort()));
- await t.require(turn.message, equals("TASK-FAN-IN-COMPLETE"));
- turn.event("step.started", { count: 1 });
- reported = true;
- break;
- }
- turn.notEvent("step.started");
- }
- await t.require(reported, equals(true));
- t.calledSubagent("fanout-worker", { status: "completed", count: 2 });
- t.notCalledTool("task_peek");
- t.noFailedActions();
-
- function collectRequests(turn: EveEvalTurn) {
- setupEvents.push(...turn.events);
- for (const request of turn.inputRequests) {
- const marker = request.action.input.marker;
- if (request.action.toolName === "release" && typeof marker === "string")
- requests.set(marker, request);
- }
- }
-
- async function release(marker: string) {
- await post({
- inputResponses: [{ optionId: "approve", requestId: requests.get(marker)!.requestId }],
- });
- }
-
- async function post(body: unknown) {
- const response = await t.target.fetch(
- `/eve/v1/session/${encodeURIComponent(started.sessionId)}`,
- {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- signal: t.signal,
- },
- );
- await response.body?.cancel();
- await t.require(response.status, equals(202));
- }
-
- async function nextTurn() {
- const live = t.target.watchTurn(started.sessionId, {
- startIndex: requireSessionStreamIndex(session, "Partial join"),
- });
- const turn = (await live.result()).expectOk();
- session = live.session;
- return turn;
- }
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.accepted-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.accepted-nonterminal.eval.ts
deleted file mode 100644
index cdf412544..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.accepted-nonterminal.eval.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { satisfies } from "eve/evals/expect";
-
-import {
- requireBackgroundTaskId,
- requireTaskView,
- sendAndFollowQueuedTurn,
- waitForTaskInput,
-} from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-/** Cancellation commits `cancelled` while the child is waiting for input. */
-export default defineTaskEval({
- description: "task_cancel commits a final cancelled state on a nonterminal task.",
- transition: {
- primary: "task.lifecycle.cancel.accepted-nonterminal",
- setup: ["task.dispatch.start.accepted-acknowledged", "task.input.require.accepted-valid-batch"],
- dimensions: { transport: "local", parentPhase: "active" },
- },
- async test(t) {
- const started = await t.send("TASK-CANCEL-SETUP", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- started.messageIncludes("TASK-CANCEL-READY");
- started.event("action.result", {
- count: 1,
- data: {
- result: { kind: "tool-result", output: { status: "working" }, toolName: "fanout-worker" },
- },
- });
- const taskId = requireBackgroundTaskId(started);
-
- const blocked = await waitForTaskInput(t, started.session, "release");
- const cancelled = await sendAndFollowQueuedTurn(t, "TASK-CANCEL-NOW", blocked.session);
- cancelled.turn.expectOk();
- cancelled.turn.messageIncludes("TASK-CANCEL-DONE");
- cancelled.turn.calledTool("task_cancel", { input: { taskIds: [taskId] } });
- const cancelledCall = cancelled.turn.toolCalls.find((call) => call.name === "task_cancel");
- const cancelledView = requireTaskView(cancelledCall?.output, taskId);
- await t.require(
- cancelledView,
- satisfies(
- (view: Record<string, unknown>) => isCancelledTaskView(view, taskId),
- "the first cancellation returns the cancelled task without output or pending input",
- ),
- );
-
- // Cancellation is retained by the parent before the control call returns.
- // The next turn must observe it without retrying a child-state read.
- const { turn: verified } = await sendAndFollowQueuedTurn(
- t,
- `TASK-CANCEL-VERIFY ${taskId}`,
- cancelled.session,
- );
- verified.expectOk();
- verified.messageIncludes("TASK-CANCEL-STATUS");
- await t.require(
- requireTaskView(verified.requireToolCall("task_cancel").output, taskId),
- satisfies(
- (view: Record<string, unknown>) => hasSameCancelledFields(view, cancelledView),
- "no-op cancellation preserves the cancelled task's semantic fields",
- ),
- );
- },
-});
-
-function isCancelledTaskView(view: Record<string, unknown>, taskId: string): boolean {
- return (
- Reflect.get(view, "taskId") === taskId &&
- Reflect.get(view, "status") === "cancelled" &&
- !Object.hasOwn(view, "inputRequests") &&
- !Object.hasOwn(view, "lastOutput")
- );
-}
-
-function hasSameCancelledFields(
- actual: Record<string, unknown>,
- expected: Record<string, unknown>,
-): boolean {
- const actualMetadata = Reflect.get(actual, "metadata");
- const expectedMetadata = Reflect.get(expected, "metadata");
- const expectedTaskId = Reflect.get(expected, "taskId");
- return (
- typeof expectedTaskId === "string" &&
- isCancelledTaskView(actual, expectedTaskId) &&
- actualMetadata !== null &&
- typeof actualMetadata === "object" &&
- expectedMetadata !== null &&
- typeof expectedMetadata === "object" &&
- Reflect.get(actualMetadata, "agentId") === Reflect.get(expectedMetadata, "agentId") &&
- Reflect.get(actualMetadata, "kind") === Reflect.get(expectedMetadata, "kind") &&
- Reflect.get(actualMetadata, "mode") === Reflect.get(expectedMetadata, "mode") &&
- Reflect.get(actualMetadata, "name") === Reflect.get(expectedMetadata, "name")
- );
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.ts
deleted file mode 100644
index 01ac891f3..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { requireBackgroundTaskId, waitForTaskInput, waitForTaskNotification } from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-/** Plain session cancellation remains turn-only while the parent is parked. */
-export default defineTaskEval({
- description: "session.cancel() preserves an admitted background task by default.",
- transition: {
- primary: "task.lifecycle.cancel.default-preserves-nonterminal",
- setup: ["task.dispatch.start.accepted-acknowledged", "task.input.require.accepted-valid-batch"],
- dimensions: { transport: "local", parentPhase: "parked" },
- },
- async test(t) {
- const started = await t.send("TASK-CANCEL-SETUP", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- const taskId = requireBackgroundTaskId(started);
- const blocked = await waitForTaskInput(t, started.session, "release");
- const sessionId = blocked.session.sessionId;
- if (sessionId === undefined) throw new Error("Task parent has no session id.");
-
- const response = await t.target.fetch(`/eve/v1/session/${sessionId}/cancel`, {
- method: "POST",
- });
- if (response.status !== 202) {
- throw new Error(`Plain parked cancellation returned HTTP ${response.status}.`);
- }
-
- const answered = await blocked.session.respond([
- { optionId: "approve", requestId: blocked.request.requestId },
- ]);
- answered.expectOk();
-
- const completed = await waitForTaskNotification(t, blocked.session, taskId, "completed", [
- answered,
- ]);
- const followUp = await completed.session.send("TASK-CANCEL-VERIFY-NOOP", {
- taskDeliveryPolicy: "cohort",
- });
- followUp.expectOk();
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.noop-already-cancelled.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.noop-already-cancelled.eval.ts
deleted file mode 100644
index 944d24d8b..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.noop-already-cancelled.eval.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { satisfies } from "eve/evals/expect";
-
-import {
- requireBackgroundTaskId,
- requireTaskView,
- sendAndFollowQueuedTurn,
- waitForTaskInput,
-} from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-/** Repeating cancellation preserves the existing cancelled task view. */
-export default defineTaskEval({
- description: "task_cancel is a no-op when the task is already cancelled.",
- transition: {
- primary: "task.lifecycle.cancel.noop-already-cancelled",
- setup: [
- "task.dispatch.start.accepted-acknowledged",
- "task.input.require.accepted-valid-batch",
- "task.lifecycle.cancel.accepted-nonterminal",
- ],
- dimensions: { transport: "local", parentPhase: "active" },
- },
- async test(t) {
- const started = await t.send("TASK-CANCEL-SETUP", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- started.messageIncludes("TASK-CANCEL-READY");
- started.event("action.result", {
- count: 1,
- data: {
- result: { kind: "tool-result", output: { status: "working" }, toolName: "fanout-worker" },
- },
- });
- const taskId = requireBackgroundTaskId(started);
-
- const blocked = await waitForTaskInput(t, started.session, "release");
- const cancelled = await sendAndFollowQueuedTurn(t, "TASK-CANCEL-NOW", blocked.session);
- cancelled.turn.expectOk();
- cancelled.turn.calledTool("task_cancel", { input: { taskIds: [taskId] } });
- const cancelledCall = cancelled.turn.toolCalls.find((call) => call.name === "task_cancel");
- const cancelledView = requireTaskView(cancelledCall?.output, taskId);
-
- const repeated = await sendAndFollowQueuedTurn(t, "TASK-CANCEL-NOW", cancelled.session);
- repeated.turn.expectOk();
- repeated.turn.messageIncludes("TASK-CANCEL-DONE");
- repeated.turn.calledTool("task_cancel", { input: { taskIds: [taskId] } });
- const repeatedCall = repeated.turn.toolCalls.find((call) => call.name === "task_cancel");
- await t.require(
- requireTaskView(repeatedCall?.output, taskId),
- satisfies(
- (view: Record<string, unknown>) => hasSameCancelledFields(view, cancelledView),
- "repeated cancellation preserves every model-visible cancelled-task field",
- ),
- );
-
- const { turn: still } = await sendAndFollowQueuedTurn(
- t,
- `TASK-CANCEL-VERIFY ${taskId}`,
- repeated.session,
- );
- still.expectOk();
- await t.require(
- requireTaskView(still.requireToolCall("task_cancel").output, taskId),
- satisfies(
- (view: Record<string, unknown>) => hasSameCancelledFields(view, cancelledView),
- "another no-op cancellation observes the same semantic fields",
- ),
- );
- },
-});
-
-function hasSameCancelledFields(
- actual: Record<string, unknown>,
- expected: Record<string, unknown>,
-): boolean {
- const actualMetadata = Reflect.get(actual, "metadata");
- const expectedMetadata = Reflect.get(expected, "metadata");
- return (
- Reflect.get(actual, "taskId") === Reflect.get(expected, "taskId") &&
- Reflect.get(actual, "status") === "cancelled" &&
- Reflect.get(expected, "status") === "cancelled" &&
- !Object.hasOwn(actual, "inputRequests") &&
- !Object.hasOwn(actual, "lastOutput") &&
- !Object.hasOwn(expected, "inputRequests") &&
- !Object.hasOwn(expected, "lastOutput") &&
- actualMetadata !== null &&
- typeof actualMetadata === "object" &&
- expectedMetadata !== null &&
- typeof expectedMetadata === "object" &&
- Reflect.get(actualMetadata, "agentId") === Reflect.get(expectedMetadata, "agentId") &&
- Reflect.get(actualMetadata, "kind") === Reflect.get(expectedMetadata, "kind") &&
- Reflect.get(actualMetadata, "mode") === Reflect.get(expectedMetadata, "mode") &&
- Reflect.get(actualMetadata, "name") === Reflect.get(expectedMetadata, "name")
- );
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.ts
deleted file mode 100644
index db6a37849..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { satisfies } from "eve/evals/expect";
-
-import {
- requireBackgroundTaskId,
- requireTaskView,
- waitForTaskInput,
- sendAndFollowQueuedTurn,
-} from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-/** Session cancellation can retire indexed tasks while the parent is parked. */
-export default defineTaskEval({
- description: "session.cancel({ tasks: true }) cancels an owned task without ending the session.",
- transition: {
- primary: "task.lifecycle.cancel.owned-session-accepted-nonterminal",
- setup: ["task.dispatch.start.accepted-acknowledged", "task.input.require.accepted-valid-batch"],
- dimensions: { transport: "local", parentPhase: "parked" },
- },
- async test(t) {
- const started = await t.send("TASK-CANCEL-SETUP", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- const taskId = requireBackgroundTaskId(started);
- const blocked = await waitForTaskInput(t, started.session, "release");
- const sessionId = blocked.session.sessionId;
- if (sessionId === undefined) throw new Error("Task parent has no session id.");
-
- const response = await t.target.fetch(`/eve/v1/session/${sessionId}/cancel`, {
- body: JSON.stringify({ tasks: true }),
- headers: { "content-type": "application/json" },
- method: "POST",
- });
- const responseBody: unknown = await response.json();
- await t.require(
- { body: responseBody, status: response.status },
- satisfies(
- (result: { readonly body: unknown; readonly status: number }) =>
- result.status === 202 &&
- result.body !== null &&
- typeof result.body === "object" &&
- Reflect.get(result.body, "status") === "accepted",
- "the parked session accepts owned-task cancellation",
- ),
- );
-
- // Before task_cancel can affect the outcome, prove session cancellation
- // retired the approval route: its old answer must reach the parent model.
- // If the task were still live, this answer would instead release the child.
- const staleAnswer = await blocked.session.respond([
- { optionId: "approve", requestId: blocked.request.requestId },
- ]);
- staleAnswer.expectOk();
- staleAnswer.event("step.started", { count: 1 });
- staleAnswer.notCalledTool("task_cancel");
- staleAnswer.notEvent("subagent.completed");
- const inspected = await sendAndFollowQueuedTurn(
- t,
- `TASK-CANCEL-INSPECT ${taskId}`,
- staleAnswer.session,
- );
- const verified = inspected.turn;
- for (const turn of [staleAnswer, ...inspected.observedTurns]) {
- turn.notEvent("message.received", {
- data: { message: (message) => message.startsWith("Background task ") },
- });
- }
- verified.expectOk();
- verified.messageIncludes("TASK-CANCEL-STATUS");
- await t.require(
- requireTaskView(verified.requireToolCall("task_cancel").output, taskId),
- satisfies(
- (view: Record<string, unknown>) => Reflect.get(view, "status") === "cancelled",
- "the session remains usable and exposes the cancelled task",
- ),
- );
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.complete.accepted-nonterminal.child-tool-surface.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.complete.accepted-nonterminal.child-tool-surface.eval.ts
deleted file mode 100644
index 9201c6b93..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.complete.accepted-nonterminal.child-tool-surface.eval.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { satisfies } from "eve/evals/expect";
-
-import { defineTaskEval } from "./task-transition.js";
-import { requireBackgroundTaskId, waitForTaskNotification } from "./shared.js";
-
-export default defineTaskEval({
- description:
- "A background child no longer advertises task_update, and its final tool report still reaches the parent.",
- transition: {
- primary: "task.lifecycle.complete.accepted-nonterminal",
- setup: ["task.dispatch.start.accepted-acknowledged"],
- dimensions: { transport: "local" },
- },
- async test(t) {
- const started = await t.send(
- "Alice asks Bob to summarize the available tools for a background task.",
- { taskDeliveryPolicy: "cohort" },
- );
- started.expectOk();
- started.calledSubagent("tool-surface-worker", { status: "working", count: 1 });
- started.event("action.result", {
- count: 1,
- data: {
- result: {
- kind: "tool-result",
- output: { status: "working" },
- callId: "task-child-tool-surface",
- toolName: "tool-surface-worker",
- },
- },
- });
- const taskId = requireBackgroundTaskId(started);
-
- const completed = await waitForTaskNotification(t, started.session, taskId, "completed", [
- started,
- ]);
- completed.turn.expectOk();
- t.event("subagent.completed", {
- count: 1,
- data: { callId: "task-child-tool-surface", subagentName: "tool-surface-worker" },
- });
- t.calledSubagent("tool-surface-worker", { status: "completed", count: 1 });
- const report = completed.turn.message;
- if (report === undefined) throw new Error("Parent did not return the child's tool report.");
- await t.require(
- JSON.parse(report) as unknown,
- satisfies((value) => {
- if (value === null || typeof value !== "object") return false;
- const tools = Reflect.get(value, "tools");
- return (
- Reflect.get(value, "result") === "TASK-CHILD-FINAL-RESULT" &&
- Array.isArray(tools) &&
- tools.every((tool) => typeof tool === "string") &&
- !tools.includes("task_update")
- );
- }, "the child reports its advertised tools without task_update and a final result"),
- );
- completed.turn.eventsSatisfy(
- "the final child report reaches its owning parent task",
- (events) =>
- events.some(
- (event) =>
- event.type === "message.received" &&
- typeof event.data.message === "string" &&
- event.data.message.includes(
- `Background task ${taskId} (tool-surface-worker) is completed.`,
- ) &&
- event.data.message.includes(report),
- ),
- );
- t.notCalledTool("task_update");
- t.noFailedActions();
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.fail.accepted-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.fail.accepted-nonterminal.eval.ts
deleted file mode 100644
index 00c36e5d1..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.fail.accepted-nonterminal.eval.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { satisfies } from "eve/evals/expect";
-
-import { requireBackgroundTaskId, requireTaskView, waitForTaskStatus } from "./shared.js";
-import { defineTaskEval } from "./task-transition.js";
-
-const CALL_ID = "task-a2-failing-busy-worker";
-
-/** A child execution failure remains observable through its durable task view. */
-export default defineTaskEval({
- description:
- "A background child that fails terminally leaves a failed task with a stable error projection.",
- transition: {
- primary: "task.lifecycle.fail.accepted-nonterminal",
- setup: ["task.dispatch.start.accepted-acknowledged"],
- dimensions: { transport: "local" },
- },
- async test(t) {
- const started = await t.send("TASK-A2-CHILD-FAILURE", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- started.messageIncludes("TASK-A2-CHILD-FAILURE-STARTED");
- started.event("action.result", {
- count: 1,
- data: {
- result: {
- kind: "tool-result",
- output: { status: "working" },
- callId: CALL_ID,
- toolName: "busy-worker",
- },
- },
- });
- const taskId = requireBackgroundTaskId(started);
-
- const failed = await waitForTaskStatus(
- t,
- started.session,
- "TASK-A2-CHILD-FAILURE-VERIFY",
- taskId,
- "failed",
- );
- failed.expectOk();
- failed.messageIncludes("TASK-A2-FAILED");
- const inspected = failed.requireToolCall("task_cancel", { input: { taskIds: [taskId] } });
- const view = requireTaskView(inspected.output, taskId);
- await t.require(
- view,
- satisfies(
- (task: Record<string, unknown>) =>
- Reflect.get(task, "taskId") === taskId &&
- Reflect.get(task, "status") === "failed" &&
- hasTaskMetadata(task, "busy-worker", "local") &&
- hasFailureOutput(task, "SUBAGENT_EXECUTION_FAILED"),
- "failed task keeps its id, busy-worker metadata, and stable error code",
- ),
- );
- },
-});
-
-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 hasFailureOutput(task: Record<string, unknown>, code: string): boolean {
- const lastOutput = Reflect.get(task, "lastOutput");
- if (
- lastOutput === null ||
- typeof lastOutput !== "object" ||
- Reflect.get(lastOutput, "type") !== "error"
- ) {
- return false;
- }
- const data = Reflect.get(lastOutput, "data");
- return data !== null && typeof data === "object" && Reflect.get(data, "code") === code;
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.ts
deleted file mode 100644
index c64d248ac..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
-import { type EveEvalTurn, type InputRequest } from "eve/evals";
-import { satisfies } from "eve/evals/expect";
-
-import { defineTaskEval } from "./task-transition.js";
-import {
- requireSessionStreamIndex,
- sendAndFollowQueuedTurn,
- type TaskEvalSessionDriver,
-} from "./shared.js";
-
-const FANOUT_SIZE = 10;
-
-/** The parent remains interactive while its background children await input. */
-export default defineTaskEval({
- description: "A parent accepts a new tool-free turn while ten background children remain live.",
- transition: {
- primary: "task.parent-interaction.send.accepted-live-children",
- setup: ["task.dispatch.start.accepted-acknowledged", "task.input.require.accepted-valid-batch"],
- dimensions: { transport: "local", parentPhase: "active" },
- },
- async test(t) {
- const started = await t.send("TASK-FANOUT-PARENT-UPDATES", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- started.messageIncludes("TASK-FANOUT-STARTED");
- started.calledSubagent("fanout-worker", { status: "working", count: FANOUT_SIZE });
-
- const taskIds = backgroundTaskIds(started);
- await t.require(
- taskIds,
- satisfies(
- (ids: readonly string[]) => ids.length === FANOUT_SIZE && new Set(ids).size === FANOUT_SIZE,
- `${FANOUT_SIZE} distinct background task receipts`,
- ),
- );
-
- const blockedSession = await waitForReleaseRequests(t, started.session, started);
- const interactive = await sendAndFollowQueuedTurn(
- t,
- "TASK-FANOUT-INTERACTIVE-CHECK",
- blockedSession,
- );
- interactive.turn.expectOk();
- interactive.turn.messageIncludes("TASK-FANOUT-INTERACTIVE-OK");
- interactive.turn.usedNoTools();
- t.noFailedActions();
- },
-});
-
-async function waitForReleaseRequests(
- t: Parameters<typeof sendAndFollowQueuedTurn>[0],
- initialSession: TaskEvalSessionDriver,
- initialTurn: EveEvalTurn,
-): Promise<TaskEvalSessionDriver> {
- const requests = new Map<string, InputRequest>();
- let session = initialSession;
- collectReleaseRequests(initialTurn, requests);
- // The parent completion may be the first watched boundary before child HITL
- // callbacks arrive, so allow one boundary in addition to the ten requests.
- for (let attempt = 0; attempt <= FANOUT_SIZE && requests.size < FANOUT_SIZE; attempt += 1) {
- const sessionId = session.sessionId;
- if (sessionId === undefined) throw new Error("Task fanout has no parent session id.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Task fanout release wait"),
- });
- const turn = await live.result();
- collectReleaseRequests(turn, requests);
- session = live.session;
- }
- if (requests.size !== FANOUT_SIZE) {
- throw new Error(`Expected ${FANOUT_SIZE} release requests; received ${requests.size}.`);
- }
- return session;
-}
-
-function collectReleaseRequests(turn: EveEvalTurn, requests: Map<string, InputRequest>): void {
- for (const request of turn.inputRequests) {
- if (request.action.toolName === "release") requests.set(request.requestId, request);
- }
-}
-
-function backgroundTaskIds(turn: EveEvalTurn): readonly string[] {
- return taskReceipts(turn.events).map(({ taskId }) => taskId);
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.batching.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.batching.eval.ts
deleted file mode 100644
index 3d9487bc6..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.batching.eval.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { equals } from "eve/evals/expect";
-
-import { completedTaskIds, completionMetrics, startBlockedFanout } from "./batching.js";
-import { defineTaskEval } from "./task-transition.js";
-
-const FANOUT_SIZE = 10;
-const EXPECTED_REPORT = JSON.stringify({
- report: "TASK-BATCHING-REPORT",
- results: Array.from(
- { length: FANOUT_SIZE },
- (_, index) => `FANOUT-COMPLETE:FANOUT-WORKER-${index + 1}`,
- ).sort(),
-});
-
-export default [
- { schedule: "burst", batches: [9] },
- { schedule: "staggered", batches: [1, 1, 1, 1, 1, 1, 1, 1, 1] },
-].map(({ schedule, batches }) =>
- defineTaskEval({
- description: `Measure completion-driven parent model steps for ${FANOUT_SIZE} children (${schedule}).`,
- timeoutMs: 180_000,
- transition: {
- primary: "task.parent.wake.emitted-ready",
- setup: [
- "task.dispatch.start.accepted-acknowledged",
- "task.input.require.accepted-valid-batch",
- "task.input.answer.accepted-complete",
- "task.lifecycle.complete.accepted-nonterminal",
- "task.parent.wake.noop-pending-cohort",
- ],
- dimensions: { transport: "local", parentPhase: "parked" },
- },
- async test(t) {
- const children = await startBlockedFanout(t, FANOUT_SIZE);
-
- // Child streams, not parent replies, acknowledge each release batch.
- for (const count of batches) await children.completeNext(count);
- await t.require(children.completedChildren.length, equals(FANOUT_SIZE - 1));
-
- const question = await children.send("TASK-BATCHING-QUESTION");
- const intermediate = completionMetrics(children.completionTurns);
- t.check(intermediate.modelSteps, equals(0)).label("no intermediate completion model steps");
- t.check(completionMetrics(children.parentTurns).modelSteps, equals(1)).label(
- "only the independent user question invokes the parent before settlement",
- );
- t.check(question.message, equals("56")).label(
- "user question answered while a child is blocked",
- );
- question.usedNoTools();
-
- await children.completeNext(1);
- t.check(
- children.completionTurns.flatMap(completedTaskIds).sort(),
- equals([...children.taskIds].sort()),
- ).label("every child result delivered exactly once, with no unknown task ids");
- t.check(children.completionTurns.at(-1)?.message, equals(EXPECTED_REPORT)).label(
- "final report contains every distinct child result exactly once",
- );
-
- const total = completionMetrics(children.completionTurns);
- t.check(
- total,
- equals({
- parentTurns: 1,
- modelSteps: 1,
- silentMessages: 0,
- visibleMessages: 1,
- completionsPerTurn: [FANOUT_SIZE],
- }),
- ).label("one full-cohort model turn and visible report");
- t.log(
- `task-batching ${JSON.stringify({ schedule, children: FANOUT_SIZE, intermediate, total })}`,
- );
- t.notEvent("compaction.requested");
- t.noFailedActions();
- },
- }),
-);
diff --git a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.cross-turn-cohort.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.cross-turn-cohort.eval.ts
deleted file mode 100644
index 40db0e64a..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.cross-turn-cohort.eval.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { equals } from "eve/evals/expect";
-import { CROSS_TURN_SCENARIO } from "../agent/lib/lifecycle-model.js";
-import { completedTaskIds } from "./batching.js";
-import { assertLifecycleUnion, lifecycleDriver } from "./lifecycle.js";
-import { defineTaskEval } from "./task-transition.js";
-
-export default (["A", "B"] as const).map((first) =>
- defineTaskEval({
- description: `Join overlapping launches in distinct user turns; ${first} completes while the other task is still gated.`,
- timeoutMs: 180_000,
- transition: {
- primary: "task.parent.wake.emitted-ready",
- setup: [
- "task.parent.wake.noop-pending-cohort",
- "task.lifecycle.complete.accepted-nonterminal",
- ],
- dimensions: { transport: "local", parentPhase: "parked" },
- },
- async test(t) {
- const key = crypto.randomUUID();
- const driver = lifecycleDriver(t, key);
- const started = await driver.start(`${CROSS_TURN_SCENARIO} ${key}`);
- started.messageIncludes("LAUNCHED:A");
- const a = await driver.gate("A");
- await t.require([...driver.taskIds.keys()], equals(["A"]));
- await driver.active(a);
-
- const launchB = "Alice now launches the second piece of work.";
- await driver.enqueue(launchB);
- const second = await driver.through(launchB);
- second.messageIncludes("LAUNCHED:B");
- const b = await driver.gate("B");
- await driver.active(a);
- await driver.active(b);
- await t.require([...driver.taskIds.keys()].sort(), equals(["A", "B"]));
- await t.require(new Set(driver.taskIds.values()).size, equals(2));
- const owners = driver.controls.filter((event) => event.kind === "owner");
- await t.require(
- owners.map((event) => event.marker),
- equals(["A", "B"]),
- );
- await t.require(new Set(owners.map((event) => event.turnId)).size, equals(2));
- const creatingTurns = [started, second].map(
- (turn) => turn.events.find((event) => event.type === "actions.requested")?.data.turnId,
- );
- await t.require(
- owners.map((event) => event.turnId),
- equals(creatingTurns),
- );
-
- const remaining = first === "A" ? "B" : "A";
- await driver.release(first === "A" ? a : b);
- await driver.settled(first);
- await driver.active(remaining === "A" ? a : b);
- const checkpoint = "Alice checks that the other piece of work is still pending.";
- await driver.enqueue(checkpoint);
- const pending = await driver.through(checkpoint);
- pending.messageIncludes("PENDING-CHECK-ACK");
- t.check(driver.turns.flatMap(completedTaskIds), equals([])).label(
- `${first} cannot report while ${remaining} remains pending in another creating turn`,
- );
-
- await driver.release(remaining === "A" ? a : b);
- await driver.settled(remaining);
- await driver.report();
- const drain = "Alice confirms that all completion deliveries have been observed.";
- await driver.enqueue(drain);
- (await driver.through(drain, true)).messageIncludes("DRAIN-ACK");
- assertLifecycleUnion(t, driver);
- t.noFailedActions();
- t.notEvent("compaction.requested");
- },
- }),
-);
diff --git a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.eval.ts
deleted file mode 100644
index 0963c315f..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.eval.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import { taskReceipts } from "@eve-e2e/config/task-receipts";
-import { type EveEvalContext, type EveEvalTurn, type InputRequest } from "eve/evals";
-import { satisfies } from "eve/evals/expect";
-
-import { defineTaskEval } from "./task-transition.js";
-import { requireSessionStreamIndex, type TaskEvalSessionDriver } from "./shared.js";
-
-const FANOUT_SIZE = 3;
-const COMPLETED_NOTIFICATION = /Background task (task_[a-z0-9]+) \([^)]+\) is completed\./giu;
-
-/** The final child releases every sibling's result in one parent turn. */
-export default defineTaskEval({
- description:
- "Three completed children wake their parent once with all task notifications and no duplicate or unknown task ids.",
- transition: {
- primary: "task.parent.wake.emitted-ready",
- setup: [
- "task.dispatch.start.accepted-acknowledged",
- "task.input.require.accepted-valid-batch",
- "task.input.answer.accepted-complete",
- "task.lifecycle.complete.accepted-nonterminal",
- ],
- dimensions: { transport: "local", parentPhase: "active" },
- },
- async test(t) {
- const started = await t.send("TASK-PARENT-WAKE-UPDATES", { taskDeliveryPolicy: "cohort" });
- started.expectOk();
- started.messageIncludes("TASK-FANOUT-STARTED");
- started.calledSubagent("fanout-worker", { status: "working", count: FANOUT_SIZE });
-
- const taskIds = backgroundTaskIds(started);
- await t.require(
- taskIds,
- satisfies(
- (ids: readonly string[]) => ids.length === FANOUT_SIZE && new Set(ids).size === FANOUT_SIZE,
- `${FANOUT_SIZE} distinct background task receipts`,
- ),
- );
-
- const blocked = await waitForReleaseRequests(t, started.session, started);
- const released = await blocked.session.respond(
- blocked.requests.map((request) => ({
- optionId: "approve",
- requestId: request.requestId,
- })),
- );
- released.expectOk();
-
- const completionTurns = [...blocked.observedTurns, released].filter(
- (turn) => completedNotificationTaskIds(turn).length > 0,
- );
- const notifiedTaskIds = completionTurns.flatMap(completedNotificationTaskIds);
- const observedKnownTaskIds = new Set(
- notifiedTaskIds.filter((taskId) => taskIds.includes(taskId)),
- );
- let session = blocked.session;
- for (
- let attempt = 0;
- attempt < FANOUT_SIZE && observedKnownTaskIds.size < FANOUT_SIZE;
- attempt += 1
- ) {
- const sessionId = session.sessionId;
- if (sessionId === undefined) throw new Error("Task fanout has no parent session id.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Task fanout notification wait"),
- });
- const turn = await live.result();
- if (completedNotificationTaskIds(turn).length > 0) completionTurns.push(turn);
- for (const taskId of completedNotificationTaskIds(turn)) {
- notifiedTaskIds.push(taskId);
- if (taskIds.includes(taskId)) observedKnownTaskIds.add(taskId);
- }
- session = live.session;
- }
-
- await t.require(
- notifiedTaskIds,
- satisfies(
- (ids: readonly string[]) =>
- ids.length === FANOUT_SIZE &&
- JSON.stringify([...ids].sort()) === JSON.stringify([...taskIds].sort()),
- "exactly one completed notification for every known task and none for unknown task ids",
- ),
- );
- await t.require(
- completionTurns.length,
- satisfies((count) => count === 1, "only the last sibling triggers a completion turn"),
- );
- completionTurns[0]!.event("step.started", { count: 1 });
- t.noFailedActions();
- },
-});
-
-interface BlockedFanout {
- readonly observedTurns: readonly EveEvalTurn[];
- readonly requests: readonly InputRequest[];
- readonly session: TaskEvalSessionDriver;
-}
-
-async function waitForReleaseRequests(
- t: EveEvalContext,
- initialSession: TaskEvalSessionDriver,
- initialTurn: EveEvalTurn,
-): Promise<BlockedFanout> {
- const requests = new Map<string, InputRequest>();
- const observedTurns = [initialTurn];
- let session = initialSession;
- collectReleaseRequests(initialTurn, requests);
- for (let attempt = 0; attempt < FANOUT_SIZE && requests.size < FANOUT_SIZE; attempt += 1) {
- const sessionId = session.sessionId;
- if (sessionId === undefined) throw new Error("Task fanout has no parent session id.");
- const live = t.target.watchTurn(sessionId, {
- startIndex: requireSessionStreamIndex(session, "Task fanout release wait"),
- });
- const turn = await live.result();
- observedTurns.push(turn);
- collectReleaseRequests(turn, requests);
- session = live.session;
- }
- if (requests.size !== FANOUT_SIZE) {
- throw new Error(`Expected ${FANOUT_SIZE} release requests; received ${requests.size}.`);
- }
- return { observedTurns, requests: [...requests.values()], session };
-}
-
-function collectReleaseRequests(turn: EveEvalTurn, requests: Map<string, InputRequest>): void {
- for (const request of turn.inputRequests) {
- if (request.action.toolName === "release") requests.set(request.requestId, request);
- }
-}
-
-function backgroundTaskIds(turn: EveEvalTurn): readonly string[] {
- return taskReceipts(turn.events).map(({ taskId }) => taskId);
-}
-
-function completedNotificationTaskIds(turn: EveEvalTurn): readonly string[] {
- return turn.events.flatMap((event) => {
- if (event.type !== "message.received") return [];
- return [...messageText(event.data.message).matchAll(COMPLETED_NOTIFICATION)].map(
- (match) => match[1] as string,
- );
- });
-}
-
-function messageText(message: unknown): string {
- if (typeof message === "string") return message;
- if (!Array.isArray(message)) return "";
- return message
- .flatMap((part) =>
- part !== null &&
- typeof part === "object" &&
- Reflect.get(part, "type") === "text" &&
- typeof Reflect.get(part, "text") === "string"
- ? [Reflect.get(part, "text") as string]
- : [],
- )
- .join("\n");
-}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.lifecycle-order.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.lifecycle-order.eval.ts
deleted file mode 100644
index 3b400c00d..000000000
--- a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.lifecycle-order.eval.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { equals } from "eve/evals/expect";
-import { LIFECYCLE_SCENARIO } from "../agent/lib/lifecycle-model.js";
-import { completedTaskIds } from "./batching.js";
-import { assertLifecycleUnion, lifecycleDriver } from "./lifecycle.js";
-import { defineTaskEval } from "./task-transition.js";
-
-export default defineTaskEval({
- description:
- "Process A completion, B terminal agent settlement, and B completion in FIFO order after an active parent turn.",
- timeoutMs: 180_000,
- transition: {
- primary: "task.parent.wake.emitted-ready",
- setup: ["task.lifecycle.complete.accepted-nonterminal", "task.parent.wake.noop-pending-cohort"],
- dimensions: { transport: "local", parentPhase: "active" },
- },
- async test(t) {
- const key = crypto.randomUUID();
- const driver = lifecycleDriver(t, key);
- const started = await driver.start(`${LIFECYCLE_SCENARIO} ${key}`);
- started.messageIncludes("LAUNCHED:A,B");
- const a = await driver.gate("A");
- const b = await driver.gate("B");
- await t.require([...driver.taskIds.keys()].sort(), equals(["A", "B"]));
- await t.require(new Set(driver.taskIds.values()).size, equals(2));
- const owners = driver.controls.filter((event) => event.kind === "owner");
- await t.require(owners.map((event) => event.marker).sort(), equals(["A", "B"]));
- await t.require(new Set(owners.map((event) => event.turnId)).size, equals(1));
-
- const holding = "Alice keeps the parent active while Bob finishes.";
- await driver.enqueue(holding);
- const parent = await driver.gate("parent");
- await driver.active(parent);
-
- await driver.release(a);
- // Owner completion includes the awaited terminal notification, unlike child stream completion.
- await driver.settled("A");
- await driver.active(parent);
- await driver.release(b);
- // This owner sends three notifications: agent invocation, agent settlement,
- // and task completion. All must be delivered before its run settles.
- await driver.settled("B", true);
- const child = await t.target.watchTurn(b.sessionId, { startIndex: 0 }).result();
- child.event("session.failed");
- t.check(
- child.events.flatMap((event) =>
- event.type === "step.completed"
- ? [
- {
- inputTokens: event.data.usage?.inputTokens,
- outputTokens: event.data.usage?.outputTokens,
- },
- ]
- : [],
- ),
- equals([{ inputTokens: 211, outputTokens: 37 }]),
- ).label("B performed real metered work before its terminal provider rejection");
- await driver.active(parent);
- // Owner completion proves enqueue, not driver receipt. A normal cancellation
- // behind B's wake must traverse the same FIFO inbox before ending this turn.
- // Releasing the unrelated fixture hook here would let turn-result win early.
- await driver.cancelHeldTurn(parent);
- const cancelled = await driver.through(holding);
- await t.require(
- cancelled.events.flatMap((event) =>
- event.type === "turn.cancelled" ? [event.data.turnId] : [],
- ),
- equals([parent.turnId]),
- );
- cancelled.event("session.waiting");
- cancelled.notEvent("turn.completed");
- await t.require(completedTaskIds(cancelled), equals([]));
- await driver.parentGateCancelled(parent);
- t.log(
- "FIFO cancellation acknowledged: A completed -> B agent-settled -> B completed were buffered before the held turn ended; its fixture hook was disposed.",
- );
- await driver.report();
-
- const drain = "Alice confirms that all completion deliveries have been observed.";
- await driver.enqueue(drain);
- (await driver.through(drain, true)).messageIncludes("DRAIN-ACK");
- assertLifecycleUnion(t, driver);
- // This is the actual framework handle announcement in the model request,
- // not a status inferred from the successful background-task report.
- const handlesMessage = "Alice checks that Bob's terminal session has no retained handle.";
- await driver.enqueue(handlesMessage);
- const handles = await driver.through(handlesMessage);
- t.check(JSON.parse(handles.message!), equals([])).label(
- "B's terminal child has no retained available or parked handle",
- );
- handles.usedNoTools();
-
- await driver.enqueue("Alice performs the final metered accounting check.");
- (await driver.through("Alice performs the final metered accounting check.")).messageIncludes(
- "ACCOUNTING-CHECK",
- );
- await driver.enqueue("Alice checks the remaining session budget.");
- const budget = await driver.nextTurn();
- await t.require(budget.inputRequests.length, equals(1));
- const request = budget.inputRequests[0]!;
- t.check(
- { kind: request.kind, tool: request.action.toolName, input: request.action.input },
- equals({
- kind: "session-limit",
- tool: "session_limit_continuation",
- input: { kind: "input", limit: 1_000_000, usedTokens: 1_000_001 },
- }),
- ).label(
- "runtime session total includes exactly B's 211 input tokens plus 999790 parent tokens",
- );
- budget.notEvent("step.completed");
- t.check(
- budget.toolCalls.map((call) => call.name),
- equals(["session_limit_continuation"]),
- ).label("only the runtime's session-limit control runs, not an authored tool");
- t.notEvent("compaction.requested");
- // No blanket noFailedActions: Bob's provider rejection is intentional.
- },
-});
diff --git a/e2e/fixtures/fixture-tasks/package.json b/e2e/fixtures/fixture-tasks/package.json
deleted file mode 100644
index 2ccaccfaf..000000000
--- a/e2e/fixtures/fixture-tasks/package.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "name": "fixture-tasks",
- "version": "0.0.0",
- "private": true,
- "type": "module",
- "scripts": {
- "build": "eve build",
- "dev": "eve dev",
- "start": "eve start",
- "typecheck": "pnpm validate:transitions && eve build --skip-sandbox-prewarm && tsc",
- "validate:transitions": "node scripts/validate-transitions.mjs",
- "test:e2e": "eve eval --strict",
- "test:unit": "node --test evals/lifecycle-model.test.mjs"
- },
- "dependencies": {
- "@eve-e2e/config": "workspace:*",
- "@workflow/world-postgres": "catalog:",
- "eve": "workspace:*",
- "zod": "catalog:"
- },
- "devDependencies": {
- "@types/node": "catalog:",
- "typescript": "catalog:"
- }
-}
diff --git a/e2e/fixtures/fixture-tasks/scripts/reproduce-tui-idle-work.sh b/e2e/fixtures/fixture-tasks/scripts/reproduce-tui-idle-work.sh
deleted file mode 100755
index ccb920a3f..000000000
--- a/e2e/fixtures/fixture-tasks/scripts/reproduce-tui-idle-work.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/usr/bin/env bash
-# Reproduce a TUI that follows background work after its foreground turn ended.
-#
-# Run this from the repository root:
-# e2e/fixtures/fixture-tasks/scripts/reproduce-tui-idle-work.sh
-#
-# In the TUI, send TUI-IDLE-WORK-REPRO. The parent reports
-# TUI-IDLE-WORK-STARTED and returns to its prompt; its background task then
-# durably waits 20 seconds before asking for first_gate, second_gate, and
-# third_gate approvals.
-set -euo pipefail
-
-repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
-port="${EVE_TUI_REPRO_PORT:-3217}"
-log_file="${TMPDIR:-/tmp}/eve-tui-idle-work-${port}.log"
-
-cleanup() {
- if [[ -n "${server_pid:-}" ]] && kill -0 "$server_pid" 2>/dev/null; then
- kill "$server_pid" 2>/dev/null || true
- wait "$server_pid" 2>/dev/null || true
- fi
-}
-trap cleanup EXIT INT TERM
-
-cd "$repo_root"
-EVE_E2E_MODEL=mock pnpm --filter fixture-tasks exec eve dev --no-ui --port "$port" >"$log_file" 2>&1 &
-server_pid=$!
-
-until curl --silent --fail --max-time 1 "http://127.0.0.1:${port}/eve/v1/health" >/dev/null; do
- if ! kill -0 "$server_pid" 2>/dev/null; then
- cat "$log_file" >&2
- exit 1
- fi
- sleep 0.2
-done
-
-printf 'Fixture server: http://127.0.0.1:%s\nServer log: %s\n\n' "$port" "$log_file"
-cat <<'EOF'
-Background idle-follow repro:
- TUI-IDLE-WORK-REPRO
- Returns to the prompt, then waits 20 seconds before requesting approval.
-
-Foreground hang lab (each holds for 45 seconds):
- TUI-HANG-IN-PROCESS ordinary Node.js promise timer
- TUI-HANG-WORKFLOW durable workflow sleep
- TUI-HANG-COMMAND child process: sleep 45 (logs start/completion)
- TUI-HANG-SUBAGENT foreground subagent whose own tool waits
-EOF
-printf '\n'
-
-pnpm --filter fixture-tasks exec eve remote connect --url "http://127.0.0.1:${port}"
diff --git a/e2e/fixtures/fixture-tasks/scripts/validate-transitions.mjs b/e2e/fixtures/fixture-tasks/scripts/validate-transitions.mjs
deleted file mode 100644
index 907a2f64c..000000000
--- a/e2e/fixtures/fixture-tasks/scripts/validate-transitions.mjs
+++ /dev/null
@@ -1,53 +0,0 @@
-import { readdir, readFile } from "node:fs/promises";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-
-const fixtureRoot = dirname(dirname(fileURLToPath(import.meta.url)));
-const evalsRoot = join(fixtureRoot, "evals");
-const files = await collectEvalFiles(evalsRoot);
-const issues = [];
-
-for (const file of files) {
- const source = await readFile(join(evalsRoot, file), "utf8");
- const anchors = [...source.matchAll(/primary:\s*"([^"]+)"/gu)].map((match) => match[1]);
- if (!source.includes("defineTaskEval(")) {
- issues.push(`${file}: task evals must use defineTaskEval().`);
- }
- if (source.includes("defineEval(")) {
- issues.push(`${file}: direct defineEval() bypasses transition validation.`);
- }
- if (anchors.length !== 1) {
- issues.push(
- `${file}: expected exactly one primary transition anchor; found ${anchors.length}.`,
- );
- continue;
- }
- const anchor = anchors[0];
- const fileName = file.split("/").at(-1);
- if (fileName !== `${anchor}.eval.ts` && !fileName?.startsWith(`${anchor}.`)) {
- issues.push(`${file}: filename must derive from primary anchor ${anchor}.`);
- }
- if (!source.includes("dimensions:")) {
- issues.push(`${file}: transition declaration must factor scenario dimensions.`);
- }
-}
-
-if (issues.length > 0) {
- process.stderr.write(`${issues.join("\n")}\n`);
- process.exitCode = 1;
-} else {
- process.stdout.write(`Validated ${files.length} task eval transition declarations.\n`);
-}
-
-async function collectEvalFiles(directory, prefix = "") {
- const files = [];
- for (const entry of await readdir(directory, { withFileTypes: true })) {
- const relativePath = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
- if (entry.isDirectory()) {
- files.push(...(await collectEvalFiles(join(directory, entry.name), relativePath)));
- } else if (entry.name.endsWith(".eval.ts")) {
- files.push(relativePath);
- }
- }
- return files.sort();
-}
diff --git a/e2e/fixtures/fixture-tasks/tsconfig.json b/e2e/fixtures/fixture-tasks/tsconfig.json
deleted file mode 100644
index 032878901..000000000
--- a/e2e/fixtures/fixture-tasks/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "esnext",
- "moduleResolution": "bundler",
- "outDir": "dist",
- "rootDir": ".",
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "forceConsistentCasingInFileNames": true,
- "declaration": true,
- "noEmit": true,
- "types": ["node", "eve/workflow-modules"]
- },
- "include": ["agent/**/*.ts", "evals/**/*.ts"]
-}
diff --git a/e2e/fixtures/fixture-tasks/vercel.json b/e2e/fixtures/fixture-tasks/vercel.json
deleted file mode 100644
index 4fee39508..000000000
--- a/e2e/fixtures/fixture-tasks/vercel.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "experimentalServices": {
- "eve": {
- "entrypoint": ".",
- "framework": "eve",
- "routePrefix": "/eve/v1"
- }
- }
-}
diff --git a/packages/eve-code/extension/lib/prwatch-github.ts b/packages/eve-code/extension/lib/prwatch-github.ts
index 94c12290e..5479e9936 100644
--- a/packages/eve-code/extension/lib/prwatch-github.ts
+++ b/packages/eve-code/extension/lib/prwatch-github.ts
@@ -80,8 +80,7 @@ export function framePullRequestWatchWake(instruction: string): string {
`${instruction}\n\n` +
"This is an internal watch wake, not a request for a progress report. Continue any necessary " +
"work. Send a user-facing response only when the original request is complete or a new blocker " +
- "requires human input. Otherwise, finish by replying with exactly <eve-empty-delivery/> and no " +
- "other text. Do not report that nothing changed or that work is still in progress."
+ "requires human input. Do not report that nothing changed or that work is still in progress."
);
}
diff --git a/packages/eve-code/test/scenario/prwatch-github.test.ts b/packages/eve-code/test/scenario/prwatch-github.test.ts
index 5281d2603..dfae6aa0d 100644
--- a/packages/eve-code/test/scenario/prwatch-github.test.ts
+++ b/packages/eve-code/test/scenario/prwatch-github.test.ts
@@ -41,7 +41,6 @@ test("frames watcher wakes as internal work rather than progress reports", () =>
assert.match(framed, /internal watch wake/u);
assert.match(framed, /original request is complete/u);
assert.match(framed, /new blocker requires human input/u);
- assert.match(framed, /exactly <eve-empty-delivery\/>/u);
assert.match(framed, /Do not report that nothing changed/u);
});
diff --git a/packages/eve/extension-contracts/reports/channel/v35.json b/packages/eve/extension-contracts/reports/channel/v35.json
new file mode 100644
index 000000000..f3be784c0
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v35.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 35,
+ "sha256": "07ec76a130a0be1e90616e729a16c98cf33430273951833ce9aa863ce4e88b59",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v29.json b/packages/eve/extension-contracts/reports/connection/v29.json
new file mode 100644
index 000000000..e17515935
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v29.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 29,
+ "sha256": "a5bda1481190add46c8ddaf42f38f8c9cc8e9056388a7dd2c1dde2f9d9627ba9",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v25.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v25.json
new file mode 100644
index 000000000..d4733faa0
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v25.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicInstructions",
+ "epoch": 25,
+ "sha256": "3cf5599712e1587a297324c0cbb6d8661fc7ab8a85745b3313bac0294bf2d8ea",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v24.json b/packages/eve/extension-contracts/reports/dynamicSkill/v24.json
new file mode 100644
index 000000000..547e9207d
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v24.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicSkill",
+ "epoch": 24,
+ "sha256": "709d6de98a0b0be8541f66e707363440932c6ed428bd85bd42ba9b42f7a34a05",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v57.json b/packages/eve/extension-contracts/reports/dynamicTool/v57.json
new file mode 100644
index 000000000..a046617e4
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v57.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 57,
+ "sha256": "ce4685fa1cc0faa147f1a7bdeb2b9f86bf0ef1d55b596cf7a9515fc155d41db9",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v30.json b/packages/eve/extension-contracts/reports/hook/v30.json
new file mode 100644
index 000000000..cc8949390
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v30.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 30,
+ "sha256": "f414fa00cf8f1b924df114b4b366695a85cd8d0adbbc10c098f7bcb6c9c21747",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/schedule/v17.json b/packages/eve/extension-contracts/reports/schedule/v17.json
new file mode 100644
index 000000000..92fd676c5
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/schedule/v17.json
@@ -0,0 +1,14 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "schedule",
+ "epoch": 17,
+ "sha256": "2bd223e2801629a6c071674f148888bc9f26dea8984ceae402f550539aab7c18",
+ "exports": [
+ "ScheduleDefinition",
+ "ScheduleHandlerArgs",
+ "ScheduleRunHandler",
+ "ScheduleToFn",
+ "TypedReceiveTarget",
+ "defineSchedule"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/subagent/v22.json b/packages/eve/extension-contracts/reports/subagent/v22.json
new file mode 100644
index 000000000..3c8370489
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/subagent/v22.json
@@ -0,0 +1,23 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "subagent",
+ "epoch": 22,
+ "sha256": "ee121593d3d52e1a446d8c706c5cf4f07b4115b4f6da3e9ce0f366f324ff5de6",
+ "exports": [
+ "AgentCompactionDefinition",
+ "AgentDefinition",
+ "AgentModelDefinition",
+ "AgentStaticModelDefinition",
+ "DefinedAgent",
+ "DynamicLocalSubagentDefinition",
+ "DynamicSubagentDefinition",
+ "RemoteAgentDefinition",
+ "RemoteAgentDefinitionInput",
+ "WorkspaceAgentDefinition",
+ "WorkspaceAgentTransport",
+ "defineAgent",
+ "defineDynamic",
+ "defineRemoteAgent",
+ "defineWorkspaceAgent"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v60.json b/packages/eve/extension-contracts/reports/tool/v60.json
new file mode 100644
index 000000000..22abbdb4d
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v60.json
@@ -0,0 +1,27 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 60,
+ "sha256": "84b90752d3945baec7deb98258f0548a0a7b7085fc459151d773eb4f70944120",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "evaluate",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 3d5a0d40b..a76dc9b0f 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -187,11 +187,6 @@
"import": "./dist/src/public/tools/connection-search.js",
"default": "./dist/src/public/tools/connection-search.js"
},
- "./tools/task_cancel": {
- "types": "./dist/src/public/tools/task-cancel.d.ts",
- "import": "./dist/src/public/tools/task-cancel.js",
- "default": "./dist/src/public/tools/task-cancel.js"
- },
"./tools/glob": {
"types": "./dist/src/public/tools/glob.d.ts",
"import": "./dist/src/public/tools/glob.js",
diff --git a/packages/eve/src/channel/channel-address.test.ts b/packages/eve/src/channel/channel-address.test.ts
index d1dc8f72a..a8cc3808d 100644
--- a/packages/eve/src/channel/channel-address.test.ts
+++ b/packages/eve/src/channel/channel-address.test.ts
@@ -19,34 +19,6 @@ function createRuntime(): Runtime {
}
describe("createChannelAddress", () => {
- it("carries each send's task policy through creation and continuation", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.dispatchContinuation).mockResolvedValueOnce({ status: "session_not_active" });
- vi.mocked(runtime.createSession).mockResolvedValue({ sessionId: "sess_1" } as never);
- const address = createChannelAddress({
- adapter: { kind: "http" },
- channelName: "reports",
- continuationToken: "alice",
- runtime,
- });
- await address.send("Prepare reports", { auth: null, taskDeliveryPolicy: "cohort" });
- expect(runtime.createSession).toHaveBeenCalledWith(
- expect.objectContaining({
- taskDeliveryPolicy: "cohort",
- continuationConflictCommand: expect.objectContaining({ taskDeliveryPolicy: "cohort" }),
- }),
- );
- await address.send("Share useful results as they arrive", {
- auth: null,
- taskDeliveryPolicy: "auto",
- });
- expect(runtime.dispatchContinuation).toHaveBeenLastCalledWith(
- expect.objectContaining({
- command: expect.objectContaining({ taskDeliveryPolicy: "auto" }),
- }),
- );
- });
-
it("rejects channel addresses in the framework-reserved session namespace", () => {
expect(() =>
createChannelAddress({
diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.ts
index 696dd487f..4d5a065c9 100644
--- a/packages/eve/src/channel/channel-address.ts
+++ b/packages/eve/src/channel/channel-address.ts
@@ -20,7 +20,6 @@ import type {
SessionCallback,
SessionCommand,
TurnPolicy,
- TaskDeliveryPolicy,
} from "#channel/types.js";
import { DEFAULT_TURN_POLICY } from "#channel/types.js";
import { isReservedSessionCommandToken } from "#execution/session-inbox/address.js";
@@ -31,7 +30,6 @@ interface BaseChannelAddressDeliveryOptions {
readonly initiatorAuth?: SessionAuthContext | null;
readonly title?: string;
readonly turnPolicy?: TurnPolicy;
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
}
/** Delivery options for a channel address whose continuation token is already bound. */
@@ -72,7 +70,6 @@ export function createChannelAddress<TState = undefined>(input: {
readonly metadata?: ChannelDeliverySource;
readonly runtime: Runtime;
readonly turnPolicy?: TurnPolicy;
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
}): ChannelAddress<TState> {
const metadata: Partial<ChannelDeliverySource> = input.metadata ?? {};
const namespacedToken = `${input.channelName}:${input.continuationToken}`;
@@ -89,9 +86,7 @@ export function createChannelAddress<TState = undefined>(input: {
: undefined;
const payload = normalizeSendInput(sendInput);
const caller = sessionCallbackToTurnCaller(options.callback);
- const taskDeliveryPolicy = options.taskDeliveryPolicy ?? input.taskDeliveryPolicy;
const commandWithoutCaller = {
- taskDeliveryPolicy,
auth: options.auth,
delivery,
kind: "send" as const,
@@ -138,7 +133,6 @@ export function createChannelAddress<TState = undefined>(input: {
};
if (adapter !== input.adapter) copyChannelActivityPresentation(input.adapter, adapter);
const runInput: RunInput = {
- taskDeliveryPolicy,
adapter,
auth: options.auth,
capabilities: { requestInput: true },
@@ -214,7 +208,6 @@ export function createChannelAddressFn<TState = undefined>(input: {
readonly metadata?: ChannelDeliverySource;
readonly runtime: Runtime;
readonly turnPolicy?: TurnPolicy;
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
}): ChannelAddressFn<TState> {
return (continuationToken) => createChannelAddress({ ...input, continuationToken });
}
diff --git a/packages/eve/src/channel/channel-operations.ts b/packages/eve/src/channel/channel-operations.ts
index cda22f38b..abd9d236a 100644
--- a/packages/eve/src/channel/channel-operations.ts
+++ b/packages/eve/src/channel/channel-operations.ts
@@ -17,7 +17,6 @@ import type {
SessionAuthContext,
SessionCallback,
TurnPolicy,
- TaskDeliveryPolicy,
} from "#channel/types.js";
import {
type InputResponse,
@@ -32,8 +31,6 @@ interface BaseChannelSendOptions {
readonly initiatorAuth?: SessionAuthContext | null;
readonly title?: string;
readonly turnPolicy?: TurnPolicy;
- /** Updates the session policy; omission preserves it. New sessions default to auto, schedules to cohort. */
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
}
/** Options for sending a message from a channel-local continuation address. */
@@ -98,7 +95,6 @@ export function createChannelOperations<TState = undefined>(input: {
readonly metadata?: ChannelDeliverySource;
readonly runtime: Runtime;
readonly turnPolicy?: TurnPolicy;
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
}): ChannelReceiveContext<TState> {
const channelAddress = createChannelAddressFn<TState>(input);
diff --git a/packages/eve/src/channel/cross-channel-receive.test.ts b/packages/eve/src/channel/cross-channel-receive.test.ts
index 8e36f2a4e..7bc21fb2c 100644
--- a/packages/eve/src/channel/cross-channel-receive.test.ts
+++ b/packages/eve/src/channel/cross-channel-receive.test.ts
@@ -6,8 +6,6 @@ import {
type CrossChannelTarget,
type CrossChannelToFn,
} from "#channel/cross-channel-receive.js";
-import { TaskDeliveryPolicyKey } from "#context/keys.js";
-import { buildRunContext } from "#execution/runtime-context.js";
import type { Session } from "#channel/session.js";
import type { Runtime } from "#channel/types.js";
import type { SlackChannel, SlackReceiveTarget } from "#public/channels/slack/slackChannel.js";
@@ -78,52 +76,6 @@ function makeChannel(name: string): {
}
describe("createCrossChannelToFn", () => {
- it("defaults to auto when both the sender and receiver omit the task policy", async () => {
- const runtime = makeRuntime();
- vi.mocked(runtime.dispatchContinuation).mockResolvedValue({ status: "session_not_active" });
- vi.mocked(runtime.createSession).mockImplementation(async (run) => {
- const context = buildRunContext({ bundle: {} as never, run });
- expect(context.get(TaskDeliveryPolicyKey)).toBe("auto");
- return { sessionId: "sess_1" } as never;
- });
- const channel = makeChannel("reports");
- channel.receive.mockImplementation((input, { from }) =>
- from("alice").send(input.message, { auth: input.auth }),
- );
-
- const session = await createCrossChannelToFn(runtime, [channel.target])(
- channel.definition,
- {},
- ).send("Prepare reports", { auth: null });
-
- expect(runtime.createSession).toHaveBeenCalledOnce();
- expect(session.id).toBe("sess_1");
- });
-
- it("carries a cross-channel send policy through the receiver's local send", async () => {
- const runtime = makeRuntime();
- vi.mocked(runtime.dispatchContinuation).mockResolvedValue({
- sessionId: "sess_1",
- status: "accepted",
- });
- const channel = makeChannel("reports");
- channel.receive.mockImplementation((input, { from }) =>
- from("alice").send(input.message, { auth: input.auth }),
- );
- await createCrossChannelToFn(runtime, [channel.target])(channel.definition, {}).send(
- "Prepare reports",
- {
- auth: null,
- taskDeliveryPolicy: "cohort",
- },
- );
- expect(runtime.dispatchContinuation).toHaveBeenCalledWith(
- expect.objectContaining({
- command: expect.objectContaining({ taskDeliveryPolicy: "cohort" }),
- }),
- );
- });
-
it("accepts a Slack channel whose receive target is a closed interface", () => {
const typeOnlyCalls = (to: CrossChannelToFn, slack: SlackChannel) => {
const target: SlackReceiveTarget = { channelId: "C1" };
diff --git a/packages/eve/src/channel/cross-channel-receive.ts b/packages/eve/src/channel/cross-channel-receive.ts
index d96213ee2..756b404bd 100644
--- a/packages/eve/src/channel/cross-channel-receive.ts
+++ b/packages/eve/src/channel/cross-channel-receive.ts
@@ -9,12 +9,7 @@ import {
} from "#channel/compiled-channel.js";
import type { InferReceiveTarget } from "#channel/receive-target.js";
import type { Session } from "#channel/session.js";
-import type {
- Runtime,
- SessionAuthContext,
- TurnPolicy,
- TaskDeliveryPolicy,
-} from "#channel/types.js";
+import type { Runtime, SessionAuthContext, TurnPolicy } from "#channel/types.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
/**
@@ -23,8 +18,6 @@ import type { ResolvedChannelDefinition } from "#runtime/types.js";
interface CrossChannelSendOptions {
readonly auth: SessionAuthContext | null;
readonly turnPolicy?: TurnPolicy;
- /** Updates the session policy; omission preserves it. New sessions default to auto, schedules to cohort. */
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
}
/** Message delivery bound to one channel-specific proactive target. */
@@ -96,7 +89,6 @@ export function createCrossChannelToFn(
auth: options.auth,
},
turnPolicy: options.turnPolicy,
- taskDeliveryPolicy: options.taskDeliveryPolicy,
describeMissingReceive: () =>
`ctx.to(): channel "${targetChannel.name}" does not implement receive(). ` +
`Declare a receive hook on the channel to accept cross-channel sessions.`,
@@ -117,7 +109,6 @@ interface InvokeChannelReceiveInput {
readonly auth: SessionAuthContext | null;
};
readonly turnPolicy?: TurnPolicy;
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
readonly describeMissingReceive: () => string;
readonly describeMissingAdapter: () => string;
}
@@ -137,7 +128,6 @@ async function invokeChannelReceive(args: InvokeChannelReceiveInput): Promise<Se
channelName: args.target.name,
runtime: args.runtime,
turnPolicy: args.turnPolicy ?? args.target.turnPolicy,
- taskDeliveryPolicy: args.taskDeliveryPolicy,
});
return await args.target.receive(args.input, channelOperations);
}
diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.ts
index 3a8674206..7f4ebfeb1 100644
--- a/packages/eve/src/channel/schedule.test.ts
+++ b/packages/eve/src/channel/schedule.test.ts
@@ -9,9 +9,8 @@ import {
SCHEDULE_APP_AUTH,
ScheduleDispatcher,
} from "#channel/schedule.js";
-import { buildRunContext } from "#execution/runtime-context.js";
import { contextStorage } from "#context/container.js";
-import { ScheduleIdKey, TaskDeliveryPolicyKey } from "#context/keys.js";
+import { ScheduleIdKey } from "#context/keys.js";
import type { RunHandle, Runtime } from "#channel/types.js";
import { slackChannel } from "#public/channels/slack/slackChannel.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
@@ -60,40 +59,6 @@ function makeSlackChannelEntry(): {
}
describe("ScheduleDispatcher", () => {
- it.each([undefined, "auto", "cohort"] as const)(
- "uses the schedule default unless send supplies %s",
- async (taskDeliveryPolicy) => {
- vi.stubEnv("SLACK_BOT_TOKEN", "xoxb-test");
- vi.stubEnv("SLACK_SIGNING_SECRET", "test-secret");
- try {
- const runtime = createMockRuntime();
- const policies: unknown[] = [];
- runtime.createSession = vi.fn(async (run) => {
- policies.push(buildRunContext({ bundle: {} as never, run }).get(TaskDeliveryPolicyKey));
- return createMockRunHandle();
- });
- const { definition, resolved } = makeSlackChannelEntry();
- const result = await new ScheduleDispatcher({ runtime, channels: [resolved] }).trigger({
- scheduleId: "daily-report",
- run({ to, waitUntil, appAuth }) {
- waitUntil(
- Promise.resolve().then(() =>
- to(definition, { channelId: "C0123ABC" }).send("Report", {
- auth: appAuth,
- taskDeliveryPolicy,
- }),
- ),
- );
- },
- });
- await Promise.all(result.waitUntilTasks);
- expect(policies).toEqual([taskDeliveryPolicy ?? "cohort"]);
- } finally {
- vi.unstubAllEnvs();
- }
- },
- );
-
describe("markdown form", () => {
it("starts a Session via runtime.createSession with the SCHEDULE_ADAPTER", async () => {
const runtime = createMockRuntime();
diff --git a/packages/eve/src/channel/session-callback.ts b/packages/eve/src/channel/session-callback.ts
index 58f92b423..cfbb56e22 100644
--- a/packages/eve/src/channel/session-callback.ts
+++ b/packages/eve/src/channel/session-callback.ts
@@ -20,7 +20,6 @@ const sessionCallbackSchema = z
.object({
callId: z.string().min(1),
subagentName: z.string().min(1),
- taskId: z.string().min(1).optional(),
token: z.string().min(1),
url: z.string().min(1),
})
diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.ts
index 34e96a4f2..dd3666040 100644
--- a/packages/eve/src/channel/session.test.ts
+++ b/packages/eve/src/channel/session.test.ts
@@ -55,20 +55,6 @@ function createRuntime(): Runtime {
}
describe("createSession#cancel", () => {
- it("passes an explicit task policy through a fixed-session send", async () => {
- const runtime = createRuntime();
- await createSession("sess_1", runtime).send("Report when ready", {
- auth: null,
- taskDeliveryPolicy: "auto",
- });
- expect(runtime.dispatchSession).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionId: "sess_1",
- command: expect.objectContaining({ taskDeliveryPolicy: "auto" }),
- }),
- );
- });
-
it("cancels this session's turn by session id", async () => {
const runtime = createRuntime();
const session = createSession("sess_1", runtime);
@@ -80,14 +66,14 @@ describe("createSession#cancel", () => {
});
});
- it("forwards the turn guard and owned-task scope", async () => {
+ it("forwards the turn guard", async () => {
const runtime = createRuntime();
const session = createSession("sess_1", runtime);
- await session.cancel({ tasks: true, turnId: "turn_2" });
+ await session.cancel({ turnId: "turn_2" });
expect(runtime.dispatchSession).toHaveBeenCalledWith({
- command: { kind: "cancel", tasks: true, turnId: "turn_2" },
+ command: { kind: "cancel", turnId: "turn_2" },
sessionId: "sess_1",
});
});
diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.ts
index 50d257aa8..9497fabbf 100644
--- a/packages/eve/src/channel/session.ts
+++ b/packages/eve/src/channel/session.ts
@@ -16,7 +16,6 @@ import type {
SessionCallback,
SessionSendCommandResult,
TurnPolicy,
- TaskDeliveryPolicy,
TurnCaller,
} from "#channel/types.js";
import { DEFAULT_TURN_POLICY } from "#channel/types.js";
@@ -51,12 +50,8 @@ export interface Session {
inputResponses: StrictInputResponses<TResponses>,
options: SessionRespondOptions,
): Promise<SessionSendCommandResult>;
- /** Requests cancellation of this exact session's active turn and optionally its owned tasks. */
- cancel(options?: {
- taskId?: string;
- tasks?: boolean;
- turnId?: string;
- }): Promise<CancelTurnResult>;
+ /** Requests cancellation of this exact session's active turn. */
+ cancel(options?: { turnId?: string }): Promise<CancelTurnResult>;
/** Queues compaction on this exact session ID. */
compact(): Promise<CompactSessionResult>;
/** Queues a context clear on this exact session ID. */
@@ -81,8 +76,6 @@ export type SessionSendOptions = SessionDeliveryOptions & {
/** Initial workflow title for a prewarmed session. */
readonly title?: string;
readonly turnPolicy?: TurnPolicy;
- /** Updates the session policy; omission preserves it. New sessions default to auto, schedules to cohort. */
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
};
/** Options for answering pending input requests through a fixed session handle. */
@@ -129,7 +122,6 @@ export function createSession(
payload,
requestId: metadata.requestId,
turnPolicy: options.turnPolicy ?? metadata.turnPolicy ?? DEFAULT_TURN_POLICY,
- taskDeliveryPolicy: options.taskDeliveryPolicy,
title: options.title,
};
return await runtime.dispatchSession({
@@ -163,12 +155,8 @@ export function createSession(
sessionId: id,
});
},
- async cancel(options?: { taskId?: string; tasks?: boolean; turnId?: string }) {
- const command: { kind: "cancel"; taskId?: string; tasks?: boolean; turnId?: string } = {
- kind: "cancel",
- };
- if (options?.taskId !== undefined) command.taskId = options.taskId;
- if (options?.tasks !== undefined) command.tasks = options.tasks;
+ async cancel(options?: { turnId?: string }) {
+ const command: { kind: "cancel"; turnId?: string } = { kind: "cancel" };
if (options?.turnId !== undefined) command.turnId = options.turnId;
return await runtime.dispatchSession({ command, sessionId: id });
},
@@ -273,6 +261,5 @@ export function sessionCallbackToTurnCaller(
callId: callback.callId,
replyTo: { kind: "callback", token: callback.token, url: callback.url },
subagentName: callback.subagentName,
- taskId: callback.taskId,
};
}
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 36f3736e4..43f086f93 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -9,19 +9,12 @@ import type {
RuntimeToolResultActionResult,
} from "#shared/action-types.js";
import type { InputRequest, InputResponse } from "#shared/input.js";
-import type { ToolInputResponseResponder } from "#tools/definition.js";
import type { ChannelAdapter } from "#channel/adapter.js";
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 { ConversationContext } from "#shared/conversation-context.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";
@@ -36,10 +29,6 @@ export type RunSessionLimits = Pick<
/** Identifies the session turn to cancel. */
export interface CancelTurnInput {
readonly sessionId: string;
- /** Framework task whose queued child deliveries should be discarded. */
- readonly taskId?: string;
- /** Cancels every nonterminal task owned by the session. */
- readonly tasks?: boolean;
/** Limits the request to the turn the caller observed. */
readonly turnId?: string;
}
@@ -149,8 +138,6 @@ export interface TurnCaller {
readonly activityObserver?: ActivityObserverConfig;
readonly callId: string;
readonly subagentName: string;
- /** Present when this turn is the executor for a durable background task. */
- readonly taskId?: string;
readonly replyTo:
| { readonly kind: "hook"; readonly token: string }
| { readonly kind: "callback"; readonly token: string; readonly url: string };
@@ -170,28 +157,12 @@ export interface TurnCaller {
*/
export interface DeliverPayload {
readonly inputResponses?: readonly InputResponse[];
- /** Authenticated identity associated with an internal forwarded input response. */
- readonly responder?: ToolInputResponseResponder;
readonly message?: string | UserContent;
readonly context?: readonly string[];
readonly outputSchema?: JsonObject;
- /** 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 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[];
- };
readonly [key: string]: unknown;
}
-/** Controls background task wake timing and whether partial results require a report. */
-export type TaskDeliveryPolicy = "cohort" | "auto";
-
/** Controls how a channel message interacts with an active turn. */
export type TurnPolicy = "steer" | "queue";
@@ -209,19 +180,10 @@ export type SessionCommand =
readonly payload: DeliverPayload;
readonly delivery?: ChannelDeliveryMetadata;
readonly requestId?: string;
- /**
- * Replay-stable identity for one task-owned child delivery; lets the
- * parent inbox dedupe retried durable-step deliveries. See
- * {@link DeliverHookPayload.taskDeliveryId}.
- */
- readonly taskDeliveryId?: string;
readonly turnPolicy?: TurnPolicy;
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
}
| {
readonly kind: "cancel";
- readonly taskId?: string;
- readonly tasks?: boolean;
readonly turnId?: string;
}
| { readonly kind: "compact" }
@@ -282,19 +244,9 @@ export interface DeliverHookPayload {
readonly deliveryMetadata?: readonly ChannelDeliveryMetadataEntry[];
/** Inbound channel request id used only for workflow attributes. */
readonly requestId?: string;
- /**
- * Replay-stable identity for one task-owned child delivery. Task-run steps
- * derive it from deterministic inputs (task id, event kind, sequence) so the
- * parent inbox can drop the duplicate when a durable step retries after
- * `resumeHook` already succeeded.
- */
- readonly taskDeliveryId?: string;
- /** All source notifications when the session queue combines task results. */
- readonly taskDeliveryIds?: readonly string[];
readonly kind: "deliver";
readonly payloads: readonly DeliverPayload[];
readonly turnPolicy?: TurnPolicy;
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
}
/** Internal deadline signal sent through the stable session command inbox. */
@@ -420,7 +372,6 @@ export interface ActivityObserverConfig {
export interface SessionCallback {
readonly callId: string;
readonly subagentName: string;
- readonly taskId?: string;
readonly token: string;
readonly url: string;
}
@@ -462,10 +413,7 @@ export interface SessionCapabilities {
* subagent tool wrapper).
*/
export interface RunInput {
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
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
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 978fe60cc..a75dbb2e4 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -374,7 +374,6 @@ describe("registryHandoffAddress", () => {
suspendPromptForInput: () => promptSuspended.resolve(),
subagents: {
begin: vi.fn(),
- background: vi.fn(),
upsertStep: vi.fn(),
upsertTool: vi.fn(),
removeTool: vi.fn(),
@@ -881,7 +880,7 @@ describe("EveTUIRunner idle session follow", () => {
expect(renderIdleStream).not.toHaveBeenCalled();
});
- it("renders background completion after two quiet minutes without another user message", async () => {
+ it("renders an idle-session turn after two quiet minutes without another user message", async () => {
vi.useFakeTimers();
const session = stubSession();
const prompt = createDeferred<string | undefined>();
@@ -896,7 +895,7 @@ describe("EveTUIRunner idle session follow", () => {
type: "message.completed",
data: {
finishReason: "stop",
- message: "Alice's background review is ready for Bob.",
+ message: "Alice's review is ready for Bob.",
sequence: 1,
stepIndex: 0,
turnId: "wake-turn",
@@ -949,7 +948,7 @@ describe("EveTUIRunner idle session follow", () => {
expect(idleEvents).toContainEqual({
type: "assistant-complete",
id: "text:wake-turn:0",
- text: "Alice's background review is ready for Bob.",
+ text: "Alice's review is ready for Bob.",
});
expect(send).not.toHaveBeenCalled();
} finally {
@@ -1012,10 +1011,10 @@ describe("EveTUIRunner idle session follow", () => {
data: {
actions: [
{
- callId: "cancel-1",
- input: { taskIds: ["task_123"] },
+ callId: "lookup-1",
+ input: { query: "research status" },
kind: "tool-call",
- toolName: "task_cancel",
+ toolName: "lookup",
},
],
sequence: 1,
@@ -1027,10 +1026,10 @@ describe("EveTUIRunner idle session follow", () => {
type: "action.result",
data: {
result: {
- callId: "cancel-1",
+ callId: "lookup-1",
kind: "tool-result",
- output: { tasks: [{ status: "cancelled", taskId: "task_123" }] },
- toolName: "task_cancel",
+ output: { status: "finished" },
+ toolName: "lookup",
},
sequence: 1,
status: "completed",
@@ -1041,7 +1040,7 @@ describe("EveTUIRunner idle session follow", () => {
{
type: "message.appended",
data: {
- messageDelta: "Background research finished.",
+ messageDelta: "Research finished.",
sequence: 1,
stepIndex: 1,
turnId: "wake-turn",
@@ -1051,7 +1050,7 @@ describe("EveTUIRunner idle session follow", () => {
type: "message.completed",
data: {
finishReason: "stop",
- message: "Background research finished.",
+ message: "Research finished.",
sequence: 1,
stepIndex: 1,
turnId: "wake-turn",
@@ -1116,7 +1115,7 @@ describe("EveTUIRunner idle session follow", () => {
expect(send).toHaveBeenCalledOnce();
expect(idleEvents.filter((event) => event.type === "assistant-delta")).toEqual([
{
- delta: "Background research finished.",
+ delta: "Research finished.",
id: "text:wake-turn:1",
type: "assistant-delta",
},
@@ -1133,7 +1132,7 @@ describe("EveTUIRunner idle session follow", () => {
it("reconnects idle following when a transport stream ends before an approval arrives", async () => {
const session = stubSession();
const prompt = createDeferred<string | undefined>();
- const requestId = "task_123:approval-after-reconnect";
+ const requestId = "approval-after-reconnect";
const firstWakeEvents = [
stampTestEvent({
type: "message.appended",
@@ -1230,10 +1229,10 @@ describe("EveTUIRunner idle session follow", () => {
);
});
- it("answers a background-task approval that arrives while the prompt is idle", async () => {
+ it("answers an approval that arrives while the prompt is idle", async () => {
const session = stubSession();
const prompt = createDeferred<string | undefined>();
- const requestId = "task_123:approval-1";
+ const requestId = "approval-1";
const wakeEvents = [
stampTestEvent({
type: "input.requested",
@@ -3618,7 +3617,6 @@ describe("EveTUIRunner renderer teardown", () => {
}),
subagents: {
begin: vi.fn(),
- background: vi.fn(),
upsertStep: vi.fn(),
upsertTool: vi.fn(),
removeTool: vi.fn(),
@@ -3660,122 +3658,6 @@ describe("EveTUIRunner renderer teardown", () => {
expect(completeSubagent).toHaveBeenCalledWith({ authoritative: true, callId: "call-child" });
});
- it("keeps a subagent section open when action.result returns a working receipt", async () => {
- const backgroundSubagent = vi.fn();
- const completeSubagent = vi.fn();
- const runner = new EveTUIRunner({
- name: "Weather Agent",
- renderer: fakeRenderer({
- readPrompt: vi.fn().mockResolvedValueOnce("delegate").mockResolvedValueOnce(undefined),
- renderStream: vi.fn(async (result) => {
- for await (const event of result.events as AsyncIterable<unknown>) void event;
- }),
- subagents: {
- begin: vi.fn(),
- background: backgroundSubagent,
- upsertStep: vi.fn(),
- upsertTool: vi.fn(),
- removeTool: vi.fn(),
- markChildToolCallId: vi.fn(),
- complete: completeSubagent,
- },
- }),
- session: sessionYielding([
- {
- type: "subagent.called",
- data: {
- callId: "call-child",
- childSessionId: "child-session",
- childStreamPath: "/eve/v1/session/child-session/stream",
- name: "researcher",
- sequence: 0,
- sessionId: "parent-session",
- toolName: "researcher",
- turnId: "turn-parent",
- workflowId: "workflow-parent",
- },
- },
- {
- type: "action.result",
- data: {
- status: "completed",
- sequence: 1,
- stepIndex: 0,
- turnId: "turn-parent",
- result: {
- kind: "tool-result",
- callId: "call-child",
- output: { agentId: "agent-1", status: "working", taskId: "task_123" },
- toolName: "researcher",
- },
- },
- },
- { type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },
- { type: "session.waiting", data: { wait: "next-user-message" } },
- ]),
- });
-
- await runner.run();
-
- expect(backgroundSubagent).toHaveBeenCalledWith({ callId: "call-child" });
- expect(completeSubagent).not.toHaveBeenCalled();
- });
-
- it("does not settle a subagent section when completed carries a background receipt", async () => {
- const backgroundSubagent = vi.fn();
- const completeSubagent = vi.fn();
- const runner = new EveTUIRunner({
- name: "Weather Agent",
- renderer: fakeRenderer({
- readPrompt: vi.fn().mockResolvedValueOnce("delegate").mockResolvedValueOnce(undefined),
- renderStream: vi.fn(async (result) => {
- for await (const event of result.events as AsyncIterable<unknown>) void event;
- }),
- subagents: {
- begin: vi.fn(),
- background: backgroundSubagent,
- upsertStep: vi.fn(),
- upsertTool: vi.fn(),
- removeTool: vi.fn(),
- markChildToolCallId: vi.fn(),
- complete: completeSubagent,
- },
- }),
- session: sessionYielding([
- {
- type: "subagent.called",
- data: {
- callId: "call-child",
- childSessionId: "child-session",
- childStreamPath: "/eve/v1/session/child-session/stream",
- name: "researcher",
- sequence: 0,
- sessionId: "parent-session",
- toolName: "researcher",
- turnId: "turn-parent",
- workflowId: "workflow-parent",
- },
- },
- {
- type: "subagent.completed",
- data: {
- backgroundTask: { status: "working", taskId: "task_123" },
- callId: "call-child",
- output: '{"status":"working","taskId":"task_123"}',
- subagentName: "researcher",
- },
- },
- { type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },
- { type: "session.waiting", data: { wait: "next-user-message" } },
- ]),
- });
-
- await runner.run();
-
- expect(backgroundSubagent).toHaveBeenCalledWith({ callId: "call-child" });
- expect(completeSubagent).not.toHaveBeenCalled();
- });
-
it("aborts child-session streams when Ctrl-C exits the runner", async () => {
const client = stubClient();
let childSignal: AbortSignal | undefined;
@@ -4892,7 +4774,6 @@ describe("EveTUIRunner cancelled-turn subagent settling", () => {
]);
const view = {
begin: vi.fn(),
- background: vi.fn(),
upsertStep: vi.fn(),
upsertTool: vi.fn(),
removeTool: vi.fn(),
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index c72f3be6f..f7d53e84d 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -1,4 +1,3 @@
-import { isJsonObjectValue } from "#shared/json.js";
import type { ModelAccessChange } from "#shared/model-connection.js";
import { SteeringStream } from "#cli/dev/tui/steering-stream.js";
import {
@@ -188,7 +187,7 @@ export type AgentTUIStreamEvent =
export type AgentTUITurnState = {
aborted?: boolean;
- boundaryEvent?: "session.completed" | "session.failed" | "session.waiting";
+ boundaryEvent?: "session.completed" | "session.failed" | "session.waiting" | "turn.waiting";
pendingApprovals: AgentTUIToolApprovalRequest[];
pendingQuestions: InputRequest[];
sawSessionFailure: boolean;
@@ -1129,7 +1128,7 @@ export class EveTUIRunner {
// Every pending question was skipped without an answer. Fall
// back to the prompt rather than sending an empty response set:
// the questions stay open, and the server decides whether the
- // user's next message answers, dismisses, or leaves them.
+ // user's next message answers them or steers the turn.
break;
}
@@ -1627,9 +1626,7 @@ export class EveTUIRunner {
pendingInputRequests: this.#pendingInputRequests,
turnState,
onSubagentCalled: (called) => this.#subagentPump.begin(called),
- onSubagentBackgrounded: (callId) => this.#subagentPump.background(callId),
onSubagentCompleted: (callId) => this.#subagentPump.settle(callId),
- // Cancellation is turn-scoped; background descendants survive.
onTurnCancelled: (turnId) => this.#subagentPump.settleCancelledTurn(turnId),
onConnectionAuthRequired: (event) => this.#handleConnectionAuthRequired(event),
onConnectionAuthCompleted: (event) => this.#handleConnectionAuthCompleted(event),
@@ -2108,7 +2105,6 @@ type EveStreamTranslatorInput = {
pendingInputRequests: Map<string, InputRequest>;
turnState: AgentTUITurnState;
onSubagentCalled?: (event: SubagentCalledStreamEvent) => void;
- onSubagentBackgrounded?: (callId: string) => void;
onSubagentCompleted?: (callId: string) => void;
onTurnCancelled?: (turnId: string) => void;
onConnectionAuthRequired?: (event: AuthorizationRequiredStreamEvent) => void;
@@ -2155,7 +2151,6 @@ async function* eveEventsToTUIStream(
pendingInputRequests,
turnState,
onSubagentCalled,
- onSubagentBackgrounded,
onSubagentCompleted,
onTurnCancelled,
onConnectionAuthRequired,
@@ -2253,7 +2248,6 @@ async function* eveEventsToTUIStream(
const message = event.data.message;
if (state.completed) {
- if (message === null) break;
if (stepEpoch <= state.completedEpoch) break;
// Channels that skip per-delta events: a new full message under a
// reused key after a fresh model call.
@@ -2269,32 +2263,26 @@ async function* eveEventsToTUIStream(
}
const id = partGenerationId(base, state.generation);
- if (message !== null) {
- if (state.text.length === 0) {
- state.text = message;
- state.completed = true;
- state.completedEpoch = stepEpoch;
- yield { type: "assistant-complete", id, text: message };
- } else if (message.startsWith(state.text)) {
- const suffix = message.slice(state.text.length);
- if (suffix.length > 0) {
- if (suffix) input.onAssistantResponse?.();
- yield { type: "assistant-delta", id, delta: suffix };
- }
- state.text = message;
- state.completed = true;
- state.completedEpoch = stepEpoch;
- yield { type: "assistant-complete", id };
- } else {
- state.text = message;
- state.completed = true;
- state.completedEpoch = stepEpoch;
- yield { type: "assistant-complete", id, text: message };
+ if (state.text.length === 0) {
+ state.text = message;
+ state.completed = true;
+ state.completedEpoch = stepEpoch;
+ yield { type: "assistant-complete", id, text: message };
+ } else if (message.startsWith(state.text)) {
+ const suffix = message.slice(state.text.length);
+ if (suffix.length > 0) {
+ if (suffix) input.onAssistantResponse?.();
+ yield { type: "assistant-delta", id, delta: suffix };
}
- } else if (state.text.length > 0) {
+ state.text = message;
state.completed = true;
state.completedEpoch = stepEpoch;
yield { type: "assistant-complete", id };
+ } else {
+ state.text = message;
+ state.completed = true;
+ state.completedEpoch = stepEpoch;
+ yield { type: "assistant-complete", id, text: message };
}
break;
}
@@ -2444,17 +2432,6 @@ async function* eveEventsToTUIStream(
case "action.result": {
const resultEvent = event as ActionResultStreamEvent;
- const result = resultEvent.data.result;
- const output = "output" in result ? result.output : undefined;
- if (
- resultEvent.data.status === "completed" &&
- isJsonObjectValue(output) &&
- output.status === "working" &&
- typeof output.taskId === "string" &&
- typeof output.agentId === "string"
- ) {
- onSubagentBackgrounded?.(result.callId);
- }
if (resultEvent.data.result.kind !== "tool-result") {
break;
}
@@ -2532,6 +2509,22 @@ async function* eveEventsToTUIStream(
sentFinish = true;
return;
+ case "turn.waiting":
+ // The turn stays open; it ends this stream only when a call it runs
+ // asked something the person must answer first.
+ if (turnState.pendingApprovals.length === 0 && turnState.pendingQuestions.length === 0) {
+ break;
+ }
+ turnState.boundaryEvent = event.type;
+ yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
+ yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
+ yield {
+ type: "finish",
+ usage: latestStepUsage,
+ };
+ sentFinish = true;
+ return;
+
case "turn.completed":
visibleTurnCompleted = true;
yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
@@ -2564,11 +2557,7 @@ async function* eveEventsToTUIStream(
case "subagent.completed": {
const completed = event as SubagentCompletedStreamEvent;
- if (completed.data.backgroundTask === undefined) {
- onSubagentCompleted?.(completed.data.callId);
- } else {
- onSubagentBackgrounded?.(completed.data.callId);
- }
+ onSubagentCompleted?.(completed.data.callId);
break;
}
diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts
index 2b0e59875..d9db51544 100644
--- a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts
+++ b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts
@@ -19,7 +19,6 @@ afterEach(() => {
function fakeView(): SubagentView {
return {
begin: vi.fn(),
- background: vi.fn(),
upsertStep: vi.fn(),
upsertTool: vi.fn(),
removeTool: vi.fn(),
@@ -179,14 +178,12 @@ function completedEvent(index: number): MessageStreamEvent {
}
describe("SubagentPump.settleCancelledTurn", () => {
- it("cancels only foreground descendants of the exact turn", async () => {
- const backgroundA = pushableChildStream();
- const backgroundB = pushableChildStream();
- const foregroundB = pushableChildStream();
+ it("cancels only descendants of the exact turn", async () => {
+ const childA = pushableChildStream();
+ const childB = pushableChildStream();
const streams = new Map([
- ["/eve/v1/children/background-a/stream", backgroundA],
- ["/eve/v1/children/background-b/stream", backgroundB],
- ["/eve/v1/children/foreground-b/stream", foregroundB],
+ ["/eve/v1/children/child-a/stream", childA],
+ ["/eve/v1/children/child-b/stream", childB],
]);
const requests = serveChildStreams(({ path, signal }) => {
const child = streams.get(path);
@@ -195,23 +192,19 @@ describe("SubagentPump.settleCancelledTurn", () => {
});
const { pump, view } = createPump();
- pump.begin(subagentCalled("background-a", "turn-a"));
- pump.background("background-a");
- pump.begin(subagentCalled("background-b", "turn-b"));
- pump.background("background-b");
- pump.begin(subagentCalled("foreground-b", "turn-b"));
- await vi.waitFor(() => expect(requests).toHaveLength(3));
+ pump.begin(subagentCalled("child-a", "turn-a"));
+ pump.begin(subagentCalled("child-b", "turn-b"));
+ await vi.waitFor(() => expect(requests).toHaveLength(2));
pump.settleCancelledTurn("turn-b");
expect(view.complete).toHaveBeenCalledTimes(1);
expect(view.complete).toHaveBeenCalledWith({
authoritative: true,
- callId: "foreground-b",
+ callId: "child-b",
});
- expect(foregroundB.aborted).toBe(true);
- expect(backgroundA.aborted).toBe(false);
- expect(backgroundB.aborted).toBe(false);
+ expect(childB.aborted).toBe(true);
+ expect(childA.aborted).toBe(false);
pump.abortAll();
});
@@ -249,52 +242,7 @@ describe("SubagentPump.settleCancelledTurn", () => {
});
});
-describe("SubagentPump background receipts", () => {
- it("retains a receipt that arrives before child dispatch", () => {
- const view = fakeView();
- const pump = new SubagentPump({ view, formatActionResultError: () => "failed" });
- pump.background("call-1");
- pump.begin(subagentCalled("call-1"));
- pump.settleCancelledTurn("turn-1");
- expect(view.background).toHaveBeenCalledWith({ callId: "call-1" });
- expect(view.complete).not.toHaveBeenCalled();
- });
-
- it("keeps the section open until the child stream reaches its own boundary", async () => {
- const child = pushableChildStream();
- const requests = serveChildStreams(({ signal }) => child.response(signal));
- const { pump, view } = createPump();
-
- pump.begin(subagentCalled("call-1"));
- pump.background("call-1");
-
- expect(view.background).toHaveBeenCalledWith({ callId: "call-1" });
- expect(view.complete).not.toHaveBeenCalled();
-
- await vi.waitFor(() => expect(requests).toHaveLength(1));
- child.push(reasoningEvent("still working", 0));
- child.push(boundaryEvent(1));
- await vi.waitFor(() =>
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),
- );
-
- expect(view.upsertStep).toHaveBeenCalledWith(
- expect.objectContaining({ callId: "call-1", reasoning: "still working" }),
- );
- });
-
- it("treats a child failure boundary as authoritative completion", async () => {
- serveChildStreams(durableChild([failedBoundaryEvent(0)]));
- const { pump, view } = createPump();
-
- pump.begin(subagentCalled("call-1"));
- pump.background("call-1");
-
- await vi.waitFor(() =>
- expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),
- );
- });
-
+describe("SubagentPump completion", () => {
it("reopens after parent completion and upgrades at the child boundary", async () => {
const child = pushableChildStream();
const requests = serveChildStreams(({ signal }) => child.response(signal));
diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.ts
index 79a97c6c5..f908d0260 100644
--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts
+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts
@@ -35,8 +35,6 @@ const childStreamReconnectPolicy = {
export interface SubagentView {
/** Opens a call's section the moment its dispatch is announced. */
begin(update: { callId: string; name: string }): void;
- /** Keeps a receipt-returned background call mutable across parent turns. */
- background(update: { callId: string }): void;
upsertStep(update: SubagentStepUpdate): void;
upsertTool(update: SubagentToolUpdate): void;
/** Drops a child tool row whose call never materialized. */
@@ -74,8 +72,6 @@ export type SubagentRun = {
childSessionId: string;
/** Parent turn that originated this dispatch; cancellation is scoped to it. */
parentTurnId: string;
- /** A receipt-returned task survives cancellation of its originating turn. */
- background: boolean;
/** Parent completion is provisional; only a child boundary is authoritative. */
status: "open" | "provisional" | "authoritative";
/** Dispatch event whose parent-origin child stream this run follows. */
@@ -135,8 +131,6 @@ export class SubagentPump {
| ((subagentName: string, toolName: string, output: unknown) => Promise<void>)
| undefined;
readonly #runs = new Map<string, SubagentRun>();
- // Task admission can return its receipt before the child dispatch event arrives.
- readonly #pendingBackgroundCalls = new Set<string>();
readonly #pumps = new Map<string, AbortController>();
/** Durable child cursor shared by repeated calls into one conversation subagent. */
readonly #childStreamIndices = new Map<string, number>();
@@ -168,7 +162,6 @@ export class SubagentPump {
name: called.data.name,
childSessionId: called.data.childSessionId,
parentTurnId: called.data.turnId,
- background: false,
status: "open",
called,
steps: new Map(),
@@ -182,7 +175,6 @@ export class SubagentPump {
this.#view?.markChildToolCallId(callId);
if (existing !== undefined && existing.status !== "open") return;
this.#view?.begin({ callId, name: called.data.name });
- if (this.#pendingBackgroundCalls.delete(callId)) this.background(callId);
if (existing !== undefined) return;
this.#activateOrQueue(callId);
}
@@ -196,41 +188,21 @@ export class SubagentPump {
this.#finalizeRun(callId, false);
}
- /**
- * The originating call returned a task receipt, not the child's result.
- * Keep the section open until the child stream reaches its own boundary.
- * A child that already settled before the receipt raced in stays settled.
- */
- background(callId: string): void {
- const run = this.#runs.get(callId);
- if (run === undefined) {
- this.#pendingBackgroundCalls.add(callId);
- return;
- }
- run.background = true;
- if (run.status === "authoritative") return;
- this.#view?.background({ callId });
- }
-
abortAll(): void {
for (const controller of this.#pumps.values()) {
controller.abort();
}
this.#pumps.clear();
this.#runs.clear();
- this.#pendingBackgroundCalls.clear();
this.#childStreamIndices.clear();
this.#activeChildCalls.clear();
this.#queuedChildCalls.clear();
}
- /**
- * Settles and aborts only foreground descendants of the cancelled parent
- * turn. Background tasks survive even when that same turn started them.
- */
+ /** Settles and aborts the descendants of the cancelled parent turn. */
settleCancelledTurn(turnId: string): void {
for (const [callId, run] of this.#runs) {
- if (run.parentTurnId !== turnId || run.background) continue;
+ if (run.parentTurnId !== turnId) continue;
this.#finalizeRun(callId, true);
this.#pumps.get(callId)?.abort();
this.#pumps.delete(callId);
@@ -484,7 +456,7 @@ export class SubagentPump {
}
case "message.completed": {
const { key, step } = openCurrentSubagentSection(run);
- if (event.data.message !== null && step.message.length === 0) {
+ if (step.message.length === 0) {
// Some channels emit only `message.completed` without per-delta
// `message.appended` events. Capture the full text in that case.
step.message = event.data.message;
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
index d8dea6eaf..b8d2db44b 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -993,8 +993,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
it("settles an authorization block when its callback arrives in a later stream pass", async () => {
const { screen, renderer } = makeRenderer();
renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.beginSubagent({ callId: "background", name: "researcher" });
- renderer.backgroundSubagent({ callId: "background" });
+ renderer.beginSubagent({ callId: "research", name: "researcher" });
renderer.upsertConnectionAuth({
name: "linear",
description: "Authorization required for linear",
@@ -1158,54 +1157,6 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
- it("keeps late background child output inside its section across parent turns", async () => {
- const { screen, renderer } = makeRenderer();
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.beginSubagent({ callId: "s1", name: "researcher" });
- renderer.backgroundSubagent({ callId: "s1" });
-
- await renderer.renderStream(
- streamOf([
- { type: "assistant-delta", id: "parent-1", delta: "Research task started." },
- { type: "assistant-complete", id: "parent-1" },
- { type: "finish" },
- ]),
- { continueSession: true },
- );
- await renderer.renderStream(
- streamOf([
- { type: "assistant-delta", id: "parent-2", delta: "It is still running." },
- { type: "assistant-complete", id: "parent-2" },
- { type: "finish" },
- ]),
- { continueSession: true, submittedPrompt: "cool" },
- );
-
- // The child emits after both parent turns. It still inserts beside its
- // call's header, not at the current transcript edge beneath parent-2.
- renderer.upsertSubagentTool({
- callId: "s1",
- subagentName: "researcher",
- childCallId: "dig-1",
- toolName: "dig",
- input: { phase: "sources" },
- status: "executing",
- });
-
- const snapshot = screen.snapshot();
- const header = snapshot.indexOf("※ subagent(researcher)");
- const child = snapshot.indexOf("dig");
- const firstParent = snapshot.indexOf("Research task started.");
- const user = snapshot.indexOf("cool");
- const secondParent = snapshot.indexOf("It is still running.");
- expect(firstParent).toBeGreaterThan(-1);
- expect(user).toBeGreaterThan(firstParent);
- expect(secondParent).toBeGreaterThan(user);
- expect(header).toBeGreaterThan(secondParent);
- expect(child).toBeGreaterThan(header);
- renderer.shutdown();
- });
-
it("swaps a dispatch's preparing placeholder for the section header", async () => {
const { screen, renderer } = makeRenderer();
renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
@@ -1316,193 +1267,6 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
- it("commits an authoritative background completion out of the live prompt region", async () => {
- const { screen, input, renderer } = makeRenderer();
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.beginSubagent({ callId: "s1", name: "researcher" });
- renderer.backgroundSubagent({ callId: "s1" });
- renderer.upsertSubagentTool({
- callId: "s1",
- subagentName: "researcher",
- childCallId: "dig-1",
- toolName: "dig",
- input: { phase: "sources" },
- status: "done",
- output: { ok: true },
- });
-
- renderer.completeSubagent({ authoritative: true, callId: "s1" });
- const outputAfterCommit = screen.rawOutput().length;
- const prompt = renderer.readPrompt();
- input.type("next message");
-
- // Prompt repaint must not redraw the completed subagent cohort: it has
- // moved to immutable scrollback and no longer occupies the live region.
- expect(screen.rawOutput().slice(outputAfterCommit)).not.toContain("subagent(researcher)");
- input.enter();
- expect(await prompt).toBe("next message");
- renderer.shutdown();
- });
-
- it("keeps the activity ticker running while a background subagent remains live", async () => {
- vi.useFakeTimers();
- try {
- const { screen, renderer } = makeRenderer();
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.beginSubagent({ callId: "background", name: "researcher" });
- renderer.backgroundSubagent({ callId: "background" });
- renderer.upsertSubagentTool({
- callId: "background",
- subagentName: "researcher",
- childCallId: "child-hold",
- toolName: "hold",
- input: { durationMs: 45_000 },
- status: "executing",
- });
-
- await renderer.renderStream(streamOf([{ type: "finish" }]), {
- continueSession: true,
- submittedPrompt: "start background work",
- });
- const outputBeforeTick = screen.rawOutput().length;
- await vi.advanceTimersByTimeAsync(90);
- expect(screen.rawOutput().length).toBeGreaterThan(outputBeforeTick);
-
- renderer.completeSubagent({ authoritative: true, callId: "background" });
- const outputAfterCompletion = screen.rawOutput().length;
- await vi.advanceTimersByTimeAsync(180);
- expect(screen.rawOutput()).toHaveLength(outputAfterCompletion);
- renderer.shutdown();
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("keeps the ticker running when one of two background subagents completes", async () => {
- vi.useFakeTimers();
- try {
- const { screen, renderer } = makeRenderer();
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- const startBackground = (callId: string) => {
- renderer.beginSubagent({ callId, name: "hang-worker" });
- renderer.backgroundSubagent({ callId });
- renderer.upsertSubagentTool({
- callId,
- subagentName: "hang-worker",
- childCallId: `${callId}-hold`,
- toolName: "hold",
- input: { durationMs: 45_000 },
- status: "executing",
- });
- };
-
- startBackground("first");
- await renderer.renderStream(streamOf([{ type: "finish" }]), {
- continueSession: true,
- submittedPrompt: "start first background worker",
- });
- await renderer.renderStream(
- streamOf([
- { type: "assistant-complete", id: "a", text: "Mock reply: a" },
- { type: "finish" },
- ]),
- { continueSession: true, submittedPrompt: "a" },
- );
- startBackground("second");
- await renderer.renderStream(streamOf([{ type: "finish" }]), {
- continueSession: true,
- submittedPrompt: "start second background worker",
- });
-
- renderer.completeSubagent({ authoritative: true, callId: "first" });
- const outputBeforeTick = screen.rawOutput().length;
- await vi.advanceTimersByTimeAsync(90);
- expect(screen.rawOutput().length).toBeGreaterThan(outputBeforeTick);
-
- renderer.completeSubagent({ authoritative: true, callId: "second" });
- const outputAfterCompletion = screen.rawOutput().length;
- await vi.advanceTimersByTimeAsync(180);
- expect(screen.rawOutput()).toHaveLength(outputAfterCompletion);
- renderer.shutdown();
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("stops background activity ticking when a session boundary abandons its child", async () => {
- vi.useFakeTimers();
- try {
- const { screen, renderer } = makeRenderer();
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.beginSubagent({ callId: "background", name: "researcher" });
- renderer.backgroundSubagent({ callId: "background" });
- renderer.upsertSubagentTool({
- callId: "background",
- subagentName: "researcher",
- childCallId: "child-hold",
- toolName: "hold",
- input: { durationMs: 45_000 },
- status: "executing",
- });
-
- renderer.renderSessionBoundary();
- const outputAfterBoundary = screen.rawOutput().length;
- await vi.advanceTimersByTimeAsync(180);
- expect(screen.rawOutput()).toHaveLength(outputAfterBoundary);
- renderer.shutdown();
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("commits completed foreground turns ahead of a live background subagent", async () => {
- const { screen, renderer } = makeRenderer(48, 8);
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.beginSubagent({ callId: "background", name: "researcher" });
- // These settled blocks arrive before the parent reports that the child
- // is background work. Reclassifying the child must release them from its
- // formerly leading live cohort.
- renderer.renderNotice("EARLY_SETTLED_FOREGROUND_ONE");
- renderer.renderNotice("EARLY_SETTLED_FOREGROUND_TWO");
- renderer.backgroundSubagent({ callId: "background" });
- renderer.upsertSubagentStep({
- callId: "background",
- subagentName: "researcher",
- sectionKey: 0,
- reasoning: "",
- message: "still researching background details",
- finalized: false,
- });
-
- await renderer.renderStream(
- streamOf([
- { type: "assistant-complete", id: "answer-1", text: "FIRST_COMPLETED_ANSWER" },
- { type: "finish" },
- ]),
- { continueSession: true, submittedPrompt: "FIRST_COMPLETED_PROMPT" },
- );
- await renderer.renderStream(
- streamOf([
- { type: "assistant-complete", id: "answer-2", text: "SECOND_COMPLETED_ANSWER" },
- { type: "finish" },
- ]),
- { continueSession: true, submittedPrompt: "SECOND_COMPLETED_PROMPT" },
- );
-
- const transcript = screen.snapshot();
- expect(transcript).toContain("EARLY_SETTLED_FOREGROUND_ONE");
- expect(transcript).toContain("EARLY_SETTLED_FOREGROUND_TWO");
- expect(transcript).toContain("FIRST_COMPLETED_PROMPT");
- expect(transcript).toContain("FIRST_COMPLETED_ANSWER");
- expect(transcript).toContain("SECOND_COMPLETED_PROMPT");
- expect(transcript).toContain("SECOND_COMPLETED_ANSWER");
- expect(transcript).toContain("still researching background details");
-
- renderer.completeSubagent({ authoritative: true, callId: "background" });
- expect(screen.snapshot()).not.toContain("hidden while streaming");
- renderer.shutdown();
- });
-
it("keeps parent completion provisional until delayed child output reaches its boundary", async () => {
const { screen, input, renderer } = makeRenderer();
renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
@@ -1541,46 +1305,6 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
- it.each(["active", "idle"] as const)(
- "settles only the %s cancelled turn's top-level tools",
- async (mode) => {
- const { screen, renderer } = makeRenderer();
- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
- renderer.beginSubagent({ callId: "background", name: "researcher" });
- renderer.backgroundSubagent({ callId: "background" });
- renderer.upsertSubagentTool({
- callId: "background",
- subagentName: "researcher",
- childCallId: "child-bash",
- toolName: "bash",
- input: { command: "background-child" },
- status: "executing",
- });
- const result = streamOf([
- {
- type: "tool-call",
- toolCallId: "current-bash",
- toolName: "bash",
- input: { command: "idle-current" },
- },
- { type: "turn-cancelled" },
- { type: "finish" },
- ]);
-
- if (mode === "active") {
- await renderer.renderStream(result, { continueSession: true });
- } else {
- await renderer.renderIdleStream(result, { continueSession: true });
- }
-
- const snapshot = screen.snapshot();
- expect(snapshot).toContain("background-child");
- expect(snapshot).toContain("idle-current");
- expect(countOccurrences(snapshot, "interrupted")).toBe(1);
- renderer.shutdown();
- },
- );
-
it("renders parallel calls to the same subagent as ordinal-numbered sections", async () => {
const { screen, renderer } = makeRenderer();
renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
@@ -1721,17 +1445,6 @@ describe("TerminalRenderer (inline scrollback)", () => {
await renderer.renderIdleStream(
streamOf([
- {
- type: "tool-call",
- input: { taskIds: ["task_123"] },
- toolCallId: "cancel-1",
- toolName: "task_cancel",
- },
- {
- type: "tool-result",
- output: { tasks: [{ status: "cancelled", taskId: "task_123" }] },
- toolCallId: "cancel-1",
- },
{ type: "assistant-delta", id: "wake-1", delta: "Research finished." },
{ type: "assistant-complete", id: "wake-1" },
{ type: "finish" },
@@ -4658,8 +4371,7 @@ describe("TerminalRenderer setup flow session", () => {
try {
const { screen, renderer } = makeRenderer();
renderer.setupFlow.begin("Add integration");
- renderer.beginSubagent({ callId: "background", name: "researcher" });
- renderer.backgroundSubagent({ callId: "background" });
+ renderer.beginSubagent({ callId: "research", name: "researcher" });
let release!: () => void;
const inherited = renderer.setupFlow.withInheritedStdio(
() => new Promise<void>((resolve) => (release = resolve)),
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index dda18b58b..570401058 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -433,8 +433,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
#updateSequence = 0;
/** Call ids per subagent name, for the sections' ordinal subtitles. */
readonly #subagentCallsByName = new Map<string, string[]>();
- /** Background sections kept at the live edge until their child boundary. */
- readonly #backgroundSubagentCallIds = new Set<string>();
/** Parent-completed sections retained as mutable until the child boundary. */
readonly #provisionalSubagentCallIds = new Set<string>();
/** Session-local file contents, so write blocks can render real diffs. */
@@ -867,7 +865,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
async readPrompt(options?: AgentTUISessionOptions): Promise<string> {
this.#start(options);
- this.#syncBackgroundActivityTicker();
+ this.#syncProvisionalSubagentTicker();
this.#commitTurnStats();
this.#inputActive = true;
this.#promptPlaceholderActive = true;
@@ -1209,7 +1207,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (this.#turnIndicator.kind === "waiting") {
this.#turnIndicator = { kind: "idle" };
}
- this.#syncBackgroundActivityTicker();
+ this.#syncProvisionalSubagentTicker();
this.#status = completedTurnStatus({
interrupted: this.#interrupted,
cancelled: this.#turnCancelled,
@@ -1223,7 +1221,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
// prefix wedged and freeze scrollback for the rest of the session.
if (this.#interrupted || turnState.cancelled) this.#settleCurrentTurnToolBlocks(turnState);
this.#finalizeAllBlocks();
- this.#syncBackgroundActivityTicker();
+ this.#syncProvisionalSubagentTicker();
this.#diagnostics?.reportStats();
this.#paint();
@@ -1275,7 +1273,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#sweepPreparingToolBlocks(turnState);
if (turnState.cancelled) this.#settleCurrentTurnToolBlocks(turnState);
this.#finalizeAllBlocks();
- this.#syncBackgroundActivityTicker();
+ this.#syncProvisionalSubagentTicker();
this.#diagnostics?.reportStats();
this.#paint();
}
@@ -1779,7 +1777,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
*/
readonly subagents: SubagentView = {
begin: (update) => this.beginSubagent(update),
- background: (update) => this.backgroundSubagent(update),
upsertStep: (update) => this.upsertSubagentStep(update),
upsertTool: (update) => this.upsertSubagentTool(update),
removeTool: (update) => this.removeSubagentTool(update),
@@ -1806,24 +1803,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
}
- /**
- * A background receipt closes the model tool call, not the child. Mark the
- * header running so turn finalization cannot commit immutable scrollback
- * before the child pump has folded in its later events.
- */
- backgroundSubagent(update: { callId: string }): void {
- const header = this.#blockById.get(subagentHeaderId(update.callId));
- if (header === undefined || this.#committedIds.has(subagentHeaderId(update.callId))) return;
- header.status = "running";
- header.live = true;
- header.updateSeq = ++this.#updateSequence;
- const wasBackground = this.#backgroundSubagentCallIds.has(update.callId);
- this.#backgroundSubagentCallIds.add(update.callId);
- if (!wasBackground) this.#moveSubagentCohortToBackgroundTail(update.callId);
- this.#syncBackgroundActivityTicker();
- this.#paint();
- }
-
/**
* Marks a subagent call complete — its final message has arrived — so the
* section's closing corner reports `Done`. The header stays live until the
@@ -1834,7 +1813,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (header === undefined) return;
header.status = "done";
if (update.authoritative) {
- this.#backgroundSubagentCallIds.delete(update.callId);
this.#provisionalSubagentCallIds.delete(update.callId);
for (const block of this.#blocks) {
if (block.subagentCallId === update.callId) block.live = false;
@@ -1845,7 +1823,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (block.subagentCallId === update.callId) block.live = true;
}
}
- this.#syncBackgroundActivityTicker();
+ this.#syncProvisionalSubagentTicker();
this.#paint();
}
@@ -1973,14 +1951,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#childToolCallIds.clear();
this.#parentToolBlockIds.clear();
this.#subagentHeaders.clear();
- this.#backgroundSubagentCallIds.clear();
this.#provisionalSubagentCallIds.clear();
this.#subagentCallsByName.clear();
this.#messageQueue.reset();
this.#nextSubmittedPromptOrigin = undefined;
this.#fileContents.clear();
this.#turnClock.reset();
- this.#syncBackgroundActivityTicker();
+ this.#syncProvisionalSubagentTicker();
}
/**
@@ -3153,7 +3130,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#startTicker();
this.#armFlowIdleTrap();
} else {
- this.#syncBackgroundActivityTicker();
+ this.#syncProvisionalSubagentTicker();
}
this.#live.reset();
this.#paint();
@@ -3625,7 +3602,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
#stopTicker() {
- if (this.#hasLiveBackgroundActivity()) return;
+ if (this.#hasLiveProvisionalSubagents()) return;
this.#clearTicker();
}
@@ -3636,19 +3613,18 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
}
- #hasLiveBackgroundActivity(): boolean {
+ #hasLiveProvisionalSubagents(): boolean {
return this.#blocks.some(
(block) =>
block.live &&
block.subagentCallId !== undefined &&
- (this.#backgroundSubagentCallIds.has(block.subagentCallId) ||
- this.#provisionalSubagentCallIds.has(block.subagentCallId)),
+ this.#provisionalSubagentCallIds.has(block.subagentCallId),
);
}
/** Keeps mutable subagent sections visibly active after their parent turn settles. */
- #syncBackgroundActivityTicker(): void {
- if (this.#hasLiveBackgroundActivity()) {
+ #syncProvisionalSubagentTicker(): void {
+ if (this.#hasLiveProvisionalSubagents()) {
this.#startTicker();
} else if (!this.#streamDraftActive && this.#turnIndicator.kind === "idle") {
this.#clearTicker();
@@ -3667,18 +3643,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
#pushBlock(block: Block) {
if (block.id !== this.#devRebuild?.id) this.#settleDevRebuildStatus();
block.updateSeq = ++this.#updateSequence;
- const isBackgroundChild =
- block.subagentCallId !== undefined &&
- this.#backgroundSubagentCallIds.has(block.subagentCallId);
- const backgroundIndex = isBackgroundChild
- ? -1
- : this.#blocks.findIndex(
- (candidate) =>
- candidate.subagentCallId !== undefined &&
- this.#backgroundSubagentCallIds.has(candidate.subagentCallId),
- );
- if (backgroundIndex < 0) this.#blocks.push(block);
- else this.#blocks.splice(backgroundIndex, 0, block);
+ this.#blocks.push(block);
if (block.id) this.#blockById.set(block.id, block);
}
@@ -3812,9 +3777,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
/**
* Inserts a new child beside the rest of its call's cohort instead of at
- * the transcript's live edge. Background children can emit after parent
- * and user blocks from later turns; arrival order must not split their
- * section.
+ * the transcript's live edge. A child's final events can arrive after later
+ * parent blocks; arrival order must not split its section.
*/
#upsertSubagentBlock(block: Block) {
if (block.id && this.#committedIds.has(block.id)) return;
@@ -3845,18 +3809,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#blockById.delete(id);
}
- /**
- * Background children may outlive several foreground turns. Keep their
- * mutable cohort at the live edge so it cannot hold those settled turns in
- * the renderer's leading-prefix commit queue.
- */
- #moveSubagentCohortToBackgroundTail(callId: string): void {
- const cohort = this.#blocks.filter((block) => block.subagentCallId === callId);
- if (cohort.length === 0) return;
- this.#blocks = this.#blocks.filter((block) => block.subagentCallId !== callId);
- this.#blocks.push(...cohort);
- }
-
#finalizeAllBlocks() {
for (const block of this.#blocks) {
// Blocks awaiting an approval decision, action.result, or OAuth callback
@@ -4071,7 +4023,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
break;
}
- // Activity is independent of transcript visibility and idle/background streams.
+ // Activity is independent of transcript visibility and idle streams.
if (turnState === this.#activeTurnState && turnActivityLabel(turnState) !== previousActivity) {
this.#paint();
}
diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
index 0913dcaed..90c97cebc 100644
--- a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
+++ b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
@@ -161,7 +161,6 @@ describe("presentTool", () => {
grep: { pattern: "useEve" },
load_skill: { skill: "commit" },
read_file: { filePath: "/workspace/a.ts" },
- task_cancel: { taskIds: ["task_abc"] },
web_fetch: { url: "https://example.com" },
web_search: { query: "eve framework" },
write_file: { filePath: "/workspace/a.ts", content: "x" },
diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.ts b/packages/eve/src/cli/dev/tui/tool-presentation.ts
index ff00ef728..553de6f0f 100644
--- a/packages/eve/src/cli/dev/tui/tool-presentation.ts
+++ b/packages/eve/src/cli/dev/tui/tool-presentation.ts
@@ -123,14 +123,6 @@ const BUILTIN_TOOL_COPY: Readonly<Record<string, BuiltinToolCopy>> = {
singularNoun: "file",
pluralNoun: "files",
},
- task_cancel: {
- verb: "Cancel",
- pastVerb: "Cancelled",
- argKey: "taskIds",
- extractItem: taskIdsArg,
- singularNoun: "task",
- pluralNoun: "tasks",
- },
web_fetch: {
verb: "Fetch",
pastVerb: "Fetched",
@@ -345,16 +337,6 @@ function webSearchActionArg(input: unknown): string | undefined {
* renders verbatim in aggregated rows, so a model-controlled value must lose
* its terminal controls here, not at the render call sites.
*/
-/** Joins a `taskIds: string[]` argument into one salient line. */
-function taskIdsArg(input: unknown): string | undefined {
- if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;
- const value = (input as Record<string, unknown>).taskIds;
- if (!Array.isArray(value)) return undefined;
- const ids = value.filter((id): id is string => typeof id === "string");
- if (ids.length === 0) return undefined;
- return salientLine(ids.join(", "));
-}
-
function salientArg(input: unknown, key: string): string | undefined {
if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;
const value = (input as Record<string, unknown>)[key];
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
index 844d988de..8a32a83d9 100644
--- a/packages/eve/src/client/agent-info-schema.ts
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -252,8 +252,8 @@ const remoteAgent = entry
const kernelEffect = z
.object({
- action: z.enum(["subagent-call", "task-cancel", "workflow-tool-call"]).optional(),
- audience: z.array(z.enum(["root-session", "delegated-task-child"])),
+ action: z.enum(["subagent-call", "workflow-tool-call"]).optional(),
+ audience: z.array(z.literal("root-session")),
kind: z.enum(["dispatch", "provider-tool"]),
sourceId: z.string(),
})
diff --git a/packages/eve/src/client/eve-agent-store-helpers.ts b/packages/eve/src/client/eve-agent-store-helpers.ts
index 440c0dade..08c6dc9bb 100644
--- a/packages/eve/src/client/eve-agent-store-helpers.ts
+++ b/packages/eve/src/client/eve-agent-store-helpers.ts
@@ -1,25 +1,29 @@
-import { updatePendingAuthorizations } from "#client/session-utils.js";
+import {
+ isTurnSegmentBoundary,
+ updatePendingAuthorizations,
+ updatePendingInputRequests,
+} from "#client/session-utils.js";
import type { ActiveTurn } from "#client/eve-agent-store-state.js";
import type { MessageResponse } from "#client/message-response.js";
import type { CancelSessionResult, SendTurnPayload } from "#client/types.js";
-import { isCurrentTurnBoundaryEvent, type MessageStreamEvent } from "#protocol/message.js";
+import type { MessageStreamEvent } from "#protocol/message.js";
import type { UserContent } from "ai";
export function isSettledSessionTail(events: readonly MessageStreamEvent[]): boolean {
const tail = events.at(-1);
+ if (tail === undefined) return false;
+ const pendingAuthorizations = new Set<string>();
+ const pendingInputRequests = new Set<string>();
+ for (const event of events) {
+ updatePendingAuthorizations(pendingAuthorizations, event);
+ updatePendingInputRequests(pendingInputRequests, event);
+ }
return (
- tail !== undefined &&
- isCurrentTurnBoundaryEvent(tail) &&
- (tail.type !== "session.waiting" || collectPendingAuthorizations(events).size === 0)
+ isTurnSegmentBoundary(tail, pendingInputRequests) &&
+ (tail.type !== "session.waiting" || pendingAuthorizations.size === 0)
);
}
-function collectPendingAuthorizations(events: readonly MessageStreamEvent[]): Set<string> {
- const pending = new Set<string>();
- for (const event of events) updatePendingAuthorizations(pending, event);
- return pending;
-}
-
export function assertExclusiveTurnInput(input: SendTurnPayload): void {
const hasMessage = input.message !== undefined;
const hasResponses = input.inputResponses !== undefined;
@@ -103,11 +107,13 @@ export async function followSteeredTurns(
await Promise.allSettled(turn.followUpDispatches);
}
if (turn.receivedFollowUps >= turn.acceptedFollowUps) return;
+ const pendingInputRequests = new Set<string>();
for await (const event of events) {
if (!isActive()) return;
turn.receivedFollowUps += turn.receivedFollowUpEvents.get(event) ?? 0;
turn.receivedFollowUpEvents.delete(event);
- if (isCurrentTurnBoundaryEvent(event)) {
+ updatePendingInputRequests(pendingInputRequests, event);
+ if (isTurnSegmentBoundary(event, pendingInputRequests)) {
while (turn.followUpDispatches.size > 0) {
await Promise.allSettled(turn.followUpDispatches);
}
diff --git a/packages/eve/src/client/eve-agent-store.test.ts b/packages/eve/src/client/eve-agent-store.test.ts
index 8cf182e72..ec2acd609 100644
--- a/packages/eve/src/client/eve-agent-store.test.ts
+++ b/packages/eve/src/client/eve-agent-store.test.ts
@@ -596,7 +596,7 @@ describe("EveAgentStore prewarming", () => {
expect(store.snapshot.session?.streamIndex).toBe(6);
});
- it("keeps following background completion after a refused approval returns to waiting", async () => {
+ it("keeps following an unsolicited turn after a refused approval returns to waiting", async () => {
const live = controlledStreamResponse();
const fetchMock = vi
.spyOn(globalThis, "fetch")
@@ -653,11 +653,11 @@ describe("EveAgentStore prewarming", () => {
]),
);
- const background = stampTestEvents([
+ const unsolicited = stampTestEvents([
createTurnStartedEvent({ sequence: 1, turnId: "turn-report" }),
createMessageCompletedEvent({
finishReason: "stop",
- message: "Bob's background report is complete.",
+ message: "Bob's report is complete.",
sequence: 1,
stepIndex: 0,
turnId: "turn-report",
@@ -665,18 +665,18 @@ describe("EveAgentStore prewarming", () => {
createSessionWaitingEvent(),
]).map((event) => ({
...event,
- meta: { ...event.meta, id: `background-${event.meta.id}`, deliveryIds: ["report-delivery"] },
+ meta: { ...event.meta, id: `unsolicited-${event.meta.id}`, deliveryIds: ["report-delivery"] },
}));
- live.emit(background[0]!);
+ live.emit(unsolicited[0]!);
await vi.waitFor(() => expect(store.snapshot.status).toBe("streaming"));
- for (const event of background.slice(1)) live.emit(event);
+ for (const event of unsolicited.slice(1)) live.emit(event);
await vi.waitFor(() =>
- expect(store.snapshot.events).toEqual([...initialEvents, ...refusal, ...background]),
+ expect(store.snapshot.events).toEqual([...initialEvents, ...refusal, ...unsolicited]),
);
expect(store.snapshot.status).toBe("ready");
expect(store.snapshot.data.messages.flatMap((message) => message.parts)).toEqual(
expect.arrayContaining([
- expect.objectContaining({ type: "text", text: "Bob's background report is complete." }),
+ expect.objectContaining({ type: "text", text: "Bob's report is complete." }),
]),
);
expect(onEvent).toHaveBeenCalledTimes(5);
@@ -684,7 +684,7 @@ describe("EveAgentStore prewarming", () => {
expect(fetchMock.mock.calls[0]![1]?.signal?.aborted).toBe(false);
});
- it("projects a background turn that arrives while another message is being accepted", async () => {
+ it("projects an unsolicited turn that arrives while another message is being accepted", async () => {
const live = controlledStreamResponse();
const accepted = Promise.withResolvers<Response>();
const fetchMock = vi
@@ -698,21 +698,21 @@ describe("EveAgentStore prewarming", () => {
const sending = store.send({ message: "Next question" });
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
- const background = stampTestEvents([
- createTurnStartedEvent({ sequence: 0, turnId: "turn_background" }),
+ const unsolicited = stampTestEvents([
+ createTurnStartedEvent({ sequence: 0, turnId: "turn_scheduled" }),
createMessageCompletedEvent({
finishReason: "stop",
- message: "Background result",
+ message: "Scheduled result",
sequence: 1,
stepIndex: 0,
- turnId: "turn_background",
+ turnId: "turn_scheduled",
}),
createSessionWaitingEvent(),
]).map((event) => ({
...event,
- meta: { ...event.meta, deliveryIds: ["background-delivery"] },
+ meta: { ...event.meta, deliveryIds: ["scheduled-delivery"] },
}));
- for (const event of background) live.emit(event);
+ for (const event of unsolicited) live.emit(event);
await vi.waitFor(() => expect(store.snapshot.events).toHaveLength(3));
expect(store.snapshot.data.messages.some((message) => message.metadata?.optimistic)).toBe(true);
@@ -729,7 +729,7 @@ describe("EveAgentStore prewarming", () => {
await vi.waitFor(() => expect(store.snapshot.events).toHaveLength(6));
await sending;
- expect(store.snapshot.events).toEqual([...background, ...messageTurn]);
+ expect(store.snapshot.events).toEqual([...unsolicited, ...messageTurn]);
expect(store.snapshot.data.messages.some((message) => message.metadata?.optimistic)).toBe(
false,
);
diff --git a/packages/eve/src/client/eve-agent-store.ts b/packages/eve/src/client/eve-agent-store.ts
index 9fc046974..231b57b76 100644
--- a/packages/eve/src/client/eve-agent-store.ts
+++ b/packages/eve/src/client/eve-agent-store.ts
@@ -21,7 +21,7 @@ import { EveAgentProjection } from "#client/eve-agent-projection.js";
import { OptimisticMessageSubmissions } from "#client/optimistic-message-submissions.js";
import type { ClientSession } from "#client/session.js";
import { createEventDeduper } from "#protocol/event-dedupe.js";
-import { isCurrentTurnBoundaryEvent, type MessageStreamEvent } from "#protocol/message.js";
+import type { MessageStreamEvent } from "#protocol/message.js";
import {
assertExclusiveTurnInput,
createAbortSignal,
@@ -32,7 +32,11 @@ import {
toTerminalStreamFailureError,
waitWithSignal,
} from "#client/eve-agent-store-helpers.js";
-import { updatePendingAuthorizations } from "#client/session-utils.js";
+import {
+ isTurnSegmentBoundary,
+ updatePendingAuthorizations,
+ updatePendingInputRequests,
+} from "#client/session-utils.js";
import { toError } from "#shared/errors.js";
import type { CancelSessionResult, SendTurnPayload } from "#client/types.js";
@@ -58,6 +62,7 @@ export class EveAgentStore<TData> {
#attached = false;
#stream: SessionEventStream | undefined;
readonly #pendingAuthorizations = new Set<string>();
+ readonly #pendingInputRequests = new Set<string>();
readonly #externalSession: boolean;
readonly #optimistic: boolean;
readonly #projection: EveAgentProjection<TData>;
@@ -94,7 +99,7 @@ export class EveAgentStore<TData> {
const initialEvents: MessageStreamEvent[] = [];
for (const event of init.initialEvents ?? []) {
if (this.#seenEvents.admit(event)) initialEvents.push(event);
- updatePendingAuthorizations(this.#pendingAuthorizations, event);
+ this.#trackPendingRequests(event);
}
this.#events = initialEvents;
this.#projection = new EveAgentProjection(init.reducer, this.#events);
@@ -334,7 +339,7 @@ export class EveAgentStore<TData> {
if (!this.#isActiveTurn(turn)) return;
turn.receivedFollowUps += turn.receivedFollowUpEvents.get(event) ?? 0;
turn.receivedFollowUpEvents.delete(event);
- if (isCurrentTurnBoundaryEvent(event) && this.#pendingAuthorizations.size === 0) break;
+ if (this.#isSettledAt(event)) break;
}
}
await followSteeredTurns(turn, reader, () => this.#isActiveTurn(turn));
@@ -388,6 +393,7 @@ export class EveAgentStore<TData> {
this.#stream?.close();
this.#stream = undefined;
this.#pendingAuthorizations.clear();
+ this.#pendingInputRequests.clear();
const turn = this.#activeTurn;
this.#activeTurn = undefined;
turn?.resolveResponse(undefined);
@@ -593,12 +599,12 @@ export class EveAgentStore<TData> {
#acceptServerEvent(event: MessageStreamEvent): void {
if (!this.#seenEvents.admit(event)) return;
const wasStreaming = this.#status === "streaming";
- updatePendingAuthorizations(this.#pendingAuthorizations, event);
+ this.#trackPendingRequests(event);
this.#events = [...this.#events, event];
this.#handleReconciliation(this.#messageSubmissions.apply(event));
this.#callbacks.onEvent?.(event);
this.#applyTerminalStreamFailure(event);
- const settled = isCurrentTurnBoundaryEvent(event) && this.#pendingAuthorizations.size === 0;
+ const settled = this.#isSettledAt(event);
if (this.#status !== "resuming" && this.#error === undefined) {
if ("data" in event && "turnId" in event.data) this.#status = "streaming";
if (this.#activeTurn === undefined && settled) this.#status = "ready";
@@ -612,6 +618,18 @@ export class EveAgentStore<TData> {
}
}
+ #trackPendingRequests(event: MessageStreamEvent): void {
+ updatePendingAuthorizations(this.#pendingAuthorizations, event);
+ updatePendingInputRequests(this.#pendingInputRequests, event);
+ }
+
+ #isSettledAt(event: MessageStreamEvent): boolean {
+ return (
+ isTurnSegmentBoundary(event, this.#pendingInputRequests) &&
+ this.#pendingAuthorizations.size === 0
+ );
+ }
+
#handleReconciliation(
reconciliation: ReturnType<OptimisticMessageSubmissions<TData>["apply"]>,
): boolean {
diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.ts
index eb6cd5999..a85da64f1 100644
--- a/packages/eve/src/client/index.ts
+++ b/packages/eve/src/client/index.ts
@@ -100,6 +100,7 @@ export type {
ActionPartialStreamEvent,
ActionResultStreamEvent,
ActionsRequestedStreamEvent,
+ AgentStartedStreamEvent,
AssistantStepFinishReason,
AuthorizationOutcome,
CompactionCompletedStreamEvent,
@@ -138,6 +139,7 @@ export type {
TurnFailedStreamEvent,
TurnStartedStreamEvent,
TurnFailureStreamEvent,
+ TurnWaitingStreamEvent,
} from "#protocol/message.js";
export { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";
diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.ts
index dd0c00bf4..3a7c1cd04 100644
--- a/packages/eve/src/client/message-reducer.test.ts
+++ b/packages/eve/src/client/message-reducer.test.ts
@@ -1279,41 +1279,6 @@ describe("defaultMessageReducer", () => {
]);
});
- it("removes streamed text for a null message completion", () => {
- const reducer = defaultMessageReducer();
- const data = reduceServerEvents(reducer, reducer.initial(), [
- createMessageCompletedEvent({
- message: "Earlier step.",
- sequence: 0,
- stepIndex: 0,
- turnId: "turn_1",
- }),
- createMessageAppendedEvent({
- messageDelta: "<eve-empty-delivery/>",
- sequence: 1,
- stepIndex: 1,
- turnId: "turn_1",
- }),
- createMessageCompletedEvent({
- message: null,
- sequence: 1,
- stepIndex: 1,
- turnId: "turn_1",
- }),
- ]);
-
- expect(data.messages[0]?.parts).toEqual([
- { type: "step-start" },
- {
- state: "done",
- stepIndex: 0,
- text: "Earlier step.",
- type: "text",
- },
- { type: "step-start" },
- ]);
- });
-
it("preserves separate participant messages received within one turn", () => {
const reducer = defaultMessageReducer();
const events = stampTestEvents([
@@ -1366,20 +1331,6 @@ describe("defaultMessageReducer", () => {
expect(data.messages[0]?.id).toBe("turn_1:2:user");
});
- it("does not project framework-authored task input", () => {
- const reducer = defaultMessageReducer();
- const [event] = stampTestEvents([
- createMessageReceivedEvent({
- kind: "execution.background_task",
- message: "Task completed",
- sequence: 1,
- turnId: "turn_1",
- }),
- ]);
-
- expect(reducer.reduce(reducer.initial(), event!).messages).toEqual([]);
- });
-
it("projects structured file parts from message.received onto the user message", () => {
const reducer = defaultMessageReducer();
const data = reduceServerEvents(reducer, reducer.initial(), [
diff --git a/packages/eve/src/client/message-reducer.ts b/packages/eve/src/client/message-reducer.ts
index 8b5779721..0951af119 100644
--- a/packages/eve/src/client/message-reducer.ts
+++ b/packages/eve/src/client/message-reducer.ts
@@ -104,7 +104,6 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): E
}
case "message.received":
- if (event.data.kind === "execution.background_task") return data;
return upsertMessage(data, {
id: `${receivedMessageEventId(event)}:user`,
metadata: {
@@ -359,10 +358,6 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): E
case "message.completed":
return updateAssistantMessage(data, event.data.turnId, (message) => {
- if (event.data.message === null) {
- return removeTextPart(message, event.data.stepIndex);
- }
-
return messageRun.upsert(ensureStepStartPart(message, event.data.stepIndex), {
state: "done",
stepIndex: event.data.stepIndex,
@@ -533,24 +528,6 @@ function upsertPart(message: EveAssistantMessage, next: EveMessagePart): EveAssi
};
}
-function removeTextPart(message: EveAssistantMessage, stepIndex: number): EveAssistantMessage {
- const parts = message.parts.filter(
- (part) => part.type !== "text" || part.stepIndex !== stepIndex,
- );
- if (parts.length === message.parts.length) {
- return message;
- }
-
- return {
- ...message,
- metadata: {
- ...message.metadata,
- status: "complete",
- },
- parts,
- };
-}
-
function updateToolPart(
data: EveMessageData,
toolCallId: string,
diff --git a/packages/eve/src/client/optimistic-message-submissions.test.ts b/packages/eve/src/client/optimistic-message-submissions.test.ts
index e9ecc001a..d36643e74 100644
--- a/packages/eve/src/client/optimistic-message-submissions.test.ts
+++ b/packages/eve/src/client/optimistic-message-submissions.test.ts
@@ -43,20 +43,6 @@ describe("OptimisticMessageSubmissions", () => {
expect(projection.data.messages.some((message) => message.metadata?.optimistic)).toBe(false);
});
- it("does not reconcile framework-authored task input", () => {
- const { projection, submissions } = setup();
- const id = submissions.submit({ message: "Hello" }, 0)!;
- submissions.correlate(id, "mine", []);
- const taskWake = received("Task completed", ["mine"]);
- submissions.apply({
- ...taskWake,
- data: { ...taskWake.data, kind: "execution.background_task" },
- });
-
- expect(projection.data.messages).toHaveLength(1);
- expect(projection.data.messages[0]?.metadata?.optimistic).toBe(true);
- });
-
it("reconciles events that arrive before the POST response", () => {
const { projection, submissions } = setup();
const id = submissions.submit({ message: "Hello" }, 0)!;
diff --git a/packages/eve/src/client/optimistic-message-submissions.ts b/packages/eve/src/client/optimistic-message-submissions.ts
index 7f405c176..10eaed786 100644
--- a/packages/eve/src/client/optimistic-message-submissions.ts
+++ b/packages/eve/src/client/optimistic-message-submissions.ts
@@ -49,10 +49,6 @@ export class OptimisticMessageSubmissions<TData> {
this.#projection.append(event);
return undefined;
}
- if (event.data.kind === "execution.background_task") {
- this.#projection.append(event);
- return undefined;
- }
const matching = this.#matching(event);
if (matching.length === 0) {
this.#projection.append(event);
@@ -75,9 +71,7 @@ export class OptimisticMessageSubmissions<TData> {
const pending = this.#pending.find((candidate) => candidate.id === submissionId);
if (pending === undefined) return undefined;
for (const event of events.slice(pending.eventStartIndex)) {
- if (event.type !== "message.received" || event.data.kind === "execution.background_task") {
- continue;
- }
+ if (event.type !== "message.received") continue;
const matching = this.#matching(event);
if (matching.some((candidate) => candidate.id === submissionId)) {
return this.#reconcile(matching, event, true);
diff --git a/packages/eve/src/client/session-controls.ts b/packages/eve/src/client/session-controls.ts
index 33ef31a7d..e70cf611e 100644
--- a/packages/eve/src/client/session-controls.ts
+++ b/packages/eve/src/client/session-controls.ts
@@ -28,7 +28,6 @@ export async function cancelClientSession(input: {
readonly context: SessionControlContext;
readonly options?: {
readonly signal?: AbortSignal;
- readonly tasks?: boolean;
readonly turnId?: string;
};
readonly sessionId: string;
diff --git a/packages/eve/src/client/session-utils.ts b/packages/eve/src/client/session-utils.ts
index b5952cc50..5fff24e8f 100644
--- a/packages/eve/src/client/session-utils.ts
+++ b/packages/eve/src/client/session-utils.ts
@@ -34,10 +34,12 @@ export function summarizeTurnEvents(
let failure: TurnFailureStreamEvent | undefined;
let message: string | undefined;
const inputRequests: InputRequest[] = [];
+ const pendingInputRequests = new Set<string>();
const pendingAuthorizations = new Map<string, PendingAuthorization>();
for (const event of events) {
- if (isCurrentTurnBoundaryEvent(event)) boundary = event;
+ updatePendingInputRequests(pendingInputRequests, event);
+ if (isTurnSegmentBoundary(event, pendingInputRequests)) boundary = event;
if (isTurnFailureEvent(event)) failure = event;
if (isFinalMessageCompleted(event)) message = event.data.message ?? undefined;
if (event.type === "input.requested") inputRequests.push(...event.data.requests);
@@ -55,27 +57,59 @@ export function summarizeTurnEvents(
inputRequests,
message,
pendingAuthorizations: [...pendingAuthorizations.values()],
- status:
- boundary?.type === "session.waiting"
- ? "waiting"
- : boundary?.type === "session.failed"
- ? "failed"
- : "completed",
+ status: summarizeBoundaryStatus(boundary),
};
}
+function summarizeBoundaryStatus(
+ boundary: UnstampedMessageStreamEvent | undefined,
+): TurnEventSummary["status"] {
+ if (boundary?.type === "session.waiting" || boundary?.type === "turn.waiting") return "waiting";
+ if (boundary?.type === "session.failed") return "failed";
+ return "completed";
+}
+
/** Collects one segment of an event stream through its current-turn boundary. */
export async function collectTurnEvents(
stream: AsyncIterable<UnstampedMessageStreamEvent>,
): Promise<readonly UnstampedMessageStreamEvent[]> {
const events: UnstampedMessageStreamEvent[] = [];
+ const pendingInputRequests = new Set<string>();
for await (const event of stream) {
events.push(event);
- if (isCurrentTurnBoundaryEvent(event)) break;
+ updatePendingInputRequests(pendingInputRequests, event);
+ if (isTurnSegmentBoundary(event, pendingInputRequests)) break;
}
return events;
}
+/**
+ * Returns true when one segment of a turn's events ends at `event`: at a
+ * current-turn boundary, or at `turn.waiting` while an input request read in
+ * the segment is unanswered. The turn stays open there until a person answers;
+ * without a pending request, `turn.waiting` is informational and reading goes
+ * on to the turn's real end.
+ */
+export function isTurnSegmentBoundary(
+ event: UnstampedMessageStreamEvent,
+ pendingInputRequests: ReadonlySet<string>,
+): boolean {
+ if (event.type === "turn.waiting") return pendingInputRequests.size > 0;
+ return isCurrentTurnBoundaryEvent(event);
+}
+
+/** Tracks the input requests read in a segment that no `input.resolved` has answered yet. */
+export function updatePendingInputRequests(
+ pending: Set<string>,
+ event: UnstampedMessageStreamEvent,
+): void {
+ if (event.type === "input.requested") {
+ for (const request of event.data.requests) pending.add(request.requestId);
+ } else if (event.type === "input.resolved") {
+ for (const resolution of event.data.resolutions) pending.delete(resolution.requestId);
+ }
+}
+
function isFinalMessageCompleted(
event: UnstampedMessageStreamEvent,
): event is MessageCompletedStreamEvent {
diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.ts
index f915ed34b..8545ec0a3 100644
--- a/packages/eve/src/client/session.test.ts
+++ b/packages/eve/src/client/session.test.ts
@@ -144,7 +144,7 @@ describe("ClientSession", () => {
expect(requests[1]!.headers.get("authorization")).toBe("Bearer token-2");
});
- it("sends tasks in the cancel body and uses signal only for fetch", async () => {
+ it("sends the turn id in the cancel body and uses signal only for fetch", async () => {
const controller = new AbortController();
const fetchMock = vi
.spyOn(globalThis, "fetch")
@@ -153,14 +153,15 @@ describe("ClientSession", () => {
);
const session = createSession();
- await expect(
- session.cancel({ signal: controller.signal, tasks: true, turnId: "turn_1" }),
- ).resolves.toEqual({ sessionId: "session_1", status: "accepted" });
+ await expect(session.cancel({ signal: controller.signal, turnId: "turn_1" })).resolves.toEqual({
+ sessionId: "session_1",
+ status: "accepted",
+ });
expect(fetchMock).toHaveBeenCalledTimes(1);
const init = fetchMock.mock.calls[0]?.[1];
expect(init?.signal).toBe(controller.signal);
- expect(JSON.parse(String(init?.body))).toEqual({ tasks: true, turnId: "turn_1" });
+ expect(JSON.parse(String(init?.body))).toEqual({ turnId: "turn_1" });
});
it("snapshots the session from the start through one pinned durable tail", async () => {
@@ -580,19 +581,6 @@ describe("ClientSession", () => {
});
});
- it("serializes taskDeliveryPolicy with a fixed-session message", async () => {
- const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());
- const session = createSession();
-
- await session.send("Wait your turn", { taskDeliveryPolicy: "cohort" });
-
- const init = fetchMock.mock.calls[0]?.[1] as RequestInit;
- expect(JSON.parse(String(init.body))).toEqual({
- message: "Wait your turn",
- taskDeliveryPolicy: "cohort",
- });
- });
-
it("serializes clientContext when continuing a session", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());
const session = createSession({
@@ -947,7 +935,7 @@ describe("ClientSession", () => {
for await (const _event of session.stream()) {
// Invalid events fail before delivery.
}
- }).rejects.toThrow("Invalid message append delta for stream version 25.");
+ }).rejects.toThrow("Invalid message append delta for stream version 26.");
expect(fetchMock).toHaveBeenCalledOnce();
});
@@ -1181,6 +1169,41 @@ describe("ClientSession", () => {
expect(session.state.streamIndex).toBe(2);
});
+ it("stops at turn.waiting only while a question it read is unanswered", async () => {
+ const turn = { sequence: 0, stepIndex: 0, turnId: "turn_0" };
+ const question = (requestId: string) => ({
+ action: { callId: "call_1", input: {}, kind: "tool-call", toolName: "deploy" },
+ kind: "question",
+ prompt: "Deploy now?",
+ requestId,
+ });
+ const answered = { kind: "question", outcome: "answered", requestId: "request_1" };
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_request, init) =>
+ (init?.method ?? "GET") === "POST"
+ ? createAcceptedResponse()
+ : createStreamResponse([
+ { type: "input.requested", data: { ...turn, requests: [question("request_1")] } },
+ { type: "input.resolved", data: { ...turn, resolutions: [answered] } },
+ { type: "turn.waiting", data: { sequence: 0, turnId: "turn_0" } },
+ { type: "input.requested", data: { ...turn, requests: [question("request_2")] } },
+ { type: "turn.waiting", data: { sequence: 0, turnId: "turn_0" } },
+ { type: "turn.completed", data: { sequence: 0, turnId: "turn_0" } },
+ ]),
+ );
+
+ const result = await (await createSession().send("first")).result();
+
+ expect(result.events.map((event) => event.type)).toEqual([
+ "input.requested",
+ "input.resolved",
+ "turn.waiting",
+ "input.requested",
+ "turn.waiting",
+ ]);
+ expect(result.status).toBe("waiting");
+ expect(result.inputRequests.at(-1)?.requestId).toBe("request_2");
+ });
+
it("honors an explicit idle reconnect limit for an active turn", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (_request, init) => {
return (init?.method ?? "GET") === "POST"
@@ -1430,16 +1453,6 @@ describe("ClientSession.streamSubagent", () => {
expect(urls[0]!.pathname).toBe("/eve/v1/session/child_1/stream");
});
- it("rejects a subagent event from a different parent session", () => {
- const fetchMock = vi.spyOn(globalThis, "fetch");
- const session = createSession();
-
- expect(() => session.streamSubagent(calledEvent({ sessionId: "session_2" }))).toThrow(
- "streamSubagent() requires a subagent.called event from session session_1, but it came from session session_2.",
- );
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
it("rejects a subagent event recorded before childStreamPath existed", () => {
const fetchMock = vi.spyOn(globalThis, "fetch");
const session = createSession();
diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.ts
index 2634dd9b3..f6af4cfcd 100644
--- a/packages/eve/src/client/session.ts
+++ b/packages/eve/src/client/session.ts
@@ -1,6 +1,14 @@
-import { updatePendingAuthorizations } from "#client/session-utils.js";
-import type { MessageStreamEvent, SubagentCalledStreamEvent } from "#protocol/message.js";
-import { EVE_SESSION_ID_HEADER, isCurrentTurnBoundaryEvent } from "#protocol/message.js";
+import {
+ isTurnSegmentBoundary,
+ updatePendingAuthorizations,
+ updatePendingInputRequests,
+} from "#client/session-utils.js";
+import type {
+ AgentStartedStreamEvent,
+ MessageStreamEvent,
+ SubagentCalledStreamEvent,
+} from "#protocol/message.js";
+import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";
import {
EVE_SESSION_ROUTE_PATH,
createEveSessionRoutePath,
@@ -165,10 +173,9 @@ export class ClientSession {
);
}
- /** Requests cooperative cancellation of this session's active turn and optionally its tasks. */
+ /** Requests cooperative cancellation of this session's active turn. */
async cancel(options?: {
readonly signal?: AbortSignal;
- readonly tasks?: boolean;
readonly turnId?: string;
}): Promise<CancelSessionResult> {
return await cancelClientSession({
@@ -213,32 +220,23 @@ export class ClientSession {
/**
* Follows one delegated child's durable event stream through this parent session.
*
- * Pass a `subagent.called` event from this session. The client reads its
- * `childStreamPath` with this session's host and credentials: a local child's
- * own stream route, or the parent-origin proxy for a remote child, which the
- * parent deployment authenticates to the remote agent. Reading the child never
- * advances this session's cursor. The child cursor starts at `0`; pass
+ * Pass an `agent.started` or `subagent.called` event from this session. The
+ * client reads the child's stream path with this session's host and
+ * credentials: a local child's own stream route, or the parent-origin proxy
+ * for a remote child, which the parent deployment authenticates to the remote
+ * agent after checking that the parent recorded the child. Reading the child
+ * never advances this session's cursor. The child cursor starts at `0`; pass
* `startIndex` to resume. Stop at a child turn boundary with
* `isCurrentTurnBoundaryEvent`.
*
- * @throws {Error} When `called` belongs to a different session or has no
- * `childStreamPath` because an older eve version recorded it.
+ * @throws {Error} When a `subagent.called` event has no `childStreamPath`
+ * because an older eve version recorded it.
*/
streamSubagent(
- called: SubagentCalledStreamEvent,
+ started: AgentStartedStreamEvent | SubagentCalledStreamEvent,
options?: StreamOptions,
): AsyncIterable<MessageStreamEvent> {
- if (called.data.sessionId !== this.#state.sessionId) {
- throw new Error(
- `streamSubagent() requires a subagent.called event from session ${this.#state.sessionId}, but it came from session ${called.data.sessionId}.`,
- );
- }
- // Events persisted before childStreamPath existed replay without it.
- if (typeof called.data.childStreamPath !== "string") {
- throw new Error(
- `streamSubagent() requires a subagent.called event with childStreamPath, but call ${called.data.callId} has none. The event was recorded by an older eve version.`,
- );
- }
+ const path = readChildStreamPath(started);
const startIndex = options?.startIndex ?? 0;
if (options?.follow === false && startIndex < 0) {
throw new Error(
@@ -248,7 +246,7 @@ export class ClientSession {
return followStreamIterable({
follow: options?.follow,
host: this.#context.host,
- path: called.data.childStreamPath,
+ path,
redirect: this.#context.redirect,
resolveHeaders: () => this.#context.resolveHeaders(),
signal: options?.signal,
@@ -287,6 +285,7 @@ export class ClientSession {
let started = deliveryId === undefined;
let reachedBoundary = false;
const pendingAuthorizations = new Set<string>();
+ const pendingInputRequests = new Set<string>();
try {
for await (const event of source ??
this.#readStream({
@@ -310,8 +309,9 @@ export class ClientSession {
started = true;
}
updatePendingAuthorizations(pendingAuthorizations, event);
+ updatePendingInputRequests(pendingInputRequests, event);
reachedBoundary =
- isCurrentTurnBoundaryEvent(event) &&
+ isTurnSegmentBoundary(event, pendingInputRequests) &&
(event.type !== "session.waiting" || pendingAuthorizations.size === 0);
yield event;
if (reachedBoundary) {
@@ -384,6 +384,17 @@ export class ClientSession {
}
}
+function readChildStreamPath(started: AgentStartedStreamEvent | SubagentCalledStreamEvent): string {
+ if (started.type === "agent.started") return started.data.streamPath;
+ // Events persisted before childStreamPath existed replay without it.
+ if (typeof started.data.childStreamPath !== "string") {
+ throw new Error(
+ `streamSubagent() requires a subagent.called event with childStreamPath, but call ${started.data.callId} has none. The event was recorded by an older eve version.`,
+ );
+ }
+ return started.data.childStreamPath;
+}
+
/** @internal Follow continuously while the frontend owns the session. */
export function followClientSession(
session: ClientSession,
@@ -501,9 +512,6 @@ function createMessageBody(
if (!requireMessage && input.message !== undefined && input.turnPolicy !== undefined) {
body.turnPolicy = input.turnPolicy;
}
- if (input.message !== undefined && input.taskDeliveryPolicy !== undefined) {
- body.taskDeliveryPolicy = input.taskDeliveryPolicy;
- }
if (input.clientContext !== undefined) body.clientContext = input.clientContext;
const outputSchema = serializeOutputSchema(input.outputSchema);
if (outputSchema !== undefined) body.outputSchema = outputSchema;
diff --git a/packages/eve/src/client/stream-version.test.ts b/packages/eve/src/client/stream-version.test.ts
index 201e48a32..de0664b43 100644
--- a/packages/eve/src/client/stream-version.test.ts
+++ b/packages/eve/src/client/stream-version.test.ts
@@ -4,7 +4,7 @@ import { readMessageStreamVersion } from "#client/stream-version.js";
import { EVE_STREAM_VERSION_HEADER } from "#protocol/message.js";
describe("readMessageStreamVersion", () => {
- it.each(["21", "22", "23", "24", "25"] as const)("accepts stream version %s", (version) => {
+ it.each(["21", "22", "23", "24", "25", "26"] as const)("accepts stream version %s", (version) => {
expect(readMessageStreamVersion(new Headers({ [EVE_STREAM_VERSION_HEADER]: version }))).toBe(
version,
);
@@ -18,7 +18,7 @@ describe("readMessageStreamVersion", () => {
it("rejects an unsupported version", () => {
expect(() =>
- readMessageStreamVersion(new Headers({ [EVE_STREAM_VERSION_HEADER]: "26" })),
- ).toThrow("Unsupported message stream version: 26.");
+ readMessageStreamVersion(new Headers({ [EVE_STREAM_VERSION_HEADER]: "27" })),
+ ).toThrow("Unsupported message stream version: 27.");
});
});
diff --git a/packages/eve/src/client/stream-version.ts b/packages/eve/src/client/stream-version.ts
index 0cb4fcc27..d3127e15c 100644
--- a/packages/eve/src/client/stream-version.ts
+++ b/packages/eve/src/client/stream-version.ts
@@ -7,6 +7,7 @@ const supportedMessageStreamVersions = {
"23": true,
"24": true,
"25": true,
+ "26": true,
} as const satisfies Record<MessageStreamVersion, true>;
/** Reads and validates the schema version declared by a message stream response. */
diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.ts
index 43d99d7be..8e95a00e0 100644
--- a/packages/eve/src/client/types.ts
+++ b/packages/eve/src/client/types.ts
@@ -6,7 +6,7 @@ import type { CancelTurnResult } from "#protocol/cancel-turn.js";
import type { ClearStatus } from "#protocol/clear-session.js";
import type { CompactStatus } from "#protocol/compact-session.js";
import type { ResetStatus } from "#protocol/reset-session.js";
-import type { TurnPolicy, TaskDeliveryPolicy } from "#channel/types.js";
+import type { TurnPolicy } from "#channel/types.js";
import type { InputRequest, InputResponse } from "#shared/input.js";
import type { JsonObject } from "#shared/json.js";
export type { HealthResult } from "#client/health-schema.js";
@@ -120,8 +120,6 @@ export interface CreateSessionOptions {
export interface SendTurnOptions<TOutput = unknown> {
/** Policy for a message sent while the fixed session has an active turn. */
readonly turnPolicy?: TurnPolicy;
- /** Updates the session’s background task reporting policy. Omit to preserve it. */
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
/**
* Ephemeral client/page context for the current turn.
@@ -163,10 +161,7 @@ export interface SendTurnOptions<TOutput = unknown> {
}
/** Options for answering pending HITL input requests on a client session. */
-export type RespondTurnOptions<TOutput = unknown> = Omit<
- SendTurnOptions<TOutput>,
- "taskDeliveryPolicy"
->;
+export type RespondTurnOptions<TOutput = unknown> = SendTurnOptions<TOutput>;
/** @internal Transport envelope used by stores and command adapters. */
export type SendTurnPayload<TOutput = unknown> =
diff --git a/packages/eve/src/compiler/default-tool-policy.ts b/packages/eve/src/compiler/default-tool-policy.ts
index 8ef803c62..84524a2b4 100644
--- a/packages/eve/src/compiler/default-tool-policy.ts
+++ b/packages/eve/src/compiler/default-tool-policy.ts
@@ -22,21 +22,6 @@ export function assertFrameworkToolPolicy(
'The required "connection_search" tool cannot be disabled. Remove "agent/tools/connection_search.ts" or export a replacement tool from it.',
);
}
- const closedDispatchSlots = {
- "tools/task_cancel": "task-cancel",
- } as const;
- const expectedAction = closedDispatchSlots[slot as keyof typeof closedDispatchSlots];
- if (
- expectedAction !== undefined &&
- result.kind === "tool" &&
- (result.definition.behavior?.handling?.kind !== "dispatch" ||
- result.definition.behavior.handling.action !== expectedAction)
- ) {
- const toolName = slot.slice("tools/".length);
- throw new Error(
- `The framework "${toolName}" tool cannot be overridden. Re-export it from "eve/tools/${toolName}" or disable it with disableTool().`,
- );
- }
}
export function applyAgentToolPolicy(
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 2d90f01f1..49923547e 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 59,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55, 58, 59],
+ current: 60,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55, 60],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
15: "TaskExec replaces stageEffect with send",
@@ -61,13 +61,15 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
53: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
56: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",
57: "agentRouter() no longer accepts a model-facing outputSchema; structured subagent output is requested only through ctx.agent().",
+ 58: "Workflow tools no longer accept execution or return background task receipts; every call blocks until it settles.",
+ 59: "Workflow tools no longer accept execution or return background task receipts, and every call blocks until it settles. ctx.ask() no longer accepts dismissible and reports a withdrawn request as cancelled, workflow tool contexts carry interruptSignal, and ctx.agent(name) returns a session handle whose send() delivers a message and whose result() resolves the turn; ctx.agent(name, { message, agentId }) and AgentInput were removed. A ctx.ask() question parks the open turn with turn.waiting instead of ending it.",
},
},
dynamicTool: {
- current: 56,
+ current: 57,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,
- 56,
+ 57,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -99,11 +101,12 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
51: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
53: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",
55: "Run mode was removed; sessions always park and ConversationContext no longer carries mode.",
+ 56: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
},
},
channel: {
- current: 34,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 33, 34],
+ current: 35,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 35],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
19: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.",
@@ -118,18 +121,21 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
28: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
30: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",
32: "Run mode and caller-supplied output schemas were removed from channel operations; sessions always park, and send options, audience inputs, and ConversationContext no longer carry mode, while from().send() and from().respond() no longer accept outputSchema.",
+ 33: "Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text.",
+ 34: 'Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
},
},
schedule: {
- current: 16,
- supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
+ current: 17,
+ supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17],
dropped: {
5: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
+ 16: 'Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
},
},
subagent: {
- current: 21,
- supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 21],
+ current: 22,
+ supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 22],
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",
@@ -137,22 +143,24 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
17: "Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.",
18: "Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.",
20: "Run mode was removed and agent definitions no longer declare outputSchema; sessions always park, ConversationContext no longer carries mode, and structured output is requested per turn.",
+ 21: 'Background task execution was removed: subagent results no longer carry backgroundTask, message.completed always carries text, and experimental.tasks is gone. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
},
},
connection: {
- current: 28,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 28],
+ current: 29,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 29],
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.",
23: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
25: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",
27: "Run mode was removed; sessions always park and ConversationContext no longer carries mode.",
+ 28: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
},
},
hook: {
- current: 29,
- supported: [10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 27, 28, 29],
+ current: 30,
+ supported: [10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 27, 30],
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.",
@@ -166,24 +174,28 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
16: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
24: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
26: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",
+ 28: "Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text.",
+ 29: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
},
},
skill: { current: 2, supported: [1, 2], dropped: {} },
dynamicSkill: {
- current: 23,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 23],
+ current: 24,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 24],
dropped: {
13: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
22: "Run mode was removed; sessions always park and ConversationContext no longer carries mode.",
+ 23: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
},
},
instructions: { current: 2, supported: [1, 2], dropped: {} },
dynamicInstructions: {
- current: 24,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 24],
+ current: 25,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 25],
dropped: {
14: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
23: "Run mode was removed; sessions always park and ConversationContext no longer carries mode.",
+ 24: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',
},
},
config: { current: 1, supported: [1], dropped: {} },
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 9c0516524..318e8015b 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -814,12 +814,12 @@ const compiledDynamicConnectionDefinitionSchema: z.ZodType<CompiledDynamicConnec
const compiledToolBehaviorSchema: z.ZodType<CompiledToolBehavior> = z
.object({
- availability: z.array(z.enum(["delegated-task-child", "root-session"])).readonly(),
+ availability: z.array(z.literal("root-session")).readonly(),
handling: z
.discriminatedUnion("kind", [
z
.object({
- action: z.enum(["self-agent", "task-cancel"]),
+ action: z.literal("self-agent"),
kind: z.literal("dispatch"),
})
.strict(),
@@ -840,7 +840,6 @@ const compiledToolBehaviorSchema: z.ZodType<CompiledToolBehavior> = z
presentation: z.literal("load-skill").optional(),
shape: z
.object({
- lifetime: z.enum(["step", "task"]),
suspend: z.enum(["none", "workflow"]),
})
.strict()
@@ -853,7 +852,6 @@ const compiledToolDefinitionSchema = z
availableInSubagents: z.boolean().optional(),
behavior: compiledToolBehaviorSchema.optional(),
description: z.string(),
- execution: z.literal("background").optional(),
exportName: z.string().optional(),
hasExecute: z.boolean(),
hasModelOutputProjection: z.boolean(),
diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.ts
index fb8610a50..0f36a093c 100644
--- a/packages/eve/src/compiler/normalize-manifest.test.ts
+++ b/packages/eve/src/compiler/normalize-manifest.test.ts
@@ -265,16 +265,6 @@ describe("compileAgentManifest source graph", () => {
);
});
- it("does not install task_update from the framework registry", async () => {
- const compiled = await compileAgentManifest(manifest());
-
- expect(compiled.tools.map((tool) => tool.name)).toContain("task_cancel");
- expect(compiled.tools.map((tool) => tool.name)).not.toContain("task_update");
- expect(Object.values(compiled.bindings).map((binding) => binding.logicalPath)).not.toContain(
- "tools/task_update.ts",
- );
- });
-
it("does not install ask_question from the framework registry", async () => {
const compiled = await compileAgentManifest(manifest());
@@ -304,31 +294,9 @@ describe("compileAgentManifest source graph", () => {
availableInSubagents: false,
behavior: { availability: [] },
description: "Route delegated work.",
- execution: undefined,
});
});
- it.each(["task_cancel"])("rejects overriding closed framework tool %s", async (toolName) => {
- const sourceRegistry = registry([
- {
- logicalPath: `tools/${toolName}.ts`,
- loadNamespace: async () => ({
- default: defineTool({
- description: "Replacement tool.",
- execute: async () => null,
- inputSchema: {},
- }),
- }),
- },
- ]);
-
- await expect(
- compileAgentManifest(manifest(), { sourceRegistries: [sourceRegistry] }),
- ).rejects.toThrow(
- `The framework "${toolName}" tool cannot be overridden. Re-export it from "eve/tools/${toolName}" or disable it with disableTool().`,
- );
- });
-
it("compiles a workflow tool with programmatic executor metadata", async () => {
const execute = async () => ({ ok: true });
Reflect.set(execute, "workflowId", "workflow//example/tool//execute");
@@ -355,7 +323,7 @@ describe("compileAgentManifest source graph", () => {
kind: "workflow-tool",
workflowId: "workflow//example/tool//execute",
},
- shape: { lifetime: "step", suspend: "workflow" },
+ shape: { suspend: "workflow" },
});
});
diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.ts
index 628c71a54..0a17ae809 100644
--- a/packages/eve/src/compiler/normalize-tool.ts
+++ b/packages/eve/src/compiler/normalize-tool.ts
@@ -102,20 +102,7 @@ export async function compileToolEntry(
}
const workflowId = readWorkflowFunctionId(entry.definition.execute);
- if (
- entry.definition.execution === "background" &&
- workflowId === undefined &&
- !(
- entry.definition.behavior?.handling?.kind === "dispatch" &&
- entry.definition.behavior.handling.action === "self-agent"
- )
- ) {
- throw new Error(
- `Background tool "${source.logicalPath}" must use defineWorkflowTool(). defineTool() tools run in the foreground.`,
- );
- }
const shape = {
- lifetime: entry.definition.execution === "background" ? ("task" as const) : ("step" as const),
suspend: workflowId === undefined ? ("none" as const) : ("workflow" as const),
};
return {
@@ -129,7 +116,6 @@ export async function compileToolEntry(
: { ...entry.definition.behavior, shape }
: { availability: [], handling: { kind: "workflow-tool", workflowId }, shape },
description: entry.definition.description,
- execution: entry.definition.execution,
exportName: source.exportName,
hasExecute: entry.definition.hasExecute,
hasModelOutputProjection: entry.definition.hasModelOutputProjection,
diff --git a/packages/eve/src/compiler/subagent-execution.scenario.test.ts b/packages/eve/src/compiler/subagent-execution.scenario.test.ts
index f870ac884..b86dbbe40 100644
--- a/packages/eve/src/compiler/subagent-execution.scenario.test.ts
+++ b/packages/eve/src/compiler/subagent-execution.scenario.test.ts
@@ -27,10 +27,6 @@ describe("subagent compilation", () => {
const child = manifest.subagents[0];
expect(child).not.toHaveProperty("execution");
- if (child?.configResolver !== undefined) throw new Error("Expected a static child.");
- const toolNames = child?.agent.tools.map((tool) => tool.name);
- expect(toolNames).toContain("task_cancel");
- expect(toolNames).not.toContain("task_update");
});
it("compiles a subagent without root configuration", async () => {
diff --git a/packages/eve/src/context/build-dynamic-tools.ts b/packages/eve/src/context/build-dynamic-tools.ts
index a67842a79..25d981fe3 100644
--- a/packages/eve/src/context/build-dynamic-tools.ts
+++ b/packages/eve/src/context/build-dynamic-tools.ts
@@ -103,12 +103,6 @@ export function replayDynamicTools(
if (metadata.length > 0 && scope.sessionId.length === 0) {
throw new Error("Dynamic tool replay requires a session id.");
}
- const background = metadata.find((entry) => entry.execution === "background");
- if (background !== undefined) {
- throw new Error(
- `Dynamic tool "${background.name}" used removed background execution. Move durable background work to a static defineWorkflowTool().`,
- );
- }
return metadata.map((entry) => {
const owner = { ...entry, ...scope };
const approvalKeyReference = entry.callbacks.approvalKey;
@@ -159,7 +153,6 @@ export function replayDynamicTools(
}),
inputSchema: replayDynamicToolSchema(entry, owner, "inputSchema")!,
name: entry.name,
- execution: entry.execution,
approval: buildReplayedApproval(entry, owner),
...(approvalKeyReference === undefined
? {}
diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
index 3fb4e2816..897aa87e1 100644
--- a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
@@ -158,7 +158,7 @@ describe("dynamic subagent lifecycle", () => {
expect(getDynamicSubagentSelection(ctx, resolver.nodeId)).toBeUndefined();
});
- it("runs every dynamic local and remote selection in the background", async () => {
+ it("runs every dynamic local and remote selection as a workflow tool", async () => {
const ctx = createContext();
const created = createResolver({ eventNames: ["session.started", "turn.started"] });
const resolver: ResolvedDynamicSubagentResolver = {
@@ -166,7 +166,7 @@ describe("dynamic subagent lifecycle", () => {
events: {
"session.started": () =>
defineAgent({
- description: "Research in the background.",
+ description: "Research the request.",
model: "openai/gpt-5.5",
modelContextWindowTokens: 200_000,
}),
@@ -184,7 +184,9 @@ describe("dynamic subagent lifecycle", () => {
messages: [],
resolvers: [resolver],
});
- expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(
+ "workflow//eve//subagentToolExecuteWorkflow",
+ );
expect(buildDynamicSubagentTools(ctx)[0]?.nodeId).toEqual(expect.any(String));
await dispatchDynamicSubagentEvent({
@@ -193,7 +195,9 @@ describe("dynamic subagent lifecycle", () => {
messages: [],
resolvers: [resolver],
});
- expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(
+ "workflow//eve//subagentToolExecuteWorkflow",
+ );
expect(buildDynamicSubagentTools(ctx)[0]?.nodeId).toEqual(expect.any(String));
});
@@ -205,7 +209,7 @@ describe("dynamic subagent lifecycle", () => {
events: {
"session.started": () =>
defineAgent({
- description: "Research in the background.",
+ description: "Research the request.",
model: "openai/gpt-5.5",
modelContextWindowTokens: 200_000,
}),
@@ -219,7 +223,9 @@ describe("dynamic subagent lifecycle", () => {
resolvers: [resolver],
});
- expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(
+ "workflow//eve//subagentToolExecuteWorkflow",
+ );
});
it("lets a turn-scoped agent config switch the subagent model", async () => {
@@ -271,7 +277,7 @@ describe("dynamic subagent lifecycle", () => {
});
});
- it("runs dynamic local selections in the background", async () => {
+ it("runs dynamic local selections as workflow tools", async () => {
const ctx = createContext();
const selected = defineAgent({
description: "Research the request.",
@@ -287,7 +293,9 @@ describe("dynamic subagent lifecycle", () => {
resolvers: [created.resolver],
});
- expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(
+ "workflow//eve//subagentToolExecuteWorkflow",
+ );
});
it("exposes a remote subagent with the returned remote config", async () => {
@@ -373,7 +381,7 @@ describe("dynamic subagent lifecycle", () => {
});
});
- it("runs dynamic remote selections in the background", async () => {
+ it("runs dynamic remote selections as workflow tools", async () => {
const ctx = createContext();
const remoteAgent = defineRemoteAgent({
description: "Research on the remote deployment.",
@@ -388,7 +396,9 @@ describe("dynamic subagent lifecycle", () => {
resolvers: [created.resolver],
});
- expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(
+ "workflow//eve//subagentToolExecuteWorkflow",
+ );
});
it("omits an invalid non-null result", async () => {
diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.ts
index 157cce8ef..0af640f5e 100644
--- a/packages/eve/src/context/dynamic-subagent-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.ts
@@ -9,7 +9,7 @@ import {
TurnDynamicSubagentSelectionsKey,
type DurableDynamicSubagentSelection,
} from "#context/keys.js";
-import { createPreparedWorkflowToolHarnessDefinition } from "#execution/tools/workflow/background.js";
+import { createPreparedWorkflowToolHarnessDefinition } from "#execution/tools/workflow/harness-definition.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import { createLogger } from "#internal/logging.js";
import type { SessionStartedStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";
@@ -193,11 +193,18 @@ export function getDynamicSubagentSelection(
input: ContextReader,
nodeId: string,
): Exclude<DurableDynamicSubagentSelection, null> | undefined {
- const turn = input.get(TurnDynamicSubagentSelectionsKey) ?? {};
- if (Object.hasOwn(turn, nodeId)) {
- return turn[nodeId] ?? undefined;
- }
+ return readDynamicSubagentSelections(input)[nodeId] ?? undefined;
+}
- const session = input.get(SessionDynamicSubagentSelectionsKey) ?? {};
- return session[nodeId] ?? undefined;
+/**
+ * The dynamic subagents selected for the current turn, by node id. A turn
+ * selection overrides the session's, and `null` withdraws one.
+ */
+export function readDynamicSubagentSelections(
+ input: ContextReader,
+): Readonly<Record<string, DurableDynamicSubagentSelection>> {
+ return {
+ ...input.get(SessionDynamicSubagentSelectionsKey),
+ ...input.get(TurnDynamicSubagentSelectionsKey),
+ };
}
diff --git a/packages/eve/src/context/dynamic-tool-metadata.ts b/packages/eve/src/context/dynamic-tool-metadata.ts
index 2347fca80..9fdbfc001 100644
--- a/packages/eve/src/context/dynamic-tool-metadata.ts
+++ b/packages/eve/src/context/dynamic-tool-metadata.ts
@@ -5,7 +5,6 @@ interface DynamicToolMetadataBase {
readonly availableInSubagents?: boolean;
readonly name: string;
readonly description: string;
- readonly execution?: "background";
readonly inputSchema: JsonObject;
readonly outputSchema?: JsonObject;
readonly resolverSlug: string;
diff --git a/packages/eve/src/context/key-names.ts b/packages/eve/src/context/key-names.ts
index e8b5492ac..512c237a5 100644
--- a/packages/eve/src/context/key-names.ts
+++ b/packages/eve/src/context/key-names.ts
@@ -11,5 +11,3 @@
export const CHANNEL_CONTEXT_KEY_NAME = "eve.channel";
export const SESSION_CALLBACK_CONTEXT_KEY_NAME = "eve.sessionCallback";
-
-export const TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME = "eve.runtime.taskDeliveryPolicy";
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 013f7ceaa..213f5f177 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -4,7 +4,6 @@
* `#runtime/sessions/runtime-context-keys.ts`.
*/
-import { TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME } from "#context/key-names.js";
import type { LanguageModel, ModelMessage, SystemModelMessage } from "ai";
import type {
@@ -17,7 +16,6 @@ import type {
SessionParent,
SessionTraceContext,
SessionTurn,
- TaskDeliveryPolicy,
} from "#channel/types.js";
import { ContextKey } from "#context/key.js";
import {
@@ -104,19 +102,9 @@ export const SessionTitleKey = new ContextKey<string>("eve.sessionTitle");
export const ChannelDeliveryKey = new ContextKey<ChannelDeliveryMetadata>("eve.channelDelivery");
/** Accepted messages whose response owns the current turn's durable stream events. */
export const TurnDeliveryIdsKey = new ContextKey<readonly string[]>("eve.turnDeliveryIds");
-/** Resolved task delivery policy, also read by the workflow inbox. */
-export const TaskDeliveryPolicyKey = new ContextKey<TaskDeliveryPolicy>(
- TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME,
-);
-/** Task-reporting phase for the active root turn. */
-export const TurnTaskDeliveryKey = new ContextKey<"none" | "initiating" | "pending" | "settled">(
- "eve.turnTaskDelivery",
-);
/** Last framework announcements recorded in the retained session history. */
export interface HistoryState {
readonly availableSkills?: string;
- readonly taskState?: string;
- readonly deliveryInstruction?: string;
}
export const HistoryStateKey = new ContextKey<HistoryState>("eve.historyState");
export interface ActiveChannelDelivery {
diff --git a/packages/eve/src/context/provider.ts b/packages/eve/src/context/provider.ts
index 651096544..4e64caaeb 100644
--- a/packages/eve/src/context/provider.ts
+++ b/packages/eve/src/context/provider.ts
@@ -1,4 +1,4 @@
-import type { HarnessSession, StepResult } from "#harness/types.js";
+import type { HarnessSession } from "#harness/types.js";
import type { ContextContainer } from "#context/container.js";
import type { ContextKey } from "#context/key.js";
@@ -35,7 +35,4 @@ export interface FrameworkContextProvider<T> {
/** Rolls back provider-owned effects when the callback or a later commit fails. */
rollback?(value: T, cause: unknown): void | Promise<void>;
-
- /** Adds provider-owned durable effects to a successfully committed harness step. */
- decorateStepResult?(value: T, result: StepResult): StepResult | Promise<StepResult>;
}
diff --git a/packages/eve/src/context/run-step.ts b/packages/eve/src/context/run-step.ts
index efaeac6c9..8cf06bf9e 100644
--- a/packages/eve/src/context/run-step.ts
+++ b/packages/eve/src/context/run-step.ts
@@ -34,16 +34,14 @@ export async function withContextScope<T>(
ctx: ContextContainer,
harnessSession: HarnessSession,
callback: (session: HarnessSession) => Promise<ContextScopeResult<T>>,
- additionalProviders: readonly FrameworkContextProvider<any>[] = [],
): Promise<ContextScopeResult<T>> {
let session = harnessSession;
- const providers = [...frameworkProviders, ...additionalProviders];
const createdProviders: FrameworkContextProvider<any>[] = [];
ctx.clearVirtualContext();
try {
- for (const provider of providers) {
+ for (const provider of frameworkProviders) {
const result = await provider.create(ctx, session);
if (result !== undefined) {
ctx.setVirtualContext(provider.key, result.value);
@@ -99,23 +97,10 @@ export async function runStep(
ctx: ContextContainer,
harnessSession: HarnessSession,
callback: (session: HarnessSession) => Promise<StepResult>,
- additionalProviders: readonly FrameworkContextProvider<any>[] = [],
): Promise<StepResult> {
- const scoped = await withContextScope(
- ctx,
- harnessSession,
- async (enriched) => {
- const result = await callback(enriched);
- return { result, session: result.session };
- },
- additionalProviders,
- );
-
- let result = { ...scoped.result, session: scoped.session };
- for (const provider of [...frameworkProviders, ...additionalProviders]) {
- if (provider.decorateStepResult !== undefined && ctx.has(provider.key)) {
- result = await provider.decorateStepResult(ctx.require(provider.key), result);
- }
- }
- return result;
+ const scoped = await withContextScope(ctx, harnessSession, async (enriched) => {
+ const result = await callback(enriched);
+ return { result, session: result.session };
+ });
+ return { ...scoped.result, session: scoped.session };
}
diff --git a/packages/eve/src/evals/assertions/run.test.ts b/packages/eve/src/evals/assertions/run.test.ts
index 27c37351b..4fbf5a4ac 100644
--- a/packages/eve/src/evals/assertions/run.test.ts
+++ b/packages/eve/src/evals/assertions/run.test.ts
@@ -224,20 +224,13 @@ describe("run assertions", () => {
subagentCall("child", "completed"),
subagentCall("child", "failed"),
subagentCall("child", "cancelled"),
- subagentCall("child", "input_required"),
],
- subagentCallCount: 5,
+ subagentCallCount: 4,
},
});
expect((await Run.calledSubagent("child").evaluate(result)).score).toBe(1);
- for (const status of [
- "working",
- "input_required",
- "completed",
- "failed",
- "cancelled",
- ] as const) {
+ for (const status of ["working", "completed", "failed", "cancelled"] as const) {
expect((await Run.calledSubagent("child", { status, count: 1 }).evaluate(result)).score).toBe(
1,
);
diff --git a/packages/eve/src/evals/assertions/run.ts b/packages/eve/src/evals/assertions/run.ts
index d908c208a..8ee86767a 100644
--- a/packages/eve/src/evals/assertions/run.ts
+++ b/packages/eve/src/evals/assertions/run.ts
@@ -367,7 +367,7 @@ export function outputMatches(schema: StandardSchemaV1): RunAssertion {
function joinCompletedMessages(events: readonly MessageStreamEvent[]): string {
const parts: string[] = [];
for (const evt of events) {
- if (evt.type === "message.completed" && evt.data.message !== null) {
+ if (evt.type === "message.completed") {
parts.push(evt.data.message);
}
}
diff --git a/packages/eve/src/evals/runner/derive-run-facts.test.ts b/packages/eve/src/evals/runner/derive-run-facts.test.ts
index 0a2109678..e91f7f5b3 100644
--- a/packages/eve/src/evals/runner/derive-run-facts.test.ts
+++ b/packages/eve/src/evals/runner/derive-run-facts.test.ts
@@ -317,7 +317,7 @@ describe("deriveRunFacts", () => {
type: "message.completed",
data: {
finishReason: "tool-calls",
- message: null,
+ message: "Checking.",
stepIndex: 1,
turnId: "t1",
sequence: 2,
@@ -347,80 +347,6 @@ describe("deriveRunFacts", () => {
expect(facts.reasoningBlockCount).toBe(2);
});
- it("keeps a working receipt working until an actual result arrives", () => {
- const admission: UnstampedMessageStreamEvent = {
- type: "subagent.completed",
- data: {
- callId: "c1",
- subagentName: "researcher",
- output: "working",
- backgroundTask: { status: "working", taskId: "task-1" },
- },
- };
- const receipt: UnstampedMessageStreamEvent = {
- type: "action.result",
- data: {
- sequence: 1,
- stepIndex: 0,
- turnId: "t1",
- status: "completed",
- result: {
- kind: "subagent-result",
- origin: "child",
- callId: "c1",
- subagentName: "researcher",
- backgroundTask: { status: "working", taskId: "task-1" },
- output: { status: "working", taskId: "task-1" },
- outcome: {
- kind: "parked",
- result: { kind: "succeeded", output: "working" },
- usageDelta: {
- inputTokens: 0,
- outputTokens: 0,
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- },
- },
- },
- },
- };
- const toolReceipt = actionResult({
- callId: "c1",
- toolName: "researcher",
- output: { agentId: "agent-1", status: "working", taskId: "task-1" },
- });
- for (const events of [
- [admission],
- [receipt],
- [toolReceipt],
- [admission, receipt],
- [receipt, admission],
- ]) {
- expect(derive(events).subagentCalls).toEqual([
- expect.objectContaining({ callId: "c1", status: "working" }),
- ]);
- expect(derive(events).subagentCalls[0]?.output).toBeUndefined();
- }
- const completed: UnstampedMessageStreamEvent = {
- type: "subagent.completed",
- data: { callId: "c1", subagentName: "researcher", output: "actual result" },
- };
- expect(derive([toolReceipt, completed, admission, receipt, toolReceipt]).subagentCalls).toEqual(
- [expect.objectContaining({ callId: "c1", status: "completed", output: "actual result" })],
- );
- for (const status of ["failed", "rejected"] as const) {
- const failure = subagentResult({
- callId: "c1",
- subagentName: "researcher",
- output: "child failed",
- status,
- });
- expect(derive([admission, failure, admission, receipt]).subagentCalls).toEqual([
- expect.objectContaining({ callId: "c1", status: "failed", output: "child failed" }),
- ]);
- }
- });
-
it("joins subagent.called with subagent.completed by call id", () => {
const events: UnstampedMessageStreamEvent[] = [
turnStarted("t1", 0),
diff --git a/packages/eve/src/evals/runner/derive-run-facts.ts b/packages/eve/src/evals/runner/derive-run-facts.ts
index 03c455739..9eb1a6580 100644
--- a/packages/eve/src/evals/runner/derive-run-facts.ts
+++ b/packages/eve/src/evals/runner/derive-run-facts.ts
@@ -1,4 +1,3 @@
-import { isJsonObjectValue } from "#shared/json.js";
import type { MessageStreamEvent } from "#protocol/message.js";
import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
import type { InputRequest } from "#shared/input.js";
@@ -34,11 +33,12 @@ export interface DeriveRunFactsOptions {
}
/**
- * Event types that only close out a turn. When the last meaningful event
- * before this epilogue is `input.requested`, the run ended parked on
- * unanswered HITL input.
+ * Event types that only park or close out a turn. When the last meaningful
+ * event before them is `input.requested`, the run ended parked on unanswered
+ * HITL input.
*/
-const TURN_EPILOGUE_EVENT_TYPES: ReadonlySet<MessageStreamEvent["type"]> = new Set([
+const PARKING_EVENT_TYPES: ReadonlySet<MessageStreamEvent["type"]> = new Set([
+ "turn.waiting",
"turn.completed",
"session.waiting",
"session.completed",
@@ -124,20 +124,14 @@ export function deriveRunFacts(
const call = ensureToolCall(result.callId, result.toolName, {});
call.output = result.output;
call.status = status;
- const output = result.output;
- if (
- status === "completed" &&
- isJsonObjectValue(output) &&
- output.status === "working" &&
- typeof output.taskId === "string" &&
- typeof output.agentId === "string"
- ) {
- ensureSubagentCall(result.callId, result.toolName);
+ // An agent tool runs as a workflow tool; its tool result settles the delegation.
+ const subagentCall = subagentCallsByCallId.get(result.callId);
+ if (subagentCall?.status === "working") {
+ subagentCall.output ??= result.output;
+ subagentCall.status = status === "rejected" ? "failed" : status;
}
} else if (result.kind === "subagent-result") {
const call = ensureSubagentCall(result.callId, result.subagentName);
- // A working receipt settles dispatch, not the delegated work.
- if (result.origin === "child" && result.backgroundTask !== undefined) break;
call.output = call.output ?? result.output;
if (result.origin === "child" && result.outcome.result.kind === "cancelled") {
call.status = "cancelled";
@@ -164,7 +158,7 @@ export function deriveRunFacts(
case "subagent.completed": {
const call = ensureSubagentCall(event.data.callId, event.data.subagentName);
- if (event.data.backgroundTask !== undefined || call.status !== "working") break;
+ if (call.status !== "working") break;
call.output = event.data.output;
call.status = "completed";
break;
@@ -228,14 +222,15 @@ export function createEmptyDerivedFacts(): EveEvalDerivedFacts {
}
/**
- * A run ended parked when the last event before the turn epilogue
- * (`turn.completed` → `session.waiting`) is `input.requested`: the harness
- * surfaced HITL requests and stopped without resolving them.
+ * A run ended parked when the last event before its parking events is
+ * `input.requested`: either the turn ended on the request (`turn.completed` →
+ * `session.waiting`), or a call the turn runs asked and the open turn parked
+ * (`turn.waiting`).
*/
function endedParkedOnInput(events: readonly MessageStreamEvent[]): boolean {
for (let i = events.length - 1; i >= 0; i--) {
const event = events[i];
- if (event === undefined || TURN_EPILOGUE_EVENT_TYPES.has(event.type)) continue;
+ if (event === undefined || PARKING_EVENT_TYPES.has(event.type)) continue;
return event.type === "input.requested";
}
return false;
diff --git a/packages/eve/src/evals/session-content.ts b/packages/eve/src/evals/session-content.ts
index d80c8cb54..da087336c 100644
--- a/packages/eve/src/evals/session-content.ts
+++ b/packages/eve/src/evals/session-content.ts
@@ -8,7 +8,7 @@ export function formatEvalTranscript(events: readonly MessageStreamEvent[]): str
for (const event of events) {
if (event.type === "message.received") {
messages.push(`User:\n${event.data.message}`);
- } else if (event.type === "message.completed" && event.data.message !== null) {
+ } else if (event.type === "message.completed") {
messages.push(`Assistant:\n${event.data.message}`);
}
}
diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.ts
index 4c420d171..3b05d6014 100644
--- a/packages/eve/src/evals/session.ts
+++ b/packages/eve/src/evals/session.ts
@@ -14,11 +14,16 @@ import type {
import type {
MessageStreamEvent,
RuntimeTraceContext,
+ AgentStartedStreamEvent,
SubagentCalledStreamEvent,
TurnFailureStreamEvent,
} from "#protocol/message.js";
-import { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";
-import { summarizeTurnEvents } from "#client/session-utils.js";
+import { isTurnFailureEvent } from "#protocol/message.js";
+import {
+ isTurnSegmentBoundary,
+ summarizeTurnEvents,
+ updatePendingInputRequests,
+} from "#client/session-utils.js";
import { extractCompletedResult } from "#client/output-schema.js";
import type { InputRequest, InputResponse } from "#shared/input.js";
import { deriveRunFacts } from "#evals/runner/derive-run-facts.js";
@@ -147,10 +152,10 @@ export class EvalSessionDriver implements EveEvalSession {
}
streamSubagent(
- called: SubagentCalledStreamEvent,
+ started: AgentStartedStreamEvent | SubagentCalledStreamEvent,
options: StreamOptions = {},
): AsyncIterable<MessageStreamEvent> {
- return this.#session.streamSubagent(called, {
+ return this.#session.streamSubagent(started, {
...options,
signal: options.signal ?? this.#signal,
});
@@ -444,8 +449,10 @@ class EvalLiveTurn implements EveEvalLiveTurn {
): Promise<EveEvalTurn> {
try {
let sawBoundary = false;
+ const pendingInputRequests = new Set<string>();
for await (const event of source) {
this.#events.push(event);
+ updatePendingInputRequests(pendingInputRequests, event);
observe(event);
this.#resolveWaiters(event);
@@ -457,7 +464,7 @@ class EvalLiveTurn implements EveEvalLiveTurn {
);
}
- if (isCurrentTurnBoundaryEvent(event)) {
+ if (isTurnSegmentBoundary(event, pendingInputRequests)) {
sawBoundary = true;
this.#closeWaiters(
new Error(`Session ${this.sessionId} reached ${event.type} before the expected event.`),
diff --git a/packages/eve/src/evals/types.ts b/packages/eve/src/evals/types.ts
index c66392cc2..208d326cb 100644
--- a/packages/eve/src/evals/types.ts
+++ b/packages/eve/src/evals/types.ts
@@ -5,6 +5,7 @@ import type {
RuntimeIdentity,
RuntimeTraceContext,
MessageStreamEvent,
+ AgentStartedStreamEvent,
SubagentCalledStreamEvent,
} from "#protocol/message.js";
import type {
@@ -17,7 +18,6 @@ import type {
} from "#client/types.js";
import type { InputRequest, InputResponse } from "#shared/input.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
-import type { TaskStatus } from "#tasks/types.js";
import type { AgentModelOptionsDefinition } from "#shared/agent-definition.js";
import type { EvalReporter } from "#evals/runner/reporters/types.js";
import type {
@@ -65,8 +65,8 @@ export interface EveEvalSubagentCall {
readonly remoteUrl?: string;
/** Output from the matching `subagent.completed` event; `undefined` when the call never completed. */
readonly output?: JsonValue;
- /** Task lifecycle status inferred from the captured delegation events. */
- readonly status: TaskStatus;
+ /** Delegation status inferred from the captured delegation events. */
+ readonly status: "working" | "completed" | "failed" | "cancelled";
/** Zero-based index of the turn the delegation happened in. */
readonly turnIndex: number;
/** Owning session id, when the runner knows it. */
@@ -333,7 +333,7 @@ interface EveEvalSessionDriver {
* children use the parent-origin proxy.
*/
streamSubagent(
- called: SubagentCalledStreamEvent,
+ started: AgentStartedStreamEvent | SubagentCalledStreamEvent,
options?: StreamOptions,
): AsyncIterable<MessageStreamEvent>;
}
diff --git a/packages/eve/src/eve-channel/create-request.ts b/packages/eve/src/eve-channel/create-request.ts
index 598c2f234..467b63cb3 100644
--- a/packages/eve/src/eve-channel/create-request.ts
+++ b/packages/eve/src/eve-channel/create-request.ts
@@ -4,12 +4,10 @@ import type {
ActivityObserverConfig,
SessionCallback,
SessionCapabilities,
- TaskDeliveryPolicy,
} from "#channel/types.js";
import type { JsonObject } from "#shared/json.js";
export interface ParsedCreateBody {
- taskDeliveryPolicy?: TaskDeliveryPolicy;
activityObserver?: ActivityObserverConfig;
callback?: SessionCallback;
capabilities?: SessionCapabilities;
diff --git a/packages/eve/src/eve-channel/delivery-policy-request.ts b/packages/eve/src/eve-channel/delivery-policy-request.ts
deleted file mode 100644
index 6246746d9..000000000
--- a/packages/eve/src/eve-channel/delivery-policy-request.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import type { UserContent } from "ai";
-import type { TaskDeliveryPolicy, TurnPolicy } from "#channel/types.js";
-
-export function parseTaskDeliveryPolicyField(
- value: unknown,
- message: string | UserContent | undefined,
-): TaskDeliveryPolicy | undefined | Response {
- if (value === undefined) return undefined;
- if (value !== "auto" && value !== "cohort") {
- return Response.json(
- { error: "Expected 'taskDeliveryPolicy' to be either 'auto' or 'cohort'.", ok: false },
- { status: 400 },
- );
- }
- if (message === undefined) {
- return Response.json(
- { error: "'taskDeliveryPolicy' requires a non-empty 'message'.", ok: false },
- { status: 400 },
- );
- }
- return value;
-}
-
-export function parseTurnPolicyField(value: unknown): TurnPolicy | Response | undefined {
- if (value === undefined) return undefined;
- if (value === "queue" || value === "steer") return value;
- return Response.json(
- { error: "Expected 'turnPolicy' to be either 'queue' or 'steer'.", ok: false },
- { status: 400 },
- );
-}
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index 388410e00..73afda89d 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -6,7 +6,6 @@ import { resolveForwardedPrincipal } from "#channel/forwarded-principal.js";
import { handleConnectionCallbackRequest } from "#execution/connections/callback-route.js";
import { handleActivityRequest } from "#execution/activity-route.js";
import { handleSessionCallbackRequest } from "#subagents/callback-route.js";
-import { handleTaskInputResponseRequest } from "#execution/task-input-response-route.js";
import {
handleWorkflowWebhookRequest,
WORKFLOW_WEBHOOK_ROUTE_PATTERN,
@@ -23,8 +22,8 @@ import {
EVE_STREAM_FORMAT_HEADER,
EVE_STREAM_TAIL_INDEX_HEADER,
EVE_STREAM_VERSION_HEADER,
- type SubagentCalledStreamEvent,
} from "#protocol/message.js";
+import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";
import {
EVE_ACTIVITY_ROUTE_PATTERN,
EVE_CALLBACK_ROUTE_PATTERN,
@@ -39,7 +38,6 @@ import {
EVE_SESSION_RESET_ROUTE_PATTERN,
EVE_SESSION_STREAM_ROUTE_PATTERN,
EVE_SUBAGENT_STREAM_ROUTE_PATTERN,
- EVE_TASK_INPUT_ROUTE_PATTERN,
createEveSessionStreamRoutePath,
createEveSubagentStreamRoutePath,
} from "#protocol/routes.js";
@@ -78,9 +76,11 @@ import {
requireSessionId,
} from "#eve-channel/request.js";
import { attachClientContext } from "#internal/client-context.js";
+import type { ParsedCreateBody } from "#eve-channel/create-request.js";
import {
- findRemoteSubagentBinding,
+ findRemoteAgentBinding,
healthResponse,
+ type RemoteAgentBinding,
normalizeEveCors,
resolveOnMessage,
} from "#eve-channel/support.js";
@@ -99,6 +99,18 @@ const log = createLogger("eve.channel");
* Default-export the result as your `agent/channels/eve.ts` channel; reach for
* {@link defineChannel} directly only for a custom transport.
*/
+/** A delegating caller checks that this deployment speaks its remote agent protocol. */
+function createdSessionBody(sessionId: string, body: ParsedCreateBody) {
+ const created: {
+ ok: true;
+ protocolVersion?: number;
+ sessionId: string;
+ status: "accepted";
+ } = { ok: true, sessionId, status: "accepted" };
+ if (body.callback !== undefined) created.protocolVersion = REMOTE_AGENT_PROTOCOL_VERSION;
+ return created;
+}
+
export function eveChannel(input: EveChannelInput): EveChannel {
const uploadPolicy = mergeUploadPolicy(input.uploadPolicy);
@@ -140,7 +152,6 @@ export function eveChannel(input: EveChannelInput): EveChannel {
POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN, handleConnectionCallbackRequest),
POST(EVE_ACTIVITY_ROUTE_PATTERN, handleActivityRequest),
POST(EVE_CALLBACK_ROUTE_PATTERN, handleSessionCallbackRequest),
- POST(EVE_TASK_INPUT_ROUTE_PATTERN, handleTaskInputResponseRequest),
GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),
POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),
PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),
@@ -234,16 +245,13 @@ export function eveChannel(input: EveChannelInput): EveChannel {
if (operationToken !== undefined) {
const owner = await args.resolveSession(operationToken);
if (owner !== undefined) {
- return Response.json(
- { ok: true, sessionId: owner.id, status: "accepted" },
- {
- headers: {
- "cache-control": "no-store",
- [EVE_SESSION_ID_HEADER]: owner.id,
- },
- status: 202,
+ return Response.json(createdSessionBody(owner.id, body), {
+ headers: {
+ "cache-control": "no-store",
+ [EVE_SESSION_ID_HEADER]: owner.id,
},
- );
+ status: 202,
+ });
}
}
@@ -308,7 +316,6 @@ export function eveChannel(input: EveChannelInput): EveChannel {
let handle: Awaited<ReturnType<typeof createSession>>;
try {
handle = await createSession({
- taskDeliveryPolicy: body.taskDeliveryPolicy,
activityObserver: body.activityObserver,
audienceAuth: authResult,
auth: messageResult.auth,
@@ -340,16 +347,13 @@ export function eveChannel(input: EveChannelInput): EveChannel {
);
}
- return Response.json(
- { ok: true, sessionId: handle.sessionId, status: "accepted" },
- {
- headers: {
- "cache-control": "no-store",
- [EVE_SESSION_ID_HEADER]: handle.sessionId,
- },
- status: 202,
+ return Response.json(createdSessionBody(handle.sessionId, body), {
+ headers: {
+ "cache-control": "no-store",
+ [EVE_SESSION_ID_HEADER]: handle.sessionId,
},
- );
+ status: 202,
+ });
}),
POST(EVE_SESSION_ROUTE_PATTERN, async (req, { attachSession, params }) => {
@@ -394,7 +398,6 @@ export function eveChannel(input: EveChannelInput): EveChannel {
const session = attachSession(sessionId);
const options = attachClientContext(
{
- taskDeliveryPolicy: body.taskDeliveryPolicy,
activityObserver: body.activityObserver,
auth: dispatchAuth,
callback: body.callback,
@@ -456,11 +459,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
if (body instanceof Response) return body;
let result: Awaited<ReturnType<Session["cancel"]>>;
try {
- result = await attachSession(sessionId).cancel({
- taskId: body.taskId,
- tasks: body.tasks,
- turnId: body.turnId,
- });
+ result = await attachSession(sessionId).cancel({ turnId: body.turnId });
} catch (error) {
const errorId = logError(log, "cancel-turn request failed", error, { sessionId });
return Response.json(
@@ -607,10 +606,10 @@ export function eveChannel(input: EveChannelInput): EveChannel {
childSessionId,
parentSessionId,
});
- let binding: SubagentCalledStreamEvent;
+ let binding: RemoteAgentBinding;
try {
const parent = args.attachSession(parentSessionId);
- const found = await findRemoteSubagentBinding({
+ const found = await findRemoteAgentBinding({
callId,
childSessionId,
childStreamPath,
@@ -638,18 +637,14 @@ export function eveChannel(input: EveChannelInput): EveChannel {
let headers: Record<string, string>;
try {
- headers = await resolveHeaders({
- name: binding.data.toolName,
- resolverId: binding.data.remote!.resolverId,
- url: binding.data.remote!.url,
- });
+ headers = await resolveHeaders(binding);
} catch {
return Response.json({ error: "Subagent stream not found.", ok: false }, { status: 404 });
}
const upstreamUrl = new URL(
createEveSessionStreamRoutePath(childSessionId).replace(/^\/+/, ""),
- `${binding.data.remote!.url.replace(/\/+$/, "")}/`,
+ `${binding.url.replace(/\/+$/, "")}/`,
);
if (startIndex !== undefined) {
upstreamUrl.searchParams.set("startIndex", String(startIndex));
diff --git a/packages/eve/src/eve-channel/request.activity.test.ts b/packages/eve/src/eve-channel/request.activity.test.ts
index 80d1232fc..c3b0c1ca8 100644
--- a/packages/eve/src/eve-channel/request.activity.test.ts
+++ b/packages/eve/src/eve-channel/request.activity.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { parseCreateBody } from "#eve-channel/request.js";
+import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";
const sink = {
url: "https://parent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
@@ -29,6 +30,7 @@ describe("parseCreateBody activity relay", () => {
callback,
activityObserver: { sink, workIdentity },
message: "research this",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
).toMatchObject({ callback, activityObserver: { sink, workIdentity } });
});
@@ -47,6 +49,7 @@ describe("parseCreateBody activity relay", () => {
callback,
activityObserver: { sink, workIdentity: identity },
message: "hi",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
});
expect(response).toBeInstanceOf(Response);
expect((response as Response).status).toBe(400);
@@ -60,6 +63,7 @@ describe("parseCreateBody activity relay", () => {
workIdentity,
},
message: "hi",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
});
expect(response).toBeInstanceOf(Response);
expect((response as Response).status).toBe(400);
diff --git a/packages/eve/src/eve-channel/request.cancel.test.ts b/packages/eve/src/eve-channel/request.cancel.test.ts
deleted file mode 100644
index a6cb499cc..000000000
--- a/packages/eve/src/eve-channel/request.cancel.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { parseCancelTurnBody } from "#eve-channel/request.js";
-
-describe("parseCancelTurnBody", () => {
- it("parses session-owned task cancellation", async () => {
- const result = await parseCancelTurnBody(
- new Request("https://eve.test/eve/v1/session/session_1/cancel", {
- body: JSON.stringify({ tasks: true, turnId: "turn_1" }),
- method: "POST",
- }),
- );
-
- expect(result).toEqual({ tasks: true, turnId: "turn_1" });
- });
-
- it.each([null, 1, "true", []])("rejects a non-boolean tasks value %o", async (tasks) => {
- const result = await parseCancelTurnBody(
- new Request("https://eve.test/eve/v1/session/session_1/cancel", {
- body: JSON.stringify({ tasks }),
- method: "POST",
- }),
- );
-
- expect(result).toBeInstanceOf(Response);
- if (!(result instanceof Response)) return;
- expect(result.status).toBe(400);
- await expect(result.json()).resolves.toEqual({
- error: "Expected 'tasks' to be a boolean.",
- ok: false,
- });
- });
-});
diff --git a/packages/eve/src/eve-channel/request.task-policy.test.ts b/packages/eve/src/eve-channel/request.task-policy.test.ts
deleted file mode 100644
index c4760183e..000000000
--- a/packages/eve/src/eve-channel/request.task-policy.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { parseCreateBody, parseSessionMessageBody } from "#eve-channel/request.js";
-
-describe("task delivery policy on HTTP sends", () => {
- it.each([parseCreateBody, parseSessionMessageBody])("validates policy at %s", async (parse) => {
- for (const taskDeliveryPolicy of ["auto", "cohort"] as const) {
- expect(parse({ message: "Prepare reports", taskDeliveryPolicy })).toMatchObject({
- taskDeliveryPolicy,
- });
- }
- const messageFree = parse({ taskDeliveryPolicy: "cohort" });
- expect(messageFree).toBeInstanceOf(Response);
- expect((messageFree as Response).status).toBe(400);
- const invalid = parse({ message: "Prepare reports", taskDeliveryPolicy: "individual" });
- expect(invalid).toBeInstanceOf(Response);
- expect((invalid as Response).status).toBe(400);
- expect(await (invalid as Response).json()).toMatchObject({
- error: expect.stringContaining("taskDeliveryPolicy"),
- });
- });
-});
diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.ts
index 437b891d1..c350f74fd 100644
--- a/packages/eve/src/eve-channel/request.ts
+++ b/packages/eve/src/eve-channel/request.ts
@@ -6,7 +6,6 @@ import type {
SessionCallback,
SessionCapabilities,
TurnPolicy,
- TaskDeliveryPolicy,
} from "#channel/types.js";
import type { Session } from "#channel/session.js";
import { parseSessionCallback } from "#channel/session-callback.js";
@@ -27,6 +26,11 @@ import {
EVE_STREAM_TAIL_INDEX_HEADER,
EVE_STREAM_VERSION_HEADER,
} from "#protocol/message.js";
+import {
+ REMOTE_AGENT_PROTOCOL_MISMATCH,
+ REMOTE_AGENT_PROTOCOL_VERSION,
+ readRemoteAgentProtocolVersion,
+} from "#protocol/remote-agent-protocol.js";
import {
collectUploadPolicyViolations,
formatUploadPolicyViolation,
@@ -34,10 +38,7 @@ import {
} from "#public/channels/upload-policy.js";
import { isInputResponse, type ValidatedInputResponse } from "#shared/input.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
-import {
- parseTaskDeliveryPolicyField,
- parseTurnPolicyField,
-} from "#eve-channel/delivery-policy-request.js";
+import { parseTurnPolicyField } from "#eve-channel/turn-policy-request.js";
import { type ParsedCreateBody, validateMessageFreeCreate } from "#eve-channel/create-request.js";
const SESSION_STREAM_HEARTBEAT_MS = 10_000;
@@ -78,6 +79,10 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB
const callback = parseCallbackField(payload.callback);
if (callback instanceof Response) return callback;
+ if (callback !== undefined) {
+ const protocolRejection = rejectRemoteAgentProtocolMismatch(payload.protocolVersion);
+ if (protocolRejection !== undefined) return protocolRejection;
+ }
const capabilities = parseCapabilitiesField(payload.capabilities);
if (capabilities instanceof Response) return capabilities;
@@ -89,8 +94,6 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB
if (observerRejection !== undefined) return observerRejection;
}
- const taskDeliveryPolicy = parseTaskDeliveryPolicyField(payload.taskDeliveryPolicy, message);
- if (taskDeliveryPolicy instanceof Response) return taskDeliveryPolicy;
const outputSchema = parseOutputSchemaField(payload.outputSchema);
if (outputSchema instanceof Response) return outputSchema;
@@ -113,7 +116,6 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB
}
const result: ParsedCreateBody = {
- taskDeliveryPolicy,
activityObserver,
callback,
capabilities,
@@ -126,7 +128,6 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB
}
interface ParsedSessionMessageBody {
- taskDeliveryPolicy?: TaskDeliveryPolicy;
activityObserver?: ActivityObserverConfig;
callback?: SessionCallback;
message?: string | UserContent;
@@ -156,8 +157,6 @@ export function parseSessionMessageBody(
if (inputResponses instanceof Response) return inputResponses;
const context = parseClientContextField(payload.clientContext);
if (context instanceof Response) return context;
- const taskDeliveryPolicy = parseTaskDeliveryPolicyField(payload.taskDeliveryPolicy, message);
- if (taskDeliveryPolicy instanceof Response) return taskDeliveryPolicy;
const outputSchema = parseOutputSchemaField(payload.outputSchema);
if (outputSchema instanceof Response) return outputSchema;
const turnPolicy = parseTurnPolicyField(payload.turnPolicy);
@@ -188,13 +187,10 @@ export function parseSessionMessageBody(
context,
outputSchema,
turnPolicy,
- taskDeliveryPolicy,
};
}
interface ParsedCancelTurnBody {
- taskId?: string;
- tasks?: boolean;
turnId?: string;
}
@@ -205,31 +201,13 @@ export async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTur
if (tokenRejection !== null) return tokenRejection;
const turnId = payload.turnId;
- const taskId = payload.taskId;
- const tasks = payload.tasks;
if (turnId !== undefined && (typeof turnId !== "string" || turnId.length === 0)) {
return Response.json(
{ error: "Expected 'turnId' to be a non-empty string.", ok: false },
{ status: 400 },
);
}
- if (tasks !== undefined && typeof tasks !== "boolean") {
- return Response.json(
- { error: "Expected 'tasks' to be a boolean.", ok: false },
- { status: 400 },
- );
- }
- if (taskId !== undefined && (typeof taskId !== "string" || taskId.length === 0)) {
- return Response.json(
- { error: "Expected 'taskId' to be a non-empty string.", ok: false },
- { status: 400 },
- );
- }
- const result: ParsedCancelTurnBody = {};
- if (typeof taskId === "string") result.taskId = taskId;
- if (typeof tasks === "boolean") result.tasks = tasks;
- if (typeof turnId === "string") result.turnId = turnId;
- return result;
+ return typeof turnId === "string" ? { turnId } : {};
}
export async function parseJsonRequest(req: Request): Promise<Record<string, unknown> | Response> {
@@ -369,6 +347,21 @@ function parseCallbackField(value: unknown): SessionCallback | Response | undefi
return Response.json({ error: parsed.message, ok: false }, { status: 400 });
}
+/** Delegating callers must speak this deployment's remote agent protocol. */
+function rejectRemoteAgentProtocolMismatch(value: unknown): Response | undefined {
+ const callerVersion = readRemoteAgentProtocolVersion(value);
+ if (callerVersion === REMOTE_AGENT_PROTOCOL_VERSION) return undefined;
+ return Response.json(
+ {
+ code: REMOTE_AGENT_PROTOCOL_MISMATCH,
+ error: `This deployment speaks eve remote agent protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}, but the caller speaks protocol ${String(callerVersion)}. Upgrade both deployments to the same eve release.`,
+ ok: false,
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
+ },
+ { status: 409 },
+ );
+}
+
function parseCapabilitiesField(value: unknown): SessionCapabilities | Response | undefined {
if (value === undefined) return undefined;
if (value === null || typeof value !== "object" || Array.isArray(value)) {
diff --git a/packages/eve/src/eve-channel/support.ts b/packages/eve/src/eve-channel/support.ts
index 09a21078a..a072864f0 100644
--- a/packages/eve/src/eve-channel/support.ts
+++ b/packages/eve/src/eve-channel/support.ts
@@ -3,7 +3,7 @@ import type { UserContent } from "ai";
import type { SessionAuthContext } from "#channel/types.js";
import { workflowEntryReference } from "#execution/workflow-runtime.js";
import { createLogger, logError } from "#internal/logging.js";
-import type { MessageStreamEvent, SubagentCalledStreamEvent } from "#protocol/message.js";
+import type { MessageStreamEvent } from "#protocol/message.js";
import type { ChannelCors } from "#public/definitions/channel.js";
import {
defaultEveAuth,
@@ -25,37 +25,45 @@ export function healthResponse(): Response {
});
}
-export async function findRemoteSubagentBinding(input: {
+/** Where a remote child the parent session recorded runs, and its credential key. */
+export interface RemoteAgentBinding {
+ readonly name: string;
+ readonly resolverId?: string;
+ readonly url: string;
+}
+
+interface RemoteAgentStreamCoordinates {
readonly callId: string;
readonly childSessionId: string;
readonly childStreamPath: string;
readonly parentSessionId: string;
- readonly parent: {
- getEventStream(options?: { startIndex?: number }): Promise<ReadableStream<MessageStreamEvent>>;
- getStreamTailIndex(): Promise<number>;
- };
-}): Promise<SubagentCalledStreamEvent | undefined> {
+}
+
+/**
+ * Finds the remote child the parent session recorded for one proxy route, from
+ * its `agent.started` event or, for the model's agent tools, `subagent.called`.
+ */
+export async function findRemoteAgentBinding(
+ input: RemoteAgentStreamCoordinates & {
+ readonly parent: {
+ getEventStream(options?: {
+ startIndex?: number;
+ }): Promise<ReadableStream<MessageStreamEvent>>;
+ getStreamTailIndex(): Promise<number>;
+ };
+ },
+): Promise<RemoteAgentBinding | undefined> {
const tailIndex = await input.parent.getStreamTailIndex();
if (tailIndex < 0) return undefined;
const events = await input.parent.getEventStream({ startIndex: 0 });
const reader = events.getReader();
- let binding: SubagentCalledStreamEvent | undefined;
+ let binding: RemoteAgentBinding | undefined;
try {
for (let index = 0; index <= tailIndex; index += 1) {
const next = await reader.read();
if (next.done) break;
- const event = next.value;
- if (
- event.type === "subagent.called" &&
- event.data.sessionId === input.parentSessionId &&
- event.data.callId === input.callId &&
- event.data.childSessionId === input.childSessionId &&
- event.data.childStreamPath === input.childStreamPath &&
- event.data.remote !== undefined
- ) {
- binding = event;
- }
+ binding = readRemoteAgentBinding(next.value, input) ?? binding;
}
} finally {
await reader.cancel().catch(() => {});
@@ -63,6 +71,33 @@ export async function findRemoteSubagentBinding(input: {
return binding;
}
+function readRemoteAgentBinding(
+ event: MessageStreamEvent,
+ coordinates: RemoteAgentStreamCoordinates,
+): RemoteAgentBinding | undefined {
+ if (event.type === "agent.started") {
+ const { data } = event;
+ // The stream path embeds the parent session id, so matching it binds the parent.
+ const matches =
+ data.callId === coordinates.callId &&
+ data.sessionId === coordinates.childSessionId &&
+ data.streamPath === coordinates.childStreamPath;
+ if (!matches || data.remote === undefined) return undefined;
+ return { name: data.name, ...data.remote };
+ }
+ if (event.type === "subagent.called") {
+ const { data } = event;
+ const matches =
+ data.sessionId === coordinates.parentSessionId &&
+ data.callId === coordinates.callId &&
+ data.childSessionId === coordinates.childSessionId &&
+ data.childStreamPath === coordinates.childStreamPath;
+ if (!matches || data.remote === undefined) return undefined;
+ return { name: data.toolName, ...data.remote };
+ }
+ return undefined;
+}
+
export function normalizeEveCors(cors: EveChannelCors | undefined): ChannelCors {
if (cors === undefined || cors === false) {
return false;
diff --git a/packages/eve/src/eve-channel/turn-policy-request.ts b/packages/eve/src/eve-channel/turn-policy-request.ts
new file mode 100644
index 000000000..620c06188
--- /dev/null
+++ b/packages/eve/src/eve-channel/turn-policy-request.ts
@@ -0,0 +1,10 @@
+import type { TurnPolicy } from "#channel/types.js";
+
+export function parseTurnPolicyField(value: unknown): TurnPolicy | Response | undefined {
+ if (value === undefined) return undefined;
+ if (value === "queue" || value === "steer") return value;
+ return Response.json(
+ { error: "Expected 'turnPolicy' to be either 'queue' or 'steer'.", ok: false },
+ { status: 400 },
+ );
+}
diff --git a/packages/eve/src/execution/activity-cohort.ts b/packages/eve/src/execution/activity-cohort.ts
index 814f4e1fd..76ac9b963 100644
--- a/packages/eve/src/execution/activity-cohort.ts
+++ b/packages/eve/src/execution/activity-cohort.ts
@@ -19,17 +19,12 @@ export function updateActivityRootForDelivery(input: {
readonly ctx: ContextContainer;
readonly delivery?: DeliverHookPayload;
readonly sessionState: SessionStateMap | undefined;
- readonly taskRootTurnId?: string;
}): void {
if (!input.ctx.has(ActivityObserverKey)) return;
- if (input.taskRootTurnId !== undefined) {
- input.ctx.set(ActivityRootTurnIdKey, input.taskRootTurnId);
- return;
- }
const delivery = input.delivery;
if (delivery === undefined) return;
const hasMessage = delivery.payloads.some((payload) => payload.message !== undefined);
- if (hasMessage && delivery.taskDeliveryId === undefined) {
+ if (hasMessage) {
input.ctx.set(ActivityRootTurnIdKey, input.activeTurnId);
input.ctx.delete(ActivityPendingBlockersKey);
return;
diff --git a/packages/eve/src/execution/activity-events.test.ts b/packages/eve/src/execution/activity-events.test.ts
index d3a24525f..2bb9ca1b5 100644
--- a/packages/eve/src/execution/activity-events.test.ts
+++ b/packages/eve/src/execution/activity-events.test.ts
@@ -273,40 +273,4 @@ describe("projectActivityEvents", () => {
},
]);
});
-
- it("keeps delegated work active for a background receipt", () => {
- expect(
- projectActivityEvents({
- at: "2026-01-01T00:00:02Z",
- event: {
- data: {
- result: {
- backgroundTask: { status: "working", taskId: "task-1" },
- callId: "child-1",
- kind: "subagent-result",
- origin: "child",
- outcome: {
- kind: "parked",
- result: { kind: "succeeded", output: "working" },
- usageDelta: {
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- inputTokens: 0,
- outputTokens: 0,
- },
- },
- output: "working",
- subagentName: "researcher",
- },
- sequence: 0,
- status: "completed",
- stepIndex: 0,
- turnId: "turn",
- },
- type: "action.result",
- },
- lineage: { ...lineage, sessionId: "root", turnId: "turn" },
- }),
- ).toEqual([]);
- });
});
diff --git a/packages/eve/src/execution/activity-events.ts b/packages/eve/src/execution/activity-events.ts
index 23ef78707..91f758651 100644
--- a/packages/eve/src/execution/activity-events.ts
+++ b/packages/eve/src/execution/activity-events.ts
@@ -62,7 +62,6 @@ export function projectActivityEvents(input: {
if (event.type === "action.result") {
const result = event.data.result;
if (result.kind === "subagent-result") {
- if ("backgroundTask" in result && result.backgroundTask !== undefined) return [];
const workId = deriveChildActivityWorkId({
callId: result.callId,
parentSessionId: lineage.sessionId ?? lineage.rootSessionId,
diff --git a/packages/eve/src/execution/activity-work.ts b/packages/eve/src/execution/activity-work.ts
index 78dd40d6c..fd6006c0e 100644
--- a/packages/eve/src/execution/activity-work.ts
+++ b/packages/eve/src/execution/activity-work.ts
@@ -20,33 +20,6 @@ export function deriveRootTurnWorkIdentity(session: Session): ActivityWorkIdenti
};
}
-export function deriveBackgroundTaskActivityObserver(input: {
- readonly activityObserver: ActivityObserverConfig | undefined;
- readonly callId: string;
- readonly label?: string;
- readonly name: string;
- readonly parentSessionId: string;
- readonly parentTurnId: string;
- readonly rootSessionId: string;
-}): ActivityObserverConfig | undefined {
- if (input.activityObserver === undefined) return undefined;
- const parentWork = input.activityObserver.workIdentity ?? {
- id: deriveRootTurnActivityWorkId({
- sessionId: input.parentSessionId,
- turnId: input.parentTurnId,
- }),
- kind: "root-turn" as const,
- rootSessionId: input.rootSessionId,
- rootTurnId: input.parentTurnId,
- sessionId: input.parentSessionId,
- turnId: input.parentTurnId,
- };
- return {
- sink: input.activityObserver.sink,
- workIdentity: deriveChildWorkIdentity({ ...input, kind: "task", parentWork }),
- };
-}
-
export function deriveChildActivityObserverConfig(input: {
readonly callId: string;
readonly kind: Exclude<ActivityWorkKind, "root-turn">;
diff --git a/packages/eve/src/execution/agent-messaging.scenario.test.ts b/packages/eve/src/execution/agent-messaging.scenario.test.ts
deleted file mode 100644
index d6f0c35e4..000000000
--- a/packages/eve/src/execution/agent-messaging.scenario.test.ts
+++ /dev/null
@@ -1,480 +0,0 @@
-import { spawn, type ChildProcessByStdio } from "node:child_process";
-import { join } from "node:path";
-import type { Readable } from "node:stream";
-
-import { describe, expect, it } from "vitest";
-
-import { Client } from "#client/client.js";
-import { filterEventsByType } from "#internal/testing/events.js";
-import { type ScenarioAppDescriptor, useScenarioApp } from "#internal/testing/scenario-app.js";
-import type { HandleMessageStreamEvent } from "#protocol/message.js";
-
-const scenarioApp = useScenarioApp();
-const SCENARIO_TIMEOUT_MS = 360_000;
-const EVENT_TIMEOUT_MS = 30_000;
-const CODEWORD = "LANTERN-COMET-7319";
-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 toolName = "run-program";
- const firstProgram = `return ctx.agent(${JSON.stringify(subagentName)}, { message: ${JSON.stringify(`Remember the codeword ${CODEWORD}. Confirm that you stored it.`)} });`;
- const secondProgram = (agentIdExpression: string) =>
- `return ctx.agent(${JSON.stringify(subagentName)}, { agentId: ${agentIdExpression}, message: "What codeword did I ask you to remember? Reply with the codeword." });`;
-
- return `import { defineAgent } from "eve";
-import { mockModel } from "eve/evals";
-
-const CODEWORD = ${JSON.stringify(CODEWORD)};
-const SUBAGENT_NAME = ${JSON.stringify(subagentName)};
-const AGENT_ID_PATTERN = new RegExp(${JSON.stringify(agentIdPattern)}, "u");
-
-const model = mockModel((request) => {
- const firstResult = request.toolResults.find((result) => result.id === "memory-exchange-1");
- if (request.userMessageCount === 1) {
- if (firstResult !== undefined) return "FIRST_EXCHANGE_COMPLETE";
- return {
- toolCalls: [
- {
- id: "memory-exchange-1",
- input: { js: ${JSON.stringify(firstProgram)} },
- name: ${JSON.stringify(toolName)},
- },
- ],
- };
- }
-
- const secondResult = request.toolResults.find((result) => result.id === "memory-exchange-2");
- if (request.userMessageCount === 2) {
- if (secondResult !== undefined) {
- if (typeof secondResult.output !== "string") {
- throw new Error("Second child result was not text.");
- }
- return \`PARENT_RECALLED=\${secondResult.output}\`;
- }
- const agentsSnippet = request.messages.map((message) => message.text).join("\\n");
- const agentId = AGENT_ID_PATTERN.exec(agentsSnippet)?.[1];
- if (agentId === undefined) {
- throw new Error(\`Parent model did not receive a \${SUBAGENT_NAME} agent id.\`);
- }
- return {
- toolCalls: [
- {
- id: "memory-exchange-2",
- input: {
- js: ${JSON.stringify(secondProgram("__AGENT_ID__"))}.replace("__AGENT_ID__", JSON.stringify(agentId)),
- },
- name: ${JSON.stringify(toolName)},
- },
- ],
- };
- }
-
- throw new Error("Parent model received an unexpected conversation length.");
-});
-export default defineAgent({
- model,
- modelContextWindowTokens: 32_000,
-});
-`;
-}
-
-const EVE_CHANNEL_SOURCE = `import { none } from "eve/channels/auth";
-import { eveChannel } from "eve/channels/eve";
-
-export default eveChannel({ auth: none() });
-`;
-
-const AUTHENTICATED_EVE_CHANNEL_SOURCE = `import { eveChannel } from "eve/channels/eve";
-
-export default eveChannel({
- auth(request) {
- if (request.headers.get("authorization") !== "Bearer ${REMOTE_MEMORY_TOKEN}") return null;
- return {
- attributes: {},
- authenticator: "scenario-bearer",
- principalId: "remote-memory-parent",
- principalType: "service",
- };
- },
-});
-`;
-
-const MEMORY_AGENT_SOURCE = `import { defineAgent } from "eve";
-import { mockModel } from "eve/evals";
-
-const CODEWORD = ${JSON.stringify(CODEWORD)};
-
-const model = mockModel((request) => {
- if (request.userMessageCount === 1) {
- return request.lastUserMessage?.includes(CODEWORD) === true
- ? \`STORED=\${CODEWORD}\`
- : "FIRST_EXCHANGE_MISSING_CODEWORD";
- }
-
- if (request.userMessageCount === 2) {
- const retainedFirstExchange = request.userMessages[0]?.includes(CODEWORD) === true;
- const asksForCodeword = request.lastUserMessage?.includes("What codeword") === true;
- return retainedFirstExchange && asksForCodeword ? CODEWORD : "CONTEXT_LOST";
- }
-
- throw new Error("Child model received an unexpected conversation length.");
-});
-
-export default defineAgent({
- description: "Remember a fact and recall it in a later agent exchange.",
- model,
- modelContextWindowTokens: 32_000,
-});
-`;
-
-function createWorkflowProgramToolSource(): string {
- return `import { workflow } from "eve/tools/workflow";
-
-export default workflow({ maxSubagents: 2 });
-`;
-}
-
-const AGENT_MESSAGING_DESCRIPTOR: ScenarioAppDescriptor = {
- files: {
- "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/run-program.ts": createWorkflowProgramToolSource(),
- "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",
- },
- installDependencies: true,
- name: "agent-messaging",
-};
-
-const REMOTE_MEMORY_AGENT_DESCRIPTOR: ScenarioAppDescriptor = {
- files: {
- "agent/agent.ts": MEMORY_AGENT_SOURCE,
- "agent/channels/eve.ts": AUTHENTICATED_EVE_CHANNEL_SOURCE,
- "agent/instructions.md":
- "Remember facts from earlier turns and answer follow-up questions from that history.\n",
- },
- installDependencies: true,
- name: "remote-memory-agent",
-};
-
-function createRemoteAgentMessagingDescriptor(remoteUrl: string): ScenarioAppDescriptor {
- return {
- files: {
- "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/run-program.ts": createWorkflowProgramToolSource(),
- "agent/subagents/remote-memory-child.ts": `import { defineRemoteAgent } from "eve";
-import { bearer } from "eve/agents/auth";
-
-export default defineRemoteAgent({
- auth: bearer(${JSON.stringify(REMOTE_MEMORY_TOKEN)}),
- description: "Remember a fact and recall it in a later agent exchange.",
- url: ${JSON.stringify(remoteUrl)},
-});
-`,
- },
- installDependencies: true,
- name: "remote-agent-messaging",
- };
-}
-
-describe("agent messaging", () => {
- it(
- "continues one parked child with its retained conversation and terminates it with the parent",
- async () => {
- const app = await scenarioApp(AGENT_MESSAGING_DESCRIPTOR);
- const server = await startScriptedEveDev(app.appRoot);
-
- try {
- const childSessionId = await runScriptedParentSession({
- serverUrl: server.url,
- subagentName: "memory-child",
- });
- await expectRetainedChildConversation({
- childSessionId,
- client: new Client({ host: server.url }),
- expectedCompletionCount: 0,
- });
- } catch (error) {
- throw new Error(
- [`stdout:\n${server.stdout()}`, `stderr:\n${server.stderr()}`].join("\n\n"),
- { cause: error },
- );
- } finally {
- await server.stop();
- }
- },
- SCENARIO_TIMEOUT_MS,
- );
-
- it(
- "continues one parked remote agent with its retained conversation",
- async () => {
- const remoteApp = await scenarioApp(REMOTE_MEMORY_AGENT_DESCRIPTOR);
- const remoteServer = await startScriptedEveDev(remoteApp.appRoot);
-
- try {
- const parentApp = await scenarioApp(createRemoteAgentMessagingDescriptor(remoteServer.url));
- const parentServer = await startScriptedEveDev(parentApp.appRoot);
-
- try {
- const childSessionId = await runScriptedParentSession({
- expectedRemoteUrl: remoteServer.url,
- serverUrl: parentServer.url,
- subagentName: "remote-memory-child",
- });
- await expectRetainedChildConversation({
- childSessionId,
- client: new Client({
- auth: { bearer: REMOTE_MEMORY_TOKEN },
- host: remoteServer.url,
- }),
- expectedCompletionCount: 0,
- });
- } catch (error) {
- throw new Error(
- [
- `parent stdout:\n${parentServer.stdout()}`,
- `parent stderr:\n${parentServer.stderr()}`,
- `remote stdout:\n${remoteServer.stdout()}`,
- `remote stderr:\n${remoteServer.stderr()}`,
- ].join("\n\n"),
- { cause: error },
- );
- } finally {
- await parentServer.stop();
- }
- } finally {
- await remoteServer.stop();
- }
- },
- SCENARIO_TIMEOUT_MS,
- );
-});
-
-async function runScriptedParentSession(input: {
- readonly expectedRemoteUrl?: string;
- readonly serverUrl: string;
- readonly subagentName: string;
-}): Promise<string> {
- const client = new Client({ host: input.serverUrl });
- const { session: parentSession, response: firstResponse } = await client.sessions.create({
- message: `Run both scripted ${input.subagentName} exchanges.`,
- });
- const firstTurn = await firstResponse.result();
- const firstTurnEvents = firstTurn.events;
- const secondTurn = await (
- await parentSession.send("Continue the same child and report its recalled codeword.")
- ).result();
- const parentEvents = [...firstTurnEvents, ...secondTurn.events];
- const calls = filterEventsByType(parentEvents, "subagent.called");
-
- if (calls.length !== 2) {
- throw new Error(`Expected two subagent calls. Parent events: ${JSON.stringify(parentEvents)}`);
- }
- expect(calls.map((call) => call.data.name)).toEqual([input.subagentName, input.subagentName]);
- expect(calls[0]?.data.childSessionId).toBeDefined();
- expect(calls[1]?.data.childSessionId).toBe(calls[0]?.data.childSessionId);
- if (input.expectedRemoteUrl === undefined) {
- expect(calls.every((call) => call.data.remote === undefined)).toBe(true);
- } else {
- expect(calls.map((call) => call.data.remote?.url)).toEqual([
- input.expectedRemoteUrl,
- input.expectedRemoteUrl,
- ]);
- }
- expect(secondTurn.status).toBe("waiting");
- expect(secondTurn.message).toBe(PARENT_RESULT);
-
- const childSessionId = calls[0]?.data.childSessionId;
- if (childSessionId === undefined) {
- throw new Error("First subagent.called event did not include a child session id.");
- }
- return childSessionId;
-}
-
-async function expectRetainedChildConversation(input: {
- readonly childSessionId: string;
- readonly client: Client;
- readonly expectedCompletionCount: number;
-}): Promise<void> {
- const childEvents = await collectStreamToEnd({
- label: "persisted child events",
- stream: input.client.sessions.attach(input.childSessionId).stream({ follow: false }),
- });
- const childTurnStarts = indexesOf(childEvents, "turn.started");
- const childWaits = indexesOf(childEvents, "session.waiting");
-
- expect(childTurnStarts).toHaveLength(2);
- expect(childWaits).toHaveLength(2);
- expect(childWaits[0]).toBeLessThan(childTurnStarts[1] ?? -1);
- expect(filterEventsByType(childEvents, "session.completed")).toHaveLength(
- input.expectedCompletionCount,
- );
- expect(filterEventsByType(childEvents, "session.failed")).toHaveLength(0);
- expect(
- filterEventsByType(childEvents, "message.completed").some(
- (event) => event.data.message === CODEWORD,
- ),
- ).toBe(true);
-}
-
-async function collectStreamToEnd(input: {
- readonly label: string;
- readonly stream: AsyncIterable<HandleMessageStreamEvent>;
-}): Promise<readonly HandleMessageStreamEvent[]> {
- const events: HandleMessageStreamEvent[] = [];
- let timeout: ReturnType<typeof setTimeout> | undefined;
-
- try {
- return await Promise.race([
- (async () => {
- for await (const event of input.stream) {
- events.push(event);
- }
- return events;
- })(),
- new Promise<never>((_resolve, reject) => {
- timeout = setTimeout(
- () => reject(new Error(`Timed out waiting for ${input.label}.`)),
- EVENT_TIMEOUT_MS,
- );
- }),
- ]);
- } finally {
- if (timeout !== undefined) {
- clearTimeout(timeout);
- }
- }
-}
-
-function indexesOf(
- events: readonly HandleMessageStreamEvent[],
- type: HandleMessageStreamEvent["type"],
-): readonly number[] {
- return events.flatMap((event, index) => (event.type === type ? [index] : []));
-}
-
-interface RunningScriptedEveDev {
- readonly stderr: () => string;
- readonly stdout: () => string;
- readonly url: string;
- stop(): Promise<void>;
-}
-
-async function startScriptedEveDev(appRoot: string): Promise<RunningScriptedEveDev> {
- const eveBinPath = join(appRoot, "node_modules", "eve", "bin", "eve.js");
- const child = spawn(
- process.execPath,
- [eveBinPath, "dev", "--no-ui", "--host", "127.0.0.1", "--port", "0"],
- {
- cwd: appRoot,
- env: {
- ...process.env,
- EVE_MOCK_AUTHORED_MODELS: "",
- NODE_ENV: "production",
- },
- stdio: ["ignore", "pipe", "pipe"],
- },
- );
- let stderr = "";
- let stdout = "";
-
- child.stdout.setEncoding("utf8");
- child.stderr.setEncoding("utf8");
- child.stdout.on("data", (chunk: string) => {
- stdout += chunk;
- });
- child.stderr.on("data", (chunk: string) => {
- stderr += chunk;
- });
-
- let url: string;
- try {
- url = await waitForServerUrl(child, () => ({ stderr, stdout }));
- } catch (error) {
- await stopChild(child);
- throw error;
- }
-
- return {
- stderr: () => stderr,
- stdout: () => stdout,
- async stop() {
- await stopChild(child);
- },
- url,
- };
-}
-
-async function waitForServerUrl(
- child: ChildProcessByStdio<null, Readable, Readable>,
- output: () => { readonly stderr: string; readonly stdout: string },
-): Promise<string> {
- return await new Promise((resolve, reject) => {
- const timeout = setTimeout(() => {
- cleanup();
- const current = output();
- reject(
- new Error(
- `Timed out waiting for eve dev.\n\nstdout:\n${current.stdout}\n\nstderr:\n${current.stderr}`,
- ),
- );
- }, EVENT_TIMEOUT_MS);
-
- function inspect() {
- const match = /\[DEV\] server listening at (http:\/\/[^\s]+)/u.exec(output().stdout);
- if (match?.[1] === undefined) {
- return;
- }
- cleanup();
- resolve(match[1]);
- }
-
- function exited(code: number | null, signal: NodeJS.Signals | null) {
- cleanup();
- const current = output();
- reject(
- new Error(
- [
- `eve dev exited before startup (code ${String(code)}, signal ${String(signal)}).`,
- `stdout:\n${current.stdout}`,
- `stderr:\n${current.stderr}`,
- ].join("\n\n"),
- ),
- );
- }
-
- function cleanup() {
- clearTimeout(timeout);
- child.stdout.off("data", inspect);
- child.stderr.off("data", inspect);
- child.off("exit", exited);
- }
-
- child.stdout.on("data", inspect);
- child.stderr.on("data", inspect);
- child.once("exit", exited);
- inspect();
- });
-}
-
-async function stopChild(child: ChildProcessByStdio<null, Readable, Readable>): Promise<void> {
- if (child.exitCode !== null || child.signalCode !== null) {
- return;
- }
-
- await new Promise<void>((resolve) => {
- const force = setTimeout(() => child.kill("SIGKILL"), 10_000);
- child.once("exit", () => {
- clearTimeout(force);
- resolve();
- });
- child.kill("SIGTERM");
- });
-}
diff --git a/packages/eve/src/execution/agent-sessions/context.ts b/packages/eve/src/execution/agent-sessions/context.ts
new file mode 100644
index 000000000..0d5e75ca2
--- /dev/null
+++ b/packages/eve/src/execution/agent-sessions/context.ts
@@ -0,0 +1,118 @@
+import type {
+ ActivityObserverConfig,
+ ChannelInstrumentationProjection,
+ RunSessionLimits,
+ SessionAuthContext,
+ SessionCapabilities,
+ SessionParent,
+} from "#channel/types.js";
+import type { LocalDevRequestProvenance } from "#context/keys.js";
+import type { DynamicSubagentSelections } from "#execution/agent-sessions/target.js";
+import type { PreparedCoordinationDispatch } from "#execution/coordination-dispatch-shared.js";
+import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";
+import {
+ serializeDurableCompiledArtifactsSource,
+ type DurableCompiledArtifactsSource,
+} from "#runtime/durable-compiled-artifacts-source.js";
+import type { SandboxState } from "#sandbox/state.js";
+import type { ConversationContext } from "#shared/conversation-context.js";
+import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";
+import {
+ resolveToolCallAgentTrace,
+ type AgentChildTraceDispatch,
+} from "#tracing/agent-invocation-coordinator.js";
+
+/**
+ * What a workflow run needs to open `ctx.agent` sessions for its caller,
+ * captured from the calling session in the run's start input. The run never
+ * reads the session again: opening, sending to, and ending its sessions never
+ * pass through the caller.
+ */
+export interface AgentSessionContext {
+ readonly activityObserver?: ActivityObserverConfig & {
+ readonly workIdentity: ActivityWorkIdentityV1;
+ };
+ /** The caller's principal, which every session runs as. */
+ readonly auth: SessionAuthContext | null;
+ readonly bundle: AgentSessionBundle;
+ /** Forwarded unchanged, so a session asks a person only when its caller can. */
+ readonly capabilities?: SessionCapabilities;
+ readonly channelMetadata?: ChannelInstrumentationProjection;
+ readonly conversation?: ConversationContext;
+ /** Dynamic agents the calling turn selected, by node id. */
+ readonly dynamicSelections: DynamicSubagentSelections;
+ readonly initiatorAuth: SessionAuthContext | null;
+ /** The token budget each session inherits: the caller's remaining quota. */
+ readonly limits: RunSessionLimits;
+ readonly localDevRequest?: LocalDevRequestProvenance;
+ /** The calling session, turn, and tool call, recorded as each session's lineage. */
+ readonly parent: SessionParent;
+ readonly sandbox: AgentSessionSandbox;
+ readonly trace: AgentChildTraceDispatch;
+}
+
+/** The compiled agent that owns the tool, which resolves agent names. */
+export interface AgentSessionBundle {
+ readonly nodeId?: string;
+ readonly source: DurableCompiledArtifactsSource;
+}
+
+/** The caller's sandbox, which agents declared with a parent sandbox share. */
+export interface AgentSessionSandbox {
+ readonly sessionId: string;
+ readonly state?: SandboxState;
+}
+
+type CallerDispatch = Pick<
+ PreparedCoordinationDispatch<unknown>,
+ | "activityObserver"
+ | "auth"
+ | "batch"
+ | "bundle"
+ | "capabilities"
+ | "channelMetadata"
+ | "dynamicSubagentSelections"
+ | "inheritedConversation"
+ | "initiatorAuth"
+ | "localDevRequest"
+ | "sandboxSessionId"
+ | "serializedContext"
+ | "session"
+>;
+
+/** Captures the agent session context for one workflow tool call's run. */
+export function captureAgentSessionContext(
+ caller: CallerDispatch,
+ callId: string,
+): AgentSessionContext {
+ const { batch, session } = caller;
+ return {
+ activityObserver: caller.activityObserver,
+ auth: caller.auth,
+ bundle: {
+ nodeId: caller.bundle.nodeId,
+ source: serializeDurableCompiledArtifactsSource(caller.bundle.compiledArtifactsSource),
+ },
+ capabilities: caller.capabilities,
+ channelMetadata: caller.channelMetadata,
+ conversation: caller.inheritedConversation,
+ dynamicSelections: caller.dynamicSubagentSelections,
+ initiatorAuth: caller.initiatorAuth,
+ limits: resolveRemainingSessionTokenLimits(session),
+ localDevRequest: caller.localDevRequest,
+ parent: {
+ callId,
+ rootSessionId: session.rootSessionId ?? session.sessionId,
+ sessionId: session.sessionId,
+ turn: { id: batch.event.turnId, sequence: batch.event.sequence },
+ },
+ sandbox: { sessionId: caller.sandboxSessionId, state: session.sandboxState },
+ trace: resolveToolCallAgentTrace({
+ callId,
+ conversation: caller.inheritedConversation,
+ serializedContext: caller.serializedContext,
+ sessionId: session.sessionId,
+ turnId: batch.event.turnId,
+ }),
+ };
+}
diff --git a/packages/eve/src/execution/agent-sessions/requests.ts b/packages/eve/src/execution/agent-sessions/requests.ts
new file mode 100644
index 000000000..e9f1a9d8a
--- /dev/null
+++ b/packages/eve/src/execution/agent-sessions/requests.ts
@@ -0,0 +1,61 @@
+import type {
+ SubagentAuthorizationEventHookPayload,
+ SubagentInputRequestHookPayload,
+} from "#channel/types.js";
+import {
+ sessionCommandHookToken,
+ sessionInboxHookToken,
+} from "#execution/session-inbox/address.js";
+import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
+import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.js";
+
+/** A child's question or sign-in, which only a person at the root can answer. */
+export type AgentSessionRequest =
+ | SubagentAuthorizationEventHookPayload
+ | SubagentInputRequestHookPayload;
+
+/**
+ * Sends a child's question or sign-in to the session that owns the run, which
+ * proxies it up the owner chain to the root. Answers route back down to the
+ * child by request id.
+ */
+export async function forwardAgentSessionRequest(input: {
+ readonly from: WorkflowToolRunRef;
+ readonly owner: WorkflowToolRunInbox;
+ readonly replyTo: string;
+ readonly request: AgentSessionRequest;
+}): Promise<void> {
+ const { from, request } = input;
+ if (request.kind === "subagent-authorization-event") {
+ await input.owner.send({
+ from,
+ kind: "request",
+ replyTo: input.replyTo,
+ request: { event: request, kind: "authorization-request" },
+ });
+ return;
+ }
+ await input.owner.send({
+ from,
+ kind: "request",
+ replyTo: childAnswerToken(request),
+ request: { kind: "input-batch", requests: request.event.requests },
+ requestCoordinates: {
+ sequence: request.event.sequence,
+ stepIndex: request.event.stepIndex,
+ turnId: request.event.turnId,
+ },
+ });
+}
+
+/**
+ * Current session inboxes take answers on their physical token. A remote
+ * child's create-once operation hook is already a narrowed reply capability.
+ */
+function childAnswerToken(request: SubagentInputRequestHookPayload): string {
+ const inbox = request.childSessionInbox;
+ if (inbox?.sessionId === request.childSessionId) {
+ return sessionInboxHookToken(sessionCommandHookToken(inbox.sessionId));
+ }
+ return request.childContinuationToken;
+}
diff --git a/packages/eve/src/execution/agent-sessions/session.ts b/packages/eve/src/execution/agent-sessions/session.ts
new file mode 100644
index 000000000..c88090134
--- /dev/null
+++ b/packages/eve/src/execution/agent-sessions/session.ts
@@ -0,0 +1,231 @@
+import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
+
+import type { RuntimeActionResultHookPayload } from "#channel/types.js";
+import {
+ forwardAgentSessionRequest,
+ type AgentSessionRequest,
+} from "#execution/agent-sessions/requests.js";
+import {
+ cancelAgentSessionTurnStep,
+ endAgentSessionsStep,
+ openAgentSessionStep,
+ sendAgentSessionMessageStep,
+ type AgentSessionAddress,
+ type AgentSessionMessage,
+} from "#execution/agent-sessions/steps.js";
+import { disposeHook } from "#execution/hook-ownership.js";
+import type { WorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
+import type { RuntimeSubagentResult } from "#shared/action-types.js";
+import { normalizeRequestedOutputSchema } from "#subagents/invocation.js";
+import { serializeOutputSchema } from "#tools/schema-emission.js";
+import type {
+ AgentMessageResult,
+ AgentResponse,
+ AgentSendOptions,
+ AgentSession,
+} from "#tools/workflow-definition.js";
+
+type AgentTurnReply = AgentSessionRequest | RuntimeActionResultHookPayload;
+
+type AgentTurnEnd =
+ | { readonly kind: "ended"; readonly result: AgentMessageResult<unknown> }
+ | { readonly kind: "failed"; readonly error: unknown };
+
+/**
+ * Opens `ctx.agent` sessions for a workflow run. A handle's position in the
+ * run names its session, so replay reaches the same one, and `close` ends
+ * every session the run opened, cancelling any turn still running.
+ */
+export function createAgentSessions(run: WorkflowToolRunContext): {
+ readonly close: () => Promise<void>;
+ readonly open: (name: string) => AgentSession;
+} {
+ const opened: AgentSessionAddress[] = [];
+ let handles = 0;
+ return {
+ open: (name) => {
+ if (typeof name !== "string" || name.trim() === "") {
+ throw new TypeError("ctx.agent() requires a non-empty agent name.");
+ }
+ const key = `${run.from.runId}:${String(handles)}`;
+ handles += 1;
+ return new RunAgentSession({ key, name, opened, run });
+ },
+ close: async () => {
+ if (opened.length === 0) return;
+ await endAgentSessionsStep({ context: run.agentContext, sessions: opened });
+ },
+ };
+}
+
+/** One turn of a session: its result and questions arrive on the turn's own hook. */
+interface AgentTurn {
+ readonly hook: Hook<AgentTurnReply>;
+ readonly response: AgentResponse<unknown>;
+}
+
+class RunAgentSession implements AgentSession {
+ readonly #key: string;
+ readonly #name: string;
+ /** Every session the run opened, which it ends when it finishes. */
+ readonly #opened: AgentSessionAddress[];
+ readonly #run: WorkflowToolRunContext;
+ #address: Promise<AgentSessionAddress> | undefined;
+ #turn: AgentTurn | undefined;
+
+ constructor(input: {
+ readonly key: string;
+ readonly name: string;
+ readonly opened: AgentSessionAddress[];
+ readonly run: WorkflowToolRunContext;
+ }) {
+ this.#key = input.key;
+ this.#name = input.name;
+ this.#opened = input.opened;
+ this.#run = input.run;
+ }
+
+ async send<TOutput = unknown>(
+ message: string,
+ options: AgentSendOptions<TOutput> = {},
+ ): Promise<AgentResponse<TOutput>> {
+ if (typeof message !== "string" || message.trim() === "") {
+ throw new TypeError(`ctx.agent("${this.#name}").send() requires a non-empty message.`);
+ }
+ // The reply's shape and the child's output mode must agree on whether a
+ // schema was requested, and an empty one requests none.
+ const outputSchema = normalizeRequestedOutputSchema(
+ serializeOutputSchema(options.outputSchema),
+ );
+ const running = this.#turn;
+ const turn = running ?? this.#startTurn(outputSchema !== undefined);
+ try {
+ await this.#deliver({
+ context: this.#run.agentContext,
+ message,
+ outputSchema,
+ replyTo: turn.hook.token,
+ });
+ } catch (error) {
+ if (running === undefined) await this.#closeTurn(turn);
+ throw error;
+ }
+ if (options.signal !== undefined) this.#cancelTurnOnAbort(turn, options.signal);
+ return turn.response as AgentResponse<TOutput>;
+ }
+
+ #startTurn(expectsData: boolean): AgentTurn {
+ const hook = createHook<AgentTurnReply>();
+ const ended = this.#readTurn(hook, expectsData);
+ const turn: AgentTurn = {
+ hook,
+ response: { result: () => ended.then(unwrapTurnEnd) },
+ };
+ this.#turn = turn;
+ return turn;
+ }
+
+ /** Forwards the turn's questions up to the session and settles with its result. */
+ async #readTurn(hook: Hook<AgentTurnReply>, expectsData: boolean): Promise<AgentTurnEnd> {
+ try {
+ for await (const reply of hook) {
+ if (reply.kind !== "runtime-action-result") {
+ await forwardAgentSessionRequest({
+ from: this.#run.from,
+ owner: this.#run.owner,
+ replyTo: hook.token,
+ request: reply,
+ });
+ continue;
+ }
+ const result = reply.results.find(
+ (candidate): candidate is RuntimeSubagentResult => candidate.kind === "subagent-result",
+ );
+ if (result !== undefined) {
+ return { kind: "ended", result: toAgentMessageResult(result, expectsData) };
+ }
+ }
+ return {
+ error: new Error(`Agent "${this.#name}" stopped reporting before its turn ended.`),
+ kind: "failed",
+ };
+ } catch (error) {
+ return { error, kind: "failed" };
+ } finally {
+ await this.#closeTurn({ hook });
+ }
+ }
+
+ async #closeTurn(turn: Pick<AgentTurn, "hook">): Promise<void> {
+ if (this.#turn?.hook === turn.hook) this.#turn = undefined;
+ try {
+ await disposeHook(turn.hook);
+ } catch {
+ // The turn already has its outcome; releasing its hook is best effort.
+ }
+ }
+
+ async #deliver(message: AgentSessionMessage): Promise<void> {
+ if (this.#address === undefined) {
+ this.#address = this.#open(message);
+ await this.#address;
+ return;
+ }
+ const address = await this.#address;
+ await sendAgentSessionMessageStep({ ...message, address });
+ }
+
+ async #open(message: AgentSessionMessage): Promise<AgentSessionAddress> {
+ try {
+ const address = await openAgentSessionStep({ ...message, key: this.#key, name: this.#name });
+ this.#opened.push(address);
+ await this.#run.owner.send({ from: this.#run.from, kind: "agent-started", session: address });
+ return address;
+ } catch (error) {
+ this.#address = undefined;
+ throw error;
+ }
+ }
+
+ /** Aborting cancels only the turn the message went to, never a later one. */
+ #cancelTurnOnAbort(turn: AgentTurn, signal: AbortSignal): void {
+ const cancel = (): void => {
+ if (this.#turn !== turn || this.#address === undefined) return;
+ void this.#address
+ .then((address) => cancelAgentSessionTurnStep({ address, context: this.#run.agentContext }))
+ .catch(() => {});
+ };
+ if (signal.aborted) {
+ cancel();
+ return;
+ }
+ signal.addEventListener("abort", cancel, { once: true });
+ }
+}
+
+function unwrapTurnEnd(end: AgentTurnEnd): AgentMessageResult<unknown> {
+ if (end.kind === "failed") throw end.error;
+ return end.result;
+}
+
+const NO_REPLY = { data: undefined, message: undefined } as const;
+
+function toAgentMessageResult(
+ result: RuntimeSubagentResult,
+ expectsData: boolean,
+): AgentMessageResult<unknown> {
+ if (result.origin !== "child") return { ...NO_REPLY, status: "failed" };
+ const { outcome } = result;
+ switch (outcome.result.kind) {
+ case "failed":
+ return { ...NO_REPLY, status: "failed" };
+ case "cancelled":
+ return { ...NO_REPLY, status: "waiting" };
+ case "succeeded": {
+ const { output } = outcome.result;
+ const status = outcome.kind === "terminal" ? "completed" : "waiting";
+ if (expectsData) return { data: output, message: undefined, status };
+ return { data: undefined, message: typeof output === "string" ? output : undefined, status };
+ }
+ }
+}
diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.ts
new file mode 100644
index 000000000..eadf2ed8a
--- /dev/null
+++ b/packages/eve/src/execution/agent-sessions/steps.ts
@@ -0,0 +1,327 @@
+import { FatalError, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
+import { resolveAgentAction, resolveAgentStartTarget } from "#execution/agent-sessions/target.js";
+import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";
+import type { SubagentStartTarget } from "#execution/tools/subagent/start.js";
+import {
+ createWorkflowCallbackUrl,
+ resolveWorkflowCallbackBaseUrl,
+} from "#execution/workflow-callback-url.js";
+import {
+ createWorkflowRuntime,
+ dispatchWorkflowSessionCommand,
+ requestWorkflowTurnCancellation,
+ waitForCommandHookOwner,
+} from "#execution/workflow-runtime.js";
+import { createLogger, logError } from "#internal/logging.js";
+import { createEveCallbackRoutePath } from "#protocol/routes.js";
+import { resolveDurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";
+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
+import { toErrorMessage } from "#shared/errors.js";
+import type { JsonObject } from "#shared/json.js";
+import type { SubagentParentContext } from "#subagents/invocation.js";
+import {
+ cancelRemoteAgentTurn,
+ continueRemoteAgentSession,
+ resetRemoteAgentSession,
+ resolveRemoteAgentForAction,
+ startRemoteAgentSession,
+} from "#subagents/remote-dispatch.js";
+import { buildSubagentRunInput } from "#subagents/tool.js";
+import { resolveConversationId } from "#shared/conversation-identity.js";
+
+const log = createLogger("execution.agent-sessions");
+
+const RUN_FINISHED_REASON = "The workflow run that opened this session finished.";
+
+/** Where a session a run opened lives, for its later sends, cancels, and end. */
+export type AgentSessionAddress =
+ | {
+ readonly kind: "local";
+ readonly name: string;
+ readonly nodeId: string;
+ readonly sessionId: string;
+ }
+ | {
+ readonly callbackBaseUrl: string;
+ readonly kind: "remote";
+ readonly name: string;
+ readonly nodeId: string;
+ /** Keys the authored credential functions, as on `agent.started`. */
+ readonly resolverId?: string;
+ readonly sessionId: string;
+ readonly url: string;
+ };
+
+/** One message to a session; its turn's result and questions arrive on `replyTo`. */
+export interface AgentSessionMessage {
+ readonly context: AgentSessionContext;
+ readonly message: string;
+ readonly outputSchema?: JsonObject;
+ readonly replyTo: string;
+}
+
+/**
+ * Opens a run's session with its first message. `key` names the handle within
+ * the run, so a retried step reaches the same session instead of a second one.
+ */
+export async function openAgentSessionStep(
+ input: AgentSessionMessage & { readonly key: string; readonly name: string },
+): Promise<AgentSessionAddress> {
+ "use step";
+
+ const { context } = input;
+ const bundle = await loadAgentSessionBundle(context);
+ const action = resolveAgentAction({
+ bundle,
+ callId: context.parent.callId,
+ dynamicSelections: context.dynamicSelections,
+ input: { message: input.message, outputSchema: input.outputSchema, target: input.name },
+ });
+ const plan = resolveAgentStartTarget({
+ action,
+ bundle,
+ dynamicSelections: context.dynamicSelections,
+ isRootSession: context.parent.rootSessionId === context.parent.sessionId,
+ });
+ if (plan.kind === "reject") {
+ throw new FatalError(toErrorMessage(plan.result.output));
+ }
+ const start = { bundle, context, key: input.key, replyTo: input.replyTo };
+ if (plan.target.kind === "remote") {
+ return await startRemoteSession({ ...start, target: plan.target });
+ }
+ return await startLocalSession({ ...start, target: plan.target });
+}
+
+/** Sends a later message; it joins the session's running turn or starts the next. */
+export async function sendAgentSessionMessageStep(
+ input: AgentSessionMessage & { readonly address: AgentSessionAddress },
+): Promise<void> {
+ "use step";
+
+ const { address, context } = input;
+ if (address.kind === "remote") {
+ const remote = await resolveSessionRemote(context, address);
+ await continueRemoteAgentSession({
+ activityObserver: context.activityObserver,
+ auth: context.auth,
+ callback: {
+ callId: context.parent.callId,
+ subagentName: address.name,
+ token: input.replyTo,
+ url: createWorkflowCallbackUrl(
+ address.callbackBaseUrl,
+ createEveCallbackRoutePath(input.replyTo),
+ ),
+ },
+ message: input.message,
+ outputSchema: input.outputSchema,
+ remote,
+ sessionId: address.sessionId,
+ });
+ return;
+ }
+ const result = await dispatchWorkflowSessionCommand({
+ command: {
+ auth: context.auth,
+ caller: {
+ activityObserver: context.activityObserver,
+ callId: context.parent.callId,
+ replyTo: { kind: "hook", token: input.replyTo },
+ subagentName: address.name,
+ },
+ kind: "send",
+ payload: { message: input.message, outputSchema: input.outputSchema },
+ },
+ sessionId: address.sessionId,
+ });
+ if (result.status !== "accepted") {
+ throw new Error(`Agent "${address.name}" can no longer receive messages; its session ended.`);
+ }
+}
+
+/** Cancels a session's running turn; the turn still reports, as cancelled. */
+export async function cancelAgentSessionTurnStep(input: {
+ readonly address: AgentSessionAddress;
+ readonly context: AgentSessionContext;
+}): Promise<void> {
+ "use step";
+
+ const { address } = input;
+ try {
+ if (address.kind === "remote") {
+ const remote = await resolveSessionRemote(input.context, address);
+ await cancelRemoteAgentTurn({ remote, sessionId: address.sessionId });
+ return;
+ }
+ await requestWorkflowTurnCancellation({ sessionId: address.sessionId });
+ } catch (error) {
+ logError(log, "failed to cancel an agent session turn", error, {
+ name: address.name,
+ sessionId: address.sessionId,
+ });
+ }
+}
+
+/** Ends a run's sessions when the run finishes, cancelling any turn still running. */
+export async function endAgentSessionsStep(input: {
+ readonly context: AgentSessionContext;
+ readonly sessions: readonly AgentSessionAddress[];
+}): Promise<void> {
+ "use step";
+
+ await Promise.all(input.sessions.map((address) => endAgentSession(input.context, address)));
+}
+
+async function endAgentSession(
+ context: AgentSessionContext,
+ address: AgentSessionAddress,
+): Promise<void> {
+ try {
+ if (address.kind === "remote") {
+ const remote = await resolveSessionRemote(context, address);
+ await resetRemoteAgentSession({
+ reason: RUN_FINISHED_REASON,
+ remote,
+ sessionId: address.sessionId,
+ });
+ return;
+ }
+ await dispatchWorkflowSessionCommand({
+ command: { kind: "reset", reason: RUN_FINISHED_REASON },
+ sessionId: address.sessionId,
+ });
+ } catch (error) {
+ logError(log, "failed to end an agent session", error, {
+ name: address.name,
+ sessionId: address.sessionId,
+ });
+ }
+}
+
+interface SessionStart<Target extends SubagentStartTarget> {
+ readonly bundle: CompiledBundle;
+ readonly context: AgentSessionContext;
+ readonly key: string;
+ readonly replyTo: string;
+ readonly target: Target;
+}
+
+async function startLocalSession(
+ input: SessionStart<Extract<SubagentStartTarget, { readonly kind: "local" }>>,
+): Promise<AgentSessionAddress> {
+ const { bundle, context, target } = input;
+ const { action } = target;
+ const { childContinuationToken, runInput } = buildSubagentRunInput({
+ action,
+ activityObserver: context.activityObserver,
+ auth: context.auth,
+ capabilities: context.capabilities,
+ channelMetadata: context.channelMetadata,
+ continuationKey: input.key,
+ graph: bundle.graph,
+ inheritedConversation: context.conversation,
+ initiatorAuth: context.initiatorAuth,
+ limits: context.limits,
+ parent: createParentContext(context, input.replyTo),
+ sandboxSessionId: context.sandbox.sessionId,
+ selfAgent: target.source.type === "runtime",
+ session: {
+ continuationToken: input.replyTo,
+ sandboxState: context.sandbox.state,
+ sessionId: context.parent.sessionId,
+ },
+ source: target.source,
+ });
+ const childRuntime = createWorkflowRuntime({
+ compiledArtifactsSource: bundle.compiledArtifactsSource,
+ dynamicSubagentAgentConfig: target.dynamicSubagentAgentConfig,
+ nodeId: action.nodeId,
+ });
+ await contextStorage.run(new ContextContainer({ localDevRequest: context.localDevRequest }), () =>
+ childRuntime.createSession(runInput),
+ );
+ const owner = await waitForCommandHookOwner(sessionInboxHookToken(childContinuationToken));
+ return { kind: "local", name: action.name, nodeId: action.nodeId, sessionId: owner.runId };
+}
+
+async function startRemoteSession(
+ input: SessionStart<Extract<SubagentStartTarget, { readonly kind: "remote" }>>,
+): Promise<AgentSessionAddress> {
+ const { bundle, context, target } = input;
+ const { action } = target;
+ const remote = resolveRemoteAgentForAction({
+ dynamicRemoteAgent: target.dynamicRemoteAgent,
+ nodeId: action.nodeId,
+ registry: bundle.subagentRegistry.subagentsByNodeId,
+ remoteAgentName: action.remoteAgentName,
+ });
+ const callbackBaseUrl = resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url);
+ const child = await startRemoteAgentSession({
+ action,
+ activityObserver: deriveChildActivityObserverConfig({
+ activityObserver: context.activityObserver,
+ callId: action.callId,
+ kind: "remote-agent",
+ name: action.remoteAgentName,
+ parentSessionId: context.parent.sessionId,
+ parentTurnId: context.parent.turn.id,
+ }),
+ auth: context.auth,
+ callbackBaseUrl,
+ initiatorAuth: context.initiatorAuth,
+ operationId: `agent-session:${input.key}`,
+ originAudience: context.trace.originAudience,
+ parent: createParentContext(context, input.replyTo),
+ remote,
+ session: { continuationToken: input.replyTo },
+ });
+ return {
+ callbackBaseUrl,
+ kind: "remote",
+ name: action.remoteAgentName,
+ nodeId: action.nodeId,
+ resolverId: target.dynamicRemoteAgent?.credentialsStepId ?? action.nodeId,
+ sessionId: child.sessionId,
+ url: remote.url,
+ };
+}
+
+function createParentContext(context: AgentSessionContext, replyTo: string): SubagentParentContext {
+ return {
+ continuationToken: replyTo,
+ conversationId:
+ context.trace.conversationId ?? resolveConversationId(context.parent.rootSessionId),
+ lineage: context.parent,
+ originAudience: context.trace.originAudience,
+ traceContext: context.trace.parentTraceContext,
+ };
+}
+
+/** A remote session keeps running where it was opened, even after the registry moves on. */
+async function resolveSessionRemote(
+ context: AgentSessionContext,
+ address: Extract<AgentSessionAddress, { readonly kind: "remote" }>,
+): Promise<ResolvedRuntimeRemoteAgentNode> {
+ const bundle = await loadAgentSessionBundle(context);
+ const selection = context.dynamicSelections[address.nodeId];
+ const resolved = resolveRemoteAgentForAction({
+ dynamicRemoteAgent: selection?.kind === "remote" ? selection.remoteAgent : undefined,
+ nodeId: address.nodeId,
+ registry: bundle.subagentRegistry.subagentsByNodeId,
+ remoteAgentName: address.name,
+ });
+ return { ...resolved, url: address.url };
+}
+
+async function loadAgentSessionBundle(context: AgentSessionContext): Promise<CompiledBundle> {
+ return await getCompiledRuntimeAgentBundle({
+ compiledArtifactsSource: resolveDurableCompiledArtifactsSource(context.bundle.source),
+ nodeId: context.bundle.nodeId,
+ });
+}
diff --git a/packages/eve/src/execution/agent-sessions/target.ts b/packages/eve/src/execution/agent-sessions/target.ts
new file mode 100644
index 000000000..a0b725d16
--- /dev/null
+++ b/packages/eve/src/execution/agent-sessions/target.ts
@@ -0,0 +1,169 @@
+import { FatalError } from "#compiled/@workflow/core/index.js";
+
+import type { DurableDynamicSubagentSelection } from "#context/keys.js";
+import {
+ createRecursiveAgentRootOnlyResult,
+ createUnavailableDynamicSubagentResult,
+ getSubagentName,
+} from "#execution/dispatch-action-failures.js";
+import type { SubagentStartTarget } from "#execution/tools/subagent/start.js";
+import { createLogger } from "#internal/logging.js";
+import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import type {
+ RuntimeAgentDispatchRequest,
+ RuntimeSubagentDispatchFailure,
+ RuntimeSubagentDispatchRequest,
+} from "#shared/action-types.js";
+import type { JsonObject } from "#shared/json.js";
+import type { SubagentInputSource } from "#subagents/tool.js";
+import { AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";
+
+const log = createLogger("execution.agent-target");
+
+export type DynamicSubagentSelections = Readonly<Record<string, DurableDynamicSubagentSelection>>;
+
+/** One message to an agent, addressed by its invocation name. */
+export interface AgentActionInput {
+ readonly agentId?: string;
+ readonly message: string;
+ readonly outputSchema?: JsonObject;
+ readonly target: string;
+}
+
+export type AgentStartPlan =
+ | { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }
+ | { readonly kind: "start"; readonly target: SubagentStartTarget };
+
+/**
+ * Resolves an agent name against the calling agent's registry, its dynamic
+ * selections, and the built-in root copy, as a dispatch request.
+ */
+export function resolveAgentAction(input: {
+ readonly bundle: CompiledBundle;
+ readonly callId: string;
+ readonly dynamicSelections: DynamicSubagentSelections;
+ readonly input: AgentActionInput;
+}): RuntimeAgentDispatchRequest {
+ const definition = findAgentDefinition(input.bundle, input.dynamicSelections, input.input.target);
+ if (definition === undefined) {
+ throw new FatalError(`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.callId,
+ 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 };
+}
+
+function findAgentDefinition(
+ bundle: CompiledBundle,
+ dynamicSelections: DynamicSubagentSelections,
+ name: string,
+) {
+ const registered = bundle.subagentRegistry.subagentsByName.get(name);
+ if (registered !== undefined) return registered.definition;
+ const dynamic = Object.values(dynamicSelections).find(
+ (selection) => selection !== null && selection.prepared.name === name,
+ );
+ if (dynamic != null) return dynamic.prepared;
+ if (name === AGENT_TOOL_NAME && bundle.nodeId === undefined) {
+ return {
+ description: AGENT_TOOL_DESCRIPTION,
+ kind: "subagent" as const,
+ name: AGENT_TOOL_NAME,
+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
+ };
+ }
+ return undefined;
+}
+
+/**
+ * Plans a fresh child for a dispatch request, rejecting a dynamic agent whose
+ * selection changed and a root copy outside the root session.
+ */
+export function resolveAgentStartTarget(input: {
+ readonly action: RuntimeAgentDispatchRequest;
+ readonly bundle: CompiledBundle;
+ readonly dynamicSelections: DynamicSubagentSelections;
+ readonly isRootSession: boolean;
+}): AgentStartPlan {
+ const { action } = input;
+ const registry = input.bundle.subagentRegistry.subagentsByNodeId;
+ const isDynamicSubagent =
+ input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true;
+ const dynamicSubagentSelection = isDynamicSubagent
+ ? (input.dynamicSelections[action.nodeId] ?? undefined)
+ : 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.isRootSession) {
+ log.warn("recursive agent call blocked outside the root session", {
+ callId: action.callId,
+ nodeId: action.nodeId,
+ 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 ? { type: "runtime" } : { description, type: "local" };
+ return {
+ kind: "start",
+ target: { action, dynamicSubagentAgentConfig: dynamicAgentConfig, kind: "local", source },
+ };
+}
+
+function isRecursiveAgentAction(
+ action: RuntimeAgentDispatchRequest,
+ subagentsByNodeId: ReadonlyMap<string, unknown>,
+): action is RuntimeSubagentDispatchRequest {
+ return (
+ action.kind === "subagent-call" &&
+ action.subagentName === AGENT_TOOL_NAME &&
+ !subagentsByNodeId.has(action.nodeId)
+ );
+}
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 d4297f5f3..a51b1c796 100644
--- a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
@@ -135,10 +135,9 @@ describe("cancelDescendantTurnsStep", () => {
sessionStarted: true,
},
"eve.workflowTool": {
- version: 3,
+ version: 4,
runs: [
{
- lifetime: "turn",
callId: "call",
toolName: "research",
origin: { turnId: "turn_0", stepIndex: 0 },
diff --git a/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts b/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts
deleted file mode 100644
index e7a4c231e..000000000
--- a/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { DurableSessionState } from "#execution/durable-session-store.js";
-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
-import {
- getBackgroundTasks,
- readWorkflowTaskView,
- type BackgroundWorkflowToolRun,
-} from "#harness/workflow-tool-runs.js";
-import { captureLogRecords } from "#internal/testing/log-records.js";
-
-const { cancelOwnedTaskMock, deserializeContextMock, hydrateDurableSessionMock } = vi.hoisted(
- () => ({
- cancelOwnedTaskMock: vi.fn(),
- deserializeContextMock: vi.fn(),
- hydrateDurableSessionMock: vi.fn(),
- }),
-);
-
-vi.mock("#context/serialize.js", () => ({ deserializeContext: deserializeContextMock }));
-vi.mock("#execution/effective-agent-config.js", () => ({
- resolveEffectiveAgentRuntime: vi.fn(() => ({ turnAgent: "turn-agent" })),
-}));
-vi.mock("#execution/session.js", () => ({ hydrateDurableSession: hydrateDurableSessionMock }));
-vi.mock("#execution/tasks/parent/dispatch.js", () => ({ cancelOwnedTask: cancelOwnedTaskMock }));
-
-describe("cancelAllIndexedSessionTasksStep", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- cancelOwnedTaskMock.mockImplementation(
- async ({ entry }: { entry: BackgroundWorkflowToolRun }) => cancelledView(entry),
- );
- deserializeContextMock.mockResolvedValue({ require: vi.fn(() => "bundle") });
- hydrateDurableSessionMock.mockReturnValue("runtime-session");
- });
-
- it("cancels every indexed task sequentially with the hydrated parent session", async () => {
- const logs = captureLogRecords();
- const task1 = indexedTask("task-1");
- const task2 = indexedTask("task-2");
-
- const result = await cancelAllIndexedSessionTasksStep({
- serializedContext: { context: "latest" },
- sessionState: makeSessionState([task1, task2]),
- });
-
- expect(result.sessionState).toBeDefined();
- expect(
- getBackgroundTasks(result.sessionState?.snapshot.session.state)
- .query()
- .map((task) => readWorkflowTaskView(task.run.task)),
- ).toEqual([cancelledView(task1), cancelledView(task2)]);
- expect(cancelOwnedTaskMock).toHaveBeenCalledTimes(2);
- expect(cancelOwnedTaskMock).toHaveBeenNthCalledWith(1, {
- cancelOwnedWork: expect.any(Function),
- entry: task1,
- serializedContext: { context: "latest" },
- session: "runtime-session",
- });
- expect(cancelOwnedTaskMock).toHaveBeenNthCalledWith(2, {
- cancelOwnedWork: expect.any(Function),
- entry: task2,
- serializedContext: { context: "latest" },
- session: "runtime-session",
- });
- expect(logs.records).toContainEqual(
- expect.objectContaining({
- level: "warn",
- message: "failed to settle background task instrumentation",
- }),
- );
- });
-
- it("leaves a task working when cancellation fails", async () => {
- const logs = captureLogRecords();
- cancelOwnedTaskMock.mockRejectedValueOnce(new Error("Cancellation unavailable"));
- const result = await cancelAllIndexedSessionTasksStep({
- serializedContext: {},
- sessionState: makeSessionState([indexedTask("failed-cancel"), indexedTask("cancelled")]),
- });
- expect(
- getBackgroundTasks(result.sessionState?.snapshot.session.state)
- .query()
- .map((task) => task.status),
- ).toEqual(["working", "cancelled"]);
- expect(logs.records).toContainEqual(
- expect.objectContaining({ level: "error", message: "failed to cancel indexed task" }),
- );
- expect(logs.records).toContainEqual(
- expect.objectContaining({
- level: "warn",
- message: "failed to settle background task instrumentation",
- }),
- );
- });
-
- it("does not require runtime context when no tasks are indexed", async () => {
- await expect(
- cancelAllIndexedSessionTasksStep({ sessionState: makeSessionState([]) }),
- ).resolves.toEqual({ sessionState: makeSessionState([]) });
-
- expect(deserializeContextMock).not.toHaveBeenCalled();
- expect(cancelOwnedTaskMock).not.toHaveBeenCalled();
- });
-});
-
-function indexedTask(taskId: string): BackgroundWorkflowToolRun {
- return {
- callId: taskId,
- toolName: "research",
- lifetime: "session" as const,
- origin: { turnId: "turn_0", stepIndex: 0 },
- address: { runId: `${taskId}-run`, hookToken: `${taskId}-inbox` },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "tool", name: "research" },
- taskId,
- },
- };
-}
-
-function makeSessionState(tasks: readonly BackgroundWorkflowToolRun[]): DurableSessionState {
- return {
- continuationToken: "http:test",
- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },
- hasProxyInputRequests: false,
- sessionId: "parent-session",
- snapshot: {
- session: {
- agent: { system: "" },
- continuationToken: "http:test",
- history: [],
- sessionId: "parent-session",
- state: { "eve.workflowTool": { version: 3, runs: tasks } },
- },
- },
- version: 1,
- };
-}
-
-function cancelledView(entry: BackgroundWorkflowToolRun) {
- return { taskId: entry.task.taskId, metadata: entry.task.metadata, status: "cancelled" as const };
-}
diff --git a/packages/eve/src/execution/cancel-indexed-session-tasks-step.ts b/packages/eve/src/execution/cancel-indexed-session-tasks-step.ts
deleted file mode 100644
index ce55b3ced..000000000
--- a/packages/eve/src/execution/cancel-indexed-session-tasks-step.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { recordTerminalTaskViewsStep } from "#execution/tasks/parent/hitl-proxy-steps.js";
-import type { SessionStateTransition } from "#execution/session/state-cursor.js";
-import type { TaskView } from "#tasks/types.js";
-import { deserializeContext } from "#context/serialize.js";
-import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
-import { hydrateDurableSession } from "#execution/session.js";
-import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";
-import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";
-import { createLogger, logError } from "#internal/logging.js";
-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-import { getBackgroundTasks } from "#harness/workflow-tool-runs.js";
-
-const log = createLogger("execution.cancel-indexed-session-tasks");
-
-/** Cooperatively cancels every task currently indexed by a durable session. */
-export async function cancelAllIndexedSessionTasksStep(input: {
- readonly serializedContext?: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<SessionStateTransition> {
- "use step";
-
- let durable;
- try {
- durable = readDurableSession(input.sessionState);
- } catch (error) {
- logError(log, "failed to read the session for indexed task cancellation", error, {
- parentSessionId: input.sessionState.sessionId,
- });
- return { sessionState: input.sessionState };
- }
-
- let tasks;
- let working;
- try {
- tasks = getBackgroundTasks(durable.state);
- working = tasks.query({ state: "working" });
- } catch (error) {
- logError(log, "failed to read the task index", error, {
- parentSessionId: durable.sessionId,
- });
- return { sessionState: input.sessionState };
- }
- // A cancelled task is retried: its earlier cancellation may have committed before its child
- // stopped. Reading retained outcomes can fail without blocking cancellation of live work.
- let retries: typeof working = [];
- try {
- retries = tasks.query({ state: "cancelled" });
- } catch (error) {
- logError(log, "failed to read cancelled task outcomes", error, {
- parentSessionId: durable.sessionId,
- });
- }
- const entries = [...working, ...retries].map((task) => task.run);
- if (entries.length === 0) return { sessionState: input.sessionState };
- if (input.serializedContext === undefined) {
- throw new Error("Indexed task cancellation requires serialized runtime context.");
- }
-
- const ctx = await deserializeContext(input.serializedContext);
- const bundle = ctx.require(BundleKey);
- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
- const session = hydrateDurableSession({
- durable,
- turnAgent: effectiveAgent.turnAgent,
- });
-
- const views: TaskView[] = [];
- for (const entry of entries) {
- try {
- const view = await cancelOwnedTask({
- cancelOwnedWork: cancelBackgroundAgentTask,
- entry,
- serializedContext: input.serializedContext,
- session,
- });
- views.push(view);
- } catch (error) {
- logError(log, "failed to cancel indexed task", error, {
- parentSessionId: durable.sessionId,
- taskId: entry.task.taskId,
- });
- }
- }
- // Session finalization closes the inbox before cancellation, so it cannot
- // rely on child notifications to record outcomes or settle activity.
- return await recordTerminalTaskViewsStep({
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- views,
- });
-}
diff --git a/packages/eve/src/execution/cancelled-model-call-batch.ts b/packages/eve/src/execution/cancelled-model-call-batch.ts
index dfed51418..01d400ad9 100644
--- a/packages/eve/src/execution/cancelled-model-call-batch.ts
+++ b/packages/eve/src/execution/cancelled-model-call-batch.ts
@@ -5,10 +5,8 @@ import { serializeContext } from "#context/serialize.js";
import { preserveCancelledTurnMessage } from "#execution/cancelled-turn-message.js";
import { createDurableSessionState } from "#execution/durable-session-store.js";
import type { DurableStepResult } from "#execution/session/turn-step-types.js";
-import { readRetainedBackgroundToolResult } from "#execution/tasks/parent/tool-execution.js";
import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";
import { preserveSerializedInstrumentationState } from "#instrumentation/state.js";
-import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";
import { preserveSerializedAgentTraceState } from "#tracing/agent-trace-context-store.js";
export interface CompletedModelCallCheckpoint {
@@ -25,12 +23,7 @@ export async function createCancelledModelCallBatchResult(input: {
readonly stepInput: StepInput | undefined;
}): Promise<DurableStepResult> {
const interruptedContext = serializeContext(input.ctx);
- const retained = readRetainedBackgroundToolResult(input.ctx);
- const backgroundTaskSession =
- retained?.backgroundTaskSession ?? input.checkpoint?.result.backgroundTaskSession;
- const backgroundTasks = retained?.backgroundTasks ?? input.checkpoint?.result.backgroundTasks;
- const checkpointSession =
- backgroundTaskSession ?? input.checkpoint?.result.session ?? input.initialSession;
+ const checkpointSession = input.checkpoint?.result.session ?? input.initialSession;
const cancelledSession =
input.checkpoint === undefined
? await contextStorage.run(input.ctx, () =>
@@ -44,17 +37,6 @@ export async function createCancelledModelCallBatchResult(input: {
return {
action: "cancelled",
- ...(backgroundTaskSession === undefined || backgroundTasks === undefined
- ? {}
- : {
- backgroundTaskContext: preserveSerializedBackgroundTaskObservabilityState(
- input.beforeBatchContext,
- interruptedContext,
- backgroundTasks,
- ),
- backgroundTaskState: createDurableSessionState({ session: cancelledSession }),
- backgroundTasks,
- }),
serializedContext: preserveSerializedInstrumentationState(
preserveSerializedAgentTraceState(
preserveSerializedSessionDynamicModelSelection(checkpointContext, interruptedContext),
diff --git a/packages/eve/src/execution/cancelled-turn-message.test.ts b/packages/eve/src/execution/cancelled-turn-message.test.ts
index 96230b55e..f6a024102 100644
--- a/packages/eve/src/execution/cancelled-turn-message.test.ts
+++ b/packages/eve/src/execution/cancelled-turn-message.test.ts
@@ -19,19 +19,19 @@ function session(): HarnessSession {
}
describe("preserveCancelledTurnMessage", () => {
- it("preserves the framework kind on a cancelled task delivery", async () => {
+ it("preserves the framework kind on a cancelled framework delivery", async () => {
const result = await preserveCancelledTurnMessage(
session(),
markFrameworkStepInput(
- { message: "Background task task_1 completed." },
- "execution.background_task",
+ { message: "Continue the interrupted turn." },
+ "execution.continuation",
),
);
expect(result.history).toEqual([
{
- content: "Background task task_1 completed.",
- kind: "execution.background_task",
+ content: "Continue the interrupted turn.",
+ kind: "execution.continuation",
role: "user",
},
]);
diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.ts
index e761e65b7..bf40fb293 100644
--- a/packages/eve/src/execution/coordination-dispatch-shared.ts
+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts
@@ -33,11 +33,7 @@ import {
} 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 { RuntimeActionResult, RuntimeWorkflowTaskRequest } from "#shared/action-types.js";
import type { SessionParent } from "#channel/types.js";
import {
createDurableSessionState,
@@ -47,15 +43,12 @@ import {
import { hydrateDurableSession } from "#execution/session.js";
import { buildSubagentRunInput } from "#subagents/tool.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
-import { isTaskControlAction } from "#execution/tasks/parent/dispatch.js";
import type { WorkflowToolRunOwner } from "#execution/tools/workflow/messages.js";
import { resolveWorkflowAgentMetadata } from "#execution/tools/subagent/metadata.js";
+import { readDynamicSubagentSelections } from "#context/dynamic-subagent-lifecycle.js";
+import type { DynamicSubagentSelections } from "#execution/agent-sessions/target.js";
import type { WorkflowAgentMetadata } from "#tools/workflow-definition.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;
@@ -72,7 +65,7 @@ export interface CoordinationDispatchResult {
}
/** Everything preflight produces before either step's dispatch loop runs. */
-export interface PreparedCoordinationDispatch<PlanEntry = DispatchPlanEntry> {
+export interface PreparedCoordinationDispatch<PlanEntry = RuntimeWorkflowTaskRequest> {
readonly adapter: ChannelAdapter;
readonly adapterCtx: ChannelAdapterContext;
readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
@@ -80,6 +73,7 @@ export interface PreparedCoordinationDispatch<PlanEntry = DispatchPlanEntry> {
readonly bundle: CompiledBundle;
readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ readonly dynamicSubagentSelections: DynamicSubagentSelections;
readonly inheritedConversation: Parameters<
typeof buildSubagentRunInput
>[0]["inheritedConversation"];
@@ -116,7 +110,7 @@ export async function prepareCoordinationDispatch(input: {
const pending = getPendingCoordinationBatch(durableSession.state);
if (pending === undefined) return undefined;
- const requests = [...pending.runtimeActions, ...pending.tasks];
+ const requests = 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 };
@@ -129,7 +123,7 @@ export async function prepareCoordinationDispatch(input: {
},
ctx,
durableSession,
- plan: () => planDispatch({ requests }),
+ plan: () => requests,
serializedContext: input.serializedContext,
});
if (event === pending.event) {
@@ -148,8 +142,6 @@ export async function prepareCoordinationDispatch(input: {
};
}
-type DispatchRequest = RuntimeToolCallActionRequest | RuntimeWorkflowTaskRequest;
-
interface DispatchBatch {
readonly event: {
readonly sequence: number;
@@ -223,6 +215,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {
bundle,
capabilities: ctx.get(CapabilitiesKey),
channelMetadata: ctx.get(ChannelInstrumentationKey),
+ dynamicSubagentSelections: readDynamicSubagentSelections(ctx),
inheritedConversation: ctx.get(ConversationContextKey),
fanoutSize: input.fanoutSize ?? batch.localFanoutSize ?? 0,
initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,
@@ -265,21 +258,3 @@ function resolveActiveSandboxSessionId(adapterState: unknown, sessionId: string)
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
index 17719846d..651027787 100644
--- a/packages/eve/src/execution/coordination-dispatch-step.ts
+++ b/packages/eve/src/execution/coordination-dispatch-step.ts
@@ -1,4 +1,4 @@
-/** Starts workflow-tool runs and framework controls for pending coordination. */
+/** Starts workflow-tool runs for pending coordination. */
import {
prepareCoordinationDispatch,
@@ -6,9 +6,8 @@ import {
type CoordinationDispatchResult,
} from "#execution/coordination-dispatch-shared.js";
import { createDurableSessionState } from "#execution/durable-session-store.js";
-import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";
-import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";
import { startWorkflowTask } from "#execution/tools/workflow/start.js";
+import { captureAgentSessionContext } from "#execution/agent-sessions/context.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
type CoordinationDispatchStepInput = CoordinationDispatchInput & {
@@ -35,33 +34,20 @@ export async function dispatchCoordinationStep(
let nextSession = session;
const results: RuntimeActionResult[] = [];
- for (const entry of prepared.plan) {
- if (entry.kind === "workflow-task") {
- const started = await startWorkflowTask({
- agents: prepared.workflowAgents,
- auth: prepared.auth,
- batchEvent: batch.event,
- canRequestInput: prepared.capabilities?.requestInput === true,
- initiatorAuth: prepared.initiatorAuth,
- owner: input.workflowToolRunOwner,
- 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,
- cancelOwnedWork: cancelBackgroundAgentTask,
- serializedContext: prepared.serializedContext,
- session: nextSession,
- });
- nextSession = control.session;
- results.push(control.result);
- }
+ for (const task of prepared.plan) {
+ const started = await startWorkflowTask({
+ agentContext: captureAgentSessionContext(prepared, task.callId),
+ agents: prepared.workflowAgents,
+ auth: prepared.auth,
+ batchEvent: batch.event,
+ initiatorAuth: prepared.initiatorAuth,
+ owner: input.workflowToolRunOwner,
+ parentSession: prepared.parentSession,
+ session: nextSession,
+ task,
+ });
+ nextSession = started.session;
+ if (started.result !== undefined) results.push(started.result);
}
return {
diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.ts
index 8e895a78f..0220dc9b1 100644
--- a/packages/eve/src/execution/create-session-step.test.ts
+++ b/packages/eve/src/execution/create-session-step.test.ts
@@ -18,27 +18,6 @@ const TestTurnAgent: RuntimeTurnAgent = {
};
describe("createSessionStep", () => {
- it("preserves task ownership without injecting progress-reporting instructions", async () => {
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
- resolvedAgent: {
- config: {},
- },
- turnAgent: TestTurnAgent,
- } as never);
-
- const { state } = await createSessionStep({
- compiledArtifactsSource: { kind: "bundled" },
- continuationToken: "subagent:test",
- sessionId: "sess-child",
- taskId: "task-1",
- });
-
- expect(state.snapshot.session.agent.system).not.toContain("Background task updates");
- expect(state.snapshot.session.agent.system).not.toContain("task_update");
- expect(state.snapshot.session.taskId).toBe("task-1");
- expect(state.snapshot.session.state).toBeUndefined();
- });
-
it("defaults root sessions to the root input token budget", async () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
resolvedAgent: {
diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.ts
index 2a7472c7b..361c09e41 100644
--- a/packages/eve/src/execution/create-session-step.ts
+++ b/packages/eve/src/execution/create-session-step.ts
@@ -39,7 +39,6 @@ export async function createSessionStep(input: {
readonly nodeId?: string;
readonly rootSessionId?: string;
readonly sessionId: string;
- readonly taskId?: string;
}): Promise<CreateSessionStepResult> {
"use step";
@@ -80,7 +79,6 @@ export async function createSessionStep(input: {
outputSchema: input.outputSchema,
rootSessionId: input.rootSessionId,
sessionId: input.sessionId,
- taskId: input.taskId,
turnAgent: effectiveAgent.turnAgent,
});
diff --git a/packages/eve/src/execution/deliver-payloads.test.ts b/packages/eve/src/execution/deliver-payloads.test.ts
index a1f8b1e82..6ca529bef 100644
--- a/packages/eve/src/execution/deliver-payloads.test.ts
+++ b/packages/eve/src/execution/deliver-payloads.test.ts
@@ -61,54 +61,4 @@ 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 d674aa80d..8aeff8087 100644
--- a/packages/eve/src/execution/deliver-payloads.ts
+++ b/packages/eve/src/execution/deliver-payloads.ts
@@ -2,15 +2,7 @@ import type { DeliverPayload } from "#channel/types.js";
import { coalesceTurnInputs } from "#harness/messages.js";
import type { StepInput } from "#harness/types.js";
-const COALESCED_DELIVER_FIELDS = [
- "context",
- "inputResponses",
- "message",
- "outputSchema",
- "task",
-] as const;
-
-type TaskEnvelope = NonNullable<DeliverPayload["task"]>;
+const COALESCED_DELIVER_FIELDS = ["context", "inputResponses", "message", "outputSchema"] as const;
/** Coalesces channel payloads while preserving turn input and adapter-specific fields. */
export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): DeliverPayload {
@@ -18,17 +10,9 @@ export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): De
if (payloads.length === 1) return payloads[0] ?? {};
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)) {
if (value !== undefined) {
merged[key] = value;
@@ -41,12 +25,5 @@ export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): De
delete merged[field];
}
- 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;
-
return Object.assign(merged, turnInput);
}
diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.ts
index e2ac1c277..0e7d3c17b 100644
--- a/packages/eve/src/execution/durable-session-store.ts
+++ b/packages/eve/src/execution/durable-session-store.ts
@@ -59,7 +59,6 @@ export interface DurableSession {
readonly outputSchema?: JsonObject;
readonly state?: SessionStateMap;
readonly sandboxState?: SandboxState;
- readonly taskId?: string;
readonly agent: {
readonly system: string;
};
diff --git a/packages/eve/src/execution/dynamic-workflow/program-step.scenario.test.ts b/packages/eve/src/execution/dynamic-workflow/program-step.scenario.test.ts
index 0f652f258..67b372b95 100644
--- a/packages/eve/src/execution/dynamic-workflow/program-step.scenario.test.ts
+++ b/packages/eve/src/execution/dynamic-workflow/program-step.scenario.test.ts
@@ -110,7 +110,11 @@ try {
});
it("enforces the total call budget through the real sandbox", async () => {
- const agent = vi.fn().mockResolvedValue("ok");
+ const agent = vi.fn(() => ({
+ send: async () => ({
+ result: async () => ({ data: undefined, message: "ok", status: "waiting" }),
+ }),
+ }));
const ctx = {
abortSignal: new AbortController().signal,
agent,
diff --git a/packages/eve/src/execution/dynamic-workflow/program-step.ts b/packages/eve/src/execution/dynamic-workflow/program-step.ts
index 0cdd6858d..00dbf949f 100644
--- a/packages/eve/src/execution/dynamic-workflow/program-step.ts
+++ b/packages/eve/src/execution/dynamic-workflow/program-step.ts
@@ -1,5 +1,6 @@
import { jsonSchema, type ToolSet } from "ai";
+import { FatalError } from "#compiled/@workflow/core/index.js";
import {
WORKFLOW_PROGRAM_BRIDGE_REQUEST_LIMIT,
WORKFLOW_PROGRAM_CALL_INTERRUPT_KIND,
@@ -8,6 +9,7 @@ import {
type WorkflowProgramCallInterrupt,
type WorkflowProgramInput,
} from "#execution/dynamic-workflow/schema.js";
+import { toErrorMessage } from "#shared/errors.js";
import {
continueWorkflowSandboxInterrupt,
createParkingHostTool,
@@ -41,7 +43,6 @@ const agentBridgeSchema = jsonSchema({
input: {
additionalProperties: false,
properties: {
- agentId: { type: "string" },
message: { type: "string" },
outputSchema: { type: "object" },
},
@@ -60,6 +61,17 @@ export async function runWorkflowProgramStep(
): Promise<WorkflowProgramStepOutcome> {
"use step";
+ try {
+ return await runWorkflowProgram(input);
+ } catch (error) {
+ // The sandbox is deterministic, so a failed program fails the same way on every retry.
+ throw new FatalError(toErrorMessage(error));
+ }
+}
+
+async function runWorkflowProgram(
+ input: WorkflowProgramStepInput,
+): Promise<WorkflowProgramStepOutcome> {
const tools = buildWorkflowProgramTools();
const security = input.program.continuationSecurity as WorkflowSandboxContinuationSecurity;
let raw: unknown;
diff --git a/packages/eve/src/execution/dynamic-workflow/schema.test.ts b/packages/eve/src/execution/dynamic-workflow/schema.test.ts
index 0f6f23122..01e398eba 100644
--- a/packages/eve/src/execution/dynamic-workflow/schema.test.ts
+++ b/packages/eve/src/execution/dynamic-workflow/schema.test.ts
@@ -23,7 +23,6 @@ describe("workflow program schema", () => {
readWorkflowProgramAgentCall({
target: "researcher",
input: {
- agentId: "agent-1",
message: "continue",
outputSchema: { properties: { ok: { type: "boolean" } }, type: "object" },
},
@@ -31,7 +30,6 @@ describe("workflow program schema", () => {
).toEqual({
target: "researcher",
input: {
- agentId: "agent-1",
message: "continue",
outputSchema: { properties: { ok: { type: "boolean" } }, type: "object" },
},
diff --git a/packages/eve/src/execution/dynamic-workflow/schema.ts b/packages/eve/src/execution/dynamic-workflow/schema.ts
index ca90df6e0..123c7ac96 100644
--- a/packages/eve/src/execution/dynamic-workflow/schema.ts
+++ b/packages/eve/src/execution/dynamic-workflow/schema.ts
@@ -26,9 +26,8 @@ export interface WorkflowProgramInput {
export type WorkflowProgramOptions = Pick<WorkflowProgramInput, "maxSubagents">;
-interface WorkflowProgramAgentCall {
+export interface WorkflowProgramAgentCall {
readonly input: {
- readonly agentId?: string;
readonly message: string;
readonly outputSchema?: JsonObject;
};
@@ -72,15 +71,10 @@ export function readWorkflowProgramAgentCall(value: unknown): WorkflowProgramAge
if (typeof rawInput.message !== "string") {
throw new TypeError('Workflow program ctx.agent() requires a "message" string.');
}
- if (rawInput.agentId !== undefined && typeof rawInput.agentId !== "string") {
- throw new TypeError('Workflow program ctx.agent() "agentId" must be a string.');
- }
const input: {
- agentId?: string;
message: string;
outputSchema?: JsonObject;
} = { message: rawInput.message };
- if (rawInput.agentId !== undefined) input.agentId = rawInput.agentId;
if (rawInput.outputSchema !== undefined) {
input.outputSchema = parseJsonObject(rawInput.outputSchema);
}
diff --git a/packages/eve/src/execution/dynamic-workflow/workflow.test.ts b/packages/eve/src/execution/dynamic-workflow/workflow.test.ts
index 424301c10..069cebdb8 100644
--- a/packages/eve/src/execution/dynamic-workflow/workflow.test.ts
+++ b/packages/eve/src/execution/dynamic-workflow/workflow.test.ts
@@ -20,7 +20,17 @@ const pending = {
toolName: "agent",
},
} as never;
-const agent = vi.fn();
+/** Each child's reply to the one message a program sends it. */
+const reply = vi.fn();
+const agent = (target: string) => ({
+ send: async (message: string) => ({
+ result: async () => ({
+ data: undefined,
+ message: await reply(target, message),
+ status: "waiting",
+ }),
+ }),
+});
const ctx = {
abortSignal: new AbortController().signal,
agent,
@@ -35,10 +45,10 @@ describe("runJsProgram", () => {
mocks.runWorkflowProgramStep
.mockResolvedValueOnce({ interrupt: pending, pending: [pending], status: "interrupted" })
.mockResolvedValueOnce({ output: { result: "done" }, status: "completed" });
- agent.mockResolvedValue({ result: "child" });
+ reply.mockResolvedValue({ result: "child" });
await expect(runJsProgram("return 1", ctx, options)).resolves.toEqual({ result: "done" });
- expect(agent).toHaveBeenCalledWith("researcher", { message: "one" });
+ expect(reply).toHaveBeenCalledWith("researcher", "one");
expect(mocks.runWorkflowProgramStep).toHaveBeenLastCalledWith(
expect.objectContaining({
resume: {
@@ -66,12 +76,12 @@ describe("runJsProgram", () => {
status: "interrupted",
})
.mockResolvedValueOnce({ output: ["one", "two"], status: "completed" });
- agent.mockImplementation((_target, call: { readonly message: string }) =>
- call.message === "one" ? first.promise : second.promise,
+ reply.mockImplementation((_target, message: string) =>
+ message === "one" ? first.promise : second.promise,
);
const result = runJsProgram("return 1", ctx, options);
- await vi.waitFor(() => expect(agent).toHaveBeenCalledTimes(2));
+ await vi.waitFor(() => expect(reply).toHaveBeenCalledTimes(2));
first.resolve("one");
await Promise.resolve();
expect(mocks.runWorkflowProgramStep).toHaveBeenCalledTimes(1);
@@ -85,7 +95,7 @@ describe("runJsProgram", () => {
mocks.runWorkflowProgramStep
.mockResolvedValueOnce({ interrupt: pending, pending: [pending], status: "interrupted" })
.mockResolvedValueOnce({ output: "caught", status: "completed" });
- agent.mockRejectedValue(new Error("child failed"));
+ reply.mockRejectedValue(new Error("child failed"));
await expect(runJsProgram("return 1", ctx, options)).resolves.toBe("caught");
expect(mocks.runWorkflowProgramStep).toHaveBeenLastCalledWith(
@@ -107,10 +117,10 @@ describe("runJsProgram", () => {
status: "interrupted",
})
.mockResolvedValueOnce({ output: "limited", status: "completed" });
- agent.mockResolvedValueOnce("one").mockResolvedValueOnce("two");
+ reply.mockResolvedValueOnce("one").mockResolvedValueOnce("two");
await expect(runJsProgram("return 1", ctx, options)).resolves.toBe("limited");
- expect(agent).toHaveBeenCalledTimes(2);
+ expect(reply).toHaveBeenCalledTimes(2);
expect(mocks.runWorkflowProgramStep).toHaveBeenLastCalledWith(
expect.objectContaining({
resume: expect.objectContaining({
@@ -148,7 +158,7 @@ describe("runJsProgram", () => {
pending: [pending],
status: "interrupted",
});
- agent.mockImplementation(async () => {
+ reply.mockImplementation(async () => {
controller.abort(new Error("owner cancelled"));
throw new Error("child stopped");
});
diff --git a/packages/eve/src/execution/dynamic-workflow/workflow.ts b/packages/eve/src/execution/dynamic-workflow/workflow.ts
index 2b80f5418..7e5d4b3f8 100644
--- a/packages/eve/src/execution/dynamic-workflow/workflow.ts
+++ b/packages/eve/src/execution/dynamic-workflow/workflow.ts
@@ -4,6 +4,7 @@ import {
parseWorkflowProgramOptions,
readWorkflowProgramAgentCall,
readWorkflowProgramCallInterrupt,
+ type WorkflowProgramAgentCall,
type WorkflowProgramInput,
} from "#execution/dynamic-workflow/schema.js";
import {
@@ -52,7 +53,7 @@ export async function runJsProgram(
};
}
try {
- const output = await ctx.agent(call.target, call.input);
+ const output = await callProgramAgent(ctx, call);
return { status: "completed" as const, output };
} catch (error) {
ctx.abortSignal.throwIfAborted();
@@ -68,4 +69,21 @@ export async function runJsProgram(
return outcome.output;
}
+/** Sends one program agent call to a new session and returns that turn's reply. */
+async function callProgramAgent(
+ ctx: WorkflowToolContext,
+ call: WorkflowProgramAgentCall,
+): Promise<JsonValue> {
+ const { message, outputSchema } = call.input;
+ const response = await ctx
+ .agent(call.target)
+ .send<JsonValue>(message, { outputSchema, signal: ctx.abortSignal });
+ const result = await response.result();
+ if (result.status === "failed") {
+ throw new Error(`Agent "${call.target}" failed to handle the message.`);
+ }
+ if (outputSchema !== undefined) return result.data ?? null;
+ return result.message ?? null;
+}
+
export { MAX_WORKFLOW_PROGRAM_MAX_SUBAGENTS };
diff --git a/packages/eve/src/execution/legacy-session/inbox.ts b/packages/eve/src/execution/legacy-session/inbox.ts
index dc3d73bbc..ccde4e6b4 100644
--- a/packages/eve/src/execution/legacy-session/inbox.ts
+++ b/packages/eve/src/execution/legacy-session/inbox.ts
@@ -79,25 +79,9 @@ export function encodeLegacyCommand(command: Command, declaredVersion: unknown):
throw new UnsupportedLegacySessionError();
}
if (command.kind !== "send" && command.kind !== "deliver") {
- const value: Record<string, unknown> = { ...command, version };
- if (command.kind === "cancel" && version < 6) {
- if (command.tasks === true)
- throw new Error("This session cannot cancel owned tasks before import.");
- delete value.tasks;
- }
- return value;
+ return { ...command, version };
}
- const payloads = (command.kind === "send" ? [command.payload] : command.payloads).map(
- (payload) => {
- if (payload.task === undefined || version >= 5) return payload;
- const {
- agentRequests: _agentRequests,
- inputRequests: _inputRequests,
- ...task
- } = payload.task;
- return { ...payload, task };
- },
- );
+ const payloads = command.kind === "send" ? [command.payload] : command.payloads;
let caller = command.caller;
if (caller?.activityObserver !== undefined && version < 7) {
const { activityObserver, ...rest } = caller;
@@ -130,7 +114,6 @@ export function encodeLegacyCommand(command: Command, declaredVersion: unknown):
payload: coalesceDeliverPayloads(payloads),
payloads,
requestId: command.requestId,
- taskDeliveryId: command.taskDeliveryId,
turnPolicy: command.turnPolicy,
version,
};
diff --git a/packages/eve/src/execution/legacy-session/input.test.ts b/packages/eve/src/execution/legacy-session/input.test.ts
index 06be72600..f8eb5470e 100644
--- a/packages/eve/src/execution/legacy-session/input.test.ts
+++ b/packages/eve/src/execution/legacy-session/input.test.ts
@@ -40,24 +40,6 @@ describe("legacy turn input", () => {
expect(input.serializedContext).toEqual(committed.serializedContext);
expect(input.delivery).toBeUndefined();
});
- it("uses the final committed checkpoint instead of the earlier background-task checkpoint", () => {
- const finalState = { sessionId: "old", snapshot: "final" };
- const input = readLegacyTurnInput({
- version: 2,
- stepInput: step,
- completionToken: "old:turn:0",
- initialStep: {
- result: {
- action: "park",
- sessionState: finalState,
- serializedContext: { final: true },
- backgroundTaskState: { sessionId: "old", snapshot: "before" },
- },
- },
- });
- expect(input.sessionState).toEqual(finalState);
- expect(input.delivery).toBeUndefined();
- });
it("rejects unknown formats before publishing an owner", () => {
expect(() => readLegacyTurnInput({ version: 3 })).toThrow("Unsupported");
expect(() => readLegacyTurnInput({ version: 2 })).toThrow("Invalid");
diff --git a/packages/eve/src/execution/legacy-session/input.ts b/packages/eve/src/execution/legacy-session/input.ts
index 398ba431f..1437ad787 100644
--- a/packages/eve/src/execution/legacy-session/input.ts
+++ b/packages/eve/src/execution/legacy-session/input.ts
@@ -25,13 +25,8 @@ export function readLegacyTurnInput(value: unknown): LegacyTurnInput {
isObject(value.initialStep) && isObject(value.initialStep.result)
? value.initialStep.result
: undefined;
- const state =
- (committed?.action === "cancelled" ? committed.backgroundTaskState : undefined) ??
- committed?.sessionState ??
- committed?.backgroundTaskState ??
- step.sessionState;
- const context =
- committed?.serializedContext ?? committed?.backgroundTaskContext ?? step.serializedContext;
+ const state = committed?.sessionState ?? step.sessionState;
+ const context = committed?.serializedContext ?? step.serializedContext;
if (
!isObject(state) ||
typeof state.sessionId !== "string" ||
diff --git a/packages/eve/src/execution/model-call-batching.ts b/packages/eve/src/execution/model-call-batching.ts
index 8a0cd03ec..1fe4812ee 100644
--- a/packages/eve/src/execution/model-call-batching.ts
+++ b/packages/eve/src/execution/model-call-batching.ts
@@ -46,9 +46,7 @@ function shouldRunAnotherModelCall(input: {
}): boolean {
if (
input.completedModelCalls >= input.modelCallsPerStep ||
- typeof input.result.next !== "function" ||
- input.result.backgroundTaskSession !== undefined ||
- input.result.backgroundTasks !== undefined
+ typeof input.result.next !== "function"
) {
return false;
}
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 b09c5ec16..60ed2cb58 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
@@ -13,6 +13,7 @@ import {
notifyTurnCallerStep,
resolveInitialTurnCallerStep,
} from "#subagents/parent-notification.js";
+import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";
import { startRemoteAgentSession } from "#subagents/remote-dispatch.js";
import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
import { authHookToken, CallbackBaseUrlKey, getHookUrl } from "#harness/authorization.js";
@@ -238,6 +239,7 @@ describe("multi-agent callback routing", () => {
response.end(
JSON.stringify({
ok: true,
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
sessionId: "remote-session-1",
status: "accepted",
}),
@@ -417,7 +419,6 @@ describe("multi-agent callback routing", () => {
const sessionCallback = {
callId: "call-support",
subagentName: "research",
- taskId: "task-support",
...callback,
};
const serializedContext = {
diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.ts
index bf1d86ea2..242f0fc02 100644
--- a/packages/eve/src/execution/node-step.test.ts
+++ b/packages/eve/src/execution/node-step.test.ts
@@ -196,7 +196,6 @@ async function createNodeWithSourceOwnedTools(input: {
: undefined,
description: frameworkAgent ? AGENT_TOOL_DESCRIPTION : `${name} programmatic tool.`,
execute: async () => `${name}-sentinel`,
- execution: frameworkAgent ? "background" : undefined,
inputSchema: frameworkAgent ? SUBAGENT_TOOL_INPUT_SCHEMA : null,
logicalPath: `tools/${name}.ts`,
name,
@@ -260,7 +259,7 @@ describe("createNodeHarnessTools", () => {
expect(createNodeHarnessTools({ node }).get("web_search")?.label?.start).toBeUndefined();
});
- it("lowers the compiled framework agent tool as a background tool", async () => {
+ it("lowers the compiled framework agent tool as a workflow tool", async () => {
const node = await createNodeWithSourceOwnedTools({ names: ["agent"] });
const agentTool = createNodeHarnessTools({ node }).get("agent");
@@ -270,9 +269,8 @@ describe("createNodeHarnessTools", () => {
expect(agentTool?.description).toContain("include essential context");
expect(agentTool?.description).toContain("non-overlapping scopes");
expect(agentTool?.description).not.toContain("eve");
- expect(agentTool?.execution).toBe("background");
- expect(agentTool?.runtimeAction).toBeUndefined();
- expect(agentTool?.execute).toBeDefined();
+ expect(agentTool?.execute).toBeUndefined();
+ expect(agentTool?.workflowId).toBe("workflow//eve//subagentToolExecuteWorkflow");
});
it("keeps an authored agent tool separate from self-delegation", async () => {
@@ -283,22 +281,12 @@ describe("createNodeHarnessTools", () => {
const agentTool = createNodeHarnessTools({ node }).get("agent");
expect(agentTool?.availableInSubagents).toBeUndefined();
- expect(agentTool?.execution).toBeUndefined();
expect(agentTool).not.toHaveProperty("resultKind");
expect(agentTool?.rootOnly).toBeUndefined();
expect(agentTool?.workflowId).toBeUndefined();
});
- it("lowers task_cancel from its framework definition", async () => {
- const node = await createNodeWithSourceOwnedTools({ names: ["task_cancel"] });
- const tools = createNodeHarnessTools({ node });
-
- expect(tools.get("task_cancel")?.runtimeAction).toEqual({ kind: "task-control" });
- expect(tools.get("task_cancel")?.execute).toBeUndefined();
- expect(tools.has("task_sleep")).toBe(false);
- });
-
- it("executes compiled local and remote delegation tools as background tasks", async () => {
+ it("lowers compiled local and remote delegation tools as workflow tools", async () => {
const delegationTools: StaticRuntimeTurnAgent["tools"] = [
createPreparedRuntimeSubagentTool({
description: "Delegate local research.",
@@ -328,22 +316,11 @@ describe("createNodeHarnessTools", () => {
}),
});
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)?.execute).toBeUndefined();
expect(tools.get(name)?.nodeId).toEqual(expect.any(String));
expect(tools.get(name)?.workflowId).toBe("workflow//eve//subagentToolExecuteWorkflow");
}
});
-
- it("does not recreate task tools absent from the compiled graph", async () => {
- const tools = createNodeHarnessTools({
- node: await createNodeWithSourceOwnedTools({ names: [] }),
- });
-
- expect(tools.has("task_update")).toBe(false);
- expect(tools.has("task_cancel")).toBe(false);
- });
});
describe("createExecutionNodeStep", () => {
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index 917f48e98..b5a755149 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -17,7 +17,6 @@ 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, PreparedRuntimeWorkflowTask } from "#runtime/sessions/turn.js";
@@ -28,7 +27,7 @@ import { connectionToolReplayIdentity } from "#execution/tools/connection-search
import {
createPreparedWorkflowToolHarnessDefinition,
createWorkflowToolHarnessDefinition,
-} from "#execution/tools/workflow/background.js";
+} from "#execution/tools/workflow/harness-definition.js";
import {
resolveWebSearchActivityLabel,
WEB_SEARCH_TOOL_NAME,
@@ -262,14 +261,6 @@ function createRegisteredHarnessToolDefinition(input: {
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 };
- }
- }
const rawExecute = def.execute;
const definition: HarnessToolDefinition = {
@@ -282,7 +273,6 @@ function createRegisteredHarnessToolDefinition(input: {
approvalKey: def.approvalKey,
behavior: input.behavior,
description: def.description,
- execution: def.execution,
executeInput: def.executeInput,
execute: resolveAuthoredExecute({
rawExecute,
diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.ts
index d591be64f..9b04177de 100644
--- a/packages/eve/src/execution/proxied-deliver-step.ts
+++ b/packages/eve/src/execution/proxied-deliver-step.ts
@@ -7,28 +7,21 @@ import {
readDurableSession,
replaceDurableSessionSnapshot,
} from "#execution/durable-session-store.js";
+import { relaySessionEvents, type SessionStepState } from "#execution/publish-session-events.js";
import { routeDeliverPayload } from "#subagents/hitl-proxy.js";
-import { sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
import {
- resumeWorkflowToolRunAnswers,
- resumeWorkflowToolRunDismissal,
+ sendWorkflowAskAnswers,
toToolInputResponseResponder,
} from "#execution/tools/workflow/answer.js";
-import { getPendingCoordinationBatch } from "#harness/coordination.js";
-import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
+import type { PendingInputBatchEvent } from "#harness/pending-input-batches.js";
+import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";
import {
createInputResolvedEvent,
- encodeMessageStreamEvent,
type InputResolution,
- stampMessageStreamEvent,
+ type UnstampedMessageStreamEvent,
} from "#protocol/message.js";
-import type { InputResponse } from "#shared/input.js";
-import { getBackgroundTasks } from "#harness/workflow-tool-runs.js";
-import {
- createTaskInputRequestId,
- retireProxyInputRequests,
-} from "#harness/proxy-input-requests.js";
+import { retireProxyInputRequests } from "#harness/proxy-input-requests.js";
export type RoutedDeliverResult =
| {
@@ -44,25 +37,24 @@ export type RoutedDeliverResult =
};
interface ChildBucket {
- readonly answerHook?: AnswerHookRoute;
+ readonly workflowAsk?: WorkflowAskRoute;
readonly childContinuationToken: string;
readonly childSessionInbox?: SessionInboxAddress;
- readonly childResponseUrl?: string;
- readonly dismissedRequestIds: string[];
+ readonly event: PendingInputBatchEvent;
readonly metadata: NonNullable<DeliverHookPayload["deliveryMetadata"]>[number][];
readonly payloads: DeliverPayload[];
- readonly retireRequestIds: string[];
- readonly sourcePayloadIndexes: number[];
- readonly taskId?: string;
+ /** Keyed by request id: a request resolves once however many payloads answer it. */
+ readonly resolutions: Map<string, InputResolution>;
}
-/** Splits an envelope and validates task routes before forwarding descendant input. */
-export async function routeProxiedDeliverStep(input: {
- readonly delivery: DeliverHookPayload;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly serializedContext?: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<RoutedDeliverResult> {
+/**
+ * Splits an envelope and forwards descendant input to the child that asked for
+ * it. This session relayed each forwarded request's `input.requested`, so it
+ * also relays their `input.resolved` once the answers are on their way down.
+ */
+export async function routeProxiedDeliverStep(
+ input: SessionStepState & { readonly delivery: DeliverHookPayload },
+): Promise<RoutedDeliverResult> {
"use step";
let durableSession = readDurableSession(input.sessionState);
const sourceDelivery = input.delivery;
@@ -71,20 +63,15 @@ export async function routeProxiedDeliverStep(input: {
let parentAction: { readonly kind: "cancel-turn" } | undefined;
// Only a person's own message may answer or skip a pending question.
const resolveMessage =
- !hasDelegatedSessionContext(input.serializedContext ?? {}) &&
- sourceDelivery.caller === undefined &&
- sourceDelivery.taskDeliveryId === undefined;
- // Every payload routes against the same state, so an answer-hook request
- // resolved by an earlier payload is hidden from later ones; its hook accepts
+ !hasDelegatedSessionContext(input.serializedContext) && sourceDelivery.caller === undefined;
+ // Every payload routes against the same state, so a `ctx.ask()` question
+ // resolved by an earlier payload is hidden from later ones; its run takes
// one answer, and later messages must reach the parent instead.
const resolvedQuestions = new Set<string>();
for (const [sourcePayloadIndex, payload] of sourceDelivery.payloads.entries()) {
const routed = routeDeliverPayload({
- allowRoute: (requestId, route) =>
- !resolvedQuestions.has(requestId) &&
- (route.taskId === undefined ||
- getBackgroundTasks(durableSession.state).get(route.taskId) !== undefined),
+ allowRoute: (requestId) => !resolvedQuestions.has(requestId),
payload,
resolveMessage,
state: durableSession.state,
@@ -93,32 +80,29 @@ export async function routeProxiedDeliverStep(input: {
if (routed.forSelf !== undefined) parentPayloads.set(sourcePayloadIndex, routed.forSelf);
for (const [childIndex, forChild] of routed.forChildren.entries()) {
- if (forChild.answerHook !== undefined) {
- for (const requestId of forChild.retireRequestIds) resolvedQuestions.add(requestId);
+ if (forChild.workflowAsk !== undefined) {
+ for (const { requestId } of forChild.resolved.resolutions) resolvedQuestions.add(requestId);
}
const key = [
forChild.childContinuationToken,
forChild.childSessionInbox?.sessionId ?? "",
- forChild.childResponseUrl ?? "",
- forChild.taskId ?? "",
].join("\0");
- const child = children.get(key) ?? {
- answerHook: forChild.answerHook,
+ const child: ChildBucket = children.get(key) ?? {
+ workflowAsk: forChild.workflowAsk,
childContinuationToken: forChild.childContinuationToken,
childSessionInbox: forChild.childSessionInbox,
- childResponseUrl: forChild.childResponseUrl,
- dismissedRequestIds: [],
+ event: forChild.resolved.event,
metadata: [],
payloads: [],
- retireRequestIds: [],
- sourcePayloadIndexes: [],
- taskId: forChild.taskId,
+ resolutions: new Map(),
};
const childPayloadIndex = child.payloads.length;
child.payloads.push(forChild.payload);
- child.dismissedRequestIds.push(...(forChild.dismissedRequestIds ?? []));
- child.retireRequestIds.push(...forChild.retireRequestIds);
- child.sourcePayloadIndexes.push(sourcePayloadIndex);
+ for (const resolution of forChild.resolved.resolutions) {
+ if (!child.resolutions.has(resolution.requestId)) {
+ child.resolutions.set(resolution.requestId, resolution);
+ }
+ }
if (routed.forSelf === undefined && childIndex === 0) {
for (const metadata of sourceDelivery.deliveryMetadata ?? []) {
if (metadata.payloadIndex === sourcePayloadIndex) {
@@ -131,85 +115,47 @@ export async function routeProxiedDeliverStep(input: {
}
let retired = false;
+ const resolvedEvents: UnstampedMessageStreamEvent[] = [];
for (const child of children.values()) {
- // 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 = getBackgroundTasks(durableSession.state).get(taskId)?.run;
- if (entry === undefined) {
- mergeStrandedResponses(parentPayloads, child, taskId);
- continue;
- }
- const payload = coalesceDeliverPayloads(child.payloads);
- const delivery = await sendTaskInboundPayload({
- taskInboxToken: entry.address.hookToken,
- payload: {
- auth: sourceDelivery.auth,
- childContinuationToken: child.childContinuationToken,
- childSessionInbox: child.childSessionInbox,
- childResponseUrl: child.childResponseUrl,
- inputResponses: payload.inputResponses ?? [],
- kind: "input-response",
- responder: payload.responder ?? toToolInputResponseResponder(sourceDelivery.auth),
- taskId,
- },
- });
- if (delivery === "unreachable") {
- mergeStrandedResponses(parentPayloads, child, taskId);
- continue;
- }
- durableSession = retireProxyInputRequests(durableSession, child.retireRequestIds);
- retired = true;
- continue;
- }
-
- if (child.answerHook !== undefined) {
- const payload = coalesceDeliverPayloads(child.payloads);
- const responses = payload.inputResponses ?? [];
- await resumeWorkflowToolRunAnswers(
- child.childContinuationToken,
+ if (child.workflowAsk !== undefined) {
+ const responses = coalesceDeliverPayloads(child.payloads).inputResponses ?? [];
+ await sendWorkflowAskAnswers(
+ child.workflowAsk,
responses,
- payload.responder ?? toToolInputResponseResponder(sourceDelivery.auth),
+ toToolInputResponseResponder(sourceDelivery.auth),
+ );
+ } else {
+ const childDelivery: DeliverHookPayload = {
+ ...sourceDelivery,
+ deliveryMetadata: child.metadata.length === 0 ? undefined : child.metadata,
+ payloads: child.payloads,
+ };
+ await resumeSessionInbox(
+ child.childSessionInbox ?? child.childContinuationToken,
+ childDelivery,
+ );
+ }
+ if (child.resolutions.size > 0) {
+ resolvedEvents.push(
+ createInputResolvedEvent({ resolutions: [...child.resolutions.values()], ...child.event }),
);
- if (child.dismissedRequestIds.length > 0) {
- await resumeWorkflowToolRunDismissal(child.childContinuationToken);
- }
- if (child.answerHook.question !== undefined) {
- await emitQuestionResolutions({
- dismissedRequestIds: child.dismissedRequestIds,
- responses,
- sessionState: durableSession.state,
- sessionWritable: input.sessionWritable,
- });
- }
- durableSession = retireProxyInputRequests(durableSession, child.retireRequestIds);
- retired = true;
- continue;
}
-
- const childDelivery: DeliverHookPayload = {
- ...sourceDelivery,
- deliveryMetadata: child.metadata.length === 0 ? undefined : child.metadata,
- payloads: child.payloads,
- };
- await resumeSessionInbox(
- child.childSessionInbox ?? child.childContinuationToken,
- childDelivery,
- );
// Successfully forwarded request IDs are retired so later deliveries
// cannot route through stale entries.
- durableSession = retireProxyInputRequests(durableSession, child.retireRequestIds);
+ durableSession = retireProxyInputRequests(durableSession, [...child.resolutions.keys()]);
retired = true;
}
- const context = {
- serializedContext: input.serializedContext ?? {},
- sessionState: retired
- ? replaceDurableSessionSnapshot({ session: durableSession, state: input.sessionState })
- : input.sessionState,
- };
+ const context = await relaySessionEvents(
+ {
+ serializedContext: input.serializedContext,
+ sessionState: retired
+ ? replaceDurableSessionSnapshot({ session: durableSession, state: input.sessionState })
+ : input.sessionState,
+ sessionWritable: input.sessionWritable,
+ },
+ resolvedEvents,
+ );
if (parentAction !== undefined) return { ...context, ...parentAction };
const orderedParentPayloads = [...parentPayloads].sort(([a], [b]) => a - b);
const parentMetadata = orderedParentPayloads.flatMap(([sourcePayloadIndex], payloadIndex) =>
@@ -227,64 +173,3 @@ export async function routeProxiedDeliverStep(input: {
};
return { ...context, kind: "continue", remainder };
}
-
-// A `ctx.ask()` question is resolved by its workflow, not the harness, so the
-// parent announces the resolution. A blocking run starts from the pending
-// coordination batch, which carries the coordinates of its request.
-async function emitQuestionResolutions(input: {
- readonly dismissedRequestIds: readonly string[];
- readonly responses: readonly InputResponse[];
- readonly sessionState: Parameters<typeof getPendingCoordinationBatch>[0];
- readonly sessionWritable: WritableStream<Uint8Array>;
-}): Promise<void> {
- const event = getPendingCoordinationBatch(input.sessionState)?.event;
- if (event === undefined) return;
- const resolutions: InputResolution[] = [
- ...input.responses.map((response) => ({
- kind: "question" as const,
- outcome: "answered" as const,
- requestId: response.requestId,
- response,
- })),
- ...input.dismissedRequestIds.map((requestId) => ({
- kind: "question" as const,
- outcome: "ignored" as const,
- requestId,
- })),
- ];
- if (resolutions.length === 0) return;
- const writer = input.sessionWritable.getWriter();
- try {
- await writer.write(
- encodeMessageStreamEvent(
- stampMessageStreamEvent(createInputResolvedEvent({ resolutions, ...event })),
- ),
- );
- } finally {
- writer.releaseLock();
- }
-}
-
-// Answers to a task that finished mid-flight rejoin the parent-local
-// remainder, where the model sees them as stale rather than silently
-// vanishing.
-function mergeStrandedResponses(
- parentPayloads: Map<number, DeliverPayload>,
- child: ChildBucket,
- taskId: string,
-): void {
- for (const [childPayloadIndex, payload] of child.payloads.entries()) {
- const sourcePayloadIndex = child.sourcePayloadIndexes[childPayloadIndex];
- if (sourcePayloadIndex === undefined) continue;
- const strandedResponses: InputResponse[] = (payload.inputResponses ?? []).map((response) => ({
- ...response,
- requestId: createTaskInputRequestId(taskId, response.requestId),
- }));
- if (strandedResponses.length === 0) continue;
- const forSelf = parentPayloads.get(sourcePayloadIndex);
- parentPayloads.set(sourcePayloadIndex, {
- ...forSelf,
- inputResponses: [...(forSelf?.inputResponses ?? []), ...strandedResponses],
- });
- }
-}
diff --git a/packages/eve/src/execution/publish-channel-event.ts b/packages/eve/src/execution/publish-channel-event.ts
deleted file mode 100644
index 05f9f4ffb..000000000
--- a/packages/eve/src/execution/publish-channel-event.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import {
- callAdapterEventHandler,
- type ChannelAdapter,
- type ChannelAdapterContext,
-} from "#channel/adapter.js";
-import type { ContextContainer } from "#context/container.js";
-import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";
-import { setChannelContext } from "#execution/channel-context.js";
-import {
- encodeMessageStreamEvent,
- stampMessageStreamEvent,
- type MessageStreamEvent,
- type UnstampedMessageStreamEvent,
-} from "#protocol/message.js";
-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-
-interface ChannelEventInput {
- readonly adapter: ChannelAdapter;
- readonly adapterCtx: ChannelAdapterContext;
- readonly ctx: ContextContainer;
- readonly deliveryIds?: readonly string[];
- readonly event: UnstampedMessageStreamEvent;
- readonly writer: WritableStreamDefaultWriter<Uint8Array>;
-}
-
-/**
- * Publishes an already-routed event, then runs its stream-event hooks on the
- * stamped event. Callers with subscribed hooks must hold an active context scope.
- */
-export async function publishChannelEvent(input: ChannelEventInput): Promise<MessageStreamEvent> {
- const stamped = await writeChannelEvent(input);
- await dispatchStreamEventHooks({
- // Only turn-step events can cancel the running turn; see turn-event-handler.ts.
- cancelTurn: undefined,
- ctx: input.ctx,
- registry: input.ctx.require(BundleKey).hookRegistry,
- event: stamped,
- });
- return stamped;
-}
-
-/**
- * Publishes without hooks. Only `createSessionEventSink` uses this: turn steps
- * run memory lifecycle before hooks, and subagent notifications release the
- * writer before hooks. Both dispatch hooks themselves after `sink.emit`.
- */
-export async function writeChannelEvent(input: ChannelEventInput): Promise<MessageStreamEvent> {
- const event = await callAdapterEventHandler(input.adapter, input.event, input.adapterCtx);
- setChannelContext(input.ctx, { ...input.adapter, state: { ...input.adapterCtx.state } });
- const stamped = stampMessageStreamEvent(event, input.deliveryIds);
- await input.writer.write(encodeMessageStreamEvent(stamped));
- return stamped;
-}
diff --git a/packages/eve/src/execution/publish-session-events.integration.test.ts b/packages/eve/src/execution/publish-session-events.integration.test.ts
new file mode 100644
index 000000000..a66625dd6
--- /dev/null
+++ b/packages/eve/src/execution/publish-session-events.integration.test.ts
@@ -0,0 +1,123 @@
+import { expect, it } from "vitest";
+
+import { replaceDurableSessionSnapshot } from "#execution/durable-session-store.js";
+import { emitWorkflowToolRunReportStep } from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";
+import { withdrawWorkflowToolRunQuestionStep } from "#execution/tools/workflow/withdraw-step.js";
+import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
+import type { HarnessSession } from "#harness/types.js";
+import { createTestRuntime } from "#internal/testing/app-harness.js";
+import { createTestSessionState } from "#internal/testing/session-state.js";
+import type { MessageStreamEvent } from "#protocol/message.js";
+import { defineHook } from "#public/definitions/hook.js";
+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+
+const serializedContext = {
+ "eve.auth": null,
+ "eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.channel": { kind: "http", state: {} },
+ "eve.continuationToken": "test-token",
+ "eve.sessionId": "test-session",
+};
+
+async function createPublishingRuntime() {
+ const hooked: { event: MessageStreamEvent; sessionId: string }[] = [];
+ const runtime = await createTestRuntime({
+ agent: { name: "publish-session-events" },
+ modules: [
+ {
+ logicalPath: "hooks/audit.ts",
+ loadNamespace: async () => ({
+ default: defineHook({
+ events: {
+ async "action.partial"(event, ctx) {
+ hooked.push({ event, sessionId: ctx.session.id });
+ },
+ async "input.resolved"(event, ctx) {
+ hooked.push({ event, sessionId: ctx.session.id });
+ },
+ },
+ }),
+ }),
+ },
+ ],
+ });
+ const streamed: MessageStreamEvent[] = [];
+ const sessionWritable = new WritableStream<Uint8Array>({
+ write(chunk) {
+ streamed.push(JSON.parse(new TextDecoder().decode(chunk)) as MessageStreamEvent);
+ },
+ });
+ return { hooked, runtime, sessionWritable, streamed };
+}
+
+it("publishes a session step's action.partial to the stream and its hooks", async () => {
+ const { hooked, runtime, sessionWritable, streamed } = await createPublishingRuntime();
+
+ await runtime.run(async () => {
+ await emitWorkflowToolRunReportStep({
+ from: {
+ callId: "call-1",
+ input: {},
+ runId: "run-1",
+ sequence: 1,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-1",
+ },
+ serializedContext,
+ sessionState: createTestSessionState(),
+ sessionWritable,
+ update: { progress: "halfway" },
+ });
+ });
+
+ expect(streamed).toEqual([
+ expect.objectContaining({
+ type: "action.partial",
+ data: expect.objectContaining({ turnId: "turn-1" }),
+ }),
+ ]);
+ expect(hooked).toEqual([{ event: streamed[0], sessionId: "test-session" }]);
+});
+
+it("relays a withdrawn workflow question's input.resolved to the stream and its hooks", async () => {
+ const { hooked, runtime, sessionWritable, streamed } = await createPublishingRuntime();
+ const base = createTestSessionState();
+ const asked = upsertProxyInputRequests({
+ entries: [
+ [
+ "ask-1",
+ {
+ workflowAsk: { control: "control", question: {}, runId: "run-1" },
+ childContinuationToken: "ask-1",
+ event: { sequence: 1, stepIndex: 0, turnId: "turn-1" },
+ kind: "question",
+ },
+ ],
+ ],
+ forChildContinuationToken: "ask-1",
+ session: base.snapshot.session as HarnessSession,
+ });
+
+ await runtime.run(async () => {
+ await withdrawWorkflowToolRunQuestionStep({
+ control: "control",
+ requestId: "ask-1",
+ runId: "run-1",
+ serializedContext,
+ sessionState: replaceDurableSessionSnapshot({ session: asked, state: base }),
+ sessionWritable,
+ });
+ });
+
+ expect(streamed).toEqual([
+ expect.objectContaining({
+ type: "input.resolved",
+ data: expect.objectContaining({
+ resolutions: [{ kind: "question", outcome: "cancelled", requestId: "ask-1" }],
+ turnId: "turn-1",
+ }),
+ }),
+ ]);
+ expect(hooked).toEqual([{ event: streamed[0], sessionId: "test-session" }]);
+});
diff --git a/packages/eve/src/execution/publish-session-events.ts b/packages/eve/src/execution/publish-session-events.ts
new file mode 100644
index 000000000..b11b21e6b
--- /dev/null
+++ b/packages/eve/src/execution/publish-session-events.ts
@@ -0,0 +1,327 @@
+import { buildAdapterContext } from "#channel/adapter-context.js";
+import { callAdapterEventHandler, type ChannelAdapterContext } from "#channel/adapter.js";
+import { type ContextContainer, contextStorage } from "#context/container.js";
+import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";
+import { ParentSessionKey, TurnDeliveryIdsKey } from "#context/keys.js";
+import { withContextScope } from "#context/run-step.js";
+import { deserializeContext, serializeContext } from "#context/serialize.js";
+import * as activityCohort from "#execution/activity-cohort.js";
+import { setChannelContext } from "#execution/channel-context.js";
+import {
+ createDurableSessionState,
+ readDurableSession,
+ type DurableSession,
+ type DurableSessionState,
+} from "#execution/durable-session-store.js";
+import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
+import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";
+import { observeSessionActivity } from "#execution/session-activity-projection.js";
+import { hydrateDurableSession } from "#execution/session.js";
+import { activeTurnId } from "#harness/active-turn-id.js";
+import { getHarnessEmissionState } from "#harness/emission.js";
+import type { HandleEventFn, HarnessSession } from "#harness/types.js";
+import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
+import { createLogger } from "#internal/logging.js";
+import {
+ encodeMessageStreamEvent,
+ stampMessageStreamEvent,
+ type MessageStreamEvent,
+ type UnstampedMessageStreamEvent,
+} from "#protocol/message.js";
+import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+
+const log = createLogger("execution.publish-session-events");
+
+/**
+ * Whose event a session publishes. Every event reaches the channel adapter, the
+ * session stream, and stream-event hooks. The session's own events also reach
+ * its instrumentation and activity and carry its turn's delivery ids.
+ *
+ * A relayed event belongs to an exchange this session carries for a child
+ * session or a workflow run: the question or sign-in it raised, the turn
+ * boundary that question causes here, and the `input.resolved` for the answer
+ * this session routes back. This session's instrumentation and activity never
+ * track that pending input, so no event of the exchange reaches them; the
+ * child records its side as its own.
+ */
+export type SessionEventOrigin = "own" | "relayed";
+
+/** The session a step publishes to: its stream and the state it starts from. */
+export interface SessionStepState {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ readonly sessionWritable: WritableStream<Uint8Array>;
+}
+
+/** The context and session state a publication leaves behind. */
+export interface PublishedSessionEvents {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}
+
+/**
+ * Publishes a session step's own events, such as a workflow tool's
+ * `action.partial`, exactly as a turn publishes its events. Call from a step
+ * and adopt the result: hooks run in the session's context and may change it.
+ */
+export async function publishSessionEvents(
+ target: SessionStepState,
+ events: readonly UnstampedMessageStreamEvent[],
+): Promise<PublishedSessionEvents> {
+ return await publishFromStep(target, "own", events);
+}
+
+/** Publishes events of an exchange this session relays; see {@link SessionEventOrigin}. */
+export async function relaySessionEvents(
+ target: SessionStepState,
+ events: readonly UnstampedMessageStreamEvent[],
+): Promise<PublishedSessionEvents> {
+ return await publishFromStep(target, "relayed", events);
+}
+
+async function publishFromStep(
+ target: SessionStepState,
+ origin: SessionEventOrigin,
+ events: readonly UnstampedMessageStreamEvent[],
+): Promise<PublishedSessionEvents> {
+ if (events.length === 0) {
+ return { serializedContext: target.serializedContext, sessionState: target.sessionState };
+ }
+ const ctx = await deserializeContext(target.serializedContext);
+ const { session } = await withSessionEventEmitter(
+ {
+ ctx,
+ durableSession: readDurableSession(target.sessionState),
+ origin,
+ sessionWritable: target.sessionWritable,
+ },
+ async (emit, scopedSession) => {
+ for (const event of events) await emit(event);
+ return { result: undefined, session: scopedSession };
+ },
+ );
+ return {
+ serializedContext: serializeContext(ctx),
+ sessionState: createDurableSessionState({
+ session: reconcileSessionContinuationToken(ctx, session),
+ }),
+ };
+}
+
+/**
+ * Runs `emitEvents` in the session's context scope with an emit that publishes
+ * each event with the given origin. `ctx` is updated in place; the returned
+ * session is the one `emitEvents` returns after the scope commits.
+ */
+export async function withSessionEventEmitter<T>(
+ input: {
+ readonly ctx: ContextContainer;
+ readonly durableSession: DurableSession;
+ readonly origin: SessionEventOrigin;
+ readonly sessionWritable: WritableStream<Uint8Array>;
+ },
+ emitEvents: (
+ emit: HandleEventFn,
+ session: HarnessSession,
+ ) => Promise<{ readonly result: T; readonly session: HarnessSession }>,
+): Promise<{ readonly result: T; readonly session: HarnessSession }> {
+ const { ctx } = input;
+ const bundle = ctx.require(BundleKey);
+ const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
+ const session = hydrateDurableSession({
+ compactionOverrides: { thresholdPercent: effectiveAgent.thresholdPercent },
+ durable: input.durableSession,
+ turnAgent: effectiveAgent.turnAgent,
+ });
+ const instrumentation =
+ input.origin === "own"
+ ? bindSessionInstrumentation({
+ agentName: effectiveAgent.turnAgent.id,
+ ctx,
+ rootSessionId: session.rootSessionId ?? session.sessionId,
+ sessionId: session.sessionId,
+ })
+ : undefined;
+
+ const sink = openSessionEventStream({
+ ctx,
+ origin: input.origin,
+ sessionId: session.sessionId,
+ sessionWritable: input.sessionWritable,
+ });
+ try {
+ return await withContextScope(ctx, session, async (enrichedSession) => {
+ const publish: HandleEventFn = async (event) => {
+ const stamped = await sink.emit(event);
+ // Only turn-step events can cancel the running turn; see turn-event-handler.ts.
+ await dispatchStreamEventHooks({
+ cancelTurn: undefined,
+ ctx,
+ registry: bundle.hookRegistry,
+ event: stamped,
+ });
+ };
+ const emit =
+ instrumentation?.createHandleEvent({
+ handleEvent: publish,
+ turnId: activeTurnId(getHarnessEmissionState(input.durableSession.state)),
+ }) ?? publish;
+ return await emitEvents(emit, enrichedSession);
+ });
+ } finally {
+ await instrumentation?.flush();
+ sink.release();
+ }
+}
+
+/** A session's stream held by one step. */
+export interface SessionEventSink {
+ readonly adapterCtx: ChannelAdapterContext;
+ /**
+ * Routes one event through the channel adapter, then stamps and writes it.
+ * Stream-event hooks and instrumentation belong to the caller.
+ */
+ emit(event: UnstampedMessageStreamEvent): Promise<MessageStreamEvent>;
+ /** Closes the session stream; only a terminal `done` step does this. */
+ close(): Promise<void>;
+ /** Releases the writer lock so the next step can acquire it. Safe after `close()`. */
+ release(): void;
+}
+
+/**
+ * The turn step's sink for its own events. A turn composes the rest of the
+ * publication itself: its tool loop binds instrumentation to each model call,
+ * and an event's hooks run after that event's memory lifecycle.
+ */
+export function createSessionEventSink(input: {
+ readonly ctx: ContextContainer;
+ readonly sessionId: string;
+ readonly sessionWritable: WritableStream<Uint8Array>;
+}): SessionEventSink {
+ return openSessionEventStream({ ...input, origin: "own" });
+}
+
+function openSessionEventStream(input: {
+ readonly ctx: ContextContainer;
+ readonly origin: SessionEventOrigin;
+ readonly sessionId: string;
+ readonly sessionWritable: WritableStream<Uint8Array>;
+}): SessionEventSink {
+ const { ctx, origin } = input;
+ const adapter = ctx.require(ChannelKey);
+ const adapterCtx = buildAdapterContext(adapter, ctx);
+ const writer = input.sessionWritable.getWriter();
+
+ let released = false;
+ const release = (): void => {
+ if (released) return;
+ released = true;
+ writer.releaseLock();
+ };
+ return {
+ adapterCtx,
+ async emit(event) {
+ if (origin === "own") activityCohort.updateActivityBlockers(ctx, event);
+ const routed = await callAdapterEventHandler(adapter, event, adapterCtx);
+ setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });
+ const stamped = stampMessageStreamEvent(
+ routed,
+ origin === "own" ? ctx.get(TurnDeliveryIdsKey) : undefined,
+ );
+ await writer.write(encodeMessageStreamEvent(stamped));
+ if (origin === "own") {
+ void observeSessionActivity({ ctx, event: stamped, sessionId: input.sessionId });
+ }
+ return stamped;
+ },
+ close: async () => {
+ await writer.close();
+ release();
+ },
+ release,
+ };
+}
+
+type TerminalSessionEvent = Extract<
+ UnstampedMessageStreamEvent,
+ { type: "session.completed" | "session.failed" }
+>;
+
+/**
+ * Publishes a terminal `session.completed` or `session.failed` from outside a
+ * turn as the session's own event, through its channel adapter and
+ * instrumentation. Stream-event hooks do not run: the ending session may not
+ * restore, and no turn scope remains for authored code. Never throws.
+ *
+ * When the context cannot be restored, the event is only stamped and written so
+ * the stream still ends: the one degraded write of a session event.
+ */
+export async function publishTerminalSessionEvent(input: {
+ readonly errorId?: string;
+ readonly event: TerminalSessionEvent;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionWritable: WritableStream<Uint8Array>;
+ /** The turn the event ends, for instrumentation. */
+ readonly turnId?: string;
+}): Promise<void> {
+ const sessionId = (input.serializedContext["eve.sessionId"] as string | undefined) ?? "";
+ const fields = { errorId: input.errorId, sessionId };
+ const { type } = input.event;
+
+ let ctx: ContextContainer;
+ let sink: SessionEventSink;
+ try {
+ ctx = await deserializeContext(input.serializedContext);
+ sink = createSessionEventSink({ ctx, sessionId, sessionWritable: input.sessionWritable });
+ } catch (error) {
+ log.error(`failed to restore context for terminal ${type} event`, { ...fields, error });
+ await writeUnroutedSessionEvent(input.sessionWritable, input.event).catch((writeError) =>
+ log.error(`failed to write terminal ${type} event`, { ...fields, error: writeError }),
+ );
+ return;
+ }
+
+ const publish: HandleEventFn = async (event) => {
+ await sink.emit(event);
+ };
+ let instrumentation: ReturnType<typeof bindSessionInstrumentation>;
+ try {
+ instrumentation = bindSessionInstrumentation({
+ agentName: ctx.require(BundleKey).turnAgent.id,
+ ctx,
+ rootSessionId: ctx.get(ParentSessionKey)?.rootSessionId ?? sessionId,
+ sessionId,
+ });
+ } catch (error) {
+ log.error(`failed to bind instrumentation for terminal ${type} event`, { ...fields, error });
+ }
+ const emit =
+ instrumentation?.createHandleEvent({ handleEvent: publish, turnId: input.turnId }) ?? publish;
+ try {
+ await contextStorage.run(ctx, () => emit(input.event));
+ } catch (error) {
+ log.error(`failed to publish terminal ${type} event`, { ...fields, error });
+ } finally {
+ sink.release();
+ try {
+ await instrumentation?.flush();
+ } catch (error) {
+ log.error(`failed to flush instrumentation after terminal ${type} event`, {
+ ...fields,
+ error,
+ });
+ }
+ }
+}
+
+async function writeUnroutedSessionEvent(
+ sessionWritable: WritableStream<Uint8Array>,
+ event: UnstampedMessageStreamEvent,
+): Promise<void> {
+ const writer = sessionWritable.getWriter();
+ try {
+ await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(event)));
+ } finally {
+ writer.releaseLock();
+ }
+}
diff --git a/packages/eve/src/execution/route-child-delivery.test.ts b/packages/eve/src/execution/route-child-delivery.test.ts
deleted file mode 100644
index 41c49e8b2..000000000
--- a/packages/eve/src/execution/route-child-delivery.test.ts
+++ /dev/null
@@ -1,590 +0,0 @@
-import { SessionInputQueue } from "#execution/session/input-queue.js";
-import type { DeliverHookPayload } from "#channel/types.js";
-import { registerWorkflowToolRun, recordWorkflowTaskView } from "#harness/workflow-tool-runs.js";
-import { createTestSessionState } from "#internal/testing/session-state.js";
-import { assert, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
-import {
- emitRecordedTaskInputRequestStep,
- runProxySubagentEventStep,
-} from "#subagents/event-proxy-step.js";
-import {
- recordTaskInputRequestStep,
- recordTerminalTaskViewsStep,
-} 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,
- settleTaskAgentInvocationStep,
-} from "#execution/tools/subagent/invoke-step.js";
-import { resumeHookStep } from "#execution/tools/workflow/resume-hook-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(),
- recordTerminalTaskViewsStep: 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(),
- settleTaskAgentInvocationStep: vi.fn(),
-}));
-vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({
- resumeHookStep: vi.fn(),
-}));
-
-const state = (hasProxyInputRequests: boolean): DurableSessionState =>
- createTestSessionState({
- continuationToken: "parent-token",
- emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "" },
- hasProxyInputRequests,
- sessionId: "parent-session",
- version: 1,
- });
-
-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",
- },
- sequence: 1,
- stepIndex: 2,
- taskId: "task-1",
- turnId: "turn_child",
-};
-describe("task HITL delivery routing", () => {
- beforeEach(() => vi.resetAllMocks());
-
- it("acknowledges late settlement after restoring only the recorded task outcome", async () => {
- const session = registerWorkflowToolRun(state(false).snapshot.session, {
- callId: "call-1",
- toolName: "worker",
- lifetime: "session",
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-inbox" },
- task: {
- taskId: "task-1",
- metadata: { kind: "subagent", name: "worker" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- });
- const cancelled = {
- taskId: "task-1",
- metadata: { kind: "subagent", name: "worker" },
- status: "cancelled" as const,
- };
- const sessionState = createTestSessionState({
- snapshot: {
- session: {
- ...session,
- state: JSON.parse(JSON.stringify(recordWorkflowTaskView(session.state, cancelled).state)),
- },
- },
- });
- vi.mocked(recordTerminalTaskViewsStep).mockResolvedValue({
- views: [],
- subagentCompletions: [],
- sessionState,
- serializedContext: {},
- });
- const context = {
- sessionState,
- serializedContext: {},
- sessionWritable: new WritableStream<Uint8Array>(),
- };
- const queue = new SessionInputQueue();
- async function routeQueued(delivery: DeliverHookPayload) {
- const admitted = queue.enqueueDelivery(delivery, sessionState.snapshot.session.state);
- assert(admitted);
- const routed = await routeDeliverToChildren({ ...context, delivery });
- assert(routed.kind === "continue");
- queue.replaceDelivery(admitted.sequence, routed.remainder);
- return queue.delivery(admitted.sequence);
- }
- const outcome = await routeQueued({
- kind: "deliver",
- taskDeliveryId: "task-1:ready:completed",
- payloads: [
- {
- message: "Late completion",
- task: {
- views: [
- {
- ...cancelled,
- status: "completed",
- lastOutput: { type: "result", data: "Late result" },
- },
- ],
- },
- },
- ],
- });
- expect(recordTerminalTaskViewsStep).toHaveBeenCalledOnce();
- expect(outcome).toBeUndefined();
- vi.mocked(settleTaskAgentInvocationStep).mockResolvedValue({
- settled: false,
- sessionState,
- serializedContext: {},
- });
- const settlement = await routeQueued({
- kind: "deliver",
- taskDeliveryId: "task-1:agent:run-1:settled",
- payloads: [
- {
- task: {
- agentRequests: [
- {
- taskId: "task-1",
- replyTo: "settlement-reply",
- request: {
- kind: "agent-settled",
- result: {
- callId: "child-call",
- kind: "subagent-result",
- origin: "child",
- subagentName: "worker",
- output: "",
- outcome: {
- kind: "parked",
- result: { kind: "cancelled" },
- usageDelta: {
- inputTokens: 0,
- outputTokens: 0,
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- },
- },
- },
- },
- },
- ],
- },
- },
- ],
- });
- expect(settlement).toBeUndefined();
- expect(resumeHookStep).toHaveBeenCalledWith(
- "settlement-reply",
- { kind: "agent-settled", callId: "child-call" },
- { ifPresent: true },
- );
- expect(
- queue.enqueueDelivery(
- {
- kind: "deliver",
- taskDeliveryId: "task-1:update:1",
- payloads: [{ message: "Still working" }],
- },
- sessionState.snapshot.session.state,
- ),
- ).toBeUndefined();
- const user = await routeQueued({
- kind: "deliver",
- payloads: [{ message: "New request" }],
- });
- expect(user).toMatchObject({
- payloads: [{ message: "New request" }],
- });
- });
-
- it("commits the task route before emitting and consumes the framework-only delivery", async () => {
- const recordedState = state(true);
- vi.mocked(recordTaskInputRequestStep).mockResolvedValue({
- accepted: true,
- request: taskRequest,
- sessionState: recordedState,
- });
- vi.mocked(emitRecordedTaskInputRequestStep).mockResolvedValue({
- serializedContext: { adapter: "updated" },
- sessionState: recordedState,
- });
- vi.mocked(routeProxiedDeliverStep).mockResolvedValue({
- kind: "continue",
- remainder: undefined,
- serializedContext: { adapter: "updated" },
- sessionState: recordedState,
- });
-
- const result = await routeDeliverToChildren({
- delivery: {
- kind: "deliver",
- payloads: [{ task: { inputRequests: [taskRequest] } }],
- },
- sessionWritable: new WritableStream<Uint8Array>(),
- serializedContext: {},
- sessionState: state(false),
- });
-
- 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({ request: taskRequest }),
- );
- expect(vi.mocked(recordTaskInputRequestStep).mock.invocationCallOrder[0]).toBeLessThan(
- vi.mocked(emitRecordedTaskInputRequestStep).mock.invocationCallOrder[0] ?? 0,
- );
- });
-
- it("ignores stale requests coalesced with their task's terminal outcome", async () => {
- vi.mocked(recordTerminalTaskViewsStep).mockResolvedValue({
- subagentCompletions: [],
- views: [],
- serializedContext: {},
- sessionState: state(false),
- });
- await routeDeliverToChildren({
- delivery: {
- kind: "deliver",
- payloads: [
- {
- task: {
- inputRequests: [taskRequest],
- agentRequests: [
- {
- replyTo: "agent-reply",
- taskId: "task-1",
- request: {
- kind: "agent-invoke",
- invocationId: "late-spawn",
- input: { target: "research", message: "Find it" },
- },
- },
- ],
- views: [
- {
- taskId: "task-1",
- metadata: { kind: "tool", name: "export" },
- status: "cancelled",
- },
- ],
- },
- },
- ],
- },
- sessionWritable: new WritableStream<Uint8Array>(),
- serializedContext: {},
- sessionState: state(false),
- });
- expect(recordTaskInputRequestStep).not.toHaveBeenCalled();
- expect(emitRecordedTaskInputRequestStep).not.toHaveBeenCalled();
- expect(dispatchTaskAgentInvocationStep).not.toHaveBeenCalled();
- expect(recordTerminalTaskViewsStep).toHaveBeenCalledOnce();
- });
-
- it("consumes a late outcome without notifying the model again", async () => {
- const cancelled = {
- taskId: "task-1",
- metadata: { kind: "tool", name: "export" },
- status: "cancelled" as const,
- };
- vi.mocked(recordTerminalTaskViewsStep).mockResolvedValue({
- subagentCompletions: [],
- views: [],
- serializedContext: {},
- sessionState: state(false),
- });
- const result = await routeDeliverToChildren({
- delivery: {
- kind: "deliver",
- taskDeliveryId: "task-1:ready:completed",
- payloads: [
- {
- message: "Success!",
- task: {
- views: [
- { ...cancelled, status: "completed", lastOutput: { type: "result", data: "late" } },
- ],
- },
- },
- ],
- },
- sessionWritable: new WritableStream<Uint8Array>(),
- serializedContext: {},
- sessionState: state(false),
- });
- expect(result).toMatchObject({
- kind: "continue",
- remainder: undefined,
- });
- });
-
- it("retains every task notification identity after consuming terminal views", async () => {
- const taskDeliveryIds = ["task-1:ready:completed", "task-2:ready:completed"];
- const views = ["task-1", "task-2"].map((taskId) => ({
- taskId,
- status: "completed" as const,
- metadata: { kind: "tool", name: "report" },
- lastOutput: { type: "result" as const, data: taskId },
- }));
- vi.mocked(recordTerminalTaskViewsStep).mockResolvedValue({
- subagentCompletions: [],
- views,
- serializedContext: {},
- sessionState: state(false),
- });
- const result = await routeDeliverToChildren({
- delivery: {
- kind: "deliver",
- taskDeliveryId: taskDeliveryIds[0],
- taskDeliveryIds,
- payloads: views.map((view) => ({ message: view.taskId, task: { views: [view] } })),
- },
- sessionWritable: new WritableStream<Uint8Array>(),
- serializedContext: {},
- sessionState: state(false),
- });
- expect(result).toMatchObject({
- kind: "continue",
- remainder: {
- taskDeliveryId: taskDeliveryIds[0],
- taskDeliveryIds,
- payloads: [
- { message: "Background task task-1 (report) is completed.\n\nResult:\ntask-1" },
- { message: "Background task task-2 (report) is completed.\n\nResult:\ntask-2" },
- ],
- },
- });
- expect(recordTerminalTaskViewsStep).toHaveBeenCalledWith(expect.objectContaining({ views }));
- });
-
- it("adopts instrumentation context returned with terminal task views", async () => {
- const recordedState = state(false);
- const view = {
- lastOutput: { data: "done", type: "result" as const },
- metadata: { kind: "tool", name: "publish" },
- status: "completed" as const,
- taskId: "task-1",
- };
- vi.mocked(recordTerminalTaskViewsStep).mockResolvedValue({
- subagentCompletions: [],
- views: [view],
- serializedContext: { trace: "settled" },
- sessionState: recordedState,
- });
-
- const result = await routeDeliverToChildren({
- delivery: {
- kind: "deliver",
- payloads: [{ task: { views: [view] } }],
- },
- sessionWritable: new WritableStream<Uint8Array>(),
- serializedContext: { trace: "open" },
- sessionState: state(false),
- });
-
- expect(recordTerminalTaskViewsStep).toHaveBeenCalledWith({
- serializedContext: { trace: "open" },
- sessionState: state(false),
- views: [view],
- });
- expect(result).toEqual({
- kind: "continue",
- remainder: undefined,
- serializedContext: { trace: "settled" },
- sessionState: recordedState,
- });
- });
-
- it("drops an unowned task envelope before it can reach the parent model", async () => {
- vi.mocked(recordTaskInputRequestStep).mockResolvedValue({
- accepted: false,
- sessionState: state(false),
- });
-
- const result = await routeDeliverToChildren({
- delivery: {
- kind: "deliver",
- payloads: [{ task: { inputRequests: [{ ...taskRequest, taskId: "foreign-task" }] } }],
- },
- sessionWritable: new WritableStream<Uint8Array>(),
- serializedContext: {},
- sessionState: state(false),
- });
-
- expect(result).toMatchObject({ kind: "continue", remainder: undefined });
- expect(emitRecordedTaskInputRequestStep).not.toHaveBeenCalled();
- 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" }],
- },
- },
- ],
- },
- sessionWritable: 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",
- },
- ],
- },
- },
- ],
- },
- sessionWritable: 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({
- kind: "continue",
- remainder: undefined,
- serializedContext: {},
- sessionState: routedState,
- });
- const caller = {
- callId: "call-parent",
- replyTo: { kind: "hook" as const, token: "parent-turn" },
- subagentName: "research",
- };
-
- await routeDeliverToChildren({
- delivery: {
- caller,
- deliveryMetadata: [
- { channelKind: "test", channelName: "main", deliveryId: "task", payloadIndex: 0 },
- { channelKind: "test", channelName: "main", deliveryId: "ordinary", payloadIndex: 1 },
- ],
- kind: "deliver",
- payloads: [{ task: { views: [] } }, { message: "parent message" }],
- requestId: "request-1",
- taskDeliveryId: "task-delivery-1",
- turnPolicy: "queue",
- },
- sessionWritable: new WritableStream<Uint8Array>(),
- serializedContext: {},
- sessionState: routedState,
- });
-
- expect(routeProxiedDeliverStep).toHaveBeenCalledWith(
- expect.objectContaining({
- delivery: {
- caller,
- deliveryMetadata: [expect.objectContaining({ deliveryId: "ordinary", payloadIndex: 0 })],
- kind: "deliver",
- payloads: [{ message: "parent message" }],
- requestId: "request-1",
- taskDeliveryId: "task-delivery-1",
- turnPolicy: "queue",
- },
- }),
- );
- });
-});
diff --git a/packages/eve/src/execution/route-child-delivery.ts b/packages/eve/src/execution/route-child-delivery.ts
index a33940a70..f2eed911c 100644
--- a/packages/eve/src/execution/route-child-delivery.ts
+++ b/packages/eve/src/execution/route-child-delivery.ts
@@ -1,28 +1,14 @@
-import { emitSubagentEventStep } from "#execution/tools/subagent/emit-event-step.js";
-import { formatTaskNotification, hasRecordedTaskOutcome } from "#tasks/notification.js";
-import type { TaskView } from "#tasks/types.js";
-import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";
-import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";
+import type { DeliverHookPayload } from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import {
routeProxiedDeliverStep,
type RoutedDeliverResult,
} from "#execution/proxied-deliver-step.js";
-import {
- emitRecordedTaskInputRequestStep,
- runProxySubagentEventStep,
-} from "#subagents/event-proxy-step.js";
-import {
- 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
- * responses down to the owning child. A descendant session-limit Stop is
- * returned as parent-owned turn control after the child consumes the answer.
+ * Routes any descendant-bound input responses down to the owning child. A
+ * descendant session-limit Stop is returned as parent-owned turn control after
+ * the child consumes the answer.
*
* Short-circuits via `hasProxyInputRequests` so the common no-active-descendant
* path skips a durable step boundary. Lives in its own non-step module so both
@@ -35,144 +21,14 @@ export async function routeDeliverToChildren(input: {
readonly sessionState: DurableSessionState;
readonly serializedContext: Record<string, unknown>;
}): Promise<RoutedDeliverResult> {
- const payload = coalesceDeliverPayloads(input.delivery.payloads);
- let serializedContext = input.serializedContext;
- let sessionState = input.sessionState;
- const recordedTaskViews = new Map<string, TaskView>();
- // Coalescing can put an old request beside its outcome. Do not start new work
- // or display new questions for a task settling in this same delivery.
- const settlingTaskIds = new Set((payload.task?.views ?? []).map((view) => view.taskId));
-
- for (const request of payload.task?.inputRequests ?? []) {
- if (settlingTaskIds.has(request.taskId)) continue;
- const recorded = await recordTaskInputRequestStep({
- request,
- sessionState,
- });
- sessionState = recorded.sessionState;
- if (!recorded.accepted) continue;
- const emitted = await emitRecordedTaskInputRequestStep({
- sessionWritable: input.sessionWritable,
- request: recorded.request,
- serializedContext,
- sessionState,
- });
- serializedContext = emitted.serializedContext;
- sessionState = emitted.sessionState;
- }
-
- for (const request of payload.task?.agentRequests ?? []) {
- if (request.request.kind === "agent-invoke" && settlingTaskIds.has(request.taskId)) continue;
- const applied = await applyTaskAgentRequest(
- { ...request, ownerId: request.taskId },
- {
- sessionWritable: input.sessionWritable,
- 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 ?? []) {
- if (
- delivery.hookPayload.event.type === "authorization.required" &&
- settlingTaskIds.has(delivery.taskId)
- )
- continue;
- const accepted = await acceptTaskAuthorizationEventStep({ delivery, sessionState });
- if (!accepted) continue;
- const emitted = await runProxySubagentEventStep({
- hookPayload: delivery.hookPayload,
- sessionWritable: input.sessionWritable,
- serializedContext,
- sessionState,
- });
- serializedContext = emitted.serializedContext;
- 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) {
- const recorded = await recordTerminalTaskViewsStep({
- serializedContext,
- sessionState,
- views: payload.task?.views ?? [],
- });
- serializedContext = recorded.serializedContext;
- sessionState = recorded.sessionState;
- for (const view of recorded.views) recordedTaskViews.set(view.taskId, view);
- // Publish after the durable write; replay retains these events, while duplicate deliveries return none.
- for (const event of recorded.subagentCompletions) {
- const emitted = await emitSubagentEventStep({
- event,
- sessionWritable: input.sessionWritable,
- serializedContext,
- sessionState,
- });
- serializedContext = emitted.serializedContext;
- sessionState = emitted.sessionState;
- }
- }
-
- // The delivery that records a task's first outcome still notifies the model. A later report
- // of that outcome only applies its envelopes above.
- const stateBeforeDelivery = input.sessionState.snapshot.session.state;
- if (payload.task !== undefined && hasRecordedTaskOutcome(input.delivery, stateBeforeDelivery)) {
- return { kind: "continue", remainder: undefined, serializedContext, sessionState };
- }
-
- const ordinaryPayloads: DeliverPayload[] = [];
- const ordinaryMetadata: NonNullable<DeliverHookPayload["deliveryMetadata"]>[number][] = [];
- for (const [sourcePayloadIndex, sourcePayload] of input.delivery.payloads.entries()) {
- const ordinaryPayload = { ...sourcePayload };
- delete ordinaryPayload.task;
- if (ordinaryPayload.message !== undefined && sourcePayload.task?.views !== undefined) {
- const notifications = sourcePayload.task.views.flatMap(({ taskId }) => {
- const view = recordedTaskViews.get(taskId);
- return view === undefined ? [] : [formatTaskNotification(view)];
- });
- if (notifications.length === 0) delete ordinaryPayload.message;
- else ordinaryPayload.message = notifications.join("\n\n");
- }
- if (Object.keys(ordinaryPayload).length === 0) continue;
- const payloadIndex = ordinaryPayloads.length;
- ordinaryPayloads.push(ordinaryPayload);
- for (const metadata of input.delivery.deliveryMetadata ?? []) {
- if (metadata.payloadIndex === sourcePayloadIndex) {
- ordinaryMetadata.push({ ...metadata, payloadIndex });
- }
- }
- }
- const delivery: DeliverHookPayload | undefined =
- ordinaryPayloads.length === 0
- ? undefined
- : {
- ...input.delivery,
- deliveryMetadata: ordinaryMetadata.length === 0 ? undefined : ordinaryMetadata,
- payloads: ordinaryPayloads,
- };
- if (delivery === undefined) {
- return { kind: "continue", remainder: undefined, serializedContext, sessionState };
- }
- if (!sessionState.hasProxyInputRequests) {
+ if (!input.sessionState.hasProxyInputRequests) {
return {
kind: "continue",
- remainder: delivery,
- serializedContext,
- sessionState,
+ remainder: input.delivery,
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
};
}
- return await routeProxiedDeliverStep({
- delivery,
- sessionWritable: input.sessionWritable,
- serializedContext,
- sessionState,
- });
+ return await routeProxiedDeliverStep(input);
}
diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.ts
index 62c38127a..aba52b063 100644
--- a/packages/eve/src/execution/runtime-context.test.ts
+++ b/packages/eve/src/execution/runtime-context.test.ts
@@ -13,7 +13,6 @@ import {
SessionIdKey,
SessionKey,
ScheduleIdKey,
- TaskDeliveryPolicyKey,
SessionTitleKey,
} from "#context/keys.js";
import { setChannelContext } from "#execution/channel-context.js";
@@ -156,22 +155,6 @@ function createMinimalBundle(): Parameters<typeof buildRunContext>[0]["bundle"]
}
describe("buildRunContext", () => {
- it.each([undefined, "auto", "cohort"] as const)(
- "resolves an ordinary send policy %s",
- (taskDeliveryPolicy) => {
- const ctx = buildRunContext({
- bundle: createMinimalBundle(),
- run: {
- auth: null,
- adapter: { kind: "http" },
- input: { message: "Report" },
- taskDeliveryPolicy,
- },
- });
- expect(ctx.get(TaskDeliveryPolicyKey)).toBe(taskDeliveryPolicy ?? "auto");
- },
- );
-
it.each([undefined, testAuth])(
"defers prewarm initiator identity unless explicitly forwarded (%s)",
(initiatorAuth) => {
@@ -239,10 +222,9 @@ describe("buildRunContext", () => {
expect(ctx.require(ScheduleIdKey)).toBe("dynamic-tasks");
});
- it("inherits schedule provenance but not its delivery policy in child sessions", () => {
+ it("inherits schedule provenance in child sessions", () => {
const scope = new ContextContainer();
scope.set(ScheduleIdKey, "automatic-reports");
- scope.set(TaskDeliveryPolicyKey, "auto");
const ctx = contextStorage.run(scope, () =>
buildRunContext({
bundle: createMinimalBundle(),
@@ -260,7 +242,6 @@ describe("buildRunContext", () => {
}),
);
expect(ctx.require(ScheduleIdKey)).toBe("automatic-reports");
- expect(ctx.get(TaskDeliveryPolicyKey)).toBe("cohort");
});
it("stores a title only for top-level sessions", () => {
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index a41c238f0..3e2389ffd 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -16,7 +16,6 @@ import {
ParentTraceContextKey,
ActivityObserverKey,
ScheduleIdKey,
- TaskDeliveryPolicyKey,
SessionCallbackKey,
SessionTitleKey,
} from "#context/keys.js";
@@ -88,12 +87,6 @@ export function buildRunContext(input: {
ctx.set(ScheduleIdKey, scheduleId);
}
- ctx.set(
- TaskDeliveryPolicyKey,
- run.taskDeliveryPolicy ??
- (run.parent !== undefined || scheduleId !== undefined ? "cohort" : "auto"),
- );
-
if (run.delivery !== undefined) {
ctx.set(ChannelDeliveryKey, run.delivery);
}
diff --git a/packages/eve/src/execution/scheduled-launch-delivery.test.ts b/packages/eve/src/execution/scheduled-launch-delivery.test.ts
deleted file mode 100644
index 5dab45e43..000000000
--- a/packages/eve/src/execution/scheduled-launch-delivery.test.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- createMessageAppendedEvent,
- createMessageCompletedEvent,
- createResultCompletedEvent,
-} from "#protocol/message.js";
-import { scheduledLaunchDeliveryEvent } from "#execution/scheduled-launch-delivery.js";
-
-describe("scheduledLaunchDeliveryEvent", () => {
- const completed = createMessageCompletedEvent({
- message: "answer",
- sequence: 0,
- stepIndex: 0,
- turnId: "turn_0",
- });
-
- it("hides an initiating scheduled reply but keeps its completion event", () => {
- const appended = createMessageAppendedEvent({
- messageDelta: "answer",
- sequence: 0,
- stepIndex: 0,
- turnId: "turn_0",
- });
-
- expect(
- scheduledLaunchDeliveryEvent(appended, {
- isFirstTurn: true,
- isScheduled: true,
- taskPhase: "initiating",
- }),
- ).toBeUndefined();
- expect(
- scheduledLaunchDeliveryEvent(completed, {
- isFirstTurn: true,
- isScheduled: true,
- taskPhase: "initiating",
- }),
- ).toEqual(expect.objectContaining({ data: expect.objectContaining({ message: null }) }));
- });
-
- it("keeps a direct scheduled answer", () => {
- expect(
- scheduledLaunchDeliveryEvent(completed, {
- isFirstTurn: true,
- isScheduled: true,
- taskPhase: "none",
- }),
- ).toBe(completed);
- });
-
- it("keeps an interactive acknowledgement in a schedule-created session", () => {
- expect(
- scheduledLaunchDeliveryEvent(completed, {
- isFirstTurn: false,
- isScheduled: true,
- taskPhase: "initiating",
- }),
- ).toBe(completed);
- });
-
- it("hides an initiating scheduled structured result", () => {
- const result = createResultCompletedEvent({
- result: { status: "pending" },
- sequence: 0,
- stepIndex: 0,
- turnId: "turn_0",
- });
- expect(
- scheduledLaunchDeliveryEvent(result, {
- isFirstTurn: true,
- isScheduled: true,
- taskPhase: "initiating",
- }),
- ).toBeUndefined();
- });
-});
diff --git a/packages/eve/src/execution/scheduled-launch-delivery.ts b/packages/eve/src/execution/scheduled-launch-delivery.ts
deleted file mode 100644
index a7c4306ba..000000000
--- a/packages/eve/src/execution/scheduled-launch-delivery.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-
-/** Hides a scheduled background launch while preserving its turn boundary. */
-export function scheduledLaunchDeliveryEvent(
- event: UnstampedMessageStreamEvent,
- input: {
- readonly isFirstTurn: boolean;
- readonly isScheduled: boolean;
- readonly taskPhase: "none" | "initiating" | "pending" | "settled" | undefined;
- },
-): UnstampedMessageStreamEvent | undefined {
- if (!input.isFirstTurn || !input.isScheduled || input.taskPhase !== "initiating") return event;
- if (event.type === "message.appended" || event.type === "result.completed") return undefined;
- if (event.type === "message.completed") {
- return { ...event, data: { ...event.data, message: null } };
- }
- return event;
-}
diff --git a/packages/eve/src/execution/session-activity-projection.test.ts b/packages/eve/src/execution/session-activity-projection.test.ts
index c3294cece..aeee59195 100644
--- a/packages/eve/src/execution/session-activity-projection.test.ts
+++ b/packages/eve/src/execution/session-activity-projection.test.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { ActivityObserverKey, TurnTaskDeliveryKey } from "#context/keys.js";
+import { ActivityObserverKey } from "#context/keys.js";
import { ContextContainer } from "#context/container.js";
import {
observeSessionActivity,
@@ -92,7 +92,7 @@ describe("projectSessionActivity", () => {
]);
});
- it("keeps an originating root open while HITL or background work is pending", () => {
+ it("keeps an originating root open while HITL or subagent work is pending", () => {
const event = turnEvent("turn.completed", "turn-1");
expect(
projectSessionActivity({
@@ -238,7 +238,7 @@ describe("projectSessionActivity", () => {
describe("observeSessionActivity", () => {
afterEach(() => vi.unstubAllGlobals());
- function context(taskDelivery?: "none" | "initiating" | "pending" | "settled"): ContextContainer {
+ function context(): ContextContainer {
const ctx = new ContextContainer();
ctx.set(ActivityObserverKey, {
sink: {
@@ -246,7 +246,6 @@ describe("observeSessionActivity", () => {
version: 1,
},
});
- if (taskDelivery !== undefined) ctx.set(TurnTaskDeliveryKey, taskDelivery);
return ctx;
}
@@ -269,34 +268,6 @@ describe("observeSessionActivity", () => {
expect(fetchMock).not.toHaveBeenCalled();
});
- it("does not project internal background-task delivery turns as new root work", async () => {
- const fetchMock = vi.fn();
- vi.stubGlobal("fetch", fetchMock);
-
- for (const taskDelivery of ["pending", "settled"] as const) {
- await observeSessionActivity({
- ctx: context(taskDelivery),
- event: turnEvent("turn.started", `turn-${taskDelivery}`),
- sessionId: "session-1",
- });
- }
-
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
- it("keeps projecting the turn that initiates background tasks", async () => {
- const fetchMock = vi.fn(async () => new Response(null, { status: 202 }));
- vi.stubGlobal("fetch", fetchMock);
-
- await observeSessionActivity({
- ctx: context("initiating"),
- event: turnEvent("turn.started"),
- sessionId: "session-1",
- });
-
- expect(fetchMock).toHaveBeenCalledOnce();
- });
-
it("submits projected activity and swallows transport failure", async () => {
const logs = captureLogRecords();
const fetchMock = vi.fn().mockRejectedValue(new Error("network down"));
diff --git a/packages/eve/src/execution/session-activity-projection.ts b/packages/eve/src/execution/session-activity-projection.ts
index 80c860eb9..5fe3c7414 100644
--- a/packages/eve/src/execution/session-activity-projection.ts
+++ b/packages/eve/src/execution/session-activity-projection.ts
@@ -3,7 +3,6 @@ import {
ActivityObserverKey,
ActivityPendingBlockersKey,
ActivityRootTurnIdKey,
- TurnTaskDeliveryKey,
} from "#context/keys.js";
import { projectActivityEvents } from "#execution/activity-events.js";
import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
@@ -19,22 +18,12 @@ export async function observeSessionActivity(input: {
}): Promise<void> {
const observer = input.ctx.get(ActivityObserverKey);
if (observer === undefined) return;
- const taskDelivery = input.ctx.get(TurnTaskDeliveryKey);
- if (
- observer.workIdentity === undefined &&
- input.ctx.get(ActivityRootTurnIdKey) === undefined &&
- (taskDelivery === "pending" || taskDelivery === "settled")
- )
- return;
await submitActivity({
events: projectSessionActivity({
event: input.event,
rootTurnId: input.ctx.get(ActivityRootTurnIdKey),
sessionId: input.sessionId,
- suppressRootSettlement:
- taskDelivery === "initiating" ||
- taskDelivery === "pending" ||
- (input.ctx.get(ActivityPendingBlockersKey)?.length ?? 0) > 0,
+ suppressRootSettlement: (input.ctx.get(ActivityPendingBlockersKey)?.length ?? 0) > 0,
workIdentity: observer.workIdentity,
}),
sink: observer.sink,
diff --git a/packages/eve/src/execution/session-activity.test.ts b/packages/eve/src/execution/session-activity.test.ts
index 794d53617..015596f6c 100644
--- a/packages/eve/src/execution/session-activity.test.ts
+++ b/packages/eve/src/execution/session-activity.test.ts
@@ -255,90 +255,6 @@ describe("activity protocol and reducer", () => {
expect(snapshot.blockers["child-input"]?.phase).toBe("cancelled");
});
- it("keeps background task subtrees active when their initiating turn settles", () => {
- const task = {
- callId: "call-task",
- id: "work:task",
- kind: "subagent" as const,
- parentId: work.id,
- rootSessionId: "session",
- rootTurnId: "turn",
- };
- const child = {
- id: "work:task-child",
- kind: "subagent" as const,
- parentId: task.id,
- rootSessionId: "session",
- rootTurnId: "turn",
- };
- const snapshot = reduce([
- { eventId: "root", kind: "work.started", startedAt: "1", work },
- {
- action: {
- id: `action:${work.id}:call-task`,
- kind: "tool",
- name: "researcher",
- parentWorkId: work.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "task-action",
- kind: "action.started",
- startedAt: "2",
- },
- { eventId: "task", kind: "work.started", startedAt: "2", work: task },
- { eventId: "task-child", kind: "work.started", startedAt: "3", work: child },
- {
- eventId: "root-settled",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "4",
- workId: work.id,
- },
- ]);
-
- expect(snapshot.work[work.id]?.phase).toBe("completed");
- expect(snapshot.work[task.id]?.phase).toBe("running");
- expect(snapshot.work[child.id]?.phase).toBe("running");
- });
-
- it("starts background task work even when its parent turn already settled", () => {
- const task = {
- callId: "call-task",
- id: "work:task",
- kind: "subagent" as const,
- parentId: work.id,
- rootSessionId: "session",
- rootTurnId: "turn",
- };
- const snapshot = reduce([
- { eventId: "root", kind: "work.started", startedAt: "1", work },
- {
- action: {
- id: `action:${work.id}:call-task`,
- kind: "tool",
- name: "researcher",
- parentWorkId: work.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "task-action",
- kind: "action.started",
- startedAt: "1",
- },
- {
- eventId: "root-settled",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "2",
- workId: work.id,
- },
- { eventId: "task", kind: "work.started", startedAt: "3", work: task },
- ]);
-
- expect(snapshot.work[task.id]?.phase).toBe("running");
- });
-
it("cancels running owned actions and blockers when work settles", () => {
const snapshot = reduce([
{ eventId: "work", kind: "work.started", startedAt: "1", work },
diff --git a/packages/eve/src/execution/session-activity.ts b/packages/eve/src/execution/session-activity.ts
index 288c8c094..2960b856a 100644
--- a/packages/eve/src/execution/session-activity.ts
+++ b/packages/eve/src/execution/session-activity.ts
@@ -85,11 +85,7 @@ function startWork(
const parent = event.work.parentId === undefined ? undefined : snapshot.work[event.work.parentId];
const phase =
pending?.outcome ??
- (!isBackgroundWorkBoundary(snapshot, event.work) &&
- parent !== undefined &&
- parent.phase !== "running"
- ? "cancelled"
- : "running");
+ (parent !== undefined && parent.phase !== "running" ? "cancelled" : "running");
const work: ActivityWorkStateV1 = {
...event.work,
label: event.work.label === undefined ? undefined : normalizePresentationText(event.work.label),
@@ -273,12 +269,7 @@ function settleWorkTree(
while (discovered) {
discovered = false;
for (const work of Object.values(snapshot.work)) {
- if (
- work.parentId === undefined ||
- !subtree.has(work.parentId) ||
- subtree.has(work.id) ||
- isBackgroundWorkBoundary(snapshot, work)
- )
+ if (work.parentId === undefined || !subtree.has(work.parentId) || subtree.has(work.id))
continue;
subtree.add(work.id);
discovered = true;
@@ -308,15 +299,6 @@ function settleWorkTree(
};
}
-function isBackgroundWorkBoundary(
- snapshot: ActivitySnapshotV1,
- work: ActivityWorkStateV1 | Extract<ActivityEventV1, { readonly kind: "work.started" }>["work"],
-): boolean {
- if (work.kind === "task") return true;
- if (work.callId === undefined || work.parentId === undefined) return false;
- return snapshot.actions[`action:${work.parentId}:${work.callId}`] !== undefined;
-}
-
function mapActivityStates<T>(
values: Readonly<Record<string, T>>,
transform: (value: T) => T,
diff --git a/packages/eve/src/execution/session-callback-request.test.ts b/packages/eve/src/execution/session-callback-request.test.ts
index d20a0a0c5..2bee0a6b7 100644
--- a/packages/eve/src/execution/session-callback-request.test.ts
+++ b/packages/eve/src/execution/session-callback-request.test.ts
@@ -32,7 +32,6 @@ describe("postSessionCallbackRequest", () => {
body: {
kind,
callId: "call-1",
- taskId: "task-1",
sessionId: "child-session",
subagentName: "research",
message: "private update",
@@ -49,7 +48,6 @@ describe("postSessionCallbackRequest", () => {
expect.objectContaining({
kind,
callId: "call-1",
- taskId: "task-1",
sessionId: "child-session",
subagentName: "research",
callbackOrigin: "https://agent.example.com",
@@ -78,7 +76,7 @@ describe("postSessionCallbackRequest", () => {
await expect(
postSessionCallbackRequest({
- body: { kind: "session.completed", taskId: "task-1" },
+ body: { kind: "session.completed" },
url: callbackUrl,
timeoutMs: 123,
}),
@@ -86,7 +84,7 @@ describe("postSessionCallbackRequest", () => {
expect(errorSpy).toHaveBeenCalledExactlyOnceWith(
"[eve:execution.session-callback] callback delivery failed",
- expect.objectContaining({ failure, timeoutMs: 123, taskId: "task-1" }),
+ expect.objectContaining({ failure, timeoutMs: 123 }),
);
expect(JSON.stringify(errorSpy.mock.calls)).not.toContain("opaque-token");
expect(JSON.stringify(errorSpy.mock.calls)).not.toContain("secret-credential");
diff --git a/packages/eve/src/execution/session-callback-request.ts b/packages/eve/src/execution/session-callback-request.ts
index cfe763244..cacf02512 100644
--- a/packages/eve/src/execution/session-callback-request.ts
+++ b/packages/eve/src/execution/session-callback-request.ts
@@ -68,7 +68,6 @@ function callbackLogFields(input: { readonly body: unknown; readonly url: string
for (const key of [
"kind",
"callId",
- "taskId",
"sessionId",
"childSessionId",
"subagentName",
diff --git a/packages/eve/src/execution/session-inbox/inbox.test.ts b/packages/eve/src/execution/session-inbox/inbox.test.ts
index 567300577..683fdcc20 100644
--- a/packages/eve/src/execution/session-inbox/inbox.test.ts
+++ b/packages/eve/src/execution/session-inbox/inbox.test.ts
@@ -101,7 +101,6 @@ describe("createSessionInbox", () => {
kind: "report",
from: {
callId: "call",
- execution: "blocking",
input: {},
runId: "tool-run",
sequence: 0,
diff --git a/packages/eve/src/execution/session-inbox/inbox.ts b/packages/eve/src/execution/session-inbox/inbox.ts
index 763557f2f..0d4761575 100644
--- a/packages/eve/src/execution/session-inbox/inbox.ts
+++ b/packages/eve/src/execution/session-inbox/inbox.ts
@@ -212,5 +212,11 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {
}
export function isWorkflowMessage(value: SessionInboxPayload): value is WorkflowToolRunMessage {
- return value.kind === "report" || value.kind === "request" || value.kind === "outcome";
+ return (
+ value.kind === "agent-started" ||
+ value.kind === "report" ||
+ value.kind === "request" ||
+ value.kind === "withdraw" ||
+ value.kind === "outcome"
+ );
}
diff --git a/packages/eve/src/execution/session-inbox/protocol.test.ts b/packages/eve/src/execution/session-inbox/protocol.test.ts
index a07b3263e..aa8e8b6db 100644
--- a/packages/eve/src/execution/session-inbox/protocol.test.ts
+++ b/packages/eve/src/execution/session-inbox/protocol.test.ts
@@ -10,7 +10,6 @@ describe("session inbox payloads", () => {
expect(
decodeSessionInboxPayload({
delivery: { deliveryId: "delivery-1" },
- taskDeliveryPolicy: "cohort",
kind: "send",
payload: { message: "hello" },
}),
@@ -21,9 +20,8 @@ describe("session inbox payloads", () => {
kind: "deliver",
payloads: [{ message: "hello" }],
requestId: undefined,
- taskDeliveryId: undefined,
+ title: undefined,
turnPolicy: undefined,
- taskDeliveryPolicy: "cohort",
});
});
diff --git a/packages/eve/src/execution/session-inbox/protocol.ts b/packages/eve/src/execution/session-inbox/protocol.ts
index 551807adc..548214c91 100644
--- a/packages/eve/src/execution/session-inbox/protocol.ts
+++ b/packages/eve/src/execution/session-inbox/protocol.ts
@@ -23,13 +23,6 @@ export function decodeSessionInboxPayload(value: unknown): DecodedSessionInbox {
throw new SessionInboxPayloadError("Session inbox payload must be an object with a kind.");
}
const payload = value as Record<string, unknown>;
- if (
- payload.taskDeliveryPolicy !== undefined &&
- payload.taskDeliveryPolicy !== "auto" &&
- payload.taskDeliveryPolicy !== "cohort"
- ) {
- throw new SessionInboxPayloadError('Task delivery policy must be "auto" or "cohort".');
- }
switch (payload.kind) {
case "send": {
if (payload.payload === null || typeof payload.payload !== "object") {
@@ -45,9 +38,7 @@ export function decodeSessionInboxPayload(value: unknown): DecodedSessionInbox {
kind: "deliver",
payloads: [command.payload],
requestId: command.requestId,
- taskDeliveryId: command.taskDeliveryId,
turnPolicy: command.turnPolicy,
- taskDeliveryPolicy: command.taskDeliveryPolicy,
};
}
case "deliver": {
diff --git a/packages/eve/src/execution/session-workflow-tool-run.test.ts b/packages/eve/src/execution/session-workflow-tool-run.test.ts
index 3b776ba78..52a508b06 100644
--- a/packages/eve/src/execution/session-workflow-tool-run.test.ts
+++ b/packages/eve/src/execution/session-workflow-tool-run.test.ts
@@ -25,7 +25,6 @@ it("settles the agent request once and treats workflow completion as an ordinary
const session = registerWorkflowToolRun(sessionState.snapshot.session, {
callId: "call",
toolName: "agent",
- lifetime: "turn",
origin: { turnId: "turn", stepIndex: 0 },
address: { runId: "run", hookToken: "control" },
});
diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.ts
index 43c68ecb8..e60697918 100644
--- a/packages/eve/src/execution/session-workflow-tool-run.ts
+++ b/packages/eve/src/execution/session-workflow-tool-run.ts
@@ -1,10 +1,17 @@
import { deliverWorkflowAuthorization } from "#execution/tools/workflow/owner.js";
-import { emitWorkflowToolRunReportStep } from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";
+import {
+ emitAgentStartedStep,
+ emitWorkflowToolRunReportStep,
+} from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";
import type {
+ WorkflowToolAskRequest,
WorkflowToolRunMessage,
WorkflowToolRunOutcomeMessage,
+ WorkflowToolRunRef,
WorkflowToolRunRequestMessage,
+ WorkflowToolRunWithdrawMessage,
} from "#execution/tools/workflow/messages.js";
+import { withdrawWorkflowToolRunQuestionStep } from "#execution/tools/workflow/withdraw-step.js";
import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
import type { SessionStateCursor } from "#execution/session/state-cursor.js";
import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requests.js";
@@ -20,7 +27,7 @@ import {
isInboxToolResultFromRecordedWorkflowToolRun,
} from "#harness/workflow-tool-runs.js";
import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";
-import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
+import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
interface HandlerInput<T> {
@@ -39,12 +46,22 @@ export async function handleWorkflowToolRunMessage(
case "request":
await handleWorkflowToolRunRequest({ ...input, message });
return undefined;
+ case "withdraw":
+ await handleWorkflowToolRunWithdraw({ ...input, message });
+ return undefined;
case "report":
- await emitWorkflowToolRunReportStep({
- from: message.from,
- sessionWritable: input.cursor.sessionWritable,
- update: message.update,
- });
+ await input.cursor.apply(
+ await emitWorkflowToolRunReportStep({
+ ...input.cursor.stepState(),
+ from: message.from,
+ update: message.update,
+ }),
+ );
+ return undefined;
+ case "agent-started":
+ await input.cursor.apply(
+ await emitAgentStartedStep({ ...input.cursor.stepState(), message }),
+ );
return undefined;
}
}
@@ -140,9 +157,7 @@ async function handleWorkflowToolRunRequest(
await cursor.apply(
await runProxySubagentEventStep({
hookPayload: request.event,
- sessionWritable: cursor.sessionWritable,
- serializedContext: cursor.serializedContext,
- sessionState: cursor.sessionState,
+ ...cursor.stepState(),
}),
);
});
@@ -150,35 +165,52 @@ async function handleWorkflowToolRunRequest(
}
await cursor.apply(
await runProxySubagentEventStep({
- ...(message.requestCoordinates === undefined
- ? { answerHook: createAnswerHookRoute(message) }
- : {}),
+ ...(message.request.kind === "ask" && {
+ workflowAsk: createWorkflowAskRoute(message.from, message.request),
+ }),
hookPayload: workflowToolRunRequestToInputRequestPayload(message),
- sessionWritable: cursor.sessionWritable,
- serializedContext: cursor.serializedContext,
- sessionState: cursor.sessionState,
+ ...cursor.stepState(),
+ }),
+ );
+}
+
+/**
+ * A run asks to withdraw a `ctx.ask()` question. The session decides: it
+ * withdraws the question unless it already accepted an answer or stopped
+ * offering it, and tells the run either way.
+ */
+async function handleWorkflowToolRunWithdraw(
+ input: HandlerInput<WorkflowToolRunWithdrawMessage>,
+): Promise<void> {
+ const { cursor, message } = input;
+ await cursor.apply(
+ await withdrawWorkflowToolRunQuestionStep({
+ ...cursor.stepState(),
+ control: message.control,
+ requestId: message.replyTo,
+ runId: message.from.runId,
}),
);
}
-function createAnswerHookRoute(message: WorkflowToolRunRequestMessage): AnswerHookRoute {
- if (message.request.kind !== "ask") return { runId: message.from.runId };
- const { allowFreeform, dismissible, options } = message.request.request;
+function createWorkflowAskRoute(
+ from: WorkflowToolRunRef,
+ ask: WorkflowToolAskRequest,
+): WorkflowAskRoute {
+ const { allowFreeform, options } = ask.request;
return {
+ control: ask.control,
question: {
...(allowFreeform !== undefined && { allowFreeform }),
- ...(dismissible !== undefined && { dismissible }),
...(options !== undefined && { options: [...options] }),
},
- runId: message.from.runId,
+ runId: from.runId,
};
}
function requestContext(input: HandlerInput<unknown>) {
return {
callbackBaseUrl: resolveWorkflowCallbackBaseUrl(input.callbackMetadataUrl),
- sessionWritable: input.cursor.sessionWritable,
- serializedContext: input.cursor.serializedContext,
- sessionState: input.cursor.sessionState,
+ ...input.cursor.stepState(),
};
}
diff --git a/packages/eve/src/execution/session.ts b/packages/eve/src/execution/session.ts
index 516488db9..ce7995db2 100644
--- a/packages/eve/src/execution/session.ts
+++ b/packages/eve/src/execution/session.ts
@@ -74,7 +74,6 @@ interface CreateSessionInput {
readonly turnAgent: RuntimeTurnAgent;
readonly limits?: AuthoredSessionLimits;
readonly outputSchema?: HarnessSession["outputSchema"];
- readonly taskId?: string;
}
/** Creates a fresh {@link HarnessSession} from the current `turnAgent`. */
@@ -102,9 +101,6 @@ export function createSession(input: CreateSessionInput): HarnessSession {
if (input.outputSchema !== undefined) {
session.outputSchema = input.outputSchema;
}
- if (input.taskId !== undefined) {
- session.taskId = input.taskId;
- }
return session;
}
@@ -196,7 +192,6 @@ export function projectToDurableSession(session: HarnessSession): DurableSession
sandboxState?: HarnessSession["sandboxState"];
sessionId: string;
state?: HarnessSession["state"];
- taskId?: string;
} = {
agent: { system: session.agent.system },
continuationToken: session.continuationToken,
@@ -228,9 +223,6 @@ export function projectToDurableSession(session: HarnessSession): DurableSession
if (session.state !== undefined) {
durable.state = session.state;
}
- if (session.taskId !== undefined) {
- durable.taskId = session.taskId;
- }
return durable;
}
@@ -282,9 +274,6 @@ export function hydrateDurableSession(input: {
if (durable.state !== undefined) {
session.state = durable.state;
}
- if (durable.taskId !== undefined) {
- session.taskId = durable.taskId;
- }
return session;
}
diff --git a/packages/eve/src/execution/session/admission.ts b/packages/eve/src/execution/session/admission.ts
index ceafade55..a993bcdff 100644
--- a/packages/eve/src/execution/session/admission.ts
+++ b/packages/eve/src/execution/session/admission.ts
@@ -1,7 +1,6 @@
import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
-import type { RuntimeActionResultHookPayload, SessionCommand } from "#channel/types.js";
-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
+import type { RuntimeActionResultHookPayload } from "#channel/types.js";
import type { DeliveryAdmission, SessionInputQueue } from "#execution/session/input-queue.js";
import { isWorkflowMessage, type SessionInboxPayload } from "#execution/session-inbox/inbox.js";
import {
@@ -14,12 +13,10 @@ import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.
import { findRunningAgentHandle } from "#subagents/handles/query.js";
import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";
-type SessionCancellation = Extract<SessionCommand, { readonly kind: "cancel" }>;
-
/** One canonical admission result, after wire decoding but before turn policy. */
type SessionAdmission =
| { readonly admission: DeliveryAdmission; readonly kind: "delivery" }
- | { readonly command: SessionCancellation; readonly kind: "cancel" }
+ | { readonly kind: "cancel" }
| { readonly kind: "consumed" }
| { readonly kind: "runtime-action-result"; readonly payload: RuntimeActionResultHookPayload }
| { readonly kind: "workflow"; readonly message: WorkflowToolRunMessage };
@@ -54,9 +51,7 @@ export async function admitSessionInboxPayload(
await input.cursor.apply(
await runProxySubagentEventStep({
hookPayload: value,
- sessionWritable: input.cursor.sessionWritable,
- serializedContext: input.cursor.serializedContext,
- sessionState: input.cursor.sessionState,
+ ...input.cursor.stepState(),
}),
);
}
@@ -73,13 +68,8 @@ export async function admitSessionInboxPayload(
}
switch (command.kind) {
- case "deliver": {
- const admission = input.queue.enqueueDelivery(
- command,
- input.cursor.sessionState.snapshot.session.state,
- );
- return admission === undefined ? { kind: "consumed" } : { admission, kind: "delivery" };
- }
+ case "deliver":
+ return { admission: input.queue.enqueueDelivery(command), kind: "delivery" };
case "clear":
case "compact":
input.queue.enqueueControl(command.kind);
@@ -92,27 +82,8 @@ export async function admitSessionInboxPayload(
return { kind: "consumed" };
case "reset":
input.queue.enqueueControl("reset");
- return { command: { kind: "cancel" }, kind: "cancel" };
+ return { kind: "cancel" };
case "cancel":
- return { command, kind: "cancel" };
- }
-}
-
-/** Applies accepted cancellation effects after the active-turn guard passes. */
-export async function applySessionCancellation(
- command: SessionCancellation,
- input: {
- readonly cursor: SessionStateCursor;
- readonly queue: SessionInputQueue;
- },
-): Promise<void> {
- if (command.tasks === true) {
- const cancelled = await cancelAllIndexedSessionTasksStep({
- serializedContext: input.cursor.serializedContext,
- sessionState: input.cursor.sessionState,
- });
- await input.cursor.apply(cancelled);
- input.queue.discardStaleNotifications(input.cursor.sessionState.snapshot.session.state);
+ return { kind: "cancel" };
}
- if (command.taskId !== undefined) input.queue.cancelTask(command.taskId);
}
diff --git a/packages/eve/src/execution/session/entry-handoff.integration.test.ts b/packages/eve/src/execution/session/entry-handoff.integration.test.ts
index 5677e164d..ed253d0b1 100644
--- a/packages/eve/src/execution/session/entry-handoff.integration.test.ts
+++ b/packages/eve/src/execution/session/entry-handoff.integration.test.ts
@@ -61,22 +61,13 @@ describe("workflowEntry integration", () => {
state: {
...session.state,
"eve.workflowTool": {
- version: 3,
+ version: 4,
runs: [
{
- callId: "task",
+ callId: "call",
toolName: "research",
- lifetime: "session" as const,
origin: { turnId: "turn", stepIndex: 0 },
address: { runId: "run", hookToken: 42 },
- task: {
- taskId: "task",
- metadata: { kind: "tool", name: "research" },
- outcome: {
- status: "cancelled",
- },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
},
],
},
diff --git a/packages/eve/src/execution/session/entry-input.ts b/packages/eve/src/execution/session/entry-input.ts
index b8c665b5a..09ff5d4a2 100644
--- a/packages/eve/src/execution/session/entry-input.ts
+++ b/packages/eve/src/execution/session/entry-input.ts
@@ -21,7 +21,6 @@ export interface InitialWorkflowEntryInput {
readonly retention?: AgentWorkflowRetentionDefinition;
readonly sessionTimeoutMs?: number | false;
readonly serializedContext: Record<string, unknown>;
- readonly taskId?: string;
}
/** A successor owner started by a previous owner during a deployment handoff. */
diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.ts
index 93dc1750e..8c1303d91 100644
--- a/packages/eve/src/execution/session/entry.ts
+++ b/packages/eve/src/execution/session/entry.ts
@@ -101,7 +101,6 @@ async function bootInitialOwner(
outputSchema: input.input.outputSchema,
rootSessionId: readRootSessionId(serializedContext),
sessionId,
- taskId: input.taskId,
}),
inbox.claimSessionHook(sessionCommandHookToken(sessionId)),
continuationToken === "" ? Promise.resolve() : inbox.claimSessionHook(continuationToken),
diff --git a/packages/eve/src/execution/session/event-sink.ts b/packages/eve/src/execution/session/event-sink.ts
deleted file mode 100644
index 5b0ce9037..000000000
--- a/packages/eve/src/execution/session/event-sink.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { buildAdapterContext } from "#channel/adapter-context.js";
-import type { ChannelAdapter } from "#channel/adapter.js";
-import type { ContextContainer } from "#context/container.js";
-import { ScheduleIdKey, TurnDeliveryIdsKey, TurnTaskDeliveryKey } from "#context/keys.js";
-import * as activityCohort from "#execution/activity-cohort.js";
-import { writeChannelEvent } from "#execution/publish-channel-event.js";
-import { observeSessionActivity } from "#execution/session-activity-projection.js";
-import { scheduledLaunchDeliveryEvent } from "#execution/scheduled-launch-delivery.js";
-import { forwardTaskEventToSessionCallback } from "#execution/task-event-callback.js";
-import {
- type MessageStreamEvent,
- stampMessageStreamEvent,
- type UnstampedMessageStreamEvent,
-} from "#protocol/message.js";
-
-interface SessionEventSinkInput {
- readonly adapter: ChannelAdapter;
- readonly ctx: ContextContainer;
- readonly isFirstTurn: boolean;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly sessionId: string;
-}
-
-export interface PublishedSessionEvent {
- readonly event: MessageStreamEvent;
- readonly suppressed: boolean;
-}
-
-export interface SessionEventSink {
- readonly adapterCtx: ReturnType<typeof buildAdapterContext>;
- emit(event: UnstampedMessageStreamEvent): Promise<PublishedSessionEvent>;
- /** Closes the parent stream; only a terminal `done` step does this. */
- close(): Promise<void>;
- /** Releases the writer lock so the next step can acquire it. Safe after `close()`. */
- release(): void;
-}
-
-/** Publishes events without executing hooks or preparing model context. */
-export function createSessionEventSink(input: SessionEventSinkInput): SessionEventSink {
- const { adapter, ctx } = input;
- const adapterCtx = buildAdapterContext(adapter, ctx);
- const writer = input.sessionWritable.getWriter();
-
- const deliver = async (event: UnstampedMessageStreamEvent): Promise<PublishedSessionEvent> => {
- const forwardedToTaskParent = await forwardTaskEventToSessionCallback(ctx, event);
- if (forwardedToTaskParent) {
- return {
- event: stampMessageStreamEvent(event, ctx.get(TurnDeliveryIdsKey)),
- suppressed: false,
- };
- }
- const deliverableEvent = scheduledLaunchDeliveryEvent(event, {
- isFirstTurn: input.isFirstTurn,
- isScheduled: ctx.get(ScheduleIdKey) !== undefined,
- taskPhase: ctx.get(TurnTaskDeliveryKey),
- });
- if (deliverableEvent === undefined) {
- return {
- event: stampMessageStreamEvent(event, ctx.get(TurnDeliveryIdsKey)),
- suppressed: true,
- };
- }
- const stamped = await writeChannelEvent({
- adapter,
- adapterCtx,
- ctx,
- writer,
- event: deliverableEvent,
- deliveryIds: ctx.get(TurnDeliveryIdsKey),
- });
- return { event: stamped, suppressed: false };
- };
-
- let released = false;
- const release = (): void => {
- if (released) return;
- released = true;
- writer.releaseLock();
- };
- return {
- adapterCtx,
- async emit(event) {
- activityCohort.updateActivityBlockers(ctx, event);
- const emitted = await deliver(event);
- void observeSessionActivity({ ctx, event: emitted.event, sessionId: input.sessionId });
- return emitted;
- },
- close: async () => {
- await writer.close();
- release();
- },
- release,
- };
-}
diff --git a/packages/eve/src/execution/session/finalization.test.ts b/packages/eve/src/execution/session/finalization.test.ts
index 5e90ab319..c9987844d 100644
--- a/packages/eve/src/execution/session/finalization.test.ts
+++ b/packages/eve/src/execution/session/finalization.test.ts
@@ -1,9 +1,8 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { finalizeSession } from "#execution/session/finalization.js";
-import { resolveSessionStepResult } from "#execution/session/turn-step-result.js";
+import { createDurableSessionState } from "#execution/durable-session-store.js";
import { setTurnUsageState, takeSessionUsageDelta } from "#harness/turn-tag-state.js";
import type { HarnessSession } from "#harness/types.js";
-import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
import { notifyTurnCallerStep } from "#subagents/parent-notification.js";
vi.mock("#execution/terminate-child-sessions-step.js", () => ({
@@ -31,7 +30,7 @@ function withUsage(session: HarnessSession, inputTokens: number): HarnessSession
return setTurnUsageState(session, { ...totals, session: totals, turnId: "current" });
}
-function sessionAwaitingCallerNotification() {
+function sessionWithUnreportedUsage() {
const session: HarnessSession = {
agent: { modelReference: { id: "unused" }, system: "", tools: [] },
compaction: { recentWindowSize: 10, threshold: 100_000 },
@@ -40,30 +39,7 @@ function sessionAwaitingCallerNotification() {
sessionId: "detector",
};
const previouslySettled = takeSessionUsageDelta(withUsage(session, 100)).session;
- const pending = registerWorkflowToolRun(withUsage(previouslySettled, 250), {
- callId: "worker",
- toolName: "worker",
- lifetime: "session",
- origin: { turnId: "current", stepIndex: 0 },
- address: { runId: "worker", hookToken: "worker" },
- task: {
- taskId: "worker",
- metadata: { kind: "subagent", name: "worker" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- });
- const parked = resolveSessionStepResult(
- {
- next: null,
- session: pending,
- settledTurn: { output: "Verification is running." },
- },
- {},
- {},
- "current",
- );
- expect(parked).toMatchObject({ action: "park", settled: { notifyCaller: false } });
- return parked.sessionState;
+ return createDurableSessionState({ session: withUsage(previouslySettled, 250) });
}
beforeEach(() => vi.clearAllMocks());
@@ -82,7 +58,7 @@ describe("session finalization with an unsettled caller", () => {
};
const result = await finalizeSession(outcome, {
caller,
- cursor: { serializedContext: {}, sessionState: sessionAwaitingCallerNotification() },
+ cursor: { serializedContext: {}, sessionState: sessionWithUnreportedUsage() },
sessionWritable: new WritableStream(),
});
expect(result).toMatchObject({
@@ -109,7 +85,7 @@ describe("session finalization with an unsettled caller", () => {
{ kind: "expired" },
{
caller: undefined,
- cursor: { serializedContext: {}, sessionState: sessionAwaitingCallerNotification() },
+ cursor: { serializedContext: {}, sessionState: sessionWithUnreportedUsage() },
sessionWritable: new WritableStream(),
},
);
diff --git a/packages/eve/src/execution/session/handoff-steps.test.ts b/packages/eve/src/execution/session/handoff-steps.test.ts
index 49fdbb084..e75d21220 100644
--- a/packages/eve/src/execution/session/handoff-steps.test.ts
+++ b/packages/eve/src/execution/session/handoff-steps.test.ts
@@ -33,27 +33,18 @@ describe("validateSessionCheckpointStep", () => {
expect(readDurableSessionMock).toHaveBeenCalledWith(checkpoint.sessionState);
});
- it("rejects an incompatible settled task with the current checkpoint version", async () => {
+ it("rejects an incompatible workflow tool run with the current checkpoint version", async () => {
deserializeContextMock.mockResolvedValue({ require: vi.fn() });
readDurableSessionMock.mockReturnValue({
state: {
"eve.workflowTool": {
- version: 3,
+ version: 4,
runs: [
{
- callId: "task",
+ callId: "call",
toolName: "research",
- lifetime: "session" as const,
origin: { turnId: "turn", stepIndex: 0 },
address: { runId: "run", hookToken: 42 },
- task: {
- taskId: "task",
- metadata: { kind: "tool", name: "research" },
- outcome: {
- status: "cancelled",
- },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
},
],
},
diff --git a/packages/eve/src/execution/session/handoff-steps.ts b/packages/eve/src/execution/session/handoff-steps.ts
index 1868f8a99..f575e209e 100644
--- a/packages/eve/src/execution/session/handoff-steps.ts
+++ b/packages/eve/src/execution/session/handoff-steps.ts
@@ -1,4 +1,4 @@
-import { getBackgroundTasks, getBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";
+import { getBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";
import { deserializeContext } from "#context/serialize.js";
import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
import {
@@ -16,9 +16,8 @@ import { getAgentHandleStore } from "#subagents/handles/store.js";
/** Parses retained work with this deployment's code before deciding whether it can move. */
export function isSessionStateIdleForHandoff(sessionState: DurableSessionState): boolean {
const { state } = readDurableSession(sessionState);
- // Decoding every background task, terminal ones included, rejects corrupt outcomes before any
- // busy-work shortcut.
- const backgroundTasks = getBackgroundTasks(state).query();
+ // Decoding the run registry rejects corrupt state before any busy-work shortcut.
+ const workflowToolRuns = getBlockingWorkflowToolRuns(state);
const handles = getAgentHandleStore(state);
// These registries are deleted when work settles. Their ordinary readers
@@ -44,8 +43,7 @@ export function isSessionStateIdleForHandoff(sessionState: DurableSessionState):
handles.handles.every(
(handle) => handle.phase === "parked" || handle.phase === "available",
)) &&
- getBlockingWorkflowToolRuns(state).length === 0 &&
- backgroundTasks.every((task) => task.status !== "working")
+ workflowToolRuns.length === 0
);
}
diff --git a/packages/eve/src/execution/session/input-queue.test.ts b/packages/eve/src/execution/session/input-queue.test.ts
deleted file mode 100644
index a8d965d0a..000000000
--- a/packages/eve/src/execution/session/input-queue.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { describe, expect, it } from "vitest";
-import type { DeliverHookPayload } from "#channel/types.js";
-import { SessionInputQueue } from "#execution/session/input-queue.js";
-import { recordWorkflowTaskView, registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-import { createTestSessionState } from "#internal/testing/session-state.js";
-import type { SessionStateMap } from "#harness/types.js";
-
-function tasks() {
- let session = createTestSessionState({}).snapshot.session;
- for (const taskId of ["first", "second"]) {
- session = registerWorkflowToolRun(session, {
- callId: taskId,
- toolName: "worker",
- lifetime: "session",
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: `${taskId}-run`, hookToken: `${taskId}-inbox` },
- task: {
- taskId,
- cohortId: "siblings",
- metadata: { kind: "subagent", name: "worker" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- });
- }
- return session.state;
-}
-
-function settle(
- state: SessionStateMap | undefined,
- taskId: string,
- status: "completed" | "cancelled",
-) {
- return recordWorkflowTaskView(state, {
- taskId,
- metadata: { kind: "subagent", name: "worker" },
- ...(status === "cancelled"
- ? { status }
- : { status, lastOutput: { type: "result", data: "done" } }),
- }).state;
-}
-
-const first: DeliverHookPayload = {
- kind: "deliver",
- taskDeliveryId: "first:ready:completed",
- payloads: [{ message: "First finished" }],
-};
-const second: DeliverHookPayload = {
- kind: "deliver",
- taskDeliveryId: "second:ready:completed",
- payloads: [{ message: "Second finished" }],
-};
-const user: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "New request" }] };
-
-describe.each(["auto", "cohort"] as const)(
- "task notifications with %s delivery",
- (taskDeliveryPolicy) => {
- it("discards an already queued completion during cancellation without changing its outcome", () => {
- const queue = new SessionInputQueue();
- let state = settle(tasks(), "first", "completed");
- queue.enqueueDelivery(first);
- state = settle(state, "second", "cancelled");
- queue.discardStaleNotifications(state);
- expect(queue.takeNext(state, { taskDeliveryPolicy })).toBeUndefined();
- expect(queue.pendingCount).toBe(0);
- });
-
- it("uses restored outcomes to reject late model notifications while retaining settlement", () => {
- const state = JSON.parse(JSON.stringify(settle(tasks(), "first", "cancelled")));
- const queue = new SessionInputQueue();
- expect(queue.enqueueDelivery(first, state)).toBeUndefined();
- expect(
- queue.enqueueDelivery({ ...first, taskDeliveryId: "first:update:1" }, state),
- ).toBeUndefined();
- const settlement: DeliverHookPayload = {
- ...first,
- payloads: [
- {
- task: {
- views: [
- {
- taskId: "first",
- status: "cancelled",
- metadata: { kind: "subagent", name: "worker" },
- },
- ],
- },
- },
- ],
- };
- const admitted = queue.enqueueDelivery(settlement, state);
- expect(admitted).toBeDefined();
- queue.discardStaleNotifications(state);
- expect(queue.taskDeliveries()).toMatchObject([admitted]);
- queue.replaceDelivery(admitted!.sequence, undefined);
- queue.enqueueDelivery(user, state);
- expect(queue.takeNext(state, { taskDeliveryPolicy })).toMatchObject({ delivery: user });
- });
-
- it("preserves updates and results for a worker whose cancellation failed", () => {
- const queue = new SessionInputQueue();
- const state = settle(tasks(), "first", "cancelled");
- const update = { ...second, taskDeliveryId: "second:update:1" };
- queue.enqueueDelivery(update, state);
- queue.discardStaleNotifications(state);
- expect(queue.takeNext(state, { taskDeliveryPolicy })).toMatchObject({ delivery: update });
- queue.enqueueDelivery(second, state);
- expect(
- queue.takeNext(settle(state, "second", "completed"), { taskDeliveryPolicy }),
- ).toMatchObject({ delivery: second });
- });
-
- it("releases a completed sibling without waiting for the cancelled task's duplicate receipt", () => {
- const queue = new SessionInputQueue();
- const state = settle(tasks(), "first", "cancelled");
- queue.enqueueDelivery(second, state);
- expect(
- queue.takeNext(settle(state, "second", "completed"), { taskDeliveryPolicy }),
- ).toMatchObject({ delivery: second });
- });
- },
-);
diff --git a/packages/eve/src/execution/session/input-queue.ts b/packages/eve/src/execution/session/input-queue.ts
index c1a848a76..fd88a1e0f 100644
--- a/packages/eve/src/execution/session/input-queue.ts
+++ b/packages/eve/src/execution/session/input-queue.ts
@@ -1,7 +1,4 @@
-import type { SessionStateMap } from "#harness/types.js";
-import { getBackgroundTasks, type BackgroundTasks } from "#harness/workflow-tool-runs.js";
-import { hasRecordedTaskOutcome, taskIdOfDelivery } from "#tasks/notification.js";
-import type { TaskDeliveryPolicy, DeliverHookPayload, DeliverPayload } from "#channel/types.js";
+import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";
import { coalesceDeliveries } from "#harness/messages.js";
import { jsonValuesEqual } from "#shared/json.js";
@@ -50,51 +47,24 @@ export type SessionInputSelection =
| { readonly kind: "authorization-resume"; readonly payloads: readonly DeliverPayload[] };
/**
- * Ordered, admitted session input, plus the idempotency and cancellation
- * facts for task deliveries this owner has seen. Entries are private; callers
- * receive typed admission and selection values. Everything here is rebuilt
- * deterministically on replay. Indexed task outcomes live in session state.
+ * Ordered, admitted session input. Entries are private; callers receive typed
+ * admission and selection values. Everything here is rebuilt deterministically
+ * on replay.
*/
export class SessionInputQueue {
private readonly entries: QueuedSessionInput[] = [];
- private readonly cancelledTaskIds = new Set<string>();
- private readonly seenTaskDeliveryIds = new Set<string>();
private nextSequence = 0;
get pendingCount(): number {
return this.entries.length;
}
- /** Drops notifications the model must not see; lifecycle envelopes are always admitted. */
- enqueueDelivery(
- delivery: DeliverHookPayload,
- state?: SessionStateMap,
- ): DeliveryAdmission | undefined {
- if (isStaleNotification(delivery, state)) return undefined;
- const deliveryId = taskDeliveryId(delivery);
- if (deliveryId !== undefined) {
- const terminalId = terminalTaskId(delivery);
- // Competing outcomes for one task must not produce separate cohort reports.
- const deduplicationId = terminalId === undefined ? deliveryId : `${terminalId}:ready`;
- if (this.seenTaskDeliveryIds.has(deduplicationId) || this.isCancelledNotification(delivery)) {
- return undefined;
- }
- this.seenTaskDeliveryIds.add(deduplicationId);
- }
+ enqueueDelivery(delivery: DeliverHookPayload): DeliveryAdmission {
const admission = { delivery, sequence: this.nextSequence++ };
this.entries.push({ ...admission, kind: "delivery" });
return admission;
}
- /** A caller's own task id counts as seen so its echo is not admitted twice. */
- rememberTask(taskId: string): void {
- this.seenTaskDeliveryIds.add(taskId);
- }
-
- isTaskCancelled(taskId: string): boolean {
- return this.cancelledTaskIds.has(taskId);
- }
-
enqueueControl(control: SessionControl): void {
this.entries.push({ control, kind: "control", sequence: this.nextSequence++ });
}
@@ -127,37 +97,18 @@ export class SessionInputQueue {
return entry?.delivery;
}
- /** Task lifecycle effects must be applied even while their cohort report is held. */
- taskDeliveries(): readonly DeliveryAdmission[] {
- return this.entries.filter(
- (entry): entry is QueuedDelivery =>
- entry.kind === "delivery" && !isNotificationOnly(entry.delivery),
- );
- }
-
replaceDelivery(sequence: number, delivery: DeliverHookPayload | undefined): void {
const index = this.entries.findIndex(
(entry) => entry.kind === "delivery" && entry.sequence === sequence,
);
if (index < 0) return;
- if (delivery === undefined || this.isCancelledNotification(delivery)) {
+ if (delivery === undefined) {
this.entries.splice(index, 1);
return;
}
this.entries[index] = { delivery, kind: "delivery", sequence };
}
- /** Revokes model wakeups for a cancelled task; its lifecycle envelopes still reach routing. */
- cancelTask(taskId: string): void {
- this.cancelledTaskIds.add(taskId);
- this.discardDeliveries((delivery) => this.isCancelledNotification(delivery));
- }
-
- /** After cancellation records outcomes, queued notifications for those tasks are stale. */
- discardStaleNotifications(state: SessionStateMap | undefined): void {
- this.discardDeliveries((delivery) => isStaleNotification(delivery, state));
- }
-
takeSteering(
admitted: ReadonlySet<number>,
callerCallId: string | undefined,
@@ -178,21 +129,17 @@ export class SessionInputQueue {
};
}
- takeNext(
- state: SessionStateMap | undefined,
- options?: {
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
- /**
- * Attempt ids of the open authorization challenge. Callbacks for other
- * attempts are stale and dropped; once every expected attempt has
- * reported, the collected payloads resume the challenge ahead of
- * ordinary input.
- */
- readonly expectedAttemptIds?: ReadonlySet<string>;
- /** Sequence of a delivery admitted while nothing else was pending. */
- readonly freshSequence?: number;
- },
- ): SessionInputSelection | undefined {
+ takeNext(options?: {
+ /**
+ * Attempt ids of the open authorization challenge. Callbacks for other
+ * attempts are stale and dropped; once every expected attempt has
+ * reported, the collected payloads resume the challenge ahead of
+ * ordinary input.
+ */
+ readonly expectedAttemptIds?: ReadonlySet<string>;
+ /** Sequence of a delivery admitted while nothing else was pending. */
+ readonly freshSequence?: number;
+ }): SessionInputSelection | undefined {
const expected = options?.expectedAttemptIds ?? new Set<string>();
this.retain((entry) => entry.kind !== "authorization" || expected.has(entry.attemptId));
if (expected.size > 0) {
@@ -209,104 +156,19 @@ export class SessionInputQueue {
};
}
}
- const tasks = getBackgroundTasks(state);
- // A cohort reports once every task is ready; a cancelled task's notification may never arrive.
- const pendingCohorts = new Set(
- tasks
- .query({ state: "working" })
- .filter(
- ({ taskId }) =>
- !this.seenTaskDeliveryIds.has(`${taskId}:ready`) && !this.cancelledTaskIds.has(taskId),
- )
- .map((task) => task.cohortId),
- );
- const index = this.nextActionableIndex(
- tasks,
- pendingCohorts,
- options?.taskDeliveryPolicy ?? "cohort",
- );
+ const index = this.entries.findIndex((entry) => entry.kind !== "authorization");
if (index < 0) return undefined;
- return this.takeSelectionAt(index, tasks, options?.freshSequence);
+ return this.takeSelectionAt(index, options?.freshSequence);
}
- private nextActionableIndex(
- tasks: BackgroundTasks,
- pendingCohorts: ReadonlySet<string>,
- taskDeliveryPolicy: TaskDeliveryPolicy,
- ): number {
- return this.entries.findIndex((entry) => {
- if (entry.kind === "control") return true;
- if (entry.kind === "authorization") return false;
- if (this.isCancelledDelivery(entry.delivery)) return false;
- const cohort = terminalCohort(entry.delivery, tasks);
- return taskDeliveryPolicy === "auto" || cohort === undefined || !pendingCohorts.has(cohort);
- });
- }
-
- private takeSelectionAt(
- index: number,
- tasks: BackgroundTasks,
- freshSequence: number | undefined,
- ): SessionInputSelection {
- const selected = this.entries[index]!;
- if (selected.kind !== "delivery") {
- this.entries.splice(index, 1);
- if (selected.kind === "control") return { control: selected.control, kind: "control" };
- return { kind: "authorization-resume", payloads: [selected.payload] };
- }
- const readyCohort = terminalCohort(selected.delivery, tasks);
- if (readyCohort !== undefined) {
- const lastSibling = this.entries.findLastIndex(
- (entry) =>
- entry.kind === "delivery" &&
- !this.isCancelledDelivery(entry.delivery) &&
- terminalCohort(entry.delivery, tasks) === readyCohort,
- );
- const boundary = this.entries.findIndex(
- (entry, position) =>
- position > index &&
- position < lastSibling &&
- (entry.kind !== "delivery" ||
- (!this.isCancelledDelivery(entry.delivery) &&
- terminalCohort(entry.delivery, tasks) === undefined)),
- );
- if (boundary >= 0) return this.takeSelectionAt(boundary, tasks, freshSequence);
- }
-
+ private takeSelectionAt(index: number, freshSequence: number | undefined): SessionInputSelection {
const first = this.entries.splice(index, 1)[0]!;
- if (first.kind !== "delivery") throw new Error("Selected a non-delivery entry as a turn.");
- const turnEntries = [first];
- const cohort = terminalCohort(first.delivery, tasks);
- if (cohort !== undefined) {
- const siblings = this.entries.filter(
- (entry): entry is QueuedDelivery =>
- entry.kind === "delivery" &&
- !this.isCancelledDelivery(entry.delivery) &&
- terminalCohort(entry.delivery, tasks) === cohort,
- );
- turnEntries.push(...siblings);
- this.retain((entry) => entry.kind !== "delivery" || !siblings.includes(entry));
- } else {
- const authenticated =
- first.delivery.auth != null && first.delivery.auth.principalType !== "anonymous";
- let caller = first.delivery.caller;
- while (this.entries.length > index) {
- const next = this.entries[index];
- if (
- next?.kind !== "delivery" ||
- first.delivery.taskDeliveryId !== undefined ||
- next.delivery.taskDeliveryId !== undefined ||
- !authenticated ||
- !jsonValuesEqual(first.delivery.auth, next.delivery.auth) ||
- (caller !== undefined && next.delivery.caller !== undefined)
- ) {
- break;
- }
- turnEntries.push(this.entries.splice(index, 1)[0] as QueuedDelivery);
- caller ??= next.delivery.caller;
- }
+ if (first.kind === "control") return { control: first.control, kind: "control" };
+ if (first.kind === "authorization") {
+ return { kind: "authorization-resume", payloads: [first.payload] };
}
+ const turnEntries = [first, ...this.takeFollowingDeliveriesFrom(first, index)];
const sequences = turnEntries.map(({ sequence }) => sequence);
const combined = combine(turnEntries);
return {
@@ -315,25 +177,32 @@ export class SessionInputQueue {
sequences.length === 1 &&
sequences[0] === freshSequence &&
combined.caller === undefined &&
- taskDeliveryId(combined) === undefined &&
this.entries.length === 0,
kind: "turn",
sequences,
};
}
- private isCancelledDelivery(delivery: DeliverHookPayload): boolean {
- const deliveryId = taskDeliveryId(delivery);
- return deliveryId !== undefined && this.cancelledTaskIds.has(taskIdOfDelivery(deliveryId));
- }
-
- /** A cancelled task's notification never reaches the model. */
- private isCancelledNotification(delivery: DeliverHookPayload): boolean {
- return isNotificationOnly(delivery) && this.isCancelledDelivery(delivery);
- }
-
- private discardDeliveries(predicate: (delivery: DeliverHookPayload) => boolean): void {
- this.retain((entry) => entry.kind !== "delivery" || !predicate(entry.delivery));
+ /** One authenticated principal's consecutive deliveries share a turn, with at most one caller. */
+ private takeFollowingDeliveriesFrom(first: QueuedDelivery, index: number): QueuedDelivery[] {
+ const authenticated =
+ first.delivery.auth != null && first.delivery.auth.principalType !== "anonymous";
+ const following: QueuedDelivery[] = [];
+ let caller = first.delivery.caller;
+ while (this.entries.length > index) {
+ const next = this.entries[index];
+ if (
+ next?.kind !== "delivery" ||
+ !authenticated ||
+ !jsonValuesEqual(first.delivery.auth, next.delivery.auth) ||
+ (caller !== undefined && next.delivery.caller !== undefined)
+ ) {
+ break;
+ }
+ following.push(this.entries.splice(index, 1)[0] as QueuedDelivery);
+ caller ??= next.delivery.caller;
+ }
+ return following;
}
private retain(predicate: (entry: QueuedSessionInput) => boolean): void {
@@ -342,65 +211,35 @@ export class SessionInputQueue {
}
}
-/** Carries only model-facing text, without `payload.task` envelopes that routing must apply. */
-function isNotificationOnly(delivery: DeliverHookPayload): boolean {
- return delivery.payloads.every((payload) => payload.task === undefined);
-}
-
-/** A notification for a task whose outcome the parent already recorded and reported. */
-function isStaleNotification(
+export function isSteeringDelivery(
delivery: DeliverHookPayload,
- state: SessionStateMap | undefined,
+ callerCallId: string | undefined,
): boolean {
- return isNotificationOnly(delivery) && hasRecordedTaskOutcome(delivery, state);
+ return (
+ (delivery.turnPolicy ?? "steer") === "steer" &&
+ (delivery.caller === undefined || delivery.caller.callId === callerCallId)
+ );
}
-export function isSteeringDelivery(
+/** A steering delivery with a message for the model, not only answers to requests. */
+export function isSteeringMessage(
delivery: DeliverHookPayload,
callerCallId: string | undefined,
): boolean {
return (
- delivery.taskDeliveryId === undefined &&
- (delivery.turnPolicy ?? "steer") === "steer" &&
- (delivery.caller === undefined || delivery.caller.callId === callerCallId)
+ isSteeringDelivery(delivery, callerCallId) &&
+ delivery.payloads.some(
+ (payload) => payload.message !== undefined && payload.inputResponses === undefined,
+ )
);
}
function combine(entries: readonly DeliveryAdmission[]): DeliverHookPayload {
if (entries.length === 1) return entries[0]!.delivery;
- const deliveries = entries.map(({ delivery }) => delivery);
- const taskDeliveryIds = deliveries.flatMap(
- (delivery) =>
- delivery.taskDeliveryIds ??
- (delivery.taskDeliveryId === undefined ? [] : [delivery.taskDeliveryId]),
- );
- return {
- ...coalesceDeliveries(deliveries),
- taskDeliveryIds: taskDeliveryIds.length > 0 ? taskDeliveryIds : undefined,
- };
+ return coalesceDeliveries(entries.map(({ delivery }) => delivery));
}
function authorizationAttemptId(payload: DeliverPayload): string | undefined {
const callback = payload["authorizationCallback"] as { readonly attemptId?: unknown } | undefined;
return typeof callback?.attemptId === "string" ? callback.attemptId : undefined;
}
-
-function taskDeliveryId(delivery: DeliverHookPayload): string | undefined {
- return delivery.taskDeliveryId ?? delivery.caller?.taskId;
-}
-
-function terminalCohort(delivery: DeliverHookPayload, tasks: BackgroundTasks): string | undefined {
- const taskId = terminalTaskId(delivery);
- return taskId === undefined ? undefined : tasks.get(taskId)?.cohortId;
-}
-
-function terminalTaskId(delivery: DeliverHookPayload): string | undefined {
- if (delivery.caller !== undefined) return undefined;
- for (const status of ["completed", "failed", "cancelled"]) {
- const suffix = `:ready:${status}`;
- if (delivery.taskDeliveryId?.endsWith(suffix)) {
- return delivery.taskDeliveryId.slice(0, -suffix.length);
- }
- }
- return undefined;
-}
diff --git a/packages/eve/src/execution/session/next-input.test.ts b/packages/eve/src/execution/session/next-input.test.ts
index 2489d1c5c..56364ea33 100644
--- a/packages/eve/src/execution/session/next-input.test.ts
+++ b/packages/eve/src/execution/session/next-input.test.ts
@@ -1,7 +1,5 @@
-import { applySessionCancellation } from "#execution/session/admission.js";
-import { recordWorkflowTaskView } from "#harness/workflow-tool-runs.js";
import { createTestSessionState } from "#internal/testing/session-state.js";
-import { assert, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DeliverHookPayload, SessionAuthContext } from "#channel/types.js";
import { nextTurnDelivery } from "#execution/session/next-input.js";
@@ -9,7 +7,6 @@ import { SessionInputQueue } from "#execution/session/input-queue.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import type { SessionInbox, SessionInboxPayload } from "#execution/session-inbox/inbox.js";
import { SessionStateCursor } from "#execution/session/state-cursor.js";
-import type { TaskView } from "#tasks/types.js";
vi.mock("#compiled/@workflow/core/index.js", () => ({
getWorkflowMetadata: () => ({ workflowRunId: "owner-1" }),
@@ -17,18 +14,9 @@ vi.mock("#compiled/@workflow/core/index.js", () => ({
vi.mock("../route-child-delivery.js", () => ({
routeDeliverToChildren: vi.fn(),
}));
-vi.mock("../cancel-indexed-session-tasks-step.js", () => ({
- cancelAllIndexedSessionTasksStep: vi.fn(),
-}));
-
-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
beforeEach(() => {
vi.mocked(routeDeliverToChildren).mockReset();
- vi.mocked(cancelAllIndexedSessionTasksStep).mockReset();
- vi.mocked(cancelAllIndexedSessionTasksStep).mockImplementation(async ({ sessionState }) => ({
- sessionState,
- }));
});
interface ScriptedRead {
@@ -82,9 +70,9 @@ function authorizationRead(): ScriptedRead {
return { result: { done: false, value: authorizationCallbackPayload } };
}
-function cancelRead(command: Record<string, unknown> = {}): ScriptedRead {
+function cancelRead(): ScriptedRead {
return {
- result: { done: false, value: { kind: "cancel", ...command } },
+ result: { done: false, value: { kind: "cancel" } },
};
}
@@ -153,7 +141,7 @@ describe("nextTurnDelivery", () => {
kind: "turn",
delivery: {
auth,
- payloads: [...report(first).payloads, ...report(second).payloads],
+ payloads: [...first.payloads, ...second.payloads],
deliveryMetadata: [
first.deliveryMetadata![0],
{ ...second.deliveryMetadata![0], payloadIndex: 1 },
@@ -260,63 +248,6 @@ describe("nextTurnDelivery", () => {
expect(next.payloads).toEqual(authorizationCallbackPayload.payloads);
});
- it("cancels indexed tasks and keeps waiting for ordinary parked activity", async () => {
- const inbox = createMockInbox([cancelRead({ tasks: true }), authorizationRead()]);
- const input = waitInput(inbox);
-
- const next = await nextTurnDelivery(input);
-
- expect(next.kind).toBe("authorization-resume");
- expect(cancelAllIndexedSessionTasksStep).toHaveBeenCalledWith({
- serializedContext: input.cursor.serializedContext,
- sessionState: input.cursor.sessionState,
- });
- });
-
- it("discards a held completion when session cancellation records the remaining task", async () => {
- const input = batchingInput(2);
- const session = input.cursor.sessionState.snapshot.session;
- const completed = recordWorkflowTaskView(session.state, {
- taskId: "task_0",
- metadata: { kind: "subagent", name: "worker" },
- status: "completed",
- lastOutput: { type: "result", data: "done" },
- }).state;
- await input.cursor.apply({
- sessionState: {
- ...input.cursor.sessionState,
- snapshot: { session: { ...session, state: completed } },
- },
- });
- input.queue.enqueueDelivery(report(completion("task_0")));
- vi.mocked(cancelAllIndexedSessionTasksStep).mockImplementation(async ({ sessionState }) => ({
- sessionState: {
- ...sessionState,
- snapshot: {
- session: {
- ...sessionState.snapshot.session,
- state: recordWorkflowTaskView(sessionState.snapshot.session.state, {
- taskId: "task_1",
- metadata: { kind: "subagent", name: "worker" },
- status: "cancelled",
- }).state,
- },
- },
- },
- }));
-
- await applySessionCancellation({ kind: "cancel", tasks: true }, input);
-
- expect(input.queue.pendingCount).toBe(0);
- expect(input.queue.isTaskCancelled("task_0")).toBe(false);
- expect(input.queue.isTaskCancelled("task_1")).toBe(false);
- input.inbox = createMockInbox([messageRead("New request")]);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: { payloads: [{ message: "New request" }] },
- });
- });
-
it("resumes authorization after a consumed no-op cancel", async () => {
// A cancel with no active turn is consumed without producing a parent
// turn; the wait continues and the callback must still resume the challenge.
@@ -416,560 +347,3 @@ function batchingInputFor(bufferedDeliveries: DeliverHookPayload[]) {
);
return { ...input, queue: queueOf(...bufferedDeliveries) };
}
-
-describe("nextTurnDelivery routing", () => {
- it("keeps waiting instead of starting a parent turn for a fully routed task response", async () => {
- const sessionState = createTestSessionState({
- continuationToken: "token",
- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "turn" },
- hasProxyInputRequests: true,
- sessionId: "session",
- version: 1,
- });
- const routedSessionState = { ...sessionState, hasProxyInputRequests: false };
- vi.mocked(routeDeliverToChildren)
- .mockResolvedValueOnce({
- kind: "continue",
- remainder: undefined,
- serializedContext: {},
- sessionState,
- })
- .mockResolvedValueOnce({
- kind: "continue",
- remainder: { kind: "deliver", payloads: [{ message: "ordinary" }] },
- serializedContext: {},
- sessionState: routedSessionState,
- });
- const commands = [
- { kind: "send" as const, payload: { inputResponses: [{ requestId: "task-request" }] } },
- { kind: "send" as const, payload: { message: "ordinary" } },
- ];
- const inbox: SessionInbox = {
- claimedTokens: [],
- claimSessionHook: vi.fn(),
- claimSessionHooks: vi.fn(),
- drain: vi.fn(() => commands.splice(0)),
- hasPending: vi.fn(() => commands.length > 0),
- next: vi.fn(async () => commands.shift()),
- onDelivery: vi.fn(() => () => {}),
- onInterrupt: vi.fn(() => () => {}),
- restore: vi.fn(),
- };
-
- const cursor = createCursor(inbox, sessionState);
- const result = await nextTurnDelivery({
- inbox,
- cursor,
- queue: new SessionInputQueue(),
- });
-
- expect(result).toMatchObject({
- delivery: { payloads: [{ message: "ordinary" }] },
- kind: "turn",
- });
- expect(routeDeliverToChildren).toHaveBeenCalledTimes(2);
- expect(cursor.sessionState).toBe(routedSessionState);
- });
-});
-
-function completion(taskId: string): DeliverHookPayload {
- return {
- kind: "deliver",
- taskDeliveryId: `${taskId}:ready:completed`,
- payloads: [
- {
- message: taskId,
- task: {
- views: [
- {
- taskId,
- status: "completed",
- metadata: { kind: "subagent", name: "worker" },
- lastOutput: { type: "result", data: taskId },
- },
- ],
- },
- },
- ],
- deliveryMetadata: [
- {
- payloadIndex: 0,
- deliveryId: taskId,
- channelKind: "eve",
- channelName: "eve",
- acceptedDeploymentId: "deployment",
- },
- ],
- };
-}
-
-function terminalDelivery(taskId: string, status: "failed" | "cancelled"): DeliverHookPayload {
- const view: TaskView = {
- taskId,
- metadata: { kind: "subagent", name: "worker" },
- ...(status === "failed"
- ? { status, lastOutput: { type: "error", data: "failed" } }
- : { status }),
- };
- return {
- kind: "deliver",
- taskDeliveryId: `${taskId}:ready:${status}`,
- payloads: [{ message: status, task: { views: [view] } }],
- };
-}
-
-function report(delivery: DeliverHookPayload): DeliverHookPayload {
- return {
- ...delivery,
- payloads: delivery.payloads.map(({ task: _task, ...payload }) => payload),
- };
-}
-
-function batchingInput(count = 100, crossTurn = false) {
- const input = waitInput(createMockInbox([]));
- const taskSessionState = {
- ...sessionState,
- snapshot: {
- session: {
- sessionId: "session",
- continuationToken: "token",
- history: [],
- agent: { system: "" },
- state: {
- "eve.workflowTool": {
- version: 3,
- runs: Array.from({ length: count }, (_, index) => ({
- callId: `task_${index}`,
- toolName: "worker",
- lifetime: "session" as const,
- origin: { turnId: crossTurn ? `turn-${index + 1}` : "turn-1", stepIndex: 0 },
- address: { runId: `run-${index}`, hookToken: `inbox-${index}` },
- task: {
- taskId: `task_${index}`,
- cohortId: "task_0",
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "subagent", name: "worker" },
- },
- })).concat([
- {
- callId: "other-cohort",
- toolName: "worker",
- lifetime: "session" as const,
- origin: { turnId: "turn-2", stepIndex: 0 },
- address: { runId: "other-run", hookToken: "other-inbox" },
- task: {
- taskId: "other-cohort",
- cohortId: "other-cohort",
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "subagent", name: "worker" },
- },
- },
- ]),
- },
- },
- },
- },
- };
- input.cursor = createCursor({ claimSessionHooks: async () => {} }, taskSessionState);
- vi.mocked(routeDeliverToChildren).mockImplementation(
- async ({ delivery, sessionState, serializedContext }) => ({
- kind: "continue",
- remainder: report(delivery),
- sessionState,
- serializedContext,
- }),
- );
- return { ...input };
-}
-
-describe("buffered task completion batching", () => {
- beforeEach(() => vi.mocked(routeDeliverToChildren).mockReset());
- afterEach(() => vi.mocked(routeDeliverToChildren).mockReset());
-
- it.each(["completed", "failed", "cancelled"] as const)(
- "keeps routed %s remainders behind the cohort barrier",
- async (status) => {
- const input = batchingInput(2);
- const original =
- status === "completed" ? completion("task_0") : terminalDelivery("task_0", status);
- const admission = input.queue.enqueueDelivery(original);
- assert(admission !== undefined);
- const routed = {
- ...original,
- payloads: original.payloads.map(({ task: _task, ...payload }) => payload),
- };
- input.queue.replaceDelivery(admission.sequence, routed);
- const last = completion("task_1");
- input.inbox = createMockInbox([
- messageRead("still working"),
- { result: { done: false, value: last } },
- ]);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- delivery: { payloads: [{ message: "still working" }] },
- });
- expect(input.queue.pendingCount).toBe(1);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- delivery: { payloads: [...routed.payloads, ...report(last).payloads] },
- });
- expect(input.queue.pendingCount).toBe(0);
- },
- );
-
- it.each(["completed", "failed", "cancelled"] as const)(
- "auto wakes for a %s outcome while its cross-turn sibling remains unfinished",
- async (status) => {
- const input = batchingInput(2, true);
- await input.cursor.apply({ serializedContext: { "eve.runtime.taskDeliveryPolicy": "auto" } });
- const first =
- status === "completed" ? completion("task_0") : terminalDelivery("task_0", status);
- input.queue.enqueueDelivery(first);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: report(first),
- });
- expect(input.queue.pendingCount).toBe(0);
- },
- );
-
- it("auto combines ready siblings without waiting for the remaining task", async () => {
- const input = batchingInput(3);
- await input.cursor.apply({ serializedContext: { "eve.runtime.taskDeliveryPolicy": "auto" } });
- const first = completion("task_0");
- const second = completion("task_1");
- input.queue.enqueueDelivery(first);
- input.queue.enqueueDelivery(first);
- input.queue.enqueueDelivery(second);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: {
- payloads: [...report(first).payloads, ...report(second).payloads],
- taskDeliveryIds: [first.taskDeliveryId, second.taskDeliveryId],
- },
- });
- expect(input.queue.pendingCount).toBe(0);
- input.queue.enqueueDelivery(first);
- expect(input.queue.pendingCount).toBe(0);
- });
-
- it("auto preserves intervening user input boundaries", async () => {
- const input = batchingInput(3);
- await input.cursor.apply({ serializedContext: { "eve.runtime.taskDeliveryPolicy": "auto" } });
- const question = {
- kind: "deliver",
- payloads: [{ message: "Alice checks the status." }],
- } as const;
- const first = completion("task_0");
- const second = completion("task_1");
- input.queue.enqueueDelivery(first);
- input.queue.enqueueDelivery(question);
- input.queue.enqueueDelivery(second);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: question,
- });
- expect(input.queue.pendingCount).toBe(2);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: { payloads: [...report(first).payloads, ...report(second).payloads] },
- });
- });
-
- it("delivers 100 buffered sibling results and their metadata in one parent turn", async () => {
- const input = batchingInput();
- const deliveries = Array.from({ length: 100 }, (_, index) => completion(`task_${index}`));
- const queue = queueOf(...deliveries);
- const next = await nextTurnDelivery({ ...input, queue });
-
- expect(next).toMatchObject({
- kind: "turn",
- delivery: {
- taskDeliveryId: "task_0:ready:completed",
- payloads: deliveries.flatMap((delivery) => report(delivery).payloads),
- deliveryMetadata: deliveries.map((delivery, payloadIndex) => ({
- ...delivery.deliveryMetadata![0],
- payloadIndex,
- })),
- },
- });
- expect(queue.pendingCount).toBe(0);
- expect(routeDeliverToChildren).toHaveBeenCalledTimes(101);
- });
-
- it.each([
- ["input request", { ...completion("task_2"), taskDeliveryId: "task_2:input:request-1" }],
- ["update", { ...completion("task_2"), taskDeliveryId: "task_2:update:1" }],
- ["other cohort", completion("other-cohort")],
- ["unknown task", completion("unknown-task")],
- ["user message", { kind: "deliver", payloads: [{ message: "user direction" }] }],
- [
- "caller",
- {
- ...completion("task_2"),
- caller: {
- callId: "call",
- subagentName: "worker",
- replyTo: { kind: "hook", token: "reply" },
- taskId: "task_2",
- },
- },
- ],
- ] satisfies readonly (readonly [string, DeliverHookPayload])[])(
- "services a %s while retaining incomplete cohorts",
- async (_name, boundary) => {
- const input = batchingInput();
- const first = completion("task_0");
- const second = completion("task_1");
- const later = completion("task_3");
- const queue = queueOf(first, second, boundary, later);
- const next = await nextTurnDelivery({ ...input, queue });
- expect(next).toMatchObject({ kind: "turn", delivery: report(boundary) });
- expect(queue.pendingCount).toBe(3);
- },
- );
-
- it.each([false, true])(
- "keeps the cohort across a user turn (cross-turn launches: %s)",
- async (crossTurn) => {
- const input = batchingInput(3, crossTurn);
- const first = completion("task_0");
- const second = completion("task_1");
- const last = completion("task_2");
- input.queue.enqueueDelivery(first);
- input.inbox = createMockInbox([
- { result: { done: false, value: second } },
- messageRead("user question"),
- { result: { done: false, value: last } },
- ]);
-
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: { payloads: [{ message: "user question" }] },
- });
- expect(input.queue.pendingCount).toBe(2);
- expect(routeDeliverToChildren).toHaveBeenCalledTimes(3);
-
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: {
- payloads: [
- ...report(first).payloads,
- ...report(second).payloads,
- ...report(last).payloads,
- ],
- },
- });
- expect(input.queue.pendingCount).toBe(0);
- expect(routeDeliverToChildren).toHaveBeenCalledTimes(5);
- },
- );
-
- it("batches a whole cohort when every completion arrives after the active turn", async () => {
- const input = batchingInput(3);
- const deliveries = [completion("task_0"), completion("task_1"), completion("task_2")];
- input.inbox = createMockInbox(
- deliveries.map((value) => ({ result: { done: false, value }, source: "session" })),
- );
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: { payloads: deliveries.flatMap((delivery) => report(delivery).payloads) },
- });
- expect(routeDeliverToChildren).toHaveBeenCalledTimes(4);
- });
-
- it("routes intervening child settlement before releasing the completion cohort", async () => {
- const input = batchingInput(2);
- const first = completion("task_0");
- const last = completion("task_1");
- const settlement: DeliverHookPayload = {
- kind: "deliver",
- payloads: [
- {
- task: {
- agentRequests: [
- {
- taskId: "task_1",
- replyTo: "child-reply",
- request: {
- kind: "agent-settled",
- result: {
- callId: "child-call",
- kind: "subagent-result",
- origin: "child",
- subagentName: "worker",
- output: "done",
- outcome: {
- kind: "terminal",
- result: { kind: "succeeded", output: "done" },
- usageDelta: {
- inputTokens: 211,
- outputTokens: 37,
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- },
- },
- },
- },
- },
- ],
- },
- },
- ],
- };
- for (const delivery of [first, settlement, last]) input.queue.enqueueDelivery(delivery);
- vi.mocked(routeDeliverToChildren).mockImplementation(
- async ({ delivery, sessionState, serializedContext }) => ({
- kind: "continue",
- remainder: delivery.payloads.some((payload) => payload.task?.agentRequests !== undefined)
- ? undefined
- : report(delivery),
- sessionState,
- serializedContext,
- }),
- );
-
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: { payloads: [...report(first).payloads, ...report(last).payloads] },
- });
- expect(vi.mocked(routeDeliverToChildren).mock.calls.map(([call]) => call.delivery)).toEqual([
- first,
- settlement,
- last,
- expect.objectContaining({ payloads: [...report(first).payloads, ...report(last).payloads] }),
- ]);
- expect(input.queue.pendingCount).toBe(0);
- });
-
- it("combines siblings across buffered deliveries from another cohort", async () => {
- const input = batchingInput(2);
- const first = completion("task_0");
- const last = completion("task_1");
- const other = completion("other-cohort");
- for (const delivery of [first, other, last]) input.queue.enqueueDelivery(delivery);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: { payloads: [...report(first).payloads, ...report(last).payloads] },
- });
- expect(input.queue.pendingCount).toBe(1);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: report(other),
- });
- });
-
- it.each(["clear", "compact", "reset", "session-timeout"] as const)(
- "services %s without releasing an incomplete cohort",
- async (kind) => {
- const input = batchingInput(2);
- const first = completion("task_0");
- input.queue.enqueueDelivery(first);
- const value: SessionInboxPayload =
- kind === "session-timeout" ? { kind, ownerRunId: "owner-1" } : { kind };
- input.inbox = createMockInbox([{ result: { done: false, value } }]);
- await expect(nextTurnDelivery(input)).resolves.toEqual({
- kind: kind === "session-timeout" ? "expired" : kind,
- });
- expect(input.queue.pendingCount).toBe(1);
- expect(routeDeliverToChildren).toHaveBeenCalledOnce();
- },
- );
-
- it("does not wait for a cancelled sibling whose notifications are discarded", async () => {
- const input = batchingInput(2);
- const first = completion("task_0");
- input.queue.enqueueDelivery(first);
- input.inbox = createMockInbox([cancelRead({ taskId: "task_1" })]);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: report(first),
- });
- });
-
- it("releases a cohort when cancellation is already recorded without waiting for its echo", () => {
- const input = batchingInput(2);
- const state = recordWorkflowTaskView(input.cursor.sessionState.snapshot.session.state, {
- taskId: "task_1",
- metadata: { kind: "subagent", name: "worker" },
- status: "cancelled",
- }).state;
- input.queue.enqueueDelivery(completion("task_0"));
- expect(input.queue.takeNext(state)).toMatchObject({ kind: "turn" });
- expect(input.queue.pendingCount).toBe(0);
- });
-
- it.each(["failed", "cancelled"] as const)(
- "does not admit a second terminal notification with a different %s outcome",
- (status) => {
- for (const deliveries of [
- [completion("task_0"), terminalDelivery("task_0", status)],
- [terminalDelivery("task_0", status), completion("task_0")],
- ]) {
- const queue = new SessionInputQueue();
- const [first, late] = deliveries;
- if (first === undefined || late === undefined) throw new Error("Expected two deliveries.");
- expect(queue.enqueueDelivery(first)).toBeDefined();
- expect(queue.enqueueDelivery(late)).toBeUndefined();
- expect(queue.pendingCount).toBe(1);
- expect(queue.takeNext(undefined)).toBeDefined();
- expect(queue.enqueueDelivery(late)).toBeUndefined();
- expect(queue.pendingCount).toBe(0);
- }
- },
- );
-
- it("ignores duplicate notifications while waiting for the last sibling", async () => {
- const input = batchingInput(2);
- const first = completion("task_0");
- const last = completion("task_1");
- input.inbox = createMockInbox(
- [first, first, last].map((value) => ({
- result: { done: false, value },
- source: "session",
- })),
- );
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: { payloads: [...report(first).payloads, ...report(last).payloads] },
- });
- });
-
- it.each(["failed", "cancelled"] as const)(
- "batches %s with successful siblings from the same cohort",
- async (status) => {
- const input = batchingInput(2);
- const first = completion("task_0");
- const terminal = terminalDelivery("task_1", status);
- for (const delivery of [first, terminal]) input.queue.enqueueDelivery(delivery);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: { payloads: [...report(first).payloads, ...report(terminal).payloads] },
- });
- expect(input.queue.pendingCount).toBe(0);
- },
- );
-
- it.each(["failed", "cancelled"] as const)(
- "batches an all-%s cohort into one report",
- async (status) => {
- const input = batchingInput(2);
- const first = terminalDelivery("task_0", status);
- const last = terminalDelivery("task_1", status);
- for (const delivery of [first, last]) input.queue.enqueueDelivery(delivery);
- await expect(nextTurnDelivery(input)).resolves.toMatchObject({
- kind: "turn",
- delivery: { payloads: [...report(first).payloads, ...report(last).payloads] },
- });
- expect(input.queue.pendingCount).toBe(0);
- },
- );
-
- it("services ready authorization before a buffered completion batch", async () => {
- const input = batchingInput();
- const queue = queueOf(completion("task_0"), completion("task_1"));
- queue.enqueueAuthorization(authorizationCallbackPayload.payloads);
- const next = await nextTurnDelivery({ ...input, queue, inbox: createMockInbox([]) });
- expect(next.kind).toBe("authorization-resume");
- expect(queue.pendingCount).toBe(2);
- expect(routeDeliverToChildren).toHaveBeenCalledTimes(2);
- });
-});
diff --git a/packages/eve/src/execution/session/next-input.ts b/packages/eve/src/execution/session/next-input.ts
index 4346a2220..031e0f418 100644
--- a/packages/eve/src/execution/session/next-input.ts
+++ b/packages/eve/src/execution/session/next-input.ts
@@ -1,6 +1,4 @@
-import { TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME } from "#context/key-names.js";
import type { DeliverPayload } from "#channel/types.js";
-import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import { routeSelectedDelivery } from "#execution/session/route-selected-delivery.js";
import type {
SessionControl,
@@ -8,10 +6,7 @@ import type {
TurnSelection,
} from "#execution/session/input-queue.js";
import type { SessionInboxReader } from "#execution/session-inbox/inbox.js";
-import {
- admitSessionInboxPayload,
- applySessionCancellation,
-} from "#execution/session/admission.js";
+import { admitSessionInboxPayload } from "#execution/session/admission.js";
import type { SessionStateCursor } from "#execution/session/state-cursor.js";
import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
@@ -41,22 +36,7 @@ export async function nextTurnDelivery(input: {
// pumped) is the only kind that may move the session to another deployment.
let freshSequence: number | undefined;
while (true) {
- for (const { delivery, sequence } of queue.taskDeliveries()) {
- const routed = await routeDeliverToChildren({
- delivery,
- sessionWritable: cursor.sessionWritable,
- serializedContext: cursor.serializedContext,
- sessionState: cursor.sessionState,
- });
- await cursor.apply(routed);
- queue.replaceDelivery(sequence, routed.kind === "cancel-turn" ? undefined : routed.remainder);
- if (routed.kind === "cancel-turn") return routed;
- }
- const selected = queue.takeNext(cursor.sessionState.snapshot.session.state, {
- taskDeliveryPolicy:
- cursor.serializedContext[TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME] === "auto"
- ? "auto"
- : "cohort",
+ const selected = queue.takeNext({
expectedAttemptIds: input.expectedAttemptIds,
freshSequence: inbox.hasPending() ? undefined : freshSequence,
});
@@ -80,16 +60,6 @@ export async function nextTurnDelivery(input: {
const admitted = await admitSessionInboxPayload(payload, input);
freshSequence =
wasIdle && admitted.kind === "delivery" ? admitted.admission.sequence : undefined;
- switch (admitted.kind) {
- case "workflow":
- return { kind: "workflow", message: admitted.message };
- case "cancel":
- await applySessionCancellation(admitted.command, input);
- break;
- case "delivery":
- case "consumed":
- case "runtime-action-result":
- break;
- }
+ if (admitted.kind === "workflow") return { kind: "workflow", message: admitted.message };
}
}
diff --git a/packages/eve/src/execution/session/pending-turn-state.ts b/packages/eve/src/execution/session/pending-turn-state.ts
index 44fe3ca66..ed94edb68 100644
--- a/packages/eve/src/execution/session/pending-turn-state.ts
+++ b/packages/eve/src/execution/session/pending-turn-state.ts
@@ -22,8 +22,6 @@ export function derivePendingState(session: HarnessSession): {
if (batch === undefined) return base;
return {
...base,
- pendingCoordinationCallIds: [...batch.runtimeActions, ...batch.tasks].map(
- (request) => request.callId,
- ),
+ pendingCoordinationCallIds: batch.tasks.map((request) => request.callId),
};
}
diff --git a/packages/eve/src/execution/session/program.ts b/packages/eve/src/execution/session/program.ts
index f6fd18284..a5bb97a2a 100644
--- a/packages/eve/src/execution/session/program.ts
+++ b/packages/eve/src/execution/session/program.ts
@@ -224,7 +224,6 @@ async function runSessionLoop(
let turnIndex = 0;
const runTurn = async (payload: TurnStepPayload | undefined): Promise<TurnOutcome> => {
const caller = progress.caller;
- if (caller?.taskId !== undefined) queue.rememberTask(caller.taskId);
if (caller !== undefined) {
await cursor.apply({
serializedContext: await bindTurnCallerContextStep({
@@ -249,9 +248,7 @@ async function runSessionLoop(
};
const settleCancelledTurn = async () => {
const settled = await settleCancelledTurnStep({
- sessionWritable: boot.sessionWritable,
- serializedContext: cursor.serializedContext,
- sessionState: cursor.sessionState,
+ ...cursor.stepState(),
});
await cursor.apply(settled);
progress.caller = undefined;
@@ -308,7 +305,7 @@ async function runSessionLoop(
? cancelledCaller
: { ...cancelledCaller, usage: settled.usage },
);
- } else if (action.settled?.notifyCaller === true) {
+ } else if (action.settled !== undefined) {
if (progress.caller !== undefined) {
await notifyTurnCallerStep({
caller: progress.caller,
diff --git a/packages/eve/src/execution/session/route-selected-delivery.ts b/packages/eve/src/execution/session/route-selected-delivery.ts
index 8e2082069..db0d9d134 100644
--- a/packages/eve/src/execution/session/route-selected-delivery.ts
+++ b/packages/eve/src/execution/session/route-selected-delivery.ts
@@ -14,9 +14,7 @@ export async function routeSelectedDelivery(
): Promise<RoutedTurnSelection> {
const routed = await routeDeliverToChildren({
delivery: selection.delivery,
- sessionWritable: cursor.sessionWritable,
- serializedContext: cursor.serializedContext,
- sessionState: cursor.sessionState,
+ ...cursor.stepState(),
});
await cursor.apply(routed);
if (routed.kind === "cancel-turn") return { kind: "cancel-turn" };
diff --git a/packages/eve/src/execution/session/state-compatibility.test.ts b/packages/eve/src/execution/session/state-compatibility.test.ts
index b09e95ce7..5d94c2c8c 100644
--- a/packages/eve/src/execution/session/state-compatibility.test.ts
+++ b/packages/eve/src/execution/session/state-compatibility.test.ts
@@ -1,66 +1,19 @@
-import { assert, describe, expect, it } from "vitest";
+import { describe, expect, it } from "vitest";
import { createTestSessionState } from "#internal/testing/session-state.js";
import { isSessionStateIdleForHandoff } from "#execution/session/handoff-steps.js";
-import {
- readWorkflowTaskView,
- recordWorkflowTaskView,
- getBackgroundTasks,
- registerWorkflowToolRun,
-} from "#harness/workflow-tool-runs.js";
-import { parseActivityWorkIdentityV1 } from "#protocol/activity.js";
-import type { HarnessSession } from "#harness/types.js";
import type { AgentHandle, AgentHandlePhase } from "#subagents/handles/store.js";
-const metadata = { kind: "tool", name: "research" };
-const activity = {
- id: "work",
- kind: "task" as const,
- rootSessionId: "root",
- rootTurnId: "turn",
- futureActivity: { label: "Alice's research" },
-};
-const task = {
- callId: "task",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn", stepIndex: 0, futureOrigin: true },
- address: { runId: "run", hookToken: "inbox", futureAddress: true },
- futureInvocation: true,
- task: {
- taskId: "task",
- metadata,
- activityWorkIdentity: activity,
- futureTask: { revision: 2 },
- outcome: {
- status: "completed" as const,
- lastOutput: { type: "result" as const, data: "done", futureOutput: true },
- usage: {
- inputTokens: 1,
- outputTokens: 2,
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- futureUsage: true,
- },
- futureView: true,
- },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
+const run = {
+ callId: "call",
+ toolName: "research",
+ origin: { turnId: "turn", stepIndex: 0 },
+ address: { runId: "run", hookToken: "inbox" },
};
+
function checkpoint(state: Record<string, unknown>) {
const value = createTestSessionState();
return { ...value, snapshot: { session: { ...value.snapshot.session, state } } };
}
-function session(state: Record<string, unknown>): HarnessSession {
- return {
- agent: { modelReference: { id: "model" }, system: "", tools: [] },
- compaction: { recentWindowSize: 4, threshold: 1_000_000 },
- continuationToken: "token",
- history: [],
- sessionId: "session",
- state,
- };
-}
-const restored = <T>(value: T): T => JSON.parse(JSON.stringify(value));
const identity = { id: "ag_researcher:operation", name: "researcher", nodeId: "agent" };
const address = {
@@ -89,92 +42,14 @@ function handle(phase: AgentHandlePhase): AgentHandle {
case "parked":
return { address, identity, lastStatus: "Research complete", phase };
case "reserved":
- return { identity, operationId: "operation", ownerId: "task", phase };
+ return { identity, operationId: "operation", ownerId: "run", phase };
case "claimed":
- return { address, identity, operationId: "operation", ownerId: "task", phase };
+ return { address, identity, operationId: "operation", ownerId: "run", phase };
case "available":
return { address, identity, phase };
}
}
-describe("additive durable state", () => {
- it("preserves task extensions through parsing, replayed creation and duplicate terminal deliveries", () => {
- const state = {
- authored: { opaque: true },
- "eve.workflowTool": { version: 3, runs: [task], futureIndex: true },
- };
- expect(
- getBackgroundTasks(restored(state))
- .query()
- .map((entry) => entry.run),
- ).toEqual([task]);
- expect(parseActivityWorkIdentityV1(activity)).toEqual(activity);
- const updated = registerWorkflowToolRun(session(restored(state)), {
- callId: "task",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn", stepIndex: 0 },
- address: { runId: "new-run", hookToken: "inbox" },
- task: {
- taskId: "task",
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata,
- activityWorkIdentity: {
- id: "work",
- kind: "task",
- rootSessionId: "root",
- rootTurnId: "turn",
- },
- },
- });
- const saved = recordWorkflowTaskView(updated.state, {
- taskId: "task",
- metadata,
- status: "completed",
- lastOutput: { type: "result", data: "updated" },
- usage: { inputTokens: 3, outputTokens: 4, cacheReadTokens: 0, cacheWriteTokens: 0 },
- }).state;
- expect(restored(saved)).toMatchObject({
- authored: { opaque: true },
- "eve.workflowTool": {
- version: 3,
- futureIndex: true,
- runs: [
- {
- address: { runId: "new-run", futureAddress: true },
- origin: { futureOrigin: true },
- futureInvocation: true,
- task: {
- futureTask: { revision: 2 },
- activityWorkIdentity: activity,
- outcome: {
- futureView: true,
- lastOutput: { data: "done", futureOutput: true },
- usage: { inputTokens: 1, futureUsage: true },
- },
- },
- },
- ],
- },
- });
- assert(saved !== undefined);
- expect(isSessionStateIdleForHandoff(checkpoint(restored(saved)))).toBe(true);
- const cancelled = recordWorkflowTaskView(saved, {
- taskId: "task",
- metadata,
- status: "cancelled",
- }).state;
- expect(getBackgroundTasks(restored(cancelled)).get("task")?.run.task.outcome).toMatchObject({
- futureView: true,
- status: "completed",
- });
- expect(cancelled).toBe(saved);
- const retained = getBackgroundTasks(restored(cancelled)).get("task");
- assert(retained !== undefined);
- expect(readWorkflowTaskView(retained.run.task)?.lastOutput?.data).toBe("done");
- });
-});
-
describe("handoff state inspection", () => {
it("accepts additive framework metadata and opaque authored state", () => {
expect(
@@ -182,7 +57,6 @@ describe("handoff state inspection", () => {
checkpoint({
"eve.agent.handles": { handles: [], futureStore: true },
authored: { version: "anything", values: [null, false] },
- "eve.workflowTool": { version: 3, runs: [task], futureIndex: true },
}),
),
).toBe(true);
@@ -218,42 +92,29 @@ describe("handoff state inspection", () => {
),
).toThrow("Corrupt agent handle store");
});
- it("parses settled entries before checking their terminal status", () => {
- const incompatible = { ...task, address: { ...task.address, hookToken: 42 } };
+ it("parses workflow tool runs before checking for waiting work", () => {
+ const incompatible = { ...run, address: { ...run.address, hookToken: 42 } };
expect(() =>
isSessionStateIdleForHandoff(
checkpoint({
- "eve.workflowTool": { version: 3, runs: [incompatible] },
+ "eve.workflowTool": { version: 4, runs: [incompatible] },
}),
),
).toThrow("Corrupt workflow tool run registry");
});
- it("does not skip task parsing when another registry is busy", () => {
+ it("does not skip run parsing when another registry is busy", () => {
expect(() =>
isSessionStateIdleForHandoff(
checkpoint({
"eve.runtime.pendingAuthorization": {},
"eve.workflowTool": {
- version: 3,
- runs: [{ ...task, address: { ...task.address, runId: null } }],
+ version: 4,
+ runs: [{ ...run, address: { ...run.address, runId: null } }],
},
}),
),
).toThrow("Corrupt workflow tool run registry");
});
- it("validates retained results even when other work prevents handoff", () => {
- expect(() =>
- isSessionStateIdleForHandoff(
- checkpoint({
- "eve.runtime.pendingAuthorization": {},
- "eve.workflowTool": {
- version: 3,
- runs: [{ ...task, task: { ...task.task, outcome: { status: "completed" } } }],
- },
- }),
- ),
- ).toThrow("Corrupt workflow task result");
- });
it.each([
["eve.runtime.pendingAuthorization", false],
["eve.runtime.pendingInputBatch", {}],
diff --git a/packages/eve/src/execution/session/state-cursor.ts b/packages/eve/src/execution/session/state-cursor.ts
index aaa061a23..63c96f1d0 100644
--- a/packages/eve/src/execution/session/state-cursor.ts
+++ b/packages/eve/src/execution/session/state-cursor.ts
@@ -1,7 +1,7 @@
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { SessionStepState } from "#execution/publish-session-events.js";
import { sessionHookTokens } from "#execution/session/hook-tokens.js";
import type { SessionInboxOwnership } from "#execution/session-inbox/inbox.js";
-import type { TurnStepInput, TurnStepPayload } from "#execution/session/turn-step-types.js";
/** A durable-state transition; absent fields keep the cursor's current value. */
export interface SessionStateTransition {
@@ -51,16 +51,12 @@ export class SessionStateCursor {
this.currentSessionState = sessionState;
}
- createStepInput(
- input: TurnStepPayload | undefined,
- signals: Pick<TurnStepInput, "abortSignal" | "steeringSignal">,
- ): TurnStepInput {
+ /** The session's stream and current state, spread into a step's input. */
+ stepState(): SessionStepState {
return {
- ...signals,
- input,
- sessionWritable: this.sessionWritable,
serializedContext: this.currentSerializedContext,
sessionState: this.currentSessionState,
+ sessionWritable: this.sessionWritable,
};
}
}
diff --git a/packages/eve/src/execution/session/task-settlement.integration.test.ts b/packages/eve/src/execution/session/task-settlement.integration.test.ts
deleted file mode 100644
index 6ba063457..000000000
--- a/packages/eve/src/execution/session/task-settlement.integration.test.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
-import { emitSubagentEventStep } from "#execution/tools/subagent/emit-event-step.js";
-
-vi.mock("#execution/tools/subagent/emit-event-step.js", () => ({
- emitSubagentEventStep: vi.fn(),
-}));
-
-import { expect, it, vi } from "vitest";
-
-import type { DeliverHookPayload } from "#channel/types.js";
-import { replaceDurableSessionSnapshot } from "#execution/durable-session-store.js";
-import { SessionInputQueue } from "#execution/session/input-queue.js";
-import { nextTurnDelivery } from "#execution/session/next-input.js";
-import { SessionStateCursor } from "#execution/session/state-cursor.js";
-import {
- getProxyInputRequests,
- upsertProxyInputRequestState,
-} from "#harness/proxy-input-requests.js";
-import { getBackgroundTasks, registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-import { createTestSessionState } from "#internal/testing/session-state.js";
-import type { TaskView } from "#tasks/types.js";
-
-it.each(["completed", "failed", "cancelled"] as const)(
- "records a parked parent's %s task and removes its question before reporting the cohort",
- async (status) => {
- vi.mocked(emitSubagentEventStep)
- .mockReset()
- .mockImplementation(async (input) => ({
- serializedContext: {},
- sessionState: input.sessionState,
- }));
- let state = createTestSessionState();
- let session = state.snapshot.session;
- for (const taskId of ["A", "B"]) {
- session = registerWorkflowToolRun(session, {
- callId: taskId,
- toolName: "worker",
- lifetime: "session",
- origin: { turnId: "turn", stepIndex: 0 },
- address: { runId: taskId, hookToken: taskId },
- task: {
- taskId,
- metadata: { kind: "subagent", name: "worker" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- });
- }
- session = {
- ...session,
- state: upsertProxyInputRequestState({
- state: session.state,
- forChildContinuationToken: "answer-A",
- entries: [
- [
- "question-A",
- {
- childContinuationToken: "answer-A",
- childRequestId: "question",
- kind: "question",
- taskId: "A",
- },
- ],
- ],
- }),
- };
- state = replaceDurableSessionSnapshot({ session, state });
- const cursor = new SessionStateCursor({
- inbox: { claimSessionHooks: async () => {} },
- sessionWritable: new WritableStream<Uint8Array>(),
- serializedContext: {},
- sessionState: state,
- });
- const queue = new SessionInputQueue();
- const a: TaskView = {
- taskId: "A",
- metadata: { kind: "subagent", name: "worker" },
- ...(status === "completed"
- ? { status, lastOutput: { type: "result", data: "done" } }
- : status === "failed"
- ? { status, lastOutput: { type: "error", data: "timeout" } }
- : { status }),
- };
- const notification = (view: TaskView): DeliverHookPayload => ({
- kind: "deliver",
- taskDeliveryId: `${view.taskId}:ready:${view.status}`,
- payloads: [{ message: "task outcome", task: { views: [view] } }],
- });
- queue.enqueueDelivery(notification(a));
- let reads = 0;
- const next = await nextTurnDelivery({
- cursor,
- queue,
- inbox: {
- hasPending: () => false,
- drain: () => [],
- onInterrupt: () => () => {},
- onDelivery: () => () => {},
- restore: () => {},
- async next() {
- // The owner is about to wait for B; A must already be settled without a model turn.
- reads++;
- const current = cursor.sessionState.snapshot.session;
- expect(getBackgroundTasks(current.state).get("A")?.run.task.outcome).toEqual({
- status: a.status,
- lastOutput: a.lastOutput,
- usage: a.usage,
- });
- expect(getProxyInputRequests(current.state).size).toBe(0);
- expect(cursor.sessionState.hasProxyInputRequests).toBe(false);
- expect(queue.pendingCount).toBe(1);
- expect(emitSubagentEventStep).toHaveBeenCalledTimes(status === "completed" ? 1 : 0);
- return notification({
- taskId: "B",
- metadata: { kind: "subagent", name: "worker" },
- status: "completed",
- lastOutput: { type: "result", data: "done B" },
- });
- },
- },
- });
- expect(reads).toBe(1);
- expect(next).toMatchObject({
- kind: "turn",
- delivery: {
- payloads: [
- { message: expect.stringContaining("Background task A") },
- { message: expect.stringContaining("Background task B") },
- ],
- },
- });
- expect(queue.pendingCount).toBe(0);
- },
-);
-
-it.each(["completed", "failed", "cancelled"] as const)(
- "publishes a background subagent result only for a newly recorded success (%s)",
- async (status) => {
- vi.mocked(emitSubagentEventStep).mockReset();
- const initial = createTestSessionState();
- const metadata = { kind: "subagent", name: "researcher" };
- let sessionState = replaceDurableSessionSnapshot({
- state: initial,
- session: registerWorkflowToolRun(initial.snapshot.session, {
- callId: "original-call",
- toolName: "researcher",
- lifetime: "session",
- origin: { turnId: "turn", stepIndex: 0 },
- address: { runId: "run", hookToken: "hook" },
- task: {
- taskId: "task",
- metadata,
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- }),
- });
- const view: TaskView = {
- taskId: "task",
- metadata,
- ...(status === "completed"
- ? { status, lastOutput: { type: "result", data: { answer: 42 } } }
- : status === "failed"
- ? { status, lastOutput: { type: "error", data: "failed" } }
- : { status }),
- };
- vi.mocked(emitSubagentEventStep).mockImplementation(async (input) => {
- expect(
- getBackgroundTasks(input.sessionState.snapshot.session.state).get("task")?.run.task.outcome,
- ).toEqual({ status: view.status, lastOutput: view.lastOutput, usage: view.usage });
- return {
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- });
- const deliver = async (outcome: TaskView) => {
- const result = await routeDeliverToChildren({
- delivery: { kind: "deliver", payloads: [{ task: { views: [outcome] } }] },
- serializedContext: {},
- sessionState,
- sessionWritable: new WritableStream<Uint8Array>(),
- });
- sessionState = result.sessionState;
- };
- await deliver(view);
- await deliver(view);
- // A late success must not replace a failed or cancelled task, nor republish a success.
- await deliver({
- taskId: "task",
- metadata,
- status: "completed",
- lastOutput: { type: "result", data: "late" },
- });
- expect(emitSubagentEventStep).toHaveBeenCalledTimes(status === "completed" ? 1 : 0);
- if (status === "completed") {
- expect(emitSubagentEventStep).toHaveBeenCalledWith(
- expect.objectContaining({
- event: {
- type: "subagent.completed",
- data: { callId: "original-call", subagentName: "researcher", output: '{"answer":42}' },
- },
- }),
- );
- }
- expect(
- getBackgroundTasks(sessionState.snapshot.session.state).get("task")?.run.task.outcome,
- ).toEqual({ status: view.status, lastOutput: view.lastOutput, usage: view.usage });
- },
-);
diff --git a/packages/eve/src/execution/session/turn-event-handler.ts b/packages/eve/src/execution/session/turn-event-handler.ts
index 4202a3d20..c32c9dc1b 100644
--- a/packages/eve/src/execution/session/turn-event-handler.ts
+++ b/packages/eve/src/execution/session/turn-event-handler.ts
@@ -8,7 +8,7 @@ import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";
import { dispatchMemoryLifecycleEvent } from "#context/memory-event-lifecycle.js";
import type { bindDynamicConnections } from "#execution/dynamic-connections.js";
import type { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
-import type { SessionEventSink } from "#execution/session/event-sink.js";
+import type { SessionEventSink } from "#execution/publish-session-events.js";
import { throwIfTurnAborted, TurnCancelledError } from "#harness/turn-cancellation.js";
import type { HandleEventFn } from "#harness/types.js";
import type { HookEventType } from "#public/definitions/hook.js";
@@ -25,6 +25,7 @@ const HOOK_CANCELLABLE_EVENTS = {
"action.partial": true,
"action.result": true,
"actions.requested": true,
+ "agent.started": false,
"approval.candidate": true,
"approval.settled": true,
"authorization.completed": true,
@@ -55,6 +56,7 @@ const HOOK_CANCELLABLE_EVENTS = {
"turn.completed": false,
"turn.failed": false,
"turn.started": true,
+ "turn.waiting": false,
} as const satisfies Record<HookEventType, boolean>;
/** True when a hook on this event type may cancel the running turn. */
@@ -94,50 +96,48 @@ export function createTurnEventHandler(input: {
nodeId: bundle.nodeId ?? "__root__",
});
const cancelTurn =
- input.canCancelTurn && isHookCancellableEvent(emitted.event.type)
+ input.canCancelTurn && isHookCancellableEvent(emitted.type)
? () => input.hookCancellation.abort(new TurnCancelledError())
: undefined;
- if (!emitted.suppressed) {
- await dispatchStreamEventHooks({
- cancelTurn,
- ctx,
- registry: bundle.hookRegistry,
- event: emitted.event,
- });
- }
- if (emitted.event.type !== "step.started") {
+ await dispatchStreamEventHooks({
+ cancelTurn,
+ ctx,
+ registry: bundle.hookRegistry,
+ event: emitted,
+ });
+ if (emitted.type !== "step.started") {
await dispatchDynamicModelEvent({
abortSignal,
ctx,
dynamicModel: effectiveAgent.turnAgent.dynamicModel,
- event: emitted.event,
+ event: emitted,
messages: lifecycleMessages,
scope: { moduleMap: bundle.moduleMap, nodeId: bundle.nodeId },
});
}
- await input.dynamicConnections.dispatch(emitted.event);
+ await input.dynamicConnections.dispatch(emitted);
await dispatchDynamicSubagentEvent({
ctx,
resolvers: bundle.subagentRegistry.dynamicResolvers ?? [],
- event: emitted.event,
+ event: emitted,
messages: lifecycleMessages,
});
await dispatchDynamicToolEvent({
ctx,
resolvers: bundle.resolvedAgent.dynamicToolResolvers ?? [],
- event: emitted.event,
+ event: emitted,
messages: lifecycleMessages,
});
await dispatchDynamicSkillEvent({
ctx,
resolvers: bundle.resolvedAgent.dynamicSkillResolvers ?? [],
- event: emitted.event,
+ event: emitted,
messages: lifecycleMessages,
});
await dispatchDynamicInstructionEvent({
ctx,
resolvers: bundle.resolvedAgent.dynamicInstructionsResolvers ?? [],
- event: emitted.event,
+ event: emitted,
messages: lifecycleMessages,
});
if (cancelTurn !== undefined) throwIfTurnAborted(input.hookCancellation.signal);
diff --git a/packages/eve/src/execution/session/turn-step-result.test.ts b/packages/eve/src/execution/session/turn-step-result.test.ts
deleted file mode 100644
index e23abff34..000000000
--- a/packages/eve/src/execution/session/turn-step-result.test.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { resolveSessionStepResult } from "#execution/session/turn-step-result.js";
-import { setTurnUsageState, takeSessionUsageDelta } from "#harness/turn-tag-state.js";
-import type { HarnessSession, SettledTurn } from "#harness/types.js";
-import { recordWorkflowTaskView, registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-
-function session(): HarnessSession {
- return {
- agent: { modelReference: { id: "unused" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100_000 },
- continuationToken: "detector",
- history: [],
- sessionId: "detector",
- };
-}
-
-function startWorker(
- session: HarnessSession,
- taskId: string,
- turnId = "current-turn",
-): HarnessSession {
- return registerWorkflowToolRun(session, {
- callId: taskId,
- toolName: "worker",
- lifetime: "session",
- origin: { turnId, stepIndex: 0 },
- address: { runId: taskId, hookToken: taskId },
- task: {
- taskId,
- metadata: { kind: "subagent", name: "worker" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- });
-}
-
-function endTurn(session: HarnessSession, settledTurn: SettledTurn, turnId = "current-turn") {
- return resolveSessionStepResult({ next: null, session, settledTurn }, {}, {}, turnId);
-}
-
-function withUsage(session: HarnessSession, inputTokens: number): HarnessSession {
- const totals = {
- inputTokens,
- outputTokens: 0,
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- costUsd: 0,
- sawCost: false,
- };
- return setTurnUsageState(session, { ...totals, session: totals, turnId: "current-turn" });
-}
-
-describe("delegated turn completion", () => {
- it("defers caller notification while a task is working and reports accumulated usage with the final result", () => {
- const pending = startWorker(withUsage(session(), 100), "worker-1");
- const parked = endTurn(pending, { output: "Verification is running." });
- expect(parked).toMatchObject({
- action: "park",
- settled: { output: "Verification is running.", notifyCaller: false },
- });
- const checkpoint = { ...pending, state: parked.sessionState.snapshot.session.state };
- expect(takeSessionUsageDelta(checkpoint).delta.inputTokens).toBe(100);
-
- const completed = withUsage(
- {
- ...checkpoint,
- state: recordWorkflowTaskView(checkpoint.state, {
- taskId: "worker-1",
- metadata: { kind: "subagent", name: "worker" },
- status: "completed",
- lastOutput: { type: "result", data: "VERIFIED" },
- }).state,
- },
- 150,
- );
- // The worker's notification wakes a later turn, which gives the final answer.
- const settled = endTurn(completed, { output: "VERIFIED" }, "woken-turn");
- expect(settled).toMatchObject({
- action: "park",
- settled: {
- notifyCaller: true,
- output: "VERIFIED",
- usage: { inputTokens: 150 },
- },
- });
- expect(
- takeSessionUsageDelta({ ...completed, state: settled.sessionState.snapshot.session.state })
- .delta.inputTokens,
- ).toBe(0);
- });
-
- it("does not notify the caller after one worker finishes while another is working", () => {
- const pending = startWorker(startWorker(session(), "worker-1"), "worker-2");
- const partiallyCompleted = {
- ...pending,
- state: recordWorkflowTaskView(pending.state, {
- taskId: "worker-1",
- metadata: { kind: "subagent", name: "worker" },
- status: "completed",
- lastOutput: { type: "result", data: "First result" },
- }).state,
- };
- expect(endTurn(partiallyCompleted, { output: "Still working." })).toMatchObject({
- action: "park",
- settled: { notifyCaller: false },
- });
- });
-
- it("answers the caller when only work started by an earlier turn is still working", () => {
- const pending = startWorker(session(), "monitor", "earlier-turn");
- expect(endTurn(pending, { output: "Here is the report." })).toMatchObject({
- action: "park",
- settled: { notifyCaller: true, output: "Here is the report." },
- });
- });
-
- it.each(["failed", "cancelled"] as const)(
- "allows a final response after a worker is %s",
- (status) => {
- const pending = startWorker(session(), "worker-1");
- const finished = {
- ...pending,
- state: recordWorkflowTaskView(pending.state, {
- taskId: "worker-1",
- metadata: { kind: "subagent", name: "worker" },
- ...(status === "failed"
- ? { status, lastOutput: { type: "error" as const, data: "Failed" } }
- : { status }),
- }).state,
- };
- expect(endTurn(finished, { output: "Unable to verify." })).toMatchObject({
- action: "park",
- settled: { notifyCaller: true, output: "Unable to verify." },
- });
- },
- );
-
- it("answers the caller with a final error even when its worker is still working", () => {
- expect(
- endTurn(startWorker(session(), "worker-1"), { isError: true, output: "Model failed" }),
- ).toMatchObject({
- action: "park",
- settled: { notifyCaller: true, isError: true, output: "Model failed" },
- });
- });
-});
diff --git a/packages/eve/src/execution/session/turn-step-result.ts b/packages/eve/src/execution/session/turn-step-result.ts
index b996758c4..52d3dfcf8 100644
--- a/packages/eve/src/execution/session/turn-step-result.ts
+++ b/packages/eve/src/execution/session/turn-step-result.ts
@@ -1,17 +1,12 @@
import { createDurableSessionState } from "#execution/durable-session-store.js";
import { derivePendingState } from "#execution/session/pending-turn-state.js";
import type { DurableStepResult } from "#execution/session/turn-step-types.js";
-import { getBackgroundTasks } from "#harness/workflow-tool-runs.js";
import { getTurnUsageState, takeSessionUsageDelta, toUsage } from "#harness/turn-tag-state.js";
import type { StepResult } from "#harness/types.js";
-import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";
export function resolveSessionStepResult(
stepResult: StepResult,
nextSerializedContext: Record<string, unknown>,
- beforeStepContext: Record<string, unknown>,
- /** The turn this step belongs to. */
- turnId: string,
): DurableStepResult {
const nextState = createDurableSessionState({ session: stepResult.session });
if (stepResult.steered)
@@ -20,20 +15,6 @@ export function resolveSessionStepResult(
serializedContext: nextSerializedContext,
sessionState: nextState,
};
- const backgroundTransition =
- stepResult.backgroundTasks === undefined || stepResult.backgroundTaskSession === undefined
- ? {}
- : {
- backgroundTaskContext: preserveSerializedBackgroundTaskObservabilityState(
- beforeStepContext,
- nextSerializedContext,
- stepResult.backgroundTasks,
- ),
- backgroundTaskState: createDurableSessionState({
- session: stepResult.backgroundTaskSession,
- }),
- backgroundTasks: stepResult.backgroundTasks,
- };
if (
stepResult.next !== null &&
@@ -43,7 +24,6 @@ export function resolveSessionStepResult(
const sessionTotals = getTurnUsageState(stepResult.session.state)?.session;
return {
action: "done",
- ...backgroundTransition,
output: stepResult.next.output,
isError: stepResult.next.isError,
serializedContext: nextSerializedContext,
@@ -56,32 +36,15 @@ export function resolveSessionStepResult(
if (stepResult.next === null) {
const pending = derivePendingState(stepResult.session);
- // A turn that ends while its own background tasks are working yields: its answer is interim.
- // Usage stays unreported so the caller's final result includes every yielded turn. An error
- // is final and always answers the caller.
+ // Usage stays unreported until the turn settles, so the caller's result includes all of it.
if (stepResult.settledTurn !== undefined) {
- const yielded =
- stepResult.settledTurn.isError !== true &&
- getBackgroundTasks(stepResult.session.state).query({ state: "working", turnId }).length > 0;
- if (yielded) {
- return {
- action: "park",
- ...backgroundTransition,
- ...pending,
- settled: { ...stepResult.settledTurn, notifyCaller: false },
- serializedContext: nextSerializedContext,
- sessionState: nextState,
- };
- }
const { delta, session: reportedSession } = takeSessionUsageDelta(stepResult.session);
return {
action: "park",
- ...backgroundTransition,
...pending,
serializedContext: nextSerializedContext,
sessionState: createDurableSessionState({ session: reportedSession }),
settled: {
- notifyCaller: true,
output: stepResult.settledTurn.output,
isError: stepResult.settledTurn.isError,
usage: delta,
@@ -91,7 +54,6 @@ export function resolveSessionStepResult(
return {
action: "park",
- ...backgroundTransition,
...pending,
serializedContext: nextSerializedContext,
sessionState: nextState,
@@ -100,7 +62,6 @@ export function resolveSessionStepResult(
return {
action: "continue",
- ...backgroundTransition,
serializedContext: nextSerializedContext,
sessionState: nextState,
};
diff --git a/packages/eve/src/execution/session/turn-step-types.ts b/packages/eve/src/execution/session/turn-step-types.ts
index 19a54028c..51166d58b 100644
--- a/packages/eve/src/execution/session/turn-step-types.ts
+++ b/packages/eve/src/execution/session/turn-step-types.ts
@@ -1,15 +1,10 @@
import type { DeliverHookPayload } from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
-import type { SettledTurn, StepResult } from "#harness/types.js";
+import type { SessionStepState } from "#execution/publish-session-events.js";
+import type { SettledTurn } from "#harness/types.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
import type { TokenUsage } from "#shared/token-usage.js";
-/** A settled turn as the session parks it. The session, not the harness, decides caller delivery. */
-export interface ParkedSettledTurn extends SettledTurn {
- /** False while background tasks started by this turn are still working. */
- readonly notifyCaller: boolean;
-}
-
/** Trusted runtime-action results collected by the session owner. */
export interface RuntimeActionResultStepInput {
readonly acceptedAtMsByCallId?: Readonly<Record<string, number>>;
@@ -28,20 +23,13 @@ export interface TurnStepPayload {
}
/** Input for one atomic, session-owner-executed turn step. */
-export interface TurnStepInput {
+export interface TurnStepInput extends SessionStepState {
readonly abortSignal?: AbortSignal;
readonly steeringSignal?: AbortSignal;
readonly input: TurnStepPayload | undefined;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
}
interface DurableStepResultFields {
- /** Pre-step context plus the observability state owned by committed background tasks. */
- readonly backgroundTaskContext?: Record<string, unknown>;
- readonly backgroundTaskState?: DurableSessionState;
- readonly backgroundTasks?: StepResult["backgroundTasks"];
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}
@@ -62,7 +50,7 @@ export type DurableStepResult = (
readonly hasPendingAuthorization: boolean;
readonly hasPendingInputBatch: boolean;
readonly pendingCoordinationCallIds?: readonly string[];
- readonly settled?: ParkedSettledTurn;
+ readonly settled?: SettledTurn;
}
) &
DurableStepResultFields;
@@ -80,5 +68,5 @@ export type TurnOutcome =
readonly authorizationAttemptIds?: readonly string[];
readonly cancelled?: true;
readonly kind: "park";
- readonly settled?: ParkedSettledTurn;
+ readonly settled?: SettledTurn;
};
diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.ts
index 048ac45d5..3c6c011e9 100644
--- a/packages/eve/src/execution/session/turn-step.test.ts
+++ b/packages/eve/src/execution/session/turn-step.test.ts
@@ -7,18 +7,14 @@ import type {
SessionAuthContext,
SubagentInputRequestHookPayload,
} from "#channel/types.js";
-import { ContextContainer, contextStorage, loadContext } from "#context/container.js";
+import { ContextContainer, loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import {
- ActivityObserverKey,
- ActivityRootTurnIdKey,
AuthKey,
ChannelInstrumentationKey,
ContinuationHookTokensKey,
ContinuationTokenKey,
DynamicSubagentAgentConfigKey,
- ScheduleIdKey,
- SessionCallbackKey,
SessionDynamicSubagentRuntimeRevisionKey,
SessionDynamicModelReferenceKey,
SessionDynamicToolMetadataKey,
@@ -27,7 +23,6 @@ import {
SessionTraceSeedKey,
TurnDynamicToolMetadataKey,
TurnDeliveryIdsKey,
- TurnTaskDeliveryKey,
HistoryStateKey,
} from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
@@ -36,17 +31,14 @@ import { getPendingCoordinationBatch, setPendingCoordinationBatch } from "#harne
import { TurnCancelledError } from "#harness/turn-cancellation.js";
import { setHarnessEmissionState } from "#harness/emission-state.js";
import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";
-import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
+import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import { appendPendingInputBatch } from "#harness/input-requests.js";
import { queueDeferredStepInput } from "#harness/pending-input-batches.js";
import type { HarnessSession, StepFn, StepResult } from "#harness/types.js";
import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";
import {
- createActionsRequestedEvent,
createInputRequestedEvent,
- createMessageAppendedEvent,
createMessageCompletedEvent,
- createResultCompletedEvent,
createStepStartedEvent,
createTurnCompletedEvent,
createTurnStartedEvent,
@@ -67,8 +59,6 @@ import { defineState } from "#public/definitions/state.js";
import { stampDurableDynamicCallback } from "#tools/durable-callbacks.js";
import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";
-import { sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
-import { recordTaskInputRequestStep } from "#execution/tasks/parent/hitl-proxy-steps.js";
import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";
import { turnStep as runTurnStep } from "#execution/session/turn-step.js";
import type { TurnStepInput, TurnStepPayload } from "#execution/session/turn-step-types.js";
@@ -96,6 +86,8 @@ function turnStep(input: Omit<TurnStepInput, "input"> & { readonly input?: Legac
import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";
import { captureLogRecords } from "#internal/testing/log-records.js";
+const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };
+
// The harness runs outside a workflow body here, where run attributes cannot
// be written; the attribute contract is covered by emit.test.ts.
vi.mock("#runtime/attributes/emit.js", () => ({ setEveAttributes: vi.fn(async () => {}) }));
@@ -127,6 +119,10 @@ vi.mock("#instrumentation/runtime.js", async (importOriginal) => {
};
});
+vi.mock("#execution/tools/workflow/start.js", () => ({
+ startWorkflowTask: vi.fn(async ({ session }: { session: unknown }) => ({ session })),
+}));
+
vi.mock("../durable-session-store.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../durable-session-store.js")>();
return {
@@ -135,9 +131,6 @@ vi.mock("../durable-session-store.js", async (importOriginal) => {
readDurableSession: vi.fn(),
};
});
-vi.mock("../tasks/parent/run-parent.js", () => ({
- sendTaskInboundPayload: vi.fn(),
-}));
const mockIdentityHistoryViewProjector = vi.hoisted(() =>
vi.fn(({ messages }: { readonly messages: readonly ModelMessage[] }) => messages),
@@ -331,8 +324,6 @@ afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
vi.restoreAllMocks();
- vi.mocked(sendTaskInboundPayload).mockReset();
- vi.mocked(sendTaskInboundPayload).mockResolvedValue("delivered");
mockIdentityHistoryViewProjector.mockReset();
mockIdentityHistoryViewProjector.mockImplementation(({ messages }) => messages);
});
@@ -346,6 +337,7 @@ describe("routeProxiedDeliverStep", () => {
{
childContinuationToken: "stale-alias",
childSessionInbox: { sessionId: "original-child" },
+ event: REQUEST_EVENT,
kind: "question",
},
],
@@ -359,6 +351,7 @@ describe("routeProxiedDeliverStep", () => {
installSessionStoreMocks([session]);
await routeProxiedDeliverStep({
+ serializedContext: createSerializedContext(),
sessionWritable: createTestWritable(),
delivery: {
kind: "deliver",
@@ -378,6 +371,26 @@ describe("routeProxiedDeliverStep", () => {
payloads: [{ inputResponses: [{ requestId: "request-1", text: "yes" }] }],
}),
);
+ // The parent emitted the child's question, so it announces the answer too.
+ const writes = workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE) ?? [];
+ expect(
+ writes.map((chunk) => JSON.parse(new TextDecoder().decode(chunk as Uint8Array))),
+ ).toEqual([
+ expect.objectContaining({
+ data: {
+ ...REQUEST_EVENT,
+ resolutions: [
+ {
+ kind: "question",
+ outcome: "answered",
+ requestId: "request-1",
+ response: { requestId: "request-1", text: "yes" },
+ },
+ ],
+ },
+ type: "input.resolved",
+ }),
+ ]);
});
it("answers a root question once when one delivery carries several messages", async () => {
@@ -386,18 +399,20 @@ describe("routeProxiedDeliverStep", () => {
[
"ask-1",
{
- answerHook: { question: { allowFreeform: true, dismissible: true }, runId: "run-1" },
- childContinuationToken: "answer-token",
+ workflowAsk: { control: "control", question: { allowFreeform: true }, runId: "run-1" },
+ childContinuationToken: "ask-1",
+ event: REQUEST_EVENT,
kind: "question",
},
],
],
- forChildContinuationToken: "answer-token",
+ forChildContinuationToken: "ask-1",
session: createStubSession(),
});
installSessionStoreMocks([session]);
const result = await routeProxiedDeliverStep({
+ serializedContext: createSerializedContext(),
delivery: {
kind: "deliver",
payloads: [{ message: "Use the canary pool." }, { message: "Also check the logs." }],
@@ -407,10 +422,10 @@ describe("routeProxiedDeliverStep", () => {
});
expect(resumeHookMock).toHaveBeenCalledTimes(1);
- expect(resumeHookMock).toHaveBeenCalledWith("answer-token", {
- optionId: undefined,
- status: "answered",
- text: "Use the canary pool.",
+ expect(resumeHookMock).toHaveBeenCalledWith("control", {
+ kind: "answer",
+ requestId: "ask-1",
+ response: { optionId: undefined, status: "answered", text: "Use the canary pool." },
});
expect(result).toMatchObject({
kind: "continue",
@@ -437,20 +452,21 @@ describe("routeProxiedDeliverStep", () => {
[
"ask-1",
{
- answerHook: {
+ workflowAsk: {
+ control: "control",
question: {
allowFreeform: false,
- dismissible: false,
options: [{ id: "approve", label: "Approve" }],
},
runId: "run-1",
},
- childContinuationToken: "answer-token",
+ childContinuationToken: "ask-1",
+ event: REQUEST_EVENT,
kind: "question",
},
],
],
- forChildContinuationToken: "answer-token",
+ forChildContinuationToken: "ask-1",
session: createStubSession(),
});
installSessionStoreMocks([session]);
@@ -478,8 +494,14 @@ describe("routeProxiedDeliverStep", () => {
};
const session = upsertProxyInputRequests({
entries: [
- ["request-1", { childContinuationToken: "child-token", kind: "tool-approval" }],
- ["request-2", { childContinuationToken: "child-token", kind: "tool-approval" }],
+ [
+ "request-1",
+ { childContinuationToken: "child-token", event: REQUEST_EVENT, kind: "tool-approval" },
+ ],
+ [
+ "request-2",
+ { childContinuationToken: "child-token", event: REQUEST_EVENT, kind: "tool-approval" },
+ ],
],
forChildContinuationToken: "child-token",
session: createStubSession({
@@ -490,6 +512,7 @@ describe("routeProxiedDeliverStep", () => {
installSessionStoreMocks([session]);
const result = await routeProxiedDeliverStep({
+ serializedContext: createSerializedContext(),
sessionWritable: createTestWritable(),
delivery: {
kind: "deliver",
@@ -530,12 +553,23 @@ describe("routeProxiedDeliverStep", () => {
};
const session = upsertProxyInputRequests({
entries: [
- ["child-a", { childContinuationToken: "child-token-a", kind: "question" }],
- ["child-b", { childContinuationToken: "child-token-b", kind: "question" }],
+ [
+ "child-a",
+ { childContinuationToken: "child-token-a", event: REQUEST_EVENT, kind: "question" },
+ ],
+ [
+ "child-b",
+ { childContinuationToken: "child-token-b", event: REQUEST_EVENT, kind: "question" },
+ ],
],
forChildContinuationToken: "child-token-a",
session: upsertProxyInputRequests({
- entries: [["child-b", { childContinuationToken: "child-token-b", kind: "question" }]],
+ entries: [
+ [
+ "child-b",
+ { childContinuationToken: "child-token-b", event: REQUEST_EVENT, kind: "question" },
+ ],
+ ],
forChildContinuationToken: "child-token-b",
session: createStubSession(),
}),
@@ -567,6 +601,7 @@ describe("routeProxiedDeliverStep", () => {
};
const result = await routeProxiedDeliverStep({
+ serializedContext: createSerializedContext(),
delivery,
sessionWritable: createTestWritable(),
sessionState: createStubSessionState({ hasProxyInputRequests: true }),
@@ -610,166 +645,6 @@ describe("routeProxiedDeliverStep", () => {
},
});
});
-
- 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,
- childRequestId: "request-1",
- ...(options?.childResponseUrl === undefined
- ? {}
- : { childResponseUrl: options.childResponseUrl }),
- kind: "tool-approval",
- taskId: "task-1",
- },
- ],
- ],
- forChildContinuationToken: childContinuationToken,
- session: createStubSession({
- continuationToken: "parent-token",
- sessionId: "parent-session",
- state:
- options?.owned === false
- ? undefined
- : {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task-1",
- toolName: "research",
- lifetime: "session" as const,
- origin: { turnId: "turn-parent", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "tool", name: "research" },
- taskId: "task-1",
- },
- },
- ],
- },
- },
- }),
- });
- }
-
- const taskRouteInput = {
- delivery: {
- kind: "deliver" as const,
- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }] }],
- },
- sessionState: createStubSessionState({ hasProxyInputRequests: true }),
- };
-
- it("hands a task-owned answer to its task controller", async () => {
- installSessionStoreMocks([createTaskRouteSession()]);
-
- const result = await routeProxiedDeliverStep({
- ...taskRouteInput,
- sessionWritable: createTestWritable(),
- });
- expect(result).toMatchObject({ kind: "continue", remainder: undefined });
- expect(sendTaskInboundPayload).toHaveBeenCalledWith({
- payload: {
- auth: undefined,
- childContinuationToken: "child-token",
- childResponseUrl: undefined,
- inputResponses: [{ optionId: "approve", requestId: "request-1" }],
- kind: "input-response",
- taskId: "task-1",
- },
- taskInboxToken: "task-token",
- });
- 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, sessionWritable: 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, sessionWritable: 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 })]);
-
- await expect(
- routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() }),
- ).resolves.toMatchObject({
- kind: "continue",
- remainder: {
- kind: "deliver",
- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }] }],
- },
- });
- expect(resumeHookMock).not.toHaveBeenCalled();
- });
-
- it("returns answers to the parent when the task run already finished", async () => {
- installSessionStoreMocks([createTaskRouteSession()]);
- vi.mocked(sendTaskInboundPayload).mockResolvedValueOnce("unreachable");
-
- await expect(
- routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() }),
- ).resolves.toMatchObject({
- kind: "continue",
- remainder: {
- kind: "deliver",
- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }] }],
- },
- });
- });
-
- it("keeps a task answer retryable after delivery fails", async () => {
- const session = createTaskRouteSession();
- installSessionStoreMocks([session, session]);
- vi.mocked(sendTaskInboundPayload)
- .mockRejectedValueOnce(new Error("transient"))
- .mockResolvedValueOnce("delivered");
-
- await expect(
- routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() }),
- ).rejects.toThrow("transient");
- await expect(
- routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() }),
- ).resolves.toMatchObject({ kind: "continue", remainder: undefined });
- expect(sendTaskInboundPayload).toHaveBeenCalledTimes(2);
- });
});
function currentSessionHook(token: string) {
@@ -780,79 +655,6 @@ function currentSessionHook(token: string) {
};
}
-describe("recordTaskInputRequestStep", () => {
- 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",
- },
- 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: {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task-1",
- toolName: "research",
- lifetime: "session" as const,
- origin: { turnId: "turn-parent", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "tool", name: "research" },
- taskId: "task-1",
- },
- },
- ],
- },
- },
- });
- installSessionStoreMocks([session]);
-
- const result = await recordTaskInputRequestStep({
- request: taskRequest,
- sessionState: createStubSessionState(),
- });
-
- expect(result.accepted).toBe(true);
- expect(
- getProxyInputRequests(result.sessionState.snapshot.session.state).get("task-1:request-1"),
- ).toEqual({
- childContinuationToken: "eve:workflow-tool-run-answer:run-1:0",
- childRequestId: "request-1",
- kind: "question",
- question: {},
- taskId: "task-1",
- });
- expect(result).toMatchObject({
- accepted: true,
- request: { request: { requestId: "task-1:request-1" } },
- });
- });
-
- it("rejects cross-session and stale batches without recording a route", async () => {
- const session = createStubSession();
- installSessionStoreMocks([session, session]);
-
- const result = await recordTaskInputRequestStep({
- request: { ...taskRequest, taskId: "foreign-task" },
- sessionState: createStubSessionState(),
- });
-
- expect(result).toEqual({ accepted: false, sessionState: createStubSessionState() });
- });
-});
-
describe("dispatchCoordinationStep", () => {
it("repairs an empty pending turn id from the active session turn", async () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
@@ -871,15 +673,16 @@ describe("dispatchCoordinationStep", () => {
turnAgent: TestTurnAgent,
} as never);
const session = setPendingCoordinationBatch({
- runtimeActions: [
+ tasks: [
{
callId: "call-1",
+ executeInput: {},
input: {},
- kind: "tool-call",
- toolName: "task_cancel",
+ kind: "workflow-task",
+ toolName: "research",
+ workflowId: "workflow//eve//research",
},
],
- tasks: [],
event: { sequence: 3, stepIndex: 2, turnId: "" },
responseMessages: [],
session: createStubSession(),
@@ -901,208 +704,6 @@ describe("dispatchCoordinationStep", () => {
expect(result.sessionState).not.toBe(sessionState);
expect(getPendingCoordinationBatch(persisted?.state)?.event.turnId).toBe("turn_3");
});
-
- 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 },
- },
- hookRegistry: createRuntimeHookRegistry([]),
- resolvedAgent: { config: {} },
- subagentRegistry: {
- subagentsByNodeId: new Map([
- ["subagents/agent", { definition: { kind: "subagent", name: "agent" } }],
- ]),
- },
- toolRegistry: {},
- turnAgent: TestTurnAgent,
- } as never);
- const session = setPendingCoordinationBatch({
- runtimeActions: [
- {
- callId: "call-1",
- description: "Runtime action event description.",
- input: { message: "investigate latest routing" },
- 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",
- }),
- });
- installSessionStoreMocks([session]);
-
- const sessionState = createStubSessionState({
- continuationToken: "http:parent",
- sessionId: "parent-session",
- });
- startMock.mockResolvedValue({ runId: "child-run" });
-
- await expect(
- dispatchCoordinationStep({
- action: "park",
- workflowToolRunOwner: { inbox: "generated-owner-token" },
- sessionWritable: 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 () => {
- const compiledBundle = {
- adapterRegistry: {
- adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
- },
- compiledArtifactsSource: {},
- graph: {
- nodesByNodeId: new Map(),
- root: {
- sandboxRegistry: { sandbox: null },
- turnAgent: TestTurnAgent,
- },
- },
- hookRegistry: createRuntimeHookRegistry([]),
- resolvedAgent: { config: {} },
- subagentRegistry: {
- subagentsByNodeId: new Map(),
- },
- toolRegistry: {},
- turnAgent: TestTurnAgent,
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
-
- const session = setPendingCoordinationBatch({
- runtimeActions: [
- {
- callId: "call-1",
- description: "Delegate the work.",
- input: { message: "try to recurse" },
- 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",
- }),
- });
- installSessionStoreMocks([session]);
-
- const sessionState = createStubSessionState({
- continuationToken: "http:parent",
- sessionId: "parent-session",
- });
-
- await expect(
- dispatchCoordinationStep({
- action: "park",
- workflowToolRunOwner: { inbox: "generated-owner-token" },
- sessionWritable: createTestWritable(),
- serializedContext: createSerializedContext(),
- sessionState,
- }),
- ).rejects.toThrow('Unsupported coordination request "subagent-call".');
- expect(startMock).not.toHaveBeenCalled();
- expect(warn).not.toHaveBeenCalled();
- expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE)).toBeUndefined();
- });
-
- it("blocks a dynamic subagent call when the current selection omits it", async () => {
- const nodeId = "subagents/researcher";
- const compiledBundle = {
- adapterRegistry: {
- adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
- },
- compiledArtifactsSource: {},
- graph: {
- nodesByNodeId: new Map(),
- root: {
- sandboxRegistry: { sandbox: null },
- turnAgent: TestTurnAgent,
- },
- },
- hookRegistry: createRuntimeHookRegistry([]),
- resolvedAgent: { config: {} },
- subagentRegistry: {
- dynamicNodeIds: new Set([nodeId]),
- dynamicResolvers: [],
- subagentsByNodeId: new Map([
- [
- nodeId,
- {
- definition: {
- description: "Research the request.",
- kind: "subagent",
- },
- },
- ],
- ]),
- },
- toolRegistry: {},
- turnAgent: TestTurnAgent,
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- vi.spyOn(console, "warn").mockImplementation(() => {});
-
- const session = setPendingCoordinationBatch({
- runtimeActions: [
- {
- callId: "call-dynamic",
- description: "Research the request.",
- input: { message: "investigate" },
- kind: "subagent-call",
- name: "researcher",
- nodeId,
- subagentName: "researcher",
- } as never,
- ],
- tasks: [],
- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
- responseMessages: [],
- session: createStubSession({
- continuationToken: "http:parent",
- sessionId: "parent-session",
- }),
- });
- installSessionStoreMocks([session]);
- const sessionState = createStubSessionState({
- continuationToken: "http:parent",
- sessionId: "parent-session",
- });
-
- await expect(
- dispatchCoordinationStep({
- action: "park",
- workflowToolRunOwner: { inbox: "generated-owner-token" },
- sessionWritable: createTestWritable(),
- serializedContext: createSerializedContext(),
- sessionState,
- }),
- ).rejects.toThrow('Unsupported coordination request "subagent-call".');
- expect(startMock).not.toHaveBeenCalled();
- });
});
describe("turnStep", () => {
@@ -1141,227 +742,40 @@ describe("turnStep", () => {
expect(loadContext().get(ChannelKey)?.state).toEqual({ reply: { recipient: "alice" } });
return { next: { done: true, output: "Original answer" }, session: current };
});
- vi.mocked(createExecutionNodeStep).mockImplementation(() => execute);
- const ctx = new ContextContainer();
- ctx.set(AuthKey, originalAuth);
- ctx.set(TurnDeliveryIdsKey, ["original-delivery"]);
- ctx.set(BundleKey, bundle);
- ctx.set(ChannelKey, adapter);
- ctx.set(ContinuationTokenKey, "ignore-correction");
- ctx.set(SessionIdKey, "sess-test");
-
- const result = await turnStep({
- input: {
- auth: correctionAuth,
- kind: "deliver",
- payloads: [{ message: "Ignored correction" }],
- deliveryMetadata: [
- {
- channelKind: adapter.kind,
- channelName: adapter.kind,
- deliveryId: "ignored-delivery",
- payloadIndex: 0,
- },
- ],
- },
- sessionWritable: createTestWritable(),
- serializedContext: serializeContext(ctx),
- sessionState: createStubSessionState({ emissionState }),
- });
- expect(result).toMatchObject({ action: "done", output: "Original answer" });
- expect(execute).toHaveBeenCalledOnce();
- expect(execute.mock.calls[0]?.[0].history).toEqual(session.history);
- expect(result.sessionState.emissionState.turnId).toBe("turn_0");
- expect(result.serializedContext[AuthKey.name]).toEqual(originalAuth);
- expect(result.serializedContext[TurnDeliveryIdsKey.name]).toEqual(["original-delivery"]);
- });
- it("keeps one task stream open while hiding a scheduled fallback from delivery hooks", async () => {
- const appended: string[] = [];
- const delivered: Array<string | null> = [];
- const hookEvents: string[] = [];
- const adapter: ChannelAdapter = {
- kind: "scheduled-output-capture",
- "message.appended"(data) {
- appended.push(data.messageDelta);
- },
- "message.completed"(data) {
- delivered.push(data.message);
- },
- };
- const bundle = Object.assign({}, createTurnStepTestBundle() as object, {
- adapterRegistry: { adaptersByKind: new Map([[adapter.kind, adapter]]) },
- hookRegistry: createRuntimeHookRegistry([
- {
- events: {
- "*": async (event: UnstampedMessageStreamEvent) => {
- hookEvents.push(JSON.stringify(event));
- },
- },
- logicalPath: "hooks/audit.ts",
- slug: "audit",
- sourceId: "hooks/audit.ts",
- sourceKind: "module",
- } as never,
- ]),
- }) as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(bundle);
-
- const task = {
- callId: "task_report",
- toolName: "daily_report",
- lifetime: "session" as const,
- origin: { turnId: "turn_0", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "report", name: "daily_report" },
- taskId: "task_report",
- },
- };
- const emissionState = {
- sequence: 0,
- sessionStarted: true,
- stepIndex: 0,
- turnId: "turn_0",
- };
- const pending = createStubSession({
- state: {
- "eve.harness.emission": emissionState,
- "eve.workflowTool": { version: 3, runs: [task] },
- },
- });
- const outcome = {
- lastOutput: { data: "report complete", type: "result" as const },
- status: "completed" as const,
- };
- const settled = createStubSession({
- state: {
- "eve.harness.emission": { ...emissionState, sequence: 1, turnId: "turn_1" },
- "eve.workflowTool": {
- version: 3,
- runs: [{ ...task, task: { ...task.task, outcome } }],
- },
- },
- });
- installSessionStoreMocks([pending, settled]);
-
- let modelTurn = 0;
- vi.mocked(createExecutionNodeStep).mockImplementation((input) => {
- return async (session): Promise<StepResult> => {
- const message = modelTurn++ === 0 ? "Premature fallback" : "Final report";
- await input.handleEvent?.(
- createMessageAppendedEvent({
- messageDelta: message,
- sequence: modelTurn - 1,
- stepIndex: 0,
- turnId: `turn_${String(modelTurn - 1)}`,
- }),
- session.history,
- );
- await input.handleEvent?.(
- createMessageCompletedEvent({
- message,
- sequence: modelTurn - 1,
- stepIndex: 0,
- turnId: `turn_${String(modelTurn - 1)}`,
- }),
- session.history,
- );
- await input.handleEvent?.(
- createResultCompletedEvent({
- result: { report: message },
- sequence: modelTurn - 1,
- stepIndex: 0,
- turnId: `turn_${String(modelTurn - 1)}`,
- }),
- session.history,
- );
- return modelTurn === 1
- ? {
- next: null,
- session,
- settledTurn: { output: { report: message } },
- }
- : { next: { done: true, output: { report: message } }, session };
- };
- });
-
+ vi.mocked(createExecutionNodeStep).mockImplementation(() => execute);
const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
+ ctx.set(AuthKey, originalAuth);
+ ctx.set(TurnDeliveryIdsKey, ["original-delivery"]);
ctx.set(BundleKey, bundle);
ctx.set(ChannelKey, adapter);
- ctx.set(ContinuationTokenKey, "http:scheduled-output-capture");
- ctx.set(ScheduleIdKey, "daily-report");
- ctx.set(SessionIdKey, "session-1");
- const serializedContext = serializeContext(ctx);
- const writable = createTestWritable("scheduled-task");
+ ctx.set(ContinuationTokenKey, "ignore-correction");
+ ctx.set(SessionIdKey, "sess-test");
- const launch = await turnStep({
+ const result = await turnStep({
input: {
+ auth: correctionAuth,
kind: "deliver",
- payloads: [
+ payloads: [{ message: "Ignored correction" }],
+ deliveryMetadata: [
{
- message: "Run the daily report",
- outputSchema: {
- properties: { report: { type: "string" } },
- required: ["report"],
- type: "object",
- },
+ channelKind: adapter.kind,
+ channelName: adapter.kind,
+ deliveryId: "ignored-delivery",
+ payloadIndex: 0,
},
],
},
- sessionWritable: writable,
- serializedContext,
+ sessionWritable: createTestWritable(),
+ serializedContext: serializeContext(ctx),
sessionState: createStubSessionState({ emissionState }),
});
- expect(appended).toEqual([]);
- expect(delivered).toEqual([null]);
- const launchEvents = (workflowWritesByNamespace.get("scheduled-task") ?? []).map((chunk) =>
- JSON.parse(new TextDecoder().decode(chunk as Uint8Array)),
- );
- expect(launchEvents).toEqual([
- expect.objectContaining({
- data: expect.objectContaining({ message: null }),
- type: "message.completed",
- }),
- ]);
- expect(JSON.stringify(launchEvents)).not.toContain("Premature fallback");
- expect(hookEvents.join("\n")).not.toContain("Premature fallback");
-
- await turnStep({
- input: {
- kind: "deliver",
- payloads: [{ message: "Background task task_report is completed." }],
- taskDeliveryId: "task_report:ready:completed",
- },
- sessionWritable: writable,
- serializedContext: launch.serializedContext,
- sessionState: launch.sessionState,
- });
-
- expect(appended).toEqual(["Final report"]);
- expect(delivered).toEqual([null, "Final report"]);
- const settledEvents = (workflowWritesByNamespace.get("scheduled-task") ?? []).map((chunk) =>
- JSON.parse(new TextDecoder().decode(chunk as Uint8Array)),
- );
- expect(settledEvents.filter((event) => event.type === "message.completed")).toEqual([
- expect.objectContaining({
- data: expect.objectContaining({ message: null }),
- type: "message.completed",
- }),
- expect.objectContaining({
- data: expect.objectContaining({ message: "Final report" }),
- type: "message.completed",
- }),
- ]);
- expect(settledEvents.filter((event) => event.type === "result.completed")).toEqual([
- expect.objectContaining({
- data: expect.objectContaining({ result: { report: "Final report" } }),
- type: "result.completed",
- }),
- ]);
+ expect(result).toMatchObject({ action: "done", output: "Original answer" });
+ expect(execute).toHaveBeenCalledOnce();
+ expect(execute.mock.calls[0]?.[0].history).toEqual(session.history);
+ expect(result.sessionState.emissionState.turnId).toBe("turn_0");
+ expect(result.serializedContext[AuthKey.name]).toEqual(originalAuth);
+ expect(result.serializedContext[TurnDeliveryIdsKey.name]).toEqual(["original-delivery"]);
});
-
it("runs the configured number of model calls inside one Workflow step", async () => {
const bundle = createTurnStepTestBundle(3);
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(bundle);
@@ -1523,35 +937,6 @@ describe("turnStep", () => {
expect(execute).toHaveBeenCalledOnce();
});
- it("checkpoints before persisting a background-task state transition", async () => {
- const bundle = createTurnStepTestBundle(3);
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(bundle);
- const session = createStubSession();
- installSessionStoreMocks([session]);
-
- const continueStep: StepFn = async (current) => ({ next: null, session: current });
- const execute = vi.fn(async (current: HarnessSession): Promise<StepResult> => ({
- backgroundTasks: [],
- backgroundTaskSession: current,
- next: continueStep,
- session: current,
- }));
- vi.mocked(createExecutionNodeStep).mockImplementation(() => execute);
-
- const result = await turnStep({
- input: { kind: "deliver", payloads: [{ message: "delegate" }] },
- sessionWritable: createTestWritable(),
- serializedContext: createSerializedContext(),
- sessionState: createStubSessionState(),
- });
-
- expect(result).toMatchObject({
- action: "continue",
- backgroundTasks: [],
- });
- expect(execute).toHaveBeenCalledOnce();
- });
-
it("retains coalesced delivery ownership when a message steers the active turn", async () => {
const session = createStubSession({
state: {
@@ -2000,145 +1385,6 @@ describe("turnStep", () => {
expect(observed).toEqual(expected);
});
- it("projects inherited task tool activity while routing HITL only to the parent callback", async () => {
- const inputRequested = vi.fn();
- const remoteTaskAdapter: ChannelAdapter = {
- kind: "remote-task-test",
- "input.requested": inputRequested,
- };
- const compiledBundle = {
- adapterRegistry: {
- adaptersByKind: new Map([[remoteTaskAdapter.kind, remoteTaskAdapter]]),
- },
- compiledArtifactsSource: {} as never,
- graph: {
- nodesByNodeId: new Map(),
- root: {
- sandboxRegistry: { sandbox: null },
- turnAgent: TestTurnAgent,
- },
- },
- moduleMap: { nodes: {} },
- hookRegistry: createRuntimeHookRegistry([]),
- resolvedAgent: {
- config: {},
- },
- subagentRegistry: {},
- toolRegistry: {},
- turnAgent: TestTurnAgent,
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- const session = createStubSession();
- installSessionStoreMocks([session]);
- vi.mocked(createExecutionNodeStep).mockImplementation((input) => {
- return async (stepSession): Promise<StepResult> => {
- await input.handleEvent?.(
- createActionsRequestedEvent({
- actions: [
- {
- callId: "tool-call-1",
- input: { query: "activity" },
- kind: "tool-call",
- toolName: "search_slack",
- },
- ],
- sequence: 1,
- stepIndex: 2,
- turnId: "turn-child",
- }),
- );
- await input.handleEvent?.(
- createInputRequestedEvent({
- requests: [
- {
- action: {
- callId: "tool-call-1",
- input: {},
- kind: "tool-call",
- toolName: "dangerous_tool",
- },
- kind: "tool-approval",
- options: [
- { id: "approve", label: "Approve" },
- { id: "cancel", label: "Cancel" },
- ],
- prompt: "Approve?",
- requestId: "request-1",
- },
- ],
- sequence: 1,
- stepIndex: 2,
- turnId: "turn-child",
- }),
- );
- return { next: null, session: stepSession };
- };
- });
- const activityRequest = new Promise<Response>(() => {});
- const fetchMock = vi.fn((url: string) =>
- url.includes("/activity/")
- ? activityRequest
- : Promise.resolve(new Response(null, { status: 202 })),
- );
- vi.stubGlobal("fetch", fetchMock);
-
- const ctx = new ContextContainer();
- ctx.set(ActivityObserverKey, {
- sink: {
- url: "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- workIdentity: {
- callId: "parent-call",
- id: "work:child",
- kind: "task",
- name: "remote-worker",
- rootSessionId: "root",
- rootTurnId: "turn-root",
- },
- });
- ctx.set(AuthKey, null);
- ctx.set(BundleKey, compiledBundle);
- ctx.set(ChannelKey, remoteTaskAdapter);
- ctx.set(ContinuationTokenKey, "child-token");
- ctx.set(SessionCallbackKey, {
- callId: "parent-call",
- subagentName: "remote-worker",
- taskId: "task_abc",
- token: "task-token",
- url: "https://parent.example/eve/v1/callback/task-token",
- });
- ctx.set(SessionIdKey, "child-session");
-
- await turnStep({
- input: { kind: "deliver", payloads: [{ message: "run the task" }] },
- sessionWritable: createTestWritable(),
- serializedContext: serializeContext(ctx),
- sessionState: createStubSessionState(),
- });
-
- expect(fetchMock).toHaveBeenCalledWith(
- "https://parent.example/eve/v1/callback/task-token",
- expect.objectContaining({
- body: expect.stringContaining('"kind":"task.input-requested"'),
- }),
- );
- expect(inputRequested).not.toHaveBeenCalled();
- expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE) ?? []).toHaveLength(1);
- expect(fetchMock).toHaveBeenCalledWith(
- "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- expect.objectContaining({
- body: expect.stringContaining(
- '"action":{"id":"action:work:child:tool-call-1","kind":"tool","name":"search_slack","parentWorkId":"work:child","rootTurnId":"turn-root"',
- ),
- }),
- );
- expect(fetchMock).toHaveBeenCalledWith(
- "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- expect.objectContaining({ body: expect.stringContaining('"kind":"blocker.started"') }),
- );
- });
-
it("keeps a session-scoped dynamic model selection when the first turn is cancelled", async () => {
const announcement = "Available skills\n- policy: Tenant policy";
const session = createStubSession({
@@ -2453,7 +1699,7 @@ describe("turnStep", () => {
await turnStep({
input: {
kind: "deliver",
- payloads: [{ message: "check background work" }],
+ payloads: [{ message: "check the work" }],
},
sessionWritable: createTestWritable(),
serializedContext: createSerializedContext(),
@@ -2489,7 +1735,7 @@ describe("turnStep", () => {
expect(result).toMatchObject({
action: "park",
- settled: { notifyCaller: true, output: "settled answer" },
+ settled: { output: "settled answer" },
});
});
@@ -2521,7 +1767,7 @@ describe("turnStep", () => {
expect(result).toMatchObject({
action: "park",
- settled: { notifyCaller: true, output: "settled answer" },
+ settled: { output: "settled answer" },
});
});
@@ -2712,7 +1958,6 @@ describe("turnStep", () => {
expect(first).toMatchObject({
action: "park",
settled: {
- notifyCaller: true,
output: "first answer",
usage: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 100, outputTokens: 40 },
},
@@ -2746,7 +1991,6 @@ describe("turnStep", () => {
expect(second).toMatchObject({
action: "park",
settled: {
- notifyCaller: true,
output: "second answer",
usage: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 50, outputTokens: 20 },
},
@@ -2793,7 +2037,7 @@ describe("turnStep", () => {
expect(result).toMatchObject({
action: "park",
hasPendingInputBatch: true,
- settled: { notifyCaller: true, output: "settled while approval remains open" },
+ settled: { output: "settled while approval remains open" },
});
});
@@ -2839,24 +2083,6 @@ describe("turnStep", () => {
session,
}),
},
- {
- name: "runtime action",
- withPending: (session: HarnessSession): HarnessSession =>
- setPendingCoordinationBatch({
- runtimeActions: [
- {
- callId: "call-runtime",
- input: {},
- kind: "tool-call",
- toolName: "runtime-tool",
- },
- ],
- tasks: [],
- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
- responseMessages: [],
- session,
- }),
- },
])("does not infer settled output from a pending $name", async ({ withPending }) => {
const session = createStubSession();
installSessionStoreMocks([session]);
@@ -2916,243 +2142,6 @@ describe("turnStep", () => {
});
});
- it.each([
- [undefined, undefined, "auto"],
- ["cohort", undefined, "cohort"],
- ["auto", undefined, "auto"],
- [undefined, "cohort", "cohort"],
- ["auto", "cohort", "cohort"],
- ["cohort", "cohort", "cohort"],
- [undefined, "auto", "auto"],
- ["auto", "auto", "auto"],
- ["cohort", "auto", "auto"],
- ] as const)(
- "updates stored policy %s from explicit send policy %s to %s",
- async (storedPolicy, sendPolicy, expected) => {
- const metadata = { kind: "report-probe", name: "report_probe" };
- const session = createStubSession({
- state: {
- "eve.workflowTool": {
- version: 3,
- runs: ["A", "B"].map((taskId) => ({
- callId: taskId,
- toolName: metadata.name,
- lifetime: "session",
- origin: { turnId: "turn-parent", stepIndex: 0 },
- address: { runId: `run-${taskId}`, hookToken: `inbox-${taskId}` },
- task: {
- taskId,
- cohortId: "A",
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata,
- ...(taskId === "A"
- ? {
- outcome: {
- status: "completed",
- lastOutput: { type: "result", data: "Report A" },
- },
- }
- : {}),
- },
- })),
- },
- },
- });
- installSessionStoreMocks([session]);
- const phases: unknown[] = [];
- vi.mocked(createExecutionNodeStep).mockImplementation(() => async (session) => {
- phases.push(contextStorage.getStore()?.get(TurnTaskDeliveryKey));
- return { next: { done: true, output: "ok" }, session };
- });
- const serializedContext = createSerializedContext();
- if (storedPolicy !== undefined) {
- serializedContext["eve.runtime.taskDeliveryPolicy"] = storedPolicy;
- }
- const result = await turnStep({
- input: {
- kind: "deliver",
- taskDeliveryPolicy: sendPolicy,
- taskDeliveryId: "A:ready:completed",
- payloads: [{ message: "A completed." }],
- },
- sessionWritable: createTestWritable(),
- serializedContext,
- sessionState: createStubSessionState(),
- });
- expect(result.serializedContext["eve.runtime.taskDeliveryPolicy"]).toBe(expected);
- expect(phases).toEqual(["pending"]);
- },
- );
-
- it("marks task-owned deliveries even when task state is unavailable", async () => {
- const observedInputs: unknown[] = [];
- const observedTaskDeliveries: unknown[] = [];
- const observedActivityRoots: unknown[] = [];
- const metadata = { kind: "report-probe", name: "report_probe" } as const;
- const session = createStubSession({
- state: {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task_1",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-parent", stepIndex: 0 },
- address: { runId: "run_1", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata,
- taskId: "task_1",
- outcome: {
- lastOutput: { data: { result: "done" }, type: "result" },
- status: "completed",
- },
- },
- },
- ],
- },
- },
- });
- installSessionStoreMocks([session, session, session]);
- vi.mocked(createExecutionNodeStep).mockImplementation(() => {
- return async (stepSession, stepInput): Promise<StepResult> => {
- observedInputs.push(stepInput);
- observedTaskDeliveries.push(contextStorage.getStore()?.get(TurnTaskDeliveryKey));
- observedActivityRoots.push(contextStorage.getStore()?.get(ActivityRootTurnIdKey));
- return { next: { done: true, output: "ok" }, session: stepSession };
- };
- });
-
- const initialSerializedContext = createSerializedContext();
- initialSerializedContext[ActivityObserverKey.name] = {
- sink: {
- url: "https://agent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz",
- version: 1,
- },
- };
-
- const first = await turnStep({
- input: {
- kind: "deliver",
- payloads: [{ message: "Background task task_1 is completed." }],
- taskDeliveryId: "task_1:ready:completed",
- },
- sessionWritable: createTestWritable(),
- serializedContext: initialSerializedContext,
- sessionState: createStubSessionState(),
- });
- const second = await turnStep({
- input: {
- kind: "deliver",
- payloads: [{ message: "Background task task_unknown is completed." }],
- taskDeliveryId: "task_unknown:ready:completed",
- },
- sessionWritable: createTestWritable(),
- serializedContext: first.serializedContext,
- sessionState: first.sessionState,
- });
- await turnStep({
- input: { kind: "deliver", payloads: [{ message: "What happened?" }] },
- sessionWritable: createTestWritable(),
- serializedContext: second.serializedContext,
- sessionState: second.sessionState,
- });
-
- expect(observedTaskDeliveries).toEqual(["settled", "none", "none"]);
- expect(observedActivityRoots).toEqual(["turn-parent", "turn-parent", "turn_0"]);
- expect(observedInputs[0]).toMatchObject({
- frameworkMessageKind: "execution.background_task",
- });
- expect(observedInputs[1]).toMatchObject({
- frameworkMessageKind: "execution.background_task",
- });
- expect(observedInputs[2]).not.toHaveProperty("frameworkMessageKind");
- });
-
- it.each(["none", "initiating"] as const)("sets initiating task phase (%s)", async (phase) => {
- 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: createRuntimeHookRegistry([]),
- resolvedAgent: {
- config: {},
- },
- subagentRegistry: {},
- toolRegistry: {},
- turnAgent: TestTurnAgent,
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(tasksBundle);
-
- const session = createStubSession({
- state: {
- "eve.harness.emission": {
- sequence: 0,
- sessionStarted: true,
- stepIndex: 1,
- turnId: "turn_0",
- },
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task_1",
- toolName: "report_probe",
- lifetime: "session" as const,
- origin: { turnId: "turn_0", stepIndex: 0 },
- address: { runId: "run_1", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "report-probe", name: "report_probe" },
- taskId: "task_1",
- },
- },
- ],
- },
- },
- });
- installSessionStoreMocks([session]);
-
- let observedInput: unknown;
- let observedPhase: unknown;
- vi.mocked(createExecutionNodeStep).mockImplementation(() => {
- return async (stepSession, stepInput): Promise<StepResult> => {
- observedInput = stepInput;
- observedPhase = contextStorage.getStore()?.get(TurnTaskDeliveryKey);
- return { next: { done: true, output: "ok" }, session: stepSession };
- };
- });
- const serializedContext = createSerializedContext();
- serializedContext[TurnTaskDeliveryKey.name] = phase;
-
- await turnStep({
- input: undefined,
- sessionWritable: createTestWritable(),
- serializedContext,
- sessionState: createStubSessionState({
- emissionState: {
- sequence: 0,
- sessionStarted: true,
- stepIndex: 1,
- turnId: "turn_0",
- },
- }),
- });
-
- expect(observedPhase).toBe("initiating");
- expect(observedInput).toBeUndefined();
- });
-
it("persists onDeliver context into the next durable step", async () => {
const seenMessages: string[] = [];
const session = createStubSession();
@@ -4102,11 +3091,10 @@ describe("runProxySubagentEventStep", () => {
// The step writes the outgoing `input.requested` event to the
// durable stream so channel-side UI (Slack Block Kit buttons,
- // HTTP stream consumers) sees the prompt, then follows it with a
- // `turn.completed` + `session.waiting` boundary pair so clients
- // stop draining the stream and prompt the user for HITL input.
+ // HTTP stream consumers) sees the prompt, then follows it with
+ // `turn.waiting`, where clients stop and prompt the user for HITL input.
const writes = workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE) ?? [];
- expect(writes).toHaveLength(3);
+ expect(writes).toHaveLength(2);
});
it("returns every continuation address claimed by the input.requested handler", async () => {
diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.ts
index 605a769f7..8086c05b1 100644
--- a/packages/eve/src/execution/session/turn-step.ts
+++ b/packages/eve/src/execution/session/turn-step.ts
@@ -3,6 +3,7 @@ import { deriveSessionTitle } from "#execution/eve-workflow-attributes.js";
import { setEveAttributes } from "#runtime/attributes/emit.js";
import { defaultDeliverResult } from "#channel/adapter.js";
import { contextStorage } from "#context/container.js";
+import { runStep } from "#context/run-step.js";
import {
drainDynamicInstructionUserMessages,
prepareDynamicInstructionPreamble,
@@ -24,8 +25,6 @@ import {
SessionDynamicSubagentRuntimeRevisionKey,
SessionDynamicToolRuntimeRevisionKey,
StaticModelReferenceKey,
- TurnTaskDeliveryKey,
- TaskDeliveryPolicyKey,
TurnDeliveryIdsKey,
} from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
@@ -53,7 +52,7 @@ import { consumeDeferredStepInput } from "#harness/pending-input-batches.js";
import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";
import type { DurableStepResult, TurnStepInput } from "#execution/session/turn-step-types.js";
import { resolveSessionStepResult } from "#execution/session/turn-step-result.js";
-import { createSessionEventSink } from "#execution/session/event-sink.js";
+import { createSessionEventSink } from "#execution/publish-session-events.js";
import { createTurnEventHandler } from "#execution/session/turn-event-handler.js";
import { derivePendingState } from "#execution/session/pending-turn-state.js";
import {
@@ -70,16 +69,6 @@ import {
import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";
-import {
- getBackgroundTaskDelivery,
- markBackgroundTaskStepInput,
- resolveInitiatingTaskContext,
- resolveTaskDeliveryContext,
-} from "#tasks/delivery-context.js";
-import {
- readRetainedBackgroundToolResult,
- runBackgroundStep,
-} from "#execution/tasks/parent/tool-execution.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";
@@ -121,9 +110,6 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
const adapter = ctx.require(ChannelKey);
const bundle = ctx.require(BundleKey);
const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
- const taskDeliveryPolicy =
- rawDelivery?.taskDeliveryPolicy ?? ctx.get(TaskDeliveryPolicyKey) ?? "auto";
- ctx.set(TaskDeliveryPolicyKey, taskDeliveryPolicy);
// Populate the callback base URL so getHookUrl() works during tool
// execution, preferring eve's active local origin over metadata fallback.
@@ -170,7 +156,6 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
ctx.set(AuthKey, delivery.auth ?? null);
if (!ctx.has(InitiatorAuthKey)) ctx.set(InitiatorAuthKey, delivery.auth ?? null);
}
- const backgroundTaskDelivery = getBackgroundTaskDelivery(delivery);
const initialSession = hydrateDurableSession({
compactionOverrides: {
thresholdPercent: effectiveAgent.thresholdPercent,
@@ -235,9 +220,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
await instrumentation?.flush();
};
const sink = createSessionEventSink({
- adapter,
ctx,
- isFirstTurn: initialEmissionState.sequence === 0,
sessionWritable: input.sessionWritable,
sessionId: initialSession.sessionId,
});
@@ -280,9 +263,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
: defaultDeliverResult(payload);
if (result !== undefined && result !== null) {
- results.push(
- backgroundTaskDelivery === undefined ? result : markBackgroundTaskStepInput(result),
- );
+ results.push(result);
}
}
} catch (error) {
@@ -300,7 +281,6 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
else ctx.set(AuthKey, previousAuth);
adapterCtx.state = previousAdapterState!;
} else {
- if (rawDelivery !== undefined) ctx.set(TurnTaskDeliveryKey, "none");
if (rawDelivery?.payloads.some((payload) => payload.message !== undefined)) {
const ids = rawDelivery.deliveryMetadata?.map((entry) => entry.deliveryId) ?? [];
ctx.set(
@@ -324,44 +304,13 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
resolved = { ...resolved, runtimeActionResults: runtimeResults.results };
}
- let taskRootTurnId: string | undefined;
- if (resolved !== undefined && backgroundTaskDelivery !== undefined) {
- const taskContext = resolveTaskDeliveryContext({
- state: durableSession.state,
- taskDeliveryIds: backgroundTaskDelivery.taskDeliveryIds ?? [
- backgroundTaskDelivery.taskDeliveryId,
- ],
- taskDeliveryPolicy,
- });
- if (taskContext !== undefined) {
- ctx.set(TurnTaskDeliveryKey, taskContext.phase);
- taskRootTurnId = taskContext.rootTurnId;
- resolved = {
- ...resolved,
- context: [...(resolved.context ?? []), taskContext.context],
- };
- }
- }
-
activityCohort.updateActivityRootForDelivery({
activeTurnId: activeTurnId(initialEmissionState),
ctx,
delivery: ignoredActiveDelivery ? undefined : rawDelivery,
sessionState: durableSession.state,
- taskRootTurnId,
});
- const taskDeliveryPhase = ctx.get(TurnTaskDeliveryKey);
- if (taskDeliveryPhase === "none" || taskDeliveryPhase === "initiating") {
- const taskContext = resolveInitiatingTaskContext({
- state: durableSession.state,
- turnId: activeTurnId(initialEmissionState),
- });
- if (taskContext !== undefined) {
- ctx.set(TurnTaskDeliveryKey, taskContext.phase);
- }
- }
-
if (rawDelivery !== undefined) {
const updatedAdapter = { ...adapter, state: { ...adapterCtx.state } };
setChannelContext(ctx, updatedAdapter);
@@ -495,7 +444,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
initialSession,
modelCallsPerStep,
runStep: async ({ firstCall, session, stepInput }) => {
- const result = await runBackgroundStep(ctx, session, async (enrichedSession) => {
+ const result = await runStep(ctx, session, async (enrichedSession) => {
ctx.setVirtualContext(HandleEventKey, handleEvent);
ctx.setVirtualContext(StaticModelReferenceKey, effectiveAgent.turnAgent.model ?? null);
let schemaSession =
@@ -587,8 +536,6 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
await failChannelDeliveries(error);
throw error;
}
- const retained = readRetainedBackgroundToolResult(ctx);
- instrumentation?.rememberBackgroundTasks(retained?.backgroundTasks ?? []);
return createCancelledModelCallBatchResult({
beforeBatchContext: input.serializedContext,
checkpoint: completedModelCall,
@@ -598,19 +545,13 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
});
}
- instrumentation?.rememberBackgroundTasks(stepResult.backgroundTasks ?? []);
// Re-stamp the current address after handlers add a continuation alias.
const aliased = reconcileSessionContinuationToken(ctx, stepResult.session);
agentTraceState.pruneAgentTraceState(ctx, aliased.sessionId, aliased.state);
const nextSerializedContext = serializeContext(ctx);
stepResult = { ...stepResult, session: aliased };
- const durableResult = resolveSessionStepResult(
- stepResult,
- nextSerializedContext,
- input.serializedContext,
- activeTurnId(initialEmissionState),
- );
+ const durableResult = resolveSessionStepResult(stepResult, nextSerializedContext);
if (durableResult.action === "done") await sink.close();
return durableResult;
} finally {
diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.ts
index bb7a8017e..50ceb088d 100644
--- a/packages/eve/src/execution/session/turn.test.ts
+++ b/packages/eve/src/execution/session/turn.test.ts
@@ -6,7 +6,6 @@ import { SessionInputQueue } from "#execution/session/input-queue.js";
import { SessionExecution } from "#execution/session/turn.js";
import { SessionStateCursor } from "#execution/session/state-cursor.js";
import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
-import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";
import { turnStep } from "#execution/session/turn-step.js";
import type { DeliverHookPayload, SessionCapabilities } from "#channel/types.js";
import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
@@ -21,9 +20,6 @@ vi.mock("#execution/coordination-dispatch-step.js", () => ({ dispatchCoordinatio
vi.mock("#execution/session/turn-step.js", () => ({
turnStep: vi.fn(),
}));
-vi.mock("#execution/tasks/parent/delegate.js", () => ({
- acknowledgeDelegatedTasksStep: vi.fn(),
-}));
vi.mock("#execution/cancel-descendant-turns-step.js", () => ({
cancelDescendantTurnsStep: vi.fn(),
}));
@@ -43,7 +39,7 @@ beforeEach(() => {
});
afterEach(() => vi.restoreAllMocks());
-describe("SessionExecution background task checkpoints", () => {
+describe("SessionExecution checkpoints", () => {
it("retains the durable steering signal across steps until a correction uses it", async () => {
const inbox: SessionInbox = {
claimedTokens: [],
@@ -247,14 +243,13 @@ describe("SessionExecution background task checkpoints", () => {
it.each([
{ kind: "deliver", turnPolicy: "queue", payloads: [{ message: "Queued" }] },
- { kind: "deliver", taskDeliveryId: "task-1:done", payloads: [{ message: "Notification" }] },
{
kind: "deliver",
payloads: [{ inputResponses: [{ requestId: "child-request", text: "Answer" }] }],
},
{ kind: "deliver", caller: { callId: "other-child" }, payloads: [{ message: "Other caller" }] },
])(
- "does not interrupt generation for non-steering delivery $kind $turnPolicy $taskDeliveryId",
+ "does not interrupt generation for non-steering delivery $kind $turnPolicy",
async (payload) => {
let notify: (payload: SessionInboxPayload) => void = () => {};
const inbox: SessionInbox = {
@@ -374,53 +369,6 @@ describe("SessionExecution background task checkpoints", () => {
expect(queue.takeNext(undefined)).toMatchObject({ delivery: followUp, kind: "turn" });
});
- it("steers a continuing turn with user input while retaining background notifications for cohort routing", async () => {
- const background: DeliverHookPayload = {
- kind: "deliver",
- taskDeliveryId: "task-1:completed",
- payloads: [{ message: "Background task task-1 is completed." }],
- };
- const steering: DeliverHookPayload = {
- kind: "deliver",
- payloads: [{ message: "Include Alice's update." }],
- };
- const queue = new SessionInputQueue();
- const inbox: SessionInbox = {
- claimedTokens: [],
- claimSessionHook: vi.fn(),
- claimSessionHooks: vi.fn(),
- drain: vi.fn().mockReturnValueOnce([background, steering]).mockReturnValue([]),
- hasPending: vi.fn(() => false),
- next: vi.fn(() => new Promise<never>(() => {})),
- onDelivery: vi.fn(() => () => {}),
- onInterrupt: vi.fn(() => () => {}),
- restore: vi.fn(),
- };
- const execution = createExecution({ inbox, queue, sessionState: state("") });
- vi.mocked(turnStep)
- .mockReset()
- .mockImplementationOnce(async (input) => ({
- action: "continue",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- }))
- .mockImplementation(async (input) => ({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- }));
-
- await execution.runTurn({
- delivery: { kind: "deliver", payloads: [{ message: "Start the work." }] },
- });
-
- expect(turnStep).toHaveBeenCalledTimes(2);
- expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toEqual({ delivery: steering });
- expect(queue.pendingCount).toBe(1);
- });
-
it("applies steering accepted during a blocking action before its result continues the turn", async () => {
const sessionState = state("");
const steering: DeliverHookPayload = {
@@ -509,7 +457,7 @@ describe("SessionExecution background task checkpoints", () => {
hasPendingInputBatch: false,
serializedContext: input.serializedContext,
sessionState: input.sessionState,
- settled: { notifyCaller: true, output: "Done." },
+ settled: { output: "Done." },
}));
await expect(
@@ -518,7 +466,7 @@ describe("SessionExecution background task checkpoints", () => {
}),
).resolves.toMatchObject({
kind: "park",
- settled: { notifyCaller: true, output: "Done." },
+ settled: { output: "Done." },
});
expect(turnStep).toHaveBeenCalledTimes(1);
@@ -574,84 +522,62 @@ describe("SessionExecution background task checkpoints", () => {
},
);
- it.each([
- { backgroundTasks: false, settled: { notifyCaller: true, output: "Done." } },
- { backgroundTasks: true, settled: { notifyCaller: true, output: "Done." } },
- { backgroundTasks: false, settled: { notifyCaller: false, output: "Still working." } },
- { backgroundTasks: true, settled: { notifyCaller: false, output: "Still working." } },
- ] as const)(
- "preserves the completed turn when cancellation races its checkpoint (notify caller: $settled.notifyCaller, background tasks: $backgroundTasks)",
- async ({ backgroundTasks, settled }) => {
- const followUp: DeliverHookPayload = {
- kind: "deliver",
- payloads: [{ message: "Follow up after completion." }],
- };
- const cancel = { kind: "cancel", turnId: "turn_0" } as const;
- let interrupt: (payload: SessionInboxPayload) => void = () => {};
- const queue = new SessionInputQueue();
- const inbox: SessionInbox = {
- claimedTokens: [],
- claimSessionHook: vi.fn(),
- claimSessionHooks: vi.fn(),
- drain: vi.fn().mockReturnValueOnce([cancel, followUp]).mockReturnValue([]),
- hasPending: () => false,
- next: vi.fn(),
- restore: vi.fn(),
- onDelivery: () => () => {},
- onInterrupt: (handler) => {
- interrupt = handler;
- return () => {};
- },
- };
- const completedState = state("http:completed");
- const execution = createExecution({ inbox, queue, sessionState: state("") });
- vi.mocked(cancelDescendantTurnsStep).mockClear();
- vi.mocked(acknowledgeDelegatedTasksStep).mockReset();
- vi.mocked(turnStep)
- .mockReset()
- .mockImplementationOnce(async (input) => {
- interrupt(cancel);
- expect(input.abortSignal?.aborted).toBe(true);
- return {
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- serializedContext: input.serializedContext,
- sessionState: completedState,
- settled,
- ...(backgroundTasks
- ? {
- backgroundTaskState: state("http:background"),
- backgroundTasks: [
- {
- callId: "call-1",
- taskId: "task-1",
- taskInboxToken: "inbox-1",
- taskRunId: "run-1",
- },
- ],
- }
- : {}),
- };
- });
- await expect(execution.runTurn(undefined)).resolves.toMatchObject({
- kind: "park",
- settled,
+ it("preserves the completed turn when cancellation races its checkpoint", async () => {
+ const settled = { output: "Done." };
+ const followUp: DeliverHookPayload = {
+ kind: "deliver",
+ payloads: [{ message: "Follow up after completion." }],
+ };
+ const cancel = { kind: "cancel", turnId: "turn_0" } as const;
+ let interrupt: (payload: SessionInboxPayload) => void = () => {};
+ const queue = new SessionInputQueue();
+ const inbox: SessionInbox = {
+ claimedTokens: [],
+ claimSessionHook: vi.fn(),
+ claimSessionHooks: vi.fn(),
+ drain: vi.fn().mockReturnValueOnce([cancel, followUp]).mockReturnValue([]),
+ hasPending: () => false,
+ next: vi.fn(),
+ restore: vi.fn(),
+ onDelivery: () => () => {},
+ onInterrupt: (handler) => {
+ interrupt = handler;
+ return () => {};
+ },
+ };
+ const completedState = state("http:completed");
+ const execution = createExecution({ inbox, queue, sessionState: state("") });
+ vi.mocked(cancelDescendantTurnsStep).mockClear();
+ vi.mocked(turnStep)
+ .mockReset()
+ .mockImplementationOnce(async (input) => {
+ interrupt(cancel);
+ expect(input.abortSignal?.aborted).toBe(true);
+ return {
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ serializedContext: input.serializedContext,
+ sessionState: completedState,
+ settled,
+ };
});
- expect(execution.cursor.sessionState).toBe(completedState);
- expect(cancelDescendantTurnsStep).not.toHaveBeenCalled();
- expect(queue.pendingCount).toBe(1);
- },
- );
+ await expect(execution.runTurn(undefined)).resolves.toMatchObject({
+ kind: "park",
+ settled,
+ });
+ expect(execution.cursor.sessionState).toBe(completedState);
+ expect(cancelDescendantTurnsStep).not.toHaveBeenCalled();
+ expect(queue.pendingCount).toBe(1);
+ });
- it("routes a task-owned answer to a descendant while waiting for runtime results", async () => {
+ it("routes a proxied answer to a descendant while waiting for runtime results", async () => {
const sessionState = { ...state(""), hasProxyInputRequests: true };
- const taskAnswer: DeliverHookPayload = {
+ const answer: DeliverHookPayload = {
kind: "deliver",
payloads: [{ inputResponses: [{ requestId: "child-request", text: "blue" }] }],
- taskDeliveryId: "task-1:child-request",
};
- const runtimePayloads = [taskAnswer, { kind: "cancel" as const }];
+ const runtimePayloads = [answer, { kind: "cancel" as const }];
const queue = new SessionInputQueue();
const inbox: SessionInbox = {
claimedTokens: [],
@@ -691,89 +617,10 @@ describe("SessionExecution background task checkpoints", () => {
).resolves.toEqual({ cancelled: true, kind: "park" });
expect(routeDeliverToChildren).toHaveBeenCalledWith(
- expect.objectContaining({ delivery: taskAnswer }),
+ expect.objectContaining({ delivery: answer }),
);
expect(queue.pendingCount).toBe(0);
});
-
- it.each(["cancelled", "done"] as const)(
- "retains task observability when a %s step races cancellation",
- async (action) => {
- const initialState = state("");
- const backgroundState = state("http:background");
- const completedState = state("http:completed");
- const tasks = [
- { callId: "call-1", taskId: "task-1", taskInboxToken: "inbox-1", taskRunId: "run-1" },
- ];
- const observability = {
- "eve.harness.agentTrace": { actions: { "action-1": {} }, sessions: {}, turns: {} },
- "eve.harness.instrumentationActionScopes": {
- "action-1": { scope: { turnId: "turn_0" }, taskId: "task-1" },
- },
- "eve.harness.instrumentationState": { "sink\0action-1": { value: "open" } },
- };
- const backgroundContext = { ...observability, state: "before" };
- const completedContext = { ...observability, state: "completed" };
- let interrupt: ((payload: SessionInboxPayload) => void) | undefined;
- const inbox: SessionInbox = {
- claimedTokens: [],
- claimSessionHook: vi.fn(),
- claimSessionHooks: vi.fn(),
- drain: vi
- .fn()
- .mockReturnValueOnce([{ kind: "cancel" }])
- .mockReturnValue([]),
- hasPending: vi.fn(() => false),
- next: vi.fn(() => new Promise<never>(() => {})),
- onDelivery: vi.fn(() => () => {}),
- onInterrupt: vi.fn((handler) => {
- interrupt = handler;
- return () => {};
- }),
- restore: vi.fn(),
- };
- const execution = createExecution({
- inbox,
- serializedContext: { state: "before" },
- sessionState: initialState,
- });
- const apply = vi.spyOn(SessionStateCursor.prototype, "apply");
- vi.mocked(acknowledgeDelegatedTasksStep).mockImplementation(async () => {
- expect(execution.cursor.serializedContext).toEqual(backgroundContext);
- expect(execution.cursor.sessionState).toBe(backgroundState);
- });
- vi.mocked(turnStep).mockImplementationOnce(async (input) => {
- // The pump pushes the accepted cancel while this step is still running.
- interrupt?.({ kind: "cancel" });
- await vi.waitFor(() => expect(input.abortSignal?.aborted).toBe(true));
- return {
- action,
- backgroundTaskContext: backgroundContext,
- backgroundTaskState: backgroundState,
- backgroundTasks: tasks,
- serializedContext: completedContext,
- sessionState: completedState,
- };
- });
-
- const result = await execution.runTurn({
- delivery: { kind: "deliver", payloads: [{ message: "work" }] },
- });
- expect(result).toEqual({
- cancelled: true,
- kind: "park",
- });
- expect(apply.mock.calls[0]?.[0]).toEqual({
- serializedContext: backgroundContext,
- sessionState: backgroundState,
- });
- expect(acknowledgeDelegatedTasksStep).toHaveBeenCalledWith({ tasks });
- expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({
- serializedContext: completedContext,
- sessionState: backgroundState,
- });
- },
- );
});
function createExecution(input: {
diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.ts
index 3e2b9717a..8253a52e6 100644
--- a/packages/eve/src/execution/session/turn.ts
+++ b/packages/eve/src/execution/session/turn.ts
@@ -5,19 +5,16 @@ import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-st
import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import { routeSelectedDelivery } from "#execution/session/route-selected-delivery.js";
-import { isSteeringDelivery, type SessionInputQueue } from "#execution/session/input-queue.js";
+import { isSteeringMessage, type SessionInputQueue } from "#execution/session/input-queue.js";
import {
sessionCommandHookToken,
sessionInboxHookToken,
} from "#execution/session-inbox/address.js";
import type { SessionInboxPayload, SessionInboxReader } from "#execution/session-inbox/inbox.js";
-import {
- admitSessionInboxPayload,
- applySessionCancellation,
-} from "#execution/session/admission.js";
+import { admitSessionInboxPayload } from "#execution/session/admission.js";
import type { SessionStateCursor } from "#execution/session/state-cursor.js";
-import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";
import { handleWorkflowToolRunMessage } from "#execution/session-workflow-tool-run.js";
+import { interruptWorkflowToolRun } from "#execution/tools/workflow/interrupt.js";
import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
import type {
DurableStepResult,
@@ -31,7 +28,10 @@ import { activeTurnId } from "#harness/active-turn-id.js";
import { coalesceDeliveries } from "#harness/messages.js";
import { TurnCancelledError } from "#harness/turn-cancellation.js";
import { decodeSessionInboxPayload } from "#execution/session-inbox/protocol.js";
-import { isInboxToolResultFromRecordedWorkflowToolRun } from "#harness/workflow-tool-runs.js";
+import {
+ findBlockingWorkflowToolRun,
+ isInboxToolResultFromRecordedWorkflowToolRun,
+} from "#harness/workflow-tool-runs.js";
import { isInboxSubagentResultFromRunningHandle } from "#subagents/handles/query.js";
import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
@@ -90,45 +90,25 @@ export class SessionExecution {
while (true) {
const { cursor } = this.input;
- const beforeStepContext = cursor.serializedContext;
- const result: DurableStepResult = await turnStep(
- cursor.createStepInput(nextStepInput, {
- abortSignal: turn.signal,
- steeringSignal: turn.steeringSignal,
- }),
- );
+ const result: DurableStepResult = await turnStep({
+ ...cursor.stepState(),
+ abortSignal: turn.signal,
+ input: nextStepInput,
+ steeringSignal: turn.steeringSignal,
+ });
const pendingCallIds =
result.action === "park" ? result.pendingCoordinationCallIds : undefined;
- const hasBackgroundTasks = (result.backgroundTasks?.length ?? 0) > 0;
const turnCompleted = result.action === "park" && result.settled !== undefined;
- if (hasBackgroundTasks) {
- if (result.backgroundTaskState === undefined) {
- throw new Error("Background tasks were returned without their committed session state.");
- }
- await cursor.apply({
- serializedContext: result.backgroundTaskContext ?? beforeStepContext,
- sessionState: result.backgroundTaskState,
- });
- await acknowledgeDelegatedTasksStep({ tasks: result.backgroundTasks ?? [] });
- }
-
await cursor.apply({
serializedContext: result.serializedContext,
- sessionState:
- result.action === "cancelled" || (!turnCompleted && turn.signal.aborted)
- ? (result.backgroundTaskState ?? result.sessionState)
- : result.sessionState,
+ sessionState: result.sessionState,
});
await turn.admitBoundary();
turn.resetSteering();
if (result.action === "cancelled") return await this.finishCancelledTurn();
- if (
- !turnCompleted &&
- turn.signal.aborted &&
- (pendingCallIds === undefined || hasBackgroundTasks)
- ) {
+ if (!turnCompleted && turn.signal.aborted && pendingCallIds === undefined) {
return await this.finishCancelledTurn();
}
@@ -149,9 +129,7 @@ export class SessionExecution {
workflowToolRunOwner: {
inbox: sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId)),
},
- sessionWritable: cursor.sessionWritable,
- serializedContext: cursor.serializedContext,
- sessionState: cursor.sessionState,
+ ...cursor.stepState(),
});
const initialAcceptedAtMs = dispatchResult.results.length === 0 ? undefined : Date.now();
await cursor.apply(dispatchResult);
@@ -215,6 +193,7 @@ export class SessionExecution {
readonly turn: ActiveTurn;
}): Promise<RuntimeActionResultStepInput | "cancelled"> {
const results: RuntimeActionResult[] = [...input.initialResults];
+ let interrupted = false;
const acceptedAtMsByCallId = new Map<string, number>();
if (input.initialAcceptedAtMs !== undefined) {
for (const result of results)
@@ -237,6 +216,12 @@ export class SessionExecution {
const next = await input.turn.nextRuntimeEvent();
if (next === "cancelled") return next;
+ if (next.kind === "steering") {
+ // Only the first steering message interrupts; later ones wait for the calls anyway.
+ if (!interrupted) await this.interruptWaitedWorkflowCalls(input.pendingCallIds, results);
+ interrupted = true;
+ continue;
+ }
if (next.kind === "runtime-action-result") {
const snapshot = this.input.cursor.sessionState.snapshot.session.state;
const accepted = next.results.filter((result) => {
@@ -263,11 +248,28 @@ export class SessionExecution {
}
}
}
+
+ /** Fires the `interruptSignal` of every workflow tool call the wait has no result for yet. */
+ private async interruptWaitedWorkflowCalls(
+ pendingCallIds: readonly string[],
+ settled: readonly RuntimeActionResult[],
+ ): Promise<void> {
+ const state = this.input.cursor.sessionState.snapshot.session.state;
+ const settledCallIds = new Set(settled.map((result) => result.callId));
+ const waited = pendingCallIds.filter((callId) => !settledCallIds.has(callId));
+ const runs = waited.flatMap((callId) => {
+ const run = findBlockingWorkflowToolRun(state, callId);
+ return run === undefined ? [] : [run.address];
+ });
+ await Promise.all(runs.map((run) => interruptWorkflowToolRun(run)));
+ }
}
type RuntimeEvent =
| { readonly kind: "runtime-action-result"; readonly results: readonly RuntimeActionResult[] }
| { readonly kind: "workflow"; readonly message: WorkflowToolRunMessage }
+ /** A steering message that answered no pending request arrived during the wait. */
+ | { readonly kind: "steering" }
| "cancelled";
/**
@@ -311,14 +313,8 @@ class ActiveTurn {
}
if (
delivery.kind === "deliver" &&
- isSteeringDelivery(delivery, this.callerCallId) &&
- !this.input.cursor.sessionState.hasProxyInputRequests &&
- delivery.payloads.some(
- (value) =>
- value.message !== undefined &&
- value.inputResponses === undefined &&
- value.task === undefined,
- )
+ isSteeringMessage(delivery, this.callerCallId) &&
+ !this.input.cursor.sessionState.hasProxyInputRequests
)
this.steeringController.abort();
};
@@ -369,17 +365,22 @@ class ActiveTurn {
return steering.length === 1 ? steering[0] : coalesceDeliveries(steering);
}
- /** Next runtime result or workflow message, admitting inbox traffic while waiting. */
+ /**
+ * Next runtime result, workflow message, or steering, admitting inbox traffic
+ * while waiting. Deliveries admitted before the wait began are routed first,
+ * so a message that arrived as the calls started still steers.
+ */
async nextRuntimeEvent(): Promise<RuntimeEvent> {
while (true) {
+ const steered = await this.routeAdmittedToChildren();
if (this.signal.aborted) return "cancelled";
+ if (steered) return { kind: "steering" };
const event = this.runtimeResults.shift();
if (event !== undefined) return event;
const payload = await this.input.inbox.next();
if (payload === undefined)
throw new Error("Session inbox closed before runtime actions completed.");
await this.admit(payload);
- await this.routeAdmittedToChildren();
}
}
@@ -405,17 +406,20 @@ class ActiveTurn {
this.runtimeResults.push({ kind: "workflow", message: admitted.message });
return;
case "cancel":
- if (!this.cancelsThisTurn(value)) return;
- await applySessionCancellation(admitted.command, this.input);
- this.abort();
+ if (this.cancelsThisTurn(value)) this.abort();
return;
case "consumed":
return;
}
}
- /** During a runtime wait, descendant-bound answers cannot wait for the boundary. */
- private async routeAdmittedToChildren(): Promise<void> {
+ /**
+ * During a runtime wait, descendant-bound answers cannot wait for the
+ * boundary. Returns whether a newly routed delivery still steers: it
+ * answered nothing, so its message is for the model.
+ */
+ private async routeAdmittedToChildren(): Promise<boolean> {
+ let steered = false;
for (const sequence of this.admitted) {
if (this.routedToChildren.has(sequence)) continue;
const delivery = this.input.queue.delivery(sequence);
@@ -426,20 +430,23 @@ class ActiveTurn {
this.routedToChildren.add(sequence);
const routed = await routeDeliverToChildren({
delivery,
- sessionWritable: this.input.cursor.sessionWritable,
- serializedContext: this.input.cursor.serializedContext,
- sessionState: this.input.cursor.sessionState,
+ ...this.input.cursor.stepState(),
});
await this.input.cursor.apply(routed);
if (routed.kind === "cancel-turn") {
this.input.queue.replaceDelivery(sequence, undefined);
this.admitted.delete(sequence);
this.abort();
- return;
+ return false;
}
this.input.queue.replaceDelivery(sequence, routed.remainder);
- if (routed.remainder === undefined) this.admitted.delete(sequence);
+ if (routed.remainder === undefined) {
+ this.admitted.delete(sequence);
+ continue;
+ }
+ if (isSteeringMessage(routed.remainder, this.callerCallId)) steered = true;
}
+ return steered;
}
private abort(): void {
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 b94f71393..66fdcba85 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,12 +5,7 @@ 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 { setPendingCoordinationBatch } from "#harness/coordination.js";
-import {
- getWorkflowToolRuns,
- registerWorkflowToolRun,
- type BackgroundWorkflowToolRun,
-} from "#harness/workflow-tool-runs.js";
+import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
import {
AGENT_HANDLES_STATE_KEY,
@@ -171,7 +166,6 @@ describe("settleCancelledTurnStep handle store", () => {
const session = registerWorkflowToolRun(createCancelledTurnSession([CLAIMED_HANDLE]), {
callId: "workflow-call",
toolName: "Workflow",
- lifetime: "turn" as const,
origin: { turnId: "turn-1", stepIndex: 0 },
address: { runId: "workflow-run", hookToken: "workflow-hook" },
});
@@ -193,64 +187,4 @@ describe("settleCancelledTurnStep handle store", () => {
});
});
});
- it.each([false, true])(
- "retains task payloads on turn cancellation (paused=%s)",
- async (paused) => {
- const runtime = await createTestRuntime({ agent: { name: "settle-mixed-invocations" } });
- await runtime.run(async () => {
- const background: BackgroundWorkflowToolRun = {
- callId: "background-call",
- lifetime: "session",
- toolName: "research",
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "background-run", hookToken: "background-hook" },
- task: {
- taskId: "background-task",
- metadata: { kind: "tool", name: "research" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- };
- let session = registerWorkflowToolRun(createCancelledTurnSession([]), background);
- session = registerWorkflowToolRun(session, {
- ...background,
- callId: "completed-call",
- task: {
- ...background.task,
- taskId: "completed-task",
- outcome: {
- status: "completed",
- lastOutput: { type: "result", data: "retained output" },
- },
- },
- });
- const tasks = getWorkflowToolRuns(session.state);
- session = registerWorkflowToolRun(session, {
- callId: "waiting-call",
- toolName: "research",
- lifetime: "turn",
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "waiting-run", hookToken: "waiting-hook" },
- });
- if (paused)
- session = setPendingCoordinationBatch({
- event: { sequence: 3, stepIndex: 1, turnId: "turn-1" },
- responseMessages: [],
- runtimeActions: [],
- tasks: [],
- session: setHarnessEmissionState(session, {
- sequence: 4,
- stepIndex: 0,
- sessionStarted: true,
- turnId: "",
- }),
- });
- const result = await settleCancelledTurnStep({
- sessionWritable: new WritableStream<Uint8Array>({ write() {} }),
- serializedContext: buildSerializedContext(),
- sessionState: createDurableSessionState({ session }),
- });
- expect(getWorkflowToolRuns(result.sessionState.snapshot.session.state)).toEqual(tasks);
- });
- },
- );
});
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.ts
index 959d08a49..cfe9a34c8 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -1,30 +1,16 @@
import { getPendingCoordinationBatch } from "#harness/coordination.js";
-import { buildAdapterContext } from "#channel/adapter-context.js";
-import { TurnDeliveryIdsKey } from "#context/keys.js";
-import { withContextScope } from "#context/run-step.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
-import { publishChannelEvent } from "#execution/publish-channel-event.js";
-import { observeSessionActivity } from "#execution/session-activity-projection.js";
import {
createDurableSessionState,
type DurableSessionState,
readDurableSession,
} from "#execution/durable-session-store.js";
-import { hydrateDurableSession } from "#execution/session.js";
+import { withSessionEventEmitter } from "#execution/publish-session-events.js";
import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";
-import { activeTurnId } from "#harness/active-turn-id.js";
import { emitCancelledTurn } from "#harness/cancelled-turn-emission.js";
import { clearPendingSessionLimitPrompt } from "#harness/input-requests.js";
-import {
- getHarnessEmissionState,
- isHarnessBetweenTurns,
- setHarnessEmissionState,
-} from "#harness/emission.js";
-import {
- clearAllProxyInputRequests,
- getProxyInputRequests,
- hasProxyInputRequests,
-} from "#harness/proxy-input-requests.js";
+import { getHarnessEmissionState, setHarnessEmissionState } from "#harness/emission.js";
+import { clearAllProxyInputRequests } from "#harness/proxy-input-requests.js";
import {
abandonAgentInvocationOwners,
abandonRunningAgentTurns,
@@ -34,11 +20,7 @@ import {
removeBlockingWorkflowToolRuns,
getBlockingWorkflowToolRuns,
} from "#harness/workflow-tool-runs.js";
-import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
import { getTurnUsageState, toUsage } from "#harness/turn-tag-state.js";
-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
import type { TokenUsage } from "#shared/token-usage.js";
export interface CancelledTurnSettleResult {
@@ -62,70 +44,15 @@ export async function settleCancelledTurnStep(input: {
const durableSession = readDurableSession(input.sessionState);
const ctx = await deserializeContext(input.serializedContext);
- const adapter = ctx.require(ChannelKey);
- const adapterCtx = buildAdapterContext(adapter, ctx);
- const bundle = ctx.require(BundleKey);
- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
-
- let session = hydrateDurableSession({
- compactionOverrides: {
- thresholdPercent: effectiveAgent.thresholdPercent,
- },
- durable: durableSession,
- turnAgent: effectiveAgent.turnAgent,
- });
- const instrumentation = bindSessionInstrumentation({
- agentName: effectiveAgent.turnAgent.id,
- ctx,
- rootSessionId: session.rootSessionId ?? session.sessionId,
- sessionId: session.sessionId,
- });
-
- let emissionState = getHarnessEmissionState(durableSession.state);
- // A descendant HITL wait already streamed this turn's waiting boundary
- // (the proxy epilogue clears the turn id); re-emitting would fabricate
- // a turn id and duplicate the boundary.
- const proxyRequests = getProxyInputRequests(durableSession.state);
- const stoppedAtDescendantLimit = [...proxyRequests.values()].some(
- (request) => request.kind === "session-limit",
+ const emitted = await withSessionEventEmitter(
+ { ctx, durableSession, origin: "own", sessionWritable: input.sessionWritable },
+ async (emit, scopedSession) => ({
+ result: await emitCancelledTurn(emit, getHarnessEmissionState(durableSession.state)),
+ session: scopedSession,
+ }),
);
- const alreadyEpilogued =
- isHarnessBetweenTurns(session) &&
- hasProxyInputRequests(durableSession.state) &&
- !stoppedAtDescendantLimit;
-
- if (!alreadyEpilogued) {
- const writer = input.sessionWritable.getWriter();
- try {
- const scoped = await withContextScope(ctx, session, async (enrichedSession) => {
- const baseEmit = async (event: UnstampedMessageStreamEvent): Promise<void> => {
- const stamped = await publishChannelEvent({
- adapter,
- adapterCtx,
- ctx,
- writer,
- event,
- deliveryIds: ctx.get(TurnDeliveryIdsKey),
- });
- void observeSessionActivity({ ctx, event: stamped, sessionId: session.sessionId });
- };
- const emit =
- instrumentation?.createHandleEvent({
- handleEvent: baseEmit,
- turnId: activeTurnId(emissionState),
- }) ?? baseEmit;
- return {
- result: await emitCancelledTurn(emit, emissionState),
- session: enrichedSession,
- };
- });
- emissionState = scoped.result;
- session = scoped.session;
- } finally {
- await instrumentation?.flush();
- writer.releaseLock();
- }
- }
+ const emissionState = emitted.result;
+ let session = emitted.session;
// `clearPendingSessionLimitPrompt`: cancellation settles with the step's
// input snapshot, which can resurrect an already-answered session-limit
diff --git a/packages/eve/src/execution/task-event-callback.ts b/packages/eve/src/execution/task-event-callback.ts
deleted file mode 100644
index b3598ea1c..000000000
--- a/packages/eve/src/execution/task-event-callback.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { ContextContainer } from "#context/container.js";
-import { ContinuationTokenKey, SessionCallbackKey, SessionIdKey } from "#context/keys.js";
-import { fireTaskEventCallbackStep } from "#subagents/callback-step.js";
-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-
-/**
- * Forwards one task child's blocking transition to its parent's session
- * callback.
- *
- * Task children report HITL and authorization transitions exclusively to the
- * parent's task run, so the run can block/unblock the task under one durable
- * decision and only the parent channel owns the interaction. Returns whether
- * the event was forwarded and must therefore be suppressed locally.
- */
-export async function forwardTaskEventToSessionCallback(
- ctx: ContextContainer,
- event: UnstampedMessageStreamEvent,
-): Promise<boolean> {
- const callback = ctx.get(SessionCallbackKey);
- if (callback?.taskId === undefined) return false;
- if (
- event.type !== "input.requested" &&
- event.type !== "authorization.required" &&
- event.type !== "authorization.completed"
- ) {
- return false;
- }
- await fireTaskEventCallbackStep({
- callback,
- childContinuationToken: ctx.require(ContinuationTokenKey),
- childSessionId: ctx.require(SessionIdKey),
- event,
- });
- return true;
-}
diff --git a/packages/eve/src/execution/task-input-capability.test.ts b/packages/eve/src/execution/task-input-capability.test.ts
deleted file mode 100644
index a04ff4d37..000000000
--- a/packages/eve/src/execution/task-input-capability.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- createTaskInputCapabilityToken,
- readTaskInputTargetToken,
-} from "#execution/task-input-capability.js";
-
-const DIGEST = "0123456789abcdef0123456789abcdef";
-
-describe("task input capabilities", () => {
- it("round-trips only an eve create-once session hook", () => {
- const capability = createTaskInputCapabilityToken(`eve:eve:op:${DIGEST}`);
-
- expect(capability).toBe(`eve:task-input:${DIGEST}`);
- expect(readTaskInputTargetToken(capability)).toBe(`eve:eve:op:${DIGEST}`);
- });
-
- it.each(["eve:session:victim:inbox", "task:task_1:0123456789abcdef0123456789abcdef"])(
- "does not mint a task-input capability for %s",
- (token) => {
- expect(() => createTaskInputCapabilityToken(token)).toThrow(
- "requires an eve create-once session capability",
- );
- },
- );
-
- it("rejects malformed task-input capabilities", () => {
- expect(readTaskInputTargetToken("eve:task-input:not-a-digest")).toBeUndefined();
- });
-});
diff --git a/packages/eve/src/execution/task-input-capability.ts b/packages/eve/src/execution/task-input-capability.ts
deleted file mode 100644
index d1150a0f6..000000000
--- a/packages/eve/src/execution/task-input-capability.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-const OPERATION_TOKEN_PREFIX = "eve:eve:op:";
-const TASK_INPUT_TOKEN_PREFIX = "eve:task-input:";
-const TOKEN_DIGEST = /^[a-f0-9]{32}$/;
-
-/** Narrows one private create-once session token to task-input delivery only. */
-export function createTaskInputCapabilityToken(operationToken: string): string {
- const digest = readTokenDigest(operationToken, OPERATION_TOKEN_PREFIX);
- if (digest === undefined) {
- throw new Error("Remote task input requires an eve create-once session capability.");
- }
- return `${TASK_INPUT_TOKEN_PREFIX}${digest}`;
-}
-
-/** Resolves a task-input capability to the create-once session hook it may address. */
-export function readTaskInputTargetToken(capabilityToken: string): string | undefined {
- const digest = readTokenDigest(capabilityToken, TASK_INPUT_TOKEN_PREFIX);
- return digest === undefined ? undefined : `${OPERATION_TOKEN_PREFIX}${digest}`;
-}
-
-function readTokenDigest(token: string, prefix: string): string | undefined {
- if (!token.startsWith(prefix)) return undefined;
- const digest = token.slice(prefix.length);
- return TOKEN_DIGEST.test(digest) ? digest : undefined;
-}
diff --git a/packages/eve/src/execution/task-input-response-route.ts b/packages/eve/src/execution/task-input-response-route.ts
deleted file mode 100644
index c6ec68427..000000000
--- a/packages/eve/src/execution/task-input-response-route.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { readTaskInputTargetToken } from "#execution/task-input-capability.js";
-import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
-import type { RouteContext } from "#public/definitions/channel.js";
-import type { InputResponse } from "#shared/input.js";
-import type { ToolInputResponseResponder } from "#tools/definition.js";
-
-export async function handleTaskInputResponseRequest(
- request: Request,
- ctx: RouteContext,
-): Promise<Response> {
- const token = ctx.params.token;
- if (typeof token !== "string" || token.length === 0) {
- return Response.json({ error: "Missing task input token.", ok: false }, { status: 400 });
- }
- const targetToken = readTaskInputTargetToken(token);
- if (targetToken === undefined) {
- return Response.json({ error: "Invalid task input token.", ok: false }, { status: 403 });
- }
- let body: unknown;
- try {
- body = await request.json();
- } catch {
- return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
- }
- const inputResponses = readInputResponses(body);
- if (inputResponses === undefined || inputResponses.length === 0) {
- return Response.json(
- { error: "Expected a non-empty inputResponses array.", ok: false },
- { status: 400 },
- );
- }
- const responder = readResponder(body);
- if (responder === null) {
- return Response.json({ error: "Invalid responder identity.", ok: false }, { status: 400 });
- }
- // Child inboxes outlive deployments; cross the hook in the durable
- // delivery envelope like every other session-inbox producer.
- try {
- await resumeSessionInbox(targetToken, {
- kind: "send",
- payload: { inputResponses, responder },
- });
- } catch {
- return Response.json(
- { error: "Task input target is not pending.", ok: false },
- { status: 404 },
- );
- }
- return Response.json({ ok: true }, { status: 202 });
-}
-
-function readInputResponses(value: unknown): readonly InputResponse[] | undefined {
- if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
- const responses = Reflect.get(value, "inputResponses");
- if (!Array.isArray(responses)) return undefined;
- const parsed: InputResponse[] = [];
- for (const response of responses) {
- if (response === null || typeof response !== "object" || Array.isArray(response))
- return undefined;
- const requestId = Reflect.get(response, "requestId");
- const optionId = Reflect.get(response, "optionId");
- const text = Reflect.get(response, "text");
- if (
- typeof requestId !== "string" ||
- (optionId !== undefined && typeof optionId !== "string") ||
- (text !== undefined && typeof text !== "string")
- ) {
- return undefined;
- }
- const item: { optionId?: string; requestId: string; text?: string } = { requestId };
- if (typeof optionId === "string") item.optionId = optionId;
- if (typeof text === "string") item.text = text;
- parsed.push(item);
- }
- return parsed;
-}
-
-function readResponder(value: unknown): ToolInputResponseResponder | undefined | null {
- if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
- const responder = Reflect.get(value, "responder");
- if (responder === undefined) return undefined;
- if (responder === null || typeof responder !== "object" || Array.isArray(responder)) return null;
- const authenticator = Reflect.get(responder, "authenticator");
- const principalId = Reflect.get(responder, "principalId");
- const principalType = Reflect.get(responder, "principalType");
- if (
- typeof authenticator !== "string" ||
- typeof principalId !== "string" ||
- typeof principalType !== "string"
- ) {
- return null;
- }
- return { authenticator, principalId, principalType };
-}
diff --git a/packages/eve/src/execution/tasks/child/notify.test.ts b/packages/eve/src/execution/tasks/child/notify.test.ts
deleted file mode 100644
index 1393e7bb6..000000000
--- a/packages/eve/src/execution/tasks/child/notify.test.ts
+++ /dev/null
@@ -1,385 +0,0 @@
-import { HookNotFoundError, RunExpiredError } from "#compiled/@workflow/errors/index.js";
-import { formatTaskNotification } from "#tasks/notification.js";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import {
- emitTaskActivityStep,
- deliverTaskInputResponsesStep,
- projectTaskActivity,
- notifyTaskParent,
-} from "#execution/tasks/child/notify.js";
-import { resumeWorkflowToolRunAnswers } from "#execution/tools/workflow/answer.js";
-import type { TaskView } from "#tasks/types.js";
-import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
-import { submitActivity } from "#execution/submit-activity.js";
-import { captureLogRecords } from "#internal/testing/log-records.js";
-
-vi.mock("#execution/submit-activity.js", () => ({ submitActivity: vi.fn() }));
-
-vi.mock("#execution/session-inbox/resume.js", () => ({ resumeSessionInbox: vi.fn() }));
-vi.mock("#execution/tools/workflow/answer.js", () => ({
- resumeWorkflowToolRunAnswers: vi.fn(),
- toToolInputResponseResponder: (
- auth:
- | {
- readonly authenticator: string;
- readonly principalId: string;
- readonly principalType: string;
- }
- | null
- | undefined,
- ) =>
- auth === null || auth === undefined
- ? undefined
- : {
- authenticator: auth.authenticator,
- principalId: auth.principalId,
- principalType: auth.principalType,
- },
-}));
-
-afterEach(() => {
- vi.resetAllMocks();
- vi.unstubAllGlobals();
-});
-
-const metadata = {
- kind: "tool" as const,
- name: "reviewer",
-};
-
-const notificationCases: readonly { readonly expected: string; readonly view: TaskView }[] = [
- {
- expected: "Background task task-1 (reviewer) is completed.\n\nResult:\nship it",
- view: {
- lastOutput: { data: "ship it", type: "result" },
- metadata,
- status: "completed",
- taskId: "task-1",
- },
- },
- {
- expected: 'Background task task-1 (reviewer) is completed.\n\nResult:\n{"verdict":"ship"}',
- view: {
- lastOutput: { data: { verdict: "ship" }, type: "result" },
- metadata,
- status: "completed",
- taskId: "task-1",
- },
- },
- {
- expected: 'Background task task-1 (reviewer) failed.\n\nError:\n{"code":"FAILED"}',
- view: {
- lastOutput: { data: { code: "FAILED" }, type: "error" },
- metadata,
- status: "failed",
- taskId: "task-1",
- },
- },
-];
-
-describe("emitTaskActivityStep", () => {
- it("waits for best-effort activity submission before the step finishes", async () => {
- const submission = Promise.withResolvers<void>();
- const submitted = Promise.withResolvers<void>();
- vi.mocked(submitActivity).mockImplementation(() => {
- submitted.resolve();
- return submission.promise;
- });
- let finished = false;
- const appended = emitTaskActivityStep({ view: notificationCases[0]!.view }).then(() => {
- finished = true;
- });
- await submitted.promise;
- await Promise.resolve();
- expect(finished).toBe(false);
- submission.resolve();
- await appended;
- expect(finished).toBe(true);
- });
-});
-
-describe("projectTaskActivity", () => {
- afterEach(() => vi.unstubAllGlobals());
-
- it("projects terminal task settlement", () => {
- expect(
- projectTaskActivity({
- 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("projects task work when execution starts", () => {
- const workIdentity = {
- id: "work:task",
- kind: "task" as const,
- name: "export",
- parentId: "work:root",
- rootSessionId: "root",
- rootTurnId: "turn",
- };
- expect(
- projectTaskActivity({
- activityObserver: {
- sink: {
- url: "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- workIdentity,
- },
- settledAt: "2026-01-01T00:00:00.000Z",
- view: { metadata, status: "working", taskId: "task-1" },
- }),
- ).toEqual([
- {
- eventId: "work:task:started",
- kind: "work.started",
- startedAt: "2026-01-01T00:00:00.000Z",
- work: workIdentity,
- },
- ]);
- });
-
- it("does nothing without activity observation", () => {
- expect(
- projectTaskActivity({
- 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",
- ({ expected, view }) => {
- expect(formatTaskNotification(view)).toBe(expected);
- },
- );
-
- it("reports cancellation without inventing output", () => {
- const view = {
- metadata,
- status: "cancelled",
- taskId: "task-1",
- } satisfies TaskView;
-
- 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("uses the persisted child address after its continuation alias changes", async () => {
- const childSessionInbox = { sessionId: "original-child", version: 1 };
- await deliverTaskInputResponsesStep({
- answer: { ...answer, childSessionInbox },
- requestIds: ["req-1"],
- });
-
- expect(resumeSessionInbox).toHaveBeenCalledWith(
- childSessionInbox,
- expect.objectContaining({
- payload: { inputResponses: [{ optionId: "approve", requestId: "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,
- auth: {
- attributes: { private: "channel-only" },
- authenticator: "test",
- principalId: "bob",
- principalType: "user",
- },
- 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" }],
- responder: { authenticator: "test", principalId: "bob", principalType: "user" },
- }),
- 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,
- auth: {
- attributes: { private: "channel-only" },
- authenticator: "test",
- principalId: "bob",
- principalType: "user",
- },
- 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" }],
- { authenticator: "test", principalId: "bob", principalType: "user" },
- );
- });
-});
-
-describe("notifyTaskParent", () => {
- 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 notifyTaskParent({ 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",
- });
- });
-});
-
-describe("notifyTaskParent", () => {
- const notification = {
- token: "parent-token",
- view: {
- taskId: "task-1",
- metadata,
- status: "completed" as const,
- lastOutput: { type: "result" as const, data: "done" },
- },
- };
-
- it("preserves the payload and deduplication identity", async () => {
- await notifyTaskParent(notification);
- expect(resumeSessionInbox).toHaveBeenCalledExactlyOnceWith(notification.token, {
- kind: "send",
- payload: {
- message: "Background task task-1 (reviewer) is completed.\n\nResult:\ndone",
- task: { views: [notification.view] },
- },
- taskDeliveryId: "task-1:ready:completed",
- });
- });
-
- it.each([
- new HookNotFoundError("parent-token"),
- new Error("delivery failed", { cause: new RunExpiredError("parent ended") }),
- ])("tolerates an ended parent", async (error) => {
- const logs = captureLogRecords();
- vi.mocked(resumeSessionInbox).mockRejectedValueOnce(error);
- await expect(notifyTaskParent(notification)).resolves.toBeUndefined();
- expect(logs.records).toContainEqual(
- expect.objectContaining({
- level: "warn",
- message: "task notification target is gone; the parent session already ended",
- }),
- );
- });
-
- it("propagates transient delivery failures so the durable step can retry", async () => {
- const error = new Error("storage unavailable");
- vi.mocked(resumeSessionInbox).mockRejectedValueOnce(error);
- await expect(notifyTaskParent(notification)).rejects.toBe(error);
- });
-});
diff --git a/packages/eve/src/execution/tasks/child/notify.ts b/packages/eve/src/execution/tasks/child/notify.ts
deleted file mode 100644
index bd734d3ea..000000000
--- a/packages/eve/src/execution/tasks/child/notify.ts
+++ /dev/null
@@ -1,240 +0,0 @@
-import type { ActivityObserverConfig, SessionAuthContext, SessionCommand } from "#channel/types.js";
-import { submitActivity } from "#execution/submit-activity.js";
-import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
-import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
-import {
- resumeWorkflowToolRunAnswers,
- toToolInputResponseResponder,
-} 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 {
- WorkflowToolAuthorizationRequest,
- WorkflowToolRunRequestMessage,
- WorkflowToolRunReport,
-} from "#execution/tools/workflow/messages.js";
-import { workflowToolRunInputRequests } from "#execution/tools/workflow/owner-inbox.js";
-import { formatTaskNotification, formatTaskOutput } from "#tasks/notification.js";
-import {
- isTerminalTaskStatus,
- taskAuthorizationRequestId,
- type TaskAgentRequestDelivery,
- type TaskAuthorizationEventDelivery,
- type TaskInputRequestDelivery,
- type TaskView,
- type TaskInboundAnswerInput,
-} from "#tasks/types.js";
-
-const log = createLogger("execution.tasks.run");
-
-type TaskParentNotification =
- | {
- readonly view: TaskView;
- readonly update?: { readonly report: WorkflowToolRunReport; readonly index: number };
- }
- | {
- readonly taskId: string;
- readonly request: WorkflowToolRunRequestMessage;
- };
-
-/** Delivers task outcomes, updates, and requests through the parent's session inbox. */
-export async function notifyTaskParent(
- input: TaskParentNotification & { readonly token: string },
-): Promise<void> {
- "use step";
-
- const command = taskNotificationCommand(input);
- try {
- await resumeSessionInbox(input.token, command);
- } catch (error) {
- if (!isTaskWorkflowTargetGone(error)) throw error;
- log.warn("task notification target is gone; the parent session already ended", {
- taskDeliveryId: command.taskDeliveryId,
- });
- }
-}
-
-function taskNotificationCommand(
- input: TaskParentNotification,
-): Extract<SessionCommand, { readonly kind: "send" }> {
- if ("view" in input) {
- const { view, update } = input;
- if (update !== undefined) {
- return {
- kind: "send",
- payload: {
- message: `Background task ${view.taskId} (${view.metadata.name}) update: ${formatTaskOutput(update.report.update)}`,
- },
- taskDeliveryId: `${view.taskId}:update:${view.taskId}:${update.index}:${update.report.from.callId}`,
- };
- }
- const payload: { message: string; task?: { views: readonly TaskView[] } } = {
- message: formatTaskNotification(view),
- };
- if (isTerminalTaskStatus(view.status)) payload.task = { views: [view] };
- return {
- kind: "send",
- payload,
- taskDeliveryId: `${view.taskId}:ready:${view.status}`,
- };
- }
-
- const { taskId, request: message } = input;
- const { request } = message;
- if (request.kind === "authorization-request") return taskAuthorizationCommand(request, taskId);
- if (request.kind === "agent-invoke" || request.kind === "agent-settled") {
- const delivery: TaskAgentRequestDelivery = { replyTo: message.replyTo, request, taskId };
- const invocationId =
- request.kind === "agent-invoke" ? request.invocationId : `${request.result.callId}:settled`;
- return {
- kind: "send",
- payload: { task: { agentRequests: [delivery] } },
- taskDeliveryId: `${taskId}:agent:${message.from.runId}:${invocationId}`,
- };
- }
-
- const coordinates = message.requestCoordinates ?? message.from;
- const delivery: TaskInputRequestDelivery = {
- replyTo: message.replyTo,
- requests: workflowToolRunInputRequests(message),
- sequence: coordinates.sequence,
- stepIndex: coordinates.stepIndex,
- taskId,
- turnId: coordinates.turnId,
- };
- return {
- kind: "send",
- payload: { task: { inputRequests: [delivery] } },
- taskDeliveryId: `${taskId}:input:${coordinates.turnId}:${coordinates.stepIndex}:${coordinates.sequence}`,
- };
-}
-
-function taskAuthorizationCommand(
- request: WorkflowToolAuthorizationRequest,
- taskId: string,
-): Extract<SessionCommand, { readonly kind: "send" }> {
- const { event: hookPayload } = request;
- const data = hookPayload.event.data;
- const payload: {
- message?: string;
- task: { authorizationEvents: TaskAuthorizationEventDelivery[] };
- } = { task: { authorizationEvents: [{ hookPayload, taskId }] } };
- if (hookPayload.event.type === "authorization.required") {
- payload.message = `Background task ${taskId} needs authorization.`;
- }
- return {
- kind: "send",
- payload,
- taskDeliveryId: `${taskId}:authorization:${hookPayload.event.type}:${data.turnId}:${data.stepIndex}:${data.sequence}:${taskAuthorizationRequestId(hookPayload.event)}`,
- };
-}
-
-/** Emits task activity without storing a second task-state record. */
-export async function emitTaskActivityStep(input: {
- readonly activityObserver?: ActivityObserverConfig;
- readonly view: TaskView;
-}): Promise<void> {
- "use step";
-
- const events = projectTaskActivity({
- activityObserver: input.activityObserver,
- settledAt: new Date().toISOString(),
- view: input.view,
- });
- await submitActivity({ events, sink: input.activityObserver?.sink });
-}
-
-export function projectTaskActivity(input: {
- readonly activityObserver: ActivityObserverConfig | undefined;
- readonly settledAt: string;
- readonly view: TaskView;
-}): readonly ActivityEventV1[] {
- const work = input.activityObserver?.workIdentity;
- if (work === undefined) return [];
- const status = input.view.status;
- if (status === "working") {
- return [
- {
- eventId: `${work.id}:started`,
- kind: "work.started",
- startedAt: input.settledAt,
- work,
- },
- ];
- }
- if (status !== "completed" && status !== "failed" && status !== "cancelled") return [];
- return [
- {
- eventId: `${work.id}:settled:${status}`,
- kind: "work.settled",
- outcome: status,
- settledAt: input.settledAt,
- workId: work.id,
- },
- ];
-}
-
-/**
- * Forwards answered input to the blocked child.
- *
- * The task run performs this itself so the child unblocks and the
- * view leaves `input_required` under one durable decision. Returns
- * `unreachable` when the child hook is already gone, which leaves the
- * outstanding batch untouched rather than reporting a task as working
- * when nothing received the answer.
- */
-export async function deliverTaskInputResponsesStep(input: {
- readonly answer: TaskInboundAnswerInput;
- readonly answerHook?: AnswerHookRoute;
- readonly requestIds: readonly string[];
-}): Promise<"delivered" | "unreachable"> {
- "use step";
-
- const answered = new Set(input.requestIds);
- const command: SessionCommand = {
- auth: input.answer.auth as SessionAuthContext | null | undefined,
- kind: "send",
- payload: {
- inputResponses: input.answer.inputResponses.filter((response) =>
- answered.has(response.requestId),
- ),
- },
- taskDeliveryId: `${input.answer.taskId}:${[...input.requestIds].sort().join(",")}`,
- };
- try {
- if (input.answer.childResponseUrl !== undefined) {
- const responder = input.answer.responder ?? toToolInputResponseResponder(command.auth);
- const response = await fetch(input.answer.childResponseUrl, {
- body: JSON.stringify({ inputResponses: command.payload.inputResponses, responder }),
- headers: { "content-type": "application/json" },
- method: "POST",
- redirect: "error",
- });
- if (response.status === 404) return "unreachable";
- if (!response.ok)
- throw new Error(`Remote task input delivery failed with HTTP ${response.status}.`);
- } else if (input.answerHook !== undefined) {
- await resumeWorkflowToolRunAnswers(
- input.answer.childContinuationToken,
- command.payload.inputResponses,
- input.answer.responder ?? toToolInputResponseResponder(command.auth),
- );
- } else {
- await resumeSessionInbox(
- input.answer.childSessionInbox ?? input.answer.childContinuationToken,
- command,
- );
- }
- return "delivered";
- } catch (error) {
- if (isTaskWorkflowTargetGone(error)) {
- log.warn("task input answer target is gone; the child turn already ended", {
- taskId: input.answer.taskId,
- });
- return "unreachable";
- }
- throw error;
- }
-}
diff --git a/packages/eve/src/execution/tasks/parent/control-shared.ts b/packages/eve/src/execution/tasks/parent/control-shared.ts
deleted file mode 100644
index 57a4a9565..000000000
--- a/packages/eve/src/execution/tasks/parent/control-shared.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import type { HarnessSession as RuntimeSession } from "#harness/types.js";
-import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#shared/action-types.js";
-import { taskViewsToJson } from "#tasks/json.js";
-import { getBackgroundTasks, type BackgroundWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-import type { TaskView } from "#tasks/types.js";
-
-/**
- * Result and lookup helpers shared by the task-control executors
- * (`task_cancel` in the dispatch module,
- * task controls in their own).
- */
-
-/** Resolves owned index entries, or the ids this session does not own. */
-export function lookupTaskEntries(
- session: RuntimeSession,
- taskIds: readonly string[],
-):
- | { readonly entries: BackgroundWorkflowToolRun[]; readonly kind: "found" }
- | { readonly kind: "unknown"; readonly unknown: string[] } {
- const entries: BackgroundWorkflowToolRun[] = [];
- const unknown: string[] = [];
- const tasks = getBackgroundTasks(session.state);
- for (const taskId of taskIds) {
- const entry = tasks.get(taskId)?.run;
- if (entry === undefined) {
- unknown.push(taskId);
- } else {
- entries.push(entry);
- }
- }
- return unknown.length > 0 ? { kind: "unknown", unknown } : { entries, kind: "found" };
-}
-
-/** One successful task-control result carrying full task views. */
-export function createTaskViewsResult(
- action: RuntimeToolCallActionRequest,
- views: readonly TaskView[],
-): RuntimeActionResult {
- return {
- callId: action.callId,
- kind: "tool-result",
- output: taskViewsToJson(views),
- toolName: action.toolName,
- };
-}
-
-/** One task-control error the model can act on. */
-export function createTaskControlError(
- action: RuntimeToolCallActionRequest,
- message: string,
-): RuntimeActionResult {
- return {
- callId: action.callId,
- isError: true,
- kind: "tool-result",
- output: { message },
- toolName: action.toolName,
- };
-}
-
-/** The ownership error for ids outside this session's task index. */
-export function createUnknownTasksError(
- action: RuntimeToolCallActionRequest,
- unknown: readonly string[],
-): RuntimeActionResult {
- return createTaskControlError(
- action,
- `Unknown task ids: ${unknown.join(", ")}. Tasks belong to the session that created them.`,
- );
-}
diff --git a/packages/eve/src/execution/tasks/parent/delegate.test.ts b/packages/eve/src/execution/tasks/parent/delegate.test.ts
deleted file mode 100644
index 84ecfe587..000000000
--- a/packages/eve/src/execution/tasks/parent/delegate.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";
-import { sendTaskCommandToOwner } from "#execution/tasks/parent/run-parent.js";
-
-vi.mock("#execution/tasks/parent/run-parent.js", () => ({
- sendTaskCommandToOwner: vi.fn(),
-}));
-
-const mocks = vi.hoisted(() => ({ getRun: vi.fn() }));
-vi.mock("#internal/workflow/runtime.js", () => mocks);
-
-describe("task readiness", () => {
- beforeEach(() => {
- vi.resetAllMocks();
- vi.mocked(sendTaskCommandToOwner).mockResolvedValue({ runId: "run-owner" });
- });
-
- it("acknowledges a generic background task after indexing", async () => {
- await acknowledgeDelegatedTasksStep({
- tasks: [{ taskId: "task-1", taskInboxToken: "task-token", taskRunId: "run-1" }],
- });
- expect(sendTaskCommandToOwner).toHaveBeenCalledWith(
- expect.objectContaining({ command: { kind: "ready" }, taskInboxToken: "task-token" }),
- );
- });
- it.each(["completed", "cancelled", "failed", "running"] as const)(
- "handles a missing readiness hook when the run is %s",
- async (status) => {
- vi.mocked(sendTaskCommandToOwner).mockResolvedValue(undefined);
- mocks.getRun.mockReturnValue({ status: Promise.resolve(status) });
- const ready = acknowledgeDelegatedTasksStep({
- tasks: [{ taskId: "task-1", taskInboxToken: "task-token", taskRunId: "run-1" }],
- });
- if (status === "completed" || status === "cancelled")
- await expect(ready).resolves.toBeUndefined();
- else await expect(ready).rejects.toThrow("did not accept its readiness command");
- },
- );
-});
diff --git a/packages/eve/src/execution/tasks/parent/delegate.ts b/packages/eve/src/execution/tasks/parent/delegate.ts
deleted file mode 100644
index b07b117e8..000000000
--- a/packages/eve/src/execution/tasks/parent/delegate.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * Session-owned invocation identity, admission acknowledgement, and dispatch rejection.
- * The parent commits its session index before releasing the workflow body.
- */
-import { getRun } from "#internal/workflow/runtime.js";
-import type { HarnessSession } from "#harness/types.js";
-import type {
- BackgroundWorkflowToolRun,
- TaskAgentDispatchContext,
-} from "#harness/workflow-tool-runs.js";
-import { sendTaskCommand, sendTaskCommandToOwner } from "#execution/tasks/parent/run-parent.js";
-import type { JsonValue } from "#shared/json.js";
-import { deriveTaskInboxToken, deriveTaskId } from "#tasks/task-id.js";
-import type { TaskMetadata } from "#tasks/types.js";
-import type { ContextReader } from "#context/key.js";
-import {
- SessionDynamicSubagentSelectionsKey,
- TurnDynamicSubagentSelectionsKey,
- type SessionAuth,
-} from "#context/keys.js";
-
-export function createTaskAgentDispatchContext(
- ctx: ContextReader,
- auth: SessionAuth,
-): TaskAgentDispatchContext {
- return {
- auth,
- sessionDynamicSubagentSelections: ctx.get(SessionDynamicSubagentSelectionsKey),
- turnDynamicSubagentSelections: ctx.get(TurnDynamicSubagentSelectionsKey),
- };
-}
-
-export type BackgroundTaskDraft = Omit<BackgroundWorkflowToolRun, "address"> & {
- readonly address: { readonly hookToken: string };
-};
-
-/** Derives the replay-stable task identity before its owning run is started. */
-export function prepareBackgroundTask(input: {
- readonly callId: string;
- readonly dispatchContext: TaskAgentDispatchContext;
- readonly metadata: TaskMetadata;
- readonly parentSessionId: string;
- readonly parentStepIndex?: number;
- readonly parentTurnId: string;
- readonly session: HarnessSession;
-}): BackgroundTaskDraft {
- const taskId = deriveTaskId({
- callId: input.callId,
- parentSessionId: input.parentSessionId,
- parentTurnId: input.parentTurnId,
- });
- return {
- callId: input.callId,
- toolName: input.metadata.name,
- lifetime: "session",
- origin: { turnId: input.parentTurnId, stepIndex: input.parentStepIndex ?? 0 },
- address: {
- hookToken: deriveTaskInboxToken({
- parentContinuationToken: input.session.continuationToken,
- taskId,
- }),
- },
- task: { dispatchContext: input.dispatchContext, metadata: input.metadata, taskId },
- };
-}
-
-/** Releases task events only after the parent session index committed. */
-export async function acknowledgeDelegatedTasksStep(input: {
- readonly tasks: readonly {
- readonly taskInboxToken: string;
- readonly taskId: string;
- readonly taskRunId: string;
- }[];
-}): Promise<void> {
- "use step";
-
- for (const task of input.tasks) {
- const owner = await sendTaskCommandToOwner({
- command: { kind: "ready" },
- taskInboxToken: task.taskInboxToken,
- retryUnreachable: { attempts: 20, delayMs: 250 },
- });
- if (owner !== undefined) continue;
- const status = await getRun(task.taskRunId).status;
- if (status === "completed" || status === "cancelled") continue;
- throw new Error(`Task run "${task.taskId}" did not accept its readiness command.`);
- }
-}
-
-/** Silently terminates a task whose child dispatch failed before parent indexing. */
-export async function rejectDelegatedDispatch(input: {
- readonly error: JsonValue;
- readonly task: BackgroundWorkflowToolRun;
-}): Promise<void> {
- await sendTaskCommand({
- command: { data: input.error, kind: "reject-dispatch" },
- taskInboxToken: input.task.address.hookToken,
- retryUnreachable: { attempts: 20, delayMs: 250 },
- });
-}
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.test.ts b/packages/eve/src/execution/tasks/parent/dispatch.test.ts
deleted file mode 100644
index d21450919..000000000
--- a/packages/eve/src/execution/tasks/parent/dispatch.test.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-import { getBackgroundTasks } from "#harness/workflow-tool-runs.js";
-import type { HarnessSession } from "#harness/types.js";
-import { WORKFLOW_CANCELLATION_SETTLE_MS } from "#execution/tools/workflow/cancellation-policy.js";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import {
- cancelOwnedTask,
- executeTaskControlAction,
- isTaskControlAction,
-} from "#execution/tasks/parent/dispatch.js";
-import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";
-import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
-
-const { cancelRun, getRun } = vi.hoisted(() => ({
- cancelRun: vi.fn(),
- getRun: vi.fn(),
-}));
-
-vi.mock("#execution/tasks/parent/run-parent.js", () => ({
- sendTaskCommand: vi.fn(),
-}));
-vi.mock("#execution/session-inbox/resume.js", () => ({ resumeSessionInbox: vi.fn() }));
-vi.mock("#internal/workflow/runtime.js", () => ({
- cancelRun,
- getRun,
- getWorld: vi.fn(() => ({})),
-}));
-
-const entry = {
- callId: "task-1",
- toolName: "export",
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "tool", name: "export" },
- taskId: "task-1",
- },
-} as const;
-
-describe("task cancellation", () => {
- beforeEach(() => {
- vi.resetAllMocks();
- vi.useFakeTimers();
- vi.mocked(sendTaskCommand).mockResolvedValue("delivered");
- getRun.mockReturnValue({ status: Promise.resolve("completed") });
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("cancels a live task despite an unrelated malformed retained result", async () => {
- const session: HarnessSession = {
- agent: { modelReference: { id: "test" }, system: "", tools: [] },
- compaction: { recentWindowSize: 4, threshold: 100_000 },
- history: [],
- continuationToken: "parent",
- sessionId: "parent-session",
- state: {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- ...entry,
- callId: "old",
- task: { ...entry.task, taskId: "old", outcome: { status: "completed" } },
- },
- entry,
- ],
- },
- },
- };
- const cancelled = await executeTaskControlAction({
- action: {
- kind: "tool-call",
- callId: "cancel",
- toolName: "task_cancel",
- input: { taskIds: [entry.task.taskId] },
- },
- session,
- });
- expect(getBackgroundTasks(cancelled.session.state).get(entry.task.taskId)).toMatchObject({
- status: "cancelled",
- });
- expect(sendTaskCommand).toHaveBeenCalledExactlyOnceWith({
- command: { kind: "cancel" },
- taskInboxToken: entry.address.hookToken,
- });
- });
-
- it("signals cancellation before stopping task-owned work", async () => {
- const cancelled = cancelOwnedTask({ entry });
- await vi.runAllTimersAsync();
- await cancelled;
- expect(sendTaskCommand).toHaveBeenNthCalledWith(1, {
- command: { kind: "cancel" },
- taskInboxToken: "task-token",
- });
- expect(cancelRun).not.toHaveBeenCalled();
- expect(resumeSessionInbox).not.toHaveBeenCalled();
- });
-
- it("retries child cancellation after the cancelled task's inbox has closed", async () => {
- const cancelOwnedWork = vi
- .fn()
- .mockRejectedValueOnce(new Error("Child cancellation failed"))
- .mockResolvedValueOnce(undefined);
- const session = { sessionId: "parent-session" } as Parameters<
- typeof cancelOwnedTask
- >[0]["session"];
- await expect(cancelOwnedTask({ cancelOwnedWork, entry, session })).rejects.toThrow(
- "Child cancellation failed",
- );
- expect(resumeSessionInbox).not.toHaveBeenCalled();
-
- vi.mocked(sendTaskCommand).mockResolvedValue("unreachable");
- await expect(cancelOwnedTask({ cancelOwnedWork, entry, session })).resolves.toMatchObject({
- status: "cancelled",
- });
- expect(cancelOwnedWork).toHaveBeenCalledTimes(2);
- expect(resumeSessionInbox).toHaveBeenCalledTimes(1);
- expect(cancelOwnedWork.mock.invocationCallOrder[1]).toBeLessThan(
- vi.mocked(resumeSessionInbox).mock.invocationCallOrder[0]!,
- );
- });
-
- it("leaves child work untouched when completion won the cancellation race", async () => {
- const cancelOwnedWork = vi.fn();
- await cancelOwnedTask({
- cancelOwnedWork,
- entry: {
- ...entry,
- task: {
- ...entry.task,
- outcome: {
- lastOutput: { type: "result", data: "Finished" },
- status: "completed",
- },
- },
- },
- });
- expect(cancelOwnedWork).not.toHaveBeenCalled();
- });
-
- it("allows cleanup lasting longer than one second without force-stopping or duplicating delivery", async () => {
- getRun.mockReturnValue({ status: Promise.resolve("running") });
- const cancelled = cancelOwnedTask({ entry });
- await vi.advanceTimersByTimeAsync(2_000);
- expect(cancelRun).not.toHaveBeenCalled();
- getRun.mockReturnValue({ status: Promise.resolve("completed") });
- await vi.advanceTimersByTimeAsync(250);
- await cancelled;
- expect(cancelRun).not.toHaveBeenCalled();
- expect(resumeSessionInbox).not.toHaveBeenCalled();
- });
-
- it("hard-cancels a task run that does not unwind cooperatively", async () => {
- getRun.mockReturnValue({ status: Promise.resolve("running") });
-
- const cancelled = cancelOwnedTask({ entry });
- await vi.runAllTimersAsync();
- await cancelled;
-
- expect(cancelRun).toHaveBeenCalledWith({}, "task-run", {
- cancelReason: "Task task-1 was cancelled.",
- });
- });
-
- it("preserves the committed parent notification when cancellation stops a slow task run", async () => {
- const view = {
- metadata: entry.task.metadata,
- status: "cancelled",
- taskId: entry.task.taskId,
- } as const;
- getRun.mockReturnValue({ status: Promise.resolve("running") });
- const session = { sessionId: "parent-session" } as Parameters<
- typeof cancelOwnedTask
- >[0]["session"];
- const cancelled = cancelOwnedTask({ entry, session });
-
- await vi.advanceTimersByTimeAsync(WORKFLOW_CANCELLATION_SETTLE_MS - 1);
- expect(cancelRun).not.toHaveBeenCalled();
- expect(resumeSessionInbox).not.toHaveBeenCalled();
- await vi.advanceTimersByTimeAsync(1);
- await expect(cancelled).resolves.toEqual(view);
-
- expect(cancelRun).toHaveBeenCalledTimes(1);
- expect(resumeSessionInbox).toHaveBeenCalledExactlyOnceWith("eve:session:parent-session:inbox", {
- kind: "send",
- payload: {
- message: "Background task task-1 (export) is cancelled.",
- task: { views: [view] },
- },
- taskDeliveryId: "task-1:ready:cancelled",
- });
- expect(vi.mocked(cancelRun).mock.invocationCallOrder[0]).toBeLessThan(
- vi.mocked(resumeSessionInbox).mock.invocationCallOrder[0]!,
- );
- });
-
- it("retries the parent notification after the cancelled task inbox is gone", async () => {
- const view = {
- metadata: entry.task.metadata,
- status: "cancelled",
- taskId: entry.task.taskId,
- } as const;
- getRun.mockReturnValue({ status: Promise.resolve("running") });
- vi.mocked(resumeSessionInbox).mockRejectedValueOnce(new Error("temporary delivery failure"));
- const session = { sessionId: "parent-session" } as Parameters<
- typeof cancelOwnedTask
- >[0]["session"];
- const cancelled = cancelOwnedTask({ entry, session });
- const failed = expect(cancelled).rejects.toThrow("temporary delivery failure");
- await vi.runAllTimersAsync();
- await failed;
-
- vi.mocked(sendTaskCommand).mockResolvedValue("unreachable");
- getRun.mockReturnValue({ status: Promise.resolve("cancelled") });
- await expect(cancelOwnedTask({ entry, session })).resolves.toEqual(view);
- expect(cancelRun).toHaveBeenCalledTimes(1);
- expect(resumeSessionInbox).toHaveBeenCalledTimes(2);
- expect(vi.mocked(resumeSessionInbox).mock.calls[1]).toEqual(
- vi.mocked(resumeSessionInbox).mock.calls[0],
- );
- });
-});
-
-describe("task control actions", () => {
- it.each([
- ["task_cancel", true],
- ["task_update", false],
- ])("recognizes %s as a task control: %s", (toolName, expected) => {
- expect(isTaskControlAction({ callId: "call-1", input: {}, kind: "tool-call", toolName })).toBe(
- expected,
- );
- });
-});
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.ts
deleted file mode 100644
index 224cb6f3e..000000000
--- a/packages/eve/src/execution/tasks/parent/dispatch.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import type { HarnessSession as RuntimeSession } from "#harness/types.js";
-import {
- createTaskControlError,
- createTaskViewsResult,
- createUnknownTasksError,
- lookupTaskEntries,
-} from "#execution/tasks/parent/control-shared.js";
-import {
- recordWorkflowTaskView,
- readWorkflowTaskView,
- type BackgroundWorkflowToolRun,
-} from "#harness/workflow-tool-runs.js";
-import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";
-import { notifyTaskParent } from "#execution/tasks/child/notify.js";
-import { sessionCommandHookToken } from "#execution/session-inbox/address.js";
-import {
- cancelTaskOwnedWork,
- type TaskExecutorCancel,
-} from "#execution/tasks/parent/task-cancel.js";
-import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#shared/action-types.js";
-import { type TaskView } from "#tasks/types.js";
-import { TASK_CANCEL_TOOL_NAME, TASK_TOOL_NAMES } from "#tools/framework/task-contract.js";
-
-export function isTaskControlAction(action: RuntimeToolCallActionRequest): boolean {
- return action.kind === "tool-call" && TASK_TOOL_NAMES.has(action.toolName);
-}
-
-export async function executeTaskControlAction(input: {
- readonly action: RuntimeToolCallActionRequest;
- readonly cancelOwnedWork?: TaskExecutorCancel;
- readonly serializedContext?: Record<string, unknown>;
- readonly session: RuntimeSession;
-}): Promise<{
- readonly result: RuntimeActionResult;
- readonly session: RuntimeSession;
-}> {
- const { action } = input;
- let session = input.session;
- const taskIds = readTaskIds(action.input);
- if (taskIds === undefined || taskIds.length === 0) {
- return {
- result: createTaskControlError(action, "Provide a non-empty `taskIds` array."),
- session,
- };
- }
- const lookup = lookupTaskEntries(session, taskIds);
- if (lookup.kind === "unknown") {
- return { result: createUnknownTasksError(action, lookup.unknown), session };
- }
- if (action.toolName !== TASK_CANCEL_TOOL_NAME) {
- return {
- result: createTaskControlError(action, `Unsupported task control "${action.toolName}".`),
- session,
- };
- }
-
- const views: TaskView[] = [];
- for (const entry of lookup.entries) {
- const view = await cancelOwnedTask({
- cancelOwnedWork: input.cancelOwnedWork,
- entry,
- serializedContext: input.serializedContext,
- session,
- });
- session = { ...session, state: recordWorkflowTaskView(session.state, view).state };
- views.push(view);
- }
- return { result: createTaskViewsResult(action, views), session };
-}
-
-/** Cancels task-owned work; the caller records the outcome in the parent session. */
-export async function cancelOwnedTask(input: {
- readonly cancelOwnedWork?: TaskExecutorCancel;
- readonly entry: BackgroundWorkflowToolRun;
- readonly serializedContext?: Record<string, unknown>;
- readonly session?: RuntimeSession;
-}): Promise<TaskView> {
- const previous = readWorkflowTaskView(input.entry.task);
- if (previous !== undefined && previous.status !== "cancelled") return previous;
- const view: TaskView = previous ?? {
- metadata: input.entry.task.metadata,
- status: "cancelled",
- taskId: input.entry.task.taskId,
- };
- await sendTaskCommand({
- command: { kind: "cancel" },
- taskInboxToken: input.entry.address.hookToken,
- });
- // The task inbox may be closed after an earlier cancellation committed but
- // failed to stop its child. Retrying must still finish that cancellation.
- await cancelTaskOwnedWork({
- cancelOwnedWork: input.cancelOwnedWork,
- entry: input.entry,
- serializedContext: input.serializedContext,
- session: input.session,
- });
- if (input.session !== undefined) {
- // Queue settlement even when the child cannot report. The parent records
- // this control result before routing queued notifications; late outcomes lose.
- await notifyTaskParent({
- token: sessionCommandHookToken(input.session.sessionId),
- view,
- });
- }
- return view;
-}
-
-function readTaskIds(input: Record<string, unknown>): readonly string[] | undefined {
- const value = input.taskIds;
- if (!Array.isArray(value)) return undefined;
- return value.filter((id): id is string => typeof id === "string" && id.trim() !== "");
-}
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
deleted file mode 100644
index 6d3be38ad..000000000
--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts
+++ /dev/null
@@ -1,366 +0,0 @@
-import { recordWorkflowTaskView, getBackgroundTasks } from "#harness/workflow-tool-runs.js";
-import { createTestSessionState } from "#internal/testing/session-state.js";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { ContextContainer } from "#context/container.js";
-import { serializeContext } from "#context/serialize.js";
-import { readDurableSession } from "#execution/durable-session-store.js";
-import {
- recordTerminalTaskViewsStep,
- recordTaskInputRequestStep,
-} from "#execution/tasks/parent/hitl-proxy-steps.js";
-import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
-import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";
-import {
- getProxyInputRequests,
- upsertProxyInputRequestState,
-} from "#harness/proxy-input-requests.js";
-
-const flushInstrumentation = vi.hoisted(() => vi.fn());
-const publishBackgroundTaskSettlements = vi.hoisted(() => vi.fn());
-
-vi.mock("#execution/durable-session-store.js", async (importOriginal) => ({
- ...(await importOriginal()),
- readDurableSession: vi.fn(),
-}));
-vi.mock("#instrumentation/runtime.js", () => ({
- bindSessionInstrumentation: vi.fn(),
-}));
-vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({
- getCompiledRuntimeAgentBundle: vi.fn(),
-}));
-vi.mock("#shared/input.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#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 = createTestSessionState({
- continuationToken: "parent-token",
- emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },
- hasProxyInputRequests: false,
- sessionId: "parent-session",
- version: 1,
-});
-const remoteReplyTo = "eve:eve:op:0123456789abcdef0123456789abcdef";
-
-describe("recordTaskInputRequestStep", () => {
- beforeEach(() => {
- vi.resetAllMocks();
- vi.mocked(readDurableSession).mockReturnValue({
- agent: { system: "" },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- state: {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task-1",
- toolName: "export",
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "tool", name: "export" },
- taskId: "task-1",
- },
- },
- ],
- },
- },
- });
- });
-
- it("records a generic workflow answer route for a parent-owned task", async () => {
- 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",
- question: {},
- taskId: "task-1",
- });
- });
-
- it("rejects a late input request after parent settlement", async () => {
- const session = readDurableSession(sessionState);
- vi.mocked(readDurableSession).mockReturnValue({
- ...session,
- state: recordWorkflowTaskView(session.state, {
- lastOutput: { data: "done", type: "result" },
- metadata: { kind: "tool", name: "export" },
- status: "completed",
- taskId: "task-1",
- }).state,
- });
-
- 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).mockReturnValue({
- agent: { system: "" },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- state: setAgentHandleStore(
- {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task-1",
- toolName: "export",
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "tool", name: "export" },
- taskId: "task-1",
- },
- },
- ],
- },
- },
- {
- 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" },
- };
-
- 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", () => {
- beforeEach(() => {
- vi.resetAllMocks();
- vi.mocked(bindSessionInstrumentation).mockReturnValue({
- flush: flushInstrumentation,
- publishBackgroundTaskSettlements,
- } as never);
- });
-
- it("records an owned outcome and releases its agent lease and input routes", async () => {
- vi.mocked(readDurableSession).mockReturnValue({
- agent: { system: "" },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- state: setAgentHandleStore(
- {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task-1",
- toolName: { agentId: "agent-1", kind: "subagent", mode: "local", name: "research" }
- .name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: {
- agentId: "agent-1",
- kind: "subagent",
- mode: "local",
- name: "research",
- },
- taskId: "task-1",
- },
- },
- ],
- },
- },
- {
- 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 current = readDurableSession(sessionState);
- vi.mocked(readDurableSession).mockReturnValue({
- ...current,
- state: upsertProxyInputRequestState({
- state: current.state,
- forChildContinuationToken: "question-hook",
- entries: [
- [
- "task-1:question",
- { childContinuationToken: "question-hook", kind: "question", taskId: "task-1" },
- ],
- ],
- }),
- });
- const result = await recordTerminalTaskViewsStep({
- serializedContext: {},
- sessionState,
- views: [view],
- });
- const state = result.sessionState.snapshot.session.state;
-
- expect(getBackgroundTasks(state).query()[0]?.run.task.outcome).toEqual({
- status: view.status,
- lastOutput: view.lastOutput,
- });
- expect(getProxyInputRequests(state).size).toBe(0);
- expect(result.sessionState.hasProxyInputRequests).toBe(false);
- expect(getAgentHandleStore(state)?.handles).toEqual([
- expect.objectContaining({ phase: "available" }),
- ]);
- expect(result.serializedContext).toEqual({});
- expect(result.subagentCompletions).toHaveLength(1);
-
- vi.mocked(readDurableSession).mockReturnValue(result.sessionState.snapshot.session);
- const repeated = await recordTerminalTaskViewsStep({
- serializedContext: {},
- sessionState: result.sessionState,
- views: [view],
- });
- expect(repeated.subagentCompletions).toEqual([]);
- expect(repeated.views).toEqual([]);
- });
-
- it("settles instrumentation from an accepted terminal task view", async () => {
- const bundle = {
- compiledArtifactsSource: { kind: "bundled" },
- nodeId: "__root__",
- turnAgent: { id: "parent-agent" },
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(bundle);
- const context = new ContextContainer();
- context.set(BundleKey, bundle);
- const serializedContext = serializeContext(context);
- vi.mocked(readDurableSession).mockReturnValue({
- agent: { system: "" },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- state: {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task-1",
- toolName: "export",
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "tool", name: "export" },
- taskId: "task-1",
- },
- },
- ],
- },
- },
- });
- const view = {
- lastOutput: { data: "done", type: "result" as const },
- metadata: { kind: "tool", name: "export" },
- status: "completed" as const,
- taskId: "task-1",
- };
-
- const result = await recordTerminalTaskViewsStep({
- serializedContext,
- sessionState,
- views: [view],
- });
-
- expect(result.subagentCompletions).toEqual([]);
- expect(bindSessionInstrumentation).toHaveBeenCalledWith({
- agentName: "parent-agent",
- ctx: expect.any(ContextContainer),
- rootSessionId: "parent-session",
- sessionId: "parent-session",
- });
- expect(publishBackgroundTaskSettlements).toHaveBeenCalledWith({
- acceptedAtMs: expect.any(Number),
- views: [view],
- });
- expect(flushInstrumentation).toHaveBeenCalledOnce();
- expect(result.serializedContext).not.toBe(serializedContext);
- });
-});
diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
deleted file mode 100644
index f5069adc2..000000000
--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import type { SubagentCompletedStreamEvent } from "#protocol/message.js";
-import { ActivityObserverKey } from "#context/keys.js";
-import { projectTaskActivity } from "#execution/tasks/child/notify.js";
-import { submitActivity } from "#execution/submit-activity.js";
-import { contextStorage } from "#context/container.js";
-import { deserializeContext, serializeContext } from "#context/serialize.js";
-import {
- type DurableSessionState,
- readDurableSession,
- replaceDurableSessionSnapshot,
-} from "#execution/durable-session-store.js";
-import { createTaskInputCapabilityToken } from "#execution/task-input-capability.js";
-import { createRemoteTaskInputCallbackUrl } from "#execution/workflow-callback-url.js";
-import {
- clearProxyInputRequestsForTask,
- createTaskInputRequestId,
- upsertProxyInputRequestState,
- type ProxyInputRequest,
-} from "#harness/proxy-input-requests.js";
-import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
-import { createLogger } from "#internal/logging.js";
-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-import { isInputRequest } from "#shared/input.js";
-import { getAgentHandleStore } from "#subagents/handles/store.js";
-import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";
-import { createEveTaskInputRoutePath } from "#protocol/routes.js";
-import { getBackgroundTasks, recordWorkflowTaskView } from "#harness/workflow-tool-runs.js";
-import type { TaskInputRequestDelivery, TaskView } from "#tasks/types.js";
-
-const log = createLogger("execution.tasks.parent");
-
-/** Validates and records a generic task-owned workflow request. */
-export async function recordTaskInputRequestStep(input: {
- readonly request: TaskInputRequestDelivery;
- readonly sessionState: DurableSessionState;
-}): Promise<
- | { readonly accepted: false; readonly sessionState: DurableSessionState }
- | {
- readonly accepted: true;
- readonly request: TaskInputRequestDelivery;
- readonly sessionState: DurableSessionState;
- }
-> {
- "use step";
-
- const durableSession = readDurableSession(input.sessionState);
- const task = getBackgroundTasks(durableSession.state).get(input.request.taskId);
- const requests = input.request.requests ?? [input.request.request];
- if (task?.status !== "working" || requests.length === 0 || !requests.every(isInputRequest)) {
- return { accepted: false, sessionState: input.sessionState };
- }
-
- 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,
- );
- 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 (request.kind === "question") {
- route.question = {
- ...(request.allowFreeform !== undefined && { allowFreeform: request.allowFreeform }),
- ...(request.options !== undefined && { options: [...request.options] }),
- };
- }
- if (remoteResponseUrl !== undefined) route.childResponseUrl = remoteResponseUrl;
- return [parentRequest.requestId, route] as const;
- });
- const state = upsertProxyInputRequestState({
- entries,
- 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,
- request,
- sessionState: replaceDurableSessionSnapshot({
- session: { ...durableSession, state },
- state: input.sessionState,
- }),
- };
-}
-
-/** Records child outcomes in the parent; its first terminal decision wins. */
-export async function recordTerminalTaskViewsStep(input: {
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
- readonly views: readonly TaskView[];
-}): Promise<{
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
- /** Newly recorded terminal outcomes eligible for model notification. */
- readonly views: readonly TaskView[];
- readonly subagentCompletions: readonly SubagentCompletedStreamEvent[];
-}> {
- "use step";
- const durableSession = readDurableSession(input.sessionState);
- let session = durableSession;
- const acceptedViews: TaskView[] = [];
- const firstOutcomeViews: TaskView[] = [];
- const subagentCompletions: SubagentCompletedStreamEvent[] = [];
- for (const view of input.views) {
- const entry = getBackgroundTasks(session.state).get(view.taskId)?.run;
- if (entry === undefined) continue;
- const recorded = recordWorkflowTaskView(session.state, view);
- session = { ...session, state: recorded.state };
- if (
- recorded.firstOutcome &&
- recorded.view.metadata.kind === "subagent" &&
- recorded.view.status === "completed"
- ) {
- subagentCompletions.push({
- type: "subagent.completed",
- data: {
- callId: entry.callId,
- subagentName: entry.toolName,
- output:
- typeof recorded.view.lastOutput.data === "string"
- ? recorded.view.lastOutput.data
- : JSON.stringify(recorded.view.lastOutput.data),
- },
- });
- }
- acceptedViews.push(recorded.view);
- if (recorded.firstOutcome) firstOutcomeViews.push(recorded.view);
- session = clearProxyInputRequestsForTask(session, view.taskId);
- session = applyTaskAgentHandleCommand(session, {
- kind: "release-owner",
- ownerId: view.taskId,
- }).session;
- }
- const serializedContext = await settleBackgroundTaskActions({
- serializedContext: input.serializedContext,
- session,
- views: acceptedViews,
- });
- const sessionState =
- session === durableSession
- ? input.sessionState
- : replaceDurableSessionSnapshot({ session, state: input.sessionState });
- return { serializedContext, sessionState, views: firstOutcomeViews, subagentCompletions };
-}
-
-async function settleBackgroundTaskActions(input: {
- readonly serializedContext: Record<string, unknown>;
- readonly session: Awaited<ReturnType<typeof readDurableSession>>;
- readonly views: readonly TaskView[];
-}): Promise<Record<string, unknown>> {
- if (input.views.length === 0) return input.serializedContext;
- try {
- const ctx = await deserializeContext(input.serializedContext);
- const observer = ctx.get(ActivityObserverKey);
- const settledAt = new Date().toISOString();
- const tasks = getBackgroundTasks(input.session.state);
- const events = input.views.flatMap((view) => {
- const entry = tasks.get(view.taskId)?.run;
- return projectTaskActivity({
- activityObserver:
- observer === undefined
- ? undefined
- : {
- sink: observer.sink,
- workIdentity: entry?.task.activityWorkIdentity,
- },
- settledAt,
- view,
- });
- });
- await submitActivity({ events, sink: observer?.sink });
- const bundle = ctx.get(BundleKey);
- if (bundle === undefined) return input.serializedContext;
- const instrumentation = bindSessionInstrumentation({
- agentName: bundle.turnAgent.id,
- ctx,
- rootSessionId: input.session.rootSessionId ?? input.session.sessionId,
- sessionId: input.session.sessionId,
- });
- if (instrumentation === undefined) return input.serializedContext;
- try {
- await contextStorage.run(ctx, () =>
- instrumentation.publishBackgroundTaskSettlements({
- acceptedAtMs: Date.now(),
- views: input.views,
- }),
- );
- } finally {
- await instrumentation.flush();
- }
- return serializeContext(ctx);
- } catch (error) {
- log.warn("failed to settle background task instrumentation", {
- error,
- sessionId: input.session.sessionId,
- taskIds: input.views.map((view) => view.taskId),
- });
- return input.serializedContext;
- }
-}
diff --git a/packages/eve/src/execution/tasks/parent/run-parent.ts b/packages/eve/src/execution/tasks/parent/run-parent.ts
deleted file mode 100644
index 3e530830f..000000000
--- a/packages/eve/src/execution/tasks/parent/run-parent.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import type { BackgroundWorkflowToolRunInput } from "#execution/tools/workflow/types.js";
-import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
-import {
- startWorkflowOnCurrentDeployment,
- workflowToolRunWorkflowReference,
- waitForCommandHookOwner,
-} from "#execution/workflow-runtime.js";
-import { resumeHook } from "#internal/workflow/runtime.js";
-import {
- type TaskCommand,
- type TaskCommandHookPayload,
- type TaskRunInboundPayload,
-} from "#tasks/types.js";
-
-/**
- * Node-side admission and cancellation for session-owned workflow invocations.
- *
- * 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
- * inside one durable boundary.
- */
-
-/** Starts a session-owned invocation through the common workflow entry. */
-export async function startTaskRun(input: BackgroundWorkflowToolRunInput): Promise<void> {
- await startWorkflowOnCurrentDeployment(workflowToolRunWorkflowReference, [input]);
-}
-
-/** Resolves the task run that won ownership of one replay-stable command token. */
-export async function waitForTaskCommandOwner(input: {
- readonly taskInboxToken: string;
-}): Promise<{ readonly runId: string }> {
- return await waitForCommandHookOwner(input.taskInboxToken);
-}
-
-/**
- * Submits one command to a task run.
- *
- * `unreachable` means the hook is not resumable — either the run
- * already finished and disposed it (the task is terminal; read the
- * final view) or, right after creation, the freshly started run has
- * not registered it yet. Senders racing that startup window pass
- * `retryUnreachable`; senders addressing an established task treat
- * `unreachable` as the terminal signal.
- */
-export async function sendTaskCommand(input: {
- readonly command: TaskCommand;
- readonly taskInboxToken: string;
- readonly retryUnreachable?: { readonly attempts: number; readonly delayMs: number };
-}): Promise<"delivered" | "unreachable"> {
- return (await sendTaskCommandToOwner(input)) === undefined ? "unreachable" : "delivered";
-}
-
-/** Delivers one command and returns the accepting task workflow's run id. */
-export async function sendTaskCommandToOwner(input: {
- readonly command: TaskCommand;
- readonly taskInboxToken: string;
- readonly retryUnreachable?: { readonly attempts: number; readonly delayMs: number };
-}): Promise<{ readonly runId: string } | undefined> {
- const payload: TaskCommandHookPayload = { command: input.command, kind: "task-command" };
- const attempts = Math.max(1, input.retryUnreachable?.attempts ?? 1);
- for (let attempt = 0; ; attempt += 1) {
- try {
- const owner = await resumeHook(input.taskInboxToken, payload);
- if (
- typeof owner !== "object" ||
- owner === null ||
- !("runId" in owner) ||
- typeof owner.runId !== "string"
- ) {
- throw new Error(`Task inbox hook "${input.taskInboxToken}" returned no owner run id.`);
- }
- return { runId: owner.runId };
- } catch (error) {
- if (!isTaskWorkflowTargetGone(error)) {
- throw error;
- }
- if (attempt + 1 >= attempts) {
- return undefined;
- }
- await new Promise((resolve) => setTimeout(resolve, input.retryUnreachable?.delayMs ?? 250));
- }
- }
-}
-
-/**
- * Hands one non-command inbound payload to a task run.
- *
- * Used for payloads the run must act on before it may record them —
- * today only answered input batches, which it forwards to the child
- * first. `unreachable` means the task already finished and disposed its
- * hook, so the payload is stale by definition.
- */
-export async function sendTaskInboundPayload(input: {
- readonly taskInboxToken: string;
- readonly payload: TaskRunInboundPayload;
-}): Promise<"delivered" | "unreachable"> {
- try {
- await resumeHook(input.taskInboxToken, input.payload);
- return "delivered";
- } catch (error) {
- if (!isTaskWorkflowTargetGone(error)) {
- throw error;
- }
- return "unreachable";
- }
-}
diff --git a/packages/eve/src/execution/tasks/parent/subagent-task-projection.ts b/packages/eve/src/execution/tasks/parent/subagent-task-projection.ts
deleted file mode 100644
index b4f9be82e..000000000
--- a/packages/eve/src/execution/tasks/parent/subagent-task-projection.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
-import type { loadContext } from "#context/container.js";
-import { createSubagentReceiptIdentity } from "#execution/tools/subagent/receipt-identity.js";
-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-import type { JsonObject } from "#shared/json.js";
-
-export interface SubagentTaskProjection {
- readonly identity?: ReturnType<typeof createSubagentReceiptIdentity>;
- readonly metadata: {
- readonly agentId: string;
- readonly kind: "subagent";
- readonly mode: "local" | "remote";
- readonly name: string;
- };
- readonly receipt: { readonly agentId: string };
-}
-
-export function projectSubagentTask(input: {
- readonly ctx: ReturnType<typeof loadContext>;
- readonly input: JsonObject;
- 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";
-}
diff --git a/packages/eve/src/execution/tasks/parent/task-cancel.ts b/packages/eve/src/execution/tasks/parent/task-cancel.ts
deleted file mode 100644
index 4d4205f42..000000000
--- a/packages/eve/src/execution/tasks/parent/task-cancel.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { HarnessSession } from "#harness/types.js";
-import { settleWorkflowToolRunCancellation } from "#execution/tools/workflow/cancel.js";
-import type { BackgroundWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-
-export interface TaskExecutorCancelContext {
- readonly entry: BackgroundWorkflowToolRun;
- readonly serializedContext?: Record<string, unknown>;
- readonly session?: Pick<HarnessSession, "state">;
-}
-
-export type TaskExecutorCancel = (input: TaskExecutorCancelContext) => Promise<void>;
-
-/** Cancels task-owned work and waits for the invocation cleanup boundary. */
-export async function cancelTaskOwnedWork(
- input: TaskExecutorCancelContext & { readonly cancelOwnedWork?: TaskExecutorCancel },
-): Promise<void> {
- await input.cancelOwnedWork?.(input);
- await settleWorkflowToolRunCancellation(
- input.entry.address.runId,
- `Task ${input.entry.task.taskId} was cancelled.`,
- );
-}
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 0b154c4c5..000000000
--- a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts
+++ /dev/null
@@ -1,430 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { ActivityObserverConfig } from "#channel/types.js";
-import { ContextContainer, contextStorage } from "#context/container.js";
-import { ActivityObserverKey, SessionKey, type SessionAuth } from "#context/keys.js";
-import {
- sendTaskCommand,
- startTaskRun,
- waitForTaskCommandOwner,
-} from "#execution/tasks/parent/run-parent.js";
-import {
- backgroundToolExecutionProvider,
- readRetainedBackgroundToolResult,
-} from "#execution/tasks/parent/tool-execution.js";
-import { steerBackgroundAgent } from "#execution/tools/subagent/steer.js";
-import {
- BackgroundToolExecutorKey,
- createBackgroundToolCallBatch,
-} from "#harness/background-tools.js";
-import { setHarnessEmissionState } from "#harness/emission-state.js";
-import { TurnCancelledError } from "#harness/turn-cancellation.js";
-import type { HarnessSession } from "#harness/types.js";
-import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";
-import { getBackgroundTasks, registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-vi.mock("#execution/tools/subagent/steer.js", () => ({ steerBackgroundAgent: vi.fn() }));
-vi.mock("#execution/tasks/parent/run-parent.js", () => ({
- sendTaskCommand: vi.fn(async () => "delivered"),
- startTaskRun: vi.fn(),
- waitForTaskCommandOwner: vi.fn(),
-}));
-
-const identity = { id: "agent-1", name: "research", nodeId: "subagents/research" };
-const address = {
- continuationToken: "child-token",
- kind: "agent/local" as const,
- sessionId: "child-session",
-};
-const handle = {
- address,
- callId: "original-call",
- identity,
- operationId: "original-operation",
- ownerId: "original-task",
- phase: "claimed" as const,
-};
-const entry = {
- callId: handle.ownerId,
- toolName: { agentId: identity.id, kind: "subagent", name: identity.name }.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "original-task-run", hookToken: "original-task-inbox" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { agentId: identity.id, kind: "subagent", name: identity.name },
- taskId: handle.ownerId,
- },
-};
-
-function createSession(owned = true): HarnessSession {
- const session = setHarnessEmissionState(
- {
- agent: { dynamicModel: true, system: "", tools: [] },
- compaction: { recentWindowSize: 5, threshold: 10_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent",
- state: setAgentHandleStore(undefined, { handles: [handle] }),
- },
- { sessionStarted: true, sequence: 2, stepIndex: 0, turnId: "turn-2" },
- );
- return owned ? registerWorkflowToolRun(session, entry) : session;
-}
-
-async function createScope(
- session = createSession(),
- activityObserver?: ActivityObserverConfig,
- auth: SessionAuth = { current: null, initiator: null },
-) {
- const ctx = new ContextContainer();
- ctx.setVirtualContext(SessionKey, {
- auth,
- sessionId: session.sessionId,
- turn: { id: "turn-2", sequence: 2 },
- });
- if (activityObserver !== undefined) {
- ctx.setVirtualContext(ActivityObserverKey, activityObserver);
- }
- const created = await backgroundToolExecutionProvider.create(ctx, session);
- if (created === undefined) throw new Error("Expected background executor");
- const executor = created.value;
- ctx.setVirtualContext(BackgroundToolExecutorKey, executor);
- const batch = createBackgroundToolCallBatch();
- return {
- execute(
- callId = "steering-call",
- agentId: string | undefined = identity.id,
- name = identity.name,
- kind: "subagent" | "tool" = "subagent",
-
- label?: (input: unknown) => string,
- ) {
- const definition = {
- execute: vi.fn(),
- label: label === undefined ? undefined : { start: label },
- name,
- nodeId: kind === "subagent" ? identity.nodeId : undefined,
- workflowId: "research-workflow",
- };
- const toolInput = { agentId, message: "Use the updated instruction" };
- batch.setTool(name, definition);
- batch.register({ callId, input: toolInput, toolName: name });
- return contextStorage.run(ctx, () =>
- executor.execute({
- batch,
- definition,
- options: { messages: [], toolCallId: callId },
- toolInput,
- }),
- );
- },
- commit: () => backgroundToolExecutionProvider.commit!(executor, session),
- rollback: (cause: unknown) => backgroundToolExecutionProvider.rollback!(executor, cause),
- retained: () => readRetainedBackgroundToolResult(ctx),
- };
-}
-
-describe("background subagent steering", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- vi.mocked(steerBackgroundAgent).mockResolvedValue(undefined);
- vi.mocked(startTaskRun).mockResolvedValue(undefined as never);
- vi.mocked(waitForTaskCommandOwner).mockResolvedValue({ runId: "steering-task-run" } as never);
- });
-
- it("steers the existing child without replacing its task, claim, or receipt", async () => {
- const scope = await createScope();
- const receipt = await scope.execute();
- expect(steerBackgroundAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- handle,
- callId: "steering-call",
- input: { agentId: identity.id, message: "Use the updated instruction" },
- }),
- );
- expect(receipt).toEqual({ agentId: identity.id, status: "working", taskId: entry.task.taskId });
- const session = await scope.commit();
- expect(getAgentHandleStore(session.state)?.handles).toEqual([handle]);
- expect(
- getBackgroundTasks(session.state)
- .query()
- .map(({ run }) => run),
- ).toEqual([entry]);
- expect(startTaskRun).not.toHaveBeenCalled();
- expect(waitForTaskCommandOwner).not.toHaveBeenCalled();
- expect(sendTaskCommand).not.toHaveBeenCalled();
- });
-
- it("keeps the original claim and starts no replacement when delivery fails", async () => {
- const scope = await createScope();
- vi.mocked(steerBackgroundAgent).mockRejectedValueOnce(new Error("Delivery failed"));
- await expect(scope.execute()).rejects.toThrow("Delivery failed");
- expect(startTaskRun).not.toHaveBeenCalled();
- expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);
- });
-
- it("persists the creating turn's auth on the background task", async () => {
- const creatorCurrent = {
- attributes: {},
- authenticator: "test-idp",
- issuer: "test-idp",
- principalId: "creator-current",
- principalType: "user" as const,
- };
- const creatorInitiator = { ...creatorCurrent, principalId: "creator-initiator" };
- const scope = await createScope(createSession(), undefined, {
- current: creatorCurrent,
- initiator: creatorInitiator,
- });
-
- await scope.execute("new-call", "");
- const committed = await scope.commit();
- const task = getBackgroundTasks(committed.state)
- .query()
- .map(({ run }) => run)
- .find((candidate) => candidate.task.taskId !== entry.task.taskId);
-
- expect(task?.task.dispatchContext).toEqual({
- auth: { current: creatorCurrent, initiator: creatorInitiator },
- });
- if (task === undefined) throw new Error("Expected created task");
- const replayed = registerWorkflowToolRun(committed, {
- ...task,
- task: {
- ...task.task,
- dispatchContext: {
- auth: {
- current: { ...creatorCurrent, principalId: "later-current" },
- initiator: { ...creatorInitiator, principalId: "later-initiator" },
- },
- },
- },
- });
- expect(
- getBackgroundTasks(replayed.state)
- .query()
- .map(({ run }) => run)
- .find((candidate) => candidate.task.taskId === task.task.taskId)?.task.dispatchContext,
- ).toEqual({ auth: { current: creatorCurrent, initiator: creatorInitiator } });
- });
-
- it("persists schedule-shaped auth with no current principal and one session initiator", async () => {
- const sessionInitiator = {
- attributes: {},
- authenticator: "test-idp",
- issuer: "test-idp",
- principalId: "session-initiator",
- principalType: "user" as const,
- };
- const scope = await createScope(createSession(), undefined, {
- current: null,
- initiator: sessionInitiator,
- });
-
- await scope.execute("new-call", "");
- const committed = await scope.commit();
- const task = getBackgroundTasks(committed.state)
- .query()
- .map(({ run }) => run)
- .find((candidate) => candidate.task.taskId !== entry.task.taskId);
-
- expect(task?.task.dispatchContext).toEqual({
- auth: { current: null, initiator: sessionInitiator },
- });
- });
-
- it.each(["subagent", "tool"] as const)(
- "retains activity identity for parent-owned settlement (%s)",
- async (kind) => {
- const activityObserver = {
- sink: { url: "https://parent.example/activity", version: 1 as const },
- workIdentity: {
- id: "work:root",
- kind: "root-turn" as const,
- rootSessionId: "parent",
- rootTurnId: "turn-2",
- },
- };
- const scope = await createScope(createSession(), activityObserver);
-
- await scope.execute("new-call", "", identity.name, kind);
- const committed = await scope.commit();
- const task = getBackgroundTasks(committed.state)
- .query()
- .map(({ run }) => run)
- .find((candidate) => candidate.task.taskId !== entry.task.taskId);
-
- expect(task).toBeDefined();
- expect(task?.task.activityWorkIdentity).toMatchObject({
- callId: "new-call",
- kind: "task",
- name: "research",
- parentId: "work:root",
- rootSessionId: "parent",
- rootTurnId: "turn-2",
- });
- },
- );
-
- it("persists a tool-derived task label without changing its subagent identity", async () => {
- const activityObserver = {
- sink: { url: "https://parent.example/activity", version: 1 as const },
- workIdentity: {
- id: "work:root",
- kind: "root-turn" as const,
- rootSessionId: "parent",
- rootTurnId: "turn-2",
- },
- };
- const scope = await createScope(createSession(), activityObserver);
-
- await scope.execute("new-call", "", identity.name, "subagent", (input) => {
- (input as { message: string }).message = "Mutated";
- return "Investigator";
- });
- expect(startTaskRun).toHaveBeenCalledWith(
- expect.objectContaining({
- workflow: expect.objectContaining({
- input: { agentId: "", message: "Use the updated instruction" },
- }),
- }),
- );
- const committed = await scope.commit();
- const task = getBackgroundTasks(committed.state)
- .query()
- .map(({ run }) => run)
- .find((candidate) => candidate.task.taskId !== entry.task.taskId);
-
- expect(task).toMatchObject({
- task: {
- activityWorkIdentity: { label: "Investigator", name: "research" },
- metadata: { name: "research" },
- },
- });
- });
-
- it("does not steer a task outside the parent task index", async () => {
- const scope = await createScope(createSession(false));
- await expect(scope.execute()).rejects.toThrow("AGENT_BUSY");
- expect(steerBackgroundAgent).not.toHaveBeenCalled();
- });
-
- it("does not steer a task associated with another child", async () => {
- const scope = await createScope(
- registerWorkflowToolRun(createSession(), {
- ...entry,
- task: { ...entry.task, metadata: { ...entry.task.metadata, agentId: "another-child" } },
- }),
- );
- await expect(scope.execute()).rejects.toThrow("AGENT_BUSY");
- expect(steerBackgroundAgent).not.toHaveBeenCalled();
- });
-
- it("rejects a different subagent tool before delivery", async () => {
- const scope = await createScope();
- await expect(scope.execute("call-1", identity.id, "another-tool")).rejects.toThrow(
- "AGENT_MISMATCH",
- );
- expect(steerBackgroundAgent).not.toHaveBeenCalled();
- });
-
- it("rejects a different local/remote target before delivery", async () => {
- const session = createSession();
- const scope = await createScope({
- ...session,
- state: setAgentHandleStore(session.state, {
- handles: [
- {
- ...handle,
- address: {
- kind: "agent/remote",
- sessionId: address.sessionId,
- url: "https://child.example",
- callbackBaseUrl: "https://parent.example",
- },
- },
- ],
- }),
- });
- await expect(scope.execute()).rejects.toThrow("AGENT_MISMATCH");
- expect(steerBackgroundAgent).not.toHaveBeenCalled();
- });
-
- it("does not steer a reservation before the child has an address", async () => {
- const { address: _address, ...reservation } = handle;
- const session = createSession();
- const scope = await createScope({
- ...session,
- state: setAgentHandleStore(session.state, {
- handles: [{ ...reservation, phase: "reserved" }],
- }),
- });
- await expect(scope.execute()).rejects.toThrow("AGENT_BUSY");
- expect(steerBackgroundAgent).not.toHaveBeenCalled();
- });
-
- it("preserves a different child's claim made while steering was pending", async () => {
- const second = {
- address: { ...address, sessionId: "second-session" },
- identity: { ...identity, id: "agent-2" },
- phase: "available" as const,
- };
- const session = createSession();
- const scope = await createScope({
- ...session,
- state: setAgentHandleStore(session.state, { handles: [handle, second] }),
- });
- const delivery = Promise.withResolvers<void>();
- vi.mocked(steerBackgroundAgent).mockReturnValueOnce(delivery.promise);
- const first = scope.execute();
- await scope.execute("second-call", second.identity.id);
- delivery.resolve();
- await first;
- expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([
- handle,
- expect.objectContaining({
- identity: second.identity,
- phase: "claimed",
- callId: "second-call",
- }),
- ]);
- });
-
- it("accepts concurrent steering without transferring ownership", async () => {
- const scope = await createScope();
- const receipts = await Promise.all([scope.execute("first-call"), scope.execute("second-call")]);
- expect(receipts).toEqual([
- { agentId: identity.id, status: "working", taskId: entry.task.taskId },
- { agentId: identity.id, status: "working", taskId: entry.task.taskId },
- ]);
- expect(steerBackgroundAgent).toHaveBeenCalledTimes(2);
- expect(startTaskRun).not.toHaveBeenCalled();
- expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);
- });
-
- it("allows another steering attempt after delivery fails", async () => {
- const scope = await createScope();
- vi.mocked(steerBackgroundAgent).mockRejectedValueOnce(new Error("Delivery failed"));
- await expect(scope.execute("first-call")).rejects.toThrow("Delivery failed");
-
- await expect(scope.execute("retry-call")).resolves.toMatchObject({
- agentId: identity.id,
- status: "working",
- });
- expect(steerBackgroundAgent).toHaveBeenCalledTimes(2);
- expect(startTaskRun).not.toHaveBeenCalled();
- expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);
- });
-
- it.each([new Error("Parent step failed"), new TurnCancelledError()])(
- "does not compensate the pre-existing task on rollback: %s",
- async (cause) => {
- const scope = await createScope();
- await scope.execute();
- await scope.rollback(cause);
- expect(sendTaskCommand).not.toHaveBeenCalled();
- expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);
- expect(scope.retained()).toBeUndefined();
- },
- );
-});
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.ts
deleted file mode 100644
index 01cfed3ee..000000000
--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts
+++ /dev/null
@@ -1,583 +0,0 @@
-import {
- type BackgroundWorkflowToolRun,
- getBackgroundTasks,
- registerWorkflowToolRun,
-} from "#harness/workflow-tool-runs.js";
-import type { ContextContainer } from "#context/container.js";
-import { loadContext } from "#context/container.js";
-import { ActivityObserverKey, CapabilitiesKey } from "#context/keys.js";
-import type { FrameworkContextProvider } from "#context/provider.js";
-import { runStep } from "#context/run-step.js";
-import { buildCallbackContext } from "#context/build-callback-context.js";
-import { activeTurnId } from "#harness/active-turn-id.js";
-import { resolveWorkflowAgentMetadata } from "#execution/tools/subagent/metadata.js";
-import { getHarnessEmissionState } from "#harness/emission.js";
-import { isTurnCancellation } from "#harness/turn-cancellation.js";
-import type { HarnessSession, StepResult } from "#harness/types.js";
-import {
- BackgroundToolExecutorKey,
- type BackgroundExecutableTool,
- type BackgroundToolCallBatch,
- type BackgroundToolExecutor,
-} from "#harness/background-tools.js";
-import { deriveBackgroundTaskActivityObserver } from "#execution/activity-work.js";
-import { projectToolStartLabel } from "#harness/action-presentation.js";
-import type { ToolExecuteOptions } from "#tools/definition.js";
-import type { AgentView } from "#subagents/handles/prompt.js";
-import {
- createTaskAgentDispatchContext,
- prepareBackgroundTask,
- rejectDelegatedDispatch,
-} from "#execution/tasks/parent/delegate.js";
-import { parseWorkflowToolInput } from "#execution/tools/workflow/background.js";
-import { startTaskRun, waitForTaskCommandOwner } from "#execution/tasks/parent/run-parent.js";
-import { sessionCommandHookToken } from "#execution/session-inbox/address.js";
-import { projectSubagentTask } from "#execution/tasks/parent/subagent-task-projection.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";
-import { steerBackgroundAgent } from "#execution/tools/subagent/steer.js";
-
-interface BackgroundToolExecutionRecord {
- readonly callId: string;
- claim?: {
- readonly operationId: string;
- readonly taskId: string;
- };
- reservation?: {
- readonly agentId: string;
- readonly operationId: string;
- };
- settled: boolean;
- task?: BackgroundWorkflowToolRun;
-}
-
-interface BackgroundToolStepResult {
- readonly backgroundTaskSession: HarnessSession;
- readonly backgroundTasks: NonNullable<StepResult["backgroundTasks"]>;
-}
-
-export function runBackgroundStep(
- ctx: ContextContainer,
- session: HarnessSession,
- callback: (session: HarnessSession) => Promise<StepResult>,
-): Promise<StepResult> {
- return runStep(ctx, session, callback, [backgroundToolExecutionProvider]);
-}
-
-/**
- * Makes background tool work transactional with the harness step.
- *
- * 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
- * is compensated with it.
- *
- * Lifetime: one {@link BackgroundToolExecutionScope} per step. `create` runs
- * before the authored callback; exactly one of `commit` or `rollback` settles
- * the scope afterwards; `decorateStepResult` runs last, only after a
- * successful commit. Nothing survives the step except retained tasks (below).
- *
- * - `commit` — step succeeded. Compensates executions that never settled
- * (the tool neither delegated nor completed its task), then records the
- * 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}
- * instead of killed.
- * - `decorateStepResult` — attaches `backgroundTasks` and
- * `backgroundTaskSession` to the {@link StepResult} so the turn loop keeps
- * tracking the spawned tasks after the step returns.
- */
-export const backgroundToolExecutionProvider: FrameworkContextProvider<BackgroundToolExecutor> = {
- key: BackgroundToolExecutorKey,
- create(_ctx, session) {
- return { value: new BackgroundToolExecutionScope(session) };
- },
- async commit(executor, session) {
- return await requireExecutionScope(executor).commit(session);
- },
- async rollback(executor, cause) {
- await requireExecutionScope(executor).rollback(cause);
- },
- decorateStepResult(executor, result) {
- return requireExecutionScope(executor).decorate(result);
- },
-};
-
-/**
- * Returns what a successful commit would have produced (session with task
- * entries and executor session writes applied) when turn cancellation raced
- * a successfully delegated task. `rollback` deliberately does not compensate
- * settled records on cancellation — that would kill already-running tasks —
- * so the cancellation epilogue reads this instead to keep those tasks tracked
- * in durable state rather than orphaned. `undefined` when nothing was retained.
- */
-export function readRetainedBackgroundToolResult(
- ctx: ContextContainer,
-): BackgroundToolStepResult | undefined {
- const executor = ctx.get(BackgroundToolExecutorKey);
- return executor instanceof BackgroundToolExecutionScope ? executor.retainedResult() : undefined;
-}
-
-class BackgroundToolExecutionScope implements BackgroundToolExecutor {
- 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) {
- this.initialSession = initialSession;
- this.agentHandleSession = initialSession;
- }
-
- execute(input: {
- readonly batch: BackgroundToolCallBatch;
- readonly definition: BackgroundExecutableTool;
- readonly options: ToolExecuteOptions;
- readonly toolInput: unknown;
- }): Promise<unknown> {
- const existing = this.executions.get(input.options.toolCallId);
- if (existing !== undefined) return existing;
- if (!input.batch.calls.some((call) => call.callId === input.options.toolCallId)) {
- throw new Error(
- `Background tool call "${input.options.toolCallId}" was not registered before execution.`,
- );
- }
- const execution = this.start(input);
- this.executions.set(input.options.toolCallId, execution);
- 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,
- },
- ];
- });
- }
-
- hasPendingTasks(): boolean {
- return (
- getBackgroundTasks(this.initialSession.state).query({ state: "working" }).length > 0 ||
- this.records.some((record) => record.settled && record.task !== undefined)
- );
- }
-
- async commit(session: HarnessSession): Promise<HarnessSession> {
- const incomplete = this.records.filter((record) => !record.settled);
- if (incomplete.length > 0) {
- await this.compensate(
- incomplete,
- new Error("Background tool execution did not delegate or complete its task."),
- );
- }
- return this.apply(session);
- }
-
- decorate(result: StepResult): StepResult {
- const fields = this.resultFields();
- return fields === undefined ? result : { ...result, ...fields };
- }
-
- async rollback(cause: unknown): Promise<void> {
- const settled = this.records.filter((record) => record.settled);
- const incomplete = this.records.filter((record) => !record.settled);
- if (incomplete.length > 0) {
- await this.compensate(incomplete, cause);
- }
- if (settled.length === 0) {
- this.retained = this.agentHandlesChanged && isTurnCancellation(cause);
- return;
- }
- // Cancellation must not compensate settled records: their tasks are
- // already running. Retain them for readRetainedBackgroundToolResult.
- if (isTurnCancellation(cause)) {
- this.retained = true;
- return;
- }
- await this.compensate(settled, cause);
- }
-
- retainedResult(): BackgroundToolStepResult | undefined {
- return this.retained ? this.resultFields() : undefined;
- }
-
- private apply(session: HarnessSession): HarnessSession {
- let next = session;
- for (const record of this.records) {
- if (!record.settled || record.task === undefined) continue;
- next = registerWorkflowToolRun(next, record.task);
- }
- if (this.agentHandlesChanged) {
- next = writeHandles(next, getAgentHandleStore(this.agentHandleSession.state)?.handles ?? []);
- }
- return next;
- }
-
- private resultFields(): BackgroundToolStepResult | undefined {
- const tasks = this.records.flatMap((record) =>
- record.settled && record.task !== undefined
- ? [
- {
- callId: record.callId,
- taskInboxToken: record.task.address.hookToken,
- taskId: record.task.task.taskId,
- taskRunId: record.task.address.runId,
- },
- ]
- : [],
- );
- if (tasks.length === 0 && !this.agentHandlesChanged) return undefined;
- return {
- backgroundTaskSession: this.apply(this.initialSession),
- backgroundTasks: tasks,
- };
- }
-
- private async start(input: {
- readonly batch: BackgroundToolCallBatch;
- readonly definition: BackgroundExecutableTool;
- readonly options: ToolExecuteOptions;
- readonly toolInput: unknown;
- }): Promise<unknown> {
- const record: BackgroundToolExecutionRecord = {
- callId: input.options.toolCallId,
- settled: false,
- };
- this.records.push(record);
- const emission = getHarnessEmissionState(this.initialSession.state);
- const ctx = loadContext();
- const started = await this.startTask({ ctx, emission, input, record });
- if (started.kind === "steered") {
- record.settled = true;
- return started.receipt;
- }
- const task = started.task;
- record.task = task;
-
- record.settled = true;
- return { ...started.receipt, status: "working", taskId: task.task.taskId };
- }
-
- 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 kind: "started";
- readonly receipt?: { readonly agentId: string };
- readonly task: BackgroundWorkflowToolRun;
- }
- | {
- readonly kind: "steered";
- readonly receipt: {
- readonly agentId: string;
- readonly taskId: string;
- readonly status: "working";
- };
- }
- > {
- const workflow = input.input.definition;
- let workflowInput = parseWorkflowToolInput(input.input.toolInput, input.input.definition.name);
- const parentTurnId = activeTurnId(input.emission);
- let subagentProjection =
- workflow.nodeId !== 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 metadata = subagentProjection?.metadata ?? {
- kind: "tool" as const,
- name: input.input.definition.name,
- };
- const activityLabel = projectToolStartLabel(input.input.definition, input.input.toolInput);
- const callbackSession = buildCallbackContext().session;
- const taskInput = {
- activityObserver: deriveBackgroundTaskActivityObserver({
- activityObserver: input.ctx.get(ActivityObserverKey),
- callId: input.input.options.toolCallId,
- label: activityLabel,
- name: metadata.name,
- parentSessionId: this.initialSession.sessionId,
- parentTurnId,
- rootSessionId: this.initialSession.rootSessionId ?? this.initialSession.sessionId,
- }),
- callId: input.input.options.toolCallId,
- dispatchContext: createTaskAgentDispatchContext(input.ctx, callbackSession.auth),
- metadata,
- parentSessionId: this.initialSession.sessionId,
- parentStepIndex: input.emission.stepIndex,
- parentTurnId,
- session: this.initialSession,
- };
- const prepared = prepareBackgroundTask(taskInput);
- const task = {
- ...prepared,
- task: {
- ...prepared.task,
- activityWorkIdentity: taskInput.activityObserver?.workIdentity,
- },
- };
- if (
- workflow.nodeId !== undefined &&
- 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.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.nodeId !== undefined &&
- 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.task.taskId,
- });
- if (claim.kind === "busy" && claim.handle.phase === "claimed") {
- const handle = claim.handle;
- const owner = getBackgroundTasks(this.agentHandleSession.state).get(handle.ownerId);
- if (
- owner?.metadata.kind === "subagent" &&
- owner.metadata.agentId === handle.identity.id &&
- owner.metadata.name === handle.identity.name &&
- owner.status === "working"
- ) {
- await steerBackgroundAgent({
- ctx: input.ctx,
- handle,
- callId: taskInput.callId,
- input: workflowInput,
- session: this.agentHandleSession,
- });
- return {
- kind: "steered",
- receipt: { agentId: handle.identity.id, taskId: owner.taskId, status: "working" },
- };
- }
- }
- if (!readClaimedHandle(claim)) {
- throwAgentClaimError(subagentProjection.metadata.agentId, claim);
- } else {
- input.record.claim = {
- operationId,
- taskId: task.task.taskId,
- };
- }
- }
- await startTaskRun({
- activityObserver: taskInput.activityObserver,
- initialView: { metadata: task.task.metadata, status: "working", taskId: task.task.taskId },
- parentContinuationToken: sessionCommandHookToken(this.initialSession.sessionId),
- taskInboxToken: task.address.hookToken,
- workflow: {
- agents: resolveWorkflowAgentMetadata(input.ctx),
- callId: taskInput.callId,
- canRequestInput: input.ctx.get(CapabilitiesKey)?.requestInput === true,
- executeInput: workflow.executeInput?.(workflowInput),
- input: workflowInput,
- session: callbackSession,
- stepIndex: input.emission.stepIndex,
- toolName: input.input.definition.name,
- workflowId: workflow.workflowId,
- },
- });
- const owner = await waitForTaskCommandOwner({ taskInboxToken: task.address.hookToken });
- const backgroundTask = {
- ...task,
- address: { ...task.address, runId: owner.runId },
- };
- input.record.task = backgroundTask;
- if (workflow.nodeId === undefined) {
- return { kind: "started", task: backgroundTask };
- }
-
- if (subagentProjection === undefined) {
- return { kind: "started", task: backgroundTask };
- }
- return { kind: "started", 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.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 requireExecutionScope(executor: BackgroundToolExecutor): BackgroundToolExecutionScope {
- if (!(executor instanceof BackgroundToolExecutionScope)) {
- throw new Error("The background tool executor is not owned by the task runtime.");
- }
- return executor;
-}
-
-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 (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/tasks/workflow-target.ts b/packages/eve/src/execution/tasks/workflow-target.ts
index ee45b0d18..4f47ca056 100644
--- a/packages/eve/src/execution/tasks/workflow-target.ts
+++ b/packages/eve/src/execution/tasks/workflow-target.ts
@@ -21,3 +21,12 @@ export function isTaskWorkflowTargetGone(error: unknown): boolean {
}
return false;
}
+
+/** Awaits traffic to a workflow hook or run, which a target already gone makes moot. */
+export async function ignoreGoneTarget(pending: Promise<unknown>): Promise<void> {
+ try {
+ await pending;
+ } catch (error) {
+ if (!isTaskWorkflowTargetGone(error)) throw error;
+ }
+}
diff --git a/packages/eve/src/execution/terminal-session-completion-step.ts b/packages/eve/src/execution/terminal-session-completion-step.ts
index f0cb2c926..5820d10b8 100644
--- a/packages/eve/src/execution/terminal-session-completion-step.ts
+++ b/packages/eve/src/execution/terminal-session-completion-step.ts
@@ -1,4 +1,4 @@
-import { emitTerminalSessionEvent } from "#execution/terminal-session-event.js";
+import { publishTerminalSessionEvent } from "#execution/publish-session-events.js";
import { createSessionCompletedEvent } from "#protocol/message.js";
/** Emits a terminal `session.completed` outside a turn. */
@@ -8,5 +8,5 @@ export async function emitTerminalSessionCompletionStep(input: {
}): Promise<void> {
"use step";
- await emitTerminalSessionEvent({ ...input, event: createSessionCompletedEvent() });
+ await publishTerminalSessionEvent({ ...input, event: createSessionCompletedEvent() });
}
diff --git a/packages/eve/src/execution/terminal-session-event.ts b/packages/eve/src/execution/terminal-session-event.ts
deleted file mode 100644
index 24d156c8d..000000000
--- a/packages/eve/src/execution/terminal-session-event.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import { buildAdapterContext } from "#channel/adapter-context.js";
-import { callAdapterEventHandler } from "#channel/adapter.js";
-import { ContextContainer, contextStorage } from "#context/container.js";
-import { ParentSessionKey } from "#context/keys.js";
-import { deserializeContext } from "#context/serialize.js";
-import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
-import type { HandleEventFn } from "#harness/types.js";
-import { createLogger } from "#internal/logging.js";
-import {
- encodeMessageStreamEvent,
- stampMessageStreamEvent,
- type UnstampedMessageStreamEvent,
-} from "#protocol/message.js";
-import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
-
-const log = createLogger("execution.workflow-entry");
-
-type TerminalSessionEvent = Extract<
- UnstampedMessageStreamEvent,
- { type: "session.completed" | "session.failed" }
->;
-
-/** Delivers one out-of-turn terminal event through the native instrumentation lifecycle. */
-export async function emitTerminalSessionEvent(input: {
- readonly errorId?: string;
- readonly event: TerminalSessionEvent;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly turnId?: string;
-}): Promise<void> {
- const sessionId = (input.serializedContext["eve.sessionId"] as string | undefined) ?? "";
- let ctx: ContextContainer | undefined;
-
- try {
- ctx = await deserializeContext(input.serializedContext);
- } catch (error) {
- log.error(`failed to restore context for terminal ${input.event.type} event`, {
- error,
- errorId: input.errorId,
- sessionId,
- });
- }
-
- const handleEvent: HandleEventFn = async (event) => {
- if (ctx !== undefined) {
- const adapter = ctx.get(ChannelKey);
- if (adapter !== undefined) {
- try {
- await callAdapterEventHandler(adapter, event, buildAdapterContext(adapter, ctx));
- } catch (error) {
- log.error(`adapter failed to handle terminal ${event.type} event`, {
- error,
- errorId: input.errorId,
- sessionId,
- });
- }
- }
- }
-
- try {
- const writer = input.sessionWritable.getWriter();
- try {
- await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(event)));
- } finally {
- writer.releaseLock();
- }
- } catch (error) {
- log.error(`failed to write terminal ${event.type} event to durable stream`, {
- error,
- errorId: input.errorId,
- sessionId,
- });
- }
- };
-
- let instrumentation: ReturnType<typeof bindSessionInstrumentation>;
- if (ctx !== undefined) {
- try {
- const bundle = ctx.require(BundleKey);
- instrumentation = bindSessionInstrumentation({
- agentName: bundle.turnAgent.id,
- ctx,
- rootSessionId: ctx.get(ParentSessionKey)?.rootSessionId ?? sessionId,
- sessionId,
- });
- } catch (error) {
- log.error(`failed to bind instrumentation for terminal ${input.event.type} event`, {
- error,
- errorId: input.errorId,
- sessionId,
- });
- }
- }
-
- const emit =
- instrumentation?.createHandleEvent({
- handleEvent,
- turnId: input.turnId,
- }) ?? handleEvent;
- try {
- if (ctx === undefined) {
- await emit(input.event);
- } else {
- await contextStorage.run(ctx, () => emit(input.event));
- }
- } catch (error) {
- log.error(`instrumentation failed to handle terminal ${input.event.type} event`, {
- error,
- errorId: input.errorId,
- sessionId,
- });
- } finally {
- try {
- await instrumentation?.flush();
- } catch (error) {
- log.error(`failed to flush instrumentation after terminal ${input.event.type} event`, {
- error,
- errorId: input.errorId,
- sessionId,
- });
- }
- }
-}
diff --git a/packages/eve/src/execution/terminal-session-failure-step.ts b/packages/eve/src/execution/terminal-session-failure-step.ts
index 6f8b810c0..ec0c568b3 100644
--- a/packages/eve/src/execution/terminal-session-failure-step.ts
+++ b/packages/eve/src/execution/terminal-session-failure-step.ts
@@ -1,4 +1,4 @@
-import { emitTerminalSessionEvent } from "#execution/terminal-session-event.js";
+import { publishTerminalSessionEvent } from "#execution/publish-session-events.js";
import { summarizeKnownError } from "#harness/semantic-errors/index.js";
import { createLogger, formatError } from "#internal/logging.js";
import { createSessionFailedEvent } from "#protocol/message.js";
@@ -39,7 +39,7 @@ export async function emitTerminalSessionFailureStep(input: {
code,
});
- await emitTerminalSessionEvent({
+ await publishTerminalSessionEvent({
errorId: typeof details.errorId === "string" ? details.errorId : undefined,
event: createSessionFailedEvent({ code, details, message, sessionId }),
sessionWritable: input.sessionWritable,
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 b0879f2e1..4a9e14dbb 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts
@@ -3,15 +3,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
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 type { BackgroundWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-import { captureLogRecords } from "#internal/testing/log-records.js";
const COMPILED_BUNDLE = {
subagentRegistry: { subagentsByNodeId: new Map() },
};
const {
- cancelOwnedTaskMock,
cancelRunMock,
deserializeContextMock,
getWorldMock,
@@ -22,7 +19,6 @@ const {
resolveRemoteAgentStreamHeadersMock,
resolveEffectiveAgentRuntimeMock,
} = vi.hoisted(() => ({
- cancelOwnedTaskMock: vi.fn(),
cancelRunMock: vi.fn(),
deserializeContextMock: vi.fn(),
getWorldMock: vi.fn(),
@@ -51,9 +47,6 @@ vi.mock("#subagents/remote-dispatch.js", () => ({
resolveRemoteAgentForAction: resolveRemoteAgentForActionMock,
resolveRemoteAgentStreamHeaders: resolveRemoteAgentStreamHeadersMock,
}));
-vi.mock("#execution/tasks/parent/dispatch.js", () => ({
- cancelOwnedTask: cancelOwnedTaskMock,
-}));
vi.mock("#internal/workflow/runtime.js", () => ({
cancelRun: cancelRunMock,
getWorld: getWorldMock,
@@ -61,10 +54,6 @@ vi.mock("#internal/workflow/runtime.js", () => ({
describe("terminateChildSessionsStep", () => {
beforeEach(() => {
- cancelOwnedTaskMock.mockReset();
- cancelOwnedTaskMock.mockImplementation(
- async ({ entry }: { entry: BackgroundWorkflowToolRun }) => cancelledView(entry),
- );
cancelRunMock.mockReset();
cancelRunMock.mockResolvedValue(undefined);
deserializeContextMock.mockReset();
@@ -246,101 +235,6 @@ describe("terminateChildSessionsStep", () => {
});
});
- it("settles every indexed task cancellation before terminating local children", async () => {
- const logs = captureLogRecords();
- const firstCancellation = createDeferred();
- const secondCancellation = createDeferred();
- const order: string[] = [];
- cancelOwnedTaskMock
- .mockImplementationOnce(async ({ entry }: { entry: BackgroundWorkflowToolRun }) => {
- await firstCancellation.promise;
- order.push("task-1-settled");
- return cancelledView(entry);
- })
- .mockImplementationOnce(async ({ entry }: { entry: BackgroundWorkflowToolRun }) => {
- await secondCancellation.promise;
- order.push("task-2-settled");
- return cancelledView(entry);
- });
- cancelRunMock.mockImplementation(async () => {
- order.push("child-cancelled");
- });
-
- const termination = terminateChildSessionsStep({
- serializedContext: { context: "serialized" },
- sessionState: makeSessionState(
- [runningHandle({ id: "ag_local:1", kind: "agent/local", sessionId: "session-local" })],
- [indexedTask("task-1"), indexedTask("task-2")],
- ),
- });
-
- await vi.waitFor(() => expect(cancelOwnedTaskMock).toHaveBeenCalledTimes(1));
- expect(cancelRunMock).not.toHaveBeenCalled();
-
- firstCancellation.resolve();
- await vi.waitFor(() => expect(cancelOwnedTaskMock).toHaveBeenCalledTimes(2));
- expect(order).toEqual(["task-1-settled"]);
- expect(cancelRunMock).not.toHaveBeenCalled();
-
- secondCancellation.resolve();
- await termination;
-
- expect(order).toEqual(["task-1-settled", "task-2-settled", "child-cancelled"]);
- expect(cancelRunMock).toHaveBeenCalledExactlyOnceWith("world", "session-local", {
- cancelReason: "Parent session ended",
- });
- expect(logs.records).toContainEqual(
- expect.objectContaining({
- level: "warn",
- message: "failed to settle background task instrumentation",
- }),
- );
- });
-
- it("continues finalization after an indexed task cancellation fails", async () => {
- const logs = captureLogRecords();
- cancelOwnedTaskMock
- .mockRejectedValueOnce(new Error("task cancellation unavailable"))
- .mockImplementationOnce(async ({ entry }: { entry: BackgroundWorkflowToolRun }) =>
- cancelledView(entry),
- );
-
- await expect(
- terminateChildSessionsStep({
- serializedContext: { context: "serialized" },
- sessionState: makeSessionState(
- [
- parkedHandle({
- id: "ag_local:1",
- kind: "agent/local",
- sessionId: "session-local",
- }),
- ],
- [indexedTask("task-1"), indexedTask("task-2")],
- ),
- }),
- ).resolves.toBeUndefined();
-
- expect(cancelOwnedTaskMock).toHaveBeenCalledTimes(2);
- expect(cancelRunMock).toHaveBeenCalledExactlyOnceWith("world", "session-local", {
- cancelReason: "Parent session ended",
- });
- expect(logs.records).toContainEqual(
- expect.objectContaining({
- level: "error",
- namespace: "execution.cancel-indexed-session-tasks",
- message: "failed to cancel indexed task",
- fields: expect.objectContaining({ parentSessionId: "parent-session", taskId: "task-1" }),
- }),
- );
- expect(logs.records).toContainEqual(
- expect.objectContaining({
- level: "warn",
- message: "failed to settle background task instrumentation",
- }),
- );
- });
-
it("continues terminating children after one termination fails", async () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
cancelRunMock
@@ -444,31 +338,7 @@ function startingHandle(input: {
};
}
-function indexedTask(taskId: string): BackgroundWorkflowToolRun {
- return {
- callId: taskId,
- toolName: {
- kind: "tool",
- name: "research",
- }.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: `run-${taskId}`, hookToken: `${taskId}:inbox` },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: {
- kind: "tool",
- name: "research",
- },
- taskId,
- },
- };
-}
-
-function makeSessionState(
- handles: readonly AgentHandle[],
- tasks: readonly BackgroundWorkflowToolRun[] = [],
-): DurableSessionState {
+function makeSessionState(handles: readonly AgentHandle[]): DurableSessionState {
return {
continuationToken: "parent-token",
emissionState: {
@@ -485,27 +355,9 @@ function makeSessionState(
continuationToken: "parent-token",
history: [],
sessionId: "parent-session",
- state:
- tasks.length === 0
- ? { [AGENT_HANDLES_STATE_KEY]: { handles } }
- : {
- [AGENT_HANDLES_STATE_KEY]: { handles },
- "eve.workflowTool": { version: 3, runs: tasks },
- },
+ state: { [AGENT_HANDLES_STATE_KEY]: { handles } },
},
},
version: 1,
};
}
-
-function createDeferred(): { readonly promise: Promise<void>; resolve(): void } {
- let resolve!: () => void;
- const promise = new Promise<void>((next) => {
- resolve = next;
- });
- return { promise, resolve };
-}
-
-function cancelledView(entry: BackgroundWorkflowToolRun) {
- return { taskId: entry.task.taskId, metadata: entry.task.metadata, status: "cancelled" as const };
-}
diff --git a/packages/eve/src/execution/terminate-child-sessions-step.ts b/packages/eve/src/execution/terminate-child-sessions-step.ts
index a424c9e76..0e20e94bf 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.ts
@@ -1,7 +1,6 @@
import { deserializeContext } from "#context/serialize.js";
import type { ContextContainer } from "#context/container.js";
import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
import {
resetRemoteAgentSession,
@@ -51,11 +50,6 @@ export async function terminateChildSessionsStep(input: {
readonly ctx: ContextContainer;
}
| undefined;
- // Record cancellation in the parent before terminating its child sessions.
- await cancelAllIndexedSessionTasksStep({
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- });
if (hasRemoteHandle) {
if (input.serializedContext === undefined) {
throw new Error("Child finalization requires serialized runtime context.");
diff --git a/packages/eve/src/execution/tools/agent-router-workflow.ts b/packages/eve/src/execution/tools/agent-router-workflow.ts
index ef9463af2..53921019b 100644
--- a/packages/eve/src/execution/tools/agent-router-workflow.ts
+++ b/packages/eve/src/execution/tools/agent-router-workflow.ts
@@ -11,7 +11,12 @@ export async function executeAgentRouterTool(
"use workflow";
const target = await chooseTarget(input.message, descriptions(ctx), ctx.abortSignal);
- return ctx.agent(target, { message: input.message });
+ const response = await ctx.agent(target).send(input.message, { signal: ctx.abortSignal });
+ const { message, status } = await response.result();
+ if (status === "failed") {
+ throw new Error(`Agent "${target}" failed to handle the task.`);
+ }
+ return message ?? null;
}
async function chooseTarget(
diff --git a/packages/eve/src/execution/tools/ask-question.ts b/packages/eve/src/execution/tools/ask-question.ts
deleted file mode 100644
index 765b5d175..000000000
--- a/packages/eve/src/execution/tools/ask-question.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { defineJsonSchema } from "#tools/schema.js";
-
-export { executeAskQuestionTool } from "#execution/tools/ask-question-workflow.js";
-
-export const ASK_QUESTION_TOOL_DESCRIPTION = [
- "Ask the user a question and wait for the answer. Use this only when you cannot make good progress without the user's input: to choose between materially different approaches, fill in a missing requirement, or confirm something risky or irreversible. Do not ask for information you can find with your other tools, and do not ask the user to confirm routine steps.",
- "",
- "Usage:",
- "- Ask one focused question that includes the context needed to answer it.",
- '- For a decision, offer 2-3 mutually exclusive options. Put the option you recommend first and end its label with "(Recommended)".',
- '- Do not add an "Other" option; the user can always type their own answer.',
- "- The result's `answer` is the chosen option's label or the user's own words.",
- '- If the status is "dismissed", the user moved on without answering; respond to their next message instead.',
- '- If the status is "unavailable", no one can answer in this session; continue with your best judgment and state the assumption you made.',
-].join("\n");
-
-export interface AskQuestionInput {
- options?: { description: string; label: string }[];
- question: string;
-}
-
-export type AskQuestionOutput =
- | { answer: string; status: "answered" }
- | { status: "dismissed" }
- | { status: "unavailable" };
-
-export const ASK_QUESTION_INPUT_SCHEMA = defineJsonSchema<AskQuestionInput>(
- {
- type: "object",
- properties: {
- options: {
- type: "array",
- minItems: 2,
- maxItems: 3,
- items: {
- type: "object",
- properties: {
- description: {
- type: "string",
- minLength: 1,
- maxLength: 200,
- description: "One short sentence on the impact or tradeoff of choosing this option.",
- },
- label: {
- type: "string",
- minLength: 1,
- maxLength: 80,
- description: "User-facing label, 1-5 words.",
- },
- },
- required: ["description", "label"],
- additionalProperties: false,
- },
- description:
- 'Two or three mutually exclusive choices, recommended option first. Omit for an open-ended question. Never include an "Other" option.',
- },
- question: {
- type: "string",
- minLength: 1,
- maxLength: 2000,
- description: "The question to show the user, with the context needed to answer it.",
- },
- },
- required: ["question"],
- additionalProperties: false,
- },
- // Labels double as option ids, so duplicates would make answers ambiguous.
- (input) =>
- input.options !== undefined &&
- new Set(input.options.map((option) => option.label)).size !== input.options.length
- ? "Option labels must be unique."
- : undefined,
-);
-
-export const ASK_QUESTION_OUTPUT_SCHEMA = defineJsonSchema<AskQuestionOutput>({
- oneOf: [
- {
- type: "object",
- properties: {
- answer: {
- type: "string",
- description: "The chosen option's label, or the user's own words.",
- },
- status: { type: "string", const: "answered" },
- },
- required: ["answer", "status"],
- additionalProperties: false,
- },
- {
- type: "object",
- properties: { status: { type: "string", const: "dismissed" } },
- required: ["status"],
- additionalProperties: false,
- },
- {
- type: "object",
- properties: { status: { type: "string", const: "unavailable" } },
- required: ["status"],
- additionalProperties: false,
- },
- ],
-});
diff --git a/packages/eve/src/execution/tools/sleep-workflow.ts b/packages/eve/src/execution/tools/sleep-workflow.ts
deleted file mode 100644
index 7f7eda358..000000000
--- a/packages/eve/src/execution/tools/sleep-workflow.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { sleep } from "#compiled/@workflow/core/index.js";
-
-import type { SleepToolInput, SleepToolOutput } from "#execution/tools/sleep.js";
-
-/** Waits durably in a workflow dedicated to this tool call. */
-export async function executeSleepTool(input: SleepToolInput): Promise<SleepToolOutput> {
- "use workflow";
-
- await sleep(Math.ceil(input.seconds * 1_000));
- return { waitedSeconds: input.seconds };
-}
diff --git a/packages/eve/src/execution/tools/sleep.ts b/packages/eve/src/execution/tools/sleep.ts
deleted file mode 100644
index 4763bfaa7..000000000
--- a/packages/eve/src/execution/tools/sleep.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { defineJsonSchema } from "#tools/schema.js";
-
-export { executeSleepTool } from "#execution/tools/sleep-workflow.js";
-
-const MAX_SLEEP_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1_000);
-
-export const SLEEP_TOOL_DESCRIPTION =
- "Wait for a specified amount of time before continuing. Use this when a process or condition needs time to change before it is useful to check its progress or status again.";
-
-export interface SleepToolInput {
- seconds: number;
-}
-
-export interface SleepToolOutput {
- waitedSeconds: number;
-}
-
-export const SLEEP_INPUT_SCHEMA = defineJsonSchema<SleepToolInput>({
- type: "object",
- properties: {
- seconds: {
- type: "number",
- exclusiveMinimum: 0,
- maximum: MAX_SLEEP_SECONDS,
- description: "How long to wait, in seconds.",
- },
- },
- required: ["seconds"],
- additionalProperties: false,
-});
-
-export const SLEEP_OUTPUT_SCHEMA = defineJsonSchema<SleepToolOutput>({
- type: "object",
- properties: {
- waitedSeconds: { type: "number", exclusiveMinimum: 0 },
- },
- required: ["waitedSeconds"],
- additionalProperties: false,
-});
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
deleted file mode 100644
index 8e8af5007..000000000
--- a/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-import { recordWorkflowTaskView } from "#harness/workflow-tool-runs.js";
-import { createTestSessionState } from "#internal/testing/session-state.js";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import { readDurableSession } from "#execution/durable-session-store.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", async (importOriginal) => ({
- ...(await importOriginal()),
- readDurableSession: vi.fn(),
-}));
-
-const sessionState = createTestSessionState({
- continuationToken: "parent-token",
- emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },
- hasProxyInputRequests: false,
- sessionId: "parent-session",
- version: 1,
-});
-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.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task-1",
- toolName: "export",
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "tool", name: "export" },
- taskId: "task-1",
- },
- },
- ],
- },
-};
-
-function mockSession(handles: readonly unknown[]): void {
- vi.mocked(readDurableSession).mockReturnValue({
- 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",
- },
- ]);
- });
-
- 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);
- });
-
- it("accepts the owning workflow tool's event without an agent handle", async () => {
- mockSession([]);
- const event = {
- ...hookPayload,
- childSessionId: "task-run",
- subagentName: "export",
- event: { ...hookPayload.event, data: { ...hookPayload.event.data, turnId: "turn-1" } },
- };
- await expect(
- acceptTaskAuthorizationEventStep({
- delivery: { hookPayload: event, taskId: "task-1" },
- sessionState,
- }),
- ).resolves.toBe(true);
- await expect(
- acceptTaskAuthorizationEventStep({
- delivery: { hookPayload: { ...event, childSessionId: "different-run" }, taskId: "task-1" },
- sessionState,
- }),
- ).resolves.toBe(false);
- });
-
- 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 () => {
- const session = readDurableSession(sessionState);
- vi.mocked(readDurableSession).mockReturnValue({
- ...session,
- state: recordWorkflowTaskView(session.state, {
- lastOutput: { data: "done", type: "result" },
- metadata: { kind: "tool", name: "export" },
- status: "completed",
- taskId: "task-1",
- }).state,
- });
-
- 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
deleted file mode 100644
index 5bf94703f..000000000
--- a/packages/eve/src/execution/tools/subagent/accept-event-step.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
-import { getAgentHandleStore } from "#subagents/handles/store.js";
-import { getBackgroundTasks } from "#harness/workflow-tool-runs.js";
-import { type TaskAuthorizationEventDelivery } from "#tasks/types.js";
-
-/** Accepts authorization events from the workflow task itself or an agent it owns. */
-export async function acceptTaskAuthorizationEventStep(input: {
- readonly delivery: TaskAuthorizationEventDelivery;
- readonly sessionState: DurableSessionState;
-}): Promise<boolean> {
- "use step";
-
- const { hookPayload, taskId } = input.delivery;
- const durableSession = readDurableSession(input.sessionState);
- const task = getBackgroundTasks(durableSession.state).get(taskId);
- if (task === undefined) return false;
-
- // A workflow tool can request authorization without invoking a child agent.
- // It has no agent handle, so bind its sender to the recorded task run, tool,
- // and launching turn before accepting the event.
- if (
- task.metadata.kind === "tool" &&
- task.run.address.runId === hookPayload.childSessionId &&
- task.metadata.name === hookPayload.subagentName &&
- task.turnId === hookPayload.event.data.turnId
- ) {
- // Completion can arrive after the body has returned; its sign-in UI must still close.
- return hookPayload.event.type === "authorization.completed" || task.status === "working";
- }
-
- 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;
-
- return task.status === "working";
-}
diff --git a/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.ts b/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.ts
index 8840dc1a8..a4827a3fe 100644
--- a/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.ts
+++ b/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.ts
@@ -13,7 +13,7 @@ import {
} from "#context/keys.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
import { emitSubagentEventStep } from "#execution/tools/subagent/emit-event-step.js";
-import { createSessionEventSink } from "#execution/session/event-sink.js";
+import { createSessionEventSink } from "#execution/publish-session-events.js";
import { createStubSandboxRegistry } from "#internal/testing/stub-sandbox-registry.js";
import { createTestSessionState } from "#internal/testing/session-state.js";
import type { MessageStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";
@@ -98,7 +98,6 @@ it.each(
expect(received.type).toBe(event.type);
if (received.type === "subagent.completed") expect(received.data.output).toBe("done");
expect(loadContext()).toBe(ctx);
- expect(stream.locked).toBe(false);
expect(received).toEqual(JSON.parse(new TextDecoder().decode(chunks[0])));
expect(ctx.has(SandboxKey)).toBe(true);
calls.push(kind);
@@ -224,9 +223,7 @@ it.each(events)(
},
});
const sink = createSessionEventSink({
- adapter: ctx.require(ChannelKey),
ctx,
- isFirstTurn: false,
sessionWritable: stream,
sessionId: "parent",
});
@@ -283,31 +280,3 @@ it("fails hook context setup before publishing so a retry cannot duplicate the e
expect(hook).not.toHaveBeenCalled();
expect(stream.locked).toBe(false);
});
-
-it("does not prepare context when no hook subscribes to the published event", async () => {
- const ctx = new ContextContainer();
- ctx.set(SessionIdKey, "parent");
- ctx.set(AuthKey, null);
- ctx.set(ChannelKey, { kind: "test" });
- const bundle: Partial<CompiledBundle> = {
- hookRegistry: createRuntimeHookRegistry([]),
- get turnAgent(): never {
- throw new Error("unsubscribed event prepared runtime context");
- },
- };
- ctx.set(BundleKey, bundle as CompiledBundle);
- vi.mocked(deserializeContext).mockResolvedValue(ctx);
- vi.mocked(serializeContext).mockReturnValue({ channel: true });
- const input = {
- event: events[0]!,
- sessionWritable: new WritableStream<Uint8Array>(),
- serializedContext: { channel: true },
- sessionState: createTestSessionState({ sessionId: "parent" }),
- };
- expect(await emitSubagentEventStep(input)).toEqual({
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- });
- expect(ctx.has(SessionKey)).toBe(false);
- expect(ctx.has(SandboxKey)).toBe(false);
-});
diff --git a/packages/eve/src/execution/tools/subagent/emit-event-step.ts b/packages/eve/src/execution/tools/subagent/emit-event-step.ts
index ece8b081f..1ba3fbcfc 100644
--- a/packages/eve/src/execution/tools/subagent/emit-event-step.ts
+++ b/packages/eve/src/execution/tools/subagent/emit-event-step.ts
@@ -1,84 +1,15 @@
-import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";
-import { withContextScope } from "#context/run-step.js";
-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
-import { hydrateDurableSession } from "#execution/session.js";
-import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";
-import { contextStorage } from "#context/container.js";
-import { deserializeContext, serializeContext } from "#context/serialize.js";
import {
- createDurableSessionState,
- readDurableSession,
- type DurableSessionState,
-} from "#execution/durable-session-store.js";
-import {
- createSessionEventSink,
- type PublishedSessionEvent,
-} from "#execution/session/event-sink.js";
+ publishSessionEvents,
+ type PublishedSessionEvents,
+ type SessionStepState,
+} from "#execution/publish-session-events.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
-/** Publishes a subagent notification, then runs its hooks without model preparation. */
-export async function emitSubagentEventStep(input: {
- readonly event: UnstampedMessageStreamEvent;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<{
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}> {
+/** Publishes a subagent notification without model preparation. */
+export async function emitSubagentEventStep(
+ input: SessionStepState & { readonly event: UnstampedMessageStreamEvent },
+): Promise<PublishedSessionEvents> {
"use step";
- const ctx = await deserializeContext(input.serializedContext);
- const bundle = ctx.require(BundleKey);
- const publish = async (): Promise<PublishedSessionEvent> => {
- const sink = createSessionEventSink({
- adapter: ctx.require(ChannelKey),
- ctx,
- isFirstTurn: input.sessionState.emissionState.sequence === 0,
- sessionWritable: input.sessionWritable,
- sessionId: input.sessionState.sessionId,
- });
- try {
- return await contextStorage.run(ctx, () => sink.emit(input.event));
- } finally {
- sink.release();
- }
- };
- // Decided before publishing to prevent duplicate events: subscribed events
- // prepare hook context before the write, so a setup failure retries this step
- // without having published. Unsubscribed events skip that setup entirely.
- const registry = bundle.hookRegistry;
- if (
- (registry.streamEventsByType.get(input.event.type)?.length ?? 0) === 0 &&
- registry.streamEventsWildcard.length === 0
- ) {
- await publish();
- return { serializedContext: serializeContext(ctx), sessionState: input.sessionState };
- }
-
- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
- const session = hydrateDurableSession({
- durable: readDurableSession(input.sessionState),
- turnAgent: effectiveAgent.turnAgent,
- compactionOverrides: { thresholdPercent: effectiveAgent.thresholdPercent },
- });
- const scoped = await withContextScope(ctx, session, async (enriched) => {
- const emitted = await publish();
- if (!emitted.suppressed) {
- await dispatchStreamEventHooks({
- cancelTurn: undefined,
- ctx,
- registry,
- event: emitted.event,
- });
- }
- return { result: undefined, session: enriched };
- });
- return {
- serializedContext: serializeContext(ctx),
- sessionState: createDurableSessionState({
- session: reconcileSessionContinuationToken(ctx, scoped.session),
- }),
- };
+ return await publishSessionEvents(input, [input.event]);
}
diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts
index b28b6beb2..90918ff3c 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts
@@ -1,10 +1,17 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { ask, attachWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
+import {
+ ask,
+ attachWorkflowToolRunContext,
+ WorkflowToolRunAsks,
+} from "#execution/tools/workflow/ask.js";
import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
+import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.js";
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
import {
- agent,
+ invokeAgent,
type AgentInvocationReply,
+ type InternalAgentInput,
validateAgentInput,
} from "#execution/tools/subagent/invoke-agent.js";
import type { ToolContext } from "#tools/definition.js";
@@ -27,6 +34,24 @@ vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({
}));
beforeEach(() => vi.resetAllMocks());
+const agentContext = {} as AgentSessionContext;
+
+function runOwner(inbox: string): WorkflowToolRunInbox {
+ return {
+ sent: 0,
+ send: async (message) => {
+ await mocks.resumeHook(inbox, message);
+ },
+ };
+}
+
+function invokeResearch(
+ ctx: ToolContext,
+ input: Pick<InternalAgentInput, "message" | "outputSchema">,
+) {
+ return invokeAgent(ctx, { ...input, target: "research" }, { invocationId: "call-1:agent-reply" });
+}
+
describe("workflow helper context errors", () => {
it.each([
["ordinary tool", { callId: "call-1", session: {} }],
@@ -35,10 +60,7 @@ describe("workflow helper context errors", () => {
["missing context", undefined],
["null context", null],
])("rejects %s before creating hooks or dispatching work", async (_name, context) => {
- const ctx = context as ToolContext;
- await expect(agent(ctx, "reviewer", { message: "Review" })).rejects.toThrow(
- "ctx.agent() requires a defineWorkflowTool() executor context.",
- );
+ const ctx = context as never;
expect(() => ask(ctx, { prompt: "Continue?" })).toThrow(
"ctx.ask() requires a defineWorkflowTool() executor context.",
);
@@ -48,12 +70,6 @@ describe("workflow helper context errors", () => {
});
describe("agent invocation input", () => {
- it("requires a non-empty positional agent name", () => {
- expect(() => validateAgentInput({ message: "Review", target: "" })).toThrow(
- "agent() requires a non-empty agent name as its first argument.",
- );
- });
-
it.each([null, [], "object"])("rejects a non-object output schema (%j)", (outputSchema) => {
expect(() =>
validateAgentInput({
@@ -61,11 +77,11 @@ describe("agent invocation input", () => {
outputSchema: outputSchema as never,
target: "reviewer",
}),
- ).toThrow("agent() `outputSchema` must be a JSON Schema object.");
+ ).toThrow('Agent tool "reviewer" `outputSchema` must be a JSON Schema object.');
});
});
-describe("background agent invocation routing", () => {
+describe("workflow agent invocation routing", () => {
it("stops waiting when the workflow body is cancelled", async () => {
const controller = new AbortController();
mocks.createHook.mockReturnValue({
@@ -74,9 +90,10 @@ describe("background agent invocation routing", () => {
});
const ctx = { abortSignal: controller.signal, callId: "call-1" } as ToolContext;
attachWorkflowToolRunContext(ctx, {
+ asks: new WorkflowToolRunAsks("run-1"),
+ control: "control",
from: {
callId: "call-1",
- execution: "background",
input: { message: "Find it" },
runId: "run-1",
sequence: 0,
@@ -84,12 +101,11 @@ describe("background agent invocation routing", () => {
toolName: "research",
turnId: "turn-1",
},
- owner: {
- inbox: "owner-inbox",
- },
+ agentContext,
+ owner: runOwner("owner-inbox"),
});
- const result = agent(ctx, "research", { message: "Find it" });
+ const result = invokeResearch(ctx, { message: "Find it" });
await vi.waitFor(() => expect(mocks.resumeHook).toHaveBeenCalledOnce());
controller.abort(new Error("task cancelled"));
@@ -131,7 +147,6 @@ describe("background agent invocation routing", () => {
mocks.resumeHook.mockImplementation(async () => undefined);
const from: WorkflowToolRunRef = {
callId: "call-1",
- execution: "background",
input: { message: "Find it" },
runId: "run-1",
sequence: 0,
@@ -141,10 +156,11 @@ describe("background agent invocation routing", () => {
};
const ctx = { callId: "call-1" } as ToolContext;
attachWorkflowToolRunContext(ctx, {
+ asks: new WorkflowToolRunAsks("run-1"),
+ control: "control",
from,
- owner: {
- inbox: "owner-inbox",
- },
+ agentContext,
+ owner: runOwner("owner-inbox"),
});
const outputSchema = {
@@ -152,7 +168,7 @@ describe("background agent invocation routing", () => {
required: ["findings"],
type: "object",
};
- await expect(agent(ctx, "research", { message: "Find it", outputSchema })).resolves.toEqual({
+ await expect(invokeResearch(ctx, { message: "Find it", outputSchema })).resolves.toEqual({
findings: ["available"],
});
@@ -168,65 +184,6 @@ describe("background agent invocation routing", () => {
});
});
- it("derives unique invocation ids for repeated parallel calls", async () => {
- for (const token of ["reply-1", "reply-2"]) {
- const replies: AgentInvocationReply[] = [
- {
- kind: "runtime-action-result",
- results: [
- {
- callId: `call-1:${token}`,
- kind: "subagent-result",
- origin: "child",
- output: token,
- subagentName: "research",
- } as never,
- ],
- },
- { kind: "agent-settled", callId: `call-1:${token}` },
- ];
- mocks.createHook.mockReturnValueOnce({
- [Symbol.asyncIterator]: () => ({
- next: async () =>
- replies.length > 0
- ? { done: false as const, value: replies.shift()! }
- : { done: true as const, value: undefined },
- }),
- token,
- });
- }
- mocks.resumeHook.mockImplementation(async () => undefined);
- const ctx = { callId: "call-1" } as ToolContext;
- attachWorkflowToolRunContext(ctx, {
- from: {
- callId: "call-1",
- execution: "blocking",
- input: {},
- runId: "run-1",
- sequence: 0,
- stepIndex: 0,
- toolName: "research",
- turnId: "turn-1",
- },
- owner: { inbox: "owner-inbox" },
- });
-
- await expect(
- Promise.all([
- agent(ctx, "research", { message: "First" }),
- agent(ctx, "research", { message: "Second" }),
- ]),
- ).resolves.toEqual(["reply-1", "reply-2"]);
-
- const requests = mocks.resumeHook.mock.calls
- .map(([, message]) => message.request)
- .filter((request) => request.kind === "agent-invoke");
- expect(requests.map((request) => request.invocationId)).toEqual([
- "call-1:reply-1",
- "call-1:reply-2",
- ]);
- });
-
it("waits for agent calls inside a blocking workflow tool", async () => {
const result = {
callId: "call-1:agent-reply",
@@ -263,9 +220,10 @@ describe("background agent invocation routing", () => {
});
const ctx = { callId: "call-1" } as ToolContext;
attachWorkflowToolRunContext(ctx, {
+ asks: new WorkflowToolRunAsks("run-1"),
+ control: "control",
from: {
callId: "call-1",
- execution: "blocking",
input: { message: "Find it" },
runId: "run-1",
sequence: 0,
@@ -273,16 +231,15 @@ describe("background agent invocation routing", () => {
toolName: "research",
turnId: "turn-1",
},
- owner: {
- inbox: "owner-inbox",
- },
+ agentContext,
+ owner: runOwner("owner-inbox"),
});
- await expect(agent(ctx, "research", { message: "Find it" })).resolves.toBe("inline");
+ await expect(invokeResearch(ctx, { message: "Find it" })).resolves.toBe("inline");
expect(mocks.resumeHook).toHaveBeenCalledTimes(2);
expect(mocks.resumeHook).toHaveBeenNthCalledWith(1, "owner-inbox", {
kind: "request",
- from: expect.objectContaining({ execution: "blocking", runId: "run-1" }),
+ from: expect.objectContaining({ runId: "run-1" }),
replyTo: "agent-reply",
request: {
input: { message: "Find it", target: "research" },
@@ -317,9 +274,10 @@ describe("background agent invocation routing", () => {
});
const ctx = { callId: "call-1" } as ToolContext;
attachWorkflowToolRunContext(ctx, {
+ asks: new WorkflowToolRunAsks("run-1"),
+ control: "control",
from: {
callId: "call-1",
- execution: "blocking",
input: {},
runId: "run-1",
sequence: 0,
@@ -327,10 +285,11 @@ describe("background agent invocation routing", () => {
toolName: "research",
turnId: "turn-1",
},
- owner: { inbox: "owner" },
+ agentContext,
+ owner: runOwner("owner"),
});
const returned = vi.fn();
- const output = agent(ctx, "research", { message: "Find it" }).then(
+ const output = invokeResearch(ctx, { message: "Find it" }).then(
(value) => {
returned();
return value;
@@ -382,9 +341,10 @@ describe("background agent invocation routing", () => {
});
const ctx = { callId: "call-1" } as ToolContext;
attachWorkflowToolRunContext(ctx, {
+ asks: new WorkflowToolRunAsks("run-1"),
+ control: "control",
from: {
callId: "call-1",
- execution: "blocking",
input: { message: "Find it" },
runId: "run-1",
sequence: 0,
@@ -392,12 +352,11 @@ describe("background agent invocation routing", () => {
toolName: "research",
turnId: "turn-1",
},
- owner: {
- inbox: "owner-inbox",
- },
+ agentContext,
+ owner: runOwner("owner-inbox"),
});
- await expect(agent(ctx, "research", { message: "Find it" })).rejects.toEqual(failure.output);
+ await expect(invokeResearch(ctx, { message: "Find it" })).rejects.toEqual(failure.output);
expect(mocks.resumeHook).toHaveBeenCalledTimes(1);
expect(mocks.resumeHook).not.toHaveBeenCalledWith(
"owner-inbox",
@@ -466,7 +425,6 @@ describe("background agent invocation routing", () => {
mocks.resumeHook.mockImplementation(async () => undefined);
const from: WorkflowToolRunRef = {
callId: "call-1",
- execution: "background",
input: { message: "Find it" },
runId: "run-1",
sequence: 0,
@@ -476,13 +434,14 @@ describe("background agent invocation routing", () => {
};
const ctx = { callId: "call-1" } as ToolContext;
attachWorkflowToolRunContext(ctx, {
+ asks: new WorkflowToolRunAsks("run-1"),
+ control: "control",
from,
- owner: {
- inbox: "owner-inbox",
- },
+ agentContext,
+ owner: runOwner("owner-inbox"),
});
- await expect(agent(ctx, "research", { message: "Find it" })).resolves.toBe("done");
+ await expect(invokeResearch(ctx, { message: "Find it" })).resolves.toBe("done");
expect(mocks.resumeHook).toHaveBeenNthCalledWith(2, "owner-inbox", {
kind: "request",
@@ -507,7 +466,7 @@ describe("background agent invocation routing", () => {
},
);
- it("forwards background authorization as an owner authorization request", async () => {
+ it("forwards child authorization as an owner authorization request", async () => {
const replies: AgentInvocationReply[] = [
{
callId: "call-1",
@@ -551,7 +510,6 @@ describe("background agent invocation routing", () => {
mocks.resumeHook.mockImplementation(async () => undefined);
const from: WorkflowToolRunRef = {
callId: "call-1",
- execution: "background",
input: { message: "Find it", target: "research" },
runId: "run-1",
sequence: 0,
@@ -561,13 +519,14 @@ describe("background agent invocation routing", () => {
};
const ctx = { callId: "call-1" } as ToolContext;
attachWorkflowToolRunContext(ctx, {
+ asks: new WorkflowToolRunAsks("run-1"),
+ control: "control",
from,
- owner: {
- inbox: "owner-inbox",
- },
+ agentContext,
+ owner: runOwner("owner-inbox"),
});
- await expect(agent(ctx, "research", { message: "Find it" })).resolves.toBe("done");
+ await expect(invokeResearch(ctx, { message: "Find it" })).resolves.toBe("done");
expect(mocks.resumeHook).toHaveBeenCalledWith("owner-inbox", {
kind: "request",
diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.ts
index 94da39f05..fd1f14a7f 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-agent.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-agent.ts
@@ -1,21 +1,15 @@
import { createHook } from "#compiled/@workflow/core/index.js";
-import type {
- RuntimeActionResultHookPayload,
- SubagentAuthorizationEventHookPayload,
- SubagentInputRequestHookPayload,
-} from "#channel/types.js";
+import type { RuntimeActionResultHookPayload } from "#channel/types.js";
+import {
+ forwardAgentSessionRequest,
+ type AgentSessionRequest,
+} from "#execution/agent-sessions/requests.js";
import { 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 { disposeHook } from "#execution/hook-ownership.js";
-import {
- sessionCommandHookToken,
- sessionInboxHookToken,
-} from "#execution/session-inbox/address.js";
-import type { AgentInput } from "#tools/workflow-definition.js";
import type { ToolContext } from "#tools/definition.js";
export type InternalAgentInput = {
@@ -45,44 +39,27 @@ export interface AgentSettlementRequest {
readonly result: RuntimeSubagentChildResult;
}
-export type AgentInvocationEvent =
- | SubagentAuthorizationEventHookPayload
- | SubagentInputRequestHookPayload;
-
export type AgentInvocationReply =
- | AgentInvocationEvent
+ | AgentSessionRequest
| RuntimeActionResultHookPayload
| { readonly kind: "agent-settled"; readonly callId: string };
-/** Invokes an agent from a workflow tool. */
-export async function agent(
- ctx: ToolContext,
- target: string,
- input: AgentInput,
-): Promise<JsonValue> {
- readWorkflowToolRunRef(ctx);
- validateAgentInput({ ...input, target });
- return await invokeAgent(ctx, {
- agentId: input.agentId,
- message: input.message,
- outputSchema: input.outputSchema,
- target,
- });
-}
-
-/** Invokes an agent with a framework-selected replay-stable invocation id. */
+/**
+ * Invokes an agent for one of the model's agent tools, whose tool call id is
+ * the invocation id. The owning session spawns the child and leases its handle.
+ */
export async function invokeAgent(
ctx: ToolContext,
input: InternalAgentInput,
- options: { readonly invocationId?: string } = {},
+ options: { readonly invocationId: string },
): Promise<JsonValue> {
validateAgentInput(input);
const run = readWorkflowToolRunRef(ctx);
const owner = readWorkflowToolRunOwner(ctx);
const replies = createHook<AgentInvocationReply>();
- const invocationId = options.invocationId ?? `${ctx.callId}:${replies.token}`;
+ const { invocationId } = options;
try {
- await resumeHookStep(owner.inbox, {
+ await owner.send({
kind: "request",
from: run,
replyTo: replies.token,
@@ -101,7 +78,7 @@ export async function invokeAgent(
);
if (result !== undefined) {
if (result.origin === "child") {
- await resumeHookStep(owner.inbox, {
+ await owner.send({
kind: "request",
from: run,
replyTo: replies.token,
@@ -125,33 +102,11 @@ export async function invokeAgent(
continue;
}
if (reply.kind === "agent-settled") continue;
- if (reply.kind === "subagent-input-request") {
- await resumeHookStep(owner.inbox, {
- kind: "request",
- from: run,
- // Current session inboxes use their physical token. A remote child's
- // create-once operation hook is already a narrowed reply capability.
- replyTo:
- reply.childSessionInbox?.sessionId === reply.childSessionId
- ? sessionInboxHookToken(sessionCommandHookToken(reply.childSessionInbox.sessionId))
- : reply.childContinuationToken,
- request: {
- kind: "input-batch",
- requests: reply.event.requests,
- },
- requestCoordinates: {
- sequence: reply.event.sequence,
- stepIndex: reply.event.stepIndex,
- turnId: reply.event.turnId,
- },
- });
- continue;
- }
- await resumeHookStep(owner.inbox, {
- kind: "request",
+ await forwardAgentSessionRequest({
from: run,
+ owner,
replyTo: replies.token,
- request: { event: reply, kind: "authorization-request" },
+ request: reply,
});
}
} finally {
@@ -184,11 +139,8 @@ async function nextAgentReply(
}
export function validateAgentInput(input: InternalAgentInput): void {
- if (typeof input.target !== "string" || input.target.trim() === "") {
- throw new TypeError("agent() requires a non-empty agent name as its first argument.");
- }
if (typeof input.message !== "string" || input.message.trim() === "") {
- throw new TypeError("agent() requires a non-empty `message`.");
+ throw new TypeError(`Agent tool "${input.target}" requires a non-empty \`message\`.`);
}
if (
input.outputSchema !== undefined &&
@@ -196,6 +148,8 @@ export function validateAgentInput(input: InternalAgentInput): void {
input.outputSchema === null ||
Array.isArray(input.outputSchema))
) {
- throw new TypeError("agent() `outputSchema` must be a JSON Schema object.");
+ throw new TypeError(
+ `Agent tool "${input.target}" \`outputSchema\` must be a JSON Schema object.`,
+ );
}
}
diff --git a/packages/eve/src/execution/tools/subagent/invoke-origin.test.ts b/packages/eve/src/execution/tools/subagent/invoke-origin.test.ts
deleted file mode 100644
index 8c62f1e63..000000000
--- a/packages/eve/src/execution/tools/subagent/invoke-origin.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { ContextContainer } from "#context/container.js";
-import { deserializeContext } from "#context/serialize.js";
-import { prepareActionDispatch } from "#execution/coordination-dispatch-shared.js";
-import { createDurableSessionState } from "#execution/durable-session-store.js";
-import { setHarnessEmissionState } from "#harness/emission-state.js";
-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-import { prepareOwnerAgentInvocation } from "./invoke-preparation.js";
-
-vi.mock("#context/serialize.js", () => ({ deserializeContext: vi.fn() }));
-vi.mock("#execution/coordination-dispatch-shared.js", () => ({ prepareActionDispatch: vi.fn() }));
-
-describe("background invocation origin", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- const ctx = new ContextContainer();
- ctx.set(BundleKey, {
- subagentRegistry: {
- subagentsByName: new Map([
- [
- "research",
- {
- definition: {
- kind: "subagent",
- name: "research",
- nodeId: "research",
- description: "Research",
- },
- },
- ],
- ]),
- },
- } as never);
- vi.mocked(deserializeContext).mockResolvedValue(ctx);
- });
-
- it.each([true, false])(
- "uses the task's creating turn after the parent advances: task=%s",
- async (background) => {
- const session = registerWorkflowToolRun(
- setHarnessEmissionState(
- {
- agent: { dynamicModel: true, system: "", tools: [] },
- compaction: { recentWindowSize: 5, threshold: 10_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent",
- },
- { sessionStarted: true, sequence: 3, stepIndex: 2, turnId: "turn-3" },
- ),
- {
- callId: "task",
- toolName: { kind: "subagent", name: "research", agentId: "agent" }.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-inbox" },
- task: {
- taskId: "task",
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "subagent", name: "research", agentId: "agent" },
- },
- },
- );
- await prepareOwnerAgentInvocation({
- invocation: { target: "research", message: "Review Alice's plan" },
- invocationId: "original-call",
- serializedContext: {},
- sessionState: createDurableSessionState({ session }),
- taskId: background ? "task" : undefined,
- });
- expect(prepareActionDispatch).toHaveBeenCalledWith(
- expect.objectContaining({
- batch: expect.objectContaining({
- event: expect.objectContaining({
- turnId: background ? "turn-1" : "turn-3",
- stepIndex: background ? 0 : 2,
- }),
- }),
- }),
- );
- },
- );
-});
diff --git a/packages/eve/src/execution/tools/subagent/invoke-preparation.test.ts b/packages/eve/src/execution/tools/subagent/invoke-preparation.test.ts
index a36b3962a..13ca8d85a 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-preparation.test.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-preparation.test.ts
@@ -34,7 +34,7 @@ describe("planAgentDispatch", () => {
subagentRegistry: { subagentsByNodeId: new Map() },
turnAgent: {},
} as never,
- ctx: {} as never,
+ ctx: { get: () => undefined } as never,
session: session("root") as never,
}),
).toMatchObject({
@@ -86,7 +86,7 @@ describe("planAgentDispatch", () => {
},
turnAgent: {},
} as never,
- ctx: {} as never,
+ ctx: { get: () => undefined } as never,
knownAgentIds: [],
session: session() as never,
}),
diff --git a/packages/eve/src/execution/tools/subagent/invoke-preparation.ts b/packages/eve/src/execution/tools/subagent/invoke-preparation.ts
index 35fbab645..444157c21 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-preparation.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-preparation.ts
@@ -7,21 +7,12 @@ import {
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 {
+ RuntimeAgentDispatchRequest,
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,
@@ -29,16 +20,13 @@ import {
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";
+ getDynamicSubagentSelection,
+ readDynamicSubagentSelections,
+} from "#context/dynamic-subagent-lifecycle.js";
+import { resolveAgentAction, resolveAgentStartTarget } from "#execution/agent-sessions/target.js";
import type { SubagentStartTarget } from "#execution/tools/subagent/start.js";
-import type { SubagentInputSource } from "#subagents/tool.js";
import { createLogger } from "#internal/logging.js";
-import { getBackgroundTasks } from "#harness/workflow-tool-runs.js";
const log = createLogger("execution.agent-invocation");
@@ -59,28 +47,20 @@ export async function prepareOwnerAgentInvocation(input: {
readonly knownAgentIds?: readonly string[];
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
- readonly taskId?: string;
}): Promise<Omit<PreparedCoordinationDispatch<OwnerAgentDispatchPlanEntry>, "sessionState">> {
const durableSession = readDurableSession(input.sessionState);
const ctx = await deserializeContext(input.serializedContext);
const event = getHarnessEmissionState(durableSession.state);
- const task =
- input.taskId === undefined
- ? undefined
- : getBackgroundTasks(durableSession.state).get(input.taskId)?.run;
- const action = resolveAgentInvocationAction({
- ctx,
+ const action = resolveAgentAction({
+ bundle: ctx.require(BundleKey),
+ callId: input.invocationId,
+ dynamicSelections: readDynamicSubagentSelections(ctx),
input: input.invocation,
- invocationId: input.invocationId,
});
return await prepareActionDispatch({
batch: {
requests: [action],
- event: {
- ...event,
- stepIndex: task?.origin.stepIndex ?? event.stepIndex,
- turnId: task?.origin.turnId ?? activeTurnId(event),
- },
+ event: { ...event, turnId: activeTurnId(event) },
},
ctx,
durableSession,
@@ -134,71 +114,12 @@ export function planAgentDispatch(input: {
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 ? { type: "runtime" } : { description, type: "local" };
- return {
- kind: "start",
- target: { action, dynamicSubagentAgentConfig: dynamicAgentConfig, kind: "local", source },
- };
+ return resolveAgentStartTarget({
+ action: input.action,
+ bundle: input.bundle,
+ dynamicSelections: readDynamicSubagentSelections(input.ctx),
+ isRootSession: input.session.rootSessionId === undefined,
+ });
}
function ownerPlanReusesSandbox(input: {
@@ -218,64 +139,3 @@ function ownerPlanReusesSandbox(input: {
);
});
}
-
-function isRecursiveAgentAction(
- action: RuntimeAgentDispatchRequest,
- subagentsByNodeId: ReadonlyMap<string, unknown>,
-): action is RuntimeSubagentDispatchRequest {
- return (
- action.kind === "subagent-call" &&
- action.subagentName === "agent" &&
- !subagentsByNodeId.has(action.nodeId)
- );
-}
-
-export function resolveAgentInvocationAction(input: {
- readonly ctx: ContextReader;
- 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
index 1f81dcabc..b86cc90d5 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts
@@ -76,12 +76,12 @@ describe("blocking workflow agent continuation", () => {
}));
});
- it("forwards inherited activity when starting a background subagent", async () => {
+ it("forwards inherited activity when starting a subagent", async () => {
const activityObserver = {
sink: { url: "https://parent.example/activity", version: 1 as const },
workIdentity: {
- id: "work:task",
- kind: "task" as const,
+ id: "work:slack",
+ kind: "subagent" as const,
name: "slack",
parentId: "work:root",
rootSessionId: "root-session",
diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts b/packages/eve/src/execution/tools/subagent/invoke-step.test.ts
index cb86468e3..e7776a651 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-step.test.ts
@@ -2,7 +2,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import {
dispatchAgentInvocation,
- dispatchTaskAgentInvocationStep,
releaseAgentInvocationOwnerStep,
settleTaskAgentInvocationStep,
} from "#execution/tools/subagent/invoke-step.js";
@@ -11,13 +10,6 @@ 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";
-import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-import {
- AuthKey,
- InitiatorAuthKey,
- SessionDynamicSubagentSelectionsKey,
- TurnDynamicSubagentSelectionsKey,
-} from "#context/keys.js";
vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({
...(await importOriginal()),
@@ -49,15 +41,6 @@ const action = {
nodeId: "subagents/research",
subagentName: "research",
};
-const creatorAuth = {
- attributes: {},
- authenticator: "test-idp",
- principalId: "creator-current",
- principalType: "user" as const,
-};
-const sessionInitiatorAuth = { ...creatorAuth, principalId: "session-initiator" };
-const receiverAuth = { ...creatorAuth, principalId: "receiver-current" };
-const receiverInitiatorAuth = { ...creatorAuth, principalId: "receiver-initiator" };
const availableRecord = {
address: { continuationToken: "child", kind: "agent/local" as const, sessionId: "child" },
identity: { id: "agent-1", name: "research", nodeId: "subagents/research" },
@@ -116,7 +99,7 @@ describe("owner agent invocation dispatch", () => {
phase: "claimed",
ownerId: "task-1",
}),
- reply: { kind: "reply", parentToken: "agent-reply", taskId: "task-1" },
+ parentToken: "agent-reply",
}),
);
expect(dispatched).toMatchObject({ agentId: "agent-1", kind: "dispatched" });
@@ -212,220 +195,6 @@ describe("owner agent invocation dispatch", () => {
).toEqual(["agent-1", "agent-1"]);
});
- it.each([
- { dispatchKind: "start", taskKind: "subagent", observed: true },
- { dispatchKind: "resume", taskKind: "subagent", observed: true },
- { dispatchKind: "start", taskKind: "tool", observed: true },
- { dispatchKind: "resume", taskKind: "tool", observed: true },
- { dispatchKind: "start", taskKind: "subagent", observed: false },
- { dispatchKind: "resume", taskKind: "subagent", observed: false },
- ] as const)(
- "resolves task activity for $dispatchKind ($taskKind, observed=$observed)",
- async ({ dispatchKind, taskKind, observed }) => {
- const serializedContext = {
- [AuthKey.name]: receiverAuth,
- [InitiatorAuthKey.name]: receiverInitiatorAuth,
- [SessionDynamicSubagentSelectionsKey.name]: { source: "receiver-session" },
- [TurnDynamicSubagentSelectionsKey.name]: { source: "receiver-turn" },
- "eve.test": "preserved",
- };
- const taskDispatchContext = {
- auth: { current: creatorAuth, initiator: sessionInitiatorAuth },
- sessionDynamicSubagentSelections: { source: "creator-session" } as never,
- turnDynamicSubagentSelections: { source: "creator-turn" } as never,
- };
- const planningContext = {
- ...serializedContext,
- [AuthKey.name]: creatorAuth,
- [InitiatorAuthKey.name]: sessionInitiatorAuth,
- [SessionDynamicSubagentSelectionsKey.name]: { source: "creator-session" },
- [TurnDynamicSubagentSelectionsKey.name]: { source: "creator-turn" },
- };
- const taskWork = {
- callId: "task-call",
- id: "work:task",
- kind: "task" as const,
- name: "research",
- parentId: "work:root",
- rootSessionId: "root-session",
- rootTurnId: "root-turn",
- };
- const indexedSession = registerWorkflowToolRun(session, {
- callId: "task-1",
- toolName: { kind: taskKind, name: "research" }.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- activityWorkIdentity: taskWork,
- dispatchContext: taskDispatchContext,
- metadata: { kind: taskKind, name: "research" },
- taskId: "task-1",
- },
- });
- vi.mocked(readDurableSession).mockReturnValue(indexedSession as never);
- vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({
- ...prepared,
- auth: creatorAuth,
- activityObserver: observed
- ? {
- sink: { url: "https://parent.example/activity", version: 1 },
- workIdentity: {
- id: "work:root",
- kind: "root-turn",
- rootSessionId: "root-session",
- rootTurnId: "root-turn",
- },
- }
- : undefined,
- initiatorAuth: sessionInitiatorAuth,
- plan: [
- dispatchKind === "start"
- ? { kind: "start", target: { action, kind: "local", source: { type: "runtime" } } }
- : { kind: "resume", action, agentId: "agent-1" },
- ],
- serializedContext: planningContext,
- session: indexedSession,
- } as never);
- vi.mocked(startSubagent).mockResolvedValue(called);
- vi.mocked(dispatchToClaimedAgentAddress).mockResolvedValue(called);
-
- const result = await dispatchTaskAgentInvocationStep({
- ownerId: "task-1",
- replyTo: "agent-reply",
- request: {
- input: { message: "Find it", target: "research" },
- invocationId: "call-1",
- kind: "agent-invoke",
- },
- serializedContext,
- sessionState: {} as never,
- taskId: "task-1",
- });
-
- const taskObserver =
- observed && taskKind === "subagent"
- ? { sink: { url: "https://parent.example/activity", version: 1 }, workIdentity: taskWork }
- : undefined;
- if (dispatchKind === "start") {
- expect(startSubagent).toHaveBeenCalledWith(
- expect.objectContaining({
- auth: creatorAuth,
- initiatorAuth: sessionInitiatorAuth,
- taskActivityObserver: taskObserver,
- }),
- );
- } else {
- expect(dispatchToClaimedAgentAddress).toHaveBeenCalledWith(
- expect.objectContaining({ activityObserver: taskObserver, auth: creatorAuth }),
- );
- }
- expect(prepareOwnerAgentInvocation).toHaveBeenCalledWith(
- expect.objectContaining({ serializedContext: planningContext }),
- );
- expect(result).toMatchObject({ serializedContext });
- },
- );
-
- it("uses an anonymous task's captured auth despite an authenticated receiving turn", async () => {
- const serializedContext = {
- [AuthKey.name]: receiverAuth,
- [InitiatorAuthKey.name]: receiverInitiatorAuth,
- [SessionDynamicSubagentSelectionsKey.name]: { source: "receiver-session" },
- [TurnDynamicSubagentSelectionsKey.name]: { source: "receiver-turn" },
- };
- const planningContext = {
- [AuthKey.name]: null,
- [InitiatorAuthKey.name]: sessionInitiatorAuth,
- };
- const indexedSession = registerWorkflowToolRun(session, {
- callId: "task-1",
- toolName: "research",
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: {
- auth: { current: null, initiator: sessionInitiatorAuth },
- },
- metadata: { kind: "subagent", name: "research" },
- taskId: "task-1",
- },
- });
- vi.mocked(readDurableSession).mockReturnValue(indexedSession as never);
- vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({
- ...prepared,
- auth: null,
- initiatorAuth: sessionInitiatorAuth,
- plan: [{ kind: "start", target: { action, kind: "local", source: { type: "runtime" } } }],
- serializedContext: planningContext,
- session: indexedSession,
- } as never);
- vi.mocked(startSubagent).mockResolvedValue(called);
-
- const result = await dispatchTaskAgentInvocationStep({
- ownerId: "task-1",
- replyTo: "agent-reply",
- request: {
- input: { message: "Find it", target: "research" },
- invocationId: "call-1",
- kind: "agent-invoke",
- },
- serializedContext,
- sessionState: { sessionId: "parent" } as never,
- taskId: "task-1",
- });
-
- expect(startSubagent).toHaveBeenCalledWith(
- expect.objectContaining({ auth: null, initiatorAuth: sessionInitiatorAuth }),
- );
- expect(prepareOwnerAgentInvocation).toHaveBeenCalledWith(
- expect.objectContaining({ serializedContext: planningContext }),
- );
- expect(result).toMatchObject({ serializedContext });
- });
-
- it("rejects missing creator context before dispatching with receiver authentication", async () => {
- vi.mocked(readDurableSession).mockReturnValue({
- ...session,
- state: {
- ...session.state,
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task-1",
- toolName: "research",
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- metadata: { kind: "subagent", name: "research" },
- taskId: "task-1",
- },
- },
- ],
- },
- },
- } as never);
-
- await expect(
- dispatchTaskAgentInvocationStep({
- ownerId: "task-1",
- replyTo: "agent-reply",
- request: {
- input: { message: "Find it", target: "research" },
- invocationId: "call-1",
- kind: "agent-invoke",
- },
- serializedContext: { "eve.auth": receiverAuth },
- sessionState: { sessionId: "parent" } as never,
- taskId: "task-1",
- }),
- ).rejects.toThrow("Corrupt workflow tool run registry");
- expect(prepareOwnerAgentInvocation).not.toHaveBeenCalled();
- });
-
it("starts a fresh agent with task-owned handle semantics", async () => {
const reserved = {
callId: "call-1",
@@ -451,10 +220,7 @@ describe("owner agent invocation dispatch", () => {
const dispatched = await dispatch();
expect(startSubagent).toHaveBeenCalledWith(
- expect.objectContaining({
- parentContinuationToken: "agent-reply",
- taskId: "task-1",
- }),
+ expect.objectContaining({ parentContinuationToken: "agent-reply" }),
);
expect(dispatched).toMatchObject({ agentId: "agent-receipt", kind: "dispatched" });
expect(startSubagent).toHaveBeenCalledWith(
@@ -472,12 +238,8 @@ describe("owner agent invocation dispatch", () => {
});
});
-describe("task-owned agent settlement", () => {
- it.each(
- (["parked", "terminal"] as const).flatMap((kind) =>
- ([undefined, "tool", "subagent"] as const).map((taskKind) => ({ kind, taskKind })),
- ),
- )("applies a $kind child outcome under $taskKind ownership", async ({ kind, taskKind }) => {
+describe("owner agent settlement", () => {
+ it.each(["parked", "terminal"] as const)("applies a %s child outcome", async (kind) => {
const claimed = {
...availableRecord,
callId: "call-1",
@@ -485,24 +247,9 @@ describe("task-owned agent settlement", () => {
phase: "claimed" as const,
ownerId: "task-1",
};
- const owner =
- taskKind === undefined
- ? session
- : registerWorkflowToolRun(session, {
- callId: "call-1",
- toolName: "research",
- lifetime: "session",
- origin: { turnId: "turn", stepIndex: 0 },
- address: { runId: "run", hookToken: "hook" },
- task: {
- taskId: "task-1",
- metadata: { kind: taskKind, name: "research" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- });
vi.mocked(readDurableSession).mockReturnValue({
- ...owner,
- state: setAgentHandleStore(owner.state, { handles: [claimed] }),
+ ...session,
+ state: setAgentHandleStore(session.state, { handles: [claimed] }),
} as never);
const settled = await settleTaskAgentInvocationStep({
@@ -526,17 +273,12 @@ describe("task-owned agent settlement", () => {
},
ownerId: "task-1",
sessionState: {} as never,
- taskId: taskKind === undefined ? undefined : "task-1",
});
- expect(settled.completion).toEqual(
- taskKind === "subagent"
- ? undefined
- : {
- type: "subagent.completed",
- data: { callId: "call-1", subagentName: "research", output: "done" },
- },
- );
+ expect(settled.completion).toEqual({
+ type: "subagent.completed",
+ data: { callId: "call-1", subagentName: "research", output: "done" },
+ });
const handles = getAgentHandleStore(settled.sessionState.snapshot.session.state)?.handles ?? [];
expect(handles).toEqual(
kind === "parked" ? [expect.objectContaining({ phase: "available" })] : [],
@@ -656,6 +398,5 @@ async function dispatch() {
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
index 12a1c36d9..eb083575a 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-step.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-step.ts
@@ -9,7 +9,6 @@ import { prepareOwnerAgentInvocation } from "#execution/tools/subagent/invoke-pr
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 type { ActivityWorkIdentityV1 } from "#protocol/activity.js";
import {
createSubagentCalledEvent,
type SubagentCalledStreamEvent,
@@ -19,7 +18,7 @@ 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 { mintStartOperation } from "#execution/dispatch-start-operation.js";
import {
readDurableSession,
replaceDurableSessionSnapshot,
@@ -42,12 +41,8 @@ import {
AGENT_UNREACHABLE,
formatAgentBusyMessage,
} from "#subagents/agent-handle-errors.js";
-import { getBackgroundTasks, type TaskAgentDispatchContext } from "#harness/workflow-tool-runs.js";
import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
-import {
- clearProxyInputRequestsForChild,
- clearProxyInputRequestsForTask,
-} from "#harness/proxy-input-requests.js";
+import { clearProxyInputRequestsForChild } from "#harness/proxy-input-requests.js";
import {
accumulateSessionUsage,
getTurnUsageState,
@@ -58,12 +53,6 @@ import {
flushAgentInvocationTraces,
settleAgentInvocationTrace,
} from "#tracing/agent-invocation-terminal.js";
-import {
- AuthKey,
- InitiatorAuthKey,
- SessionDynamicSubagentSelectionsKey,
- TurnDynamicSubagentSelectionsKey,
-} from "#context/keys.js";
export type AgentInvocationDispatchResult =
| {
@@ -80,13 +69,8 @@ export type AgentInvocationDispatchResult =
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 activityWorkIdentity?: ActivityWorkIdentityV1;
readonly callbackBaseUrl: string;
readonly emit?: HandleEventFn;
readonly replyTo: string;
@@ -94,9 +78,6 @@ export async function dispatchAgentInvocation(input: {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
readonly ownerId: string;
- /** Optional creator snapshot used only to prepare this invocation. */
- readonly invocationContext?: Record<string, unknown>;
- readonly taskId?: string | undefined;
}): Promise<AgentInvocationDispatchResult> {
const durableSession = readDurableSession(input.sessionState);
const agentHandles = getAgentHandleStore(durableSession.state)?.handles ?? [];
@@ -104,9 +85,8 @@ export async function dispatchAgentInvocation(input: {
invocation: input.request.input,
invocationId: input.request.invocationId,
knownAgentIds: agentHandles.map((handle) => handle.identity.id),
- serializedContext: input.invocationContext ?? input.serializedContext,
+ serializedContext: input.serializedContext,
sessionState: input.sessionState,
- taskId: input.taskId,
});
const entry = prepared.plan[0];
if (entry === undefined) {
@@ -129,13 +109,8 @@ export async function dispatchAgentInvocation(input: {
sessionId: prepared.session.sessionId,
sessionState: durableSession.state,
startTimeMs: Date.now(),
- taskId: input.taskId,
turnId: prepared.batch.event.turnId,
});
- const taskActivityObserver =
- prepared.activityObserver === undefined || input.activityWorkIdentity === undefined
- ? undefined
- : { sink: prepared.activityObserver.sink, workIdentity: input.activityWorkIdentity };
let session = prepared.session;
const currentAgentHandles = (): readonly AgentHandle[] =>
getAgentHandleStore(session.state)?.handles ?? [];
@@ -200,16 +175,12 @@ export async function dispatchAgentInvocation(input: {
dynamicRemoteAgent: entry.dynamicRemoteAgent,
});
outcome = await dispatchToClaimedAgentAddress({
- activityObserver: taskActivityObserver,
action: entry.action,
auth: prepared.auth,
bundle,
currentSession: session,
handle: claimed,
- reply:
- input.taskId === undefined
- ? { kind: "reply", parentToken: input.replyTo }
- : { kind: "reply", parentToken: input.replyTo, taskId: input.taskId },
+ parentToken: input.replyTo,
});
if (outcome.kind === "error" && outcome.deliveryPermanent === true) {
applyHandleCommand({ agentId: entry.agentId, kind: "remove", ownerId: input.ownerId });
@@ -228,9 +199,9 @@ export async function dispatchAgentInvocation(input: {
const start =
reserved.length === 1
? { identity: reserved[0]!.identity, operation: { id: reserved[0]!.operationId } }
- : createSubagentReceiptIdentity({
+ : mintStartOperation({
callId: action.callId,
- subagentName:
+ name:
action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName,
nodeId: action.nodeId,
parentSessionId: prepared.session.sessionId,
@@ -267,10 +238,8 @@ export async function dispatchAgentInvocation(input: {
localDevRequest: prepared.localDevRequest,
parentContinuationToken: input.replyTo,
activityObserver: prepared.activityObserver,
- taskActivityObserver,
sandboxSessionId: prepared.sandboxSessionId,
session,
- taskId: input.taskId,
target: entry.target,
trace: tracing.dispatch,
});
@@ -337,57 +306,19 @@ export async function dispatchAgentInvocation(input: {
}
/**
- * 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.
+ * Dispatches one workflow-owned agent request. 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> {
+): Promise<AgentInvocationDispatchResult> {
"use step";
- let activityWorkIdentity: ActivityWorkIdentityV1 | undefined;
- let taskDispatchContext: TaskAgentDispatchContext | undefined;
- if (input.taskId !== undefined) {
- const session = readDurableSession(input.sessionState);
- const task = getBackgroundTasks(session.state).get(input.taskId);
- if (task?.status !== "working") {
- return { kind: "not-admitted", sessionState: input.sessionState };
- }
- taskDispatchContext = task.run.task.dispatchContext;
- if (task.metadata.kind === "subagent") {
- activityWorkIdentity = task.run.task.activityWorkIdentity;
- }
- }
- const dispatched = await dispatchAgentInvocation({
+ return await dispatchAgentInvocation({
...input,
- activityWorkIdentity,
callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),
- invocationContext:
- taskDispatchContext === undefined
- ? undefined
- : applyTaskDispatchContext(input.serializedContext, taskDispatchContext),
});
- return dispatched;
-}
-
-function applyTaskDispatchContext(
- parent: Record<string, unknown>,
- task: TaskAgentDispatchContext,
-): Record<string, unknown> {
- const context = {
- ...parent,
- [AuthKey.name]: task.auth.current,
- [InitiatorAuthKey.name]: task.auth.initiator,
- };
- for (const [key, value] of [
- [SessionDynamicSubagentSelectionsKey.name, task.sessionDynamicSubagentSelections],
- [TurnDynamicSubagentSelectionsKey.name, task.turnDynamicSubagentSelections],
- ] as const) {
- if (value === undefined) delete context[key];
- else context[key] = value;
- }
- return context;
}
/** Applies an owner-scoped child settlement to the parent session's canonical state. */
@@ -396,7 +327,6 @@ export async function settleTaskAgentInvocationStep(input: {
readonly result: RuntimeSubagentChildResult;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
- readonly taskId?: string | undefined;
}): Promise<{
readonly settled: boolean;
readonly completion?: SubagentCompletedStreamEvent;
@@ -449,16 +379,11 @@ export async function settleTaskAgentInvocationStep(input: {
: 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.result.outcome.kind === "terminal" && "continuationToken" in handle.address) {
+ session = clearProxyInputRequestsForChild(
+ session as Parameters<typeof clearProxyInputRequestsForChild>[0],
+ handle.address.continuationToken,
+ );
}
session = setTurnUsageState(
session,
@@ -467,13 +392,8 @@ export async function settleTaskAgentInvocationStep(input: {
usage: input.result.outcome.usageDelta,
}),
);
- const task =
- input.taskId === undefined ? undefined : getBackgroundTasks(session.state).get(input.taskId);
- // A generated subagent task completes when the parent records its task outcome.
- // Nested agents inside authored background workflows settle independently of that task.
- const isTaskAgent = task?.metadata.kind === "subagent" && task.run.callId === input.result.callId;
const completion: SubagentCompletedStreamEvent | undefined =
- input.result.outcome.result.kind !== "succeeded" || isTaskAgent
+ input.result.outcome.result.kind !== "succeeded"
? undefined
: {
type: "subagent.completed",
diff --git a/packages/eve/src/execution/tools/subagent/receipt-identity.ts b/packages/eve/src/execution/tools/subagent/receipt-identity.ts
deleted file mode 100644
index dab16e9b7..000000000
--- a/packages/eve/src/execution/tools/subagent/receipt-identity.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-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/start.ts b/packages/eve/src/execution/tools/subagent/start.ts
index a85b20914..c85f8da86 100644
--- a/packages/eve/src/execution/tools/subagent/start.ts
+++ b/packages/eve/src/execution/tools/subagent/start.ts
@@ -49,13 +49,8 @@ export async function startSubagent(input: {
readonly activityObserver?: ActivityObserverConfig & {
readonly workIdentity: ActivityWorkIdentityV1;
};
- /** The backing agent reports as this task, rather than as a separate child work item. */
- readonly taskActivityObserver?: ActivityObserverConfig & {
- readonly workIdentity: ActivityWorkIdentityV1;
- };
readonly sandboxSessionId: string;
readonly session: RuntimeSession;
- readonly taskId?: string;
readonly target: SubagentStartTarget;
readonly trace: AgentChildTraceDispatch;
}): Promise<DispatchOutcome> {
@@ -90,11 +85,10 @@ export async function startSubagent(input: {
initiatorAuth: input.initiatorAuth,
localDevRequest: input.localDevRequest,
parent,
- activityObserver: input.taskActivityObserver ?? input.activityObserver,
+ activityObserver: input.activityObserver,
sandboxSessionId: input.sandboxSessionId,
session: input.session,
source: input.target.source,
- taskId: input.taskId,
});
case "remote":
return startRemoteSubagent({
@@ -107,9 +101,7 @@ export async function startSubagent(input: {
initiatorAuth: input.initiatorAuth,
parent,
activityObserver: input.activityObserver,
- taskActivityObserver: input.taskActivityObserver,
session: input.session,
- taskId: input.taskId,
});
default: {
const _exhaustive: never = input.target;
diff --git a/packages/eve/src/execution/tools/subagent/steer.ts b/packages/eve/src/execution/tools/subagent/steer.ts
deleted file mode 100644
index dd8094df1..000000000
--- a/packages/eve/src/execution/tools/subagent/steer.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import type { ContextReader } from "#context/key.js";
-import { AuthKey } from "#context/keys.js";
-import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
-import type { HarnessSession } from "#harness/types.js";
-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-import type { JsonObject } from "#shared/json.js";
-import { createAgentContinuationBundle } from "#subagents/continuation-bundle.js";
-import { dispatchToClaimedAgentAddress } from "#subagents/handle-dispatch.js";
-import type { TaskOwnedAgentHandle } from "#subagents/handles/store.js";
-import { normalizeRequestedOutputSchema } from "#subagents/invocation.js";
-import { resolveAgentInvocationAction } from "./invoke-preparation.js";
-
-export async function steerBackgroundAgent(input: {
- readonly ctx: ContextReader;
- readonly handle: Extract<TaskOwnedAgentHandle, { phase: "claimed" }>;
- readonly callId: string;
- readonly input: JsonObject;
- readonly session: HarnessSession;
-}): Promise<void> {
- const action = resolveAgentInvocationAction({
- ctx: input.ctx,
- invocationId: input.callId,
- input: {
- agentId: input.handle.identity.id,
- message: typeof input.input.message === "string" ? input.input.message : "",
- outputSchema: normalizeRequestedOutputSchema(input.input.outputSchema),
- target: input.handle.identity.name,
- },
- });
- const dynamic = getDynamicSubagentSelection(input.ctx, input.handle.identity.nodeId);
- const outcome = await dispatchToClaimedAgentAddress({
- action,
- auth: input.ctx.get(AuthKey) ?? null,
- bundle: createAgentContinuationBundle({
- action,
- bundle: input.ctx.require(BundleKey),
- dynamicRemoteAgent: dynamic?.kind === "remote" ? dynamic.remoteAgent : undefined,
- }),
- currentSession: input.session,
- handle: input.handle,
- reply: { kind: "steer" },
- });
- if (outcome.kind === "error") {
- throw new Error(JSON.stringify(outcome.result.output));
- }
-}
diff --git a/packages/eve/src/execution/tools/subagent/task-activity.integration.test.ts b/packages/eve/src/execution/tools/subagent/task-activity.integration.test.ts
deleted file mode 100644
index 2f349a0b5..000000000
--- a/packages/eve/src/execution/tools/subagent/task-activity.integration.test.ts
+++ /dev/null
@@ -1,333 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { ActivityObserverConfig, RunInput, TurnCaller } from "#channel/types.js";
-import { ActivityObserverKey } from "#context/keys.js";
-import {
- parseActivityObserverField,
- validateActivityObserverBinding,
-} from "#eve-channel/activity-observer-request.js";
-import {
- deriveBackgroundTaskActivityObserver,
- deriveRootTurnWorkIdentity,
-} from "#execution/activity-work.js";
-import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";
-import { projectSessionActivity } from "#execution/session-activity-projection.js";
-import { projectTaskActivity } from "#execution/tasks/child/notify.js";
-import { startSubagent, type SubagentStartTarget } from "#execution/tools/subagent/start.js";
-import type { ActivityEventV1, ActivitySnapshotV1 } from "#protocol/activity.js";
-import type { MessageStreamEvent } from "#protocol/message.js";
-import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
-import { createRuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
-import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
-import { dispatchToClaimedAgentAddress } from "#subagents/handle-dispatch.js";
-import type { AgentAddress } from "#subagents/handles/store.js";
-import { bindTurnCallerContextStep } from "#subagents/parent-notification.js";
-import type {
- continueRemoteAgentSession as ContinueRemote,
- startRemoteAgentSession as StartRemote,
-} from "#subagents/remote-dispatch.js";
-
-type Observer = ActivityObserverConfig & {
- workIdentity: NonNullable<ActivityObserverConfig["workIdentity"]>;
-};
-type Kind = "local" | "remote";
-const { createSession, dispatchSession, startRemote, continueRemote } = vi.hoisted(() => ({
- createSession: vi.fn(async (_input: RunInput) => undefined),
- dispatchSession: vi.fn(async (_input: { command: { caller?: TurnCaller } }) => ({
- status: "accepted",
- })),
- startRemote: vi.fn(async (_input: Parameters<typeof StartRemote>[0]) => ({
- sessionId: "remote-session",
- })),
- continueRemote: vi.fn(async (_input: Parameters<typeof ContinueRemote>[0]) => undefined),
-}));
-vi.mock("#execution/workflow-runtime.js", () => ({
- createWorkflowRuntime: () => ({ createSession, dispatchSession }),
- waitForCommandHookOwner: async () => ({ runId: "child-session" }),
-}));
-vi.mock("#subagents/remote-dispatch.js", () => ({
- resolveRemoteAgentForAction: () => ({ url: "https://remote.example/eve/v1" }),
- startRemoteAgentSession: startRemote,
- continueRemoteAgentSession: continueRemote,
-}));
-
-const at = "2026-01-01T00:00:00.000Z";
-const root = deriveRootTurnWorkIdentity({
- sessionId: "parent",
- auth: { current: null, initiator: null },
- turn: { id: "parent-turn", sequence: 0 },
-});
-const parentObserver: Observer = {
- sink: {
- url: "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- workIdentity: root,
-};
-const session = {
- sessionId: "parent",
- continuationToken: "parent-token",
- history: [],
- agent: { dynamicModel: true as const, system: "", tools: [] },
- compaction: { recentWindowSize: 5, threshold: 10_000 },
-};
-const bundle = {
- subagentRegistry: createRuntimeSubagentRegistry({ subagents: [] }),
-} as Parameters<typeof startSubagent>[0]["bundle"];
-
-function taskObserver(callId: string, label?: string): Observer {
- const observer = deriveBackgroundTaskActivityObserver({
- activityObserver: parentObserver,
- callId,
- label,
- name: "research",
- parentSessionId: session.sessionId,
- parentTurnId: "parent-turn",
- rootSessionId: session.sessionId,
- });
- if (observer?.workIdentity === undefined) throw new Error("Expected task identity");
- return { ...observer, workIdentity: observer.workIdentity };
-}
-
-function target(kind: Kind, callId: string): SubagentStartTarget {
- const action = {
- callId,
- description: "Research",
- input: { message: "Find it" },
- name: "research",
- nodeId: "subagents/research",
- };
- return kind === "local"
- ? {
- kind,
- action: { ...action, kind: "subagent-call", subagentName: "research" },
- source: { type: "runtime" },
- }
- : { kind, action: { ...action, kind: "remote-agent-call", remoteAgentName: "research" } };
-}
-
-async function start(kind: Kind, task?: Observer): Promise<ActivityObserverConfig | undefined> {
- const result = await startSubagent({
- auth: null,
- batchEvent: { sequence: 0, turnId: "parent-turn" },
- bundle,
- callbackBaseUrl: "https://parent.example",
- capabilities: undefined,
- channelMetadata: undefined,
- currentSession: session,
- fanoutSize: 1,
- initiatorAuth: null,
- parentContinuationToken: "parent-token",
- activityObserver: task === undefined ? undefined : parentObserver,
- taskActivityObserver: task,
- sandboxSessionId: "sandbox",
- session,
- taskId: "task-a",
- target: target(kind, "task-a"),
- trace: { originAudience: "private", parentTraceContext: undefined },
- });
- expect(result.kind).toBe("called");
- if (kind === "local") return createSession.mock.calls[0]![0].activityObserver;
- const request = startRemote.mock.calls[0]![0];
- if (request.activityObserver !== undefined) {
- const parsed = parseActivityObserverField(request.activityObserver);
- if (parsed === undefined || parsed instanceof Response) throw new Error("Invalid observer");
- expect(
- validateActivityObserverBinding(parsed, {
- callId: request.action.callId,
- subagentName: request.action.remoteAgentName,
- token: "parent-token",
- url: `${request.callbackBaseUrl}/eve/v1/callback/parent-token`,
- }),
- ).toBeUndefined();
- }
- return request.activityObserver;
-}
-
-function apply(snapshot: ActivitySnapshotV1, events: readonly ActivityEventV1[]) {
- return reduceActivityBatch(snapshot, { version: 1, events });
-}
-function project(event: MessageStreamEvent, observer: ActivityObserverConfig, sessionId = "child") {
- return projectSessionActivity({ event, sessionId, workIdentity: observer.workIdentity });
-}
-function turn(type: "turn.started" | "turn.completed", turnId: string): MessageStreamEvent {
- return { type, data: { sequence: 0, turnId }, meta: { id: `${type}:${turnId}`, at } };
-}
-function tool(type: "actions.requested" | "action.result", turnId: string): MessageStreamEvent {
- const data = { turnId, sequence: 1, stepIndex: 0 };
- const meta = { id: `${type}:${turnId}`, at };
- return type === "actions.requested"
- ? {
- type,
- meta,
- data: {
- ...data,
- actions: [{ kind: "tool-call", callId: "search-call", toolName: "search", input: {} }],
- },
- }
- : {
- type,
- meta,
- data: {
- ...data,
- status: "completed",
- result: {
- kind: "tool-result",
- callId: "search-call",
- toolName: "search",
- output: "Found it",
- },
- },
- };
-}
-function taskEvents(observer: Observer, status: "working" | "completed" | "cancelled") {
- return projectTaskActivity({
- activityObserver: observer,
- settledAt: at,
- view: {
- taskId: observer.workIdentity.callId!,
- metadata: { kind: "subagent", name: "research" },
- ...(status === "completed"
- ? { status, lastOutput: { type: "result" as const, data: "Done" } }
- : { status }),
- },
- });
-}
-function initialSnapshot() {
- return apply(
- createActivitySnapshot(),
- project(turn("turn.started", "parent-turn"), parentObserver, "parent"),
- );
-}
-
-describe("task-owned subagent activity", () => {
- beforeEach(() => vi.clearAllMocks());
-
- it.each(["local", "remote"] as const)(
- "keeps one task item through %s child activity and settlement",
- async (kind) => {
- const task = taskObserver("task-a", "Investigator");
- const captured = await start(kind, task);
- if (captured === undefined) throw new Error("Expected child observer");
- expect(captured).toEqual(task);
- expect(captured.workIdentity).toMatchObject({ label: "Investigator", name: "research" });
- let snapshot = apply(initialSnapshot(), taskEvents(task, "working"));
- snapshot = apply(snapshot, project(turn("turn.started", "child-turn"), captured));
- snapshot = apply(snapshot, project(tool("actions.requested", "child-turn"), captured));
- expect(Object.values(snapshot.work)).toHaveLength(2);
- expect(snapshot.work[task.workIdentity.id]).toMatchObject({
- kind: "task",
- parentId: root.id,
- phase: "running",
- });
- expect(Object.values(snapshot.actions)).toEqual([
- expect.objectContaining({ parentWorkId: task.workIdentity.id, phase: "running" }),
- ]);
- snapshot = apply(snapshot, project(tool("action.result", "child-turn"), captured));
- snapshot = apply(snapshot, project(turn("turn.completed", "child-turn"), captured));
- expect(snapshot.work[task.workIdentity.id]?.phase).toBe("running");
- snapshot = apply(snapshot, taskEvents(task, "completed"));
- snapshot = apply(
- snapshot,
- project(turn("turn.completed", "parent-turn"), parentObserver, "parent"),
- );
- expect(Object.values(snapshot.work).map((work) => work.phase)).toEqual([
- "completed",
- "completed",
- ]);
- expect(Object.values(snapshot.actions).map((action) => action.phase)).toEqual(["completed"]);
- },
- );
-
- it.each(["local", "remote"] as const)(
- "keeps %s observation disabled without an observer",
- async (kind) => {
- expect(await start(kind)).toBeUndefined();
- },
- );
-
- it.each([
- ["local", "completed"],
- ["local", "cancelled"],
- ["remote", "completed"],
- ["remote", "cancelled"],
- ] as const)("rebinds %s child progress after task A is %s", async (kind, status) => {
- const a = taskObserver("task-a");
- const original = await start(kind, a);
- const b = taskObserver("task-b");
- const address: AgentAddress =
- kind === "local"
- ? { kind: "agent/local", sessionId: "child-session", continuationToken: "child-token" }
- : {
- kind: "agent/remote",
- sessionId: "remote-session",
- callbackBaseUrl: "https://parent.example",
- url: "https://remote.example/eve/v1",
- credentialResolver: { resolverId: "subagents/research" },
- };
- const result = await dispatchToClaimedAgentAddress({
- activityObserver: b,
- action: target(kind, "task-b").action,
- auth: null,
- bundle,
- currentSession: session,
- handle: {
- address,
- identity: { id: "agent-1", name: "research", nodeId: "subagents/research" },
- callId: "task-b",
- operationId: "operation-b",
- ownerId: "task-b",
- phase: "claimed",
- },
- reply: { kind: "reply", parentToken: "task-b-reply", taskId: "task-b" },
- });
- expect(result.kind).toBe("called");
- let caller: TurnCaller | undefined;
- if (kind === "local") caller = dispatchSession.mock.calls[0]![0].command.caller;
- else {
- const request = continueRemote.mock.calls[0]![0];
- const parsed = parseActivityObserverField(request.activityObserver);
- if (parsed === undefined || parsed instanceof Response) throw new Error("Invalid observer");
- const callback = request.callback;
- if (callback === undefined) throw new Error("Expected callback");
- expect(validateActivityObserverBinding(parsed, callback)).toBeUndefined();
- caller = {
- callId: callback.callId,
- activityObserver: parsed,
- subagentName: callback.subagentName,
- taskId: callback.taskId,
- replyTo: { kind: "callback", token: callback.token, url: callback.url },
- };
- }
- const context = await bindTurnCallerContextStep({
- caller,
- serializedContext: {
- [ActivityObserverKey.name]: original,
- [ChannelKey.name]: {
- kind: SUBAGENT_ADAPTER_KIND,
- state: {
- callId: "task-a",
- parentContinuationToken: "parent-token",
- parentSessionId: "parent",
- subagentName: "research",
- },
- },
- },
- });
- const rebound = context[ActivityObserverKey.name] as ActivityObserverConfig;
- expect(rebound).toEqual(b);
- let snapshot = apply(initialSnapshot(), taskEvents(a, "working"));
- snapshot = apply(snapshot, project(tool("actions.requested", "first-turn"), a));
- snapshot = apply(snapshot, project(tool("action.result", "first-turn"), a));
- snapshot = apply(snapshot, taskEvents(a, status));
- snapshot = apply(snapshot, taskEvents(b, "working"));
- snapshot = apply(snapshot, project(turn("turn.started", "second-turn"), rebound));
- snapshot = apply(snapshot, project(tool("actions.requested", "second-turn"), rebound));
- expect(snapshot.work[a.workIdentity.id]?.phase).toBe(status);
- expect(snapshot.work[b.workIdentity.id]?.phase).toBe("running");
- expect(Object.values(snapshot.actions)).toEqual([
- expect.objectContaining({ parentWorkId: a.workIdentity.id, phase: "completed" }),
- expect.objectContaining({ parentWorkId: b.workIdentity.id, phase: "running" }),
- ]);
- });
-});
diff --git a/packages/eve/src/execution/tools/subagent/task-agent-requests.ts b/packages/eve/src/execution/tools/subagent/task-agent-requests.ts
index 2494662ef..81481d84e 100644
--- a/packages/eve/src/execution/tools/subagent/task-agent-requests.ts
+++ b/packages/eve/src/execution/tools/subagent/task-agent-requests.ts
@@ -5,13 +5,13 @@ import {
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";
+import type { WorkflowToolAgentRequest } from "#execution/tools/workflow/messages.js";
interface AgentRequestDelivery {
readonly ownerId: string;
- readonly replyTo: TaskAgentRequestDelivery["replyTo"];
- readonly request: TaskAgentRequestDelivery["request"];
- readonly taskId?: string;
+ /** The requesting run's reply hook. */
+ readonly replyTo: string;
+ readonly request: WorkflowToolAgentRequest;
}
interface TaskAgentRequestContext {
@@ -28,7 +28,7 @@ interface AppliedTaskAgentRequest {
/**
* 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.
+ * handle.
*/
export async function applyTaskAgentRequest(
delivery: AgentRequestDelivery,
@@ -42,7 +42,6 @@ export async function applyTaskAgentRequest(
result: request.result,
serializedContext: ctx.serializedContext,
sessionState: ctx.sessionState,
- taskId: delivery.taskId,
});
let serializedContext = settled.serializedContext;
let sessionState = settled.sessionState;
@@ -73,7 +72,6 @@ export async function applyTaskAgentRequest(
request,
serializedContext: ctx.serializedContext,
sessionState: ctx.sessionState,
- taskId: delivery.taskId,
});
switch (dispatched.kind) {
case "dispatched": {
@@ -93,11 +91,6 @@ export async function applyTaskAgentRequest(
serializedContext: dispatched.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.test.ts b/packages/eve/src/execution/tools/subagent/task-cancel.test.ts
deleted file mode 100644
index 4acad47d9..000000000
--- a/packages/eve/src/execution/tools/subagent/task-cancel.test.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { ContextContainer } from "#context/container.js";
-import { beforeEach, expect, it, vi } from "vitest";
-import { cancelBackgroundAgentTask, cancelAgentInvocationOwnerStep } from "./task-cancel.js";
-import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
-import { createTestSessionState } from "#internal/testing/session-state.js";
-import { deserializeContext } from "#context/serialize.js";
-import { cancelRemoteAgentTurn, resolveRemoteAgentForAction } from "#subagents/remote-dispatch.js";
-import { setAgentHandleStore, type AgentHandle } from "#subagents/handles/store.js";
-import type { BackgroundWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-
-vi.mock("#execution/workflow-runtime.js", () => ({ requestWorkflowTurnCancellation: vi.fn() }));
-vi.mock("#context/serialize.js", () => ({ deserializeContext: vi.fn() }));
-vi.mock("#context/dynamic-subagent-lifecycle.js", () => ({ getDynamicSubagentSelection: vi.fn() }));
-vi.mock("#subagents/remote-dispatch.js", () => ({
- cancelRemoteAgentTurn: vi.fn(),
- resolveRemoteAgentForAction: vi.fn(),
-}));
-vi.mock("#internal/logging.js", () => ({ createLogger: vi.fn(() => ({})), logError: vi.fn() }));
-
-const entry: BackgroundWorkflowToolRun = {
- callId: "call",
- toolName: "research",
- lifetime: "session",
- origin: { turnId: "turn", stepIndex: 0 },
- address: { runId: "run", hookToken: "hook" },
- task: {
- taskId: "owner",
- metadata: { kind: "tool", name: "research" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
-};
-const claimed = (id: string, ownerId = "owner"): AgentHandle => ({
- phase: "claimed",
- ownerId,
- operationId: `op-${id}`,
- identity: { id, name: "research", nodeId: "subagents/research" },
- address: { kind: "agent/local", sessionId: id, continuationToken: `token-${id}` },
-});
-const session = {
- state: setAgentHandleStore(undefined, {
- handles: [
- claimed("child-a"),
- claimed("child-b"),
- claimed("other-child", "other-owner"),
- {
- phase: "available",
- identity: { id: "idle", name: "research", nodeId: "subagents/research" },
- address: { kind: "agent/local", sessionId: "idle", continuationToken: "idle" },
- },
- ],
- }),
-};
-
-beforeEach(() => vi.resetAllMocks());
-
-it.each(["background", "waiting"])(
- "cancels every claimed child of a %s owner, leaving unrelated children alone",
- async (mode) => {
- if (mode === "background") {
- await cancelBackgroundAgentTask({ entry, session, serializedContext: {} });
- } else {
- const sessionState = createTestSessionState();
- await cancelAgentInvocationOwnerStep({
- ownerId: "owner",
- serializedContext: {},
- sessionState: {
- ...sessionState,
- snapshot: { session: { ...sessionState.snapshot.session, ...session } },
- },
- });
- }
- expect(requestWorkflowTurnCancellation).toHaveBeenCalledTimes(2);
- expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
- sessionId: "child-a",
- tasks: true,
- });
- expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
- sessionId: "child-b",
- tasks: true,
- });
- expect(deserializeContext).not.toHaveBeenCalled();
- },
-);
-
-it("propagates child cancellation failure so background cancellation can retry", async () => {
- vi.mocked(requestWorkflowTurnCancellation).mockRejectedValueOnce(new Error("unavailable"));
- await expect(
- cancelBackgroundAgentTask({ entry, session, serializedContext: {} }),
- ).rejects.toThrow("Failed to cancel owned agent turns");
- expect(requestWorkflowTurnCancellation).toHaveBeenCalledTimes(2);
-});
-
-it("waits for sibling cancellation requests before returning a failure", async () => {
- const release = Promise.withResolvers<void>();
- vi.mocked(requestWorkflowTurnCancellation)
- .mockRejectedValueOnce(new Error("first child failed"))
- .mockImplementationOnce(async () => {
- await release.promise;
- return { status: "accepted", sessionId: "child-b" };
- });
- const cancellation = cancelBackgroundAgentTask({ entry, session, serializedContext: {} });
- const rejected = vi.fn();
- cancellation.catch(rejected);
- await Promise.resolve();
- await Promise.resolve();
- expect(rejected).not.toHaveBeenCalled();
- release.resolve();
- await expect(cancellation).rejects.toThrow("Failed to cancel owned agent turns");
-});
-
-it("cancels remote children at their recorded address", async () => {
- const remoteSession = {
- state: setAgentHandleStore(undefined, {
- handles: [
- {
- ...claimed("remote"),
- phase: "claimed",
- ownerId: "owner",
- operationId: "op-remote",
- address: {
- kind: "agent/remote",
- sessionId: "remote",
- url: "https://original.example",
- callbackBaseUrl: "https://parent.example",
- },
- },
- ],
- }),
- };
- const ctx = new ContextContainer();
- vi.spyOn(ctx, "require").mockReturnValue({ subagentRegistry: { subagentsByNodeId: new Map() } });
- vi.mocked(deserializeContext).mockResolvedValue(ctx);
- vi.mocked(resolveRemoteAgentForAction).mockReturnValue({
- kind: "remote",
- name: "research",
- description: "Research",
- nodeId: "subagents/research",
- path: "/research",
- logicalPath: "subagents/research",
- sourceId: "research",
- sourceKind: "module",
- url: "https://new.example",
- });
- await cancelBackgroundAgentTask({ entry, session: remoteSession, serializedContext: {} });
- expect(cancelRemoteAgentTurn).toHaveBeenCalledWith({
- remote: expect.objectContaining({ url: "https://original.example" }),
- sessionId: "remote",
- tasks: true,
- });
-});
diff --git a/packages/eve/src/execution/tools/subagent/task-cancel.ts b/packages/eve/src/execution/tools/subagent/task-cancel.ts
index 497778edd..a4772d823 100644
--- a/packages/eve/src/execution/tools/subagent/task-cancel.ts
+++ b/packages/eve/src/execution/tools/subagent/task-cancel.ts
@@ -1,5 +1,4 @@
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";
@@ -11,16 +10,6 @@ import { createLogger, logError } from "#internal/logging.js";
const log = createLogger("execution.agent-invocation-cancel");
-/** Cancels child turns and their nested tasks still owned by a background task. */
-export const cancelBackgroundAgentTask: TaskExecutorCancel = async (input) => {
- if (input.session === undefined || input.serializedContext === undefined) return;
- await cancelAgentInvocationOwner({
- ownerId: input.entry.task.taskId,
- serializedContext: input.serializedContext,
- session: input.session,
- });
-};
-
/** Cancels a child turn still claimed by a completed workflow-tool run. */
export async function cancelAgentInvocationOwnerStep(input: {
readonly ownerId: string;
@@ -54,7 +43,7 @@ async function cancelAgentInvocationOwner(input: {
const results = await Promise.allSettled(
handles.map(async (handle) => {
if (handle.address.kind !== "agent/remote") {
- await requestWorkflowTurnCancellation({ sessionId: handle.address.sessionId, tasks: true });
+ await requestWorkflowTurnCancellation({ sessionId: handle.address.sessionId });
return;
}
remoteContext ??= deserializeContext(input.serializedContext);
@@ -70,7 +59,6 @@ async function cancelAgentInvocationOwner(input: {
await cancelRemoteAgentTurn({
remote: { ...remote, url: handle.address.url },
sessionId: handle.address.sessionId,
- tasks: true,
});
}),
);
diff --git a/packages/eve/src/execution/tools/tasks.ts b/packages/eve/src/execution/tools/tasks.ts
deleted file mode 100644
index 40f4e6b0d..000000000
--- a/packages/eve/src/execution/tools/tasks.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import {
- TASK_CANCEL_INPUT_SCHEMA,
- TASK_CANCEL_TOOL_NAME,
- TASK_VIEWS_OUTPUT_SCHEMA,
-} from "#tools/framework/task-contract.js";
-
-/** Builds the harness definition for the compiled framework task control. */
-export function createTaskToolHarnessDefinitions(): readonly HarnessToolDefinition[] {
- return [
- {
- 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.",
- inputSchema: TASK_CANCEL_INPUT_SCHEMA,
- name: TASK_CANCEL_TOOL_NAME,
- outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,
- runtimeAction: { kind: "task-control" },
- },
- ];
-}
diff --git a/packages/eve/src/execution/tools/workflow/answer.ts b/packages/eve/src/execution/tools/workflow/answer.ts
index 2c38a20d1..90a0e251b 100644
--- a/packages/eve/src/execution/tools/workflow/answer.ts
+++ b/packages/eve/src/execution/tools/workflow/answer.ts
@@ -1,7 +1,11 @@
import type { SessionAuthContext } from "#channel/types.js";
+import type {
+ WorkflowToolRunAnswer,
+ WorkflowToolRunControlMessage,
+} from "#execution/tools/workflow/messages.js";
+import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";
import { resumeHook } from "#internal/workflow/runtime.js";
import type { InputResponse } from "#shared/input.js";
-import type { ToolInputResponse } from "#tools/definition.js";
import type { ToolInputResponseResponder } from "#tools/definition.js";
export function toToolInputResponseResponder(
@@ -16,29 +20,27 @@ export function toToolInputResponseResponder(
};
}
-/** Resumed with the bare response, not a session-inbox delivery, so the body can race the hook. */
-export async function resumeWorkflowToolRunAnswers(
- answerToken: string,
+/**
+ * Sends the answers the session accepted to the asking run's control hook,
+ * the same ordered inbox its commands use, so an answer the session accepted
+ * before an interrupt or cancel reaches the body before them.
+ */
+export async function sendWorkflowAskAnswers(
+ route: WorkflowAskRoute,
responses: readonly InputResponse[] | undefined,
responder?: ToolInputResponseResponder,
): Promise<void> {
for (const response of responses ?? []) {
- const answer: ToolInputResponse = {
- optionId: response.optionId,
- status: "answered",
- text: response.text,
- ...(responder === undefined
- ? {}
- : {
- responder,
- }),
+ const { optionId, text } = response;
+ const answered: WorkflowToolRunAnswer =
+ responder === undefined
+ ? { optionId, status: "answered", text }
+ : { optionId, responder, status: "answered", text };
+ const answer: WorkflowToolRunControlMessage = {
+ kind: "answer",
+ requestId: response.requestId,
+ response: answered,
};
- await resumeHook(answerToken, answer);
+ await resumeHook(route.control, answer);
}
}
-
-/** Resolves a dismissible `ctx.ask()` request the user moved past without answering. */
-export async function resumeWorkflowToolRunDismissal(answerToken: string): Promise<void> {
- const answer: ToolInputResponse = { status: "dismissed" };
- await resumeHook(answerToken, answer);
-}
diff --git a/packages/eve/src/execution/tools/workflow/ask.test.ts b/packages/eve/src/execution/tools/workflow/ask.test.ts
index 795f0dc47..570a8f609 100644
--- a/packages/eve/src/execution/tools/workflow/ask.test.ts
+++ b/packages/eve/src/execution/tools/workflow/ask.test.ts
@@ -1,20 +1,23 @@
import { describe, expect, it, vi } from "vitest";
-import { createHook } from "#compiled/@workflow/core/index.js";
-import { ask, attachWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
+import {
+ ask,
+ attachWorkflowToolRunContext,
+ WorkflowToolRunAsks,
+} from "#execution/tools/workflow/ask.js";
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
import type { ToolContext } from "#tools/definition.js";
-vi.mock("#compiled/@workflow/core/index.js", () => ({ createHook: vi.fn() }));
-vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({ resumeHookStep: vi.fn() }));
-
describe("ask", () => {
it("resolves as unavailable without waiting when the session cannot request input", async () => {
const ctx = {} as ToolContext;
+ const send = vi.fn();
attachWorkflowToolRunContext(ctx, {
- canRequestInput: false,
+ agentContext: { capabilities: { requestInput: false } } as AgentSessionContext,
+ asks: new WorkflowToolRunAsks("run"),
+ control: "control",
from: {
callId: "call",
- execution: "blocking",
input: {},
runId: "run",
sequence: 1,
@@ -22,12 +25,12 @@ describe("ask", () => {
toolName: "ask_question",
turnId: "turn",
},
- owner: { inbox: "inbox" },
+ owner: { send, sent: 0 },
});
await expect(ask(ctx, { prompt: "Which region?" })).resolves.toEqual({
status: "unavailable",
});
- expect(createHook).not.toHaveBeenCalled();
+ expect(send).not.toHaveBeenCalled();
});
});
diff --git a/packages/eve/src/execution/tools/workflow/ask.ts b/packages/eve/src/execution/tools/workflow/ask.ts
index c210cf6fe..521480196 100644
--- a/packages/eve/src/execution/tools/workflow/ask.ts
+++ b/packages/eve/src/execution/tools/workflow/ask.ts
@@ -1,11 +1,15 @@
-import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
-
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
import type {
- WorkflowToolRunOwner,
+ WorkflowToolRunAskDecision,
WorkflowToolRunRef,
} from "#execution/tools/workflow/messages.js";
-import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
-import type { ToolContext, ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
+import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.js";
+import type {
+ ToolContext,
+ ToolInputRequest,
+ ToolInputRequestOptions,
+ ToolInputResponse,
+} from "#tools/definition.js";
import { workflowToolContextErrorMessage } from "#shared/workflow-tool-context.js";
// `Symbol.for`, not a module-local WeakMap: workflow helpers and body setup may
@@ -13,9 +17,16 @@ import { workflowToolContextErrorMessage } from "#shared/workflow-tool-context.j
const WORKFLOW_TOOL_RUN_CONTEXT = Symbol.for("eve.workflow-tool-run.context");
export interface WorkflowToolRunContext {
- readonly canRequestInput?: boolean;
+ /**
+ * What the run's caller lends it: the lineage and principal `ctx.agent`
+ * sessions run with, and whether `ctx.ask()` can reach a person.
+ */
+ readonly agentContext: AgentSessionContext;
+ readonly asks: WorkflowToolRunAsks;
+ /** The run's control hook, where the session sends its decisions on the run's questions. */
+ readonly control: string;
readonly from: WorkflowToolRunRef;
- readonly owner: WorkflowToolRunOwner;
+ readonly owner: WorkflowToolRunInbox;
}
type WorkflowToolRunContextCarrier = {
@@ -53,23 +64,113 @@ export function readWorkflowToolRunRef(ctx: ToolContext): WorkflowToolRunRef {
return readWorkflowToolRunContext(ctx, "agent").from;
}
-export function readWorkflowToolRunOwner(ctx: ToolContext): WorkflowToolRunOwner {
+export function readWorkflowToolRunOwner(ctx: ToolContext): WorkflowToolRunInbox {
return readWorkflowToolRunContext(ctx, "agent").owner;
}
-/** Returns an answer which may be awaited or raced with another workflow operation. */
+const CANCELLED: ToolInputResponse = { status: "cancelled" };
+const UNAVAILABLE: ToolInputResponse = { status: "unavailable" };
+
+interface PendingAsk {
+ readonly resolve: (response: ToolInputResponse) => void;
+ readonly reject: (error: unknown) => void;
+}
+
+/**
+ * The run's pending `ctx.ask()` questions. The run names each one, and each
+ * resolves only from what the session decided about it, delivered in order on
+ * the run's control hook, or as `cancelled` once the session stops the work.
+ */
+export class WorkflowToolRunAsks {
+ private opened = 0;
+ private readonly pending = new Map<string, PendingAsk>();
+ private readonly runId: string;
+
+ constructor(runId: string) {
+ this.runId = runId;
+ }
+
+ /** Opens a question under a request ID that replays deterministically with the run. */
+ open(): { readonly answer: Promise<ToolInputResponse>; readonly requestId: string } {
+ this.opened += 1;
+ const requestId = `${this.runId}-ask-${String(this.opened)}`;
+ const answer = new Promise<ToolInputResponse>((resolve, reject) => {
+ this.pending.set(requestId, { reject, resolve });
+ });
+ return { answer, requestId };
+ }
+
+ isPending(requestId: string): boolean {
+ return this.pending.has(requestId);
+ }
+
+ /** Applies the session's decision. The first one wins; a repeated one is dropped. */
+ settle(decision: WorkflowToolRunAskDecision): void {
+ const response = decision.kind === "answer" ? decision.response : CANCELLED;
+ this.take(decision.requestId)?.resolve(response);
+ }
+
+ fail(requestId: string, error: unknown): void {
+ this.take(requestId)?.reject(error);
+ }
+
+ /** The session stopped the work, so it answers none of its questions anymore. */
+ cancelAll(): void {
+ for (const requestId of this.pending.keys()) {
+ this.take(requestId)?.resolve(CANCELLED);
+ }
+ }
+
+ private take(requestId: string): PendingAsk | undefined {
+ const pending = this.pending.get(requestId);
+ this.pending.delete(requestId);
+ return pending;
+ }
+}
+
+/**
+ * Returns an answer which may be awaited or raced with another workflow
+ * operation. When the call's `abortSignal` or `options.signal` aborts, the run
+ * asks the session to withdraw the question. The answer is `cancelled` only if
+ * the session withdrew it before it accepted a person's answer.
+ */
export function ask(
ctx: ToolContext,
request: ToolInputRequest,
-): Hook<ToolInputResponse> | Promise<ToolInputResponse> {
+ options: ToolInputRequestOptions = {},
+): Promise<ToolInputResponse> {
const context = readWorkflowToolRunContext(ctx, "ask");
- if (context.canRequestInput === false) return Promise.resolve({ status: "unavailable" });
- const answer = createHook<ToolInputResponse>();
- void resumeHookStep(context.owner.inbox, {
+ // A caller that can't reach a person resolves `ctx.ask()` as `unavailable`.
+ if (context.agentContext.capabilities?.requestInput !== true) {
+ return Promise.resolve(UNAVAILABLE);
+ }
+ const signals = [ctx.abortSignal];
+ if (options.signal !== undefined) signals.push(options.signal);
+ if (signals.some((signal) => signal.aborted)) return Promise.resolve(CANCELLED);
+
+ const { asks, control, owner } = context;
+ const { answer, requestId } = asks.open();
+ const from = context.from;
+ const sent = owner.send({
kind: "request",
- from: context.from,
- replyTo: answer.token,
- request: { kind: "ask", request },
+ from,
+ replyTo: requestId,
+ request: { control, kind: "ask", request },
+ });
+ sent.catch((error: unknown) => asks.fail(requestId, error));
+
+ const requestWithdrawal = (): void => {
+ if (!asks.isPending(requestId)) return;
+ // The withdrawal must not overtake the request it withdraws.
+ const withdrawal = sent.then(() =>
+ owner.send({ control, from, kind: "withdraw", replyTo: requestId }),
+ );
+ withdrawal.catch((error: unknown) => asks.fail(requestId, error));
+ };
+ for (const signal of signals) {
+ signal.addEventListener("abort", requestWithdrawal, { once: true });
+ }
+ return answer.finally(() => {
+ for (const signal of signals) signal.removeEventListener("abort", requestWithdrawal);
});
- return answer;
}
diff --git a/packages/eve/src/execution/tools/workflow/background.test.ts b/packages/eve/src/execution/tools/workflow/background.test.ts
deleted file mode 100644
index 4a1533ee8..000000000
--- a/packages/eve/src/execution/tools/workflow/background.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { jsonSchema } from "ai";
-import { createWorkflowToolHarnessDefinition, parseWorkflowToolInput } from "./background.js";
-
-describe("createWorkflowToolHarnessDefinition", () => {
- it("preserves agent identity on workflow-backed tools", () => {
- expect(
- createWorkflowToolHarnessDefinition({
- definition: {
- description: "Delegate research.",
- execution: "background",
- execute: () => undefined,
- inputSchema: jsonSchema({ type: "object" }),
- name: "research",
- },
- nodeId: "subagents/research",
- workflowId: "workflow//eve//subagentToolExecuteWorkflow",
- }),
- ).toMatchObject({ nodeId: "subagents/research" });
- });
-});
-
-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
deleted file mode 100644
index 534f195e6..000000000
--- a/packages/eve/src/execution/tools/workflow/background.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-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 { UNSPECIFIED_INPUT_SCHEMA, toInputSchema, toOutputSchema } from "#tools/schema.js";
-
-interface WorkflowToolHarnessDefinitionInput {
- readonly definition: HarnessToolDefinition;
- readonly executeInput?: (input: unknown) => JsonValue;
- /** Selected agent definition's runtime graph ID; absent for authored workflow tools. */
- readonly nodeId?: string;
-
- readonly workflowId: string;
-}
-
-export function createWorkflowToolHarnessDefinition(
- input: WorkflowToolHarnessDefinitionInput,
-): HarnessToolDefinition {
- const definition = input.definition;
- const workflow = {
- executeInput: input.executeInput,
- nodeId: input.nodeId,
- 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,
- workflowId: tool.task.workflowId,
- };
- return createWorkflowToolHarnessDefinition(input);
-}
-
-/** Returns a task receipt after the background scope starts the owning run. */
-function createWorkflowToolBackgroundExecute(input: {
- readonly toolName: string;
- readonly workflowId: string;
-}): NonNullable<HarnessToolDefinition["execute"]> {
- return (_toolInput: unknown, _options: ToolExecuteOptions): 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.test.ts b/packages/eve/src/execution/tools/workflow/body.test.ts
index 6024881ff..8ff141781 100644
--- a/packages/eve/src/execution/tools/workflow/body.test.ts
+++ b/packages/eve/src/execution/tools/workflow/body.test.ts
@@ -1,25 +1,33 @@
import { expect, it, vi } from "vitest";
import type { ToolContext } from "#tools/definition.js";
import type { WorkflowToolContext } from "#tools/workflow-definition.js";
-import { executeWorkflowBody, type WorkflowBodyInput } from "#execution/tools/workflow/body.js";
-import { readWorkflowToolRunRef } from "#execution/tools/workflow/ask.js";
+import { startWorkflowBody, type WorkflowBodyInput } from "#execution/tools/workflow/body.js";
+import { readWorkflowToolRunRef, WorkflowToolRunAsks } from "#execution/tools/workflow/ask.js";
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
-const mocks = vi.hoisted(() => ({ execute: vi.fn(), agent: vi.fn(), ask: vi.fn() }));
+const mocks = vi.hoisted(() => ({ execute: vi.fn(), openAgent: vi.fn(), ask: vi.fn() }));
vi.mock("#execution/workflow-registry.js", () => ({ readRegisteredWorkflow: () => mocks.execute }));
-vi.mock("#execution/tools/subagent/invoke-agent.js", () => ({ agent: mocks.agent }));
vi.mock("#execution/tools/workflow/ask.js", async (importOriginal) => ({
...(await importOriginal()),
ask: mocks.ask,
}));
+vi.mock("#execution/agent-sessions/session.js", () => ({
+ createAgentSessions: () => ({ close: async () => {}, open: mocks.openAgent }),
+}));
+
+const agentContext = { capabilities: { requestInput: true } } as AgentSessionContext;
+const owner = { send: vi.fn(), sent: 0 };
it("defaults agent metadata to an empty registry for older workflow payloads", async () => {
mocks.execute.mockImplementation(async (_input, ctx: WorkflowToolContext) => {
expect(ctx.agents).toEqual({});
return null;
});
- await executeWorkflowBody(
+ await startWorkflowBody(
{
+ agentContext,
callId: "legacy-call",
+ hookToken: "control",
input: {},
session: {
auth: { current: null, initiator: null },
@@ -29,19 +37,24 @@ it("defaults agent metadata to an empty registry for older workflow payloads", a
stepIndex: 0,
toolName: "legacy",
workflowId: "workflow//test//legacy",
- owner: { inbox: "inbox" },
- execution: "blocking",
+ owner,
runId: "run",
},
- new AbortController().signal,
- );
+ {
+ abortSignal: new AbortController().signal,
+ interruptSignal: new AbortController().signal,
+ },
+ new WorkflowToolRunAsks("run"),
+ ).outcome;
});
it("binds workflow-only methods to the run context", async () => {
const signal = new AbortController().signal;
const input = {
+ agentContext,
agents: { reviewer: { description: "Review deployments." } },
callId: "call",
+ hookToken: "control",
input: {},
session: {
auth: { current: null, initiator: null },
@@ -51,15 +64,14 @@ it("binds workflow-only methods to the run context", async () => {
stepIndex: 0,
toolName: "deploy",
workflowId: "workflow//test//execute",
- owner: { inbox: "inbox" },
- execution: "blocking",
+ owner,
runId: "run",
- } as WorkflowBodyInput & { execution: "blocking"; runId: string };
+ } as WorkflowBodyInput & { runId: string };
const question = { prompt: "Continue?" };
const target = "reviewer";
- const invocation = { message: "Review" };
+ const session = { send: vi.fn() };
mocks.ask.mockResolvedValue({ optionId: "yes" });
- mocks.agent.mockResolvedValue("reviewed");
+ mocks.openAgent.mockReturnValue(session);
mocks.execute.mockImplementation(async (_input, ctx: WorkflowToolContext & ToolContext) => {
expect(readWorkflowToolRunRef(ctx).runId).toBe("run");
expect(ctx.abortSignal).toBe(signal);
@@ -67,13 +79,17 @@ it("binds workflow-only methods to the run context", async () => {
expect(Object.isFrozen(ctx.agents)).toBe(true);
expect(Object.isFrozen(ctx.agents.reviewer)).toBe(true);
const answer = await ctx.ask(question);
- const result = await ctx.agent(target, invocation);
- expect(mocks.ask).toHaveBeenCalledWith(ctx, question);
- expect(mocks.agent).toHaveBeenCalledWith(ctx, target, invocation);
- return { answer, result };
- });
- await expect(executeWorkflowBody(input, signal)).resolves.toEqual({
- outcome: { status: "completed", output: { answer: { optionId: "yes" }, result: "reviewed" } },
- reportCount: 0,
+ expect(ctx.agent(target)).toBe(session);
+ expect(mocks.ask).toHaveBeenCalledWith(ctx, question, undefined);
+ expect(mocks.openAgent).toHaveBeenCalledWith(target);
+ return { answer };
});
+ const interruptSignal = new AbortController().signal;
+ await expect(
+ startWorkflowBody(
+ input,
+ { abortSignal: signal, interruptSignal },
+ new WorkflowToolRunAsks("run"),
+ ).outcome,
+ ).resolves.toEqual({ status: "completed", output: { answer: { optionId: "yes" } } });
});
diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.ts
index 02680b7f7..32a28861f 100644
--- a/packages/eve/src/execution/tools/workflow/body.ts
+++ b/packages/eve/src/execution/tools/workflow/body.ts
@@ -1,30 +1,30 @@
import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
import type { SessionContext } from "#context/session-context.js";
-import { agent } from "#execution/tools/subagent/invoke-agent.js";
-import type { AgentInput, WorkflowToolContext } from "#tools/workflow-definition.js";
-import { ask, attachWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
+import { createAgentSessions } from "#execution/agent-sessions/session.js";
+import type { AgentSession, WorkflowToolContext } from "#tools/workflow-definition.js";
import {
- type WorkflowToolRunOutcome,
- type WorkflowToolRunOwner,
- type WorkflowToolRunRef,
- type WorkflowToolRunReport,
+ ask,
+ attachWorkflowToolRunContext,
+ type WorkflowToolRunAsks,
+} from "#execution/tools/workflow/ask.js";
+import type {
+ WorkflowToolRunOutcome,
+ WorkflowToolRunRef,
} from "#execution/tools/workflow/messages.js";
-import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
+import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.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 {
+ /** Everything the run needs to open `ctx.agent` sessions for its caller. */
+ readonly agentContext: AgentSessionContext;
/** Snapshot added for new runs; absent only when resuming an older durable payload. */
readonly agents?: WorkflowToolContext["agents"];
readonly callId: string;
- /**
- * Whether the owning session can reach a human. `false` makes `ctx.ask()`
- * resolve as `unavailable` instead of waiting for an answer no one can give.
- */
- readonly canRequestInput?: boolean;
readonly executeInput?: JsonValue;
readonly input: JsonObject;
@@ -35,12 +35,22 @@ export interface WorkflowBodyDefinition {
}
export interface WorkflowBodyInput extends WorkflowBodyDefinition {
- readonly owner: WorkflowToolRunOwner;
+ /** The run's control hook, which the session answers the body's questions on. */
+ readonly hookToken: string;
+ readonly owner: WorkflowToolRunInbox;
}
-export interface WorkflowBodyResult {
- readonly outcome: WorkflowToolRunOutcome;
- readonly reportCount: number;
+/** The call's signals, which commands on the run's control hook abort. */
+export interface WorkflowBodyRun {
+ readonly abortSignal: AbortSignal;
+ readonly interruptSignal: AbortSignal;
+}
+
+/** A body the run started. */
+export interface StartedWorkflowBody {
+ /** Releases what the body opened, such as its `ctx.agent` sessions, once the run ends. */
+ close(): Promise<void>;
+ readonly outcome: Promise<WorkflowToolRunOutcome>;
}
type WorkflowToolExecute = (
@@ -48,23 +58,34 @@ type WorkflowToolExecute = (
ctx: WorkflowToolContext,
) => 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<WorkflowBodyResult> {
- const from = createWorkflowBodyRef(input);
- const ctx = createWorkflowBodyContext(input, signal);
- attachWorkflowToolRunContext(ctx, {
- canRequestInput: input.canRequestInput,
- from,
+/** Starts one registered workflow body, which reports progress to its owner. */
+export function startWorkflowBody(
+ input: WorkflowBodyInput & { readonly runId?: string },
+ run: WorkflowBodyRun,
+ asks: WorkflowToolRunAsks,
+): StartedWorkflowBody {
+ const runContext = {
+ agentContext: input.agentContext,
+ asks,
+ control: input.hookToken,
+ from: createWorkflowBodyRef(input),
owner: input.owner,
- });
- let reportCount = 0;
+ };
+ const agentSessions = createAgentSessions(runContext);
+ const ctx = createWorkflowBodyContext(input, run, agentSessions.open);
+ attachWorkflowToolRunContext(ctx, runContext);
+ return {
+ close: agentSessions.close,
+ outcome: executeWorkflowBody(input, ctx, runContext.from),
+ };
+}
+async function executeWorkflowBody(
+ input: WorkflowBodyInput,
+ ctx: ToolContext & WorkflowToolContext,
+ from: WorkflowToolRunRef,
+): Promise<WorkflowToolRunOutcome> {
+ const signal = ctx.abortSignal;
try {
const execute = resolveWorkflowToolExecute(input);
const result = execute(input.executeInput ?? input.input, ctx);
@@ -77,41 +98,29 @@ export async function executeWorkflowBody(
let next = await iterator.next();
while (next.done !== true) {
last = next.value;
- const report: WorkflowToolRunReport = { from, update: next.value };
- await resumeHookStep(input.owner.inbox, { kind: "report", ...report });
- reportCount += 1;
+ await input.owner.send({ from, kind: "report", update: next.value });
next = await iterator.next();
}
- output =
- (next.value as JsonValue | undefined) ??
- (input.execution === "blocking" ? last : undefined) ??
- null;
+ output = (next.value as JsonValue | undefined) ?? last ?? null;
}
- return { outcome: { output, status: "completed" }, reportCount };
+ return { output, status: "completed" };
} catch (error) {
if (signal.aborted) {
return {
- outcome: {
- reason:
- signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? ""),
- status: "cancelled",
- },
- reportCount,
+ reason:
+ signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? ""),
+ status: "cancelled",
};
}
- return { outcome: { error: normalizeSerializableError(error), status: "failed" }, reportCount };
+ return { error: normalizeSerializableError(error), status: "failed" };
}
}
export function createWorkflowBodyRef(
- input: WorkflowBodyDefinition & {
- readonly execution: "background" | "blocking";
- readonly runId?: string;
- },
+ input: WorkflowBodyDefinition & { readonly runId?: string },
): WorkflowToolRunRef {
return {
callId: input.callId,
- execution: input.execution,
input: input.input,
runId: input.runId ?? getWorkflowMetadata().workflowRunId,
sequence: input.session.turn.sequence,
@@ -133,7 +142,8 @@ function resolveWorkflowToolExecute(input: WorkflowBodyInput): WorkflowToolExecu
function createWorkflowBodyContext(
input: WorkflowBodyInput,
- signal: AbortSignal,
+ run: WorkflowBodyRun,
+ agent: (name: string) => AgentSession,
): ToolContext & WorkflowToolContext {
const unavailable = (member: string, hint: string): never => {
throw new Error(
@@ -141,8 +151,7 @@ function createWorkflowBodyContext(
);
};
const ctx: ToolContext & WorkflowToolContext = {
- agent: ((target: string, agentInput: AgentInput) =>
- agent(ctx, target, agentInput)) as WorkflowToolContext["agent"],
+ agent,
agents: Object.freeze(
Object.fromEntries(
Object.entries(input.agents ?? {}).map(([name, metadata]) => [
@@ -151,9 +160,10 @@ function createWorkflowBodyContext(
]),
),
),
- ask: (request) => ask(ctx, request),
- abortSignal: signal,
+ ask: (request, options) => ask(ctx, request, options),
+ abortSignal: run.abortSignal,
callId: input.callId,
+ interruptSignal: run.interruptSignal,
getSandbox: () => unavailable("getSandbox()", "the session sandbox belongs to the turn"),
getToken: () =>
unavailable("getToken()", 'pass ctx directly to a "use step" helper to resolve credentials'),
diff --git a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts
index b5d4775ee..f77fbdf09 100644
--- a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts
+++ b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts
@@ -1,17 +1,23 @@
-import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
-import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
import {
- createActionPartialEvent,
- encodeMessageStreamEvent,
- stampMessageStreamEvent,
-} from "#protocol/message.js";
+ publishSessionEvents,
+ type PublishedSessionEvents,
+ type SessionStepState,
+} from "#execution/publish-session-events.js";
+import type {
+ WorkflowToolRunAgentStartedMessage,
+ WorkflowToolRunRef,
+} from "#execution/tools/workflow/messages.js";
+import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
+import { createActionPartialEvent, createAgentStartedEvent } from "#protocol/message.js";
import type { JsonValue } from "#shared/json.js";
-export async function emitWorkflowToolRunReportStep(input: {
- readonly from: WorkflowToolRunRef;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly update: JsonValue;
-}): Promise<void> {
+/** Publishes a workflow tool run's `ctx.report()` update as `action.partial`. */
+export async function emitWorkflowToolRunReportStep(
+ input: SessionStepState & {
+ readonly from: WorkflowToolRunRef;
+ readonly update: JsonValue;
+ },
+): Promise<PublishedSessionEvents> {
"use step";
const event = createActionPartialEvent({
@@ -24,10 +30,31 @@ export async function emitWorkflowToolRunReportStep(input: {
stepIndex: input.from.stepIndex,
turnId: input.from.turnId,
});
- const writer = input.sessionWritable.getWriter();
- try {
- await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(event)));
- } finally {
- writer.releaseLock();
- }
+ return await publishSessionEvents(input, [event]);
+}
+
+/** Publishes `agent.started` for a session a workflow tool run opened. */
+export async function emitAgentStartedStep(
+ input: SessionStepState & {
+ readonly message: WorkflowToolRunAgentStartedMessage;
+ },
+): Promise<PublishedSessionEvents> {
+ "use step";
+
+ const { from, session } = input.message;
+ const event = createAgentStartedEvent({
+ callId: from.callId,
+ name: session.name,
+ parentSessionId: input.sessionState.sessionId,
+ remote:
+ session.kind === "remote"
+ ? {
+ url: session.url,
+ ...(session.resolverId !== undefined && { resolverId: session.resolverId }),
+ }
+ : undefined,
+ sessionId: session.sessionId,
+ turnId: from.turnId,
+ });
+ return await publishSessionEvents(input, [event]);
}
diff --git a/packages/eve/src/execution/tools/workflow/harness-definition.test.ts b/packages/eve/src/execution/tools/workflow/harness-definition.test.ts
new file mode 100644
index 000000000..43eb55714
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/harness-definition.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import { jsonSchema } from "ai";
+import { createWorkflowToolHarnessDefinition } from "./harness-definition.js";
+
+describe("createWorkflowToolHarnessDefinition", () => {
+ it("preserves agent identity on workflow-backed tools", () => {
+ expect(
+ createWorkflowToolHarnessDefinition({
+ definition: {
+ description: "Delegate research.",
+ execute: () => undefined,
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "research",
+ },
+ nodeId: "subagents/research",
+ workflowId: "workflow//eve//subagentToolExecuteWorkflow",
+ }),
+ ).toMatchObject({ execute: undefined, nodeId: "subagents/research" });
+ });
+});
diff --git a/packages/eve/src/execution/tools/workflow/harness-definition.ts b/packages/eve/src/execution/tools/workflow/harness-definition.ts
new file mode 100644
index 000000000..e33fe76d3
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/harness-definition.ts
@@ -0,0 +1,46 @@
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
+import type { JsonValue } from "#shared/json.js";
+import { UNSPECIFIED_INPUT_SCHEMA, toInputSchema, toOutputSchema } from "#tools/schema.js";
+
+export interface WorkflowToolHarnessDefinitionInput {
+ readonly definition: HarnessToolDefinition;
+ readonly executeInput?: (input: unknown) => JsonValue;
+ /** Selected agent definition's runtime graph ID; absent for authored workflow tools. */
+ readonly nodeId?: string;
+
+ readonly workflowId: string;
+}
+
+/** Workflow tools run outside the model step, so the harness definition carries no `execute`. */
+export function createWorkflowToolHarnessDefinition(
+ input: WorkflowToolHarnessDefinitionInput,
+): HarnessToolDefinition {
+ return {
+ ...input.definition,
+ execute: undefined,
+ executeInput: input.executeInput,
+ nodeId: input.nodeId,
+ 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.`);
+ }
+ return createWorkflowToolHarnessDefinition({
+ definition: {
+ behavior: tool.behavior,
+ description: tool.description,
+ inputSchema: toInputSchema(tool.inputSchema) ?? UNSPECIFIED_INPUT_SCHEMA,
+ name: tool.name,
+ outputSchema: toOutputSchema(tool.outputSchema),
+ rootOnly: tool.rootOnly,
+ },
+ nodeId: tool.task.nodeId,
+ workflowId: tool.task.workflowId,
+ });
+}
diff --git a/packages/eve/src/execution/tools/workflow/interrupt.ts b/packages/eve/src/execution/tools/workflow/interrupt.ts
new file mode 100644
index 000000000..d8fe5b910
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/interrupt.ts
@@ -0,0 +1,13 @@
+import type { WorkflowToolRunControlMessage } from "#execution/tools/workflow/messages.js";
+import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
+import type { WorkflowToolRunAddress } from "#execution/tools/workflow/types.js";
+
+const INTERRUPT: WorkflowToolRunControlMessage = { kind: "interrupt" };
+
+/**
+ * Fires the call's `interruptSignal`. A run that already finished has nothing
+ * left to interrupt, so a missing hook is not an error.
+ */
+export async function interruptWorkflowToolRun(run: WorkflowToolRunAddress): Promise<void> {
+ await resumeHookStep(run.hookToken, INTERRUPT, { ifPresent: true });
+}
diff --git a/packages/eve/src/execution/tools/workflow/messages.ts b/packages/eve/src/execution/tools/workflow/messages.ts
index 07c8e22d7..4827b6dd6 100644
--- a/packages/eve/src/execution/tools/workflow/messages.ts
+++ b/packages/eve/src/execution/tools/workflow/messages.ts
@@ -1,18 +1,23 @@
import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";
+import type { AgentSessionAddress } from "#execution/agent-sessions/steps.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";
+import type {
+ ToolInputRequest,
+ ToolInputResponse,
+ ToolInputResponseResponder,
+} from "#tools/definition.js";
export interface WorkflowToolRunOwner {
readonly inbox: string;
}
/**
- * Requests the owner must apply on the run's behalf because they touch
+ * Requests the owner applies for the model's agent tools because they touch
* owner-held state: spawning an agent and releasing its handle afterwards.
*/
export type WorkflowToolAgentRequest = AgentInvocationRequest | AgentSettlementRequest;
@@ -29,6 +34,8 @@ export interface WorkflowToolAuthorizationRequest {
/** A question authored with `ask()` from `eve/workflow`, before owner normalization. */
export interface WorkflowToolAskRequest {
+ /** The run's control hook, where the session sends its decision on the question. */
+ readonly control: string;
readonly kind: "ask";
readonly request: ToolInputRequest;
}
@@ -52,9 +59,7 @@ export type WorkflowToolRequest =
/** 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 runId: string;
readonly sequence: number;
readonly stepIndex: number;
@@ -88,17 +93,104 @@ export interface WorkflowToolRunOutcomeMessage {
readonly result: WorkflowToolRunOutcome;
}
+/**
+ * The run asks the session to withdraw the `ctx.ask()` question sent under
+ * `replyTo`. The session answers `withdrawn` on `control`, unless it accepted
+ * an answer first.
+ */
+export interface WorkflowToolRunWithdrawMessage {
+ readonly control: string;
+ readonly from: WorkflowToolRunRef;
+ readonly replyTo: string;
+}
+
+/** The run opened a session with `ctx.agent`, which its session announces as `agent.started`. */
+export interface WorkflowToolRunAgentStartedMessage {
+ readonly from: WorkflowToolRunRef;
+ readonly session: AgentSessionAddress;
+}
+
export type WorkflowToolRunMessage =
+ | ({ readonly kind: "agent-started" } & WorkflowToolRunAgentStartedMessage)
| ({ readonly kind: "report" } & WorkflowToolRunReport)
| ({ readonly kind: "request" } & WorkflowToolRunRequestMessage)
+ | ({ readonly kind: "withdraw" } & WorkflowToolRunWithdrawMessage)
| ({ readonly kind: "outcome" } & WorkflowToolRunOutcomeMessage);
-export type WorkflowToolRunControlMessage = { readonly kind: "cancel"; readonly reason: string };
+/** A person's answer to a `ctx.ask()` question, as the session accepted it. */
+export type WorkflowToolRunAnswer = Extract<ToolInputResponse, { readonly status: "answered" }>;
+
+/**
+ * The session's decision on one `ctx.ask()` question: it accepted an answer,
+ * or it withdrew the question first. It decides once, and the ask resolves
+ * from that decision alone.
+ */
+export type WorkflowToolRunAskDecision =
+ | {
+ readonly kind: "answer";
+ readonly requestId: string;
+ readonly response: WorkflowToolRunAnswer;
+ }
+ | { readonly kind: "withdrawn"; readonly requestId: string };
+
+/**
+ * Commands the body applies, in the order the session sent them. `cancel`
+ * aborts the call's `abortSignal`; `interrupt` aborts its `interruptSignal`,
+ * because steering arrived while the turn waits on the call.
+ */
+export type WorkflowBodyCommand =
+ | { readonly kind: "cancel"; readonly reason: string }
+ | { readonly kind: "interrupt" };
+
+/**
+ * Everything the session sends a run, on the run's control hook: its one
+ * inbox. Only the session writes to it, so the run receives commands and
+ * decisions in the order the session made them.
+ */
+export type WorkflowToolRunControlMessage = WorkflowBodyCommand | WorkflowToolRunAskDecision;
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";
+ const { kind, reason, requestId, response } = value as Record<string, unknown>;
+ switch (kind) {
+ case "interrupt":
+ return true;
+ case "cancel":
+ return typeof reason === "string";
+ case "answer":
+ return typeof requestId === "string" && isWorkflowToolRunAnswer(response);
+ case "withdrawn":
+ return typeof requestId === "string";
+ default:
+ return false;
+ }
+}
+
+export function isWorkflowToolRunAskDecision(
+ message: WorkflowToolRunControlMessage,
+): message is WorkflowToolRunAskDecision {
+ return message.kind === "answer" || message.kind === "withdrawn";
+}
+
+function isWorkflowToolRunAnswer(value: unknown): value is WorkflowToolRunAnswer {
+ if (typeof value !== "object" || value === null) return false;
+ const { optionId, responder, status, text } = value as Record<string, unknown>;
+ return (
+ status === "answered" &&
+ (optionId === undefined || typeof optionId === "string") &&
+ (responder === undefined || isToolInputResponseResponder(responder)) &&
+ (text === undefined || typeof text === "string")
+ );
+}
+
+function isToolInputResponseResponder(value: unknown): value is ToolInputResponseResponder {
+ if (typeof value !== "object" || value === null) return false;
+ const { authenticator, principalId, principalType } = value as Record<string, unknown>;
+ return (
+ typeof authenticator === "string" &&
+ typeof principalId === "string" &&
+ typeof principalType === "string"
+ );
}
diff --git a/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts b/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts
index f16baa431..bab83c36b 100644
--- a/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts
+++ b/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts
@@ -7,7 +7,6 @@ import {
const from = {
callId: "call-1",
- execution: "background" as const,
input: { message: "Find it" },
runId: "run-1",
sequence: 0,
diff --git a/packages/eve/src/execution/tools/workflow/owner.ts b/packages/eve/src/execution/tools/workflow/owner.ts
index 78fe000b2..a9fdf8cef 100644
--- a/packages/eve/src/execution/tools/workflow/owner.ts
+++ b/packages/eve/src/execution/tools/workflow/owner.ts
@@ -3,27 +3,43 @@ import type {
WorkflowToolRunMessage,
WorkflowToolRunRequestMessage,
WorkflowToolAuthorizationRequest,
- WorkflowToolRunOwner,
} from "#execution/tools/workflow/messages.js";
import {
createChannelReader,
type ChannelReader,
} from "#execution/tools/workflow/owner-channels.js";
import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
-import { disposeHook } from "#execution/hook-ownership.js";
+
+/**
+ * The run's inbox as its body sees it. Everything the body sends its session,
+ * except the outcome, goes through the run, which relays each message before
+ * the outcome.
+ */
+export interface WorkflowToolRunInbox {
+ /** Messages that reached the run's inbox so far. */
+ readonly sent: number;
+ send(message: Exclude<WorkflowToolRunMessage, { readonly kind: "outcome" }>): Promise<void>;
+}
export interface WorkflowToolRunOwnerInbox {
- dispose(): Promise<void>;
- readonly owner: WorkflowToolRunOwner;
+ readonly owner: WorkflowToolRunInbox;
readonly reader: ChannelReader<"workflow", WorkflowToolRunMessage>;
}
-/** Receives body messages before routing them to the turn or session owner. */
+/** Receives body messages before routing them to the waiting turn. */
export function openWorkflowToolRunOwnerInbox(): WorkflowToolRunOwnerInbox {
const hook = createHook<WorkflowToolRunMessage>();
+ let sent = 0;
return {
- dispose: () => disposeHook(hook),
- owner: { inbox: hook.token },
+ owner: {
+ get sent() {
+ return sent;
+ },
+ async send(message) {
+ await resumeHookStep(hook.token, message);
+ sent += 1;
+ },
+ },
reader: createChannelReader("workflow", hook),
};
}
diff --git a/packages/eve/src/execution/tools/workflow/start.test.ts b/packages/eve/src/execution/tools/workflow/start.test.ts
index dbef0fde1..f01325d01 100644
--- a/packages/eve/src/execution/tools/workflow/start.test.ts
+++ b/packages/eve/src/execution/tools/workflow/start.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { startWorkflowToolRun } from "./start.js";
import type { WorkflowToolRunInput } from "./types.js";
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
import {
startWorkflowOnCurrentDeployment,
workflowToolRunWorkflowReference,
@@ -13,6 +14,7 @@ vi.mock("#execution/workflow-runtime.js", () => ({
}));
const input: Omit<WorkflowToolRunInput, "hookToken"> = {
+ agentContext: {} as AgentSessionContext,
agents: { reviewer: { description: "Review deployments." } },
callId: "call-1",
input: { service: "api" },
diff --git a/packages/eve/src/execution/tools/workflow/start.ts b/packages/eve/src/execution/tools/workflow/start.ts
index bc636dec9..26c22f76b 100644
--- a/packages/eve/src/execution/tools/workflow/start.ts
+++ b/packages/eve/src/execution/tools/workflow/start.ts
@@ -1,4 +1,5 @@
import type { SessionAuth, SessionParent } from "#context/session-context.js";
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
import { createLogger, logError } from "#internal/logging.js";
@@ -33,9 +34,9 @@ export async function startWorkflowToolRun(
/** Starts one durable workflow task and records it on the owning session. */
export async function startWorkflowTask(input: {
+ readonly agentContext: AgentSessionContext;
readonly agents: WorkflowToolRunInput["agents"];
readonly auth: SessionAuth["current"];
- readonly canRequestInput: boolean;
readonly batchEvent: {
readonly sequence: number;
readonly stepIndex: number;
@@ -50,9 +51,9 @@ export async function startWorkflowTask(input: {
const { task, batchEvent, session } = input;
try {
const started = await startWorkflowToolRun({
+ agentContext: input.agentContext,
agents: input.agents,
callId: task.callId,
- canRequestInput: input.canRequestInput,
executeInput: task.executeInput,
input: task.input,
owner: input.owner,
@@ -69,7 +70,6 @@ export async function startWorkflowTask(input: {
return {
session: registerWorkflowToolRun(session, {
callId: task.callId,
- lifetime: "turn",
origin: { turnId: batchEvent.turnId, stepIndex: batchEvent.stepIndex },
address: started,
toolName: task.toolName,
diff --git a/packages/eve/src/execution/tools/workflow/step-execution.test.ts b/packages/eve/src/execution/tools/workflow/step-execution.test.ts
index 474cfd145..17a8adef5 100644
--- a/packages/eve/src/execution/tools/workflow/step-execution.test.ts
+++ b/packages/eve/src/execution/tools/workflow/step-execution.test.ts
@@ -88,7 +88,7 @@ describe("workflow step authorization", () => {
"Read ctx.agents in the workflow body and pass the required serializable metadata into the step.",
},
{
- access: (ctx: WorkflowToolContext) => ctx.agent("researcher", { message: "Investigate" }),
+ access: (ctx: WorkflowToolContext) => ctx.agent("researcher"),
capability: "ctx.agent()",
guidance: "Call ctx.agent() in the workflow body.",
},
diff --git a/packages/eve/src/execution/tools/workflow/step.ts b/packages/eve/src/execution/tools/workflow/step.ts
index c58d183e7..0cf4335d8 100644
--- a/packages/eve/src/execution/tools/workflow/step.ts
+++ b/packages/eve/src/execution/tools/workflow/step.ts
@@ -7,7 +7,6 @@ import {
type WorkflowToolRunContext,
} from "#execution/tools/workflow/ask.js";
import { disposeHook } from "#execution/hook-ownership.js";
-import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
import {
createAuthorizationRequiredEvent,
createAuthorizationCompletedEvent,
@@ -240,7 +239,7 @@ async function reportAuthorization(
const acknowledged = createHook<void>();
try {
await withAbort(
- resumeHookStep(run.owner.inbox, {
+ run.owner.send({
kind: "request",
from: run.from,
replyTo: acknowledged.token,
diff --git a/packages/eve/src/execution/tools/workflow/types.ts b/packages/eve/src/execution/tools/workflow/types.ts
index ce99ffa12..94aed96fe 100644
--- a/packages/eve/src/execution/tools/workflow/types.ts
+++ b/packages/eve/src/execution/tools/workflow/types.ts
@@ -1,10 +1,7 @@
-import type { ActivityObserverConfig } from "#channel/types.js";
-import type { TaskView } from "#tasks/types.js";
import type { WorkflowBodyDefinition } from "#execution/tools/workflow/body.js";
import type { WorkflowToolRunOwner } from "#execution/tools/workflow/messages.js";
export interface WorkflowToolRunInput extends WorkflowBodyDefinition {
- readonly execution?: "background" | "blocking";
readonly hookToken: string;
readonly owner: WorkflowToolRunOwner;
}
@@ -13,11 +10,3 @@ export interface WorkflowToolRunAddress {
readonly hookToken: string;
readonly runId: string;
}
-
-export interface BackgroundWorkflowToolRunInput {
- readonly activityObserver?: ActivityObserverConfig;
- readonly initialView: TaskView;
- readonly parentContinuationToken: string;
- readonly taskInboxToken: string;
- readonly workflow: WorkflowBodyDefinition;
-}
diff --git a/packages/eve/src/execution/tools/workflow/withdraw-step.ts b/packages/eve/src/execution/tools/workflow/withdraw-step.ts
new file mode 100644
index 000000000..97a078148
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/withdraw-step.ts
@@ -0,0 +1,77 @@
+import {
+ readDurableSession,
+ replaceDurableSessionSnapshot,
+ type DurableSession,
+} from "#execution/durable-session-store.js";
+import {
+ relaySessionEvents,
+ type PublishedSessionEvents,
+ type SessionStepState,
+} from "#execution/publish-session-events.js";
+import type { WorkflowToolRunControlMessage } from "#execution/tools/workflow/messages.js";
+import { ignoreGoneTarget } from "#execution/tasks/workflow-target.js";
+import { resumeHook } from "#internal/workflow/runtime.js";
+import { getProxyInputRequests, retireProxyInputRequests } from "#harness/proxy-input-requests.js";
+import { createInputResolvedEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
+
+/**
+ * Decides a run's request to withdraw a question. A question the session
+ * still offers is retired and relayed `cancelled`, so channels stop offering
+ * it. One it no longer offers was already answered or dropped with its turn.
+ * Either way the run hears `withdrawn`, after any answer the session sent it
+ * first, so the question resolves from the session's first decision.
+ */
+export async function withdrawWorkflowToolRunQuestionStep(
+ input: SessionStepState & {
+ readonly control: string;
+ readonly requestId: string;
+ readonly runId: string;
+ },
+): Promise<PublishedSessionEvents> {
+ "use step";
+
+ const session = readDurableSession(input.sessionState);
+ const withdrawn = withdrawWorkflowAsks(
+ session,
+ (requestId, runId) => requestId === input.requestId && runId === input.runId,
+ );
+ const decision: WorkflowToolRunControlMessage = {
+ kind: "withdrawn",
+ requestId: input.requestId,
+ };
+ await ignoreGoneTarget(resumeHook(input.control, decision));
+ return await relaySessionEvents(
+ {
+ serializedContext: input.serializedContext,
+ sessionState: replaceDurableSessionSnapshot({
+ session: withdrawn.session,
+ state: input.sessionState,
+ }),
+ sessionWritable: input.sessionWritable,
+ },
+ withdrawn.events,
+ );
+}
+
+/**
+ * Retires the `ctx.ask()` questions `select` picks and returns the
+ * `input.resolved` events that report them `cancelled`.
+ */
+export function withdrawWorkflowAsks(
+ session: DurableSession,
+ select: (requestId: string, runId: string) => boolean,
+): { readonly events: readonly UnstampedMessageStreamEvent[]; readonly session: DurableSession } {
+ const requestIds: string[] = [];
+ const events: UnstampedMessageStreamEvent[] = [];
+ for (const [requestId, route] of getProxyInputRequests(session.state)) {
+ if (route.workflowAsk === undefined || !select(requestId, route.workflowAsk.runId)) continue;
+ requestIds.push(requestId);
+ events.push(
+ createInputResolvedEvent({
+ resolutions: [{ kind: "question", outcome: "cancelled", requestId }],
+ ...route.event,
+ }),
+ );
+ }
+ return { events, session: retireProxyInputRequests(session, requestIds) };
+}
diff --git a/packages/eve/src/execution/tools/workflow/workflow-owner-background.test.ts b/packages/eve/src/execution/tools/workflow/workflow-owner-background.test.ts
deleted file mode 100644
index 8fd3a02a0..000000000
--- a/packages/eve/src/execution/tools/workflow/workflow-owner-background.test.ts
+++ /dev/null
@@ -1,561 +0,0 @@
-import { assert, beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
-import { workflowToolRunWorkflow } from "#execution/tools/workflow/workflow.js";
-import type { TaskCommand, TaskView } from "#tasks/types.js";
-import {
- createAuthorizationRequiredEvent,
- createAuthorizationCompletedEvent,
-} from "#protocol/message.js";
-
-const mocks = vi.hoisted(() => ({
- emitTaskActivityStep: vi.fn(),
- claimHookOwnership: vi.fn(),
- createChannelReader: vi.fn((channel: string) => ({
- channel,
- landed: [],
- iterator: [][Symbol.iterator](),
- })),
- createHook: vi.fn(() => ({ token: "task-token" })),
- deliverTaskInputResponsesStep: vi.fn(),
- raceChannelReads: vi.fn(),
- resumeHookStep: vi.fn(),
- notifyTaskParent: vi.fn(),
- executeWorkflowBody: vi.fn(),
- sleep: vi.fn(),
-}));
-
-vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#compiled/@workflow/core/index.js")>()),
- createHook: mocks.createHook,
- sleep: mocks.sleep,
-}));
-vi.mock("#execution/hook-ownership.js", () => ({
- claimHookOwnership: mocks.claimHookOwnership,
- isHookConflictError: () => false,
-}));
-vi.mock("#execution/tasks/child/notify.js", () => ({
- emitTaskActivityStep: mocks.emitTaskActivityStep,
- deliverTaskInputResponsesStep: mocks.deliverTaskInputResponsesStep,
- notifyTaskParent: mocks.notifyTaskParent,
-}));
-vi.mock("#execution/tools/workflow/owner-channels.js", () => ({
- createChannelReader: mocks.createChannelReader,
- raceChannelReads: mocks.raceChannelReads,
-}));
-vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({
- resumeHookStep: mocks.resumeHookStep,
-}));
-vi.mock("#execution/tools/workflow/body.js", () => ({
- executeWorkflowBody: mocks.executeWorkflowBody,
- createWorkflowBodyRef: () => bufferedAgentRequest.from,
-}));
-vi.mock("#execution/tools/workflow/owner.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#execution/tools/workflow/owner.js")>()),
- openWorkflowToolRunOwnerInbox: () => ({
- owner: { inbox: "owner" },
- reader: { channel: "workflow" },
- }),
-}));
-
-const initialView = {
- metadata: { kind: "tool", name: "approval-worker" },
- status: "working",
- taskId: "task-1",
-} satisfies TaskView;
-
-const bufferedAgentRequest = {
- kind: "request",
- 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 WorkflowToolRunMessage;
-
-const workflowAgentRequest = {
- ...bufferedAgentRequest,
- request: {
- input: { message: "authorize", target: "approver" },
- invocationId: "tool-call-1:approver:2",
- kind: "agent-invoke",
- },
-} satisfies WorkflowToolRunMessage;
-
-function authorizationRequest(attemptId: string, completed = false) {
- const data = { attemptId, name: "github", sequence: 0, stepIndex: 0, turnId: "turn-parent" };
- return {
- ...bufferedAgentRequest,
- replyTo: `ack-${attemptId}`,
- request: {
- kind: "authorization-request",
- event: {
- kind: "subagent-authorization-event",
- callId: "tool-call-1",
- childSessionId: "run-1",
- subagentName: "approval-worker",
- event: completed
- ? createAuthorizationCompletedEvent({ ...data, outcome: "authorized" })
- : createAuthorizationRequiredEvent({ ...data, description: "Sign in" }),
- },
- },
- } satisfies WorkflowToolRunMessage;
-}
-
-function queueOwnerRequest(value: WorkflowToolRunMessage) {
- mocks.raceChannelReads.mockResolvedValueOnce(
- value.kind === "outcome"
- ? {
- channel: "body",
- next: { done: false, value: { outcome: value.result, reportCount: 0 } },
- }
- : {
- channel: "workflow",
- next: { done: false, value },
- },
- );
-}
-
-function queueCommand(command: TaskCommand) {
- mocks.raceChannelReads.mockResolvedValueOnce({
- channel: "commands",
- next: { done: false, value: { kind: "task-command", command } },
- });
-}
-
-const workflowInput = {
- initialView,
- parentContinuationToken: "parent-token",
- taskInboxToken: "task-token",
- 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",
- },
-};
-
-describe("workflowToolRunWorkflow", () => {
- beforeEach(() => {
- vi.resetAllMocks();
- mocks.createHook.mockReturnValue({ token: "task-token" });
- mocks.executeWorkflowBody.mockReturnValue(new Promise(() => {}));
- mocks.sleep.mockReturnValue(new Promise(() => {}));
- });
-
- it("forwards auth events before acknowledging them", async () => {
- queueCommand({ kind: "ready" });
- queueOwnerRequest(authorizationRequest("a"));
- queueOwnerRequest(authorizationRequest("b"));
- queueOwnerRequest(authorizationRequest("a", true));
- queueOwnerRequest(authorizationRequest("b", true));
- mocks.raceChannelReads.mockResolvedValueOnce({ channel: "commands", next: { done: true } });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.notifyTaskParent).toHaveBeenCalledTimes(4);
- expect(mocks.resumeHookStep).toHaveBeenCalledTimes(4);
- for (let i = 0; i < 4; i++) {
- const notified = mocks.notifyTaskParent.mock.invocationCallOrder[i];
- const acknowledged = mocks.resumeHookStep.mock.invocationCallOrder[i];
- assert(notified !== undefined && acknowledged !== undefined);
- expect(notified).toBeLessThan(acknowledged);
- }
- });
-
- it("keeps ordinary input answerable when authorization completes with the same request id", async () => {
- const requestId = "request-1";
- const answer = {
- kind: "input-response" as const,
- childContinuationToken: "answer-hook",
- taskId: initialView.taskId,
- inputResponses: [{ requestId, optionId: "approve" }],
- };
- queueCommand({ kind: "ready" });
- queueOwnerRequest({
- ...bufferedAgentRequest,
- replyTo: "answer-hook",
- request: {
- kind: "tool-approval",
- requestId,
- prompt: "Approve deployment?",
- action: { kind: "tool-call", callId: "deploy", toolName: "deploy", input: {} },
- },
- });
- queueOwnerRequest(authorizationRequest(requestId));
- queueOwnerRequest(authorizationRequest(requestId, true));
- mocks.deliverTaskInputResponsesStep.mockResolvedValue("delivered");
- mocks.raceChannelReads.mockResolvedValueOnce({
- channel: "commands",
- next: { done: false, value: answer },
- });
- mocks.raceChannelReads.mockResolvedValueOnce({ channel: "commands", next: { done: true } });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.deliverTaskInputResponsesStep).toHaveBeenCalledExactlyOnceWith({
- answer,
- answerHook: { runId: "run-1" },
- requestIds: [requestId],
- });
- });
-
- it("acknowledges discarded authorization prompts after cancellation", async () => {
- queueCommand({ kind: "ready" });
- queueCommand({ kind: "cancel" });
- queueOwnerRequest(authorizationRequest("late"));
- mocks.raceChannelReads.mockResolvedValueOnce({ channel: "commands", next: { done: true } });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.notifyTaskParent).toHaveBeenCalledExactlyOnceWith({
- token: "parent-token",
- view: { ...initialView, status: "cancelled" },
- });
- expect(mocks.resumeHookStep).toHaveBeenCalledExactlyOnceWith("ack-late", null, {
- ifPresent: true,
- });
- });
-
- it("forwards child-agent auth without treating it as the workflow's own request", async () => {
- const message = authorizationRequest("child");
- message.request.event.childSessionId = "child-session";
- queueCommand({ kind: "ready" });
- queueOwnerRequest(message);
- mocks.raceChannelReads.mockResolvedValueOnce({ channel: "commands", next: { done: true } });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.notifyTaskParent).toHaveBeenCalledExactlyOnceWith({
- request: message,
- taskId: initialView.taskId,
- token: workflowInput.parentContinuationToken,
- });
- expect(mocks.resumeHookStep).not.toHaveBeenCalled();
- expect(
- mocks.emitTaskActivityStep.mock.calls.some(
- ([input]) => input.view.status === "input_required",
- ),
- ).toBe(false);
- });
-
- it("does not acknowledge auth after failed forwarding", async () => {
- queueCommand({ kind: "ready" });
- queueOwnerRequest(authorizationRequest("a"));
- mocks.notifyTaskParent.mockRejectedValue(new Error("failed forwarding"));
- await expect(workflowToolRunWorkflow(workflowInput)).rejects.toThrow("failed forwarding");
- expect(mocks.resumeHookStep).not.toHaveBeenCalled();
- });
-
- 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: "workflow",
- next: { done: false, value: workflowAgentRequest },
- })
- .mockResolvedValueOnce({ channel: "commands", next: { done: true, value: undefined } });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.notifyTaskParent).toHaveBeenCalledWith({
- request: workflowAgentRequest,
- taskId: "task-1",
- token: "parent-token",
- });
- });
-
- it("waits for agent settlement delivery before publishing task completion", async () => {
- const delivery = Promise.withResolvers<void>();
- const delivering = Promise.withResolvers<void>();
- mocks.notifyTaskParent.mockImplementationOnce(() => {
- delivering.resolve();
- return delivery.promise;
- });
- const settlement = {
- ...bufferedAgentRequest,
- request: {
- kind: "agent-settled",
- result: {
- callId: "nested",
- kind: "subagent-result",
- origin: "child",
- outcome: {
- kind: "parked",
- result: { kind: "succeeded", output: "done" },
- usageDelta: {
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- inputTokens: 2,
- outputTokens: 3,
- },
- },
- output: "done",
- subagentName: "research",
- },
- },
- } satisfies WorkflowToolRunMessage;
- queueCommand({ kind: "ready" });
- queueOwnerRequest(settlement);
- queueOwnerRequest({
- kind: "outcome",
- from: bufferedAgentRequest.from,
- result: { status: "completed", output: "done" },
- });
- const execution = workflowToolRunWorkflow(workflowInput);
- await delivering.promise;
- expect(mocks.notifyTaskParent).toHaveBeenCalledTimes(1);
- delivery.resolve();
- await execution;
- expect(mocks.notifyTaskParent).toHaveBeenNthCalledWith(1, {
- request: settlement,
- taskId: "task-1",
- token: "parent-token",
- });
- expect(mocks.notifyTaskParent).toHaveBeenNthCalledWith(2, {
- token: "parent-token",
- view: expect.objectContaining({ status: "completed" }),
- });
- });
-
- it("does not execute a workflow body before task admission", async () => {
- mocks.raceChannelReads.mockResolvedValueOnce({
- channel: "commands",
- next: { done: true, value: undefined },
- });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.executeWorkflowBody).not.toHaveBeenCalled();
- });
-
- it.each(["ready", "reject-dispatch"] as const)(
- "does not start pre-admission cancelled work after %s",
- async (kind) => {
- queueCommand({ kind: "cancel" });
- queueCommand(kind === "ready" ? { kind } : { kind, data: "step failed" });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.executeWorkflowBody).not.toHaveBeenCalled();
- expect(mocks.notifyTaskParent).toHaveBeenCalledTimes(kind === "ready" ? 1 : 0);
- if (kind === "ready")
- expect(mocks.notifyTaskParent).toHaveBeenLastCalledWith({
- token: "parent-token",
- view: { ...initialView, status: "cancelled" },
- });
- },
- );
-
- 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 workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.executeWorkflowBody).toHaveBeenCalledOnce();
- expect(mocks.executeWorkflowBody).toHaveBeenCalledWith(
- expect.objectContaining({ execution: "background" }),
- expect.any(AbortSignal),
- );
- });
-
- it.each(["tool", "subagent"])(
- "consumes %s progress and only forwards subagent updates",
- async (kind) => {
- const report = {
- from: { ...bufferedAgentRequest.from, callId: "call-1" },
- update: "progress",
- };
- mocks.raceChannelReads
- .mockResolvedValueOnce({
- channel: "commands",
- next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
- })
- .mockResolvedValueOnce({
- channel: "workflow",
- next: { done: false, value: { ...report, kind: "report" } },
- })
- .mockResolvedValueOnce({
- channel: "body",
- next: {
- done: false,
- value: {
- reportCount: 0,
- outcome: { status: "completed", output: "done" },
- },
- },
- });
-
- await workflowToolRunWorkflow({
- ...workflowInput,
- initialView: { ...initialView, metadata: { ...initialView.metadata, kind } },
- });
-
- if (kind === "subagent") {
- expect(mocks.notifyTaskParent).toHaveBeenNthCalledWith(1, {
- token: "parent-token",
- update: { report: expect.objectContaining(report), index: 0 },
- view: expect.objectContaining({ status: "working" }),
- });
- expect(mocks.notifyTaskParent).toHaveBeenNthCalledWith(2, {
- token: "parent-token",
- view: expect.objectContaining({ status: "completed" }),
- });
- return;
- }
- expect(mocks.notifyTaskParent).toHaveBeenCalledTimes(1);
- },
- );
-
- 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: {
- reportCount: 0,
- outcome: { reason: "cancelled", status: "cancelled" },
- },
- },
- });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.notifyTaskParent).toHaveBeenCalledWith({
- token: "parent-token",
- view: expect.objectContaining({ status: "cancelled" }),
- });
- });
-
- it("ignores duplicate admission commands while cancelled work finishes cleanup", async () => {
- queueCommand({ kind: "ready" });
- queueCommand({ kind: "cancel" });
- queueCommand({ kind: "ready" });
- queueCommand({ kind: "reject-dispatch", data: "late rejection" });
- queueOwnerRequest(authorizationRequest("cleanup", true));
- queueOwnerRequest({
- from: bufferedAgentRequest.from,
- kind: "outcome",
- result: { status: "cancelled", reason: "stop" },
- });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.raceChannelReads).toHaveBeenCalledTimes(6);
- expect(mocks.executeWorkflowBody).toHaveBeenCalledOnce();
- expect(mocks.resumeHookStep).toHaveBeenCalledExactlyOnceWith("ack-cleanup", null, {
- ifPresent: true,
- });
- expect(mocks.notifyTaskParent).toHaveBeenCalledTimes(2);
- const acknowledged = mocks.resumeHookStep.mock.invocationCallOrder[0];
- const completed = mocks.notifyTaskParent.mock.invocationCallOrder[1];
- assert(acknowledged !== undefined && completed !== undefined);
- expect(acknowledged).toBeLessThan(completed);
- });
-
- it("keeps explicit cancellation final when the invocation completes late", 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: {
- reportCount: 0,
- outcome: { output: "late success", status: "completed" },
- },
- },
- });
-
- await workflowToolRunWorkflow(workflowInput);
-
- expect(mocks.notifyTaskParent).toHaveBeenCalledWith({
- token: "parent-token",
- view: expect.objectContaining({ status: "cancelled" }),
- });
- expect(mocks.notifyTaskParent).toHaveBeenLastCalledWith({
- token: "parent-token",
- view: expect.objectContaining({ status: "cancelled" }),
- });
- });
-
- it("drains background yields before delivering the return value without progress notifications", async () => {
- mocks.raceChannelReads
- .mockResolvedValueOnce({
- channel: "commands",
- next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
- })
- .mockResolvedValueOnce({
- channel: "body",
- next: {
- done: false,
- value: {
- reportCount: 1,
- outcome: { output: "done", status: "completed" },
- },
- },
- })
- .mockResolvedValueOnce({
- channel: "workflow",
- next: {
- done: false,
- value: {
- kind: "report",
- from: bufferedAgentRequest.from,
- update: "Review the export",
- },
- },
- });
- await workflowToolRunWorkflow(workflowInput);
- expect(mocks.raceChannelReads).toHaveBeenCalledTimes(3);
- expect(mocks.notifyTaskParent).toHaveBeenCalledTimes(1);
- expect(mocks.notifyTaskParent).toHaveBeenCalledExactlyOnceWith({
- token: "parent-token",
- view: expect.objectContaining({
- status: "completed",
- lastOutput: { type: "result", data: "done" },
- }),
- });
- });
-});
diff --git a/packages/eve/src/execution/tools/workflow/workflow-owner-background.ts b/packages/eve/src/execution/tools/workflow/workflow-owner-background.ts
deleted file mode 100644
index 519d7e53a..000000000
--- a/packages/eve/src/execution/tools/workflow/workflow-owner-background.ts
+++ /dev/null
@@ -1,204 +0,0 @@
-import { createHook } from "#compiled/@workflow/core/index.js";
-
-import { claimHookOwnership, isHookConflictError } from "#execution/hook-ownership.js";
-import {
- emitTaskActivityStep,
- deliverTaskInputResponsesStep,
- notifyTaskParent,
-} from "#execution/tasks/child/notify.js";
-import type { BackgroundWorkflowToolRunInput } from "#execution/tools/workflow/types.js";
-import { deliverWorkflowAuthorization } from "#execution/tools/workflow/owner.js";
-import type {
- WorkflowToolRunRequestMessage,
- WorkflowToolRunReport,
- WorkflowToolRunMessage,
-} from "#execution/tools/workflow/messages.js";
-import {
- createChannelReader,
- type ChannelReader,
-} from "#execution/tools/workflow/owner-channels.js";
-import { workflowToolRunInputRequests } from "#execution/tools/workflow/owner-inbox.js";
-import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
-import { applyTaskTransition } from "#tasks/transitions.js";
-import {
- isTerminalTaskStatus,
- readTaskInputRequestId,
- type TaskCommand,
- type TaskInboundAnswerInput,
- type TaskRunInboundPayload,
- type TaskView,
-} from "#tasks/types.js";
-
-interface BackgroundWorkflowOwner {
- readonly kind: "session";
- readonly commands: ChannelReader<"commands", TaskRunInboundPayload>;
- readonly signal: AbortSignal;
- handleCommand(payload: TaskRunInboundPayload): Promise<"start" | "stop" | undefined>;
- handleMessage(message: WorkflowToolRunMessage): Promise<void>;
-}
-
-/** Routes child messages; the parent session owns persisted task state. */
-export async function createBackgroundWorkflowOwner(
- input: BackgroundWorkflowToolRunInput,
-): Promise<BackgroundWorkflowOwner | undefined> {
- const commands = createHook<TaskRunInboundPayload>({ token: input.taskInboxToken });
- let view = input.initialView;
- let updateIndex = 0;
- const answerHooks = new Map<string, AnswerHookRoute>();
- const bodyController = new AbortController();
- try {
- await claimHookOwnership(commands);
- } catch (error) {
- if (isHookConflictError(error)) return;
- throw error;
- }
- await emitTaskActivityStep({ activityObserver: input.activityObserver, view });
- return {
- kind: "session",
- commands: createChannelReader("commands", commands),
- signal: bodyController.signal,
- handleCommand,
- handleMessage,
- };
-
- async function handleCommand(
- payload: TaskRunInboundPayload,
- ): Promise<"start" | "stop" | undefined> {
- if (payload.kind === "task-command") {
- if (payload.command.kind === "ready") {
- if (!isTerminalTaskStatus(view.status)) return "start";
- await notifyTaskParent({ token: input.parentContinuationToken, view });
- return "stop";
- }
- if (payload.command.kind === "reject-dispatch") {
- applyTransition(payload.command);
- return "stop";
- }
- }
- await applyPayload(payload);
- }
-
- async function handleMessage(message: WorkflowToolRunMessage): Promise<void> {
- if (message.kind === "report") {
- await handleReport(message);
- return;
- }
- if (message.kind === "outcome") {
- const transitioned = applyTransition(message);
- if (transitioned || view.status === "cancelled") {
- await notifyTaskParent({ token: input.parentContinuationToken, view });
- }
- return;
- }
- const request = message;
- const kind = request.request.kind;
- if (kind === "agent-invoke" || kind === "agent-settled" || kind === "authorization-request") {
- await handleOwnerRequest(request);
- return;
- }
- if (request.requestCoordinates === undefined) {
- answerHooks.set(request.replyTo, { runId: request.from.runId });
- }
- const accepted = applyTransition({
- kind: "require-input",
- inputRequests: workflowToolRunInputRequests(request),
- });
- if (!accepted) return;
- await notifyTaskParent({
- request,
- taskId: view.taskId,
- token: input.parentContinuationToken,
- });
- }
-
- async function handleReport(report: WorkflowToolRunReport): Promise<void> {
- const index = updateIndex++;
- if (view.metadata.kind !== "subagent" || isTerminalTaskStatus(view.status)) return;
- await notifyTaskParent({
- token: input.parentContinuationToken,
- update: { report, index },
- view,
- });
- }
-
- async function applyPayload(payload: TaskRunInboundPayload): Promise<void> {
- 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-command") {
- command = payload.command;
- } else {
- return;
- }
- if (command === undefined) return;
-
- const accepted = applyTransition(command);
- if (!accepted) return;
- if (command.kind === "cancel") {
- bodyController.abort(new Error(`Task ${view.taskId} was cancelled.`));
- }
- }
-
- function applyTransition(
- command: TaskCommand | Extract<WorkflowToolRunMessage, { kind: "outcome" }>,
- ): boolean {
- const result = applyTaskTransition(view, command);
- if (result.action !== "accepted") return false;
- view = result.view;
- return true;
- }
-
- // Owner traffic must wait until the parent has acknowledged task dispatch.
- async function handleOwnerRequest(message: WorkflowToolRunRequestMessage): Promise<void> {
- const { request } = message;
- if (request.kind === "authorization-request") {
- await deliverWorkflowAuthorization({ ...message, request }, async () => {
- // A cancelled workflow may still need to close its own displayed prompt.
- const closesPrompt =
- request.event.childSessionId === message.from.runId &&
- request.event.event.type === "authorization.completed";
- if (isTerminalTaskStatus(view.status) && !closesPrompt) return;
- await notifyTaskParent({
- request: message,
- taskId: view.taskId,
- token: input.parentContinuationToken,
- });
- });
- return;
- }
- if (isTerminalTaskStatus(view.status)) return;
- await notifyTaskParent({
- request: message,
- taskId: view.taskId,
- token: input.parentContinuationToken,
- });
- }
-}
-
-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);
- return requestId === undefined ? [] : [requestId];
- }),
- );
- const requestIds = answer.inputResponses
- .map((response) => response.requestId)
- .filter((id) => outstanding.has(id));
- if (requestIds.length === 0) return undefined;
- return (await deliverTaskInputResponsesStep({ answer, answerHook, requestIds })) === "delivered"
- ? { kind: "answered", requestIds }
- : undefined;
-}
diff --git a/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts b/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts
index bbe7b3f7c..b288792a4 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts
@@ -1,35 +1,48 @@
import { createHook } from "#compiled/@workflow/core/index.js";
+import type { WorkflowToolRunAsks } from "#execution/tools/workflow/ask.js";
import {
createChannelReader,
type ChannelReader,
} from "#execution/tools/workflow/owner-channels.js";
-import {
- isWorkflowToolRunControlMessage,
- type WorkflowToolRunMessage,
- type WorkflowToolRunControlMessage,
+import type {
+ WorkflowBodyCommand,
+ WorkflowToolRunControlMessage,
+ WorkflowToolRunMessage,
} from "#execution/tools/workflow/messages.js";
import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
import type { WorkflowToolRunInput } from "#execution/tools/workflow/types.js";
export interface BlockingWorkflowOwner {
- readonly kind: "turn";
readonly commands: ChannelReader<"control", WorkflowToolRunControlMessage>;
+ /** The call's `interruptSignal`: steering arrived while the turn waits on the call. */
+ readonly interruptSignal: AbortSignal;
readonly signal: AbortSignal;
- handleCommand(message: WorkflowToolRunControlMessage): void;
+ handleCommand(command: WorkflowBodyCommand): void;
handleMessage(message: WorkflowToolRunMessage): Promise<void>;
}
-/** Routes invocation messages to the waiting turn and accepts cancellation. */
-export function createBlockingWorkflow(input: WorkflowToolRunInput): BlockingWorkflowOwner {
+/** Routes invocation messages to the waiting turn and accepts cancellation and interrupts. */
+export function createBlockingWorkflow(
+ input: WorkflowToolRunInput,
+ asks: WorkflowToolRunAsks,
+): BlockingWorkflowOwner {
const controller = new AbortController();
+ const interrupt = new AbortController();
const hook = createHook<WorkflowToolRunControlMessage>({ token: input.hookToken });
return {
- kind: "turn",
commands: createChannelReader("control", hook),
+ interruptSignal: interrupt.signal,
signal: controller.signal,
- handleCommand(message: WorkflowToolRunControlMessage) {
- if (isWorkflowToolRunControlMessage(message))
- controller.abort(new WorkflowToolRunCancelledError(message.reason));
+ handleCommand(command: WorkflowBodyCommand) {
+ if (command.kind === "interrupt") {
+ interrupt.abort();
+ return;
+ }
+ // The session retired the call's questions when it stopped the call,
+ // so it accepts no answer after this; settle them before the abort
+ // would ask to withdraw them.
+ asks.cancelAll();
+ controller.abort(new WorkflowToolRunCancelledError(command.reason));
},
handleMessage(message: WorkflowToolRunMessage) {
return resumeHookStep(input.owner.inbox, message, {
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run-authorization-close.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run-authorization-close.integration.test.ts
index e624ab248..afe6bd77c 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run-authorization-close.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run-authorization-close.integration.test.ts
@@ -6,11 +6,7 @@ import { sessionCommandHookToken } from "#execution/session-inbox/address.js";
import { handleConnectionCallbackRequest } from "#execution/connections/callback-route.js";
import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
import { authorizedDeployWorkflow } from "#internal/testing/workflow-tool-fixtures.js";
-import {
- captureConsoleOutput,
- taskParentEndedNotice,
- workflowSdkNotice,
-} from "#internal/testing/log-records.js";
+import { captureConsoleOutput, workflowSdkNotice } from "#internal/testing/log-records.js";
import {
buildWorkflowToolSerializedContext,
createWorkflowToolRuntime,
@@ -18,18 +14,12 @@ import {
} from "#internal/testing/workflow-tool-run-harness.js";
describe("workflow step authorization failures", () => {
- it.each([
- { background: false, disposition: "denied" },
- { background: false, disposition: "rejected" },
- { background: false, disposition: "cancel" },
- { background: true, disposition: "cancel" },
- ])(
- "closes authorization on $disposition (background=$background)",
- async ({ background, disposition }) => {
+ it.each(["denied", "rejected", "cancel"])(
+ "closes authorization on %s",
+ async (disposition) => {
const output = captureConsoleOutput();
const runtime = await createWorkflowToolRuntime({
agentName: "workflow-step-auth-failure",
- background,
execute: authorizedDeployWorkflow,
toolName: "deploy_service",
});
@@ -56,25 +46,21 @@ describe("workflow step authorization failures", () => {
]);
const stream = captureTurnEvents(run);
try {
- const events = [];
- for (
- let i = 0;
- i < 5 && filterEventsByType(events, "authorization.required").length === 0;
- i++
- )
- events.push(...(await stream.nextTurn()));
+ // The sign-in parks the open turn; the run keeps waiting for its callback.
+ const events = await stream.nextUntil((event) => event.type === "turn.waiting");
+ expect(events.at(-2)?.type).toBe("authorization.required");
+ expect(filterEventsByType(events, "turn.completed")).toHaveLength(0);
const required = filterEventsByType(events, "authorization.required")[0]!;
- expect(required).toBeDefined();
const url = new URL(required.data.webhookUrl!);
const token = decodeURIComponent(url.pathname.split("/").at(-1)!);
const world = await getWorld();
const executorRunId = (await world.hooks.getByToken(token)).runId;
const params = { token, attemptId: required.data.attemptId!, name: required.data.name };
if (disposition === "cancel") {
- await resumeSessionInbox(
- sessionCommandHookToken(run.runId),
- background ? { kind: "cancel", tasks: true } : { kind: "cancel", turnId: "turn_0" },
- );
+ await resumeSessionInbox(sessionCommandHookToken(run.runId), {
+ kind: "cancel",
+ turnId: "turn_0",
+ });
} else {
url.searchParams.set("code", disposition === "denied" ? "denied" : "approved");
expect(
@@ -82,10 +68,8 @@ describe("workflow step authorization failures", () => {
).toBe(200);
}
if (disposition === "cancel") {
- if (!background) {
- events.push(...(await stream.nextTurn()));
- expect(filterEventsByType(events, "turn.cancelled")).toHaveLength(1);
- }
+ events.push(...(await stream.nextTurn()));
+ expect(filterEventsByType(events, "turn.cancelled")).toHaveLength(1);
} else {
for (
let i = 0;
@@ -114,7 +98,7 @@ describe("workflow step authorization failures", () => {
expect(
output.lines.filter((line) => line.startsWith(workflowSdkNotice.fatalStep)),
).toHaveLength(disposition === "cancel" ? 0 : 1);
- expect(output.unexpected(workflowSdkNotice.fatalStep, taskParentEndedNotice)).toEqual([]);
+ expect(output.unexpected(workflowSdkNotice.fatalStep)).toEqual([]);
},
60_000,
);
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run-authorization.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run-authorization.integration.test.ts
index 8981fc4cb..a9bdf3c35 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run-authorization.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run-authorization.integration.test.ts
@@ -54,16 +54,11 @@ describe("workflow step authorization", () => {
});
}, 60_000);
- it.each([
- { background: false, service: "interactive" },
- { background: true, service: "interactive" },
- { background: false, service: "retry" },
- ])(
- "parks on its own callback and resumes the step (background=$background, service=$service)",
- async ({ background, service }) => {
+ it.each(["interactive", "retry"])(
+ "parks on its own callback and resumes the step (service=%s)",
+ async (service) => {
const runtime = await createWorkflowToolRuntime({
agentName: "workflow-step-auth",
- background,
execute: authorizedDeployWorkflow,
toolName: "deploy_service",
});
@@ -90,15 +85,11 @@ describe("workflow step authorization", () => {
]);
const stream = captureTurnEvents(run);
try {
- const events = [];
- for (
- let i = 0;
- i < 5 && filterEventsByType(events, "authorization.required").length === 0;
- i++
- )
- events.push(...(await stream.nextTurn()));
+ // The sign-in parks the open turn; the run keeps waiting for its callback.
+ const events = await stream.nextUntil((event) => event.type === "turn.waiting");
+ expect(events.at(-2)?.type).toBe("authorization.required");
+ expect(filterEventsByType(events, "turn.completed")).toHaveLength(0);
const required = filterEventsByType(events, "authorization.required")[0]!;
- expect(required).toBeDefined();
const url = new URL(required.data.webhookUrl!);
const parts = url.pathname.split("/").map(decodeURIComponent);
const token = parts.at(-1)!;
@@ -124,6 +115,9 @@ describe("workflow step authorization", () => {
(event) => event.data.outcome,
),
).toEqual(["authorized"]);
+ // The turn the sign-in parked resumes and completes once.
+ expect(filterEventsByType(events, "turn.started")).toHaveLength(1);
+ expect(filterEventsByType(events, "turn.completed")).toHaveLength(1);
const text = JSON.stringify(events);
expect(text).toContain("authenticatedAs");
expect(text).toContain("user-1");
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run-background.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run-background.integration.test.ts
deleted file mode 100644
index 16974a9e4..000000000
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run-background.integration.test.ts
+++ /dev/null
@@ -1,223 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { start } from "#internal/workflow/runtime.js";
-import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";
-import { workflowEntry } from "#execution/session/entry.js";
-import { sessionCommandHookToken } from "#execution/session-inbox/address.js";
-import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
-import type { TestRuntime } from "#internal/testing/app-harness.js";
-import {
- backgroundDeployWorkflow,
- confirmDeployWorkflow,
- failingDeployWorkflow,
-} from "#internal/testing/workflow-tool-fixtures.js";
-import type { InputRequestedStreamEvent } from "#protocol/message.js";
-import {
- buildWorkflowToolSerializedContext,
- createWorkflowToolRuntime,
-} from "#internal/testing/workflow-tool-run-harness.js";
-import {
- captureConsoleOutput,
- taskParentEndedNotice,
- workflowSdkNotice,
-} from "#internal/testing/log-records.js";
-
-describe("background workflow tools", () => {
- afterEach(() => vi.unstubAllEnvs());
- it("runs a session-owned background workflow invocation", async () => {
- const output = captureConsoleOutput();
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_inline");
- const runtime = await createWorkflowToolRuntime({
- agentName: "workflow-tool-background",
- execute: backgroundDeployWorkflow,
- toolName: "report_deploy",
- });
-
- await runtime.run(async () => {
- enableBackgroundTool(runtime, "report_deploy");
-
- const run = await start(workflowEntry, [
- {
- kind: "initial",
- ownerDeploymentId: "dpl_inline",
- input: { message: 'Run report_deploy with service "api"' },
- serializedContext: buildWorkflowToolSerializedContext({
- acceptedDeploymentId: "dpl_inline",
- continuationToken: "http:workflow-tool-background",
- }),
- },
- ]);
- const stream = captureTurnEvents(run);
-
- try {
- const receiptTurn = await stream.nextTurn();
- const receipt = filterEventsByType(receiptTurn, "action.result").find(
- (event) => event.data.result.kind === "tool-result",
- );
- expect(receipt?.data.result.output).toMatchObject({ status: "working" });
- expect(filterEventsByType(receiptTurn, "turn.failed")).toHaveLength(0);
-
- const notifications: string[] = [];
- for (
- let turn = 0;
- turn < 3 && !notifications.some((text) => text.includes("is completed"));
- turn += 1
- ) {
- const woken = await stream.nextTurn();
- expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);
- notifications.push(eventsText(filterEventsByType(woken, "message.received")));
- }
- const text = notifications.join("\n");
- expect(text).not.toContain("Review plan:api");
- expect(text).not.toContain("update: planned api");
- expect(text).toContain("is completed");
- expect(text).toContain("plan:api");
- } finally {
- stream.dispose();
- await run.cancel();
- }
- });
- expect(output.unexpected(workflowSdkNotice.unpinnedDelivery, taskParentEndedNotice)).toEqual(
- [],
- );
- }, 90_000);
-
- it("wakes the agent with the failure when a background workflow tool throws", async () => {
- const runtime = await createWorkflowToolRuntime({
- agentName: "workflow-tool-background-fail",
- execute: failingDeployWorkflow,
- toolName: "deploy_service",
- });
-
- await runtime.run(async () => {
- enableBackgroundTool(runtime, "deploy_service");
-
- const run = await start(workflowEntry, [
- {
- kind: "initial",
- ownerDeploymentId: "dpl_inline",
- input: { message: 'Run deploy_service with service "api"' },
- serializedContext: buildWorkflowToolSerializedContext({
- continuationToken: "http:workflow-tool-background-fail",
- }),
- },
- ]);
- const stream = captureTurnEvents(run);
-
- try {
- const receiptTurn = await stream.nextTurn();
- expect(filterEventsByType(receiptTurn, "turn.failed")).toHaveLength(0);
-
- const notifications: string[] = [];
- for (
- let turn = 0;
- turn < 3 && !notifications.some((t) => t.includes("failed"));
- turn += 1
- ) {
- const woken = await stream.nextTurn();
- expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);
- notifications.push(eventsText(filterEventsByType(woken, "message.received")));
- }
- const text = notifications.join("\n");
- expect(text).toContain("(deploy_service) failed.");
- expect(text).toContain("deploy of api exploded");
- } finally {
- stream.dispose();
- await run.cancel();
- }
- });
- }, 90_000);
-
- it("lets a background workflow tool ask now and act when answered", async () => {
- const runtime = await createWorkflowToolRuntime({
- agentName: "workflow-tool-background-hitl",
- execute: confirmDeployWorkflow,
- toolName: "confirm_deploy",
- });
-
- await runtime.run(async () => {
- enableBackgroundTool(runtime, "confirm_deploy");
-
- const run = await start(workflowEntry, [
- {
- kind: "initial",
- ownerDeploymentId: "dpl_inline",
- input: { message: 'Run confirm_deploy with service "api"' },
- serializedContext: buildWorkflowToolSerializedContext({
- continuationToken: "http:workflow-tool-background-hitl",
- requestInput: true,
- }),
- },
- ]);
- const stream = captureTurnEvents(run);
-
- try {
- const receiptTurn = await stream.nextTurn();
- expect(filterEventsByType(receiptTurn, "turn.failed")).toHaveLength(0);
- expect(
- filterEventsByType(receiptTurn, "action.result").some(
- (event) =>
- event.data.result.kind === "tool-result" &&
- typeof event.data.result.output === "object" &&
- event.data.result.output !== null &&
- "taskId" in event.data.result.output,
- ),
- ).toBe(true);
-
- // The question arrives after the turn that called the tool ended.
- let request: InputRequestedStreamEvent["data"]["requests"][number] | undefined;
- for (let turn = 0; turn < 3 && request === undefined; turn += 1) {
- const woken = await stream.nextTurn();
- expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);
- request = (
- filterEventsByType(woken, "input.requested")[0] as InputRequestedStreamEvent | undefined
- )?.data.requests[0];
- }
- expect(request).toMatchObject({ kind: "question", prompt: "Apply plan:api?" });
-
- // The stable session inbox already took the task's wake, so it is
- // known to exist; answer through it directly.
- await resumeSessionInbox(sessionCommandHookToken(run.runId), {
- kind: "send",
- payload: { inputResponses: [{ optionId: "approve", requestId: request!.requestId }] },
- });
-
- const notifications: string[] = [];
- for (
- let turn = 0;
- turn < 3 && !notifications.some((text) => text.includes("is completed"));
- turn += 1
- ) {
- const woken = await stream.nextTurn();
- expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);
- notifications.push(eventsText(filterEventsByType(woken, "message.received")));
- }
- const text = notifications.join("\n");
- expect(text).toContain("is completed");
- expect(text).toContain('\\"approved\\":true');
- } finally {
- stream.dispose();
- await run.cancel();
- }
- });
- }, 90_000);
-});
-
-/** Flags one manifest tool as `execution: "background"` under `experimental.tasks`. */
-function enableBackgroundTool(runtime: TestRuntime, toolName: string): void {
- const artifacts = runtime.session.compiledArtifacts;
- if (artifacts === null) throw new Error("expected installed compiled artifacts");
- runtime.session.compiledArtifacts = {
- ...artifacts,
- manifest: {
- ...artifacts.manifest,
- config: artifacts.manifest.config,
- tools: artifacts.manifest.tools.map((tool) =>
- tool.name === toolName ? { ...tool, execution: "background" as const } : tool,
- ),
- },
- };
-}
-
-function eventsText(events: readonly { readonly data?: unknown }[]): string {
- return events.map((event) => JSON.stringify(event.data ?? null)).join("\n");
-}
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run-cancellation.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run-cancellation.integration.test.ts
index 6d39197ca..91cb5455b 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run-cancellation.integration.test.ts
@@ -1,217 +1,21 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { getRun, getWorld, start } from "#internal/workflow/runtime.js";
+import { getWorld, start } from "#internal/workflow/runtime.js";
import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";
import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
import { workflowEntry } from "#execution/session/entry.js";
import { sessionCommandHookToken } from "#execution/session-inbox/address.js";
import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
-import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";
-import { setAgentHandleStore } from "#subagents/handles/store.js";
-import {
- holdUntilAbortedWorkflow,
- receiveDelegatedResultWorkflow,
-} from "#internal/testing/workflow-tool-fixtures.js";
+import { holdUntilAbortedWorkflow } from "#internal/testing/workflow-tool-fixtures.js";
import { workflowToolRunWorkflowReference } from "#execution/workflow-runtime.js";
import {
buildWorkflowToolSerializedContext,
createWorkflowToolRuntime,
waitForWorkflowToolRunTerminal,
} from "#internal/testing/workflow-tool-run-harness.js";
-import {
- captureConsoleOutput,
- taskParentEndedNotice,
- workflowSdkNotice,
-} from "#internal/testing/log-records.js";
+import { captureConsoleOutput, workflowSdkNotice } from "#internal/testing/log-records.js";
describe("workflow tool cancellation", () => {
afterEach(() => vi.unstubAllEnvs());
- it("fails the retained caller when a yielded child receives reset", async () => {
- const output = captureConsoleOutput();
- const kind = "reset";
- const runtime = await createWorkflowToolRuntime({
- agentName: `yielded-child-${kind}`,
- background: true,
- execute: holdUntilAbortedWorkflow,
- toolName: "deploy_service",
- });
- await runtime.run(async () => {
- const parentToken = `parent-result-${kind}`;
- const parent = await start(receiveDelegatedResultWorkflow, [parentToken]);
- let child: ReturnType<typeof getRun> | undefined;
- let stream: ReturnType<typeof captureTurnEvents> | undefined;
- let nestedRunId: string | undefined;
- try {
- await waitForHook(parent, { token: parentToken });
- const before = await listWorkflowToolRunIds();
- child = await start(workflowEntry, [
- {
- kind: "initial",
- ownerDeploymentId: "dpl_inline",
- input: { message: 'Run deploy_service with service "api"' },
- serializedContext: {
- ...buildWorkflowToolSerializedContext({
- continuationToken: `child-${kind}`,
- }),
- "eve.channel": {
- kind: "subagent",
- state: {
- callId: "delegate",
- subagentName: "detector",
- parentContinuationToken: parentToken,
- parentSessionId: parent.runId,
- },
- },
- },
- },
- ]);
- stream = captureTurnEvents(child);
- const yielded = await stream.nextTurn();
- expect(filterEventsByType(yielded, "turn.completed")).toHaveLength(1);
- expect(yielded.at(-1)?.type).toBe("session.waiting");
- nestedRunId = await waitForNewWorkflowToolRun(before);
- await waitForHook({ runId: nestedRunId });
- expect(await parent.status).toBe("running");
- await resumeSessionInbox(sessionCommandHookToken(child.runId), { kind });
- await expect(parent.returnValue).resolves.toMatchObject({
- kind: "runtime-action-result",
- results: [
- {
- callId: "delegate",
- isError: true,
- outcome: {
- kind: "terminal",
- result: { kind: "failed" },
- },
- },
- ],
- });
- await expect(child.returnValue).resolves.toEqual({
- output: "The session ended before the delegated task completed.",
- });
- expect(await waitForWorkflowToolRunTerminal(nestedRunId)).toBe("completed");
- } finally {
- stream?.dispose();
- if (nestedRunId !== undefined) {
- const nested = getRun(nestedRunId);
- const status = await nested.status;
- if (status === "pending" || status === "running") await nested.cancel();
- }
- for (const run of [child, parent]) {
- if (run === undefined) continue;
- const status = await run.status;
- if (status === "pending" || status === "running") await run.cancel();
- }
- }
- });
- expect(output.lines).toContainEqual(expect.stringContaining(workflowSdkNotice.maxRetries));
- expect(output.lines).toContainEqual(expect.stringContaining(taskParentEndedNotice));
- expect(
- output.unexpected(
- workflowSdkNotice.maxRetries,
- taskParentEndedNotice,
- workflowSdkNotice.unpinnedDelivery,
- ),
- ).toEqual([]);
- }, 30_000);
-
- it("cancels nested work after its owning child has yielded", async () => {
- const output = captureConsoleOutput();
- const runtime = await createWorkflowToolRuntime({
- agentName: "yielded-child-cancel",
- background: true,
- execute: holdUntilAbortedWorkflow,
- toolName: "deploy_service",
- });
- await runtime.run(async () => {
- const before = await listWorkflowToolRunIds();
- const child = await start(workflowEntry, [
- {
- kind: "initial",
- ownerDeploymentId: "dpl_inline",
- input: { message: 'Run deploy_service with service "api"' },
- serializedContext: buildWorkflowToolSerializedContext({
- continuationToken: "http:yielded-child-cancel",
- }),
- },
- ]);
- const stream = captureTurnEvents(child);
- let nestedRunId: string | undefined;
- try {
- const yielded = await stream.nextTurn();
- expect(filterEventsByType(yielded, "turn.completed")).toHaveLength(1);
- expect(yielded.at(-1)?.type).toBe("session.waiting");
- nestedRunId = await waitForNewWorkflowToolRun(before);
- await waitForHook({ runId: nestedRunId });
- expect(await getRun(nestedRunId).status).toBe("running");
-
- await cancelBackgroundAgentTask({
- entry: {
- callId: "delegate",
- toolName: "child",
- lifetime: "session",
- origin: { turnId: "parent-turn", stepIndex: 0 },
- address: { runId: child.runId, hookToken: "unused" },
- task: {
- taskId: "outer-task",
- metadata: { kind: "subagent", name: "child" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- },
- session: {
- state: setAgentHandleStore(undefined, {
- handles: [
- {
- phase: "claimed",
- ownerId: "outer-task",
- operationId: "delegate",
- identity: { id: "child", name: "child", nodeId: "subagents/child" },
- address: {
- kind: "agent/local",
- sessionId: child.runId,
- continuationToken: "child",
- },
- },
- ],
- }),
- },
- serializedContext: {},
- });
-
- // The held step can finish only after its abort signal fires or its 60s timer expires.
- // Finishing within 15s proves cancellation reached the yielded child's work.
- expect(await waitForWorkflowToolRunTerminal(nestedRunId)).toBe("completed");
-
- // This input follows the cancellation notification in the child's inbox.
- // It must be the next turn, without a task notification waking the child first.
- await resumeSessionInbox(sessionCommandHookToken(child.runId), {
- kind: "send",
- payload: { message: "Hello again" },
- });
- const next = await stream.nextTurn();
- expect(
- filterEventsByType(next, "message.received").map((event) => event.data.message),
- ).toEqual(["Hello again"]);
- expect(filterEventsByType(next, "turn.failed")).toHaveLength(0);
- } finally {
- stream.dispose();
- if (nestedRunId !== undefined) {
- const nested = getRun(nestedRunId);
- const status = await nested.status;
- if (status === "pending" || status === "running") await nested.cancel();
- }
- await child.cancel();
- }
- });
- expect(output.lines).toContainEqual(expect.stringContaining(workflowSdkNotice.maxRetries));
- expect(
- output.unexpected(
- workflowSdkNotice.maxRetries,
- workflowSdkNotice.unpinnedDelivery,
- taskParentEndedNotice,
- ),
- ).toEqual([]);
- }, 30_000);
-
it("cancels the run when the waiting turn is cancelled and lets the body clean up", async () => {
const output = captureConsoleOutput();
vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_inline");
@@ -262,11 +66,7 @@ describe("workflow tool cancellation", () => {
});
expect(output.lines).toContainEqual(expect.stringContaining(workflowSdkNotice.maxRetries));
expect(
- output.unexpected(
- workflowSdkNotice.maxRetries,
- workflowSdkNotice.unpinnedDelivery,
- taskParentEndedNotice,
- ),
+ output.unexpected(workflowSdkNotice.maxRetries, workflowSdkNotice.unpinnedDelivery),
).toEqual([]);
}, 60_000);
});
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
index ae2ad4bdf..c1d70115c 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
@@ -7,7 +7,8 @@ import {
} from "#internal/testing/events.js";
import { workflowEntry } from "#execution/session/entry.js";
import { sessionCommandHookToken } from "#execution/session-inbox/address.js";
-import { SLEEP_INPUT_SCHEMA, executeSleepTool } from "#execution/tools/sleep.js";
+import { SLEEP_INPUT_SCHEMA } from "#tools/provided/sleep.js";
+import { executeSleepTool } from "#tools/provided/sleep-workflow.js";
import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
import {
askThenRaceWorkflow,
@@ -196,6 +197,10 @@ describe("workflow tools", () => {
prompt: "Apply plan:api?",
});
expect(request.options?.map((option) => option.id)).toEqual(["approve", "cancel"]);
+ // The call is still running, so the question parks the open turn.
+ const [parked] = filterEventsByType(asked, "turn.waiting");
+ expect(asked.at(-1)).toBe(parked);
+ expect(filterEventsByType(asked, "turn.completed")).toHaveLength(0);
const commandToken = sessionCommandHookToken(run.runId);
await resumeSessionInbox(commandToken, {
@@ -204,6 +209,9 @@ describe("workflow tools", () => {
});
const answered = await stream.nextTurn();
+ expect(filterEventsByType(answered, "input.resolved")).toMatchObject([
+ { data: { resolutions: [{ outcome: "answered", requestId: request.requestId }] } },
+ ]);
const progress = answered.findIndex(
(event) =>
event.type === "action.partial" && event.data.result.output === "approval received",
@@ -221,6 +229,15 @@ describe("workflow tools", () => {
JSON.stringify({ approved: true, service: "api" }),
);
expect(filterEventsByType(answered, "turn.failed")).toHaveLength(0);
+ // The answer resumes the same turn, which completes once.
+ const turnIds = new Set(
+ answered.flatMap((event) =>
+ "data" in event && "turnId" in event.data ? [event.data.turnId] : [],
+ ),
+ );
+ expect([...turnIds]).toEqual([parked!.data.turnId]);
+ expect(filterEventsByType(answered, "turn.started")).toHaveLength(0);
+ expect(filterEventsByType(answered, "turn.completed")).toHaveLength(1);
} finally {
stream.dispose();
await run.cancel();
diff --git a/packages/eve/src/execution/tools/workflow/workflow.test.ts b/packages/eve/src/execution/tools/workflow/workflow.test.ts
index c9f698c4d..4a530c16c 100644
--- a/packages/eve/src/execution/tools/workflow/workflow.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow.test.ts
@@ -1,22 +1,21 @@
import { beforeEach, expect, it, vi } from "vitest";
-import type { TaskRunInboundPayload } from "#tasks/types.js";
-import { createBackgroundWorkflowOwner } from "#execution/tools/workflow/workflow-owner-background.js";
-import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
+import type {
+ WorkflowToolRunControlMessage,
+ WorkflowToolRunMessage,
+} from "#execution/tools/workflow/messages.js";
+import { WorkflowToolRunAsks } from "#execution/tools/workflow/ask.js";
import { workflowToolRunWorkflow } from "#execution/tools/workflow/workflow.js";
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
const mocks = vi.hoisted(() => ({
sleep: vi.fn(),
control: vi.fn(),
deliver: vi.fn(),
- executeWorkflowBody: vi.fn(),
+ runBody: vi.fn(),
openWorkflowToolRunOwnerInbox: vi.fn(),
}));
-vi.mock("#execution/tools/workflow/workflow-owner-background.js", () => ({
- createBackgroundWorkflowOwner: vi.fn(),
-}));
-
vi.mock("#compiled/@workflow/core/index.js", () => ({ sleep: mocks.sleep }));
vi.mock("#execution/tools/workflow/workflow-owner-blocking.js", () => ({
@@ -27,14 +26,12 @@ vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({ resumeHookStep
vi.mock("#execution/tools/workflow/body.js", () => ({
createWorkflowBodyRef: (input: {
callId: string;
- execution: "background" | "blocking";
input: object;
session: { turn: { id: string; sequence: number } };
stepIndex: number;
toolName: string;
}) => ({
callId: input.callId,
- execution: input.execution,
input: input.input,
runId: "run-1",
sequence: input.session.turn.sequence,
@@ -42,7 +39,10 @@ vi.mock("#execution/tools/workflow/body.js", () => ({
toolName: input.toolName,
turnId: input.session.turn.id,
}),
- executeWorkflowBody: mocks.executeWorkflowBody,
+ startWorkflowBody: (...args: unknown[]) => ({
+ close: async () => {},
+ outcome: mocks.runBody(...args),
+ }),
}));
vi.mock("#execution/tools/workflow/owner.js", () => ({
openWorkflowToolRunOwnerInbox: mocks.openWorkflowToolRunOwnerInbox,
@@ -51,10 +51,10 @@ vi.mock("#execution/tools/workflow/owner.js", () => ({
import { createChannelReader } from "#execution/tools/workflow/owner-channels.js";
const input = {
+ agentContext: {} as AgentSessionContext,
hookToken: "control",
owner: { inbox: "parent" },
callId: "call-1",
- execution: "background" as const,
input: {},
session: {
auth: { current: null, initiator: null },
@@ -69,17 +69,14 @@ const input = {
beforeEach(() => {
vi.resetAllMocks();
setControl(new AbortController());
- mocks.executeWorkflowBody.mockResolvedValue({
- outcome: { output: "done", status: "completed" },
- reportCount: 1,
- });
+ mocks.runBody.mockResolvedValue({ output: "done", status: "completed" });
});
it("emits every persisted report before the terminal outcome", async () => {
+ const invocationOwner = { send: vi.fn(), sent: 1 };
const report = {
from: {
callId: "call-1",
- execution: "background" as const,
input: {},
runId: "run-1",
sequence: 0,
@@ -91,7 +88,7 @@ it("emits every persisted report before the terminal outcome", async () => {
update: "halfway",
};
mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
- owner: { inbox: "invocation-owner" },
+ owner: invocationOwner,
reader: createChannelReader(
"workflow",
(async function* () {
@@ -108,85 +105,63 @@ it("emits every persisted report before the terminal outcome", async () => {
2,
"parent",
{
- from: expect.objectContaining({ callId: "call-1", execution: "background" }),
+ from: expect.objectContaining({ callId: "call-1" }),
kind: "outcome",
result: { output: "done", status: "completed" },
},
{ ifPresent: false },
);
- expect(mocks.executeWorkflowBody).toHaveBeenCalledWith(
- expect.objectContaining({ owner: { inbox: "invocation-owner" } }),
- expect.any(AbortSignal),
+ expect(mocks.runBody).toHaveBeenCalledWith(
+ expect.objectContaining({ owner: invocationOwner }),
+ { abortSignal: expect.any(AbortSignal), interruptSignal: expect.any(AbortSignal) },
+ expect.any(WorkflowToolRunAsks),
);
});
-for (const execution of ["blocking", "background"] as const) {
- it.each(["completed", "failed", "cancelled", "throw", "blocked"] as const)(
- `${execution} keeps cancellation final when cleanup is %s`,
- async (status) => {
- const controller = new AbortController();
- const release = Promise.withResolvers<void>();
- const started = Promise.withResolvers<void>();
- mocks.sleep.mockImplementation(async () => {
- if (status === "blocked") return;
- await new Promise<void>(() => {});
- });
- mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
- owner: { inbox: "owner" },
- reader: createChannelReader("workflow", {
- [Symbol.asyncIterator]: () => ({
- next: () => new Promise<IteratorResult<never>>(() => {}),
- }),
- }),
- });
- mocks.executeWorkflowBody.mockImplementation(async () => {
- started.resolve();
- await release.promise;
- if (status === "throw") throw new Error("cleanup failed");
- return {
- reportCount: 0,
- outcome:
- status === "failed"
- ? { status, error: "failed" }
- : status === "cancelled"
- ? { status, reason: "body cancelled" }
- : { status: "completed", output: "late success" },
- };
- });
- setControl(controller);
- const completion = workflowToolRunWorkflow({ ...input, execution });
- await started.promise;
- controller.abort(new Error("stop"));
- if (status !== "blocked") release.resolve();
- await completion;
- expect(mocks.deliver).toHaveBeenCalledExactlyOnceWith(
- "parent",
- expect.objectContaining({
- kind: "outcome",
- result: { status: "cancelled", reason: "stop" },
+it.each(["completed", "failed", "cancelled", "throw", "blocked"] as const)(
+ "keeps cancellation final when cleanup is %s",
+ async (status) => {
+ const controller = new AbortController();
+ const release = Promise.withResolvers<void>();
+ const started = Promise.withResolvers<void>();
+ mocks.sleep.mockImplementation(async () => {
+ if (status === "blocked") return;
+ await new Promise<void>(() => {});
+ });
+ mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
+ owner: { send: vi.fn(), sent: 0 },
+ reader: createChannelReader("workflow", {
+ [Symbol.asyncIterator]: () => ({
+ next: () => new Promise<IteratorResult<never>>(() => {}),
}),
- { ifPresent: true },
- );
- },
- );
-}
-
-it("does not start a body cancelled before its first read", async () => {
- const controller = new AbortController();
- controller.abort(new Error("never admitted"));
- setControl(controller);
- await workflowToolRunWorkflow(input);
- expect(mocks.deliver).toHaveBeenCalledWith(
- "parent",
- expect.objectContaining({
- result: expect.objectContaining({ status: "cancelled" }),
- }),
- { ifPresent: true },
- );
- expect(mocks.executeWorkflowBody).not.toHaveBeenCalled();
- expect(mocks.openWorkflowToolRunOwnerInbox).not.toHaveBeenCalled();
- expect(mocks.sleep).not.toHaveBeenCalled();
-});
+ }),
+ });
+ mocks.runBody.mockImplementation(async () => {
+ started.resolve();
+ await release.promise;
+ if (status === "throw") throw new Error("cleanup failed");
+ return status === "failed"
+ ? { status, error: "failed" }
+ : status === "cancelled"
+ ? { status, reason: "body cancelled" }
+ : { status: "completed", output: "late success" };
+ });
+ setControl(controller);
+ const completion = workflowToolRunWorkflow(input);
+ await started.promise;
+ controller.abort(new Error("stop"));
+ if (status !== "blocked") release.resolve();
+ await completion;
+ expect(mocks.deliver).toHaveBeenCalledExactlyOnceWith(
+ "parent",
+ expect.objectContaining({
+ kind: "outcome",
+ result: { status: "cancelled", reason: "stop" },
+ }),
+ { ifPresent: true },
+ );
+ },
+);
it("preserves the pending inbox read across cancellation and drains the report before settling", async () => {
const controller = new AbortController();
@@ -195,7 +170,6 @@ it("preserves the pending inbox read across cancellation and drains the report b
const report: WorkflowToolRunMessage = {
from: {
callId: input.callId,
- execution: input.execution,
input: input.input,
runId: "run-1",
sequence: 0,
@@ -208,7 +182,7 @@ it("preserves the pending inbox read across cancellation and drains the report b
};
mocks.sleep.mockReturnValue(new Promise<void>(() => {}));
mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
- owner: { inbox: "owner" },
+ owner: { send: vi.fn(), sent: 1 },
reader: createChannelReader("workflow", { [Symbol.asyncIterator]: () => ({ next }) }),
});
setControl(controller);
@@ -234,7 +208,7 @@ it("preserves the pending inbox read across cancellation and drains the report b
function setControl(controller: AbortController) {
const { signal } = controller;
mocks.control.mockReturnValue({
- kind: "turn",
+ interruptSignal: new AbortController().signal,
signal,
commands: createChannelReader(
"control",
@@ -259,18 +233,16 @@ it("applies cancellation buffered during the last report delivery before publish
const controller = new AbortController();
const cancel = Promise.withResolvers<void>();
const commands = createChannelReader(
- "commands",
- (async function* (): AsyncGenerator<TaskRunInboundPayload> {
- yield { kind: "task-command", command: { kind: "ready" } };
+ "control",
+ (async function* (): AsyncGenerator<WorkflowToolRunControlMessage> {
await cancel.promise;
- yield { kind: "task-command", command: { kind: "cancel" } };
+ yield { kind: "cancel", reason: "stop" };
await new Promise<void>(() => {});
})(),
);
const report: WorkflowToolRunMessage = {
from: {
callId: input.callId,
- execution: input.execution,
input: {},
runId: "run-1",
sequence: 0,
@@ -287,20 +259,16 @@ it("applies cancellation buffered during the last report delivery before publish
await vi.waitFor(() => expect(commands.landed).toHaveLength(1));
}
});
- vi.mocked(createBackgroundWorkflowOwner).mockResolvedValue({
- kind: "session",
+ mocks.control.mockReturnValue({
+ interruptSignal: new AbortController().signal,
commands,
signal: controller.signal,
handleMessage: deliver,
- async handleCommand(payload) {
- if (payload.kind !== "task-command") return;
- if (payload.command.kind === "ready") return "start";
- if (payload.command.kind === "cancel") controller.abort(new Error("stop"));
- },
+ handleCommand: () => controller.abort(new Error("stop")),
});
mocks.sleep.mockReturnValue(new Promise<void>(() => {}));
mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
- owner: { inbox: "owner" },
+ owner: { send: vi.fn(), sent: 1 },
reader: createChannelReader(
"workflow",
(async function* () {
@@ -310,12 +278,7 @@ it("applies cancellation buffered during the last report delivery before publish
})(),
),
});
- await workflowToolRunWorkflow({
- workflow: input,
- initialView: { status: "working", taskId: "task", metadata: { kind: "tool", name: "worker" } },
- taskInboxToken: "commands",
- parentContinuationToken: "parent",
- });
+ await workflowToolRunWorkflow(input);
expect(deliver).toHaveBeenNthCalledWith(1, report);
expect(deliver).toHaveBeenNthCalledWith(
2,
@@ -329,18 +292,15 @@ it("applies cancellation buffered during the last report delivery before publish
it("keeps waiting for the body after the control hook closes", async () => {
mocks.control.mockReturnValue({
- kind: "turn",
+ interruptSignal: new AbortController().signal,
signal: new AbortController().signal,
commands: createChannelReader("control", (async function* () {})()),
handleCommand: vi.fn(),
handleMessage: mocks.deliver,
});
- mocks.executeWorkflowBody.mockResolvedValue({
- reportCount: 0,
- outcome: { status: "completed", output: "done" },
- });
+ mocks.runBody.mockResolvedValue({ status: "completed", output: "done" });
mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
- owner: { inbox: "owner" },
+ owner: { send: vi.fn(), sent: 0 },
reader: createChannelReader("workflow", {
[Symbol.asyncIterator]: () => ({
next: () => new Promise<IteratorResult<WorkflowToolRunMessage>>(() => {}),
@@ -357,12 +317,9 @@ it("keeps waiting for the body after the control hook closes", async () => {
});
it("propagates terminal delivery failure instead of replacing the invocation outcome", async () => {
- mocks.executeWorkflowBody.mockResolvedValue({
- reportCount: 0,
- outcome: { status: "completed", output: "done" },
- });
+ mocks.runBody.mockResolvedValue({ status: "completed", output: "done" });
mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
- owner: { inbox: "owner" },
+ owner: { send: vi.fn(), sent: 0 },
reader: createChannelReader("workflow", {
[Symbol.asyncIterator]: () => ({
next: () => new Promise<IteratorResult<WorkflowToolRunMessage>>(() => {}),
diff --git a/packages/eve/src/execution/tools/workflow/workflow.ts b/packages/eve/src/execution/tools/workflow/workflow.ts
index 6c40703b7..257bbaa83 100644
--- a/packages/eve/src/execution/tools/workflow/workflow.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow.ts
@@ -1,144 +1,112 @@
import { WORKFLOW_CANCELLATION_CLEANUP_MS } from "#execution/tools/workflow/cancellation-policy.js";
import { sleep } from "#compiled/@workflow/core/index.js";
import { normalizeSerializableError } from "#execution/workflow-errors.js";
+import { createWorkflowBodyRef, startWorkflowBody } from "#execution/tools/workflow/body.js";
+import { WorkflowToolRunAsks } from "#execution/tools/workflow/ask.js";
import {
- createWorkflowBodyRef,
- executeWorkflowBody,
- type WorkflowBodyResult,
-} from "#execution/tools/workflow/body.js";
-import type { WorkflowToolRunOutcome } from "#execution/tools/workflow/messages.js";
+ isWorkflowToolRunAskDecision,
+ isWorkflowToolRunControlMessage,
+ type WorkflowToolRunOutcome,
+} from "#execution/tools/workflow/messages.js";
import {
createChannelReader,
raceChannelReads,
type ChannelReader,
} from "#execution/tools/workflow/owner-channels.js";
+import { openWorkflowToolRunOwnerInbox } from "#execution/tools/workflow/owner.js";
import {
- openWorkflowToolRunOwnerInbox,
- type WorkflowToolRunOwnerInbox,
-} from "#execution/tools/workflow/owner.js";
-import { createBackgroundWorkflowOwner } from "#execution/tools/workflow/workflow-owner-background.js";
-import { createBlockingWorkflow } from "#execution/tools/workflow/workflow-owner-blocking.js";
-import type {
- BackgroundWorkflowToolRunInput,
- WorkflowToolRunInput,
-} from "#execution/tools/workflow/types.js";
+ createBlockingWorkflow,
+ type BlockingWorkflowOwner,
+} from "#execution/tools/workflow/workflow-owner-blocking.js";
+import type { WorkflowToolRunInput } from "#execution/tools/workflow/types.js";
-/** Owns admission, command intake, body execution, and settlement for either lifetime. */
-export async function workflowToolRunWorkflow(
- input: WorkflowToolRunInput | BackgroundWorkflowToolRunInput,
-): Promise<void> {
+/** Owns command intake, body execution, and settlement for one workflow tool call. */
+export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Promise<void> {
"use workflow";
- const owner =
- "workflow" in input
- ? await createBackgroundWorkflowOwner(input)
- : createBlockingWorkflow(input);
- if (owner === undefined) return;
- const definition =
- "workflow" in input
- ? { ...input.workflow, execution: "background" as const }
- : { ...input, execution: input.execution ?? "blocking" };
+ const asks = new WorkflowToolRunAsks(createWorkflowBodyRef(input).runId);
+ const owner = createBlockingWorkflow(input, asks);
const { signal } = owner;
- let admitted = owner.kind === "turn";
+ const inbox = openWorkflowToolRunOwnerInbox();
+ const started = startWorkflowBody(
+ { ...input, owner: inbox.owner },
+ { abortSignal: signal, interruptSignal: owner.interruptSignal },
+ asks,
+ );
+ const body: ChannelReader<"body", WorkflowToolRunOutcome> = createChannelReader(
+ "body",
+ awaitBodyOutcome(started.outcome),
+ );
let commandsOpen = true;
- let body:
- | {
- readonly inbox: WorkflowToolRunOwnerInbox;
- readonly reader: ChannelReader<"body", WorkflowBodyResult>;
- }
- | undefined;
- let consumedReports = 0;
- let bodyResult: WorkflowBodyResult | undefined;
+ let relayedMessages = 0;
+ let bodyOutcome: WorkflowToolRunOutcome | undefined;
let cleanupDeadline: Promise<"cancel"> | undefined;
let outcome: WorkflowToolRunOutcome | undefined;
- while (true) {
- if (admitted && signal.aborted) {
- if (body === undefined) break;
- cleanupDeadline ??= sleep(WORKFLOW_CANCELLATION_CLEANUP_MS).then(() => "cancel");
- }
- if (
- // Wait for the body to produce its final outcome.
- bodyResult !== undefined &&
- // Persisted reports must also finish delivery before settlement.
- consumedReports >= bodyResult.reportCount &&
- // Handle buffered commands, especially cancellation, before publishing the outcome.
- owner.commands.landed.length === 0 &&
- // Propagate a command-read failure instead of hiding it behind completion.
- owner.commands.failure === undefined
- ) {
- outcome = bodyResult.outcome;
- break;
- }
- let read;
- try {
- if (admitted && body === undefined) {
- const inbox = openWorkflowToolRunOwnerInbox();
- body = {
- inbox,
- reader: createChannelReader(
- "body",
- awaitBodyResult(executeWorkflowBody({ ...definition, owner: inbox.owner }, signal)),
- ),
- };
+ // Close the body on every exit: a relay throws once the calling session's
+ // inbox is gone, which is exactly when what the body opened must stop.
+ try {
+ while (true) {
+ if (signal.aborted) {
+ cleanupDeadline ??= sleep(WORKFLOW_CANCELLATION_CLEANUP_MS).then(() => "cancel");
+ }
+ if (
+ // Wait for the body to produce its final outcome.
+ bodyOutcome !== undefined &&
+ // Everything the body sent must be relayed before settlement.
+ relayedMessages >= inbox.owner.sent &&
+ // Handle buffered commands, especially cancellation, before publishing the outcome.
+ owner.commands.landed.length === 0 &&
+ // Propagate a command-read failure instead of hiding it behind completion.
+ owner.commands.failure === undefined
+ ) {
+ outcome = bodyOutcome;
+ break;
}
- const readers: Array<
- | typeof owner.commands
- | WorkflowToolRunOwnerInbox["reader"]
- | ChannelReader<"body", WorkflowBodyResult>
- > = [];
- if (commandsOpen) readers.push(owner.commands);
- if (body !== undefined) {
- readers.push(body.inbox.reader);
- if (bodyResult === undefined) readers.push(body.reader);
+ let read;
+ try {
+ const readers: Array<
+ | typeof owner.commands
+ | typeof inbox.reader
+ | ChannelReader<"body", WorkflowToolRunOutcome>
+ > = [];
+ if (commandsOpen) readers.push(owner.commands);
+ readers.push(inbox.reader);
+ if (bodyOutcome === undefined) readers.push(body);
+ read = await raceChannelReads(readers, cleanupDeadline);
+ } catch (error) {
+ if (owner.commands.failure !== undefined) throw error;
+ outcome = { status: "failed", error: normalizeSerializableError(error) };
+ break;
+ }
+ if (read === "cancel") break;
+ if (read.next.done) {
+ if (read.channel === "control") {
+ commandsOpen = false;
+ continue;
+ }
+ if (read.channel === "body") {
+ outcome = { status: "failed", error: "Workflow body ended without an outcome." };
+ break;
+ }
+ if (signal.aborted) break;
+ return;
}
- read = await raceChannelReads(readers, cleanupDeadline);
- } catch (error) {
- if (owner.commands.failure !== undefined) throw error;
- outcome = { status: "failed", error: normalizeSerializableError(error) };
- break;
- }
- if (read === "cancel") break;
- if (read.next.done) {
if (read.channel === "control") {
- commandsOpen = false;
+ applyControlMessage(owner, asks, read.next.value);
continue;
}
if (read.channel === "body") {
- outcome = { status: "failed", error: "Workflow body ended without an outcome." };
- break;
- }
- if (admitted && signal.aborted) break;
- return;
- }
- if (read.channel === "control") {
- if (owner.kind !== "turn")
- throw new Error("Session-owned workflow run received a turn command.");
- owner.handleCommand(read.next.value);
- continue;
- }
- if (read.channel === "commands") {
- if (owner.kind !== "session")
- throw new Error("Turn-owned workflow run received a task command.");
- const payload = read.next.value;
- if (
- admitted &&
- payload.kind === "task-command" &&
- (payload.command.kind === "ready" || payload.command.kind === "reject-dispatch")
- )
+ bodyOutcome = read.next.value;
continue;
- const action = await owner.handleCommand(payload);
- if (action === "stop") return;
- if (action === "start") admitted = true;
- continue;
- }
- if (read.channel === "body") {
- bodyResult = read.next.value;
- continue;
+ }
+ const message = read.next.value;
+ if (message.kind === "outcome") continue;
+ relayedMessages += 1;
+ await owner.handleMessage(message);
}
- if (read.next.value.kind === "outcome") continue;
- if (read.next.value.kind === "report") consumedReports += 1;
- await owner.handleMessage(read.next.value);
+ } finally {
+ await started.close();
}
// Cleanup cannot undo cancellation, even when the body returns success.
if (signal.aborted) {
@@ -149,15 +117,33 @@ export async function workflowToolRunWorkflow(
}
if (outcome !== undefined) {
await owner.handleMessage({
- from: createWorkflowBodyRef(definition),
+ from: createWorkflowBodyRef(input),
kind: "outcome",
result: outcome,
});
}
}
-async function* awaitBodyResult(
- result: Promise<WorkflowBodyResult>,
-): AsyncGenerator<WorkflowBodyResult> {
- yield await result;
+/**
+ * Applies one message from the run's control hook. Decisions on questions and
+ * commands share the hook, so the body sees them in the order the session
+ * made them.
+ */
+function applyControlMessage(
+ owner: BlockingWorkflowOwner,
+ asks: WorkflowToolRunAsks,
+ message: unknown,
+): void {
+ if (!isWorkflowToolRunControlMessage(message)) return;
+ if (isWorkflowToolRunAskDecision(message)) {
+ asks.settle(message);
+ return;
+ }
+ owner.handleCommand(message);
+}
+
+async function* awaitBodyOutcome(
+ outcome: Promise<WorkflowToolRunOutcome>,
+): AsyncGenerator<WorkflowToolRunOutcome> {
+ yield await outcome;
}
diff --git a/packages/eve/src/execution/workflow-callback-url.test.ts b/packages/eve/src/execution/workflow-callback-url.test.ts
index 6a53fc7ce..08976c3ed 100644
--- a/packages/eve/src/execution/workflow-callback-url.test.ts
+++ b/packages/eve/src/execution/workflow-callback-url.test.ts
@@ -1,7 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
- createRemoteTaskInputCallbackUrl,
createWorkflowCallbackUrl,
resolveVercelProductionCallbackBaseUrl,
resolveWorkflowCallbackBaseUrl,
@@ -135,41 +134,3 @@ describe("createWorkflowCallbackUrl", () => {
);
});
});
-
-describe("createRemoteTaskInputCallbackUrl", () => {
- afterEach(() => {
- vi.unstubAllEnvs();
- });
-
- it("adds the bypass only for the current Vercel deployment host", () => {
- vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "secret");
- vi.stubEnv("VERCEL_URL", "current-deployment.vercel.app");
-
- expect(
- createRemoteTaskInputCallbackUrl(
- "https://current-deployment.vercel.app",
- "/eve/v1/task-input/token",
- ),
- ).toBe(
- "https://current-deployment.vercel.app/eve/v1/task-input/token?x-vercel-protection-bypass=secret",
- );
- });
-
- it("does not disclose the bypass to an external remote host", () => {
- vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "secret");
- vi.stubEnv("VERCEL_URL", "current-deployment.vercel.app");
-
- expect(
- createRemoteTaskInputCallbackUrl("https://remote.example", "/eve/v1/task-input/token"),
- ).toBe("https://remote.example/eve/v1/task-input/token");
- });
-
- it("does not add the Vercel bypass to loopback HTTP", () => {
- vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "secret");
- vi.stubEnv("VERCEL_URL", "127.0.0.1");
-
- expect(
- createRemoteTaskInputCallbackUrl("http://127.0.0.1:3000", "/eve/v1/task-input/token"),
- ).toBe("http://127.0.0.1:3000/eve/v1/task-input/token");
- });
-});
diff --git a/packages/eve/src/execution/workflow-callback-url.ts b/packages/eve/src/execution/workflow-callback-url.ts
index fa8317cc8..0a061b4cb 100644
--- a/packages/eve/src/execution/workflow-callback-url.ts
+++ b/packages/eve/src/execution/workflow-callback-url.ts
@@ -7,11 +7,6 @@ import {
const PRODUCTION_ENVIRONMENT = "production";
const VERCEL_PROTECTION_BYPASS_QUERY = "x-vercel-protection-bypass";
const WORKFLOW_LOCAL_BASE_URL_ENV = "WORKFLOW_LOCAL_BASE_URL";
-const VERCEL_CALLBACK_HOST_ENVS = [
- "VERCEL_URL",
- "VERCEL_BRANCH_URL",
- "VERCEL_PROJECT_PRODUCTION_URL",
-] as const;
/**
* Workflow metadata is deployment-specific, so on Vercel it can point at
@@ -75,22 +70,3 @@ export function createWorkflowCallbackUrl(baseUrl: string, callbackPath: string)
return url.toString();
}
-
-/**
- * Builds a callback to a remote task child without disclosing this deployment's
- * protection bypass secret to an authored external origin.
- */
-export function createRemoteTaskInputCallbackUrl(baseUrl: string, callbackPath: string): string {
- const callback = new URL(callbackPath, "http://eve.local");
- const url = new URL(baseUrl);
- url.pathname = joinEveRoutePath(url.pathname, callback.pathname);
- url.search = callback.search;
- const bypassSecret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();
- const isCurrentVercelHost = VERCEL_CALLBACK_HOST_ENVS.some(
- (name) => process.env[name]?.trim().toLowerCase() === url.hostname.toLowerCase(),
- );
- if (bypassSecret && url.protocol === "https:" && isCurrentVercelHost) {
- url.searchParams.set(VERCEL_PROTECTION_BYPASS_QUERY, bypassSecret);
- }
- return url.toString();
-}
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 0911be8ad..76b1fd9c8 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -946,22 +946,6 @@ 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" },
- 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 68a473eb6..d0e755710 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -211,9 +211,7 @@ export function createWorkflowRuntime(config: {
ownerDeploymentId: await resolveCurrentWorkflowDeploymentId(),
serializedContext,
};
- const taskId = input.taskId ?? input.callback?.taskId;
if (input.limits !== undefined) workflowInput.limits = input.limits;
- if (taskId !== undefined) workflowInput.taskId = taskId;
if (collectorRunId !== undefined) {
workflowInput.activityCollectorRunId = collectorRunId;
}
@@ -293,7 +291,7 @@ export function createWorkflowRuntime(config: {
async dispatchSession<TCommand extends SessionCommand>(
input: DispatchSessionInput<TCommand>,
): Promise<SessionCommandResult<TCommand>> {
- return await dispatchWorkflowCommand({ sessionId: input.sessionId }, input.command);
+ return await dispatchWorkflowSessionCommand(input);
},
async getEventStream(
@@ -454,15 +452,18 @@ function inactiveCommandResult<TCommand extends SessionCommand>(
return result as SessionCommandResult<TCommand>;
}
+/** Sends one command to a session through its stable command inbox. */
+export async function dispatchWorkflowSessionCommand<TCommand extends SessionCommand>(
+ input: DispatchSessionInput<TCommand>,
+): Promise<SessionCommandResult<TCommand>> {
+ return await dispatchWorkflowCommand({ sessionId: input.sessionId }, input.command);
+}
+
/** Requests cancellation through a session's stable command inbox. */
export async function requestWorkflowTurnCancellation(
input: CancelTurnInput,
): Promise<CancelTurnResult> {
- const command: { kind: "cancel"; taskId?: string; tasks?: boolean; turnId?: string } = {
- kind: "cancel",
- };
- if (input.taskId !== undefined) command.taskId = input.taskId;
- if (input.tasks !== undefined) command.tasks = input.tasks;
+ const command: { kind: "cancel"; turnId?: string } = { kind: "cancel" };
if (input.turnId !== undefined) command.turnId = input.turnId;
return await dispatchWorkflowCommand({ sessionId: input.sessionId }, command);
}
diff --git a/packages/eve/src/framework/sources/registry.ts b/packages/eve/src/framework/sources/registry.ts
index 0943e1e53..4b8aee491 100644
--- a/packages/eve/src/framework/sources/registry.ts
+++ b/packages/eve/src/framework/sources/registry.ts
@@ -45,10 +45,6 @@ const localDefaults = defineProgrammaticAgentSource({
logicalPath: "tools/connection_search.ts",
loadNamespace: () => import("#tools/framework/connection-search.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"),
diff --git a/packages/eve/src/harness/advertised-tools.test.ts b/packages/eve/src/harness/advertised-tools.test.ts
index f192d8dbc..fd842feef 100644
--- a/packages/eve/src/harness/advertised-tools.test.ts
+++ b/packages/eve/src/harness/advertised-tools.test.ts
@@ -85,42 +85,12 @@ describe("getAdvertisedTools for definition arrays", () => {
const tools = new Map([
["add", createTool("add")],
["root_only", createAvailableTool("root_only", ["root-session"])],
- ["child_only", createAvailableTool("child_only", ["delegated-task-child"])],
]) satisfies HarnessToolMap;
const advertisedTools = getAdvertisedTools({ session: {}, tools });
expect([...advertisedTools.keys()]).toEqual(["add", "root_only"]);
});
-
- it("exposes delegated-task-child tools from persisted session ownership", () => {
- const tools = new Map([
- ["add", createTool("add")],
- ["root_only", createAvailableTool("root_only", ["root-session"])],
- ["child_only", createAvailableTool("child_only", ["delegated-task-child"])],
- ]) satisfies HarnessToolMap;
-
- const advertisedTools = getAdvertisedTools({
- session: { rootSessionId: "root-session", taskId: "task-1" },
- tools,
- });
-
- expect([...advertisedTools.keys()]).toEqual(["add", "child_only"]);
- });
-
- it.each([{}, { rootSessionId: "root-session" }])(
- "removes delegated-task-child tools from sessions without task ownership (%j)",
- (session) => {
- const tools = new Map([
- ["add", createTool("add")],
- ["child_only", createAvailableTool("child_only", ["delegated-task-child"])],
- ]) satisfies HarnessToolMap;
-
- const advertisedTools = getAdvertisedTools({ session, tools });
-
- expect([...advertisedTools.keys()]).toEqual(["add"]);
- },
- );
});
function createTool(name: string): HarnessToolDefinition {
diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.ts
index 3385069d6..1c3003e12 100644
--- a/packages/eve/src/harness/advertised-tools.ts
+++ b/packages/eve/src/harness/advertised-tools.ts
@@ -2,7 +2,7 @@ import type { ToolSet } from "ai";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import type { HarnessSession, HarnessToolMap } from "#harness/types.js";
-type AdvertisedToolSession = Pick<HarnessSession, "rootSessionId" | "taskId">;
+type AdvertisedToolSession = Pick<HarnessSession, "rootSessionId">;
type AdvertisedToolMapInput = {
readonly session: AdvertisedToolSession;
@@ -104,10 +104,6 @@ function shouldHideTool(
) {
return delegated;
}
- if (definition.behavior?.availability.includes("delegated-task-child") === true) {
- return session.taskId === undefined;
- }
-
return false;
}
diff --git a/packages/eve/src/harness/background-tools.ts b/packages/eve/src/harness/background-tools.ts
deleted file mode 100644
index 1be2bac92..000000000
--- a/packages/eve/src/harness/background-tools.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { loadContext } from "#context/container.js";
-import { ContextKey } from "#context/key.js";
-import type { InternalToolLabelDefinition, ToolExecuteOptions } from "#tools/definition.js";
-import type { AgentView } from "#subagents/handles/prompt.js";
-import type { JsonValue } from "#shared/json.js";
-
-export interface BackgroundExecutableTool {
- readonly label?: InternalToolLabelDefinition;
- readonly executeInput?: (input: unknown) => JsonValue;
- readonly name: string;
- /** Selected agent definition's runtime graph ID; absent for authored workflow tools. */
- readonly nodeId?: string;
-
- /** Registered durable workflow body run by the session-owned task. */
- readonly workflowId: string;
-}
-
-export interface BackgroundToolCall {
- readonly callId: string;
- readonly definition: BackgroundExecutableTool;
- readonly input: unknown;
-}
-
-export interface BackgroundToolCallBatch {
- readonly calls: readonly BackgroundToolCall[];
- register(call: {
- readonly callId: string;
- readonly input: unknown;
- readonly toolName: string;
- }): void;
- setTool(name: string, definition?: BackgroundExecutableTool): void;
-}
-
-export interface BackgroundToolExecutor {
- hasPendingTasks?(): boolean;
- readAgentViews?(): Promise<readonly AgentView[]>;
- execute(input: {
- readonly batch: BackgroundToolCallBatch;
- readonly definition: BackgroundExecutableTool;
- readonly options: ToolExecuteOptions;
- readonly toolInput: unknown;
- }): Promise<unknown>;
-}
-
-// 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, 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).
-// 3. "No task runtime active" stays a runtime condition instead of a link-time one:
-// tool sets can be built anywhere, and `require()` only throws if a background
-// call actually fires outside a task step.
-export const BackgroundToolExecutorKey = new ContextKey<BackgroundToolExecutor>(
- "eve.internal.backgroundToolExecution",
-);
-
-export function createBackgroundToolCallBatch(): BackgroundToolCallBatch {
- const calls: BackgroundToolCall[] = [];
- const callsById = new Map<string, BackgroundToolCall>();
- const tools = new Map<string, BackgroundExecutableTool>();
- return {
- calls,
- register(call) {
- const definition = tools.get(call.toolName);
- if (definition === undefined) return;
-
- const existing = callsById.get(call.callId);
- if (existing?.definition === definition) return;
- if (existing !== undefined) {
- throw new Error(`Background tool call "${call.callId}" was registered more than once.`);
- }
-
- const registeredCall = { callId: call.callId, definition, input: call.input };
- callsById.set(call.callId, registeredCall);
- calls.push(registeredCall);
- },
- setTool(name, definition) {
- if (definition === undefined) {
- tools.delete(name);
- } else {
- tools.set(name, definition);
- }
- },
- };
-}
-
-export async function executeBackgroundToolCall(input: {
- readonly batch: BackgroundToolCallBatch;
- readonly definition: BackgroundExecutableTool;
- readonly options: ToolExecuteOptions;
- readonly toolInput: unknown;
-}): Promise<unknown> {
- return await loadContext().require(BackgroundToolExecutorKey).execute(input);
-}
diff --git a/packages/eve/src/harness/compaction.test.ts b/packages/eve/src/harness/compaction.test.ts
index 2625cd4c2..f1f803fc7 100644
--- a/packages/eve/src/harness/compaction.test.ts
+++ b/packages/eve/src/harness/compaction.test.ts
@@ -758,7 +758,7 @@ describe("compactMessages: forced summary", () => {
const messages = [
user("Keep the original request."),
assistant("Work is in progress."),
- user("A background task completed."),
+ user("A scheduled report completed."),
];
const original = structuredClone(messages);
diff --git a/packages/eve/src/harness/coordination.test.ts b/packages/eve/src/harness/coordination.test.ts
index 4a517b684..c391a7737 100644
--- a/packages/eve/src/harness/coordination.test.ts
+++ b/packages/eve/src/harness/coordination.test.ts
@@ -27,6 +27,8 @@ import type { HarnessSession } from "#harness/types.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import { isRuntimeWorkflowToolAction } from "#shared/action-types.js";
+const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };
+
const CHILD_SESSION_ID = "local-child-123456789012";
const CHILD_CONTINUATION_TOKEN = "subagent:private-token";
const ZERO_USAGE = {
@@ -248,42 +250,12 @@ describe("createCoordinationRequestFromToolCall", () => {
]),
}),
).toEqual({
- kind: "task",
- request: {
- callId: "call-1",
- executeInput: undefined,
- input: { message: "research this" },
- kind: "workflow-task",
- toolName: "researcher",
- workflowId: "workflow://subagent-tool",
- },
- });
- });
-
- it("reserves runtime actions for task controls", () => {
- expect(
- createCoordinationRequestFromToolCall({
- toolCall: { ...toolCall, input: { taskIds: ["task-1"] }, toolName: "task_cancel" },
- tools: new Map([
- [
- "task_cancel",
- {
- description: "Cancel tasks.",
- inputSchema: jsonSchema({ type: "object" }),
- name: "task_cancel",
- runtimeAction: { kind: "task-control" as const },
- },
- ],
- ]),
- }),
- ).toEqual({
- kind: "runtime-action",
- request: {
- callId: "call-1",
- input: { taskIds: ["task-1"] },
- kind: "tool-call",
- toolName: "task_cancel",
- },
+ callId: "call-1",
+ executeInput: undefined,
+ input: { message: "research this" },
+ kind: "workflow-task",
+ toolName: "researcher",
+ workflowId: "workflow://subagent-tool",
});
});
});
@@ -312,7 +284,6 @@ function createParkedSession(): HarnessSession {
});
return setPendingCoordinationBatch({
- runtimeActions: [],
tasks: [
{
callId: "call-1",
@@ -342,7 +313,6 @@ describe("coordination batch identity", () => {
expect(() =>
setPendingCoordinationBatch({
- runtimeActions: [],
tasks: [task, { ...task, toolName: "other" }],
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
@@ -379,43 +349,6 @@ function createSessionWithRunningChild(): HarnessSession {
}
describe("resolvePendingCoordination", () => {
- it("does not emit subagent completion for a working task receipt", async () => {
- const events: UnstampedMessageStreamEvent[] = [];
- const taskId = "task_0123456789abcdef";
-
- const resolved = await resolvePendingCoordination({
- emit: async (event) => {
- events.push(event);
- },
- session: createParkedSession(),
- stepInput: {
- runtimeActionResults: [
- {
- backgroundTask: { status: "working", taskId },
- callId: "call-1",
- kind: "subagent-result",
- origin: "child",
- outcome: {
- kind: "parked",
- result: { kind: "succeeded", output: "delegated" },
- usageDelta: ZERO_USAGE,
- },
- output: {
- agentId: deriveAgentId("researcher", OPERATION_ID),
- status: "working",
- taskId,
- },
- subagentName: "researcher",
- },
- ],
- },
- });
-
- expect(events.some((event) => event.type === "subagent.completed")).toBe(false);
- expect(events).toContainEqual(expect.objectContaining({ type: "action.result" }));
- expect(getAgentHandleStore(resolved.session.state)).toBeUndefined();
- });
-
it("settles the running handle terminally and deletes it with the batch", async () => {
const session = createSessionWithRunningChild();
@@ -501,7 +434,14 @@ describe("resolvePendingCoordination", () => {
it("clears the child's proxy-input entries before settling its handle", async () => {
const session = upsertProxyInputRequests({
entries: [
- ["request-1", { childContinuationToken: CHILD_CONTINUATION_TOKEN, kind: "question" }],
+ [
+ "request-1",
+ {
+ childContinuationToken: CHILD_CONTINUATION_TOKEN,
+ event: REQUEST_EVENT,
+ kind: "question",
+ },
+ ],
],
forChildContinuationToken: CHILD_CONTINUATION_TOKEN,
session: createSessionWithRunningChild(),
@@ -535,7 +475,6 @@ describe("resolvePendingCoordination", () => {
const parked = setPendingCoordinationBatch({
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
- runtimeActions: [],
session: createParkedSession(),
tasks: [
{
@@ -550,14 +489,20 @@ describe("resolvePendingCoordination", () => {
const withRun = registerWorkflowToolRun(parked, {
callId: "call-1",
toolName: "deploy",
- lifetime: "turn" as const,
origin: { turnId: "turn_0", stepIndex: 0 },
address: { runId: "run-1", hookToken: "eve:workflow-tool-run:op-1" },
});
const answerToken = "eve:workflow-tool-run-answer:run-1:0";
const session = upsertProxyInputRequests({
entries: [
- ["other-request", { childContinuationToken: CHILD_CONTINUATION_TOKEN, kind: "question" }],
+ [
+ "other-request",
+ {
+ childContinuationToken: CHILD_CONTINUATION_TOKEN,
+ event: REQUEST_EVENT,
+ kind: "question",
+ },
+ ],
],
forChildContinuationToken: CHILD_CONTINUATION_TOKEN,
session: upsertProxyInputRequests({
@@ -565,8 +510,9 @@ describe("resolvePendingCoordination", () => {
[
answerToken,
{
- answerHook: { runId: "run-1" },
+ workflowAsk: { control: "control", question: {}, runId: "run-1" },
childContinuationToken: answerToken,
+ event: REQUEST_EVENT,
kind: "question",
},
],
@@ -594,7 +540,6 @@ describe("resolvePendingCoordination", () => {
const parked = setPendingCoordinationBatch({
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
- runtimeActions: [],
session: createParkedSession(),
tasks: [
{
@@ -773,7 +718,6 @@ describe("resolvePendingCoordination", () => {
// A terminal failure on the follow-up turn deletes the handle.
const secondBatch = setPendingCoordinationBatch({
- runtimeActions: [],
tasks: [
{
callId: "call-2",
@@ -892,7 +836,6 @@ describe("resolvePendingCoordination", () => {
},
} as HarnessSession;
const secondBatch = setPendingCoordinationBatch({
- runtimeActions: [],
tasks: [
{
callId: "call-2",
diff --git a/packages/eve/src/harness/coordination.ts b/packages/eve/src/harness/coordination.ts
index 9c5a69d0b..eb8f2f569 100644
--- a/packages/eve/src/harness/coordination.ts
+++ b/packages/eve/src/harness/coordination.ts
@@ -5,7 +5,6 @@ import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.
import type {
RuntimeActionRequest,
RuntimeActionResult,
- RuntimeToolCallActionRequest,
RuntimeWorkflowTaskRequest,
} from "#shared/action-types.js";
import { markRuntimeWorkflowToolAction } from "#shared/action-types.js";
@@ -71,8 +70,6 @@ interface PendingCoordinationEventMetadata {
* authority for continuing, settling, and cancelling children.
*/
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;
@@ -102,7 +99,6 @@ export function getPendingCoordinationBatch(
const batch = value as PendingCoordinationBatch;
if (
- !Array.isArray(batch.runtimeActions) ||
!Array.isArray(batch.tasks) ||
!Array.isArray(batch.responseMessages) ||
typeof batch.event !== "object" ||
@@ -127,17 +123,15 @@ export function clearPendingCoordinationBatch(session: HarnessSession): HarnessS
* Stores one pending coordination batch on the session.
*/
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 {
- assertUniqueCoordinationCallIds([...input.runtimeActions, ...input.tasks]);
+ assertUniqueCoordinationCallIds(input.tasks);
const state = { ...input.session.state };
state[PENDING_COORDINATION_BATCH_KEY] = {
- runtimeActions: [...input.runtimeActions],
tasks: [...input.tasks],
event: input.event,
localFanoutSize: input.localFanoutSize,
@@ -188,9 +182,7 @@ function resolveResultsForCoordinationBatch(input: {
readonly state: SessionStateMap | undefined;
}): RuntimeActionResult[] | undefined {
return resolveRuntimeActionResultsForCallIds({
- pendingCallIds: [...input.batch.runtimeActions, ...input.batch.tasks].map(
- (request) => request.callId,
- ),
+ pendingCallIds: input.batch.tasks.map((request) => request.callId),
results: input.results.filter((result) => isResultBoundToRunningHandle(input.state, result)),
});
}
@@ -246,11 +238,6 @@ export async function resolvePendingCoordination(input: {
if (result.kind !== "subagent-result" || result.origin !== "child") {
continue;
}
- // A background receipt confirms task admission, not child-turn settlement.
- // The task snapshot later carries the actual parked/terminal outcome.
- if (readBackgroundTaskReceipt(result) !== undefined) {
- continue;
- }
const handle = findRunningAgentHandle(nextSession.state, { callId: result.callId });
if (handle === undefined) {
continue;
@@ -283,7 +270,7 @@ export async function resolvePendingCoordination(input: {
nextSession = removeBlockingWorkflowToolRuns(
clearProxyInputRequestsWhere(
nextSession,
- (route) => route.answerHook?.runId === record.address.runId,
+ (route) => route.workflowAsk?.runId === record.address.runId,
),
batch.event.turnId,
record.callId,
@@ -326,8 +313,7 @@ export async function resolvePendingCoordination(input: {
if (
result.kind === "subagent-result" &&
result.origin === "child" &&
- result.outcome.result.kind === "succeeded" &&
- readBackgroundTaskReceipt(result) === undefined
+ result.outcome.result.kind === "succeeded"
) {
const data = {
callId: result.callId,
@@ -398,12 +384,6 @@ export async function resolvePendingCoordination(input: {
};
}
-function readBackgroundTaskReceipt(
- result: Extract<RuntimeActionResult, { kind: "subagent-result" }>,
-): { readonly status: "working"; readonly taskId: string } | undefined {
- return "backgroundTask" in result ? result.backgroundTask : undefined;
-}
-
/**
* Projects one AI SDK tool call into the eve runtime-action contract.
*/
@@ -428,43 +408,27 @@ export function createRuntimeActionRequestFromToolCall(input: {
return definition?.workflowId === undefined ? action : markRuntimeWorkflowToolAction(action);
}
-/** Projects one deferred harness tool call into task/control coordination. */
+/** Projects one deferred harness tool call into a workflow run request. */
export function createCoordinationRequestFromToolCall(input: {
readonly toolCall: TypedToolCall<ToolSet>;
readonly tools: HarnessToolMap;
-}):
- | { readonly kind: "runtime-action"; readonly request: RuntimeToolCallActionRequest }
- | { readonly kind: "task"; readonly request: RuntimeWorkflowTaskRequest } {
+}): RuntimeWorkflowTaskRequest {
const definition = input.tools.get(input.toolCall.toolName);
+ if (definition?.workflowId === undefined) {
+ throw new Error(`Deferred tool "${input.toolCall.toolName}" has no workflow.`);
+ }
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,
- },
- };
- }
- if (definition?.workflowId !== undefined) {
- return {
- kind: "task",
- request: {
- callId: input.toolCall.toolCallId,
- executeInput: definition.executeInput?.(inputObject),
- input: inputObject,
- kind: "workflow-task",
- toolName: input.toolCall.toolName,
- workflowId: definition.workflowId,
- },
- };
- }
- throw new Error(`Deferred tool "${input.toolCall.toolName}" has no task or runtime action.`);
+ return {
+ callId: input.toolCall.toolCallId,
+ executeInput: definition.executeInput?.(inputObject),
+ input: inputObject,
+ kind: "workflow-task",
+ toolName: input.toolCall.toolName,
+ workflowId: definition.workflowId,
+ };
}
/**
diff --git a/packages/eve/src/harness/current-messages.test.ts b/packages/eve/src/harness/current-messages.test.ts
index 306b917a0..3fc874c95 100644
--- a/packages/eve/src/harness/current-messages.test.ts
+++ b/packages/eve/src/harness/current-messages.test.ts
@@ -51,13 +51,13 @@ describe("createCurrentMessages", () => {
{ currentTurnMessages },
);
- current.add("task state", "context.state");
- current.add("delivery guidance", "context.instruction");
+ current.add("skills state", "context.state");
+ current.add("channel guidance", "context.instruction");
expect(current.nonSystemMessages).toEqual([
{ role: "user", content: "history", kind: "user" },
- { role: "user", content: "task state", kind: "context.state" },
- { role: "user", content: "delivery guidance", kind: "context.instruction" },
+ { role: "user", content: "skills state", kind: "context.state" },
+ { role: "user", content: "channel guidance", kind: "context.instruction" },
{ role: "user", content: "channel context", kind: "user" },
{ role: "user", content: "current request", kind: "user" },
]);
@@ -65,57 +65,45 @@ describe("createCurrentMessages", () => {
it("appends messages without interpreting their text", () => {
const current = createCurrentMessages([
- { role: "user", content: "[Task state]\nuser-authored text", kind: "user" },
+ { role: "user", content: "[Skills]\nuser-authored text", kind: "user" },
]);
- current.add("[Task state]\nworking", "context.state");
- current.add("[Task state]\nworking", "context.state");
+ current.add("[Skills]\nworking", "context.state");
+ current.add("[Skills]\nworking", "context.state");
expect(current.history.map((message) => message.content)).toEqual([
- "[Task state]\nuser-authored text",
- "[Task state]\nworking",
- "[Task state]\nworking",
+ "[Skills]\nuser-authored text",
+ "[Skills]\nworking",
+ "[Skills]\nworking",
]);
});
it("prepares tracked announcements without advancing the recorded baseline", () => {
- const recorded = { taskState: "working" };
+ const recorded = { availableSkills: "working" };
const current = createCurrentMessages([{ role: "user", content: "working", kind: "user" }], {
historyState: recorded,
});
- current.addAnnouncements({ taskState: "working" });
- current.addAnnouncements({ taskState: "completed" });
- current.addAnnouncements({ taskState: "completed", availableSkills: "completed" });
+ current.addAnnouncements({ availableSkills: "working" });
+ current.addAnnouncements({ availableSkills: "completed" });
+ current.addAnnouncements({ availableSkills: "completed" });
- expect(recorded).toEqual({ taskState: "working" });
- expect(current.historyState).toEqual({ taskState: "completed", availableSkills: "completed" });
+ expect(recorded).toEqual({ availableSkills: "working" });
+ expect(current.historyState).toEqual({ availableSkills: "completed" });
expect(current.history).toEqual([
{ role: "user", content: "working", kind: "user" },
{ role: "user", content: "completed", kind: "context.state" },
- { role: "user", content: "completed", kind: "context.state" },
]);
});
- it("keeps announcement order stable and ignores empty or absent values", () => {
+ it("ignores empty or absent announcements", () => {
const current = createCurrentMessages([]);
- current.addAnnouncements({
- deliveryInstruction: "report",
- taskState: "working",
- availableSkills: "skills",
- });
- current.addAnnouncements({ availableSkills: "", taskState: undefined });
+ current.addAnnouncements({ availableSkills: "skills" });
+ current.addAnnouncements({ availableSkills: "" });
+ current.addAnnouncements({});
- expect(current.history).toEqual([
- { role: "user", content: "skills", kind: "context.state" },
- { role: "user", content: "working", kind: "context.state" },
- { role: "user", content: "report", kind: "context.instruction" },
- ]);
- expect(current.historyState).toEqual({
- availableSkills: "skills",
- taskState: "working",
- deliveryInstruction: "report",
- });
+ expect(current.history).toEqual([{ role: "user", content: "skills", kind: "context.state" }]);
+ expect(current.historyState).toEqual({ availableSkills: "skills" });
});
it("persists additions without storing client context or replacing projected history", () => {
@@ -132,16 +120,16 @@ describe("createCurrentMessages", () => {
input,
],
});
- current.add("[Task state]\nworking", "context.state");
+ current.add("[Skills]\nworking", "context.state");
current.addSystem({ role: "system", content: "turn-scoped instructions" });
expect(current.history).toEqual([
hidden,
- { role: "user", content: "[Task state]\nworking", kind: "context.state" },
+ { role: "user", content: "[Skills]\nworking", kind: "context.state" },
input,
]);
expect(current.nonSystemMessages).toEqual([
{ role: "user", content: "ephemeral client context", kind: "user" },
- { role: "user", content: "[Task state]\nworking", kind: "context.state" },
+ { role: "user", content: "[Skills]\nworking", kind: "context.state" },
input,
]);
});
@@ -169,9 +157,9 @@ describe("createCurrentMessages", () => {
approvalTail,
]);
- current.addAnnouncements({ taskState: "task state" });
+ current.addAnnouncements({ availableSkills: "skills" });
- expect(current.systemMessages).toEqual([{ role: "system", content: "task state" }]);
+ expect(current.systemMessages).toEqual([{ role: "system", content: "skills" }]);
expect(current.nonSystemMessages.at(-1)).toBe(approvalTail);
expect(current.historyState).toEqual({});
});
diff --git a/packages/eve/src/harness/current-messages.ts b/packages/eve/src/harness/current-messages.ts
index addcb3451..75ee95e8a 100644
--- a/packages/eve/src/harness/current-messages.ts
+++ b/packages/eve/src/harness/current-messages.ts
@@ -17,12 +17,6 @@ interface CurrentMessagesOptions {
readonly projectedMessages?: readonly HarnessModelMessage[];
}
-const ANNOUNCEMENT_KINDS = {
- availableSkills: "context.state",
- deliveryInstruction: "context.instruction",
- taskState: "context.state",
-} as const satisfies Record<keyof HistoryState, FrameworkMessageKind>;
-
/** Builds the model view and durable history for one step. */
export function createCurrentMessages(
history: readonly HarnessModelMessage[],
@@ -82,12 +76,11 @@ export function createCurrentMessages(
return {
add,
addAnnouncements(announcements) {
- for (const key of ["availableSkills", "taskState", "deliveryInstruction"] as const) {
- const message = announcements[key];
- if (message === undefined || message.length === 0 || historyState[key] === message)
- continue;
- if (add(message, ANNOUNCEMENT_KINDS[key])) historyState[key] = message;
+ const skills = announcements.availableSkills;
+ if (skills === undefined || skills.length === 0 || historyState.availableSkills === skills) {
+ return;
}
+ if (add(skills, "context.state")) historyState.availableSkills = skills;
},
addSystem(messages) {
systemMessages.push(...(Array.isArray(messages) ? messages : [messages]));
diff --git a/packages/eve/src/harness/emission.test.ts b/packages/eve/src/harness/emission.test.ts
index 97a85c1f7..e8c2b8016 100644
--- a/packages/eve/src/harness/emission.test.ts
+++ b/packages/eve/src/harness/emission.test.ts
@@ -14,9 +14,7 @@ import {
getTurnClientContextState,
setTurnClientContextState,
} from "#harness/turn-client-context.js";
-import { markFrameworkStepInput } from "#harness/messages.js";
import type { HarnessEmitFn, HarnessSession } from "#harness/types.js";
-import { EMPTY_DELIVERY_SENTINEL } from "#shared/empty-delivery.js";
async function* streamOf(parts: TextStreamPart<ToolSet>[]): AsyncIterable<TextStreamPart<ToolSet>> {
for (const part of parts) {
@@ -152,30 +150,6 @@ describe("setHarnessEmissionState", () => {
});
describe("emitTurnPreamble", () => {
- it("marks framework-authored task input as non-participant stream activity", async () => {
- const events: Array<Parameters<HarnessEmitFn>[0]> = [];
-
- await emitTurnPreamble(
- async (event) => {
- events.push(event);
- },
- markFrameworkStepInput(
- { message: "Framework-authored task state" },
- "execution.background_task",
- ),
- { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "" },
- [],
- );
-
- expect(events).toEqual([
- expect.objectContaining({ type: "turn.started" }),
- expect.objectContaining({
- data: expect.objectContaining({ kind: "execution.background_task" }),
- type: "message.received",
- }),
- ]);
- });
-
it("keeps participant messages visible", async () => {
const events: Array<Parameters<HarnessEmitFn>[0]> = [];
@@ -183,7 +157,7 @@ describe("emitTurnPreamble", () => {
async (event) => {
events.push(event);
},
- { message: "Start background work" },
+ { message: "Start the work" },
{ sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "" },
[],
);
@@ -260,87 +234,6 @@ describe("emitStreamContent empty delivery", () => {
);
expect(events.at(-1)?.type).toBe("message.completed");
});
-
- it("streams a split sentinel immediately and completes with a null message", async () => {
- const emit = createEmitStub();
-
- await emitStreamContent(
- emit,
- EMISSION_STATE,
- streamOf([
- { id: "text-1", text: " <eve-empty", type: "text-delta" },
- { id: "text-1", text: "-delivery/> ", type: "text-delta" },
- { finishReason: "stop", type: "finish-step" },
- ] as TextStreamPart<ToolSet>[]),
- );
-
- const events = vi.mocked(emit).mock.calls.map(([event]) => event);
- expect(events.map((event) => event.type)).toEqual([
- "message.appended",
- "message.appended",
- "message.completed",
- ]);
- expect(events[0]).toEqual(
- expect.objectContaining({
- data: expect.objectContaining({ messageDelta: " <eve-empty" }),
- }),
- );
- expect(events.at(-1)).toEqual(
- expect.objectContaining({
- data: expect.objectContaining({ finishReason: "stop", message: null }),
- }),
- );
- });
-
- it("preserves normal text that initially resembles the sentinel", async () => {
- const emit = createEmitStub();
- const message = "<eve-empty-delivery is not a marker";
-
- await emitStreamContent(
- emit,
- EMISSION_STATE,
- streamOf([
- { id: "text-1", text: "<eve-empty", type: "text-delta" },
- { id: "text-1", text: "-delivery is not a marker", type: "text-delta" },
- { finishReason: "stop", type: "finish-step" },
- ] as TextStreamPart<ToolSet>[]),
- );
-
- const events = vi.mocked(emit).mock.calls.map(([event]) => event);
- expect(events.filter((event) => event.type === "message.appended")).toHaveLength(2);
- expect(events.at(-1)).toEqual(
- expect.objectContaining({
- data: expect.objectContaining({ message }),
- type: "message.completed",
- }),
- );
- });
-
- it.each([EMPTY_DELIVERY_SENTINEL, "&lt;eve-empty-delivery/&gt;"])(
- "delivers explanations that quote %s across streamed deltas",
- async (sentinel) => {
- const emit = createEmitStub();
- const deltas = ["The pending-task instruction requires `", sentinel, "` and no other text."];
- const message = deltas.join("");
-
- await emitStreamContent(
- emit,
- EMISSION_STATE,
- streamOf([
- ...deltas.map((text) => ({ id: "text-1", text, type: "text-delta" })),
- { finishReason: "stop", type: "finish-step" },
- ] as TextStreamPart<ToolSet>[]),
- );
-
- const events = vi.mocked(emit).mock.calls.map(([event]) => event);
- expect(events.at(-1)).toEqual(
- expect.objectContaining({
- data: expect.objectContaining({ message }),
- type: "message.completed",
- }),
- );
- },
- );
});
describe("emitStreamContent action requests", () => {
@@ -718,53 +611,6 @@ describe("emitStreamContent action requests", () => {
]);
});
- it("returns a background receipt without announcing subagent completion", 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",
- nodeId: "subagents/researcher",
- 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", "action.result"]);
- expect(events[1]).toMatchObject({
- data: {
- result: { callId: "call-delegate", output: { status: "working", taskId: "task-1" } },
- },
- type: "action.result",
- });
- });
-
it("does not fail tool streaming when label projections throw", async () => {
const tools = new Map<string, HarnessToolDefinition>([
[
diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.ts
index 44387c489..6cc3fc885 100644
--- a/packages/eve/src/harness/emission.ts
+++ b/packages/eve/src/harness/emission.ts
@@ -34,7 +34,6 @@ import {
createTurnFailedEvent,
createTurnStartedEvent,
} from "#protocol/message.js";
-import { hasEmptyDeliverySentinel } from "#shared/empty-delivery.js";
import type { JsonObject } from "#shared/json.js";
import {
createRuntimeToolResultFromStepResult,
@@ -61,7 +60,6 @@ import { isInlineAuthorizationToolResult } from "#harness/inline-tool-authorizat
import type { HarnessEmissionState } from "#harness/emission-state.js";
import type { HarnessEmitFn, HarnessToolMap, StepInput } from "#harness/types.js";
import { normalizeAssistantStepFinishReason } from "#harness/finish-reason.js";
-import { frameworkMessageKindForStepInput } from "#harness/messages.js";
export {
getHarnessEmissionState,
@@ -99,10 +97,8 @@ export async function emitTurnPreamble(
}
if (input.message !== undefined) {
- const kind = frameworkMessageKindForStepInput(input);
await emitFn(
createMessageReceivedEvent({
- kind: kind === "execution.background_task" ? kind : undefined,
message: input.message,
sequence: state.sequence,
turnId,
@@ -666,23 +662,7 @@ async function consumeStreamContent(
);
}
- // Channel adapters deliver terminal completions, so the reserved marker
- // becomes a null completion without delaying normal streaming deltas.
- if (
- finishReason !== "content-filter" &&
- finishReason !== "tool-calls" &&
- hasEmptyDeliverySentinel(currentMessage)
- ) {
- await emitFn(
- createMessageCompletedEvent({
- finishReason,
- message: null,
- sequence: state.sequence,
- stepIndex: state.stepIndex,
- turnId: state.turnId,
- }),
- );
- } else if (finishReason !== "content-filter" && currentMessage.trim().length > 0) {
+ if (finishReason !== "content-filter" && currentMessage.trim().length > 0) {
await emitFn(
createMessageCompletedEvent({
finishReason,
diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.ts
index 593281b30..6ea91954c 100644
--- a/packages/eve/src/harness/execute-tool.ts
+++ b/packages/eve/src/harness/execute-tool.ts
@@ -5,14 +5,6 @@ import type { InternalToolLabelDefinition, ToolExecuteOptions } from "#tools/def
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 `task_cancel`: it carries no child address of its
- * own — the dispatch step resolves targets through the session task index.
- */
-export type HarnessRuntimeActionDefinition = { readonly kind: "task-control" };
-
/**
* Unified harness-owned tool definition.
*/
@@ -25,7 +17,6 @@ export interface HarnessToolDefinition {
readonly execute?: (input: any, options: ToolExecuteOptions) => 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;
@@ -39,7 +30,6 @@ export interface HarnessToolDefinition {
* 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/generation-steering.test.ts b/packages/eve/src/harness/generation-steering.test.ts
index 562b60c8d..de6f27282 100644
--- a/packages/eve/src/harness/generation-steering.test.ts
+++ b/packages/eve/src/harness/generation-steering.test.ts
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import { GenerationSteering } from "#harness/generation-steering.js";
import {
createMessageAppendedEvent,
- createMessageCompletedEvent,
createReasoningAppendedEvent,
createInputRequestedEvent,
createStepFailedEvent,
@@ -30,15 +29,6 @@ describe("GenerationSteering", () => {
turnId: "turn_0",
}),
);
- generation.beforeEvent(
- createMessageCompletedEvent({
- message: null,
- finishReason: "tool-calls",
- sequence: 0,
- stepIndex: 0,
- turnId: "turn_0",
- }),
- );
steering.abort();
expect(() =>
generation.beforeEvent(
diff --git a/packages/eve/src/harness/input-request-resolution.ts b/packages/eve/src/harness/input-request-resolution.ts
index 02eddee9a..77993c515 100644
--- a/packages/eve/src/harness/input-request-resolution.ts
+++ b/packages/eve/src/harness/input-request-resolution.ts
@@ -1,4 +1,3 @@
-import { isApprovalRequest } from "#harness/input-request-class.js";
import type { PendingInputBatchEvent } from "#harness/pending-input-batches.js";
import type { InputRequest, InputResponse } from "#shared/input.js";
@@ -33,11 +32,7 @@ export function buildResolvedInputBatch(
inputs: batch.requests.map((request) => {
const response = responseMap.get(request.requestId);
return {
- outcome: isApprovalRequest(request)
- ? resolveApprovalOutcome(response).status
- : response === undefined
- ? "ignored"
- : "answered",
+ outcome: resolveInputOutcome(request.kind, response),
request,
response,
...(batch.toolReplayIdentities?.[request.requestId] === undefined
@@ -50,6 +45,18 @@ export function buildResolvedInputBatch(
};
}
+/**
+ * One request's terminal outcome once its batch resolves: an approval's
+ * decision, or whether a question received a response.
+ */
+export function resolveInputOutcome(
+ kind: InputRequest["kind"],
+ response: InputResponse | undefined,
+): "answered" | ApprovalTerminalStatus {
+ if (kind === "tool-approval") return resolveApprovalOutcome(response).status;
+ return response === undefined ? "ignored" : "answered";
+}
+
export function resolveApprovalOutcome(response: InputResponse | undefined): {
readonly approved: boolean;
readonly reason: string | undefined;
diff --git a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts b/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts
index d840b6e8a..16306e9ce 100644
--- a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts
+++ b/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts
@@ -10,8 +10,6 @@ import { setPendingAuthorization } from "#harness/authorization.js";
import { z } from "zod";
import { ContextContainer, contextStorage } from "#context/container.js";
import { SessionKey } from "#context/keys.js";
-import { BackgroundToolExecutorKey } from "#harness/background-tools.js";
-import { getBackgroundTasks, registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
import { getHarnessEmissionState } from "#harness/emission.js";
import { getPendingCoordinationBatch } from "#harness/coordination.js";
import { getPendingInputBatches } from "#harness/pending-input-batches.js";
@@ -45,7 +43,6 @@ function fixture(
responseAuthorized: boolean | ApprovalResponsePolicy = false,
outputLimit?: number,
outputSchema?: HarnessSession["outputSchema"],
- executorHasPendingTasks = false,
) {
const script: Reply[] = [];
const events: UnstampedMessageStreamEvent[] = [];
@@ -148,22 +145,6 @@ function fixture(
inputSchema: jsonSchema({ type: "object" }),
workflowId: "diagnostic-workflow",
});
- tools.set("control", {
- name: "control",
- description: "Deferred runtime control",
- inputSchema: jsonSchema({ type: "object" }),
- runtimeAction: { kind: "task-control" },
- });
- tools.set("background", {
- name: "background",
- description: "Background workflow",
- inputSchema: jsonSchema({ type: "object" }),
- workflowId: "diagnostic-background",
- execution: "background",
- execute: async () => {
- throw new Error("Must dispatch through executor");
- },
- });
const restoredTurns: string[] = [];
const harness = createToolLoopHarness({
prepareApprovalTurn: async (event) => {
@@ -206,14 +187,6 @@ function fixture(
auth: { current: null, initiator: null },
turn: { id: emission.turnId || `turn_${emission.sequence}`, sequence: emission.sequence },
});
- ctx.set(BackgroundToolExecutorKey, {
- hasPendingTasks: () => executorHasPendingTasks,
- async execute({ batch, options }) {
- expect(batch.calls.some((call) => call.callId === options.toolCallId)).toBe(true);
- executions.push("background-admitted");
- return { status: "working", taskId: "diagnostic-background-task" };
- },
- });
const result = await contextStorage.run(ctx, () => harness(session, input));
session = result.session;
steps.push({
@@ -275,7 +248,7 @@ function fixture(
const batch = getPendingCoordinationBatch(session.state);
if (!batch) throw new Error("Expected actual pending coordination batch");
return drive({
- runtimeActionResults: [...batch.tasks, ...batch.runtimeActions].map((r) => ({
+ runtimeActionResults: batch.tasks.map((r) => ({
kind: "tool-result" as const,
callId: r.callId,
toolName: r.toolName,
@@ -340,18 +313,16 @@ for (const variant of ["approve", "cancel"] as const) {
});
}
-for (const tool of ["workflow", "control"]) {
- it(`interprets a completed ${tool} result while an earlier approval remains`, async () => {
- const f = fixture(tool);
- await f.gate("gateA");
- f.script.push(calls(tool), "FINAL");
- await f.drive({ message: `Run unrelated ${tool}.` });
- const result = await f.finishRuntime();
- expect(JSON.stringify(result.session.history)).toContain("runtime-RESULT");
- expect(f.pending()).toHaveLength(1);
- expect(result.settledTurn?.output).toBe("FINAL");
- });
-}
+it("interprets a completed workflow result while an earlier approval remains", async () => {
+ const f = fixture("workflow");
+ await f.gate("gateA");
+ f.script.push(calls("workflow"), "FINAL");
+ await f.drive({ message: "Run unrelated workflow." });
+ const result = await f.finishRuntime();
+ expect(JSON.stringify(result.session.history)).toContain("runtime-RESULT");
+ expect(f.pending()).toHaveLength(1);
+ expect(result.settledTurn?.output).toBe("FINAL");
+});
it("completes a plain tool turn without any pending input [control]", async () => {
const f = fixture("control-no-pending");
@@ -504,14 +475,6 @@ it("reaches the next budget prompt after a grant without an older approval [cont
});
for (const pending of [true, false]) {
- it(`continues after a background admission receipt ${pending ? "with pending approval" : "[control]"}`, async () => {
- const f = fixture(`background-${pending}`);
- if (pending) await f.gate("gateA");
- f.script.push(calls("background"), "FINAL");
- const result = await f.drive({ message: "Start background work and acknowledge admission." });
- expect(f.executions).toEqual(["background-admitted"]);
- expect(result.settledTurn?.output).toBe("FINAL");
- });
it(`continues after a provider-executed result ${pending ? "with pending approval" : "[control]"}`, async () => {
const f = fixture(`provider-${pending}`);
if (pending) await f.gate("gateA");
@@ -650,64 +613,6 @@ it.each(["rejected", "failed", "timed-out"] as const)(
},
);
-it.each(["persisted", "executor"] as const)(
- "finishes a refusal while unrelated background work is %s, like an ordinary conversation turn",
- async (source) => {
- const f = fixture(
- `refusal-with-background-${source}`,
- () => ({ status: "rejected", reason: "Bob must approve Alice's note." }),
- undefined,
- undefined,
- source === "executor",
- );
- await f.gate("gateA");
- if (source === "persisted") {
- f.updateSession((session) =>
- registerWorkflowToolRun(session, {
- callId: "report-call",
- toolName: "report",
- lifetime: "session",
- origin: { turnId: "report-turn", stepIndex: 0 },
- address: { runId: "report-run", hookToken: "report-hook" },
- task: {
- taskId: "report-task",
- metadata: { kind: "workflow", name: "report" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
- }),
- );
- }
- const ordinaryStart = f.events.length;
- f.script.push("The report is still running.");
- await f.drive({ message: "What is the report's status?" });
- expect(f.events.slice(ordinaryStart).at(-1)?.type).toBe("session.waiting");
-
- const responseStart = f.events.length;
- await f.drive({
- attributedInputResponses: f.respond("gateA").inputResponses!.map((response) => ({
- response,
- auth: {
- attributes: {},
- authenticator: "test",
- issuer: "test",
- principalId: "alice",
- principalType: "user" as const,
- },
- })),
- });
- expect(f.events.slice(responseStart).map((event) => event.type)).toEqual([
- "approval.candidate",
- "approval.candidate",
- "session.waiting",
- ]);
- expect(f.pending()).toHaveLength(1);
- expect(f.executions).toEqual([]);
- if (source === "persisted") {
- expect(getBackgroundTasks(f.session.state).query({ state: "working" })).toHaveLength(1);
- }
- },
-);
-
it("does not announce waiting while a candidate needs sign-in, then completes on expiry", async () => {
const policy = vi.fn(() => ({ status: "allowed" as const }));
const f = fixture("candidate-sign-in", policy);
diff --git a/packages/eve/src/harness/messages.test.ts b/packages/eve/src/harness/messages.test.ts
index a158b4713..499e72994 100644
--- a/packages/eve/src/harness/messages.test.ts
+++ b/packages/eve/src/harness/messages.test.ts
@@ -31,23 +31,6 @@ function textFilePart(overrides: {
}
describe("coalesceDeliveries", () => {
- it("keeps the last explicit task policy when batching authored sends", () => {
- const result = coalesceDeliveries([
- {
- kind: "deliver" as const,
- payloads: [{ message: "First" }],
- taskDeliveryPolicy: "cohort" as const,
- },
- {
- kind: "deliver" as const,
- payloads: [{ message: "Second" }],
- taskDeliveryPolicy: "auto" as const,
- },
- { kind: "deliver" as const, payloads: [{ message: "Third" }] },
- ]);
- expect(result.taskDeliveryPolicy).toBe("auto");
- });
-
const caller = {
callId: "call-1",
replyTo: { kind: "hook" as const, token: "turn-caller" },
@@ -57,13 +40,13 @@ describe("coalesceDeliveries", () => {
it("preserves the only caller in a delivery batch", () => {
expect(
coalesceDeliveries([
- { kind: "deliver", payloads: [{ context: ["background"] }] },
+ { kind: "deliver", payloads: [{ context: ["earlier context"] }] },
{ caller, kind: "deliver", payloads: [{ message: "question" }] },
]),
).toEqual({
caller,
kind: "deliver",
- payloads: [{ context: ["background"] }, { message: "question" }],
+ payloads: [{ context: ["earlier context"] }, { message: "question" }],
});
});
@@ -125,22 +108,19 @@ describe("coalesceTurnInputs", () => {
it("preserves a framework kind only when all merged message content shares it", () => {
expect(
coalesceTurnInputs(
- markFrameworkStepInput({ message: "first" }, "execution.background_task"),
- markFrameworkStepInput({ message: "second" }, "execution.background_task"),
+ markFrameworkStepInput({ message: "first" }, "execution.continuation"),
+ markFrameworkStepInput({ message: "second" }, "execution.continuation"),
),
- ).toEqual(markFrameworkStepInput({ message: "first\n\nsecond" }, "execution.background_task"));
+ ).toEqual(markFrameworkStepInput({ message: "first\n\nsecond" }, "execution.continuation"));
expect(
- coalesceTurnInputs(
- markFrameworkStepInput({ message: "first" }, "execution.background_task"),
- {
- message: "second",
- },
- ),
+ coalesceTurnInputs(markFrameworkStepInput({ message: "first" }, "execution.continuation"), {
+ message: "second",
+ }),
).toEqual({ message: "first\n\nsecond" });
expect(
coalesceTurnInputs(
markFrameworkStepInput({ message: "first" }, "context.instruction"),
- markFrameworkStepInput({ message: "second" }, "execution.background_task"),
+ markFrameworkStepInput({ message: "second" }, "execution.continuation"),
),
).toEqual({ message: "first\n\nsecond" });
});
@@ -311,7 +291,7 @@ describe("createFrameworkUserMessage", () => {
"context.state",
"context.compaction",
"memory.load",
- "execution.background_task",
+ "execution.continuation",
"execution.continuation",
"execution.retry",
] as const)("recognizes %s as a framework message kind", (kind) => {
@@ -320,13 +300,13 @@ describe("createFrameworkUserMessage", () => {
it("brands framework-authored user-role messages", () => {
const message = createFrameworkUserMessage(
- "execution.background_task",
- "Background task task_1 completed.",
+ "execution.continuation",
+ "Continue the interrupted turn.",
);
expect(message).toEqual({
- content: "Background task task_1 completed.",
- kind: "execution.background_task",
+ content: "Continue the interrupted turn.",
+ kind: "execution.continuation",
role: "user",
});
expect(isFrameworkUserMessage(message)).toBe(true);
diff --git a/packages/eve/src/harness/messages.ts b/packages/eve/src/harness/messages.ts
index cf7f43b85..65fc4fabe 100644
--- a/packages/eve/src/harness/messages.ts
+++ b/packages/eve/src/harness/messages.ts
@@ -5,7 +5,6 @@ import type {
DeliverPayload,
SessionAuthContext,
TurnCaller,
- TaskDeliveryPolicy,
} from "#channel/types.js";
import type { InputResponse } from "#shared/input.js";
import type { StepInput } from "#harness/types.js";
@@ -17,7 +16,6 @@ export type FrameworkMessageKind =
| "context.state"
| "context.compaction"
| "memory.load"
- | "execution.background_task"
| "execution.continuation"
| "execution.retry";
@@ -109,7 +107,6 @@ export function isFrameworkMessageKind(value: unknown): value is FrameworkMessag
value === "context.state" ||
value === "context.compaction" ||
value === "memory.load" ||
- value === "execution.background_task" ||
value === "execution.continuation" ||
value === "execution.retry"
);
@@ -399,7 +396,6 @@ interface DeliverLike {
readonly auth?: SessionAuthContext | null;
readonly caller?: TurnCaller;
readonly deliveryMetadata?: readonly ChannelDeliveryMetadataEntry[];
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
readonly kind: "deliver";
readonly payloads: readonly DeliverPayload[];
}
@@ -422,14 +418,12 @@ export function coalesceDeliveries<T extends DeliverLike>(items: readonly T[]):
}
let auth = first.auth;
- let taskDeliveryPolicy = first.taskDeliveryPolicy;
let caller = first.caller;
const payloads = [...first.payloads];
const deliveryMetadata = [...(first.deliveryMetadata ?? [])];
for (const item of rest) {
const payloadOffset = payloads.length;
- taskDeliveryPolicy = item.taskDeliveryPolicy ?? taskDeliveryPolicy;
if (item.auth !== undefined) {
auth = item.auth;
}
@@ -450,7 +444,6 @@ export function coalesceDeliveries<T extends DeliverLike>(items: readonly T[]):
return {
...first,
- taskDeliveryPolicy,
auth,
caller,
deliveryMetadata: deliveryMetadata.length === 0 ? undefined : deliveryMetadata,
diff --git a/packages/eve/src/harness/proxy-input-requests.test.ts b/packages/eve/src/harness/proxy-input-requests.test.ts
index 036cca73d..3c3c4411a 100644
--- a/packages/eve/src/harness/proxy-input-requests.test.ts
+++ b/packages/eve/src/harness/proxy-input-requests.test.ts
@@ -11,6 +11,8 @@ import type { SubagentInputRequestHookPayload } from "#channel/types.js";
import type { InputRequest, InputRequestKind } from "#shared/input.js";
import type { HarnessSession } from "#harness/types.js";
+const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };
+
function createSession(state?: Record<string, unknown>): HarnessSession {
return {
agent: {
@@ -39,7 +41,9 @@ describe("upsertProxyInputRequests", () => {
it("records a fresh batch of proxy entries", () => {
const session = createSession();
const next = upsertProxyInputRequests({
- entries: [["req-1", { childContinuationToken: "child-a", kind: "question" }]],
+ entries: [
+ ["req-1", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],
+ ],
forChildContinuationToken: "child-a",
session,
});
@@ -47,50 +51,24 @@ describe("upsertProxyInputRequests", () => {
expect(hasProxyInputRequests(next.state)).toBe(true);
expect(getProxyInputRequests(next.state).get("req-1")).toEqual({
childContinuationToken: "child-a",
+ event: REQUEST_EVENT,
kind: "question",
});
});
- it("round-trips task ownership without exposing malformed ownership as an unscoped route", () => {
- const next = upsertProxyInputRequests({
- entries: [
- [
- "task-1:req-1",
- {
- childContinuationToken: "child-a",
- childRequestId: "req-1",
- kind: "question",
- taskId: "task-1",
- },
- ],
- ],
- forChildContinuationToken: "child-a",
- session: createSession(),
- });
- expect(getProxyInputRequests(next.state).get("task-1:req-1")).toEqual({
- childContinuationToken: "child-a",
- childRequestId: "req-1",
- kind: "question",
- taskId: "task-1",
- });
- expect(
- getProxyInputRequests({
- "eve.runtime.proxyInputRequests": {
- "req-1": { childContinuationToken: "child-a", kind: "question", taskId: 42 },
- },
- }).size,
- ).toBe(0);
- });
-
it("replaces prior entries for the same child continuation token", () => {
let session = upsertProxyInputRequests({
- entries: [["req-1", { childContinuationToken: "child-a", kind: "question" }]],
+ entries: [
+ ["req-1", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],
+ ],
forChildContinuationToken: "child-a",
session: createSession(),
});
session = upsertProxyInputRequests({
- entries: [["req-2", { childContinuationToken: "child-a", kind: "question" }]],
+ entries: [
+ ["req-2", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],
+ ],
forChildContinuationToken: "child-a",
session,
});
@@ -100,6 +78,7 @@ describe("upsertProxyInputRequests", () => {
expect(entries.get("req-1")).toBeUndefined();
expect(entries.get("req-2")).toEqual({
childContinuationToken: "child-a",
+ event: REQUEST_EVENT,
kind: "question",
});
});
@@ -107,34 +86,46 @@ describe("upsertProxyInputRequests", () => {
it("drops a prior child's batch when its request ID is claimed by another child", () => {
let session = upsertProxyInputRequests({
entries: [
- ["req-1", { childContinuationToken: "child-a", kind: "question" }],
- ["req-2", { childContinuationToken: "child-a", kind: "question" }],
+ ["req-1", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],
+ ["req-2", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],
],
forChildContinuationToken: "child-a",
session: createSession(),
});
session = upsertProxyInputRequests({
- entries: [["req-1", { childContinuationToken: "child-b", kind: "tool-approval" }]],
+ entries: [
+ [
+ "req-1",
+ { childContinuationToken: "child-b", event: REQUEST_EVENT, kind: "tool-approval" },
+ ],
+ ],
forChildContinuationToken: "child-b",
session,
});
expect(Object.fromEntries(getProxyInputRequests(session.state))).toEqual({
- "req-1": { childContinuationToken: "child-b", kind: "tool-approval" },
- "req-2": { childContinuationToken: "child-a", kind: "question" },
+ "req-1": { childContinuationToken: "child-b", event: REQUEST_EVENT, kind: "tool-approval" },
+ "req-2": { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" },
});
});
it("keeps entries from other children when upserting", () => {
let session = upsertProxyInputRequests({
- entries: [["req-a", { childContinuationToken: "child-a", kind: "question" }]],
+ entries: [
+ ["req-a", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],
+ ],
forChildContinuationToken: "child-a",
session: createSession(),
});
session = upsertProxyInputRequests({
- entries: [["req-b", { childContinuationToken: "child-b", kind: "tool-approval" }]],
+ entries: [
+ [
+ "req-b",
+ { childContinuationToken: "child-b", event: REQUEST_EVENT, kind: "tool-approval" },
+ ],
+ ],
forChildContinuationToken: "child-b",
session,
});
@@ -143,10 +134,12 @@ describe("upsertProxyInputRequests", () => {
expect(entries.size).toBe(2);
expect(entries.get("req-a")).toEqual({
childContinuationToken: "child-a",
+ event: REQUEST_EVENT,
kind: "question",
});
expect(entries.get("req-b")).toEqual({
childContinuationToken: "child-b",
+ event: REQUEST_EVENT,
kind: "tool-approval",
});
});
@@ -203,6 +196,7 @@ describe("toProxyInputRequestEntries", () => {
requestIds: ["question-1", "approval-1"],
},
childContinuationToken: "child-a",
+ event: { sequence: 3, stepIndex: 2, turnId: "turn-1" },
kind: "question",
question: {},
},
@@ -215,6 +209,7 @@ describe("toProxyInputRequestEntries", () => {
requestIds: ["question-1", "approval-1"],
},
childContinuationToken: "child-a",
+ event: { sequence: 3, stepIndex: 2, turnId: "turn-1" },
kind: "tool-approval",
},
],
@@ -225,13 +220,20 @@ describe("toProxyInputRequestEntries", () => {
describe("clearProxyInputRequestsForChild", () => {
it("removes only the target child's entries", () => {
let session = upsertProxyInputRequests({
- entries: [["req-a", { childContinuationToken: "child-a", kind: "question" }]],
+ entries: [
+ ["req-a", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],
+ ],
forChildContinuationToken: "child-a",
session: createSession(),
});
session = upsertProxyInputRequests({
- entries: [["req-b", { childContinuationToken: "child-b", kind: "tool-approval" }]],
+ entries: [
+ [
+ "req-b",
+ { childContinuationToken: "child-b", event: REQUEST_EVENT, kind: "tool-approval" },
+ ],
+ ],
forChildContinuationToken: "child-b",
session,
});
@@ -242,6 +244,7 @@ describe("clearProxyInputRequestsForChild", () => {
expect(entries.size).toBe(1);
expect(entries.get("req-b")).toEqual({
childContinuationToken: "child-b",
+ event: REQUEST_EVENT,
kind: "tool-approval",
});
});
@@ -263,15 +266,16 @@ describe("getProxyInputRequests type safety", () => {
const session = createSession({
"eve.runtime.proxyInputRequests": {
"req-1": 42,
- "req-2": { childContinuationToken: 42, kind: "question" },
+ "req-2": { childContinuationToken: 42, event: REQUEST_EVENT, kind: "question" },
"req-3": { childContinuationToken: "child-c", kind: "other" },
- "req-4": { childContinuationToken: "child-d", kind: "question" },
+ "req-4": { childContinuationToken: "child-d", event: REQUEST_EVENT, kind: "question" },
},
});
const entries = getProxyInputRequests(session.state);
expect(entries.size).toBe(1);
expect(entries.get("req-4")).toEqual({
childContinuationToken: "child-d",
+ event: REQUEST_EVENT,
kind: "question",
});
});
@@ -286,59 +290,22 @@ describe("getProxyInputRequests type safety", () => {
it("keeps legacy routes and ignores malformed optional batch metadata", () => {
const session = createSession({
"eve.runtime.proxyInputRequests": {
- legacy: { childContinuationToken: "child-a", kind: "question" },
+ legacy: { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" },
malformed: {
batch: { approvalRequestIds: ["other"], requestIds: ["malformed"] },
childContinuationToken: "child-a",
+ event: REQUEST_EVENT,
kind: "tool-approval",
},
},
});
expect([...getProxyInputRequests(session.state)]).toEqual([
- ["legacy", { childContinuationToken: "child-a", kind: "question" }],
- ["malformed", { childContinuationToken: "child-a", kind: "tool-approval" }],
+ ["legacy", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],
+ [
+ "malformed",
+ { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "tool-approval" },
+ ],
]);
});
-
- it("accepts HTTPS child response URLs", () => {
- expect(readChildResponseUrl("https://remote.example/eve/v1/task-input/token")).toBe(
- "https://remote.example/eve/v1/task-input/token",
- );
- });
-
- it.each([
- "http://localhost:3000/eve/v1/task-input/token",
- "http://worker.localhost:3000/eve/v1/task-input/token",
- "http://127.0.0.1:3000/eve/v1/task-input/token",
- "http://127.0.0.2:3000/eve/v1/task-input/token",
- "http://[::1]:3000/eve/v1/task-input/token",
- "http://[::ffff:7f00:1]:3000/eve/v1/task-input/token",
- ])("accepts an HTTP loopback child response URL: %s", (url) => {
- expect(readChildResponseUrl(url)).toBe(url);
- });
-
- it.each([
- "http://remote.example/eve/v1/task-input/token",
- "http://10.0.0.1/eve/v1/task-input/token",
- "http://localhost.example/eve/v1/task-input/token",
- "ftp://localhost/eve/v1/task-input/token",
- "not a URL",
- ])("rejects a non-HTTPS, non-loopback, or malformed child response URL: %s", (url) => {
- expect(readChildResponseUrl(url)).toBeUndefined();
- });
});
-
-function readChildResponseUrl(childResponseUrl: string): string | undefined {
- return getProxyInputRequests({
- "eve.runtime.proxyInputRequests": {
- "task-1:req-1": {
- childContinuationToken: "child-a",
- childRequestId: "req-1",
- childResponseUrl,
- kind: "question",
- taskId: "task-1",
- },
- },
- }).get("task-1:req-1")?.childResponseUrl;
-}
diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.ts
index a7e755937..17c895444 100644
--- a/packages/eve/src/harness/proxy-input-requests.ts
+++ b/packages/eve/src/harness/proxy-input-requests.ts
@@ -1,7 +1,7 @@
import type { SubagentInputRequestHookPayload } from "#channel/types.js";
+import type { PendingInputBatchEvent } from "#harness/pending-input-batches.js";
import type { HarnessSession, SessionStateMap } from "#harness/types.js";
import { inputOptionSchema, type InputOption, type InputRequestKind } from "#shared/input.js";
-import { isLoopbackHostname } from "#shared/network-address.js";
import {
isSessionInboxAddress,
type SessionInboxAddress,
@@ -16,38 +16,38 @@ const PROXY_INPUT_REQUEST_KINDS = {
} satisfies Readonly<Record<InputRequestKind, true>>;
/**
- * Marks a continuation token as a bare hook a workflow tool run created for one
- * request, resumed with the plain response, rather than a child session inbox.
+ * Marks a request as a workflow tool run's `ctx.ask()` question, rather than a
+ * child session's. Its answer goes to the run's control hook, which carries
+ * every decision the session makes for the run, in order.
*/
-export interface AnswerHookRoute {
+export interface WorkflowAskRoute {
+ readonly control: string;
+ /** What a plain-text message may answer. */
+ readonly question: ProxyInputQuestion;
readonly runId: string;
- /** Present for a `ctx.ask()` question: what a plain-text message may answer or dismiss. */
- readonly question?: AnswerHookQuestion;
}
/** The parts of a `ctx.ask()` request a plain-text message is resolved against. */
-export interface AnswerHookQuestion {
+export interface ProxyInputQuestion {
readonly allowFreeform?: boolean;
- readonly dismissible?: boolean;
readonly options?: readonly InputOption[];
}
/** Routing and control metadata for one descendant-owned input request. */
export interface ProxyInputRequest {
- readonly answerHook?: AnswerHookRoute;
+ readonly workflowAsk?: WorkflowAskRoute;
/** Batch semantics are optional so sessions written before this field remain routable. */
readonly batch?: ProxyInputRequestBatch;
readonly childContinuationToken: string;
readonly childSessionInbox?: SessionInboxAddress;
- /** Child-local id restored before forwarding a namespaced task response. */
- readonly childRequestId?: string;
- /** Trusted parent-derived capability URL for a remote task child. */
- readonly childResponseUrl?: string;
+ /**
+ * Coordinates of the `input.requested` this session emitted for the request;
+ * the `input.resolved` it emits once it routes the answer repeats them.
+ */
+ readonly event: PendingInputBatchEvent;
readonly kind: InputRequestKind;
/** Question metadata lets the human-facing parent resolve plain text before proxying by ID. */
- readonly question?: AnswerHookQuestion;
- /** Present when the route is authorized by a parent-owned durable task. */
- readonly taskId?: string;
+ readonly question?: ProxyInputQuestion;
}
export interface ProxyInputRequestBatch {
@@ -58,11 +58,6 @@ export interface ProxyInputRequestBatch {
/** `requestId → route` map stored on the parent session. */
type ProxyInputRequestMap = Readonly<Record<string, ProxyInputRequest>>;
-/** Parent-visible id for one task-owned child-local input request. */
-export function createTaskInputRequestId(taskId: string, childRequestId: string): string {
- return `${taskId}:${childRequestId}`;
-}
-
/**
* Returns the proxy-routing map as a fresh `Map`. Never returns a live
* reference so accidental mutation cannot corrupt session state.
@@ -185,14 +180,6 @@ export function retireProxyInputRequests<T extends { readonly state?: SessionSta
return changed ? writeMap(session, next) : session;
}
-/** Removes every proxy route owned by one durable task. */
-export function clearProxyInputRequestsForTask<T extends { readonly state?: SessionStateMap }>(
- session: T,
- taskId: string,
-): T {
- return clearProxyInputRequestsWhere(session, (route) => route.taskId === taskId);
-}
-
/**
* Removes every proxy entry. Called when a cancelled turn orphans its
* descendants so stale HITL responses no longer route to them.
@@ -210,7 +197,6 @@ export function clearAllProxyInputRequests(session: HarnessSession): HarnessSess
*/
export function toProxyInputRequestEntries(
payload: SubagentInputRequestHookPayload,
- taskId?: string,
): readonly (readonly [requestId: string, route: ProxyInputRequest])[] {
const batch: ProxyInputRequestBatch = {
approvalRequestIds: payload.event.requests.flatMap((request) =>
@@ -218,17 +204,22 @@ export function toProxyInputRequestEntries(
),
requestIds: payload.event.requests.map((request) => request.requestId),
};
+ const event: PendingInputBatchEvent = {
+ sequence: payload.event.sequence,
+ stepIndex: payload.event.stepIndex,
+ turnId: payload.event.turnId,
+ };
return payload.event.requests.map((request) => {
const route: {
readonly childContinuationToken: string;
childSessionInbox?: SessionInboxAddress;
- childResponseUrl?: string;
+ readonly event: PendingInputBatchEvent;
readonly kind: InputRequestKind;
- question?: AnswerHookQuestion;
- taskId?: string;
+ question?: ProxyInputQuestion;
} & { readonly batch: ProxyInputRequestBatch } = {
batch,
childContinuationToken: payload.childContinuationToken,
+ event,
kind: request.kind,
};
if (request.kind === "question") {
@@ -237,7 +228,6 @@ export function toProxyInputRequestEntries(
...(request.options !== undefined && { options: [...request.options] }),
};
}
- if (taskId !== undefined) route.taskId = taskId;
if (payload.childSessionInbox?.sessionId === payload.childSessionId) {
route.childSessionInbox = payload.childSessionInbox;
}
@@ -291,77 +281,67 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
if (typeof value.childContinuationToken !== "string" || !isInputRequestKind(value.kind)) {
return undefined;
}
- const taskId = "taskId" in value ? value.taskId : undefined;
- const childRequestId = "childRequestId" in value ? value.childRequestId : undefined;
- const childResponseUrl = "childResponseUrl" in value ? value.childResponseUrl : undefined;
- if (taskId !== undefined && (typeof taskId !== "string" || taskId.length === 0)) {
- return undefined;
- }
- if (
- childRequestId !== undefined &&
- (typeof childRequestId !== "string" || childRequestId.length === 0)
- ) {
- return undefined;
- }
- if ((taskId === undefined) !== (childRequestId === undefined)) return undefined;
- if (
- childResponseUrl !== undefined &&
- (typeof childResponseUrl !== "string" || !isAllowedChildResponseUrl(childResponseUrl))
- ) {
- return undefined;
- }
+ const event = "event" in value ? parseInputRequestEvent(value.event) : undefined;
+ if (event === undefined) return undefined;
const batch = "batch" in value ? parseProxyInputRequestBatch(value.batch) : undefined;
- const answerHook = "answerHook" in value ? parseAnswerHookRoute(value.answerHook) : undefined;
- if ("answerHook" in value && answerHook === undefined) return undefined;
- const question = "question" in value ? parseAnswerHookQuestion(value.question) : undefined;
+ const workflowAsk = "workflowAsk" in value ? parseWorkflowAskRoute(value.workflowAsk) : undefined;
+ if ("workflowAsk" in value && workflowAsk === undefined) return undefined;
+ const question = "question" in value ? parseProxyInputQuestion(value.question) : undefined;
if ("question" in value && question === undefined) return undefined;
const childSessionInbox = "childSessionInbox" in value ? value.childSessionInbox : undefined;
if (childSessionInbox !== undefined && !isSessionInboxAddress(childSessionInbox))
return undefined;
const request: {
- answerHook?: AnswerHookRoute;
+ workflowAsk?: WorkflowAskRoute;
batch?: ProxyInputRequestBatch;
readonly childContinuationToken: string;
childSessionInbox?: SessionInboxAddress;
- childRequestId?: string;
- childResponseUrl?: string;
+ readonly event: PendingInputBatchEvent;
readonly kind: InputRequestKind;
- question?: AnswerHookQuestion;
- taskId?: string;
+ question?: ProxyInputQuestion;
} = {
childContinuationToken: value.childContinuationToken,
+ event,
kind: value.kind,
};
- if (answerHook !== undefined) request.answerHook = answerHook;
+ if (workflowAsk !== undefined) request.workflowAsk = workflowAsk;
if (childSessionInbox !== undefined) request.childSessionInbox = childSessionInbox;
if (batch !== undefined && batch.requestIds.includes(requestId)) request.batch = batch;
- if (typeof childRequestId === "string") request.childRequestId = childRequestId;
- if (typeof childResponseUrl === "string") request.childResponseUrl = childResponseUrl;
if (question !== undefined) request.question = question;
- if (typeof taskId === "string") request.taskId = taskId;
return request;
}
-function parseAnswerHookRoute(value: unknown): AnswerHookRoute | undefined {
- if (value === null || typeof value !== "object" || !("runId" in value)) return undefined;
- if (typeof value.runId !== "string" || value.runId.length === 0) return undefined;
- if (!("question" in value) || value.question === undefined) return { runId: value.runId };
- const question = parseAnswerHookQuestion(value.question);
- return question === undefined ? undefined : { question, runId: value.runId };
+function parseInputRequestEvent(value: unknown): PendingInputBatchEvent | undefined {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
+ const sequence = Reflect.get(value, "sequence");
+ const stepIndex = Reflect.get(value, "stepIndex");
+ const turnId = Reflect.get(value, "turnId");
+ if (typeof sequence !== "number" || typeof stepIndex !== "number") return undefined;
+ if (typeof turnId !== "string") return undefined;
+ return { sequence, stepIndex, turnId };
}
-function parseAnswerHookQuestion(value: unknown): AnswerHookQuestion | undefined {
+function parseWorkflowAskRoute(value: unknown): WorkflowAskRoute | undefined {
+ if (value === null || typeof value !== "object") return undefined;
+ const control = Reflect.get(value, "control");
+ const runId = Reflect.get(value, "runId");
+ if (typeof control !== "string" || control.length === 0) return undefined;
+ if (typeof runId !== "string" || runId.length === 0) return undefined;
+ const question = parseProxyInputQuestion(Reflect.get(value, "question"));
+ if (question === undefined) return undefined;
+ return { control, question, runId };
+}
+
+function parseProxyInputQuestion(value: unknown): ProxyInputQuestion | undefined {
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
const question: {
allowFreeform?: boolean;
- dismissible?: boolean;
options?: readonly InputOption[];
} = {};
- for (const key of ["allowFreeform", "dismissible"] as const) {
- const flag = Reflect.get(value, key);
- if (flag === undefined) continue;
- if (typeof flag !== "boolean") return undefined;
- question[key] = flag;
+ const allowFreeform = Reflect.get(value, "allowFreeform");
+ if (allowFreeform !== undefined) {
+ if (typeof allowFreeform !== "boolean") return undefined;
+ question.allowFreeform = allowFreeform;
}
const options = Reflect.get(value, "options");
if (options !== undefined) {
@@ -391,17 +371,6 @@ function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
}
-function isAllowedChildResponseUrl(value: string): boolean {
- let url: URL;
- try {
- url = new URL(value);
- } catch {
- return false;
- }
- if (url.protocol === "https:") return true;
- return url.protocol === "http:" && isLoopbackHostname(url.hostname);
-}
-
function isInputRequestKind(value: unknown): value is InputRequestKind {
return typeof value === "string" && Object.hasOwn(PROXY_INPUT_REQUEST_KINDS, value);
}
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 c381993e7..66a2dee30 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
@@ -17,7 +17,6 @@ import {
SessionDynamicToolMetadataKey,
TurnDynamicToolMetadataKey,
StepDynamicToolMetadataKey,
- TurnTaskDeliveryKey,
} from "#context/keys.js";
import { setHarnessEmissionState } from "#harness/emission.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
@@ -28,7 +27,6 @@ import { getPendingInputBatches } from "#harness/pending-input-batches.js";
import { createToolLoopHarness } from "#harness/tool-loop.js";
import { setTurnUsageState } from "#harness/turn-tag-state.js";
import type { HarnessSession, ToolLoopHarnessConfig } from "#harness/types.js";
-import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
import { once } from "#tools/approval/policies.js";
import { defineTool } from "#tools/definition.js";
import {
@@ -835,21 +833,13 @@ describe("tool loop generate approval resume (real AI SDK)", () => {
});
});
- // Regression: turn-local context (task state, dynamic skill announcement) was
+ // Regression: turn-local context (a dynamic skill announcement) was
// appended as a user message after the approval response. The AI SDK reads
// approvals only from the tail tool message, so the approved tool never ran
// and the provider rejected the prompt with a tool call that had no output.
- it.each(
- [
- {
- label: "dynamic skill announcement",
- historyKey: "availableSkills" as const,
- },
- { label: "task state", historyKey: "taskState" as const },
- ].flatMap((context) => [false, true].map((restoredAnchor) => ({ ...context, restoredAnchor }))),
- )(
- "executes the approved tool when $label is injected on the resume step (restored anchor: $restoredAnchor)",
- async ({ historyKey, restoredAnchor }) => {
+ it.each([false, true])(
+ "executes the approved tool when a dynamic skill announcement is injected on the resume step (restored anchor: %s)",
+ async (restoredAnchor) => {
const siblingCall = {
input: { command: "whoami" },
toolCallId: "call-sibling",
@@ -862,7 +852,7 @@ describe("tool loop generate approval resume (real AI SDK)", () => {
toolName: "bash",
type: "tool-result" as const,
};
- let session = appendPendingInputBatch({
+ const session = appendPendingInputBatch({
requests: [pendingApprovalInputRequest],
// The parked shape when a gated call shares a step with an ungated one.
responseMessages: [
@@ -872,27 +862,8 @@ describe("tool loop generate approval resume (real AI SDK)", () => {
session: createBaseSession(),
});
const ctx = new ContextContainer();
- const runtimeContextAnnouncement =
- historyKey === "taskState"
- ? '[Task state]\n{"tasks":[{"name":"analysis","status":"pending","taskId":"analysis"}]}'
- : "Available skills\n- policy: Tenant policy";
- if (historyKey === "taskState") {
- ctx.set(TurnTaskDeliveryKey, "initiating");
- session = registerWorkflowToolRun(session, {
- callId: "analysis",
- toolName: "analysis",
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "report-probe", name: "analysis" },
- taskId: "analysis",
- },
- });
- } else {
- ctx.set(PendingSkillAnnouncementKey, runtimeContextAnnouncement);
- }
+ const runtimeContextAnnouncement = "Available skills\n- policy: Tenant policy";
+ ctx.set(PendingSkillAnnouncementKey, runtimeContextAnnouncement);
const execute = vi.fn(async () => "/workspace");
const model = createModel();
const runStep = createToolLoopHarness(createConfig(model, execute));
@@ -950,7 +921,9 @@ describe("tool loop generate approval resume (real AI SDK)", () => {
(message) => message.content === runtimeContextAnnouncement,
),
).toHaveLength(1);
- expect(ctx.get(HistoryStateKey)).toMatchObject({ [historyKey]: runtimeContextAnnouncement });
+ expect(ctx.get(HistoryStateKey)).toMatchObject({
+ availableSkills: runtimeContextAnnouncement,
+ });
},
);
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index 4d9369a1c..52ac9fe01 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -2,7 +2,6 @@ import { context as otelContext, trace } from "#compiled/@opentelemetry/api/inde
import {
type FilePart,
jsonSchema,
- type LanguageModelCallEndEvent,
type LanguageModel,
type ModelMessage,
ToolLoopAgent,
@@ -21,23 +20,17 @@ import {
ChannelInstrumentationKey,
ConversationIdKey,
HistoryStateKey,
- InitiatorAuthKey,
LiveStepDynamicModelSelectionKey,
ParentSessionKey,
SandboxKey,
- ScheduleIdKey,
SessionTraceSeedKey,
SessionKey,
SessionIdKey,
SessionDynamicInstructionsKey,
SessionDynamicModelReferenceKey,
- SessionDynamicSubagentSelectionsKey,
SessionDynamicToolMetadataKey,
StepDynamicToolMetadataKey,
- TurnTaskDeliveryKey,
- TaskDeliveryPolicyKey,
} from "#context/keys.js";
-import { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";
import { invocationOwnerKey } from "#internal/invocation/metadata.js";
import { decodeSandboxRef, isSandboxRefUrl } from "#internal/attachments/sandbox-refs.js";
import { attachClientContext } from "#internal/client-context.js";
@@ -46,7 +39,6 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import type { InstrumentationStepStartedEventInput } 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 { ChannelAudience } from "#shared/channel-audience.js";
@@ -60,7 +52,6 @@ import { compactMessages, shouldCompact } from "#harness/compaction.js";
import {
createFrameworkUserMessage,
createUserMessage,
- markFrameworkStepInput,
type HarnessModelMessage,
} from "#harness/messages.js";
import {
@@ -79,11 +70,8 @@ import {
appendPendingInputBatch,
} from "#harness/input-requests.js";
import { getDeferredStepInput } from "#harness/pending-input-batches.js";
-import { activeTurnId } from "#harness/active-turn-id.js";
-import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.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 { PendingSkillAnnouncementKey } from "#context/dynamic-skill-lifecycle.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
import { stashToolInterrupt } from "#harness/tool-interrupts.js";
@@ -105,14 +93,6 @@ import {
type SessionInstrumentation,
} from "#instrumentation/runtime.js";
import type { RuntimeContextResolver } from "#tracing/otel-declaration.js";
-import {
- CONDITIONAL_DELIVERY_INSTRUCTION,
- EMPTY_DELIVERY_SENTINEL,
-} from "#shared/empty-delivery.js";
-import {
- TASK_DELIVERY_INITIATING_INSTRUCTION,
- TASK_DELIVERY_SETTLED_INSTRUCTION,
-} from "#tasks/delivery-context.js";
import { captureLogRecords } from "#internal/testing/log-records.js";
// The harness runs outside a workflow body here, where run attributes cannot
@@ -302,24 +282,6 @@ function createTestSession(overrides?: Partial<HarnessSession>): HarnessSession
};
}
-const analysisTaskAnnouncement =
- '[Task state]\n{"tasks":[{"name":"analysis","status":"pending","taskId":"analysis"}]}';
-
-function recordBackgroundTask(session: HarnessSession, taskId = "analysis"): HarnessSession {
- return registerWorkflowToolRun(session, {
- callId: taskId,
- toolName: { kind: "report-probe", name: taskId }.name,
- lifetime: "session" as const,
- origin: { turnId: activeTurnId(getHarnessEmissionState(session.state)), stepIndex: 0 },
- address: { runId: `run-${taskId}`, hookToken: `token-${taskId}` },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata: { kind: "report-probe", name: taskId },
- taskId,
- },
- });
-}
-
function createTestConfig(
emit?: HarnessEmitFn,
overrides?: Partial<ToolLoopHarnessConfig>,
@@ -367,28 +329,6 @@ function createDelegationToolMap(): ToolLoopHarnessConfig["tools"] {
]);
}
-function createScheduleContext(): ContextContainer {
- const ctx = new ContextContainer();
- ctx.set(AuthKey, SCHEDULE_APP_AUTH);
- ctx.set(InitiatorAuthKey, SCHEDULE_APP_AUTH);
- ctx.set(ScheduleIdKey, "test-schedule");
- return ctx;
-}
-
-function createScheduledUserContext(): ContextContainer {
- const auth = {
- attributes: {},
- authenticator: "fixture-user",
- principalId: "scheduled-owner",
- principalType: "user" as const,
- };
- const ctx = new ContextContainer();
- ctx.set(AuthKey, auth);
- ctx.set(InitiatorAuthKey, auth);
- ctx.set(ScheduleIdKey, "dynamic-tasks");
- return ctx;
-}
-
function setDelegatedParent(ctx: ContextContainer): void {
ctx.set(ParentSessionKey, {
callId: "call-parent",
@@ -1112,84 +1052,6 @@ describe("createToolLoopHarness", () => {
]);
});
- it.each([
- ["literal", EMPTY_DELIVERY_SENTINEL],
- ["HTML-escaped", "&lt;eve-empty-delivery/&gt;"],
- ])(
- "parks without delivery when a terminal response is only the %s sentinel",
- async (_, sentinel) => {
- const message = ` \n${sentinel}\t `;
- setupMockAgent({
- finishReason: "stop",
- response: {
- messages: [
- {
- content: message,
- role: "assistant",
- },
- ],
- },
- text: message,
- toolCalls: [],
- toolResults: [],
- });
-
- const { emit, events } = createEventCollector();
- const runStep = createToolLoopHarness(createTestConfig(emit));
-
- const result = await runStep(createTestSession(), { message: "Hi" });
-
- expect(result.next).toBeNull();
- expect(result.session.history).toEqual([
- { content: "Hi", kind: "user" as const, role: "user" },
- ]);
- expect(vi.mocked(ToolLoopAgent).mock.calls.length).toBe(1);
- expect(events).toContainEqual(
- expect.objectContaining({
- data: expect.objectContaining({ message: null }),
- type: "message.completed",
- }),
- );
- },
- );
-
- it.each([EMPTY_DELIVERY_SENTINEL, "&lt;eve-empty-delivery/&gt;"])(
- "delivers and persists explanations that quote %s",
- async (sentinel) => {
- const message = `The pending-task instruction requires \`${sentinel}\` and no other text.`;
- setupMockAgent({
- finishReason: "stop",
- response: { messages: [{ content: message, role: "assistant" }] },
- text: message,
- toolCalls: [],
- toolResults: [],
- });
-
- const { emit, events } = createEventCollector();
- const runStep = createToolLoopHarness(createTestConfig(emit));
- const result = await runStep(createTestSession(), { message: "Hi" });
-
- expect(result.next).toBeNull();
- expect(result.session.history).toEqual([
- { content: "Hi", kind: "user" as const, role: "user" },
- { content: message, role: "assistant" },
- ]);
- expect(vi.mocked(ToolLoopAgent).mock.calls.length).toBe(1);
- expect(events).toContainEqual(
- expect.objectContaining({
- data: expect.objectContaining({ message }),
- type: "message.completed",
- }),
- );
- expect(events).not.toContainEqual(
- expect.objectContaining({
- data: expect.objectContaining({ message: null }),
- type: "message.completed",
- }),
- );
- },
- );
-
it("keeps executable tools directly available to the model", async () => {
setupMockAgent({
finishReason: "stop",
@@ -1211,82 +1073,6 @@ describe("createToolLoopHarness", () => {
expect(agentCall!.tools).not.toHaveProperty("Workflow");
});
- it("registers atomic background tool calls before AI SDK execution", async () => {
- setupMockAgent({
- finishReason: "stop",
- response: { messages: [{ content: "Hello!", role: "assistant" }] },
- text: "Hello!",
- toolCalls: [],
- toolResults: [],
- });
-
- const runStep = createToolLoopHarness(
- createTestConfig(undefined, {
- tools: new Map([
- [
- "background_work",
- {
- description: "Start background work.",
- execute: vi.fn(),
- execution: "background" as const,
- inputSchema: jsonSchema({ type: "object" }),
- name: "background_work",
- workflowId: "workflow//test//background_work",
- },
- ],
- ]),
- }),
- );
- await runStep(createTestSession(), { message: "Hi" });
-
- const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0] as
- | (ConstructorParameters<typeof ToolLoopAgent>[0] & {
- onLanguageModelCallEnd?: (event: LanguageModelCallEndEvent) => Promise<void> | void;
- })
- | undefined;
- const backgroundTool = agentCall?.tools?.background_work as
- | {
- execute?: (input: unknown, options: { toolCallId: string }) => Promise<unknown>;
- onInputAvailable?: (input: {
- input: unknown;
- toolCallId: string;
- }) => Promise<void> | void;
- }
- | undefined;
- expect(agentCall?.onLanguageModelCallEnd).toBeTypeOf("function");
- expect(backgroundTool?.onInputAvailable).toBeTypeOf("function");
-
- await backgroundTool!.onInputAvailable!({ input: { value: 1 }, toolCallId: "call-a" });
- await agentCall!.onLanguageModelCallEnd!({
- content: [
- {
- input: { value: 1 },
- toolCallId: "call-a",
- toolName: "background_work",
- type: "tool-call",
- },
- {
- input: { value: 2 },
- toolCallId: "call-b",
- toolName: "background_work",
- type: "tool-call",
- },
- ],
- } as never);
-
- let registeredCallIds: string[] = [];
- const ctx = new ContextContainer();
- ctx.set(BackgroundToolExecutorKey, {
- async execute({ batch }) {
- registeredCallIds = batch.calls.map((call) => call.callId);
- return { ok: true };
- },
- });
- await contextStorage.run(ctx, () => backgroundTool!.execute!({}, { toolCallId: "call-a" }));
-
- expect(registeredCallIds).toEqual(["call-a", "call-b"]);
- });
-
it("announces parked agents as user-role content before the user message, outside the system prompt", async () => {
setupMockAgent({
finishReason: "stop",
@@ -1844,72 +1630,6 @@ describe("createToolLoopHarness", () => {
]);
});
- it("does not park dynamic background subagent calls on the turn", async () => {
- setupMockAgent({
- finishReason: "tool-calls",
- response: {
- messages: [
- {
- content: [
- {
- input: { message: "investigate" },
- toolCallId: "call-dynamic",
- toolName: "researcher",
- type: "tool-call",
- },
- ],
- role: "assistant",
- },
- ],
- },
- text: "",
- toolCalls: [
- {
- input: { message: "investigate" },
- toolCallId: "call-dynamic",
- toolName: "researcher",
- type: "tool-call",
- },
- ],
- toolResults: [],
- });
- const ctx = new ContextContainer();
- ctx.set(SessionDynamicSubagentSelectionsKey, {
- "subagents/researcher": {
- agentConfig: {
- description: "Research the request.",
- model: { id: "openai/gpt-5.5" },
- },
- kind: "subagent",
- prepared: createPreparedRuntimeSubagentTool({
- description: "Research the request.",
- kind: "subagent",
- logicalPath: "subagents/researcher",
- name: "researcher",
- nodeId: "subagents/researcher",
- sourceId: "subagents/researcher",
- sourceKind: "module",
- }),
- },
- });
- const { emit, events } = createEventCollector();
- const runStep = createToolLoopHarness(createTestConfig(emit));
-
- const result = await contextStorage.run(ctx, () =>
- runStep(createTestSession(), { message: "Research this." }),
- );
-
- expect(events.find((event) => event.type === "actions.requested")?.data.actions).toEqual([
- expect.objectContaining({
- callId: "call-dynamic",
- input: { message: "investigate" },
- kind: "tool-call",
- toolName: "researcher",
- }),
- ]);
- expect(getPendingCoordinationBatch(result.session.state)).toBeUndefined();
- });
-
it("parks on both batches when one step carries a workflow task and an approval", async () => {
const gateToolCall = {
input: { action: "run" },
@@ -5605,7 +5325,6 @@ describe("createToolLoopHarness", () => {
kind: "execution.retry",
role: "user",
});
- expect(reissueMessages.at(-1)?.content).not.toContain(EMPTY_DELIVERY_SENTINEL);
expect(
result.session.history.some(
(message) =>
@@ -5787,122 +5506,6 @@ describe("createToolLoopHarness", () => {
}
});
- it("offers conditional delivery on an empty-response retry for a scheduled turn", async () => {
- setupFirstThenAgent(emptyResult, successResult);
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
- const { emit } = createEventCollector();
- const runStep = createToolLoopHarness(createTestConfig(emit));
-
- try {
- await contextStorage.run(createScheduleContext(), () =>
- runStep(createTestSession(), { message: "Check for alerts." }),
- );
-
- const reissueAgent = vi.mocked(ToolLoopAgent).mock.results[1]?.value as {
- stream: ReturnType<typeof vi.fn>;
- };
- const reissueMessages = reissueAgent.stream.mock.calls[0]?.[0]?.messages as Array<{
- content: unknown;
- role: string;
- }>;
- expect(reissueMessages.at(-1)).toMatchObject({
- content: expect.stringContaining(EMPTY_DELIVERY_SENTINEL),
- kind: "execution.retry",
- role: "user",
- });
- } finally {
- warnSpy.mockRestore();
- }
- });
-
- it("does not offer silent delivery on an initiating-task retry", async () => {
- setupFirstThenAgent(emptyResult, successResult);
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
- const { emit } = createEventCollector();
- const runStep = createToolLoopHarness(createTestConfig(emit));
- const ctx = new ContextContainer();
- ctx.set(TurnTaskDeliveryKey, "initiating");
-
- try {
- await contextStorage.run(ctx, () =>
- runStep(createTestSession(), { message: "[Task state]" }),
- );
-
- const reissueAgent = vi.mocked(ToolLoopAgent).mock.results[1]?.value as {
- stream: ReturnType<typeof vi.fn>;
- };
- const reissueMessages = reissueAgent.stream.mock.calls[0]?.[0]?.messages as Array<{
- content: unknown;
- role: string;
- }>;
- expect(reissueMessages.at(-1)).toMatchObject({
- content: expect.stringContaining("was not delivered"),
- kind: "execution.retry",
- role: "user",
- });
- expect(reissueMessages.at(-1)?.content).not.toContain(EMPTY_DELIVERY_SENTINEL);
- } finally {
- warnSpy.mockRestore();
- }
- });
-
- it("offers silent delivery on a user-auth scheduled initiating retry", async () => {
- setupFirstThenAgent(emptyResult, successResult);
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
- const { emit } = createEventCollector();
- const runStep = createToolLoopHarness(createTestConfig(emit));
- const ctx = createScheduledUserContext();
- ctx.set(TurnTaskDeliveryKey, "initiating");
-
- try {
- await contextStorage.run(ctx, () =>
- runStep(createTestSession(), { message: "[Task state]" }),
- );
-
- const reissueAgent = vi.mocked(ToolLoopAgent).mock.results[1]?.value as {
- stream: ReturnType<typeof vi.fn>;
- };
- const reissueMessages = reissueAgent.stream.mock.calls[0]?.[0]?.messages as Array<{
- content: unknown;
- role: string;
- }>;
- expect(reissueMessages.at(-1)?.content).toContain(EMPTY_DELIVERY_SENTINEL);
- } finally {
- warnSpy.mockRestore();
- }
- });
-
- it("does not offer conditional delivery on a scheduled retry with an output schema", async () => {
- setupFirstThenAgent(emptyResult, finalOutputResult("Done.", { status: "ok" }));
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
- const { emit } = createEventCollector();
- const runStep = createToolLoopHarness(createTestConfig(emit));
-
- try {
- await contextStorage.run(createScheduleContext(), () =>
- runStep(createTestSession({ outputSchema: { type: "object" } }), {
- message: "Check for alerts.",
- }),
- );
-
- const reissueAgent = vi.mocked(ToolLoopAgent).mock.results[1]?.value as {
- stream: ReturnType<typeof vi.fn>;
- };
- const reissueMessages = reissueAgent.stream.mock.calls[0]?.[0]?.messages as Array<{
- content: unknown;
- role: string;
- }>;
- expect(reissueMessages.at(-1)).toMatchObject({
- content: expect.stringContaining("was not delivered"),
- kind: "execution.retry",
- role: "user",
- });
- expect(reissueMessages.at(-1)?.content).not.toContain(EMPTY_DELIVERY_SENTINEL);
- } finally {
- warnSpy.mockRestore();
- }
- });
-
it("reissues a blank 'stop' response instead of treating it as intentional silence", async () => {
setupFirstThenAgent(emptyStopResult, successResult);
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
@@ -9415,12 +9018,12 @@ describe("createToolLoopHarness", () => {
history: [{ content: "old message", kind: "user" as const, role: "user" }],
});
const ctx = new ContextContainer();
- ctx.set(HistoryStateKey, { taskState: "old message" });
+ ctx.set(HistoryStateKey, { availableSkills: "old message" });
const result = await contextStorage.run(ctx, () => runStep(session));
expect(result.next).toBeNull();
expect(result.session).toBe(session);
- expect(ctx.get(HistoryStateKey)).toEqual({ taskState: "old message" });
+ expect(ctx.get(HistoryStateKey)).toEqual({ availableSkills: "old message" });
expect(getCompatibilityEventTypes(events)).toEqual(["compaction.requested", "session.waiting"]);
expect(ToolLoopAgent).not.toHaveBeenCalled();
expect(logs.records).toContainEqual(
@@ -11927,8 +11530,9 @@ describe("createToolLoopHarness", () => {
toolCalls: [toolCall],
toolResults: [{ ...toolResult, input: toolCall.input }],
});
+ const announcement = "Available skills\n- policy: Tenant policy";
const ctx = new ContextContainer();
- ctx.set(TurnTaskDeliveryKey, "initiating");
+ ctx.set(PendingSkillAnnouncementKey, announcement);
const runStep = createToolLoopHarness(
createTestConfig(undefined, {
historyProjector:
@@ -11950,7 +11554,7 @@ describe("createToolLoopHarness", () => {
const input = { context: ["Current channel context"], message: "Add 20 and 22." };
const first = await contextStorage.run(ctx, () =>
runStep(
- recordBackgroundTask(initial),
+ initial,
withClientContext ? attachClientContext(input, ["Client context"]) : input,
),
);
@@ -11958,26 +11562,23 @@ describe("createToolLoopHarness", () => {
const firstPrompt = structuredClone(getLastAgentSettings().messages);
expect(first.session.history).toContainEqual({
role: "user",
- content: analysisTaskAnnouncement,
+ content: announcement,
kind: "context.state",
});
const nextState = changed
- ? '[Task state]\n{"tasks":[{"name":"analysis","status":"pending","taskId":"analysis"},{"name":"verification","status":"pending","taskId":"verification"}]}'
- : analysisTaskAnnouncement;
+ ? "Available skills\n- policy: Tenant policy\n- billing: Billing policy"
+ : announcement;
const nextContext = await deserializeContext(
JSON.parse(JSON.stringify(serializeContext(ctx))),
);
+ nextContext.set(PendingSkillAnnouncementKey, nextState);
setupMockAgent(defaultModelResult());
const restored = JSON.parse(JSON.stringify(first.session)) as HarnessSession;
- await contextStorage.run(nextContext, () =>
- runStep(changed ? recordBackgroundTask(restored, "verification") : restored),
- );
+ await contextStorage.run(nextContext, () => runStep(restored));
const nextPrompt = getLastAgentSettings().messages;
expect(nextPrompt.slice(0, firstPrompt.length)).toEqual(firstPrompt);
- expect(
- nextPrompt.filter((message) => message.content === analysisTaskAnnouncement),
- ).toHaveLength(1);
- expect(nextContext.get(HistoryStateKey)).toMatchObject({ taskState: nextState });
+ expect(nextPrompt.filter((message) => message.content === announcement)).toHaveLength(1);
+ expect(nextContext.get(HistoryStateKey)).toMatchObject({ availableSkills: nextState });
if (changed) {
expect(nextPrompt.at(-1)).toEqual({
role: "user",
@@ -12113,19 +11714,13 @@ describe("createToolLoopHarness", () => {
async (replacement) => {
const ctx = new ContextContainer();
const availableSkills = "Available skills\n- policy: Tenant policy";
- const taskState = analysisTaskAnnouncement;
ctx.set(PendingSkillAnnouncementKey, availableSkills);
- ctx.set(TurnTaskDeliveryKey, "initiating");
const runStep = createToolLoopHarness(createTestConfig());
setupMockAgent(defaultModelResult());
const first = await contextStorage.run(ctx, () =>
- runStep(recordBackgroundTask(createTestSession()), { message: "Check progress." }),
+ runStep(createTestSession(), { message: "Check progress." }),
);
- const expectedState = {
- availableSkills,
- taskState,
- deliveryInstruction: TASK_DELIVERY_INITIATING_INSTRUCTION,
- };
+ const expectedState = { availableSkills };
expect(ctx.get(HistoryStateKey)).toEqual(expectedState);
vi.mocked(compactMessages).mockResolvedValue([
@@ -12231,279 +11826,6 @@ describe("createToolLoopHarness", () => {
expect(instructions).toBe("You are a test assistant.");
});
- it("adds conditional-delivery guidance to a top-level scheduled turn", async () => {
- setupMockAgent(defaultModelResult());
- const runStep = createToolLoopHarness(createTestConfig());
-
- await contextStorage.run(createScheduleContext(), () =>
- runStep(createTestSession(), { message: "Check for alerts." }),
- );
-
- const { instructions, messages } = getLastAgentSettings();
- expect(instructions).toBe("You are a test assistant.");
- expect(messages).toContainEqual({
- role: "user",
- content: CONDITIONAL_DELIVERY_INSTRUCTION,
- kind: "context.instruction",
- });
- });
-
- it("does not add conditional-delivery guidance when a scheduled turn has an output schema", async () => {
- setupMockAgent(finalOutputResult("Done.", { status: "ok" }));
- const runStep = createToolLoopHarness(createTestConfig());
-
- await contextStorage.run(createScheduleContext(), () =>
- runStep(createTestSession({ outputSchema: { type: "object" } }), {
- message: "Check for alerts.",
- }),
- );
-
- const { instructions } = getLastAgentSettings();
- expect(instructions).toBe("You are a test assistant.");
- });
-
- it("adds initiating task-reporting guidance without enabling silent delivery", async () => {
- setupMockAgent(defaultModelResult());
- const runStep = createToolLoopHarness(createTestConfig());
- const ctx = new ContextContainer();
- ctx.set(TurnTaskDeliveryKey, "initiating");
-
- await contextStorage.run(ctx, () =>
- runStep(recordBackgroundTask(createTestSession()), {
- message: "Start the background work.",
- }),
- );
-
- const { instructions, messages } = getLastAgentSettings();
- expect(instructions).toBe("You are a test assistant.");
- expect(messages.slice(0, 2)).toEqual([
- { role: "user", content: analysisTaskAnnouncement, kind: "context.state" },
- {
- role: "user",
- content: TASK_DELIVERY_INITIATING_INSTRUCTION,
- kind: "context.instruction",
- },
- ]);
- });
-
- it("routes later-turn initiating task context through user messages", async () => {
- setupMockAgent(defaultModelResult());
- const runStep = createToolLoopHarness(createTestConfig());
- const ctx = new ContextContainer();
- const taskState = analysisTaskAnnouncement;
- ctx.set(TurnTaskDeliveryKey, "initiating");
- const session = setHarnessEmissionState(createTestSession(), {
- sequence: 1,
- sessionStarted: true,
- stepIndex: 0,
- turnId: "",
- });
-
- await contextStorage.run(ctx, () =>
- runStep(recordBackgroundTask(session), { message: "Start the background work." }),
- );
-
- const { instructions, messages } = getLastAgentSettings();
- expect(instructions).toBe("You are a test assistant.");
- expect(messages.slice(-3)).toEqual([
- { role: "user", content: taskState, kind: "context.state" },
- {
- role: "user",
- content: TASK_DELIVERY_INITIATING_INSTRUCTION,
- kind: "context.instruction",
- },
- { kind: "user" as const, role: "user", content: "Start the background work." },
- ]);
- });
-
- it.each(["none", "pending", "settled"] as const)(
- "does not inject initiating task state during the %s phase",
- async (phase) => {
- setupMockAgent(defaultModelResult());
- const ctx = new ContextContainer();
- ctx.set(TurnTaskDeliveryKey, phase);
- await contextStorage.run(ctx, () =>
- createToolLoopHarness(createTestConfig())(recordBackgroundTask(createTestSession()), {
- message: "Check progress.",
- }),
- );
- expect(getLastAgentSettings().messages).not.toContainEqual({
- kind: "user" as const,
- role: "user",
- content: analysisTaskAnnouncement,
- });
- expect(ctx.get(HistoryStateKey)?.taskState).toBeUndefined();
- },
- );
-
- it("keeps a scheduled initiating task turn conditionally deliverable", async () => {
- setupMockAgent(defaultModelResult());
- const runStep = createToolLoopHarness(createTestConfig());
- const ctx = createScheduledUserContext();
- ctx.set(TurnTaskDeliveryKey, "initiating");
-
- await contextStorage.run(ctx, () =>
- runStep(createTestSession(), { message: "[Task state]" }),
- );
-
- const { instructions, messages } = getLastAgentSettings();
- expect(instructions).toBe("You are a test assistant.");
- expect(messages).toContainEqual({
- role: "user",
- content: CONDITIONAL_DELIVERY_INSTRUCTION,
- kind: "context.instruction",
- });
- });
-
- it("does not apply session schedule provenance to a later human turn", async () => {
- setupMockAgent(defaultModelResult());
- const runStep = createToolLoopHarness(createTestConfig());
- const ctx = createScheduledUserContext();
- const session = setHarnessEmissionState(createTestSession(), {
- sequence: 1,
- sessionStarted: true,
- stepIndex: 0,
- turnId: "",
- });
-
- await contextStorage.run(ctx, () => runStep(session, { message: "What happened?" }));
-
- expect(getLastAgentSettings().instructions).toBe("You are a test assistant.");
- });
-
- it("does not inject or retain silence guidance after a pending task wake", async () => {
- setupMockAgent(defaultModelResult());
- const runStep = createToolLoopHarness(createTestConfig());
- const ctx = new ContextContainer();
- ctx.set(TurnTaskDeliveryKey, "pending");
- const session = setHarnessEmissionState(createTestSession(), {
- sequence: 1,
- sessionStarted: true,
- stepIndex: 0,
- turnId: "",
- });
-
- const first = await contextStorage.run(ctx, () =>
- runStep(
- session,
- markFrameworkStepInput(
- { message: "Background task task_1 is completed." },
- "execution.background_task",
- ),
- ),
- );
- expect(getLastAgentSettings().messages).toEqual([
- {
- role: "user",
- content: "Background task task_1 is completed.",
- kind: "execution.background_task",
- },
- ]);
- expect(ctx.get(HistoryStateKey)?.deliveryInstruction).toBeUndefined();
-
- ctx.set(TurnTaskDeliveryKey, "none");
- await contextStorage.run(ctx, () =>
- runStep(first.session, { message: "What is 7 times 8?" }),
- );
- expect(getLastAgentSettings().messages).toEqual([
- ...first.session.history,
- { kind: "user" as const, role: "user", content: "What is 7 times 8?" },
- ]);
- });
-
- it.each(["pending", "settled"] as const)(
- "auto permits a silent %s result turn",
- async (phase) => {
- setupMockAgent({
- finishReason: "stop",
- response: { messages: [{ role: "assistant", content: EMPTY_DELIVERY_SENTINEL }] },
- text: EMPTY_DELIVERY_SENTINEL,
- toolCalls: [],
- toolResults: [],
- });
- const ctx = new ContextContainer();
- ctx.set(TurnTaskDeliveryKey, phase);
- ctx.set(TaskDeliveryPolicyKey, "auto");
- const { emit, events } = createEventCollector();
- const runStep = createToolLoopHarness(createTestConfig(emit));
- const result = await contextStorage.run(ctx, () =>
- runStep(
- createTestSession(),
- markFrameworkStepInput(
- { message: "Background task A completed." },
- "execution.background_task",
- ),
- ),
- );
- expect(result.next).toBeNull();
- expect(getLastAgentSettings().messages).toContainEqual(
- expect.objectContaining({
- content: expect.stringContaining("previously withheld results"),
- }),
- );
- expect(events).toContainEqual(
- expect.objectContaining({
- type: "message.completed",
- data: expect.objectContaining({ message: null }),
- }),
- );
- expect(vi.mocked(ToolLoopAgent)).toHaveBeenCalledTimes(1);
- },
- );
-
- it("adds settled task-delivery guidance to a top-level framework wake", async () => {
- setupMockAgent(defaultModelResult());
- const runStep = createToolLoopHarness(createTestConfig());
- const ctx = new ContextContainer();
- ctx.set(TurnTaskDeliveryKey, "settled");
- const session = setHarnessEmissionState(createTestSession(), {
- sequence: 1,
- sessionStarted: true,
- stepIndex: 0,
- turnId: "",
- });
-
- await contextStorage.run(ctx, () =>
- runStep(
- session,
- markFrameworkStepInput(
- { message: "Background task task_1 is completed." },
- "execution.background_task",
- ),
- ),
- );
-
- const { instructions, messages } = getLastAgentSettings();
- expect(instructions).toBe("You are a test assistant.");
- expect(messages.slice(-2)).toEqual([
- {
- role: "user",
- content: TASK_DELIVERY_SETTLED_INSTRUCTION,
- kind: "context.instruction",
- },
- {
- role: "user",
- content: "Background task task_1 is completed.",
- kind: "execution.background_task",
- },
- ]);
- });
-
- it("does not add conditional-delivery guidance to a task-owned conversation child", async () => {
- setupMockAgent(defaultModelResult());
- const runStep = createToolLoopHarness(createTestConfig());
- const ctx = new ContextContainer();
- ctx.set(TurnTaskDeliveryKey, "pending");
- setDelegatedParent(ctx);
-
- await contextStorage.run(ctx, () =>
- runStep(createTestSession(), { message: "Resume after HITL." }),
- );
-
- const { instructions } = getLastAgentSettings();
- expect(instructions).toBe("You are a test assistant.");
- });
-
it("routes dynamic instruction messages from durable keys into instructions", async () => {
setupMockAgent(defaultModelResult());
const runStep = createToolLoopHarness(createTestConfig());
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index 6ea414e73..8bae640bc 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -31,11 +31,8 @@ import {
AuthKey,
HistoryStateKey,
ParentSessionKey,
- ScheduleIdKey,
SessionCallbackKey,
StaticModelReferenceKey,
- TurnTaskDeliveryKey,
- TaskDeliveryPolicyKey,
} from "#context/keys.js";
import {
buildDynamicInstructionMessages,
@@ -71,7 +68,7 @@ import {
} from "#protocol/message.js";
import type { RuntimeTraceContext } from "#protocol/message.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { projectParkedAgentHandles, resolveAgentsAnnouncement } from "#subagents/handles/prompt.js";
+import { resolveAgentsAnnouncement } from "#subagents/handles/prompt.js";
import { getAgentHandleStore } from "#subagents/handles/store.js";
import type { InputRequest } from "#shared/input.js";
import {
@@ -182,15 +179,8 @@ import {
import { summarizeKnownError, type SemanticErrorSummary } from "#harness/semantic-errors/index.js";
import { isTurnCancellation, throwIfTurnAborted } from "#harness/turn-cancellation.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
-import { EMPTY_DELIVERY_SENTINEL, hasEmptyDeliverySentinel } from "#shared/empty-delivery.js";
-import { resolveDeliveryPolicy } from "#tasks/delivery-policy.js";
-import { resolveInitiatingTaskContext } from "#tasks/delivery-context.js";
import { extractWorkflowStreamWriteErrorDetails } from "#harness/workflow-stream-error.js";
import { getAdvertisedTools } from "#harness/advertised-tools.js";
-import {
- BackgroundToolExecutorKey,
- createBackgroundToolCallBatch,
-} from "#harness/background-tools.js";
import {
applyLastToolCacheBreakpoint,
applySystemCacheBreakpoint,
@@ -946,7 +936,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
isHarnessBetweenTurns(pending.session) &&
getPendingAuthorization(pending.session.state) === undefined
) {
- // Like a conversation turn, a completed response may wait while background work continues.
await emit?.(createSessionWaitingEvent());
}
return { next: null, session: pending.session };
@@ -1120,21 +1109,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
// rationale (assistant-final rejection, prompt-cache preservation).
const agentStore = getAgentHandleStore(session.state);
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,
});
@@ -1263,17 +1238,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
),
);
- const isFirstTurn = emissionState.sequence === 0;
- const hasScheduleProvenance = isFirstTurn && ctx?.get(ScheduleIdKey) !== undefined;
- const deliveryPolicy = resolveDeliveryPolicy({
- hasScheduleProvenance,
- hasOutputSchema: session.outputSchema !== undefined,
- isChild: ctx?.get(ParentSessionKey) !== undefined,
- isFirstTurn,
- taskDeliveryPhase: ctx?.get(TurnTaskDeliveryKey),
- taskDeliveryPolicy: ctx?.get(TaskDeliveryPolicyKey),
- });
-
// --- Execute via ToolLoopAgent ------------------------------------------
/*
@@ -1292,14 +1256,8 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
if (ctx !== undefined) {
currentMessages.addSystem(buildDynamicInstructionMessages(ctx));
}
- const taskContext =
- ctx?.get(TurnTaskDeliveryKey) === "initiating"
- ? resolveInitiatingTaskContext({ state: session.state, turnId })
- : undefined;
currentMessages.addAnnouncements({
availableSkills: ctx?.get(PendingSkillAnnouncementKey),
- taskState: taskContext?.context,
- deliveryInstruction: deliveryPolicy.instruction,
});
const pendingApprovals = renderPendingApprovalsInstruction(
getPendingInputBatches(session.state).flatMap((batch) => batch.requests),
@@ -1412,7 +1370,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const prepareModelTools = async (opts: ModelCallOptions) => {
const harnessTools = buildHarnessToolsWithDynamicSubagents(config.tools, ctx);
- const backgroundBatch = createBackgroundToolCallBatch();
const advertisedHarnessTools = getAdvertisedTools({
session,
tools: harnessTools,
@@ -1421,7 +1378,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const flatTools = await buildToolSetWithProviderTools({
approvedTools,
- backgroundBatch,
disabledProviderTools: opts.disabledProviderTools,
modelReference: requireSessionModelReference(session),
tools: advertisedHarnessTools,
@@ -1437,14 +1393,13 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
});
const dynamicToolSet = buildToolSetFromDefinitions({
approvedTools,
- backgroundBatch,
disabledProviderTools: opts.disabledProviderTools,
tools: dynamicTools,
});
// Dynamic tools override a same-named authored tool.
for (const [name, toolDefinition] of Object.entries(dynamicToolSet)) {
const advertised = advertisedHarnessTools.get(name);
- if (advertised?.runtimeAction !== undefined || advertised?.workflowId !== undefined) {
+ if (advertised?.workflowId !== undefined) {
throw new Error(
`Dynamic tool "${name}" collides with a coordination-visible deferred tool.`,
);
@@ -1487,33 +1442,15 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
generation.protectToolExecution();
return execute(...args);
};
- const onInputAvailable = tool.onInputAvailable;
- if (onInputAvailable !== undefined)
- tool.onInputAvailable = (...args: Parameters<typeof onInputAvailable>) => {
- generation.protectToolExecution();
- return onInputAvailable(...args);
- };
}
- return {
- effectiveTools,
- backgroundBatch,
- advertisedHarnessTools,
- modelTools,
- presentationTools,
- };
+ return { effectiveTools, modelTools, presentationTools };
};
const runSingleModelCall = async (
opts: ModelCallOptions & { readonly attemptIndex: number },
): Promise<HarnessStepResult> => {
- let {
- effectiveTools,
- backgroundBatch,
- advertisedHarnessTools,
- modelTools,
- presentationTools,
- } = await prepareModelTools(opts);
+ let { effectiveTools, modelTools, presentationTools } = await prepareModelTools(opts);
currentMessages = createRequestMessages();
requestEnvelopeTokens = await estimateRequestEnvelope({
history: projectedMessages,
@@ -1569,13 +1506,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
normalizeModelMessages(projectHistory(createModelMessages(messages), session.state)),
);
currentMessages = createRequestMessages();
- ({
- effectiveTools,
- backgroundBatch,
- advertisedHarnessTools,
- modelTools,
- presentationTools,
- } = await prepareModelTools(opts));
+ ({ effectiveTools, modelTools, presentationTools } = await prepareModelTools(opts));
requestEnvelopeTokens = await estimateRequestEnvelope({
history: projectedMessages,
instructions: prepareModelInstructions(opts.extraSystemNote),
@@ -1636,20 +1567,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
usage: event.usage,
costUsd: extractGatewayCostUsd(event.providerMetadata),
});
- for (const part of event.content) {
- if (
- part.type !== "tool-call" ||
- part.providerExecuted === true ||
- isInvalidToolCall(part)
- ) {
- continue;
- }
- backgroundBatch.register({
- callId: part.toolCallId,
- input: part.input,
- toolName: part.toolName,
- });
- }
},
onToolExecutionEnd: logToolExecutionError,
// Replaces the AI SDK's default `console.error`; the harness still
@@ -1678,16 +1595,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const executeModelCall = async (): Promise<HarnessStepResult> => {
if (emit) {
- const hiddenRuntimeActionToolNames = [...config.tools]
- .filter(
- ([name, tool]) =>
- tool.runtimeAction !== undefined && advertisedHarnessTools.get(name) === undefined,
- )
- .map(([name]) => name);
- const excludedActionToolNames = new Set([
- FINAL_OUTPUT_TOOL_NAME,
- ...hiddenRuntimeActionToolNames,
- ]);
+ const excludedActionToolNames = new Set([FINAL_OUTPUT_TOOL_NAME]);
const streamResult = await agent.stream({
abortSignal: generation.signal,
messages: callMessages,
@@ -1842,7 +1750,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
}),
(current) =>
attemptEmptyResponseRecovery({
- emptyDeliveryEnabled: deliveryPolicy.allowsEmptyDelivery,
error: current.error,
retryCallOptions: current.retryCallOptions,
runOneModelCall,
@@ -2475,9 +2382,9 @@ function buildDisabledToolNote(toolNames: readonly string[]): string {
}
/**
- * True when a step produced no assistant text and no tool calls. Intentional
- * silence uses {@link EMPTY_DELIVERY_SENTINEL}; a genuinely blank response is
- * ambiguous and must be retried instead of silently dropping a HITL reply.
+ * True when a step produced no assistant text and no tool calls. A blank
+ * response is ambiguous and must be retried instead of silently dropping a
+ * HITL reply.
*/
function isEmptyModelResponse(step: HarnessStepResult): boolean {
return (
@@ -2516,13 +2423,6 @@ function rethrowNoOutputAsEmptyResponse(error: unknown): never {
const EMPTY_RESPONSE_NUDGE =
"Your previous reply was empty and was not delivered. Continue the current user request. Reuse completed results when they satisfy the request. If existing results are stale or insufficient, use the appropriate read tools to get fresh results. Do not repeat writes or other side effects that already completed. Do not mention this notice.";
-function buildEmptyResponseNudge(emptyDeliveryEnabled: boolean): string {
- if (!emptyDeliveryEnabled) {
- return EMPTY_RESPONSE_NUDGE;
- }
- return `${EMPTY_RESPONSE_NUDGE} If the current task explicitly requires conditional delivery and there is nothing to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}.`;
-}
-
/**
* Recovers a model call that completed without content (see
* {@link EmptyModelResponseError}) by reissuing the same call once, with
@@ -2540,7 +2440,6 @@ function buildEmptyResponseNudge(emptyDeliveryEnabled: boolean): string {
* restore what the earlier recovery removed.
*/
async function attemptEmptyResponseRecovery(input: {
- readonly emptyDeliveryEnabled: boolean;
readonly error: unknown;
readonly retryCallOptions?: RecoveryRetryCallOptions;
readonly runOneModelCall: RecoveryModelCallFn;
@@ -2561,7 +2460,7 @@ async function attemptEmptyResponseRecovery(input: {
...input.retryCallOptions,
retryReason: "empty-response",
suppressStepStartedEmission: true,
- trailingUserNote: buildEmptyResponseNudge(input.emptyDeliveryEnabled),
+ trailingUserNote: EMPTY_RESPONSE_NUDGE,
});
return { outcome: "recovered", result };
} catch (retryError) {
@@ -2592,11 +2491,7 @@ async function handleStepResult(input: {
const { config, emit, promptMessages, result, runStep } = input;
let { emissionState, session } = input;
- const resolvedStepOutput = resolveAssistantStepText(result.response.messages, result.text);
- const emptyDelivery =
- result.finishReason !== "tool-calls" &&
- result.toolCalls.length === 0 &&
- hasEmptyDeliverySentinel(resolvedStepOutput);
+ const stepOutput = resolveAssistantStepText(result.response.messages, result.text);
const invalidInputToolErrors = getInvalidToolCallInputErrors({
toolCalls: result.toolCalls as TypedToolCall<ToolSet>[],
});
@@ -2608,15 +2503,12 @@ async function handleStepResult(input: {
...result.toolCalls.filter(isInvalidToolCall).map((toolCall) => toolCall.toolCallId),
...invalidInputToolErrors.map((toolError) => toolError.toolCallId),
]);
- const rawResponseMessages = emptyDelivery
- ? []
- : appendMissingToolResultMessages({
- append: invalidInputToolErrors.map((toolError) =>
- createToolResultMessagePartFromToolError(toolError),
- ),
- responseMessages: result.response.messages,
- });
- const stepOutput = emptyDelivery ? null : resolvedStepOutput;
+ const rawResponseMessages = appendMissingToolResultMessages({
+ append: invalidInputToolErrors.map((toolError) =>
+ createToolResultMessagePartFromToolError(toolError),
+ ),
+ responseMessages: result.response.messages,
+ });
const providerExecutedOutcomeIds = new Set<string>();
for (const part of [...(result.content ?? []), ...(result.toolResults ?? [])]) {
@@ -2672,7 +2564,7 @@ async function handleStepResult(input: {
session: baseSession,
tools: input.coordinationTools,
});
- const pendingCoordination = ((result.toolCalls ?? []) as TypedToolCall<ToolSet>[])
+ const tasks = ((result.toolCalls ?? []) as TypedToolCall<ToolSet>[])
.filter((toolCall) => !invalidInputToolCallIds.has(toolCall.toolCallId))
.filter((toolCall) => isDeferredHarnessTool(input.coordinationTools.get(toolCall.toolName)))
.filter((toolCall) => {
@@ -2693,13 +2585,7 @@ async function handleStepResult(input: {
}),
);
- 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] : [],
- );
+ if (tasks.length > 0) {
// 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
@@ -2711,7 +2597,6 @@ async function handleStepResult(input: {
next: null,
session: setHarnessEmissionState(
setPendingCoordinationBatch({
- runtimeActions,
tasks,
event: {
sequence: emissionState.sequence,
@@ -2727,7 +2612,6 @@ async function handleStepResult(input: {
}
let parkedSession = setPendingCoordinationBatch({
- runtimeActions,
tasks,
event: {
sequence: emissionState.sequence,
@@ -2924,10 +2808,7 @@ async function handleStepResult(input: {
}
function isDeferredHarnessTool(tool: HarnessToolDefinition | undefined): boolean {
- return (
- tool?.runtimeAction !== undefined ||
- (tool?.workflowId !== undefined && tool.execution !== "background")
- );
+ return tool?.workflowId !== undefined;
}
const OUTPUT_SCHEMA_NOT_FULFILLED = {
diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.ts
index 05720f5ca..fb37db931 100644
--- a/packages/eve/src/harness/tools.test.ts
+++ b/packages/eve/src/harness/tools.test.ts
@@ -17,7 +17,6 @@ import {
} from "#harness/provider-tool-schemas.js";
import type { JsonObject } from "#shared/json.js";
import { isAsyncIterable } from "#shared/async-iterable.js";
-import { BackgroundToolExecutorKey } from "#harness/background-tools.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import { buildToolApproval, buildToolSet, buildToolSetWithProviderTools } from "#harness/tools.js";
import type { HarnessToolMap } from "#harness/types.js";
@@ -137,57 +136,6 @@ describe("buildToolSet", () => {
expect(receivedOptions?.toolCallId).toBe("call_observe");
});
- it("registers background calls at execution when input callbacks are skipped or repeated", async () => {
- const observedBatches: string[][] = [];
- const ctx = new ContextContainer();
- ctx.set(BackgroundToolExecutorKey, {
- async execute({ batch }) {
- observedBatches.push(batch.calls.map((call) => call.callId));
- return { status: "working" };
- },
- });
- const tools: HarnessToolMap = new Map([
- [
- "background_work",
- {
- description: "Start background work.",
- execute: async () => ({ status: "working" }),
- execution: "background",
- inputSchema: jsonSchema({ type: "object" }),
- name: "background_work",
- workflowId: "workflow//test//background_work",
- },
- ],
- ]);
-
- const result = buildToolSet({ tools });
- const backgroundTool = result.background_work as typeof result.background_work & {
- readonly onInputAvailable: (input: {
- readonly input: unknown;
- readonly toolCallId: string;
- }) => void;
- };
- await contextStorage.run(ctx, async () => {
- await executeSdkTool({
- tool: backgroundTool,
- toolCallId: "approved-call",
- toolInput: { task: "resume" },
- });
-
- backgroundTool.onInputAvailable({
- input: { task: "new" },
- toolCallId: "new-call",
- });
- await executeSdkTool({
- tool: backgroundTool,
- toolCallId: "new-call",
- toolInput: { task: "new" },
- });
- });
-
- expect(observedBatches).toEqual([["approved-call"], ["approved-call", "new-call"]]);
- });
-
it("passes the AI SDK abort signal to the authored tool context", async () => {
const abortController = new AbortController();
let receivedSignal: AbortSignal | undefined;
diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.ts
index 86e0cb87d..ffc06d3c6 100644
--- a/packages/eve/src/harness/tools.ts
+++ b/packages/eve/src/harness/tools.ts
@@ -19,12 +19,6 @@ import { toModelSchema } from "#tools/schema.js";
import { normalizeToolJsonOutput, normalizeToolModelOutput } from "#harness/tool-model-output.js";
import type { ToolExecuteOptions } from "#tools/definition.js";
import { isAsyncIterable } from "#shared/async-iterable.js";
-import {
- createBackgroundToolCallBatch,
- executeBackgroundToolCall,
- type BackgroundExecutableTool,
- type BackgroundToolCallBatch,
-} from "#harness/background-tools.js";
type NativeApprovalStatus = Exclude<ApprovalStatus, boolean>;
@@ -46,12 +40,10 @@ const toolApprovals = new WeakMap<
*/
export function buildToolSet(input: {
readonly approvedTools?: ReadonlySet<string>;
- readonly backgroundBatch?: BackgroundToolCallBatch;
readonly disabledProviderTools?: ReadonlySet<string>;
readonly tools: HarnessToolMap;
}): ToolSet {
const tools: Record<string, ToolSet[string]> = {};
- const backgroundBatch = input.backgroundBatch ?? createBackgroundToolCallBatch();
const disabled = input.disabledProviderTools;
for (const definition of input.tools.values()) {
@@ -59,44 +51,13 @@ export function buildToolSet(input: {
continue;
}
- backgroundBatch.setTool(
- definition.name,
- definition.execution === "background" && definition.execute !== undefined
- ? {
- executeInput: definition.executeInput,
- name: definition.name,
- nodeId: definition.nodeId,
- workflowId: requireBackgroundWorkflowId(definition),
- }
- : undefined,
- );
const authorToModelOutput = definition.toModelOutput;
const approval = buildApprovalFn(definition, input);
const aiTool = tool({
description: definition.description,
- execute: wrapToolExecute(definition, backgroundBatch),
+ execute: wrapToolExecute(definition),
inputSchema: toModelSchema(definition.inputSchema, "input"),
strict: false,
- ...(definition.execution === "background"
- ? {
- onInputAvailable: ({
- input: toolInput,
- toolCallId,
- }: {
- readonly input: unknown;
- readonly toolCallId: string;
- }) => {
- if (definition.execute === undefined) {
- throw new Error(`Background tool "${definition.name}" has no execute function.`);
- }
- backgroundBatch.register({
- callId: toolCallId,
- input: toolInput,
- toolName: definition.name,
- });
- },
- }
- : {}),
outputSchema: toModelSchema(definition.outputSchema, "output"),
...(definition.execute !== undefined
? {
@@ -156,15 +117,6 @@ export function buildToolSet(input: {
return tools as ToolSet;
}
-function requireBackgroundWorkflowId(definition: HarnessToolDefinition): string {
- if (definition.workflowId === undefined) {
- throw new Error(
- `Background tool "${definition.name}" must be defined with defineWorkflowTool().`,
- );
- }
- return definition.workflowId;
-}
-
/**
* Builds a ToolSet from an ordered list of harness definitions.
*
@@ -173,7 +125,6 @@ function requireBackgroundWorkflowId(definition: HarnessToolDefinition): string
*/
export function buildToolSetFromDefinitions(input: {
readonly approvedTools?: ReadonlySet<string>;
- readonly backgroundBatch?: BackgroundToolCallBatch;
readonly disabledProviderTools?: ReadonlySet<string>;
readonly tools: readonly HarnessToolDefinition[];
}): ToolSet {
@@ -185,7 +136,6 @@ export function buildToolSetFromDefinitions(input: {
}
return buildToolSet({
approvedTools: input.approvedTools,
- backgroundBatch: input.backgroundBatch,
disabledProviderTools: input.disabledProviderTools,
tools,
});
@@ -200,7 +150,6 @@ export function buildToolSetFromDefinitions(input: {
*/
export function wrapToolExecute(
definition: HarnessToolDefinition,
- backgroundBatch: BackgroundToolCallBatch = createBackgroundToolCallBatch(),
): ((input: any, options: ToolExecuteOptions) => Promise<any> | AsyncIterable<any>) | undefined {
const execute = definition.execute;
if (execute === undefined) return undefined;
@@ -208,21 +157,7 @@ export function wrapToolExecute(
return (input, options) => {
let output: unknown;
try {
- if (definition.execution === "background") {
- backgroundBatch.register({
- callId: options.toolCallId,
- input,
- toolName: definition.name,
- });
- output = executeBackgroundToolCall({
- batch: backgroundBatch,
- definition: definition as BackgroundExecutableTool,
- options,
- toolInput: input,
- });
- } else {
- output = execute(input, options);
- }
+ output = execute(input, options);
} catch (error) {
return Promise.reject(error);
}
@@ -285,7 +220,6 @@ function normalizeToolExecuteOutput(
*/
export async function buildToolSetWithProviderTools(input: {
readonly approvedTools?: ReadonlySet<string>;
- readonly backgroundBatch?: BackgroundToolCallBatch;
readonly disabledProviderTools?: ReadonlySet<string>;
readonly modelReference: RuntimeModelReference;
readonly tools: HarnessToolMap;
@@ -294,7 +228,6 @@ export async function buildToolSetWithProviderTools(input: {
const tools: ToolSet = {
...buildToolSet({
approvedTools: input.approvedTools,
- backgroundBatch: input.backgroundBatch,
disabledProviderTools: disabled,
tools: input.tools,
}),
diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.ts
index ac59e0797..bdb9f2230 100644
--- a/packages/eve/src/harness/types.ts
+++ b/packages/eve/src/harness/types.ts
@@ -94,8 +94,6 @@ export interface HarnessSession {
readonly sessionId: string;
readonly sandboxState?: SandboxState;
readonly state?: SessionStateMap;
- /** Framework task that owns this durable session, when present. */
- readonly taskId?: string;
}
export function requireSessionModelReference(session: HarnessSession): RuntimeModelReference {
@@ -212,15 +210,6 @@ export interface SettledTurn {
*/
export interface StepResult {
readonly steered?: true;
- /** Background-tool effects projected onto the session that entered this step. */
- readonly backgroundTaskSession?: HarnessSession;
- /** Durable tasks started by background tools and awaiting the parent commit barrier. */
- readonly backgroundTasks?: readonly {
- readonly callId?: string;
- readonly taskInboxToken: string;
- readonly taskId: string;
- readonly taskRunId: string;
- }[];
readonly next: StepNext;
readonly session: HarnessSession;
/**
@@ -296,8 +285,6 @@ export interface ToolLoopHarnessConfig {
* Omitted in production until an instrumentation runtime opts in.
*/
readonly instrumentation?: SessionInstrumentation;
- /** Whether this node enables framework background-task behavior. */
- readonly tasksEnabled?: boolean;
/** Restores runtime resources for the originating turn before approval work. */
readonly prepareApprovalTurn?: (event: {
readonly sequence: number;
diff --git a/packages/eve/src/harness/workflow-tool-run-registry.test.ts b/packages/eve/src/harness/workflow-tool-run-registry.test.ts
index c31da9711..bc71f4a94 100644
--- a/packages/eve/src/harness/workflow-tool-run-registry.test.ts
+++ b/packages/eve/src/harness/workflow-tool-run-registry.test.ts
@@ -1,299 +1,65 @@
-import { runInNewContext } from "node:vm";
import { describe, expect, it } from "vitest";
import type { SessionStateMap } from "#harness/types.js";
import {
- getBackgroundTasks,
- readWorkflowTaskView,
- recordWorkflowTaskView,
findBlockingWorkflowToolRun,
- getWorkflowToolRuns,
+ getBlockingWorkflowToolRuns,
registerWorkflowToolRun,
removeBlockingWorkflowToolRuns,
- type BackgroundWorkflowToolRun,
type BlockingWorkflowToolRun,
} from "./workflow-tool-runs.js";
-import { resolveTaskDeliveryContext } from "#tasks/delivery-context.js";
const waiting = (turnId: string): BlockingWorkflowToolRun => ({
- lifetime: "turn",
callId: "same-call",
toolName: "research",
origin: { turnId, stepIndex: 0 },
address: { runId: `run-${turnId}`, hookToken: `hook-${turnId}` },
});
-const task = (taskId: string): BackgroundWorkflowToolRun => ({
- ...waiting("turn-a"),
- callId: taskId,
- lifetime: "session",
- address: { runId: `run-${taskId}`, hookToken: `hook-${taskId}` },
- task: {
- taskId,
- metadata: { kind: "tool", name: "research" },
- dispatchContext: { auth: { current: null, initiator: null } },
- },
-});
-describe("shared workflow invocation ownership", () => {
- it("stores blocking and background runs together under eve.workflowTool", () => {
- const blocking = waiting("turn-a");
- const background = task("task-a");
+describe("workflow tool run registry", () => {
+ it("stores waiting runs under eve.workflowTool", () => {
+ const first = waiting("turn-a");
+ const second = waiting("turn-b");
const initial: { state?: SessionStateMap } = {};
- const session = registerWorkflowToolRun(registerWorkflowToolRun(initial, blocking), background);
+ const session = registerWorkflowToolRun(registerWorkflowToolRun(initial, first), second);
expect(session.state).toEqual({
- "eve.workflowTool": { version: 3, runs: [blocking, background] },
+ "eve.workflowTool": { version: 4, runs: [first, second] },
});
});
- it("clears only one turn while retaining another turn, live tasks and completed payloads", () => {
+ it("clears only one turn while retaining another turn", () => {
let session: { state?: SessionStateMap } = registerWorkflowToolRun({}, waiting("turn-a"));
session = registerWorkflowToolRun(session, waiting("turn-b"));
- session = registerWorkflowToolRun(session, task("task-a"));
- session = registerWorkflowToolRun(session, task("task-b"));
- session = {
- ...session,
- state: recordWorkflowTaskView(session.state, {
- taskId: "task-a",
- metadata: task("task-a").task.metadata,
- status: "completed",
- lastOutput: { type: "result", data: "first" },
- }).state,
- };
session = removeBlockingWorkflowToolRuns(session, "turn-a");
- const entries = getWorkflowToolRuns(session.state);
- expect(entries.map((entry) => [entry.lifetime, entry.callId])).toEqual([
- ["turn", "same-call"],
- ["session", "task-a"],
- ["session", "task-b"],
- ]);
+ expect(getBlockingWorkflowToolRuns(session.state)).toEqual([waiting("turn-b")]);
expect(findBlockingWorkflowToolRun(session.state, "same-call", "turn-a")).toBeUndefined();
expect(findBlockingWorkflowToolRun(session.state, "same-call", "turn-b")).toEqual(
waiting("turn-b"),
);
- expect(
- resolveTaskDeliveryContext({
- state: session.state,
- taskDeliveryIds: ["task-a:ready:completed"],
- taskDeliveryPolicy: "cohort",
- })?.phase,
- ).toBe("pending");
- session = {
- ...session,
- state: recordWorkflowTaskView(session.state, {
- taskId: "task-b",
- metadata: task("task-b").task.metadata,
- status: "failed",
- lastOutput: { type: "error", data: "second" },
- }).state,
- };
- const restored = JSON.parse(
- JSON.stringify(removeBlockingWorkflowToolRuns(session, "turn-b").state),
- );
- const beforeReport = JSON.stringify(restored);
- const report = resolveTaskDeliveryContext({
- state: restored,
- taskDeliveryIds: ["task-b:ready:failed"],
- taskDeliveryPolicy: "cohort",
- });
- expect(report?.phase).toBe("settled");
- expect(report?.context).toContain("first");
- expect(report?.context).toContain("second");
- expect(
- getBackgroundTasks(restored)
- .query()
- .map((task) => task.cohortId),
- ).toEqual(["task-a", "task-a"]);
- expect(
- JSON.stringify(removeBlockingWorkflowToolRuns({ state: restored }, "turn-a").state),
- ).toBe(beforeReport);
- });
-
- it("preserves malformed historical results during unrelated ownership mutations", () => {
- const old = task("old");
- const retained = { ...old, task: { ...old.task, outcome: { status: "completed" } } };
- let session: { state?: SessionStateMap } = {
- state: { "eve.workflowTool": { version: 3, runs: [retained] } },
- };
- session = registerWorkflowToolRun(session, waiting("turn-b"));
- session = registerWorkflowToolRun(session, task("live"));
- session = {
- ...session,
- state: recordWorkflowTaskView(session.state, {
- taskId: "live",
- metadata: old.task.metadata,
- status: "cancelled",
- }).state,
- };
- session = removeBlockingWorkflowToolRuns(session, "turn-b");
- const entries = getWorkflowToolRuns(session.state);
- expect(entries[0]).toEqual(retained);
- expect(() => readWorkflowTaskView(retained.task)).toThrow("Corrupt workflow task result");
- expect(entries).toHaveLength(2);
- });
-
- it("retains creator auth and opaque selections without sharing parsed mutable containers", () => {
- const entry = task("task-a");
- const principal = {
- attributes: { roles: ["researcher"], team: "eve" },
- authenticator: "test",
- principalId: "alice",
- principalType: "user",
- };
- const selections = { researcher: { futureSelection: true } };
- const retained = {
- ...entry,
- task: {
- ...entry.task,
- dispatchContext: {
- auth: { current: principal, initiator: principal },
- sessionDynamicSubagentSelections: selections,
- },
- },
- };
- const [parsed] = getWorkflowToolRuns({
- "eve.workflowTool": { version: 3, runs: [retained] },
- });
- expect(parsed).toEqual(retained);
- expect(parsed?.lifetime).toBe("session");
- if (parsed?.lifetime !== "session") throw new Error("Expected a background run.");
- const context = parsed.task.dispatchContext;
- expect(context.auth.current).not.toBe(principal);
- expect(context.auth.current?.attributes.roles).not.toBe(principal.attributes.roles);
- expect(Object.isFrozen(context.auth.current?.attributes.roles)).toBe(true);
- expect(context.sessionDynamicSubagentSelections).not.toBe(selections);
- expect(context.sessionDynamicSubagentSelections?.researcher).toBe(selections.researcher);
- });
-
- it("reads creator auth and dynamic selections restored in the workflow VM", () => {
- const entry = task("task-a");
- const state = {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- ...entry,
- task: {
- ...entry.task,
- dispatchContext: {
- auth: {
- current: {
- attributes: { roles: ["researcher"] },
- authenticator: "test",
- principalId: "alice",
- principalType: "user",
- },
- initiator: null,
- },
- sessionDynamicSubagentSelections: { researcher: { futureSelection: true } },
- turnDynamicSubagentSelections: {},
- },
- },
- },
- ],
- },
- };
- const restored = runInNewContext("JSON.parse(input)", { input: JSON.stringify(state) });
- expect(Object.getPrototypeOf(restored)).not.toBe(Object.prototype);
- expect(getWorkflowToolRuns(restored)).toEqual(state["eve.workflowTool"].runs);
- expect(() => registerWorkflowToolRun({ state: restored }, waiting("turn-b"))).not.toThrow();
- });
-
- it.each([
- { auth: { current: null } },
- { auth: { current: null, initiator: null, injected: true } },
- {
- auth: {
- current: {
- attributes: { roles: Array(1) },
- authenticator: "test",
- principalId: "alice",
- principalType: "user",
- },
- initiator: null,
- },
- },
- {
- auth: {
- current: {
- attributes: { roles: ["researcher", 1] },
- authenticator: "test",
- principalId: "alice",
- principalType: "user",
- },
- initiator: null,
- },
- },
- {
- auth: {
- current: {
- attributes: {},
- authenticator: "test",
- principalId: "alice",
- principalType: "user",
- injected: true,
- },
- initiator: null,
- },
- },
- { auth: { current: null, initiator: null }, sessionDynamicSubagentSelections: [] },
- ])("rejects malformed retained creator authority: %j", (dispatchContext) => {
- const entry = task("task-a");
- expect(() =>
- getWorkflowToolRuns({
- "eve.workflowTool": {
- version: 3,
- runs: [{ ...entry, task: { ...entry.task, dispatchContext } }],
- },
- }),
- ).toThrow("Corrupt workflow tool run registry");
+ expect(removeBlockingWorkflowToolRuns(session, "turn-b").state).toBeUndefined();
});
- it("rejects duplicate originating call identities even without task payloads", () => {
+ it("rejects duplicate originating call identities", () => {
expect(() =>
- getWorkflowToolRuns({
+ getBlockingWorkflowToolRuns({
"eve.workflowTool": {
- version: 3,
+ version: 4,
runs: [waiting("turn-a"), waiting("turn-a")],
},
}),
).toThrow("Run identities must be unique");
});
- it.each([Infinity, NaN, -1, "0"])("rejects corrupt terminal usage %s", (costUsd) => {
- const entry = task("task-a");
- expect(() =>
- readWorkflowTaskView({
- ...entry.task,
- outcome: {
- status: "completed",
- lastOutput: { type: "result", data: "done" },
- usage: {
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- inputTokens: 1,
- outputTokens: 1,
- costUsd,
- },
- },
- }),
- ).toThrow("Corrupt workflow task result");
- });
-
- it("does not change lifetime on replay", () => {
+ it("does not change tool identity on replay", () => {
const session = registerWorkflowToolRun({}, waiting("turn-a"));
expect(() =>
- registerWorkflowToolRun(session, { ...task("task-a"), callId: "same-call" }),
- ).toThrow("Replayed invocation changed its ownership");
- });
-
- it("rejects the task-only index from main", () => {
- expect(() => getWorkflowToolRuns({ "eve.tasks": { version: 2, tasks: [] } })).toThrow(
- "Unsupported workflow tool run state",
- );
+ registerWorkflowToolRun(session, { ...waiting("turn-a"), toolName: "deploy" }),
+ ).toThrow("Replayed invocation changed its tool identity");
});
- it("rejects the separate blocking-run store from main", () => {
- expect(() => getWorkflowToolRuns({ "eve.runtime.workflowToolRuns": [] })).toThrow(
- "Unsupported workflow tool run state",
- );
+ it.each([
+ ["the task-only index", { "eve.tasks": { version: 2, tasks: [] } }],
+ ["the separate blocking-run store", { "eve.runtime.workflowToolRuns": [] }],
+ ])("rejects %s", (_, state) => {
+ expect(() => getBlockingWorkflowToolRuns(state)).toThrow("Unsupported workflow tool run state");
});
});
diff --git a/packages/eve/src/harness/workflow-tool-run-tasks.test.ts b/packages/eve/src/harness/workflow-tool-run-tasks.test.ts
deleted file mode 100644
index bccf05e8d..000000000
--- a/packages/eve/src/harness/workflow-tool-run-tasks.test.ts
+++ /dev/null
@@ -1,574 +0,0 @@
-import { assert, describe, expect, it } from "vitest";
-import type { HarnessSession } from "#harness/types.js";
-import {
- getBackgroundTasks,
- recordWorkflowTaskView,
- registerWorkflowToolRun,
-} from "#harness/workflow-tool-runs.js";
-import { deriveTaskId } from "#tasks/task-id.js";
-import type { TaskView } from "#tasks/types.js";
-import type { BackgroundTask } from "#harness/workflow-tool-runs.js";
-
-function views(tasks: readonly BackgroundTask[]): TaskView[] {
- return tasks.map(({ cohortId: _cohortId, turnId: _turnId, run: _run, ...view }) => view);
-}
-
-function ids(tasks: readonly BackgroundTask[]): string[] {
- return tasks.map((task) => task.taskId);
-}
-
-function createSession(state?: HarnessSession["state"]): HarnessSession {
- return {
- agent: {
- modelReference: { id: "model_test" },
- system: "",
- tools: [],
- },
- compaction: { recentWindowSize: 4, threshold: 1_000_000 },
- continuationToken: "continuation_test",
- history: [],
- sessionId: "session_parent",
- state,
- };
-}
-
-describe("session task index", () => {
- const metadata = {
- kind: "tool" as const,
- name: "research",
- };
- const dispatchContext = { auth: { current: null, initiator: null } } as const;
- it("returns an empty index when the key is absent", () => {
- expect(getBackgroundTasks({}).query()).toEqual([]);
- expect(getBackgroundTasks(undefined).query()).toEqual([]);
- });
-
- it("queries restored background tasks by state across turns, excluding blocking runs", () => {
- let session = registerWorkflowToolRun(createSession(), task("working", "turn-1"));
- for (const status of ["completed", "failed", "cancelled"] as const) {
- session = registerWorkflowToolRun(session, task(status, "turn-2"));
- session = {
- ...session,
- state: recordWorkflowTaskView(session.state, terminal(status, status)).state,
- };
- }
- session = registerWorkflowToolRun(session, {
- callId: "blocking",
- toolName: "research",
- lifetime: "turn",
- origin: { turnId: "turn-2", stepIndex: 0 },
- address: { runId: "blocking", hookToken: "blocking" },
- });
-
- const backgroundTasks = getBackgroundTasks(JSON.parse(JSON.stringify(session.state)));
- expect(views(backgroundTasks.query({ state: "working" }))).toEqual([
- { taskId: "working", metadata, status: "working" },
- ]);
- expect(views(backgroundTasks.query({ state: "completed" }))).toEqual([
- terminal("completed", "completed"),
- ]);
- expect(views(backgroundTasks.query({ state: "failed" }))).toEqual([
- terminal("failed", "failed"),
- ]);
- expect(views(backgroundTasks.query({ state: "cancelled" }))).toEqual([
- terminal("cancelled", "cancelled"),
- ]);
- expect(getBackgroundTasks(undefined).query({ state: "working" })).toEqual([]);
- });
-
- it("distinguishes a first terminal settlement from repeated and late reports", () => {
- const session = registerWorkflowToolRun(createSession(), task("task_a", "turn-1"));
- const completed = terminal("task_a", "completed");
- const first = recordWorkflowTaskView(session.state, completed);
- expect(first.firstOutcome).toBe(true);
- expect(first.view).toEqual(completed);
-
- const repeated = recordWorkflowTaskView(first.state, completed);
- expect(repeated.state).toBe(first.state);
- expect(repeated.firstOutcome).toBe(false);
- expect(repeated.view).toEqual(completed);
-
- const late = recordWorkflowTaskView(repeated.state, terminal("task_a", "cancelled"));
- expect(late.state).toBe(repeated.state);
- expect(late.firstOutcome).toBe(false);
- expect(late.view).toEqual(completed);
- });
-
- it("retains cancellation across restore and late outcomes without removing cohort membership", () => {
- const session = registerWorkflowToolRun(createSession(), task("task_a", "turn-1"));
- const state = recordWorkflowTaskView(session.state, terminal("task_a", "cancelled")).state;
- const replay = registerWorkflowToolRun(
- createSession(JSON.parse(JSON.stringify(state))),
- task("task_a", "turn-1"),
- );
- const late = recordWorkflowTaskView(replay.state, terminal("task_a", "completed")).state;
- expect(views(getBackgroundTasks(late).query({ state: "cancelled" }))).toEqual([
- terminal("task_a", "cancelled"),
- ]);
- expect(getBackgroundTasks(late).get("task_a")?.cohortId).toBe("task_a");
- });
-
- it("decodes only the tasks a read returns", () => {
- const retained = task("task_old", "turn-1");
- const tasks = getBackgroundTasks({
- "eve.workflowTool": {
- version: 3,
- runs: [
- { ...retained, task: { ...retained.task, outcome: { status: "completed" } } },
- task("task_live", "turn-2"),
- ],
- },
- });
- // A corrupt retained outcome must not block reads of unrelated work.
- expect(ids(tasks.query({ state: "working" }))).toEqual(["task_live"]);
- expect(tasks.get("task_live")?.status).toBe("working");
- expect(() => tasks.get("task_old")).toThrow("Corrupt workflow task result");
- expect(() => tasks.query({ state: "completed" })).toThrow("Corrupt workflow task result");
- expect(() => tasks.query()).toThrow("Corrupt workflow task result");
- });
-
- it("filters by starting turn, cohort, and a set of states", () => {
- let session = registerWorkflowToolRun(createSession(), task("task_a", "turn-1"));
- // Work started while task_a is open joins its cohort.
- session = registerWorkflowToolRun(session, task("task_b", "turn-2"));
- session = {
- ...session,
- state: recordWorkflowTaskView(session.state, terminal("task_a", "cancelled")).state,
- };
- const tasks = getBackgroundTasks(session.state);
- expect(ids(tasks.query({ turnId: "turn-2" }))).toEqual(["task_b"]);
- expect(ids(tasks.query({ cohortId: "task_a" }))).toEqual(["task_a", "task_b"]);
- expect(ids(tasks.query({ state: ["working", "cancelled"] }))).toEqual(["task_a", "task_b"]);
- expect(ids(tasks.query({ state: "working", turnId: "turn-1" }))).toEqual([]);
- expect(tasks.get("task_b")).toMatchObject({ cohortId: "task_a", turnId: "turn-2" });
- });
-
- it("records a task and finds it by id", () => {
- const session = registerWorkflowToolRun(createSession(), {
- callId: "task_a",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task:token-1" },
- task: { dispatchContext, metadata, taskId: "task_a" },
- });
-
- expect(getBackgroundTasks(session.state).get("task_a")?.run).toEqual({
- callId: "task_a",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task:token-1" },
- task: { dispatchContext, metadata, taskId: "task_a" },
- });
- expect(getBackgroundTasks(session.state).get("task_other")?.run).toBeUndefined();
- });
-
- it("keeps activity identity in the persisted task index", () => {
- const activityWorkIdentity = {
- callId: "call-1",
- id: "work:task",
- kind: "task" as const,
- name: "research",
- parentId: "work:root",
- rootSessionId: "root-session",
- rootTurnId: "root-turn",
- };
- const session = registerWorkflowToolRun(createSession(), {
- callId: "task_a",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task:token-1" },
- task: { activityWorkIdentity, dispatchContext, metadata, taskId: "task_a" },
- });
-
- const restoredState = JSON.parse(JSON.stringify(session.state));
- expect(getBackgroundTasks(restoredState).get("task_a")?.run.task.activityWorkIdentity).toEqual(
- activityWorkIdentity,
- );
- });
-
- it("keeps subagent metadata in the persisted task index", () => {
- const subagentMetadata = {
- agentId: "ag_worker",
- kind: "subagent",
- mode: "remote",
- name: "research",
- } as const;
-
- const session = registerWorkflowToolRun(createSession(), {
- callId: "task_a",
- toolName: subagentMetadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task:token-1" },
- task: { dispatchContext, metadata: subagentMetadata, taskId: "task_a" },
- });
-
- expect(getBackgroundTasks(session.state).get("task_a")?.run.task.metadata).toEqual(
- subagentMetadata,
- );
- });
-
- it("keeps a terminal view when replayed activity presentation changes", () => {
- let session = registerWorkflowToolRun(createSession(), {
- callId: "task_a",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task:token-1" },
- task: {
- activityWorkIdentity: {
- callId: "call-1",
- id: "work:task",
- kind: "task",
- label: "First label",
- name: "research",
- parentId: "work:root",
- rootSessionId: "root-session",
- rootTurnId: "root-turn",
- },
- dispatchContext,
- metadata,
- taskId: "task_a",
- },
- });
- session = {
- ...session,
- state: recordWorkflowTaskView(session.state, terminal("task_a", "completed")).state,
- };
- session = registerWorkflowToolRun(session, {
- callId: "task_a",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-2", hookToken: "task:token-2" },
- task: {
- activityWorkIdentity: {
- callId: "call-1",
- id: "work:task",
- kind: "task",
- label: "Second label",
- name: "research",
- parentId: "work:root",
- rootSessionId: "root-session",
- rootTurnId: "root-turn",
- },
- dispatchContext,
- metadata,
- taskId: "task_a",
- },
- });
-
- expect(getBackgroundTasks(session.state).get("task_a")?.run).toMatchObject({
- task: {
- activityWorkIdentity: { label: "Second label" },
- outcome: { status: "completed", lastOutput: { type: "result", data: "done" } },
- },
- });
- });
-
- it("replaces the entry on replayed creation instead of duplicating it", () => {
- let session = registerWorkflowToolRun(createSession(), {
- callId: "task_a",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task:token-1" },
- task: { dispatchContext, metadata, taskId: "task_a" },
- });
- session = registerWorkflowToolRun(session, {
- callId: "task_a",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-2", hookToken: "task:token-2" },
- task: { dispatchContext, metadata, taskId: "task_a" },
- });
-
- const entries = getBackgroundTasks(session.state)
- .query()
- .map((task) => task.run);
- expect(entries).toHaveLength(1);
- expect(entries[0]?.address.runId).toBe("run-2");
- });
-
- function task(taskId: string, createdByTurnId: string) {
- return {
- callId: taskId,
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: createdByTurnId, stepIndex: 0 },
- address: { runId: `run-${taskId}`, hookToken: `inbox-${taskId}` },
- task: { dispatchContext, metadata, taskId },
- };
- }
-
- function terminal(taskId: string, status: "completed" | "failed" | "cancelled"): TaskView {
- if (status === "cancelled") return { metadata, status, taskId };
- return status === "completed"
- ? { metadata, status, taskId, lastOutput: { type: "result", data: "done" } }
- : { metadata, status, taskId, lastOutput: { type: "error", data: "failed" } };
- }
-
- it("durably joins overlapping work across turns", () => {
- const first = task("task_a", "turn-1");
- const initial = registerWorkflowToolRun(createSession(), first);
- const second = task("task_b", "turn-2");
- const session = registerWorkflowToolRun(initial, second);
- const tasks = getBackgroundTasks(session.state).query();
- expect(tasks.map((task) => task.cohortId)).toEqual(["task_a", "task_a"]);
- expect(tasks.map((task) => task.turnId)).toEqual(["turn-1", "turn-2"]);
- // A cohort's first task has no join target; later members store it.
- expect(tasks[0]?.run.task.cohortId).toBeUndefined();
- expect(tasks[1]?.run.task.cohortId).toBe("task_a");
- const restored = createSession(JSON.parse(JSON.stringify(initial.state)));
- expect(registerWorkflowToolRun(restored, second).state).toEqual(session.state);
- expect(getBackgroundTasks(initial.state).query()).toHaveLength(1);
- });
-
- it.each(["completed", "failed", "cancelled"] as const)(
- "keeps a %s sibling in a pending cohort, then starts a new cohort after settlement",
- (status) => {
- let session = registerWorkflowToolRun(createSession(), task("task_a", "turn-1"));
- session = registerWorkflowToolRun(session, task("task_b", "turn-1"));
- session = {
- ...session,
- state: recordWorkflowTaskView(session.state, terminal("task_a", status)).state,
- };
- session = registerWorkflowToolRun(session, task("task_c", "turn-2"));
- expect(
- getBackgroundTasks(session.state)
- .query()
- .map((task) => task.cohortId),
- ).toEqual(["task_a", "task_a", "task_a"]);
- for (const taskId of ["task_b", "task_c"]) {
- session = {
- ...session,
- state: recordWorkflowTaskView(session.state, terminal(taskId, status)).state,
- };
- }
- // Even another creation in the same turn must not reopen a settled cohort.
- session = registerWorkflowToolRun(session, task("task_d", "turn-2"));
- expect(
- getBackgroundTasks(session.state)
- .query()
- .map((task) => task.cohortId),
- ).toEqual(["task_a", "task_a", "task_a", "task_d"]);
- },
- );
-
- it("preserves replayed membership, creation provenance, order, and settlement", () => {
- let session = registerWorkflowToolRun(createSession(), task("task_a", "turn-1"));
- session = registerWorkflowToolRun(session, task("task_b", "turn-2"));
- for (const taskId of ["task_a", "task_b"]) {
- session = {
- ...session,
- state: recordWorkflowTaskView(session.state, terminal(taskId, "completed")).state,
- };
- }
- session = registerWorkflowToolRun(session, task("task_c", "turn-3"));
- session = registerWorkflowToolRun(session, {
- ...task("task_a", "turn-1"),
- origin: { ...task("task_a", "turn-1").origin, stepIndex: 9 },
- address: { ...task("task_a", "turn-1").address, runId: "run-replayed" },
- });
- session = registerWorkflowToolRun(session, {
- ...task("task_b", "turn-2"),
- origin: { ...task("task_b", "turn-2").origin, stepIndex: 9 },
- });
- expect(
- getBackgroundTasks(session.state)
- .query()
- .map((task) => ({
- taskId: task.taskId,
- cohortId: task.cohortId,
- turnId: task.turnId,
- stepIndex: task.run.origin.stepIndex,
- settled: task.status !== "working",
- })),
- ).toEqual([
- { taskId: "task_a", cohortId: "task_a", turnId: "turn-1", stepIndex: 0, settled: true },
- { taskId: "task_b", cohortId: "task_a", turnId: "turn-2", stepIndex: 0, settled: true },
- { taskId: "task_c", cohortId: "task_c", turnId: "turn-3", stepIndex: 0, settled: false },
- ]);
- expect(getBackgroundTasks(session.state).get("task_a")?.run.address.runId).toBe("run-replayed");
- session = registerWorkflowToolRun(session, task("task_d", "turn-4"));
- expect(getBackgroundTasks(session.state).get("task_d")?.run.task.cohortId).toBe("task_c");
- });
-
- it.each(["", null, 42])("rejects an invalid additive cohort identity: %j", (cohortId) => {
- expect(() =>
- getBackgroundTasks({
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- ...task("task_a", "turn-1"),
- task: { ...task("task_a", "turn-1").task, cohortId: cohortId },
- },
- ],
- },
- }),
- ).toThrow(/Corrupt workflow tool run registry/u);
- });
-
- it("validates retained outcomes when they are consumed", () => {
- const base = {
- callId: "task_a",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task:token-1" },
- task: { dispatchContext, metadata, taskId: "task_a" },
- };
- const outcome = {
- lastOutput: { data: "done", type: "result" as const },
- status: "completed" as const,
- };
-
- const session = registerWorkflowToolRun(createSession(), {
- ...base,
- task: { ...base.task, outcome },
- });
- expect(getBackgroundTasks(session.state).get("task_a")?.run.task.outcome).toEqual(outcome);
- for (const invalidOutcome of [
- { status: "working" },
- { status: "completed" },
- {
- lastOutput: { data: "wrong", type: "result" },
- status: "failed",
- },
- {
- lastOutput: { data: "wrong", type: "result" },
- status: "cancelled",
- },
- {
- inputRequests: [{ requestId: "stale" }],
- lastOutput: { data: "done", type: "result" },
- status: "completed",
- },
- ]) {
- const tasks = getBackgroundTasks({
- "eve.workflowTool": {
- version: 3,
- runs: [{ ...base, task: { ...base.task, outcome: invalidOutcome } }],
- },
- });
- // The registry keeps the entry; only reading its view rejects the outcome.
- expect(tasks.query({ state: "working" })).toEqual([]);
- expect(() => tasks.get(base.task.taskId)).toThrow("Corrupt workflow task result");
- expect(() =>
- registerWorkflowToolRun(createSession(), {
- ...base,
- task: { ...base.task, outcome: invalidOutcome },
- }),
- ).toThrow("Corrupt workflow task result");
- }
- });
-
- it.each(["completed", "failed", "cancelled"] as const)(
- "keeps the parent's first %s outcome across duplicates and competing deliveries",
- (status) => {
- const session = registerWorkflowToolRun(createSession(), task("task_a", "turn-1"));
- const usage = { inputTokens: 3, outputTokens: 5, cacheReadTokens: 0, cacheWriteTokens: 0 };
- const first = { ...terminal("task_a", status), usage };
- const state = recordWorkflowTaskView(session.state, first).state;
- for (const late of ["completed", "failed", "cancelled"] as const) {
- expect(recordWorkflowTaskView(state, terminal("task_a", late)).state).toBe(state);
- }
- const recorded = getBackgroundTasks(state).get("task_a");
- assert(recorded !== undefined);
- expect(recorded.run.task.outcome).toEqual(
- status === "cancelled"
- ? { status, usage }
- : { status, usage, lastOutput: first.lastOutput },
- );
- expect(views([recorded])).toEqual([first]);
- },
- );
-
- it("rejects an incoming result with metadata belonging to a different task", () => {
- const session = registerWorkflowToolRun(createSession(), task("task_a", "turn-1"));
- expect(
- () =>
- recordWorkflowTaskView(session.state, {
- ...terminal("task_a", "cancelled"),
- metadata: { kind: "tool", name: "other" },
- }).state,
- ).toThrow("Task view metadata does not match");
- });
-
- it("throws on a corrupt index instead of treating it as absent", () => {
- expect(() =>
- getBackgroundTasks({
- "eve.workflowTool": { version: 3, runs: [{ taskId: 42 }] },
- }),
- ).toThrow("Corrupt workflow tool run registry");
- });
-
- it("rejects missing creator context", () => {
- const entry = task("task_a", "turn-1");
- expect(() =>
- getBackgroundTasks({
- "eve.workflowTool": {
- version: 3,
- runs: [{ ...entry, task: { ...entry.task, dispatchContext: undefined } }],
- },
- }),
- ).toThrow("Corrupt workflow tool run registry");
- });
-
- it("rejects reassigning a task id to another originating turn", () => {
- const session = registerWorkflowToolRun(createSession(), task("task_a", "turn-1"));
- expect(() => registerWorkflowToolRun(session, task("task_a", "turn-2"))).toThrow(
- "Task ids must be unique",
- );
- });
-
- it("rejects unrecognized task dispatch context fields", () => {
- expect(() =>
- getBackgroundTasks({
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- callId: "task_a",
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: "turn-1", stepIndex: 0 },
- address: { runId: "run-1", hookToken: "task:token-1" },
- task: {
- dispatchContext: {
- auth: { current: null, initiator: null },
- unexpected: "receiver-context",
- },
- metadata,
- taskId: "task_a",
- },
- },
- ],
- },
- }),
- ).toThrow("Corrupt workflow tool run registry");
- });
-
- it("rejects an unsupported registry version", () => {
- expect(() =>
- getBackgroundTasks({
- "eve.workflowTool": { version: 99, runs: [] },
- }),
- ).toThrow("Corrupt workflow tool run registry");
- });
-});
-
-describe("deriveTaskId", () => {
- it("is deterministic for the same originating call and distinct otherwise", () => {
- const input = { callId: "call-1", parentSessionId: "session-1", parentTurnId: "turn-1" };
-
- expect(deriveTaskId(input)).toBe(deriveTaskId(input));
- expect(deriveTaskId(input)).toMatch(/^task_[0-9a-f]{24}$/);
- expect(deriveTaskId({ ...input, callId: "call-2" })).not.toBe(deriveTaskId(input));
- });
-});
diff --git a/packages/eve/src/harness/workflow-tool-runs.test.ts b/packages/eve/src/harness/workflow-tool-runs.test.ts
index 4c34f6d88..05a94967e 100644
--- a/packages/eve/src/harness/workflow-tool-runs.test.ts
+++ b/packages/eve/src/harness/workflow-tool-runs.test.ts
@@ -12,7 +12,6 @@ import type { HarnessSession } from "#harness/types.js";
const RECORD = {
callId: "call_1",
toolName: "deploy",
- lifetime: "turn" as const,
origin: { turnId: "turn-1", stepIndex: 0 },
address: { runId: "wrun_1", hookToken: "eve:workflow-tool-run:abc" },
};
@@ -27,7 +26,7 @@ describe("workflow tool run records", () => {
getBlockingWorkflowToolRuns({
"eve.workflowTool": { version: 1, runs: [RECORD] },
}),
- ).toThrow("Corrupt workflow tool run registry");
+ ).toThrow("Unsupported workflow tool run state");
});
it("records, finds, and removes runs by call id", () => {
@@ -98,7 +97,7 @@ describe("workflow tool run records", () => {
it("rejects malformed state", () => {
expect(() =>
getBlockingWorkflowToolRuns({
- "eve.workflowTool": { version: 3, runs: { not: "an array" } },
+ "eve.workflowTool": { version: 4, runs: { not: "an array" } },
}),
).toThrow("Corrupt workflow tool run registry");
});
diff --git a/packages/eve/src/harness/workflow-tool-runs.ts b/packages/eve/src/harness/workflow-tool-runs.ts
index 3dc9f8e6d..9e19f7bda 100644
--- a/packages/eve/src/harness/workflow-tool-runs.ts
+++ b/packages/eve/src/harness/workflow-tool-runs.ts
@@ -1,158 +1,40 @@
import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
import { isNonEmptyString, isObject } from "#shared/guards.js";
import type { SessionStateMap } from "#harness/types.js";
-import { parseActivityWorkIdentityV1, type ActivityWorkIdentityV1 } from "#protocol/activity.js";
-import type { SessionAuthContext } from "#channel/types.js";
-import {
- sameTaskMetadata,
- type TaskMetadata,
- type TaskOutput,
- type TaskStatus,
- type TaskUsage,
- type TaskView,
-} from "#tasks/types.js";
-import type { DurableDynamicSubagentSelection, SessionAuth } from "#context/keys.js";
-// Version 3 replaces the task-only index with the shared workflow tool run registry.
export const WORKFLOW_TOOL_RUNS_STATE_KEY = "eve.workflowTool";
-const WORKFLOW_TOOL_RUNS_VERSION = 3;
+// Version 4 records only runs a turn waits on; earlier versions also held session-owned runs.
+const WORKFLOW_TOOL_RUNS_VERSION = 4;
-export interface WorkflowTaskPayload {
- readonly taskId: string;
- readonly metadata: TaskMetadata;
- readonly dispatchContext: TaskAgentDispatchContext;
- readonly activityWorkIdentity?: ActivityWorkIdentityV1;
- readonly cohortId?: string;
- /** Parent-owned outcome. Read through readWorkflowTaskView before consuming it. */
- readonly outcome?: unknown;
-}
-
-/** Settled task data; identity and metadata belong to the owning task. */
-type TaskOutcome = {
- readonly usage?: TaskUsage;
-} & (
- | { readonly status: "completed"; readonly lastOutput: Extract<TaskOutput, { type: "result" }> }
- | { readonly status: "failed"; readonly lastOutput: Extract<TaskOutput, { type: "error" }> }
- | { readonly status: "cancelled"; readonly lastOutput?: never }
-);
-
-interface WorkflowToolRunBase {
+/** One workflow tool call the originating turn waits on. */
+export interface BlockingWorkflowToolRun {
readonly callId: string;
readonly toolName: string;
-
readonly origin: { readonly turnId: string; readonly stepIndex: number };
readonly address: { readonly runId: string; readonly hookToken: string };
}
-export type BlockingWorkflowToolRun = WorkflowToolRunBase & { readonly lifetime: "turn" };
-export type BackgroundWorkflowToolRun = WorkflowToolRunBase & {
- readonly lifetime: "session";
- readonly task: WorkflowTaskPayload;
-};
-export type WorkflowToolRun = BlockingWorkflowToolRun | BackgroundWorkflowToolRun;
-
-export interface TaskAgentDispatchContext {
- readonly auth: SessionAuth;
- readonly sessionDynamicSubagentSelections?: Readonly<
- Record<string, DurableDynamicSubagentSelection>
- >;
- readonly turnDynamicSubagentSelections?: Readonly<
- Record<string, DurableDynamicSubagentSelection>
- >;
-}
interface WorkflowToolRunRegistry {
readonly version: typeof WORKFLOW_TOOL_RUNS_VERSION;
- readonly runs: readonly WorkflowToolRun[];
+ readonly runs: readonly BlockingWorkflowToolRun[];
readonly [key: string]: unknown;
}
// These readers run inside the workflow driver: importing a schema runtime here also
// embeds it and its source map in every deployed workflow function.
-function isTaskMetadata(value: unknown): value is TaskMetadata {
- return isObject(value) && isNonEmptyString(value.kind) && isNonEmptyString(value.name);
-}
-
-/** Workflow checkpoints can carry records created in another VM realm. */
-function isRecord(value: unknown): value is Record<string, unknown> {
- if (!isObject(value)) return false;
- const constructor = value.constructor;
- return (
- typeof constructor !== "function" ||
- (isObject(constructor.prototype) && Object.hasOwn(constructor.prototype, "isPrototypeOf"))
- );
-}
-
-function isSessionAuthContext(value: unknown): value is SessionAuthContext | null {
- return (
- value === null ||
- (isObject(value) &&
- Object.keys(value).every((key) =>
- [
- "attributes",
- "authenticator",
- "issuer",
- "principalId",
- "principalType",
- "subject",
- ].includes(key),
- ) &&
- isRecord(value.attributes) &&
- Object.values(value.attributes).every(
- (attribute) =>
- typeof attribute === "string" ||
- (Array.isArray(attribute) &&
- Array.from(attribute).every((item) => typeof item === "string")),
- ) &&
- typeof value.authenticator === "string" &&
- typeof value.principalId === "string" &&
- typeof value.principalType === "string" &&
- (value.issuer === undefined || typeof value.issuer === "string") &&
- (value.subject === undefined || typeof value.subject === "string"))
- );
-}
-
-function isTaskAgentDispatchContext(value: unknown): value is TaskAgentDispatchContext {
+function isWorkflowToolRun(value: unknown): value is BlockingWorkflowToolRun {
return (
isObject(value) &&
- Object.keys(value).every((key) =>
- ["auth", "sessionDynamicSubagentSelections", "turnDynamicSubagentSelections"].includes(key),
- ) &&
- isObject(value.auth) &&
- Object.keys(value.auth).every((key) => key === "current" || key === "initiator") &&
- isSessionAuthContext(value.auth.current) &&
- isSessionAuthContext(value.auth.initiator) &&
- (value.sessionDynamicSubagentSelections === undefined ||
- isRecord(value.sessionDynamicSubagentSelections)) &&
- (value.turnDynamicSubagentSelections === undefined ||
- isRecord(value.turnDynamicSubagentSelections))
- );
-}
-
-function isWorkflowToolRun(value: unknown): value is WorkflowToolRun {
- if (
- !isObject(value) ||
- !isNonEmptyString(value.callId) ||
- !isNonEmptyString(value.toolName) ||
- !isObject(value.origin) ||
- !isNonEmptyString(value.origin.turnId) ||
- typeof value.origin.stepIndex !== "number" ||
- !Number.isSafeInteger(value.origin.stepIndex) ||
- value.origin.stepIndex < 0 ||
- !isObject(value.address) ||
- !isNonEmptyString(value.address.runId) ||
- !isNonEmptyString(value.address.hookToken)
- )
- return false;
- if (value.lifetime === "turn") return value.task === undefined;
- if (value.lifetime !== "session" || !isObject(value.task)) return false;
- const task = value.task;
- return (
- isNonEmptyString(task.taskId) &&
- isTaskMetadata(task.metadata) &&
- isTaskAgentDispatchContext(task.dispatchContext) &&
- (task.cohortId === undefined || isNonEmptyString(task.cohortId)) &&
- (task.activityWorkIdentity === undefined ||
- parseActivityWorkIdentityV1(task.activityWorkIdentity) !== undefined)
+ isNonEmptyString(value.callId) &&
+ isNonEmptyString(value.toolName) &&
+ isObject(value.origin) &&
+ isNonEmptyString(value.origin.turnId) &&
+ typeof value.origin.stepIndex === "number" &&
+ Number.isSafeInteger(value.origin.stepIndex) &&
+ value.origin.stepIndex >= 0 &&
+ isObject(value.address) &&
+ isNonEmptyString(value.address.runId) &&
+ isNonEmptyString(value.address.hookToken)
);
}
@@ -166,16 +48,11 @@ function parseRegistry(value: unknown): WorkflowToolRunRegistry {
throw new Error("Corrupt workflow tool run registry: invalid version or run.");
}
const identities = new Set<string>();
- const tasks = new Set<string>();
for (const entry of value.runs) {
const identity = JSON.stringify([entry.origin.turnId, entry.callId]);
if (identities.has(identity))
throw new Error("Corrupt workflow tool run registry: Run identities must be unique.");
identities.add(identity);
- if (entry.lifetime !== "session") continue;
- if (tasks.has(entry.task.taskId))
- throw new Error("Corrupt workflow tool run registry: Task ids must be unique.");
- tasks.add(entry.task.taskId);
}
return {
...value,
@@ -184,170 +61,34 @@ function parseRegistry(value: unknown): WorkflowToolRunRegistry {
};
}
-function copySessionAuthContext(value: SessionAuthContext | null): SessionAuthContext | null {
- if (value === null) return null;
- return {
- ...value,
- attributes: Object.fromEntries(
- Object.entries(value.attributes).map(([key, attribute]) => [
- key,
- typeof attribute === "string" ? attribute : Object.freeze([...attribute]),
- ]),
- ),
- };
-}
-
-function copyWorkflowToolRun(entry: WorkflowToolRun): WorkflowToolRun {
- const base = { ...entry, origin: { ...entry.origin }, address: { ...entry.address } };
- if (entry.lifetime === "turn") return base;
- const dispatch = entry.task.dispatchContext;
- const dispatchContext = {
- ...dispatch,
- auth: {
- current: copySessionAuthContext(dispatch.auth.current),
- initiator: copySessionAuthContext(dispatch.auth.initiator),
- },
- };
- if (dispatch.sessionDynamicSubagentSelections !== undefined)
- dispatchContext.sessionDynamicSubagentSelections = {
- ...dispatch.sessionDynamicSubagentSelections,
- };
- if (dispatch.turnDynamicSubagentSelections !== undefined)
- dispatchContext.turnDynamicSubagentSelections = { ...dispatch.turnDynamicSubagentSelections };
- return {
- ...base,
- lifetime: "session",
- task: { ...entry.task, metadata: { ...entry.task.metadata }, dispatchContext },
- };
-}
-
-function parseTaskOutcome(value: unknown): TaskOutcome | undefined {
- if (!isObject(value) || value.inputRequests !== undefined) return undefined;
- const usage = value.usage;
- if (
- usage !== undefined &&
- (!isObject(usage) ||
- ![
- usage.cacheReadTokens,
- usage.cacheWriteTokens,
- usage.inputTokens,
- usage.outputTokens,
- ...(usage.costUsd === undefined ? [] : [usage.costUsd]),
- ].every((count) => typeof count === "number" && Number.isFinite(count) && count >= 0))
- )
- return undefined;
- if (value.status === "cancelled") {
- if (value.lastOutput !== undefined) return undefined;
- } else {
- if (value.status !== "completed" && value.status !== "failed") return undefined;
- const outputType = value.status === "completed" ? "result" : "error";
- if (!isObject(value.lastOutput) || value.lastOutput.type !== outputType) return undefined;
- }
- // Output data and additive fields are opaque; only the known lifecycle fields are decoded.
- const outcome = { ...value };
- if (usage !== undefined) outcome.usage = { ...usage };
- if (isObject(value.lastOutput)) outcome.lastOutput = { ...value.lastOutput };
- return outcome as TaskOutcome;
-}
-
-/** Decode retained output only when it is consumed, independently of ownership reads. */
-export function readWorkflowTaskView(task: WorkflowTaskPayload): TaskView | undefined {
- if (task.outcome === undefined) return undefined;
- const outcome = parseTaskOutcome(task.outcome);
- if (outcome === undefined)
- throw new Error(`Corrupt workflow task result "${task.taskId}": invalid outcome.`);
- return { ...outcome, taskId: task.taskId, metadata: { ...task.metadata } };
+function copyWorkflowToolRun(entry: BlockingWorkflowToolRun): BlockingWorkflowToolRun {
+ return { ...entry, origin: { ...entry.origin }, address: { ...entry.address } };
}
function readRegistry(state: SessionStateMap | undefined): WorkflowToolRunRegistry {
- if (state?.["eve.tasks"] !== undefined || state?.["eve.runtime.workflowToolRuns"] !== undefined) {
+ const raw = state?.[WORKFLOW_TOOL_RUNS_STATE_KEY];
+ if (isUnsupportedState(state, raw)) {
throw new Error(
"Unsupported workflow tool run state: start a new session or import its conversation.",
);
}
- const raw = state?.[WORKFLOW_TOOL_RUNS_STATE_KEY];
if (raw === undefined) return { version: WORKFLOW_TOOL_RUNS_VERSION, runs: [] };
return parseRegistry(raw);
}
-export function getWorkflowToolRuns(
- state: SessionStateMap | undefined,
-): readonly WorkflowToolRun[] {
- return readRegistry(state).runs;
-}
-
-/** Parent-observed lifecycle state. Input requests are tracked on the parent session instead. */
-export type BackgroundTaskState = Exclude<TaskStatus, "input_required">;
-
-/** A background run with its decoded lifecycle view. */
-export type BackgroundTask = TaskView & {
- /** Overlapping work reported together; a task without a join target starts its own cohort. */
- readonly cohortId: string;
- /** The parent turn that started the task. */
- readonly turnId: string;
- readonly run: BackgroundWorkflowToolRun;
-};
-
-export interface BackgroundTaskFilter {
- readonly state?: BackgroundTaskState | readonly BackgroundTaskState[];
- readonly cohortId?: string;
- readonly turnId?: string;
-}
-
-export interface BackgroundTasks {
- get(taskId: string): BackgroundTask | undefined;
- query(filter?: BackgroundTaskFilter): readonly BackgroundTask[];
-}
-
-/**
- * Read-only parent view: a task without a recorded terminal outcome is working.
- * Only returned tasks are decoded, so one corrupt retained outcome cannot block
- * reads of unrelated tasks, and working-only reads never decode.
- */
-export function getBackgroundTasks(state: SessionStateMap | undefined): BackgroundTasks {
- const runs = getWorkflowToolRuns(state).filter(
- (run): run is BackgroundWorkflowToolRun => run.lifetime === "session",
- );
- return {
- get(taskId) {
- const run = runs.find((candidate) => candidate.task.taskId === taskId);
- return run === undefined ? undefined : toBackgroundTask(run);
- },
- query(filter = {}) {
- const states: readonly TaskStatus[] | undefined =
- typeof filter.state === "string" ? [filter.state] : filter.state;
- const admitsOutcomes = states === undefined || states.some((status) => status !== "working");
- return runs.flatMap((run) => {
- if (filter.cohortId !== undefined && cohortIdOf(run) !== filter.cohortId) return [];
- if (filter.turnId !== undefined && run.origin.turnId !== filter.turnId) return [];
- if (run.task.outcome !== undefined && !admitsOutcomes) return [];
- const task = toBackgroundTask(run);
- return states === undefined || states.includes(task.status) ? [task] : [];
- });
- },
- };
-}
-
-function cohortIdOf(run: BackgroundWorkflowToolRun): string {
- return run.task.cohortId ?? run.task.taskId;
-}
-
-function toBackgroundTask(run: BackgroundWorkflowToolRun): BackgroundTask {
- const view = readWorkflowTaskView(run.task) ?? {
- taskId: run.task.taskId,
- metadata: run.task.metadata,
- status: "working" as const,
- };
- return { ...view, cohortId: cohortIdOf(run), turnId: run.origin.turnId, run };
+function isUnsupportedState(state: SessionStateMap | undefined, raw: unknown): boolean {
+ const hasRetiredStore =
+ state?.["eve.tasks"] !== undefined || state?.["eve.runtime.workflowToolRuns"] !== undefined;
+ const hasEarlierVersion = isObject(raw) && raw.version !== WORKFLOW_TOOL_RUNS_VERSION;
+ return hasRetiredStore || hasEarlierVersion;
}
export function getBlockingWorkflowToolRuns(
state: SessionStateMap | undefined,
turnId?: string,
): readonly BlockingWorkflowToolRun[] {
- return getWorkflowToolRuns(state).filter(
- (entry): entry is BlockingWorkflowToolRun =>
- entry.lifetime === "turn" && (turnId === undefined || entry.origin.turnId === turnId),
+ return readRegistry(state).runs.filter(
+ (entry) => turnId === undefined || entry.origin.turnId === turnId,
);
}
@@ -366,10 +107,10 @@ function writeRegistry(
};
}
-/** Registration is idempotent by originating turn and call; retained task facts survive replay. */
+/** Registration is idempotent by originating turn and call. */
export function registerWorkflowToolRun<T extends { readonly state?: SessionStateMap }>(
session: T,
- entry: WorkflowToolRun,
+ entry: BlockingWorkflowToolRun,
): T {
const registry = readRegistry(session.state);
const runs = [...registry.runs];
@@ -378,47 +119,9 @@ export function registerWorkflowToolRun<T extends { readonly state?: SessionStat
candidate.origin.turnId === entry.origin.turnId && candidate.callId === entry.callId,
);
const previous = runs[index];
- if (
- previous !== undefined &&
- (previous.lifetime !== entry.lifetime || previous.toolName !== entry.toolName)
- ) {
- throw new Error("Replayed invocation changed its ownership or tool identity.");
+ if (previous !== undefined && previous.toolName !== entry.toolName) {
+ throw new Error("Replayed invocation changed its tool identity.");
}
- if (entry.lifetime === "session") {
- if (previous?.lifetime === "session") {
- if (entry.task.taskId !== previous.task.taskId)
- throw new Error("Replayed invocation changed its task identity.");
- entry = {
- ...entry,
- task: {
- ...previous.task,
- ...entry.task,
- metadata: { ...previous.task.metadata, ...entry.task.metadata },
- activityWorkIdentity:
- entry.task.activityWorkIdentity === undefined
- ? previous.task.activityWorkIdentity
- : { ...previous.task.activityWorkIdentity, ...entry.task.activityWorkIdentity },
- cohortId: previous.task.cohortId,
- dispatchContext: previous.task.dispatchContext,
- outcome: previous.task.outcome ?? entry.task.outcome,
- },
- };
- } else {
- const pending = runs.find(
- (candidate): candidate is BackgroundWorkflowToolRun =>
- candidate.lifetime === "session" && candidate.task.outcome === undefined,
- );
- entry = {
- ...entry,
- task: {
- ...entry.task,
- cohortId:
- pending === undefined ? undefined : (pending.task.cohortId ?? pending.task.taskId),
- },
- };
- }
- }
- if (entry.lifetime === "session") readWorkflowTaskView(entry.task);
if (previous === undefined) runs.push(entry);
else
runs[index] = {
@@ -430,50 +133,7 @@ export function registerWorkflowToolRun<T extends { readonly state?: SessionStat
return { ...session, state: writeRegistry(session.state, { ...registry, runs }) };
}
-/** Records the first terminal outcome and distinguishes it from repeated or late reports. */
-export function recordWorkflowTaskView(
- state: SessionStateMap | undefined,
- view: TaskView,
-): {
- readonly state: SessionStateMap | undefined;
- readonly view: TaskView;
- /** True only when this call recorded the task's first outcome. */
- readonly firstOutcome: boolean;
-} {
- const { taskId, metadata, ...result } = view;
- const outcome = parseTaskOutcome(result);
- if (!isNonEmptyString(taskId) || !isTaskMetadata(metadata) || outcome === undefined)
- throw new Error("Invalid terminal workflow task view.");
- const registry = readRegistry(state);
- const runs = [...registry.runs];
- const index = runs.findIndex(
- (entry) => entry.lifetime === "session" && entry.task.taskId === taskId,
- );
- const entry = runs[index];
- if (entry === undefined || entry.lifetime !== "session")
- return { state, view, firstOutcome: false };
- if (!sameTaskMetadata(entry.task.metadata, metadata))
- throw new Error(`Task view metadata does not match invocation "${view.taskId}".`);
- const previous = readWorkflowTaskView(entry.task);
- // Parent delivery order decides settlement. Replays and late outcomes cannot replace it.
- if (previous !== undefined) {
- return { state, view: previous, firstOutcome: false };
- }
- runs[index] = {
- ...entry,
- task: {
- ...entry.task,
- outcome,
- },
- };
- return {
- state: writeRegistry(state, { ...registry, runs }),
- view,
- firstOutcome: true,
- };
-}
-
-/** Removes only this turn's waiting calls. Session-owned task payloads are never pruned here. */
+/** Removes this turn's waiting calls, or only one of them when `callId` is given. */
export function removeBlockingWorkflowToolRuns<T extends { readonly state?: SessionStateMap }>(
session: T,
turnId: string,
@@ -482,10 +142,7 @@ export function removeBlockingWorkflowToolRuns<T extends { readonly state?: Sess
const registry = readRegistry(session.state);
const entries = registry.runs;
const remaining = entries.filter(
- (entry) =>
- entry.lifetime !== "turn" ||
- entry.origin.turnId !== turnId ||
- (callId !== undefined && entry.callId !== callId),
+ (entry) => entry.origin.turnId !== turnId || (callId !== undefined && entry.callId !== callId),
);
return remaining.length === entries.length
? session
@@ -503,6 +160,7 @@ export function findBlockingWorkflowToolRun(
);
return candidates.length === 1 ? candidates[0] : undefined;
}
+
/** The turn inbox is shared; a result settles a call only if the turn recorded that run. */
export function isInboxToolResultFromRecordedWorkflowToolRun(
state: SessionStateMap | undefined,
diff --git a/packages/eve/src/instrumentation/background-task-runtime.ts b/packages/eve/src/instrumentation/background-task-runtime.ts
deleted file mode 100644
index ec282f9f5..000000000
--- a/packages/eve/src/instrumentation/background-task-runtime.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { contextStorage, type ContextContainer } from "#context/container.js";
-import type { InstrumentationHooks } from "#instrumentation/lifecycle.js";
-import { publishBackgroundTaskSettlements } from "#instrumentation/native-events.js";
-import { rememberInstrumentationBackgroundTaskForCall } from "#instrumentation/state.js";
-import type { TaskView } from "#tasks/types.js";
-
-export interface BackgroundTaskInstrumentation {
- readonly publishBackgroundTaskSettlements: (input: {
- readonly acceptedAtMs?: number;
- readonly views: readonly TaskView[];
- }) => Promise<void>;
- readonly rememberBackgroundTasks: (
- tasks: readonly { readonly callId?: string; readonly taskId: string }[],
- ) => void;
-}
-
-export function createBackgroundTaskInstrumentation(input: {
- readonly ctx: ContextContainer;
- readonly hooks: () => InstrumentationHooks;
- readonly sessionId: string;
-}): BackgroundTaskInstrumentation {
- return {
- publishBackgroundTaskSettlements: (settlements) =>
- publishBackgroundTaskSettlements({
- ...settlements,
- hooks: input.hooks(),
- }),
- rememberBackgroundTasks: (tasks) => {
- contextStorage.run(input.ctx, () => {
- for (const task of tasks) {
- if (task.callId === undefined) continue;
- rememberInstrumentationBackgroundTaskForCall(input.sessionId, task.callId, task.taskId);
- }
- });
- },
- };
-}
diff --git a/packages/eve/src/instrumentation/lifecycle.test.ts b/packages/eve/src/instrumentation/lifecycle.test.ts
index 7a2ce41e9..cd0eeefd4 100644
--- a/packages/eve/src/instrumentation/lifecycle.test.ts
+++ b/packages/eve/src/instrumentation/lifecycle.test.ts
@@ -21,8 +21,6 @@ import {
findInstrumentationActionScopeForCall,
instrumentationStateSlot,
rememberInstrumentationActionScope,
- rememberInstrumentationBackgroundTask,
- takeInstrumentationActionScopeForTask,
} from "#instrumentation/state.js";
const { logDebug, logWarn } = vi.hoisted(() => ({ logDebug: vi.fn(), logWarn: vi.fn() }));
@@ -326,55 +324,6 @@ describe("provider state lifecycle", () => {
type: "action.failed",
});
});
-
- it("keeps an admitted background action open when its initiating turn is cancelled", async () => {
- const actionKey = actionIdempotencyKey(scope.sessionId, scope.turnId, "call-1");
- const completed = vi.fn();
- const failed = vi.fn();
- const hooks = createInstrumentationHooks([
- {
- events: {
- "action.completed": completed,
- "action.failed": failed,
- "action.started": (_event, ctx) => ctx.state.set("open"),
- },
- name: "sink",
- },
- ]);
- await contextStorage.run(new ContextContainer(), async () => {
- rememberInstrumentationActionScope(actionKey, scope);
- await hooks.publish({
- callId: "call-1",
- idempotencyKey: actionKey,
- input: {},
- kind: "tool-call",
- name: "tool",
- scope,
- type: "action.started",
- });
- rememberInstrumentationBackgroundTask("task-1", { idempotencyKey: actionKey, scope });
- await hooks.publish({
- idempotencyKey: turnIdempotencyKey(scope.sessionId, scope.turnId),
- sessionId: scope.sessionId,
- turnId: scope.turnId,
- type: "turn.cancelled",
- });
-
- expect(failed).not.toHaveBeenCalled();
- expect(instrumentationStateSlot("sink", actionKey).get()).toBe("open");
- const correlation = takeInstrumentationActionScopeForTask("task-1");
- expect(correlation).toEqual({ idempotencyKey: actionKey, scope });
- await hooks.publish({
- idempotencyKey: correlation!.idempotencyKey,
- outcome: "completed",
- output: { output: "done", type: "result" },
- scope: correlation!.scope,
- type: "action.completed",
- });
- expect(instrumentationStateSlot("sink", actionKey).get()).toBeUndefined();
- });
- expect(completed).toHaveBeenCalledOnce();
- });
});
describe("provider handler deadlines", () => {
diff --git a/packages/eve/src/instrumentation/native-events-background-tasks.test.ts b/packages/eve/src/instrumentation/native-events-background-tasks.test.ts
deleted file mode 100644
index 285206ed5..000000000
--- a/packages/eve/src/instrumentation/native-events-background-tasks.test.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { ContextContainer, contextStorage } from "#context/container.js";
-import { deserializeContext, serializeContext } from "#context/serialize.js";
-import type {
- InstrumentationAttemptScope,
- InstrumentationEvent,
- InstrumentationHooks,
-} from "#instrumentation/lifecycle.js";
-import { actionIdempotencyKey } from "#instrumentation/lifecycle.js";
-import {
- createInstrumentationHandleEvent,
- publishBackgroundTaskSettlements,
-} from "#instrumentation/native-events.js";
-import { rememberInstrumentationBackgroundTaskForCall } from "#instrumentation/state.js";
-import { createActionResultEvent, createActionsRequestedEvent } from "#protocol/message.js";
-import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";
-import { deriveTaskId } from "#tasks/task-id.js";
-
-const scope: InstrumentationAttemptScope = {
- attemptId: "session-1:turn-1:0:0",
- attemptIndex: 0,
- sessionId: "session-1",
- stepIndex: 0,
- turnId: "turn-1",
-};
-
-function recordingHooks(events: InstrumentationEvent[]): InstrumentationHooks {
- return {
- capturesContent: true,
- publish: async (event) => void events.push(event),
- };
-}
-
-async function emitBackgroundReceipt(
- context: ContextContainer,
- events: InstrumentationEvent[],
-): Promise<string> {
- const taskId = deriveTaskId({
- callId: "workflow-1",
- parentSessionId: scope.sessionId,
- parentTurnId: scope.turnId,
- });
- await contextStorage.run(context, async () => {
- const handleEvent = createInstrumentationHandleEvent({
- getAttemptScope: () => scope,
- handleEvent: async () => {},
- hooks: recordingHooks(events),
- sessionId: scope.sessionId,
- })!;
- await handleEvent(
- createActionsRequestedEvent({
- actions: [
- {
- callId: "workflow-1",
- input: { report: "weekly" },
- kind: "workflow-tool-call",
- toolName: "publish",
- workflowId: "publish-workflow",
- },
- ],
- sequence: 0,
- stepIndex: 0,
- turnId: scope.turnId,
- }),
- );
- await handleEvent(
- createActionResultEvent({
- result: {
- callId: "workflow-1",
- kind: "tool-result",
- output: { status: "working", taskId },
- toolName: "publish",
- },
- sequence: 0,
- stepIndex: 0,
- turnId: scope.turnId,
- }),
- );
- rememberInstrumentationBackgroundTaskForCall(scope.sessionId, "workflow-1", taskId);
- });
- return taskId;
-}
-
-describe("background task action instrumentation", () => {
- it("keeps the action open until its terminal task view arrives", async () => {
- const events: InstrumentationEvent[] = [];
- const context = new ContextContainer();
- const taskId = await emitBackgroundReceipt(context, events);
- expect(events.map((event) => event.type)).toEqual(["action.started"]);
-
- const restored = await deserializeContext(
- preserveSerializedBackgroundTaskObservabilityState({}, serializeContext(context), [
- { taskId },
- ]),
- );
- await contextStorage.run(restored, async () => {
- await publishBackgroundTaskSettlements({
- acceptedAtMs: 1_234,
- hooks: recordingHooks(events),
- views: [
- {
- lastOutput: { data: { reportId: "report-1" }, type: "result" },
- metadata: { kind: "tool", name: "publish" },
- status: "completed",
- taskId,
- usage: {
- cacheReadTokens: 3,
- cacheWriteTokens: 4,
- inputTokens: 10,
- outputTokens: 5,
- },
- },
- ],
- });
- });
-
- expect(events[1]).toEqual({
- acceptedAtMs: 1_234,
- idempotencyKey: actionIdempotencyKey(scope.sessionId, scope.turnId, "workflow-1"),
- outcome: "completed",
- output: { output: { reportId: "report-1" }, type: "result" },
- scope,
- type: "action.completed",
- usage: {
- inputTokenDetails: { cacheReadTokens: 3, cacheWriteTokens: 4 },
- inputTokens: 10,
- outputTokens: 5,
- },
- });
- });
-
- it.each([
- {
- error: "publish failed",
- errorCode: "BACKGROUND_TASK_FAILED",
- status: "failed" as const,
- view: {
- lastOutput: { data: "publish failed", type: "error" as const },
- metadata: { kind: "tool", name: "publish" },
- status: "failed" as const,
- },
- },
- {
- error: expect.any(Error),
- errorCode: "BACKGROUND_TASK_CANCELLED",
- status: "cancelled" as const,
- view: {
- metadata: { kind: "tool", name: "publish" },
- status: "cancelled" as const,
- },
- },
- ])("settles the action when its task is $status", async (input) => {
- const events: InstrumentationEvent[] = [];
- const context = new ContextContainer();
- const taskId = await emitBackgroundReceipt(context, events);
- await contextStorage.run(context, async () => {
- await publishBackgroundTaskSettlements({
- acceptedAtMs: 1_234,
- hooks: recordingHooks(events),
- views: [{ ...input.view, taskId }],
- });
- });
-
- expect(events[1]).toMatchObject({
- acceptedAtMs: 1_234,
- error: input.error,
- errorCode: input.errorCode,
- outcome: input.status,
- type: "action.failed",
- });
- });
-});
diff --git a/packages/eve/src/instrumentation/native-events.ts b/packages/eve/src/instrumentation/native-events.ts
index 9c515bc55..9bb683ebd 100644
--- a/packages/eve/src/instrumentation/native-events.ts
+++ b/packages/eve/src/instrumentation/native-events.ts
@@ -20,11 +20,9 @@ import {
turnIdempotencyKey,
} from "#instrumentation/lifecycle.js";
import {
- findInstrumentationActionScopeForCall,
rememberInstrumentationActionScope,
rememberInstrumentationInputScope,
takeInstrumentationActionScopeForCall,
- takeInstrumentationActionScopeForTask,
takeInstrumentationInputScope,
} from "#instrumentation/state.js";
import type { ResolvedInputBatch } from "#harness/input-requests.js";
@@ -36,8 +34,6 @@ import {
type RuntimeActionResult,
} from "#shared/action-types.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
-import { deriveTaskId } from "#tasks/task-id.js";
-import type { TaskUsage, TaskView } from "#tasks/types.js";
export interface CreateInstrumentationHandleEventInput {
readonly agentName?: string;
@@ -229,16 +225,11 @@ async function publishActionTerminal(
input: CreateInstrumentationHandleEventInput,
hooks: InstrumentationHooks,
): Promise<void> {
- const correlation = findInstrumentationActionScopeForCall(
+ const correlation = takeInstrumentationActionScopeForCall(
input.sessionId,
event.data.result.callId,
);
if (correlation === undefined) return;
- const backgroundTask = readBackgroundTaskReceipt(event.data.result, correlation);
- if (event.data.status === "completed" && backgroundTask !== undefined) {
- return;
- }
- takeInstrumentationActionScopeForCall(input.sessionId, event.data.result.callId);
const { idempotencyKey, scope } = correlation;
const capturesOutputs = hooks.capturesOutputs ?? hooks.capturesContent;
@@ -283,85 +274,6 @@ async function publishActionTerminal(
);
}
-/** Settles actions whose model-facing result was an admitted background-task receipt. */
-export async function publishBackgroundTaskSettlements(input: {
- readonly acceptedAtMs?: number;
- readonly hooks: InstrumentationHooks;
- readonly views: readonly TaskView[];
-}): Promise<void> {
- const capturesOutputs = input.hooks.capturesOutputs ?? input.hooks.capturesContent;
- const acceptedAtMs = input.acceptedAtMs ?? Date.now();
- for (const view of input.views) {
- if (view.status !== "completed" && view.status !== "failed" && view.status !== "cancelled") {
- continue;
- }
- const correlation = takeInstrumentationActionScopeForTask(view.taskId);
- if (correlation === undefined) continue;
- if (view.status === "completed") {
- await input.hooks.publish(
- Object.freeze({
- acceptedAtMs,
- idempotencyKey: correlation.idempotencyKey,
- outcome: "completed",
- output: Object.freeze(
- capturesOutputs ? { output: view.lastOutput.data, type: "result" } : { type: "result" },
- ),
- scope: correlation.scope,
- type: "action.completed",
- usage: instrumentationUsage(view.usage),
- }),
- );
- continue;
- }
- await input.hooks.publish(
- Object.freeze({
- acceptedAtMs,
- error:
- view.status === "failed"
- ? capturesOutputs
- ? view.lastOutput.data
- : undefined
- : new Error("The background task was cancelled."),
- errorCode:
- view.status === "failed" ? "BACKGROUND_TASK_FAILED" : "BACKGROUND_TASK_CANCELLED",
- idempotencyKey: correlation.idempotencyKey,
- outcome: view.status,
- scope: correlation.scope,
- type: "action.failed",
- } satisfies InstrumentationActionFailedEvent),
- );
- }
-}
-
-function readBackgroundTaskReceipt(
- result: RuntimeActionResult,
- correlation: { readonly scope: InstrumentationAttemptScope },
-): { readonly taskId: string } | undefined {
- const output = result.output;
- if (typeof output !== "object" || output === null || Array.isArray(output)) return undefined;
- if (Reflect.get(output, "status") !== "working") return undefined;
- const taskId = Reflect.get(output, "taskId");
- if (typeof taskId !== "string") return undefined;
- const expectedTaskId = deriveTaskId({
- callId: result.callId,
- parentSessionId: correlation.scope.sessionId,
- parentTurnId: correlation.scope.turnId,
- });
- return taskId === expectedTaskId ? { taskId } : undefined;
-}
-
-function instrumentationUsage(usage: TaskUsage | undefined): InstrumentationUsage | undefined {
- if (usage === undefined) return undefined;
- return {
- inputTokenDetails: {
- cacheReadTokens: usage.cacheReadTokens,
- cacheWriteTokens: usage.cacheWriteTokens,
- },
- inputTokens: usage.inputTokens,
- outputTokens: usage.outputTokens,
- };
-}
-
function actionUsage(result: RuntimeActionResult): InstrumentationUsage | undefined {
if (
result.kind !== "subagent-result" ||
diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.ts
index eb082e939..b13465fa9 100644
--- a/packages/eve/src/instrumentation/runtime.ts
+++ b/packages/eve/src/instrumentation/runtime.ts
@@ -28,10 +28,6 @@ import {
publishInputResolutions,
type CreateInstrumentationHandleEventInput,
} from "#instrumentation/native-events.js";
-import {
- createBackgroundTaskInstrumentation,
- type BackgroundTaskInstrumentation,
-} from "#instrumentation/background-task-runtime.js";
import type { ResolvedInputBatch } from "#harness/input-requests.js";
import type { HandleEventFn } from "#harness/types.js";
import {
@@ -175,7 +171,7 @@ export interface SessionInstrumentation {
) => Promise<TResult>;
}
-export interface ExecutionInstrumentation extends BackgroundTaskInstrumentation {
+export interface ExecutionInstrumentation {
readonly createHandleEvent: (input: {
readonly handleEvent?: HandleEventFn;
readonly turnId?: string;
@@ -484,11 +480,6 @@ export function bindInstrumentationRuntime(
};
};
return {
- ...createBackgroundTaskInstrumentation({
- ctx,
- hooks: () => bindHooks(readSessionContext()),
- sessionId: boundSession.sessionId,
- }),
createHandleEvent: (input) => {
const sessionContext = readSessionContext();
return createInstrumentationHandleEvent({
diff --git a/packages/eve/src/instrumentation/state.test.ts b/packages/eve/src/instrumentation/state.test.ts
index d34ca19f4..0d9be754c 100644
--- a/packages/eve/src/instrumentation/state.test.ts
+++ b/packages/eve/src/instrumentation/state.test.ts
@@ -12,16 +12,11 @@ import {
instrumentationStateSlot,
isInstrumentationStateAbandoned,
rememberInstrumentationActionScope,
- rememberInstrumentationBackgroundTaskForCall,
releaseAllInstrumentationAttemptState,
releaseAllInstrumentationState,
- releaseAllInstrumentationTurnState,
- takeInstrumentationActionScopeForTask,
takeInstrumentationActionScopeForCall,
- takeInstrumentationActionScopes,
} from "#instrumentation/state.js";
import { preserveSerializedInstrumentationState } from "#instrumentation/state.js";
-import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";
describe("instrumentation state", () => {
it("survives a serialized step boundary", async () => {
@@ -79,44 +74,6 @@ describe("instrumentation state", () => {
});
});
- it("keeps a background action across turn cleanup until its task settles", async () => {
- const actionKey = actionIdempotencyKey("session-1", "turn-1", "call-1");
- const scope: InstrumentationAttemptScope = {
- attemptId: "session-1:turn-1:0:0",
- attemptIndex: 0,
- sessionId: "session-1",
- stepIndex: 0,
- turnId: "turn-1",
- };
- const context = new ContextContainer();
- await contextStorage.run(context, async () => {
- rememberInstrumentationActionScope(actionKey, scope);
- rememberInstrumentationBackgroundTaskForCall(scope.sessionId, "call-1", "task-1");
- instrumentationStateSlot("sink", actionKey, {
- sessionId: scope.sessionId,
- turnId: scope.turnId,
- }).set("open");
- });
-
- const serialized = await serializeContext(context);
- expect(serialized["eve.harness.instrumentationActionScopes"]).toEqual({
- [actionKey]: { scope, taskId: "task-1" },
- });
- expect(serialized).not.toHaveProperty("eve.harness.instrumentationBackgroundTasks");
- const restored = await deserializeContext(serialized);
- contextStorage.run(restored, () => {
- expect(takeInstrumentationActionScopes(scope.sessionId, scope.turnId)).toEqual([]);
- releaseAllInstrumentationTurnState(scope.sessionId, scope.turnId);
- expect(instrumentationStateSlot("sink", actionKey).get()).toBe("open");
- expect(findInstrumentationActionScopeForCall(scope.sessionId, "call-1")).toBeDefined();
- expect(takeInstrumentationActionScopeForTask("task-1")).toEqual({
- idempotencyKey: actionKey,
- scope,
- });
- expect(findInstrumentationActionScopeForCall(scope.sessionId, "call-1")).toBeUndefined();
- });
- });
-
it("deserializes the previous scope-only action state", async () => {
const scope: InstrumentationAttemptScope = {
attemptId: "session-1:turn-1:0:0",
@@ -199,116 +156,6 @@ describe("instrumentation state", () => {
});
});
- it("preserves only observability state owned by committed background tasks", () => {
- const existingAction = "action:session-1:turn-0:existing";
- const backgroundAction = "action:session-1:turn-1:background";
- const unrelatedAction = "action:session-1:turn-1:unrelated";
- const original = {
- authored: "original",
- "eve.activeChannelDeliveries": { existing: true },
- "eve.harness.agentTrace": {
- actionAnchors: { [existingAction]: { callId: "existing", trace: "existing" } },
- actions: { [existingAction]: { callId: "existing", trace: "existing" } },
- invocations: {
- "invocation-existing": {
- callId: "existing-child",
- parentActionCallId: "existing",
- },
- },
- sessions: { "session-1": { trace: "session" } },
- turns: { "session-1\0turn-0": { trace: "turn" } },
- },
- "eve.harness.instrumentationActionScopes": {
- [existingAction]: { scope: { turnId: "turn-0" }, taskId: "task-existing" },
- },
- "eve.harness.instrumentationInputScopes": { existing: { turnId: "turn-0" } },
- "eve.harness.instrumentationState": {
- [`sink\0${existingAction}`]: { value: "existing" },
- },
- };
- const completed = {
- authored: "completed",
- "eve.activeChannelDeliveries": { unrelated: true },
- "eve.harness.agentTrace": {
- actionAnchors: {
- [backgroundAction]: { callId: "background", trace: "background" },
- [unrelatedAction]: { callId: "unrelated", trace: "unrelated" },
- },
- actions: {
- [backgroundAction]: { callId: "background", trace: "background" },
- [unrelatedAction]: { callId: "unrelated", trace: "unrelated" },
- },
- invocations: {
- "invocation-background": {
- callId: "background-child",
- parentActionCallId: "background",
- },
- "invocation-background-nested": {
- callId: "background-grandchild",
- parentActionCallId: "background-child",
- },
- "invocation-unrelated": {
- callId: "unrelated-child",
- parentActionCallId: "unrelated",
- },
- },
- sessions: { "session-2": { trace: "unrelated" } },
- turns: { "session-1\0turn-1": { trace: "unrelated" } },
- },
- "eve.harness.instrumentationActionScopes": {
- [backgroundAction]: { scope: { turnId: "turn-1" }, taskId: "task-1" },
- [unrelatedAction]: { scope: { turnId: "turn-1" }, taskId: "task-2" },
- },
- "eve.harness.instrumentationInputScopes": { unrelated: { turnId: "turn-1" } },
- "eve.harness.instrumentationState": {
- [`sink\0${backgroundAction}`]: { value: "background" },
- [`sink\0${unrelatedAction}`]: { value: "unrelated" },
- },
- };
-
- expect(
- preserveSerializedBackgroundTaskObservabilityState(original, completed, [
- { taskId: "task-1" },
- ]),
- ).toEqual({
- ...original,
- "eve.harness.agentTrace": {
- actionAnchors: {
- [existingAction]: { callId: "existing", trace: "existing" },
- [backgroundAction]: { callId: "background", trace: "background" },
- },
- actions: {
- [existingAction]: { callId: "existing", trace: "existing" },
- [backgroundAction]: { callId: "background", trace: "background" },
- },
- invocations: {
- "invocation-existing": {
- callId: "existing-child",
- parentActionCallId: "existing",
- },
- "invocation-background": {
- callId: "background-child",
- parentActionCallId: "background",
- },
- "invocation-background-nested": {
- callId: "background-grandchild",
- parentActionCallId: "background-child",
- },
- },
- sessions: { "session-1": { trace: "session" } },
- turns: { "session-1\0turn-0": { trace: "turn" } },
- },
- "eve.harness.instrumentationActionScopes": {
- [existingAction]: { scope: { turnId: "turn-0" }, taskId: "task-existing" },
- [backgroundAction]: { scope: { turnId: "turn-1" }, taskId: "task-1" },
- },
- "eve.harness.instrumentationState": {
- [`sink\0${existingAction}`]: { value: "existing" },
- [`sink\0${backgroundAction}`]: { value: "background" },
- },
- });
- });
-
it("persists abandonment across serialization", async () => {
const context = new ContextContainer();
contextStorage.run(context, () => {
diff --git a/packages/eve/src/instrumentation/state.ts b/packages/eve/src/instrumentation/state.ts
index a5cb18d46..63b7a5894 100644
--- a/packages/eve/src/instrumentation/state.ts
+++ b/packages/eve/src/instrumentation/state.ts
@@ -30,7 +30,6 @@ export interface InstrumentationStateOwner {
type InstrumentationStateMap = Readonly<Record<string, InstrumentationStateRecord>>;
interface InstrumentationActionState {
readonly scope: InstrumentationAttemptScope;
- readonly taskId?: string;
}
type InstrumentationActionStateMap = Readonly<Record<string, InstrumentationActionState>>;
type InstrumentationScopeMap = Readonly<Record<string, InstrumentationAttemptScope>>;
@@ -163,13 +162,9 @@ export function releaseAllInstrumentationAttemptState(attemptId: string): void {
}
export function releaseAllInstrumentationTurnState(sessionId: string, turnId?: string): void {
- const protectedActions =
- turnId === undefined ? new Set<string>() : backgroundActionKeys(sessionId, turnId);
releaseMatchingInstrumentationState(
- (key, record) =>
- record.sessionId === sessionId &&
- (turnId === undefined || record.turnId === turnId) &&
- !protectedActions.has(instrumentationStateOperationId(key)),
+ (_key, record) =>
+ record.sessionId === sessionId && (turnId === undefined || record.turnId === turnId),
);
}
@@ -197,13 +192,10 @@ export function rememberInstrumentationActionScope(
idempotencyKey: string,
scope: InstrumentationAttemptScope,
): void {
- writeContextKey(InstrumentationActionStateKey, (state) => {
- const taskId = state[idempotencyKey]?.taskId;
- return {
- ...state,
- [idempotencyKey]: taskId === undefined ? { scope } : { scope, taskId },
- };
- });
+ writeContextKey(InstrumentationActionStateKey, (state) => ({
+ ...state,
+ [idempotencyKey]: { scope },
+ }));
}
/** Remembers where a durable input request originated. */
@@ -236,30 +228,6 @@ interface InstrumentationActionCorrelation {
readonly scope: InstrumentationAttemptScope;
}
-/** Binds an admitted background task to the action that started it. */
-export function rememberInstrumentationBackgroundTask(
- taskId: string,
- correlation: InstrumentationActionCorrelation,
-): void {
- writeContextKey(InstrumentationActionStateKey, (state) => ({
- ...state,
- [correlation.idempotencyKey]: {
- scope: state[correlation.idempotencyKey]?.scope ?? correlation.scope,
- taskId,
- },
- }));
-}
-
-/** Binds a background task when its executor admits the originating call. */
-export function rememberInstrumentationBackgroundTaskForCall(
- sessionId: string,
- callId: string,
- taskId: string,
-): void {
- const correlation = findInstrumentationActionScopeForCall(sessionId, callId);
- if (correlation !== undefined) rememberInstrumentationBackgroundTask(taskId, correlation);
-}
-
export function findInstrumentationActionScopeForCall(
sessionId: string,
callId: string,
@@ -285,20 +253,6 @@ export function takeInstrumentationActionScopeForCall(
return correlation;
}
-/** Reads and releases the action correlation owned by a terminal background task. */
-export function takeInstrumentationActionScopeForTask(
- taskId: string,
-): InstrumentationActionCorrelation | undefined {
- const actions = contextStorage.getStore()?.get(InstrumentationActionStateKey);
- if (actions === undefined) return undefined;
- for (const [idempotencyKey, action] of Object.entries(actions)) {
- if (action.taskId !== taskId) continue;
- releaseInstrumentationActionCorrelation(idempotencyKey);
- return { idempotencyKey, scope: action.scope };
- }
- return undefined;
-}
-
/** Takes every still-open action owned by one session or turn. */
export function takeInstrumentationActionScopes(
sessionId: string,
@@ -310,8 +264,7 @@ export function takeInstrumentationActionScopes(
.filter(
([, action]) =>
action.scope.sessionId === sessionId &&
- (turnId === undefined || action.scope.turnId === turnId) &&
- (turnId === undefined || action.taskId === undefined),
+ (turnId === undefined || action.scope.turnId === turnId),
)
.map(([idempotencyKey, action]) => ({ idempotencyKey, scope: action.scope }));
if (correlations.length === 0) return [];
@@ -332,20 +285,6 @@ function releaseInstrumentationActionCorrelation(idempotencyKey: string): void {
});
}
-function backgroundActionKeys(sessionId: string, turnId: string): ReadonlySet<string> {
- const actions = contextStorage.getStore()?.get(InstrumentationActionStateKey);
- if (actions === undefined) return new Set();
- return new Set(
- Object.entries(actions).flatMap(([idempotencyKey, action]) =>
- action.taskId !== undefined &&
- action.scope.sessionId === sessionId &&
- action.scope.turnId === turnId
- ? [idempotencyKey]
- : [],
- ),
- );
-}
-
function writeSlot(
state: InstrumentationStateMap,
key: string,
@@ -384,10 +323,6 @@ function stateKey(provider: string, idempotencyKey: string): string {
return `${provider}\0${idempotencyKey}`;
}
-function instrumentationStateOperationId(key: string): string {
- return key.slice(key.indexOf("\0") + 1);
-}
-
function deserializeState(data: unknown): InstrumentationStateMap {
if (typeof data !== "object" || data === null || Array.isArray(data)) return {};
const state: Record<string, InstrumentationStateRecord> = {};
@@ -440,8 +375,7 @@ function deserializeActionStates(data: unknown): InstrumentationActionStateMap {
!Array.isArray(record["scope"])
? (record["scope"] as InstrumentationAttemptScope)
: (value as InstrumentationAttemptScope);
- const taskId = typeof record["taskId"] === "string" ? record["taskId"] : undefined;
- actions[idempotencyKey] = taskId === undefined ? { scope } : { scope, taskId };
+ actions[idempotencyKey] = { scope };
}
return actions;
}
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.ts
index b7d0247c7..6063809af 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts
@@ -155,16 +155,6 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal
if (hasExecute) {
definition.execute = expectFunction(record.execute, message) as ToolExecuteFn;
}
- if (record.execution !== undefined) {
- if (!hasExecute) {
- throw new Error(`${message} Execute-less native tools cannot use background execution.`);
- }
- const execution = expectString(record.execution, message);
- if (execution !== "background") {
- throw new Error(`${message} Expected "execution" to be "background".`);
- }
- definition.execution = execution;
- }
if (outputSchema !== undefined) {
definition.outputSchema = outputSchema;
}
diff --git a/packages/eve/src/internal/authored-module-loader.integration.test.ts b/packages/eve/src/internal/authored-module-loader.integration.test.ts
index 0ea99e5bc..8c9ab1fce 100644
--- a/packages/eve/src/internal/authored-module-loader.integration.test.ts
+++ b/packages/eve/src/internal/authored-module-loader.integration.test.ts
@@ -138,7 +138,7 @@ export default defineWorkflowTool({ description: "Probe", inputSchema: { type: "
"use workflow";
return delegate(ctx, input);
} });`,
- "agent/lib/delegate.ts": `export async function delegate(ctx, input) { return ctx.agent("researcher", input); }`,
+ "agent/lib/delegate.ts": `export async function delegate(ctx, input) {\n const response = await ctx.agent("researcher").send(input.message);\n return (await response.result()).message;\n}`,
},
name: "valid-workflow-helper",
});
diff --git a/packages/eve/src/internal/invocation/workflow-execution.ts b/packages/eve/src/internal/invocation/workflow-execution.ts
index 06b09958d..e29b93aef 100644
--- a/packages/eve/src/internal/invocation/workflow-execution.ts
+++ b/packages/eve/src/internal/invocation/workflow-execution.ts
@@ -364,7 +364,7 @@ function projectInvocation(
break;
case "message.completed":
// Only tool-call narration continues the turn; any other finish is the reply.
- if (event.data.finishReason !== "tool-calls" && event.data.message !== null) {
+ if (event.data.finishReason !== "tool-calls") {
result = safeJson(event.data.message);
}
break;
diff --git a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
index e8a8ba254..35162cf36 100644
--- a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
@@ -705,13 +705,12 @@ describe("development generation artifacts", () => {
const app = await scenarioApp({
files: {
"agents/assistant/agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',
- "agents/assistant/agent/instructions.md": "Use the background tool.",
+ "agents/assistant/agent/instructions.md": "Use the mission plan tool.",
"agents/assistant/agent/tools/request_mission_plan.mjs": [
'import { defineWorkflowTool } from "eve/tools";',
"",
"export default defineWorkflowTool({",
' description: "Run a mission plan.",',
- ' execution: "background",',
" inputSchema: {},",
" async execute() {",
' "use workflow";',
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 c92db586b..2b91da03f 100644
--- a/packages/eve/src/internal/structural-tests/file-length.test.ts
+++ b/packages/eve/src/internal/structural-tests/file-length.test.ts
@@ -17,7 +17,6 @@ const LONG_SOURCE_FILE_ALLOWLIST = new Set<string>([
"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/events.ts b/packages/eve/src/internal/testing/events.ts
index 8269a8470..4025c5575 100644
--- a/packages/eve/src/internal/testing/events.ts
+++ b/packages/eve/src/internal/testing/events.ts
@@ -1,5 +1,5 @@
import type { UnstampedMessageStreamEvent, MessageStreamEvent } from "#protocol/message.js";
-import { isCurrentTurnBoundaryEvent } from "#protocol/message.js";
+import { isTurnSegmentBoundary, updatePendingInputRequests } from "#client/session-utils.js";
/**
* Minimal, duck-typed handle to one workflow `Run`'s readable stream.
@@ -23,11 +23,17 @@ export interface WorkflowRunHandle {
*/
export interface CapturedTurnStream {
/**
- * Reads stream lines until the next turn-boundary event (`session.waiting`,
- * `session.completed`, or `session.failed`) and returns every event
- * observed in that turn.
+ * Reads stream lines until the next turn boundary (`session.waiting`,
+ * `session.completed`, `session.failed`, or a `turn.waiting` while an input
+ * request is unanswered) and returns every event observed in that segment.
*/
nextTurn(): Promise<MessageStreamEvent[]>;
+ /**
+ * Reads stream lines until `matches` accepts an event, such as the
+ * `turn.waiting` an open turn emits while it parks, and returns every event
+ * read through that one.
+ */
+ nextUntil(matches: (event: MessageStreamEvent) => boolean): Promise<MessageStreamEvent[]>;
/** Releases the reader lock on the underlying `ReadableStream`. */
dispose(): void;
}
@@ -49,13 +55,20 @@ export function captureTurnEvents(
const decoder = options.decoder ?? new TextDecoder();
let disposed = false;
+ const readUntil = async (matches: (event: MessageStreamEvent) => boolean) => {
+ if (disposed) {
+ throw new Error("CapturedTurnStream: stream already disposed.");
+ }
+
+ return await readUntilMatch(reader, state, decoder, matches);
+ };
+
return {
async nextTurn() {
- if (disposed) {
- throw new Error("CapturedTurnStream: stream already disposed.");
- }
-
- return await readUntilBoundary(reader, state, decoder);
+ return await readUntil(createTurnSegmentBoundary());
+ },
+ async nextUntil(matches) {
+ return await readUntil(matches);
},
dispose() {
if (disposed) {
@@ -144,10 +157,19 @@ interface StreamState {
buffer: string;
}
-async function readUntilBoundary(
+function createTurnSegmentBoundary(): (event: MessageStreamEvent) => boolean {
+ const pendingInputRequests = new Set<string>();
+ return (event) => {
+ updatePendingInputRequests(pendingInputRequests, event);
+ return isTurnSegmentBoundary(event, pendingInputRequests);
+ };
+}
+
+async function readUntilMatch(
reader: ReadableStreamDefaultReader<Uint8Array>,
state: StreamState,
decoder: InstanceType<typeof TextDecoder>,
+ matches: (event: MessageStreamEvent) => boolean,
): Promise<MessageStreamEvent[]> {
const events: MessageStreamEvent[] = [];
@@ -167,7 +189,7 @@ async function readUntilBoundary(
const event = JSON.parse(line) as MessageStreamEvent;
events.push(event);
- if (isCurrentTurnBoundaryEvent(event)) {
+ if (matches(event)) {
return events;
}
}
diff --git a/packages/eve/src/internal/testing/log-records.ts b/packages/eve/src/internal/testing/log-records.ts
index 4340f303b..366cdba82 100644
--- a/packages/eve/src/internal/testing/log-records.ts
+++ b/packages/eve/src/internal/testing/log-records.ts
@@ -26,10 +26,6 @@ export const workflowSdkNotice = {
"[workflow-sdk] Queue message was delivered to a deployment it was not pinned to",
} as const;
-/** Logged when a background task reports back after its parent session ended. */
-export const taskParentEndedNotice =
- "[eve:execution.tasks.run] task notification target is gone; the parent session already ended";
-
// The workflow SDK reports a duplicate in-process delivery of the same step
// whenever redelivery races a slow step, so its presence depends on load.
const WORKFLOW_STEP_SINGLE_FLIGHT_NOTICE =
diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
index 97e2350a4..b236cae65 100644
--- a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
@@ -174,18 +174,6 @@ export async function* reportingDeployWorkflow(
return { plan };
}
-export async function* backgroundDeployWorkflow(
- input: DeployInput,
- _ctx: WorkflowToolContext,
-): AsyncGenerator<string, { readonly plan: string }> {
- "use workflow";
-
- const plan = await planDeployStep(input.service);
- yield `planned ${input.service}`;
- yield `review ${plan}`;
- return { plan };
-}
-
async function planDeployStep(service: string): Promise<string> {
"use step";
diff --git a/packages/eve/src/internal/testing/workflow-tool-run-harness.ts b/packages/eve/src/internal/testing/workflow-tool-run-harness.ts
index fc3fc400f..d16bb0b47 100644
--- a/packages/eve/src/internal/testing/workflow-tool-run-harness.ts
+++ b/packages/eve/src/internal/testing/workflow-tool-run-harness.ts
@@ -3,10 +3,7 @@ import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-a
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { serializeInputSchema, toInputSchema } from "#tools/schema.js";
import { getRun } from "#internal/workflow/runtime.js";
-import {
- type BlockingWorkflowToolDefinition,
- defineWorkflowTool,
-} from "#tools/workflow-definition.js";
+import { type WorkflowToolDefinition, defineWorkflowTool } from "#tools/workflow-definition.js";
const DEPLOY_INPUT_SCHEMA = toInputSchema({
additionalProperties: false,
@@ -46,7 +43,6 @@ export function buildWorkflowToolSerializedContext(input: {
*/
export async function createWorkflowToolRuntime(input: {
readonly agentName: string;
- readonly background?: boolean;
readonly execute: (...args: never[]) => unknown;
readonly inputSchema?: ResolvedToolDefinition["inputSchema"];
readonly toolName: string;
@@ -58,9 +54,8 @@ export async function createWorkflowToolRuntime(input: {
logicalPath: `tools/${input.toolName}.ts`,
loadNamespace: async () => ({
default: defineWorkflowTool({
- execution: input.background === true ? "background" : undefined,
description: `Deploys a service (${input.toolName}).`,
- execute: input.execute as BlockingWorkflowToolDefinition["execute"],
+ execute: input.execute as WorkflowToolDefinition["execute"],
inputSchema: serializeInputSchema(input.inputSchema ?? DEPLOY_INPUT_SCHEMA) ?? {},
}),
}),
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 11bd1653a..f386687ca 100644
--- a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
@@ -142,6 +142,7 @@ describe("WorkflowBundleBuilder", () => {
resolvePackageSourceDirectoryPath("src/execution"),
resolvePackageSourceDirectoryPath("src/runtime/subagents"),
resolvePackageSourceDirectoryPath("src/subagents"),
+ resolvePackageSourceDirectoryPath("src/tools/provided"),
]);
});
@@ -660,13 +661,9 @@ describe("WorkflowBundleBuilder", () => {
});
it.each([
- ["sleep tool", "src/execution/tools/sleep-workflow.ts", "executeSleepTool"],
+ ["sleep tool", "src/tools/provided/sleep-workflow.ts", "executeSleepTool"],
["session owner", "src/execution/session/entry.ts", "nextTurnDelivery"],
- [
- "workflow tool owner",
- "src/execution/tools/workflow/workflow.ts",
- "createBackgroundWorkflowOwner",
- ],
+ ["workflow tool owner", "src/execution/tools/workflow/workflow.ts", "workflowToolRunWorkflow"],
])("keeps the %s schemas out of the workflow driver", async (_name, sourcePath, marker) => {
const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-no-schemas-"));
const outDir = join(tempRoot, "workflow-build");
diff --git a/packages/eve/src/internal/workflow-bundle/builder.ts b/packages/eve/src/internal/workflow-bundle/builder.ts
index 2e35eb889..cef526c56 100644
--- a/packages/eve/src/internal/workflow-bundle/builder.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder.ts
@@ -68,6 +68,7 @@ export class WorkflowBundleBuilder {
resolvePackageSourceDirectoryPath("src/execution"),
resolvePackageSourceDirectoryPath("src/runtime/subagents"),
resolvePackageSourceDirectoryPath("src/subagents"),
+ resolvePackageSourceDirectoryPath("src/tools/provided"),
];
if (options.includeTestFixtures === true) {
dirs.push(resolvePackageSourceDirectoryPath("src/internal/testing"));
@@ -107,7 +108,7 @@ export class WorkflowBundleBuilder {
if (frameworkInputFiles.length === 0) {
throw new Error(
- `Expected framework workflow source files under eve's execution, runtime/subagents, or subagents source directories.`,
+ `Expected framework workflow source files under eve's execution, runtime/subagents, subagents, or tools/provided 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 ea9b8003d..aba9d2822 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
@@ -117,7 +117,7 @@ describe("applyWorkflowTransform", () => {
});
it("stamps versioned package workflow metadata without consuming the framework body", async () => {
- const filename = "src/execution/tools/sleep.ts";
+ const filename = "src/tools/provided/sleep-workflow.ts";
const transformed = await applyWorkflowTransform(
filename,
[
diff --git a/packages/eve/src/protocol/activity.ts b/packages/eve/src/protocol/activity.ts
index 81a6c81b2..5a33378df 100644
--- a/packages/eve/src/protocol/activity.ts
+++ b/packages/eve/src/protocol/activity.ts
@@ -1,6 +1,6 @@
const MAX_ACTIVITY_EVENTS_PER_BATCH = 100;
-export type ActivityWorkKind = "root-turn" | "subagent" | "remote-agent" | "task";
+export type ActivityWorkKind = "root-turn" | "subagent" | "remote-agent";
export type ActivityWorkPhase = "running" | "completed" | "failed" | "cancelled";
type ActivityActionKind = "tool" | "skill";
export type ActivityActionPhase = "running" | "completed" | "failed" | "rejected" | "cancelled";
@@ -130,7 +130,7 @@ export function parseActivityWorkIdentityV1(value: unknown): ActivityWorkIdentit
if (!isRecord(value)) return undefined;
const kind = value.kind;
if (
- !isOneOf(kind, ["root-turn", "subagent", "remote-agent", "task"] as const) ||
+ !isOneOf(kind, ["root-turn", "subagent", "remote-agent"] as const) ||
!isIdentity(value.id) ||
!isIdentity(value.rootSessionId) ||
!isIdentity(value.rootTurnId) ||
diff --git a/packages/eve/src/protocol/message-version.ts b/packages/eve/src/protocol/message-version.ts
index 5ff6cbaa2..e266a3940 100644
--- a/packages/eve/src/protocol/message-version.ts
+++ b/packages/eve/src/protocol/message-version.ts
@@ -52,10 +52,12 @@ interface MessageStreamAppendEventsByVersion {
| MessageAppendedStreamEventV24
| ReasoningAppendedStreamEventV24;
"25": ActionInputAppendedStreamEvent | MessageAppendedStreamEvent | ReasoningAppendedStreamEvent;
+ "26": ActionInputAppendedStreamEvent | MessageAppendedStreamEvent | ReasoningAppendedStreamEvent;
}
export type MessageStreamVersion = keyof MessageStreamAppendEventsByVersion;
-type LegacyMessageStreamVersion = Exclude<MessageStreamVersion, "25">;
+type DeltaMessageStreamVersion = "25" | "26";
+type LegacyMessageStreamVersion = Exclude<MessageStreamVersion, DeltaMessageStreamVersion>;
type VersionIndependentMessageStreamEvent = Exclude<
UnstampedMessageStreamEvent,
@@ -94,7 +96,11 @@ export function normalizeMessageStreamEvent(
event as MessageStreamEventForVersion<LegacyMessageStreamVersion>,
);
case "25":
- return validateCurrentMessageStreamEvent(event as MessageStreamEventForVersion<"25">);
+ case "26":
+ return validateDeltaMessageStreamEvent(
+ version,
+ event as MessageStreamEventForVersion<DeltaMessageStreamVersion>,
+ );
default:
return assertNever(version);
}
@@ -184,30 +190,32 @@ function normalizeLegacyMessageStreamEvent(
return event;
}
-function validateCurrentMessageStreamEvent(
- event: MessageStreamEventForVersion<"25">,
+function validateDeltaMessageStreamEvent(
+ version: DeltaMessageStreamVersion,
+ event: MessageStreamEventForVersion<DeltaMessageStreamVersion>,
): MessageStreamEvent {
if (event.type === "message.appended") {
- assertCurrentAppendDelta(event.data.messageDelta, "message");
- assertUnsupportedAppendField(event.data, "messageOffset", "message");
- assertUnsupportedAppendField(event.data, "messageSoFar", "message");
+ assertAppendDelta(event.data.messageDelta, "message", version);
+ assertUnsupportedAppendField(event.data, "messageOffset", "message", version);
+ assertUnsupportedAppendField(event.data, "messageSoFar", "message", version);
} else if (event.type === "reasoning.appended") {
- assertCurrentAppendDelta(event.data.reasoningDelta, "reasoning");
- assertUnsupportedAppendField(event.data, "reasoningOffset", "reasoning");
- assertUnsupportedAppendField(event.data, "reasoningSoFar", "reasoning");
+ assertAppendDelta(event.data.reasoningDelta, "reasoning", version);
+ assertUnsupportedAppendField(event.data, "reasoningOffset", "reasoning", version);
+ assertUnsupportedAppendField(event.data, "reasoningSoFar", "reasoning", version);
} else if (event.type === "action.input.appended") {
- assertCurrentAppendDelta(event.data.inputTextDelta, "action input");
- assertUnsupportedAppendField(event.data, "inputTextOffset", "action input");
+ assertAppendDelta(event.data.inputTextDelta, "action input", version);
+ assertUnsupportedAppendField(event.data, "inputTextOffset", "action input", version);
}
return event;
}
-function assertCurrentAppendDelta(
+function assertAppendDelta(
delta: unknown,
stream: "action input" | "message" | "reasoning",
+ version: DeltaMessageStreamVersion,
): void {
if (typeof delta !== "string") {
- throw new TypeError(`Invalid ${stream} append delta for stream version 25.`);
+ throw new TypeError(`Invalid ${stream} append delta for stream version ${version}.`);
}
}
@@ -215,9 +223,10 @@ function assertUnsupportedAppendField(
data: object,
field: string,
stream: "action input" | "message" | "reasoning",
+ version: DeltaMessageStreamVersion,
): void {
if (field in data) {
- throw new TypeError(`Invalid ${stream} append shape for stream version 25.`);
+ throw new TypeError(`Invalid ${stream} append shape for stream version ${version}.`);
}
}
diff --git a/packages/eve/src/protocol/message.test.ts b/packages/eve/src/protocol/message.test.ts
index 4daeb22f6..cc25d599f 100644
--- a/packages/eve/src/protocol/message.test.ts
+++ b/packages/eve/src/protocol/message.test.ts
@@ -32,7 +32,7 @@ import { createEveConnectionCallbackRoutePath } from "#protocol/routes.js";
describe("message stream protocol", () => {
it("pins the stream version for timed session events", () => {
- expect(EVE_MESSAGE_STREAM_VERSION).toBe("25");
+ expect(EVE_MESSAGE_STREAM_VERSION).toBe("26");
});
it.each(["21", "22", "23", "24"] as const)(
diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.ts
index aa35fa8a5..5d5e6b767 100644
--- a/packages/eve/src/protocol/message.ts
+++ b/packages/eve/src/protocol/message.ts
@@ -27,7 +27,7 @@ export const EVE_STREAM_TAIL_INDEX_HEADER = "x-eve-stream-tail-index";
export const EVE_STREAM_VERSION_HEADER = "x-eve-stream-version";
export const EVE_MESSAGE_STREAM_CONTENT_TYPE = "application/x-ndjson; charset=utf-8";
export const EVE_MESSAGE_STREAM_FORMAT = "ndjson";
-export const EVE_MESSAGE_STREAM_VERSION = "25";
+export const EVE_MESSAGE_STREAM_VERSION = "26";
/** Version of transport control records understood by this eve release. */
export const EVE_STREAM_CONTROL_VERSION = "1";
@@ -202,8 +202,6 @@ export interface TurnStartedStreamEvent {
*/
export interface MessageReceivedStreamEvent {
data: {
- /** Present when eve, rather than a channel participant, authored the input. */
- kind?: "execution.background_task";
message: string;
parts?: readonly MessageReceivedPart[];
sequence: number;
@@ -297,7 +295,13 @@ export interface InputRequestedStreamEvent {
}
/** Authoritative terminal outcome for one human-input request. */
-export type InputResolutionOutcome = "answered" | "approved" | "denied" | "ignored" | "invalid";
+export type InputResolutionOutcome =
+ | "answered"
+ | "approved"
+ | "cancelled"
+ | "denied"
+ | "ignored"
+ | "invalid";
/** One server-accepted resolution from a pending human-input batch. */
export interface InputResolution {
@@ -386,6 +390,34 @@ export interface SubagentCalledStreamEvent {
type: "subagent.called";
}
+/**
+ * Stream event emitted when a workflow run opens a session with `ctx.agent`.
+ * `callId` and `turnId` name the tool call whose run opened it; follow the
+ * session with `session.streamSubagent(event)`.
+ */
+export interface AgentStartedStreamEvent {
+ data: {
+ callId: string;
+ /** The turn of the call whose run opened the session. */
+ turnId: string;
+ name: string;
+ /** The opened session's id. */
+ sessionId: string;
+ /** A local session's stream route, or the parent-origin proxy for a remote one. */
+ streamPath: string;
+ /**
+ * Where a remote session runs, read by the parent's stream proxy. As on
+ * `subagent.called`, `resolverId` keys the authored credential functions,
+ * never resolved header values.
+ */
+ remote?: {
+ resolverId?: string;
+ url: string;
+ };
+ };
+ type: "agent.started";
+}
+
/**
* Stream event emitted when an inline subagent execution starts.
*/
@@ -416,15 +448,6 @@ export interface SubagentChildEventStreamEvent {
*/
export interface SubagentCompletedStreamEvent {
data: {
- /**
- * Historical admission marker retained for reading existing streams.
- * A marked event is a working receipt, not a completed invocation.
- * New receipts are published only as action.result tool outputs.
- */
- backgroundTask?: {
- taskId: string;
- status: "working";
- };
callId: string;
output: string;
subagentName: string;
@@ -487,7 +510,7 @@ export interface ReasoningAppendedStreamEvent {
export interface MessageCompletedStreamEvent {
data: {
finishReason: AssistantStepFinishReason;
- message: string | null;
+ message: string;
sequence: number;
stepIndex: number;
turnId: string;
@@ -583,6 +606,20 @@ export interface TurnCompletedStreamEvent {
type: "turn.completed";
}
+/**
+ * Stream event emitted each time an open turn parks, such as when a call it is
+ * running asks a question. The turn stays open: the next `step.started` with
+ * the same `turnId` means it resumed, and only `turn.completed`,
+ * `turn.failed`, or `turn.cancelled` end it.
+ */
+export interface TurnWaitingStreamEvent {
+ data: {
+ sequence: number;
+ turnId: string;
+ };
+ type: "turn.waiting";
+}
+
/**
* Stream event emitted when one turn fails.
*/
@@ -756,6 +793,7 @@ export interface SessionCompletedStreamEvent {
*/
export type UnstampedMessageStreamEvent =
| ActionInputAppendedStreamEvent
+ | AgentStartedStreamEvent
| ApprovalCandidateStreamEvent
| ApprovalSettledStreamEvent
| ContextClearedStreamEvent
@@ -788,7 +826,8 @@ export type UnstampedMessageStreamEvent =
| TurnCancelledStreamEvent
| TurnCompletedStreamEvent
| TurnFailedStreamEvent
- | TurnStartedStreamEvent;
+ | TurnStartedStreamEvent
+ | TurnWaitingStreamEvent;
/**
* Stream events that represent an unrecovered turn/session failure.
@@ -901,15 +940,12 @@ export function createTurnStartedEvent(input: {
* consumers while preserving the authored turn content upstream.
*/
export function createMessageReceivedEvent(input: {
- /** Present when eve, rather than a channel participant, authored the input. */
- readonly kind?: "execution.background_task";
readonly message: string | UserContent;
readonly sequence: number;
readonly turnId: string;
}): MessageReceivedStreamEvent {
return {
data: {
- kind: input.kind,
message: summarizeUserContent(input.message),
parts: projectUserContentParts(input.message),
sequence: input.sequence,
@@ -1389,6 +1425,38 @@ export function createSubagentCalledEvent(input: {
};
}
+/**
+ * Creates the `agent.started` event for one session a workflow run opened.
+ */
+export function createAgentStartedEvent(input: {
+ readonly callId: string;
+ readonly name: string;
+ readonly parentSessionId: string;
+ readonly remote?: {
+ readonly resolverId?: string;
+ readonly url: string;
+ };
+ readonly sessionId: string;
+ readonly turnId: string;
+}): AgentStartedStreamEvent {
+ const data: AgentStartedStreamEvent["data"] = {
+ callId: input.callId,
+ turnId: input.turnId,
+ name: input.name,
+ sessionId: input.sessionId,
+ streamPath: createEveSessionStreamRoutePath(input.sessionId),
+ };
+ if (input.remote !== undefined) {
+ data.remote = input.remote;
+ data.streamPath = createEveSubagentStreamRoutePath({
+ callId: input.callId,
+ childSessionId: input.sessionId,
+ parentSessionId: input.parentSessionId,
+ });
+ }
+ return { data, type: "agent.started" };
+}
+
/**
* Creates the `message.appended` event for one streamed assistant text delta.
*/
@@ -1434,7 +1502,7 @@ export function createReasoningAppendedEvent(input: {
*/
export function createMessageCompletedEvent(input: {
readonly finishReason?: AssistantStepFinishReason;
- readonly message: string | null;
+ readonly message: string;
readonly sequence: number;
readonly stepIndex: number;
readonly turnId: string;
@@ -1588,6 +1656,22 @@ export function createTurnCompletedEvent(input: {
};
}
+/**
+ * Creates the `turn.waiting` event for one open turn that parked.
+ */
+export function createTurnWaitingEvent(input: {
+ readonly sequence: number;
+ readonly turnId: string;
+}): TurnWaitingStreamEvent {
+ return {
+ data: {
+ sequence: input.sequence,
+ turnId: input.turnId,
+ },
+ type: "turn.waiting",
+ };
+}
+
/**
* Creates the `turn.failed` event for one failed turn.
*/
diff --git a/packages/eve/src/protocol/remote-agent-protocol.ts b/packages/eve/src/protocol/remote-agent-protocol.ts
new file mode 100644
index 000000000..2640c1de1
--- /dev/null
+++ b/packages/eve/src/protocol/remote-agent-protocol.ts
@@ -0,0 +1,25 @@
+/**
+ * Version of the protocol a parent deployment speaks with a remote agent's
+ * deployment. A create-session request that delegates work names the caller's
+ * version, and the receiver's response names its own; both deployments must
+ * speak the same one. Deployments from before the version existed speak 1.
+ */
+export const REMOTE_AGENT_PROTOCOL_VERSION = 2;
+
+/** Error code a receiver answers when the caller speaks another protocol version. */
+export const REMOTE_AGENT_PROTOCOL_MISMATCH = "REMOTE_AGENT_PROTOCOL_MISMATCH";
+
+const UNVERSIONED_REMOTE_AGENT_PROTOCOL = 1;
+
+/** Reads a peer's protocol version, treating an absent one as the unversioned protocol. */
+export function readRemoteAgentProtocolVersion(value: unknown): number {
+ return typeof value === "number" ? value : UNVERSIONED_REMOTE_AGENT_PROTOCOL;
+}
+
+/** The caller's message when a remote agent's deployment speaks another version. */
+export function formatRemoteAgentProtocolMismatch(input: {
+ readonly name: string;
+ readonly receiverVersion: number;
+}): string {
+ return `Remote agent "${input.name}" speaks eve remote agent protocol ${String(input.receiverVersion)}, but this deployment speaks protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}. Upgrade both deployments to the same eve release.`;
+}
diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.ts
index c2afd35ea..c41b9a402 100644
--- a/packages/eve/src/protocol/routes.ts
+++ b/packages/eve/src/protocol/routes.ts
@@ -115,9 +115,6 @@ export const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connec
*/
export const EVE_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/callback/:token`;
-/** Capability route used by a parent task to answer a remote child HITL batch. */
-export const EVE_TASK_INPUT_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/task-input/:token`;
-
/** Capability route for best-effort activity batches. */
export const EVE_ACTIVITY_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/activity/:token`;
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
index 3635f34eb..2a0ac75ec 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
@@ -238,7 +238,6 @@ describe("chatSdkChannel", () => {
auth: AUTH,
thread,
title: "mention",
- taskDeliveryPolicy: "cohort",
});
});
@@ -262,7 +261,6 @@ describe("chatSdkChannel", () => {
},
},
title: "mention",
- taskDeliveryPolicy: "cohort",
});
});
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
index aa9414e2a..fbb3d1ca8 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
@@ -8,7 +8,7 @@ import {
} from "#channel/channel-operations.js";
import { normalizeSendInput } from "#channel/send-input.js";
import type { SendPayload } from "#channel/routes.js";
-import type { SessionAuthContext, TurnPolicy, TaskDeliveryPolicy } from "#channel/types.js";
+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";
@@ -140,8 +140,6 @@ export type ChatSdkChannelEvents<TAdapters extends ChatSdkAdapters = ChatSdkAdap
export interface ChatSdkSendOptions {
readonly auth?: SessionAuthContext | null;
readonly callback?: ChannelAddressDeliveryOptions<ChatSdkChannelState>["callback"];
- /** Updates the session policy; omission preserves it. */
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
readonly thread: SerializedThread | Thread | string;
readonly title?: string;
/**
@@ -579,8 +577,6 @@ async function bridgeSend<TAdapters extends ChatSdkAdapters>(
if (options.callback !== undefined) deliveryOptions.callback = options.callback;
if (options.title !== undefined) deliveryOptions.title = options.title;
if (options.turnPolicy !== undefined) deliveryOptions.turnPolicy = options.turnPolicy;
- if (options.taskDeliveryPolicy !== undefined)
- deliveryOptions.taskDeliveryPolicy = options.taskDeliveryPolicy;
const source = active.from(thread.id) as InternalChannelSource<ChatSdkChannelState>;
return source[INTERNAL_CHANNEL_DELIVER](payload, deliveryOptions);
}
diff --git a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
index f81653276..1344c6e12 100644
--- a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
+++ b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from "vitest";
+import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";
/**
* Integration coverage for forwarded principal across the create route and the
@@ -133,6 +134,7 @@ describe("eveChannel forwarded principal → runtime principal", () => {
url: "https://caller.example.com/eve/v1/callback/parent-token",
},
message: "check my dashboards",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
headers: {
"content-type": "application/json",
@@ -251,6 +253,7 @@ describe("eveChannel forwarded principal → runtime principal", () => {
url: "https://caller.example.com/eve/v1/callback/parent-token",
},
message: "check my dashboards",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
headers: {
"content-type": "application/json",
@@ -305,6 +308,7 @@ describe("eveChannel forwarded principal → runtime principal", () => {
url: "https://caller.example.com/eve/v1/callback/parent-token",
},
message: "check my dashboards",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
headers: {
"content-type": "application/json",
@@ -343,6 +347,7 @@ describe("eveChannel forwarded principal → runtime principal", () => {
url: "https://caller.example.com/eve/v1/callback/parent-token",
},
message: "check my dashboards",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
headers: {
"content-type": "application/json",
diff --git a/packages/eve/src/public/channels/eve-session-routes.test.ts b/packages/eve/src/public/channels/eve-session-routes.test.ts
index 9d6541f49..5af037a0b 100644
--- a/packages/eve/src/public/channels/eve-session-routes.test.ts
+++ b/packages/eve/src/public/channels/eve-session-routes.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from "vitest";
+import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";
import type { RouteHandlerArgs } from "#channel/routes.js";
import type { Session } from "#channel/session.js";
@@ -173,6 +174,7 @@ describe("eve ID-addressed session routes", () => {
url: "https://caller.example.com/eve/v1/callback/tok123",
},
message: "hello",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
headers: {
"content-type": "application/json",
@@ -213,6 +215,7 @@ describe("eve ID-addressed session routes", () => {
url: "https://caller.example.com/eve/v1/callback/tok123",
},
message: "hello",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
headers: {
"content-type": "application/json",
@@ -254,6 +257,7 @@ describe("eve ID-addressed session routes", () => {
url: "https://caller.example.com/eve/v1/callback/tok123",
},
message: "hello",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
headers: {
"content-type": "application/json",
@@ -303,6 +307,7 @@ describe("eve ID-addressed session routes", () => {
}
: undefined,
message: "hello",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
headers: {
"content-type": "application/json",
@@ -316,7 +321,7 @@ describe("eve ID-addressed session routes", () => {
);
expect(response.status).toBe(202);
- await expect(response.json()).resolves.toEqual({
+ await expect(response.json()).resolves.toMatchObject({
ok: true,
sessionId: "wrun_A",
status: "accepted",
@@ -368,6 +373,7 @@ describe("eve ID-addressed session routes", () => {
url: "https://caller.example.com/eve/v1/callback/tok123",
},
message: "hello",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
headers: {
"content-type": "application/json",
@@ -485,21 +491,17 @@ describe("eve ID-addressed session routes", () => {
expect(session[operation]).toHaveBeenCalledTimes(1);
});
- it("forwards owned-task cancellation without changing the response", async () => {
+ it("forwards the turn guard without changing the response", async () => {
const session = createFixedSession();
const response = await route("POST", "/eve/v1/session/:sessionId/cancel")(
new Request("https://eve.test/eve/v1/session/wrun_A/cancel", {
- body: JSON.stringify({ tasks: true, turnId: "turn_1" }),
+ body: JSON.stringify({ turnId: "turn_1" }),
method: "POST",
}),
createArgs(session),
);
- expect(session.cancel).toHaveBeenCalledWith({
- taskId: undefined,
- tasks: true,
- turnId: "turn_1",
- });
+ expect(session.cancel).toHaveBeenCalledWith({ turnId: "turn_1" });
expect(response.status).toBe(202);
await expect(response.json()).resolves.toEqual({
ok: true,
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index d957a2ab6..5fcc1cfda 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -1,4 +1,5 @@
import type { FilePart, UserContent } from "ai";
+import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";
import { describe, expect, it, vi } from "vitest";
import { buildAdapterContext } from "#channel/adapter-context.js";
@@ -872,7 +873,6 @@ describe("eveChannel — onMessage", () => {
callback: {
callId: "call-2",
subagentName: "research",
- taskId: "task-2",
token: "tok123",
url: "https://caller.example.com/eve/v1/callback/tok123",
},
@@ -887,7 +887,6 @@ describe("eveChannel — onMessage", () => {
callback: {
callId: "call-2",
subagentName: "research",
- taskId: "task-2",
token: "tok123",
url: "https://caller.example.com/eve/v1/callback/tok123",
},
@@ -1097,6 +1096,7 @@ describe("eveChannel — create session (text)", () => {
url: "https://caller.example.com/eve/v1/callback/tok123",
},
message: "hi",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
);
@@ -1124,6 +1124,7 @@ describe("eveChannel — create session (text)", () => {
url: "https://caller.example.com/eve/support/v1/callback/tok123",
},
message: "hi",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
}),
);
diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.ts
index 8114c7e1b..4ec1a58be 100644
--- a/packages/eve/src/public/channels/index.ts
+++ b/packages/eve/src/public/channels/index.ts
@@ -40,7 +40,6 @@ export {
type SessionRespondOptions,
type SessionSendOptions,
type TurnPolicy,
- type TaskDeliveryPolicy,
type RouteDefinition,
type RouteHandlerArgs,
type HttpRouteDefinition,
diff --git a/packages/eve/src/public/channels/slack/activity-plan.test.ts b/packages/eve/src/public/channels/slack/activity-plan.test.ts
index f60d85c8d..17a4106f5 100644
--- a/packages/eve/src/public/channels/slack/activity-plan.test.ts
+++ b/packages/eve/src/public/channels/slack/activity-plan.test.ts
@@ -21,7 +21,7 @@ const verifier = {
};
const stage = {
id: "stage",
- kind: "task" as const,
+ kind: "subagent" as const,
name: "verify_stage",
parentId: verifier.id,
rootSessionId: "session",
@@ -37,7 +37,7 @@ const reviewer = {
};
const reviewStage = {
id: "review-stage",
- kind: "task" as const,
+ kind: "subagent" as const,
name: "review_stage",
parentId: reviewer.id,
rootSessionId: "session",
diff --git a/packages/eve/src/public/channels/slack/activity-progress.test.ts b/packages/eve/src/public/channels/slack/activity-progress.test.ts
index c63495ed7..b5f57d6ab 100644
--- a/packages/eve/src/public/channels/slack/activity-progress.test.ts
+++ b/packages/eve/src/public/channels/slack/activity-progress.test.ts
@@ -137,10 +137,10 @@ describe("Slack activity activity", () => {
);
});
- it("renders inherited child tool activity beneath an existing task row", () => {
+ it("renders inherited child tool activity beneath an existing subagent row", () => {
const task = {
id: "work:task",
- kind: "task" as const,
+ kind: "subagent" as const,
name: "slack",
parentId: root.id,
rootSessionId: "root",
@@ -172,22 +172,22 @@ describe("Slack activity activity", () => {
);
});
- it("renders a background task instead of its duplicate initiating tool action", () => {
- const task = {
- callId: "call-background",
- id: "work:background",
+ it("renders a delegated child instead of its duplicate initiating tool action", () => {
+ const child = {
+ callId: "call-researcher",
+ id: "work:researcher",
kind: "subagent" as const,
name: "researcher",
parentId: root.id,
rootSessionId: "root",
rootTurnId: "turn",
};
- const background = reduceActivityBatch(createActivitySnapshot(), {
+ const delegated = reduceActivityBatch(createActivitySnapshot(), {
events: [
{ eventId: "root", kind: "work.started", startedAt: "1", work: root },
{
action: {
- id: `action:${root.id}:call-background`,
+ id: `action:${root.id}:call-researcher`,
kind: "tool",
name: "researcher",
parentWorkId: root.id,
@@ -198,12 +198,12 @@ describe("Slack activity activity", () => {
kind: "action.started",
startedAt: "2",
},
- { eventId: "task", kind: "work.started", startedAt: "3", work: task },
+ { eventId: "child", kind: "work.started", startedAt: "3", work: child },
],
version: 1,
});
- expect(activityMessages(background).get("turn")).toBe("```\n• Working\n└── • researcher\n```");
+ expect(activityMessages(delegated).get("turn")).toBe("```\n• Working\n└── • researcher\n```");
});
it("keeps temporarily orphaned nested work renderable", () => {
diff --git a/packages/eve/src/public/channels/slack/activity.ts b/packages/eve/src/public/channels/slack/activity.ts
index e6bf7971c..2a671cdaa 100644
--- a/packages/eve/src/public/channels/slack/activity.ts
+++ b/packages/eve/src/public/channels/slack/activity.ts
@@ -458,7 +458,7 @@ function renderWorkTree(
children.push(item);
byParent.set(parentId, children);
}
- const backgroundActionIds = new Set(
+ const delegatedActionIds = new Set(
work.flatMap((item) =>
item.parentId !== undefined && item.callId !== undefined
? [`action:${item.parentId}:${item.callId}`]
@@ -467,7 +467,7 @@ function renderWorkTree(
);
const actionsByParent = new Map<string, ActivityActionStateV1[]>();
for (const action of actions) {
- if (action.kind === "tool" && backgroundActionIds.has(action.id)) continue;
+ if (action.kind === "tool" && delegatedActionIds.has(action.id)) continue;
const siblings = actionsByParent.get(action.parentWorkId) ?? [];
siblings.push(action);
actionsByParent.set(action.parentWorkId, siblings);
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index ca3038a2a..9f65b94c0 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -2805,7 +2805,7 @@ describe("slackChannel() generic Events API pipeline", () => {
expect(compact).toHaveBeenCalledWith("C01:1700000000.000001");
});
- it("binds Slack state, title, and task policy on a generic event send", async () => {
+ it("binds Slack state and title on a generic event send", async () => {
const send = vi.fn().mockResolvedValue({ id: "s1" });
const channel = slackChannel({
credentials: { botToken: "xoxb-test" },
@@ -2814,7 +2814,6 @@ describe("slackChannel() generic Events API pipeline", () => {
auth: null,
target: { channelId: "C01", threadTs: "1700000000.000001" },
title: "Reaction follow-up",
- taskDeliveryPolicy: "cohort",
});
},
});
@@ -2833,7 +2832,6 @@ describe("slackChannel() generic Events API pipeline", () => {
triggeringUserId: "U01",
},
title: "Reaction follow-up",
- taskDeliveryPolicy: "cohort",
});
});
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index 79603764f..79c7f80a5 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -9,7 +9,7 @@ import type {
import { defaultDeliverResult } from "#channel/adapter.js";
import type { Session, SessionHandle } from "#channel/session.js";
import { setChannelActivityRenderers, setChannelBuildMetadata } from "#channel/compiled-channel.js";
-import type { SessionAuthContext, TaskDeliveryPolicy, TurnPolicy } from "#channel/types.js";
+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
import type { VercelConnectMetadata } from "#shared/vercel-connect-metadata.js";
import type { CardElement } from "#compiled/chat/index.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
@@ -344,8 +344,6 @@ export interface SlackInitialMessage {
* Options for one turn requested by a generic Slack event handler.
*/
export interface SlackEventSendOptions {
- /** Updates the session policy; omission preserves it. */
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
readonly auth: SessionAuthContext | null;
readonly target: SlackReceiveTarget;
/** Overrides the workflow run title without changing the message sent to the model. */
@@ -1088,7 +1086,6 @@ async function receiveOnSlack(
readonly message: string | UserContent;
readonly target: SlackReceiveTarget;
readonly title?: string;
- readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
},
deps: {
readonly from: ChannelFrom<SlackChannelState>;
@@ -1169,7 +1166,6 @@ async function receiveOnSlack(
auth: input.auth,
state,
title: input.title,
- taskDeliveryPolicy: input.taskDeliveryPolicy,
});
}
@@ -1503,9 +1499,9 @@ async function dispatchSlackEvent(input: {
input.resolveSession(slackContinuationToken(target.channelId, target.threadTs)),
respond: (inputResponses, { auth, target }) =>
sourceFor(target).respond(inputResponses, { auth }),
- send: (message, { auth, target, title, taskDeliveryPolicy }) =>
+ send: (message, { auth, target, title }) =>
receiveOnSlack(
- { auth, message, target, title, taskDeliveryPolicy },
+ { auth, message, target, title },
{
from: input.from,
api: input.api,
diff --git a/packages/eve/src/public/channels/task-delivery-policy.test.ts b/packages/eve/src/public/channels/task-delivery-policy.test.ts
deleted file mode 100644
index 29520f481..000000000
--- a/packages/eve/src/public/channels/task-delivery-policy.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { expectTypeOf, it } from "vitest";
-
-import type {
- ChannelSendOptions,
- SessionSendOptions,
- defineChannel,
-} from "#public/channels/index.js";
-import type { chatSdkChannel, ChatSdkSendOptions } from "#public/channels/chat-sdk/index.js";
-import type { discordChannel } from "#public/channels/discord/index.js";
-import type { eveChannel } from "#public/channels/eve.js";
-import type { githubChannel } from "#public/channels/github/index.js";
-import type { linearChannel } from "#public/channels/linear/index.js";
-import type { linqChannel } from "#public/channels/linq/index.js";
-import type { mcpChannel } from "#public/channels/mcp.js";
-import type { photonIMessageChannel } from "#public/channels/photon/index.js";
-import type {
- slackChannel,
- SlackSendOptions,
- SlackEventSendOptions,
-} from "#public/channels/slack/index.js";
-import type { teamsChannel } from "#public/channels/teams/index.js";
-import type { telegramChannel } from "#public/channels/telegram/index.js";
-import type { twilioChannel } from "#public/channels/twilio/index.js";
-import type { ScheduleDefinition } from "#public/schedules/index.js";
-
-it("exposes task delivery policy on sends, not channel or schedule definitions", () => {
- expectTypeOf<ChannelSendOptions>()
- .toHaveProperty("taskDeliveryPolicy")
- .toEqualTypeOf<"auto" | "cohort" | undefined>();
- expectTypeOf<SessionSendOptions>()
- .toHaveProperty("taskDeliveryPolicy")
- .toEqualTypeOf<"auto" | "cohort" | undefined>();
- expectTypeOf<ChatSdkSendOptions>()
- .toHaveProperty("taskDeliveryPolicy")
- .toEqualTypeOf<"auto" | "cohort" | undefined>();
- expectTypeOf<SlackSendOptions>()
- .toHaveProperty("taskDeliveryPolicy")
- .toEqualTypeOf<"auto" | "cohort" | undefined>();
- expectTypeOf<SlackEventSendOptions>()
- .toHaveProperty("taskDeliveryPolicy")
- .toEqualTypeOf<"auto" | "cohort" | undefined>();
- expectTypeOf<Parameters<typeof defineChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof chatSdkChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof discordChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof eveChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof githubChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof linearChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof linqChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof mcpChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof photonIMessageChannel>[0]>().not.toHaveProperty(
- "taskDeliveryPolicy",
- );
- expectTypeOf<Parameters<typeof slackChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof teamsChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof telegramChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<Parameters<typeof twilioChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");
- expectTypeOf<ScheduleDefinition>().not.toHaveProperty("taskDeliveryPolicy");
-});
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index 6e4e73702..ad424b788 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -37,7 +37,6 @@ export type {
ResetSessionResult,
SessionCallback,
TurnPolicy,
- TaskDeliveryPolicy,
} from "#channel/types.js";
export type { Session, SessionHandle } from "#channel/session.js";
export type { ChannelAudience } from "#shared/channel-audience.js";
diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.ts
index d920cd77f..7577b5400 100644
--- a/packages/eve/src/public/definitions/exact.test.ts
+++ b/packages/eve/src/public/definitions/exact.test.ts
@@ -23,8 +23,7 @@ import { defineSandbox } from "#public/definitions/sandbox.js";
import { DockerSandbox, VercelSandbox } from "#sandbox/providers.js";
import { defineSchedule } from "#public/definitions/schedule.js";
import { defineSkill } from "#public/definitions/skill.js";
-import { defineTool, type TaskReceipt, type ToolDefinition } from "#public/tools/index.js";
-import { defineWorkflowTool } from "#public/tools/index.js";
+import { defineTool, type ToolDefinition } from "#public/tools/index.js";
describe("definition helper exact inputs", () => {
it("preserves literal inference for valid definitions", () => {
@@ -105,34 +104,6 @@ describe("definition helper exact inputs", () => {
>();
});
- it("types background workflow tools in terms of their receipt", () => {
- const backgroundTool = defineWorkflowTool({
- description: "Start a durable export.",
- execution: "background",
- inputSchema: z.object({ jobId: z.string() }),
- async *execute(input) {
- yield { jobId: input.jobId };
- return { jobId: input.jobId };
- },
- });
-
- expectTypeOf(backgroundTool.execution).toEqualTypeOf<"background">();
- expectTypeOf<
- Parameters<NonNullable<typeof backgroundTool.toModelOutput>>[0]
- >().toEqualTypeOf<TaskReceipt>();
- expect(backgroundTool.execution).toBe("background");
- });
-
- it("rejects background execution on ordinary tools", () => {
- const definition = {
- description: "Start a durable export.",
- execution: "background",
- inputSchema: z.object({ jobId: z.string() }),
- execute: async () => null,
- };
- expect(() => defineTool(definition)).toThrow("Use defineWorkflowTool for background work");
- });
-
it("infers tool input from Zod 3 schemas", () => {
const tool = defineTool({
description: "Fetch current weather for a city.",
diff --git a/packages/eve/src/public/definitions/hook.ts b/packages/eve/src/public/definitions/hook.ts
index f9e4ca1c5..1c3f6fb49 100644
--- a/packages/eve/src/public/definitions/hook.ts
+++ b/packages/eve/src/public/definitions/hook.ts
@@ -21,6 +21,7 @@ export interface HookEventMap {
readonly "approval.candidate": ProtocolEvent<"approval.candidate">;
readonly "approval.settled": ProtocolEvent<"approval.settled">;
readonly "actions.requested": ProtocolEvent<"actions.requested">;
+ readonly "agent.started": ProtocolEvent<"agent.started">;
readonly "authorization.completed": ProtocolEvent<"authorization.completed">;
readonly "authorization.required": ProtocolEvent<"authorization.required">;
readonly "compaction.completed": ProtocolEvent<"compaction.completed">;
@@ -49,6 +50,7 @@ export interface HookEventMap {
readonly "turn.completed": ProtocolEvent<"turn.completed">;
readonly "turn.failed": ProtocolEvent<"turn.failed">;
readonly "turn.started": ProtocolEvent<"turn.started">;
+ readonly "turn.waiting": ProtocolEvent<"turn.waiting">;
}
/** Event type discriminators available to authored hooks. */
diff --git a/packages/eve/src/public/memory/index.ts b/packages/eve/src/public/memory/index.ts
index c07acc622..a93e48bea 100644
--- a/packages/eve/src/public/memory/index.ts
+++ b/packages/eve/src/public/memory/index.ts
@@ -121,7 +121,6 @@ export interface MemoryToolsContext extends DynamicResolveContext {
export interface MemoryToolDefinition {
readonly approval?: Approval<never>;
readonly description: string;
- readonly execution?: never;
execute(input: never, context: ToolContext): unknown | Promise<unknown> | AsyncIterable<unknown>;
readonly inputSchema: unknown;
readonly outputSchema?: unknown;
diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.ts
index 22686ab2d..2f54d5ac5 100644
--- a/packages/eve/src/public/tools/index.ts
+++ b/packages/eve/src/public/tools/index.ts
@@ -37,10 +37,16 @@ export {
export {
defineWorkflowTool,
type WorkflowStepToolContext,
- type TaskReceipt,
type WorkflowToolContext,
type WorkflowToolDefinition,
- type AgentInput,
+ type AgentMessageResult,
+ type AgentResponse,
+ type AgentSendOptions,
+ type AgentSession,
type WorkflowAgentMetadata,
} from "#tools/workflow-definition.js";
-export type { ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
+export type {
+ ToolInputRequest,
+ ToolInputRequestOptions,
+ ToolInputResponse,
+} from "#tools/definition.js";
diff --git a/packages/eve/src/public/tools/task-cancel.ts b/packages/eve/src/public/tools/task-cancel.ts
deleted file mode 100644
index fd8c8bba3..000000000
--- a/packages/eve/src/public/tools/task-cancel.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { taskCancel, taskCancel as default } from "#tools/framework/task-cancel.js";
diff --git a/packages/eve/src/runtime/agent/bootstrap.test.ts b/packages/eve/src/runtime/agent/bootstrap.test.ts
index 37acc485a..f56baf855 100644
--- a/packages/eve/src/runtime/agent/bootstrap.test.ts
+++ b/packages/eve/src/runtime/agent/bootstrap.test.ts
@@ -22,7 +22,6 @@ function createFrameworkAgentTool(): PreparedRuntimeTool {
},
},
description: "Message a persistent agent.",
- execution: "background",
inputSchema: null,
kind: "authored-tool",
logicalPath: `tools/${AGENT_TOOL_NAME}.ts`,
@@ -90,28 +89,17 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
);
});
- it("includes background messaging instructions for the root framework agent tool", () => {
+ it("includes 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("task receipt"));
+ expect(turnAgent.instructions).toContainEqual(expect.stringContaining("Agent messaging"));
expect(turnAgent.instructions).toContainEqual(expect.stringContaining("Tool execution"));
});
- it("explains task-derived busy agents in task mode", () => {
- const turnAgent = createResolvedRuntimeTurnAgent({
- agent: createResolvedAgentForTest(),
- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
- tools: [createFrameworkAgentTool()],
- });
-
- expect(turnAgent.instructions).toContainEqual(expect.stringContaining("availability=busy"));
- expect(turnAgent.instructions).toContainEqual(expect.stringContaining("taskId"));
- });
-
it("omits the messaging instruction when an authored tool named agent shadows the framework tool", () => {
const turnAgent = createResolvedRuntimeTurnAgent({
agent: createResolvedAgentForTest({
@@ -131,7 +119,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
],
});
- expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Agent messaging"));
});
it("omits the messaging instruction when no agent tool was compiled", () => {
@@ -143,7 +131,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
tools: [],
});
- expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Agent messaging"));
});
it("omits the messaging instruction for a non-root node without declared subagents", () => {
@@ -155,6 +143,6 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
tools: [],
});
- expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Agent messaging"));
});
});
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 d06c77751..74f95edcc 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
@@ -73,29 +73,6 @@ describe("createMockAuthoredRuntimeModel", () => {
]);
});
- 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 4d39d39fb..8aafaad6d 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.ts
@@ -302,7 +302,7 @@ function createAuthoredToolCallResult(
): BootstrapGenerateResult | null {
const lastUserMessage = getLastUserPromptText(options.prompt);
- if (lastUserMessage === null || /^Background task task_[a-z0-9]+\b/iu.test(lastUserMessage)) {
+ if (lastUserMessage === null) {
return null;
}
diff --git a/packages/eve/src/runtime/prompt/compose.test.ts b/packages/eve/src/runtime/prompt/compose.test.ts
index fd855a19f..fc08e487f 100644
--- a/packages/eve/src/runtime/prompt/compose.test.ts
+++ b/packages/eve/src/runtime/prompt/compose.test.ts
@@ -12,36 +12,12 @@ describe("composeRuntimeBasePrompt", () => {
expect(prompt).toContainEqual(expect.stringContaining("<agents>"));
});
- it("instructs parents to rely on notifications instead of polling", () => {
- const prompt = composeRuntimeBasePrompt({
- subagentsAvailable: true,
- });
-
- expect(prompt).toContainEqual(
- expect.stringContaining("return immediately with a task receipt"),
- );
- expect(prompt).toContainEqual(
- expect.stringContaining("notifications include the task's result"),
- );
- expect(prompt).not.toContainEqual(expect.stringContaining("task_peek"));
- expect(prompt).not.toContainEqual(expect.stringContaining("task_sleep"));
- expect(prompt).toContainEqual(expect.stringContaining("notify you"));
- });
-
- it("describes steering as updating the existing task without cancellation", () => {
- const prompt = composeRuntimeBasePrompt({ subagentsAvailable: true }).join("\n");
-
- expect(prompt).toContain("steers its active turn at the next safe boundary");
- expect(prompt).toContain("preserving the same taskId, child session, and pending approvals");
- expect(prompt).not.toContain("cancels its previous task");
- });
-
it("omits agent messaging instructions when subagents are unavailable", () => {
const prompt = composeRuntimeBasePrompt({
subagentsAvailable: false,
});
- expect(prompt).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ expect(prompt).not.toContainEqual(expect.stringContaining("Agent messaging"));
expect(prompt).not.toContainEqual(expect.stringContaining("<agents>"));
});
});
diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.ts
index 2406b4d1d..6e36edeb5 100644
--- a/packages/eve/src/runtime/prompt/compose.ts
+++ b/packages/eve/src/runtime/prompt/compose.ts
@@ -12,7 +12,7 @@ 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\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. To steer delegated work, send the updated instruction to the original subagent tool with that agentId. If availability=busy, this steers its active turn at the next safe boundary, preserving the same taskId, child session, and pending approvals. Forward user steering to the affected child promptly; an acknowledgement alone does not update its work. Leave unrelated background work running. If availability=available, the same call continues the idle child. Calling a subagent without agentId starts a new agent session. Use task_cancel with its taskId to stop work without sending a replacement instruction.";
+ "Agent messaging\nA subagent call runs until the subagent replies, and its reply is the tool result. Agents you have already delegated to remain visible in the framework-authored `<agents>` conversation note. To continue an agent's conversation, call the original subagent tool again with that agentId. Calling a subagent without agentId starts a new agent session.";
/**
* Input for composing the base authored instructions prompt for one
diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.ts
index b2739cf24..a244ca2ae 100644
--- a/packages/eve/src/runtime/resolve-tool.ts
+++ b/packages/eve/src/runtime/resolve-tool.ts
@@ -88,7 +88,6 @@ export async function resolveToolDefinition(
description: definition.description,
execute,
executeInput,
- execution: definition.execution,
exportName: definition.exportName,
inputSchema,
logicalPath: definition.logicalPath,
diff --git a/packages/eve/src/runtime/sessions/turn.ts b/packages/eve/src/runtime/sessions/turn.ts
index d3668c523..9bc5b423e 100644
--- a/packages/eve/src/runtime/sessions/turn.ts
+++ b/packages/eve/src/runtime/sessions/turn.ts
@@ -32,11 +32,10 @@ export type PreparedRuntimeAuthoredTool = Readonly<
>;
type PreparedRuntimeDelegationToolBase<TKind extends "remote" | "subagent"> = Readonly<
- Omit<InternalToolDefinition, "execution"> &
+ InternalToolDefinition &
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 9a104019a..7b73edd32 100644
--- a/packages/eve/src/runtime/subagents/registry.ts
+++ b/packages/eve/src/runtime/subagents/registry.ts
@@ -5,9 +5,8 @@ import type {
ResolvedRuntimeDelegationNode,
} from "#runtime/types.js";
import type { JsonObject } from "#shared/json.js";
-import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";
+import { serializeInputSchema } 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";
/**
@@ -42,7 +41,6 @@ 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 owned by one
@@ -154,14 +152,12 @@ export function createPreparedRuntimeSubagentTool(
},
},
},
- description: `${definition.description}\n\nThis call starts a background task and returns a task receipt immediately.`,
- execution: "background",
+ description: definition.description,
inputSchema,
kind: definition.kind,
logicalPath: definition.logicalPath,
name: definition.name,
nodeId: definition.nodeId,
- outputSchema: SUBAGENT_TOOL_OUTPUT_JSON_SCHEMA,
sourceId: definition.sourceId,
task: {
nodeId: definition.nodeId,
diff --git a/packages/eve/src/runtime/subagents/workflow.ts b/packages/eve/src/runtime/subagents/workflow.ts
index f6bfc7dcc..653706741 100644
--- a/packages/eve/src/runtime/subagents/workflow.ts
+++ b/packages/eve/src/runtime/subagents/workflow.ts
@@ -1,6 +1,6 @@
-// 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.
+// Agent tools continue children by `agentId` through the owner's handle store,
+// which `ctx.agent` sessions never touch. 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;
diff --git a/packages/eve/src/runtime/task-input-response-route.test.ts b/packages/eve/src/runtime/task-input-response-route.test.ts
deleted file mode 100644
index cab228188..000000000
--- a/packages/eve/src/runtime/task-input-response-route.test.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { RouteContext } from "#public/definitions/channel.js";
-import { handleTaskInputResponseRequest } from "#execution/task-input-response-route.js";
-
-const resumeHookMock = vi.fn();
-const DIGEST = "0123456789abcdef0123456789abcdef";
-const CAPABILITY_TOKEN = `eve:task-input:${DIGEST}`;
-const TARGET_TOKEN = `eve:eve:op:${DIGEST}`;
-const TARGET_HOOK = {
- metadata: { sessionId: "child-session" },
- runId: "child-session",
- token: TARGET_TOKEN,
-};
-
-vi.mock("#compiled/@workflow/core/runtime.js", () => ({
- resumeHook: (...args: unknown[]) => resumeHookMock(...args),
-}));
-
-describe("task input response capability", () => {
- beforeEach(() => {
- resumeHookMock.mockReset();
- });
-
- it("resumes only the addressed child input batch", async () => {
- resumeHookMock.mockResolvedValue(TARGET_HOOK);
- const response = await handleTaskInputResponseRequest(
- request({ inputResponses: [{ optionId: "approve", requestId: "req-1" }] }),
- context(CAPABILITY_TOKEN),
- );
-
- expect(response.status).toBe(202);
- expect(resumeHookMock).toHaveBeenCalledWith(`eve:inbox:v1:${TARGET_TOKEN}`, {
- kind: "send",
- payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },
- });
- });
-
- it("forwards only public responder fields", async () => {
- resumeHookMock.mockResolvedValue(TARGET_HOOK);
- const response = await handleTaskInputResponseRequest(
- request({
- inputResponses: [{ requestId: "req-1", text: "approved" }],
- responder: {
- attributes: { private: "channel-only" },
- authenticator: "test",
- principalId: "bob",
- principalType: "user",
- },
- }),
- context(CAPABILITY_TOKEN),
- );
-
- expect(response.status).toBe(202);
- expect(resumeHookMock).toHaveBeenCalledWith(`eve:inbox:v1:${TARGET_TOKEN}`, {
- kind: "send",
- payload: {
- inputResponses: [{ requestId: "req-1", text: "approved" }],
- responder: {
- authenticator: "test",
- principalId: "bob",
- principalType: "user",
- },
- },
- });
- });
-
- it("rejects messages and empty response batches", async () => {
- for (const body of [{ message: "not allowed" }, { inputResponses: [] }]) {
- const response = await handleTaskInputResponseRequest(
- request(body),
- context(CAPABILITY_TOKEN),
- );
- expect(response.status).toBe(400);
- }
- expect(resumeHookMock).not.toHaveBeenCalled();
- });
-
- it("rejects incomplete responder identities", async () => {
- const response = await handleTaskInputResponseRequest(
- request({
- inputResponses: [{ requestId: "req-1", text: "approved" }],
- responder: { authenticator: "test", principalId: "bob" },
- }),
- context(CAPABILITY_TOKEN),
- );
-
- expect(response.status).toBe(400);
- expect(resumeHookMock).not.toHaveBeenCalled();
- });
-
- it("rejects generic workflow hook tokens", async () => {
- const response = await handleTaskInputResponseRequest(
- request({ inputResponses: [{ requestId: "req-1", text: "forged" }] }),
- context("eve:session:victim:inbox"),
- );
-
- expect(response.status).toBe(403);
- expect(resumeHookMock).not.toHaveBeenCalled();
- });
-});
-
-function request(body: unknown): Request {
- return new Request("https://remote.example/eve/v1/task-input/child-token", {
- body: JSON.stringify(body),
- headers: { "content-type": "application/json" },
- method: "POST",
- });
-}
-
-function context(token: string): RouteContext {
- return {
- params: { token },
- requestIp: null,
- waitUntil() {},
- };
-}
diff --git a/packages/eve/src/runtime/tools/registry.ts b/packages/eve/src/runtime/tools/registry.ts
index 78a29046f..ad1abd815 100644
--- a/packages/eve/src/runtime/tools/registry.ts
+++ b/packages/eve/src/runtime/tools/registry.ts
@@ -99,7 +99,6 @@ async function createPreparedRuntimeTool(
isSelfAgent ? subagentToolExecuteWorkflowReference.workflowId : undefined,
),
description: definition.description,
- execution: definition.execution,
inputSchema: serializeInputSchema(definition.inputSchema),
kind: "authored-tool",
logicalPath: definition.logicalPath,
@@ -135,18 +134,13 @@ function prepareToolBehavior(
target: { kind: "self-agent-call", nodeId, subagentName: AGENT_TOOL_NAME },
};
} else if (behavior.handling?.kind === "dispatch") {
- if (behavior.handling.action === "self-agent" && nodeId === undefined) {
+ if (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 };
+ handling = {
+ kind: "dispatch",
+ target: { kind: "self-agent-call", nodeId, subagentName: AGENT_TOOL_NAME },
+ };
} else if (behavior.handling?.kind === "workflow-tool") {
handling = {
kind: "dispatch",
diff --git a/packages/eve/src/shared/action-types.ts b/packages/eve/src/shared/action-types.ts
index 99bb03a35..112a24a7f 100644
--- a/packages/eve/src/shared/action-types.ts
+++ b/packages/eve/src/shared/action-types.ts
@@ -115,8 +115,7 @@ export const runtimeRemoteAgentDispatchRequestSchema = z
/**
* 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.
+ * durable run named by `workflowId` and waits for its result.
*
* Tasks are the coordination contract for authored workflow tools and
* subagents. They are intentionally separate from `RuntimeActionRequest`.
@@ -226,17 +225,8 @@ const runtimeToolResultActionResultSchema = z
* field. `usage`
* carries the turn's token spend so the caller can attribute the
* subagent's tokens.
- *
- * `backgroundTask` marks the one parent-produced exception: delegated
- * dispatch resolves the model's tool call with a parked task receipt before
- * the child settles. Stream consumers use the marker to keep child lifecycle
- * open while still recording the receipt as the tool result.
*/
export interface RuntimeSubagentChildResult {
- readonly backgroundTask?: {
- readonly status: "working";
- readonly taskId: string;
- };
readonly callId: string;
readonly isError?: boolean;
readonly kind: "subagent-result";
diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.ts
index 393185faf..f0acbc502 100644
--- a/packages/eve/src/shared/agent-definition.ts
+++ b/packages/eve/src/shared/agent-definition.ts
@@ -202,13 +202,6 @@ export interface AgentLimitsDefinition {
* These options are unstable and may change or be removed in any release.
*/
export interface AgentExperimentalDefinition {
- /**
- * Runs this agent's delegated subagent calls as durable background tasks.
- * The originating tool call returns a task receipt immediately and the
- * model manages the work through the `task_*` framework tools. Root agents
- * only.
- */
- readonly tasks?: boolean;
/**
* Durable Workflow runtime configuration.
*/
diff --git a/packages/eve/src/shared/empty-delivery.test.ts b/packages/eve/src/shared/empty-delivery.test.ts
deleted file mode 100644
index 852cdde1a..000000000
--- a/packages/eve/src/shared/empty-delivery.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { EMPTY_DELIVERY_SENTINEL, hasEmptyDeliverySentinel } from "#shared/empty-delivery.js";
-
-describe("hasEmptyDeliverySentinel", () => {
- describe.each([EMPTY_DELIVERY_SENTINEL, "&lt;eve-empty-delivery/&gt;"])("%s", (sentinel) => {
- it("recognizes a standalone sentinel with optional surrounding whitespace", () => {
- expect(hasEmptyDeliverySentinel(sentinel)).toBe(true);
- expect(hasEmptyDeliverySentinel(` \n${sentinel}\t `)).toBe(true);
- });
-
- it.each([
- `before ${sentinel}`,
- `${sentinel} after`,
- `before ${sentinel} after`,
- `\`${sentinel}\``,
- `\`\`\`\n${sentinel}\n\`\`\``,
- `${sentinel}\n${sentinel}`,
- ])("preserves message content: %s", (message) => {
- expect(hasEmptyDeliverySentinel(message)).toBe(false);
- });
- });
-
- it("rejects absent, empty, and partial sentinels", () => {
- expect(hasEmptyDeliverySentinel("<eve-empty-delivery>")).toBe(false);
- expect(hasEmptyDeliverySentinel("")).toBe(false);
- expect(hasEmptyDeliverySentinel(" \n\t")).toBe(false);
- expect(hasEmptyDeliverySentinel(null)).toBe(false);
- expect(hasEmptyDeliverySentinel(undefined)).toBe(false);
- });
-});
diff --git a/packages/eve/src/shared/empty-delivery.ts b/packages/eve/src/shared/empty-delivery.ts
deleted file mode 100644
index c452af763..000000000
--- a/packages/eve/src/shared/empty-delivery.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export const EMPTY_DELIVERY_SENTINEL = "<eve-empty-delivery/>";
-const HTML_ESCAPED_EMPTY_DELIVERY_SENTINEL = "&lt;eve-empty-delivery/&gt;";
-
-export const CONDITIONAL_DELIVERY_INSTRUCTION = `Conditional delivery\nOnly when the current task explicitly makes delivery conditional and there is nothing new to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL} and no other text. This includes results already delivered or incorporated into an earlier response; do not send an acknowledgement of that redundancy. Do not use this marker for ordinary conversations, after input or approval responses, or to omit commentary from a response that still needs delivery. Never return an empty response; use the marker to intentionally deliver nothing.`;
-
-export function hasEmptyDeliverySentinel(text: string | null | undefined): boolean {
- const trimmed = text?.trim();
- return trimmed === EMPTY_DELIVERY_SENTINEL || trimmed === HTML_ESCAPED_EMPTY_DELIVERY_SENTINEL;
-}
diff --git a/packages/eve/src/shared/serialized-observability-state.ts b/packages/eve/src/shared/serialized-observability-state.ts
index 19b92c47b..74c010caf 100644
--- a/packages/eve/src/shared/serialized-observability-state.ts
+++ b/packages/eve/src/shared/serialized-observability-state.ts
@@ -5,8 +5,6 @@ export const SERIALIZED_INSTRUMENTATION_STATE_KEYS = {
providerState: "eve.harness.instrumentationState",
} as const;
-const SERIALIZED_AGENT_TRACE_STATE_KEY = "eve.harness.agentTrace";
-
/** Keeps instrumentation state needed to settle operations opened by a discarded step. */
export function preserveSerializedInstrumentationState(
original: Record<string, unknown>,
@@ -19,132 +17,3 @@ export function preserveSerializedInstrumentationState(
}
return preserved;
}
-
-/** Keeps only the observability state a retained background task needs before readiness. */
-export function preserveSerializedBackgroundTaskObservabilityState(
- original: Record<string, unknown>,
- completed: Record<string, unknown>,
- tasks: readonly { readonly taskId: string }[],
-): Record<string, unknown> {
- const taskIds = new Set(tasks.map((task) => task.taskId));
- const completedActions = asRecord(completed[SERIALIZED_INSTRUMENTATION_STATE_KEYS.actionScopes]);
- const actions = Object.fromEntries(
- Object.entries(completedActions).filter(([, value]) => {
- const action = asRecord(value);
- return typeof action["taskId"] === "string" && taskIds.has(action["taskId"]);
- }),
- );
- const actionIds = new Set(Object.keys(actions));
- if (actionIds.size === 0) return original;
-
- let preserved = mergeSerializedRecord(
- original,
- SERIALIZED_INSTRUMENTATION_STATE_KEYS.actionScopes,
- actions,
- );
- const providerState = Object.fromEntries(
- Object.entries(asRecord(completed[SERIALIZED_INSTRUMENTATION_STATE_KEYS.providerState])).filter(
- ([key]) => {
- const separator = key.indexOf("\0");
- return separator >= 0 && actionIds.has(key.slice(separator + 1));
- },
- ),
- );
- preserved = mergeSerializedRecord(
- preserved,
- SERIALIZED_INSTRUMENTATION_STATE_KEYS.providerState,
- providerState,
- );
-
- const completedTrace = asRecord(completed[SERIALIZED_AGENT_TRACE_STATE_KEY]);
- const traceActionAnchors = selectEntries(completedTrace["actionAnchors"], actionIds);
- const traceActions = Object.fromEntries(
- Object.entries(asRecord(completedTrace["actions"])).filter(([key]) => actionIds.has(key)),
- );
- const retainedCallIds = new Set<string>();
- for (const value of [...Object.values(traceActionAnchors), ...Object.values(traceActions)]) {
- const callId = asRecord(value)["callId"];
- if (typeof callId === "string") retainedCallIds.add(callId);
- }
- const traceInvocations = selectOwnedInvocations(
- completedTrace["invocations"],
- actionIds,
- retainedCallIds,
- );
- if (
- Object.keys(traceActionAnchors).length === 0 &&
- Object.keys(traceActions).length === 0 &&
- Object.keys(traceInvocations).length === 0
- ) {
- return preserved;
- }
- const originalTrace = asRecord(original[SERIALIZED_AGENT_TRACE_STATE_KEY]);
- return {
- ...preserved,
- [SERIALIZED_AGENT_TRACE_STATE_KEY]: {
- actionAnchors: {
- ...asRecord(originalTrace["actionAnchors"]),
- ...traceActionAnchors,
- },
- actions: { ...asRecord(originalTrace["actions"]), ...traceActions },
- invocations: {
- ...asRecord(originalTrace["invocations"]),
- ...traceInvocations,
- },
- sessions: asRecord(originalTrace["sessions"]),
- turns: asRecord(originalTrace["turns"]),
- },
- };
-}
-
-function selectEntries(value: unknown, keys: ReadonlySet<string>): Record<string, unknown> {
- return Object.fromEntries(Object.entries(asRecord(value)).filter(([key]) => keys.has(key)));
-}
-
-function selectOwnedInvocations(
- value: unknown,
- actionIds: ReadonlySet<string>,
- retainedCallIds: Set<string>,
-): Record<string, unknown> {
- const pending = Object.entries(asRecord(value));
- const selected: Record<string, unknown> = {};
- let found = true;
- while (found) {
- found = false;
- for (let index = pending.length - 1; index >= 0; index--) {
- const [key, candidate] = pending[index]!;
- const invocation = asRecord(candidate);
- const parentActionCallId = invocation["parentActionCallId"];
- if (
- !actionIds.has(key) &&
- !(typeof parentActionCallId === "string" && retainedCallIds.has(parentActionCallId))
- ) {
- continue;
- }
- selected[key] = candidate;
- const callId = invocation["callId"];
- if (typeof callId === "string") retainedCallIds.add(callId);
- pending.splice(index, 1);
- found = true;
- }
- }
- return selected;
-}
-
-function mergeSerializedRecord(
- context: Record<string, unknown>,
- key: string,
- entries: Record<string, unknown>,
-): Record<string, unknown> {
- if (Object.keys(entries).length === 0) return context;
- return {
- ...context,
- [key]: { ...asRecord(context[key]), ...entries },
- };
-}
-
-function asRecord(value: unknown): Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value)
- ? (value as Record<string, unknown>)
- : {};
-}
diff --git a/packages/eve/src/subagents/adapter-state.ts b/packages/eve/src/subagents/adapter-state.ts
index 2b096d07e..02381a571 100644
--- a/packages/eve/src/subagents/adapter-state.ts
+++ b/packages/eve/src/subagents/adapter-state.ts
@@ -30,8 +30,6 @@ 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;
}
/**
@@ -55,7 +53,6 @@ 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.taskId === undefined || (typeof state.taskId === "string" && state.taskId.length > 0))
+ state.subagentName.length > 0
);
}
diff --git a/packages/eve/src/subagents/auth-proxy.integration.test.ts b/packages/eve/src/subagents/auth-proxy.integration.test.ts
index ffe1ec36e..1ae8ac4fa 100644
--- a/packages/eve/src/subagents/auth-proxy.integration.test.ts
+++ b/packages/eve/src/subagents/auth-proxy.integration.test.ts
@@ -9,6 +9,7 @@ import { ContextContainer } from "#context/container.js";
import { AuthKey, ContinuationTokenKey, SessionIdKey } from "#context/keys.js";
import { emitProxiedSubagentEvent } from "#subagents/event-proxy-step.js";
import { projectToDurableSession } from "#execution/session.js";
+import { setHarnessEmissionState } from "#harness/emission-state.js";
import type { HarnessSession } from "#harness/types.js";
import type { MessageStreamEvent } from "#protocol/message.js";
import type { StreamEventHook } from "#public/definitions/hook.js";
@@ -72,6 +73,7 @@ function buildBundle(
"approval.candidate": hook,
"approval.settled": hook,
"turn.completed": hook,
+ "turn.waiting": hook,
"session.waiting": hook,
},
logicalPath: "hooks/audit.ts",
@@ -208,9 +210,10 @@ describe("subagent authorization proxy", () => {
expect(hook.mock.calls.map(([event]) => event)).toEqual(chunks.map(decodeEvent));
expect(hook.mock.calls.every(([, ctx]) => ctx.session.id === parentSessionId)).toBe(true);
});
- it("preserves required/completed events as standalone parent turns", async () => {
+ it("parks the parent's open turn on a sign-in without ending it", async () => {
const parentSessionId = "parent-session";
- const session = createSession(parentSessionId);
+ const openTurn = { sessionStarted: true, sequence: 3, stepIndex: 1, turnId: "parent-turn" };
+ const session = setHarnessEmissionState(createSession(parentSessionId), openTurn);
const { bundle, ctx, hook } = buildContext({
adapter: authorizationAdapter,
sessionId: parentSessionId,
@@ -270,13 +273,14 @@ describe("subagent authorization proxy", () => {
kind: authorizationAdapter.kind,
state: { outcome: "authorized" },
});
- expect(chunks).toHaveLength(6);
- expect(decodeEvent(chunks[0]!)).toMatchObject(requiredEvent);
- 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");
+ // The call that needs the sign-in keeps running, so the parent's turn parks
+ // and resumes under the same turn id rather than ending.
+ expect(chunks.map(decodeEvent)).toMatchObject([
+ requiredEvent,
+ { data: { sequence: 3, turnId: "parent-turn" }, type: "turn.waiting" },
+ completedEvent,
+ ]);
+ expect(completed.sessionState.emissionState).toMatchObject(openTurn);
expect(hook.mock.calls.map(([event]) => event)).toEqual(chunks.map(decodeEvent));
expect(hook.mock.calls.every(([, ctx]) => ctx.session.id === parentSessionId)).toBe(true);
});
diff --git a/packages/eve/src/subagents/callback-route.test.ts b/packages/eve/src/subagents/callback-route.test.ts
index 751137d14..3b802a7c4 100644
--- a/packages/eve/src/subagents/callback-route.test.ts
+++ b/packages/eve/src/subagents/callback-route.test.ts
@@ -4,8 +4,6 @@ import type { RouteContext } from "#public/definitions/channel.js";
import { handleSessionCallbackRequest } from "#subagents/callback-route.js";
const resumeHookMock = vi.fn();
-const TASK_ID = "task_1";
-const TASK_TOKEN = `task:${TASK_ID}:0123456789abcdef0123456789abcdef`;
vi.mock("#compiled/@workflow/core/runtime.js", () => ({
resumeHook: (token: string, payload: unknown) => resumeHookMock(token, payload),
@@ -16,202 +14,6 @@ describe("session callback route", () => {
resumeHookMock.mockReset();
});
- 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}`, {
- body: JSON.stringify({
- callId: "call-task",
- kind: "turn.started",
- sessionId: "child-session",
- subagentName: "research",
- taskId: TASK_ID,
- turnId: "turn_child_7",
- }),
- method: "POST",
- }),
- createRouteContext({ token: TASK_TOKEN }),
- );
-
- expect(response.status).toBe(410);
- expect(resumeHookMock).not.toHaveBeenCalled();
- });
-
- it("rejects removed direct task input callbacks", async () => {
- resumeHookMock.mockResolvedValue(undefined);
- const event = {
- requests: [
- {
- action: {
- callId: "release-call",
- input: { marker: "RELEASE" },
- kind: "tool-call",
- toolName: "release",
- },
- allowFreeform: false,
- display: "confirmation",
- kind: "tool-approval",
- options: [
- { id: "approve", label: "Approve" },
- { id: "reject", label: "Reject" },
- ],
- requestId: "req-1",
- prompt: "Approve release",
- },
- ],
- sequence: 3,
- stepIndex: 2,
- turnId: "turn-child",
- };
- const response = await handleSessionCallbackRequest(
- new Request(`https://app.example.com/eve/v1/callback/${TASK_TOKEN}`, {
- 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: 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("invocation-reply", {
- callId: "call-task",
- childContinuationToken: "remote-child-token",
- childSessionId: "child-session",
- event,
- kind: "subagent-input-request",
- subagentName: "research",
- });
- });
-
- 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.each([TASK_TOKEN, "invocation-reply"])(
- "rejects obsolete child task.update callbacks on %s",
- async (token) => {
- const response = await handleSessionCallbackRequest(
- new Request(`https://app.example.com/eve/v1/callback/${token}`, {
- body: JSON.stringify({
- callId: "update-call",
- updateIndex: 2,
- updateEpoch: "turn-child",
- kind: "task.update",
- message: "Found three matching records.",
- taskId: TASK_ID,
- }),
- method: "POST",
- }),
- createRouteContext({ token }),
- );
-
- expect(response.status).toBe(400);
- await expect(response.json()).resolves.toEqual({
- error: "Unsupported callback kind.",
- ok: false,
- });
- expect(resumeHookMock).not.toHaveBeenCalled();
- },
- );
-
- it.each([
- ["parent turn token", "turn-inbox", TASK_ID],
- ["different task token", TASK_TOKEN, "task_other"],
- ])("rejects task events carried by a %s", async (_label, token, taskId) => {
- const response = await handleSessionCallbackRequest(
- new Request(`https://app.example.com/eve/v1/callback/${token}`, {
- body: JSON.stringify({
- kind: "turn.started",
- sessionId: "child-session",
- taskId,
- turnId: "turn-child",
- }),
- method: "POST",
- }),
- createRouteContext({ token }),
- );
-
- expect(response.status).toBe(403);
- expect(resumeHookMock).not.toHaveBeenCalled();
- });
-
it("resumes a completed conversation turn with its outcome envelope", async () => {
resumeHookMock.mockResolvedValue(undefined);
diff --git a/packages/eve/src/subagents/callback-route.ts b/packages/eve/src/subagents/callback-route.ts
index 4859617b2..c2f485797 100644
--- a/packages/eve/src/subagents/callback-route.ts
+++ b/packages/eve/src/subagents/callback-route.ts
@@ -1,16 +1,9 @@
import { resumeHook } from "#internal/workflow/runtime.js";
import { z } from "#compiled/zod/index.js";
import type { RouteContext } from "#public/definitions/channel.js";
-import type {
- SubagentAuthorizationEvent,
- SubagentAuthorizationEventHookPayload,
- SubagentInputRequestHookPayload,
-} from "#channel/types.js";
import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
import { agentTurnOutcomeWithCostSchema } from "#shared/agent-turn-outcome.js";
import { jsonValueSchema } from "#shared/json-schemas.js";
-import { isInputRequest } from "#shared/input.js";
-import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
// Wire schemas of the child→parent callback route. Possession of the
// callback token is the authorization to settle; results bind to the
@@ -18,88 +11,6 @@ import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
// diagnostics) and never verified — new senders emit it, older eve
// deployments may omit it.
-const eventCoordinateSchema = z.number().int().nonnegative();
-
-const authorizationChallengeSchema = z.looseObject({
- displayName: z.string().optional(),
- expiresAt: z.string().optional(),
- instructions: z.string().optional(),
- url: z.string().optional(),
- userCode: z.string().optional(),
-});
-
-/**
- * Event payloads validate the fields the parent consumes and pass any
- * 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.looseObject({
- requests: z.array(jsonValueSchema.refine(isInputRequest)).min(1),
- sequence: eventCoordinateSchema,
- stepIndex: eventCoordinateSchema,
- turnId: z.string(),
-});
-
-const taskAuthorizationEventSchema: z.ZodType<SubagentAuthorizationEvent> = z.discriminatedUnion(
- "type",
- [
- z.looseObject({
- data: z.looseObject({
- attemptId: z.string().optional(),
- authorization: authorizationChallengeSchema.optional(),
- description: z.string(),
- name: z.string(),
- sequence: eventCoordinateSchema,
- stepIndex: eventCoordinateSchema,
- turnId: z.string(),
- webhookUrl: z.string().optional(),
- }),
- type: z.literal("authorization.required"),
- }),
- z.looseObject({
- data: z.looseObject({
- attemptId: z.string().optional(),
- authorization: authorizationChallengeSchema.optional(),
- name: z.string(),
- outcome: z.enum(["authorized", "declined", "failed", "timed-out"]),
- reason: z.string().optional(),
- sequence: eventCoordinateSchema,
- stepIndex: eventCoordinateSchema,
- turnId: z.string(),
- }),
- type: z.literal("authorization.completed"),
- }),
- ],
-);
-
-const taskEventCallbackSchema = z.discriminatedUnion("kind", [
- z.object({
- callId: z.string(),
- childContinuationToken: z.string(),
- childSessionId: z.string(),
- event: taskInputEventSchema,
- kind: z.literal("task.input-requested"),
- subagentName: z.string(),
- taskId: z.string(),
- }),
- z.object({
- callId: z.string(),
- childContinuationToken: z.string(),
- childSessionId: z.string(),
- event: taskAuthorizationEventSchema,
- kind: z.literal("task.authorization"),
- subagentName: z.string(),
- taskId: z.string(),
- }),
-]);
-
-const taskTurnStartedCallbackSchema = z.object({
- kind: z.literal("turn.started"),
- sessionId: z.string().min(1),
- taskId: z.string().min(1),
- turnId: z.string().min(1),
-});
-
/**
* Turn callbacks must carry the explicit `AgentTurnOutcome` envelope:
* the receiving parent settles the child's handle from `outcome.kind`, so
@@ -139,28 +50,6 @@ export async function handleSessionCallbackRequest(
return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
}
- const taskEvent = projectTaskEvent(body, token);
- if (taskEvent instanceof Response) return taskEvent;
- if (taskEvent !== undefined) {
- try {
- await resumeHook(token, taskEvent);
- } catch {
- return Response.json({ error: "Session callback not pending.", ok: false }, { status: 404 });
- }
- return Response.json({ ok: true }, { status: 202 });
- }
-
- const started = rejectDirectTaskTurnStarted(body, token);
- if (started instanceof Response) return started;
- if (started !== undefined) {
- try {
- await resumeHook(token, started);
- } catch {
- return Response.json({ error: "Session callback not pending.", ok: false }, { status: 404 });
- }
- return Response.json({ ok: true }, { status: 202 });
- }
-
const result = projectSessionCallbackResult(body);
if (result instanceof Response) {
return result;
@@ -183,66 +72,6 @@ function callbackKind(value: unknown): unknown {
return Reflect.get(value, "kind");
}
-function projectTaskEvent(
- value: unknown,
- token: string,
-): SubagentAuthorizationEventHookPayload | SubagentInputRequestHookPayload | Response | undefined {
- const kind = callbackKind(value);
- if (kind !== "task.input-requested" && kind !== "task.authorization") return undefined;
- const parsed = taskEventCallbackSchema.safeParse(value);
- if (!parsed.success) {
- return Response.json({ error: "Invalid task event callback.", ok: false }, { status: 400 });
- }
- const payload = parsed.data;
- 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 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 rejectDirectTaskTurnStarted(value: unknown, token: string): Response | undefined {
- if (callbackKind(value) !== "turn.started") return undefined;
- const parsed = taskTurnStartedCallbackSchema.safeParse(value);
- if (!parsed.success) {
- return Response.json(
- { error: "Invalid task turn-start callback.", ok: false },
- { status: 400 },
- );
- }
- const tokenRejection = rejectMismatchedTaskToken(token, parsed.data.taskId);
- if (tokenRejection !== undefined) return tokenRejection;
- return Response.json(
- { error: "Direct subagent task turn callbacks are no longer accepted.", ok: false },
- { status: 410 },
- );
-}
-
-function rejectMismatchedTaskToken(token: string, taskId: string): Response | undefined {
- return readTaskIdFromInboxToken(token) === taskId
- ? undefined
- : Response.json({ error: "Task callback token mismatch.", ok: false }, { status: 403 });
-}
-
function projectSessionCallbackResult(value: unknown): RuntimeSubagentChildResult | Response {
if (value === null || typeof value !== "object") {
return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
diff --git a/packages/eve/src/subagents/callback-step.ts b/packages/eve/src/subagents/callback-step.ts
deleted file mode 100644
index 98c2d5aa2..000000000
--- a/packages/eve/src/subagents/callback-step.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import type { SessionCallback, SubagentAuthorizationEvent } from "#channel/types.js";
-import { parseSessionCallback } from "#channel/session-callback.js";
-import { postSessionCallbackRequest } from "#execution/session-callback-request.js";
-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-
-/** Sends task-owned remote HITL and authorization events to the parent callback capability. */
-export async function fireTaskEventCallbackStep(input: {
- readonly callback: unknown;
- readonly childContinuationToken: string;
- readonly childSessionId: string;
- readonly event:
- | SubagentAuthorizationEvent
- | Extract<UnstampedMessageStreamEvent, { type: "input.requested" }>;
-}): Promise<void> {
- "use step";
-
- const callback = parseSerializedSessionCallback(input.callback);
- if (callback.taskId === undefined) return;
- const inputRequested = input.event.type === "input.requested";
- const kind = inputRequested ? "task.input-requested" : "task.authorization";
- const response = await postSessionCallbackRequest({
- body: {
- callId: callback.callId,
- childContinuationToken: input.childContinuationToken,
- childSessionId: input.childSessionId,
- event: inputRequested ? input.event.data : input.event,
- kind,
- subagentName: callback.subagentName,
- taskId: callback.taskId,
- },
- url: callback.url,
- });
- if (!response.ok) {
- throw new Error(`Task event callback failed with HTTP ${response.status}.`);
- }
-}
-
-function parseSerializedSessionCallback(value: unknown): SessionCallback {
- const parsed = parseSessionCallback(value);
- if (!parsed.ok) {
- throw new Error("Serialized session callback is invalid.", {
- cause: parsed.cause,
- });
- }
-
- return parsed.callback;
-}
diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.ts
index 6952cf3b4..1f7772241 100644
--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts
+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts
@@ -5,7 +5,6 @@ import type { SubagentInputRequestHookPayload } from "#channel/types.js";
import { ContextContainer } from "#context/container.js";
import { AuthKey, ContinuationTokenKey, SessionIdKey } from "#context/keys.js";
import type { DurableSession } from "#execution/durable-session-store.js";
-import { getProxyInputRequests } from "#harness/proxy-input-requests.js";
import { createSessionLimitContinuationRequest } from "#harness/session-limit-continuation.js";
import type { MessageStreamEvent } from "#protocol/message.js";
import type { HookContext } from "#public/definitions/hook.js";
@@ -18,7 +17,7 @@ import {
import { emitProxiedSubagentEvent } from "#subagents/event-proxy-step.js";
import { routeDeliverPayload } from "#subagents/hitl-proxy.js";
-function fixture(turnId = "parent-turn") {
+function fixture() {
const order: string[] = [];
const events: MessageStreamEvent[] = [];
const typed = vi.fn(async (event: MessageStreamEvent, _ctx: HookContext) => {
@@ -34,12 +33,6 @@ function fixture(turnId = "parent-turn") {
ctx.state.pendingRequests = data.requests;
ctx.session.continuation?.alias("parent-thread");
},
- "turn.completed"() {
- order.push("channel:turn.completed");
- },
- "session.waiting"() {
- order.push("channel:session.waiting");
- },
};
const turnAgent = { id: "parent", model: { id: "unused" }, tools: [] };
const bundle: CompiledBundle = {
@@ -50,8 +43,7 @@ function fixture(turnId = "parent-turn") {
{
events: {
"input.requested": typed,
- "turn.completed": typed,
- "session.waiting": typed,
+ "turn.waiting": typed,
"*": wildcard,
},
logicalPath: "hooks/audit.ts",
@@ -77,7 +69,12 @@ function fixture(turnId = "parent-turn") {
history: [],
sessionId: "parent-session",
state: {
- "eve.harness.emission": { turnId, sequence: 1, stepIndex: 0, sessionStarted: true },
+ "eve.harness.emission": {
+ turnId: "parent-turn",
+ sequence: 1,
+ stepIndex: 0,
+ sessionStarted: true,
+ },
},
};
const request = createSessionLimitContinuationRequest({
@@ -113,94 +110,56 @@ function fixture(turnId = "parent-turn") {
}
describe("proxied stream hooks", () => {
- it.each([{ turnId: "parent-turn" }, { turnId: "" }] as const)(
- "publishes hooks in parent context (turn=$turnId)",
- async ({ turnId }) => {
- const f = fixture(turnId);
- const result = await emitProxiedSubagentEvent(f);
- const types = ["input.requested", "turn.completed", "session.waiting"];
- expect(f.events.map((event) => event.type)).toEqual(types);
- expect(f.order).toEqual(
- types.flatMap((type) => [
- `channel:${type}`,
- `stream:${type}`,
- `typed:${type}`,
- `wildcard:${type}`,
- ]),
- );
- expect(f.typed.mock.calls.map(([event]) => event)).toEqual(f.events);
- expect(f.wildcard.mock.calls.map(([event]) => event)).toEqual(f.events);
- for (const [, ctx] of [...f.typed.mock.calls, ...f.wildcard.mock.calls]) {
- expect(ctx).toMatchObject({
- session: { id: "parent-session", turn: { id: turnId || "turn_1" } },
- agent: { name: "parent", nodeId: "parent" },
- channel: { kind: "proxy-hook-test", continuationToken: "http:parent-thread" },
- });
- }
- expect(f.events[0]).toMatchObject({ data: f.hookPayload.event });
- expect(result.serializedContext[ChannelKey.name]).toMatchObject({
- state: { pendingRequests: [f.request] },
- });
- expect(result.sessionState.continuationToken).toBe("http:parent-thread");
- expect(result.sessionState.hasProxyInputRequests).toBe(true);
- const routed = routeDeliverPayload({
- payload: { inputResponses: [{ requestId: f.request.requestId, optionId: "continue" }] },
- state: result.sessionState.snapshot.session.state,
- });
- expect(routed.forSelf).toBeUndefined();
- expect(routed.forChildren).toEqual([
- {
- childContinuationToken: "child-token",
- payload: { inputResponses: [{ requestId: f.request.requestId, optionId: "continue" }] },
- retireRequestIds: [f.request.requestId],
- },
- ]);
- },
- );
-
- it("retains pre-recorded task response destinations and child request IDs", async () => {
+ it("publishes the request and parks the open turn in parent context", async () => {
const f = fixture();
- const childRequestId = f.request.requestId;
- const requestId = `task-1:${childRequestId}`;
- const route = {
- childContinuationToken: "child-token",
- childRequestId,
- childResponseUrl: "https://child.example/eve/input",
- kind: "session-limit",
- taskId: "task-1",
- } as const;
- const result = await emitProxiedSubagentEvent({
- ...f,
- recordProxyInputRequests: false,
- durableSession: {
- ...f.durableSession,
- state: {
- ...f.durableSession.state,
- "eve.runtime.proxyInputRequests": { [requestId]: route },
- },
- },
- hookPayload: {
- ...f.hookPayload,
- event: { ...f.hookPayload.event, requests: [{ ...f.request, requestId }] },
- },
+ const result = await emitProxiedSubagentEvent(f);
+ expect(f.events.map((event) => event.type)).toEqual(["input.requested", "turn.waiting"]);
+ expect(f.events[1]).toMatchObject({ data: { sequence: 1, turnId: "parent-turn" } });
+ expect(f.order).toEqual([
+ "channel:input.requested",
+ "stream:input.requested",
+ "typed:input.requested",
+ "wildcard:input.requested",
+ "stream:turn.waiting",
+ "typed:turn.waiting",
+ "wildcard:turn.waiting",
+ ]);
+ expect(f.typed.mock.calls.map(([event]) => event)).toEqual(f.events);
+ expect(f.wildcard.mock.calls.map(([event]) => event)).toEqual(f.events);
+ for (const [, ctx] of [...f.typed.mock.calls, ...f.wildcard.mock.calls]) {
+ expect(ctx).toMatchObject({
+ session: { id: "parent-session", turn: { id: "parent-turn" } },
+ agent: { name: "parent", nodeId: "parent" },
+ channel: { kind: "proxy-hook-test", continuationToken: "http:parent-thread" },
+ });
+ }
+ expect(f.events[0]).toMatchObject({ data: f.hookPayload.event });
+ expect(result.serializedContext[ChannelKey.name]).toMatchObject({
+ state: { pendingRequests: [f.request] },
});
- expect(f.typed.mock.calls.filter(([event]) => event.type === "input.requested")).toHaveLength(
- 1,
- );
- const state = result.sessionState.snapshot.session.state;
- expect(getProxyInputRequests(state).get(requestId)).toEqual(route);
- expect(
- routeDeliverPayload({
- payload: { inputResponses: [{ requestId, optionId: "continue" }] },
- state,
- }).forChildren,
- ).toEqual([
+ expect(result.sessionState.continuationToken).toBe("http:parent-thread");
+ expect(result.sessionState.hasProxyInputRequests).toBe(true);
+ expect(result.sessionState.emissionState).toMatchObject({ sequence: 1, turnId: "parent-turn" });
+ const routed = routeDeliverPayload({
+ payload: { inputResponses: [{ requestId: f.request.requestId, optionId: "continue" }] },
+ state: result.sessionState.snapshot.session.state,
+ });
+ expect(routed.forSelf).toBeUndefined();
+ expect(routed.forChildren).toEqual([
{
- childContinuationToken: route.childContinuationToken,
- childResponseUrl: route.childResponseUrl,
- taskId: route.taskId,
- payload: { inputResponses: [{ requestId: childRequestId, optionId: "continue" }] },
- retireRequestIds: [requestId],
+ childContinuationToken: "child-token",
+ payload: { inputResponses: [{ requestId: f.request.requestId, optionId: "continue" }] },
+ resolved: {
+ event: { sequence: 7, stepIndex: 2, turnId: "child-turn" },
+ resolutions: [
+ {
+ kind: "session-limit",
+ outcome: "answered",
+ requestId: f.request.requestId,
+ response: { requestId: f.request.requestId, optionId: "continue" },
+ },
+ ],
+ },
},
]);
});
@@ -209,13 +168,9 @@ describe("proxied stream hooks", () => {
const f = fixture();
f.typed.mockRejectedValueOnce(new Error("audit unavailable"));
await emitProxiedSubagentEvent(f);
- expect(f.events.map((event) => event.type)).toEqual([
- "input.requested",
- "turn.completed",
- "session.waiting",
- ]);
- expect(f.typed).toHaveBeenCalledTimes(3);
- expect(f.wildcard).toHaveBeenCalledTimes(3);
+ expect(f.events.map((event) => event.type)).toEqual(["input.requested", "turn.waiting"]);
+ expect(f.typed).toHaveBeenCalledTimes(2);
+ expect(f.wildcard).toHaveBeenCalledTimes(2);
expect(f.sessionWritable.locked).toBe(false);
});
});
diff --git a/packages/eve/src/subagents/event-proxy-step.ts b/packages/eve/src/subagents/event-proxy-step.ts
index e1f56219d..7b640f2ac 100644
--- a/packages/eve/src/subagents/event-proxy-step.ts
+++ b/packages/eve/src/subagents/event-proxy-step.ts
@@ -1,60 +1,42 @@
-import { buildAdapterContext } from "#channel/adapter-context.js";
import type {
SubagentAuthorizationEventHookPayload,
SubagentInputRequestHookPayload,
} from "#channel/types.js";
import type { ContextContainer } from "#context/container.js";
-import { withContextScope } from "#context/run-step.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
-import { publishChannelEvent } from "#execution/publish-channel-event.js";
import {
createDurableSessionState,
type DurableSession,
- type DurableSessionState,
readDurableSession,
} from "#execution/durable-session-store.js";
-import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";
-import { hydrateDurableSession } from "#execution/session.js";
import {
- emitTurnEpilogue,
- getHarnessEmissionState,
- setHarnessEmissionState,
-} from "#harness/emission.js";
-import { emitProxiedInputRequest } from "#subagents/hitl-proxy.js";
+ withSessionEventEmitter,
+ type PublishedSessionEvents,
+ type SessionStepState,
+} from "#execution/publish-session-events.js";
+import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";
+import { emitProxiedAuthorizationEvent, 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";
-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
-import type { TaskInputRequestDelivery } from "#tasks/types.js";
+import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";
type SubagentEventHookPayload =
| SubagentAuthorizationEventHookPayload
| SubagentInputRequestHookPayload;
-type ProxyInputRequestEntries = readonly (readonly [requestId: string, route: ProxyInputRequest])[];
-
-interface ProxySubagentEventResult {
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}
-
/** Proxies one child event through its parent channel across a durable step boundary. */
-export async function runProxySubagentEventStep(input: {
- readonly answerHook?: AnswerHookRoute;
- readonly hookPayload: SubagentEventHookPayload;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<ProxySubagentEventResult> {
+export async function runProxySubagentEventStep(
+ input: SessionStepState & {
+ readonly workflowAsk?: WorkflowAskRoute;
+ readonly hookPayload: SubagentEventHookPayload;
+ },
+): Promise<PublishedSessionEvents> {
"use step";
const durableSession = readDurableSession(input.sessionState);
const ctx = await deserializeContext(input.serializedContext);
return emitProxiedSubagentEvent({
- answerHook: input.answerHook,
+ workflowAsk: input.workflowAsk,
ctx,
durableSession,
hookPayload: input.hookPayload,
@@ -62,110 +44,42 @@ export async function runProxySubagentEventStep(input: {
});
}
-/** Emits a task request whose proxy routes were committed by a prior step. */
-export async function emitRecordedTaskInputRequestStep(input: {
- readonly request: TaskInputRequestDelivery;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<ProxySubagentEventResult> {
- "use step";
-
- const durableSession = readDurableSession(input.sessionState);
- const ctx = await deserializeContext(input.serializedContext);
- return await emitProxiedSubagentEvent({
- ctx,
- durableSession,
- 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,
- },
- sessionWritable: input.sessionWritable,
- recordProxyInputRequests: false,
- });
-}
-
-/** Applies one proxied child event to an already-hydrated parent context. */
+/** Relays one child event through the parent session's channel. */
export async function emitProxiedSubagentEvent(input: {
- readonly answerHook?: AnswerHookRoute;
+ readonly workflowAsk?: WorkflowAskRoute;
readonly ctx: ContextContainer;
readonly durableSession: DurableSession;
readonly hookPayload: SubagentEventHookPayload;
readonly sessionWritable: WritableStream<Uint8Array>;
- readonly recordProxyInputRequests?: boolean;
-}): Promise<ProxySubagentEventResult> {
- const { ctx } = input;
- const adapter = ctx.require(ChannelKey);
- const bundle = ctx.require(BundleKey);
- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
- const session = hydrateDurableSession({
- compactionOverrides: {
- thresholdPercent: effectiveAgent.thresholdPercent,
+}): Promise<PublishedSessionEvents> {
+ const { ctx, hookPayload } = input;
+ const relayed = await withSessionEventEmitter(
+ {
+ ctx,
+ durableSession: input.durableSession,
+ origin: "relayed",
+ sessionWritable: input.sessionWritable,
},
- durable: input.durableSession,
- turnAgent: effectiveAgent.turnAgent,
- });
- const adapterCtx = buildAdapterContext(adapter, ctx);
- const writer = input.sessionWritable.getWriter();
-
- let proxyEntries: ProxyInputRequestEntries | undefined;
- let scopedSession: HarnessSession;
- try {
- // A re-emitted child event is a distinct event on the parent stream, so it
- // gets its own id rather than the child's.
- const emit = async (event: UnstampedMessageStreamEvent): Promise<void> => {
- // The child event is already routed; do not forward it again or apply
- // the parent's scheduled-turn suppression from createSessionEventSink.
- await publishChannelEvent({ adapter, adapterCtx, ctx, event, writer });
- };
-
- const scopeResult = await withContextScope(ctx, session, async (enrichedSession) => {
- if (input.hookPayload.kind === "subagent-authorization-event") {
- await emit(input.hookPayload.event);
- return {
- result: undefined,
- session: await closeStandaloneAuthorizationEvent({
- emit,
- eventType: input.hookPayload.event.type,
- session: enrichedSession,
- }),
- };
+ async (emit, session) => {
+ if (hookPayload.kind === "subagent-authorization-event") {
+ await emitProxiedAuthorizationEvent({ emit, hookPayload, session });
+ return { result: undefined, session };
}
- const proxyResult = await emitProxiedInputRequest({
- emit,
- hookPayload: input.hookPayload,
- session: enrichedSession,
- });
- return { result: proxyResult.entries, session: proxyResult.session };
- });
- proxyEntries = scopeResult.result;
- scopedSession = scopeResult.session;
- } finally {
- writer.releaseLock();
- }
+ const entries = await emitProxiedInputRequest({ emit, hookPayload, session });
+ return { result: entries, session };
+ },
+ );
- if (
- input.recordProxyInputRequests !== false &&
- proxyEntries !== undefined &&
- input.hookPayload.kind === "subagent-input-request"
- ) {
- const answerHook = input.answerHook;
+ let scopedSession = relayed.session;
+ if (relayed.result !== undefined && hookPayload.kind === "subagent-input-request") {
+ const workflowAsk = input.workflowAsk;
scopedSession = upsertProxyInputRequests({
entries:
- answerHook === undefined
- ? proxyEntries
- : proxyEntries.map(([requestId, route]) => [requestId, { ...route, answerHook }]),
- forChildContinuationToken: input.hookPayload.childContinuationToken,
+ workflowAsk === undefined
+ ? relayed.result
+ : relayed.result.map(([requestId, route]) => [requestId, { ...route, workflowAsk }]),
+ forChildContinuationToken: hookPayload.childContinuationToken,
session: scopedSession,
});
}
@@ -177,20 +91,3 @@ 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 session: HarnessSession;
-}): Promise<HarnessSession> {
- if (
- input.eventType !== "authorization.required" &&
- input.eventType !== "authorization.completed"
- ) {
- return input.session;
- }
-
- const state = getHarnessEmissionState(input.session.state);
- const nextState = await emitTurnEpilogue(input.emit, state);
- return setHarnessEmissionState(input.session, nextState);
-}
diff --git a/packages/eve/src/subagents/handle-dispatch.test.ts b/packages/eve/src/subagents/handle-dispatch.test.ts
index 8fe4cc1eb..f9d359a42 100644
--- a/packages/eve/src/subagents/handle-dispatch.test.ts
+++ b/packages/eve/src/subagents/handle-dispatch.test.ts
@@ -1,15 +1,9 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
import { dispatchToClaimedAgentAddress } from "./handle-dispatch.js";
-import { continueRemoteAgentSession, resolveRemoteAgentForAction } from "./remote-dispatch.js";
import { captureLogRecords } from "#internal/testing/log-records.js";
vi.mock("#execution/workflow-runtime.js", () => ({ createWorkflowRuntime: vi.fn() }));
-vi.mock("#subagents/remote-dispatch.js", async (importOriginal) => ({
- ...(await importOriginal()),
- continueRemoteAgentSession: vi.fn(),
- resolveRemoteAgentForAction: vi.fn(),
-}));
describe("claimed child delivery", () => {
const dispatchSession = vi.fn();
@@ -40,7 +34,7 @@ describe("claimed child delivery", () => {
ownerId: "original-task",
phase: "claimed",
},
- reply: { kind: "steer" },
+ parentToken: "reply-token",
} satisfies Parameters<typeof dispatchToClaimedAgentAddress>[0];
beforeEach(() => {
@@ -49,24 +43,8 @@ describe("claimed child delivery", () => {
vi.mocked(createWorkflowRuntime).mockReturnValue({ dispatchSession } as never);
});
- it("steers without replacing the active turn's caller", async () => {
- await expect(dispatchToClaimedAgentAddress(input)).resolves.toMatchObject({ kind: "called" });
- expect(dispatchSession).toHaveBeenCalledExactlyOnceWith({
- sessionId: "child",
- command: {
- auth: null,
- caller: undefined,
- kind: "send",
- payload: { message: "Use Alice's updated requirements", outputSchema: undefined },
- },
- });
- });
-
- it("supplies a new caller when continuing an idle child", async () => {
- await dispatchToClaimedAgentAddress({
- ...input,
- reply: { kind: "reply", parentToken: "reply-token", taskId: "new-task" },
- });
+ it("supplies a caller when continuing an idle child", async () => {
+ await dispatchToClaimedAgentAddress(input);
expect(dispatchSession).toHaveBeenCalledWith(
expect.objectContaining({
command: expect.objectContaining({
@@ -74,7 +52,6 @@ describe("claimed child delivery", () => {
callId: "update-call",
replyTo: { kind: "hook", token: "reply-token" },
subagentName: "research",
- taskId: "new-task",
},
}),
}),
@@ -93,34 +70,4 @@ describe("claimed child delivery", () => {
expect.objectContaining({ level: "error", message: "task agent delivery failed" }),
);
});
-
- it("steers a remote child without replacing its callback", async () => {
- vi.mocked(resolveRemoteAgentForAction).mockReturnValue({ name: "research" } as never);
- const remoteInput = {
- ...input,
- action: { ...input.action, kind: "remote-agent-call" as const, remoteAgentName: "research" },
- bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,
- handle: {
- ...input.handle,
- address: {
- kind: "agent/remote" as const,
- sessionId: "remote-child",
- url: "https://child.example",
- callbackBaseUrl: "https://parent.example",
- },
- },
- };
- await expect(dispatchToClaimedAgentAddress(remoteInput)).resolves.toMatchObject({
- kind: "called",
- });
- expect(continueRemoteAgentSession).toHaveBeenCalledExactlyOnceWith({
- auth: null,
- callback: undefined,
- message: "Use Alice's updated requirements",
- outputSchema: undefined,
- remote: { name: "research", url: "https://child.example" },
- sessionId: "remote-child",
- });
- expect(dispatchSession).not.toHaveBeenCalled();
- });
});
diff --git a/packages/eve/src/subagents/handle-dispatch.ts b/packages/eve/src/subagents/handle-dispatch.ts
index bf52aa207..5255860cd 100644
--- a/packages/eve/src/subagents/handle-dispatch.ts
+++ b/packages/eve/src/subagents/handle-dispatch.ts
@@ -1,4 +1,4 @@
-/** Continuation delivery for task-owned agent sessions. */
+/** Continuation delivery for agent sessions claimed by one owner. */
import type { ActivityObserverConfig, SessionAuthContext } from "#channel/types.js";
import { AGENT_UNREACHABLE } from "#subagents/agent-handle-errors.js";
@@ -24,7 +24,6 @@ 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");
@@ -71,14 +70,6 @@ export type DispatchOutcome =
readonly session: RuntimeSession;
};
-/**
- * Where the callee reports its result. A new turn replies to the caller's
- * hook; steering an active turn keeps that turn's original reply target.
- */
-export type AgentReplyTarget =
- | { readonly kind: "reply"; readonly parentToken: string; readonly taskId?: string }
- | { readonly kind: "steer" };
-
/** Delivers a continuation after the session handle store atomically claimed it for one owner. */
export async function dispatchToClaimedAgentAddress(input: {
readonly activityObserver?: ActivityObserverConfig;
@@ -87,7 +78,8 @@ export async function dispatchToClaimedAgentAddress(input: {
readonly bundle: CompiledBundle;
readonly currentSession: RuntimeSession;
readonly handle: Extract<TaskOwnedAgentHandle, { phase: "claimed" }>;
- readonly reply: AgentReplyTarget;
+ /** Hook token the callee's turn result is delivered to. */
+ readonly parentToken: string;
}): Promise<DispatchOutcome> {
const { action, handle } = input;
const agentId = handle.identity.id;
@@ -99,7 +91,7 @@ export async function dispatchToClaimedAgentAddress(input: {
auth: input.auth,
bundle: input.bundle,
identity: handle.identity,
- reply: input.reply,
+ parentToken: input.parentToken,
});
if (!delivery.ok) {
const { cause, permanent } = delivery.error;
@@ -152,18 +144,14 @@ async function deliverToAgentAddress(input: {
readonly auth: SessionAuthContext | null;
readonly bundle: CompiledBundle;
readonly identity: AgentIdentity;
- readonly reply: AgentReplyTarget;
+ readonly parentToken: string;
}): Promise<
Result<
void,
{ readonly cause: unknown; readonly deliveryAmbiguous: boolean; readonly permanent: boolean }
>
> {
- const { action, address, bundle, identity, reply } = input;
- const taskId =
- reply.kind === "reply"
- ? (reply.taskId ?? readTaskIdFromInboxToken(reply.parentToken))
- : undefined;
+ const { action, address, bundle, identity, parentToken } = input;
if (address.kind === "agent/remote") {
let resolvedRemote;
@@ -182,19 +170,15 @@ async function deliverToAgentAddress(input: {
await continueRemoteAgentSession({
activityObserver: input.activityObserver,
auth: input.auth,
- callback:
- reply.kind === "steer"
- ? undefined
- : {
- callId: action.callId,
- subagentName: identity.name,
- taskId,
- token: reply.parentToken,
- url: createWorkflowCallbackUrl(
- address.callbackBaseUrl,
- createEveCallbackRoutePath(reply.parentToken),
- ),
- },
+ callback: {
+ callId: action.callId,
+ subagentName: identity.name,
+ token: parentToken,
+ url: createWorkflowCallbackUrl(
+ address.callbackBaseUrl,
+ createEveCallbackRoutePath(parentToken),
+ ),
+ },
message: readSubagentMessage(action),
outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),
remote: { ...resolvedRemote, url: address.url },
@@ -218,16 +202,12 @@ async function deliverToAgentAddress(input: {
const result = await childRuntime.dispatchSession({
command: {
auth: input.auth,
- caller:
- reply.kind === "steer"
- ? undefined
- : {
- activityObserver: input.activityObserver,
- callId: action.callId,
- replyTo: { kind: "hook", token: reply.parentToken },
- subagentName: identity.name,
- taskId,
- },
+ caller: {
+ activityObserver: input.activityObserver,
+ callId: action.callId,
+ replyTo: { kind: "hook", token: parentToken },
+ subagentName: identity.name,
+ },
kind: "send",
payload: {
message: readSubagentMessage(action),
diff --git a/packages/eve/src/subagents/handles/prompt.test.ts b/packages/eve/src/subagents/handles/prompt.test.ts
index b04c8cc46..c4134450c 100644
--- a/packages/eve/src/subagents/handles/prompt.test.ts
+++ b/packages/eve/src/subagents/handles/prompt.test.ts
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import {
projectParkedAgentHandles,
- renderAgentViewsSnippet,
renderAgentsSnippet,
resolveAgentsAnnouncement,
} from "#subagents/handles/prompt.js";
@@ -78,26 +77,6 @@ describe("projectParkedAgentHandles / renderAgentsSnippet", () => {
});
});
-describe("renderAgentViewsSnippet", () => {
- it("keeps task-owned agents visible with derived busy state", () => {
- const snippet = renderAgentViewsSnippet([
- {
- availability: "busy",
- id: identity.id,
- name: identity.name,
- taskId: "task_123",
- taskStatus: "input_required",
- },
- ]);
-
- expect(snippet).toContain(
- `<agent id="${identity.id}" name="research" availability="busy" taskId="task_123" taskStatus="input_required">(busy)</agent>`,
- );
- expect(snippet).not.toContain("SESSION_ID_SENTINEL");
- expect(snippet).not.toContain("CONTINUATION_TOKEN_SENTINEL");
- });
-});
-
describe("resolveAgentsAnnouncement", () => {
it("announces a changed listing without replacing earlier conversation content", () => {
const messages = [{ content: "Earlier response", role: "assistant" as const }];
diff --git a/packages/eve/src/subagents/handles/prompt.ts b/packages/eve/src/subagents/handles/prompt.ts
index 941693b61..9232d912f 100644
--- a/packages/eve/src/subagents/handles/prompt.ts
+++ b/packages/eve/src/subagents/handles/prompt.ts
@@ -9,16 +9,6 @@ import type { AgentHandle, AgentHandleStore } from "#subagents/handles/store.js"
*/
export const AGENTS_SNIPPET_LABEL = "[Agents]";
-/** Model-safe projection of one persistent task-mode agent. */
-export interface AgentView {
- readonly availability: "available" | "busy";
- readonly id: string;
- readonly name: string;
- readonly statusLine?: string;
- readonly taskId?: string;
- readonly taskStatus?: "working" | "input_required";
-}
-
/** Returns the resumable handles: the only phases the model may continue. */
export function projectParkedAgentHandles(
store: AgentHandleStore,
@@ -42,19 +32,6 @@ export function renderAgentsSnippet(store: AgentHandleStore): string {
return [AGENTS_SNIPPET_LABEL, "<agents>", ...agents, "</agents>"].join("\n");
}
-/** Renders task-derived availability without exposing private addresses. */
-export function renderAgentViewsSnippet(views: readonly AgentView[]): string {
- const agents = views.map((view) => {
- const task =
- view.taskId === undefined || view.taskStatus === undefined
- ? ""
- : ` taskId="${escapeXml(view.taskId)}" taskStatus="${view.taskStatus}"`;
- const status = view.statusLine ?? (view.availability === "busy" ? "(busy)" : "(available)");
- return `<agent id="${escapeXml(view.id)}" name="${escapeXml(view.name)}" availability="${view.availability}"${task}>${escapeXml(status)}</agent>`;
- });
- return [AGENTS_SNIPPET_LABEL, "<agents>", ...agents, "</agents>"].join("\n");
-}
-
/**
* Returns an append-only announcement when the visible handle listing
* changed since the last one in history, or `undefined` when it is
@@ -74,7 +51,6 @@ export function renderAgentViewsSnippet(views: readonly AgentView[]): string {
* eve-injected so the model does not attribute it to the user.
*/
export function resolveAgentsAnnouncement(input: {
- readonly agentViews?: readonly AgentView[];
readonly messages: readonly ModelMessage[];
readonly store: AgentHandleStore | undefined;
}): string | undefined {
@@ -85,16 +61,11 @@ export function resolveAgentsAnnouncement(input: {
message.content.startsWith(AGENTS_SNIPPET_LABEL),
);
const store = input.store ?? { handles: [] };
- const visibleCount = input.agentViews?.length ?? projectParkedAgentHandles(store).length;
-
- if (latest === undefined && visibleCount === 0) {
+ if (latest === undefined && projectParkedAgentHandles(store).length === 0) {
return undefined;
}
- const rendered =
- input.agentViews === undefined
- ? renderAgentsSnippet(store)
- : renderAgentViewsSnippet(input.agentViews);
+ const rendered = renderAgentsSnippet(store);
return latest?.content === rendered ? undefined : rendered;
}
diff --git a/packages/eve/src/subagents/handles/query.ts b/packages/eve/src/subagents/handles/query.ts
index bcb028cd6..0c0726ebf 100644
--- a/packages/eve/src/subagents/handles/query.ts
+++ b/packages/eve/src/subagents/handles/query.ts
@@ -62,7 +62,7 @@ export function isResultBoundToRunningHandle(
if (result.kind !== "subagent-result") {
return true;
}
- if (result.origin === "dispatch" || result.backgroundTask !== undefined) {
+ if (result.origin === "dispatch") {
return true;
}
return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;
diff --git a/packages/eve/src/subagents/hitl-proxy.integration.test.ts b/packages/eve/src/subagents/hitl-proxy.integration.test.ts
index f1fc99c04..a2118de9e 100644
--- a/packages/eve/src/subagents/hitl-proxy.integration.test.ts
+++ b/packages/eve/src/subagents/hitl-proxy.integration.test.ts
@@ -9,6 +9,7 @@ import { ContextContainer } from "#context/container.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { serializeContext } from "#context/serialize.js";
+import { setHarnessEmissionState } from "#harness/emission-state.js";
import { hasProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import type { HarnessEmitFn, HarnessSession } from "#harness/types.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
@@ -164,6 +165,15 @@ function buildEmptySession(continuationToken: string, sessionId: string): Harnes
};
}
+function buildOpenTurnSession(continuationToken: string, sessionId: string): HarnessSession {
+ return setHarnessEmissionState(buildEmptySession(continuationToken, sessionId), {
+ sessionStarted: true,
+ sequence: 3,
+ stepIndex: 1,
+ turnId: "turn_3",
+ });
+}
+
/**
* Builds an adapter-aware emit helper and a captured-events sink
* paired to one parent context. The returned `emit` mirrors the
@@ -220,10 +230,11 @@ describe("subagent HITL proxy → Slack-style text-approve regression (Finding #
});
const { emit, events, persistAdapterState } = buildCapturingEmit(ctx);
- const { entries, session: sessionAfterEmit } = await emitProxiedInputRequest({
+ const parentSession = buildOpenTurnSession("parent-token", "sess-parent");
+ const entries = await emitProxiedInputRequest({
emit,
hookPayload,
- session: buildEmptySession("parent-token", "sess-parent"),
+ session: parentSession,
});
// Simulate the workflow step's post-step
// `ctx.set(ChannelKey, { …adapter, state })` — the mutation the
@@ -246,20 +257,19 @@ describe("subagent HITL proxy → Slack-style text-approve regression (Finding #
requestIds: ["req-approve-1"],
},
childContinuationToken: "subagent:parent:call-1",
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
kind: "tool-approval",
},
],
]);
- // The helper follows the proxied `input.requested` with a
- // `turn.completed` + `session.waiting` pair so client event-stream
- // readers stop draining and prompt for the HITL response.
- const emittedTypes = events.map((event) => event.type);
- expect(emittedTypes).toEqual(["input.requested", "turn.completed", "session.waiting"]);
-
- // The returned session carries the advanced emission state so
- // the next harness step starts a fresh logical turn.
- expect(sessionAfterEmit.state?.["eve.harness.emission"]).toBeDefined();
+ // The proxied `input.requested` parks the parent's open turn with
+ // `turn.waiting`; the call that asked is still running, so the turn
+ // neither completes nor resets.
+ expect(events.slice(1)).toEqual([
+ { data: { sequence: 3, turnId: "turn_3" }, type: "turn.waiting" },
+ ]);
+ expect(events[0]?.type).toBe("input.requested");
// The serialized adapter state must include mutations made while
// rendering the proxied input request.
@@ -312,7 +322,17 @@ describe("subagent HITL proxy → Slack-style text-approve regression (Finding #
payload: {
inputResponses: [{ optionId: "approve", requestId: "req-approve-1" }],
},
- retireRequestIds: ["req-approve-1"],
+ resolved: {
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ resolutions: [
+ {
+ kind: "tool-approval",
+ outcome: "approved",
+ requestId: "req-approve-1",
+ response: { optionId: "approve", requestId: "req-approve-1" },
+ },
+ ],
+ },
},
]);
});
@@ -348,7 +368,7 @@ describe("subagent HITL proxy → concurrent-descendant routing", () => {
request: requestA,
subagentName: "descendantA",
});
- const { entries: entriesA } = await emitProxiedInputRequest({
+ const entriesA = await emitProxiedInputRequest({
emit,
hookPayload: payloadA,
session: buildEmptySession("parent-token", "sess-parent"),
@@ -363,7 +383,7 @@ describe("subagent HITL proxy → concurrent-descendant routing", () => {
request: requestB,
subagentName: "descendantB",
});
- const { entries: entriesB } = await emitProxiedInputRequest({
+ const entriesB = await emitProxiedInputRequest({
emit,
hookPayload: payloadB,
session: buildEmptySession("parent-token", "sess-parent"),
diff --git a/packages/eve/src/subagents/hitl-proxy.test.ts b/packages/eve/src/subagents/hitl-proxy.test.ts
index b295eb941..4b855c621 100644
--- a/packages/eve/src/subagents/hitl-proxy.test.ts
+++ b/packages/eve/src/subagents/hitl-proxy.test.ts
@@ -4,6 +4,8 @@ import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import type { HarnessSession } from "#harness/types.js";
import { routeDeliverPayload } from "#subagents/hitl-proxy.js";
+const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };
+
function createSession(state?: Record<string, unknown>): HarnessSession {
return {
agent: {
@@ -28,6 +30,7 @@ describe("routeDeliverPayload", () => {
{
childContinuationToken: "child-alias",
childSessionInbox: { sessionId: "child-a" },
+ event: REQUEST_EVENT,
kind: "question",
},
],
@@ -36,6 +39,7 @@ describe("routeDeliverPayload", () => {
{
childContinuationToken: "child-alias",
childSessionInbox: { sessionId: "child-b" },
+ event: REQUEST_EVENT,
kind: "question",
},
],
@@ -70,10 +74,20 @@ describe("routeDeliverPayload", () => {
it("routes responses to matching descendants and keeps unknown ones on forSelf", () => {
const session = upsertProxyInputRequests({
- entries: [["req-a", { childContinuationToken: "child-a", kind: "tool-approval" }]],
+ entries: [
+ [
+ "req-a",
+ { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "tool-approval" },
+ ],
+ ],
forChildContinuationToken: "child-a",
session: upsertProxyInputRequests({
- entries: [["req-b", { childContinuationToken: "child-b", kind: "tool-approval" }]],
+ entries: [
+ [
+ "req-b",
+ { childContinuationToken: "child-b", event: REQUEST_EVENT, kind: "tool-approval" },
+ ],
+ ],
forChildContinuationToken: "child-b",
session: createSession(),
}),
@@ -116,43 +130,11 @@ describe("routeDeliverPayload", () => {
});
it("returns forSelf as undefined when every response routes to a descendant", () => {
- const session = upsertProxyInputRequests({
- entries: [["req-a", { childContinuationToken: "child-a", kind: "tool-approval" }]],
- forChildContinuationToken: "child-a",
- session: createSession(),
- });
-
- const routed = routeDeliverPayload({
- payload: {
- inputResponses: [{ optionId: "approve", requestId: "req-a" }],
- },
- state: session.state,
- });
-
- expect(routed.forChildren).toHaveLength(1);
- expect(routed.forSelf).toBeUndefined();
- });
-
- it("keeps one task response batch atomic and marks it for its task run", () => {
const session = upsertProxyInputRequests({
entries: [
[
- "task-1:req-a",
- {
- childContinuationToken: "child-a",
- childRequestId: "req-a",
- kind: "tool-approval",
- taskId: "task-1",
- },
- ],
- [
- "task-1:req-b",
- {
- childContinuationToken: "child-a",
- childRequestId: "req-b",
- kind: "question",
- taskId: "task-1",
- },
+ "req-a",
+ { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "tool-approval" },
],
],
forChildContinuationToken: "child-a",
@@ -161,81 +143,23 @@ describe("routeDeliverPayload", () => {
const routed = routeDeliverPayload({
payload: {
- inputResponses: [
- { optionId: "approve", requestId: "task-1:req-a" },
- { text: "west", requestId: "task-1:req-b" },
- ],
+ inputResponses: [{ optionId: "approve", requestId: "req-a" }],
},
state: session.state,
});
- expect(routed.forChildren).toEqual([
- {
- childContinuationToken: "child-a",
- payload: {
- inputResponses: [
- { optionId: "approve", requestId: "req-a" },
- { text: "west", requestId: "req-b" },
- ],
- },
- retireRequestIds: ["task-1:req-a", "task-1:req-b"],
- taskId: "task-1",
- },
- ]);
+ expect(routed.forChildren).toHaveLength(1);
+ expect(routed.forSelf).toBeUndefined();
});
- it("keeps identical child-local ids isolated across tasks", () => {
- let session = upsertProxyInputRequests({
- entries: [
- [
- "task-1:req-shared",
- {
- childContinuationToken: "child-a",
- childRequestId: "req-shared",
- kind: "tool-approval",
- taskId: "task-1",
- },
- ],
- ],
- forChildContinuationToken: "child-a",
- session: createSession(),
- });
- session = upsertProxyInputRequests({
+ it("asks the parent to cancel after routing Stop to a descendant session-limit request", () => {
+ const session = upsertProxyInputRequests({
entries: [
[
- "task-2:req-shared",
- {
- childContinuationToken: "child-b",
- childRequestId: "req-shared",
- kind: "tool-approval",
- taskId: "task-2",
- },
+ "req-limit",
+ { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "session-limit" },
],
],
- forChildContinuationToken: "child-b",
- session,
- });
-
- const routed = routeDeliverPayload({
- payload: {
- inputResponses: [{ optionId: "approve", requestId: "task-1:req-shared" }],
- },
- state: session.state,
- });
-
- expect(routed.forChildren).toEqual([
- {
- childContinuationToken: "child-a",
- payload: { inputResponses: [{ optionId: "approve", requestId: "req-shared" }] },
- retireRequestIds: ["task-1:req-shared"],
- taskId: "task-1",
- },
- ]);
- });
-
- it("asks the parent to cancel after routing Stop to a descendant session-limit request", () => {
- const session = upsertProxyInputRequests({
- entries: [["req-limit", { childContinuationToken: "child-a", kind: "session-limit" }]],
forChildContinuationToken: "child-a",
session: createSession(),
});
@@ -251,7 +175,17 @@ describe("routeDeliverPayload", () => {
{
childContinuationToken: "child-a",
payload: { inputResponses: [{ optionId: "stop", requestId: "req-limit" }] },
- retireRequestIds: ["req-limit"],
+ resolved: {
+ event: REQUEST_EVENT,
+ resolutions: [
+ {
+ kind: "session-limit",
+ outcome: "answered",
+ requestId: "req-limit",
+ response: { optionId: "stop", requestId: "req-limit" },
+ },
+ ],
+ },
},
]);
expect(routed.parentAction).toEqual({ kind: "cancel-turn" });
@@ -260,9 +194,7 @@ describe("routeDeliverPayload", () => {
describe("routeDeliverPayload message resolution", () => {
function askSession(
- questions: ReadonlyArray<
- readonly [requestId: string, question: { allowFreeform?: boolean; dismissible?: boolean }]
- >,
+ questions: ReadonlyArray<readonly [requestId: string, question: { allowFreeform?: boolean }]>,
): HarnessSession {
let session = createSession();
for (const [requestId, question] of questions) {
@@ -271,7 +203,7 @@ describe("routeDeliverPayload message resolution", () => {
[
requestId,
{
- answerHook: {
+ workflowAsk: {
question: {
...question,
options: [
@@ -280,8 +212,10 @@ describe("routeDeliverPayload message resolution", () => {
],
},
runId: `run-${requestId}`,
+ control: `control-${requestId}`,
},
childContinuationToken: `hook-${requestId}`,
+ event: REQUEST_EVENT,
kind: "question",
},
],
@@ -297,7 +231,7 @@ describe("routeDeliverPayload message resolution", () => {
const routed = routeDeliverPayload({
payload: { message: "production" },
resolveMessage: true,
- state: askSession([["ask-1", { dismissible: true }]]).state,
+ state: askSession([["ask-1", {}]]).state,
});
expect(routed.forSelf).toBeUndefined();
@@ -305,17 +239,16 @@ describe("routeDeliverPayload message resolution", () => {
{
childContinuationToken: "hook-ask-1",
payload: { inputResponses: [{ optionId: "2", requestId: "ask-1" }] },
- retireRequestIds: ["ask-1"],
+ resolved: { resolutions: [{ outcome: "answered", requestId: "ask-1" }] },
},
]);
- expect(routed.forChildren[0]?.dismissedRequestIds).toBeUndefined();
});
it("answers the only pending question with free text when it allows it", () => {
const routed = routeDeliverPayload({
payload: { message: "Use the canary pool" },
resolveMessage: true,
- state: askSession([["ask-1", { allowFreeform: true, dismissible: true }]]).state,
+ state: askSession([["ask-1", { allowFreeform: true }]]).state,
});
expect(routed.forSelf).toBeUndefined();
@@ -324,33 +257,30 @@ describe("routeDeliverPayload message resolution", () => {
]);
});
- it("dismisses dismissible questions and keeps an unrelated message for the turn", () => {
+ it("keeps a message for the turn when several questions are pending", () => {
const routed = routeDeliverPayload({
payload: { message: "Actually, check the logs first." },
resolveMessage: true,
state: askSession([
- ["ask-1", { dismissible: true }],
+ ["ask-1", {}],
["ask-2", {}],
]).state,
});
expect(routed.forSelf).toEqual({ message: "Actually, check the logs first." });
- expect(routed.forChildren).toEqual([
- {
- answerHook: expect.objectContaining({ runId: "run-ask-1" }),
- childContinuationToken: "hook-ask-1",
- dismissedRequestIds: ["ask-1"],
- payload: { inputResponses: [] },
- retireRequestIds: ["ask-1"],
- },
- ]);
+ expect(routed.forChildren).toEqual([]);
});
it("does not answer a question while a subagent question is also pending", () => {
const session = upsertProxyInputRequests({
- entries: [["child-ask", { childContinuationToken: "child-token", kind: "question" }]],
+ entries: [
+ [
+ "child-ask",
+ { childContinuationToken: "child-token", event: REQUEST_EVENT, kind: "question" },
+ ],
+ ],
forChildContinuationToken: "child-token",
- session: askSession([["ask-1", { allowFreeform: true, dismissible: true }]]),
+ session: askSession([["ask-1", { allowFreeform: true }]]),
});
const routed = routeDeliverPayload({
payload: { message: "Use the canary pool" },
@@ -359,13 +289,13 @@ describe("routeDeliverPayload message resolution", () => {
});
expect(routed.forSelf).toEqual({ message: "Use the canary pool" });
- expect(routed.forChildren).toMatchObject([{ dismissedRequestIds: ["ask-1"] }]);
+ expect(routed.forChildren).toEqual([]);
});
it("leaves questions alone unless a person's message may resolve them", () => {
const routed = routeDeliverPayload({
payload: { message: "production" },
- state: askSession([["ask-1", { dismissible: true }]]).state,
+ state: askSession([["ask-1", {}]]).state,
});
expect(routed.forSelf).toEqual({ message: "production" });
@@ -395,7 +325,7 @@ describe("routeDeliverPayload message resolution", () => {
message: "production",
},
resolveMessage: true,
- state: askSession([["ask-1", { dismissible: true }]]).state,
+ state: askSession([["ask-1", {}]]).state,
});
expect(routed.forSelf).toEqual({ message: "production" });
diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.ts
index fa0555425..fab124966 100644
--- a/packages/eve/src/subagents/hitl-proxy.ts
+++ b/packages/eve/src/subagents/hitl-proxy.ts
@@ -1,17 +1,23 @@
import type { SessionInboxAddress } from "#execution/session-inbox/address.js";
-import type { DeliverPayload, SubagentInputRequestHookPayload } from "#channel/types.js";
-import {
- emitTurnEpilogue,
- getHarnessEmissionState,
- setHarnessEmissionState,
-} from "#harness/emission.js";
+import type {
+ DeliverPayload,
+ SubagentAuthorizationEventHookPayload,
+ SubagentInputRequestHookPayload,
+} from "#channel/types.js";
+import { getHarnessEmissionState } from "#harness/emission.js";
+import { resolveInputOutcome } from "#harness/input-request-resolution.js";
+import type { PendingInputBatchEvent } from "#harness/pending-input-batches.js";
import {
getProxyInputRequests,
toProxyInputRequestEntries,
} from "#harness/proxy-input-requests.js";
-import type { AnswerHookRoute, ProxyInputRequest } from "#harness/proxy-input-requests.js";
+import type { WorkflowAskRoute, ProxyInputRequest } from "#harness/proxy-input-requests.js";
import type { HarnessEmitFn, HarnessSession, SessionStateMap } from "#harness/types.js";
-import { createInputRequestedEvent } from "#protocol/message.js";
+import {
+ createInputRequestedEvent,
+ createTurnWaitingEvent,
+ type InputResolution,
+} from "#protocol/message.js";
import type { InputResponse } from "#shared/input.js";
import { resolveTextToResponse } from "#channel/resolve-text.js";
import { SESSION_LIMIT_STOP_OPTION_ID } from "#harness/session-limit-continuation.js";
@@ -21,18 +27,16 @@ import { SESSION_LIMIT_STOP_OPTION_ID } from "#harness/session-limit-continuatio
// ---------------------------------------------------------------------------
/**
- * Runs the parent-side work for a `subagent-input-request`: emits the request
- * and a waiting boundary on the parent stream. The returned proxy entries
- * route the eventual response back down to the child.
+ * Runs the parent-side work for a `subagent-input-request`: emits the request,
+ * then `turn.waiting` for the parent's open turn. The call that asked is still
+ * running, so the turn stays open until the answer lets that call settle. The
+ * returned proxy entries route the eventual response back down to the asker.
*/
export async function emitProxiedInputRequest(input: {
readonly emit: HarnessEmitFn;
readonly hookPayload: SubagentInputRequestHookPayload;
readonly session: HarnessSession;
-}): Promise<{
- readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];
- readonly session: HarnessSession;
-}> {
+}): Promise<readonly (readonly [requestId: string, route: ProxyInputRequest])[]> {
await input.emit(
createInputRequestedEvent({
requests: input.hookPayload.event.requests,
@@ -41,13 +45,30 @@ export async function emitProxiedInputRequest(input: {
turnId: input.hookPayload.event.turnId,
}),
);
+ await emitTurnWaiting(input.emit, input.session);
+ return toProxyInputRequestEntries(input.hookPayload);
+}
- const state = getHarnessEmissionState(input.session.state);
- const nextState = await emitTurnEpilogue(input.emit, state);
- return {
- entries: toProxyInputRequestEntries(input.hookPayload),
- session: setHarnessEmissionState(input.session, nextState),
- };
+/**
+ * Runs the parent-side work for a `subagent-authorization-event`: re-emits the
+ * event, and after `authorization.required` parks the parent's open turn with
+ * `turn.waiting`. The sign-in completes on the asker's own callback while the
+ * call keeps running, so the parent's turn neither ends nor resets.
+ */
+export async function emitProxiedAuthorizationEvent(input: {
+ readonly emit: HarnessEmitFn;
+ readonly hookPayload: SubagentAuthorizationEventHookPayload;
+ readonly session: HarnessSession;
+}): Promise<void> {
+ await input.emit(input.hookPayload.event);
+ if (input.hookPayload.event.type === "authorization.required") {
+ await emitTurnWaiting(input.emit, input.session);
+ }
+}
+
+async function emitTurnWaiting(emit: HarnessEmitFn, session: HarnessSession): Promise<void> {
+ const turn = getHarnessEmissionState(session.state);
+ await emit(createTurnWaitingEvent({ sequence: turn.sequence, turnId: turn.turnId }));
}
// ---------------------------------------------------------------------------
@@ -56,17 +77,23 @@ export async function emitProxiedInputRequest(input: {
/** One proxied-child bucket of a routed deliver payload. */
export interface RoutedChildDelivery {
- readonly answerHook?: AnswerHookRoute;
+ readonly workflowAsk?: WorkflowAskRoute;
readonly childContinuationToken: string;
readonly childSessionInbox?: SessionInboxAddress;
- readonly childResponseUrl?: string;
- /** Answer-hook requests the user moved past; each hook resumes as `dismissed`. */
- readonly dismissedRequestIds?: readonly string[];
readonly payload: { readonly inputResponses: readonly InputResponse[] };
- /** Parent-visible request IDs safe to retire once this bucket is forwarded. */
- readonly retireRequestIds: readonly string[];
- /** Present when the child is owned by a task run, which delivers on the parent's behalf. */
- readonly taskId?: string;
+ /** What forwarding this bucket resolves on the routing session. */
+ readonly resolved: ProxiedInputResolutions;
+}
+
+/**
+ * The parent-visible requests one forwarded bucket resolves: those it answers,
+ * plus the rest of a batch those answers complete. Each retires from the proxy
+ * map, and the session announces them with one `input.resolved` at `event`,
+ * the coordinates of the child batch's `input.requested`.
+ */
+export interface ProxiedInputResolutions {
+ readonly event: PendingInputBatchEvent;
+ readonly resolutions: readonly InputResolution[];
}
/**
@@ -82,16 +109,15 @@ export interface RoutedDeliverPayload {
/** In-progress accumulation for one `forChildren` bucket. */
interface ChildResponseBucket {
- readonly answerHook?: AnswerHookRoute;
+ readonly workflowAsk?: WorkflowAskRoute;
readonly childContinuationToken: string;
readonly childSessionInbox?: SessionInboxAddress;
- readonly childResponseUrl?: string;
- readonly dismissedRequestIds: string[];
+ /** A child's routes all come from its latest batch, so they share coordinates. */
+ readonly event: PendingInputBatchEvent;
/** Parent-visible request IDs answered in this bucket. */
readonly parentRequestIds: string[];
readonly responses: InputResponse[];
readonly routes: ProxyInputRequest[];
- readonly taskId?: string;
}
/**
@@ -100,7 +126,7 @@ interface ChildResponseBucket {
* With `resolveMessage`, a plain-text message is also resolved against pending
* `ctx.ask()` questions: when exactly one question is pending, a matching option or
* permitted free text answers it and consumes the message. Otherwise the
- * message dismisses every `dismissible` question and stays with the parent.
+ * message stays with the parent.
*/
export function routeDeliverPayload(input: {
readonly allowRoute?: (requestId: string, route: ProxyInputRequest) => boolean;
@@ -124,26 +150,21 @@ export function routeDeliverPayload(input: {
let parentAction: RoutedDeliverPayload["parentAction"];
const bucketFor = (route: ProxyInputRequest): ChildResponseBucket => {
- const bucketKey = [
- route.childContinuationToken,
- route.childSessionInbox?.sessionId ?? "",
- route.childResponseUrl ?? "local",
- route.taskId ?? "",
- ].join("\0");
+ const bucketKey = [route.childContinuationToken, route.childSessionInbox?.sessionId ?? ""].join(
+ "\0",
+ );
const existing = responsesByChild.get(bucketKey);
if (existing !== undefined) return existing;
const bucket: ChildResponseBucket = {
childContinuationToken: route.childContinuationToken,
- dismissedRequestIds: [],
+ event: route.event,
parentRequestIds: [],
responses: [],
routes: [],
...(route.childSessionInbox !== undefined && {
childSessionInbox: route.childSessionInbox,
}),
- ...(route.answerHook !== undefined && { answerHook: route.answerHook }),
- ...(route.childResponseUrl !== undefined && { childResponseUrl: route.childResponseUrl }),
- ...(route.taskId !== undefined && { taskId: route.taskId }),
+ ...(route.workflowAsk !== undefined && { workflowAsk: route.workflowAsk }),
};
responsesByChild.set(bucketKey, bucket);
return bucket;
@@ -167,29 +188,22 @@ export function routeDeliverPayload(input: {
const bucket = bucketFor(route);
bucket.parentRequestIds.push(response.requestId);
- bucket.responses.push(toChildInputResponse(response, route));
+ bucket.responses.push(response);
bucket.routes.push(route);
}
- for (const requestId of message.dismissedRequestIds) {
- const route = entries.get(requestId);
- if (route !== undefined) bucketFor(route).dismissedRequestIds.push(requestId);
- }
-
const forChildren = [...responsesByChild.values()].map(
({
- answerHook,
+ workflowAsk,
childContinuationToken,
childSessionInbox,
- childResponseUrl,
- dismissedRequestIds,
+ event,
parentRequestIds,
responses,
routes,
- taskId,
}): RoutedChildDelivery => {
const responseIds = new Set(parentRequestIds);
- const retireRequestIds = new Set([...responseIds, ...dismissedRequestIds]);
+ const retireRequestIds = new Set(responseIds);
// A fully-answered approval batch retires its sibling requests
// too, so a late free-form answer cannot route through a stale
@@ -206,12 +220,12 @@ export function routeDeliverPayload(input: {
return {
childContinuationToken,
payload: { inputResponses: responses },
- retireRequestIds: [...retireRequestIds],
- ...(dismissedRequestIds.length > 0 && { dismissedRequestIds }),
+ resolved: {
+ event,
+ resolutions: resolveRetiredRequests({ entries, responses, retireRequestIds }),
+ },
...(childSessionInbox !== undefined && { childSessionInbox }),
- ...(answerHook !== undefined && { answerHook }),
- ...(childResponseUrl !== undefined && { childResponseUrl }),
- ...(taskId !== undefined && { taskId }),
+ ...(workflowAsk !== undefined && { workflowAsk }),
};
},
);
@@ -239,6 +253,31 @@ export function routeDeliverPayload(input: {
return { forChildren, forSelf, parentAction };
}
+function resolveRetiredRequests(input: {
+ readonly entries: ReadonlyMap<string, ProxyInputRequest>;
+ readonly responses: readonly InputResponse[];
+ readonly retireRequestIds: ReadonlySet<string>;
+}): InputResolution[] {
+ const responses = new Map(input.responses.map((response) => [response.requestId, response]));
+ const resolutions: InputResolution[] = [];
+ for (const requestId of input.retireRequestIds) {
+ const route = input.entries.get(requestId);
+ if (route === undefined) continue;
+ resolutions.push(toInputResolution(requestId, route, responses.get(requestId)));
+ }
+ return resolutions;
+}
+
+function toInputResolution(
+ requestId: string,
+ route: ProxyInputRequest,
+ response: InputResponse | undefined,
+): InputResolution {
+ const outcome = resolveInputOutcome(route.kind, response);
+ const resolution: InputResolution = { kind: route.kind, outcome, requestId };
+ return response === undefined ? resolution : { ...resolution, response };
+}
+
function resolveMessageAgainstQuestions(input: {
readonly enabled: boolean;
readonly entries: ReadonlyMap<string, ProxyInputRequest>;
@@ -246,21 +285,20 @@ function resolveMessageAgainstQuestions(input: {
readonly routable: (requestId: string, route: ProxyInputRequest) => boolean;
}): {
readonly consumed: boolean;
- readonly dismissedRequestIds: readonly string[];
readonly responses: readonly InputResponse[];
} {
- const none = { consumed: false, dismissedRequestIds: [], responses: [] };
+ const none = { consumed: false, responses: [] };
// An explicit structured answer means the client already chose what to answer.
if (!input.enabled || (input.payload.inputResponses?.length ?? 0) > 0) return none;
if (input.payload.message === undefined) return none;
- // Task and subagent questions carry no answer-hook metadata, so plain text
+ // Task and subagent questions carry no `ctx.ask()` metadata, so plain text
// cannot resolve them, but they still make the message ambiguous.
const pending = [...input.entries].filter(
([requestId, route]) => route.kind === "question" && input.routable(requestId, route),
);
const questions = pending.flatMap(([requestId, route]) => {
- const question = route.answerHook?.question ?? route.question;
+ const question = route.workflowAsk?.question ?? route.question;
return question !== undefined ? [{ requestId, ...question }] : [];
});
if (questions.length === 0) return none;
@@ -270,15 +308,8 @@ function resolveMessageAgainstQuestions(input: {
pending.length === 1 && only !== undefined && typeof input.payload.message === "string"
? resolveTextToResponse(input.payload.message, only)
: undefined;
- if (answer !== undefined) return { consumed: true, dismissedRequestIds: [], responses: [answer] };
-
- return {
- consumed: false,
- dismissedRequestIds: questions
- .filter((question) => question.dismissible === true)
- .map((question) => question.requestId),
- responses: [],
- };
+ if (answer !== undefined) return { consumed: true, responses: [answer] };
+ return none;
}
function batchResolves(input: {
@@ -309,9 +340,3 @@ function sameBatch(
route.batch.requestIds.every((requestId, index) => requestId === input.batch.requestIds[index])
);
}
-
-function toChildInputResponse(response: InputResponse, route: ProxyInputRequest): InputResponse {
- return route.childRequestId === undefined
- ? response
- : { ...response, requestId: route.childRequestId };
-}
diff --git a/packages/eve/src/subagents/parent-notification.test.ts b/packages/eve/src/subagents/parent-notification.test.ts
index ebb064043..16e668b11 100644
--- a/packages/eve/src/subagents/parent-notification.test.ts
+++ b/packages/eve/src/subagents/parent-notification.test.ts
@@ -88,11 +88,10 @@ describe("turn caller notification", () => {
expect(resumeHookMock).not.toHaveBeenCalled();
});
- it("restores task ownership from a local adapter with an opaque reply hook", async () => {
+ it("restores the caller from a local adapter with an opaque reply hook", async () => {
const caller = await resolveInitialTurnCallerStep({
serializedContext: createSerializedContext({
parentContinuationToken: "invocation-reply-hook",
- taskId: "task-1",
}),
});
@@ -100,7 +99,6 @@ describe("turn caller notification", () => {
callId: "call-1",
replyTo: { kind: "hook", token: "invocation-reply-hook" },
subagentName: "research",
- taskId: "task-1",
});
});
@@ -345,7 +343,7 @@ describe("turn caller notification", () => {
});
describe("turn caller binding", () => {
- it("rebinds local adapter forwarding to a non-task continuation caller", async () => {
+ it("rebinds local adapter forwarding to a continuation caller", async () => {
await expect(
bindTurnCallerContextStep({
caller: {
@@ -361,7 +359,6 @@ describe("turn caller binding", () => {
parentContinuationToken: "turn-old",
parentSessionId: "parent",
subagentName: "research",
- taskId: "task-old",
},
},
},
@@ -379,7 +376,7 @@ describe("turn caller binding", () => {
});
});
- it("rebinds remote callback forwarding to a non-task continuation caller", async () => {
+ it("rebinds remote callback forwarding to a continuation caller", async () => {
await expect(
bindTurnCallerContextStep({
caller: {
@@ -402,60 +399,4 @@ describe("turn caller binding", () => {
},
});
});
-
- it("rebinds local adapter forwarding to the current task", async () => {
- const serializedContext = {
- [ChannelKey.name]: {
- kind: SUBAGENT_ADAPTER_KIND,
- state: {
- callId: "call-old",
- parentContinuationToken: "task-old",
- parentSessionId: "parent",
- subagentName: "research",
- },
- },
- };
-
- await expect(
- bindTurnCallerContextStep({
- caller: {
- callId: "call-new",
- replyTo: { kind: "hook", token: "task-new" },
- subagentName: "research",
- taskId: "task-new",
- },
- serializedContext,
- }),
- ).resolves.toMatchObject({
- [ChannelKey.name]: {
- state: { callId: "call-new", parentContinuationToken: "task-new", taskId: "task-new" },
- },
- });
- });
-
- it("rebinds remote callback forwarding to the current task", async () => {
- await expect(
- bindTurnCallerContextStep({
- caller: {
- callId: "call-new",
- replyTo: {
- kind: "callback",
- token: "task-new",
- url: "https://parent.example/eve/v1/callback/task-new",
- },
- subagentName: "research",
- taskId: "task-new",
- },
- serializedContext: {},
- }),
- ).resolves.toEqual({
- [SessionCallbackKey.name]: {
- callId: "call-new",
- subagentName: "research",
- taskId: "task-new",
- token: "task-new",
- url: "https://parent.example/eve/v1/callback/task-new",
- },
- });
- });
});
diff --git a/packages/eve/src/subagents/parent-notification.ts b/packages/eve/src/subagents/parent-notification.ts
index 4027acbcc..6a83ac779 100644
--- a/packages/eve/src/subagents/parent-notification.ts
+++ b/packages/eve/src/subagents/parent-notification.ts
@@ -20,7 +20,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 { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
const log = createLogger("execution.delegated-parent-notification");
@@ -186,7 +185,6 @@ export async function resolveInitialTurnCallerStep(input: {
url: parsed.callback.url,
},
subagentName: parsed.callback.subagentName,
- taskId: parsed.callback.taskId ?? readTaskIdFromInboxToken(parsed.callback.token),
};
}
@@ -200,7 +198,6 @@ export async function resolveInitialTurnCallerStep(input: {
callId: adapter.state.callId,
replyTo: { kind: "hook", token: adapter.state.parentContinuationToken },
subagentName: adapter.state.subagentName,
- taskId: adapter.state.taskId ?? readTaskIdFromInboxToken(adapter.state.parentContinuationToken),
};
}
@@ -224,11 +221,7 @@ export async function bindTurnCallerContextStep(input: {
token: caller.replyTo.token,
url: caller.replyTo.url,
};
- return {
- ...withActivity,
- [SessionCallbackKey.name]:
- caller.taskId === undefined ? callback : { ...callback, taskId: caller.taskId },
- };
+ return { ...withActivity, [SessionCallbackKey.name]: callback };
}
const adapter = withActivity[ChannelKey.name];
@@ -241,14 +234,12 @@ 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,
+ const nextState: SubagentAdapterState = {
+ ...state,
callId: caller.callId,
parentContinuationToken: caller.replyTo.token,
subagentName: caller.subagentName,
};
- if (caller.taskId !== undefined) nextState.taskId = caller.taskId;
return {
...withActivity,
[ChannelKey.name]: {
diff --git a/packages/eve/src/subagents/remote-dispatch.test.ts b/packages/eve/src/subagents/remote-dispatch.test.ts
index 8675f812d..f6064f3cd 100644
--- a/packages/eve/src/subagents/remote-dispatch.test.ts
+++ b/packages/eve/src/subagents/remote-dispatch.test.ts
@@ -176,7 +176,7 @@ describe("startRemoteAgentSession", () => {
.fn()
.mockResolvedValue(
Response.json(
- { ok: true, sessionId: "remote-session", status: "accepted" },
+ { ok: true, protocolVersion: 2, sessionId: "remote-session", status: "accepted" },
{ status: 202 },
),
);
@@ -187,14 +187,7 @@ describe("startRemoteAgentSession", () => {
callbackBaseUrl: "https://caller.example.com",
operationId: "operation-1",
remote: createRemoteAgent(),
- session: {
- agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100000 },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- state: {},
- },
+ session: { continuationToken: "eve:parent-token" },
});
expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toMatchObject({
@@ -209,6 +202,7 @@ describe("startRemoteAgentSession", () => {
Response.json(
{
ok: true,
+ protocolVersion: 2,
sessionId: "accepted-child",
status: "accepted",
},
@@ -237,14 +231,7 @@ describe("startRemoteAgentSession", () => {
baggage: "eve.conversation.id=operator-id,vendor=value",
},
},
- session: {
- agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100000 },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- state: {},
- },
+ session: { continuationToken: "eve:parent-token" },
};
await expect(startRemoteAgentSession(input)).resolves.toEqual({
@@ -270,6 +257,7 @@ describe("startRemoteAgentSession", () => {
new Response(
JSON.stringify({
ok: true,
+ protocolVersion: 2,
sessionId: "remote-session",
status: "accepted",
}),
@@ -285,21 +273,7 @@ describe("startRemoteAgentSession", () => {
...createRemoteAgent(),
headers: { Traceparent: "00-authored", "x-static": "yes" },
},
- session: {
- agent: {
- modelReference: { id: "mock/test" },
- system: "",
- tools: [],
- },
- compaction: {
- recentWindowSize: 10,
- threshold: 100000,
- },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- state: {},
- },
+ session: { continuationToken: "eve:parent-token" },
parent: {
lineage: {
callId: "call-remote",
@@ -345,6 +319,7 @@ describe("startRemoteAgentSession", () => {
"find the marker",
].join("\n"),
capabilities: {},
+ protocolVersion: 2,
});
expect(
readForwardedParentSessionBaggage(
@@ -358,42 +333,6 @@ 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",
- 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",
- parent: { continuationToken: "invocation-reply" },
- });
-
- 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()
@@ -407,14 +346,7 @@ describe("startRemoteAgentSession", () => {
action: createAction(),
callbackBaseUrl: "https://caller.example.com",
remote: createRemoteAgent(),
- session: {
- agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100000 },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- state: {},
- },
+ session: { continuationToken: "eve:parent-token" },
}),
).rejects.toThrow("create-session response was invalid");
});
@@ -430,21 +362,7 @@ describe("startRemoteAgentSession", () => {
action: createAction(),
callbackBaseUrl: "https://caller.example.com",
remote: createRemoteAgent(),
- session: {
- agent: {
- modelReference: { id: "mock/test" },
- system: "",
- tools: [],
- },
- compaction: {
- recentWindowSize: 10,
- threshold: 100000,
- },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- state: {},
- },
+ session: { continuationToken: "eve:parent-token" },
}),
).rejects.toThrow("create-session response was invalid");
});
@@ -454,6 +372,7 @@ describe("startRemoteAgentSession", () => {
new Response(
JSON.stringify({
ok: true,
+ protocolVersion: 2,
sessionId: "remote-session",
status: "accepted",
}),
@@ -469,13 +388,7 @@ describe("startRemoteAgentSession", () => {
...createRemoteAgent(),
url: "https://remote.example.com/eve/researcher",
},
- session: {
- agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100000 },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- },
+ session: { continuationToken: "eve:parent-token" },
});
expect(fetchMock).toHaveBeenCalledWith(
@@ -489,6 +402,7 @@ describe("startRemoteAgentSession", () => {
new Response(
JSON.stringify({
ok: true,
+ protocolVersion: 2,
sessionId: "remote-session",
status: "accepted",
}),
@@ -508,14 +422,7 @@ describe("startRemoteAgentSession", () => {
action: { ...action, input: { ...action.input, outputSchema } },
callbackBaseUrl: "https://caller.example.com",
remote: createRemoteAgent(),
- session: {
- agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100000 },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- state: {},
- },
+ session: { continuationToken: "eve:parent-token" },
});
const body = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string);
@@ -531,6 +438,7 @@ describe("startRemoteAgentSession", () => {
new Response(
JSON.stringify({
ok: true,
+ protocolVersion: 2,
sessionId: "remote-session",
status: "accepted",
}),
@@ -546,14 +454,7 @@ describe("startRemoteAgentSession", () => {
action: { ...action, input: { ...action.input, outputSchema: {} } },
callbackBaseUrl: "https://caller.example.com",
remote: createRemoteAgent(),
- session: {
- agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100000 },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- state: {},
- },
+ session: { continuationToken: "eve:parent-token" },
});
const body = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string);
@@ -565,6 +466,7 @@ describe("startRemoteAgentSession", () => {
new Response(
JSON.stringify({
ok: true,
+ protocolVersion: 2,
sessionId: "remote-session",
status: "accepted",
}),
@@ -577,13 +479,7 @@ describe("startRemoteAgentSession", () => {
action: createAction(),
callbackBaseUrl: "https://caller.example.com",
remote: createRemoteAgent(),
- session: {
- agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100000 },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- },
+ session: { continuationToken: "eve:parent-token" },
parent: { continuationToken: "turn-inbox" },
});
@@ -601,6 +497,7 @@ describe("startRemoteAgentSession", () => {
new Response(
JSON.stringify({
ok: true,
+ protocolVersion: 2,
sessionId: "remote-session",
status: "accepted",
}),
@@ -613,21 +510,7 @@ describe("startRemoteAgentSession", () => {
action: createAction(),
callbackBaseUrl: "https://caller.example.com",
remote: createRemoteAgent(),
- session: {
- agent: {
- modelReference: { id: "mock/test" },
- system: "",
- tools: [],
- },
- compaction: {
- recentWindowSize: 10,
- threshold: 100000,
- },
- continuationToken: "eve:parent-token",
- history: [],
- sessionId: "parent-session",
- state: {},
- },
+ session: { continuationToken: "eve:parent-token" },
});
expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toEqual(
@@ -667,6 +550,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {
return new Response(
JSON.stringify({
ok: true,
+ protocolVersion: 2,
sessionId: "remote-session",
status: "accepted",
}),
@@ -846,6 +730,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {
new Response(
JSON.stringify({
ok: true,
+ protocolVersion: 2,
sessionId: "remote-session",
status: "accepted",
}),
@@ -884,6 +769,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {
new Response(
JSON.stringify({
ok: true,
+ protocolVersion: 2,
sessionId: "remote-session",
status: "accepted",
}),
@@ -1172,22 +1058,6 @@ describe("cancelRemoteAgentTurn", () => {
);
});
- it("forwards cancellation of a yielded child's background tasks", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValue(
- Response.json({ ok: true, sessionId: "child-1", status: "accepted" }, { status: 202 }),
- );
- vi.stubGlobal("fetch", fetchMock);
-
- await cancelRemoteAgentTurn({ remote: createRemoteAgent(), sessionId: "child-1", tasks: true });
-
- expect(fetchMock).toHaveBeenCalledWith(
- "https://remote.example.com/eve/v1/session/child-1/cancel",
- expect.objectContaining({ body: JSON.stringify({ tasks: true }), method: "POST" }),
- );
- });
-
it("preserves a prefixed remote base path on cancel-turn requests", async () => {
const fetchMock = vi
.fn()
diff --git a/packages/eve/src/subagents/remote-dispatch.ts b/packages/eve/src/subagents/remote-dispatch.ts
index 6b1e7060f..9d06e6192 100644
--- a/packages/eve/src/subagents/remote-dispatch.ts
+++ b/packages/eve/src/subagents/remote-dispatch.ts
@@ -1,7 +1,14 @@
+import { FatalError } from "#compiled/@workflow/core/index.js";
import { z } from "#compiled/zod/index.js";
import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";
import { ResetResponseSchema, type ResetResponse } from "#protocol/reset-session.js";
import { AgentHandleError } from "#protocol/agent-handle-error.js";
+import {
+ REMOTE_AGENT_PROTOCOL_MISMATCH,
+ REMOTE_AGENT_PROTOCOL_VERSION,
+ formatRemoteAgentProtocolMismatch,
+ readRemoteAgentProtocolVersion,
+} from "#protocol/remote-agent-protocol.js";
import {
createEveCallbackRoutePath,
createEveSessionCancelRoutePath,
@@ -33,7 +40,6 @@ import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agen
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";
import type { JsonObject } from "#shared/json.js";
-import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
import {
writeForwardedAudienceBaggage,
writeForwardedParentSessionBaggage,
@@ -43,6 +49,7 @@ import { writeConversationBaggage } from "#tracing/conversation-context.js";
const CreateSessionResponseSchema = z.object({
ok: z.literal(true),
+ protocolVersion: z.number().optional(),
sessionId: z.string().min(1),
status: z.literal("accepted"),
});
@@ -80,8 +87,7 @@ export async function startRemoteAgentSession(input: {
readonly lineage?: SubagentParentContext["lineage"];
};
readonly remote: ResolvedRuntimeRemoteAgentNode;
- readonly session: HarnessSession;
- readonly taskId?: string;
+ readonly session: Pick<HarnessSession, "continuationToken">;
}): Promise<RemoteAgentSessionCoordinates> {
const callbackToken = input.parent?.continuationToken ?? input.session.continuationToken;
if (!callbackToken) {
@@ -97,7 +103,6 @@ export async function startRemoteAgentSession(input: {
callback: {
callId: string;
subagentName: string;
- taskId?: string;
token: string;
url: string;
};
@@ -106,12 +111,12 @@ export async function startRemoteAgentSession(input: {
message: string;
operationId?: string;
outputSchema?: object;
+ protocolVersion: number;
} = {
capabilities: {},
callback: {
callId: input.action.callId,
subagentName: input.action.remoteAgentName,
- taskId: input.taskId ?? readTaskIdFromInboxToken(callbackToken),
token: callbackToken,
url: createWorkflowCallbackUrl(
input.callbackBaseUrl,
@@ -123,6 +128,7 @@ export async function startRemoteAgentSession(input: {
remote: input.remote,
}),
outputSchema: normalizeRequestedOutputSchema(input.action.input.outputSchema),
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
};
if (input.activityObserver !== undefined) requestBody.activityObserver = input.activityObserver;
if (forwardedPrincipal !== undefined) {
@@ -165,6 +171,7 @@ export async function startRemoteAgentSession(input: {
});
if (!response.ok) {
+ await throwIfRemoteAgentProtocolMismatch(response, input.action.remoteAgentName);
throw new Error(
`Remote agent "${input.action.remoteAgentName}" create-session request failed with HTTP ${response.status}.`,
);
@@ -185,10 +192,30 @@ export async function startRemoteAgentSession(input: {
`Remote agent "${input.action.remoteAgentName}" create-session response was invalid.`,
);
}
+ const receiverVersion = readRemoteAgentProtocolVersion(parsed.data.protocolVersion);
+ if (receiverVersion !== REMOTE_AGENT_PROTOCOL_VERSION) {
+ throw new FatalError(
+ formatRemoteAgentProtocolMismatch({ name: input.action.remoteAgentName, receiverVersion }),
+ );
+ }
return { sessionId: parsed.data.sessionId };
}
+/** A receiver that speaks another protocol version rejects the create with its own version. */
+async function throwIfRemoteAgentProtocolMismatch(response: Response, name: string): Promise<void> {
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch {
+ return;
+ }
+ if (body === null || typeof body !== "object") return;
+ if (Reflect.get(body, "code") !== REMOTE_AGENT_PROTOCOL_MISMATCH) return;
+ const receiverVersion = readRemoteAgentProtocolVersion(Reflect.get(body, "protocolVersion"));
+ throw new FatalError(formatRemoteAgentProtocolMismatch({ name, receiverVersion }));
+}
+
function buildForwardedTraceAssertion(input: {
readonly forwardedPrincipal: ForwardedPrincipal | undefined;
readonly originAudience: ChannelAudience | undefined;
@@ -216,10 +243,9 @@ export async function continueRemoteAgentSession(input: {
readonly activityObserver?: ActivityObserverConfig;
/** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */
readonly auth: SessionAuthContext | null;
- readonly callback?: {
+ readonly callback: {
readonly callId: string;
readonly subagentName: string;
- readonly taskId?: string;
readonly token: string;
readonly url: string;
};
@@ -356,16 +382,11 @@ export async function cancelRemoteAgentTurn(input: {
readonly headers?: Record<string, string>;
readonly remote: Pick<ResolvedRuntimeRemoteAgentNode, "auth" | "headers" | "name" | "url">;
readonly sessionId: string;
- readonly taskId?: string;
- readonly tasks?: boolean;
readonly turnId?: string;
}): Promise<CancelTurnResult> {
const headers = input.headers ?? (await resolveRemoteAgentRequestHeaders(input.remote));
const response = await fetch(createRemoteAgentCancelTurnUrl(input.remote, input.sessionId), {
- body:
- input.turnId === undefined && input.taskId === undefined && input.tasks === undefined
- ? undefined
- : JSON.stringify({ taskId: input.taskId, tasks: input.tasks, turnId: input.turnId }),
+ body: input.turnId === undefined ? undefined : JSON.stringify({ turnId: input.turnId }),
headers,
method: "POST",
});
@@ -418,6 +439,7 @@ function setHeader(headers: Record<string, string>, name: string, value: string
/** Retires one exact remote child session through eve's authenticated reset route. */
export async function resetRemoteAgentSession(input: {
readonly headers?: Record<string, string>;
+ readonly reason?: string;
readonly remote: Pick<ResolvedRuntimeRemoteAgentNode, "auth" | "headers" | "name" | "url">;
readonly sessionId: string;
}): Promise<ResetResponse> {
@@ -425,7 +447,7 @@ export async function resetRemoteAgentSession(input: {
const response = await fetch(
createRemoteAgentRouteUrl(input.remote.url, createEveSessionResetRoutePath(input.sessionId)),
{
- body: JSON.stringify({ reason: "Parent session ended" }),
+ body: JSON.stringify({ reason: input.reason ?? "Parent session ended" }),
headers: { "content-type": "application/json", ...headers },
method: "POST",
},
@@ -459,7 +481,7 @@ export function resolveRemoteAgentForAction(input: {
const definition = registered?.definition;
if (input.dynamicRemoteAgent !== undefined) {
if (definition === undefined) {
- throw new Error(`Missing remote agent "${input.remoteAgentName}" in runtime registry.`);
+ throw new FatalError(`Missing remote agent "${input.remoteAgentName}" in runtime registry.`);
}
const credentials = resolveDynamicRemoteAgentCredentials(input.dynamicRemoteAgent);
const config = input.dynamicRemoteAgent;
@@ -499,7 +521,7 @@ export function resolveRemoteAgentForAction(input: {
return remote;
}
if (definition?.kind !== "remote") {
- throw new Error(`Missing remote agent "${input.remoteAgentName}" in runtime registry.`);
+ throw new FatalError(`Missing remote agent "${input.remoteAgentName}" in runtime registry.`);
}
return definition;
}
diff --git a/packages/eve/src/subagents/start-local.test.ts b/packages/eve/src/subagents/start-local.test.ts
index eae616fe1..ce74aebdd 100644
--- a/packages/eve/src/subagents/start-local.test.ts
+++ b/packages/eve/src/subagents/start-local.test.ts
@@ -73,7 +73,7 @@ describe("startLocalSubagent", () => {
sink: { url: "https://parent.example/activity", version: 1 as const },
workIdentity: {
id: "work:task",
- kind: "task" as const,
+ kind: "subagent" as const,
name: "slack",
parentId: "work:root",
rootSessionId: "root-session",
diff --git a/packages/eve/src/subagents/start-local.ts b/packages/eve/src/subagents/start-local.ts
index 9e9e79206..8d55195e1 100644
--- a/packages/eve/src/subagents/start-local.ts
+++ b/packages/eve/src/subagents/start-local.ts
@@ -3,6 +3,7 @@ import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch
import { ContextContainer, contextStorage } from "#context/container.js";
import type { LocalDevRequestProvenance } from "#context/keys.js";
import { buildSubagentRunInput, type SubagentInputSource } from "#subagents/tool.js";
+import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";
import { createWorkflowRuntime, waitForCommandHookOwner } from "#execution/workflow-runtime.js";
import { SUBAGENT_START_FAILED } from "#subagents/agent-handle-errors.js";
import { createLogger, logError } from "#internal/logging.js";
@@ -37,7 +38,6 @@ export async function startLocalSubagent(input: {
readonly sandboxSessionId: string;
readonly session: RuntimeSession;
readonly source: SubagentInputSource;
- readonly taskId?: string;
}): Promise<DispatchOutcome> {
const { action, source } = input;
const childRuntime = createWorkflowRuntime({
@@ -50,17 +50,17 @@ export async function startLocalSubagent(input: {
auth: input.auth,
capabilities: input.capabilities,
channelMetadata: input.channelMetadata,
+ continuationKey: `${input.session.sessionId}:${action.callId}`,
inheritedConversation: input.inheritedConversation,
- fanoutSize: input.fanoutSize,
initiatorAuth: input.initiatorAuth,
graph: input.bundle.graph,
+ limits: resolveRemainingSessionTokenLimits(input.session, input.fanoutSize),
parent: input.parent,
activityObserver: input.activityObserver,
sandboxSessionId: input.sandboxSessionId,
session: input.session,
selfAgent: source.type === "runtime",
source,
- taskId: input.taskId,
});
const targetKind = source.type === "runtime" ? ("agent/self" as const) : ("agent/local" as const);
diff --git a/packages/eve/src/subagents/start-remote.test.ts b/packages/eve/src/subagents/start-remote.test.ts
index d5e7254e3..4fef9932d 100644
--- a/packages/eve/src/subagents/start-remote.test.ts
+++ b/packages/eve/src/subagents/start-remote.test.ts
@@ -12,13 +12,11 @@ vi.mock("#subagents/remote-dispatch.js", () => ({
import { startRemoteSubagent } from "#subagents/start-remote.js";
-const taskObserver = {
+const parentObserver = {
sink: { url: "https://parent.example/activity", version: 1 as const },
workIdentity: {
- id: "work:task",
- kind: "task" as const,
- name: "research-task",
- parentId: "work:root",
+ id: "work:root",
+ kind: "root-turn" as const,
rootSessionId: "root-session",
rootTurnId: "root-turn",
},
@@ -27,7 +25,7 @@ const taskObserver = {
describe("startRemoteSubagent", () => {
beforeEach(() => vi.clearAllMocks());
- it("derives a child identity when no task-owned observer is supplied", async () => {
+ it("derives a child identity beneath the parent observer", async () => {
await startRemoteSubagent({
action: {
callId: "call-remote",
@@ -38,7 +36,7 @@ describe("startRemoteSubagent", () => {
nodeId: "remoteAgents/research",
remoteAgentName: "research",
},
- activityObserver: taskObserver,
+ activityObserver: parentObserver,
auth: null,
batchEvent: { sequence: 0, turnId: "parent-turn" },
bundle: { subagentRegistry: { subagentsByNodeId: new Map() } },
@@ -58,23 +56,21 @@ describe("startRemoteSubagent", () => {
traceContext: undefined,
},
session: { sessionId: "parent-session" },
- taskId: "task-1",
} as never);
expect(startRemoteAgentSession).toHaveBeenCalledWith(
expect.objectContaining({
activityObserver: {
- sink: taskObserver.sink,
+ sink: parentObserver.sink,
workIdentity: expect.objectContaining({
callId: "call-remote",
kind: "remote-agent",
name: "research",
- parentId: taskObserver.workIdentity.id,
+ parentId: parentObserver.workIdentity.id,
rootSessionId: "root-session",
rootTurnId: "root-turn",
}),
},
- taskId: "task-1",
}),
);
});
diff --git a/packages/eve/src/subagents/start-remote.ts b/packages/eve/src/subagents/start-remote.ts
index d8cb95345..125ae1cde 100644
--- a/packages/eve/src/subagents/start-remote.ts
+++ b/packages/eve/src/subagents/start-remote.ts
@@ -26,22 +26,17 @@ export async function startRemoteSubagent(input: {
readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];
readonly parent: SubagentParentContext;
readonly activityObserver?: Parameters<typeof startRemoteAgentSession>[0]["activityObserver"];
- /** Already resolved task-owned work; do not derive another child identity. */
- readonly taskActivityObserver?: Parameters<typeof startRemoteAgentSession>[0]["activityObserver"];
readonly session: RuntimeSession;
- readonly taskId?: string;
}): Promise<DispatchOutcome> {
const { action } = input;
- const activityObserver =
- input.taskActivityObserver ??
- deriveChildActivityObserverConfig({
- activityObserver: input.activityObserver,
- callId: action.callId,
- kind: "remote-agent",
- name: action.remoteAgentName,
- parentSessionId: input.session.sessionId,
- parentTurnId: input.parent.lineage.turn.id,
- });
+ const activityObserver = deriveChildActivityObserverConfig({
+ activityObserver: input.activityObserver,
+ callId: action.callId,
+ kind: "remote-agent",
+ name: action.remoteAgentName,
+ parentSessionId: input.session.sessionId,
+ parentTurnId: input.parent.lineage.turn.id,
+ });
// Preflight resolution failures happen before ownership exists, so they
// reject without touching the handle store.
@@ -96,7 +91,6 @@ export async function startRemoteSubagent(input: {
activityObserver,
remote: resolvedRemote,
session: input.session,
- taskId: input.taskId,
});
const address = {
callbackBaseUrl,
diff --git a/packages/eve/src/subagents/tool.test.ts b/packages/eve/src/subagents/tool.test.ts
index 2bc794c98..837676c67 100644
--- a/packages/eve/src/subagents/tool.test.ts
+++ b/packages/eve/src/subagents/tool.test.ts
@@ -51,11 +51,17 @@ function makeParent(
};
}
+const NO_LIMITS = { maxInputTokensPerSession: false, maxOutputTokensPerSession: false } as const;
+
function buildRuntimeSubagentRunInput(
- input: Omit<BuildSubagentRunInput, "selfAgent" | "source"> & { readonly selfAgent?: boolean },
+ input: Omit<BuildSubagentRunInput, "continuationKey" | "limits" | "selfAgent" | "source"> & {
+ readonly selfAgent?: boolean;
+ },
): ReturnType<typeof buildSubagentRunInput> {
return buildSubagentRunInput({
...input,
+ continuationKey: `${input.session.sessionId}:${input.action.callId}`,
+ limits: NO_LIMITS,
selfAgent: input.selfAgent ?? false,
source: { type: "runtime" },
});
@@ -139,27 +145,6 @@ describe("buildSubagentRunInput", () => {
});
});
- it("retains a background task identity beside an opaque parent reply hook", () => {
- const { runInput } = buildRuntimeSubagentRunInput({
- action: makeAction(),
- auth: null,
- initiatorAuth: null,
- session: makeSession(),
- taskId: "task-1",
- parent: makeParent(
- makeSession(),
- { id: "turn-0", sequence: 0 },
- { continuationToken: "invocation-reply-hook" },
- ),
- });
-
- 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",
@@ -237,28 +222,6 @@ describe("buildSubagentRunInput", () => {
});
});
- it("threads inherited limits through the child run input", () => {
- const { runInput } = buildRuntimeSubagentRunInput({
- action: makeAction(),
- auth: null,
- initiatorAuth: null,
- session: {
- ...makeSession(),
- },
- parent: makeParent(
- {
- ...makeSession(),
- },
- { id: "turn-0", sequence: 0 },
- ),
- });
-
- expect(runInput.limits).toEqual({
- maxInputTokensPerSession: false,
- maxOutputTokensPerSession: false,
- });
- });
-
it("threads outputSchema from action input to RunInput", () => {
const schema = { type: "object", properties: { result: { type: "string" } } };
const action: RuntimeSubagentDispatchRequest = {
@@ -308,7 +271,9 @@ describe("buildSubagentRunInput", () => {
description: "Runtime action event description.",
},
auth: null,
+ continuationKey: "parent-session:call-1",
initiatorAuth: null,
+ limits: NO_LIMITS,
selfAgent: false,
session: makeSession(),
source: { description: "Local delegate subagent description.", type: "local" },
diff --git a/packages/eve/src/subagents/tool.ts b/packages/eve/src/subagents/tool.ts
index e14081392..c54a2fd92 100644
--- a/packages/eve/src/subagents/tool.ts
+++ b/packages/eve/src/subagents/tool.ts
@@ -15,7 +15,6 @@ import type {
import type { HarnessSession } from "#harness/types.js";
import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";
import { mintSubagentContinuationToken } from "#execution/session.js";
-import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";
import type { ConversationContext } from "#shared/conversation-context.js";
export type SubagentInputSource =
@@ -69,15 +68,10 @@ export function buildSubagentRunInput(input: {
*/
readonly capabilities?: SessionCapabilities;
readonly channelMetadata?: ChannelInstrumentationProjection;
+ /** Replay-stable key the child's continuation token derives from. */
+ readonly continuationKey: string;
/** Parent's immutable conversation classification. */
readonly inheritedConversation?: ConversationContext;
- /**
- * Number of local subagent calls dispatched in this batch. The parent's
- * remaining token quota is split evenly across them so parallel children
- * are collectively, not individually, bounded by it. Remote agents run
- * under their own deployment's limits and are not counted.
- */
- readonly fanoutSize?: number;
readonly initiatorAuth: SessionAuthContext | null;
/**
* Runtime graph used to detect whether this declared child selected the
@@ -87,12 +81,12 @@ export function buildSubagentRunInput(input: {
/** Durable session identity of the sandbox currently used by the parent. */
readonly sandboxSessionId?: string;
readonly selfAgent: boolean;
+ /** Session token limits the child inherits. */
+ readonly limits: RunSessionLimits;
readonly parent: SubagentParentContext;
readonly activityObserver?: ActivityObserverConfig;
- readonly session: HarnessSession;
+ readonly session: Pick<HarnessSession, "continuationToken" | "sandboxState" | "sessionId">;
readonly source: SubagentInputSource;
- /** Owning task when this child starts from a background workflow tool. */
- readonly taskId?: string;
}): SubagentRunInputBuild {
const {
action,
@@ -105,13 +99,7 @@ export function buildSubagentRunInput(input: {
source,
} = input;
- const childContinuationToken = mintSubagentContinuationToken(
- `${session.sessionId}:${action.callId}`,
- );
-
- const inheritedLimits: {
- -readonly [K in keyof RunSessionLimits]: RunSessionLimits[K];
- } = resolveRemainingSessionTokenLimits(session, input.fanoutSize);
+ const childContinuationToken = mintSubagentContinuationToken(input.continuationKey);
const requestedOutputSchema = normalizeRequestedOutputSchema(action.input.outputSchema);
const adapterState: Record<string, unknown> = {
callId: action.callId,
@@ -119,7 +107,6 @@ export function buildSubagentRunInput(input: {
parentSessionId: session.sessionId,
subagentName: action.subagentName,
};
- if (input.taskId !== undefined) adapterState.taskId = input.taskId;
const reusesOwnerSandbox =
input.graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox?.definition.kind ===
"parent" || input.selfAgent;
@@ -150,14 +137,12 @@ export function buildSubagentRunInput(input: {
}),
outputSchema: requestedOutputSchema,
},
- limits: inheritedLimits,
+ limits: input.limits,
conversationId: input.parent.conversationId,
parent: input.parent.lineage,
parentTraceContext: input.parent.traceContext,
activityObserver: input.activityObserver,
};
- if (input.taskId !== undefined) runInput.taskId = input.taskId;
-
return { childContinuationToken, runInput };
}
diff --git a/packages/eve/src/tasks/delivery-context.test.ts b/packages/eve/src/tasks/delivery-context.test.ts
deleted file mode 100644
index 1818c3ab9..000000000
--- a/packages/eve/src/tasks/delivery-context.test.ts
+++ /dev/null
@@ -1,307 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import type { SessionStateMap } from "#harness/types.js";
-import { EMPTY_DELIVERY_SENTINEL } from "#shared/empty-delivery.js";
-import {
- getBackgroundTaskDelivery,
- markBackgroundTaskStepInput,
- resolveInitiatingTaskContext,
- resolveTaskDeliveryContext,
- TASK_DELIVERY_CONTEXT_LABEL,
- TASK_DELIVERY_INITIATING_INSTRUCTION,
- TASK_DELIVERY_SETTLED_INSTRUCTION,
-} from "#tasks/delivery-context.js";
-import type { BackgroundWorkflowToolRun } from "#harness/workflow-tool-runs.js";
-import type { TaskView } from "#tasks/types.js";
-
-const metadata = { kind: "report-probe", name: "report_probe" } as const;
-
-describe("task delivery instructions", () => {
- it("initiating instruction requires one launch acknowledgement", () => {
- expect(TASK_DELIVERY_INITIATING_INSTRUCTION).toContain(TASK_DELIVERY_CONTEXT_LABEL);
- expect(TASK_DELIVERY_INITIATING_INSTRUCTION).toContain("runtime-authored");
- expect(TASK_DELIVERY_INITIATING_INSTRUCTION).toContain(
- "continue independently after this turn",
- );
- expect(TASK_DELIVERY_INITIATING_INSTRUCTION).toContain(
- "including starting any remaining background work",
- );
- expect(TASK_DELIVERY_INITIATING_INSTRUCTION).toContain(
- "When no further tool calls are needed in this turn",
- );
- expect(TASK_DELIVERY_INITIATING_INSTRUCTION).toContain("one brief user-facing acknowledgement");
- expect(TASK_DELIVERY_INITIATING_INSTRUCTION).not.toContain(EMPTY_DELIVERY_SENTINEL);
- });
-
- it("settled instruction unconditionally forbids the sentinel and requires one combined response", () => {
- expect(TASK_DELIVERY_SETTLED_INSTRUCTION).toContain(TASK_DELIVERY_CONTEXT_LABEL);
- expect(TASK_DELIVERY_SETTLED_INSTRUCTION).toContain("runtime-authored");
- expect(TASK_DELIVERY_SETTLED_INSTRUCTION).toContain("terminal output");
- expect(TASK_DELIVERY_SETTLED_INSTRUCTION).toContain(
- `Do not reply with ${EMPTY_DELIVERY_SENTINEL}`,
- );
- expect(TASK_DELIVERY_SETTLED_INSTRUCTION).toContain("one user-facing response");
- expect(TASK_DELIVERY_SETTLED_INSTRUCTION).not.toContain("When no task");
- });
-});
-
-describe("getBackgroundTaskDelivery", () => {
- it("recognizes task-owned deliveries independently of their payload", () => {
- expect(
- getBackgroundTaskDelivery({
- kind: "deliver",
- payloads: [{ message: "Background task task_1 completed." }],
- taskDeliveryId: "task_1:ready:completed",
- }),
- ).toMatchObject({ taskDeliveryId: "task_1:ready:completed" });
- expect(getBackgroundTaskDelivery({ kind: "deliver", payloads: [{ message: "Hello." }] })).toBe(
- undefined,
- );
- });
-
- it("marks task-produced input before delivery results are coalesced", () => {
- expect(markBackgroundTaskStepInput({ message: "Task completed." })).toMatchObject({
- frameworkMessageKind: "execution.background_task",
- message: "Task completed.",
- });
- expect(markBackgroundTaskStepInput({ context: ["Task state"] })).toEqual({
- context: ["Task state"],
- });
- });
-});
-
-describe("resolveInitiatingTaskContext", () => {
- it("projects the active turn's accepted background tasks as initiating", () => {
- expect(
- resolveInitiatingTaskContext({
- state: taskState([
- taskEntry("task_1", "turn_1"),
- {
- ...taskEntry("task_2", "turn_2"),
- task: { ...taskEntry("task_2", "turn_2").task, cohortId: "task_1" },
- },
- ]),
- turnId: "turn_1",
- }),
- ).toEqual({
- context:
- '[Task state]\n{"tasks":[{"name":"report_probe","status":"pending","taskId":"task_1"}]}',
- phase: "initiating",
- });
- });
-
- it("recognizes an indexed invocation without an executor binding", () => {
- expect(
- resolveInitiatingTaskContext({
- state: taskState([taskEntry("task_1", "turn_1")]),
- turnId: "turn_1",
- }),
- ).toMatchObject({ phase: "initiating" });
- });
-});
-
-describe("resolveTaskDeliveryContext", () => {
- it("auto retains earlier outputs and pending siblings for a later combined report", () => {
- const first = {
- taskId: "task_1",
- status: "completed",
- metadata,
- lastOutput: { type: "result", data: "first" },
- } as const;
- const second = {
- ...first,
- taskId: "task_2",
- lastOutput: { type: "result", data: "second" },
- } as const;
- const state = taskState([
- taskEntry("task_1", "turn_1", first),
- {
- ...taskEntry("task_2", "turn_2", second),
- task: { ...taskEntry("task_2", "turn_2", second).task, cohortId: "task_1" },
- },
- {
- ...taskEntry("task_3", "turn_3"),
- task: { ...taskEntry("task_3", "turn_3").task, cohortId: "task_1" },
- },
- ]);
- const result = resolveTaskDeliveryContext({
- state,
- taskDeliveryIds: ["task_2:ready:completed"],
- taskDeliveryPolicy: "auto",
- });
- expect(result?.phase).toBe("pending");
- expect(result?.rootTurnId).toBe("turn_2");
- expect(JSON.parse(result!.context.slice(TASK_DELIVERY_CONTEXT_LABEL.length))).toEqual({
- tasks: [
- { name: metadata.name, output: first.lastOutput, status: "completed", taskId: "task_1" },
- { name: metadata.name, output: second.lastOutput, status: "completed", taskId: "task_2" },
- { name: metadata.name, status: "pending", taskId: "task_3" },
- ],
- });
- const batch = resolveTaskDeliveryContext({
- state,
- taskDeliveryIds: ["task_2:ready:completed", "task_1:ready:completed"],
- taskDeliveryPolicy: "auto",
- });
- expect(batch).toEqual(result);
- });
-
- it("auto keeps an advisory wake pending until the delivered task is terminal", () => {
- const result = resolveTaskDeliveryContext({
- state: taskState([taskEntry("task_1", "turn_1")]),
- taskDeliveryIds: ["task_1:message:1"],
- taskDeliveryPolicy: "auto",
- });
- expect(result?.phase).toBe("pending");
- });
-
- it("includes completed siblings while a cross-turn cohort is pending", () => {
- const completed = {
- lastOutput: { data: { result: "first" }, type: "result" },
- metadata,
- status: "completed",
- taskId: "task_1",
- } satisfies TaskView;
- const state = taskState([
- taskEntry("task_1", "turn_1", completed),
- {
- ...taskEntry("task_2", "turn_2"),
- task: { ...taskEntry("task_2", "turn_2").task, cohortId: "task_1" },
- },
- taskEntry("task_3", "turn_1"),
- ]);
-
- expect(
- resolveTaskDeliveryContext({
- state,
- taskDeliveryIds: ["task_1:ready:completed"],
- taskDeliveryPolicy: "cohort",
- }),
- ).toEqual({
- context:
- '[Task state]\n{"tasks":[{"name":"report_probe","status":"completed","taskId":"task_1"},{"name":"report_probe","status":"pending","taskId":"task_2"}]}',
- phase: "pending",
- rootTurnId: "turn_1",
- });
- });
-
- it("includes every output once the parent has received the whole terminal cohort", () => {
- const first = {
- lastOutput: { data: { result: "first" }, type: "result" },
- metadata,
- status: "completed",
- taskId: "task_1",
- } satisfies TaskView;
- const second = {
- lastOutput: { data: { result: "second" }, type: "result" },
- metadata,
- status: "completed",
- taskId: "task_2",
- } satisfies TaskView;
-
- expect(
- resolveTaskDeliveryContext({
- state: taskState([
- taskEntry("task_1", "turn_1", first),
- {
- ...taskEntry("task_2", "turn_2", second),
- task: { ...taskEntry("task_2", "turn_2", second).task, cohortId: "task_1" },
- },
- ]),
- taskDeliveryIds: ["task_2:ready:completed"],
- taskDeliveryPolicy: "cohort",
- }),
- ).toEqual({
- context:
- '[Task state]\n{"tasks":[{"name":"report_probe","output":{"data":{"result":"first"},"type":"result"},"status":"completed","taskId":"task_1"},{"name":"report_probe","output":{"data":{"result":"second"},"type":"result"},"status":"completed","taskId":"task_2"}]}',
- phase: "settled",
- rootTurnId: "turn_2",
- });
- });
-
- it("includes failure and cancellation in the terminal cohort, but not an earlier settled report", () => {
- const failed: TaskView = {
- metadata,
- taskId: "task_failed",
- status: "failed",
- lastOutput: { type: "error", data: "Worker failed" },
- };
- const cancelled: TaskView = { metadata, taskId: "task_cancelled", status: "cancelled" };
- const previous: TaskView = {
- metadata,
- taskId: "task_previous",
- status: "completed",
- lastOutput: { type: "result", data: "Already reported" },
- };
- const state = taskState([
- taskEntry("task_previous", "turn_1", previous),
- taskEntry("task_failed", "turn_1", failed),
- {
- ...taskEntry("task_cancelled", "turn_2", cancelled),
- task: { ...taskEntry("task_cancelled", "turn_2", cancelled).task, cohortId: "task_failed" },
- },
- ]);
- const result = resolveTaskDeliveryContext({
- state,
- taskDeliveryIds: ["task_cancelled:ready:cancelled"],
- taskDeliveryPolicy: "cohort",
- });
- expect(result).toMatchObject({ phase: "settled", rootTurnId: "turn_2" });
- expect(JSON.parse(result!.context.slice(`${TASK_DELIVERY_CONTEXT_LABEL}\n`.length))).toEqual({
- tasks: [
- { name: metadata.name, output: failed.lastOutput, status: "failed", taskId: "task_failed" },
- { name: metadata.name, status: "cancelled", taskId: "task_cancelled" },
- ],
- });
- expect(result!.context).not.toContain("Already reported");
- expect(result!.context).not.toContain("inbox-");
- expect(result!.context).not.toContain("cohortId");
- expect(result!.context).not.toContain("createdByTurnId");
- });
-
- it.each([{ taskDeliveryIds: [] }, { taskDeliveryIds: ["task_unknown:ready:completed"] }])(
- "returns no context for missing or unowned deliveries: $taskDeliveryIds",
- ({ taskDeliveryIds }) => {
- expect(
- resolveTaskDeliveryContext({
- state: taskState([taskEntry("task_1", "turn_1")]),
- taskDeliveryIds,
- taskDeliveryPolicy: "cohort",
- }),
- ).toBeUndefined();
- },
- );
-});
-
-function taskEntry(
- taskId: string,
- createdByTurnId: string,
- outcome?: TaskView,
-): BackgroundWorkflowToolRun {
- return {
- callId: taskId,
- toolName: metadata.name,
- lifetime: "session" as const,
- origin: { turnId: createdByTurnId, stepIndex: 0 },
- address: { runId: `run-${taskId}`, hookToken: `inbox-${taskId}` },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- metadata,
- taskId,
- outcome:
- outcome === undefined
- ? undefined
- : {
- status: outcome.status,
- lastOutput: outcome.lastOutput,
- usage: outcome.usage,
- },
- },
- };
-}
-
-function taskState(tasks: readonly ReturnType<typeof taskEntry>[]): SessionStateMap {
- return {
- "eve.workflowTool": { version: 3, runs: tasks },
- } as SessionStateMap;
-}
diff --git a/packages/eve/src/tasks/delivery-context.ts b/packages/eve/src/tasks/delivery-context.ts
deleted file mode 100644
index 65b2284c2..000000000
--- a/packages/eve/src/tasks/delivery-context.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import type { TaskDeliveryPolicy, DeliverHookPayload } from "#channel/types.js";
-import { markFrameworkStepInput } from "#harness/messages.js";
-import type { SessionStateMap, StepInput } from "#harness/types.js";
-import { EMPTY_DELIVERY_SENTINEL } from "#shared/empty-delivery.js";
-import { getBackgroundTasks, type BackgroundTask } from "#harness/workflow-tool-runs.js";
-import { taskIdOfDelivery } from "#tasks/notification.js";
-
-export const TASK_DELIVERY_CONTEXT_LABEL = "[Task state]";
-
-export const TASK_DELIVERY_INITIATING_INSTRUCTION = `Background task reporting: launch acknowledgement
-The latest ${TASK_DELIVERY_CONTEXT_LABEL} message is runtime-authored and lists background tasks accepted so far from the current turn. They continue independently after this turn.
-
-Continue carrying out the user's request, including starting any remaining background work. When no further tool calls are needed in this turn, send one brief user-facing acknowledgement that the background work has started. Do not wait for results or report results that are not available yet. End the turn after the acknowledgement.`;
-
-export const TASK_DELIVERY_SETTLED_INSTRUCTION = `Background task reporting\nFor this background-task update, the accompanying ${TASK_DELIVERY_CONTEXT_LABEL} message is runtime-authored and lists the settled tasks in this cohort and their available terminal outputs. Report their useful results together in one user-facing response without repeating results already reported. Do not reply with ${EMPTY_DELIVERY_SENTINEL}.`;
-
-export const TASK_DELIVERY_AUTO_INSTRUCTION = `Background task reporting\nFor this background-task update, the accompanying ${TASK_DELIVERY_CONTEXT_LABEL} message is runtime-authored and lists the whole cohort, including pending tasks and every available terminal output. A received result has not necessarily been reported to the user. Report new results only when they are useful independently of unfinished work. When that work settles, combine its results with any previously withheld results. If there is nothing new and useful to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}. Do not repeat results already reported or send an acknowledgement just to say you are waiting.`;
-
-type BackgroundTaskDelivery = DeliverHookPayload & {
- readonly taskDeliveryId: string;
-};
-
-/** Returns task delivery provenance when a child task wakes its parent. */
-export function getBackgroundTaskDelivery(input: unknown): BackgroundTaskDelivery | undefined {
- if (typeof input !== "object" || input === null) return undefined;
- const delivery = input as { readonly kind?: unknown; readonly taskDeliveryId?: unknown };
- return delivery.kind === "deliver" && typeof delivery.taskDeliveryId === "string"
- ? (input as BackgroundTaskDelivery)
- : undefined;
-}
-
-/** Marks a task-produced user message before the harness coalesces delivery results. */
-export function markBackgroundTaskStepInput(input: StepInput): StepInput {
- return input.message === undefined
- ? input
- : markFrameworkStepInput(input, "execution.background_task");
-}
-
-/** Projects the report group without changing the delivered task's activity root. */
-export function resolveTaskDeliveryContext(input: {
- readonly state: SessionStateMap | undefined;
- readonly taskDeliveryIds: readonly string[];
- readonly taskDeliveryPolicy: TaskDeliveryPolicy;
-}):
- | {
- readonly context: string;
- readonly phase: "pending" | "settled";
- readonly rootTurnId: string;
- }
- | undefined {
- const firstDeliveryId = input.taskDeliveryIds[0];
- if (firstDeliveryId === undefined) return undefined;
- const tasks = getBackgroundTasks(input.state);
- const delivered = tasks.get(taskIdOfDelivery(firstDeliveryId));
- if (delivered === undefined) return undefined;
- return {
- ...projectTaskCohort(
- tasks.query({ cohortId: delivered.cohortId }),
- input.taskDeliveryPolicy === "auto",
- ),
- rootTurnId: delivered.turnId,
- };
-}
-
-/** Returns model context for durable tasks launched by the active parent turn. */
-export function resolveInitiatingTaskContext(input: {
- readonly state: SessionStateMap | undefined;
- readonly turnId: string;
-}): { readonly context: string; readonly phase: "initiating" } | undefined {
- const tasks = getBackgroundTasks(input.state);
- if (tasks.query({ state: "working", turnId: input.turnId }).length === 0) return undefined;
- return {
- ...projectTaskCohort(tasks.query({ turnId: input.turnId }), false),
- phase: "initiating",
- };
-}
-
-function projectTaskCohort(
- cohort: readonly BackgroundTask[],
- includePartialOutputs: boolean,
-): {
- readonly context: string;
- readonly phase: "pending" | "settled";
-} {
- const settled = cohort.every((task) => task.status !== "working");
- const tasks = cohort.map((task) => ({
- name: task.metadata.name,
- output: settled || includePartialOutputs ? task.lastOutput : undefined,
- // The model-facing projection names unsettled work "pending".
- status: task.status === "working" ? "pending" : task.status,
- taskId: task.taskId,
- }));
-
- return {
- context: `${TASK_DELIVERY_CONTEXT_LABEL}\n${JSON.stringify({ tasks })}`,
- phase: settled ? "settled" : "pending",
- };
-}
diff --git a/packages/eve/src/tasks/delivery-policy.test.ts b/packages/eve/src/tasks/delivery-policy.test.ts
deleted file mode 100644
index 272e347aa..000000000
--- a/packages/eve/src/tasks/delivery-policy.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { CONDITIONAL_DELIVERY_INSTRUCTION } from "#shared/empty-delivery.js";
-import {
- TASK_DELIVERY_AUTO_INSTRUCTION,
- TASK_DELIVERY_INITIATING_INSTRUCTION,
- TASK_DELIVERY_SETTLED_INSTRUCTION,
-} from "#tasks/delivery-context.js";
-import { resolveDeliveryPolicy } from "#tasks/delivery-policy.js";
-
-describe("resolveDeliveryPolicy", () => {
- it.each([
- ["scheduled launch", "initiating", true, true, CONDITIONAL_DELIVERY_INSTRUCTION, true],
- ["user launch", "initiating", true, false, TASK_DELIVERY_INITIATING_INSTRUCTION, false],
- ["settled wake", "settled", false, true, TASK_DELIVERY_SETTLED_INSTRUCTION, false],
- ] as const)(
- "resolves %s",
- (
- _name,
- taskDeliveryPhase,
- isFirstTurn,
- hasScheduleProvenance,
- instruction,
- allowsEmptyDelivery,
- ) => {
- expect(
- resolveDeliveryPolicy({
- taskDeliveryPolicy: "cohort",
- hasScheduleProvenance,
- hasOutputSchema: false,
- isChild: false,
- isFirstTurn,
- taskDeliveryPhase,
- }),
- ).toEqual({ allowsEmptyDelivery, instruction });
- },
- );
-
- it.each(["pending", "settled"] as const)(
- "allows auto to withhold a %s report",
- (taskDeliveryPhase) => {
- expect(
- resolveDeliveryPolicy({
- taskDeliveryPolicy: "auto",
- taskDeliveryPhase,
- hasScheduleProvenance: false,
- hasOutputSchema: false,
- isChild: false,
- isFirstTurn: false,
- }),
- ).toEqual({ allowsEmptyDelivery: true, instruction: TASK_DELIVERY_AUTO_INSTRUCTION });
- },
- );
-
- it("allows an empty pending wake without instructing the model to stay silent", () => {
- expect(
- resolveDeliveryPolicy({
- taskDeliveryPolicy: "cohort",
- hasScheduleProvenance: false,
- hasOutputSchema: false,
- isChild: false,
- isFirstTurn: false,
- taskDeliveryPhase: "pending",
- }),
- ).toEqual({ allowsEmptyDelivery: true });
- });
-
- it.each([
- ["structured output", true, false],
- ["child session", false, true],
- ] as const)("keeps %s mandatory", (_name, hasOutputSchema, isChild) => {
- expect(
- resolveDeliveryPolicy({
- taskDeliveryPolicy: "cohort",
- hasScheduleProvenance: true,
- hasOutputSchema,
- isChild,
- isFirstTurn: true,
- taskDeliveryPhase: "initiating",
- }),
- ).toEqual({ allowsEmptyDelivery: false });
- });
-
- it("acknowledges background work launched on a later turn", () => {
- expect(
- resolveDeliveryPolicy({
- taskDeliveryPolicy: "cohort",
- hasOutputSchema: false,
- hasScheduleProvenance: true,
- isChild: false,
- isFirstTurn: false,
- taskDeliveryPhase: "initiating",
- }),
- ).toEqual({
- allowsEmptyDelivery: false,
- instruction: TASK_DELIVERY_INITIATING_INSTRUCTION,
- });
- });
-});
diff --git a/packages/eve/src/tasks/delivery-policy.ts b/packages/eve/src/tasks/delivery-policy.ts
deleted file mode 100644
index d4029c361..000000000
--- a/packages/eve/src/tasks/delivery-policy.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import type { TaskDeliveryPolicy } from "#channel/types.js";
-import { CONDITIONAL_DELIVERY_INSTRUCTION } from "#shared/empty-delivery.js";
-import {
- TASK_DELIVERY_AUTO_INSTRUCTION,
- TASK_DELIVERY_INITIATING_INSTRUCTION,
- TASK_DELIVERY_SETTLED_INSTRUCTION,
-} from "#tasks/delivery-context.js";
-
-export interface DeliveryPolicy {
- readonly allowsEmptyDelivery: boolean;
- readonly instruction?: string;
-}
-
-const POLICIES = {
- auto: { allowsEmptyDelivery: true, instruction: TASK_DELIVERY_AUTO_INSTRUCTION },
- conditional: {
- allowsEmptyDelivery: true,
- instruction: CONDITIONAL_DELIVERY_INSTRUCTION,
- },
- initiating: {
- allowsEmptyDelivery: false,
- instruction: TASK_DELIVERY_INITIATING_INSTRUCTION,
- },
- normal: { allowsEmptyDelivery: false },
- pending: {
- allowsEmptyDelivery: true,
- },
- settled: {
- allowsEmptyDelivery: false,
- instruction: TASK_DELIVERY_SETTLED_INSTRUCTION,
- },
-} as const satisfies Record<string, DeliveryPolicy>;
-
-/** Resolves one policy for both model prompting and empty-response recovery. */
-export function resolveDeliveryPolicy(input: {
- readonly hasOutputSchema: boolean;
- readonly isChild: boolean;
- readonly isFirstTurn: boolean;
- readonly hasScheduleProvenance: boolean;
- readonly taskDeliveryPolicy: TaskDeliveryPolicy | undefined;
- readonly taskDeliveryPhase: "none" | "initiating" | "pending" | "settled" | undefined;
-}): DeliveryPolicy {
- // These runs have an explicit output consumer, so silence would violate the call contract.
- if (input.hasOutputSchema || input.isChild) return POLICIES.normal;
- if (
- input.taskDeliveryPolicy === "auto" &&
- (input.taskDeliveryPhase === "pending" || input.taskDeliveryPhase === "settled")
- )
- return POLICIES.auto;
- if (input.taskDeliveryPhase === "pending") return POLICIES.pending;
- // Delivered terminal results must not disappear silently.
- if (input.taskDeliveryPhase === "settled") return POLICIES.settled;
- // Nobody prompted a schedule-created first turn, so starting work needs no acknowledgement.
- if (input.isFirstTurn && input.hasScheduleProvenance) return POLICIES.conditional;
- // User-prompted background work acknowledges acceptance without waiting for results.
- if (input.taskDeliveryPhase === "initiating") return POLICIES.initiating;
- // Ordinary turns retain the agent's normal response contract.
- return POLICIES.normal;
-}
diff --git a/packages/eve/src/tasks/json.test.ts b/packages/eve/src/tasks/json.test.ts
deleted file mode 100644
index ec36a1cf5..000000000
--- a/packages/eve/src/tasks/json.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { taskCancel } from "#tools/framework/task-cancel.js";
-import { TASK_VIEWS_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";
-import { taskViewToJson } from "#tasks/json.js";
-import type { TaskView } from "#tasks/types.js";
-
-describe("taskViewToJson", () => {
- it("projects only the model-visible task fields", () => {
- const view: TaskView = {
- lastOutput: { data: { answer: 42 }, type: "result" },
- metadata: {
- agentId: "agent-1",
- kind: "subagent",
- mode: "remote",
- name: "researcher",
- },
- status: "completed",
- taskId: "task-1",
- usage: {
- cacheReadTokens: 1,
- cacheWriteTokens: 2,
- inputTokens: 3,
- outputTokens: 4,
- },
- };
-
- expect(taskViewToJson(view)).toEqual({
- lastOutput: { data: { answer: 42 }, type: "result" },
- metadata: {
- agentId: "agent-1",
- kind: "subagent",
- mode: "remote",
- name: "researcher",
- },
- status: "completed",
- taskId: "task-1",
- });
- });
-});
-
-describe("taskCancel.outputSchema", () => {
- it("preserves the broad task-control output contract", () => {
- expect(taskCancel.outputSchema).toBe(TASK_VIEWS_OUTPUT_SCHEMA);
- expect(
- TASK_VIEWS_OUTPUT_SCHEMA["~standard"].validate({
- tasks: [
- {
- inputRequests: [{ prompt: "Choose" }],
- lastOutput: { data: "partial", type: "result" },
- metadata: { data: { source: "custom" }, kind: "tool", name: "report" },
- status: "working",
- taskId: "task-1",
- },
- ],
- }),
- ).toMatchObject({ value: { tasks: [{ status: "working", taskId: "task-1" }] } });
- });
-});
diff --git a/packages/eve/src/tasks/json.ts b/packages/eve/src/tasks/json.ts
deleted file mode 100644
index 86ae7fcd8..000000000
--- a/packages/eve/src/tasks/json.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { z } from "#compiled/zod/index.js";
-
-import type { JsonValue } from "#shared/json.js";
-import { jsonValueSchema } from "#shared/json-schemas.js";
-import type { TaskView } from "#tasks/types.js";
-
-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,
- type: z.enum(["result", "error"]),
-});
-
-const taskViewJsonBaseShape = {
- metadata: taskMetadataJsonSchema,
- taskId: z.string(),
-};
-
-/** Strict model-visible task projection. */
-const TASK_VIEW_JSON_SCHEMA = z.discriminatedUnion("status", [
- z.object({ ...taskViewJsonBaseShape, status: z.literal("working") }),
- z.object({
- ...taskViewJsonBaseShape,
- inputRequests: z.array(jsonValueSchema).readonly(),
- status: z.literal("input_required"),
- }),
- z.object({
- ...taskViewJsonBaseShape,
- lastOutput: taskOutputJsonSchema.extend({ type: z.literal("result") }),
- status: z.literal("completed"),
- }),
- z.object({
- ...taskViewJsonBaseShape,
- lastOutput: taskOutputJsonSchema.extend({ type: z.literal("error") }),
- status: z.literal("failed"),
- }),
- z.object({ ...taskViewJsonBaseShape, status: z.literal("cancelled") }),
-]);
-
-/**
- * Model-visible task view, inferred from {@link TASK_VIEW_JSON_SCHEMA}.
- *
- * This is the public projection of `TaskView` (#tasks/types.js), not a
- * replacement for it: the durable view additionally carries private
- * `executor` and `usage`, and its module must stay zod-free because it is
- * bundled into workflow bodies.
- */
-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 {
- // `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);
-}
-
-/** Projects many views into one `{ tasks }` tool output. */
-export function taskViewsToJson(views: readonly TaskView[]): JsonValue {
- return { tasks: views.map((view) => taskViewToJson(view)) };
-}
diff --git a/packages/eve/src/tasks/notification.ts b/packages/eve/src/tasks/notification.ts
deleted file mode 100644
index 86bfb821d..000000000
--- a/packages/eve/src/tasks/notification.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import type { DeliverHookPayload } from "#channel/types.js";
-import type { SessionStateMap } from "#harness/types.js";
-import { getBackgroundTasks } from "#harness/workflow-tool-runs.js";
-import type { JsonValue } from "#shared/json.js";
-import type { TaskView } from "#tasks/types.js";
-
-export function formatTaskNotification(view: TaskView): string {
- const subject = `Background task ${view.taskId} (${view.metadata.name})`;
- if (view.status === "input_required") {
- return `${subject} needs input.`;
- }
- if (view.status === "completed") {
- return `${subject} is completed.\n\nResult:\n${formatTaskOutput(view.lastOutput.data)}`;
- }
- if (view.status === "failed") {
- return `${subject} failed.\n\nError:\n${formatTaskOutput(view.lastOutput.data)}`;
- }
- return `${subject} is cancelled.`;
-}
-
-export function formatTaskOutput(output: JsonValue): string {
- return typeof output === "string" ? output : (JSON.stringify(output) ?? "null");
-}
-
-/** Task delivery ids are `<taskId>` or `<taskId>:<event>`; derived task ids never contain `:`. */
-export function taskIdOfDelivery(deliveryId: string): string {
- const separator = deliveryId.indexOf(":");
- return separator < 0 ? deliveryId : deliveryId.slice(0, separator);
-}
-
-/** The parent already recorded this task's outcome, so the delivery cannot notify the model again. */
-export function hasRecordedTaskOutcome(
- delivery: DeliverHookPayload,
- state: SessionStateMap | undefined,
-): boolean {
- const deliveryId = delivery.taskDeliveryId;
- if (deliveryId === undefined) return false;
- const task = getBackgroundTasks(state).get(taskIdOfDelivery(deliveryId));
- return task !== undefined && task.status !== "working";
-}
diff --git a/packages/eve/src/tasks/task-id.ts b/packages/eve/src/tasks/task-id.ts
deleted file mode 100644
index 94cc70113..000000000
--- a/packages/eve/src/tasks/task-id.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { createHash } from "node:crypto";
-
-/**
- * Derives the stable task id for one originating background call.
- *
- * 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.
- *
- * Lives apart from the pure task modules because the derivation needs
- * `node:crypto`, which workflow bodies reject; ids are only ever minted
- * inside dispatch steps.
- */
-export function deriveTaskId(input: {
- readonly callId: string;
- readonly parentSessionId: string;
- readonly parentTurnId: string;
-}): string {
- return `task_${createHash("sha256")
- .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}`)
- .digest("hex")
- .slice(0, 24)}`;
-}
-
-/**
- * Derives the task run's private inbox token.
- *
- * Deterministic on purpose: a durable replay of the dispatch step must
- * re-derive the same token so the duplicate task run loses the hook
- * claim and exits instead of splitting the lifecycle across two runs.
- * Unguessable in practice: the parent session's continuation token is
- * itself a private capability, and the derived token never renders to
- * the model.
- */
-export function deriveTaskInboxToken(input: {
- readonly parentContinuationToken: string;
- readonly taskId: string;
-}): string {
- return `task:${input.taskId}:${createHash("sha256")
- .update(`${input.taskId}\0${input.parentContinuationToken}`)
- .digest("hex")
- .slice(0, 32)}`;
-}
diff --git a/packages/eve/src/tasks/task-inbox-token.test.ts b/packages/eve/src/tasks/task-inbox-token.test.ts
deleted file mode 100644
index 658d020f5..000000000
--- a/packages/eve/src/tasks/task-inbox-token.test.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-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/task-inbox-token.ts b/packages/eve/src/tasks/task-inbox-token.ts
deleted file mode 100644
index c4a4eabca..000000000
--- a/packages/eve/src/tasks/task-inbox-token.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-/** Reads the non-secret task id embedded in a private task inbox token. */
-export function readTaskIdFromInboxToken(token: string): string | undefined {
- const match = /^task:(task_[^:]+):[a-f0-9]{32}$/.exec(token);
- return match?.[1];
-}
diff --git a/packages/eve/src/tasks/transitions.test.ts b/packages/eve/src/tasks/transitions.test.ts
deleted file mode 100644
index 52b9905a1..000000000
--- a/packages/eve/src/tasks/transitions.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import type { JsonValue } from "#shared/json.js";
-import { describe, expect, it } from "vitest";
-
-import { applyTaskTransition } from "#tasks/transitions.js";
-import type { TaskStatus, TaskView } from "#tasks/types.js";
-
-function view(status: TaskStatus, overrides: Partial<TaskView> = {}): TaskView {
- return {
- metadata: { kind: "tool", name: "export" },
- status,
- taskId: "task-1",
- ...overrides,
- } as TaskView;
-}
-
-describe("applyTaskTransition", () => {
- it("moves through input, answer, and completion", () => {
- const blocked = applyTaskTransition(view("working"), {
- inputRequests: [{ prompt: "Continue?", requestId: "req-1" }],
- kind: "require-input",
- });
- 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, outcome({ answer: 42 }));
- expect(completed).toMatchObject({
- action: "accepted",
- view: { lastOutput: { data: { answer: 42 }, type: "result" }, status: "completed" },
- });
- });
-
- it("rejects malformed input batches", () => {
- for (const inputRequests of [
- [],
- [{ prompt: "missing id" }],
- [{ requestId: "same" }, { requestId: "same" }],
- ]) {
- expect(
- applyTaskTransition(view("working"), { inputRequests, kind: "require-input" }).action,
- ).toBe("rejected");
- }
- });
-
- 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, outcome("late")).action).toBe("rejected");
- });
-});
-
-function outcome(output: JsonValue) {
- return {
- kind: "outcome" as const,
- result: { status: "completed" as const, output },
- from: {
- callId: "call",
- execution: "background" as const,
- input: {},
- runId: "run",
- sequence: 0,
- stepIndex: 0,
- toolName: "export",
- turnId: "turn",
- },
- };
-}
diff --git a/packages/eve/src/tasks/transitions.ts b/packages/eve/src/tasks/transitions.ts
deleted file mode 100644
index 5017efeb4..000000000
--- a/packages/eve/src/tasks/transitions.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import type { WorkflowToolRunOutcomeMessage } from "#execution/tools/workflow/messages.js";
-import { workflowToolRunFailureOutput } from "#execution/tools/workflow/owner-inbox.js";
-import {
- isTerminalTaskStatus,
- readTaskInputRequestId,
- type TaskCommand,
- type TaskInputRequest,
- type TaskView,
-} from "#tasks/types.js";
-
-export type TaskTransitionResult =
- | { readonly action: "accepted"; readonly view: TaskView }
- | { readonly action: "noop"; readonly view: TaskView }
- | { readonly action: "rejected"; readonly view: TaskView; readonly reason: string };
-
-/** Pure transition function for the background invocation view. */
-export function applyTaskTransition(
- view: TaskView,
- command: TaskCommand | ({ readonly kind: "outcome" } & WorkflowToolRunOutcomeMessage),
-): TaskTransitionResult {
- if (isTerminalTaskStatus(view.status)) {
- 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.`,
- view,
- };
- }
-
- const base = { metadata: view.metadata, taskId: view.taskId };
- if (command.kind === "outcome") {
- const result = command.result;
- return {
- action: "accepted",
- view:
- result.status === "completed"
- ? { ...base, status: "completed", lastOutput: { type: "result", data: result.output } }
- : result.status === "failed"
- ? {
- ...base,
- status: "failed",
- lastOutput: { type: "error", data: workflowToolRunFailureOutput(command) },
- }
- : { ...base, status: "cancelled" },
- };
- }
-
- switch (command.kind) {
- case "reject-dispatch":
- return {
- action: "accepted",
- view: { ...base, lastOutput: { data: command.data, type: "error" }, status: "failed" },
- };
- case "cancel":
- return {
- action: "accepted",
- view:
- command.usage === undefined
- ? { ...base, status: "cancelled" }
- : { ...base, status: "cancelled", usage: command.usage },
- };
- case "require-input":
- if (!isValidInputRequestBatch(command.inputRequests)) {
- return {
- action: "rejected",
- reason: `Task "${view.taskId}" received an invalid input request batch.`,
- view,
- };
- }
- return {
- action: "accepted",
- view: {
- inputRequests: command.inputRequests,
- metadata: view.metadata,
- status: "input_required",
- taskId: view.taskId,
- },
- };
- case "ready":
- return { action: "accepted", view };
- case "answered": {
- if (view.status !== "input_required") return { action: "noop", view };
- const answered = new Set(command.requestIds);
- const remaining = view.inputRequests.filter((request) => {
- const requestId = readTaskInputRequestId(request);
- return requestId === undefined || !answered.has(requestId);
- });
- if (remaining.length === view.inputRequests.length) return { action: "noop", view };
- if (remaining.length > 0) {
- return {
- action: "accepted",
- view: { ...view, inputRequests: remaining },
- };
- }
- return {
- action: "accepted",
- view: {
- metadata: view.metadata,
- status: "working",
- taskId: view.taskId,
- },
- };
- }
- }
-}
-
-function isValidInputRequestBatch(requests: readonly TaskInputRequest[]): boolean {
- if (requests.length === 0) return false;
- const ids = requests.map(readTaskInputRequestId);
- return (
- ids.every((id): id is string => id !== undefined && id.length > 0) &&
- new Set(ids).size === ids.length
- );
-}
diff --git a/packages/eve/src/tasks/types.test.ts b/packages/eve/src/tasks/types.test.ts
deleted file mode 100644
index a7e118599..000000000
--- a/packages/eve/src/tasks/types.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { readTaskInputRequestId, readTaskUsage, sameTaskMetadata } from "#tasks/types.js";
-
-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("reads opaque input request ids", () => {
- expect(readTaskInputRequestId({ prompt: "Continue?", requestId: "req-1" })).toBe("req-1");
- expect(readTaskInputRequestId({ prompt: "Continue?" })).toBeUndefined();
- });
-
- it("accepts complete non-negative usage and drops malformed usage", () => {
- const usage = {
- cacheReadTokens: 1,
- cacheWriteTokens: 2,
- costUsd: 0.25,
- 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
deleted file mode 100644
index 5253787b0..000000000
--- a/packages/eve/src/tasks/types.ts
+++ /dev/null
@@ -1,198 +0,0 @@
-import type {
- SubagentAuthorizationEvent,
- SubagentAuthorizationEventHookPayload,
-} from "#channel/types.js";
-import type { WorkflowToolAgentRequest } from "#execution/tools/workflow/messages.js";
-import type { SessionInboxAddress } from "#execution/session-inbox/address.js";
-import { jsonValuesEqual, type JsonValue } from "#shared/json.js";
-import type { ToolInputResponseResponder } from "#tools/definition.js";
-
-/** Durable lifecycle status for one unit of background work. */
-export type TaskStatus = "working" | "input_required" | "completed" | "failed" | "cancelled";
-
-/** Executor-neutral identity shown for one task. */
-export interface TaskMetadata {
- readonly kind: string;
- readonly name: string;
- readonly [key: string]: JsonValue | undefined;
-}
-
-export function sameTaskMetadata(left: TaskMetadata, right: TaskMetadata): boolean {
- return jsonValuesEqual(left, right);
-}
-
-export type TaskOutput =
- | { readonly type: "result"; readonly data: JsonValue }
- | { readonly type: "error"; readonly data: JsonValue };
-
-/** An outstanding request carried opaquely by the task lifecycle. */
-export type TaskInputRequest = JsonValue;
-
-export interface TaskUsage {
- readonly cacheReadTokens: number;
- readonly cacheWriteTokens: number;
- readonly costUsd?: number;
- readonly inputTokens: number;
- readonly outputTokens: number;
-}
-
-/** 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");
- const cacheWriteTokens = readUsageAxis(value, "cacheWriteTokens");
- const costUsd = readUsageAxis(value, "costUsd");
- const inputTokens = readUsageAxis(value, "inputTokens");
- const outputTokens = readUsageAxis(value, "outputTokens");
- if (
- cacheReadTokens === undefined ||
- cacheWriteTokens === undefined ||
- inputTokens === undefined ||
- outputTokens === undefined
- ) {
- return undefined;
- }
- const usage: {
- cacheReadTokens: number;
- cacheWriteTokens: number;
- costUsd?: number;
- inputTokens: number;
- outputTokens: number;
- } = { cacheReadTokens, cacheWriteTokens, inputTokens, outputTokens };
- if (costUsd !== undefined) usage.costUsd = costUsd;
- return usage;
-}
-
-function readUsageAxis(value: object, key: string): number | undefined {
- const field = Reflect.get(value, key);
- return typeof field === "number" && Number.isFinite(field) && field >= 0 ? field : undefined;
-}
-
-/** 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;
-}
-
-interface TaskViewBase {
- readonly taskId: string;
- readonly metadata: TaskMetadata;
- /** Retained for accounting, excluded from model-visible JSON. */
- readonly usage?: TaskUsage;
-}
-
-export type TaskView = TaskViewBase &
- (
- | {
- readonly status: "working";
- readonly inputRequests?: never;
- readonly lastOutput?: never;
- }
- | {
- readonly status: "input_required";
- readonly inputRequests: readonly TaskInputRequest[];
- readonly lastOutput?: never;
- }
- | {
- readonly status: "completed";
- readonly inputRequests?: never;
- readonly lastOutput: Extract<TaskOutput, { type: "result" }>;
- }
- | {
- readonly status: "failed";
- readonly inputRequests?: never;
- readonly lastOutput: Extract<TaskOutput, { type: "error" }>;
- }
- | {
- readonly status: "cancelled";
- readonly inputRequests?: never;
- readonly lastOutput?: never;
- }
- );
-
-/** Admission, cancellation, and input state changes for a background invocation. */
-export type TaskCommand =
- | { readonly kind: "reject-dispatch"; readonly data: JsonValue }
- | {
- readonly kind: "cancel";
- readonly usage?: TaskUsage;
- }
- | { readonly kind: "require-input"; readonly inputRequests: readonly TaskInputRequest[] }
- | { readonly kind: "ready" }
- | { readonly kind: "answered"; readonly requestIds: readonly string[] };
-
-export interface TaskCommandHookPayload {
- readonly kind: "task-command";
- readonly command: TaskCommand;
-}
-
-/** One human answer routed through the task that owns the blocked executor. */
-export interface TaskInboundAnswerInput {
- readonly auth?: unknown;
- readonly childContinuationToken: string;
- readonly childSessionInbox?: SessionInboxAddress;
- readonly childResponseUrl?: string;
- readonly inputResponses: readonly {
- readonly optionId?: string;
- readonly requestId: string;
- readonly text?: string;
- }[];
- readonly responder?: ToolInputResponseResponder;
- readonly kind: "input-response";
- readonly taskId: string;
-}
-
-export type TaskRunInboundPayload = TaskCommandHookPayload | TaskInboundAnswerInput;
-
-/** 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;
-}
-
-export function isTerminalTaskStatus(status: TaskStatus): boolean {
- return status === "completed" || status === "failed" || status === "cancelled";
-}
-
-export function isReadyTaskStatus(status: TaskStatus): boolean {
- return status === "input_required" || isTerminalTaskStatus(status);
-}
diff --git a/packages/eve/src/tools/behavior.ts b/packages/eve/src/tools/behavior.ts
index ded50bfb7..7564b0f6e 100644
--- a/packages/eve/src/tools/behavior.ts
+++ b/packages/eve/src/tools/behavior.ts
@@ -1,17 +1,16 @@
import type { WebSearchProvider } from "#shared/web-search.js";
/** Session facts that can hide a selected tool without changing source composition. */
-export type ToolAvailabilityCondition = "delegated-task-child" | "root-session";
+export type ToolAvailabilityCondition = "root-session";
/** Native behavior declared by a selected compiled tool. */
export type CompiledToolHandling =
- | { readonly kind: "dispatch"; readonly action: "self-agent" | "task-cancel" }
+ | { readonly kind: "dispatch"; readonly action: "self-agent" }
| { readonly kind: "provider-tool"; readonly provider: WebSearchProvider }
| { readonly kind: "workflow-tool"; readonly workflowId: string };
/** Closed, serializable behavior carried by one selected compiled tool. */
export interface ToolExecutionShape {
- readonly lifetime: "step" | "task";
readonly suspend: "none" | "workflow";
}
@@ -39,7 +38,6 @@ export type PreparedDispatchTarget =
readonly nodeId: string;
readonly subagentName: string;
}
- | { readonly kind: "task-cancel" }
| { readonly kind: "workflow-tool-call"; readonly workflowId: string };
/** Runtime-prepared handling consumed by the harness and execution boundary. */
diff --git a/packages/eve/src/tools/definition-auth.test.ts b/packages/eve/src/tools/definition-auth.test.ts
index adebfeb8f..efcad312e 100644
--- a/packages/eve/src/tools/definition-auth.test.ts
+++ b/packages/eve/src/tools/definition-auth.test.ts
@@ -34,14 +34,4 @@ describe("defineTool approvalKey", () => {
});
expect(definition.approvalKey?.({ scope: "repo" })).toBe("write:repo");
});
-
- it("rejects background execution", () => {
- const definition = {
- description: "Scoped background write",
- execution: "background",
- inputSchema: z.object({ scope: z.string() }),
- execute: async () => null,
- };
- expect(() => defineTool(definition)).toThrow("Use defineWorkflowTool for background work");
- });
});
diff --git a/packages/eve/src/tools/definition.ts b/packages/eve/src/tools/definition.ts
index bb2442e53..0cff930de 100644
--- a/packages/eve/src/tools/definition.ts
+++ b/packages/eve/src/tools/definition.ts
@@ -30,13 +30,10 @@ export type ToolExecuteFn<TInput = unknown, TOutput = unknown> = (
options: ToolExecuteOptions,
) => Promise<TOutput> | TOutput | AsyncIterable<TOutput>;
-export type ToolExecution = "background";
-
interface ToolDefinitionBase {
/** Whether delegated agent sessions receive this tool. Defaults to `true`. */
readonly availableInSubagents?: boolean;
readonly description: string;
- readonly execution?: ToolExecution;
}
export interface ToolLabelDefinition<TInput = unknown, TOutput = unknown> {
@@ -114,12 +111,6 @@ export interface ToolInputRequest {
* {@link options}.
*/
readonly allowFreeform?: boolean;
- /**
- * Whether the user's next message may skip the question. When `true`, a
- * message that does not answer it resolves the request as `dismissed`, and
- * the message reaches the agent as usual.
- */
- readonly dismissible?: boolean;
/** Rendering hint: confirmation buttons, a selection list, or a text field. */
readonly display?: "confirmation" | "select" | "text";
/** Selectable answers. */
@@ -137,8 +128,10 @@ export interface ToolInputResponseResponder {
/**
* The outcome of a {@link ToolInputRequest}.
*
- * - `answered`: the user picked an option or typed an answer.
- * - `dismissed`: the user moved on without answering a `dismissible` request.
+ * - `answered`: the user picked an option or typed an answer. An answer the
+ * session accepted before a withdrawal wins, even after a signal aborted.
+ * - `cancelled`: the request was withdrawn before anyone answered it, because
+ * the ask's `signal` or the call's `abortSignal` aborted.
* - `unavailable`: the session cannot reach a human, such as a scheduled run,
* so the request resolved immediately without being shown.
*/
@@ -152,9 +145,20 @@ export type ToolInputResponse =
/** Free text, when the user typed an answer. */
readonly text?: string;
}
- | { readonly status: "dismissed" }
+ | { readonly status: "cancelled" }
| { readonly status: "unavailable" };
+/** Options for `ctx.ask` in a `defineWorkflowTool` executor. */
+export interface ToolInputRequestOptions {
+ /**
+ * Withdraws the request when it aborts: the channel stops offering the
+ * question and the ask resolves as `cancelled`, unless the session accepted
+ * an answer first, which the ask then resolves with. Pass
+ * `ctx.interruptSignal` to stop asking once a new message arrives.
+ */
+ readonly signal?: AbortSignal;
+}
+
/**
* Authored tool context. Passed as the last argument to
* {@link ToolDefinition.execute}.
@@ -210,7 +214,6 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends Pub
TInput,
TOutput
> {
- readonly execution?: never;
execute(input: TInput, ctx: ToolContext): Promise<TOutput> | TOutput | AsyncIterable<TOutput>;
/**
* Optional per-tool approval gate. The return value determines whether
@@ -346,11 +349,6 @@ export function defineTool<TInput = unknown, TOutput = unknown>(
export function defineTool<TInput = unknown, TOutput = unknown>(
definition: ToolDefinition<TInput, TOutput>,
): ToolDefinition<TInput, TOutput> {
- if ("execution" in definition && definition.execution !== undefined) {
- throw new Error(
- 'defineTool: "execution" is not supported. Use defineWorkflowTool for background work.',
- );
- }
return stampToolDefinition(definition, "defineTool");
}
diff --git a/packages/eve/src/tools/framework/agent-contract.ts b/packages/eve/src/tools/framework/agent-contract.ts
index 0b60841b1..95275db64 100644
--- a/packages/eve/src/tools/framework/agent-contract.ts
+++ b/packages/eve/src/tools/framework/agent-contract.ts
@@ -3,7 +3,7 @@ import { defineJsonSchema } from "#tools/schema.js";
export const AGENT_TOOL_NAME = "agent";
export const AGENT_TOOL_DESCRIPTION = [
- "Delegate a focused subtask to a copy of yourself, or continue or steer a previous delegation with `agentId`.",
+ "Delegate a focused subtask to a copy of yourself, or continue a previous delegation with `agentId`.",
"Use it to isolate complex work or split a large task into independent pieces.",
"Issue multiple `agent` calls in one response to run a small fixed set in parallel.",
"A new child has fresh history and state but reuses your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes.",
@@ -20,7 +20,7 @@ export const SUBAGENT_TOOL_INPUT_SCHEMA = defineJsonSchema<SubagentToolInput>({
agentId: {
type: ["string", "null"],
description:
- "The id of an existing agent from the <agents> list or a task receipt. A message to a busy agent steers it: its previous task is cancelled and the updated work runs in the same child session. Omit this field (or pass null or an empty string) to start a new agent.",
+ "The id of an existing agent from the <agents> list. Omit this field (or pass null or an empty string) to start a new agent.",
},
message: {
type: "string",
diff --git a/packages/eve/src/tools/framework/agent.ts b/packages/eve/src/tools/framework/agent.ts
index 73b8d6657..f6eb174a4 100644
--- a/packages/eve/src/tools/framework/agent.ts
+++ b/packages/eve/src/tools/framework/agent.ts
@@ -3,20 +3,14 @@ import {
AGENT_TOOL_DESCRIPTION,
SUBAGENT_TOOL_INPUT_SCHEMA,
} from "#tools/framework/agent-contract.js";
-import {
- SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,
- type SubagentTaskReceipt,
-} from "#tools/framework/task-contract.js";
import { attachToolBehavior } from "#tools/behavior.js";
export const agent = attachToolBehavior(
stampToolDefinition(
{
- description: `${AGENT_TOOL_DESCRIPTION} This call starts a background task and returns a task receipt immediately.`,
- execution: "background",
+ description: AGENT_TOOL_DESCRIPTION,
inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
- outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,
- execute(): SubagentTaskReceipt {
+ execute(): never {
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.',
);
diff --git a/packages/eve/src/tools/framework/task-cancel.ts b/packages/eve/src/tools/framework/task-cancel.ts
deleted file mode 100644
index 3a678c627..000000000
--- a/packages/eve/src/tools/framework/task-cancel.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import {
- TASK_CANCEL_INPUT_SCHEMA,
- TASK_VIEWS_OUTPUT_SCHEMA,
-} from "#tools/framework/task-contract.js";
-import { defineNativeTool } from "#tools/native-definition.js";
-
-export const taskCancel = defineNativeTool(
- {
- 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.",
- inputSchema: TASK_CANCEL_INPUT_SCHEMA,
- outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,
- },
- {
- availability: ["root-session"],
- handling: { action: "task-cancel", kind: "dispatch" },
- },
-);
-
-export default taskCancel;
diff --git a/packages/eve/src/tools/framework/task-contract.ts b/packages/eve/src/tools/framework/task-contract.ts
deleted file mode 100644
index bb096c805..000000000
--- a/packages/eve/src/tools/framework/task-contract.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { defineJsonSchema } from "#tools/schema.js";
-
-export const TASK_CANCEL_TOOL_NAME = "task_cancel";
-
-/** Framework task-control tool names lowered by the runtime. */
-export const TASK_TOOL_NAMES: ReadonlySet<string> = new Set([TASK_CANCEL_TOOL_NAME]);
-
-export const TASK_CANCEL_INPUT_SCHEMA = defineJsonSchema<{ taskIds: string[] }>({
- type: "object",
- properties: {
- taskIds: {
- type: "array",
- minItems: 1,
- items: { type: "string", minLength: 1 },
- description: "Task ids from earlier subagent task receipts.",
- },
- },
- required: ["taskIds"],
- additionalProperties: false,
-});
-
-/**
- * Broad schema advertised by task-control tool outputs. Objects stay open so
- * task metadata can grow without breaking consumers of the output contract.
- */
-export const TASK_VIEWS_OUTPUT_SCHEMA = defineJsonSchema({
- type: "object",
- properties: {
- tasks: {
- type: "array",
- items: {
- type: "object",
- properties: {
- inputRequests: { type: "array", items: {} },
- lastOutput: {
- type: "object",
- properties: {
- data: {},
- type: { type: "string", enum: ["result", "error"] },
- },
- required: ["data", "type"],
- },
- metadata: {
- type: "object",
- properties: {
- agentId: { type: "string" },
- kind: { type: "string" },
- mode: { type: "string", enum: ["local", "remote"] },
- name: { type: "string" },
- },
- required: ["kind", "name"],
- },
- status: {
- type: "string",
- enum: ["working", "input_required", "completed", "failed", "cancelled"],
- },
- taskId: { type: "string" },
- },
- required: ["metadata", "status", "taskId"],
- },
- },
- },
- required: ["tasks"],
-});
-
-export interface SubagentTaskReceipt {
- agentId: string;
- status: "working";
- taskId: string;
-}
-
-export const SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA = defineJsonSchema<SubagentTaskReceipt>({
- type: "object",
- properties: {
- agentId: { type: "string" },
- status: { type: "string", const: "working" },
- taskId: { type: "string" },
- },
- required: ["agentId", "status", "taskId"],
- additionalProperties: false,
-});
diff --git a/packages/eve/src/tools/native-definition.ts b/packages/eve/src/tools/native-definition.ts
deleted file mode 100644
index db420f539..000000000
--- a/packages/eve/src/tools/native-definition.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import type { PublicToolDefinition } from "#tools/definition.js";
-import { attachToolBehavior, type CompiledToolBehavior } from "#tools/behavior.js";
-
-/** Framework-only tool definition whose implementation is owned outside an executor. */
-type NativeToolDefinition<TInput = unknown, TOutput = unknown> = PublicToolDefinition<
- TInput,
- TOutput
->;
-
-/** Defines an execute-less framework tool with closed internal behavior. */
-export function defineNativeTool<TInput = unknown, TOutput = unknown>(
- definition: NativeToolDefinition<TInput, TOutput>,
- behavior: CompiledToolBehavior,
-): NativeToolDefinition<TInput, TOutput> {
- return attachToolBehavior(definition, behavior);
-}
diff --git a/packages/eve/src/tools/provided/agent-router.test.ts b/packages/eve/src/tools/provided/agent-router.test.ts
index eea39c2b1..d912f502a 100644
--- a/packages/eve/src/tools/provided/agent-router.test.ts
+++ b/packages/eve/src/tools/provided/agent-router.test.ts
@@ -22,7 +22,7 @@ describe("agentRouter", () => {
vi.mocked(evaluate).mockResolvedValue({
answers: { route: { choice: "operator", type: "choice" } },
} as never);
- const agent = vi.fn().mockResolvedValue("operated");
+ const { agent, send } = replyingAgent("operated");
const abortSignal = new AbortController().signal;
const ctx = workflowContext({
abortSignal,
@@ -50,11 +50,12 @@ describe("agentRouter", () => {
},
},
});
- expect(agent).toHaveBeenCalledWith("operator", { message: "Deploy the service" });
+ expect(agent).toHaveBeenCalledWith("operator");
+ expect(send).toHaveBeenCalledWith("Deploy the service", { signal: abortSignal });
});
it("ignores agents without descriptions", async () => {
- const agent = vi.fn().mockResolvedValue("researched");
+ const { agent, send } = replyingAgent("researched");
const ctx = workflowContext({
agent,
agents: {
@@ -67,11 +68,12 @@ describe("agentRouter", () => {
"researched",
);
expect(evaluate).not.toHaveBeenCalled();
- expect(agent).toHaveBeenCalledWith("researcher", { message: "Investigate" });
+ expect(agent).toHaveBeenCalledWith("researcher");
+ expect(send).toHaveBeenCalledWith("Investigate", { signal: expect.any(AbortSignal) });
});
it("invokes the only available described agent without evaluation", async () => {
- const agent = vi.fn().mockResolvedValue("researched");
+ const { agent, send } = replyingAgent("researched");
const ctx = workflowContext({
agent,
agents: { researcher: { description: "Investigate and explain." } },
@@ -81,7 +83,8 @@ describe("agentRouter", () => {
"researched",
);
expect(evaluate).not.toHaveBeenCalled();
- expect(agent).toHaveBeenCalledWith("researcher", { message: "Investigate" });
+ expect(agent).toHaveBeenCalledWith("researcher");
+ expect(send).toHaveBeenCalledWith("Investigate", { signal: expect.any(AbortSignal) });
});
it("rejects an agent map without descriptions before evaluation", async () => {
@@ -97,6 +100,14 @@ describe("agentRouter", () => {
});
});
+/** An agent whose session replies to every message with `message`. */
+function replyingAgent(message: string) {
+ const send = vi.fn(async () => ({
+ result: async () => ({ data: undefined, message, status: "waiting" as const }),
+ }));
+ return { agent: vi.fn(() => ({ send })), send };
+}
+
function workflowContext(
input: Pick<WorkflowToolContext, "agent" | "agents"> &
Partial<Pick<WorkflowToolContext, "abortSignal">>,
diff --git a/packages/eve/src/tools/provided/agent-router.ts b/packages/eve/src/tools/provided/agent-router.ts
index c6a8e9e49..0716fe14c 100644
--- a/packages/eve/src/tools/provided/agent-router.ts
+++ b/packages/eve/src/tools/provided/agent-router.ts
@@ -5,14 +5,11 @@ import {
executeAgentRouterTool,
type AgentRouterInput,
} from "#execution/tools/agent-router.js";
-import {
- defineWorkflowTool,
- type BlockingWorkflowToolDefinition,
-} from "#tools/workflow-definition.js";
+import { defineWorkflowTool, type WorkflowToolDefinition } from "#tools/workflow-definition.js";
export type { AgentRouterInput };
-export type AgentRouterTool = BlockingWorkflowToolDefinition<AgentRouterInput, JsonValue>;
+export type AgentRouterTool = WorkflowToolDefinition<AgentRouterInput, JsonValue>;
/** Defines a workflow tool that uses JEV to route a task across all available agent targets. */
export function agentRouter(): AgentRouterTool {
diff --git a/packages/eve/src/execution/tools/ask-question-workflow.ts b/packages/eve/src/tools/provided/ask-question-workflow.ts
similarity index 56%
rename from packages/eve/src/execution/tools/ask-question-workflow.ts
rename to packages/eve/src/tools/provided/ask-question-workflow.ts
index 1cba41644..f351627de 100644
--- a/packages/eve/src/execution/tools/ask-question-workflow.ts
+++ b/packages/eve/src/tools/provided/ask-question-workflow.ts
@@ -1,15 +1,18 @@
-import type { AskQuestionInput, AskQuestionOutput } from "#execution/tools/ask-question.js";
-import type { ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
-import type { WorkflowToolContext } from "#tools/workflow-definition.js";
+import type {
+ ToolInputRequest,
+ ToolInputResponse,
+ WorkflowToolContext,
+} from "#public/tools/index.js";
+import type { AskQuestionInput, AskQuestionOutput } from "#tools/provided/ask-question.js";
-/** Asks the session's user one question in a workflow dedicated to this tool call. */
+/** Asks the session's user one question, and withdraws it when a new message arrives. */
export async function executeAskQuestionTool(
input: AskQuestionInput,
ctx: WorkflowToolContext,
): Promise<AskQuestionOutput> {
"use workflow";
- const answer = await ctx.ask(toAskQuestionRequest(input));
+ const answer = await ctx.ask(toAskQuestionRequest(input), { signal: ctx.interruptSignal });
return toAskQuestionOutput(answer);
}
@@ -25,7 +28,6 @@ export function toAskQuestionRequest(input: AskQuestionInput): ToolInputRequest
}));
return {
allowFreeform: true,
- dismissible: true,
display: options === undefined ? "text" : "select",
prompt: input.question,
...(options !== undefined && { options }),
@@ -33,6 +35,12 @@ export function toAskQuestionRequest(input: AskQuestionInput): ToolInputRequest
}
export function toAskQuestionOutput(answer: ToolInputResponse): AskQuestionOutput {
- if (answer.status !== "answered") return { status: answer.status };
- return { answer: answer.optionId ?? answer.text ?? "", status: "answered" };
+ switch (answer.status) {
+ case "answered":
+ return { answer: answer.optionId ?? answer.text ?? "", status: "answered" };
+ case "cancelled":
+ return { interrupted: true };
+ case "unavailable":
+ return { status: "unavailable" };
+ }
}
diff --git a/packages/eve/src/tools/provided/ask-question.test.ts b/packages/eve/src/tools/provided/ask-question.test.ts
index 9568f1b86..d8bd7839f 100644
--- a/packages/eve/src/tools/provided/ask-question.test.ts
+++ b/packages/eve/src/tools/provided/ask-question.test.ts
@@ -3,12 +3,12 @@ import { describe, expect, it, vi } from "vitest";
import {
ASK_QUESTION_INPUT_SCHEMA,
ASK_QUESTION_TOOL_DESCRIPTION,
-} from "#execution/tools/ask-question.js";
+ askQuestion,
+} from "#tools/provided/ask-question.js";
import {
toAskQuestionOutput,
toAskQuestionRequest,
-} from "#execution/tools/ask-question-workflow.js";
-import { askQuestion } from "#tools/provided/ask-question.js";
+} from "#tools/provided/ask-question-workflow.js";
import { isWorkflowToolDefinition } from "#tools/workflow-definition.js";
function accepts(value: unknown): boolean {
@@ -32,11 +32,16 @@ describe("askQuestion", () => {
expect(isWorkflowToolDefinition(definition)).toBe(true);
expect(definition.description).toBe(ASK_QUESTION_TOOL_DESCRIPTION);
- await expect(definition.execute(colorQuestion, { ask } as never)).resolves.toEqual({
+ const interruptSignal = new AbortController().signal;
+ await expect(
+ definition.execute(colorQuestion, { ask, interruptSignal } as never),
+ ).resolves.toEqual({
answer: "Blue",
status: "answered",
});
- expect(ask).toHaveBeenCalledExactlyOnceWith(toAskQuestionRequest(colorQuestion));
+ expect(ask).toHaveBeenCalledExactlyOnceWith(toAskQuestionRequest(colorQuestion), {
+ signal: interruptSignal,
+ });
});
it("accepts one question with at most three label and description options", () => {
@@ -71,10 +76,9 @@ describe("askQuestion", () => {
});
describe("toAskQuestionRequest", () => {
- it("always allows free text and lets the user move on", () => {
+ it("always allows free text", () => {
expect(toAskQuestionRequest(colorQuestion)).toEqual({
allowFreeform: true,
- dismissible: true,
display: "select",
options: [
{ description: "Warm and bold.", id: "Red (Recommended)", label: "Red (Recommended)" },
@@ -84,7 +88,6 @@ describe("toAskQuestionRequest", () => {
});
expect(toAskQuestionRequest({ question: "What should we call it?" })).toEqual({
allowFreeform: true,
- dismissible: true,
display: "text",
prompt: "What should we call it?",
});
@@ -103,10 +106,8 @@ describe("toAskQuestionOutput", () => {
});
});
- it("passes through dismissed and unavailable answers", () => {
- expect(toAskQuestionOutput({ status: "dismissed" })).toEqual({
- status: "dismissed",
- });
+ it("reports a withdrawn question as interrupted and passes through unavailable", () => {
+ expect(toAskQuestionOutput({ status: "cancelled" })).toEqual({ interrupted: true });
expect(toAskQuestionOutput({ status: "unavailable" })).toEqual({
status: "unavailable",
});
diff --git a/packages/eve/src/tools/provided/ask-question.ts b/packages/eve/src/tools/provided/ask-question.ts
index b94ebf8c6..14cd2110c 100644
--- a/packages/eve/src/tools/provided/ask-question.ts
+++ b/packages/eve/src/tools/provided/ask-question.ts
@@ -1,14 +1,105 @@
-import { defineWorkflowTool, type WorkflowToolDefinition } from "#tools/workflow-definition.js";
+import { defineWorkflowTool, type WorkflowToolDefinition } from "#public/tools/index.js";
+import { executeAskQuestionTool } from "#tools/provided/ask-question-workflow.js";
import {
- ASK_QUESTION_INPUT_SCHEMA,
- ASK_QUESTION_OUTPUT_SCHEMA,
- ASK_QUESTION_TOOL_DESCRIPTION,
- executeAskQuestionTool,
- type AskQuestionInput,
- type AskQuestionOutput,
-} from "#execution/tools/ask-question.js";
+ INTERRUPTED_OUTPUT_SCHEMA,
+ toInterruptibleModelOutput,
+ type InterruptedOutput,
+} from "#tools/provided/interrupted.js";
+import { defineJsonSchema } from "#tools/schema.js";
-export type { AskQuestionInput, AskQuestionOutput };
+export const ASK_QUESTION_TOOL_DESCRIPTION = [
+ "Ask the user a question and wait for the answer. Use this only when you cannot make good progress without the user's input: to choose between materially different approaches, fill in a missing requirement, or confirm something risky or irreversible. Do not ask for information you can find with your other tools, and do not ask the user to confirm routine steps.",
+ "",
+ "Usage:",
+ "- Ask one focused question that includes the context needed to answer it.",
+ '- For a decision, offer 2-3 mutually exclusive options. Put the option you recommend first and end its label with "(Recommended)".',
+ '- Do not add an "Other" option; the user can always type their own answer.',
+ "- The result's `answer` is the chosen option's label or the user's own words.",
+ "- If the question stopped early because a new message arrived, respond to that message instead.",
+ '- If the status is "unavailable", no one can answer in this session; continue with your best judgment and state the assumption you made.',
+].join("\n");
+
+export interface AskQuestionInput {
+ options?: { description: string; label: string }[];
+ question: string;
+}
+
+export type AskQuestionOutput =
+ | { answer: string; status: "answered" }
+ | InterruptedOutput
+ | { status: "unavailable" };
+
+export const ASK_QUESTION_INPUT_SCHEMA = defineJsonSchema<AskQuestionInput>(
+ {
+ type: "object",
+ properties: {
+ options: {
+ type: "array",
+ minItems: 2,
+ maxItems: 3,
+ items: {
+ type: "object",
+ properties: {
+ description: {
+ type: "string",
+ minLength: 1,
+ maxLength: 200,
+ description: "One short sentence on the impact or tradeoff of choosing this option.",
+ },
+ label: {
+ type: "string",
+ minLength: 1,
+ maxLength: 80,
+ description: "User-facing label, 1-5 words.",
+ },
+ },
+ required: ["description", "label"],
+ additionalProperties: false,
+ },
+ description:
+ 'Two or three mutually exclusive choices, recommended option first. Omit for an open-ended question. Never include an "Other" option.',
+ },
+ question: {
+ type: "string",
+ minLength: 1,
+ maxLength: 2000,
+ description: "The question to show the user, with the context needed to answer it.",
+ },
+ },
+ required: ["question"],
+ additionalProperties: false,
+ },
+ // Labels double as option ids, so duplicates would make answers ambiguous.
+ (input) =>
+ input.options !== undefined &&
+ new Set(input.options.map((option) => option.label)).size !== input.options.length
+ ? "Option labels must be unique."
+ : undefined,
+);
+
+const ASK_QUESTION_OUTPUT_SCHEMA = defineJsonSchema<AskQuestionOutput>({
+ oneOf: [
+ {
+ type: "object",
+ properties: {
+ answer: {
+ type: "string",
+ description: "The chosen option's label, or the user's own words.",
+ },
+ status: { type: "string", const: "answered" },
+ },
+ required: ["answer", "status"],
+ additionalProperties: false,
+ },
+ INTERRUPTED_OUTPUT_SCHEMA,
+ {
+ type: "object",
+ properties: { status: { type: "string", const: "unavailable" } },
+ required: ["status"],
+ additionalProperties: false,
+ },
+ ],
+});
/**
* Defines the opt-in `ask_question` tool.
@@ -22,7 +113,8 @@ export type { AskQuestionInput, AskQuestionOutput };
* ```
*
* Each call runs as a durable workflow that asks through `ctx.ask()`, so the
- * turn waits for the answer without holding an application runtime open.
+ * turn waits for the answer without holding an application runtime open. A new
+ * message that does not answer the question withdraws it.
*/
export function askQuestion(): WorkflowToolDefinition<AskQuestionInput, AskQuestionOutput> {
return defineWorkflowTool({
@@ -30,5 +122,6 @@ export function askQuestion(): WorkflowToolDefinition<AskQuestionInput, AskQuest
execute: executeAskQuestionTool,
inputSchema: ASK_QUESTION_INPUT_SCHEMA,
outputSchema: ASK_QUESTION_OUTPUT_SCHEMA,
+ toModelOutput: toInterruptibleModelOutput,
});
}
diff --git a/packages/eve/src/tools/provided/interrupted.ts b/packages/eve/src/tools/provided/interrupted.ts
new file mode 100644
index 000000000..53545ef4c
--- /dev/null
+++ b/packages/eve/src/tools/provided/interrupted.ts
@@ -0,0 +1,21 @@
+import { toolOutput, type ToolModelOutput } from "#public/tools/index.js";
+
+/** What a provided tool returns when a new message stops it early. */
+export interface InterruptedOutput {
+ readonly interrupted: true;
+}
+
+const INTERRUPTED_TEXT = "Stopped early because a new message arrived.";
+
+/** The model sees an interrupted call as text and every other output as JSON, as it would by default. */
+export function toInterruptibleModelOutput(output: object): ToolModelOutput {
+ if ("interrupted" in output) return toolOutput.text(INTERRUPTED_TEXT);
+ return toolOutput.json(output);
+}
+
+export const INTERRUPTED_OUTPUT_SCHEMA = {
+ type: "object",
+ properties: { interrupted: { type: "boolean", const: true } },
+ required: ["interrupted"],
+ additionalProperties: false,
+} as const;
diff --git a/packages/eve/src/tools/provided/sleep-workflow.ts b/packages/eve/src/tools/provided/sleep-workflow.ts
new file mode 100644
index 000000000..1ca0e9d09
--- /dev/null
+++ b/packages/eve/src/tools/provided/sleep-workflow.ts
@@ -0,0 +1,19 @@
+import { sleep } from "#compiled/@workflow/core/index.js";
+
+import type { WorkflowToolContext } from "#public/tools/index.js";
+import type { SleepToolInput, SleepToolOutput } from "#tools/provided/sleep.js";
+
+/** Waits durably, and stops early when a new message arrives. */
+export async function executeSleepTool(
+ input: SleepToolInput,
+ ctx: WorkflowToolContext,
+): Promise<SleepToolOutput> {
+ "use workflow";
+
+ const interrupted = new Promise<"interrupted">((resolve) =>
+ ctx.interruptSignal.addEventListener("abort", () => resolve("interrupted"), { once: true }),
+ );
+ const elapsed = sleep(Math.ceil(input.seconds * 1_000)).then(() => "elapsed" as const);
+ const woke = await Promise.race([elapsed, interrupted]);
+ return woke === "elapsed" ? { waitedSeconds: input.seconds } : { interrupted: true };
+}
diff --git a/packages/eve/src/tools/provided/sleep.test.ts b/packages/eve/src/tools/provided/sleep.test.ts
index 01fd77b63..13e7bf7c9 100644
--- a/packages/eve/src/tools/provided/sleep.test.ts
+++ b/packages/eve/src/tools/provided/sleep.test.ts
@@ -30,7 +30,8 @@ describe("sleep", () => {
}),
);
const definition = sleep();
- const output = definition.execute({ seconds: 2.5001 }, {} as never);
+ const interruptSignal = new AbortController().signal;
+ const output = definition.execute({ seconds: 2.5001 }, { interruptSignal } as never);
await vi.waitFor(() => {
expect(workflowSleep).toHaveBeenCalledExactlyOnceWith(2_501);
diff --git a/packages/eve/src/tools/provided/sleep.ts b/packages/eve/src/tools/provided/sleep.ts
index 3e83e6fdc..2f467c801 100644
--- a/packages/eve/src/tools/provided/sleep.ts
+++ b/packages/eve/src/tools/provided/sleep.ts
@@ -1,14 +1,48 @@
-import { defineWorkflowTool, type WorkflowToolDefinition } from "#tools/workflow-definition.js";
+import { defineWorkflowTool, type WorkflowToolDefinition } from "#public/tools/index.js";
import {
- executeSleepTool,
- SLEEP_INPUT_SCHEMA,
- SLEEP_OUTPUT_SCHEMA,
- SLEEP_TOOL_DESCRIPTION,
- type SleepToolInput,
- type SleepToolOutput,
-} from "#execution/tools/sleep.js";
+ INTERRUPTED_OUTPUT_SCHEMA,
+ toInterruptibleModelOutput,
+ type InterruptedOutput,
+} from "#tools/provided/interrupted.js";
+import { executeSleepTool } from "#tools/provided/sleep-workflow.js";
+import { defineJsonSchema } from "#tools/schema.js";
-export type { SleepToolInput, SleepToolOutput };
+const MAX_SLEEP_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1_000);
+
+const SLEEP_TOOL_DESCRIPTION =
+ "Wait for a specified amount of time before continuing. Use this when a process or condition needs time to change before it is useful to check its progress or status again.";
+
+export interface SleepToolInput {
+ seconds: number;
+}
+
+export type SleepToolOutput = { waitedSeconds: number } | InterruptedOutput;
+
+export const SLEEP_INPUT_SCHEMA = defineJsonSchema<SleepToolInput>({
+ type: "object",
+ properties: {
+ seconds: {
+ type: "number",
+ exclusiveMinimum: 0,
+ maximum: MAX_SLEEP_SECONDS,
+ description: "How long to wait, in seconds.",
+ },
+ },
+ required: ["seconds"],
+ additionalProperties: false,
+});
+
+const SLEEP_OUTPUT_SCHEMA = defineJsonSchema<SleepToolOutput>({
+ oneOf: [
+ {
+ type: "object",
+ properties: { waitedSeconds: { type: "number", exclusiveMinimum: 0 } },
+ required: ["waitedSeconds"],
+ additionalProperties: false,
+ },
+ INTERRUPTED_OUTPUT_SCHEMA,
+ ],
+});
/**
* Defines the opt-in durable `sleep` tool.
@@ -22,7 +56,7 @@ export type { SleepToolInput, SleepToolOutput };
* ```
*
* Each call runs as a durable workflow, so the wait does not hold an
- * application runtime open.
+ * application runtime open. A new message ends the wait early.
*/
export function sleep(): WorkflowToolDefinition<SleepToolInput, SleepToolOutput> {
return defineWorkflowTool({
@@ -30,5 +64,6 @@ export function sleep(): WorkflowToolDefinition<SleepToolInput, SleepToolOutput>
execute: executeSleepTool,
inputSchema: SLEEP_INPUT_SCHEMA,
outputSchema: SLEEP_OUTPUT_SCHEMA,
+ toModelOutput: toInterruptibleModelOutput,
});
}
diff --git a/packages/eve/src/tools/provided/workflow.test.ts b/packages/eve/src/tools/provided/workflow.test.ts
index 6c339f6c1..4734ea2ed 100644
--- a/packages/eve/src/tools/provided/workflow.test.ts
+++ b/packages/eve/src/tools/provided/workflow.test.ts
@@ -21,11 +21,10 @@ describe("workflow", () => {
expect(isWorkflowToolDefinition(definition)).toBe(true);
expect(definition.description).toContain(
- "ctx.agent(name, { message: string, agentId?: string, outputSchema?: object })",
- );
- expect(definition.description).toContain(
- "resolves directly to the child's JSON-serializable output",
+ "ctx.agent(name, { message: string, outputSchema?: object })",
);
+ expect(definition.description).toContain("Each call starts a new agent");
+ expect(definition.description).toContain("resolves directly to the agent's reply");
expect(definition.description).toContain("does not return an agent metadata wrapper");
expect(definition.description).toContain("owning agent resolves the target");
expect(definition.description).toContain(
@@ -52,9 +51,7 @@ describe("workflow", () => {
expect(inputSchema).toMatchObject({
properties: {
js: {
- description: expect.stringContaining(
- "resolves directly to the child's JSON-serializable output",
- ),
+ description: expect.stringContaining("resolves directly to the agent's reply"),
},
},
});
diff --git a/packages/eve/src/tools/provided/workflow.ts b/packages/eve/src/tools/provided/workflow.ts
index 8b1e6845c..00667f612 100644
--- a/packages/eve/src/tools/provided/workflow.ts
+++ b/packages/eve/src/tools/provided/workflow.ts
@@ -4,10 +4,7 @@ import {
} from "#execution/dynamic-workflow/schema.js";
import { executeWorkflowProgram } from "#execution/dynamic-workflow/tool.js";
import type { JsonValue } from "#shared/json.js";
-import {
- defineWorkflowTool,
- type BlockingWorkflowToolDefinition,
-} from "#tools/workflow-definition.js";
+import { defineWorkflowTool, type WorkflowToolDefinition } from "#tools/workflow-definition.js";
import { attachWorkflowProgramOptions } from "#tools/workflow-program-input.js";
import { defineJsonSchema } from "#tools/schema.js";
@@ -20,10 +17,10 @@ export interface WorkflowToolInput {
readonly js: string;
}
-export type WorkflowTool = BlockingWorkflowToolDefinition<WorkflowToolInput, JsonValue>;
+export type WorkflowTool = WorkflowToolDefinition<WorkflowToolInput, JsonValue>;
const workflowProgramAgentContract =
- "Call ctx.agent(name, { message: string, agentId?: string, outputSchema?: object }). It resolves directly to the child's JSON-serializable output; when outputSchema is provided, the output matches that schema. It does not return an agent metadata wrapper. Use an agentId from the conversation's <agents> block to continue that child. The owning agent resolves the target and applies its existing availability and authorization checks.";
+ "Call ctx.agent(name, { message: string, outputSchema?: object }). Each call starts a new agent that does not see this conversation, so put everything it needs in message. It resolves directly to the agent's reply; when outputSchema is provided, the reply matches that schema. It does not return an agent metadata wrapper. The owning agent resolves the target and applies its existing availability and authorization checks.";
const workflowInputSchema = defineJsonSchema<WorkflowToolInput>({
type: "object",
diff --git a/packages/eve/src/tools/schema-emission.ts b/packages/eve/src/tools/schema-emission.ts
new file mode 100644
index 000000000..afe6900db
--- /dev/null
+++ b/packages/eve/src/tools/schema-emission.ts
@@ -0,0 +1,76 @@
+import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
+
+import { parseJsonObject, type JsonObject } from "#shared/json.js";
+import type { ToolSchemaSource } from "#tools/schema.js";
+
+// Kept apart from `#tools/schema.js`, which loads the AI SDK and a JSON Schema
+// validator: workflow code serializes `ctx.agent` output schemas with this
+// module, and everything it imports ships in every workflow bundle.
+
+export type SchemaDirection = "input" | "output";
+
+/** `null` and `undefined` pass through every conversion untouched. */
+export type SchemaResult<TSource, TResult> = TSource extends null | undefined ? TSource : TResult;
+
+type JsonSchemaEmitter = StandardJSONSchemaV1.Converter[SchemaDirection];
+
+const JSON_SCHEMA_TARGET: StandardJSONSchemaV1.Target = "draft-07";
+
+/**
+ * Serializes an output schema source into canonical JSON Schema data (no
+ * `$schema` key) for compiled artifacts, durable state, and protocol
+ * responses. `null` and `undefined` pass through untouched.
+ */
+export function serializeOutputSchema<T extends ToolSchemaSource | null | undefined>(
+ source: T,
+): SchemaResult<T, JsonObject> {
+ if (source === null || source === undefined) return source as SchemaResult<T, JsonObject>;
+ return emitJsonSchema(source, "output") as SchemaResult<T, JsonObject>;
+}
+
+/**
+ * Normalizes one source into canonical JSON Schema data. Standard Schemas
+ * emit their requested direction; plain data passes through. The `$schema`
+ * version key is always stripped so every eve boundary carries one canonical
+ * wire form.
+ */
+export function emitJsonSchema(source: ToolSchemaSource, direction: SchemaDirection): JsonObject {
+ const standard = getStandardSchemaProperties(source);
+ if (standard === undefined) return withoutSchemaVersion(parseJsonObject(source));
+
+ const emit = readJsonSchemaEmitter(standard, direction);
+ if (emit === undefined) throw new Error(describeMissingEmitter(standard));
+ return withoutSchemaVersion(parseJsonObject(emit({ target: JSON_SCHEMA_TARGET })));
+}
+
+export function readJsonSchemaEmitter(
+ standard: Record<string, unknown>,
+ direction: SchemaDirection,
+): JsonSchemaEmitter | undefined {
+ const jsonSchema = standard.jsonSchema;
+ if (typeof jsonSchema !== "object" || jsonSchema === null) return undefined;
+ const emit = (jsonSchema as Record<string, unknown>)[direction];
+ return typeof emit === "function" ? (emit as JsonSchemaEmitter) : undefined;
+}
+
+export function getStandardSchemaProperties(value: unknown): Record<string, unknown> | undefined {
+ if (typeof value !== "object" || value === null || !("~standard" in value)) return undefined;
+
+ const standard = (value as Record<string, unknown>)["~standard"];
+ return typeof standard === "object" && standard !== null
+ ? (standard as Record<string, unknown>)
+ : undefined;
+}
+
+function describeMissingEmitter(standard: Record<string, unknown>): string {
+ const vendor = typeof standard.vendor === "string" ? standard.vendor : "unknown";
+ if (vendor === "zod") {
+ return "Zod 3 cannot emit an output JSON Schema. Upgrade to Zod 4 or provide a plain JSON Schema object.";
+ }
+ return `Standard Schema vendor "${vendor}" does not support JSON Schema conversion. Provide a Standard Schema implementation with JSON Schema conversion or a plain JSON Schema object.`;
+}
+
+function withoutSchemaVersion(schema: JsonObject): JsonObject {
+ const { $schema: _schemaVersion, ...canonical } = schema;
+ return canonical;
+}
diff --git a/packages/eve/src/tools/schema.ts b/packages/eve/src/tools/schema.ts
index e92648aa6..bbcec56eb 100644
--- a/packages/eve/src/tools/schema.ts
+++ b/packages/eve/src/tools/schema.ts
@@ -16,6 +16,15 @@ import type {
import { toErrorMessage } from "#shared/errors.js";
import { isObject } from "#shared/guards.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
+import {
+ emitJsonSchema,
+ getStandardSchemaProperties,
+ readJsonSchemaEmitter,
+ type SchemaDirection,
+ type SchemaResult,
+} from "#tools/schema-emission.js";
+
+export { serializeOutputSchema } from "#tools/schema-emission.js";
/**
* eve-owned schema contract for tool input and output schemas: a Standard
@@ -34,13 +43,6 @@ export type ToolSchema<Input = unknown, Output = Input> = StandardSchemaV1<Input
*/
export type ToolSchemaSource = StandardJSONSchemaV1 | StandardSchemaV1 | Record<string, unknown>;
-type SchemaDirection = "input" | "output";
-
-/** `null` and `undefined` pass through every conversion untouched. */
-type SchemaResult<TSource, TResult> = TSource extends null | undefined ? TSource : TResult;
-
-const JSON_SCHEMA_TARGET: StandardJSONSchemaV1.Target = "draft-07";
-
/**
* Resolves a source into a live input {@link ToolSchema}. Live schemas pass
* through unchanged; plain JSON Schema data becomes a {@link defineJsonSchema}
@@ -74,17 +76,6 @@ export function serializeInputSchema<T extends ToolSchemaSource | null | undefin
return serializeSchema(source, "input") as SchemaResult<T, JsonObject>;
}
-/**
- * Serializes an output schema source into canonical JSON Schema data (no
- * `$schema` key) for compiled artifacts, durable state, and protocol
- * responses. `null` and `undefined` pass through untouched.
- */
-export function serializeOutputSchema<T extends ToolSchemaSource | null | undefined>(
- source: T,
-): SchemaResult<T, JsonObject> {
- return serializeSchema(source, "output") as SchemaResult<T, JsonObject>;
-}
-
/**
* Returns whether a value implements the full {@link ToolSchema} contract:
* Standard Schema validation plus JSON Schema emission.
@@ -241,59 +232,24 @@ function serializeSchema(
return toJsonObject(source, direction);
}
-/**
- * Normalizes one source into canonical JSON Schema data. Standard Schemas
- * emit their requested direction; plain data passes through. The `$schema`
- * version key is always stripped so every eve boundary carries one canonical
- * wire form.
- */
function toJsonObject(source: ToolSchemaSource, direction: SchemaDirection): JsonObject {
- const standard = getStandardSchemaProperties(source);
- const jsonSchema = standard?.jsonSchema;
- const emit =
- typeof jsonSchema === "object" && jsonSchema !== null
- ? (jsonSchema as Record<string, unknown>)[direction]
- : undefined;
- const vendor = typeof standard?.vendor === "string" ? standard.vendor : "unknown";
- if (standard !== undefined && typeof emit !== "function" && vendor === "zod") {
- if (direction === "input") {
- // Zod 3 and early Zod 4 releases predate Standard JSON Schema. The schema
- // comes from the author's own Zod, which the author's AI SDK also uses.
- const schema = asSchema(source as Parameters<typeof asSchema>[0]);
- const { $schema: _schemaVersion, ...canonical } = parseJsonObject(schema.jsonSchema);
- return canonical;
- }
-
- throw new Error(
- "Zod 3 cannot emit an output JSON Schema. Upgrade to Zod 4 or provide a plain JSON Schema object.",
- );
- }
-
- if (standard !== undefined && typeof emit !== "function") {
- throw new Error(
- `Standard Schema vendor "${vendor}" does not support JSON Schema conversion. Provide a Standard Schema implementation with JSON Schema conversion or a plain JSON Schema object.`,
- );
+ if (direction === "input" && isLegacyZodSchema(source)) {
+ // Zod 3 and early Zod 4 releases predate Standard JSON Schema. The schema
+ // comes from the author's own Zod, which the author's AI SDK also uses.
+ const schema = asSchema(source as Parameters<typeof asSchema>[0]);
+ const { $schema: _schemaVersion, ...canonical } = parseJsonObject(schema.jsonSchema);
+ return canonical;
}
-
- const raw =
- standard === undefined
- ? parseJsonObject(source)
- : parseJsonObject(
- (emit as StandardJSONSchemaV1.Converter[SchemaDirection])({
- target: JSON_SCHEMA_TARGET,
- }),
- );
- const { $schema: _schemaVersion, ...canonical } = raw;
- return canonical;
+ return emitJsonSchema(source, direction);
}
-function getStandardSchemaProperties(value: unknown): Record<string, unknown> | undefined {
- if (typeof value !== "object" || value === null || !("~standard" in value)) return undefined;
-
- const standard = (value as Record<string, unknown>)["~standard"];
- return typeof standard === "object" && standard !== null
- ? (standard as Record<string, unknown>)
- : undefined;
+function isLegacyZodSchema(source: ToolSchemaSource): boolean {
+ const standard = getStandardSchemaProperties(source);
+ return (
+ standard !== undefined &&
+ standard.vendor === "zod" &&
+ readJsonSchemaEmitter(standard, "input") === undefined
+ );
}
// ---------------------------------------------------------------------------
diff --git a/packages/eve/src/tools/workflow-definition.test.ts b/packages/eve/src/tools/workflow-definition.test.ts
index b4daa10b6..6b57b8cb1 100644
--- a/packages/eve/src/tools/workflow-definition.test.ts
+++ b/packages/eve/src/tools/workflow-definition.test.ts
@@ -5,9 +5,9 @@ import { defineTool } from "#tools/definition.js";
import {
defineWorkflowTool,
isWorkflowToolDefinition,
+ type AgentMessageResult,
type WorkflowAgentMetadata,
type WorkflowStepToolContext,
- type TaskReceipt,
type WorkflowToolContext,
} from "#tools/workflow-definition.js";
import { normalizeToolDefinition } from "#internal/authored-definition/schema-backed.js";
@@ -21,20 +21,14 @@ describe("defineWorkflowTool", () => {
expectTypeOf(input).toEqualTypeOf<{ service: string }>();
expectTypeOf(ctx).toEqualTypeOf<WorkflowToolContext>();
expectTypeOf(ctx.agents.researcher).toEqualTypeOf<WorkflowAgentMetadata | undefined>();
- const review = ctx.agent("researcher", {
- message: "Review the deployment.",
- outputSchema: {
- properties: {
- findings: { items: { type: "string" }, type: "array" },
- score: { type: "number" },
- },
- required: ["findings"],
- type: "object",
- },
+ const review = await ctx.agent("researcher").send("Review the deployment.", {
+ outputSchema: z.object({ findings: z.array(z.string()), score: z.number().optional() }),
});
- expectTypeOf(review).toEqualTypeOf<Promise<{ findings: string[]; score?: number }>>();
- // @ts-expect-error The subagent name is the first argument, not part of the input.
- void ctx.agent({ message: "Review the deployment.", target: "researcher" });
+ expectTypeOf(await review.result()).toEqualTypeOf<
+ AgentMessageResult<{ findings: string[]; score?: number | undefined }>
+ >();
+ // @ts-expect-error The message is sent with send(), not passed to ctx.agent().
+ void ctx.agent("researcher", { message: "Review the deployment." });
// Token capabilities are available when this context is passed into a step.
void ctx.getToken;
// @ts-expect-error Workflow bodies do not have a session sandbox.
@@ -70,23 +64,18 @@ describe("defineWorkflowTool", () => {
expectTypeOf(useStepContext).parameter(0).toEqualTypeOf<WorkflowStepToolContext>();
});
- it("provides progress yields and receipt projections for background workflows", () => {
- const definition = defineWorkflowTool({
+ it("rejects the removed execution option", () => {
+ const definition = {
description: "Report a deployment",
execution: "background",
inputSchema: z.object({ service: z.string() }),
- async *execute(input, ctx) {
- expectTypeOf(input).toEqualTypeOf<{ service: string }>();
- expectTypeOf(ctx).toEqualTypeOf<WorkflowToolContext>();
- yield { status: "planning" };
- return { deployed: input.service };
- },
- toModelOutput(receipt) {
- expectTypeOf(receipt).toEqualTypeOf<TaskReceipt>();
- return { type: "text", value: receipt.taskId };
+ async execute() {
+ return null;
},
- });
- expect(isWorkflowToolDefinition(definition)).toBe(true);
+ };
+ expect(() => defineWorkflowTool(definition)).toThrow(
+ '"execution" was removed; workflow tool calls now block until they settle.',
+ );
});
it("keeps workflow capabilities off ordinary tools and top-level exports", () => {
diff --git a/packages/eve/src/tools/workflow-definition.ts b/packages/eve/src/tools/workflow-definition.ts
index f98c96915..181efd5a8 100644
--- a/packages/eve/src/tools/workflow-definition.ts
+++ b/packages/eve/src/tools/workflow-definition.ts
@@ -3,71 +3,18 @@ import type {
StandardSchemaV1,
} from "#compiled/@standard-schema/spec/index.js";
import type { Approval } from "#approval/definition.js";
-import type { JsonObject, JsonValue } from "#shared/json.js";
+import type { MessageResult, SendTurnOptions } from "#client/types.js";
+import type { JsonObject } from "#shared/json.js";
import {
stampToolDefinition,
type PublicToolDefinition,
type ToolContext,
type ToolInputRequest,
+ type ToolInputRequestOptions,
type ToolInputResponse,
} from "#tools/definition.js";
import type { ToolModelOutput } from "#tools/model-output.js";
-/** Fixed acknowledgement returned when a background task is admitted. */
-export interface TaskReceipt {
- readonly status: "working";
- readonly taskId: string;
-}
-
-export interface AgentInput {
- readonly agentId?: string;
- readonly message: string;
- readonly outputSchema?: JsonObject;
-}
-
-type JsonSchemaProperties = Readonly<Record<string, JsonObject>>;
-type JsonSchemaRequiredKeys<
- TProperties extends JsonSchemaProperties,
- TRequired,
-> = TRequired extends readonly string[] ? Extract<TRequired[number], keyof TProperties> : never;
-type Simplify<TValue> = { [TKey in keyof TValue]: TValue[TKey] };
-type JsonSchemaObjectOutput<TProperties extends JsonSchemaProperties, TRequired> = Simplify<
- {
- -readonly [TKey in JsonSchemaRequiredKeys<TProperties, TRequired>]-?: JsonSchemaOutput<
- TProperties[TKey]
- >;
- } & {
- -readonly [
- TKey in Exclude<keyof TProperties, JsonSchemaRequiredKeys<TProperties, TRequired>>
- ]?: JsonSchemaOutput<TProperties[TKey]>;
- }
->;
-
-type JsonSchemaOutput<TSchema> = TSchema extends { readonly const: infer TValue }
- ? Extract<TValue, JsonValue>
- : TSchema extends { readonly enum: readonly (infer TValue)[] }
- ? Extract<TValue, JsonValue>
- : TSchema extends {
- readonly type: "object";
- readonly properties: infer TProperties extends JsonSchemaProperties;
- readonly required?: infer TRequired;
- }
- ? JsonSchemaObjectOutput<TProperties, TRequired>
- : TSchema extends {
- readonly type: "array";
- readonly items: infer TItems extends JsonObject;
- }
- ? JsonSchemaOutput<TItems>[]
- : TSchema extends { readonly type: "string" }
- ? string
- : TSchema extends { readonly type: "integer" | "number" }
- ? number
- : TSchema extends { readonly type: "boolean" }
- ? boolean
- : TSchema extends { readonly type: "null" }
- ? null
- : JsonValue;
-
export interface WorkflowAgentMetadata {
readonly description: string;
}
@@ -78,12 +25,44 @@ export type WorkflowStepToolContext = Pick<
"abortSignal" | "callId" | "session" | "toolName" | "getToken" | "requireAuth"
>;
-interface WorkflowAgent {
- <const TOutputSchema extends JsonObject>(
- target: string,
- input: AgentInput & { readonly outputSchema: TOutputSchema },
- ): Promise<JsonSchemaOutput<TOutputSchema>>;
- (target: string, input: AgentInput): Promise<JsonValue>;
+/** Options for one message to a `ctx.agent` session. */
+export interface AgentSendOptions<TOutput = unknown> {
+ /** Structured output for the turn, as on the client's `send`. */
+ readonly outputSchema?: SendTurnOptions<TOutput>["outputSchema"];
+ /** Aborting cancels the turn this message started or joined; the turn still reports. */
+ readonly signal?: AbortSignal;
+}
+
+/**
+ * How one agent turn ended, as the client's `MessageResult` reports it:
+ * `"waiting"` when the session waits for its next message, including after a
+ * cancelled turn, which carries neither `data` nor `message`; `"completed"`
+ * when the session ended with the turn; and `"failed"` when the turn failed.
+ */
+export type AgentMessageResult<TOutput = unknown> = Pick<
+ MessageResult<TOutput>,
+ "data" | "message" | "status"
+>;
+
+/** The response to one message sent to a `ctx.agent` session. */
+export interface AgentResponse<TOutput = unknown> {
+ /** Resolves when the turn the message started or joined ends. */
+ result(): Promise<AgentMessageResult<TOutput>>;
+}
+
+/**
+ * A session the workflow run owns, opened by its first `send` and ended when
+ * the run finishes. Only the run can address it.
+ */
+export interface AgentSession {
+ /**
+ * Delivers a message. It joins the session's running turn, whose result the
+ * response resolves, or starts the next turn when the session is idle.
+ */
+ send<TOutput = unknown>(
+ message: string,
+ options?: AgentSendOptions<TOutput>,
+ ): Promise<AgentResponse<TOutput>>;
}
/**
@@ -94,62 +73,44 @@ export type WorkflowToolContext = Pick<
ToolContext,
"abortSignal" | "callId" | "session" | "toolName" | "getToken" | "requireAuth"
> & {
- /** Invoke an agent by its invocation name. */
- agent: WorkflowAgent;
+ /**
+ * Returns a new session with the agent of this invocation name. Nothing
+ * starts until the first `send`.
+ */
+ agent(name: string): AgentSession;
/** Metadata for agents callable by this workflow, including hidden agents. */
agents: Readonly<Record<string, WorkflowAgentMetadata>>;
- /** Ask the human on the session's channel; awaiting the answer suspends the run. */
- ask(request: ToolInputRequest): PromiseLike<ToolInputResponse>;
+ /**
+ * Ask the human on the session's channel; awaiting the answer suspends the
+ * run. The request is withdrawn, resolving as `cancelled`, when
+ * `options.signal` or the call's `abortSignal` aborts.
+ */
+ ask(request: ToolInputRequest, options?: ToolInputRequestOptions): PromiseLike<ToolInputResponse>;
+ /**
+ * Aborts once, on the first steering message that arrives while the turn
+ * waits on this call. What it means is the tool's choice: a body that
+ * ignores it keeps going, and one that should stop early races or passes it.
+ */
+ readonly interruptSignal: AbortSignal;
};
const WORKFLOW_TOOL_BRAND = Symbol.for("eve:workflow-tool-brand");
/** A static tool whose executor runs as a durable workflow. Its executor must start with "use workflow". */
-export interface BlockingWorkflowToolDefinition<
+export interface WorkflowToolDefinition<
TInput = unknown,
TOutput = unknown,
> extends PublicToolDefinition<TInput, TOutput> {
readonly [WORKFLOW_TOOL_BRAND]: true;
- readonly execution?: never;
execute(input: TInput, ctx: WorkflowToolContext): Promise<TOutput> | AsyncIterable<TOutput>;
approval?: Approval<unknown extends TInput ? Record<string, unknown> : TInput>;
toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;
}
-export type BackgroundWorkflowToolDefinition<TInput, TOutput> = PublicToolDefinition<
- TInput,
- TaskReceipt
-> & {
- readonly [WORKFLOW_TOOL_BRAND]: true;
- readonly execution: "background";
- execute(input: TInput, ctx: WorkflowToolContext): Promise<TOutput> | AsyncIterable<unknown>;
- approval?: Approval<unknown extends TInput ? Record<string, unknown> : TInput>;
- toModelOutput?: (output: TaskReceipt) => ToolModelOutput | Promise<ToolModelOutput>;
-};
-
-/** A static tool whose executor runs as a durable workflow. */
-export type WorkflowToolDefinition<TInput = unknown, TOutput = unknown> =
- | BlockingWorkflowToolDefinition<TInput, TOutput>
- | BackgroundWorkflowToolDefinition<TInput, TOutput>;
-
-type Unbranded<T> = T extends unknown ? Omit<T, typeof WORKFLOW_TOOL_BRAND> : never;
-type BackgroundReturn<T> =
- T extends AsyncGenerator<unknown, infer Output>
- ? Output
- : T extends AsyncIterable<unknown>
- ? null
- : Awaited<T>;
-type BackgroundDefinition<TInput, TReturn> = Omit<
- BackgroundWorkflowToolDefinition<TInput, BackgroundReturn<TReturn>>,
- typeof WORKFLOW_TOOL_BRAND | "execute"
-> & {
- execute(input: TInput, ctx: WorkflowToolContext): TReturn;
-};
-
type WorkflowReturn<T> = T extends AsyncIterable<infer Output> ? Output : Awaited<T>;
type Schema = StandardSchemaV1<unknown, unknown> | StandardJSONSchemaV1<unknown, unknown>;
type Definition<TInput, TReturn> = Omit<
- BlockingWorkflowToolDefinition<TInput, WorkflowReturn<TReturn>>,
+ WorkflowToolDefinition<TInput, WorkflowReturn<TReturn>>,
typeof WORKFLOW_TOOL_BRAND | "execute"
> & {
execute(input: TInput, ctx: WorkflowToolContext): TReturn;
@@ -169,25 +130,10 @@ export function defineWorkflowTool<
inputSchema: TInputSchema;
outputSchema: TOutputSchema;
},
-): BlockingWorkflowToolDefinition<
+): WorkflowToolDefinition<
StandardSchemaV1.InferOutput<TInputSchema>,
StandardJSONSchemaV1.InferOutput<TOutputSchema>
>;
-export function defineWorkflowTool<
- TSchema extends Schema,
- TReturn extends Promise<unknown> | AsyncIterable<unknown>,
->(
- definition: Omit<
- BackgroundDefinition<StandardSchemaV1.InferOutput<TSchema>, TReturn>,
- "inputSchema"
- > & { inputSchema: TSchema },
-): BackgroundWorkflowToolDefinition<
- StandardSchemaV1.InferOutput<TSchema>,
- BackgroundReturn<TReturn>
->;
-export function defineWorkflowTool<TReturn extends Promise<unknown> | AsyncIterable<unknown>>(
- definition: BackgroundDefinition<Record<string, unknown>, TReturn> & { inputSchema: JsonObject },
-): BackgroundWorkflowToolDefinition<Record<string, unknown>, BackgroundReturn<TReturn>>;
export function defineWorkflowTool<
TSchema extends Schema,
TReturn extends Promise<unknown> | AsyncIterable<unknown>,
@@ -195,16 +141,19 @@ export function defineWorkflowTool<
definition: Omit<Definition<StandardSchemaV1.InferOutput<TSchema>, TReturn>, "inputSchema"> & {
inputSchema: TSchema;
},
-): BlockingWorkflowToolDefinition<StandardSchemaV1.InferOutput<TSchema>, WorkflowReturn<TReturn>>;
+): WorkflowToolDefinition<StandardSchemaV1.InferOutput<TSchema>, WorkflowReturn<TReturn>>;
export function defineWorkflowTool<TReturn extends Promise<unknown> | AsyncIterable<unknown>>(
definition: Definition<Record<string, unknown>, TReturn> & { inputSchema: JsonObject },
-): BlockingWorkflowToolDefinition<Record<string, unknown>, WorkflowReturn<TReturn>>;
+): WorkflowToolDefinition<Record<string, unknown>, WorkflowReturn<TReturn>>;
export function defineWorkflowTool<TInput = unknown, TOutput = unknown>(
- definition: Unbranded<WorkflowToolDefinition<TInput, TOutput>>,
+ definition: Omit<WorkflowToolDefinition<TInput, TOutput>, typeof WORKFLOW_TOOL_BRAND>,
): WorkflowToolDefinition<TInput, TOutput>;
export function defineWorkflowTool<TInput, TOutput>(
- definition: Unbranded<WorkflowToolDefinition<TInput, TOutput>>,
+ definition: Omit<WorkflowToolDefinition<TInput, TOutput>, typeof WORKFLOW_TOOL_BRAND>,
): WorkflowToolDefinition<TInput, TOutput> {
+ if ("execution" in definition) {
+ throw new Error('"execution" was removed; workflow tool calls now block until they settle.');
+ }
stampToolDefinition(definition, "defineWorkflowTool");
return Object.assign(definition, { [WORKFLOW_TOOL_BRAND]: true as const });
}
diff --git a/packages/eve/src/tracing/agent-invocation-coordinator.test.ts b/packages/eve/src/tracing/agent-invocation-coordinator.test.ts
index ad4ba5f58..e9f72aca8 100644
--- a/packages/eve/src/tracing/agent-invocation-coordinator.test.ts
+++ b/packages/eve/src/tracing/agent-invocation-coordinator.test.ts
@@ -7,7 +7,6 @@ import { prepareAgentInvocationTrace } from "#tracing/agent-invocation-coordinat
import { settleAgentInvocationTrace } from "#tracing/agent-invocation-terminal.js";
import { deriveAgentActionSpanId } from "#tracing/agent-span-id-generator.js";
import { ContextAgentTraceStateStore } from "#tracing/agent-trace-context-store.js";
-import { deriveTaskId } from "#tasks/task-id.js";
import { actionIdempotencyKey } from "#instrumentation/lifecycle.js";
import type { ConversationContext } from "#shared/conversation-context.js";
@@ -21,12 +20,11 @@ const conversation: ConversationContext = {
const sessionState = {
"eve.workflowTool": {
- version: 3,
+ version: 4,
runs: [
{
callId: "workflow",
toolName: "coordinate",
- lifetime: "turn" as const,
origin: { turnId: "turn-1", stepIndex: 0 },
address: { runId: "workflow-run", hookToken: "workflow-hook" },
},
@@ -167,55 +165,6 @@ describe("agent invocation trace coordinator", () => {
});
});
- it("uses the persisted action anchor after the live action is gone", async () => {
- const context = new ContextContainer();
- await contextStorage.run(context, () => {
- const store = new ContextAgentTraceStateStore();
- const action = outerAction();
- store.setAction(outerKey, action);
- store.setActionAnchor(outerKey, action);
- store.deleteAction(outerKey);
- });
-
- const prepared = prepareAgentInvocationTrace({
- invocation: { callId: "workflow:background", kind: "subagent-call", name: "research" },
- ownerId: "background-task",
- startTimeMs: 2,
- serializedContext: serializeContext(context),
- sessionId: "session-1",
- taskId: deriveTaskId({
- callId: "workflow",
- parentSessionId: "session-1",
- parentTurnId: "turn-1",
- }),
- turnId: "later-turn",
- });
-
- expect(prepared.dispatch.parentTraceContext?.spanId).toBe(
- deriveAgentActionSpanId("session-1", "turn-1", "workflow:background"),
- );
- await expect(readInvocations(prepared.serializedContext)).resolves.toEqual([
- expect.objectContaining({
- callId: "workflow:background",
- parentActionCallId: "workflow",
- }),
- ]);
- const failed = prepared.fail({
- callId: "workflow:background",
- isError: true,
- kind: "subagent-result",
- origin: "dispatch",
- output: "unreachable",
- subagentName: "research",
- });
- await expect(readInvocations(failed)).resolves.toEqual([
- expect.objectContaining({
- turnId: "turn-1",
- terminal: expect.objectContaining({ outcome: "failed" }),
- }),
- ]);
- });
-
it("does not infer an outer call from caller-chosen invocation IDs", async () => {
const prepared = prepareAgentInvocationTrace({
invocation: { callId: "workflow:unowned", kind: "subagent-call", name: "research" },
diff --git a/packages/eve/src/tracing/agent-invocation-coordinator.ts b/packages/eve/src/tracing/agent-invocation-coordinator.ts
index 33353b594..6c446134a 100644
--- a/packages/eve/src/tracing/agent-invocation-coordinator.ts
+++ b/packages/eve/src/tracing/agent-invocation-coordinator.ts
@@ -13,7 +13,6 @@ import {
import { deriveAgentActionSpanId } from "#tracing/agent-span-id-generator.js";
import {
readActionTraceContext,
- readTaskActionTrace,
readTurnTraceContext,
recordActionInvocationKind,
recordNestedAgentInvocation,
@@ -41,7 +40,6 @@ export function prepareAgentInvocationTrace(input: {
readonly sessionId: string;
readonly sessionState?: SessionStateMap;
readonly startTimeMs: number;
- readonly taskId?: string;
readonly turnId: string;
}): {
readonly dispatch: AgentChildTraceDispatch;
@@ -49,17 +47,10 @@ export function prepareAgentInvocationTrace(input: {
readonly serializedContext: Record<string, unknown>;
} {
const conversationId = readConversationId(input.serializedContext[ConversationIdKey.name]);
- const taskAction =
- input.taskId === undefined
- ? undefined
- : readTaskActionTrace(input.serializedContext, input.sessionId, input.taskId);
- const parentActionCallId =
- input.taskId === undefined
- ? getBlockingWorkflowToolRuns(input.sessionState).find(
- (run) => run.address.runId === input.ownerId,
- )?.callId
- : taskAction?.callId;
- const turnId = taskAction?.turnId ?? input.turnId;
+ const parentActionCallId = getBlockingWorkflowToolRuns(input.sessionState).find(
+ (run) => run.address.runId === input.ownerId,
+ )?.callId;
+ const { turnId } = input;
const parentTurnContext = readTurnTraceContext(input.serializedContext, input.sessionId, turnId);
const conversation = input.conversation;
const liveAudience = conversation?.audience ?? "unknown";
@@ -111,28 +102,12 @@ export function prepareAgentInvocationTrace(input: {
turnId,
input.invocation.callId,
);
- const storedParentTraceContext = callerTraceContext ?? outerTrace;
- const forwardedTracePolicy = readForwardedTraceAssertion(
- storedParentTraceContext?.forwardedTracePolicy,
- );
- const parentTraceContext =
- storedParentTraceContext?.decision === undefined
- ? storedParentTraceContext
- : {
- ...storedParentTraceContext,
- decision: applyLiveDeliveryAudienceCeiling(
- storedParentTraceContext.decision,
- liveAudience,
- forwardedTracePolicy,
- environment,
- ),
- };
return {
- dispatch: {
+ dispatch: toChildTraceDispatch({
+ conversation,
conversationId,
- originAudience: forwardedTracePolicy?.originAudience ?? liveAudience,
- parentTraceContext,
- },
+ stored: callerTraceContext ?? outerTrace,
+ }),
fail: (result) =>
recordNestedAgentInvocationTerminal({
callId: input.invocation.callId,
@@ -148,3 +123,53 @@ export function prepareAgentInvocationTrace(input: {
serializedContext,
};
}
+
+/**
+ * The trace dispatch for sessions a workflow tool call's run opens with
+ * `ctx.agent`, read from the calling session when the run starts.
+ */
+export function resolveToolCallAgentTrace(input: {
+ readonly callId: string;
+ readonly conversation?: ConversationContext;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionId: string;
+ readonly turnId: string;
+}): AgentChildTraceDispatch {
+ const { serializedContext, sessionId, turnId } = input;
+ return toChildTraceDispatch({
+ conversation: input.conversation,
+ conversationId: readConversationId(serializedContext[ConversationIdKey.name]),
+ stored:
+ readActionTraceContext(serializedContext, sessionId, turnId, input.callId) ??
+ readTurnTraceContext(serializedContext, sessionId, turnId),
+ });
+}
+
+/** Caps a stored parent trace context to the live delivery audience. */
+function toChildTraceDispatch(input: {
+ readonly conversation?: ConversationContext;
+ readonly conversationId?: string;
+ readonly stored?: SessionTraceContext;
+}): AgentChildTraceDispatch {
+ const { stored } = input;
+ const liveAudience = input.conversation?.audience ?? "unknown";
+ const environment = input.conversation?.environment ?? "production";
+ const forwardedTracePolicy = readForwardedTraceAssertion(stored?.forwardedTracePolicy);
+ const parentTraceContext =
+ stored?.decision === undefined
+ ? stored
+ : {
+ ...stored,
+ decision: applyLiveDeliveryAudienceCeiling(
+ stored.decision,
+ liveAudience,
+ forwardedTracePolicy,
+ environment,
+ ),
+ };
+ return {
+ conversationId: input.conversationId,
+ originAudience: forwardedTracePolicy?.originAudience ?? liveAudience,
+ parentTraceContext,
+ };
+}
diff --git a/packages/eve/src/tracing/agent-otel-content.test.ts b/packages/eve/src/tracing/agent-otel-content.test.ts
index f19bae7b1..966190808 100644
--- a/packages/eve/src/tracing/agent-otel-content.test.ts
+++ b/packages/eve/src/tracing/agent-otel-content.test.ts
@@ -14,7 +14,6 @@ const FRAMEWORK_MESSAGE_KINDS = [
"context.state",
"context.compaction",
"memory.load",
- "execution.background_task",
"execution.continuation",
"execution.retry",
] as const satisfies readonly FrameworkMessageKind[];
@@ -60,13 +59,13 @@ describe("GenAI message attributes", () => {
genAiInputMessagesAttribute([
{ content: "A real user message.", kind: "user", role: "user" },
{
- content: "A background task completed.",
- kind: "execution.background_task",
+ content: "Continue the interrupted turn.",
+ kind: "execution.continuation",
role: "user",
},
]),
).toBe(
- '[{"kind":"user","parts":[{"content":"A real user message.","type":"text"}],"role":"user"},{"kind":"execution.background_task","parts":[{"content":"A background task completed.","type":"text"}],"role":"user"}]',
+ '[{"kind":"user","parts":[{"content":"A real user message.","type":"text"}],"role":"user"},{"kind":"execution.continuation","parts":[{"content":"Continue the interrupted turn.","type":"text"}],"role":"user"}]',
);
});
diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.ts
index 2dda5c680..70752a202 100644
--- a/packages/eve/src/tracing/agent-otel-provider.test.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts
@@ -65,12 +65,6 @@ import {
sessionIdempotencyKey,
turnIdempotencyKey,
} from "#instrumentation/lifecycle.js";
-import {
- rememberInstrumentationActionScope,
- rememberInstrumentationBackgroundTask,
- takeInstrumentationActionScopeForTask,
-} from "#instrumentation/state.js";
-import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";
import { isRuntimeWorkflowToolAction } from "#shared/action-types.js";
const traceContext = (audience: ChannelAudience = "public") => ({
@@ -1562,12 +1556,11 @@ describe("createAgentOtelInstrumentation", () => {
sessionId: scope.sessionId,
sessionState: {
"eve.workflowTool": {
- version: 3,
+ version: 4,
runs: [
{
callId: "workflow",
toolName: "coordinate",
- lifetime: "turn" as const,
origin: { turnId: "turn-1", stepIndex: 0 },
address: { runId: "workflow-run", hookToken: "workflow-hook" },
},
@@ -2691,86 +2684,8 @@ describe("createAgentOtelInstrumentation", () => {
expect(byName(spans, "agent.step")).toHaveLength(1);
});
- it("keeps a background action open after its initiating turn is cancelled", async () => {
- const runtime = createRuntime();
- const ctx = new ContextContainer();
- const scope: InstrumentationAttemptScope = {
- attemptId: "session-1:turn-1:0:0",
- attemptIndex: 0,
- sessionId: "session-1",
- stepIndex: 0,
- turnId: "turn-1",
- };
- const actionKey = actionIdempotencyKey(scope.sessionId, scope.turnId, "tool-1");
-
- await contextStorage.run(ctx, async () => {
- await publishTurnStarted({
- hooks: runtime.hooks,
- sessionId: scope.sessionId,
- turnId: scope.turnId,
- turnSequence: 0,
- });
- await runtime.hooks.publish({
- idempotencyKey: attemptIdempotencyKey(scope),
- operation: { modelId: "model", operationId: "ai.streamText", provider: "test" },
- scope,
- type: "step.attempt.started",
- });
- rememberInstrumentationActionScope(actionKey, scope);
- await runtime.hooks.publish({
- callId: "tool-1",
- idempotencyKey: actionKey,
- input: { report: "weekly" },
- kind: "tool-call",
- name: "publish",
- scope,
- type: "action.started",
- });
- rememberInstrumentationBackgroundTask("task-1", { idempotencyKey: actionKey, scope });
- await runtime.hooks.publish({
- idempotencyKey: attemptIdempotencyKey(scope),
- scope,
- type: "step.attempt.completed",
- });
- await runtime.hooks.publish({
- idempotencyKey: turnIdempotencyKey(scope.sessionId, scope.turnId),
- sessionId: scope.sessionId,
- turnId: scope.turnId,
- type: "turn.cancelled",
- });
- });
- await runtime.provider.forceFlush();
- expect(byName(runtime.exporter.getFinishedSpans(), "agent.action")).toHaveLength(0);
-
- const restored = await deserializeContext(
- preserveSerializedBackgroundTaskObservabilityState({}, serializeContext(ctx), [
- { taskId: "task-1" },
- ]),
- );
- const acceptedAtMs = Date.now() + 1_000;
- await contextStorage.run(restored, async () => {
- const correlation = takeInstrumentationActionScopeForTask("task-1")!;
- await runtime.hooks.publish({
- acceptedAtMs,
- idempotencyKey: correlation.idempotencyKey,
- outcome: "completed",
- output: { output: { reportId: "report-1" }, type: "result" },
- scope: correlation.scope,
- type: "action.completed",
- });
- });
- await runtime.provider.forceFlush();
-
- const action = byName(runtime.exporter.getFinishedSpans(), "agent.action")[0]!;
- expect(action.attributes).toMatchObject({
- "agent.action.outcome": "completed",
- "gen_ai.tool.call.result": expect.stringContaining("report-1"),
- });
- expect(nanos(action.endTime)).toBe(BigInt(acceptedAtMs) * 1_000_000n);
- });
-
- it("records serialized task error detail only when output content is admitted", async () => {
- const taskError = {
+ it("records serialized action error detail only when output content is admitted", async () => {
+ const publishError = {
code: "PUBLISH_FAILED",
detail: "x".repeat(CONTENT_ATTRIBUTE_LIMIT * 2),
message: "private publish failure",
@@ -2799,8 +2714,8 @@ describe("createAgentOtelInstrumentation", () => {
type: "action.started",
});
await runtime.hooks.publish({
- error: taskError,
- errorCode: "BACKGROUND_TASK_FAILED",
+ error: publishError,
+ errorCode: "PUBLISH_FAILED",
idempotencyKey: actionIdempotencyKey(sessionId, scope.turnId, "tool-1"),
outcome: "failed",
scope,
@@ -2812,9 +2727,9 @@ describe("createAgentOtelInstrumentation", () => {
const recorded = await run(createRuntime(), "recorded");
expect(recorded.attributes).toMatchObject({
- "agent.action.error.code": "BACKGROUND_TASK_FAILED",
+ "agent.action.error.code": "PUBLISH_FAILED",
"agent.action.outcome": "failed",
- "error.type": "BACKGROUND_TASK_FAILED",
+ "error.type": "PUBLISH_FAILED",
});
expect(recorded.status.code).toBe(SpanStatusCode.ERROR);
expect(recorded.status.message).toContain("private publish failure");
@@ -2824,7 +2739,7 @@ describe("createAgentOtelInstrumentation", () => {
expect.objectContaining({
attributes: expect.objectContaining({
"exception.message": recorded.status.message,
- "exception.type": "BACKGROUND_TASK_FAILED",
+ "exception.type": "PUBLISH_FAILED",
}),
name: "exception",
}),
@@ -2839,9 +2754,9 @@ describe("createAgentOtelInstrumentation", () => {
"redacted",
);
expect(redacted.attributes).toMatchObject({
- "agent.action.error.code": "BACKGROUND_TASK_FAILED",
+ "agent.action.error.code": "PUBLISH_FAILED",
"agent.action.outcome": "failed",
- "error.type": "BACKGROUND_TASK_FAILED",
+ "error.type": "PUBLISH_FAILED",
});
expect(redacted.status).toEqual({ code: SpanStatusCode.ERROR });
expect(redacted.events.filter((event) => event.name === "exception")).toEqual([]);
diff --git a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts
index 19ab071b4..646495629 100644
--- a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts
+++ b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts
@@ -367,12 +367,11 @@ describe("exported agent telemetry contract", () => {
turnId: "turn_0",
sessionState: {
"eve.workflowTool": {
- version: 3,
+ version: 4,
runs: [
{
callId: "workflow",
toolName: "coordinate",
- lifetime: "turn" as const,
origin: { turnId: "turn-1", stepIndex: 0 },
address: { runId: "workflow-run", hookToken: "hook" },
},
diff --git a/packages/eve/src/tracing/agent-trace-context-store.ts b/packages/eve/src/tracing/agent-trace-context-store.ts
index 1a274496b..b7bbde888 100644
--- a/packages/eve/src/tracing/agent-trace-context-store.ts
+++ b/packages/eve/src/tracing/agent-trace-context-store.ts
@@ -13,9 +13,8 @@ import type {
AgentTurnTraceState,
} from "#tracing/agent-trace-state.js";
import { actionIdempotencyKey } from "#instrumentation/lifecycle.js";
-import { deriveTaskId } from "#tasks/task-id.js";
import type { SessionStateMap } from "#harness/types.js";
-import { getBlockingWorkflowToolRuns, getBackgroundTasks } from "#harness/workflow-tool-runs.js";
+import { getBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";
import { createLogger } from "#internal/logging.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
@@ -38,7 +37,7 @@ const AgentTraceContextKey = new ContextKey<AgentTraceContextState>(AGENT_TRACE_
},
});
-/** Run after task-provider commits, so a returned background receipt keeps its anchor. */
+/** Run after task-provider commits, so a pending workflow tool call keeps its anchor. */
export function pruneAgentTraceState(
context: ContextAccessor,
sessionId: string,
@@ -62,24 +61,12 @@ function pruneTraceOwnership(
const state = context.get(AgentTraceContextKey);
if (state === undefined) return;
const calls = new Set(getBlockingWorkflowToolRuns(sessionState).map((run) => run.callId));
- const tasks = new Set(
- getBackgroundTasks(sessionState)
- .query({ state: "working" })
- .map((task) => task.taskId),
- );
const actionAnchors = Object.fromEntries(
Object.entries(state.actionAnchors).filter(
([key, action]) =>
action.sessionId !== sessionId ||
state.actions[key] !== undefined ||
- calls.has(action.callId) ||
- tasks.has(
- deriveTaskId({
- callId: action.callId,
- parentSessionId: sessionId,
- parentTurnId: action.turnId,
- }),
- ),
+ calls.has(action.callId),
),
);
const retainedCalls = new Set(
@@ -156,24 +143,6 @@ export function readActionTraceContext(
);
}
-/** Task IDs already bind the originating call and turn, including after that turn ends. */
-export function readTaskActionTrace(
- serializedContext: Readonly<Record<string, unknown>>,
- sessionId: string,
- taskId: string,
-): AgentActionTraceState | undefined {
- const state = deserializeAgentTraceContextState(serializedContext[AgentTraceContextKey.name]);
- return Object.values(state.actionAnchors).find(
- (action) =>
- action.sessionId === sessionId &&
- deriveTaskId({
- callId: action.callId,
- parentSessionId: sessionId,
- parentTurnId: action.turnId,
- }) === taskId,
- );
-}
-
export function recordNestedAgentInvocation(input: {
readonly callId: string;
readonly kind: "remote-agent-call" | "subagent-call";
diff --git a/packages/eve/src/tracing/agent-trace-retention.test.ts b/packages/eve/src/tracing/agent-trace-retention.test.ts
index 56b5883ad..44e421f04 100644
--- a/packages/eve/src/tracing/agent-trace-retention.test.ts
+++ b/packages/eve/src/tracing/agent-trace-retention.test.ts
@@ -6,7 +6,6 @@ import {
pruneAgentTraceState,
} from "#tracing/agent-trace-context-store.js";
import { AGENT_TRACE_CONTEXT_KEY } from "#tracing/agent-trace-context-codec.js";
-import { deriveTaskId } from "#tasks/task-id.js";
import { AgentTraceSpanProcessor } from "#tracing/agent-trace-span-processor.js";
const anchor = {
@@ -60,49 +59,6 @@ describe("trace retention by live work", () => {
expect(serializeContext(context)[AGENT_TRACE_CONTEXT_KEY]).toMatchObject({ actionAnchors: {} });
});
- it("keeps background anchors until their recorded task finishes", () => {
- const context = new ContextContainer();
- contextStorage.run(context, () =>
- new ContextAgentTraceStateStore().setActionAnchor("key", anchor),
- );
- const task = {
- callId: deriveTaskId({ callId: "call", parentSessionId: "session", parentTurnId: "turn" }),
- toolName: "workflow",
- lifetime: "session" as const,
- origin: { turnId: "turn", stepIndex: 0 },
- address: { runId: "task-run", hookToken: "task-token" },
- task: {
- dispatchContext: { auth: { current: null, initiator: null } },
- taskId: deriveTaskId({ callId: "call", parentSessionId: "session", parentTurnId: "turn" }),
- metadata: { kind: "tool", name: "workflow" },
- },
- };
- pruneAgentTraceState(context, "session", {
- "eve.workflowTool": { version: 3, runs: [task] },
- });
- expect(serializeContext(context)[AGENT_TRACE_CONTEXT_KEY]).toMatchObject({
- actionAnchors: { key: anchor },
- });
- pruneAgentTraceState(context, "session", {
- "eve.workflowTool": {
- version: 3,
- runs: [
- {
- ...task,
- task: {
- ...task.task,
- outcome: {
- status: "completed",
- lastOutput: { type: "result", data: "done" },
- },
- },
- },
- ],
- },
- });
- expect(serializeContext(context)[AGENT_TRACE_CONTEXT_KEY]).toMatchObject({ actionAnchors: {} });
- });
-
it("unpins completed activation traces only after the writer flushes", async () => {
const processor = new AgentTraceSpanProcessor([]);
for (let index = 0; index < 1000; index++) {
diff --git a/packages/eve/src/tracing/local-trace-analysis.test.ts b/packages/eve/src/tracing/local-trace-analysis.test.ts
index 050da718c..3366a3b3d 100644
--- a/packages/eve/src/tracing/local-trace-analysis.test.ts
+++ b/packages/eve/src/tracing/local-trace-analysis.test.ts
@@ -144,7 +144,7 @@ describe("analyzeLocalTrace", () => {
expect(analysis.records[0]).toMatchObject({ category: "tool", toolName: "web_search" });
});
- it("preserves a background action lifetime without adding it to tool work", () => {
+ it("preserves a subagent action lifetime without adding it to tool work", () => {
const analysis = analyzeLocalTrace(traceId, [
span({
attributes: { "agent.action.kind": "subagent-call", "agent.action.name": "worker" },
diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.ts
index f49cd90bc..a4a92b1a7 100644
--- a/packages/eve/test/runtime-subagent-registry.test.ts
+++ b/packages/eve/test/runtime-subagent-registry.test.ts
@@ -14,7 +14,7 @@ const SUBAGENT_TOOL_INPUT_SCHEMA = {
agentId: {
type: ["string", "null"],
description:
- "The id of an existing agent from the <agents> list or a task receipt. A message to a busy agent steers it: its previous task is cancelled and the updated work runs in the same child session. Omit this field (or pass null or an empty string) to start a new agent.",
+ "The id of an existing agent from the <agents> list. Omit this field (or pass null or an empty string) to start a new agent.",
},
message: {
type: "string",
@@ -58,9 +58,7 @@ describe("createRuntimeSubagentRegistry", () => {
expect(registry.preparedTools).toMatchObject([
{
- description:
- "Investigate one task in depth.\n\nThis call starts a background task and returns a task receipt immediately.",
- execution: "background",
+ description: "Investigate one task in depth.",
inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
kind: "subagent",
logicalPath: "subagents/researcher",
@@ -69,9 +67,7 @@ describe("createRuntimeSubagentRegistry", () => {
sourceId: "subagents/researcher",
},
{
- description:
- "Review one draft for clarity.\n\nThis call starts a background task and returns a task receipt immediately.",
- execution: "background",
+ description: "Review one draft for clarity.",
inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
kind: "subagent",
logicalPath: "subagents/reviewer",
@@ -99,7 +95,7 @@ describe("createRuntimeSubagentRegistry", () => {
).toThrowError(RuntimeRegistryError);
});
- it("always prepares subagent tools for background execution", () => {
+ it("prepares subagent tools as workflow tools", () => {
const definition = createResolvedRuntimeSubagentNode({
description: "Investigate one task in depth.",
logicalPath: "subagents/researcher",
@@ -110,7 +106,6 @@ describe("createRuntimeSubagentRegistry", () => {
const prepared = createPreparedRuntimeSubagentTool(definition);
- expect(prepared.execution).toBe("background");
expect(prepared.task).toEqual({
nodeId: definition.nodeId,
workflowId: expect.stringContaining("subagentToolExecuteWorkflow"),
diff --git a/packages/eve/test/runtime-tool-registry.test.ts b/packages/eve/test/runtime-tool-registry.test.ts
index 69176b9c4..a79977188 100644
--- a/packages/eve/test/runtime-tool-registry.test.ts
+++ b/packages/eve/test/runtime-tool-registry.test.ts
@@ -46,22 +46,22 @@ describe("createRuntimeToolRegistry", () => {
});
});
- it("carries delegated-task-child availability into the prepared tool descriptor", async () => {
+ it("carries root-session availability into the prepared tool descriptor", async () => {
const registry = await createRuntimeToolRegistry({
tools: [
createResolvedToolDefinition({
behavior: {
- availability: ["delegated-task-child"],
+ availability: ["root-session"],
},
- logicalPath: "tools/child_only.ts",
- name: "child_only",
- sourceId: "tools/child_only.ts",
+ logicalPath: "tools/root_only.ts",
+ name: "root_only",
+ sourceId: "tools/root_only.ts",
}),
],
});
expect(registry.preparedTools[0]?.behavior).toEqual({
- availability: ["delegated-task-child"],
+ availability: ["root-session"],
handling: undefined,
presentation: undefined,
});
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 f67a837cc..9ce41058d 100644
--- a/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts
+++ b/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts
@@ -73,7 +73,6 @@ describe("eve dist single-chunk module evaluation", () => {
// workflow's `steps.mjs`.
const stepSources = [
"src/internal/workflow/builtins.ts",
- "src/subagents/callback-step.ts",
"src/subagents/adapter.ts",
"src/execution/session/turn.ts",
"src/execution/session/entry.ts",
diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
index 818ab6cd2..613872e01 100644
--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts
+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
@@ -179,7 +179,7 @@ describe("compiler artifacts", () => {
kind: "workflow-tool",
workflowId: `workflow//${packageInfo.name}@${packageInfo.version}//executeSleepTool`,
},
- shape: { lifetime: "step", suspend: "workflow" },
+ shape: { suspend: "workflow" },
},
logicalPath: "tools/sleep.mjs",
name: "sleep",
diff --git a/packages/eve/test/scenarios/steering.scenario.test.ts b/packages/eve/test/scenarios/steering.scenario.test.ts
index 24f3df89a..17d187290 100644
--- a/packages/eve/test/scenarios/steering.scenario.test.ts
+++ b/packages/eve/test/scenarios/steering.scenario.test.ts
@@ -7,9 +7,9 @@ import { startEveDev } from "./dev-server-harness.js";
const scenarioApp = useScenarioApp();
describe("durable generation steering", () => {
- it("does not repeat a model step when background children wake the owner mid-lease", async () => {
+ it("does not repeat a model step when subagent children wake the owner mid-lease", async () => {
const app = await scenarioApp({
- name: "steering-background-wakes",
+ name: "steering-child-wakes",
installDependencies: true,
files: {
"agent/instructions.md": "Delegate the five work items.\n",
@@ -29,7 +29,7 @@ export default defineAgent({
"agent/subagents/worker/agent.ts": `import { defineAgent } from "eve";
import { mockModel } from "eve/evals";
export default defineAgent({
- description: "Complete a work item in the background.",
+ description: "Complete a work item.",
model: mockModel(async () => {
await new Promise(resolve => setTimeout(resolve, 2000));
return "Work complete";
@@ -43,7 +43,7 @@ export default defineAgent({
EVE_MOCK_AUTHORED_MODELS: "",
NODE_ENV: "production",
// A one-second lease expires mid-step, so the ownership backstop
- // races the background wakes into the single-flight guard.
+ // races the child wakes into the single-flight guard.
WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS: "1",
},
});
diff --git a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts
index 50daa2ccf..24b5d8f38 100644
--- a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts
+++ b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts
@@ -174,20 +174,20 @@ describe("turn cancellation descendant cascade", () => {
].join("\n"),
});
const parentIterator = response[Symbol.asyncIterator]();
- const called = await readSubagentCalls({
+ const started = await readAgentStarts({
count: 2,
iterator: parentIterator,
- label: "local and remote subagent dispatch",
+ label: "local and remote agent sessions",
});
- const localCalled = called.find((event) => event.data.remote === undefined);
- const remoteCalled = called.find((event) => event.data.remote !== undefined);
- if (localCalled === undefined || remoteCalled === undefined) {
- throw new Error("Expected one local and one remote subagent.called event.");
+ const localStarted = started.find((event) => event.data.remote === undefined);
+ const remoteStarted = started.find((event) => event.data.remote !== undefined);
+ if (localStarted === undefined || remoteStarted === undefined) {
+ throw new Error("Expected one local and one remote agent.started event.");
}
- expect(remoteCalled.data.remote?.url).toBe(remoteServer.url);
+ expect(remoteStarted.data.remote?.url).toBe(remoteServer.url);
const localIterator = parentClient.sessions
- .attach(localCalled.data.childSessionId)
+ .attach(localStarted.data.sessionId)
.stream()
[Symbol.asyncIterator]();
@@ -196,7 +196,7 @@ describe("turn cancellation descendant cascade", () => {
host: remoteServer.url,
});
const remoteIterator = remoteClient.sessions
- .attach(remoteCalled.data.childSessionId)
+ .attach(remoteStarted.data.sessionId)
.stream()
[Symbol.asyncIterator]();
await Promise.all([
@@ -241,7 +241,6 @@ describe("turn cancellation descendant cascade", () => {
expectCancellationBoundary(localEvents);
expectCancellationBoundary(remoteEvents);
expectCancellationBoundary(parentEvents);
- expect(parentEvents.some((event) => event.type === "subagent.completed")).toBe(false);
const followUp = await (
await parentSession.send("Reply with the exact string `still-alive` and nothing else.")
@@ -290,7 +289,7 @@ describe("turn cancellation descendant cascade", () => {
iterator: response[Symbol.asyncIterator](),
label: "root session-limit prompt",
});
- const calls = events.filter((event) => event.type === "subagent.called");
+ const calls = events.filter((event) => event.type === "agent.started");
const requests = events.flatMap((event) =>
event.type === "input.requested" ? event.data.requests : [],
);
@@ -303,7 +302,7 @@ describe("turn cancellation descendant cascade", () => {
const declined = await (await session.respond([{ optionId: "stop", requestId }])).result();
expect(declined.status).toBe("waiting");
expectCancellationBoundary(declined.events);
- expect(declined.events.some((event) => event.type === "subagent.called")).toBe(false);
+ expect(declined.events.some((event) => event.type === "agent.started")).toBe(false);
} catch (error) {
throw new Error(
[
@@ -320,20 +319,20 @@ describe("turn cancellation descendant cascade", () => {
);
});
-type SubagentCalledEvent = Extract<MessageStreamEvent, { type: "subagent.called" }>;
+type AgentStartedEvent = Extract<MessageStreamEvent, { type: "agent.started" }>;
-async function readSubagentCalls(input: {
+async function readAgentStarts(input: {
readonly count: number;
readonly iterator: AsyncIterator<MessageStreamEvent>;
readonly label: string;
-}): Promise<readonly SubagentCalledEvent[]> {
+}): Promise<readonly AgentStartedEvent[]> {
return await withinEventDeadline(
(async () => {
- const events: SubagentCalledEvent[] = [];
+ const events: AgentStartedEvent[] = [];
while (events.length < input.count) {
const next = await input.iterator.next();
if (next.done) throw new Error(`Stream ended before ${input.label}.`);
- if (next.value.type === "subagent.called") events.push(next.value);
+ if (next.value.type === "agent.started") events.push(next.value);
}
return events;
})(),
diff --git a/packages/eve/test/setup/workflow-global-setup.ts b/packages/eve/test/setup/workflow-global-setup.ts
index 436f84dea..9df54ff5e 100644
--- a/packages/eve/test/setup/workflow-global-setup.ts
+++ b/packages/eve/test/setup/workflow-global-setup.ts
@@ -60,6 +60,7 @@ async function discoverWorkflowEntries(): Promise<WorkflowBundleDiscoveredEntrie
resolvePackageSourceDirectoryPath("src/runtime/subagents"),
)),
...(await collectWorkflowInputFiles(resolvePackageSourceDirectoryPath("src/subagents"))),
+ ...(await collectWorkflowInputFiles(resolvePackageSourceDirectoryPath("src/tools/provided"))),
resolvePackageSourceFilePath("test/setup/compiled-artifacts-bootstrap.mjs"),
];
const discovered: WorkflowBundleDiscoveredEntries = {
diff --git a/packages/eve/test/tui-client/tui-background-task-hitl.ts b/packages/eve/test/tui-client/tui-background-task-hitl.ts
deleted file mode 100644
index efa324cae..000000000
--- a/packages/eve/test/tui-client/tui-background-task-hitl.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { Buffer } from "node:buffer";
-import { setTimeout as sleep } from "node:timers/promises";
-
-import { Client } from "eve/client";
-import { EveTUIRunner, MockScreen, MockUserInput } from "./lib/tui.ts";
-
-import { run } from "./lib/run.ts";
-import { theme } from "./lib/theme.ts";
-
-/**
- * End-to-end proof that a local background task can raise HITL after its
- * dispatching parent turn has completed. The real task workflow must wake the
- * idle TUI, each answer must route directly to the blocked child, and the task
- * must eventually wake the parent with its terminal notification.
- */
-
-process.env.EVE_TUI_UNICODE = "1";
-
-const GATES = ["first_gate", "second_gate", "third_gate"] as const;
-
-run(
- {
- app: "fixture-tasks",
- kind: "local-build",
- startEnv: { ...process.env, EVE_E2E_MODEL: "mock" },
- },
- async (target) => {
- const client = new Client({ host: target.baseUrl });
- const screen = new MockScreen({ columns: 120, rows: 50 });
- const input = new MockUserInput();
- const runner = new EveTUIRunner({
- client,
- screen,
- userInput: input,
- name: "Background task HITL smoke",
- });
-
- const runPromise = runner.run().catch((error: unknown) => {
- if (error instanceof Error && error.message === "Interrupted") return;
- throw error;
- });
-
- await screen.waitForIdlePrompt(5_000);
- input.type("TASK-HITL-ROUTING");
- input.enter();
-
- await screen.waitForText("TASK-HITL-STARTED", 60_000);
- console.log(theme.muted("[tui-background-task-hitl] background task started"));
-
- for (const gate of GATES) {
- await waitForCondition(() => approvalPromptVisible(screen.snapshot(), gate), {
- timeoutMs: 60_000,
- label: `approval prompt for ${gate}`,
- onTimeout: () => screen.snapshot(),
- });
- await sleep(500);
- input.emit("data", Buffer.from("y"));
- console.log(theme.muted(`[tui-background-task-hitl] approved ${gate}`));
- }
-
- await screen.waitForText("TASK-NOTIFICATION-ACK", 60_000);
- await screen.waitForIdlePrompt(30_000);
-
- const finalSnapshot = screen.snapshot();
- if (finalSnapshot.includes("Error")) {
- throw new Error(`Final screen contains an Error section:\n${finalSnapshot}`);
- }
-
- console.log(theme.muted("[tui-background-task-hitl] task completed and parent returned idle"));
- input.ctrlC();
- input.ctrlC();
- await runPromise;
- },
-);
-
-function approvalPromptVisible(snapshot: string, toolName: string): boolean {
- return (
- snapshot.includes(`Approve ${toolName}?`) ||
- snapshot.includes(`Approve ${toolName.replaceAll("_", " ")}?`)
- );
-}
-
-async function waitForCondition(
- predicate: () => boolean,
- options: { timeoutMs: number; label: string; intervalMs?: number; onTimeout?: () => string },
-): Promise<void> {
- const intervalMs = options.intervalMs ?? 100;
- const deadline = Date.now() + options.timeoutMs;
- while (Date.now() < deadline) {
- if (predicate()) return;
- await sleep(intervalMs);
- }
- const extra = options.onTimeout?.() ?? "";
- throw new Error(`Timed out waiting for: ${options.label}${extra ? `\n\n${extra}` : ""}`);
-}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 75cf07f36..b066dfcbd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -792,28 +792,6 @@ importers:
specifier: 'catalog:'
version: 7.0.2
- e2e/fixtures/agent-background-tools:
- dependencies:
- '@eve-e2e/config':
- specifier: workspace:*
- version: link:../e2e-config
- '@workflow/world-postgres':
- specifier: 'catalog:'
- eve:
- specifier: workspace:*
- version: link:../../../packages/eve
- zod:
- specifier: 'catalog:'
- version: 4.5.4
- devDependencies:
- '@types/node':
- specifier: 'catalog:'
- version: 24.13.3
- typescript:
- specifier: 'catalog:'
- version: 7.0.2
-
e2e/fixtures/agent-basic-runtime:
dependencies:
'@eve-e2e/config':
@@ -1289,53 +1267,6 @@ importers:
specifier: 'catalog:'
version: 7.0.2
- e2e/fixtures/agent-task-reporting:
- dependencies:
- '@eve-e2e/config':
- specifier: workspace:*
- version: link:../e2e-config
- '@workflow/world-postgres':
- specifier: 'catalog:'
- eve:
- specifier: workspace:*
- version: link:../../../packages/eve
- just-bash:
- specifier: 3.1.0
- version: 3.1.0([email protected])
- zod:
- specifier: 'catalog:'
- version: 4.5.4
- devDependencies:
- '@types/node':
- specifier: 'catalog:'
- version: 24.13.3
- typescript:
- specifier: 'catalog:'
- version: 7.0.2
-
- e2e/fixtures/agent-task-wake-policy:
- dependencies:
- '@eve-e2e/config':
- specifier: workspace:*
- version: link:../e2e-config
- '@workflow/world-postgres':
- specifier: 'catalog:'
- eve:
- specifier: workspace:*
- version: link:../../../packages/eve
- zod:
- specifier: 'catalog:'
- version: 4.5.4
- devDependencies:
- '@types/node':
- specifier: 'catalog:'
- version: 24.13.3
- typescript:
- specifier: 'catalog:'
- version: 7.0.2
-
e2e/fixtures/agent-tools:
dependencies:
'@eve-e2e/config':
@@ -1546,28 +1477,6 @@ importers:
specifier: 'catalog:'
version: 7.0.2
- e2e/fixtures/fixture-tasks:
- dependencies:
- '@eve-e2e/config':
- specifier: workspace:*
- version: link:../e2e-config
- '@workflow/world-postgres':
- specifier: 'catalog:'
- eve:
- specifier: workspace:*
- version: link:../../../packages/eve
- zod:
- specifier: 'catalog:'
- version: 4.5.4
- devDependencies:
- '@types/node':
- specifier: 'catalog:'
- version: 24.13.3
- typescript:
- specifier: 'catalog:'
- version: 7.0.2
-
e2e/fixtures/gadget-extension:
dependencies:
slugify:
diff --git a/research/background-task-wake-policy.md b/research/background-task-wake-policy.md
deleted file mode 100644
index dbf07bef8..000000000
--- a/research/background-task-wake-policy.md
+++ /dev/null
@@ -1,54 +0,0 @@
----
-issue: https://github.com/vercel/eve/issues/1084
-status: implemented
-last_updated: "2026-09-19"
----
-
-# Background task delivery policy
-
-Message sends choose when background results are reported; task execution and
-session completion remain independent of that choice.
-
-## Authoring
-
-```ts
-await from(address).send(message, { auth, taskDeliveryPolicy: "auto" });
-await to(slack, target).send(message, { auth, taskDeliveryPolicy: "cohort" });
-await session.send(message, { auth, taskDeliveryPolicy: "auto" });
-```
-
-`taskDeliveryPolicy: "auto" | "cohort"` is authored only on sends, including client
-sends. New channel sessions default to `"auto"`; new schedule and internal child
-sessions default to `"cohort"`. Explicit sends update the session policy, including
-pending tasks; omission preserves the current value. Schedule handlers override
-the default on their `send(...)`; Markdown schedules use the default.
-
-## Observable behavior
-
-A cohort contains overlapping tasks, including launches in later user turns.
-`"cohort"` holds terminal outcomes until that cohort settles, then reports
-the results together. `"auto"` allows each ready completion to invoke the parent;
-results already queued from the same cohort may share a turn.
-
-For independent tasks A and B, auto can report A while B runs. When A needs B to
-produce a useful answer, the parent may stay silent after A and report both after
-B settles. This is a model judgment about delivery, not a way to avoid the model
-call. The runtime retains available outputs in the workflow tool run registry and includes the
-whole cohort in subsequent reporting contexts. Received does not mean reported.
-User input and intervention notifications remain serviceable under either policy.
-
-## Runtime boundaries
-
-Sends carry the policy through session creation or the durable inbox envelope.
-Cross-channel sends supply a default to the receiver's local send. The last explicit
-value wins when authored deliveries are coalesced. The workflow queue and reporting
-prompt share one resolved value in `eve.runtime.taskDeliveryPolicy`.
-
-Reporting projects cohort state from the existing workflow tool run registry. Auto exposes
-available outputs while the cohort is pending and permits an empty delivery.
-Cohort reports wait for settlement and require a response. Child calls and
-structured outputs retain their explicit output contracts.
-
-Scheduled task-mode sessions check pending workflow tasks as well as newly launched
-tasks before finishing. A partial report cannot end the session and cancel siblings.
-No separate store of reported or withheld task outputs is introduced.
diff --git a/scripts/guard-invariants-baseline.json b/scripts/guard-invariants-baseline.json
index 43e9e5eec..f726dd26c 100644
--- a/scripts/guard-invariants-baseline.json
+++ b/scripts/guard-invariants-baseline.json
@@ -38,5 +38,17 @@
"packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts",
"packages/eve/test/scenarios/load-agent-info-data.scenario.test.ts",
"packages/eve/test/scenarios/runtime-loaders.scenario.test.ts"
+ ],
+ "rule45_providedToolPrivateImportAllowlist": [
+ "packages/eve/src/tools/provided/agent-router.ts",
+ "packages/eve/src/tools/provided/bash.ts",
+ "packages/eve/src/tools/provided/glob.ts",
+ "packages/eve/src/tools/provided/grep.ts",
+ "packages/eve/src/tools/provided/load-skill.ts",
+ "packages/eve/src/tools/provided/read-file.ts",
+ "packages/eve/src/tools/provided/web-fetch.ts",
+ "packages/eve/src/tools/provided/web-search.ts",
+ "packages/eve/src/tools/provided/workflow.ts",
+ "packages/eve/src/tools/provided/write-file.ts"
]
}
diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjs
index cfef01076..b599f3d36 100644
--- a/scripts/guard-invariants.mjs
+++ b/scripts/guard-invariants.mjs
@@ -109,6 +109,13 @@
* `defineSandboxProvider()` and does not import sandbox runtime
* orchestration, registries, key derivation, or session state.
* Built-ins and authored providers must share one contract.
+ * rule 45 — Provided tools under `packages/eve/src/tools/provided/**` import
+ * only public eve entry points (the `#` specifiers of the
+ * package's `exports`), the vendored Workflow SDK that authored
+ * bodies import as `workflow`, and each other. eve is built on
+ * eve: a provided tool that needs a private hook means authors
+ * cannot build the same tool. Files that predate the rule are
+ * baselined and may only leave the baseline.
*
* Baselines for rules with pre-existing violations live in
* `guard-invariants-baseline.json`. Counts and allowlists in that file
@@ -206,6 +213,7 @@ function isTsLike(relPath) {
* rule42: Violation[];
* rule43: Violation[];
* rule44: Violation[];
+ * rule45: { allowlist: Set<string>; violations: Violation[] };
* symlinks: string[];
* }} state
*/
@@ -237,6 +245,7 @@ async function scanRepo(state) {
checkRule42(posix, lines, state.rule42);
checkRule43(posix, lines, state.rule43);
checkRule44(posix, lines, state.rule44);
+ checkRule45(posix, lines, state.rule45);
}
}
@@ -333,6 +342,75 @@ function checkRule44(posix, lines, violations) {
});
}
+// ---------- Rule 45: provided tools use only public entry points ----------
+
+const PROVIDED_TOOLS_DIR = "packages/eve/src/tools/provided/";
+
+const EVE_PACKAGE_EXPORTS = require(join(REPO_ROOT, "packages/eve/package.json")).exports;
+const EXPORTED_TYPES_PATH_RE = /^\.\/dist\/src\/(.+)\.d\.ts$/;
+
+/**
+ * The `#` specifier eve's own source uses for one exported module, such as
+ * `#public/tools/index.js` for `eve/tools`.
+ *
+ * @param {unknown} target
+ */
+function toSourceSpecifier(target) {
+ if (typeof target !== "object" || target === null) return undefined;
+ const types = Reflect.get(target, "types");
+ if (typeof types !== "string") return undefined;
+ const match = EXPORTED_TYPES_PATH_RE.exec(types);
+ return match === null ? undefined : `#${match[1]}.js`;
+}
+
+const EVE_PUBLIC_ENTRY_SPECIFIERS = new Set(
+ Object.values(EVE_PACKAGE_EXPORTS)
+ .map(toSourceSpecifier)
+ .filter((specifier) => specifier !== undefined),
+);
+
+const PROVIDED_TOOL_EXTRA_IMPORTS = new Set([
+ // What an authored body imports as `workflow`: eve vendors the Workflow SDK.
+ "#compiled/@workflow/core/index.js",
+ // `defineJsonSchema` is not public yet, and provided tools declare schemas without zod.
+ "#tools/schema.js",
+]);
+
+// The task kernel's `task_wait` and `task_cancel` read the session's task table
+// directly. When they land, list their files here rather than in the baseline.
+const PROVIDED_KERNEL_TOOL_FILES = new Set();
+
+const IMPORT_SPECIFIER_RE = /(?:\bfrom\s+|\bimport\s*\(\s*|^\s*import\s+)["']([^"']+)["']/;
+
+/** @param {string} specifier */
+function isProvidedToolImportAllowed(specifier) {
+ if (EVE_PUBLIC_ENTRY_SPECIFIERS.has(specifier)) return true;
+ if (PROVIDED_TOOL_EXTRA_IMPORTS.has(specifier)) return true;
+ return specifier.startsWith("#tools/provided/") || specifier.startsWith("./");
+}
+
+/**
+ * @param {string} posix
+ * @param {string[]} lines
+ * @param {{ allowlist: Set<string>; violations: Violation[] }} state
+ */
+function checkRule45(posix, lines, state) {
+ if (!posix.startsWith(PROVIDED_TOOLS_DIR) || posix.endsWith(".test.ts")) return;
+ if (state.allowlist.has(posix) || PROVIDED_KERNEL_TOOL_FILES.has(posix)) return;
+ lines.forEach((line, idx) => {
+ // Doc comments show authors how to import the tool from its public entry.
+ if (/^\s*(?:\*|\/\/)/.test(line)) return;
+ const specifier = IMPORT_SPECIFIER_RE.exec(line)?.[1];
+ if (specifier === undefined || isProvidedToolImportAllowed(specifier)) return;
+ state.violations.push({
+ rule: 45,
+ file: posix,
+ line: idx + 1,
+ message: `imports "${specifier}", which is not a public eve entry point. Provided tools use only the API authors have: import from the matching entry in packages/eve/package.json "exports" (for example "#public/tools/index.js" for eve/tools), or make the capability public first.`,
+ });
+ });
+}
+
// ---------- Rule 13: spread-ternary object composition ----------
/** Matches `...(<expr> ? {} : { ... })` or the mirrored form. */
@@ -1384,6 +1462,10 @@ async function main() {
rule42: /** @type {Violation[]} */ ([]),
rule43: /** @type {Violation[]} */ ([]),
rule44: /** @type {Violation[]} */ ([]),
+ rule45: {
+ allowlist: new Set(baseline.rule45_providedToolPrivateImportAllowlist),
+ violations: /** @type {Violation[]} */ ([]),
+ },
symlinks: /** @type {string[]} */ ([]),
};
@@ -1495,6 +1577,9 @@ async function main() {
violations.push({ rule: 44, ...issue });
}
+ // Rule 45
+ violations.push(...state.rule45.violations);
+
if (violations.length === 0) {
process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");
return;