The Open Framework for Building Agents
feat(eve): configure background task reporting on message sends (#3478)
Rui3be0b749e2ce
diff --git a/.changeset/background-task-wake-policy.md b/.changeset/background-task-wake-policy.mdnew file mode 100644index 000000000..031905d1a--- /dev/null+++ b/.changeset/background-task-wake-policy.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Add `taskDeliveryPolicy: "auto" | "cohort"` to message sends. New channel sessions default to `"auto"`, allowing independently useful reports or silence until related work settles; schedules default to `"cohort"`, and explicit sends can select or update the session's policy.diff --git a/.changeset/chat-channel-declaration-chunks.md b/.changeset/chat-channel-declaration-chunks.mdnew file mode 100644index 000000000..53634be2b--- /dev/null+++ b/.changeset/chat-channel-declaration-chunks.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Align the bundled Chat SDK and adapters with version 4.41.0. Chat SDK channel types now reference the installed `chat` package so external adapters and handlers share the same type identity; `chat` is an optional peer for this integration.diff --git a/.syncpackrc.json b/.syncpackrc.jsonindex b8c2e9b72..4d74a2b89 100644--- a/.syncpackrc.json+++ b/.syncpackrc.json@@ -10,6 +10,11 @@"!**/templates/**"],"versionGroups": [+ {+ "label": "Chat SDK declarations and consumers must use matching versions",+ "dependencies": ["chat", "@chat-adapter/*"],+ "dependencyTypes": ["dev", "prod"]+ },{"label": "Extension fixtures declare a broad eve peer range like published extensions","dependencies": ["eve"],diff --git a/docs/channels/overview.mdx b/docs/channels/overview.mdxindex cacdd9343..8f7d4f94e 100644--- a/docs/channels/overview.mdx+++ b/docs/channels/overview.mdx@@ -76,6 +76,54 @@ When eve doesn't ship a channel for your surface, build one with `defineChannel`A cross-channel `send(...)` supplies input to the agent and invokes the model on the destination channel. eve does not currently provide a direct cross-channel provider-message queue. To post without starting a turn, use the provider API. See [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications) when delivery also needs application-managed retries and deduplication.+## Background task results++Pass `taskDeliveryPolicy` to `send(...)` to choose how the session reports background results:++- `"auto"` (default for new channel sessions): ready results can invoke the parent while other tasks continue. The parent reports results that are useful independently and stays silent when a useful answer needs unfinished work.+- `"cohort"`: wait for overlapping tasks to settle, then deliver their terminal outcomes together.++```ts title="agent/channels/reports.ts"+import { defineChannel, POST } from "eve/channels";+import { localDev, routeAuth } from "eve/channels/auth";++export default defineChannel({+ routes: [+ POST("/reports", async (request, { from }) => {+ const auth = await routeAuth(request, localDev());+ if (auth instanceof Response) return auth;+ const session = await from("daily-report").send("Prepare the daily reports.", {+ auth,+ taskDeliveryPolicy: "cohort",+ });+ return Response.json({ sessionId: session.id });+ }),+ ],+});+```++The option is available on channel-local `from(...).send(...)`, cross-channel+`to(...).send(...)`, fixed-session `send(...)`, Chat SDK `bridge.send(...)`, and client+sends. An explicit value+updates the session's policy, including pending background tasks; later sends that+omit it preserve that policy. A cross-channel send carries its setting through the+receiver's `from(...).send(...)` unless that call supplies an explicit value.++[Schedules](../schedules#background-task-results) default new sessions to `"cohort"`.+A schedule handler can pass `taskDeliveryPolicy: "auto"` to `send(...)` to override+that default. Child sessions use their own policy.++With `"auto"`, a model call may finish without a user-visible message. Results+already queued from the same cohort may share a turn. Each reporting turn receives+the whole cohort, including pending tasks and available outputs, so previously+withheld results remain available for a later combined report.++Input requests and explicit task messages remain eligible for delivery under+either policy. Failure and cancellation update task state immediately; their+automatic reports follow the selected policy. User messages follow `turnPolicy`.+See [Completion batching](../subagents#completion-batching) for cohort membership+and result ordering.+## Relationship to the Chat SDKeve uses the [Chat SDK's card-builder components](https://chat-sdk.dev/docs/api/cards) (Cards, Buttons, Actions, etc.) for composing rich Slack messages. When you build a card with the [Slack channel](./slack), the underlying primitives come from the Chat SDK and get converted to Slack Block Kit at post time.diff --git a/docs/schedules.mdx b/docs/schedules.mdxindex 3912172c9..262b65f21 100644--- a/docs/schedules.mdx+++ b/docs/schedules.mdx@@ -44,7 +44,7 @@ export default defineSchedule({});```-You can write the same thing as a plain `.md` file: its frontmatter takes `cron` and nothing else, and the body is the prompt.+You can write the same thing as a plain `.md` file: its frontmatter takes `cron`, and the body is the prompt.`agent/schedules/cleanup.md`:@@ -88,6 +88,40 @@ The `auth` option controls which principal the session runs as. A handler may inA handler-form session runs on the same durable runtime engine as any other session, so it can park (durably suspend), for instance when the channel handoff is waiting for a Slack reply. Only markdown task mode is barred from waiting.+## Background task results++New sessions started by schedules default to `"cohort"`: background+outcomes wait for overlapping tasks to settle before waking the parent. To report+independently useful results as they arrive, pass `taskDeliveryPolicy: "auto"` to+`send(...)` inside a schedule handler:++```ts title="agent/schedules/digest.ts"+import { defineSchedule } from "eve/schedules";+import slack from "../channels/slack";++export default defineSchedule({+ cron: "0 9 * * *",+ run({ to, waitUntil, appAuth }) {+ waitUntil(+ to(slack, { channelId: "C0123ABC" }).send("Prepare the daily reports.", {+ auth: appAuth,+ taskDeliveryPolicy: "auto",+ }),+ );+ },+});+```++The option belongs to `send(...)`. Markdown schedules use the `"cohort"` default;+use a handler when you need to override it. Sending to an existing session preserves+its policy unless the send supplies an explicit value.++Under `"auto"`, a model call may finish silently while related work is pending.+Available results remain in the next reporting context so the parent can combine+previously withheld outputs later. A scheduled task-mode session stays alive while+it owns pending background tasks. See+[Background task results](./channels/overview#background-task-results).+## Session continuityMarkdown schedules start a new session on every fire. Handler schedules do too, unless they send to an existing conversation, such as a Slack thread. Store data that must survive across fires outside session state.diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex 2e94faa39..390238f6a 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -13,16 +13,30 @@ Use a subagent to run independent work in parallel, narrow the available tools,Overlapping background work owned by a session forms a cohort. Tasks launched inlater user turns join the open cohort while earlier work is still pending or its-terminal results await delivery. eve holds completion, failure, and cancellation-notifications until every task in that cohort is terminal, then delivers all outcomes-together in one parent turn. This includes cohorts where every task failed or was-cancelled. Partial settlements do not invoke the parent model. Work started after the-cohort settles forms a new cohort. No configuration or debounce timer is required.--User messages, input requests, and authorization events are handled without waiting-for the cohort. Failure and cancellation update task lifecycle state immediately;-their automatic conversational report waits for the cohort. Child lifecycle events-are processed before terminal delivery so usage accounting and handle cleanup stay ordered.+terminal results await delivery. With `taskDeliveryPolicy: "cohort"`, eve holds+completion, failure, and cancellation notifications+until every task in that cohort has completed, failed, or been cancelled, then+delivers all outcomes together in one parent turn. Partial settlements+do not invoke the parent model. Work started after the cohort settles forms a new+cohort.++New channel sessions default to `"auto"`; schedules default to `"cohort"`.+Pass `taskDeliveryPolicy` to `send(...)` to select or update the session policy. See+[Background task results](/docs/channels/overview#background-task-results).++With `"auto"`, a terminal outcome can start a parent turn while other tasks are+still running. The parent reports independently useful results and stays silent+when a useful answer depends on unfinished tasks. Ready results may share a turn.+The reporting context includes the whole cohort and every available output,+including previously withheld results, for a later combined report.++The setting applies to background tools and built-in, declared, and remote+subagents owned by the session. Internal subagent sessions use `"cohort"` for+background work they start.++User messages, input requests, authorization events, failures, and cancellation+are handled without waiting for the cohort. Child lifecycle events are processed+before completion delivery so usage accounting and handle cleanup stay ordered.To follow work in progress, subscribe to the child session streams.## The built-in `agent` tooldiff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdxindex 42a83d822..d1099b842 100644--- a/docs/tools/overview.mdx+++ b/docs/tools/overview.mdx@@ -149,12 +149,20 @@ After the initiating turn accepts background tasks, eve supplies runtime-authorecohort and instructs the model to acknowledge that the work started without waiting for results.[Schedule](/docs/schedules)-initiated turns are the exception: no user prompted them, so theirlaunches keep conditional delivery and send no acknowledgement.-Later task-triggered parent turns receive fresh state for the same cohort. Once every related-task is terminal, one automatic parent turn receives the cohort's completed, failed, and cancelled-outcomes so the model can combine the useful results.-eve does not instruct the model to stay silent while sibling tasks are pending; a new user-question can receive an answer while background work continues. [Completion batching](/docs/subagents#completion-batching)-combines terminal results already queued for the parent.+Channel sessions default to `taskDeliveryPolicy: "auto"`: ready results can invoke+the parent while other tasks continue. The parent reports independently useful+results and can stay silent until related work settles. Each reporting context+includes the whole cohort and available outputs, including previously withheld+results. Ready results may share a turn.+Schedules default to `"cohort"`: terminal outcomes wait for overlapping tasks+to settle, then arrive together. Pass `taskDeliveryPolicy` to `send(...)` to select+or update the session policy. See+[Background task results](/docs/channels/overview#background-task-results) and+[Schedules](/docs/schedules#background-task-results).+User questions, input requests, and explicit task messages do not wait for the+cohort under either policy. Failure and cancellation update lifecycle state+immediately; their automatic reports follow the selected policy.+See [Completion batching](/docs/subagents#completion-batching).### Yield and returndiff --git a/e2e/fixtures/agent-task-reporting/evals/reporting.ts b/e2e/fixtures/agent-task-reporting/evals/reporting.tsindex 8f29b2976..20417d0e9 100644--- a/e2e/fixtures/agent-task-reporting/evals/reporting.ts+++ b/e2e/fixtures/agent-task-reporting/evals/reporting.ts@@ -43,14 +43,16 @@ export interface ReportingRun {export async function startWarehouseLookups(t: EveEvalContext): Promise<ReportingRun> {const modelId = e2eModel();if (typeof modelId !== "string") throw new Error("Warehouse reporting requires a real CI model.");- const started =- await t.send(`Alice is preparing an inventory checklist for Bob's warehouse handoff. Please delegate these three entries to three separate background assistants using the built-in agent tool, so the checks can proceed independently. Include the entry's check reference in each assistant's assignment. Keep this small checklist in the conversation rather than creating a separate todo list.+ const started = await t.send(+ `Alice is preparing an inventory checklist for Bob's warehouse handoff. Please delegate these three entries to three separate background assistants using the built-in agent tool, so the checks can proceed independently. Include the entry's check reference in each assistant's assignment. Keep this small checklist in the conversation rather than creating a separate todo list.1. check=first: Find the inventory item for the first entry using the inventory lookup tool (probe), and share the item it returns.2. check=second: Find the inventory item for the second entry using the inventory lookup tool (probe), and share the item it returns.3. check=third: Assign a third background assistant with agent, just like the first two entries. Ask that assistant to use warehouse_lookup; the workflow contacts the warehouse specialist and returns its item.-Once all three assignments are accepted, let Alice know the checks are underway. When all three results are ready, reply directly from the returned items without further tool calls or task-list updates. Bob needs only three checklist entries, with each item listed once and no separate summary.`);+Once all three assignments are accepted, let Alice know the checks are underway. When all three results are ready, reply directly from the returned items without further tool calls or task-list updates. Bob needs only three checklist entries, with each item listed once and no separate summary.`,+ { taskDeliveryPolicy: "cohort" },+ );started.expectOk();started.calledSubagent("agent", { status: "working", count: TASK_COUNT });started.notCalledTool("probe");diff --git a/e2e/fixtures/agent-task-wake-policy/agent/agent.ts b/e2e/fixtures/agent-task-wake-policy/agent/agent.tsnew file mode 100644index 000000000..c0d5465cc--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/agent/agent.ts@@ -0,0 +1,76 @@+import { e2eAgentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";+import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";++function respond(request: MockModelRequest): MockModelResponse | string {+ const assignment = request.userMessages.find((message) =>+ /^Bob prepares report [ABC]\./m.test(message),+ );+ if (assignment !== undefined) {+ const marker = assignment.match(/report ([ABC])/)![1]!;+ if (!request.toolResults.some((result) => result.name === "release")) {+ return { toolCalls: [{ name: "release", input: { marker } }] };+ }+ return `REPORT:${marker}`;+ }+ const last =+ request.messages+ .map((message) => message.text)+ .reverse()+ .find(+ (message) =>+ message.includes("Alice checks the status") ||+ message.startsWith("Background task task_"),+ ) ?? "";+ if (last.includes("Alice checks the status")) return "STATUS:AVAILABLE";+ const pending = ["A", "B", "C"].filter(+ (marker) => !request.toolResults.some((result) => result.id === `report-${marker}`),+ );+ if (pending.length > 0) {+ return {+ toolCalls: pending.map((marker) => ({+ id: `report-${marker}`,+ name: "agent",+ input: {+ message: `Bob prepares report ${marker}. Ask Alice to release the report before returning its result.`,+ },+ })),+ };+ }+ const stateMessage = request.messages+ .map((message) => message.text)+ .reverse()+ .find((message) => message.startsWith("[Task state]\n"));+ const state =+ stateMessage === undefined+ ? undefined+ : (JSON.parse(stateMessage.slice("[Task state]\n".length)) as {+ tasks: { status: string; output?: { type: string; data: unknown } }[];+ });+ const results =+ state?.tasks.flatMap((task) => (task.output?.type === "result" ? [task.output.data] : [])) ??+ [];+ const reported = new Set(+ request.messages.flatMap((message) =>+ message.role === "assistant" && message.text.startsWith('["REPORT:')+ ? (JSON.parse(message.text) as string[])+ : [],+ ),+ );+ const unreported = results.filter(+ (result) => typeof result === "string" && !reported.has(result),+ );+ const ready = unreported.filter(+ (result) =>+ result === "REPORT:A" || (results.includes("REPORT:B") && results.includes("REPORT:C")),+ );+ if (ready.length > 0) return JSON.stringify(ready.sort());+ return results.length > 0 ? "<eve-empty-delivery/>" : "REPORTS:STARTED";+}++const base = e2eAgentConfig({ mock: respond });+export default defineAgent({+ ...base,+ model: mockModel(respond),+ modelContextWindowTokens: base.modelContextWindowTokens ?? 1_000_000,+});diff --git a/e2e/fixtures/agent-task-wake-policy/agent/channels/eve.ts b/e2e/fixtures/agent-task-wake-policy/agent/channels/eve.tsnew file mode 100644index 000000000..ee18cb0ec--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/agent/channels/eve.ts@@ -0,0 +1,12 @@+import { eveChannel } from "eve/channels/eve";++export default eveChannel({+ auth: () => ({+ attributes: { fixture: "task-wake-policy" },+ authenticator: "e2e-fixture",+ issuer: "e2e",+ principalId: "task-wake-policy-e2e-user",+ principalType: "user",+ subject: "task-wake-policy-e2e-user",+ }),+});diff --git a/e2e/fixtures/agent-task-wake-policy/agent/channels/scheduled-reports.ts b/e2e/fixtures/agent-task-wake-policy/agent/channels/scheduled-reports.tsnew file mode 100644index 000000000..6e747d6eb--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/agent/channels/scheduled-reports.ts@@ -0,0 +1,8 @@+import { defineChannel, POST } from "eve/channels";++export default defineChannel<undefined, void, { id: string }>({+ routes: [POST("/scheduled-reports", async () => new Response("ok"))],+ receive(input, { from }) {+ return from(input.target.id).send(input.message, { auth: input.auth });+ },+});diff --git a/e2e/fixtures/agent-task-wake-policy/agent/instructions.md b/e2e/fixtures/agent-task-wake-policy/agent/instructions.mdnew file mode 100644index 000000000..02f5d0a79--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/agent/instructions.md@@ -0,0 +1 @@+Prepare reports A, B, and C. Ask Alice to release each report before returning its result. Share A independently; combine B and C once both are available. Answer Alice while other work continues.diff --git a/e2e/fixtures/agent-task-wake-policy/agent/schedules/automatic-reports.ts b/e2e/fixtures/agent-task-wake-policy/agent/schedules/automatic-reports.tsnew file mode 100644index 000000000..7012ad5db--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/agent/schedules/automatic-reports.ts@@ -0,0 +1,14 @@+import { defineSchedule } from "eve/schedules";+import reports from "../channels/scheduled-reports";++export default defineSchedule({+ cron: "0 9 * * *",+ run({ to, waitUntil, appAuth }) {+ waitUntil(+ to(reports, { id: crypto.randomUUID() }).send(+ "Alice asks Bob to prepare reports A, B, and C. Report A is independent; reports B and C form a joint comparison. Share A when ready and combine B with C once both are available.",+ { auth: appAuth, taskDeliveryPolicy: "auto" },+ ),+ );+ },+});diff --git a/e2e/fixtures/agent-task-wake-policy/agent/tools/release.ts b/e2e/fixtures/agent-task-wake-policy/agent/tools/release.tsnew file mode 100644index 000000000..ee98188cc--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/agent/tools/release.ts@@ -0,0 +1,10 @@+import { defineTool } from "eve/tools";+import { once } from "eve/tools/approval";+import { z } from "zod";++export default defineTool({+ description: "Wait for Alice to release this report.",+ inputSchema: z.object({ marker: z.enum(["A", "B", "C"]) }),+ approval: once(),+ execute: async ({ marker }) => ({ marker }),+});diff --git a/e2e/fixtures/agent-task-wake-policy/evals/evals.config.ts b/e2e/fixtures/agent-task-wake-policy/evals/evals.config.tsnew file mode 100644index 000000000..3a1a10d6f--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/evals/evals.config.ts@@ -0,0 +1,3 @@+import { defineEvalConfig } from "eve/evals";++export default defineEvalConfig({});diff --git a/e2e/fixtures/agent-task-wake-policy/evals/result-delivery.eval.ts b/e2e/fixtures/agent-task-wake-policy/evals/result-delivery.eval.tsnew file mode 100644index 000000000..b195ad0fe--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/evals/result-delivery.eval.ts@@ -0,0 +1,109 @@+import { defineEval, type EveEvalTurn, type InputRequest } from "eve/evals";+import { equals } from "eve/evals/expect";++export default defineEval({+ description:+ "A scheduled send using auto overrides the cohort default: report A independently, withhold B until C finishes, then report B and C together.",+ timeoutMs: 120_000,+ async test(t) {+ if (!t.target.capabilities.devRoutes) {+ t.skip("Schedule dispatch requires dev routes.");+ }+ const dispatched = await t.target.dispatchSchedule("automatic-reports");+ await t.require(dispatched.sessionIds.length, equals(1));+ const launch = t.target.watchTurn(dispatched.sessionIds[0]!);+ const started = (await launch.result()).expectOk();+ started.calledSubagent("agent", { status: "working", count: 3 });+ let streamIndex = launch.session.state!.streamIndex;+ const requests = new Map<string, InputRequest>();+ const turns: EveEvalTurn[] = [started];+ collectRequests(started);+ for (let attempt = 0; requests.size < 3 && attempt < 8; attempt += 1)+ collectRequests(await nextTurn());+ await t.require([...requests.keys()].sort(), equals(["A", "B", "C"]));++ await release("A");+ (await through('["REPORT:A"]')).usedNoTools();++ await release("B");+ const partial = await throughCompletion("REPORT:B");+ partial.usedNoTools();+ await t.require(partial.message, equals(undefined));+ await post({+ message: "Alice checks the status while Bob's report C awaits her approval.",+ turnPolicy: "queue",+ });+ (await through("STATUS:AVAILABLE")).usedNoTools();++ await release("C");+ (await through('["REPORT:B","REPORT:C"]')).usedNoTools();+ const reports = turns+ .map((turn) => turn.message)+ .filter((message) => message?.startsWith('["REPORT:'));+ t.check(reports, equals(['["REPORT:A"]', '["REPORT:B","REPORT:C"]'])).label(+ "A reports once; B is retained until it can be combined with C",+ );+ for (const turn of turns) turn.noFailedActions();++ function collectRequests(turn: EveEvalTurn) {+ for (const request of turn.inputRequests) {+ const marker = request.action.input.marker;+ if (request.action.toolName === "release" && typeof marker === "string")+ requests.set(marker, request);+ }+ }++ async function release(marker: string) {+ await post({+ inputResponses: [{ requestId: requests.get(marker)!.requestId, optionId: "approve" }],+ });+ }++ async function post(body: unknown) {+ const response = await t.target.fetch(+ `/eve/v1/session/${encodeURIComponent(started.sessionId)}`,+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ signal: t.signal,+ },+ );+ await t.require(response.status, equals(202));+ await response.body?.cancel();+ }++ async function nextTurn() {+ const live = t.target.watchTurn(started.sessionId, { startIndex: streamIndex });+ const turn = (await live.result()).expectOk();+ streamIndex = live.session.state!.streamIndex;+ turns.push(turn);+ return turn;+ }++ async function throughCompletion(marker: string) {+ for (let attempt = 0; attempt < 8; attempt += 1) {+ const turn = await nextTurn();+ if (+ turn.events.some(+ (event) =>+ event.type === "message.received" &&+ JSON.stringify(event.data.message).includes(marker),+ )+ )+ return turn;+ }+ throw new Error(`The parent did not receive ${marker}.`);+ }++ async function through(message: string) {+ for (let attempt = 0; attempt < 8; attempt += 1) {+ const turn = await nextTurn();+ if (turn.message === message) return turn;+ if (turn.message?.startsWith('["REPORT:'))+ throw new Error(`Unexpected report: ${turn.message}`);+ }+ throw new Error(`The parent did not produce ${message}.`);+ }+ },+});diff --git a/e2e/fixtures/agent-task-wake-policy/package.json b/e2e/fixtures/agent-task-wake-policy/package.jsonnew file mode 100644index 000000000..dc8c1d8c9--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/package.json@@ -0,0 +1,23 @@+{+ "name": "agent-task-wake-policy",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "build": "eve build",+ "dev": "eve dev",+ "start": "eve start",+ "typecheck": "eve build && tsc",+ "test:e2e": "eve eval --strict"+ },+ "dependencies": {+ "@eve-e2e/config": "workspace:*",+ "@workflow/world-postgres": "catalog:",+ "eve": "workspace:*",+ "zod": "catalog:"+ },+ "devDependencies": {+ "@types/node": "catalog:",+ "typescript": "catalog:"+ }+}diff --git a/e2e/fixtures/agent-task-wake-policy/tsconfig.json b/e2e/fixtures/agent-task-wake-policy/tsconfig.jsonnew file mode 100644index 000000000..1b9a6162e--- /dev/null+++ b/e2e/fixtures/agent-task-wake-policy/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "esnext",+ "moduleResolution": "bundler",+ "outDir": "dist",+ "rootDir": ".",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "noEmit": true,+ "types": ["node", "eve/workflow-modules"]+ },+ "include": ["agent/**/*.ts", "evals/**/*.ts"]+}diff --git a/e2e/fixtures/fixture-tasks/evals/batching.ts b/e2e/fixtures/fixture-tasks/evals/batching.tsindex a8049c6fc..ff3e69c73 100644--- a/e2e/fixtures/fixture-tasks/evals/batching.ts+++ b/e2e/fixtures/fixture-tasks/evals/batching.ts@@ -10,7 +10,7 @@ import {/** Release children independently of parent wakes, retaining the entire parent stream suffix. */export async function startBlockedFanout(t: EveEvalContext, count: number) {- const started = await t.send("TASK-BATCHING-BENCHMARK");+ const started = await t.send("TASK-BATCHING-BENCHMARK", { taskDeliveryPolicy: "cohort" });let session: TaskEvalSessionDriver = started.session;started.expectOk();started.noFailedActions();diff --git a/e2e/fixtures/fixture-tasks/evals/lifecycle.ts b/e2e/fixtures/fixture-tasks/evals/lifecycle.tsindex 25a4446ab..02c2425d9 100644--- a/e2e/fixtures/fixture-tasks/evals/lifecycle.ts+++ b/e2e/fixtures/fixture-tasks/evals/lifecycle.ts@@ -57,7 +57,7 @@ export function lifecycleDriver(t: EveEvalContext, key: string) {controls,taskIds,async start(message: string) {- const turn = (await t.send(message)).expectOk();+ const turn = (await t.send(message, { taskDeliveryPolicy: "cohort" })).expectOk();sessionId = turn.sessionId;streamIndex = requireSessionStreamIndex(turn.session, "Lifecycle setup");return record(turn);diff --git a/e2e/fixtures/fixture-tasks/evals/shared.ts b/e2e/fixtures/fixture-tasks/evals/shared.tsindex d6572d916..70631b5bb 100644--- a/e2e/fixtures/fixture-tasks/evals/shared.ts+++ b/e2e/fixtures/fixture-tasks/evals/shared.ts@@ -140,7 +140,7 @@ export async function sendAndFollowQueuedTurn(options: FollowQueuedTurnOptions = {},): Promise<FollowedQueuedTurn> {let session = initialSession;- let turn = await session.send(message);+ let turn = await session.send(message, { taskDeliveryPolicy: "cohort" });const observedTurns = [turn];for (let attempt = 0; attempt < 20; attempt += 1) {if (options.allowFailedActions !== true) {diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.tsindex b1ac9da57..5956f5ae8 100644--- a/e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.ts@@ -19,7 +19,7 @@ export default defineTaskEval({},async test(t) {t.log("starting first task");- const setup = await t.send("TASK-CONTINUATION-HITL-SETUP");+ const setup = await t.send("TASK-CONTINUATION-HITL-SETUP", { taskDeliveryPolicy: "cohort" });setup.expectOk();const firstTaskId = requireBackgroundTaskId(setup);diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.tsindex e42709e7b..ff5af9f15 100644--- a/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts@@ -25,7 +25,7 @@ export default defineTaskEval({dimensions: { transport: "local", parentPhase: "active" },},async test(t) {- const setup = await t.send("CHILD-TASK-EXCLUSIVITY-SETUP");+ const setup = await t.send("CHILD-TASK-EXCLUSIVITY-SETUP", { taskDeliveryPolicy: "cohort" });setup.expectOk();setup.messageIncludes("CHILD-TASK-EXCLUSIVITY-READY");const initialTaskId = requireBackgroundTaskId(setup);diff --git a/e2e/fixtures/fixture-tasks/evals/task.authorization.callback.accepted-current-attempt.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.authorization.callback.accepted-current-attempt.eval.tsindex 4a99f4469..7536f5d45 100644--- a/e2e/fixtures/fixture-tasks/evals/task.authorization.callback.accepted-current-attempt.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.authorization.callback.accepted-current-attempt.eval.ts@@ -27,7 +27,7 @@ export default defineTaskEval({dimensions: { transport: "local" },},async test(t) {- const started = await t.send("TASK-C7-AUTHORIZATION");+ const started = await t.send("TASK-C7-AUTHORIZATION", { taskDeliveryPolicy: "cohort" });started.expectOk();started.messageIncludes("TASK-C7-STARTED");started.event("action.result", {diff --git a/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.tsindex e580a82d9..edadd7cd3 100644--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts@@ -18,7 +18,9 @@ export default defineTaskEval({dimensions: { transport: "mixed", parentPhase: "active" },},async test(t) {- const started = await t.send("TASK-D6-PARTIAL-FANOUT-FAILURE");+ const started = await t.send("TASK-D6-PARTIAL-FANOUT-FAILURE", {+ taskDeliveryPolicy: "cohort",+ });started.expectOk();started.messageIncludes("TASK-D6-PARTIAL-FANOUT-STARTED");started.eventsSatisfy("dispatch results cover every sibling", (events) => {diff --git a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.accepted-acknowledged.creator-context.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.accepted-acknowledged.creator-context.eval.tsindex f0600a5b7..aa2c4e70e 100644--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.accepted-acknowledged.creator-context.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.accepted-acknowledged.creator-context.eval.ts@@ -25,6 +25,7 @@ export default defineTaskEval({// One authenticated caller creates the session and remains its initiator.const firstTurn = await t.send("TASK-AUTH-SNAPSHOT-ROOT", {+ taskDeliveryPolicy: "cohort",headers: { authorization: SESSION_INITIATOR_AUTHORIZATION },});const session = firstTurn.session;@@ -40,6 +41,7 @@ export default defineTaskEval({// A route-authenticated, schedule-shaped turn has no current session principal.const key = crypto.randomUUID();const started = await session.send(`TASK-AUTH-SNAPSHOT ${key}`, {+ taskDeliveryPolicy: "cohort",headers: { [ANONYMOUS_TASK_CREATOR_HEADER]: "1" },});started.expectOk();@@ -57,6 +59,7 @@ export default defineTaskEval({// Another authenticated caller takes the last parent turn before nested dispatch.const lastParentTurn = await session.send("TASK-AUTH-SNAPSHOT-LATER", {+ taskDeliveryPolicy: "cohort",headers: { authorization: LATER_PARENT_CALLER_AUTHORIZATION },});lastParentTurn.expectOk();diff --git a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.tsindex 23d192ed9..9734dfae6 100644--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts@@ -12,7 +12,9 @@ export default defineTaskEval({dimensions: { transport: "remote", parentPhase: "active" },},async test(t) {- const started = await t.send("TASK-A3-DISPATCH-START-FAILURE");+ const started = await t.send("TASK-A3-DISPATCH-START-FAILURE", {+ taskDeliveryPolicy: "cohort",+ });started.expectOk();started.messageIncludes("TASK-A3-PARENT-SURVIVED");started.event("action.result", {diff --git a/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.local.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.local.eval.tsindex 657ea1030..73216f676 100644--- a/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.local.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.local.eval.ts@@ -13,7 +13,7 @@ export default defineTaskEval({dimensions: { transport: "local" },},async test(t) {- const started = await t.send("TASK-HITL-ROUTING");+ const started = await t.send("TASK-HITL-ROUTING", { taskDeliveryPolicy: "cohort" });started.expectOk();started.event("action.result", {count: 1,diff --git a/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.remote.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.remote.eval.tsindex 1326745de..ce98568c1 100644--- a/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.remote.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.remote.eval.ts@@ -26,7 +26,7 @@ export default defineTaskEval({dimensions: { transport: "remote" },},async test(t) {- const started = await t.send("TASK-C8-REMOTE-HITL");+ const started = await t.send("TASK-C8-REMOTE-HITL", { taskDeliveryPolicy: "cohort" });started.expectOk();started.messageIncludes("TASK-C8-STARTED");started.event("action.result", {diff --git a/e2e/fixtures/fixture-tasks/evals/task.input.route.observed-stale-unrouted.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.input.route.observed-stale-unrouted.eval.tsindex 74481948f..a0038d43e 100644--- a/e2e/fixtures/fixture-tasks/evals/task.input.route.observed-stale-unrouted.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.input.route.observed-stale-unrouted.eval.ts@@ -18,7 +18,7 @@ export default defineTaskEval({dimensions: { transport: "local" },},async test(t) {- const started = await t.send("TASK-INPUT-BATCH-ORDERING");+ const started = await t.send("TASK-INPUT-BATCH-ORDERING", { taskDeliveryPolicy: "cohort" });started.expectOk();const taskId = requireBackgroundTaskId(started);diff --git a/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-all-terminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-all-terminal.eval.tsindex e88c19f05..712028f21 100644--- a/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-all-terminal.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-all-terminal.eval.ts@@ -29,7 +29,7 @@ export default defineTaskEval({dimensions: { transport: "local", parentPhase: "active" },},async test(t) {- const started = await t.send("TASK-FAN-IN");+ const started = await t.send("TASK-FAN-IN", { taskDeliveryPolicy: "cohort" });started.expectOk();started.messageIncludes("TASK-FAN-IN-STARTED");started.calledSubagent("fanout-worker", { status: "working", count: FAN_IN_SIZE });diff --git a/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-partial.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-partial.eval.tsindex 12e03d6f0..bf648f7ab 100644--- a/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-partial.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.join.evaluate.observed-partial.eval.ts@@ -28,7 +28,7 @@ export default defineTaskEval({dimensions: { transport: "local", parentPhase: "parked" },},async test(t) {- const started = (await t.send("TASK-FAN-IN")).expectOk();+ const started = (await t.send("TASK-FAN-IN", { taskDeliveryPolicy: "cohort" })).expectOk();started.messageIncludes("TASK-FAN-IN-STARTED");started.calledSubagent("fanout-worker", { status: "working", count: MARKERS.length });let session: TaskEvalSessionDriver = started.session;diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.accepted-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.accepted-nonterminal.eval.tsindex e03ff8c89..cdf412544 100644--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.accepted-nonterminal.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.accepted-nonterminal.eval.ts@@ -17,7 +17,7 @@ export default defineTaskEval({dimensions: { transport: "local", parentPhase: "active" },},async test(t) {- const started = await t.send("TASK-CANCEL-SETUP");+ const started = await t.send("TASK-CANCEL-SETUP", { taskDeliveryPolicy: "cohort" });started.expectOk();started.messageIncludes("TASK-CANCEL-READY");started.event("action.result", {diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.tsindex ea6db79cc..01ac891f3 100644--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.ts@@ -10,7 +10,7 @@ export default defineTaskEval({dimensions: { transport: "local", parentPhase: "parked" },},async test(t) {- const started = await t.send("TASK-CANCEL-SETUP");+ const started = await t.send("TASK-CANCEL-SETUP", { taskDeliveryPolicy: "cohort" });started.expectOk();const taskId = requireBackgroundTaskId(started);const blocked = await waitForTaskInput(t, started.session, "release");@@ -32,7 +32,9 @@ export default defineTaskEval({const completed = await waitForTaskNotification(t, blocked.session, taskId, "completed", [answered,]);- const followUp = await completed.session.send("TASK-CANCEL-VERIFY-NOOP");+ const followUp = await completed.session.send("TASK-CANCEL-VERIFY-NOOP", {+ taskDeliveryPolicy: "cohort",+ });followUp.expectOk();},});diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.noop-already-cancelled.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.noop-already-cancelled.eval.tsindex 74a7e27db..f8d65534c 100644--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.noop-already-cancelled.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.noop-already-cancelled.eval.ts@@ -22,7 +22,7 @@ export default defineTaskEval({dimensions: { transport: "local", parentPhase: "active" },},async test(t) {- const started = await t.send("TASK-CANCEL-SETUP");+ const started = await t.send("TASK-CANCEL-SETUP", { taskDeliveryPolicy: "cohort" });started.expectOk();started.messageIncludes("TASK-CANCEL-READY");started.event("action.result", {diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.tsindex e0b046181..d1130cd62 100644--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.ts@@ -17,7 +17,7 @@ export default defineTaskEval({dimensions: { transport: "local", parentPhase: "parked" },},async test(t) {- const started = await t.send("TASK-CANCEL-SETUP");+ const started = await t.send("TASK-CANCEL-SETUP", { taskDeliveryPolicy: "cohort" });started.expectOk();const taskId = requireBackgroundTaskId(started);const blocked = await waitForTaskInput(t, started.session, "release");diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.complete.accepted-nonterminal.child-tool-surface.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.complete.accepted-nonterminal.child-tool-surface.eval.tsindex 435464e99..9201c6b93 100644--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.complete.accepted-nonterminal.child-tool-surface.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.complete.accepted-nonterminal.child-tool-surface.eval.ts@@ -14,6 +14,7 @@ export default defineTaskEval({async test(t) {const started = await t.send("Alice asks Bob to summarize the available tools for a background task.",+ { taskDeliveryPolicy: "cohort" },);started.expectOk();started.calledSubagent("tool-surface-worker", { status: "working", count: 1 });diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.fail.accepted-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.fail.accepted-nonterminal.eval.tsindex 1deb7f708..00c36e5d1 100644--- a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.fail.accepted-nonterminal.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.fail.accepted-nonterminal.eval.ts@@ -15,7 +15,7 @@ export default defineTaskEval({dimensions: { transport: "local" },},async test(t) {- const started = await t.send("TASK-A2-CHILD-FAILURE");+ const started = await t.send("TASK-A2-CHILD-FAILURE", { taskDeliveryPolicy: "cohort" });started.expectOk();started.messageIncludes("TASK-A2-CHILD-FAILURE-STARTED");started.event("action.result", {diff --git a/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.tsindex 92808f803..c64d248ac 100644--- a/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.ts@@ -20,7 +20,7 @@ export default defineTaskEval({dimensions: { transport: "local", parentPhase: "active" },},async test(t) {- const started = await t.send("TASK-FANOUT-PARENT-UPDATES");+ const started = await t.send("TASK-FANOUT-PARENT-UPDATES", { taskDeliveryPolicy: "cohort" });started.expectOk();started.messageIncludes("TASK-FANOUT-STARTED");started.calledSubagent("fanout-worker", { status: "working", count: FANOUT_SIZE });diff --git a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.eval.tsindex 258986bd0..0963c315f 100644--- a/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.parent.wake.emitted-ready.eval.ts@@ -23,7 +23,7 @@ export default defineTaskEval({dimensions: { transport: "local", parentPhase: "active" },},async test(t) {- const started = await t.send("TASK-PARENT-WAKE-UPDATES");+ const started = await t.send("TASK-PARENT-WAKE-UPDATES", { taskDeliveryPolicy: "cohort" });started.expectOk();started.messageIncludes("TASK-FANOUT-STARTED");started.calledSubagent("fanout-worker", { status: "working", count: FANOUT_SIZE });diff --git a/packages/eve/extension-contracts/compatibility/channel/v27.ts b/packages/eve/extension-contracts/compatibility/channel/v27.tsnew file mode 100644index 000000000..d43a9bc02--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/channel/v27.ts@@ -0,0 +1,17 @@+import { defineChannel, POST } from "#public/channels/index.js";++export default defineChannel({+ routes: [+ POST("/continue/:sessionId", async (_request, { attachSession, params }) => {+ const result = await attachSession(params.sessionId!).send("Continue.", {+ auth: null,+ title: "Daily report",+ turnPolicy: "queue",+ });+ if (result.status === "session_not_active") {+ return Response.json({ accepted: false }, { status: 409 });+ }+ return Response.json({ sessionId: result.sessionId, deliveryId: result.deliveryId });+ }),+ ],+});diff --git a/packages/eve/extension-contracts/compatibility/schedule/v14.ts b/packages/eve/extension-contracts/compatibility/schedule/v14.tsnew file mode 100644index 000000000..c4ea3db13--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/schedule/v14.ts@@ -0,0 +1,23 @@+import { defineChannel } from "#public/channels/index.js";+import { defineSchedule } from "#public/schedules/index.js";++const updates = defineChannel({+ routes: [],+ receive(input, { from }) {+ return from("daily-updates").send(input.message, { auth: input.auth });+ },+});++export default defineSchedule({+ cron: "0 9 * * *",+ async run({ to, waitUntil, appAuth }) {+ const session = await to(updates, {}).send("Prepare the daily summary.", { auth: appAuth });+ const result = await session.send("Include yesterday's activity.", {+ auth: appAuth,+ title: "Daily summary",+ turnPolicy: "queue",+ });+ if (result.status === "session_not_active") return;+ waitUntil(Promise.resolve(result.sessionId));+ },+});diff --git a/packages/eve/extension-contracts/reports/channel/v28.json b/packages/eve/extension-contracts/reports/channel/v28.jsonnew file mode 100644index 000000000..4afc7cade--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v28.json@@ -0,0 +1,21 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 28,+ "sha256": "685fe8345ae2a4667eb26a61a0c0a555cd57d33b93edc8e77d888df7c63ecad9",+ "exports": [+ "DELETE",+ "GET",+ "HEAD",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "disableRoute",+ "isChannel",+ "isDisabledRouteSentinel"+ ]+}diff --git a/packages/eve/extension-contracts/reports/schedule/v15.json b/packages/eve/extension-contracts/reports/schedule/v15.jsonnew file mode 100644index 000000000..a610d625f--- /dev/null+++ b/packages/eve/extension-contracts/reports/schedule/v15.json@@ -0,0 +1,14 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "schedule",+ "epoch": 15,+ "sha256": "ad9559014d6eb64379a1e6a10aead9b30ce9ee7d2cb365a58b6c8dc0d662ba79",+ "exports": [+ "ScheduleDefinition",+ "ScheduleHandlerArgs",+ "ScheduleRunHandler",+ "ScheduleToFn",+ "TypedReceiveTarget",+ "defineSchedule"+ ]+}diff --git a/packages/eve/package.json b/packages/eve/package.jsonindex 3f95de165..625295e77 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -491,9 +491,9 @@"@ai-sdk/otel": "catalog:","@ai-sdk/provider": "catalog:","@ai-sdk/provider-utils": "catalog:",- "@chat-adapter/slack": "4.34.0",- "@chat-adapter/state-memory": "4.34.0",- "@chat-adapter/twilio": "4.34.0",+ "@chat-adapter/slack": "4.41.0",+ "@chat-adapter/state-memory": "4.41.0",+ "@chat-adapter/twilio": "4.41.0","@clack/core": "1.3.1","@eve/catalog": "workspace:*","@linqapp/chat-sdk-adapter": "^0.5.1",@@ -525,7 +525,7 @@"@workflow/world-local": "5.0.0-beta.46","@workflow/world-vercel": "5.0.0-beta.50","ai": "catalog:",- "chat": "4.34.0",+ "chat": "4.41.0","chokidar": "5.0.0","commander": "14.0.3","dd-trace": "6.13.0",@@ -559,6 +559,7 @@"@opentelemetry/api": "^1.0.0","ai": "catalog:","braintrust": "^3.0.0",+ "chat": "^4.41.0","dd-trace": "^6.13.0","just-bash": "^3.1.0","microsandbox": "^0.5.0"@@ -570,6 +571,9 @@"braintrust": {"optional": true},+ "chat": {+ "optional": true+ },"dd-trace": {"optional": true},diff --git a/packages/eve/scripts/vendor-compiled/chat.mjs b/packages/eve/scripts/vendor-compiled/chat.mjsindex affcc5ff8..0bbd8b073 100644--- a/packages/eve/scripts/vendor-compiled/chat.mjs+++ b/packages/eve/scripts/vendor-compiled/chat.mjs@@ -1,43 +1,10 @@-import {- buildOpaqueTypesStub,- buildUniqueSymbolStub,- createDeclarationCopier,-} from "./_shared.mjs";-/**- * Type declarations for `chat` are copied verbatim from the installed- * package at vendor time. The chat surface (Thread, Message, Author,- * SentMessage, …) is reachable by consumer code as `ctx.thread.refresh()`- * etc., so the public type contract has to be the *actual* chat shape —- * hand-written stubs would drift on every version bump.- *- * Three transforms apply during the copy:- *- * 1. The sibling `jsx-runtime-<hash>.d.ts` chunk is co-copied so chat's- * relative import resolves locally. The chunk's filename has a content- * hash, so we discover it dynamically.- * 2. `from '@workflow/serde'` is rewritten to a local stub that declares- * just the unique symbols chat references.- * 3. `from 'mdast'` is rewritten to a local stub that aliases the names- * chat references to `unknown` — consumers don't need @types/mdast.+ * Keep Chat SDK type identity shared with consumer adapters. Copying its class+ * declarations creates distinct private fields, making external adapters and+ * handlers incompatible even when both copies use the same package version.*/export default {packageName: "chat",compiledPath: "chat",- copyDeclarations: createDeclarationCopier({- rewrites: {- "@workflow/serde": {- kind: "stub",- stubBaseName: "_workflow-serde",- build: buildUniqueSymbolStub,- },- mdast: {- kind: "stub",- stubBaseName: "_mdast",- build: buildOpaqueTypesStub,- },- },- discoverExtraFiles: (distEntries) =>- distEntries.filter((name) => /^jsx-runtime-[^./]+\.d\.ts$/.test(name)),- }),+ declaration: 'export * from "chat";\n',};diff --git a/packages/eve/src/channel/channel-address.test.ts b/packages/eve/src/channel/channel-address.test.tsindex a8cc3808d..d1dc8f72a 100644--- a/packages/eve/src/channel/channel-address.test.ts+++ b/packages/eve/src/channel/channel-address.test.ts@@ -19,6 +19,34 @@ function createRuntime(): Runtime {}describe("createChannelAddress", () => {+ it("carries each send's task policy through creation and continuation", async () => {+ const runtime = createRuntime();+ vi.mocked(runtime.dispatchContinuation).mockResolvedValueOnce({ status: "session_not_active" });+ vi.mocked(runtime.createSession).mockResolvedValue({ sessionId: "sess_1" } as never);+ const address = createChannelAddress({+ adapter: { kind: "http" },+ channelName: "reports",+ continuationToken: "alice",+ runtime,+ });+ await address.send("Prepare reports", { auth: null, taskDeliveryPolicy: "cohort" });+ expect(runtime.createSession).toHaveBeenCalledWith(+ expect.objectContaining({+ taskDeliveryPolicy: "cohort",+ continuationConflictCommand: expect.objectContaining({ taskDeliveryPolicy: "cohort" }),+ }),+ );+ await address.send("Share useful results as they arrive", {+ auth: null,+ taskDeliveryPolicy: "auto",+ });+ expect(runtime.dispatchContinuation).toHaveBeenLastCalledWith(+ expect.objectContaining({+ command: expect.objectContaining({ taskDeliveryPolicy: "auto" }),+ }),+ );+ });+it("rejects channel addresses in the framework-reserved session namespace", () => {expect(() =>createChannelAddress({diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.tsindex 6f3a0eb54..eeac78c0c 100644--- a/packages/eve/src/channel/channel-address.ts+++ b/packages/eve/src/channel/channel-address.ts@@ -20,6 +20,7 @@ import type {SessionCallback,SessionCommand,TurnPolicy,+ TaskDeliveryPolicy,} from "#channel/types.js";import { DEFAULT_TURN_POLICY } from "#channel/types.js";import { isReservedSessionCommandToken } from "#execution/session-inbox/address.js";@@ -32,6 +33,7 @@ interface BaseChannelAddressDeliveryOptions {readonly mode?: RunMode;readonly title?: string;readonly turnPolicy?: TurnPolicy;+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;}/** Delivery options for a channel address whose continuation token is already bound. */@@ -74,6 +76,7 @@ export function createChannelAddress<TState = undefined>(input: {readonly metadata?: ChannelDeliverySource;readonly runtime: Runtime;readonly turnPolicy?: TurnPolicy;+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;}): ChannelAddress<TState> {const metadata: Partial<ChannelDeliverySource> = input.metadata ?? {};const namespacedToken = `${input.channelName}:${input.continuationToken}`;@@ -90,7 +93,9 @@ export function createChannelAddress<TState = undefined>(input: {: undefined;const payload = normalizeSendInput(sendInput);const caller = sessionCallbackToTurnCaller(options.callback);+ const taskDeliveryPolicy = options.taskDeliveryPolicy ?? input.taskDeliveryPolicy;const commandWithoutCaller = {+ taskDeliveryPolicy,auth: options.auth,delivery,kind: "send" as const,@@ -139,6 +144,7 @@ export function createChannelAddress<TState = undefined>(input: {const capabilities: RunInput["capabilities"] =options.mode === "task" ? undefined : { requestInput: true };const runInput: RunInput = {+ taskDeliveryPolicy,adapter,auth: options.auth,capabilities,@@ -215,6 +221,7 @@ export function createChannelAddressFn<TState = undefined>(input: {readonly metadata?: ChannelDeliverySource;readonly runtime: Runtime;readonly turnPolicy?: TurnPolicy;+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;}): ChannelAddressFn<TState> {return (continuationToken) => createChannelAddress({ ...input, continuationToken });}diff --git a/packages/eve/src/channel/channel-operations.ts b/packages/eve/src/channel/channel-operations.tsindex ddf457037..05a90a9d9 100644--- a/packages/eve/src/channel/channel-operations.ts+++ b/packages/eve/src/channel/channel-operations.ts@@ -17,6 +17,7 @@ import type {SessionAuthContext,SessionCallback,TurnPolicy,+ TaskDeliveryPolicy,} from "#channel/types.js";import {type InputResponse,@@ -35,6 +36,8 @@ interface BaseChannelSendOptions {readonly outputSchema?: JsonObject;readonly title?: string;readonly turnPolicy?: TurnPolicy;+ /** Updates the session policy; omission preserves it. New sessions default to auto, schedules to cohort. */+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;}/** Options for sending a message from a channel-local continuation address. */@@ -100,6 +103,7 @@ export function createChannelOperations<TState = undefined>(input: {readonly metadata?: ChannelDeliverySource;readonly runtime: Runtime;readonly turnPolicy?: TurnPolicy;+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;}): ChannelReceiveContext<TState> {const channelAddress = createChannelAddressFn<TState>(input);diff --git a/packages/eve/src/channel/cross-channel-receive.test.ts b/packages/eve/src/channel/cross-channel-receive.test.tsindex 7bc21fb2c..8e36f2a4e 100644--- a/packages/eve/src/channel/cross-channel-receive.test.ts+++ b/packages/eve/src/channel/cross-channel-receive.test.ts@@ -6,6 +6,8 @@ import {type CrossChannelTarget,type CrossChannelToFn,} from "#channel/cross-channel-receive.js";+import { TaskDeliveryPolicyKey } from "#context/keys.js";+import { buildRunContext } from "#execution/runtime-context.js";import type { Session } from "#channel/session.js";import type { Runtime } from "#channel/types.js";import type { SlackChannel, SlackReceiveTarget } from "#public/channels/slack/slackChannel.js";@@ -76,6 +78,52 @@ function makeChannel(name: string): {}describe("createCrossChannelToFn", () => {+ it("defaults to auto when both the sender and receiver omit the task policy", async () => {+ const runtime = makeRuntime();+ vi.mocked(runtime.dispatchContinuation).mockResolvedValue({ status: "session_not_active" });+ vi.mocked(runtime.createSession).mockImplementation(async (run) => {+ const context = buildRunContext({ bundle: {} as never, run });+ expect(context.get(TaskDeliveryPolicyKey)).toBe("auto");+ return { sessionId: "sess_1" } as never;+ });+ const channel = makeChannel("reports");+ channel.receive.mockImplementation((input, { from }) =>+ from("alice").send(input.message, { auth: input.auth }),+ );++ const session = await createCrossChannelToFn(runtime, [channel.target])(+ channel.definition,+ {},+ ).send("Prepare reports", { auth: null });++ expect(runtime.createSession).toHaveBeenCalledOnce();+ expect(session.id).toBe("sess_1");+ });++ it("carries a cross-channel send policy through the receiver's local send", async () => {+ const runtime = makeRuntime();+ vi.mocked(runtime.dispatchContinuation).mockResolvedValue({+ sessionId: "sess_1",+ status: "accepted",+ });+ const channel = makeChannel("reports");+ channel.receive.mockImplementation((input, { from }) =>+ from("alice").send(input.message, { auth: input.auth }),+ );+ await createCrossChannelToFn(runtime, [channel.target])(channel.definition, {}).send(+ "Prepare reports",+ {+ auth: null,+ taskDeliveryPolicy: "cohort",+ },+ );+ expect(runtime.dispatchContinuation).toHaveBeenCalledWith(+ expect.objectContaining({+ command: expect.objectContaining({ taskDeliveryPolicy: "cohort" }),+ }),+ );+ });+it("accepts a Slack channel whose receive target is a closed interface", () => {const typeOnlyCalls = (to: CrossChannelToFn, slack: SlackChannel) => {const target: SlackReceiveTarget = { channelId: "C1" };diff --git a/packages/eve/src/channel/cross-channel-receive.ts b/packages/eve/src/channel/cross-channel-receive.tsindex e914ff584..c26a1d593 100644--- a/packages/eve/src/channel/cross-channel-receive.ts+++ b/packages/eve/src/channel/cross-channel-receive.ts@@ -9,7 +9,12 @@ import {} from "#channel/compiled-channel.js";import type { InferReceiveTarget } from "#channel/receive-target.js";import type { Session } from "#channel/session.js";-import type { Runtime, SessionAuthContext, TurnPolicy } from "#channel/types.js";+import type {+ Runtime,+ SessionAuthContext,+ TurnPolicy,+ TaskDeliveryPolicy,+} from "#channel/types.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";/**@@ -18,6 +23,8 @@ import type { ResolvedChannelDefinition } from "#runtime/types.js";export interface CrossChannelSendOptions {readonly auth: SessionAuthContext | null;readonly turnPolicy?: TurnPolicy;+ /** Updates the session policy; omission preserves it. New sessions default to auto, schedules to cohort. */+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;}/** Message delivery bound to one channel-specific proactive target. */@@ -89,6 +96,7 @@ export function createCrossChannelToFn(auth: options.auth,},turnPolicy: options.turnPolicy,+ taskDeliveryPolicy: options.taskDeliveryPolicy,describeMissingReceive: () =>`ctx.to(): channel "${targetChannel.name}" does not implement receive(). ` +`Declare a receive hook on the channel to accept cross-channel sessions.`,@@ -109,6 +117,7 @@ interface InvokeChannelReceiveInput {readonly auth: SessionAuthContext | null;};readonly turnPolicy?: TurnPolicy;+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;readonly describeMissingReceive: () => string;readonly describeMissingAdapter: () => string;}@@ -128,6 +137,7 @@ export async function invokeChannelReceive(args: InvokeChannelReceiveInput): ProchannelName: args.target.name,runtime: args.runtime,turnPolicy: args.turnPolicy ?? args.target.turnPolicy,+ taskDeliveryPolicy: args.taskDeliveryPolicy,});return await args.target.receive(args.input, channelOperations);}diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.tsindex 504536fcd..2a391b094 100644--- a/packages/eve/src/channel/schedule.test.ts+++ b/packages/eve/src/channel/schedule.test.ts@@ -9,8 +9,9 @@ import {SCHEDULE_APP_AUTH,ScheduleDispatcher,} from "#channel/schedule.js";+import { buildRunContext } from "#execution/runtime-context.js";import { contextStorage } from "#context/container.js";-import { ScheduleIdKey } from "#context/keys.js";+import { ScheduleIdKey, TaskDeliveryPolicyKey } from "#context/keys.js";import type { RunHandle, Runtime } from "#channel/types.js";import { slackChannel } from "#public/channels/slack/slackChannel.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";@@ -59,6 +60,40 @@ function makeSlackChannelEntry(): {}describe("ScheduleDispatcher", () => {+ it.each([undefined, "auto", "cohort"] as const)(+ "uses the schedule default unless send supplies %s",+ async (taskDeliveryPolicy) => {+ vi.stubEnv("SLACK_BOT_TOKEN", "xoxb-test");+ vi.stubEnv("SLACK_SIGNING_SECRET", "test-secret");+ try {+ const runtime = createMockRuntime();+ const policies: unknown[] = [];+ runtime.createSession = vi.fn(async (run) => {+ policies.push(buildRunContext({ bundle: {} as never, run }).get(TaskDeliveryPolicyKey));+ return createMockRunHandle();+ });+ const { definition, resolved } = makeSlackChannelEntry();+ const result = await new ScheduleDispatcher({ runtime, channels: [resolved] }).trigger({+ scheduleId: "daily-report",+ run({ to, waitUntil, appAuth }) {+ waitUntil(+ Promise.resolve().then(() =>+ to(definition, { channelId: "C0123ABC" }).send("Report", {+ auth: appAuth,+ taskDeliveryPolicy,+ }),+ ),+ );+ },+ });+ await Promise.all(result.waitUntilTasks);+ expect(policies).toEqual([taskDeliveryPolicy ?? "cohort"]);+ } finally {+ vi.unstubAllEnvs();+ }+ },+ );+describe("markdown form", () => {it("starts a Session via runtime.createSession with the SCHEDULE_ADAPTER", async () => {const runtime = createMockRuntime();diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.tsindex 004cf2cf8..34e96a4f2 100644--- a/packages/eve/src/channel/session.test.ts+++ b/packages/eve/src/channel/session.test.ts@@ -55,6 +55,20 @@ function createRuntime(): Runtime {}describe("createSession#cancel", () => {+ it("passes an explicit task policy through a fixed-session send", async () => {+ const runtime = createRuntime();+ await createSession("sess_1", runtime).send("Report when ready", {+ auth: null,+ taskDeliveryPolicy: "auto",+ });+ expect(runtime.dispatchSession).toHaveBeenCalledWith(+ expect.objectContaining({+ sessionId: "sess_1",+ command: expect.objectContaining({ taskDeliveryPolicy: "auto" }),+ }),+ );+ });+it("cancels this session's turn by session id", async () => {const runtime = createRuntime();const session = createSession("sess_1", runtime);diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.tsindex 099ab6dac..50d257aa8 100644--- a/packages/eve/src/channel/session.ts+++ b/packages/eve/src/channel/session.ts@@ -16,6 +16,7 @@ import type {SessionCallback,SessionSendCommandResult,TurnPolicy,+ TaskDeliveryPolicy,TurnCaller,} from "#channel/types.js";import { DEFAULT_TURN_POLICY } from "#channel/types.js";@@ -80,6 +81,8 @@ export type SessionSendOptions = SessionDeliveryOptions & {/** Initial workflow title for a prewarmed session. */readonly title?: string;readonly turnPolicy?: TurnPolicy;+ /** Updates the session policy; omission preserves it. New sessions default to auto, schedules to cohort. */+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;};/** Options for answering pending input requests through a fixed session handle. */@@ -126,6 +129,7 @@ export function createSession(payload,requestId: metadata.requestId,turnPolicy: options.turnPolicy ?? metadata.turnPolicy ?? DEFAULT_TURN_POLICY,+ taskDeliveryPolicy: options.taskDeliveryPolicy,title: options.title,};return await runtime.dispatchSession({diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex a33c2fe6b..c90e16ea4 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -195,6 +195,9 @@ export interface DeliverPayload {readonly [key: string]: unknown;}+/** Controls background task wake timing and whether partial results require a report. */+export type TaskDeliveryPolicy = "cohort" | "auto";+/** Controls how a channel message interacts with an active turn. */export type TurnPolicy = "steer" | "queue";@@ -219,6 +222,7 @@ export type SessionCommand =*/readonly taskDeliveryId?: string;readonly turnPolicy?: TurnPolicy;+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;}| {readonly kind: "cancel";@@ -291,9 +295,12 @@ export interface DeliverHookPayload {* `resumeHook` already succeeded.*/readonly taskDeliveryId?: string;+ /** All source notifications when the session queue combines task results. */+ readonly taskDeliveryIds?: readonly string[];readonly kind: "deliver";readonly payloads: readonly DeliverPayload[];readonly turnPolicy?: TurnPolicy;+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;}/** Internal deadline signal sent through the stable session command inbox. */@@ -464,6 +471,7 @@ export interface SessionCapabilities {* subagent tool wrapper).*/export interface RunInput {+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;readonly adapter: ChannelAdapter<any>;/** Framework task that owns this run, when the run is a task executor. */readonly taskId?: string;diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.tsindex bda857b4c..74518b7c9 100644--- a/packages/eve/src/client/session.test.ts+++ b/packages/eve/src/client/session.test.ts@@ -575,6 +575,19 @@ describe("ClientSession", () => {});});+ it("serializes taskDeliveryPolicy with a fixed-session message", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());+ const session = createSession();++ await session.send("Wait your turn", { taskDeliveryPolicy: "cohort" });++ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;+ expect(JSON.parse(String(init.body))).toEqual({+ message: "Wait your turn",+ taskDeliveryPolicy: "cohort",+ });+ });+it("serializes clientContext when continuing a session", async () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());const session = createSession({diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex b5b36fed5..9ad5d784a 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -450,6 +450,9 @@ function createMessageBody(if (!requireMessage && input.message !== undefined && input.turnPolicy !== undefined) {body.turnPolicy = input.turnPolicy;}+ if (input.message !== undefined && input.taskDeliveryPolicy !== undefined) {+ body.taskDeliveryPolicy = input.taskDeliveryPolicy;+ }if (input.clientContext !== undefined) body.clientContext = input.clientContext;const outputSchema = serializeOutputSchema(input.outputSchema);if (outputSchema !== undefined) body.outputSchema = outputSchema;diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.tsindex 8e95a00e0..43d99d7be 100644--- a/packages/eve/src/client/types.ts+++ b/packages/eve/src/client/types.ts@@ -6,7 +6,7 @@ import type { CancelTurnResult } from "#protocol/cancel-turn.js";import type { ClearStatus } from "#protocol/clear-session.js";import type { CompactStatus } from "#protocol/compact-session.js";import type { ResetStatus } from "#protocol/reset-session.js";-import type { TurnPolicy } from "#channel/types.js";+import type { TurnPolicy, TaskDeliveryPolicy } from "#channel/types.js";import type { InputRequest, InputResponse } from "#shared/input.js";import type { JsonObject } from "#shared/json.js";export type { HealthResult } from "#client/health-schema.js";@@ -120,6 +120,8 @@ export interface CreateSessionOptions {export interface SendTurnOptions<TOutput = unknown> {/** Policy for a message sent while the fixed session has an active turn. */readonly turnPolicy?: TurnPolicy;+ /** Updates the session’s background task reporting policy. Omit to preserve it. */+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;/*** Ephemeral client/page context for the current turn.@@ -161,7 +163,10 @@ export interface SendTurnOptions<TOutput = unknown> {}/** Options for answering pending HITL input requests on a client session. */-export type RespondTurnOptions<TOutput = unknown> = SendTurnOptions<TOutput>;+export type RespondTurnOptions<TOutput = unknown> = Omit<+ SendTurnOptions<TOutput>,+ "taskDeliveryPolicy"+>;/** @internal Transport envelope used by stores and command adapters. */export type SendTurnPayload<TOutput = unknown> =diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 313eeeca4..8c093c6ef 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -95,8 +95,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},channel: {- current: 27,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 27],+ current: 28,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 27, 28],dropped: {12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",19: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.",@@ -110,8 +110,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},schedule: {- current: 14,- supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14],+ current: 15,+ supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],dropped: {5: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",},diff --git a/packages/eve/src/context/key-names.ts b/packages/eve/src/context/key-names.tsindex 512c237a5..e8b5492ac 100644--- a/packages/eve/src/context/key-names.ts+++ b/packages/eve/src/context/key-names.ts@@ -11,3 +11,5 @@export const CHANNEL_CONTEXT_KEY_NAME = "eve.channel";export const SESSION_CALLBACK_CONTEXT_KEY_NAME = "eve.sessionCallback";++export const TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME = "eve.runtime.taskDeliveryPolicy";diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex 85816b2db..ee753d2f4 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -4,6 +4,7 @@* `#runtime/sessions/runtime-context-keys.ts`.*/+import { TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME } from "#context/key-names.js";import type { LanguageModel, ModelMessage, SystemModelMessage } from "ai";import type {@@ -16,6 +17,7 @@ import type {SessionParent,SessionTraceContext,SessionTurn,+ TaskDeliveryPolicy,} from "#channel/types.js";import { ContextKey } from "#context/key.js";import {@@ -100,6 +102,10 @@ export const SessionTitleKey = new ContextKey<string>("eve.sessionTitle");export const ChannelDeliveryKey = new ContextKey<ChannelDeliveryMetadata>("eve.channelDelivery");/** Accepted messages whose response owns the current turn's durable stream events. */export const TurnDeliveryIdsKey = new ContextKey<readonly string[]>("eve.turnDeliveryIds");+/** Resolved task delivery policy, also read by the workflow inbox. */+export const TaskDeliveryPolicyKey = new ContextKey<TaskDeliveryPolicy>(+ TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME,+);/** Task-reporting phase for the active root turn. */export const TurnTaskDeliveryKey = new ContextKey<"none" | "initiating" | "pending" | "settled">("eve.turnTaskDelivery",diff --git a/packages/eve/src/eve-channel/create-request.ts b/packages/eve/src/eve-channel/create-request.tsindex b9ad052a1..f807ae4e6 100644--- a/packages/eve/src/eve-channel/create-request.ts+++ b/packages/eve/src/eve-channel/create-request.ts@@ -4,11 +4,13 @@ import type {ActivityObserverConfig,SessionCallback,SessionCapabilities,+ TaskDeliveryPolicy,} from "#channel/types.js";import type { JsonObject } from "#shared/json.js";import type { RunMode } from "#shared/run-mode.js";export interface ParsedCreateBody {+ taskDeliveryPolicy?: TaskDeliveryPolicy;activityObserver?: ActivityObserverConfig;callback?: SessionCallback;capabilities?: SessionCapabilities;diff --git a/packages/eve/src/eve-channel/delivery-policy-request.ts b/packages/eve/src/eve-channel/delivery-policy-request.tsnew file mode 100644index 000000000..6246746d9--- /dev/null+++ b/packages/eve/src/eve-channel/delivery-policy-request.ts@@ -0,0 +1,31 @@+import type { UserContent } from "ai";+import type { TaskDeliveryPolicy, TurnPolicy } from "#channel/types.js";++export function parseTaskDeliveryPolicyField(+ value: unknown,+ message: string | UserContent | undefined,+): TaskDeliveryPolicy | undefined | Response {+ if (value === undefined) return undefined;+ if (value !== "auto" && value !== "cohort") {+ return Response.json(+ { error: "Expected 'taskDeliveryPolicy' to be either 'auto' or 'cohort'.", ok: false },+ { status: 400 },+ );+ }+ if (message === undefined) {+ return Response.json(+ { error: "'taskDeliveryPolicy' requires a non-empty 'message'.", ok: false },+ { status: 400 },+ );+ }+ return value;+}++export function parseTurnPolicyField(value: unknown): TurnPolicy | Response | undefined {+ if (value === undefined) return undefined;+ if (value === "queue" || value === "steer") return value;+ return Response.json(+ { error: "Expected 'turnPolicy' to be either 'queue' or 'steer'.", ok: false },+ { status: 400 },+ );+}diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.tsindex d3cac1aef..c531a6076 100644--- a/packages/eve/src/eve-channel/index.ts+++ b/packages/eve/src/eve-channel/index.ts@@ -308,6 +308,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {let handle: Awaited<ReturnType<typeof createSession>>;try {handle = await createSession({+ taskDeliveryPolicy: body.taskDeliveryPolicy,activityObserver: body.activityObserver,audienceAuth: authResult,auth: messageResult.auth,@@ -395,6 +396,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {const session = attachSession(sessionId);const options = attachClientContext({+ taskDeliveryPolicy: body.taskDeliveryPolicy,activityObserver: body.activityObserver,auth: dispatchAuth,callback: body.callback,diff --git a/packages/eve/src/eve-channel/request.task-policy.test.ts b/packages/eve/src/eve-channel/request.task-policy.test.tsnew file mode 100644index 000000000..c4760183e--- /dev/null+++ b/packages/eve/src/eve-channel/request.task-policy.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vitest";+import { parseCreateBody, parseSessionMessageBody } from "#eve-channel/request.js";++describe("task delivery policy on HTTP sends", () => {+ it.each([parseCreateBody, parseSessionMessageBody])("validates policy at %s", async (parse) => {+ for (const taskDeliveryPolicy of ["auto", "cohort"] as const) {+ expect(parse({ message: "Prepare reports", taskDeliveryPolicy })).toMatchObject({+ taskDeliveryPolicy,+ });+ }+ const messageFree = parse({ taskDeliveryPolicy: "cohort" });+ expect(messageFree).toBeInstanceOf(Response);+ expect((messageFree as Response).status).toBe(400);+ const invalid = parse({ message: "Prepare reports", taskDeliveryPolicy: "individual" });+ expect(invalid).toBeInstanceOf(Response);+ expect((invalid as Response).status).toBe(400);+ expect(await (invalid as Response).json()).toMatchObject({+ error: expect.stringContaining("taskDeliveryPolicy"),+ });+ });+});diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.tsindex 752fa3f4d..e25f2bd0f 100644--- a/packages/eve/src/eve-channel/request.ts+++ b/packages/eve/src/eve-channel/request.ts@@ -6,6 +6,7 @@ import type {SessionCallback,SessionCapabilities,TurnPolicy,+ TaskDeliveryPolicy,} from "#channel/types.js";import type { Session } from "#channel/session.js";import { parseSessionCallback } from "#channel/session-callback.js";@@ -34,6 +35,10 @@ import {import { isInputResponse, type ValidatedInputResponse } from "#shared/input.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";import type { RunMode } from "#shared/run-mode.js";+import {+ parseTaskDeliveryPolicyField,+ parseTurnPolicyField,+} from "#eve-channel/delivery-policy-request.js";import { type ParsedCreateBody, validateMessageFreeCreate } from "#eve-channel/create-request.js";const SESSION_STREAM_HEARTBEAT_MS = 10_000;@@ -88,6 +93,8 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBconst mode = parseModeField(payload.mode);if (mode instanceof Response) return mode;+ const taskDeliveryPolicy = parseTaskDeliveryPolicyField(payload.taskDeliveryPolicy, message);+ if (taskDeliveryPolicy instanceof Response) return taskDeliveryPolicy;const outputSchema = parseOutputSchemaField(payload.outputSchema);if (outputSchema instanceof Response) return outputSchema;@@ -111,6 +118,7 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB}const result: ParsedCreateBody = {+ taskDeliveryPolicy,activityObserver,callback,capabilities,@@ -124,6 +132,7 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB}interface ParsedSessionMessageBody {+ taskDeliveryPolicy?: TaskDeliveryPolicy;activityObserver?: ActivityObserverConfig;callback?: SessionCallback;message?: string | UserContent;@@ -153,6 +162,8 @@ export function parseSessionMessageBody(if (inputResponses instanceof Response) return inputResponses;const context = parseClientContextField(payload.clientContext);if (context instanceof Response) return context;+ const taskDeliveryPolicy = parseTaskDeliveryPolicyField(payload.taskDeliveryPolicy, message);+ if (taskDeliveryPolicy instanceof Response) return taskDeliveryPolicy;const outputSchema = parseOutputSchemaField(payload.outputSchema);if (outputSchema instanceof Response) return outputSchema;const turnPolicy = parseTurnPolicyField(payload.turnPolicy);@@ -183,6 +194,7 @@ export function parseSessionMessageBody(context,outputSchema,turnPolicy,+ taskDeliveryPolicy,};}@@ -396,15 +408,6 @@ function parseModeField(value: unknown): RunMode | Response | undefined {);}-function parseTurnPolicyField(value: unknown): TurnPolicy | Response | undefined {- if (value === undefined) return undefined;- if (value === "queue" || value === "steer") return value;- return Response.json(- { error: "Expected 'turnPolicy' to be either 'queue' or 'steer'.", ok: false },- { status: 400 },- );-}-function parseMessageField(value: unknown): string | UserContent | undefined | Response {if (value === undefined) return undefined;if (typeof value === "string") return value.length > 0 ? value : undefined;diff --git a/packages/eve/src/execution/route-child-delivery.test.ts b/packages/eve/src/execution/route-child-delivery.test.tsindex d0759b85b..9b87ffcc7 100644--- a/packages/eve/src/execution/route-child-delivery.test.ts+++ b/packages/eve/src/execution/route-child-delivery.test.ts@@ -187,6 +187,45 @@ describe("task HITL delivery routing", () => {});});+ it("retains every task notification identity after consuming terminal views", async () => {+ const taskDeliveryIds = ["task-1:ready:completed", "task-2:ready:completed"];+ const views = ["task-1", "task-2"].map((taskId) => ({+ taskId,+ status: "completed" as const,+ metadata: { kind: "tool", name: "report" },+ lastOutput: { type: "result" as const, data: taskId },+ }));+ vi.mocked(recordTerminalTaskViewsStep).mockResolvedValue({+ subagentCompletions: [],+ views,+ serializedContext: {},+ sessionState: state(false),+ });+ const result = await routeDeliverToChildren({+ delivery: {+ kind: "deliver",+ taskDeliveryId: taskDeliveryIds[0],+ taskDeliveryIds,+ payloads: views.map((view) => ({ message: view.taskId, task: { views: [view] } })),+ },+ sessionWritable: new WritableStream<Uint8Array>(),+ serializedContext: {},+ sessionState: state(false),+ });+ expect(result).toMatchObject({+ kind: "continue",+ remainder: {+ taskDeliveryId: taskDeliveryIds[0],+ taskDeliveryIds,+ payloads: [+ { message: "Background task task-1 (report) is completed.\n\nResult:\ntask-1" },+ { message: "Background task task-2 (report) is completed.\n\nResult:\ntask-2" },+ ],+ },+ });+ expect(recordTerminalTaskViewsStep).toHaveBeenCalledWith(expect.objectContaining({ views }));+ });+it("adopts instrumentation context returned with terminal task views", async () => {const recordedState = state(false);const view = {diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.tsindex 039698c3f..41a75293c 100644--- a/packages/eve/src/execution/runtime-context.test.ts+++ b/packages/eve/src/execution/runtime-context.test.ts@@ -13,6 +13,7 @@ import {SessionIdKey,SessionKey,ScheduleIdKey,+ TaskDeliveryPolicyKey,SessionTitleKey,} from "#context/keys.js";import { setChannelContext } from "#execution/channel-context.js";@@ -155,6 +156,23 @@ function createMinimalBundle(): Parameters<typeof buildRunContext>[0]["bundle"]}describe("buildRunContext", () => {+ it.each([undefined, "auto", "cohort"] as const)(+ "resolves an ordinary send policy %s",+ (taskDeliveryPolicy) => {+ const ctx = buildRunContext({+ bundle: createMinimalBundle(),+ run: {+ auth: null,+ adapter: { kind: "http" },+ input: { message: "Report" },+ mode: "conversation",+ taskDeliveryPolicy,+ },+ });+ expect(ctx.get(TaskDeliveryPolicyKey)).toBe(taskDeliveryPolicy ?? "auto");+ },+ );+it.each([undefined, testAuth])("defers prewarm initiator identity unless explicitly forwarded (%s)",(initiatorAuth) => {@@ -226,6 +244,31 @@ describe("buildRunContext", () => {expect(ctx.require(ScheduleIdKey)).toBe("dynamic-tasks");});+ it("inherits schedule provenance but not its delivery policy in child sessions", () => {+ const scope = new ContextContainer();+ scope.set(ScheduleIdKey, "automatic-reports");+ scope.set(TaskDeliveryPolicyKey, "auto");+ const ctx = contextStorage.run(scope, () =>+ buildRunContext({+ bundle: createMinimalBundle(),+ run: {+ auth: testAuth,+ adapter: { kind: "subagent" },+ input: { message: "Prepare report A" },+ mode: "task",+ parent: {+ callId: "call-1",+ rootSessionId: "root-session",+ sessionId: "parent-session",+ turn: { id: "turn-1", sequence: 0 },+ },+ },+ }),+ );+ expect(ctx.require(ScheduleIdKey)).toBe("automatic-reports");+ expect(ctx.get(TaskDeliveryPolicyKey)).toBe("cohort");+ });+it("stores a title only for top-level sessions", () => {const root = buildRunContext({bundle: createMinimalBundle(),diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex d120743bc..65d420118 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -17,6 +17,7 @@ import {ParentTraceContextKey,ActivityObserverKey,ScheduleIdKey,+ TaskDeliveryPolicyKey,SessionCallbackKey,SessionTitleKey,} from "#context/keys.js";@@ -89,6 +90,12 @@ export function buildRunContext(input: {ctx.set(ScheduleIdKey, scheduleId);}+ ctx.set(+ TaskDeliveryPolicyKey,+ run.taskDeliveryPolicy ??+ (run.parent !== undefined || scheduleId !== undefined ? "cohort" : "auto"),+ );+if (run.delivery !== undefined) {ctx.set(ChannelDeliveryKey, run.delivery);}diff --git a/packages/eve/src/execution/session-inbox/protocol.test.ts b/packages/eve/src/execution/session-inbox/protocol.test.tsindex e85289bae..a07b3263e 100644--- a/packages/eve/src/execution/session-inbox/protocol.test.ts+++ b/packages/eve/src/execution/session-inbox/protocol.test.ts@@ -10,6 +10,7 @@ describe("session inbox payloads", () => {expect(decodeSessionInboxPayload({delivery: { deliveryId: "delivery-1" },+ taskDeliveryPolicy: "cohort",kind: "send",payload: { message: "hello" },}),@@ -22,6 +23,7 @@ describe("session inbox payloads", () => {requestId: undefined,taskDeliveryId: undefined,turnPolicy: undefined,+ taskDeliveryPolicy: "cohort",});});diff --git a/packages/eve/src/execution/session-inbox/protocol.ts b/packages/eve/src/execution/session-inbox/protocol.tsindex 127dfdfd5..a8b5c41c1 100644--- a/packages/eve/src/execution/session-inbox/protocol.ts+++ b/packages/eve/src/execution/session-inbox/protocol.ts@@ -23,6 +23,13 @@ export function decodeSessionInboxPayload(value: unknown): DecodedSessionInbox {throw new SessionInboxPayloadError("Session inbox payload must be an object with a kind.");}const payload = value as Record<string, unknown>;+ if (+ payload.taskDeliveryPolicy !== undefined &&+ payload.taskDeliveryPolicy !== "auto" &&+ payload.taskDeliveryPolicy !== "cohort"+ ) {+ throw new SessionInboxPayloadError('Task delivery policy must be "auto" or "cohort".');+ }switch (payload.kind) {case "send": {if (payload.payload === null || typeof payload.payload !== "object") {@@ -40,6 +47,7 @@ export function decodeSessionInboxPayload(value: unknown): DecodedSessionInbox {requestId: command.requestId,taskDeliveryId: command.taskDeliveryId,turnPolicy: command.turnPolicy,+ taskDeliveryPolicy: command.taskDeliveryPolicy,};}case "deliver": {diff --git a/packages/eve/src/execution/session/input-queue.ts b/packages/eve/src/execution/session/input-queue.tsindex 96cd6bb67..6cc9a1e88 100644--- a/packages/eve/src/execution/session/input-queue.ts+++ b/packages/eve/src/execution/session/input-queue.ts@@ -1,4 +1,4 @@-import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";+import type { TaskDeliveryPolicy, DeliverHookPayload, DeliverPayload } from "#channel/types.js";import { coalesceDeliveries } from "#harness/messages.js";import { jsonValuesEqual } from "#shared/json.js";import type { getSessionTaskCohorts } from "#tasks/session-task-cohorts.js";@@ -182,6 +182,7 @@ export class SessionInputQueue {cohorts: TaskCohorts,options?: {readonly deferDeliveries?: boolean;+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;/*** Attempt ids of the open authorization challenge. Callbacks for other* attempts are stale and dropped; once every expected attempt has@@ -209,12 +210,20 @@ export class SessionInputQueue {};}}- const index = this.nextActionableIndex(cohorts, options?.deferDeliveries === true);+ const index = this.nextActionableIndex(+ cohorts,+ options?.deferDeliveries === true,+ options?.taskDeliveryPolicy ?? "cohort",+ );if (index < 0) return undefined;return this.takeSelectionAt(index, cohorts, options?.freshSequence);}- private nextActionableIndex(cohorts: TaskCohorts, deferDeliveries: boolean): number {+ private nextActionableIndex(+ cohorts: TaskCohorts,+ deferDeliveries: boolean,+ taskDeliveryPolicy: TaskDeliveryPolicy,+ ): number {const pendingCohorts = new Set<string>();for (const [taskId, cohortId] of cohorts) {// A control step can record cancellation before its notification is admitted.@@ -227,7 +236,7 @@ export class SessionInputQueue {if (entry.kind === "control") return true;if (entry.kind === "authorization" || deferDeliveries) return false;const cohort = terminalCohort(entry.delivery, cohorts);- return cohort === undefined || !pendingCohorts.has(cohort);+ return taskDeliveryPolicy === "auto" || cohort === undefined || !pendingCohorts.has(cohort);});}@@ -331,9 +340,17 @@ export function isSteeringDelivery(}function combine(entries: readonly DeliveryAdmission[]): DeliverHookPayload {- return entries.length === 1- ? entries[0]!.delivery- : coalesceDeliveries(entries.map(({ delivery }) => delivery));+ if (entries.length === 1) return entries[0]!.delivery;+ const deliveries = entries.map(({ delivery }) => delivery);+ const taskDeliveryIds = deliveries.flatMap(+ (delivery) =>+ delivery.taskDeliveryIds ??+ (delivery.taskDeliveryId === undefined ? [] : [delivery.taskDeliveryId]),+ );+ return {+ ...coalesceDeliveries(deliveries),+ taskDeliveryIds: taskDeliveryIds.length > 0 ? taskDeliveryIds : undefined,+ };}function authorizationAttemptId(payload: DeliverPayload): string | undefined {diff --git a/packages/eve/src/execution/session/next-input.test.ts b/packages/eve/src/execution/session/next-input.test.tsindex 0b3fea17c..c03f6d2b1 100644--- a/packages/eve/src/execution/session/next-input.test.ts+++ b/packages/eve/src/execution/session/next-input.test.ts@@ -151,7 +151,7 @@ describe("nextTurnDelivery", () => {kind: "turn",delivery: {auth,- payloads: [...first.payloads, ...second.payloads],+ payloads: [...report(first).payloads, ...report(second).payloads],deliveryMetadata: [first.deliveryMetadata![0],{ ...second.deliveryMetadata![0], payloadIndex: 1 },@@ -579,6 +579,68 @@ describe("buffered task completion batching", () => {},);+ it.each(["completed", "failed", "cancelled"] as const)(+ "auto wakes for a %s outcome while its cross-turn sibling remains unfinished",+ async (status) => {+ const input = batchingInput(2, true);+ await input.cursor.apply({ serializedContext: { "eve.runtime.taskDeliveryPolicy": "auto" } });+ const first =+ status === "completed" ? completion("task_0") : terminalDelivery("task_0", status);+ input.queue.enqueueDelivery(first);+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ kind: "turn",+ delivery: report(first),+ });+ expect(input.queue.pendingCount).toBe(0);+ },+ );++ it("auto combines ready siblings without waiting for the remaining task", async () => {+ const input = batchingInput(3);+ await input.cursor.apply({ serializedContext: { "eve.runtime.taskDeliveryPolicy": "auto" } });+ const first = completion("task_0");+ const second = completion("task_1");+ input.queue.enqueueDelivery(first);+ input.queue.enqueueDelivery(first);+ input.queue.enqueueDelivery(second);+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ kind: "turn",+ delivery: {+ payloads: [...report(first).payloads, ...report(second).payloads],+ taskDeliveryIds: [first.taskDeliveryId, second.taskDeliveryId],+ },+ });+ expect(input.queue.pendingCount).toBe(0);+ input.queue.enqueueDelivery(first);+ expect(input.queue.pendingCount).toBe(0);+ });++ it("auto preserves intervening user input and deferred delivery boundaries", async () => {+ const input = batchingInput(3);+ await input.cursor.apply({ serializedContext: { "eve.runtime.taskDeliveryPolicy": "auto" } });+ const question = {+ kind: "deliver",+ payloads: [{ message: "Alice checks the status." }],+ } as const;+ const first = completion("task_0");+ const second = completion("task_1");+ input.queue.enqueueDelivery(first);+ input.queue.enqueueDelivery(question);+ input.queue.enqueueDelivery(second);+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ kind: "turn",+ delivery: question,+ });+ expect(+ input.queue.takeNext(new Map(), { taskDeliveryPolicy: "auto", deferDeliveries: true }),+ ).toBeUndefined();+ expect(input.queue.pendingCount).toBe(2);+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ kind: "turn",+ delivery: { payloads: [...report(first).payloads, ...report(second).payloads] },+ });+ });+it("delivers 100 buffered sibling results and their metadata in one parent turn", async () => {const input = batchingInput();const deliveries = Array.from({ length: 100 }, (_, index) => completion(`task_${index}`));diff --git a/packages/eve/src/execution/session/next-input.ts b/packages/eve/src/execution/session/next-input.tsindex b4d2179f6..19acf0727 100644--- a/packages/eve/src/execution/session/next-input.ts+++ b/packages/eve/src/execution/session/next-input.ts@@ -1,3 +1,4 @@+import { TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME } from "#context/key-names.js";import type { DeliverPayload } from "#channel/types.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";import { routeSelectedDelivery } from "#execution/session/route-selected-delivery.js";@@ -57,6 +58,10 @@ export async function nextTurnDelivery(input: {getSessionTaskCohorts(cursor.sessionState.snapshot.session.state),{deferDeliveries: input.deferDeliveries,+ taskDeliveryPolicy:+ cursor.serializedContext[TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME] === "auto"+ ? "auto"+ : "cohort",expectedAttemptIds: input.expectedAttemptIds,freshSequence: inbox.hasPending() ? undefined : freshSequence,},diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex e37bae705..bff93be1b 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -2640,6 +2640,74 @@ describe("turnStep", () => {});});+ it.each([+ [undefined, undefined, "auto"],+ ["cohort", undefined, "cohort"],+ ["auto", undefined, "auto"],+ [undefined, "cohort", "cohort"],+ ["auto", "cohort", "cohort"],+ ["cohort", "cohort", "cohort"],+ [undefined, "auto", "auto"],+ ["auto", "auto", "auto"],+ ["cohort", "auto", "auto"],+ ] as const)(+ "updates stored policy %s from explicit send policy %s to %s",+ async (storedPolicy, sendPolicy, expected) => {+ const metadata = { kind: "report-probe", name: "report_probe" };+ const session = createStubSession({+ state: {+ "eve.workflowTool": {+ version: 3,+ runs: ["A", "B"].map((taskId) => ({+ callId: taskId,+ toolName: metadata.name,+ lifetime: "session",+ origin: { turnId: "turn-parent", stepIndex: 0 },+ address: { runId: `run-${taskId}`, hookToken: `inbox-${taskId}` },+ task: {+ taskId,+ cohortId: "A",+ dispatchContext: { auth: { current: null, initiator: null } },+ metadata,+ ...(taskId === "A"+ ? {+ outcome: {+ status: "completed",+ lastOutput: { type: "result", data: "Report A" },+ },+ }+ : {}),+ },+ })),+ },+ },+ });+ installSessionStoreMocks([session]);+ const phases: unknown[] = [];+ vi.mocked(createExecutionNodeStep).mockImplementation(() => async (session) => {+ phases.push(contextStorage.getStore()?.get(TurnTaskDeliveryKey));+ return { next: { done: true, output: "ok" }, session };+ });+ const serializedContext = createSerializedContext();+ if (storedPolicy !== undefined) {+ serializedContext["eve.runtime.taskDeliveryPolicy"] = storedPolicy;+ }+ const result = await turnStep({+ input: {+ kind: "deliver",+ taskDeliveryPolicy: sendPolicy,+ taskDeliveryId: "A:ready:completed",+ payloads: [{ message: "A completed." }],+ },+ sessionWritable: createTestWritable(),+ serializedContext,+ sessionState: createStubSessionState(),+ });+ expect(result.serializedContext["eve.runtime.taskDeliveryPolicy"]).toBe(expected);+ expect(phases).toEqual(["pending"]);+ },+ );+it("marks task-owned deliveries even when task state is unavailable", async () => {const observedInputs: unknown[] = [];const observedTaskDeliveries: unknown[] = [];diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsindex e9aa1fe06..be8265760 100644--- a/packages/eve/src/execution/session/turn-step.ts+++ b/packages/eve/src/execution/session/turn-step.ts@@ -25,6 +25,7 @@ import {SessionDynamicToolRuntimeRevisionKey,StaticModelReferenceKey,TurnTaskDeliveryKey,+ TaskDeliveryPolicyKey,TurnDeliveryIdsKey,} from "#context/keys.js";import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";@@ -120,6 +121,9 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>const adapter = ctx.require(ChannelKey);const bundle = ctx.require(BundleKey);const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);+ const taskDeliveryPolicy =+ rawDelivery?.taskDeliveryPolicy ?? ctx.get(TaskDeliveryPolicyKey) ?? "auto";+ ctx.set(TaskDeliveryPolicyKey, taskDeliveryPolicy);// Populate the callback base URL so getHookUrl() works during tool// execution, preferring eve's active local origin over metadata fallback.@@ -307,7 +311,10 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>if (resolved !== undefined && backgroundTaskDelivery !== undefined) {const taskContext = resolveTaskDeliveryContext({state: durableSession.state,- taskDeliveryId: backgroundTaskDelivery.taskDeliveryId,+ taskDeliveryIds: backgroundTaskDelivery.taskDeliveryIds ?? [+ backgroundTaskDelivery.taskDeliveryId,+ ],+ taskDeliveryPolicy,});if (taskContext !== undefined) {ctx.set(TurnTaskDeliveryKey, taskContext.phase);diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.tsindex 3d8f45e26..6c4bb09d5 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts@@ -1,6 +1,7 @@import {type BackgroundWorkflowToolRun,findBackgroundWorkflowToolRun,+ getBackgroundWorkflowToolRuns,registerWorkflowToolRun,} from "#harness/workflow-tool-runs.js";import type { ContextContainer } from "#context/container.js";@@ -187,7 +188,11 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {}hasPendingTasks(): boolean {- return this.records.some((record) => record.settled && record.task !== undefined);+ return (+ getBackgroundWorkflowToolRuns(this.initialSession.state).some(+ (entry) => entry.task.outcome === undefined,+ ) || this.records.some((record) => record.settled && record.task !== undefined)+ );}async commit(session: HarnessSession): Promise<HarnessSession> {diff --git a/packages/eve/src/harness/messages.test.ts b/packages/eve/src/harness/messages.test.tsindex bb9d8a055..a158b4713 100644--- a/packages/eve/src/harness/messages.test.ts+++ b/packages/eve/src/harness/messages.test.ts@@ -31,6 +31,23 @@ function textFilePart(overrides: {}describe("coalesceDeliveries", () => {+ it("keeps the last explicit task policy when batching authored sends", () => {+ const result = coalesceDeliveries([+ {+ kind: "deliver" as const,+ payloads: [{ message: "First" }],+ taskDeliveryPolicy: "cohort" as const,+ },+ {+ kind: "deliver" as const,+ payloads: [{ message: "Second" }],+ taskDeliveryPolicy: "auto" as const,+ },+ { kind: "deliver" as const, payloads: [{ message: "Third" }] },+ ]);+ expect(result.taskDeliveryPolicy).toBe("auto");+ });+const caller = {callId: "call-1",replyTo: { kind: "hook" as const, token: "turn-caller" },diff --git a/packages/eve/src/harness/messages.ts b/packages/eve/src/harness/messages.tsindex 2c02080cb..cf7f43b85 100644--- a/packages/eve/src/harness/messages.ts+++ b/packages/eve/src/harness/messages.ts@@ -5,6 +5,7 @@ import type {DeliverPayload,SessionAuthContext,TurnCaller,+ TaskDeliveryPolicy,} from "#channel/types.js";import type { InputResponse } from "#shared/input.js";import type { StepInput } from "#harness/types.js";@@ -398,6 +399,7 @@ interface DeliverLike {readonly auth?: SessionAuthContext | null;readonly caller?: TurnCaller;readonly deliveryMetadata?: readonly ChannelDeliveryMetadataEntry[];+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;readonly kind: "deliver";readonly payloads: readonly DeliverPayload[];}@@ -420,12 +422,14 @@ export function coalesceDeliveries<T extends DeliverLike>(items: readonly T[]):}let auth = first.auth;+ let taskDeliveryPolicy = first.taskDeliveryPolicy;let caller = first.caller;const payloads = [...first.payloads];const deliveryMetadata = [...(first.deliveryMetadata ?? [])];for (const item of rest) {const payloadOffset = payloads.length;+ taskDeliveryPolicy = item.taskDeliveryPolicy ?? taskDeliveryPolicy;if (item.auth !== undefined) {auth = item.auth;}@@ -446,6 +450,7 @@ export function coalesceDeliveries<T extends DeliverLike>(items: readonly T[]):return {...first,+ taskDeliveryPolicy,auth,caller,deliveryMetadata: deliveryMetadata.length === 0 ? undefined : deliveryMetadata,diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 2522b5ebb..91e07d6a9 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -34,6 +34,7 @@ import {SessionDynamicSubagentSelectionsKey,StepDynamicToolMetadataKey,TurnTaskDeliveryKey,+ TaskDeliveryPolicyKey,} from "#context/keys.js";import { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";import { invocationOwnerKey } from "#internal/invocation/metadata.js";@@ -872,6 +873,90 @@ function createGatewayModelCallError(input: {}describe("createToolLoopHarness", () => {+ it("keeps a scheduled task session alive across individual results until all tasks settle", async () => {+ const { SessionInputQueue } = await import("#execution/session/input-queue.js");+ const { getSessionTaskCohorts } = await import("#tasks/session-task-cohorts.js");+ const { recordWorkflowTaskView, findBackgroundWorkflowToolRun } =+ await import("#harness/workflow-tool-runs.js");+ const { resolveTaskDeliveryContext } = await import("#tasks/delivery-context.js");+ const { backgroundToolExecutionProvider } =+ await import("#execution/tasks/parent/tool-execution.js");+ const schema = {+ properties: { summary: { type: "string" } },+ required: ["summary"],+ type: "object",+ } as const;+ let session = recordBackgroundTask(+ recordBackgroundTask(createTestSession({ outputSchema: schema }), "A"),+ "B",+ );+ const queue = new SessionInputQueue();+ queue.enqueueDelivery({+ kind: "deliver",+ taskDeliveryId: "A:ready:completed",+ payloads: [{ message: "A completed" }],+ });+ expect(+ queue.takeNext(getSessionTaskCohorts(session.state), { taskDeliveryPolicy: "cohort" }),+ ).toBeUndefined();+ expect(+ queue.takeNext(getSessionTaskCohorts(session.state), { taskDeliveryPolicy: "auto" })?.kind,+ ).toBe("turn");+ session = {+ ...session,+ state: recordWorkflowTaskView(session.state, {+ taskId: "A",+ metadata: { kind: "report-probe", name: "A" },+ status: "completed",+ lastOutput: { type: "result", data: "Report A" },+ }),+ };+ const report = resolveTaskDeliveryContext({+ state: session.state,+ taskDeliveryIds: ["A:ready:completed"],+ taskDeliveryPolicy: "auto",+ })!;+ const ctx = new ContextContainer();+ ctx.set(ScheduleIdKey, "scheduled-report");+ ctx.set(TurnTaskDeliveryKey, report.phase);+ const scope = await backgroundToolExecutionProvider.create(ctx, session);+ if (scope === undefined) throw new Error("Expected background executor");+ ctx.set(BackgroundToolExecutorKey, scope.value);+ expect(scope.value.hasPendingTasks?.()).toBe(true);+ setupMockAgent(finalOutputResult("Report A", { summary: "Report A" }));+ const runStep = createToolLoopHarness(createTestConfig("task"));+ const result = await contextStorage.run(ctx, () =>+ runStep(session, { message: "A completed", context: [report.context] }),+ );+ expect(findBackgroundWorkflowToolRun(result.session.state, "B")?.task.outcome).toBeUndefined();+ expect(result.next).toBeNull();++ session = {+ ...result.session,+ state: recordWorkflowTaskView(result.session.state, {+ taskId: "B",+ metadata: { kind: "report-probe", name: "B" },+ status: "completed",+ lastOutput: { type: "result", data: "Report B" },+ }),+ };+ const finalReport = resolveTaskDeliveryContext({+ state: session.state,+ taskDeliveryIds: ["B:ready:completed"],+ taskDeliveryPolicy: "auto",+ })!;+ ctx.set(TurnTaskDeliveryKey, finalReport.phase);+ const finalScope = await backgroundToolExecutionProvider.create(ctx, session);+ if (finalScope === undefined) throw new Error("Expected background executor");+ ctx.set(BackgroundToolExecutorKey, finalScope.value);+ expect(finalScope.value.hasPendingTasks?.()).toBe(false);+ setupMockAgent(finalOutputResult("Report B", { summary: "Report B" }));+ const finalResult = await contextStorage.run(ctx, () =>+ runStep(session, { message: "B completed", context: [finalReport.context] }),+ );+ expect(finalResult.next).toEqual({ done: true, output: { summary: "Report B" } });+ });+it("uses one projected history view for step consumers while preserving raw history", async () => {setupMockAgent({finishReason: "stop",@@ -13237,6 +13322,46 @@ describe("createToolLoopHarness", () => {]);});+ it.each(["pending", "settled"] as const)(+ "auto permits a silent %s result turn",+ async (phase) => {+ setupMockAgent({+ finishReason: "stop",+ response: { messages: [{ role: "assistant", content: EMPTY_DELIVERY_SENTINEL }] },+ text: EMPTY_DELIVERY_SENTINEL,+ toolCalls: [],+ toolResults: [],+ });+ const ctx = new ContextContainer();+ ctx.set(TurnTaskDeliveryKey, phase);+ ctx.set(TaskDeliveryPolicyKey, "auto");+ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(createTestConfig("conversation", emit));+ const result = await contextStorage.run(ctx, () =>+ runStep(+ createTestSession(),+ markFrameworkStepInput(+ { message: "Background task A completed." },+ "execution.background_task",+ ),+ ),+ );+ expect(result.next).toBeNull();+ expect(getLastAgentSettings().messages).toContainEqual(+ expect.objectContaining({+ content: expect.stringContaining("previously withheld results"),+ }),+ );+ expect(events).toContainEqual(+ expect.objectContaining({+ type: "message.completed",+ data: expect.objectContaining({ message: null }),+ }),+ );+ expect(vi.mocked(ToolLoopAgent)).toHaveBeenCalledTimes(1);+ },+ );+it("adds settled task-delivery guidance to a top-level framework wake", async () => {setupMockAgent(defaultModelResult());const runStep = createToolLoopHarness(createTestConfig("conversation"));diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 848470c64..cd8636117 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -36,6 +36,7 @@ import {SessionCallbackKey,StaticModelReferenceKey,TurnTaskDeliveryKey,+ TaskDeliveryPolicyKey,} from "#context/keys.js";import {buildDynamicInstructionMessages,@@ -1240,6 +1241,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {isChild: ctx?.get(ParentSessionKey) !== undefined,isFirstTurn,taskDeliveryPhase: ctx?.get(TurnTaskDeliveryKey),+ taskDeliveryPolicy: ctx?.get(TaskDeliveryPolicyKey),});// --- Execute via ToolLoopAgent ------------------------------------------diff --git a/packages/eve/src/harness/workflow-tool-run-registry.test.ts b/packages/eve/src/harness/workflow-tool-run-registry.test.tsindex a8fd286cc..ed9b0767e 100644--- a/packages/eve/src/harness/workflow-tool-run-registry.test.ts+++ b/packages/eve/src/harness/workflow-tool-run-registry.test.ts@@ -70,8 +70,11 @@ describe("shared workflow invocation ownership", () => {waiting("turn-b"),);expect(- resolveTaskDeliveryContext({ state: session.state, taskDeliveryId: "task-a:ready:completed" })- ?.phase,+ resolveTaskDeliveryContext({+ state: session.state,+ taskDeliveryIds: ["task-a:ready:completed"],+ taskDeliveryPolicy: "cohort",+ })?.phase,).toBe("pending");session = {...session,@@ -88,7 +91,8 @@ describe("shared workflow invocation ownership", () => {const beforeReport = JSON.stringify(restored);const report = resolveTaskDeliveryContext({state: restored,- taskDeliveryId: "task-b:ready:failed",+ taskDeliveryIds: ["task-b:ready:failed"],+ taskDeliveryPolicy: "cohort",});expect(report?.phase).toBe("settled");expect(report?.context).toContain("first");diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.tsindex a3726b7b1..e057fab18 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts@@ -1,4 +1,5 @@-import { describe, expect, it, vi } from "vitest";+import { describe, expect, expectTypeOf, it, vi } from "vitest";+import type { Message as ExternalMessage, Thread as ExternalThread } from "chat";import { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";@@ -30,6 +31,11 @@ import type {} from "#compiled/chat/index.js";import { Message, parseMarkdown } from "#compiled/chat/index.js";+it("shares Chat SDK type identity with external adapters and handlers", () => {+ expectTypeOf<Message>().toEqualTypeOf<ExternalMessage>();+ expectTypeOf<Thread>().toEqualTypeOf<ExternalThread>();+});+const THREAD_ID = "test:C01:1700000000.000001";const CHANNEL_ID = "test:C01";@@ -226,7 +232,12 @@ describe("chatSdkChannel", () => {});bridge.bot.onNewMention(async (thread: Thread, message: Message) => {- await bridge.send(message.text, { auth: AUTH, thread, title: "mention" });+ await bridge.send(message.text, {+ auth: AUTH,+ thread,+ title: "mention",+ taskDeliveryPolicy: "cohort",+ });});const { cancel, response, send } = await firePost(bridge.channel, "/eve/v1/test", {@@ -249,6 +260,7 @@ describe("chatSdkChannel", () => {},},title: "mention",+ taskDeliveryPolicy: "cohort",});});diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.tsindex 7b57bd277..9325486f4 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts@@ -8,7 +8,7 @@ import {} from "#channel/channel-operations.js";import { normalizeSendInput } from "#channel/send-input.js";import type { SendPayload } from "#channel/routes.js";-import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy, TaskDeliveryPolicy } from "#channel/types.js";import { ContextContainer, contextStorage } from "#context/container.js";import { ContextKey } from "#context/key.js";import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";@@ -136,14 +136,13 @@ export interface ChatSdkEventContext<TAdapters extends ChatSdkAdapters = ChatSdkexport type ChatSdkChannelEvents<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> =ChannelEvents<ChatSdkChannelContext<TAdapters>>;-/**- * Options for `bridge.send(...)` inside Chat SDK handlers. The `thread`- * determines the eve continuation token and the persisted channel state.- */+/** The thread determines the eve continuation token and persisted channel state. */export interface ChatSdkSendOptions {readonly auth?: SessionAuthContext | null;readonly callback?: ChannelAddressDeliveryOptions<ChatSdkChannelState>["callback"];readonly mode?: ChannelAddressDeliveryOptions<ChatSdkChannelState>["mode"];+ /** Updates the session policy; omission preserves it. */+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;readonly thread: SerializedThread | Thread | string;readonly title?: string;/**@@ -280,7 +279,7 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>({ inputResponses: [response] },{auth: config.resolveInputAuth ? await config.resolveInputAuth(event) : null,- thread: event.thread,+ thread: event.thread.toJSON(),},);});@@ -582,6 +581,8 @@ async function bridgeSend<TAdapters extends ChatSdkAdapters>(if (options.mode !== undefined) deliveryOptions.mode = options.mode;if (options.title !== undefined) deliveryOptions.title = options.title;if (options.turnPolicy !== undefined) deliveryOptions.turnPolicy = options.turnPolicy;+ if (options.taskDeliveryPolicy !== undefined)+ deliveryOptions.taskDeliveryPolicy = options.taskDeliveryPolicy;const source = active.from(thread.id) as InternalChannelSource<ChatSdkChannelState>;return source[INTERNAL_CHANNEL_DELIVER](payload, deliveryOptions);}diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.tsindex 4ec1a58be..8114c7e1b 100644--- a/packages/eve/src/public/channels/index.ts+++ b/packages/eve/src/public/channels/index.ts@@ -40,6 +40,7 @@ export {type SessionRespondOptions,type SessionSendOptions,type TurnPolicy,+ type TaskDeliveryPolicy,type RouteDefinition,type RouteHandlerArgs,type HttpRouteDefinition,diff --git a/packages/eve/src/public/channels/linq/linqChannel.test.ts b/packages/eve/src/public/channels/linq/linqChannel.test.tsindex ff26596f4..a3c3fd240 100644--- a/packages/eve/src/public/channels/linq/linqChannel.test.ts+++ b/packages/eve/src/public/channels/linq/linqChannel.test.ts@@ -46,7 +46,10 @@ describe("linqChannel", () => {if (handler === undefined) throw new Error("Expected an inbound direct-message handler.");const thread = { id: "thread-id" };const message = new Message({- author: { isBot: false, isMe: false, userId: "user", userName: "user" },+ attachments: [],+ formatted: { type: "root", children: [] },+ metadata: { dateSent: new Date(0), edited: false },+ author: { fullName: "User", isBot: false, isMe: false, userId: "user", userName: "user" },id: "message-id",raw: {},text: "Hello Linq",@@ -97,7 +100,10 @@ describe("linqChannel", () => {if (handler === undefined) throw new Error("Expected an inbound direct-message handler.");const thread = { id: "thread-id" };const message = new Message({- author: { isBot: false, isMe: false, userId: "user", userName: "user" },+ attachments: [],+ formatted: { type: "root", children: [] },+ metadata: { dateSent: new Date(0), edited: false },+ author: { fullName: "User", isBot: false, isMe: false, userId: "user", userName: "user" },id: "message-id",raw: {},text: " \n",diff --git a/packages/eve/src/public/channels/photon/inboundContent.test.ts b/packages/eve/src/public/channels/photon/inboundContent.test.tsindex c031c075e..fc1d80e24 100644--- a/packages/eve/src/public/channels/photon/inboundContent.test.ts+++ b/packages/eve/src/public/channels/photon/inboundContent.test.ts@@ -6,7 +6,9 @@ import { photonInboundContent } from "#public/channels/photon/inboundContent.js"function message(text: string, attachments: Message["attachments"] = []): Message {return new Message({attachments,- author: { isBot: false, isMe: false, userId: "user", userName: "user" },+ formatted: { type: "root", children: [] },+ metadata: { dateSent: new Date(0), edited: false },+ author: { fullName: "User", isBot: false, isMe: false, userId: "user", userName: "user" },id: "message-id",raw: {},text,diff --git a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.tsindex 6a0e471f0..a45573e38 100644--- a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts+++ b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts@@ -43,7 +43,10 @@ describe("photonIMessageChannel", () => {if (handler === undefined) throw new Error("Expected an inbound direct-message handler.");const thread = { id: "thread-id" };const message = new Message({- author: { isBot: false, isMe: false, userId: "user", userName: "user" },+ attachments: [],+ formatted: { type: "root", children: [] },+ metadata: { dateSent: new Date(0), edited: false },+ author: { fullName: "User", isBot: false, isMe: false, userId: "user", userName: "user" },id: "message-id",raw: {},text: "Steer this response",@@ -66,7 +69,10 @@ describe("photonIMessageChannel", () => {if (handler === undefined) throw new Error("Expected an inbound direct-message handler.");const thread = { id: "thread-id" };const message = new Message({- author: { isBot: false, isMe: false, userId: "user", userName: "user" },+ attachments: [],+ formatted: { type: "root", children: [] },+ metadata: { dateSent: new Date(0), edited: false },+ author: { fullName: "User", isBot: false, isMe: false, userId: "user", userName: "user" },id: "message-id",raw: {},text: "Hello Photon",@@ -100,7 +106,10 @@ describe("photonIMessageChannel", () => {if (handler === undefined) throw new Error("Expected an inbound direct-message handler.");const thread = { id: "thread-id" };const message = new Message({- author: { isBot: false, isMe: false, userId: "user", userName: "user" },+ attachments: [],+ formatted: { type: "root", children: [] },+ metadata: { dateSent: new Date(0), edited: false },+ author: { fullName: "User", isBot: false, isMe: false, userId: "user", userName: "user" },id: "message-id",raw: {},text: " \n",@@ -122,7 +131,10 @@ describe("photonIMessageChannel", () => {}const thread = { id: "group-thread-id" };const message = new Message({- author: { isBot: false, isMe: false, userId: "user", userName: "user" },+ attachments: [],+ formatted: { type: "root", children: [] },+ metadata: { dateSent: new Date(0), edited: false },+ author: { fullName: "User", isBot: false, isMe: false, userId: "user", userName: "user" },id: "message-id",raw: {},text: "Hello group",diff --git a/packages/eve/src/public/channels/slack/mrkdwn.test.ts b/packages/eve/src/public/channels/slack/mrkdwn.test.tsindex ac8a708de..b74e2a305 100644--- a/packages/eve/src/public/channels/slack/mrkdwn.test.ts+++ b/packages/eve/src/public/channels/slack/mrkdwn.test.ts@@ -41,8 +41,8 @@ describe("slackMrkdwnToGfm", () => {expect(slackMrkdwnToGfm("hi <@U123>")).toBe("hi @U123");});- it("decodes channel mentions", () => {- expect(slackMrkdwnToGfm("see <#C1|general> and <#C2>")).toBe("see #general and #C2");+ it("decodes channel mentions while retaining channel IDs", () => {+ expect(slackMrkdwnToGfm("see <#C1|general> and <#C2>")).toBe("see #general (C1) and #C2");});it("decodes broadcast mentions", () => {diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 8dc93ffbb..408e1e1ef 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -2725,7 +2725,7 @@ describe("slackChannel() generic Events API pipeline", () => {expect(compact).toHaveBeenCalledWith("C01:1700000000.000001");});- it("binds Slack session state and title when a generic event send creates", async () => {+ it("binds Slack state, title, and task policy on a generic event send", async () => {const send = vi.fn().mockResolvedValue({ id: "s1" });const channel = slackChannel({credentials: { botToken: "xoxb-test" },@@ -2734,6 +2734,7 @@ describe("slackChannel() generic Events API pipeline", () => {auth: null,target: { channelId: "C01", threadTs: "1700000000.000001" },title: "Reaction follow-up",+ taskDeliveryPolicy: "cohort",});},});@@ -2752,6 +2753,7 @@ describe("slackChannel() generic Events API pipeline", () => {triggeringUserId: "U01",},title: "Reaction follow-up",+ taskDeliveryPolicy: "cohort",});});diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex 44ce0f44b..337ea38f4 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -9,7 +9,7 @@ import type {import { defaultDeliverResult } from "#channel/adapter.js";import type { Session, SessionHandle } from "#channel/session.js";import { setChannelActivityRenderers } from "#channel/compiled-channel.js";-import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy, TaskDeliveryPolicy } from "#channel/types.js";import type { CardElement } from "#compiled/chat/index.js";import type { SessionContext } from "#public/definitions/callback-context.js";import type { ChannelContinuationOps } from "#public/definitions/channel.js";@@ -336,6 +336,8 @@ export interface SlackInitialMessage {* Options for one turn requested by a generic Slack event handler.*/export interface SlackEventSendOptions {+ /** Updates the session policy; omission preserves it. */+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;readonly auth: SessionAuthContext | null;readonly target: SlackReceiveTarget;/** Overrides the workflow run title without changing the message sent to the model. */@@ -1062,6 +1064,7 @@ async function receiveOnSlack(readonly message: string | UserContent;readonly target: SlackReceiveTarget;readonly title?: string;+ readonly taskDeliveryPolicy?: TaskDeliveryPolicy;},deps: {readonly from: ChannelFrom<SlackChannelState>;@@ -1140,6 +1143,7 @@ async function receiveOnSlack(auth: input.auth,state,title: input.title,+ taskDeliveryPolicy: input.taskDeliveryPolicy,});}@@ -1465,9 +1469,9 @@ async function dispatchSlackEvent(input: {input.resolveSession(slackContinuationToken(target.channelId, target.threadTs)),respond: (inputResponses, { auth, target }) =>sourceFor(target).respond(inputResponses, { auth }),- send: (message, { auth, target, title }) =>+ send: (message, { auth, target, title, taskDeliveryPolicy }) =>receiveOnSlack(- { auth, message, target, title },+ { auth, message, target, title, taskDeliveryPolicy },{from: input.from,credentials: input.credentials,diff --git a/packages/eve/src/public/channels/task-delivery-policy.test.ts b/packages/eve/src/public/channels/task-delivery-policy.test.tsnew file mode 100644index 000000000..29520f481--- /dev/null+++ b/packages/eve/src/public/channels/task-delivery-policy.test.ts@@ -0,0 +1,58 @@+import { expectTypeOf, it } from "vitest";++import type {+ ChannelSendOptions,+ SessionSendOptions,+ defineChannel,+} from "#public/channels/index.js";+import type { chatSdkChannel, ChatSdkSendOptions } from "#public/channels/chat-sdk/index.js";+import type { discordChannel } from "#public/channels/discord/index.js";+import type { eveChannel } from "#public/channels/eve.js";+import type { githubChannel } from "#public/channels/github/index.js";+import type { linearChannel } from "#public/channels/linear/index.js";+import type { linqChannel } from "#public/channels/linq/index.js";+import type { mcpChannel } from "#public/channels/mcp.js";+import type { photonIMessageChannel } from "#public/channels/photon/index.js";+import type {+ slackChannel,+ SlackSendOptions,+ SlackEventSendOptions,+} from "#public/channels/slack/index.js";+import type { teamsChannel } from "#public/channels/teams/index.js";+import type { telegramChannel } from "#public/channels/telegram/index.js";+import type { twilioChannel } from "#public/channels/twilio/index.js";+import type { ScheduleDefinition } from "#public/schedules/index.js";++it("exposes task delivery policy on sends, not channel or schedule definitions", () => {+ expectTypeOf<ChannelSendOptions>()+ .toHaveProperty("taskDeliveryPolicy")+ .toEqualTypeOf<"auto" | "cohort" | undefined>();+ expectTypeOf<SessionSendOptions>()+ .toHaveProperty("taskDeliveryPolicy")+ .toEqualTypeOf<"auto" | "cohort" | undefined>();+ expectTypeOf<ChatSdkSendOptions>()+ .toHaveProperty("taskDeliveryPolicy")+ .toEqualTypeOf<"auto" | "cohort" | undefined>();+ expectTypeOf<SlackSendOptions>()+ .toHaveProperty("taskDeliveryPolicy")+ .toEqualTypeOf<"auto" | "cohort" | undefined>();+ expectTypeOf<SlackEventSendOptions>()+ .toHaveProperty("taskDeliveryPolicy")+ .toEqualTypeOf<"auto" | "cohort" | undefined>();+ expectTypeOf<Parameters<typeof defineChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof chatSdkChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof discordChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof eveChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof githubChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof linearChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof linqChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof mcpChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof photonIMessageChannel>[0]>().not.toHaveProperty(+ "taskDeliveryPolicy",+ );+ expectTypeOf<Parameters<typeof slackChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof teamsChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof telegramChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<Parameters<typeof twilioChannel>[0]>().not.toHaveProperty("taskDeliveryPolicy");+ expectTypeOf<ScheduleDefinition>().not.toHaveProperty("taskDeliveryPolicy");+});diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex e31f71192..e94aa4cd9 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -37,6 +37,7 @@ export type {ResetSessionResult,SessionCallback,TurnPolicy,+ TaskDeliveryPolicy,} from "#channel/types.js";export type { Session, SessionHandle } from "#channel/session.js";export type { ChannelAudience } from "#shared/channel-audience.js";diff --git a/packages/eve/src/tasks/delivery-context.test.ts b/packages/eve/src/tasks/delivery-context.test.tsindex d89737b6b..1818c3ab9 100644--- a/packages/eve/src/tasks/delivery-context.test.ts+++ b/packages/eve/src/tasks/delivery-context.test.ts@@ -101,6 +101,60 @@ describe("resolveInitiatingTaskContext", () => {});describe("resolveTaskDeliveryContext", () => {+ it("auto retains earlier outputs and pending siblings for a later combined report", () => {+ const first = {+ taskId: "task_1",+ status: "completed",+ metadata,+ lastOutput: { type: "result", data: "first" },+ } as const;+ const second = {+ ...first,+ taskId: "task_2",+ lastOutput: { type: "result", data: "second" },+ } as const;+ const state = taskState([+ taskEntry("task_1", "turn_1", first),+ {+ ...taskEntry("task_2", "turn_2", second),+ task: { ...taskEntry("task_2", "turn_2", second).task, cohortId: "task_1" },+ },+ {+ ...taskEntry("task_3", "turn_3"),+ task: { ...taskEntry("task_3", "turn_3").task, cohortId: "task_1" },+ },+ ]);+ const result = resolveTaskDeliveryContext({+ state,+ taskDeliveryIds: ["task_2:ready:completed"],+ taskDeliveryPolicy: "auto",+ });+ expect(result?.phase).toBe("pending");+ expect(result?.rootTurnId).toBe("turn_2");+ expect(JSON.parse(result!.context.slice(TASK_DELIVERY_CONTEXT_LABEL.length))).toEqual({+ tasks: [+ { name: metadata.name, output: first.lastOutput, status: "completed", taskId: "task_1" },+ { name: metadata.name, output: second.lastOutput, status: "completed", taskId: "task_2" },+ { name: metadata.name, status: "pending", taskId: "task_3" },+ ],+ });+ const batch = resolveTaskDeliveryContext({+ state,+ taskDeliveryIds: ["task_2:ready:completed", "task_1:ready:completed"],+ taskDeliveryPolicy: "auto",+ });+ expect(batch).toEqual(result);+ });++ it("auto keeps an advisory wake pending until the delivered task is terminal", () => {+ const result = resolveTaskDeliveryContext({+ state: taskState([taskEntry("task_1", "turn_1")]),+ taskDeliveryIds: ["task_1:message:1"],+ taskDeliveryPolicy: "auto",+ });+ expect(result?.phase).toBe("pending");+ });+it("includes completed siblings while a cross-turn cohort is pending", () => {const completed = {lastOutput: { data: { result: "first" }, type: "result" },@@ -117,14 +171,18 @@ describe("resolveTaskDeliveryContext", () => {taskEntry("task_3", "turn_1"),]);- expect(resolveTaskDeliveryContext({ state, taskDeliveryId: "task_1:ready:completed" })).toEqual(- {- context:- '[Task state]\n{"tasks":[{"name":"report_probe","status":"completed","taskId":"task_1"},{"name":"report_probe","status":"pending","taskId":"task_2"}]}',- phase: "pending",- rootTurnId: "turn_1",- },- );+ expect(+ resolveTaskDeliveryContext({+ state,+ taskDeliveryIds: ["task_1:ready:completed"],+ taskDeliveryPolicy: "cohort",+ }),+ ).toEqual({+ context:+ '[Task state]\n{"tasks":[{"name":"report_probe","status":"completed","taskId":"task_1"},{"name":"report_probe","status":"pending","taskId":"task_2"}]}',+ phase: "pending",+ rootTurnId: "turn_1",+ });});it("includes every output once the parent has received the whole terminal cohort", () => {@@ -150,7 +208,8 @@ describe("resolveTaskDeliveryContext", () => {task: { ...taskEntry("task_2", "turn_2", second).task, cohortId: "task_1" },},]),- taskDeliveryId: "task_2:ready:completed",+ taskDeliveryIds: ["task_2:ready:completed"],+ taskDeliveryPolicy: "cohort",}),).toEqual({context:@@ -184,7 +243,8 @@ describe("resolveTaskDeliveryContext", () => {]);const result = resolveTaskDeliveryContext({state,- taskDeliveryId: "task_cancelled:ready:cancelled",+ taskDeliveryIds: ["task_cancelled:ready:cancelled"],+ taskDeliveryPolicy: "cohort",});expect(result).toMatchObject({ phase: "settled", rootTurnId: "turn_2" });expect(JSON.parse(result!.context.slice(`${TASK_DELIVERY_CONTEXT_LABEL}\n`.length))).toEqual({@@ -199,14 +259,18 @@ describe("resolveTaskDeliveryContext", () => {expect(result!.context).not.toContain("createdByTurnId");});- it("returns no context when the delivery is not owned by the session task index", () => {- expect(- resolveTaskDeliveryContext({- state: taskState([taskEntry("task_1", "turn_1")]),- taskDeliveryId: "task_unknown:ready:completed",- }),- ).toBeUndefined();- });+ it.each([{ taskDeliveryIds: [] }, { taskDeliveryIds: ["task_unknown:ready:completed"] }])(+ "returns no context for missing or unowned deliveries: $taskDeliveryIds",+ ({ taskDeliveryIds }) => {+ expect(+ resolveTaskDeliveryContext({+ state: taskState([taskEntry("task_1", "turn_1")]),+ taskDeliveryIds,+ taskDeliveryPolicy: "cohort",+ }),+ ).toBeUndefined();+ },+ );});function taskEntry(diff --git a/packages/eve/src/tasks/delivery-context.ts b/packages/eve/src/tasks/delivery-context.tsindex 741dc4f15..a994d4c4a 100644--- a/packages/eve/src/tasks/delivery-context.ts+++ b/packages/eve/src/tasks/delivery-context.ts@@ -1,4 +1,4 @@-import type { DeliverHookPayload } from "#channel/types.js";+import type { TaskDeliveryPolicy, DeliverHookPayload } from "#channel/types.js";import { markFrameworkStepInput } from "#harness/messages.js";import type { SessionStateMap, StepInput } from "#harness/types.js";import { EMPTY_DELIVERY_SENTINEL } from "#shared/empty-delivery.js";@@ -16,7 +16,9 @@ The latest ${TASK_DELIVERY_CONTEXT_LABEL} message is runtime-authored and listsContinue carrying out the user's request, including starting any remaining background work. When no further tool calls are needed in this turn, send one brief user-facing acknowledgement that the background work has started. Do not wait for results or report results that are not available yet. End the turn after the acknowledgement.`;-export const TASK_DELIVERY_SETTLED_INSTRUCTION = `Background task reporting\nThis turn was triggered by background task activity. The accompanying ${TASK_DELIVERY_CONTEXT_LABEL} message is runtime-authored and lists overlapping background tasks in the same cohort, potentially started across different user turns, all settled, with every available terminal output. Do not reply with ${EMPTY_DELIVERY_SENTINEL}. Send one user-facing response that combines their useful results.`;+export const TASK_DELIVERY_SETTLED_INSTRUCTION = `Background task reporting\nFor this background-task update, the accompanying ${TASK_DELIVERY_CONTEXT_LABEL} message is runtime-authored and lists the settled tasks in this cohort and their available terminal outputs. Report their useful results together in one user-facing response without repeating results already reported. Do not reply with ${EMPTY_DELIVERY_SENTINEL}.`;++export const TASK_DELIVERY_AUTO_INSTRUCTION = `Background task reporting\nFor this background-task update, the accompanying ${TASK_DELIVERY_CONTEXT_LABEL} message is runtime-authored and lists the whole cohort, including pending tasks and every available terminal output. A received result has not necessarily been reported to the user. Report new results only when they are useful independently of unfinished work. When that work settles, combine its results with any previously withheld results. If there is nothing new and useful to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}. Do not repeat results already reported or send an acknowledgement just to say you are waiting.`;type BackgroundTaskDelivery = DeliverHookPayload & {readonly taskDeliveryId: string;@@ -38,10 +40,11 @@ export function markBackgroundTaskStepInput(input: StepInput): StepInput {: markFrameworkStepInput(input, "execution.background_task");}-/** Groups overlapping tasks without changing the delivered task's activity root. */+/** Projects the report group without changing the delivered task's activity root. */export function resolveTaskDeliveryContext(input: {readonly state: SessionStateMap | undefined;- readonly taskDeliveryId: string;+ readonly taskDeliveryIds: readonly string[];+ readonly taskDeliveryPolicy: TaskDeliveryPolicy;}):| {readonly context: string;@@ -49,16 +52,19 @@ export function resolveTaskDeliveryContext(input: {readonly rootTurnId: string;}| undefined {+ const firstDeliveryId = input.taskDeliveryIds[0];+ if (firstDeliveryId === undefined) return undefined;const entries = getBackgroundWorkflowToolRuns(input.state);- const delivered = entries.find((entry) =>- input.taskDeliveryId.startsWith(`${entry.task.taskId}:`),- );+ const delivered = entries.find((entry) => firstDeliveryId.startsWith(`${entry.task.taskId}:`));if (delivered === undefined) return undefined;const cohort = entries.filter((entry) => getTaskCohortId(entry.task) === getTaskCohortId(delivered.task),);- return { ...projectTaskCohort(cohort), rootTurnId: delivered.origin.turnId };+ return {+ ...projectTaskCohort(cohort, input.taskDeliveryPolicy === "auto"),+ rootTurnId: delivered.origin.turnId,+ };}/** Returns model context for durable tasks launched by the active parent turn. */@@ -72,10 +78,13 @@ export function resolveInitiatingTaskContext(input: {if (!cohort.some((entry) => entry.task.outcome === undefined)) {return undefined;}- return { ...projectTaskCohort(cohort), phase: "initiating" };+ return { ...projectTaskCohort(cohort, false), phase: "initiating" };}-function projectTaskCohort(cohort: readonly BackgroundWorkflowToolRun[]): {+function projectTaskCohort(+ cohort: readonly BackgroundWorkflowToolRun[],+ includePartialOutputs: boolean,+): {readonly context: string;readonly phase: "pending" | "settled";} {@@ -84,7 +93,7 @@ function projectTaskCohort(cohort: readonly BackgroundWorkflowToolRun[]): {const view = readWorkflowTaskView(entry.task);return {name: entry.task.metadata.name,- output: settled ? view?.lastOutput : undefined,+ output: settled || includePartialOutputs ? view?.lastOutput : undefined,status: view?.status ?? "pending",taskId: entry.task.taskId,};diff --git a/packages/eve/src/tasks/delivery-policy.test.ts b/packages/eve/src/tasks/delivery-policy.test.tsindex 54aae1086..272e347aa 100644--- a/packages/eve/src/tasks/delivery-policy.test.ts+++ b/packages/eve/src/tasks/delivery-policy.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import { CONDITIONAL_DELIVERY_INSTRUCTION } from "#shared/empty-delivery.js";import {+ TASK_DELIVERY_AUTO_INSTRUCTION,TASK_DELIVERY_INITIATING_INSTRUCTION,TASK_DELIVERY_SETTLED_INSTRUCTION,} from "#tasks/delivery-context.js";@@ -24,6 +25,7 @@ describe("resolveDeliveryPolicy", () => {) => {expect(resolveDeliveryPolicy({+ taskDeliveryPolicy: "cohort",hasScheduleProvenance,hasOutputSchema: false,isChild: false,@@ -34,9 +36,26 @@ describe("resolveDeliveryPolicy", () => {},);+ it.each(["pending", "settled"] as const)(+ "allows auto to withhold a %s report",+ (taskDeliveryPhase) => {+ expect(+ resolveDeliveryPolicy({+ taskDeliveryPolicy: "auto",+ taskDeliveryPhase,+ hasScheduleProvenance: false,+ hasOutputSchema: false,+ isChild: false,+ isFirstTurn: false,+ }),+ ).toEqual({ allowsEmptyDelivery: true, instruction: TASK_DELIVERY_AUTO_INSTRUCTION });+ },+ );+it("allows an empty pending wake without instructing the model to stay silent", () => {expect(resolveDeliveryPolicy({+ taskDeliveryPolicy: "cohort",hasScheduleProvenance: false,hasOutputSchema: false,isChild: false,@@ -52,6 +71,7 @@ describe("resolveDeliveryPolicy", () => {] as const)("keeps %s mandatory", (_name, hasOutputSchema, isChild) => {expect(resolveDeliveryPolicy({+ taskDeliveryPolicy: "cohort",hasScheduleProvenance: true,hasOutputSchema,isChild,@@ -64,6 +84,7 @@ describe("resolveDeliveryPolicy", () => {it("acknowledges background work launched on a later turn", () => {expect(resolveDeliveryPolicy({+ taskDeliveryPolicy: "cohort",hasOutputSchema: false,hasScheduleProvenance: true,isChild: false,diff --git a/packages/eve/src/tasks/delivery-policy.ts b/packages/eve/src/tasks/delivery-policy.tsindex 1341fa825..d4029c361 100644--- a/packages/eve/src/tasks/delivery-policy.ts+++ b/packages/eve/src/tasks/delivery-policy.ts@@ -1,5 +1,7 @@+import type { TaskDeliveryPolicy } from "#channel/types.js";import { CONDITIONAL_DELIVERY_INSTRUCTION } from "#shared/empty-delivery.js";import {+ TASK_DELIVERY_AUTO_INSTRUCTION,TASK_DELIVERY_INITIATING_INSTRUCTION,TASK_DELIVERY_SETTLED_INSTRUCTION,} from "#tasks/delivery-context.js";@@ -10,6 +12,7 @@ export interface DeliveryPolicy {}const POLICIES = {+ auto: { allowsEmptyDelivery: true, instruction: TASK_DELIVERY_AUTO_INSTRUCTION },conditional: {allowsEmptyDelivery: true,instruction: CONDITIONAL_DELIVERY_INSTRUCTION,@@ -34,12 +37,18 @@ export function resolveDeliveryPolicy(input: {readonly isChild: boolean;readonly isFirstTurn: boolean;readonly hasScheduleProvenance: boolean;+ readonly taskDeliveryPolicy: TaskDeliveryPolicy | undefined;readonly taskDeliveryPhase: "none" | "initiating" | "pending" | "settled" | undefined;}): DeliveryPolicy {// These runs have an explicit output consumer, so silence would violate the call contract.if (input.hasOutputSchema || input.isChild) return POLICIES.normal;+ if (+ input.taskDeliveryPolicy === "auto" &&+ (input.taskDeliveryPhase === "pending" || input.taskDeliveryPhase === "settled")+ )+ return POLICIES.auto;if (input.taskDeliveryPhase === "pending") return POLICIES.pending;- // A complete cohort owes its caller the consolidated result and must not disappear silently.+ // Delivered terminal results must not disappear silently.if (input.taskDeliveryPhase === "settled") return POLICIES.settled;// Nobody prompted a schedule-created first turn, so starting work needs no acknowledgement.if (input.isFirstTurn && input.hasScheduleProvenance) return POLICIES.conditional;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e94905f08..fbef76099 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1289,6 +1289,28 @@ importers:specifier: 'catalog:'version: 7.0.2+ e2e/fixtures/agent-task-wake-policy:+ dependencies:+ '@eve-e2e/config':+ specifier: workspace:*+ version: link:../e2e-config+ '@workflow/world-postgres':+ specifier: 'catalog:'+ version: 5.0.0-beta.45(@opentelemetry/[email protected])(@types/[email protected])(@upstash/[email protected])([email protected])([email protected])([email protected])+ eve:+ specifier: workspace:*+ version: link:../../../packages/eve+ zod:+ specifier: 'catalog:'+ version: 4.5.4+ devDependencies:+ '@types/node':+ specifier: 'catalog:'+ version: 24.13.3+ typescript:+ specifier: 'catalog:'+ version: 7.0.2+e2e/fixtures/agent-tools:dependencies:'@eve-e2e/config':@@ -1631,14 +1653,14 @@ importers:specifier: 'catalog:'version: 5.0.43([email protected])'@chat-adapter/slack':- specifier: 4.34.0- version: 4.34.0([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])+ specifier: 4.41.0+ version: 4.41.0([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])'@chat-adapter/state-memory':- specifier: 4.34.0+ specifier: 4.41.0'@chat-adapter/twilio':- specifier: 4.34.0+ specifier: 4.41.0'@clack/core':specifier: 1.3.1version: 1.3.1@@ -1647,7 +1669,7 @@ importers:version: link:../eve-catalog'@linqapp/chat-sdk-adapter':specifier: ^0.5.1- version: 0.5.1([email protected]([email protected]([email protected]))([email protected])([email protected]))+ version: 0.5.1([email protected]([email protected]([email protected]))([email protected])([email protected]))'@modelcontextprotocol/server':specifier: 2.0.0version: 2.0.0@@ -1671,7 +1693,7 @@ importers:version: 2.6.1(@opentelemetry/[email protected])'@photon-ai/chat-adapter-imessage':specifier: 3.2.0- version: 3.2.0([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])+ version: 3.2.0([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])'@standard-schema/spec':specifier: 1.1.0version: 1.1.0@@ -1733,8 +1755,8 @@ importers:specifier: 'catalog:'version: 7.0.105([email protected])chat:- specifier: 4.34.0+ specifier: 4.41.0chokidar:specifier: 5.0.0version: 5.0.0@@ -2440,8 +2462,8 @@ packages:resolution: {integrity: sha512-l+hHljueSiw/74CZKhjXpmreVlgfUaLcn9+Oh/xzwjbozrqlw3h7+c7PixiHLeuu2vc22uA2GQoFopDdjmXQQw==}engines: {node: '>=20'}- '@chat-adapter/[email protected]':- resolution: {integrity: sha512-voZQK+bAz6RLwUDb582f+Wub5aChp6eVqtHAGjf1gAYFUKcIy54k0JA540jG1ZHLym6m0kIH5FjVXDCDb5DLng==}+ '@chat-adapter/[email protected]':+ resolution: {integrity: sha512-6y+P1vpI8edvBHhO/SlF5sMgWlDxJiDTsTcAiJO5yOyADoVl97wlTaOiXfc5Y+b2+fhEcERvhNpjGyvT7hRdVA==}engines: {node: '>=20'}'@chat-adapter/[email protected]':@@ -2452,8 +2474,8 @@ packages:resolution: {integrity: sha512-skezIMJ0XWeBsBoUhebhBmc6nsza6kCjxADgD653fxg9IrxzIgJVoYCaSrCS4ixGG+FuC6V7Tu5Nkdzu9qWr2g==}engines: {node: '>=20'}- '@chat-adapter/[email protected]':- resolution: {integrity: sha512-icrd4T0pE7djK0c8BHwVciIgAVXlpZGJh+7qpF5K0H2GWE5NP9V93Yku48blJgjVTBYUXrynFiGqKBzOx1r9Mw==}+ '@chat-adapter/[email protected]':+ resolution: {integrity: sha512-AqxPzaAotFseMVvEDZJ7Wia4ZzV9K7fl03n1+PGfDbKxoRzoOnWMKCl7WiKDWJ3Di3lr6Ar23zT9N43U+kL6BQ==}engines: {node: '>=20'}'@chat-adapter/[email protected]':@@ -16950,6 +16972,7 @@ snapshots:- ai- supports-color- zod+ optional: true'@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])':dependencies:@@ -16982,13 +17005,21 @@ snapshots:- supports-color- utf-8-validate- zod+ optional: true- '@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])':+ '@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])':dependencies:+ '@chat-adapter/shared': 4.41.0([email protected]([email protected]))([email protected])([email protected])+ '@slack/socket-mode': 2.0.7([email protected])([email protected]([email protected]))([email protected])transitivePeerDependencies:- ai+ - bufferutil+ - debug- supports-color+ - utf-8-validate+ - workflow- zod'@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])':@@ -17012,13 +17043,14 @@ snapshots:- workflow- zod- '@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])':+ '@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])':dependencies:- '@chat-adapter/shared': 4.34.0([email protected]([email protected]))([email protected])([email protected])+ '@chat-adapter/shared': 4.41.0([email protected]([email protected]))([email protected])([email protected])transitivePeerDependencies:- ai- supports-color+ - workflow- zod'@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])':@@ -17986,10 +18018,10 @@ snapshots:- debug- utf-8-validate- '@linqapp/[email protected]([email protected]([email protected]([email protected]))([email protected])([email protected]))':+ '@linqapp/[email protected]([email protected]([email protected]([email protected]))([email protected])([email protected]))':dependencies:'@linqapp/sdk': 0.47.1standardwebhooks: 1.1.1'@linqapp/[email protected]':@@ -18173,30 +18205,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected])':- dependencies:- '@hono/node-server': 2.1.1([email protected])- ajv: 8.20.0- ajv-formats: 3.0.1([email protected])- content-type: 1.0.5- cors: 2.8.6- cross-spawn: 7.0.6- eventsource: 3.0.7- eventsource-parser: 3.1.0- express: 5.2.1([email protected])- hono: 4.13.8- jose: 6.2.3- json-schema-typed: 8.0.2- pkce-challenge: 5.0.1- raw-body: 3.0.2- zod: 4.5.4- zod-to-json-schema: 3.25.2([email protected])- optionalDependencies:- '@cfworker/json-schema': 4.1.1- transitivePeerDependencies:- - supports-color-'@modelcontextprotocol/[email protected]':dependencies:'@modelcontextprotocol/core': 2.0.0@@ -19631,12 +19639,12 @@ snapshots:nice-grpc: 2.1.17nice-grpc-common: 2.0.4- '@photon-ai/[email protected]([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])':+ '@photon-ai/[email protected]([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])':dependencies:'@chat-adapter/shared': 4.40.0([email protected]([email protected]))([email protected])([email protected])'@spectrum-ts/core': 10.0.0([email protected])([email protected])'@spectrum-ts/imessage': 10.0.0(@spectrum-ts/[email protected]([email protected])([email protected]))([email protected])([email protected])mime-types: 3.0.2transitivePeerDependencies:- ai@@ -24133,6 +24141,7 @@ snapshots:zod: 4.5.4transitivePeerDependencies:- supports-color+ optional: truedependencies:diff --git a/research/background-task-wake-policy.md b/research/background-task-wake-policy.mdnew file mode 100644index 000000000..dbf07bef8--- /dev/null+++ b/research/background-task-wake-policy.md@@ -0,0 +1,54 @@+---+issue: https://github.com/vercel/eve/issues/1084+status: implemented+last_updated: "2026-09-19"+---++# Background task delivery policy++Message sends choose when background results are reported; task execution and+session completion remain independent of that choice.++## Authoring++```ts+await from(address).send(message, { auth, taskDeliveryPolicy: "auto" });+await to(slack, target).send(message, { auth, taskDeliveryPolicy: "cohort" });+await session.send(message, { auth, taskDeliveryPolicy: "auto" });+```++`taskDeliveryPolicy: "auto" | "cohort"` is authored only on sends, including client+sends. New channel sessions default to `"auto"`; new schedule and internal child+sessions default to `"cohort"`. Explicit sends update the session policy, including+pending tasks; omission preserves the current value. Schedule handlers override+the default on their `send(...)`; Markdown schedules use the default.++## Observable behavior++A cohort contains overlapping tasks, including launches in later user turns.+`"cohort"` holds terminal outcomes until that cohort settles, then reports+the results together. `"auto"` allows each ready completion to invoke the parent;+results already queued from the same cohort may share a turn.++For independent tasks A and B, auto can report A while B runs. When A needs B to+produce a useful answer, the parent may stay silent after A and report both after+B settles. This is a model judgment about delivery, not a way to avoid the model+call. The runtime retains available outputs in the workflow tool run registry and includes the+whole cohort in subsequent reporting contexts. Received does not mean reported.+User input and intervention notifications remain serviceable under either policy.++## Runtime boundaries++Sends carry the policy through session creation or the durable inbox envelope.+Cross-channel sends supply a default to the receiver's local send. The last explicit+value wins when authored deliveries are coalesced. The workflow queue and reporting+prompt share one resolved value in `eve.runtime.taskDeliveryPolicy`.++Reporting projects cohort state from the existing workflow tool run registry. Auto exposes+available outputs while the cohort is pending and permits an empty delivery.+Cohort reports wait for settlement and require a response. Child calls and+structured outputs retain their explicit output contracts.++Scheduled task-mode sessions check pending workflow tasks as well as newly launched+tasks before finishing. A partial report cannot end the session and cancel siblings.+No separate store of reported or withheld task outputs is introduced.