The Open Framework for Building Agents
feat(eve)!: remove todo and rebuild ask_question on ctx.ask (#3648)
Andrew Barba60998d606bfc
diff --git a/.changeset/remove-todo-opt-in-ask-question.md b/.changeset/remove-todo-opt-in-ask-question.mdnew file mode 100644index 000000000..d8cb13d56--- /dev/null+++ b/.changeset/remove-todo-opt-in-ask-question.md@@ -0,0 +1,9 @@+---+"eve": minor+---++Remove the `todo` tool, its `eve/tools/todo` export, and the dev TUI todo panel; delete any `agent/tools/todo.ts`, including one that exports `disableTool()`, which now fails the build because there is no default `todo` tool to disable. Compaction no longer resets `write_file` read tracking, so a file read before compaction can be overwritten without re-reading it; stale-read detection still rejects the write if the file changed since that read.++`ask_question` is no longer a default tool and is now an ordinary workflow tool built on `ctx.ask()`. Add it with `eve add tool/ask_question`, or change an existing `agent/tools/ask_question.ts` to `import { askQuestion } from "eve/tools/ask_question"; export default askQuestion();`. The model now asks one `question` with up to three `{ label, description }` options, can always receive a free-text answer, and gets back `{ status: "answered", answer }` with the chosen label or the user's words. In sessions that cannot request input, the tool is still available and returns `{ status: "unavailable" }`. If you disabled `ask_question` with `disableTool()`, delete that file; it now fails the build for the same reason.++`ctx.ask()` now resolves to `{ status: "answered", optionId?, text? }`, `{ status: "dismissed" }`, or `{ status: "unavailable" }`; check `status` before reading `optionId`. It returns `unavailable` immediately when the session cannot request input. A plain-text message answers a blocking tool's `ctx.ask()` question when it is the only pending question and the message matches an option or the question allows free text. Pass `dismissible: true` to resolve the question as `dismissed` when the user sends an unrelated message instead. An `ask_question` request's `requestId` is no longer its tool call ID; use `action.callId` to relate a request to its tool call.diff --git a/apps/docs/registry.json b/apps/docs/registry.jsonindex 2e194e123..daece4467 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": "",@@ -357,7 +313,7 @@"name": "tool/ask_question","type": "registry:item","title": "Ask Question",- "description": "Let the agent ask the user a question during a turn.",+ "description": "Let the agent ask the user one question and wait for the answer.","files": [{"path": "registry/tools/ask_question.ts",@@ -418,19 +374,6 @@}]},- {- "name": "tool/todo",- "type": "registry:item",- "title": "Todo",- "description": "Maintain a durable per-session todo list.",- "files": [- {- "path": "registry/tools/todo.ts",- "type": "registry:file",- "target": "agent/tools/todo.ts"- }- ]- },{"name": "tool/web_fetch","type": "registry:item",@@ -549,9 +492,7 @@"requires": ">=0.29.0"}},- "dependencies": [- "@vercel/connect"- ],+ "dependencies": ["@vercel/connect"],"files": [{"path": "registry/connections/vercel.ts",@@ -571,20 +512,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",@@ -604,20 +537,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",@@ -637,20 +562,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",@@ -670,20 +587,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",@@ -718,12 +627,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",@@ -743,20 +648,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",@@ -776,20 +673,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",@@ -809,20 +698,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",@@ -842,20 +723,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",@@ -875,20 +748,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",@@ -908,20 +773,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",@@ -941,20 +798,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",@@ -974,20 +823,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",@@ -1007,20 +848,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",@@ -1040,20 +873,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",@@ -1073,20 +898,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",@@ -1106,20 +923,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",@@ -1139,20 +948,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",@@ -1172,20 +973,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",@@ -1205,20 +998,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",@@ -1238,20 +1023,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",@@ -1271,20 +1048,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",@@ -1304,20 +1073,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",@@ -1337,22 +1098,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",@@ -1372,20 +1123,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",@@ -1405,20 +1148,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",@@ -1438,20 +1173,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",@@ -1471,20 +1198,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",@@ -1504,20 +1223,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",@@ -1537,20 +1248,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",@@ -1570,20 +1273,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",@@ -1603,20 +1298,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",@@ -1636,11 +1323,7 @@"command": "eve","package": "eve","bin": "eve",- "args": [- "integration",- "setup",- "shopify"- ]+ "args": ["integration", "setup", "shopify"]},"requires": ">=0.46.1"}@@ -1664,20 +1347,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",@@ -1697,20 +1372,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",@@ -1730,20 +1397,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",@@ -1763,20 +1422,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",@@ -1809,9 +1460,7 @@"requires": ">=0.48.0"}},- "dependencies": [- "@vercel/connect"- ],+ "dependencies": ["@vercel/connect"],"files": [{"path": "registry/connections/tinybird.ts",@@ -1831,20 +1480,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",@@ -1864,20 +1505,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",@@ -1897,20 +1530,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",@@ -1930,20 +1555,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",@@ -1963,20 +1580,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",@@ -1996,40 +1605,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",@@ -2048,23 +1645,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",@@ -2116,9 +1705,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": ""@@ -2148,23 +1735,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",@@ -2177,23 +1756,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",@@ -2206,11 +1777,7 @@"command": "eve","package": "eve","bin": "eve",- "args": [- "integration",- "setup",- "web"- ]+ "args": ["integration", "setup", "web"]},"requires": ">=0.33.0","docs": "/docs/channels/eve",@@ -2458,11 +2025,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",@@ -2485,11 +2048,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",@@ -2515,11 +2074,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",@@ -2543,11 +2098,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",@@ -2572,11 +2123,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": ""@@ -2600,11 +2147,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": ""@@ -2628,11 +2171,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": "",@@ -2657,11 +2196,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",@@ -2685,11 +2220,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": ""@@ -2713,23 +2244,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",@@ -2742,11 +2265,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": "",@@ -2771,20 +2290,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",@@ -2797,11 +2310,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": "",@@ -2826,11 +2335,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": "",@@ -2855,11 +2360,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": ""@@ -2883,11 +2384,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",@@ -2911,11 +2408,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": "",@@ -2940,11 +2433,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": "",@@ -2981,9 +2470,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": ""},@@ -3024,9 +2511,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": ""@@ -3044,9 +2529,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": ""@@ -3064,9 +2547,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": ""},@@ -3083,9 +2564,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": ""@@ -3103,9 +2582,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": ""},@@ -3122,9 +2599,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/ask_question.ts b/apps/docs/registry/tools/ask_question.tsindex 2468b1ba2..533cc8526 100644--- a/apps/docs/registry/tools/ask_question.ts+++ b/apps/docs/registry/tools/ask_question.ts@@ -1 +1,3 @@-export { default } from "eve/tools/ask_question";+import { askQuestion } from "eve/tools/ask_question";++export default askQuestion();diff --git a/apps/docs/registry/tools/todo.ts b/apps/docs/registry/tools/todo.tsdeleted file mode 100644index 7df699773..000000000--- a/apps/docs/registry/tools/todo.ts+++ /dev/null@@ -1 +0,0 @@-export { default } from "eve/tools/todo";diff --git a/apps/fixtures/agent-tui-client/agent/tools/ask_question.ts b/apps/fixtures/agent-tui-client/agent/tools/ask_question.tsnew file mode 100644index 000000000..533cc8526--- /dev/null+++ b/apps/fixtures/agent-tui-client/agent/tools/ask_question.ts@@ -0,0 +1,3 @@+import { askQuestion } from "eve/tools/ask_question";++export default askQuestion();diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.mdindex f6980844d..b793a3e19 100644--- a/docs/concepts/built-in-tools.md+++ b/docs/concepts/built-in-tools.md@@ -213,72 +213,6 @@ import { disableTool } from "eve/tools";export default disableTool();```-### `todo`--`todo` maintains a durable todo list for the session.--```sh-eve add tool/todo-```--```ts title="agent/tools/todo.ts"-export { default } from "eve/tools/todo";-```--Override it. Spreading the definition preserves its durable state key:--```ts title="agent/tools/todo.ts"-import { defineTool } from "eve/tools";-import { todo } from "eve/tools/todo";--export default defineTool({- ...todo,- description: "Track the current implementation plan.",-});-```--Disable it:--```ts title="agent/tools/todo.ts"-import { disableTool } from "eve/tools";--export default disableTool();-```--### `ask_question`--`ask_question` asks the user for clarification or a choice, then parks the turn until they answer. It appears only when the session can request user input. See [Human-in-the-loop](/docs/human-in-the-loop).--```sh-eve add tool/ask_question-```--```ts title="agent/tools/ask_question.ts"-export { default } from "eve/tools/ask_question";-```--Replace its request-input behavior with an ordinary authored tool:--```ts title="agent/tools/ask_question.ts"-import { defineTool } from "eve/tools";--export default defineTool({- description: "Record a clarification request.",- inputSchema: { type: "object" },- async execute(input) {- return { recorded: input };- },-});-```--Disable it:--```ts title="agent/tools/ask_question.ts"-import { disableTool } from "eve/tools";--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).@@ -365,6 +299,22 @@ You can also add the opt-in framework tools described below.These framework-provided tools are not added by default. Add only the ones the agent needs.+### `ask_question`++`ask_question` lets the model ask the user one question, then waits for the answer. The model can offer two or three options, each with a label and a short description, and the user can always type their own answer instead. Channels render the options as native UI, such as Slack select menus. Without the tool, the model can still ask in its reply text and the user answers with their next message. See [Human-in-the-loop](/docs/human-in-the-loop). Add it:++```sh+eve add tool/ask_question+```++```ts title="agent/tools/ask_question.ts"+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.+### `glob``glob` finds sandbox files by glob pattern. Add it:diff --git a/docs/concepts/default-harness.md b/docs/concepts/default-harness.mdindex 35fa0500a..c08ed9931 100644--- a/docs/concepts/default-harness.md+++ b/docs/concepts/default-harness.md@@ -24,8 +24,6 @@ input token count plus an estimate of new messages. A smaller character estimatealone cannot satisfy compaction triggered by a higher provider count. If trimmingcannot free enough space, eve summarizes the older history.-Compaction also preserves the framework's own tool state automatically. It resets read-before-write tracking (so a write afterward re-reads the file whose read evidence was summarized away) and re-injects the active todo list, so the model keeps its task list across the summary. There is no per-tool hook to configure.-First-class [memory](../memory) participates in a separate lifecycle. eve asksproviders to capture before compaction, excludes attributed recalled recordsfrom the summarizer, keeps their canonical latest values, and recalls againdiff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex b0e266449..3990f6441 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -77,7 +77,7 @@ The stream is newline-delimited JSON (NDJSON), one event per line:| `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 `ask_question`); carries `requests`. |+| `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` to attach to. || `subagent.completed` | The parent recorded a successful subagent invocation result; carries the actual output. |@@ -210,7 +210,7 @@ Message sends default to `"steer"`. Before assistant output begins, eve interrupIf 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.-With one question-only batch, an exact option match or permitted freeform response answers `ask_question`. Any other follow-up marks the question unanswered and starts the new turn. With several approval or question batches pending, eve does not guess which batch plain text addresses: the message starts an ordinary turn and the batches stay open. Use structured responses to target requests unambiguously.+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 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.diff --git a/docs/evals/assertions.mdx b/docs/evals/assertions.mdxindex 215a11b06..fd4e92b99 100644--- a/docs/evals/assertions.mdx+++ b/docs/evals/assertions.mdx@@ -111,8 +111,8 @@ t.calledSubagent("weather", {```tsconst request = session.requireInputRequest({- toolName: "ask_question",- optionIds: ["red", "blue"],+ toolName: "confirm_deploy",+ optionIds: ["approve", "cancel"],});```diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex 4463c9553..f433fa5ae 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -218,7 +218,7 @@ received attachment as a `file` part on the user message. The part includes `med## Human-in-the-loop prompts-Tools opt into approval with `approval`, and the model can also ask a question with `ask_question` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event, and the pending request rides on a `dynamic-tool` part at `part.toolMetadata?.eve?.inputRequest`. Scan every message because an unrelated turn can add newer messages while an approval stays open, then answer through the same session with `respond()`:+Tools opt into approval with `approval`, and workflow tools such as the opt-in `ask_question` tool ask the user a question with `ctx.ask()` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event, and the pending request rides on a `dynamic-tool` part at `part.toolMetadata?.eve?.inputRequest`. Scan every message because an unrelated turn can add newer messages while an approval stays open, then answer through the same session with `respond()`:```tsxconst pendingRequests = agent.data.messagesdiff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex 8781ca50a..8431c1478 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -113,44 +113,45 @@ Tool definitions accept `availableInSubagents: false` to restrict the tool to to## Imports at a glance-| Import | Holds |-| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |-| `eve` | `defineAgent`, `defineRemoteAgent`, `defineDynamic`, agent config types |-| `eve/tools` | `defineTool`, `defineWorkflowTool`, `defineDurableCallback`, `defineDurableSchema`, `defineDynamic`, `disableTool`, tool types |-| `eve/tools/{bash,read_file,write_file,todo,web_fetch,load_skill,glob,grep}` | Individual reusable tool definitions |-| `eve/tools/approval` | Approval types and `auto`, `always`, `once`, `never` |-| `eve/tools/web_search` | Provider-managed `webSearch` configuration |-| `eve/tools/workflow` | Runtime-generated `workflow` tool factory |-| `eve/tools/sleep` | Opt-in durable `sleep` tool |-| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection`, `defineDynamic` |-| `eve/channels` | `defineChannel`, `disableRoute`, route verbs |-| `eve/channels/eve` | `eveChannel` |-| `eve/channels/auth` | `localDev`, `vercelOidc`, `placeholderAuth` |-| `eve/channels/{slack,discord,teams,telegram,twilio,github}` | platform channel factories |-| `eve/hooks` | `defineHook` |-| `eve/schedules` | `defineSchedule` |-| `eve/skills` | `defineSkill`, `defineDynamic` |-| `eve/instructions` | `defineInstructions`, `defineDynamic` |-| `eve/memory` | `defineMemory`, `defineMemoryProvider`, provider and lifecycle types |-| `eve/memory/scope` | `byPrincipal` and memory scope helpers |-| `eve/memory/file` | `fileMemory`, `inMemory`, and the conditional document backend contract |-| `eve/memory/file/vercel` | `vercelBlob` and Vercel Blob backend options |-| `eve/context` | `defineState`, session and state types |-| `eve/sandbox` | `defineSandbox`, provider environments, and sandbox session types |-| `eve/instrumentation` | `defineInstrumentation`, `disableInstrumentation`, `isChannel`, lifecycle provider types |-| `eve/instrumentation/otel` | `otel`, `otelIntegration`, `localTraces`, OpenTelemetry policy types |-| `eve/local-dev` | `getLocalDevCapability`, `LocalDevCapability` |-| [`eve/models`](../guides/evaluate) | Automatic model selection with `auto` |-| `eve/models/openai` | `openai`, `chatgpt`, deprecated `experimental_chatgpt` |-| `eve/models/anthropic` | `anthropic` |-| [`eve/ai`](../guides/evaluate#evaluate-inside-a-tool) | Standalone `evaluate` |-| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |-| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |-| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |-| `eve/evals/loaders` | `loadJson`, `loadYaml` |-| `eve/react`, `eve/vue`, `eve/svelte` | `useEveAgent` |-| `eve/next`, `eve/nuxt`, `eve/sveltekit` | framework bundler plugins |-| [`eve/client`](../guides/client/overview) | `Client`, `ClientSession`, health and agent-info schemas, response errors |+| Import | Holds |+| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| `eve` | `defineAgent`, `defineRemoteAgent`, `defineDynamic`, agent config types |+| `eve/tools` | `defineTool`, `defineWorkflowTool`, `defineDurableCallback`, `defineDurableSchema`, `defineDynamic`, `disableTool`, tool types |+| `eve/tools/{bash,read_file,write_file,web_fetch,load_skill,glob,grep}` | Individual reusable tool definitions |+| `eve/tools/approval` | Approval types and `auto`, `always`, `once`, `never` |+| `eve/tools/ask_question` | Opt-in `askQuestion` tool factory |+| `eve/tools/web_search` | Provider-managed `webSearch` configuration |+| `eve/tools/workflow` | Runtime-generated `workflow` tool factory |+| `eve/tools/sleep` | Opt-in durable `sleep` tool |+| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection`, `defineDynamic` |+| `eve/channels` | `defineChannel`, `disableRoute`, route verbs |+| `eve/channels/eve` | `eveChannel` |+| `eve/channels/auth` | `localDev`, `vercelOidc`, `placeholderAuth` |+| `eve/channels/{slack,discord,teams,telegram,twilio,github}` | platform channel factories |+| `eve/hooks` | `defineHook` |+| `eve/schedules` | `defineSchedule` |+| `eve/skills` | `defineSkill`, `defineDynamic` |+| `eve/instructions` | `defineInstructions`, `defineDynamic` |+| `eve/memory` | `defineMemory`, `defineMemoryProvider`, provider and lifecycle types |+| `eve/memory/scope` | `byPrincipal` and memory scope helpers |+| `eve/memory/file` | `fileMemory`, `inMemory`, and the conditional document backend contract |+| `eve/memory/file/vercel` | `vercelBlob` and Vercel Blob backend options |+| `eve/context` | `defineState`, session and state types |+| `eve/sandbox` | `defineSandbox`, provider environments, and sandbox session types |+| `eve/instrumentation` | `defineInstrumentation`, `disableInstrumentation`, `isChannel`, lifecycle provider types |+| `eve/instrumentation/otel` | `otel`, `otelIntegration`, `localTraces`, OpenTelemetry policy types |+| `eve/local-dev` | `getLocalDevCapability`, `LocalDevCapability` |+| [`eve/models`](../guides/evaluate) | Automatic model selection with `auto` |+| `eve/models/openai` | `openai`, `chatgpt`, deprecated `experimental_chatgpt` |+| `eve/models/anthropic` | `anthropic` |+| [`eve/ai`](../guides/evaluate#evaluate-inside-a-tool) | Standalone `evaluate` |+| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |+| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |+| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |+| `eve/evals/loaders` | `loadJson`, `loadYaml` |+| `eve/react`, `eve/vue`, `eve/svelte` | `useEveAgent` |+| `eve/next`, `eve/nuxt`, `eve/sveltekit` | framework bundler plugins |+| [`eve/client`](../guides/client/overview) | `Client`, `ClientSession`, health and agent-info schemas, response errors |Exported types ship from the same entrypoint as the helper they describe (for example `ToolDefinition` and `ToolContext` from `eve/tools`). The `exports` field in `packages/eve/package.json` lists every public entrypoint.diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.mdindex a08ef2ac5..3e8b9d6cd 100644--- a/docs/tools/human-in-the-loop.md+++ b/docs/tools/human-in-the-loop.md@@ -150,27 +150,38 @@ export default defineTool({## Questions-The built-in `ask_question` tool lets the model pause and ask the user, rather than guessing. It has no `execute` — the model calls it with `{ prompt, options?, allowFreeform? }`:+The `ask_question` tool lets the model pause and ask the user one question, rather than guessing. The model calls it with `{ question, options? }`:-- `prompt`: the question to put to the user.-- `options`: an optional list of choices to offer. Channels render these as buttons or a select menu.-- `allowFreeform`: whether the user may answer with free text instead of picking an option.+- `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.-`ask_question` is part of the [default tool set](/docs/concepts/built-in-tools), so it is available without you defining anything. It produces the same `input.requested` pause as an approval, and resumes the same way.+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.++`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:++```ts title="agent/tools/ask_question.ts"+import { askQuestion } from "eve/tools/ask_question";++export default askQuestion();+```++`ask_question` is an ordinary [workflow tool](/docs/tools/workflows) built on `ctx.ask()`. Write your own workflow tool with `ctx.ask()` when you need a different schema or want to act on the answer in the same call. Without any asking tool, the model asks in its reply text and the user's next message carries the answer.## How pause and resume worksApprovals and questions share one protocol:-1. The model requests input (an approval, or an `ask_question`).+1. A tool call needs approval, or a workflow tool such as `ask_question` calls `ctx.ask()`.2. eve emits an `input.requested` stream event carrying the pending requests.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.+Each request includes a `kind` discriminator: `tool-approval`, `question`, or-`session-limit`. Clients should use `kind` to choose behavior and presentation;-`toolName` and `requestId` identify the action and request but do not encode its-semantics.+`session-limit`. Clients should use `kind` to choose behavior and presentation.+`requestId` identifies the request to answer, and `action.callId` identifies the+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.@@ -189,7 +200,7 @@ From your own frontend, scan all messages for pending requests and answer throug## What to read next- [Tools](/docs/tools): define the typed actions an approval gates-- [Built-in tools](/docs/concepts/built-in-tools): the default tools, including `ask_question`+- [Built-in tools](/docs/concepts/built-in-tools): the default tools and opt-in tools such as `ask_question`- [Sessions, runs & streaming](/docs/concepts/sessions-runs-and-streaming): the event and resume contract behind the pause- [Building a frontend](/docs/guides/frontend/overview): render and answer requests from your own UI- [Multi-tenant approvals](/docs/patterns/multi-tenant-approvals): resolve per-tenant approval policy for authored and connection toolsdiff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdxindex 5b22e9cb8..5ec491d3c 100644--- a/docs/tools/workflows.mdx+++ b/docs/tools/workflows.mdx@@ -44,7 +44,7 @@ export default defineWorkflowTool({],});- if (answer.optionId !== "approve") {+ if (answer.status !== "answered" || answer.optionId !== "approve") {return { deployed: false, reason: "rejected" };}return { deployed: true, url: await applyDeploy(plan) };@@ -277,12 +277,30 @@ const answer = await ctx.ask({display?: "confirmation" | "select" | "text",options?: { id: string; label: string; description?: string; style?: "primary" | "danger" | "default" }[],allowFreeform?: boolean,-}); // { optionId?: string; text?: string }+ dismissible?: boolean,+});+// | { status: "answered"; optionId?: string; text?: string }+// | { status: "dismissed" }+// | { status: "unavailable" }````ctx.ask` publishes an `input.requested` event on the session — rendered the way channels render-`ask_question` and tool approvals — and returns an awaitable answer. Awaiting it suspends the run until a response arrives.-It composes with the SDK's own constructs; race it against a deadline:+tool approvals — and returns an awaitable answer. Awaiting it suspends the run until a response arrives.+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.+- `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.++`ctx.ask` composes with the SDK's own constructs; race it against a deadline:```tsconst pending = ctx.ask({ prompt: `Deploy ${service}?`, options: APPROVE_OR_CANCEL });@@ -290,13 +308,16 @@ 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 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, dismissed,+ or the run ends. In a background tool that means long after the turn that started it.- 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+ example from an old Slack menu, the agent receives the `id` as a new message, not the label.- 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 while a request is pending follows the session's- normal `turnPolicy`.+- A response never steers. A new human message that does not answer a pending request follows the+ session's normal `turnPolicy`.Compare the [`approval`](/docs/human-in-the-loop) policy, which gates the call before `execute` runsand can only show the model's input. Both compose: `approval` before the run, `ctx.ask` inside it.@@ -515,7 +536,9 @@ async execute({ service }, ctx) {}if (answer === undefined) return { deployed: false, reason: "timed out" };- if (answer.optionId !== "approve") return { deployed: false, reason: "rejected" };+ if (answer.status !== "answered" || answer.optionId !== "approve") {+ return { deployed: false, reason: "rejected" };+ }return { deployed: true, url: await applyDeploy(plan) };}```@@ -574,7 +597,9 @@ export default defineWorkflowTool({],});- if (decision.optionId !== "approve") return { refunded: false };+ if (decision.status !== "answered" || decision.optionId !== "approve") {+ return { refunded: false };+ }return { refunded: true, receipt: await issueRefund(orderId, amount) };},});diff --git a/docs/tutorial/guard-the-spend.mdx b/docs/tutorial/guard-the-spend.mdxindex 2ca629c51..f35f8c1b6 100644--- a/docs/tutorial/guard-the-spend.mdx+++ b/docs/tutorial/guard-the-spend.mdx@@ -55,7 +55,7 @@ The model proposes the query, `approval` returns `"user-approval"`, and the turnEach session has exactly one active continuation. Answer an approval against a stale handle and it's rejected, so there's no way to double-resume the same parked turn.-The same machinery backs the built-in `ask_question` tool, where the model asks you mid-turn, and per-connection approval via `approval: once()`. See [Tools and human-in-the-loop](../tools).+The same machinery backs the opt-in `ask_question` tool, where the model asks you mid-turn, and per-connection approval via `approval: once()`. See [Tools and human-in-the-loop](../tools).→ Next: [Ship it](./ship-it)diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.tsindex a736facdd..18acf12f2 100644--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts@@ -17,11 +17,7 @@ export default defineAgent({toolCalls: [{id: "child-question",- input: {- allowFreeform: true,- options: [],- prompt: "What marker should the child return?",- },+ input: { question: "What marker should the child return?" },name: "ask_question",},],diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.mdindex b409d3e7d..1bd233329 100644--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md@@ -5,6 +5,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 prompt `What marker should the child return?`, then reply with `CHILD_HITL_RESULT=` followed by the answer.+- 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/sleeper/tools/ask_question.ts b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/tools/ask_question.tsnew file mode 100644index 000000000..533cc8526--- /dev/null+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/tools/ask_question.ts@@ -0,0 +1,3 @@+import { askQuestion } from "eve/tools/ask_question";++export default askQuestion();diff --git a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts b/e2e/fixtures/agent-compaction-regressions/agent/agent.tsindex b1bd1ff61..8fd667036 100644--- a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts+++ b/e2e/fixtures/agent-compaction-regressions/agent/agent.ts@@ -13,23 +13,19 @@ import {TASK_TAIL_SENTINEL,} from "../constants";import { assistantHasReport } from "../report-evidence";-import { handoffReferences, reviewReferences } from "../release-reports";+import { HANDOFF_REFERENCE, REVIEW_REFERENCE } from "../release-reports";const TEST_CONTEXT_WINDOW_TOKENS = 32_000;-// The compiled fixture's instructions and 13 advertised tools occupy ~2,823+// The compiled fixture's instructions and 11 advertised tools occupy ~2,371// tokens. Reserve them in addition to the summarizer's history budget.-const TEST_REQUEST_ENVELOPE_TOKENS = 2_823;+const TEST_REQUEST_ENVELOPE_TOKENS = 2_371;// 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;const COMPACTION_PRESSURE_USAGE = { inputTokens: TEST_REQUEST_ENVELOPE_TOKENS + 4_096 };const MAX_TOOL_CALLS = 10;-type RegressionCase =- | "content-output-file-stub"- | "redundant-tool-calls"- | "stale-todo-work"- | "task-survival";+type RegressionCase = "content-output-file-stub" | "redundant-tool-calls" | "task-survival";let activeCase: RegressionCase | undefined;const handoffCallCounts = new Map<RegressionCase, number>();@@ -172,9 +168,8 @@ const taskModel = mockModel({};}- const subject = regressionCase === "redundant-tool-calls" ? "repository" : "checkout";- const reviewId = reviewReferences[subject];- const handoffId = handoffReferences[subject];+ const reviewId = REVIEW_REFERENCE;+ const handoffId = HANDOFF_REFERENCE;if (assistantHasReport(request.messages, reviewId)) {if (assistantHasReport(request.messages, handoffId)) {@@ -191,7 +186,7 @@ const taskModel = mockModel({toolCalls: [{id: `prepare-handoff-${handoffCalls + 1}`,- input: { subject, reviewId },+ input: { reviewId },name: "prepare-handoff",},],@@ -207,9 +202,9 @@ const taskModel = mockModel({usage: COMPACTION_PRESSURE_USAGE,toolCalls: [{- id: `${subject}-review-${reviewCalls + 1}`,- input: { scope: subject },- name: subject === "repository" ? "inspect-repository" : "perform-source-analysis",+ id: `repository-review-${reviewCalls + 1}`,+ input: { scope: "repository" },+ name: "inspect-repository",},],};@@ -246,7 +241,6 @@ function regressionCaseFromText(text: string): RegressionCase | undefined {if (text.includes("[case: content-output-file-stub]")) return "content-output-file-stub";if (text.toLowerCase().includes("review the storefront repository"))return "redundant-tool-calls";- if (text.toLowerCase().includes("review the checkout implementation")) return "stale-todo-work";if (text.includes("[case: task-survival]")) return "task-survival";return undefined;}diff --git a/e2e/fixtures/agent-compaction-regressions/agent/tools/inspect-repository.ts b/e2e/fixtures/agent-compaction-regressions/agent/tools/inspect-repository.tsindex bed77d557..015490fe9 100644--- a/e2e/fixtures/agent-compaction-regressions/agent/tools/inspect-repository.ts+++ b/e2e/fixtures/agent-compaction-regressions/agent/tools/inspect-repository.ts@@ -3,7 +3,7 @@ import { defineTool } from "eve/tools";import { z } from "zod";import { repositoryFindings } from "../../release-findings";-import { reviewReferences, saveReleaseRecord } from "../../release-reports";+import { REVIEW_REFERENCE, saveReleaseRecord } from "../../release-reports";const invocationCount = defineState("storefront.inspect-repository", () => 0);@@ -14,8 +14,7 @@ export default defineTool({const attempt = invocationCount.get() + 1;invocationCount.update(() => attempt);const report = {- reportId: reviewReferences.repository,- subject: "repository" as const,+ reportId: REVIEW_REFERENCE,status: "completed" as const,findings: repositoryFindings,};diff --git a/e2e/fixtures/agent-compaction-regressions/agent/tools/perform-source-analysis.ts b/e2e/fixtures/agent-compaction-regressions/agent/tools/perform-source-analysis.tsdeleted file mode 100644index 90dda9024..000000000--- a/e2e/fixtures/agent-compaction-regressions/agent/tools/perform-source-analysis.ts+++ /dev/null@@ -1,32 +0,0 @@-import { defineState } from "eve/context";-import { defineTool } from "eve/tools";-import { todo } from "eve/tools/todo";-import { z } from "zod";--import { checkoutFindings } from "../../release-findings";-import { reviewReferences, saveReleaseRecord } from "../../release-reports";--const invocationCount = defineState("storefront.perform-source-analysis", () => 0);--export default defineTool({- description: "Review the checkout implementation and save a completed review record.",- inputSchema: z.object({ scope: z.literal("checkout") }),- async execute(_input, ctx) {- const attempt = invocationCount.get() + 1;- invocationCount.update(() => attempt);- await todo.execute(- {- todos: [{ content: "Review checkout implementation", priority: "high", status: "pending" }],- },- ctx,- );- const report = {- reportId: reviewReferences.checkout,- subject: "checkout" as const,- status: "completed" as const,- findings: checkoutFindings,- };- saveReleaseRecord(report);- return { completed: true, ...report, attempt, hardStop: attempt >= 10 };- },-});diff --git a/e2e/fixtures/agent-compaction-regressions/agent/tools/prepare-handoff.ts b/e2e/fixtures/agent-compaction-regressions/agent/tools/prepare-handoff.tsindex 861afbfa3..ecf9a0976 100644--- a/e2e/fixtures/agent-compaction-regressions/agent/tools/prepare-handoff.ts+++ b/e2e/fixtures/agent-compaction-regressions/agent/tools/prepare-handoff.ts@@ -3,28 +3,26 @@ import { defineTool } from "eve/tools";import { z } from "zod";import { handoffNotes } from "../../release-findings";-import { handoffReferences, releaseRecords, saveReleaseRecord } from "../../release-reports";+import { HANDOFF_REFERENCE, releaseRecords, saveReleaseRecord } from "../../release-reports";const invocationCount = defineState("storefront.prepare-handoff", () => 0);export default defineTool({description: "Prepare a release handoff from a completed storefront review record.",inputSchema: z.object({- subject: z.enum(["repository", "checkout"]),reviewId: z.string().min(1),}),async execute(input) {const review = releaseRecords.get()[input.reviewId];- if (review?.status !== "completed" || review.subject !== input.subject) {+ if (review?.status !== "completed") {throw new Error("Complete the requested review before preparing its release handoff.");}const attempt = invocationCount.get() + 1;invocationCount.update(() => attempt);const report = {- reportId: handoffReferences[input.subject],- subject: input.subject,+ reportId: HANDOFF_REFERENCE,status: "completed" as const,- findings: handoffNotes[input.subject],+ findings: handoffNotes,};saveReleaseRecord(report);return {diff --git a/e2e/fixtures/agent-compaction-regressions/evals/redundant-tool-calls.eval.ts b/e2e/fixtures/agent-compaction-regressions/evals/redundant-tool-calls.eval.tsindex d67b433bc..d24247f6d 100644--- a/e2e/fixtures/agent-compaction-regressions/evals/redundant-tool-calls.eval.ts+++ b/e2e/fixtures/agent-compaction-regressions/evals/redundant-tool-calls.eval.ts@@ -1,6 +1,6 @@import { defineEval } from "eve/evals";-import { handoffReferences, reviewReferences } from "../release-reports";+import { HANDOFF_REFERENCE, REVIEW_REFERENCE } from "../release-reports";export default defineEval({tags: ["real-model"],@@ -17,16 +17,16 @@ export default defineEval({t.calledTool("inspect-repository", {count: 1,input: { scope: "repository" },- output: { completed: true, reportId: reviewReferences.repository, status: "completed" },+ output: { completed: true, reportId: REVIEW_REFERENCE, status: "completed" },});t.calledTool("prepare-handoff", {count: 1,- input: { subject: "repository", reviewId: reviewReferences.repository },- output: { completed: true, reportId: handoffReferences.repository, status: "completed" },+ input: { reviewId: REVIEW_REFERENCE },+ output: { completed: true, reportId: HANDOFF_REFERENCE, status: "completed" },});t.event("compaction.completed", { count: (count) => count >= 2 });- t.messageIncludes(reviewReferences.repository);- t.messageIncludes(handoffReferences.repository);+ t.messageIncludes(REVIEW_REFERENCE);+ t.messageIncludes(HANDOFF_REFERENCE);t.noFailedActions();t.calledTool("inspect-repository", { count: 1 }).soft().label("no repeated inspection");diff --git a/e2e/fixtures/agent-compaction-regressions/evals/stale-todo-work.eval.ts b/e2e/fixtures/agent-compaction-regressions/evals/stale-todo-work.eval.tsdeleted file mode 100644index d9a1bba40..000000000--- a/e2e/fixtures/agent-compaction-regressions/evals/stale-todo-work.eval.ts+++ /dev/null@@ -1,36 +0,0 @@-import { defineEval } from "eve/evals";--import { handoffReferences, reviewReferences } from "../release-reports";--export default defineEval({- tags: ["real-model"],- description: "A completed checkout review stays complete when the task board has a stale todo.",- async test(t) {- const turn = await t.send(- "Review the checkout implementation and prepare a release handoff for the next maintainer. " +- "Check pricing, inventory, order persistence, and customer notifications. The task board may be out of date; " +- "use the completed review as the source of truth. Include the review and handoff record references in your final note.",- );-- turn.expectOk();- t.succeeded();- t.calledTool("perform-source-analysis", {- count: 1,- input: { scope: "checkout" },- output: { completed: true, reportId: reviewReferences.checkout, status: "completed" },- });- t.calledTool("prepare-handoff", {- count: 1,- input: { subject: "checkout", reviewId: reviewReferences.checkout },- output: { completed: true, reportId: handoffReferences.checkout, status: "completed" },- });- t.event("compaction.completed", { count: (count) => count >= 2 });- t.messageIncludes(reviewReferences.checkout);- t.messageIncludes(handoffReferences.checkout);- t.noFailedActions();-- t.calledTool("perform-source-analysis", { count: 1 }).soft().label("no repeated analysis");- t.calledTool("prepare-handoff", { count: 1 }).soft().label("no repeated handoff");- t.event("compaction.completed", { count: 2 }).soft().label("compaction efficiency");- },-});diff --git a/e2e/fixtures/agent-compaction-regressions/release-findings.ts b/e2e/fixtures/agent-compaction-regressions/release-findings.tsindex 7ba3f1f88..4bc97a7c3 100644--- a/e2e/fixtures/agent-compaction-regressions/release-findings.ts+++ b/e2e/fixtures/agent-compaction-regressions/release-findings.ts@@ -15,54 +15,19 @@ export const repositoryFindings = ["The review covers startup, catalog, cart, checkout, saved orders, and notifications. Release validation should now concentrate on the purchase and cancellation journeys, including retries, without repeating this repository inspection.",];-export const checkoutFindings = [- "Checkout validates the cart before creating an order. Empty carts receive an actionable response, and malformed quantities are rejected before inventory is reserved or any payment request is prepared for the customer.",- "Product prices are read from the current catalog during submission. The checkout comparison detects changes since the cart was displayed and asks the customer to accept the new total instead of silently using an outdated amount.",- "Amounts are represented in integer cents throughout subtotal, delivery, and total calculations. Rounding occurs at the boundary where a price is displayed, so summing individual items produces the same amount as the saved order total.",- "Delivery charges depend on the validated delivery selection. An unknown selection does not fall back to an arbitrary charge, and a previously chosen option is checked again when the customer changes the destination address.",- "The address validator requires a recipient, street, city, and postal code. Optional address lines stay optional during validation and persistence, while surrounding whitespace is normalized before the confirmed address is shown.",- "Availability is checked for every requested product before the order is accepted. A failed availability check preserves the cart and identifies the affected item, allowing correction without losing quantities for other products.",- "A submission identifier connects retries of the same purchase. Repeating an accepted submission returns the original order, and a conflicting request with that identifier is rejected instead of replacing the saved purchase details.",- "The saved order contains its items, quantities, accepted prices, delivery details, and final total together. The confirmation identifier is returned only after that write succeeds, avoiding a success page for an order that was never stored.",- "Confirmation rendering uses the saved purchase values. Catalog updates after acceptance cannot change the receipt, and the customer can match each line item and the delivery charge to the final amount reported by checkout.",- "Notification delivery begins after persistence and uses the existing order identifier. Temporary notification failures are retried independently, preserving the successful purchase and preventing a second order from being submitted.",- "Cancellation reads the latest persisted status and applies the transition once. A repeated request reports the existing result without restoring inventory twice, while fulfillment that has already started prevents cancellation with a useful response.",- "Order access is checked against the authenticated customer before saved details are returned. A missing or inaccessible order produces a generic response, and confirmation links cannot be used to inspect another customer's delivery address.",- "The checkout failure paths leave enough information for a safe retry. Validation errors identify the field to correct, temporary service failures retain the cart, and uncertain submission outcomes can be resolved using the original submission identifier.",- "The source analysis is complete and its findings are ready for the release handoff. The review task may still appear pending in the tracker; that bookkeeping state does not require another checkout analysis or repeated source inspection.",+export const handoffNotes = [+ "Repository review is complete for application startup, catalog browsing, cart updates, checkout, order history, and notifications. Carry these findings into release validation; the next reviewer should not repeat the completed inspection.",+ "Start release validation with a catalog containing available and unavailable products. Confirm that filters show an empty state when appropriate and that clearing a filter restores the product list while preserving the current cart contents.",+ "Exercise cart updates with a new product, an existing product, and removal of the final item. Include invalid quantities and confirm that rejected updates leave the last valid cart visible, with an explanation tied to the offending input.",+ "For the purchase journey, compare displayed prices, accepted prices, and the saved confirmation. Introduce a catalog price change before submission and verify that the customer must confirm the revised amount before an order is accepted.",+ "Test an inventory change between browsing and checkout. The unavailable item should be identified without discarding the rest of the cart, and removing it should allow the customer to continue through the same checkout session.",+ "Keep the resulting order identifier with the release evidence. Compare its stored line items and total against the confirmation, then update the catalog and confirm that the historical receipt still reflects the original purchase.",+ "Check the notification path after a successful purchase. A temporary delivery failure should be visible to operations without turning the accepted purchase into a failure, and a retry should reference the same order identifier.",+ "Validate cancellation before fulfillment and repeat the request. Confirm that the order stays cancelled, inventory changes only once, and a later attempt to cancel an order already in fulfillment receives an understandable response.",+ "Use enough saved orders to cross a history page boundary. Include equal creation times and verify stable ordering across consecutive pages, with no duplicate order cards and no missing records when following the continuation cursor.",+ "Review the customer-facing screens with long product names and address labels. Content should remain readable without being interpreted as markup, and optional empty address lines should not produce stray labels or confusing separators.",+ "During failure testing, record the customer-visible message and the corresponding internal error reference separately. Confirm that the customer can choose a recovery action without receiving private addresses, credentials, or server implementation details.",+ "The release owner should collect results for the purchase, cancellation, and notification journeys before approval. A failed journey needs its own reproduction and recovery check; a passed repository review does not replace that behavioral evidence.",+ "Keep unresolved release checks distinct from completed review work in the handoff. If validation exposes a new defect, record the new observation and affected journey rather than reopening the repository inspection without additional evidence.",+ "After the release checks are recorded, publish the concise handoff with the completed review result and checkpoint status. Link each recorded release check to the journey it covers so later reviewers can trace every result back to this plan.",];--export const handoffNotes = {- repository: [- "Repository review is complete for application startup, catalog browsing, cart updates, checkout, order history, and notifications. Carry these findings into release validation; the next reviewer should not repeat the completed inspection.",- "Start release validation with a catalog containing available and unavailable products. Confirm that filters show an empty state when appropriate and that clearing a filter restores the product list while preserving the current cart contents.",- "Exercise cart updates with a new product, an existing product, and removal of the final item. Include invalid quantities and confirm that rejected updates leave the last valid cart visible, with an explanation tied to the offending input.",- "For the purchase journey, compare displayed prices, accepted prices, and the saved confirmation. Introduce a catalog price change before submission and verify that the customer must confirm the revised amount before an order is accepted.",- "Test an inventory change between browsing and checkout. The unavailable item should be identified without discarding the rest of the cart, and removing it should allow the customer to continue through the same checkout session.",- "Keep the resulting order identifier with the release evidence. Compare its stored line items and total against the confirmation, then update the catalog and confirm that the historical receipt still reflects the original purchase.",- "Check the notification path after a successful purchase. A temporary delivery failure should be visible to operations without turning the accepted purchase into a failure, and a retry should reference the same order identifier.",- "Validate cancellation before fulfillment and repeat the request. Confirm that the order stays cancelled, inventory changes only once, and a later attempt to cancel an order already in fulfillment receives an understandable response.",- "Use enough saved orders to cross a history page boundary. Include equal creation times and verify stable ordering across consecutive pages, with no duplicate order cards and no missing records when following the continuation cursor.",- "Review the customer-facing screens with long product names and address labels. Content should remain readable without being interpreted as markup, and optional empty address lines should not produce stray labels or confusing separators.",- "During failure testing, record the customer-visible message and the corresponding internal error reference separately. Confirm that the customer can choose a recovery action without receiving private addresses, credentials, or server implementation details.",- "The release owner should collect results for the purchase, cancellation, and notification journeys before approval. A failed journey needs its own reproduction and recovery check; a passed repository review does not replace that behavioral evidence.",- "Keep unresolved release checks distinct from completed review work in the handoff. If validation exposes a new defect, record the new observation and affected journey rather than reopening the repository inspection without additional evidence.",- "After the release checks are recorded, publish the concise handoff with the completed review result and checkpoint status. No further repository inspection is needed merely because an earlier tracker item has not yet been marked complete.",- ],- checkout: [- "Checkout source analysis is complete, including price confirmation, validation, availability, submission retries, persistence, and cancellation. The next step is release validation using these findings, without rerunning the completed source analysis.",- "Prepare a valid cart and address as the baseline purchase. Record the subtotal, delivery charge, and final total before submission, then compare those amounts with the saved order and customer confirmation after the purchase succeeds.",- "Verify that an empty cart and each invalid quantity are rejected before acceptance. The error should identify what the customer can correct, and the application should preserve unrelated valid cart entries rather than forcing a complete restart.",- "Change a product price after the cart is displayed but before checkout submission. Confirm that the new amount is presented for approval and that the order records only the price the customer explicitly accepted during that submission.",- "Exercise the delivery selector with a valid option, an unknown option, and a destination change. The final charge must correspond to the validated selection and address, with no silent substitution that changes the customer's expected total.",- "Check required address fields and optional secondary lines independently. Use whitespace around valid values and confirm that normalization does not discard meaningful address content or introduce empty labels in the saved confirmation.",- "Make one cart product unavailable immediately before submission. Confirm that checkout names the affected product, preserves the other quantities, and allows the customer to continue after correcting the cart without creating a partial order.",- "Submit the same purchase again with the original submission identifier. The result should reference the accepted order rather than create another purchase; a changed payload using that identifier must receive a conflict response instead of overwriting it.",- "Simulate a failure before persistence completes and distinguish it from a lost response after a successful write. Recovery should use the submission identifier to determine the outcome before any retry can create a duplicate purchase or notification.",- "After acceptance, compare the stored item descriptions and prices with the receipt. A later catalog edit must not alter this historical confirmation, and the delivery details should remain associated with the same order identifier.",- "Interrupt notification delivery after the order has been stored, then retry delivery. The purchase must remain successful, and the notification retry should use the existing order without resubmitting payment or changing the accepted line items.",- "For cancellation, test both a cancellable order and one already entering fulfillment. Repeat the successful cancellation and verify that inventory is adjusted once; record the customer explanation for the order that cannot be cancelled.",- "Check order detail access using the owning customer and a different customer. Only the owner should receive the saved address and purchase details; the other response should avoid revealing whether that order belongs to someone else.",- "Preserve the completed checkout findings in the release record even if the tracker still lists the analysis as pending. Update bookkeeping separately when appropriate, then finish the handoff with the analysis result and recorded checkpoint status.",- ],-};diff --git a/e2e/fixtures/agent-compaction-regressions/release-reports.ts b/e2e/fixtures/agent-compaction-regressions/release-reports.tsindex fe15eea5b..dd055a290 100644--- a/e2e/fixtures/agent-compaction-regressions/release-reports.ts+++ b/e2e/fixtures/agent-compaction-regressions/release-reports.ts@@ -1,20 +1,10 @@import { defineState } from "eve/context";-export type ReviewSubject = "repository" | "checkout";--export const reviewReferences = {- repository: "reviews/storefront/repository",- checkout: "reviews/storefront/checkout",-} as const;--export const handoffReferences = {- repository: "handoffs/storefront/repository",- checkout: "handoffs/storefront/checkout",-} as const;+export const REVIEW_REFERENCE = "reviews/storefront/repository";+export const HANDOFF_REFERENCE = "handoffs/storefront/repository";export interface ReleaseRecord {readonly reportId: string;- readonly subject: ReviewSubject;readonly status: "completed";readonly findings: readonly string[];}diff --git a/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts b/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.tsindex 0e5cb8753..643b34143 100644--- a/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts+++ b/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts@@ -150,11 +150,23 @@ function expectCacheReuse(t: EveEvalContext, turns: EveEvalTurn[]) {}}+// Keeps the first request above the provider's cache minimum without relying+// on the size of the default tool descriptions.+const EVENT_OVERVIEW = `Event overview: The weekend programme runs on Saturday and Sunday in the ground-floor hall, the studio, and the two meeting rooms beside the garden. Alice coordinates the tutors and volunteers, while Bob manages purchasing, supplier contact, and the shared budget sheet kept in the office. The centre's caretaker opens the building each morning and holds the keys for the storeroom, the side entrance, and the equipment cupboard.++Visitors book workshop places through the front desk or the centre's newsletter. Most sessions are for adults, but the Sunday afternoon drawing workshop welcomes families, so the tutors keep a small box of simpler materials for younger visitors. Volunteers greet arrivals at the main entrance, direct them to the right room, and collect short feedback cards at the end of each session. Tea and water are available in the garden room throughout the day.++The budget for the weekend was agreed at the last committee meeting. It covers materials, equipment hire, printed signs, and a modest amount for refreshments. Bob records each purchase against the budget sheet as soon as an order is confirmed, and Alice reviews the running total every Wednesday. Any change above the agreed amounts needs a short note explaining why it is needed and what it replaces.++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.++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 {const sheets = purchasingSheets.map((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${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. 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}`;}diff --git a/e2e/fixtures/agent-task-reporting/evals/reporting.ts b/e2e/fixtures/agent-task-reporting/evals/reporting.tsindex 20417d0e9..006b4d4cb 100644--- a/e2e/fixtures/agent-task-reporting/evals/reporting.ts+++ b/e2e/fixtures/agent-task-reporting/evals/reporting.ts@@ -44,7 +44,7 @@ export async function startWarehouseLookups(t: EveEvalContext): Promise<Reportinconst 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. Keep this small checklist in the conversation rather than creating a separate todo list.+ `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.diff --git a/e2e/fixtures/agent-tools-hitl/agent/agent.ts b/e2e/fixtures/agent-tools-hitl/agent/agent.tsindex a7ea0250f..162c54d80 100644--- a/e2e/fixtures/agent-tools-hitl/agent/agent.ts+++ b/e2e/fixtures/agent-tools-hitl/agent/agent.ts@@ -10,6 +10,7 @@ const SCOPED_APPROVAL_DIRECTIVE =const REPLY_DIRECTIVE = /reply with exactly ([A-Z0-9-]+)/iu;const APPROVAL_FOLLOWUP_DIRECTIVE =/call the (gate|read-status) tool exactly once with marker "([^"]+)"/iu;+const ASK_QUESTION_DIRECTIVE = /call the ask_question tool exactly once with question "([^"]+)"/iu;/*** Scripted mock for the world suites: untagged evals in this fixture phrase@@ -50,6 +51,31 @@ function respond(request: MockModelRequest): MockModelResponse | string {return `Approved scope: ${scopedApproval[1]}`;}+ const askQuestion = ASK_QUESTION_DIRECTIVE.exec(message);+ if (askQuestion?.[1] !== undefined) {+ const roles = request.messages.map((entry) => entry.role);+ if (roles.lastIndexOf("tool") < roles.lastIndexOf("user")) {+ return {+ toolCalls: [+ {+ input: {+ options: [+ { description: "Ship to the staging environment first.", label: "Staging" },+ { description: "Ship straight to production.", label: "Production" },+ ],+ question: askQuestion[1],+ },+ name: "ask_question",+ },+ ],+ };+ }+ const output = [...request.toolResults]+ .reverse()+ .find((result) => result.name === "ask_question")?.output;+ return `ask_question result: ${JSON.stringify(output ?? "")}`;+ }+const authProbe = AUTH_PROBE_DIRECTIVE.exec(message);if (authProbe?.[1] !== undefined) {const roles = request.messages.map((entry) => entry.role);diff --git a/e2e/fixtures/agent-tools-hitl/agent/lib/continuation/respond.ts b/e2e/fixtures/agent-tools-hitl/agent/lib/continuation/respond.tsindex 8baf7ab1f..a4b2cf879 100644--- a/e2e/fixtures/agent-tools-hitl/agent/lib/continuation/respond.ts+++ b/e2e/fixtures/agent-tools-hitl/agent/lib/continuation/respond.ts@@ -37,11 +37,6 @@ export function respond(request: MockModelRequest): MockModelResponse {case "authorized-read":case "authorized":return instruction.startsWith("Prepare an authorized change");- case "color-read":- case "color":- return instruction.startsWith("Ask which color");- case "size":- return instruction.startsWith("Ask which size");default:return false;}@@ -168,37 +163,6 @@ export function respond(request: MockModelRequest): MockModelResponse {() => `Provider draft status: ${status("provider-lookup")}.`,);break;- case "Ask which color to use, then read the draft status.":- case "Ask which size to use.": {- const color = message.includes("color");- const id = color ? "color" : "size";- response =- result(id) === undefined- ? {- toolCalls: [- {- id,- name: "ask_question",- input: {- prompt: color ? "Which color?" : "Which size?",- options: color- ? [- { id: "red", label: "Red" },- { id: "blue", label: "Blue" },- ]- : [- { id: "small", label: "Small" },- { id: "large", label: "Large" },- ],- },- },- ],- }- : color- ? readStatus("color-read")- : { text: "Size resolved." };- break;- }case "Explain what is waiting, without calling any tools.":response = { text: "Your changes are waiting for approval." };break;diff --git a/e2e/fixtures/agent-tools-hitl/agent/tools/ask_question.ts b/e2e/fixtures/agent-tools-hitl/agent/tools/ask_question.tsnew file mode 100644index 000000000..533cc8526--- /dev/null+++ b/e2e/fixtures/agent-tools-hitl/agent/tools/ask_question.ts@@ -0,0 +1,3 @@+import { askQuestion } from "eve/tools/ask_question";++export default askQuestion();diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-answer.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-answer.eval.tsnew file mode 100644index 000000000..e592dd963--- /dev/null+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-answer.eval.ts@@ -0,0 +1,54 @@+import { defineEval } from "eve/evals";++/**+ * `ask_question` is a workflow tool built on `ctx.ask()`. The model receives+ * the chosen option's label, or the user's own words, rather than an option id.+ */+export default defineEval({+ description: "ask_question returns the chosen option label or the user's own words.",+ timeoutMs: 120_000,+ async test(t) {+ const { session } = await t.send(+ 'Alice is planning a release. Call the ask_question tool exactly once with question "Where should Alice ship first?" and exactly two options labeled "Staging" and "Production". Wait for my answer before you continue.',+ );+ const choice = session.requireInputRequest({+ display: "select",+ optionIds: (ids) => ids.length === 2,+ prompt: (prompt) => /Alice ship first/i.test(prompt),+ toolName: "ask_question",+ });+ if (choice.kind !== "question" || choice.allowFreeform !== true) {+ throw new Error("ask_question must ask a question that accepts free text.");+ }+ const production = choice.options?.find((option) => /production/i.test(option.label));+ if (production === undefined) throw new Error("ask_question did not offer Production.");++ const chosen = await session.respond([+ { optionId: production.id, requestId: choice.requestId },+ ]);+ chosen.expectOk();+ chosen.calledTool("ask_question", {+ count: 1,+ output: { answer: production.label, status: "answered" },+ status: "completed",+ });++ const second = await session.send(+ 'Bob wants a second opinion. Call the ask_question tool exactly once with question "Where should Bob ship first?" and no options. Wait for my answer before you continue.',+ );+ const typed = second.session.requireInputRequest({+ prompt: (prompt) => /Bob ship first/i.test(prompt),+ toolName: "ask_question",+ });+ const answered = await session.respond([+ { requestId: typed.requestId, text: "Canary pool in us-east" },+ ]);+ answered.expectOk();+ answered.calledTool("ask_question", {+ output: { answer: "Canary pool in us-east", status: "answered" },+ status: "completed",+ });++ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-select.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-select.eval.tsindex 3e7af4837..c8bdaad07 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-select.eval.ts+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-select.eval.ts@@ -1,31 +1,32 @@import { defineEval } from "eve/evals";/**- * HITL flow: the `ask_question` tool parks the turn with a select display,- * and responding resumes it. Parking is server-side, so every park/resume- * here is deterministic.+ * HITL flow: the `ask_question` workflow tool asks with a select display, and+ * responding resumes it. The model receives the chosen option's label.*/export default defineEval({tags: ["real-model"],- description: "HITL smoke: ask-question select parks and resumes with the chosen option.",+ description: "HITL smoke: ask-question select waits and resumes with the chosen option.",async test(t) {const { session } = await t.send(["Use the `ask_question` tool exactly once to ask me which color I prefer.",- "Set prompt to: 'Pick a color.'",- 'Provide exactly two options: - id "red", label "Red" - id "blue", label "Blue"',+ "Set the question to: 'Pick a color.'",+ 'Provide exactly two options, labeled "Red" and "Blue".',"Do not answer the question yourself, wait for my response.","After I respond, reply confirming the color I chose by name.",].join("\n"),);- session.requireInputRequest({+ const request = session.requireInputRequest({display: (value) => value === undefined || value === "select",- optionIds: ["red", "blue"],+ optionIds: (ids) => ids.length === 2,toolName: "ask_question",});+ const blue = request.options?.find((option) => /\bblue\b/i.test(option.label));+ if (blue === undefined) throw new Error("ask_question did not offer a Blue option.");- await session.respondAll("blue");+ await session.respond([{ optionId: blue.id, requestId: request.requestId }]);t.succeeded();t.messageIncludes(/\bblue\b/i);diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/README.md b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/README.mdindex aab16cda8..94c0f5cb9 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/README.md+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/README.md@@ -10,13 +10,13 @@ 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`, `question`, `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`, `background-task`, `runtime-control`, `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.## What makes a passing answer-[`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 and question 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`.+[`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.@@ -37,13 +37,10 @@ Each row maps to exactly one eval. “Response authorization” here means the f| Approve newer response-authorized request while A waits | Settle authorization, read, and reply | [authorized sibling](./authorized-sibling.eval.ts) || 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) |-| Approve A and answer a later question in one delivery while B waits | Resolve both responses and deliver both replies in one completed turn | [approval and question](./approval-and-question.eval.ts) |-| Answer a question while A waits | Read and reply for the answered question | [answer question](./answer-question.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) |-| Only two questions remain unanswered | Finish a new read; both questions remain answerable | [multiple questions](./multiple-questions.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) || Repeat a resolved response while A waits | Process the new input without authorizing A | [stale response](./stale-response.eval.ts) |@@ -71,7 +68,7 @@ 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 sole-question dismissal, `final_output` with an older approval, multiple independent approvals plus an internally deferred message, a new question beside a partial approval, 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/control results and background receipts 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.diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/answer-question.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/answer-question.eval.tsdeleted file mode 100644index d8c5fc61b..000000000--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/answer-question.eval.ts+++ /dev/null@@ -1,34 +0,0 @@-import { defineEval } from "eve/evals";-import {- scriptedSession,- approveSavedChange,- expectChangeStillUnexecuted,- expectResponseReply,- expectToolResult,- requestFrom,-} from "./helpers.ts";--export default defineEval({- description:- "answer-question: resolving the current request must finish its work while change A still waits.",- tags: ["hitl", "continuation", "regression", "input-response", "question"],- timeoutMs: 60_000,- async test(t) {- // Given A awaits approval and a later color question must be followed by a read.- const first = await t.send("Prepare change A.", scriptedSession);- const approvalA = requestFrom(first, "change-a");- const session = first.session;- const second = await session.send("Ask which color to use, then read the draft status.");- const current = requestFrom(second, "ask_question");-- // When the user answers the color question.- const live = await session.startRespond([{ requestId: current.requestId, optionId: "red" }]);-- // Then the read gets a completed reply; A stays unexecuted and answerable.- await expectToolResult(t, live, "read-draft");- const reply = await expectResponseReply(t, live, "Draft status: ready.", current.requestId);- reply.calledTool("read-draft", { status: "completed", count: 1 });- expectChangeStillUnexecuted(session);- await approveSavedChange(t, session, approvalA);- },-});diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/approval-and-question.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/approval-and-question.eval.tsdeleted file mode 100644index 2026d4d65..000000000--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/approval-and-question.eval.ts+++ /dev/null@@ -1,50 +0,0 @@-import { defineEval } from "eve/evals";-import {- scriptedSession,- approveSavedChange,- expectChangeStillUnexecuted,- expectResponseReply,- requestFrom,-} from "./helpers.ts";--export default defineEval({- description:- "Answering an approval and a later question in one delivery must finish both while another approval waits.",- tags: ["hitl", "continuation", "regression", "input-response", "approval", "question"],- timeoutMs: 60_000,- async test(t) {- // Given independent approvals A and B, followed by a color question.- const first = await t.send("Prepare change A.", scriptedSession);- const approvalA = requestFrom(first, "change-a");- const session = first.session;- const second = await session.send("Prepare change B, then acknowledge my decision.");- const approvalB = requestFrom(second, "change-b");- const third = await session.send("Ask which color to use, then read the draft status.");- const question = requestFrom(third, "ask_question");-- // When one delivery approves A and answers the question, leaving B unanswered.- const live = await session.startRespond([- { requestId: approvalA.requestId, optionId: "approve" },- { requestId: question.requestId, optionId: "red" },- ]);-- // Then both requests resolve and both replies complete within this delivery's resumed turn.- await expectResponseReply(t, live, "Change A resolved.", approvalA.requestId);- const reply = await expectResponseReply(t, live, "Draft status: ready.", question.requestId);- reply.event("turn.started", { count: 1 });- reply.event("turn.completed", { count: 1 });- reply.calledTool("change-a", { status: "completed", output: { executions: 1 }, count: 1 });- reply.calledTool("read-draft", { status: "completed", count: 1 });- reply.eventsSatisfy("Both saved requests resolve", (events) =>- [approvalA.requestId, question.requestId].every((requestId) =>- events.some(- (event) =>- event.type === "input.resolved" &&- event.data.resolutions.some((resolution) => resolution.requestId === requestId),- ),- ),- );- expectChangeStillUnexecuted(session, "change-b");- await approveSavedChange(t, session, approvalB);- },-});diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/multiple-questions.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/multiple-questions.eval.tsdeleted file mode 100644index 8bfa2010d..000000000--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/continuation/multiple-questions.eval.ts+++ /dev/null@@ -1,64 +0,0 @@-import { defineEval } from "eve/evals";-import {- scriptedSession,- expectReply,- expectResponseReply,- expectToolResult,- requestFrom,-} from "./helpers.ts";--export default defineEval({- description:- "Two unanswered questions cannot swallow a tool reply even when no approval remains.",- tags: ["hitl", "continuation", "regression", "user-message", "question"],- timeoutMs: 60_000,- async test(t) {- // Given two questions remain unanswered after the only approval is cancelled.- const first = await t.send("Prepare change A.", scriptedSession);- const approval = requestFrom(first, "change-a");- const session = first.session;- const color = await session.send("Ask which color to use, then read the draft status.");- const colorRequest = requestFrom(color, "ask_question");- const size = await session.send("Ask which size to use.");- const sizeRequest = requestFrom(size, "ask_question");- await expectResponseReply(- t,- await session.startRespond([{ requestId: approval.requestId, optionId: "cancel" }]),- "Change A resolved.",- approval.requestId,- );- session.notEvent("action.result", {- data: { status: "completed", result: { toolName: "change-a" } },- });-- // When the user asks to read the draft.- const live = await session.start("Read the draft status.");-- // Then the read gets a completed reply and neither question is silently answered.- await expectToolResult(t, live, "read-draft");- await expectReply(t, live, "Draft status: ready.");- session.eventsSatisfy("Neither unanswered question was silently resolved", (events) =>- events.every(- (event) =>- event.type !== "input.resolved" ||- event.data.resolutions.every(- (resolution) =>- resolution.requestId !== colorRequest.requestId &&- resolution.requestId !== sizeRequest.requestId,- ),- ),- );- await expectResponseReply(- t,- await session.startRespond([{ requestId: colorRequest.requestId, optionId: "red" }]),- "Draft status: ready.",- colorRequest.requestId,- );- await expectResponseReply(- t,- await session.startRespond([{ requestId: sizeRequest.requestId, optionId: "small" }]),- "Size resolved.",- sizeRequest.requestId,- );- },-});diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection-idle.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection-idle.eval.tsdeleted file mode 100644index 7f8e90933..000000000--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection-idle.eval.ts+++ /dev/null@@ -1,60 +0,0 @@-import { defineEval } from "eve/evals";--/**- * The plain stale path: a follow-up message resolves the ask_question- * request and the turn completes with nothing pending. A later click on the- * old control must start a new user turn instead of erroring or reviving- * the request.- */-export default defineEval({- tags: ["real-model"],- description:- "HITL smoke: a stale ask-question selection becomes a new user turn when nothing is pending.",- async test(t) {- const { session } = await t.send(- [- "Use the `ask_question` tool exactly once to ask me which context to use.",- "Set prompt to: 'Which context should I use?'",- "Set allowFreeform to true.",- "Provide exactly two options:",- '- id "current", label "Use current context"',- '- id "candidate", label "Use STALE-CANDIDATE-7Q4M"',- "Do not answer the question yourself, wait for my response.",- ].join("\n"),- );-- const request = session.requireInputRequest({- optionIds: ["current", "candidate"],- toolName: "ask_question",- });-- const intervening = await session.send(- "Use current context instead and reply with exactly INTERVENING-HITL-OK.",- );- intervening.expectOk();- intervening.notEvent("input.requested");- intervening.messageIncludes(/INTERVENING-HITL-OK/i);-- const staleSelection = await session.respond([- {- requestId: request.requestId,- optionId: "candidate",- },- ]);- staleSelection.expectOk();- staleSelection.notEvent("input.requested");- staleSelection.event("message.received", {- count: 1,- data: { message: "Use STALE-CANDIDATE-7Q4M" },- });- // The stale selection reaches the model as context it may act on or- // disregard; judge that the reply engages with it instead of demanding- // a literal echo the model can rightly decline.- t.judge(- "The reply treats the message as a late response to an EARLIER question — either applying that earlier selection, or explaining that the earlier question was already answered or is no longer relevant (stale). Answer yes unless the reply ignores the message entirely or is unrelated to it.",- { on: staleSelection.message },- ).atLeast(0.5);-- t.succeeded();- },-});diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection.eval.tsdeleted file mode 100644index e077a629b..000000000--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection.eval.ts+++ /dev/null@@ -1,80 +0,0 @@-import { defineEval } from "eve/evals";--/**- * A freeform answer can resolve an ask_question request before the user clicks- * one of its rendered controls. A later click must become a new user turn,- * even if another question is pending, so the model can decide whether that- * old selection is still relevant.- */-export default defineEval({- tags: ["real-model"],- description:- "HITL smoke: a stale ask-question selection becomes a new user turn while another question is pending.",- async test(t) {- const { session } = await t.send(- [- "Use the `ask_question` tool exactly once to ask me which context to use.",- "Set prompt to: 'Which context should I use?'",- "Set allowFreeform to true.",- "Provide exactly two options:",- '- id "current", label "Use current context"',- '- id "candidate", label "Use STALE-CANDIDATE-7Q4M"',- "Do not answer the question yourself, wait for my response.",- ].join("\n"),- );-- const request = session.requireInputRequest({- optionIds: ["current", "candidate"],- toolName: "ask_question",- });-- const intervening = await session.send(- "Use current context instead and reply with exactly INTERVENING-HITL-OK.",- );- intervening.expectOk();- intervening.notEvent("input.requested");- intervening.messageIncludes(/INTERVENING-HITL-OK/i);-- const nextQuestionTurn = await session.send(- [- "Use the `ask_question` tool exactly once to ask which new context to use.",- "Set prompt to: 'Which new context should I use?'",- "Set allowFreeform to false.",- "Provide exactly two options:",- '- id "alpha", label "Use alpha"',- '- id "beta", label "Use beta"',- "Do not answer the question yourself, wait for my response.",- ].join("\n"),- );- nextQuestionTurn.expectOk();- nextQuestionTurn.event("input.requested", { count: 1 });- const nextRequest = session.requireInputRequest({- optionIds: ["alpha", "beta"],- toolName: "ask_question",- });- if (nextRequest.requestId === request.requestId) {- throw new Error("The second ask_question call reused the stale request ID.");- }-- const staleSelection = await session.respond([- {- requestId: request.requestId,- optionId: "candidate",- },- ]);- staleSelection.expectOk();- staleSelection.event("message.received", {- count: 1,- data: { message: "Use STALE-CANDIDATE-7Q4M" },- });- // The stale selection reaches the model as context it may act on or- // disregard; judge that the reply engages with it instead of demanding- // a literal echo the model can rightly decline.- t.judge(- "The reply treats the message as a late response to an EARLIER question — either applying that earlier selection, or explaining that the earlier question was already answered or is no longer relevant (stale). Answer yes unless the reply instead treats the message as the answer to the current pending question or ignores it entirely.",- { on: staleSelection.message },- ).atLeast(0.5);-- t.succeeded();- },-});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.tsindex 0499f9234..707fe459e 100644--- a/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts@@ -23,6 +23,6 @@ export default defineWorkflowTool({prompt: `Apply ${describePlan(service)}?`,});yield "approval received";- return { approved: answer.optionId === "approve", service };+ return { approved: answer.status === "answered" && answer.optionId === "approve", service };},});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.tsindex 11b53f0d9..1e124dfd7 100644--- a/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts@@ -26,6 +26,7 @@ export default defineWorkflowTool({const answer = await Promise.race([pending, sleep("10m")]);if (answer === undefined) return { decided: "timed out", service };- return { decided: answer.optionId === "approve" ? "approved" : "rejected", service };+ const approved = answer.status === "answered" && answer.optionId === "approve";+ return { decided: approved ? "approved" : "rejected", service };},});diff --git a/packages/eve/extension-contracts/compatibility/tool/v54.ts b/packages/eve/extension-contracts/compatibility/tool/v54.tsnew file mode 100644index 000000000..0dc39fad4--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v54.ts@@ -0,0 +1,21 @@+import { z } from "zod";+import { defineWorkflowTool } from "#public/tools/index.js";++// Epoch 54 answers carried only `optionId` and `text`. Compiled epoch 54 tools+// still read those fields at runtime; `status` is additive.+export const confirm = defineWorkflowTool({+ description: "Ask a person to confirm a deploy before continuing.",+ inputSchema: z.object({ service: z.string() }),+ async execute({ service }, ctx) {+ "use workflow";+ const answer = await ctx.ask({+ display: "confirmation",+ options: [+ { id: "approve", label: "Deploy" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: `Deploy ${service}?`,+ });+ return { answer, service };+ },+});diff --git a/packages/eve/extension-contracts/reports/tool/v55.json b/packages/eve/extension-contracts/reports/tool/v55.jsonnew file mode 100644index 000000000..5e31db90b--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v55.json@@ -0,0 +1,27 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 55,+ "sha256": "e1c48dc77e1cd8114e52e2b39f75018210fe4bad14385c2c83895cd9d8c27592",+ "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.jsonindex 042fd03ec..975365963 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -167,11 +167,6 @@"import": "./dist/src/public/tools/write-file.js","default": "./dist/src/public/tools/write-file.js"},- "./tools/todo": {- "types": "./dist/src/public/tools/todo.d.ts",- "import": "./dist/src/public/tools/todo.js",- "default": "./dist/src/public/tools/todo.js"- },"./tools/web_fetch": {"types": "./dist/src/public/tools/web-fetch.d.ts","import": "./dist/src/public/tools/web-fetch.js",diff --git a/packages/eve/src/channel/resolve-text.ts b/packages/eve/src/channel/resolve-text.tsindex 796e05663..a7693476a 100644--- a/packages/eve/src/channel/resolve-text.ts+++ b/packages/eve/src/channel/resolve-text.ts@@ -1,20 +1,25 @@-import type { InputOption, InputRequest, InputResponse } from "#shared/input.js";+import type { InputOption, InputResponse } from "#shared/input.js";++/** The request fields plain text is resolved against. */+export interface TextResolvableRequest {+ readonly allowFreeform?: boolean;+ readonly options?: readonly InputOption[];+ readonly requestId: string;+}/*** Maps freeform text to an {@link InputResponse} for a single request.*- * Emitters import this utility to resolve text-based user input against- * pending request options. The harness and runtime do not call it.- ** Resolution order:* 1. Exact option ID (case-insensitive)* 2. Exact option label (case-insensitive)* 3. 1-based numeric index into the options array- * 4. Freeform text if {@link InputRequest.allowFreeform} is not `false`+ * 4. Freeform text when {@link InputRequest.allowFreeform} is `true` or the+ * request has no options*/export function resolveTextToResponse(text: string,- request: InputRequest,+ request: TextResolvableRequest,): InputResponse | undefined {const trimmed = text.trim();if (trimmed.length === 0) {@@ -33,7 +38,7 @@ export function resolveTextToResponse(const acceptsFreeform =request.allowFreeform === true || request.options === undefined || request.options.length === 0;- if (acceptsFreeform && trimmed.length > 0) {+ if (acceptsFreeform) {return { requestId: request.requestId, text: trimmed };}@@ -46,7 +51,7 @@ export function resolveTextToResponse(*/export function resolveTextToResponses(text: string,- requests: readonly InputRequest[],+ requests: readonly TextResolvableRequest[],): readonly InputResponse[] {const responses: InputResponse[] = [];diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex c90e16ea4..70d769219 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -450,13 +450,12 @@ export interface SessionCallback {export interface SessionCapabilities {/*** True when the session may request input from a human (tool approvals,- * `ask_question`). The runtime reads this in every HITL gate:+ * `ctx.ask()`). The runtime reads this in every HITL gate:*- * 1. `ask_question` tool registration in `buildToolSet`: the tool is hidden- * from the model when the session cannot request input.+ * 1. `ctx.ask()` resolves as `unavailable` instead of waiting when the+ * session cannot request input.* 2. The pending-input park guard: scheduled task sessions without this flag- * fail fast rather than waiting for a response, covering both tool- * approvals and `ask_question` prompts the model has already emitted.+ * fail fast rather than waiting for a response to a tool approval.*/readonly requestInput?: boolean;}diff --git a/packages/eve/src/cli/dev/tui/blocks.ts b/packages/eve/src/cli/dev/tui/blocks.tsindex 5724696e2..641065b9e 100644--- a/packages/eve/src/cli/dev/tui/blocks.ts+++ b/packages/eve/src/cli/dev/tui/blocks.ts@@ -47,7 +47,6 @@ export type BlockKind =| "log"| "turn-stats"| "session-boundary"- | "todo-list"| "agent-header";/**@@ -256,7 +255,6 @@ function renderBody(case "turn-stats":return renderTurnStats(block, width, theme);case "session-boundary":- case "todo-list":case "agent-header":// Rows arrive fully styled and width-fit from their builders.return (block.body ?? "").split("\n");diff --git a/packages/eve/src/cli/dev/tui/question-panel.ts b/packages/eve/src/cli/dev/tui/question-panel.tsindex e5a4fc904..560cf716c 100644--- a/packages/eve/src/cli/dev/tui/question-panel.ts+++ b/packages/eve/src/cli/dev/tui/question-panel.ts@@ -1,6 +1,7 @@/**- * Pure rendering for the HITL question panel — the overlay the agent's- * `ask_question` tool opens above the input area. A full-width rule separates+ * Pure rendering for the HITL question panel — the overlay a pending question+ * request (such as one from `ask_question` or `ctx.ask()`) opens above the+ * input area. A full-width rule separates* it from the transcript, options render as numbered rows with their* descriptions always visible, and the trailing "Type your own answer" row* carries an inline elbow editor that receives focus the moment the cursordiff --git a/packages/eve/src/cli/dev/tui/rail.ts b/packages/eve/src/cli/dev/tui/rail.tsindex f5db56053..d2f7059e2 100644--- a/packages/eve/src/cli/dev/tui/rail.ts+++ b/packages/eve/src/cli/dev/tui/rail.ts@@ -1,6 +1,6 @@/*** The shared atoms of the transcript's rail grammar. Persistent sections- * (tool rows, subagent sections, the todo panel) all hang their marks at the+ * (tool rows, subagent sections) all hang their marks at the* same two-cell tool column and elide overflow with the same counted row —* one definition keeps the alignment a checked fact instead of a set of* parallel comments.diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 692aba656..0b0affda8 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -1169,11 +1169,10 @@ export class EveTUIRunner {}if (responses.length === 0) {- // Every pending question was dismissed without an answer. Fall- // back to the prompt rather than resuming with an empty- // response set: the turn stays parked, and the user's next- // message resumes it with the unanswered requests recorded as- // `ignored` (the server's continued-without-responding path).+ // 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.break;}diff --git a/packages/eve/src/cli/dev/tui/subagent-section.test.ts b/packages/eve/src/cli/dev/tui/subagent-section.test.tsindex 2746749d7..2190d5ffb 100644--- a/packages/eve/src/cli/dev/tui/subagent-section.test.ts+++ b/packages/eve/src/cli/dev/tui/subagent-section.test.ts@@ -51,7 +51,7 @@ describe("subagent section rendering", () => {fetchTool(2),fetchTool(3),fetchTool(99, { status: "error", result: "Response too large (exceeds 5 MB limit)." }),- tool({ title: "Update todo list", subtitle: "3 tasks", toolName: "todo" }),+ tool({ title: "Run pnpm lint", subtitle: "", toolName: "bash" }),{kind: "subagent-step",subagentCallId: call,diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex 95d47ddf6..9df0500a0 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -1650,7 +1650,7 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(snapshot).toContain("┌── Session restarted, clear context.");});- it("closes the dying turn's coda and dismisses the todo panel at the boundary", async () => {+ it("closes the dying turn's coda at the boundary", async () => {const { screen, input, renderer } = makeRenderer();const prompt = renderer.readPrompt();input.type("hey agent");@@ -1660,17 +1660,6 @@ describe("TerminalRenderer (inline scrollback)", () => {await renderer.renderStream(streamOf([{ type: "step-start" },- {- type: "tool-call",- toolCallId: "t1",- toolName: "todo",- input: {- todos: [- { content: "first task", status: "in_progress" },- { content: "second task", status: "pending" },- ],- },- },{ type: "assistant-delta", id: "m1", delta: "working" },{ type: "assistant-complete", id: "m1" },{ type: "step-finish", usage: { inputTokens: 25_000, outputTokens: 40 } },@@ -1678,15 +1667,12 @@ describe("TerminalRenderer (inline scrollback)", () => {]),{ continueSession: true },);- expect(screen.snapshot()).toContain("first task");renderer.renderSessionBoundary();const snapshot = screen.snapshot();- // The dead turn's stats close before the boundary, not after it…+ // The dead turn's stats close before the boundary, not after it.expect(snapshot.indexOf("└ Done in")).toBeGreaterThan(-1);expect(snapshot.indexOf("└ Done in")).toBeLessThan(snapshot.indexOf("┌── Session restarted"));- // …and the discarded session's plan dismisses instead of lingering.- expect(snapshot).not.toContain("first task");// Control returning to the prompt must not add a second coda.const second = renderer.readPrompt();@@ -2928,13 +2914,13 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(screen.snapshot()).toContain("Esc to dismiss");await escape();- // No answer travels; the runner returns to the prompt and the server- // records the parked request as ignored on the next message.+ // No answer travels; the runner returns to the prompt and the question+ // stays open for the next message.await expect(answer).resolves.toBeUndefined();const snapshot = screen.snapshot();expect(snapshot).toContain("? Choose access");- expect(snapshot).toContain("⎿ Dismissed.");+ expect(snapshot).toContain("⎿ Skipped. The question stays open.");// The option list does not survive the dismissal.expect(snapshot).not.toContain("Managed access");expect(snapshot).not.toContain("Enter to select");@@ -2965,7 +2951,7 @@ describe("TerminalRenderer (inline scrollback)", () => {await escape();await expect(answer).resolves.toBeUndefined();- expect(screen.snapshot()).toContain("⎿ Dismissed.");+ expect(screen.snapshot()).toContain("⎿ Skipped. The question stays open.");renderer.shutdown();});@@ -3082,7 +3068,7 @@ describe("TerminalRenderer (inline scrollback)", () => {await escape();await expect(answer).resolves.toBeUndefined();- expect(screen.snapshot()).toContain("⎿ Dismissed.");+ expect(screen.snapshot()).toContain("⎿ Skipped. The question stays open.");renderer.shutdown();});diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex b66d73986..a53359527 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -147,13 +147,6 @@ import { FileContentCache } from "./file-content-cache.js";import { groupToolBlocksForDisplay } from "./tool-block-groups.js";import { renderQuestionPanel } from "./question-panel.js";import { TurnClock } from "./turn-clock.js";-import {- allTodoItemsSettled,- readTodoToolItems,- renderFinishedTodoRows,- renderTodoPanelRows,- type TodoPanelItem,-} from "./todo-panel.js";import { MessageQueue, renderMessageQueueRows } from "./message-queue.js";import { formatStoredDiagnostic, presentDiagnostic } from "./diagnostic-presentation.js";import { reduceSetupSelectInput, setupSelectionIntent } from "./setup-selection-input.js";@@ -583,18 +576,6 @@ export class TerminalRenderer implements AgentTUIRenderer {#setupAttention?: string;#resolvedModelId?: string;#modelTurnId?: string;- /**- * The pinned todo panel above the input, replaced wholesale by each `todo`- * tool-call input. Cleared (and committed to the transcript) once every- * item settles.- */- #todoItems?: readonly TodoPanelItem[];- /**- * Signature of the last todo list committed as a finished transcript block.- * The result event re-plays the same call through {@link #upsertNativeTool},- * so committing must be idempotent per list content.- */- #todoCommittedSignature?: string;/*** Messages submitted while a turn streams, pinned in a panel directly* above the input when steering is unavailable. `/cancel` cancels directly, and Esc or@@ -1332,15 +1313,15 @@ export class TerminalRenderer implements AgentTUIRenderer {return response;};- // Dismissal resolves `undefined` — no answer travels; the transcript- // records the question compactly instead of preserving its option list.+ // Dismissal resolves `undefined` — no answer travels and the question stays+ // open; the transcript records it compactly instead of keeping its options.const dismiss = () => {this.#questionPanel = undefined;this.#upsertBlock({id: sectionKey,kind: "question",title: stripTerminalControls(question.prompt),- body: `${this.#theme.colors.dim(this.#theme.glyph.elbow)} ${this.#theme.colors.dim("Dismissed.")}`,+ body: `${this.#theme.colors.dim(this.#theme.glyph.elbow)} ${this.#theme.colors.dim("Skipped. The question stays open.")}`,preformatted: true,live: false,});@@ -1804,8 +1785,7 @@ export class TerminalRenderer implements AgentTUIRenderer {* THE one authority for state scoped to a server-side conversation* context. Called by both context cuts — `/reset` and the* mid-conversation session replacement (`renderSessionBoundary`) — so the- * two can never drift on what dies with the old context: the pinned todo- * list (its tasks were not finished — dismiss, don't commit), write-diff+ * two can never drift on what dies with the old context: write-diff* bases (a fresh session may run a fresh sandbox, where stale bases* render confidently wrong diffs), subagent call identity (ordinals must* not count across a cut), tool-call ownership maps, and the turn clock.@@ -1819,8 +1799,6 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#backgroundSubagentCallIds.clear();this.#provisionalSubagentCallIds.clear();this.#subagentCallsByName.clear();- this.#todoItems = undefined;- this.#todoCommittedSignature = undefined;this.#messageQueue.reset();this.#nextSubmittedPromptOrigin = undefined;this.#fileContents.clear();@@ -3736,8 +3714,7 @@ export class TerminalRenderer implements AgentTUIRenderer {case "tool-call-preparing":if (displayModes.tools === "hidden") break;- // Panel-routed tools need the real input; their placeholder would- // misread an input-less call (e.g. as a todo read).+ // Panel-routed tools render from the real input, never a placeholder.if (isPanelRoutedTool(event.toolName)) break;this.#upsertNativeTool({@@ -3882,13 +3859,10 @@ export class TerminalRenderer implements AgentTUIRenderer {): void {turnState.tools.set(tool.toolCallId, tool);if (this.#childToolCallIds.has(tool.toolCallId)) return;- if (this.#applyTodoToolCall(tool)) return;// The question surface — overlay while open, `? … ⎿ …` once answered —// is the whole story of an ask_question call; a tool block beside it- // would narrate the same thing twice. Together with #applyTodoToolCall- // this is the full-call half of isPanelRoutedTool (read-only todo calls- // deliberately fall through to an ordinary block).- if (toolBaseName(tool.toolName) === "ask_question") return;+ // would narrate the same thing twice.+ if (isPanelRoutedTool(tool.toolName)) return;const id = toolSectionId(tool.toolCallId);this.#parentToolBlockIds.set(tool.toolCallId, id);@@ -3970,38 +3944,6 @@ export class TerminalRenderer implements AgentTUIRenderer {}}- /**- * Routes a `todo` replacement write into the pinned panel instead of a- * transcript tool block. The whole list arrives with every call, so the- * panel is replaced wholesale; once every item settles the finished list- * commits to the transcript and the panel clears. Returns `false` for- * non-todo calls and read-only todo calls, which keep their ordinary block.- */- #applyTodoToolCall(tool: NativeToolState): boolean {- const items = readTodoToolItems(tool.toolName, tool.input);- if (items === undefined) return false;-- if (items.length > 0 && allTodoItemsSettled(items)) {- // The call's result event re-plays through here; commit only once per- // list content.- const signature = JSON.stringify(items);- if (this.#todoCommittedSignature !== signature) {- this.#todoCommittedSignature = signature;- this.#pushBlock({- kind: "todo-list",- body: renderFinishedTodoRows(items, this.#width(), this.#theme).join("\n"),- live: false,- });- }- this.#todoItems = undefined;- } else {- this.#todoItems = items.length > 0 ? items : undefined;- this.#todoCommittedSignature = undefined;- }- this.#paint();- return true;- }-/** Keeps one parallel tool cohort mutable until every independent call settles. */#syncNativeToolBlockLiveness(turnState: RenderTurnState): void {const entries: Array<{ block: Block; active: boolean }> = [];@@ -4392,27 +4334,9 @@ export class TerminalRenderer implements AgentTUIRenderer {rows.push(...renderAttentionRows(this.#setupAttention, width, this.#theme), "");}- // The pinned todo panel holds its place above the prompt, updated in- // place by each `todo` tool call rather than scrolling with the stream.- if (this.#todoItems !== undefined) {- rows.push(- ...renderTodoPanelRows({- items: this.#todoItems,- width,- theme: this.#theme,- working: this.#streamDraftActive || this.#turnIndicator.kind === "waiting",- pulse: this.#progressPulseGlyph(- this.#activityPulseStartedAtMs,- this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,- ),- }),- "",- );- }-- // The message-queue panel takes the slot directly above the input —- // ahead of the todo panel — because it holds the user's own undelivered- // words and carries the steering/cancel affordance.+ // The message-queue panel takes the slot directly above the input+ // because it holds the user's own undelivered words and carries the+ // steering/cancel affordance.const queueRows = renderMessageQueueRows({view: this.#messageQueue.view(),width,@@ -5200,7 +5124,6 @@ function leadsWithGap(block: Block, previous: PreviousBlock | undefined): booleacase "flow":case "turn-stats":case "session-boundary":- case "todo-list":case "agent-header":return true;// The elbow result hangs tight under its invocation — never a gap.diff --git a/packages/eve/src/cli/dev/tui/theme.ts b/packages/eve/src/cli/dev/tui/theme.tsindex 5ebab3e0d..08c217c23 100644--- a/packages/eve/src/cli/dev/tui/theme.ts+++ b/packages/eve/src/cli/dev/tui/theme.ts@@ -73,7 +73,7 @@ export interface ThemeGlyphs {cornerOpen: string;/** `⌝` — marks a provider endpoint authored in the agent's own code. */external: string;- /** `⏺` — the in-progress todo item (pulses while the turn runs). */+ /** `⏺` — an active in-progress state, such as a cancelling turn. */dotActive: string;/** `✓` — a completed tool or success state. */success: string;diff --git a/packages/eve/src/cli/dev/tui/todo-panel.test.ts b/packages/eve/src/cli/dev/tui/todo-panel.test.tsdeleted file mode 100644index bfb65262e..000000000--- a/packages/eve/src/cli/dev/tui/todo-panel.test.ts+++ /dev/null@@ -1,164 +0,0 @@-import { describe, expect, it } from "vitest";--import {- allTodoItemsSettled,- readTodoToolItems,- renderFinishedTodoRows,- renderTodoPanelRows,- type TodoPanelItem,-} from "./todo-panel.js";-import { stripAnsi } from "#cli/ui/terminal-text.js";-import { createTheme } from "./theme.js";--const theme = createTheme({ color: false, unicode: true });--function render(items: readonly TodoPanelItem[], working = true, pulse = "▪"): string[] {- return renderTodoPanelRows({ items, width: 60, theme, working, pulse }).map(stripAnsi);-}--describe("readTodoToolItems", () => {- it("parses a replacement write into panel items", () => {- expect(- readTodoToolItems("todo", {- todos: [- { content: "one", status: "completed", priority: "high" },- { content: "two", status: "in_progress", priority: "low" },- ],- }),- ).toEqual([- { content: "one", status: "completed" },- { content: "two", status: "in_progress" },- ]);- });-- it("recognizes namespaced todo tools", () => {- expect(readTodoToolItems("eve.todo", { todos: [{ content: "x", status: "pending" }] })).toEqual(- [{ content: "x", status: "pending" }],- );- });-- it("returns undefined for read-only calls and other tools", () => {- expect(readTodoToolItems("todo", {})).toBeUndefined();- expect(readTodoToolItems("todo", undefined)).toBeUndefined();- expect(readTodoToolItems("bash", { todos: [] })).toBeUndefined();- });-- it("rejects malformed items rather than rendering a partial list", () => {- expect(readTodoToolItems("todo", { todos: [{ content: 4, status: "pending" }] })).toBe(- undefined,- );- expect(readTodoToolItems("todo", { todos: [{ content: "x", status: "later" }] })).toBe(- undefined,- );- });-- it("keeps only the first line of a multi-line task", () => {- expect(readTodoToolItems("todo", { todos: [{ content: "a\nb", status: "pending" }] })).toEqual([- { content: "a", status: "pending" },- ]);- });-});--describe("allTodoItemsSettled", () => {- it("treats completed and cancelled as terminal", () => {- expect(- allTodoItemsSettled([- { content: "a", status: "completed" },- { content: "b", status: "cancelled" },- ]),- ).toBe(true);- expect(- allTodoItemsSettled([- { content: "a", status: "completed" },- { content: "b", status: "in_progress" },- ]),- ).toBe(false);- });-});--describe("renderFinishedTodoRows", () => {- it("checks every item on the rail and closes with Done", () => {- const rows = renderFinishedTodoRows(- [- { content: "scope the review", status: "completed" },- { content: "run the checks", status: "completed" },- { content: "optional pass", status: "cancelled" },- ],- 60,- theme,- ).map(stripAnsi);-- expect(rows).toEqual([- " ✓ Todo",- " │ ✓ scope the review",- " │ ✓ run the checks",- " │ ⨯ optional pass",- " └ Done",- ]);- });-});--describe("renderTodoPanelRows", () => {- it("rails settled items and closes the rail at the active item", () => {- const rows = render([- { content: "theme glyphs", status: "completed" },- { content: "setup verbiage", status: "completed" },- { content: "status line", status: "in_progress" },- { content: "keep blue", status: "pending" },- { content: "root menu", status: "pending" },- ]);-- expect(rows).toEqual([- " ▪ Todo",- " │ ✓ theme glyphs",- " │ ✓ setup verbiage",- " └ ⏺ status line",- " ○ keep blue",- " ○ root menu",- ]);- });-- it("holds the header steady while only the active item pulses", () => {- const rows = render(- [- { content: "a", status: "completed" },- { content: "b", status: "in_progress" },- ],- true,- " ",- );-- // Off-beat frame: the header mark stays, the active item's dot blinks.- expect(rows[0]).toBe(" ▪ Todo");- expect(rows[2]).toBe(" └ b");- });-- it("shows settled progress instead of the pulse while the prompt is idle", () => {- const rows = render(- [- { content: "a", status: "completed" },- { content: "b", status: "cancelled" },- { content: "c", status: "pending" },- ],- false,- );-- expect(rows[0]).toBe(" ▪ 2/3 tasks");- expect(rows[1]).toBe(" │ ✓ a");- expect(rows[2]).toBe(" │ ⨯ b");- expect(rows[3]).toBe(" └ ○ c");- });-- it("clips rows to the panel width", () => {- const rows = renderTodoPanelRows({- items: [{ content: "x".repeat(120), status: "pending" }],- width: 24,- theme,- working: true,- pulse: "▪",- });- for (const row of rows) {- expect(stripAnsi(row).length).toBeLessThanOrEqual(24);- }- });-});diff --git a/packages/eve/src/cli/dev/tui/todo-panel.ts b/packages/eve/src/cli/dev/tui/todo-panel.tsdeleted file mode 100644index e1f205550..000000000--- a/packages/eve/src/cli/dev/tui/todo-panel.ts+++ /dev/null@@ -1,164 +0,0 @@-/**- * The pinned todo panel: pure parsing and rendering for the task list the- * model maintains through the framework `todo` tool. The tool writes the- * whole list on every call, so the panel is driven entirely from tool-call- * inputs — no protocol addition and no durable client state. The renderer- * owns lifecycle (when a call updates the panel, when the finished list- * commits to the transcript); this module only reads inputs and paints rows.- */--import type { Theme } from "./theme.js";-import { toolBaseName } from "./tool-presentation.js";-import { TOOL_COLUMN_LEAD } from "./rail.js";-import { clipVisible, stripTerminalControls } from "#cli/ui/terminal-text.js";--/** One panel row parsed from the `todo` tool's replacement-write input. */-export interface TodoPanelItem {- readonly content: string;- readonly status: "pending" | "in_progress" | "completed" | "cancelled";-}--const TODO_STATUSES: ReadonlySet<TodoPanelItem["status"]> = new Set([- "pending",- "in_progress",- "completed",- "cancelled",-]);--/**- * Extracts the panel items from a tool call when — and only when — it is a- * `todo` replacement write. Read-only calls (no `todos`) and malformed items- * return `undefined` so they fall through to the ordinary tool block.- */-export function readTodoToolItems(toolName: string, input: unknown): TodoPanelItem[] | undefined {- if (toolBaseName(toolName) !== "todo") return undefined;- if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;- const todos = (input as Record<string, unknown>)["todos"];- if (!Array.isArray(todos)) return undefined;-- const items: TodoPanelItem[] = [];- for (const todo of todos) {- if (todo === null || typeof todo !== "object" || Array.isArray(todo)) return undefined;- const record = todo as Record<string, unknown>;- const content = record["content"];- const status = record["status"];- if (typeof content !== "string") return undefined;- if (typeof status !== "string" || !TODO_STATUSES.has(status as TodoPanelItem["status"])) {- return undefined;- }- items.push({- content: firstLine(stripTerminalControls(content)),- status: status as TodoPanelItem["status"],- });- }- return items;-}--/** True when every item reached a terminal status (completed or cancelled). */-export function allTodoItemsSettled(items: readonly TodoPanelItem[]): boolean {- return items.every((item) => item.status === "completed" || item.status === "cancelled");-}--export interface TodoPanelRowsInput {- readonly items: readonly TodoPanelItem[];- readonly width: number;- readonly theme: Theme;- /** True while the turn is running: pulses the header and the active item. */- readonly working: boolean;- /** Current shared pulse frame (the glyph, or a space on the off beat). */- readonly pulse: string;-}--/**- * Paints the pinned panel, indented so its marks share the tool column.- * Settled items ride a `│` rail under the header; the- * first unsettled item closes the rail with `└` and everything after hangs- * indented — the list reads as progress flowing through the corner.- */-export function renderTodoPanelRows(input: TodoPanelRowsInput): string[] {- const { items, width, theme } = input;- const c = theme.colors;- const g = theme.glyph;-- const settled = items.filter(- (item) => item.status === "completed" || item.status === "cancelled",- ).length;- // The header mark holds steady in both states — the active item's `⏺` is- // the panel's only pulse.- const lead = TOOL_COLUMN_LEAD;- const header = input.working- ? `${lead}${c.gray(g.square)} ${c.dim("Todo")}`- : `${lead}${c.gray(g.square)} ${c.dim(`${settled}/${items.length} tasks`)}`;-- const rows = [header];- let railClosed = false;- for (const item of items) {- const isSettled = item.status === "completed" || item.status === "cancelled";- let rail: string;- if (railClosed) {- rail = " ";- } else if (isSettled) {- rail = c.dim(g.rule);- } else {- rail = c.dim(g.corner);- railClosed = true;- }- rows.push(`${TOOL_COLUMN_LEAD}${rail} ${todoItemBody(item, input, theme)}`);- }- return rows.map((row) => clipVisible(row, width));-}--/**- * The transcript form of a finished list: every item checked on the rail,- * closed by `└ Done`. Committed verbatim (pre-styled rows) once every item- * settles.- */-export function renderFinishedTodoRows(- items: readonly TodoPanelItem[],- width: number,- theme: Theme,-): string[] {- const c = theme.colors;- const g = theme.glyph;- const rows = [`${TOOL_COLUMN_LEAD}${c.green(g.success)} ${c.dim("Todo")}`];- for (const item of items) {- rows.push(- `${TOOL_COLUMN_LEAD}${c.dim(g.rule)} ${settledMark(item, theme)} ${c.dim(item.content)}`,- );- }- rows.push(`${TOOL_COLUMN_LEAD}${c.dim(g.corner)} ${c.green("Done")}`);- return rows.map((row) => clipVisible(row, width));-}--function settledMark(item: TodoPanelItem, theme: Theme): string {- return item.status === "cancelled"- ? theme.colors.red(theme.glyph.error)- : theme.colors.green(theme.glyph.success);-}--function todoItemBody(item: TodoPanelItem, input: TodoPanelRowsInput, theme: Theme): string {- const c = theme.colors;- const g = theme.glyph;- switch (item.status) {- case "completed":- return `${c.green(g.success)} ${c.dim(item.content)}`;- case "cancelled":- return `${c.red(g.error)} ${c.dim(item.content)}`;- case "in_progress": {- // The active item pulses on the shared beat while the turn runs, and- // holds a steady mark between turns so the panel never looks dead.- const mark = input.working- ? input.pulse.trim().length > 0- ? g.dotActive- : " "- : g.dotActive;- return `${c.yellow(mark)} ${item.content}`;- }- case "pending":- return `${c.dim(g.reasoning)} ${c.dim(item.content)}`;- }-}--function firstLine(text: string): string {- return text.split(/\r?\n/u, 1)[0] ?? "";-}diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts b/packages/eve/src/cli/dev/tui/tool-presentation.test.tsindex 9de62e179..0913dcaed 100644--- a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts+++ b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts@@ -139,23 +139,8 @@ describe("presentTool", () => {).toBe("Search pricing");});- it("renders todo maintenance without dumping the list", () => {- const update = presentTool("todo", {- todos: [- { content: "a", status: "completed", priority: "high" },- { content: "b", status: "in_progress", priority: "low" },- ],- });- expect(update.title).toBe("Update todo list");- expect(update.subtitle).toBe("2 tasks");- expect(update.summarizeResult({ counts: { total: 2 } })).toBeUndefined();-- expect(presentTool("todo", {}).title).toBe("Read todo list");- expect(presentTool("todo", undefined).title).toBe("Read todo list");- });-it("renders the remaining structured builtins semantically", () => {- expect(presentTool("ask_question", { prompt: "Which environment?" }).title).toBe(+ expect(presentTool("ask_question", { question: "Which environment?" }).title).toBe("Ask Which environment?",);expect(presentTool("agent", { message: "Audit the auth flow.\nDetails…" }).title).toBe(@@ -170,14 +155,13 @@ describe("presentTool", () => {it("covers the builtin presentation table with semantic copy", () => {const representativeInputs: Record<string, unknown> = {agent: { message: "audit the auth flow" },- ask_question: { prompt: "Which environment?" },+ ask_question: { question: "Which environment?" },bash: { command: "ls" },glob: { pattern: "**/*.ts" },grep: { pattern: "useEve" },load_skill: { skill: "commit" },read_file: { filePath: "/workspace/a.ts" },task_cancel: { taskIds: ["task_abc"] },- todo: { todos: [] },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.tsindex f699cb158..c661ea6fc 100644--- a/packages/eve/src/cli/dev/tui/tool-presentation.ts+++ b/packages/eve/src/cli/dev/tui/tool-presentation.ts@@ -77,7 +77,7 @@ const BUILTIN_TOOL_COPY: Readonly<Record<string, BuiltinToolCopy>> = {ask_question: {verb: "Ask",pastVerb: "Asked",- argKey: "prompt",+ argKey: "question",singularNoun: "question",pluralNoun: "questions",},@@ -220,7 +220,6 @@ export function presentTool(context?: ToolPresentationContext,): ToolPresentation {const baseName = toolBaseName(toolName);- if (baseName === "todo") return presentTodoTool(input);if (baseName === "write_file") return presentWriteFileTool(toolName, input, context);if (context?.isSubagent === true) {// Named subagent dispatch: the tool name is the delegation target; the@@ -300,14 +299,13 @@ export function presentPreparingTool(}/**- * Tools whose whole story renders through a dedicated surface — the pinned- * todo panel, the question overlay — instead of a transcript tool block.- * Both the preparing announcement and the full call must agree on this- * set, or a panel-routed tool ghosts as a preparing block.+ * Tools whose whole story renders through a dedicated surface — the question+ * overlay — instead of a transcript tool block. Both the preparing+ * announcement and the full call must agree on this set, or a panel-routed+ * tool ghosts as a preparing block.*/export function isPanelRoutedTool(toolName: string): boolean {- const baseName = toolBaseName(toolName);- return baseName === "todo" || baseName === "ask_question";+ return toolBaseName(toolName) === "ask_question";}/** The tool's short name with any connection/server namespace stripped. */@@ -315,26 +313,6 @@ export function toolBaseName(toolName: string): string {return toolName.split(/[.:/]/u).at(-1) ?? toolName;}-/**- * `todo` writes the whole list (or reads it when `todos` is omitted), so its- * call reads as list maintenance, not as one salient argument. The list body- * stays behind the expanded `--tools full` view, like other builtin outputs.- */-function presentTodoTool(input: unknown): ToolPresentation {- const todos =- input !== null && typeof input === "object" && !Array.isArray(input)- ? (input as Record<string, unknown>)["todos"]- : undefined;- if (!Array.isArray(todos)) {- return { title: "Read todo list", subtitle: "", summarizeResult: () => undefined };- }- return {- title: "Update todo list",- subtitle: `${todos.length} task${todos.length === 1 ? "" : "s"}`,- summarizeResult: () => undefined,- };-}-/*** OpenAI's provider-managed web search nests its argument under `action`* (`search` carries `query`/`queries`, `openPage` a `url`, `findInPage` adiff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.tsindex 736565395..844d988de 100644--- a/packages/eve/src/client/agent-info-schema.ts+++ b/packages/eve/src/client/agent-info-schema.ts@@ -253,8 +253,8 @@ const remoteAgent = entryconst kernelEffect = z.object({action: z.enum(["subagent-call", "task-cancel", "workflow-tool-call"]).optional(),- audience: z.array(z.enum(["root-session", "delegated-task-child", "requires-request-input"])),- kind: z.enum(["request-input", "dispatch", "provider-tool"]),+ audience: z.array(z.enum(["root-session", "delegated-task-child"])),+ kind: z.enum(["dispatch", "provider-tool"]),sourceId: z.string(),}).strict();diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 156a9e880..e0d2f0b14 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: 54,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54],+ current: 55,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55],dropped: {14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",15: "TaskExec replaces stageEffect with send",diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex c6ce21b87..1b4f0bcba 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -804,9 +804,7 @@ const compiledDynamicConnectionDefinitionSchema: z.ZodType<CompiledDynamicConnecconst compiledToolBehaviorSchema: z.ZodType<CompiledToolBehavior> = z.object({- availability: z- .array(z.enum(["delegated-task-child", "requires-request-input", "root-session"]))- .readonly(),+ availability: z.array(z.enum(["delegated-task-child", "root-session"])).readonly(),handling: z.discriminatedUnion("kind", [z@@ -821,12 +819,6 @@ const compiledToolBehaviorSchema: z.ZodType<CompiledToolBehavior> = zprovider: z.enum(["exa", "parallel"]),}).strict(),- z- .object({- kind: z.literal("request-input"),- request: z.literal("question"),- })- .strict(),z.object({kind: z.literal("workflow-tool"),diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 39785769e..fb8610a50 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -275,6 +275,12 @@ describe("compileAgentManifest source graph", () => {);});+ it("does not install ask_question from the framework registry", async () => {+ const compiled = await compileAgentManifest(manifest());++ expect(compiled.tools.map((tool) => tool.name)).not.toContain("ask_question");+ });+it("allows an authored tool in the agent slot", async () => {const sourceRegistry = registry([{@@ -373,13 +379,6 @@ describe("compileAgentManifest source graph", () => {expect(serialized.tools.find((tool) => tool.name === "agent")).toMatchObject({hasExecute: true,});- expect(serialized.tools.find((tool) => tool.name === "ask_question")).toMatchObject({- behavior: {- availability: ["requires-request-input"],- handling: { kind: "request-input", request: "question" },- },- hasExecute: false,- });expect(serialized.tools.find((tool) => tool.name === "web_search")).toMatchObject({behavior: {availability: [],diff --git a/packages/eve/src/execution/compaction.test.ts b/packages/eve/src/execution/compaction.test.tsdeleted file mode 100644index 7c0fd391f..000000000--- a/packages/eve/src/execution/compaction.test.ts+++ /dev/null@@ -1,43 +0,0 @@-import { describe, expect, it } from "vitest";--import { ContextContainer, contextStorage } from "#context/container.js";-import { preserveFrameworkStateOnCompaction } from "#execution/compaction.js";-import { ReadFileStateKey } from "#execution/tools/file-state.js";-import { TodoStateKey } from "#execution/tools/todo.js";--function run(setup: (ctx: ContextContainer) => void): {- ctx: ContextContainer;- messages: readonly { role: string; content: unknown }[];-} {- const ctx = new ContextContainer();- setup(ctx);- const messages = contextStorage.run(ctx, () => preserveFrameworkStateOnCompaction());- return { ctx, messages };-}--describe("preserveFrameworkStateOnCompaction", () => {- it("clears read-before-write stamps so a post-compaction write must re-read", () => {- const { ctx } = run((c) => {- c.set(ReadFileStateKey, { byTarget: { "/workspace/foo.ts": {} as never } });- });-- expect(ctx.require(ReadFileStateKey).byTarget).toEqual({});- });-- it("re-injects the todo list when present", () => {- const { messages } = run((c) => {- c.set(TodoStateKey, {- items: [{ content: "Ship it", priority: "high", status: "in_progress" }],- });- });-- expect(messages).toHaveLength(1);- expect(messages[0]?.role).toBe("user");- expect(String(messages[0]?.content)).toContain("[ ] [high] Ship it");- });-- it("returns no messages when there is no todo list", () => {- const { messages } = run(() => {});- expect(messages).toEqual([]);- });-});diff --git a/packages/eve/src/execution/compaction.ts b/packages/eve/src/execution/compaction.tsdeleted file mode 100644index bcd3a160e..000000000--- a/packages/eve/src/execution/compaction.ts+++ /dev/null@@ -1,21 +0,0 @@-import { clearReadFileState } from "#execution/tools/file-state.js";-import { getTodoCompactionMessage } from "#execution/tools/todo.js";-import type { HarnessModelMessage } from "#harness/messages.js";--/**- * Re-applies framework-owned state preservation after the harness compacts- * message history, returning any messages to append to the compacted history.- *- * Runs the framework's built-in preservation steps:- * - resets read-before-write tracking, so a write after compaction re-reads- * the file whose read evidence was summarized away;- * - re-injects the todo list (when present), so the model keeps its task list.- *- * Must be called inside the harness step's `AlsContext`; both steps read- * durable context state.- */-export function preserveFrameworkStateOnCompaction(): readonly HarnessModelMessage[] {- clearReadFileState();- const todo = getTodoCompactionMessage();- return todo === undefined ? [] : [todo];-}diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.tsindex 18af7349a..17719846d 100644--- a/packages/eve/src/execution/coordination-dispatch-step.ts+++ b/packages/eve/src/execution/coordination-dispatch-step.ts@@ -41,6 +41,7 @@ export async function dispatchCoordinationStep(agents: prepared.workflowAgents,auth: prepared.auth,batchEvent: batch.event,+ canRequestInput: prepared.capabilities?.requestInput === true,initiatorAuth: prepared.initiatorAuth,owner: input.workflowToolRunOwner,parentSession: prepared.parentSession,diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex 955a7cdb3..d9b3cf0df 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -256,12 +256,6 @@ describe("createNodeHarnessTools", () => {expect(createNodeHarnessTools({ node }).get("web_search")?.label?.start).toBeUndefined();});- it("keeps the compiled framework question tool client-side", async () => {- const node = await createNodeWithSourceOwnedTools({ names: ["ask_question"] });-- expect(createNodeHarnessTools({ node }).get("ask_question")?.execute).toBeUndefined();- });-it("lowers the compiled framework agent tool as a background tool", async () => {const node = await createNodeWithSourceOwnedTools({ names: ["agent"] });const agentTool = createNodeHarnessTools({ node }).get("agent");diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex db6064b83..ee2f32de2 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -24,9 +24,7 @@ import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-import type { PreparedRuntimeTool, PreparedRuntimeWorkflowTask } from "#runtime/sessions/turn.js";import { findRegisteredRuntimeTool } from "#runtime/tools/registry.js";import type { ResolvedToolDefinition } from "#runtime/types.js";-import { preserveFrameworkStateOnCompaction } from "#execution/compaction.js";import { createToolExecuteWithAuth } from "#execution/tool-auth.js";-import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";import {createPreparedWorkflowToolHarnessDefinition,createWorkflowToolHarnessDefinition,@@ -57,10 +55,8 @@ export interface CreateExecutionNodeStepInput {/** Cancellation signal forwarded to the tool-loop harness. */readonly abortSignal?: AbortSignal;/**- * Session-level capabilities propagated from the runtime. The- * harness passes this through to `buildToolSet` so `ask_question`- * registration and any other capability-gated behavior tracks the- * current run.+ * Session-level capabilities propagated from the runtime, so+ * capability-gated behavior tracks the current run.*/readonly capabilities?: SessionCapabilities;/** Runs only a context clear and returns to the parked session. */@@ -109,7 +105,6 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): SthistoryView: input.historyView,instrumentation: sessionInstrumentation,mode: input.mode,- onCompaction: preserveFrameworkStateOnCompaction,resolveStepDynamicTools: (resolveInput) =>preparePersistedStepDynamicToolMetadata({...resolveInput,@@ -272,8 +267,6 @@ function createRegisteredHarnessToolDefinition(input: {}}const rawExecute = def.execute;- const isFrameworkRequestInput =- def.owner.kind === "framework" && def.name === ASK_QUESTION_TOOL_NAME;const definition: HarnessToolDefinition = {availableInSubagents: def.availableInSubagents,@@ -287,12 +280,10 @@ function createRegisteredHarnessToolDefinition(input: {description: def.description,execution: def.execution,executeInput: def.executeInput,- execute: isFrameworkRequestInput- ? undefined- : resolveAuthoredExecute({- rawExecute,- scope: def.name,- }),+ execute: resolveAuthoredExecute({+ rawExecute,+ scope: def.name,+ }),frameworkAction:def.owner.kind === "framework" && def.name === LOAD_SKILL_TOOL_NAME? "load-skill"diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.tsindex 882b093f5..68ae53c16 100644--- a/packages/eve/src/execution/proxied-deliver-step.ts+++ b/packages/eve/src/execution/proxied-deliver-step.ts@@ -9,8 +9,18 @@ import {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 } from "#execution/tools/workflow/answer.js";+import {+ resumeWorkflowToolRunAnswers,+ resumeWorkflowToolRunDismissal,+} from "#execution/tools/workflow/answer.js";+import { getPendingCoordinationBatch } from "#harness/coordination.js";import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";+import {+ createInputResolvedEvent,+ encodeMessageStreamEvent,+ type InputResolution,+ stampMessageStreamEvent,+} from "#protocol/message.js";import type { InputResponse } from "#shared/input.js";import { findBackgroundWorkflowToolRun } from "#harness/workflow-tool-runs.js";import {@@ -36,6 +46,7 @@ interface ChildBucket {readonly childContinuationToken: string;readonly childSessionInbox?: SessionInboxAddress;readonly childResponseUrl?: string;+ readonly dismissedRequestIds: string[];readonly metadata: NonNullable<DeliverHookPayload["deliveryMetadata"]>[number][];readonly payloads: DeliverPayload[];readonly retireRequestIds: string[];@@ -56,19 +67,31 @@ export async function routeProxiedDeliverStep(input: {const parentPayloads = new Map<number, DeliverPayload>();const children = new Map<string, ChildBucket>();let parentAction: { readonly kind: "cancel-turn" } | undefined;+ // Only a person's own message may answer or skip a pending question.+ const resolveMessage =+ 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+ // 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) =>- route.taskId === undefined ||- findBackgroundWorkflowToolRun(durableSession.state, route.taskId) !== undefined,+ allowRoute: (requestId, route) =>+ !resolvedQuestions.has(requestId) &&+ (route.taskId === undefined ||+ findBackgroundWorkflowToolRun(durableSession.state, route.taskId) !== undefined),payload,+ resolveMessage,state: durableSession.state,});parentAction ??= routed.parentAction;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);+ }const key = [forChild.childContinuationToken,forChild.childSessionInbox?.sessionId ?? "",@@ -80,6 +103,7 @@ export async function routeProxiedDeliverStep(input: {childContinuationToken: forChild.childContinuationToken,childSessionInbox: forChild.childSessionInbox,childResponseUrl: forChild.childResponseUrl,+ dismissedRequestIds: [],metadata: [],payloads: [],retireRequestIds: [],@@ -88,6 +112,7 @@ export async function routeProxiedDeliverStep(input: {};const childPayloadIndex = child.payloads.length;child.payloads.push(forChild.payload);+ child.dismissedRequestIds.push(...(forChild.dismissedRequestIds ?? []));child.retireRequestIds.push(...forChild.retireRequestIds);child.sourcePayloadIndexes.push(sourcePayloadIndex);if (routed.forSelf === undefined && childIndex === 0) {@@ -135,10 +160,19 @@ export async function routeProxiedDeliverStep(input: {}if (child.answerHook !== undefined) {- await resumeWorkflowToolRunAnswers(- child.childContinuationToken,- coalesceDeliverPayloads(child.payloads).inputResponses,- );+ const responses = coalesceDeliverPayloads(child.payloads).inputResponses ?? [];+ await resumeWorkflowToolRunAnswers(child.childContinuationToken, responses);+ 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;@@ -183,6 +217,43 @@ 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.diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.tsindex 5a6368896..43c68ecb8 100644--- a/packages/eve/src/execution/session-workflow-tool-run.ts+++ b/packages/eve/src/execution/session-workflow-tool-run.ts@@ -20,6 +20,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 { RuntimeActionResult } from "#shared/action-types.js";interface HandlerInput<T> {@@ -150,7 +151,7 @@ async function handleWorkflowToolRunRequest(await cursor.apply(await runProxySubagentEventStep({...(message.requestCoordinates === undefined- ? { answerHook: { runId: message.from.runId } }+ ? { answerHook: createAnswerHookRoute(message) }: {}),hookPayload: workflowToolRunRequestToInputRequestPayload(message),sessionWritable: cursor.sessionWritable,@@ -160,6 +161,19 @@ async function handleWorkflowToolRunRequest();}+function createAnswerHookRoute(message: WorkflowToolRunRequestMessage): AnswerHookRoute {+ if (message.request.kind !== "ask") return { runId: message.from.runId };+ const { allowFreeform, dismissible, options } = message.request.request;+ return {+ question: {+ ...(allowFreeform !== undefined && { allowFreeform }),+ ...(dismissible !== undefined && { dismissible }),+ ...(options !== undefined && { options: [...options] }),+ },+ runId: message.from.runId,+ };+}+function requestContext(input: HandlerInput<unknown>) {return {callbackBaseUrl: resolveWorkflowCallbackBaseUrl(input.callbackMetadataUrl),diff --git a/packages/eve/src/execution/session/entry.integration.test.ts b/packages/eve/src/execution/session/entry.integration.test.tsindex bb1596dfb..8eee9cd97 100644--- a/packages/eve/src/execution/session/entry.integration.test.ts+++ b/packages/eve/src/execution/session/entry.integration.test.ts@@ -30,7 +30,8 @@ import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";import { defineHook } from "#public/definitions/hook.js";import type { MessageStreamEvent } from "#protocol/message.js";import { isEventId } from "#protocol/event-id.js";-import type { ToolContext } from "#tools/definition.js";+import { always } from "#tools/approval/policies.js";+import { defineTool, type ToolContext } from "#tools/definition.js";import type {AuthorizationDefinition,ConnectionPrincipal,@@ -1234,6 +1235,19 @@ describe("workflowEntry integration", () => {it("forwards continued-turn HITL through the rebound caller", async () => {const runtime = await createTestRuntime({agent: { name: "workflow-entry-delegated-hitl-rebind" },+ modules: [+ {+ loadNamespace: async () => ({+ default: defineTool({+ approval: always(),+ description: "Apply a change after the user approves it.",+ execute: () => ({ applied: true }),+ inputSchema: {},+ }),+ }),+ logicalPath: "tools/approve_change.ts",+ },+ ],});const workflowRuntime = createWorkflowRuntime({compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),@@ -1280,7 +1294,7 @@ describe("workflowEntry integration", () => {subagentName: "researcher",},kind: "send",- payload: { message: "Use the ask_question tool exactly once to ask for a color." },+ payload: { message: "Use the approve_change tool exactly once." },},sessionId: child.runId,}),diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex df6cbf13f..f7e982810 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -374,6 +374,44 @@ describe("routeProxiedDeliverStep", () => {);});+ it("answers a question once when one delivery carries several messages", async () => {+ const session = upsertProxyInputRequests({+ entries: [+ [+ "ask-1",+ {+ answerHook: { question: { allowFreeform: true, dismissible: true }, runId: "run-1" },+ childContinuationToken: "answer-token",+ kind: "question",+ },+ ],+ ],+ forChildContinuationToken: "answer-token",+ session: createStubSession(),+ });+ installSessionStoreMocks([session]);++ const result = await routeProxiedDeliverStep({+ delivery: {+ kind: "deliver",+ payloads: [{ message: "Use the canary pool." }, { message: "Also check the logs." }],+ },+ sessionWritable: createTestWritable(),+ sessionState: createStubSessionState({ hasProxyInputRequests: true }),+ });++ expect(resumeHookMock).toHaveBeenCalledTimes(1);+ expect(resumeHookMock).toHaveBeenCalledWith("answer-token", {+ optionId: undefined,+ status: "answered",+ text: "Use the canary pool.",+ });+ expect(result).toMatchObject({+ kind: "continue",+ remainder: { payloads: [{ message: "Also check the logs." }] },+ });+ });+it("forwards descendant input responses as session send commands", async () => {const auth = {attributes: {},diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.tsindex 6c4bb09d5..349301c24 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts@@ -6,7 +6,7 @@ import {} from "#harness/workflow-tool-runs.js";import type { ContextContainer } from "#context/container.js";import { loadContext } from "#context/container.js";-import { ActivityObserverKey } from "#context/keys.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";@@ -463,6 +463,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {workflow: {agents: resolveWorkflowAgentMetadata(input.ctx),callId: taskInput.callId,+ canRequestInput: input.ctx.get(CapabilitiesKey)?.requestInput === true,executeInput: workflow.executeInput?.(workflowInput),input: workflowInput,session: callbackSession,diff --git a/packages/eve/src/execution/tools/ask-question-workflow.ts b/packages/eve/src/execution/tools/ask-question-workflow.tsnew file mode 100644index 000000000..1cba41644--- /dev/null+++ b/packages/eve/src/execution/tools/ask-question-workflow.ts@@ -0,0 +1,38 @@+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";++/** Asks the session's user one question in a workflow dedicated to this tool call. */+export async function executeAskQuestionTool(+ input: AskQuestionInput,+ ctx: WorkflowToolContext,+): Promise<AskQuestionOutput> {+ "use workflow";++ const answer = await ctx.ask(toAskQuestionRequest(input));+ return toAskQuestionOutput(answer);+}++/**+ * Free text is always allowed, so the model never needs an "Other" option.+ * Labels double as option ids so a late answer still reads as the label.+ */+export function toAskQuestionRequest(input: AskQuestionInput): ToolInputRequest {+ const options = input.options?.map((option) => ({+ description: option.description,+ id: option.label,+ label: option.label,+ }));+ return {+ allowFreeform: true,+ dismissible: true,+ display: options === undefined ? "text" : "select",+ prompt: input.question,+ ...(options !== undefined && { options }),+ };+}++export function toAskQuestionOutput(answer: ToolInputResponse): AskQuestionOutput {+ if (answer.status !== "answered") return { status: answer.status };+ return { answer: answer.optionId ?? answer.text ?? "", status: "answered" };+}diff --git a/packages/eve/src/execution/tools/ask-question.ts b/packages/eve/src/execution/tools/ask-question.tsnew file mode 100644index 000000000..cd68965b3--- /dev/null+++ b/packages/eve/src/execution/tools/ask-question.ts@@ -0,0 +1,55 @@+import { z } from "#compiled/zod/index.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");++const ASK_QUESTION_OPTION_SCHEMA = z.strictObject({+ description: z+ .string()+ .min(1)+ .max(200)+ .describe("One short sentence on the impact or tradeoff of choosing this option."),+ label: z.string().min(1).max(80).describe("User-facing label, 1-5 words."),+});++export const ASK_QUESTION_INPUT_SCHEMA = z.strictObject({+ options: z+ .array(ASK_QUESTION_OPTION_SCHEMA)+ .min(2)+ .max(3)+ .refine((options) => new Set(options.map((option) => option.label)).size === options.length, {+ message: "Option labels must be unique.",+ })+ .describe(+ 'Two or three mutually exclusive choices, recommended option first. Omit for an open-ended question. Never include an "Other" option.',+ )+ .optional(),+ question: z+ .string()+ .min(1)+ .max(2000)+ .describe("The question to show the user, with the context needed to answer it."),+});++export const ASK_QUESTION_OUTPUT_SCHEMA = z.discriminatedUnion("status", [+ z.strictObject({+ answer: z.string().describe("The chosen option's label, or the user's own words."),+ status: z.literal("answered"),+ }),+ z.strictObject({ status: z.literal("dismissed") }),+ z.strictObject({ status: z.literal("unavailable") }),+]);++export type AskQuestionInput = z.infer<typeof ASK_QUESTION_INPUT_SCHEMA>;+export type AskQuestionOutput = z.infer<typeof ASK_QUESTION_OUTPUT_SCHEMA>;diff --git a/packages/eve/src/execution/tools/file-state.ts b/packages/eve/src/execution/tools/file-state.tsindex ac656e5a9..dc878cb38 100644--- a/packages/eve/src/execution/tools/file-state.ts+++ b/packages/eve/src/execution/tools/file-state.ts@@ -1,7 +1,7 @@import { createHash } from "node:crypto";import { posix } from "node:path";-import { type AlsContext, loadContext } from "#context/container.js";+import type { AlsContext } from "#context/container.js";import { ContextKey } from "#context/key.js";// Read-file stamps track the last-known content for stale-write detection.@@ -87,16 +87,3 @@ export function setReadFileStamp(ctx: AlsContext, targetKey: string, stamp: ReadbyTarget: { ...state.byTarget, [targetKey]: stamp },});}--// ----------------------------------------------------------------------------// Compaction reset-// -----------------------------------------------------------------------------/**- * Clears all read-file stamps from the context. The framework calls this on- * context compaction so a write afterward must re-read the file whose read- * evidence was summarized out of history.- */-export function clearReadFileState(): void {- loadContext().set(ReadFileStateKey, { byTarget: {} });-}diff --git a/packages/eve/src/execution/tools/todo.test.ts b/packages/eve/src/execution/tools/todo.test.tsdeleted file mode 100644index 38a14ec7a..000000000--- a/packages/eve/src/execution/tools/todo.test.ts+++ /dev/null@@ -1,178 +0,0 @@-import { describe, expect, it } from "vitest";--import type { ModelMessage } from "ai";--import { ContextContainer, contextStorage } from "#context/container.js";-import {- executeTodoTool,- getTodoCompactionMessage,- type TodoItem,- type TodoState,- TodoStateKey,-} from "#execution/tools/todo.js";-import { isFrameworkUserMessage } from "#harness/messages.js";--function runInContext(- fn: () => unknown,- state?: TodoState,-): { context: ContextContainer; result: unknown } {- const ctx = new ContextContainer();- ctx.set(TodoStateKey, state ?? { items: [] });- const result = contextStorage.run(ctx, fn);- return { context: ctx, result };-}--const sampleTodos: TodoItem[] = [- { content: "Fix the bug", priority: "high", status: "in_progress" },- { content: "Write tests", priority: "medium", status: "pending" },- { content: "Update docs", priority: "low", status: "completed" },-];--describe("executeTodoTool", () => {- describe("read (no todos param)", () => {- it("returns empty list when no state exists", () => {- const { result } = runInContext(() => executeTodoTool({}));-- expect(result).toEqual({- counts: { cancelled: 0, completed: 0, in_progress: 0, pending: 0, total: 0 },- todos: [],- });- });-- it("returns current list when state has items", () => {- const { result } = runInContext(() => executeTodoTool({}), { items: sampleTodos });-- const output = result as { counts: Record<string, number>; todos: readonly TodoItem[] };- expect(output.todos).toHaveLength(3);- expect(output.counts).toEqual({- cancelled: 0,- completed: 1,- in_progress: 1,- pending: 1,- total: 3,- });- });-- it("handles empty input gracefully", () => {- // The runtime execute wrapper coerces nullish model input into- // `{}` before calling executeTodoTool, so the typed executor only- // ever sees a valid TodoToolInput. This test verifies the- // empty-object case returns the current (empty) list.- const { result } = runInContext(() => executeTodoTool({}));-- const output = result as { todos: readonly TodoItem[] };- expect(output.todos).toEqual([]);- });- });-- describe("write (todos param provided)", () => {- it("replaces the entire list", () => {- const { context, result } = runInContext(() => executeTodoTool({ todos: sampleTodos }));-- const output = result as { counts: Record<string, number>; todos: readonly TodoItem[] };- expect(output.todos).toEqual(sampleTodos);- expect(output.counts.total).toBe(3);-- const state = context.require(TodoStateKey);- expect(state.items).toEqual(sampleTodos);- });-- it("clears the list when empty array provided", () => {- const { context, result } = runInContext(() => executeTodoTool({ todos: [] }), {- items: sampleTodos,- });-- const output = result as { counts: Record<string, number>; todos: readonly TodoItem[] };- expect(output.todos).toEqual([]);- expect(output.counts.total).toBe(0);-- const state = context.require(TodoStateKey);- expect(state.items).toEqual([]);- });-- it("overwrites previous state", () => {- const newTodos: TodoItem[] = [{ content: "New task", priority: "high", status: "pending" }];-- const { context } = runInContext(() => executeTodoTool({ todos: newTodos }), {- items: sampleTodos,- });-- const state = context.require(TodoStateKey);- expect(state.items).toEqual(newTodos);- expect(state.items).toHaveLength(1);- });- });-- describe("counts", () => {- it("counts each status correctly", () => {- const todos: TodoItem[] = [- { content: "a", priority: "high", status: "pending" },- { content: "b", priority: "high", status: "pending" },- { content: "c", priority: "medium", status: "in_progress" },- { content: "d", priority: "low", status: "completed" },- { content: "e", priority: "low", status: "completed" },- { content: "f", priority: "low", status: "completed" },- { content: "g", priority: "medium", status: "cancelled" },- ];-- const { result } = runInContext(() => executeTodoTool({ todos }));-- const output = result as { counts: Record<string, number> };- expect(output.counts).toEqual({- cancelled: 1,- completed: 3,- in_progress: 1,- pending: 2,- total: 7,- });- });- });-});--describe("getTodoCompactionMessage", () => {- function callHook(state: TodoState | undefined): ModelMessage | undefined {- const ctx = new ContextContainer();- if (state !== undefined) {- ctx.set(TodoStateKey, state);- }- return contextStorage.run(ctx, () => getTodoCompactionMessage());- }-- it("returns the full summary when the list contains active work", () => {- const message = callHook({- items: [- { content: "Fix bug", priority: "high", status: "completed" },- { content: "Write tests", priority: "medium", status: "pending" },- { content: "Cancelled task", priority: "low", status: "cancelled" },- ],- });-- expect(message).toBeDefined();- expect(message === undefined ? false : isFrameworkUserMessage(message)).toBe(true);- expect(message).toMatchObject({ kind: "context.state", role: "user" });- const text = String(message?.content ?? "");- expect(text).toContain("[Your task list was preserved");- expect(text).toContain("[x] [high] Fix bug");- expect(text).toContain("[ ] [medium] Write tests");- expect(text).toContain("[-] [low] Cancelled task");- });-- it("returns undefined when every item is terminal", () => {- expect(- callHook({- items: [- { content: "Fix bug", priority: "high", status: "completed" },- { content: "Skip docs", priority: "low", status: "cancelled" },- ],- }),- ).toBeUndefined();- });-- it("returns undefined for an empty list", () => {- expect(callHook({ items: [] })).toBeUndefined();- });-- it("returns undefined when no state has been set", () => {- expect(callHook(undefined)).toBeUndefined();- });-});diff --git a/packages/eve/src/execution/tools/todo.ts b/packages/eve/src/execution/tools/todo.tsdeleted file mode 100644index 7183f82fc..000000000--- a/packages/eve/src/execution/tools/todo.ts+++ /dev/null@@ -1,136 +0,0 @@-import { z } from "#compiled/zod/index.js";--import { loadContext } from "#context/container.js";-import { ContextKey } from "#context/key.js";-import { TODO_COMPACTION_PRESERVATION_LABEL } from "#harness/compaction-prompt.js";-import { createFrameworkUserMessage, type UserModelMessage } from "#harness/messages.js";--// ----------------------------------------------------------------------------// Durable context key-// -----------------------------------------------------------------------------/**- * Single item in the todo list.- */-export type TodoItem = z.infer<typeof TODO_ITEM_SCHEMA>;--/**- * Durable state for the framework todo tool.- */-export interface TodoState {- readonly items: readonly TodoItem[];-}--export const TodoStateKey = new ContextKey<TodoState>("eve.todo");--/**- * Typed input accepted by {@link executeTodoTool}.- *- * When `todos` is provided, the list is replaced (full replacement write).- * When `todos` is omitted, the current list is returned without modification.- */-export type TodoToolInput = z.infer<typeof TODO_INPUT_SCHEMA>;--function formatTodoSummary(state: TodoState): string | undefined {- if (state.items.length === 0) return undefined;-- const lines = state.items.map((item) => {- const check = item.status === "completed" ? "x" : item.status === "cancelled" ? "-" : " ";- return `- [${check}] [${item.priority}] ${item.content}`;- });-- return `${TODO_COMPACTION_PRESERVATION_LABEL}\n${lines.join("\n")}`;-}--/**- * Builds the message that re-injects the current todo list after the harness- * compacts message history, so the agent keeps its task list across- * compaction. Returns `undefined` when there is no list to preserve.- */-export function getTodoCompactionMessage(): UserModelMessage | undefined {- const state = loadContext().get(TodoStateKey);- if (- state === undefined ||- !state.items.some((item) => item.status === "pending" || item.status === "in_progress")- ) {- return undefined;- }- const summary = formatTodoSummary(state);- if (summary === undefined) return undefined;- return createFrameworkUserMessage("context.state", summary);-}--function formatTodoResult(state: TodoState): object {- const { items } = state;-- const counts = {- cancelled: 0,- completed: 0,- in_progress: 0,- pending: 0,- total: items.length,- };-- for (const item of items) {- counts[item.status]++;- }-- return {- counts,- todos: items,- };-}--/**- * Executes the framework todo tool.- *- * - Read: omit `todos` → returns the current list.- * - Write: provide `todos` → replaces the entire list, returns the new list.- *- * Both paths return the same formatted output so the model always sees- * the full current state.- */-export function executeTodoTool(input: TodoToolInput): unknown {- const ctx = loadContext();- const { todos } = input ?? {};-- if (todos !== undefined) {- const newState: TodoState = { items: [...todos] };- ctx.set(TodoStateKey, newState);- return formatTodoResult(newState);- }-- const current = ctx.ensure(TodoStateKey, () => ({ items: [] }));- return formatTodoResult(current);-}--// ----------------------------------------------------------------------------// Tool definition-// -----------------------------------------------------------------------------const TODO_ITEM_SCHEMA = z.strictObject({- content: z.string().describe("Brief description of the task."),- priority: z.enum(["high", "medium", "low"]).describe("Priority level of the task."),- status: z- .enum(["pending", "in_progress", "completed", "cancelled"])- .describe("Current status of the task."),-});--export const TODO_INPUT_SCHEMA = z.strictObject({- todos: z- .array(TODO_ITEM_SCHEMA)- .describe("The updated todo list. Omit to read the current list without modifying it.")- .optional(),-});--const countSchema = z.number().int().min(0);-export const TODO_OUTPUT_SCHEMA = z.strictObject({- counts: z.strictObject({- cancelled: countSchema,- completed: countSchema,- in_progress: countSchema,- pending: countSchema,- total: countSchema,- }),- todos: z.array(TODO_ITEM_SCHEMA),-});diff --git a/packages/eve/src/execution/tools/workflow/answer.ts b/packages/eve/src/execution/tools/workflow/answer.tsindex f1f60ac92..4e34c8041 100644--- a/packages/eve/src/execution/tools/workflow/answer.ts+++ b/packages/eve/src/execution/tools/workflow/answer.ts@@ -8,7 +8,17 @@ export async function resumeWorkflowToolRunAnswers(responses: readonly InputResponse[] | undefined,): Promise<void> {for (const response of responses ?? []) {- const answer: ToolInputResponse = { optionId: response.optionId, text: response.text };+ const answer: ToolInputResponse = {+ optionId: response.optionId,+ status: "answered",+ text: response.text,+ };await resumeHook(answerToken, 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.tsnew file mode 100644index 000000000..795f0dc47--- /dev/null+++ b/packages/eve/src/execution/tools/workflow/ask.test.ts@@ -0,0 +1,33 @@+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 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;+ attachWorkflowToolRunContext(ctx, {+ canRequestInput: false,+ from: {+ callId: "call",+ execution: "blocking",+ input: {},+ runId: "run",+ sequence: 1,+ stepIndex: 0,+ toolName: "ask_question",+ turnId: "turn",+ },+ owner: { inbox: "inbox" },+ });++ await expect(ask(ctx, { prompt: "Which region?" })).resolves.toEqual({+ status: "unavailable",+ });+ expect(createHook).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/execution/tools/workflow/ask.ts b/packages/eve/src/execution/tools/workflow/ask.tsindex 1f56a5fa4..c210cf6fe 100644--- a/packages/eve/src/execution/tools/workflow/ask.ts+++ b/packages/eve/src/execution/tools/workflow/ask.ts@@ -13,6 +13,7 @@ import { workflowToolContextErrorMessage } from "#shared/workflow-tool-context.jconst WORKFLOW_TOOL_RUN_CONTEXT = Symbol.for("eve.workflow-tool-run.context");export interface WorkflowToolRunContext {+ readonly canRequestInput?: boolean;readonly from: WorkflowToolRunRef;readonly owner: WorkflowToolRunOwner;}@@ -56,9 +57,13 @@ export function readWorkflowToolRunOwner(ctx: ToolContext): WorkflowToolRunOwnerreturn readWorkflowToolRunContext(ctx, "agent").owner;}-/** Returns an answer hook which may be awaited or raced with another workflow operation. */-export function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse> {+/** Returns an answer which may be awaited or raced with another workflow operation. */+export function ask(+ ctx: ToolContext,+ request: ToolInputRequest,+): Hook<ToolInputResponse> | 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, {kind: "request",diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.tsindex 4ae20ffa8..b8bf63100 100644--- a/packages/eve/src/execution/tools/workflow/body.ts+++ b/packages/eve/src/execution/tools/workflow/body.ts@@ -20,6 +20,11 @@ export interface WorkflowBodyDefinition {/** 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;@@ -54,6 +59,7 @@ export async function executeWorkflowBody(const from = createWorkflowBodyRef(input);const ctx = createWorkflowBodyContext(input, signal);attachWorkflowToolRunContext(ctx, {+ canRequestInput: input.canRequestInput,from,owner: input.owner,});diff --git a/packages/eve/src/execution/tools/workflow/start.ts b/packages/eve/src/execution/tools/workflow/start.tsindex 12ecdf835..bc636dec9 100644--- a/packages/eve/src/execution/tools/workflow/start.ts+++ b/packages/eve/src/execution/tools/workflow/start.ts@@ -35,6 +35,7 @@ export async function startWorkflowToolRun(export async function startWorkflowTask(input: {readonly agents: WorkflowToolRunInput["agents"];readonly auth: SessionAuth["current"];+ readonly canRequestInput: boolean;readonly batchEvent: {readonly sequence: number;readonly stepIndex: number;@@ -51,6 +52,7 @@ export async function startWorkflowTask(input: {const started = await startWorkflowToolRun({agents: input.agents,callId: task.callId,+ canRequestInput: input.canRequestInput,executeInput: task.executeInput,input: task.input,owner: input.owner,diff --git a/packages/eve/src/framework/sources/registry.ts b/packages/eve/src/framework/sources/registry.tsindex 0574bfbff..361f18b9b 100644--- a/packages/eve/src/framework/sources/registry.ts+++ b/packages/eve/src/framework/sources/registry.ts@@ -9,7 +9,7 @@ import {type ProgrammaticModuleNamespace,} from "#compiler/source-graph.js";-const revision = `eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v49`;+const revision = `eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v50`;const localDefaults = defineProgrammaticAgentSource({id: "eve:defaults",@@ -33,10 +33,6 @@ const localDefaults = defineProgrammaticAgentSource({logicalPath: "tools/write_file.ts",loadNamespace: () => import("#tools/provided/write-file.js"),},- {- logicalPath: "tools/todo.ts",- loadNamespace: () => import("#tools/provided/todo.js"),- },{logicalPath: "tools/web_fetch.ts",loadNamespace: () => import("#tools/provided/web-fetch.js"),@@ -49,10 +45,6 @@ const localDefaults = defineProgrammaticAgentSource({logicalPath: "tools/connection_search.ts",loadNamespace: () => import("#tools/framework/connection-search.js"),},- {- logicalPath: "tools/ask_question.ts",- loadNamespace: () => import("#tools/framework/ask-question.js"),- },{logicalPath: "tools/task_cancel.ts",loadNamespace: () => import("#tools/framework/task-cancel.js"),diff --git a/packages/eve/src/harness/compaction-prompt.ts b/packages/eve/src/harness/compaction-prompt.tsindex 90573cb8e..3965a98ae 100644--- a/packages/eve/src/harness/compaction-prompt.ts+++ b/packages/eve/src/harness/compaction-prompt.ts@@ -7,14 +7,6 @@ export const COMPACTION_CHECKPOINT_MARKER = "Summary of our conversation so far:/** Synthetic resumption prompt used when no real user message can be replayed. */export const COMPACTION_RESUMPTION_MESSAGE = "Continue.";-/**- * Label line of the framework-injected todo preservation message. Owned here- * so compaction can recognize the message as synthetic when picking a user- * message to replay after compaction.- */-export const TODO_COMPACTION_PRESERVATION_LABEL =- "[Your task list was preserved across context compaction]";-const COMPACTION_SYSTEM_PROMPT = `You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.Include:diff --git a/packages/eve/src/harness/hitl/approval-input-requests.ts b/packages/eve/src/harness/hitl/approval-input-requests.tsindex 6f599fa18..d5fc6bedc 100644--- a/packages/eve/src/harness/hitl/approval-input-requests.ts+++ b/packages/eve/src/harness/hitl/approval-input-requests.ts@@ -26,12 +26,6 @@ import type {ResolvePendingInputResult,ToolResponsePart,} from "#harness/hitl/pending-input-resolution.js";-import {- buildQuestionToolResponsePart,- findAnsweredQuestionBatches,- resolveQuestionBatches,-} from "#harness/hitl/question-input-requests.js";-import type { QuestionInputRequest } from "#harness/hitl/question-input-requests.js";import type { HarnessSession } from "#harness/types.js";const APPROVED_TOOLS_KEY = "eve.runtime.hitl.approvedTools";@@ -54,33 +48,18 @@ export function findAnsweredApprovalBatches(export function resolveApprovalInputBatches(input: InputDomainResolverInput & {- readonly approvalBatches: readonly PendingInputBatch[];- readonly questionBatches: readonly PendingInputBatch[];readonly resolveApprovalKey?: (request: InputRequest) => string | undefined;},): ResolvePendingInputResult {- const answeredApprovalBatches = new Set(- findAnsweredApprovalBatches(input.approvalBatches, input.responses),- );- const answeredQuestionBatches = new Set(- findAnsweredQuestionBatches(input.questionBatches, input.responses),- );- let resolvedBatches = input.batches.filter(- (batch) => answeredApprovalBatches.has(batch) || answeredQuestionBatches.has(batch),- );- const firstApprovalIndex = resolvedBatches.findIndex((batch) =>- batch.requests.some((request) => isApprovalRequest(request)),- );- if (firstApprovalIndex >= 0) {- // Anything after this batch would hide its approval response from AI- // SDK's tail-tool-message scan. Its responses replay on the next step.- resolvedBatches = resolvedBatches.slice(0, firstApprovalIndex + 1);- }-- const openBatches = input.batches.filter((batch) => !resolvedBatches.includes(batch));+ const answered = new Set(findAnsweredApprovalBatches(input.batches, input.responses));+ // Only the first answered batch resolves: anything after it would hide its+ // approval response from AI SDK's tail-tool-message scan. Later answers+ // replay on the next step.+ const approvalBatch = input.batches.find((batch) => answered.has(batch));+ const openBatches = input.batches.filter((batch) => batch !== approvalBatch);const leftoverResponses = responsesForBatches(input.responses, openBatches);- if (resolvedBatches.length === 0) {+ if (approvalBatch === undefined) {if (input.resolvedStepInput?.message === undefined) {return {outcome: "unresolved",@@ -101,37 +80,23 @@ export function resolveApprovalInputBatches(};}- const approvalBatch = resolvedBatches.find((batch) =>- batch.requests.some((request) => isApprovalRequest(request)),- );- const questionBatches = resolvedBatches.filter((batch) => batch !== approvalBatch);- const questions = resolveQuestionBatches({- batches: questionBatches,+ const approval = resolveApprovalBatch({+ batch: approvalBatch,messages: [...input.baseHistory],+ resolveApprovalKey: input.resolveApprovalKey,responses: input.responses,+ session: input.session,});- const approval =- approvalBatch === undefined- ? { messages: questions, session: input.session }- : resolveApprovalBatch({- batch: approvalBatch,- messages: questions,- resolveApprovalKey: input.resolveApprovalKey,- responses: input.responses,- session: input.session,- });+ const resolved = buildResolvedInputBatch(approvalBatch, input.responses);return finishResolvedInput({- deferTurnInput: approvalBatch !== undefined || input.deferTurnInput,+ deferTurnInput: true,leftoverResponses,messages: approval.messages,rejectedActions: approval.rejectedActions,- resolvedInputs: resolvedBatches.flatMap((batch) => {- const resolved = buildResolvedInputBatch(batch, input.responses);- return resolved === undefined ? [] : [resolved];- }),+ resolvedInputs: resolved === undefined ? [] : [resolved],resolvedStepInput: input.resolvedStepInput,- session: removePendingInputBatches(approval.session, resolvedBatches),+ session: removePendingInputBatches(approval.session, [approvalBatch]),});}@@ -253,11 +218,9 @@ function buildApprovalBatchToolResponseParts();break;case "question":- parts.push(buildQuestionToolResponsePart(request as QuestionInputRequest, response));- break;case "session-limit":throw new TypeError(- "Session-limit pending input batches must contain only session-limit requests.",+ `Approval pending input batches cannot contain a "${request.kind}" request.`,);default: {const unhandled: never = request.kind;diff --git a/packages/eve/src/harness/hitl/question-input-requests.ts b/packages/eve/src/harness/hitl/question-input-requests.tsdeleted file mode 100644index 76b28cd39..000000000--- a/packages/eve/src/harness/hitl/question-input-requests.ts+++ /dev/null@@ -1,135 +0,0 @@-import type { ModelMessage } from "ai";--import type { InputRequest, InputResponse } from "#shared/input.js";-import { buildResolvedInputBatch } from "#harness/input-request-resolution.js";-import type { PendingInputBatch } from "#harness/pending-input-batches.js";-import {- queueDeferredStepInput,- removePendingInputBatches,-} from "#harness/pending-input-batches.js";-import {- appendResolvedBatchTranscript,- compactStepInput,- finishResolvedInput,- responsesForBatches,-} from "#harness/hitl/pending-input-resolution.js";-import type {- InputDomainResolverInput,- ResolvePendingInputResult,- ToolResponsePart,-} from "#harness/hitl/pending-input-resolution.js";--export type QuestionInputRequest = InputRequest & { readonly kind: "question" };--export function resolveQuestionOnlyInputBatches(- input: InputDomainResolverInput,-): ResolvePendingInputResult {- const resolvedBatches = findAnsweredQuestionBatches(input.batches, input.responses);- const openBatches = input.batches.filter((batch) => !resolvedBatches.includes(batch));- const leftoverResponses = responsesForBatches(input.responses, openBatches);-- if (resolvedBatches.length === 0) {- if (input.resolvedStepInput?.message === undefined) {- return {- outcome: "unresolved",- messages: [...input.baseHistory],- session: queueDeferredStepInput(input.session, compactStepInput(input.resolvedStepInput)),- };- }-- const sole = input.batches.length === 1 ? input.batches[0] : undefined;- if (sole === undefined) {- const session =- leftoverResponses.length === 0- ? input.session- : queueDeferredStepInput(input.session, { inputResponses: leftoverResponses });- return {- consumedMessage: input.resolvedStepInput.messageConsumed,- outcome: "continue",- messages: [...input.baseHistory],- session,- };- }-- // One question-only batch keeps the dismiss-and-continue behavior.- const messages = resolveQuestionBatches({- batches: [sole],- messages: [...input.baseHistory],- responses: [],- });- return {- consumedMessage: input.resolvedStepInput.messageConsumed,- outcome: "resolved",- messages,- resolvedInputs: [buildResolvedInputBatch(sole, [])].filter(- (batch): batch is NonNullable<typeof batch> => batch !== undefined,- ),- session: removePendingInputBatches(input.session, [sole]),- };- }-- const messages = resolveQuestionBatches({- batches: resolvedBatches,- messages: [...input.baseHistory],- responses: input.responses,- });-- return finishResolvedInput({- deferTurnInput: input.deferTurnInput,- leftoverResponses,- messages,- resolvedInputs: resolvedBatches.flatMap((batch) => {- const resolved = buildResolvedInputBatch(batch, input.responses);- return resolved === undefined ? [] : [resolved];- }),- resolvedStepInput: input.resolvedStepInput,- session: removePendingInputBatches(input.session, resolvedBatches),- });-}--export function findAnsweredQuestionBatches(- batches: readonly PendingInputBatch[],- responses: readonly InputResponse[],-): PendingInputBatch[] {- const responseIds = new Set(responses.map((response) => response.requestId));- return batches.filter((batch) =>- batch.requests.some((request) => responseIds.has(request.requestId)),- );-}--export function resolveQuestionBatches(input: {- readonly batches: readonly PendingInputBatch[];- readonly messages: ModelMessage[];- readonly responses: readonly InputResponse[];-}): ModelMessage[] {- const responseMap = new Map(input.responses.map((response) => [response.requestId, response]));- for (const batch of input.batches) {- const toolParts = batch.requests.map((request) =>- buildQuestionToolResponsePart(- request as QuestionInputRequest,- responseMap.get(request.requestId),- ),- );- appendResolvedBatchTranscript(input.messages, batch, toolParts);- }-- return input.messages;-}--export function buildQuestionToolResponsePart(- request: QuestionInputRequest,- response: InputResponse | undefined,-): ToolResponsePart {- return {- output: {- type: "json",- value:- response !== undefined- ? { optionId: response.optionId, text: response.text, status: "answered" }- : { status: "ignored" },- },- toolCallId: request.action.callId,- toolName: request.action.toolName,- type: "tool-result",- };-}diff --git a/packages/eve/src/harness/input-extraction.test.ts b/packages/eve/src/harness/input-extraction.test.tsindex a57c885fd..fea08b96a 100644--- a/packages/eve/src/harness/input-extraction.test.ts+++ b/packages/eve/src/harness/input-extraction.test.ts@@ -1,114 +1,6 @@import { describe, expect, it } from "vitest";-import {- extractQuestionInputRequests,- extractToolApprovalInputRequests,-} from "#harness/input-extraction.js";--const QUESTION_TOOLS = new Map([- [- "ask_question",- {- behavior: {- availability: ["requires-request-input" as const],- handling: { kind: "request-input" as const, request: "question" as const },- },- description: "Ask a question.",- inputSchema: {} as never,- name: "ask_question",- },- ],-]);--describe("extractQuestionInputRequests", () => {- it("extracts a question request from an ask_question tool call", () => {- const result = extractQuestionInputRequests({- excludedCallIds: new Set(),- toolCalls: [- {- input: {- options: [{ id: "yes", label: "Approve" }],- prompt: "Continue?",- },- toolCallId: "call-1",- toolName: "ask_question",- type: "tool-call",- },- ],- tools: QUESTION_TOOLS,- });-- expect(result).toEqual([- {- action: {- callId: "call-1",- input: {- options: [{ id: "yes", label: "Approve" }],- prompt: "Continue?",- },- kind: "tool-call",- toolName: "ask_question",- },- display: "select",- kind: "question",- options: [{ id: "yes", label: "Approve" }],- prompt: "Continue?",- requestId: "call-1",- },- ]);- });-- it("includes allowFreeform when present in the tool input", () => {- const result = extractQuestionInputRequests({- excludedCallIds: new Set(),- toolCalls: [- {- input: { allowFreeform: true, prompt: "What do you want?" },- toolCallId: "call-1",- toolName: "ask_question",- type: "tool-call",- },- ],- tools: QUESTION_TOOLS,- });-- expect(result[0]?.allowFreeform).toBe(true);- });-- it("skips non-ask_question tool calls", () => {- const result = extractQuestionInputRequests({- excludedCallIds: new Set(),- toolCalls: [- {- input: { a: 1 },- toolCallId: "call-1",- toolName: "add",- type: "tool-call",- },- ],- tools: QUESTION_TOOLS,- });-- expect(result).toEqual([]);- });-- it("skips tool calls present in the excluded set", () => {- const result = extractQuestionInputRequests({- excludedCallIds: new Set(["call-1"]),- toolCalls: [- {- input: { prompt: "Continue?" },- toolCallId: "call-1",- toolName: "ask_question",- type: "tool-call",- },- ],- tools: QUESTION_TOOLS,- });-- expect(result).toEqual([]);- });-});+import { extractToolApprovalInputRequests } from "#harness/input-extraction.js";describe("extractToolApprovalInputRequests", () => {it("extracts a tool approval request from content parts", () => {diff --git a/packages/eve/src/harness/input-extraction.ts b/packages/eve/src/harness/input-extraction.tsindex 1cb7ae2a7..b92278f6f 100644--- a/packages/eve/src/harness/input-extraction.ts+++ b/packages/eve/src/harness/input-extraction.ts@@ -1,7 +1,6 @@-import type { ContentPart, ModelMessage, ToolSet, TypedToolCall } from "ai";+import type { ContentPart, ModelMessage, ToolSet } from "ai";import { z } from "zod";-import type { HarnessToolMap } from "#harness/types.js";import type { InputRequest } from "#shared/input.js";import { createRuntimeToolCallActionFromToolCall } from "#harness/tool-call-action.js";@@ -31,72 +30,6 @@ const ToolApprovalRequestSchema = z.object({type: z.literal("tool-approval-request"),});-/**- * Extracts question input requests from tool calls that target the- * `ask_question` framework tool.- */-export function extractQuestionInputRequests(input: {- readonly excludedCallIds: ReadonlySet<string>;- readonly toolCalls: readonly TypedToolCall<ToolSet>[];- readonly tools: HarnessToolMap;-}): InputRequest[] {- return extractQuestionRequests(input);-}--function extractQuestionRequests(input: {- readonly excludedCallIds: ReadonlySet<string>;- readonly toolCalls: readonly ToolCallDescriptor[];- readonly tools: HarnessToolMap;-}): InputRequest[] {- const requests: InputRequest[] = [];-- for (const toolCall of input.toolCalls) {- const handling = input.tools.get(toolCall.toolName)?.behavior?.handling;- if (handling?.kind !== "request-input" || handling.request !== "question") {- continue;- }-- if (input.excludedCallIds.has(toolCall.toolCallId)) {- continue;- }-- const action = createRuntimeToolCallActionFromToolCall({ toolCall });- const toolInput = action.input as {- allowFreeform?: boolean;- options?: InputRequest["options"];- prompt: string;- };- const request: {- action: InputRequest["action"];- allowFreeform?: InputRequest["allowFreeform"];- display?: InputRequest["display"];- kind: InputRequest["kind"];- options?: InputRequest["options"];- prompt: InputRequest["prompt"];- requestId: InputRequest["requestId"];- } = {- action,- display: "text",- kind: "question",- prompt: String(toolInput.prompt),- requestId: action.callId,- };-- if (toolInput.allowFreeform !== undefined) {- request.allowFreeform = toolInput.allowFreeform;- }-- if (toolInput.options !== undefined) {- request.options = toolInput.options;- request.display = "select";- }-- requests.push(request);- }-- return requests;-}-/*** Extracts tool approval input requests from AI SDK content parts that* contain `tool-approval-request` entries.@@ -175,14 +108,13 @@ function extractApprovalRequests(input: {}/**- * Recovers request metadata for submitted input response IDs from model- * history. The newest occurrence wins so compacted or repeated history does- * not replace the request that is closest to the current turn.+ * Recovers approval request metadata for submitted input response IDs from+ * model history. The newest occurrence wins so compacted or repeated history+ * does not replace the request that is closest to the current turn.*/export function extractHistoricalInputRequests(input: {readonly history: readonly ModelMessage[];readonly requestIds: ReadonlySet<string>;- readonly tools: HarnessToolMap;}): ReadonlyMap<string, InputRequest> {const requests = new Map<string, InputRequest>();@@ -192,19 +124,10 @@ export function extractHistoricalInputRequests(input: {continue;}- const toolCalls = message.content.flatMap((part: unknown) => {- const toolCall = PersistedToolCallSchema.safeParse(part);- return toolCall.success && input.requestIds.has(toolCall.data.toolCallId)- ? [toolCall.data]- : [];+ const candidates = extractApprovalRequests({+ content: message.content,+ includedRequestIds: input.requestIds,});- const candidates = [- ...extractQuestionRequests({ excludedCallIds: new Set(), toolCalls, tools: input.tools }),- ...extractApprovalRequests({- content: message.content,- includedRequestIds: input.requestIds,- }),- ];for (const request of candidates) {if (!input.requestIds.has(request.requestId) || requests.has(request.requestId)) {diff --git a/packages/eve/src/harness/input-request-class.test.ts b/packages/eve/src/harness/input-request-class.test.tsindex 69f11b784..4216e7bd7 100644--- a/packages/eve/src/harness/input-request-class.test.ts+++ b/packages/eve/src/harness/input-request-class.test.ts@@ -1,84 +1,7 @@import { describe, expect, it } from "vitest";-import { classifyInputRequest, isApprovalRequest } from "#harness/input-request-class.js";+import { isApprovalRequest } from "#harness/input-request-class.js";import { createSessionLimitContinuationRequest } from "#harness/session-limit-continuation.js";-import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";--describe("classifyInputRequest", () => {- const action = {- callId: "call_1",- input: {},- kind: "tool-call",- toolName: "ask_user",- } as const;-- it("requires an explicit answer for tool approvals", () => {- expect(- classifyInputRequest({- action,- kind: "tool-approval",- options: [- { id: "approve", label: "Approve" },- { id: "deny", label: "Deny" },- ],- prompt: "Run the tool?",- requestId: "call_1",- }),- ).toBe("required");- });-- it("requires an explicit answer for session-limit continuations", () => {- expect(- classifyInputRequest(- createSessionLimitContinuationRequest({- sessionId: "sess-test",- violation: { kind: "input", limit: 12, usedTokens: 12 },- }),- ),- ).toBe("required");- });-- it("classifies model questions as dismissable", () => {- expect(- classifyInputRequest({- action: { ...action, toolName: ASK_QUESTION_TOOL_NAME },- allowFreeform: true,- kind: "question",- options: [{ id: "blue", label: "Blue" }],- prompt: "Which color?",- requestId: "call_1",- }),- ).toBe("dismissable");- });-- it("does not mistake non-approval two-option requests for approvals", () => {- const request = {- action: { ...action, toolName: ASK_QUESTION_TOOL_NAME },- kind: "question" as const,- options: [- { id: "approve", label: "Approve" },- { id: "deny", label: "Deny" },- ],- prompt: "Should we proceed?",- requestId: "call_1",- };-- expect(isApprovalRequest(request)).toBe(false);- expect(classifyInputRequest(request)).toBe("dismissable");- });-- it("uses the request kind rather than the action tool name", () => {- const request = {- action,- kind: "question" as const,- prompt: "What should happen next?",- requestId: "call_1",- };-- expect(isApprovalRequest(request)).toBe(false);- expect(classifyInputRequest(request)).toBe("dismissable");- });-});describe("isApprovalRequest", () => {const action = {@@ -103,7 +26,7 @@ describe("isApprovalRequest", () => {).toBe(true);expect(isApprovalRequest({- action: { ...action, toolName: ASK_QUESTION_TOOL_NAME },+ action: { ...action, toolName: "ask_question" },kind: "question",options: [{ id: "approve", label: "Approve" },diff --git a/packages/eve/src/harness/input-request-class.ts b/packages/eve/src/harness/input-request-class.tsindex da86c8927..e1fc7ad91 100644--- a/packages/eve/src/harness/input-request-class.ts+++ b/packages/eve/src/harness/input-request-class.ts@@ -1,45 +1,6 @@-/**- * Shape and behavior classification for pending input requests, shared by- * the harness resolution path and protocol clients (e.g. the dev TUI's- * rendering decisions).- */import type { InputRequest } from "#shared/input.js";/** Returns true when the request gates an AI SDK tool call. */export function isApprovalRequest(request: InputRequest): boolean {return request.kind === "tool-approval";}--/**- * Behavioral class of a pending input request.- *- * `"required"` — the request must be explicitly answered before the turn can- * move on. While one is unanswered, any other arriving input is queued and- * replayed on the step after the answer. The pending batch never churns, so- * the request ids the user is answering stay valid.- *- * `"dismissable"` — a plain follow-up message counts as the user moving on.- * The request resolves as a real `tool-result` with `status: "ignored"` and- * the model continues with the message in the same step.- */-export type InputRequestClass = "dismissable" | "required";--/** Classifies one pending request; see {@link InputRequestClass}. */-export function classifyInputRequest(request: InputRequest): InputRequestClass {- switch (request.kind) {- // AI SDK requires a tool approval to resolve in isolation. Skipping it- // would leave the intercepted call permanently unadjudicated.- case "tool-approval":- return "required";- // Ignoring a session-limit continuation cannot move forward. The next- // pre-model gate would park on the same violation again.- case "session-limit":- return "required";- case "question":- return "dismissable";- default: {- const unhandled: never = request.kind;- return unhandled;- }- }-}diff --git a/packages/eve/src/harness/input-requests.test.ts b/packages/eve/src/harness/input-requests.test.tsindex 46cf635fb..2116037c2 100644--- a/packages/eve/src/harness/input-requests.test.ts+++ b/packages/eve/src/harness/input-requests.test.ts@@ -120,144 +120,6 @@ describe("createRuntimeToolCallActionFromToolCall", () => {});describe("resolvePendingInput", () => {- it("keeps approvals pending when another request is answered first", () => {- const session = appendPendingInputBatch({- requests: [- {- action: {- callId: "question-call",- input: { prompt: "Pick one." },- kind: "tool-call",- toolName: "ask_question",- },- display: "select",- kind: "question",- prompt: "Pick one.",- requestId: "question-call",- },- {- action: {- callId: "approval-call",- input: { command: "rm -rf /tmp/demo" },- kind: "tool-call",- toolName: "bash",- },- allowFreeform: false,- display: "confirmation",- kind: "tool-approval",- options: [- { id: "approve", label: "Yes" },- { id: "cancel", label: "No" },- ],- prompt: "Approve tool call: bash",- requestId: "approval-1",- },- ],- responseMessages: [- {- content: [- { text: "Need input.", type: "text" },- {- input: { prompt: "Pick one." },- toolCallId: "question-call",- toolName: "ask_question",- type: "tool-call",- },- ],- role: "assistant",- } satisfies ModelMessage,- ],- session: createHarnessSession(),- });-- const result = resolvePendingInput({- stepInput: {- inputResponses: [- {- requestId: "question-call",- optionId: "yes",- },- ],- },- session,- });-- expect(result.outcome).toBe("unresolved");- expect(result.messages).toEqual([{ content: "previous", kind: "user", role: "user" }]);- expect(hasDeferredStepInput(result.session)).toBe(true);-- const deferred = consumeDeferredStepInput({ session: result.session });- expect(deferred.input).toEqual({- inputResponses: [- {- requestId: "question-call",- optionId: "yes",- },- ],- });- });-- it("resolves freeform question input from a follow-up message", () => {- const session = appendPendingInputBatch({- requests: [- {- action: {- callId: "question-call",- input: { prompt: "Pick one." },- kind: "tool-call",- toolName: "ask_question",- },- display: "text",- kind: "question",- prompt: "Pick one.",- requestId: "question-call",- } satisfies InputRequest,- ],- responseMessages: [- {- content: [- { text: "Need input.", type: "text" },- {- input: { prompt: "Pick one." },- toolCallId: "question-call",- toolName: "ask_question",- type: "tool-call",- },- ],- role: "assistant",- } satisfies ModelMessage,- ],- session: createHarnessSession(),- });-- const result = resolvePendingInput({- stepInput: {- message: "Ignore that and continue.",- },- session,- });-- expect(result.outcome).toBe("resolved");- expect(result.messages.at(-1)).toEqual({- content: [- {- output: {- type: "json",- value: {- optionId: undefined,- text: "Ignore that and continue.",- status: "answered",- },- },- toolCallId: "question-call",- toolName: "ask_question",- type: "tool-result",- },- ],- role: "tool",- });- });-it("defers a follow-up message until after tool approvals are resolved", () => {const session = appendPendingInputBatch({requests: [@@ -997,25 +859,6 @@ describe("pending input batch collection", () => {};}- function questionRequest(requestId: string, callId: string): InputRequest {- return {- action: {- callId,- input: { prompt: "Pick one." },- kind: "tool-call",- toolName: "ask_question",- },- display: "select",- kind: "question",- options: [- { id: "red", label: "Red" },- { id: "blue", label: "Blue" },- ],- prompt: "Pick one.",- requestId,- };- }-function batchOutput(callId: string, toolName: string): ModelMessage {return {content: [{ input: {}, toolCallId: callId, toolName, type: "tool-call" }],@@ -1037,13 +880,13 @@ describe("pending input batch collection", () => {expect(getPendingInputRequestIds(legacySession.state)).toEqual(new Set(["approval-1"]));const appended = appendPendingInputBatch({- requests: [questionRequest("question-1", "call-2")],- responseMessages: [batchOutput("call-2", "ask_question")],+ requests: [approvalRequest("approval-2", "call-2")],+ responseMessages: [batchOutput("call-2", "bash")],session: legacySession,});expect(appended.state?.["eve.runtime.pendingInputBatch"]).toBeUndefined();expect(getPendingInputRequestIds(appended.state)).toEqual(- new Set(["approval-1", "question-1"]),+ new Set(["approval-1", "approval-2"]),);const result = resolvePendingInput({@@ -1055,52 +898,6 @@ describe("pending input batch collection", () => {expect(hasPendingInputBatch(result.session.state)).toBe(false);});- it("keeps earlier batches open while a later batch resolves", () => {- let session = appendPendingInputBatch({- requests: [approvalRequest("approval-1", "call-1")],- responseMessages: [batchOutput("call-1", "bash")],- session: createHarnessSession(),- });- session = appendPendingInputBatch({- requests: [questionRequest("question-1", "call-2")],- responseMessages: [batchOutput("call-2", "ask_question")],- session,- });-- const answered = resolvePendingInput({- session,- stepInput: { inputResponses: [{ requestId: "question-1", optionId: "red" }] },- });- expect(answered.outcome).toBe("resolved");- expect(getPendingInputRequestIds(answered.session.state)).toEqual(new Set(["approval-1"]));- // Only the answered batch's withheld output is restored.- expect(answered.messages).toEqual([- { content: "previous", kind: "user", role: "user" },- batchOutput("call-2", "ask_question"),- {- content: [- {- output: {- type: "json",- value: { optionId: "red", text: undefined, status: "answered" },- },- toolCallId: "call-2",- toolName: "ask_question",- type: "tool-result",- },- ],- role: "tool",- },- ]);-- const approved = resolvePendingInput({- session: answered.session,- stepInput: { inputResponses: [{ requestId: "approval-1", optionId: "approve" }] },- });- expect(approved.outcome).toBe("resolved");- expect(hasPendingInputBatch(approved.session.state)).toBe(false);- });-it("resolves only the first approval-bearing batch and defers later responses", () => {let session = appendPendingInputBatch({requests: [approvalRequest("approval-1", "call-1")],@@ -1255,8 +1052,8 @@ describe("pending input batch collection", () => {session: createHarnessSession(),});session = appendPendingInputBatch({- requests: [questionRequest("question-1", "call-2")],- responseMessages: [batchOutput("call-2", "ask_question")],+ requests: [approvalRequest("approval-2", "call-2")],+ responseMessages: [batchOutput("call-2", "bash")],session,});@@ -1266,7 +1063,7 @@ describe("pending input batch collection", () => {expect(result.messages).toEqual([{ content: "previous", kind: "user", role: "user" }]);expect(hasDeferredStepInput(result.session)).toBe(false);expect(getPendingInputRequestIds(result.session.state)).toEqual(- new Set(["approval-1", "question-1"]),+ new Set(["approval-1", "approval-2"]),);});diff --git a/packages/eve/src/harness/input-requests.ts b/packages/eve/src/harness/input-requests.tsindex 9176f6062..6db69db47 100644--- a/packages/eve/src/harness/input-requests.ts+++ b/packages/eve/src/harness/input-requests.ts@@ -22,10 +22,6 @@ import type {ResolvePendingInputResult,ResolvedStepInput,} from "#harness/hitl/pending-input-resolution.js";-import {- findAnsweredQuestionBatches,- resolveQuestionOnlyInputBatches,-} from "#harness/hitl/question-input-requests.js";import { resolveToolCallInputObject } from "#harness/coordination.js";import {clearPendingSessionLimitPrompt,@@ -77,14 +73,8 @@ export function hasRunnableDeferredStepInput(session: HarnessSession): boolean {return route.batch.requests.every((request) =>responses.some((response) => response.requestId === request.requestId),);- case "with-approvals":- // An unanswered approval must not prevent an answered question from running.- return (- findAnsweredApprovalBatches(route.approvalBatches, responses).length > 0 ||- findAnsweredQuestionBatches(route.questionBatches, responses).length > 0- );- case "questions-only":- return findAnsweredQuestionBatches(batches, responses).length > 0;+ case "approvals":+ return findAnsweredApprovalBatches(batches, responses).length > 0;}}@@ -100,7 +90,7 @@ export function hasPendingApprovalBatch(session: HarnessSession): boolean {** Ordered batches remain independently answerable. Session-limit prompts own* resolution while open; approval batches preserve AI SDK's tail-message- * requirement; question-only batches retain dismiss-and-continue behavior.+ * requirement.*/export function resolvePendingInput(input: {/** The turn currently advancing through the harness tool loop. */@@ -150,10 +140,10 @@ export function resolvePendingInput(input: {}if (- route.kind === "with-approvals" &&+ route.kind === "approvals" &&input.deferMessagesWhileApprovalsPending === true &&resolvedStepInput?.message !== undefined &&- findAnsweredApprovalBatches(route.approvalBatches, responses).length === 0+ findAnsweredApprovalBatches(batches, responses).length === 0) {return {deferredMessage: true,@@ -185,15 +175,11 @@ export function resolvePendingInput(input: {switch (route.kind) {case "session-limit":return resolveSessionLimitInput({ ...resolverInput, pendingBatch: route.batch });- case "with-approvals":+ case "approvals":return resolveApprovalInputBatches({...resolverInput,- approvalBatches: route.approvalBatches,- questionBatches: route.questionBatches,resolveApprovalKey: input.resolveApprovalKey,});- case "questions-only":- return resolveQuestionOnlyInputBatches(resolverInput);}}@@ -211,9 +197,7 @@ function canContinuePastHistoricalInput(input: {if (input.activeTurnId === undefined || input.route.kind === "session-limit") return false;if (input.responses.length > 0 &&- (input.route.kind !== "with-approvals" ||- findAnsweredApprovalBatches(input.route.approvalBatches, input.responses).length > 0 ||- findAnsweredQuestionBatches(input.route.questionBatches, input.responses).length > 0)+ findAnsweredApprovalBatches(input.batches, input.responses).length > 0) {return false;}@@ -224,51 +208,20 @@ function canContinuePastHistoricalInput(input: {type PendingInputRoute =| { readonly batch: PendingInputBatch; readonly kind: "session-limit" }- | {- readonly approvalBatches: readonly PendingInputBatch[];- readonly kind: "with-approvals";- readonly questionBatches: readonly PendingInputBatch[];- }- | { readonly kind: "questions-only" };--type PendingInputBatchDomain = "approval" | "question" | "session-limit";+ | { readonly kind: "approvals" };function routePendingInput(batches: readonly PendingInputBatch[]): PendingInputRoute {- const classified = batches.map((batch) => ({ batch, domain: classifyPendingInputBatch(batch) }));- const limitBatch = classified.find(({ domain }) => domain === "session-limit")?.batch;+ const limitBatch = batches.find((batch) => isSessionLimitInputBatch(batch));if (limitBatch !== undefined) return { batch: limitBatch, kind: "session-limit" };- const approvalBatches = classified- .filter(({ domain }) => domain === "approval")- .map(({ batch }) => batch);- if (approvalBatches.length > 0) {- const approvalSet = new Set(approvalBatches);- return {- approvalBatches,- kind: "with-approvals",- questionBatches: batches.filter((batch) => !approvalSet.has(batch)),- };- }-- return { kind: "questions-only" };-}--function classifyPendingInputBatch(batch: PendingInputBatch): PendingInputBatchDomain {- for (const request of batch.requests) {- switch (request.kind) {- case "question":- case "session-limit":- case "tool-approval":- break;- default: {- const unhandled: never = request.kind;- throw new TypeError(`Unhandled pending input request kind: ${String(unhandled)}`);+ for (const batch of batches) {+ for (const request of batch.requests) {+ if (!isApprovalRequest(request)) {+ throw new TypeError(`Unhandled pending input request kind: ${request.kind}`);}}}-- if (isSessionLimitInputBatch(batch)) return "session-limit";- return batch.requests.some((request) => isApprovalRequest(request)) ? "approval" : "question";+ return { kind: "approvals" };}function canonicalizeInputResponses(responses: readonly InputResponse[]): readonly InputResponse[] {diff --git a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts b/packages/eve/src/harness/issue-3494-adversarial.integration.test.tsindex 6f7f351a1..b9b27fec6 100644--- a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts+++ b/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts@@ -68,18 +68,7 @@ function fixture(type: "tool-call" as const,toolCallId: `call-${call}-${index}`,toolName: tool.toolName,- input: JSON.stringify(- tool.input ??- (tool.toolName === "question"- ? {- prompt: "Choose a color",- options: [- { id: "red", label: "Red" },- { id: "blue", label: "Blue" },- ],- }- : { n: 1 }),- ),+ input: JSON.stringify(tool.input ?? { n: 1 }),providerExecuted: tool.providerExecuted,},...(tool.providerExecuted@@ -130,15 +119,6 @@ function fixture(},});}- tools.set("question", {- name: "question",- description: "Ask a question",- inputSchema: jsonSchema({ type: "object" }),- behavior: {- availability: ["requires-request-input"],- handling: { kind: "request-input", request: "question" },- },- });tools.set("workflow", {name: "workflow",description: "Deferred workflow",@@ -305,18 +285,6 @@ for (const variant of ["approve", "cancel"] as const) {});}-it("finishes tool work after answering a question while an earlier approval remains", async () => {- const f = fixture("question-answer");- await f.gate("gateA");- f.script.push(calls("question"));- await f.drive({ message: "Ask me for a color." });- expect(f.pending()).toHaveLength(2);- f.script.push(calls("read"), "FINAL");- const result = await f.drive(f.respond("question", "red"));- expect(f.pending().map((r) => r.action.toolName)).toEqual(["gateA"]);- expect(result.settledTurn?.output).toBe("FINAL");-});-for (const tool of ["workflow", "control"]) {it(`interprets a completed ${tool} result while an earlier approval remains`, async () => {const f = fixture(tool);@@ -330,21 +298,6 @@ for (const tool of ["workflow", "control"]) {});}-it("allows a tool turn while only multiple question batches remain", async () => {- const f = fixture("multiple-questions");- await f.gate("gateA");- for (let i = 0; i < 2; i++) {- f.script.push(calls("question"));- await f.drive({ message: `Ask question ${i}.` });- }- f.script.push("Cancelled.");- await f.drive(f.respond("gateA", "cancel"));- expect(f.pending().map((r) => r.kind)).toEqual(["question", "question"]);- f.script.push(calls("read"), "FINAL");- const result = await f.drive({ message: "Read the status first." });- expect(result.settledTurn?.output).toBe("FINAL");-});-it("completes a plain tool turn without any pending input [control]", async () => {const f = fixture("control-no-pending");f.script.push(calls("read"), "FINAL");@@ -368,17 +321,6 @@ it("finishes after resolving the only approval [control]", async () => {expect(f.pending()).toHaveLength(0);});-it("dismisses a sole question and completes the follow-up tool turn [control]", async () => {- const f = fixture("control-sole-question");- f.script.push(calls("question"));- await f.drive({ message: "Ask a question." });- f.script.push(calls("read"), "FINAL");- expect((await f.drive({ message: "Never mind. Read the status." })).settledTurn?.output).toBe(- "FINAL",- );- expect(f.pending()).toHaveLength(0);-});-it("finishes a deferred workflow without pending input [control]", async () => {const f = fixture("control-workflow");f.script.push(calls("workflow"), "FINAL");@@ -592,30 +534,6 @@ it("continues after responder-authorized approval of the older batch", async ()expect(result.settledTurn?.output).toBe("FINAL");});-it("parks on a new question while retaining a partial approval [control]", async () => {- const f = fixture("partial-approval-new-question");- // Given A and B need approval together, and only A has been answered.- await f.gate("gateA", "gateB");- await f.drive(f.respond("gateA"));-- // When the next user message causes the model to ask a question.- f.script.push(calls("question"));- const result = await f.step({ message: "Ask which color to use." });-- // Then the new question parks immediately, and A's answer is still remembered.- expect(result.next).toBeNull();- expect(f.pending().map((request) => request.kind)).toEqual([- "tool-approval",- "tool-approval",- "question",- ]);- expect(f.executions).toHaveLength(0);- f.script.push("Approved.");- await f.drive(f.respond("gateB"));- expect(f.executions).toEqual(["gateA", "gateB"]);- expect(f.pending().map((request) => request.kind)).toEqual(["question"]);-});-it("resumes a complete batch while another batch has only a partial approval [control]", async () => {const f = fixture("complete-and-partial-approvals");// Given A and B need approval together, and a second independent B is pending.@@ -644,27 +562,3 @@ it("resumes a complete batch while another batch has only a partial approval [coexpect(f.executions).toEqual(["gateB", "gateA", "gateB"]);expect(f.pending()).toHaveLength(0);});--it("answers a queued question after an approval while another approval stays pending", async () => {- const f = fixture("approval-then-question-with-sibling");- // Given independent approvals A and B, followed by a question.- await f.gate("gateA");- f.script.push(calls("gateB"));- await f.drive({ message: "Prepare B." });- f.script.push(calls("question"));- await f.drive({ message: "Ask which color." });-- // When one delivery answers A and the question, leaving B unanswered.- f.script.push("A approved.", "Color answered.");- const result = await f.drive({- inputResponses: [- ...f.respond("gateA").inputResponses!,- ...f.respond("question", "red").inputResponses!,- ],- });-- // Then both answers are processed and B alone stays pending.- expect(result.settledTurn?.output).toBe("Color answered.");- expect(f.executions).toEqual(["gateA"]);- expect(f.pending().map((request) => request.action.toolName)).toEqual(["gateB"]);-});diff --git a/packages/eve/src/harness/pending-input-batches.test.ts b/packages/eve/src/harness/pending-input-batches.test.tsindex b82b45002..acaf11ee0 100644--- a/packages/eve/src/harness/pending-input-batches.test.ts+++ b/packages/eve/src/harness/pending-input-batches.test.ts@@ -120,7 +120,7 @@ describe("pending input request ID uniqueness", () => {});describe("persisted pending input validation", () => {- it("rejects an unknown request kind instead of routing it as a question", () => {+ it("rejects an unknown request kind", () => {const persisted = session({"eve.runtime.pendingInputBatches": [{diff --git a/packages/eve/src/harness/pending-input-batches.ts b/packages/eve/src/harness/pending-input-batches.tsindex 37e461f2e..1686c7fc8 100644--- a/packages/eve/src/harness/pending-input-batches.ts+++ b/packages/eve/src/harness/pending-input-batches.ts@@ -37,7 +37,7 @@ export interface PendingInputBatch {/*** Returns true when the session holds at least one pending HITL batch- * (tool approvals or `ask_question` prompts).+ * (tool approvals or a session-limit continuation prompt).*/export function hasPendingInputBatch(state: SessionStateMap | undefined): boolean {return getPendingInputBatches(state).length > 0;diff --git a/packages/eve/src/harness/provider-tool-history.test.ts b/packages/eve/src/harness/provider-tool-history.test.tsindex 355d80a18..5e8a9094d 100644--- a/packages/eve/src/harness/provider-tool-history.test.ts+++ b/packages/eve/src/harness/provider-tool-history.test.ts@@ -162,9 +162,9 @@ describe("normalizeProviderToolHistory", () => {},{type: "tool-call",- toolCallId: "todo-1",- toolName: "todo",- input: { todos: [] },+ toolCallId: "read-1",+ toolName: "read_file",+ input: { filePath: "/workspace/a.ts" },},],},@@ -173,9 +173,9 @@ describe("normalizeProviderToolHistory", () => {content: [{type: "tool-result",- toolCallId: "todo-1",- toolName: "todo",- output: { type: "json", value: { todos: [] } },+ toolCallId: "read-1",+ toolName: "read_file",+ output: { type: "json", value: { content: "" } },},],},@@ -215,9 +215,9 @@ describe("normalizeProviderToolHistory", () => {content: [{type: "tool-call",- toolCallId: "todo-1",- toolName: "todo",- input: { todos: [] },+ toolCallId: "read-1",+ toolName: "read_file",+ input: { filePath: "/workspace/a.ts" },},],},@@ -226,9 +226,9 @@ describe("normalizeProviderToolHistory", () => {content: [{type: "tool-result",- toolCallId: "todo-1",- toolName: "todo",- output: { type: "json", value: { todos: [] } },+ toolCallId: "read-1",+ toolName: "read_file",+ output: { type: "json", value: { content: "" } },},],},diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.tsindex 44fd81c37..dac11fa8d 100644--- a/packages/eve/src/harness/proxy-input-requests.ts+++ b/packages/eve/src/harness/proxy-input-requests.ts@@ -1,6 +1,6 @@import type { SubagentInputRequestHookPayload } from "#channel/types.js";import type { HarnessSession, SessionStateMap } from "#harness/types.js";-import type { InputRequestKind } from "#shared/input.js";+import { inputOptionSchema, type InputOption, type InputRequestKind } from "#shared/input.js";import { isLoopbackHostname } from "#shared/network-address.js";import {isSessionInboxAddress,@@ -21,6 +21,15 @@ const PROXY_INPUT_REQUEST_KINDS = {*/export interface AnswerHookRoute {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 {+ readonly allowFreeform?: boolean;+ readonly dismissible?: boolean;+ readonly options?: readonly InputOption[];}/** Routing and control metadata for one descendant-owned input request. */@@ -322,9 +331,32 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRefunction parseAnswerHookRoute(value: unknown): AnswerHookRoute | undefined {if (value === null || typeof value !== "object" || !("runId" in value)) return undefined;- return typeof value.runId === "string" && value.runId.length > 0- ? { runId: value.runId }- : 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 parseAnswerHookQuestion(value: unknown): AnswerHookQuestion | 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 options = Reflect.get(value, "options");+ if (options !== undefined) {+ const parsed = inputOptionSchema.array().safeParse(options);+ if (!parsed.success) return undefined;+ question.options = parsed.data;+ }+ return question;}function parseProxyInputRequestBatch(value: unknown): ProxyInputRequestBatch | undefined {diff --git a/packages/eve/src/harness/request-input-tool.ts b/packages/eve/src/harness/request-input-tool.tsdeleted file mode 100644index f6e5f68e6..000000000--- a/packages/eve/src/harness/request-input-tool.ts+++ /dev/null@@ -1,4 +0,0 @@-/**- * Stable model-visible name for the framework question tool.- */-export const ASK_QUESTION_TOOL_NAME = "ask_question";diff --git a/packages/eve/src/harness/stale-input-responses.test.ts b/packages/eve/src/harness/stale-input-responses.test.tsindex 45893f36b..101a1437b 100644--- a/packages/eve/src/harness/stale-input-responses.test.ts+++ b/packages/eve/src/harness/stale-input-responses.test.ts@@ -7,21 +7,6 @@ import {dropStaleSessionLimitContinuationResponses,} from "#harness/stale-input-responses.js";-const QUESTION_TOOLS = new Map([- [- "ask_question",- {- behavior: {- availability: ["requires-request-input" as const],- handling: { kind: "request-input" as const, request: "question" as const },- },- description: "Ask a question.",- inputSchema: {} as never,- name: "ask_question",- },- ],-]);-const approvalHistory: ModelMessage[] = [{content: [@@ -41,7 +26,7 @@ const approvalHistory: ModelMessage[] = [},];-const questionHistory: ModelMessage[] = [+const unrecoverableHistory: ModelMessage[] = [{content: [{@@ -69,7 +54,6 @@ it("converts a stale approval into a non-authorizing user message", () => {stepInput: {inputResponses: [{ optionId: "approve", requestId: "approval-1" }],},- tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");@@ -86,9 +70,9 @@ it("converts a stale approval into a non-authorizing user message", () => {);});-it("converts an attributed stale question selection using its option label", () => {+it("converts an attributed stale approval using its option label", () => {const result = convertStaleResponsesToUserMessage({- history: questionHistory,+ history: approvalHistory,pendingRequestIds: new Set(),stepInput: {attributedInputResponses: [@@ -99,11 +83,10 @@ it("converts an attributed stale question selection using its option label", ()principalId: "user-1",principalType: "user",},- response: { optionId: "candidate", requestId: "question-1" },+ response: { optionId: "approve", requestId: "approval-1" },},],},- tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");@@ -111,17 +94,14 @@ it("converts an attributed stale question selection using its option label", ()throw new Error("Expected the stale response to be converted.");}- expect(result.displayMessage).toBe("Use the candidate");- expect(result.stepInput.message).toEqual(expect.stringContaining("Which context should I use?"));- expect(result.stepInput.message).toEqual(expect.stringContaining('"requestType": "question"'));- expect(result.stepInput.message).not.toEqual(- expect.stringContaining("This does not authorize an earlier action"),- );+ expect(result.displayMessage).toBe("Approve");+ expect(result.stepInput.attributedInputResponses).toBeUndefined();+ expect(result.stepInput.message).toEqual(expect.stringContaining('"requestType": "approval"'));});it("keeps responses for pending requests structured while converting stale ones", () => {const result = convertStaleResponsesToUserMessage({- history: questionHistory,+ history: unrecoverableHistory,pendingRequestIds: new Set(["question-2"]),stepInput: {inputResponses: [@@ -129,7 +109,6 @@ it("keeps responses for pending requests structured while converting stale ones"{ optionId: "candidate", requestId: "question-1" },],},- tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");@@ -149,7 +128,6 @@ it("keeps the non-authorization notice when request metadata is missing", () =>stepInput: {inputResponses: [{ optionId: "approve", requestId: "approval-gone" }],},- tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");@@ -172,7 +150,6 @@ it("returns unchanged when every response matches the pending batch", () => {history: approvalHistory,pendingRequestIds: new Set(["approval-1"]),stepInput,- tools: QUESTION_TOOLS,});expect(result.kind).toBe("unchanged");@@ -239,10 +216,9 @@ it("converts remaining stale responses after the drop pass", () => {},});const result = convertStaleResponsesToUserMessage({- history: questionHistory,+ history: unrecoverableHistory,pendingRequestIds,stepInput,- tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");diff --git a/packages/eve/src/harness/stale-input-responses.ts b/packages/eve/src/harness/stale-input-responses.tsindex db032daf6..8169fdb57 100644--- a/packages/eve/src/harness/stale-input-responses.ts+++ b/packages/eve/src/harness/stale-input-responses.ts@@ -1,10 +1,9 @@import type { ModelMessage, UserContent } from "ai";import { extractHistoricalInputRequests } from "#harness/input-extraction.js";-import { isApprovalRequest } from "#harness/input-request-class.js";import { appendUserContent, normalizeUserContent } from "#harness/messages.js";import { isSessionLimitContinuationRequestId } from "#harness/session-limit-continuation.js";-import type { HarnessToolMap, StepInput } from "#harness/types.js";+import type { StepInput } from "#harness/types.js";import type { InputRequest, InputResponse } from "#shared/input.js";type StaleResponseConversion =@@ -72,7 +71,6 @@ export function convertStaleResponsesToUserMessage(input: {readonly history: readonly ModelMessage[];readonly pendingRequestIds: ReadonlySet<string>;readonly stepInput?: StepInput;- readonly tools: HarnessToolMap;}): StaleResponseConversion {if (input.stepInput === undefined) return { kind: "unchanged" };const responses = input.stepInput.inputResponses ?? [];@@ -104,7 +102,6 @@ export function convertStaleResponsesToUserMessage(input: {const requests = extractHistoricalInputRequests({history: input.history,requestIds: new Set(staleResponses.map((response) => response.requestId)),- tools: input.tools,});const modelMessage = appendOptionalUserContent(input.stepInput.message,@@ -162,30 +159,22 @@ function formatModelMessage(const resolved: {prompt?: string;requestId: string;- requestType?: "approval" | "question";+ requestType?: "approval";response: typeof responseDetails;} = { requestId: response.requestId, response: responseDetails };if (request !== undefined) {resolved.prompt = request.prompt;- resolved.requestType = isApprovalRequest(request) ? "approval" : "question";+ resolved.requestType = "approval";}return resolved;});- // Request metadata can be missing (compacted history, subagent-proxied- // request), so a response without it may still be an approval: default to- // including the notice.- const mayIncludeApproval = responses.some((response) => {- const request = requests.get(response.requestId);- return request === undefined || isApprovalRequest(request);- });- const approvalNotice = mayIncludeApproval- ? " This does not authorize an earlier action; request approval again if that action is still needed."- : "";+ // History only recovers approvals, and a response without recovered+ // metadata may still be one, so the notice always applies.return ["The user submitted the following response to an earlier interactive prompt.",- `Treat it as new input at the current point in the conversation and decide whether it is still relevant.${approvalNotice}`,+ "Treat it as new input at the current point in the conversation and decide whether it is still relevant. This does not authorize an earlier action; request approval again if that action is still needed.",JSON.stringify(resolvedResponses, null, 2),].join("\n");}diff --git a/packages/eve/src/harness/tool-input-validation.integration.test.ts b/packages/eve/src/harness/tool-input-validation.integration.test.tsindex 7e14868f4..e6328b7ad 100644--- a/packages/eve/src/harness/tool-input-validation.integration.test.ts+++ b/packages/eve/src/harness/tool-input-validation.integration.test.ts@@ -2,11 +2,8 @@ import type { LanguageModel, ModelMessage } from "ai";import { MockLanguageModelV4 } from "ai/test";import { describe, expect, it } from "vitest";-import { getPendingInputRequestIds } from "#harness/input-requests.js";import { createToolLoopHarness } from "#harness/tool-loop.js";import type { HarnessSession, ToolLoopHarnessConfig } from "#harness/types.js";-import { ASK_QUESTION_INPUT_SCHEMA, askQuestion } from "#tools/framework/ask-question.js";-import { serializeInputSchema } from "#tools/schema.js";const usage = {inputTokens: {@@ -34,127 +31,6 @@ function findToolResult(messages: readonly ModelMessage[], toolCallId: string):}describe("framework tool input validation (real AI SDK)", () => {- it("returns malformed and schema-invalid ask_question input to the model before accepting a retry", async () => {- const malformedCallId = "question-malformed";- const invalidCallId = "question-invalid";- const validCallId = "question-valid";- const model = new MockLanguageModelV4({- doGenerate: [- {- content: [- {- input: '{"prompt":',- toolCallId: malformedCallId,- toolName: "ask_question",- type: "tool-call",- },- ],- finishReason: { raw: undefined, unified: "tool-calls" },- usage,- warnings: [],- },- {- content: [- {- input: JSON.stringify({ prompt: 42 }),- toolCallId: invalidCallId,- toolName: "ask_question",- type: "tool-call",- },- ],- finishReason: { raw: undefined, unified: "tool-calls" },- usage,- warnings: [],- },- {- content: [- {- input: JSON.stringify({ prompt: "Which option should I use?" }),- toolCallId: validCallId,- toolName: "ask_question",- type: "tool-call",- },- ],- finishReason: { raw: undefined, unified: "tool-calls" },- usage,- warnings: [],- },- ],- modelId: "tool-validation-model",- provider: "eve-integration-mock",- });- const tools: ToolLoopHarnessConfig["tools"] = new Map([- [- "ask_question",- {- behavior: {- availability: ["requires-request-input"],- handling: { kind: "request-input", request: "question" },- },- description: askQuestion.description,- inputSchema: ASK_QUESTION_INPUT_SCHEMA,- name: "ask_question",- },- ],- ]);- const config: ToolLoopHarnessConfig = {- capabilities: { requestInput: true },- mode: "conversation",- resolveModel: async (): Promise<LanguageModel> => model,- tools,- };- const session: HarnessSession = {- agent: {- modelReference: { id: "tool-validation-model" },- system: "You are a test assistant.",- tools: [- {- description: askQuestion.description,- inputSchema: serializeInputSchema(ASK_QUESTION_INPUT_SCHEMA),- name: "ask_question",- },- ],- },- compaction: { recentWindowSize: 10, threshold: 100_000 },- continuationToken: "http:tool-validation-session",- history: [],- sessionId: "tool-validation-session",- };- const runStep = createToolLoopHarness(config);-- const malformedStep = await runStep(session, { message: "Ask me which option to use." });-- expect(typeof malformedStep.next).toBe("function");- expect(getPendingInputRequestIds(malformedStep.session.state)).toEqual(new Set());- expect(findToolResult(malformedStep.session.history, malformedCallId)).toMatchObject({- output: expect.objectContaining({ type: "error-text" }),- toolName: "ask_question",- });-- if (typeof malformedStep.next !== "function") {- throw new TypeError("Expected the malformed tool call to continue the tool loop.");- }- const invalidStep = await malformedStep.next(malformedStep.session);-- expect(typeof invalidStep.next).toBe("function");- expect(getPendingInputRequestIds(invalidStep.session.state)).toEqual(new Set());- expect(findToolResult(invalidStep.session.history, invalidCallId)).toMatchObject({- output: expect.objectContaining({ type: "error-text" }),- toolName: "ask_question",- });-- if (typeof invalidStep.next !== "function") {- throw new TypeError("Expected the invalid tool call to continue the tool loop.");- }- const validStep = await invalidStep.next(invalidStep.session);-- expect(model.doGenerateCalls).toHaveLength(3);- expect(findToolResult(model.doGenerateCalls[1]?.prompt ?? [], malformedCallId)).toBeDefined();- expect(findToolResult(model.doGenerateCalls[2]?.prompt ?? [], invalidCallId)).toBeDefined();- expect(validStep.next).toBeNull();- expect(getPendingInputRequestIds(validStep.session.state)).toEqual(new Set([validCallId]));- });-it("rejects invalid final_output input instead of terminating the task", async () => {const invalidCallId = "final-invalid";const validCallId = "final-valid";diff --git a/packages/eve/src/harness/tool-loop-compaction-accounting.test.ts b/packages/eve/src/harness/tool-loop-compaction-accounting.test.tsindex b3a95acce..8323f9db2 100644--- a/packages/eve/src/harness/tool-loop-compaction-accounting.test.ts+++ b/packages/eve/src/harness/tool-loop-compaction-accounting.test.ts@@ -349,15 +349,20 @@ describe("tool-loop structured compaction accounting", () => {requests: [{action: {- callId: "question-call",- input: { prompt: "Pick one." },+ callId: "call-1",+ input: { command: "pwd" },kind: "tool-call",- toolName: "ask_question",+ toolName: "bash",},- display: "select",- kind: "question",- prompt: "Pick one.",- requestId: "question-call",+ allowFreeform: false,+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Yes" },+ { id: "cancel", label: "No" },+ ],+ prompt: "Approve tool call: bash",+ requestId: "approval-1",},],responseMessages: [],@@ -375,8 +380,8 @@ describe("tool-loop structured compaction accounting", () => {const result = await runStep(session, {inputResponses: [{- optionId: "yes",- requestId: "question-call",+ optionId: "approve",+ requestId: "approval-1",},],});@@ -596,58 +601,4 @@ describe("final request envelope compaction", () => {expect(events.indexOf("compaction.requested")).toBeGreaterThan(events.indexOf("step.started"));expect(vi.mocked(ToolLoopAgent).mock.calls[0]?.[0].tools).toHaveProperty("catalog");});-- it("does not count a capability-filtered tool that the provider never sees", async () => {- setupMockAgentSequence([completed()]);- const runStep = createToolLoopHarness(- createTestConfig({- tools: new Map([- [- "hidden",- {- name: "hidden",- description: "private catalog ".repeat(10_000),- inputSchema: jsonSchema({ type: "object" }),- behavior: { availability: ["requires-request-input"] },- },- ],- ]),- }),- );- await runStep(- createTestSession({- compaction: {- lastKnownInputTokens: 8_000,- lastKnownPromptMessageCount: 1,- recentWindowSize: 0,- threshold: 10_000,- },- history: [{ role: "user", kind: "user", content: "earlier" }],- }),- { message: "continue" },- );- expect(generateText).not.toHaveBeenCalled();- expect(vi.mocked(ToolLoopAgent).mock.calls[0]?.[0].tools).not.toHaveProperty("hidden");- });- it("propagates a compaction callback failure without treating it as a model failure", async () => {- const error = new Error("memory recall failed");- const onCompaction = vi.fn(() => {- throw error;- });- vi.mocked(generateText).mockResolvedValue({ text: "summary" } as Awaited<- ReturnType<typeof generateText>- >);- const runStep = createToolLoopHarness(createTestConfig({ onCompaction }));- await expect(- runStep(- createTestSession({- compaction: { recentWindowSize: 0, threshold: 100 },- history: [{ role: "user", kind: "user", content: "history ".repeat(1_000) }],- }),- { message: "continue" },- ),- ).rejects.toBe(error);- expect(onCompaction).toHaveBeenCalledOnce();- expect(ToolLoopAgent).not.toHaveBeenCalled();- });});diff --git a/packages/eve/src/harness/tool-loop-steering.integration.test.ts b/packages/eve/src/harness/tool-loop-steering.integration.test.tsindex d0276bf21..b03de2890 100644--- a/packages/eve/src/harness/tool-loop-steering.integration.test.ts+++ b/packages/eve/src/harness/tool-loop-steering.integration.test.ts@@ -6,6 +6,9 @@ import { getHarnessEmissionState } from "#harness/emission-state.js";import { TurnCancelledError } from "#harness/turn-cancellation.js";import type { HarnessSession } from "#harness/types.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";+import { always } from "#tools/approval/policies.js";+import { ContextContainer, contextStorage } from "#context/container.js";+import { SessionKey } from "#context/keys.js";type StreamResult = Awaited<ReturnType<MockLanguageModelV3["doStream"]>>;type Part = StreamResult["stream"] extends ReadableStream<infer T> ? T : never;@@ -86,9 +89,9 @@ describe("generation steering with the real AI SDK", () => {start(controller) {controller.enqueue({type: "tool-call",- toolCallId: "question-1",- toolName: "ask_question",- input: JSON.stringify({ prompt: "Which year should Alice use?" }),+ toolCallId: "publish-1",+ toolName: "publish_report",+ input: JSON.stringify({}),});controller.enqueue({type: "finish",@@ -101,21 +104,19 @@ describe("generation steering with the real AI SDK", () => {};},});- const result = await createToolLoopHarness({+ const harness = createToolLoopHarness({mode: "conversation",capabilities: { requestInput: true },steeringSignal: steering.signal,tools: new Map([[- "ask_question",+ "publish_report",{- name: "ask_question",- description: "Ask the user a question",+ approval: always(),+ name: "publish_report",+ description: "Publish Alice's report after approval",+ execute: async () => ({ published: true }),inputSchema: jsonSchema({ type: "object" }),- behavior: {- availability: ["requires-request-input"],- handling: { kind: "request-input", request: "question" },- },},],]),@@ -124,7 +125,16 @@ describe("generation steering with the real AI SDK", () => {events.push(event);if (event.type === boundary) steering.abort();},- })(session(), { message: "Report only if there is a new update" });+ });+ const ctx = new ContextContainer();+ ctx.set(SessionKey, {+ auth: { current: null, initiator: null },+ sessionId: session().sessionId,+ turn: { id: "turn_0", sequence: 0 },+ });+ const result = await contextStorage.run(ctx, () =>+ harness(session(), { message: "Report only if there is a new update" }),+ );expect(result.steered).toBeUndefined();expect(result.next).toBeNull();expect(events.filter((event) => event.type === boundary)).toHaveLength(1);diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 91e07d6a9..cf00e0517 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -364,23 +364,6 @@ function createDelegationToolMap(): ToolLoopHarnessConfig["tools"] {]);}-function createQuestionToolMap(): ToolLoopHarnessConfig["tools"] {- return new Map([- [- "ask_question",- {- behavior: {- availability: ["requires-request-input"],- handling: { kind: "request-input", request: "question" },- },- description: "Ask the user a question.",- inputSchema: jsonSchema({ type: "object" }),- name: "ask_question",- },- ],- ]);-}-function createScheduleContext(): ContextContainer {const ctx = new ContextContainer();ctx.set(AuthKey, SCHEDULE_APP_AUTH);@@ -3972,87 +3955,6 @@ describe("createToolLoopHarness", () => {});});- it("does not park an invalid ask_question call and continues with its tool error", async () => {- setupMockAgent({- finishReason: "tool-calls",- response: {- messages: [- {- content: [- {- input: { prompt: 42 },- toolCallId: "question-invalid",- toolName: "ask_question",- type: "tool-call",- },- ],- role: "assistant",- },- {- content: [- {- output: { type: "error-text", value: "Expected string, received number" },- toolCallId: "question-invalid",- toolName: "ask_question",- type: "tool-result",- },- ],- role: "tool",- },- ],- },- toolCalls: [- {- dynamic: true,- error: new Error("Expected string, received number"),- input: { prompt: 42 },- invalid: true,- toolCallId: "question-invalid",- toolName: "ask_question",- type: "tool-call",- },- ],- toolResults: [],- });-- const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(- createTestConfig("conversation", emit, {- capabilities: { requestInput: true },- tools: new Map([- [- "ask_question",- {- description: "Ask the user a question.",- inputSchema: jsonSchema({ type: "object" }),- name: "ask_question",- },- ],- ]),- }),- );- const session = createTestSession({- agent: {- modelReference: { id: "test-model" },- system: "You are a test assistant.",- tools: [- {- description: "Ask the user a question.",- inputSchema: { type: "object" },- name: "ask_question",- },- ],- },- });-- const result = await runStep(session, { message: "Ask me a question." });-- expect(typeof result.next).toBe("function");- expect(hasPendingInputBatch(result.session.state)).toBe(false);- expect(events.some((event) => event.type === "input.requested")).toBe(false);- expect(result.session.history.at(-1)?.role).toBe("tool");- });-it("feeds non-object tool call input back to the model as a failed tool result", async () => {const invalidInput = '"not an object"';const errorMessage =@@ -7337,12 +7239,14 @@ describe("createToolLoopHarness", () => {});it("normalizes provider history before parking on an input request", async () => {- const searchCallId = "parallel_search_before_question";- const questionCallId = "question-after-search";+ const searchCallId = "parallel_search_before_gate";+ const gateCallId = "gate-after-search";const webSearchOutput = { results: [], searchId: "search-1" };- const questionInput = {- options: [{ id: "one", label: "One" }],- prompt: "Choose one.",+ const gateInput = { action: "run" };+ const approvalRequest = {+ approvalId: "approval-after-search",+ toolCallId: gateCallId,+ type: "tool-approval-request" as const,};setupMockAgent({content: [@@ -7360,11 +7264,12 @@ describe("createToolLoopHarness", () => {type: "tool-result",},{- input: questionInput,- toolCallId: questionCallId,- toolName: "ask_question",+ input: gateInput,+ toolCallId: gateCallId,+ toolName: "add",type: "tool-call",},+ approvalRequest,],finishReason: "tool-calls",response: {@@ -7385,11 +7290,12 @@ describe("createToolLoopHarness", () => {type: "tool-result",},{- input: questionInput,- toolCallId: questionCallId,- toolName: "ask_question",+ input: gateInput,+ toolCallId: gateCallId,+ toolName: "add",type: "tool-call",},+ approvalRequest,],role: "assistant",},@@ -7404,9 +7310,9 @@ describe("createToolLoopHarness", () => {type: "tool-call",},{- input: questionInput,- toolCallId: questionCallId,- toolName: "ask_question",+ input: gateInput,+ toolCallId: gateCallId,+ toolName: "add",type: "tool-call",},],@@ -7424,7 +7330,6 @@ describe("createToolLoopHarness", () => {const harness = createToolLoopHarness(createTestConfig("conversation", undefined, {capabilities: { requestInput: true },- tools: createQuestionToolMap(),}),);const result = await harness(@@ -7432,17 +7337,10 @@ describe("createToolLoopHarness", () => {agent: {modelReference: { id: "anthropic/claude-sonnet-5" },system: "You are a test assistant.",- tools: [- { description: "Search the web", name: "web_search", inputSchema: null },- {- description: "Ask the user a question.",- name: "ask_question",- inputSchema: { type: "object" },- },- ],+ tools: [{ description: "Search the web", name: "web_search", inputSchema: null }],},}),- { message: "Search, then ask me a question." },+ { message: "Search, then run the gated tool." },);const pendingResponseMessages = (@@ -7480,11 +7378,12 @@ describe("createToolLoopHarness", () => {{content: [{- input: questionInput,- toolCallId: questionCallId,- toolName: "ask_question",+ input: gateInput,+ toolCallId: gateCallId,+ toolName: "add",type: "tool-call",},+ approvalRequest,],role: "assistant",},@@ -8669,202 +8568,6 @@ describe("createToolLoopHarness", () => {expect(getPendingInputRequestIds(result.session.state)).toEqual(new Set(["approval-1"]));});- it("parks a second input batch while an earlier approval stays open", async () => {- const generateCalls: Array<Array<{ role: string; content: unknown }>> = [];- const agentResults = [- {- finishReason: "tool-calls",- response: {- messages: [- {- content: [- { text: "Which color?", type: "text" },- {- input: {- options: [- { id: "red", label: "Red" },- { id: "blue", label: "Blue" },- ],- prompt: "Pick a color.",- },- toolCallId: "question-call",- toolName: "ask_question",- type: "tool-call",- },- ],- role: "assistant",- },- ],- },- text: "",- toolCalls: [- {- input: {- options: [- { id: "red", label: "Red" },- { id: "blue", label: "Blue" },- ],- prompt: "Pick a color.",- },- toolCallId: "question-call",- toolName: "ask_question",- type: "tool-call",- },- ],- toolResults: [],- },- {- finishReason: "stop",- response: { messages: [{ content: "Red it is.", role: "assistant" }] },- text: "Red it is.",- toolCalls: [],- toolResults: [],- },- {- finishReason: "stop",- response: {- messages: [{ content: "Understood, not running it.", role: "assistant" }],- },- text: "Understood, not running it.",- toolCalls: [],- toolResults: [],- },- ] satisfies Record<string, unknown>[];- let instanceIndex = 0;-- vi.mocked(ToolLoopAgent).mockImplementation(function (- this: MockAgentInstance,- settings: MockAgentSettings,- ) {- const result = agentResults[instanceIndex];- instanceIndex += 1;- if (result === undefined) {- throw new Error("ToolLoopAgent mock exhausted its scripted results.");- }- const { onStepEnd, prepareStep } = settings;- this.generate = vi.fn().mockImplementation(async (input: { messages: unknown[] }) => {- if (prepareStep) {- await prepareStep({- messages: input.messages,- steps: [],- stepNumber: 0,- model: {},- context: undefined,- });- }- generateCalls.push(input.messages as Array<{ role: string; content: unknown }>);- if (onStepEnd) await onStepEnd(result);- return createMockGenerateResult(result);- });- return this;- } as MockAgentConstructor);-- const session = appendPendingInputBatch({- requests: [- {- action: {- callId: "call-1",- input: { command: "rm -rf /tmp/demo" },- kind: "tool-call",- toolName: "bash",- },- allowFreeform: false,- display: "confirmation",- kind: "tool-approval",- options: [- { id: "approve", label: "Yes" },- { id: "cancel", label: "No" },- ],- prompt: "Approve tool call: bash",- requestId: "approval-1",- },- ],- responseMessages: [- {- content: [- {- input: { command: "rm -rf /tmp/demo" },- toolCallId: "call-1",- toolName: "bash",- type: "tool-call",- },- {- approvalId: "approval-1",- toolCallId: "call-1",- type: "tool-approval-request",- },- ],- role: "assistant",- },- ],- session: createTestSession({- agent: {- modelReference: { id: "test-model" },- system: "You are a test assistant.",- tools: [- { description: "Run shell commands", name: "bash", inputSchema: { type: "object" } },- {- description: "Ask the user a question.",- name: "ask_question",- inputSchema: { type: "object" },- },- ],- },- }),- });- const config = createTestConfig("conversation", undefined, {- capabilities: { requestInput: true },- tools: new Map([- [- "bash",- {- description: "Run shell commands",- execute: vi.fn().mockResolvedValue("ok"),- inputSchema: jsonSchema({ type: "object" }),- name: "bash",- },- ],- ...createQuestionToolMap(),- ]),- });-- // The intervening turn raises its own question batch; the approval batch- // must survive it instead of being overwritten.- const questionTurn = await createToolLoopHarness(config)(session, {- message: "Ask me which color to use.",- });- expect(questionTurn.next).toBeNull();- const questionSettings = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0];- expect(questionSettings?.toolChoice).not.toBe("none");- expect(questionSettings?.tools).toHaveProperty("bash");- expect(getPendingInputRequestIds(questionTurn.session.state)).toEqual(- new Set(["approval-1", "question-call"]),- );-- // Answering the question closes only its own batch.- const answered = await createToolLoopHarness(config)(questionTurn.session, {- inputResponses: [{ requestId: "question-call", optionId: "red" }],- });- expect(getPendingInputRequestIds(answered.session.state)).toEqual(new Set(["approval-1"]));- const answeredPrompt = generateCalls[1] ?? [];- expect(- answeredPrompt.some((message) => JSON.stringify(message.content).includes("question-call")),- ).toBe(true);- expect(- answeredPrompt.some((message) => JSON.stringify(message.content).includes("call-1")),- ).toBe(false);-- // The original approval still resolves afterwards.- const denied = await createToolLoopHarness(config)(answered.session, {- inputResponses: [{ requestId: "approval-1", optionId: "cancel" }],- });- expect(hasPendingInputBatch(denied.session.state)).toBe(false);- expect(denied.session.history.at(-1)).toEqual({- content: "Understood, not running it.",- role: "assistant",- });- });-it("releases a message wedged behind an approval by an earlier version", async () => {const generateCalls: Array<Array<{ role: string; content: unknown }>> = [];const stillHere = {@@ -9508,437 +9211,6 @@ describe("createToolLoopHarness", () => {},);- it("continues deferred input when approval resolution raises another request", async () => {- setupMockAgentSequence([- {- finishReason: "tool-calls",- response: {- messages: [- {- content: [- {- input: { prompt: "Which color?" },- toolCallId: "question-1",- toolName: "ask_question",- type: "tool-call",- },- ],- role: "assistant",- },- ],- },- text: "",- toolCalls: [- {- input: { prompt: "Which color?" },- toolCallId: "question-1",- toolName: "ask_question",- type: "tool-call",- },- ],- toolResults: [],- },- {- finishReason: "stop",- response: { messages: [{ content: "Handled the deferred message.", role: "assistant" }] },- text: "Handled the deferred message.",- toolCalls: [],- toolResults: [],- },- ]);-- const base = createPendingBashApprovalSession();- const session = {- ...base,- agent: {- ...base.agent,- tools: [- ...base.agent.tools,- {- description: "Ask the user a question.",- inputSchema: { type: "object" },- name: "ask_question",- },- ],- },- };- const config = createTestConfig("conversation", undefined, {- capabilities: { requestInput: true },- tools: new Map([- [- "bash",- {- description: "Run shell commands",- execute: vi.fn().mockResolvedValue("ok"),- inputSchema: jsonSchema({ type: "object" }),- name: "bash",- },- ],- [- "ask_question",- {- behavior: {- availability: ["requires-request-input"],- handling: { kind: "request-input", request: "question" },- },- description: "Ask the user a question.",- inputSchema: jsonSchema({ type: "object" }),- name: "ask_question",- },- ],- ]),- });- const runStep = createToolLoopHarness(config);-- const first = await runStep(session, {- inputResponses: [{ optionId: "cancel", requestId: "approval-1" }],- message: "Use this instead.",- });-- expect(typeof first.next).toBe("function");- expect(getPendingInputRequestIds(first.session.state)).toEqual(new Set(["question-1"]));- if (typeof first.next !== "function") {- throw new TypeError("Expected deferred input to continue after the new question.");- }- const result = await first.next(first.session);-- expect(result.next).toBeNull();- expect(hasDeferredStepInput(result.session)).toBe(false);- expect(hasPendingInputBatch(result.session.state)).toBe(false);- expect(JSON.stringify(result.session.history)).toContain("Use this instead.");- });-- it("emits input.requested for ask_question and does not emit actions.requested", async () => {- setupMockAgent({- content: [],- finishReason: "tool-calls",- response: {- messages: [- {- content: [- { text: "I need a choice.", type: "text" },- {- input: {- options: [{ id: "one", label: "One" }],- prompt: "Choose one.",- },- toolCallId: "question-1",- toolName: "ask_question",- type: "tool-call",- },- ],- role: "assistant",- },- ],- },- text: "",- toolCalls: [- {- input: {- options: [{ id: "one", label: "One" }],- prompt: "Choose one.",- },- toolCallId: "question-1",- toolName: "ask_question",- type: "tool-call",- },- ],- toolResults: [],- });-- const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(- createTestConfig("conversation", emit, {- capabilities: { requestInput: true },- tools: createQuestionToolMap(),- }),- );- const session = createTestSession({- agent: {- modelReference: { id: "test-model" },- system: "You are a test assistant.",- tools: [- {- description: "Ask the user a question.",- name: "ask_question",- inputSchema: { type: "object" },- },- ],- },- });-- const result = await runStep(session, { message: "Choose for me." });-- expect(result.next).toBeNull();- expect(events.some((event) => event.type === "actions.requested")).toBe(false);- expect(events.find((event) => event.type === "input.requested")).toEqual({- data: {- requests: [- {- action: {- callId: "question-1",- input: {- options: [{ id: "one", label: "One" }],- prompt: "Choose one.",- },- kind: "tool-call",- toolName: "ask_question",- },- display: "select",- kind: "question",- options: [{ id: "one", label: "One" }],- prompt: "Choose one.",- requestId: "question-1",- },- ],- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- type: "input.requested",- });- });-- it("delivers a stale ask_question selection as a new user turn while another question is pending", async () => {- const nextQuestionInput = {- allowFreeform: false,- options: [- { id: "alpha", label: "Use alpha" },- { id: "beta", label: "Use beta" },- ],- prompt: "Which new context should I use?",- };- setupMockAgent({- content: [],- finishReason: "tool-calls",- response: {- messages: [- {- content: [- {- input: nextQuestionInput,- toolCallId: "question-2",- toolName: "ask_question",- type: "tool-call",- },- ],- role: "assistant",- },- ],- },- text: "",- toolCalls: [- {- input: nextQuestionInput,- toolCallId: "question-2",- toolName: "ask_question",- type: "tool-call",- },- ],- toolResults: [],- });- const nextQuestionImplementation = vi.mocked(ToolLoopAgent).getMockImplementation();- setupMockAgent({- finishReason: "stop",- response: { messages: [{ content: "I will use the candidate.", role: "assistant" }] },- text: "I will use the candidate.",- toolCalls: [],- toolResults: [],- });- vi.mocked(ToolLoopAgent).mockImplementationOnce(nextQuestionImplementation!);-- const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(- createTestConfig("conversation", emit, {- capabilities: { requestInput: true },- tools: createQuestionToolMap(),- }),- );- const questionInput = {- allowFreeform: true,- options: [- {- description: "Use the current conversation context.",- id: "current",- label: "Use current context",- },- {- description: "Use the candidate from the earlier question.",- id: "candidate",- label: "Use STALE-CANDIDATE-7Q4M",- },- ],- prompt: "Which context should I use?",- };- const session = appendPendingInputBatch({- requests: [- {- action: {- callId: "question-1",- input: questionInput,- kind: "tool-call",- toolName: "ask_question",- },- allowFreeform: true,- display: "select",- kind: "question",- options: questionInput.options,- prompt: questionInput.prompt,- requestId: "question-1",- },- ],- responseMessages: [- {- content: [- {- input: questionInput,- toolCallId: "question-1",- toolName: "ask_question",- type: "tool-call",- },- ],- role: "assistant",- },- ],- session: createTestSession({- history: [{ content: "Help me choose.", kind: "user" as const, role: "user" }],- }),- });-- const followupResult = await runStep(session, {- message: "Use current context instead.",- });-- expect(followupResult.next).toBeNull();- expect(hasPendingInputBatch(followupResult.session.state)).toBe(true);-- const secondTurnEventIndex = events.length;- const result = await runStep(followupResult.session, {- inputResponses: [{ requestId: "question-1", optionId: "candidate" }],- });-- const agent = vi.mocked(ToolLoopAgent).mock.results.at(-1)?.value;- if (agent === undefined) {- throw new Error("ToolLoopAgent mock did not return an instance.");- }- const modelMessages = vi.mocked(agent.stream).mock.calls[0]?.[0].messages;-- expect(result.next).toBeNull();- expect(hasPendingInputBatch(result.session.state)).toBe(false);- expect(modelMessages?.at(-1)).toEqual({- content: expect.stringContaining("STALE-CANDIDATE-7Q4M"),- kind: "user" as const,- role: "user",- });- expect(- events.slice(secondTurnEventIndex).find((event) => event.type === "message.received"),- ).toMatchObject({- data: {- message: "Use STALE-CANDIDATE-7Q4M",- },- });- });-- it("delivers a stale ask_question selection as a new user turn when nothing is pending", async () => {- setupMockAgent({- finishReason: "stop",- response: { messages: [{ content: "Understood.", role: "assistant" }] },- text: "Understood.",- toolCalls: [],- toolResults: [],- });-- const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(- createTestConfig("conversation", emit, {- capabilities: { requestInput: true },- tools: createQuestionToolMap(),- }),- );- const questionInput = {- allowFreeform: true,- options: [- { id: "current", label: "Use current context" },- { id: "candidate", label: "Use STALE-CANDIDATE-7Q4M" },- ],- prompt: "Which context should I use?",- };- const session = appendPendingInputBatch({- requests: [- {- action: {- callId: "question-1",- input: questionInput,- kind: "tool-call",- toolName: "ask_question",- },- allowFreeform: true,- display: "select",- kind: "question",- options: questionInput.options,- prompt: questionInput.prompt,- requestId: "question-1",- },- ],- responseMessages: [- {- content: [- {- input: questionInput,- toolCallId: "question-1",- toolName: "ask_question",- type: "tool-call",- },- ],- role: "assistant",- },- ],- session: createTestSession({- history: [{ content: "Help me choose.", kind: "user" as const, role: "user" }],- }),- });-- // The follow-up resolves question-1 as freeform; the turn completes with- // nothing pending.- const followupResult = await runStep(session, {- message: "Use current context instead.",- });-- expect(followupResult.next).toBeNull();- expect(hasPendingInputBatch(followupResult.session.state)).toBe(false);-- const secondTurnEventIndex = events.length;- const result = await runStep(followupResult.session, {- inputResponses: [{ requestId: "question-1", optionId: "candidate" }],- });-- const agent = vi.mocked(ToolLoopAgent).mock.results.at(-1)?.value;- if (agent === undefined) {- throw new Error("ToolLoopAgent mock did not return an instance.");- }- const modelMessages = vi.mocked(agent.stream).mock.calls[0]?.[0].messages;-- expect(result.next).toBeNull();- expect(hasPendingInputBatch(result.session.state)).toBe(false);- expect(modelMessages?.at(-1)).toEqual({- content: expect.stringContaining("STALE-CANDIDATE-7Q4M"),- kind: "user" as const,- role: "user",- });- // The stale selection must not append a second tool result for- // question-1: only the freeform answer from the follow-up turn exists.- expect(modelMessages?.filter((message: ModelMessage) => message.role === "tool")).toHaveLength(- 1,- );- expect(- events.slice(secondTurnEventIndex).find((event) => event.type === "message.received"),- ).toMatchObject({- data: {- message: "Use STALE-CANDIDATE-7Q4M",- },- });- });-it("emits compaction.requested and compaction.completed when compaction triggers", async () => {vi.mocked(shouldCompact).mockReturnValue(true);vi.mocked(compactMessages).mockResolvedValue([@@ -10143,7 +9415,6 @@ describe("createToolLoopHarness", () => {vi.mocked(compactMessages).mockResolvedValue(compactedHistory);const { emit, events } = createEventCollector();- const onCompaction = vi.fn(() => []);const hidden = {content: "Hidden internal context.",kind: "user" as const,@@ -10153,7 +9424,6 @@ describe("createToolLoopHarness", () => {createTestConfig("conversation", emit, {compactOnly: true,historyProjector: ({ messages }) => messages.filter((message) => message !== hidden),- onCompaction,resolveModel: vi.fn().mockResolvedValue({ modelId: "gpt-4", provider: "openai" } as LanguageModel),@@ -10186,7 +9456,6 @@ describe("createToolLoopHarness", () => {{ content: "Dynamic user instructions.", kind: "user" as const, role: "user" },{ content: "old reply", role: "assistant" },]);- expect(onCompaction).toHaveBeenCalledOnce();expect(ToolLoopAgent).not.toHaveBeenCalled();expect(getCompatibilityEventTypes(events)).toEqual(["compaction.requested",@@ -10475,43 +9744,6 @@ describe("createToolLoopHarness", () => {});});- it("invokes onCompaction callback after compaction", async () => {- vi.mocked(shouldCompact).mockReturnValue(true);- vi.mocked(compactMessages).mockResolvedValue([- createFrameworkUserMessage("context.compaction", "Summary of our conversation so far:"),- { content: "summary", role: "assistant" },- ]);-- setupMockAgent({- finishReason: "stop",- response: { messages: [{ content: "Resuming.", role: "assistant" }] },- text: "Resuming.",- toolCalls: [],- toolResults: [],- });-- const onCompaction = vi- .fn()- .mockReturnValue([createFrameworkUserMessage("context.state", "[State preserved]")]);-- const runStep = createToolLoopHarness(- createTestConfig("conversation", undefined, { onCompaction }),- );- const session = createTestSession({- history: [{ content: "old", kind: "user" as const, role: "user" }],- });-- const result = await runStep(session, { message: "Continue" });-- expect(onCompaction).toHaveBeenCalledTimes(1);- expect(result.session.history).toEqual([- { content: "Summary of our conversation so far:", kind: "context.compaction", role: "user" },- { content: "summary", role: "assistant" },- { content: "[State preserved]", kind: "context.state", role: "user" },- { content: "Resuming.", role: "assistant" },- ]);- });-it("compaction appends a framework continuation when recent window trails with assistant", async () => {// Step 1: tool call → harness continues (next === runStep).setupMockAgent({@@ -10594,26 +9826,6 @@ describe("createToolLoopHarness", () => {});});- it("does not call onCompaction when compaction does not trigger", async () => {- vi.mocked(shouldCompact).mockReturnValue(false);-- setupMockAgent({- finishReason: "stop",- response: { messages: [{ content: "Hello!", role: "assistant" }] },- text: "Hello!",- toolCalls: [],- toolResults: [],- });-- const onCompaction = vi.fn();- const runStep = createToolLoopHarness(- createTestConfig("conversation", undefined, { onCompaction }),- );- await runStep(createTestSession(), { message: "Hi" });-- expect(onCompaction).not.toHaveBeenCalled();- });-describe("prompt caching", () => {function setupStopResult(): void {setupMockAgent({diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex c1def1609..8f404a943 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -71,7 +71,6 @@ import {type UnstampedMessageStreamEvent,} from "#protocol/message.js";import type { RuntimeTraceContext } from "#protocol/message.js";-import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { projectParkedAgentHandles, resolveAgentsAnnouncement } from "#subagents/handles/prompt.js";import { getAgentHandleStore } from "#subagents/handles/store.js";@@ -111,10 +110,7 @@ import {isHarnessBetweenTurns,setHarnessEmissionState,} from "#harness/emission.js";-import {- extractQuestionInputRequests,- extractToolApprovalInputRequests,-} from "#harness/input-extraction.js";+import { extractToolApprovalInputRequests } from "#harness/input-extraction.js";import {renderPendingApprovalsInstruction,renderPendingApprovalsSnippet,@@ -633,7 +629,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {historyProjector: config.historyProjector,messages: [...session.history],model: resolvedModel.model,- onCompaction: config.onCompaction,requestEnvelopeTokens: getRequestEnvelopeTokens(session),resolveModel: config.resolveModel,runtimeIdentity: config.runtimeIdentity,@@ -687,7 +682,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {pendingRequestIds,stepInput: stepInput.input,}),- tools: config.tools,});const effectiveStepInput = staleConversion.stepInput;const preambleStepInput =@@ -1393,7 +1387,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const flatTools = await buildToolSetWithProviderTools({approvedTools,backgroundBatch,- capabilities: config.capabilities,disabledProviderTools: opts.disabledProviderTools,modelReference: requireSessionModelReference(session),tools: advertisedHarnessTools,@@ -1407,7 +1400,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const dynamicToolSet = buildToolSetFromDefinitions({approvedTools,backgroundBatch,- capabilities: config.capabilities,disabledProviderTools: opts.disabledProviderTools,tools: dynamicTools,});@@ -1480,7 +1472,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {historyProjector: config.historyProjector,messages: [...messages],model,- onCompaction: config.onCompaction,promptMessages: createModelMessages(messages),requestEnvelopeTokens,resolveModel: config.resolveModel,@@ -1626,7 +1617,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {).map(([name]) => name);const excludedActionToolNames = new Set([- ASK_QUESTION_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME,...hiddenRuntimeActionToolNames,]);@@ -2633,13 +2623,7 @@ async function handleStepResult(input: {content: result.content ?? [],excludedCallIds: invalidInputToolCallIds,});- const approvalRequestCallIds = new Set(approvalRequests.map((request) => request.action.callId));- const questionRequests = extractQuestionInputRequests({- toolCalls: result.toolCalls,- excludedCallIds: new Set([...invalidInputToolCallIds, ...approvalRequestCallIds]),- tools: input.coordinationTools,- });- const inputRequests: InputRequest[] = [...approvalRequests, ...questionRequests];+ const inputRequests: InputRequest[] = approvalRequests;const pendingApprovals = renderPendingApprovalsSnippet(approvalRequests);// Keep outcomes from resumed work ahead of the framework pending-approval// message; only the unresolved assistant response belongs to the parked batch.@@ -3193,7 +3177,6 @@ async function maybeCompact(input: {readonly historyProjector?: HistoryViewProjector;readonly messages: HarnessModelMessage[];readonly model: LanguageModel;- readonly onCompaction?: ToolLoopHarnessConfig["onCompaction"];/** Model-visible prompt used only to decide whether durable history needs compaction. */readonly promptMessages?: readonly HarnessModelMessage[];readonly requestEnvelopeTokens?: number;@@ -3306,12 +3289,6 @@ async function maybeCompact(input: {: [...ordinary];messages = validateHarnessModelMessages([...canonical.memory, ...compactedOrdinary]);- if (input.onCompaction) {- for (const msg of input.onCompaction()) {- messages.push(msg);- }- }-if (emit) {const ctx = contextStorage.getStore();if (ctx !== undefined) {diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.tsindex 98025e864..43522659d 100644--- a/packages/eve/src/harness/tools.test.ts+++ b/packages/eve/src/harness/tools.test.ts@@ -393,18 +393,18 @@ describe("buildToolSet", () => {} satisfies JSONSchema7;const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([[- "ask_question",+ "pick_color",{- description: "Ask the user a question.",+ description: "Let the client pick a color.",inputSchema: jsonSchema(schema),- name: "ask_question",+ name: "pick_color",},],]);- const result = buildToolSet({ capabilities: { requestInput: true }, tools });+ const result = buildToolSet({ tools });- expect(getJsonSchema(result.ask_question)).toEqual(schema);+ expect(getJsonSchema(result.pick_color)).toEqual(schema);});it("omits tools whose name is in disabledProviderTools", () => {@@ -567,32 +567,6 @@ describe("buildToolSet", () => {expect(result.web_search).toBeUndefined();});- it("omits ask_question when the session cannot request input", () => {- const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([- [- "ask_question",- {- behavior: {- availability: ["requires-request-input"],- handling: { kind: "request-input", request: "question" },- },- description: "Ask the user a question.",- inputSchema: jsonSchema({}),- name: "ask_question",- },- ],- ]);-- const withoutCapability = buildToolSet({ tools });- const withCapability = buildToolSet({- capabilities: { requestInput: true },- tools,- });-- expect(withoutCapability.ask_question).toBeUndefined();- expect(withCapability.ask_question).toBeDefined();- });-it("defaults to no approval when no approval function is set", async () => {const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([[diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.tsindex e849a91d3..adbcc7dac 100644--- a/packages/eve/src/harness/tools.ts+++ b/packages/eve/src/harness/tools.ts@@ -1,6 +1,5 @@import { type ToolApprovalConfiguration, type ToolApprovalStatus, type ToolSet, tool } from "ai";-import type { SessionCapabilities } from "#channel/types.js";import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";import { isObject } from "#shared/guards.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";@@ -39,11 +38,6 @@ const toolApprovals = new WeakMap<* Tools without `execute` are surfaced to the model as client-side tools* (no server execution).*- * The framework's `ask_question` tool is only exposed to the model when- * {@link SessionCapabilities.requestInput} is `true`. Sessions without- * the HITL capability (scheduled task roots and any subagent chain- * descending from one) never see the tool.- ** Entries listed in `disabledProviderTools` are skipped entirely. Used* by the harness recovery path when a gateway fallback provider has* rejected a provider-specific tool — the tool is dropped for the@@ -52,23 +46,14 @@ const toolApprovals = new WeakMap<export function buildToolSet(input: {readonly approvedTools?: ReadonlySet<string>;readonly backgroundBatch?: BackgroundToolCallBatch;- readonly capabilities?: SessionCapabilities;readonly disabledProviderTools?: ReadonlySet<string>;readonly tools: HarnessToolMap;}): ToolSet {const tools: Record<string, ToolSet[string]> = {};const backgroundBatch = input.backgroundBatch ?? createBackgroundToolCallBatch();- const canRequestInput = input.capabilities?.requestInput === true;const disabled = input.disabledProviderTools;for (const definition of input.tools.values()) {- if (- definition.behavior?.availability.includes("requires-request-input") === true &&- !canRequestInput- ) {- continue;- }-if (disabled?.has(definition.name)) {continue;}@@ -187,7 +172,6 @@ function requireBackgroundWorkflowId(definition: HarnessToolDefinition): stringexport function buildToolSetFromDefinitions(input: {readonly approvedTools?: ReadonlySet<string>;readonly backgroundBatch?: BackgroundToolCallBatch;- readonly capabilities?: SessionCapabilities;readonly disabledProviderTools?: ReadonlySet<string>;readonly tools: readonly HarnessToolDefinition[];}): ToolSet {@@ -200,7 +184,6 @@ export function buildToolSetFromDefinitions(input: {return buildToolSet({approvedTools: input.approvedTools,backgroundBatch: input.backgroundBatch,- capabilities: input.capabilities,disabledProviderTools: input.disabledProviderTools,tools,});@@ -301,7 +284,6 @@ function normalizeToolExecuteOutput(export async function buildToolSetWithProviderTools(input: {readonly approvedTools?: ReadonlySet<string>;readonly backgroundBatch?: BackgroundToolCallBatch;- readonly capabilities?: SessionCapabilities;readonly disabledProviderTools?: ReadonlySet<string>;readonly modelReference: RuntimeModelReference;readonly tools: HarnessToolMap;@@ -311,7 +293,6 @@ export async function buildToolSetWithProviderTools(input: {...buildToolSet({approvedTools: input.approvedTools,backgroundBatch: input.backgroundBatch,- capabilities: input.capabilities,disabledProviderTools: disabled,tools: input.tools,}),diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex 6facf3842..9b29934ca 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -279,8 +279,8 @@ export interface ToolLoopHarnessConfig {readonly abortSignal?: AbortSignal;/*** Session-level capabilities. The harness reads- * {@link SessionCapabilities.requestInput} when assembling the- * per-step toolset to decide whether `ask_question` is available.+ * {@link SessionCapabilities.requestInput} to decide whether a session-limit+ * continuation prompt may park a task-mode session.*/readonly capabilities?: SessionCapabilities;/** Clears model-message history without running a model turn. */@@ -307,13 +307,6 @@ export interface ToolLoopHarnessConfig {readonly mode: RunMode;/** Whether this node enables framework background-task behavior. */readonly tasksEnabled?: boolean;- /**- * Called after compaction to let the execution layer re-apply- * framework-owned state preservation (read-before-write reset, todo- * re-injection). The harness appends the returned messages to the- * compacted history.- */- readonly onCompaction?: () => readonly HarnessModelMessage[];/** Resolves persisted step-scoped tools before an approval policy reads them. */readonly resolveStepDynamicTools?: (input: {readonly ctx: AlsContext;diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.tsindex b7b47b904..b7d0247c7 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts@@ -132,11 +132,7 @@ export function normalizeToolDefinition(value: unknown, message: string): Normalconst behavior = readToolBehavior(value);const workflowProgram = readWorkflowProgramOptions(value);const hasExecute = record.execute !== undefined;- if (- !hasExecute &&- behavior?.handling?.kind !== "dispatch" &&- behavior?.handling?.kind !== "request-input"- ) {+ if (!hasExecute && behavior?.handling?.kind !== "dispatch") {expectFunction(record.execute, message);}const definition: MutableNormalizedAuthoredTool = {diff --git a/packages/eve/src/internal/invocation/mcp-agent-channel.scenario.test.ts b/packages/eve/src/internal/invocation/mcp-agent-channel.scenario.test.tsindex edc7f57c3..485b82ec6 100644--- a/packages/eve/src/internal/invocation/mcp-agent-channel.scenario.test.ts+++ b/packages/eve/src/internal/invocation/mcp-agent-channel.scenario.test.ts@@ -27,8 +27,11 @@ const model = mockModel((request) => {toolCalls: [{id: "question-1",input: {- options: [{ id: "yes", label: "Yes" }, { id: "no", label: "No" }],- prompt: "Proceed with the delegated work?",+ options: [+ { description: "Continue the delegated work.", label: "Yes" },+ { description: "Stop before the delegated work.", label: "No" },+ ],+ question: "Proceed with the delegated work?",},name: "ask_question",}],@@ -55,6 +58,10 @@ export default mcpChannel({});`,"agent/instructions.md": "Follow the deterministic mock-model lifecycle.\n",+ "agent/tools/ask_question.ts": `import { askQuestion } from "eve/tools/ask_question";++export default askQuestion();+`,},installDependencies: true,name: "mcp-agent-channel",@@ -85,7 +92,7 @@ describe("MCP agent channel", () => {});expect(hidden.isError).toBe(true);- const responses = [{ optionId: "yes", requestId }];+ const responses = [{ optionId: "Yes", requestId }];await expect(callTool(server.url, "alice", "modern", "agent_update", {invocationId,diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.tsindex fd450425f..25cbb028d 100644--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts@@ -124,7 +124,6 @@ describe("buildAgentInfoResponse", () => {expect(response.kernelEffects).toEqual(expect.arrayContaining([- expect.objectContaining({ kind: "request-input" }),expect.objectContaining({ action: "subagent-call", kind: "dispatch" }),]),);diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.tsindex 495b3ce1c..142a7038a 100644--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts@@ -440,13 +440,6 @@ function projectPreparedKernelEffects(sourceId: tool.sourceId,});break;- case "request-input":- effects.push({- audience: [...behavior.availability],- kind: "request-input",- sourceId: tool.sourceId,- });- break;case "workflow-tool":effects.push({action: "workflow-tool-call",diff --git a/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts b/packages/eve/src/internal/testing/scenario-apps/tool-overrides.tsindex 4557bcf52..a90776255 100644--- a/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts+++ b/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts@@ -2,7 +2,7 @@ import type { ScenarioAppDescriptor } from "#internal/testing/scenario-app.js";/*** Scenario-tier descriptor exercising every framework-tool override pattern:- * wrap (`bash`), replace (`todo`), and disable (`agent`, `web_fetch`, `web_search`).+ * wrap (`bash`), replace (`write_file`), and disable (`agent`, `web_fetch`, `web_search`).* The compile pipeline must preserve the override semantics end-to-end.*/export const TOOL_OVERRIDES_DESCRIPTOR: ScenarioAppDescriptor = {@@ -41,7 +41,7 @@ export default defineTool({},});`,- "agent/tools/todo.ts": `import { defineState } from "eve/context";+ "agent/tools/write_file.ts": `import { defineState } from "eve/context";import { defineTool } from "eve/tools";import { z } from "zod";diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.tsindex 86a37d348..0dc97cd38 100644--- a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts@@ -139,7 +139,8 @@ export async function* confirmDeployWorkflow(prompt: `Apply ${plan}?`,});yield "approval received";- return { approved: answer.optionId === "approve", service: input.service };+ const approved = answer.status === "answered" && answer.optionId === "approve";+ return { approved, service: input.service };}export async function failingDeployWorkflow(input: DeployInput): Promise<never> {diff --git a/packages/eve/src/public/tools/ask-question.ts b/packages/eve/src/public/tools/ask-question.tsindex 6ca4341cc..19fa21aca 100644--- a/packages/eve/src/public/tools/ask-question.ts+++ b/packages/eve/src/public/tools/ask-question.ts@@ -1 +1,5 @@-export { askQuestion, askQuestion as default } from "#tools/framework/ask-question.js";+export {+ type AskQuestionInput,+ type AskQuestionOutput,+ askQuestion,+} from "#tools/provided/ask-question.js";diff --git a/packages/eve/src/public/tools/todo.ts b/packages/eve/src/public/tools/todo.tsdeleted file mode 100644index a4c805d57..000000000--- a/packages/eve/src/public/tools/todo.ts+++ /dev/null@@ -1,5 +0,0 @@-import todoDefinition from "#tools/provided/todo.js";--export { todo } from "#tools/provided/todo.js";--export default todoDefinition;diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts b/packages/eve/src/runtime/agent/mock-model-adapter.test.tsindex 7485340bf..d06c77751 100644--- a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts+++ b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts@@ -296,14 +296,14 @@ describe("createMockAuthoredRuntimeModel", () => {]);});- it("builds ask_question input from prompt text and option labels", async () => {+ it("builds ask_question input from question text and option labels", async () => {const result = await generateWithPrompt([{content: ["Use the ask_question tool exactly once.",- "Set prompt to: 'Pick a color.'",- 'Provide exactly two options: - id "red", label "Red" - id "blue", label "Blue"',+ "Set question to: 'Pick a color.'",+ 'Provide exactly two options: label "Red" and label "Blue".',].join("\n"),role: "user",},@@ -312,9 +312,8 @@ describe("createMockAuthoredRuntimeModel", () => {{inputSchema: {properties: {- allowFreeform: { type: "boolean" },options: { type: "array" },- prompt: { type: "string" },+ question: { type: "string" },},type: "object",},@@ -328,10 +327,10 @@ describe("createMockAuthoredRuntimeModel", () => {expect(result.content).toEqual([{input: JSON.stringify({- prompt: "Pick a color.",+ question: "Pick a color.",options: [- { id: "red", label: "Red" },- { id: "blue", label: "Blue" },+ { description: "Choose Red.", label: "Red" },+ { description: "Choose Blue.", label: "Blue" },],}),toolCallId: "call_ask_question",diff --git a/packages/eve/src/runtime/agent/mock-model-fixtures.ts b/packages/eve/src/runtime/agent/mock-model-fixtures.tsindex ec8378abd..c6eb87961 100644--- a/packages/eve/src/runtime/agent/mock-model-fixtures.ts+++ b/packages/eve/src/runtime/agent/mock-model-fixtures.ts@@ -19,8 +19,8 @@ export function createMockAuthoredToolInput(city: string,): Record<string, unknown> {const inputPropertyNames = getToolInputPropertyNames(tool.inputSchema);- if (tool.name === "ask_question" || hasProperties(inputPropertyNames, ["prompt", "options"])) {- return createAskQuestionInput(message);+ if (inputPropertyNames.includes("question")) {+ return createQuestionInput(message);}if (inputPropertyNames.includes("command")) {@@ -238,40 +238,24 @@ function hasDeclaredInputProperties(schema: unknown): boolean {return isRecord(schema) && isRecord(schema.properties);}-function hasProperties(actual: readonly string[], expected: readonly string[]): boolean {- return expected.every((property) => actual.includes(property));-}--function createAskQuestionInput(message: string): Record<string, unknown> {- const options = parseInputOptions(message);- const input: Record<string, unknown> = {- prompt: resolveQuestionPrompt(message),+function createQuestionInput(message: string): Record<string, unknown> {+ const labels = parseOptionLabels(message);+ return {+ question: resolveQuestionPrompt(message),+ ...(labels.length >= 2 && {+ options: labels.map((label) => ({ description: `Choose ${label}.`, label })),+ }),};-- if (options.length > 0) {- input.options = options;- }-- if (/\ballow\s*freeform\s+(?:to\s+)?true\b|\ballowfreeform\s+(?:to\s+)?true\b/iu.test(message)) {- input.allowFreeform = true;- }-- return input;}-function parseInputOptions(message: string): Array<{ id: string; label: string }> {- return [...message.matchAll(/\bid\b\s*:?\s*"([^"]+)"\s*,\s*label\b\s*:?\s*"([^"]+)"/giu)].map(- (match) => ({- id: match[1] ?? "",- label: match[2] ?? "",- }),- );+function parseOptionLabels(message: string): string[] {+ return [...message.matchAll(/\blabel\b\s*:?\s*"([^"]+)"/giu)].map((match) => match[1] ?? "");}function resolveQuestionPrompt(message: string): string {const quotedPrompt =- /\b(?:set\s+)?prompt\s+to:\s*'([^']+)'/iu.exec(message) ??- /\b(?:set\s+)?prompt\s+to:\s*"([^"]+)"/iu.exec(message);+ /\b(?:set\s+)?question\s+to:\s*'([^']+)'/iu.exec(message) ??+ /\b(?:set\s+)?question\s+to:\s*"([^"]+)"/iu.exec(message);if (quotedPrompt?.[1]) {return quotedPrompt[1].trim();}diff --git a/packages/eve/src/shared/input.ts b/packages/eve/src/shared/input.tsindex e248b0317..2d35b45ad 100644--- a/packages/eve/src/shared/input.ts+++ b/packages/eve/src/shared/input.ts@@ -7,12 +7,7 @@ import { runtimeToolCallActionRequestSchema } from "#shared/action-types.js";*/export type InputOption = z.infer<typeof inputOptionSchema>;-/**- * Zod schema for one input option.- *- * Includes descriptions because the `ask_question` tool input embeds this- * schema and exposes it directly to the model.- */+/** Zod schema for one input option. */export const inputOptionSchema = z.object({description: z.string().describe("Optional additional context for this option.").optional(),diff --git a/packages/eve/src/subagents/hitl-proxy.test.ts b/packages/eve/src/subagents/hitl-proxy.test.tsindex 25127cdb3..b295eb941 100644--- a/packages/eve/src/subagents/hitl-proxy.test.ts+++ b/packages/eve/src/subagents/hitl-proxy.test.ts@@ -257,3 +257,150 @@ describe("routeDeliverPayload", () => {expect(routed.parentAction).toEqual({ kind: "cancel-turn" });});});++describe("routeDeliverPayload message resolution", () => {+ function askSession(+ questions: ReadonlyArray<+ readonly [requestId: string, question: { allowFreeform?: boolean; dismissible?: boolean }]+ >,+ ): HarnessSession {+ let session = createSession();+ for (const [requestId, question] of questions) {+ session = upsertProxyInputRequests({+ entries: [+ [+ requestId,+ {+ answerHook: {+ question: {+ ...question,+ options: [+ { id: "1", label: "Staging" },+ { id: "2", label: "Production" },+ ],+ },+ runId: `run-${requestId}`,+ },+ childContinuationToken: `hook-${requestId}`,+ kind: "question",+ },+ ],+ ],+ forChildContinuationToken: `hook-${requestId}`,+ session,+ });+ }+ return session;+ }++ it("answers the only pending question with a matching option label", () => {+ const routed = routeDeliverPayload({+ payload: { message: "production" },+ resolveMessage: true,+ state: askSession([["ask-1", { dismissible: true }]]).state,+ });++ expect(routed.forSelf).toBeUndefined();+ expect(routed.forChildren).toMatchObject([+ {+ childContinuationToken: "hook-ask-1",+ payload: { inputResponses: [{ optionId: "2", requestId: "ask-1" }] },+ retireRequestIds: ["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,+ });++ expect(routed.forSelf).toBeUndefined();+ expect(routed.forChildren[0]?.payload.inputResponses).toEqual([+ { requestId: "ask-1", text: "Use the canary pool" },+ ]);+ });++ it("dismisses dismissible questions and keeps an unrelated message for the turn", () => {+ const routed = routeDeliverPayload({+ payload: { message: "Actually, check the logs first." },+ resolveMessage: true,+ state: askSession([+ ["ask-1", { dismissible: true }],+ ["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"],+ },+ ]);+ });++ it("does not answer a question while a subagent question is also pending", () => {+ const session = upsertProxyInputRequests({+ entries: [["child-ask", { childContinuationToken: "child-token", kind: "question" }]],+ forChildContinuationToken: "child-token",+ session: askSession([["ask-1", { allowFreeform: true, dismissible: true }]]),+ });+ const routed = routeDeliverPayload({+ payload: { message: "Use the canary pool" },+ resolveMessage: true,+ state: session.state,+ });++ expect(routed.forSelf).toEqual({ message: "Use the canary pool" });+ expect(routed.forChildren).toMatchObject([{ dismissedRequestIds: ["ask-1"] }]);+ });++ 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,+ });++ expect(routed.forSelf).toEqual({ message: "production" });+ expect(routed.forChildren).toEqual([]);+ });++ it("routes only the first answer when a payload repeats a request", () => {+ const routed = routeDeliverPayload({+ payload: {+ inputResponses: [+ { optionId: "1", requestId: "ask-1" },+ { optionId: "2", requestId: "ask-1" },+ ],+ },+ state: askSession([["ask-1", {}]]).state,+ });++ expect(routed.forChildren[0]?.payload.inputResponses).toEqual([+ { optionId: "1", requestId: "ask-1" },+ ]);+ });++ it("prefers explicit input responses over resolving the message", () => {+ const routed = routeDeliverPayload({+ payload: {+ inputResponses: [{ optionId: "1", requestId: "ask-1" }],+ message: "production",+ },+ resolveMessage: true,+ state: askSession([["ask-1", { dismissible: true }]]).state,+ });++ expect(routed.forSelf).toEqual({ message: "production" });+ expect(routed.forChildren[0]?.payload.inputResponses).toEqual([+ { optionId: "1", requestId: "ask-1" },+ ]);+ });+});diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.tsindex 3c48b9e32..bdc1cb15e 100644--- a/packages/eve/src/subagents/hitl-proxy.ts+++ b/packages/eve/src/subagents/hitl-proxy.ts@@ -14,6 +14,7 @@ import type { HarnessEmitFn, HarnessSession, SessionStateMap } from "#harness/tyimport { createInputRequestedEvent } from "#protocol/message.js";import type { RunMode } from "#shared/run-mode.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";// ---------------------------------------------------------------------------@@ -67,6 +68,8 @@ export interface RoutedChildDelivery {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[];@@ -91,6 +94,7 @@ interface ChildResponseBucket {readonly childContinuationToken: string;readonly childSessionInbox?: SessionInboxAddress;readonly childResponseUrl?: string;+ readonly dismissedRequestIds: string[];/** Parent-visible request IDs answered in this bucket. */readonly parentRequestIds: string[];readonly responses: InputResponse[];@@ -98,57 +102,86 @@ interface ChildResponseBucket {readonly taskId?: string;}-/** Splits a deliver payload into parent-local and proxied-child buckets. */+/**+ * Splits a deliver payload into parent-local and proxied-child buckets.+ *+ * 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.+ */export function routeDeliverPayload(input: {readonly allowRoute?: (requestId: string, route: ProxyInputRequest) => boolean;readonly payload: DeliverPayload;+ readonly resolveMessage?: boolean;readonly state: SessionStateMap | undefined;}): RoutedDeliverPayload {const entries = getProxyInputRequests(input.state);- const inputResponses = input.payload.inputResponses ?? [];+ const routable = (requestId: string, route: ProxyInputRequest | undefined) =>+ route !== undefined && input.allowRoute?.(requestId, route) !== false;+ const message = resolveMessageAgainstQuestions({+ enabled: input.resolveMessage === true,+ entries,+ payload: input.payload,+ routable,+ });+ const inputResponses = [...(input.payload.inputResponses ?? []), ...message.responses];const responsesByChild = new Map<string, ChildResponseBucket>();const unroutedResponses: InputResponse[] = [];let parentAction: RoutedDeliverPayload["parentAction"];+ const bucketFor = (route: ProxyInputRequest): ChildResponseBucket => {+ const bucketKey = [+ route.childContinuationToken,+ route.childSessionInbox?.sessionId ?? "",+ route.childResponseUrl ?? "local",+ route.taskId ?? "",+ ].join("\0");+ const existing = responsesByChild.get(bucketKey);+ if (existing !== undefined) return existing;+ const bucket: ChildResponseBucket = {+ childContinuationToken: route.childContinuationToken,+ dismissedRequestIds: [],+ 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 }),+ };+ responsesByChild.set(bucketKey, bucket);+ return bucket;+ };++ const routedRequestIds = new Set<string>();for (const response of inputResponses) {const route = entries.get(response.requestId);- if (route === undefined || input.allowRoute?.(response.requestId, route) === false) {+ if (route === undefined || !routable(response.requestId, route)) {unroutedResponses.push(response);continue;}+ // A request takes one answer; the first one in the payload wins.+ if (routedRequestIds.has(response.requestId)) continue;+ routedRequestIds.add(response.requestId);if (route.kind === "session-limit" && response.optionId === SESSION_LIMIT_STOP_OPTION_ID) {parentAction = { kind: "cancel-turn" };}- const bucketKey = [- route.childContinuationToken,- route.childSessionInbox?.sessionId ?? "",- route.childResponseUrl ?? "local",- route.taskId ?? "",- ].join("\0");- const existing = responsesByChild.get(bucketKey);+ const bucket = bucketFor(route);+ bucket.parentRequestIds.push(response.requestId);+ bucket.responses.push(toChildInputResponse(response, route));+ bucket.routes.push(route);+ }- if (existing === undefined) {- responsesByChild.set(bucketKey, {- childContinuationToken: route.childContinuationToken,- parentRequestIds: [response.requestId],- responses: [toChildInputResponse(response, route)],- routes: [route],- ...(route.childSessionInbox !== undefined && {- childSessionInbox: route.childSessionInbox,- }),- ...(route.answerHook !== undefined && { answerHook: route.answerHook }),- ...(route.childResponseUrl !== undefined && { childResponseUrl: route.childResponseUrl }),- ...(route.taskId !== undefined && { taskId: route.taskId }),- });- } else {- existing.parentRequestIds.push(response.requestId);- existing.responses.push(toChildInputResponse(response, route));- existing.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(@@ -157,13 +190,14 @@ export function routeDeliverPayload(input: {childContinuationToken,childSessionInbox,childResponseUrl,+ dismissedRequestIds,parentRequestIds,responses,routes,taskId,}): RoutedChildDelivery => {const responseIds = new Set(parentRequestIds);- const retireRequestIds = new Set(responseIds);+ const retireRequestIds = new Set([...responseIds, ...dismissedRequestIds]);// A fully-answered approval batch retires its sibling requests// too, so a late free-form answer cannot route through a stale@@ -181,6 +215,7 @@ export function routeDeliverPayload(input: {childContinuationToken,payload: { inputResponses: responses },retireRequestIds: [...retireRequestIds],+ ...(dismissedRequestIds.length > 0 && { dismissedRequestIds }),...(childSessionInbox !== undefined && { childSessionInbox }),...(answerHook !== undefined && { answerHook }),...(childResponseUrl !== undefined && { childResponseUrl }),@@ -198,6 +233,7 @@ export function routeDeliverPayload(input: {if (key === "inputResponses" || value === undefined) {continue;}+ if (key === "message" && message.consumed) continue;remainder[key] = value;}@@ -211,6 +247,48 @@ export function routeDeliverPayload(input: {return { forChildren, forSelf, parentAction };}+function resolveMessageAgainstQuestions(input: {+ readonly enabled: boolean;+ readonly entries: ReadonlyMap<string, ProxyInputRequest>;+ readonly payload: DeliverPayload;+ readonly routable: (requestId: string, route: ProxyInputRequest) => boolean;+}): {+ readonly consumed: boolean;+ readonly dismissedRequestIds: readonly string[];+ readonly responses: readonly InputResponse[];+} {+ const none = { consumed: false, dismissedRequestIds: [], 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+ // 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;+ return question !== undefined ? [{ requestId, ...question }] : [];+ });+ if (questions.length === 0) return none;++ const [only] = questions;+ const answer =+ 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: [],+ };+}+function batchResolves(input: {readonly batch: NonNullable<ProxyInputRequest["batch"]>;readonly childContinuationToken: string;diff --git a/packages/eve/src/tools/behavior.ts b/packages/eve/src/tools/behavior.tsindex e4bc11b59..ded50bfb7 100644--- a/packages/eve/src/tools/behavior.ts+++ b/packages/eve/src/tools/behavior.ts@@ -1,16 +1,12 @@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"- | "requires-request-input"- | "root-session";+export type ToolAvailabilityCondition = "delegated-task-child" | "root-session";/** Native behavior declared by a selected compiled tool. */export type CompiledToolHandling =| { readonly kind: "dispatch"; readonly action: "self-agent" | "task-cancel" }| { readonly kind: "provider-tool"; readonly provider: WebSearchProvider }- | { readonly kind: "request-input"; readonly request: "question" }| { readonly kind: "workflow-tool"; readonly workflowId: string };/** Closed, serializable behavior carried by one selected compiled tool. */@@ -49,7 +45,7 @@ export type PreparedDispatchTarget =/** Runtime-prepared handling consumed by the harness and execution boundary. */export type PreparedToolHandling =| { readonly kind: "dispatch"; readonly target: PreparedDispatchTarget }- | Extract<CompiledToolHandling, { readonly kind: "provider-tool" | "request-input" }>;+ | Extract<CompiledToolHandling, { readonly kind: "provider-tool" }>;/** Runtime-prepared behavior carried by one harness-visible tool. */export interface PreparedToolBehavior {diff --git a/packages/eve/src/tools/definition.ts b/packages/eve/src/tools/definition.tsindex 1109b64df..6083bed54 100644--- a/packages/eve/src/tools/definition.ts+++ b/packages/eve/src/tools/definition.ts@@ -112,8 +112,8 @@ export interface PublicToolDefinitionWithExecuteFn</*** A question a workflow tool asks the human on the session's channel, sent- * with `ctx.ask` from a `defineWorkflowTool` executor. Channels render it the way they render- * `ask_question` and tool approvals.+ * with `ctx.ask` from a `defineWorkflowTool` executor. Channels render it the+ * way they render tool approvals.*/export interface ToolInputRequest {/**@@ -121,6 +121,12 @@ 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. */@@ -128,13 +134,24 @@ export interface ToolInputRequest {readonly prompt: string;}-/** The human's answer to a {@link ToolInputRequest}. */-export interface ToolInputResponse {- /** The selected option's `id`, when the user picked one. */- readonly optionId?: string;- /** Free text, when the user typed an answer. */- readonly text?: string;-}+/**+ * 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.+ * - `unavailable`: the session cannot reach a human, such as a scheduled run,+ * so the request resolved immediately without being shown.+ */+export type ToolInputResponse =+ | {+ readonly status: "answered";+ /** The selected option's `id`, when the user picked one. */+ readonly optionId?: string;+ /** Free text, when the user typed an answer. */+ readonly text?: string;+ }+ | { readonly status: "dismissed" }+ | { readonly status: "unavailable" };/*** Authored tool context. Passed as the last argument todiff --git a/packages/eve/src/tools/framework/ask-question.test.ts b/packages/eve/src/tools/framework/ask-question.test.tsdeleted file mode 100644index 844c865f0..000000000--- a/packages/eve/src/tools/framework/ask-question.test.ts+++ /dev/null@@ -1,54 +0,0 @@-import { describe, expect, it } from "vitest";--import { ASK_QUESTION_INPUT_SCHEMA, askQuestion } from "#tools/framework/ask-question.js";-import { serializeInputSchema } from "#tools/schema.js";--describe("ASK_QUESTION_INPUT_SCHEMA", () => {- it("is derived from the input request schema", () => {- expect(serializeInputSchema(ASK_QUESTION_INPUT_SCHEMA)).toEqual({- additionalProperties: false,- properties: {- allowFreeform: {- description:- "Whether the user may answer with freeform text instead of selecting one of the provided options.",- type: "boolean",- },- options: {- description: "Selectable answer options to present to the user.",- items: {- additionalProperties: false,- properties: {- description: {- description: "Optional additional context for this option.",- type: "string",- },- id: {- description: "Stable identifier for the option.",- type: "string",- },- label: {- description: "User-facing label for the option.",- type: "string",- },- style: {- description: "Visual treatment hint for the option.",- enum: ["primary", "danger", "default"],- type: "string",- },- },- required: ["id", "label"],- type: "object",- },- type: "array",- },- prompt: {- description: "The prompt to present to the user.",- type: "string",- },- },- required: ["prompt"],- type: "object",- });- expect(askQuestion.inputSchema).toBe(ASK_QUESTION_INPUT_SCHEMA);- });-});diff --git a/packages/eve/src/tools/framework/ask-question.ts b/packages/eve/src/tools/framework/ask-question.tsdeleted file mode 100644index a5a2f2251..000000000--- a/packages/eve/src/tools/framework/ask-question.ts+++ /dev/null@@ -1,32 +0,0 @@-import { z } from "#compiled/zod/index.js";-import { inputRequestSchema } from "#shared/input.js";-import { defineNativeTool } from "#tools/native-definition.js";--export const ASK_QUESTION_INPUT_SCHEMA = inputRequestSchema.omit({- action: true,- display: true,- kind: true,- requestId: true,-});-export const ASK_QUESTION_OUTPUT_SCHEMA = z- .object({- optionId: z.string().optional(),- status: z.enum(["answered", "ignored"]),- text: z.string().optional(),- })- .strict();--export const askQuestion = defineNativeTool(- {- description:- "Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.",- inputSchema: ASK_QUESTION_INPUT_SCHEMA,- outputSchema: ASK_QUESTION_OUTPUT_SCHEMA,- },- {- availability: ["requires-request-input"],- handling: { kind: "request-input", request: "question" },- },-);--export default askQuestion;diff --git a/packages/eve/src/tools/provided/ask-question.test.ts b/packages/eve/src/tools/provided/ask-question.test.tsnew file mode 100644index 000000000..667e11d9f--- /dev/null+++ b/packages/eve/src/tools/provided/ask-question.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it, vi } from "vitest";++import {+ ASK_QUESTION_INPUT_SCHEMA,+ ASK_QUESTION_TOOL_DESCRIPTION,+} from "#execution/tools/ask-question.js";+import {+ toAskQuestionOutput,+ toAskQuestionRequest,+} from "#execution/tools/ask-question-workflow.js";+import { askQuestion } from "#tools/provided/ask-question.js";+import { isWorkflowToolDefinition } from "#tools/workflow-definition.js";++const colorQuestion = {+ options: [+ { description: "Warm and bold.", label: "Red (Recommended)" },+ { description: "Calm and cool.", label: "Blue" },+ ],+ question: "Which color should the banner use?",+};++describe("askQuestion", () => {+ it("defines a blocking workflow tool that asks through ctx.ask()", async () => {+ const definition = askQuestion();+ const ask = vi.fn().mockResolvedValue({ optionId: "Blue", status: "answered" });++ expect(isWorkflowToolDefinition(definition)).toBe(true);+ expect(definition.description).toBe(ASK_QUESTION_TOOL_DESCRIPTION);+ await expect(definition.execute(colorQuestion, { ask } as never)).resolves.toEqual({+ answer: "Blue",+ status: "answered",+ });+ expect(ask).toHaveBeenCalledExactlyOnceWith(toAskQuestionRequest(colorQuestion));+ });++ it("accepts one question with at most three label and description options", () => {+ expect(ASK_QUESTION_INPUT_SCHEMA.safeParse(colorQuestion).success).toBe(true);+ expect(+ ASK_QUESTION_INPUT_SCHEMA.safeParse({ question: "What should we call it?" }).success,+ ).toBe(true);+ expect(+ ASK_QUESTION_INPUT_SCHEMA.safeParse({+ options: [colorQuestion.options[0]],+ question: "Only one choice?",+ }).success,+ ).toBe(false);+ expect(+ ASK_QUESTION_INPUT_SCHEMA.safeParse({+ options: [...colorQuestion.options, ...colorQuestion.options],+ question: "Too many choices?",+ }).success,+ ).toBe(false);+ expect(+ ASK_QUESTION_INPUT_SCHEMA.safeParse({+ options: colorQuestion.options.map((option, index) => ({ ...option, id: `${index}` })),+ question: colorQuestion.question,+ }).success,+ ).toBe(false);+ expect(+ ASK_QUESTION_INPUT_SCHEMA.safeParse({ ...colorQuestion, questions: [colorQuestion] }).success,+ ).toBe(false);+ expect(+ ASK_QUESTION_INPUT_SCHEMA.safeParse({+ options: [colorQuestion.options[1], colorQuestion.options[1]],+ question: "Blue or blue?",+ }).success,+ ).toBe(false);+ });+});++describe("toAskQuestionRequest", () => {+ it("always allows free text and lets the user move on", () => {+ expect(toAskQuestionRequest(colorQuestion)).toEqual({+ allowFreeform: true,+ dismissible: true,+ display: "select",+ options: [+ { description: "Warm and bold.", id: "Red (Recommended)", label: "Red (Recommended)" },+ { description: "Calm and cool.", id: "Blue", label: "Blue" },+ ],+ prompt: "Which color should the banner use?",+ });+ expect(toAskQuestionRequest({ question: "What should we call it?" })).toEqual({+ allowFreeform: true,+ dismissible: true,+ display: "text",+ prompt: "What should we call it?",+ });+ });+});++describe("toAskQuestionOutput", () => {+ it("returns the chosen label or the user's own words", () => {+ expect(toAskQuestionOutput({ optionId: "Red (Recommended)", status: "answered" })).toEqual({+ answer: "Red (Recommended)",+ status: "answered",+ });+ expect(toAskQuestionOutput({ status: "answered", text: "Green" })).toEqual({+ answer: "Green",+ status: "answered",+ });+ });++ it("passes through dismissed and unavailable answers", () => {+ expect(toAskQuestionOutput({ status: "dismissed" })).toEqual({+ status: "dismissed",+ });+ 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.tsnew file mode 100644index 000000000..b94ebf8c6--- /dev/null+++ b/packages/eve/src/tools/provided/ask-question.ts@@ -0,0 +1,34 @@+import { defineWorkflowTool, type WorkflowToolDefinition } from "#tools/workflow-definition.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";++export type { AskQuestionInput, AskQuestionOutput };++/**+ * Defines the opt-in `ask_question` tool.+ *+ * Export it from `agent/tools/ask_question.ts`:+ *+ * ```ts+ * import { askQuestion } from "eve/tools/ask_question";+ *+ * export default askQuestion();+ * ```+ *+ * 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.+ */+export function askQuestion(): WorkflowToolDefinition<AskQuestionInput, AskQuestionOutput> {+ return defineWorkflowTool({+ description: ASK_QUESTION_TOOL_DESCRIPTION,+ execute: executeAskQuestionTool,+ inputSchema: ASK_QUESTION_INPUT_SCHEMA,+ outputSchema: ASK_QUESTION_OUTPUT_SCHEMA,+ });+}diff --git a/packages/eve/src/tools/provided/sleep.ts b/packages/eve/src/tools/provided/sleep.tsindex 684862476..3e83e6fdc 100644--- a/packages/eve/src/tools/provided/sleep.ts+++ b/packages/eve/src/tools/provided/sleep.ts@@ -1,7 +1,4 @@-import {- defineWorkflowTool,- type BlockingWorkflowToolDefinition,-} from "#tools/workflow-definition.js";+import { defineWorkflowTool, type WorkflowToolDefinition } from "#tools/workflow-definition.js";import {executeSleepTool,SLEEP_INPUT_SCHEMA,@@ -27,7 +24,7 @@ export type { SleepToolInput, SleepToolOutput };* Each call runs as a durable workflow, so the wait does not hold an* application runtime open.*/-export function sleep(): BlockingWorkflowToolDefinition<SleepToolInput, SleepToolOutput> {+export function sleep(): WorkflowToolDefinition<SleepToolInput, SleepToolOutput> {return defineWorkflowTool({description: SLEEP_TOOL_DESCRIPTION,execute: executeSleepTool,diff --git a/packages/eve/src/tools/provided/todo.ts b/packages/eve/src/tools/provided/todo.tsdeleted file mode 100644index 180724527..000000000--- a/packages/eve/src/tools/provided/todo.ts+++ /dev/null@@ -1,36 +0,0 @@-import {- executeTodoTool,- TODO_INPUT_SCHEMA,- TODO_OUTPUT_SCHEMA,- type TodoToolInput,-} from "#execution/tools/todo.js";-import { defineTool } from "#tools/definition.js";--export const todo = defineTool({- description: [- "Use this tool to create and manage a structured task list for the current session.",- "This helps you track progress, organize complex tasks, and demonstrate thoroughness.",- "",- "When to use:",- "- Complex multistep tasks requiring 3 or more distinct steps",- "- When the user provides multiple tasks or a numbered list",- "- After receiving new instructions, to capture requirements",- "- After completing a task, to mark it complete and add follow-ups",- "",- "When NOT to use:",- "- Single, straightforward tasks that need no tracking",- "- Purely conversational or informational requests",- "",- "Usage:",- "- Call with `todos` to replace the entire list (full replacement write)",- "- Call without `todos` to read the current list",- "- Both return the full current list with status counts",- "- Mark tasks in_progress when you start, completed when done",- "- Only have ONE task in_progress at a time",- ].join("\n"),- execute: async (input) => executeTodoTool((input ?? {}) as TodoToolInput),- inputSchema: TODO_INPUT_SCHEMA,- outputSchema: TODO_OUTPUT_SCHEMA,-});--export default todo;diff --git a/packages/eve/test/file-tool-compaction.test.ts b/packages/eve/test/file-tool-compaction.test.tsdeleted file mode 100644index 9522afd07..000000000--- a/packages/eve/test/file-tool-compaction.test.ts+++ /dev/null@@ -1,135 +0,0 @@-import { describe, expect, it } from "vitest";--import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";--import { ContextContainer, contextStorage } from "../src/context/container.js";-import { SandboxKey } from "../src/context/keys.js";-import { executeReadFileOnSandbox } from "../src/execution/sandbox/read-file.js";-import type { SandboxAccess } from "../src/sandbox/state.js";-import type { SandboxSession } from "../src/shared/sandbox-session.js";-import { executeWriteFileOnSandbox } from "../src/execution/sandbox/write-file.js";-import { ReadFileStateKey } from "../src/execution/tools/file-state.js";-import { preserveFrameworkStateOnCompaction } from "../src/execution/compaction.js";--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------function createFakeAccess(files: Record<string, string>): {- access: SandboxAccess;- files: Record<string, string>;- session: SandboxSession;-} {- const session = {- id: "test-file-compaction-sandbox",- async readFile() {- return null;- },- async readBinaryFile() {- return null;- },- async readTextFile({ path }: { path: string }) {- return files[path] ?? null;- },- async setNetworkPolicy() {},- async removePath({ path }: { path: string }) {- delete files[path];- },- resolvePath(path: string) {- return path;- },- async run(_options: { command: string }) {- return { exitCode: 0, stderr: "", stdout: "" };- },- async spawn() {- return stubSpawnProcess();- },- async writeFile() {},- async writeBinaryFile() {},- async writeTextFile({ path, content }: { path: string; content: string }) {- files[path] = content;- },- } as SandboxSession;-- return {- access: {- async captureState() {- return { initialized: false, session: null };- },- async stop() {},- async get() {- return session;- },- },- files,- session,- };-}--// ----------------------------------------------------------------------------// Compaction tests-// -----------------------------------------------------------------------------describe("read_file compaction", () => {- it("preserveFrameworkStateOnCompaction() clears read-file state", () => {- const ctx = new ContextContainer();- ctx.set(ReadFileStateKey, {- byTarget: { "/workspace/foo.ts": {} as never },- });-- contextStorage.run(ctx, () => preserveFrameworkStateOnCompaction());-- const state = ctx.require(ReadFileStateKey);- expect(state.byTarget).toEqual({});- });-- it("after compaction, a previously read file must be read again before overwrite", async () => {- const { access, files, session } = createFakeAccess({- "/workspace/foo.ts": "original",- });-- const ctx = new ContextContainer();- ctx.set(SandboxKey, access);- ctx.set(ReadFileStateKey, { byTarget: {} });-- // Read the file first- await contextStorage.run(ctx, () =>- executeReadFileOnSandbox(session, { filePath: "/workspace/foo.ts" }),- );-- // Verify stamp exists- const stateBeforeCompaction = ctx.require(ReadFileStateKey);- expect(stateBeforeCompaction.byTarget["/workspace/foo.ts"]).toBeDefined();-- // Simulate compaction — the framework resets read-before-write tracking.- contextStorage.run(ctx, () => preserveFrameworkStateOnCompaction());-- // Verify stamp is gone- const stateAfterCompaction = ctx.require(ReadFileStateKey);- expect(stateAfterCompaction.byTarget["/workspace/foo.ts"]).toBeUndefined();-- // Write should now fail- await expect(- contextStorage.run(ctx, () =>- executeWriteFileOnSandbox(session, {- filePath: "/workspace/foo.ts",- content: "updated",- }),- ),- ).rejects.toThrow("You must read file /workspace/foo.ts before overwriting it.");-- // But writing still works after re-reading- await contextStorage.run(ctx, () =>- executeReadFileOnSandbox(session, { filePath: "/workspace/foo.ts" }),- );-- await contextStorage.run(ctx, () =>- executeWriteFileOnSandbox(session, {- filePath: "/workspace/foo.ts",- content: "updated after re-read",- }),- );-- expect(files["/workspace/foo.ts"]).toBe("updated after re-read");- });-});diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.tsindex 115e40218..f5e38ee67 100644--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts@@ -827,7 +827,7 @@ describe("compileAgent", () => {.sort(),).toEqual(["tools/agent.ts", "tools/web_fetch.ts", "tools/web_search.ts"]);- // Both the wrapped bash and the replacement todo land in `tools` as+ // Both the wrapped bash and the replacement write_file land in `tools` as// ordinary CompiledToolDefinitions. Disabled slots are absent from the// effective tool graph and retained only as composition diagnostics.const toolsByName = new Map(@@ -837,7 +837,7 @@ describe("compileAgent", () => {]),);- expect([...toolsByName.keys()].sort()).toEqual(["bash", "todo"]);+ expect([...toolsByName.keys()].sort()).toEqual(["bash", "write_file"]);expect(toolsByName.get("bash")).toMatchObject({description: "Run a vetted shell command in the project sandbox.",@@ -846,11 +846,11 @@ describe("compileAgent", () => {sourceId: "tools/bash.ts",sourceKind: "module",});- expect(toolsByName.get("todo")).toMatchObject({+ expect(toolsByName.get("write_file")).toMatchObject({description: "Append a note or read the running list of notes.",- logicalPath: "tools/todo.ts",- name: "todo",- sourceId: "tools/todo.ts",+ logicalPath: "tools/write_file.ts",+ name: "write_file",+ sourceId: "tools/write_file.ts",sourceKind: "module",});expect(result.diagnostics).toEqual([]);diff --git a/packages/eve/test/tui-client/tui-questions-freeform.ts b/packages/eve/test/tui-client/tui-questions-freeform.tsindex c37062cce..669a1f741 100644--- a/packages/eve/test/tui-client/tui-questions-freeform.ts+++ b/packages/eve/test/tui-client/tui-questions-freeform.ts@@ -9,7 +9,7 @@ import { theme } from "./lib/theme.ts";/*** Covers the freeform-via-arrow-nav UX. The model raises an- * `ask_question` with `allowFreeform: true` and a small set of+ * `ask_question`, which always accepts free text, with a small set of* predefined options. The TUI surfaces a navigable "Type your own* answer" row below the last option. Pressing Enter on that row* switches to text mode, and the typed reply is sent as `text` (not@@ -41,12 +41,8 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {const promptLines = ["Use the ask_question tool exactly once to ask me to choose an environment.",- "Set prompt to: 'Which environment?'",- "Set allowFreeform to true.",- "Provide exactly three options:",- `- id "prod", label "Production"`,- `- id "staging", label "Staging"`,- `- id "preview", label "Preview"`,+ "Set question to: 'Which environment?'",+ 'Provide exactly three options: label "Production", label "Staging", and label "Preview".',"Wait for my response. Then repeat back exactly what I said.",];input.type(promptLines.join(" · "));diff --git a/packages/eve/test/tui-client/tui-questions.ts b/packages/eve/test/tui-client/tui-questions.tsindex 85afd1044..00998c419 100644--- a/packages/eve/test/tui-client/tui-questions.ts+++ b/packages/eve/test/tui-client/tui-questions.ts@@ -17,7 +17,7 @@ import { theme } from "./lib/theme.ts";* 1. Start the apps/fixtures/agent-tui-client server.* 2. Boot an `EveTUIRunner` with a mock terminal.* 3. Type a prompt that asks the model to call `ask_question` with- * two options (red/blue).+ * two options (Red/Blue).* 4. Wait for the question overlay to display the numbered select* indicator (`› 1. <label>`), which proves the question UI is up.* 5. Send Down arrow + Enter to pick the second option (blue).@@ -27,8 +27,6 @@ import { theme } from "./lib/theme.ts";* flowed through to the agent and resolved the pending input.*/-const RED_ID = "red";-const BLUE_ID = "blue";process.env.EVE_TUI_UNICODE = "1";run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {@@ -53,10 +51,8 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {const promptLines = ["Use the ask_question tool exactly once to ask me which color I prefer.",- "Set prompt to: 'Pick a color.'",- "Provide exactly two options:",- `- id "${RED_ID}", label "Red"`,- `- id "${BLUE_ID}", label "Blue"`,+ "Set question to: 'Pick a color.'",+ 'Provide exactly two options: label "Red" and label "Blue".',"Wait for my response.",];input.type(promptLines.join(" · "));