Metadata-Version: 2.4
Name: brewer-nash-dispatcher
Version: 0.1.8
Summary: Brewer-Nash session dispatcher + OpenAI compatible streaming API
Author-email: Rexllnia <328626536@qq.com>
License: MIT
Project-URL: Homepage, https://github.com/Rexllnia/brewer-nash-dispatcher
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: fastapi>=0.100
Requires-Dist: uvicorn>=0.20
Requires-Dist: httpx>=0.24
Requires-Dist: websockets>=12.0

# brewer-nash-dispatcher

> A session-affinity dispatcher for AI workers, inspired by the dynamic access-history mechanism of the **Brewer-Nash (Chinese Wall)** security model.
>
> 一个面向 AI Worker 的会话亲和调度器，灵感来自 **Brewer-Nash（中国墙）** 安全模型的动态访问历史机制。

The core idea: **isolation is triggered only by information asymmetry.** Workers with identical history are interchangeable; a worker holding non-empty history is walled off from unrelated new tasks. Fresh tasks target the zero-information state, so only workers with empty history qualify.

核心思想：**只有信息不对称才触发隔离。** history 完全相同的 worker 可以互换；持有非空 history 的 worker 不能接不相关的新任务。新任务的目标状态是"零信息"，因此只有 `history=[]` 的全新 worker 才有资格。

---

## Install / 安装

### pip

```bash
pip install brewer-nash-dispatcher
```

---

## Quick Start / 快速开始

> 三个进程，三个终端。

### 1. Start the dispatcher / 启动调度器

```bash
brewer-nash-dispatcher --host 127.0.0.1 --port 9000
```

### 2. Attach workers / 挂载 worker

任意能向 `/ws` 建立 WebSocket 的客户端都可以作为 worker。仓库内附带了一个用于测试的参考实现：

```bash
python -m fake_agent --url ws://127.0.0.1:9000/ws
```

可以启动多个实例，每个代表一个 worker。

### 3. Start the OpenAI-compatible gateway / 启动 OpenAI 兼容网关

```bash
brewer-nash-dispatcher-openai-apikey-server --host 127.0.0.1 --port 8001
```

### 4. Use with any OpenAI SDK / 用任意 OpenAI SDK 调用

现在可以用任意 OpenAI SDK 指向 `http://127.0.0.1:8001/v1`：

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://127.0.0.1:8001/v1",
    api_key="sk-darkdola-demo-123456",
)

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello"}],
    stream=True,          # required — only streaming is supported
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

> **Note**: The gateway only supports streaming mode (`stream=true`). Non-streaming requests return `400`.
>
> **注意**：网关仅支持流式模式（`stream=true`）。非流式请求会返回 `400`。

---

## Architecture / 架构

```text
┌──────────────┐      HTTP/SSE      ┌────────────────────┐
│  OpenAI SDK  │ ─────────────────▶ │  apikey-server     │
│  (client)    │ ◀───────────────── │  :8001 /v1/...     │
└──────────────┘                    └─────────┬──────────┘
                                              │
                                              │ WebSocket
                                              ▼
                                    ┌────────────────────┐
                                    │  dispatcher        │
                                    │  :9000 /ws         │
                                    │  session affinity  │
                                    └─────────┬──────────┘
                                              │
                          ┌───────────────────┼───────────────────┐
                          ▼                   ▼                   ▼
                    ┌──────────┐        ┌──────────┐        ┌──────────┐
                    │ worker A │        │ worker B │        │ worker C │
                    │ hist=[]  │        │ hist=[x] │        │ hist=[]  │
                    └──────────┘        └──────────┘        └──────────┘
```

New task (`history=[]`) is routed only to workers whose history is empty (A or C). A worker with non-empty history (B) is walled off from unrelated tasks and can only continue conversations whose history it already holds.

新任务（`history=[]`）只会被路由到 history 为空的 worker（A 或 C）。持有非空 history 的 worker（B）不能接不相关的新任务，只能继续它已经承载的会话。

---

## Why Brewer-Nash / 为什么是 Brewer-Nash

In the **Brewer-Nash** model, a subject is allowed to access an object only if doing so does not violate a Chinese Wall — i.e., does not grant access across datasets that must remain isolated. The wall is not pre-declared; it emerges from the subject's access history.

In **brewer-nash-dispatcher**, each worker's `history` plays the role of access history. A worker that has already "seen" information from task A cannot be reused for unrelated task B, because doing so would leak A into B's context. Only zero-history workers are safe for fresh tasks.

在 **Brewer-Nash** 模型中，主体只有在不违反中国墙的前提下才能访问客体——即不能跨越必须隔离的数据集。中国墙不是预先声明的，而是从主体的访问历史中动态浮现。

在 **brewer-nash-dispatcher** 中，每个 worker 的 `history` 就扮演访问历史的角色。已经"看过"任务 A 信息的 worker 不能复用于不相关的任务 B，否则会把 A 泄漏进 B 的上下文。只有零 history 的 worker 对新任务才安全。

---

## Session Affinity / 会话亲和

| Worker state | Can accept new task? | Can continue existing session? |
| :--- | :---: | :---: |
| `history == []` | ✅ | ❌ (nothing to continue) |
| `history == [task_id]` | ❌ | ✅ (only that `task_id`) |
| `history == [task_id, ...]` | ❌ | ✅ (any `task_id` in history) |

| Worker 状态 | 能接新任务？ | 能续接已有会话？ |
| :--- | :---: | :---: |
| `history == []` | ✅ | ❌（没有可续接的） |
| `history == [task_id]` | ❌ | ✅（仅该 `task_id`） |
| `history == [task_id, ...]` | ❌ | ✅（history 中任意 `task_id`） |

---

## Components / 组件

| Component | Entry point | Role |
| :--- | :--- | :--- |
| **dispatcher** | `brewer-nash-dispatcher` | WebSocket server, routes tasks to workers by session affinity |
| **apikey-server** | `brewer-nash-dispatcher-openai-apikey-server` | OpenAI-compatible HTTP/SSE gateway, validates API key, proxies to dispatcher |
| **fake_agent** | `python -m fake_agent` | Reference worker implementation, useful for local testing |

| 组件 | 入口 | 作用 |
| :--- | :--- | :--- |
| **dispatcher** | `brewer-nash-dispatcher` | WebSocket 服务端，按会话亲和把任务路由到 worker |
| **apikey-server** | `brewer-nash-dispatcher-openai-apikey-server` | OpenAI 兼容的 HTTP/SSE 网关，校验 API Key 后转发给 dispatcher |
| **fake_agent** | `python -m fake_agent` | 参考 worker 实现，用于本地测试 |

---

## Configuration / 配置项

### dispatcher

| Flag | Default | Description |
| :--- | :--- | :--- |
| `--host` | `127.0.0.1` | Bind address |
| `--port` | `9000` | WebSocket port |

### apikey-server

| Flag | Default | Description |
| :--- | :--- | :--- |
| `--host` | `127.0.0.1` | Bind address |
| `--port` | `8001` | HTTP port |
| API Key | `sk-darkdola-demo-123456` | Set via server config (see source) |

> API Key 的配置方式以源码为准。演示用的默认 key 仅适用于本地开发，请勿在生产环境沿用。

---

## Test / 测试

```bash
# Terminal 1
brewer-nash-dispatcher

# Terminal 2
python -m fake_agent --url ws://127.0.0.1:9000/ws

# Terminal 3
brewer-nash-dispatcher-openai-apikey-server

# Terminal 4 — send a test request
python - <<'PY'
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:8001/v1", api_key="sk-darkdola-demo-123456")
stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello"}],
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)
PY
```

If the worker is attached and history is empty, you should see the streamed response within the same terminal.

如果 worker 已挂载且 history 为空，你应该能在同一个终端看到流式输出。

---

## Known Limitations / 已知限制

- **Streaming only**: the gateway rejects `stream=false` with `400`. / 网关拒绝 `stream=false`，返回 `400`。
- **WebSocket transport**: workers must be able to open a WS connection to `/ws`. / worker 必须能向 `/ws` 建立 WebSocket 连接。
- **In-memory routing state**: dispatcher keeps session affinity in memory; restarting it loses routing history. / dispatcher 的会话亲和状态保存在内存中，重启会丢失路由历史。
- **Single dispatcher**: no built-in clustering; scale by running multiple dispatchers behind an L7 proxy if needed. / 无内置集群；需要横向扩展时可在 L7 代理后跑多个 dispatcher。

---

## License / 许可证

MIT License. See [LICENSE](LICENSE) for details.

MIT 许可证。详见 [LICENSE](LICENSE)。
