Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): forward caller identity on agent continuation (#2338)

Ruib57c9659adf4
diff --git a/.changeset/calm-owls-forward-auth.md b/.changeset/calm-owls-forward-auth.md
new file mode 100644
index 000000000..b597d64f0
--- /dev/null
+++ b/.changeset/calm-owls-forward-auth.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Forward the active caller on persistent local and remote subagent continuations so user-scoped connections resolve for the current turn without inheriting the previous caller's authority. Upgrade both remote-agent deployments before resuming existing persistent sessions; create-only receivers reject forwarded continuations rather than falling back to service authority.
diff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.md
index 5b6453176..ee7ebe28a 100644
--- a/docs/guides/auth-and-route-protection.md
+++ b/docs/guides/auth-and-route-protection.md
@@ -223,7 +223,7 @@ Keep secret values (`ROUTE_AUTH_BASIC_PASSWORD`, signing keys) in environment va
## Accepting forwarded identity from another deployment
-A `defineRemoteAgent({ forwardPrincipal: true })` caller (see [Remote agents](./remote-agents#forwarding-the-caller-identity)) asserts its end user's principal on the create-session request as a `forwardedPrincipal` body field. By default every such assertion is rejected with `403` — accepting someone else's word for who the user is requires naming exactly which forwarders you trust. Do that with `trustedForwarders` on `eveChannel`:
+A `defineRemoteAgent({ forwardPrincipal: true })` caller (see [Remote agents](./remote-agents#forwarding-the-caller-identity)) asserts its end user's principal on create and continuation requests as a `forwardedPrincipal` body field. By default every such assertion is rejected with `403` — accepting someone else's word for who the user is requires naming exactly which forwarders you trust. Do that with `trustedForwarders` on `eveChannel`:
```ts title="agent/channels/eve.ts"
import { eveChannel } from "eve/channels/eve";
@@ -239,7 +239,11 @@ export default eveChannel({
The predicate authorizes the _forwarder_ (the verified route-auth principal — who is asserting), not the forwarded principal (what is asserted). Match it precisely: a permissive predicate like `() => true` lets any caller that passes route auth assert any principal, including preview deployments of your own project when `vercelOidc()` is in the walk. `trustedForwarders` exists only on your authored channel — the framework default channel never accepts a forwarded principal, so a receiving deployment must author `agent/channels/eve.ts`.
-When the predicate accepts, the forwarded principal replaces the session principal: `ctx.session.auth.current` and `.initiator` carry the forwarded user exactly as if they had called your deployment directly, so user-scoped connections, local subagents, and further `forwardPrincipal` hops all see that user. The forwarder is recorded on the accepted contexts as the `eve:forwarded-by` attribute (always overwritten by the receiver, so a forwarder cannot falsify it). Rejections fail loud: a forwarded body without `trustedForwarders` configured or with a forwarder the predicate refuses is a `403`, and a malformed payload is a `400`. Only principal metadata is ever accepted — tokens and credentials never cross the hop.
+When the predicate accepts a create request, `ctx.session.auth.current` and `.initiator` carry the forwarded user exactly as if they had called your deployment directly. On continuation, only `auth.current` is replaced; `auth.initiator` remains the session creator. User-scoped connections, local subagents, and further `forwardPrincipal` hops therefore see the active turn's caller. The forwarder is recorded on accepted contexts as the `eve:forwarded-by` attribute (always overwritten by the receiver, so a forwarder cannot falsify it). Rejections fail loud: a forwarded body without `trustedForwarders` configured or with a forwarder the predicate refuses is a `403`, and a malformed payload is a `400`. Only principal metadata is ever accepted — tokens and credentials never cross the hop.
+
+> ⚠️ Both deployments must support continuation forwarding before you resume persistent remote sessions. A create-only receiver rejects a forwarded continuation with HTTP 400; the sender does not fall back to service authority. See [Forwarding the caller identity](./remote-agents#forwarding-the-caller-identity) for the upgrade behavior.
+
+Persistent sessions do not preserve caller authority between turns. Every accepted follow-up replaces `auth.current`, including replacing it with no authenticated caller on internal local delivery; per-user connection lookup is then keyed from that current principal. This prevents a later caller from resolving a prior caller's OAuth grant. It does not hide the persistent session's conversation history or artifacts from a caller who is otherwise allowed to continue that session; session ownership remains an application policy.
## What reaches `ctx.session.auth`
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index 0166b5b72..3291ff8fe 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -114,9 +114,17 @@ export default defineRemoteAgent({
});
```
-The create-session request then carries the parent turn's `session.auth.current` and `session.auth.initiator` as a `forwardedPrincipal` body field (`initiator` is optional on the wire; when absent, the receiver seeds both from `current`). Only principal metadata crosses the wire — never tokens or credentials. The receiving deployment mints its own per-user credentials through its own connections.
+The create-session request carries the parent turn's `session.auth.current` and `session.auth.initiator` as a `forwardedPrincipal` body field (`initiator` is optional on the wire; when absent, the receiver seeds both from `current`). Every continuation carries only that turn's `session.auth.current`; the remote session keeps its original `auth.initiator`. Only principal metadata crosses the wire — never tokens or credentials. The receiving deployment resolves its own per-user credentials through its own connections.
-Forwarding is explicit on both sides. The receiver names which forwarders it trusts with `eveChannel({ trustedForwarders })` (see [Auth & route protection](./auth-and-route-protection#accepting-forwarded-identity-from-another-deployment)); a receiver that refuses the forwarder — or has no `trustedForwarders` at all — rejects with a 403 and the dispatch fails. One caveat: a receiver on an eve version that predates principal forwarding drops the unknown field and runs the session as your app's service identity (per-user connections there fail with `principal_required`), so upgrade both deployments together when enabling forwarding. When the dispatching turn has no auth at all, the field is omitted and the call proceeds on transport trust alone.
+This makes caller authority turn-scoped even when the remote child session is persistent. If Alice starts the child and Bob later continues it, the follow-up runs with Bob as `auth.current`, not Alice. If the parent turn's auth is `null`, a local child clears `auth.current`, while a remote child uses the freshly verified transport principal; neither inherits Alice. eve's in-step bearer cache is also keyed by the resolved principal and is not serialized across steps. The external authorization provider may preserve each user's server-side OAuth grant, but a later turn can resolve only the grant belonging to its own `auth.current` principal.
+
+Identity forwarding does not make a persistent session private to one caller. Conversation history, tool outputs, and other child-session state still persist. If those values must not be visible across users, give each user a distinct child session or enforce that ownership at the application boundary.
+
+Forwarding is explicit on both sides. The receiver names which forwarders it trusts with `eveChannel({ trustedForwarders })` (see [Auth & route protection](./auth-and-route-protection#accepting-forwarded-identity-from-another-deployment)); a receiver that refuses the forwarder — or has no `trustedForwarders` at all — rejects with a 403 and the dispatch fails.
+
+> ⚠️ **Upgrade both deployments before resuming persistent remote sessions.** A sender with continuation forwarding includes `forwardedPrincipal` on each authenticated follow-up. A receiver that supports forwarding only on session creation rejects that continuation with HTTP 400. eve does not retry without the field because that would run the follow-up as the transport service principal and silently change caller authority. The parent retains the child handle after this failure, so you can retry the same session after upgrading the receiver.
+
+A receiver on an eve version that predates all principal forwarding may instead drop the unknown field and run the session as your app's service identity; per-user connections there fail with `principal_required`. On remote requests where the dispatching turn has no auth, the field is omitted and the call proceeds on transport trust alone.
## How remote dispatch and callbacks work
diff --git a/e2e/fixtures/agent-subagents/agent/channels/eve.ts b/e2e/fixtures/agent-subagents/agent/channels/eve.ts
index e9dd7f5ef..1f69976cb 100644
--- a/e2e/fixtures/agent-subagents/agent/channels/eve.ts
+++ b/e2e/fixtures/agent-subagents/agent/channels/eve.ts
@@ -3,21 +3,21 @@ import { eveChannel } from "eve/channels/eve";
import type { SessionAuthContext } from "eve/context";
/**
- * Authored eve channel for the remote principal-forwarding eval. Three
+ * Authored eve channel for the remote principal-forwarding eval. Four
* deterministic principals, no injected env (the deployment is deliberately
* open — fixture-only; do not pattern production channels off this):
*
* - The `remote-loopback` hop authenticates with a fixed bearer and runs as
* the `router-app` service principal — the trusted forwarder.
- * - A second fixed bearer authenticates as a distinct end user, so the eval
- * can continue a session as a different caller and prove the current and
- * initiator principals cross the hop independently.
+ * - Bob and the observer each have a fixed bearer, so the eval can continue
+ * Alice's child as two distinct callers. Bob has his own user grant; the
+ * observer deliberately has none.
* - Every other caller (the local eval driver is anonymous; the Vercel one
- * may carry ambient OIDC) falls through to a fixed `user` principal, so
- * the parent session always has an end-user identity to forward.
+ * may carry ambient OIDC) falls through to Alice's fixed user principal.
*/
const ROUTER_AUTHORIZATION = "Bearer e2e-principal-forwarding-router";
-const SECOND_USER_AUTHORIZATION = "Bearer e2e-principal-forwarding-second-user";
+const BOB_AUTHORIZATION = "Bearer e2e-principal-forwarding-bob";
+const OBSERVER_AUTHORIZATION = "Bearer e2e-principal-forwarding-observer";
function createFixtureUserPrincipal(principalId: string): SessionAuthContext {
return {
@@ -40,14 +40,19 @@ const authenticateRouter: AuthFn<Request> = (request) => {
};
};
-const authenticateSecondUser: AuthFn<Request> = (request) => {
- if (request.headers.get("authorization") !== SECOND_USER_AUTHORIZATION) return null;
+const authenticateBob: AuthFn<Request> = (request) => {
+ if (request.headers.get("authorization") !== BOB_AUTHORIZATION) return null;
return createFixtureUserPrincipal("e2e-user-2");
};
+const authenticateObserver: AuthFn<Request> = (request) => {
+ if (request.headers.get("authorization") !== OBSERVER_AUTHORIZATION) return null;
+ return createFixtureUserPrincipal("e2e-observer");
+};
+
const authenticateDefaultUser: AuthFn<Request> = () => createFixtureUserPrincipal("e2e-user");
export default eveChannel({
- auth: [authenticateRouter, authenticateSecondUser, authenticateDefaultUser],
+ auth: [authenticateRouter, authenticateBob, authenticateObserver, authenticateDefaultUser],
trustedForwarders: (forwarder) => forwarder.principalId === "router-app",
});
diff --git a/e2e/fixtures/agent-subagents/agent/tools/read-private-data.ts b/e2e/fixtures/agent-subagents/agent/tools/read-private-data.ts
new file mode 100644
index 000000000..16640c979
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/agent/tools/read-private-data.ts
@@ -0,0 +1,37 @@
+import type { NonInteractiveAuthorizationDefinition } from "eve/connections";
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+const privateDataByGrant: Readonly<Record<string, string>> = {
+ "grant:alice": "ALICE_PRIVATE_DM_7K4M",
+ "grant:bob": "BOB_PRIVATE_DM_9P2R",
+};
+
+const grantByPrincipal: Readonly<Record<string, string>> = {
+ "e2e-user": "grant:alice",
+ "e2e-user-2": "grant:bob",
+};
+
+// Models a provider-side grant store: eve selects the principal, while the
+// provider returns only that principal's bearer.
+const userGrant: NonInteractiveAuthorizationDefinition = {
+ principalType: "user",
+ async getToken({ principal }) {
+ if (principal.type !== "user") throw new Error("A user grant is required.");
+ const token = grantByPrincipal[principal.id];
+ if (token === undefined) throw new Error(`No OAuth grant exists for ${principal.id}.`);
+ return { token };
+ },
+};
+
+export default defineTool({
+ description:
+ "Reads private data using the current caller's user-scoped grant. Call only when explicitly requested.",
+ inputSchema: z.object({}),
+ async execute(_input, ctx) {
+ const grant = await ctx.getToken(userGrant, { authKey: "private-data" });
+ const privateData = privateDataByGrant[grant.token];
+ if (privateData === undefined) throw new Error("No private data exists for this grant.");
+ return { privateData };
+ },
+});
diff --git a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts
index 65b37797b..72f2dd249 100644
--- a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts
@@ -1,42 +1,92 @@
-import { defineEval } from "eve/evals";
+import { defineEval, type EveEvalTurn } from "eve/evals";
-/**
- * Principal forwarding across a real remote-agent hop, end to end. The
- * fixture deployment plays both sides: `remote-loopback` dynamically selects
- * a `defineRemoteAgent({ forwardPrincipal: true })` pointing back at this
- * deployment, whose authored eve channel trusts principals only from the
- * hop's `router-app` bearer (`trustedForwarders`).
- *
- * Two turns give the parent session *distinct* principals: turn one starts
- * the session as the fixed `user:e2e-user` (pinning it as the initiator),
- * turn two continues it as `user:e2e-user-2` via the second fixture bearer
- * and dispatches the hop. The child session's `whoami` marker can therefore
- * only show `current=e2e-user-2 initiator=e2e-user` — with
- * `forwarded-by=router-app`, the receiver-stamped audit attribute — if both
- * principals crossed the wire independently, the gate accepted the
- * forwarder, and the replacement reached the child runtime. Without
- * forwarding the child would report the transport caller,
- * `service:router-app`, for both.
- */
-const FORWARDED_MARKER =
- "WHOAMI current=user:e2e-user-2 initiator=user:e2e-user forwarded-by=router-app";
+const ALICE_PRIVATE_DATA = "ALICE_PRIVATE_DM_7K4M";
+const BOB_PRIVATE_DATA = "BOB_PRIVATE_DM_9P2R";
+const BOB_AUTHORIZATION = "Bearer e2e-principal-forwarding-bob";
+const OBSERVER_AUTHORIZATION = "Bearer e2e-principal-forwarding-observer";
+const CHILD_MESSAGE = [
+ "[forward-auth:child] Call read-private-data exactly once.",
+ "If it succeeds, reply with only its privateData value.",
+ "If it fails, reply with only ACCESS_DENIED.",
+].join(" ");
+const CREATE_CHILD_MESSAGE = [
+ "[forward-auth:create] Use remote-loopback exactly once with this message:",
+ JSON.stringify(CHILD_MESSAGE),
+ "Reply with only the child's output.",
+].join(" ");
+const CONTINUE_CHILD_MESSAGE = [
+ "[forward-auth:continue] Continue that same remote-loopback agent using its agentId with this message:",
+ JSON.stringify(CHILD_MESSAGE),
+ "Reply with only the child's output.",
+].join(" ");
+function requireRemoteChild(parentTurn: EveEvalTurn, expectedSessionId?: string): string {
+ const call = parentTurn.events.find(
+ (event) => event.type === "subagent.called" && event.data.name === "remote-loopback",
+ );
+ if (call?.type !== "subagent.called") {
+ throw new Error("The parent turn did not call remote-loopback.");
+ }
+ if (expectedSessionId !== undefined && call.data.childSessionId !== expectedSessionId) {
+ throw new Error("The parent turn did not continue the existing remote child.");
+ }
+ return call.data.childSessionId;
+}
+
+/** Three users resume one remote child; each tool call resolves only its current caller's grant. */
export default defineEval({
- tags: ["real-model"],
+ tags: ["principal-forwarding", "real-model"],
description:
- "Dynamic remote-agent selection and principal forwarding: the child session runs as the parent's end user, with the distinct initiator preserved and the forwarder stamped.",
+ "A persistent remote child switches between two user grants and denies a third caller with none.",
async test(t) {
- await t.send("Reply with the single word: ready.");
+ // Alice creates the child and reads with her own grant.
+ const aliceParent = await t.send(CREATE_CHILD_MESSAGE);
+ const childSessionId = requireRemoteChild(aliceParent);
+ const aliceChild = await t.target.watchTurn(childSessionId).result();
+ let childEventCount = aliceChild.events.length;
- await t.send(
- "Use the remote-loopback agent with this exact message and nothing else (no outputSchema): 'Run the whoami tool and reply with only its marker string, verbatim.' When it returns, reply with the agent's exact output included verbatim.",
- { headers: { authorization: "Bearer e2e-principal-forwarding-second-user" } },
- );
+ // Bob continues the same child and must resolve Bob's grant, not Alice's.
+ const bobParent = await t.send(CONTINUE_CHILD_MESSAGE, {
+ headers: { authorization: BOB_AUTHORIZATION },
+ });
+ requireRemoteChild(bobParent, childSessionId);
+ const bobChild = await t.target
+ .watchTurn(childSessionId, { startIndex: childEventCount })
+ .result();
+ childEventCount += bobChild.events.length;
- t.succeeded();
- t.calledSubagent("remote-loopback", {
- output: /WHOAMI current=user:e2e-user-2 initiator=user:e2e-user forwarded-by=router-app/,
+ // A grantless observer continues it once more. Reusing either prior bearer
+ // would complete this call; correct per-turn scoping makes it fail.
+ const observerParent = await t.send(CONTINUE_CHILD_MESSAGE, {
+ headers: { authorization: OBSERVER_AUTHORIZATION },
+ });
+ requireRemoteChild(observerParent, childSessionId);
+ const observerChild = await t.target
+ .watchTurn(childSessionId, { startIndex: childEventCount })
+ .result();
+
+ aliceChild.calledTool("read-private-data", {
+ count: 1,
+ output: { privateData: ALICE_PRIVATE_DATA },
+ status: "completed",
});
- t.messageIncludes(FORWARDED_MARKER);
+ bobChild.calledTool("read-private-data", {
+ count: 1,
+ output: { privateData: BOB_PRIVATE_DATA },
+ status: "completed",
+ });
+ observerChild.calledTool("read-private-data", { count: 1, status: "failed" });
+ observerChild.calledTool("read-private-data", { count: 0, status: "completed" });
+ observerChild.event("action.result", {
+ count: 1,
+ data: {
+ error: { message: /No OAuth grant exists for e2e-observer/ },
+ result: { kind: "tool-result", toolName: "read-private-data" },
+ status: "failed",
+ },
+ });
+
+ t.calledSubagent("remote-loopback", { count: 3 });
+ t.succeeded();
},
});
diff --git a/packages/eve/src/channel/forwarded-principal.ts b/packages/eve/src/channel/forwarded-principal.ts
index 6751b46ac..a09c4c56c 100644
--- a/packages/eve/src/channel/forwarded-principal.ts
+++ b/packages/eve/src/channel/forwarded-principal.ts
@@ -15,7 +15,7 @@ const log = createLogger("channel.forwarded-principal");
export const FORWARDED_BY_ATTRIBUTE = "eve:forwarded-by";
/**
- * Wire shape of the create-session `forwardedPrincipal` body field: the
+ * Wire shape of the session-request `forwardedPrincipal` body field: the
* dispatching turn's session principals, asserted by a trusted forwarder.
* Only principal metadata crosses the wire — never tokens or credentials.
*/
@@ -43,7 +43,7 @@ export type ForwardedPrincipalParseResult =
};
/**
- * The create route's effective session principals after the forwarded
+ * A session route's effective principals after the forwarded
* principal gate: the transport principal untouched when the body carries no
* assertion, or the stamped forwarded contexts once a trusted forwarder's
* assertion is accepted.
@@ -85,7 +85,7 @@ const forwardedPrincipalSchema = z
.strict();
/**
- * Gates the create-session `forwardedPrincipal` body field and resolves the
+ * Gates the `forwardedPrincipal` body field and resolves the
* effective session principals. Returns the failure `Response` on rejection:
* 403 when the channel accepts no forwarded principal or the predicate
* refuses the forwarder, 400 on a malformed payload, 500 when the authored
@@ -141,7 +141,7 @@ export async function resolveForwardedPrincipal(input: {
}
/**
- * Parses the create-session `forwardedPrincipal` body field against the
+ * Parses the `forwardedPrincipal` body field against the
* strict wire schema. Mirrors `parseSessionCallback` for `callback`: strict
* keys, formatted error strings, and no exceptions.
*/
diff --git a/packages/eve/src/execution/agent-handle-dispatch.ts b/packages/eve/src/execution/agent-handle-dispatch.ts
index 472c19fc5..be7beb776 100644
--- a/packages/eve/src/execution/agent-handle-dispatch.ts
+++ b/packages/eve/src/execution/agent-handle-dispatch.ts
@@ -8,6 +8,7 @@
* dead (handle deleted) or retryable (handle restored to `parked`).
*/
+import type { SessionAuthContext } from "#channel/types.js";
import { AGENT_BUSY, AGENT_MISMATCH, AGENT_UNREACHABLE } from "#harness/agent-handle-errors.js";
import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
import {
@@ -102,6 +103,7 @@ export type DispatchOutcome =
export async function dispatchToAgentHandle(input: {
readonly action: RuntimeAgentHandleAction;
readonly agentId: string;
+ readonly auth: SessionAuthContext | null;
readonly bundle: CompiledBundle;
readonly currentSession: RuntimeSession;
readonly parentToken: string;
@@ -180,6 +182,7 @@ export async function dispatchToAgentHandle(input: {
const delivery = await deliverToAgentAddress({
action,
address: handle.address,
+ auth: input.auth,
bundle,
identity: handle.identity,
parentToken: input.parentToken,
@@ -227,6 +230,7 @@ export async function dispatchToAgentHandle(input: {
export async function dispatchToTaskAgentAddress(input: {
readonly action: RuntimeAgentHandleAction;
readonly agentId: string;
+ readonly auth: SessionAuthContext | null;
readonly bundle: CompiledBundle;
readonly currentSession: RuntimeSession;
readonly parentToken: string;
@@ -264,6 +268,7 @@ export async function dispatchToTaskAgentAddress(input: {
const delivery = await deliverToAgentAddress({
action,
address: record.address,
+ auth: input.auth,
bundle: input.bundle,
identity: record.identity,
parentToken: input.parentToken,
@@ -316,6 +321,7 @@ export async function dispatchToTaskAgentAddress(input: {
async function deliverToAgentAddress(input: {
readonly action: RuntimeAgentHandleAction;
readonly address: AgentAddress;
+ readonly auth: SessionAuthContext | null;
readonly bundle: CompiledBundle;
readonly identity: AgentIdentity;
readonly parentToken: string;
@@ -342,6 +348,7 @@ async function deliverToAgentAddress(input: {
}
try {
await continueRemoteAgentSession({
+ auth: input.auth,
callback: {
callId: action.callId,
subagentName: identity.name,
@@ -374,6 +381,7 @@ async function deliverToAgentAddress(input: {
try {
const result = await childRuntime.dispatchSession({
command: {
+ auth: input.auth,
caller: {
callId: action.callId,
replyTo: { kind: "hook", token: input.parentToken },
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
index 1cd1f12d9..9072747c1 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ChannelAdapter } from "#channel/adapter.js";
+import type { SessionAuthContext } from "#channel/types.js";
import { ContextContainer, loadContext } from "#context/container.js";
import { RemoteAgentContinueRequestError } from "#execution/remote-agent-dispatch.js";
import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
@@ -101,6 +102,14 @@ const BASE_STATE: DurableSessionState = {
version: 1,
};
const CHILD_SESSION_ID = "child-session-123456789012";
+const TURN_AUTH: SessionAuthContext = {
+ attributes: { user_id: "U456" },
+ authenticator: "slack-webhook",
+ issuer: "slack",
+ principalId: "slack:U456",
+ principalType: "user",
+ subject: "U456",
+};
const PARKED_START_OPERATION_ID = deriveAgentOperationId({
callId: "call-0",
@@ -747,6 +756,38 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {
expect(mocks.startWorkflowPreferLatest).not.toHaveBeenCalled();
});
+ it("passes the active turn principal to a tasks-mode continuation", async () => {
+ const addressedHandle: AgentHandle = {
+ address: LOCAL_PARKED_HANDLE.address,
+ identity: LOCAL_PARKED_HANDLE.identity,
+ phase: "addressed",
+ };
+ const session = createPendingSession({
+ handle: addressedHandle,
+ agentId: addressedHandle.identity.id,
+ });
+ installContext(session, undefined, true, TURN_AUTH);
+
+ const result = await dispatchTaskStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(mocks.dispatchSession).toHaveBeenCalledWith({
+ command: expect.objectContaining({
+ auth: TURN_AUTH,
+ kind: "send",
+ }),
+ sessionId: CHILD_SESSION_ID,
+ });
+ expect(result.results[0]).toMatchObject({
+ origin: "child",
+ output: { agentId: addressedHandle.identity.id, status: "working" },
+ });
+ });
+
const continueOperationId = deriveAgentOperationId({
callId: "call-1",
parentSessionId: "parent-session",
@@ -777,6 +818,7 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {
subagentName: "research",
},
kind: "send",
+ auth: null,
payload: {
message: "continue with raw input",
outputSchema: undefined,
@@ -959,10 +1001,15 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {
handle: REMOTE_PARKED_HANDLE,
agentId: REMOTE_PARKED_HANDLE.identity.id,
});
- installContext(session, {
- definition: REMOTE_REGISTRY_DEFINITION,
- nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,
- });
+ installContext(
+ session,
+ {
+ definition: REMOTE_REGISTRY_DEFINITION,
+ nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,
+ },
+ false,
+ TURN_AUTH,
+ );
mocks.continueRemoteAgentSession.mockRejectedValue(
new RemoteAgentContinueRequestError(
"continue-session request failed permanently with HTTP 404.",
@@ -979,6 +1026,7 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {
expect(mocks.continueRemoteAgentSession).toHaveBeenCalledWith(
expect.objectContaining({
+ auth: TURN_AUTH,
message: "continue with raw input",
remote: expect.objectContaining({
nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,
@@ -1171,6 +1219,7 @@ function installContext(
session: HarnessSession,
remote?: { readonly definition: unknown; readonly nodeId: string },
tasks = false,
+ auth: SessionAuthContext | null = null,
): void {
const subagentsByNodeId = new Map<string, { definition: unknown }>();
if (remote !== undefined) {
@@ -1190,7 +1239,7 @@ function installContext(
},
};
const values = new Map<unknown, unknown>([
- [AuthKey, null],
+ [AuthKey, auth],
[BundleKey, bundle],
[CapabilitiesKey, undefined],
[ChannelInstrumentationKey, undefined],
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index 0227b410d..8a3ee9474 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -68,6 +68,7 @@ export async function dispatchRuntimeActionsStep(
outcome = await dispatchToAgentHandle({
action: entry.action,
agentId: entry.agentId,
+ auth: prepared.auth,
bundle: createAgentContinuationBundle({
action: entry.action,
bundle,
diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.ts
index c667b27b1..c646ccb21 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts
@@ -674,6 +674,7 @@ describe("continueRemoteAgentSession", () => {
vi.stubGlobal("fetch", fetchMock);
await continueRemoteAgentSession({
+ auth: null,
callback: {
callId: "call-next",
subagentName: "research",
@@ -709,6 +710,67 @@ describe("continueRemoteAgentSession", () => {
);
});
+ it("forwards only the current turn principal when continuation forwarding is enabled", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+ const current: SessionAuthContext = {
+ attributes: { user_id: "U456" },
+ authenticator: "slack-webhook",
+ issuer: "slack",
+ principalId: "slack:U456",
+ principalType: "user",
+ subject: "U456",
+ };
+
+ await continueRemoteAgentSession({
+ auth: current,
+ callback: {
+ callId: "call-next",
+ subagentName: "research",
+ token: "parent-inbox",
+ url: "https://caller.example.com/eve/v1/callback/parent-inbox",
+ },
+ message: "follow up",
+ remote: { ...createRemoteAgent(), forwardPrincipal: true },
+ sessionId: "remote-session",
+ });
+
+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).forwardedPrincipal).toEqual({
+ current,
+ });
+ });
+
+ it("suggests receiver version skew without making a forwarded continuation permanent", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 400 })));
+ const current: SessionAuthContext = {
+ attributes: { user_id: "U456" },
+ authenticator: "slack-webhook",
+ issuer: "slack",
+ principalId: "slack:U456",
+ principalType: "user",
+ subject: "U456",
+ };
+
+ const error = await continueRemoteAgentSession({
+ auth: current,
+ callback: {
+ callId: "call-next",
+ subagentName: "research",
+ token: "parent-inbox",
+ url: "https://caller.example.com/eve/v1/callback/parent-inbox",
+ },
+ message: "follow up",
+ remote: { ...createRemoteAgent(), forwardPrincipal: true },
+ sessionId: "remote-session",
+ }).catch((cause: unknown) => cause);
+
+ expect(error).toMatchObject({
+ message:
+ 'Remote agent "research" continue-session request failed with HTTP 400. The receiver may support forwarded principals only on session creation; upgrade it before retrying.',
+ });
+ expect(isRetryableRemoteAgentContinueError(error)).toBe(true);
+ });
+
it("classifies only missing-session continue failures as permanent", async () => {
const fetchMock = vi
.fn()
@@ -721,6 +783,7 @@ describe("continueRemoteAgentSession", () => {
vi.stubGlobal("fetch", fetchMock);
const continueInput = () => ({
+ auth: null,
callback: {
callId: "call-next",
subagentName: "research",
diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.ts
index b544e8f83..269428806 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.ts
@@ -165,6 +165,8 @@ export async function startRemoteAgentSession(input: {
/** Continues one remote-agent session by its immutable session ID. */
export async function continueRemoteAgentSession(input: {
+ /** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */
+ readonly auth: SessionAuthContext | null;
readonly callback: {
readonly callId: string;
readonly subagentName: string;
@@ -177,12 +179,23 @@ export async function continueRemoteAgentSession(input: {
readonly remote: ResolvedRuntimeRemoteAgentNode;
readonly sessionId: string;
}): Promise<void> {
+ const forwardedPrincipal = buildForwardedPrincipalField(input);
+ const requestBody: {
+ callback: typeof input.callback;
+ forwardedPrincipal?: ForwardedPrincipal;
+ message: string;
+ outputSchema?: JsonObject;
+ } = {
+ callback: input.callback,
+ message: input.message,
+ outputSchema: input.outputSchema,
+ };
+ if (forwardedPrincipal !== undefined) {
+ requestBody.forwardedPrincipal = forwardedPrincipal;
+ }
+
const response = await fetch(createRemoteAgentContinueUrl(input.remote, input.sessionId), {
- body: JSON.stringify({
- callback: input.callback,
- message: input.message,
- outputSchema: input.outputSchema,
- }),
+ body: JSON.stringify(requestBody),
headers: {
"content-type": "application/json",
...(await resolveRemoteAgentRequestHeaders(input.remote)),
@@ -194,10 +207,14 @@ export async function continueRemoteAgentSession(input: {
const responseCode = await readRemoteAgentErrorCode(response);
const permanent =
response.status === 404 || responseCode === AgentHandleError.SessionNotResumable.code;
+ const compatibilityHint =
+ response.status === 400 && forwardedPrincipal !== undefined
+ ? " The receiver may support forwarded principals only on session creation; upgrade it before retrying."
+ : "";
throw new RemoteAgentContinueRequestError(
`Remote agent "${input.remote.name}" continue-session request failed${
permanent ? " permanently" : ""
- } with HTTP ${response.status}.`,
+ } with HTTP ${response.status}.${compatibilityHint}`,
{
deliveryAmbiguous: isAmbiguousRemoteContinueStatus(response.status),
retryable: !permanent,
diff --git a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
index 1616fb917..9fda6c9da 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
@@ -134,6 +134,7 @@ export async function dispatchTaskStep(
outcome = await dispatchToTaskAgentAddress({
action: entry.action,
agentId: entry.agentId,
+ auth: prepared.auth,
bundle: createAgentContinuationBundle({
action: entry.action,
bundle,
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index a3661fb30..bfb6f9dcc 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -2,7 +2,11 @@ import type { ModelMessage } from "ai";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ChannelAdapter, ChannelAdapterContext } from "#channel/adapter.js";
-import type { DeliverPayload, SubagentInputRequestHookPayload } from "#channel/types.js";
+import type {
+ DeliverPayload,
+ SessionAuthContext,
+ SubagentInputRequestHookPayload,
+} from "#channel/types.js";
import { ContextContainer, contextStorage, loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import {
@@ -1567,6 +1571,76 @@ describe("turnStep", () => {
expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE) ?? []).toEqual([]);
});
+ it.each([
+ {
+ expected: {
+ attributes: { user_id: "U456" },
+ authenticator: "slack-webhook",
+ issuer: "slack",
+ principalId: "slack:U456",
+ principalType: "user",
+ subject: "U456",
+ } satisfies SessionAuthContext,
+ title: "replaces the previous caller",
+ },
+ { expected: null, title: "clears the previous caller" },
+ ])("$title from deliver-time auth", async ({ expected }) => {
+ const bundle = {
+ adapterRegistry: {
+ adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
+ },
+ compiledArtifactsSource: {} as never,
+ graph: {
+ nodesByNodeId: new Map(),
+ root: {
+ sandboxRegistry: { sandbox: null },
+ turnAgent: TestTurnAgent,
+ },
+ },
+ moduleMap: { nodes: {} },
+ hookRegistry: createEmptyHookRegistry(),
+ resolvedAgent: { config: {} },
+ subagentRegistry: {},
+ toolRegistry: {},
+ turnAgent: TestTurnAgent,
+ } as never;
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(bundle);
+ installSessionStoreMocks([createStubSession()]);
+
+ const previous: SessionAuthContext = {
+ attributes: { user_id: "U123" },
+ authenticator: "slack-webhook",
+ issuer: "slack",
+ principalId: "slack:U123",
+ principalType: "user",
+ subject: "U123",
+ };
+ const ctx = new ContextContainer();
+ ctx.set(AuthKey, previous);
+ ctx.set(BundleKey, bundle);
+ ctx.set(ChannelKey, threadContextAdapter);
+ ctx.set(ContinuationTokenKey, "http:auth-replacement");
+ ctx.set(ModeKey, "conversation");
+ ctx.set(SessionIdKey, "session-1");
+
+ let observed: SessionAuthContext | null | undefined;
+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {
+ return async (session): Promise<StepResult> => {
+ observed = loadContext().get(AuthKey);
+ return { next: null, session };
+ };
+ });
+
+ await turnStep({
+ input: { auth: expected, kind: "deliver", payloads: [{ message: "follow up" }] },
+ parentWritable: createTestWritable(),
+ serializedContext: serializeContext(ctx),
+ sessionState: createStubSessionState(),
+ });
+
+ expect(observed).toEqual(expected);
+ });
+
it("routes remote task HITL only to the parent callback", async () => {
const inputRequested = vi.fn();
const remoteTaskAdapter: ChannelAdapter = {
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index cfde014cc..9616a07c5 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -2165,12 +2165,49 @@ describe("eveChannel — forwarded principal", () => {
expect(options.initiatorAuth).toBeUndefined();
});
- it("rejects forwarded principal on the continue route", async () => {
+ it("replaces only the current principal on a trusted continuation", async () => {
+ const onMessage = vi.fn((ctx: Parameters<typeof defaultEveAuth>[0]) => ({
+ auth: defaultEveAuth(ctx),
+ }));
const handler = createEveContinueHandler({
- trustedForwarders: () => true,
auth: () => ROUTER_CALLER,
+ onMessage,
+ trustedForwarders: (forwarder) => forwarder.principalId === ROUTER_CALLER.principalId,
});
+ const response = await handler.fetch(
+ new Request("https://example.com/eve/v1/session/test-session-id", {
+ body: JSON.stringify({
+ forwardedPrincipal: {
+ current: FORWARDED_CURRENT,
+ initiator: FORWARDED_INITIATOR,
+ },
+ message: "hi",
+ }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ }),
+ );
+
+ expect(response.status).toBe(202);
+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;
+ expect(options.auth).toEqual({
+ ...FORWARDED_CURRENT,
+ attributes: {
+ ...FORWARDED_CURRENT.attributes,
+ "eve:forwarded-by": ROUTER_CALLER.principalId,
+ },
+ });
+ expect(options.initiatorAuth).toBeUndefined();
+ expect(onMessage).toHaveBeenCalledOnce();
+ expect(onMessage.mock.calls[0]?.[0].eve.caller?.principalId).toBe(
+ FORWARDED_CURRENT.principalId,
+ );
+ });
+
+ it("rejects a forwarded continuation when the channel has no trustedForwarders", async () => {
+ const handler = createEveContinueHandler({ auth: () => ROUTER_CALLER });
+
const response = await handler.fetch(
new Request("https://example.com/eve/v1/session/test-session-id", {
body: JSON.stringify({
@@ -2182,11 +2219,7 @@ describe("eveChannel — forwarded principal", () => {
}),
);
- expect(response.status).toBe(400);
+ expect(response.status).toBe(403);
expect(handler.send).not.toHaveBeenCalled();
- await expect(response.json()).resolves.toMatchObject({
- error: "A forwarded principal is only accepted on session creation.",
- ok: false,
- });
});
});
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index 1d39ac680..ce38d0c69 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -155,7 +155,7 @@ export interface EveChannelInput {
readonly auth: AuthFn<Request> | readonly AuthFn<Request>[];
/**
* The trusted-forwarders policy: which transport-authenticated callers may
- * assert a forwarded principal on the create-session route (the
+ * assert a forwarded principal on the create-session or continuation route (the
* `forwardedPrincipal` body field a `defineRemoteAgent({ forwardPrincipal:
* true })` sender emits). The predicate receives the *verified* route-auth
* principal of the forwarder — who is asserting, never what is asserted —
@@ -164,12 +164,12 @@ export interface EveChannelInput {
* A permissive predicate lets any authenticated forwarder assert any
* principal.
*
- * When a trusted forwarder's assertion is accepted, the forwarded
- * principal replaces the session principal (`session.auth.current` /
- * `session.auth.initiator`) exactly as if that user had called this
- * deployment directly, and the forwarder is recorded on the accepted
- * contexts as the `eve:forwarded-by` attribute. Omit the option to reject
- * every forwarded assertion with 403.
+ * When a trusted forwarder's assertion is accepted on session creation, the
+ * forwarded principal replaces `session.auth.current` and
+ * `session.auth.initiator`. On continuation, only `session.auth.current`
+ * changes; the initiator remains pinned to the session's creator. The
+ * forwarder is recorded on accepted contexts as the `eve:forwarded-by`
+ * attribute. Omit the option to reject every forwarded assertion with 403.
*/
readonly trustedForwarders?: TrustedForwarders;
/**
@@ -370,6 +370,12 @@ export function eveChannel(input: EveChannelInput): EveChannel {
if (sessionId instanceof Response) return sessionId;
const payload = await parseJsonRequest(req);
if (payload instanceof Response) return payload;
+ const forwarded = await resolveForwardedPrincipal({
+ trustedForwarders: input.trustedForwarders,
+ forwarder: authResult,
+ payload,
+ });
+ if (forwarded instanceof Response) return forwarded;
const body = parseSessionMessageBody(payload);
if (body instanceof Response) return body;
@@ -377,10 +383,10 @@ export function eveChannel(input: EveChannelInput): EveChannel {
if (policyRejection !== null) return policyRejection;
let context = body.context;
- let dispatchAuth: SessionAuthContext | null = authResult;
+ let dispatchAuth: SessionAuthContext | null = forwarded.auth;
if (body.message !== undefined) {
const messageResult = await resolveOnMessage({
- auth: authResult,
+ auth: forwarded.auth,
config: input,
message: body.message,
request: req,
@@ -909,12 +915,6 @@ function parseSessionMessageBody(
): ParsedSessionMessageBody | Response {
const tokenRejection = rejectSessionContinuationToken(payload);
if (tokenRejection !== null) return tokenRejection;
- if (payload.forwardedPrincipal !== undefined) {
- return Response.json(
- { error: "A forwarded principal is only accepted on session creation.", ok: false },
- { status: 400 },
- );
- }
const message = parseMessageField(payload.message);
if (message instanceof Response) return message;
diff --git a/packages/eve/src/public/definitions/remote-agent.ts b/packages/eve/src/public/definitions/remote-agent.ts
index de6993e48..6d08675df 100644
--- a/packages/eve/src/public/definitions/remote-agent.ts
+++ b/packages/eve/src/public/definitions/remote-agent.ts
@@ -24,11 +24,13 @@ export interface RemoteAgentDefinition {
readonly description: string;
/**
* Forwards the dispatching turn's session principal to the remote
- * deployment as the `forwardedPrincipal` create-session body field, so the
- * remote session runs as the same end user as the parent (per-user
- * Connect, local subagents, and further remote hops all see that
- * principal). Defaults to `false` — forwarding identity to another
- * deployment is an explicit decision, never ambient.
+ * deployment as the `forwardedPrincipal` session-request body field, so
+ * each remote turn runs as the same end user as the parent (per-user
+ * Connect, local subagents, and further remote hops all see that active
+ * principal). Session creation forwards current and initiator identity;
+ * continuation forwards only the active caller and leaves the remote
+ * session's initiator pinned. Defaults to `false` — forwarding identity to
+ * another deployment is an explicit decision, never ambient.
*
* Only principal metadata crosses the wire, never tokens or credentials —
* {@link auth} keeps authenticating *this* deployment to the remote. The
diff --git a/research/remote-agent-auth-forwarding.md b/research/remote-agent-auth-forwarding.md
index 02cee7284..1caf5482c 100644
--- a/research/remote-agent-auth-forwarding.md
+++ b/research/remote-agent-auth-forwarding.md
@@ -1,7 +1,7 @@
---
issue: https://github.com/vercel/eve/issues/604
status: implemented
-last_updated: "2026-07-23"
+last_updated: "2026-08-20"
---
# Forwarding end-user identity across remote agent hops
@@ -27,6 +27,11 @@ is "trusted forwarder": the route's `auth` authenticates the asserting deploymen
the receiver authorizes forwarding with a predicate over that verified transport principal — the
same shape as `X-Forwarded-*` behind a trusted proxy, without token-exchange machinery.
+Persistent remote children also accept continuation requests. Those requests must forward the
+active parent turn's principal through the same trust gate: otherwise the child sees only the
+calling deployment's service identity and per-user connections fail. A continuation replaces
+only `auth.current`; `auth.initiator` remains pinned to the principal that created the child.
+
```text
Slack user U ── router deployment ──────────────► site-ops deployment
auth.current = U POST /eve/v1/session
@@ -60,9 +65,9 @@ export default defineRemoteAgent({
- `forwardPrincipal?: boolean`, default `false`. Forwarding identity to another deployment is an
explicit decision, never ambient.
-- When `true`, dispatch serializes the parent turn's `AuthKey` / `InitiatorAuthKey` (already in
- scope in `dispatch-runtime-actions-step.ts`) into a `forwardedPrincipal` field on the create-session
- body: `{ current: SessionAuthContext, initiator?: SessionAuthContext }`.
+- When `true`, creation serializes the parent turn's `AuthKey` / `InitiatorAuthKey` into a
+ `forwardedPrincipal` field: `{ current: SessionAuthContext, initiator?: SessionAuthContext }`.
+ Continuation serializes only the active `AuthKey`: `{ current: SessionAuthContext }`.
- The field is omitted only when `AuthKey` is `null` (the request was accepted with no
credentials); the call then proceeds on transport trust alone. Any non-null context is forwarded as-is — including anonymous
(`principalType: "anonymous"` from `none()`), schedule (`SCHEDULE_APP_AUTH`), and service
@@ -106,12 +111,18 @@ export default eveChannel({
## Semantics
-- **Accepted forwarding replaces the session principal.** `session.auth.current` = forwarded
- `current`; `session.auth.initiator` = forwarded `initiator` ?? forwarded `current`. Both seed
- `RunInput.auth` / `RunInput.initiatorAuth` exactly as if the user had called the deployment
- directly. Everything downstream works unchanged: `resolveConnectionPrincipal` sees
- `principalType: "user"` (per-user Connect resolves), local subagents inherit the principal, and
- a further `forwardPrincipal: true` remote hop chains the same identity onward.
+- **Accepted forwarding replaces the active session principal.** On creation,
+ `session.auth.current` = forwarded `current` and `session.auth.initiator` = forwarded
+ `initiator` ?? forwarded `current`. On continuation, only `session.auth.current` changes;
+ `session.auth.initiator` remains pinned. Everything downstream works unchanged:
+ `resolveConnectionPrincipal` sees the active turn's user (per-user Connect resolves), local
+ subagents inherit that principal, and a further `forwardPrincipal: true` remote hop chains it.
+- **Caller authority is turn-scoped.** Local continuation always carries `SessionCommand.auth`,
+ including `null`, so a later unauthenticated turn clears rather than inherits the previous
+ caller. Remote continuation omits the assertion for `null` and the receiver uses its verified
+ transport principal. Connection bearer caches are keyed by principal and virtual to one step;
+ an upstream provider may retain each user's grant, but a turn can resolve only its current
+ principal's grant.
- **Audit trail is receiver-written.** The receiver records the transport caller on the accepted
contexts as attribute `eve:forwarded-by` = the _verified_ transport `principalId`, always
overwriting any sender-supplied value — a forwarder must not be able to falsify the trail. On
@@ -125,10 +136,14 @@ export default eveChannel({
- **Rejections fail loud.** A body carrying `forwardedPrincipal` when the channel has no
`trustedForwarders` option → 403 ("this deployment does not accept a forwarded
principal"). Predicate returns `false` → 403. Malformed `forwardedPrincipal` payload → 400. Each
- fails the sender's dispatch inline. The one case that does not fail at the hop is a receiver on
- an eve version that predates forwarding: it drops the unknown field and runs the session as the
- transport principal, surfacing as `principal_required` at per-user Connect (see the
- acknowledgment note under Out of scope).
+ fails the sender's dispatch inline.
+- **Mixed versions fail closed.** A receiver that supports forwarding only on session creation
+ rejects a forwarded continuation with HTTP 400. The sender must not retry without the field:
+ doing so would run the turn as the transport principal and silently change authority. The parent
+ preserves the child handle, so the same session can be retried after the receiver is upgraded. A
+ receiver that predates all principal forwarding may instead drop the unknown field and run as
+ the transport principal, surfacing as `principal_required` at per-user Connect. Deploy both
+ sides before resuming persistent remote sessions.
- **What never crosses the wire:** tokens, credentials, claims. Only the `SessionAuthContext`
shape (`attributes`, `authenticator`, `issuer`, `principalId`, `principalType`, `subject`).
Per-user provider credentials always live on the receiving deployment via its own Connect
@@ -139,14 +154,15 @@ export default eveChannel({
## Boundaries and surfaces
-| Surface | Change |
-| -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
-| `public/definitions/remote-agent.ts` | `forwardPrincipal?: boolean` |
-| `execution/dispatch-runtime-actions-step.ts` | pass `auth` / `initiatorAuth` (already in scope) to remote dispatch |
-| `execution/remote-agent-dispatch.ts` | build `forwardedPrincipal` body field |
-| `channel/forwarded-principal.ts` (new) | strict wire schema for `{ current, initiator? }` (open `authenticator` / `principalType`), beside `session-callback.ts` |
-| `public/channels/eve.ts` | `trustedForwarders` option; forwarded-principal gate + principal replacement on the create route |
-| `docs/guides/remote-agents.md`, `docs/guides/auth-and-route-protection.md` | forwarding section on each side + trust-model warning |
+| Surface | Change |
+| ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
+| `public/definitions/remote-agent.ts` | `forwardPrincipal?: boolean` |
+| `execution/dispatch-runtime-actions-step.ts` | pass `auth` / `initiatorAuth` (already in scope) to remote dispatch |
+| `execution/tasks/parent/dispatch-task-step.ts`, `execution/agent-handle-dispatch.ts` | pass active `auth` through persistent local and remote continuation |
+| `execution/remote-agent-dispatch.ts` | build `forwardedPrincipal` body field |
+| `channel/forwarded-principal.ts` (new) | strict wire schema for `{ current, initiator? }` (open `authenticator` / `principalType`), beside `session-callback.ts` |
+| `public/channels/eve.ts` | `trustedForwarders` option; forwarded-principal gate + principal replacement on create and continuation routes |
+| `docs/guides/remote-agents.md`, `docs/guides/auth-and-route-protection.md` | forwarding section on each side + trust-model warning |
Docs must carry the security guidance explicitly: match the transport principal precisely (e.g.
`subject === vercelSubject({ teamSlug, projectName })`); a permissive predicate (`() => true`)
@@ -167,16 +183,14 @@ channel has no `trustedForwarders`, so a receiving deployment must author its ow
- Per-call forwarding decisions (the flag is per remote-agent definition).
- Reduced-scope or transformed principals (an `onMessage` override on the receiver already covers
reshaping).
-- Forwarding on the deliver route (`POST /eve/v1/session/:sessionId`). Remote dispatch is
- create-only today, so nothing in eve would send it; the same field + predicate can extend to
- deliver if external eve clients need multi-turn forwarding later.
+- Cross-principal visibility of persistent child history, tool outputs, and artifacts. Principal
+ forwarding selects the active turn's credential authority; applications that require private
+ history must key child sessions by principal or enforce a same-principal ownership policy.
- A response acknowledgment (`forwardedPrincipal: "accepted"` on the 202) letting the sender
- detect a pre-forwarding receiver that silently drops the unknown body field. Considered and
- dropped: forwarding only ever works after the receiver's author adds
- `trustedForwarders` — which requires a forwarding-aware eve — so a stale receiver is
- always an incomplete setup, caught during enablement when per-user Connect fails
- `principal_required`. Permanent wire surface (plus best-effort orphan-session cancellation on a
- missing ack) was not justified by a transitional, pre-1.0 skew window.
+ detect a receiver that cannot apply the assertion. Considered and dropped: create-only receivers
+ already reject forwarded continuations, the sender preserves the child handle for a retry after
+ upgrade, and deployment docs make the coordinated-upgrade requirement explicit. Permanent wire
+ surface was not justified by a transitional, pre-1.0 skew window.
## Delivery and verification
@@ -188,10 +202,13 @@ Single PR with a **patch** changeset: both options are additive; no public API b
without option → 403, predicate false → 403, predicate true → principal replaced,
`eve:forwarded-by` stamped from the verified transport principal and sender-supplied values
overwritten, stamping visible to `onMessage`).
+- Unit/integration: continuation sends only active `current` when forwarding is enabled; the
+ receiver applies the same trust gate, changes only `auth.current`, and local delivery replaces
+ or clears the previous turn's `AuthKey`. Cover both persistent-session and tasks dispatch.
- Integration: create route end-to-end in memory — forwarded principal becomes
`session.auth.current` / `.initiator` and reaches `resolveConnectionPrincipal` as a `user`
principal.
-- Scenario: two in-process eve servers over real HTTP — router with `forwardPrincipal: true` dispatches
- to a receiver whose `trustedForwarders` predicate accepts it, asserting the child session
- principal; plus the 403 mismatch path. (No remote-agent e2e fixture exists today; a scenario
- with a real HTTP boundary covers the hop without requiring a second CI deployment.)
+- E2E: the `agent-subagents` loopback remote runs through a real HTTP hop. One parent turn creates
+ the child as user A; a second, user-B-authenticated turn continues the same `childSessionId`.
+ The child reports `auth.current` as B, keeps A as `auth.initiator`, and carries the
+ receiver-written `eve:forwarded-by` attribute on both turns.