@lingda-ai/dsh-plugin-quota 0.0.0-stage → 0.1.2
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 +202 -0
- package/README.md +123 -2
- package/cordis.patch.yml +8 -0
- package/icon.svg +5 -0
- package/index.js +212 -0
- package/lib/book.js +290 -0
- package/lib/breaker.js +80 -0
- package/lib/client.js +438 -0
- package/lib/policy.js +125 -0
- package/lib/rates.js +172 -0
- package/lib/redact.js +58 -0
- package/lib/route.js +68 -0
- package/lib/tool.js +70 -0
- package/lib/usage.js +72 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
package/lib/client.js
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @lingda-ai/dsh-plugin-quota —— Client 半(右侧栏「航油」tab)
|
|
3
|
+
*
|
|
4
|
+
* 形态同黑匣子:宿主把 client.js 原样拼成 classic script,不能有 import/export,
|
|
5
|
+
* 只允许一次 window.__ModuleLoader__.load()。
|
|
6
|
+
*
|
|
7
|
+
* 读法:同源 `GET /dsh-quota/api?state=1`,Host 只读投影,浏览器不落盘。
|
|
8
|
+
* 布局硬约束:右栏最窄 300px;所有数字列定宽,长文本省略。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
window.__ModuleLoader__.load({
|
|
12
|
+
id: '@lingda-ai/dsh-plugin-quota',
|
|
13
|
+
factory(require) {
|
|
14
|
+
const React = require('react')
|
|
15
|
+
const h = React.createElement
|
|
16
|
+
const { useState, useEffect, useRef, useCallback, useMemo } = React
|
|
17
|
+
|
|
18
|
+
const ID = '@lingda-ai/dsh-plugin-quota'
|
|
19
|
+
const KIND = 'quota.fuel'
|
|
20
|
+
const API = '/dsh-quota/api'
|
|
21
|
+
|
|
22
|
+
const C = {
|
|
23
|
+
t1: '#1f2733',
|
|
24
|
+
t2: '#5a6472',
|
|
25
|
+
t3: '#64707f',
|
|
26
|
+
t4: '#8a93a0',
|
|
27
|
+
hair: '#eef1f5',
|
|
28
|
+
green: '#2f7d64',
|
|
29
|
+
amber: '#c98a12',
|
|
30
|
+
red: '#b4453c',
|
|
31
|
+
track: '#f0f3f7',
|
|
32
|
+
fill: '#2f6feb',
|
|
33
|
+
fillWarn: '#c98a12',
|
|
34
|
+
fillOver: '#b4453c',
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const DICT = {
|
|
38
|
+
zh: {
|
|
39
|
+
title: '航油',
|
|
40
|
+
guideDesc: '预算与熔断:还能花多少、按现在的速度会不会超、到线怎么办',
|
|
41
|
+
loading: '正在读额度…',
|
|
42
|
+
refresh: '刷新',
|
|
43
|
+
periodDay: '今日',
|
|
44
|
+
periodWeek: '本周',
|
|
45
|
+
periodMonth: '本月',
|
|
46
|
+
used: '已用',
|
|
47
|
+
remaining: '剩余',
|
|
48
|
+
noBudget: '本周期还没设预算',
|
|
49
|
+
noBudgetBody: '不设预算就不拦任何人——这是默认。想开预算,写一个文件即可,改完立刻生效。',
|
|
50
|
+
noBudgetHint: '~/.dsh/ops/quota/policy.json 例:{"budget":{"period":"month","amount":20}}',
|
|
51
|
+
forecast: '按当前速度,周期结束约 {v}',
|
|
52
|
+
forecastOver: '按这个速度会用超',
|
|
53
|
+
forecastEarly: '刚开始,还看不出趋势',
|
|
54
|
+
calls: '{n} 次调用',
|
|
55
|
+
saved: '缓存已省 {v}',
|
|
56
|
+
unknown: '{n} 次费率未知,未计入',
|
|
57
|
+
actionDowngrade: '到线后:降级到 {model}(不打断会话)',
|
|
58
|
+
actionNotify: '到线后:只提醒,不拦截',
|
|
59
|
+
warnAt: '到 {p}% 先提醒',
|
|
60
|
+
days: '本周期日消耗',
|
|
61
|
+
sessions: '最贵的会话',
|
|
62
|
+
noSessions: '本周期还没有会话',
|
|
63
|
+
errTitle: '额度读不出来',
|
|
64
|
+
emptyTitle: '还没有消耗',
|
|
65
|
+
emptyBody: '发一条消息就开始计。数据只记金额与次数,不记内容。',
|
|
66
|
+
notConfigured: '未设预算',
|
|
67
|
+
config: '配置',
|
|
68
|
+
},
|
|
69
|
+
en: {
|
|
70
|
+
title: 'Fuel',
|
|
71
|
+
guideDesc: 'Budget and breaker: how much is left, whether you will overshoot, what happens at the limit',
|
|
72
|
+
loading: 'Reading budget…',
|
|
73
|
+
refresh: 'Refresh',
|
|
74
|
+
periodDay: 'Today',
|
|
75
|
+
periodWeek: 'This week',
|
|
76
|
+
periodMonth: 'This month',
|
|
77
|
+
used: 'Used',
|
|
78
|
+
remaining: 'Left',
|
|
79
|
+
noBudget: 'No budget for this period',
|
|
80
|
+
noBudgetBody: 'Without a budget nothing is limited — that is the default. To enable, write one file; it applies immediately.',
|
|
81
|
+
noBudgetHint: '~/.dsh/ops/quota/policy.json e.g. {"budget":{"period":"month","amount":20}}',
|
|
82
|
+
forecast: 'At this rate the period ends near {v}',
|
|
83
|
+
forecastOver: 'At this rate you will overshoot',
|
|
84
|
+
forecastEarly: 'Too early to project',
|
|
85
|
+
calls: '{n} calls',
|
|
86
|
+
saved: 'cache saved {v}',
|
|
87
|
+
unknown: '{n} calls unpriced, excluded',
|
|
88
|
+
actionDowngrade: 'At the limit: downgrade to {model} (session continues)',
|
|
89
|
+
actionNotify: 'At the limit: notify only',
|
|
90
|
+
warnAt: 'warn at {p}%',
|
|
91
|
+
days: 'Daily spend',
|
|
92
|
+
sessions: 'Costliest sessions',
|
|
93
|
+
noSessions: 'No sessions this period',
|
|
94
|
+
errTitle: 'Budget unavailable',
|
|
95
|
+
emptyTitle: 'Nothing spent yet',
|
|
96
|
+
emptyBody: 'Send one message to start. Only amounts and counts are recorded.',
|
|
97
|
+
notConfigured: 'no budget',
|
|
98
|
+
config: 'Config',
|
|
99
|
+
},
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let T = DICT.zh
|
|
103
|
+
|
|
104
|
+
function getService(ctx, name) {
|
|
105
|
+
try {
|
|
106
|
+
if (ctx && typeof ctx.get === 'function') return ctx.get(name) ?? null
|
|
107
|
+
return (ctx && ctx[name]) ?? null
|
|
108
|
+
} catch {
|
|
109
|
+
return null
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function detectLocale(ctx) {
|
|
114
|
+
const locale = getService(ctx, 'locale')
|
|
115
|
+
let id = ''
|
|
116
|
+
try {
|
|
117
|
+
const snapshot = typeof locale?.getLocale === 'function' ? locale.getLocale() : null
|
|
118
|
+
if (typeof snapshot === 'string') id = snapshot
|
|
119
|
+
else if (snapshot) id = String(snapshot.id || snapshot.locale || snapshot.language || '')
|
|
120
|
+
} catch {
|
|
121
|
+
id = ''
|
|
122
|
+
}
|
|
123
|
+
if (id.length === 0) {
|
|
124
|
+
try {
|
|
125
|
+
id = window.navigator.language || ''
|
|
126
|
+
} catch {
|
|
127
|
+
id = ''
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return /^en/i.test(id) ? 'en' : 'zh'
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// #region 格式化
|
|
134
|
+
function money(amount, currency) {
|
|
135
|
+
if (!Number.isFinite(amount)) return null
|
|
136
|
+
const symbol = currency === 'CNY' ? '¥' : currency === 'USD' ? '$' : ''
|
|
137
|
+
const abs = Math.abs(amount)
|
|
138
|
+
const digits = abs >= 10 ? 1 : abs >= 0.1 ? 2 : 4
|
|
139
|
+
return symbol + amount.toFixed(digits)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function periodLabel(kind) {
|
|
143
|
+
return kind === 'day' ? T.periodDay : kind === 'week' ? T.periodWeek : T.periodMonth
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function fillOf(ratio) {
|
|
147
|
+
if (!Number.isFinite(ratio)) return C.fill
|
|
148
|
+
if (ratio >= 1) return C.fillOver
|
|
149
|
+
if (ratio >= 0.8) return C.fillWarn
|
|
150
|
+
return C.fill
|
|
151
|
+
}
|
|
152
|
+
// #endregion
|
|
153
|
+
|
|
154
|
+
async function getJson(query, signal) {
|
|
155
|
+
const response = await fetch(API + '?' + query, { signal, headers: { accept: 'application/json' } })
|
|
156
|
+
if (!response.ok) throw new Error('HTTP ' + response.status)
|
|
157
|
+
const data = await response.json()
|
|
158
|
+
if (!data || data.ok !== true) throw new Error((data && data.error) || '查询失败')
|
|
159
|
+
return data
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function Meter(props) {
|
|
163
|
+
const ratio = props.ratio
|
|
164
|
+
const width = Number.isFinite(ratio) ? Math.max(0, Math.min(100, ratio * 100)) : 0
|
|
165
|
+
return h('div', { style: { position: 'relative', height: 8, borderRadius: 4, background: C.track, overflow: 'hidden' } },
|
|
166
|
+
h('i', {
|
|
167
|
+
style: {
|
|
168
|
+
display: 'block', height: '100%', width: width + '%',
|
|
169
|
+
background: fillOf(ratio), borderRadius: 4, transition: 'width .3s ease',
|
|
170
|
+
},
|
|
171
|
+
}),
|
|
172
|
+
props.warn !== null && Number.isFinite(props.warn)
|
|
173
|
+
? h('i', {
|
|
174
|
+
title: '提醒线 ' + Math.round(props.warn * 100) + '%',
|
|
175
|
+
style: {
|
|
176
|
+
position: 'absolute', top: 0, bottom: 0, width: 1,
|
|
177
|
+
left: Math.min(99, Math.round(props.warn * 100)) + '%', background: 'rgba(31,39,51,.28)',
|
|
178
|
+
},
|
|
179
|
+
})
|
|
180
|
+
: null,
|
|
181
|
+
)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function Bar(props) {
|
|
185
|
+
const max = props.max > 0 ? props.max : 1
|
|
186
|
+
return props.rows.length === 0
|
|
187
|
+
? h('div', { style: { fontSize: 11, color: C.t3, padding: '4px 0' } }, T.noSessions)
|
|
188
|
+
: h('div', { style: { display: 'flex', alignItems: 'flex-end', gap: 4, height: 46, paddingTop: 6 } },
|
|
189
|
+
props.rows.map((row) => h('div', {
|
|
190
|
+
key: row.day,
|
|
191
|
+
title: row.day + ' ' + (money(row.amount, row.currency) || '—'),
|
|
192
|
+
style: { flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'center', gap: 3 },
|
|
193
|
+
},
|
|
194
|
+
h('i', {
|
|
195
|
+
style: {
|
|
196
|
+
display: 'block', width: '100%', borderRadius: 2,
|
|
197
|
+
height: Math.max(2, Math.round((Math.max(0, row.amount) / max) * 34)) + 'px',
|
|
198
|
+
background: row.unknown > 0 && row.amount === 0 ? C.amber : '#b9c6da',
|
|
199
|
+
},
|
|
200
|
+
}),
|
|
201
|
+
h('span', { style: { fontSize: 9, color: C.t4 } }, row.day.slice(5)),
|
|
202
|
+
)))
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function Panel(props) {
|
|
206
|
+
const [data, setData] = useState(null)
|
|
207
|
+
const [error, setError] = useState(null)
|
|
208
|
+
const [loading, setLoading] = useState(true)
|
|
209
|
+
const [tick, setTick] = useState(0)
|
|
210
|
+
const alive = useRef(true)
|
|
211
|
+
|
|
212
|
+
useEffect(() => () => { alive.current = false }, [])
|
|
213
|
+
|
|
214
|
+
useEffect(() => {
|
|
215
|
+
const controller = new AbortController()
|
|
216
|
+
setLoading(true)
|
|
217
|
+
getJson('state=1', controller.signal)
|
|
218
|
+
.then((payload) => {
|
|
219
|
+
if (!alive.current) return
|
|
220
|
+
setData(payload)
|
|
221
|
+
setError(null)
|
|
222
|
+
setLoading(false)
|
|
223
|
+
})
|
|
224
|
+
.catch((cause) => {
|
|
225
|
+
if (cause && cause.name === 'AbortError') return
|
|
226
|
+
if (!alive.current) return
|
|
227
|
+
setError(cause.message || '读取失败')
|
|
228
|
+
setLoading(false)
|
|
229
|
+
})
|
|
230
|
+
return () => controller.abort()
|
|
231
|
+
}, [tick])
|
|
232
|
+
|
|
233
|
+
const refresh = useCallback(() => setTick((n) => n + 1), [])
|
|
234
|
+
|
|
235
|
+
const head = h('div', {
|
|
236
|
+
style: {
|
|
237
|
+
display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px 8px',
|
|
238
|
+
borderBottom: '1px solid ' + C.hair,
|
|
239
|
+
},
|
|
240
|
+
},
|
|
241
|
+
h('span', { style: { fontSize: 13, fontWeight: 600, color: C.t1, whiteSpace: 'nowrap' } }, T.title),
|
|
242
|
+
h('span', {
|
|
243
|
+
style: {
|
|
244
|
+
fontSize: 10.5, color: C.t3, border: '1px solid #e1e6ee', borderRadius: 999,
|
|
245
|
+
padding: '1px 7px', whiteSpace: 'nowrap',
|
|
246
|
+
},
|
|
247
|
+
}, data ? periodLabel(data.period.kind) + ' · ' + data.period.key : '—'),
|
|
248
|
+
h('button', {
|
|
249
|
+
type: 'button',
|
|
250
|
+
onClick: refresh,
|
|
251
|
+
style: {
|
|
252
|
+
marginLeft: 'auto', border: '1px solid #d8dee7', background: '#fff',
|
|
253
|
+
borderRadius: 7, padding: '3px 9px', fontSize: 11.5, color: C.t2, cursor: 'pointer',
|
|
254
|
+
},
|
|
255
|
+
}, T.refresh),
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
let body
|
|
259
|
+
if (loading && !data) {
|
|
260
|
+
body = h('div', { style: { padding: '16px 14px', fontSize: 11.5, color: C.t3 } }, T.loading)
|
|
261
|
+
} else if (error) {
|
|
262
|
+
body = h('div', { style: { padding: '16px 14px' } },
|
|
263
|
+
h('div', { style: { fontSize: 13, fontWeight: 600, color: C.t1, marginBottom: 6 } }, T.errTitle),
|
|
264
|
+
h('div', { style: { fontSize: 11.5, color: C.t2, lineHeight: 1.7 } }, error))
|
|
265
|
+
} else if (data) {
|
|
266
|
+
const limit = data.limit
|
|
267
|
+
const hasBudget = Number.isFinite(limit) && limit > 0
|
|
268
|
+
const spentText = money(data.total.amount, data.currency) || '—'
|
|
269
|
+
const limitText = hasBudget ? money(limit, data.currency) : T.notConfigured
|
|
270
|
+
const policy = data.policy || {}
|
|
271
|
+
const warn = policy.thresholds ? policy.thresholds.warn : null
|
|
272
|
+
const maxDay = (data.days || []).reduce((max, row) => Math.max(max, row.amount || 0), 0)
|
|
273
|
+
|
|
274
|
+
const action = policy.action && policy.action.atLimit === 'downgrade'
|
|
275
|
+
? T.actionDowngrade.replace('{model}', policy.action.downgradeModel || '—')
|
|
276
|
+
: T.actionNotify
|
|
277
|
+
|
|
278
|
+
body = h('div', null,
|
|
279
|
+
// 主数字
|
|
280
|
+
h('div', { style: { padding: '12px 14px 0' } },
|
|
281
|
+
h('div', { style: { display: 'flex', alignItems: 'baseline', gap: 6, flexWrap: 'wrap' } },
|
|
282
|
+
h('span', { style: { fontSize: 11, color: C.t3 } }, T.used),
|
|
283
|
+
h('span', { style: { fontSize: 22, fontWeight: 600, color: C.t1, fontVariantNumeric: 'tabular-nums' } }, spentText),
|
|
284
|
+
h('span', { style: { fontSize: 11.5, color: C.t4 } }, '/ ' + limitText),
|
|
285
|
+
),
|
|
286
|
+
hasBudget
|
|
287
|
+
? h('div', { style: { marginTop: 8 } },
|
|
288
|
+
h(Meter, { ratio: data.ratio, warn }),
|
|
289
|
+
h('div', { style: { display: 'flex', justifyContent: 'space-between', marginTop: 5, fontSize: 10.5, color: C.t3 } },
|
|
290
|
+
h('span', null, T.remaining + ' ' + (money(data.remaining, data.currency) || '—')),
|
|
291
|
+
h('span', null, T.warnAt.replace('{p}', String(Math.round((warn ?? 0.8) * 100)))),
|
|
292
|
+
))
|
|
293
|
+
: h('div', {
|
|
294
|
+
style: {
|
|
295
|
+
marginTop: 10, padding: '9px 10px', background: '#f6f8fb',
|
|
296
|
+
borderLeft: '2px solid ' + C.t3, borderRadius: '0 8px 8px 0',
|
|
297
|
+
fontSize: 11, lineHeight: 1.7, color: C.t2,
|
|
298
|
+
},
|
|
299
|
+
},
|
|
300
|
+
h('b', { style: { color: C.t1 } }, T.noBudget),
|
|
301
|
+
h('br'),
|
|
302
|
+
T.noBudgetBody,
|
|
303
|
+
h('div', { style: { marginTop: 6, fontFamily: 'ui-monospace, monospace', fontSize: 10.5, color: C.t3 } }, T.noBudgetHint),
|
|
304
|
+
),
|
|
305
|
+
),
|
|
306
|
+
|
|
307
|
+
(data.policyWarnings || []).length > 0
|
|
308
|
+
? h('div', {
|
|
309
|
+
style: {
|
|
310
|
+
margin: '0 14px', padding: '7px 9px', background: '#fdf7ec',
|
|
311
|
+
borderLeft: '2px solid ' + C.amber, borderRadius: '0 8px 8px 0',
|
|
312
|
+
fontSize: 10.5, lineHeight: 1.65, color: C.t2,
|
|
313
|
+
},
|
|
314
|
+
},
|
|
315
|
+
h('b', { style: { color: C.amber } }, '策略提示:'),
|
|
316
|
+
data.policyWarnings.join(';'))
|
|
317
|
+
: null,
|
|
318
|
+
|
|
319
|
+
// 三格
|
|
320
|
+
h('div', { style: { display: 'flex', gap: 8, padding: '12px 14px 4px' } },
|
|
321
|
+
[
|
|
322
|
+
[T.calls.replace('{n}', String(data.total.calls ?? 0)), null],
|
|
323
|
+
[T.saved.replace('{v}', money(data.saved.amount, data.currency) || '—'), C.green],
|
|
324
|
+
[data.total.unknown > 0 ? T.unknown.replace('{n}', String(data.total.unknown)) : action, data.total.unknown > 0 ? C.amber : C.t3],
|
|
325
|
+
].map(([text, color], index) => h('div', {
|
|
326
|
+
key: index,
|
|
327
|
+
style: {
|
|
328
|
+
flex: 1, minWidth: 0, padding: '7px 8px', background: '#fafbfd',
|
|
329
|
+
borderRadius: 8, fontSize: 10.5, lineHeight: 1.5, color: color || C.t2,
|
|
330
|
+
},
|
|
331
|
+
}, text)),
|
|
332
|
+
),
|
|
333
|
+
|
|
334
|
+
// 预测
|
|
335
|
+
h('div', { style: { padding: '8px 14px 0', fontSize: 11, color: C.t3 } },
|
|
336
|
+
data.forecast
|
|
337
|
+
? (data.forecast.projected > (hasBudget ? limit : Infinity)
|
|
338
|
+
? h('span', { style: { color: C.red } },
|
|
339
|
+
T.forecast.replace('{v}', money(data.forecast.projected, data.currency) || '—') + ' · ' + T.forecastOver)
|
|
340
|
+
: T.forecast.replace('{v}', money(data.forecast.projected, data.currency) || '—'))
|
|
341
|
+
: T.forecastEarly),
|
|
342
|
+
|
|
343
|
+
// 日柱
|
|
344
|
+
(data.days || []).length > 0
|
|
345
|
+
? h('div', { style: { padding: '10px 14px 0' } },
|
|
346
|
+
h('div', { style: { fontSize: 11, fontWeight: 600, color: C.t1, borderTop: '1px solid ' + C.hair, paddingTop: 8 } }, T.days),
|
|
347
|
+
h(Bar, { rows: data.days.slice(-7), max: maxDay }))
|
|
348
|
+
: null,
|
|
349
|
+
|
|
350
|
+
// 会话榜
|
|
351
|
+
(data.sessions || []).length > 0
|
|
352
|
+
? h('div', { style: { padding: '10px 14px 4px' } },
|
|
353
|
+
h('div', { style: { fontSize: 11, fontWeight: 600, color: C.t1, borderTop: '1px solid ' + C.hair, paddingTop: 8 } }, T.sessions),
|
|
354
|
+
data.sessions.slice(0, 5).map((item) => h('div', {
|
|
355
|
+
key: item.sid,
|
|
356
|
+
style: { display: 'flex', gap: 8, padding: '5px 0', alignItems: 'baseline' },
|
|
357
|
+
},
|
|
358
|
+
h('span', {
|
|
359
|
+
style: {
|
|
360
|
+
flex: 1, minWidth: 0, fontSize: 11.5, color: C.t2,
|
|
361
|
+
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
|
|
362
|
+
},
|
|
363
|
+
title: item.sid,
|
|
364
|
+
}, item.title || item.cwdName || item.sid.slice(0, 16)),
|
|
365
|
+
h('span', { style: { fontSize: 11, color: C.t4 } }, (item.calls ?? 0) + ''),
|
|
366
|
+
h('span', { style: { fontSize: 11.5, color: C.t1, fontVariantNumeric: 'tabular-nums' } },
|
|
367
|
+
money(item.amount, data.currency) || '—'),
|
|
368
|
+
)))
|
|
369
|
+
: null,
|
|
370
|
+
)
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const foot = h('div', {
|
|
374
|
+
style: { padding: '10px 14px 12px', fontSize: 10.5, lineHeight: 1.65, color: C.t4 },
|
|
375
|
+
}, '只记金额与次数,不记对话内容;配置在 ~/.dsh/ops/quota/policy.json,改完即生效')
|
|
376
|
+
|
|
377
|
+
return h('div', { style: { display: 'flex', flexDirection: 'column', minHeight: 0 } }, head, body, foot)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function makeTitle() {
|
|
381
|
+
return function Title() {
|
|
382
|
+
return h('span', { style: { fontSize: 12, fontWeight: 600, color: C.t1 } }, T.title)
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function apply(ctx) {
|
|
387
|
+
if (!ctx) return
|
|
388
|
+
T = DICT[detectLocale(ctx)] || DICT.zh
|
|
389
|
+
|
|
390
|
+
const tabs = getService(ctx, 'sidebarRightTabs')
|
|
391
|
+
const slots = getService(ctx, 'slots')
|
|
392
|
+
let disposers = []
|
|
393
|
+
|
|
394
|
+
if (tabs && typeof tabs.register === 'function') {
|
|
395
|
+
try {
|
|
396
|
+
disposers.push(tabs.register({
|
|
397
|
+
id: ID,
|
|
398
|
+
kind: KIND,
|
|
399
|
+
title: () => T.title,
|
|
400
|
+
priority: 'extension',
|
|
401
|
+
keepMounted: false,
|
|
402
|
+
guide: [{ id: 'quota.open', order: 50, title: () => T.title, description: () => T.guideDesc }],
|
|
403
|
+
}))
|
|
404
|
+
} catch (error) {
|
|
405
|
+
console.warn('[quota] 右栏 tab 登记失败:', error)
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (slots && typeof slots.inject === 'function' && typeof slots.register === 'function') {
|
|
410
|
+
try {
|
|
411
|
+
disposers.push(slots.inject('sidebar.right.pane.tab', () =>
|
|
412
|
+
slots.register({ name: 'sidebar.right.pane.tab', key: ID }, Panel)))
|
|
413
|
+
disposers.push(slots.inject('sidebar.right.pane.tab.title', () =>
|
|
414
|
+
slots.register({ name: 'sidebar.right.pane.tab.title', key: ID }, makeTitle())))
|
|
415
|
+
} catch (error) {
|
|
416
|
+
console.warn('[quota] 面板挂载失败:', error)
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const cleanup = () => {
|
|
421
|
+
for (const dispose of disposers) {
|
|
422
|
+
try {
|
|
423
|
+
dispose && dispose()
|
|
424
|
+
} catch {}
|
|
425
|
+
}
|
|
426
|
+
disposers = []
|
|
427
|
+
}
|
|
428
|
+
if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
|
|
429
|
+
else if (typeof ctx.on === 'function') ctx.on('dispose', cleanup)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
return {
|
|
433
|
+
inject: ['sidebarRightTabs'],
|
|
434
|
+
apply,
|
|
435
|
+
__test: { money, periodLabel, fillOf, detectLocale, DICT, apply },
|
|
436
|
+
}
|
|
437
|
+
},
|
|
438
|
+
})
|
package/lib/policy.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 预算策略:从 `~/.dsh/ops/quota/policy.json` 读,改完即生效,不重启。
|
|
3
|
+
*
|
|
4
|
+
* 原则:
|
|
5
|
+
* 1. **读不到就是没配预算**,不是错误。没配就没有任何拦截,用户不该被一个坏文件卡住;
|
|
6
|
+
* 2. 任何字段非法都退回默认值并回报 `warnings`,绝不因为拼错一个数字就整体失效;
|
|
7
|
+
* 3. 策略里不放凭据、不放路径白名单以外的东西。
|
|
8
|
+
*/
|
|
9
|
+
import { readFileSync } from 'node:fs'
|
|
10
|
+
import { homedir } from 'node:os'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
export const POLICY_SUBDIR = join('.dsh', 'ops', 'quota')
|
|
14
|
+
|
|
15
|
+
export function defaultPolicyPath() {
|
|
16
|
+
return join(process.env.DSH_HOME ?? homedir(), POLICY_SUBDIR, 'policy.json')
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const PERIODS = Object.freeze(['day', 'week', 'month'])
|
|
20
|
+
export const ACTIONS = Object.freeze(['notify', 'downgrade'])
|
|
21
|
+
|
|
22
|
+
export const DEFAULT_POLICY = Object.freeze({
|
|
23
|
+
v: 1,
|
|
24
|
+
currency: 'CNY',
|
|
25
|
+
budget: Object.freeze({ period: 'month', amount: null }),
|
|
26
|
+
thresholds: Object.freeze({ warn: 0.8, limit: 1 }),
|
|
27
|
+
action: Object.freeze({ atWarn: 'notify', atLimit: 'downgrade', downgradeModel: 'deepseek-v4-flash' }),
|
|
28
|
+
sessionCap: null,
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
function num(value) {
|
|
32
|
+
const n = Number(value)
|
|
33
|
+
return Number.isFinite(n) ? n : null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function pick(value, allowed, fallback) {
|
|
37
|
+
return allowed.includes(value) ? value : fallback
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 规范化任意输入(文件内容或手写对象)→ 完整策略 + 警告列表。
|
|
42
|
+
* 纯函数,便于断言;不读文件。
|
|
43
|
+
*/
|
|
44
|
+
export function normalizePolicy(raw) {
|
|
45
|
+
const warnings = []
|
|
46
|
+
const source = raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
|
47
|
+
if (Object.keys(source).length === 0) warnings.push('policy-empty')
|
|
48
|
+
|
|
49
|
+
const budget = source.budget !== null && typeof source.budget === 'object' ? source.budget : {}
|
|
50
|
+
const amount = num(budget.amount)
|
|
51
|
+
if (budget.amount !== undefined && budget.amount !== null && (amount === null || amount <= 0)) {
|
|
52
|
+
warnings.push('budget.amount 必须是正数,已按"未设置"处理')
|
|
53
|
+
}
|
|
54
|
+
const period = pick(budget.period, PERIODS, DEFAULT_POLICY.budget.period)
|
|
55
|
+
if (budget.period !== undefined && period !== budget.period) warnings.push(`budget.period 只支持 ${PERIODS.join(' / ')}`)
|
|
56
|
+
|
|
57
|
+
const thresholds = source.thresholds !== null && typeof source.thresholds === 'object' ? source.thresholds : {}
|
|
58
|
+
let warn = num(thresholds.warn) ?? DEFAULT_POLICY.thresholds.warn
|
|
59
|
+
let limit = num(thresholds.limit) ?? DEFAULT_POLICY.thresholds.limit
|
|
60
|
+
if (warn <= 0 || warn > 1) {
|
|
61
|
+
warnings.push('thresholds.warn 必须在 (0,1],已用默认 0.8')
|
|
62
|
+
warn = DEFAULT_POLICY.thresholds.warn
|
|
63
|
+
}
|
|
64
|
+
if (limit < 1) {
|
|
65
|
+
warnings.push('thresholds.limit 不能小于 1,已用默认 1')
|
|
66
|
+
limit = DEFAULT_POLICY.thresholds.limit
|
|
67
|
+
}
|
|
68
|
+
if (warn >= limit) {
|
|
69
|
+
warnings.push('thresholds.warn 必须小于 limit,已按 0.8 / 1 处理')
|
|
70
|
+
warn = DEFAULT_POLICY.thresholds.warn
|
|
71
|
+
limit = DEFAULT_POLICY.thresholds.limit
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const action = source.action !== null && typeof source.action === 'object' ? source.action : {}
|
|
75
|
+
const atWarn = pick(action.atWarn, ACTIONS, DEFAULT_POLICY.action.atWarn)
|
|
76
|
+
const atLimit = pick(action.atLimit, ACTIONS, DEFAULT_POLICY.action.atLimit)
|
|
77
|
+
if (action.atLimit !== undefined && atLimit !== action.atLimit) warnings.push(`action.atLimit 只支持 ${ACTIONS.join(' / ')}`)
|
|
78
|
+
const downgradeModel = typeof action.downgradeModel === 'string' && action.downgradeModel.length > 0
|
|
79
|
+
? action.downgradeModel
|
|
80
|
+
: DEFAULT_POLICY.action.downgradeModel
|
|
81
|
+
|
|
82
|
+
const sessionCap = num(source.sessionCap)
|
|
83
|
+
if (source.sessionCap !== undefined && source.sessionCap !== null && (sessionCap === null || sessionCap <= 0)) {
|
|
84
|
+
warnings.push('sessionCap 必须是正数,已按"未设置"处理')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
policy: {
|
|
89
|
+
v: 1,
|
|
90
|
+
currency: typeof source.currency === 'string' && source.currency.length > 0 ? source.currency : DEFAULT_POLICY.currency,
|
|
91
|
+
budget: { period, amount: amount !== null && amount > 0 ? amount : null },
|
|
92
|
+
thresholds: { warn, limit },
|
|
93
|
+
action: { atWarn, atLimit, downgradeModel },
|
|
94
|
+
sessionCap: sessionCap !== null && sessionCap > 0 ? sessionCap : null,
|
|
95
|
+
},
|
|
96
|
+
warnings,
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 读文件;不存在/坏 JSON 都退回默认策略,并把原因放进 warnings。 */
|
|
101
|
+
export function loadPolicy(options = {}) {
|
|
102
|
+
const path = options.path ?? defaultPolicyPath()
|
|
103
|
+
let text
|
|
104
|
+
try {
|
|
105
|
+
text = readFileSync(path, 'utf8')
|
|
106
|
+
} catch (error) {
|
|
107
|
+
const missing = error && error.code === 'ENOENT'
|
|
108
|
+
const { policy, warnings } = normalizePolicy(null)
|
|
109
|
+
return { policy, warnings: missing ? [] : [`读取策略失败:${error?.message ?? error}`], path, exists: false }
|
|
110
|
+
}
|
|
111
|
+
let parsed
|
|
112
|
+
try {
|
|
113
|
+
parsed = JSON.parse(text)
|
|
114
|
+
} catch (error) {
|
|
115
|
+
const { policy } = normalizePolicy(null)
|
|
116
|
+
return { policy, warnings: [`policy.json 不是合法 JSON:${error.message}`], path, exists: true }
|
|
117
|
+
}
|
|
118
|
+
const { policy, warnings } = normalizePolicy(parsed)
|
|
119
|
+
return { policy, warnings, path, exists: true }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 预算是否可用:没设金额就等于"没开预算",此时任何拦截都不该发生。 */
|
|
123
|
+
export function budgetArmed(policy) {
|
|
124
|
+
return Boolean(policy && policy.budget && Number.isFinite(policy.budget.amount) && policy.budget.amount > 0)
|
|
125
|
+
}
|