dsh-ta 0.2.0 → 0.3.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/usage/ledger.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Durable per-turn usage ledger for Ta sessions. */
2
- import { appendFileSync, mkdirSync, readFileSync } from 'node:fs'
2
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, unlinkSync } from 'node:fs'
3
3
  import { resolve } from 'node:path'
4
4
  import { isTaSession } from '../gates.js'
5
5
  import { readInternalSessions, todayText } from '../storage.js'
@@ -124,3 +124,37 @@ export function readUsageRecords(config, date) {
124
124
  return []
125
125
  }
126
126
  }
127
+
128
+
129
+ /**
130
+ * 清零本地花销账本:只删除 state/usage 下的日期 JSONL,不碰目录和其他文件。
131
+ * 返回删除的文件数、记录数和警告;TA 家未配置时什么都不做。
132
+ */
133
+ export function resetUsage(config) {
134
+ const home = config?.taHome
135
+ if (typeof home !== 'string' || home.length === 0) {
136
+ return { files: 0, records: 0, warnings: ['TA 的家尚未配置'] }
137
+ }
138
+ const directory = resolve(home, 'state/usage')
139
+ let entries
140
+ try {
141
+ entries = readdirSync(directory, { withFileTypes: true })
142
+ } catch {
143
+ return { files: 0, records: 0, warnings: [] }
144
+ }
145
+ let files = 0
146
+ let records = 0
147
+ const warnings = []
148
+ for (const entry of entries) {
149
+ if (!entry.isFile() || !/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(entry.name)) continue
150
+ const path = resolve(directory, entry.name)
151
+ try {
152
+ records += readFileSync(path, 'utf8').split(/\r?\n/).filter(Boolean).length
153
+ unlinkSync(path)
154
+ files += 1
155
+ } catch (cause) {
156
+ warnings.push(`删除 ${entry.name} 失败:${cause instanceof Error ? cause.message : String(cause)}`)
157
+ }
158
+ }
159
+ return { files, records, warnings }
160
+ }
package/usage/serve.js CHANGED
@@ -1,6 +1,54 @@
1
1
  import { aggregateUsage, usageCsv } from './aggregate.js'
2
+ import { resetUsage } from './ledger.js'
2
3
 
3
4
  const ROOT = '/api/dsh-ta/usage'
5
+ const BODY_LIMIT = 4096
6
+
7
+ function sendJson(response, status, payload) {
8
+ response.writeHead(status, {
9
+ 'content-type': 'application/json; charset=utf-8',
10
+ 'cache-control': 'no-store',
11
+ })
12
+ response.end(JSON.stringify(payload))
13
+ }
14
+
15
+ /** 读取很小的 JSON 确认体;超过上限或格式错误都走 4xx。 */
16
+ function readJsonBody(request) {
17
+ return new Promise((resolve, reject) => {
18
+ const chunks = []
19
+ let size = 0
20
+ let settled = false
21
+ const fail = (status, message) => {
22
+ if (settled) return
23
+ settled = true
24
+ reject(Object.assign(new Error(message), { status }))
25
+ }
26
+ request.on('data', chunk => {
27
+ if (settled) return
28
+ size += chunk.length
29
+ if (size > BODY_LIMIT) {
30
+ fail(413, '确认信息过大')
31
+ return
32
+ }
33
+ chunks.push(chunk)
34
+ })
35
+ request.on('end', () => {
36
+ if (settled) return
37
+ settled = true
38
+ const text = Buffer.concat(chunks).toString('utf8')
39
+ if (!text.trim()) {
40
+ resolve({})
41
+ return
42
+ }
43
+ try {
44
+ resolve(JSON.parse(text))
45
+ } catch {
46
+ fail(400, '确认信息不是合法 JSON')
47
+ }
48
+ })
49
+ request.on('error', () => fail(400, '读取请求失败'))
50
+ })
51
+ }
4
52
 
5
53
  export function mountUsageRoute(ctx, config) {
6
54
  if (typeof ctx.inject !== 'function') return
@@ -15,6 +63,36 @@ export function mountUsageRoute(ctx, config) {
15
63
  handler: (request, response) => {
16
64
  const url = new URL(request.url ?? '/', 'http://localhost')
17
65
  const suffix = url.pathname.slice(ROOT.length)
66
+ if (suffix === '/reset' || suffix === '/reset/') {
67
+ if (String(request.method ?? 'GET').toUpperCase() !== 'POST') {
68
+ response.setHeader?.('allow', 'POST')
69
+ sendJson(response, 405, {
70
+ ok: false,
71
+ error: { code: 'METHOD_NOT_ALLOWED', message: '清零只支持 POST' },
72
+ })
73
+ return
74
+ }
75
+ void readJsonBody(request).then(body => {
76
+ if (body?.confirm !== '清零') {
77
+ sendJson(response, 400, {
78
+ ok: false,
79
+ error: { code: 'RESET_CONFIRM_REQUIRED', message: '请输入“清零”确认' },
80
+ })
81
+ return
82
+ }
83
+ const result = resetUsage(config)
84
+ sendJson(response, 200, { ok: true, data: { cleared: true, ...result } })
85
+ }).catch(error => {
86
+ sendJson(response, error?.status === 413 ? 413 : 400, {
87
+ ok: false,
88
+ error: {
89
+ code: error?.status === 413 ? 'PAYLOAD_TOO_LARGE' : 'INVALID_JSON',
90
+ message: error instanceof Error ? error.message : '确认失败',
91
+ },
92
+ })
93
+ })
94
+ return
95
+ }
18
96
  const report = aggregateUsage(config, {
19
97
  from: url.searchParams.get('from') ?? undefined,
20
98
  to: url.searchParams.get('to') ?? undefined,