one-model-router 0.0.10 → 0.0.11
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/LICENSE +21 -21
- package/package.json +1 -1
- package/src/admin.js +941 -941
- package/src/balances.js +61 -61
- package/src/boot.js +117 -117
- package/src/channels/buddy.js +2031 -2031
- package/src/channels/cline.js +753 -753
- package/src/channels/codearts.js +2051 -2051
- package/src/channels/comate.js +830 -830
- package/src/channels/doubaowork.js +1784 -1784
- package/src/channels/freebuff.js +1316 -1316
- package/src/channels/gemini.js +1721 -1721
- package/src/channels/index.js +270 -270
- package/src/channels/joycode.js +936 -936
- package/src/channels/kimi.js +572 -572
- package/src/channels/lobsterai.js +1226 -1226
- package/src/channels/loomy.js +1032 -1032
- package/src/channels/miaoshou.js +1396 -1396
- package/src/channels/mimo.js +474 -474
- package/src/channels/minimax.js +1451 -1451
- package/src/channels/qoder-wasm.js +434 -434
- package/src/channels/qoder.js +1619 -1619
- package/src/channels/raccoon.js +1842 -1842
- package/src/channels/tabbit.js +1457 -1457
- package/src/channels/trae.js +1405 -1405
- package/src/channels/zcode-global.js +35 -35
- package/src/channels/zcode.js +2085 -2085
- package/src/checkin.js +496 -496
- package/src/credits.js +464 -464
- package/src/crypto.js +132 -132
- package/src/free-models.js +683 -683
- package/src/gateway.js +596 -578
- package/src/health.js +86 -86
- package/src/model-key.js +35 -35
- package/src/paths.js +96 -96
- package/src/probe.js +318 -318
- package/src/providers/builtin.js +626 -626
- package/src/providers/index.js +483 -457
- package/src/providers/kilo.js +111 -111
- package/src/providers/last-good.js +69 -69
- package/src/providers/modelsdev.js +242 -242
- package/src/providers/openai-compat.js +312 -312
- package/src/providers/opencode/bun-fetch.js +226 -226
- package/src/providers/opencode/lane.js +186 -186
- package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
- package/src/providers/opencode/o2a/asset-source.js +43 -43
- package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
- package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
- package/src/providers/opencode/o2a/entry.js +17 -17
- package/src/providers/opencode/o2a/gateway-body.js +42 -42
- package/src/providers/opencode/o2a/headers.js +133 -133
- package/src/providers/opencode/o2a/identity.js +148 -148
- package/src/providers/opencode/o2a/official-prompt.js +191 -191
- package/src/providers/opencode/o2a/official-tools.js +110 -110
- package/src/providers/opencode/o2a/tool-renames.js +217 -217
- package/src/providers/opencode/o2a/toolshape.js +418 -418
- package/src/providers/opencode/o2a/version.js +37 -37
- package/src/providers/opencode/upstream.js +403 -403
- package/src/providers/opencode/wire.js +496 -496
- package/src/providers/opencode.js +652 -652
- package/src/router.js +629 -629
- package/src/server.js +33 -33
- package/src/store.js +467 -467
- package/src/sync/index.js +1529 -1529
- package/src/sync/login-preload.cjs +52 -52
- package/src/sync/noise.js +141 -141
- package/src/sync/relay-http.js +176 -176
- package/src/sync/remote-host.js +818 -818
- package/src/sync/remote-http.js +112 -112
- package/src/sync/remote-login.js +657 -657
- package/src/sync/remote-pairing.js +204 -204
- package/src/sync/remote-protocol.js +321 -321
- package/src/sync/snapshot.js +211 -211
- package/src/util.js +334 -334
- package/web/app.js +3972 -3972
- package/web/index.html +32 -32
- package/web/style.css +971 -971
|
@@ -1,403 +1,403 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OpenCode 免密车道的线缆层(请求整形 + 身份铸造 + 端点分流)。
|
|
3
|
-
*
|
|
4
|
-
* 本文件承担请求整形、身份铸造与端点分流;`o2a/` 子目录是匿名道整形层的
|
|
5
|
-
* 各纯函数模块(见 o2a/ 各文件头注释与本文件第 2 节)。
|
|
6
|
-
*
|
|
7
|
-
* ## 1. 上游事实(每条都对应一次 403/429 实测)
|
|
8
|
-
*
|
|
9
|
-
* - 免费道只认「官方 2.x CLI 客户端形状」:UA `opencode/latest/<major≥2.x.x>/cli`
|
|
10
|
-
* 整串匹配、四个会话头同值、40-hex `x-opencode-project`、`traceparent`/`b3`;
|
|
11
|
-
* **发 v1 专用头 `x-opencode-request` 即 403**。
|
|
12
|
-
* - session id 必须是铸造形状(`ses_` + 降序时钟 12 hex + 14 base62),且内嵌日期
|
|
13
|
-
* 要可信(慢钟:今日 UTC 零点 − ≤30 天)。哈希派生 → 403/429。
|
|
14
|
-
* - 请求体里出现别的客户端的工具词汇即 429 ⇒ 调用方工具全部改名 `clint_<12hex>`,
|
|
15
|
-
* 再补官方 13 工具全量(逐字定义);已能折 onto 官方拼写的(`Bash`→`shell` 等)
|
|
16
|
-
* 直接绑官方名,不再重复补。
|
|
17
|
-
* - 缺官方 CLI 系统提示(base + `<env>` + skills)即 429。
|
|
18
|
-
* - `tool_choice: 'none'` 一律 403,绝不下发;Responses 线无 choice 时补 `auto`。
|
|
19
|
-
* - 配额按 **出口 IP × project id** 计,一对话一 session(逐请求新铸会把额度烧成 429)。
|
|
20
|
-
*
|
|
21
|
-
* 端点按 2.1 客户端的 provider 家族分组:`/inference/openai/v1/…`、
|
|
22
|
-
* `/inference/anthropic/v1/messages?beta=true`(旧的扁平 `/inference/v1/…` 仍通,
|
|
23
|
-
* 但那是 2.0 的形状)。
|
|
24
|
-
*
|
|
25
|
-
* ## 2. 本实现与官方客户端的差异(有意为之)
|
|
26
|
-
*
|
|
27
|
-
* 1. **占位提示保留**:注入的官方工具对本机的调用方(Claude Code / Cline / …)
|
|
28
|
-
* 不可执行,注入后追加一句「placeholders in this session」压住模型调用。
|
|
29
|
-
* 2. **`tool_choice:'none'` 兜底删除**:调用方(含 OMR 自身的续写路径)可能留下它。
|
|
30
|
-
* 3. **幂等整形**:重试路径可能对已整形的请求体再次整形,逐字官方声明视为官方声明。
|
|
31
|
-
* 4. **Chat 线提示注入保留块对象**(前插,不折叠重建)。
|
|
32
|
-
* 5. **不强制 `stream`**:OMR 的门面自己决定流式与否,这里只在 `stream===true`
|
|
33
|
-
* 时补 `stream_options`。
|
|
34
|
-
* 6. **会话跨重启持久**:conversation → session 落盘 `opencode-session-map.json`,
|
|
35
|
-
* 日期离窗的旧 id 重铸。
|
|
36
|
-
* 7. **响应端 copy-on-write**:工具对象/历史行属于调用方,改名一律换浅拷贝。
|
|
37
|
-
*
|
|
38
|
-
* @module src/providers/opencode/upstream
|
|
39
|
-
*/
|
|
40
|
-
|
|
41
|
-
import fs from 'node:fs'
|
|
42
|
-
import path from 'node:path'
|
|
43
|
-
import { DATA_DIR } from '../../store.js'
|
|
44
|
-
import {
|
|
45
|
-
CANONICAL_SESSION_RE,
|
|
46
|
-
CLIENT_UA,
|
|
47
|
-
DESCENDING_TIME_RE,
|
|
48
|
-
O2A_VERSION,
|
|
49
|
-
ToolRenameMap,
|
|
50
|
-
canonicalSessionID,
|
|
51
|
-
ensureChatUsage,
|
|
52
|
-
ensureV2CompletionLimit,
|
|
53
|
-
gatewayHeaders as o2aGatewayHeaders,
|
|
54
|
-
injectOfficialPrompt,
|
|
55
|
-
officialTool,
|
|
56
|
-
phaseAgeMs,
|
|
57
|
-
randomProjectID,
|
|
58
|
-
renameAndCompleteTools,
|
|
59
|
-
renamableToolName,
|
|
60
|
-
sessionPhaseMs,
|
|
61
|
-
} from './o2a/entry.js'
|
|
62
|
-
|
|
63
|
-
export { CLIENT_UA, O2A_VERSION, ANONYMOUS_CREDENTIAL } from './o2a/entry.js'
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* 上游 Origin(可覆盖,便于把测试指向本机 stand-in 网关,杜绝离线套件打到真实免费道)。
|
|
67
|
-
* 环境变量优先,其次设置里的 baseUrl(由门面归一成 Origin)。
|
|
68
|
-
*/
|
|
69
|
-
export function upstreamOrigin(settings) {
|
|
70
|
-
const override = String(process.env.OMR_OPENCODE_BASE ?? '').trim()
|
|
71
|
-
if (override !== '') return override.replace(/\/+$/, '')
|
|
72
|
-
const configured = typeof settings?.baseUrl === 'string' ? settings.baseUrl.trim() : ''
|
|
73
|
-
if (configured !== '') {
|
|
74
|
-
try {
|
|
75
|
-
const url = new URL(configured)
|
|
76
|
-
return `${url.protocol}//${url.host}`.replace(/\/+$/, '')
|
|
77
|
-
} catch { /* 非法地址:回落默认 Origin */ }
|
|
78
|
-
}
|
|
79
|
-
return 'https://opencode.ai'
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export const DEFAULT_ORIGIN = 'https://opencode.ai'
|
|
83
|
-
|
|
84
|
-
/** 清单地址:`/models` 在两条线都回同一份 id 清单,取扁平旧路径。 */
|
|
85
|
-
export const LISTING_PATH = '/inference/v1/models'
|
|
86
|
-
|
|
87
|
-
const MAX_SESSION_LENGTH = 256
|
|
88
|
-
/** 上游工具名上限(Anthropic Messages 线的硬限制)。 */
|
|
89
|
-
export const MAX_TOOL_NAME_LEN = 64
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* 需要 Responses 线的免费模型(Chat 线对其 400/404)。按 id 前缀判别,因为上游
|
|
93
|
-
* 清单里同一族的 id 会随版本换后缀(muse-spark-1.2/1.3-contributor-free)。
|
|
94
|
-
*/
|
|
95
|
-
const RESPONSES_MODELS = new Set(['muse-spark-1.2-contributor-free', 'muse-spark-1.3-contributor-free'])
|
|
96
|
-
/** 只认 Anthropic Messages 线的模型。 */
|
|
97
|
-
const MESSAGES_MODELS = new Set(['union-alpha'])
|
|
98
|
-
|
|
99
|
-
/** 去掉尾部 "(level)" 思考档位后缀,便于按基名查表。 */
|
|
100
|
-
export function baseModelId(model) {
|
|
101
|
-
return String(model ?? '').replace(/\([^()]+\)\s*$/, '').trim()
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function isMuseSpark(modelId) {
|
|
105
|
-
const clean = baseModelId(modelId)
|
|
106
|
-
const base = clean.includes('/') ? clean.split('/').pop() : clean
|
|
107
|
-
return /^muse[-_]?spark(?:$|[-_:.\s])/i.test(base)
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/** 该模型走哪条线('chat' | 'responses' | 'messages')。 */
|
|
111
|
-
export function wireOf(modelId) {
|
|
112
|
-
if (isMuseSpark(modelId) || RESPONSES_MODELS.has(baseModelId(modelId))) return 'responses'
|
|
113
|
-
if (MESSAGES_MODELS.has(baseModelId(modelId))) return 'messages'
|
|
114
|
-
return 'chat'
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/** 整形层的形状名(o2a 各模块用的三值)。 */
|
|
118
|
-
export function shapeOf(wire) {
|
|
119
|
-
return wire === 'responses' ? 'flat' : wire === 'messages' ? 'claude' : 'chat'
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/** 该模型的上游路径(含 Anthropic 的 beta 查询)。 */
|
|
123
|
-
export function endpointFor(modelId) {
|
|
124
|
-
const wire = wireOf(modelId)
|
|
125
|
-
if (wire === 'responses') return '/inference/openai/v1/responses'
|
|
126
|
-
if (wire === 'messages') return '/inference/anthropic/v1/messages?beta=true'
|
|
127
|
-
return '/inference/openai/v1/chat/completions'
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// ── 会话身份 ────────────────────────────────────────────────────────────────
|
|
131
|
-
|
|
132
|
-
export const SESSION_RE = CANONICAL_SESSION_RE
|
|
133
|
-
export const SESSION_DESCENDING_RE = DESCENDING_TIME_RE
|
|
134
|
-
|
|
135
|
-
/** 该 id 是否为上游会照单接受的官方铸造形状。 */
|
|
136
|
-
export function isCanonicalSession(id) {
|
|
137
|
-
return typeof id === 'string' && SESSION_RE.test(id.trim()) && SESSION_DESCENDING_RE.test(id.trim().slice(4, 16))
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/** 任意会话信号 → 规范 session(官方 id 透传,其余按慢钟重铸)。 */
|
|
141
|
-
export function canonicalizeSession(signal) {
|
|
142
|
-
return canonicalSessionID(signal)
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* 保留的 session id 允许的相位龄。线上时间段是 36 位毫秒相位(约 795 天一个循环),
|
|
147
|
-
* 慢钟铸造的相位最老 30 天;60 天上限既让本车道铸的 id 长期复用,又能把早期
|
|
148
|
-
* 遗留的「哈希相位」旧 id 重铸掉(那些 id 一律答 429)。
|
|
149
|
-
*/
|
|
150
|
-
const SESSION_PLAUSIBILITY_MS = 60 * 24 * 60 * 60 * 1000
|
|
151
|
-
|
|
152
|
-
const SESSION_MAP_FILE = 'opencode-session-map.json'
|
|
153
|
-
let sessions
|
|
154
|
-
|
|
155
|
-
function sessionStorePath() {
|
|
156
|
-
try { return path.join(path.resolve(DATA_DIR), SESSION_MAP_FILE) } catch { return undefined }
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
function loadSessions() {
|
|
160
|
-
if (sessions !== undefined) return sessions
|
|
161
|
-
sessions = new Map()
|
|
162
|
-
try {
|
|
163
|
-
const file = sessionStorePath()
|
|
164
|
-
if (file === undefined) return sessions
|
|
165
|
-
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
166
|
-
for (const [seed, id] of Object.entries(parsed?.sessions ?? {})) {
|
|
167
|
-
if (typeof id === 'string' && SESSION_RE.test(id)) sessions.set(seed, id)
|
|
168
|
-
}
|
|
169
|
-
} catch { /* 首次运行或文件不可读:从空表开始 */ }
|
|
170
|
-
return sessions
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
function rememberSession(seed, id) {
|
|
174
|
-
loadSessions().set(seed, id)
|
|
175
|
-
try {
|
|
176
|
-
const file = sessionStorePath()
|
|
177
|
-
if (file === undefined) return
|
|
178
|
-
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
179
|
-
const temp = `${file}.tmp`
|
|
180
|
-
writeAtomic(temp, JSON.stringify({ version: 2, at: Date.now(), sessions: Object.fromEntries(sessions) }, undefined, 2))
|
|
181
|
-
fs.renameSync(temp, file)
|
|
182
|
-
} catch { /* 非致命:id 仍然可用,只是重启后不保留 */ }
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
function writeAtomic(target, text) {
|
|
186
|
-
fs.writeFileSync(target, text, 'utf8')
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** 保留的 session 内嵌相位是否仍在上游接受的窗口内。 */
|
|
190
|
-
function plausibleSession(id) {
|
|
191
|
-
const phase = sessionPhaseMs(id)
|
|
192
|
-
return phase !== null && phaseAgeMs(phase) < SESSION_PLAUSIBILITY_MS
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* 一个下游会话 → 一个稳定上游 session:铸一次并持久化,重试/换模型都不轮转。
|
|
197
|
-
* 调用方给的规范 id 直接保留。
|
|
198
|
-
*/
|
|
199
|
-
export function sessionForConversation(sessionId) {
|
|
200
|
-
if (typeof sessionId === 'string' && isCanonicalSession(sessionId)) return sessionId.trim()
|
|
201
|
-
const seed = typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : 'global'
|
|
202
|
-
const remembered = loadSessions().get(seed)
|
|
203
|
-
if (remembered !== undefined && isCanonicalSession(remembered) && plausibleSession(remembered)) return remembered
|
|
204
|
-
const minted = canonicalizeSession(seed)
|
|
205
|
-
rememberSession(seed, minted)
|
|
206
|
-
return minted
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/** 截断到上游接受的 session 长度。 */
|
|
210
|
-
export function truncateSession(value) {
|
|
211
|
-
if (typeof value !== 'string') return ''
|
|
212
|
-
const trimmed = value.trim()
|
|
213
|
-
return trimmed.length > MAX_SESSION_LENGTH ? trimmed.slice(0, MAX_SESSION_LENGTH) : trimmed
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/** 一次性 project id(40 hex):调用方没命名项目时用,便于按请求摊配额。 */
|
|
217
|
-
export function randomProjectId() {
|
|
218
|
-
return randomProjectID()
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* 免密道的头集(v2 形状)。`session` 同时作为 project 信号传入 ⇒
|
|
223
|
-
* 同一会话的重试/续写/刷新共用一个配额桶。
|
|
224
|
-
*/
|
|
225
|
-
export function gatewayHeaders({ session, userAgent, anthropic = false, accept } = {}) {
|
|
226
|
-
const canonical = truncateSession(session)
|
|
227
|
-
const headers = o2aGatewayHeaders({
|
|
228
|
-
session: canonical,
|
|
229
|
-
project: canonical,
|
|
230
|
-
anthropic,
|
|
231
|
-
...(accept === undefined ? {} : { accept }),
|
|
232
|
-
})
|
|
233
|
-
if (typeof userAgent === 'string' && userAgent.trim() !== '') headers['user-agent'] = userAgent
|
|
234
|
-
return headers
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// ── 请求体整形 ──────────────────────────────────────────────────────────────
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* 门禁校验的两个名字(v1 时代结论,v2 起闸门比对全量官方定义):
|
|
241
|
-
* 保留导出只为守卫测试与人工排障时一眼看出核心项。
|
|
242
|
-
*/
|
|
243
|
-
export const FINGERPRINT_TOOLS = ['read', 'shell']
|
|
244
|
-
|
|
245
|
-
function toolNameOf(tool) {
|
|
246
|
-
if (!tool || typeof tool !== 'object' || Array.isArray(tool)) return ''
|
|
247
|
-
if (typeof tool.name === 'string' && tool.name.trim()) return tool.name.trim()
|
|
248
|
-
const fn = tool.function
|
|
249
|
-
if (fn && typeof fn === 'object' && !Array.isArray(fn) && typeof fn.name === 'string') return fn.name.trim()
|
|
250
|
-
return ''
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/** 该声明是否已带逐字官方定义(幂等整形的判据;按渲染后的官方项比对)。 */
|
|
254
|
-
function carriesOfficialDefinition(entry, name, shape) {
|
|
255
|
-
const own = definitionOf(entry, shape)
|
|
256
|
-
if (own === null) return false
|
|
257
|
-
const rendered = officialTool(shape, name)
|
|
258
|
-
const wrapper = shape === 'chat' ? rendered.function : rendered
|
|
259
|
-
if (!wrapper) return false
|
|
260
|
-
return own.description === wrapper.description
|
|
261
|
-
&& JSON.stringify(own.schema) === JSON.stringify(wrapper.parameters)
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
/** 一条工具声明在某形状下的描述与参数 schema 位置。 */
|
|
265
|
-
function definitionOf(entry, shape) {
|
|
266
|
-
if (!entry || typeof entry !== 'object') return null
|
|
267
|
-
const wrapper = shape === 'chat' ? entry.function : entry
|
|
268
|
-
if (wrapper === null || wrapper === undefined || typeof wrapper !== 'object') return null
|
|
269
|
-
const schema = shape === 'claude' ? wrapper.input_schema : wrapper.parameters
|
|
270
|
-
return { description: wrapper.description, schema }
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* 注入的官方工具对本机调用方不可执行 —— 措辞是实测选出来的:
|
|
275
|
-
* 写成「不可用」会让模型连调用方自己的 `Read`/`Bash` 也一起拒绝;
|
|
276
|
-
* 「占位、请用别的工具」才既压住注入项、又不误伤调用方的工具。
|
|
277
|
-
*/
|
|
278
|
-
function placeholderNote(names) {
|
|
279
|
-
const list = names.map(name => `\`${name}\``).join(', ')
|
|
280
|
-
return `The tools ${list} are part of the host CLI's own toolset and are placeholders in this session; they do nothing here. Use the other tools you have been given instead.`
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
/** 只追加免费道上下文,绝不替换调用方的 system 文本或块对象。 */
|
|
284
|
-
function appendSystemContext(body, shape, note) {
|
|
285
|
-
if (shape === 'flat') {
|
|
286
|
-
body.instructions = typeof body.instructions === 'string' && body.instructions.trim() !== ''
|
|
287
|
-
? `${body.instructions}\n\n${note}`
|
|
288
|
-
: note
|
|
289
|
-
return
|
|
290
|
-
}
|
|
291
|
-
if (shape === 'claude') {
|
|
292
|
-
body.system = Array.isArray(body.system)
|
|
293
|
-
? [...body.system, { type: 'text', text: note }]
|
|
294
|
-
: typeof body.system === 'string' && body.system !== '' ? `${body.system}\n\n${note}` : note
|
|
295
|
-
return
|
|
296
|
-
}
|
|
297
|
-
const messages = Array.isArray(body.messages) ? body.messages : []
|
|
298
|
-
const first = messages[0]
|
|
299
|
-
if (first?.role === 'system' && typeof first.content === 'string') {
|
|
300
|
-
body.messages = [{ ...first, content: `${first.content}\n\n${note}` }, ...messages.slice(1)]
|
|
301
|
-
return
|
|
302
|
-
}
|
|
303
|
-
if (first?.role === 'system' && Array.isArray(first.content)) {
|
|
304
|
-
body.messages = [{ ...first, content: [...first.content, { type: 'text', text: note }] }, ...messages.slice(1)]
|
|
305
|
-
return
|
|
306
|
-
}
|
|
307
|
-
body.messages = [{ role: 'system', content: note }, ...messages]
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
/**
|
|
311
|
-
* 免费道把「无工具、1–3 轮、带标题标记」的请求体读作标题生成器
|
|
312
|
-
* (`title.IsTitleRequest`):给它挂上 agent 形状的工具清单
|
|
313
|
-
* 会换来 403/429。对这类请求体停止整形,本车道同做——
|
|
314
|
-
* 标题请求按调用方原样上线(不注入提示、不补工具、不改名)。
|
|
315
|
-
*/
|
|
316
|
-
const TITLE_MARKERS = /generate a title|write a title|create a title|come up with a title|title (?:for|of) (?:this|the) (?:conversation|chat|session|exchange|request)|conversation title|summarize (?:this|the) conversation/i
|
|
317
|
-
|
|
318
|
-
export function isTitleRequest(body, shape) {
|
|
319
|
-
if (!body || typeof body !== 'object') return false
|
|
320
|
-
if ((Array.isArray(body.tools) && body.tools.length > 0) || (Array.isArray(body.functions) && body.functions.length > 0)) return false
|
|
321
|
-
if (body.tool_choice !== undefined) return false
|
|
322
|
-
const textOf = value => typeof value === 'string' ? value
|
|
323
|
-
: Array.isArray(value) ? value.map(part => part?.text ?? '').join('\n') : ''
|
|
324
|
-
let turns
|
|
325
|
-
let leading = ''
|
|
326
|
-
if (shape === 'flat') {
|
|
327
|
-
turns = (Array.isArray(body.input) ? body.input : []).filter(item => item !== null && typeof item === 'object' && typeof item.role === 'string')
|
|
328
|
-
leading = textOf(body.instructions)
|
|
329
|
-
} else {
|
|
330
|
-
turns = (Array.isArray(body.messages) ? body.messages : []).filter(message => message !== null && typeof message === 'object')
|
|
331
|
-
leading = shape === 'claude' ? textOf(body.system) : ''
|
|
332
|
-
}
|
|
333
|
-
if (turns.length === 0 || turns.length > 3) return false
|
|
334
|
-
for (const turn of turns) {
|
|
335
|
-
if (!['user', 'system', 'developer'].includes(String(turn.role ?? ''))) return false
|
|
336
|
-
}
|
|
337
|
-
return TITLE_MARKERS.test(`${leading}\n${turns.map(turn => textOf(turn.content)).join('\n')}`)
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
/**
|
|
341
|
-
* 满足免费道的 v2 客户端指纹(整形顺序固定):
|
|
342
|
-
*
|
|
343
|
-
* 1. 标题请求整类免整形;
|
|
344
|
-
* 2. 注入官方 CLI 系统提示(base + `<env>` + skills,按线注入,已带标记的跳过);
|
|
345
|
-
* 3. 调用方工具全部改名/绑定官方名 + 补齐官方 13 工具(逐字定义,幂等);
|
|
346
|
-
* 4. 注入项补「占位」提示;
|
|
347
|
-
* 5. 绝不下发 `tool_choice:'none'`;Responses 线无 choice 时补 `auto`;
|
|
348
|
-
* 6. Chat 线补 `stream_options.include_usage` 与 `max_completion_tokens` 上限。
|
|
349
|
-
*
|
|
350
|
-
* @param {object} body - 请求体(就地整形;调用方对象按 copy-on-write 替换)
|
|
351
|
-
* @param {'chat'|'flat'|'claude'} shape - 该请求体说的话
|
|
352
|
-
* @param {object} [options]
|
|
353
|
-
* @param {string} [options.model] - 提示 `<env>` 里报出的模型 id
|
|
354
|
-
* @param {string} [options.workDir] - 提示 `<env>` 里的工作目录
|
|
355
|
-
* @returns {ToolRenameMap} 线上名 → 调用方原名(响应侧还原用)
|
|
356
|
-
*/
|
|
357
|
-
export function applyFingerprint(body, shape, { model, workDir } = {}) {
|
|
358
|
-
if (!body || typeof body !== 'object') return new ToolRenameMap()
|
|
359
|
-
if (isTitleRequest(body, shape)) return new ToolRenameMap()
|
|
360
|
-
|
|
361
|
-
injectOfficialPrompt(body, shape, { workDir, model })
|
|
362
|
-
|
|
363
|
-
const tools = Array.isArray(body.tools) ? body.tools : []
|
|
364
|
-
const keep = new Set()
|
|
365
|
-
for (const tool of tools) {
|
|
366
|
-
const name = renamableToolName(shape, tool)
|
|
367
|
-
if (name !== null && carriesOfficialDefinition(tool, name, shape)) keep.add(name)
|
|
368
|
-
}
|
|
369
|
-
const { renames, injected } = renameAndCompleteTools(body, shape, { keep })
|
|
370
|
-
|
|
371
|
-
if (injected.length > 0) appendSystemContext(body, shape, placeholderNote(injected))
|
|
372
|
-
|
|
373
|
-
if (body.tool_choice === 'none'
|
|
374
|
-
|| (body.tool_choice !== null && typeof body.tool_choice === 'object' && body.tool_choice.type === 'none')) {
|
|
375
|
-
delete body.tool_choice
|
|
376
|
-
}
|
|
377
|
-
if (shape === 'flat' && !body.tool_choice) body.tool_choice = 'auto'
|
|
378
|
-
|
|
379
|
-
ensureChatUsage(body, shape)
|
|
380
|
-
ensureV2CompletionLimit(body, shape)
|
|
381
|
-
return renames
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
/** 把上游报回的工具名还原成调用方声明的名字(流式增量与最终负载都走这里)。 */
|
|
385
|
-
export function restoreToolName(name, map) {
|
|
386
|
-
if (!map) return name
|
|
387
|
-
if (typeof map.resolve === 'function') return map.resolve(name)
|
|
388
|
-
if (map.size === 0) return name
|
|
389
|
-
return map.get(name) ?? name
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
/** 请求体声明的工具名集合(排障/守卫用)。 */
|
|
393
|
-
export function declaredToolNames(body) {
|
|
394
|
-
const names = new Set()
|
|
395
|
-
for (const tool of Array.isArray(body.tools) ? body.tools : []) {
|
|
396
|
-
const n = toolNameOf(tool)
|
|
397
|
-
if (n) names.add(n)
|
|
398
|
-
}
|
|
399
|
-
return names
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/** 供离线守卫复用:整形用到的官方工具名集合。 */
|
|
403
|
-
export { V2_OFFICIAL_TOOL_ORDER } from './o2a/entry.js'
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode 免密车道的线缆层(请求整形 + 身份铸造 + 端点分流)。
|
|
3
|
+
*
|
|
4
|
+
* 本文件承担请求整形、身份铸造与端点分流;`o2a/` 子目录是匿名道整形层的
|
|
5
|
+
* 各纯函数模块(见 o2a/ 各文件头注释与本文件第 2 节)。
|
|
6
|
+
*
|
|
7
|
+
* ## 1. 上游事实(每条都对应一次 403/429 实测)
|
|
8
|
+
*
|
|
9
|
+
* - 免费道只认「官方 2.x CLI 客户端形状」:UA `opencode/latest/<major≥2.x.x>/cli`
|
|
10
|
+
* 整串匹配、四个会话头同值、40-hex `x-opencode-project`、`traceparent`/`b3`;
|
|
11
|
+
* **发 v1 专用头 `x-opencode-request` 即 403**。
|
|
12
|
+
* - session id 必须是铸造形状(`ses_` + 降序时钟 12 hex + 14 base62),且内嵌日期
|
|
13
|
+
* 要可信(慢钟:今日 UTC 零点 − ≤30 天)。哈希派生 → 403/429。
|
|
14
|
+
* - 请求体里出现别的客户端的工具词汇即 429 ⇒ 调用方工具全部改名 `clint_<12hex>`,
|
|
15
|
+
* 再补官方 13 工具全量(逐字定义);已能折 onto 官方拼写的(`Bash`→`shell` 等)
|
|
16
|
+
* 直接绑官方名,不再重复补。
|
|
17
|
+
* - 缺官方 CLI 系统提示(base + `<env>` + skills)即 429。
|
|
18
|
+
* - `tool_choice: 'none'` 一律 403,绝不下发;Responses 线无 choice 时补 `auto`。
|
|
19
|
+
* - 配额按 **出口 IP × project id** 计,一对话一 session(逐请求新铸会把额度烧成 429)。
|
|
20
|
+
*
|
|
21
|
+
* 端点按 2.1 客户端的 provider 家族分组:`/inference/openai/v1/…`、
|
|
22
|
+
* `/inference/anthropic/v1/messages?beta=true`(旧的扁平 `/inference/v1/…` 仍通,
|
|
23
|
+
* 但那是 2.0 的形状)。
|
|
24
|
+
*
|
|
25
|
+
* ## 2. 本实现与官方客户端的差异(有意为之)
|
|
26
|
+
*
|
|
27
|
+
* 1. **占位提示保留**:注入的官方工具对本机的调用方(Claude Code / Cline / …)
|
|
28
|
+
* 不可执行,注入后追加一句「placeholders in this session」压住模型调用。
|
|
29
|
+
* 2. **`tool_choice:'none'` 兜底删除**:调用方(含 OMR 自身的续写路径)可能留下它。
|
|
30
|
+
* 3. **幂等整形**:重试路径可能对已整形的请求体再次整形,逐字官方声明视为官方声明。
|
|
31
|
+
* 4. **Chat 线提示注入保留块对象**(前插,不折叠重建)。
|
|
32
|
+
* 5. **不强制 `stream`**:OMR 的门面自己决定流式与否,这里只在 `stream===true`
|
|
33
|
+
* 时补 `stream_options`。
|
|
34
|
+
* 6. **会话跨重启持久**:conversation → session 落盘 `opencode-session-map.json`,
|
|
35
|
+
* 日期离窗的旧 id 重铸。
|
|
36
|
+
* 7. **响应端 copy-on-write**:工具对象/历史行属于调用方,改名一律换浅拷贝。
|
|
37
|
+
*
|
|
38
|
+
* @module src/providers/opencode/upstream
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import fs from 'node:fs'
|
|
42
|
+
import path from 'node:path'
|
|
43
|
+
import { DATA_DIR } from '../../store.js'
|
|
44
|
+
import {
|
|
45
|
+
CANONICAL_SESSION_RE,
|
|
46
|
+
CLIENT_UA,
|
|
47
|
+
DESCENDING_TIME_RE,
|
|
48
|
+
O2A_VERSION,
|
|
49
|
+
ToolRenameMap,
|
|
50
|
+
canonicalSessionID,
|
|
51
|
+
ensureChatUsage,
|
|
52
|
+
ensureV2CompletionLimit,
|
|
53
|
+
gatewayHeaders as o2aGatewayHeaders,
|
|
54
|
+
injectOfficialPrompt,
|
|
55
|
+
officialTool,
|
|
56
|
+
phaseAgeMs,
|
|
57
|
+
randomProjectID,
|
|
58
|
+
renameAndCompleteTools,
|
|
59
|
+
renamableToolName,
|
|
60
|
+
sessionPhaseMs,
|
|
61
|
+
} from './o2a/entry.js'
|
|
62
|
+
|
|
63
|
+
export { CLIENT_UA, O2A_VERSION, ANONYMOUS_CREDENTIAL } from './o2a/entry.js'
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 上游 Origin(可覆盖,便于把测试指向本机 stand-in 网关,杜绝离线套件打到真实免费道)。
|
|
67
|
+
* 环境变量优先,其次设置里的 baseUrl(由门面归一成 Origin)。
|
|
68
|
+
*/
|
|
69
|
+
export function upstreamOrigin(settings) {
|
|
70
|
+
const override = String(process.env.OMR_OPENCODE_BASE ?? '').trim()
|
|
71
|
+
if (override !== '') return override.replace(/\/+$/, '')
|
|
72
|
+
const configured = typeof settings?.baseUrl === 'string' ? settings.baseUrl.trim() : ''
|
|
73
|
+
if (configured !== '') {
|
|
74
|
+
try {
|
|
75
|
+
const url = new URL(configured)
|
|
76
|
+
return `${url.protocol}//${url.host}`.replace(/\/+$/, '')
|
|
77
|
+
} catch { /* 非法地址:回落默认 Origin */ }
|
|
78
|
+
}
|
|
79
|
+
return 'https://opencode.ai'
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export const DEFAULT_ORIGIN = 'https://opencode.ai'
|
|
83
|
+
|
|
84
|
+
/** 清单地址:`/models` 在两条线都回同一份 id 清单,取扁平旧路径。 */
|
|
85
|
+
export const LISTING_PATH = '/inference/v1/models'
|
|
86
|
+
|
|
87
|
+
const MAX_SESSION_LENGTH = 256
|
|
88
|
+
/** 上游工具名上限(Anthropic Messages 线的硬限制)。 */
|
|
89
|
+
export const MAX_TOOL_NAME_LEN = 64
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 需要 Responses 线的免费模型(Chat 线对其 400/404)。按 id 前缀判别,因为上游
|
|
93
|
+
* 清单里同一族的 id 会随版本换后缀(muse-spark-1.2/1.3-contributor-free)。
|
|
94
|
+
*/
|
|
95
|
+
const RESPONSES_MODELS = new Set(['muse-spark-1.2-contributor-free', 'muse-spark-1.3-contributor-free'])
|
|
96
|
+
/** 只认 Anthropic Messages 线的模型。 */
|
|
97
|
+
const MESSAGES_MODELS = new Set(['union-alpha'])
|
|
98
|
+
|
|
99
|
+
/** 去掉尾部 "(level)" 思考档位后缀,便于按基名查表。 */
|
|
100
|
+
export function baseModelId(model) {
|
|
101
|
+
return String(model ?? '').replace(/\([^()]+\)\s*$/, '').trim()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function isMuseSpark(modelId) {
|
|
105
|
+
const clean = baseModelId(modelId)
|
|
106
|
+
const base = clean.includes('/') ? clean.split('/').pop() : clean
|
|
107
|
+
return /^muse[-_]?spark(?:$|[-_:.\s])/i.test(base)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 该模型走哪条线('chat' | 'responses' | 'messages')。 */
|
|
111
|
+
export function wireOf(modelId) {
|
|
112
|
+
if (isMuseSpark(modelId) || RESPONSES_MODELS.has(baseModelId(modelId))) return 'responses'
|
|
113
|
+
if (MESSAGES_MODELS.has(baseModelId(modelId))) return 'messages'
|
|
114
|
+
return 'chat'
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 整形层的形状名(o2a 各模块用的三值)。 */
|
|
118
|
+
export function shapeOf(wire) {
|
|
119
|
+
return wire === 'responses' ? 'flat' : wire === 'messages' ? 'claude' : 'chat'
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 该模型的上游路径(含 Anthropic 的 beta 查询)。 */
|
|
123
|
+
export function endpointFor(modelId) {
|
|
124
|
+
const wire = wireOf(modelId)
|
|
125
|
+
if (wire === 'responses') return '/inference/openai/v1/responses'
|
|
126
|
+
if (wire === 'messages') return '/inference/anthropic/v1/messages?beta=true'
|
|
127
|
+
return '/inference/openai/v1/chat/completions'
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ── 会话身份 ────────────────────────────────────────────────────────────────
|
|
131
|
+
|
|
132
|
+
export const SESSION_RE = CANONICAL_SESSION_RE
|
|
133
|
+
export const SESSION_DESCENDING_RE = DESCENDING_TIME_RE
|
|
134
|
+
|
|
135
|
+
/** 该 id 是否为上游会照单接受的官方铸造形状。 */
|
|
136
|
+
export function isCanonicalSession(id) {
|
|
137
|
+
return typeof id === 'string' && SESSION_RE.test(id.trim()) && SESSION_DESCENDING_RE.test(id.trim().slice(4, 16))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** 任意会话信号 → 规范 session(官方 id 透传,其余按慢钟重铸)。 */
|
|
141
|
+
export function canonicalizeSession(signal) {
|
|
142
|
+
return canonicalSessionID(signal)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 保留的 session id 允许的相位龄。线上时间段是 36 位毫秒相位(约 795 天一个循环),
|
|
147
|
+
* 慢钟铸造的相位最老 30 天;60 天上限既让本车道铸的 id 长期复用,又能把早期
|
|
148
|
+
* 遗留的「哈希相位」旧 id 重铸掉(那些 id 一律答 429)。
|
|
149
|
+
*/
|
|
150
|
+
const SESSION_PLAUSIBILITY_MS = 60 * 24 * 60 * 60 * 1000
|
|
151
|
+
|
|
152
|
+
const SESSION_MAP_FILE = 'opencode-session-map.json'
|
|
153
|
+
let sessions
|
|
154
|
+
|
|
155
|
+
function sessionStorePath() {
|
|
156
|
+
try { return path.join(path.resolve(DATA_DIR), SESSION_MAP_FILE) } catch { return undefined }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function loadSessions() {
|
|
160
|
+
if (sessions !== undefined) return sessions
|
|
161
|
+
sessions = new Map()
|
|
162
|
+
try {
|
|
163
|
+
const file = sessionStorePath()
|
|
164
|
+
if (file === undefined) return sessions
|
|
165
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
166
|
+
for (const [seed, id] of Object.entries(parsed?.sessions ?? {})) {
|
|
167
|
+
if (typeof id === 'string' && SESSION_RE.test(id)) sessions.set(seed, id)
|
|
168
|
+
}
|
|
169
|
+
} catch { /* 首次运行或文件不可读:从空表开始 */ }
|
|
170
|
+
return sessions
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function rememberSession(seed, id) {
|
|
174
|
+
loadSessions().set(seed, id)
|
|
175
|
+
try {
|
|
176
|
+
const file = sessionStorePath()
|
|
177
|
+
if (file === undefined) return
|
|
178
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
179
|
+
const temp = `${file}.tmp`
|
|
180
|
+
writeAtomic(temp, JSON.stringify({ version: 2, at: Date.now(), sessions: Object.fromEntries(sessions) }, undefined, 2))
|
|
181
|
+
fs.renameSync(temp, file)
|
|
182
|
+
} catch { /* 非致命:id 仍然可用,只是重启后不保留 */ }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function writeAtomic(target, text) {
|
|
186
|
+
fs.writeFileSync(target, text, 'utf8')
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 保留的 session 内嵌相位是否仍在上游接受的窗口内。 */
|
|
190
|
+
function plausibleSession(id) {
|
|
191
|
+
const phase = sessionPhaseMs(id)
|
|
192
|
+
return phase !== null && phaseAgeMs(phase) < SESSION_PLAUSIBILITY_MS
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 一个下游会话 → 一个稳定上游 session:铸一次并持久化,重试/换模型都不轮转。
|
|
197
|
+
* 调用方给的规范 id 直接保留。
|
|
198
|
+
*/
|
|
199
|
+
export function sessionForConversation(sessionId) {
|
|
200
|
+
if (typeof sessionId === 'string' && isCanonicalSession(sessionId)) return sessionId.trim()
|
|
201
|
+
const seed = typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : 'global'
|
|
202
|
+
const remembered = loadSessions().get(seed)
|
|
203
|
+
if (remembered !== undefined && isCanonicalSession(remembered) && plausibleSession(remembered)) return remembered
|
|
204
|
+
const minted = canonicalizeSession(seed)
|
|
205
|
+
rememberSession(seed, minted)
|
|
206
|
+
return minted
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** 截断到上游接受的 session 长度。 */
|
|
210
|
+
export function truncateSession(value) {
|
|
211
|
+
if (typeof value !== 'string') return ''
|
|
212
|
+
const trimmed = value.trim()
|
|
213
|
+
return trimmed.length > MAX_SESSION_LENGTH ? trimmed.slice(0, MAX_SESSION_LENGTH) : trimmed
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** 一次性 project id(40 hex):调用方没命名项目时用,便于按请求摊配额。 */
|
|
217
|
+
export function randomProjectId() {
|
|
218
|
+
return randomProjectID()
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* 免密道的头集(v2 形状)。`session` 同时作为 project 信号传入 ⇒
|
|
223
|
+
* 同一会话的重试/续写/刷新共用一个配额桶。
|
|
224
|
+
*/
|
|
225
|
+
export function gatewayHeaders({ session, userAgent, anthropic = false, accept } = {}) {
|
|
226
|
+
const canonical = truncateSession(session)
|
|
227
|
+
const headers = o2aGatewayHeaders({
|
|
228
|
+
session: canonical,
|
|
229
|
+
project: canonical,
|
|
230
|
+
anthropic,
|
|
231
|
+
...(accept === undefined ? {} : { accept }),
|
|
232
|
+
})
|
|
233
|
+
if (typeof userAgent === 'string' && userAgent.trim() !== '') headers['user-agent'] = userAgent
|
|
234
|
+
return headers
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ── 请求体整形 ──────────────────────────────────────────────────────────────
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* 门禁校验的两个名字(v1 时代结论,v2 起闸门比对全量官方定义):
|
|
241
|
+
* 保留导出只为守卫测试与人工排障时一眼看出核心项。
|
|
242
|
+
*/
|
|
243
|
+
export const FINGERPRINT_TOOLS = ['read', 'shell']
|
|
244
|
+
|
|
245
|
+
function toolNameOf(tool) {
|
|
246
|
+
if (!tool || typeof tool !== 'object' || Array.isArray(tool)) return ''
|
|
247
|
+
if (typeof tool.name === 'string' && tool.name.trim()) return tool.name.trim()
|
|
248
|
+
const fn = tool.function
|
|
249
|
+
if (fn && typeof fn === 'object' && !Array.isArray(fn) && typeof fn.name === 'string') return fn.name.trim()
|
|
250
|
+
return ''
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** 该声明是否已带逐字官方定义(幂等整形的判据;按渲染后的官方项比对)。 */
|
|
254
|
+
function carriesOfficialDefinition(entry, name, shape) {
|
|
255
|
+
const own = definitionOf(entry, shape)
|
|
256
|
+
if (own === null) return false
|
|
257
|
+
const rendered = officialTool(shape, name)
|
|
258
|
+
const wrapper = shape === 'chat' ? rendered.function : rendered
|
|
259
|
+
if (!wrapper) return false
|
|
260
|
+
return own.description === wrapper.description
|
|
261
|
+
&& JSON.stringify(own.schema) === JSON.stringify(wrapper.parameters)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** 一条工具声明在某形状下的描述与参数 schema 位置。 */
|
|
265
|
+
function definitionOf(entry, shape) {
|
|
266
|
+
if (!entry || typeof entry !== 'object') return null
|
|
267
|
+
const wrapper = shape === 'chat' ? entry.function : entry
|
|
268
|
+
if (wrapper === null || wrapper === undefined || typeof wrapper !== 'object') return null
|
|
269
|
+
const schema = shape === 'claude' ? wrapper.input_schema : wrapper.parameters
|
|
270
|
+
return { description: wrapper.description, schema }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 注入的官方工具对本机调用方不可执行 —— 措辞是实测选出来的:
|
|
275
|
+
* 写成「不可用」会让模型连调用方自己的 `Read`/`Bash` 也一起拒绝;
|
|
276
|
+
* 「占位、请用别的工具」才既压住注入项、又不误伤调用方的工具。
|
|
277
|
+
*/
|
|
278
|
+
function placeholderNote(names) {
|
|
279
|
+
const list = names.map(name => `\`${name}\``).join(', ')
|
|
280
|
+
return `The tools ${list} are part of the host CLI's own toolset and are placeholders in this session; they do nothing here. Use the other tools you have been given instead.`
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** 只追加免费道上下文,绝不替换调用方的 system 文本或块对象。 */
|
|
284
|
+
function appendSystemContext(body, shape, note) {
|
|
285
|
+
if (shape === 'flat') {
|
|
286
|
+
body.instructions = typeof body.instructions === 'string' && body.instructions.trim() !== ''
|
|
287
|
+
? `${body.instructions}\n\n${note}`
|
|
288
|
+
: note
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
if (shape === 'claude') {
|
|
292
|
+
body.system = Array.isArray(body.system)
|
|
293
|
+
? [...body.system, { type: 'text', text: note }]
|
|
294
|
+
: typeof body.system === 'string' && body.system !== '' ? `${body.system}\n\n${note}` : note
|
|
295
|
+
return
|
|
296
|
+
}
|
|
297
|
+
const messages = Array.isArray(body.messages) ? body.messages : []
|
|
298
|
+
const first = messages[0]
|
|
299
|
+
if (first?.role === 'system' && typeof first.content === 'string') {
|
|
300
|
+
body.messages = [{ ...first, content: `${first.content}\n\n${note}` }, ...messages.slice(1)]
|
|
301
|
+
return
|
|
302
|
+
}
|
|
303
|
+
if (first?.role === 'system' && Array.isArray(first.content)) {
|
|
304
|
+
body.messages = [{ ...first, content: [...first.content, { type: 'text', text: note }] }, ...messages.slice(1)]
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
body.messages = [{ role: 'system', content: note }, ...messages]
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* 免费道把「无工具、1–3 轮、带标题标记」的请求体读作标题生成器
|
|
312
|
+
* (`title.IsTitleRequest`):给它挂上 agent 形状的工具清单
|
|
313
|
+
* 会换来 403/429。对这类请求体停止整形,本车道同做——
|
|
314
|
+
* 标题请求按调用方原样上线(不注入提示、不补工具、不改名)。
|
|
315
|
+
*/
|
|
316
|
+
const TITLE_MARKERS = /generate a title|write a title|create a title|come up with a title|title (?:for|of) (?:this|the) (?:conversation|chat|session|exchange|request)|conversation title|summarize (?:this|the) conversation/i
|
|
317
|
+
|
|
318
|
+
export function isTitleRequest(body, shape) {
|
|
319
|
+
if (!body || typeof body !== 'object') return false
|
|
320
|
+
if ((Array.isArray(body.tools) && body.tools.length > 0) || (Array.isArray(body.functions) && body.functions.length > 0)) return false
|
|
321
|
+
if (body.tool_choice !== undefined) return false
|
|
322
|
+
const textOf = value => typeof value === 'string' ? value
|
|
323
|
+
: Array.isArray(value) ? value.map(part => part?.text ?? '').join('\n') : ''
|
|
324
|
+
let turns
|
|
325
|
+
let leading = ''
|
|
326
|
+
if (shape === 'flat') {
|
|
327
|
+
turns = (Array.isArray(body.input) ? body.input : []).filter(item => item !== null && typeof item === 'object' && typeof item.role === 'string')
|
|
328
|
+
leading = textOf(body.instructions)
|
|
329
|
+
} else {
|
|
330
|
+
turns = (Array.isArray(body.messages) ? body.messages : []).filter(message => message !== null && typeof message === 'object')
|
|
331
|
+
leading = shape === 'claude' ? textOf(body.system) : ''
|
|
332
|
+
}
|
|
333
|
+
if (turns.length === 0 || turns.length > 3) return false
|
|
334
|
+
for (const turn of turns) {
|
|
335
|
+
if (!['user', 'system', 'developer'].includes(String(turn.role ?? ''))) return false
|
|
336
|
+
}
|
|
337
|
+
return TITLE_MARKERS.test(`${leading}\n${turns.map(turn => textOf(turn.content)).join('\n')}`)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* 满足免费道的 v2 客户端指纹(整形顺序固定):
|
|
342
|
+
*
|
|
343
|
+
* 1. 标题请求整类免整形;
|
|
344
|
+
* 2. 注入官方 CLI 系统提示(base + `<env>` + skills,按线注入,已带标记的跳过);
|
|
345
|
+
* 3. 调用方工具全部改名/绑定官方名 + 补齐官方 13 工具(逐字定义,幂等);
|
|
346
|
+
* 4. 注入项补「占位」提示;
|
|
347
|
+
* 5. 绝不下发 `tool_choice:'none'`;Responses 线无 choice 时补 `auto`;
|
|
348
|
+
* 6. Chat 线补 `stream_options.include_usage` 与 `max_completion_tokens` 上限。
|
|
349
|
+
*
|
|
350
|
+
* @param {object} body - 请求体(就地整形;调用方对象按 copy-on-write 替换)
|
|
351
|
+
* @param {'chat'|'flat'|'claude'} shape - 该请求体说的话
|
|
352
|
+
* @param {object} [options]
|
|
353
|
+
* @param {string} [options.model] - 提示 `<env>` 里报出的模型 id
|
|
354
|
+
* @param {string} [options.workDir] - 提示 `<env>` 里的工作目录
|
|
355
|
+
* @returns {ToolRenameMap} 线上名 → 调用方原名(响应侧还原用)
|
|
356
|
+
*/
|
|
357
|
+
export function applyFingerprint(body, shape, { model, workDir } = {}) {
|
|
358
|
+
if (!body || typeof body !== 'object') return new ToolRenameMap()
|
|
359
|
+
if (isTitleRequest(body, shape)) return new ToolRenameMap()
|
|
360
|
+
|
|
361
|
+
injectOfficialPrompt(body, shape, { workDir, model })
|
|
362
|
+
|
|
363
|
+
const tools = Array.isArray(body.tools) ? body.tools : []
|
|
364
|
+
const keep = new Set()
|
|
365
|
+
for (const tool of tools) {
|
|
366
|
+
const name = renamableToolName(shape, tool)
|
|
367
|
+
if (name !== null && carriesOfficialDefinition(tool, name, shape)) keep.add(name)
|
|
368
|
+
}
|
|
369
|
+
const { renames, injected } = renameAndCompleteTools(body, shape, { keep })
|
|
370
|
+
|
|
371
|
+
if (injected.length > 0) appendSystemContext(body, shape, placeholderNote(injected))
|
|
372
|
+
|
|
373
|
+
if (body.tool_choice === 'none'
|
|
374
|
+
|| (body.tool_choice !== null && typeof body.tool_choice === 'object' && body.tool_choice.type === 'none')) {
|
|
375
|
+
delete body.tool_choice
|
|
376
|
+
}
|
|
377
|
+
if (shape === 'flat' && !body.tool_choice) body.tool_choice = 'auto'
|
|
378
|
+
|
|
379
|
+
ensureChatUsage(body, shape)
|
|
380
|
+
ensureV2CompletionLimit(body, shape)
|
|
381
|
+
return renames
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** 把上游报回的工具名还原成调用方声明的名字(流式增量与最终负载都走这里)。 */
|
|
385
|
+
export function restoreToolName(name, map) {
|
|
386
|
+
if (!map) return name
|
|
387
|
+
if (typeof map.resolve === 'function') return map.resolve(name)
|
|
388
|
+
if (map.size === 0) return name
|
|
389
|
+
return map.get(name) ?? name
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 请求体声明的工具名集合(排障/守卫用)。 */
|
|
393
|
+
export function declaredToolNames(body) {
|
|
394
|
+
const names = new Set()
|
|
395
|
+
for (const tool of Array.isArray(body.tools) ? body.tools : []) {
|
|
396
|
+
const n = toolNameOf(tool)
|
|
397
|
+
if (n) names.add(n)
|
|
398
|
+
}
|
|
399
|
+
return names
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** 供离线守卫复用:整形用到的官方工具名集合。 */
|
|
403
|
+
export { V2_OFFICIAL_TOOL_ORDER } from './o2a/entry.js'
|