@hsupu/copilot-api 0.7.17-beta.0 → 0.7.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,183 +1,231 @@
1
1
  # Copilot API Proxy (Fork)
2
2
 
3
- > [!WARNING]
4
- > 这是 GitHub Copilot API 的逆向代理。GitHub 官方不提供支持,且可能随时失效。使用风险自负。
5
-
6
- 本项目是 [ericc-ch/copilot-api](https://github.com/ericc-ch/copilot-api) 的 fork,因使用中遇到报错,故尝试魔改。
3
+ > [!NOTE]
4
+ > This is a fork of [ericc-ch/copilot-api](https://github.com/ericc-ch/copilot-api) with additional improvements and bug fixes.
7
5
 
8
- ## Fork 的考虑和改进
6
+ > [!WARNING]
7
+ > This is a reverse proxy for the GitHub Copilot API. It is not officially supported by GitHub and may break at any time. Use at your own risk.
9
8
 
10
- CC + Opus/Haiku 是作者的唯一核心场景。其他任何花哨的功能要么是继承自上游,要么是 fallback 方案。改动全 AI 完成,我只提供功能需求、参考项目和使用反馈。
9
+ A reverse proxy that exposes GitHub Copilot API as OpenAI and Anthropic compatible API endpoints. Works with Claude Code and other tools that speak OpenAI or Anthropic protocols.
11
10
 
12
- fork 相对于上游项目包含以下增强:
11
+ ## Quick Start
13
12
 
14
- ### 新功能
13
+ ### Install from npm (Recommended)
15
14
 
16
- - **`--host` 选项**:将服务器绑定到指定网络接口(如 `--host 0.0.0.0` 绑定所有接口,`--host 127.0.0.1` 仅绑定本地)
17
- - **自适应限流**:基于指数退避的智能限流,支持自动恢复和 Retry-After 头(替代原有的队列限流)
18
- - **直连 Anthropic API**:Claude 模型使用 Copilot 的原生 Anthropic 端点,无需格式转换
19
- - **智能自动截断**:超出上下文限制时自动截断对话历史,支持可选的 tool result 压缩
20
- - **`/api/event_logging/batch` 端点**:为 Anthropic SDK 的 event logging 提供兼容端点(返回 OK,不做处理)
21
- - **`logout` 命令**:通过 `copilot-api logout` 移除已存储的 GitHub token
22
- - **`list-claude-code` 命令**:列出所有本地安装的 Claude Code 版本
23
- - **工具名长度处理**:自动截断超过 64 字符的工具名以符合 OpenAI 限制,使用 hash 后缀避免冲突。响应中会还原原始名称。
24
- - **请求历史 UI**:内置 Web UI(默认启用),可查看、搜索、过滤和导出所有 API 请求/响应。访问 `/history`。
25
- - **`setup-claude-code` 命令**:交互式配置 Claude Code 以使用本代理
26
- - **Sonnet 重定向到 Opus**:可选将 sonnet 模型请求重定向到最佳可用 opus 模型
27
- - **安全研究模式**:为授权渗透测试、CTF 和安全教育提供专用模式
15
+ ```sh
16
+ # Run directly
17
+ npx -y @hsupu/copilot-api start
18
+ ```
28
19
 
29
- ### Bug 修复
20
+ ### Run from Source
30
21
 
31
- - **修复流式响应中缺少 `model` 字段**:Copilot API 的首个流式 chunk 有时 `choices` 数组为空但包含模型名。现已保存该值供后续事件使用。
32
- - **自动修复消息序列错误**:当 tool 调用被中断(如用户取消)时,API 会自动添加占位 `tool_result` 块以维持合法的消息序列
33
- - **修复 `bunx` 符号链接问题**:将 pre-commit hook 改为使用 `bun x` 替代 `bunx` 以提高兼容性
22
+ ```sh
23
+ git clone https://github.com/puxu-msft/copilot-api-js.git
24
+ cd copilot-api-js
25
+ bun install
26
+ bun run dev # Development mode with hot reload
27
+ bun run start # Production mode
28
+ bun run build # Build for distribution
29
+ ```
34
30
 
35
- ## 快速开始
31
+ ## Using with Claude Code
36
32
 
37
- ### npm 安装(推荐)
33
+ Run the interactive setup command:
38
34
 
39
35
  ```sh
40
- # 直接用 npx 运行
41
- npx @hsupu/copilot-api start
36
+ copilot-api setup-claude-code
37
+ ```
42
38
 
43
- # 或全局安装
44
- npm install -g @hsupu/copilot-api
45
- copilot-api start
39
+ Or manually create `~/.claude/settings.json`:
40
+
41
+ ```json
42
+ {
43
+ "env": {
44
+ "ANTHROPIC_BASE_URL": "http://localhost:4141",
45
+ "ANTHROPIC_AUTH_TOKEN": "dummy",
46
+ "ANTHROPIC_MODEL": "opus",
47
+ "ANTHROPIC_SMALL_FAST_MODEL": "haiku",
48
+ "DISABLE_NON_ESSENTIAL_MODEL_CALLS": "1",
49
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
50
+ }
51
+ }
46
52
  ```
47
53
 
48
- ### 从 GitHub 安装
54
+ ## Features
49
55
 
50
- 也可以直接从 GitHub 安装(需要构建步骤):
56
+ ### Dual API Compatibility
51
57
 
52
- ```sh
53
- npm install -g github:puxu-msft/copilot-api-js
54
- copilot-api start
55
- ```
58
+ Exposes both OpenAI and Anthropic compatible endpoints through a single proxy:
56
59
 
57
- ### 从源码运行
60
+ - **Direct Anthropic path** — Uses Copilot API's anthropic endpoint
61
+ - **Translated path** — Translates to OpenAI format and uses Copilot's OpenAI-compatible endpoint
58
62
 
59
- ```sh
60
- # 克隆仓库
61
- git clone https://github.com/puxu-msft/copilot-api-js.git
62
- cd copilot-api-js
63
+ ### Adaptive Rate Limiting
63
64
 
64
- # 安装依赖
65
- bun install
65
+ Intelligent rate limiting with exponential backoff, replacing the upstream queue-based approach. Operates in three modes:
66
66
 
67
- # 开发模式(热重载)
68
- bun run dev
67
+ - **Normal** — Requests pass through freely
68
+ - **Rate-limited** — Queues requests with configurable intervals after hitting limits
69
+ - **Recovering** — Gradually resumes normal operation after consecutive successes
69
70
 
70
- # 生产模式
71
- bun run start
71
+ Learns from Copilot API's `Retry-After` headers for optimal retry timing.
72
72
 
73
- # 构建发布版
74
- bun run build
75
- ```
73
+ ### Auto-Truncate
76
74
 
77
- ### 构建后使用
75
+ Automatically handles context length limits (enabled by default):
78
76
 
79
- ```sh
80
- # 本地运行构建版本
81
- npx .
77
+ - **Reactive** — Retries failed requests with a truncated payload when hitting token or byte limits
78
+ - **Proactive** — Pre-checks requests against known model limits before sending
79
+ - **Dynamic limit learning** — Adjusts limits based on actual API error responses
80
+ - **Tool result compression** — Compresses old `tool_result` content before truncating messages, preserving more conversation context
81
+ - Up to 5 retry attempts per request with 2% safety margin
82
82
 
83
- # 或全局链接
84
- bun link
85
- copilot-api start
86
- ```
83
+ ### Message Sanitization
87
84
 
88
- ## 命令参考
89
-
90
- | 命令 | 说明 |
91
- |------|------|
92
- | `start` | 启动 API 服务器(需要时自动进行认证) |
93
- | `auth` | 仅运行 GitHub 认证流程 |
94
- | `logout` | 移除已存储的 GitHub token |
95
- | `check-usage` | 查看 Copilot 用量和配额 |
96
- | `debug` | 显示诊断信息 |
97
- | `list-claude-code` | 列出所有本地安装的 Claude Code 版本 |
98
- | `setup-claude-code` | 交互式配置 Claude Code 连接 |
99
-
100
- ### start 命令选项
101
-
102
- | 选项 | 说明 | 默认值 |
103
- |------|------|--------|
104
- | `--port`, `-p` | 监听端口 | 4141 |
105
- | `--host`, `-H` | 绑定的主机/接口 | (所有接口) |
106
- | `--verbose`, `-v` | 启用详细日志 | false |
107
- | `--account-type`, `-a` | 账户类型(individual, business, enterprise) | individual |
108
- | `--manual` | 手动请求审批模式 | false |
109
- | `--no-rate-limit` | 禁用自适应限流 | false |
110
- | `--retry-interval` | 限流后重试等待秒数 | 10 |
111
- | `--request-interval` | 限流模式下请求间隔秒数 | 10 |
112
- | `--recovery-timeout` | 尝试恢复前等待的分钟数 | 10 |
113
- | `--consecutive-successes` | 退出限流模式所需的连续成功次数 | 5 |
114
- | `--github-token`, `-g` | 直接提供 GitHub token | 无 |
115
- | `--show-github-token` | 在日志中显示 GitHub token | false |
116
- | `--proxy-env` | 使用环境变量中的代理 | false |
117
- | `--history-limit` | 内存中最大历史记录条数(0 = 无限) | 200 |
118
- | `--no-auto-truncate` | 禁用超限自动截断 | false |
119
- | `--no-compress-tool-results` | 禁用自动截断时的 tool result 压缩 | false(默认启用压缩) |
120
- | `--redirect-anthropic` | 强制 Anthropic 请求走 OpenAI 转换 | false |
121
- | `--no-rewrite-anthropic-tools` | 不重写服务端工具 | false |
122
- | `--redirect-count-tokens` | count_tokens 走 OpenAI 转换而非原生 Anthropic | false |
123
- | `--redirect-sonnet-to-opus` | 将 sonnet 模型请求重定向到最佳可用 opus 模型 | false |
124
- | `--security-research-mode` | 启用安全研究模式(需要口令) | 无 |
125
-
126
- ## API 端点
127
-
128
- ### OpenAI 兼容
129
-
130
- | 端点 | 方法 | 说明 |
131
- |------|------|------|
132
- | `/v1/chat/completions` | POST | Chat completions |
133
- | `/v1/models` | GET | 列出可用模型 |
134
- | `/v1/embeddings` | POST | 文本嵌入 |
85
+ Cleans up messages before forwarding to the API:
135
86
 
136
- ### Anthropic 兼容
87
+ - Filters orphaned `tool_use` / `tool_result` blocks (unpaired due to interrupted tool calls or truncation)
88
+ - Handles server-side tools (`server_tool_use` / `*_tool_result`) that appear inline in assistant messages
89
+ - Fixes double-serialized tool inputs from stream accumulation
90
+ - Removes corrupted blocks from older history data
91
+ - Fixes tool name casing mismatches
92
+ - Removes empty text content blocks
93
+ - Strips `<system-reminder>` tags from message content
137
94
 
138
- | 端点 | 方法 | 说明 |
139
- |------|------|------|
140
- | `/v1/messages` | POST | Messages API |
141
- | `/v1/messages/count_tokens` | POST | Token 计数 |
142
- | `/api/event_logging/batch` | POST | Event logging(空操作) |
95
+ ### Model Name Translation
143
96
 
144
- ### 工具端点
97
+ Translates client-sent model names to matching Copilot models:
145
98
 
146
- | 端点 | 方法 | 说明 |
147
- |------|------|------|
148
- | `/` | GET | 服务器状态 |
149
- | `/usage` | GET | Copilot 用量统计 |
150
- | `/token` | GET | 当前 Copilot token |
151
- | `/health` | GET | 健康检查 |
152
- | `/history` | GET | 请求历史 Web UI(默认启用) |
153
- | `/history/api/*` | GET/DELETE | 历史记录 API 端点 |
99
+ | Input | Resolved To |
100
+ |-------|-------------|
101
+ | `opus`, `sonnet`, `haiku` | Best available model in that family |
102
+ | `claude-opus-4-6` | `claude-opus-4.6` |
103
+ | `claude-sonnet-4-5-20250514` | `claude-sonnet-4.5` |
104
+ | `claude-sonnet-4`, `gpt-4` | Passed through directly |
154
105
 
155
- ## 配合 Claude Code 使用
106
+ Each model family has a priority list. Short aliases resolve to the first available model.
156
107
 
157
- 在用户根目录或者打开的项目中创建 `.claude/settings.json`:
108
+ ### Server-Side Tools
158
109
 
159
- ```json
160
- {
161
- "env": {
162
- "ANTHROPIC_BASE_URL": "http://localhost:4141",
163
- "ANTHROPIC_AUTH_TOKEN": "dummy",
164
- "ANTHROPIC_MODEL": "gpt-4.1",
165
- "ANTHROPIC_SMALL_FAST_MODEL": "gpt-4.1",
166
- "DISABLE_NON_ESSENTIAL_MODEL_CALLS": "1",
167
- "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
168
- },
169
- "permissions": {
170
- "deny": ["WebSearch"]
171
- }
172
- }
173
- ```
110
+ Supports Anthropic server-side tools (e.g., `web_search`, `tool_search`). These tools are executed by the API backend, with both `server_tool_use` and result blocks appearing inline in assistant messages. Tool definitions can optionally be rewritten to a custom format (configurable via `--no-rewrite-anthropic-tools`).
174
111
 
175
- 或使用交互式设置:
112
+ ### Request History UI
176
113
 
177
- ```sh
178
- copilot-api setup-claude-code
179
- ```
114
+ Built-in web interface for inspecting API requests and responses. Access at `http://localhost:4141/history`.
115
+
116
+ - Real-time updates via WebSocket
117
+ - Filter by model, endpoint, status, and time range
118
+ - Full-text search across request/response content
119
+ - Export as JSON or CSV
120
+ - Session tracking and statistics
121
+
122
+ ### Additional Features
123
+
124
+ - **Sonnet → Opus redirection** — Optionally redirect sonnet model requests to the best available opus model
125
+ - **Security research mode** — Passphrase-protected mode for authorized penetration testing, CTF competitions, and security education
126
+ - **Tool name truncation** — Automatically truncates tool names exceeding 64 characters (OpenAI limit) with hash suffixes, restoring original names in responses
127
+ - **Health checks** — Container-ready health endpoint at `/health`
128
+ - **Graceful shutdown** — Connection draining on shutdown signals
129
+ - **Proxy support** — HTTP/HTTPS proxy via environment variables
130
+
131
+ ## Commands
132
+
133
+ | Command | Description |
134
+ |---------|-------------|
135
+ | `start` | Start the API server (authenticates automatically if needed) |
136
+ | `auth` | Run GitHub authentication flow only |
137
+ | `logout` | Remove stored GitHub token |
138
+ | `check-usage` | Show Copilot usage and quota information |
139
+ | `debug info` | Display diagnostic information |
140
+ | `debug models` | Fetch and display raw model data from Copilot API |
141
+ | `list-claude-code` | List all locally installed Claude Code versions |
142
+ | `setup-claude-code` | Interactively configure Claude Code to use this proxy |
143
+
144
+ ### `start` Options
145
+
146
+ | Option | Default | Description |
147
+ |--------|---------|-------------|
148
+ | `--port`, `-p` | 4141 | Port to listen on |
149
+ | `--host`, `-H` | (all interfaces) | Host/interface to bind to |
150
+ | `--verbose`, `-v` | false | Enable verbose logging |
151
+ | `--account-type`, `-a` | individual | Account type: `individual`, `business`, or `enterprise` |
152
+ | `--manual` | false | Manual request approval mode |
153
+ | `--github-token`, `-g` | | Provide GitHub token directly |
154
+ | `--proxy-env` | false | Use proxy from environment variables |
155
+ | `--history-limit` | 200 | Max history entries in memory (0 = unlimited) |
156
+
157
+ **Rate Limiting:**
158
+
159
+ | Option | Default | Description |
160
+ |--------|---------|-------------|
161
+ | `--no-rate-limit` | false | Disable adaptive rate limiting |
162
+ | `--retry-interval` | 10 | Seconds to wait before retrying after rate limit |
163
+ | `--request-interval` | 10 | Seconds between requests in rate-limited mode |
164
+ | `--recovery-timeout` | 10 | Minutes before attempting recovery |
165
+ | `--consecutive-successes` | 5 | Consecutive successes needed to exit rate-limited mode |
166
+
167
+ **Auto-Truncate:**
168
+
169
+ | Option | Default | Description |
170
+ |--------|---------|-------------|
171
+ | `--no-auto-truncate` | false | Disable auto-truncation on context limit errors |
172
+ | `--no-compress-tool-results` | false | Disable tool result compression during truncation |
173
+
174
+ **Anthropic-Specific:**
175
+
176
+ | Option | Default | Description |
177
+ |--------|---------|-------------|
178
+ | `--redirect-anthropic` | false | Force Anthropic requests through OpenAI translation |
179
+ | `--no-rewrite-anthropic-tools` | false | Don't rewrite server-side tools to custom format |
180
+ | `--redirect-count-tokens` | false | Route count_tokens through OpenAI translation |
181
+ | `--redirect-sonnet-to-opus` | false | Redirect sonnet requests to best available opus |
182
+ | `--security-research-mode` | | Enable security research mode with passphrase |
183
+
184
+ ## API Endpoints
185
+
186
+ ### OpenAI Compatible
187
+
188
+ | Endpoint | Method | Description |
189
+ |----------|--------|-------------|
190
+ | `/v1/chat/completions` | POST | Chat completions |
191
+ | `/v1/models` | GET | List available models |
192
+ | `/v1/models/:model` | GET | Get specific model details |
193
+ | `/v1/embeddings` | POST | Text embeddings |
194
+
195
+ All endpoints also work without the `/v1` prefix.
196
+
197
+ ### Anthropic Compatible
198
+
199
+ | Endpoint | Method | Description |
200
+ |----------|--------|-------------|
201
+ | `/v1/messages` | POST | Messages API |
202
+ | `/v1/messages/count_tokens` | POST | Token counting |
203
+ | `/api/event_logging/batch` | POST | Event logging (no-op, returns OK) |
204
+
205
+ ### Utility
206
+
207
+ | Endpoint | Method | Description |
208
+ |----------|--------|-------------|
209
+ | `/health` | GET | Health check (200 healthy, 503 unhealthy) |
210
+ | `/usage` | GET | Copilot usage and quota statistics |
211
+ | `/token` | GET | Current Copilot token information |
212
+ | `/history` | GET | Request history web UI |
213
+ | `/history/ws` | WebSocket | Real-time history updates |
214
+ | `/history/api/entries` | GET | Query history entries |
215
+ | `/history/api/stats` | GET | Usage statistics |
216
+ | `/history/api/export` | GET | Export history (JSON/CSV) |
217
+ | `/history/api/sessions` | GET | List sessions |
218
+
219
+ ## Account Types
220
+
221
+ The account type determines the Copilot API base URL:
222
+
223
+ | Type | API Base URL |
224
+ |------|-------------|
225
+ | `individual` | `api.githubcopilot.com` |
226
+ | `business` | `api.business.githubcopilot.com` |
227
+ | `enterprise` | `api.enterprise.githubcopilot.com` |
180
228
 
181
- ## 上游项目
229
+ ## License
182
230
 
183
- 原始项目的文档、功能和更新请参见:[ericc-ch/copilot-api](https://github.com/ericc-ch/copilot-api)
231
+ [MIT](LICENSE)