The Open Framework for Building Agents
Bind background subagents to creator auth (#3367)
e0-gh-vercel-connect[bot]a63fb187fd7a
diff --git a/.changeset/background-subagent-auth.md b/.changeset/background-subagent-auth.mdnew file mode 100644index 000000000..8fb7116fa--- /dev/null+++ b/.changeset/background-subagent-auth.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep background subagents bound to the authentication context of the turn that created their task, even when another caller starts a later turn first.diff --git a/e2e/fixtures/fixture-tasks/agent/agent.ts b/e2e/fixtures/fixture-tasks/agent/agent.tsindex 41dd2873d..742d4772d 100644--- a/e2e/fixtures/fixture-tasks/agent/agent.ts+++ b/e2e/fixtures/fixture-tasks/agent/agent.ts@@ -7,6 +7,7 @@ import {type MockModelToolResult,} from "eve/evals";+import { AUTH_SNAPSHOT_MARKER } from "./lib/lifecycle-control.js";import { lifecycleModel } from "./lib/lifecycle-model.js";const TASK_ID_PATTERN = /task_[a-z0-9]+/iu;@@ -32,6 +33,21 @@ function respond(request: MockModelRequest): MockModelResponse | string {if (message.startsWith("CHILD-TASK-EXCLUSIVITY-LATER ")) {return laterBusyWorker(request, message);}+ if (message === "TASK-AUTH-SNAPSHOT-ROOT") {+ return reportAuthSnapshotTurn(+ request,+ "task-auth-snapshot-root",+ "TASK-AUTH-SNAPSHOT-ROOT-ACK",+ );+ }+ if (message === "TASK-AUTH-SNAPSHOT-LATER") {+ return reportAuthSnapshotTurn(+ request,+ "task-auth-snapshot-later",+ "TASK-AUTH-SNAPSHOT-LATER-ACK",+ );+ }+ if (message.startsWith("TASK-AUTH-SNAPSHOT ")) return startAuthSnapshotTask(request, message);if (message.startsWith("TASK-A2-CHILD-FAILURE-VERIFY ")) {return inspectTerminalTask(request,@@ -168,6 +184,43 @@ function respond(request: MockModelRequest): MockModelResponse | string {return `Mock reply: ${message}`;}+function startAuthSnapshotTask(+ request: MockModelRequest,+ message: string,+): MockModelResponse | string {+ const authCallId = "task-auth-snapshot-creator";+ if (resultById(request, authCallId) === undefined) {+ return authSnapshotToolCall(authCallId);+ }+ const callId = "task-auth-snapshot";+ if (resultById(request, callId) !== undefined) return "TASK-AUTH-SNAPSHOT-STARTED";+ const key = message.split(" ").at(-1);+ if (key === undefined) throw new Error("Auth snapshot scenario has no lifecycle key.");+ return {+ toolCalls: [+ {+ id: callId,+ input: { child: false, delayedAuthChild: true, key, marker: AUTH_SNAPSHOT_MARKER },+ name: "lifecycle_task",+ },+ ],+ };+}++function reportAuthSnapshotTurn(+ request: MockModelRequest,+ callId: string,+ acknowledgement: string,+): MockModelResponse | string {+ return resultById(request, callId) === undefined ? authSnapshotToolCall(callId) : acknowledgement;+}++function authSnapshotToolCall(callId: string): MockModelResponse {+ return {+ toolCalls: [{ id: callId, input: {}, name: "snapshot_whoami" }],+ };+}+function childToolSurfaceReport(request: MockModelRequest): MockModelResponse | string {const task = latestTaskState(request.userMessages)?.tasks.find((entry) => entry.status === "completed",diff --git a/e2e/fixtures/fixture-tasks/agent/channels/eve.ts b/e2e/fixtures/fixture-tasks/agent/channels/eve.tsindex 3ccf45418..f6e06cab8 100644--- a/e2e/fixtures/fixture-tasks/agent/channels/eve.ts+++ b/e2e/fixtures/fixture-tasks/agent/channels/eve.ts@@ -2,8 +2,9 @@ import type { AuthFn } from "eve/channels/auth";import { eveChannel } from "eve/channels/eve";import type { SessionAuthContext } from "eve/context";-const PRINCIPAL_A = "Bearer e2e-task-operation-a";-const PRINCIPAL_B = "Bearer e2e-task-operation-b";+const SESSION_INITIATOR_AUTHORIZATION = "Bearer e2e-task-session-initiator";+const LATER_PARENT_CALLER_AUTHORIZATION = "Bearer e2e-task-later-parent-caller";+const ANONYMOUS_TASK_CREATOR_HEADER = "x-eve-fixture-anonymous-task-creator";const REMOTE_CHILD = "Bearer e2e-task-remote-loopback";function principal(principalId: string): SessionAuthContext {@@ -17,11 +18,15 @@ function principal(principalId: string): SessionAuthContext {};}-const authenticateA: AuthFn<Request> = (request) =>- request.headers.get("authorization") === PRINCIPAL_A ? principal("operation-user-a") : null;+const authenticateSessionInitiator: AuthFn<Request> = (request) =>+ request.headers.get("authorization") === SESSION_INITIATOR_AUTHORIZATION+ ? principal("session-initiator")+ : null;-const authenticateB: AuthFn<Request> = (request) =>- request.headers.get("authorization") === PRINCIPAL_B ? principal("operation-user-b") : null;+const authenticateLaterParentCaller: AuthFn<Request> = (request) =>+ request.headers.get("authorization") === LATER_PARENT_CALLER_AUTHORIZATION+ ? principal("later-parent-caller")+ : null;const authenticateRemoteChild: AuthFn<Request> = (request) =>request.headers.get("authorization") === REMOTE_CHILD ? principal("remote-http-child") : null;@@ -29,5 +34,15 @@ const authenticateRemoteChild: AuthFn<Request> = (request) =>const authenticateEvalDriver: AuthFn<Request> = () => principal("eval-driver");export default eveChannel({- auth: [authenticateA, authenticateB, authenticateRemoteChild, authenticateEvalDriver],+ auth: [+ authenticateSessionInitiator,+ authenticateLaterParentCaller,+ authenticateRemoteChild,+ authenticateEvalDriver,+ ],+ onMessage({ eve }) {+ return {+ auth: eve.request.headers.get(ANONYMOUS_TASK_CREATOR_HEADER) === "1" ? null : eve.caller,+ };+ },});diff --git a/e2e/fixtures/fixture-tasks/agent/channels/lifecycle.ts b/e2e/fixtures/fixture-tasks/agent/channels/lifecycle.tsindex 6d0525ac5..70d283508 100644--- a/e2e/fixtures/fixture-tasks/agent/channels/lifecycle.ts+++ b/e2e/fixtures/fixture-tasks/agent/channels/lifecycle.ts@@ -1,13 +1,17 @@import { defineChannel, POST } from "eve/channels";import { getHookByToken, getRun, getWorld, resumeHook } from "workflow/api";import { z } from "zod";-import { lifecycleNamespace, type LifecycleControlEvent } from "../lib/lifecycle-control.js";+import {+ AUTH_SNAPSHOT_MARKER,+ lifecycleNamespace,+ type LifecycleControlEvent,+} from "../lib/lifecycle-control.js";const bodySchema = z.object({key: z.string().uuid(),index: z.number().int().min(0).max(20).optional(),token: z.string().min(1).max(512).optional(),- marker: z.enum(["A", "B"]).optional(),+ marker: z.enum(["A", "B", AUTH_SNAPSHOT_MARKER]).optional(),});// Fixture-only capability routes: a per-eval random key addresses only its owndiff --git a/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-control.ts b/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-control.tsindex 048787703..181059f75 100644--- a/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-control.ts+++ b/e2e/fixtures/fixture-tasks/agent/lib/lifecycle-control.ts@@ -1,9 +1,13 @@import { createHook, getWorkflowMetadata } from "workflow";import { getRun } from "workflow/api";+export const AUTH_SNAPSHOT_MARKER = "auth-snapshot" as const;++export type LifecycleMarker = "A" | "B" | "parent" | typeof AUTH_SNAPSHOT_MARKER;+export interface LifecycleControlEvent {readonly kind: "gate" | "owner" | "gate-cancelled";- readonly marker: "A" | "B" | "parent";+ readonly marker: LifecycleMarker;readonly runId: string;readonly sessionId: string;readonly turnId: string;@@ -34,7 +38,7 @@ export async function lifecycleGate(input: {parentSessionId: string;key: string;- marker: "A" | "B" | "parent";+ marker: LifecycleMarker;sessionId: string;turnId: string;},diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/agent.ts b/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/agent.tsnew file mode 100644index 000000000..bf1ac6250--- /dev/null+++ b/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/agent.ts@@ -0,0 +1,7 @@+import { e2eSubagentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";++export default defineAgent({+ ...e2eSubagentConfig(),+ description: "Report the task dispatch principal through snapshot_whoami.",+});diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/tools/snapshot_whoami.ts b/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/tools/snapshot_whoami.tsnew file mode 100644index 000000000..0ca6aaa47--- /dev/null+++ b/e2e/fixtures/fixture-tasks/agent/subagents/auth-snapshot-worker/tools/snapshot_whoami.ts@@ -0,0 +1,13 @@+import { defineTool } from "eve/tools";+import { z } from "zod";++export default defineTool({+ description: "Report the current and initiating principals for this child session.",+ inputSchema: z.object({}),+ execute(_input, ctx) {+ return {+ current: ctx.session.auth.current?.principalId ?? null,+ initiator: ctx.session.auth.initiator?.principalId ?? null,+ };+ },+});diff --git a/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_task.ts b/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_task.tsindex 1b8d370da..ebfa1a48d 100644--- a/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_task.ts+++ b/e2e/fixtures/fixture-tasks/agent/tools/lifecycle_task.ts@@ -5,11 +5,24 @@ import {} from "eve/tools";import { getWorkflowMetadata } from "workflow";import { z } from "zod";-import { lifecycleGate, publishLifecycleControl } from "../lib/lifecycle-control.js";+import {+ AUTH_SNAPSHOT_MARKER,+ lifecycleGate,+ publishLifecycleControl,+ type LifecycleMarker,+} from "../lib/lifecycle-control.js";-type Input = { key: string; marker: "A" | "B"; child: boolean };+type Input = {+ key: string;+ marker: Exclude<LifecycleMarker, "parent">;+ child: boolean;+ delayedAuthChild?: boolean;+};-async function execute({ key, marker, child }: Input, ctx: WorkflowToolContext): Promise<string> {+async function execute(+ { key, marker, child, delayedAuthChild }: Input,+ ctx: WorkflowToolContext,+): Promise<string> {"use workflow";const parentSessionId = ctx.session.id;await publishLifecycleControl(parentSessionId, key, {@@ -19,7 +32,18 @@ async function execute({ key, marker, child }: Input, ctx: WorkflowToolContext):sessionId: parentSessionId,turnId: ctx.session.turn.id,});- if (child) {+ if (delayedAuthChild === true) {+ await lifecycleGate({+ parentSessionId,+ key,+ marker,+ sessionId: ctx.session.id,+ turnId: ctx.session.turn.id,+ });+ await ctx.agent("auth-snapshot-worker", {+ message: "Call snapshot_whoami exactly once.",+ });+ } else if (child) {try {await ctx.agent("lifecycle-worker", {message: JSON.stringify({ parentSessionId, key, marker }),@@ -47,10 +71,14 @@ async function execute({ key, marker, child }: Input, ctx: WorkflowToolContext):}const tool: WorkflowToolDefinition<Input, string> = defineWorkflowTool({- description:- "Coordinate Alice and Bob's independently released background work for lifecycle checks.",+ description: "Coordinate independently released background work for lifecycle checks.",execution: "background",- inputSchema: z.object({ key: z.string().uuid(), marker: z.enum(["A", "B"]), child: z.boolean() }),+ inputSchema: z.object({+ key: z.string().uuid(),+ marker: z.enum(["A", "B", AUTH_SNAPSHOT_MARKER]),+ child: z.boolean(),+ delayedAuthChild: z.boolean().optional(),+ }),execute,});diff --git a/e2e/fixtures/fixture-tasks/agent/tools/snapshot_whoami.ts b/e2e/fixtures/fixture-tasks/agent/tools/snapshot_whoami.tsnew file mode 100644index 000000000..88f42426c--- /dev/null+++ b/e2e/fixtures/fixture-tasks/agent/tools/snapshot_whoami.ts@@ -0,0 +1,13 @@+import { defineTool } from "eve/tools";+import { z } from "zod";++export default defineTool({+ description: "Report the current and initiating principals for this session turn.",+ inputSchema: z.object({}),+ execute(_input, ctx) {+ return {+ current: ctx.session.auth.current?.principalId ?? null,+ initiator: ctx.session.auth.initiator?.principalId ?? null,+ };+ },+});diff --git a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.accepted-acknowledged.creator-context.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.accepted-acknowledged.creator-context.eval.tsnew file mode 100644index 000000000..0d174b415--- /dev/null+++ b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.accepted-acknowledged.creator-context.eval.ts@@ -0,0 +1,142 @@+import { e2eModel } from "@eve-e2e/config";+import type { EveEvalContext } from "eve/evals";+import { equals } from "eve/evals/expect";++import type { LifecycleControlEvent } from "../agent/lib/lifecycle-control.js";+import { requireSessionStreamIndex, type TaskEvalSessionDriver } from "./shared.js";+import { defineTaskEval } from "./task-transition.js";++const SESSION_INITIATOR_AUTHORIZATION = "Bearer e2e-task-session-initiator";+const LATER_PARENT_CALLER_AUTHORIZATION = "Bearer e2e-task-later-parent-caller";+const ANONYMOUS_TASK_CREATOR_HEADER = "x-eve-fixture-anonymous-task-creator";++export default defineTaskEval({+ description:+ "A schedule-shaped background task with no current principal keeps the session initiator after a later turn changes the current caller.",+ tags: ["real-model"],+ transition: {+ primary: "task.dispatch.start.accepted-acknowledged",+ dimensions: { transport: "local" },+ },+ async test(t) {+ const modelId = e2eModel();+ if (typeof modelId !== "string")+ throw new Error("Auth snapshot coverage requires a real model.");++ // One authenticated caller creates the session and remains its initiator.+ const firstTurn = await t.send("TASK-AUTH-SNAPSHOT-ROOT", {+ headers: { authorization: SESSION_INITIATOR_AUTHORIZATION },+ });+ firstTurn.expectOk();+ firstTurn.messageIncludes("TASK-AUTH-SNAPSHOT-ROOT-ACK");+ firstTurn.calledTool("snapshot_whoami", { count: 1, status: "completed" });+ // The first authenticated turn establishes the only session initiator.+ await t.require(+ firstTurn.requireToolCall("snapshot_whoami").output,+ equals({ current: "session-initiator", initiator: "session-initiator" }),+ );++ // A route-authenticated, schedule-shaped turn has no current session principal.+ const key = crypto.randomUUID();+ const started = await t.send(`TASK-AUTH-SNAPSHOT ${key}`, {+ headers: { [ANONYMOUS_TASK_CREATOR_HEADER]: "1" },+ });+ started.expectOk();+ started.messageIncludes("TASK-AUTH-SNAPSHOT-STARTED");+ started.calledTool("snapshot_whoami", { count: 1, status: "completed" });+ // The schedule-shaped turn has no current principal but retains the session initiator.+ await t.require(+ started.requireToolCall("snapshot_whoami").output,+ equals({ current: null, initiator: "session-initiator" }),+ );+ const sessionId = started.sessionId;+ if (sessionId === undefined) throw new Error("The task has no parent session.");++ const gateToken = await waitForGate(t, sessionId, key);++ // Another authenticated caller takes the last parent turn before nested dispatch.+ const lastParentTurn = await t.send("TASK-AUTH-SNAPSHOT-LATER", {+ headers: { authorization: LATER_PARENT_CALLER_AUTHORIZATION },+ });+ lastParentTurn.expectOk();+ lastParentTurn.messageIncludes("TASK-AUTH-SNAPSHOT-LATER-ACK");+ lastParentTurn.calledTool("snapshot_whoami", { count: 1, status: "completed" });+ // The later parent turn changes only the current principal.+ await t.require(+ lastParentTurn.requireToolCall("snapshot_whoami").output,+ equals({ current: "later-parent-caller", initiator: "session-initiator" }),+ );++ await releaseGate(t, sessionId, key, gateToken);+ const childSessionId = await waitForSubagent(t, t);+ const child = await t.target.watchTurn(childSessionId).result();+ child.expectOk();+ child.noFailedActions();+ child.event("step.started", { data: { modelId } });+ child.calledTool("snapshot_whoami", { count: 1, status: "completed" });+ // Nested dispatch uses the task creator's null current principal, not the later caller.+ await t.require(+ child.requireToolCall("snapshot_whoami").output,+ equals({ current: null, initiator: "session-initiator" }),+ );+ },+});++async function waitForGate(t: EveEvalContext, sessionId: string, key: string): Promise<string> {+ for (let index = 0; index < 2; index += 1) {+ const response = await t.target.fetch(+ `/eve/v1/task-lifecycle/${encodeURIComponent(sessionId)}/next`,+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ key, index }),+ signal: t.signal,+ },+ );+ await t.require(response.status, equals(200));+ const event = (await response.json()) as LifecycleControlEvent;+ if (event.kind === "gate" && event.token !== undefined) return event.token;+ }+ throw new Error("The background task did not pause before starting its subagent.");+}++async function releaseGate(+ t: EveEvalContext,+ sessionId: string,+ key: string,+ token: string,+): Promise<void> {+ const response = await t.target.fetch(+ `/eve/v1/task-lifecycle/${encodeURIComponent(sessionId)}/release`,+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ key, token }),+ signal: t.signal,+ },+ );+ await t.require(response.status, equals(200));+ await t.require(await response.json(), equals({ released: true }));+}++async function waitForSubagent(+ t: EveEvalContext,+ initialSession: TaskEvalSessionDriver,+): Promise<string> {+ let session = initialSession;+ for (let attempt = 0; attempt < 8; attempt += 1) {+ const sessionId = session.sessionId;+ if (sessionId === undefined) throw new Error("The task has no parent session.");+ const live = t.target.watchTurn(sessionId, {+ startIndex: requireSessionStreamIndex(session, "Subagent wait"),+ });+ const turn = await live.result();+ turn.expectOk();+ session = live.session;+ const called = turn.events.find(+ (event) => event.type === "subagent.called" && event.data.name === "auth-snapshot-worker",+ );+ if (called?.type === "subagent.called") return called.data.childSessionId;+ }+ throw new Error("The background task did not start its subagent.");+}diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v39.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v39.tsnew file mode 100644index 000000000..27a08b5bb--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v39.ts@@ -0,0 +1,18 @@+import { defineDynamic, defineTool } from "#public/tools/index.js";++export default defineDynamic({+ events: {+ "session.started": () =>+ defineTool({+ description: "Read a token with retained epoch 39 provider ownership.",+ inputSchema: { type: "object", properties: {} },+ async execute(_input, ctx) {+ const token = await ctx.getToken({+ getToken: async () => ({ token: "fixture-token" }),+ principalType: "app",+ });+ return { token: token.token };+ },+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v42.ts b/packages/eve/extension-contracts/compatibility/tool/v42.tsnew file mode 100644index 000000000..8bfc99f51--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v42.ts@@ -0,0 +1,13 @@+import { defineTool } from "#public/tools/index.js";++export default defineTool({+ description: "Read a token with retained epoch 42 provider ownership.",+ inputSchema: { type: "object", properties: {} },+ async execute(_input, ctx) {+ const token = await ctx.getToken({+ getToken: async () => ({ token: "fixture-token" }),+ principalType: "app",+ });+ return { token: token.token };+ },+});diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v40.json b/packages/eve/extension-contracts/reports/dynamicTool/v40.jsonnew file mode 100644index 000000000..72a265938--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v40.json@@ -0,0 +1,14 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 40,+ "sha256": "c9b466bb11919ea9d79e4e522ea05331644c4fb285a3465bddc3c7bc4a9a3680",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "defineDurableCallback",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v43.json b/packages/eve/extension-contracts/reports/tool/v43.jsonnew file mode 100644index 000000000..da4bbec24--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v43.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 43,+ "sha256": "9ed3a0843b2498e4abf67bcd31cb4df6033f0ead47695ecddeb87ba07cf7a3a3",+ "exports": [+ "WorkflowTool",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 924156ede..98f2a989a 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 42,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 34, 35, 42],+ current: 43,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 34, 35, 42, 43],dropped: {14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",15: "TaskExec replaces stageEffect with send",@@ -49,10 +49,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},dynamicTool: {- current: 39,+ current: 40,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 28, 29, 30, 31, 32,- 33, 34, 39,+ 33, 34, 39, 40,],dropped: {21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",diff --git a/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts b/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.tsindex 72440edfd..55ec1a691 100644--- a/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts+++ b/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts@@ -64,6 +64,7 @@ describe("cancelAllIndexedSessionTasksStep", () => {function indexedTask(taskId: string): SessionTaskIndexEntry {return {createdByTurnId: "turn_0",+ dispatchContext: { auth: { current: null, initiator: null } },executor: { data: {}, kind: "workflow" },metadata: { kind: "tool", name: "research" },taskId,diff --git a/packages/eve/src/execution/parked-delivery-wait.test.ts b/packages/eve/src/execution/parked-delivery-wait.test.tsindex fb7944ca7..9528c4277 100644--- a/packages/eve/src/execution/parked-delivery-wait.test.ts+++ b/packages/eve/src/execution/parked-delivery-wait.test.ts@@ -471,6 +471,7 @@ function batchingInput(count = 100, crossTurn = false) {taskRunId: `run-${index}`,taskInboxToken: `inbox-${index}`,createdByTurnId: crossTurn ? `turn-${index + 1}` : "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "subagent", name: "worker" },})).concat([{@@ -479,6 +480,7 @@ function batchingInput(count = 100, crossTurn = false) {taskRunId: "other-run",taskInboxToken: "other-inbox",createdByTurnId: "turn-2",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "subagent", name: "worker" },},]),diff --git a/packages/eve/src/execution/tasks/parent/delegate.ts b/packages/eve/src/execution/tasks/parent/delegate.tsindex 15d471b8b..7d352ebd0 100644--- a/packages/eve/src/execution/tasks/parent/delegate.ts+++ b/packages/eve/src/execution/tasks/parent/delegate.ts@@ -18,10 +18,18 @@ import type { JsonValue } from "#shared/json.js";import type { TaskExecutorBinding } from "#tools/task.js";import { deriveTaskInboxToken, deriveTaskId } from "#tasks/task-id.js";import { isTerminalTaskStatus, type TaskMetadata } from "#tasks/types.js";+import type { TaskAgentDispatchContext } from "#tasks/session-index.js";+import type { ContextReader } from "#context/key.js";+import {+ SessionDynamicSubagentSelectionsKey,+ TurnDynamicSubagentSelectionsKey,+ type SessionAuth,+} from "#context/keys.js";/** A prepared background task: identity plus its started durable run. */export interface BackgroundTask {readonly activityWorkIdentity?: ActivityWorkIdentityV1;+ readonly dispatchContext: TaskAgentDispatchContext;readonly taskInboxToken: string;readonly createdByStepIndex?: number;readonly createdByTurnId: string;@@ -31,11 +39,23 @@ export interface BackgroundTask {readonly taskRunId: string;}+export function createTaskAgentDispatchContext(+ ctx: ContextReader,+ auth: SessionAuth,+): TaskAgentDispatchContext {+ return {+ auth,+ sessionDynamicSubagentSelections: ctx.get(SessionDynamicSubagentSelectionsKey),+ turnDynamicSubagentSelections: ctx.get(TurnDynamicSubagentSelectionsKey),+ };+}+type BackgroundTaskDraft = Omit<BackgroundTask, "taskRunId">;/** Derives the replay-stable task identity before its owning run is started. */export function prepareBackgroundTask(input: {readonly callId: string;+ readonly dispatchContext: TaskAgentDispatchContext;readonly metadata: TaskMetadata;readonly parentSessionId: string;readonly parentStepIndex?: number;@@ -54,6 +74,7 @@ export function prepareBackgroundTask(input: {}),createdByStepIndex: input.parentStepIndex ?? 0,createdByTurnId: input.parentTurnId,+ dispatchContext: input.dispatchContext,metadata: input.metadata,taskId,};@@ -63,6 +84,7 @@ export function prepareBackgroundTask(input: {export async function beginBackgroundTask(input: {readonly activityObserver?: ActivityObserverConfig;readonly callId: string;+ readonly dispatchContext: TaskAgentDispatchContext;readonly metadata: TaskMetadata;readonly parentSessionId: string;readonly parentStepIndex?: number;diff --git a/packages/eve/src/execution/tasks/parent/dispatch.test.ts b/packages/eve/src/execution/tasks/parent/dispatch.test.tsindex 3956ea987..89a6827cd 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.test.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.test.ts@@ -24,6 +24,7 @@ vi.mock("#internal/workflow/runtime.js", () => ({const entry = {createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },executor: { data: { hookToken: "run-hook", runId: "run-1" }, kind: "workflow-tool" },metadata: { kind: "tool", name: "export" },taskId: "task-1",diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.tsindex 48d9ebb55..5cfb36b95 100644--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts@@ -74,6 +74,7 @@ describe("recordTaskInputRequestStep", () => {tasks: [{createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "tool", name: "export" },taskId: "task-1",taskInboxToken: "task-token",@@ -137,6 +138,7 @@ describe("recordTaskInputRequestStep", () => {tasks: [{createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "tool", name: "export" },taskId: "task-1",taskInboxToken: "task-token",@@ -208,6 +210,7 @@ describe("recordTerminalTaskViewsStep", () => {tasks: [{createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { agentId: "agent-1", kind: "subagent", mode: "local", name: "research" },taskId: "task-1",taskInboxToken: "task-token",@@ -275,6 +278,7 @@ describe("recordTerminalTaskViewsStep", () => {tasks: [{createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "tool", name: "export" },taskId: "task-1",taskInboxToken: "task-token",diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.tsindex 0c51ea80c..c5d7d08b6 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import type { ActivityObserverConfig } from "#channel/types.js";import { ContextContainer, contextStorage } from "#context/container.js";-import { ActivityObserverKey, SessionKey } from "#context/keys.js";+import { ActivityObserverKey, SessionKey, type SessionAuth } from "#context/keys.js";import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";import { startTaskRun, waitForTaskCommandOwner } from "#execution/tasks/parent/run-parent.js";import {@@ -51,6 +51,7 @@ const handle = {};const entry = {createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { agentId: identity.id, kind: "subagent", name: identity.name },taskId: handle.ownerId,taskInboxToken: "original-task-inbox",@@ -77,10 +78,14 @@ function createSession(owned = true): HarnessSession {return owned ? recordSessionTask(session, entry) : session;}-async function createScope(session = createSession(), activityObserver?: ActivityObserverConfig) {+async function createScope(+ session = createSession(),+ activityObserver?: ActivityObserverConfig,+ auth: SessionAuth = { current: null, initiator: null },+) {const ctx = new ContextContainer();ctx.setVirtualContext(SessionKey, {- auth: { current: null, initiator: null },+ auth,sessionId: session.sessionId,turn: { id: "turn-2", sequence: 2 },});@@ -137,6 +142,69 @@ describe("background subagent steering", () => {} as never);});+ it("persists the creating turn's auth on the background task", async () => {+ const creatorCurrent = {+ attributes: {},+ authenticator: "test-idp",+ issuer: "test-idp",+ principalId: "creator-current",+ principalType: "user" as const,+ };+ const creatorInitiator = { ...creatorCurrent, principalId: "creator-initiator" };+ const scope = await createScope(createSession(), undefined, {+ current: creatorCurrent,+ initiator: creatorInitiator,+ });++ await scope.execute();+ const committed = await scope.commit();+ const task = getSessionTaskIndex(committed.state).find(+ (candidate) => candidate.taskId !== entry.taskId,+ );++ expect(task?.dispatchContext).toEqual({+ auth: { current: creatorCurrent, initiator: creatorInitiator },+ });+ if (task === undefined) throw new Error("Expected created task");+ const replayed = recordSessionTask(committed, {+ ...task,+ dispatchContext: {+ auth: {+ current: { ...creatorCurrent, principalId: "later-current" },+ initiator: { ...creatorInitiator, principalId: "later-initiator" },+ },+ },+ });+ expect(+ getSessionTaskIndex(replayed.state).find((candidate) => candidate.taskId === task.taskId)+ ?.dispatchContext,+ ).toEqual({ auth: { current: creatorCurrent, initiator: creatorInitiator } });+ });++ it("persists schedule-shaped auth with no current principal and one session initiator", async () => {+ const sessionInitiator = {+ attributes: {},+ authenticator: "test-idp",+ issuer: "test-idp",+ principalId: "session-initiator",+ principalType: "user" as const,+ };+ const scope = await createScope(createSession(), undefined, {+ current: null,+ initiator: sessionInitiator,+ });++ await scope.execute();+ const committed = await scope.commit();+ const task = getSessionTaskIndex(committed.state).find(+ (candidate) => candidate.taskId !== entry.taskId,+ );++ expect(task?.dispatchContext).toEqual({+ auth: { current: null, initiator: sessionInitiator },+ });+ });+it.each([{ metadata: undefined, supported: false },{ metadata: { sessionInboxWireVersion: 6 }, supported: false },diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.test.tsindex 51c7357fa..5cfe7d636 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { ContextContainer, contextStorage } from "#context/container.js";+import { SessionKey } from "#context/keys.js";import { backgroundToolExecutionProvider } from "#execution/tasks/parent/tool-execution.js";import { beginBackgroundTask } from "#execution/tasks/parent/delegate.js";import { sendTaskCommand, sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";@@ -11,7 +12,10 @@ import {} from "#harness/background-tools.js";import type { HarnessSession } from "#harness/types.js";-vi.mock("#execution/tasks/parent/delegate.js", () => ({ beginBackgroundTask: vi.fn() }));+vi.mock("#execution/tasks/parent/delegate.js", () => ({+ beginBackgroundTask: vi.fn(),+ createTaskAgentDispatchContext: vi.fn(() => ({ auth: { current: null, initiator: null } })),+}));vi.mock("#execution/tasks/parent/run-parent.js", () => ({sendTaskCommand: vi.fn(),sendTaskInboundPayload: vi.fn(),@@ -24,6 +28,7 @@ describe("ordinary background tool execution", () => {vi.mocked(sendTaskInboundPayload).mockResolvedValue("delivered");vi.mocked(beginBackgroundTask).mockResolvedValue({createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "tool", name: "export" },taskId: "task-1",taskInboxToken: "inbox-1",@@ -33,6 +38,11 @@ describe("ordinary background tool execution", () => {it("returns the fixed receipt while routing yields and the final return separately", async () => {const ctx = new ContextContainer();+ ctx.setVirtualContext(SessionKey, {+ auth: { current: null, initiator: null },+ sessionId: "session-1",+ turn: { id: "turn-1", sequence: 0 },+ });const session: HarnessSession = setHarnessEmissionState({agent: { modelReference: { id: "openai/gpt-5.4" }, system: "", tools: [] },diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.tsindex 4f72ab4f6..1c77e289b 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts@@ -26,6 +26,7 @@ import { findSessionTaskEntry, recordSessionTask } from "#tasks/session-index.jsimport type { AgentView } from "#subagents/handles/prompt.js";import {beginBackgroundTask,+ createTaskAgentDispatchContext,prepareBackgroundTask,rejectDelegatedDispatch,type BackgroundTask,@@ -386,6 +387,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {name: input.input.definition.name,};const activityLabel = projectToolStartLabel(input.input.definition, input.input.toolInput);+ const callbackSession = buildCallbackContext().session;const taskInput = {activityObserver: deriveBackgroundTaskActivityObserver({activityObserver: input.ctx.get(ActivityObserverKey),@@ -397,6 +399,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {rootSessionId: this.initialSession.rootSessionId ?? this.initialSession.sessionId,}),callId: input.input.options.toolCallId,+ dispatchContext: createTaskAgentDispatchContext(input.ctx, callbackSession.auth),metadata,parentSessionId: this.initialSession.sessionId,parentStepIndex: input.emission.stepIndex,@@ -408,6 +411,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {task: await beginBackgroundTask({activityObserver: taskInput.activityObserver,callId: taskInput.callId,+ dispatchContext: taskInput.dispatchContext,metadata: taskInput.metadata,parentSessionId: taskInput.parentSessionId,parentStepIndex: taskInput.parentStepIndex,@@ -490,7 +494,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {executeInput: workflow.executeInput?.(workflowInput),input: workflowInput,resultKind: workflow.resultKind,- session: buildCallbackContext().session,+ session: callbackSession,stepIndex: input.emission.stepIndex,toolName: input.input.definition.name,taskId: task.taskId,diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.tsindex 67d9090a5..40472d1c1 100644--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts@@ -431,6 +431,7 @@ function indexedTask(taskId: string): SessionTaskIndexEntry {return {taskInboxToken: `${taskId}:inbox`,createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: {kind: "tool",name: "research",diff --git a/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts b/packages/eve/src/execution/tools/subagent/accept-event-step.test.tsindex 16e178adf..f48644f3b 100644--- a/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts+++ b/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts@@ -36,6 +36,7 @@ const taskIndex = {tasks: [{createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "tool", name: "export" },taskId: "task-1",taskInboxToken: "task-token",diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts b/packages/eve/src/execution/tools/subagent/invoke-step.test.tsindex 4fa0f448a..42781fe7f 100644--- a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-step.test.ts@@ -13,6 +13,12 @@ import { readDurableSession } from "#execution/durable-session-store.js";import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";import { recordSessionTask } from "#tasks/session-index.js";+import {+ AuthKey,+ InitiatorAuthKey,+ SessionDynamicSubagentSelectionsKey,+ TurnDynamicSubagentSelectionsKey,+} from "#context/keys.js";vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({...(await importOriginal()),@@ -45,6 +51,15 @@ const action = {nodeId: "subagents/research",subagentName: "research",};+const creatorAuth = {+ attributes: {},+ authenticator: "test-idp",+ principalId: "creator-current",+ principalType: "user" as const,+};+const sessionInitiatorAuth = { ...creatorAuth, principalId: "session-initiator" };+const receiverAuth = { ...creatorAuth, principalId: "receiver-current" };+const receiverInitiatorAuth = { ...creatorAuth, principalId: "receiver-initiator" };const availableRecord = {address: { continuationToken: "child", kind: "agent/local" as const, sessionId: "child" },identity: { id: "agent-1", name: "research", nodeId: "subagents/research" },@@ -210,6 +225,25 @@ describe("owner agent invocation dispatch", () => {] as const)("resolves task activity for $dispatchKind ($taskKind, observed=$observed)",async ({ dispatchKind, taskKind, observed }) => {+ const serializedContext = {+ [AuthKey.name]: receiverAuth,+ [InitiatorAuthKey.name]: receiverInitiatorAuth,+ [SessionDynamicSubagentSelectionsKey.name]: { source: "receiver-session" },+ [TurnDynamicSubagentSelectionsKey.name]: { source: "receiver-turn" },+ "eve.test": "preserved",+ };+ const taskDispatchContext = {+ auth: { current: creatorAuth, initiator: sessionInitiatorAuth },+ sessionDynamicSubagentSelections: { source: "creator-session" } as never,+ turnDynamicSubagentSelections: { source: "creator-turn" } as never,+ };+ const planningContext = {+ ...serializedContext,+ [AuthKey.name]: creatorAuth,+ [InitiatorAuthKey.name]: sessionInitiatorAuth,+ [SessionDynamicSubagentSelectionsKey.name]: { source: "creator-session" },+ [TurnDynamicSubagentSelectionsKey.name]: { source: "creator-turn" },+ };const taskWork = {callId: "task-call",id: "work:task",@@ -222,6 +256,7 @@ describe("owner agent invocation dispatch", () => {const indexedSession = recordSessionTask(session as never, {activityWorkIdentity: taskWork,createdByTurnId: "turn-1",+ dispatchContext: taskDispatchContext,metadata: { kind: taskKind, name: "research" },taskId: "task-1",taskInboxToken: "task-token",@@ -235,6 +270,7 @@ describe("owner agent invocation dispatch", () => {});vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({...prepared,+ auth: creatorAuth,activityObserver: observed? {sink: { url: "https://parent.example/activity", version: 1 },@@ -246,17 +282,19 @@ describe("owner agent invocation dispatch", () => {},}: undefined,+ initiatorAuth: sessionInitiatorAuth,plan: [dispatchKind === "start"? { kind: "start", target: { action, kind: "local", source: { type: "runtime" } } }: { kind: "resume", action, agentId: "agent-1" },],+ serializedContext: planningContext,session: indexedSession,} as never);vi.mocked(startSubagent).mockResolvedValue(called);vi.mocked(dispatchToClaimedAgentAddress).mockResolvedValue(called);- await dispatchTaskAgentInvocationStep({+ const result = await dispatchTaskAgentInvocationStep({ownerId: "task-1",replyTo: "agent-reply",request: {@@ -264,7 +302,7 @@ describe("owner agent invocation dispatch", () => {invocationId: "call-1",kind: "agent-invoke",},- serializedContext: {},+ serializedContext,sessionState: {} as never,taskId: "task-1",});@@ -275,16 +313,131 @@ describe("owner agent invocation dispatch", () => {: undefined;if (dispatchKind === "start") {expect(startSubagent).toHaveBeenCalledWith(- expect.objectContaining({ taskActivityObserver: taskObserver }),+ expect.objectContaining({+ auth: creatorAuth,+ initiatorAuth: sessionInitiatorAuth,+ taskActivityObserver: taskObserver,+ }),);} else {expect(dispatchToClaimedAgentAddress).toHaveBeenCalledWith(- expect.objectContaining({ activityObserver: taskObserver }),+ expect.objectContaining({ activityObserver: taskObserver, auth: creatorAuth }),);}+ expect(prepareOwnerAgentInvocation).toHaveBeenCalledWith(+ expect.objectContaining({ serializedContext: planningContext }),+ );+ expect(result).toMatchObject({ serializedContext });},);+ it("uses an anonymous task's captured auth despite an authenticated receiving turn", async () => {+ const serializedContext = {+ [AuthKey.name]: receiverAuth,+ [InitiatorAuthKey.name]: receiverInitiatorAuth,+ [SessionDynamicSubagentSelectionsKey.name]: { source: "receiver-session" },+ [TurnDynamicSubagentSelectionsKey.name]: { source: "receiver-turn" },+ };+ const planningContext = {+ [AuthKey.name]: null,+ [InitiatorAuthKey.name]: sessionInitiatorAuth,+ };+ const indexedSession = recordSessionTask(session as never, {+ createdByTurnId: "turn-1",+ dispatchContext: {+ auth: { current: null, initiator: sessionInitiatorAuth },+ },+ metadata: { kind: "subagent", name: "research" },+ taskId: "task-1",+ taskInboxToken: "task-token",+ taskRunId: "task-run",+ });+ vi.mocked(readDurableSession).mockResolvedValue(indexedSession as never);+ vi.mocked(readLatestTaskView).mockResolvedValue({+ metadata: { kind: "subagent", name: "research" },+ status: "working",+ taskId: "task-1",+ });+ vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({+ ...prepared,+ auth: null,+ initiatorAuth: sessionInitiatorAuth,+ plan: [{ kind: "start", target: { action, kind: "local", source: { type: "runtime" } } }],+ serializedContext: planningContext,+ session: indexedSession,+ } as never);+ vi.mocked(startSubagent).mockResolvedValue(called);++ const result = await dispatchTaskAgentInvocationStep({+ ownerId: "task-1",+ replyTo: "agent-reply",+ request: {+ input: { message: "Find it", target: "research" },+ invocationId: "call-1",+ kind: "agent-invoke",+ },+ serializedContext,+ sessionState: { sessionId: "parent" } as never,+ taskId: "task-1",+ });++ expect(startSubagent).toHaveBeenCalledWith(+ expect.objectContaining({ auth: null, initiatorAuth: sessionInitiatorAuth }),+ );+ expect(prepareOwnerAgentInvocation).toHaveBeenCalledWith(+ expect.objectContaining({ serializedContext: planningContext }),+ );+ expect(result).toMatchObject({ serializedContext });+ });++ it("rejects only nested dispatch for a legacy task without creator context", async () => {+ vi.mocked(readDurableSession).mockResolvedValue({+ ...session,+ state: {+ ...session.state,+ "eve.tasks": {+ tasks: [+ {+ createdByTurnId: "turn-1",+ metadata: { kind: "subagent", name: "research" },+ taskId: "task-1",+ taskInboxToken: "task-token",+ taskRunId: "task-run",+ },+ ],+ version: 2,+ },+ },+ } as never);+ vi.mocked(readLatestTaskView).mockResolvedValue({+ metadata: { kind: "subagent", name: "research" },+ status: "working",+ taskId: "task-1",+ });++ await expect(+ dispatchTaskAgentInvocationStep({+ ownerId: "task-1",+ replyTo: "agent-reply",+ request: {+ input: { message: "Find it", target: "research" },+ invocationId: "call-1",+ kind: "agent-invoke",+ },+ serializedContext: { "eve.auth": receiverAuth },+ sessionState: { sessionId: "parent" } as never,+ taskId: "task-1",+ }),+ ).resolves.toMatchObject({+ kind: "failed",+ result: {+ isError: true,+ output: { code: "AGENT_INVOCATION_AUTH_UNAVAILABLE" },+ },+ });+ expect(prepareOwnerAgentInvocation).not.toHaveBeenCalled();+ });+it("starts a fresh agent with task-owned handle semantics", async () => {const reserved = {callId: "call-1",diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.ts b/packages/eve/src/execution/tools/subagent/invoke-step.tsindex 98411159f..e7a96131b 100644--- a/packages/eve/src/execution/tools/subagent/invoke-step.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-step.ts@@ -56,6 +56,13 @@ import {flushAgentInvocationTraces,settleAgentInvocationTrace,} from "#tracing/agent-invocation-terminal.js";+import {+ AuthKey,+ InitiatorAuthKey,+ SessionDynamicSubagentSelectionsKey,+ TurnDynamicSubagentSelectionsKey,+} from "#context/keys.js";+import type { TaskAgentDispatchContext } from "#tasks/session-index.js";export type AgentInvocationDispatchResult =| {@@ -86,6 +93,8 @@ export async function dispatchAgentInvocation(input: {readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;readonly ownerId: string;+ /** Optional creator snapshot used only to prepare this invocation. */+ readonly invocationContext?: Record<string, unknown>;readonly taskId?: string | undefined;}): Promise<AgentInvocationDispatchResult> {const durableSession = await readDurableSession(input.sessionState);@@ -94,7 +103,7 @@ export async function dispatchAgentInvocation(input: {invocation: input.request.input,invocationId: input.request.invocationId,knownAgentIds: agentHandles.map((handle) => handle.identity.id),- serializedContext: input.serializedContext,+ serializedContext: input.invocationContext ?? input.serializedContext,sessionState: input.sessionState,});const entry = prepared.plan[0];@@ -105,7 +114,7 @@ export async function dispatchAgentInvocation(input: {return {kind: "failed",result: entry.result,- serializedContext: prepared.serializedContext,+ serializedContext: input.serializedContext,sessionState: input.sessionState,};}@@ -114,7 +123,7 @@ export async function dispatchAgentInvocation(input: {conversation: prepared.inheritedConversation,invocation: invocationAction,ownerId: input.ownerId,- serializedContext: prepared.serializedContext,+ serializedContext: input.serializedContext,sessionId: prepared.session.sessionId,sessionState: durableSession.state,startTimeMs: Date.now(),@@ -334,6 +343,7 @@ export async function dispatchTaskAgentInvocationStep("use step";let activityWorkIdentity: ActivityWorkIdentityV1 | undefined;+ let taskDispatchContext: TaskAgentDispatchContext | undefined;if (input.taskId !== undefined) {const session = await readDurableSession(input.sessionState);const entry = findSessionTaskEntry(session.state, input.taskId);@@ -342,15 +352,63 @@ export async function dispatchTaskAgentInvocationStep(if (view === undefined || isTerminalTaskStatus(view.status)) {return { kind: "not-admitted", sessionState: input.sessionState };}+ if ("legacy" in entry.dispatchContext) {+ return missingTaskDispatchContext(input);+ }+ taskDispatchContext = entry.dispatchContext;if (entry.metadata.kind === "subagent") {activityWorkIdentity = entry.activityWorkIdentity;}}- return await dispatchAgentInvocation({+ const dispatched = await dispatchAgentInvocation({...input,activityWorkIdentity,callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),+ invocationContext:+ taskDispatchContext === undefined+ ? undefined+ : applyTaskDispatchContext(input.serializedContext, taskDispatchContext),});+ return dispatched;+}++function missingTaskDispatchContext(+ input: Parameters<typeof dispatchTaskAgentInvocationStep>[0],+): TaskAgentInvocationDispatchResult {+ return {+ kind: "failed",+ result: {+ callId: input.request.invocationId,+ isError: true,+ kind: "subagent-result",+ origin: "dispatch",+ output: {+ code: "AGENT_INVOCATION_AUTH_UNAVAILABLE",+ message: "The background task predates captured authentication context.",+ },+ subagentName: input.request.input.target,+ },+ sessionState: input.sessionState,+ };+}++function applyTaskDispatchContext(+ parent: Record<string, unknown>,+ task: TaskAgentDispatchContext,+): Record<string, unknown> {+ const context = {+ ...parent,+ [AuthKey.name]: task.auth.current,+ [InitiatorAuthKey.name]: task.auth.initiator,+ };+ for (const [key, value] of [+ [SessionDynamicSubagentSelectionsKey.name, task.sessionDynamicSubagentSelections],+ [TurnDynamicSubagentSelectionsKey.name, task.turnDynamicSubagentSelections],+ ] as const) {+ if (value === undefined) delete context[key];+ else context[key] = value;+ }+ return context;}/** Applies an owner-scoped child settlement to the parent session's canonical state. */diff --git a/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts b/packages/eve/src/execution/tools/subagent/task-agent-requests.test.tsindex c8dded0b3..f0b52b9e7 100644--- a/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts+++ b/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts@@ -65,7 +65,17 @@ describe("workflow-owned agent requests", () => {});it("retains existing context when replaying a dispatch result without tracing state", async () => {- const serializedContext = { "eve.test": "preserved" };+ const receiver = {+ attributes: {},+ authenticator: "test-idp",+ principalId: "receiver",+ principalType: "user",+ };+ const serializedContext = {+ "eve.auth": receiver,+ "eve.initiatorAuth": receiver,+ "eve.test": "preserved",+ };const event = { type: "subagent.called" } as never;vi.mocked(dispatchTaskAgentInvocationStep).mockResolvedValue({agentId: "child",diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 5b81604b0..c4eac6dd9 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -524,6 +524,7 @@ describe("routeProxiedDeliverStep", () => {{taskInboxToken: "task-token",createdByTurnId: "turn-parent",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "tool", name: "research" },taskId: "task-1",taskRunId: "run-1",@@ -672,6 +673,7 @@ describe("recordTaskInputRequestStep", () => {{taskInboxToken: "task-token",createdByTurnId: "turn-parent",+ dispatchContext: { auth: { current: null, initiator: null } },executor: {data: {address: {@@ -1240,6 +1242,7 @@ describe("turnStep", () => {const task = {createdByTurnId: "turn_0",+ dispatchContext: { auth: { current: null, initiator: null } },executor: { data: {}, kind: "workflow-tool" },metadata: { kind: "report", name: "daily_report" },taskId: "task_report",@@ -2651,6 +2654,7 @@ describe("turnStep", () => {{taskInboxToken: "task-token",createdByTurnId: "turn-parent",+ dispatchContext: { auth: { current: null, initiator: null } },metadata,taskId: "task_1",taskRunId: "run_1",@@ -2759,6 +2763,7 @@ describe("turnStep", () => {{createdByStepIndex: 0,createdByTurnId: "turn_0",+ dispatchContext: { auth: { current: null, initiator: null } },executor: { data: {}, kind: "workflow-tool" },metadata: { kind: "report-probe", name: "report_probe" },taskId: "task_1",diff --git a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.tsindex dc6c3bfb8..c1f016092 100644--- a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts+++ b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts@@ -878,6 +878,7 @@ describe("tool loop generate approval resume (real AI SDK)", () => {ctx.set(TurnTaskDeliveryKey, "initiating");session = recordSessionTask(session, {createdByTurnId: "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },executor: { data: {}, kind: "workflow-tool" },metadata: { kind: "report-probe", name: "analysis" },taskId: "analysis",diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 6fa27d0a0..75030b9a1 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -301,6 +301,7 @@ const analysisTaskAnnouncement =function recordBackgroundTask(session: HarnessSession, taskId = "analysis"): HarnessSession {return recordSessionTask(session, {createdByTurnId: activeTurnId(getHarnessEmissionState(session.state)),+ dispatchContext: { auth: { current: null, initiator: null } },executor: { data: {}, kind: "workflow-tool" },metadata: { kind: "report-probe", name: taskId },taskId,diff --git a/packages/eve/src/internal/testing/task-cancel-notification-workflow.ts b/packages/eve/src/internal/testing/task-cancel-notification-workflow.tsindex c51155a04..aaf7f2f0c 100644--- a/packages/eve/src/internal/testing/task-cancel-notification-workflow.ts+++ b/packages/eve/src/internal/testing/task-cancel-notification-workflow.ts@@ -39,6 +39,7 @@ export async function startSlowCancelledTaskStep(input: {await waitForCommandHookOwner(taskInboxToken);return {createdByTurnId: "turn_0",+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "tool", name: "slow-cancel" },taskId,taskInboxToken,diff --git a/packages/eve/src/tasks/delivery-context.test.ts b/packages/eve/src/tasks/delivery-context.test.tsindex 220bcdaf1..3c121d727 100644--- a/packages/eve/src/tasks/delivery-context.test.ts+++ b/packages/eve/src/tasks/delivery-context.test.ts@@ -208,6 +208,7 @@ function taskEntry(): SessionTaskIndexEntry {return {createdByTurnId,+ dispatchContext: { auth: { current: null, initiator: null } },executor,metadata,taskId,diff --git a/packages/eve/src/tasks/session-index.test.ts b/packages/eve/src/tasks/session-index.test.tsindex 5f55fd9fa..0db2dacdc 100644--- a/packages/eve/src/tasks/session-index.test.ts+++ b/packages/eve/src/tasks/session-index.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import type { HarnessSession } from "#harness/types.js";import {+ LEGACY_TASK_AGENT_DISPATCH_CONTEXT,SESSION_TASKS_STATE_KEY,cacheTerminalTaskView,findSessionTaskEntry,@@ -32,6 +33,7 @@ describe("session task index", () => {kind: "tool" as const,name: "research",};+ const dispatchContext = { auth: { current: null, initiator: null } } as const;it("returns an empty index when the key is absent", () => {expect(getSessionTaskIndex({})).toEqual([]);expect(getSessionTaskIndex(undefined)).toEqual([]);@@ -39,6 +41,7 @@ describe("session task index", () => {it("records a task and finds it by id", () => {const session = recordSessionTask(createSession(), {+ dispatchContext,taskInboxToken: "task:token-1",createdByTurnId: "turn-1",metadata,@@ -47,6 +50,7 @@ describe("session task index", () => {});expect(findSessionTaskEntry(session.state, "task_a")).toEqual({+ dispatchContext,taskInboxToken: "task:token-1",createdByTurnId: "turn-1",metadata,@@ -68,6 +72,7 @@ describe("session task index", () => {};const session = recordSessionTask(createSession(), {activityWorkIdentity,+ dispatchContext,taskInboxToken: "task:token-1",createdByTurnId: "turn-1",metadata,@@ -90,6 +95,7 @@ describe("session task index", () => {} as const;const session = recordSessionTask(createSession(), {+ dispatchContext,taskInboxToken: "task:token-1",createdByTurnId: "turn-1",metadata: subagentMetadata,@@ -112,6 +118,7 @@ describe("session task index", () => {rootSessionId: "root-session",rootTurnId: "root-turn",},+ dispatchContext,taskInboxToken: "task:token-1",createdByTurnId: "turn-1",metadata,@@ -133,6 +140,7 @@ describe("session task index", () => {rootSessionId: "root-session",rootTurnId: "root-turn",},+ dispatchContext,taskInboxToken: "task:token-2",createdByTurnId: "turn-1",metadata,@@ -148,6 +156,7 @@ describe("session task index", () => {it("replaces the entry on replayed creation instead of duplicating it", () => {let session = recordSessionTask(createSession(), {+ dispatchContext,taskInboxToken: "task:token-1",createdByTurnId: "turn-1",metadata,@@ -155,6 +164,7 @@ describe("session task index", () => {taskRunId: "run-1",});session = recordSessionTask(session, {+ dispatchContext,taskInboxToken: "task:token-2",createdByTurnId: "turn-1",metadata,@@ -171,6 +181,7 @@ describe("session task index", () => {return {createdByStepIndex: 0,createdByTurnId,+ dispatchContext,metadata,taskId,taskInboxToken: `inbox-${taskId}`,@@ -290,6 +301,7 @@ describe("session task index", () => {it("retains only terminal views as expired-run fallbacks", () => {const base = {+ dispatchContext,taskInboxToken: "task:token-1",createdByTurnId: "turn-1",metadata,@@ -348,6 +360,48 @@ describe("session task index", () => {).toThrow(`Corrupt task index under session state key "${SESSION_TASKS_STATE_KEY}"`);});+ it("normalizes a task without creator context to an explicit legacy state", () => {+ expect(+ getSessionTaskIndex({+ [SESSION_TASKS_STATE_KEY]: {+ tasks: [+ {+ createdByTurnId: "turn-1",+ metadata,+ taskId: "task_a",+ taskInboxToken: "task:token-1",+ taskRunId: "run-1",+ },+ ],+ version: 2,+ },+ })[0]?.dispatchContext,+ ).toEqual(LEGACY_TASK_AGENT_DISPATCH_CONTEXT);+ });++ it("rejects unrecognized task dispatch context fields", () => {+ expect(() =>+ getSessionTaskIndex({+ [SESSION_TASKS_STATE_KEY]: {+ tasks: [+ {+ createdByTurnId: "turn-1",+ dispatchContext: {+ auth: { current: null, initiator: null },+ unexpected: "receiver-context",+ },+ metadata,+ taskId: "task_a",+ taskInboxToken: "task:token-1",+ taskRunId: "run-1",+ },+ ],+ version: 2,+ },+ }),+ ).toThrow(`Corrupt task index under session state key "${SESSION_TASKS_STATE_KEY}"`);+ });+it("rejects the old task index version explicitly", () => {expect(() =>getSessionTaskIndex({ [SESSION_TASKS_STATE_KEY]: { tasks: [], version: 1 } }),diff --git a/packages/eve/src/tasks/session-index.ts b/packages/eve/src/tasks/session-index.tsindex fcab08ace..fb6112a4a 100644--- a/packages/eve/src/tasks/session-index.ts+++ b/packages/eve/src/tasks/session-index.ts@@ -5,6 +5,7 @@ import { parseActivityWorkIdentityV1, type ActivityWorkIdentityV1 } from "#protoimport type { JsonValue } from "#shared/json.js";import type { TaskExecutorBinding } from "#tools/task.js";import { sameTaskMetadata, type TaskMetadata, type TaskView } from "#tasks/types.js";+import { type DurableDynamicSubagentSelection, type SessionAuth } from "#context/keys.js";import {getTaskCohortId,SESSION_TASKS_STATE_KEY,@@ -33,6 +34,7 @@ export { SESSION_TASKS_STATE_KEY } from "#tasks/session-task-cohorts.js";*/export interface SessionTaskIndexEntry {readonly activityWorkIdentity?: ActivityWorkIdentityV1;+ readonly dispatchContext: SessionTaskDispatchContext;readonly taskId: string;readonly taskRunId: string;/** Immutable fallback once the owning workflow run expires. */@@ -51,6 +53,47 @@ const taskMetadataSchema = z.looseObject({name: z.string().min(1),}) as z.ZodType<TaskMetadata>;+export interface TaskAgentDispatchContext {+ readonly auth: SessionAuth;+ readonly sessionDynamicSubagentSelections?: Readonly<+ Record<string, DurableDynamicSubagentSelection>+ >;+ readonly turnDynamicSubagentSelections?: Readonly<+ Record<string, DurableDynamicSubagentSelection>+ >;+}++export const LEGACY_TASK_AGENT_DISPATCH_CONTEXT = { legacy: true } as const;+export type SessionTaskDispatchContext =+ | TaskAgentDispatchContext+ | typeof LEGACY_TASK_AGENT_DISPATCH_CONTEXT;++const sessionAuthContextSchema = z.strictObject({+ attributes: z.record(z.string(), z.union([z.string(), z.array(z.string()).readonly()])),+ authenticator: z.string(),+ issuer: z.string().optional(),+ principalId: z.string(),+ principalType: z.string(),+ subject: z.string().optional(),+});+const dynamicSubagentSelectionsSchema = z.record(+ z.string(),+ z.custom<DurableDynamicSubagentSelection>(),+);++const taskAgentDispatchContextSchema: z.ZodType<TaskAgentDispatchContext> = z.strictObject({+ auth: z.strictObject({+ current: sessionAuthContextSchema.nullable(),+ initiator: sessionAuthContextSchema.nullable(),+ }),+ sessionDynamicSubagentSelections: dynamicSubagentSelectionsSchema.optional(),+ turnDynamicSubagentSelections: dynamicSubagentSelectionsSchema.optional(),+});+const sessionTaskDispatchContextSchema = z.union([+ taskAgentDispatchContextSchema,+ z.strictObject({ legacy: z.literal(true) }),+]);+const taskViewBaseShape = {executor: z.strictObject({@@ -94,7 +137,7 @@ const taskViewSchema: z.ZodType<TaskView> = z.discriminatedUnion("status", [z.strictObject({ ...taskViewBaseShape, status: z.literal("cancelled") }),]);-const sessionTaskIndexEntrySchema: z.ZodType<SessionTaskIndexEntry> = z.strictObject({+const storedSessionTaskIndexEntrySchema = z.strictObject({activityWorkIdentity: z.custom<ActivityWorkIdentityV1>((value) => parseActivityWorkIdentityV1(value) !== undefined).optional(),@@ -102,6 +145,7 @@ const sessionTaskIndexEntrySchema: z.ZodType<SessionTaskIndexEntry> = z.strictObcreatedByStepIndex: z.number().int().nonnegative().optional(),createdByTurnId: z.string().min(1),cohortId: z.string().min(1).optional(),+ dispatchContext: sessionTaskDispatchContextSchema.optional(),executor: z.strictObject({data: z.record(z.string(), z.custom<JsonValue>()),@@ -116,7 +160,7 @@ const sessionTaskIndexEntrySchema: z.ZodType<SessionTaskIndexEntry> = z.strictObconst sessionTaskIndexSchema = z.strictObject({- tasks: z.array(sessionTaskIndexEntrySchema),+ tasks: z.array(storedSessionTaskIndexEntrySchema),version: z.literal(SESSION_TASKS_STATE_VERSION),}).refine(@@ -166,7 +210,10 @@ export function getSessionTaskIndex(`Corrupt task index under session state key "${SESSION_TASKS_STATE_KEY}": ${parsed.error.message}`,);}- return parsed.data.tasks;+ return parsed.data.tasks.map((entry): SessionTaskIndexEntry => ({+ ...entry,+ dispatchContext: entry.dispatchContext ?? LEGACY_TASK_AGENT_DISPATCH_CONTEXT,+ }));}/** Caches one terminal view beside its task-run address. */@@ -232,6 +279,7 @@ export function recordSessionTask(cohortId: previous.cohortId,createdByStepIndex: previous.createdByStepIndex,createdByTurnId: previous.createdByTurnId,+ dispatchContext: previous.dispatchContext,terminalView: previous.terminalView ?? entry.terminalView,};} else {diff --git a/packages/eve/src/tasks/session-task-cohorts.test.ts b/packages/eve/src/tasks/session-task-cohorts.test.tsindex cce4e7779..9b3d375d0 100644--- a/packages/eve/src/tasks/session-task-cohorts.test.ts+++ b/packages/eve/src/tasks/session-task-cohorts.test.ts@@ -18,6 +18,7 @@ describe("workflow task cohort lookup", () => {taskRunId: `run-${index}`,taskInboxToken: `inbox-${index}`,createdByTurnId,+ dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "subagent", name: "worker" },})),},diff --git a/packages/eve/src/tracing/agent-trace-retention.test.ts b/packages/eve/src/tracing/agent-trace-retention.test.tsindex 002635554..0ac13e487 100644--- a/packages/eve/src/tracing/agent-trace-retention.test.ts+++ b/packages/eve/src/tracing/agent-trace-retention.test.ts@@ -64,6 +64,7 @@ describe("trace retention by live work", () => {new ContextAgentTraceStateStore().setActionAnchor("key", anchor),);const task = {+ dispatchContext: { auth: { current: null, initiator: null } },taskId: deriveTaskId({ callId: "call", parentSessionId: "session", parentTurnId: "turn" }),taskRunId: "task-run",taskInboxToken: "task-token",