Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add remote client authentication foundation (#191)

Ruib29e2ae59770
diff --git a/.changeset/remote-client-foundation.md b/.changeset/remote-client-foundation.md
new file mode 100644
index 000000000..eadd85e59
--- /dev/null
+++ b/.changeset/remote-client-foundation.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Remote clients can now send Vercel OIDC credentials through a dedicated auth mode and reject malformed agent metadata before using it.
diff --git a/docs/guides/client/overview.mdx b/docs/guides/client/overview.mdx
index 59d794af0..fb2246bd9 100644
--- a/docs/guides/client/overview.mdx
+++ b/docs/guides/client/overview.mdx
@@ -32,6 +32,15 @@ console.log(health.status, health.workflowId);
Non-2xx responses throw `ClientError`, which carries the HTTP `status` and response `body`.
+## Inspect an agent
+
+Use `info()` to inspect a development agent. The client parses and validates the complete response before returning it:
+
+```ts
+const info = await client.info();
+console.log(info.agent.name, info.agent.model.id);
+```
+
## Authentication
Pass `auth` when the [eve channel](../../channels/eve) route requires credentials:
@@ -59,6 +68,21 @@ const client = new Client({
});
```
+For a Vercel OIDC-protected deployment, use `vercelOidc`. The client resolves the token once per request and sends it as both the bearer credential and Vercel's trusted-OIDC header:
+
+```ts
+import { getVercelOidcToken } from "@vercel/oidc";
+
+const client = new Client({
+ host: "https://agent.example.com",
+ auth: {
+ vercelOidc: {
+ token: async () => await getVercelOidcToken(),
+ },
+ },
+});
+```
+
Use `headers` for route-specific credentials such as bypass tokens or tenant hints. Like `auth`, it can be static or dynamic:
```ts
diff --git a/packages/eve/src/cli/dev/tui/remote-auth-result.ts b/packages/eve/src/cli/dev/tui/remote-auth-result.ts
new file mode 100644
index 000000000..ea98b8b54
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/remote-auth-result.ts
@@ -0,0 +1,43 @@
+import type { VerifiedVercelTarget } from "#setup/vercel-deployment.js";
+
+export type RemoteAuthCompletedMutation = { readonly kind: "vercel-login" };
+
+export type RemoteAuthPreparation =
+ | {
+ readonly kind: "prepared";
+ readonly target: VerifiedVercelTarget;
+ readonly resolveToken: () => Promise<string>;
+ readonly completedMutations: readonly RemoteAuthCompletedMutation[];
+ }
+ | {
+ readonly kind: "cancelled";
+ readonly completedMutations: readonly RemoteAuthCompletedMutation[];
+ }
+ | {
+ readonly kind: "failed";
+ readonly message: string;
+ readonly completedMutations: readonly RemoteAuthCompletedMutation[];
+ };
+
+/** Human-readable actions that completed and cannot be rolled back automatically. */
+export function describeRemoteAuthCompletedMutations(
+ completedMutations: readonly RemoteAuthCompletedMutation[],
+): string[] {
+ return completedMutations.map((mutation) => {
+ switch (mutation.kind) {
+ case "vercel-login":
+ return "logged in to Vercel";
+ }
+ });
+}
+
+/** Adds the mutations that cannot be rolled back to an authentication failure. */
+export function appendRemoteAuthMutationSummary(
+ message: string,
+ completedMutations: readonly RemoteAuthCompletedMutation[],
+): string {
+ const completed = describeRemoteAuthCompletedMutations(completedMutations);
+ return completed.length === 0
+ ? message
+ : `${message} Completed before the failure: ${completed.join(", ")}.`;
+}
diff --git a/packages/eve/src/cli/dev/tui/remote-connection-probe.ts b/packages/eve/src/cli/dev/tui/remote-connection-probe.ts
new file mode 100644
index 000000000..3464d4626
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/remote-connection-probe.ts
@@ -0,0 +1,59 @@
+import { ClientError, type Client } from "#client/index.js";
+import { isVercelAuthChallenge } from "#services/dev-client/vercel-auth-error.js";
+import { toErrorMessage } from "#shared/errors.js";
+import { isObject } from "#shared/guards.js";
+
+import type { RemoteConnectionState } from "./remote-connection-types.js";
+
+export type RemoteProbeResult = Extract<
+ RemoteConnectionState,
+ { state: "ready" | "auth-required" | "unavailable" }
+>;
+
+function isEveOidcChallenge(error: unknown): boolean {
+ if (!(error instanceof ClientError) || error.status !== 401) return false;
+
+ try {
+ const body: unknown = JSON.parse(error.body);
+ return (
+ isObject(body) &&
+ body.ok === false &&
+ body.code === "unauthorized" &&
+ body.error === "Authorization is required for this route."
+ );
+ } catch {
+ return false;
+ }
+}
+
+export function classifyRemoteError(error: unknown): RemoteProbeResult {
+ if (isVercelAuthChallenge(error)) {
+ return {
+ state: "auth-required",
+ challenge: { kind: "vercel-deployment-protection" },
+ };
+ }
+ if (isEveOidcChallenge(error)) {
+ return {
+ state: "auth-required",
+ challenge: { kind: "eve-oidc" },
+ };
+ }
+ if (error instanceof ClientError) {
+ return { state: "unavailable", failure: { message: error.message } };
+ }
+ return {
+ state: "unavailable",
+ failure: { message: toErrorMessage(error) },
+ };
+}
+
+export async function probeRemoteInfo(input: {
+ readonly client: Client;
+}): Promise<RemoteProbeResult> {
+ try {
+ return { state: "ready", info: await input.client.info() };
+ } catch (error) {
+ return classifyRemoteError(error);
+ }
+}
diff --git a/packages/eve/src/cli/dev/tui/remote-connection-types.ts b/packages/eve/src/cli/dev/tui/remote-connection-types.ts
new file mode 100644
index 000000000..51fe9f3e6
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/remote-connection-types.ts
@@ -0,0 +1,83 @@
+import type { Client, AgentInfoResult } from "#client/index.js";
+import type { DevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";
+import type { DevelopmentOidcTokenResolution } from "#services/dev-client/request-headers.js";
+import type {
+ ResolvedVercelDeployment,
+ VercelDeploymentResolution,
+} from "#setup/vercel-deployment.js";
+
+import type { RemoteAuthCompletedMutation, RemoteAuthPreparation } from "./remote-auth-result.js";
+import type { RemoteDevelopmentTarget } from "./target.js";
+
+export type RemoteAuthChallenge =
+ | { readonly kind: "eve-oidc" }
+ | { readonly kind: "vercel-deployment-protection" };
+
+interface RemoteRequestFailure {
+ readonly message: string;
+}
+
+export type RemoteConnectionState =
+ | { readonly state: "checking" }
+ | { readonly state: "ready"; readonly info: AgentInfoResult }
+ | {
+ readonly state: "auth-required";
+ readonly challenge: RemoteAuthChallenge;
+ }
+ | {
+ readonly state: "authenticating";
+ readonly challenge: RemoteAuthChallenge;
+ }
+ | {
+ readonly state: "auth-failed";
+ readonly challenge: RemoteAuthChallenge;
+ }
+ | {
+ readonly state: "unavailable";
+ readonly failure: RemoteRequestFailure;
+ };
+
+export interface RemoteConnectionSnapshot {
+ readonly target: RemoteDevelopmentTarget;
+ readonly connection: RemoteConnectionState;
+ /** Last deployment identity resolved from Vercel for this target. */
+ readonly deployment?: ResolvedVercelDeployment;
+}
+
+export type RemoteAuthCompletion =
+ | { readonly kind: "authenticated" }
+ | {
+ readonly kind: "cancelled";
+ readonly completedMutations: readonly RemoteAuthCompletedMutation[];
+ }
+ | {
+ readonly kind: "failed";
+ readonly message: string;
+ }
+ | {
+ readonly kind: "unavailable";
+ readonly failure: RemoteRequestFailure;
+ };
+
+export interface RemoteConnectionController {
+ current(): RemoteConnectionSnapshot;
+ check(): Promise<RemoteConnectionState>;
+ authenticate(
+ prepare: (signal: AbortSignal) => Promise<RemoteAuthPreparation>,
+ signal?: AbortSignal,
+ ): Promise<RemoteAuthCompletion>;
+ reportFailure(error: unknown): RemoteConnectionState;
+ dispose(): void;
+}
+
+export interface RemoteConnectionControllerOptions {
+ readonly client: Client;
+ readonly credentials: DevelopmentCredentialGate;
+ readonly target: RemoteDevelopmentTarget;
+ /** Resolves an ambient token only after Vercel proves the exact target origin. */
+ readonly resolveOidcToken?: (
+ deployment: Pick<ResolvedVercelDeployment, "ownerId" | "projectId">,
+ ) => Promise<DevelopmentOidcTokenResolution>;
+ readonly resolveDeployment?: (signal: AbortSignal) => Promise<VercelDeploymentResolution>;
+ readonly onChange: (snapshot: RemoteConnectionSnapshot) => void;
+}
diff --git a/packages/eve/src/cli/dev/tui/remote-connection.test.ts b/packages/eve/src/cli/dev/tui/remote-connection.test.ts
new file mode 100644
index 000000000..0e90350a8
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/remote-connection.test.ts
@@ -0,0 +1,389 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { Client, ClientError, type AgentInfoResult } from "#client/index.js";
+import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";
+import {
+ createDevelopmentCredentialGate,
+ type DevelopmentCredentialGate,
+} from "#services/dev-client/credential-gate.js";
+import type { VercelDeploymentResolution } from "#setup/vercel-deployment.js";
+
+import type { RemoteAuthPreparation } from "./remote-auth-result.js";
+import {
+ createRemoteConnectionController,
+ type RemoteConnectionControllerOptions,
+} from "./remote-connection.js";
+import { remoteHost, type RemoteDevelopmentTarget } from "./target.js";
+
+const TARGET = {
+ kind: "remote",
+ serverUrl: "https://vpoke.playground-vercel.tools",
+ workspaceRoot: "/tmp/weather-agent",
+} satisfies RemoteDevelopmentTarget;
+
+const VERIFIED_TARGET = await resolveTestVercelTarget({
+ host: remoteHost(TARGET),
+ projectId: "prj_inbound",
+ projectName: "inbound",
+ environment: "production",
+});
+const RESOLVED_DEPLOYMENT = {
+ kind: "resolved",
+ target: VERIFIED_TARGET,
+} satisfies VercelDeploymentResolution;
+
+const NEWER_VERIFIED_TARGET = await resolveTestVercelTarget({
+ host: remoteHost(TARGET),
+ projectId: "prj_inbound_next",
+ projectName: "inbound-next",
+});
+
+const INFO: AgentInfoResult = {
+ agent: {
+ agentRoot: "/tmp/weather-agent/agent",
+ appRoot: "/tmp/weather-agent",
+ model: { id: "gpt-5" },
+ name: "Weather Agent",
+ },
+ capabilities: { devRoutes: true },
+ channels: { authored: [], available: [], disabledFramework: [], framework: [] },
+ connections: [],
+ diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
+ hooks: [],
+ instructions: {
+ dynamic: [],
+ static: {
+ logicalPath: "agent/instructions.md",
+ markdown: "You are a weather assistant.",
+ name: "instructions",
+ sourceKind: "markdown",
+ },
+ },
+ kind: "eve-agent-info",
+ mode: "development",
+ sandbox: null,
+ schedules: [],
+ skills: { dynamic: [], static: [] },
+ subagents: { local: [], total: 0 },
+ tools: {
+ authored: [],
+ available: [],
+ disabledFramework: [],
+ dynamic: [],
+ framework: [],
+ reserved: [],
+ },
+ version: 1,
+ workflow: { enabled: false, toolName: "Workflow" },
+ workspace: { resourceRoot: null, rootEntries: [] },
+};
+
+const VERCEL_SSO_CHALLENGE = `
+<title>Authentication Required</title>
+<a href="https://vercel.com/sso-api?url=https%3A%2F%2Fvpoke.playground-vercel.tools">
+ Vercel Authentication
+</a>`;
+function eveUnauthorized(error = "Authorization is required for this route."): ClientError {
+ return new ClientError(401, JSON.stringify({ code: "unauthorized", error, ok: false }));
+}
+
+type HarnessOptions = Pick<
+ RemoteConnectionControllerOptions,
+ "resolveDeployment" | "resolveOidcToken"
+> & {
+ readonly info?: (credentials: DevelopmentCredentialGate) => Promise<AgentInfoResult>;
+};
+
+function createHarness(options: HarnessOptions = {}) {
+ const { info = async () => INFO, ...controllerOptions } = options;
+ const credentials = createDevelopmentCredentialGate(TARGET.serverUrl);
+ const client = new Client({ host: TARGET.serverUrl });
+ const infoSpy = vi.spyOn(client, "info").mockImplementation(() => info(credentials));
+ const controller = createRemoteConnectionController({
+ ...controllerOptions,
+ client,
+ credentials,
+ target: TARGET,
+ onChange: () => {},
+ });
+ return { client, controller, credentials, info: infoSpy };
+}
+
+function deferred<T>() {
+ let settle: ((value: T) => void) | undefined;
+ const promise = new Promise<T>((resolve) => {
+ settle = resolve;
+ });
+ return {
+ promise,
+ resolve(value: T): void {
+ if (settle === undefined) throw new Error("Deferred promise was not initialized.");
+ settle(value);
+ },
+ };
+}
+
+async function checkFailure(error: unknown) {
+ const { controller } = createHarness({
+ info: async () => {
+ throw error;
+ },
+ });
+ return await controller.check();
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+});
+
+describe("createRemoteConnectionController", () => {
+ it.each([
+ {
+ name: "the exact Eve OIDC challenge",
+ error: eveUnauthorized(),
+ expected: { state: "auth-required", challenge: { kind: "eve-oidc" } },
+ },
+ {
+ name: "an Eve-shaped 401 with different copy",
+ error: eveUnauthorized("Authenticate with this unrelated service."),
+ expected: { state: "unavailable" },
+ },
+ {
+ name: "the Vercel Deployment Protection challenge",
+ error: new ClientError(401, VERCEL_SSO_CHALLENGE),
+ expected: {
+ state: "auth-required",
+ challenge: { kind: "vercel-deployment-protection" },
+ },
+ },
+ {
+ name: "an ordinary HTTP failure",
+ error: new ClientError(503, "Unavailable"),
+ expected: { state: "unavailable", failure: { message: "Unavailable" } },
+ },
+ {
+ name: "a network failure",
+ error: new Error("offline"),
+ expected: { state: "unavailable", failure: { message: "offline" } },
+ },
+ {
+ name: "an invalid response",
+ error: new SyntaxError("bad JSON"),
+ expected: { state: "unavailable", failure: { message: "bad JSON" } },
+ },
+ ])("classifies $name", async ({ error, expected }) => {
+ await expect(checkFailure(error)).resolves.toMatchObject(expected);
+ });
+
+ it("resolves ambient credentials only after deployment authority is established", async () => {
+ const pending = deferred<VercelDeploymentResolution>();
+ const resolveDeployment = vi.fn(() => pending.promise);
+ const resolveOidcToken = vi.fn(async () => ({
+ kind: "resolved" as const,
+ token: " ambient-token ",
+ }));
+ const harness = createHarness({
+ resolveDeployment,
+ resolveOidcToken,
+ info: async (credentials) => {
+ await expect(credentials.resolveToken()).resolves.toBe("ambient-token");
+ return INFO;
+ },
+ });
+
+ const check = harness.controller.check();
+ await vi.waitFor(() => expect(resolveDeployment).toHaveBeenCalledOnce());
+ expect(harness.info).not.toHaveBeenCalled();
+ expect(resolveOidcToken).not.toHaveBeenCalled();
+
+ pending.resolve(RESOLVED_DEPLOYMENT);
+ await expect(check).resolves.toEqual({ state: "ready", info: INFO });
+ expect(harness.controller.current().deployment).toEqual(VERIFIED_TARGET.deployment);
+ expect(resolveOidcToken).toHaveBeenCalledWith(VERIFIED_TARGET.deployment);
+ });
+
+ it("uses the authenticated token resolver for every request", async () => {
+ let request = 0;
+ const info = vi.fn(async (credentials: DevelopmentCredentialGate) => {
+ request += 1;
+ if (request === 1) throw eveUnauthorized();
+ await expect(credentials.resolveToken()).resolves.toBe("first-token");
+ return INFO;
+ });
+ const resolveToken = vi
+ .fn<() => Promise<string>>()
+ .mockResolvedValueOnce(" first-token ")
+ .mockResolvedValueOnce("second-token");
+ const harness = createHarness({ info });
+
+ await harness.controller.check();
+ await expect(
+ harness.controller.authenticate(async () => ({
+ kind: "prepared",
+ target: VERIFIED_TARGET,
+ resolveToken,
+ completedMutations: [],
+ })),
+ ).resolves.toEqual({ kind: "authenticated" });
+
+ expect(resolveToken).toHaveBeenCalledOnce();
+ await expect(harness.credentials.resolveToken()).resolves.toBe("second-token");
+ expect(harness.controller.current().connection).toEqual({ state: "ready", info: INFO });
+ });
+
+ it("keeps a ready connection when manual authentication preparation fails", async () => {
+ const harness = createHarness();
+
+ await expect(harness.controller.check()).resolves.toEqual({ state: "ready", info: INFO });
+ await expect(
+ harness.controller.authenticate(async () => ({
+ kind: "failed",
+ message: "Vercel login failed.",
+ completedMutations: [],
+ })),
+ ).resolves.toEqual({ kind: "failed", message: "Vercel login failed." });
+ expect(harness.controller.current().connection).toEqual({ state: "ready", info: INFO });
+ });
+
+ it("reports a rejected token and its completed mutations without retrying", async () => {
+ const info = vi.fn<() => Promise<AgentInfoResult>>().mockRejectedValue(eveUnauthorized());
+ const attempt = vi.fn<() => Promise<RemoteAuthPreparation>>(async () => ({
+ kind: "prepared",
+ target: VERIFIED_TARGET,
+ resolveToken: async () => "rejected-token",
+ completedMutations: [{ kind: "vercel-login" }],
+ }));
+ const harness = createHarness({ info });
+
+ await harness.controller.check();
+ await expect(harness.controller.authenticate(attempt)).resolves.toEqual({
+ kind: "failed",
+ message:
+ "The selected Vercel project did not authorize vpoke.playground-vercel.tools. " +
+ "Completed before the failure: logged in to Vercel.",
+ });
+ expect(attempt).toHaveBeenCalledOnce();
+ expect(info).toHaveBeenCalledTimes(2);
+ await expect(harness.credentials.resolveToken()).resolves.toBe("");
+ });
+
+ it("restores prior connection authority when verification is cancelled", async () => {
+ let request = 0;
+ const verification = deferred<AgentInfoResult>();
+ const verificationStarted = deferred<void>();
+ const harness = createHarness({
+ info: async (credentials) => {
+ request += 1;
+ if (request === 1) throw eveUnauthorized();
+ await credentials.resolveToken();
+ verificationStarted.resolve(undefined);
+ return await verification.promise;
+ },
+ });
+ harness.credentials.authorize({
+ target: VERIFIED_TARGET,
+ resolveToken: async () => "previous-token",
+ });
+ await harness.controller.check();
+ const previous = harness.controller.current().connection;
+
+ const abort = new AbortController();
+ const authentication = harness.controller.authenticate(
+ async () => ({
+ kind: "prepared",
+ target: NEWER_VERIFIED_TARGET,
+ resolveToken: async () => "candidate-token",
+ completedMutations: [],
+ }),
+ abort.signal,
+ );
+ await verificationStarted.promise;
+ abort.abort();
+ verification.resolve(INFO);
+ await expect(authentication).resolves.toEqual({ kind: "cancelled", completedMutations: [] });
+ expect(harness.controller.current().connection).toEqual(previous);
+ expect(harness.controller.current().deployment).toBeUndefined();
+ await expect(harness.credentials.resolveToken()).resolves.toBe("previous-token");
+ });
+
+ it("clears an authenticated credential before starting a new check", async () => {
+ const tokens: string[] = [];
+ let request = 0;
+ const harness = createHarness({
+ info: async (credentials) => {
+ request += 1;
+ tokens.push(await credentials.resolveToken());
+ if (request === 1) throw eveUnauthorized();
+ return INFO;
+ },
+ });
+
+ await expect(harness.controller.check()).resolves.toMatchObject({ state: "auth-required" });
+ await expect(
+ harness.controller.authenticate(async () => ({
+ kind: "prepared",
+ target: VERIFIED_TARGET,
+ resolveToken: async () => "authenticated-token",
+ completedMutations: [],
+ })),
+ ).resolves.toEqual({ kind: "authenticated" });
+ await expect(harness.controller.check()).resolves.toEqual({ state: "ready", info: INFO });
+
+ expect(tokens[0]).toBe("");
+ expect(tokens[1]).toBe("authenticated-token");
+ expect(tokens[2]).toBe("");
+ });
+
+ it("clears ambient credentials before a later unverified check", async () => {
+ const tokens: string[] = [];
+ const resolveDeployment = vi
+ .fn<(signal: AbortSignal) => Promise<VercelDeploymentResolution>>()
+ .mockResolvedValueOnce(RESOLVED_DEPLOYMENT)
+ .mockResolvedValueOnce({ kind: "not-found" });
+ const harness = createHarness({
+ resolveDeployment,
+ resolveOidcToken: async () => ({ kind: "resolved", token: "ambient-token" }),
+ info: async (credentials) => {
+ tokens.push(await credentials.resolveToken());
+ return INFO;
+ },
+ });
+
+ await expect(harness.controller.check()).resolves.toEqual({ state: "ready", info: INFO });
+ await expect(harness.controller.check()).resolves.toEqual({ state: "ready", info: INFO });
+
+ expect(tokens[0]).toBe("ambient-token");
+ expect(tokens[1]).toBe("");
+ expect(harness.controller.current().deployment).toBeUndefined();
+ });
+
+ it("does not publish a stale deployment lookup", async () => {
+ const pending: Array<{
+ readonly signal: AbortSignal;
+ readonly resolve: (resolution: VercelDeploymentResolution) => void;
+ }> = [];
+ const harness = createHarness({
+ resolveDeployment: (signal) => new Promise((resolve) => pending.push({ signal, resolve })),
+ resolveOidcToken: async () => ({ kind: "resolved", token: "ambient-token" }),
+ });
+
+ const first = harness.controller.check();
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ const second = harness.controller.check();
+ await vi.waitFor(() => expect(pending).toHaveLength(2));
+ const [older, newer] = pending;
+ if (older === undefined || newer === undefined) throw new Error("Missing deployment lookup.");
+ expect(older.signal.aborted).toBe(true);
+
+ newer.resolve({ kind: "resolved", target: NEWER_VERIFIED_TARGET });
+ await second;
+ older.resolve(RESOLVED_DEPLOYMENT);
+ await first;
+ expect(harness.controller.current().deployment).toEqual(NEWER_VERIFIED_TARGET.deployment);
+ await expect(harness.credentials.resolveToken()).resolves.toBe("ambient-token");
+
+ harness.controller.dispose();
+ await expect(harness.credentials.resolveToken()).resolves.toBe("");
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/remote-connection.ts b/packages/eve/src/cli/dev/tui/remote-connection.ts
new file mode 100644
index 000000000..19beaf18d
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/remote-connection.ts
@@ -0,0 +1,227 @@
+import type { ResolvedVercelDeployment, VerifiedVercelTarget } from "#setup/vercel-deployment.js";
+import { toErrorMessage } from "#shared/errors.js";
+
+import {
+ appendRemoteAuthMutationSummary,
+ type RemoteAuthPreparation,
+} from "./remote-auth-result.js";
+import { classifyRemoteError, probeRemoteInfo } from "./remote-connection-probe.js";
+import type {
+ RemoteAuthChallenge,
+ RemoteAuthCompletion,
+ RemoteConnectionController,
+ RemoteConnectionControllerOptions,
+ RemoteConnectionSnapshot,
+ RemoteConnectionState,
+} from "./remote-connection-types.js";
+import { remoteHost } from "./target.js";
+
+export type {
+ RemoteAuthChallenge,
+ RemoteAuthCompletion,
+ RemoteConnectionController,
+ RemoteConnectionControllerOptions,
+ RemoteConnectionSnapshot,
+ RemoteConnectionState,
+} from "./remote-connection-types.js";
+
+function challengeFor(state: RemoteConnectionState): RemoteAuthChallenge {
+ switch (state.state) {
+ case "auth-required":
+ case "authenticating":
+ case "auth-failed":
+ return state.challenge;
+ case "checking":
+ case "ready":
+ case "unavailable":
+ return { kind: "eve-oidc" };
+ }
+}
+
+export function createRemoteConnectionController(
+ options: RemoteConnectionControllerOptions,
+): RemoteConnectionController {
+ let connection: RemoteConnectionState = { state: "checking" };
+ let deployment: ResolvedVercelDeployment | undefined;
+ let operationAbort: AbortController | undefined;
+ let restoreActiveCredentials: (() => void) | undefined;
+ let operationGeneration = 0;
+ let disposed = false;
+
+ const snapshot = (): RemoteConnectionSnapshot =>
+ deployment === undefined
+ ? { target: options.target, connection }
+ : { target: options.target, connection, deployment };
+ const update = (next: RemoteConnectionState): RemoteConnectionState => {
+ connection = next;
+ if (!disposed) options.onChange(snapshot());
+ return next;
+ };
+ const beginOperation = (
+ parentSignal?: AbortSignal,
+ ): { readonly generation: number; readonly signal: AbortSignal } => {
+ operationAbort?.abort();
+ const abort = new AbortController();
+ operationAbort = abort;
+ const signal =
+ parentSignal === undefined ? abort.signal : AbortSignal.any([abort.signal, parentSignal]);
+ return { generation: ++operationGeneration, signal };
+ };
+ const isCurrent = (generation: number): boolean =>
+ !disposed && generation === operationGeneration;
+ const publishTarget = (target: VerifiedVercelTarget): void => {
+ deployment = target.deployment;
+ if (!disposed) options.onChange(snapshot());
+ };
+ const authorizeResolvedTarget = async (
+ signal: AbortSignal,
+ generation: number,
+ ): Promise<(() => void) | undefined> => {
+ const resolveDeployment = options.resolveDeployment;
+ if (resolveDeployment === undefined) return;
+ try {
+ const resolved = await resolveDeployment(signal);
+ if (!isCurrent(generation) || signal.aborted || resolved.kind !== "resolved") return;
+ publishTarget(resolved.target);
+ const resolveToken = async () =>
+ (await options.resolveOidcToken?.(resolved.target.deployment)) ?? "";
+ return options.credentials.authorize({ target: resolved.target, resolveToken });
+ } catch {
+ // Deployment metadata and ambient credentials are optional. The anonymous
+ // probe below remains the authoritative connection result.
+ }
+ return undefined;
+ };
+
+ options.onChange(snapshot());
+
+ return {
+ current: snapshot,
+
+ async check(): Promise<RemoteConnectionState> {
+ const operation = beginOperation();
+ restoreActiveCredentials?.();
+ restoreActiveCredentials = undefined;
+ deployment = undefined;
+ update({ state: "checking" });
+ const restoreCredentials = await authorizeResolvedTarget(
+ operation.signal,
+ operation.generation,
+ );
+ if (!isCurrent(operation.generation)) {
+ restoreCredentials?.();
+ return connection;
+ }
+ restoreActiveCredentials = restoreCredentials;
+ const probe = await probeRemoteInfo({ client: options.client });
+ if (!isCurrent(operation.generation)) return connection;
+ return update(probe);
+ },
+
+ async authenticate(
+ prepare: (signal: AbortSignal) => Promise<RemoteAuthPreparation>,
+ signal?: AbortSignal,
+ ): Promise<RemoteAuthCompletion> {
+ const operation = beginOperation(signal);
+ const previous = connection;
+ const challenge = challengeFor(connection);
+ update({ state: "authenticating", challenge });
+
+ let preparation: RemoteAuthPreparation;
+ try {
+ preparation = await prepare(operation.signal);
+ } catch (error) {
+ preparation = {
+ kind: "failed",
+ message: toErrorMessage(error),
+ completedMutations: [],
+ };
+ }
+
+ if (!isCurrent(operation.generation)) {
+ return { kind: "cancelled", completedMutations: preparation.completedMutations };
+ }
+ if (preparation.kind === "cancelled") {
+ update(previous);
+ return { kind: "cancelled", completedMutations: preparation.completedMutations };
+ }
+ if (preparation.kind === "failed") {
+ update(previous.state === "ready" ? previous : { state: "auth-failed", challenge });
+ return { kind: "failed", message: preparation.message };
+ }
+ if (operation.signal.aborted) {
+ update(previous);
+ return { kind: "cancelled", completedMutations: preparation.completedMutations };
+ }
+
+ const restorePreviousCredentials = restoreActiveCredentials;
+ let restoreCandidateCredentials: () => void;
+ try {
+ restoreCandidateCredentials = options.credentials.authorize({
+ target: preparation.target,
+ resolveToken: preparation.resolveToken,
+ });
+ } catch (error) {
+ const message = appendRemoteAuthMutationSummary(
+ toErrorMessage(error),
+ preparation.completedMutations,
+ );
+ update({ state: "auth-failed", challenge });
+ return { kind: "failed", message };
+ }
+ const verified = await probeRemoteInfo({ client: options.client });
+ if (!isCurrent(operation.generation)) {
+ restoreCandidateCredentials();
+ return { kind: "cancelled", completedMutations: preparation.completedMutations };
+ }
+ if (operation.signal.aborted) {
+ restoreCandidateCredentials();
+ update(previous);
+ return { kind: "cancelled", completedMutations: preparation.completedMutations };
+ }
+ if (verified.state === "ready") {
+ publishTarget(preparation.target);
+ restoreActiveCredentials = () => {
+ restoreCandidateCredentials();
+ restorePreviousCredentials?.();
+ };
+ update(verified);
+ return { kind: "authenticated" };
+ }
+ restoreCandidateCredentials();
+ if (verified.state === "auth-required") {
+ const message = appendRemoteAuthMutationSummary(
+ `The selected Vercel project did not authorize ${remoteHost(options.target)}.`,
+ preparation.completedMutations,
+ );
+ update({ state: "auth-failed", challenge: verified.challenge });
+ return { kind: "failed", message };
+ }
+
+ const failure = {
+ ...verified.failure,
+ message: appendRemoteAuthMutationSummary(
+ verified.failure.message,
+ preparation.completedMutations,
+ ),
+ };
+ update({ state: "unavailable", failure });
+ return { kind: "unavailable", failure };
+ },
+
+ reportFailure(error: unknown): RemoteConnectionState {
+ operationAbort?.abort();
+ operationGeneration += 1;
+ return update(classifyRemoteError(error));
+ },
+
+ dispose(): void {
+ disposed = true;
+ operationGeneration += 1;
+ operationAbort?.abort();
+ operationAbort = undefined;
+ restoreActiveCredentials?.();
+ restoreActiveCredentials = undefined;
+ },
+ };
+}
diff --git a/packages/eve/src/cli/dev/tui/target.ts b/packages/eve/src/cli/dev/tui/target.ts
index 3cef97d01..7d16af687 100644
--- a/packages/eve/src/cli/dev/tui/target.ts
+++ b/packages/eve/src/cli/dev/tui/target.ts
@@ -43,3 +43,8 @@ export function resolveTuiTitle(input: {
.join(" ");
return humanized.length > 0 ? humanized : undefined;
}
+
+/** Returns the URL host shown in remote status and authentication messages. */
+export function remoteHost(target: RemoteDevelopmentTarget): string {
+ return new URL(target.serverUrl).host;
+}
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
new file mode 100644
index 000000000..56d0d67cd
--- /dev/null
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -0,0 +1,210 @@
+import { z } from "zod";
+
+const source = z.object({
+ exportName: z.string().optional(),
+ logicalPath: z.string(),
+ sourceId: z.string().optional(),
+ sourceKind: z.string(),
+});
+
+const entry = source.extend({ name: z.string() });
+
+const modelRouting = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("gateway"), target: z.string(), byok: z.string().optional() }),
+ z.object({ kind: z.literal("external"), provider: z.string() }),
+]);
+
+const modelEndpoint = z.union([
+ z.object({ kind: z.literal("external"), provider: z.string() }),
+ z.object({
+ kind: z.literal("gateway"),
+ connected: z.literal(true),
+ credential: z.enum(["api-key", "oidc"]),
+ }),
+ z.object({ kind: z.literal("gateway"), connected: z.literal(false) }),
+]);
+
+const tool = entry.extend({
+ description: z.string(),
+ hasAuth: z.boolean(),
+ hasExecute: z.boolean(),
+ hasModelOutputProjection: z.boolean(),
+ hasOutputSchema: z.boolean(),
+ inputSchema: z.unknown(),
+ origin: z.enum(["authored", "framework"]),
+ outputSchema: z.unknown().optional(),
+ replacesFrameworkTool: z.boolean(),
+ requiresApproval: z.boolean(),
+});
+
+const frameworkTool = tool.extend({
+ disabledByAuthor: z.boolean(),
+ replacedByAuthoredTool: z.boolean(),
+ status: z.enum(["active", "disabled", "replaced"]),
+});
+
+const dynamicResolver = source.extend({
+ eventNames: z.array(z.string()),
+ origin: z.enum(["authored", "framework"]),
+ slug: z.string(),
+});
+
+const skill = entry.extend({
+ description: z.string(),
+ license: z.string().optional(),
+ markdown: z.string(),
+ metadata: z.record(z.string(), z.string()).optional(),
+});
+
+const instructions = entry.extend({ markdown: z.string() });
+
+const schedule = entry.extend({
+ cron: z.string(),
+ hasRun: z.boolean(),
+ markdown: z.string().optional(),
+});
+
+const subagent = entry.extend({
+ description: z.string(),
+ entryPath: z.string(),
+ nodeId: z.string(),
+ rootPath: z.string(),
+ summary: z.object({
+ channels: z.number(),
+ connections: z.number(),
+ hooks: z.number(),
+ instructions: z.boolean(),
+ schedules: z.number(),
+ skills: z.number(),
+ tools: z.number(),
+ }),
+});
+
+const channel = entry.extend({
+ adapterKind: z.string().optional(),
+ method: z.string(),
+ origin: z.enum(["authored", "framework"]),
+ urlPath: z.string(),
+});
+
+const frameworkChannel = channel.extend({
+ disabledByAuthor: z.boolean(),
+ replacedByAuthoredChannel: z.boolean(),
+ status: z.enum(["active", "disabled", "replaced"]),
+});
+
+const connection = source.extend({
+ connectionName: z.string(),
+ description: z.string(),
+ hasApproval: z.boolean(),
+ hasAuthorization: z.boolean(),
+ hasHeaders: z.boolean(),
+ protocol: z.string(),
+ toolFilter: z.unknown().optional(),
+ url: z.string(),
+});
+
+const hook = source.extend({
+ eventNames: z.array(z.string()),
+ slug: z.string(),
+});
+
+const sandbox = source.extend({
+ backendKind: z.string().optional(),
+ description: z.string().optional(),
+ hasBootstrap: z.boolean(),
+ hasOnSession: z.boolean(),
+ revalidationKey: z.string().optional(),
+ sourceHash: z.string().optional(),
+});
+
+/** Runtime contract for the complete `/eve/v1/info` response. */
+export const AgentInfoResultSchema = z.object({
+ agent: z.object({
+ agentRoot: z.string(),
+ appRoot: z.string(),
+ configSource: source.optional(),
+ description: z.string().optional(),
+ model: z.object({
+ contextWindowTokens: z.number().optional(),
+ id: z.string(),
+ providerOptions: z.unknown().optional(),
+ source: source.optional(),
+ routing: modelRouting.optional(),
+ endpoint: modelEndpoint.optional(),
+ }),
+ name: z.string(),
+ outputSchema: z.unknown().optional(),
+ }),
+ capabilities: z.object({ devRoutes: z.boolean() }),
+ channels: z.object({
+ authored: z.array(channel),
+ available: z.array(channel),
+ disabledFramework: z.array(z.string()),
+ framework: z.array(frameworkChannel),
+ }),
+ connections: z.array(connection),
+ diagnostics: z.object({
+ discoveryErrors: z.number(),
+ discoveryWarnings: z.number(),
+ }),
+ hooks: z.array(hook),
+ instructions: z.object({
+ dynamic: z.array(dynamicResolver),
+ static: instructions.nullable(),
+ }),
+ kind: z.literal("eve-agent-info"),
+ mode: z.enum(["development", "production"]),
+ sandbox: sandbox.nullable(),
+ schedules: z.array(schedule),
+ skills: z.object({
+ dynamic: z.array(dynamicResolver),
+ static: z.array(skill),
+ }),
+ subagents: z.object({
+ local: z.array(subagent),
+ total: z.number(),
+ }),
+ tools: z.object({
+ authored: z.array(tool),
+ available: z.array(tool),
+ disabledFramework: z.array(z.string()),
+ dynamic: z.array(dynamicResolver),
+ framework: z.array(frameworkTool),
+ reserved: z.array(z.string()),
+ }),
+ version: z.literal(1),
+ workflow: z.object({
+ enabled: z.boolean(),
+ toolName: z.string(),
+ }),
+ workspace: z.object({
+ resourceRoot: z.unknown(),
+ rootEntries: z.array(z.string()),
+ }),
+});
+
+type ReadonlyDeep<T> = T extends readonly (infer Item)[]
+ ? readonly ReadonlyDeep<Item>[]
+ : T extends object
+ ? { readonly [Key in keyof T]: ReadonlyDeep<T[Key]> }
+ : T;
+
+export type AgentInfoSource = ReadonlyDeep<z.output<typeof source>>;
+export type AgentInfoEntry = ReadonlyDeep<z.output<typeof entry>>;
+export type AgentInfoToolEntry = ReadonlyDeep<z.output<typeof tool>>;
+export type AgentInfoFrameworkToolEntry = ReadonlyDeep<z.output<typeof frameworkTool>>;
+export type AgentInfoDynamicResolverEntry = ReadonlyDeep<z.output<typeof dynamicResolver>>;
+export type AgentInfoTools = AgentInfoResult["tools"];
+export type AgentInfoSkillEntry = ReadonlyDeep<z.output<typeof skill>>;
+export type AgentInfoInstructionsEntry = ReadonlyDeep<z.output<typeof instructions>>;
+export type AgentInfoInstructions = AgentInfoResult["instructions"];
+export type AgentInfoScheduleEntry = ReadonlyDeep<z.output<typeof schedule>>;
+export type AgentInfoSubagentEntry = ReadonlyDeep<z.output<typeof subagent>>;
+export type AgentInfoChannelEntry = ReadonlyDeep<z.output<typeof channel>>;
+export type AgentInfoFrameworkChannelEntry = ReadonlyDeep<z.output<typeof frameworkChannel>>;
+export type AgentInfoChannels = AgentInfoResult["channels"];
+export type AgentInfoConnectionEntry = ReadonlyDeep<z.output<typeof connection>>;
+export type AgentInfoHookEntry = ReadonlyDeep<z.output<typeof hook>>;
+export type AgentInfoSandboxEntry = ReadonlyDeep<z.output<typeof sandbox>>;
+export type AgentInfoResult = ReadonlyDeep<z.output<typeof AgentInfoResultSchema>>;
diff --git a/packages/eve/src/client/client.test.ts b/packages/eve/src/client/client.test.ts
index e7441ae33..d1d25db9d 100644
--- a/packages/eve/src/client/client.test.ts
+++ b/packages/eve/src/client/client.test.ts
@@ -1,16 +1,53 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { Client } from "#client/client.js";
+import type { AgentInfoResult } from "#client/types.js";
+import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";
+import { resolveRemoteDevelopmentClientOptions } from "#services/dev-client/client-options.js";
+import { createDevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";
+
+const AGENT_INFO: AgentInfoResult = {
+ agent: {
+ agentRoot: "/tmp/weather-agent/agent",
+ appRoot: "/tmp/weather-agent",
+ model: { id: "openai/gpt-5.5" },
+ name: "Weather Agent",
+ },
+ capabilities: { devRoutes: true },
+ channels: { authored: [], available: [], disabledFramework: [], framework: [] },
+ connections: [],
+ diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
+ hooks: [],
+ instructions: { dynamic: [], static: null },
+ kind: "eve-agent-info",
+ mode: "development",
+ sandbox: null,
+ schedules: [],
+ skills: { dynamic: [], static: [] },
+ subagents: { local: [], total: 0 },
+ tools: {
+ authored: [],
+ available: [],
+ disabledFramework: [],
+ dynamic: [],
+ framework: [],
+ reserved: [],
+ },
+ version: 1,
+ workflow: { enabled: false, toolName: "Workflow" },
+ workspace: { resourceRoot: null, rootEntries: [] },
+};
afterEach(() => {
vi.restoreAllMocks();
+ vi.unstubAllEnvs();
});
describe("Client request policy", () => {
it("enforces its redirect policy for info, health, raw fetch, and sessions", async () => {
const fetchMock = vi
.spyOn(globalThis, "fetch")
- .mockResolvedValueOnce(Response.json({ agent: {} }))
+ .mockResolvedValueOnce(Response.json(AGENT_INFO))
.mockResolvedValueOnce(Response.json({ ok: true, status: "ready", workflowId: "wf" }))
.mockResolvedValueOnce(new Response(null, { status: 204 }))
.mockResolvedValueOnce(
@@ -31,4 +68,131 @@ describe("Client request policy", () => {
expect(init?.redirect).toBe("manual");
}
});
+
+ it("expands vercelOidc auth into the bearer and trusted-oidc headers", async () => {
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValueOnce(Response.json(AGENT_INFO));
+ const client = new Client({
+ host: "https://eve.test",
+ auth: { vercelOidc: { token: () => Promise.resolve("oidc-tok") } },
+ });
+
+ await client.info();
+
+ const sent = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);
+ expect(sent.get("authorization")).toBe("Bearer oidc-tok");
+ expect(sent.get("x-vercel-trusted-oidc-idp-token")).toBe("oidc-tok");
+ });
+
+ it("keeps an in-flight remote request on one credential snapshot after rollback", async () => {
+ vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "bypass-secret");
+ const target = await resolveTestVercelTarget({ host: "eve.test", projectId: "prj_eve" });
+ const credentials = createDevelopmentCredentialGate("https://eve.test");
+ const rollback = credentials.authorize({
+ target,
+ resolveToken: async () => "candidate-token",
+ });
+ const client = new Client(
+ resolveRemoteDevelopmentClientOptions({ credentials, serverUrl: "https://eve.test" }),
+ );
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null));
+
+ const request = client.fetch("/eve/v1/info");
+ rollback();
+ await request;
+
+ const sent = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);
+ expect(sent.get("authorization")).toBe("Bearer candidate-token");
+ expect(sent.get("x-vercel-protection-bypass")).toBe("bypass-secret");
+ expect(sent.get("x-vercel-trusted-oidc-idp-token")).toBe("candidate-token");
+ await expect(credentials.resolveToken()).resolves.toBe("");
+ });
+
+ it("accepts a tool whose undefined output schema was omitted during JSON serialization", async () => {
+ const toolWithoutOutputSchema = {
+ description: "Search the web",
+ hasAuth: false,
+ hasExecute: false,
+ hasModelOutputProjection: false,
+ hasOutputSchema: false,
+ inputSchema: null,
+ logicalPath: "eve:framework/web-search",
+ name: "web_search",
+ origin: "framework",
+ replacesFrameworkTool: false,
+ requiresApproval: false,
+ sourceKind: "module",
+ };
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({
+ ...AGENT_INFO,
+ tools: {
+ ...AGENT_INFO.tools,
+ available: [toolWithoutOutputSchema],
+ },
+ }),
+ );
+ const client = new Client({ host: "https://eve.test" });
+
+ const info = await client.info();
+
+ expect(info.tools.available[0]).toMatchObject({
+ hasOutputSchema: false,
+ name: "web_search",
+ });
+ expect(info.tools.available[0]).not.toHaveProperty("outputSchema");
+ });
+
+ it("returns the parsed agent info payload", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({ ...AGENT_INFO, ignoredByClient: true }),
+ );
+ const client = new Client({ host: "https://eve.test" });
+
+ const info = await client.info();
+
+ expect(info).not.toHaveProperty("ignoredByClient");
+ });
+
+ it("rejects a non-Eve response from the agent info route", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({ kind: "eve-agent-info", version: 1 }),
+ );
+ const client = new Client({ host: "https://eve.test" });
+
+ await expect(client.info()).rejects.toThrow(SyntaxError);
+ });
+
+ it("rejects an incomplete agent info payload", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({
+ agent: { model: { id: "openai/gpt-5.5" } },
+ diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
+ kind: "eve-agent-info",
+ version: 1,
+ }),
+ );
+ const client = new Client({ host: "https://eve.test" });
+
+ await expect(client.info()).rejects.toThrow(SyntaxError);
+ });
+
+ it.each([null, { kind: "gateway", connected: true }, { kind: "external" }])(
+ "rejects an invalid model endpoint from the agent info route",
+ async (endpoint) => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({
+ ...AGENT_INFO,
+ agent: {
+ ...AGENT_INFO.agent,
+ model: { ...AGENT_INFO.agent.model, endpoint },
+ },
+ }),
+ );
+ const client = new Client({ host: "https://eve.test" });
+
+ await expect(client.info()).rejects.toThrow(SyntaxError);
+ },
+ );
});
diff --git a/packages/eve/src/client/client.ts b/packages/eve/src/client/client.ts
index 96668c782..e4a5642bc 100644
--- a/packages/eve/src/client/client.ts
+++ b/packages/eve/src/client/client.ts
@@ -1,4 +1,5 @@
import { EVE_HEALTH_ROUTE_PATH, EVE_INFO_ROUTE_PATH } from "#protocol/routes.js";
+import { AgentInfoResultSchema } from "#client/agent-info-schema.js";
import { ClientError } from "#client/client-error.js";
import { ClientSession } from "#client/session.js";
import { createInitialSessionState } from "#client/session-utils.js";
@@ -13,6 +14,7 @@ import type {
SessionState,
TokenValue,
} from "#client/types.js";
+import { VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER } from "#client/types.js";
/**
* HTTP client for talking to a deployed eve agent.
@@ -66,16 +68,21 @@ export class Client {
* @throws {ClientError} If the server returns a non-successful status.
*/
async info(): Promise<AgentInfoResult> {
- const url = createClientUrl(this.#host, EVE_INFO_ROUTE_PATH);
- const headers = await this.#resolveHeaders();
- const response = await fetch(url, withRedirectPolicy({ headers }, this.#redirect));
+ const response = await this.fetch(EVE_INFO_ROUTE_PATH);
if (!response.ok) {
const body = await response.text();
throw new ClientError(response.status, body);
}
- return (await response.json()) as AgentInfoResult;
+ const result = AgentInfoResultSchema.safeParse(await response.json());
+ if (!result.success) {
+ throw new SyntaxError(
+ "The server returned an unrecognized response from the Eve agent info route.",
+ );
+ }
+
+ return result.data;
}
/**
@@ -128,7 +135,12 @@ export class Client {
async #resolveHeaders(perRequest?: Readonly<Record<string, string>>): Promise<Headers> {
const headers = new Headers();
- const baseHeaders = await resolveHeadersValue(this.#headers);
+ // Start both dynamic providers together so shared credential state is
+ // captured once per request, before either provider can be replaced.
+ const [baseHeaders, authHeaders] = await Promise.all([
+ resolveHeadersValue(this.#headers),
+ this.#resolveAuthHeaders(),
+ ]);
for (const [key, value] of Object.entries(baseHeaders)) {
headers.set(key, value);
@@ -140,36 +152,47 @@ export class Client {
}
}
- const authorization = await this.#resolveAuthorizationHeader();
- if (authorization) {
- headers.set("authorization", authorization);
+ for (const [key, value] of Object.entries(authHeaders)) {
+ headers.set(key, value);
}
return headers;
}
- async #resolveAuthorizationHeader(): Promise<string | undefined> {
+ async #resolveAuthHeaders(): Promise<Readonly<Record<string, string>>> {
const auth = this.#auth;
- if (!auth) return undefined;
+ if (!auth) return {};
+
+ if ("vercelOidc" in auth) {
+ // One credential, two headers: the bearer the route reads and the
+ // trusted-OIDC header Vercel Deployment Protection accepts. Resolved
+ // once; the client-side mirror of the server `vercelOidc()` channel.
+ const token = (await resolveTokenValue(auth.vercelOidc.token)).trim();
+ if (token.length === 0) return {};
+ return {
+ authorization: `Bearer ${token}`,
+ [VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER]: token,
+ };
+ }
if ("bearer" in auth) {
+ // Skip the header entirely on an empty token rather than emitting a
+ // malformed `Bearer ` value the server has to reject. The dev client's
+ // OIDC resolver returns "" when no token is available locally; the
+ // request then goes out unauthenticated and the framework's
+ // `vercelOidc()` channel handler returns a clean 401.
const token = (await resolveTokenValue(auth.bearer)).trim();
- // Skip the header entirely on an empty token rather than emitting
- // a malformed `Bearer ` value the server has to reject. The dev
- // client's OIDC resolver returns an empty string when no Vercel
- // OIDC token is available locally; in that case the request goes
- // out unauthenticated and the framework's `vercelOidc()` channel
- // handler returns a clean 401.
- if (token.length === 0) return undefined;
- return `Bearer ${token}`;
+ return token.length === 0 ? {} : { authorization: `Bearer ${token}` };
}
if ("basic" in auth) {
const password = await resolveTokenValue(auth.basic.password);
- return `Basic ${encodeBasicCredentials(auth.basic.username, password)}`;
+ return {
+ authorization: `Basic ${encodeBasicCredentials(auth.basic.username, password)}`,
+ };
}
- return undefined;
+ return {};
}
}
diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.ts
index 114a7fdbb..bb15fe479 100644
--- a/packages/eve/src/client/types.ts
+++ b/packages/eve/src/client/types.ts
@@ -4,8 +4,27 @@ import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index
import type { HandleMessageStreamEvent } from "#protocol/message.js";
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
import type { JsonObject } from "#shared/json.js";
-import type { ModelRouting } from "#shared/agent-definition.js";
-import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
+
+export type {
+ AgentInfoChannelEntry,
+ AgentInfoChannels,
+ AgentInfoConnectionEntry,
+ AgentInfoDynamicResolverEntry,
+ AgentInfoEntry,
+ AgentInfoFrameworkChannelEntry,
+ AgentInfoFrameworkToolEntry,
+ AgentInfoHookEntry,
+ AgentInfoInstructions,
+ AgentInfoInstructionsEntry,
+ AgentInfoResult,
+ AgentInfoSandboxEntry,
+ AgentInfoScheduleEntry,
+ AgentInfoSkillEntry,
+ AgentInfoSource,
+ AgentInfoSubagentEntry,
+ AgentInfoToolEntry,
+ AgentInfoTools,
+} from "./agent-info-schema.js";
/**
* Static credential value or per-request credential resolver.
@@ -28,7 +47,18 @@ export type HeadersValue =
*/
export type ClientAuth =
| { readonly basic: { readonly username: string; readonly password: TokenValue } }
- | { readonly bearer: TokenValue };
+ | { readonly bearer: TokenValue }
+ // The client-side mirror of the framework's server `vercelOidc()` channel
+ // auth: one token the client expands into both Vercel deployment-protection
+ // headers (Authorization and {@link VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER}).
+ | { readonly vercelOidc: { readonly token: TokenValue } };
+
+/**
+ * Vercel header that presents a trusted OIDC token as proof the caller is
+ * authorized for a protected deployment. The client emits it alongside
+ * `Authorization` for the {@link ClientAuth} `vercelOidc` variant.
+ */
+export const VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER = "x-vercel-trusted-oidc-idp-token";
/** Redirect modes supported by the configured fetch implementation. */
export type ClientRedirectPolicy = NonNullable<RequestInit["redirect"]>;
@@ -207,191 +237,6 @@ export interface HealthResult {
readonly workflowId: string;
}
-/**
- * Source reference shared by entries in {@link AgentInfoResult}.
- */
-export interface AgentInfoSource {
- readonly exportName?: string;
- readonly logicalPath: string;
- readonly sourceId?: string;
- readonly sourceKind: string;
-}
-
-export interface AgentInfoEntry extends AgentInfoSource {
- readonly name: string;
-}
-
-export interface AgentInfoToolEntry extends AgentInfoEntry {
- readonly description: string;
- readonly hasAuth: boolean;
- readonly hasExecute: boolean;
- readonly hasModelOutputProjection: boolean;
- readonly hasOutputSchema: boolean;
- readonly inputSchema: unknown;
- readonly origin: "authored" | "framework";
- readonly outputSchema: unknown;
- readonly replacesFrameworkTool: boolean;
- readonly requiresApproval: boolean;
-}
-
-export interface AgentInfoFrameworkToolEntry extends AgentInfoToolEntry {
- readonly disabledByAuthor: boolean;
- readonly replacedByAuthoredTool: boolean;
- readonly status: "active" | "disabled" | "replaced";
-}
-
-export interface AgentInfoDynamicResolverEntry extends AgentInfoSource {
- readonly eventNames: readonly string[];
- readonly origin: "authored" | "framework";
- readonly slug: string;
-}
-
-export interface AgentInfoTools {
- readonly authored: readonly AgentInfoToolEntry[];
- readonly available: readonly AgentInfoToolEntry[];
- readonly disabledFramework: readonly string[];
- readonly dynamic: readonly AgentInfoDynamicResolverEntry[];
- readonly framework: readonly AgentInfoFrameworkToolEntry[];
- readonly reserved: readonly string[];
-}
-
-export interface AgentInfoSkillEntry extends AgentInfoEntry {
- readonly description: string;
- readonly license?: string;
- readonly markdown: string;
- readonly metadata?: Readonly<Record<string, string>>;
-}
-
-export interface AgentInfoInstructionsEntry extends AgentInfoEntry {
- readonly markdown: string;
-}
-
-export interface AgentInfoInstructions {
- readonly dynamic: readonly AgentInfoDynamicResolverEntry[];
- readonly static: AgentInfoInstructionsEntry | null;
-}
-
-export interface AgentInfoScheduleEntry extends AgentInfoEntry {
- readonly cron: string;
- readonly hasRun: boolean;
- readonly markdown?: string;
-}
-
-export interface AgentInfoSubagentEntry extends AgentInfoEntry {
- readonly description: string;
- readonly entryPath: string;
- readonly nodeId: string;
- readonly rootPath: string;
- readonly summary: {
- readonly channels: number;
- readonly connections: number;
- readonly hooks: number;
- readonly instructions: boolean;
- readonly schedules: number;
- readonly skills: number;
- readonly tools: number;
- };
-}
-
-export interface AgentInfoChannelEntry extends AgentInfoEntry {
- readonly adapterKind?: string;
- readonly method: string;
- readonly origin: "authored" | "framework";
- readonly urlPath: string;
-}
-
-export interface AgentInfoFrameworkChannelEntry extends AgentInfoChannelEntry {
- readonly disabledByAuthor: boolean;
- readonly replacedByAuthoredChannel: boolean;
- readonly status: "active" | "disabled" | "replaced";
-}
-
-export interface AgentInfoChannels {
- readonly authored: readonly AgentInfoChannelEntry[];
- readonly available: readonly AgentInfoChannelEntry[];
- readonly disabledFramework: readonly string[];
- readonly framework: readonly AgentInfoFrameworkChannelEntry[];
-}
-
-export interface AgentInfoConnectionEntry extends AgentInfoSource {
- readonly connectionName: string;
- readonly description: string;
- readonly hasApproval: boolean;
- readonly hasAuthorization: boolean;
- readonly hasHeaders: boolean;
- readonly protocol: string;
- readonly toolFilter?: unknown;
- readonly url: string;
-}
-
-export interface AgentInfoHookEntry extends AgentInfoSource {
- readonly eventNames: readonly string[];
- readonly slug: string;
-}
-
-export interface AgentInfoSandboxEntry extends AgentInfoSource {
- readonly backendKind?: string;
- readonly description?: string;
- readonly hasBootstrap: boolean;
- readonly hasOnSession: boolean;
- readonly revalidationKey?: string;
- readonly sourceHash?: string;
-}
-
-export interface AgentInfoResult {
- readonly agent: {
- readonly agentRoot: string;
- readonly appRoot: string;
- readonly configSource?: AgentInfoSource;
- readonly description?: string;
- readonly model: {
- readonly contextWindowTokens?: number;
- readonly id: string;
- readonly providerOptions?: unknown;
- readonly source?: AgentInfoSource;
- /** How the model is routed (gateway vs external), decided at compile time. */
- readonly routing?: ModelRouting;
- /** Composed routing + runtime credential readiness; absent only on legacy payloads. */
- readonly endpoint?: ModelEndpointStatus;
- };
- readonly name: string;
- readonly outputSchema?: unknown;
- };
- readonly capabilities: {
- readonly devRoutes: boolean;
- };
- readonly channels: AgentInfoChannels;
- readonly connections: readonly AgentInfoConnectionEntry[];
- readonly diagnostics: {
- readonly discoveryErrors: number;
- readonly discoveryWarnings: number;
- };
- readonly hooks: readonly AgentInfoHookEntry[];
- readonly instructions: AgentInfoInstructions;
- readonly kind: "eve-agent-info";
- readonly mode: "development" | "production";
- readonly sandbox: AgentInfoSandboxEntry | null;
- readonly schedules: readonly AgentInfoScheduleEntry[];
- readonly skills: {
- readonly dynamic: readonly AgentInfoDynamicResolverEntry[];
- readonly static: readonly AgentInfoSkillEntry[];
- };
- readonly subagents: {
- readonly local: readonly AgentInfoSubagentEntry[];
- readonly total: number;
- };
- readonly tools: AgentInfoTools;
- readonly version: 1;
- readonly workflow: {
- readonly enabled: boolean;
- readonly toolName: string;
- };
- readonly workspace: {
- readonly resourceRoot: unknown;
- readonly rootEntries: readonly string[];
- };
-}
-
/**
* Serializable session cursor. Persist this value and pass it back to
* {@link Client.session} to resume a conversation later.
diff --git a/packages/eve/src/services/dev-client/client-options.test.ts b/packages/eve/src/services/dev-client/client-options.test.ts
index 85d8b520d..f62db2fe8 100644
--- a/packages/eve/src/services/dev-client/client-options.test.ts
+++ b/packages/eve/src/services/dev-client/client-options.test.ts
@@ -35,15 +35,15 @@ describe("resolveDevelopmentClientOptions", () => {
it("binds an authorized credential gate to a non-redirecting client", () => {
const credentials = createDevelopmentCredentialGate("https://verified.example.com");
- expect(
- resolveRemoteDevelopmentClientOptions({
- credentials,
- serverUrl: "https://verified.example.com",
- }),
- ).toEqual({
- headers: credentials.resolveHeaders,
- host: "https://verified.example.com",
- redirect: "manual",
+ const options = resolveRemoteDevelopmentClientOptions({
+ credentials,
+ serverUrl: "https://verified.example.com",
});
+
+ expect(options.host).toBe("https://verified.example.com");
+ expect(options.redirect).toBe("manual");
+ expect(options.headers).toBe(credentials.resolveBypassHeaders);
+ // The token flows through the higher-level vercelOidc auth, never headers.
+ expect(options.auth).toEqual({ vercelOidc: { token: expect.any(Function) } });
});
});
diff --git a/packages/eve/src/services/dev-client/client-options.ts b/packages/eve/src/services/dev-client/client-options.ts
index f3008c585..f69c462d9 100644
--- a/packages/eve/src/services/dev-client/client-options.ts
+++ b/packages/eve/src/services/dev-client/client-options.ts
@@ -23,7 +23,8 @@ export function resolveRemoteDevelopmentClientOptions(input: {
);
}
return {
- headers: input.credentials.resolveHeaders,
+ auth: { vercelOidc: { token: () => input.credentials.resolveToken() } },
+ headers: input.credentials.resolveBypassHeaders,
host: input.serverUrl,
redirect: "manual",
};
diff --git a/packages/eve/src/services/dev-client/credential-gate.test.ts b/packages/eve/src/services/dev-client/credential-gate.test.ts
index c8f3d5f61..4fd5cc2dd 100644
--- a/packages/eve/src/services/dev-client/credential-gate.test.ts
+++ b/packages/eve/src/services/dev-client/credential-gate.test.ts
@@ -21,20 +21,34 @@ function resolvedToken(token: string): DevelopmentOidcTokenResolution {
return { kind: "resolved", token };
}
+function deferred<T>() {
+ let settle: ((value: T) => void) | undefined;
+ const promise = new Promise<T>((resolve) => {
+ settle = resolve;
+ });
+ return {
+ promise,
+ resolve(value: T): void {
+ if (settle === undefined) throw new Error("Deferred promise was not initialized.");
+ settle(value);
+ },
+ };
+}
+
describe("createDevelopmentCredentialGate", () => {
it("stays anonymous until an authoritative target is installed", async () => {
vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "ambient-bypass");
const gate = createDevelopmentCredentialGate("https://verified.example.com/path");
- await expect(gate.resolveHeaders()).resolves.toEqual({});
+ await expect(gate.resolveToken()).resolves.toBe("");
+ await expect(gate.resolveBypassHeaders()).resolves.toEqual({});
const target = await verifiedTarget("verified.example.com");
gate.authorize({ target, resolveToken: async () => resolvedToken(" oidc-token ") });
- await expect(gate.resolveHeaders()).resolves.toEqual({
- authorization: "Bearer oidc-token",
+ await expect(gate.resolveToken()).resolves.toBe("oidc-token");
+ await expect(gate.resolveBypassHeaders()).resolves.toEqual({
"x-vercel-protection-bypass": "ambient-bypass",
- "x-vercel-trusted-oidc-idp-token": "oidc-token",
});
});
@@ -50,15 +64,13 @@ describe("createDevelopmentCredentialGate", () => {
resolveToken: async () => resolvedToken("other-token"),
}),
).toThrow("does not match");
- await expect(gate.resolveHeaders()).resolves.toMatchObject({
- authorization: "Bearer first-token",
- });
+ await expect(gate.resolveToken()).resolves.toBe("first-token");
});
it("permits an automation bypass only after origin verification", async () => {
vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "verified-bypass");
const gate = createDevelopmentCredentialGate("https://verified.example.com");
- await expect(gate.resolveHeaders()).resolves.toEqual({});
+ await expect(gate.resolveBypassHeaders()).resolves.toEqual({});
const failure = { kind: "invalid-claims", invalidClaims: ["project_id"] } as const;
gate.authorize({
@@ -66,7 +78,8 @@ describe("createDevelopmentCredentialGate", () => {
resolveToken: async () => failure,
});
- await expect(gate.resolveHeaders()).resolves.toEqual({
+ await expect(gate.resolveToken()).resolves.toBe("");
+ await expect(gate.resolveBypassHeaders()).resolves.toEqual({
"x-vercel-protection-bypass": "verified-bypass",
});
expect(gate.lastTokenFailure()).toEqual(failure);
@@ -83,12 +96,8 @@ describe("createDevelopmentCredentialGate", () => {
resolveToken,
});
- await expect(gate.resolveHeaders()).resolves.toMatchObject({
- authorization: "Bearer first-token",
- });
- await expect(gate.resolveHeaders()).resolves.toMatchObject({
- authorization: "Bearer second-token",
- });
+ await expect(gate.resolveToken()).resolves.toBe("first-token");
+ await expect(gate.resolveToken()).resolves.toBe("second-token");
expect(resolveToken).toHaveBeenCalledTimes(2);
});
@@ -104,11 +113,26 @@ describe("createDevelopmentCredentialGate", () => {
resolveToken,
});
- await expect(gate.resolveHeaders()).resolves.toEqual({});
+ await expect(gate.resolveToken()).resolves.toBe("");
expect(gate.lastTokenFailure()).toEqual(failure);
- await expect(gate.resolveHeaders()).resolves.toMatchObject({
- authorization: "Bearer fresh-token",
- });
+ await expect(gate.resolveToken()).resolves.toBe("fresh-token");
expect(gate.lastTokenFailure()).toBeUndefined();
});
+
+ it("keeps a restored grant's failure when a retired request completes", async () => {
+ const failure = { kind: "resolution-failed", message: "previous grant failed" } as const;
+ const gate = createDevelopmentCredentialGate("https://verified.example.com");
+ const target = await verifiedTarget("verified.example.com");
+ gate.authorize({ target, resolveToken: async () => failure });
+ await expect(gate.resolveToken()).resolves.toBe("");
+
+ const candidate = deferred<DevelopmentOidcTokenResolution>();
+ const restore = gate.authorize({ target, resolveToken: async () => await candidate.promise });
+ const inFlight = gate.resolveToken();
+ restore();
+ candidate.resolve(resolvedToken("candidate-token"));
+
+ await expect(inFlight).resolves.toBe("candidate-token");
+ expect(gate.lastTokenFailure()).toEqual(failure);
+ });
});
diff --git a/packages/eve/src/services/dev-client/credential-gate.ts b/packages/eve/src/services/dev-client/credential-gate.ts
index 6c2e40cb6..2b9d7c6e6 100644
--- a/packages/eve/src/services/dev-client/credential-gate.ts
+++ b/packages/eve/src/services/dev-client/credential-gate.ts
@@ -4,23 +4,27 @@ import {
type DevelopmentOidcTokenFailure,
type DevelopmentOidcTokenResolution,
VERCEL_PROTECTION_BYPASS_HEADER,
- VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER,
} from "./request-headers.js";
export interface DevelopmentCredentialGrant {
readonly target: VerifiedVercelTarget;
- readonly resolveToken: () => Promise<DevelopmentOidcTokenResolution>;
+ readonly resolveToken: () => Promise<DevelopmentOidcTokenResolution | string>;
}
/** Per-client authority for resolving and emitting remote Vercel credentials. */
export interface DevelopmentCredentialGate {
/** The origin this gate is permanently bound to. */
readonly serverOrigin: string;
- /** Installs authority after Vercel verifies the exact origin. */
- authorize(grant: DevelopmentCredentialGrant): void;
- /** Resolves headers for one request. */
- resolveHeaders(): Promise<Readonly<Record<string, string>>>;
- /** Token failure from the most recent {@link resolveHeaders}, or `undefined` if it resolved one. */
+ /**
+ * Installs authority after Vercel verifies the exact origin.
+ * Returns a rollback that restores the prior grant if this grant is still current.
+ */
+ authorize(grant: DevelopmentCredentialGrant): () => void;
+ /** The verified target's OIDC token for one request, or "" when unavailable. */
+ resolveToken(): Promise<string>;
+ /** Non-credential Vercel headers (protection bypass), or {} when anonymous. */
+ resolveBypassHeaders(): Promise<Readonly<Record<string, string>>>;
+ /** Token failure from the most recent {@link resolveToken}, or `undefined` if it resolved one. */
lastTokenFailure(): DevelopmentOidcTokenFailure | undefined;
}
@@ -28,7 +32,7 @@ type DevelopmentCredentialGateState =
| { readonly kind: "anonymous" }
| {
readonly kind: "vercel";
- readonly resolveToken: () => Promise<DevelopmentOidcTokenResolution>;
+ readonly resolveToken: () => Promise<DevelopmentOidcTokenResolution | string>;
};
/** Creates an anonymous credential gate bound to one client origin. */
@@ -37,37 +41,55 @@ export function createDevelopmentCredentialGate(serverUrl: string): DevelopmentC
let state: DevelopmentCredentialGateState = { kind: "anonymous" };
let tokenFailure: DevelopmentOidcTokenFailure | undefined;
- const authorize = (grant: DevelopmentCredentialGrant): void => {
+ const authorize = (grant: DevelopmentCredentialGrant): (() => void) => {
if (grant.target.origin !== serverOrigin) {
throw new Error(
`Verified Vercel origin ${grant.target.origin} does not match client origin ${serverOrigin}.`,
);
}
- state = {
+ const previous = state;
+ const previousTokenFailure = tokenFailure;
+ const next = {
kind: "vercel",
resolveToken: grant.resolveToken,
} as const;
+ state = next;
+ tokenFailure = undefined;
+ return () => {
+ if (state === next) {
+ state = previous;
+ tokenFailure = previousTokenFailure;
+ }
+ };
};
- const resolveHeaders = async (): Promise<Readonly<Record<string, string>>> => {
+ const resolveToken = async (): Promise<string> => {
const authorized = state;
- if (authorized.kind === "anonymous") return {};
-
- const headers: Record<string, string> = {};
- const bypassSecret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();
- if (bypassSecret) headers[VERCEL_PROTECTION_BYPASS_HEADER] = bypassSecret;
+ if (authorized.kind === "anonymous") return "";
const resolution = await authorized.resolveToken();
- tokenFailure = resolution.kind === "resolved" ? undefined : resolution;
- if (resolution.kind !== "resolved") return headers;
-
- const token = resolution.token.trim();
- if (token.length > 0) {
- headers.authorization = `Bearer ${token}`;
- headers[VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER] = token;
+ const failure =
+ typeof resolution === "string" || resolution.kind === "resolved" ? undefined : resolution;
+ if (state === authorized) tokenFailure = failure;
+ if (typeof resolution === "string") {
+ return resolution.trim();
}
- return headers;
+
+ return resolution.kind === "resolved" ? resolution.token.trim() : "";
};
- return { authorize, resolveHeaders, serverOrigin, lastTokenFailure: () => tokenFailure };
+ const resolveBypassHeaders = async (): Promise<Readonly<Record<string, string>>> => {
+ const authorized = state;
+ if (authorized.kind === "anonymous") return {};
+ const bypassSecret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();
+ return bypassSecret ? { [VERCEL_PROTECTION_BYPASS_HEADER]: bypassSecret } : {};
+ };
+
+ return {
+ authorize,
+ lastTokenFailure: () => tokenFailure,
+ resolveBypassHeaders,
+ resolveToken,
+ serverOrigin,
+ };
}
diff --git a/packages/eve/src/services/dev-client/request-headers.ts b/packages/eve/src/services/dev-client/request-headers.ts
index fa70245c0..034363ab1 100644
--- a/packages/eve/src/services/dev-client/request-headers.ts
+++ b/packages/eve/src/services/dev-client/request-headers.ts
@@ -94,16 +94,3 @@ function validateDevelopmentOidcToken(
* Automation token issued from Project Settings.
*/
export const VERCEL_PROTECTION_BYPASS_HEADER = "x-vercel-protection-bypass";
-
-/**
- * Vercel header used to bypass deployment protection by presenting a
- * trusted OIDC token issued by Vercel for the linked project. When the
- * CLI is `vercel link`-ed (or running inside a Vercel function), the
- * platform mints an OIDC token whose audience and subject match the
- * deployment, and accepts it as proof that the caller is authorized.
- *
- * This is preferred over {@link VERCEL_PROTECTION_BYPASS_HEADER} because
- * it requires no per-project secret — the token is already available via
- * `@vercel/oidc`.
- */
-export const VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER = "x-vercel-trusted-oidc-idp-token";
diff --git a/packages/eve/src/services/dev-client/vercel-auth-error.test.ts b/packages/eve/src/services/dev-client/vercel-auth-error.test.ts
index 57c753b04..444c992ec 100644
--- a/packages/eve/src/services/dev-client/vercel-auth-error.test.ts
+++ b/packages/eve/src/services/dev-client/vercel-auth-error.test.ts
@@ -31,6 +31,14 @@ describe("isVercelAuthChallenge", () => {
expect(isVercelAuthChallenge({ body: VERCEL_SSO_CHALLENGE_BODY, status: 401 })).toBe(true);
});
+ it("requires HTTP 401 and the complete Vercel challenge signature", () => {
+ expect(isVercelAuthChallenge(new ClientError(500, VERCEL_SSO_CHALLENGE_BODY))).toBe(false);
+ expect(
+ isVercelAuthChallenge(new ClientError(401, "<title>Authentication Required</title>")),
+ ).toBe(false);
+ expect(isVercelAuthChallenge({ body: VERCEL_SSO_CHALLENGE_BODY })).toBe(false);
+ });
+
it("returns false for non-error inputs", () => {
expect(isVercelAuthChallenge(undefined)).toBe(false);
expect(isVercelAuthChallenge(null)).toBe(false);
diff --git a/packages/eve/src/services/dev-client/vercel-auth-error.ts b/packages/eve/src/services/dev-client/vercel-auth-error.ts
index 4bcebe4c8..4c8fb3e28 100644
--- a/packages/eve/src/services/dev-client/vercel-auth-error.ts
+++ b/packages/eve/src/services/dev-client/vercel-auth-error.ts
@@ -16,6 +16,7 @@
import { ClientError } from "#client/client-error.js";
import type { DevelopmentOidcTokenFailure } from "#services/dev-client/request-headers.js";
+import { isObject } from "#shared/guards.js";
/**
* Substrings that uniquely identify the Vercel Deployment Protection
@@ -41,17 +42,7 @@ const VERCEL_AUTH_CHALLENGE_MARKERS: readonly string[] = [
* so the CLI keeps degrading gracefully when Vercel tweaks the page.
*/
function bodyLooksLikeVercelAuthChallenge(body: string): boolean {
- if (body.length === 0) {
- return false;
- }
-
- for (const marker of VERCEL_AUTH_CHALLENGE_MARKERS) {
- if (body.includes(marker)) {
- return true;
- }
- }
-
- return false;
+ return body.length > 0 && VERCEL_AUTH_CHALLENGE_MARKERS.every((marker) => body.includes(marker));
}
/**
@@ -69,19 +60,15 @@ function bodyLooksLikeVercelAuthChallenge(body: string): boolean {
*/
export function isVercelAuthChallenge(error: unknown): boolean {
if (error instanceof ClientError) {
- return bodyLooksLikeVercelAuthChallenge(error.body);
- }
-
- if (
- error !== null &&
- typeof error === "object" &&
- "body" in error &&
- typeof (error as { body: unknown }).body === "string"
- ) {
- return bodyLooksLikeVercelAuthChallenge((error as { body: string }).body);
+ return error.status === 401 && bodyLooksLikeVercelAuthChallenge(error.body);
}
- return false;
+ return (
+ isObject(error) &&
+ error.status === 401 &&
+ typeof error.body === "string" &&
+ bodyLooksLikeVercelAuthChallenge(error.body)
+ );
}
/**
diff --git a/packages/eve/src/setup/verified-remote-client.test.ts b/packages/eve/src/setup/verified-remote-client.test.ts
index 463f567a9..1f7bca453 100644
--- a/packages/eve/src/setup/verified-remote-client.test.ts
+++ b/packages/eve/src/setup/verified-remote-client.test.ts
@@ -25,12 +25,13 @@ describe("resolveVerifiedRemoteDevelopmentClient", () => {
});
expect(options.redirect).toBe("manual");
- expect(typeof options.headers).toBe("function");
- if (typeof options.headers !== "function") throw new Error("Expected dynamic headers.");
- const headers = new Headers(await options.headers());
-
- expect(headers.get("authorization")).toBe("Bearer fresh-token");
- expect(headers.get("x-vercel-trusted-oidc-idp-token")).toBe("fresh-token");
+ // The OIDC token rides the higher-level vercelOidc auth; the client expands
+ // it into the Authorization + trusted-OIDC headers (covered in client.test.ts).
+ if (options.auth === undefined || !("vercelOidc" in options.auth)) {
+ throw new Error("Expected vercelOidc auth.");
+ }
+ const { token } = options.auth.vercelOidc;
+ expect(typeof token === "function" ? await token() : token).toBe("fresh-token");
expect(resolveDevelopmentOidcToken).toHaveBeenCalledWith({
ownerId: "team_test",
projectId: "prj_example",
@@ -51,9 +52,11 @@ describe("resolveVerifiedRemoteDevelopmentClient", () => {
},
});
- expect(typeof options.headers).toBe("function");
- if (typeof options.headers !== "function") throw new Error("Expected dynamic headers.");
- await expect(options.headers()).resolves.toEqual({});
+ if (options.auth === undefined || !("vercelOidc" in options.auth)) {
+ throw new Error("Expected vercelOidc auth.");
+ }
+ const { token } = options.auth.vercelOidc;
+ expect(typeof token === "function" ? await token() : token).toBe("");
expect(lastOidcTokenFailure()).toEqual(failure);
});
diff --git a/packages/eve/test/client.test.ts b/packages/eve/test/client.test.ts
index 42cfd296d..9c344dfbf 100644
--- a/packages/eve/test/client.test.ts
+++ b/packages/eve/test/client.test.ts
@@ -1,6 +1,11 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { Client, ClientError, type HandleMessageStreamEvent } from "../src/client/index.js";
+import {
+ Client,
+ ClientError,
+ type AgentInfoResult,
+ type HandleMessageStreamEvent,
+} from "../src/client/index.js";
import {
EVE_SESSION_ID_HEADER,
createMessageCompletedEvent,
@@ -227,6 +232,7 @@ describe("Client.info", () => {
},
name: "Weather Agent",
},
+ capabilities: { devRoutes: true },
channels: {
authored: [],
available: [],
@@ -293,7 +299,7 @@ describe("Client.info", () => {
resourceRoot: null,
rootEntries: [],
},
- };
+ } satisfies AgentInfoResult;
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(Response.json(payload));
const client = new Client({ host: "http://localhost:3000" });
diff --git a/packages/eve/test/dev-client-harness/request-headers.ts b/packages/eve/test/dev-client-harness/request-headers.ts
index aba8c1116..04820d5a3 100644
--- a/packages/eve/test/dev-client-harness/request-headers.ts
+++ b/packages/eve/test/dev-client-harness/request-headers.ts
@@ -1,15 +1,11 @@
import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";
+import { VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER } from "#client/types.js";
import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";
import { isLocalDevelopmentServerUrl } from "#services/dev-client/local-host.js";
-import {
- VERCEL_PROTECTION_BYPASS_HEADER,
- VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER,
-} from "#services/dev-client/request-headers.js";
+import { VERCEL_PROTECTION_BYPASS_HEADER } from "#services/dev-client/request-headers.js";
-export {
- VERCEL_PROTECTION_BYPASS_HEADER,
- VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER,
-} from "#services/dev-client/request-headers.js";
+export { VERCEL_PROTECTION_BYPASS_HEADER } from "#services/dev-client/request-headers.js";
+export { VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER } from "#client/types.js";
const EVE_ROUTE_PREFIX_WITH_SEPARATOR = `${EVE_ROUTE_PREFIX}/`;
export const VERCEL_OIDC_TOKEN_HEADER = "x-vercel-oidc-token";
diff --git a/packages/eve/test/dev-send-message.test.ts b/packages/eve/test/dev-send-message.test.ts
index 165a03a32..e7439ed3f 100644
--- a/packages/eve/test/dev-send-message.test.ts
+++ b/packages/eve/test/dev-send-message.test.ts
@@ -11,10 +11,8 @@ import {
createTurnStartedEvent,
} from "../src/protocol/message.js";
import { createEveMessageStreamRoutePath } from "../src/protocol/routes.js";
-import {
- VERCEL_PROTECTION_BYPASS_HEADER,
- VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER,
-} from "../src/services/dev-client/request-headers.js";
+import { VERCEL_PROTECTION_BYPASS_HEADER } from "../src/services/dev-client/request-headers.js";
+import { VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER } from "../src/client/types.js";
import { sendDevelopmentMessage } from "./dev-client-harness/send-message.js";
import { createDevelopmentSessionState } from "./dev-client-harness/session.js";