li2895 commited on
Commit
3f08cad
·
0 Parent(s):

fix: 思考内容可见 + Anthropic 流式协议修复

Browse files
Files changed (5) hide show
  1. Dockerfile +6 -0
  2. README.md +350 -0
  3. config.json +47 -0
  4. package.json +15 -0
  5. server.js +1595 -0
Dockerfile ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ FROM node:18-alpine
2
+ ENV PORT=7860
3
+ WORKDIR /app
4
+ COPY server.js config.json package.json ./
5
+ EXPOSE 7860
6
+ CMD ["node", "server.js"]
README.md ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ima2api
2
+
3
+ 逆向 IMA App 的 AI API,封装为 **OpenAI Chat Completions** 和 **Anthropic Messages** 兼容格式,支持 **tool calling**(prompt 注入方式)。
4
+
5
+ 一次抓包即可,之后都会自动刷新cookie。
6
+
7
+ ## 快速开始
8
+
9
+ ```bash
10
+ cd ima2api
11
+ npm install
12
+ python3 ima_runner.py
13
+ ```
14
+
15
+ ## 配置
16
+
17
+ 编辑 `config.json`:
18
+
19
+ ```json5
20
+ {
21
+ "server": { "port": 8080, "host": "0.0.0.0" },
22
+ "auth": {
23
+ // 从 IMA App 抓包获取的完整 Cookie
24
+ "cookie": "IMA-GUID=...;IMA-TOKEN=...;...",
25
+ "refresh_token": "抓包https://ima.qq.com/auth_login/refresh请求获取",
26
+ "registration_id": "抓包https://ima.qq.com/auth_login/refresh请求获取"
27
+ },
28
+ "api_keys": ["sk-ima-demo-key-change-me"],
29
+ "default_model": "glm-5.2"
30
+ }
31
+ ```
32
+
33
+ ### 获取 Cookie
34
+
35
+ 1. 手机安装 IMA App,QQ/微信登录
36
+ 2. 配置 HTTPS 代理(mitmproxy / Charles / Fiddler)
37
+ 3. 发送任意消息,复制请求中的 `x-ima-cookie` 值
38
+ 4. 填入 `config.json` → `auth.cookie`
39
+ 5. 将 https://ima.qq.com/auth_login/refresh 这条请求里的refresh_token和registration_id也填入config.json (用于自动刷新cookie)
40
+
41
+ ## API 端点
42
+
43
+ ### OpenAI 兼容 (`/v1`)
44
+
45
+ ```bash
46
+ # 模型列表
47
+ curl http://localhost:8080/v1/models -H "Authorization: Bearer YOUR_KEY"
48
+
49
+ # 普通对话
50
+ curl http://localhost:8080/v1/chat/completions \
51
+ -H "Authorization: Bearer YOUR_KEY" \
52
+ -H "Content-Type: application/json" \
53
+ -d '{"model":"glm-5.2","messages":[{"role":"user","content":"你好"}]}'
54
+
55
+ # 流式
56
+ curl http://localhost:8080/v1/chat/completions \
57
+ -H "Authorization: Bearer YOUR_KEY" \
58
+ -d '{"model":"glm-5.2","messages":[{"role":"user","content":"你好"}],"stream":true}'
59
+
60
+ # Tool calling
61
+ curl http://localhost:8080/v1/chat/completions \
62
+ -H "Authorization: Bearer YOUR_KEY" \
63
+ -d '{
64
+ "model":"glm-5.2",
65
+ "messages":[{"role":"user","content":"执行 uname -a"}],
66
+ "tools":[{
67
+ "type":"function",
68
+ "function":{"name":"Bash","description":"执行命令","parameters":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}}
69
+ }],
70
+ "tool_choice":"auto"
71
+ }'
72
+
73
+ # Tool 结果回传 (多轮)
74
+ curl http://localhost:8080/v1/chat/completions \
75
+ -H "Authorization: Bearer YOUR_KEY" \
76
+ -d '{
77
+ "model":"glm-5.2",
78
+ "messages":[
79
+ {"role":"user","content":"执行 uname -a"},
80
+ {"role":"assistant","tool_calls":[{"id":"call_1","type":"function","function":{"name":"Bash","arguments":"{\"command\":\"uname -a\"}"}}]},
81
+ {"role":"tool","tool_call_id":"call_1","content":"Linux ..."}
82
+ ]
83
+ }'
84
+ ```
85
+
86
+ ### Anthropic 兼容 (`/v1`)
87
+
88
+ ```bash
89
+ # 流式对话
90
+ curl http://localhost:8080/v1/messages \
91
+ -H "Authorization: Bearer YOUR_KEY" \
92
+ -d '{"model":"glm-5.2","max_tokens":1024,"messages":[{"role":"user","content":"你好"}],"stream":true}'
93
+
94
+ # Tool use
95
+ curl http://localhost:8080/v1/messages \
96
+ -H "Authorization: Bearer YOUR_KEY" \
97
+ -d '{
98
+ "model":"glm-5.2",
99
+ "max_tokens":1024,
100
+ "messages":[{"role":"user","content":"执行 pwd"}],
101
+ "tools":[{"name":"Bash","description":"执行命令","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}}]
102
+ }'
103
+ ```
104
+
105
+ ## Tool Calling 机制
106
+
107
+ 采用 **prompt 注入** 方式实现 function calling:
108
+
109
+ ```
110
+ ## CRITICAL — YOU MUST USE FUNCTION CALLING
111
+
112
+ <function name="Bash">
113
+ <description>执行 bash 命令</description>
114
+ <parameters>{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}</parameters>
115
+ </function>
116
+
117
+ ## HOW TO CALL A FUNCTION
118
+ 输出 <function_call>{"name":"...","arguments":{...}}</function_call>,然后立即停止。
119
+ ```
120
+
121
+ 工作流:
122
+ 1. 客户端发送 `tools` 参数 → 服务器将工具定义注入 prompt
123
+ 2. IMA 模型输出 `<function_call>…</function_call>` → 服务器解析为 `tool_calls` / `tool_use` 返回
124
+ 3. 客户端本地执行工具 → 将结果回传
125
+ 4. 服务器检测到 `tool_use` + `tool_result` → 用 `⚠️ 系统通知` 格式告知模型结果
126
+ 5. 模型基于结果直接回答用户
127
+
128
+ 特性:
129
+ - 最多展示 8 个工具(截断保护)
130
+ - Schema 自动压缩(去掉 `$schema`/`$defs`/`$ref` 等元数据)
131
+ - 自动检测中文用户 → 要求中文回复
132
+ - 会话自动复用(基于首条消息 hash)
133
+
134
+ ## 可用模型
135
+
136
+ | 模型 ID | 底座 | 说明 |
137
+ |---------|------|------|
138
+ | `glm-5.2` | GLM-5.2 | 默认 |
139
+ | `glm-5.2-think` | GLM-5.2 | 思考模式 |
140
+ | `deepseek-v4-flash` | DeepSeek V4 | 快速 |
141
+ | `deepseek-v4-flash-think` | DeepSeek V4 | 思考模式 |
142
+ | `hy3-preview` | 混元 Hy3 | 预览 |
143
+ | `hy3-preview-think` | 混元 Hy3 | 思考模式 |
144
+
145
+ ## 认证
146
+
147
+ - `Authorization: Bearer <key>` 或 `x-api-key: <key>`
148
+ - 支持配置多个 API Key
149
+
150
+ ## 客户端集成
151
+
152
+ ### OpenAI SDK (Python)
153
+
154
+ ```python
155
+ from openai import OpenAI
156
+ client = OpenAI(base_url="http://localhost:8080/v1", api_key="your-key")
157
+ response = client.chat.completions.create(
158
+ model="glm-5.2",
159
+ messages=[{"role": "user", "content": "你好"}],
160
+ tools=[{"type":"function","function":{"name":"Bash","description":"执行命令","parameters":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}}}],
161
+ stream=True
162
+ )
163
+ for chunk in response:
164
+ if chunk.choices[0].delta.content:
165
+ print(chunk.choices[0].delta.content, end="")
166
+ ```
167
+
168
+ ### Anthropic SDK (Python)
169
+
170
+ ```python
171
+ from anthropic import Anthropic
172
+ client = Anthropic(base_url="http://localhost:8080/v1", api_key="your-key")
173
+ with client.messages.stream(
174
+ model="glm-5.2",
175
+ max_tokens=1024,
176
+ messages=[{"role": "user", "content": "你好"}]
177
+ ) as stream:
178
+ for text in stream.text_stream:
179
+ print(text, end="")
180
+ ```
181
+
182
+ ## 局限性
183
+
184
+ - IMA 模型需要 prompt 注入才能触发 tool calling(非原生支持)
185
+ - 流式输出中的 `<function_call>` 块会被服务器端过滤(客户端不可见)
186
+ - IMA 会话限制约 20 轮,超出后需重新建立
187
+
188
+
189
+ ## 保姆级部署教程(零基础上手)
190
+
191
+ 本教程不需要编程基础,不需要安装任何软件,全程在手机和网页上完成。总耗时约 15 分钟。
192
+
193
+ ---
194
+
195
+ ### 准备工作:获取 IMA 的 Cookie
196
+
197
+ 这一步是唯一需要花点时间的。你需要从手机上的 IMA App 抓取请求数据。
198
+
199
+ **你需要:** 一部安装了 IMA App 的手机(已用 QQ/微信登录)+ 一台电脑。
200
+
201
+ #### 1.1 安装抓包工具
202
+
203
+ 在电脑上安装 **mitmproxy**(免费、开源):
204
+ - 打开 [mitmproxy.org](https://mitmproxy.org/),点击下载 Windows 安装包,一路「下一步」安装完成。
205
+
206
+ #### 1.2 配置手机代理
207
+
208
+ 1. 确保手机和电脑在**同一个 WiFi** 下
209
+ 2. 电脑上:Win+R → 输入 `cmd` → 回车,输入 `ipconfig`,找到 IPv4 地址(形如 `192.168.x.x`)
210
+ 3. 手机上:设置 → WiFi → 点击当前连接的 WiFi → 代理 → 手动
211
+ - 服务器:填入电脑的 IPv4 地址,端口:`8080`
212
+ 4. 手机浏览器打开 `mitm.it`,按提示安装 mitmproxy 的 CA 证书
213
+ - Android:选「用于 VPN 和应用」
214
+ - iOS:还需在 设置→通用→关于→证书信任设置 中开启信任
215
+
216
+ #### 1.3 抓取 Cookie
217
+
218
+ 1. 电脑上 Win+R → `cmd` → 输入 `mitmweb` 回车(浏览器会自动打开 http://127.0.0.1:8081)
219
+ 2. 手机上打开 IMA App,随便发一条消息(比如「你好」)
220
+ 3. 回到电脑浏览器,在 mitmweb 界面找 `ima.qq.com` 开头的请求
221
+ 4. 点开任意一条,在 Request Headers 中找到 **`x-ima-cookie`**,完整复制它的值
222
+
223
+ > 这个值很长,类似 `IMA-GUID=xxx;APP-VERSION=xxx;IMA-Q36=xxx;...;IMA-TOKEN=xxx;...`
224
+
225
+ #### 1.4 获取 refresh_token 和 registration_id
226
+
227
+ 1. 在 mitmweb 页面的搜索框输入 `/auth_login/refresh`
228
+ 2. 点开这个请求 → 点击 Request 标签 → 在内容区找:
229
+ - `refresh_token`:一串很长的字符串
230
+ - `registration_id`:另一串字符串
231
+ 3. 分别复制保存
232
+
233
+ **把这三个值记在手边备用:** x-ima-cookie、refresh_token、registration_id。
234
+
235
+ > 抓完后记得**把手机代理关掉**(WiFi 设置里改回「无」),否则断开电脑后手机没法上网。
236
+
237
+ ---
238
+
239
+ ### 第一步:注册 Hugging Face
240
+
241
+ 1. 打开 [huggingface.co/join](https://huggingface.co/join)
242
+ 2. 输入邮箱和密码 → Next → 完成人机验证
243
+ 3. 去邮箱点击确认链接激活账号
244
+
245
+ ---
246
+
247
+ ### 第二步:创建 Space
248
+
249
+ 1. 打开 [huggingface.co/new-space](https://huggingface.co/new-space)
250
+ 2. 填写:
251
+ - **Space name**:随便取,比如 `my-ima-api`(只能用英文字母、数字、短横线)
252
+ - **License**:选 `mit`
253
+ - **Space SDK**:选 **Docker**
254
+ - **Space Template**:选 **Blank**
255
+ - **Space Visibility**:选 **Private**(关键!不选这个别人能看见你的 API 地址)
256
+ 3. 点 **Create Space** 按钮
257
+
258
+ ---
259
+
260
+ ### 第三步:上传文件
261
+
262
+ 你现在在 Space 页面了。用网页拖拽上传,不需要装 Git。
263
+
264
+ 1. 点击顶部 **Files** 标签页
265
+ 2. 点击 **Add file** → **Upload files**
266
+ 3. 把以下 4 个文件拖进去:`server.js`、`config.json`、`package.json`、`Dockerfile`
267
+ 4. 往下滚,Commit message 随便填,点 **Commit to main**
268
+
269
+ > 不用上传 `ima_runner.py`,HF 上不需要它。
270
+
271
+ ---
272
+
273
+ ### 第四步:设置 Secrets(密码)
274
+
275
+ 1. 在 Space 页面顶部点 **Settings** 标签页
276
+ 2. 往下滚找到 **Repository Secrets**
277
+ 3. 点 **New secret**,逐个添加:
278
+
279
+ | Name | Value |
280
+ |------|-------|
281
+ | `IMA_COOKIE` | 粘贴完整 x-ima-cookie |
282
+ | `IMA_REFRESH_TOKEN` | 粘贴 refresh_token |
283
+ | `IMA_REGISTRATION_ID` | 粘贴 registration_id |
284
+ | `IMA_API_KEYS` | 自己编一个密码,如 `sk-my-secret-key-2024` |
285
+
286
+ > `IMA_API_KEYS` 是你调用 API 用的「密码」。多个 key 用逗号分隔:`sk-key1,sk-key2`。
287
+
288
+ ---
289
+
290
+ ### 第五步:等待启动
291
+
292
+ 1. 回到顶部点 **App** 标签页
293
+ 2. 看到 "Building..." 等待 1-2 分钟,变成绿色 "Running" 即成功
294
+ 3. 如果卡住,点右上角 → **Factory reboot**
295
+
296
+ ---
297
+
298
+ ### 第六步:测试
299
+
300
+ 浏览器打开 `https://你的用户名-你的空间名.hf.space/`,看到 JSON 数据含 `"service": "ima2api"` 就说明成功。
301
+
302
+ ---
303
+
304
+ ### 第七步:接入 Claude Code / Codex
305
+
306
+ **Claude Code(终端):**
307
+ ```bash
308
+ set ANTHROPIC_BASE_URL=https://你的用户名-你的空间名.hf.space/v1
309
+ set ANTHROPIC_API_KEY=sk-my-secret-key-2024
310
+ claude
311
+ ```
312
+
313
+ **Codex(桌面版设置页):**
314
+ - Provider: Anthropic 或 OpenAI Compatible
315
+ - Base URL: `https://你的用户名-你的空间名.hf.space/v1`
316
+ - API Key: `sk-my-secret-key-2024`
317
+ - Model: `glm-5.2`
318
+
319
+ **Cherry Studio / ChatGPT-Next-Web:** 创建自定义 Provider,填入相同的 Base URL 和 API Key。
320
+
321
+ ---
322
+
323
+ ### 常见问题
324
+
325
+ **Q: 显示 "Running" 但访问报错?**
326
+ 等 30 秒再试,启动后首次 token 刷新需要十几秒。
327
+
328
+ **Q: API 返回 401 Unauthorized?**
329
+ 检查 Secrets 里的 `IMA_API_KEYS` 和请求里用的 key 是否完全一致。
330
+
331
+ **Q: 回复是乱码或空内容?**
332
+ Cookie 可能过期了,重新抓一次 IMA Cookie,更新 Secret 后点 Factory reboot。
333
+
334
+ **Q: Token 会自动刷新吗?**
335
+ 会。server.js 内置定时刷新,无需额外操作。
336
+
337
+ **Q: 免费层够用吗?**
338
+ 完全够。16GB 内存 + 2 CPU,个人使用远达不到限制。长时间不活动会休眠,下次访问自动唤醒(等几秒就好)。
339
+
340
+ ---
341
+
342
+ ### 本地开发仍可用
343
+
344
+ ```bash
345
+ # 方式1:Python watchdog(token 刷新会重启 npm)
346
+ python ima_runner.py
347
+
348
+ # 方式2:纯 Node(HF 同款,token 热更新不重启)
349
+ npm start
350
+ ```
config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "server": {
3
+ "port": 8080,
4
+ "host": "0.0.0.0"
5
+ },
6
+ "auth": {
7
+ "cookie": "抓包获取并填入",
8
+ "refresh_token": "抓包获取并填入",
9
+ "registration_id": "抓包获取并填入"
10
+ },
11
+ "api_keys": [
12
+ "sk-ima-demo-key-change-me"
13
+ ],
14
+ "default_model": "glm-5.2",
15
+ "models": {
16
+ "hy3-preview": {
17
+ "type": 0,
18
+ "id": "official_0",
19
+ "name": "Tencent Hy3 preview"
20
+ },
21
+ "hy3-preview-think": {
22
+ "type": 2,
23
+ "id": "official_2",
24
+ "name": "Tencent Hy3 preview (Think)"
25
+ },
26
+ "deepseek-v4-flash": {
27
+ "type": 3,
28
+ "id": "official_3",
29
+ "name": "DeepSeek V4-Flash"
30
+ },
31
+ "deepseek-v4-flash-think": {
32
+ "type": 1,
33
+ "id": "official_1",
34
+ "name": "DeepSeek V4-Flash (Think)"
35
+ },
36
+ "glm-5.2": {
37
+ "type": 3000,
38
+ "id": "official_3000",
39
+ "name": "GLM-5.2"
40
+ },
41
+ "glm-5.2-think": {
42
+ "type": 3001,
43
+ "id": "official_3001",
44
+ "name": "GLM-5.2 (Think)"
45
+ }
46
+ }
47
+ }
package.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "ima2api",
3
+ "version": "1.0.0",
4
+ "description": "IMA AI API reverse-engineered server - OpenAI + Anthropic compatible API",
5
+ "main": "server.js",
6
+ "scripts": {
7
+ "start": "node server.js",
8
+ "dev": "node --watch server.js"
9
+ },
10
+ "keywords": ["ima", "ai", "openai", "anthropic", "api"],
11
+ "license": "MIT",
12
+ "engines": {
13
+ "node": ">=18"
14
+ }
15
+ }
server.js ADDED
@@ -0,0 +1,1595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ const https = require("https");
4
+ const http = require("http");
5
+ const crypto = require("crypto");
6
+
7
+ // ============================================================
8
+ // 1. 配置
9
+ // ============================================================
10
+ const CONFIG = require("./config.json");
11
+ const BASE_HOST = "ima.qq.com";
12
+ const BASE_URL = "https://ima.qq.com";
13
+ let COOKIE = process.env.IMA_COOKIE || CONFIG.auth.cookie;
14
+ const REFRESH_TOKEN = process.env.IMA_REFRESH_TOKEN || CONFIG.auth.refresh_token;
15
+ const REGISTRATION_ID = process.env.IMA_REGISTRATION_ID || CONFIG.auth.registration_id;
16
+ const API_KEYS = new Set([ ...(CONFIG.api_keys || []), ...(process.env.IMA_API_KEYS || "").split(/[\n,]+/).map(k => k.trim()).filter(Boolean) ]);
17
+
18
+ let IMA_TOKEN = (() => {
19
+ const m = COOKIE.match(/IMA-TOKEN=([^;]+)/);
20
+ return m ? m[1] : "";
21
+ })();
22
+
23
+ let BKN = (() => {
24
+ let h = 5381;
25
+ for (let i = 0; i < IMA_TOKEN.length; i++) h += (h << 5) + IMA_TOKEN.charCodeAt(i);
26
+ return String(h & 0x7fffffff);
27
+ })();
28
+
29
+ function maskKey(k) {
30
+ if (!k || k.length < 12) return "***";
31
+ return k.slice(0, 6) + "..." + k.slice(-4);
32
+ }
33
+
34
+ // ============================================================
35
+ // 2. HTTP 客户端
36
+ // ============================================================
37
+ const IMA_HEADERS = {
38
+ "from_browser_ima": "1",
39
+ get "x-ima-cookie"() { return COOKIE; },
40
+ get "x-ima-bkn"() { return BKN; },
41
+ referer: BASE_URL,
42
+ origin: BASE_URL,
43
+ "User-Agent": "okhttp/4.12.0",
44
+ "Content-Type": "application/json; charset=utf-8",
45
+ "Accept-Encoding": "gzip", // ⭐ 修复: 与真实 App 请求头一致
46
+ };
47
+
48
+ function imaPost(path, body, extraH = {}, timeout = 30000) {
49
+ return new Promise((resolve, reject) => {
50
+ const payload = JSON.stringify(body);
51
+ const req = https.request({
52
+ hostname: BASE_HOST, port: 443, path, method: "POST",
53
+ headers: { ...IMA_HEADERS, ...extraH, "Content-Length": Buffer.byteLength(payload) },
54
+ timeout,
55
+ }, (res) => {
56
+ // ⭐ 修复: 处理 gzip 压缩响应(与 Accept-Encoding: gzip 配套)
57
+ const zlib = require("zlib");
58
+ const encoding = res.headers["content-encoding"] || "";
59
+ let stream = res;
60
+ if (encoding === "gzip") stream = res.pipe(zlib.createGunzip());
61
+ else if (encoding === "deflate") stream = res.pipe(zlib.createInflate());
62
+ const chunks = [];
63
+ stream.on("data", (c) => chunks.push(c));
64
+ stream.on("end", () => {
65
+ const raw = Buffer.concat(chunks).toString("utf-8");
66
+ try { resolve({ status: res.statusCode, data: JSON.parse(raw) }); }
67
+ catch { resolve({ status: res.statusCode, data: raw }); }
68
+ });
69
+ stream.on("error", reject);
70
+ });
71
+ req.on("error", reject);
72
+ req.on("timeout", () => { req.destroy(); reject(new Error("timeout")); });
73
+ req.write(payload); req.end();
74
+ });
75
+ }
76
+
77
+ function imaSse(path, body) {
78
+ return new Promise((resolve, reject) => {
79
+ const payload = JSON.stringify(body);
80
+ const req = https.request({
81
+ hostname: BASE_HOST, port: 443, path, method: "POST",
82
+ headers: { ...IMA_HEADERS, Accept: "text/event-stream", "Content-Length": Buffer.byteLength(payload) },
83
+ timeout: 180000,
84
+ }, (res) => {
85
+ if (res.statusCode !== 200) {
86
+ let e = ""; res.on("data", c => e += c);
87
+ res.on("end", () => reject(new Error(`HTTP ${res.statusCode}: ${e}`)));
88
+ return;
89
+ }
90
+ resolve(parseSSE(res));
91
+ });
92
+ req.on("error", reject);
93
+ req.on("timeout", () => { req.destroy(); reject(new Error("SSE timeout")); });
94
+ req.write(payload); req.end();
95
+ });
96
+ }
97
+ // Token auto-refresh (in-memory, no Python dependency)
98
+ async function refreshCookie() {
99
+ const uid = (COOKIE.match(/IMA-UID=([^;]+)/) || [])[1];
100
+ if (!uid || !REFRESH_TOKEN || !REGISTRATION_ID) {
101
+ console.error("[REFRESH] Cannot refresh: missing uid, REFRESH_TOKEN, or REGISTRATION_ID");
102
+ return;
103
+ }
104
+ const payload = JSON.stringify({
105
+ user_id: uid,
106
+ refresh_token: REFRESH_TOKEN,
107
+ token_type: 14,
108
+ registration_id: REGISTRATION_ID,
109
+ });
110
+ try {
111
+ const data = await imaPost("/auth_login/refresh", JSON.parse(payload));
112
+ if (data.data && data.data.code === 0 && data.data.token) {
113
+ const newToken = data.data.token;
114
+ const validTime = data.data.token_valid_time || 7200;
115
+ COOKIE = COOKIE.replace(/IMA-TOKEN=([^;]+)/, "IMA-TOKEN=" + newToken);
116
+ IMA_TOKEN = newToken;
117
+ let h = 5381;
118
+ for (let i = 0; i < IMA_TOKEN.length; i++) h += (h << 5) + IMA_TOKEN.charCodeAt(i);
119
+ BKN = String(h & 0x7fffffff);
120
+ console.log("[REFRESH] Token refreshed, valid " + validTime + "s, BKN=" + BKN);
121
+ } else {
122
+ console.error("[REFRESH] Refresh returned unexpected: " + JSON.stringify(data).slice(0, 200));
123
+ }
124
+ } catch (e) {
125
+ console.error("[REFRESH] Failed: " + e.message);
126
+ }
127
+ }
128
+
129
+
130
+ function parseSSEBlock(part) {
131
+ let event = "";
132
+ const dataLines = [];
133
+ for (const line of part.split("\n")) {
134
+ if (line.startsWith("event:")) event = line.slice(6).trim();
135
+ else if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
136
+ else if (line.startsWith("data")) dataLines.push("");
137
+ }
138
+ return { event, data: dataLines.join("\n") };
139
+ }
140
+
141
+ async function* parseSSE(readable) {
142
+ let buf = "";
143
+ let _sseCount = 0;
144
+ for await (const chunk of readable) {
145
+ buf += chunk.toString("utf-8");
146
+ const parts = buf.split(/\r?\n\r?\n/); buf = parts.pop() || "";
147
+ for (const part of parts) {
148
+ if (!part.trim()) continue;
149
+ const evt = parseSSEBlock(part);
150
+ if (DEBUG_SSE) {
151
+ _sseCount++;
152
+ const preview = evt.data ? evt.data.slice(0, 300) : "(no data)";
153
+ console.log("[SSE-DBG #" + _sseCount + "] event=" + (evt.event || "(none)") + " data=" + preview);
154
+ }
155
+ if (evt.event || evt.data) yield evt;
156
+ }
157
+ }
158
+ if (buf.trim()) {
159
+ const evt = parseSSEBlock(buf);
160
+ if (DEBUG_SSE) console.log("[SSE-DBG #final] event=" + (evt.event || "(none)") + " data=" + ((evt.data||"").slice(0,300)));
161
+ if (evt.event || evt.data) yield evt;
162
+ }
163
+ }
164
+
165
+ const CONTROL_EVENTS = new Set(["COMPLETED", "CLOSE", "INNER_EXCEPTION", "ERROR", "FAILED"]);
166
+ const DEBUG_SSE = process.env.IMA_DEBUG === "1";
167
+
168
+ // Recursive key lookup in nested objects (depth-limited)
169
+ function _recurseObj(obj, keySet, depth) {
170
+ if (depth > 3) return "";
171
+ for (const k of keySet) {
172
+ const v = obj[k];
173
+ if (typeof v === "string" && v) return v;
174
+ }
175
+ for (const v of Object.values(obj)) {
176
+ if (v && typeof v === "object" && !Array.isArray(v)) {
177
+ const r = _recurseObj(v, keySet, depth + 1);
178
+ if (r) return r;
179
+ }
180
+ }
181
+ return "";
182
+ }
183
+
184
+ const _TEXT_KEYS = new Set(["Text", "text", "Content", "content", "Delta", "delta", "Msg", "msg", "reply", "Reply", "answer", "Answer"]);
185
+ const _THINK_KEYS = new Set(["think", "Think", "thinking", "Thinking", "reasoning",
186
+ "reasoning_content", "Reasoning", "thought", "Thought",
187
+ "思维", "思考", "推理",
188
+ "reasoningText", "thinkContent", "think_text", "Message"]);
189
+
190
+ function extractEventText(d) {
191
+ if (d == null) return "";
192
+ if (typeof d === "string") return d;
193
+ if (typeof d !== "object") return String(d);
194
+ return _recurseObj(d, _TEXT_KEYS, 0);
195
+ }
196
+
197
+ // Extract thinking/reasoning content from SSE event data
198
+ function extractThinkText(d) {
199
+ if (d == null) return "";
200
+ if (typeof d === "string") return "";
201
+ if (typeof d !== "object") return "";
202
+ return _recurseObj(d, _THINK_KEYS, 0);
203
+ }
204
+
205
+ // Return both text & think content from a parsed SSE event
206
+ function eventTexts(evt) {
207
+ const raw = evt && evt.data;
208
+ if (!raw) return { text: "", think: "" };
209
+ let d;
210
+ try { d = JSON.parse(raw); }
211
+ catch { try { d = tryRepairJson(raw); } catch { d = null; } }
212
+ if (d == null) return { text: "", think: "" };
213
+ // THINKING events: IMA uses "Message" key for streaming thinking content
214
+ if (evt.event === "THINKING" && typeof d.Message === "string") return { text: "", think: d.Message };
215
+ return { text: extractEventText(d), think: extractThinkText(d) };
216
+ }
217
+
218
+ function eventText(evt) {
219
+ const raw = evt && evt.data;
220
+ if (!raw) return "";
221
+ let d;
222
+ try { d = JSON.parse(raw); }
223
+ catch { try { d = tryRepairJson(raw); } catch { d = null; } }
224
+ if (d == null) return "";
225
+ return extractEventText(d);
226
+ }
227
+
228
+ // ============================================================
229
+ // 3. IMA API
230
+ // ============================================================
231
+ async function imaInitSession(question) {
232
+ const { data } = await imaPost("/cgi-bin/session_logic/init_session", {
233
+ env_info: { interact_type: 2, robot_type: 10000 },
234
+ name: (question || "新对话").slice(0, 50),
235
+ msgs_limit: 20, // IMA 上限为 20(超过会报 code=51)
236
+ });
237
+ if (data.code === 0) return data.session_id;
238
+ throw new Error(`InitSession failed: code=${data.code} msg=${data.msg}`);
239
+ }
240
+
241
+ function imaQaStream(sessionId, question, modelType, modelId) {
242
+ return imaSse("/cgi-bin/assistant/qa", {
243
+ session_id: sessionId,
244
+ robot_type: 10000,
245
+ question,
246
+ question_type: 2,
247
+ command_info: { question_info: {} },
248
+ client_id: crypto.randomUUID(),
249
+ model_info: { model_type: modelType, model_id: modelId },
250
+ });
251
+ }
252
+
253
+ async function collectResponseText(events) {
254
+ let text = "";
255
+ const seen = [];
256
+ for await (const evt of events) {
257
+ if (CONTROL_EVENTS.has(evt.event)) break;
258
+ text += eventText(evt);
259
+ if (DEBUG_SSE) seen.push(evt.event || "(none)");
260
+ }
261
+ if (DEBUG_SSE && !text) console.error(`[SSE-EMPTY] events=${JSON.stringify(seen)}`);
262
+ return text;
263
+ }
264
+
265
+ // ============================================================
266
+ // 4. 会话缓存
267
+ // ============================================================
268
+ const sessions = new Map();
269
+ const SESSION_TTL = 30 * 60 * 1000;
270
+
271
+ function getCachedSession(convId) {
272
+ const now = Date.now();
273
+ for (const [k, v] of sessions) { if (now - v.ts > SESSION_TTL) sessions.delete(k); }
274
+ if (convId && sessions.has(convId)) { sessions.get(convId).ts = now; return sessions.get(convId).id; }
275
+ return null;
276
+ }
277
+
278
+ async function ensureSession(convId, question, forceNew = false) {
279
+ if (!forceNew) {
280
+ const c = getCachedSession(convId);
281
+ if (c) return c;
282
+ }
283
+ const id = await imaInitSession(question);
284
+ if (convId) sessions.set(convId, { id, ts: Date.now() });
285
+ return id;
286
+ }
287
+
288
+ // ⭐ 修复: IMA 会话达到 msgs_limit 后自动重建,避免"突然结束"
289
+ async function imaQaStreamWithRetry(convId, question, modelType, modelId) {
290
+ let sessionId = await ensureSession(convId, question);
291
+ const events = await imaQaStream(sessionId, question, modelType, modelId);
292
+ // 收集并检测是否触发会话限制错误(INNER_EXCEPTION 含 session limit)
293
+ return (async function*() {
294
+ let hitLimit = false;
295
+ for await (const evt of events) {
296
+ if (evt.event === "INNER_EXCEPTION" || evt.event === "ERROR" || evt.event === "FAILED") {
297
+ // IMA 会话满了通常返回 INNER_EXCEPTION,此时重建 session 重试一次
298
+ try {
299
+ const newId = await ensureSession(convId, question, true);
300
+ const retryEvents = await imaQaStream(newId, question, modelType, modelId);
301
+ for await (const e2 of retryEvents) yield e2;
302
+ } catch (_) {
303
+ yield evt; // 重试也失败,把原始事件透传出去
304
+ }
305
+ return;
306
+ }
307
+ yield evt;
308
+ }
309
+ })();
310
+ }
311
+
312
+ // ============================================================
313
+ // 5. 模型
314
+ // ============================================================
315
+ const MODELS = CONFIG.models;
316
+ const DEFAULT_MODEL = CONFIG.default_model;
317
+
318
+ function resolveModel(requested) {
319
+ if (!requested) return MODELS[DEFAULT_MODEL];
320
+ if (MODELS[requested]) return MODELS[requested];
321
+ const lower = requested.toLowerCase();
322
+ for (const [k, v] of Object.entries(MODELS)) {
323
+ if (k.toLowerCase() === lower || String(v.type) === lower) return v;
324
+ }
325
+ return MODELS[DEFAULT_MODEL];
326
+ }
327
+
328
+ // ============================================================
329
+ // 6. 认证 & 工具
330
+ // ============================================================
331
+ function checkAuth(req) {
332
+ const bearer = (req.headers["authorization"] || "").replace(/^Bearer\s+/i, "");
333
+ if (bearer && API_KEYS.has(bearer)) return true;
334
+ return API_KEYS.has(req.headers["x-api-key"] || "");
335
+ }
336
+
337
+ function cors(res) {
338
+ res.setHeader("Access-Control-Allow-Origin", "*");
339
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
340
+ res.setHeader("Access-Control-Allow-Headers",
341
+ "Content-Type, Authorization, x-api-key, x-conversation-id, x-session-id, x-request-id, x-stainless-*");
342
+ }
343
+
344
+ function json(res, code, obj) {
345
+ cors(res);
346
+ res.writeHead(code, { "Content-Type": "application/json; charset=utf-8" });
347
+ res.end(JSON.stringify(obj));
348
+ if (code >= 400) {
349
+ console.error(`[RESP] ${code} ${JSON.stringify(obj).slice(0, 200)}`);
350
+ }
351
+ }
352
+
353
+ function extractContent(msg) {
354
+ if (typeof msg.content === "string") return msg.content;
355
+ if (Array.isArray(msg.content))
356
+ return msg.content.map(c => {
357
+ if (c.type === "text") return c.text;
358
+ if (c.type === "tool_result") {
359
+ // Anthropic tool_result content 可能是 string 或 content_block[]
360
+ const tc = typeof c.content === "string" ? c.content
361
+ : Array.isArray(c.content) ? c.content.map(cc => cc.text || "").join("") : "";
362
+ return `Tool result:\n${tc}`;
363
+ }
364
+ if (c.type === "tool_use") return `Tool call: ${c.name}(${JSON.stringify(c.input)})`;
365
+ return "";
366
+ }).filter(Boolean).join("\n");
367
+ return String(msg.content || "");
368
+ }
369
+
370
+ // ============================================================
371
+ // 7. Function Calling — Prompt 注入引擎
372
+ // ============================================================
373
+
374
+ function escapeRawCtrlInStrings(s) {
375
+ let out = "", inStr = false, esc = false;
376
+ for (let i = 0; i < s.length; i++) {
377
+ const c = s[i];
378
+ if (esc) { out += c; esc = false; continue; }
379
+ if (c === "\\") { out += c; esc = true; continue; }
380
+ if (c === '"') { inStr = !inStr; out += c; continue; }
381
+ if (inStr) {
382
+ if (c === "\n") { out += "\\n"; continue; }
383
+ if (c === "\r") { out += "\\r"; continue; }
384
+ if (c === "\t") { out += "\\t"; continue; }
385
+ }
386
+ out += c;
387
+ }
388
+ return out;
389
+ }
390
+
391
+ // 修复 LLM 常见的 JSON 错误 (未转义引号、尾逗号、缺括号、字符串内裸换行)
392
+ function tryRepairJson(raw) {
393
+ try { return JSON.parse(raw); } catch (e) { /* continue */ }
394
+ let fixed = raw;
395
+ // 0. 转义字符串内的裸控制符 (写文件时 content 含真实换行 → 否则 JSON.parse 失败)
396
+ fixed = escapeRawCtrlInStrings(fixed);
397
+ try { return JSON.parse(fixed); } catch (e) { /* continue */ }
398
+ // 1. 去尾逗号
399
+ fixed = fixed.replace(/,(\s*[}\]])/g, '$1');
400
+ try { return JSON.parse(fixed); } catch (e) { /* continue */ }
401
+ // 2. 补缺失的闭合括号
402
+ let depth = 0;
403
+ for (const c of fixed) {
404
+ if (c === '{' || c === '[') depth++;
405
+ if (c === '}' || c === ']') depth--;
406
+ }
407
+ if (depth > 0) {
408
+ const lastChar = fixed.trim().slice(-1);
409
+ const closer = lastChar === '}' ? ']' : '}';
410
+ fixed += closer.repeat(Math.min(depth, 5));
411
+ try { return JSON.parse(fixed); } catch (e) { /* continue */ }
412
+ }
413
+ // 3. 提取 name + arguments (即使 JSON 破损也能尽可能恢复)
414
+ const nameMatch = fixed.match(/"name"\s*:\s*"([^"]+)"/);
415
+ if (nameMatch) {
416
+ const argsStart = fixed.indexOf('{', fixed.indexOf('"arguments"'));
417
+ if (argsStart >= 0) {
418
+ let d = 0, end = -1;
419
+ for (let i = argsStart; i < fixed.length; i++) {
420
+ if (fixed[i] === '{' || fixed[i] === '[') d++;
421
+ if (fixed[i] === '}' || fixed[i] === ']') { d--; if (d === 0) { end = i + 1; break; } }
422
+ }
423
+ try { return { name: nameMatch[1], arguments: JSON.parse(fixed.slice(argsStart, end)) }; } catch (e) { /* fall through */ }
424
+ }
425
+ return { name: nameMatch[1], arguments: {} };
426
+ }
427
+ return null;
428
+ }
429
+
430
+ // 压缩 JSON Schema: 去掉 $schema/$defs/$ref 等元数据,单行紧凑输出
431
+ function compactSchema(schema) {
432
+ if (!schema || typeof schema !== "object") return "{}";
433
+ // 深拷贝后递归清理
434
+ function clean(obj) {
435
+ if (Array.isArray(obj)) return obj.map(clean);
436
+ if (obj && typeof obj === "object") {
437
+ const out = {};
438
+ for (const [k, v] of Object.entries(obj)) {
439
+ if (k.startsWith("$")) continue; // 去掉 $schema, $defs, $ref, $dynamicAnchor 等
440
+ out[k] = clean(v);
441
+ }
442
+ return out;
443
+ }
444
+ return obj;
445
+ }
446
+ return JSON.stringify(clean(schema)); // 单行,无缩进
447
+ }
448
+
449
+ function buildToolsPrompt(tools) {
450
+ if (!tools || tools.length === 0) return "";
451
+
452
+ const funcDefs = tools
453
+ .filter(t => t.type === "function" && t.function)
454
+ .map(t => {
455
+ const fn = t.function;
456
+ const params = compactSchema(fn.parameters);
457
+ return `<function name="${fn.name}">
458
+ <description>${fn.description || "No description"}</description>
459
+ <parameters>${params}</parameters>
460
+ </function>`;
461
+ })
462
+ .join("\n");
463
+
464
+ return `## ⚠️ CRITICAL — YOU MUST USE FUNCTION CALLING
465
+
466
+ You have access to these functions. When the user asks you to do something
467
+ that a function can handle, you MUST call the function. NEVER say "I cannot"
468
+ or "I don't have the ability". NEVER tell the user to save a file, run a
469
+ command, or do any step themselves — DO IT by calling the function (e.g. use
470
+ Write to create files, Bash to run commands). ALWAYS use a function instead.
471
+
472
+ ${funcDefs}
473
+
474
+ ## HOW TO CALL A FUNCTION
475
+
476
+ Output EXACTLY this format, then STOP:
477
+
478
+ <function_call>
479
+ {"name": "<function_name>", "arguments": {<args_as_json>}}
480
+ </function_call>
481
+
482
+ Rules:
483
+ - arguments MUST be a valid JSON object matching the function's parameters
484
+ - For file content, put the FULL content in the string value (newlines allowed)
485
+ - Do NOT add any text before or after the <function_call> block
486
+ - NEVER output file content or code for the user to copy — write it via Write`;
487
+ }
488
+
489
+ // ⭐ 工具结果回传轮专用 — "继续行动"版工具提示。
490
+ // 修复历史: ① 旧的强制版 ("YOU MUST call / 不要输出任何文本") 让模型回传轮要么再发多余
491
+ // 调用要么沉默; ② 过软版 ("有足够信息就用纯文本作答") 又走向另一极端 —— 模型把"让我先读
492
+ // 取文件"这种【意图叙述】当成回答然后停手, 多步任务半途而废。
493
+ // 本版核心原则: 叙述意图 ≠ 完成任务。只要还有未完成的步骤, 必须【在本轮就发出函数调用】,
494
+ // 不能只说"我接下来要做 X"。只有当任务真正全部完成时, 才用纯文本给出最终答复。
495
+ function buildToolsPromptSoft(tools) {
496
+ if (!tools || tools.length === 0) return "";
497
+
498
+ const funcDefs = tools
499
+ .filter(t => t.type === "function" && t.function)
500
+ .map(t => {
501
+ const fn = t.function;
502
+ return `<function name="${fn.name}">
503
+ <description>${fn.description || "No description"}</description>
504
+ <parameters>${compactSchema(fn.parameters)}</parameters>
505
+ </function>`;
506
+ })
507
+ .join("\n");
508
+
509
+ return `## Available functions
510
+
511
+ ${funcDefs}
512
+
513
+ ## CRITICAL — keep going until the task is fully done
514
+
515
+ The user's request may need MULTIPLE steps. After each function result, decide:
516
+ the task is NOT finished yet → call the next function NOW; the task IS fully
517
+ finished → give the final answer in plain text.
518
+
519
+ NEVER reply with only your intention (e.g. "Let me read the file", "I'll now
520
+ start the server", "下一步我将…"). Stating intent is NOT an action and NOT an
521
+ answer. If you intend to do something, you MUST emit the function call for it
522
+ in THIS SAME reply.
523
+
524
+ ## To call a function
525
+ Output EXACTLY: <function_call>{"name":"...","arguments":{...}}</function_call> then stop.
526
+ (For file content, put the FULL content in the string value; newlines allowed.)
527
+
528
+ ## To finish
529
+ Only when every step is done, reply to the user in plain text WITHOUT any
530
+ <function_call> block.`;
531
+ }
532
+
533
+ // ⭐ StreamFilter: 实时过滤流式输出中的 <function_call> 块
534
+ // 防止 Claude Code 客户端因看到 XML 标记而截停
535
+ class StreamFilter {
536
+ constructor() {
537
+ this._buf = ''; // 未决缓冲区
538
+ this._emitted = ''; // 已输出的纯净文本
539
+ this._funcBlocks = []; // 捕获的 function_call JSON
540
+ this._inFunc = false; // 是否在 <function_call> 内部
541
+ this._tagLen = 16; // '<function_call>'.length
542
+ this._leftover = ''; // ⭐ parseCalls 无法解析的残留文本 (供流式层兜底输出)
543
+ }
544
+
545
+ // 喂入新文本块,返回应发送给客户端的纯净文本 (可能为空)
546
+ feed(chunk) {
547
+ this._buf += chunk;
548
+ const out = [];
549
+ const startTag = '<function_call>';
550
+ const endTag = '</function_call>';
551
+
552
+ while (this._buf.length > 0) {
553
+ if (!this._inFunc) {
554
+ const idx = this._buf.indexOf(startTag);
555
+ if (idx === -1) {
556
+ // 没有发现开始标签 — 但先检查尾部是否部分匹配
557
+ const partialLen = this._partialMatch(startTag);
558
+ if (partialLen > 0) {
559
+ // 保留可能的部分标签在缓冲区
560
+ const safe = this._buf.slice(0, -partialLen);
561
+ if (safe) out.push(safe);
562
+ this._buf = this._buf.slice(-partialLen);
563
+ break;
564
+ }
565
+ // 完全安全,全部输出
566
+ out.push(this._buf);
567
+ this._buf = '';
568
+ break;
569
+ }
570
+ // 发现开始标签 — 输出标签之前的文本
571
+ if (idx > 0) out.push(this._buf.slice(0, idx));
572
+ this._buf = this._buf.slice(idx + startTag.length);
573
+ this._inFunc = true;
574
+ }
575
+
576
+ if (this._inFunc) {
577
+ const idx = this._buf.indexOf(endTag);
578
+ if (idx === -1) {
579
+ // 还没找到结束标签 — 全部抑制
580
+ break;
581
+ }
582
+ // 找到结束标签 — 捕获函数调用 JSON
583
+ const json = this._buf.slice(0, idx).trim();
584
+ if (json) this._funcBlocks.push(json);
585
+ this._buf = this._buf.slice(idx + endTag.length);
586
+ this._inFunc = false;
587
+ // 继续循环,可能后面还有文本或更多 function_call
588
+ }
589
+ }
590
+
591
+ const text = out.join('');
592
+ if (text) this._emitted += text;
593
+ return text;
594
+ }
595
+
596
+ // 检查缓冲区末尾是否部分匹配 tag
597
+ _partialMatch(tag) {
598
+ for (let i = tag.length - 1; i > 0; i--) {
599
+ if (this._buf.endsWith(tag.slice(0, i))) return i;
600
+ }
601
+ return 0;
602
+ }
603
+
604
+ // 流结束时调用 — 返回可能残留的缓冲区内容 (不含 function_call 部分)
605
+ flush() {
606
+ if (this._inFunc) {
607
+ // ⭐ 修复: 流在 </function_call> 到达前就结束了 (IMA 截断 / 模型漏写闭合标签)。
608
+ // 旧逻辑直接丢弃缓冲区, 导致"调用命令后无任何回复" — 这里改为把残留 JSON
609
+ // 当作一个 function block 捕获, 交给 parseCalls() 去尽力修复。
610
+ const pending = this._buf.trim();
611
+ if (pending) this._funcBlocks.push(pending);
612
+ this._buf = '';
613
+ this._inFunc = false;
614
+ return '';
615
+ }
616
+ if (this._buf) {
617
+ this._emitted += this._buf;
618
+ const r = this._buf;
619
+ this._buf = '';
620
+ return r;
621
+ }
622
+ return '';
623
+ }
624
+
625
+ // 解析已捕获的所有 function_call 块
626
+ parseCalls() {
627
+ const calls = [];
628
+ for (const raw of this._funcBlocks) {
629
+ const parsed = tryRepairJson(raw);
630
+ if (parsed && parsed.name) {
631
+ calls.push({
632
+ id: 'toolu_' + crypto.randomUUID().slice(0, 12),
633
+ type: 'function',
634
+ function: {
635
+ name: parsed.name || '',
636
+ arguments: JSON.stringify(parsed.arguments || parsed.parameters || {}),
637
+ },
638
+ });
639
+ } else if (raw.length > 0) {
640
+ // ⭐ JSON 修复失败 — 累积到 _leftover, 由流式层兜底输出, 避免对话静默中断。
641
+ // (非流式走 cleanText/_emitted; 流式层需读取 leftover 单独 emit)
642
+ const note = '\n[Function call (malformed)]:\n' + raw + '\n';
643
+ this._emitted += note;
644
+ this._leftover += note;
645
+ }
646
+ }
647
+ return calls;
648
+ }
649
+
650
+ get cleanText() { return this._emitted; }
651
+ get hasFunc() { return this._funcBlocks.length > 0; }
652
+ get leftover() { return this._leftover; }
653
+ }
654
+
655
+ function parseFunctionCalls(text) {
656
+ if (!text) return { found: false, text: "" };
657
+
658
+ // 也匹配 ```json {...} ``` 格式 (模型可能输出 JSON 代码块)
659
+ const jsonBlockRegex = /```(?:json)?\s*\n?\s*(\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\})\s*\n?\s*```/g;
660
+
661
+ const regex = /<function_call>\s*\n?\s*(\{[\s\S]*?\})\s*\n?\s*<\/function_call>/g;
662
+ const calls = [];
663
+ let cleanText = text;
664
+
665
+ // 尝试两种格式: <function_call> 和 ```json name/arguments
666
+ const patterns = [
667
+ regex,
668
+ /```(?:json)?\s*\n?\s*\{[^{}]*"name"\s*:\s*"[^"]+"[^{}]*"arguments"\s*:\s*\{[\s\S]*?\}\s*\}\s*\n?\s*```/g,
669
+ ];
670
+
671
+ for (const pattern of patterns) {
672
+ let match;
673
+ while ((match = pattern.exec(text)) !== null) {
674
+ const parsed = tryRepairJson(match[1].trim());
675
+ if (parsed && parsed.name) {
676
+ calls.push({
677
+ id: "toolu_" + crypto.randomUUID().slice(0, 12),
678
+ type: "function",
679
+ function: {
680
+ name: parsed.name || "",
681
+ arguments: JSON.stringify(parsed.arguments || parsed.parameters || {}),
682
+ },
683
+ });
684
+ }
685
+ }
686
+ if (calls.length > 0) break;
687
+ }
688
+
689
+ if (calls.length > 0) {
690
+ cleanText = text.replace(regex, "").replace(/```(?:json)?\s*\n?\s*\{[\s\S]*?\}\s*\n?\s*```/g, "").trim();
691
+ return { found: true, calls, text: cleanText };
692
+ }
693
+
694
+ // 调试: 检查模型是否输出了近似的 function call 格式
695
+ if (text.includes('function') || text.includes('tool') || text.includes('bash') || text.includes('read_file')) {
696
+ }
697
+ return { found: false, text };
698
+ }
699
+
700
+ // ============================================================
701
+ // 8. OpenAI /v1/chat/completions
702
+ // ============================================================
703
+ async function openaiChat(req, res, body) {
704
+ const modelKey = body.model || DEFAULT_MODEL;
705
+ const model = resolveModel(modelKey);
706
+ const stream = !!body.stream;
707
+ const messages = body.messages || [];
708
+ const tools = body.tools || null;
709
+ const toolChoice = body.tool_choice || null;
710
+
711
+ // --- 构建 question ---
712
+ const hasToolResults = messages.some(m => m.role === "tool");
713
+ const hasToolCalls = messages.some(m => m.role === "assistant" && m.tool_calls);
714
+ let question;
715
+
716
+ // 确定工具集 (两个分支共用)
717
+ let effectiveTools = tools;
718
+ if ((!effectiveTools || effectiveTools.length === 0) && toolChoice !== "none") {
719
+ effectiveTools = [
720
+ {type: "function", function: {name: "Bash", description: "Execute bash command", parameters: {type: "object", properties: {command: {type: "string"}}, required: ["command"]}}},
721
+ {type: "function", function: {name: "Read", description: "Read a file", parameters: {type: "object", properties: {file_path: {type: "string"}}, required: ["file_path"]}}},
722
+ {type: "function", function: {name: "Write", description: "Write to a file", parameters: {type: "object", properties: {file_path: {type: "string"}, content: {type: "string"}}, required: ["file_path", "content"]}}},
723
+ {type: "function", function: {name: "Glob", description: "Find files by pattern", parameters: {type: "object", properties: {pattern: {type: "string"}}, required: ["pattern"]}}},
724
+ {type: "function", function: {name: "Grep", description: "Search file contents", parameters: {type: "object", properties: {pattern: {type: "string"}, path: {type: "string"}}, required: ["pattern"]}}},
725
+ ];
726
+ }
727
+ // ⭐ 标题生成请求不需要 tools
728
+ const _sysParts = messages.filter(m => m.role === "system").map(m => extractContent(m));
729
+ const _sysPrompt = _sysParts.length > 0 ? _sysParts.join("\n") : "";
730
+ const isTitleGenOAI = _sysPrompt.includes('Generate a concise, sentence-case title');
731
+
732
+ // ⭐ 限制工具数量,防止 prompt 超出限制
733
+ const MAX_TOOLS_OAI = 8;
734
+ const ESSENTIAL_OAI = new Set(['Bash', 'Read', 'Write', 'Glob', 'Grep']);
735
+ if (isTitleGenOAI) {
736
+ effectiveTools = []; // 标题生成不需要工具
737
+ } else if (effectiveTools && effectiveTools.length > MAX_TOOLS_OAI) {
738
+ const essential = effectiveTools.filter(t => ESSENTIAL_OAI.has(t.function?.name));
739
+ const others = effectiveTools.filter(t => !ESSENTIAL_OAI.has(t.function?.name));
740
+ const available = MAX_TOOLS_OAI - essential.length;
741
+ effectiveTools = [...essential, ...others.slice(0, Math.max(0, available))];
742
+ }
743
+ const toolsPrompt = (effectiveTools && effectiveTools.length > 0 && toolChoice !== "none")
744
+ ? buildToolsPrompt(effectiveTools) : "";
745
+
746
+ let toolResultPathOAI = false;
747
+
748
+ if (hasToolResults && hasToolCalls) {
749
+ toolResultPathOAI = true;
750
+ // 工具结果回传轮 — 单段系统通知格式
751
+ const lastUserOAI = messages.filter(m => m.role === "user").pop();
752
+ const lastUserTextOAI = extractContent(lastUserOAI || {});
753
+ const cjkOAI = /[一-鿿㐀-䶿]/.test(lastUserTextOAI);
754
+
755
+ // 收集函数调用和结果
756
+ const calledOAI = [], resultsOAI = [];
757
+ for (const m of messages) {
758
+ if (m.role === "assistant" && m.tool_calls) {
759
+ for (const tc of m.tool_calls) calledOAI.push(tc.function.name + "(" + tc.function.arguments + ")");
760
+ }
761
+ if (m.role === "tool") {
762
+ resultsOAI.push(extractContent(m).slice(0, 3000));
763
+ }
764
+ }
765
+ // 找到用户原始提问
766
+ const userQsOAI = [];
767
+ for (const m of messages) {
768
+ if (m.role !== "user") continue;
769
+ if (Array.isArray(m.content) && m.content.some(c => c.type === "tool_result")) continue;
770
+ const q = extractContent(m);
771
+ if (q && !q.startsWith("<session") && !q.startsWith("<system-reminder")) userQsOAI.push(q);
772
+ }
773
+ const origQ = userQsOAI.length > 0 ? userQsOAI[userQsOAI.length - 1] : (lastUserTextOAI || "");
774
+
775
+ if (cjkOAI) {
776
+ question = "⚠️ 系统通知:你刚才调用了以下函数,返回结果如下:\n\n";
777
+ for (let i = 0; i < calledOAI.length; i++) {
778
+ question += "函数调用: " + calledOAI[i] + "\n返回结果:\n\"\"\"\n" + (resultsOAI[i] || "") + "\n\"\"\"\n\n";
779
+ }
780
+ question += "用户原始提问: \"" + origQ + "\"\n\n请用简体中文直接回答用户的问题。说出答案即可。不要说\"你分享了\"或\"看起来像是\"。上面用 \"\"\" 包裹的内容是你自己调用函数得到的返回结果。";
781
+ } else {
782
+ question = "⚠️ SYSTEM: You just called these functions and received these outputs:\n\n";
783
+ for (let i = 0; i < calledOAI.length; i++) {
784
+ question += "Function: " + calledOAI[i] + "\nOutput:\n\"\"\"\n" + (resultsOAI[i] || "") + "\n\"\"\"\n\n";
785
+ }
786
+ question += "User's original question: \"" + origQ + "\"\n\nAnswer DIRECTLY based on the outputs. Do NOT say \"you shared\" or \"it looks like\". The \"\"\" content is YOUR function output, NOT user input.";
787
+ }
788
+
789
+ // 工具结果回传轮: 不携带完整 sysPrompt, 仅 5 个核心工具
790
+ // ⭐ 用软版提示 — 允许模型直接用文字作答, 避免被强制再发 function_call 而沉默
791
+ const minimalOAI = buildToolsPromptSoft(
792
+ (effectiveTools || []).filter(t => ESSENTIAL_OAI.has(t.function?.name)).slice(0, 5)
793
+ );
794
+ question = minimalOAI + "\n\n---\n" + question;
795
+ } else {
796
+ // 普通问答 / 首轮 tool calling
797
+ let sysPrompt = "";
798
+ const sysParts = messages.filter(m => m.role === "system").map(m => extractContent(m));
799
+ if (sysParts.length > 0) sysPrompt = sysParts.join("\n");
800
+
801
+ const nonSys = messages.filter(m => m.role !== "system" && m.role !== "tool");
802
+ const userMsgs = nonSys.filter(m => m.role === "user");
803
+ if (userMsgs.length === 0) {
804
+ return json(res, 400, { error: { message: "No user message", type: "invalid_request_error" } });
805
+ }
806
+
807
+ // ⭐ 跳过系统注入消息 (<session>, <system-reminder>)
808
+ const realUserMsgs = userMsgs.filter(m => {
809
+ const c = extractContent(m);
810
+ return !c.startsWith('<session') && !c.startsWith('<system-reminder') && c.length > 10;
811
+ });
812
+ const lastUserMsg = realUserMsgs.length > 0
813
+ ? extractContent(realUserMsgs[realUserMsgs.length - 1])
814
+ : extractContent(userMsgs[userMsgs.length - 1]);
815
+
816
+ // ⭐ 语言检测
817
+ const hasCJKOAI = /[一-鿿㐀-䶿]/.test(lastUserMsg);
818
+ const langHintOAI = hasCJKOAI ? "\n## Language\nRespond in the same language as the user's message. The user is writing in Chinese — respond in Chinese (简体中文).\n" : "";
819
+
820
+ // IMA question 字段限制 10240 字符
821
+ const MAX_QUESTION = 10000;
822
+
823
+ if (nonSys.length > 1 && realUserMsgs.length >= 1) {
824
+ const realMsgs = nonSys.filter(m => {
825
+ const c = extractContent(m);
826
+ return c.length > 10 && !c.startsWith('<session') && !c.startsWith('<system-reminder');
827
+ });
828
+ if (realMsgs.length > 1) {
829
+ // ⭐ 修复: 扩展到 20 条,按字符数动态裁剪
830
+ const MAX_HISTORY_CHARS = 6000;
831
+ const recentMsgs = realMsgs
832
+ .filter(m => m.role === "user" || m.role === "assistant")
833
+ .slice(-20);
834
+ let historyParts = [];
835
+ let historyLen = 0;
836
+ for (let i = recentMsgs.length - 1; i >= 0; i--) {
837
+ const m = recentMsgs[i];
838
+ const line = `${m.role === "user" ? "User" : "Assistant"}: ${extractContent(m)}`;
839
+ if (historyLen + line.length > MAX_HISTORY_CHARS && historyParts.length > 0) break;
840
+ historyParts.unshift(line);
841
+ historyLen += line.length + 1;
842
+ }
843
+ const history = historyParts.join("\n");
844
+ question = (sysPrompt ? sysPrompt + "\n\n" : "") + (toolsPrompt ? toolsPrompt + "\n\n---\n" : "") + history;
845
+ } else {
846
+ question = `${sysPrompt ? "(Background)\n" + sysPrompt + "\n\n" : ""}${toolsPrompt}\n\n---\nUser message (respond to this):\n${lastUserMsg}`;
847
+ }
848
+ } else {
849
+ // ⭐ 智能压缩 system prompt (保留 toolsPrompt 完整)
850
+ let context = sysPrompt;
851
+ const overhead = toolsPrompt.length + lastUserMsg.length + 200;
852
+ const remaining = MAX_QUESTION - overhead;
853
+
854
+ if (context && context.length > remaining && remaining > 0) {
855
+ // ⭐ 修复: 保留头尾,中间裁剪(保留核心规则 + 最新文件信息)
856
+ const layoutMatch = context.match(/<project_layout>([\s\S]*?)<\/project_layout>/);
857
+ const layoutSummary = layoutMatch
858
+ ? layoutMatch[1].trim().split("\n").slice(0, 30).join("\n")
859
+ : "";
860
+ const headLen = Math.min(800, Math.floor(remaining * 0.6));
861
+ const tailLen = Math.min(400, remaining - headLen);
862
+ const head = context.slice(0, headLen);
863
+ const tail = context.length > headLen + tailLen ? context.slice(-tailLen) : "";
864
+ const layoutPart = layoutSummary ? "\n\nDirectory (summary):\n" + layoutSummary.slice(0, Math.min(300, remaining - headLen - tailLen - 50)) : "";
865
+ context = tail ? head + "\n...[truncated]..." + layoutPart + "\n" + tail : head + layoutPart;
866
+ context = context.slice(0, remaining);
867
+ }
868
+
869
+ question = `${context ? "(Background)\n" + context + "\n\n" : ""}${toolsPrompt}\n\n---\nUser message (respond to this):\n${lastUserMsg}`;
870
+ }
871
+
872
+ // ⭐ 注入语言提示 & 截断 (工具结果回传轮跳过)
873
+ if (!toolResultPathOAI) {
874
+ question += langHintOAI;
875
+
876
+ // 最终截断 — 始终保留 toolsPrompt,否则模型看不到 function 定义
877
+ if (question.length > MAX_QUESTION) {
878
+ const minTemplate = "\n\n---\nUser message (respond to this):\n";
879
+ const compact = toolsPrompt + minTemplate + lastUserMsg + langHintOAI;
880
+ if (compact.length > MAX_QUESTION) {
881
+ const availForUser = Math.max(500, MAX_QUESTION - toolsPrompt.length - minTemplate.length - langHintOAI.length);
882
+ question = toolsPrompt + minTemplate + lastUserMsg.slice(0, Math.max(0, availForUser)) + langHintOAI;
883
+ } else {
884
+ question = compact;
885
+ }
886
+ }
887
+ }
888
+ }
889
+
890
+ if (!question) {
891
+ return json(res, 400, { error: { message: "Empty question", type: "invalid_request_error" } });
892
+ }
893
+
894
+
895
+ // 会话 — 复用 IMA session 保持对话记忆
896
+ // ⭐ 修复: 用系统 prompt 作为稳定锚点(同 Anthropic 路径保持一致)
897
+ let oaiConvId = req.headers["x-conversation-id"] || req.headers["x-session-id"] || "";
898
+ if (!oaiConvId && messages.length > 0) {
899
+ const sysMsg = messages.find(m => m.role === "system");
900
+ const anchor = sysMsg
901
+ ? extractContent(sysMsg).slice(0, 200)
902
+ : extractContent(messages[0]).slice(0, 200);
903
+ oaiConvId = "conv-" + crypto.createHash("md5").update(anchor).digest("hex").slice(0, 12);
904
+ }
905
+ let sessionId;
906
+ try {
907
+ sessionId = await ensureSession(oaiConvId, question.slice(0, 100));
908
+ } catch (e) {
909
+ return json(res, 502, { error: { message: "Session init failed: " + e.message, type: "api_error" } });
910
+ }
911
+
912
+ // --- 非流式 ---
913
+ if (!stream) {
914
+ try {
915
+ const events = await imaQaStreamWithRetry(oaiConvId, question, model.type, model.id);
916
+ const text = await collectResponseText(events);
917
+ const parsed = parseFunctionCalls(text);
918
+
919
+ const choice = { index: 0, message: {}, finish_reason: "stop" };
920
+
921
+ if (parsed.found && parsed.calls.length > 0) {
922
+ choice.message = {
923
+ role: "assistant",
924
+ content: parsed.text || null,
925
+ tool_calls: parsed.calls,
926
+ };
927
+ choice.finish_reason = "tool_calls";
928
+ } else {
929
+ // ⭐ 兜底: 空文本时给出占位, 避免客户端收到完全空的回复
930
+ choice.message = { role: "assistant", content: text || "(本轮没有生成内容,请重试或换一种问法。)" };
931
+ }
932
+
933
+ return json(res, 200, {
934
+ id: "chatcmpl-" + crypto.randomUUID().slice(0, 8),
935
+ object: "chat.completion",
936
+ created: Math.floor(Date.now() / 1000),
937
+ model: modelKey,
938
+ choices: [choice],
939
+ usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
940
+ });
941
+ } catch (e) {
942
+ return json(res, 502, { error: { message: "IMA error: " + e.message, type: "api_error" } });
943
+ }
944
+ }
945
+
946
+ // --- 流式 ---
947
+ cors(res);
948
+ res.writeHead(200, {
949
+ "Content-Type": "text/event-stream",
950
+ "Cache-Control": "no-cache",
951
+ Connection: "keep-alive",
952
+ "x-request-id": "chatcmpl-" + crypto.randomUUID().slice(0, 8),
953
+ });
954
+
955
+ const chatId = "chatcmpl-" + crypto.randomUUID().slice(0, 8);
956
+ const created = Math.floor(Date.now() / 1000);
957
+ let resClosed = false;
958
+ let sentText = false; // ⭐ 是否已向客户端发送过任何文本/工具内容 (兜底判断)
959
+ res.on('close', () => { resClosed = true; });
960
+
961
+ function emit(delta, finishReason, toolCalls) {
962
+ if (resClosed) return;
963
+ try {
964
+ const d = toolCalls && toolCalls.length > 0
965
+ ? { role: "assistant", tool_calls: toolCalls }
966
+ : { role: "assistant", content: delta };
967
+ if ((delta && delta.length > 0) || (toolCalls && toolCalls.length > 0)) sentText = true;
968
+ res.write("data: " + JSON.stringify({
969
+ id: chatId, object: "chat.completion.chunk", created, model: modelKey,
970
+ choices: [{ index: 0, delta: d, finish_reason: finishReason }],
971
+ }) + "\n\n");
972
+ } catch (e) { resClosed = true; }
973
+ }
974
+
975
+ try {
976
+ const events = await imaQaStreamWithRetry(oaiConvId, question, model.type, model.id);
977
+ const filter = new StreamFilter();
978
+ let done = false;
979
+
980
+ let sawEvent = false;
981
+ for await (const evt of events) {
982
+ if (resClosed) break;
983
+ if (CONTROL_EVENTS.has(evt.event)) {
984
+ if (evt.event === "COMPLETED" || evt.event === "CLOSE") done = true;
985
+ break;
986
+ }
987
+ sawEvent = true;
988
+ const et = eventTexts(evt);
989
+ // Emit reasoning/thinking content (openai reasoning_content delta)
990
+ if (et.think) {
991
+ if (DEBUG_SSE) console.log("[SSE-THINK] " + JSON.stringify(et.think).slice(0, 200));
992
+ if (!resClosed) {
993
+ try {
994
+ sentText = true;
995
+ res.write("data: " + JSON.stringify({
996
+ id: chatId, object: "chat.completion.chunk", created, model: modelKey,
997
+ choices: [{ index: 0, delta: { role: "assistant", reasoning_content: et.think }, finish_reason: null }],
998
+ }) + "\n\n");
999
+ } catch (e) { resClosed = true; }
1000
+ }
1001
+ }
1002
+ if (et.text) {
1003
+ ensureBlock("text");
1004
+ const clean = filter.feed(et.text);
1005
+ if (clean) emit(clean, null, null);
1006
+ }
1007
+ }
1008
+ if (DEBUG_SSE && !sawEvent) console.error("[SSE-EMPTY] openai stream: no data events");
1009
+
1010
+ // 冲刷残留缓冲
1011
+ ensureBlock("text");
1012
+ const flushed = filter.flush();
1013
+ if (flushed && !resClosed) emit(flushed, null, null);
1014
+
1015
+ // 检测并发送函数调用
1016
+ if (!resClosed) {
1017
+ const calls = filter.parseCalls();
1018
+ // ⭐ 无法解析的 function_call 残留 — 作为文本输出, 避免静默丢失
1019
+ if (filter.leftover) emit(filter.leftover, null, null);
1020
+ if (calls.length > 0) {
1021
+ // ⭐ OpenAI streaming tool_calls: 逐个发送
1022
+ for (let i = 0; i < calls.length; i++) {
1023
+ const tc = calls[i];
1024
+ if (resClosed) break;
1025
+ try {
1026
+ sentText = true;
1027
+ res.write("data: " + JSON.stringify({
1028
+ id: chatId, object: "chat.completion.chunk", created, model: modelKey,
1029
+ choices: [{ index: 0, delta: { tool_calls: [{ index: i, id: tc.id, type: "function", function: { name: tc.function.name, arguments: tc.function.arguments } }] }, finish_reason: null }],
1030
+ }) + "\n\n");
1031
+ } catch (e) { resClosed = true; }
1032
+ }
1033
+ if (!resClosed) {
1034
+ res.write("data: " + JSON.stringify({
1035
+ id: chatId, object: "chat.completion.chunk", created, model: modelKey,
1036
+ choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }],
1037
+ }) + "\n\n");
1038
+ }
1039
+ } else {
1040
+ // ⭐ 兜底: 流正常结束但既无文本也无工具调用 (模型只回了被过滤的内容 /
1041
+ // 空响应 / 异常中断)。绝不让客户端收到完全空的回复 — 这是"无回复就结束"的根因。
1042
+ if (!sentText && !resClosed) {
1043
+ const fb = done
1044
+ ? "(本轮没有生成内容,请重试或换一种问法。)"
1045
+ : "(响应在完成前被中断,请重试。)";
1046
+ emit(fb, null, null);
1047
+ }
1048
+ // done 为 true 表示正常完成
1049
+ res.write("data: " + JSON.stringify({
1050
+ id: chatId, object: "chat.completion.chunk", created, model: modelKey,
1051
+ choices: [{ index: 0, delta: {}, finish_reason: done ? "stop" : "length" }],
1052
+ }) + "\n\n");
1053
+ }
1054
+ }
1055
+ } catch (e) {
1056
+ if (!resClosed) {
1057
+ try { res.write("data: " + JSON.stringify({
1058
+ id: chatId, object: "chat.completion.chunk", created, model: modelKey,
1059
+ choices: [{ index: 0, delta: {}, finish_reason: "error" }],
1060
+ }) + "\n\n"); } catch {}
1061
+ }
1062
+ console.error(`[STREAM-ERR] ${e.message}`);
1063
+ }
1064
+ if (!resClosed) {
1065
+ try { res.write("data: [DONE]\n\n"); res.end(); } catch {}
1066
+ }
1067
+ }
1068
+
1069
+ // ============================================================
1070
+ // 9. Anthropic /v1/messages
1071
+ // ============================================================
1072
+ async function anthropicMessages(req, res, body) {
1073
+ const modelKey = body.model || DEFAULT_MODEL;
1074
+ const model = resolveModel(modelKey);
1075
+ const stream = !!body.stream;
1076
+ const messages = body.messages || [];
1077
+
1078
+ // system prompt
1079
+ let sysPrompt = "";
1080
+ if (typeof body.system === "string") sysPrompt = body.system;
1081
+ else if (Array.isArray(body.system))
1082
+ sysPrompt = body.system.filter(s => s.type === "text").map(s => s.text).join("\n");
1083
+
1084
+ // tools → prompt injection
1085
+ // 如果 Claude Code 没发送 tools,注入默认工具集
1086
+ let tools = body.tools;
1087
+ if (!tools || tools.length === 0) {
1088
+ tools = [
1089
+ {name: "Bash", description: "Execute a bash command. Use for: reading files (cat/ls), system info (uname/df/free), git, npm, find, grep, etc.", input_schema: {type: "object", properties: {command: {type: "string", description: "The bash command to execute"}}, required: ["command"]}},
1090
+ {name: "Read", description: "Read contents of a file. Use for: inspecting file contents, reading configs, source code.", input_schema: {type: "object", properties: {file_path: {type: "string", description: "Absolute path to the file"}}, required: ["file_path"]}},
1091
+ {name: "Write", description: "Write content to a file. Use for: creating new files, overwriting existing files.", input_schema: {type: "object", properties: {file_path: {type: "string", description: "Absolute path"}, content: {type: "string", description: "Content to write"}}, required: ["file_path", "content"]}},
1092
+ {name: "Glob", description: "Find files matching a pattern. Use for: searching for files by name.", input_schema: {type: "object", properties: {pattern: {type: "string", description: "Glob pattern like **/*.js"}}, required: ["pattern"]}},
1093
+ {name: "Grep", description: "Search file contents for a pattern. Use for: finding code, searching logs.", input_schema: {type: "object", properties: {pattern: {type: "string", description: "Regex pattern to search for"}, path: {type: "string", description: "Directory or file to search in"}}, required: ["pattern"]}},
1094
+ ];
1095
+ }
1096
+
1097
+ // ⭐ 标题生成请求不需要 tools (Claude Code 首轮请求)
1098
+ const isTitleGen = sysPrompt.includes('Generate a concise, sentence-case title');
1099
+
1100
+ // ⭐ 限制工具数量,防止 prompt 超出 IMA 10240 字符限制
1101
+ const MAX_TOOLS = 8;
1102
+ const ESSENTIAL_TOOLS = new Set(['Bash', 'Read', 'Write', 'Glob', 'Grep']);
1103
+ let displayTools = tools;
1104
+ if (isTitleGen) {
1105
+ displayTools = []; // 标题生成不需要工具
1106
+ } else if (displayTools.length > MAX_TOOLS) {
1107
+ // 优先保留核心工具,再按原顺序补充其他工具
1108
+ const essential = displayTools.filter(t => ESSENTIAL_TOOLS.has(t.name));
1109
+ const others = displayTools.filter(t => !ESSENTIAL_TOOLS.has(t.name));
1110
+ const available = MAX_TOOLS - essential.length;
1111
+ displayTools = [...essential, ...others.slice(0, Math.max(0, available))];
1112
+ }
1113
+ // —— 过滤消息 ——
1114
+ // ⭐ 检测 Anthropic 格式的 tool_use / tool_result (多轮回传)
1115
+ function msgHasType(msg, type) {
1116
+ if (Array.isArray(msg.content)) return msg.content.some(c => c.type === type);
1117
+ return false;
1118
+ }
1119
+ const hasToolUses = messages.some(m => m.role === "assistant" && msgHasType(m, "tool_use"));
1120
+ const hasToolResults = messages.some(m => m.role === "user" && msgHasType(m, "tool_result"));
1121
+
1122
+ // ⭐ 清理用户消息中的系统注入元数据
1123
+ function stripMetadata(text) {
1124
+ return text
1125
+ // 删除元数据块 (含内容一起删)
1126
+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '')
1127
+ .replace(/<local-command-caveat>[\s\S]*?<\/local-command-caveat>/g, '')
1128
+ .replace(/<local-command-stdout>[\s\S]*?<\/local-command-stdout>/g, '')
1129
+ // 删除单行命令元数据
1130
+ .replace(/<command-name>[^<]*<\/command-name>/g, '')
1131
+ .replace(/<command-message>[^<]*<\/command-message>/g, '')
1132
+ .replace(/<command-args>[^<]*<\/command-args>/g, '')
1133
+ // ⭐ <session> 只删标签、保留内容 (用户消息在 session 内)
1134
+ .replace(/<\/?session>/g, '')
1135
+ .trim();
1136
+ }
1137
+
1138
+ const nonSys = messages.filter(m => m.role !== "system");
1139
+ const userMsgs = nonSys.filter(m => m.role === "user");
1140
+ if (userMsgs.length === 0)
1141
+ return json(res, 400, { type: "error", error: { type: "invalid_request_error", message: "No user message" } });
1142
+
1143
+ // ⭐ 提取最后一条用户消息的实质内容
1144
+ const realUserMsgs = userMsgs.filter(m => {
1145
+ const c = stripMetadata(extractContent(m));
1146
+ return c.length > 5;
1147
+ });
1148
+ const lastUserMsg = realUserMsgs.length > 0
1149
+ ? stripMetadata(extractContent(realUserMsgs[realUserMsgs.length - 1]))
1150
+ : stripMetadata(extractContent(userMsgs[userMsgs.length - 1]));
1151
+
1152
+ if (!lastUserMsg) {
1153
+ }
1154
+
1155
+ // ⭐ 语言检测: 用户用中文则要求中文回复
1156
+ const hasCJK = /[一-鿿㐀-䶿]/.test(lastUserMsg);
1157
+ const langHint = hasCJK ? "\n## Language\nRespond in the same language as the user's message. The user is writing in Chinese — respond in Chinese (简体中文).\n" : "";
1158
+
1159
+ // 工具通过 toolsPrompt 单独注入 (见下方 question 构建)
1160
+ const toolsPrompt = (displayTools && displayTools.length > 0) ? buildToolsPrompt(
1161
+ displayTools.map(t => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.input_schema || {} } }))
1162
+ ) : "";
1163
+
1164
+ let question;
1165
+ let toolResultPath = false; // 工具结果回传轮标记 (跳过 langHint 和截断)
1166
+ const MAX_QUESTION = 10000;
1167
+
1168
+ if (hasToolResults && hasToolUses) {
1169
+ toolResultPath = true; // 标记: 后续跳过 langHint 注入和通用截断
1170
+ // ⭐ 工具结果回传轮 — 单段系统通知格式,让模型把结果当作系统提供的信息
1171
+ const isCJK = hasCJK;
1172
+
1173
+ // 收集工具调用名+结果
1174
+ const calledFuncs = [];
1175
+ const results = [];
1176
+ for (const m of messages) {
1177
+ if (m.role === "assistant" && Array.isArray(m.content)) {
1178
+ for (const c of m.content) {
1179
+ if (c.type === "tool_use") calledFuncs.push(c.name + "(" + JSON.stringify(c.input) + ")");
1180
+ }
1181
+ }
1182
+ if (m.role === "user" && Array.isArray(m.content)) {
1183
+ for (const c of m.content) {
1184
+ if (c.type === "tool_result") {
1185
+ const tc = typeof c.content === "string" ? c.content
1186
+ : Array.isArray(c.content) ? c.content.map(cc => cc.text || "").join("") : "";
1187
+ results.push(tc);
1188
+ }
1189
+ }
1190
+ }
1191
+ }
1192
+
1193
+ // 找到用户的原始提问 (第一条非 tool_result 的用户消息)
1194
+ const userQs = [];
1195
+ for (const m of messages) {
1196
+ if (m.role !== "user") continue;
1197
+ if (Array.isArray(m.content) && m.content.some(c => c.type === "tool_result")) continue;
1198
+ const q = stripMetadata(extractContent(m));
1199
+ if (q) userQs.push(q);
1200
+ }
1201
+ const originalQuestion = userQs.length > 0 ? userQs[userQs.length - 1] : (lastUserMsg || "");
1202
+
1203
+ // 构建通知: 系统消息 + 函数���用 + 结果
1204
+ if (isCJK) {
1205
+ question = "⚠️ 系统通知:你刚才调用了以下函数,返回结果如下:\n\n";
1206
+ for (let i = 0; i < calledFuncs.length; i++) {
1207
+ question += "函数调用: " + calledFuncs[i] + "\n";
1208
+ question += "返回结果:\n\"\"\"\n" + (results[i] || "") + "\n\"\"\"\n\n";
1209
+ }
1210
+ question += "用户原始提问: \"" + originalQuestion + "\"\n\n";
1211
+ question += "请用简体中文直接回答用户的问题。说出答案即可。不要说\"你分享了\"或\"看起来像是\"或\"I see you've shared\"。上面用 \"\"\" 包裹的内容是你自己调用函数得到的返回结果,不是用户发给你的。";
1212
+ } else {
1213
+ question = "⚠️ SYSTEM: You just called these functions and received these outputs:\n\n";
1214
+ for (let i = 0; i < calledFuncs.length; i++) {
1215
+ question += "Function: " + calledFuncs[i] + "\n";
1216
+ question += "Output:\n\"\"\"\n" + (results[i] || "") + "\n\"\"\"\n\n";
1217
+ }
1218
+ question += "User's original question: \"" + originalQuestion + "\"\n\n";
1219
+ question += "Answer the user's question DIRECTLY based on the outputs above. Do NOT say \"you shared\" or \"I see you've shared\" or \"it looks like\". The content inside \"\"\" blocks is YOUR function output, NOT content the user sent you.";
1220
+ }
1221
+
1222
+ // ⭐ 工具结果回传轮: 不携带完整 sysPrompt 和大量 tools (⚠️ 通知已提供足够上下文)
1223
+ // 仅保留 5 个核心工具, 确保总长度 < 10000 不会被后面的通用截断逻辑破坏
1224
+ // ⭐ 用软版提示 — 允许模型基于结果直接用文字回答, 而非被强制再发 function_call
1225
+ const minimalToolsPrompt = buildToolsPromptSoft(
1226
+ displayTools.filter(t => ESSENTIAL_TOOLS.has(t.name)).slice(0, 5)
1227
+ .map(t => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.input_schema || {} } }))
1228
+ );
1229
+ question = minimalToolsPrompt + "\n\n---\n" + question;
1230
+ // 跳过后续的 langHint 注入和通用截断 — 此路径的 question 已包含语言指令且 < 10000
1231
+ } else if (nonSys.length > 1 && realUserMsgs.length >= 1) {
1232
+ // 取真正的用户消息(过滤掉系统注入的元数据)
1233
+ const realMsgs = nonSys
1234
+ .filter(m => {
1235
+ const c = stripMetadata(extractContent(m));
1236
+ return c.length > 5;
1237
+ });
1238
+ if (realMsgs.length > 1) {
1239
+ // ⭐ 修复: 从 6 条扩展到 20 条,并按总字符限制动态裁剪(保留最新的消息)
1240
+ const MAX_HISTORY_CHARS = 6000; // 留出空间给 sysPrompt + toolsPrompt
1241
+ const recentMsgs = realMsgs.slice(-20);
1242
+ let historyParts = [];
1243
+ let historyLen = 0;
1244
+ for (let i = recentMsgs.length - 1; i >= 0; i--) {
1245
+ const m = recentMsgs[i];
1246
+ const line = (m.role === "user" ? "User" : "Assistant") + ": " + stripMetadata(extractContent(m));
1247
+ if (historyLen + line.length > MAX_HISTORY_CHARS && historyParts.length > 0) break;
1248
+ historyParts.unshift(line);
1249
+ historyLen += line.length + 1;
1250
+ }
1251
+ question = historyParts.join("\n");
1252
+ question = (sysPrompt ? sysPrompt + "\n\n" : "") + (toolsPrompt ? toolsPrompt + "\n\n---\n" : "") + question;
1253
+ } else {
1254
+ // 只有一条真正消息,走单轮路径
1255
+ question = (sysPrompt ? "(Background)\n" + sysPrompt + "\n\n" : "") + toolsPrompt + "\n\n---\nUser message (respond to this):\n" + lastUserMsg;
1256
+ }
1257
+ } else {
1258
+ let context = sysPrompt;
1259
+ const overhead = toolsPrompt.length + lastUserMsg.length + 200;
1260
+ const remaining = MAX_QUESTION - overhead;
1261
+ if (context && context.length > remaining && remaining > 0) {
1262
+ // ⭐ 修复: 保留头部(核心规则)+ 尾部(最新文件列表),中间裁剪
1263
+ // 而非旧逻辑的"只保留前500字+目录",那样会丢失大量重要指令
1264
+ const layoutMatch = context.match(/<project_layout>([\s\S]*?)<\/project_layout>/);
1265
+ const layoutSummary = layoutMatch ? layoutMatch[1].trim().split("\n").slice(0, 30).join("\n") : "";
1266
+ const headLen = Math.min(800, Math.floor(remaining * 0.6));
1267
+ const tailLen = Math.min(400, remaining - headLen);
1268
+ const head = context.slice(0, headLen);
1269
+ const tail = context.length > headLen + tailLen ? context.slice(-tailLen) : "";
1270
+ const layoutPart = layoutSummary ? "\n\nDirectory (summary):\n" + layoutSummary.slice(0, Math.min(300, remaining - headLen - tailLen - 50)) : "";
1271
+ context = tail ? head + "\n...[truncated]..." + layoutPart + "\n" + tail : head + layoutPart;
1272
+ context = context.slice(0, remaining);
1273
+ }
1274
+ question = (context ? "(Background)\n" + context + "\n\n" : "") + toolsPrompt + "\n\n---\nUser message (respond to this):\n" + lastUserMsg;
1275
+ }
1276
+
1277
+ // ⭐ 注入语言提示 & 截断 (工具结果回传轮跳过 — 已自带语言指令且 < 10000)
1278
+ if (!toolResultPath) {
1279
+ question += langHint;
1280
+
1281
+ if (question.length > MAX_QUESTION) {
1282
+ const minTemplate = "\n\n---\nUser message (respond to this):\n";
1283
+ const compact = toolsPrompt + minTemplate + lastUserMsg + langHint;
1284
+ if (compact.length > MAX_QUESTION) {
1285
+ const availForUser = Math.max(500, MAX_QUESTION - toolsPrompt.length - minTemplate.length - langHint.length);
1286
+ question = toolsPrompt + minTemplate + lastUserMsg.slice(0, Math.max(0, availForUser)) + langHint;
1287
+ } else {
1288
+ question = compact;
1289
+ }
1290
+ }
1291
+ }
1292
+
1293
+
1294
+ // 会话 — ⭐ 关键: 必须复用 IMA session 才能保持对话记忆
1295
+ const convId = req.headers["x-conversation-id"] || req.headers["x-session-id"] || "";
1296
+ // ⭐ 修复: 用系统 prompt + 第一条用户消息的 hash 作为稳定会话锚点
1297
+ // Claude Code 不发 x-conversation-id, 但同一对话的 system prompt 内容固定
1298
+ let effectiveConvId = convId;
1299
+ if (!effectiveConvId && messages.length > 0) {
1300
+ // 优先用 system prompt (Claude Code 在 system 里放项目路径等固定信息)
1301
+ const sysMsg = messages.find(m => m.role === "system");
1302
+ const anchor = sysMsg
1303
+ ? extractContent(sysMsg).slice(0, 200) // system prompt 前200字,通常含项目路径
1304
+ : extractContent(messages[0]).slice(0, 200); // fallback: 第一条消息
1305
+ effectiveConvId = "conv-" + crypto.createHash("md5").update(anchor).digest("hex").slice(0, 12);
1306
+ }
1307
+ let sessionId;
1308
+ const isNewSession = !getCachedSession(effectiveConvId);
1309
+ try { sessionId = await ensureSession(effectiveConvId, question.slice(0, 100)); }
1310
+ catch (e) {
1311
+ console.error(`[ANTHROPIC-SESSION] init failed: ${e.message}`);
1312
+ return json(res, 502, { type: "error", error: { type: "api_error", message: "Session init failed: " + e.message } });
1313
+ }
1314
+
1315
+ // --- 非流式 ---
1316
+ if (!stream) {
1317
+ try {
1318
+ const events = await imaQaStreamWithRetry(effectiveConvId, question, model.type, model.id);
1319
+ const text = await collectResponseText(events);
1320
+ const parsed = parseFunctionCalls(text);
1321
+
1322
+ if (parsed.found && parsed.calls.length > 0) {
1323
+ const content = [];
1324
+ if (parsed.text) content.push({ type: "text", text: parsed.text });
1325
+ for (const c of parsed.calls) {
1326
+ content.push({
1327
+ type: "tool_use", id: c.id,
1328
+ name: c.function.name,
1329
+ input: JSON.parse(c.function.arguments || "{}"),
1330
+ });
1331
+ }
1332
+ return json(res, 200, {
1333
+ id: "msg_" + crypto.randomUUID().slice(0, 8),
1334
+ type: "message", role: "assistant", model: modelKey,
1335
+ content, stop_reason: "tool_use", stop_sequence: null,
1336
+ usage: { input_tokens: 0, output_tokens: 0 },
1337
+ });
1338
+ }
1339
+
1340
+ return json(res, 200, {
1341
+ id: "msg_" + crypto.randomUUID().slice(0, 8),
1342
+ type: "message", role: "assistant", model: modelKey,
1343
+ // ⭐ 兜底: 空文本时给出占位, 避免客户端收到空 content
1344
+ content: [{ type: "text", text: text || "(本轮没有生成内容,请重试或换一种问法。)" }],
1345
+ stop_reason: "end_turn", stop_sequence: null,
1346
+ usage: { input_tokens: 0, output_tokens: 0 },
1347
+ });
1348
+ } catch (e) {
1349
+ console.error(`[ANTHROPIC-NONSTREAM-ERR] ${e.message}`);
1350
+ return json(res, 502, { type: "error", error: { type: "api_error", message: "IMA error: " + e.message } });
1351
+ }
1352
+ }
1353
+
1354
+ // --- 流式 ---
1355
+ cors(res);
1356
+ res.writeHead(200, {
1357
+ "Content-Type": "text/event-stream",
1358
+ "Cache-Control": "no-cache",
1359
+ Connection: "keep-alive",
1360
+ });
1361
+
1362
+ const msgId = "msg_" + crypto.randomUUID().slice(0, 8);
1363
+ let resClosed = false;
1364
+ res.on('close', () => { resClosed = true; });
1365
+
1366
+ const em = (e, d) => {
1367
+ if (resClosed) return;
1368
+ try {
1369
+ if (e) res.write(`event: ${e}\n`);
1370
+ res.write(`data: ${JSON.stringify(d)}\n\n`);
1371
+ } catch (_) { resClosed = true; }
1372
+ };
1373
+
1374
+ em("message_start", {
1375
+ type: "message_start",
1376
+ message: { id: msgId, type: "message", role: "assistant", model: modelKey, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } },
1377
+ });
1378
+ // === Dynamic content block management ===
1379
+ let blockIdx = -1;
1380
+ let blockType = null; // null | "thinking" | "text"
1381
+
1382
+ function ensureBlock(type) {
1383
+ if (blockType === type) return;
1384
+ if (blockType !== null) {
1385
+ if (!resClosed) em("content_block_stop", { type: "content_block_stop", index: blockIdx });
1386
+ }
1387
+ blockIdx++;
1388
+ blockType = type;
1389
+ const cb = { type: "content_block_start", index: blockIdx, content_block: { type: type } };
1390
+ if (type === "thinking") cb.content_block.thinking = "";
1391
+ if (type === "text") cb.content_block.text = "";
1392
+ if (!resClosed) em("content_block_start", cb);
1393
+ }
1394
+
1395
+ function closeBlock() {
1396
+ if (blockType === null || resClosed) return;
1397
+ em("content_block_stop", { type: "content_block_stop", index: blockIdx });
1398
+ blockType = null;
1399
+ }
1400
+
1401
+ let stopReason = "end_turn";
1402
+ let done = false;
1403
+ let sentText = false; // ⭐ 是否已发送过任何文本 delta (兜底判断)
1404
+ const filter = new StreamFilter();
1405
+ let calls = []; // 在 try 外声明,供后续 tool_use 发送使用
1406
+ try {
1407
+ const events = await imaQaStreamWithRetry(effectiveConvId, question, model.type, model.id);
1408
+
1409
+ for await (const evt of events) {
1410
+ if (resClosed) break;
1411
+ if (CONTROL_EVENTS.has(evt.event)) {
1412
+ if (evt.event === "COMPLETED" || evt.event === "CLOSE") done = true;
1413
+ break;
1414
+ }
1415
+ const et = eventTexts(evt);
1416
+ // Emit thinking content as separate content block
1417
+ if (et.think) {
1418
+ if (DEBUG_SSE) console.log("[SSE-THINK] " + JSON.stringify(et.think).slice(0, 200));
1419
+ if (!resClosed) {
1420
+ try {
1421
+ ensureBlock("thinking");
1422
+ sentText = true;
1423
+ em("content_block_delta", { type: "content_block_delta", index: blockIdx, delta: { type: "thinking_delta", thinking: et.think } });
1424
+ } catch (e) { resClosed = true; }
1425
+ }
1426
+ }
1427
+ if (et.text) {
1428
+ ensureBlock("text");
1429
+ const clean = filter.feed(et.text);
1430
+ if (clean) { em("content_block_delta", { type: "content_block_delta", index: blockIdx, delta: { type: "text_delta", text: clean } }); sentText = true; }
1431
+ }
1432
+ }
1433
+
1434
+ // 冲刷残留缓冲
1435
+ ensureBlock("text");
1436
+ const flushed = filter.flush();
1437
+ if (flushed && !resClosed) { em("content_block_delta", { type: "content_block_delta", index: blockIdx, delta: { type: "text_delta", text: flushed } }); sentText = true; }
1438
+
1439
+ calls = filter.parseCalls();
1440
+ // ⭐ 无法解析的 function_call 残留 — 作为文本输出, 避免静默丢失
1441
+ if (filter.leftover && !resClosed) { em("content_block_delta", { type: "content_block_delta", index: blockIdx, delta: { type: "text_delta", text: filter.leftover } }); sentText = true; }
1442
+
1443
+ // ⭐ 兜底: 流结束但既无文本也无工具调用 — 绝不让客户端收到完全空的回复。
1444
+ // 这是 Claude Code "执行命令后无任何回复就结束" 的最终防线。
1445
+ if (!sentText && calls.length === 0 && !resClosed) {
1446
+ const fb = done
1447
+ ? "(本轮没有生成内容,请重试或换一种问法。)"
1448
+ : "(响应在完成前被中断,请重试。)";
1449
+ ensureBlock("text");
1450
+ em("content_block_delta", { type: "content_block_delta", index: blockIdx, delta: { type: "text_delta", text: fb } });
1451
+ sentText = true;
1452
+ }
1453
+ } catch (e) {
1454
+ console.error(`[ANTHROPIC-STREAM-ERR] ${e.message}`);
1455
+ // ⭐ 异常路径同样兜底, 保证至少有一段文本
1456
+ if (!sentText && !resClosed) {
1457
+ try { em("content_block_delta", { type: "content_block_delta", index: blockIdx, delta: { type: "text_delta", text: "(响应处理出错,请重试。)" } }); sentText = true; } catch {}
1458
+ }
1459
+ }
1460
+
1461
+ // 结束文本块 (仅在未截停时)
1462
+ if (!resClosed) closeBlock();
1463
+
1464
+ // ⭐ 发送函数调用 — 使用上面已解析的 calls (避免重复解析)
1465
+ if (!resClosed && calls.length > 0) {
1466
+ stopReason = "tool_use";
1467
+ for (let i = 0; i < calls.length; i++) {
1468
+ const c = calls[i];
1469
+ const idx = blockIdx + 1 + i;
1470
+ if (resClosed) break;
1471
+ em("content_block_start", { type: "content_block_start", index: idx, content_block: { type: "tool_use", id: c.id, name: c.function.name, input: {} } });
1472
+ em("content_block_delta", { type: "content_block_delta", index: idx, delta: { type: "input_json_delta", partial_json: c.function.arguments } });
1473
+ em("content_block_stop", { type: "content_block_stop", index: idx });
1474
+ }
1475
+ }
1476
+
1477
+ if (!resClosed) {
1478
+ em("message_delta", { type: "message_delta", delta: { stop_reason: stopReason, stop_sequence: null }, usage: { output_tokens: 0 } });
1479
+ em("message_stop", { type: "message_stop" });
1480
+ try { res.end(); } catch {}
1481
+ }
1482
+ }
1483
+
1484
+ // ============================================================
1485
+ // 10. 路由
1486
+ // ============================================================
1487
+ async function router(req, res) {
1488
+ cors(res);
1489
+ if (req.method === "OPTIONS") { res.writeHead(204); return res.end(); }
1490
+
1491
+ const url = req.url;
1492
+ const urlPath = url.split("?")[0];
1493
+
1494
+ // Log every request (skip health checks)
1495
+ if (urlPath !== "/health") {
1496
+ console.log("[REQ] " + req.method + " " + urlPath);
1497
+ }
1498
+
1499
+ if (urlPath === "/health") return json(res, 200, { status: "ok" });
1500
+ if (urlPath === "/") return json(res, 200, {
1501
+ service: "ima2api",
1502
+ version: "3.0.0",
1503
+ endpoints: {
1504
+ openai: ["POST /v1/chat/completions (tools / function calling)", "GET /v1/models"],
1505
+ anthropic: ["POST /v1/messages (tools / tool_use)"],
1506
+ },
1507
+ models: Object.keys(MODELS),
1508
+ auth: "Bearer <api_key> or x-api-key header",
1509
+ });
1510
+
1511
+ if (!checkAuth(req)) {
1512
+ return json(res, 401, { error: { type: "authentication_error", message: "Invalid API key" } });
1513
+ }
1514
+
1515
+ let body = {};
1516
+ if (req.method === "POST") {
1517
+ try {
1518
+ const raw = await new Promise((resolve, reject) => {
1519
+ const chunks = [];
1520
+ req.on("data", c => chunks.push(c));
1521
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
1522
+ req.on("error", reject);
1523
+ });
1524
+ body = raw ? JSON.parse(raw) : {};
1525
+
1526
+ // body 已解析
1527
+ } catch (e) {
1528
+ return json(res, 400, { error: { type: "invalid_request_error", message: "Invalid JSON body" } });
1529
+ }
1530
+ }
1531
+
1532
+ if (req.method === "GET" && urlPath === "/v1/models") {
1533
+ const modelList = Object.entries(MODELS).map(([id, info]) => ({
1534
+ id, object: "model", created: 1700000000, owned_by: "ima",
1535
+ type: "model", display_name: info.name,
1536
+ created_at: "2024-01-01T00:00:00Z",
1537
+ }));
1538
+ const ids = modelList.map(m => m.id);
1539
+ return json(res, 200, {
1540
+ object: "list",
1541
+ data: modelList,
1542
+ has_more: false,
1543
+ first_id: ids[0] || null,
1544
+ last_id: ids[ids.length - 1] || null,
1545
+ });
1546
+ }
1547
+
1548
+ // Anthropic SDK: GET /v1/models/{model_id}
1549
+ if (req.method === "GET" && urlPath.startsWith("/v1/models/")) {
1550
+ const modelId = url.slice("/v1/models/".length);
1551
+ const model = resolveModel(modelId);
1552
+ if (!model) return json(res, 404, { error: { type: "error", error: { type: "not_found_error", message: `Model not found: ${modelId}` } } });
1553
+ return json(res, 200, {
1554
+ id: modelId,
1555
+ type: "model",
1556
+ display_name: model.name,
1557
+ created_at: "2024-01-01T00:00:00Z",
1558
+ });
1559
+ }
1560
+
1561
+ if (req.method === "POST" && urlPath === "/v1/chat/completions") {
1562
+ try { return await openaiChat(req, res, body); }
1563
+ catch (e) {
1564
+ console.error(`[OPENAI-FATAL] ${e.message}\n${e.stack}`);
1565
+ if (!res.headersSent) return json(res, 500, { error: { type: "api_error", message: e.message } });
1566
+ else { try { res.end(); } catch {} }
1567
+ }
1568
+ }
1569
+ if (req.method === "POST" && urlPath === "/v1/messages") {
1570
+ try { return await anthropicMessages(req, res, body); }
1571
+ catch (e) {
1572
+ console.error(`[ANTHROPIC-FATAL] ${e.message}\n${e.stack}`);
1573
+ if (!res.headersSent) return json(res, 500, { error: { type: "api_error", message: e.message } });
1574
+ else { try { res.end(); } catch {} }
1575
+ }
1576
+ }
1577
+
1578
+ json(res, 404, { error: { message: `Not found: ${req.method} ${url}` } });
1579
+ }
1580
+
1581
+ // ============================================================
1582
+ // 11. 启动
1583
+ // ============================================================
1584
+ const PORT = process.env.PORT || CONFIG.server?.port || 8080;
1585
+ const HOST = CONFIG.server?.host || "0.0.0.0";
1586
+
1587
+ http.createServer(router).listen(PORT, HOST, () => {
1588
+ console.log(`\n${'='.repeat(50)}`);
1589
+ console.log(`[STARTUP] 服务启动于 http://${HOST}:${PORT}`);
1590
+ console.log(`[STARTUP] API keys count: ${API_KEYS.size} (source: ${(process.env.IMA_API_KEYS || "") ? "env IMA_API_KEYS" : "config.json"})`);
1591
+ for (const k of API_KEYS) {
1592
+ console.log(`[STARTUP] key: ${maskKey(k)} (len=${k.length})`);
1593
+ }
1594
+ setInterval(refreshCookie, 60 * 1000);
1595
+ });