fix(core): name the unset key variable when a model call has no key

Merged
OK
1d ago
+482-19

What

  • A step that calls the model with no key configured names the cause: MODEL_PROVIDER_FAILED: the model has no credential: AI_GATEWAY_API_KEY is not set, so no request was sent. Set AI_GATEWAY_API_KEY, or pass the key where the model is constructed. It no longer shows the provider's Unauthenticated request to AI Gateway text, or the hint that the provider rejected a credential.
  • Nothing else about the run changes. The step fails as on main (exit 3), tests with no agent call and recorded agent.act steps still run and pass, and nothing is retried.
  • A configured credential that failed to load, was malformed, or was refused keeps the provider's own error, as on main.
  • e2e doctor prints ! (warn) for a Vercel AI Gateway or OpenRouter model whose key variable is not set, and its last line counts the warnings: e2e run can start here, with 1 warning.

Why

A coding agent's sandbox usually has no model key, so a keyless first run is the default. On main every agent step that needs the model fails with the model provider failed: Unauthenticated request to AI Gateway. The summary line never names the key, and our own hint says the provider rejected a credential when none was sent. e2e doctor says the run can start and shows ?.

An earlier head of this PR stopped the run with MODEL_UNAVAILABLE at the first keyless model call. Two reviewers measured what that costs on a suite that mostly replays recordings: the web benchmark's agent suite with no key passes 26 of 34 tests on main and passed 0 with the run stop, which also cut short tests that were replaying. The run stop is gone. Only the text of the failure changes.

How it works

  1. withMissingCredentialNamed (packages/core/src/agent/model/missing-credential.ts:67) is a wrapGenerate middleware around the model instance, wired into both tiers inside the stall guard: judgments at packages/core/src/agent/model/sdk.ts:69, the act loop at packages/core/src/agent/tool-loop.ts:316. It has to sit there because ai replaces every gateway authentication error with one text and drops its cause before generateText returns.
  2. unsetKeyVariable (missing-credential.ts:29) decides from facts whether nothing was configured:
    • AI_LoadAPIKeyError: loadApiKey raises it for a missing key and for a key that is not a string, and names the variable only in its text. The name is read there and held against the environment. The key is missing only when that variable is undefined, because loadApiKey sends an empty one. createOpenAI({ apiKey: 42 }) names no variable, so it keeps OpenAI API key must be a string.
    • GatewayAuthenticationError: the gateway raises "No authentication provided" for every failure to resolve a token, with the real error in cause. Nothing was configured only when resolution fell through to the OIDC token (the cause is a VercelOidcTokenError) and neither AI_GATEWAY_API_KEY nor VERCEL_OIDC_TOKEN holds a value. The gateway reads an empty variable as unset. A throwing apiKey callback, a callback that returns nothing, and a set but malformed or expired VERCEL_OIDC_TOKEN pass through untouched.
  3. For a missing key the middleware rethrows a private NoCredentialConfigured error (missing-credential.ts:42) that carries the message and the provider's error as cause. It is not an APICallError, so the SDK's transport retries do not repeat it.
  4. missingCredentialError (missing-credential.ts:56) turns that into AgentError('MODEL_PROVIDER_FAILED') at the two places a step already classifies a provider failure: sdk.ts:362 and tool-loop.ts:433. Building it there, not in the middleware, keeps the stack that leads to the test's line, so the report still shows the code frame.
  5. e2e doctor: unsetGatewayKey (packages/e2e/src/cli/doctor.ts:366) finds the model's gateway preset by the provider name the instance reports, and applies that provider's own rule for "unset". The new sendsEmptyKey on the OpenRouter preset (packages/e2e/src/cli/init/gateways.ts:57) says an empty OPENROUTER_API_KEY is sent as the key, so doctor shows ? for it, not !. The verdict line counts warn checks (doctor.ts:434).
  6. Docs: the MODEL_PROVIDER_FAILED row in reference/errors.mdx, one row in models.mdx, the debugging.mdx row, doctor's model row in reference/cli.mdx, and skills/e2e debugging (plugin copy synced). The MODEL_UNAVAILABLE rows are back to what main says.

Decisions a reviewer may ask about:

  • The code is MODEL_PROVIDER_FAILED, not MODEL_UNAVAILABLE. MODEL_UNAVAILABLE is documented and implemented as a run-level error that stops the run; this failure must stay per step. MODEL_PROVIDER_FAILED keeps main's class (infrastructure, exit 3), is not retry-eligible at the test level (isRetryEligible takes only test failures and timeouts), and evicts no recording.
  • The doctor-1 schema description ("only fail stops a run") is unchanged. It is true again: this warn names steps that fail, not a run that stops.
  • A linked Vercel project whose token refresh fails, with both variables unset, still reads as AI_GATEWAY_API_KEY is not set. The statement is true and the provider's error is kept as cause, but the message does not mention the linked project. Telling the two apart would mean reading .vercel/project.json the way @vercel/oidc does.
  • Doctor knows two gateways. An arbitrary AI SDK instance exposes provider and modelId and nothing about its credential, so it stays ?.
  • A custom executor that calls a model itself is not covered: the middleware wraps the built-in agent's model only.

Verified

Ran it locally: yes. Built CLI, no key in the environment (env -u AI_GATEWAY_API_KEY -u VERCEL_OIDC_TOKEN -u OPENROUTER_API_KEY -u OPENAI_API_KEY), main at 95f80b8b8 against this branch.

Keyless web agent suite, pnpm --filter @e2e-dev/web-benchmark run test:agent --strict-cache, one run each:

mainthis PR
Tests26 passed, 8 failed26 passed, 8 failed
Exit code33
The 5 steps with no recordingMODEL_PROVIDER_FAILED: the model provider failed: Unauthenticated request to AI Gateway.MODEL_PROVIDER_FAILED: the model has no credential: AI_GATEWAY_API_KEY is not set, so no request was sent. Set AI_GATEWAY_API_KEY, or pass the key where the model is constructed

The same 8 tests fail on both sides. The other 3 are planted-bugs tests that catch the failed model call and assert on its code.

A scratch project with model: gateway('openai/gpt-6-luna-fast'), a static page, and three tests (a judgment, an act, no agent call), e2e run:

main (exit 3, 2 failed, 1 passed):

 FAIL  |web| tests/keyless.e2e.ts > acts
MODEL_PROVIDER_FAILED: the model provider failed: Unauthenticated request to AI Gateway.

To authenticate, set the AI_GATEWAY_API_KEY environment variable with your API key.

Alternatively, you can use a provider module instead of the AI Gateway.

Learn more: https://ai-sdk.dev/unauthenticated-ai-gateway
the provider rejected the credential the model instance was created with: check the variable the provider package reads, or the key passed at construction
 ❯ tests/keyless.e2e.ts:10:3

this PR (exit 3, 2 failed, 1 passed):

   × judges > agent.assert "the page says Hello" 19ms · 1 model call failed
   × |web| tests/keyless.e2e.ts > judges 336ms ai 0 tokens
     → the model has no credential: AI_GATEWAY_API_KEY is not set, so no reques…
   × acts > agent.act "click Go" 106ms failed
   × |web| tests/keyless.e2e.ts > acts 213ms
     → the model has no credential: AI_GATEWAY_API_KEY is not set, so no reques…
   ✓ |web| tests/keyless.e2e.ts > opens the app 47ms

 FAIL  |web| tests/keyless.e2e.ts > acts
MODEL_PROVIDER_FAILED: the model has no credential: AI_GATEWAY_API_KEY is not set, so no request was sent. Set AI_GATEWAY_API_KEY, or pass the key where the model is constructed
 ❯ tests/keyless.e2e.ts:10:3
      8| test('acts', async ({ app, agent }) => {
      9|   await app.open();
     10|   await agent.act('click Go');
       |   ^

 Test Files  1 failed | 0 passed (1)
      Tests  2 failed | 1 passed (3)

e2e doctor and e2e doctor --check-model, same scratch project, one model per row. --check-model is MODEL_PROVIDER_FAILED, exit 2, on both sides in every row; the column shows its message.

Model and environmentmain doctorthis PR doctormain --check-modelthis PR --check-model
gateway(), no key?! AI_GATEWAY_API_KEY is not set: agent steps that call the model fail with MODEL_PROVIDER_FAILED, unless the model signs in another way; --check-model calls itUnauthenticated request to AI Gateway...the model has no credential: AI_GATEWAY_API_KEY is not set, so no request was sent...
gateway(), VERCEL_OIDC_TOKEN=a.b.c??Unauthenticated request to AI Gateway...same as main
createGateway({ apiKey }) with a callback that throws?! (the variable is unset; a key passed at construction is invisible to doctor)Unauthenticated request to AI Gateway...same as main
openrouter(), key unset?! OPENROUTER_API_KEY is not set: ...OpenRouter API key is missing. Pass it using the 'apiKey' parameter or the OPENROUTER_API_KEY environment variable.the model has no credential: OPENROUTER_API_KEY is not set, so no request was sent...
createOpenRouter on a local server that answers 401, OPENROUTER_API_KEY=''??No auth credentials found; the provider rejected the credential...same as main
createOpenAI({ apiKey: 42 })??OpenAI API key must be a string.same as main

With a warning, doctor's last line on this PR is e2e run can start here, with 1 warning; without one it is e2e run can start here, as on main.

Tests:

  • tests/unit/missing-credential.test.ts runs the real createGateway, createOpenAI, and createOpenRouter instances through the middleware with a counting fetch: no request leaves for a missing key, one leaves for an empty OPENROUTER_API_KEY, and a model that throws the missing-key error is called once with maxRetries: 5.
  • tests/integration/missing-model-key.test.ts runs a keyless suite with a judgment first and with an act first: both agent tests fail with the message, the test with no agent call passes, exit 3, no run-level error, one attempt each with retries: 1.
  • tests/integration/cli-doctor.test.ts covers the gateway (unset, blank, key, token) and a real openrouter(...) instance (unset, empty, --check-model).
  • Mutation check: 14 mutants over the new branches and constants, all killed by a failing assertion in those three files. They include the three that survived in review (the wrapper removed from createModelAdapter, provider: 'openrouter' removed from the preset, a trim in doctor's check), plus reading the gateway by message text alone and ignoring the cause or either variable.

Not run:

  • A rejected key against the live gateway or OpenRouter, and an OIDC refresh failure on a linked Vercel project: both need a hosted service.
  • pnpm bench:ab: it needs live model calls and this machine has no model key. The change adds one pass-through middleware per request.
  • No terminal recording and no docs screenshots: the changed output is the text above, and the docs change is table rows.