@lls-a1/dsh-balance-float 0.0.0-stage → 1.1.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -2
- package/client.js +1761 -0
- package/cordis.patch.yml +16 -0
- package/icon.svg +13 -0
- package/index.js +284 -0
- package/lib/ledger.js +180 -0
- package/lib/pricing.js +138 -0
- package/lib/snapshot.js +213 -0
- package/lib/tracker.js +203 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +50 -4
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# balance-float bundle patch.
|
|
2
|
+
#
|
|
3
|
+
# One row with two halves: the Host half (`exports["."]`) owns the local usage
|
|
4
|
+
# ledger (turn accounting + balance poll) and serves a read-only JSON snapshot
|
|
5
|
+
# from /balance-float/snapshot; the Client half (`exports["./client"]`, declared
|
|
6
|
+
# by `dsh.client` in package.json) renders the floating pill in `shell.overlay`.
|
|
7
|
+
#
|
|
8
|
+
# Every path is optional: an empty value resolves the usual locations.
|
|
9
|
+
- insert:
|
|
10
|
+
- id: balance-float
|
|
11
|
+
name: '@lls-a1/dsh-balance-float'
|
|
12
|
+
config:
|
|
13
|
+
storeFile: '' # 账本路径,默认 $DSH_HOME/balance-float/usage.json
|
|
14
|
+
legacyFile: '' # 首次运行的种子账本,默认 $DSH_HOME/.dshw-usage.json
|
|
15
|
+
refreshSeconds: 20 # 余额轮询间隔
|
|
16
|
+
apiKeyRef: DEEPSEEK_API_KEY
|
package/icon.svg
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Balance Float">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="dbf-bg" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#2f7dff"/>
|
|
5
|
+
<stop offset="1" stop-color="#16b39b"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
</defs>
|
|
8
|
+
<rect x="5" y="9" width="54" height="46" rx="13" fill="url(#dbf-bg)"/>
|
|
9
|
+
<path d="M14 33h8.5l4.2-10.2 5.4 20.2 4.1-12.1H50"
|
|
10
|
+
fill="none" stroke="#ffffff" stroke-width="3.4"
|
|
11
|
+
stroke-linecap="round" stroke-linejoin="round"/>
|
|
12
|
+
<circle cx="50" cy="22" r="3.2" fill="#ffffff" opacity="0.9"/>
|
|
13
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of the balance-float bundle.
|
|
3
|
+
*
|
|
4
|
+
* Owns the local usage ledger this widget shows:
|
|
5
|
+
*
|
|
6
|
+
* - folds every session's settled turns into per-model cost events (official
|
|
7
|
+
* CNY prices, peak/valley aware) and appends them to the ledger;
|
|
8
|
+
* - polls the balance endpoint of the configured DeepSeek credential and
|
|
9
|
+
* derives today's spend from the day's opening balance;
|
|
10
|
+
* - serves one read-only JSON snapshot on `/balance-float/snapshot` with the
|
|
11
|
+
* ledger, the current peak/valley window and the price table, so the pill and
|
|
12
|
+
* card agree with the Host clock.
|
|
13
|
+
*
|
|
14
|
+
* The route sits behind the Host's browser trust fence like every other
|
|
15
|
+
* browser-facing endpoint. No credential value ever leaves the Host process and
|
|
16
|
+
* nothing is logged about it.
|
|
17
|
+
*/
|
|
18
|
+
import { readFileSync, statSync } from 'node:fs'
|
|
19
|
+
import { loadState, resolvePaths, saveState } from './lib/ledger.js'
|
|
20
|
+
import { buildSnapshot } from './lib/snapshot.js'
|
|
21
|
+
import { createTracker } from './lib/tracker.js'
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* This package's own version, shown in the widget footer.
|
|
25
|
+
*
|
|
26
|
+
* Read lazily and cached by mtime: a host that is only reloaded rarely (or a
|
|
27
|
+
* hot-linked workspace) must not keep serving the version it saw at boot.
|
|
28
|
+
*/
|
|
29
|
+
let versionCache = { mtimeMs: -1, value: '' }
|
|
30
|
+
function packageVersion() {
|
|
31
|
+
try {
|
|
32
|
+
const file = new URL('./package.json', import.meta.url)
|
|
33
|
+
const stat = statSync(file)
|
|
34
|
+
if (stat.mtimeMs !== versionCache.mtimeMs) {
|
|
35
|
+
const pkg = JSON.parse(readFileSync(file, 'utf8'))
|
|
36
|
+
versionCache = { mtimeMs: stat.mtimeMs, value: typeof pkg.version === 'string' ? pkg.version : '' }
|
|
37
|
+
}
|
|
38
|
+
return versionCache.value
|
|
39
|
+
} catch {
|
|
40
|
+
return ''
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Compare two dotted versions: true when `a` is newer than `b`.
|
|
46
|
+
* Non-numeric parts are ignored so a pre-release tag never beats a release.
|
|
47
|
+
*/
|
|
48
|
+
function isNewer(a, b) {
|
|
49
|
+
const parse = (value) => String(value).replace(/^v/i, '').split('.').map((part) => Number.parseInt(part, 10) || 0)
|
|
50
|
+
const left = parse(a)
|
|
51
|
+
const right = parse(b)
|
|
52
|
+
for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
|
|
53
|
+
const x = left[i] ?? 0
|
|
54
|
+
const y = right[i] ?? 0
|
|
55
|
+
if (x !== y) return x > y
|
|
56
|
+
}
|
|
57
|
+
return false
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Cached check against the published package.json on the default branch. */
|
|
61
|
+
const UPDATE_TTL_MS = 5 * 60 * 1000
|
|
62
|
+
// Only the *published* version is cached; `current` is re-read every call so a
|
|
63
|
+
// locally bumped version never reports the value cached minutes ago.
|
|
64
|
+
let updateCache = { at: 0, latest: null }
|
|
65
|
+
|
|
66
|
+
async function checkUpdate({ fresh = false } = {}) {
|
|
67
|
+
const now = Date.now()
|
|
68
|
+
const current = packageVersion()
|
|
69
|
+
// A manual click must never be answered from the cache: the published version
|
|
70
|
+
// can change right after a silent check.
|
|
71
|
+
if (!fresh && updateCache.latest !== null && now - updateCache.at < UPDATE_TTL_MS) {
|
|
72
|
+
return { ok: true, current, latest: updateCache.latest, hasUpdate: isNewer(updateCache.latest, current) }
|
|
73
|
+
}
|
|
74
|
+
const controller = new AbortController()
|
|
75
|
+
const timer = setTimeout(() => controller.abort(), 10000)
|
|
76
|
+
try {
|
|
77
|
+
// api.github.com is reachable on hosts where raw.githubusercontent.com is
|
|
78
|
+
// not (and it needs no token for a public repo).
|
|
79
|
+
const response = await fetch(
|
|
80
|
+
'https://api.github.com/repos/ming-a1/dsh-balance-float/contents/package.json?ref=main',
|
|
81
|
+
{
|
|
82
|
+
signal: controller.signal,
|
|
83
|
+
headers: { accept: 'application/vnd.github.raw', 'user-agent': 'dsh-balance-float' },
|
|
84
|
+
},
|
|
85
|
+
)
|
|
86
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
87
|
+
const pkg = JSON.parse(await response.text())
|
|
88
|
+
const latest = typeof pkg?.version === 'string' ? pkg.version : ''
|
|
89
|
+
if (latest !== '') updateCache = { at: now, latest }
|
|
90
|
+
return { ok: true, current, latest, hasUpdate: latest !== '' && isNewer(latest, current) }
|
|
91
|
+
} catch (error) {
|
|
92
|
+
// Do not cache failures: the next click retries.
|
|
93
|
+
return { ok: false, current, latest: '', hasUpdate: false, error: error instanceof Error ? error.message : String(error) }
|
|
94
|
+
} finally {
|
|
95
|
+
clearTimeout(timer)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export const name = 'balance-float'
|
|
100
|
+
|
|
101
|
+
/** Services this plugin cannot work without (`credentials` is read optionally). */
|
|
102
|
+
export const inject = ['webServer', 'timer']
|
|
103
|
+
|
|
104
|
+
const ROUTE = '/balance-float/snapshot'
|
|
105
|
+
const ROUTE_UPDATE = '/balance-float/update'
|
|
106
|
+
const BALANCE_URL = 'https://api.deepseek.com/user/balance'
|
|
107
|
+
const BALANCE_TIMEOUT_MS = 8000
|
|
108
|
+
|
|
109
|
+
/** JSON response with the headers a same-origin poll expects. */
|
|
110
|
+
function respondJson(res, status, body) {
|
|
111
|
+
const text = JSON.stringify(body)
|
|
112
|
+
res.writeHead(status, {
|
|
113
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
114
|
+
'Content-Length': Buffer.byteLength(text),
|
|
115
|
+
'Cache-Control': 'no-store',
|
|
116
|
+
})
|
|
117
|
+
res.end(text)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** One usable number from a response field. */
|
|
121
|
+
function numeric(value) {
|
|
122
|
+
const n = Number(value)
|
|
123
|
+
return Number.isFinite(n) ? n : null
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Mount the ledger, the accounting listener, the balance poll and the route.
|
|
128
|
+
*
|
|
129
|
+
* @param ctx - plugin context.
|
|
130
|
+
* @param config - row config: `storeFile`, `legacyFile`, `refreshSeconds`, `apiKeyRef`.
|
|
131
|
+
*/
|
|
132
|
+
export function apply(ctx, config) {
|
|
133
|
+
const paths = resolvePaths(config)
|
|
134
|
+
const loaded = loadState(config)
|
|
135
|
+
const refreshSeconds = Number.isFinite(config?.refreshSeconds) ? Math.max(5, Math.floor(config.refreshSeconds)) : 20
|
|
136
|
+
const apiKeyRef =
|
|
137
|
+
typeof config?.apiKeyRef === 'string' && config.apiKeyRef.trim() !== '' ? config.apiKeyRef.trim() : 'DEEPSEEK_API_KEY'
|
|
138
|
+
|
|
139
|
+
let pollTimer = null
|
|
140
|
+
let polling = false
|
|
141
|
+
|
|
142
|
+
const tracker = createTracker({
|
|
143
|
+
state: loaded.state,
|
|
144
|
+
storePath: paths.store,
|
|
145
|
+
logger: ctx.logger,
|
|
146
|
+
onTurn: () => schedulePoll(1500),
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
// Materialize the ledger right away: on a first run this persists the seed
|
|
150
|
+
// copied from the legacy ledger, so the widget starts from known values.
|
|
151
|
+
saveState(paths.store, tracker.state)
|
|
152
|
+
const seededAt = Date.now()
|
|
153
|
+
|
|
154
|
+
/** Read the configured credential and refresh the balance. */
|
|
155
|
+
async function pollBalance() {
|
|
156
|
+
if (polling) return
|
|
157
|
+
polling = true
|
|
158
|
+
try {
|
|
159
|
+
const credentials = ctx.get('credentials')
|
|
160
|
+
if (!credentials || typeof credentials.resolve !== 'function') return
|
|
161
|
+
let credential
|
|
162
|
+
try {
|
|
163
|
+
credential = await credentials.resolve(apiKeyRef)
|
|
164
|
+
} catch {
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
const token = credential && typeof credential.value === 'string' ? credential.value : ''
|
|
168
|
+
if (token === '') return
|
|
169
|
+
const response = await fetch(BALANCE_URL, {
|
|
170
|
+
headers: { Authorization: 'Bearer ' + token, Accept: 'application/json' },
|
|
171
|
+
signal: AbortSignal.timeout(BALANCE_TIMEOUT_MS),
|
|
172
|
+
})
|
|
173
|
+
if (!response.ok) return
|
|
174
|
+
const payload = await response.json()
|
|
175
|
+
const infos = Array.isArray(payload?.balance_infos) ? payload.balance_infos : []
|
|
176
|
+
const info = infos.find((entry) => String(entry?.currency || '').toUpperCase() === 'CNY') || infos[0]
|
|
177
|
+
const total = numeric(info?.total_balance)
|
|
178
|
+
if (total === null) return
|
|
179
|
+
tracker.applyBalance(total, 'apikey')
|
|
180
|
+
} catch (error) {
|
|
181
|
+
ctx.logger?.debug?.(`balance-float: balance poll failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
182
|
+
} finally {
|
|
183
|
+
polling = false
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Poll again soon, collapsing several turns into one request. */
|
|
188
|
+
function schedulePoll(delay) {
|
|
189
|
+
if (pollTimer !== null) return
|
|
190
|
+
pollTimer = setTimeout(() => {
|
|
191
|
+
pollTimer = null
|
|
192
|
+
void pollBalance()
|
|
193
|
+
}, delay)
|
|
194
|
+
if (typeof pollTimer.unref === 'function') pollTimer.unref()
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
ctx.effect(
|
|
198
|
+
() =>
|
|
199
|
+
ctx.on('session/event', (session, event) => {
|
|
200
|
+
try {
|
|
201
|
+
tracker.handleEvent(session, event)
|
|
202
|
+
} catch (error) {
|
|
203
|
+
ctx.logger?.warn?.(`balance-float: turn accounting failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
204
|
+
}
|
|
205
|
+
}),
|
|
206
|
+
'balance-float: turn accounting',
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
ctx.effect(() => ctx.timer.interval(() => void pollBalance(), refreshSeconds * 1000), 'balance-float: balance poll')
|
|
210
|
+
|
|
211
|
+
ctx.effect(
|
|
212
|
+
() => () => {
|
|
213
|
+
if (pollTimer !== null) {
|
|
214
|
+
clearTimeout(pollTimer)
|
|
215
|
+
pollTimer = null
|
|
216
|
+
}
|
|
217
|
+
tracker.dispose()
|
|
218
|
+
},
|
|
219
|
+
'balance-float: ledger flush',
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
ctx.effect(
|
|
223
|
+
() =>
|
|
224
|
+
ctx.webServer.register({
|
|
225
|
+
kind: 'exact',
|
|
226
|
+
path: ROUTE,
|
|
227
|
+
handler: (req, res) => {
|
|
228
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
229
|
+
respondJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
230
|
+
return
|
|
231
|
+
}
|
|
232
|
+
const rejection = ctx.get('connection')?.requestRejection?.({ headers: req.headers })
|
|
233
|
+
if (rejection !== undefined) {
|
|
234
|
+
respondJson(res, rejection === 401 ? 401 : 403, { ok: false, error: 'forbidden' })
|
|
235
|
+
return
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
const snapshot = buildSnapshot({
|
|
239
|
+
ledger: tracker.state,
|
|
240
|
+
sourcePath: paths.store,
|
|
241
|
+
mtimeMs: tracker.lastSavedAt > 0 ? tracker.lastSavedAt : seededAt,
|
|
242
|
+
serverNow: Date.now(),
|
|
243
|
+
version: packageVersion(),
|
|
244
|
+
})
|
|
245
|
+
respondJson(res, 200, snapshot)
|
|
246
|
+
} catch (error) {
|
|
247
|
+
ctx.logger?.warn?.(`balance-float: snapshot failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
248
|
+
respondJson(res, 500, { ok: false, error: 'snapshot failed' })
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
}),
|
|
252
|
+
'balance-float: snapshot route',
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
ctx.effect(
|
|
256
|
+
() =>
|
|
257
|
+
ctx.webServer.register({
|
|
258
|
+
kind: 'exact',
|
|
259
|
+
path: ROUTE_UPDATE,
|
|
260
|
+
handler: async (req, res) => {
|
|
261
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
262
|
+
respondJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
const rejection = ctx.get('connection')?.requestRejection?.({ headers: req.headers })
|
|
266
|
+
if (rejection !== undefined) {
|
|
267
|
+
respondJson(res, rejection === 401 ? 401 : 403, { ok: false, error: 'forbidden' })
|
|
268
|
+
return
|
|
269
|
+
}
|
|
270
|
+
try {
|
|
271
|
+
const fresh = new URL(req.url ?? '/', 'http://localhost').searchParams.get('fresh') === '1'
|
|
272
|
+
respondJson(res, 200, await checkUpdate({ fresh }))
|
|
273
|
+
} catch (error) {
|
|
274
|
+
ctx.logger?.warn?.(`balance-float: update check failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
275
|
+
respondJson(res, 500, { ok: false, error: 'update check failed' })
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
}),
|
|
279
|
+
'balance-float: update route',
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
// First reading right after activation; the interval below covers the rest.
|
|
283
|
+
schedulePoll(1200)
|
|
284
|
+
}
|
package/lib/ledger.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local usage ledger owned by this plugin.
|
|
3
|
+
*
|
|
4
|
+
* The widget used to read the ledger another balance widget maintained. It now
|
|
5
|
+
* owns the file: the Host half appends one event per settled turn, refreshes
|
|
6
|
+
* the balance from the configured DeepSeek credential, and persists atomically
|
|
7
|
+
* under `$DSH_HOME/balance-float/usage.json`.
|
|
8
|
+
*
|
|
9
|
+
* On first run it seeds itself from a legacy ledger when one exists, so the
|
|
10
|
+
* shown balance/today/history do not jump on the takeover.
|
|
11
|
+
*/
|
|
12
|
+
import fs from 'node:fs'
|
|
13
|
+
import os from 'node:os'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import { LEGACY_UNIT, beijingDay } from './pricing.js'
|
|
16
|
+
|
|
17
|
+
/** Keep the ledger bounded; the widget only shows the last 7 days anyway. */
|
|
18
|
+
const MAX_EVENTS = 1200
|
|
19
|
+
|
|
20
|
+
/** DSH home, with the documented fallback when the env var is absent. */
|
|
21
|
+
function dshHome() {
|
|
22
|
+
return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Resolve the store file and the legacy ledger path.
|
|
27
|
+
*
|
|
28
|
+
* @param config - raw row config (`storeFile` / `legacyFile` overrides).
|
|
29
|
+
* @returns `{ store, legacy }` absolute paths.
|
|
30
|
+
*/
|
|
31
|
+
export function resolvePaths(config) {
|
|
32
|
+
const configuredStore = typeof config?.storeFile === 'string' ? config.storeFile.trim() : ''
|
|
33
|
+
const configuredLegacy = typeof config?.legacyFile === 'string' ? config.legacyFile.trim() : ''
|
|
34
|
+
return {
|
|
35
|
+
store: configuredStore !== '' ? path.resolve(configuredStore) : path.join(dshHome(), 'balance-float', 'usage.json'),
|
|
36
|
+
legacy: configuredLegacy !== '' ? path.resolve(configuredLegacy) : path.join(dshHome(), '.dshw-usage.json'),
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Parse one JSON file; null when missing or unreadable. */
|
|
41
|
+
function readJson(file) {
|
|
42
|
+
try {
|
|
43
|
+
const stat = fs.statSync(file)
|
|
44
|
+
if (!stat.isFile()) return null
|
|
45
|
+
const data = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
46
|
+
return data !== null && typeof data === 'object' ? { data, mtimeMs: stat.mtimeMs } : null
|
|
47
|
+
} catch {
|
|
48
|
+
return null
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A fresh ledger for one Beijing day. */
|
|
53
|
+
export function emptyState(day = beijingDay()) {
|
|
54
|
+
return {
|
|
55
|
+
version: 1,
|
|
56
|
+
date: day,
|
|
57
|
+
dayStart: null,
|
|
58
|
+
lastBalance: null,
|
|
59
|
+
todayUsage: 0,
|
|
60
|
+
history: {},
|
|
61
|
+
events: [],
|
|
62
|
+
balanceSource: null,
|
|
63
|
+
balanceAt: null,
|
|
64
|
+
updatedAt: new Date().toISOString(),
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Finite number or null. */
|
|
69
|
+
function numOrNull(value) {
|
|
70
|
+
const n = Number(value)
|
|
71
|
+
return Number.isFinite(n) ? n : null
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Convert a legacy balance-widget ledger into this plugin's shape.
|
|
76
|
+
*
|
|
77
|
+
* @param legacy - parsed legacy ledger.
|
|
78
|
+
* @param now - epoch milliseconds.
|
|
79
|
+
*/
|
|
80
|
+
export function seedFromLegacy(legacy, now = Date.now()) {
|
|
81
|
+
const day = beijingDay(now)
|
|
82
|
+
const state = emptyState(day)
|
|
83
|
+
if (legacy === null || typeof legacy !== 'object') return state
|
|
84
|
+
|
|
85
|
+
state.date = typeof legacy.date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(legacy.date) ? legacy.date : day
|
|
86
|
+
state.dayStart = numOrNull(legacy.dayStart)
|
|
87
|
+
state.lastBalance = numOrNull(legacy.lastBalance)
|
|
88
|
+
if (state.lastBalance === null) {
|
|
89
|
+
// Legacy accounting stores 1e-8 units; the newest day's closing balance is
|
|
90
|
+
// the last usable value when `lastBalance` is absent.
|
|
91
|
+
const book = legacy.accounting?.books?.[legacy.accounting?.active]
|
|
92
|
+
const days = book?.days && typeof book.days === 'object' ? Object.keys(book.days).sort() : []
|
|
93
|
+
const last = days.length > 0 ? book.days[days[days.length - 1]] : null
|
|
94
|
+
const units = numOrNull(last?.lastUnits)
|
|
95
|
+
if (units !== null) state.lastBalance = units / LEGACY_UNIT
|
|
96
|
+
}
|
|
97
|
+
state.todayUsage = Math.max(0, numOrNull(legacy.todayUsage) ?? 0)
|
|
98
|
+
if (legacy.history !== null && typeof legacy.history === 'object') {
|
|
99
|
+
for (const key of Object.keys(legacy.history)) {
|
|
100
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(key)) continue
|
|
101
|
+
const value = numOrNull(legacy.history[key])
|
|
102
|
+
if (value !== null) state.history[key] = value
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const events = Array.isArray(legacy.events) ? legacy.events : []
|
|
106
|
+
state.events = events
|
|
107
|
+
.filter((event) => event !== null && typeof event === 'object')
|
|
108
|
+
.map((event) => ({
|
|
109
|
+
ts: numOrNull(event.ts) ?? 0,
|
|
110
|
+
day: typeof event.day === 'string' ? event.day : day,
|
|
111
|
+
model: String(event.model || 'unknown'),
|
|
112
|
+
cost: Math.max(0, numOrNull(event.cost) ?? 0),
|
|
113
|
+
tokens: Math.max(0, numOrNull(event.tokens) ?? 0),
|
|
114
|
+
}))
|
|
115
|
+
.filter((event) => event.ts > 0)
|
|
116
|
+
.sort((a, b) => a.ts - b.ts)
|
|
117
|
+
.slice(-MAX_EVENTS)
|
|
118
|
+
if (state.history[day] === undefined) state.history[day] = state.todayUsage
|
|
119
|
+
state.balanceSource = 'ledger'
|
|
120
|
+
state.balanceAt = now
|
|
121
|
+
return state
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Guard a stored ledger against partial/corrupt content. */
|
|
125
|
+
function normalize(state, now) {
|
|
126
|
+
const base = emptyState(beijingDay(now))
|
|
127
|
+
if (state === null || typeof state !== 'object') return base
|
|
128
|
+
const merged = { ...base, ...state }
|
|
129
|
+
merged.version = 1
|
|
130
|
+
merged.date = typeof merged.date === 'string' ? merged.date : base.date
|
|
131
|
+
merged.dayStart = numOrNull(merged.dayStart)
|
|
132
|
+
merged.lastBalance = numOrNull(merged.lastBalance)
|
|
133
|
+
merged.todayUsage = Math.max(0, numOrNull(merged.todayUsage) ?? 0)
|
|
134
|
+
merged.history = merged.history !== null && typeof merged.history === 'object' ? merged.history : {}
|
|
135
|
+
merged.events = Array.isArray(merged.events) ? merged.events.slice(-MAX_EVENTS) : []
|
|
136
|
+
merged.balanceAt = numOrNull(merged.balanceAt)
|
|
137
|
+
return merged
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Load the plugin's own ledger, or seed from the legacy one.
|
|
142
|
+
*
|
|
143
|
+
* @param config - raw row config.
|
|
144
|
+
* @param now - epoch milliseconds.
|
|
145
|
+
* @returns `{ state, path, mtimeMs, seeded }`.
|
|
146
|
+
*/
|
|
147
|
+
export function loadState(config, now = Date.now()) {
|
|
148
|
+
const { store, legacy } = resolvePaths(config)
|
|
149
|
+
const own = readJson(store)
|
|
150
|
+
if (own !== null) {
|
|
151
|
+
return { state: normalize(own.data, now), path: store, mtimeMs: own.mtimeMs, seeded: false }
|
|
152
|
+
}
|
|
153
|
+
const old = readJson(legacy)
|
|
154
|
+
if (old !== null) {
|
|
155
|
+
const seeded = seedFromLegacy(old.data, now)
|
|
156
|
+
return { state: seeded, path: store, mtimeMs: old.mtimeMs, seeded: true }
|
|
157
|
+
}
|
|
158
|
+
return { state: emptyState(beijingDay(now)), path: store, mtimeMs: 0, seeded: false }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Persist the ledger atomically (temp file + rename).
|
|
163
|
+
*
|
|
164
|
+
* @param file - store path.
|
|
165
|
+
* @param state - ledger object.
|
|
166
|
+
* @returns true on success.
|
|
167
|
+
*/
|
|
168
|
+
export function saveState(file, state) {
|
|
169
|
+
try {
|
|
170
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
171
|
+
state.updatedAt = new Date().toISOString()
|
|
172
|
+
const text = JSON.stringify(state)
|
|
173
|
+
const temp = file + '.tmp-' + process.pid
|
|
174
|
+
fs.writeFileSync(temp, text, 'utf8')
|
|
175
|
+
fs.renameSync(temp, file)
|
|
176
|
+
return true
|
|
177
|
+
} catch {
|
|
178
|
+
return false
|
|
179
|
+
}
|
|
180
|
+
}
|
package/lib/pricing.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Peak/valley calendar and the official CNY price table.
|
|
3
|
+
*
|
|
4
|
+
* Shared by the tracker (which prices each settled turn) and the snapshot
|
|
5
|
+
* (which shows the current window), so both always agree on what "peak" means.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Ledger amounts are stored as plain CNY numbers; the legacy ledger uses 1e-8 units. */
|
|
9
|
+
export const LEGACY_UNIT = 1e8
|
|
10
|
+
|
|
11
|
+
/** Peak windows in Beijing local hours: [startHour, endHour). */
|
|
12
|
+
const PEAK_HOURS = [
|
|
13
|
+
[9, 12],
|
|
14
|
+
[14, 18],
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Weekend valley pricing was introduced on Beijing 2026-08-23 00:00; earlier
|
|
19
|
+
* buckets in a legacy ledger were charged by the old all-week rule.
|
|
20
|
+
*/
|
|
21
|
+
const WEEKEND_VALLEY_FROM_SEC = Math.floor(Date.UTC(2026, 7, 22, 16, 0, 0) / 1000)
|
|
22
|
+
|
|
23
|
+
/** Statutory holidays are valley-priced all day since Beijing 2026-09-19 00:00. */
|
|
24
|
+
const HOLIDAY_VALLEY_FROM_SEC = Math.floor(Date.UTC(2026, 8, 18, 16, 0, 0) / 1000)
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Days that are holidays for billing (only days off need listing: make-up
|
|
28
|
+
* working weekends are already valley under the weekend rule).
|
|
29
|
+
* Extend this table when the 2027 schedule is published.
|
|
30
|
+
*/
|
|
31
|
+
const HOLIDAY_VALLEY = {
|
|
32
|
+
'2026-01-01': 1, '2026-01-02': 1, '2026-01-03': 1,
|
|
33
|
+
'2026-02-15': 1, '2026-02-16': 1, '2026-02-17': 1, '2026-02-18': 1, '2026-02-19': 1,
|
|
34
|
+
'2026-02-20': 1, '2026-02-21': 1, '2026-02-22': 1, '2026-02-23': 1,
|
|
35
|
+
'2026-04-04': 1, '2026-04-05': 1, '2026-04-06': 1,
|
|
36
|
+
'2026-05-01': 1, '2026-05-02': 1, '2026-05-03': 1, '2026-05-04': 1, '2026-05-05': 1,
|
|
37
|
+
'2026-06-19': 1, '2026-06-20': 1, '2026-06-21': 1,
|
|
38
|
+
'2026-09-25': 1, '2026-09-26': 1, '2026-09-27': 1,
|
|
39
|
+
'2026-10-01': 1, '2026-10-02': 1, '2026-10-03': 1, '2026-10-04': 1,
|
|
40
|
+
'2026-10-05': 1, '2026-10-06': 1, '2026-10-07': 1,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The schedule sentence shown in the widget. */
|
|
44
|
+
export const SCHEDULE = '峰:周一至周五 09:00–12:00、14:00–18:00;其余(含周末与法定节假日全天)谷价'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Official CNY price per million tokens: [off-peak, peak]. Peak is 2x off-peak.
|
|
48
|
+
* Source: https://api-docs.deepseek.com/zh-cn/quick_start/pricing
|
|
49
|
+
*/
|
|
50
|
+
export const PRICES = [
|
|
51
|
+
{ key: 'flash', model: 'deepseek-flash', hit: [0.02, 0.04], miss: [1, 2], out: [4, 8] },
|
|
52
|
+
{ key: 'pro', model: 'deepseek-v4-pro', hit: [0.15, 0.3], miss: [4.5, 9], out: [13.5, 27] },
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
const FLASH = PRICES[0]
|
|
56
|
+
const PRO = PRICES[1]
|
|
57
|
+
|
|
58
|
+
/** Beijing local hour/weekday/date for an epoch-second instant, read through UTC. */
|
|
59
|
+
function beijingParts(sec) {
|
|
60
|
+
const bj = new Date(sec * 1000 + 8 * 3600 * 1000)
|
|
61
|
+
return { hour: bj.getUTCHours(), dow: bj.getUTCDay(), day: bj.toISOString().slice(0, 10) }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* True when the instant is billed at peak price.
|
|
66
|
+
*
|
|
67
|
+
* @param sec - epoch seconds.
|
|
68
|
+
*/
|
|
69
|
+
export function isPeak(sec) {
|
|
70
|
+
if (!Number.isFinite(sec)) return false
|
|
71
|
+
const { hour, dow, day } = beijingParts(sec)
|
|
72
|
+
if (sec >= WEEKEND_VALLEY_FROM_SEC && (dow === 0 || dow === 6)) return false
|
|
73
|
+
if (sec >= HOLIDAY_VALLEY_FROM_SEC && HOLIDAY_VALLEY[day] === 1) return false
|
|
74
|
+
return PEAK_HOURS.some(([start, end]) => hour >= start && hour < end)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Next instant whose peak/valley classification differs from `sec`.
|
|
79
|
+
* Scans Beijing hour edges (00/09/12/14/18) day by day; 12 days covers the
|
|
80
|
+
* longest statutory break.
|
|
81
|
+
*
|
|
82
|
+
* @param sec - epoch seconds.
|
|
83
|
+
* @returns epoch seconds, or null when no edge flips within 12 days.
|
|
84
|
+
*/
|
|
85
|
+
export function nextPeakChange(sec) {
|
|
86
|
+
if (!Number.isFinite(sec)) return null
|
|
87
|
+
const current = isPeak(sec)
|
|
88
|
+
const midnight = Math.floor((sec + 8 * 3600) / 86400) * 86400
|
|
89
|
+
for (let day = 0; day <= 12; day++) {
|
|
90
|
+
for (const edge of [0, 9, 12, 14, 18]) {
|
|
91
|
+
const candidate = midnight + day * 86400 + edge * 3600 - 8 * 3600
|
|
92
|
+
if (candidate <= sec + 1) continue
|
|
93
|
+
if (isPeak(candidate) !== current) return candidate
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return null
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Beijing calendar date (`YYYY-MM-DD`) for an epoch-millisecond instant. */
|
|
100
|
+
export function beijingDay(ms = Date.now()) {
|
|
101
|
+
return beijingParts(Math.floor(ms / 1000)).day
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Price row for a model name: Pro tiers cost 3x Flash, everything else is Flash.
|
|
106
|
+
*
|
|
107
|
+
* @param model - model id from the assistant message source.
|
|
108
|
+
*/
|
|
109
|
+
export function priceFor(model) {
|
|
110
|
+
return String(model || '').toLowerCase().indexOf('pro') !== -1 ? PRO : FLASH
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Finite non-negative number or 0. */
|
|
114
|
+
function count(value) {
|
|
115
|
+
const n = Number(value)
|
|
116
|
+
return Number.isFinite(n) && n > 0 ? n : 0
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Cost of one assistant message in CNY at the instant it completed.
|
|
121
|
+
*
|
|
122
|
+
* DSH guarantees `reasoningTokens ⊆ outputTokens`, so reasoning is not billed
|
|
123
|
+
* again on top of the output tokens.
|
|
124
|
+
*
|
|
125
|
+
* @param model - model id.
|
|
126
|
+
* @param usage - TokenUsage from the `assistant/message` event.
|
|
127
|
+
* @param sec - epoch seconds used to pick the peak/valley price.
|
|
128
|
+
* @returns CNY amount.
|
|
129
|
+
*/
|
|
130
|
+
export function costOf(model, usage, sec) {
|
|
131
|
+
if (usage === null || typeof usage !== 'object') return 0
|
|
132
|
+
const price = priceFor(model)
|
|
133
|
+
const tier = isPeak(sec) ? 1 : 0
|
|
134
|
+
const hit = count(usage.cacheReadTokens)
|
|
135
|
+
const miss = count(usage.inputTokens)
|
|
136
|
+
const out = count(usage.outputTokens)
|
|
137
|
+
return (hit / 1e6) * price.hit[tier] + (miss / 1e6) * price.miss[tier] + (out / 1e6) * price.out[tier]
|
|
138
|
+
}
|