dsh-go-workbuddy 1.0.3 → 1.1.1
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/bridge/bridge.mjs +71 -1
- package/lib/index.js +30 -5
- package/package.json +1 -1
package/bridge/bridge.mjs
CHANGED
|
@@ -68,6 +68,62 @@ const client = new WorkBuddyUpstreamClient()
|
|
|
68
68
|
const creditCache = new Map()
|
|
69
69
|
const checkinCache = new Map()
|
|
70
70
|
|
|
71
|
+
// ——— 本机用量账本(对齐码道 .codearts-usage.json 的格式)———
|
|
72
|
+
// 上游只给「每次请求的 usage」,不按「本机」维度统计;这里把经本桥发出的请求
|
|
73
|
+
// 累计成按天 / 小时 / 账号 / 模型的 token 用量,落盘在 $DSH_HOME/.workbuddy-usage.json。
|
|
74
|
+
const USAGE_FILE = join(process.env.DSH_HOME || join(homedir(), '.dsh'), '.workbuddy-usage.json')
|
|
75
|
+
const USAGE_RETENTION_DAYS = 30
|
|
76
|
+
function localDay(at = Date.now()) {
|
|
77
|
+
const d = new Date(at), p = (n) => String(n).padStart(2, '0')
|
|
78
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
|
|
79
|
+
}
|
|
80
|
+
function localHour(at = Date.now()) { return String(new Date(at).getHours()).padStart(2, '0') }
|
|
81
|
+
function posInt(v) { return typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0 }
|
|
82
|
+
function nested(details, key) { return details && typeof details === 'object' ? details[key] : undefined }
|
|
83
|
+
function usageFromRaw(raw) {
|
|
84
|
+
const prompt = posInt(raw?.prompt_tokens)
|
|
85
|
+
const completion = posInt(raw?.completion_tokens)
|
|
86
|
+
const cached = Math.min(posInt(nested(raw?.prompt_tokens_details, 'cached_tokens') ?? raw?.cached_tokens ?? raw?.prompt_cache_hit_tokens), prompt)
|
|
87
|
+
const reasoning = Math.min(posInt(nested(raw?.completion_tokens_details, 'reasoning_tokens') ?? raw?.reasoning_tokens), completion)
|
|
88
|
+
const total = posInt(raw?.total_tokens) || (prompt + completion)
|
|
89
|
+
return { requests: 1, promptTokens: prompt, completionTokens: completion, totalTokens: total, cachedTokens: cached, reasoningTokens: reasoning }
|
|
90
|
+
}
|
|
91
|
+
function emptyTotals() { return { requests: 0, promptTokens: 0, completionTokens: 0, totalTokens: 0, cachedTokens: 0, reasoningTokens: 0 } }
|
|
92
|
+
function addTotals(into, add) {
|
|
93
|
+
into.requests += add.requests || 0
|
|
94
|
+
into.promptTokens += add.promptTokens || 0
|
|
95
|
+
into.completionTokens += add.completionTokens || 0
|
|
96
|
+
into.totalTokens += add.totalTokens || 0
|
|
97
|
+
into.cachedTokens += add.cachedTokens || 0
|
|
98
|
+
into.reasoningTokens += add.reasoningTokens || 0
|
|
99
|
+
}
|
|
100
|
+
function readUsageBook() {
|
|
101
|
+
try { const d = JSON.parse(readFileSync(USAGE_FILE, 'utf8')); return d && typeof d === 'object' && d.days ? d : { version: 1, days: {} } }
|
|
102
|
+
catch { return { version: 1, days: {} } }
|
|
103
|
+
}
|
|
104
|
+
let usageWriteQueue = Promise.resolve()
|
|
105
|
+
function recordUsage(raw, account, model) {
|
|
106
|
+
if (!raw) return
|
|
107
|
+
const t = usageFromRaw(raw)
|
|
108
|
+
if (t.totalTokens <= 0 && t.promptTokens <= 0) return
|
|
109
|
+
usageWriteQueue = usageWriteQueue.then(() => {
|
|
110
|
+
try {
|
|
111
|
+
const book = readUsageBook()
|
|
112
|
+
const day = localDay(), hour = localHour()
|
|
113
|
+
const d = book.days[day] || (book.days[day] = { models: {}, accounts: {}, hours: {} })
|
|
114
|
+
d.models ||= {}; d.accounts ||= {}; d.hours ||= {}
|
|
115
|
+
for (const [bucket, key] of [[d.models, model || 'unknown'], [d.accounts, account || 'unknown'], [d.hours, hour]]) {
|
|
116
|
+
bucket[key] ||= emptyTotals()
|
|
117
|
+
addTotals(bucket[key], t)
|
|
118
|
+
}
|
|
119
|
+
// 只留最近 N 天
|
|
120
|
+
const keys = Object.keys(book.days).sort()
|
|
121
|
+
while (keys.length > USAGE_RETENTION_DAYS) delete book.days[keys.shift()]
|
|
122
|
+
writeFileSync(USAGE_FILE, JSON.stringify(book), 'utf8')
|
|
123
|
+
} catch {}
|
|
124
|
+
})
|
|
125
|
+
}
|
|
126
|
+
|
|
71
127
|
// 一个区一个 store;refresh 直接借上游客户端的刷新接口
|
|
72
128
|
const stores = new Map()
|
|
73
129
|
function storeOf(region) {
|
|
@@ -182,6 +238,18 @@ const server = createServer(async (req, res) => {
|
|
|
182
238
|
return send(res, 200, { ok: true })
|
|
183
239
|
}
|
|
184
240
|
|
|
241
|
+
if (path === '/api/usage') {
|
|
242
|
+
const book = readUsageBook()
|
|
243
|
+
const day = localDay()
|
|
244
|
+
const d = book.days[day] || {}
|
|
245
|
+
const hours = d.hours || {}
|
|
246
|
+
return send(res, 200, {
|
|
247
|
+
requests: Object.values(hours).reduce((n, h) => n + (h.requests || 0), 0),
|
|
248
|
+
totalTokens: Object.values(hours).reduce((n, h) => n + (h.totalTokens || 0), 0),
|
|
249
|
+
hours,
|
|
250
|
+
})
|
|
251
|
+
}
|
|
252
|
+
|
|
185
253
|
if (path === '/api/accounts') {
|
|
186
254
|
const accounts = await storeOf(regionOf(req, url)).accounts()
|
|
187
255
|
return send(res, 200, { accounts })
|
|
@@ -265,6 +333,7 @@ const server = createServer(async (req, res) => {
|
|
|
265
333
|
// 有些客户端校验两者一致,这里把每个 chunk 的 model 改回请求值。
|
|
266
334
|
const reader = result.response.body.getReader()
|
|
267
335
|
const requestedModel = body.model
|
|
336
|
+
const aid = url.searchParams.get('account') || ''
|
|
268
337
|
let carry = ''
|
|
269
338
|
for (;;) {
|
|
270
339
|
const { done, value } = await reader.read()
|
|
@@ -277,6 +346,7 @@ const server = createServer(async (req, res) => {
|
|
|
277
346
|
try {
|
|
278
347
|
const j = JSON.parse(line.slice(5).trim())
|
|
279
348
|
if (j.model !== undefined) j.model = requestedModel
|
|
349
|
+
if (j.usage) recordUsage(j.usage, aid, requestedModel)
|
|
280
350
|
return 'data: ' + JSON.stringify(j)
|
|
281
351
|
} catch { return line }
|
|
282
352
|
})
|
|
@@ -298,7 +368,7 @@ const server = createServer(async (req, res) => {
|
|
|
298
368
|
const j = JSON.parse(data)
|
|
299
369
|
const delta = j.choices?.[0]?.delta?.content
|
|
300
370
|
if (typeof delta === 'string') content += delta
|
|
301
|
-
if (j.usage) out.usage = j.usage
|
|
371
|
+
if (j.usage) { out.usage = j.usage; recordUsage(j.usage, url.searchParams.get('account') || '', body.model) }
|
|
302
372
|
} catch {}
|
|
303
373
|
}
|
|
304
374
|
out.choices[0].message.content = content
|
package/lib/index.js
CHANGED
|
@@ -142,6 +142,7 @@ function saveAccount(id) {
|
|
|
142
142
|
}
|
|
143
143
|
let stripEmit = null
|
|
144
144
|
let stripLocale = 'zh'
|
|
145
|
+
let stripGen = 0 // strip 代次:dispose 后旧请求不能往新 strip 推,避免渲染错乱
|
|
145
146
|
let stripTimer = null
|
|
146
147
|
|
|
147
148
|
function isZh(caps) {
|
|
@@ -171,24 +172,33 @@ function accountQuery() {
|
|
|
171
172
|
return accountId === '' ? '' : `&account=${encodeURIComponent(accountId)}`
|
|
172
173
|
}
|
|
173
174
|
|
|
175
|
+
let stripFails = 0
|
|
174
176
|
async function pushStrip() {
|
|
175
177
|
const emit = stripEmit
|
|
178
|
+
const gen = stripGen
|
|
176
179
|
if (typeof emit !== 'function') return
|
|
177
180
|
const zh = !stripLocale.startsWith('en')
|
|
181
|
+
// 异步取数期间 strip 可能已被销毁/重建;代次变了就丢弃这次结果
|
|
182
|
+
const fresh = () => stripEmit === emit && stripGen === gen && typeof stripEmit === 'function'
|
|
178
183
|
try {
|
|
179
184
|
const credits = await api(`/api/credits?region=${region}${accountQuery()}`)
|
|
185
|
+
stripFails = 0
|
|
180
186
|
const total = Number(credits?.total ?? 0)
|
|
181
|
-
emit({ text: clip(zh ? `WB 余 ${fmt(total)} 积分` : `WB ${fmt(total)} left`, 24), tone: total <= 0 ? 'warn' : 'good' })
|
|
187
|
+
if (fresh()) emit({ text: clip(zh ? `WB 余 ${fmt(total)} 积分` : `WB ${fmt(total)} left`, 24), tone: total <= 0 ? 'warn' : 'good' })
|
|
182
188
|
} catch (error) {
|
|
189
|
+
// 桥刚重启 / 网络抖动 / 限流都会让这次读取失败。偶发失败静默保留上一次的
|
|
190
|
+
// 显示,连续 3 次都失败才提示异常:避免胶囊在「正常文字 ↔ 错误文字」之间反复闪。
|
|
191
|
+
stripFails += 1
|
|
192
|
+
if (stripFails < 3) return
|
|
183
193
|
if (error?.code === 'not_logged_in') {
|
|
184
|
-
emit({ text: zh ? 'WB 未登录' : 'WB signed out', tone: 'warn' })
|
|
194
|
+
if (fresh()) emit({ text: zh ? 'WB 未登录' : 'WB signed out', tone: 'warn' })
|
|
185
195
|
return
|
|
186
196
|
}
|
|
187
197
|
if (error?.code === 'bridge_down') {
|
|
188
|
-
emit({ text: zh ? 'WB 桥未启动' : 'WB bridge off', tone: 'warn' })
|
|
198
|
+
if (fresh()) emit({ text: zh ? 'WB 桥未启动' : 'WB bridge off', tone: 'warn' })
|
|
189
199
|
return
|
|
190
200
|
}
|
|
191
|
-
emit({ text: clip(zh ? `WB 读取失败:${error?.code ?? '网络'}` : 'WB read failed', 24), tone: 'warn' })
|
|
201
|
+
if (fresh()) emit({ text: clip(zh ? `WB 读取失败:${error?.code ?? '网络'}` : 'WB read failed', 24), tone: 'warn' })
|
|
192
202
|
}
|
|
193
203
|
}
|
|
194
204
|
|
|
@@ -321,13 +331,15 @@ function noteOf(error, zh) {
|
|
|
321
331
|
async function buildPatch(zh) {
|
|
322
332
|
const acct = accountId
|
|
323
333
|
const q = `${acct === '' ? '' : '&account=' + encodeURIComponent(acct)}&force=1`
|
|
324
|
-
const [c, k, a, cr] = await Promise.allSettled([
|
|
334
|
+
const [c, k, a, cr, u] = await Promise.allSettled([
|
|
325
335
|
api(`/api/credits?region=${region}${q}`),
|
|
326
336
|
api(`/api/checkin?region=${region}${q}`),
|
|
327
337
|
api(`/api/accounts?region=${region}`),
|
|
328
338
|
api('/api/cache/clear'),
|
|
339
|
+
api('/api/usage'),
|
|
329
340
|
])
|
|
330
341
|
void cr
|
|
342
|
+
const usage = u.status === 'fulfilled' ? u.value : null
|
|
331
343
|
const credits = c.status === 'fulfilled' ? c.value : null
|
|
332
344
|
const checkin = k.status === 'fulfilled' ? k.value : null
|
|
333
345
|
const accounts = a.status === 'fulfilled' && Array.isArray(a.value?.accounts) ? a.value.accounts : []
|
|
@@ -360,6 +372,11 @@ async function buildPatch(zh) {
|
|
|
360
372
|
action: { id: 'switch-account', args: { account: String(x.id) } },
|
|
361
373
|
}
|
|
362
374
|
}),
|
|
375
|
+
usageCats: (() => { const h = usage?.hours ?? {}; return Object.keys(h).sort((x, y) => Number(x) - Number(y)).map((k) => `${Number(k)}时`) })(),
|
|
376
|
+
usageVals: (() => { const h = usage?.hours ?? {}; return Object.keys(h).sort((x, y) => Number(x) - Number(y)).map((k) => Number(h[k]?.totalTokens ?? 0)) })(),
|
|
377
|
+
usageRequests: Number(usage?.requests ?? 0),
|
|
378
|
+
usageTokens: Number(usage?.totalTokens ?? 0),
|
|
379
|
+
hasUsage: usage !== null && Object.keys(usage?.hours ?? {}).length > 0,
|
|
363
380
|
note: zh ? `数据来自本机 WorkBuddy 登录态 · ${new Date().toLocaleTimeString('zh-CN', { hour12: false })} 更新` : 'Updated',
|
|
364
381
|
noteTone: credits === null ? 'warn' : 'info',
|
|
365
382
|
}
|
|
@@ -382,6 +399,11 @@ function mainPanel(ctx) {
|
|
|
382
399
|
[zh ? '今日获得' : 'Earned today', { $: 'data.todayCreditText' }],
|
|
383
400
|
[zh ? '即将过期' : 'Expiring', { $: 'data.expiringText' }],
|
|
384
401
|
] },
|
|
402
|
+
{ type: 'keyValue', items: [
|
|
403
|
+
[zh ? '今日请求' : 'Requests today', { $: 'data.usageRequests' }],
|
|
404
|
+
[zh ? '今日 tokens' : 'Tokens today', { $: 'data.usageTokens' }],
|
|
405
|
+
] },
|
|
406
|
+
{ type: 'chart', kind: 'bar', categories: { $: 'data.usageCats' }, series: [{ values: { $: 'data.usageVals' } }], unit: 'tokens', caption: zh ? '今日按小时(本机账本)' : 'today by hour (local ledger)' },
|
|
385
407
|
{ type: 'list', items: { $: 'data.packages' } },
|
|
386
408
|
{ type: 'callout', text: { $: 'data.note' }, tone: { $: 'data.noteTone' } },
|
|
387
409
|
{ type: 'text', text: { $: 'data.accountNote' }, tone: 'muted' },
|
|
@@ -490,8 +512,10 @@ export function apply(ctx) {
|
|
|
490
512
|
|
|
491
513
|
|
|
492
514
|
ctx.dshGo.strip('state', (scope, emit, caps) => {
|
|
515
|
+
stripGen += 1
|
|
493
516
|
stripEmit = typeof emit === 'function' ? emit : null
|
|
494
517
|
stripLocale = String(caps?.locale ?? 'zh')
|
|
518
|
+
stripFails = 0
|
|
495
519
|
void pushStrip()
|
|
496
520
|
void autoCheckin()
|
|
497
521
|
restartStripTimer()
|
|
@@ -501,6 +525,7 @@ export function apply(ctx) {
|
|
|
501
525
|
stripTimer = null
|
|
502
526
|
clearInterval(autoTimer)
|
|
503
527
|
stripEmit = null
|
|
528
|
+
stripGen += 1 // 让在途的 pushStrip 结果作废
|
|
504
529
|
}
|
|
505
530
|
})
|
|
506
531
|
|