@lls-a1/dsh-balance-float 0.0.0-stage → 1.1.43

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.
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Snapshot builder for the balance-float widget.
3
+ *
4
+ * Pure formatting over one ledger object: the Host half owns when the ledger is
5
+ * updated, this module only turns it (plus the current peak window and the
6
+ * price table) into the JSON the browser polls.
7
+ */
8
+ import path from 'node:path'
9
+ import { PRICES, SCHEDULE, beijingDay, isPeak, nextPeakChange } from './pricing.js'
10
+ import { loadState } from './ledger.js'
11
+
12
+ /** Finite number or fallback. */
13
+ function numberOr(value, fallback) {
14
+ if (value === null || value === undefined || value === '') return fallback
15
+ const n = Number(value)
16
+ return Number.isFinite(n) ? n : fallback
17
+ }
18
+
19
+ /** Rounded currency value. */
20
+ function money(value) {
21
+ const n = Number(value)
22
+ if (!Number.isFinite(n)) return null
23
+ return Math.round(n * 1e6) / 1e6
24
+ }
25
+
26
+ /** Today's events folded per model and per peak/valley period. */
27
+ function todayBreakdown(events, today) {
28
+ const models = {}
29
+ let calls = 0
30
+ let tokens = 0
31
+ let input = 0
32
+ let cacheRead = 0
33
+ let output = 0
34
+ let peakCost = 0
35
+ let valleyCost = 0
36
+ for (const event of events) {
37
+ if (!event || event.day !== today) continue
38
+ const cost = numberOr(event.cost, 0)
39
+ const eventTokens = numberOr(event.tokens, 0)
40
+ calls += 1
41
+ tokens += eventTokens
42
+ input += numberOr(event.input, 0)
43
+ cacheRead += numberOr(event.cacheRead, 0)
44
+ output += numberOr(event.output, 0)
45
+ if (isPeak(numberOr(event.ts, 0) / 1000)) peakCost += cost
46
+ else valleyCost += cost
47
+ const key = String(event.model || 'unknown')
48
+ const row =
49
+ models[key] || (models[key] = { model: key, calls: 0, tokens: 0, input: 0, cacheRead: 0, output: 0, cost: 0 })
50
+ row.calls += 1
51
+ row.tokens += eventTokens
52
+ row.input += numberOr(event.input, 0)
53
+ row.cacheRead += numberOr(event.cacheRead, 0)
54
+ row.output += numberOr(event.output, 0)
55
+ row.cost += cost
56
+ }
57
+ const rows = Object.keys(models)
58
+ .map((key) => ({ ...models[key], cost: money(models[key].cost) }))
59
+ .sort((a, b) => b.cost - a.cost)
60
+ return {
61
+ calls,
62
+ tokens,
63
+ input,
64
+ cacheRead,
65
+ output,
66
+ peakCost: money(peakCost),
67
+ valleyCost: money(valleyCost),
68
+ models: rows,
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Cost of the most recently settled turn.
74
+ *
75
+ * One turn writes one event per model, all sharing the same `ts`, so the group
76
+ * with the newest `ts` is exactly the last turn.
77
+ */
78
+ function lastTurn(events) {
79
+ let lastTs = 0
80
+ for (const event of events) {
81
+ const ts = numberOr(event && event.ts, 0)
82
+ if (ts > lastTs) lastTs = ts
83
+ }
84
+ if (lastTs <= 0) return null
85
+ let cost = 0
86
+ let tokens = 0
87
+ const byModel = {}
88
+ for (const event of events) {
89
+ if (numberOr(event && event.ts, 0) !== lastTs) continue
90
+ const eventCost = numberOr(event.cost, 0)
91
+ cost += eventCost
92
+ tokens += numberOr(event.tokens, 0)
93
+ const model = String((event && event.model) || 'unknown')
94
+ byModel[model] = (byModel[model] || 0) + eventCost
95
+ }
96
+ return {
97
+ cost: money(cost),
98
+ tokens,
99
+ at: lastTs,
100
+ models: Object.keys(byModel)
101
+ .map((model) => ({ model, cost: money(byModel[model]) }))
102
+ .sort((a, b) => b.cost - a.cost),
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Build one snapshot.
108
+ *
109
+ * @param options.ledger - the plugin's ledger object.
110
+ * @param options.sourcePath - path the ledger is stored at (shown to the user).
111
+ * @param options.mtimeMs - ledger file mtime, epoch milliseconds.
112
+ * @param options.serverNow - epoch milliseconds, injectable for tests.
113
+ * @returns JSON-serializable snapshot.
114
+ */
115
+ export function buildSnapshot({ ledger, sourcePath, mtimeMs, serverNow = Date.now(), version = '' } = {}) {
116
+ const nowSec = Math.floor(serverNow / 1000)
117
+ const peakActive = isPeak(nowSec)
118
+ const nextChange = nextPeakChange(nowSec)
119
+ const today = beijingDay(serverNow)
120
+ const events = Array.isArray(ledger?.events) ? ledger.events : []
121
+ const history = ledger?.history !== null && typeof ledger?.history === 'object' ? ledger.history : {}
122
+ const breakdown = todayBreakdown(events, today)
123
+ const balance = money(numberOr(ledger?.lastBalance, NaN))
124
+ const dayStart = money(numberOr(ledger?.dayStart, NaN))
125
+ const usedFromHistory = money(numberOr(history[today], NaN))
126
+ const base = {
127
+ ok: true,
128
+ currency: 'CNY',
129
+ serverNow,
130
+ peak: {
131
+ active: peakActive,
132
+ label: peakActive ? 'peak' : 'valley',
133
+ nextChangeAt: nextChange === null ? null : nextChange * 1000,
134
+ schedule: SCHEDULE,
135
+ },
136
+ prices: PRICES,
137
+ version,
138
+ source: {
139
+ exists: true,
140
+ path: sourcePath ?? '',
141
+ updatedAt: mtimeMs > 0 ? new Date(mtimeMs).toISOString() : null,
142
+ },
143
+ }
144
+
145
+ const days = Object.keys(history)
146
+ .filter((day) => /^\d{4}-\d{2}-\d{2}$/.test(day))
147
+ .sort()
148
+ .slice(-7)
149
+ // Each bar carries its own breakdown (folded from the stored events); old
150
+ // days whose events rolled out of MAX_EVENTS fall back to the stored total.
151
+ const recent = days.map((day) => {
152
+ const detail = todayBreakdown(events, day)
153
+ const fromEvents = money((detail.peakCost ?? 0) + (detail.valleyCost ?? 0)) ?? 0
154
+ const stored = money(numberOr(history[day], 0)) ?? 0
155
+ return {
156
+ day,
157
+ cost: money(Math.max(stored, fromEvents)),
158
+ calls: detail.calls,
159
+ tokens: detail.tokens,
160
+ input: detail.input,
161
+ cacheRead: detail.cacheRead,
162
+ output: detail.output,
163
+ peakCost: detail.peakCost,
164
+ valleyCost: detail.valleyCost,
165
+ models: detail.models,
166
+ }
167
+ })
168
+ const turn = lastTurn(events)
169
+ const todayUsed =
170
+ money(numberOr(ledger?.todayUsage, NaN)) ?? usedFromHistory ?? money((breakdown.peakCost ?? 0) + (breakdown.valleyCost ?? 0))
171
+
172
+ return {
173
+ ...base,
174
+ balance,
175
+ dayStart,
176
+ today,
177
+ todayUsed,
178
+ todayCalls: breakdown.calls,
179
+ todayTokens: breakdown.tokens,
180
+ todayInput: breakdown.input,
181
+ todayCacheRead: breakdown.cacheRead,
182
+ todayOutput: breakdown.output,
183
+ todayPeakCost: breakdown.peakCost,
184
+ todayValleyCost: breakdown.valleyCost,
185
+ models: breakdown.models,
186
+ turn,
187
+ lastEventAt: turn === null ? 0 : turn.at,
188
+ history: recent,
189
+ historyMax: recent.reduce((max, row) => Math.max(max, row.cost ?? 0), 0),
190
+ historyTotal: money(recent.reduce((sum, row) => sum + (row.cost ?? 0), 0)),
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Convenience reader used by tests and by callers without in-memory state.
196
+ *
197
+ * @param options - raw row config (`storeFile` / `legacyFile`) plus `now`.
198
+ */
199
+ export function readSnapshot(options = {}) {
200
+ const now = options.now ?? Date.now()
201
+ const loaded = loadState(options, now)
202
+ return buildSnapshot({
203
+ ledger: loaded.state,
204
+ sourcePath: loaded.path,
205
+ mtimeMs: loaded.mtimeMs,
206
+ serverNow: now,
207
+ })
208
+ }
209
+
210
+ /** File name of the store, for compact display. */
211
+ export function storeName(file) {
212
+ return path.basename(file)
213
+ }
package/lib/tracker.js ADDED
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Runtime accounting for the balance-float widget.
3
+ *
4
+ * - folds `assistant/message` usage into a per-(session, turn) aggregate and
5
+ * appends one ledger event per model when the turn ends;
6
+ * - applies each balance poll to the ledger: the day's opening balance sets the
7
+ * baseline, and `openingBalance - currentBalance` is today's spend (so usage
8
+ * from outside this Harness also counts);
9
+ * - persists on a short debounce so a busy turn does not rewrite per message.
10
+ */
11
+ import { beijingDay, costOf } from './pricing.js'
12
+ import { saveState } from './ledger.js'
13
+
14
+ /** Ledger cap; older events only feed the 7-day chart. */
15
+ const MAX_EVENTS = 1200
16
+
17
+ /** Round to the ledger's 1e-6 CNY resolution. */
18
+ function round(value) {
19
+ return Math.round(Number(value) * 1e6) / 1e6
20
+ }
21
+
22
+ /**
23
+ * Create the tracker over one mutable ledger object.
24
+ *
25
+ * @param options.state - the ledger (mutated in place).
26
+ * @param options.storePath - where to persist it.
27
+ * @param options.onTurn - called after a turn is settled (trigger a balance poll).
28
+ * @param options.logger - optional logger.
29
+ */
30
+ export function createTracker({ state, storePath, onTurn, logger } = {}) {
31
+ const turns = new Map()
32
+ let saveTimer = null
33
+ let dirty = false
34
+ let lastSavedAt = 0
35
+
36
+ function flush() {
37
+ saveTimer = null
38
+ if (!dirty) return
39
+ dirty = false
40
+ if (saveState(storePath, state)) lastSavedAt = Date.now()
41
+ }
42
+
43
+ function scheduleSave() {
44
+ dirty = true
45
+ if (saveTimer !== null) return
46
+ saveTimer = setTimeout(flush, 700)
47
+ if (typeof saveTimer.unref === 'function') saveTimer.unref()
48
+ }
49
+
50
+ /** Start a new Beijing day, carrying yesterday's total into `history`. */
51
+ function rollover(now = Date.now()) {
52
+ const today = beijingDay(now)
53
+ if (state.date === today) return
54
+ state.history[state.date] = round(state.todayUsage)
55
+ state.date = today
56
+ state.dayStart = state.lastBalance
57
+ state.todayUsage = 0
58
+ state.history[today] = 0
59
+ }
60
+
61
+ /** Sum of today's appended events. */
62
+ function eventsTodaySum() {
63
+ let sum = 0
64
+ for (const event of state.events) {
65
+ if (event && event.day === state.date) sum += Number(event.cost) || 0
66
+ }
67
+ return sum
68
+ }
69
+
70
+ /** Append one settled turn as one event per model. */
71
+ function settle(agg, now = Date.now()) {
72
+ const ts = agg.lastTs || now
73
+ const day = beijingDay(ts)
74
+ let total = 0
75
+ let tokens = 0
76
+ for (const model of Object.keys(agg.byModel)) {
77
+ const cost = round(agg.byModel[model])
78
+ if (!(cost > 0)) continue
79
+ const modelTokens = Math.max(0, Math.round(agg.byModelTokens[model] || 0))
80
+ const usage = agg.byModelUsage[model] || { input: 0, cacheRead: 0, output: 0 }
81
+ // Keep the per-bucket split: the card shows cached vs uncached input later.
82
+ state.events.push({
83
+ ts,
84
+ day,
85
+ model,
86
+ cost,
87
+ tokens: modelTokens,
88
+ input: Math.max(0, Math.round(usage.input)),
89
+ cacheRead: Math.max(0, Math.round(usage.cacheRead)),
90
+ output: Math.max(0, Math.round(usage.output)),
91
+ })
92
+ total += cost
93
+ tokens += modelTokens
94
+ }
95
+ if (total <= 0) return
96
+ if (state.events.length > MAX_EVENTS) state.events = state.events.slice(-MAX_EVENTS)
97
+ if (day === state.date) state.todayUsage = round(Math.max(state.todayUsage, eventsTodaySum()))
98
+ state.history[day] = round(Math.max(Number(state.history[day]) || 0, state.todayUsage))
99
+ state.updatedAt = new Date(now).toISOString()
100
+ scheduleSave()
101
+ onTurn?.(total, tokens)
102
+ }
103
+
104
+ function finalize(sessionId, now = Date.now()) {
105
+ const agg = turns.get(sessionId)
106
+ if (!agg) return
107
+ turns.delete(sessionId)
108
+ settle(agg, now)
109
+ }
110
+
111
+ /**
112
+ * Fold one session event.
113
+ *
114
+ * @param session - the session the event belongs to.
115
+ * @param event - the appended SessionEvent.
116
+ */
117
+ function handleEvent(session, event) {
118
+ const type = event && event.type
119
+ const data = event && event.data
120
+ if (type !== 'assistant/message' && type !== 'turn/end') return
121
+ const sessionId = session && session.id ? String(session.id) : 'default'
122
+ if (type === 'turn/end') {
123
+ finalize(sessionId)
124
+ return
125
+ }
126
+ if (!data || !Number.isFinite(Number(data.turn)) || data.usage === null || typeof data.usage !== 'object') return
127
+ const turn = Number(data.turn)
128
+ let agg = turns.get(sessionId)
129
+ if (!agg || agg.turn !== turn) {
130
+ if (agg) finalize(sessionId)
131
+ agg = { turn, byModel: {}, byModelTokens: {}, byModelUsage: {}, lastTs: 0 }
132
+ turns.set(sessionId, agg)
133
+ }
134
+ const model = String(data.message?.source?.model || 'unknown')
135
+ const usage = data.usage
136
+ const cost = costOf(model, usage, Math.floor(Date.now() / 1000))
137
+ agg.byModel[model] = (agg.byModel[model] || 0) + cost
138
+ agg.byModelTokens[model] =
139
+ (agg.byModelTokens[model] || 0) +
140
+ (Number(usage.inputTokens) || 0) +
141
+ (Number(usage.cacheReadTokens) || 0) +
142
+ (Number(usage.outputTokens) || 0)
143
+ const buckets = agg.byModelUsage[model] || (agg.byModelUsage[model] = { input: 0, cacheRead: 0, output: 0 })
144
+ buckets.input += Number(usage.inputTokens) || 0
145
+ buckets.cacheRead += Number(usage.cacheReadTokens) || 0
146
+ buckets.output += Number(usage.outputTokens) || 0
147
+ agg.lastTs = Date.now()
148
+ }
149
+
150
+ /**
151
+ * Apply one balance reading.
152
+ *
153
+ * @param balance - total balance in CNY.
154
+ * @param source - where the reading came from (`apikey`).
155
+ * @param now - epoch milliseconds.
156
+ */
157
+ function applyBalance(balance, source = 'apikey', now = Date.now()) {
158
+ const value = Number(balance)
159
+ if (!Number.isFinite(value)) return false
160
+ rollover(now)
161
+ if (state.dayStart === null) state.dayStart = value
162
+ state.lastBalance = round(value)
163
+ state.balanceSource = source
164
+ state.balanceAt = now
165
+ const delta = state.dayStart === null ? null : state.dayStart - value
166
+ if (delta === null) {
167
+ // First reading of the day doubles as the baseline.
168
+ } else if (delta >= -0.005) {
169
+ state.todayUsage = round(Math.max(state.todayUsage, delta))
170
+ } else {
171
+ // Balance went up: a top-up, so re-anchor the baseline instead of
172
+ // reporting negative spend.
173
+ state.dayStart = value
174
+ }
175
+ state.history[state.date] = round(state.todayUsage)
176
+ state.updatedAt = new Date(now).toISOString()
177
+ scheduleSave()
178
+ return true
179
+ }
180
+
181
+ /** Persist synchronously (startup seed, disposal). */
182
+ function flushNow() {
183
+ dirty = true
184
+ flush()
185
+ }
186
+
187
+ return {
188
+ handleEvent,
189
+ applyBalance,
190
+ flushNow,
191
+ get state() {
192
+ return state
193
+ },
194
+ get lastSavedAt() {
195
+ return lastSavedAt
196
+ },
197
+ dispose() {
198
+ if (saveTimer !== null) clearTimeout(saveTimer)
199
+ saveTimer = null
200
+ flushNow()
201
+ },
202
+ }
203
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Balance Float",
4
+ "description": "Floating pill that reads the locally saved usage ledger and shows the API balance, today's spend and the current peak/off-peak pricing."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "余额悬浮窗",
4
+ "description": "悬浮小窗读取本地保存的用量账本,显示 API 余额、今日已用与当前峰谷定价。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@lls-a1/dsh-balance-float",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.43",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "type": "module",
8
+ "description": "Floating Web UI pill that reads the locally saved DeepSeek usage ledger: API balance, today's spend, and current peak/off-peak pricing.",
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/ming-a1/dsh-balance-float.git"
13
+ },
14
+ "homepage": "https://github.com/ming-a1/dsh-balance-float#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/ming-a1/dsh-balance-float/issues"
17
+ },
18
+ "keywords": [
19
+ "deepseek-harness",
20
+ "dsh",
21
+ "plugin",
22
+ "bundle",
23
+ "balance",
24
+ "usage",
25
+ "peak",
26
+ "widget"
27
+ ],
28
+ "exports": {
29
+ ".": "./index.js",
30
+ "./client": "./client.js",
31
+ "./locale/*.json": "./locale/*.json",
32
+ "./icon": "./icon.svg"
33
+ },
34
+ "files": [
35
+ "index.js",
36
+ "client.js",
37
+ "lib/*.js",
38
+ "cordis.patch.yml",
39
+ "locale/*.json",
40
+ "icon.svg",
41
+ "README.md"
42
+ ],
43
+ "dsh": {
44
+ "bundle": {
45
+ "patch": "./cordis.patch.yml"
46
+ },
47
+ "client": {
48
+ "platform": "web",
49
+ "immediately": true
50
+ }
51
+ }
52
+ }