@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/lib/book.js ADDED
@@ -0,0 +1,290 @@
1
+ /**
2
+ * 航油的账:**周期预算**的累计与预测。
3
+ *
4
+ * 与黑匣子的分工:
5
+ * - 黑匣子回答"这一次会话每一步花了多少"(明细,按会话);
6
+ * - 航油回答"这个周期还能花多少"(汇总,按天/周/月,跨会话)。
7
+ *
8
+ * 三个设计取舍:
9
+ * 1. 状态是**快照文件**,不是流水:一次写一个 JSON,避免每次调用都追加磁盘;
10
+ * 2. 跨周期自动滚动:换月/换日时把旧总量清零,只保留按天桶(供趋势与预测);
11
+ * 3. 金额未知的调用单独计数,**不摊进合计**——合计偏低必须能被看见。
12
+ */
13
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
14
+ import { dirname, join } from 'node:path'
15
+ import { homedir } from 'node:os'
16
+
17
+ export const QUOTA_SUBDIR = join('.dsh', 'ops', 'quota')
18
+
19
+ export function defaultStatePath() {
20
+ return join(process.env.DSH_HOME ?? homedir(), QUOTA_SUBDIR, 'state.json')
21
+ }
22
+
23
+ const DAY = 86400000
24
+
25
+ /** 周期起止:本地时区为界,用户看到的"今天/本月"就是本地今天/本月。 */
26
+ export function periodRangeOf(period, now = Date.now()) {
27
+ const date = new Date(now)
28
+ if (period === 'day') {
29
+ const start = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
30
+ return { key: dayKeyOf(start), start, end: start + DAY }
31
+ }
32
+ if (period === 'week') {
33
+ const weekday = (date.getDay() + 6) % 7 // 周一为一周开始
34
+ const start = new Date(date.getFullYear(), date.getMonth(), date.getDate() - weekday).getTime()
35
+ return { key: `W${dayKeyOf(start)}`, start, end: start + 7 * DAY }
36
+ }
37
+ const start = new Date(date.getFullYear(), date.getMonth(), 1).getTime()
38
+ const end = new Date(date.getFullYear(), date.getMonth() + 1, 1).getTime()
39
+ return { key: dayKeyOf(start).slice(0, 7), start, end }
40
+ }
41
+
42
+ export function dayKeyOf(at) {
43
+ const d = new Date(at)
44
+ const month = String(d.getMonth() + 1).padStart(2, '0')
45
+ const day = String(d.getDate()).padStart(2, '0')
46
+ return `${d.getFullYear()}-${month}-${day}`
47
+ }
48
+
49
+ function round6(value) {
50
+ return Math.round(value * 1e6) / 1e6
51
+ }
52
+
53
+ function emptyTotal(currency = 'CNY') {
54
+ return { amount: 0, currency, calls: 0, unknown: 0 }
55
+ }
56
+
57
+ function emptyState(period, now, currency) {
58
+ const range = periodRangeOf(period, now)
59
+ return {
60
+ v: 1,
61
+ currency,
62
+ period: { kind: period, key: range.key, start: range.start, end: range.end },
63
+ total: emptyTotal(currency),
64
+ buckets: {},
65
+ sessions: {},
66
+ saved: { amount: 0, currency },
67
+ meta: { updatedAt: now, events: 0, deduped: 0, rolledOverAt: null },
68
+ }
69
+ }
70
+
71
+ /**
72
+ * @param {{statePath?: string, period?: string, currency?: string, now?: () => number,
73
+ * retentionDays?: number, flushMs?: number, maxSeen?: number, maxSessions?: number}} options
74
+ */
75
+ export function createBook(options = {}) {
76
+ const statePath = options.statePath ?? defaultStatePath()
77
+ const now = options.now ?? (() => Date.now())
78
+ const retentionDays = options.retentionDays ?? 120
79
+ const flushMs = options.flushMs ?? 400
80
+ const maxSeen = options.maxSeen ?? 20000
81
+ const maxSessions = options.maxSessions ?? 500
82
+
83
+ let period = options.period ?? 'month'
84
+ let currency = options.currency ?? 'CNY'
85
+ let state = emptyState(period, now(), currency)
86
+ const seen = new Set()
87
+ let dirty = false
88
+ let timer = null
89
+
90
+ function load() {
91
+ let text
92
+ try {
93
+ text = readFileSync(statePath, 'utf8')
94
+ } catch {
95
+ return
96
+ }
97
+ try {
98
+ const parsed = JSON.parse(text)
99
+ if (!parsed || parsed.v !== 1) return
100
+ state = parsed
101
+ period = parsed?.period?.kind ?? period
102
+ currency = parsed?.currency ?? currency
103
+ // 结构性兜底:缺失的分支补空,不让一个旧文件把后续计算变成 NaN
104
+ state.total = state.total ?? emptyTotal(currency)
105
+ state.buckets = state.buckets ?? {}
106
+ state.sessions = state.sessions ?? {}
107
+ state.saved = state.saved ?? { amount: 0, currency }
108
+ state.meta = state.meta ?? { updatedAt: now(), events: 0, deduped: 0 }
109
+ } catch {
110
+ /* 坏文件当没有:宁可丢历史统计,也不能让插件启动失败 */
111
+ }
112
+ }
113
+
114
+ function rollover() {
115
+ const range = periodRangeOf(period, now())
116
+ if (state.period?.key === range.key) return false
117
+ const previous = state.period?.key ?? null
118
+ state.period = { kind: period, key: range.key, start: range.start, end: range.end }
119
+ state.total = emptyTotal(currency)
120
+ state.sessions = {}
121
+ state.saved = { amount: 0, currency }
122
+ state.meta = { ...(state.meta ?? {}), rolledOverAt: previous }
123
+ dirty = true
124
+ return true
125
+ }
126
+
127
+ function prune() {
128
+ const cutoff = now() - retentionDays * DAY
129
+ for (const [key, bucket] of Object.entries(state.buckets)) {
130
+ const at = Date.parse(`${key}T00:00:00`)
131
+ if (Number.isFinite(at) && at < cutoff) delete state.buckets[key]
132
+ }
133
+ }
134
+
135
+ function scheduleFlush() {
136
+ dirty = true
137
+ if (flushMs <= 0) return flush()
138
+ if (timer !== null) return
139
+ timer = setTimeout(() => {
140
+ timer = null
141
+ flush()
142
+ }, flushMs)
143
+ if (typeof timer.unref === 'function') timer.unref()
144
+ }
145
+
146
+ function flush() {
147
+ if (!dirty) return false
148
+ try {
149
+ mkdirSync(dirname(statePath), { recursive: true })
150
+ state.meta.updatedAt = now()
151
+ const text = JSON.stringify(state)
152
+ const tmp = `${statePath}.tmp`
153
+ writeFileSync(tmp, text, 'utf8')
154
+ renameSync(tmp, statePath)
155
+ dirty = false
156
+ return true
157
+ } catch {
158
+ /* 写失败:保留 dirty,下次再试。绝不让采集路径抛错。 */
159
+ return false
160
+ }
161
+ }
162
+
163
+ /**
164
+ * 记一次调用。
165
+ * 去重键含事件时间:同一次调用的重复投递时间相同会被折叠,
166
+ * 而同轮同步的两个请求时间不同,必须各记一笔。
167
+ * @returns {{added:boolean, total:object, overLimit:boolean, unknown:boolean}}
168
+ */
169
+ function add(sid, spend) {
170
+ const at = now()
171
+ rollover()
172
+ state.meta.events += 1
173
+
174
+ const key = [sid ?? '', spend?.turn ?? '', spend?.step ?? '', spend?.at ?? ''].join('|')
175
+ if (seen.has(key)) {
176
+ state.meta.deduped += 1
177
+ scheduleFlush()
178
+ return { added: false, total: state.total, overLimit: false, unknown: false }
179
+ }
180
+ if (seen.size > maxSeen) seen.clear()
181
+ seen.add(key)
182
+
183
+ const dayKey = dayKeyOf(at)
184
+ state.buckets[dayKey] = state.buckets[dayKey] ?? { amount: 0, calls: 0, unknown: 0, currency }
185
+
186
+ const amount = spend?.amount
187
+ const unknown = !(typeof amount === 'number' && Number.isFinite(amount))
188
+
189
+ state.total.calls += 1
190
+ state.buckets[dayKey].calls += 1
191
+ if (unknown) {
192
+ state.total.unknown += 1
193
+ state.buckets[dayKey].unknown += 1
194
+ } else {
195
+ state.total.amount = round6(state.total.amount + amount)
196
+ state.buckets[dayKey].amount = round6(state.buckets[dayKey].amount + amount)
197
+ if (Number.isFinite(spend?.saved) && spend.saved > 0) {
198
+ state.saved.amount = round6((state.saved.amount ?? 0) + spend.saved)
199
+ }
200
+ }
201
+
202
+ if (typeof sid === 'string' && sid.length > 0) {
203
+ const entry = state.sessions[sid] ?? { amount: 0, calls: 0, unknown: 0, lastAt: null, cwdName: null }
204
+ entry.calls += 1
205
+ entry.lastAt = at
206
+ if (unknown) entry.unknown += 1
207
+ else entry.amount = round6(entry.amount + amount)
208
+ state.sessions[sid] = entry
209
+ const ids = Object.keys(state.sessions)
210
+ if (ids.length > maxSessions) {
211
+ ids.sort((a, b) => (state.sessions[a].lastAt ?? 0) - (state.sessions[b].lastAt ?? 0))
212
+ for (const drop of ids.slice(0, ids.length - maxSessions)) delete state.sessions[drop]
213
+ }
214
+ }
215
+
216
+ prune()
217
+ scheduleFlush()
218
+ return { added: true, total: state.total, unknown, overLimit: false }
219
+ }
220
+
221
+ /** 会话的工作区名与标题:只留目录名,不留绝对路径。 */
222
+ function annotate(sid, { cwdName, title } = {}) {
223
+ const entry = state.sessions[sid]
224
+ if (!entry) return
225
+ if (cwdName && !entry.cwdName) entry.cwdName = cwdName
226
+ if (title && !entry.title) entry.title = title
227
+ dirty = true
228
+ }
229
+
230
+ /**
231
+ * 只读视图:面板与 API 唯一入口。
232
+ * 预测只在"已过足够时间"时给:周期刚开始时按 1 小时用量外推是误导。
233
+ */
234
+ function snapshot(policy) {
235
+ rollover()
236
+ const range = periodRangeOf(period, now())
237
+ const at = now()
238
+ const elapsed = Math.max(0, at - range.start)
239
+ const duration = Math.max(1, range.end - range.start)
240
+ const elapsedRatio = Math.min(1, elapsed / duration)
241
+ const spent = state.total.amount ?? 0
242
+ const limit = policy?.budget?.amount ?? null
243
+ const ratio = Number.isFinite(limit) && limit > 0 ? spent / limit : null
244
+
245
+ // 前 3% 的时间不外推:一天里第一个小时估整月必然离谱
246
+ const canForecast = elapsedRatio > 0.03
247
+ const forecast = canForecast
248
+ ? {
249
+ projected: round6(spent / elapsedRatio),
250
+ daysLeft: Math.max(0, Math.round((range.end - at) / DAY)),
251
+ dailyRate: round6(spent / Math.max(1, elapsed / DAY)),
252
+ }
253
+ : null
254
+
255
+ const days = Object.entries(state.buckets)
256
+ .filter(([key]) => key >= dayKeyOf(range.start))
257
+ .sort((a, b) => (a[0] < b[0] ? -1 : 1))
258
+ .map(([key, bucket]) => ({ day: key, ...bucket }))
259
+
260
+ return {
261
+ v: 1,
262
+ currency: state.currency,
263
+ period: { ...state.period, kind: period, key: range.key, start: range.start, end: range.end },
264
+ total: { ...state.total, currency: state.currency },
265
+ saved: { ...state.saved, currency: state.currency },
266
+ limit: Number.isFinite(limit) ? limit : null,
267
+ ratio,
268
+ remaining: Number.isFinite(limit) ? round6(Math.max(0, limit - spent)) : null,
269
+ forecast,
270
+ days,
271
+ sessions: Object.entries(state.sessions)
272
+ .map(([sid, entry]) => ({ sid, ...entry }))
273
+ .sort((a, b) => (b.lastAt ?? 0) - (a.lastAt ?? 0))
274
+ .slice(0, 20),
275
+ meta: { ...state.meta, now: at, statePath },
276
+ }
277
+ }
278
+
279
+ function close() {
280
+ if (timer !== null) {
281
+ clearTimeout(timer)
282
+ timer = null
283
+ }
284
+ flush()
285
+ }
286
+
287
+ load()
288
+ rollover()
289
+ return { add, annotate, snapshot, flush, close, statePath, setPeriod: (value) => { period = value; rollover() } }
290
+ }
package/lib/breaker.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 熔断开关:把"花了多少"翻译成"这一档该做什么"。
3
+ *
4
+ * 为什么要有回滞(hysteresis):
5
+ * 没有它,用量在阈值附近抖动时,用户每次请求都会收到一次警告,
6
+ * 或者模型在 flash / pro 之间来回跳——比不做还烦人。
7
+ * 规则:升档立即生效,降档要落到阈值的 90% 以下才算真的退回来。
8
+ */
9
+
10
+ export const LEVEL_NONE = 'none'
11
+ export const LEVEL_WARN = 'warn'
12
+ export const LEVEL_LIMIT = 'limit'
13
+
14
+ /**
15
+ * 纯函数:给定比值与阈值,返回它落在哪一档(不考虑回滞)。
16
+ */
17
+ export function rawLevelOf(ratio, thresholds) {
18
+ if (!Number.isFinite(ratio)) return LEVEL_NONE
19
+ const warn = thresholds?.warn ?? 0.8
20
+ const limit = thresholds?.limit ?? 1
21
+ if (ratio >= limit) return LEVEL_LIMIT
22
+ if (ratio >= warn) return LEVEL_WARN
23
+ return LEVEL_NONE
24
+ }
25
+
26
+ const ORDER = { none: 0, warn: 1, limit: 2 }
27
+
28
+ /**
29
+ * 带状态机:>= 阈值立即升档;退回需要 ratio 低于「该档阈值 × 0.9」。
30
+ */
31
+ export function createBreaker({ warn = 0.8, limit = 1, hysteresis = 0.9 } = {}) {
32
+ const thresholds = { warn, limit }
33
+ let level = LEVEL_NONE
34
+
35
+ function update(ratio) {
36
+ const raw = rawLevelOf(ratio, thresholds)
37
+ if (ORDER[raw] >= ORDER[level]) {
38
+ level = raw
39
+ return level
40
+ }
41
+ // 想降档:必须确实落在目标档位阈值之下足够远
42
+ const bound = level === LEVEL_LIMIT ? limit : warn
43
+ if (Number.isFinite(ratio) && ratio < bound * hysteresis) {
44
+ level = raw
45
+ }
46
+ return level
47
+ }
48
+
49
+ return {
50
+ level: () => level,
51
+ update,
52
+ /** 会话切换、策略改动、周期滚动后都要清一次,否则旧的"已告警"状态会粘住。 */
53
+ reset: () => {
54
+ level = LEVEL_NONE
55
+ },
56
+ thresholds,
57
+ }
58
+ }
59
+
60
+ /**
61
+ * 决定这一档要做什么:只有 warn 档可选通知,limit 档可选降级。
62
+ * 返回 null 表示"不动"。
63
+ */
64
+ export function actionOf(level, policy) {
65
+ if (level === LEVEL_NONE || !policy) return null
66
+ const action = policy.action ?? {}
67
+ // 没写清策略时保守:只提醒,绝不擅自把用户的模型换掉。
68
+ const atWarn = action.atWarn ?? 'notify'
69
+ const atLimit = action.atLimit ?? 'notify'
70
+ if (level === LEVEL_WARN) {
71
+ return atWarn === 'notify' ? { kind: 'warn', level } : null
72
+ }
73
+ if (level === LEVEL_LIMIT) {
74
+ if (atLimit === 'downgrade') {
75
+ return { kind: 'downgrade', level, model: action.downgradeModel ?? null }
76
+ }
77
+ return atLimit === 'notify' ? { kind: 'warn', level } : null
78
+ }
79
+ return null
80
+ }