charmbracelet/crush · error

failed to set provider API key: status code

Error message

failed to set provider API key: status code %d

What it means

SetProviderAPIKey expects HTTP 200 from the provider-key endpoint. Any other status (404 workspace missing, 401/403 auth failure, 500 server error) is reported with this error carrying the numeric status.

Solutions

  1. Read the status code in the error to identify the failure class
  2. For 401/403, refresh credentials and retry
  3. For 404, verify the workspace id exists
  4. For 5xx, check server logs and retry after the server recovers
Defensive patterns

Strategy: try-catch

Try / catch

if err := c.SetProviderAPIKey(ctx, wsID, scope, pid, key); err != nil {
    var sc int
    if n, _ := fmt.Sscanf(err.Error(), "failed to set provider API key: status code %d", &sc); n == 1 {
        switch {
        case sc == 401 || sc == 403:
            return reauthAndRetry(ctx)
        case sc == 404:
            return errors.New("workspace not found")
        }
    }
    return err
}

Prevention

When it happens

Trigger: Server responds non-200 to POST /workspaces/{id}/config/provider-key — nonexistent workspace id, invalid/expired auth, or server-side persistence error.

Common situations: Typo in workspace id, stale auth token after re-login elsewhere, server version lacking the provider-key endpoint, key rejected by validation on the server.

Related errors


AI-assisted analysis of charmbracelet/crush@7944b8e522 (2026-08-29). Data as JSON: /api/errors/6fe7b2b1b65a5d44. Report an issue: GitHub.

Appendix: source

Thrown at internal/client/config.go:122

			return fmt.Errorf("failed to marshal oauth token: %w", err)
		}
		raw = b
	default:
		return fmt.Errorf("unsupported api key type %T", apiKey)
	}

	rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/config/provider-key", id), nil, jsonBody(proto.ConfigProviderKeyRequest{
		Scope:      scope,
		ProviderID: providerID,
		Kind:       kind,
		APIKey:     raw,
	}), http.Header{"Content-Type": []string{"application/json"}})
	if err != nil {
		return fmt.Errorf("failed to set provider API key: %w", err)
	}
	defer rsp.Body.Close()
	if rsp.StatusCode != http.StatusOK {
		return fmt.Errorf("failed to set provider API key: status code %d", rsp.StatusCode)
	}
	return nil
}

// ImportCopilot attempts to import a GitHub Copilot token on the
// server.
func (c *Client) ImportCopilot(ctx context.Context, id string) (*oauth.Token, bool, error) {
	rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/config/import-copilot", id), nil, nil, nil)
	if err != nil {
		return nil, false, fmt.Errorf("failed to import copilot: %w", err)
	}
	defer rsp.Body.Close()
	if rsp.StatusCode != http.StatusOK {
		return nil, false, fmt.Errorf("failed to import copilot: status code %d", rsp.StatusCode)
	}
	var result struct {
		Token   *oauth.Token `json:"token"`
		Success bool         `json:"success"`

View on GitHub (pinned to 7944b8e522)