# Python 及其他技术栈

给 Python、Go、Java 或任何其他语言写的 API 加上 rungent。你的 API 提供一份标注好的 OpenAPI 文档，回答当前登录的是谁，并校验一个签名请求头；rungent serve 在旁边运行，一个反向代理把两者放到同一个 origin 上。

rungent 的运行时是 TypeScript，所以用其他语言写的 API 要把它作为独立进程运行，也就是 `rungent serve`。反向代理把 rungent 的路径转给它，其余的转给你的 API。这样浏览器看到的是同一个 origin，用户的会话对两边都有效。

```text
browser ─> proxy :8000 ─┬─ /rungent/v0/*, /mcp, /skill.md, … ─> rungent serve :8787 ─┐
                        └─ everything else ────────────────> your API :8001  <──┘ calls as the user
```

你的 API 要通过 HTTP 实现一份很小的约定。在 Python 里，PyPI 上的 `rungent` kit（导入名 `rungent`）帮你做了大部分；在其他语言里，也就几十行代码。

| 你的 API | 必需 |
|---|---|
| 提供 OpenAPI 3.1，在允许 Agent 使用的操作上加 `x-rungent` | 是 |
| 回答一个身份操作：凭据属于谁 | 是 |
| 在来自 rungent 的调用上校验 `Rungent-Assertion` 请求头 | 是 |
| 回答对其资源的搜索操作 | 否 |

## 标注 FastAPI 应用

```bash
pip install "rungent[fastapi]"
```

这个 kit 需要 Python 3.12 或更高版本。`op()` 为 FastAPI 的 `openapi_extra` 构建 `x-rungent` 对象。它接受蛇形命名的 [x-rungent](x-rungent.md) 键（`timeout_seconds` 会变成 `timeoutSeconds`；嵌套对象保持线上格式的驼峰命名）。有键写错时，它在导入时抛出 `ValueError`，并列出所有问题。

```python
# app.py
from fastapi import FastAPI, Request
from pydantic import BaseModel

from rungent import Identity, op

app = FastAPI(title="Cloud Console")


class Vm(BaseModel):
    id: str
    name: str
    status: str


@app.get("/api/vms", openapi_extra=op("list_vms", description="List cloud servers (VMs) and their status."))
async def list_vms(request: Request) -> list[Vm]:
    return find_vms(current_user(request))


@app.post(
    "/api/vms/{vm_id}/stop",
    openapi_extra=op(
        "stop_vm",
        description="Stop a running cloud server (VM).",
        effect="update",
        resolve={"vm_id": {"op": "list_vms"}},
        confirmation={"title": "Stop server {vm_id}?"},
        cli={"command": "vm stop", "args": ["vm_id"]},
    ),
)
async def stop_vm(vm_id: str, request: Request) -> Vm:
    return stop(current_user(request), vm_id)


@app.get("/api/me", openapi_extra=op("whoami", role="identity"))
async def whoami(request: Request) -> Identity:
    user = current_user(request)
    return Identity(subject=user.id, tenant=user.tenant_id, name=user.name)
```

FastAPI 在 `/openapi.json` 提供这份文档。`Identity` 和下文的搜索、表单模型一样，按线上格式的驼峰命名序列化，并省略缺失的字段。在 `scopes` 里放上 `ADMIN_SCOPE`（`rungent:admin`），用户就能修改 rungent 的模型设置。

## 校验断言

`RungentHost` 把[以用户身份调用](acting-as-the-user.md#verify-the-assertion)里的六项检查装成一个中间件。它按 FastAPI 分派到的路由匹配操作，按操作的 `approval` 键判断是否需要确认。

```python
import json
import os

from rungent import load_public_keys
from rungent.fastapi import RungentCall, RungentHost


def caller(request: Request) -> tuple[str, str | None] | None:
    """(subject, tenant) of the request's credential, as your UI authenticates it."""
    user = current_user(request)
    return (user.id, user.tenant_id) if user else None


RungentHost(
    app,
    keys=load_public_keys([json.loads(os.environ["RUNGENT_PUBLIC_JWK"])]),
    audience="https://console.example.com",
    identity=caller,
)


@app.post("/api/vms/{vm_id}/stop", openapi_extra=op("stop_vm", effect="update"))
async def stop_vm(vm_id: str, request: Request, rungent: RungentCall) -> Vm:
    if rungent is not None:  # 这次调用经由 rungent，且已经过用户确认
        audit(actor="rungent", user=rungent.sub, run=rungent.rid, approval=rungent.apr)
    return stop(current_user(request), vm_id)
```

`audience` 是你的公开 origin，和 rungent 的 `RUNGENT_HOST_ORIGIN` 相同。不带这个请求头的请求原样放行；任何一项检查没通过，就返回 `401 {"detail": "rungent_assertion_invalid", "code": "<check>"}`。`RungentCall` 是校验过的 `AssertionClaims`（`sub`、`ten`、`op`、`rid`、`cid`、`sid`、`apr` 等），用户直接调用时为 `None`。你的 `identity` 函数抛出的 `HTTPException` 会原样作为响应返回。

| `RungentHost` 选项 | 什么时候用 |
|---|---|
| `public_url="https://console.example.com/gw"` | 代理在请求到达 FastAPI 前去掉了一段路径前缀。断言绑定的 URL 会用 `public_url` 加上原始路径和查询串重建；默认是 `audience`。 |
| `replay_cache=Redis.from_url("redis://cache:6379/0")` | 你运行多个 worker 或副本。任何具备 redis-py 的 `set(key, value, *, nx=True, ex=seconds)` 的对象都行，同步异步皆可；默认的 `MemoryReplayCache()` 只在单个进程内有效。 |
| `openapi=lambda: catalog_document` | 应用是一个网关，并没有每个操作对应的路由。这时按方法和路径模板对照这份文档匹配操作；向上游转发请求时用 `strip_rungent_headers(request.headers)`。 |

密钥轮换期间，把两个公钥都传给 `load_public_keys`。

## 搜索和表单操作

`role="search"` 的操作返回 `SearchResponse`。rungent 以用户身份调用它，所以只返回这个用户能看到的内容（[搜索与知识](search.md#add-a-search-source)）：

```python
from rungent import SearchHit, SearchResponse


@app.get("/api/vms/search", openapi_extra=op("search_vms", role="search"))
async def search_vms(request: Request, q: str, limit: int = 10) -> SearchResponse:
    return SearchResponse(hits=[
        SearchHit(type="vm", id=vm.id, title=vm.name, url=f"/console/instance/{vm.id}", content=vm.description)
        for vm in find_vms(current_user(request), q, limit)
    ])
```

`role="form"` 的操作接收目前已知的参数，返回一个 `Form`（[表单与确认](forms-and-approvals.md#declare-the-form)）：

```python
from typing import Any

from rungent import ChoiceQuestion, Form, FormOption, TextQuestion


@app.post("/api/vms/form", openapi_extra=op("vm_form", role="form"))
async def vm_form(args: dict[str, Any]) -> Form:
    return Form(
        prompt="Create a server",
        questions=[
            TextQuestion(id="name", prompt="Name", required=True),
            ChoiceQuestion(id="zone_id", prompt="Zone", required=True,
                           options=[FormOption(id=z.id, label=z.name) for z in await list_zones()]),
        ],
    )


@app.post("/api/vms", openapi_extra=op("create_vm", description="Create a cloud server (VM).", form="vm_form"))
async def create_vm(body: VmSpec, request: Request) -> Vm: ...
```

## Python kit 一览

除了 `rungent.fastapi` 里的 FastAPI 集成，所有东西都从 `rungent` 导入。

| 名称 | 是什么 |
|---|---|
| `op(name, **keys)` | 给 `openapi_extra` 用的 `{"x-rungent": {...}}`，按 x-rungent schema 检查。带类型的嵌套对象：`Confirmation`、`Reference`、`Next`、`Cli`。 |
| `RungentHost`、`RungentCall` | 断言中间件，以及把校验过的声明交给路由的依赖项。 |
| `Identity`、`ADMIN_SCOPE` | 身份操作的返回；`"rungent:admin"`。 |
| `SearchHit`、`SearchResponse` | 搜索的返回：最多 50 条结果，`excerpt` ≤ 300 个字符，`content` ≤ 4000 个字符。 |
| `Form`、`TextQuestion`、`ChoiceQuestion`、`FormOption` | 通用表单：1 到 24 个问题，id 不能重复。 |
| `load_public_keys(jwks)` | 从 `rungent keys generate` 打印的 JWK 得到按 `kid` 索引的公钥。 |
| `verify_assertion(token, *, keys, audience, method, url, body, remember)` | 不依赖 FastAPI，检查签名、有效期、受众、请求绑定和重放；`url` 是发送时的完整 URL，`body` 是原始字节。 |
| `check_call(claims, *, subject, tenant, op, approval)` | 检查用户、操作和确认。 |
| `RungentAssertionError` | 两者都会抛出，带 `code`：没通过的那项检查。 |
| `args_hash`、`canonical_json` | 确认所绑定的哈希，与 TypeScript 里的一致。 |
| `strip_rungent_headers(headers)` | 去掉 `Rungent-Assertion` 和 `Rungent-Host-Assertion` 后的副本。 |

失败代码：`malformed`、`unknown_key`、`bad_signature`、`expired`、`not_yet_valid`、`too_long`、`audience`、`method`、`url`、`body`、`replay`、`subject`、`tenant`、`operation`、`approval_missing`。

## 其他任何语言

用 Go 写的 Acahti 在自己的代码里实现了这份约定。保留你现有的 OpenAPI 生成器（swag、springdoc、手写文件）：它只要把 `x-rungent` 原样传出来就行。身份操作返回 `{"subject": "u_123", "tenant": "t_9", "name": "Ada Lovelace"}`。然后校验断言：只要有一项检查不成立，就以 `401` 和 `rungent_assertion_invalid` 拒绝请求。

| 检查 | 成立条件 |
|---|---|
| 签名 | 头部是 `{"alg":"EdDSA","typ":"rungent-call+jwt","kid":…}`，并且签名能用该 `kid` 对应的固定公钥验证通过 |
| 有效期 | `exp - iat` ≤ 60，`exp` 已过期不超过 60 秒，且 `iat` 超前不超过 60 秒 |
| 受众 | `aud` 是你的公开 origin |
| 请求 | `htm` 是请求方法；`htu` 是你的公开 origin 加上收到的路径和查询串；`bsh` 是原始请求体字节的 base64url SHA-256 |
| 重放 | `jti` 之前没出现过；保留到 `exp` 加上允许的时钟偏差，并由所有进程共享 |
| 用户 | `sub`（以及存在时的 `ten`）等于你的 API 从凭据解析出的身份 |
| 操作 | `op` 是处理这个方法和路径的操作的 `x-rungent.name` |
| 确认 | 当这个操作需要确认时（默认所有写操作都需要），`apr` 存在 |

两项密码学检查，用 Go 标准库实现：

```go
// keys：kid → ed25519.PublicKey，由每个固定 JWK 的 base64url "x" 解码而来。
func verifySignature(token string, keys map[string]ed25519.PublicKey) (claims []byte, err error) {
	parts := strings.Split(token, ".")
	if len(parts) != 3 {
		return nil, errInvalid
	}
	raw, err := base64.RawURLEncoding.DecodeString(parts[0])
	var header struct{ Alg, Kid, Typ string }
	if err != nil || json.Unmarshal(raw, &header) != nil || header.Alg != "EdDSA" || header.Typ != "rungent-call+jwt" {
		return nil, errInvalid
	}
	key, ok := keys[header.Kid]
	sig, err := base64.RawURLEncoding.DecodeString(parts[2])
	if !ok || err != nil || !ed25519.Verify(key, []byte(parts[0]+"."+parts[1]), sig) {
		return nil, errInvalid
	}
	return base64.RawURLEncoding.DecodeString(parts[1])
}

// bsh：收到的原始请求体，在任何解析之前。
func bodyHash(body []byte) string {
	sum := sha256.Sum256(body)
	return base64.RawURLEncoding.EncodeToString(sum[:])
}
```

计算 `htu` 时，即使 rungent 通过内部地址访问你，也要用公开 origin（在 Go 里是 `origin + r.URL.RequestURI()`）。

## 在 API 旁运行 rungent serve

先生成一个签名密钥。这条命令把公钥 JWK 打印出来（给你的 API 用），把私钥写进一个新文件（给 rungent 用）：

```bash
npx rungent keys generate --kid rungent-dev -o rungent-dev.private.jwk > rungent-dev.public.jwk

RUNGENT_URL=http://localhost:8000 \
RUNGENT_HOST_ORIGIN=http://localhost:8000 \
RUNGENT_HOST_BASE_URL=http://localhost:8001 \
RUNGENT_HOST_OPENAPI=/openapi.json \
RUNGENT_SIGNING_KEY="$(cat rungent-dev.private.jwk)" \
RUNGENT_SECRET="a development secret of 32 bytes or more" \
RUNGENT_DATABASE_URL=sqlite:rungent.sqlite \
RUNGENT_MODELS='[{"id":"main","provider":"openai","model":"gpt-4.1-mini","apiKey":"sk-…"}]' \
PORT=8787 \
npx rungent serve
```

`RUNGENT_HOST_ORIGIN` 是浏览器看到的 origin；`RUNGENT_HOST_BASE_URL` 是 rungent 访问你 API 的地址。`rungent serve` 需要 Node.js 24；Docker 镜像 `ghcr.io/rungent/rungent-server` 运行的是同一个服务。所有变量见[部署](deploy.md#configure-it)。

## 把两者放在同一个 origin 后面

任何反向代理都可以。开发时用 Caddy，几行就够：

```text
# Caddyfile
:8000 {
	@rungent path /rungent/* /mcp /skill.md /llms.txt /.well-known/rungent-keys.json
	handle @rungent {
		reverse_proxy localhost:8787
	}
	handle {
		reverse_proxy localhost:8001
	}
}
```

生产环境的 nginx 配置见[部署](deploy.md#route-the-rungent-paths)。然后用一个你的 API 接受的令牌检查一下：

```bash
npx rungent check --openapi http://localhost:8001/openapi.json
curl -H "Authorization: Bearer $TOKEN" http://localhost:8000/skill.md
RUNGENT_HOST=http://localhost:8000 RUNGENT_TOKEN=$TOKEN npx rungent vm stop vm-42
```

`/skill.md` 会列出 `list_vms` 和 `stop_vm`。CLI 先请你确认，然后 rungent 以你的身份调用 `POST /api/vms/vm-42/stop`。要在页面里加面板，做法和 [JavaScript](javascript.md#add-the-dock) 完全一样，只是从 `:8000` 提供。

## 接下来

- [部署](deploy.md)：生产环境中的 Docker 镜像、Postgres、密钥和代理。
- [测试](testing.md)：针对你的 API 端到端地检查这份约定。
