@hyprnos/dsh-remote-plugin 0.0.0-stage → 0.8.8

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.
Files changed (210) hide show
  1. package/README.en.md +61 -0
  2. package/README.md +60 -2
  3. package/apk/dsh-remote.apk +0 -0
  4. package/approval-summary.mjs +115 -0
  5. package/client.js +197 -0
  6. package/cordis.patch.yml +5 -0
  7. package/doctor-skill.mjs +99 -0
  8. package/doctor-target.mjs +24 -0
  9. package/file-delivery.mjs +84 -0
  10. package/gateway-stats.cjs +501 -0
  11. package/gateway.cjs +8451 -0
  12. package/index.mjs +1784 -0
  13. package/insights.mjs +111 -0
  14. package/market.mjs +86 -0
  15. package/package.json +71 -4
  16. package/peak-reminders.mjs +50 -0
  17. package/plugin-center.mjs +777 -0
  18. package/plugin-transaction.mjs +300 -0
  19. package/public/activity.js +188 -0
  20. package/public/admin.html +820 -0
  21. package/public/admin.js +1167 -0
  22. package/public/announcement-forms.js +89 -0
  23. package/public/announcements.json +464 -0
  24. package/public/app.js +8826 -0
  25. package/public/approval-records.js +301 -0
  26. package/public/approval-summary.js +78 -0
  27. package/public/build.json +5 -0
  28. package/public/cache-upgrade.js +51 -0
  29. package/public/chat-copy.js +59 -0
  30. package/public/chat-files.js +87 -0
  31. package/public/desktop/desktop.css +816 -0
  32. package/public/desktop/desktop.html +871 -0
  33. package/public/desktop/desktop.js +4548 -0
  34. package/public/desktop/i18n.js +85 -0
  35. package/public/diagnostics.js +203 -0
  36. package/public/doctor-entry.js +94 -0
  37. package/public/doctor.css +205 -0
  38. package/public/doctor.js +769 -0
  39. package/public/donate.png +0 -0
  40. package/public/e2ee-transport.js +219 -0
  41. package/public/extensions.css +109 -0
  42. package/public/extensions.js +215 -0
  43. package/public/file-inbox.css +66 -0
  44. package/public/file-inbox.js +289 -0
  45. package/public/genui.css +8 -0
  46. package/public/genui.js +254 -0
  47. package/public/history.js +304 -0
  48. package/public/i18n.js +57 -0
  49. package/public/icon.svg +12 -0
  50. package/public/image-cache.js +141 -0
  51. package/public/image-preview.js +290 -0
  52. package/public/index.html +1548 -0
  53. package/public/insights.css +28 -0
  54. package/public/insights.js +290 -0
  55. package/public/jsqr.min.js +10104 -0
  56. package/public/lan-discovery.js +94 -0
  57. package/public/link-check.js +109 -0
  58. package/public/manifest.webmanifest +16 -0
  59. package/public/md.js +333 -0
  60. package/public/morphicons-init.js +41 -0
  61. package/public/motion.js +557 -0
  62. package/public/network.js +100 -0
  63. package/public/onboarding.css +36 -0
  64. package/public/onboarding.js +253 -0
  65. package/public/operations.js +141 -0
  66. package/public/permission-presets.js +159 -0
  67. package/public/plugin-center.css +120 -0
  68. package/public/plugin-center.js +666 -0
  69. package/public/plugin-icon.svg +5 -0
  70. package/public/plugin.html +68 -0
  71. package/public/plugin.js +211 -0
  72. package/public/qrcode.min.js +2297 -0
  73. package/public/relay-autopair.js +251 -0
  74. package/public/relay-devices.js +80 -0
  75. package/public/relay-settings.css +24 -0
  76. package/public/relay-settings.js +194 -0
  77. package/public/remote-state.js +27 -0
  78. package/public/remote-ui.css +148 -0
  79. package/public/remote-ui.js +243 -0
  80. package/public/session-deck.css +79 -0
  81. package/public/session-deck.js +180 -0
  82. package/public/session-presets.js +47 -0
  83. package/public/setup.css +18 -0
  84. package/public/setup.js +213 -0
  85. package/public/sha256.js +119 -0
  86. package/public/skills.css +81 -0
  87. package/public/skills.js +202 -0
  88. package/public/skins/blue-fish/DESIGN.md +24 -0
  89. package/public/skins/blue-fish/face.png +0 -0
  90. package/public/skins/blue-fish/icon-blush.png +0 -0
  91. package/public/skins/blue-fish/icon-sleep.png +0 -0
  92. package/public/skins/blue-fish/icon-smile.png +0 -0
  93. package/public/skins/blue-fish/icon-star.png +0 -0
  94. package/public/skins/blue-fish/icon-wink.png +0 -0
  95. package/public/skins/blue-fish/icon.png +0 -0
  96. package/public/skins/blue-fish/mascot.png +0 -0
  97. package/public/skins/blue-fish/pattern.png +0 -0
  98. package/public/skins/blue-fish/preview.html +12 -0
  99. package/public/skins/blue-fish/skin.css +122 -0
  100. package/public/skins/blue-fish/sparkles.svg +18 -0
  101. package/public/skins/bocchi/DESIGN.md +99 -0
  102. package/public/skins/bocchi/face.png +0 -0
  103. package/public/skins/bocchi/grain.png +0 -0
  104. package/public/skins/bocchi/icon-blush.png +0 -0
  105. package/public/skins/bocchi/icon-sleep.png +0 -0
  106. package/public/skins/bocchi/icon-smile.png +0 -0
  107. package/public/skins/bocchi/icon-star.png +0 -0
  108. package/public/skins/bocchi/icon-wink.png +0 -0
  109. package/public/skins/bocchi/icon.png +0 -0
  110. package/public/skins/bocchi/pattern-soft.png +0 -0
  111. package/public/skins/bocchi/pattern.png +0 -0
  112. package/public/skins/bocchi/preview.html +55 -0
  113. package/public/skins/bocchi/skin.css +233 -0
  114. package/public/skins/bocchi/stage-bg.png +0 -0
  115. package/public/skins/bocchi/stage-soft.png +0 -0
  116. package/public/skins/bocchi/stand.png +0 -0
  117. package/public/skins/bocchi/sticker-guitar.png +0 -0
  118. package/public/skins/kessoku/DESIGN.md +38 -0
  119. package/public/skins/kessoku/grain.png +0 -0
  120. package/public/skins/kessoku/skin.css +212 -0
  121. package/public/skins/kita/SOURCES.json +51 -0
  122. package/public/skins/kita/face.png +0 -0
  123. package/public/skins/kita/icon-live.png +0 -0
  124. package/public/skins/kita/icon-reddress.png +0 -0
  125. package/public/skins/kita/icon-seifuku.png +0 -0
  126. package/public/skins/kita/pattern.png +0 -0
  127. package/public/skins/kita/preview.html +56 -0
  128. package/public/skins/kita/skin.css +26 -0
  129. package/public/skins/kita/stand.png +0 -0
  130. package/public/skins/kita/sticker-live.png +0 -0
  131. package/public/skins/nijika/SOURCES.json +51 -0
  132. package/public/skins/nijika/face.png +0 -0
  133. package/public/skins/nijika/icon-live.png +0 -0
  134. package/public/skins/nijika/icon-reddress.png +0 -0
  135. package/public/skins/nijika/icon-seifuku.png +0 -0
  136. package/public/skins/nijika/pattern.png +0 -0
  137. package/public/skins/nijika/preview.html +56 -0
  138. package/public/skins/nijika/skin.css +25 -0
  139. package/public/skins/nijika/stand.png +0 -0
  140. package/public/skins/nijika/sticker-live.png +0 -0
  141. package/public/skins/penguin/DESIGN.md +33 -0
  142. package/public/skins/penguin/SOURCES.json +22 -0
  143. package/public/skins/penguin/aic-blueprint.svg +24 -0
  144. package/public/skins/penguin/endfield-triangles.svg +4 -0
  145. package/public/skins/penguin/face.png +0 -0
  146. package/public/skins/penguin/icon-blush.png +0 -0
  147. package/public/skins/penguin/icon-dizzy.png +0 -0
  148. package/public/skins/penguin/icon-laugh.png +0 -0
  149. package/public/skins/penguin/icon-sleep.png +0 -0
  150. package/public/skins/penguin/icon-smile.png +0 -0
  151. package/public/skins/penguin/icon-star.png +0 -0
  152. package/public/skins/penguin/icon-wink.png +0 -0
  153. package/public/skins/penguin/icon.png +0 -0
  154. package/public/skins/penguin/mascot.png +0 -0
  155. package/public/skins/penguin/pattern-night.png +0 -0
  156. package/public/skins/penguin/pattern.png +0 -0
  157. package/public/skins/penguin/preview.html +12 -0
  158. package/public/skins/penguin/skin.css +212 -0
  159. package/public/skins/ryo/SOURCES.json +51 -0
  160. package/public/skins/ryo/face.png +0 -0
  161. package/public/skins/ryo/icon-live.png +0 -0
  162. package/public/skins/ryo/icon-reddress.png +0 -0
  163. package/public/skins/ryo/icon-seifuku.png +0 -0
  164. package/public/skins/ryo/pattern.png +0 -0
  165. package/public/skins/ryo/preview.html +56 -0
  166. package/public/skins/ryo/skin.css +25 -0
  167. package/public/skins/ryo/stand.png +0 -0
  168. package/public/skins/ryo/sticker-live.png +0 -0
  169. package/public/sponsor-entry.js +21 -0
  170. package/public/styles.css +1494 -0
  171. package/public/subagents.css +61 -0
  172. package/public/subagents.js +275 -0
  173. package/public/task-board.js +109 -0
  174. package/public/teams.js +98 -0
  175. package/public/theme-picker.css +58 -0
  176. package/public/theme-vars.css +1044 -0
  177. package/public/theme.js +166 -0
  178. package/public/transcribe-core.js +74 -0
  179. package/public/turn-results.js +121 -0
  180. package/public/update.json +49 -0
  181. package/public/vendor/gsap/NOTICE.md +10 -0
  182. package/public/vendor/gsap/gsap.min.js +11 -0
  183. package/public/vendor/morphicons/LICENSE +21 -0
  184. package/public/vendor/morphicons/README.md +10 -0
  185. package/public/vendor/morphicons/controller-CXZuwJ_M.js +152 -0
  186. package/public/vendor/morphicons/dom.js +206 -0
  187. package/public/vendor/morphicons/element.js +261 -0
  188. package/public/vendor/morphicons/normalize-CYnN3Npw.js +540 -0
  189. package/public/vendor/morphicons/spring-CFHloqPP.js +623 -0
  190. package/public/version.json +3 -0
  191. package/public/voice-input.js +739 -0
  192. package/public/workflow.css +365 -0
  193. package/public/workflow.js +409 -0
  194. package/session-file.mjs +39 -0
  195. package/skills/dsh-remote-doctor/SKILL.md +186 -0
  196. package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
  197. package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
  198. package/skills/dsh-remote-doctor/references/wiki/connection.md +76 -0
  199. package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
  200. package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
  201. package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
  202. package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
  203. package/skills/dsh-remote-doctor/references/wiki/notifications.md +33 -0
  204. package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
  205. package/skills/dsh-remote-doctor/references/wiki/plugins.md +90 -0
  206. package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
  207. package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
  208. package/skills.mjs +53 -0
  209. package/task-board.mjs +57 -0
  210. package/teams.mjs +58 -0
@@ -0,0 +1,84 @@
1
+ // DSH model-facing file delivery tools. Host services are optional; no SDK dependency.
2
+ import { createHash } from 'node:crypto'
3
+ import { realpathSync } from 'node:fs'
4
+ import { isAbsolute, relative, resolve, sep } from 'node:path'
5
+
6
+ const description = 'Send a single existing local file to a paired DSH Remote device. The recipient must explicitly accept before downloading. A queued delivery is NOT a successful receipt. Use remote_devices first and remote_file_status to check results. Do not repeatedly send after an uncertain response.'
7
+ const objectSchema = properties => ({ type: 'object', additionalProperties: false, properties })
8
+ const string = description => ({ type: 'string', description })
9
+ const output = {
10
+ schema: { ...objectSchema({ ok: { type: 'boolean' }, message: { type: 'string' }, details: { type: 'string' } }), required: ['ok', 'message', 'details'] },
11
+ render: (_args, value) => [{ type: 'text', text: value.message + '\n' + value.details }],
12
+ }
13
+ const result = (value, message) => ({ ok: true, message, details: JSON.stringify(value) })
14
+ export function createDeliveryTools(ctx, request) {
15
+ const context = exec => {
16
+ const sessionId = exec?.agent?.session?.id
17
+ if (!sessionId || !exec.callId) throw new Error('Remote 文件工具需要有效的 DSH 会话与工具调用编号')
18
+ exec.signal?.throwIfAborted()
19
+ return sessionId
20
+ }
21
+ const definition = (name, description, properties, required, execute) => ({ name, description, parameters: { ...objectSchema(properties), required }, output, execute, timeoutMs: 60000 })
22
+ return [
23
+ definition('remote_devices', 'List paired Remote receiving devices, including offline devices. Ask the user which device to use if ambiguous. Devices appear after opening the Remote file inbox.', {}, [], async (args, exec) => {
24
+ context(exec)
25
+ if (!args || Object.keys(args).length) throw new Error('remote_devices 不接受参数')
26
+ return result(await request('GET', null, exec.signal), '选择明确的接收设备;离线设备可以暂存文件,24 小时内打开 Remote 接收。')
27
+ }),
28
+ definition('remote_send_file', description, { path: string('Existing local regular file inside the calling session working directory, at most 50 MiB.'), device_id: string('Exact receiver id returned by remote_devices.'), title: string('Short title for the recipient.'), message: string('Optional explanation for the recipient, at most 600 characters.') }, ['path', 'device_id'], async (args, exec) => {
29
+ const sessionId = context(exec)
30
+ if (!args || Object.keys(args).some(k => !['path', 'device_id', 'title', 'message'].includes(k)) || typeof args.path !== 'string' || !args.path.trim() || typeof args.device_id !== 'string' || !args.device_id || args.title !== undefined && (typeof args.title !== 'string' || args.title.length > 120) || args.message !== undefined && (typeof args.message !== 'string' || args.message.length > 600)) throw new Error('文件、设备编号或说明参数无效')
31
+ // Resolve in the session's execution world first. Remote v1 additionally
32
+ // requires a host-local path under the current working directory.
33
+ const cwd = await ctx.workingDirectory.ensure(exec.agent, exec.signal)
34
+ const target = await ctx.fs.resolve(args.path, { cwd, signal: exec.signal })
35
+ const info = await ctx.fs.stat(target, exec.signal)
36
+ if (!info || info.type !== 'file' || info.size > 50 * 1024 * 1024) throw new Error('仅支持不超过 50 MiB 的本地普通文件')
37
+ const local = ctx.fs.processPath(target)
38
+ if (!isAbsolute(local) || !isAbsolute(cwd)) throw new Error('第一版仅支持主机本地工作目录中的文件')
39
+ const workspaceRoot = realpathSync(cwd), source = realpathSync(local), rel = relative(workspaceRoot, source)
40
+ if (!rel || rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)) throw new Error('文件必须位于当前会话工作目录内,不能通过链接越界')
41
+ exec.signal?.throwIfAborted()
42
+ const id = createHash('sha256').update(sessionId + '\0' + exec.callId).digest('hex')
43
+ try {
44
+ const receipt = await request('POST', { action: 'send', id, path: resolve(source), workspaceRoot, deviceId: args.device_id, sessionId, title: args.title || '', message: args.message || '' }, exec.signal)
45
+ return result(receipt, '文件已投递待确认,尚未接收。使用 remote_file_status 查询;不要报告已保存。')
46
+ } catch (error) {
47
+ if (error.confirmed) throw error
48
+ throw new Error('投递结果未确认,请勿重复发送。使用 remote_file_status 查询编号:' + id)
49
+ }
50
+ }),
51
+ definition('remote_file_status', 'Check a delivery from this session. pending/accepted/downloading are not success; downloaded means handed to a browser, complete means the device reported saving it.', { transfer_id: string('Transfer id from remote_send_file, including an uncertain send error.') }, ['transfer_id'], async (args, exec) => {
52
+ const sessionId = context(exec)
53
+ if (!args || Object.keys(args).some(k => k !== 'transfer_id') || typeof args.transfer_id !== 'string' || !/^[a-zA-Z0-9-]{16,80}$/.test(args.transfer_id)) throw new Error('传输编号无效')
54
+ return result(await request('POST', { action: 'status', id: args.transfer_id, sessionId }, exec.signal), '状态以接收设备回执为准;downloaded 只表示交给浏览器保存,不能证明文件已落盘。')
55
+ }),
56
+ ]
57
+ }
58
+
59
+ export function registerFileDeliveryTools(ctx, { gatewayBase, gatewayToken, fetchImpl = fetch }) {
60
+ if (typeof ctx.inject !== 'function') return false
61
+ ctx.inject(['tools', 'fs', 'workingDirectory'], child => {
62
+ const service = name => child.get?.(name) ?? child[name]
63
+ const scoped = { fs: service('fs'), workingDirectory: service('workingDirectory') }
64
+ const tools = service('tools')
65
+ if (!tools?.register || !scoped.fs?.resolve || !scoped.workingDirectory?.ensure) return
66
+ const request = async (method, body, signal) => {
67
+ const token = gatewayToken()
68
+ if (!token) throw Object.assign(new Error('Remote 网关尚未就绪,请先启动网关'), { confirmed: true })
69
+ const timeout = AbortSignal.timeout(55000)
70
+ const combined = new AbortController()
71
+ const abort = () => combined.abort()
72
+ signal?.addEventListener('abort', abort, { once: true }); timeout.addEventListener('abort', abort, { once: true })
73
+ if (signal?.aborted) abort()
74
+ try {
75
+ const response = await fetchImpl(gatewayBase() + '/admin/api/file-inbox', { method, headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}), signal: combined.signal, redirect: 'error' })
76
+ const data = await response.json()
77
+ if (!response.ok) throw Object.assign(new Error('Remote 文件投递被拒绝:' + String(data.error || response.status).slice(0, 100)), { confirmed: response.status < 500 })
78
+ return data
79
+ } finally { signal?.removeEventListener('abort', abort); timeout.removeEventListener('abort', abort) }
80
+ }
81
+ for (const definition of createDeliveryTools(scoped, request)) child.effect(() => tools.register(definition), 'dsh-remote: ' + definition.name)
82
+ })
83
+ return true
84
+ }
@@ -0,0 +1,501 @@
1
+ /* DSH Remote 统计核心 —— 零依赖
2
+ *
3
+ * 事件来源:
4
+ * - 插件进程实时监听 DSH 'session/event' (assistant/message + usage) -> POST /stats/ingest
5
+ * - 网关扫描 ~/.dsh/sessions 下的 session.jsonl.zstd 历史回填(启动全量 + 定期增量)
6
+ *
7
+ * 聚合:
8
+ * time(UTC 毫秒) -> Asia/Shanghai(固定 UTC+8, 无夏令时) -> 日 × 小时 × 模型
9
+ * 时段: 工作日高峰 9:00-12:00 / 14:00-18:00(含起点, 不含终点), 周末全天空闲
10
+ * 四桶: input(未缓存输入) / cacheRead(缓存命中读) / cacheWrite(缓存写) / output(输出)
11
+ *
12
+ * 存储:
13
+ * ~/.dsh-remote/stats/days/YYYY-MM-DD.json 按天一个文件, 内含 hours
14
+ * ~/.dsh-remote/stats/cursors.json 每个 session 已处理的最大 seq(幂等游标)
15
+ *
16
+ * 费用: 固定价格表(元 / 百万 tokens), v2 将改为可配置。
17
+ */
18
+ 'use strict'
19
+
20
+ const fs = require('node:fs')
21
+ const path = require('node:path')
22
+ const os = require('node:os')
23
+ const { spawn } = require('node:child_process')
24
+ const readline = require('node:readline')
25
+ const zlib = require('node:zlib')
26
+
27
+ function logGeneration(file) {
28
+ const match = /^session(?:\.v([1-9]\d*))?\.jsonl(?:\.zstd)?$/.exec(path.basename(file))
29
+ return match && Number.isSafeInteger(Number(match[1] || 0)) ? Number(match[1] || 0) : null
30
+ }
31
+
32
+ // V3 preserves message IDs, times and usage while renumbering durable seqs.
33
+ function usageIdentity(event) {
34
+ return JSON.stringify([event.data?.message?.id || '', event.time, normalizeUsage(event)])
35
+ }
36
+
37
+ // ---------- 固定价格表(v1 硬编码; v2 将改为配置文件/环境变量) ----------
38
+ // 时段判定: 工作日北京时间 9:00-12:00 与 14:00-18:00 为高峰(含起点不含终点),周末全天谷时
39
+ const PEAK_HOURS = [[9, 12], [14, 18]]
40
+ const PRICES = {
41
+ 'deepseek-v4-flash': {
42
+ inputCacheHit: { peak: 0.10, off: 0.05 },
43
+ inputMiss: { peak: 3.0, off: 1.5 },
44
+ output: { peak: 9.0, off: 4.5 },
45
+ },
46
+ 'deepseek-v4-pro': {
47
+ inputCacheHit: { peak: 0.30, off: 0.15 },
48
+ inputMiss: { peak: 9.0, off: 4.5 },
49
+ output: { peak: 27.0, off: 13.5 },
50
+ },
51
+ }
52
+ // 缓存写入按未命中输入价计费(DeepSeek 缓存写入以未命中输入计费)
53
+ const BUCKET_PRICE_KEY = {
54
+ input: 'inputMiss',
55
+ cacheRead: 'inputCacheHit',
56
+ cacheWrite: 'inputMiss',
57
+ output: 'output',
58
+ }
59
+
60
+ const BJ_OFFSET_MS = 8 * 3600 * 1000
61
+ // 定价生效日(北京时间): 2026-08-17 零点更新, 此前的 token 不计入费用统计
62
+ const PRICING_START_DATE = '2026-08-17'
63
+ const DAYS_DIR = 'days'
64
+ const CURSORS_FILE = 'cursors.json'
65
+
66
+ function pad2(n) { return String(n).padStart(2, '0') }
67
+
68
+ /** UTC 毫秒 -> 北京小时(0-23)。固定 UTC+8, 不随服务器本地时区。 */
69
+ function beijingHour(timeMs) {
70
+ return new Date(timeMs + BJ_OFFSET_MS).getUTCHours()
71
+ }
72
+
73
+ /** UTC 毫秒 -> 北京自然日 'YYYY-MM-DD'。 */
74
+ function beijingDate(timeMs) {
75
+ const d = new Date(timeMs + BJ_OFFSET_MS)
76
+ return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())}`
77
+ }
78
+
79
+ /** 北京小时 -> 时段。 */
80
+ function periodOfHour(hour) {
81
+ for (const [start, end] of PEAK_HOURS) {
82
+ if (hour >= start && hour < end) return 'peak'
83
+ }
84
+ return 'off'
85
+ }
86
+
87
+ /** 北京自然日是否为周六/周日。 */
88
+ function isWeekendDate(date) {
89
+ const parts = String(date || '').split('-').map(Number)
90
+ if (parts.length !== 3 || parts.some(n => !Number.isInteger(n))) return false
91
+ const day = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2])).getUTCDay()
92
+ return day === 0 || day === 6
93
+ }
94
+
95
+ /** 北京日期 + 小时 -> 计费时段;周末全天谷时。 */
96
+ function periodOfDateHour(date, hour) {
97
+ return isWeekendDate(date) ? 'off' : periodOfHour(hour)
98
+ }
99
+
100
+ /** 时段单价; 未知模型返回全 0(统计照记, 费用为 0)。 */
101
+ function pricesFor(model) {
102
+ return PRICES[model] || null
103
+ }
104
+
105
+ function emptyBucket() {
106
+ return { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, cost: 0 }
107
+ }
108
+
109
+ function addTokens(bucket, key, tokens) {
110
+ if (typeof tokens === 'number' && Number.isFinite(tokens) && tokens > 0) {
111
+ bucket[key] += tokens
112
+ }
113
+ return bucket
114
+ }
115
+
116
+ /** 把一个 usage 事件累计进 bucket(含费用)。 */
117
+ function addUsage(bucket, model, period, usage) {
118
+ const prices = pricesFor(model)
119
+ const usageObj = usage || {}
120
+ for (const key of ['input', 'cacheRead', 'cacheWrite', 'output']) {
121
+ const tokens = usageObj[key]
122
+ if (typeof tokens !== 'number' || !Number.isFinite(tokens) || tokens <= 0) continue
123
+ bucket[key] += tokens
124
+ if (prices) {
125
+ const priceKey = BUCKET_PRICE_KEY[key]
126
+ bucket.cost += tokens / 1e6 * prices[priceKey][period]
127
+ }
128
+ }
129
+ return bucket
130
+ }
131
+
132
+ /** 按当前日期规则重算 bucket 费用,兼容升级前已按工作日价格写入的周末历史数据。 */
133
+ function pricedBucket(model, period, bucket) {
134
+ return addUsage(emptyBucket(), model, period, bucket)
135
+ }
136
+
137
+ function mergeBucket(dst, src) {
138
+ for (const key of ['input', 'cacheRead', 'cacheWrite', 'output', 'cost']) {
139
+ dst[key] += src[key]
140
+ }
141
+ return dst
142
+ }
143
+
144
+ /** 时段事件 -> 日/小时/模型聚合的 key。 */
145
+ function eventKey(timeMs) {
146
+ const date = beijingDate(timeMs)
147
+ const hour = beijingHour(timeMs)
148
+ return { date, hour, period: periodOfDateHour(date, hour) }
149
+ }
150
+
151
+ /** 事件里的模型: 优先 message.source.model。 */
152
+ function eventModel(event) {
153
+ try {
154
+ const m = event?.data?.message?.source?.model
155
+ if (typeof m === 'string' && m) return m
156
+ } catch {}
157
+ return ''
158
+ }
159
+
160
+ function normalizeUsage(event) {
161
+ const u = event?.data?.usage
162
+ if (!u || typeof u !== 'object') return null
163
+ return {
164
+ input: typeof u.inputTokens === 'number' && Number.isFinite(u.inputTokens) ? u.inputTokens : 0,
165
+ cacheRead: typeof u.cacheReadTokens === 'number' && Number.isFinite(u.cacheReadTokens) ? u.cacheReadTokens : 0,
166
+ cacheWrite: typeof u.cacheWriteTokens === 'number' && Number.isFinite(u.cacheWriteTokens) ? u.cacheWriteTokens : 0,
167
+ output: typeof u.outputTokens === 'number' && Number.isFinite(u.outputTokens) ? u.outputTokens : 0,
168
+ }
169
+ }
170
+
171
+ /** 汇总一天(hours) -> peak/off/total。 */
172
+ function summarizeDay(day) {
173
+ const peak = emptyBucket()
174
+ const off = emptyBucket()
175
+ for (const hourStr of Object.keys(day?.hours || {})) {
176
+ const hour = Number(hourStr)
177
+ const period = periodOfDateHour(day?.date, hour)
178
+ const target = period === 'peak' ? peak : off
179
+ for (const model of Object.keys(day.hours[hourStr] || {})) {
180
+ mergeBucket(target, pricedBucket(model, period, day.hours[hourStr][model]))
181
+ }
182
+ }
183
+ const total = emptyBucket()
184
+ mergeBucket(total, peak)
185
+ mergeBucket(total, off)
186
+ return { peak, off, total }
187
+ }
188
+
189
+ function dayTotals(day) {
190
+ const s = summarizeDay(day)
191
+ return s
192
+ }
193
+
194
+ function tokenKeyName(key) {
195
+ return { input: 'input', cacheRead: 'cacheRead', cacheWrite: 'cacheWrite', output: 'output' }[key] || key
196
+ }
197
+
198
+ /** 统计存储: 单文件按天 + 游标。写操作由网关单进程调用, 内部用同步队列串行化。 */
199
+ class StatsStore {
200
+ constructor(dir, options = {}) {
201
+ this.dir = dir || path.join(os.homedir(), '.dsh-remote', 'stats')
202
+ this.daysDir = path.join(this.dir, DAYS_DIR)
203
+ this.cursorsFile = path.join(this.dir, CURSORS_FILE)
204
+ this.spawn = typeof options.spawn === 'function' ? options.spawn : spawn
205
+ this.cursors = null
206
+ this.queue = Promise.resolve()
207
+ fs.mkdirSync(this.daysDir, { recursive: true })
208
+ }
209
+
210
+ _dayFile(date) { return path.join(this.daysDir, `${date}.json`) }
211
+
212
+ _loadDay(date) {
213
+ try {
214
+ return JSON.parse(fs.readFileSync(this._dayFile(date), 'utf8'))
215
+ } catch {
216
+ return { date, hours: {} }
217
+ }
218
+ }
219
+
220
+ _saveDay(day) {
221
+ const file = this._dayFile(day.date)
222
+ const tmp = file + '.tmp'
223
+ fs.mkdirSync(path.dirname(file), { recursive: true })
224
+ fs.writeFileSync(tmp, JSON.stringify(day))
225
+ fs.renameSync(tmp, file)
226
+ }
227
+
228
+ _loadCursors() {
229
+ if (this.cursors) return this.cursors
230
+ try {
231
+ this.cursors = JSON.parse(fs.readFileSync(this.cursorsFile, 'utf8'))
232
+ } catch {
233
+ this.cursors = {}
234
+ }
235
+ return this.cursors
236
+ }
237
+
238
+ _saveCursors() {
239
+ const tmp = this.cursorsFile + '.tmp'
240
+ fs.mkdirSync(path.dirname(this.cursorsFile), { recursive: true })
241
+ fs.writeFileSync(tmp, JSON.stringify(this.cursors))
242
+ fs.renameSync(tmp, this.cursorsFile)
243
+ }
244
+
245
+ _cursor(sessionId) {
246
+ const c = this._loadCursors()
247
+ const cur = c[sessionId]
248
+ if (cur && typeof cur.lastSeq === 'number') return cur
249
+ return null
250
+ }
251
+
252
+ _setCursor(sessionId, lastSeq, generation) {
253
+ const c = this._loadCursors()
254
+ c[sessionId] = { ...c[sessionId], lastSeq, updatedAt: Date.now(), ...(generation == null ? {} : { generation }) }
255
+ this._saveCursors()
256
+ }
257
+
258
+ /** 在串行队列里执行统计写操作。 */
259
+ _enqueue(fn) {
260
+ const run = this.queue.then(fn)
261
+ this.queue = run.catch(() => {})
262
+ return run
263
+ }
264
+
265
+ /**
266
+ * 处理单个 session 事件(已过滤为 assistant/message 且 usage 有效)。
267
+ * - seq <= cursor: 重复, 跳过
268
+ * - seq === cursor+1: 正常聚合
269
+ * - seq > cursor+1: gap, 不聚合, 等待扫描补漏
270
+ */
271
+ processEvent(sessionId, event, fallbackModel) {
272
+ const seq = typeof event.seq === 'number' ? event.seq : -1
273
+ const time = typeof event.time === 'number' ? event.time : Date.now()
274
+ const usage = normalizeUsage(event)
275
+ if (!usage || seq < 0) return { processed: false, gap: false, skip: true }
276
+ const cur = this._cursor(sessionId)
277
+ const lastSeq = cur ? cur.lastSeq : -1
278
+ if (seq <= lastSeq) return { processed: false, gap: false, skip: true }
279
+ if (seq > lastSeq + 1) return { processed: false, gap: true, skip: true }
280
+
281
+ const model = eventModel(event) || fallbackModel || 'unknown'
282
+ const { date, hour, period } = eventKey(time)
283
+ if (date < PRICING_START_DATE) {
284
+ // 定价生效日前的事件不计费,但必须推进游标;否则生效日后的第一条事件会被误判为 gap。
285
+ this._setCursor(sessionId, seq)
286
+ return { processed: false, gap: false, skip: true }
287
+ }
288
+ const day = this._loadDay(date)
289
+ const hourBucket = day.hours[hour] || (day.hours[hour] = {})
290
+ const modelBucket = hourBucket[model] || (hourBucket[model] = emptyBucket())
291
+ addUsage(modelBucket, model, period, usage)
292
+ this._saveDay(day)
293
+ this._setCursor(sessionId, seq)
294
+ return { processed: true, gap: false, skip: false }
295
+ }
296
+
297
+ /** 串行化版本(HTTP ingest 用)。 */
298
+ ingestEvent(sessionId, event, fallbackModel) {
299
+ return this._enqueue(() => this.processEvent(sessionId, event, fallbackModel))
300
+ }
301
+
302
+ /**
303
+ * 扫描一个 zstd 会话文件, 从游标后顺序处理。返回处理的事件数。
304
+ * 用系统 zstd 命令解压(项目约束: 不新增 npm 运行时依赖; Windows 无 zstd 时跳过)。
305
+ */
306
+ scanFile(file, onProgress) {
307
+ return this._enqueue(() => this._scanFile(file, onProgress))
308
+ }
309
+
310
+ async _readLog(file, visit) {
311
+ let input, source, child, childResult
312
+ if (!file.endsWith('.zstd')) input = fs.createReadStream(file)
313
+ else if (this.spawn === spawn && typeof zlib.createZstdDecompress === 'function') {
314
+ source = fs.createReadStream(file)
315
+ input = zlib.createZstdDecompress()
316
+ source.on('error', error => input.destroy(error))
317
+ source.pipe(input)
318
+ } else {
319
+ child = this.spawn('zstd', ['-dc', file], { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })
320
+ input = child.stdout
321
+ childResult = new Promise(resolve => {
322
+ child.once('close', code => resolve({ code }))
323
+ child.once('error', error => resolve({ error }))
324
+ })
325
+ child.on('error', error => input.destroy(error))
326
+ }
327
+ const rl = readline.createInterface({ input })
328
+ let lines = 0
329
+ try {
330
+ for await (const line of rl) {
331
+ if (!line.trim()) continue
332
+ const event = JSON.parse(line)
333
+ if (Number.isSafeInteger(event.seq)) visit(event)
334
+ if (++lines % 500 === 0) await new Promise(resolve => setImmediate(resolve))
335
+ }
336
+ if (childResult) {
337
+ const result = await childResult
338
+ if (result.error) throw result.error
339
+ if (result.code !== 0) throw new Error('zstd-decompression-failed')
340
+ }
341
+ } finally {
342
+ rl.close()
343
+ input.destroy()
344
+ source?.destroy()
345
+ child?.kill?.()
346
+ }
347
+ }
348
+
349
+ async _scanFile(file, onProgress) {
350
+ const sessionId = path.basename(path.dirname(file))
351
+ const cur = this._cursor(sessionId)
352
+ const generation = logGeneration(file) ?? 0
353
+ const migrated = cur && generation !== (cur.generation ?? 0)
354
+ let lastSeq = migrated ? -1 : (cur?.lastSeq ?? -1)
355
+ let processed = 0
356
+ let currentModel = ''
357
+ const dirtyDays = new Map()
358
+ const counted = new Map()
359
+ try {
360
+ if (migrated) {
361
+ // Read the preserved predecessor before advancing to a renumbered log.
362
+ // Missing predecessor is an explicit error, never a blind double count.
363
+ const names = await fs.promises.readdir(path.dirname(file))
364
+ const previous = names.find(name => logGeneration(name) === (cur.generation ?? 0))
365
+ if (!previous) throw new Error('stats-migration-source-missing')
366
+ await this._readLog(path.join(path.dirname(file), previous), event => {
367
+ if (event.seq <= cur.lastSeq && event.type === 'assistant/message' && normalizeUsage(event)) {
368
+ const key = usageIdentity(event)
369
+ counted.set(key, (counted.get(key) || 0) + 1)
370
+ }
371
+ })
372
+ }
373
+ await this._readLog(file, event => {
374
+ if (event.type === 'request/header' && event.data?.config?.model) currentModel = event.data.config.model
375
+ if (event.type === 'request/context' && event.data?.model) currentModel = event.data.model
376
+ if (event.seq <= lastSeq) return
377
+ lastSeq = event.seq
378
+ if (event.type !== 'assistant/message') return
379
+ const usage = normalizeUsage(event)
380
+ if (!usage) return
381
+ const key = usageIdentity(event)
382
+ if (counted.get(key)) { counted.set(key, counted.get(key) - 1); return }
383
+ const model = eventModel(event) || currentModel || 'unknown'
384
+ const { date, hour, period } = eventKey(event.time)
385
+ if (date < PRICING_START_DATE) return
386
+ // Stage detached buckets: a failed read must not mutate cached totals.
387
+ const day = dirtyDays.get(date) || JSON.parse(JSON.stringify(this._loadDay(date)))
388
+ dirtyDays.set(date, day)
389
+ const hourBucket = day.hours[hour] || (day.hours[hour] = {})
390
+ addUsage(hourBucket[model] || (hourBucket[model] = emptyBucket()), model, period, usage)
391
+ processed++
392
+ })
393
+ if ([...counted.values()].some(count => count > 0)) throw new Error('stats-migration-usage-mismatch')
394
+ for (const day of dirtyDays.values()) this._saveDay(day)
395
+ if (lastSeq >= 0) this._setCursor(sessionId, lastSeq, generation)
396
+ if (onProgress) onProgress({ sessionId, processed })
397
+ return { sessionId, processed }
398
+ } catch (error) {
399
+ return { sessionId, processed: 0, error: error.code || error.message }
400
+ }
401
+ }
402
+
403
+ /** 扫描 ~/.dsh/sessions 下全部 session.jsonl.zstd。 */
404
+ async scanAll(sessionsRoot, onProgress) {
405
+ const root = sessionsRoot || path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'sessions')
406
+ let files = []
407
+ try {
408
+ const walk = async (dir) => {
409
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true })
410
+ const logs = entries.filter(ent => ent.isFile() && logGeneration(ent.name) !== null)
411
+ .sort((a, b) => logGeneration(b.name) - logGeneration(a.name) || a.name.localeCompare(b.name))
412
+ if (logs.length) files.push(path.join(dir, logs[0].name))
413
+ for (const ent of entries) {
414
+ if (ent.isDirectory()) await walk(path.join(dir, ent.name))
415
+ }
416
+ }
417
+ await walk(root)
418
+ } catch (err) {
419
+ console.warn('[stats] 扫描会话目录失败: ' + (err.message || err))
420
+ return { files: 0, processed: 0 }
421
+ }
422
+ let processed = 0
423
+ const errors = []
424
+ // 串行扫描, 避免大量并发 zstd 子进程
425
+ for (const file of files) {
426
+ const out = await this.scanFile(file, onProgress)
427
+ processed += out.processed || 0
428
+ if (out.error) errors.push({ sessionId: out.sessionId, error: out.error })
429
+ }
430
+ return { files: files.length, processed, ...(errors.length ? { errors } : {}) }
431
+ }
432
+
433
+ summary(days) {
434
+ const n = Math.max(1, Math.min(Number(days) || 7, 90))
435
+ const out = []
436
+ // 查询窗口起点: 不早于定价生效日(生效日之前不统计)
437
+ const today = beijingDate(Date.now())
438
+ const startD = new Date(Date.now() + BJ_OFFSET_MS)
439
+ startD.setUTCDate(startD.getUTCDate() - (n - 1))
440
+ const windowStart = `${startD.getUTCFullYear()}-${pad2(startD.getUTCMonth() + 1)}-${pad2(startD.getUTCDate())}`
441
+ const first = windowStart > PRICING_START_DATE ? windowStart : PRICING_START_DATE
442
+ const [fy, fm, fd] = first.split('-').map(Number)
443
+ for (let cur = Date.UTC(fy, fm - 1, fd); ; cur += 86400_000) {
444
+ const date = beijingDate(cur)
445
+ if (date > today) break
446
+ const day = this._loadDay(date)
447
+ const s = dayTotals(day)
448
+ const byModel = {}
449
+ for (const hourStr of Object.keys(day.hours || {})) {
450
+ const period = periodOfDateHour(date, Number(hourStr))
451
+ for (const [model, bucket] of Object.entries(day.hours[hourStr])) {
452
+ const m = byModel[model] || (byModel[model] = { peak: emptyBucket(), off: emptyBucket(), total: emptyBucket() })
453
+ const priced = pricedBucket(model, period, bucket)
454
+ mergeBucket(m[period], priced)
455
+ mergeBucket(m.total, priced)
456
+ }
457
+ }
458
+ out.push({ date, ...s, byModel })
459
+ }
460
+ return out
461
+ }
462
+
463
+ detail(date) {
464
+ // 生效日前不返回统计(页面会展示空态与生效日提示)
465
+ const effective = date >= PRICING_START_DATE ? date : PRICING_START_DATE
466
+ const day = this._loadDay(effective)
467
+ const hours = []
468
+ for (let hour = 0; hour < 24; hour++) {
469
+ const period = periodOfDateHour(effective, hour)
470
+ const models = {}
471
+ const total = emptyBucket()
472
+ for (const [model, bucket] of Object.entries(day.hours[hour] || {})) {
473
+ models[model] = pricedBucket(model, period, bucket)
474
+ mergeBucket(total, models[model])
475
+ }
476
+ hours.push({ hour, period, models, total })
477
+ }
478
+ return { date: effective, pricingStart: PRICING_START_DATE, hours }
479
+ }
480
+ }
481
+
482
+ module.exports = {
483
+ BJ_OFFSET_MS,
484
+ PRICING_START_DATE,
485
+ PEAK_HOURS,
486
+ PRICES,
487
+ beijingHour,
488
+ beijingDate,
489
+ periodOfHour,
490
+ isWeekendDate,
491
+ periodOfDateHour,
492
+ emptyBucket,
493
+ addUsage,
494
+ pricedBucket,
495
+ summarizeDay,
496
+ dayTotals,
497
+ eventKey,
498
+ eventModel,
499
+ normalizeUsage,
500
+ StatsStore,
501
+ }