The Open Framework for Building Agents
docs(research): plan eve tasks to replace background tasks (#3821)
Andrew Barba9772ab11e725
diff --git a/research/background-tasks-redesign.md b/research/background-tasks-redesign.mddeleted file mode 100644index 0f8411e37..000000000--- a/research/background-tasks-redesign.md+++ /dev/null@@ -1,426 +0,0 @@-----issue: https://github.com/vercel/eve/issues/1084-status: draft-last_updated: "2026-09-18"------# Background tasks: one workflow runtime--**Prototype result: background work is a session-owned workflow tool run.** Waiting and-background tools now enter through one durable workflow kind, use one session invocation registry,-and share body execution, report drainage, and cancellation cleanup. The parent session retains-task outcomes, pending input routes, child ownership, and accounting. The background owner handles-admission and routes child messages through the existing session inbox.--This prototype is based on `32aca9b1485ce8fce0eb9c636d741456c1779f25`. The linked, closed issue-is provenance only. The branch is an investigation, not a production-ready migration.--## Approved decisions--The prototype implements three approved scope decisions:--1. Authored background work uses `defineWorkflowTool({ execution: "background" })`.- `defineTool` and dynamic tools no longer accept background execution.-2. The authored `TaskExec` third argument, `TaskMessage`, `task.postMessage`, and deprecated task- fields are removed. Background workflow yields are consumed without a task-progress stream; `ctx.ask`, authorization, and- framework-owned workflow requests remain.-3. Completed, failed, and cancelled outcomes wait for their existing session cohort and become one- automatic report, including all-failed and all-cancelled cohorts. Lifecycle state still updates- when each task settles. User input, human-input requests, and authorization do not wait for the- cohort.--## Resulting execution model--`workflowToolRunWorkflow` in `workflow.ts` is the durable entry and execution loop for both-modes. It starts `executeWorkflowBody`, owns the internal workflow inbox, reads commands and-requests, and drains every persisted report before emitting the outcome. Background work starts-only after `ready`; cancellation cleanup is bounded. [Shared workflow][prototype-invocation]--`workflow-owner-blocking.ts` routes messages to the waiting turn. `workflow-owner-background.ts`-handles task admission and routes messages through the parent session inbox. The parent records-task outcomes and pending input routes. Admitted background work survives the initiating turn.-[Blocking owner][prototype-blocking], [background owner][prototype-background]--Both paths use `deliverWorkflowAuthorization` to deliver or deliberately discard an authorization-event before acknowledging it. Only step-owned events receive that acknowledgement; forwarded-agent events retain their invocation reply channel. Blocking delivery completes after parent event-processing; background delivery completes when the parent inbox accepts the notification.-The background owner filters events after cancellation, allowing workflow authorization completion-to close a displayed prompt. Pending authorization attempts remain in the shared workflow step;-the background owner tracks only ordinary input requests for answer routing.--| Concern | Before | Prototype |-| ----------------------------------- | ---------------------------------------------------- | --------------------------------------------------- |-| Workflow-body execution owners | 2 direct callers of `executeWorkflowBody` | 1 shared invocation loop |-| Background executor implementations | Workflow body or inline `defineTool` body | Workflow body only |-| Durable workflow kinds | Foreground workflow-tool run and background task run | One workflow-tool run entry |-| Persistent records | Separate workflow-tool-run and task registries | One invocation registry, with task payloads |-| Authored background protocols | Return/yield plus `TaskExec`/`TaskMessage` | Return/yield plus workflow context |-| Terminal report classifier | Successful `:ready:completed` delivery ID suffix | Stable terminal delivery ID, retained after routing |--A task is the public handle for an admitted session-owned invocation. Both lifetimes now live in-`eve.workflowTool` as `{ version: 3, runs: WorkflowToolRun[] }`; task lookup and blocking-run lookup-are filtered views of that registry. Version 3 replaces the version-2 task-only index on main.-Cleanup selects the originating turn and `lifetime: "turn"`, so it cannot discard-session-owned work. [Registry][prototype-registry]--## Shared state and retention--Store invocation identity and ownership once; keep task-specific behavior in a typed `task` payload.-The identity is `(origin.turnId, callId)` within the owning session. `taskId` remains the public task-handle. No additional invocation ID or generic extension system is introduced.--```ts-type WorkflowToolRun = {- callId: string;- toolName: string;- origin: { turnId: string; stepIndex: number };- address: { runId: string; hookToken: string };-} & (- | { lifetime: "turn" }- | {- lifetime: "session";- task: {- taskId: string;- metadata: TaskMetadata;- dispatchContext: TaskAgentDispatchContext;- activityWorkIdentity?: ActivityWorkIdentityV1;- cohortId?: string;- outcome?: TaskOutcome;- };- }-);-```--`WorkflowToolRun` has `BlockingWorkflowToolRun` and `BackgroundWorkflowToolRun` variants;-`WorkflowTaskPayload` holds the background task fields. `TaskAgentDispatchContext`-captures the creator's authentication and dynamic subagent selections; it must not be replaced-with the authentication of a later input delivery. `TaskMetadata` describes the public task,-`ActivityWorkIdentityV1` links its activity stream, and `TaskView` is its public status/output view.-`cohortId` groups overlapping work for one combined report.--| State | Owner and lifetime |-| ------------------------------------------------- | --------------------------------------------------------------------------------------------------- |-| Common identity, origin, run address | Session registry; waiting entries are removed when their call settles or their turn is cancelled |-| Task metadata, creator context, cohort membership | Typed task payload; retained for the session lifetime |-| Pending questions | Parent session proxy-input state |-| Final task status and output | Parent-owned `task.outcome`; retained for the session lifetime, including after the combined report |-| Pending deliveries and report deduplication | Existing session input queue |--Registration precedes the `ready` admission command. A waiting outcome is matched against its-originating turn, call ID, and run ID. Authorization can end the visible turn while its workflow-call remains pending; cancellation uses the pending coordination batch's originating turn in that-case. Results without an origin can bind only to an unambiguous recorded call. Replaying-registration preserves original creator context,-cohort membership, and any recorded terminal outcome. Reusing a task ID for another turn is rejected.--**Retention decision:** completed, failed, and cancelled task payloads stay until the session ends.-Report delivery does not prune them. This avoids a second cleanup protocol for now; retained state-therefore grows with task count and final output size. Live progress is not copied into this registry.--## What was eliminated--The prototype deletes these responsibilities rather than renaming them:--- Parent-step execution of ordinary background tool bodies, async-iterable drainage, authorization- return handling, and final task-command delivery.-- Lifecycle-only task runs with no workflow body and the optional no-body branch in- the background workflow input.-- Two `TaskExec` constructors, `TaskMessage` detection, message buffering, and the dedicated- task-message parent wake step.-- Background dynamic-tool persistence and replay.-- Success-only cohort classification; all three terminal delivery suffixes now share the barrier.-- `TaskExecutorBinding`, the `bind` command, fixed executor tags, and the separate executor-run- cancellation lookup.-- The `taskRunWorkflow` durable entry and its stable workflow registration.-- Workflow-to-task outcome, progress, and question wrappers. The background owner consumes- workflow messages directly; only session delivery and public view projection adapt their shape.-- Pre-admission progress buffering: the workflow body cannot emit before `ready` starts it.-- The separate `eve.runtime.workflowToolRuns` store and independent task-index write path;- `eve.workflowTool` now holds both lifetimes without duplicate creation provenance or run addresses.--These responsibilities were retained or relocated:--- Body start, report drainage, cancellation cleanup, and final outcome construction live in the shared invocation loop.-- Admission, compensation, child reservation/claiming, steering, task cancellation, and session- indexing remain in the task owner.-- Waiting-run and task lookup remain filtered projections of the shared invocation registry.- The lifetime discriminator controls cleanup.-- The session input queue still buffers active-turn deliveries and performs cohort release.--## Size comparison--The reduction comes from deleting ordinary background executors, the authored task-message-protocol, executor bindings, duplicate message conversions, and their associated tests. Shared-ordering and cancellation tests exercise the real invocation and channel readers for both modes.--Measure the current patch with `git diff --numstat 32aca9b1485ce8fce0eb9c636d741456c1779f25`.-For production source, include `packages/eve/src/**` and exclude `*.test.ts` and-`src/internal/testing/**`. Report documentation, generated extension reports, test support,-and E2E fixtures separately. The PR description records the current diff totals.--## Observable semantics--Background authoring has one supported shape:--```ts-import { defineWorkflowTool } from "eve/tools";-import { z } from "zod";--export default defineWorkflowTool({- description: "Review a change in the background.",- execution: "background",- inputSchema: z.object({ request: z.string() }),- async *execute({ request }, ctx) {- "use workflow";- yield { phase: "reviewing" };- return await ctx.agent("reviewer", { message: request });- },-});-```--The original call receives `{ status: "working", taskId }` after admission. Progress yields update-the stream without starting a parent turn. `return` completes the task, an escaping error fails it,-and task cancellation remains final against a late successful invocation outcome.--A **cohort** is overlapping background work owned by one session. Existing membership is-preserved across overlapping turns. The automatic report becomes eligible only when every member-is terminal, and it contains success, failure, and cancellation payloads. A user message remains a-normal turn, and workflow input/authorization requests remain serviceable while a cohort is open.-Explicit cancellation checks the parent's recorded outcome before cancelling owned work. It records-cancellation when the control step returns and queues a settlement notification with the existing-delivery ID. Late child outcomes cannot replace that parent decision. Steering cancellation continues to mark-superseded task deliveries for suppression.--## Compatibility and migration--This is a breaking authoring change, so the prototype includes a minor changeset and updated public-docs. Extension capability generation records `tool` epoch 45 and `dynamicTool` epoch 42. Channel epoch 24 removes executor bindings from task views and drops epoch 23. The authoring change also-drops retained epochs that explicitly exercised the removed surfaces: tool epoch 28, dynamic-tool-epochs 28–30, and the previous current epochs 44 and 41.--Migrate an ordinary background definition by replacing `defineTool` with `defineWorkflowTool`,-adding `"use workflow"`, moving nondeterministic side effects into `"use step"` helpers, removing-the third executor argument, and replacing parent messages with progress or the final return value.-A dependency on an intermediate result belongs inside the owning workflow through `ctx.agent`,-`ctx.ask`, or another durable operation.--Existing sessions containing either old registry key are rejected by the new runtime. Conversation-import can stop discoverable old runs and retain conversation history, but does not migrate pending-work. Completed task payloads also require the new format before deployment handoff.--The cross-deployment checkpoint version is now **6**. Version 4 and 5 readers also enforce exact-version equality, so both old-to-new and new-to-old handoffs reject the incompatible checkpoint-before hydrating nested state or claiming session hooks. The original owner recovers its hooks-and processes the triggering message. This version boundary is necessary even for idle sessions:-an older reader could otherwise overlook the new registry key and lose retained task outputs.--Within version 6, unknown fields on the registry, invocation, origin, address, task payload, and-terminal output survive parsing, replayed registration, and terminal-cache updates. Authentication-and dispatch-context schemas remain strict; incompatible changes there require another checkpoint-version bump. Session turns execute on their owning deployment. Legacy import returns its prepared-conversation snapshot to the parked old driver, rather than exporting the new owner's registry.--These checks protect the handoff boundary; they do not migrate in-flight workflows. A rollout must-keep the original deployments available for retained sessions and old task runs, or drain them first.--## Demonstrated behavior--| Requirement | Evidence |-| ------------------------------------------------------------- | ----------------------------------------------------------------- |-| Waiting workflow completion, failure, and progress | Workflow integration suite |-| Background receipt before later completion | Workflow integration suite exercises both root and child owners |-| Commit before body start | Task-owner unit test starts the workflow body only after `ready` |-| Report before outcome | Shared invocation unit test and task-owner report/outcome test |-| Explicit cancellation wins over late completion | Background-owner tests and invocation-loop tests for both modes |-| Workflow human input and authorization routing | Workflow integration suite and task-owner authorization tests |-| Mixed success/failure and success/cancellation report | Session next-input unit tests |-| All-failed and all-cancelled report | Session next-input unit tests |-| Active parent does not steer on terminal failure/cancellation | Session input queue and active-turn unit tests |-| Duplicate terminal delivery | Existing session next-input deduplication unit test |-| Cross-turn cohort membership | Existing session next-input cross-turn unit test |-| Forced-stop cancellation notification | Cancellation integration test |-| Mixed invocation lifetimes and retained terminal payloads | Shared registry unit test and turn-cancellation integration tests |-| Completion after authorization ends the visible turn | Workflow authorization integration tests |-| Extension migration boundary | Generated capability reports and invariant guard |--Checks run before the checkpoint-version follow-up:--- Full unit tier: **799 files passed; 8,676 tests passed; 1 skipped**.-- Workflow/session integration slices: **7 files, 107 tests passed**, including authorization, handoff,- telemetry, forced-stop cancellation, and retention during active or paused turn cancellation.-- TypeScript `--noEmit`, fresh production TypeScript/Rolldown build, focused lint, formatting,- `git diff --check`, extension-contract generation, and `guard:invariants`: passed.-- Documentation frontmatter/navigation, import snippets, and MDX compilation: passed for all 89- published pages.--The checkpoint-version follow-up passed 101 focused unit tests and all 35 session-entry and-legacy-import integration tests, plus typechecking and a fresh production build. The integration-suite initially failed a compatible legacy handoff while a build ran concurrently; the complete-rerun and an isolated repeat of that handoff passed. Build interference is unconfirmed. The tests verify version rejection before nested-state reads, recovery without duplicate input, and preservation of additive invocation fields.--The normal package-manager wrapper remains unavailable in this checkout because the private-registry requires `SOCKET_PASSWORD_B64`. Dependencies were installed from the local store with a-frozen lockfile, and the underlying checks were invoked directly. No credential value was read or-printed. Local E2E was not run because the repository marks it CI-only.--## Correctness and entropy review--Admission starts an invocation; only its outcome settles running work. A duplicate `ready` after-cancellation previously set the settled flag and exited before cleanup messages were consumed.-That defect was carried through from the old task owner. Admission is now accepted once; rejection-before admission returns without starting the body. The regression test first failed after consuming-only three of six messages, then passed with cleanup acknowledged before terminal delivery.--The review also removed seven registry/type aliases and the task-index facade. Callers now use the-workflow tool run registry directly. Mutations reuse their parsed registry rather than reading it-again during the write, and replay registration merges common fields once. Persisted formats and-task-payload retention are unchanged by these corrections.--This pass ran the full unit suite (799 files, 8,678 passed, one skipped), then 51 focused tests-after the final registry and admission edits. All 64 integration tests across workflow execution,-background dispatch, cancellation, and approval passed on rerun. The progress-after-answer test-failed once before passing in isolation and in the full rerun; the cause remains unconfirmed, and-its assertion now includes captured events for diagnosis. Typechecking, production build, focused-lint, formatting, and invariant guards passed.--## Ownership and cancellation consolidation--Ownership reads no longer decode every retained result, and both invocation lifetimes share-cancellation escalation. The persisted registry is version 2 and checkpoints are version 6.--- Removed the unused coordination `pendingTasks` acknowledgement list. Real background admission- still persists ownership before sending `ready`.-- `settleWorkflowToolRunCancellation` owns polling and forced stop for both lifetimes. Body cleanup- retains its 30-second limit; callers allow 35 seconds for cleanup and outcome publication. This- replaces the task-specific one-second cutoff. The parent records cancellation after the control step finishes.-- Both child-owner paths use the same cancellation function and attempt every claimed child.- Turn cancellation starts child cancellation alongside workflow cancellation. Background child- failures remain retryable; all child requests settle before the helper returns or throws.-- Registry ownership and routing reads validate addresses, identity, and ownership metadata.- `readWorkflowTaskView` validates the selected retained result and its task identity when consumed.- A malformed old result cannot block cancelling an unrelated live invocation or removing a waiting- invocation. Handoff still validates every retained result, even when other work is pending.--Cohort membership, delivery eligibility, creator context, and session-lifetime retention are unchanged.-No corruption recovery or quarantine mechanism was added.--Validation: all 800 unit files passed (8,692 tests, one skipped), and 73 integration tests passed-across workflow execution, task dispatch, turn cancellation, forced-stop notification, and handoff.-After final helper changes, the 29 workflow/cancellation integration tests and five child-cancellation-unit tests passed again. Typechecking, production build, lint, formatting, invariant guards, and all-89 published-doc checks passed. The first unit run exposed a missing active-turn marker in the new-cancellation fixture; correcting the fixture made it exercise the intended path.--## Remaining proof gaps and migration risks--The prototype does not yet demonstrate these full boundaries:--- A live upgrade and rollback between actual released deployments. Version rejection and owner- recovery are tested locally; the old reader's version check was inspected in the base revision.--- An explicit initiating-turn cancellation racing after task admission while the background body- remains blocked. Ownership is unchanged and existing retention code covers this path, but the- exact combined prototype path lacks a dedicated test.-- One end-to-end model-call assertion that active-parent buffered terminal outcomes later become a- single report. The tests separately prove active buffering and parked cohort release.-- Parent-session finalization cancelling a currently blocked invocation through the new reader.-- Reusable-child steering with a late superseded success through the complete combined path.-- Replay at the exact parent commit/`ready` boundary and a crash during final cohort release.--Removing the old `taskRunWorkflow` registration changes replay compatibility for in-flight runs-created by older deployments, including workflow-backed tasks. A production rollout needs deployment-pinning or a drain/migration plan; the prototype does not provide a legacy workflow fallback.--Delaying automatic failure output behind a slow sibling is an intentional behavior change. Task-state and activity still show failure promptly, but the model does not receive the failure as-conversation input until the cohort closes. Long-lived overlapping cohorts can therefore delay the-automatic report. No new timeout or grouping option was added.--The framework `agent` tool remains an internal exception to authored compilation: its definition is-runtime-rebound to the shared subagent workflow. The compiler exemption is limited to the existing-`self-agent` handling marker; authored background tools without a workflow ID fail with a migration-error.--## Parent-owned task state--The parent session owns durable task outcomes and pending input routes. Children send outcomes,-input requests, and authorization events through the existing session inbox; they no longer write-an `eve.task` snapshot stream. The child keeps only execution-local state for admission, abort,-and answer routing. Task notifications share one durable delivery step, preserving their existing-payloads and deduplication IDs. The unused `eve.task.progress` stream is removed: authored background-yields are consumed without publishing progress, while subagent update notifications still reach-the parent.--The first terminal outcome recorded by the parent wins. Duplicate or competing child deliveries-cannot overwrite it. Terminal notifications deduplicate by task, and their model-facing text uses-the parent's recorded outcome. A cohort waits for each terminal notification, including cancellation-already recorded by a control step, before releasing its report. Settlement clears pending task input routes. Coalesced input and spawn-requests are ignored when the same delivery also settles their task; agent settlement still runs-before its ownership lease is released.--`task_cancel` reads the parent's outcome instead of polling a child view. An already recorded-success or failure is returned unchanged. Otherwise cancellation signals the child, attempts-owned-agent cleanup, retains the existing bounded workflow-status wait, and records the cancelled-outcome in the parent. A queued notification ensures cohort reporting also works after forced stop.-The task-view polling loop and stream read timeout are deleted. Startup and reset waits are unchanged.--Validation for the parent-owned state change: all 8,911 unit tests passed (one skipped), and all 82 tests across seven-workflow, cancellation, session, and reset integration suites passed. Typechecking, the production-build, lint, formatting, invariant guards, and published-doc checks passed. The cancellation eval-now checks the retained outcome on the next turn without retrying; it remains CI-only.--After notification consolidation and progress-stream removal, all 8,915 unit tests passed (one-skipped), followed by 33 focused tests including the added agent-settlement delivery ordering test.-All 46 selected workflow and cancellation integration tests passed. The background-workflow eval-now asserts that yields emit no progress events; fixture lifecycle audits count the shared delivery-step and retain their handle-cleanup and accounting checks. E2E remains CI-only.--The wire registry is version 3. Each task stores its identity and metadata once; `outcome`-contains only terminal status, output, and optional usage. Readers combine them into a `TaskView`.-Proxy-input routes reuse their existing store. No legacy task-stream fallback is added.--## Agent settlement--Workflow runs carry no `resultKind`: every run returns a tool outcome. `agent-settled` owns-agent handle settlement and usage accounting. The agent helper waits for an acknowledgement on-its existing reply hook before returning output or throwing the child failure. The parent applies-settlement before acknowledging; workflow completion does not settle that agent again.--Settlement requires the exact owner and invocation call ID. Duplicate results are no-ops, including-late deliveries after a reusable agent has been claimed by another call. Agent preparation keeps its-existing node identity for receipts and reservations; this identity is not copied onto workflow runs.-The registry version changes to 2 and checkpoint version to 6 because older readers require the-removed discriminator and expect the former result protocol.--## Subagent result observation--Both execution modes use `subagent.called` for dispatch and `subagent.completed` for a-successful parent-recorded invocation result. The completion carries actual output and the-original `callId`; it does not imply termination of the reusable child session.--A background receipt is an `action.result` tool output with `status: "working"`. It does not-emit `subagent.completed`. For a generated subagent task, completion follows the parent's-first recorded successful task outcome. Replayed notifications and late success after failure-or cancellation cannot publish another completion. An agent invoked inside an authored-background workflow settles independently of its enclosing task, as in a blocking workflow.--Completion events do not wait for sibling tasks; the existing combined report still does.-Failure and cancellation retain their distinct task outcomes and do not emit successful-completion. Evals use `pending` until they observe a successful result, then `completed`.-The task itself uses `working` or `input_required` while active. No new event or stream-version is added; existing receipt-marked events remain readable as admission.--## Recommendation--Retain the shared invocation runtime and parent-owned task state. A task settles when the parent-records its outcome; this does not claim that the wrapper workflow has already exited. Workflow-status remains useful for cancellation cleanup, but it does not replace the parent's task result.-An infrastructure failure before outcome delivery still needs separate reconciliation; this change-does not introduce a runtime completion subscription or repair the local runtime cancellation race.--[prototype-invocation]: ../packages/eve/src/execution/tools/workflow/workflow.ts-[prototype-blocking]: ../packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts-[prototype-background]: ../packages/eve/src/execution/tools/workflow/workflow-owner-background.ts-[prototype-registry]: ../packages/eve/src/harness/workflow-tool-runs.tsdiff --git a/research/eve-tasks.md b/research/eve-tasks.mdnew file mode 100644index 000000000..2ee23982d--- /dev/null+++ b/research/eve-tasks.md@@ -0,0 +1,763 @@+---+issue: https://github.com/vercel/eve/issues/1084+status: draft+last_updated: "2026-09-26"+---++# eve tasks++This plan replaces background tasks as shipped in eve 0.66 with one task model. It specifies the+authoring API, the model's tools, and the observable semantics, then the runtime invariants and a+stack of pull requests that lands it in pieces. Paths are relative to `packages/eve/src/`.++## Summary++1. **A workflow tool defines exactly one entry point.** `execute(input, ctx)` is an ordinary tool+ call, as on `main`: the turn parks durably until the call settles, and its result is the tool+ result.+2. **`task(input, ctx)` runs each call as a task.** A task returns a receipt at once and keeps+ working while the conversation continues.+3. **`serve(receive, ctx)` runs a resumable task.** It gets each call from `receive()`,+ including later calls the model sends by `taskId`, and settles them with `ctx.reply()`. Every+ agent tool is a `serve` tool built on `ctx.agent`.+4. **Steering never cancels a task.** A new message ends the model's waits, and an `execute` call+ the turn is waiting on learns about it through `ctx.interruptSignal`. Tasks stop only for+ `task_cancel`, `session.cancel()`, or session end.+5. **Results arrive one way:** a `task.result` message at a step boundary. The model gets+ `task_wait`, which parks the turn until a task settles, and `task_cancel`.+6. **No turn ends while its tasks are working.** If the model tries, eve waits as if it had called+ `task_wait`, so every result arrives in the turn that started the work.+7. **eve is built on eve.** `sleep`, `ask_question`, `agentRouter()`, the `workflow` program tool,+ and every agent tool use only public API.++This follows Codex's multi-agent v2 (`openai/codex` `9ef08dc`): the wait only wakes the model, and+content arrives through the inbox at step boundaries. Unlike Codex, eve holds a turn open while+its tasks work, because scheduled, child, MCP, and eval sessions have no later user message to+collect results.++**Baseline.** This plan builds on #3817 (no run mode) and #3700 (answers come only from people),+both on `main`. Every session parks after each settled turn, `capabilities.requestInput` is the+only gate on asking a person, and `outputSchema` is a per-turn option only callers request,+through the session API and `ctx.agent`; agent definitions and the model can't set it.++## Vocabulary++One word per concept, used the same way in the API, docs, model text, events, and errors.++- **Call:** one invocation of a tool by the model, with its own `callId`.+- **Task:** a call that returns a receipt at once and keeps working while the conversation+ continues: every agent call, and every call to a `task()` or `serve()` tool.+- **Receipt:** a task call's immediate tool result, naming its `taskId`.+- **Resumable task:** a task defined with `serve()`, which accepts more calls with its `taskId`.+ Between results it is idle: available, but not working.+- **Result:** one call's outcome, `completed`, `failed`, or `cancelled`, delivered once.+- **Steering:** a `turnPolicy: "steer"` message from the turn's own principal arriving during a+ turn.++## 1. Workflow tools++A workflow tool defines exactly one of three entry points, and the entry point decides how its+calls run. Each entry point is run by the call that starts it: every `execute` or `task` call runs+its own body, and a `serve` body runs once per task and gets later calls through `receive()`.++```ts+defineWorkflowTool({+ description: "Deploy a service.",+ inputSchema: z.object({ service: z.string() }),+ async task(input, ctx) {+ "use workflow";+ return await deploy(input.service, { signal: ctx.abortSignal }); // the task's result+ },+});+```++- **`execute(input, ctx)`** is an ordinary tool call, exactly as on `main` and like+ `defineTool`'s `execute`: the turn parks durably until the call settles, and its result is the+ tool result. Its context, `WorkflowToolContext`, has `callId`, `abortSignal`, and+ `interruptSignal` (§2).+- **`task(input, ctx)`** runs the call as a task: a receipt now, the result later as a+ `task.result` message. Its context, `WorkflowTaskContext`, has `callId` and `abortSignal`, and+ no `interruptSignal`, because tasks are never interrupted.+- **`serve(receive, ctx)`** runs a resumable task (§3). `receive()` resolves each call with its+ own `callId` and `abortSignal`, and the context, `WorkflowServeContext`, has `reply(output)`+ and no `interruptSignal`.+- All three contexts share `ask`, `agent`, `agents`, `getToken`, `requireAuth`, and `session`.+- In `execute` and `task`, `return output` settles the call and a throw fails it. `async *execute`+ and `async *task` still yield progress as `action.partial`.++Defining none of the three, or more than one, fails at definition, where `{found}` is `none` or+the entry points defined, such as `execute and task`:++```text+Define exactly one of execute(input, ctx), task(input, ctx), or serve(receive, ctx); this tool+defines {found}.+```++**Tool calls and tasks.** The entry point answers whether the conversation should continue while+the call runs. Parking alone doesn't need a task: a question, a sleep, or an approval parks+durably inside an `execute` call and holds no compute. A twenty-minute deploy, or research the+model may not need right away, is a task. A long `execute` tool holds the conversation until it+settles; the docs say so where `task()` is introduced.++| Call | Runs as | Result | Steering during the call |+| ------------------------------------------------------------------------ | ------------------------- | ------------------------------------------------- | --------------------------------------------- |+| `execute()` tool, including `sleep` and `ask_question` | Tool call; the turn parks | The tool result | Its `interruptSignal` fires; the call decides |+| `task()` tool, including `agentRouter()` and the `workflow` program tool | Task | A receipt, then a `task.result` message | Nothing |+| `serve()` tool, including every agent tool | Resumable task | A receipt, then a `task.result` message per reply | Nothing |+| `task_wait` | Kernel wait | Which tasks settled | Returns `interrupt` |+| Plain and MCP tools | Inside the model step | The tool result | Applied at the next step boundary |++**Agents are always `serve` tasks.** Whether an agent's result is needed now depends on the+conversation, which only the model sees, and the turn rule (§6) guarantees the result reaches it.+An ordering that must always hold, such as "publish only after the review", is a workflow tool+that runs the review through `ctx.agent` and then acts, with the side effect not exposed as a+separate tool.++## 2. Steering and cancellation++Steering is applied in this order:++1. If the message answers a pending request, it answers it and doesn't steer. Only a person's+ message to the session they're talking to can answer, as on `main` after #3700; a caller's+ message, such as an agent tool's message to its child, never does.+2. Otherwise, the `interruptSignal` of every `execute` call the turn is waiting on fires, and+ `task_wait` returns `interrupt`. Tasks are untouched. The model sees the message once the+ step's `execute` calls settle, and decides whether to keep, correct, or cancel each task.++Steering never ends the turn. A `"queue"` message waits for the turn to end.++**`ctx.interruptSignal`** fires once, on the first steering message while the turn waits on the+call; later messages are applied after the call settles anyway. What it means is the author's+choice. A body that ignores it keeps going: a deploy waiting on an approval survives unrelated+messages. A body that wants to stop races or passes the signal. Tasks are never interrupted, so+`task` and `serve` have no `interruptSignal`.++**Anything that waits takes a `signal`.** `ctx.ask(request, { signal })` withdraws the request+when the signal aborts: it resolves `{ status: "cancelled" }`, and `input.resolved` reports+`outcome: "cancelled"` so channels update the question. Cancellation withdraws a pending ask the+same way. An ask that should end when the conversation moves on passes `ctx.interruptSignal`,+which replaces `dismissible`. The built-in tools do exactly this:++```ts+// ask_question, as eve ships it+async execute(input, ctx) {+ "use workflow";+ const answer = await ctx.ask(toQuestion(input), { signal: ctx.interruptSignal });+ return answer.status === "cancelled" ? { interrupted: true } : answer;+}++// sleep, as eve ships it+async execute(input, ctx) {+ "use workflow";+ const interrupted = new Promise<"interrupted">((resolve) =>+ ctx.interruptSignal.addEventListener("abort", () => resolve("interrupted"), { once: true }),+ );+ const elapsed = sleep(input.seconds * 1_000).then(() => "elapsed" as const);+ const woke = await Promise.race([elapsed, interrupted]);+ return woke === "elapsed" ? { waitedSeconds: input.seconds } : { interrupted: true };+}+```++Both render `{ interrupted: true }` as `Stopped early because a new message arrived.`++**Cancellation.**++- **`session.cancel()`** cancels the turn, the `execute` calls it is waiting on, and every+ working task. Its `tasks` option is removed; `turnId` and `signal` stay.+- **`task_cancel({ taskId })`** cancels one task's current work and returns+ `{ status: "cancelled" | "already_finished" }`.+- **Session end** ends every task.++Cancelled work never reports back. A `task()` task is then finished. A `serve()` task stays+available if its body catches the abort (§3): its waiting calls settle as `cancelled`, their+`abortSignal` aborts, and the task becomes idle. For an agent, that cancels the agent's turn and+keeps its conversation.++## 3. Resumable tasks: `serve`++```ts+defineWorkflowTool({+ description: "Draft a release plan and revise it on request.",+ inputSchema: z.object({ request: z.string() }),+ async serve(receive, ctx) {+ "use workflow";+ let plan: Plan | undefined;+ for (;;) {+ const { input, abortSignal } = await receive(); // the first call, then each by taskId+ try {+ plan = await revise(plan, input.request, { signal: abortSignal });+ ctx.reply(plan); // a result; the task stays available+ } catch (error) {+ if (!abortSignal.aborted) throw error; // cancelled: wait for the next call+ }+ }+ },+});+```++A `serve` body runs once per task and gets its calls from `receive()` instead of taking an input:++- **`receive()`** resolves with the next call, `{ input, callId, abortSignal }`, with `input`+ validated by `inputSchema`. The first `receive()` resolves in memory from the call that started+ the task, with no step or hook. After that, it resolves with each call made with the task's+ `taskId`, in arrival order. Calls that arrive while the body isn't waiting are kept. A pending+ `receive()` is shared: calling it again returns the same promise, so a `Promise.race` it loses+ never drops a call.+- **`ctx.reply(output)`** settles the calls received so far with `output`, and the task goes idle+ until the next call. A reply with no call left to settle is dropped, and `ctx.ask` throws while+ no call is waiting for a result.+- **`return output`** settles the calls still waiting and ends the task; throwing fails them.+ `serve` is not a generator, so it can't yield progress for now.+- **`taskId` on the model input.** eve adds an optional `taskId` to the tool's model input.+ Without it, a call starts a new task; with it, the call goes to that task. The build fails if+ `inputSchema` declares its own `taskId`. The ID must name an unfinished task this tool started+ for the caller's principal, or the call fails `UNKNOWN_TASK`.+- **One `abortSignal` per stretch of work.** A stretch starts when a call reaches an idle task and+ ends when a reply or a cancel settles its calls; calls that arrive during it carry the same+ signal. Each signal aborts at most once and the next stretch gets a new one, so a task can be+ cancelled any number of times. A body stays available only if it catches its stretch's abort+ and returns to `receive()`; an abort that escapes the body finishes the task. A body that ignores+ the signal keeps working, and its reply is dropped.+- **The context follows the call.** `ctx.session` (its turn and auth) and `ctx.agents` describe+ the call being served, from the moment `receive()` resolves it. An agent session the body opens+ belongs to the call that opened it: its parent, turn, and trace come from that call. Each+ message the body sends it carries the auth of the call being served when it is sent.+- **Working and idle.** A resumable task is working while one of its calls has no result, and+ idle otherwise. An idle task holds no turn and doesn't count toward the cap.+- **Finishing.** The task finishes when its body returns or throws, or when the session ends,+ which aborts the current stretch's signal and rejects a pending `receive()`.+- eve appends this sentence to the tool's description:++```text+To send this task more input, call this tool again with its taskId; without taskId, each call+starts a new task.+```++## 4. Agents++**`ctx.agent(name)`** returns a handle to a child session owned by the run, shaped like the+TypeScript client's session. The child opens on the first `send`.++```ts+const agent = ctx.agent("researcher");+const response = await agent.send("Find the incidents behind the March outage.", {+ outputSchema, // optional, per turn, as on the client+ signal, // optional; aborting cancels this turn+});+const { data, message, status } = await response.result();+```++- `send` delivers a caller's message. If the agent's turn is running, the message joins it and its+ response resolves with that turn's result; if the agent is idle, it starts the next turn.+- `result()` returns the client's `MessageResult` fields `data`, `message`, and `status`. The+ agent's events stay on its own stream.+- Nothing about opening, sending to, or settling the session passes through the parent session.+ A person still answers the agent's questions and sign-ins at the root, through the owner chain+ (§7). The model can't address these sessions; it sees what the body returns or replies.+- A run's sessions end when the run finishes, cancelling any turn still running.++**Agent tools.** Every agent is a tool named after it, with model input+`{ message: string; taskId?: string }`. It is a `serve` tool that forwards each call to one+session, as eve ships it:++```ts+async serve(receive, ctx) {+ "use workflow";+ const agent = ctx.agent(name);+ // A cancel aborts the call's abortSignal, which ends the agent's turn.+ const send = ({ input, abortSignal }: Awaited<ReturnType<typeof receive>>) =>+ agent+ .send(input.message, { signal: abortSignal })+ .then((response) => response.result());+ let latest = send(await receive());+ for (;;) {+ const event = await Promise.race([+ latest.then((result) => ({ result })),+ receive().then((next) => ({ next })),+ ]);+ if ("next" in event) {+ latest = send(event.next); // joins the running turn, or starts the next if it just ended+ continue;+ }+ if (event.result.status === "failed") throw new Error("The agent's session ended.");+ ctx.reply(toOutput(event.result)); // settles the calls received so far; dropped after a cancel+ latest = send(await receive());+ }+}+```++- **No `outputSchema` from the model.** As on `main` after #3817, structured output is a+ caller's per-turn choice through `send`; the model's agent tools and `agentRouter()` don't+ offer it.+- **One result per agent turn:** the turn's final response. A message that joined the turn is+ settled by the same reply.+- The tool description is the agent's `description` followed by:++```text+It does not see this conversation, so put everything it needs in message. To correct or continue+an agent task, call this tool again with its taskId; without taskId, each call starts a new agent.+```++## 5. The model's view++```ts+task_wait({ timeout?: number }) // parks the turn until any of its tasks settles; ms+task_cancel({ taskId: string }) // → { status: "cancelled" | "already_finished" }+```++Both are offered, with the system block below, when the agent has an agent or a `task()` or+`serve()` tool.+All model text is a draft, tuned with real-model evals.++**`task_wait`** returns when any task the turn's principal started settles, when `timeout`+passes, or when steering arrives, and at once if a result is already waiting. It never returns+content; the settled results follow as the `task.result` message in the same step. Waiting never+stops a task, and a task waiting on a person keeps the wait going.++```text+Wait until one of your tasks has a result, a new message arrives, or timeout (in milliseconds)+passes. Results arrive in a <task_result> message right after this call returns. Waiting never+stops a task. Omit timeout to wait until a result or a message arrives; a timeout of 0 returns+at once with any results that are ready.+```++```ts+type TaskWaitResult =+ | { status: "settled"; settled: string[]; working: string[] } // both empty: nothing was working+ | { status: "timeout" | "interrupt"; working: string[] };+```++`settled` lists the tasks whose results follow, failed ones included; cancelled work never wakes+a wait. The model gets text:++```text+d0-2b0c1a completed; its result follows. 1 task is still working: sre-9x1k2p.++Stopped waiting after 5m; 2 tasks are still working. Their results arrive before your turn+ends; wait again only if you need them now.++A new message arrived, so the wait ended after 40s; 2 tasks are still working. Read the message,+answer it if it asks you something, and decide whether it changes this work: keep the tasks, call+an agent again with its taskId to correct it, or stop a task with task_cancel.++No tasks are working.+```++**`task.result` message.** The one way results reach the model: a user-role message of kind+`task.result` with one `<task_result>` block per result, appended at the next tool-step boundary+after a result settles, right after `task_wait` returns, or when a held turn wakes. The body is+`toModelOutput(output)` when defined, or the error message for a failed call, with+`</task_result` escaped. All results in one message share a limit of 50 KB and 2,000 lines, then+`[truncated]`.++```text+<task_result id="d0-2b0c1a" tool="d0" status="completed">…</task_result>+```++**`task_cancel`:**++```text+Stop a task's current work. That work never reports back; if it already had a result, that+result is still delivered. An agent, or any task that accepts more input, stays available: call+its tool with its taskId to give it new work.+```++**Receipts.** IDs are `<tool>-<6 base32>`.++```text+Started task researcher-7k2m9q. Call researcher again with taskId researcher-7k2m9q to send it+another message.++Started task deploy-4hd8sa.++Sent to task researcher-7k2m9q.+```++**`[Tasks]` note.** A `context.state` message appended at a model-step boundary when the listing+changes, and after compaction, so task IDs survive it. It is derived only from the session's task+table in process, never from child streams: the turn principal's working tasks with tool and+status, then its 10 most recent idle resumable tasks.++```text+[Tasks]+<tasks>+<task id="deploy-4hd8sa" tool="deploy" status="working"/>+</tasks>+<idle>+<task id="researcher-7k2m9q" tool="researcher"/>+</idle>+```++**System block.**++```text+Every subagent call and some tools start a task and return its id right away; the task keeps+working while you continue. Results arrive in <task_result> messages. When you need a result to+continue, call task_wait; it returns when any task has a result. Start independent tasks first,+then wait. To correct or continue an agent, or any task that accepts more input, call its tool+again with its taskId. If you don't need a task's result yet, reply now instead of calling+task_wait: your turn stays open while your tasks work, and eve gives you their results when they+finish. A new message never stops your tasks: answer it if it asks you something, decide whether+it changes the work, then keep the tasks, correct an agent with taskId, or stop a task with+task_cancel. Never use sleep to wait for a task.+```++**Errors.** These are the only task error codes.++| Code | Where | Message |+| ---------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |+| `UNKNOWN_TASK` | Call with `taskId`, `task_cancel` | `No task "{id}" is available to {tool}: it may have ended or belong to another tool or caller. Start a new one by calling {tool} without taskId.` |+| `TOO_MANY_TASKS` | Start, call to an idle resumable task | `32 tasks are already working ({ids}). Wait with task_wait or stop one with task_cancel, then try again.` |++## 6. Turns, principals, and limits++**The turn rule.** No turn ends while tasks its principal started are working, in any session.+When the model ends such a turn, eve does what `task_wait` does: it parks until one of those tasks+settles or the same principal steers, appends the settled results, and calls the model again. A+`final_output` call while tasks work returns an error naming them. No result ever starts a turn.+Session expiry and turn failures cancel the turn's tasks, as `session.cancel()` does.++**Presentation of a held turn.** A held turn stays open. Each time an open turn parks, the stream+emits `turn.waiting` with the turn's ID: when eve holds a turn the model tried to end, in every+session kind; when `task_wait` actually parks, not for `timeout: 0` or results already waiting;+and when a call the turn is running (a task, an agent's session, or an `execute` body, which+includes `ask_question`) asks a question or needs a sign-in, right after its `input.requested` or+`authorization.required`. `turn.waiting` is informational, never a response+boundary: the next `step.started` with the same `turnId` means the turn resumed, and only+`turn.completed`, `turn.failed`, or `turn.cancelled` end it. `session.waiting` keeps one meaning,+the turn has ended and the session awaits another message, and carries no `turnId`. A tool+approval the turn requests still ends that turn, as today: `input.requested`, `turn.completed`,+then `session.waiting`. A root turn's held text step completes normally as+`"stop"`, and a person can keep writing. A child turn (its session has a caller) and a schedule's+turn (`ScheduleIdKey`, `harness/tool-loop.ts`) report their held text step as+`finishReason: "tool-calls"`, which channels already skip, so the run posts once. History and+traces keep the model's own finish reason.++**Where a response ends.** `send()`, the helpers that collect a turn's events, and MCP stop at+`session.waiting`, `session.completed`, or `session.failed`, and at `turn.waiting` only when+questions are pending in what they read, the way pending sign-ins already gate+`session.waiting`. Then `result()` returns `status: "waiting"` with the questions, and+`respond()` keeps reading the same open turn to its real end. Without pending questions,+`turn.waiting` is not a boundary, so `send().result()` and an MCP `agent_get` see the final reply;+this closes the gap #3817 notes for MCP `agent_start` with a delegating agent. Turn trace spans+end only on `turn.completed`, `turn.failed`, or `turn.cancelled`.++**Slack posts the text before a wait.** Channels post only on `finishReason: "stop"`, and use a+`"tool-calls"` step's text as a typing status. Slack also posts that text when the step's only+tool call is `task_wait`, so a person sees what is running ("Checking revenue and incidents now;+I'll report back.") while the turn waits. It buffers the text on `message.completed` and posts it+on the following `actions.requested` when that step's only action is `task_wait`. A step with any+other tool call keeps today's typing status, and a schedule's turn doesn't post it. A task+call's receipt doesn't show as finished: Slack's activity keeps the call running from its receipt+until `task.settled` for that `callId`, then settles it with the real status. There is no option+yet, and other channels are unchanged.++**Principals.** Only the turn's own principal steers it; another principal's message waits for+the turn to end, then starts that principal's turn. Calls with `taskId` and `task_cancel` accept+only the task's creator principal, and `task_wait` and `[Tasks]` cover only the turn principal's+tasks. Anonymous callers share one principal. Queued messages from one principal share a turn+even when their claims differ, and the turn runs with the latest claims.++**No task time limits.** `defineAgent`'s `limits.sessionTimeoutMs` keeps its meaning, the+session lifetime (default 30 days), and bounds all work in the session; with `false`, tasks are+unbounded. A body that needs a limit races `sleep` against its work. A person who wants an update asks, and the model decides whether to keep+waiting or cancel.++**Cap.** At most 32 working tasks per session (`TOO_MANY_TASKS`), a worst-case backstop normal use+shouldn't reach. Idle resumable tasks don't count.++### Stream events++```ts+{ type: "turn.waiting"; data: { turnId, sequence } }+{ type: "task.started"; data: { taskId, callId, turnId, name } }+{ type: "task.settled"; data: { taskId, callId, turnId,+ status: "completed" | "failed" | "cancelled",+ output?: JsonValue, error?: { message: string } } }+{ type: "agent.started"; data: { callId, turnId, taskId?, name, sessionId, streamPath } }+```++- **`turn.waiting`** has the shape of `turn.completed` and comes each time an open turn parks+ (above). It names no tasks; `task.started` and `task.settled` say which are working.+- **`task.started` and `task.settled`** come once each per call to a task: when the call starts+ a task or reaches one by `taskId`, and when a reply, return, failure, or cancel settles it.+ `(taskId, callId)` identifies the call; `callId` is the tool call clients attach status to, and+ both events carry that call's `turnId`. For each invocation, `task.started` comes before the+ sessions it announces and the calls it settles.+- **`agent.started`** comes once per session a workflow run opens with `ctx.agent`, including an+ agent tool's, with the `callId` and `turnId` of the call whose invocation opened it; for a+ `serve` task that is the current call, not the first. `taskId` is present when that invocation+ runs as a task and absent for `execute`. One task can own several sessions. `streamPath` is a+ local child's stream route, or the parent-origin proxy for a remote child.+- **`output`** is a completed call's typed result; **`error.message`** explains a failed one.+ There are no error codes and no usage; either can be added later without breaking anyone.++`session.streamSubagent(started)` takes an `agent.started` event and no longer checks the parent+session ID; the proxy validates the parent and call. Hooks subscribe to the new events in place+of `subagent.*`. `input.requested` and `authorization.*` gain `taskId` when a task asks. A+`task.result` message is not published as `message.received`: it stays a user-role message in+the model's history, and clients see outcomes through `task.settled`. The eval assertion+`t.calledSubagent(name, { status })` keeps its API and reads task events.++## 7. Runtime invariants++- **One owner per task.** The session owns every task; a workflow run owns only the sessions it+ opens with `ctx.agent`, which are not tasks. One small versioned record per task, written only+ by applying the session's inbox messages (`execution/tasks/table.ts`): `id`, `name`,+ `resumable`, `status` (`working`, `idle`, or finished), the calls without a result, each with+ its `turnId`, `delivered`, `creator` (auth captured at start), and the cancel timestamp. A+ record that fails to decode fails its task ("its state could not be read"), never the session.+ Sessions aren't migrated.+- **Every wait suspends.** The session is a durable workflow (`execution/session/entry.ts`) whose+ inbox is built on Workflow SDK hooks. `execute` calls keep today's path: the call defers out+ of the model step and the turn loop parks until it settles (`execution/session/turn.ts`,+ `waitForRuntimeActionResults`). `task_wait` and a held turn park the same way until a task+ settles, the timeout (a durable `sleep` raced against the inbox), or steering. Nothing polls.+- **First call is free.** The run's start input already carries the tool input+ (`execution/tools/workflow/body.ts`). `execute` and `task` receive it as `input`, as today, and+ a `serve` body's first `receive()` resolves from it in memory and replays deterministically.+ Only later calls to a `serve` task use the run's private hook, created with a token derived+ from `taskId` before the body starts, because a Workflow SDK hook registers only when the run+ suspends.+- **One inbox per run.** A run's signals and ask results are views over one ordered inbox, so+ when an answer and an interrupt race, they resolve in inbox order: `ask_question` gets the+ answer or `cancelled`, whichever its run's inbox received first.+- **Start once.** The model step commits the task record, with an ID assigned by the session,+ alongside the tool call; the session then starts the task's run in one step keyed on `taskId`.+ Commands issued before the run reports started are held on the record.+- **Settle once.** Runs send the session `task.input` and `task.settled`, keyed+ `(taskId, callId, kind)`; a reply sends one `task.settled` per call it settles. The first+ outcome per call wins, owner-cancelled results are dropped, and every other result is appended+ once to the next `task.result` message and marked `delivered`.+- **Calls with `taskId`.** The session checks the task is resumable, unfinished, this tool's, and+ the caller's principal's (else `UNKNOWN_TASK`), records the call, marks the task `working`,+ emits `task.started`, and resumes the task's hook with the validated input.+- **Cancel.** The session settles the waiting calls as `cancelled`, sends the run `cancel`, and+ returns at once. A `task()` run aborts its call's `abortSignal`, and one sleeper run per+ session, armed only for the earliest pending confirmation, hard-stops it after 30 s. A `serve()`+ run aborts the current stretch's signal and stays parked on its hook, so it needs no hard stop.+- **Agent sessions.** A workflow run's start input carries the caller's principal, capabilities,+ dynamic agent selections, and sandbox reference. `ctx.agent` opens its child, local or remote,+ in a step keyed on the run and the handle's position; `send` uses the child's existing deliver+ path with the run's `callId` as `caller.callId`; `result()` waits through a hook. The run+ publishes `agent.started` on the session's stream, as it publishes `action.partial`.+- **Questions go up, answers come down.** A child's `input.requested` and `authorization.*` travel+ up the owner chain to the root, where a person answers, and answers route down by request ID.+ The root emits `input.resolved` for each answer it routes, during a hold too. This is the only+ path from a run's sessions to the session. Remote children run the same protocol over HTTP,+ with idempotent callbacks and a version check that fails the call at start with a message+ naming both versions.+- **Turn end.** The harness's terminate branch (`harness/tool-loop.ts`) returns `held` with the+ working task IDs, the turn loop waits, and the program (`execution/session/program.ts`) sends+ the caller's reply from one guarded site. The hold is keyed by principal, so a turn resumed+ after an approval or sign-in still holds on the parked turn's work.+- **A turn completes once.** `turn.completed` comes only at a turn's real end. A question or+ sign-in inside a running call parks the turn with `turn.waiting` and never ends it.+- **Guards** (`pnpm guard:invariants`): `tools/provided/**` and generated agent tools import only+ public entry points, except the kernel's `task_wait` and `task_cancel`; only+ `execution/tasks/table*.ts` writes records; model text lives only in+ `execution/tasks/render.ts`; one caller-reply site.++## 8. Removed and changed++These are the upgrade notes; everything is breaking and allowed pre-1.0.++- **Workflow tool bodies** keep `execute(input, ctx)`, `ctx.abortSignal`, and `ctx.callId`.+- **`execution: "background"`** is replaced by defining `task(input, ctx)` in place of+ `execute`. `defineWorkflowTool` rejects `execution` with this error:++```text+"execution" was replaced by task(). Define task(input, ctx) to run each call as a task.+```++- **`ctx.agent`:** `ctx.agent(name, { message, agentId })` returning output becomes+ `ctx.agent(name)` returning a session handle. `agentId` is removed; each handle is a new child.+- **`ctx.ask`:** `dismissible` is removed; pass `ctx.interruptSignal` as `signal`. The+ `input.resolved` outcome `"dismissed"` becomes `"cancelled"`.+- **Agent tools:** `agentId` becomes `taskId`, and every agent call is a task.+- **`agentRouter()` and the `workflow` program tool** become `task()` tools instead of blocking+ calls.+- **Removed:** `taskDeliveryPolicy` and cohorts; the `[Task state]` and `[Agents]` notes, prose+ task notifications, `<eve-empty-delivery/>`, and result turns; `session.cancel()`'s `tasks`+ option; the `subagent.called`, `subagent.completed`, `subagent.started`, and `subagent.event`+ events; the `AGENT_BUSY`, `AGENT_MISMATCH`, `AGENT_UNREACHABLE`,+ `AGENT_INVOCATION_NOT_ADMITTED`, `BACKGROUND_TASK_FAILED`, and `BACKGROUND_TASK_CANCELLED`+ codes.+- **Questions and sign-ins inside a call** no longer end the turn: on `main`, a question or+ sign-in from inside a blocking call, including `ask_question`, emitted `turn.completed` and+ `session.waiting` mid-turn; it now emits `input.requested` or `authorization.required`, then+ `turn.waiting` (§6).+- **Remote agents:** the remote protocol version changes; both deployments must upgrade together.++Workflow tools that use none of `execution: "background"`, `dismissible`, or `ctx.agent` don't+change. In the repository today, this touches those that do, code reading `subagent.*` events,+the fixtures under `e2e/`, the templates and apps, and the docs pages that describe them. In+internal-agents it touches 5 files with `ctx.agent`, 39 reading `subagent.called`, 8 with+`execution: "background"`, and 7 with `dismissible`.++## 9. Delivery++The work lands as a stack of pull requests managed with `gh stack`, on top of this plan's PR.+Each PR is one coherent step from the one below it: it passes CI on its own, updates the docs and+fixtures for the behavior it changes, and carries a changeset (`minor` when it breaks a public+API). Main may lack features between PRs, never correctness. **Hold the Changesets release from+PR 1 until PR 10 merges**, so no release ships without background work and then without its+replacement.++### Implementation rules++- **One large removal, then narrow steps.** PR 1 deletes background tasks wholesale, including+ every test of them: unit, integration, scenario, and e2e. Every later PR is tight and changes+ only what its step needs; unrelated cleanup waits for its own PR.+- **The bar for each PR is a passing build.** `pnpm build`, `pnpm typecheck`, `pnpm lint`, and+ `pnpm guard:invariants` pass, and CI is green. An existing test a PR breaks is updated if it+ still describes intended behavior and deleted if it doesn't.+- **Few tests during implementation, if any.** Don't add unit tests that restate the code just+ written. Add a test only when a PR can't be trusted without one. Proper coverage comes after+ the stack lands, as e2e suites where they prove behavior end to end (§10).+- **Code quality comes first.**+ - Write readable code, not compact code: no dense one- or two-line expressions such as nested+ ternaries, chained callbacks that do several things, or clever reduces. Name each step.+ - Extract a helper function wherever a step has a name, and define explicit interfaces and+ types at module boundaries: task records, inbox commands, the received call, and agent+ session handles.+ - Keep related code together: the task kernel under `execution/tasks/`, its model text in one+ renderer, and public types beside the definitions they describe.+ - Follow `AGENTS.md`: keep it simple, comment why rather than what, add no legacy fallbacks,+ and wrap third-party APIs.++| # | PR | Main after it lands |+| --- | ----------------------------- | --------------------------------------------------------------- |+| 1 | Remove background tasks | Every workflow tool and agent call blocks |+| 2 | Workflow tool body (dropped) | Nothing: `execute(input, ctx)` keeps its signature |+| 3 | Steering signals | `ctx.interruptSignal`; `sleep` and `ask_question` on public API |+| 4 | Agent sessions | `ctx.agent(name)` handles; `agent.started`; `turn.waiting` |+| 5 | Task kernel and the turn rule | `task(input, ctx)`, `task_wait`, `task_cancel`, held turns |+| 6 | Held-turn presentation | `turn.waiting` for every held turn; root text steps as `"stop"` |+| 7 | Resumable tasks | `serve(receive, ctx)`, `ctx.reply()`, `taskId` |+| 8 | Agents as tasks | Agent tools as `serve` tools; `subagent.*` removed |+| 9 | Slack post before a wait | The text of a `task_wait` step is posted; receipts stay running |+| 10 | Tests and release readiness | E2E suites, real-model evals, Tasks and upgrade guides |++**1. Remove background tasks.** Delete `execution: "background"` (rejected at definition),+`taskDeliveryPolicy`, cohorts, the `[Task state]` and `[Agents]` notes, prose notifications,+`<eve-empty-delivery/>`, result turns, `session.cancel()`'s `tasks` option, the+`BACKGROUND_TASK_*` codes, and background subagent dispatch; agent calls use the existing blocking+path, with `agentId` continuation unchanged. Delete the `agent-background-tools`,+`agent-task-reporting`, `agent-task-wake-policy`, and `fixture-tasks` fixtures and the background+suites in `agent-subagents`, `agent-cancellation`, and `agent-workflow-tools`; update the docs to+describe blocking calls only. Delete `research/background-task-wake-policy.md`, which describes+the removed behavior, and every test of background tasks.++**2. Workflow tool body.** Dropped. `execute(input, ctx)` keeps its signature, so no workflow+tool migrates; `receive()` and `reply()` move to PR 7 as `serve()`.++**3. Steering signals.** Start with a spike commit proving an `interrupt` command on the run's+command hook reaches the body and replays deterministically; it is the one unproven mechanism.+Then `ctx.interruptSignal` on the `execute` context, the steering rule for waited `execute`+calls, `ctx.ask(..., { signal })` withdrawal with `outcome: "cancelled"`, removing `dismissible`,+`sleep` and `ask_question` rebuilt as `execute(input, ctx)` on public API, and the+`tools/provided/**` guard.++**4. Agent sessions.** `ctx.agent(name)` handles opened from the run with the caller's principal,+capabilities, dynamic selections, and sandbox reference in the start input; `agent.started` with+the opening call's `turnId`; `streamSubagent()` accepting `agent.started`; questions and sign-ins+up the owner chain from run-owned sessions; the remote protocol change and version check.+`turn.waiting` and the message stream version bump: a question or sign-in inside a running call+emits `input.requested` or `authorization.required`, then `turn.waiting`, and no longer ends the+turn; the root emits `input.resolved` for every answer it routes to a session; clients stop at+`turn.waiting` only when questions are pending. Delete `agent-invoke`,+`agent-settled`, and the workflow-leased agent handles; migrate `agentRouter()`, the `workflow`+program tool, and the `agent-cancellation` fixture, whose `agentId` continuation is dropped. The+model's agent tools keep the old path and `subagent.called` until PR 8. Check first: how the+remote stream proxy finds the remote URL and credential key without `findRemoteSubagentBinding`+scanning for `subagent.called` (`eve-channel/support.ts`); resolve it from the agent definition by+`agent.started.name`, and if dynamic remote agents can't be resolved that way, record the binding+on the run's `agent.started` step instead.++**5. Task kernel and the turn rule.** Task records, `task(input, ctx)` with+`WorkflowTaskContext` and the one-entry-point definition error, receipts, `task.started` and+`task.settled` with each call's `turnId`, `task_wait` with `turn.waiting` when it parks,+`task_cancel`, the `task.result` message (not published as `message.received`), `[Tasks]`, the+system block, `UNKNOWN_TASK`, `TOO_MANY_TASKS`, principals, `session.cancel()` cancelling working+tasks, the hard-stop timer, and the turn rule with `final_output`'s error. `agent.started` gains+`taskId` for `task()` runs, and proxied answers emit `input.resolved` during a hold. A held turn+emits no `turn.waiting` yet: every held text step reports `"tool-calls"`, as child turns do.+`agentRouter()` and+the `workflow` program tool become `task()` tools; the `execution` error gains its final+wording.++**6. Held-turn presentation.** `turn.waiting` whenever eve holds a turn, in every session kind; a+root turn's held text step completes as `"stop"`, and `"tool-calls"` remains only for child and+schedule turns.++**7. Resumable tasks.** `serve(receive, ctx)` and `WorkflowServeContext`: `receive()` with the+first call from the start input and later calls through the run's hook, `ctx.reply()`, return+and throw settlement, `ctx.ask` throwing while no call waits, `taskId` on the model input and its+build check, per-stretch `abortSignal`, idle tasks in the turn rule and `[Tasks]`, and cancel+keeping the task. Each call carries its own turn, auth, and agent context, so `ctx.session`,+`ctx.agents`, `agent.started`, and `task.settled` describe the current call, and a session the+body opens belongs to the call that opened it.++**8. Agents as tasks.** Agent tools rebuilt as `serve` tools on `ctx.agent`;+`agentId` becomes `taskId`. Delete the old dispatch (`subagents/handle-dispatch.ts`,+`subagents/remote-dispatch.ts`, `execution/tools/subagent/`), the four `subagent.*` events, the+`AGENT_*` codes, and `streamSubagent(called)`. Move the client reducer, dev TUI, eval assertions,+and hook event map to task events. #3700's delegated-session regressions and its+`agent-subagents-hitl` eval keep passing for agent tools, local and remote.++**9. Slack post before a wait.** First confirm Slack's event handlers can read `ScheduleIdKey`.+Task receipts stay running in Slack's activity until their `task.settled`.++**10. Tests and release readiness.** The test pass in §10, a Tasks guide in `docs/` (choosing+`execute`, `task()`, or `serve()`, the ordering pattern, signals), and the upgrade guide from §8. Then release, and migrate+internal-agents.++## 10. Tests after the stack++Tests are written once the implementation has landed and the build is green, starting with e2e+suites under the fixtures they exercise.++**E2E (mock model):**++- An `execute` tool's result arrives as its tool result.+- Steering ends `sleep` but not an approval-gated tool, and a withdrawn ask reports+ `outcome: "cancelled"`.+- A `task()` tool starts, is waited on, and delivers its result; `task_cancel` stops one.+- The turn rule in each session kind: `turn.waiting` in a root session, a child turn, and a+ schedule's turn; a held root turn's `send().result()` and MCP `agent_start` with a delegating+ agent reporting only the final reply.+- A task's question during a hold emits `input.requested`, then `turn.waiting`, and the answered+ turn completes once.+- A user-defined `serve()` tool is continued by `taskId`, cancelled, and continued again.+- An agent, local and remote, is continued by `taskId` across turns and after `task_cancel` with+ its conversation intact; a child's question is answered at the root.+- Slack posts the text of a step whose only tool call is `task_wait`.++**Real-model evals** that gate the release: waits when the answer is needed; fans out, then waits+for every result; keeps tasks after an unrelated message; corrects an agent by `taskId` or+cancels after a redirect; continues an agent instead of starting a new one; doesn't wait when+told there's no rush; doesn't use a side-effect tool before the result it depends on.++**Candidates beyond e2e,** decided in this pass because e2e can't hit them deterministically:+duplicate settlement; a result before the run reports started; a cancel before it starts; a crash+between the record and the start; a hard stop racing a result; a result settling as `task_wait`+starts or ends; an agent message racing the end of its turn; a call arriving before a `serve`+body's first `receive()`.++## 11. Risks and accepted costs++1. **One more model step per needed result** (start, then wait), and one wake per result when the+ model needs several.+2. **Long `execute` tools** hold the conversation until they settle.+3. **`interruptSignal` is unproven** until PR 3's spike.+4. **Shared-thread wait.** Another person's message waits for a held turn, tasks included. One+ open turn per principal is the first follow-up.+5. **`serve` bodies own their correctness.** A body must catch its stretch's abort to stay+ available, one that never replies holds the turn until its call is cancelled, and one that+ ignores `abortSignal` keeps working after a cancel.+6. **Every agent task costs a workflow run** around its child session.+7. **A lost remote completion** leaves its task working until the session ends; remote callback+ retries and an `agent_state` tool are follow-ups.+8. **Most PRs in the stack break public API** before one release; holding the release is what+ keeps users from seeing the intermediate states.diff --git a/research/subagents-as-tasks-implementation.md b/research/subagents-as-tasks-implementation.mddeleted file mode 100644index 9296e44e7..000000000--- a/research/subagents-as-tasks-implementation.md+++ /dev/null@@ -1,222 +0,0 @@-----issue: https://github.com/vercel/eve/issues/1084-status: draft-last_updated: "2026-08-24"------# Subagents as tasks: additive delivery plan--## Summary--This plan sequences the implementation of the [subagents-as-tasks design] into strictly additive-stages behind `experimental.tasks`. Every stage must land with this invariant: **with the flag-absent, no existing codepath's behavior, wire shapes, or event stream changes.** The design doc-owns the contract; this doc owns the order of construction, what each stage reuses from the-agent-messaging stack, and how each stage is verified before the next begins.--## Baseline--The baseline is `am/04-surface`, the tip of the agent-messaging stack (the phase-one-agent2agent work), which this plan's branch now stacks on directly. That stack supplies the-session-addressing dependency the design doc declares:--- **Durable child address**: the agent handle store (`eve.agent.handles` on session state) with- replay-safe operation ids, commit-before-side-effect dispatch, and `starting/running/parked`- phases. Handles hold the child `continuationToken` (local) or `url` + `continuationToken`- (remote); credentials never render to the model.-- **Follow-up delivery**: `dispatchToTaskAgentAddress` / `continueRemoteAgentSession`, with- `AGENT_BUSY` / `AGENT_MISMATCH` / `AGENT_UNREACHABLE` classification and `intent: "resume"`- sends that 404 instead of silently starting a new session.-- **Reply envelope**: `TurnCaller` (`replyTo: hook token | callback URL`) and the- `turn.completed` / `turn.failed` callback kinds carrying an explicit `AgentTurnOutcome`.-- **Result binding**: inbox results are bound to a running handle, so a callee cannot settle a- sibling's call and replays cannot double-settle.--Tasks must not build a second addressing mechanism. The task record composes with handles:--- the **handle** identifies the reusable child session (agent-messaging owns it);-- the **task** identifies one unit of work against that handle and adds what handles lack:- a durable record that survives terminal settlement, `working` / `input_required` status,- progress messages, and receipts instead of turn-blocking.--Task identity reuses the operation-id derivation, `hash(parentSessionId, parentTurnId, callId)`,-so replayed creation for the same originating call yields the same task without new machinery.--### Persistent subagent baseline--`agentId` follow-ups to a finished child require conversation-mode children and parked-handles. Persistent subagent sessions are the default: every subagent tool exposes `agentId`, and-children park after each turn so later calls can continue the same session. `experimental.tasks`-selects background-task execution only; it does not change child identity or lifecycle.--## Additivity rules--Each PR in this plan must satisfy:--1. New optional fields only on closed contracts (`NextDriverAction`, `DurableStepResult`,- `TurnWorkflowInput.driverCapabilities`); never a changed meaning for an existing `kind`.- The driver run is pinned to its starting deployment while turn workflows route to latest,- so new turn behavior is negotiated the way `turnInbox` was.-2. New payload kinds (turn inbox, hooks, callback route) may be defined early but nothing emits- them until the stage that selects the mode. Receivers land before senders.-3. New modules over edits to shared modules wherever possible. Where a shared codepath must- branch, the branch condition is the flag or a mode value that nothing sets yet.-4. Existing tests pass unmodified through stage 4. Stage 5 intentionally replaces the one-shot- default and updates those expectations.--## Stages--Stages 1–3 are inert: they compile, are fully tested in isolation, and are unreachable in a-production agent. Stage 4 makes the flag mean something. This mirrors the design doc's Delivery-section, folding its A2A step into the baseline.--### Stage 0 — flag plumbing--Add `tasks?: boolean` to `AgentExperimentalDefinition`: authored normalization, compiler copy,-the strict compiled-manifest schema, manifest serialization, root-only enforcement, and a-`ResolvedAgent` projection. The flag does nothing.--Verification: compile/manifest unit tests; a fixture with the flag on behaves identically to one-without it.--### Stage 1 — task foundation--New `packages/eve/src/tasks/` module cluster:--- `TaskStatus`, `TaskView`, `TaskMetadata`, `TaskOutput`, and a pure transition function- enforcing the lifecycle rules (terminal is final; `working <-> input_required`). This stage- also settles how `input_required` exposes its outstanding `InputRequest[]`; agent continuations- accepts only a message follow-up for a terminal task.-- The **durable task run**: a dedicated small workflow per task (precedent: the session-timeout- run). It is the single writer for transitions, consumes commands over its own hook, and- appends a full `TaskView` snapshot per accepted command. Competing completion, cancellation,- and input-response commands serialize here.-- The **session task index**: one new namespaced session-state key holding- `{ taskId, taskRunId, metadata }` entries. Adding a key to `SessionStateMap` needs no session-version- migration.--Verification: exhaustive unit tests on transitions (late completion after `cancelled`,-idempotent cancel, replayed commands); integration tests driving a task run through every-lifecycle path.--### Stage 2 — task tools, undiscoverable--Register the task tools (`task_cancel`, `task_update`)-as framework tools, filtered out of the tool set unless the flag is on. The first implementation-has no child-facing task tool.--- `task_cancel` reads the session task index; an `agentId` continuation resolves a- terminal task's child address through the agent handle store and starts a new task.--Verification: unit tests per tool; a scenario test that the tools are absent from advertised-tool sets and `/agent-info` when the flag is off.--### Stage 3 — delegated execution mode, inert--In the runtime-action dispatch step, add a delegated mode alongside the existing dispatch plan:--1. create the durable `working` task run and record it in the session task index;-2. dispatch the child with a task binding in its adapter state, reusing the handle-store- start/continue planning for identity and addressing;-3. return `task.delegated({ executor, receipt })` with a new `"subagent"` executor kind whose- `data` carries the child acknowledgement (`{ agentId, childSessionId }`). The ack rides the- task-private executor binding, never the model-visible receipt, so dispatch must yield- `childSessionId` before `delegated()` is called;-4. resolve the originating tool call **immediately** with the task receipt- `{ taskId, status: "working" }`.--The handle ack is written at step commit, not by the tool: the background tool provider's-commit path matches `executor.kind === "subagent"` next to its unconditional session task-index write and persists the acknowledgement on the agent handle. There is no author-facing-effect API — framework-owned session writes stay in the provider, and compensation of the-dispatch on parent-step failure is already unconditional (`rejectDelegatedDispatch`).--Step 4 is what keeps the parent turn moving and history provider-valid: the receipt is the one-result the existing key-based batch matching consumes, so the turn continues without a second-result path. A task notification starts or nudges a parent turn and carries its ready result or-error directly. Nothing selects this mode yet.--Verification: integration tests invoking the mode directly; replay tests proving the same-originating call returns the same task, byte-identical `executor.data`, and never dispatches-twice; commit writes the handle ack; parent-step failure compensates through-`rejectDelegatedDispatch` alone; turn cancellation retains the delegation result for the-restarted step.--### Stage 4 — the task wire, and the flag selects the mode--Carry the six flows over the task contract for local and remote children alike, then let-`experimental.tasks` route the two subagent runtime-action kinds into delegated execution:--| Flow | Carrier |-| -------------------------- | ---------------------------------------------------------------- |-| Terminal result or failure | `task.update` command to the task run, terminal snapshot |-| Input request / approval | `task.update` with `input_required` plus the outstanding batch |-| Authorization event | `task.authorization` through the task binding |-| Input response | Parent-session HITL proxy, routed directly to the blocked child |-| Cancellation | `task_cancel`: commit `cancelled`, then propagate executor abort |--Concretely:--- a task-aware sibling of the local subagent channel adapter posts to the task run instead of- the parent turn hook; the existing adapter is untouched;-- the remote callback route gains task payload kinds alongside the existing session and turn- kinds; old payloads are unchanged and old deployments never receive the new kinds;-- routing policy: a local `input_required` snapshot commits task-owned proxy routes and emits the- exact request on the parent session; a fully routed response starts no parent model turn.- Terminal snapshots still wake the parent through the session delivery path;-- parent-session finalization extends the existing end-of-session child termination to- cooperatively cancel live tasks first.--Verification: the design doc's acceptance criteria become a scenario suite plus a new e2e-fixture with the flag on; existing subagent fixtures prove task-mode selection is flag-gated.--### Stage 5 — graduate persistent subagent sessions--Persistent sessions are now the default for subagent dispatch, and-`experimental.subagentPersistentSessions` is removed. The continuation semantics remain:-successful delegation returns an `agentId`, follow-ups address that child, and busy/unreachable-errors remain explicit. This graduation precedes default task execution so persistent identity is-the stable baseline rather than an incidental task-mode behavior.--### Stage 6 — normalize and retire task mode--Converge local and remote subagents onto the same delegated path while preserving authored-definitions, then make tasks the default subagent execution and retire the flag once the-acceptance criteria hold. Both are behavior changes, not additive, and are sequenced last-deliberately; they get their own plans if anything nontrivial surfaces.--Retiring `RuntimeAction` also requires defining `task_cancel` and `task_update` in terms of-`defineTool`, then deleting the `task-control` metadata and dispatch path. Before that migration,-settle the smallest generic `defineTool` execution capability that gives framework tools access to-their durable session and task ownership state; the harness must not branch on either tool by name.--## Settled decisions--1. **Lifecycle ownership.** In tasks mode, the task run is the sole execution-lifecycle writer.- Agent records retain stable identity and private address only. Availability is derived from- nonterminal tasks, with at most one such task per child session; busy agents remain visible in- `<agents>` with their active task id and status.-2. **Wake policy.** Terminal and `input_required` transitions wake a parked parent through the- session delivery path; they are the only wake triggers. Terminal notifications carry the full- result or error so the model needs no follow-up state read. The resulting parent turn is- conditionally delivered: the model sees the framework notification, but it may intentionally- produce no channel message.-3. **Continuation to a busy child.** An `agentId` continuation to a `working` task surfaces `AGENT_BUSY` as a tool- error, matching handle-continuation semantics. Queuing on the task run is deferred; it is- the reversible follow-up if busy errors prove noisy in practice.- The same agent is reserved for the whole dispatch batch even if its first task settles quickly.-4. **Failure taxonomy.** Child failure maps to the `failed` status, and as a consequence of- that transition the task's output carries the error (`TaskOutput.error`). Failure is the- state; the error output is its consequence. This intentionally diverges from MCP, which- reserves `failed` for protocol-level errors.-5. **Progress is deferred.** The first implementation has no child-facing progress contract.--## Known gaps to resolve in flight--1. **Remote parity is release-blocking.** Remote task children must support the same HITL,- authorization, cancellation, and terminal lifecycle as local children before the flag ships.-2. **Blocked vs computing children.** Today a child parked on input or authorization looks like- any running child. The `input_required` transition in stage 4 makes the difference observable- through the parent session's HITL events and must land before the flag ships.--[subagents-as-tasks design]: ./tools-as-tasks.mddiff --git a/research/tool-suspendability-and-lifetime.md b/research/tool-suspendability-and-lifetime.mddeleted file mode 100644index 88c0b555b..000000000--- a/research/tool-suspendability-and-lifetime.md+++ /dev/null@@ -1,377 +0,0 @@-----issue: TBD-status: draft-last_updated: "2026-09-06"------# Tools: suspendability and lifetime as two explicit axes--## 1. Summary--The proposal uses workflow-local bindings for execution data, ordinary yields-for silent progress, and `yield task.postMessage(...)` for parent messages.-There is no `task.setState()` or authored `TaskView.state`.--An authored tool has two independent properties that eve encodes as two-unrelated flags and re-derives with `if` chains at every consumer:--- **Suspendability** — can the body park without holding compute? Implied by- the `"use workflow"` directive; surfaces as `handling.kind === "workflow-tool"`.-- **Lifetime** — does the call end with the harness step, or outlive it as a- durable task? Declared by `execution: "background"`.--This document makes the pair explicit in the compiled tool shape and gives-each of the four cells one `execute` contract. The authoring surface keeps-`execution: "background"` and the third `task` argument, but `task` loses-`delegated`, `send`, `binding`, and the non-serializable `batch`. In their place a background body has one-one-way channel to its task (`yield`) and two round-trip primitives that-already exist for waiting workflow tools: `ask` for the human, and-`ctx.getToken`/`ctx.requireAuth` inside a step for the provider. The latter is-a blocker today for any Connect-backed workflow tool and is in scope.--[Implementation PR #2997](https://github.com/vercel/eve/pull/2997) implements-the compiled shape, fixed receipt, progress and message yields, and removal of-`task.delegated()`. Cancellation of-parked bodies (§7), consolidation of inbound messages (§4.1), and removal of-the remaining deprecated `TaskExec` fields (§6) are still proposed work. The-Devbox example below still depends on the cancellation work. Step-scoped-provider authorization (§3.2) is implemented through a step adapter: pass the-workflow context directly to the helper. Sign-in ends the interrupted step-attempt, parks the workflow, and retries that step with the callback. Earlier-completed steps are retained. Put auth before side effects within a step.--Motivating case: [vercel/internal-agents#2173](https://github.com/vercel/internal-agents/pull/2173)-runs Devbox as a background tool and had to build a relay workflow, a webhook-route, and a `session.completed` adapter because a background `execute()`-cannot park on an external webhook or resolve the requester's token.--## 2. The four cells--| | `lifetime: "step"` | `lifetime: "task"` |-| --------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |-| `suspend: "none"` | `execute(input, ctx)`. Runs in the step; generator yields are `action.partial`. | `execute(input, ctx, task)`. Runs in the step; yields report progress or parent messages, and `return` completes. No `ask`. |-| `suspend: "workflow"` | `execute(input, ctx)` with `"use workflow"`. Turn parks on the run. | `execute(input, ctx, task)` with `"use workflow"`. Receipt to the model; run outlives the step; all of §3. |--Every cell exists today. What changes: the pair is data the compiler writes-once (§5), the same `task` capability means the same thing in both task cells,-and a background workflow body receives `task` at all — today it is silently-absent. `execution: "background"` selects the task column; the directive selects-the workflow row; there is no combined enum.--## 3. Authoring API--### 3.1 The `task` argument and `yield`--`TaskExec` shrinks to identity plus one message constructor. It returns tagged-JSON and does no I/O, so it is replay-safe in a workflow body.--```ts-interface TaskExec {- readonly taskId: string;- postMessage(message: string): TaskMessage;-}-```--A background body may `yield` two kinds of value:--| form | parent | use |-| ----------------------------- | ------------------------------------ | -------------------------------------- |-| `yield value` (untagged) | not woken; streamed as progress | transient progress |-| `yield task.postMessage(msg)` | woken with `msg` as the turn's input | something the parent should act on now |--Ordinary yields from authored background tools become stream-only progress.-Subagent update delivery stays unchanged. `postMessage` sends one message-attributed to the task under the existing task-delivery policy.--The model receives `{ status: "working", taskId }` after task admission.-Workflow-local bindings carry the data needed after a durable wait; replay-reconstructs them from recorded steps and events. No separate authored task-snapshot is needed to resume the body.--### 3.2 Replies: `ask` and provider authorization--`yield` never asks. Anything that needs a reply is a suspension point with a-typed reply, disjoint from `yield`:--| direction | primitive | reply |-| ------------------------ | -------------------------------------------- | ----------------------------- |-| body ↔ human | `ask(ctx, request)` from `eve/workflow` | `{ optionId?, text? }` |-| body ↔ identity provider | `ctx.getToken` / `ctx.requireAuth` in a step | a token, or a park on sign-in |--The parent reaches the body only through `ctx.abortSignal`.--**`ask`** is unchanged from the waiting-tool contract in-`docs/tools/workflows.mdx`: the request travels over the run's `request`-channel, the task moves to `input_required`, the channel renders it like-`ask_question`, the answer resumes the hook. Richer response schemas are-deferred. `postMessage` tells the agent something; `ask` asks the human-something. A body never posts a question for the parent to relay.--**Provider authorization** is the change. `getToken`/`requireAuth`-throw in a workflow body. Passing the context directly into a step installs-requester-scoped auth there. Contract:--- Both are callable inside a `"use step"` that received `ctx` as a direct argument. They resolve- under the session identity in the run's serialized context, through the- shared authorization capability (`runtime/authorization-context.ts`). Ordinary tools and- workflow steps use the same `getToken`/`requireAuth` implementation. Connection search and- discovered connection tools use its underlying scoped execution for callback completion,- challenges, and rejection after sign-in. The step adapter reconstructs the capability under that identity;- the workflow body retains throwing implementations.-- The auth capability returns a shared authorization signal. The executing runtime supplies- the callback hook and owns suspension/resumption; the auth implementation does not choose- between an agent turn and an authored workflow. Interactive providers without a callback- address fail instead of leaving the model to improvise a sign-in flow.-- A token is returned to the step and never enters the body's replay log.-- Interactive authorization does not return an `AuthorizationSignal` to the- model. The workflow forwards the challenge through its owner's existing- `authorization-request` message; the task moves to `input_required` and the- parent channel renders `authorization.required`. The callback resumes the- workflow's hook and retries the interrupted step. To the body this is one- `await`; side effects before authorization must be safe to retry.-- The loop guard is unchanged: a token rejected immediately after- authorization fails the run.-- In the body itself both methods keep throwing.--### 3.3 Example: Devbox as a background durable tool--Against the api-devbox contract the v PR already codes to: one webhook URL at-`createTask`; `taskStateChange` posts with-`state ∈ { pending, running, attention-required, complete, errored }`; a-`prompt` endpoint for follow-ups; a result `{ summary, exitStatus, error?, prs? }`-from `getTask`. `Hook` is an `AsyncIterable`, so one webhook receives every-state change for the task's lifetime.--One run owns the whole api-devbox task. Every follow-up — an-attention-required answer, or "now fix the review findings" — goes through-`ask`, so there is no continuation argument and no second tool.--```ts-export default defineTool({- execution: "background",- description: "Start repository work in api-devbox and see it through. Use once per task.",- inputSchema: devboxInputSchema, // repos, prompt, title?, assistant?, model?, pr?- async execute(input, ctx) {- "use workflow";-- const events = createWebhook(); // registered before the task exists- const devbox = await createDevboxTask(input, events.url, ctx); // step-- try {- for await (const request of events) {- const change = parseTaskStateChange(await request.json());- if (change === null || change.taskId !== devbox.taskId) continue;-- switch (change.state) {- case "pending":- case "running":- continue;-- case "attention-required": {- // api-devbox does not carry the question in the webhook; the task page does.- const answer = await ask(ctx, {- prompt:- `Devbox needs your input to continue "${devbox.title}".\n` +- `Open ${devbox.taskUrl} to see what it is asking, then reply here.`,- display: "text",- allowFreeform: true,- });- await promptDevbox(devbox.taskId, answer.text ?? "", ctx); // step- continue;- }-- case "complete": {- const result = await readDevboxTask(devbox.taskId, ctx); // step: authoritative- if (input.pr === false) {- const next = await ask(ctx, {- prompt: `Review finished:\n\n${result.summary}\n\nApply these findings?`,- display: "confirmation",- options: [- { id: "apply", label: "Apply the findings", style: "primary" },- { id: "done", label: "Done" },- ],- });- if (next.optionId === "apply") {- await promptDevbox(devbox.taskId, "Apply the review findings and open a PR.", ctx);- continue;- }- }- return { summary: result.summary, prs: result.prs ?? [], taskUrl: devbox.taskUrl };- }-- case "errored": {- const result = await readDevboxTask(devbox.taskId, ctx);- throw new FatalError(result.error ?? `Devbox task ${devbox.taskId} errored`);- }- }- }- throw new FatalError(- `Webhook for Devbox task ${devbox.taskId} closed before a terminal state`,- );- } finally {- if (ctx.abortSignal.aborted) await stopDevbox(devbox.devboxId, ctx); // step- }- },-});--async function createDevboxTask(input: DevboxInput, webhookUrl: string, ctx: ToolContext) {- "use step";- const { token } = await ctx.getToken(devboxUserAuth); // parks the run on sign-in (§3.2)- const client = createDevboxClient({- token,- onUnauthorized: () => ctx.requireAuth(devboxUserAuth),- });- const snapshot = await selectSnapshot(client, input.repos);- const set = await client.createTaskSet(input.title ?? deriveTitle(input.prompt));- const created = await client.createTask({- setId: set.set_id,- snapshotId: snapshot.id,- prompt: promptWithDeliverable(input),- assistant: input.assistant,- model: input.model,- webhookUrl,- });- return {- taskId: created.task_id,- devboxId: created.devbox_id,- title: input.title ?? deriveTitle(input.prompt),- taskUrl: devboxTaskUrl(created.task_id),- };-}-```--`promptDevbox`, `readDevboxTask`, and `stopDevbox` are one-call steps over the-same client; snapshot selection and prompt construction are the PR's helpers.--What this buys over the bridge:--- attention-required is not terminal. The run parks on `ask`, the requester- answers on v's channel (only the requester — `ask` already enforces that on- Slack), and the answer is posted from the same run.-- A review can be followed by a fix without a second launch.-- Sign-in is not a state the tool returns; `getToken` parks the run under the- requester's identity.-- Cancellation stops the sandbox from `finally` (§7).-- Duplicate or out-of-order webhooks are harmless: other tasks' posts are- skipped, a repeated `attention-required` re-asks, and a post after `return`- hits a hook nobody reads.--Deleted: the relay workflow and route, the `session.completed`/`subagentName`-adapter, the launch and follow-up fingerprint guards (replay is the idempotency-mechanism), the `task` continuation argument, and `stop_devbox_task`.--## 4. Task messages--### 4.1 Delivery--`postMessage` is not a task command and does not touch the view. It is the-parent-session `send` the child workflow already issues for updates-(`wakeTaskUpdateParentStep`), carrying the author's message attributed to the-task instead of the framework's `Background task … update:` prose, deduplicated-by the same delivery id. The receiving turn runs under the existing-task-delivery policy.--Use one `TaskInboundMessage` contract for parent-bound traffic, subsuming-`TaskInboundUpdate` rather than keeping separate message and update queues.-Subagent updates retain their formatting and delivery policy. `TaskProgress`-remains the stream-only contract. The shared delivery path must preserve-deduplication ids, buffer messages until dispatch acknowledgement, and drain-persisted reports before task completion.--### 4.2 Wiring--- `runBody` already sends each yield as a `RunReport`. The owner maps- `TaskMessage` → parent `send`, untagged → progress on the stream. Subagent- reports retain their parent wakes through the shared message path.-- `createWorkflowToolBackgroundExecute` returns `{ status: "working", taskId }` after task admission. It never waits for a body yield.-- The `"Background tools cannot return AsyncIterable"` guard goes; the- ordinary background executor iterates the body, routes progress and messages,- and completes with the return value.-- Step-scoped auth: `createWorkflowToolContext` builds `getToken`/`requireAuth`- that work under ambient step context and throw otherwise;- `runRequestToInputRequestPayload` maps the `authorization` request variant to- the `authorization.required` task event the child workflow already forwards.-- Subagents and the tool-run keep binding executors through the internal- `delegated` seam. No public surface.--## 5. Compiled shape--`CompiledToolBehavior` carries the pair as data:--```ts-readonly shape: {- readonly lifetime: "step" | "task";- readonly suspend: "none" | "workflow";-};-```--`handling.kind === "workflow-tool"` collapses into `suspend: "workflow"` plus-its `workflowId`. `prepareToolBehavior`, the background-call filter in-`tool-loop.ts`, `dispatchTaskStep`, and `createWorkflowToolBackgroundExecute`-switch on `shape` instead of re-deriving it. `defineTool` overloads gate the-capabilities by cell: `task` is available only for background execution, and-`ask` requires a workflow body.--## 6. Removed--From the public `TaskExec`: `delegated()` and `TaskExecutorBinding` (a tool-parks on the external system from a workflow body instead of handing off by-sentinel; the seam stays internal), `send()` (not restart-safe by its own-contract; dominated by `yield`), `binding` (the framework callback wire stops-being reachable from authored code), `session` (use `ctx.session`), and `task`-(the durable task internals remain framework-owned).--Pre-1.0: no shim. The only known external consumer is the Devbox bridge; §3.3-is its replacement. The `agent-background-tools/export.ts` fixture is rewritten-as a workflow body.--Extension manifests requiring removed delegation contracts are rejected before-their code runs. Keep the historical contract fixtures immutable, but compile-only the versions still declared supported.--## 7. Cancellation--`task_cancel` aborts `ctx.abortSignal` in the run and waits the existing grace-period — unchanged. What changes: a body parked on a hook, webhook, `ask`, or-authorization does not observe the signal today and is abandoned after the-grace period without running `finally`. The tool-run must race the parked-await against its control inbox so `finally` runs before the run ends;-otherwise external cleanup has no home and authors reach for a second tool.--With §3.2's auth change, this is one of two `execution/` changes beyond wiring.-Both are required for the Devbox migration.--## 8. Invariants--- A tool's cell is fixed at compile time and visible in the manifest; `task`- exists iff `execution === "background"`.-- `yield` is the only one-way channel from a body to its task, and it never- asks. There is no post-return path.-- Workflow-local values survive durable waits through replay; there is no- authored `TaskView.state` snapshot.-- A fixed `{ status: "working", taskId }` receipt is observed exactly once and- never depends on a body yield.-- A token never enters a workflow body's replay log.-- Subagent task behaviour is unchanged.--## 9. Deferred--- Structured `ask` responses (a response schema instead of- `{ optionId?, text? }`).-- Externally readable authored task snapshots, pending a concrete consumer.--## 10. Testing--- Unit: message descriptor tagging; `defineTool` overload typing via- `expectTypeOf`.-- Integration: ordinary yields remain silent; `postMessage` → parent `send`;- receipt independent of body yields; local values remain usable after a- durable wait; `getToken` in a- step of a background run resolves under the session identity; a step-raised- authorization requirement parks the task `input_required` and resumes on- callback; `getToken` in the body still throws.-- Scenario: compiled `shape` for each cell.-- E2E: rewrite `agent-background-tools/export.ts` as a workflow body that- parks on `createWebhook`, posts a message on callback, and- completes. Add a body that parks on `ask` from a background run. Sign-in- cannot be driven in e2e; it stays at integration tier.diff --git a/research/tools-as-tasks.md b/research/tools-as-tasks.mddeleted file mode 100644index 6ff0c581c..000000000--- a/research/tools-as-tasks.md+++ /dev/null@@ -1,471 +0,0 @@-----issue: https://github.com/vercel/eve/issues/1084-status: draft-last_updated: "2026-08-20"------# Subagents as tasks--## Summary--Under an opt-in `experimental.tasks` mode, eve should represent long-running work as durable,-addressable tasks. This plan applies that model only to local and remote subagents. A subagent call-returns a task receipt after dispatch instead of keeping the parent turn blocked until the child-finishes. The parent receives result-bearing lifecycle notifications and can cancel the task with-a framework-owned tool. The child can intentionally report progress to its parent with one-framework-owned tool.--Without the flag, current subagent behavior must remain unchanged. The implementation uses a-generic background `defineTool` execution contract so the harness does not classify subagents.--This draft is based on the [Tools as Tasks proposal], the earlier background-task plan in-[PR #1085], and the storage-boundary findings from the closed [PR #1190] implementation spike.--## Current behavior--Authored tools expose `execute(input, ctx)`. Subagents are different: eve lowers them to-execute-less tools carrying `runtimeAction` metadata, then handles them after the model step-outside the authored tool API. The split is visible in the current-[`ToolDefinition` contract] and [`createNodeHarnessTools` lowering].--The harness first lets the AI SDK run ordinary tool calls. It then collects subagent tool calls-into a pending runtime-action batch. The turn workflow dispatches that batch and waits for all-results before starting the next model step. See the [runtime-action park path], the-[serial dispatch loop], and the [turn-level wait]. The dispatch loop starts children one by one;-once started, their runs proceed independently. The parent still waits for the whole batch.--Local and remote children also have different communication paths:--| Flow | Local child today | Remote child today |-| --------------------------------- | -------------------------------------- | ------------------------------------------------------------------- |-| Terminal result or failure | Resumes the parent turn hook | Posts `session.completed` or `session.failed` to the callback route |-| Input request, including approval | Forwarded by the subagent adapter | No callback shape |-| Authorization event | Forwarded by the subagent adapter | No callback shape |-| Input response | Routed to the child continuation token | No callback shape |-| Cancellation | Descendant cancellation | Remote `cancel-turn` request |--The [local subagent adapter] forwards input and authorization events to an active parent turn.-The [remote callback route] accepts only terminal completion and failure. This is why progress-and human input cannot be added cleanly as channel-only behavior: the parent harness and remote-transport do not share a non-terminal child protocol. Current input responses use-[child response routing], while [descendant cancellation] selects separate local and remote-cancel paths.--## Goals--- Let a parent continue its turn while delegated work runs.-- Wake the parent through lifecycle notifications instead of model-paced task checks.-- Let a child intentionally report progress to its parent instead of leaving progress to- channel-layer guesswork.-- Carry progress, input requests, authorization events, results, failures, and cancellation over- one local and remote task contract.-- Keep task state durable across turns and replay.-- Preserve provider-valid history. The originating tool call receives exactly one result.-- Keep authored subagent files unchanged.-- Give local and remote subagents the same externally visible lifecycle.-- Align task status and control semantics with the MCP Tasks extension where the contracts match.--## Non-goals--- Exposing an MCP Tasks server or client endpoint in this work.-- Stabilizing the experimental background `defineTool` contract for general authored tools.-- Changing connections, skills, or dynamic workflows.-- Rolling back external side effects after cancellation.-- Retrying failed subagent work automatically.-- Streaming every progress event into model context.-- Sharing task handles across parent sessions.--## Terminology--A **task** is one unit of work with a durable identity and lifecycle. A task is not an agent-session. Terminal tasks never restart.--A **child session** is the resumable conversation owned by a delegated agent. A follow-up sent to-the same agent creates a new task bound to the same `agentId`. This matches A2A's-separation between immutable tasks and a longer-lived [`contextId`].--A **runtime action** is today's framework-internal dispatch mechanism behind execute-less tools-such as subagent calls. This plan changes how the runtime executes the two subagent kinds, not-how authored files lower to them.--A **synchronous invocation** runs inside the current harness step. Its result may trigger another-model step in the same turn.--A **background task** is owned by the parent session, not the originating turn. It may complete,-request input, or emit progress after that turn ends.--An **agent address** is the persistent identity and private routing record for one child session.-Tasks own execution lifecycle and availability; agent addresses do not duplicate `working` or-`input_required`. At most one nonterminal task may target one child session. The model-visible-`<agents>` projection keeps an occupied agent visible as busy and names its active task.--**Delegated execution** is the outcome of a background tool handing lifecycle ownership to an-external executor. The tool's `execute` returns once that executor acknowledges the work; the task-stays `working`, and every later transition arrives over the task wire.--`completed`, `failed`, and `cancelled` are terminal statuses. `input_required` is not terminal,-but it is ready for parent action. Entering either condition wakes the parent so it never-deadlocks while its child waits for input.--## Authoring contract--The root agent opts in:--```ts-export default defineAgent({- experimental: {- tasks: true,- },-});-```--The flag changes only local and remote subagent calls. Every such call is registered as a-background `defineTool` definition and runs in the AI SDK tool loop. Without the flag, the same-subagent tools retain their existing `runtimeAction` path.--The generic execution contract is:--```ts-defineTool({- execution: "background",- async execute(input, ctx, task) {- const executor = await startExternalWork(input, task.binding);- return task.delegated({- executor: executor.binding,- receipt: executor.receipt,- });- },-});-```--An ordinary `execute` return completes the task with that value. `task.delegated(...)` ends the-tool call with a `working` receipt while the external executor retains lifecycle ownership. The-task runtime adds `taskId` and `status` to the tool-owned receipt.--The parent receives these framework-owned tools:--```ts-interface TaskParentTools {- task_cancel(input: { taskIds: string[] }): Promise<TaskToolResult<boolean>>;- task_update(input: { message: string }): Promise<{ status: "sent"; taskId: string }>;-}-```--Human responses are not a model capability. Clients answer the ordinary `input.requested` event-on the parent session, and eve routes matching responses directly to the blocked child.--The controls have distinct behavior:--- Passing `agentId` to the original subagent tool sends a follow-up after the prior task became terminal, creating a new task- bound to the same child session. It never reopens a terminal task or answers HITL.-- `task_cancel` requests cooperative cancellation. A committed terminal state is final, so a late- child result cannot revive a cancelled task.--There is no child-facing task tool in the first implementation. Child-to-parent lifecycle and-HITL communication is framework-owned; progress reporting remains a separate follow-up.--### Task view--```ts-type TaskStatus = "working" | "input_required" | "completed" | "failed" | "cancelled";--interface TaskView {- readonly taskId: string;- readonly status: TaskStatus;- readonly statusMessage?: string;- readonly metadata: TaskMetadata;- readonly lastOutput?: TaskOutput;-}--interface TaskMetadata {- readonly kind: string;- readonly name: string;-}--type TaskOutput =- | { readonly type: "result"; readonly data: JsonValue }- | { readonly type: "error"; readonly data: JsonValue };-```--When `status` is `input_required`, the view must also expose the outstanding `InputRequest[]`.-Whether that becomes a discriminated `TaskView` variant or a status-specific field is an API-decision, not an implementation detail.--Task IDs are minted identifiers. They are never child session IDs, continuation tokens, callback-tokens, or authorization capabilities. A parent session owns many tasks, and lookup verifies both-the parent `sessionId` and `taskId`.--### Original call result--After durable task creation and child-dispatch acknowledgement, the originating subagent call-gets one receipt:--```json-{- "agentId": "ag_research:...",- "taskId": "task_01K...",- "status": "working"-}-```--The eventual child result must not become a second result for that call. A framework-authored-task notification starts or nudges a parent turn and carries the ready state's result or error-directly. The notification is separate append-only conversation input, so history remains-provider-valid without a second read racing the queued notification.--## Task state and ownership--The mutable task record should live in a dedicated durable task run. That run is the single writer-for lifecycle transitions and appends a full `TaskView` snapshot after each accepted command.-Other paths submit commands to that run and read its snapshots.--The parent session stores only a live-task index:--```ts-interface SessionTaskIndexEntry {- readonly metadata: TaskMetadata;- readonly taskId: string;- readonly taskRunId: string;-}-```--This changes one sentence in the Notion proposal, which places the record directly in durable-session state. The [PR #1190] spike found that boundary unworkable: session state is threaded-through step results, while callback routes and child executors need to update task state without-holding the current session snapshot. A task-owned run also serializes competing completion,-cancellation, and input-response transitions.--The lifecycle rules are:--```text-working <-> input_required- | |- +-----> completed- +-----> failed- +-----> cancelled--completed, failed, and cancelled are final-```--- A background task survives turn completion and turn cancellation.-- It ends when it completes, fails, is cancelled, or its parent session ends.-- Parent-session finalization cooperatively cancels every live task before completing.-- Task cancellation commits the `cancelled` state before propagating the executor abort.-- Replayed creation for the same parent session and tool-call ID returns the same task and must not- dispatch duplicate work.--## Delegated execution--Today, without `experimental.tasks`, the runtime parks subagent tool calls, dispatches them as a-batch after synchronous calls, and holds the turn until every action in the batch resolves (the-[runtime-action park path], [serial dispatch loop], and [turn-level wait]). With the experiment,-the AI SDK executes subagent definitions through the generic background-tool path:--1. The harness creates a durable `working` task for the subagent call.-2. It dispatches the child with the task binding.-3. The child acknowledges its private address, which is persisted on the agent record immediately.-4. The originating call receives its receipt and the turn continues.--Everything after acknowledgement — progress, input requests, authorization, terminal outcome —-arrives over the task wire instead of resolving the dispatch. Task creation, parent indexing, the-commit barrier, readiness delivery, and compensation are generic background-tool mechanisms.-Local and remote definitions own only child dispatch, agent-handle effects, and mapping the task-wire onto their executor.--### Workflow host--The dynamic-workflow sandbox drives subagent calls through the same harness tool definitions,-but its host (`createWorkflowHostTools`) still executes only `runtimeAction` tools. With-`experimental.tasks` enabled, the background subagent definitions pass the `workflowCallable`-advertising filter and are then dropped by the host, so no host tools remain and the workflow-tool is not advertised. This is an accepted scope cut: workflows are unavailable under the-experiment.--Graduating the experiment removes the `runtimeAction` dispatch path rather than extending it.-The workflow host then executes background `defineTool` definitions through the same-task-creating `execute` path the model loop uses, and `execution: "background"` becomes the-workflow-callable contract, retiring the manual `workflowCallable` flag.--## Parent and executor wire contract--The parent-facing half of a task binding is passed to a local or remote child executor. Routing-credentials never enter model-visible context, history, task events, or compaction summaries.--```ts-interface TaskBinding {- readonly taskId: string;- readonly token: string;- readonly url: string;-}--interface TaskExecutorBinding {- readonly inbound: { readonly url: string; readonly token: string };-}--type ParentInbound =- | { readonly type: "task.update"; readonly task: TaskView }- | { readonly type: "task.authorization"; readonly taskId: string; readonly data: JsonValue };-```--An `input_required` transition carries the full outstanding request batch in its task snapshot.-The parent emits those requests through the normal `input.requested` stream contract. Matching-responses sent to the parent session route directly through its private child proxy. Authorization-uses the same task binding but remains a distinct event because it has different disclosure rules.--The five flows that split across two transports today all converge on this one contract, for-local and remote children alike:--| Flow | Over the task wire |-| --------------------------------- | ------------------------------------------------------------- |-| Terminal result or failure | `task.update` with a terminal snapshot |-| Input request, including approval | `task.update` with `input_required` and the outstanding batch |-| Authorization event | `task.authorization` |-| Input response | Parent-session proxy addressed by the recorded request id |-| Cancellation | `task_cancel`, committed then propagated to the executor |--The proposed routing policy makes terminal updates and `input_required` wake a parked parent-session. During an active turn, inbound task events wait for the next safe step boundary. They-never interrupt an active model call. A task notification starts a conditionally delivered parent-turn: the model sees the notification and may act on it, but eve does not require a user-visible-channel message. A human message or input response remains required delivery.--```mermaid-sequenceDiagram- participant M as Parent model- participant H as Parent harness- participant T as Durable task run- participant C as Child executor-- M->>H: subagent tool call- H->>T: create working task- H->>C: dispatch with TaskBinding- C-->>H: acknowledge private child address- H-->>M: task receipt- M->>H: continue turn-- C->>T: task.update or authorization- T->>H: full task snapshot- H->>H: queue until safe boundary- H-->>M: task notification with result or error-```--### Agent-to-agent dependency--This plan depends on the session-addressing route and authentication envelope from the first-phase of the [agent2agent communication proposal]. Tasks and agent handles must not collapse into-one record:--- the task identifies the current unit of work;-- the handle identifies the reusable child session;-- the task's private binding lets the parent session route HITL and guarded cancellation;-- resuming that child creates a new task bound to the same handle.--The A2A draft currently records a handle after the child's first result. That is too late for-direct HITL and cancellation during `working` or `input_required`. Task dispatch must persist the private executor-binding as soon as the child acknowledges its session. The same acknowledgement may create or-update the reusable agent handle. Both records may reuse the A2A inbox route, but routing tokens-belong in one shared credential store rather than two independent session-addressing mechanisms.--## MCP alignment--The current [MCP Tasks extension] provides the closest standard vocabulary:--- `working`, `input_required`, `completed`, `failed`, and `cancelled` statuses;-- a durable task handle returned instead of a final tool result;-- `tasks/get`, `tasks/update`, and `tasks/cancel` operations;-- full task snapshots in `notifications/tasks`;-- terminal states that do not change.--eve's `task_cancel` maps to cancellation. Result-bearing notifications replace a model-facing-`tasks/get` operation: the model receives ready state at the transition that wakes it instead of-performing a second read that can race the queued notification. eve is not implementing the MCP-wire protocol in this work.--One semantic difference is decided. MCP treats a tool-level `isError: true` result as-`completed`; `failed` is reserved for JSON-RPC execution failure. eve diverges: child failure-maps to the `failed` status, and as a consequence of that transition the task's output carries-the error (`TaskOutput.error`). Failure is the state; the error output is its consequence. The-model reasons about one lifecycle field instead of cross-referencing a completed status against-an error payload.--Cancellation also differs. MCP `tasks/cancel` acknowledges intent and allows the task to finish in-a non-cancelled state. This draft commits `cancelled` before propagating abort and discards late-results. That stronger guarantee is useful for model reasoning, but it is an eve semantic rather-than MCP compatibility.--## Delivery--1. Land the final-shape task kernel inert: types, transition rules, durable task run, and session- index. No public flag, tool, writer, or existing production caller reaches it.-2. Land authenticated create-once session creation as an independently complete channel feature.-3. Behind `experimental.tasks`, land the complete background-task runtime contract at once:- final tools, persistence writer, stable agent identity, local/remote HITL and cancellation,- receipts, and usage retention.-4. Gate that runtime with deterministic end-to-end acceptance in every supported world.-5. Land the final TUI consumer as one state machine, including background sections, idle wakes,- remote child streaming through the parent, and authoritative finalization.--## Acceptance criteria--- With `experimental.tasks` absent or false, existing tool results, events, cancellation, and- subagent blocking behavior do not change.-- With it enabled, a slow subagent returns a task receipt and the parent can take another model- step before the child completes.-- With it enabled, the workflow tool is not advertised to the root session until graduation adds- background-tool execution to the workflow host.-- The original tool call has exactly one result in durable history. Later task output cannot be- attached to that call a second time.-- Local and remote subagents support the same five parent-child flows.-- Terminal and `input_required` transitions wake the parent. Terminal notifications carry the- task result or error directly, and input requests use the parent session's ordinary HITL events.-- Parent-session responses route directly to the intended local task child without a parent model- turn and cannot cross task or session ownership. Follow-up messages use the original subagent tool with `agentId`.-- One child session owns at most one nonterminal task; repeated sends return `AGENT_BUSY` and do- not queue.-- Cancellation is cooperative and idempotent. A late completion cannot overwrite `cancelled`.-- Replay returns the same task ID for the same originating call and never dispatches the child- twice.-- Completing the parent session cancels its live tasks.-- Resuming an existing child session creates a new task with a new task ID and the same `agentId`.-- Background budgets are best-effort: each local child is capped from the parent's remainder at- its dispatch time, but no reservation couples sequential dispatches, so aggregate grants can- exceed the parent's remaining session limits. The child's reported usage is retained on the- terminal task snapshot (internal, not model-visible) so strict accounting can land later- without data loss.--## Open questions--1. Should `TaskView` include a monotonic revision for notification deduplication, or can the task- run's stream index remain internal?-2. What retention and TTL apply to terminal records and unanswered `input_required` tasks?-3. What is the cross-deployment version negotiation for task callbacks during rolling deploys?-4. How are repeated progress messages coalesced before they start parent model turns?-5. How are child token usage and remaining parent budgets accounted after a background child- completes on a later turn?-6. Should background tool inputs be constrained to `JsonValue`? Today they cross the- harness ↔ executor boundary as `unknown`: schema parsing can transform (a standard schema- may emit e.g. a `Date`), so JSON-ness is not guaranteed by construction, and annotating the- boundary alone would verify nothing. An honest constraint must land at the authoring layer- (`TInput extends JsonValue` for background-capable tools) or as per-call runtime validation;- deferred until background tools need durable/serializable inputs.--Two former open questions are settled and recorded in the [delivery plan]: failure taxonomy-(`failed` carries the error output) and wake policy (terminal and `input_required` wake a-parked parent; nothing else does).--[delivery plan]: ./subagents-as-tasks-implementation.md-[Tools as Tasks proposal]: https://app.notion.com/p/3a5e06b059c48004ad1df5c7cfa58eea-[agent2agent communication proposal]: https://app.notion.com/p/3abe06b059c4800da816f20918c5e628-[PR #1085]: https://github.com/vercel/eve/pull/1085-[PR #1190]: https://github.com/vercel/eve/pull/1190-[MCP Tasks extension]: https://modelcontextprotocol.io/extensions/tasks/overview-[`contextId`]: https://a2a-protocol.org/latest/topics/life-of-a-task/#group-related-interactions-[`ToolDefinition` contract]: https://github.com/vercel/eve/blob/a5acde8255f5e8fe38d13755a93111bce841bf2a/packages/eve/src/public/definitions/tool.ts#L117-L142-[`createNodeHarnessTools` lowering]: https://github.com/vercel/eve/blob/a5acde8255f5e8fe38d13755a93111bce841bf2a/packages/eve/src/execution/node-step.ts#L166-L234-[runtime-action park path]: https://github.com/vercel/eve/blob/a5acde8255f5e8fe38d13755a93111bce841bf2a/packages/eve/src/harness/tool-loop.ts#L1949-L1996-[serial dispatch loop]: https://github.com/vercel/eve/blob/a5acde8255f5e8fe38d13755a93111bce841bf2a/packages/eve/src/execution/dispatch-runtime-actions-step.ts#L104-L240-[turn-level wait]: https://github.com/vercel/eve/blob/a5acde8255f5e8fe38d13755a93111bce841bf2a/packages/eve/src/execution/turn-workflow.ts#L159-L198-[local subagent adapter]: https://github.com/vercel/eve/blob/a5acde8255f5e8fe38d13755a93111bce841bf2a/packages/eve/src/execution/subagent-adapter.ts#L18-L59-[remote callback route]: https://github.com/vercel/eve/blob/a5acde8255f5e8fe38d13755a93111bce841bf2a/packages/eve/src/runtime/session-callback-route.ts#L13-L130-[child response routing]: https://github.com/vercel/eve/blob/a5acde8255f5e8fe38d13755a93111bce841bf2a/packages/eve/src/execution/route-child-delivery.ts#L6-L32-[descendant cancellation]: https://github.com/vercel/eve/blob/a5acde8255f5e8fe38d13755a93111bce841bf2a/packages/eve/src/execution/cancel-descendant-turns-step.ts#L66-L147