fix(ai-connections): tell people why an API key could not be verified (#22666)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - During onboarding, a person can connect a model with a provider API
key. Paperclip checks the key with one request to the provider before it
stores it
> - `validateAiApiKey` returns "The provider rejected this API key."
only for 401 and 403. Every other answer, and every network error,
returns "The provider could not verify this account. Try again."
> - The server does not log the upstream status, so nobody can tell
later what the provider said
> - A person whose key is valid but whose account has no credit, is
rate-limited, or hits a provider outage cannot know what to fix
> - This pull request gives each case its own code and message, and logs
the status and the provider's error type without the key
> - The benefit is that people can fix the real problem, and support can
see the provider's answer in the logs

## Linked Issues or Issue Description

**What happened?**

During onboarding, a person entered a Claude API key and saw "Could not
store the API key: The provider could not verify this account. Try
again." They then switched to a Claude subscription. The server log did
not show which status the provider returned.

**Expected behavior**

The person learns whether the key is wrong, the account has no credit,
the provider is limiting requests, or the provider is down. The server
logs the upstream status.

**Steps to reproduce**

1. Call `validateAiApiKey("anthropic", key, request)` with a `request`
stub that returns 400, 402, 429 or 500.
2. Observe that all four throw `ai_connection_verification_failed` with
the same message.

**Paperclip version or commit**

`master` at `5f5ac154368`.

**Deployment mode**

Hosted onboarding. Self-hosted installs use the same check.

Refs #12675 (related: server-owned user-secret definitions for
onboarding API keys).

## What Changed

- `ai-api-key-failures.ts` (new): one code and message for each result.
The codes are `ai_connection_api_key_rejected` (unchanged),
`ai_connection_billing_required`, `ai_connection_rate_limited`,
`ai_connection_provider_unavailable`,
`ai_connection_verification_timeout`,
`ai_connection_provider_unreachable`, and
`ai_connection_verification_failed` (unchanged, for all other answers).
- `ai-api-key-test.ts`: map 401/403 to rejected (unchanged); 402, or the
error type `billing_error`, `insufficient_quota` or
`insufficient_credits`, to billing; 429 to rate limited; 5xx (including
Anthropic's 529) to provider unavailable. A `TimeoutError` maps to
timeout, and other network errors map to unreachable.
- Log the provider, the HTTP status, the provider's error type and the
result code. The error type comes from `error.type`, `error.code` or
`error.status` in at most 8 KiB of the error body. It is used and logged
only when it is on a closed list of documented provider error types
(Anthropic, OpenAI and xAI, Google, OpenRouter). Any other value is
ignored. The key and the response text are never logged. 401/403 bodies
are not read.
- `adapters/registry.ts` and `agent-environment-test.ts`: keep the
specific code in the environment check instead of collapsing it to
rejected or failed.
- The billing check looks at `error.type`, `error.code` and
`error.status` together, so a 429 with `type: invalid_request_error` and
`code: insufficient_quota` is a billing problem, not a rate limit.
- `tests/runner-e2e`: the connection harness keeps every new code in
`creationFailure` instead of saving it as `connection_request_rejected`.
One shared list feeds `connection-flow.ts`, `connection-evidence.ts` and
`result-validation.ts`, and a test keeps it equal to the server's codes.
- Tests: `ai-api-key-test.test.ts` (17 tests) and
`connection-support.test.ts`.

**The user-facing text needs a person's review.** The new messages are a
first draft. They read after the onboarding prefix "Could not store the
API key:":

| Code | Message |
|---|---|
| `ai_connection_billing_required` | The provider account for this API
key has no credit or billing set up. Add credit with the provider, then
try again. |
| `ai_connection_rate_limited` | The provider is limiting requests for
this account right now. Wait a minute, then try again. |
| `ai_connection_provider_unavailable` | The provider is having problems
right now. Try again in a few minutes. |
| `ai_connection_verification_timeout` | The provider did not answer in
time. Try again. |
| `ai_connection_provider_unreachable` | Paperclip could not reach the
provider. Check this server's network connection, then try again. |

## Verification

- `pnpm exec vitest run server/src/services/ai-api-key-test.test.ts`: 17
passed. On `master`, 11 of the original 15 fail.
- Callers: `ai-connections.test.ts`, `adapters/registry.test.ts`,
`agent-environment-test-status.test.ts` and
`agent-test-environment-routes.test.ts` with the new file: 5 files, 331
tests passed.
- `pnpm --filter @paperclipai/server typecheck` passes.
- Not run: a live check against each provider. The billing mapping uses
the documented error types (`billing_error` for Anthropic,
`insufficient_quota` for OpenAI, 402 for OpenRouter). The models
endpoint may not report a billing problem for every provider.

## Risks

- Low risk. The HTTP status of the store request stays 422, and 401/403
behavior does not change.
- An answer that does not match a known case still returns
`ai_connection_verification_failed`, as before.
- A code that consumers compare by value can now be one of five new
values. No UI code compares these codes, and the server callers now pass
them through.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file
edit, and code execution tools.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Devin Foley authored and GitHub committed 2026-11-23 11:52:56 -08:00
1 parent eada94a6d2
commit 7f343549db
9 files changed
+228 -21

No files matched your search

+13 -1
View File
@@ -4,6 +4,18 @@ import type { RunnerE2EResult } from "./types.js";
export const connectionCheckpoints = ["target", "connection_created", "connection_reloaded", "agent_created", "binding", "setup_probe", "first_run", "artifact", "tool_receipt", "followup", "visible_result"] as const;
export type ConnectionCheckpoint = typeof connectionCheckpoints[number];
export const connectionRunSignals = ["provider_overloaded", "provider_quota", "missing_file_conversion", "unsupported_session_configuration", "command_substitution_denied"] as const;
export const connectionVerificationFailureCodes = [
"ai_connection_api_key_rejected",
"ai_connection_billing_required",
"ai_connection_rate_limited",
"ai_connection_provider_unavailable",
"ai_connection_verification_timeout",
"ai_connection_provider_unreachable",
"ai_connection_verification_failed",
] as const;
export const connectionCreationFailureCodes = [...connectionVerificationFailureCodes, "connection_request_rejected"] as const;
export type ConnectionCreationFailureCode = (typeof connectionCreationFailureCodes)[number];
export interface ConnectionRunDiagnostic {
runId: string;
status: "succeeded" | "failed" | "cancelled" | "interrupted" | "timed_out" | "unknown";
@@ -28,7 +40,7 @@ export interface ConnectionEvidence {
model?: string;
inputTransport?: "prompt_base64";
setupChecks?: Array<{ code: string; level: "info" | "warn" | "error" }>;
creationFailure?: { status: number; code: "ai_connection_api_key_rejected" | "ai_connection_verification_failed" | "connection_request_rejected" };
creationFailure?: { status: number; code: ConnectionCreationFailureCode };
cleanupRetained?: boolean;
companyArchived?: boolean;
artifactChecks?: Array<{ filename: string; runId: string; sha256: string; fields: Record<string, boolean>; exactFields: boolean }>;
+3 -3
View File
@@ -5,7 +5,7 @@ import { getConnectableAppDefinition } from "../../packages/shared/src/app-defin
import { connectionCell, type ConnectionHarness, type ConnectionMode } from "./connection-cases.js";
import { ConnectionBlock, ConnectionFailure, type ConnectionConfig, type resolveConnectionSettings } from "./connection-config.js";
import { ConnectionApi, connectionDelay } from "./connection-target.js";
import { createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, type ConnectionEvidence } from "./connection-evidence.js";
import { createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, connectionVerificationFailureCodes, type ConnectionCreationFailureCode, type ConnectionEvidence } from "./connection-evidence.js";
import { createTaskThroughUi, submitTaskReply } from "./user-actions.js";
import { collectRunEvents } from "./run-observations.js";
import type { MatrixExecution } from "./types.js";
@@ -56,8 +56,8 @@ async function submitConnection(input: ConnectionFlowInput, submit: () => Promis
if (!created) throw new ConnectionFailure("connection_request_timeout");
if (created.ok()) return;
const payload = await created.json().catch(() => ({}));
const allowed = ["ai_connection_api_key_rejected", "ai_connection_verification_failed"];
const code = allowed.includes(payload?.details?.code) ? payload.details.code : "connection_request_rejected";
const allowed: readonly string[] = connectionVerificationFailureCodes;
const code: ConnectionCreationFailureCode = allowed.includes(payload?.details?.code) ? payload.details.code : "connection_request_rejected";
input.evidence.creationFailure = { status: created.status(), code };
if (code === "ai_connection_api_key_rejected") throw new ConnectionBlock("missing_credential", code);
throw new ConnectionFailure(code);
+9 -1
View File
@@ -3,11 +3,12 @@ import { chmod, mkdtemp, writeFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { AGENT_ADAPTER_TYPES } from "../../packages/shared/src/constants.js";
import { AI_KEY_VERIFICATION_FAILURES } from "../../server/src/services/ai-api-key-failures.js";
import { runnerMatrix } from "./catalog.js";
import { parseRunnerSelectors, selectRunnerExecutions, buildMatrixJobs } from "./selectors.js";
import { connectionHarnesses, connectionScopeGaps, connectionCell, supportsConnection } from "./connection-cases.js";
import { parseConnectionConfig, targetOrigin, selectedSecret, resolveConnectionSecret, resolveConnectionSettings } from "./connection-config.js";
import { connectionCheckpoints, connectionEvidencePasses, connectionRunDiagnostic, createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, type ConnectionEvidence } from "./connection-evidence.js";
import { connectionCheckpoints, connectionVerificationFailureCodes, connectionEvidencePasses, connectionRunDiagnostic, createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, type ConnectionEvidence } from "./connection-evidence.js";
import { validateRetainedRunnerResult } from "./result-validation.js";
import { ConnectionApi, verifyConnectionTarget } from "./connection-target.js";
import { cleanupConnectionCompany, connectionCreationReceipt, runConnectionCampaign, safeConnectionFailure, withConnectionCampaignCancellation } from "./connection-launch.js";
@@ -300,3 +301,10 @@ describe("independent qualification", () => {
expect(cleanupFailed.failed).toBe(1); expect(cleanupFailed.incomplete).toBe(0);
});
});
describe("connection creation failure codes", () => {
it("keeps every API key verification code the server can return", () => {
expect([...connectionVerificationFailureCodes].sort())
.toEqual(Object.values(AI_KEY_VERIFICATION_FAILURES).map(failure => failure.code).sort());
});
});
+2 -2
View File
@@ -2,7 +2,7 @@ import { SCREENSHOT_PRIVACY_REASONS } from "./screenshot-privacy.js";
import { POSTGRES_IMAGE, POSTGRES_IMAGE_ID, POSTGRES_AMD64_IMAGE, POSTGRES_AMD64_IMAGE_IDS, reviewedPostgresReceiptIdentity } from "./docker-postgres.js";
import { agentJourneyRuns, agentJourneyRunCountValid, journeyRequiredChecks } from "./product-journeys/success-contract.js";
import { validateWorkerTiming } from "./worker-timing.js";
import { connectionCheckpoints, connectionEvidencePasses, connectionRunSignals } from "./connection-evidence.js";
import { connectionCreationFailureCodes, connectionCheckpoints, connectionEvidencePasses, connectionRunSignals } from "./connection-evidence.js";
import { githubJourneyCheckpoints, gradeGitHubReviewJourney } from "./github-review-evidence.js";
import { gradeAntigravityJourney, validateAntigravityJourneyEvidence } from "./antigravity-journey-evidence.js";
import { STARTUP_REUSE_LAYERS, STARTUP_REUSE_REASONS } from "../../packages/adapter-utils/src/startup-reuse.js";
@@ -395,7 +395,7 @@ const fields = {
inputTransport: optional(oneOf("prompt_base64")),
setupChecks: optional(array(shape({ code: string, level: oneOf("info", "warn", "error") }))),
runDiagnostics: optional(array(shape({ runId: string, status: oneOf("succeeded", "failed", "cancelled", "interrupted", "timed_out", "unknown"), signals: array(oneOf(...connectionRunSignals)), logAvailable: boolean }))),
creationFailure: optional(shape({ status: integer, code: oneOf("ai_connection_api_key_rejected", "ai_connection_verification_failed", "connection_request_rejected") })),
creationFailure: optional(shape({ status: integer, code: oneOf(...connectionCreationFailureCodes) })),
connectionId: optional(string), agentId: optional(string), companyId: optional(string), artifactSha256: optional(string), model: optional(string), cleanupRetained: optional(boolean), companyArchived: optional(boolean),
})),
completionQuality: optional(array(shape({