# 凭据连接

1. CredentialData，存在凭据池里
2. resolve_connection 读取外部文件或运行辅助程序
3. ResolvedConnection
4. 线路层：凭据没有 base_url 时才用 model.base_url

从不压成一个裸 key 字符串。是否 OAuth 看 `kind`，不看 token 前缀。一个 key 可以连别的端点：百炼的 key 存上 `https://…maas.aliyuncs.com/compatible-mode/v1`，同样走 `openai-completions` 协议，不用另建模型列表。

## `CredentialData`

| `kind` | `auth_value` | `data` |
| --- | --- | --- |
| `api_key` | key 本身 | 通常为空 |
| `oauth` | access token | `refresh_token` `expires_at_ms` `client_id` `token_endpoint` `scope` `id_token` |
| `device_code` | access token | `refresh_token` `expires_at_ms` `device_code_flow_id` |
| `cli_delegated` | 空 | `store_path` `access_key_path` `refresh_key_path` `expires_key_path` |
| `credential_process` | 空 | `command` `parses` `json_key_path` `cache_seconds` |
| `sso` | 空 | `broker` `subject` |

每种 kind 还有 `base_url` 和 `headers`，默认为空。邮箱、显示名、组织 ID 留在 `Credential.metadata`。

## `resolve_connection`

| Kind | 行为 |
| --- | --- |
| `cli_delegated` | 读外部文件；以那个 CLI 为准 |
| `credential_process` | 运行辅助程序，token 按 `cache_seconds` 复用。失败抛 `AuthCredentialProcessError`，解析链重新抛出，绝不换用其他层。 |
| `sso` | 抛 `AuthConfigError`：保留项，没有流程实现 |
| 其他 | 返回 `auth_value` |

`auth.usage.acquire_pooled` 返回 `(conn, profile, cred_id)`。

## 线路规则

```
api_key  = conn.auth_value if conn else opts.api_key
base_url = (conn.base_url if conn and conn.base_url else None) or model.base_url
headers  = {**(model.headers or {}), **(conn.headers if conn else {}), **(opts.headers or {})}
is_oauth = bool(conn and conn.kind in ("oauth", "device_code"))
```

`openai_completions`、`openai_responses`、`anthropic` 相同。

**旧格式与搬迁**

运行时只认当前结构，带 `__type__` 的旧 JSON 直接报错。`auth/carry_over.py` 在存储第一次读取前运行一次：先把文件夹复制一份，再把每个旧的 `~/.openprogram/auth/<provider>/<account>.json` 的 payload 改写，并进每个 provider 一个的列表 `auth/<provider>/credentials.json`。不用重新登录。

| 旧 `__type__` | 新 `kind` | `auth_value` 来自 |
| --- | --- | --- |
| `ApiKeyPayload` | `api_key` | `api_key` |
| `OAuthPayload` | `oauth` | `access_token` |
| `DeviceCodePayload` | `device_code` | `access_token` |
| `CliDelegatedPayload` | `cli_delegated` | 空 |
| `ExternalProcessPayload` | `credential_process` | 空 |
| `SsoPayload` | `sso` | 空 |

其余字段移入 `data`。

**测试**

- `resolve_connection`：每种 kind；key 带或不带 `base_url`；实时读外部文件；辅助程序的 json 和文本解析、缓存窗口、每种失败都抛出；sso 抛出。
- `CredentialData` 序列化往返，包括 `data`。
- 线路规则：凭据的 `base_url` 优先；`kind=oauth` 不靠前缀就置 `is_oauth`。
- 端到端：带百炼 `base_url` 的 key 打到百炼；官方 OpenAI key 仍走默认端点。
- 搬迁：字段正确、无 `__type__`、每个凭据都到位、再跑一次不改任何东西。

[认证存储](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/auth/unified-auth-storage.zh.html)
