dsh-desktop-statusbar 3.0.2 → 3.0.3
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/README.en.md +145 -145
- package/README.md +142 -142
- package/cordis.patch.yml +14 -14
- package/docs/official-models.json +468 -0
- package/docs/official-models.md +190 -0
- package/docs/vendor-intelligence-order.json +124 -0
- package/docs/vendor-intelligence-order.md +77 -0
- package/icon.svg +10 -10
- package/lib/balance-api.js +516 -499
- package/lib/client.js +11436 -9670
- package/lib/exchange-rate.js +199 -199
- package/lib/holiday.js +128 -128
- package/lib/index.js +1723 -376
- package/lib/release-age.js +509 -509
- package/lib/self-update.js +913 -870
- package/locale/en.json +6 -6
- package/locale/zh.json +6 -6
- package/package.json +72 -72
- package/tools/plugin-dir.cjs +0 -4
- package/tools/shot.cjs +9 -10
package/lib/index.js
CHANGED
|
@@ -42,14 +42,15 @@
|
|
|
42
42
|
* @module dsh-desktop-statusbar
|
|
43
43
|
*/
|
|
44
44
|
import { z } from 'zod'
|
|
45
|
-
import { adapterFor, adaptersFor, pluginRoutesIn } from './balance-api.js'
|
|
45
|
+
import { adapterFor, adaptersFor, parseDeepSeekBalance, pluginRoutesIn } from './balance-api.js'
|
|
46
46
|
import { holidayHtmlToText, parseHolidayNotice } from './holiday.js'
|
|
47
47
|
import { isUpdating, lastUpdateResult, resolveSelfDir, selfUpdateOnce } from './self-update.js'
|
|
48
48
|
import { currentRate as currentExchangeRate, fetchAndCacheRate, nineAmOf, readCachedRate, shouldRefresh } from './exchange-rate.js'
|
|
49
|
-
import {
|
|
49
|
+
import { createHash } from 'node:crypto'
|
|
50
|
+
import { appendFileSync, closeSync, copyFileSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
50
51
|
/* 异步读盘用:扫描热点上按文件 `fs.promises.readFile`,读 8 MB 日志的这 5 ms 也别占主线程。 */
|
|
51
52
|
import { promises as fsPromises } from 'node:fs'
|
|
52
|
-
import { basename, dirname, join } from 'node:path'
|
|
53
|
+
import { basename, dirname, join, sep } from 'node:path'
|
|
53
54
|
import { homedir } from 'node:os'
|
|
54
55
|
import * as zlib from 'node:zlib'
|
|
55
56
|
|
|
@@ -88,13 +89,19 @@ function logHost(ctx, message) {
|
|
|
88
89
|
const sessionModelSchema = z.object({
|
|
89
90
|
provider: z.string().nullable(),
|
|
90
91
|
model: z.string().nullable(),
|
|
91
|
-
|
|
92
|
+
}).strict()
|
|
93
|
+
|
|
94
|
+
/* 客户端只读 provider/model。`updatedAt` 这类内部时间戳从未被任何代码读取,
|
|
95
|
+
已从 state 与 wire 两处彻底删除(stateVersion 2 让旧缓存重放一次)。 */
|
|
96
|
+
const sessionModelViewSchema = z.object({
|
|
97
|
+
provider: z.string().nullable(),
|
|
98
|
+
model: z.string().nullable(),
|
|
92
99
|
}).strict()
|
|
93
100
|
|
|
94
101
|
const sessionModelProjection = {
|
|
95
102
|
key: 'desktopStatusbarModel',
|
|
96
103
|
stateSchema: sessionModelSchema,
|
|
97
|
-
init: () => ({ provider: null, model: null
|
|
104
|
+
init: () => ({ provider: null, model: null }),
|
|
98
105
|
apply: (state, event) => {
|
|
99
106
|
if (event.type !== 'assistant/message') return state
|
|
100
107
|
const source = event.data === undefined || event.data === null || event.data.message === undefined || event.data.message === null
|
|
@@ -103,10 +110,10 @@ const sessionModelProjection = {
|
|
|
103
110
|
if (source === null || source === undefined || source.kind !== 'model') return state
|
|
104
111
|
const { provider, model } = source
|
|
105
112
|
if (provider === state.provider && model === state.model) return state
|
|
106
|
-
return { provider, model
|
|
113
|
+
return { provider, model }
|
|
107
114
|
},
|
|
108
|
-
wire: { viewSchema:
|
|
109
|
-
stateVersion:
|
|
115
|
+
wire: { viewSchema: sessionModelViewSchema, view: (state) => ({ provider: state.provider, model: state.model }) },
|
|
116
|
+
stateVersion: 2,
|
|
110
117
|
}
|
|
111
118
|
|
|
112
119
|
/* ------------------------------------------------------------ sessionCapacity */
|
|
@@ -114,7 +121,12 @@ const sessionModelProjection = {
|
|
|
114
121
|
const sessionCapacitySchema = z.object({
|
|
115
122
|
contextWindow: z.number().nullable(),
|
|
116
123
|
maxOutputTokens: z.number().nullable(),
|
|
117
|
-
|
|
124
|
+
}).strict()
|
|
125
|
+
|
|
126
|
+
/* 客户端只读两个容量值;updatedAt 从未被读取,已从 state 与 wire 两处删除。 */
|
|
127
|
+
const sessionCapacityViewSchema = z.object({
|
|
128
|
+
contextWindow: z.number().nullable(),
|
|
129
|
+
maxOutputTokens: z.number().nullable(),
|
|
118
130
|
}).strict()
|
|
119
131
|
|
|
120
132
|
/**
|
|
@@ -126,7 +138,7 @@ const sessionCapacitySchema = z.object({
|
|
|
126
138
|
const sessionCapacityProjection = {
|
|
127
139
|
key: 'desktopStatusbarCapacity',
|
|
128
140
|
stateSchema: sessionCapacitySchema,
|
|
129
|
-
init: () => ({ contextWindow: null, maxOutputTokens: null
|
|
141
|
+
init: () => ({ contextWindow: null, maxOutputTokens: null }),
|
|
130
142
|
apply: (state, event) => {
|
|
131
143
|
const data = event.data === undefined || event.data === null ? {} : event.data
|
|
132
144
|
let contextWindow = state.contextWindow
|
|
@@ -142,10 +154,13 @@ const sessionCapacityProjection = {
|
|
|
142
154
|
return state
|
|
143
155
|
}
|
|
144
156
|
if (contextWindow === state.contextWindow && maxOutputTokens === state.maxOutputTokens) return state
|
|
145
|
-
return { contextWindow, maxOutputTokens
|
|
157
|
+
return { contextWindow, maxOutputTokens }
|
|
158
|
+
},
|
|
159
|
+
wire: {
|
|
160
|
+
viewSchema: sessionCapacityViewSchema,
|
|
161
|
+
view: (state) => ({ contextWindow: state.contextWindow, maxOutputTokens: state.maxOutputTokens }),
|
|
146
162
|
},
|
|
147
|
-
|
|
148
|
-
stateVersion: 1,
|
|
163
|
+
stateVersion: 2,
|
|
149
164
|
}
|
|
150
165
|
|
|
151
166
|
/* -------------------------------------------------------- sessionProgress */
|
|
@@ -200,6 +215,13 @@ const sessionProgressSchema = z.object({
|
|
|
200
215
|
compacts: z.array(compactMark),
|
|
201
216
|
}).strict()
|
|
202
217
|
|
|
218
|
+
/**
|
|
219
|
+
* 进度投影的 wire 视图:客户端只读 compacts 数组本身,顶层 compactTurn/compactStep
|
|
220
|
+
* 是“最近一次成功压缩”的冗余副本(客户端从 compacts[last] 自己取),不进 wire 视图。
|
|
221
|
+
* 状态里仍保留这两个字段(宿主语义与回归测试都按它们断言)。
|
|
222
|
+
*/
|
|
223
|
+
const sessionProgressViewSchema = sessionProgressSchema.omit({ compactTurn: true, compactStep: true })
|
|
224
|
+
|
|
203
225
|
/** 从 skill 工具的参数里取技能名;参数是 JSON 字符串,坏掉就当没这个名字。 */
|
|
204
226
|
function skillNameOf(data) {
|
|
205
227
|
let args = data.arguments
|
|
@@ -385,9 +407,15 @@ const sessionProgressProjection = {
|
|
|
385
407
|
一次 read 可能读多个文件(ops_read_files),按读到的顺序各记一条;
|
|
386
408
|
读的不是子能力文档(glossary.md 之类)时这里是空数组,什么都不记。 */
|
|
387
409
|
const subSkills = name === null ? [] : readPathsOf(name, data).map(subSkillOfPath).filter((one) => one !== null)
|
|
410
|
+
/* 安全键读取:工具名来自上游(可能是 `__proto__` / `constructor` / `toString`)。
|
|
411
|
+
直接 `state.toolCounts[name]` 会命中原型属性,拿到函数/对象再 +1 就变成字符串拼接,
|
|
412
|
+
甚至把计数写成 `[object Object]1`。必须只认自有属性。 */
|
|
413
|
+
const prevCount = name !== null && Object.prototype.hasOwnProperty.call(state.toolCounts, name)
|
|
414
|
+
? state.toolCounts[name]
|
|
415
|
+
: 0
|
|
388
416
|
const counts = name === null ? state.toolCounts : {
|
|
389
417
|
...state.toolCounts,
|
|
390
|
-
[name]: (
|
|
418
|
+
[name]: (typeof prevCount === 'number' && Number.isFinite(prevCount) ? prevCount : 0) + 1,
|
|
391
419
|
}
|
|
392
420
|
let skills = state.skills
|
|
393
421
|
/* 技能有三种注入来源:调 skill 工具(自动/模型触发)、斜杠命令(user/message 分支,
|
|
@@ -429,7 +457,15 @@ const sessionProgressProjection = {
|
|
|
429
457
|
}
|
|
430
458
|
return state
|
|
431
459
|
},
|
|
432
|
-
wire: {
|
|
460
|
+
wire: {
|
|
461
|
+
viewSchema: sessionProgressViewSchema,
|
|
462
|
+
view: (state) => {
|
|
463
|
+
const out = { ...state }
|
|
464
|
+
delete out.compactTurn
|
|
465
|
+
delete out.compactStep
|
|
466
|
+
return out
|
|
467
|
+
},
|
|
468
|
+
},
|
|
433
469
|
// 字段变了(skills 变成 {name, manual}、compacts 加 manual 且只记成功、压缩 turn 可为 null),提升版本重建旧状态
|
|
434
470
|
// 7 → 8:compacts 新增 afterTurn(轮间/手动压缩显示「第 N 轮后」,替代原来的横杠)。
|
|
435
471
|
// 旧缓存里每条压缩记录没有这个字段,必须重放才能补出来。
|
|
@@ -531,6 +567,7 @@ function usageParts(usage) {
|
|
|
531
567
|
/** 一次模型调用的分量与发生时间,峰谷计价按它逐条判定。 */
|
|
532
568
|
const usageCall = z.object({
|
|
533
569
|
at: z.number(),
|
|
570
|
+
provider: z.string(),
|
|
534
571
|
model: z.string(),
|
|
535
572
|
input: z.number(),
|
|
536
573
|
cacheRead: z.number(),
|
|
@@ -550,8 +587,19 @@ const lastUsage = z.object({
|
|
|
550
587
|
}).strict()
|
|
551
588
|
|
|
552
589
|
const MAX_CALLS = 4000
|
|
553
|
-
|
|
554
|
-
|
|
590
|
+
/**
|
|
591
|
+
* 追加调用记录,只保留最近 MAX_CALLS 条。
|
|
592
|
+
* 只做**一次**数组拷贝:原实现溢出时 `slice(...).concat(more)` 会先 slice 再 concat,
|
|
593
|
+
* 把 4000 条数组复制两遍;长会话每次追加都走这条路,属于白烧内存带宽。
|
|
594
|
+
* 这里先 slice 出保留区间,再逐条 push —— 仍是纯函数(不碰入参数组)。
|
|
595
|
+
*/
|
|
596
|
+
const appendCalls = (calls, more) => {
|
|
597
|
+
if (more.length === 0) return calls
|
|
598
|
+
const keepFrom = Math.max(0, calls.length + more.length - MAX_CALLS)
|
|
599
|
+
const out = calls.slice(keepFrom)
|
|
600
|
+
for (let i = 0; i < more.length; i += 1) out.push(more[i])
|
|
601
|
+
return out
|
|
602
|
+
}
|
|
555
603
|
|
|
556
604
|
/**
|
|
557
605
|
* 被 MAX_CALLS 截掉的调用,按「模型 + 峰谷档」累计的 token。
|
|
@@ -572,23 +620,31 @@ const overflowTier = z.object({
|
|
|
572
620
|
/** 往 overflow 里加一笔;返回新的 overflow(不改原对象)。 */
|
|
573
621
|
function addOverflow(overflow, model, parts, peak) {
|
|
574
622
|
const zero = () => ({ input: 0, cacheRead: 0, cacheWrite: 0, output: 0 })
|
|
575
|
-
const
|
|
623
|
+
const hasOwn = Object.prototype.hasOwnProperty.call(overflow, model)
|
|
624
|
+
const raw = hasOwn ? overflow[model] : null
|
|
625
|
+
const prev = raw !== null && typeof raw === 'object' && !Array.isArray(raw)
|
|
626
|
+
? raw
|
|
627
|
+
: { peak: zero(), offPeak: zero() }
|
|
576
628
|
const tierName = peak === true ? 'peak' : 'offPeak'
|
|
577
|
-
const
|
|
629
|
+
const rawTier = prev[tierName]
|
|
630
|
+
const tier = rawTier !== null && typeof rawTier === 'object' && !Array.isArray(rawTier) ? rawTier : zero()
|
|
578
631
|
return {
|
|
579
632
|
...overflow,
|
|
580
633
|
[model]: {
|
|
581
634
|
...prev,
|
|
582
635
|
[tierName]: {
|
|
583
|
-
input: tier.input + parts.input,
|
|
584
|
-
cacheRead: tier.cacheRead + parts.cacheRead,
|
|
585
|
-
cacheWrite: tier.cacheWrite + parts.cacheWrite,
|
|
586
|
-
output: tier.output + parts.output,
|
|
636
|
+
input: numOrZero(tier.input) + parts.input,
|
|
637
|
+
cacheRead: numOrZero(tier.cacheRead) + parts.cacheRead,
|
|
638
|
+
cacheWrite: numOrZero(tier.cacheWrite) + parts.cacheWrite,
|
|
639
|
+
output: numOrZero(tier.output) + parts.output,
|
|
587
640
|
},
|
|
588
641
|
},
|
|
589
642
|
}
|
|
590
643
|
}
|
|
591
644
|
|
|
645
|
+
/* Provider-aware overflow was removed: it was written on every call but had no client reader.
|
|
646
|
+
The model-keyed `overflow` is the compatibility mirror the UI actually consumes. */
|
|
647
|
+
|
|
592
648
|
/**
|
|
593
649
|
* 把一笔调用并进总计:models 按模型累加、calls 追加,
|
|
594
650
|
* 超过 MAX_CALLS 被挤掉的最老几条按「模型 + 峰谷档」补进 overflow。
|
|
@@ -703,14 +759,17 @@ const sessionUsageProjection = {
|
|
|
703
759
|
: (fromMessage ? source.model : (typeof base.routeModel === 'string' ? base.routeModel : ''))
|
|
704
760
|
// 拿不到型号:放弃这一笔,好过抛错把整条投影(以及同一次驱动的其它投影)带停
|
|
705
761
|
if (model.length === 0) return base
|
|
762
|
+
/* Provider attribution is event-local: messages use their source, attempts use the
|
|
763
|
+
contemporaneous route, and compaction summaries use only their data.provider. */
|
|
706
764
|
const provider = isCompactionSummary
|
|
707
765
|
? (typeof data.provider === 'string' ? data.provider : '')
|
|
708
|
-
: (
|
|
709
|
-
? source.provider
|
|
710
|
-
: (typeof base.routeProvider === 'string' ? base.routeProvider : ''))
|
|
766
|
+
: (event.type === 'assistant/message'
|
|
767
|
+
? (source !== null && typeof source.provider === 'string' ? source.provider : '')
|
|
768
|
+
: (event.type === 'assistant/attempt' && typeof base.routeProvider === 'string' ? base.routeProvider : ''))
|
|
711
769
|
const parts = usageParts(usage)
|
|
712
770
|
const one = {
|
|
713
771
|
at: event.time,
|
|
772
|
+
provider,
|
|
714
773
|
model,
|
|
715
774
|
input: parts.input,
|
|
716
775
|
cacheRead: parts.cacheRead,
|
|
@@ -849,7 +908,11 @@ const sessionUsageProjection = {
|
|
|
849
908
|
// 官方 tokenUsage 投影不含摘要,导致「总计费用」含摘要而「总计用量」不含,同一面板两个口径。
|
|
850
909
|
// 旧缓存没有这个字段,不重放的话历史会话的「总计用量」会永远少那几笔摘要。
|
|
851
910
|
// 同一次 bump 也覆盖「轮间/手动压缩刷新本轮」的新语义(current 的重建规则变了)。
|
|
852
|
-
|
|
911
|
+
// 8 → 9:usageCall 新增 provider 并新增 provider-aware overflow,旧调用不能从 model 猜 provider。
|
|
912
|
+
// 9 → 10:session usage 不再固定 feeMultiplier;客户端按当前 non-secret provider 配置动态计价。
|
|
913
|
+
// 10 → 11:删除 `overflowByProvider`(客户端零引用、纯重复计算);旧缓存多余字段会过不了
|
|
914
|
+
// strict schema,必须重放重建。
|
|
915
|
+
stateVersion: 11,
|
|
853
916
|
}
|
|
854
917
|
|
|
855
918
|
/* -------------------------------------------------------- sessionTimeRange */
|
|
@@ -912,10 +975,22 @@ const sessionTimeRangeProjection = {
|
|
|
912
975
|
* (ttftMs/ttftSteps、decodeMs/decodeTokens),推不出单次极值,所以在 host 侧
|
|
913
976
|
* 按同一套事件口径自己折一份:`step/start` → 首个 token 分片 → `assistant/message`。
|
|
914
977
|
*
|
|
915
|
-
*
|
|
916
|
-
*
|
|
917
|
-
*
|
|
918
|
-
*
|
|
978
|
+
* 口径按大众定义(不做「数值好看」的人为过滤):
|
|
979
|
+
* · **TTFT** = `step/start` → 首个分片(含网络/排队/预填充等待)。极值如实统计所有能算出
|
|
980
|
+
* ttft 的样本:不设 60 秒上限,108 秒这种真实值就是最慢首字;message stream 兜底、
|
|
981
|
+
* 工具首片也算(首字延迟与输出内容无关)。
|
|
982
|
+
* · **TPS 的分母按结构性判据选**(不看输出 token 数/速度数值,没有 500 之类阈值):
|
|
983
|
+
* **解码窗口可信** = `decode ≥ 300ms` 且 `decode ≥ 15% × request`
|
|
984
|
+
* (后者挡住"流式时间戳被缓冲、token 末尾一次性灌入"的样本 —— 实测有解码窗口 1.1s
|
|
985
|
+
* 而请求窗口 25s 的样本,1725 t/s 是假值)。
|
|
986
|
+
* - 有 reasoning 分片且解码可信(DeepSeek/Qwen 这类思考流式可见)→ **解码窗口**
|
|
987
|
+
* (首个分片 → 消息结束)算标准解码速度,不含首字等待;
|
|
988
|
+
* - 无 reasoning 分片(GPT 这类隐藏思维链)**或**解码不可信(缓冲)→ **请求窗口**
|
|
989
|
+
* (`step/start` → 结束,扣工具区间并集)算端到端吞吐:GPT 显示 56-60 这类真实值,
|
|
990
|
+
* 缓冲样本显示用户实际等待下的真实速度。
|
|
991
|
+
* · 极值与本轮平均同一口径;只保留**测量精度**门槛(不是数值门槛):
|
|
992
|
+
* `output > 0`、非纯工具首分片、选定窗口 ≥ 300ms(时间戳分辨率,短窗口会算出几千 t/s)。
|
|
993
|
+
* 不按 token 数、速度上下限、首字上限等任何数值条件剔除真实样本。
|
|
919
994
|
*/
|
|
920
995
|
const timingMark = z.object({
|
|
921
996
|
/* 首字极值单位是毫秒,速度极值单位是 tokens/秒,看字段名区分 */
|
|
@@ -929,8 +1004,10 @@ const timingStep = z.object({
|
|
|
929
1004
|
step: z.number(),
|
|
930
1005
|
startTime: z.number(),
|
|
931
1006
|
firstTokenTime: z.number().nullable(),
|
|
932
|
-
/* 首 token 是不是工具调用分片(速度极值据此排除) */
|
|
933
1007
|
firstTokenTool: z.boolean(),
|
|
1008
|
+
reasoning: z.boolean(),
|
|
1009
|
+
toolStarts: z.record(z.number()),
|
|
1010
|
+
toolIntervals: z.array(z.tuple([z.number(), z.number()])),
|
|
934
1011
|
}).strict()
|
|
935
1012
|
|
|
936
1013
|
const timingViewSchema = z.object({
|
|
@@ -1004,6 +1081,24 @@ function firstStreamToken(stream) {
|
|
|
1004
1081
|
return undefined
|
|
1005
1082
|
}
|
|
1006
1083
|
|
|
1084
|
+
/** 该步的流里是否出现**流式思维链**分片:决定 TPS 分母取解码窗口还是请求窗口。 */
|
|
1085
|
+
function streamHasReasoning(stream) {
|
|
1086
|
+
if (Array.isArray(stream) !== true) return false
|
|
1087
|
+
for (const record of stream) {
|
|
1088
|
+
if (record === null || record === undefined || typeof record !== 'object') continue
|
|
1089
|
+
const chunk = record.type === 'chunk' && record.chunk !== null && typeof record.chunk === 'object'
|
|
1090
|
+
? record.chunk
|
|
1091
|
+
: record
|
|
1092
|
+
if (chunk.type === 'reasoning-delta') {
|
|
1093
|
+
if (typeof chunk.text === 'string' && chunk.text.length > 0) return true
|
|
1094
|
+
continue
|
|
1095
|
+
}
|
|
1096
|
+
if (chunk.type === 'reasoning-chunks') return true
|
|
1097
|
+
if (chunk.type === 'block-start' && chunk.blockType === 'reasoning') return true
|
|
1098
|
+
}
|
|
1099
|
+
return false
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1007
1102
|
/** 该步上报的输出 token 数;缺字段或非法值返回 null(这一步就不参与速度极值)。 */
|
|
1008
1103
|
function stepOutputTokens(usage) {
|
|
1009
1104
|
if (usage === null || usage === undefined || typeof usage !== 'object') return null
|
|
@@ -1014,22 +1109,36 @@ function stepOutputTokens(usage) {
|
|
|
1014
1109
|
const pickSmaller = (current, candidate) => (current === null || candidate.value < current.value ? candidate : current)
|
|
1015
1110
|
const pickLarger = (current, candidate) => (current === null || candidate.value > current.value ? candidate : current)
|
|
1016
1111
|
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1112
|
+
function toolIntervalUnionMs(open, fromTime, endTime) {
|
|
1113
|
+
const intervals = open.toolIntervals.slice()
|
|
1114
|
+
for (const callId of Object.keys(open.toolStarts)) intervals.push([open.toolStarts[callId], endTime])
|
|
1115
|
+
const clipped = intervals
|
|
1116
|
+
.map(([start, end]) => [Math.max(fromTime, start), Math.min(endTime, end)])
|
|
1117
|
+
.filter(([start, end]) => end > start)
|
|
1118
|
+
.sort((a, b) => a[0] - b[0])
|
|
1119
|
+
let total = 0
|
|
1120
|
+
let from = null
|
|
1121
|
+
let to = null
|
|
1122
|
+
for (const [start, end] of clipped) {
|
|
1123
|
+
if (from === null) {
|
|
1124
|
+
from = start
|
|
1125
|
+
to = end
|
|
1126
|
+
} else if (start <= to) {
|
|
1127
|
+
to = Math.max(to, end)
|
|
1128
|
+
} else {
|
|
1129
|
+
total += to - from
|
|
1130
|
+
from = start
|
|
1131
|
+
to = end
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
return from === null ? 0 : total + to - from
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
/* 测量精度门槛:极值与本轮平均同一套(口径见 sessionTiming 顶部注释)。 */
|
|
1138
|
+
const TPS_MIN_WINDOW_MS = 300
|
|
1139
|
+
/* 解码窗口可信度:流式时间戳若被缓冲(token 末尾一次性灌入),解码窗口会远小于请求窗口。
|
|
1140
|
+
要求解码窗口至少占请求窗口的 15%,否则时间戳不可用、改走端到端吞吐。 */
|
|
1141
|
+
const TPS_DECODE_SHARE_MIN = 0.15
|
|
1033
1142
|
|
|
1034
1143
|
const sessionTimingProjection = {
|
|
1035
1144
|
key: 'desktopStatusbarTiming',
|
|
@@ -1063,22 +1172,66 @@ const sessionTimingProjection = {
|
|
|
1063
1172
|
turnDecodeTokens: sameTurn ? state.turnDecodeTokens : 0,
|
|
1064
1173
|
openStep: {
|
|
1065
1174
|
turn: data.turn, step: data.step, startTime: event.time,
|
|
1066
|
-
firstTokenTime: null, firstTokenTool: false,
|
|
1175
|
+
firstTokenTime: null, firstTokenTool: false, reasoning: false,
|
|
1176
|
+
toolStarts: {}, toolIntervals: [],
|
|
1067
1177
|
},
|
|
1068
1178
|
}
|
|
1069
1179
|
}
|
|
1070
1180
|
if (event.type === 'assistant/attempt') {
|
|
1071
1181
|
const open = state.openStep
|
|
1072
1182
|
if (open === null || open.turn !== event.data.turn || open.step !== event.data.step) return state
|
|
1183
|
+
const reasoning = open.reasoning === true || streamHasReasoning(event.data.stream)
|
|
1073
1184
|
const first = firstStreamToken(event.data.stream)
|
|
1074
|
-
|
|
1075
|
-
|
|
1185
|
+
const missingFirst = open.firstTokenTime === null && first !== undefined
|
|
1186
|
+
if (missingFirst !== true && reasoning === open.reasoning) return state
|
|
1187
|
+
return {
|
|
1188
|
+
...state,
|
|
1189
|
+
openStep: {
|
|
1190
|
+
...open,
|
|
1191
|
+
reasoning,
|
|
1192
|
+
firstTokenTime: missingFirst === true ? first.time : open.firstTokenTime,
|
|
1193
|
+
firstTokenTool: missingFirst === true ? first.tool === true : open.firstTokenTool,
|
|
1194
|
+
},
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
if (event.type === 'tool/call') {
|
|
1198
|
+
const open = state.openStep
|
|
1199
|
+
const data = event.data === undefined || event.data === null ? {} : event.data
|
|
1200
|
+
if (open === null || open.turn !== data.turn || open.step !== data.step
|
|
1201
|
+
|| typeof data.callId !== 'string' || data.callId.length === 0) return state
|
|
1202
|
+
return {
|
|
1203
|
+
...state,
|
|
1204
|
+
openStep: { ...open, toolStarts: { ...open.toolStarts, [data.callId]: event.time } },
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
if (event.type === 'tool/result') {
|
|
1208
|
+
const open = state.openStep
|
|
1209
|
+
const data = event.data === undefined || event.data === null ? {} : event.data
|
|
1210
|
+
const message = data.message !== null && data.message !== undefined && typeof data.message === 'object' ? data.message : null
|
|
1211
|
+
const source = message !== null && message.source !== null && message.source !== undefined ? message.source : null
|
|
1212
|
+
const callId = message !== null && typeof message.toolCallId === 'string'
|
|
1213
|
+
? message.toolCallId
|
|
1214
|
+
: source !== null && typeof source.callId === 'string' ? source.callId : ''
|
|
1215
|
+
if (open === null || open.turn !== data.turn || open.step !== data.step
|
|
1216
|
+
|| callId.length === 0 || typeof open.toolStarts[callId] !== 'number') return state
|
|
1217
|
+
const toolStarts = { ...open.toolStarts }
|
|
1218
|
+
const start = toolStarts[callId]
|
|
1219
|
+
delete toolStarts[callId]
|
|
1220
|
+
return {
|
|
1221
|
+
...state,
|
|
1222
|
+
openStep: {
|
|
1223
|
+
...open,
|
|
1224
|
+
toolStarts,
|
|
1225
|
+
toolIntervals: [...open.toolIntervals, [start, Math.max(start, event.time)]],
|
|
1226
|
+
},
|
|
1227
|
+
}
|
|
1076
1228
|
}
|
|
1077
1229
|
if (event.type === 'assistant/message') {
|
|
1078
1230
|
const open = state.openStep
|
|
1079
1231
|
if (open === null || open.turn !== event.data.turn || open.step !== event.data.step) return state
|
|
1080
|
-
const
|
|
1081
|
-
const
|
|
1232
|
+
const fromAttempt = open.firstTokenTime !== null
|
|
1233
|
+
const fromStream = fromAttempt ? undefined : firstStreamToken(event.data.stream)
|
|
1234
|
+
const first = fromAttempt
|
|
1082
1235
|
? { time: open.firstTokenTime, tool: open.firstTokenTool === true }
|
|
1083
1236
|
: fromStream
|
|
1084
1237
|
const next = { ...state, openStep: null }
|
|
@@ -1087,33 +1240,36 @@ const sessionTimingProjection = {
|
|
|
1087
1240
|
const model = source !== null && source !== undefined && typeof source.model === 'string' ? source.model : ''
|
|
1088
1241
|
const ttft = Math.max(0, first.time - open.startTime)
|
|
1089
1242
|
next.samples = state.samples + 1
|
|
1243
|
+
/* 首字极值如实统计所有能算出 ttft 的样本:含 message stream 兜底、含工具首片、含异常慢请求。
|
|
1244
|
+
不做「数值好看」的过滤 —— 只保留一条测量可信度:output>0 与非工具首片是 TPS 的门槛,
|
|
1245
|
+
首字本身只要首 token 时间可得就是真实值。 */
|
|
1090
1246
|
next.fastestTtft = pickSmaller(state.fastestTtft, { value: ttft, at: event.time, model })
|
|
1091
1247
|
next.slowestTtft = pickLarger(state.slowestTtft, { value: ttft, at: event.time, model })
|
|
1092
1248
|
next.turnTtftMs = state.turnTtftMs + ttft
|
|
1093
1249
|
next.turnTtftSamples = state.turnTtftSamples + 1
|
|
1094
1250
|
const output = stepOutputTokens(event.data.usage)
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
const
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1251
|
+
if (output !== null && output > 0 && first.tool !== true) {
|
|
1252
|
+
/* 窗口净时长:先按窗口起点裁剪工具区间,再扣并集。 */
|
|
1253
|
+
const windowMs = (from) => Math.max(0, event.time - from - toolIntervalUnionMs(open, from, event.time))
|
|
1254
|
+
const decodeMs = windowMs(first.time)
|
|
1255
|
+
const requestMs = windowMs(open.startTime)
|
|
1256
|
+
/* **结构性判据选分母**(不看输出 token 数/速度数值,没有 500 阈值):
|
|
1257
|
+
解码窗口可信 = 够长(≥300ms)**且**流式确实占了请求的显著一段(≥15%)。
|
|
1258
|
+
· 有 reasoning 且解码可信 → 标准解码 TPS(DeepSeek/Qwen 思考流式可见);
|
|
1259
|
+
· 无 reasoning(GPT 这类隐藏思维链)或解码不可信(时间戳被缓冲、token 末尾一次性
|
|
1260
|
+
灌入)→ 端到端吞吐 output / 请求窗口,显示用户实际等待下的真实速度。 */
|
|
1261
|
+
const reasoning = open.reasoning === true || streamHasReasoning(event.data.stream)
|
|
1262
|
+
const decodeTrusted = decodeMs >= TPS_MIN_WINDOW_MS && decodeMs >= TPS_DECODE_SHARE_MIN * requestMs
|
|
1263
|
+
const measuredMs = reasoning === true && decodeTrusted === true ? decodeMs : requestMs
|
|
1264
|
+
const speedValue = measuredMs > 0 ? output / (measuredMs / 1000) : Infinity
|
|
1265
|
+
/* 只保留测量精度门槛:选定窗口过短时时间戳分辨率不够(极值与本轮平均共用)。 */
|
|
1266
|
+
if (measuredMs >= TPS_MIN_WINDOW_MS) {
|
|
1267
|
+
const speed = { value: speedValue, at: event.time, model }
|
|
1268
|
+
next.fastestTps = pickLarger(state.fastestTps, speed)
|
|
1269
|
+
next.slowestTps = pickSmaller(state.slowestTps, speed)
|
|
1270
|
+
next.turnDecodeMs = state.turnDecodeMs + measuredMs
|
|
1271
|
+
next.turnDecodeTokens = state.turnDecodeTokens + output
|
|
1272
|
+
}
|
|
1117
1273
|
}
|
|
1118
1274
|
return next
|
|
1119
1275
|
}
|
|
@@ -1138,7 +1294,7 @@ const sessionTimingProjection = {
|
|
|
1138
1294
|
turnDecodeTokens: state.turnDecodeTokens,
|
|
1139
1295
|
}),
|
|
1140
1296
|
},
|
|
1141
|
-
stateVersion:
|
|
1297
|
+
stateVersion: 6,
|
|
1142
1298
|
}
|
|
1143
1299
|
|
|
1144
1300
|
/* ---------------------------------------------------------------- 余额查询 */
|
|
@@ -1191,33 +1347,23 @@ function sendJson(res, status, body) {
|
|
|
1191
1347
|
res.end(text)
|
|
1192
1348
|
}
|
|
1193
1349
|
|
|
1194
|
-
/*
|
|
1195
|
-
|
|
1196
|
-
(`Content-Type: text/plain` 的 POST 不触发 CORS 预检,页面读不到响应也照样**把请求送达**)。
|
|
1197
|
-
实测:伪造的价格库被完整接受,settleUnpriced 随后按攻击者单价结算进 `days[].cost`,
|
|
1198
|
-
而 cost 一旦记下就不再改动 —— 污染不可逆;同一面还能触发 /api/self-update 真跑 pnpm 安装。
|
|
1199
|
-
按用户确认的最小方案只做这一条判定,**不**引入 CORS 预检、**不**影响 GET:
|
|
1200
|
-
· 没有 Origin(命令行 / curl / 宿主内部)→ 放行;
|
|
1201
|
-
· Origin 的 host 与请求的 host 相同 → 同源,放行;
|
|
1202
|
-
· 带跨站 Origin(含 opaque 的 `null`)的 POST → 由调用方回 403。
|
|
1203
|
-
取不到 Host 头时判不了,保守放行(本机 webServer 一定带 Host,这一支只防意外形状)。 */
|
|
1204
|
-
function isCrossSiteWrite(req) {
|
|
1350
|
+
/* 写请求来源校验:没有 Origin 的命令行/宿主调用放行;带 Origin 的 POST 必须与监听器权威 origin 完全同源。 */
|
|
1351
|
+
function isCrossSiteWrite(req, ctx) {
|
|
1205
1352
|
if (req === null || req === undefined || req.method !== 'POST') return false
|
|
1206
1353
|
const headers = req.headers
|
|
1207
1354
|
if (headers === null || headers === undefined || typeof headers !== 'object') return false
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
return hostOnly !== target
|
|
1355
|
+
if (Object.prototype.hasOwnProperty.call(headers, 'origin') !== true) return false
|
|
1356
|
+
const raw = headers.origin
|
|
1357
|
+
if (typeof raw !== 'string' || raw.trim().length === 0 || raw.trim().toLowerCase() === 'null') return true
|
|
1358
|
+
try {
|
|
1359
|
+
const server = ctx === null || ctx === undefined ? null : ctx.webServer
|
|
1360
|
+
if (server === null || server === undefined || typeof server.getOrigin !== 'function') return true
|
|
1361
|
+
const requestOrigin = new URL(raw.trim()).origin
|
|
1362
|
+
const listenerOrigin = new URL(server.getOrigin()).origin
|
|
1363
|
+
return requestOrigin !== listenerOrigin
|
|
1364
|
+
} catch (error) {
|
|
1365
|
+
return true
|
|
1366
|
+
}
|
|
1221
1367
|
}
|
|
1222
1368
|
|
|
1223
1369
|
/* 请求体上限。原先统一 4KB,但**价格库会随模型数增长**:实测一条模型约 186 字节,
|
|
@@ -1276,6 +1422,584 @@ function readJsonBody(req) {
|
|
|
1276
1422
|
})
|
|
1277
1423
|
}
|
|
1278
1424
|
|
|
1425
|
+
const RELAY_CONFIG_VERSION = 2
|
|
1426
|
+
const RELAY_SECRET_REF_PREFIX = 'DSH_DESKTOP_STATUSBAR_RELAY_'
|
|
1427
|
+
const RELAY_RESPONSE_LIMIT = 64 * 1024
|
|
1428
|
+
const RELAY_HEADER_LIMIT = 16
|
|
1429
|
+
let relayConfigWriteSeq = 0
|
|
1430
|
+
let relayFeeConfigCache
|
|
1431
|
+
let relayFeeConfigCachePath = null
|
|
1432
|
+
/* Process-local serialization only; relay config writes assume a single Host writer (no cross-process lock). */
|
|
1433
|
+
let relayConfigWriteTail = Promise.resolve()
|
|
1434
|
+
|
|
1435
|
+
function relayConfigPath() {
|
|
1436
|
+
return join(dshHome(), 'dsh-status-bar', 'relay-balance.json')
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
function relaySecretRef(channelKey) {
|
|
1440
|
+
return RELAY_SECRET_REF_PREFIX + createHash('sha256').update(channelKey).digest('hex')
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
function relayHeaderNameValid(name) {
|
|
1444
|
+
return typeof name === 'string' && name.length > 0 && name.length <= 128
|
|
1445
|
+
&& /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)
|
|
1446
|
+
&& !/^(host|content-length|connection|transfer-encoding|upgrade|cookie|set-cookie|proxy-.*)$/i.test(name)
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
function relayPathSegments(path) {
|
|
1450
|
+
if (typeof path !== 'string' || path.length === 0 || path.length > 256) return null
|
|
1451
|
+
let text = path.trim()
|
|
1452
|
+
if (text.startsWith('$')) text = text.slice(1)
|
|
1453
|
+
if (text.length > 0 && text[0] !== '.' && text[0] !== '[') text = '.' + text
|
|
1454
|
+
const segments = []
|
|
1455
|
+
let at = 0
|
|
1456
|
+
const token = /^(?:\.([A-Za-z_$][A-Za-z0-9_$-]*)|\[(0|[1-9][0-9]{0,5})\])/
|
|
1457
|
+
while (at < text.length) {
|
|
1458
|
+
const match = token.exec(text.slice(at))
|
|
1459
|
+
if (match === null) return null
|
|
1460
|
+
const segment = match[1] === undefined ? Number(match[2]) : match[1]
|
|
1461
|
+
if (typeof segment === 'string' && ['__proto__', 'prototype', 'constructor'].includes(segment)) return null
|
|
1462
|
+
segments.push(segment)
|
|
1463
|
+
at += match[0].length
|
|
1464
|
+
}
|
|
1465
|
+
return segments
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
function relayValueAt(data, segments) {
|
|
1469
|
+
let value = data
|
|
1470
|
+
for (const segment of segments) {
|
|
1471
|
+
if (value === null || value === undefined || typeof value !== 'object' || !(segment in value)) return undefined
|
|
1472
|
+
value = value[segment]
|
|
1473
|
+
}
|
|
1474
|
+
return value
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
function sanitizeRelayEndpoint(value) {
|
|
1478
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > 2048 || value.trim() !== value) return null
|
|
1479
|
+
let parsed
|
|
1480
|
+
try {
|
|
1481
|
+
parsed = new URL(value)
|
|
1482
|
+
} catch (error) {
|
|
1483
|
+
return null
|
|
1484
|
+
}
|
|
1485
|
+
if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
1486
|
+
|| parsed.username.length > 0 || parsed.password.length > 0 || parsed.hash.length > 0 || parsed.search.length > 0
|
|
1487
|
+
|| parsed.hostname.length === 0) return null
|
|
1488
|
+
/* User-configured localhost/LAN endpoints are allowed; redirects are disabled on fetch. */
|
|
1489
|
+
return parsed.toString()
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
function relayChannelKeyValid(channelKey) {
|
|
1493
|
+
return typeof channelKey === 'string' && channelKey.length > 0 && channelKey.length <= 128
|
|
1494
|
+
&& channelKey.trim() === channelKey && !/[\r\n\0]/.test(channelKey)
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
function relayIsMagpie(channelKey) {
|
|
1498
|
+
return channelKey.toLowerCase().includes('magpie')
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
function relayFeeMultiplierValid(value) {
|
|
1502
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 1000
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
/* 余额换算除数:上游可能按最小单位返回(如 500000 = ¥1),除以它再格式化。 */
|
|
1506
|
+
function relayBalanceDivisorValid(value) {
|
|
1507
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 1e12
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
function relaySettings(body, previous, headerNames) {
|
|
1511
|
+
const source = body !== null && typeof body === 'object' && !Array.isArray(body) ? body : {}
|
|
1512
|
+
const prior = previous !== null && typeof previous === 'object' ? previous : {}
|
|
1513
|
+
const channelKey = source.channelKey === undefined ? prior.channelKey : source.channelKey
|
|
1514
|
+
const endpointValue = source.endpoint === undefined ? prior.endpoint : source.endpoint
|
|
1515
|
+
const endpoint = sanitizeRelayEndpoint(endpointValue)
|
|
1516
|
+
const tokenHeader = source.tokenHeader === undefined
|
|
1517
|
+
? (prior.tokenHeader === undefined ? 'authorization' : prior.tokenHeader)
|
|
1518
|
+
: source.tokenHeader
|
|
1519
|
+
const userIdHeader = source.userIdHeader === undefined
|
|
1520
|
+
? (prior.userIdHeader === undefined ? 'x-user-id' : prior.userIdHeader)
|
|
1521
|
+
: source.userIdHeader
|
|
1522
|
+
const tokenPrefix = source.tokenPrefix === undefined
|
|
1523
|
+
? (prior.tokenPrefix === undefined ? 'Bearer ' : prior.tokenPrefix)
|
|
1524
|
+
: source.tokenPrefix
|
|
1525
|
+
const balancePath = source.balancePath === undefined
|
|
1526
|
+
? (prior.balancePath === undefined ? '$.balance' : prior.balancePath)
|
|
1527
|
+
: source.balancePath
|
|
1528
|
+
const currency = source.currency === undefined
|
|
1529
|
+
? (prior.currency === undefined ? 'CNY' : prior.currency)
|
|
1530
|
+
: source.currency
|
|
1531
|
+
const feeMultiplier = source.feeMultiplier === undefined
|
|
1532
|
+
? (prior.feeMultiplier === undefined ? 1 : prior.feeMultiplier)
|
|
1533
|
+
: source.feeMultiplier
|
|
1534
|
+
const balanceDivisor = source.balanceDivisor ?? prior.balanceDivisor ?? 1
|
|
1535
|
+
const names = headerNames === undefined ? prior.headerNames : headerNames
|
|
1536
|
+
const segments = relayPathSegments(balancePath)
|
|
1537
|
+
if (!relayChannelKeyValid(channelKey) || relayIsMagpie(channelKey) || endpoint === null
|
|
1538
|
+
|| !relayHeaderNameValid(tokenHeader) || !relayHeaderNameValid(userIdHeader)
|
|
1539
|
+
|| tokenHeader.toLowerCase() === userIdHeader.toLowerCase()
|
|
1540
|
+
|| typeof tokenPrefix !== 'string' || tokenPrefix.length > 64 || /[\r\n\0]/.test(tokenPrefix)
|
|
1541
|
+
|| segments === null || typeof currency !== 'string' || !/^[A-Z]{3}$/.test(currency)
|
|
1542
|
+
|| !relayFeeMultiplierValid(feeMultiplier)
|
|
1543
|
+
|| !relayBalanceDivisorValid(balanceDivisor)
|
|
1544
|
+
|| !Array.isArray(names) || names.length > RELAY_HEADER_LIMIT) return null
|
|
1545
|
+
const seen = new Set()
|
|
1546
|
+
for (const name of names) {
|
|
1547
|
+
if (!relayHeaderNameValid(name)) return null
|
|
1548
|
+
const lower = name.toLowerCase()
|
|
1549
|
+
if (seen.has(lower) || lower === tokenHeader.toLowerCase() || lower === userIdHeader.toLowerCase()) return null
|
|
1550
|
+
seen.add(lower)
|
|
1551
|
+
}
|
|
1552
|
+
return {
|
|
1553
|
+
channelKey,
|
|
1554
|
+
endpoint,
|
|
1555
|
+
tokenHeader,
|
|
1556
|
+
userIdHeader,
|
|
1557
|
+
tokenPrefix,
|
|
1558
|
+
balancePath,
|
|
1559
|
+
currency,
|
|
1560
|
+
feeMultiplier,
|
|
1561
|
+
balanceDivisor,
|
|
1562
|
+
headerNames: names.slice(),
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
function readRelayConfig() {
|
|
1567
|
+
let raw
|
|
1568
|
+
try {
|
|
1569
|
+
raw = JSON.parse(readFileSync(relayConfigPath(), 'utf8'))
|
|
1570
|
+
} catch (error) {
|
|
1571
|
+
if (error !== null && error.code === 'ENOENT') return { version: RELAY_CONFIG_VERSION, channels: [] }
|
|
1572
|
+
return null
|
|
1573
|
+
}
|
|
1574
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)
|
|
1575
|
+
|| raw.version !== RELAY_CONFIG_VERSION || !Array.isArray(raw.channels)
|
|
1576
|
+
|| Object.keys(raw).some((key) => key !== 'version' && key !== 'channels')) return null
|
|
1577
|
+
const channels = []
|
|
1578
|
+
const channelKeys = new Set()
|
|
1579
|
+
let hasMagpie = false
|
|
1580
|
+
const configKeys = new Set([
|
|
1581
|
+
'channelKey', 'endpoint', 'tokenHeader', 'userIdHeader', 'tokenPrefix',
|
|
1582
|
+
'balancePath', 'currency', 'feeMultiplier', 'balanceDivisor', 'headerNames',
|
|
1583
|
+
])
|
|
1584
|
+
for (const item of raw.channels) {
|
|
1585
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)
|
|
1586
|
+
|| !relayChannelKeyValid(item.channelKey)) return null
|
|
1587
|
+
if (channelKeys.has(item.channelKey)) return null
|
|
1588
|
+
channelKeys.add(item.channelKey)
|
|
1589
|
+
if (relayIsMagpie(item.channelKey)) {
|
|
1590
|
+
if (hasMagpie === true || !relayFeeMultiplierValid(item.feeMultiplier)
|
|
1591
|
+
|| Object.keys(item).some((key) => key !== 'channelKey' && key !== 'feeMultiplier')) return null
|
|
1592
|
+
hasMagpie = true
|
|
1593
|
+
channels.push({ channelKey: item.channelKey, feeMultiplier: item.feeMultiplier })
|
|
1594
|
+
continue
|
|
1595
|
+
}
|
|
1596
|
+
if (Object.keys(item).some((key) => !configKeys.has(key))) return null
|
|
1597
|
+
const config = relaySettings(item, null, item.headerNames)
|
|
1598
|
+
if (config === null) return null
|
|
1599
|
+
channels.push(config)
|
|
1600
|
+
}
|
|
1601
|
+
return { version: RELAY_CONFIG_VERSION, channels }
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
function relayFeeConfig() {
|
|
1605
|
+
const currentPath = relayConfigPath()
|
|
1606
|
+
if (relayFeeConfigCache === undefined || relayFeeConfigCachePath !== currentPath) {
|
|
1607
|
+
relayFeeConfigCache = readRelayConfig()
|
|
1608
|
+
relayFeeConfigCachePath = currentPath
|
|
1609
|
+
}
|
|
1610
|
+
return relayFeeConfigCache
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
function relayFeeMultiplierFromConfig(provider, config) {
|
|
1614
|
+
if (typeof provider !== 'string' || provider.length === 0 || config === null) return 1
|
|
1615
|
+
const channel = config.channels.find((one) => one.channelKey === provider)
|
|
1616
|
+
return channel !== undefined && relayFeeMultiplierValid(channel.feeMultiplier) ? channel.feeMultiplier : 1
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
function relayFeeMultiplierForProvider(provider) {
|
|
1620
|
+
return relayFeeMultiplierFromConfig(provider, relayFeeConfig())
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
/* ------------------------------------------------------------------ provider 归属 */
|
|
1624
|
+
/* 官方 API 域名白名单:这些 baseURL 视为官方;本机/localhost/其它自定义域名视为第三方中转。 */
|
|
1625
|
+
const OFFICIAL_PROVIDER_HOSTS = [
|
|
1626
|
+
'api.deepseek.com', 'api.openai.com', 'api.anthropic.com', 'generativelanguage.googleapis.com',
|
|
1627
|
+
'api.moonshot.cn', 'dashscope.aliyuncs.com', 'open.bigmodel.cn', 'api.x.ai',
|
|
1628
|
+
'api.minimax.chat', 'api.stepfun.com', 'api.mistral.ai',
|
|
1629
|
+
]
|
|
1630
|
+
let providerBaseUrlCache = null
|
|
1631
|
+
|
|
1632
|
+
/** 从 cordis.patch.yml 文本里抽取 llm-pi-ai.providers.<name>.baseURL。 */
|
|
1633
|
+
function parseProviderBaseUrlsFromPatch(text) {
|
|
1634
|
+
const out = {}
|
|
1635
|
+
const lines = String(text).split(/\r?\n/)
|
|
1636
|
+
let inLlm = false
|
|
1637
|
+
let llmIndent = -1
|
|
1638
|
+
let providersIndent = -1
|
|
1639
|
+
let current = null
|
|
1640
|
+
let currentIndent = -1
|
|
1641
|
+
for (const rawLine of lines) {
|
|
1642
|
+
const line = rawLine.replace(/\s+#.*$/, '')
|
|
1643
|
+
if (line.trim().length === 0) continue
|
|
1644
|
+
const indent = (line.match(/^[ \t]*/) || [''])[0].length
|
|
1645
|
+
const trimmed = line.trim()
|
|
1646
|
+
if (trimmed.startsWith("- ")) {
|
|
1647
|
+
if (inLlm !== true || indent <= llmIndent) {
|
|
1648
|
+
const idLine = trimmed.slice(2).trim()
|
|
1649
|
+
if (/^id:\s*llm-pi-ai(?:$|\s)/.test(idLine)) {
|
|
1650
|
+
inLlm = true; llmIndent = indent; providersIndent = -1; current = null; currentIndent = -1
|
|
1651
|
+
} else {
|
|
1652
|
+
inLlm = false; providersIndent = -1; current = null; currentIndent = -1
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
continue
|
|
1656
|
+
}
|
|
1657
|
+
if (inLlm !== true) continue
|
|
1658
|
+
if (providersIndent < 0) {
|
|
1659
|
+
if (trimmed === 'providers:') { providersIndent = indent; current = null; currentIndent = -1 }
|
|
1660
|
+
continue
|
|
1661
|
+
}
|
|
1662
|
+
if (indent <= providersIndent) { inLlm = false; providersIndent = -1; current = null; currentIndent = -1; continue }
|
|
1663
|
+
if (current === null) {
|
|
1664
|
+
const m = /^([A-Za-z0-9_.-]+):\s*$/.exec(trimmed)
|
|
1665
|
+
if (m !== null) { current = m[1]; currentIndent = indent }
|
|
1666
|
+
continue
|
|
1667
|
+
}
|
|
1668
|
+
if (indent <= currentIndent) {
|
|
1669
|
+
const m = /^([A-Za-z0-9_.-]+):\s*$/.exec(trimmed)
|
|
1670
|
+
if (m !== null) { current = m[1]; currentIndent = indent; continue }
|
|
1671
|
+
current = null; currentIndent = -1; continue
|
|
1672
|
+
}
|
|
1673
|
+
const b = /^baseURL:\s*(.*)$/.exec(trimmed)
|
|
1674
|
+
if (b !== null) {
|
|
1675
|
+
let value = b[1].trim()
|
|
1676
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1)
|
|
1677
|
+
out[current] = value
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
return out
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* 当前 profile 的目录:优先环境变量(Host 启动时会设 DSH_PROFILE_DIR / DSH_PROFILE),
|
|
1684
|
+
* 其次从插件自身安装路径反推(`<profile>/node_modules/<包名>`),都没有就返回 null。
|
|
1685
|
+
*/
|
|
1686
|
+
function currentProfileDir() {
|
|
1687
|
+
const home = dshHome()
|
|
1688
|
+
const fromEnv = typeof process.env.DSH_PROFILE_DIR === 'string' && process.env.DSH_PROFILE_DIR.length > 0
|
|
1689
|
+
? process.env.DSH_PROFILE_DIR
|
|
1690
|
+
: null
|
|
1691
|
+
/* 只在 DSH_PROFILE_DIR 确实位于当前 DSH_HOME 下时才采信:测试/沙箱会改写 DSH_HOME
|
|
1692
|
+
而进程环境里仍留着真实 profile 路径,若采信它就会读到别的 profile 的配置。
|
|
1693
|
+
必须按路径分隔符边界判断:`/home/user2` 不是 `/home/user` 的子目录。 */
|
|
1694
|
+
if (fromEnv !== null) {
|
|
1695
|
+
const homeBase = home.length > 1 && home.endsWith(sep) ? home.slice(0, -1) : home
|
|
1696
|
+
const lowerHome = homeBase.toLowerCase()
|
|
1697
|
+
const lowerEnv = fromEnv.toLowerCase()
|
|
1698
|
+
if (lowerEnv === lowerHome || lowerEnv.startsWith(lowerHome + sep.toLowerCase())) return fromEnv
|
|
1699
|
+
}
|
|
1700
|
+
try {
|
|
1701
|
+
const selfDir = resolveSelfDir()
|
|
1702
|
+
let current = dirname(selfDir)
|
|
1703
|
+
for (let level = 0; level < 6; level += 1) {
|
|
1704
|
+
if (basename(dirname(current)) === 'profiles') return current
|
|
1705
|
+
const parent = dirname(current)
|
|
1706
|
+
if (parent === current) break
|
|
1707
|
+
current = parent
|
|
1708
|
+
}
|
|
1709
|
+
} catch (error) { /* 解析不到安装路径时退回环境变量 */ }
|
|
1710
|
+
const name = typeof process.env.DSH_PROFILE === 'string' && process.env.DSH_PROFILE.length > 0
|
|
1711
|
+
? process.env.DSH_PROFILE
|
|
1712
|
+
: null
|
|
1713
|
+
return name === null ? null : join(dshHome(), 'profiles', name)
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
function providerPatchFiles() {
|
|
1717
|
+
const files = []
|
|
1718
|
+
const seen = new Set()
|
|
1719
|
+
const push = (file) => {
|
|
1720
|
+
if (typeof file !== 'string' || file.length === 0) return
|
|
1721
|
+
const key = file.toLowerCase()
|
|
1722
|
+
if (seen.has(key) === true) return
|
|
1723
|
+
seen.add(key)
|
|
1724
|
+
files.push(file)
|
|
1725
|
+
}
|
|
1726
|
+
/* 当前 profile 的补丁优先:多 profile 下同名 provider 可能各有各的 baseURL,
|
|
1727
|
+
绝不能把别的 profile 的值读进来(那会把 A profile 的 relay 当成 B profile 的官方地址)。 */
|
|
1728
|
+
const profileDir = currentProfileDir()
|
|
1729
|
+
if (profileDir !== null) push(join(profileDir, 'cordis.patch.yml'))
|
|
1730
|
+
/* 插件自身包根那一份(从安装路径反推)作为兜底;与 profile 目录同一份时自动去重。 */
|
|
1731
|
+
try {
|
|
1732
|
+
const selfDir = resolveSelfDir()
|
|
1733
|
+
push(join(dirname(dirname(selfDir)), 'cordis.patch.yml'))
|
|
1734
|
+
} catch (error) { /* 解析不到包根时只靠 profile 兜底 */ }
|
|
1735
|
+
return files
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
function providerBaseUrls() {
|
|
1739
|
+
if (providerBaseUrlCache !== null) return providerBaseUrlCache
|
|
1740
|
+
const out = {}
|
|
1741
|
+
const conflicts = []
|
|
1742
|
+
const files = providerPatchFiles()
|
|
1743
|
+
for (const file of files) {
|
|
1744
|
+
let parsed = null
|
|
1745
|
+
try { parsed = parseProviderBaseUrlsFromPatch(readFileSync(file, "utf8")) } catch (error) { continue }
|
|
1746
|
+
for (const key of Object.keys(parsed)) {
|
|
1747
|
+
const value = parsed[key]
|
|
1748
|
+
const hasOwn = Object.prototype.hasOwnProperty.call(out, key)
|
|
1749
|
+
if (hasOwn === true && out[key] !== value) {
|
|
1750
|
+
/* 同名 provider 两个来源给了不同 baseURL:保留先读到的(当前 profile 优先),记日志排查。 */
|
|
1751
|
+
conflicts.push(key + ': ' + String(out[key]) + ' ≠ ' + String(value) + '(' + file + ')')
|
|
1752
|
+
continue
|
|
1753
|
+
}
|
|
1754
|
+
out[key] = value
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
if (conflicts.length > 0) {
|
|
1758
|
+
logHost(ctxRef, 'provider-base-url: 同名 provider 配置冲突,已保留当前 profile 的值:' + conflicts.join(';'))
|
|
1759
|
+
}
|
|
1760
|
+
providerBaseUrlCache = out
|
|
1761
|
+
return out
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
function providerBaseUrlOf(provider) {
|
|
1765
|
+
const map = providerBaseUrls()
|
|
1766
|
+
if (typeof provider !== 'string' || provider.length === 0) return undefined
|
|
1767
|
+
if (Object.prototype.hasOwnProperty.call(map, provider)) return map[provider]
|
|
1768
|
+
const lower = provider.toLowerCase()
|
|
1769
|
+
const key = Object.keys(map).find((one) => {
|
|
1770
|
+
const k = one.toLowerCase()
|
|
1771
|
+
return lower === k || lower.includes('/' + k) || lower.startsWith(k + '/') || lower.includes('-' + k)
|
|
1772
|
+
})
|
|
1773
|
+
return key === undefined ? undefined : map[key]
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
function isLocalProviderHost(host) {
|
|
1777
|
+
return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '0.0.0.0' || host.endsWith('.localhost')
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
function isOfficialProviderBaseUrl(value) {
|
|
1781
|
+
let host = ''
|
|
1782
|
+
try { host = new URL(String(value)).hostname.toLowerCase() } catch (error) { return false }
|
|
1783
|
+
if (host.length === 0 || isLocalProviderHost(host) === true) return false
|
|
1784
|
+
return OFFICIAL_PROVIDER_HOSTS.some((domain) => host === domain || host.endsWith('.' + domain))
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
/**
|
|
1788
|
+
* 第三方中转的 provider 名兜底:这些名字即使配置表读不到(换 profile、升级后配置未同步、
|
|
1789
|
+
* 老日志里 provider 只剩短名)也必须按 relay 计价,绝不能静默回落到官方价。
|
|
1790
|
+
* Magpie 是本机网关、orbi/orbis 是外部中转站;WorkBuddy / Qoder 走上面的 points 分支。
|
|
1791
|
+
*/
|
|
1792
|
+
const RELAY_PROVIDER_HINT = /^(?:remote-magpie|magpie|magpie-anthropic|orbi|orbis)(?:[-_/].*)?$/i
|
|
1793
|
+
/**
|
|
1794
|
+
* 第三方中转的模型命名空间:`remote-magpie/...` 是 Magpie 网关的模型标识,
|
|
1795
|
+
* `orbi/...` / `orbis/...` 是 Orbi 中转的模型标识。老日志里 provider 可能为空,
|
|
1796
|
+
* 只靠 baseURL 查不到,必须按模型前缀兜底判 relay。WorkBuddy 的
|
|
1797
|
+
* `remote-magpie/workbuddy/...` 已在 points 分支优先拦下,不会被这里误判。
|
|
1798
|
+
*/
|
|
1799
|
+
const RELAY_MODEL_PREFIX = /^(?:remote-magpie|orbis?)\//i
|
|
1800
|
+
|
|
1801
|
+
/** provider 归属:official / points / relay(WorkBuddy / CodeBuddy / Qoder 按 provider 或模型标识判定)。 */
|
|
1802
|
+
function providerAffiliation(provider, model) {
|
|
1803
|
+
const providerText = String(provider === undefined || provider === null ? '' : provider)
|
|
1804
|
+
const modelText = String(model === undefined || model === null ? '' : model)
|
|
1805
|
+
const hint = providerText + '\n' + modelText
|
|
1806
|
+
if (/workbuddy|codebuddy|qoder/i.test(hint) === true) return "points"
|
|
1807
|
+
/* 模型命名空间、provider 短名是 baseURL 配置之外的第二道判据:
|
|
1808
|
+
老日志 provider 为空 / 换 profile 后配置缺失时,仍能把第三方中转认出来。 */
|
|
1809
|
+
if (RELAY_MODEL_PREFIX.test(modelText) === true) return 'relay'
|
|
1810
|
+
if (RELAY_PROVIDER_HINT.test(providerText) === true) return 'relay'
|
|
1811
|
+
const base = providerBaseUrlOf(provider)
|
|
1812
|
+
if (base === undefined || base === null || String(base).trim().length === 0) return 'official'
|
|
1813
|
+
return isOfficialProviderBaseUrl(base) ? 'official' : 'relay'
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
function relayFeeFingerprint() {
|
|
1817
|
+
const config = relayFeeConfig()
|
|
1818
|
+
if (config === null) return 'invalid'
|
|
1819
|
+
return JSON.stringify(config.channels.map((one) => [one.channelKey, one.feeMultiplier]))
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
function writeRelayConfig(config) {
|
|
1823
|
+
const file = relayConfigPath()
|
|
1824
|
+
const dir = dirname(file)
|
|
1825
|
+
const temp = file + '.' + String(process.pid) + '.' + String(++relayConfigWriteSeq) + '.tmp'
|
|
1826
|
+
mkdirSync(dir, { recursive: true })
|
|
1827
|
+
try {
|
|
1828
|
+
writeFileSync(temp, JSON.stringify(config), 'utf8')
|
|
1829
|
+
renameSync(temp, file)
|
|
1830
|
+
relayFeeConfigCache = config
|
|
1831
|
+
relayFeeConfigCachePath = file
|
|
1832
|
+
} catch (error) {
|
|
1833
|
+
try { unlinkSync(temp) } catch (nested) { /* best effort */ }
|
|
1834
|
+
throw error
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
function relayCredentials(ctx) {
|
|
1839
|
+
const service = ctx !== null && ctx !== undefined ? ctx.credentials : null
|
|
1840
|
+
return service !== null && service !== undefined
|
|
1841
|
+
&& typeof service.resolve === 'function' && typeof service.set === 'function'
|
|
1842
|
+
&& typeof service.unset === 'function' ? service : null
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
async function resolveRelaySecrets(ctx, channelKey) {
|
|
1846
|
+
const service = relayCredentials(ctx)
|
|
1847
|
+
if (service === null || !relayChannelKeyValid(channelKey) || relayIsMagpie(channelKey)) return null
|
|
1848
|
+
const hit = await service.resolve(relaySecretRef(channelKey))
|
|
1849
|
+
if (hit === undefined || hit === null) return { token: '', userId: '', headers: {} }
|
|
1850
|
+
if (typeof hit.value !== 'string') return null
|
|
1851
|
+
try {
|
|
1852
|
+
const parsed = JSON.parse(hit.value)
|
|
1853
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)
|
|
1854
|
+
|| typeof parsed.token !== 'string' || typeof parsed.userId !== 'string'
|
|
1855
|
+
|| parsed.headers === null || typeof parsed.headers !== 'object' || Array.isArray(parsed.headers)
|
|
1856
|
+
|| Object.keys(parsed).some((key) => !['token', 'userId', 'headers'].includes(key))) return null
|
|
1857
|
+
const headers = {}
|
|
1858
|
+
const seen = new Set()
|
|
1859
|
+
for (const name of Object.keys(parsed.headers)) {
|
|
1860
|
+
const value = parsed.headers[name]
|
|
1861
|
+
const lower = name.toLowerCase()
|
|
1862
|
+
if (!relayHeaderNameValid(name) || seen.has(lower) || typeof value !== 'string'
|
|
1863
|
+
|| value.length > 4096 || /[\r\n\0]/.test(value)) return null
|
|
1864
|
+
seen.add(lower)
|
|
1865
|
+
headers[name] = value
|
|
1866
|
+
}
|
|
1867
|
+
if (Object.keys(headers).length > RELAY_HEADER_LIMIT
|
|
1868
|
+
|| parsed.token.length > 8192 || /[\r\n\0]/.test(parsed.token)
|
|
1869
|
+
|| parsed.userId.length > 256 || /[\r\n\0]/.test(parsed.userId)) return null
|
|
1870
|
+
return { token: parsed.token, userId: parsed.userId, headers }
|
|
1871
|
+
} catch (error) {
|
|
1872
|
+
return null
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
|
|
1876
|
+
async function storeRelaySecrets(ctx, channelKey, secrets) {
|
|
1877
|
+
const service = relayCredentials(ctx)
|
|
1878
|
+
if (service === null) throw new Error('credential-unavailable')
|
|
1879
|
+
const ref = relaySecretRef(channelKey)
|
|
1880
|
+
/* Store an explicit empty envelope: unset would reveal ambient env/.env fallbacks. */
|
|
1881
|
+
const tombstone = {
|
|
1882
|
+
token: typeof secrets.token === 'string' ? secrets.token : '',
|
|
1883
|
+
userId: typeof secrets.userId === 'string' ? secrets.userId : '',
|
|
1884
|
+
headers: secrets.headers !== null && typeof secrets.headers === 'object' && !Array.isArray(secrets.headers)
|
|
1885
|
+
? secrets.headers
|
|
1886
|
+
: {},
|
|
1887
|
+
}
|
|
1888
|
+
await service.set(ref, JSON.stringify(tombstone))
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
function sanitizeRelayHeaders(input) {
|
|
1892
|
+
if (input === null) return {}
|
|
1893
|
+
if (input === undefined || typeof input !== 'object' || Array.isArray(input)
|
|
1894
|
+
|| Object.keys(input).length > RELAY_HEADER_LIMIT) return null
|
|
1895
|
+
const out = {}
|
|
1896
|
+
const seen = new Set()
|
|
1897
|
+
for (const name of Object.keys(input)) {
|
|
1898
|
+
const value = input[name]
|
|
1899
|
+
const lower = name.toLowerCase()
|
|
1900
|
+
if (!relayHeaderNameValid(name) || seen.has(lower) || typeof value !== 'string'
|
|
1901
|
+
|| value.length > 4096 || /[\r\n\0]/.test(value)) return null
|
|
1902
|
+
seen.add(lower)
|
|
1903
|
+
out[name] = value
|
|
1904
|
+
}
|
|
1905
|
+
return out
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
async function relayConfigView(ctx, channels) {
|
|
1909
|
+
const visible = []
|
|
1910
|
+
for (const config of channels) {
|
|
1911
|
+
if (relayIsMagpie(config.channelKey)) {
|
|
1912
|
+
visible.push({ channelKey: config.channelKey, feeMultiplier: config.feeMultiplier })
|
|
1913
|
+
continue
|
|
1914
|
+
}
|
|
1915
|
+
const secrets = await resolveRelaySecrets(ctx, config.channelKey)
|
|
1916
|
+
if (secrets === null) throw new Error('credential-unavailable')
|
|
1917
|
+
visible.push({
|
|
1918
|
+
channelKey: config.channelKey,
|
|
1919
|
+
endpoint: config.endpoint,
|
|
1920
|
+
tokenHeader: config.tokenHeader,
|
|
1921
|
+
userIdHeader: config.userIdHeader,
|
|
1922
|
+
tokenPrefix: config.tokenPrefix,
|
|
1923
|
+
balancePath: config.balancePath,
|
|
1924
|
+
currency: config.currency,
|
|
1925
|
+
feeMultiplier: config.feeMultiplier,
|
|
1926
|
+
balanceDivisor: config.balanceDivisor,
|
|
1927
|
+
headerNames: config.headerNames.slice(),
|
|
1928
|
+
tokenConfigured: secrets.token.length > 0,
|
|
1929
|
+
userIdConfigured: secrets.userId.length > 0,
|
|
1930
|
+
})
|
|
1931
|
+
}
|
|
1932
|
+
return { ok: true, channels: visible }
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
function queueRelayConfigWrite(operation) {
|
|
1936
|
+
const result = relayConfigWriteTail.then(operation, operation)
|
|
1937
|
+
relayConfigWriteTail = result.then(() => undefined, () => undefined)
|
|
1938
|
+
return result
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
async function readLimitedRelayJson(response) {
|
|
1942
|
+
const declared = Number(response.headers.get('content-length'))
|
|
1943
|
+
if (Number.isFinite(declared) && declared > RELAY_RESPONSE_LIMIT) throw new Error('response-too-large')
|
|
1944
|
+
if (response.body === null || typeof response.body.getReader !== 'function') throw new Error('missing-response-body')
|
|
1945
|
+
const reader = response.body.getReader()
|
|
1946
|
+
const chunks = []
|
|
1947
|
+
let size = 0
|
|
1948
|
+
try {
|
|
1949
|
+
for (;;) {
|
|
1950
|
+
const part = await reader.read()
|
|
1951
|
+
if (part.done === true) break
|
|
1952
|
+
size += part.value.byteLength
|
|
1953
|
+
if (size > RELAY_RESPONSE_LIMIT) {
|
|
1954
|
+
await reader.cancel()
|
|
1955
|
+
throw new Error('response-too-large')
|
|
1956
|
+
}
|
|
1957
|
+
chunks.push(Buffer.from(part.value))
|
|
1958
|
+
}
|
|
1959
|
+
} finally {
|
|
1960
|
+
reader.releaseLock()
|
|
1961
|
+
}
|
|
1962
|
+
return JSON.parse(Buffer.concat(chunks, size).toString('utf8'))
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
async function queryRelayBalance(ctx, config, now) {
|
|
1966
|
+
const secrets = await resolveRelaySecrets(ctx, config.channelKey)
|
|
1967
|
+
if (secrets === null) return { ok: false, at: now, reason: 'credential-unavailable', provider: config.channelKey }
|
|
1968
|
+
const headers = new Headers({ accept: 'application/json' })
|
|
1969
|
+
for (const name of Object.keys(secrets.headers)) headers.set(name, secrets.headers[name])
|
|
1970
|
+
if (secrets.token.length > 0) headers.set(config.tokenHeader, config.tokenPrefix + secrets.token)
|
|
1971
|
+
if (secrets.userId.length > 0) headers.set(config.userIdHeader, secrets.userId)
|
|
1972
|
+
try {
|
|
1973
|
+
const response = await fetch(config.endpoint, {
|
|
1974
|
+
method: 'GET',
|
|
1975
|
+
headers,
|
|
1976
|
+
redirect: 'manual',
|
|
1977
|
+
signal: AbortSignal.timeout(BALANCE_FETCH_TIMEOUT_MS),
|
|
1978
|
+
})
|
|
1979
|
+
if (response.status >= 300 && response.status < 400) return { ok: false, at: now, reason: 'redirect-not-allowed', provider: config.channelKey }
|
|
1980
|
+
if (!response.ok) return { ok: false, at: now, reason: 'upstream-http-error', provider: config.channelKey }
|
|
1981
|
+
const data = await readLimitedRelayJson(response)
|
|
1982
|
+
const raw = relayValueAt(data, relayPathSegments(config.balancePath))
|
|
1983
|
+
const parsed = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim().length > 0 ? Number(raw) : NaN
|
|
1984
|
+
if (!Number.isFinite(parsed)) return { ok: false, at: now, reason: 'invalid-balance', provider: config.channelKey }
|
|
1985
|
+
/* 只做单位换算,不乘费用倍率:余额是账上真实金额,不是计费口径。 */
|
|
1986
|
+
const amount = parsed / config.balanceDivisor
|
|
1987
|
+
return {
|
|
1988
|
+
ok: true,
|
|
1989
|
+
at: now,
|
|
1990
|
+
source: 'relay',
|
|
1991
|
+
provider: config.channelKey,
|
|
1992
|
+
currency: config.currency,
|
|
1993
|
+
total: formatBalanceAmount(amount),
|
|
1994
|
+
feeMultiplier: config.feeMultiplier,
|
|
1995
|
+
parts: [],
|
|
1996
|
+
available: true,
|
|
1997
|
+
}
|
|
1998
|
+
} catch (error) {
|
|
1999
|
+
return { ok: false, at: now, reason: 'relay-request-failed', provider: config.channelKey }
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
|
|
1279
2003
|
/** 环境变量是最高优先级的来源;refName 为空时按 DeepSeek 的引用名。 */
|
|
1280
2004
|
function keyFromEnv(refName) {
|
|
1281
2005
|
const name = typeof refName === 'string' && refName.length > 0 ? refName : 'DEEPSEEK_API_KEY'
|
|
@@ -1843,16 +2567,44 @@ function pickChainHit(ctx, targets, now) {
|
|
|
1843
2567
|
|
|
1844
2568
|
/* force 目前不改变行为(余额不缓存,每次请求都现查),但客户端点开气泡时会带 force=1
|
|
1845
2569
|
表达"强制刷新",保留该形参以维持 HTTP 契约,避免为省一个参数去动客户端回调。 */
|
|
1846
|
-
async function queryBalance(ctx, force, provider, model) {
|
|
2570
|
+
async function queryBalance(ctx, force, provider, model, relay) {
|
|
1847
2571
|
const now = Date.now()
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
2572
|
+
const hasProvider = typeof provider === 'string' && provider.trim().length > 0
|
|
2573
|
+
if (typeof provider === 'string' && relayIsMagpie(provider)) {
|
|
2574
|
+
return { ok: false, at: now, reason: 'unsupported-provider', provider }
|
|
2575
|
+
}
|
|
2576
|
+
/* relay 指向 Magpie 类平台:无法可靠知道上游走的是哪个模型,直接返回横杠口径(不查任何通道)。 */
|
|
2577
|
+
if (typeof relay === 'string' && relayIsMagpie(relay)) {
|
|
2578
|
+
return { ok: false, at: now, reason: 'unsupported-provider', provider: relay }
|
|
2579
|
+
}
|
|
2580
|
+
/* 第三方平台档案:channelKey 是**平台名**(一个平台一条,可被多个模型复用)。
|
|
2581
|
+
查找顺序 relay → provider → model;非法/找不到的档位直接跳过、走下一档与原逻辑。
|
|
2582
|
+
Magpie 通道永远不查余额(上面已拦 provider,这里再挡配置键)。 */
|
|
2583
|
+
const hasRelay = typeof relay === 'string' && relay.trim().length > 0
|
|
2584
|
+
if (hasProvider === true || hasRelay === true) {
|
|
2585
|
+
const relayConfig = readRelayConfig()
|
|
2586
|
+
const channels = relayConfig === null ? [] : relayConfig.channels
|
|
2587
|
+
const usable = (one) => one !== undefined && relayIsMagpie(one.channelKey) !== true
|
|
2588
|
+
const exact = (key) => (typeof key === 'string' && key.trim().length > 0
|
|
2589
|
+
? channels.find((one) => one.channelKey === key)
|
|
2590
|
+
: undefined)
|
|
2591
|
+
const byRelay = exact(relay)
|
|
2592
|
+
if (usable(byRelay) === true) return queryRelayBalance(ctx, byRelay, now)
|
|
2593
|
+
const byProvider = exact(provider)
|
|
2594
|
+
if (usable(byProvider) === true) return queryRelayBalance(ctx, byProvider, now)
|
|
2595
|
+
/* 模型名回退:先精确,再按紧凑串宽容匹配(前缀/分隔符写法不同也能命中同一模型)。 */
|
|
2596
|
+
let byModel = exact(model)
|
|
2597
|
+
if (usable(byModel) !== true && typeof model === 'string' && model.trim().length > 0) {
|
|
2598
|
+
const compact = compactModelName(model)
|
|
2599
|
+
byModel = compact.length > 0
|
|
2600
|
+
? channels.find((one) => relayIsMagpie(one.channelKey) !== true && compactModelName(one.channelKey) === compact)
|
|
2601
|
+
: undefined
|
|
2602
|
+
}
|
|
2603
|
+
if (usable(byModel) === true) return queryRelayBalance(ctx, byModel, now)
|
|
2604
|
+
}
|
|
2605
|
+
|
|
2606
|
+
/* A known provider is matched only by its provider name. Model fallback is reserved for missing provider. */
|
|
2607
|
+
const chain = hasProvider ? adaptersFor(provider, '') : adaptersFor(provider, model)
|
|
1856
2608
|
const adapter = chain.length > 0 ? chain[0] : null
|
|
1857
2609
|
if (adapter !== null && adapter.local === true) {
|
|
1858
2610
|
const local = await queryLocalAdapter(ctx, adapter, now, provider)
|
|
@@ -1877,7 +2629,6 @@ async function queryBalance(ctx, force, provider, model) {
|
|
|
1877
2629
|
|
|
1878
2630
|
/* 会话明确在用别的平台、但这个平台认不出来时不硬凑:硬凑会把 DeepSeek 的余额
|
|
1879
2631
|
当成对方的余额显示(比不显示更误导)。provider 还没上报(空)时才按 DeepSeek 处理。 */
|
|
1880
|
-
const hasProvider = typeof provider === 'string' && provider.trim().length > 0
|
|
1881
2632
|
if (adapter === null && hasProvider) {
|
|
1882
2633
|
const unknown = { ok: false, at: now, reason: 'unknown-platform' }
|
|
1883
2634
|
logHost(ctx, 'balance: 认不出 ' + provider + ' 属于哪个平台,不显示余额')
|
|
@@ -1921,9 +2672,11 @@ async function queryBalance(ctx, force, provider, model) {
|
|
|
1921
2672
|
logHost(ctx, 'balance: 使用来源 ' + String(found.source) + ' 的 key 查询余额')
|
|
1922
2673
|
|
|
1923
2674
|
try {
|
|
1924
|
-
|
|
2675
|
+
/* 端点与鉴权头也取自 adapter:request 与 parse 都只有一份实现,避免两处漂移。 */
|
|
2676
|
+
const spec = deepseekAdapter.request(found.key)
|
|
2677
|
+
const response = await fetch(spec.url, {
|
|
1925
2678
|
method: 'GET',
|
|
1926
|
-
headers:
|
|
2679
|
+
headers: spec.headers,
|
|
1927
2680
|
signal: AbortSignal.timeout(BALANCE_FETCH_TIMEOUT_MS),
|
|
1928
2681
|
})
|
|
1929
2682
|
if (!response.ok) {
|
|
@@ -1932,52 +2685,38 @@ async function queryBalance(ctx, force, provider, model) {
|
|
|
1932
2685
|
return failed
|
|
1933
2686
|
}
|
|
1934
2687
|
const data = await response.json()
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
const
|
|
1938
|
-
|
|
1939
|
-
if (picked === undefined) {
|
|
2688
|
+
/* 与 balance-api.js 的 deepseek adapter 共用同一份解析:两份实现漂移过一次,
|
|
2689
|
+
测试打 adapter 那份、生产走这份,绿了也不能证明线上正确。 */
|
|
2690
|
+
const parsed = parseDeepSeekBalance(data)
|
|
2691
|
+
if (parsed === null) {
|
|
1940
2692
|
const empty = { ok: false, at: now, reason: 'no-balance-info', source: found.source }
|
|
1941
2693
|
logHost(ctx, 'balance: 响应里没有 balance_infos')
|
|
1942
2694
|
return empty
|
|
1943
2695
|
}
|
|
2696
|
+
const grantedRaw = partAmount(parsed.parts, 'granted')
|
|
2697
|
+
const toppedUpRaw = partAmount(parsed.parts, 'toppedUp')
|
|
1944
2698
|
const value = {
|
|
1945
2699
|
ok: true,
|
|
1946
2700
|
at: now,
|
|
1947
2701
|
source: found.source,
|
|
1948
|
-
currency:
|
|
2702
|
+
currency: parsed.currency,
|
|
1949
2703
|
/* 与账号服务那条路同一套显示规则:截断到分,不足一分单独标出 */
|
|
1950
|
-
total: formatBalanceAmount(
|
|
1951
|
-
subCent: Number(
|
|
1952
|
-
granted:
|
|
1953
|
-
toppedUp:
|
|
2704
|
+
total: formatBalanceAmount(parsed.total),
|
|
2705
|
+
subCent: Number(parsed.total) > 0 && Number(parsed.total) < 0.01,
|
|
2706
|
+
granted: grantedRaw === undefined ? '0.00' : formatBalanceAmount(grantedRaw),
|
|
2707
|
+
toppedUp: toppedUpRaw === undefined ? '0.00' : formatBalanceAmount(toppedUpRaw),
|
|
1954
2708
|
available: data.is_available === true,
|
|
1955
2709
|
/* 分币种余额:DeepSeek 的 balance_infos 里可能同时有 CNY 和 USD。
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
/* 每笔也带上**自己的**充值与赠金(顶层 toppedUp/granted 只取第一笔的历史口径不动):
|
|
1967
|
-
客户端要把两个币种各自折成同一币种后相加,才能算出「充值 : 赠金」的真实比例。
|
|
1968
|
-
取不到就给 '0.00' —— 不给 undefined,客户端少一层判断。
|
|
1969
|
-
格式化与顶层一致(截断到分),保证两处数字口径相同。 */
|
|
1970
|
-
list.push({
|
|
1971
|
-
currency: info.currency === 'USD' ? 'USD' : 'CNY',
|
|
1972
|
-
total: String(info.total_balance),
|
|
1973
|
-
toppedUp: info.topped_up_balance === undefined || info.topped_up_balance === null
|
|
1974
|
-
? '0.00' : formatBalanceAmount(info.topped_up_balance),
|
|
1975
|
-
granted: info.granted_balance === undefined || info.granted_balance === null
|
|
1976
|
-
? '0.00' : formatBalanceAmount(info.granted_balance),
|
|
1977
|
-
})
|
|
1978
|
-
}
|
|
1979
|
-
return list.length === 0 ? undefined : list
|
|
1980
|
-
})(),
|
|
2710
|
+
老字段语义不变;这里额外给底栏拼「¥14.12+$3.17」用。
|
|
2711
|
+
只收 total > 0 的(0 与负数都不进 —— 用户拍板「负数也不显示」)。 */
|
|
2712
|
+
balances: Array.isArray(parsed.balances)
|
|
2713
|
+
? parsed.balances.map((one) => ({
|
|
2714
|
+
currency: one.currency === 'USD' ? 'USD' : 'CNY',
|
|
2715
|
+
total: one.total,
|
|
2716
|
+
toppedUp: formatBalanceAmount(one.toppedUp),
|
|
2717
|
+
granted: formatBalanceAmount(one.granted),
|
|
2718
|
+
}))
|
|
2719
|
+
: undefined,
|
|
1981
2720
|
}
|
|
1982
2721
|
logHost(ctx, 'balance: OK ' + String(value.total) + ' ' + String(value.currency))
|
|
1983
2722
|
return value
|
|
@@ -2097,6 +2836,18 @@ function tokenMatches(needle, hay) {
|
|
|
2097
2836
|
return needle === hay
|
|
2098
2837
|
}
|
|
2099
2838
|
|
|
2839
|
+
/**
|
|
2840
|
+
* 模型名「紧凑串」:小写 → 取最后一个 `/` 之后(去掉 provider 前缀)→ 只留 [a-z0-9]。
|
|
2841
|
+
* 用于宽容匹配:`remote-magpie/group/claude-opus-5-5` 与价格键 `claude-opus-5.5`
|
|
2842
|
+
* 都归一化成 `claudeopus55`。必须完全相等才算命中 —— `deepseek-v4` 不会命中 `deepseek-v4-pro`。
|
|
2843
|
+
*/
|
|
2844
|
+
function compactModelName(name) {
|
|
2845
|
+
if (typeof name !== 'string') return ''
|
|
2846
|
+
const lower = name.toLowerCase()
|
|
2847
|
+
const slash = lower.lastIndexOf('/')
|
|
2848
|
+
return (slash >= 0 ? lower.slice(slash + 1) : lower).replace(/[^a-z0-9]/g, '')
|
|
2849
|
+
}
|
|
2850
|
+
|
|
2100
2851
|
/** 一条价格是不是"什么都没填":两档四项加起来是 0。用来把未定价的条目挡在匹配之外。 */
|
|
2101
2852
|
function priceIsBlank(entry) {
|
|
2102
2853
|
if (entry === null || entry === undefined || typeof entry !== 'object') return true
|
|
@@ -2141,6 +2892,15 @@ function matchPriceKeyOnce(book, model, skipBlank) {
|
|
|
2141
2892
|
for (let i = 0; i < keys.length; i += 1) {
|
|
2142
2893
|
if (keys[i].toLowerCase() === lower && usable(keys[i])) return keys[i]
|
|
2143
2894
|
}
|
|
2895
|
+
/* ①b 紧凑串完全相等:带 provider 前缀(remote-magpie/group/…)或分隔符写法不同
|
|
2896
|
+
(claude-opus-5-5 vs 5.5)的模型名命中同一价格条目。
|
|
2897
|
+
放在同名词元匹配之前,但用一个更严格的判据(整串相等),不会抢掉更具体的键。 */
|
|
2898
|
+
const compactModel = compactModelName(model)
|
|
2899
|
+
if (compactModel.length > 0) {
|
|
2900
|
+
for (let i = 0; i < keys.length; i += 1) {
|
|
2901
|
+
if (usable(keys[i]) === true && compactModelName(keys[i]) === compactModel) return keys[i]
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2144
2904
|
/* ②③ 一次评选:子串命中的键与词元全含命中的键放在一起比 weight,取最具体的那个。
|
|
2145
2905
|
不能按"先全部子串、再全部词元"两轮跑 —— 那样模型名里只要含一个短键(如 flash),
|
|
2146
2906
|
就会把更具体的 deepseek-flash(只能靠词元档命中)挤掉。
|
|
@@ -2377,6 +3137,9 @@ function sanitizePriceBook(raw) {
|
|
|
2377
3137
|
/* 保留「是否峰谷计价」:没勾的条目是**全天一个价**,计价时两档都要取 peak,
|
|
2378
3138
|
否则空闲时段会挑到那个没填的档、把费用算成 0(实测缺陷)。缺省按两档。 */
|
|
2379
3139
|
const code = entry.currency === 'USD' ? 'USD' : (entry.currency === 'CNY' ? 'CNY' : null)
|
|
3140
|
+
/* 客户端「中转站」按模型填的费用倍率:非法/缺省按 1;feeConfigured 区分「留空」与「明确填 1」。 */
|
|
3141
|
+
const entryFee = relayFeeMultiplierValid(entry.feeMultiplier) ? entry.feeMultiplier : 1
|
|
3142
|
+
const feeConfigured = entry.feeConfigured === true
|
|
2380
3143
|
defineBookEntry(out, names[i], {
|
|
2381
3144
|
peak: peak !== null ? peak : offPeak,
|
|
2382
3145
|
offPeak: offPeak !== null ? offPeak : peak,
|
|
@@ -2387,6 +3150,9 @@ function sanitizePriceBook(raw) {
|
|
|
2387
3150
|
host 不替它决定(否则往返一次多出一个字段,深比较基准会被悄悄改掉)。
|
|
2388
3151
|
注意:必须保留,不保留就等于清洗时把币种丢了。 */
|
|
2389
3152
|
...(code === null ? {} : { currency: code }),
|
|
3153
|
+
...(feeConfigured === true
|
|
3154
|
+
? { feeConfigured: true, feeMultiplier: entryFee }
|
|
3155
|
+
: (entryFee === 1 ? {} : { feeMultiplier: entryFee })),
|
|
2390
3156
|
})
|
|
2391
3157
|
}
|
|
2392
3158
|
return Object.keys(out).length === 0 ? null : out
|
|
@@ -2436,6 +3202,8 @@ function fingerprintOf(book) {
|
|
|
2436
3202
|
rawOffPeak !== null ? rawOffPeak : rawPeak,
|
|
2437
3203
|
one !== null && one !== undefined && one.tiered === false ? 0 : 1,
|
|
2438
3204
|
one !== null && one !== undefined && one.currency === 'USD' ? 'USD' : 'CNY',
|
|
3205
|
+
one !== null && one !== undefined && relayFeeMultiplierValid(one.feeMultiplier) ? one.feeMultiplier : null,
|
|
3206
|
+
one !== null && one !== undefined && one.feeConfigured === true ? 1 : 0,
|
|
2439
3207
|
])
|
|
2440
3208
|
}
|
|
2441
3209
|
return FINGERPRINT_MARK + JSON.stringify(rows)
|
|
@@ -2514,12 +3282,21 @@ function parseFingerprintRows(text) {
|
|
|
2514
3282
|
const peak = tier(row[1])
|
|
2515
3283
|
const offPeak = tier(row[2])
|
|
2516
3284
|
if (peak === null && offPeak === null) continue
|
|
2517
|
-
|
|
3285
|
+
const feeRaw = Array.isArray(row) && row.length > 5 && row[5] !== null && row[5] !== undefined ? Number(row[5]) : null
|
|
3286
|
+
const feeConfigured = Array.isArray(row) && row.length > 6 && row[6] === 1
|
|
3287
|
+
const entry = {
|
|
2518
3288
|
peak: peak !== null ? peak : offPeak,
|
|
2519
3289
|
offPeak: offPeak !== null ? offPeak : peak,
|
|
2520
3290
|
tiered: row[3] !== 0,
|
|
2521
3291
|
currency: row[4] === 'USD' ? 'USD' : 'CNY',
|
|
2522
|
-
}
|
|
3292
|
+
}
|
|
3293
|
+
if (feeConfigured === true) {
|
|
3294
|
+
entry.feeConfigured = true
|
|
3295
|
+
entry.feeMultiplier = relayFeeMultiplierValid(feeRaw) ? feeRaw : 1
|
|
3296
|
+
} else if (feeRaw !== null && relayFeeMultiplierValid(feeRaw) && feeRaw !== 1) {
|
|
3297
|
+
entry.feeMultiplier = feeRaw
|
|
3298
|
+
}
|
|
3299
|
+
defineBookEntry(out, name, entry)
|
|
2523
3300
|
}
|
|
2524
3301
|
return Object.keys(out).length === 0 ? null : out
|
|
2525
3302
|
}
|
|
@@ -2529,16 +3306,66 @@ function defineBookEntry(target, name, value) {
|
|
|
2529
3306
|
Object.defineProperty(target, name, { value: value, enumerable: true, writable: true, configurable: true })
|
|
2530
3307
|
}
|
|
2531
3308
|
|
|
2532
|
-
/**
|
|
2533
|
-
|
|
2534
|
-
|
|
3309
|
+
/**
|
|
3310
|
+
* 价格条目上的「明确配置过倍率」判据:
|
|
3311
|
+
* · feeConfigured === true → 用 feeMultiplier(非法/缺省按 1);
|
|
3312
|
+
* · 旧数据没有标记但 feeMultiplier 是非 1 数字 → 按已配置兼容;
|
|
3313
|
+
* · 其余 → null(relay 视为无价,记欠账)。
|
|
3314
|
+
*/
|
|
3315
|
+
function relayPriceFee(entry) {
|
|
3316
|
+
if (entry === null || entry === undefined) return null
|
|
3317
|
+
if (entry.feeConfigured === true) return relayFeeMultiplierValid(entry.feeMultiplier) ? entry.feeMultiplier : 1
|
|
3318
|
+
if (relayFeeMultiplierValid(entry.feeMultiplier) && entry.feeMultiplier !== 1) return entry.feeMultiplier
|
|
3319
|
+
return null
|
|
3320
|
+
}
|
|
3321
|
+
|
|
3322
|
+
/** 价格条目自己的费用倍率(旧逻辑兼容:没有标记就按 1)。 */
|
|
3323
|
+
function priceFeeMultiplier(entry) {
|
|
3324
|
+
const fee = relayPriceFee(entry)
|
|
3325
|
+
return fee === null ? 1 : fee
|
|
3326
|
+
}
|
|
3327
|
+
|
|
3328
|
+
/**
|
|
3329
|
+
* 只按价格条目自身单价算「官方参考价」,**不看 provider 归属**。
|
|
3330
|
+
* 历史基线(重算前原值)与 v4 按币种重建都必须用它:模型前缀本身现在会把
|
|
3331
|
+
* `remote-magpie/...` 判成 relay,若再传 provider='' 走 tokenCost 会得到 0 而不是官方价。
|
|
3332
|
+
*/
|
|
3333
|
+
function officialTokenCost(model, at, parts, book) {
|
|
3334
|
+
const entry = book === undefined || book === null ? priceEntryFor(model) : priceEntryIn(book, model)
|
|
3335
|
+
if (entry === null) return 0
|
|
3336
|
+
/* 没勾「峰谷计价」= 全天一个价:两档都取 peak,否则空闲时段会挑到没填的那档、算成 0 */
|
|
3337
|
+
const price = entry.tiered === false ? entry.peak : (isPeakTime(at) ? entry.peak : entry.offPeak)
|
|
3338
|
+
const use = price !== null && price !== undefined ? price : entry.peak
|
|
3339
|
+
if (use === null || use === undefined) return 0
|
|
3340
|
+
return ((parts.input * numOrZero(use.input) + parts.cacheRead * numOrZero(use.cacheRead)
|
|
3341
|
+
+ parts.cacheWrite * numOrZero(use.cacheWrite) + parts.output * numOrZero(use.output)) / 1e6)
|
|
3342
|
+
}
|
|
3343
|
+
|
|
3344
|
+
/**
|
|
3345
|
+
* 一笔用量按单价折成该模型条目自己的币种;模型没有价格表就返回 0(不计入花费)。
|
|
3346
|
+
* `book` 可选:历史重算必须用**当时记账的那份价目表**(台账指纹还原),不能拿当前价库顶替,
|
|
3347
|
+
* 否则已下架/改币种的模型会被当成"没有价格"而漏算,USD 历史就是这么丢的。
|
|
3348
|
+
*/
|
|
3349
|
+
function tokenCost(model, at, parts, provider, feeMultiplier, book) {
|
|
3350
|
+
const entry = book === undefined || book === null ? priceEntryFor(model) : priceEntryIn(book, model)
|
|
2535
3351
|
if (entry === null) return 0
|
|
3352
|
+
const affiliation = providerAffiliation(provider, model)
|
|
3353
|
+
/* official / points 只按官方价:忽略价格条目与通道上的中转倍率。 */
|
|
3354
|
+
if (affiliation !== "relay") return officialTokenCost(model, at, parts, book)
|
|
2536
3355
|
/* 没勾「峰谷计价」= 全天一个价:两档都取 peak,否则空闲时段会挑到没填的那档、算成 0 */
|
|
2537
3356
|
const price = entry.tiered === false ? entry.peak : (isPeakTime(at) ? entry.peak : entry.offPeak)
|
|
2538
3357
|
const use = price !== null && price !== undefined ? price : entry.peak
|
|
2539
3358
|
if (use === null || use === undefined) return 0
|
|
2540
|
-
|
|
2541
|
-
|
|
3359
|
+
/* relay:必须明确配置过价格条目的费用倍率,否则视为无价(由调用方记欠账)。 */
|
|
3360
|
+
const entryFee = relayPriceFee(entry)
|
|
3361
|
+
if (entryFee === null) return 0
|
|
3362
|
+
const channelMultiplier = typeof feeMultiplier === 'number' && Number.isFinite(feeMultiplier) && feeMultiplier > 0
|
|
3363
|
+
? feeMultiplier
|
|
3364
|
+
: relayFeeMultiplierForProvider(provider)
|
|
3365
|
+
/* 旧 relay 通道倍率(兼容存量)× 价格条目倍率(新口径) */
|
|
3366
|
+
return ((parts.input * numOrZero(use.input) + parts.cacheRead * numOrZero(use.cacheRead)
|
|
3367
|
+
+ parts.cacheWrite * numOrZero(use.cacheWrite) + parts.output * numOrZero(use.output)) / 1e6)
|
|
3368
|
+
* channelMultiplier * entryFee
|
|
2542
3369
|
}
|
|
2543
3370
|
|
|
2544
3371
|
/**
|
|
@@ -2547,8 +3374,8 @@ function tokenCost(model, at, parts) {
|
|
|
2547
3374
|
* 只服务于"按币种分桶汇总":**算钱本身不看币种**(台账、历史数字都不受影响),
|
|
2548
3375
|
* 客户端拿到分桶后按参考价比例折成底栏显示币种,混币时才能给出一个数字。
|
|
2549
3376
|
*/
|
|
2550
|
-
function tokenCostCurrency(model) {
|
|
2551
|
-
const entry = priceEntryFor(model)
|
|
3377
|
+
function tokenCostCurrency(model, book) {
|
|
3378
|
+
const entry = book === undefined || book === null ? priceEntryFor(model) : priceEntryIn(book, model)
|
|
2552
3379
|
return entry !== null && entry.currency === 'USD' ? 'USD' : 'CNY'
|
|
2553
3380
|
}
|
|
2554
3381
|
|
|
@@ -2682,36 +3509,62 @@ function collectSessionFiles(dir, out) {
|
|
|
2682
3509
|
/* 会话日志文件清单的缓存。
|
|
2683
3510
|
为什么要有它:这条路由(/api/subagent-usage)每秒被问 2 次,每次都全量递归
|
|
2684
3511
|
sessions 目录 + 逐文件 stat,实测 26ms/次 ≈ 52ms/s 白烧在主线程上;而目录内容
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
3512
|
+
变化极慢(新会话、新队友才会变)。TTL 取 10 秒:既把递归 + 逐文件 stat 从每秒 2 次
|
|
3513
|
+
降到最多每 10 秒 1 次,又不会让新会话/新队友的用量等太久才出现。
|
|
3514
|
+
|
|
3515
|
+
**还要叠一道目录 mtime 校验**:只靠 TTL 的话,新开的队友最坏要等 10 秒才被看见
|
|
3516
|
+
(它花的钱这段时间算不进来)。真实结构是 `sessions/<workspace>/<session>/`:
|
|
3517
|
+
新增一个子会话只改**它所属 workspace 目录**的 mtime,sessions 根目录的 mtime 不变。
|
|
3518
|
+
所以每次先 stat 根目录 + 每个 workspace 目录(微秒级、数量个位数),把这一串
|
|
3519
|
+
mtime 拼成签名比较;签名一变立刻重建名单,不必等 TTL 到点。
|
|
3520
|
+
代价是每次多几个 stat,收益是把递归 + 逐文件 stat 从每秒 2 次降到最多每 10 秒 1 次。
|
|
3521
|
+
已知局限(实测过、接受):**已存在的会话目录里改文件不会改父目录 mtime**,所以
|
|
3522
|
+
"某个队友又写了新内容"这条路径不被这道校验覆盖 —— 但那种变化由缓存键里的
|
|
3523
|
+
文件 mtime+size 兜着(subagentHeaders / subagentFileUsage 各自按文件指纹失效),
|
|
3524
|
+
不需要名单层再兜。
|
|
2695
3525
|
|
|
2696
3526
|
返回的数组直接共享:调用点都只遍历、不 push / splice,所以不需要每次拷一份。 */
|
|
2697
|
-
const SESSION_FILES_TTL_MS =
|
|
2698
|
-
let sessionFilesCache = { at: 0, dir: null,
|
|
3527
|
+
const SESSION_FILES_TTL_MS = 10 * 1000
|
|
3528
|
+
let sessionFilesCache = { at: 0, dir: null, sig: null, list: null }
|
|
2699
3529
|
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
let dirMtimeMs = -1
|
|
3530
|
+
/** sessions 目录的"形状签名":根 mtime + 每个 workspace 子目录的 mtime。 */
|
|
3531
|
+
function sessionDirsSignature(dir) {
|
|
3532
|
+
let entries
|
|
2704
3533
|
try {
|
|
2705
|
-
|
|
3534
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
2706
3535
|
} catch (error) {
|
|
2707
|
-
|
|
2708
|
-
|
|
3536
|
+
return 'missing'
|
|
3537
|
+
}
|
|
3538
|
+
let rootMtime = -1
|
|
3539
|
+
try {
|
|
3540
|
+
rootMtime = statSync(dir).mtimeMs
|
|
3541
|
+
} catch (error) {
|
|
3542
|
+
/* 刚消失:按 -1 记,下一次重建自然会得到空列表 */
|
|
3543
|
+
}
|
|
3544
|
+
const parts = []
|
|
3545
|
+
for (const entry of entries) {
|
|
3546
|
+
if (entry.isDirectory() !== true) continue
|
|
3547
|
+
let mtimeMs = -1
|
|
3548
|
+
try {
|
|
3549
|
+
mtimeMs = statSync(join(dir, entry.name)).mtimeMs
|
|
3550
|
+
} catch (error) {
|
|
3551
|
+
/* 列目录与 stat 之间消失:记 -1,让签名与上一次不同即可 */
|
|
3552
|
+
}
|
|
3553
|
+
parts.push(entry.name + ':' + String(mtimeMs))
|
|
2709
3554
|
}
|
|
3555
|
+
parts.sort()
|
|
3556
|
+
return String(rootMtime) + '|' + parts.join('|')
|
|
3557
|
+
}
|
|
3558
|
+
|
|
3559
|
+
function sessionFilesCached() {
|
|
3560
|
+
const dir = sessionsRoot()
|
|
3561
|
+
const now = Date.now()
|
|
3562
|
+
const sig = sessionDirsSignature(dir)
|
|
2710
3563
|
const hit = sessionFilesCache
|
|
2711
|
-
if (hit.list !== null && hit.dir === dir && hit.
|
|
3564
|
+
if (hit.list !== null && hit.dir === dir && hit.sig === sig
|
|
2712
3565
|
&& now - hit.at < SESSION_FILES_TTL_MS) return hit.list
|
|
2713
3566
|
const list = collectSessionFiles(dir, [])
|
|
2714
|
-
sessionFilesCache = { at: now, dir: dir,
|
|
3567
|
+
sessionFilesCache = { at: now, dir: dir, sig: sig, list: list }
|
|
2715
3568
|
return list
|
|
2716
3569
|
}
|
|
2717
3570
|
|
|
@@ -2948,6 +3801,35 @@ function usageEventKey(event) {
|
|
|
2948
3801
|
return 'seq:' + String(event.seq)
|
|
2949
3802
|
}
|
|
2950
3803
|
|
|
3804
|
+
function pickedUsageRecord(event, route, parts, feeConfig) {
|
|
3805
|
+
const data = event.data !== null && event.data !== undefined && typeof event.data === 'object' ? event.data : {}
|
|
3806
|
+
const source = data.message !== null && data.message !== undefined && typeof data.message === 'object'
|
|
3807
|
+
&& data.message.source !== null && data.message.source !== undefined && typeof data.message.source === 'object'
|
|
3808
|
+
? data.message.source
|
|
3809
|
+
: null
|
|
3810
|
+
const isMessage = event.type === 'assistant/message'
|
|
3811
|
+
const isSummary = event.type === 'compaction/summary'
|
|
3812
|
+
const model = isSummary
|
|
3813
|
+
? (typeof data.model === 'string' && data.model.length > 0 ? data.model : null)
|
|
3814
|
+
: (isMessage
|
|
3815
|
+
? (source !== null && typeof source.model === 'string' ? source.model : route.model)
|
|
3816
|
+
: route.model)
|
|
3817
|
+
const provider = isSummary
|
|
3818
|
+
? (typeof data.provider === 'string' ? data.provider : '')
|
|
3819
|
+
: (isMessage
|
|
3820
|
+
? (source !== null && typeof source.provider === 'string' ? source.provider : '')
|
|
3821
|
+
: (typeof route.provider === 'string' ? route.provider : ''))
|
|
3822
|
+
return {
|
|
3823
|
+
seq: typeof event.seq === 'number' ? event.seq : Math.round(event.time),
|
|
3824
|
+
time: event.time,
|
|
3825
|
+
parts,
|
|
3826
|
+
isMessage,
|
|
3827
|
+
model,
|
|
3828
|
+
provider,
|
|
3829
|
+
feeMultiplier: relayFeeMultiplierFromConfig(provider, feeConfig),
|
|
3830
|
+
}
|
|
3831
|
+
}
|
|
3832
|
+
|
|
2951
3833
|
/**
|
|
2952
3834
|
* 从一段日志文本里挑出窗口内的用量事件。
|
|
2953
3835
|
* 同一个 key 只留一条,且 `assistant/message` 优先 —— 这样重试的 attempt 与最终消息
|
|
@@ -2955,8 +3837,11 @@ function usageEventKey(event) {
|
|
|
2955
3837
|
*/
|
|
2956
3838
|
function pickUsageEvents(text, fromMs) {
|
|
2957
3839
|
const picked = new Map()
|
|
3840
|
+
const feeConfig = relayFeeConfig()
|
|
3841
|
+
let route = { model: null, provider: '' }
|
|
2958
3842
|
for (const line of text.split('\n')) {
|
|
2959
|
-
if (line.indexOf('"usage"') < 0)
|
|
3843
|
+
if (line.indexOf('"usage"') < 0 && line.indexOf('"model/selection"') < 0
|
|
3844
|
+
&& line.indexOf('"session/title-llm-request"') < 0) continue
|
|
2960
3845
|
let event
|
|
2961
3846
|
try {
|
|
2962
3847
|
event = JSON.parse(line)
|
|
@@ -2964,6 +3849,8 @@ function pickUsageEvents(text, fromMs) {
|
|
|
2964
3849
|
continue
|
|
2965
3850
|
}
|
|
2966
3851
|
if (event === null || typeof event !== 'object') continue
|
|
3852
|
+
const routed = routedModelOf(event)
|
|
3853
|
+
if (routed !== null) route = routed
|
|
2967
3854
|
if (typeof event.time !== 'number' || event.time < fromMs) continue
|
|
2968
3855
|
const usage = usageOfEvent(event)
|
|
2969
3856
|
if (usage === null) continue
|
|
@@ -2974,48 +3861,20 @@ function pickUsageEvents(text, fromMs) {
|
|
|
2974
3861
|
const key = usageEventKey(event)
|
|
2975
3862
|
const prev = picked.get(key)
|
|
2976
3863
|
if (prev === undefined || (prev.isMessage !== true && isMessage)) {
|
|
2977
|
-
|
|
2978
|
-
const source = data.message !== null && data.message !== undefined && typeof data.message === 'object'
|
|
2979
|
-
&& data.message.source !== null && data.message.source !== undefined && typeof data.message.source === 'object'
|
|
2980
|
-
? data.message.source
|
|
2981
|
-
: null
|
|
2982
|
-
/* 模型名的两个来源:assistant/message 在 message.source.model,
|
|
2983
|
-
而 compaction/summary(压缩摘要本身是一次真实模型调用)把模型放在顶层 data.model ——
|
|
2984
|
-
只认前者会让整笔摘要用量落进「(未知模型)」欠账,永远结算不出来。 */
|
|
2985
|
-
const model = source !== null && typeof source.model === 'string'
|
|
2986
|
-
? source.model
|
|
2987
|
-
: (typeof data.model === 'string' && data.model.length > 0 ? data.model : null)
|
|
2988
|
-
picked.set(key, {
|
|
2989
|
-
seq: typeof event.seq === 'number' ? event.seq : Math.round(event.time),
|
|
2990
|
-
time: event.time,
|
|
2991
|
-
parts: parts,
|
|
2992
|
-
isMessage: isMessage,
|
|
2993
|
-
/* 计价要用模型名(不同模型单价不同) */
|
|
2994
|
-
model: model,
|
|
2995
|
-
})
|
|
3864
|
+
picked.set(key, pickedUsageRecord(event, route, parts, feeConfig))
|
|
2996
3865
|
}
|
|
2997
3866
|
}
|
|
2998
3867
|
return picked
|
|
2999
3868
|
}
|
|
3000
3869
|
|
|
3001
3870
|
/**
|
|
3002
|
-
* `pickUsageEvents`
|
|
3003
|
-
* 同样的模型名解析),只多一件事 —— 每 200 行检查一次耗时,超过 8ms 就 `await setImmediate`。
|
|
3004
|
-
*
|
|
3005
|
-
* 为什么必须存在:异步解压把 zstd 扔进线程池之后,`JSON.parse` 成了新的最长同步块
|
|
3006
|
-
* (8.8MB 日志实测 312ms,纯主线程)。解压在别的线程跑、解析留在主线程,界面照样冻住。
|
|
3007
|
-
*
|
|
3008
|
-
* 三条刻意的写法(都不要"优化"掉):
|
|
3009
|
-
* · `picked` 声明在 `await` 之外 —— 跨让出点累积,绝不中途重建(否则后面那块会丢)。
|
|
3010
|
-
* · 时间检查放在 `i % 200 === 0`(第 0 行就算起点),每 200 行一次而不是每行一次 ——
|
|
3011
|
-
* 每行 `Date.now()` 是实打实的额外开销,大日志上几十万次。
|
|
3012
|
-
* · 让出用 `setImmediate` 而不是 `setTimeout(0)`:前者在 poll 之后立刻跑,不额外吃 1ms 定时器。
|
|
3013
|
-
*
|
|
3014
|
-
* 同步版保留不动:它是语义基准,`pickUsageEventsAsync` 的结果必须与它**逐字相等**。
|
|
3871
|
+
* `pickUsageEvents` 的可让出版本:逻辑逐条照搬同步版,并按需让出事件循环。
|
|
3015
3872
|
*/
|
|
3016
3873
|
async function pickUsageEventsAsync(text, fromMs) {
|
|
3017
3874
|
const lines = text.split('\n')
|
|
3018
3875
|
const picked = new Map()
|
|
3876
|
+
const feeConfig = relayFeeConfig()
|
|
3877
|
+
let route = { model: null, provider: '' }
|
|
3019
3878
|
let sliceStart = Date.now()
|
|
3020
3879
|
for (let i = 0; i < lines.length; i += 1) {
|
|
3021
3880
|
/* 让出检查必须在**循环体最前面**,不能放在过滤逻辑之后:
|
|
@@ -3028,7 +3887,8 @@ async function pickUsageEventsAsync(text, fromMs) {
|
|
|
3028
3887
|
sliceStart = Date.now()
|
|
3029
3888
|
}
|
|
3030
3889
|
const line = lines[i]
|
|
3031
|
-
if (line.indexOf('"usage"') < 0)
|
|
3890
|
+
if (line.indexOf('"usage"') < 0 && line.indexOf('"model/selection"') < 0
|
|
3891
|
+
&& line.indexOf('"session/title-llm-request"') < 0) continue
|
|
3032
3892
|
let event
|
|
3033
3893
|
try {
|
|
3034
3894
|
event = JSON.parse(line)
|
|
@@ -3036,6 +3896,8 @@ async function pickUsageEventsAsync(text, fromMs) {
|
|
|
3036
3896
|
continue
|
|
3037
3897
|
}
|
|
3038
3898
|
if (event === null || typeof event !== 'object') continue
|
|
3899
|
+
const routed = routedModelOf(event)
|
|
3900
|
+
if (routed !== null) route = routed
|
|
3039
3901
|
if (typeof event.time !== 'number' || event.time < fromMs) continue
|
|
3040
3902
|
const usage = usageOfEvent(event)
|
|
3041
3903
|
if (usage === null) continue
|
|
@@ -3046,21 +3908,7 @@ async function pickUsageEventsAsync(text, fromMs) {
|
|
|
3046
3908
|
const key = usageEventKey(event)
|
|
3047
3909
|
const prev = picked.get(key)
|
|
3048
3910
|
if (prev === undefined || (prev.isMessage !== true && isMessage)) {
|
|
3049
|
-
|
|
3050
|
-
const source = data.message !== null && data.message !== undefined && typeof data.message === 'object'
|
|
3051
|
-
&& data.message.source !== null && data.message.source !== undefined && typeof data.message.source === 'object'
|
|
3052
|
-
? data.message.source
|
|
3053
|
-
: null
|
|
3054
|
-
const model = source !== null && typeof source.model === 'string'
|
|
3055
|
-
? source.model
|
|
3056
|
-
: (typeof data.model === 'string' && data.model.length > 0 ? data.model : null)
|
|
3057
|
-
picked.set(key, {
|
|
3058
|
-
seq: typeof event.seq === 'number' ? event.seq : Math.round(event.time),
|
|
3059
|
-
time: event.time,
|
|
3060
|
-
parts: parts,
|
|
3061
|
-
isMessage: isMessage,
|
|
3062
|
-
model: model,
|
|
3063
|
-
})
|
|
3911
|
+
picked.set(key, pickedUsageRecord(event, route, parts, feeConfig))
|
|
3064
3912
|
}
|
|
3065
3913
|
}
|
|
3066
3914
|
return picked
|
|
@@ -3079,15 +3927,45 @@ const SUBAGENT_MAX_DESCENDANTS = 2000
|
|
|
3079
3927
|
刚建好、header 还没落盘的文件下一次请求就能认出来,而真正的坏文件不会一直被反复读。
|
|
3080
3928
|
头部里的 id / parentSession 是会话创建时写死的,所以读成功的那份不会失效,只有 stat 变了才重读。
|
|
3081
3929
|
上限 SUBAGENT_HEADER_CACHE_MAX 条,超出丢最久没被重新写入的(Map 的插入顺序)。 */
|
|
3082
|
-
|
|
3930
|
+
/* 会话文件头缓存:每条只有 id/parentSession + 两个数字。上限 4096 覆盖本机常见会话数
|
|
3931
|
+
(实测 552 个文件),同时仍是硬上限,防畸形 sessions 树无限增长。 */
|
|
3932
|
+
const SUBAGENT_HEADER_CACHE_MAX = 4096
|
|
3083
3933
|
const subagentHeaders = new Map()
|
|
3084
3934
|
|
|
3935
|
+
/* 索引的“全量对账”周期:正常请求只 stat 当前会话相关文件;每 5 分钟把所有文件 stat 一遍,
|
|
3936
|
+
兜住“同一路径被替换成另一份日志”这类异常(header 里的 id/parentSession 是不可变的,
|
|
3937
|
+
正常写入不会改变它们,所以不需要每次请求都全量读)。 */
|
|
3938
|
+
const SUBAGENT_INDEX_RECONCILE_MS = 5 * 60 * 1000
|
|
3939
|
+
let subagentIndexReconcileAt = 0
|
|
3940
|
+
|
|
3085
3941
|
/** 两份同名会话文件谁更新:先比 mtime,一样再比 size(更大的一般更完整)。 */
|
|
3086
3942
|
function headerEntryNewer(candidate, current) {
|
|
3087
3943
|
if (candidate.mtimeMs !== current.mtimeMs) return candidate.mtimeMs > current.mtimeMs
|
|
3088
3944
|
return candidate.size > current.size
|
|
3089
3945
|
}
|
|
3090
3946
|
|
|
3947
|
+
/**
|
|
3948
|
+
* 把**当前请求真正用得到**的条目重新 stat 一遍(当前会话的父日志 + 它自己的后代)。
|
|
3949
|
+
* 为什么要单独做:索引层为了省掉每秒 552 次 stat,只在首次见到文件时读头,
|
|
3950
|
+
* 缓存里的 mtime/size 可能过期;而“要不要重解压这份日志”和“在不在跑”都依赖最新值。
|
|
3951
|
+
* 只 stat 几十个相关文件,代价远小于全量 552 个。
|
|
3952
|
+
*/
|
|
3953
|
+
function refreshSubagentEntryStat(one) {
|
|
3954
|
+
if (one === null || one === undefined || typeof one.file !== 'string') return one
|
|
3955
|
+
try {
|
|
3956
|
+
const stat = statSync(one.file)
|
|
3957
|
+
if (stat.mtimeMs === one.mtimeMs && stat.size === one.size) return one
|
|
3958
|
+
const cached = subagentHeaders.get(one.file)
|
|
3959
|
+
const header = cached !== undefined && cached.header !== null ? cached.header : sessionHeaderOfFile(one.file)
|
|
3960
|
+
subagentHeaders.delete(one.file)
|
|
3961
|
+
subagentHeaders.set(one.file, { mtimeMs: stat.mtimeMs, size: stat.size, header })
|
|
3962
|
+
return { ...one, mtimeMs: stat.mtimeMs, size: stat.size }
|
|
3963
|
+
} catch (error) {
|
|
3964
|
+
/* 文件消失:保留旧条目(读日志时会按 0 处理),下次索引重建自然剔除 */
|
|
3965
|
+
return one
|
|
3966
|
+
}
|
|
3967
|
+
}
|
|
3968
|
+
|
|
3091
3969
|
/**
|
|
3092
3970
|
* 会话文件 → `parentSession → [子会话]` 邻接表(外加 `duplicates` 计数,只用来打日志)。
|
|
3093
3971
|
*
|
|
@@ -3100,8 +3978,20 @@ async function subagentIndexSnapshot(files) {
|
|
|
3100
3978
|
for (const file of Array.from(subagentHeaders.keys())) {
|
|
3101
3979
|
if (live.has(file) !== true) subagentHeaders.delete(file)
|
|
3102
3980
|
}
|
|
3981
|
+
const now = Date.now()
|
|
3982
|
+
/* 全量对账每 5 分钟一次(或缓存为空时);其余请求只处理**新出现**的文件。
|
|
3983
|
+
旧的实现每个请求都对全部会话文件 stat 一遍(本机 552 个 = 每秒 1104 次 stat),
|
|
3984
|
+
而文件头里的 id/parentSession 建好就不会再变 —— 这是这条路由最白烧的一段。 */
|
|
3985
|
+
const fullScan = subagentHeaders.size === 0 || now - subagentIndexReconcileAt >= SUBAGENT_INDEX_RECONCILE_MS
|
|
3986
|
+
if (fullScan) subagentIndexReconcileAt = now
|
|
3987
|
+
let processed = 0
|
|
3103
3988
|
for (let i = 0; i < files.length; i += 1) {
|
|
3104
3989
|
const file = files[i]
|
|
3990
|
+
const cached = subagentHeaders.get(file)
|
|
3991
|
+
/* 已成功读过头的文件不用再 stat(id/parentSession 不会变)。
|
|
3992
|
+
头部读取失败(header === null)的条目要定期重试:文件修好后必须能恢复正常,
|
|
3993
|
+
不能把失败结果永久缓存。 */
|
|
3994
|
+
if (fullScan !== true && cached !== undefined && cached.header !== null) continue
|
|
3105
3995
|
let stat = null
|
|
3106
3996
|
try {
|
|
3107
3997
|
stat = statSync(file)
|
|
@@ -3113,7 +4003,6 @@ async function subagentIndexSnapshot(files) {
|
|
|
3113
4003
|
subagentHeaders.delete(file)
|
|
3114
4004
|
continue
|
|
3115
4005
|
}
|
|
3116
|
-
const cached = subagentHeaders.get(file)
|
|
3117
4006
|
if (cached !== undefined && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) continue
|
|
3118
4007
|
/* 读失败(含"没有头部")也记下来:同一个 mtime/size 的下一问直接跳过,不再重读 */
|
|
3119
4008
|
const header = sessionHeaderOfFile(file)
|
|
@@ -3125,7 +4014,8 @@ async function subagentIndexSnapshot(files) {
|
|
|
3125
4014
|
subagentHeaders.delete(oldest.value)
|
|
3126
4015
|
}
|
|
3127
4016
|
/* 首次请求要把所有会话都读一遍头部:每 8 个让出一次事件循环,别把 host 卡住 */
|
|
3128
|
-
|
|
4017
|
+
processed += 1
|
|
4018
|
+
if (processed % 8 === 7) await new Promise((resolve) => setImmediate(resolve))
|
|
3129
4019
|
}
|
|
3130
4020
|
/* 一个会话 id 可能出现在两个文件里:① 日志格式升级时同目录留下旧版本文件;
|
|
3131
4021
|
② 手工复制会话目录;③ 异常产生的重复目录。只认**最新的那一份**参与聚合
|
|
@@ -3156,13 +4046,21 @@ async function subagentIndexSnapshot(files) {
|
|
|
3156
4046
|
}
|
|
3157
4047
|
|
|
3158
4048
|
/**
|
|
3159
|
-
*
|
|
4049
|
+
* 一段父会话日志的**全部本轮事实**,一次 split + 一次逐行扫描折出来:
|
|
4050
|
+
* · `since`:本轮起点(规则见下)
|
|
4051
|
+
* · `lastUsageAt`:最后一条非空 usage 事件的时间(判断"起点之后父会话自己产出过没有")
|
|
4052
|
+
*
|
|
4053
|
+
* 为什么合并成一次扫描:父会话日志是整棵树里最大的一份;旧实现缓存失效时要在同一份
|
|
4054
|
+
* 文本上跑两趟 split + 逐行 JSON.parse(lastTurnStartOfText / lastUsageEventTimeOfText),
|
|
4055
|
+
* 两倍 CPU 与两倍临时对象。合并后每条相关行只解析一次。
|
|
4056
|
+
*
|
|
4057
|
+
* `since` 的三条时间取 max:
|
|
3160
4058
|
* ① 最后一条 `turn/start`;
|
|
3161
4059
|
* ② 最后一条**真实用户输入**的 `user/message` —— 但**只有**它落在
|
|
3162
4060
|
* 「最后一条 `turn/end` 之后、且最后一条 `turn/end` 晚于最后一条 `turn/start`」
|
|
3163
4061
|
* 这一段里,才算"新一轮已经开始、而它的 `turn/start` 还没落盘"的候选;
|
|
3164
4062
|
* ③ 日志里完全没有 `turn/start` 时,退回用最后一条真实用户消息(老兜底)。
|
|
3165
|
-
*
|
|
4063
|
+
* 都找不到就是 null(调用方据此判 sinceSource='none')。
|
|
3166
4064
|
*
|
|
3167
4065
|
* **为什么只认 `source.kind === 'user'` 的 `user/message`**(2026-10-17 修复):
|
|
3168
4066
|
* 同一轮里 DSH 会往父会话日志注入很多**不是用户输入**的 `user/message` ——
|
|
@@ -3185,26 +4083,30 @@ async function subagentIndexSnapshot(files) {
|
|
|
3185
4083
|
* 还没落盘);turn 还开着就只认 `turn/start`。
|
|
3186
4084
|
*
|
|
3187
4085
|
* 取**最大值**而不是"文件里最后一行":正常日志是追加写的,两者一致;万一有乱序行,
|
|
3188
|
-
*
|
|
4086
|
+
* 取最大值更稳。只解析可能相关的行(turn / user / usage):日志可能几 MB,
|
|
4087
|
+
* 逐行 JSON.parse 太贵。坏行跳过,绝不抛。
|
|
3189
4088
|
*/
|
|
3190
|
-
function
|
|
3191
|
-
|
|
4089
|
+
function parentLogFactsOfText(text) {
|
|
4090
|
+
const facts = { since: null, lastUsageAt: null }
|
|
4091
|
+
if (typeof text !== 'string' || text.length === 0) return facts
|
|
3192
4092
|
let lastTurnStart = null
|
|
3193
4093
|
let lastTurnEnd = null
|
|
3194
4094
|
let lastUser = null
|
|
4095
|
+
let lastUsageAt = null
|
|
3195
4096
|
const lines = text.split('\n')
|
|
3196
4097
|
for (let i = 0; i < lines.length; i += 1) {
|
|
3197
4098
|
const line = lines[i]
|
|
3198
|
-
/*
|
|
4099
|
+
/* 便宜的预筛:只解析可能相关的事件(usage 只认 assistant/message、compaction/summary) */
|
|
3199
4100
|
if (line.indexOf('"turn/start"') < 0 && line.indexOf('"turn/end"') < 0
|
|
3200
|
-
&& line.indexOf('"user/message"') < 0) continue
|
|
4101
|
+
&& line.indexOf('"user/message"') < 0 && line.indexOf('"usage"') < 0) continue
|
|
3201
4102
|
let event
|
|
3202
4103
|
try {
|
|
3203
4104
|
event = JSON.parse(line)
|
|
3204
4105
|
} catch (error) {
|
|
3205
4106
|
continue
|
|
3206
4107
|
}
|
|
3207
|
-
if (event === null || typeof event !== 'object'
|
|
4108
|
+
if (event === null || typeof event !== 'object') continue
|
|
4109
|
+
if (typeof event.time !== 'number') continue
|
|
3208
4110
|
if (event.type === 'turn/start') {
|
|
3209
4111
|
if (lastTurnStart === null || event.time > lastTurnStart) lastTurnStart = event.time
|
|
3210
4112
|
continue
|
|
@@ -3213,92 +4115,89 @@ function lastTurnStartOfText(text) {
|
|
|
3213
4115
|
if (lastTurnEnd === null || event.time > lastTurnEnd) lastTurnEnd = event.time
|
|
3214
4116
|
continue
|
|
3215
4117
|
}
|
|
3216
|
-
if (event.type
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
4118
|
+
if (event.type === 'user/message') {
|
|
4119
|
+
/* 只认真实用户输入:source 缺失(老日志/坏行)也宁可不当成新轮 —— 少算一侧
|
|
4120
|
+
的代价是多算上一轮末的队友用量(偏大),比"整轮花费被抹掉"可接受。 */
|
|
4121
|
+
const data = event.data !== null && event.data !== undefined && typeof event.data === 'object' ? event.data : {}
|
|
4122
|
+
const source = data.source !== null && data.source !== undefined && typeof data.source === 'object' ? data.source : null
|
|
4123
|
+
if (source !== null && source.kind === 'user' && (lastUser === null || event.time > lastUser)) lastUser = event.time
|
|
4124
|
+
continue
|
|
4125
|
+
}
|
|
4126
|
+
if (event.type === 'assistant/message' || event.type === 'compaction/summary') {
|
|
4127
|
+
const usage = usageOfEvent(event)
|
|
4128
|
+
if (usage === null) continue
|
|
4129
|
+
const parts = usageParts(usage)
|
|
4130
|
+
if (parts.input === 0 && parts.cacheRead === 0 && parts.cacheWrite === 0 && parts.output === 0) continue
|
|
4131
|
+
if (lastUsageAt === null || event.time > lastUsageAt) lastUsageAt = event.time
|
|
4132
|
+
}
|
|
3223
4133
|
}
|
|
4134
|
+
facts.lastUsageAt = lastUsageAt
|
|
3224
4135
|
/* 完全没有 turn/start:老日志/异常日志的兜底 —— 用最后一条真实用户消息(原来就是这样) */
|
|
3225
|
-
if (lastTurnStart === null)
|
|
4136
|
+
if (lastTurnStart === null) {
|
|
4137
|
+
facts.since = lastUser
|
|
4138
|
+
return facts
|
|
4139
|
+
}
|
|
3226
4140
|
/* 用户消息只有在"上一轮已结束(turn/end 晚于 turn/start)、且消息晚于那个 turn/end"
|
|
3227
4141
|
时才是"新轮已开始、turn/start 还没落盘"的证据;turn 还开着就只是本轮插话,不算 */
|
|
3228
4142
|
const turnClosed = lastTurnEnd !== null && lastTurnEnd > lastTurnStart
|
|
3229
4143
|
const userStartedNewTurn = turnClosed === true && lastUser !== null && lastUser > lastTurnEnd
|
|
3230
|
-
|
|
4144
|
+
facts.since = userStartedNewTurn === true && lastUser > lastTurnStart ? lastUser : lastTurnStart
|
|
4145
|
+
return facts
|
|
3231
4146
|
}
|
|
3232
4147
|
|
|
3233
|
-
/**
|
|
3234
|
-
* 一段父会话日志里**最后一条用量事件**的时间(`assistant/message` 或 `compaction/summary`
|
|
3235
|
-
* 且带非空 usage)。只服务于一个问题:"这个窗口起点之后,父会话自己到底产出过没有?"
|
|
3236
|
-
*
|
|
3237
|
-
* 只留**最大值**(一个数字)而不是把整串事件时间攒下来:要回答的是存在性
|
|
3238
|
-
* ("有没有 time >= fromMs 的用量事件" ⟺ "最大用量时间 >= fromMs"),
|
|
3239
|
-
* 而父会话日志是整棵树里最大的那一份,不该为一道布尔判断在内存里留一串时间戳。
|
|
3240
|
-
* 全 0 的 usage(被中断的尝试)不算产出 —— 与 pickUsageEvents 的口径一致。
|
|
3241
|
-
*/
|
|
3242
|
-
function lastUsageEventTimeOfText(text) {
|
|
3243
|
-
if (typeof text !== 'string' || text.length === 0) return null
|
|
3244
|
-
let at = null
|
|
3245
|
-
const lines = text.split('\n')
|
|
3246
|
-
for (let i = 0; i < lines.length; i += 1) {
|
|
3247
|
-
const line = lines[i]
|
|
3248
|
-
/* 两道便宜的字符串筛(与 pickUsageEvents / foldSessionTiming 同一套省法):
|
|
3249
|
-
绝大多数行既没有 usage 也不是这两类事件,逐行 JSON.parse 太贵 */
|
|
3250
|
-
if (line.indexOf('"usage"') < 0) continue
|
|
3251
|
-
if (line.indexOf('"assistant/message"') < 0 && line.indexOf('"compaction/summary"') < 0) continue
|
|
3252
|
-
let event
|
|
3253
|
-
try {
|
|
3254
|
-
event = JSON.parse(line)
|
|
3255
|
-
} catch (error) {
|
|
3256
|
-
continue
|
|
3257
|
-
}
|
|
3258
|
-
if (event === null || typeof event !== 'object' || typeof event.time !== 'number') continue
|
|
3259
|
-
if (event.type !== 'assistant/message' && event.type !== 'compaction/summary') continue
|
|
3260
|
-
const usage = usageOfEvent(event)
|
|
3261
|
-
if (usage === null) continue
|
|
3262
|
-
const parts = usageParts(usage)
|
|
3263
|
-
if (parts.input === 0 && parts.cacheRead === 0 && parts.cacheWrite === 0 && parts.output === 0) continue
|
|
3264
|
-
if (at === null || event.time > at) at = event.time
|
|
3265
|
-
}
|
|
3266
|
-
return at
|
|
3267
|
-
}
|
|
3268
4148
|
|
|
3269
4149
|
/* 父会话日志 → 它自己的"本轮事实":①本轮起点 ②窗口内有没有它自己的用量事件。
|
|
3270
4150
|
这个文件每次对话都在写,但只是解压一份日志、折两个标量,代价很低;照样按
|
|
3271
|
-
`文件 + mtime + size` 记忆化(内容一变就重折)——
|
|
3272
|
-
|
|
3273
|
-
|
|
4151
|
+
`文件 + mtime + size` 记忆化(内容一变就重折)—— 两件事**共用同一次解压 + 同一次
|
|
4152
|
+
逐行扫描**(parentLogFactsOfText),免得多付两趟全文 split/parse。
|
|
4153
|
+
缓存按**父文件路径**存快照:文件更新时替换旧版本,不按 mtime 累积一堆历史版本;
|
|
4154
|
+
同时限制条目数与估算总字节,防畸形超长日志把内存撑爆。 */
|
|
3274
4155
|
const SUBAGENT_SINCE_CACHE_MAX = 32
|
|
4156
|
+
const SUBAGENT_SINCE_CACHE_BYTES_MAX = 8 * 1024 * 1024
|
|
4157
|
+
let subagentSinceCacheBytes = 0
|
|
3275
4158
|
const subagentSinceCache = new Map()
|
|
3276
4159
|
|
|
3277
|
-
|
|
4160
|
+
/** 一条父日志事实的估算字节数(用于缓存淘汰;只需要量级正确)。 */
|
|
4161
|
+
function parentLogFactsBytes(value) {
|
|
4162
|
+
return 128
|
|
4163
|
+
}
|
|
4164
|
+
|
|
4165
|
+
function trimSubagentSinceCache() {
|
|
4166
|
+
while (subagentSinceCache.size > SUBAGENT_SINCE_CACHE_MAX || subagentSinceCacheBytes > SUBAGENT_SINCE_CACHE_BYTES_MAX) {
|
|
4167
|
+
const oldest = subagentSinceCache.keys().next()
|
|
4168
|
+
if (oldest.done === true) break
|
|
4169
|
+
const entry = subagentSinceCache.get(oldest.value)
|
|
4170
|
+
subagentSinceCache.delete(oldest.value)
|
|
4171
|
+
if (entry !== undefined) subagentSinceCacheBytes -= entry.bytes
|
|
4172
|
+
}
|
|
4173
|
+
}
|
|
4174
|
+
|
|
4175
|
+
async function parentLogFactsOf(one) {
|
|
3278
4176
|
const key = one.file + '|' + String(one.mtimeMs) + '|' + String(one.size)
|
|
3279
|
-
const hit = subagentSinceCache.get(
|
|
3280
|
-
if (hit !== undefined) return hit
|
|
4177
|
+
const hit = subagentSinceCache.get(one.file)
|
|
4178
|
+
if (hit !== undefined && hit.key === key) return hit.value
|
|
3281
4179
|
let text = null
|
|
3282
4180
|
try {
|
|
3283
|
-
text =
|
|
4181
|
+
text = await zstdTextAsync(await fsPromises.readFile(one.file))
|
|
3284
4182
|
} catch (error) {
|
|
3285
4183
|
text = null
|
|
3286
4184
|
}
|
|
3287
|
-
const value = text === null
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
|
|
3291
|
-
while (subagentSinceCache.size > SUBAGENT_SINCE_CACHE_MAX) {
|
|
3292
|
-
const oldest = subagentSinceCache.keys().next()
|
|
3293
|
-
if (oldest.done === true) break
|
|
3294
|
-
subagentSinceCache.delete(oldest.value)
|
|
4185
|
+
const value = text === null ? { since: null, lastUsageAt: null } : parentLogFactsOfText(text)
|
|
4186
|
+
if (hit !== undefined) {
|
|
4187
|
+
subagentSinceCache.delete(one.file)
|
|
4188
|
+
subagentSinceCacheBytes -= hit.bytes
|
|
3295
4189
|
}
|
|
4190
|
+
const bytes = parentLogFactsBytes(value)
|
|
4191
|
+
subagentSinceCache.set(one.file, { key: key, value: value, bytes: bytes })
|
|
4192
|
+
subagentSinceCacheBytes += bytes
|
|
4193
|
+
trimSubagentSinceCache()
|
|
3296
4194
|
return value
|
|
3297
4195
|
}
|
|
3298
4196
|
|
|
3299
4197
|
/** 父会话日志 → 它自己的"本轮起点"(推不出来给 null)。薄壳,只为既有调用点读起来更直白。 */
|
|
3300
|
-
function parentTurnStartOf(one) {
|
|
3301
|
-
|
|
4198
|
+
async function parentTurnStartOf(one) {
|
|
4199
|
+
const facts = await parentLogFactsOf(one)
|
|
4200
|
+
return facts.since
|
|
3302
4201
|
}
|
|
3303
4202
|
|
|
3304
4203
|
/* 每个父会话一份结果:`sessionId → { key, value }`,key 见 collectSubagentUsage。
|
|
@@ -3306,6 +4205,8 @@ function parentTurnStartOf(one) {
|
|
|
3306
4205
|
最多留 8 份,超出丢最久没用的(Map 的插入顺序)。 */
|
|
3307
4206
|
const SUBAGENT_CACHE_MAX = 8
|
|
3308
4207
|
const subagentUsageCache = new Map()
|
|
4208
|
+
/* 同一会话+同一窗口的在飞请求:共享同一个 Promise,避免重复排队/重复解压。 */
|
|
4209
|
+
const subagentUsageInflight = new Map()
|
|
3309
4210
|
|
|
3310
4211
|
/** 会话日志里的一笔用量折成钱(6 位小数,与台账的金额口径一致)。 */
|
|
3311
4212
|
function roundCost(value) {
|
|
@@ -3414,6 +4315,39 @@ function foldSessionTiming(text) {
|
|
|
3414
4315
|
收益接近零;而 1024 < 4000 会让正常场景就开始误删仍有用的键。 */
|
|
3415
4316
|
const SUBAGENT_FILE_CACHE_MAX = 4096
|
|
3416
4317
|
const subagentFileCache = new Map()
|
|
4318
|
+
/* 事件缓存按“估算字节数”再做一道总上限:条目数上限只数文件个数,不数每个文件里存了多少
|
|
4319
|
+
条 usage 事件。一个跑了几千次模型调用的队友日志,单条就可能几 MB;4096 个这样的条目
|
|
4320
|
+
会吃掉数百 MB。按 160 字节/事件估算,64 MB 总预算内正常场景永远不淘汰。 */
|
|
4321
|
+
const SUBAGENT_FILE_CACHE_BYTES_MAX = 64 * 1024 * 1024
|
|
4322
|
+
const SUBAGENT_FILE_EVENT_EST_BYTES = 160
|
|
4323
|
+
let subagentFileCacheBytes = 0
|
|
4324
|
+
|
|
4325
|
+
function subagentFileEntryBytes(entry) {
|
|
4326
|
+
const events = entry !== null && entry !== undefined && Array.isArray(entry.events) ? entry.events.length : 0
|
|
4327
|
+
return 64 + events * SUBAGENT_FILE_EVENT_EST_BYTES
|
|
4328
|
+
}
|
|
4329
|
+
|
|
4330
|
+
function trimSubagentFileCache() {
|
|
4331
|
+
while (subagentFileCache.size > SUBAGENT_FILE_CACHE_MAX || subagentFileCacheBytes > SUBAGENT_FILE_CACHE_BYTES_MAX) {
|
|
4332
|
+
const oldest = subagentFileCache.keys().next()
|
|
4333
|
+
if (oldest.done === true) break
|
|
4334
|
+
const value = subagentFileCache.get(oldest.value)
|
|
4335
|
+
subagentFileCache.delete(oldest.value)
|
|
4336
|
+
subagentFileCacheBytes -= subagentFileEntryBytes(value)
|
|
4337
|
+
}
|
|
4338
|
+
}
|
|
4339
|
+
|
|
4340
|
+
/** 写入/替换一条文件缓存并做淘汰。替换旧键时先扣掉旧条目字节,避免账目漂移。 */
|
|
4341
|
+
function putSubagentFileCacheEntry(aggKey, entry) {
|
|
4342
|
+
const previousEntry = subagentFileCache.get(aggKey)
|
|
4343
|
+
if (previousEntry !== undefined) {
|
|
4344
|
+
subagentFileCacheBytes -= subagentFileEntryBytes(previousEntry)
|
|
4345
|
+
subagentFileCache.delete(aggKey)
|
|
4346
|
+
}
|
|
4347
|
+
subagentFileCacheBytes += subagentFileEntryBytes(entry)
|
|
4348
|
+
subagentFileCache.set(aggKey, entry)
|
|
4349
|
+
trimSubagentFileCache()
|
|
4350
|
+
}
|
|
3417
4351
|
|
|
3418
4352
|
/* `file|mtime|size` → 该日志**最后一条事件的类型**(`turn/end` = 这一轮已收尾)。
|
|
3419
4353
|
与 subagentHeaders 同一套失效口径(文件一变就换键),但**只对当前会话的后代**按需读:
|
|
@@ -3616,7 +4550,18 @@ function isRunningEntry(one, now) {
|
|
|
3616
4550
|
**没法用真实夹构造**(header 与首个 turn/start 压在同一 zstd 帧里,
|
|
3617
4551
|
header 可读就必然能读到 turn/start)。传一个不存在的 file 路径就能精确命中它。
|
|
3618
4552
|
宿主只消费 `apply`,多导出一个纯函数不影响加载。 */
|
|
3619
|
-
|
|
4553
|
+
/* 仅测试用的内部入口(与 isRunningEntry 同样的先例):
|
|
4554
|
+
verify-subagent-total / verify-timing / verify-host 直接驱动这些纯逻辑与缓存,
|
|
4555
|
+
避免为了测试再造一套会话日志。生产路径不会调用它们。 */
|
|
4556
|
+
export {
|
|
4557
|
+
isRunningEntry,
|
|
4558
|
+
IDLE_EVENT_TYPES,
|
|
4559
|
+
parentLogFactsOf,
|
|
4560
|
+
parentLogFactsOfText,
|
|
4561
|
+
currentProfileDir,
|
|
4562
|
+
subagentFileEntryBytes,
|
|
4563
|
+
putSubagentFileCacheEntry,
|
|
4564
|
+
}
|
|
3620
4565
|
|
|
3621
4566
|
/* 「上下文占用百分比」的缓存(键 = 子会话文件 + mtime + size)。
|
|
3622
4567
|
为什么要它:算这个数要拿到**最后一条** usage 与 **最后一条** request/context,
|
|
@@ -3866,16 +4811,11 @@ async function subagentFileUsageAsync(one, fromMs, fingerprint) {
|
|
|
3866
4811
|
/* 传 0 = 不做窗口筛选,把整份日志的 usage 事件都收下来 */
|
|
3867
4812
|
const picked = await pickUsageEventsAsync(text, 0)
|
|
3868
4813
|
picked.forEach((event) => {
|
|
3869
|
-
entry.events.push({ time: event.time, model: event.model, parts: event.parts })
|
|
4814
|
+
entry.events.push({ time: event.time, model: event.model, provider: event.provider, parts: event.parts })
|
|
3870
4815
|
})
|
|
3871
4816
|
entry.stats = foldSessionTiming(text)
|
|
3872
4817
|
}
|
|
3873
|
-
|
|
3874
|
-
while (subagentFileCache.size > SUBAGENT_FILE_CACHE_MAX) {
|
|
3875
|
-
const oldest = subagentFileCache.keys().next()
|
|
3876
|
-
if (oldest.done === true) break
|
|
3877
|
-
subagentFileCache.delete(oldest.value)
|
|
3878
|
-
}
|
|
4818
|
+
putSubagentFileCacheEntry(aggKey, entry)
|
|
3879
4819
|
return usageAggOfEntry(entry, fromMs)
|
|
3880
4820
|
}
|
|
3881
4821
|
|
|
@@ -3891,7 +4831,8 @@ function usageAggOfEntry(entry, fromMs) {
|
|
|
3891
4831
|
agg.tokens.output += parts.output
|
|
3892
4832
|
/* 一次 usage 事件 = 一次调用(pickUsageEvents 已按 turn/step 去过重、全 0 的不算) */
|
|
3893
4833
|
agg.calls += 1
|
|
3894
|
-
const
|
|
4834
|
+
const multiplier = relayFeeMultiplierForProvider(event.provider)
|
|
4835
|
+
const amount = tokenCost(event.model, event.time, parts, event.provider, multiplier)
|
|
3895
4836
|
agg.cost += amount
|
|
3896
4837
|
/* 同一笔同时按"模型条目的币种"分桶:客户端混币时要折成一个数字(见 tokenCostCurrency) */
|
|
3897
4838
|
const code = tokenCostCurrency(event.model)
|
|
@@ -3900,6 +4841,24 @@ function usageAggOfEntry(entry, fromMs) {
|
|
|
3900
4841
|
return agg
|
|
3901
4842
|
}
|
|
3902
4843
|
|
|
4844
|
+
/** 测试用:清空两份子智能体缓存并复位字节账,避免用例之间互相污染。 */
|
|
4845
|
+
export function resetSubagentCachesForTest() {
|
|
4846
|
+
subagentFileCache.clear()
|
|
4847
|
+
subagentFileCacheBytes = 0
|
|
4848
|
+
subagentSinceCache.clear()
|
|
4849
|
+
subagentSinceCacheBytes = 0
|
|
4850
|
+
}
|
|
4851
|
+
|
|
4852
|
+
/** 测试用:读缓存规模/字节账(只读,不改状态)。 */
|
|
4853
|
+
export function subagentCacheStatsForTest() {
|
|
4854
|
+
return {
|
|
4855
|
+
fileSize: subagentFileCache.size,
|
|
4856
|
+
fileBytes: subagentFileCacheBytes,
|
|
4857
|
+
sinceSize: subagentSinceCache.size,
|
|
4858
|
+
sinceBytes: subagentSinceCacheBytes,
|
|
4859
|
+
}
|
|
4860
|
+
}
|
|
4861
|
+
|
|
3903
4862
|
/**
|
|
3904
4863
|
* 从 `sessionId` 出发,把它**全部后代**(多层:队友再开队友)的用量汇总起来。
|
|
3905
4864
|
*
|
|
@@ -3915,7 +4874,7 @@ function usageAggOfEntry(entry, fromMs) {
|
|
|
3915
4874
|
* · `host`:没传 → host 读**父会话自己**的日志推一个起点(最后一条 `turn/start`,
|
|
3916
4875
|
* 但和最后一条**真实用户输入**的 `user/message` 取较新的那个 —— 后者更新说明新一轮
|
|
3917
4876
|
* 已开始、其 `turn/start` 还没落盘,沿用旧起点会把上一轮算进来;同轮注入的
|
|
3918
|
-
* subagent-settled / team-message / tool-jobs 等通知不算,见
|
|
4877
|
+
* subagent-settled / team-message / tool-jobs 等通知不算,见 parentLogFactsOfText 的 since 规则);
|
|
3919
4878
|
* 而且**推出来的起点之后必须真的有用量事件**,否则说明起点无从验证,同样当
|
|
3920
4879
|
* `none`(宁少不多);
|
|
3921
4880
|
* · `none`:父会话日志缺失/读不出,或推出来的起点事后没有事件 → 本轮**什么都不并**
|
|
@@ -3929,13 +4888,23 @@ function usageAggOfEntry(entry, fromMs) {
|
|
|
3929
4888
|
* 前一个刚写好的缓存,同一批日志不会被重复冷解压。
|
|
3930
4889
|
*/
|
|
3931
4890
|
function collectSubagentUsage(sessionId, sinceMs) {
|
|
3932
|
-
|
|
4891
|
+
/* 同一会话、同一窗口的并发请求直接共享一个 Promise:客户端一次到期会并发问两个窗口
|
|
4892
|
+
(整会话 since=0 + 本轮 since=...),React 严格模式下还可能重复发同一问。
|
|
4893
|
+
共享后同键请求只排一次台账队列、只跑一次聚合。 */
|
|
4894
|
+
const shareKey = String(sessionId) + '|' + String(sinceMs)
|
|
4895
|
+
const pending = subagentUsageInflight.get(shareKey)
|
|
4896
|
+
if (pending !== undefined) return pending
|
|
4897
|
+
const run = queueLedgerJob(() => collectSubagentUsageNow(sessionId, sinceMs))
|
|
4898
|
+
subagentUsageInflight.set(shareKey, run)
|
|
4899
|
+
const clear = () => { if (subagentUsageInflight.get(shareKey) === run) subagentUsageInflight.delete(shareKey) }
|
|
4900
|
+
void run.then(clear, clear)
|
|
4901
|
+
return run
|
|
3933
4902
|
}
|
|
3934
4903
|
|
|
3935
4904
|
async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
3936
4905
|
/* 价格指纹:并进两个缓存键。改价后必须按新价重算 —— 否则队友那段会一直挂着旧价,
|
|
3937
4906
|
同一个「总计」里本会话用新价、队友用旧价(实测缺陷)。 */
|
|
3938
|
-
const fingerprint = priceFingerprint()
|
|
4907
|
+
const fingerprint = priceFingerprint() + '|relay:' + relayFeeFingerprint()
|
|
3939
4908
|
const clientSince = typeof sinceMs === 'number' && Number.isFinite(sinceMs) && sinceMs >= 0 ? sinceMs : null
|
|
3940
4909
|
const files = sessionFilesCached()
|
|
3941
4910
|
const index = await subagentIndexSnapshot(files)
|
|
@@ -3964,11 +4933,11 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
3964
4933
|
|
|
3965
4934
|
/* 窗口起点从哪来:① 客户端给了(它精确知道自己那一轮)→ `client`;
|
|
3966
4935
|
② 没给就问 host 自己 —— 读**父会话自己**的日志取最后一条 turn/start(或更新的
|
|
3967
|
-
真实用户 user/message,见
|
|
4936
|
+
真实用户 user/message,见 parentLogFactsOfText;同轮注入的通知不算)→ `host`;
|
|
3968
4937
|
③ 两者都没有(父会话文件缺失/读不出)→ `none`:**本轮什么都不并**
|
|
3969
4938
|
(用户规则:本轮只能小不能大,绝不能拿整会话的量顶上)。
|
|
3970
4939
|
另外 host 推的起点还要过一道"事后有事件"的验证(见下面聚合之后的那段)。 */
|
|
3971
|
-
const parentEntry = index.byId.get(sessionId)
|
|
4940
|
+
const parentEntry = refreshSubagentEntryStat(index.byId.get(sessionId))
|
|
3972
4941
|
let sinceSource = 'none'
|
|
3973
4942
|
let fromMs = null
|
|
3974
4943
|
let clamped = false
|
|
@@ -3982,14 +4951,14 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
3982
4951
|
兜一道:**只在收紧方向**生效(取较新的那个),绝不把窗口放大。
|
|
3983
4952
|
`since=0` 是客户端显式要的整会话(「总计」那一问),不参与收敛。 */
|
|
3984
4953
|
if (clientSince > 0 && parentEntry !== undefined) {
|
|
3985
|
-
const hostSince = parentTurnStartOf(parentEntry)
|
|
4954
|
+
const hostSince = await parentTurnStartOf(parentEntry)
|
|
3986
4955
|
if (hostSince !== null && hostSince > fromMs) {
|
|
3987
4956
|
fromMs = hostSince
|
|
3988
4957
|
clamped = true
|
|
3989
4958
|
}
|
|
3990
4959
|
}
|
|
3991
4960
|
} else if (parentEntry !== undefined) {
|
|
3992
|
-
const hostSince = parentTurnStartOf(parentEntry)
|
|
4961
|
+
const hostSince = await parentTurnStartOf(parentEntry)
|
|
3993
4962
|
if (hostSince !== null) {
|
|
3994
4963
|
sinceSource = 'host'
|
|
3995
4964
|
fromMs = hostSince
|
|
@@ -4004,14 +4973,16 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
4004
4973
|
const parts = []
|
|
4005
4974
|
const reading = []
|
|
4006
4975
|
for (let i = 0; i < found.length; i += 1) {
|
|
4007
|
-
/*
|
|
4976
|
+
/* 只对“当前会话真正相关”的条目重新 stat:索引里的 mtime/size 可能停在上次读头时。
|
|
4977
|
+
`parentSession` 一并带上:分层计数要区分「直接后代(团队成员 / 团队外子智能体)」
|
|
4008
4978
|
与「更深一层(成员下派的孙会话)」,判据就是 parentSession 是不是当前会话。
|
|
4009
4979
|
注意 `found` 是**全部后代**(BFS,含孙辈及以上),所以这里不需要再单独查子表。 */
|
|
4980
|
+
const fresh = refreshSubagentEntryStat(found[i])
|
|
4010
4981
|
reading.push({
|
|
4011
|
-
id:
|
|
4012
|
-
parentSession:
|
|
4982
|
+
id: fresh.id, file: fresh.file, mtimeMs: fresh.mtimeMs, size: fresh.size,
|
|
4983
|
+
parentSession: fresh.parentSession,
|
|
4013
4984
|
})
|
|
4014
|
-
parts.push(
|
|
4985
|
+
parts.push(fresh.id + ':' + String(fresh.mtimeMs) + ':' + String(fresh.size))
|
|
4015
4986
|
}
|
|
4016
4987
|
/* 这几个字段**不受窗口影响**,所以在缓存检查之前就算好,命中缓存时也能带上:
|
|
4017
4988
|
· running / teamRunning / deepRunning / 两个 ContextPercent:谁在跑、以及那一级的
|
|
@@ -4022,7 +4993,7 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
4022
4993
|
必须给 null,见下面的 turnStartFor。 */
|
|
4023
4994
|
const runInfo = runningBreakdownOf(sessionId, reading, parentEntry, index)
|
|
4024
4995
|
const running = runInfo.running
|
|
4025
|
-
const hostTurnStart = parentEntry === undefined ? null : parentTurnStartOf(parentEntry)
|
|
4996
|
+
const hostTurnStart = parentEntry === undefined ? null : await parentTurnStartOf(parentEntry)
|
|
4026
4997
|
/* 语义与 sinceSource 对齐:none(推不出 / 推出来事后没证据)时给 null。 */
|
|
4027
4998
|
const turnStartFor = (source) => (source === 'none' ? null : hostTurnStart)
|
|
4028
4999
|
/* 新出现的子会话会改变文件集合(索引重建后出现在 found 里),键自然就变了;
|
|
@@ -4100,7 +5071,7 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
4100
5071
|
两条都不成立时才按用户的"宁少不多"当没有窗口 —— 本轮不含队友。
|
|
4101
5072
|
判断只用已经折好的标量(父会话日志的最大用量时间、同一个窗口的聚合结果),
|
|
4102
5073
|
没有再解压一遍。 */
|
|
4103
|
-
const parentFacts = sinceSource === 'host' && parentEntry !== undefined ? parentLogFactsOf(parentEntry) : null
|
|
5074
|
+
const parentFacts = sinceSource === 'host' && parentEntry !== undefined ? await parentLogFactsOf(parentEntry) : null
|
|
4104
5075
|
const parentProduced = parentFacts !== null && parentFacts.lastUsageAt !== null
|
|
4105
5076
|
&& fromMs !== null && parentFacts.lastUsageAt >= fromMs
|
|
4106
5077
|
if (sinceSource === 'host' && parentProduced !== true && total.calls === 0) {
|
|
@@ -4208,6 +5179,10 @@ function ledgerPath() {
|
|
|
4208
5179
|
* 'done' = 已经重算完,恢复"只增量、不重算"的原有语义
|
|
4209
5180
|
*/
|
|
4210
5181
|
const LEDGER_VERSION = 4
|
|
5182
|
+
/* `ledger.files` 上限:会话文件只增不减,必须给扫描标记一个硬上限(见 pruneLedger)。 */
|
|
5183
|
+
const LEDGER_FILES_MAX = 4000
|
|
5184
|
+
/* v2:修复 USD 历史未重算(v1 用当前价库取价,重启后只剩内置 CNY 表,USD relay 整类漏算)。 */
|
|
5185
|
+
const PROVIDER_PRICING_AUDIT_VERSION = 2
|
|
4211
5186
|
|
|
4212
5187
|
function emptyLedger() {
|
|
4213
5188
|
return {
|
|
@@ -4216,6 +5191,7 @@ function emptyLedger() {
|
|
|
4216
5191
|
priceFingerprint: '',
|
|
4217
5192
|
unpricedBackfill: '',
|
|
4218
5193
|
costByCurrencyBackfill: 'done',
|
|
5194
|
+
providerPricingAuditVersion: '',
|
|
4219
5195
|
days: {},
|
|
4220
5196
|
seen: {},
|
|
4221
5197
|
sessions: {},
|
|
@@ -4260,6 +5236,7 @@ function migrateLedger(parsed) {
|
|
|
4260
5236
|
priceFingerprint: typeof parsed.priceFingerprint === 'string' ? parsed.priceFingerprint : '',
|
|
4261
5237
|
unpricedBackfill: typeof parsed.unpricedBackfill === 'string' ? parsed.unpricedBackfill : '',
|
|
4262
5238
|
costByCurrencyBackfill: typeof parsed.costByCurrencyBackfill === 'string' ? parsed.costByCurrencyBackfill : 'done',
|
|
5239
|
+
providerPricingAuditVersion: typeof parsed.providerPricingAuditVersion === 'number' ? parsed.providerPricingAuditVersion : '',
|
|
4263
5240
|
days: pick(parsed.days),
|
|
4264
5241
|
seen: pick(parsed.seen),
|
|
4265
5242
|
sessions: pick(parsed.sessions),
|
|
@@ -4357,7 +5334,13 @@ function writeLedger(ledger) {
|
|
|
4357
5334
|
}
|
|
4358
5335
|
}
|
|
4359
5336
|
} catch (error) {
|
|
4360
|
-
/*
|
|
5337
|
+
/* 落盘失败不能静默:下一次读到的还是旧台账,用户会以为"今天用过的量没记上"。
|
|
5338
|
+
至少写一行 stderr / host 日志,让排查有线索;内存里的台账仍然可用,不影响本次读数。 */
|
|
5339
|
+
const detail = error !== null && error !== undefined && typeof error.message === 'string'
|
|
5340
|
+
? error.message
|
|
5341
|
+
: String(error)
|
|
5342
|
+
logLedgerNote('usage-ledger: 写盘失败(' + target + '):' + detail)
|
|
5343
|
+
if (ctxRef !== null) logHost(ctxRef, 'usage-ledger: 写盘失败(' + target + '):' + detail)
|
|
4361
5344
|
}
|
|
4362
5345
|
}
|
|
4363
5346
|
|
|
@@ -4412,6 +5395,32 @@ function addUnpriced(day, model, parts, peakTime) {
|
|
|
4412
5395
|
day.unpriced = bucket
|
|
4413
5396
|
}
|
|
4414
5397
|
|
|
5398
|
+
function addUnpricedByProvider(day, provider, model, parts, peakTime, feeMultiplier) {
|
|
5399
|
+
const vendor = typeof provider === 'string' ? provider : ''
|
|
5400
|
+
const name = typeof model === 'string' && model.length > 0 ? model : '(未知模型)'
|
|
5401
|
+
const multiplier = typeof feeMultiplier === 'number' && Number.isFinite(feeMultiplier) && feeMultiplier > 0
|
|
5402
|
+
? feeMultiplier
|
|
5403
|
+
: 1
|
|
5404
|
+
const debts = Array.isArray(day.unpricedByProvider) ? day.unpricedByProvider : []
|
|
5405
|
+
let debt = debts.find((one) => one !== null && typeof one === 'object'
|
|
5406
|
+
&& one.provider === vendor && one.model === name && one.feeMultiplier === multiplier)
|
|
5407
|
+
if (debt === undefined) {
|
|
5408
|
+
debt = { provider: vendor, model: name, feeMultiplier: multiplier, peak: null, offPeak: null }
|
|
5409
|
+
debts.push(debt)
|
|
5410
|
+
}
|
|
5411
|
+
const key = peakTime === true ? 'peak' : 'offPeak'
|
|
5412
|
+
const raw = debt[key]
|
|
5413
|
+
const tier = raw !== null && typeof raw === 'object' && !Array.isArray(raw)
|
|
5414
|
+
? raw
|
|
5415
|
+
: { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 }
|
|
5416
|
+
tier.input = numOrZero(tier.input) + parts.input
|
|
5417
|
+
tier.cacheRead = numOrZero(tier.cacheRead) + parts.cacheRead
|
|
5418
|
+
tier.cacheWrite = numOrZero(tier.cacheWrite) + parts.cacheWrite
|
|
5419
|
+
tier.output = numOrZero(tier.output) + parts.output
|
|
5420
|
+
debt[key] = tier
|
|
5421
|
+
day.unpricedByProvider = debts
|
|
5422
|
+
}
|
|
5423
|
+
|
|
4415
5424
|
/** 一档用量按一档单价折成人民币(用量或单价缺失按 0 算)。 */
|
|
4416
5425
|
function costOfTier(parts, price) {
|
|
4417
5426
|
if (parts === null || parts === undefined) return 0
|
|
@@ -4435,34 +5444,180 @@ function settleUnpriced(ledger) {
|
|
|
4435
5444
|
const day = ledger.days[dates[i]]
|
|
4436
5445
|
if (day === null || day === undefined || typeof day !== 'object') continue
|
|
4437
5446
|
const bucket = day.unpriced
|
|
4438
|
-
if (bucket
|
|
4439
|
-
|
|
4440
|
-
|
|
4441
|
-
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
4446
|
-
|
|
4447
|
-
|
|
4448
|
-
|
|
5447
|
+
if (bucket !== null && bucket !== undefined && typeof bucket === 'object' && Array.isArray(bucket) !== true) {
|
|
5448
|
+
const names = Object.keys(bucket)
|
|
5449
|
+
for (let k = 0; k < names.length; k += 1) {
|
|
5450
|
+
const name = names[k]
|
|
5451
|
+
const entry = priceEntryFor(name)
|
|
5452
|
+
if (entry === null) continue
|
|
5453
|
+
const one = bucket[name]
|
|
5454
|
+
/* 外部损坏的单条欠账保留,不能让一次结算中断整个日账请求。 */
|
|
5455
|
+
if (one === null || one === undefined || typeof one !== 'object' || Array.isArray(one) === true) continue
|
|
5456
|
+
const peakPrice = entry.peak !== null && entry.peak !== undefined ? entry.peak : entry.offPeak
|
|
5457
|
+
const offPeakPrice = entry.tiered === false
|
|
5458
|
+
? peakPrice
|
|
5459
|
+
: (entry.offPeak !== null && entry.offPeak !== undefined ? entry.offPeak : entry.peak)
|
|
5460
|
+
const cost = (costOfTier(one.peak, peakPrice) + costOfTier(one.offPeak, offPeakPrice))
|
|
5461
|
+
* priceFeeMultiplier(entry)
|
|
5462
|
+
addDayCost(day, name, cost)
|
|
5463
|
+
amount += cost
|
|
5464
|
+
entries += 1
|
|
5465
|
+
delete bucket[names[k]]
|
|
5466
|
+
}
|
|
5467
|
+
if (Object.keys(bucket).length === 0) delete day.unpriced
|
|
5468
|
+
else day.unpriced = bucket
|
|
5469
|
+
}
|
|
5470
|
+
const debts = day.unpricedByProvider
|
|
5471
|
+
if (Array.isArray(debts) !== true) continue
|
|
5472
|
+
const remaining = []
|
|
5473
|
+
for (const debt of debts) {
|
|
5474
|
+
if (debt === null || typeof debt !== 'object' || typeof debt.model !== 'string'
|
|
5475
|
+
|| typeof debt.provider !== 'string' || typeof debt.feeMultiplier !== 'number'
|
|
5476
|
+
|| !Number.isFinite(debt.feeMultiplier) || debt.feeMultiplier <= 0) {
|
|
5477
|
+
remaining.push(debt)
|
|
5478
|
+
continue
|
|
5479
|
+
}
|
|
5480
|
+
const entry = priceEntryFor(debt.model)
|
|
5481
|
+
if (entry === null) {
|
|
5482
|
+
remaining.push(debt)
|
|
5483
|
+
continue
|
|
5484
|
+
}
|
|
4449
5485
|
const peakPrice = entry.peak !== null && entry.peak !== undefined ? entry.peak : entry.offPeak
|
|
4450
5486
|
const offPeakPrice = entry.tiered === false
|
|
4451
5487
|
? peakPrice
|
|
4452
5488
|
: (entry.offPeak !== null && entry.offPeak !== undefined ? entry.offPeak : entry.peak)
|
|
4453
|
-
const
|
|
4454
|
-
|
|
4455
|
-
|
|
5489
|
+
const affiliation = providerAffiliation(debt.provider, debt.model)
|
|
5490
|
+
const entryFee = affiliation === 'relay' ? relayPriceFee(entry) : 1
|
|
5491
|
+
/* 新口径:relay 必须明确配置倍率才结算;旧债务(feeMultiplier>1)保持兼容。 */
|
|
5492
|
+
if (affiliation === 'relay' && entryFee === null && !(debt.feeMultiplier > 1)) { remaining.push(debt); continue }
|
|
5493
|
+
const effectiveEntryFee = affiliation === 'relay' && entryFee !== null ? entryFee : 1
|
|
5494
|
+
const cost = (costOfTier(debt.peak, peakPrice) + costOfTier(debt.offPeak, offPeakPrice))
|
|
5495
|
+
* debt.feeMultiplier * effectiveEntryFee
|
|
5496
|
+
addDayCost(day, debt.model, cost)
|
|
4456
5497
|
amount += cost
|
|
4457
5498
|
entries += 1
|
|
4458
|
-
delete bucket[names[k]]
|
|
4459
5499
|
}
|
|
4460
|
-
if (
|
|
4461
|
-
else day.
|
|
5500
|
+
if (remaining.length === 0) delete day.unpricedByProvider
|
|
5501
|
+
else day.unpricedByProvider = remaining
|
|
4462
5502
|
}
|
|
4463
5503
|
return { entries, amount: Math.round(amount * 1e6) / 1e6 }
|
|
4464
5504
|
}
|
|
4465
5505
|
|
|
5506
|
+
/**
|
|
5507
|
+
* 历史重算用的价目表:优先用台账指纹还原的「记账当时那份」,缺的键再用当前价库补。
|
|
5508
|
+
*
|
|
5509
|
+
* 为什么不能只用当前价库:host 启动后、客户端上报价格库之前,`clientPrices` 是 null,
|
|
5510
|
+
* 当前价库只剩内置的两条 CNY 参考价。`gpt-6.1-sol` 这类 USD 中转模型在历史账上真实记过费,
|
|
5511
|
+
* 但不在内置表里 ⇒ `priceEntryFor` 返回 null ⇒ 整批 USD 事件被跳过,这就是 $388.19
|
|
5512
|
+
* 重算前后一分未变的根因(实测 2026-11-09)。台账指纹是重启后唯一还能还原历史单价的来源。
|
|
5513
|
+
*/
|
|
5514
|
+
function auditPriceBook(ledger) {
|
|
5515
|
+
const stored = parseFingerprint(ledger.priceFingerprint)
|
|
5516
|
+
if (stored === null) return activePriceBook()
|
|
5517
|
+
const current = activePriceBook()
|
|
5518
|
+
const out = {}
|
|
5519
|
+
for (const name of Object.keys(stored)) defineBookEntry(out, name, stored[name])
|
|
5520
|
+
for (const name of Object.keys(current)) {
|
|
5521
|
+
if (Object.prototype.hasOwnProperty.call(out, name) !== true) defineBookEntry(out, name, current[name])
|
|
5522
|
+
}
|
|
5523
|
+
return out
|
|
5524
|
+
}
|
|
5525
|
+
|
|
5526
|
+
/**
|
|
5527
|
+
* 一次性把 relay provider 的历史费用按「官方参考价 × 已配置倍率」重算;幂等、可恢复。
|
|
5528
|
+
*
|
|
5529
|
+
* v2 修复(task-13):v1 用**当前价库**取单价,重启后客户端还没上报价格时只剩内置 CNY 表,
|
|
5530
|
+
* USD 计价的 relay 模型(gpt-6.1-sol / remote-magpie/orbis/...)整类被漏掉,USD 历史原封不动。
|
|
5531
|
+
* v2 改为从 `ledger.priceFingerprint` 还原记账当时的价目表,并按模型命名空间兜底判 relay。
|
|
5532
|
+
*
|
|
5533
|
+
* v1 → v2 的迁移只补 USD:v1 已经改过的 CNY 不重算,避免同一笔被扣两次;
|
|
5534
|
+
* 全新台账(providerPricingAuditVersion 为空)仍按全币种重算。
|
|
5535
|
+
*/
|
|
5536
|
+
async function auditProviderPricingHistory(ledger, book) {
|
|
5537
|
+
if (ledger.providerPricingAuditVersion === PROVIDER_PRICING_AUDIT_VERSION) return null
|
|
5538
|
+
const previousVersion = typeof ledger.providerPricingAuditVersion === 'number' ? ledger.providerPricingAuditVersion : 0
|
|
5539
|
+
const auditBook = book !== undefined && book !== null ? book : auditPriceBook(ledger)
|
|
5540
|
+
/* v1 的价目表只有内置表;用它判断哪些模型 v1 已经处理过(只用于 v1→v2 迁移防重复扣)。 */
|
|
5541
|
+
const v1Book = previousVersion === 1 ? builtinPriceBook() : null
|
|
5542
|
+
const dates = Object.keys(ledger.days === undefined || ledger.days === null ? {} : ledger.days)
|
|
5543
|
+
if (dates.length === 0) {
|
|
5544
|
+
ledger.providerPricingAuditVersion = PROVIDER_PRICING_AUDIT_VERSION
|
|
5545
|
+
return { processedDays: 0, oldTotal: 0, newTotal: 0, missingFiles: 0, changes: [] }
|
|
5546
|
+
}
|
|
5547
|
+
const backup = ledgerPath() + '.bak-provider-pricing'
|
|
5548
|
+
try { statSync(backup) } catch (error) {
|
|
5549
|
+
try { copyFileSync(ledgerPath(), backup) } catch (copyError) { /* 台账文件不存在时无需备份 */ }
|
|
5550
|
+
}
|
|
5551
|
+
const stats = new Map()
|
|
5552
|
+
const files = sessionFilesCached()
|
|
5553
|
+
let missingFiles = 0
|
|
5554
|
+
for (const file of files) {
|
|
5555
|
+
let text = null
|
|
5556
|
+
try { text = await zstdTextAsync(await fsPromises.readFile(file)) } catch (error) { missingFiles += 1; continue }
|
|
5557
|
+
if (text === null) { missingFiles += 1; continue }
|
|
5558
|
+
let picked = null
|
|
5559
|
+
try { picked = await pickUsageEventsAsync(text, 0) } catch (error) { missingFiles += 1; continue }
|
|
5560
|
+
for (const one of picked.values()) {
|
|
5561
|
+
if (providerAffiliation(one.provider, one.model) !== 'relay') continue
|
|
5562
|
+
const entry = priceEntryIn(auditBook, one.model)
|
|
5563
|
+
if (entry === null) continue
|
|
5564
|
+
const code = entry.currency === 'USD' ? 'USD' : 'CNY'
|
|
5565
|
+
/* v1→v2:v1 已处理过非 USD 部分(用户看到的 900.30 就是修正后的 CNY 口径),
|
|
5566
|
+
v2 只补 v1 漏掉的 USD,避免重复扣减历史。 */
|
|
5567
|
+
if (v1Book !== null && code !== 'USD') continue
|
|
5568
|
+
if (v1Book !== null) {
|
|
5569
|
+
const v1Entry = priceEntryIn(v1Book, one.model)
|
|
5570
|
+
if (v1Entry !== null) {
|
|
5571
|
+
const v1Code = v1Entry.currency === 'USD' ? 'USD' : 'CNY'
|
|
5572
|
+
if (v1Code === code) continue
|
|
5573
|
+
}
|
|
5574
|
+
}
|
|
5575
|
+
const key = localDateKey(one.time)
|
|
5576
|
+
let slot = stats.get(key)
|
|
5577
|
+
if (slot === undefined) {
|
|
5578
|
+
slot = { oldCost: 0, newCost: 0, oldCurrency: {}, newCurrency: {}, debts: [] }
|
|
5579
|
+
stats.set(key, slot)
|
|
5580
|
+
}
|
|
5581
|
+
const officialCost = officialTokenCost(one.model, one.time, one.parts, auditBook)
|
|
5582
|
+
slot.oldCost += officialCost
|
|
5583
|
+
slot.oldCurrency[code] = numOrZero(slot.oldCurrency[code]) + officialCost
|
|
5584
|
+
const entryFee = relayPriceFee(entry)
|
|
5585
|
+
if (entryFee === null) {
|
|
5586
|
+
slot.debts.push({ provider: one.provider, model: one.model, parts: one.parts, peakTime: isPeakTime(one.time) })
|
|
5587
|
+
} else {
|
|
5588
|
+
const newCost = tokenCost(one.model, one.time, one.parts, one.provider, 1, auditBook)
|
|
5589
|
+
slot.newCost += newCost
|
|
5590
|
+
slot.newCurrency[code] = numOrZero(slot.newCurrency[code]) + newCost
|
|
5591
|
+
}
|
|
5592
|
+
}
|
|
5593
|
+
}
|
|
5594
|
+
let processedDays = 0
|
|
5595
|
+
const changes = []
|
|
5596
|
+
let oldTotal = 0
|
|
5597
|
+
let newTotal = 0
|
|
5598
|
+
for (const [key, slot] of stats) {
|
|
5599
|
+
const day = ledger.days[key]
|
|
5600
|
+
if (day === null || day === undefined || typeof day !== 'object') continue
|
|
5601
|
+
const oldCost = numOrZero(day.cost)
|
|
5602
|
+
const newCost = roundCost(Math.max(0, oldCost - slot.oldCost + slot.newCost))
|
|
5603
|
+
day.cost = newCost
|
|
5604
|
+
const book = day.costByCurrency !== null && day.costByCurrency !== undefined && typeof day.costByCurrency === 'object'
|
|
5605
|
+
? day.costByCurrency : {}
|
|
5606
|
+
const codes = new Set(Object.keys(slot.oldCurrency).concat(Object.keys(slot.newCurrency)))
|
|
5607
|
+
for (const code of codes) {
|
|
5608
|
+
book[code] = roundCost(Math.max(0, numOrZero(book[code]) - numOrZero(slot.oldCurrency[code]) + numOrZero(slot.newCurrency[code])))
|
|
5609
|
+
}
|
|
5610
|
+
day.costByCurrency = book
|
|
5611
|
+
for (const debt of slot.debts) addUnpricedByProvider(day, debt.provider, debt.model, debt.parts, debt.peakTime, 1)
|
|
5612
|
+
oldTotal += oldCost
|
|
5613
|
+
newTotal += newCost
|
|
5614
|
+
processedDays += 1
|
|
5615
|
+
changes.push({ date: key, oldCost: oldCost, newCost: newCost })
|
|
5616
|
+
}
|
|
5617
|
+
ledger.providerPricingAuditVersion = PROVIDER_PRICING_AUDIT_VERSION
|
|
5618
|
+
return { processedDays, oldTotal: roundCost(oldTotal), newTotal: roundCost(newTotal), missingFiles, changes }
|
|
5619
|
+
}
|
|
5620
|
+
|
|
4466
5621
|
/**
|
|
4467
5622
|
* 一次性回扫(升级后只做一次):v1/v2 台账没记过"哪些 token 当时没有单价",
|
|
4468
5623
|
* 只有会话日志里找得到。回扫只补这一件事:
|
|
@@ -4627,7 +5782,9 @@ async function accumulateRebuildInto(out, text, fromMs) {
|
|
|
4627
5782
|
if (priceEntryFor(one.model) === null) continue
|
|
4628
5783
|
const key = localDateKey(one.time)
|
|
4629
5784
|
const slot = rebuildCostBucket(out, key)
|
|
4630
|
-
|
|
5785
|
+
/* v4 重建按「官方参考价」算基线,provider 归属修正由 auditProviderPricingHistory 负责。
|
|
5786
|
+
这里必须用 officialTokenCost:模型前缀判 relay 后,tokenCost(provider='') 会算成 0。 */
|
|
5787
|
+
const amount = officialTokenCost(one.model, one.time, one.parts)
|
|
4631
5788
|
slot.cost += amount
|
|
4632
5789
|
const code = tokenCostCurrency(one.model)
|
|
4633
5790
|
slot.byCurrency[code] = (Object.prototype.hasOwnProperty.call(slot.byCurrency, code) ? slot.byCurrency[code] : 0) + amount
|
|
@@ -4790,8 +5947,14 @@ async function collectFileIntoLedger(ledger, file, text, fromMs, rebuilding) {
|
|
|
4790
5947
|
与 costByCurrency(正确的那份);**还没有单价的用量单独记成"欠账"**,
|
|
4791
5948
|
等用户在设置页把价补上再结算(补价只结算欠账,不动已经算好的费用)。
|
|
4792
5949
|
v4 重算那一轮的钱由重建通道独立算出并在末尾覆盖,这里不吃双份。 */
|
|
4793
|
-
|
|
4794
|
-
|
|
5950
|
+
const affiliation = providerAffiliation(one.provider, one.model)
|
|
5951
|
+
const entry = priceEntryFor(one.model)
|
|
5952
|
+
const relayFee = affiliation === "relay" && entry !== null ? relayPriceFee(entry) : null
|
|
5953
|
+
const priced = entry !== null && (affiliation !== "relay" || relayFee !== null)
|
|
5954
|
+
if (priced !== true) {
|
|
5955
|
+
/* relay 没配倍率:记 provider/model 欠账(feeMultiplier 记 1),绝不按官方价结算。 */
|
|
5956
|
+
addUnpricedByProvider(day, one.provider, one.model, one.parts, peakTime, affiliation === "relay" ? 1 : one.feeMultiplier)
|
|
5957
|
+
} else if (rebuilding !== true) addDayCost(day, one.model, tokenCost(one.model, one.time, one.parts, one.provider, one.feeMultiplier))
|
|
4795
5958
|
ledger.days[key] = day
|
|
4796
5959
|
added += 1
|
|
4797
5960
|
}
|
|
@@ -4803,6 +5966,7 @@ async function collectFileIntoLedger(ledger, file, text, fromMs, rebuilding) {
|
|
|
4803
5966
|
/** 丢掉太久以前的日桶与去重记录。保留期是滚动的「今天往前 400 天」,与统计窗口无关。 */
|
|
4804
5967
|
function pruneLedger(ledger) {
|
|
4805
5968
|
const keepFrom = localDateKey(Date.now() - 400 * 24 * 3600 * 1000)
|
|
5969
|
+
const keepFromMs = Date.now() - 400 * 24 * 3600 * 1000
|
|
4806
5970
|
for (const key of Object.keys(ledger.days)) {
|
|
4807
5971
|
if (key < keepFrom) delete ledger.days[key]
|
|
4808
5972
|
}
|
|
@@ -4813,6 +5977,26 @@ function pruneLedger(ledger) {
|
|
|
4813
5977
|
delete ledger.seen[sessionId]
|
|
4814
5978
|
}
|
|
4815
5979
|
}
|
|
5980
|
+
/* `ledger.files` 是“文件路径 → 扫描标记”:会话文件只增不减,这个对象会随使用无限长大。
|
|
5981
|
+
两道清理:① 标记里 mtime 已超出保留期的直接丢;② 总数超过上限时只留最近写过的 N 条。
|
|
5982
|
+
上限 4000 远大于本机常见会话文件数(实测 552),正常不会触发。 */
|
|
5983
|
+
const marks = Object.keys(ledger.files)
|
|
5984
|
+
if (marks.length > 0) {
|
|
5985
|
+
const kept = []
|
|
5986
|
+
for (const file of marks) {
|
|
5987
|
+
const mark = ledger.files[file]
|
|
5988
|
+
if (mark === null || mark === undefined || typeof mark !== 'object'
|
|
5989
|
+
|| (typeof mark.mtimeMs === 'number' && mark.mtimeMs < keepFromMs)) {
|
|
5990
|
+
delete ledger.files[file]
|
|
5991
|
+
continue
|
|
5992
|
+
}
|
|
5993
|
+
kept.push([file, mark])
|
|
5994
|
+
}
|
|
5995
|
+
if (kept.length > LEDGER_FILES_MAX) {
|
|
5996
|
+
kept.sort((a, b) => (Number(b[1].mtimeMs) || 0) - (Number(a[1].mtimeMs) || 0))
|
|
5997
|
+
for (let i = LEDGER_FILES_MAX; i < kept.length; i += 1) delete ledger.files[kept[i][0]]
|
|
5998
|
+
}
|
|
5999
|
+
}
|
|
4816
6000
|
}
|
|
4817
6001
|
|
|
4818
6002
|
/** 把一份 `{ CNY: n, USD: n }` 的书洗成干净对象:只留有限正数,其余丢弃。
|
|
@@ -4956,14 +6140,19 @@ function monthUsagePayload(ledger, monthStart) {
|
|
|
4956
6140
|
const key = localDateKey(at)
|
|
4957
6141
|
const inMonth = at >= monthStart && at <= monthEnd
|
|
4958
6142
|
const bucket = ledger.days[key]
|
|
6143
|
+
/* 日桶被外部改坏(null / 字符串 / 数字 / 数组)时一律当"这一天没有数据":
|
|
6144
|
+
只判 undefined 会让 null 在下面 `bucket.input` 直接抛 TypeError,整个
|
|
6145
|
+
/api/daily-usage 退化成 ledger-failed(J-1:周末坏桶只在月/年聚合里被读到)。 */
|
|
6146
|
+
const hasBucket = bucket !== null && bucket !== undefined
|
|
6147
|
+
&& typeof bucket === 'object' && Array.isArray(bucket) !== true
|
|
4959
6148
|
/* 三段明细一并带上:客户端悬停每天的方块时要显示命中 / 未命中 / 输出 */
|
|
4960
|
-
const input =
|
|
4961
|
-
const cacheRead =
|
|
4962
|
-
const cacheWrite =
|
|
4963
|
-
const output =
|
|
6149
|
+
const input = hasBucket ? bucket.input || 0 : 0
|
|
6150
|
+
const cacheRead = hasBucket ? bucket.cacheRead || 0 : 0
|
|
6151
|
+
const cacheWrite = hasBucket ? bucket.cacheWrite || 0 : 0
|
|
6152
|
+
const output = hasBucket ? bucket.output || 0 : 0
|
|
4964
6153
|
const total = input + cacheRead + cacheWrite + output
|
|
4965
|
-
const calls =
|
|
4966
|
-
const rawCost =
|
|
6154
|
+
const calls = hasBucket ? bucket.calls || 0 : 0
|
|
6155
|
+
const rawCost = hasBucket ? bucket.cost : 0
|
|
4967
6156
|
const cost = typeof rawCost === 'number' && Number.isFinite(rawCost) ? rawCost : 0
|
|
4968
6157
|
days.push({
|
|
4969
6158
|
date: key,
|
|
@@ -4972,7 +6161,7 @@ function monthUsagePayload(ledger, monthStart) {
|
|
|
4972
6161
|
calls,
|
|
4973
6162
|
cost: Math.round(cost * 10000) / 10000,
|
|
4974
6163
|
/* 分币种金额(task-52);老台账没有这个字段 ⇒ 空对象 */
|
|
4975
|
-
costByCurrency: dayCurrencyBook(bucket),
|
|
6164
|
+
costByCurrency: dayCurrencyBook(hasBucket ? bucket : null),
|
|
4976
6165
|
input,
|
|
4977
6166
|
cacheRead,
|
|
4978
6167
|
cacheWrite,
|
|
@@ -5008,7 +6197,9 @@ function yearUsagePayload(ledger, now) {
|
|
|
5008
6197
|
const byCurrency = {}
|
|
5009
6198
|
for (let d = 1; d <= daysInMonth; d += 1) {
|
|
5010
6199
|
const bucket = ledger.days[localDateKey(new Date(year, m - 1, d).getTime())]
|
|
5011
|
-
|
|
6200
|
+
/* 非对象(null / 字符串 / 数字 / 数组)一律当"这一天没有数据",与 weekUsagePayload 同口径。 */
|
|
6201
|
+
if (bucket === null || bucket === undefined
|
|
6202
|
+
|| typeof bucket !== 'object' || Array.isArray(bucket) === true) continue
|
|
5012
6203
|
input += bucket.input || 0
|
|
5013
6204
|
cacheRead += bucket.cacheRead || 0
|
|
5014
6205
|
cacheWrite += bucket.cacheWrite || 0
|
|
@@ -5313,6 +6504,10 @@ async function refreshWeekUsage(force, ctx) {
|
|
|
5313
6504
|
if (weekUsageScan === null) {
|
|
5314
6505
|
const run = queueLedgerJob(async () => {
|
|
5315
6506
|
const ledger = readLedger()
|
|
6507
|
+
/* 历史重算的价目表必须在任何扫描改动之前快照:本轮 collect 结束会把
|
|
6508
|
+
ledger.priceFingerprint 覆盖成"当前价库",而重启后当前价库可能只剩内置表。
|
|
6509
|
+
先按台账指纹还原记账当时那份,USD 模型(gpt-6.1-sol 等)才找得到单价。 */
|
|
6510
|
+
const auditBookSnapshot = auditPriceBook(ledger)
|
|
5316
6511
|
/* 升级后第一次扫描:回扫一遍日志,把"当时缺价、没算钱"的用量找出来。
|
|
5317
6512
|
只补欠账清单,历史 token 与 cost 一个都不动。 */
|
|
5318
6513
|
let backfilled = null
|
|
@@ -5321,6 +6516,16 @@ async function refreshWeekUsage(force, ctx) {
|
|
|
5321
6516
|
ledger.unpricedBackfill = 'done'
|
|
5322
6517
|
note('usage-ledger: 回扫补全缺价明细,处理了 ' + String(backfilled.scanned) + ' 个日志文件')
|
|
5323
6518
|
}
|
|
6519
|
+
/* 一次性历史重算:只改 relay provider 的历史成本,官方/points 不动。 */
|
|
6520
|
+
let providerAudit = null
|
|
6521
|
+
if (ledger.providerPricingAuditVersion !== PROVIDER_PRICING_AUDIT_VERSION) {
|
|
6522
|
+
providerAudit = await auditProviderPricingHistory(ledger, auditBookSnapshot)
|
|
6523
|
+
if (providerAudit !== null) {
|
|
6524
|
+
note('usage-ledger: provider 历史重算完成,处理 ' + String(providerAudit.processedDays) + ' 天(旧 ¥' + String(providerAudit.oldTotal) + ' → 新 ¥' + String(providerAudit.newTotal) + ')')
|
|
6525
|
+
for (const one of providerAudit.changes) note('usage-ledger: provider 历史重算 ' + String(one.date) + ':¥' + String(one.oldCost) + ' → ¥' + String(one.newCost))
|
|
6526
|
+
if (providerAudit.missingFiles > 0) note('usage-ledger: provider 历史重算跳过 ' + String(providerAudit.missingFiles) + ' 个无法读取的日志,相关日期保留原值')
|
|
6527
|
+
}
|
|
6528
|
+
}
|
|
5324
6529
|
/* 价格补上来了就把欠账结算掉(只碰欠账,不重算已经算好的费用) */
|
|
5325
6530
|
const settled = settleUnpriced(ledger)
|
|
5326
6531
|
if (settled.entries > 0) {
|
|
@@ -5333,7 +6538,7 @@ async function refreshWeekUsage(force, ctx) {
|
|
|
5333
6538
|
if (ledger.costByCurrencyBackfill === 'pending') ledger.costByCurrencyBackfill = 'done'
|
|
5334
6539
|
pruneLedger(ledger)
|
|
5335
6540
|
if (stats.added > 0 || stats.scannedFiles > 0 || ledger.updatedAt === 0
|
|
5336
|
-
|| settled.entries > 0 || backfilled !== null) {
|
|
6541
|
+
|| settled.entries > 0 || backfilled !== null || providerAudit !== null) {
|
|
5337
6542
|
ledger.updatedAt = Date.now()
|
|
5338
6543
|
writeLedger(ledger)
|
|
5339
6544
|
}
|
|
@@ -5451,32 +6656,49 @@ async function checkLatestVersion() {
|
|
|
5451
6656
|
|
|
5452
6657
|
/* ------------------------------------------------------------------ apply */
|
|
5453
6658
|
|
|
6659
|
+
/**
|
|
6660
|
+
* 注册一个 session projection,并把注册结果(Promise<ProjectionHandle>)等到真正 ready,
|
|
6661
|
+
* 卸载时调用 handle.dispose()。
|
|
6662
|
+
*
|
|
6663
|
+
* 为什么必须这样做:`sessionProjections.register` 是**异步**的,返回的是 awaitable handle;
|
|
6664
|
+
* 旧写法 `() => register(...)` 把 Promise 当成了清理函数 —— 注册失败无人知道,
|
|
6665
|
+
* 卸载时也不会 dispose,投影单元会一直留在注册表里(重复加载插件就重复计数)。
|
|
6666
|
+
*/
|
|
6667
|
+
function registerProjection(ctx, definition, label) {
|
|
6668
|
+
ctx.effect(() => {
|
|
6669
|
+
let disposed = false
|
|
6670
|
+
let handle = null
|
|
6671
|
+
const release = () => {
|
|
6672
|
+
disposed = true
|
|
6673
|
+
if (handle !== null && handle !== undefined && typeof handle.dispose === 'function') {
|
|
6674
|
+
try { void Promise.resolve(handle.dispose()).catch(() => undefined) } catch (error) { /* 卸载失败不阻断 */ }
|
|
6675
|
+
}
|
|
6676
|
+
}
|
|
6677
|
+
const ready = ctx.sessionProjections.register(definition)
|
|
6678
|
+
if (ready !== null && ready !== undefined && typeof ready.then === 'function') {
|
|
6679
|
+
/* 注册是异步的(可能做校验/恢复),失败要留日志,不能让投影静默缺席。 */
|
|
6680
|
+
ready.then((value) => {
|
|
6681
|
+
handle = value
|
|
6682
|
+
if (disposed === true) release()
|
|
6683
|
+
}, (error) => {
|
|
6684
|
+
logHost(ctxRef, 'session projection 注册失败(' + label + '):' + probeDetail(error))
|
|
6685
|
+
})
|
|
6686
|
+
/* effect 的清理函数保持**同步**:这样无论宿主怎么处理 Promise,卸载时都会走到 dispose。 */
|
|
6687
|
+
return release
|
|
6688
|
+
}
|
|
6689
|
+
/* 兼容旧宿主返回的 callable runtime value(已废弃,但老版本仍可能给) */
|
|
6690
|
+
return typeof ready === 'function' ? ready : undefined
|
|
6691
|
+
}, label)
|
|
6692
|
+
}
|
|
6693
|
+
|
|
5454
6694
|
export function apply(ctx) {
|
|
5455
6695
|
ctxRef = ctx
|
|
5456
|
-
ctx
|
|
5457
|
-
|
|
5458
|
-
|
|
5459
|
-
)
|
|
5460
|
-
ctx
|
|
5461
|
-
|
|
5462
|
-
'dsh-desktop-statusbar: sessionCapacity projection',
|
|
5463
|
-
)
|
|
5464
|
-
ctx.effect(
|
|
5465
|
-
() => ctx.sessionProjections.register(sessionProgressProjection),
|
|
5466
|
-
'dsh-desktop-statusbar: sessionProgress projection',
|
|
5467
|
-
)
|
|
5468
|
-
ctx.effect(
|
|
5469
|
-
() => ctx.sessionProjections.register(sessionUsageProjection),
|
|
5470
|
-
'dsh-desktop-statusbar: sessionUsage projection',
|
|
5471
|
-
)
|
|
5472
|
-
ctx.effect(
|
|
5473
|
-
() => ctx.sessionProjections.register(sessionTimeRangeProjection),
|
|
5474
|
-
'dsh-desktop-statusbar: sessionTimeRange projection',
|
|
5475
|
-
)
|
|
5476
|
-
ctx.effect(
|
|
5477
|
-
() => ctx.sessionProjections.register(sessionTimingProjection),
|
|
5478
|
-
'dsh-desktop-statusbar: sessionTiming projection',
|
|
5479
|
-
)
|
|
6696
|
+
registerProjection(ctx, sessionModelProjection, 'dsh-desktop-statusbar: sessionModel projection')
|
|
6697
|
+
registerProjection(ctx, sessionCapacityProjection, 'dsh-desktop-statusbar: sessionCapacity projection')
|
|
6698
|
+
registerProjection(ctx, sessionProgressProjection, 'dsh-desktop-statusbar: sessionProgress projection')
|
|
6699
|
+
registerProjection(ctx, sessionUsageProjection, 'dsh-desktop-statusbar: sessionUsage projection')
|
|
6700
|
+
registerProjection(ctx, sessionTimeRangeProjection, 'dsh-desktop-statusbar: sessionTimeRange projection')
|
|
6701
|
+
registerProjection(ctx, sessionTimingProjection, 'dsh-desktop-statusbar: sessionTiming projection')
|
|
5480
6702
|
|
|
5481
6703
|
/* 会话日志一旦被删就没了,台账是唯一留得住的地方:启动时先并一次作为预热,
|
|
5482
6704
|
之后只在用户打开活跃总览面板时(带 force=1)现扫。 */
|
|
@@ -5520,15 +6742,139 @@ export function apply(ctx) {
|
|
|
5520
6742
|
}), 'dsh-desktop-statusbar: balance api')
|
|
5521
6743
|
}
|
|
5522
6744
|
|
|
6745
|
+
async function updateRelayConfig(ctx, body) {
|
|
6746
|
+
const invalid = { status: 400, body: { ok: false, reason: 'bad-relay-config' } }
|
|
6747
|
+
if (body === null || typeof body !== 'object' || Array.isArray(body)) return invalid
|
|
6748
|
+
const current = readRelayConfig()
|
|
6749
|
+
if (current === null) throw new Error('relay-config-unavailable')
|
|
6750
|
+
if (body.remove !== undefined && body.remove !== true && body.remove !== false) return invalid
|
|
6751
|
+
const channelKey = body.channelKey
|
|
6752
|
+
if (!relayChannelKeyValid(channelKey)) return invalid
|
|
6753
|
+
const magpie = relayIsMagpie(channelKey)
|
|
6754
|
+
const existing = current.channels.find((channel) => magpie
|
|
6755
|
+
? relayIsMagpie(channel.channelKey)
|
|
6756
|
+
: channel.channelKey === channelKey) || null
|
|
6757
|
+
|
|
6758
|
+
if (body.remove === true) {
|
|
6759
|
+
if (Object.keys(body).some((key) => key !== 'remove' && key !== 'channelKey')) return invalid
|
|
6760
|
+
const channels = magpie
|
|
6761
|
+
? current.channels.filter((channel) => !relayIsMagpie(channel.channelKey))
|
|
6762
|
+
: current.channels.filter((channel) => channel.channelKey !== channelKey)
|
|
6763
|
+
if (magpie !== true) {
|
|
6764
|
+
const service = relayCredentials(ctx)
|
|
6765
|
+
if (service === null) throw new Error('credential-unavailable')
|
|
6766
|
+
const ref = relaySecretRef(channelKey)
|
|
6767
|
+
await service.resolve(ref)
|
|
6768
|
+
const next = { version: RELAY_CONFIG_VERSION, channels }
|
|
6769
|
+
writeRelayConfig(next)
|
|
6770
|
+
try {
|
|
6771
|
+
await service.unset(ref)
|
|
6772
|
+
} catch (error) {
|
|
6773
|
+
try { writeRelayConfig(current) } catch (nested) { /* preserve the original failure */ }
|
|
6774
|
+
throw error
|
|
6775
|
+
}
|
|
6776
|
+
} else {
|
|
6777
|
+
writeRelayConfig({ version: RELAY_CONFIG_VERSION, channels })
|
|
6778
|
+
}
|
|
6779
|
+
return { status: 200, body: await relayConfigView(ctx, channels) }
|
|
6780
|
+
}
|
|
6781
|
+
|
|
6782
|
+
const allowed = magpie
|
|
6783
|
+
? new Set(['channelKey', 'feeMultiplier', 'remove'])
|
|
6784
|
+
: new Set([
|
|
6785
|
+
'channelKey', 'endpoint', 'tokenHeader', 'userIdHeader', 'tokenPrefix',
|
|
6786
|
+
'balancePath', 'currency', 'feeMultiplier', 'balanceDivisor', 'token', 'userId', 'headers', 'remove',
|
|
6787
|
+
])
|
|
6788
|
+
if (Object.keys(body).some((key) => !allowed.has(key))) return invalid
|
|
6789
|
+
|
|
6790
|
+
if (magpie) {
|
|
6791
|
+
const feeMultiplier = body.feeMultiplier === undefined
|
|
6792
|
+
? (existing === null ? 1 : existing.feeMultiplier)
|
|
6793
|
+
: body.feeMultiplier
|
|
6794
|
+
if (!relayFeeMultiplierValid(feeMultiplier)) return invalid
|
|
6795
|
+
const channels = current.channels.filter((channel) => !relayIsMagpie(channel.channelKey))
|
|
6796
|
+
channels.push({ channelKey, feeMultiplier })
|
|
6797
|
+
const next = { version: RELAY_CONFIG_VERSION, channels }
|
|
6798
|
+
writeRelayConfig(next)
|
|
6799
|
+
return { status: 200, body: await relayConfigView(ctx, channels) }
|
|
6800
|
+
}
|
|
6801
|
+
|
|
6802
|
+
const previousSecrets = await resolveRelaySecrets(ctx, channelKey)
|
|
6803
|
+
if (previousSecrets === null) throw new Error('credential-unavailable')
|
|
6804
|
+
let token = previousSecrets.token
|
|
6805
|
+
if (body.token !== undefined) {
|
|
6806
|
+
if (body.token === null || body.token === '') token = ''
|
|
6807
|
+
else if (typeof body.token !== 'string' || body.token.length > 8192 || /[\r\n\0]/.test(body.token)) return invalid
|
|
6808
|
+
else token = body.token
|
|
6809
|
+
}
|
|
6810
|
+
let userId = previousSecrets.userId
|
|
6811
|
+
if (body.userId !== undefined) {
|
|
6812
|
+
if (body.userId === null || body.userId === '') userId = ''
|
|
6813
|
+
else if (typeof body.userId !== 'string' || body.userId.length > 256 || /[\r\n\0]/.test(body.userId)) return invalid
|
|
6814
|
+
else userId = body.userId
|
|
6815
|
+
}
|
|
6816
|
+
let headers = previousSecrets.headers
|
|
6817
|
+
if (body.headers !== undefined) {
|
|
6818
|
+
headers = sanitizeRelayHeaders(body.headers)
|
|
6819
|
+
if (headers === null) return invalid
|
|
6820
|
+
}
|
|
6821
|
+
const settings = relaySettings(body, existing, Object.keys(headers))
|
|
6822
|
+
if (settings === null) return invalid
|
|
6823
|
+
const channels = current.channels.slice()
|
|
6824
|
+
const index = channels.findIndex((channel) => channel.channelKey === channelKey)
|
|
6825
|
+
if (index === -1) channels.push(settings)
|
|
6826
|
+
else channels[index] = settings
|
|
6827
|
+
const next = { version: RELAY_CONFIG_VERSION, channels }
|
|
6828
|
+
writeRelayConfig(next)
|
|
6829
|
+
try {
|
|
6830
|
+
await storeRelaySecrets(ctx, channelKey, { token, userId, headers })
|
|
6831
|
+
} catch (error) {
|
|
6832
|
+
try { writeRelayConfig(current) } catch (nested) { /* preserve the original failure */ }
|
|
6833
|
+
throw error
|
|
6834
|
+
}
|
|
6835
|
+
return { status: 200, body: await relayConfigView(ctx, channels) }
|
|
6836
|
+
}
|
|
6837
|
+
|
|
5523
6838
|
async function handleApi(req, res, ctx) {
|
|
5524
6839
|
/* 带跨站 Origin 的写请求一律拒绝:浏览器里任意网页都能对本机发简单请求,
|
|
5525
6840
|
必须在**改任何状态之前**挡住(判定见 isCrossSiteWrite 的说明)。 */
|
|
5526
|
-
if (isCrossSiteWrite(req) === true) {
|
|
6841
|
+
if (isCrossSiteWrite(req, ctx) === true) {
|
|
5527
6842
|
logHost(ctx, 'api: 拒绝跨站写请求 origin=' + String(req.headers.origin))
|
|
5528
6843
|
sendJson(res, 403, { ok: false, reason: 'cross-origin' })
|
|
5529
6844
|
return
|
|
5530
6845
|
}
|
|
5531
6846
|
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
6847
|
+
if (url.pathname === '/dsh-desktop-statusbar/api/relay-balance-config') {
|
|
6848
|
+
if (req.method === 'GET') {
|
|
6849
|
+
try {
|
|
6850
|
+
const view = await queueRelayConfigWrite(async () => {
|
|
6851
|
+
const config = readRelayConfig()
|
|
6852
|
+
if (config === null) throw new Error('relay-config-unavailable')
|
|
6853
|
+
return relayConfigView(ctx, config.channels)
|
|
6854
|
+
})
|
|
6855
|
+
sendJson(res, 200, view)
|
|
6856
|
+
} catch (error) {
|
|
6857
|
+
sendJson(res, 500, { ok: false, reason: 'relay-config-failed' })
|
|
6858
|
+
}
|
|
6859
|
+
return
|
|
6860
|
+
}
|
|
6861
|
+
if (req.method !== 'POST') {
|
|
6862
|
+
sendJson(res, 405, { ok: false, reason: 'method-not-allowed' })
|
|
6863
|
+
return
|
|
6864
|
+
}
|
|
6865
|
+
try {
|
|
6866
|
+
const body = await readJsonBody(req)
|
|
6867
|
+
if (body === null) {
|
|
6868
|
+
sendJson(res, 400, { ok: false, reason: 'bad-relay-config' })
|
|
6869
|
+
return
|
|
6870
|
+
}
|
|
6871
|
+
const result = await queueRelayConfigWrite(() => updateRelayConfig(ctx, body))
|
|
6872
|
+
sendJson(res, result.status, result.body)
|
|
6873
|
+
} catch (error) {
|
|
6874
|
+
sendJson(res, 500, { ok: false, reason: 'relay-config-failed' })
|
|
6875
|
+
}
|
|
6876
|
+
return
|
|
6877
|
+
}
|
|
5532
6878
|
if (url.pathname === '/dsh-desktop-statusbar/api/prices') {
|
|
5533
6879
|
/* POST = 客户端把它的价格库(localStorage 那份,用户可增删改)报上来。
|
|
5534
6880
|
活跃总览的 cost 由 host 记账时算出,必须用同一份价格,否则用户在设置页
|
|
@@ -5836,7 +7182,8 @@ async function handleApi(req, res, ctx) {
|
|
|
5836
7182
|
fetchAndCacheRate({ logger: (message) => logHost(ctx, message) })
|
|
5837
7183
|
.catch(() => { /* 静默:汇率拉不到不影响余额 */ })
|
|
5838
7184
|
}
|
|
5839
|
-
const value = await queryBalance(ctx, force, url.searchParams.get('provider'), url.searchParams.get('model')
|
|
7185
|
+
const value = await queryBalance(ctx, force, url.searchParams.get('provider'), url.searchParams.get('model'),
|
|
7186
|
+
url.searchParams.get('relay'))
|
|
5840
7187
|
/* 把当前汇率一并交给客户端:余额是「当下的钱」,它要用**当前**汇率折算,
|
|
5841
7188
|
而汇率由 host 统一维护(每天 9:00 拉一次),客户端不必自己发请求。 */
|
|
5842
7189
|
sendJson(res, 200, Object.assign({}, value, { probe: accountProbeNote, exchangeRate: currentExchangeRate() }))
|