dsh-desktop-statusbar 3.0.1 → 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 -9203
- package/lib/exchange-rate.js +199 -0
- package/lib/holiday.js +128 -128
- package/lib/index.js +1975 -407
- package/lib/release-age.js +509 -509
- package/lib/self-update.js +913 -567
- 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,13 +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
|
-
import {
|
|
48
|
+
import { currentRate as currentExchangeRate, fetchAndCacheRate, nineAmOf, readCachedRate, shouldRefresh } from './exchange-rate.js'
|
|
49
|
+
import { createHash } from 'node:crypto'
|
|
50
|
+
import { appendFileSync, closeSync, copyFileSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
49
51
|
/* 异步读盘用:扫描热点上按文件 `fs.promises.readFile`,读 8 MB 日志的这 5 ms 也别占主线程。 */
|
|
50
52
|
import { promises as fsPromises } from 'node:fs'
|
|
51
|
-
import { basename, dirname, join } from 'node:path'
|
|
53
|
+
import { basename, dirname, join, sep } from 'node:path'
|
|
52
54
|
import { homedir } from 'node:os'
|
|
53
55
|
import * as zlib from 'node:zlib'
|
|
54
56
|
|
|
@@ -87,13 +89,19 @@ function logHost(ctx, message) {
|
|
|
87
89
|
const sessionModelSchema = z.object({
|
|
88
90
|
provider: z.string().nullable(),
|
|
89
91
|
model: z.string().nullable(),
|
|
90
|
-
|
|
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(),
|
|
91
99
|
}).strict()
|
|
92
100
|
|
|
93
101
|
const sessionModelProjection = {
|
|
94
102
|
key: 'desktopStatusbarModel',
|
|
95
103
|
stateSchema: sessionModelSchema,
|
|
96
|
-
init: () => ({ provider: null, model: null
|
|
104
|
+
init: () => ({ provider: null, model: null }),
|
|
97
105
|
apply: (state, event) => {
|
|
98
106
|
if (event.type !== 'assistant/message') return state
|
|
99
107
|
const source = event.data === undefined || event.data === null || event.data.message === undefined || event.data.message === null
|
|
@@ -102,10 +110,10 @@ const sessionModelProjection = {
|
|
|
102
110
|
if (source === null || source === undefined || source.kind !== 'model') return state
|
|
103
111
|
const { provider, model } = source
|
|
104
112
|
if (provider === state.provider && model === state.model) return state
|
|
105
|
-
return { provider, model
|
|
113
|
+
return { provider, model }
|
|
106
114
|
},
|
|
107
|
-
wire: { viewSchema:
|
|
108
|
-
stateVersion:
|
|
115
|
+
wire: { viewSchema: sessionModelViewSchema, view: (state) => ({ provider: state.provider, model: state.model }) },
|
|
116
|
+
stateVersion: 2,
|
|
109
117
|
}
|
|
110
118
|
|
|
111
119
|
/* ------------------------------------------------------------ sessionCapacity */
|
|
@@ -113,7 +121,12 @@ const sessionModelProjection = {
|
|
|
113
121
|
const sessionCapacitySchema = z.object({
|
|
114
122
|
contextWindow: z.number().nullable(),
|
|
115
123
|
maxOutputTokens: z.number().nullable(),
|
|
116
|
-
|
|
124
|
+
}).strict()
|
|
125
|
+
|
|
126
|
+
/* 客户端只读两个容量值;updatedAt 从未被读取,已从 state 与 wire 两处删除。 */
|
|
127
|
+
const sessionCapacityViewSchema = z.object({
|
|
128
|
+
contextWindow: z.number().nullable(),
|
|
129
|
+
maxOutputTokens: z.number().nullable(),
|
|
117
130
|
}).strict()
|
|
118
131
|
|
|
119
132
|
/**
|
|
@@ -125,7 +138,7 @@ const sessionCapacitySchema = z.object({
|
|
|
125
138
|
const sessionCapacityProjection = {
|
|
126
139
|
key: 'desktopStatusbarCapacity',
|
|
127
140
|
stateSchema: sessionCapacitySchema,
|
|
128
|
-
init: () => ({ contextWindow: null, maxOutputTokens: null
|
|
141
|
+
init: () => ({ contextWindow: null, maxOutputTokens: null }),
|
|
129
142
|
apply: (state, event) => {
|
|
130
143
|
const data = event.data === undefined || event.data === null ? {} : event.data
|
|
131
144
|
let contextWindow = state.contextWindow
|
|
@@ -141,10 +154,13 @@ const sessionCapacityProjection = {
|
|
|
141
154
|
return state
|
|
142
155
|
}
|
|
143
156
|
if (contextWindow === state.contextWindow && maxOutputTokens === state.maxOutputTokens) return state
|
|
144
|
-
return { contextWindow, maxOutputTokens
|
|
157
|
+
return { contextWindow, maxOutputTokens }
|
|
158
|
+
},
|
|
159
|
+
wire: {
|
|
160
|
+
viewSchema: sessionCapacityViewSchema,
|
|
161
|
+
view: (state) => ({ contextWindow: state.contextWindow, maxOutputTokens: state.maxOutputTokens }),
|
|
145
162
|
},
|
|
146
|
-
|
|
147
|
-
stateVersion: 1,
|
|
163
|
+
stateVersion: 2,
|
|
148
164
|
}
|
|
149
165
|
|
|
150
166
|
/* -------------------------------------------------------- sessionProgress */
|
|
@@ -199,6 +215,13 @@ const sessionProgressSchema = z.object({
|
|
|
199
215
|
compacts: z.array(compactMark),
|
|
200
216
|
}).strict()
|
|
201
217
|
|
|
218
|
+
/**
|
|
219
|
+
* 进度投影的 wire 视图:客户端只读 compacts 数组本身,顶层 compactTurn/compactStep
|
|
220
|
+
* 是“最近一次成功压缩”的冗余副本(客户端从 compacts[last] 自己取),不进 wire 视图。
|
|
221
|
+
* 状态里仍保留这两个字段(宿主语义与回归测试都按它们断言)。
|
|
222
|
+
*/
|
|
223
|
+
const sessionProgressViewSchema = sessionProgressSchema.omit({ compactTurn: true, compactStep: true })
|
|
224
|
+
|
|
202
225
|
/** 从 skill 工具的参数里取技能名;参数是 JSON 字符串,坏掉就当没这个名字。 */
|
|
203
226
|
function skillNameOf(data) {
|
|
204
227
|
let args = data.arguments
|
|
@@ -384,9 +407,15 @@ const sessionProgressProjection = {
|
|
|
384
407
|
一次 read 可能读多个文件(ops_read_files),按读到的顺序各记一条;
|
|
385
408
|
读的不是子能力文档(glossary.md 之类)时这里是空数组,什么都不记。 */
|
|
386
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
|
|
387
416
|
const counts = name === null ? state.toolCounts : {
|
|
388
417
|
...state.toolCounts,
|
|
389
|
-
[name]: (
|
|
418
|
+
[name]: (typeof prevCount === 'number' && Number.isFinite(prevCount) ? prevCount : 0) + 1,
|
|
390
419
|
}
|
|
391
420
|
let skills = state.skills
|
|
392
421
|
/* 技能有三种注入来源:调 skill 工具(自动/模型触发)、斜杠命令(user/message 分支,
|
|
@@ -428,7 +457,15 @@ const sessionProgressProjection = {
|
|
|
428
457
|
}
|
|
429
458
|
return state
|
|
430
459
|
},
|
|
431
|
-
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
|
+
},
|
|
432
469
|
// 字段变了(skills 变成 {name, manual}、compacts 加 manual 且只记成功、压缩 turn 可为 null),提升版本重建旧状态
|
|
433
470
|
// 7 → 8:compacts 新增 afterTurn(轮间/手动压缩显示「第 N 轮后」,替代原来的横杠)。
|
|
434
471
|
// 旧缓存里每条压缩记录没有这个字段,必须重放才能补出来。
|
|
@@ -530,6 +567,7 @@ function usageParts(usage) {
|
|
|
530
567
|
/** 一次模型调用的分量与发生时间,峰谷计价按它逐条判定。 */
|
|
531
568
|
const usageCall = z.object({
|
|
532
569
|
at: z.number(),
|
|
570
|
+
provider: z.string(),
|
|
533
571
|
model: z.string(),
|
|
534
572
|
input: z.number(),
|
|
535
573
|
cacheRead: z.number(),
|
|
@@ -549,8 +587,19 @@ const lastUsage = z.object({
|
|
|
549
587
|
}).strict()
|
|
550
588
|
|
|
551
589
|
const MAX_CALLS = 4000
|
|
552
|
-
|
|
553
|
-
|
|
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
|
+
}
|
|
554
603
|
|
|
555
604
|
/**
|
|
556
605
|
* 被 MAX_CALLS 截掉的调用,按「模型 + 峰谷档」累计的 token。
|
|
@@ -571,23 +620,31 @@ const overflowTier = z.object({
|
|
|
571
620
|
/** 往 overflow 里加一笔;返回新的 overflow(不改原对象)。 */
|
|
572
621
|
function addOverflow(overflow, model, parts, peak) {
|
|
573
622
|
const zero = () => ({ input: 0, cacheRead: 0, cacheWrite: 0, output: 0 })
|
|
574
|
-
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() }
|
|
575
628
|
const tierName = peak === true ? 'peak' : 'offPeak'
|
|
576
|
-
const
|
|
629
|
+
const rawTier = prev[tierName]
|
|
630
|
+
const tier = rawTier !== null && typeof rawTier === 'object' && !Array.isArray(rawTier) ? rawTier : zero()
|
|
577
631
|
return {
|
|
578
632
|
...overflow,
|
|
579
633
|
[model]: {
|
|
580
634
|
...prev,
|
|
581
635
|
[tierName]: {
|
|
582
|
-
input: tier.input + parts.input,
|
|
583
|
-
cacheRead: tier.cacheRead + parts.cacheRead,
|
|
584
|
-
cacheWrite: tier.cacheWrite + parts.cacheWrite,
|
|
585
|
-
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,
|
|
586
640
|
},
|
|
587
641
|
},
|
|
588
642
|
}
|
|
589
643
|
}
|
|
590
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
|
+
|
|
591
648
|
/**
|
|
592
649
|
* 把一笔调用并进总计:models 按模型累加、calls 追加,
|
|
593
650
|
* 超过 MAX_CALLS 被挤掉的最老几条按「模型 + 峰谷档」补进 overflow。
|
|
@@ -702,14 +759,17 @@ const sessionUsageProjection = {
|
|
|
702
759
|
: (fromMessage ? source.model : (typeof base.routeModel === 'string' ? base.routeModel : ''))
|
|
703
760
|
// 拿不到型号:放弃这一笔,好过抛错把整条投影(以及同一次驱动的其它投影)带停
|
|
704
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. */
|
|
705
764
|
const provider = isCompactionSummary
|
|
706
765
|
? (typeof data.provider === 'string' ? data.provider : '')
|
|
707
|
-
: (
|
|
708
|
-
? source.provider
|
|
709
|
-
: (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 : ''))
|
|
710
769
|
const parts = usageParts(usage)
|
|
711
770
|
const one = {
|
|
712
771
|
at: event.time,
|
|
772
|
+
provider,
|
|
713
773
|
model,
|
|
714
774
|
input: parts.input,
|
|
715
775
|
cacheRead: parts.cacheRead,
|
|
@@ -848,7 +908,11 @@ const sessionUsageProjection = {
|
|
|
848
908
|
// 官方 tokenUsage 投影不含摘要,导致「总计费用」含摘要而「总计用量」不含,同一面板两个口径。
|
|
849
909
|
// 旧缓存没有这个字段,不重放的话历史会话的「总计用量」会永远少那几笔摘要。
|
|
850
910
|
// 同一次 bump 也覆盖「轮间/手动压缩刷新本轮」的新语义(current 的重建规则变了)。
|
|
851
|
-
|
|
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,
|
|
852
916
|
}
|
|
853
917
|
|
|
854
918
|
/* -------------------------------------------------------- sessionTimeRange */
|
|
@@ -911,10 +975,22 @@ const sessionTimeRangeProjection = {
|
|
|
911
975
|
* (ttftMs/ttftSteps、decodeMs/decodeTokens),推不出单次极值,所以在 host 侧
|
|
912
976
|
* 按同一套事件口径自己折一份:`step/start` → 首个 token 分片 → `assistant/message`。
|
|
913
977
|
*
|
|
914
|
-
*
|
|
915
|
-
*
|
|
916
|
-
*
|
|
917
|
-
*
|
|
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 数、速度上下限、首字上限等任何数值条件剔除真实样本。
|
|
918
994
|
*/
|
|
919
995
|
const timingMark = z.object({
|
|
920
996
|
/* 首字极值单位是毫秒,速度极值单位是 tokens/秒,看字段名区分 */
|
|
@@ -928,8 +1004,10 @@ const timingStep = z.object({
|
|
|
928
1004
|
step: z.number(),
|
|
929
1005
|
startTime: z.number(),
|
|
930
1006
|
firstTokenTime: z.number().nullable(),
|
|
931
|
-
/* 首 token 是不是工具调用分片(速度极值据此排除) */
|
|
932
1007
|
firstTokenTool: z.boolean(),
|
|
1008
|
+
reasoning: z.boolean(),
|
|
1009
|
+
toolStarts: z.record(z.number()),
|
|
1010
|
+
toolIntervals: z.array(z.tuple([z.number(), z.number()])),
|
|
933
1011
|
}).strict()
|
|
934
1012
|
|
|
935
1013
|
const timingViewSchema = z.object({
|
|
@@ -1003,6 +1081,24 @@ function firstStreamToken(stream) {
|
|
|
1003
1081
|
return undefined
|
|
1004
1082
|
}
|
|
1005
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
|
+
|
|
1006
1102
|
/** 该步上报的输出 token 数;缺字段或非法值返回 null(这一步就不参与速度极值)。 */
|
|
1007
1103
|
function stepOutputTokens(usage) {
|
|
1008
1104
|
if (usage === null || usage === undefined || typeof usage !== 'object') return null
|
|
@@ -1013,22 +1109,36 @@ function stepOutputTokens(usage) {
|
|
|
1013
1109
|
const pickSmaller = (current, candidate) => (current === null || candidate.value < current.value ? candidate : current)
|
|
1014
1110
|
const pickLarger = (current, candidate) => (current === null || candidate.value > current.value ? candidate : current)
|
|
1015
1111
|
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
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
|
|
1032
1142
|
|
|
1033
1143
|
const sessionTimingProjection = {
|
|
1034
1144
|
key: 'desktopStatusbarTiming',
|
|
@@ -1062,22 +1172,66 @@ const sessionTimingProjection = {
|
|
|
1062
1172
|
turnDecodeTokens: sameTurn ? state.turnDecodeTokens : 0,
|
|
1063
1173
|
openStep: {
|
|
1064
1174
|
turn: data.turn, step: data.step, startTime: event.time,
|
|
1065
|
-
firstTokenTime: null, firstTokenTool: false,
|
|
1175
|
+
firstTokenTime: null, firstTokenTool: false, reasoning: false,
|
|
1176
|
+
toolStarts: {}, toolIntervals: [],
|
|
1066
1177
|
},
|
|
1067
1178
|
}
|
|
1068
1179
|
}
|
|
1069
1180
|
if (event.type === 'assistant/attempt') {
|
|
1070
1181
|
const open = state.openStep
|
|
1071
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)
|
|
1072
1184
|
const first = firstStreamToken(event.data.stream)
|
|
1073
|
-
|
|
1074
|
-
|
|
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
|
+
}
|
|
1075
1228
|
}
|
|
1076
1229
|
if (event.type === 'assistant/message') {
|
|
1077
1230
|
const open = state.openStep
|
|
1078
1231
|
if (open === null || open.turn !== event.data.turn || open.step !== event.data.step) return state
|
|
1079
|
-
const
|
|
1080
|
-
const
|
|
1232
|
+
const fromAttempt = open.firstTokenTime !== null
|
|
1233
|
+
const fromStream = fromAttempt ? undefined : firstStreamToken(event.data.stream)
|
|
1234
|
+
const first = fromAttempt
|
|
1081
1235
|
? { time: open.firstTokenTime, tool: open.firstTokenTool === true }
|
|
1082
1236
|
: fromStream
|
|
1083
1237
|
const next = { ...state, openStep: null }
|
|
@@ -1086,33 +1240,36 @@ const sessionTimingProjection = {
|
|
|
1086
1240
|
const model = source !== null && source !== undefined && typeof source.model === 'string' ? source.model : ''
|
|
1087
1241
|
const ttft = Math.max(0, first.time - open.startTime)
|
|
1088
1242
|
next.samples = state.samples + 1
|
|
1243
|
+
/* 首字极值如实统计所有能算出 ttft 的样本:含 message stream 兜底、含工具首片、含异常慢请求。
|
|
1244
|
+
不做「数值好看」的过滤 —— 只保留一条测量可信度:output>0 与非工具首片是 TPS 的门槛,
|
|
1245
|
+
首字本身只要首 token 时间可得就是真实值。 */
|
|
1089
1246
|
next.fastestTtft = pickSmaller(state.fastestTtft, { value: ttft, at: event.time, model })
|
|
1090
1247
|
next.slowestTtft = pickLarger(state.slowestTtft, { value: ttft, at: event.time, model })
|
|
1091
1248
|
next.turnTtftMs = state.turnTtftMs + ttft
|
|
1092
1249
|
next.turnTtftSamples = state.turnTtftSamples + 1
|
|
1093
1250
|
const output = stepOutputTokens(event.data.usage)
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
const
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
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
|
+
}
|
|
1116
1273
|
}
|
|
1117
1274
|
return next
|
|
1118
1275
|
}
|
|
@@ -1137,7 +1294,7 @@ const sessionTimingProjection = {
|
|
|
1137
1294
|
turnDecodeTokens: state.turnDecodeTokens,
|
|
1138
1295
|
}),
|
|
1139
1296
|
},
|
|
1140
|
-
stateVersion:
|
|
1297
|
+
stateVersion: 6,
|
|
1141
1298
|
}
|
|
1142
1299
|
|
|
1143
1300
|
/* ---------------------------------------------------------------- 余额查询 */
|
|
@@ -1190,33 +1347,23 @@ function sendJson(res, status, body) {
|
|
|
1190
1347
|
res.end(text)
|
|
1191
1348
|
}
|
|
1192
1349
|
|
|
1193
|
-
/*
|
|
1194
|
-
|
|
1195
|
-
(`Content-Type: text/plain` 的 POST 不触发 CORS 预检,页面读不到响应也照样**把请求送达**)。
|
|
1196
|
-
实测:伪造的价格库被完整接受,settleUnpriced 随后按攻击者单价结算进 `days[].cost`,
|
|
1197
|
-
而 cost 一旦记下就不再改动 —— 污染不可逆;同一面还能触发 /api/self-update 真跑 pnpm 安装。
|
|
1198
|
-
按用户确认的最小方案只做这一条判定,**不**引入 CORS 预检、**不**影响 GET:
|
|
1199
|
-
· 没有 Origin(命令行 / curl / 宿主内部)→ 放行;
|
|
1200
|
-
· Origin 的 host 与请求的 host 相同 → 同源,放行;
|
|
1201
|
-
· 带跨站 Origin(含 opaque 的 `null`)的 POST → 由调用方回 403。
|
|
1202
|
-
取不到 Host 头时判不了,保守放行(本机 webServer 一定带 Host,这一支只防意外形状)。 */
|
|
1203
|
-
function isCrossSiteWrite(req) {
|
|
1350
|
+
/* 写请求来源校验:没有 Origin 的命令行/宿主调用放行;带 Origin 的 POST 必须与监听器权威 origin 完全同源。 */
|
|
1351
|
+
function isCrossSiteWrite(req, ctx) {
|
|
1204
1352
|
if (req === null || req === undefined || req.method !== 'POST') return false
|
|
1205
1353
|
const headers = req.headers
|
|
1206
1354
|
if (headers === null || headers === undefined || typeof headers !== 'object') return false
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
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
|
+
}
|
|
1220
1367
|
}
|
|
1221
1368
|
|
|
1222
1369
|
/* 请求体上限。原先统一 4KB,但**价格库会随模型数增长**:实测一条模型约 186 字节,
|
|
@@ -1275,6 +1422,584 @@ function readJsonBody(req) {
|
|
|
1275
1422
|
})
|
|
1276
1423
|
}
|
|
1277
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
|
+
|
|
1278
2003
|
/** 环境变量是最高优先级的来源;refName 为空时按 DeepSeek 的引用名。 */
|
|
1279
2004
|
function keyFromEnv(refName) {
|
|
1280
2005
|
const name = typeof refName === 'string' && refName.length > 0 ? refName : 'DEEPSEEK_API_KEY'
|
|
@@ -1842,16 +2567,44 @@ function pickChainHit(ctx, targets, now) {
|
|
|
1842
2567
|
|
|
1843
2568
|
/* force 目前不改变行为(余额不缓存,每次请求都现查),但客户端点开气泡时会带 force=1
|
|
1844
2569
|
表达"强制刷新",保留该形参以维持 HTTP 契约,避免为省一个参数去动客户端回调。 */
|
|
1845
|
-
async function queryBalance(ctx, force, provider, model) {
|
|
2570
|
+
async function queryBalance(ctx, force, provider, model, relay) {
|
|
1846
2571
|
const now = Date.now()
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
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)
|
|
1855
2608
|
const adapter = chain.length > 0 ? chain[0] : null
|
|
1856
2609
|
if (adapter !== null && adapter.local === true) {
|
|
1857
2610
|
const local = await queryLocalAdapter(ctx, adapter, now, provider)
|
|
@@ -1876,7 +2629,6 @@ async function queryBalance(ctx, force, provider, model) {
|
|
|
1876
2629
|
|
|
1877
2630
|
/* 会话明确在用别的平台、但这个平台认不出来时不硬凑:硬凑会把 DeepSeek 的余额
|
|
1878
2631
|
当成对方的余额显示(比不显示更误导)。provider 还没上报(空)时才按 DeepSeek 处理。 */
|
|
1879
|
-
const hasProvider = typeof provider === 'string' && provider.trim().length > 0
|
|
1880
2632
|
if (adapter === null && hasProvider) {
|
|
1881
2633
|
const unknown = { ok: false, at: now, reason: 'unknown-platform' }
|
|
1882
2634
|
logHost(ctx, 'balance: 认不出 ' + provider + ' 属于哪个平台,不显示余额')
|
|
@@ -1920,9 +2672,11 @@ async function queryBalance(ctx, force, provider, model) {
|
|
|
1920
2672
|
logHost(ctx, 'balance: 使用来源 ' + String(found.source) + ' 的 key 查询余额')
|
|
1921
2673
|
|
|
1922
2674
|
try {
|
|
1923
|
-
|
|
2675
|
+
/* 端点与鉴权头也取自 adapter:request 与 parse 都只有一份实现,避免两处漂移。 */
|
|
2676
|
+
const spec = deepseekAdapter.request(found.key)
|
|
2677
|
+
const response = await fetch(spec.url, {
|
|
1924
2678
|
method: 'GET',
|
|
1925
|
-
headers:
|
|
2679
|
+
headers: spec.headers,
|
|
1926
2680
|
signal: AbortSignal.timeout(BALANCE_FETCH_TIMEOUT_MS),
|
|
1927
2681
|
})
|
|
1928
2682
|
if (!response.ok) {
|
|
@@ -1931,52 +2685,38 @@ async function queryBalance(ctx, force, provider, model) {
|
|
|
1931
2685
|
return failed
|
|
1932
2686
|
}
|
|
1933
2687
|
const data = await response.json()
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
const
|
|
1937
|
-
|
|
1938
|
-
if (picked === undefined) {
|
|
2688
|
+
/* 与 balance-api.js 的 deepseek adapter 共用同一份解析:两份实现漂移过一次,
|
|
2689
|
+
测试打 adapter 那份、生产走这份,绿了也不能证明线上正确。 */
|
|
2690
|
+
const parsed = parseDeepSeekBalance(data)
|
|
2691
|
+
if (parsed === null) {
|
|
1939
2692
|
const empty = { ok: false, at: now, reason: 'no-balance-info', source: found.source }
|
|
1940
2693
|
logHost(ctx, 'balance: 响应里没有 balance_infos')
|
|
1941
2694
|
return empty
|
|
1942
2695
|
}
|
|
2696
|
+
const grantedRaw = partAmount(parsed.parts, 'granted')
|
|
2697
|
+
const toppedUpRaw = partAmount(parsed.parts, 'toppedUp')
|
|
1943
2698
|
const value = {
|
|
1944
2699
|
ok: true,
|
|
1945
2700
|
at: now,
|
|
1946
2701
|
source: found.source,
|
|
1947
|
-
currency:
|
|
2702
|
+
currency: parsed.currency,
|
|
1948
2703
|
/* 与账号服务那条路同一套显示规则:截断到分,不足一分单独标出 */
|
|
1949
|
-
total: formatBalanceAmount(
|
|
1950
|
-
subCent: Number(
|
|
1951
|
-
granted:
|
|
1952
|
-
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),
|
|
1953
2708
|
available: data.is_available === true,
|
|
1954
2709
|
/* 分币种余额:DeepSeek 的 balance_infos 里可能同时有 CNY 和 USD。
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
/* 每笔也带上**自己的**充值与赠金(顶层 toppedUp/granted 只取第一笔的历史口径不动):
|
|
1966
|
-
客户端要把两个币种各自折成同一币种后相加,才能算出「充值 : 赠金」的真实比例。
|
|
1967
|
-
取不到就给 '0.00' —— 不给 undefined,客户端少一层判断。
|
|
1968
|
-
格式化与顶层一致(截断到分),保证两处数字口径相同。 */
|
|
1969
|
-
list.push({
|
|
1970
|
-
currency: info.currency === 'USD' ? 'USD' : 'CNY',
|
|
1971
|
-
total: String(info.total_balance),
|
|
1972
|
-
toppedUp: info.topped_up_balance === undefined || info.topped_up_balance === null
|
|
1973
|
-
? '0.00' : formatBalanceAmount(info.topped_up_balance),
|
|
1974
|
-
granted: info.granted_balance === undefined || info.granted_balance === null
|
|
1975
|
-
? '0.00' : formatBalanceAmount(info.granted_balance),
|
|
1976
|
-
})
|
|
1977
|
-
}
|
|
1978
|
-
return list.length === 0 ? undefined : list
|
|
1979
|
-
})(),
|
|
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,
|
|
1980
2720
|
}
|
|
1981
2721
|
logHost(ctx, 'balance: OK ' + String(value.total) + ' ' + String(value.currency))
|
|
1982
2722
|
return value
|
|
@@ -2096,6 +2836,18 @@ function tokenMatches(needle, hay) {
|
|
|
2096
2836
|
return needle === hay
|
|
2097
2837
|
}
|
|
2098
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
|
+
|
|
2099
2851
|
/** 一条价格是不是"什么都没填":两档四项加起来是 0。用来把未定价的条目挡在匹配之外。 */
|
|
2100
2852
|
function priceIsBlank(entry) {
|
|
2101
2853
|
if (entry === null || entry === undefined || typeof entry !== 'object') return true
|
|
@@ -2140,6 +2892,15 @@ function matchPriceKeyOnce(book, model, skipBlank) {
|
|
|
2140
2892
|
for (let i = 0; i < keys.length; i += 1) {
|
|
2141
2893
|
if (keys[i].toLowerCase() === lower && usable(keys[i])) return keys[i]
|
|
2142
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
|
+
}
|
|
2143
2904
|
/* ②③ 一次评选:子串命中的键与词元全含命中的键放在一起比 weight,取最具体的那个。
|
|
2144
2905
|
不能按"先全部子串、再全部词元"两轮跑 —— 那样模型名里只要含一个短键(如 flash),
|
|
2145
2906
|
就会把更具体的 deepseek-flash(只能靠词元档命中)挤掉。
|
|
@@ -2376,6 +3137,9 @@ function sanitizePriceBook(raw) {
|
|
|
2376
3137
|
/* 保留「是否峰谷计价」:没勾的条目是**全天一个价**,计价时两档都要取 peak,
|
|
2377
3138
|
否则空闲时段会挑到那个没填的档、把费用算成 0(实测缺陷)。缺省按两档。 */
|
|
2378
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
|
|
2379
3143
|
defineBookEntry(out, names[i], {
|
|
2380
3144
|
peak: peak !== null ? peak : offPeak,
|
|
2381
3145
|
offPeak: offPeak !== null ? offPeak : peak,
|
|
@@ -2386,6 +3150,9 @@ function sanitizePriceBook(raw) {
|
|
|
2386
3150
|
host 不替它决定(否则往返一次多出一个字段,深比较基准会被悄悄改掉)。
|
|
2387
3151
|
注意:必须保留,不保留就等于清洗时把币种丢了。 */
|
|
2388
3152
|
...(code === null ? {} : { currency: code }),
|
|
3153
|
+
...(feeConfigured === true
|
|
3154
|
+
? { feeConfigured: true, feeMultiplier: entryFee }
|
|
3155
|
+
: (entryFee === 1 ? {} : { feeMultiplier: entryFee })),
|
|
2389
3156
|
})
|
|
2390
3157
|
}
|
|
2391
3158
|
return Object.keys(out).length === 0 ? null : out
|
|
@@ -2435,6 +3202,8 @@ function fingerprintOf(book) {
|
|
|
2435
3202
|
rawOffPeak !== null ? rawOffPeak : rawPeak,
|
|
2436
3203
|
one !== null && one !== undefined && one.tiered === false ? 0 : 1,
|
|
2437
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,
|
|
2438
3207
|
])
|
|
2439
3208
|
}
|
|
2440
3209
|
return FINGERPRINT_MARK + JSON.stringify(rows)
|
|
@@ -2513,12 +3282,21 @@ function parseFingerprintRows(text) {
|
|
|
2513
3282
|
const peak = tier(row[1])
|
|
2514
3283
|
const offPeak = tier(row[2])
|
|
2515
3284
|
if (peak === null && offPeak === null) continue
|
|
2516
|
-
|
|
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 = {
|
|
2517
3288
|
peak: peak !== null ? peak : offPeak,
|
|
2518
3289
|
offPeak: offPeak !== null ? offPeak : peak,
|
|
2519
3290
|
tiered: row[3] !== 0,
|
|
2520
3291
|
currency: row[4] === 'USD' ? 'USD' : 'CNY',
|
|
2521
|
-
}
|
|
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)
|
|
2522
3300
|
}
|
|
2523
3301
|
return Object.keys(out).length === 0 ? null : out
|
|
2524
3302
|
}
|
|
@@ -2528,16 +3306,66 @@ function defineBookEntry(target, name, value) {
|
|
|
2528
3306
|
Object.defineProperty(target, name, { value: value, enumerable: true, writable: true, configurable: true })
|
|
2529
3307
|
}
|
|
2530
3308
|
|
|
2531
|
-
/**
|
|
2532
|
-
|
|
2533
|
-
|
|
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)
|
|
2534
3335
|
if (entry === null) return 0
|
|
2535
3336
|
/* 没勾「峰谷计价」= 全天一个价:两档都取 peak,否则空闲时段会挑到没填的那档、算成 0 */
|
|
2536
3337
|
const price = entry.tiered === false ? entry.peak : (isPeakTime(at) ? entry.peak : entry.offPeak)
|
|
2537
3338
|
const use = price !== null && price !== undefined ? price : entry.peak
|
|
2538
3339
|
if (use === null || use === undefined) return 0
|
|
2539
|
-
return (parts.input * numOrZero(use.input) + parts.cacheRead * numOrZero(use.cacheRead)
|
|
2540
|
-
+ parts.cacheWrite * numOrZero(use.cacheWrite) + parts.output * numOrZero(use.output)) / 1e6
|
|
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)
|
|
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)
|
|
3355
|
+
/* 没勾「峰谷计价」= 全天一个价:两档都取 peak,否则空闲时段会挑到没填的那档、算成 0 */
|
|
3356
|
+
const price = entry.tiered === false ? entry.peak : (isPeakTime(at) ? entry.peak : entry.offPeak)
|
|
3357
|
+
const use = price !== null && price !== undefined ? price : entry.peak
|
|
3358
|
+
if (use === null || use === undefined) return 0
|
|
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
|
|
2541
3369
|
}
|
|
2542
3370
|
|
|
2543
3371
|
/**
|
|
@@ -2546,8 +3374,8 @@ function tokenCost(model, at, parts) {
|
|
|
2546
3374
|
* 只服务于"按币种分桶汇总":**算钱本身不看币种**(台账、历史数字都不受影响),
|
|
2547
3375
|
* 客户端拿到分桶后按参考价比例折成底栏显示币种,混币时才能给出一个数字。
|
|
2548
3376
|
*/
|
|
2549
|
-
function tokenCostCurrency(model) {
|
|
2550
|
-
const entry = priceEntryFor(model)
|
|
3377
|
+
function tokenCostCurrency(model, book) {
|
|
3378
|
+
const entry = book === undefined || book === null ? priceEntryFor(model) : priceEntryIn(book, model)
|
|
2551
3379
|
return entry !== null && entry.currency === 'USD' ? 'USD' : 'CNY'
|
|
2552
3380
|
}
|
|
2553
3381
|
|
|
@@ -2681,36 +3509,62 @@ function collectSessionFiles(dir, out) {
|
|
|
2681
3509
|
/* 会话日志文件清单的缓存。
|
|
2682
3510
|
为什么要有它:这条路由(/api/subagent-usage)每秒被问 2 次,每次都全量递归
|
|
2683
3511
|
sessions 目录 + 逐文件 stat,实测 26ms/次 ≈ 52ms/s 白烧在主线程上;而目录内容
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
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
|
+
不需要名单层再兜。
|
|
2694
3525
|
|
|
2695
3526
|
返回的数组直接共享:调用点都只遍历、不 push / splice,所以不需要每次拷一份。 */
|
|
2696
|
-
const SESSION_FILES_TTL_MS =
|
|
2697
|
-
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 }
|
|
2698
3529
|
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
3530
|
+
/** sessions 目录的"形状签名":根 mtime + 每个 workspace 子目录的 mtime。 */
|
|
3531
|
+
function sessionDirsSignature(dir) {
|
|
3532
|
+
let entries
|
|
3533
|
+
try {
|
|
3534
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
3535
|
+
} catch (error) {
|
|
3536
|
+
return 'missing'
|
|
3537
|
+
}
|
|
3538
|
+
let rootMtime = -1
|
|
2703
3539
|
try {
|
|
2704
|
-
|
|
3540
|
+
rootMtime = statSync(dir).mtimeMs
|
|
2705
3541
|
} catch (error) {
|
|
2706
|
-
/*
|
|
2707
|
-
|
|
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))
|
|
2708
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)
|
|
2709
3563
|
const hit = sessionFilesCache
|
|
2710
|
-
if (hit.list !== null && hit.dir === dir && hit.
|
|
3564
|
+
if (hit.list !== null && hit.dir === dir && hit.sig === sig
|
|
2711
3565
|
&& now - hit.at < SESSION_FILES_TTL_MS) return hit.list
|
|
2712
3566
|
const list = collectSessionFiles(dir, [])
|
|
2713
|
-
sessionFilesCache = { at: now, dir: dir,
|
|
3567
|
+
sessionFilesCache = { at: now, dir: dir, sig: sig, list: list }
|
|
2714
3568
|
return list
|
|
2715
3569
|
}
|
|
2716
3570
|
|
|
@@ -2947,6 +3801,35 @@ function usageEventKey(event) {
|
|
|
2947
3801
|
return 'seq:' + String(event.seq)
|
|
2948
3802
|
}
|
|
2949
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
|
+
|
|
2950
3833
|
/**
|
|
2951
3834
|
* 从一段日志文本里挑出窗口内的用量事件。
|
|
2952
3835
|
* 同一个 key 只留一条,且 `assistant/message` 优先 —— 这样重试的 attempt 与最终消息
|
|
@@ -2954,8 +3837,11 @@ function usageEventKey(event) {
|
|
|
2954
3837
|
*/
|
|
2955
3838
|
function pickUsageEvents(text, fromMs) {
|
|
2956
3839
|
const picked = new Map()
|
|
3840
|
+
const feeConfig = relayFeeConfig()
|
|
3841
|
+
let route = { model: null, provider: '' }
|
|
2957
3842
|
for (const line of text.split('\n')) {
|
|
2958
|
-
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
|
|
2959
3845
|
let event
|
|
2960
3846
|
try {
|
|
2961
3847
|
event = JSON.parse(line)
|
|
@@ -2963,6 +3849,8 @@ function pickUsageEvents(text, fromMs) {
|
|
|
2963
3849
|
continue
|
|
2964
3850
|
}
|
|
2965
3851
|
if (event === null || typeof event !== 'object') continue
|
|
3852
|
+
const routed = routedModelOf(event)
|
|
3853
|
+
if (routed !== null) route = routed
|
|
2966
3854
|
if (typeof event.time !== 'number' || event.time < fromMs) continue
|
|
2967
3855
|
const usage = usageOfEvent(event)
|
|
2968
3856
|
if (usage === null) continue
|
|
@@ -2973,48 +3861,20 @@ function pickUsageEvents(text, fromMs) {
|
|
|
2973
3861
|
const key = usageEventKey(event)
|
|
2974
3862
|
const prev = picked.get(key)
|
|
2975
3863
|
if (prev === undefined || (prev.isMessage !== true && isMessage)) {
|
|
2976
|
-
|
|
2977
|
-
const source = data.message !== null && data.message !== undefined && typeof data.message === 'object'
|
|
2978
|
-
&& data.message.source !== null && data.message.source !== undefined && typeof data.message.source === 'object'
|
|
2979
|
-
? data.message.source
|
|
2980
|
-
: null
|
|
2981
|
-
/* 模型名的两个来源:assistant/message 在 message.source.model,
|
|
2982
|
-
而 compaction/summary(压缩摘要本身是一次真实模型调用)把模型放在顶层 data.model ——
|
|
2983
|
-
只认前者会让整笔摘要用量落进「(未知模型)」欠账,永远结算不出来。 */
|
|
2984
|
-
const model = source !== null && typeof source.model === 'string'
|
|
2985
|
-
? source.model
|
|
2986
|
-
: (typeof data.model === 'string' && data.model.length > 0 ? data.model : null)
|
|
2987
|
-
picked.set(key, {
|
|
2988
|
-
seq: typeof event.seq === 'number' ? event.seq : Math.round(event.time),
|
|
2989
|
-
time: event.time,
|
|
2990
|
-
parts: parts,
|
|
2991
|
-
isMessage: isMessage,
|
|
2992
|
-
/* 计价要用模型名(不同模型单价不同) */
|
|
2993
|
-
model: model,
|
|
2994
|
-
})
|
|
3864
|
+
picked.set(key, pickedUsageRecord(event, route, parts, feeConfig))
|
|
2995
3865
|
}
|
|
2996
3866
|
}
|
|
2997
3867
|
return picked
|
|
2998
3868
|
}
|
|
2999
3869
|
|
|
3000
3870
|
/**
|
|
3001
|
-
* `pickUsageEvents`
|
|
3002
|
-
* 同样的模型名解析),只多一件事 —— 每 200 行检查一次耗时,超过 8ms 就 `await setImmediate`。
|
|
3003
|
-
*
|
|
3004
|
-
* 为什么必须存在:异步解压把 zstd 扔进线程池之后,`JSON.parse` 成了新的最长同步块
|
|
3005
|
-
* (8.8MB 日志实测 312ms,纯主线程)。解压在别的线程跑、解析留在主线程,界面照样冻住。
|
|
3006
|
-
*
|
|
3007
|
-
* 三条刻意的写法(都不要"优化"掉):
|
|
3008
|
-
* · `picked` 声明在 `await` 之外 —— 跨让出点累积,绝不中途重建(否则后面那块会丢)。
|
|
3009
|
-
* · 时间检查放在 `i % 200 === 0`(第 0 行就算起点),每 200 行一次而不是每行一次 ——
|
|
3010
|
-
* 每行 `Date.now()` 是实打实的额外开销,大日志上几十万次。
|
|
3011
|
-
* · 让出用 `setImmediate` 而不是 `setTimeout(0)`:前者在 poll 之后立刻跑,不额外吃 1ms 定时器。
|
|
3012
|
-
*
|
|
3013
|
-
* 同步版保留不动:它是语义基准,`pickUsageEventsAsync` 的结果必须与它**逐字相等**。
|
|
3871
|
+
* `pickUsageEvents` 的可让出版本:逻辑逐条照搬同步版,并按需让出事件循环。
|
|
3014
3872
|
*/
|
|
3015
3873
|
async function pickUsageEventsAsync(text, fromMs) {
|
|
3016
3874
|
const lines = text.split('\n')
|
|
3017
3875
|
const picked = new Map()
|
|
3876
|
+
const feeConfig = relayFeeConfig()
|
|
3877
|
+
let route = { model: null, provider: '' }
|
|
3018
3878
|
let sliceStart = Date.now()
|
|
3019
3879
|
for (let i = 0; i < lines.length; i += 1) {
|
|
3020
3880
|
/* 让出检查必须在**循环体最前面**,不能放在过滤逻辑之后:
|
|
@@ -3027,7 +3887,8 @@ async function pickUsageEventsAsync(text, fromMs) {
|
|
|
3027
3887
|
sliceStart = Date.now()
|
|
3028
3888
|
}
|
|
3029
3889
|
const line = lines[i]
|
|
3030
|
-
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
|
|
3031
3892
|
let event
|
|
3032
3893
|
try {
|
|
3033
3894
|
event = JSON.parse(line)
|
|
@@ -3035,6 +3896,8 @@ async function pickUsageEventsAsync(text, fromMs) {
|
|
|
3035
3896
|
continue
|
|
3036
3897
|
}
|
|
3037
3898
|
if (event === null || typeof event !== 'object') continue
|
|
3899
|
+
const routed = routedModelOf(event)
|
|
3900
|
+
if (routed !== null) route = routed
|
|
3038
3901
|
if (typeof event.time !== 'number' || event.time < fromMs) continue
|
|
3039
3902
|
const usage = usageOfEvent(event)
|
|
3040
3903
|
if (usage === null) continue
|
|
@@ -3045,21 +3908,7 @@ async function pickUsageEventsAsync(text, fromMs) {
|
|
|
3045
3908
|
const key = usageEventKey(event)
|
|
3046
3909
|
const prev = picked.get(key)
|
|
3047
3910
|
if (prev === undefined || (prev.isMessage !== true && isMessage)) {
|
|
3048
|
-
|
|
3049
|
-
const source = data.message !== null && data.message !== undefined && typeof data.message === 'object'
|
|
3050
|
-
&& data.message.source !== null && data.message.source !== undefined && typeof data.message.source === 'object'
|
|
3051
|
-
? data.message.source
|
|
3052
|
-
: null
|
|
3053
|
-
const model = source !== null && typeof source.model === 'string'
|
|
3054
|
-
? source.model
|
|
3055
|
-
: (typeof data.model === 'string' && data.model.length > 0 ? data.model : null)
|
|
3056
|
-
picked.set(key, {
|
|
3057
|
-
seq: typeof event.seq === 'number' ? event.seq : Math.round(event.time),
|
|
3058
|
-
time: event.time,
|
|
3059
|
-
parts: parts,
|
|
3060
|
-
isMessage: isMessage,
|
|
3061
|
-
model: model,
|
|
3062
|
-
})
|
|
3911
|
+
picked.set(key, pickedUsageRecord(event, route, parts, feeConfig))
|
|
3063
3912
|
}
|
|
3064
3913
|
}
|
|
3065
3914
|
return picked
|
|
@@ -3078,15 +3927,45 @@ const SUBAGENT_MAX_DESCENDANTS = 2000
|
|
|
3078
3927
|
刚建好、header 还没落盘的文件下一次请求就能认出来,而真正的坏文件不会一直被反复读。
|
|
3079
3928
|
头部里的 id / parentSession 是会话创建时写死的,所以读成功的那份不会失效,只有 stat 变了才重读。
|
|
3080
3929
|
上限 SUBAGENT_HEADER_CACHE_MAX 条,超出丢最久没被重新写入的(Map 的插入顺序)。 */
|
|
3081
|
-
|
|
3930
|
+
/* 会话文件头缓存:每条只有 id/parentSession + 两个数字。上限 4096 覆盖本机常见会话数
|
|
3931
|
+
(实测 552 个文件),同时仍是硬上限,防畸形 sessions 树无限增长。 */
|
|
3932
|
+
const SUBAGENT_HEADER_CACHE_MAX = 4096
|
|
3082
3933
|
const subagentHeaders = new Map()
|
|
3083
3934
|
|
|
3935
|
+
/* 索引的“全量对账”周期:正常请求只 stat 当前会话相关文件;每 5 分钟把所有文件 stat 一遍,
|
|
3936
|
+
兜住“同一路径被替换成另一份日志”这类异常(header 里的 id/parentSession 是不可变的,
|
|
3937
|
+
正常写入不会改变它们,所以不需要每次请求都全量读)。 */
|
|
3938
|
+
const SUBAGENT_INDEX_RECONCILE_MS = 5 * 60 * 1000
|
|
3939
|
+
let subagentIndexReconcileAt = 0
|
|
3940
|
+
|
|
3084
3941
|
/** 两份同名会话文件谁更新:先比 mtime,一样再比 size(更大的一般更完整)。 */
|
|
3085
3942
|
function headerEntryNewer(candidate, current) {
|
|
3086
3943
|
if (candidate.mtimeMs !== current.mtimeMs) return candidate.mtimeMs > current.mtimeMs
|
|
3087
3944
|
return candidate.size > current.size
|
|
3088
3945
|
}
|
|
3089
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
|
+
|
|
3090
3969
|
/**
|
|
3091
3970
|
* 会话文件 → `parentSession → [子会话]` 邻接表(外加 `duplicates` 计数,只用来打日志)。
|
|
3092
3971
|
*
|
|
@@ -3099,8 +3978,20 @@ async function subagentIndexSnapshot(files) {
|
|
|
3099
3978
|
for (const file of Array.from(subagentHeaders.keys())) {
|
|
3100
3979
|
if (live.has(file) !== true) subagentHeaders.delete(file)
|
|
3101
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
|
|
3102
3988
|
for (let i = 0; i < files.length; i += 1) {
|
|
3103
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
|
|
3104
3995
|
let stat = null
|
|
3105
3996
|
try {
|
|
3106
3997
|
stat = statSync(file)
|
|
@@ -3112,7 +4003,6 @@ async function subagentIndexSnapshot(files) {
|
|
|
3112
4003
|
subagentHeaders.delete(file)
|
|
3113
4004
|
continue
|
|
3114
4005
|
}
|
|
3115
|
-
const cached = subagentHeaders.get(file)
|
|
3116
4006
|
if (cached !== undefined && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) continue
|
|
3117
4007
|
/* 读失败(含"没有头部")也记下来:同一个 mtime/size 的下一问直接跳过,不再重读 */
|
|
3118
4008
|
const header = sessionHeaderOfFile(file)
|
|
@@ -3124,7 +4014,8 @@ async function subagentIndexSnapshot(files) {
|
|
|
3124
4014
|
subagentHeaders.delete(oldest.value)
|
|
3125
4015
|
}
|
|
3126
4016
|
/* 首次请求要把所有会话都读一遍头部:每 8 个让出一次事件循环,别把 host 卡住 */
|
|
3127
|
-
|
|
4017
|
+
processed += 1
|
|
4018
|
+
if (processed % 8 === 7) await new Promise((resolve) => setImmediate(resolve))
|
|
3128
4019
|
}
|
|
3129
4020
|
/* 一个会话 id 可能出现在两个文件里:① 日志格式升级时同目录留下旧版本文件;
|
|
3130
4021
|
② 手工复制会话目录;③ 异常产生的重复目录。只认**最新的那一份**参与聚合
|
|
@@ -3155,13 +4046,21 @@ async function subagentIndexSnapshot(files) {
|
|
|
3155
4046
|
}
|
|
3156
4047
|
|
|
3157
4048
|
/**
|
|
3158
|
-
*
|
|
4049
|
+
* 一段父会话日志的**全部本轮事实**,一次 split + 一次逐行扫描折出来:
|
|
4050
|
+
* · `since`:本轮起点(规则见下)
|
|
4051
|
+
* · `lastUsageAt`:最后一条非空 usage 事件的时间(判断"起点之后父会话自己产出过没有")
|
|
4052
|
+
*
|
|
4053
|
+
* 为什么合并成一次扫描:父会话日志是整棵树里最大的一份;旧实现缓存失效时要在同一份
|
|
4054
|
+
* 文本上跑两趟 split + 逐行 JSON.parse(lastTurnStartOfText / lastUsageEventTimeOfText),
|
|
4055
|
+
* 两倍 CPU 与两倍临时对象。合并后每条相关行只解析一次。
|
|
4056
|
+
*
|
|
4057
|
+
* `since` 的三条时间取 max:
|
|
3159
4058
|
* ① 最后一条 `turn/start`;
|
|
3160
4059
|
* ② 最后一条**真实用户输入**的 `user/message` —— 但**只有**它落在
|
|
3161
4060
|
* 「最后一条 `turn/end` 之后、且最后一条 `turn/end` 晚于最后一条 `turn/start`」
|
|
3162
4061
|
* 这一段里,才算"新一轮已经开始、而它的 `turn/start` 还没落盘"的候选;
|
|
3163
4062
|
* ③ 日志里完全没有 `turn/start` 时,退回用最后一条真实用户消息(老兜底)。
|
|
3164
|
-
*
|
|
4063
|
+
* 都找不到就是 null(调用方据此判 sinceSource='none')。
|
|
3165
4064
|
*
|
|
3166
4065
|
* **为什么只认 `source.kind === 'user'` 的 `user/message`**(2026-10-17 修复):
|
|
3167
4066
|
* 同一轮里 DSH 会往父会话日志注入很多**不是用户输入**的 `user/message` ——
|
|
@@ -3184,26 +4083,30 @@ async function subagentIndexSnapshot(files) {
|
|
|
3184
4083
|
* 还没落盘);turn 还开着就只认 `turn/start`。
|
|
3185
4084
|
*
|
|
3186
4085
|
* 取**最大值**而不是"文件里最后一行":正常日志是追加写的,两者一致;万一有乱序行,
|
|
3187
|
-
*
|
|
4086
|
+
* 取最大值更稳。只解析可能相关的行(turn / user / usage):日志可能几 MB,
|
|
4087
|
+
* 逐行 JSON.parse 太贵。坏行跳过,绝不抛。
|
|
3188
4088
|
*/
|
|
3189
|
-
function
|
|
3190
|
-
|
|
4089
|
+
function parentLogFactsOfText(text) {
|
|
4090
|
+
const facts = { since: null, lastUsageAt: null }
|
|
4091
|
+
if (typeof text !== 'string' || text.length === 0) return facts
|
|
3191
4092
|
let lastTurnStart = null
|
|
3192
4093
|
let lastTurnEnd = null
|
|
3193
4094
|
let lastUser = null
|
|
4095
|
+
let lastUsageAt = null
|
|
3194
4096
|
const lines = text.split('\n')
|
|
3195
4097
|
for (let i = 0; i < lines.length; i += 1) {
|
|
3196
4098
|
const line = lines[i]
|
|
3197
|
-
/*
|
|
4099
|
+
/* 便宜的预筛:只解析可能相关的事件(usage 只认 assistant/message、compaction/summary) */
|
|
3198
4100
|
if (line.indexOf('"turn/start"') < 0 && line.indexOf('"turn/end"') < 0
|
|
3199
|
-
&& line.indexOf('"user/message"') < 0) continue
|
|
4101
|
+
&& line.indexOf('"user/message"') < 0 && line.indexOf('"usage"') < 0) continue
|
|
3200
4102
|
let event
|
|
3201
4103
|
try {
|
|
3202
4104
|
event = JSON.parse(line)
|
|
3203
4105
|
} catch (error) {
|
|
3204
4106
|
continue
|
|
3205
4107
|
}
|
|
3206
|
-
if (event === null || typeof event !== 'object'
|
|
4108
|
+
if (event === null || typeof event !== 'object') continue
|
|
4109
|
+
if (typeof event.time !== 'number') continue
|
|
3207
4110
|
if (event.type === 'turn/start') {
|
|
3208
4111
|
if (lastTurnStart === null || event.time > lastTurnStart) lastTurnStart = event.time
|
|
3209
4112
|
continue
|
|
@@ -3212,92 +4115,89 @@ function lastTurnStartOfText(text) {
|
|
|
3212
4115
|
if (lastTurnEnd === null || event.time > lastTurnEnd) lastTurnEnd = event.time
|
|
3213
4116
|
continue
|
|
3214
4117
|
}
|
|
3215
|
-
if (event.type
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
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
|
+
}
|
|
3222
4133
|
}
|
|
4134
|
+
facts.lastUsageAt = lastUsageAt
|
|
3223
4135
|
/* 完全没有 turn/start:老日志/异常日志的兜底 —— 用最后一条真实用户消息(原来就是这样) */
|
|
3224
|
-
if (lastTurnStart === null)
|
|
4136
|
+
if (lastTurnStart === null) {
|
|
4137
|
+
facts.since = lastUser
|
|
4138
|
+
return facts
|
|
4139
|
+
}
|
|
3225
4140
|
/* 用户消息只有在"上一轮已结束(turn/end 晚于 turn/start)、且消息晚于那个 turn/end"
|
|
3226
4141
|
时才是"新轮已开始、turn/start 还没落盘"的证据;turn 还开着就只是本轮插话,不算 */
|
|
3227
4142
|
const turnClosed = lastTurnEnd !== null && lastTurnEnd > lastTurnStart
|
|
3228
4143
|
const userStartedNewTurn = turnClosed === true && lastUser !== null && lastUser > lastTurnEnd
|
|
3229
|
-
|
|
4144
|
+
facts.since = userStartedNewTurn === true && lastUser > lastTurnStart ? lastUser : lastTurnStart
|
|
4145
|
+
return facts
|
|
3230
4146
|
}
|
|
3231
4147
|
|
|
3232
|
-
/**
|
|
3233
|
-
* 一段父会话日志里**最后一条用量事件**的时间(`assistant/message` 或 `compaction/summary`
|
|
3234
|
-
* 且带非空 usage)。只服务于一个问题:"这个窗口起点之后,父会话自己到底产出过没有?"
|
|
3235
|
-
*
|
|
3236
|
-
* 只留**最大值**(一个数字)而不是把整串事件时间攒下来:要回答的是存在性
|
|
3237
|
-
* ("有没有 time >= fromMs 的用量事件" ⟺ "最大用量时间 >= fromMs"),
|
|
3238
|
-
* 而父会话日志是整棵树里最大的那一份,不该为一道布尔判断在内存里留一串时间戳。
|
|
3239
|
-
* 全 0 的 usage(被中断的尝试)不算产出 —— 与 pickUsageEvents 的口径一致。
|
|
3240
|
-
*/
|
|
3241
|
-
function lastUsageEventTimeOfText(text) {
|
|
3242
|
-
if (typeof text !== 'string' || text.length === 0) return null
|
|
3243
|
-
let at = null
|
|
3244
|
-
const lines = text.split('\n')
|
|
3245
|
-
for (let i = 0; i < lines.length; i += 1) {
|
|
3246
|
-
const line = lines[i]
|
|
3247
|
-
/* 两道便宜的字符串筛(与 pickUsageEvents / foldSessionTiming 同一套省法):
|
|
3248
|
-
绝大多数行既没有 usage 也不是这两类事件,逐行 JSON.parse 太贵 */
|
|
3249
|
-
if (line.indexOf('"usage"') < 0) continue
|
|
3250
|
-
if (line.indexOf('"assistant/message"') < 0 && line.indexOf('"compaction/summary"') < 0) continue
|
|
3251
|
-
let event
|
|
3252
|
-
try {
|
|
3253
|
-
event = JSON.parse(line)
|
|
3254
|
-
} catch (error) {
|
|
3255
|
-
continue
|
|
3256
|
-
}
|
|
3257
|
-
if (event === null || typeof event !== 'object' || typeof event.time !== 'number') continue
|
|
3258
|
-
if (event.type !== 'assistant/message' && event.type !== 'compaction/summary') continue
|
|
3259
|
-
const usage = usageOfEvent(event)
|
|
3260
|
-
if (usage === null) continue
|
|
3261
|
-
const parts = usageParts(usage)
|
|
3262
|
-
if (parts.input === 0 && parts.cacheRead === 0 && parts.cacheWrite === 0 && parts.output === 0) continue
|
|
3263
|
-
if (at === null || event.time > at) at = event.time
|
|
3264
|
-
}
|
|
3265
|
-
return at
|
|
3266
|
-
}
|
|
3267
4148
|
|
|
3268
4149
|
/* 父会话日志 → 它自己的"本轮事实":①本轮起点 ②窗口内有没有它自己的用量事件。
|
|
3269
4150
|
这个文件每次对话都在写,但只是解压一份日志、折两个标量,代价很低;照样按
|
|
3270
|
-
`文件 + mtime + size` 记忆化(内容一变就重折)——
|
|
3271
|
-
|
|
3272
|
-
|
|
4151
|
+
`文件 + mtime + size` 记忆化(内容一变就重折)—— 两件事**共用同一次解压 + 同一次
|
|
4152
|
+
逐行扫描**(parentLogFactsOfText),免得多付两趟全文 split/parse。
|
|
4153
|
+
缓存按**父文件路径**存快照:文件更新时替换旧版本,不按 mtime 累积一堆历史版本;
|
|
4154
|
+
同时限制条目数与估算总字节,防畸形超长日志把内存撑爆。 */
|
|
3273
4155
|
const SUBAGENT_SINCE_CACHE_MAX = 32
|
|
4156
|
+
const SUBAGENT_SINCE_CACHE_BYTES_MAX = 8 * 1024 * 1024
|
|
4157
|
+
let subagentSinceCacheBytes = 0
|
|
3274
4158
|
const subagentSinceCache = new Map()
|
|
3275
4159
|
|
|
3276
|
-
|
|
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) {
|
|
3277
4176
|
const key = one.file + '|' + String(one.mtimeMs) + '|' + String(one.size)
|
|
3278
|
-
const hit = subagentSinceCache.get(
|
|
3279
|
-
if (hit !== undefined) return hit
|
|
4177
|
+
const hit = subagentSinceCache.get(one.file)
|
|
4178
|
+
if (hit !== undefined && hit.key === key) return hit.value
|
|
3280
4179
|
let text = null
|
|
3281
4180
|
try {
|
|
3282
|
-
text =
|
|
4181
|
+
text = await zstdTextAsync(await fsPromises.readFile(one.file))
|
|
3283
4182
|
} catch (error) {
|
|
3284
4183
|
text = null
|
|
3285
4184
|
}
|
|
3286
|
-
const value = text === null
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
while (subagentSinceCache.size > SUBAGENT_SINCE_CACHE_MAX) {
|
|
3291
|
-
const oldest = subagentSinceCache.keys().next()
|
|
3292
|
-
if (oldest.done === true) break
|
|
3293
|
-
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
|
|
3294
4189
|
}
|
|
4190
|
+
const bytes = parentLogFactsBytes(value)
|
|
4191
|
+
subagentSinceCache.set(one.file, { key: key, value: value, bytes: bytes })
|
|
4192
|
+
subagentSinceCacheBytes += bytes
|
|
4193
|
+
trimSubagentSinceCache()
|
|
3295
4194
|
return value
|
|
3296
4195
|
}
|
|
3297
4196
|
|
|
3298
4197
|
/** 父会话日志 → 它自己的"本轮起点"(推不出来给 null)。薄壳,只为既有调用点读起来更直白。 */
|
|
3299
|
-
function parentTurnStartOf(one) {
|
|
3300
|
-
|
|
4198
|
+
async function parentTurnStartOf(one) {
|
|
4199
|
+
const facts = await parentLogFactsOf(one)
|
|
4200
|
+
return facts.since
|
|
3301
4201
|
}
|
|
3302
4202
|
|
|
3303
4203
|
/* 每个父会话一份结果:`sessionId → { key, value }`,key 见 collectSubagentUsage。
|
|
@@ -3305,6 +4205,8 @@ function parentTurnStartOf(one) {
|
|
|
3305
4205
|
最多留 8 份,超出丢最久没用的(Map 的插入顺序)。 */
|
|
3306
4206
|
const SUBAGENT_CACHE_MAX = 8
|
|
3307
4207
|
const subagentUsageCache = new Map()
|
|
4208
|
+
/* 同一会话+同一窗口的在飞请求:共享同一个 Promise,避免重复排队/重复解压。 */
|
|
4209
|
+
const subagentUsageInflight = new Map()
|
|
3308
4210
|
|
|
3309
4211
|
/** 会话日志里的一笔用量折成钱(6 位小数,与台账的金额口径一致)。 */
|
|
3310
4212
|
function roundCost(value) {
|
|
@@ -3413,6 +4315,39 @@ function foldSessionTiming(text) {
|
|
|
3413
4315
|
收益接近零;而 1024 < 4000 会让正常场景就开始误删仍有用的键。 */
|
|
3414
4316
|
const SUBAGENT_FILE_CACHE_MAX = 4096
|
|
3415
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
|
+
}
|
|
3416
4351
|
|
|
3417
4352
|
/* `file|mtime|size` → 该日志**最后一条事件的类型**(`turn/end` = 这一轮已收尾)。
|
|
3418
4353
|
与 subagentHeaders 同一套失效口径(文件一变就换键),但**只对当前会话的后代**按需读:
|
|
@@ -3615,7 +4550,18 @@ function isRunningEntry(one, now) {
|
|
|
3615
4550
|
**没法用真实夹构造**(header 与首个 turn/start 压在同一 zstd 帧里,
|
|
3616
4551
|
header 可读就必然能读到 turn/start)。传一个不存在的 file 路径就能精确命中它。
|
|
3617
4552
|
宿主只消费 `apply`,多导出一个纯函数不影响加载。 */
|
|
3618
|
-
|
|
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
|
+
}
|
|
3619
4565
|
|
|
3620
4566
|
/* 「上下文占用百分比」的缓存(键 = 子会话文件 + mtime + size)。
|
|
3621
4567
|
为什么要它:算这个数要拿到**最后一条** usage 与 **最后一条** request/context,
|
|
@@ -3865,16 +4811,11 @@ async function subagentFileUsageAsync(one, fromMs, fingerprint) {
|
|
|
3865
4811
|
/* 传 0 = 不做窗口筛选,把整份日志的 usage 事件都收下来 */
|
|
3866
4812
|
const picked = await pickUsageEventsAsync(text, 0)
|
|
3867
4813
|
picked.forEach((event) => {
|
|
3868
|
-
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 })
|
|
3869
4815
|
})
|
|
3870
4816
|
entry.stats = foldSessionTiming(text)
|
|
3871
4817
|
}
|
|
3872
|
-
|
|
3873
|
-
while (subagentFileCache.size > SUBAGENT_FILE_CACHE_MAX) {
|
|
3874
|
-
const oldest = subagentFileCache.keys().next()
|
|
3875
|
-
if (oldest.done === true) break
|
|
3876
|
-
subagentFileCache.delete(oldest.value)
|
|
3877
|
-
}
|
|
4818
|
+
putSubagentFileCacheEntry(aggKey, entry)
|
|
3878
4819
|
return usageAggOfEntry(entry, fromMs)
|
|
3879
4820
|
}
|
|
3880
4821
|
|
|
@@ -3890,7 +4831,8 @@ function usageAggOfEntry(entry, fromMs) {
|
|
|
3890
4831
|
agg.tokens.output += parts.output
|
|
3891
4832
|
/* 一次 usage 事件 = 一次调用(pickUsageEvents 已按 turn/step 去过重、全 0 的不算) */
|
|
3892
4833
|
agg.calls += 1
|
|
3893
|
-
const
|
|
4834
|
+
const multiplier = relayFeeMultiplierForProvider(event.provider)
|
|
4835
|
+
const amount = tokenCost(event.model, event.time, parts, event.provider, multiplier)
|
|
3894
4836
|
agg.cost += amount
|
|
3895
4837
|
/* 同一笔同时按"模型条目的币种"分桶:客户端混币时要折成一个数字(见 tokenCostCurrency) */
|
|
3896
4838
|
const code = tokenCostCurrency(event.model)
|
|
@@ -3899,6 +4841,24 @@ function usageAggOfEntry(entry, fromMs) {
|
|
|
3899
4841
|
return agg
|
|
3900
4842
|
}
|
|
3901
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
|
+
|
|
3902
4862
|
/**
|
|
3903
4863
|
* 从 `sessionId` 出发,把它**全部后代**(多层:队友再开队友)的用量汇总起来。
|
|
3904
4864
|
*
|
|
@@ -3914,7 +4874,7 @@ function usageAggOfEntry(entry, fromMs) {
|
|
|
3914
4874
|
* · `host`:没传 → host 读**父会话自己**的日志推一个起点(最后一条 `turn/start`,
|
|
3915
4875
|
* 但和最后一条**真实用户输入**的 `user/message` 取较新的那个 —— 后者更新说明新一轮
|
|
3916
4876
|
* 已开始、其 `turn/start` 还没落盘,沿用旧起点会把上一轮算进来;同轮注入的
|
|
3917
|
-
* subagent-settled / team-message / tool-jobs 等通知不算,见
|
|
4877
|
+
* subagent-settled / team-message / tool-jobs 等通知不算,见 parentLogFactsOfText 的 since 规则);
|
|
3918
4878
|
* 而且**推出来的起点之后必须真的有用量事件**,否则说明起点无从验证,同样当
|
|
3919
4879
|
* `none`(宁少不多);
|
|
3920
4880
|
* · `none`:父会话日志缺失/读不出,或推出来的起点事后没有事件 → 本轮**什么都不并**
|
|
@@ -3928,13 +4888,23 @@ function usageAggOfEntry(entry, fromMs) {
|
|
|
3928
4888
|
* 前一个刚写好的缓存,同一批日志不会被重复冷解压。
|
|
3929
4889
|
*/
|
|
3930
4890
|
function collectSubagentUsage(sessionId, sinceMs) {
|
|
3931
|
-
|
|
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
|
|
3932
4902
|
}
|
|
3933
4903
|
|
|
3934
4904
|
async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
3935
4905
|
/* 价格指纹:并进两个缓存键。改价后必须按新价重算 —— 否则队友那段会一直挂着旧价,
|
|
3936
4906
|
同一个「总计」里本会话用新价、队友用旧价(实测缺陷)。 */
|
|
3937
|
-
const fingerprint = priceFingerprint()
|
|
4907
|
+
const fingerprint = priceFingerprint() + '|relay:' + relayFeeFingerprint()
|
|
3938
4908
|
const clientSince = typeof sinceMs === 'number' && Number.isFinite(sinceMs) && sinceMs >= 0 ? sinceMs : null
|
|
3939
4909
|
const files = sessionFilesCached()
|
|
3940
4910
|
const index = await subagentIndexSnapshot(files)
|
|
@@ -3963,11 +4933,11 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
3963
4933
|
|
|
3964
4934
|
/* 窗口起点从哪来:① 客户端给了(它精确知道自己那一轮)→ `client`;
|
|
3965
4935
|
② 没给就问 host 自己 —— 读**父会话自己**的日志取最后一条 turn/start(或更新的
|
|
3966
|
-
真实用户 user/message,见
|
|
4936
|
+
真实用户 user/message,见 parentLogFactsOfText;同轮注入的通知不算)→ `host`;
|
|
3967
4937
|
③ 两者都没有(父会话文件缺失/读不出)→ `none`:**本轮什么都不并**
|
|
3968
4938
|
(用户规则:本轮只能小不能大,绝不能拿整会话的量顶上)。
|
|
3969
4939
|
另外 host 推的起点还要过一道"事后有事件"的验证(见下面聚合之后的那段)。 */
|
|
3970
|
-
const parentEntry = index.byId.get(sessionId)
|
|
4940
|
+
const parentEntry = refreshSubagentEntryStat(index.byId.get(sessionId))
|
|
3971
4941
|
let sinceSource = 'none'
|
|
3972
4942
|
let fromMs = null
|
|
3973
4943
|
let clamped = false
|
|
@@ -3981,14 +4951,14 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
3981
4951
|
兜一道:**只在收紧方向**生效(取较新的那个),绝不把窗口放大。
|
|
3982
4952
|
`since=0` 是客户端显式要的整会话(「总计」那一问),不参与收敛。 */
|
|
3983
4953
|
if (clientSince > 0 && parentEntry !== undefined) {
|
|
3984
|
-
const hostSince = parentTurnStartOf(parentEntry)
|
|
4954
|
+
const hostSince = await parentTurnStartOf(parentEntry)
|
|
3985
4955
|
if (hostSince !== null && hostSince > fromMs) {
|
|
3986
4956
|
fromMs = hostSince
|
|
3987
4957
|
clamped = true
|
|
3988
4958
|
}
|
|
3989
4959
|
}
|
|
3990
4960
|
} else if (parentEntry !== undefined) {
|
|
3991
|
-
const hostSince = parentTurnStartOf(parentEntry)
|
|
4961
|
+
const hostSince = await parentTurnStartOf(parentEntry)
|
|
3992
4962
|
if (hostSince !== null) {
|
|
3993
4963
|
sinceSource = 'host'
|
|
3994
4964
|
fromMs = hostSince
|
|
@@ -4003,14 +4973,16 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
4003
4973
|
const parts = []
|
|
4004
4974
|
const reading = []
|
|
4005
4975
|
for (let i = 0; i < found.length; i += 1) {
|
|
4006
|
-
/*
|
|
4976
|
+
/* 只对“当前会话真正相关”的条目重新 stat:索引里的 mtime/size 可能停在上次读头时。
|
|
4977
|
+
`parentSession` 一并带上:分层计数要区分「直接后代(团队成员 / 团队外子智能体)」
|
|
4007
4978
|
与「更深一层(成员下派的孙会话)」,判据就是 parentSession 是不是当前会话。
|
|
4008
4979
|
注意 `found` 是**全部后代**(BFS,含孙辈及以上),所以这里不需要再单独查子表。 */
|
|
4980
|
+
const fresh = refreshSubagentEntryStat(found[i])
|
|
4009
4981
|
reading.push({
|
|
4010
|
-
id:
|
|
4011
|
-
parentSession:
|
|
4982
|
+
id: fresh.id, file: fresh.file, mtimeMs: fresh.mtimeMs, size: fresh.size,
|
|
4983
|
+
parentSession: fresh.parentSession,
|
|
4012
4984
|
})
|
|
4013
|
-
parts.push(
|
|
4985
|
+
parts.push(fresh.id + ':' + String(fresh.mtimeMs) + ':' + String(fresh.size))
|
|
4014
4986
|
}
|
|
4015
4987
|
/* 这几个字段**不受窗口影响**,所以在缓存检查之前就算好,命中缓存时也能带上:
|
|
4016
4988
|
· running / teamRunning / deepRunning / 两个 ContextPercent:谁在跑、以及那一级的
|
|
@@ -4021,7 +4993,7 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
4021
4993
|
必须给 null,见下面的 turnStartFor。 */
|
|
4022
4994
|
const runInfo = runningBreakdownOf(sessionId, reading, parentEntry, index)
|
|
4023
4995
|
const running = runInfo.running
|
|
4024
|
-
const hostTurnStart = parentEntry === undefined ? null : parentTurnStartOf(parentEntry)
|
|
4996
|
+
const hostTurnStart = parentEntry === undefined ? null : await parentTurnStartOf(parentEntry)
|
|
4025
4997
|
/* 语义与 sinceSource 对齐:none(推不出 / 推出来事后没证据)时给 null。 */
|
|
4026
4998
|
const turnStartFor = (source) => (source === 'none' ? null : hostTurnStart)
|
|
4027
4999
|
/* 新出现的子会话会改变文件集合(索引重建后出现在 found 里),键自然就变了;
|
|
@@ -4099,7 +5071,7 @@ async function collectSubagentUsageNow(sessionId, sinceMs) {
|
|
|
4099
5071
|
两条都不成立时才按用户的"宁少不多"当没有窗口 —— 本轮不含队友。
|
|
4100
5072
|
判断只用已经折好的标量(父会话日志的最大用量时间、同一个窗口的聚合结果),
|
|
4101
5073
|
没有再解压一遍。 */
|
|
4102
|
-
const parentFacts = sinceSource === 'host' && parentEntry !== undefined ? parentLogFactsOf(parentEntry) : null
|
|
5074
|
+
const parentFacts = sinceSource === 'host' && parentEntry !== undefined ? await parentLogFactsOf(parentEntry) : null
|
|
4103
5075
|
const parentProduced = parentFacts !== null && parentFacts.lastUsageAt !== null
|
|
4104
5076
|
&& fromMs !== null && parentFacts.lastUsageAt >= fromMs
|
|
4105
5077
|
if (sinceSource === 'host' && parentProduced !== true && total.calls === 0) {
|
|
@@ -4207,6 +5179,10 @@ function ledgerPath() {
|
|
|
4207
5179
|
* 'done' = 已经重算完,恢复"只增量、不重算"的原有语义
|
|
4208
5180
|
*/
|
|
4209
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
|
|
4210
5186
|
|
|
4211
5187
|
function emptyLedger() {
|
|
4212
5188
|
return {
|
|
@@ -4215,6 +5191,7 @@ function emptyLedger() {
|
|
|
4215
5191
|
priceFingerprint: '',
|
|
4216
5192
|
unpricedBackfill: '',
|
|
4217
5193
|
costByCurrencyBackfill: 'done',
|
|
5194
|
+
providerPricingAuditVersion: '',
|
|
4218
5195
|
days: {},
|
|
4219
5196
|
seen: {},
|
|
4220
5197
|
sessions: {},
|
|
@@ -4259,6 +5236,7 @@ function migrateLedger(parsed) {
|
|
|
4259
5236
|
priceFingerprint: typeof parsed.priceFingerprint === 'string' ? parsed.priceFingerprint : '',
|
|
4260
5237
|
unpricedBackfill: typeof parsed.unpricedBackfill === 'string' ? parsed.unpricedBackfill : '',
|
|
4261
5238
|
costByCurrencyBackfill: typeof parsed.costByCurrencyBackfill === 'string' ? parsed.costByCurrencyBackfill : 'done',
|
|
5239
|
+
providerPricingAuditVersion: typeof parsed.providerPricingAuditVersion === 'number' ? parsed.providerPricingAuditVersion : '',
|
|
4262
5240
|
days: pick(parsed.days),
|
|
4263
5241
|
seen: pick(parsed.seen),
|
|
4264
5242
|
sessions: pick(parsed.sessions),
|
|
@@ -4356,7 +5334,13 @@ function writeLedger(ledger) {
|
|
|
4356
5334
|
}
|
|
4357
5335
|
}
|
|
4358
5336
|
} catch (error) {
|
|
4359
|
-
/*
|
|
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)
|
|
4360
5344
|
}
|
|
4361
5345
|
}
|
|
4362
5346
|
|
|
@@ -4411,6 +5395,32 @@ function addUnpriced(day, model, parts, peakTime) {
|
|
|
4411
5395
|
day.unpriced = bucket
|
|
4412
5396
|
}
|
|
4413
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
|
+
|
|
4414
5424
|
/** 一档用量按一档单价折成人民币(用量或单价缺失按 0 算)。 */
|
|
4415
5425
|
function costOfTier(parts, price) {
|
|
4416
5426
|
if (parts === null || parts === undefined) return 0
|
|
@@ -4434,34 +5444,180 @@ function settleUnpriced(ledger) {
|
|
|
4434
5444
|
const day = ledger.days[dates[i]]
|
|
4435
5445
|
if (day === null || day === undefined || typeof day !== 'object') continue
|
|
4436
5446
|
const bucket = day.unpriced
|
|
4437
|
-
if (bucket
|
|
4438
|
-
|
|
4439
|
-
|
|
4440
|
-
|
|
4441
|
-
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
4446
|
-
|
|
4447
|
-
|
|
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
|
+
}
|
|
4448
5485
|
const peakPrice = entry.peak !== null && entry.peak !== undefined ? entry.peak : entry.offPeak
|
|
4449
5486
|
const offPeakPrice = entry.tiered === false
|
|
4450
5487
|
? peakPrice
|
|
4451
5488
|
: (entry.offPeak !== null && entry.offPeak !== undefined ? entry.offPeak : entry.peak)
|
|
4452
|
-
const
|
|
4453
|
-
|
|
4454
|
-
|
|
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)
|
|
4455
5497
|
amount += cost
|
|
4456
5498
|
entries += 1
|
|
4457
|
-
delete bucket[names[k]]
|
|
4458
5499
|
}
|
|
4459
|
-
if (
|
|
4460
|
-
else day.
|
|
5500
|
+
if (remaining.length === 0) delete day.unpricedByProvider
|
|
5501
|
+
else day.unpricedByProvider = remaining
|
|
4461
5502
|
}
|
|
4462
5503
|
return { entries, amount: Math.round(amount * 1e6) / 1e6 }
|
|
4463
5504
|
}
|
|
4464
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
|
+
|
|
4465
5621
|
/**
|
|
4466
5622
|
* 一次性回扫(升级后只做一次):v1/v2 台账没记过"哪些 token 当时没有单价",
|
|
4467
5623
|
* 只有会话日志里找得到。回扫只补这一件事:
|
|
@@ -4550,6 +5706,19 @@ function addDayCost(day, model, amount) {
|
|
|
4550
5706
|
/* 只按自有属性累加:模型名不会当币种键,但保持与 addUnpriced 同一套防御习惯 */
|
|
4551
5707
|
const hasOwn = Object.prototype.hasOwnProperty.call(book, code)
|
|
4552
5708
|
book[code] = (hasOwn === true ? book[code] : 0) + amount
|
|
5709
|
+
/* 顺手记下"这一天的钱是按什么汇率折的"(只记非 CNY 币种:CNY 折 CNY 恒为 1)。
|
|
5710
|
+
为什么要有它:底栏「本轮 / 总计」是一个**合并数字**,得把美元折成人民币。
|
|
5711
|
+
以前那个汇率是写死的常量,于是历史金额会随常量改动而整体漂移。
|
|
5712
|
+
记下来之后,每天用自己的汇率折算,历史数字就固定了。
|
|
5713
|
+
**不覆盖已有的**:同一天可能有多次写入,保留当天第一次记下的那个汇率。 */
|
|
5714
|
+
if (code !== 'CNY') {
|
|
5715
|
+
const current = currentExchangeRate()
|
|
5716
|
+
if (current !== null) {
|
|
5717
|
+
if (day.rateAt === undefined || day.rateAt === null || typeof day.rateAt !== 'object') day.rateAt = {}
|
|
5718
|
+
const seen = Object.prototype.hasOwnProperty.call(day.rateAt, code)
|
|
5719
|
+
if (seen !== true) day.rateAt[code] = current
|
|
5720
|
+
}
|
|
5721
|
+
}
|
|
4553
5722
|
}
|
|
4554
5723
|
|
|
4555
5724
|
/**
|
|
@@ -4613,7 +5782,9 @@ async function accumulateRebuildInto(out, text, fromMs) {
|
|
|
4613
5782
|
if (priceEntryFor(one.model) === null) continue
|
|
4614
5783
|
const key = localDateKey(one.time)
|
|
4615
5784
|
const slot = rebuildCostBucket(out, key)
|
|
4616
|
-
|
|
5785
|
+
/* v4 重建按「官方参考价」算基线,provider 归属修正由 auditProviderPricingHistory 负责。
|
|
5786
|
+
这里必须用 officialTokenCost:模型前缀判 relay 后,tokenCost(provider='') 会算成 0。 */
|
|
5787
|
+
const amount = officialTokenCost(one.model, one.time, one.parts)
|
|
4617
5788
|
slot.cost += amount
|
|
4618
5789
|
const code = tokenCostCurrency(one.model)
|
|
4619
5790
|
slot.byCurrency[code] = (Object.prototype.hasOwnProperty.call(slot.byCurrency, code) ? slot.byCurrency[code] : 0) + amount
|
|
@@ -4776,8 +5947,14 @@ async function collectFileIntoLedger(ledger, file, text, fromMs, rebuilding) {
|
|
|
4776
5947
|
与 costByCurrency(正确的那份);**还没有单价的用量单独记成"欠账"**,
|
|
4777
5948
|
等用户在设置页把价补上再结算(补价只结算欠账,不动已经算好的费用)。
|
|
4778
5949
|
v4 重算那一轮的钱由重建通道独立算出并在末尾覆盖,这里不吃双份。 */
|
|
4779
|
-
|
|
4780
|
-
|
|
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))
|
|
4781
5958
|
ledger.days[key] = day
|
|
4782
5959
|
added += 1
|
|
4783
5960
|
}
|
|
@@ -4789,6 +5966,7 @@ async function collectFileIntoLedger(ledger, file, text, fromMs, rebuilding) {
|
|
|
4789
5966
|
/** 丢掉太久以前的日桶与去重记录。保留期是滚动的「今天往前 400 天」,与统计窗口无关。 */
|
|
4790
5967
|
function pruneLedger(ledger) {
|
|
4791
5968
|
const keepFrom = localDateKey(Date.now() - 400 * 24 * 3600 * 1000)
|
|
5969
|
+
const keepFromMs = Date.now() - 400 * 24 * 3600 * 1000
|
|
4792
5970
|
for (const key of Object.keys(ledger.days)) {
|
|
4793
5971
|
if (key < keepFrom) delete ledger.days[key]
|
|
4794
5972
|
}
|
|
@@ -4799,6 +5977,26 @@ function pruneLedger(ledger) {
|
|
|
4799
5977
|
delete ledger.seen[sessionId]
|
|
4800
5978
|
}
|
|
4801
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
|
+
}
|
|
4802
6000
|
}
|
|
4803
6001
|
|
|
4804
6002
|
/** 把一份 `{ CNY: n, USD: n }` 的书洗成干净对象:只留有限正数,其余丢弃。
|
|
@@ -4942,14 +6140,19 @@ function monthUsagePayload(ledger, monthStart) {
|
|
|
4942
6140
|
const key = localDateKey(at)
|
|
4943
6141
|
const inMonth = at >= monthStart && at <= monthEnd
|
|
4944
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
|
|
4945
6148
|
/* 三段明细一并带上:客户端悬停每天的方块时要显示命中 / 未命中 / 输出 */
|
|
4946
|
-
const input =
|
|
4947
|
-
const cacheRead =
|
|
4948
|
-
const cacheWrite =
|
|
4949
|
-
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
|
|
4950
6153
|
const total = input + cacheRead + cacheWrite + output
|
|
4951
|
-
const calls =
|
|
4952
|
-
const rawCost =
|
|
6154
|
+
const calls = hasBucket ? bucket.calls || 0 : 0
|
|
6155
|
+
const rawCost = hasBucket ? bucket.cost : 0
|
|
4953
6156
|
const cost = typeof rawCost === 'number' && Number.isFinite(rawCost) ? rawCost : 0
|
|
4954
6157
|
days.push({
|
|
4955
6158
|
date: key,
|
|
@@ -4958,7 +6161,7 @@ function monthUsagePayload(ledger, monthStart) {
|
|
|
4958
6161
|
calls,
|
|
4959
6162
|
cost: Math.round(cost * 10000) / 10000,
|
|
4960
6163
|
/* 分币种金额(task-52);老台账没有这个字段 ⇒ 空对象 */
|
|
4961
|
-
costByCurrency: dayCurrencyBook(bucket),
|
|
6164
|
+
costByCurrency: dayCurrencyBook(hasBucket ? bucket : null),
|
|
4962
6165
|
input,
|
|
4963
6166
|
cacheRead,
|
|
4964
6167
|
cacheWrite,
|
|
@@ -4994,7 +6197,9 @@ function yearUsagePayload(ledger, now) {
|
|
|
4994
6197
|
const byCurrency = {}
|
|
4995
6198
|
for (let d = 1; d <= daysInMonth; d += 1) {
|
|
4996
6199
|
const bucket = ledger.days[localDateKey(new Date(year, m - 1, d).getTime())]
|
|
4997
|
-
|
|
6200
|
+
/* 非对象(null / 字符串 / 数字 / 数组)一律当"这一天没有数据",与 weekUsagePayload 同口径。 */
|
|
6201
|
+
if (bucket === null || bucket === undefined
|
|
6202
|
+
|| typeof bucket !== 'object' || Array.isArray(bucket) === true) continue
|
|
4998
6203
|
input += bucket.input || 0
|
|
4999
6204
|
cacheRead += bucket.cacheRead || 0
|
|
5000
6205
|
cacheWrite += bucket.cacheWrite || 0
|
|
@@ -5062,6 +6267,165 @@ function appendTipDiag(body) {
|
|
|
5062
6267
|
}
|
|
5063
6268
|
}
|
|
5064
6269
|
|
|
6270
|
+
/**
|
|
6271
|
+
* 从 pnpm 的原始输出里挑出「有意义的错误行」。
|
|
6272
|
+
*
|
|
6273
|
+
* 为什么不整段贴:pnpm 的 append-only 输出里绝大多数是进度行(`Progress: resolved 12,
|
|
6274
|
+
* reused 0, downloaded 0`)和 `Packages: +3` 这类统计,真正的错误通常只有一两行,
|
|
6275
|
+
* 混在一大段里反而看不清。这里只认三类信号:
|
|
6276
|
+
* · pnpm 的错误码:`ERR_PNPM_*` / `ERR_SQLITE_ERROR` / `ERR_INVALID_*`(统一前缀 ERR_)
|
|
6277
|
+
* · Node 的系统错误码:行首或空白后的 `E` + 大写字母组合 + 冒号(ENOSPC / EPERM: …)
|
|
6278
|
+
* · 通用异常:`Error:` / `ELIFECYCLE`(脚本失败)
|
|
6279
|
+
*
|
|
6280
|
+
* 输不出任何一条时退回「输出的最后一行非空内容」—— 那时至少给出一句人话可读的原文,
|
|
6281
|
+
* 比只写「安装失败」强。**这个保底只给 stderr 用**:stdout 里最后一行多半是
|
|
6282
|
+
* `Packages: +3` 这类统计,拿它当"错误行"反而误导。
|
|
6283
|
+
*
|
|
6284
|
+
* @param {string} text stdout 或 stderr
|
|
6285
|
+
* @param {number} limit 最多取几条
|
|
6286
|
+
* @param {boolean} [allowFallback] 没有匹配行时是否退回最后一行(默认 true)
|
|
6287
|
+
* @returns {string[]}
|
|
6288
|
+
*/
|
|
6289
|
+
function pickPnpmErrorLines(text, limit, allowFallback) {
|
|
6290
|
+
const raw = String(text === null || text === undefined ? '' : text)
|
|
6291
|
+
const lines = raw.split(/\r?\n/).map((one) => one.trim()).filter((one) => one.length > 0)
|
|
6292
|
+
const hit = lines.filter((one) => /ERR_[A-Z0-9_]+|\bE[A-Z]{2,}\b|Error:|ELIFECYCLE/.test(one))
|
|
6293
|
+
const allowLast = allowFallback !== false
|
|
6294
|
+
const picked = hit.length > 0 ? hit : (allowLast === true && lines.length > 0 ? [lines[lines.length - 1]] : [])
|
|
6295
|
+
/* 去重(stdout 与 stderr 里常出现同一行)+ 截断,最多 limit 条 */
|
|
6296
|
+
const seen = new Set()
|
|
6297
|
+
const out = []
|
|
6298
|
+
for (const line of picked) {
|
|
6299
|
+
const clean = line.length > 300 ? line.slice(0, 300) + '…' : line
|
|
6300
|
+
if (seen.has(clean) === true) continue
|
|
6301
|
+
seen.add(clean)
|
|
6302
|
+
out.push(clean)
|
|
6303
|
+
if (out.length >= limit) break
|
|
6304
|
+
}
|
|
6305
|
+
return out
|
|
6306
|
+
}
|
|
6307
|
+
|
|
6308
|
+
/**
|
|
6309
|
+
* 把宿主自己那次安装失败(self-update.js 的 `result.failureReport`)写成一句可读摘要。
|
|
6310
|
+
*
|
|
6311
|
+
* 与客户端失败不同,这里的字段**宿主全都知道**(它自己跑的 pnpm),所以能给出
|
|
6312
|
+
* 「哪个阶段、退出码多少、pnpm 原话是什么、有没有回滚」这四件对排查最有用的事实。
|
|
6313
|
+
* 用户拿着这句话就能直接搜错误码,不用先翻一整屏日志。
|
|
6314
|
+
*
|
|
6315
|
+
* @param {object} body failureReport
|
|
6316
|
+
* @returns {string}
|
|
6317
|
+
*/
|
|
6318
|
+
function describeHostInstallFailure(body) {
|
|
6319
|
+
const src = body !== null && body !== undefined && typeof body === 'object' ? body : {}
|
|
6320
|
+
const repair = src.mode === 'repair'
|
|
6321
|
+
const head = repair ? '修复安装阶段失败' : '安装阶段失败'
|
|
6322
|
+
const reasons = []
|
|
6323
|
+
if (typeof src.exitCode === 'number' && Number.isFinite(src.exitCode)) reasons.push('exit ' + String(src.exitCode))
|
|
6324
|
+
else if (src.timedOut === true) reasons.push('超时')
|
|
6325
|
+
const reason = typeof src.reason === 'string' && src.reason.length > 0 ? src.reason : null
|
|
6326
|
+
if (reason !== null) reasons.push(reason)
|
|
6327
|
+
/* pnpm 的真实错误行优先从 stderr 取,再从 stdout 补(有的版本把错误写在 stdout);
|
|
6328
|
+
stdout 不做"取最后一行"的保底 —— 那一行通常是 `Packages: +3` 这种统计。 */
|
|
6329
|
+
const errLines = pickPnpmErrorLines(src.stderr, 2, true).concat(pickPnpmErrorLines(src.stdout, 2, false))
|
|
6330
|
+
const unique = []
|
|
6331
|
+
for (const line of errLines) {
|
|
6332
|
+
if (unique.indexOf(line) < 0) unique.push(line)
|
|
6333
|
+
if (unique.length >= 3) break
|
|
6334
|
+
}
|
|
6335
|
+
const where = reasons.length > 0 ? '(' + reasons.join(',') + ')' : ''
|
|
6336
|
+
const detail = unique.length > 0 ? ':' + unique.join(' | ') : ''
|
|
6337
|
+
const rollback = src.rolledBack === true
|
|
6338
|
+
? '已回滚配置,环境未被改动。'
|
|
6339
|
+
: '未能回滚配置,环境可能仍处于中间状态。'
|
|
6340
|
+
return head + where + detail + ';' + rollback
|
|
6341
|
+
}
|
|
6342
|
+
|
|
6343
|
+
/**
|
|
6344
|
+
* 最近一条更新失败记录(客户端上报或宿主自更新失败),给状态接口读。
|
|
6345
|
+
*
|
|
6346
|
+
* 为什么要留最近一条而不是只写日志:日志是给开发者 tail 的,用户手上没有;
|
|
6347
|
+
* 而 GET /api/self-update 要把「失败之后能做什么」告诉界面时,需要这份结构化数据
|
|
6348
|
+
* (尤其是 `stage` 与 `rolledBack`:是宿主装挂了并已回滚,还是浏览器那边请求
|
|
6349
|
+
* 没发出去/回包解不开)。只留一条足够 —— 用户关心的是"刚刚这一次为什么失败"。
|
|
6350
|
+
*/
|
|
6351
|
+
let lastUpdateFailure = null
|
|
6352
|
+
|
|
6353
|
+
/**
|
|
6354
|
+
* 更新失败的统一落地点:写一条日志 + 记下最近一条。
|
|
6355
|
+
*
|
|
6356
|
+
* 两个来源共用它,保证「日志里有什么」与「状态接口里有什么」永远同源:
|
|
6357
|
+
* 1. 客户端 POST /api/update-failure(浏览器侧失败:fetch 被拦、回包解不开、HTTP 4xx);
|
|
6358
|
+
* 2. 宿主自己跑 pnpm 失败时内部直接调用(body = self-update.js 的 failureReport)。
|
|
6359
|
+
*
|
|
6360
|
+
* 为什么宿主那一侧是**直接函数调用**而不是 HTTP 回环到自己:
|
|
6361
|
+
* · 这个路由的全部效果就是「写日志 + 存一条」,纯进程内状态,没有任何需要走网络的理由;
|
|
6362
|
+
* · 回环会多一次 socket 往返,还要依赖 webServer 端口/监听状态,失败时反而会
|
|
6363
|
+
* 把一个诊断动作变成新的失败点(还得再兜一层 try)。
|
|
6364
|
+
*
|
|
6365
|
+
* @param {object} ctx 插件上下文(拿 logger)
|
|
6366
|
+
* @param {object|null} body 上报体 / failureReport
|
|
6367
|
+
*/
|
|
6368
|
+
function recordUpdateFailure(ctx, body) {
|
|
6369
|
+
const src = body !== null && body !== undefined && typeof body === 'object' ? body : {}
|
|
6370
|
+
/* 体量上限:stdout/stderr 各 64KB(见 self-update.js 的 OUTPUT_LIMIT),
|
|
6371
|
+
这里整体再压一层,避免把一整份输出塞进内存里的"最近一条"。
|
|
6372
|
+
|
|
6373
|
+
**原文也要留**:summary 是提炼过的中文摘要,用户排查时最需要的恰恰是 pnpm 的原话
|
|
6374
|
+
(哪一步、哪个包、什么错误码)。以前只留 summary,界面上就只剩「更新失败」四个字。
|
|
6375
|
+
尾部优先 —— pnpm 的失败结论总在最后几行。 */
|
|
6376
|
+
const tail = (text, limit) => {
|
|
6377
|
+
if (typeof text !== 'string' || text.length === 0) return ''
|
|
6378
|
+
return text.length <= limit ? text : text.slice(-limit)
|
|
6379
|
+
}
|
|
6380
|
+
lastUpdateFailure = {
|
|
6381
|
+
stage: typeof src.stage === 'string' ? src.stage.slice(0, 60) : 'unknown',
|
|
6382
|
+
mode: src.mode === 'repair' ? 'repair' : 'update',
|
|
6383
|
+
reason: typeof src.reason === 'string' ? src.reason.slice(0, 120) : null,
|
|
6384
|
+
rolledBack: src.rolledBack === true,
|
|
6385
|
+
at: Date.now(),
|
|
6386
|
+
summary: describeClientUpdateFailure(src),
|
|
6387
|
+
/* 界面直接把这两段原样摊在按钮下方(不滚动、不展开),所以这里就是"给人看的那份"。 */
|
|
6388
|
+
stdout: tail(src.stdout, UPDATE_FAILURE_OUTPUT_LIMIT),
|
|
6389
|
+
stderr: tail(src.stderr, UPDATE_FAILURE_OUTPUT_LIMIT),
|
|
6390
|
+
exitCode: typeof src.exitCode === 'number' ? src.exitCode : null,
|
|
6391
|
+
}
|
|
6392
|
+
logHost(ctx, 'update: 失败 ' + lastUpdateFailure.summary)
|
|
6393
|
+
}
|
|
6394
|
+
|
|
6395
|
+
/** 最近一条更新失败记录里保留的原始输出长度(尾部)。界面那块也是按这个量级展示的。 */
|
|
6396
|
+
const UPDATE_FAILURE_OUTPUT_LIMIT = 12000
|
|
6397
|
+
|
|
6398
|
+
/** 最近一条更新失败记录;没失败过就是 null。 */
|
|
6399
|
+
function lastUpdateFailureRecord() {
|
|
6400
|
+
return lastUpdateFailure
|
|
6401
|
+
}
|
|
6402
|
+
|
|
6403
|
+
/**
|
|
6404
|
+
* 日志里打印更新结果时用的紧凑版。
|
|
6405
|
+
*
|
|
6406
|
+
* 为什么不能直接 `JSON.stringify(value)`:`failureReport.stdout/stderr` 是 pnpm 的
|
|
6407
|
+
* 原始输出(各上限 64000 字符),一次失败会把几十 KB 灌进日志,同一次失败的
|
|
6408
|
+
* 可读摘要反而被淹掉。日志里只留结论字段,原文只在状态接口/诊断面按需取。
|
|
6409
|
+
*
|
|
6410
|
+
* @param {object} value selfUpdateOnce 的返回值
|
|
6411
|
+
* @returns {object}
|
|
6412
|
+
*/
|
|
6413
|
+
function compactUpdateResult(value) {
|
|
6414
|
+
const src = value !== null && value !== undefined && typeof value === 'object' ? value : {}
|
|
6415
|
+
const out = {
|
|
6416
|
+
ok: src.ok === true,
|
|
6417
|
+
mode: src.mode === 'repair' ? 'repair' : 'update',
|
|
6418
|
+
reason: src.reason === undefined ? null : src.reason,
|
|
6419
|
+
from: src.from === undefined ? null : src.from,
|
|
6420
|
+
to: src.to === undefined ? null : src.to,
|
|
6421
|
+
rolledBack: src.rolledBack === true,
|
|
6422
|
+
}
|
|
6423
|
+
if (src.failureReport !== undefined && src.failureReport !== null) {
|
|
6424
|
+
out.failureReport = '[已记入 update-failure] ' + describeClientUpdateFailure(src.failureReport)
|
|
6425
|
+
}
|
|
6426
|
+
return out
|
|
6427
|
+
}
|
|
6428
|
+
|
|
5065
6429
|
/**
|
|
5066
6430
|
* 把客户端上报的「更新失败」描述成一条能直接拿去问 AI 的日志文本。
|
|
5067
6431
|
*
|
|
@@ -5071,11 +6435,18 @@ function appendTipDiag(body) {
|
|
|
5071
6435
|
*
|
|
5072
6436
|
* 只取有限长度的字符串,避免恶意/异常的超长 body 把日志撑爆。
|
|
5073
6437
|
*
|
|
5074
|
-
*
|
|
6438
|
+
* `stage === 'host-install'` 是另一类:那时 body 就是 self-update.js 产出的
|
|
6439
|
+
* `failureReport`(宿主自己跑 pnpm 失败),字段完全不同(exitCode / stdout /
|
|
6440
|
+
* stderr / command / rolledBack),要按它自己的口径解读,不能套客户端那套。
|
|
6441
|
+
*
|
|
6442
|
+
* @param {object|null} body 客户端 POST 上来的 JSON,或宿主内部的 failureReport
|
|
5075
6443
|
* @returns {string}
|
|
5076
6444
|
*/
|
|
5077
6445
|
function describeClientUpdateFailure(body) {
|
|
5078
6446
|
const src = body !== null && body !== undefined && typeof body === 'object' ? body : {}
|
|
6447
|
+
/* 宿主安装失败优先:它有准确语义(退出码 + pnpm 原话 + 回滚结果),
|
|
6448
|
+
比客户端泛泛的「失败」信息量大得多,别再拼一串 target/current 冲淡它。 */
|
|
6449
|
+
if (src.stage === 'host-install') return describeHostInstallFailure(src)
|
|
5079
6450
|
const text = (value, max) => {
|
|
5080
6451
|
if (value === null || value === undefined) return null
|
|
5081
6452
|
const raw = typeof value === 'string' ? value : String(value)
|
|
@@ -5133,6 +6504,10 @@ async function refreshWeekUsage(force, ctx) {
|
|
|
5133
6504
|
if (weekUsageScan === null) {
|
|
5134
6505
|
const run = queueLedgerJob(async () => {
|
|
5135
6506
|
const ledger = readLedger()
|
|
6507
|
+
/* 历史重算的价目表必须在任何扫描改动之前快照:本轮 collect 结束会把
|
|
6508
|
+
ledger.priceFingerprint 覆盖成"当前价库",而重启后当前价库可能只剩内置表。
|
|
6509
|
+
先按台账指纹还原记账当时那份,USD 模型(gpt-6.1-sol 等)才找得到单价。 */
|
|
6510
|
+
const auditBookSnapshot = auditPriceBook(ledger)
|
|
5136
6511
|
/* 升级后第一次扫描:回扫一遍日志,把"当时缺价、没算钱"的用量找出来。
|
|
5137
6512
|
只补欠账清单,历史 token 与 cost 一个都不动。 */
|
|
5138
6513
|
let backfilled = null
|
|
@@ -5141,6 +6516,16 @@ async function refreshWeekUsage(force, ctx) {
|
|
|
5141
6516
|
ledger.unpricedBackfill = 'done'
|
|
5142
6517
|
note('usage-ledger: 回扫补全缺价明细,处理了 ' + String(backfilled.scanned) + ' 个日志文件')
|
|
5143
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
|
+
}
|
|
5144
6529
|
/* 价格补上来了就把欠账结算掉(只碰欠账,不重算已经算好的费用) */
|
|
5145
6530
|
const settled = settleUnpriced(ledger)
|
|
5146
6531
|
if (settled.entries > 0) {
|
|
@@ -5153,7 +6538,7 @@ async function refreshWeekUsage(force, ctx) {
|
|
|
5153
6538
|
if (ledger.costByCurrencyBackfill === 'pending') ledger.costByCurrencyBackfill = 'done'
|
|
5154
6539
|
pruneLedger(ledger)
|
|
5155
6540
|
if (stats.added > 0 || stats.scannedFiles > 0 || ledger.updatedAt === 0
|
|
5156
|
-
|| settled.entries > 0 || backfilled !== null) {
|
|
6541
|
+
|| settled.entries > 0 || backfilled !== null || providerAudit !== null) {
|
|
5157
6542
|
ledger.updatedAt = Date.now()
|
|
5158
6543
|
writeLedger(ledger)
|
|
5159
6544
|
}
|
|
@@ -5271,32 +6656,49 @@ async function checkLatestVersion() {
|
|
|
5271
6656
|
|
|
5272
6657
|
/* ------------------------------------------------------------------ apply */
|
|
5273
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
|
+
|
|
5274
6694
|
export function apply(ctx) {
|
|
5275
6695
|
ctxRef = ctx
|
|
5276
|
-
ctx
|
|
5277
|
-
|
|
5278
|
-
|
|
5279
|
-
)
|
|
5280
|
-
ctx
|
|
5281
|
-
|
|
5282
|
-
'dsh-desktop-statusbar: sessionCapacity projection',
|
|
5283
|
-
)
|
|
5284
|
-
ctx.effect(
|
|
5285
|
-
() => ctx.sessionProjections.register(sessionProgressProjection),
|
|
5286
|
-
'dsh-desktop-statusbar: sessionProgress projection',
|
|
5287
|
-
)
|
|
5288
|
-
ctx.effect(
|
|
5289
|
-
() => ctx.sessionProjections.register(sessionUsageProjection),
|
|
5290
|
-
'dsh-desktop-statusbar: sessionUsage projection',
|
|
5291
|
-
)
|
|
5292
|
-
ctx.effect(
|
|
5293
|
-
() => ctx.sessionProjections.register(sessionTimeRangeProjection),
|
|
5294
|
-
'dsh-desktop-statusbar: sessionTimeRange projection',
|
|
5295
|
-
)
|
|
5296
|
-
ctx.effect(
|
|
5297
|
-
() => ctx.sessionProjections.register(sessionTimingProjection),
|
|
5298
|
-
'dsh-desktop-statusbar: sessionTiming projection',
|
|
5299
|
-
)
|
|
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')
|
|
5300
6702
|
|
|
5301
6703
|
/* 会话日志一旦被删就没了,台账是唯一留得住的地方:启动时先并一次作为预热,
|
|
5302
6704
|
之后只在用户打开活跃总览面板时(带 force=1)现扫。 */
|
|
@@ -5340,15 +6742,139 @@ export function apply(ctx) {
|
|
|
5340
6742
|
}), 'dsh-desktop-statusbar: balance api')
|
|
5341
6743
|
}
|
|
5342
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
|
+
|
|
5343
6838
|
async function handleApi(req, res, ctx) {
|
|
5344
6839
|
/* 带跨站 Origin 的写请求一律拒绝:浏览器里任意网页都能对本机发简单请求,
|
|
5345
6840
|
必须在**改任何状态之前**挡住(判定见 isCrossSiteWrite 的说明)。 */
|
|
5346
|
-
if (isCrossSiteWrite(req) === true) {
|
|
6841
|
+
if (isCrossSiteWrite(req, ctx) === true) {
|
|
5347
6842
|
logHost(ctx, 'api: 拒绝跨站写请求 origin=' + String(req.headers.origin))
|
|
5348
6843
|
sendJson(res, 403, { ok: false, reason: 'cross-origin' })
|
|
5349
6844
|
return
|
|
5350
6845
|
}
|
|
5351
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
|
+
}
|
|
5352
6878
|
if (url.pathname === '/dsh-desktop-statusbar/api/prices') {
|
|
5353
6879
|
/* POST = 客户端把它的价格库(localStorage 那份,用户可增删改)报上来。
|
|
5354
6880
|
活跃总览的 cost 由 host 记账时算出,必须用同一份价格,否则用户在设置页
|
|
@@ -5466,20 +6992,29 @@ async function handleApi(req, res, ctx) {
|
|
|
5466
6992
|
&& compareVersions(latestVersion.latest, current) > 0,
|
|
5467
6993
|
checkedAt: latestVersion.checkedAt,
|
|
5468
6994
|
error: latestVersion.error,
|
|
6995
|
+
/* 最近一次失败的原文一并带回去:界面要把它摊在更新按钮下方。
|
|
6996
|
+
走这个接口而不是单独加一个路由 —— 客户端每次刷新本来就会问它一次,
|
|
6997
|
+
多一个字段比多一次请求划算,也不会出现「自检回来了、报错还没回来」的半态。 */
|
|
6998
|
+
lastFailure: lastUpdateFailureRecord(),
|
|
5469
6999
|
})
|
|
5470
7000
|
return
|
|
5471
7001
|
}
|
|
5472
7002
|
if (url.pathname === '/dsh-desktop-statusbar/api/self-update') {
|
|
5473
7003
|
/* 一键更新:由本插件自己完成,不依赖「插件管理器」这个别的插件,也不走
|
|
5474
7004
|
pnpm 的 24 小时发布年龄策略(做法见 self-update.js 顶部说明)。
|
|
5475
|
-
GET = 问当前状态(界面挂在更新中途刷新时能接上);POST = 发起一次更新。
|
|
7005
|
+
GET = 问当前状态(界面挂在更新中途刷新时能接上);POST = 发起一次更新。
|
|
7006
|
+
`?mode=repair` = 修复安装:不装新版本,只让 pnpm 按现有清单把 node_modules
|
|
7007
|
+
对齐(升级失败后 package.json / 锁文件 / 实物互相矛盾的场景)。 */
|
|
7008
|
+
const mode = url.searchParams.get('mode') === 'repair' ? 'repair' : 'update'
|
|
5476
7009
|
if (req.method !== 'POST') {
|
|
5477
7010
|
const last = lastUpdateResult()
|
|
7011
|
+
const failure = lastUpdateFailureRecord()
|
|
5478
7012
|
sendJson(res, 200, {
|
|
5479
7013
|
ok: true,
|
|
5480
7014
|
busy: isUpdating(),
|
|
5481
7015
|
last: last === null ? null : {
|
|
5482
7016
|
ok: last.ok === true,
|
|
7017
|
+
mode: last.mode === 'repair' ? 'repair' : 'update',
|
|
5483
7018
|
reason: last.reason === undefined ? null : last.reason,
|
|
5484
7019
|
from: last.from === undefined ? null : last.from,
|
|
5485
7020
|
to: last.to === undefined ? null : last.to,
|
|
@@ -5487,40 +7022,60 @@ async function handleApi(req, res, ctx) {
|
|
|
5487
7022
|
手工逐条 Test-Path,这里直接摊开。其它失败原因下是空数组。 */
|
|
5488
7023
|
tried: Array.isArray(last.tried) === true ? last.tried : [],
|
|
5489
7024
|
},
|
|
7025
|
+
/* 最近一次失败的**可读摘要**(宿主装挂了会带 pnpm 的错误行;客户端失败则带
|
|
7026
|
+
它自己报上来的 stage/detail)。界面不强制用它,排查时它是最短的一条线索。 */
|
|
7027
|
+
lastFailure: failure,
|
|
5490
7028
|
})
|
|
5491
7029
|
return
|
|
5492
7030
|
}
|
|
5493
7031
|
const body = await readJsonBody(req)
|
|
5494
|
-
|
|
5495
|
-
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
|
|
5502
|
-
sendJson(res, 409, { ok: false, reason: 'busy' })
|
|
5503
|
-
return
|
|
5504
|
-
}
|
|
5505
|
-
let target = raw
|
|
5506
|
-
if (target.length === 0) {
|
|
5507
|
-
/* 客户端没带版本就自己查一次最新的 */
|
|
5508
|
-
const checked = await checkLatestVersion()
|
|
5509
|
-
latestVersion = checked
|
|
5510
|
-
if (checked.latest === null) {
|
|
5511
|
-
sendJson(res, 200, { ok: false, reason: checked.error === null ? 'no-version' : checked.error })
|
|
7032
|
+
/* repair 模式不需要目标版本:它装的是"现有清单里写的那些",所以整段版本校验跳过。 */
|
|
7033
|
+
let target = ''
|
|
7034
|
+
if (mode !== 'repair') {
|
|
7035
|
+
const raw = body === null || typeof body.version !== 'string' ? '' : body.version.trim()
|
|
7036
|
+
/* 目标版本必须是明确的三段式版本号:不接受 latest/tag/范围,避免装到别的东西。
|
|
7037
|
+
空则不传 —— host 会自己问 registry 的最新版。 */
|
|
7038
|
+
if (raw.length > 0 && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(raw) !== true) {
|
|
7039
|
+
sendJson(res, 400, { ok: false, reason: 'bad-version' })
|
|
5512
7040
|
return
|
|
5513
7041
|
}
|
|
5514
|
-
|
|
7042
|
+
if (isUpdating() === true) {
|
|
7043
|
+
sendJson(res, 409, { ok: false, reason: 'busy' })
|
|
7044
|
+
return
|
|
7045
|
+
}
|
|
7046
|
+
target = raw
|
|
7047
|
+
if (target.length === 0) {
|
|
7048
|
+
/* 客户端没带版本就自己查一次最新的 */
|
|
7049
|
+
const checked = await checkLatestVersion()
|
|
7050
|
+
latestVersion = checked
|
|
7051
|
+
if (checked.latest === null) {
|
|
7052
|
+
sendJson(res, 200, { ok: false, reason: checked.error === null ? 'no-version' : checked.error })
|
|
7053
|
+
return
|
|
7054
|
+
}
|
|
7055
|
+
target = checked.latest
|
|
7056
|
+
}
|
|
7057
|
+
} else if (isUpdating() === true) {
|
|
7058
|
+
sendJson(res, 409, { ok: false, reason: 'busy' })
|
|
7059
|
+
return
|
|
5515
7060
|
}
|
|
5516
7061
|
const selfDir = resolveSelfDir()
|
|
5517
|
-
logHost(ctxRef,
|
|
7062
|
+
logHost(ctxRef, mode === 'repair'
|
|
7063
|
+
? 'update: 收到修复安装请求(mode=repair,当前目录 ' + selfDir + ')'
|
|
7064
|
+
: 'update: 收到更新请求 → ' + target + '(当前目录 ' + selfDir + ')')
|
|
5518
7065
|
const value = await selfUpdateOnce({
|
|
5519
7066
|
selfDir,
|
|
5520
7067
|
version: target,
|
|
7068
|
+
mode,
|
|
5521
7069
|
logger: (message) => logHost(ctxRef, message),
|
|
5522
7070
|
})
|
|
5523
|
-
logHost(ctxRef, 'update: 结果 ' + JSON.stringify(value))
|
|
7071
|
+
logHost(ctxRef, 'update: 结果 ' + JSON.stringify(compactUpdateResult(value)))
|
|
7072
|
+
/* M2 的收尾:失败时把结构化 failureReport 落到同一个诊断面(/api/update-failure)。
|
|
7073
|
+
这里**不走 HTTP 自己请求自己** —— 那要多一次回环、还可能被跨站防护/端口变化挡掉,
|
|
7074
|
+
而且它要做的两件事(写日志 + 记最近一条失败)本来就是本进程内的纯函数调用。
|
|
7075
|
+
下面 recordUpdateFailure 与 update-failure 路由共用同一个落地点。 */
|
|
7076
|
+
if (value.ok !== true && value.failureReport !== undefined && value.failureReport !== null) {
|
|
7077
|
+
recordUpdateFailure(ctx, value.failureReport)
|
|
7078
|
+
}
|
|
5524
7079
|
sendJson(res, 200, value)
|
|
5525
7080
|
return
|
|
5526
7081
|
}
|
|
@@ -5599,15 +7154,18 @@ async function handleApi(req, res, ctx) {
|
|
|
5599
7154
|
return
|
|
5600
7155
|
}
|
|
5601
7156
|
if (url.pathname === '/dsh-desktop-statusbar/api/update-failure') {
|
|
5602
|
-
/*
|
|
5603
|
-
`update: 结果 {...}`
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
|
|
7157
|
+
/* 更新失败的上报口(诊断面)。为什么需要它:宿主自己跑 pnpm 的那次失败已经由
|
|
7158
|
+
`update: 结果 {...}` 记了,但**客户端自己**的失败(fetch 被代理拦、响应解不出来、
|
|
7159
|
+
网络断)发生在浏览器里,宿主完全不知道 —— 用户点完只看到「更新失败」,
|
|
7160
|
+
日志里查不到任何痕迹,想用 AI 排查也无从下手。
|
|
7161
|
+
这里把它补成一条**结构化记录**:既有给人看的中文摘要,也留一份最近记录
|
|
7162
|
+
给 GET /api/self-update 用(见 recordUpdateFailure)。
|
|
7163
|
+
不做状态变更、不重试安装,所以是纯诊断面。
|
|
7164
|
+
**宿主自己的 failureReport 不走这里**(同一个函数由 self-update 那条路由
|
|
7165
|
+
直接调用):回环 HTTP 只是把进程内调用包装成一次多余的 socket 往返。 */
|
|
5608
7166
|
if (req.method === 'POST') {
|
|
5609
7167
|
const body = await readJsonBody(req)
|
|
5610
|
-
|
|
7168
|
+
recordUpdateFailure(ctx, body)
|
|
5611
7169
|
}
|
|
5612
7170
|
sendJson(res, 200, { ok: true })
|
|
5613
7171
|
return
|
|
@@ -5617,6 +7175,16 @@ async function handleApi(req, res, ctx) {
|
|
|
5617
7175
|
return
|
|
5618
7176
|
}
|
|
5619
7177
|
const force = url.searchParams.get('force') === '1'
|
|
5620
|
-
|
|
5621
|
-
|
|
7178
|
+
/* 每日汇率:搭在余额查询这条已有的 60 秒轮询上,**不新增定时器**。
|
|
7179
|
+
判据是「缓存为空 / 缓存早于今天 9:00」—— 9:00 之前一次都不拉,9:00 之后第一拍拉一次,
|
|
7180
|
+
当天再也不会重复。失败完全静默:汇率是显示用的辅助数据,拉不到就用上次那份。 */
|
|
7181
|
+
if (shouldRefresh(readCachedRate(), Date.now()) === true) {
|
|
7182
|
+
fetchAndCacheRate({ logger: (message) => logHost(ctx, message) })
|
|
7183
|
+
.catch(() => { /* 静默:汇率拉不到不影响余额 */ })
|
|
7184
|
+
}
|
|
7185
|
+
const value = await queryBalance(ctx, force, url.searchParams.get('provider'), url.searchParams.get('model'),
|
|
7186
|
+
url.searchParams.get('relay'))
|
|
7187
|
+
/* 把当前汇率一并交给客户端:余额是「当下的钱」,它要用**当前**汇率折算,
|
|
7188
|
+
而汇率由 host 统一维护(每天 9:00 拉一次),客户端不必自己发请求。 */
|
|
7189
|
+
sendJson(res, 200, Object.assign({}, value, { probe: accountProbeNote, exchangeRate: currentExchangeRate() }))
|
|
5622
7190
|
}
|