# HTTP 接口

SDK 做的一切都是普通的 HTTPS + JSON，所以任何引擎、任何语言都能直接用：C++（Unreal、自研引擎）、GDScript、Lua、Rust、Python。根地址：`https://yumina.io`。

## 让玩家登录

你的游戏是公开客户端（没有密钥），用授权码 + PKCE（S256）。

**授权地址**——在浏览器里打开，或者交给下面的扫码中转：

```
GET /api/auth/oauth2/authorize
  ?response_type=code&client_id=<client_id>
  &redirect_uri=<redirect>
  &scope=openid profile offline_access ai:chat wallet:read cards:read
  &code_challenge=<base64url(sha256(verifier))>&code_challenge_method=S256
  &state=<random, 16+ chars>
  &resource=https://yumina.io/api/ai/v1
```

`redirect` 可以是 `http://127.0.0.1:<47613–47617>/callback`（每个游戏都已登记）、Yumina 的中转 `https://yumina.io/api/apps/link/callback`，或者你自己加的 https 页面。

**令牌**

```
POST /api/auth/oauth2/token        (application/x-www-form-urlencoded)
grant_type=authorization_code&code=…&redirect_uri=…&client_id=…&code_verifier=…&resource=https://yumina.io/api/ai/v1
grant_type=refresh_token&refresh_token=…&client_id=…&resource=https://yumina.io/api/ai/v1
```

返回 `access_token`（15 分钟）、`refresh_token`（每用一次就换新——永远只留最新的；重复使用旧的会让整次登录失效）、`expires_in`。注销用 `POST /api/auth/oauth2/revoke`（`token`、`token_type_hint=refresh_token`、`client_id`）。

**扫码登录**

```
POST /api/apps/link   { "client_id": "…", "authorize_url": "<authorize URL with the relay as redirect_uri>" }
→ { "user_code": "ACDE-2345", "verification_uri": "https://yumina.io/l",
    "verification_uri_complete": "https://yumina.io/l/ACDE2345",
    "qr": { "size": 29, "rows": ["1111111010…", …] },
    "poll_token": "…", "interval": 2, "expires_in": 600 }
```

授权地址必须带 `prompt=consent`：扫码登录一定会出现确认页，并显示游戏屏幕上的码，别人贴出来的二维码没法悄悄连上玩家的账号。

把 `qr.rows[行][列] == "1" 画成深色方块，外面留 4 格浅色边。然后每 `interval` 秒轮询一次：

```
POST /api/apps/link/poll   { "poll_token": "…" }
→ { "status": "pending" } | { "status": "ready", "code": "…", "redirect_uri": "…" } | { "status": "denied" }   （过期返回 410）
```

用你的 verifier 和中转的 `redirect_uri` 去令牌接口换令牌。code 只给一次。

## 角色对话

下面所有接口都带 `Authorization: Bearer <access_token>`。

```
POST /api/ai/v1/turns
{
  "character": "abigail",                         // 你给说话角色起的 id；每个存档里每个角色一份记忆
  "card": { "id": "<published card id>" },        // 或者 { "world": { …一张 Yumina 卡… } }
  "text": "Morning! Anything warm?",              // 玩家说的话，或者 [舞台说明]
  "inputs": { "hearts": 3, "weather": "foggy" },  // 清单里的 inputs
  "allow": ["invite", { "id": "give_item", "params": { "item": { "enum": ["止血散"] } } }],
                                                  // 可选：这一轮你的规则允许的动作；写成对象可以限定这一轮的参数
                                                  //（字符串用 "enum"，数字用 "min"/"max"）
  "blocked": { "give_gold": "她钱袋空了。" },        // 可选：某个动作这一轮为什么不能做；角色会照这个理由推掉
  "period": "y1-spring-3",                        // 可选：按时段计次数用
  "memory": { "head": "<head from the save, or null>" },
  "conversation": "<id from the last turn>",      // 可选：接着上次对话；不传就开新对话
  "results": [{ "turnId": "…", "action": "give_item", "applied": true, "note": "got a coffee" }],
  "language": "zh-Hans",                          // 可选："zh-Hans"、"en"、"ja"……写语言名也行
  "model": "…",                                   // 可选：GET /models 里的 id
  "manifest": { … },                              // 可选：覆盖登记的清单
  "stream": true
}
```

每个玩家在一个游戏里同时只发一轮，每轮带上一轮返回的 head；上一轮还没答完又发，会收到 `429 request_in_progress`（SDK 会自动排队）。

不带 `stream` 时返回 `{ "turn": Turn }`；带 `stream: true` 时返回 SSE 事件：

| 事件 | 数据 |
| --- | --- |
| `text` | `{ "delta": "…" }` ——接在后面；或 `{ "replace": "…" }`——替换已显示的内容。不会带记账指令。 |
| `line` | `{ "text": "…" }` ——整句台词已经定稿，可以马上显示。台词里答应的事还在核对，所以在 `turn` 到来前什么都别执行。 |
| `turn` | `{ "turn": Turn }` ——最终的、以它为准的结果。 |
| `error` | `{ "error": { "message", "code" } }` |

```json
Turn = {
  "id": "…", "character": "abigail", "conversation": "…",
  "text": "Up since four? You look it.",
  "choices": ["Thanks, Mira.", "Extra strong is right.", "What do I owe you?"],
  "outputs": { "friendship_delta": 5 },
  "action": { "id": "give_item", "params": { "item": "coffee" }, "status": "accepted" },
  "memory": { "head": "…" },
  "model": "…",
  "yumina": { "cost": 0.3, "balance": 1999.7 }
}
```

没有动作时 `action` 是 `null`。被拒的动作是 `"status": "rejected"`，带 `code`（`limit`、`not_allowed`、`invalid_params`、`unknown_action`、`said_not_done`）、按请求 `language` 写的 `reason`、角色想给的 `params`，`said_not_done` 还带 `said`，千万别执行；`"allow": []` 是这一轮一个动作都不允许；角色下一轮会被告知这件事没发生。

`card.world` 是游戏运行时自己现做的卡，格式见[游戏自己做的角色](./cards)。

## 其他接口

| 接口 | 权限 | 返回 |
| --- | --- | --- |
| `GET /api/ai/v1/me` | wallet:read | name, username, balance, plan, defaultModel, plansUrl |
| `GET /api/ai/v1/models` | ai:chat | 玩家能选的模型，顺序和 yumina.io 一样 |
| `GET /api/ai/v1/cards` | cards:read | 为你的游戏发布的卡；这个玩家在「游戏模组」里加过的排在最前，带 `picked: true` |
| `GET /api/ai/v1/memory?character=…&head=…` | ai:chat | 角色在这个存档里记得的事，新的在前 |
| `GET /api/ai/v1/manifest` | ai:chat | 你的游戏当前用的清单 |
| `POST /api/ai/v1/chat/completions` | ai:chat | 兼容 OpenAI 的对话接口，自己拼提示词时用 |

## 错误

错误格式是 `{ "error": { "message", "type", "code" } }`。需要处理的几个：

| code | 状态码 | 怎么办 |
| --- | --- | --- |
| `invalid_token`, `missing_token` | 401 | 刷新令牌；刷新也失败就让玩家重新登录。 |
| `insufficient_balance` | 402 | 告诉玩家，打开 `/me` 里的 `plansUrl`。 |
| `app_in_development` | 403 | 游戏上线前只有你和测试者能登录。 |
| `unknown_head` | 409 | 存档的记忆属于别的账号：不传 head，从头开始。 |
| `rate_limit_exceeded`, `request_in_progress` | 429 | 等 `Retry-After` 秒。每个玩家同时只能有一轮在进行。 |
| `invalid_manifest`, `invalid_request` | 400 | message 会说是哪个字段。 |
| `app_not_reviewed` | 403 | 游戏上线前，只能玩你或测试者发布的卡。 |
