dsh-plugin-system-status 0.0.0-stage → 0.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.
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: system-status
3
+ name: 'dsh-plugin-system-status'
package/docs/DETAIL.md ADDED
@@ -0,0 +1,20 @@
1
+ # 系统状态
2
+
3
+ 在 DeepSeek Harness 里看这台机器的硬件状况:对话页输入框下方一条常驻的实时状态条,左侧栏一个图标进入历史曲线页。
4
+
5
+ ## 功能
6
+
7
+ - **实时条**(对话页,输入框下方):紧凑一行显示 CPU 利用率、内存已用/总量、GPU 利用率、显存已用/总量、GPU 温度,右侧「历史 ›」进入曲线页;数据断流时显示「重连中 / 数据已过期」。没有可用 GPU 时只显示一行「GPU 不可用」。
8
+ - **历史页**(左侧栏「系统状态」图标):CPU、GPU、内存、显存的使用率各自一张曲线图(纵轴按数据自动缩放,并在标题旁显示最新值),外加 GPU 温度曲线与各固定磁盘的已用空间;可切换近 1 小时、6 小时、24 小时、7 天,横轴是所选时间窗口(不是数据实际跨度),在图上移动可读出该时刻的具体数值。
9
+ - **降级**:没有 NVIDIA 显卡或 `nvidia-smi` 不在 PATH 上时,GPU 相关项显示「不可用」,其余指标照常;历史目录不可写时只保留实时数据。
10
+
11
+ ## 使用
12
+
13
+ 安装并启用后即时生效,无需重启 DSH。首次安装后刷新一次页面即可看到实时条与左侧栏图标。
14
+
15
+ ## 限制
16
+
17
+ - **采样频率**:每 3 秒一次;实时条随之每 3 秒刷新。
18
+ - **历史只在 DSH 运行时采样**:关掉 DSH、休眠、关机的时间段没有数据,曲线会在断档处断开。历史默认按天分文件保存在 `%DSH_HOME%/system-status/`,保留 7 天。
19
+ - **只有 GPU 温度**:Windows 的 ACPI 热区接口取不到可信的 CPU / 主板温度,需要 LibHardwareMonitor 这类带内核驱动的工具,本插件未接入。
20
+ - **数据面**:采样只在本机进行,HTTP 路由只返回数值(不包含机器名、用户名、路径),并且只监听 DSH 自己的回环地址。
package/host/gpu.js ADDED
@@ -0,0 +1,134 @@
1
+ import { spawn } from 'node:child_process'
2
+
3
+ /** Fields requested from nvidia-smi, in the order the CSV line reports them. */
4
+ const GPU_FIELDS = [
5
+ 'name',
6
+ 'memory.used',
7
+ 'memory.total',
8
+ 'utilization.gpu',
9
+ 'temperature.gpu',
10
+ 'power.draw',
11
+ 'fan.speed',
12
+ ]
13
+
14
+ /**
15
+ * Parse one `--format=csv,noheader,nounits` line from nvidia-smi into a GPU
16
+ * sample. Unavailable numeric fields become null; a line without a usable
17
+ * utilization or total VRAM is not a sample.
18
+ * @param {string} line raw CSV line
19
+ * @returns {{util: number, vramUsed: number, vramTotal: number, tempC: number | null, powerW: number | null} | null}
20
+ */
21
+ export function parseGpuLine(line) {
22
+ if (typeof line !== 'string') return null
23
+ const parts = line.trim().split(',').map((part) => part.trim())
24
+ if (parts.length < GPU_FIELDS.length) return null
25
+ const number = (text) => {
26
+ const value = Number(text)
27
+ return Number.isFinite(value) ? value : null
28
+ }
29
+ const vramUsed = number(parts[1])
30
+ const vramTotal = number(parts[2])
31
+ const util = number(parts[3])
32
+ if (util === null || vramTotal === null || vramTotal <= 0) return null
33
+ return {
34
+ util,
35
+ vramUsed: vramUsed ?? 0,
36
+ vramTotal,
37
+ tempC: number(parts[4]),
38
+ powerW: number(parts[5]),
39
+ }
40
+ }
41
+
42
+ /**
43
+ * A persistent nvidia-smi sampler. It keeps one `--loop-ms` child alive and
44
+ * caches the newest parsed sample, so a tick costs nothing when the child is
45
+ * healthy and a missing driver only degrades GPU data to null.
46
+ * @param {{command?: string, intervalMs?: number, retryMs?: number}} [options]
47
+ * @returns {{read: () => object | null, stop: () => void}}
48
+ */
49
+ export function createGpuSource({
50
+ command = 'nvidia-smi',
51
+ intervalMs = 1000,
52
+ retryMs = 60000,
53
+ spawnImpl = spawn,
54
+ } = {}) {
55
+ let latest = null
56
+ let latestAt = 0
57
+ let child = null
58
+ let retryTimer = null
59
+ let stopped = false
60
+ let buffer = ''
61
+
62
+ const scheduleRetry = () => {
63
+ if (stopped || retryTimer !== null) return
64
+ retryTimer = setTimeout(() => {
65
+ retryTimer = null
66
+ spawnChild()
67
+ }, retryMs)
68
+ retryTimer.unref?.()
69
+ }
70
+
71
+ const spawnChild = () => {
72
+ if (stopped) return
73
+ let started
74
+ try {
75
+ started = spawnImpl(
76
+ command,
77
+ [
78
+ `--query-gpu=${GPU_FIELDS.join(',')}`,
79
+ '--format=csv,noheader,nounits',
80
+ `--loop-ms=${intervalMs}`,
81
+ ],
82
+ { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] },
83
+ )
84
+ } catch {
85
+ scheduleRetry()
86
+ return
87
+ }
88
+ child = started
89
+ started.on('error', () => {
90
+ if (child === started) child = null
91
+ scheduleRetry()
92
+ })
93
+ started.on('exit', () => {
94
+ if (child === started) child = null
95
+ scheduleRetry()
96
+ })
97
+ started.stdout?.setEncoding('utf8')
98
+ started.stdout?.on('data', (chunk) => {
99
+ buffer += chunk
100
+ let at = buffer.indexOf('\n')
101
+ while (at !== -1) {
102
+ const line = buffer.slice(0, at)
103
+ buffer = buffer.slice(at + 1)
104
+ const parsed = parseGpuLine(line)
105
+ if (parsed !== null) {
106
+ latest = parsed
107
+ latestAt = Date.now()
108
+ }
109
+ at = buffer.indexOf('\n')
110
+ }
111
+ })
112
+ }
113
+
114
+ spawnChild()
115
+
116
+ return {
117
+ read: () => (latest === null ? null : { ...latest, at: latestAt }),
118
+ stop() {
119
+ stopped = true
120
+ if (retryTimer !== null) {
121
+ clearTimeout(retryTimer)
122
+ retryTimer = null
123
+ }
124
+ if (child !== null) {
125
+ try {
126
+ child.kill()
127
+ } catch {
128
+ /* already gone */
129
+ }
130
+ child = null
131
+ }
132
+ },
133
+ }
134
+ }
@@ -0,0 +1,290 @@
1
+ import { appendFile, mkdir, readdir, readFile, unlink } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+
4
+ const DAY_MS = 24 * 3600 * 1000
5
+ const FILE_RE = /^(\d{4})-(\d{2})-(\d{2})\.jsonl$/
6
+
7
+ /** Supported history windows, in milliseconds. */
8
+ export const RANGE_MS = {
9
+ '1h': 3600 * 1000,
10
+ '6h': 6 * 3600 * 1000,
11
+ '24h': 24 * 3600 * 1000,
12
+ '7d': 7 * 24 * 3600 * 1000,
13
+ }
14
+
15
+ /**
16
+ * Parse stored JSONL text into samples, skipping torn, malformed, or
17
+ * schema-incompatible lines instead of failing the whole read.
18
+ * @param {string} text file contents
19
+ * @returns {Array<object>} usable samples in file order
20
+ */
21
+ export function parseLines(text) {
22
+ const samples = []
23
+ for (const line of String(text).split('\n')) {
24
+ const trimmed = line.trim()
25
+ if (trimmed === '') continue
26
+ let value
27
+ try {
28
+ value = JSON.parse(trimmed)
29
+ } catch {
30
+ continue
31
+ }
32
+ if (value === null || typeof value !== 'object') continue
33
+ if (typeof value.t !== 'number') continue
34
+ if (typeof value.cpu?.total !== 'number') continue
35
+ if (typeof value.mem?.total !== 'number') continue
36
+ samples.push(value)
37
+ }
38
+ return samples
39
+ }
40
+
41
+ /**
42
+ * Uniformly thin a series down to at most `maxPoints`, keeping first and last
43
+ * because a chart's edges carry the window bounds.
44
+ * @param {Array<object>} samples
45
+ * @param {number} maxPoints
46
+ * @returns {Array<object>}
47
+ */
48
+ export function downsample(samples, maxPoints = 300) {
49
+ if (samples.length <= maxPoints) return samples
50
+ const step = (samples.length - 1) / (maxPoints - 1)
51
+ const result = []
52
+ for (let index = 0; index < maxPoints; index += 1) {
53
+ result.push(samples[Math.round(index * step)])
54
+ }
55
+ return result
56
+ }
57
+
58
+ const round1 = (value) => Math.round(value * 10) / 10
59
+
60
+ /**
61
+ * Average samples into fixed time buckets. A bucket with no sample is simply
62
+ * absent from the result, so the chart can draw the gap instead of a line
63
+ * across hours when DSH was not running.
64
+ * @param {Array<object>} samples
65
+ * @param {number} bucketMs
66
+ * @returns {Array<object>} bucketed samples, ascending
67
+ */
68
+ export function aggregate(samples, bucketMs) {
69
+ const buckets = new Map()
70
+ const field = () => ({ count: 0, sum: 0 })
71
+ const add = (target, value) => {
72
+ if (!Number.isFinite(value)) return
73
+ target.count += 1
74
+ target.sum += value
75
+ }
76
+ const mean = (target) => (target.count === 0 ? null : target.sum / target.count)
77
+ const ensure = (key) => {
78
+ let bucket = buckets.get(key)
79
+ if (bucket === undefined) {
80
+ bucket = {
81
+ count: 0,
82
+ cpuTotal: 0,
83
+ memUsed: 0,
84
+ memTotal: 0,
85
+ gpu: { util: field(), vramUsed: field(), vramTotal: field(), tempC: field(), powerW: field() },
86
+ disks: new Map(),
87
+ }
88
+ buckets.set(key, bucket)
89
+ }
90
+ return bucket
91
+ }
92
+ for (const sample of samples) {
93
+ const bucket = ensure(Math.floor(sample.t / bucketMs))
94
+ bucket.count += 1
95
+ bucket.cpuTotal += sample.cpu?.total ?? 0
96
+ bucket.memUsed += sample.mem?.used ?? 0
97
+ bucket.memTotal += sample.mem?.total ?? 0
98
+ if (sample.gpu) {
99
+ add(bucket.gpu.util, sample.gpu.util)
100
+ add(bucket.gpu.vramUsed, sample.gpu.vramUsed)
101
+ add(bucket.gpu.vramTotal, sample.gpu.vramTotal)
102
+ add(bucket.gpu.tempC, sample.gpu.tempC)
103
+ add(bucket.gpu.powerW, sample.gpu.powerW)
104
+ }
105
+ for (const disk of sample.disks ?? []) {
106
+ const accumulator = bucket.disks.get(disk.id) ?? { count: 0, total: 0, free: 0 }
107
+ accumulator.count += 1
108
+ accumulator.total += disk.total
109
+ accumulator.free += disk.free
110
+ bucket.disks.set(disk.id, accumulator)
111
+ }
112
+ }
113
+ return [...buckets.entries()]
114
+ .sort((left, right) => left[0] - right[0])
115
+ .map(([key, bucket]) => {
116
+ const gpu = {
117
+ util: mean(bucket.gpu.util),
118
+ vramUsed: mean(bucket.gpu.vramUsed),
119
+ vramTotal: mean(bucket.gpu.vramTotal),
120
+ tempC: mean(bucket.gpu.tempC),
121
+ powerW: mean(bucket.gpu.powerW),
122
+ }
123
+ const hasGpu = gpu.util !== null || gpu.vramUsed !== null || gpu.vramTotal !== null
124
+ return {
125
+ t: key * bucketMs,
126
+ cpu: { total: round1(bucket.cpuTotal / bucket.count), perCore: [] },
127
+ mem: {
128
+ used: Math.round(bucket.memUsed / bucket.count),
129
+ total: Math.round(bucket.memTotal / bucket.count),
130
+ },
131
+ gpu: hasGpu
132
+ ? {
133
+ util: gpu.util === null ? null : round1(gpu.util),
134
+ vramUsed: gpu.vramUsed === null ? null : Math.round(gpu.vramUsed),
135
+ vramTotal: gpu.vramTotal === null ? null : Math.round(gpu.vramTotal),
136
+ tempC: gpu.tempC === null ? null : round1(gpu.tempC),
137
+ powerW: gpu.powerW === null ? null : round1(gpu.powerW),
138
+ }
139
+ : null,
140
+ disks: [...bucket.disks.entries()].map(([id, accumulator]) => ({
141
+ id,
142
+ total: Math.round(accumulator.total / accumulator.count),
143
+ free: Math.round(accumulator.free / accumulator.count),
144
+ })),
145
+ }
146
+ })
147
+ }
148
+
149
+ const dayKey = (t) => {
150
+ const date = new Date(t)
151
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
152
+ date.getDate(),
153
+ ).padStart(2, '0')}`
154
+ }
155
+
156
+ /**
157
+ * Append-only per-day JSONL history under `dir`, with retention pruning and
158
+ * windowed reads. A directory it cannot create or write disables persistence
159
+ * (`disabled`) instead of throwing, so the live status keeps working.
160
+ * @param {{dir: string, retentionDays?: number, flushMs?: number, maxPoints?: number, now?: () => number, rangeMs?: Record<string, number>}} options
161
+ */
162
+ export function createHistoryStore({
163
+ dir,
164
+ retentionDays = 7,
165
+ flushMs = 5000,
166
+ maxPoints = 300,
167
+ now = () => Date.now(),
168
+ rangeMs = RANGE_MS,
169
+ } = {}) {
170
+ if (typeof dir !== 'string' || dir === '') throw new Error('history: dir is required')
171
+ let buffer = []
172
+ let disabled = false
173
+ let closed = false
174
+ let flushTimer = null
175
+ let pendingFlush = Promise.resolve()
176
+ let lastWriteAt = null
177
+
178
+ const fileFor = (t) => join(dir, `${dayKey(t)}.jsonl`)
179
+
180
+ async function flush() {
181
+ if (disabled || buffer.length === 0) return
182
+ const pending = buffer
183
+ buffer = []
184
+ const payload = pending.map((sample) => JSON.stringify(sample)).join('\n') + '\n'
185
+ const target = fileFor(pending[pending.length - 1].t)
186
+ pendingFlush = pendingFlush.then(async () => {
187
+ try {
188
+ await mkdir(dir, { recursive: true })
189
+ await appendFile(target, payload, 'utf8')
190
+ lastWriteAt = now()
191
+ } catch {
192
+ disabled = true
193
+ }
194
+ })
195
+ await pendingFlush
196
+ }
197
+
198
+ async function prune() {
199
+ try {
200
+ const cutoff = now() - retentionDays * DAY_MS
201
+ for (const name of await readdir(dir)) {
202
+ const match = FILE_RE.exec(name)
203
+ if (match === null) continue
204
+ const dayStart = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])).getTime()
205
+ if (dayStart < cutoff) await unlink(join(dir, name)).catch(() => {})
206
+ }
207
+ } catch {
208
+ /* nothing stored yet */
209
+ }
210
+ }
211
+
212
+ async function read(range = '1h') {
213
+ const windowMs = rangeMs[range] ?? rangeMs['1h']
214
+ const until = now()
215
+ const from = until - windowMs
216
+ const bucketMs = Math.max(1000, Math.ceil(windowMs / maxPoints))
217
+ const empty = (reason) => ({ points: [], from, until, bucketMs, disabled, reason, lastWriteAt })
218
+ let names = []
219
+ try {
220
+ names = await readdir(dir)
221
+ } catch (error) {
222
+ // A directory that does not exist yet is empty, not broken; anything else
223
+ // is a read failure the page must not present as "no data recorded".
224
+ if (error?.code === 'ENOENT') return empty(undefined)
225
+ return empty('unreadable')
226
+ }
227
+ const samples = []
228
+ for (const name of names) {
229
+ const match = FILE_RE.exec(name)
230
+ if (match === null) continue
231
+ const dayStart = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])).getTime()
232
+ if (dayStart + DAY_MS < from) continue
233
+ try {
234
+ const text = await readFile(join(dir, name), 'utf8')
235
+ for (const sample of parseLines(text)) {
236
+ if (sample.t >= from && sample.t <= until) samples.push(sample)
237
+ }
238
+ } catch {
239
+ /* unreadable file only loses its own samples */
240
+ }
241
+ }
242
+ samples.sort((left, right) => left.t - right.t)
243
+ return {
244
+ points: downsample(aggregate(samples, bucketMs), maxPoints),
245
+ from,
246
+ until,
247
+ bucketMs,
248
+ disabled,
249
+ reason: disabled ? 'unwritable' : undefined,
250
+ lastWriteAt,
251
+ }
252
+ }
253
+
254
+ async function close() {
255
+ closed = true
256
+ if (flushTimer !== null) {
257
+ clearInterval(flushTimer)
258
+ flushTimer = null
259
+ }
260
+ await flush()
261
+ }
262
+
263
+ flushTimer = setInterval(() => {
264
+ void flush()
265
+ }, flushMs)
266
+ flushTimer.unref?.()
267
+ void prune()
268
+
269
+ return {
270
+ /**
271
+ * @param {object} sample one sample in the documented shape
272
+ */
273
+ push(sample) {
274
+ if (disabled || closed) return
275
+ buffer.push(sample)
276
+ if (buffer.length >= 12) void flush()
277
+ },
278
+ flush,
279
+ read,
280
+ prune,
281
+ close,
282
+ get disabled() {
283
+ return disabled
284
+ },
285
+ get lastWriteAt() {
286
+ return lastWriteAt
287
+ },
288
+ buffered: () => buffer.length,
289
+ }
290
+ }
package/host/routes.js ADDED
@@ -0,0 +1,93 @@
1
+ export const STREAM_PATH = '/dsh-system-status/stream'
2
+ export const HISTORY_PATH = '/dsh-system-status/history'
3
+
4
+ /**
5
+ * Serve the live sample stream (SSE) and the windowed history JSON on two
6
+ * same-origin routes. The returned disposer removes both routes, unsubscribes
7
+ * from the sampler, and ends every open stream so a disabled plugin leaves no
8
+ * half-open connection behind.
9
+ * @param {{register: (route: object) => () => void}} webServer host web server service
10
+ * @param {{sampler: {subscribe: (fn: (sample: object) => void) => () => void}, history: {read: (range: string) => Promise<object>}}} sources
11
+ * @returns {() => void} disposer
12
+ */
13
+ export function registerRoutes(webServer, { sampler, history }) {
14
+ const clients = new Set()
15
+
16
+ const unsubscribe = sampler.subscribe((sample) => {
17
+ const frame = `data: ${JSON.stringify(sample)}\n\n`
18
+ for (const client of clients) {
19
+ try {
20
+ client.write(frame)
21
+ } catch {
22
+ clients.delete(client)
23
+ }
24
+ }
25
+ })
26
+
27
+ const releaseStream = webServer.register({
28
+ kind: 'exact',
29
+ path: STREAM_PATH,
30
+ handler(req, res) {
31
+ res.writeHead(200, {
32
+ 'content-type': 'text/event-stream; charset=utf-8',
33
+ 'cache-control': 'no-store',
34
+ connection: 'keep-alive',
35
+ 'x-accel-buffering': 'no',
36
+ })
37
+ res.write('retry: 3000\n\n')
38
+ clients.add(res)
39
+ req.on?.('close', () => {
40
+ clients.delete(res)
41
+ })
42
+ },
43
+ })
44
+
45
+ const releaseHistory = webServer.register({
46
+ kind: 'exact',
47
+ path: HISTORY_PATH,
48
+ async handler(req, res) {
49
+ let range = '1h'
50
+ try {
51
+ range = new URL(req.url ?? '/', 'http://local').searchParams.get('range') ?? '1h'
52
+ } catch {
53
+ /* keep the default window */
54
+ }
55
+ let payload
56
+ try {
57
+ payload = await history.read(range)
58
+ } catch {
59
+ // A read failure is not an empty history: say so with a status the page
60
+ // can distinguish from "nothing recorded".
61
+ const body = JSON.stringify({ error: 'read-failed', points: [] })
62
+ res.writeHead(500, {
63
+ 'content-type': 'application/json; charset=utf-8',
64
+ 'cache-control': 'no-store',
65
+ 'content-length': Buffer.byteLength(body),
66
+ })
67
+ res.end(body)
68
+ return
69
+ }
70
+ const body = JSON.stringify(payload)
71
+ res.writeHead(200, {
72
+ 'content-type': 'application/json; charset=utf-8',
73
+ 'cache-control': 'no-store',
74
+ 'content-length': Buffer.byteLength(body),
75
+ })
76
+ res.end(body)
77
+ },
78
+ })
79
+
80
+ return () => {
81
+ unsubscribe()
82
+ releaseStream()
83
+ releaseHistory()
84
+ for (const client of clients) {
85
+ try {
86
+ client.end()
87
+ } catch {
88
+ /* already closed by the peer */
89
+ }
90
+ }
91
+ clients.clear()
92
+ }
93
+ }
@@ -0,0 +1,139 @@
1
+ import os from 'node:os'
2
+ import { statfs } from 'node:fs/promises'
3
+
4
+ const DRIVE_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
5
+
6
+ /**
7
+ * Usage percentage between two `os.cpus()` snapshots, per core and overall.
8
+ * A counter that did not advance (or went backwards) contributes 0 instead of
9
+ * dividing by zero.
10
+ * @param {Array<{times: object}>} prevCpus snapshot taken earlier
11
+ * @param {Array<{times: object}>} nextCpus snapshot taken now
12
+ * @returns {{total: number, perCore: number[]}}
13
+ */
14
+ export function cpuPercent(prevCpus, nextCpus) {
15
+ const perCore = []
16
+ let totalDelta = 0
17
+ let idleDelta = 0
18
+ const count = Math.min(prevCpus?.length ?? 0, nextCpus?.length ?? 0)
19
+ for (let index = 0; index < count; index += 1) {
20
+ const before = prevCpus[index].times
21
+ const after = nextCpus[index].times
22
+ const beforeIdle = before.idle + (before.iowait ?? 0)
23
+ const afterIdle = after.idle + (after.iowait ?? 0)
24
+ const beforeSum =
25
+ before.user + before.nice + before.sys + before.idle + (before.irq ?? 0) + (before.iowait ?? 0)
26
+ const afterSum =
27
+ after.user + after.nice + after.sys + after.idle + (after.irq ?? 0) + (after.iowait ?? 0)
28
+ const deltaTotal = afterSum - beforeSum
29
+ const deltaIdle = afterIdle - beforeIdle
30
+ totalDelta += deltaTotal
31
+ idleDelta += deltaIdle
32
+ perCore.push(deltaTotal <= 0 ? 0 : Math.round((1000 * (deltaTotal - deltaIdle)) / deltaTotal) / 10)
33
+ }
34
+ const total = totalDelta <= 0 ? 0 : Math.round((1000 * (totalDelta - idleDelta)) / totalDelta) / 10
35
+ return { total, perCore }
36
+ }
37
+
38
+ /**
39
+ * Mounted fixed volumes with total and available bytes, one entry per drive
40
+ * letter that answers `statfs`. Probe cost is why the sampler caches it.
41
+ * @returns {Promise<Array<{id: string, total: number, free: number}>>}
42
+ */
43
+ export async function listFixedVolumes() {
44
+ const volumes = []
45
+ for (const letter of DRIVE_LETTERS) {
46
+ try {
47
+ const stats = await statfs(`${letter}:\\`)
48
+ const total = stats.bsize * stats.blocks
49
+ if (!Number.isFinite(total) || total <= 0) continue
50
+ volumes.push({ id: `${letter}:`, total, free: stats.bsize * stats.bavail })
51
+ } catch {
52
+ /* no fixed volume behind this letter */
53
+ }
54
+ }
55
+ return volumes
56
+ }
57
+
58
+ /**
59
+ * Build one status sample: CPU from consecutive snapshots, memory from os,
60
+ * disks from the cached volume list, and whatever the GPU source last read.
61
+ * @param {{gpu?: {read: () => object | null} | null, now?: () => number, intervalMs?: number, volumes?: () => Promise<Array<object>>, volumeRefreshMs?: number}} [options]
62
+ */
63
+ export function createSampler({
64
+ gpu = null,
65
+ now = () => Date.now(),
66
+ intervalMs = 1000,
67
+ volumes = listFixedVolumes,
68
+ volumeRefreshMs = 60000,
69
+ gpuStaleMs = 8000,
70
+ } = {}) {
71
+ let prevCpus = os.cpus()
72
+ let volumeCache = []
73
+ let volumeAt = -Infinity
74
+ let timer = null
75
+ const listeners = new Set()
76
+
77
+ /** @returns {Promise<object>} one sample in the documented shape */
78
+ async function tick() {
79
+ const nextCpus = os.cpus()
80
+ const cpu = cpuPercent(prevCpus, nextCpus)
81
+ prevCpus = nextCpus
82
+ const t = now()
83
+ if (t - volumeAt >= volumeRefreshMs) {
84
+ volumeAt = t
85
+ volumeCache = await volumes().catch(() => volumeCache)
86
+ }
87
+ const memTotal = os.totalmem()
88
+ const gpuSample = gpu === null ? null : gpu.read()
89
+ // A cached GPU reading older than the staleness window is not live data:
90
+ // a crashed nvidia-smi loop must not freeze the bar at a friendly number.
91
+ const gpuIsStale =
92
+ gpuSample !== null && Number.isFinite(gpuSample.at) && t - gpuSample.at > gpuStaleMs
93
+ return {
94
+ t,
95
+ cpu,
96
+ mem: { used: memTotal - os.freemem(), total: memTotal },
97
+ gpu: gpuIsStale ? null : gpuSample,
98
+ disks: volumeCache,
99
+ }
100
+ }
101
+
102
+ return {
103
+ tick,
104
+ start() {
105
+ if (timer !== null) return
106
+ timer = setInterval(() => {
107
+ void tick()
108
+ .then((sample) => {
109
+ for (const listener of listeners) {
110
+ try {
111
+ listener(sample)
112
+ } catch {
113
+ /* one bad subscriber must not stop the others */
114
+ }
115
+ }
116
+ })
117
+ .catch(() => {})
118
+ }, intervalMs)
119
+ timer.unref?.()
120
+ },
121
+ stop() {
122
+ if (timer !== null) {
123
+ clearInterval(timer)
124
+ timer = null
125
+ }
126
+ },
127
+ /**
128
+ * @param {(sample: object) => void} listener
129
+ * @returns {() => void} unsubscribe
130
+ */
131
+ subscribe(listener) {
132
+ listeners.add(listener)
133
+ return () => {
134
+ listeners.delete(listener)
135
+ }
136
+ },
137
+ listenerCount: () => listeners.size,
138
+ }
139
+ }
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="System status">
2
+ <rect x="4" y="6" width="56" height="52" rx="10" fill="#1d2733"/>
3
+ <path d="M12 44l9-13 7.4 7.8L37 24l15 20" fill="none" stroke="#4fc3f7" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
4
+ <path d="M12 51h40" fill="none" stroke="#4fc3f7" stroke-width="3" stroke-linecap="round" opacity="0.5"/>
5
+ <circle cx="47" cy="17" r="4" fill="#66bb6a"/>
6
+ </svg>