@linxin666/dsh-remote-bridge 0.4.7 → 0.4.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +2 -2
- package/README.md +93 -26
- package/README.zh.md +91 -26
- package/icon.svg +3 -0
- package/lib/client.js +274 -253
- package/lib/client.js.map +1 -1
- package/lib/index.js +8891 -2433
- package/lib/types/client/PairEntry.d.ts +2 -2
- package/lib/types/client/PairPanel.d.ts +10 -2
- package/lib/types/client/icons.d.ts +5 -13
- package/lib/types/client/locales.d.ts +10 -14
- package/lib/types/client/semantic.d.ts +9 -5
- package/lib/types/core/approvals.d.ts +24 -0
- package/lib/types/core/commands.d.ts +59 -0
- package/lib/types/core/connection.d.ts +124 -5
- package/lib/types/core/delta.d.ts +101 -0
- package/lib/types/core/devices.d.ts +98 -2
- package/lib/types/core/dsh-frames.d.ts +155 -4
- package/lib/types/core/envelope.d.ts +34 -0
- package/lib/types/core/extension.d.ts +144 -0
- package/lib/types/core/hub.d.ts +96 -20
- package/lib/types/core/jobs.d.ts +204 -0
- package/lib/types/core/liveactivity.d.ts +324 -0
- package/lib/types/core/protocol.d.ts +491 -2
- package/lib/types/core/push.d.ts +178 -0
- package/lib/types/core/questions.d.ts +109 -9
- package/lib/types/core/session-meta.d.ts +55 -1
- package/lib/types/core/squads.d.ts +130 -0
- package/lib/types/core/usage-stats.d.ts +160 -0
- package/lib/types/core/usage.d.ts +294 -0
- package/lib/types/core/wire.d.ts +1 -1
- package/lib/types/core/ws-frames.d.ts +11 -0
- package/lib/types/host/apns.d.ts +151 -0
- package/lib/types/host/squads-ledger.d.ts +39 -0
- package/lib/types/host/squads.d.ts +77 -0
- package/lib/types/host/usage-stats.d.ts +75 -0
- package/lib/types/host/watchers.d.ts +88 -0
- package/lib/types/host/websocket.d.ts +8 -1
- package/lib/types/index.d.ts +34 -3
- package/lib/types/mount-once.d.ts +55 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +20 -14
- package/src/client/PairEntry.tsx +58 -31
- package/src/client/PairPanel.tsx +181 -97
- package/src/client/icons.tsx +17 -60
- package/src/client/locales.ts +15 -23
- package/src/client/panel.module.css +239 -186
- package/src/client/semantic.ts +10 -6
- package/src/core/approvals.ts +32 -1
- package/src/core/commands.ts +95 -0
- package/src/core/connection.ts +1483 -31
- package/src/core/delta.ts +204 -0
- package/src/core/devices.ts +221 -3
- package/src/core/dsh-frames.ts +365 -8
- package/src/core/envelope.ts +46 -0
- package/src/core/extension.ts +197 -0
- package/src/core/hub.ts +441 -49
- package/src/core/jobs.ts +372 -0
- package/src/core/liveactivity.ts +833 -0
- package/src/core/protocol.ts +556 -2
- package/src/core/push.ts +354 -0
- package/src/core/questions.ts +264 -17
- package/src/core/session-meta.ts +73 -1
- package/src/core/squads.ts +345 -0
- package/src/core/usage-stats.ts +424 -0
- package/src/core/usage.ts +937 -0
- package/src/core/wire.ts +13 -1
- package/src/core/ws-frames.ts +14 -0
- package/src/host/apns.ts +320 -0
- package/src/host/squads-ledger.ts +105 -0
- package/src/host/squads.ts +206 -0
- package/src/host/usage-stats.ts +155 -0
- package/src/host/watchers.ts +272 -0
- package/src/host/websocket.ts +37 -3
- package/src/index.ts +310 -9
- package/src/mount-once.ts +142 -0
|
@@ -0,0 +1,937 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `usage.v1` 的两个读数:一条会话下一次请求由什么组成,以及某个 provider
|
|
3
|
+
* 路由背后账户的余额;外加 `usage.stats.v1` 那一份宿主台账的聚合(见
|
|
4
|
+
* `usage-stats.ts`,本模块只把它的读数转发出去)。
|
|
5
|
+
*
|
|
6
|
+
* 前两半都是「本进程自己的事实」,所以谁都不去打断会话,也不落盘:
|
|
7
|
+
*
|
|
8
|
+
* - 会话那一半折的是宿主经 `session/event` 广播给本进程的事件。上下文窗口
|
|
9
|
+
* 只有宿主真正广播过才有(最近一次 `request/context` 的 `contextWindow`),
|
|
10
|
+
* 组成由本桥按文本长度折算,因此 `composition` 恒带 `estimated: true`:它是
|
|
11
|
+
* 估算,永不冒充宿主读数。
|
|
12
|
+
* - 余额那一半只在路由确实指向官方 origin、且凭据确实拿得到时才发一次上游
|
|
13
|
+
* 请求。同一 provider + 凭据在 {@link BALANCE_CACHE_TTL_MS} 内最多一次,
|
|
14
|
+
* 并发调用合并成一次;401、超时与形状不符都回 `probe-failed`,绝不把上一
|
|
15
|
+
* 次的旧值当成新值发出去。
|
|
16
|
+
*
|
|
17
|
+
* 宿主服务一律走结构化 face:一个服务没挂载就少一档读数,而不是让整条方法
|
|
18
|
+
* 失败(`session-meta.ts` 与 `wire.ts` 都是同一套理由)。
|
|
19
|
+
*
|
|
20
|
+
* 会话那一半还有第三档读数:宿主从未广播过 `request/context` 窗口时,去问那条
|
|
21
|
+
* 路由的模型目录(`GET {baseURL}/models`),把模型自己声明的窗口填进
|
|
22
|
+
* `modelContextWindow`。两个键永不混用——`contextWindow` 恒为宿主实测,
|
|
23
|
+
* `modelContextWindow` 恒为模型声明,客户端据此能分辨该相信谁;宿主广播过窗口时
|
|
24
|
+
* 这一档根本不出现。
|
|
25
|
+
* @module dsh-remote-bridge/core/usage
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { failureText } from './gateway-errors.ts'
|
|
29
|
+
import { METHOD_USAGE_BALANCE, METHOD_USAGE_SESSION } from './protocol.ts'
|
|
30
|
+
import type { SessionStoreFace } from './session-meta.ts'
|
|
31
|
+
import { STATS_DAYS_DEFAULT, type UsageStatsAnswer, type UsageStatsReader } from './usage-stats.ts'
|
|
32
|
+
|
|
33
|
+
/** `usage.v1` 背后的两个方法:能力门按这一张表判定。 */
|
|
34
|
+
export const USAGE_METHODS: ReadonlySet<string> = new Set([METHOD_USAGE_SESSION, METHOD_USAGE_BALANCE])
|
|
35
|
+
|
|
36
|
+
/** 折算分母:一份 token 约合四个 UTF-8 字节。 */
|
|
37
|
+
export const BYTES_PER_TOKEN = 4
|
|
38
|
+
|
|
39
|
+
/** 会话折叠最多记住多少条会话,超出时丢最早的一条。 */
|
|
40
|
+
export const USAGE_SESSIONS_MAX = 512
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 宿主名册在本进程里的缓存窗口。
|
|
44
|
+
*
|
|
45
|
+
* 名册只在「活会话存储没有、事件折叠也没有」时才读,但一次开屏可能连着问几条,
|
|
46
|
+
* 所以同一个窗口内的多次存在性判定共用一次读取;窗口取得很短,是因为名册本身
|
|
47
|
+
* 会随新建会话变化。
|
|
48
|
+
*/
|
|
49
|
+
export const ROSTER_CACHE_TTL_MS = 5_000
|
|
50
|
+
|
|
51
|
+
/** 同一个 provider + 凭据在这个窗口内最多打一次上游。 */
|
|
52
|
+
export const BALANCE_CACHE_TTL_MS = 60_000
|
|
53
|
+
|
|
54
|
+
/** 一次上游探测的超时;超时与 401 一样是 `probe-failed`。 */
|
|
55
|
+
export const BALANCE_PROBE_TIMEOUT_MS = 10_000
|
|
56
|
+
|
|
57
|
+
/** 余额缓存最多记住多少个 provider + 凭据组合。 */
|
|
58
|
+
export const BALANCE_CACHE_LIMIT = 64
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 一条路由的模型目录在这个窗口内最多读一次。
|
|
62
|
+
*
|
|
63
|
+
* 目录里的窗口是模型自己声明的静态事实,不会因为一次请求而变化,所以这一档比
|
|
64
|
+
* 余额那一档长得多:10 分钟既跟得上用户改配置,也不会让每次 `usage.session`
|
|
65
|
+
* 都打一次上游。
|
|
66
|
+
*/
|
|
67
|
+
export const MODEL_WINDOW_CACHE_TTL_MS = 600_000
|
|
68
|
+
|
|
69
|
+
/** 一次模型目录探测的超时;超时与 404 一样是「这次没读到」。 */
|
|
70
|
+
export const MODEL_WINDOW_PROBE_TIMEOUT_MS = 5_000
|
|
71
|
+
|
|
72
|
+
/** 模型目录缓存最多记住多少条路由。 */
|
|
73
|
+
export const MODEL_WINDOW_CACHE_LIMIT = 32
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 官方 DeepSeek 的 API origin。
|
|
77
|
+
*
|
|
78
|
+
* 余额端点是按 origin 记账的:只有确实发往这里的路由才查得到官方账户的钱。
|
|
79
|
+
*/
|
|
80
|
+
export const DEEPSEEK_API_ORIGIN = 'https://api.deepseek.com'
|
|
81
|
+
|
|
82
|
+
/** 官方余额端点;金额单位为元,形如 `balance_infos:[{currency,total_balance,...}]`。 */
|
|
83
|
+
const DEEPSEEK_BALANCE_URL = `${DEEPSEEK_API_ORIGIN}/user/balance`
|
|
84
|
+
|
|
85
|
+
/** 官方余额适配认的 provider 路由 id,与 dsh-usage 的 deepseek adapter 同一份名单。 */
|
|
86
|
+
const DEEPSEEK_ROUTES: ReadonlySet<string> = new Set(['deepseek', 'deepseek-official'])
|
|
87
|
+
|
|
88
|
+
/** pi-ai 凭据记录的 scope:一条记录以 `<scope>/<id>` 寻址。 */
|
|
89
|
+
const PI_AI_CREDENTIAL_SCOPE = 'llm-pi-ai'
|
|
90
|
+
|
|
91
|
+
/** pi-ai 适配器的设置命名空间。 */
|
|
92
|
+
const PI_AI_SETTINGS_NS = 'llm-pi-ai'
|
|
93
|
+
|
|
94
|
+
/** 官方 DeepSeek 适配器的设置命名空间。 */
|
|
95
|
+
const DEEPSEEK_SETTINGS_NS = 'llm-deepseek'
|
|
96
|
+
|
|
97
|
+
/** 官方适配器没配 `apiKeyEnv` 时读的环境变量名。 */
|
|
98
|
+
const DEEPSEEK_API_KEY_ENV = 'DEEPSEEK_API_KEY'
|
|
99
|
+
|
|
100
|
+
/** UTF-8 编码器:宿主与浏览器两侧都是同一个实现,所以长度口径处处一致。 */
|
|
101
|
+
const encoder = new TextEncoder()
|
|
102
|
+
|
|
103
|
+
/** 一条会话事件里本模块读到的字段;结构化读取,不导入 SDK 的事件类型。 */
|
|
104
|
+
export interface UsageEventLike {
|
|
105
|
+
readonly type: string
|
|
106
|
+
readonly data?: unknown
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** 一条会话下一次请求的组成估算,单位 token,三格各自向下取整。 */
|
|
110
|
+
export interface UsageComposition {
|
|
111
|
+
/** system 消息文本折算出来的分量。 */
|
|
112
|
+
readonly system: number
|
|
113
|
+
/** 最近一次 `request/header` 的 tools schema 原文折算出来的分量。 */
|
|
114
|
+
readonly tools: number
|
|
115
|
+
/** 会话里已观察到的消息文本折算出来的分量。 */
|
|
116
|
+
readonly messages: number
|
|
117
|
+
/** 恒为 true:这是本桥的估算,宿主从未广播过这个数字。 */
|
|
118
|
+
readonly estimated: true
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** `usage.session` 的应答体;两项都取不到时是空对象。 */
|
|
122
|
+
export interface UsageSessionAnswer {
|
|
123
|
+
/** 宿主广播过的上下文窗口;没广播过就没有这个键。 */
|
|
124
|
+
readonly contextWindow?: number
|
|
125
|
+
/**
|
|
126
|
+
* 会话当前路由的模型目录声明的窗口;宿主广播过 `contextWindow` 时永不出现,
|
|
127
|
+
* 目录也取不到时同样不出现。
|
|
128
|
+
*
|
|
129
|
+
* 它与 {@link contextWindow} 是两个来源:那个是宿主实测,这个是模型声明。两者
|
|
130
|
+
* 不得混用,所以这个键的存在本身就说明「宿主没有实测值」。
|
|
131
|
+
*/
|
|
132
|
+
readonly modelContextWindow?: number
|
|
133
|
+
/** 组成估算;一项都没观察到时没有这个键。 */
|
|
134
|
+
readonly composition?: UsageComposition
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** `usage.balance` 支持不到的情况。 */
|
|
138
|
+
export type UsageUnsupported = 'no-credential' | 'not-deepseek-route' | 'probe-failed'
|
|
139
|
+
|
|
140
|
+
/** `usage.balance` 的应答体:要么是一次成功读数的四个金额,要么是为什么读不到。 */
|
|
141
|
+
export type UsageBalanceAnswer =
|
|
142
|
+
| {
|
|
143
|
+
readonly provider: string
|
|
144
|
+
readonly currency: string
|
|
145
|
+
readonly total: number
|
|
146
|
+
readonly toppedUp: number
|
|
147
|
+
readonly granted: number
|
|
148
|
+
readonly updatedAt: number
|
|
149
|
+
}
|
|
150
|
+
| {
|
|
151
|
+
readonly provider: string
|
|
152
|
+
readonly unsupported: UsageUnsupported
|
|
153
|
+
readonly reason?: string
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 一次成功读数里除 provider 与时间戳以外的四个字段。 */
|
|
157
|
+
interface ParsedBalance {
|
|
158
|
+
readonly currency: string
|
|
159
|
+
readonly total: number
|
|
160
|
+
readonly toppedUp: number
|
|
161
|
+
readonly granted: number
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 一条会话在本进程里攒下的读数。 */
|
|
165
|
+
interface SessionFacts {
|
|
166
|
+
/** 最近一次 `request/context` 广播的上下文窗口。 */
|
|
167
|
+
contextWindow?: number
|
|
168
|
+
/** 最近一次 `request/header` 的 tools schema 原文长度;undefined 表示还没广播过。 */
|
|
169
|
+
toolsBytes?: number
|
|
170
|
+
/** 最近一条 system 消息文本的长度;undefined 表示还没广播过。 */
|
|
171
|
+
systemBytes?: number
|
|
172
|
+
/** 已观察到的消息文本累计长度。 */
|
|
173
|
+
messagesBytes: number
|
|
174
|
+
/** 是否已经观察过任何一条消息事件。 */
|
|
175
|
+
sawMessages: boolean
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 会话事件的折叠:一条会话最近一次广播过的上下文窗口,以及它的组成原文长度。
|
|
180
|
+
*
|
|
181
|
+
* 只在事件里出现过的会话才有记录,所以「宿主没广播过」与「值恰好是 0」是
|
|
182
|
+
* 两件不同的事,应答里也就不会把没观察到的分量当成读数发出去。
|
|
183
|
+
*/
|
|
184
|
+
export class UsageTracker {
|
|
185
|
+
readonly #limit: number
|
|
186
|
+
readonly #facts = new Map<string, SessionFacts>()
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* @param limit - 最多记住多少条会话;默认 {@link USAGE_SESSIONS_MAX}。
|
|
190
|
+
*/
|
|
191
|
+
constructor(limit = USAGE_SESSIONS_MAX) {
|
|
192
|
+
this.#limit = limit
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 折进一条会话事件。
|
|
197
|
+
*
|
|
198
|
+
* 只认四类会改变读数的原文:`request/context` 的窗口、`request/header` 的
|
|
199
|
+
* tools schema、`system/message` 的 system 文本,以及 `user/message`、
|
|
200
|
+
* `assistant/message` 与 `tool/result` 的消息文本。其余事件一概不落记录,
|
|
201
|
+
* 所以一条只跑工具事件的会话不会凭空长出一条组成。
|
|
202
|
+
* @param sessionId - 事件所属会话。
|
|
203
|
+
* @param event - 宿主广播的事件。
|
|
204
|
+
*/
|
|
205
|
+
record(sessionId: string, event: UsageEventLike): void {
|
|
206
|
+
if (sessionId === '' || typeof event?.type !== 'string') return
|
|
207
|
+
const data = event.data
|
|
208
|
+
switch (event.type) {
|
|
209
|
+
case 'request/context': {
|
|
210
|
+
const window = contextWindowOf(data)
|
|
211
|
+
if (window === undefined) return
|
|
212
|
+
this.#factsFor(sessionId).contextWindow = window
|
|
213
|
+
return
|
|
214
|
+
}
|
|
215
|
+
case 'request/header': {
|
|
216
|
+
// header 到了就算观察过:一条不带 tools 的 header 是「这次请求没有
|
|
217
|
+
// 工具」,tools 分量因此是真实的 0,而不是没观察到。
|
|
218
|
+
const header = isRecord(data) ? data.header : undefined
|
|
219
|
+
if (!isRecord(header)) return
|
|
220
|
+
const tools = header.tools ?? []
|
|
221
|
+
this.#factsFor(sessionId).toolsBytes = utf8Bytes(JSON.stringify(tools) ?? '')
|
|
222
|
+
return
|
|
223
|
+
}
|
|
224
|
+
case 'system/message': {
|
|
225
|
+
// system 提示词是派生历史:最近一条 system 消息就是当前的提示词,
|
|
226
|
+
// 早先那条被替换掉的文本不该再算一遍。
|
|
227
|
+
this.#factsFor(sessionId).systemBytes = utf8Bytes(messageText(messageOf(data)))
|
|
228
|
+
return
|
|
229
|
+
}
|
|
230
|
+
case 'user/message':
|
|
231
|
+
case 'assistant/message':
|
|
232
|
+
case 'tool/result': {
|
|
233
|
+
const facts = this.#factsFor(sessionId)
|
|
234
|
+
facts.messagesBytes += utf8Bytes(messageText(messageOf(data)))
|
|
235
|
+
facts.sawMessages = true
|
|
236
|
+
return
|
|
237
|
+
}
|
|
238
|
+
default: return
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* 本进程是否观察过这条会话。
|
|
244
|
+
* @param sessionId - 会话 id。
|
|
245
|
+
* @returns 观察到过任何一条相关事件时为 true。
|
|
246
|
+
*/
|
|
247
|
+
known(sessionId: string): boolean {
|
|
248
|
+
return this.#facts.has(sessionId)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* 一条会话的读数,两项都取不到时是空对象。
|
|
253
|
+
*
|
|
254
|
+
* 空对象而不是 0:一个还没广播过窗口、也没观察到任何原文的会话,本桥对
|
|
255
|
+
* 它的组成一无所知,编一个 0 会把「不知道」说成「没有内容」。
|
|
256
|
+
* @param sessionId - 会话 id。
|
|
257
|
+
* @returns 应答体,字段按观察到的部分给出。
|
|
258
|
+
*/
|
|
259
|
+
answer(sessionId: string): UsageSessionAnswer {
|
|
260
|
+
const facts = this.#facts.get(sessionId)
|
|
261
|
+
const composition = facts === undefined ? undefined : compositionOf(facts)
|
|
262
|
+
if (facts?.contextWindow === undefined && composition === undefined) return {}
|
|
263
|
+
return {
|
|
264
|
+
...(facts?.contextWindow === undefined ? {} : { contextWindow: facts.contextWindow }),
|
|
265
|
+
...(composition === undefined ? {} : { composition }),
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** 取(必要时新建)一条会话的记录,并维持容量上界。 */
|
|
270
|
+
#factsFor(sessionId: string): SessionFacts {
|
|
271
|
+
const existing = this.#facts.get(sessionId)
|
|
272
|
+
if (existing !== undefined) return existing
|
|
273
|
+
const fresh: SessionFacts = { messagesBytes: 0, sawMessages: false }
|
|
274
|
+
this.#facts.set(sessionId, fresh)
|
|
275
|
+
while (this.#facts.size > this.#limit) {
|
|
276
|
+
const oldest = this.#facts.keys().next()
|
|
277
|
+
if (oldest.done === true) break
|
|
278
|
+
this.#facts.delete(oldest.value)
|
|
279
|
+
}
|
|
280
|
+
return fresh
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** 凭据服务的一角:pi-ai 记录与外部引用。 */
|
|
285
|
+
export interface CredentialStoreFace {
|
|
286
|
+
readRecord(key: string): Promise<{ readonly kind?: string; readonly key?: string } | undefined>
|
|
287
|
+
resolve(ref: string): Promise<{ readonly value?: string } | undefined>
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** 设置服务的一角:按命名空间读一段解析后的配置。 */
|
|
291
|
+
export interface SettingsFace {
|
|
292
|
+
get?(ns: string): unknown
|
|
293
|
+
describe?(options?: unknown): readonly { readonly ns?: string; readonly value?: unknown }[]
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 宿主自己的会话名册。
|
|
298
|
+
*
|
|
299
|
+
* 这是 `session.list` 服务的同一个来源,也就是手机名册的来源:它名下既有活的
|
|
300
|
+
* 会话,也有本进程没观察过、甚至当前不 live 的会话。活会话存储答不了这一问
|
|
301
|
+
* 的一半(`ctx.sessions.list()` 只列已进入存储的会话),所以名册单独一格。
|
|
302
|
+
*/
|
|
303
|
+
export interface SessionRosterFace {
|
|
304
|
+
/**
|
|
305
|
+
* 名册里的会话 id。
|
|
306
|
+
* @returns id 列表;读不到时回 undefined,调用方据此退回「不知道名册」。
|
|
307
|
+
*/
|
|
308
|
+
ids(): Promise<readonly string[] | undefined>
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** 一条会话此刻的路由:下一步要用哪个 provider 的哪个模型。 */
|
|
312
|
+
export interface SessionRouteFace {
|
|
313
|
+
/**
|
|
314
|
+
* 一条会话当前的路由。
|
|
315
|
+
*
|
|
316
|
+
* 与 `session.models` 的 `current` 同一个折叠:下一步的选择、其次是用过的
|
|
317
|
+
* 那个、最后才是目录默认——三者都不是本模块能自己推的,所以只转发。
|
|
318
|
+
* @param sessionId - 会话 id。
|
|
319
|
+
* @returns provider 与模型 id,或者 undefined 表示这条路由读不到。
|
|
320
|
+
*/
|
|
321
|
+
current(sessionId: string): Promise<{ readonly provider: string; readonly model: string } | undefined>
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** 本模块要读的宿主服务;每一个都可能不存在。 */
|
|
325
|
+
export interface UsageFaces {
|
|
326
|
+
/** 活会话的存储:`usage.session` 靠它区分「不存在」与「存在但没读数」。 */
|
|
327
|
+
readonly sessions?: SessionStoreFace | undefined
|
|
328
|
+
/** 宿主自己的会话名册:本进程没观察过的会话靠它证明自己存在。 */
|
|
329
|
+
readonly roster?: SessionRosterFace | undefined
|
|
330
|
+
/** 凭据服务:余额探测的密钥来源。 */
|
|
331
|
+
readonly credentials?: CredentialStoreFace | undefined
|
|
332
|
+
/** 设置服务:路由的 `apiKeyEnv` 与 `baseURL` 来源。 */
|
|
333
|
+
readonly settings?: SettingsFace | undefined
|
|
334
|
+
/** 会话此刻的路由:`modelContextWindow` 的来源。 */
|
|
335
|
+
readonly route?: SessionRouteFace | undefined
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** 上游探测用的 fetch 一角。 */
|
|
339
|
+
export type FetchFace = (
|
|
340
|
+
url: string,
|
|
341
|
+
init?: { readonly headers?: Record<string, string>; readonly signal?: AbortSignal },
|
|
342
|
+
) => Promise<{ readonly ok: boolean; readonly status: number; json(): Promise<unknown> }>
|
|
343
|
+
|
|
344
|
+
/** 构造 {@link UsageService} 的全部输入。 */
|
|
345
|
+
export interface UsageServiceOptions {
|
|
346
|
+
/** 每读一次宿主服务都重新解析一次,晚挂载的服务因此也能被读到。 */
|
|
347
|
+
readonly faces: () => UsageFaces
|
|
348
|
+
/** 缓存窗口与 `updatedAt` 读的时钟。 */
|
|
349
|
+
readonly now: () => number
|
|
350
|
+
/** 读不到宿主服务时的落点。 */
|
|
351
|
+
readonly log: (message: string) => void
|
|
352
|
+
/** 上游探测;默认用本进程的 `fetch`。 */
|
|
353
|
+
readonly fetch?: FetchFace
|
|
354
|
+
/** 余额缓存窗口;默认 {@link BALANCE_CACHE_TTL_MS}。 */
|
|
355
|
+
readonly ttlMs?: number
|
|
356
|
+
/** 一次探测的超时;默认 {@link BALANCE_PROBE_TIMEOUT_MS}。 */
|
|
357
|
+
readonly timeoutMs?: number
|
|
358
|
+
/** 模型目录探测的超时;默认 {@link MODEL_WINDOW_PROBE_TIMEOUT_MS}。 */
|
|
359
|
+
readonly modelTimeoutMs?: number
|
|
360
|
+
/** 宿主台账的聚合;没有它时 `usage.stats` 答 `probe-failed`。 */
|
|
361
|
+
readonly stats?: UsageStatsReader
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* `usage.v1` 的两条方法背后的读服务,一个宿主一份、所有连接共享。
|
|
366
|
+
*
|
|
367
|
+
* 会话读数是宿主的事实而不是某个设备的事实,余额是账户的事实,所以两半都
|
|
368
|
+
* 挂在宿主侧:一部手机重复问、两台手机同时问,都不该让上游多收一个请求。
|
|
369
|
+
*/
|
|
370
|
+
export class UsageService {
|
|
371
|
+
readonly #options: UsageServiceOptions
|
|
372
|
+
readonly #tracker = new UsageTracker()
|
|
373
|
+
readonly #cache = new Map<string, { readonly at: number; readonly answer: UsageBalanceAnswer }>()
|
|
374
|
+
readonly #inFlight = new Map<string, Promise<UsageBalanceAnswer>>()
|
|
375
|
+
/** 每条路由的模型目录(模型 id → 声明的窗口),以及它是哪一刻读的。 */
|
|
376
|
+
readonly #catalogs = new Map<string, { readonly at: number; readonly windows: ReadonlyMap<string, number> | undefined }>()
|
|
377
|
+
readonly #catalogInFlight = new Map<string, Promise<ReadonlyMap<string, number> | undefined>>()
|
|
378
|
+
/** 最近读到的一份宿主名册,以及它是哪一刻读的。 */
|
|
379
|
+
#roster: { readonly at: number; readonly ids: ReadonlySet<string> | undefined } | undefined
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* @param options - 宿主服务的解析函数、时钟与上游探测。
|
|
383
|
+
*/
|
|
384
|
+
constructor(options: UsageServiceOptions) {
|
|
385
|
+
this.#options = options
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* 折进一条宿主广播的会话事件。
|
|
390
|
+
*
|
|
391
|
+
* 没广播过的事件不会出现在任何应答里:本模块不读会话日志,也不回填历史,
|
|
392
|
+
* 所以一条在桥挂载前就结束的会话只有活会话存储能证明它存在。
|
|
393
|
+
* @param sessionId - 事件所属会话。
|
|
394
|
+
* @param event - 事件本身。
|
|
395
|
+
*/
|
|
396
|
+
record(sessionId: string, event: UsageEventLike): void {
|
|
397
|
+
this.#tracker.record(sessionId, event)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* 一条会话的上下文窗口与组成估算。
|
|
402
|
+
*
|
|
403
|
+
* 「不存在」与「存在但两项都取不到」是两个答案,而「存在」有三个证人:活会话
|
|
404
|
+
* 存储里有它、本进程观察过它的事件、或者宿主名册里有它。前两个是同步的,因此
|
|
405
|
+
* 只有两个都答不上来时才会去问名册——名册才是那条「本进程没观察过、当前也不
|
|
406
|
+
* live」的会话唯一的证据,把它说成不存在会变成一次假的失败。
|
|
407
|
+
*
|
|
408
|
+
* 名册也读不到时,证人只剩前两个:这时回 undefined 就是协议的
|
|
409
|
+
* `unknown-session`,与加名册之前逐字一样。
|
|
410
|
+
* @param sessionId - 会话 id。
|
|
411
|
+
* @returns 应答体,或者 undefined 表示这条会话不存在。
|
|
412
|
+
*/
|
|
413
|
+
async session(sessionId: string): Promise<UsageSessionAnswer | undefined> {
|
|
414
|
+
if (!this.#live(sessionId) && !this.#tracker.known(sessionId) && !(await this.#inRoster(sessionId))) return undefined
|
|
415
|
+
const answer = this.#tracker.answer(sessionId)
|
|
416
|
+
// 宿主实测优先,且永不混用:广播过窗口时这一档根本不出现,只有没实测值的
|
|
417
|
+
// 会话才去问模型目录。
|
|
418
|
+
if (answer.contextWindow !== undefined) return answer
|
|
419
|
+
const declared = await this.#modelContextWindow(sessionId)
|
|
420
|
+
return declared === undefined ? answer : { ...answer, modelContextWindow: declared }
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* 宿主自己那份按天记的 token 台账的聚合。
|
|
425
|
+
*
|
|
426
|
+
* 缓存、合并与「读到/没读到」的区分都在 `usage-stats.ts`:那是对另一个插件的
|
|
427
|
+
* HTTP 路由的读数,与本节两半的「本进程自己的事实」不是同一类东西,因此单独
|
|
428
|
+
* 一格。本方法只转发。
|
|
429
|
+
* @param days - 要多少天;省略按 {@link STATS_DAYS_DEFAULT}。
|
|
430
|
+
* @returns 台账聚合,或者为什么读不到。
|
|
431
|
+
*/
|
|
432
|
+
async stats(days?: number): Promise<UsageStatsAnswer> {
|
|
433
|
+
const reader = this.#options.stats
|
|
434
|
+
if (reader === undefined) return { unsupported: 'probe-failed', reason: 'no host usage route' }
|
|
435
|
+
return await reader.stats(days ?? STATS_DAYS_DEFAULT)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* 一条 provider 路由背后账户的余额,DeepSeek 官方口径。
|
|
440
|
+
*
|
|
441
|
+
* 判定的顺序就是省下上游请求的顺序:不是官方路由的 id 不查,指向别的
|
|
442
|
+
* origin 的路由不查,拿不到凭据不查;只有三关都过了才谈得上缓存与探测。
|
|
443
|
+
* @param provider - 客户端给的 provider 路由 id。
|
|
444
|
+
* @returns 余额,或者为什么读不到。
|
|
445
|
+
*/
|
|
446
|
+
async balance(provider: string): Promise<UsageBalanceAnswer> {
|
|
447
|
+
if (!DEEPSEEK_ROUTES.has(provider)) return { provider, unsupported: 'not-deepseek-route' }
|
|
448
|
+
const faces = this.#faces()
|
|
449
|
+
if (!officialRoute(provider, faces.settings)) return { provider, unsupported: 'not-deepseek-route' }
|
|
450
|
+
const credential = await this.#credentialOf(provider, faces)
|
|
451
|
+
if (credential === undefined) return { provider, unsupported: 'no-credential' }
|
|
452
|
+
// 缓存键带上凭据指纹:换一把 key 就是另一个账户,不能被上一把的读数冒充。
|
|
453
|
+
const cacheKey = `${provider}\u0000${fingerprint(credential)}`
|
|
454
|
+
const cached = this.#cache.get(cacheKey)
|
|
455
|
+
if (cached !== undefined && this.#options.now() - cached.at < this.#ttl()) return cached.answer
|
|
456
|
+
const running = this.#inFlight.get(cacheKey)
|
|
457
|
+
if (running !== undefined) return await running
|
|
458
|
+
const settle = (answer: UsageBalanceAnswer): UsageBalanceAnswer => {
|
|
459
|
+
this.#remember(cacheKey, answer)
|
|
460
|
+
this.#inFlight.delete(cacheKey)
|
|
461
|
+
return answer
|
|
462
|
+
}
|
|
463
|
+
const probe = this.#probe(provider, credential)
|
|
464
|
+
.then(settle, (error: unknown) => settle({ provider, unsupported: 'probe-failed', reason: failureText(error) }))
|
|
465
|
+
this.#inFlight.set(cacheKey, probe)
|
|
466
|
+
return await probe
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** 宿主服务的一次解析;解析本身抛错按「什么都没挂载」处理。 */
|
|
470
|
+
#faces(): UsageFaces {
|
|
471
|
+
try {
|
|
472
|
+
return this.#options.faces()
|
|
473
|
+
} catch (error) {
|
|
474
|
+
this.#options.log(`the usage faces could not be resolved: ${failureText(error)}`)
|
|
475
|
+
return {}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** 宿主名册里是否有这条会话;没有名册或读不到都按「不知道」处理。 */
|
|
480
|
+
async #inRoster(sessionId: string): Promise<boolean> {
|
|
481
|
+
return (await this.#rosterIds())?.has(sessionId) === true
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* 一个缓存窗口内的宿主名册。
|
|
486
|
+
*
|
|
487
|
+
* 一次开屏可能连着问几条会话,所以同一窗口内的判定共用一次读取;读失败(或
|
|
488
|
+
* 本进程根本没有名册来源)缓存的是 undefined,也就是「不知道名册」,判定因此
|
|
489
|
+
* 退回活会话存储与事件折叠两条证词。
|
|
490
|
+
*/
|
|
491
|
+
async #rosterIds(): Promise<ReadonlySet<string> | undefined> {
|
|
492
|
+
const now = this.#options.now()
|
|
493
|
+
if (this.#roster !== undefined && now - this.#roster.at < ROSTER_CACHE_TTL_MS) return this.#roster.ids
|
|
494
|
+
let ids: ReadonlySet<string> | undefined
|
|
495
|
+
try {
|
|
496
|
+
const read = this.#faces().roster?.ids
|
|
497
|
+
const listed = read === undefined ? undefined : await read()
|
|
498
|
+
ids = listed === undefined ? undefined : new Set(listed)
|
|
499
|
+
} catch (error) {
|
|
500
|
+
this.#options.log(`the host session roster could not be read: ${failureText(error)}`)
|
|
501
|
+
ids = undefined
|
|
502
|
+
}
|
|
503
|
+
this.#roster = { at: this.#options.now(), ids }
|
|
504
|
+
return ids
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** 活会话存储里是否有这条会话;读不到就按没有处理。 */
|
|
508
|
+
#live(sessionId: string): boolean {
|
|
509
|
+
try {
|
|
510
|
+
return this.#faces().sessions?.get(sessionId) !== undefined
|
|
511
|
+
} catch (error) {
|
|
512
|
+
this.#options.log(`the live session "${sessionId}" could not be read: ${failureText(error)}`)
|
|
513
|
+
return false
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* 这条路由这一次要用的密钥:pi-ai 的凭据记录,然后 profile 的
|
|
519
|
+
* `apiKeyEnv`,最后官方适配器自己的环境变量引用。
|
|
520
|
+
*
|
|
521
|
+
* 记录里的 OAuth grant 不算凭据:官方余额端点只认 API key,一个 grant 拿
|
|
522
|
+
* 过去只会换来 401,所以这里直接落到环境变量这一档。
|
|
523
|
+
*/
|
|
524
|
+
async #credentialOf(provider: string, faces: UsageFaces): Promise<string | undefined> {
|
|
525
|
+
const store = faces.credentials
|
|
526
|
+
if (store === undefined) return undefined
|
|
527
|
+
try {
|
|
528
|
+
const record = await store.readRecord(`${PI_AI_CREDENTIAL_SCOPE}/${provider}`)
|
|
529
|
+
if (record?.kind === 'api-key' && typeof record.key === 'string' && record.key !== '') return record.key
|
|
530
|
+
} catch (error) {
|
|
531
|
+
// 读写不了的记录按不存在处理:下一档是环境变量,那里还有一次机会。
|
|
532
|
+
this.#options.log(`the pi-ai credential of route "${provider}" could not be read: ${failureText(error)}`)
|
|
533
|
+
}
|
|
534
|
+
const name = nonEmptyText(profileOf(faces.settings, provider)?.apiKeyEnv) ?? deepseekApiKeyEnv(faces.settings)
|
|
535
|
+
try {
|
|
536
|
+
const resolved = await store.resolve(name)
|
|
537
|
+
if (typeof resolved?.value === 'string' && resolved.value !== '') return resolved.value
|
|
538
|
+
} catch (error) {
|
|
539
|
+
this.#options.log(`the credential reference "${name}" of route "${provider}" could not be resolved: ${failureText(error)}`)
|
|
540
|
+
}
|
|
541
|
+
return undefined
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* 对官方余额端点做一次探测。
|
|
546
|
+
*
|
|
547
|
+
* 失败一律折成 `probe-failed` 并带上一条短原因:401、超时与形状不符都是
|
|
548
|
+
* 「这次没读到」,任何一条都不会拿上一轮的旧值顶上。
|
|
549
|
+
*/
|
|
550
|
+
async #probe(provider: string, credential: string): Promise<UsageBalanceAnswer> {
|
|
551
|
+
const call = this.#options.fetch ?? defaultFetch
|
|
552
|
+
try {
|
|
553
|
+
const response = await call(DEEPSEEK_BALANCE_URL, {
|
|
554
|
+
headers: { authorization: `Bearer ${credential}` },
|
|
555
|
+
signal: AbortSignal.timeout(this.#timeout()),
|
|
556
|
+
})
|
|
557
|
+
if (!response.ok) return { provider, unsupported: 'probe-failed', reason: `HTTP ${response.status}` }
|
|
558
|
+
const body: unknown = await response.json().catch(() => undefined)
|
|
559
|
+
const balance = parsedBalance(body)
|
|
560
|
+
if (balance === undefined) return { provider, unsupported: 'probe-failed', reason: 'unrecognized response shape' }
|
|
561
|
+
return { provider, ...balance, updatedAt: this.#options.now() }
|
|
562
|
+
} catch (error) {
|
|
563
|
+
return { provider, unsupported: 'probe-failed', reason: failureText(error) }
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* 一条会话当前路由的模型声明的上下文窗口。
|
|
569
|
+
*
|
|
570
|
+
* 三关都不打上游请求的顺序:读不到路由不查、路由没有可寻址的 base URL 不查、
|
|
571
|
+
* 目录里没有这个模型就不出现这个键。目录按路由缓存 {@link MODEL_WINDOW_CACHE_TTL_MS},
|
|
572
|
+
* 读失败也缓存同一窗口——窗口是模型自己声明的静态事实,重试改变不了答案,而每次
|
|
573
|
+
* `usage.session` 都去打一次上游只会把这条路走成噪声。
|
|
574
|
+
* @param sessionId - 会话 id。
|
|
575
|
+
* @returns 模型声明的窗口,或者 undefined 表示这一档取不到。
|
|
576
|
+
*/
|
|
577
|
+
async #modelContextWindow(sessionId: string): Promise<number | undefined> {
|
|
578
|
+
const faces = this.#faces()
|
|
579
|
+
const route = faces.route
|
|
580
|
+
if (route === undefined) return undefined
|
|
581
|
+
let selection: { readonly provider: string; readonly model: string } | undefined
|
|
582
|
+
try {
|
|
583
|
+
selection = await route.current(sessionId)
|
|
584
|
+
} catch (error) {
|
|
585
|
+
this.#options.log(`the route of session "${sessionId}" could not be read: ${failureText(error)}`)
|
|
586
|
+
return undefined
|
|
587
|
+
}
|
|
588
|
+
if (selection === undefined) return undefined
|
|
589
|
+
const baseURL = catalogBaseUrl(selection.provider, faces.settings)
|
|
590
|
+
if (baseURL === undefined) return undefined
|
|
591
|
+
const windows = await this.#catalogOf(`${selection.provider}\u0000${baseURL}`, baseURL, selection.provider, faces)
|
|
592
|
+
return windows?.get(selection.model)
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* 一条路由的模型目录,按窗口缓存并合并并发读。
|
|
597
|
+
* @param key - provider + baseURL 的缓存键。
|
|
598
|
+
* @param baseURL - 目录的地址(已去掉结尾斜杠)。
|
|
599
|
+
* @param provider - 这条目录属于哪个 provider 路由,取凭据用。
|
|
600
|
+
* @param faces - 这一次的宿主服务。
|
|
601
|
+
* @returns 模型 id → 声明的窗口;取不到时 undefined。
|
|
602
|
+
*/
|
|
603
|
+
async #catalogOf(key: string, baseURL: string, provider: string, faces: UsageFaces): Promise<ReadonlyMap<string, number> | undefined> {
|
|
604
|
+
const cached = this.#catalogs.get(key)
|
|
605
|
+
if (cached !== undefined && this.#options.now() - cached.at < MODEL_WINDOW_CACHE_TTL_MS) return cached.windows
|
|
606
|
+
const running = this.#catalogInFlight.get(key)
|
|
607
|
+
if (running !== undefined) return await running
|
|
608
|
+
const settle = (windows: ReadonlyMap<string, number> | undefined): ReadonlyMap<string, number> | undefined => {
|
|
609
|
+
this.#rememberCatalog(key, windows)
|
|
610
|
+
this.#catalogInFlight.delete(key)
|
|
611
|
+
return windows
|
|
612
|
+
}
|
|
613
|
+
const read = this.#readCatalog(baseURL, provider, faces).then(settle, () => settle(undefined))
|
|
614
|
+
this.#catalogInFlight.set(key, read)
|
|
615
|
+
return await read
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* 读一次 `GET {baseURL}/models`。
|
|
620
|
+
*
|
|
621
|
+
* 凭据与账本同源(pi-ai 记录,然后 `apiKeyEnv`):请求发往这条路由**自己的**
|
|
622
|
+
* origin,所以不需要余额那一档的官方 origin 判定——这里问的是这条路由自己声明的
|
|
623
|
+
* 事实。拿不到凭据也照发,某些自建端点不鉴权;失败一律 undefined。
|
|
624
|
+
* @param baseURL - 目录的地址(已去掉结尾斜杠)。
|
|
625
|
+
* @param provider - 这条目录属于哪个 provider 路由。
|
|
626
|
+
* @param faces - 这一次的宿主服务。
|
|
627
|
+
* @returns 模型 id → 声明的窗口;取不到时 undefined。
|
|
628
|
+
*/
|
|
629
|
+
async #readCatalog(baseURL: string, provider: string, faces: UsageFaces): Promise<ReadonlyMap<string, number> | undefined> {
|
|
630
|
+
const call = this.#options.fetch ?? defaultFetch
|
|
631
|
+
const headers: Record<string, string> = { accept: 'application/json' }
|
|
632
|
+
const credential = await this.#credentialOf(provider, faces)
|
|
633
|
+
if (credential !== undefined) headers.authorization = `Bearer ${credential}`
|
|
634
|
+
try {
|
|
635
|
+
const response = await call(`${baseURL}/models`, {
|
|
636
|
+
headers,
|
|
637
|
+
signal: AbortSignal.timeout(this.#modelTimeout()),
|
|
638
|
+
})
|
|
639
|
+
if (!response.ok) return undefined
|
|
640
|
+
const body: unknown = await response.json().catch(() => undefined)
|
|
641
|
+
return catalogWindowsOf(body)
|
|
642
|
+
} catch (error) {
|
|
643
|
+
this.#options.log(`the model catalog of route "${provider}" could not be read: ${failureText(error)}`)
|
|
644
|
+
return undefined
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/** 记一条路由的目录(读到与没读到都记)并维持容量上界。 */
|
|
649
|
+
#rememberCatalog(key: string, windows: ReadonlyMap<string, number> | undefined): void {
|
|
650
|
+
this.#catalogs.delete(key)
|
|
651
|
+
this.#catalogs.set(key, { at: this.#options.now(), windows })
|
|
652
|
+
while (this.#catalogs.size > MODEL_WINDOW_CACHE_LIMIT) {
|
|
653
|
+
const oldest = this.#catalogs.keys().next()
|
|
654
|
+
if (oldest.done === true) return
|
|
655
|
+
this.#catalogs.delete(oldest.value)
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** 一次模型目录探测的超时。 */
|
|
660
|
+
#modelTimeout(): number {
|
|
661
|
+
return this.#options.modelTimeoutMs ?? MODEL_WINDOW_PROBE_TIMEOUT_MS
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/** 记一次读数(成功与失败都记)并维持容量上界。 */
|
|
665
|
+
#remember(cacheKey: string, answer: UsageBalanceAnswer): void {
|
|
666
|
+
this.#cache.delete(cacheKey)
|
|
667
|
+
this.#cache.set(cacheKey, { at: this.#options.now(), answer })
|
|
668
|
+
while (this.#cache.size > BALANCE_CACHE_LIMIT) {
|
|
669
|
+
const oldest = this.#cache.keys().next()
|
|
670
|
+
if (oldest.done === true) return
|
|
671
|
+
this.#cache.delete(oldest.value)
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/** 余额缓存窗口。 */
|
|
676
|
+
#ttl(): number {
|
|
677
|
+
return this.#options.ttlMs ?? BALANCE_CACHE_TTL_MS
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** 一次探测的超时。 */
|
|
681
|
+
#timeout(): number {
|
|
682
|
+
return this.#options.timeoutMs ?? BALANCE_PROBE_TIMEOUT_MS
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** 默认的探测实现:宿主与浏览器两侧都有全局 fetch。 */
|
|
687
|
+
const defaultFetch: FetchFace = (url, init) => globalThis.fetch(url, init)
|
|
688
|
+
|
|
689
|
+
/** 一条记录的长度:UTF-8 字节数,汉字因此按实际字节计。 */
|
|
690
|
+
function utf8Bytes(text: string): number {
|
|
691
|
+
return text === '' ? 0 : encoder.encode(text).length
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* 字节数折算成 token:四字节一份,向下取整。
|
|
696
|
+
*
|
|
697
|
+
* 向下而不是四舍五入,是因为一个空数组序列化成 `[]` 也有两个字节,四舍五入会
|
|
698
|
+
* 把一个「这次请求没有工具」的 header 说成占了一份 token。
|
|
699
|
+
*/
|
|
700
|
+
function tokensOf(bytes: number): number {
|
|
701
|
+
return Math.floor(bytes / BYTES_PER_TOKEN)
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/** 一条会话的组成估算;一项都没观察到时没有这个读数。 */
|
|
705
|
+
function compositionOf(facts: SessionFacts): UsageComposition | undefined {
|
|
706
|
+
if (facts.toolsBytes === undefined && facts.systemBytes === undefined && !facts.sawMessages) return undefined
|
|
707
|
+
return {
|
|
708
|
+
system: tokensOf(facts.systemBytes ?? 0),
|
|
709
|
+
tools: tokensOf(facts.toolsBytes ?? 0),
|
|
710
|
+
messages: tokensOf(facts.messagesBytes),
|
|
711
|
+
estimated: true,
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/** `request/context` 里可用的上下文窗口:非负有限整数才有意义。 */
|
|
716
|
+
function contextWindowOf(data: unknown): number | undefined {
|
|
717
|
+
if (!isRecord(data)) return undefined
|
|
718
|
+
const window = data.contextWindow
|
|
719
|
+
return typeof window === 'number' && Number.isInteger(window) && window > 0 ? window : undefined
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** 事件里的消息对象:`system/message` 与 `assistant/message` 包在 `message` 里,`user/message` 就是它本身。 */
|
|
723
|
+
function messageOf(data: unknown): unknown {
|
|
724
|
+
return isRecord(data) && isRecord(data.message) ? data.message : data
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* 一条消息的模型可见文本。
|
|
729
|
+
*
|
|
730
|
+
* 取的是每个内容块自己的 `text`(工具调用块则是它的 `arguments` 原文):这两样
|
|
731
|
+
* 是一次请求里真正占 token 的部分,而消息 id、来源记录与流式记录都不占。
|
|
732
|
+
*/
|
|
733
|
+
function messageText(message: unknown): string {
|
|
734
|
+
const content = isRecord(message) ? message.content : undefined
|
|
735
|
+
if (!Array.isArray(content)) return ''
|
|
736
|
+
let text = ''
|
|
737
|
+
for (const block of content) {
|
|
738
|
+
if (typeof block === 'string') {
|
|
739
|
+
text += block
|
|
740
|
+
continue
|
|
741
|
+
}
|
|
742
|
+
if (!isRecord(block)) continue
|
|
743
|
+
if (typeof block.text === 'string') {
|
|
744
|
+
text += block.text
|
|
745
|
+
continue
|
|
746
|
+
}
|
|
747
|
+
if (typeof block.arguments === 'string') text += block.arguments
|
|
748
|
+
}
|
|
749
|
+
return text
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* 这条路由的请求是否确实发往官方 origin。
|
|
754
|
+
*
|
|
755
|
+
* 余额端点是按 origin 记账而不是按路由 id:一个共用 `deepseek` 这个 id 的
|
|
756
|
+
* 转售 profile 只改 `baseURL`,拿官方 key 去打官方端点会把官方账户的钱印在
|
|
757
|
+
* 它的名下(串号事故)。配了别的 origin 就回 `not-deepseek-route`;没配
|
|
758
|
+
* origin 的路由用的就是适配器自己的固定端点,也就是官方 origin。
|
|
759
|
+
*/
|
|
760
|
+
function officialRoute(provider: string, settings: SettingsFace | undefined): boolean {
|
|
761
|
+
const configured = originOf(nonEmptyText(profileOf(settings, provider)?.baseURL) ?? deepseekBaseUrl(settings))
|
|
762
|
+
return configured === undefined || configured === DEEPSEEK_API_ORIGIN
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* 一条路由的模型目录地址。
|
|
767
|
+
*
|
|
768
|
+
* 目录挂在路由自己的 base URL 下,所以这里读的是那同一段配置:pi-ai profile 的
|
|
769
|
+
* `baseURL`,其次(官方适配器那几条路由)`llm-deepseek` 的 `baseURL`,都没有时
|
|
770
|
+
* 回官方 origin。别家路由没配 `baseURL` 时回 undefined——适配器自己的默认端点不在
|
|
771
|
+
* 本包的视野里,猜一个只会打到一个不存在的主机上。
|
|
772
|
+
* @param provider - provider 路由 id。
|
|
773
|
+
* @param settings - 设置服务,可能没挂载。
|
|
774
|
+
* @returns 去掉结尾斜杠的 base URL,或者 undefined。
|
|
775
|
+
*/
|
|
776
|
+
function catalogBaseUrl(provider: string, settings: SettingsFace | undefined): string | undefined {
|
|
777
|
+
const configured = nonEmptyText(profileOf(settings, provider)?.baseURL)
|
|
778
|
+
?? (DEEPSEEK_ROUTES.has(provider) ? deepseekBaseUrl(settings) : undefined)
|
|
779
|
+
const base = configured ?? (DEEPSEEK_ROUTES.has(provider) ? DEEPSEEK_API_ORIGIN : undefined)
|
|
780
|
+
if (base === undefined) return undefined
|
|
781
|
+
const trimmed = base.trim().replace(/\/+$/, '')
|
|
782
|
+
return trimmed === '' ? undefined : trimmed
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* 一份 OpenAI 兼容的 `/models` 应答里,每个模型声明的上下文窗口。
|
|
787
|
+
*
|
|
788
|
+
* 三个字段名按顺序取第一个可用值(`context_length`、`context_window`、
|
|
789
|
+
* `max_input_tokens`):不同网关各写各的,而它们说的是同一件事。一个都没有的模型
|
|
790
|
+
* 不进表,所以「目录里没写」与「写了个 0」是两件事,前者不会变成后者的读数。
|
|
791
|
+
* @param body - `GET {baseURL}/models` 的应答体。
|
|
792
|
+
* @returns 模型 id → 窗口;形状不符时 undefined。
|
|
793
|
+
*/
|
|
794
|
+
function catalogWindowsOf(body: unknown): ReadonlyMap<string, number> | undefined {
|
|
795
|
+
const listed = Array.isArray(body)
|
|
796
|
+
? body
|
|
797
|
+
: isRecord(body) && Array.isArray(body.data) ? body.data : undefined
|
|
798
|
+
if (listed === undefined) return undefined
|
|
799
|
+
const windows = new Map<string, number>()
|
|
800
|
+
for (const entry of listed) {
|
|
801
|
+
if (!isRecord(entry)) continue
|
|
802
|
+
const id = nonEmptyText(entry.id)
|
|
803
|
+
const window = declaredWindowOf(entry)
|
|
804
|
+
if (id === undefined || window === undefined) continue
|
|
805
|
+
windows.set(id, window)
|
|
806
|
+
}
|
|
807
|
+
return windows
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/** 一个模型条目自己声明的窗口:三个字段名里第一个可用值。 */
|
|
811
|
+
function declaredWindowOf(entry: Record<string, unknown>): number | undefined {
|
|
812
|
+
for (const name of ['context_length', 'context_window', 'max_input_tokens'] as const) {
|
|
813
|
+
const value = entry[name]
|
|
814
|
+
if (typeof value === 'number' && Number.isInteger(value) && value > 0) return value
|
|
815
|
+
}
|
|
816
|
+
return undefined
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/** 一个 base URL 的 origin;空值或解析不了的 URL 都回 undefined。 */
|
|
820
|
+
function originOf(baseURL: string | undefined): string | undefined {
|
|
821
|
+
if (baseURL === undefined || baseURL.trim() === '') return undefined
|
|
822
|
+
try {
|
|
823
|
+
return new URL(baseURL).origin
|
|
824
|
+
} catch {
|
|
825
|
+
return undefined
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** pi-ai profile 里这条路由的对象。 */
|
|
830
|
+
function profileOf(settings: SettingsFace | undefined, provider: string): Record<string, unknown> | undefined {
|
|
831
|
+
const section = settingsSection(settings, PI_AI_SETTINGS_NS)
|
|
832
|
+
if (!isRecord(section) || !isRecord(section.providers)) return undefined
|
|
833
|
+
const profile = section.providers[provider]
|
|
834
|
+
return isRecord(profile) ? profile : undefined
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/** 官方适配器这一档要读的环境变量引用。 */
|
|
838
|
+
function deepseekApiKeyEnv(settings: SettingsFace | undefined): string {
|
|
839
|
+
const section = settingsSection(settings, DEEPSEEK_SETTINGS_NS)
|
|
840
|
+
return (isRecord(section) ? nonEmptyText(section.apiKeyEnv) : undefined) ?? DEEPSEEK_API_KEY_ENV
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** 官方适配器自己配的 base URL。 */
|
|
844
|
+
function deepseekBaseUrl(settings: SettingsFace | undefined): string | undefined {
|
|
845
|
+
const section = settingsSection(settings, DEEPSEEK_SETTINGS_NS)
|
|
846
|
+
return isRecord(section) ? nonEmptyText(section.baseURL) : undefined
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* 读一段设置命名空间。
|
|
851
|
+
*
|
|
852
|
+
* 先问 `get`,再问 `describe`:设置服务换过读取入口,两者在宿主上都是「这一段
|
|
853
|
+
* 现在解析成什么」。读不到、抛错或根本没有设置服务,一律按「没有这段配置」,
|
|
854
|
+
* 于是 origin 判定与凭据回退都退回官方默认值。
|
|
855
|
+
*/
|
|
856
|
+
function settingsSection(settings: SettingsFace | undefined, ns: string): unknown {
|
|
857
|
+
if (settings === undefined) return undefined
|
|
858
|
+
try {
|
|
859
|
+
if (typeof settings.get === 'function') {
|
|
860
|
+
const value = settings.get(ns)
|
|
861
|
+
if (value !== undefined) return unwrap(value)
|
|
862
|
+
}
|
|
863
|
+
if (typeof settings.describe === 'function') {
|
|
864
|
+
const descriptors = settings.describe({ redactSecrets: false })
|
|
865
|
+
if (Array.isArray(descriptors)) {
|
|
866
|
+
const match = descriptors.find(entry => isRecord(entry) && entry.ns === ns)
|
|
867
|
+
if (match !== undefined) return unwrap(match.value)
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
} catch {
|
|
871
|
+
// 一段读不出来的配置按缺席处理:每次调用都记一行日志只会淹没真正的事件。
|
|
872
|
+
}
|
|
873
|
+
return undefined
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/** 解开设置服务包在读数值外面的 volatile getter。 */
|
|
877
|
+
function unwrap(value: unknown): unknown {
|
|
878
|
+
let current = value
|
|
879
|
+
for (let depth = 0; depth < 4; depth += 1) {
|
|
880
|
+
if (!isRecord(current) || typeof current.get !== 'function') break
|
|
881
|
+
current = (current as { get(): unknown }).get()
|
|
882
|
+
}
|
|
883
|
+
return current
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/**
|
|
887
|
+
* 官方 `/user/balance` 应答体里本协议要的四个数。
|
|
888
|
+
*
|
|
889
|
+
* 缺一个都算形状不符:只读到总额却把赠金与充值额编成 0,等于把「这次没读到」
|
|
890
|
+
* 说成「账户里没有」。
|
|
891
|
+
*/
|
|
892
|
+
function parsedBalance(body: unknown): ParsedBalance | undefined {
|
|
893
|
+
if (!isRecord(body)) return undefined
|
|
894
|
+
const infos = body.balance_infos
|
|
895
|
+
if (!Array.isArray(infos) || infos.length === 0) return undefined
|
|
896
|
+
const first = infos[0]
|
|
897
|
+
if (!isRecord(first)) return undefined
|
|
898
|
+
const currency = nonEmptyText(first.currency)
|
|
899
|
+
const total = amount(first.total_balance)
|
|
900
|
+
const toppedUp = amount(first.topped_up_balance)
|
|
901
|
+
const granted = amount(first.granted_balance)
|
|
902
|
+
if (currency === undefined || total === undefined || toppedUp === undefined || granted === undefined) return undefined
|
|
903
|
+
return { currency, total, toppedUp, granted }
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/** 余额端点把金额写成字符串;数字与字符串都读得出来才算数。 */
|
|
907
|
+
function amount(value: unknown): number | undefined {
|
|
908
|
+
const parsed = typeof value === 'number'
|
|
909
|
+
? value
|
|
910
|
+
: typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN
|
|
911
|
+
return Number.isFinite(parsed) ? parsed : undefined
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/**
|
|
915
|
+
* 凭据的指纹(FNV-1a)。
|
|
916
|
+
*
|
|
917
|
+
* 缓存键要按凭据区分,但进程里不该为了做键而多留一份密钥:指纹进键,密钥
|
|
918
|
+
* 只出现在发往上游的那一个请求头里。
|
|
919
|
+
*/
|
|
920
|
+
function fingerprint(secret: string): string {
|
|
921
|
+
let hash = 0x811c9dc5
|
|
922
|
+
for (let index = 0; index < secret.length; index += 1) {
|
|
923
|
+
hash ^= secret.charCodeAt(index)
|
|
924
|
+
hash = Math.imul(hash, 0x01000193) >>> 0
|
|
925
|
+
}
|
|
926
|
+
return hash.toString(16)
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/** 非空字符串,其余一律 undefined。 */
|
|
930
|
+
function nonEmptyText(value: unknown): string | undefined {
|
|
931
|
+
return typeof value === 'string' && value !== '' ? value : undefined
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/** 一个可按下标读取的普通对象。 */
|
|
935
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
936
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
937
|
+
}
|