dsh-go-workbuddy 1.0.3 → 1.1.0
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 +13 -1
- 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
|
@@ -321,13 +321,15 @@ function noteOf(error, zh) {
|
|
|
321
321
|
async function buildPatch(zh) {
|
|
322
322
|
const acct = accountId
|
|
323
323
|
const q = `${acct === '' ? '' : '&account=' + encodeURIComponent(acct)}&force=1`
|
|
324
|
-
const [c, k, a, cr] = await Promise.allSettled([
|
|
324
|
+
const [c, k, a, cr, u] = await Promise.allSettled([
|
|
325
325
|
api(`/api/credits?region=${region}${q}`),
|
|
326
326
|
api(`/api/checkin?region=${region}${q}`),
|
|
327
327
|
api(`/api/accounts?region=${region}`),
|
|
328
328
|
api('/api/cache/clear'),
|
|
329
|
+
api('/api/usage'),
|
|
329
330
|
])
|
|
330
331
|
void cr
|
|
332
|
+
const usage = u.status === 'fulfilled' ? u.value : null
|
|
331
333
|
const credits = c.status === 'fulfilled' ? c.value : null
|
|
332
334
|
const checkin = k.status === 'fulfilled' ? k.value : null
|
|
333
335
|
const accounts = a.status === 'fulfilled' && Array.isArray(a.value?.accounts) ? a.value.accounts : []
|
|
@@ -360,6 +362,11 @@ async function buildPatch(zh) {
|
|
|
360
362
|
action: { id: 'switch-account', args: { account: String(x.id) } },
|
|
361
363
|
}
|
|
362
364
|
}),
|
|
365
|
+
usageCats: (() => { const h = usage?.hours ?? {}; return Object.keys(h).sort((x, y) => Number(x) - Number(y)).map((k) => `${Number(k)}时`) })(),
|
|
366
|
+
usageVals: (() => { const h = usage?.hours ?? {}; return Object.keys(h).sort((x, y) => Number(x) - Number(y)).map((k) => Number(h[k]?.totalTokens ?? 0)) })(),
|
|
367
|
+
usageRequests: Number(usage?.requests ?? 0),
|
|
368
|
+
usageTokens: Number(usage?.totalTokens ?? 0),
|
|
369
|
+
hasUsage: usage !== null && Object.keys(usage?.hours ?? {}).length > 0,
|
|
363
370
|
note: zh ? `数据来自本机 WorkBuddy 登录态 · ${new Date().toLocaleTimeString('zh-CN', { hour12: false })} 更新` : 'Updated',
|
|
364
371
|
noteTone: credits === null ? 'warn' : 'info',
|
|
365
372
|
}
|
|
@@ -382,6 +389,11 @@ function mainPanel(ctx) {
|
|
|
382
389
|
[zh ? '今日获得' : 'Earned today', { $: 'data.todayCreditText' }],
|
|
383
390
|
[zh ? '即将过期' : 'Expiring', { $: 'data.expiringText' }],
|
|
384
391
|
] },
|
|
392
|
+
{ type: 'keyValue', items: [
|
|
393
|
+
[zh ? '今日请求' : 'Requests today', { $: 'data.usageRequests' }],
|
|
394
|
+
[zh ? '今日 tokens' : 'Tokens today', { $: 'data.usageTokens' }],
|
|
395
|
+
] },
|
|
396
|
+
{ type: 'chart', kind: 'bar', categories: { $: 'data.usageCats' }, series: [{ values: { $: 'data.usageVals' } }], unit: 'tokens', caption: zh ? '今日按小时(本机账本)' : 'today by hour (local ledger)' },
|
|
385
397
|
{ type: 'list', items: { $: 'data.packages' } },
|
|
386
398
|
{ type: 'callout', text: { $: 'data.note' }, tone: { $: 'data.noteTone' } },
|
|
387
399
|
{ type: 'text', text: { $: 'data.accountNote' }, tone: 'muted' },
|