The Open Framework for Building Agents
feat(eve): forward end-user identity across remote agent hops (#608)
Andrew Barbaad0dfa7cc071
diff --git a/.changeset/remote-agent-auth-forwarding.md b/.changeset/remote-agent-auth-forwarding.mdnew file mode 100644index 000000000..ddc645ed3--- /dev/null+++ b/.changeset/remote-agent-auth-forwarding.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Remote agents can now forward the end user's identity across deployments. `defineRemoteAgent({ forwardPrincipal: true })` sends the dispatching turn's session principal (metadata only — never tokens) on the create-session request, and the receiving deployment opts in with `eveChannel({ trustedForwarders })`, a predicate over the verified transport forwarder. Accepted forwarding replaces the session principal so per-user connections, local subagents, and chained remote hops see the original user; a receiver that refuses the forwarder (or accepts no forwarded principal) rejects with 403 and the dispatch fails instead of silently downgrading to the calling service's identity.diff --git a/.changeset/remote-agent-empty-output-schema.md b/.changeset/remote-agent-empty-output-schema.mdnew file mode 100644index 000000000..d971ed3d4--- /dev/null+++ b/.changeset/remote-agent-empty-output-schema.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Remote agent dispatch now ignores an empty `outputSchema` (`{}`) passed by the model on the lowered subagent tool call, matching local subagent dispatch. An empty schema constrains nothing, but forwarding it flipped the remote child into structured-output mode and replaced its text reply with `{}`.diff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.mdindex eb502b198..461636996 100644--- a/docs/guides/auth-and-route-protection.md+++ b/docs/guides/auth-and-route-protection.md@@ -220,6 +220,26 @@ You do not have to keep `vercelOidc()` in the final policy. For a self-hosted apKeep secret values (`ROUTE_AUTH_BASIC_PASSWORD`, signing keys) in environment variables. Route-auth secrets never land in compiled artifacts. The runtime re-materializes them from the authored channel definition at boot.+## 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`:++```ts title="agent/channels/eve.ts"+import { eveChannel } from "eve/channels/eve";+import { vercelOidc, vercelSubject } from "eve/channels/auth";++export default eveChannel({+ auth: [vercelOidc()],+ // Only the router deployment may assert a forwarded principal.+ trustedForwarders: (forwarder) =>+ forwarder.subject === vercelSubject({ teamSlug: "acme", projectName: "router" }),+});+```++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.+## What reaches `ctx.session.auth`Inside runtime code, `ctx.session.auth` carries the result of the channel's route auth (the walk above) forward as the caller snapshot:diff --git a/docs/guides/client/overview.mdx b/docs/guides/client/overview.mdxindex fa1255171..fcef19d5b 100644--- a/docs/guides/client/overview.mdx+++ b/docs/guides/client/overview.mdx@@ -108,6 +108,8 @@ const response = await session.send({await response.result();```+Per-request headers override client-level values with the same name. For example, a turn can set its application user's `Authorization` header while `vercelOidc` continues to send the deployment-protection credential in `x-vercel-trusted-oidc-idp-token`.+## SessionsCreate a `ClientSession` for each conversation:diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.mdindex 2d8e103c5..8f876c7cc 100644--- a/docs/guides/remote-agents.md+++ b/docs/guides/remote-agents.md@@ -20,14 +20,15 @@ export default defineRemoteAgent({`defineRemoteAgent` accepts:-| Parameter | Type | Required | Default | Description |-| -------------- | --------------------------------------------- | -------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `url` | `string \| (() => string \| Promise<string>)` | Yes | n/a | Base URL of the remote eve deployment to call. A string is baked at compile time; a function is resolved at runtime (see [Runtime URLs](#runtime-urls)). |-| `description` | `string` | Yes | n/a | Model-visible delegation description. |-| `auth` | `OutboundAuthFn` | No | none | Outbound auth hook from `eve/agents/auth`. |-| `headers` | `HeadersValue` | No | none | Static or lazily resolved request headers. |-| `path` | `string` | No | `/eve/v1/session` | Route appended to `url` for the create-session request. |-| `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type the caller requires. Lowered to JSON Schema at compile time and enforced by the remote like any task-mode output schema. |+| Parameter | Type | Required | Default | Description |+| ------------------ | --------------------------------------------- | -------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `url` | `string \| (() => string \| Promise<string>)` | Yes | n/a | Base URL of the remote eve deployment to call. A string is baked at compile time; a function is resolved at runtime (see [Runtime URLs](#runtime-urls)). |+| `description` | `string` | Yes | n/a | Model-visible delegation description. |+| `auth` | `OutboundAuthFn` | No | none | Outbound auth hook from `eve/agents/auth`. |+| `forwardPrincipal` | `boolean` | No | `false` | Forward the dispatching turn's session principal to the remote deployment (see [Forwarding the caller identity](#forwarding-the-caller-identity)). |+| `headers` | `HeadersValue` | No | none | Static or lazily resolved request headers. |+| `path` | `string` | No | `/eve/v1/session` | Route appended to `url` for the create-session request. |+| `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type the caller requires. Lowered to JSON Schema at compile time and enforced by the remote like any task-mode output schema. |## Runtime URLs@@ -60,6 +61,28 @@ A remote agent lowers to the same `{ message, outputSchema? }` tool shape as a lIf you are calling another Vercel-deployed eve agent, reach for `vercelOidc()`. The remote verifies the OIDC token to authorize the caller. See [Auth & route protection](./auth-and-route-protection) for the receiving side.+## Forwarding the caller identity++Outbound auth authenticates your _deployment_ to the remote, so by default the remote session runs as your calling app — not as the end user who is talking to your agent. That breaks per-user workloads on the remote deployment, most directly per-user [Vercel Connect](./auth-and-route-protection#tool-and-connection-auth), which requires an authenticated `user` principal on the session.++Set `forwardPrincipal: true` to forward the dispatching turn's session principal across the hop:++```ts title="agent/subagents/site-ops.ts"+import { defineRemoteAgent } from "eve";+import { vercelOidc } from "eve/agents/auth";++export default defineRemoteAgent({+ url: "https://site-ops.example.com",+ description: "Executes site operations as the requesting user.",+ auth: vercelOidc(), // transport trust: authenticates *this* deployment+ forwardPrincipal: true, // identity: asserts the current session principal+});+```++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.++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.+## How remote dispatch and callbacks workA local subagent runs inline. A remote one runs in its own deployment, so dispatch is asynchronous:diff --git a/e2e/fixtures/agent-subagents/agent/channels/eve.ts b/e2e/fixtures/agent-subagents/agent/channels/eve.tsnew file mode 100644index 000000000..e9dd7f5ef--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/channels/eve.ts@@ -0,0 +1,53 @@+import type { AuthFn } from "eve/channels/auth";+import { eveChannel } from "eve/channels/eve";+import type { SessionAuthContext } from "eve/context";++/**+ * Authored eve channel for the remote principal-forwarding eval. Three+ * 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.+ * - 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.+ */+const ROUTER_AUTHORIZATION = "Bearer e2e-principal-forwarding-router";+const SECOND_USER_AUTHORIZATION = "Bearer e2e-principal-forwarding-second-user";++function createFixtureUserPrincipal(principalId: string): SessionAuthContext {+ return {+ attributes: {},+ authenticator: "e2e-fixture",+ issuer: "e2e",+ principalId,+ principalType: "user",+ subject: principalId,+ };+}++const authenticateRouter: AuthFn<Request> = (request) => {+ if (request.headers.get("authorization") !== ROUTER_AUTHORIZATION) return null;+ return {+ attributes: {},+ authenticator: "e2e-bearer",+ principalId: "router-app",+ principalType: "service",+ };+};++const authenticateSecondUser: AuthFn<Request> = (request) => {+ if (request.headers.get("authorization") !== SECOND_USER_AUTHORIZATION) return null;+ return createFixtureUserPrincipal("e2e-user-2");+};++const authenticateDefaultUser: AuthFn<Request> = () => createFixtureUserPrincipal("e2e-user");++export default eveChannel({+ auth: [authenticateRouter, authenticateSecondUser, authenticateDefaultUser],+ trustedForwarders: (forwarder) => forwarder.principalId === "router-app",+});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts b/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.tsnew file mode 100644index 000000000..49ce3e624--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts@@ -0,0 +1,33 @@+import { defineRemoteAgent } from "eve";++/**+ * A remote agent pointing back at this same deployment, so one fixture plays+ * both sides of a `forwardPrincipal` hop: the create-session request leaves+ * over real HTTP carrying the parent turn's principal and lands on this+ * deployment's eve channel, whose `trustedForwarders` trusts exactly the+ * bearer this definition sends (see `agent/channels/eve.ts`).+ *+ * The URL resolves at runtime to the deployment's own address: `VERCEL_URL`+ * on Vercel, or the dev server's self-published origin locally.+ */+export default defineRemoteAgent({+ description:+ "Remote loopback agent. Call this only when the user explicitly asks to use the remote-loopback agent, passing the user's requested message through unchanged. Call it with only the `message` argument — never pass `outputSchema`.",+ url: () =>+ process.env.VERCEL_URL !== undefined && process.env.VERCEL_URL !== ""+ ? `https://${process.env.VERCEL_URL}`+ : (process.env.WORKFLOW_LOCAL_BASE_URL ?? "http://127.0.0.1:3000"),+ headers: () => {+ const headers: Record<string, string> = {+ authorization: "Bearer e2e-principal-forwarding-router",+ };+ // Preview deployments behind Vercel deployment protection need the+ // bypass header on the self-call; harmless when protection is off.+ const bypass = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;+ if (bypass !== undefined && bypass !== "") {+ headers["x-vercel-protection-bypass"] = bypass;+ }+ return headers;+ },+ forwardPrincipal: true,+});diff --git a/e2e/fixtures/agent-subagents/agent/tools/whoami.ts b/e2e/fixtures/agent-subagents/agent/tools/whoami.tsnew file mode 100644index 000000000..0ed6c105c--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/tools/whoami.ts@@ -0,0 +1,28 @@+import { defineTool } from "eve/tools";+import { z } from "zod";++/**+ * Reports the session principals as one deterministic marker string, so an+ * eval can grep a parent reply for exactly which identities a child session+ * ran under: the current (per-turn) principal, the initiator (session+ * origin) principal, and the receiver-stamped `eve:forwarded-by` audit+ * attribute a forwarded principal carries.+ */+export default defineTool({+ description:+ "Reports the current session principals as a single marker string. Only call this when explicitly asked to run the whoami tool.",+ inputSchema: z.object({}),+ async execute(_input, ctx) {+ const { current, initiator } = ctx.session.auth;+ const forwardedBy = current?.attributes["eve:forwarded-by"] ?? "none";+ return {+ marker: `WHOAMI current=${formatPrincipal(current)} initiator=${formatPrincipal(initiator)} forwarded-by=${String(forwardedBy)}`,+ };+ },+});++function formatPrincipal(+ context: { readonly principalId: string; readonly principalType: string } | null,+): string {+ return context === null ? "none" : `${context.principalType}:${context.principalId}`;+}diff --git a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.tsnew file mode 100644index 000000000..0b100e469--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts@@ -0,0 +1,42 @@+import { defineEval } from "eve/evals";++/**+ * Principal forwarding across a real remote-agent hop, end to end. The+ * fixture deployment plays both sides: `remote-loopback` is 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";++export default defineEval({+ description:+ "Remote-agent principal forwarding: the child session runs as the parent's end user, with the distinct initiator preserved and the forwarder stamped.",+ async test(t) {+ await t.send("Reply with the single word: ready.");++ await t.send({+ headers: { authorization: "Bearer e2e-principal-forwarding-second-user" },+ message:+ "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.",+ });++ t.succeeded();+ t.calledSubagent("remote-loopback", {+ output: /WHOAMI current=user:e2e-user-2 initiator=user:e2e-user forwarded-by=router-app/,+ });+ t.messageIncludes(FORWARDED_MARKER);+ },+});diff --git a/packages/eve/src/channel/forwarded-principal.test.ts b/packages/eve/src/channel/forwarded-principal.test.tsnew file mode 100644index 000000000..40866f0bd--- /dev/null+++ b/packages/eve/src/channel/forwarded-principal.test.ts@@ -0,0 +1,166 @@+import { describe, expect, it } from "vitest";++import {+ FORWARDED_BY_ATTRIBUTE,+ parseForwardedPrincipal,+ stampForwardedBy,+} from "#channel/forwarded-principal.js";+import type { SessionAuthContext } from "#channel/types.js";++function slackUser(overrides: Partial<SessionAuthContext> = {}): SessionAuthContext {+ return {+ attributes: { user_id: "U123" },+ authenticator: "slack-webhook",+ issuer: "slack",+ principalId: "slack:U123",+ principalType: "user",+ subject: "U123",+ ...overrides,+ };+}++describe("parseForwardedPrincipal", () => {+ it("accepts a current-only payload", () => {+ const result = parseForwardedPrincipal({ current: slackUser() });++ expect(result).toEqual({ forwardedPrincipal: { current: slackUser() }, ok: true });+ });++ it("accepts a payload with a distinct initiator", () => {+ const initiator = slackUser({ principalId: "slack:U999", subject: "U999" });+ const result = parseForwardedPrincipal({ current: slackUser(), initiator });++ expect(result).toEqual({+ forwardedPrincipal: { current: slackUser(), initiator },+ ok: true,+ });+ });++ it("keeps authenticator and principalType open for channel-produced contexts", () => {+ // The flagship use case: a Slack-authenticated user forwarded by a router+ // deployment. The wire schema must not mirror the runtime enum schema.+ const result = parseForwardedPrincipal({+ current: {+ attributes: {},+ authenticator: "twilio-webhook",+ principalId: "whatsapp:+15550001111",+ principalType: "anonymous",+ },+ });++ expect(result.ok).toBe(true);+ });++ it("accepts string-array attribute values", () => {+ const result = parseForwardedPrincipal({+ current: slackUser({ attributes: { groups: ["eng", "ops"], team: "T1" } }),+ });++ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.forwardedPrincipal.current.attributes).toEqual({+ groups: ["eng", "ops"],+ team: "T1",+ });+ }+ });++ it("omits absent optional fields instead of writing undefined", () => {+ const result = parseForwardedPrincipal({+ current: {+ attributes: {},+ authenticator: "jwt-hmac",+ principalId: "user-1",+ principalType: "user",+ },+ });++ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(Object.keys(result.forwardedPrincipal.current)).not.toContain("issuer");+ expect(Object.keys(result.forwardedPrincipal.current)).not.toContain("subject");+ }+ });++ it.each([+ ["a non-object", "forwarded"],+ ["null", null],+ ["an array", [slackUser()]],+ ])("rejects %s payload", (_label, value) => {+ const result = parseForwardedPrincipal(value);++ expect(result.ok).toBe(false);+ });++ it("rejects a payload without current", () => {+ const result = parseForwardedPrincipal({ initiator: slackUser() });++ expect(result).toMatchObject({+ message: expect.stringContaining("forwardedPrincipal.current"),+ ok: false,+ });+ });++ it("rejects unknown keys at the top level", () => {+ const result = parseForwardedPrincipal({ current: slackUser(), token: "secret" });++ expect(result).toMatchObject({+ message: expect.stringContaining("Invalid forwardedPrincipal metadata"),+ ok: false,+ });+ });++ it("rejects unknown keys inside a context", () => {+ const result = parseForwardedPrincipal({ current: { ...slackUser(), credential: "secret" } });++ expect(result).toMatchObject({+ message: expect.stringContaining("forwardedPrincipal.current"),+ ok: false,+ });+ });++ it("rejects an empty principalId", () => {+ const result = parseForwardedPrincipal({ current: slackUser({ principalId: "" }) });++ expect(result).toMatchObject({+ message: expect.stringContaining("forwardedPrincipal.current.principalId"),+ ok: false,+ });+ });++ it("rejects non-string attribute values", () => {+ const result = parseForwardedPrincipal({+ current: slackUser({ attributes: { count: 3 } as never }),+ });++ expect(result.ok).toBe(false);+ });+});++describe("stampForwardedBy", () => {+ it("records the transport caller as an attribute", () => {+ const stamped = stampForwardedBy(slackUser(), "router-app");++ expect(stamped.attributes[FORWARDED_BY_ATTRIBUTE]).toBe("router-app");+ expect(stamped.attributes.user_id).toBe("U123");+ expect(stamped.principalId).toBe("slack:U123");+ });++ it("overwrites a sender-supplied forwarded-by value", () => {+ const forged = slackUser({+ attributes: { [FORWARDED_BY_ATTRIBUTE]: "someone-else" },+ });++ const stamped = stampForwardedBy(forged, "router-app");++ expect(stamped.attributes[FORWARDED_BY_ATTRIBUTE]).toBe("router-app");+ });++ it("does not mutate the input context", () => {+ const original = slackUser();++ stampForwardedBy(original, "router-app");++ expect(original.attributes[FORWARDED_BY_ATTRIBUTE]).toBeUndefined();+ });+});diff --git a/packages/eve/src/channel/forwarded-principal.ts b/packages/eve/src/channel/forwarded-principal.tsnew file mode 100644index 000000000..6751b46ac--- /dev/null+++ b/packages/eve/src/channel/forwarded-principal.ts@@ -0,0 +1,212 @@+import { z } from "#compiled/zod/index.js";++import type { SessionAuthContext } from "#channel/types.js";+import { createLogger, logError } from "#internal/logging.js";++const log = createLogger("channel.forwarded-principal");++/**+ * Attribute key the receiving deployment stamps onto accepted forwarded+ * principal contexts. Holds the verified transport forwarder's `principalId`,+ * always overwriting any sender-supplied value — a forwarder must not be able+ * to falsify the audit trail. On multi-hop chains the attribute names the+ * most recent hop only.+ */+export const FORWARDED_BY_ATTRIBUTE = "eve:forwarded-by";++/**+ * Wire shape of the create-session `forwardedPrincipal` body field: the+ * dispatching turn's session principals, asserted by a trusted forwarder.+ * Only principal metadata crosses the wire — never tokens or credentials.+ */+export interface ForwardedPrincipal {+ readonly current: SessionAuthContext;+ readonly initiator?: SessionAuthContext;+}++/**+ * Authorizes which transport-authenticated forwarders may assert a forwarded+ * principal. Receives the *verified* route-auth principal (who is asserting),+ * never the forwarded identity (what is asserted).+ */+export type TrustedForwarders = (forwarder: SessionAuthContext) => boolean | Promise<boolean>;++export type ForwardedPrincipalParseResult =+ | {+ readonly forwardedPrincipal: ForwardedPrincipal;+ readonly ok: true;+ }+ | {+ readonly cause: unknown;+ readonly message: string;+ readonly ok: false;+ };++/**+ * The create route's effective session 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.+ */+export type ResolvedForwardedPrincipal =+ | {+ readonly accepted: false;+ readonly auth: SessionAuthContext;+ }+ | {+ readonly accepted: true;+ readonly auth: SessionAuthContext;+ readonly initiatorAuth: SessionAuthContext;+ };++const attributeValueSchema = z.union([z.string(), z.array(z.string()).readonly()]);++// Strict on keys, deliberately open on `authenticator` / `principalType`+// values: forwarded principals originate from arbitrary channel auth on the+// sending deployment (e.g. `authenticator: "slack-webhook"`), so the wire+// schema must mirror the open public `SessionAuthContext` interface — not the+// narrower runtime enums in `runtime/sessions/auth.ts`.+const forwardedPrincipalContextSchema = z+ .object({+ attributes: z.record(z.string(), attributeValueSchema).readonly(),+ authenticator: z.string().min(1),+ issuer: z.string().min(1).optional(),+ principalId: z.string().min(1),+ principalType: z.string().min(1),+ subject: z.string().min(1).optional(),+ })+ .strict();++const forwardedPrincipalSchema = z+ .object({+ current: forwardedPrincipalContextSchema,+ initiator: forwardedPrincipalContextSchema.optional(),+ })+ .strict();++/**+ * Gates the create-session `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+ * predicate throws. Accepted contexts are stamped with+ * {@link FORWARDED_BY_ATTRIBUTE} before they are returned, so a custom+ * `onMessage` always sees the transport forwarder on the replaced principal.+ */+export async function resolveForwardedPrincipal(input: {+ readonly trustedForwarders: TrustedForwarders | undefined;+ readonly forwarder: SessionAuthContext;+ readonly payload: Record<string, unknown>;+}): Promise<ResolvedForwardedPrincipal | Response> {+ const value = input.payload.forwardedPrincipal;+ if (value === undefined) return { accepted: false, auth: input.forwarder };++ if (input.trustedForwarders === undefined) {+ return Response.json(+ { error: "This deployment does not accept a forwarded principal.", ok: false },+ { status: 403 },+ );+ }++ const parsed = parseForwardedPrincipal(value);+ if (!parsed.ok) {+ return Response.json({ error: parsed.message, ok: false }, { status: 400 });+ }++ let accepted: boolean;+ try {+ accepted = await input.trustedForwarders(input.forwarder);+ } catch (error) {+ const errorId = logError(log, "trustedForwarders handler failed", error, {+ forwarder: input.forwarder.principalId,+ });+ return Response.json(+ { error: "trustedForwarders handler failed.", errorId, ok: false },+ { status: 500 },+ );+ }+ if (!accepted) {+ return Response.json(+ { error: "Caller is not authorized to assert a forwarded principal.", ok: false },+ { status: 403 },+ );+ }++ const current = stampForwardedBy(parsed.forwardedPrincipal.current, input.forwarder.principalId);+ const initiator =+ parsed.forwardedPrincipal.initiator === undefined+ ? current+ : stampForwardedBy(parsed.forwardedPrincipal.initiator, input.forwarder.principalId);+ return { accepted: true, auth: current, initiatorAuth: initiator };+}++/**+ * Parses the create-session `forwardedPrincipal` body field against the+ * strict wire schema. Mirrors `parseSessionCallback` for `callback`: strict+ * keys, formatted error strings, and no exceptions.+ */+export function parseForwardedPrincipal(value: unknown): ForwardedPrincipalParseResult {+ const parsed = forwardedPrincipalSchema.safeParse(value);+ if (parsed.success) {+ const current = toSessionAuthContext(parsed.data.current);+ return {+ forwardedPrincipal:+ parsed.data.initiator === undefined+ ? { current }+ : { current, initiator: toSessionAuthContext(parsed.data.initiator) },+ ok: true,+ };+ }++ return {+ cause: parsed.error,+ message: formatForwardedPrincipalParseError(parsed.error),+ ok: false,+ };+}++/**+ * Returns a copy of `context` with {@link FORWARDED_BY_ATTRIBUTE} set to the+ * verified transport forwarder's `principalId`, overwriting any+ * sender-supplied value. Attributes never affect Connect token-cache keying+ * (`principalKey` reads only issuer + id), so stamping is purely an audit+ * trail.+ */+export function stampForwardedBy(+ context: SessionAuthContext,+ forwardedBy: string,+): SessionAuthContext {+ return {+ ...context,+ attributes: { ...context.attributes, [FORWARDED_BY_ATTRIBUTE]: forwardedBy },+ };+}++function toSessionAuthContext(+ parsed: z.infer<typeof forwardedPrincipalContextSchema>,+): SessionAuthContext {+ const context: {+ -readonly [K in keyof SessionAuthContext]: SessionAuthContext[K];+ } = {+ attributes: parsed.attributes,+ authenticator: parsed.authenticator,+ principalId: parsed.principalId,+ principalType: parsed.principalType,+ };+ if (parsed.issuer !== undefined) {+ context.issuer = parsed.issuer;+ }+ if (parsed.subject !== undefined) {+ context.subject = parsed.subject;+ }+ return context;+}++function formatForwardedPrincipalParseError(error: z.ZodError): string {+ const messages = error.issues.map((issue) => {+ const path =+ issue.path.length === 0 ? "forwardedPrincipal" : `forwardedPrincipal.${issue.path.join(".")}`;+ return `${path}: ${issue.message}`;+ });+ return `Invalid forwardedPrincipal metadata: ${messages.join("; ")}`;+}diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.tsindex aa8b43b8d..d2f5f2bfc 100644--- a/packages/eve/src/channel/routes.ts+++ b/packages/eve/src/channel/routes.ts@@ -79,6 +79,13 @@ type BaseSendOptions = {auth: SessionAuthContext | null;callback?: SessionCallback;continuationToken: string;+ /**+ * The original (top-level) caller's auth for a newly started session,+ * becoming `session.auth.initiator`. Defaults to {@link auth} when omitted+ * (root session behavior). Ignored when the send resolves to an existing+ * session, whose initiator never changes after start.+ */+ initiatorAuth?: SessionAuthContext | null;mode?: RunMode;/*** Human-readable title for a newly started workflow session. Defaults todiff --git a/packages/eve/src/channel/send.ts b/packages/eve/src/channel/send.tsindex a4fe110aa..2ed42b423 100644--- a/packages/eve/src/channel/send.ts+++ b/packages/eve/src/channel/send.ts@@ -18,6 +18,7 @@ export function createSendFn<TState = undefined>(options: SendOptions<TState>,): Promise<Session> => {const auth = (options as { auth: SessionAuthContext | null }).auth;+ const initiatorAuth = (options as { initiatorAuth?: SessionAuthContext | null }).initiatorAuth;const callback = (options as { callback?: SendOptions<TState>["callback"] }).callback;const mode = (options as { mode?: SendOptions<TState>["mode"] }).mode ?? "conversation";const state = (options as { state?: TState }).state;@@ -59,7 +60,9 @@ export function createSendFn<TState = undefined>(? { ...adapter, state: { ...adapter.state, ...(state as Record<string, unknown>) } }: adapter;- const runInput: RunInput = {+ const runInput: {+ -readonly [K in keyof RunInput]: RunInput[K];+ } = {adapter: sessionAdapter,auth,capabilities: mode === "conversation" ? { requestInput: true } : undefined,@@ -71,6 +74,9 @@ export function createSendFn<TState = undefined>(requestId: metadata.requestId,title,};+ if (initiatorAuth !== undefined) {+ runInput.initiatorAuth = initiatorAuth;+ }const handle = await runtime.run(runInput);return createSession(handle.sessionId, rawToken, runtime);diff --git a/packages/eve/src/client/client.test.ts b/packages/eve/src/client/client.test.tsindex 980e32ee2..edb75edaa 100644--- a/packages/eve/src/client/client.test.ts+++ b/packages/eve/src/client/client.test.ts@@ -116,6 +116,35 @@ describe("Client request policy", () => {expect(sent.get("x-vercel-trusted-oidc-idp-token")).toBe("oidc-tok");});+ it("lets turn authorization override the client bearer while retaining trusted OIDC", async () => {+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(+ Response.json({ continuationToken: "eve:test", sessionId: "session_1" }, { status: 202 }),+ )+ .mockResolvedValueOnce(+ new Response(`${JSON.stringify({ data: {}, type: "session.completed" })}\n`),+ );+ const client = new Client({+ host: "https://eve.test",+ auth: { vercelOidc: { token: "oidc-tok" } },+ });++ await (+ await client.session().send({+ headers: { authorization: "Bearer application-user" },+ message: "hello",+ })+ ).result();++ expect(fetchMock.mock.calls).toHaveLength(2);+ for (const [, init] of fetchMock.mock.calls) {+ const sent = new Headers(init?.headers);+ expect(sent.get("authorization")).toBe("Bearer application-user");+ expect(sent.get("x-vercel-trusted-oidc-idp-token")).toBe("oidc-tok");+ }+ });+it("includes response headers in info request errors", async () => {vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("Redirecting...", {diff --git a/packages/eve/src/client/client.ts b/packages/eve/src/client/client.tsindex 287383172..a6ad00696 100644--- a/packages/eve/src/client/client.ts+++ b/packages/eve/src/client/client.ts@@ -159,16 +159,16 @@ export class Client {headers.set(key, value);}+ for (const [key, value] of Object.entries(authHeaders)) {+ headers.set(key, value);+ }+if (perRequest) {for (const [key, value] of Object.entries(perRequest)) {headers.set(key, value);}}- for (const [key, value] of Object.entries(authHeaders)) {- headers.set(key, value);- }-return headers;}diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.tsindex c9e07e6f4..9ed7d48ec 100644--- a/packages/eve/src/client/types.ts+++ b/packages/eve/src/client/types.ts@@ -165,7 +165,8 @@ export interface SendTurnPayload<TOutput = unknown> {readonly signal?: AbortSignal;/**- * Additional headers for this request only.+ * Additional headers for this request only. These override same-name+ * client-level headers, including headers generated by `ClientOptions.auth`.*/readonly headers?: Readonly<Record<string, string>>;}diff --git a/packages/eve/src/compiler/normalize-subagent.ts b/packages/eve/src/compiler/normalize-subagent.tsindex c50802b21..e48211057 100644--- a/packages/eve/src/compiler/normalize-subagent.ts+++ b/packages/eve/src/compiler/normalize-subagent.ts@@ -15,6 +15,7 @@ import {type ManifestCompileContext,} from "#compiler/normalize-helpers.js";import {+ expectBoolean,expectObjectRecord,expectOnlyKnownKeys,expectString,@@ -295,7 +296,7 @@ function normalizeRemoteAgentDefinition(const record = expectObjectRecord(value, message);expectOnlyKnownKeys(record,- ["auth", "description", "headers", "kind", "outputSchema", "path", "url"],+ ["auth", "description", "forwardPrincipal", "headers", "kind", "outputSchema", "path", "url"],message,);@@ -303,6 +304,16 @@ function normalizeRemoteAgentDefinition(throw new Error(`${message} Expected "kind" to be "remote".`);}+ // `forwardPrincipal` rides the module-backed runtime definition (like+ // `auth` and `headers`), so it is validated here but never baked into the+ // manifest.+ if (record.forwardPrincipal !== undefined) {+ expectBoolean(+ record.forwardPrincipal,+ `${message} Expected "forwardPrincipal" to be a boolean.`,+ );+ }+return {description: expectString(record.description, message),outputSchema: serializeOutputSchema(record.outputSchema as ToolSchemaSource | undefined),diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.tsindex d1d9fb4b6..370b11a75 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts@@ -186,8 +186,10 @@ export async function dispatchRuntimeActionsStep(input: {});childSessionId = await startRemoteAgentSession({action,+ auth,callbackBaseUrl: input.callbackBaseUrl,callbackToken: input.parentContinuationToken,+ initiatorAuth,remote: resolvedRemote,session,});diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.tsindex 9a33c4bc3..3e55ba6dd 100644--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts@@ -1,5 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";+import type { SessionAuthContext } from "#channel/types.js";import {cancelRemoteAgentTurn,isRetryableRemoteAgentCancelError,@@ -138,6 +139,37 @@ describe("startRemoteAgentSession", () => {expect(body.mode).toBe("task");});+ it("ignores an empty model-passed outputSchema instead of forwarding it", async () => {+ // Models routinely pass `outputSchema: {}` despite the tool schema saying+ // to omit it. An empty schema constrains nothing, but forwarding it flips+ // the remote child into structured-output mode and discards its text+ // reply — local subagent dispatch already drops it; remote must match.+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), {+ status: 202,+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const action = createAction();+ await startRemoteAgentSession({+ action: { ...action, input: { ...action.input, outputSchema: {} } },+ callbackBaseUrl: "https://caller.example.com",+ remote: createRemoteAgent(),+ session: {+ agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 100000 },+ continuationToken: "eve:parent-token",+ history: [],+ sessionId: "parent-session",+ state: {},+ },+ });++ const body = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string);+ expect(body).not.toHaveProperty("outputSchema");+ });+it("targets an active turn inbox when a callback token is supplied", async () => {const fetchMock = vi.fn()@@ -208,6 +240,133 @@ describe("startRemoteAgentSession", () => {});});+describe("startRemoteAgentSession — forwarded principal", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const CURRENT_AUTH: SessionAuthContext = {+ attributes: { user_id: "U123" },+ authenticator: "slack-webhook",+ issuer: "slack",+ principalId: "slack:U123",+ principalType: "user",+ subject: "U123",+ };++ const INITIATOR_AUTH: SessionAuthContext = {+ attributes: {},+ authenticator: "slack-webhook",+ issuer: "slack",+ principalId: "slack:U999",+ principalType: "user",+ subject: "U999",+ };++ function createSessionResponse(): Response {+ return new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), {+ status: 202,+ });+ }++ function createSession() {+ return {+ agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 100000 },+ continuationToken: "eve:parent-token",+ history: [],+ sessionId: "parent-session",+ };+ }++ it("forwards the current and initiator principals when forwardPrincipal is set", async () => {+ const fetchMock = vi.fn().mockResolvedValue(createSessionResponse());+ vi.stubGlobal("fetch", fetchMock);++ await expect(+ startRemoteAgentSession({+ action: createAction(),+ auth: CURRENT_AUTH,+ callbackBaseUrl: "https://caller.example.com",+ initiatorAuth: INITIATOR_AUTH,+ remote: { ...createRemoteAgent(), forwardPrincipal: true },+ session: createSession(),+ }),+ ).resolves.toBe("remote-session");++ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).forwardedPrincipal).toEqual({+ current: CURRENT_AUTH,+ initiator: INITIATOR_AUTH,+ });+ });++ it("omits the initiator when the dispatching turn has none", async () => {+ const fetchMock = vi.fn().mockResolvedValue(createSessionResponse());+ vi.stubGlobal("fetch", fetchMock);++ await startRemoteAgentSession({+ action: createAction(),+ auth: CURRENT_AUTH,+ callbackBaseUrl: "https://caller.example.com",+ initiatorAuth: null,+ remote: { ...createRemoteAgent(), forwardPrincipal: true },+ session: createSession(),+ });++ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).forwardedPrincipal).toEqual({+ current: CURRENT_AUTH,+ });+ });++ it("omits the field when the turn has no auth", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(+ new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), { status: 202 }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(+ startRemoteAgentSession({+ action: createAction(),+ auth: null,+ callbackBaseUrl: "https://caller.example.com",+ initiatorAuth: null,+ remote: { ...createRemoteAgent(), forwardPrincipal: true },+ session: createSession(),+ }),+ ).resolves.toBe("remote-session");++ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty(+ "forwardedPrincipal",+ );+ });++ it("does not forward when forwardPrincipal is unset even with auth in scope", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(+ new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), { status: 202 }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(+ startRemoteAgentSession({+ action: createAction(),+ auth: CURRENT_AUTH,+ callbackBaseUrl: "https://caller.example.com",+ initiatorAuth: INITIATOR_AUTH,+ remote: createRemoteAgent(),+ session: createSession(),+ }),+ ).resolves.toBe("remote-session");++ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty(+ "forwardedPrincipal",+ );+ });+});+describe("cancelRemoteAgentTurn", () => {afterEach(() => {vi.unstubAllGlobals();diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.tsindex 03a2497f1..219b35e2a 100644--- a/packages/eve/src/execution/remote-agent-dispatch.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.ts@@ -1,9 +1,13 @@import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";import { createEveCallbackRoutePath, createEveCancelTurnRoutePath } from "#protocol/routes.js";-import type { CancelTurnResult } from "#channel/types.js";+import type { CancelTurnResult, SessionAuthContext } from "#channel/types.js";+import type { ForwardedPrincipal } from "#channel/forwarded-principal.js";import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";-import { formatSubagentInput } from "#execution/subagent-invocation.js";+import {+ formatSubagentInput,+ normalizeRequestedOutputSchema,+} from "#execution/subagent-invocation.js";import type { HarnessSession } from "#harness/types.js";import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";@@ -21,8 +25,12 @@ class RemoteAgentCancelRequestError extends Error {export async function startRemoteAgentSession(input: {readonly action: RuntimeRemoteAgentCallActionRequest;+ /** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */+ readonly auth?: SessionAuthContext | null;readonly callbackBaseUrl: string | undefined;readonly callbackToken?: string;+ /** The root initiator's principal, forwarded alongside {@link auth}. */+ readonly initiatorAuth?: SessionAuthContext | null;readonly remote: ResolvedRuntimeRemoteAgentNode;readonly session: HarnessSession;}): Promise<string> {@@ -34,23 +42,40 @@ export async function startRemoteAgentSession(input: {throw new Error("Cannot dispatch remote agent without a callback base URL.");}+ const forwardedPrincipal = buildForwardedPrincipalField(input);+ const requestBody: {+ callback: {+ callId: string;+ subagentName: string;+ token: string;+ url: string;+ };+ forwardedPrincipal?: ForwardedPrincipal;+ message: string;+ mode: "task";+ outputSchema?: object;+ } = {+ callback: {+ callId: input.action.callId,+ subagentName: input.action.remoteAgentName,+ token: callbackToken,+ url: createWorkflowCallbackUrl(+ input.callbackBaseUrl,+ createEveCallbackRoutePath(callbackToken),+ ),+ },+ message: formatRemoteAgentCallInputMessage({ action: input.action, remote: input.remote }),+ mode: "task",+ outputSchema:+ normalizeRequestedOutputSchema(input.action.input.outputSchema) ?? input.remote.outputSchema,+ };+ if (forwardedPrincipal !== undefined) {+ requestBody.forwardedPrincipal = forwardedPrincipal;+ }+const headers = await resolveRemoteAgentRequestHeaders(input.remote);const response = await fetch(createRemoteAgentSessionUrl(input.remote), {- body: JSON.stringify({- callback: {- callId: input.action.callId,- subagentName: input.action.remoteAgentName,- token: callbackToken,- url: createWorkflowCallbackUrl(- input.callbackBaseUrl,- createEveCallbackRoutePath(callbackToken),- ),- },- message: formatRemoteAgentCallInputMessage({ action: input.action, remote: input.remote }),- mode: "task",- outputSchema:- (input.action.input.outputSchema as object | undefined) ?? input.remote.outputSchema,- }),+ body: JSON.stringify(requestBody),headers: {"content-type": "application/json",...headers,@@ -83,6 +108,28 @@ export async function startRemoteAgentSession(input: {);}+function buildForwardedPrincipalField(input: {+ readonly auth?: SessionAuthContext | null;+ readonly initiatorAuth?: SessionAuthContext | null;+ readonly remote: ResolvedRuntimeRemoteAgentNode;+}): ForwardedPrincipal | undefined {+ if (input.remote.forwardPrincipal !== true) {+ return undefined;+ }+ // No current principal (the request was accepted with no credentials):+ // proceed on transport trust alone.+ if (input.auth === null || input.auth === undefined) {+ return undefined;+ }+ const field: { current: SessionAuthContext; initiator?: SessionAuthContext } = {+ current: input.auth,+ };+ if (input.initiatorAuth !== null && input.initiatorAuth !== undefined) {+ field.initiator = input.initiatorAuth;+ }+ return field;+}+export async function cancelRemoteAgentTurn(input: {readonly remote: ResolvedRuntimeRemoteAgentNode;readonly sessionId: string;diff --git a/packages/eve/src/execution/subagent-invocation.test.ts b/packages/eve/src/execution/subagent-invocation.test.tsnew file mode 100644index 000000000..f3c0ab46f--- /dev/null+++ b/packages/eve/src/execution/subagent-invocation.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";++import { normalizeRequestedOutputSchema } from "#execution/subagent-invocation.js";++describe("normalizeRequestedOutputSchema", () => {+ it("passes a non-empty object schema through", () => {+ const schema = { properties: { answer: { type: "string" } }, type: "object" };++ expect(normalizeRequestedOutputSchema(schema)).toBe(schema);+ });++ it.each([+ ["an empty object", {}],+ ["a string", "object"],+ ["a number", 7],+ ["null", null],+ ["an array", [{ type: "object" }]],+ ])("normalizes %s to undefined", (_label, value) => {+ expect(normalizeRequestedOutputSchema(value)).toBeUndefined();+ });++ it("normalizes an absent value to undefined", () => {+ expect(normalizeRequestedOutputSchema(undefined)).toBeUndefined();+ });+});diff --git a/packages/eve/src/execution/subagent-invocation.ts b/packages/eve/src/execution/subagent-invocation.tsindex 0fe3c8247..c5494a44c 100644--- a/packages/eve/src/execution/subagent-invocation.ts+++ b/packages/eve/src/execution/subagent-invocation.ts@@ -1,4 +1,5 @@import type { StepInput } from "#harness/types.js";+import { isJsonObjectValue, type JsonObject, type JsonValue } from "#shared/json.js";/*** Narrowed form of {@link StepInput} whose `message` is always a plain string.@@ -8,6 +9,22 @@ export interface FormattedSubagentInvocation extends StepInput {readonly message: string;}+/**+ * Normalizes the `outputSchema` a model passed on a subagent tool call.+ * Models routinely send an empty `{}` despite the tool schema saying to omit+ * it; an empty JSON Schema constrains nothing, but honoring it flips the+ * child into structured-output mode and discards its text reply. Only a+ * non-empty object counts as a requested schema — local and remote dispatch+ * share this rule.+ */+export function normalizeRequestedOutputSchema(+ outputSchema: JsonValue | undefined,+): JsonObject | undefined {+ return isJsonObjectValue(outputSchema) && Object.keys(outputSchema).length > 0+ ? outputSchema+ : undefined;+}+type RuntimeSubagentInputFormatRequest = {readonly message: string;readonly name: string;diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.tsindex b4bfd26e5..35dd63c0f 100644--- a/packages/eve/src/execution/subagent-tool.ts+++ b/packages/eve/src/execution/subagent-tool.ts@@ -1,5 +1,8 @@import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter.js";-import { formatSubagentInput } from "#execution/subagent-invocation.js";+import {+ formatSubagentInput,+ normalizeRequestedOutputSchema,+} from "#execution/subagent-invocation.js";import type {ChannelInstrumentationProjection,RunInput,@@ -8,7 +11,6 @@ import type {SessionCapabilities,} from "#channel/types.js";import type { HarnessSession } from "#harness/types.js";-import { isJsonObjectValue } from "#shared/json.js";import type { RuntimeSubagentCallActionRequest } from "#runtime/actions/types.js";import { mintSubagentContinuationToken } from "#execution/session.js";import { resolveSubagentDepth } from "#harness/subagent-depth.js";@@ -97,11 +99,7 @@ export function buildSubagentRunInput(input: {const inheritedLimits: {-readonly [K in keyof RunSessionLimits]: RunSessionLimits[K];} = resolveRemainingSessionTokenLimits(session, input.fanoutSize);- const outputSchema = action.input.outputSchema;- const requestedOutputSchema =- isJsonObjectValue(outputSchema) && Object.keys(outputSchema).length > 0- ? outputSchema- : undefined;+ const requestedOutputSchema = normalizeRequestedOutputSchema(action.input.outputSchema);const runInput: {-readonly [K in keyof RunInput]: RunInput[K];diff --git a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.tsnew file mode 100644index 000000000..daf992204--- /dev/null+++ b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts@@ -0,0 +1,198 @@+import { describe, expect, it, vi } from "vitest";++/**+ * Integration coverage for forwarded principal across the create route and the+ * runtime: an accepted `forwardedPrincipal` body becomes the run's session+ * principal (`AuthKey` / `InitiatorAuthKey`, projected as+ * `session.auth.current` / `.initiator`) and reaches+ * `resolveConnectionPrincipal` as a `user` principal — the seam per-user+ * Vercel Connect requires on the receiving deployment.+ */++import type { RouteHandlerArgs, SendFn, SendOptions } from "#channel/routes.js";+import type { Session as ChannelSession } from "#channel/session.js";+import type { RunInput, SessionAuthContext } from "#channel/types.js";+import { contextStorage } from "#context/container.js";+import { AuthKey, InitiatorAuthKey } from "#context/keys.js";+import { buildRunContext } from "#execution/runtime-context.js";+import { isConnectionAuthorizationFailedError } from "#public/connections/errors.js";+import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";+import { eveChannel, type EveChannelInput } from "#public/channels/eve.js";++const ROUTER_CALLER: SessionAuthContext = {+ attributes: {},+ authenticator: "oidc",+ issuer: "https://oidc.vercel.com/acme",+ principalId: "https://oidc.vercel.com/acme:owner:acme:project:router:environment:production",+ principalType: "service",+ subject: "owner:acme:project:router:environment:production",+};++const FORWARDED_CURRENT: SessionAuthContext = {+ attributes: { user_id: "U123" },+ authenticator: "slack-webhook",+ issuer: "slack",+ principalId: "slack:U123",+ principalType: "user",+ subject: "U123",+};++const FORWARDED_INITIATOR: SessionAuthContext = {+ attributes: {},+ authenticator: "slack-webhook",+ issuer: "slack",+ principalId: "slack:U999",+ principalType: "user",+ subject: "U999",+};++function createEveCreateHandler(input: EveChannelInput) {+ const channel = eveChannel(input);+ const createRoute = channel.routes.find(+ (route) => route.method === "POST" && route.path === "/eve/v1/session",+ );+ if (!createRoute) throw new Error("No create POST route found");++ const mockSend = vi.fn<SendFn>().mockResolvedValue({+ id: "receiver-session-id",+ continuationToken: "eve:test",+ async cancel() {+ return { status: "no_active_turn" };+ },+ async getEventStream() {+ return new ReadableStream();+ },+ } satisfies ChannelSession);++ return {+ send: mockSend,+ async fetch(req: Request) {+ const args: RouteHandlerArgs = {+ send: mockSend,+ resolveActiveSession: async () => undefined,+ cancel: vi.fn(),+ reset: vi.fn(),+ getSession: vi.fn(),+ receive: vi.fn() as never,+ params: {},+ waitUntil: () => undefined,+ requestIp: "127.0.0.1",+ };+ return (+ createRoute as { handler: (req: Request, args: RouteHandlerArgs) => unknown }+ ).handler(req, args) as Promise<Response>;+ },+ };+}++describe("eveChannel forwarded principal → runtime principal", () => {+ it("seeds the forwarded principal into the run context and resolves a user Connect principal", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: (caller) => caller.principalId === ROUTER_CALLER.principalId,+ auth: () => ROUTER_CALLER,+ });++ const response = await handler.fetch(+ new Request("https://receiver.example.com/eve/v1/session", {+ body: JSON.stringify({+ forwardedPrincipal: { current: FORWARDED_CURRENT, initiator: FORWARDED_INITIATOR },+ message: "check my dashboards",+ mode: "task",+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ );++ expect(response.status).toBe(202);+ await expect(response.json()).resolves.toMatchObject({ ok: true });++ const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const run: RunInput = {+ adapter: { kind: "eve" },+ auth: options.auth,+ channelName: "eve",+ continuationToken: "eve:test",+ initiatorAuth: options.initiatorAuth,+ input: { message: "check my dashboards" },+ mode: "task",+ };+ const ctx = buildRunContext({ bundle: {} as CompiledBundle, run });++ const current = ctx.get(AuthKey);+ const initiator = ctx.get(InitiatorAuthKey);+ expect(current).toMatchObject({+ attributes: { "eve:forwarded-by": ROUTER_CALLER.principalId, user_id: "U123" },+ principalId: "slack:U123",+ principalType: "user",+ });+ expect(initiator).toMatchObject({+ attributes: { "eve:forwarded-by": ROUTER_CALLER.principalId },+ principalId: "slack:U999",+ principalType: "user",+ });++ const principal = contextStorage.run(ctx, () =>+ resolveConnectionPrincipal("datadog", {+ getToken: async () => ({ token: "t" }),+ principalType: "user",+ }),+ );++ expect(principal).toEqual({+ attributes: { "eve:forwarded-by": ROUTER_CALLER.principalId, user_id: "U123" },+ id: "slack:U123",+ issuer: "slack",+ type: "user",+ });+ // The audit attribute never enters Connect token-cache keying.+ expect(principalKey(principal)).toBe("user:slack:slack:U123");+ });++ it("resolves the transport service principal (and fails Connect) without forwarding", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ await handler.fetch(+ new Request("https://receiver.example.com/eve/v1/session", {+ body: JSON.stringify({ message: "check my dashboards", mode: "task" }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ );++ const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const ctx = buildRunContext({+ bundle: {} as CompiledBundle,+ run: {+ adapter: { kind: "eve" },+ auth: options.auth,+ channelName: "eve",+ continuationToken: "eve:test",+ input: { message: "check my dashboards" },+ mode: "task",+ },+ });++ expect(ctx.get(AuthKey)).toEqual(ROUTER_CALLER);+ expect(ctx.get(InitiatorAuthKey)).toEqual(ROUTER_CALLER);+ const failure = (() => {+ try {+ contextStorage.run(ctx, () =>+ resolveConnectionPrincipal("datadog", {+ getToken: async () => ({ token: "t" }),+ principalType: "user",+ }),+ );+ return undefined;+ } catch (error) {+ return error;+ }+ })();+ expect(isConnectionAuthorizationFailedError(failure)).toBe(true);+ expect(failure).toMatchObject({ reason: "principal_required" });+ });+});diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex 85ff22214..ef77801ef 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -1506,3 +1506,226 @@ describe("eveChannel — reset session", () => {});});});++describe("eveChannel — forwarded principal", () => {+ const ROUTER_CALLER: SessionAuthContext = {+ attributes: {},+ authenticator: "oidc",+ issuer: "https://oidc.vercel.com/acme",+ principalId: "https://oidc.vercel.com/acme:owner:acme:project:router:environment:production",+ principalType: "service",+ subject: "owner:acme:project:router:environment:production",+ };++ const FORWARDED_CURRENT: SessionAuthContext = {+ attributes: { user_id: "U123" },+ authenticator: "slack-webhook",+ issuer: "slack",+ principalId: "slack:U123",+ principalType: "user",+ subject: "U123",+ };++ const FORWARDED_INITIATOR: SessionAuthContext = {+ attributes: {},+ authenticator: "slack-webhook",+ issuer: "slack",+ principalId: "slack:U999",+ principalType: "user",+ subject: "U999",+ };++ function forwardedRequest(forwardedPrincipal: unknown): Request {+ return createJsonMessageRequest({ forwardedPrincipal, message: "hi", mode: "task" });+ }++ it("rejects a forwarded body when the channel has no trustedForwarders", async () => {+ const handler = createEveCreateHandler({ auth: () => ROUTER_CALLER });++ const response = await handler.fetch(forwardedRequest({ current: FORWARDED_CURRENT }));++ expect(response.status).toBe(403);+ expect(handler.send).not.toHaveBeenCalled();+ await expect(response.json()).resolves.toMatchObject({+ error: "This deployment does not accept a forwarded principal.",+ ok: false,+ });+ });++ it("rejects a caller the predicate refuses", async () => {+ const trustedForwarders = vi.fn(+ (caller: SessionAuthContext) => caller.principalId === "someone-else",+ );+ const handler = createEveCreateHandler({+ trustedForwarders,+ auth: () => ROUTER_CALLER,+ });++ const response = await handler.fetch(forwardedRequest({ current: FORWARDED_CURRENT }));++ expect(response.status).toBe(403);+ expect(trustedForwarders).toHaveBeenCalledWith(ROUTER_CALLER);+ expect(handler.send).not.toHaveBeenCalled();+ await expect(response.json()).resolves.toMatchObject({+ error: "Caller is not authorized to assert a forwarded principal.",+ ok: false,+ });+ });++ it("rejects a malformed forwarded payload with 400", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ const response = await handler.fetch(+ forwardedRequest({ current: { ...FORWARDED_CURRENT, token: "secret" } }),+ );++ expect(response.status).toBe(400);+ expect(handler.send).not.toHaveBeenCalled();+ await expect(response.json()).resolves.toMatchObject({+ error: expect.stringContaining("Invalid forwardedPrincipal metadata"),+ ok: false,+ });+ });++ it("returns 500 when the authored predicate throws", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => {+ throw new Error("boom");+ },+ auth: () => ROUTER_CALLER,+ });++ const response = await handler.fetch(forwardedRequest({ current: FORWARDED_CURRENT }));++ expect(response.status).toBe(500);+ expect(handler.send).not.toHaveBeenCalled();+ });++ it("replaces the session principal when the forwarder is accepted", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: (forwarder) => forwarder.principalId === ROUTER_CALLER.principalId,+ auth: () => ROUTER_CALLER,+ });++ const response = await handler.fetch(+ forwardedRequest({ current: FORWARDED_CURRENT, initiator: FORWARDED_INITIATOR }),+ );++ expect(response.status).toBe(202);+ await expect(response.json()).resolves.toMatchObject({+ ok: true,+ sessionId: "test-session-id",+ });++ const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ expect(options.auth).toEqual({+ ...FORWARDED_CURRENT,+ attributes: {+ ...FORWARDED_CURRENT.attributes,+ "eve:forwarded-by": ROUTER_CALLER.principalId,+ },+ });+ expect(options.initiatorAuth).toEqual({+ ...FORWARDED_INITIATOR,+ attributes: {+ ...FORWARDED_INITIATOR.attributes,+ "eve:forwarded-by": ROUTER_CALLER.principalId,+ },+ });+ expect(options.mode).toBe("task");+ });++ it("defaults the initiator to the forwarded current principal", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ await handler.fetch(forwardedRequest({ current: FORWARDED_CURRENT }));++ const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ expect(options.initiatorAuth).toEqual(options.auth);+ });++ it("overwrites a sender-supplied eve:forwarded-by attribute", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ await handler.fetch(+ forwardedRequest({+ current: {+ ...FORWARDED_CURRENT,+ attributes: { "eve:forwarded-by": "forged-value" },+ },+ }),+ );++ const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ expect(options.auth?.attributes["eve:forwarded-by"]).toBe(ROUTER_CALLER.principalId);+ });++ it("exposes the stamped forwarded principal to onMessage as the caller", async () => {+ const onMessage = vi.fn((ctx: Parameters<typeof defaultEveAuth>[0]) => {+ expect(ctx.eve.caller?.principalId).toBe(FORWARDED_CURRENT.principalId);+ expect(ctx.eve.caller?.attributes["eve:forwarded-by"]).toBe(ROUTER_CALLER.principalId);+ return { auth: defaultEveAuth(ctx) };+ });+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ onMessage,+ });++ const response = await handler.fetch(forwardedRequest({ current: FORWARDED_CURRENT }));++ expect(response.status).toBe(202);+ expect(onMessage).toHaveBeenCalledTimes(1);+ const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ expect(options.auth?.principalId).toBe(FORWARDED_CURRENT.principalId);+ });++ it("keeps the transport principal and omits initiatorAuth without a forwarded body", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ const response = await handler.fetch(createJsonMessageRequest({ message: "hi" }));++ expect(response.status).toBe(202);+ const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ expect(options.auth).toEqual(ROUTER_CALLER);+ expect(options).not.toHaveProperty("initiatorAuth");+ });++ it("rejects forwarded principal on the continue route", async () => {+ const handler = createEveContinueHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ const response = await handler.fetch(+ new Request("https://example.com/eve/v1/session/test-session-id", {+ body: JSON.stringify({+ continuationToken: "eve:test",+ forwardedPrincipal: { current: FORWARDED_CURRENT },+ message: "hi",+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ );++ expect(response.status).toBe(400);+ 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.tsindex 4b15180a4..01efce6c2 100644--- a/packages/eve/src/public/channels/eve.ts+++ b/packages/eve/src/public/channels/eve.ts@@ -3,6 +3,8 @@ import { type FilePart, type TextPart, type UserContent } from "ai";import type { CancelTurnResult, SessionAuthContext, SessionCallback } from "#channel/types.js";import type { CancelTurnResponse } from "#protocol/cancel-turn.js";import type { ResetResponse } from "#protocol/reset-session.js";+import type { SendOptions } from "#channel/routes.js";+import { resolveForwardedPrincipal, type TrustedForwarders } from "#channel/forwarded-principal.js";import { parseSessionCallback } from "#channel/session-callback.js";import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";import { createLogger, logError } from "#internal/logging.js";@@ -127,6 +129,25 @@ export interface EveChannelInput {* the next; exhaustion (including the empty array) rejects with 401. Include `none()` last for anonymous traffic.*/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+ * `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 —+ * and must match it precisely (for example+ * `(forwarder) => forwarder.subject === vercelSubject({ teamSlug, projectName })`).+ * 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.+ */+ readonly trustedForwarders?: TrustedForwarders;/*** Attachment policy for inbound file parts. Omit for the framework default (25 MB cap, all media* types); `"disabled"` rejects every attachment; a partial config is merged onto the default. Violations reject with 413 (too large) or 415 (bad type).@@ -206,6 +227,13 @@ export function eveChannel(input: EveChannelInput): EveChannel {return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });}+ const forwarded = await resolveForwardedPrincipal({+ trustedForwarders: input.trustedForwarders,+ forwarder: sessionAuth,+ payload: payload as Record<string, unknown>,+ });+ if (forwarded instanceof Response) return forwarded;+const body = parseCreateBody(payload as Record<string, unknown>);if (body instanceof Response) return body;@@ -213,7 +241,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {if (policyRejection !== null) return policyRejection;const messageResult = await resolveOnMessage({- auth: sessionAuth,+ auth: forwarded.auth,config: input,message: body.message,request: req,@@ -224,12 +252,16 @@ export function eveChannel(input: EveChannelInput): EveChannel {const token = `eve:${crypto.randomUUID()}`;const context = mergeContext(body.context, messageResult.context);- const session = await send(createSendPayload(body, context), {+ const sendOptions: SendOptions = {auth: messageResult.auth,callback: body.callback,continuationToken: token,mode: body.mode,- });+ };+ if (forwarded.accepted) {+ sendOptions.initiatorAuth = forwarded.initiatorAuth;+ }+ const session = await send(createSendPayload(body, context), sendOptions);return Response.json({@@ -589,6 +621,15 @@ interface ParsedContinueBody {}function parseContinueBody(payload: Record<string, unknown>): ParsedContinueBody | Response {+ // Fail loud instead of silently running the delivery as the transport+ // principal: principal forwarding is create-only today.+ if (payload.forwardedPrincipal !== undefined) {+ return Response.json(+ { error: "A forwarded principal is only accepted on session creation.", ok: false },+ { status: 400 },+ );+ }+const continuationToken =typeof payload.continuationToken === "string" && payload.continuationToken.length > 0? payload.continuationTokendiff --git a/packages/eve/src/public/definitions/remote-agent.ts b/packages/eve/src/public/definitions/remote-agent.tsindex dadbbdb85..324d593da 100644--- a/packages/eve/src/public/definitions/remote-agent.ts+++ b/packages/eve/src/public/definitions/remote-agent.ts@@ -22,6 +22,21 @@ export interface RemoteAgentDefinition {* The parent agent reads this as the lowered subagent tool's description.*/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.+ *+ * Only principal metadata crosses the wire, never tokens or credentials —+ * {@link auth} keeps authenticating *this* deployment to the remote. The+ * receiver must opt in with `eveChannel({ trustedForwarders })`;+ * a receiver that refuses the forwarder (or accepts no forwarded principal+ * at all) rejects with 403 and the dispatch fails.+ */+ readonly forwardPrincipal?: boolean;readonly headers?: HeadersValue;readonly kind: "remote";/**diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.tsindex 7dfa74b0e..f9a8dfb75 100644--- a/packages/eve/src/runtime/resolve-agent-graph.ts+++ b/packages/eve/src/runtime/resolve-agent-graph.ts@@ -352,6 +352,7 @@ async function resolveRuntimeRemoteAgent(input: {const resolvedRemoteAgent: {auth?: ResolvedRuntimeRemoteAgentNode["auth"];description: string;+ forwardPrincipal?: boolean;headers?: HeadersValue;kind: "remote";logicalPath: string;@@ -383,6 +384,10 @@ async function resolveRuntimeRemoteAgent(input: {resolvedRemoteAgent.auth = resolvedRecord.auth as ResolvedRuntimeRemoteAgentNode["auth"];}+ if (resolvedRecord.forwardPrincipal === true) {+ resolvedRemoteAgent.forwardPrincipal = true;+ }+const headers = resolveRemoteAgentHeaders(resolvedRecord.headers);if (headers !== undefined) {diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.tsindex 8805d52b0..8e10abea7 100644--- a/packages/eve/src/runtime/types.ts+++ b/packages/eve/src/runtime/types.ts@@ -283,6 +283,7 @@ export type ResolvedRuntimeRemoteAgentNode = Readonly<Node & {auth?: OutboundAuthFn;description: string;+ forwardPrincipal?: boolean;headers?: HeadersValue;kind: "remote";name: string;diff --git a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.tsnew file mode 100644index 000000000..dc2d3f9bf--- /dev/null+++ b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts@@ -0,0 +1,169 @@+import { describe, expect, it } from "vitest";++import type { SessionAuthContext } from "../../src/channel/types.js";+import { startRemoteAgentSession } from "../../src/execution/remote-agent-dispatch.js";+import type { RuntimeRemoteAgentCallActionRequest } from "../../src/runtime/actions/types.js";+import type { ResolvedRuntimeRemoteAgentNode } from "../../src/runtime/types.js";+import {+ type ScenarioAppDescriptor,+ useScenarioApp,+} from "../../src/internal/testing/scenario-app.js";+import { startEveDev } from "./dev-server-harness.js";++/**+ * Locks the remote-agent principal-forwarding hop over a real HTTP boundary: the+ * test process plays the router deployment (driving the real sender dispatch+ * function) against a receiver dev server whose `eveChannel` configures+ * `trustedForwarders`. The receiver's `onMessage` asserts that the+ * forwarded principal — not the transport caller — became the effective+ * session caller, with the `eve:forwarded-by` audit attribute stamped from+ * the verified transport principal.+ */++const scenarioApp = useScenarioApp();+const SCENARIO_TIMEOUT_MS = 360_000;++const ROUTER_TOKEN = "router-scenario-token";+const STRANGER_TOKEN = "stranger-scenario-token";++const RECEIVER_DESCRIPTOR: ScenarioAppDescriptor = {+ files: {+ "agent/agent.ts": `import { defineAgent } from "eve";++export default defineAgent({ model: "openai/gpt-5.4-mini" });+`,+ "agent/channels/eve.ts": `import { eveChannel } from "eve/channels/eve";++const PRINCIPALS = {+ "Bearer ${ROUTER_TOKEN}": "router-app",+ "Bearer ${STRANGER_TOKEN}": "stranger-app",+};++export default eveChannel({+ auth(request) {+ const principalId = PRINCIPALS[request.headers.get("authorization") ?? ""];+ if (principalId === undefined) return null;+ return {+ attributes: {},+ authenticator: "scenario-bearer",+ principalId,+ principalType: "service",+ };+ },+ trustedForwarders: (caller) => caller.principalId === "router-app",+ onMessage(ctx) {+ const caller = ctx.eve.caller;+ if (+ caller?.principalId !== "slack:U123" ||+ caller.principalType !== "user" ||+ caller.attributes["eve:forwarded-by"] !== "router-app"+ ) {+ throw new Error("Expected the stamped forwarded principal as the effective caller.");+ }+ return { auth: caller };+ },+});+`,+ "agent/instructions.md": "Reply tersely.\n",+ },+ installDependencies: true,+ name: "forwarded-principal-receiver",+};++const FORWARDED_USER: SessionAuthContext = {+ attributes: { user_id: "U123" },+ authenticator: "slack-webhook",+ issuer: "slack",+ principalId: "slack:U123",+ principalType: "user",+ subject: "U123",+};++describe("remote agent auth forwarding", () => {+ it(+ "asserts the forwarded principal across the hop and rejects untrusted forwarders",+ async () => {+ const receiverApp = await scenarioApp(RECEIVER_DESCRIPTOR);+ const receiver = await startEveDev(receiverApp.appRoot);++ try {+ // Accepted: the trusted transport principal asserts a forwarded user.+ // The receiver's onMessage (which throws on any other caller) proves+ // the principal replacement happened.+ const childSessionId = await startRemoteAgentSession({+ action: createAction(),+ auth: FORWARDED_USER,+ callbackBaseUrl: "https://caller.example.com",+ initiatorAuth: FORWARDED_USER,+ remote: createRemote({ token: ROUTER_TOKEN, url: receiver.url }),+ session: createParentSession(),+ });+ expect(childSessionId.length).toBeGreaterThan(0);++ // Mismatch: an authenticated caller outside the forwarder allow-list+ // fails loud at the hop instead of downgrading to service identity.+ await expect(+ startRemoteAgentSession({+ action: createAction(),+ auth: FORWARDED_USER,+ callbackBaseUrl: "https://caller.example.com",+ initiatorAuth: FORWARDED_USER,+ remote: createRemote({ token: STRANGER_TOKEN, url: receiver.url }),+ session: createParentSession(),+ }),+ ).rejects.toThrow(/HTTP 403/);+ } catch (error) {+ throw new Error(+ [`receiver stdout:\n${receiver.stdout()}`, `receiver stderr:\n${receiver.stderr()}`].join(+ "\n\n",+ ),+ { cause: error },+ );+ } finally {+ await receiver.stop();+ }+ },+ SCENARIO_TIMEOUT_MS,+ );+});++function createAction(): RuntimeRemoteAgentCallActionRequest {+ return {+ callId: "call-forwarded",+ description: "Runtime action event description.",+ input: { message: "check the site status" },+ kind: "remote-agent-call",+ name: "site-ops",+ nodeId: "subagents/site-ops.ts",+ remoteAgentName: "site-ops",+ };+}++function createRemote(input: {+ readonly token: string;+ readonly url: string;+}): ResolvedRuntimeRemoteAgentNode {+ return {+ auth: async () => ({ headers: { authorization: `Bearer ${input.token}` } }),+ description: "Executes site operations as the requesting user.",+ forwardPrincipal: true,+ kind: "remote",+ logicalPath: "subagents/site-ops.ts",+ name: "site-ops",+ nodeId: "subagents/site-ops.ts",+ path: "/eve/v1/session",+ sourceId: "subagents/site-ops.ts",+ sourceKind: "module",+ url: input.url,+ };+}++function createParentSession() {+ return {+ agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 100_000 },+ continuationToken: "eve:parent-token",+ history: [],+ sessionId: "parent-session",+ };+}diff --git a/research/remote-agent-auth-forwarding.md b/research/remote-agent-auth-forwarding.mdnew file mode 100644index 000000000..02cee7284--- /dev/null+++ b/research/remote-agent-auth-forwarding.md@@ -0,0 +1,197 @@+---+issue: https://github.com/vercel/eve/issues/604+status: implemented+last_updated: "2026-07-23"+---++# Forwarding end-user identity across remote agent hops++## Summary++A `defineRemoteAgent` hop drops the caller principal. Local subagent dispatch threads `auth` and+`initiatorAuth` onto the child `RunInput` (`execution/subagent-tool.ts`), so a child session sees+the same end user as its parent. The remote branch sends only+`{ callback, message, mode, outputSchema }` (`execution/remote-agent-dispatch.ts`), so the only+identity that can cross the hop is deployment-level trust. The receiving deployment authenticates+the _calling app_ (`principalType: "runtime"` / `"service"`), never the end user.++This breaks per-user workloads split across deployments — most directly per-user Vercel Connect:+`resolveConnectionPrincipal` requires `session.auth.current.principalType === "user"` and fails+with `principal_required` when the session principal is the calling service. A router deployment+that authenticates end users over Slack cannot delegate to a `site-ops` deployment where each user+has OAuthed their own Datadog / GitHub / Vercel connection.++This plan adds explicit, opt-in principal forwarding on both sides of the hop. Only principal+_metadata_ (`SessionAuthContext`) crosses the wire — never tokens or credentials. The trust model+is "trusted forwarder": the route's `auth` authenticates the asserting deployment as usual, and+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.++```text+Slack user U ── router deployment ──────────────► site-ops deployment+ auth.current = U POST /eve/v1/session+ headers: OIDC (router app identity)+ body.forwardedPrincipal: { current: U, initiator: U }+ │+ eveChannel auth: verifies router app+ trustedForwarders(caller): router app may forward+ │+ session.auth.current = U ──► per-user Connect,+ local subagents,+ further remote hops+```++## Authoring API++### Sender: `forwardPrincipal` on `defineRemoteAgent`++```ts+// agent/subagents/site-ops.ts+import { defineRemoteAgent } from "eve";+import { vercelOidc } from "eve/agents/auth";++export default defineRemoteAgent({+ url: "https://site-ops.example.com",+ description: "Executes site operations as the requesting user.",+ auth: vercelOidc(), // transport trust: authenticates *this* deployment+ forwardPrincipal: true, // identity: asserts the current session principal+});+```++- `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 }`.+- 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+ principals — exact parity with how local subagent dispatch threads `auth`. Non-user principals+ still fail `principal_required` at Connect on the receiver, which is the correct outcome.+- The flag rides the module-backed runtime definition next to `auth` and `headers`; the compiled+ manifest node is unchanged.++### Receiver: `trustedForwarders` on `eveChannel`++```ts+// agent/channels/eve.ts (site-ops deployment)+import { eveChannel, vercelOidc, vercelSubject } from "eve";++export default eveChannel({+ auth: [vercelOidc()],+ // Only the router deployment may assert a forwarded principal.+ trustedForwarders: (forwarder) =>+ forwarder.subject === vercelSubject({ teamSlug: "acme", projectName: "router" }),+});+```++- `trustedForwarders?: (caller: SessionAuthContext) => boolean | Promise<boolean>`. The+ predicate authorizes the _verified transport principal_ (who is asserting), not the forwarded+ identity (what is asserted). The route's `auth` walk has already authenticated the request; the+ forwarding decision is authorization over its result, so there is no second token verification+ and no new auth machinery.+- A predicate — rather than a second `AuthFn` walk — makes the Vercel OIDC always-on+ current-project bypass structurally irrelevant: the bypass lives inside `vercelOidc()` closures+ and cannot be disabled from the outside, and with a predicate the author must write an explicit+ match against the verified principal. Same-project callers (including preview deployments of+ the receiving project) get a transport principal whose `subject` simply does not match the named+ forwarder. `vercelSubject()` already produces the exact `sub` string to compare.+- The forwarded `SessionAuthContext` values are validated against a strict wire schema in a new+ `channel/forwarded-principal.ts`, mirroring how `callback` is validated today+ (`channel/session-callback.ts`). The schema is strict on keys but **must keep `authenticator`+ and `principalType` as open non-empty strings** (matching the public `SessionAuthContext`+ interface) with attribute values `string | string[]`. It must not mirror the private runtime+ schema in `runtime/sessions/auth.ts`, whose enums (`"http-basic" | "jwt-hmac" | ...`) would+ reject the flagship use case — a Slack-authenticated user has `authenticator: "slack-webhook"`.++## 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.+- **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+ multi-hop chains (A→B→C) the attribute names the most recent hop only. Attributes do not affect+ Connect token-cache keying (`principalKey` uses issuer + id only).+- **`onMessage` still runs last, after stamping.** `eve:forwarded-by` is written before+ `onMessage` runs. `EveHandle.caller` is the forwarded principal once accepted, so+ `caller.attributes["eve:forwarded-by"]` is the window a custom `onMessage` has onto the+ transport caller; `defaultEveAuth` passes the forwarded principal through, and a custom+ `onMessage` can still override or drop, same as today.+- **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).+- **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+ authorizations.+- **Events unchanged.** `subagent.called` and callbacks are untouched; forwarding is invisible to+ the parent stream. The cancel path is untouched: it authenticates with the definition's existing+ `auth` / `headers` and carries no forwarded identity.++## 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 |++Docs must carry the security guidance explicitly: match the transport principal precisely (e.g.+`subject === vercelSubject({ teamSlug, projectName })`); a permissive predicate (`() => true`)+lets any authenticated caller assert any principal. Docs must also note that the framework default+channel has no `trustedForwarders`, so a receiving deployment must author its own+`agent/channels/eve.ts` to accept forwarded identity — forwarded bodies 403 until it does.++## Out of scope++- Token exchange, delegation tokens, or forwarding credentials of any kind — the receiver mints+ its own per-user credentials via Connect.+- A context-aware `OutboundAuthFn` (passing the dispatching turn's principals so custom schemes+ can mint per-user credentials for non-eve receivers). Adding a parameter to the function type+ later is fully non-breaking — zero-arg implementations remain assignable and eve is the only+ caller — so this waits for a concrete need. It would also have to define what context the+ cancel path passes, since `cancelRemoteAgentTurn` resolves headers through the same+ `resolveRemoteAgentRequestHeaders`.+- 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.+- 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.++## Delivery and verification++Single PR with a **patch** changeset: both options are additive; no public API breaks.++- Unit: wire schema (strict on keys, open `authenticator` / `principalType`, channel-produced+ contexts like `slack-webhook` accepted, malformed rejection), dispatch body construction with+ and without `forwardPrincipal` and with null auth (field omitted), receiver matrix (field+ 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`).+- 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.)