dsh-go-workbuddy 1.0.2 → 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 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
@@ -277,25 +277,36 @@ async function setAutoEnabled(on) {
277
277
  } catch {}
278
278
  }
279
279
 
280
- // 自动签到:引擎在线时每 30 分钟检查一次,按本机日期去重;只写自己账号,静默执行。
281
- let autoCheckinDay = ''
280
+ // 自动签到:引擎在线时每 30 分钟检查一次,遍历本区域所有账号逐个签到(全账号)。
281
+ // 去重 key = 日期 + 账号,互不影响;服务端也按天去重,重载后重复检查不会重复领取。
282
+ const autoCheckinDays = new Set()
282
283
  async function autoCheckin() {
283
284
  if (!(await autoEnabled())) return
284
285
  const d = new Date()
285
- const key = `${region}-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
286
- if (key === autoCheckinDay) return
286
+ const dayKey = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
287
+ // 拉本区域所有账号;拿不到列表时退回只签当前账号
288
+ let accounts = []
287
289
  try {
288
- const before = await api(`/api/checkin?region=${region}${accountQuery()}`)
289
- if (before?.todayCheckedIn === true) {
290
- autoCheckinDay = key
291
- return
292
- }
293
- const answer = await api(`/api/checkin?region=${region}${accountQuery()}`, { method: 'POST', body: '{}' })
294
- if (answer?.claim !== undefined || before?.todayCheckedIn === true) {
295
- autoCheckinDay = key
296
- await pushStrip()
297
- }
290
+ const snap = await api(`/api/accounts?region=${region}`)
291
+ accounts = Array.isArray(snap?.accounts) ? snap.accounts : []
298
292
  } catch {}
293
+ if (accounts.length === 0 && accountId !== '') accounts = [{ id: accountId }]
294
+ for (const acc of accounts) {
295
+ const aid = String(acc?.id ?? '')
296
+ if (aid === '') continue
297
+ const key = `${region}-${dayKey}-${aid}`
298
+ if (autoCheckinDays.has(key)) continue
299
+ try {
300
+ const q = `&account=${encodeURIComponent(aid)}`
301
+ const before = await api(`/api/checkin?region=${region}${q}`)
302
+ if (before?.todayCheckedIn === true) { autoCheckinDays.add(key); continue }
303
+ const answer = await api(`/api/checkin?region=${region}${q}`, { method: 'POST', body: '{}' })
304
+ if (answer?.claim !== undefined || before?.todayCheckedIn === true) {
305
+ autoCheckinDays.add(key)
306
+ await pushStrip()
307
+ }
308
+ } catch {}
309
+ }
299
310
  }
300
311
 
301
312
  function noteOf(error, zh) {
@@ -310,13 +321,15 @@ function noteOf(error, zh) {
310
321
  async function buildPatch(zh) {
311
322
  const acct = accountId
312
323
  const q = `${acct === '' ? '' : '&account=' + encodeURIComponent(acct)}&force=1`
313
- const [c, k, a, cr] = await Promise.allSettled([
324
+ const [c, k, a, cr, u] = await Promise.allSettled([
314
325
  api(`/api/credits?region=${region}${q}`),
315
326
  api(`/api/checkin?region=${region}${q}`),
316
327
  api(`/api/accounts?region=${region}`),
317
328
  api('/api/cache/clear'),
329
+ api('/api/usage'),
318
330
  ])
319
331
  void cr
332
+ const usage = u.status === 'fulfilled' ? u.value : null
320
333
  const credits = c.status === 'fulfilled' ? c.value : null
321
334
  const checkin = k.status === 'fulfilled' ? k.value : null
322
335
  const accounts = a.status === 'fulfilled' && Array.isArray(a.value?.accounts) ? a.value.accounts : []
@@ -349,6 +362,11 @@ async function buildPatch(zh) {
349
362
  action: { id: 'switch-account', args: { account: String(x.id) } },
350
363
  }
351
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,
352
370
  note: zh ? `数据来自本机 WorkBuddy 登录态 · ${new Date().toLocaleTimeString('zh-CN', { hour12: false })} 更新` : 'Updated',
353
371
  noteTone: credits === null ? 'warn' : 'info',
354
372
  }
@@ -371,6 +389,11 @@ function mainPanel(ctx) {
371
389
  [zh ? '今日获得' : 'Earned today', { $: 'data.todayCreditText' }],
372
390
  [zh ? '即将过期' : 'Expiring', { $: 'data.expiringText' }],
373
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)' },
374
397
  { type: 'list', items: { $: 'data.packages' } },
375
398
  { type: 'callout', text: { $: 'data.note' }, tone: { $: 'data.noteTone' } },
376
399
  { type: 'text', text: { $: 'data.accountNote' }, tone: 'muted' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-go-workbuddy",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "main": "lib/index.js",
6
6
  "dsh": {