Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): preserve schedule delivery provenance (#2648)

Ruibdb3973f5110
diff --git a/.changeset/scheduled-background-launches.md b/.changeset/scheduled-background-launches.md
new file mode 100644
index 000000000..55620e92e
--- /dev/null
+++ b/.changeset/scheduled-background-launches.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Preserve schedule provenance when a handler starts a session with user credentials. Scheduled background-task launches now stay silent instead of sending a launch acknowledgement, and schedule-created workflow runs expose `$eve.schedule` for attribution.
diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.md
index 253e79a13..8d13e5028 100644
--- a/docs/guides/instrumentation.md
+++ b/docs/guides/instrumentation.md
@@ -163,6 +163,7 @@ Structural tags describe each run's place in the tree:
- `$eve.root`: session id of the root session in the chain (group a whole tree with `$eve.root=<id>`)
- `$eve.subagent`: compiled graph node id (subagent runs only)
- `$eve.trigger`: the channel kind that started the run
+- `$eve.schedule`: the authored schedule that created the session, including sessions started through a target channel
- `$eve.title`: truncated title derived from the first user message
- `$eve.trace_id`: trace id of the sampled agent trace containing the run, written on session, subagent, and turn rows so a dashboard run can be joined to its OpenTelemetry trace. Present only when the trace is sampled; absence means no exported OTEL trace exists.
diff --git a/docs/schedules.mdx b/docs/schedules.mdx
index 1ba5abf82..be93c080d 100644
--- a/docs/schedules.mdx
+++ b/docs/schedules.mdx
@@ -84,6 +84,8 @@ The agent does not have to deliver a message on every run. When a prompt makes d
- `waitUntil(promise)`: extends the cron task's lifetime so the parked session and any in-flight fetches settle before the task ends. Wrap the `send` call in it.
- `appAuth`: the app principal (`{ authenticator: "app", principalId: "eve:app", principalType: "runtime" }`). Pass it as `to(...).send(..., { auth: appAuth })` for work the agent does on its own behalf.
+The `auth` option controls which principal the session runs as. A handler may instead supply a user principal when scheduled work needs that user's grants; a session created by that dispatch still retains schedule provenance and conditional delivery behavior.
+
A handler-form session runs on the same durable runtime engine as any other session, so it can park (durably suspend), for instance when the channel handoff is waiting for a Slack reply. Only markdown task mode is barred from waiting.
## Session continuity
diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdx
index 84f3e508e..7513490a0 100644
--- a/docs/tools/overview.mdx
+++ b/docs/tools/overview.mdx
@@ -72,6 +72,8 @@ framework-owned and is not yet a stable authored-tool API.
After the initiating turn accepts background tasks, eve supplies runtime-authored state for that
cohort and instructs the model to acknowledge that the work started without waiting for results.
+[Schedule](/docs/schedules)-initiated turns are the exception: no user prompted them, so their
+launches keep conditional delivery and send no acknowledgement.
Later task-triggered parent turns receive fresh state for the same cohort. The model is instructed
to keep related intermediate results silent while any task remains pending. Once every related
task is terminal, the state includes their outputs so the model can combine the useful results.
diff --git a/e2e/fixtures/agent-background-tools/agent/agent.ts b/e2e/fixtures/agent-background-tools/agent/agent.ts
index 42651664a..8087843ac 100644
--- a/e2e/fixtures/agent-background-tools/agent/agent.ts
+++ b/e2e/fixtures/agent-background-tools/agent/agent.ts
@@ -4,10 +4,16 @@ import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/ev
const PROGRESS = "EXPORT-PROGRESS";
const RESULT = "EXPORT-COMPLETE";
+const SCHEDULED = "BACKGROUND-EXPORT-SCHEDULED";
+const EMPTY_DELIVERY_SENTINEL = "<eve-empty-delivery/>";
function respond(request: MockModelRequest): MockModelResponse | string {
const message = [...request.userMessages].reverse().find((entry) => entry.trim() !== "") ?? "";
+ if (request.userMessages.some((entry) => entry.includes(SCHEDULED))) {
+ return respondScheduled(request, message);
+ }
+
if (message.includes("BACKGROUND-EXPORT-START")) {
const roles = request.messages.map((entry) => entry.role);
if (roles.lastIndexOf("tool") <= roles.lastIndexOf("user")) {
@@ -41,6 +47,31 @@ function respond(request: MockModelRequest): MockModelResponse | string {
return "BACKGROUND-EXPORT-IDLE";
}
+function respondScheduled(request: MockModelRequest, message: string): MockModelResponse | string {
+ const taskNotification = [...request.userMessages]
+ .reverse()
+ .find((entry) => /^Background task task_[a-z0-9]+/iu.test(entry));
+ if (taskNotification?.includes("is completed") && taskNotification.includes(RESULT)) {
+ return "SCHEDULED-EXPORT-DONE";
+ }
+ const roles = request.messages.map((entry) => entry.role);
+ const launched = roles.lastIndexOf("tool") > roles.lastIndexOf("user");
+ if (!launched && taskNotification === undefined) {
+ return {
+ toolCalls: [
+ {
+ name: "export",
+ input: { query: "nightly" },
+ },
+ ],
+ };
+ }
+ const instructedToAcknowledge = request.messages.some(
+ (entry) => entry.role === "system" && entry.text.includes("launch acknowledgement"),
+ );
+ return instructedToAcknowledge ? "SCHEDULED-EXPORT-LAUNCH-ACK" : EMPTY_DELIVERY_SENTINEL;
+}
+
const base = e2eAgentConfig({ mock: respond });
export default defineAgent({
diff --git a/e2e/fixtures/agent-background-tools/agent/channels/schedule-sink.ts b/e2e/fixtures/agent-background-tools/agent/channels/schedule-sink.ts
new file mode 100644
index 000000000..c80a15933
--- /dev/null
+++ b/e2e/fixtures/agent-background-tools/agent/channels/schedule-sink.ts
@@ -0,0 +1,27 @@
+import { defineChannel, POST } from "eve/channels";
+
+/**
+ * Delivery target for the `scheduled-export` handler schedule.
+ *
+ * The only user-facing message this channel may ever receive is the settled
+ * report; the launching turn and the pending update wake must stay silent.
+ */
+export default defineChannel<undefined, void, { id: string }>({
+ routes: [POST("/schedule-sink", async () => new Response("ok"))],
+ receive(input, { from }) {
+ return from(input.target.id).send(input.message, {
+ auth: input.auth,
+ });
+ },
+ events: {
+ "message.completed"(event) {
+ if (
+ event.finishReason !== "tool-calls" &&
+ event.message !== null &&
+ !JSON.stringify(event.message).includes("SCHEDULED-EXPORT-DONE")
+ ) {
+ throw new Error(`Schedule sink received an unexpected message: ${event.message}`);
+ }
+ },
+ },
+});
diff --git a/e2e/fixtures/agent-background-tools/agent/schedules/scheduled-export.ts b/e2e/fixtures/agent-background-tools/agent/schedules/scheduled-export.ts
new file mode 100644
index 000000000..f2c940395
--- /dev/null
+++ b/e2e/fixtures/agent-background-tools/agent/schedules/scheduled-export.ts
@@ -0,0 +1,29 @@
+import { defineSchedule } from "eve/schedules";
+
+import scheduleSink from "../channels/schedule-sink";
+
+/**
+ * Handler schedule used by `evals/scheduled-export.quiet-launch.eval.ts`.
+ *
+ * Uses a user-shaped principal to reproduce schedules that run with an
+ * owner's grants. Schedule provenance must remain independent from that
+ * active principal so the launch stays silent.
+ */
+export default defineSchedule({
+ cron: "0 0 * * *",
+ run({ to, waitUntil }) {
+ waitUntil(
+ to(scheduleSink, { id: "scheduled-export" }).send(
+ "BACKGROUND-EXPORT-SCHEDULED Run the nightly export in the background.",
+ {
+ auth: {
+ attributes: { scheduled: "true" },
+ authenticator: "fixture-user",
+ principalId: "scheduled-export-owner",
+ principalType: "user",
+ },
+ },
+ ),
+ );
+ },
+});
diff --git a/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts b/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts
new file mode 100644
index 000000000..ff5d5cb99
--- /dev/null
+++ b/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts
@@ -0,0 +1,113 @@
+import { defineEval } from "eve/evals";
+import { equals, satisfies } from "eve/evals/expect";
+
+const RESULT = "EXPORT-COMPLETE";
+
+/**
+ * A schedule-launched turn that dispatches a background task sends no launch
+ * acknowledgement even when it runs with a user principal: durable schedule
+ * provenance keeps conditional delivery, so the
+ * launching turn and the pending update wake both complete with a null
+ * message, and only the settled wake delivers a report.
+ */
+export default defineEval({
+ description:
+ "Quiet scheduled launch: a schedule-dispatched background export acknowledges nothing and reports once on completion.",
+
+ async test(t) {
+ if (!t.target.capabilities.devRoutes) {
+ t.skip("Target has no dev routes; schedule dispatch is dev-only.");
+ }
+
+ const dispatch = await t.target.dispatchSchedule("scheduled-export");
+ await t.require(dispatch.scheduleId, equals("scheduled-export"));
+ await t.require(
+ dispatch.sessionIds,
+ satisfies(
+ (sessionIds: readonly string[]) => sessionIds.length > 0,
+ "schedule started a session",
+ ),
+ );
+ const sessionId = dispatch.sessionIds[0]!;
+
+ // The launching turn: dispatches the background export, then delivers
+ // nothing — no launch acknowledgement.
+ const session = await t.target.attachSession(sessionId);
+ session.succeeded();
+ session.calledTool("export");
+ session.event("session.waiting");
+ session.event("message.completed", {
+ data: (data) => data.finishReason !== "tool-calls" && data.message === null,
+ count: 1,
+ });
+ session.notEvent("message.completed", {
+ data: (data) => data.finishReason !== "tool-calls" && data.message !== null,
+ });
+
+ // The executor's progress update wakes the parent while the cohort is
+ // still pending; that wake stays silent too.
+ const updateLive = t.target.watchTurn(sessionId, {
+ startIndex: requireStreamIndex(session, "update wait"),
+ });
+ const updateTurn = await updateLive.result();
+ updateTurn.expectOk();
+ updateTurn.event("message.completed", {
+ data: (data) => data.finishReason !== "tool-calls" && data.message === null,
+ count: 1,
+ });
+ updateTurn.notEvent("message.completed", {
+ data: (data) => data.finishReason !== "tool-calls" && data.message !== null,
+ });
+ await t.require(
+ updateTurn.message,
+ satisfies((message) => message === undefined, "the pending update wake is silent"),
+ );
+
+ // Only the settled wake produces a user-facing report.
+ const doneLive = t.target.watchTurn(sessionId, {
+ startIndex: requireStreamIndex(updateLive.session, "completion wait"),
+ });
+ const doneTurn = await doneLive.result();
+ doneTurn.expectOk();
+ doneTurn.messageIncludes("SCHEDULED-EXPORT-DONE");
+ await t.require(
+ doneTurn.events,
+ satisfies(
+ (events: typeof doneTurn.events) =>
+ events.some(
+ (event) =>
+ event.type === "message.received" &&
+ messageText(event.data.message).includes("is completed") &&
+ messageText(event.data.message).includes(RESULT),
+ ),
+ "the report follows the executor completion",
+ ),
+ );
+ t.noFailedActions();
+ t.succeeded();
+ },
+});
+
+function requireStreamIndex(
+ session: { readonly state?: { readonly streamIndex?: number } },
+ operation: string,
+): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error(`${operation} has no session stream index.`);
+ return streamIndex;
+}
+
+function messageText(message: unknown): string {
+ if (typeof message === "string") return message;
+ if (!Array.isArray(message)) return "";
+ return message
+ .flatMap((part) =>
+ part !== null &&
+ typeof part === "object" &&
+ Reflect.get(part, "type") === "text" &&
+ typeof Reflect.get(part, "text") === "string"
+ ? [Reflect.get(part, "text") as string]
+ : [],
+ )
+ .join("\n");
+}
diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.ts
index 687d6b94a..504536fcd 100644
--- a/packages/eve/src/channel/schedule.test.ts
+++ b/packages/eve/src/channel/schedule.test.ts
@@ -9,6 +9,8 @@ import {
SCHEDULE_APP_AUTH,
ScheduleDispatcher,
} from "#channel/schedule.js";
+import { contextStorage } from "#context/container.js";
+import { ScheduleIdKey } from "#context/keys.js";
import type { RunHandle, Runtime } from "#channel/types.js";
import { slackChannel } from "#public/channels/slack/slackChannel.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
@@ -149,6 +151,45 @@ describe("ScheduleDispatcher", () => {
expect(result.sessions).toHaveLength(0);
});
+ it("scopes user-auth sessions started through waitUntil to the active schedule", async () => {
+ const runtime = createMockRuntime();
+ const observedScheduleIds: Array<string | undefined> = [];
+ runtime.createSession = vi.fn(async () => {
+ observedScheduleIds.push(contextStorage.getStore()?.get(ScheduleIdKey));
+ return createMockRunHandle();
+ });
+ vi.stubEnv("SLACK_BOT_TOKEN", "xoxb-test");
+ vi.stubEnv("SLACK_SIGNING_SECRET", "test-secret");
+ try {
+ const { definition, resolved } = makeSlackChannelEntry();
+ const dispatcher = new ScheduleDispatcher({ runtime, channels: [resolved] });
+
+ const result = await dispatcher.trigger({
+ scheduleId: "dynamic-tasks",
+ run({ to, waitUntil }) {
+ waitUntil(
+ Promise.resolve().then(() =>
+ to(definition, { channelId: "C0123ABC" }).send("run", {
+ auth: {
+ attributes: {},
+ authenticator: "slack",
+ principalId: "schedule-owner",
+ principalType: "user",
+ },
+ }),
+ ),
+ );
+ },
+ });
+
+ await Promise.all(result.waitUntilTasks);
+ expect(observedScheduleIds).toEqual(["dynamic-tasks"]);
+ expect(contextStorage.getStore()?.get(ScheduleIdKey)).toBeUndefined();
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
it("throws when ctx.to(channel) is called with an unregistered channel", async () => {
const runtime = createMockRuntime();
const dispatcher = new ScheduleDispatcher({ runtime, channels: [] });
diff --git a/packages/eve/src/channel/schedule.ts b/packages/eve/src/channel/schedule.ts
index 163c2e321..62deb16f2 100644
--- a/packages/eve/src/channel/schedule.ts
+++ b/packages/eve/src/channel/schedule.ts
@@ -3,6 +3,8 @@ import { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";
import { createCrossChannelToFn, toCrossChannelTargets } from "#channel/cross-channel-receive.js";
import { createSession, type Session } from "#channel/session.js";
import type { Runtime } from "#channel/types.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { ScheduleIdKey } from "#context/keys.js";
import { expectFunction } from "#internal/authored-module.js";
import type {
ScheduleDefinition,
@@ -72,6 +74,12 @@ export class ScheduleDispatcher {
}
async trigger(input: ScheduleDispatchInput): Promise<ScheduleDispatchResult> {
+ const scope = new ContextContainer();
+ scope.set(ScheduleIdKey, input.scheduleId);
+ return await contextStorage.run(scope, () => this.triggerInScope(input));
+ }
+
+ private async triggerInScope(input: ScheduleDispatchInput): Promise<ScheduleDispatchResult> {
const sessions: Session[] = [];
const waitUntilTasks: Promise<unknown>[] = [];
const toChannel = createCrossChannelToFn(this.runtime, toCrossChannelTargets(this.channels));
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 6c4e276a8..332c4bd7a 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -73,6 +73,8 @@ export const InitiatorAuthKey = new ContextKey<SessionAuthContext | null>("eve.i
export const SessionIdKey = new ContextKey<string>("eve.sessionId");
export const ContinuationTokenKey = new ContextKey<string>("eve.continuationToken");
export const ChannelRequestIdKey = new ContextKey<string>("eve.channelRequestId");
+/** Authored schedule whose dispatch created this session. */
+export const ScheduleIdKey = new ContextKey<string>("eve.scheduleId");
export const ChannelDeliveryKey = new ContextKey<ChannelDeliveryMetadata>("eve.channelDelivery");
/** Task-reporting phase for the active root turn. */
export const TurnTaskDeliveryKey = new ContextKey<"none" | "initiating" | "pending" | "settled">(
diff --git a/packages/eve/src/execution/eve-workflow-attributes.test.ts b/packages/eve/src/execution/eve-workflow-attributes.test.ts
index c16084909..189acb6d7 100644
--- a/packages/eve/src/execution/eve-workflow-attributes.test.ts
+++ b/packages/eve/src/execution/eve-workflow-attributes.test.ts
@@ -12,9 +12,10 @@ import {
readParentLineage,
readParentSessionId,
readRootSessionId,
+ readScheduleId,
readSessionTraceId,
} from "#execution/eve-workflow-attributes.js";
-import { ChannelRequestIdKey } from "#context/keys.js";
+import { ChannelRequestIdKey, ScheduleIdKey } from "#context/keys.js";
import { CHANNEL_CONTEXT_KEY_NAME } from "#context/key-names.js";
const slackChannelCtx = {
@@ -47,6 +48,14 @@ describe("readChannelKind", () => {
});
});
+describe("readScheduleId", () => {
+ it("reads only a non-empty schedule name", () => {
+ expect(readScheduleId({ [ScheduleIdKey.name]: "dynamic-tasks" })).toBe("dynamic-tasks");
+ expect(readScheduleId({ [ScheduleIdKey.name]: "" })).toBeUndefined();
+ expect(readScheduleId({ [ScheduleIdKey.name]: 42 })).toBeUndefined();
+ });
+});
+
describe("isWorkflowTraceContentVisible", () => {
it("reads audience from the shared serialized channel slot", () => {
expect(
@@ -165,6 +174,7 @@ describe("buildSessionAttributes", () => {
"$eve.channel_request_id": undefined,
"$eve.is_otel_trace_enabled": false,
"$eve.is_trace_content_visible": true,
+ "$eve.schedule": undefined,
"$eve.trace_id": undefined,
"$eve.type": "session",
"$eve.trigger": "slack",
@@ -219,6 +229,19 @@ describe("buildSessionAttributes", () => {
expect(attrs["$eve.channel_request_id"]).toBe("req_session");
});
+ it("emits the schedule while retaining the target channel trigger", () => {
+ const attrs = buildSessionAttributes({
+ inputMessage: "run the scheduled task",
+ serializedContext: {
+ ...slackChannelCtx,
+ [ScheduleIdKey.name]: "dynamic-tasks",
+ },
+ });
+
+ expect(attrs["$eve.schedule"]).toBe("dynamic-tasks");
+ expect(attrs["$eve.trigger"]).toBe("slack");
+ });
+
it("emits $eve.trace_id from a sampled trace seed", () => {
const attrs = buildSessionAttributes({
inputMessage: "hi",
diff --git a/packages/eve/src/execution/eve-workflow-attributes.ts b/packages/eve/src/execution/eve-workflow-attributes.ts
index 45f15252e..67c5d0384 100644
--- a/packages/eve/src/execution/eve-workflow-attributes.ts
+++ b/packages/eve/src/execution/eve-workflow-attributes.ts
@@ -23,6 +23,7 @@
* - `$eve.trigger` — channel adapter kind (session/subagent rows)
* - `$eve.title` — truncated session title from the first user message
* - `$eve.channel_request_id` — inbound channel request id
+ * - `$eve.schedule` — authored schedule that created the session
* - `$eve.invocation_token` — channel-local continuation token for an external invocation
* - `$eve.invocation_owner` — SHA-256 fingerprint of the invocation's initiating principal
* - `$eve.is_trace_content_visible` — whether observability may read content-bearing workflow data
@@ -33,7 +34,12 @@
*/
import { CHANNEL_CONTEXT_KEY_NAME } from "#context/key-names.js";
-import { ChannelRequestIdKey, OtelTraceEnabledKey, type SessionTraceSeed } from "#context/keys.js";
+import {
+ ChannelRequestIdKey,
+ OtelTraceEnabledKey,
+ ScheduleIdKey,
+ type SessionTraceSeed,
+} from "#context/keys.js";
import { shouldCaptureInstrumentationContent } from "#harness/instrumentation/content-policy.js";
import { isSampledTrace } from "#tracing/sampled-trace.js";
import type { EveAttributeValue } from "#runtime/attributes/normalize.js";
@@ -163,6 +169,12 @@ export function readChannelRequestId(
return isNonEmptyString(channelRequestId) ? channelRequestId : undefined;
}
+/** Reads the schedule name inherited from a schedule dispatch scope. */
+export function readScheduleId(serializedContext: Record<string, unknown>): string | undefined {
+ const scheduleId = serializedContext[ScheduleIdKey.name];
+ return isNonEmptyString(scheduleId) ? scheduleId : undefined;
+}
+
/**
* Maximum visible length (in code points) of a derived `$eve.title`.
*
@@ -242,6 +254,7 @@ export function buildSessionAttributes(input: {
const isOtelTraceEnabled = isWorkflowOtelTraceEnabled(input.serializedContext);
return {
"$eve.channel_request_id": readChannelRequestId(input.serializedContext),
+ "$eve.schedule": readScheduleId(input.serializedContext),
"$eve.is_otel_trace_enabled": isOtelTraceEnabled,
"$eve.is_trace_content_visible": isTraceContentVisible,
"$eve.trace_id": readSessionTraceId(input.serializedContext),
diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.ts
index 72a1b0c57..d92cb633b 100644
--- a/packages/eve/src/execution/runtime-context.test.ts
+++ b/packages/eve/src/execution/runtime-context.test.ts
@@ -8,6 +8,7 @@ import {
type SessionAuthContext,
SessionIdKey,
SessionKey,
+ ScheduleIdKey,
} from "#context/keys.js";
import { buildRunContext } from "#execution/runtime-context.js";
@@ -178,6 +179,26 @@ describe("buildRunContext", () => {
expect(ctx.require(AuthKey)).toBeNull();
});
+ it("inherits schedule provenance independently from run auth", () => {
+ const scope = new ContextContainer();
+ scope.set(ScheduleIdKey, "dynamic-tasks");
+
+ const ctx = contextStorage.run(scope, () =>
+ buildRunContext({
+ bundle: createMinimalBundle(),
+ run: {
+ auth: testAuth,
+ adapter: { kind: "channel:slack" },
+ input: { message: "run the scheduled task" },
+ mode: "conversation",
+ },
+ }),
+ );
+
+ expect(ctx.require(AuthKey)).toEqual(testAuth);
+ expect(ctx.require(ScheduleIdKey)).toBe("dynamic-tasks");
+ });
+
it("does not invent a continuation for an ID-only run", () => {
const ctx = buildRunContext({
bundle: createMinimalBundle(),
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index 683e4db4c..b8a722814 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -1,5 +1,5 @@
import type { RunInput, SessionAuthContext } from "#channel/types.js";
-import { ContextContainer } from "#context/container.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
import { setChannelContext } from "#execution/channel-context.js";
import {
AuthKey,
@@ -13,6 +13,7 @@ import {
ModeKey,
ParentSessionKey,
ParentTraceContextKey,
+ ScheduleIdKey,
SessionCallbackKey,
SubagentDepthKey,
} from "#context/keys.js";
@@ -62,6 +63,11 @@ export function buildRunContext(input: {
ctx.set(ChannelRequestIdKey, run.requestId);
}
+ const scheduleId = contextStorage.getStore()?.get(ScheduleIdKey);
+ if (scheduleId !== undefined) {
+ ctx.set(ScheduleIdKey, scheduleId);
+ }
+
if (run.delivery !== undefined) {
ctx.set(ChannelDeliveryKey, run.delivery);
}
diff --git a/packages/eve/src/harness/current-messages.test.ts b/packages/eve/src/harness/current-messages.test.ts
new file mode 100644
index 000000000..555b8a5a2
--- /dev/null
+++ b/packages/eve/src/harness/current-messages.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from "vitest";
+
+import { createCurrentMessages } from "#harness/current-messages.js";
+
+describe("createCurrentMessages", () => {
+ it("partitions existing history by role", () => {
+ const current = createCurrentMessages([
+ { role: "system", content: "system" },
+ { role: "user", content: "user" },
+ ]);
+ const directMutationIsRejected = () => {
+ // @ts-expect-error current-message placement must go through add/addSystem.
+ current.systemMessages.push({ role: "system", content: "bypass" });
+ };
+
+ expect(current.systemMessages).toEqual([{ role: "system", content: "system" }]);
+ expect(current.nonSystemMessages).toEqual([{ role: "user", content: "user" }]);
+ expect(directMutationIsRejected).toBeTypeOf("function");
+ });
+
+ it("returns snapshots instead of exposing its backing arrays", () => {
+ const current = createCurrentMessages([{ role: "system", content: "system" }]);
+ const exposed = current.systemMessages as Array<{ role: "system"; content: string }>;
+
+ exposed.push({ role: "system", content: "bypass" });
+
+ expect(current.systemMessages).toEqual([{ role: "system", content: "system" }]);
+ });
+
+ it("keeps first-turn context in instructions and routes later context as user messages", () => {
+ const current = createCurrentMessages([]);
+
+ current.add(0, "first");
+ current.add(1, "later");
+
+ expect(current.systemMessages).toEqual([{ role: "system", content: "first" }]);
+ expect(current.nonSystemMessages).toEqual([{ role: "user", content: "later" }]);
+ });
+
+ it("inserts later context before the current turn input", () => {
+ const currentTurnMessages = [
+ { role: "user" as const, content: "channel context" },
+ { role: "user" as const, content: "current request" },
+ ];
+ const current = createCurrentMessages(
+ [{ role: "user", content: "history" }, ...currentTurnMessages],
+ { currentTurnMessages },
+ );
+
+ current.add(1, "task state");
+ current.add(1, "delivery guidance");
+
+ expect(current.nonSystemMessages).toEqual([
+ { role: "user", content: "history" },
+ { role: "user", content: "task state" },
+ { role: "user", content: "delivery guidance" },
+ { role: "user", content: "channel context" },
+ { role: "user", content: "current request" },
+ ]);
+ });
+
+ it("keeps hierarchy-sensitive context in instructions when requested", () => {
+ const current = createCurrentMessages([]);
+
+ current.add(1, "authoritative", { cacheFriendly: false });
+
+ expect(current.systemMessages).toEqual([{ role: "system", content: "authoritative" }]);
+ expect(current.nonSystemMessages).toEqual([]);
+ });
+
+ it("adds prebuilt system messages only through the system API", () => {
+ const current = createCurrentMessages([]);
+
+ current.addSystem([
+ { role: "system", content: "one" },
+ { role: "system", content: "two" },
+ ]);
+
+ expect(current.systemMessages).toEqual([
+ { role: "system", content: "one" },
+ { role: "system", content: "two" },
+ ]);
+ expect(current.nonSystemMessages).toEqual([]);
+ });
+});
diff --git a/packages/eve/src/harness/current-messages.ts b/packages/eve/src/harness/current-messages.ts
new file mode 100644
index 000000000..3873bfd92
--- /dev/null
+++ b/packages/eve/src/harness/current-messages.ts
@@ -0,0 +1,57 @@
+import type { ModelMessage, SystemModelMessage } from "ai";
+
+interface AddCurrentMessageOptions {
+ readonly cacheFriendly?: boolean;
+}
+
+interface CurrentMessagesOptions {
+ readonly currentTurnMessages?: readonly ModelMessage[];
+}
+
+/** Model-call messages with cache-friendly placement for turn-local context. */
+export function createCurrentMessages(
+ history: readonly ModelMessage[],
+ options: CurrentMessagesOptions = {},
+): {
+ readonly nonSystemMessages: readonly ModelMessage[];
+ readonly systemMessages: readonly SystemModelMessage[];
+ add(turnSequence: number, message: string, options?: AddCurrentMessageOptions): void;
+ addSystem(messages: SystemModelMessage | readonly SystemModelMessage[]): void;
+} {
+ const systemMessages: SystemModelMessage[] = [];
+ const nonSystemMessages: ModelMessage[] = [];
+ const currentTurnMessages = new Set(options.currentTurnMessages);
+ let currentTurnInsertionIndex: number | undefined;
+
+ for (const message of history) {
+ if (currentTurnInsertionIndex === undefined && currentTurnMessages.has(message)) {
+ currentTurnInsertionIndex = nonSystemMessages.length;
+ }
+ if (message.role === "system") {
+ systemMessages.push(message);
+ } else {
+ nonSystemMessages.push(message);
+ }
+ }
+ let userInsertionIndex = currentTurnInsertionIndex ?? nonSystemMessages.length;
+
+ return {
+ add(turnSequence, message, { cacheFriendly = true } = {}) {
+ if (turnSequence > 0 && cacheFriendly === true) {
+ nonSystemMessages.splice(userInsertionIndex, 0, { role: "user", content: message });
+ userInsertionIndex += 1;
+ } else {
+ systemMessages.push({ role: "system", content: message });
+ }
+ },
+ addSystem(messages) {
+ systemMessages.push(...(Array.isArray(messages) ? messages : [messages]));
+ },
+ get nonSystemMessages() {
+ return [...nonSystemMessages];
+ },
+ get systemMessages() {
+ return [...systemMessages];
+ },
+ };
+}
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index 0ebead9f8..87d09779b 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -21,6 +21,7 @@ import {
LiveStepDynamicModelSelectionKey,
ParentSessionKey,
SandboxKey,
+ ScheduleIdKey,
SessionTraceSeedKey,
SessionKey,
SessionIdKey,
@@ -43,7 +44,11 @@ import type { DynamicResolveContext } from "#dynamic/definition.js";
import { registerDurableDynamicCallback } from "#tools/durable-callbacks.js";
import type { RunMode } from "#shared/run-mode.js";
import { compactMessages, shouldCompact } from "#harness/compaction.js";
-import { getHarnessEmissionState, isHarnessBetweenTurns } from "#harness/emission.js";
+import {
+ getHarnessEmissionState,
+ isHarnessBetweenTurns,
+ setHarnessEmissionState,
+} from "#harness/emission.js";
import {
getPendingAuthorization,
modelFacingAuthorizationOutput,
@@ -236,6 +241,21 @@ function createScheduleContext(): ContextContainer {
const ctx = new ContextContainer();
ctx.set(AuthKey, SCHEDULE_APP_AUTH);
ctx.set(InitiatorAuthKey, SCHEDULE_APP_AUTH);
+ ctx.set(ScheduleIdKey, "test-schedule");
+ return ctx;
+}
+
+function createScheduledUserContext(): ContextContainer {
+ const auth = {
+ attributes: {},
+ authenticator: "fixture-user",
+ principalId: "scheduled-owner",
+ principalType: "user" as const,
+ };
+ const ctx = new ContextContainer();
+ ctx.set(AuthKey, auth);
+ ctx.set(InitiatorAuthKey, auth);
+ ctx.set(ScheduleIdKey, "dynamic-tasks");
return ctx;
}
@@ -5226,6 +5246,32 @@ describe("createToolLoopHarness", () => {
}
});
+ it("offers silent delivery on a user-auth scheduled initiating retry", async () => {
+ setupFirstThenAgent(emptyResult, successResult);
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { emit } = createEventCollector();
+ const runStep = createToolLoopHarness(createTestConfig("conversation", emit));
+ const ctx = createScheduledUserContext();
+ ctx.set(TurnTaskDeliveryKey, "initiating");
+
+ try {
+ await contextStorage.run(ctx, () =>
+ runStep(createTestSession(), { message: "[Task state]" }),
+ );
+
+ const reissueAgent = vi.mocked(ToolLoopAgent).mock.results[1]?.value as {
+ stream: ReturnType<typeof vi.fn>;
+ };
+ const reissueMessages = reissueAgent.stream.mock.calls[0]?.[0]?.messages as Array<{
+ content: unknown;
+ role: string;
+ }>;
+ expect(reissueMessages.at(-1)?.content).toContain(EMPTY_DELIVERY_SENTINEL);
+ } finally {
+ warnSpy.mockRestore();
+ }
+ });
+
it("does not offer conditional delivery on a scheduled retry with an output schema", async () => {
setupFirstThenAgent(emptyResult, finalOutputResult("Done.", { status: "ok" }));
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
@@ -11875,10 +11921,37 @@ describe("createToolLoopHarness", () => {
});
});
+ it("routes later-turn initiating task context through user messages", async () => {
+ setupMockAgent(defaultModelResult());
+ const runStep = createToolLoopHarness(createTestConfig("conversation"));
+ const ctx = new ContextContainer();
+ const taskState = '[Task state]\n{"tasks":[]}';
+ ctx.set(TurnTaskDeliveryKey, "initiating");
+ ctx.set(TurnTaskStateKey, taskState);
+ const session = setHarnessEmissionState(createTestSession(), {
+ sequence: 1,
+ sessionStarted: true,
+ stepIndex: 0,
+ turnId: "",
+ });
+
+ await contextStorage.run(ctx, () =>
+ runStep(session, { message: "Start the background work." }),
+ );
+
+ const { instructions, messages } = getLastAgentSettings();
+ expect(instructions).toBe("You are a test assistant.");
+ expect(messages.slice(-3)).toEqual([
+ { role: "user", content: taskState },
+ { role: "user", content: TASK_DELIVERY_INITIATING_INSTRUCTION },
+ { role: "user", content: "Start the background work." },
+ ]);
+ });
+
it("keeps a scheduled initiating task turn conditionally deliverable", async () => {
setupMockAgent(defaultModelResult());
const runStep = createToolLoopHarness(createTestConfig("conversation"));
- const ctx = createScheduleContext();
+ const ctx = createScheduledUserContext();
ctx.set(TurnTaskDeliveryKey, "initiating");
await contextStorage.run(ctx, () =>
@@ -11892,6 +11965,22 @@ describe("createToolLoopHarness", () => {
});
});
+ it("does not apply session schedule provenance to a later human turn", async () => {
+ setupMockAgent(defaultModelResult());
+ const runStep = createToolLoopHarness(createTestConfig("conversation"));
+ const ctx = createScheduledUserContext();
+ const session = setHarnessEmissionState(createTestSession(), {
+ sequence: 1,
+ sessionStarted: true,
+ stepIndex: 0,
+ turnId: "",
+ });
+
+ await contextStorage.run(ctx, () => runStep(session, { message: "What happened?" }));
+
+ expect(getLastAgentSettings().instructions).toBe("You are a test assistant.");
+ });
+
it.each([
["pending", TASK_DELIVERY_PENDING_INSTRUCTION],
["settled", TASK_DELIVERY_SETTLED_INSTRUCTION],
@@ -11902,38 +11991,26 @@ describe("createToolLoopHarness", () => {
const runStep = createToolLoopHarness(createTestConfig("conversation"));
const ctx = new ContextContainer();
ctx.set(TurnTaskDeliveryKey, phase);
+ const session = setHarnessEmissionState(createTestSession(), {
+ sequence: 1,
+ sessionStarted: true,
+ stepIndex: 0,
+ turnId: "",
+ });
await contextStorage.run(ctx, () =>
- runStep(createTestSession(), { message: "Background task task_1 is completed." }),
+ runStep(session, { message: "Background task task_1 is completed." }),
);
- const { instructions } = getLastAgentSettings();
- expect(instructions).toEqual({
- role: "system",
- content: `You are a test assistant.\n\n${instruction}`,
- });
+ const { instructions, messages } = getLastAgentSettings();
+ expect(instructions).toBe("You are a test assistant.");
+ expect(messages.slice(-2)).toEqual([
+ { role: "user", content: instruction },
+ { role: "user", content: "Background task task_1 is completed." },
+ ]);
},
);
- it("does not add conditional-delivery guidance to a human continuation", async () => {
- setupMockAgent(defaultModelResult());
- const runStep = createToolLoopHarness(createTestConfig("conversation"));
- const ctx = createScheduleContext();
- ctx.set(AuthKey, {
- attributes: {},
- authenticator: "slack",
- principalId: "U123",
- principalType: "user",
- });
-
- await contextStorage.run(ctx, () =>
- runStep(createTestSession(), { message: "What happened?" }),
- );
-
- const { instructions } = getLastAgentSettings();
- expect(instructions).toBe("You are a test assistant.");
- });
-
it("does not add conditional-delivery guidance to a task-owned conversation child", 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.ts
index 2c757a139..e944cef85 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -19,7 +19,6 @@ import {
type TypedToolError,
type TypedToolResult,
} from "ai";
-import { isScheduleAppAuth } from "#channel/schedule-auth.js";
import type { SessionAuthContext } from "#channel/types.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { resolveProviderHeaders } from "#internal/gateway.js";
@@ -37,6 +36,7 @@ import {
ChannelInstrumentationKey,
ParentSessionKey,
ParentTraceContextKey,
+ ScheduleIdKey,
SessionCallbackKey,
SessionTraceSeedKey,
TurnTaskDeliveryKey,
@@ -110,6 +110,7 @@ import {
resolveCompactionModel,
shouldCompact,
} from "#harness/compaction.js";
+import { createCurrentMessages } from "#harness/current-messages.js";
import {
accumulateTurnUsage,
getTurnUsageState,
@@ -226,16 +227,8 @@ import {
import { summarizeKnownError, type SemanticErrorSummary } from "#harness/semantic-errors/index.js";
import { throwIfTurnAborted } from "#harness/turn-cancellation.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
-import {
- CONDITIONAL_DELIVERY_INSTRUCTION,
- EMPTY_DELIVERY_SENTINEL,
- hasEmptyDeliverySentinel,
-} from "#shared/empty-delivery.js";
-import {
- TASK_DELIVERY_INITIATING_INSTRUCTION,
- TASK_DELIVERY_PENDING_INSTRUCTION,
- TASK_DELIVERY_SETTLED_INSTRUCTION,
-} from "#tasks/delivery-context.js";
+import { EMPTY_DELIVERY_SENTINEL, hasEmptyDeliverySentinel } from "#shared/empty-delivery.js";
+import { resolveDeliveryPolicy } from "#tasks/delivery-policy.js";
import { extractWorkflowStreamWriteErrorDetails } from "#harness/workflow-stream-error.js";
import {
ensureOtelIntegration,
@@ -1367,27 +1360,15 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
}
const approvedTools = getApprovedTools(session);
- const taskDeliveryPhase = ctx?.get(TurnTaskDeliveryKey);
- const deliveryInstruction =
- // A structured-output run must always produce its declared result.
- session.outputSchema !== undefined ||
- // Eligibility requires durable framework provenance from the active context.
- ctx === undefined ||
- // A child must always return its result to its parent, even when framework-triggered.
- ctx.get(ParentSessionKey) !== undefined
- ? undefined
- : taskDeliveryPhase === "pending"
- ? TASK_DELIVERY_PENDING_INSTRUCTION
- : taskDeliveryPhase === "settled"
- ? TASK_DELIVERY_SETTLED_INSTRUCTION
- : // A schedule-initiated root turn may have nothing worth delivering.
- isScheduleAppAuth(ctx.get(AuthKey))
- ? CONDITIONAL_DELIVERY_INSTRUCTION
- : taskDeliveryPhase === "initiating"
- ? TASK_DELIVERY_INITIATING_INSTRUCTION
- : undefined;
- const emptyDeliveryEnabled =
- deliveryInstruction !== undefined && taskDeliveryPhase !== "initiating";
+ const isFirstTurn = emissionState.sequence === 0;
+ const hasScheduleProvenance = isFirstTurn && ctx?.get(ScheduleIdKey) !== undefined;
+ const deliveryPolicy = resolveDeliveryPolicy({
+ hasScheduleProvenance,
+ hasOutputSchema: session.outputSchema !== undefined,
+ isChild: ctx?.get(ParentSessionKey) !== undefined,
+ isFirstTurn,
+ taskDeliveryPhase: ctx?.get(TurnTaskDeliveryKey),
+ });
// --- Execute via ToolLoopAgent ------------------------------------------
@@ -1396,48 +1377,37 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
* `console.error(error)` handler inside `streamText`. Errors are
* handled by the harness catch block and emitted as stream events.
*/
- // Hydrate `eve-sandbox:` ref FileParts into inline bytes for the
- // model call only. The result is transient — `messages` itself
- // remains ref-only so it can flow into `session.history` without
- // bloating every future step boundary.
- const hydratedMessages = await hydrateSandboxAttachments(projectedMessages);
-
- // AI SDK rejects role:"system" in `messages` — route system entries
- // from durable history to `instructions` instead.
- const systemMessages: SystemModelMessage[] = [];
- const nonSystemMessages: ModelMessage[] = [];
- for (const entry of hydratedMessages) {
- if (entry.role === "system") {
- systemMessages.push(entry);
- } else {
- nonSystemMessages.push(entry);
- }
- }
+ // AI SDK rejects role:"system" in `messages`; currentMessages also keeps
+ // later turn-local context out of the stable system prompt cache prefix.
+ // Insert that context before the current delivery so the triggering user
+ // message remains the model's latest request.
+ const currentMessages = createCurrentMessages(projectedMessages, {
+ currentTurnMessages: preparedTurnInput,
+ });
if (ctx !== undefined) {
- systemMessages.push(...buildDynamicInstructionMessages(ctx));
+ currentMessages.addSystem(buildDynamicInstructionMessages(ctx));
const skillAnnouncement = ctx.get(PendingSkillAnnouncementKey);
if (skillAnnouncement !== undefined && skillAnnouncement.length > 0) {
- systemMessages.push({ role: "system", content: skillAnnouncement });
+ currentMessages.add(emissionState.sequence, skillAnnouncement);
}
const taskState = ctx.get(TurnTaskStateKey);
if (taskState !== undefined) {
- systemMessages.push({ role: "system", content: taskState });
+ currentMessages.add(emissionState.sequence, taskState);
}
}
- if (deliveryInstruction !== undefined) {
- systemMessages.push({
- role: "system",
- content: deliveryInstruction,
- });
+ if (deliveryPolicy.instruction !== undefined) {
+ currentMessages.add(emissionState.sequence, deliveryPolicy.instruction);
}
const pendingApprovals = renderPendingApprovalsInstruction(
getPendingInputBatches(session.state).flatMap((batch) => batch.requests),
);
if (pendingApprovals !== undefined) {
- systemMessages.push({ role: "system", content: pendingApprovals });
+ currentMessages.add(emissionState.sequence, pendingApprovals, { cacheFriendly: false });
}
- const modelMessages = nonSystemMessages;
+ // Hydrate `eve-sandbox:` ref FileParts into inline bytes for the model call
+ // only. Session history remains ref-only across future step boundaries.
+ const modelMessages = await hydrateSandboxAttachments(currentMessages.nonSystemMessages);
const prepareModelCallInput = (extraSystemNote?: string) => {
const extraSystemEntry: SystemModelMessage[] = extraSystemNote
@@ -1447,8 +1417,8 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
? [{ role: "system" as const, content: session.agent.system }]
: [];
const rawInstructions =
- systemMessages.length > 0 || extraSystemEntry.length > 0
- ? [...extraSystemEntry, ...baseSystemEntry, ...systemMessages]
+ currentMessages.systemMessages.length > 0 || extraSystemEntry.length > 0
+ ? [...extraSystemEntry, ...baseSystemEntry, ...currentMessages.systemMessages]
: undefined;
const markedInstructions =
rawInstructions !== undefined && marker
@@ -1512,7 +1482,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
// call's wire request.
const callMessages = opts.trailingUserNote
? [...modelMessages, { role: "user" as const, content: opts.trailingUserNote }]
- : modelMessages;
+ : [...modelMessages];
const harnessTools = buildHarnessToolsWithDynamicSubagents(config.tools, ctx);
const backgroundBatch = createBackgroundToolCallBatch();
const advertisedHarnessTools = getAdvertisedTools({
@@ -1847,7 +1817,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
}),
(current) =>
attemptEmptyResponseRecovery({
- emptyDeliveryEnabled,
+ emptyDeliveryEnabled: deliveryPolicy.allowsEmptyDelivery,
error: current.error,
retryCallOptions: current.retryCallOptions,
runOneModelCall,
diff --git a/packages/eve/src/tasks/delivery-policy.test.ts b/packages/eve/src/tasks/delivery-policy.test.ts
new file mode 100644
index 000000000..e04ed3252
--- /dev/null
+++ b/packages/eve/src/tasks/delivery-policy.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+
+import { CONDITIONAL_DELIVERY_INSTRUCTION } from "#shared/empty-delivery.js";
+import {
+ TASK_DELIVERY_INITIATING_INSTRUCTION,
+ TASK_DELIVERY_PENDING_INSTRUCTION,
+ TASK_DELIVERY_SETTLED_INSTRUCTION,
+} from "#tasks/delivery-context.js";
+import { resolveDeliveryPolicy } from "#tasks/delivery-policy.js";
+
+describe("resolveDeliveryPolicy", () => {
+ it.each([
+ ["scheduled launch", "initiating", true, true, CONDITIONAL_DELIVERY_INSTRUCTION, true],
+ ["user launch", "initiating", true, false, TASK_DELIVERY_INITIATING_INSTRUCTION, false],
+ ["pending wake", "pending", false, true, TASK_DELIVERY_PENDING_INSTRUCTION, true],
+ ["settled wake", "settled", false, true, TASK_DELIVERY_SETTLED_INSTRUCTION, false],
+ ] as const)(
+ "resolves %s",
+ (
+ _name,
+ taskDeliveryPhase,
+ isFirstTurn,
+ hasScheduleProvenance,
+ instruction,
+ allowsEmptyDelivery,
+ ) => {
+ expect(
+ resolveDeliveryPolicy({
+ hasScheduleProvenance,
+ hasOutputSchema: false,
+ isChild: false,
+ isFirstTurn,
+ taskDeliveryPhase,
+ }),
+ ).toEqual({ allowsEmptyDelivery, instruction });
+ },
+ );
+
+ it.each([
+ ["structured output", true, false],
+ ["child session", false, true],
+ ] as const)("keeps %s mandatory", (_name, hasOutputSchema, isChild) => {
+ expect(
+ resolveDeliveryPolicy({
+ hasScheduleProvenance: true,
+ hasOutputSchema,
+ isChild,
+ isFirstTurn: true,
+ taskDeliveryPhase: "initiating",
+ }),
+ ).toEqual({ allowsEmptyDelivery: false });
+ });
+
+ it("acknowledges background work launched on a later turn", () => {
+ expect(
+ resolveDeliveryPolicy({
+ hasOutputSchema: false,
+ hasScheduleProvenance: true,
+ isChild: false,
+ isFirstTurn: false,
+ taskDeliveryPhase: "initiating",
+ }),
+ ).toEqual({
+ allowsEmptyDelivery: false,
+ instruction: TASK_DELIVERY_INITIATING_INSTRUCTION,
+ });
+ });
+});
diff --git a/packages/eve/src/tasks/delivery-policy.ts b/packages/eve/src/tasks/delivery-policy.ts
new file mode 100644
index 000000000..3df2f25d7
--- /dev/null
+++ b/packages/eve/src/tasks/delivery-policy.ts
@@ -0,0 +1,53 @@
+import { CONDITIONAL_DELIVERY_INSTRUCTION } from "#shared/empty-delivery.js";
+import {
+ TASK_DELIVERY_INITIATING_INSTRUCTION,
+ TASK_DELIVERY_PENDING_INSTRUCTION,
+ TASK_DELIVERY_SETTLED_INSTRUCTION,
+} from "#tasks/delivery-context.js";
+
+export interface DeliveryPolicy {
+ readonly allowsEmptyDelivery: boolean;
+ readonly instruction?: string;
+}
+
+const POLICIES = {
+ conditional: {
+ allowsEmptyDelivery: true,
+ instruction: CONDITIONAL_DELIVERY_INSTRUCTION,
+ },
+ initiating: {
+ allowsEmptyDelivery: false,
+ instruction: TASK_DELIVERY_INITIATING_INSTRUCTION,
+ },
+ normal: { allowsEmptyDelivery: false },
+ pending: {
+ allowsEmptyDelivery: true,
+ instruction: TASK_DELIVERY_PENDING_INSTRUCTION,
+ },
+ settled: {
+ allowsEmptyDelivery: false,
+ instruction: TASK_DELIVERY_SETTLED_INSTRUCTION,
+ },
+} as const satisfies Record<string, DeliveryPolicy>;
+
+/** Resolves one policy for both model prompting and empty-response recovery. */
+export function resolveDeliveryPolicy(input: {
+ readonly hasOutputSchema: boolean;
+ readonly isChild: boolean;
+ readonly isFirstTurn: boolean;
+ readonly hasScheduleProvenance: boolean;
+ readonly 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;
+ // Partial cohort results are withheld until the parent can report the cohort once.
+ if (input.taskDeliveryPhase === "pending") return POLICIES.pending;
+ // A complete cohort owes its caller the consolidated result and must not disappear silently.
+ if (input.taskDeliveryPhase === "settled") return POLICIES.settled;
+ // Nobody prompted a schedule-created first turn, so starting work needs no acknowledgement.
+ if (input.isFirstTurn && input.hasScheduleProvenance) return POLICIES.conditional;
+ // User-prompted background work acknowledges acceptance without waiting for results.
+ if (input.taskDeliveryPhase === "initiating") return POLICIES.initiating;
+ // Ordinary turns retain the agent's normal response contract.
+ return POLICIES.normal;
+}