dsh-remote-vs 0.17.0 → 0.19.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/src/metrics.ts ADDED
@@ -0,0 +1,300 @@
1
+ /**
2
+ * One bounded POSIX probe for the host monitor panel, and its pure parser.
3
+ *
4
+ * Why a shell one-liner instead of the helper or Python on the remote:
5
+ * - the plugin targets bare POSIX hosts (the doctor probe already works this
6
+ * way); requiring `python3`/`psutil` would make the panel dead on a stock
7
+ * router or NAS;
8
+ * - one `exec` over the pooled SSH channel needs no helper deploy and no
9
+ * version handshake, so the panel also works on a host the deploy pipeline
10
+ * never touched.
11
+ *
12
+ * Every fact is a marker line (`@@RVS-MET key detail`), so a banner printed by
13
+ * a login shell or a stray line of a command can never be mistaken for a
14
+ * measurement. A metric the host cannot answer is `null` (rendered as unknown),
15
+ * never zero: a VM without a thermal zone has no temperature, it does not have
16
+ * 0 °C.
17
+ *
18
+ * CPU% and the network rate are DELTAS over the previous sample: the caller
19
+ * keeps the counters (`cpuPercent` / `netRateBps` below). The first sample is
20
+ * honestly unknown instead of a made-up number.
21
+ *
22
+ * Linux is the supported source (`/proc`). A host that is not Linux simply
23
+ * answers `unknown`, which the UI renders as "unknown", not as an empty host.
24
+ */
25
+
26
+ /** Prefix of every control line the probe prints (also the "did it answer" proof). */
27
+ export const METRICS_MARK = '@@RVS-MET'
28
+
29
+ /**
30
+ * Budget for the whole probe.
31
+ *
32
+ * A handful of `/proc` reads over one channel: if the host itself is stuck (a
33
+ * hung mount, a thief of a process, a network blip) the route must answer with
34
+ * the exec deadline instead of holding the monitor's poll forever.
35
+ */
36
+ export const METRICS_TIMEOUT_MS = 8_000
37
+
38
+ /** CPU timers from `/proc/stat` (jiffies). */
39
+ export interface CpuCounters {
40
+ /** user + nice + system + idle + iowait + irq + softirq + steal. */
41
+ total: number
42
+ /** idle + iowait. */
43
+ idle: number
44
+ }
45
+
46
+ /** Cumulative network byte counters from `/proc/net/dev` (loopback excluded). */
47
+ export interface NetCounters {
48
+ rx: number
49
+ tx: number
50
+ }
51
+
52
+ /** What the probe process itself reported, for honest unknown/error wording. */
53
+ export interface MetricsParseOptions {
54
+ exitCode: number | null
55
+ timedOut?: boolean
56
+ /** Connection error message when the command never ran. */
57
+ error?: string | undefined
58
+ stderr?: string
59
+ }
60
+
61
+ /**
62
+ * The probe's answer.
63
+ *
64
+ * `state: 'unknown'` means the command ran but the data cannot be trusted (it
65
+ * timed out, the channel died before an exit status, or the markers are
66
+ * missing). A transport failure is classified by the caller (`HostMonitor`),
67
+ * not here.
68
+ */
69
+ export interface ParsedMetrics {
70
+ state: 'ok' | 'unknown'
71
+ reason?: string
72
+ kernel: string | null
73
+ cpuCores: number | null
74
+ cpuModel: string | null
75
+ ip: string | null
76
+ uptimeSeconds: number | null
77
+ load: [number, number, number] | null
78
+ cpu: CpuCounters | null
79
+ memTotalBytes: number | null
80
+ memUsedBytes: number | null
81
+ diskTotalBytes: number | null
82
+ diskUsedBytes: number | null
83
+ temperatureC: number | null
84
+ net: NetCounters | null
85
+ }
86
+
87
+ /**
88
+ * The remote probe line.
89
+ *
90
+ * `printf` never interpolates the input; every value comes from a fixed local
91
+ * command. `2>/dev/null` is only used where the missing tool/file is itself a
92
+ * normal answer (`/proc` on a non-Linux host); the parser then sees an empty
93
+ * value and reports it as unknown rather than as a zero.
94
+ */
95
+ export function metricsCommand(): string {
96
+ const mark = METRICS_MARK
97
+ return [
98
+ 'export LC_ALL=C',
99
+ `printf '%s begin\\n' '${mark}'`,
100
+ `printf '%s kernel %s\\n' '${mark}' "$(uname -srm 2>/dev/null)"`,
101
+ `printf '%s cores %s\\n' '${mark}' "$(getconf _NPROCESSORS_ONLN 2>/dev/null || nproc 2>/dev/null)"`,
102
+ `printf '%s uptime %s\\n' '${mark}' "$(cut -d' ' -f1 /proc/uptime 2>/dev/null)"`,
103
+ `printf '%s load %s\\n' '${mark}' "$(cut -d' ' -f1-3 /proc/loadavg 2>/dev/null)"`,
104
+ `printf '%s cpu %s\\n' '${mark}' "$(awk '/^cpu /{print $2,$3,$4,$5,$6,$7,$8,$9; exit}' /proc/stat 2>/dev/null)"`,
105
+ `printf '%s mem %s\\n' '${mark}' "$(awk '/^MemTotal:/{t=$2} /^MemAvailable:/{a=$2} /^MemFree:/{f=$2} /^Buffers:/{b=$2} /^Cached:/{c=$2} END{if(t=="")exit; if(a=="")a=f+b+c; printf "%s %s", t, a}' /proc/meminfo 2>/dev/null)"`,
106
+ `printf '%s disk %s\\n' '${mark}' "$(df -Pk / 2>/dev/null | awk 'NR==2{print $2, $3}')"`,
107
+ `printf '%s net %s\\n' '${mark}' "$(awk 'NR>2{iface=$1; sub(/:$/,"",iface); if(iface=="lo")next; rx+=$2; tx+=$10} END{printf "%s %s", rx+0, tx+0}' /proc/net/dev 2>/dev/null)"`,
108
+ `printf '%s temp %s\\n' '${mark}' "$(for f in /sys/class/thermal/thermal_zone*/temp; do if [ -r "$f" ]; then cat "$f"; break; fi; done 2>/dev/null)"`,
109
+ `printf '%s model %s\\n' '${mark}' "$(awk -F: '/model name/{sub(/^[ \\t]+/,"",$2); print $2; exit}' /proc/cpuinfo 2>/dev/null)"`,
110
+ `printf '%s ip %s\\n' '${mark}' "$(hostname -I 2>/dev/null | awk '{print $1}')"`,
111
+ `printf '%s end\\n' '${mark}'`,
112
+ ].join('\n')
113
+ }
114
+
115
+ /** Anchored marker: a metric line's content can never forge or split a marker. */
116
+ const LINE_RE = new RegExp(`^${METRICS_MARK} ([a-z]+)(?: (.*))?$`)
117
+
118
+ const EMPTY: Omit<ParsedMetrics, 'state' | 'reason'> = {
119
+ kernel: null,
120
+ cpuCores: null,
121
+ cpuModel: null,
122
+ ip: null,
123
+ uptimeSeconds: null,
124
+ load: null,
125
+ cpu: null,
126
+ memTotalBytes: null,
127
+ memUsedBytes: null,
128
+ diskTotalBytes: null,
129
+ diskUsedBytes: null,
130
+ temperatureC: null,
131
+ net: null,
132
+ }
133
+
134
+ function unavailable(reason: string): ParsedMetrics {
135
+ return { state: 'unknown', reason, ...EMPTY }
136
+ }
137
+
138
+ function numberFrom(text: string | undefined): number | null {
139
+ if (text === undefined || text.trim() === '') return null
140
+ const value = Number(text.trim())
141
+ return Number.isFinite(value) ? value : null
142
+ }
143
+
144
+ function intFrom(text: string | undefined): number | null {
145
+ const value = numberFrom(text)
146
+ return value === null ? null : Math.trunc(value)
147
+ }
148
+
149
+ function tokensOf(detail: string | undefined): string[] {
150
+ return detail === undefined ? [] : detail.trim().split(/\s+/).filter(token => token !== '')
151
+ }
152
+
153
+ function textOf(facts: Map<string, string>, key: string): string | null {
154
+ const value = facts.get(key)
155
+ if (value === undefined) return null
156
+ const trimmed = value.trim()
157
+ return trimmed === '' ? null : trimmed
158
+ }
159
+
160
+ /**
161
+ * Parse the probe's stdout.
162
+ *
163
+ * Exit-code/timed-out/transport outcomes are answered BEFORE the markers so a
164
+ * half-written probe can never be reported as a complete sample.
165
+ */
166
+ export function parseMetrics(stdout: string, options: MetricsParseOptions): ParsedMetrics {
167
+ if (options.error !== undefined && options.error !== '') return unavailable(options.error)
168
+ if (options.timedOut === true) return unavailable(`probe timed out after ${METRICS_TIMEOUT_MS / 1000}s`)
169
+ if (options.exitCode === null) return unavailable('the SSH channel closed before the probe exited')
170
+ if (options.exitCode !== 0) {
171
+ const stderr = (options.stderr ?? '').trim()
172
+ const first = stderr.split(/\r?\n/)[0] ?? ''
173
+ return unavailable(`probe exited with code ${options.exitCode}${first === '' ? '' : `: ${first}`}`)
174
+ }
175
+
176
+ const facts = new Map<string, string>()
177
+ let sawBegin = false
178
+ let sawEnd = false
179
+ for (const raw of stdout.split(/\r?\n/)) {
180
+ const match = LINE_RE.exec(raw.trim())
181
+ if (match === null) continue
182
+ const key = match[1]
183
+ const detail = match[2] ?? ''
184
+ if (key === 'begin') {
185
+ sawBegin = true
186
+ continue
187
+ }
188
+ if (key === 'end') {
189
+ sawEnd = true
190
+ continue
191
+ }
192
+ facts.set(key, detail)
193
+ }
194
+ if (!sawBegin) return unavailable('the probe did not start (no begin marker)')
195
+ if (!sawEnd) return unavailable('the probe did not finish (no end marker)')
196
+
197
+ const cpuTokens = tokensOf(facts.get('cpu'))
198
+ const cpu = cpuTokens.length >= 8
199
+ ? {
200
+ total: cpuTokens.slice(0, 8).reduce((sum, token) => sum + (Number(token) || 0), 0),
201
+ idle: (Number(cpuTokens[3]) || 0) + (Number(cpuTokens[4]) || 0),
202
+ }
203
+ : null
204
+
205
+ const memTokens = tokensOf(facts.get('mem'))
206
+ const memTotalKb = memTokens.length >= 2 ? numberFrom(memTokens[0]) : null
207
+ const memAvailableKb = memTokens.length >= 2 ? numberFrom(memTokens[1]) : null
208
+ const memTotalBytes = memTotalKb === null ? null : memTotalKb * 1024
209
+ const memUsedBytes = memTotalBytes === null || memAvailableKb === null
210
+ ? null
211
+ : Math.max(0, memTotalBytes - memAvailableKb * 1024)
212
+
213
+ const diskTokens = tokensOf(facts.get('disk'))
214
+ const diskTotalKb = diskTokens.length >= 2 ? numberFrom(diskTokens[0]) : null
215
+ const diskUsedKb = diskTokens.length >= 2 ? numberFrom(diskTokens[1]) : null
216
+ const diskTotalBytes = diskTotalKb === null ? null : diskTotalKb * 1024
217
+ const diskUsedBytes = diskUsedKb === null ? null : diskUsedKb * 1024
218
+
219
+ const loadTokens = tokensOf(facts.get('load'))
220
+ const load: [number, number, number] | null = loadTokens.length >= 3
221
+ ? [Number(loadTokens[0]) || 0, Number(loadTokens[1]) || 0, Number(loadTokens[2]) || 0]
222
+ : null
223
+
224
+ const netTokens = tokensOf(facts.get('net'))
225
+ const net: NetCounters | null = netTokens.length >= 2
226
+ ? { rx: Number(netTokens[0]) || 0, tx: Number(netTokens[1]) || 0 }
227
+ : null
228
+
229
+ const temperatureMilli = intFrom(facts.get('temp'))
230
+ const temperatureC = temperatureMilli === null ? null : temperatureMilli / 1000
231
+
232
+ // A Linux host always has CPU and memory under /proc. Disk alone (a macOS
233
+ // `df`) is not enough: reporting that as an `ok` host would paint a green
234
+ // "healthy" row while every live metric on it is unknown.
235
+ if (cpu === null && memTotalBytes === null) {
236
+ return unavailable('the probe answered without /proc CPU or memory (not a Linux host?)')
237
+ }
238
+
239
+ return {
240
+ state: 'ok',
241
+ kernel: textOf(facts, 'kernel'),
242
+ cpuCores: intFrom(facts.get('cores')),
243
+ cpuModel: textOf(facts, 'model'),
244
+ ip: tokensOf(facts.get('ip'))[0] ?? null,
245
+ uptimeSeconds: numberFrom(facts.get('uptime')),
246
+ load,
247
+ cpu,
248
+ memTotalBytes,
249
+ memUsedBytes,
250
+ diskTotalBytes,
251
+ diskUsedBytes,
252
+ temperatureC,
253
+ net,
254
+ }
255
+ }
256
+
257
+ /**
258
+ * CPU busy percentage between two counter samples.
259
+ *
260
+ * Null when a counter is missing, the sum did not advance, or the counters
261
+ * went backwards (a reboot between the two samples): all three mean "unknown",
262
+ * not "0%".
263
+ */
264
+ export function cpuPercent(
265
+ previous: CpuCounters | null | undefined,
266
+ next: CpuCounters | null | undefined,
267
+ ): number | null {
268
+ if (previous === null || previous === undefined || next === null || next === undefined) return null
269
+ const total = next.total - previous.total
270
+ const idle = next.idle - previous.idle
271
+ if (total <= 0 || idle < 0 || idle > total) return null
272
+ return Math.min(100, Math.max(0, (1 - idle / total) * 100))
273
+ }
274
+
275
+ /**
276
+ * Network bytes-per-second between two counter samples.
277
+ *
278
+ * Null when either counter is missing, the interval is not positive, or a
279
+ * counter went backwards (a reboot): a rate computed from a reset counter is
280
+ * noise, and showing it as a huge spike would be worse than "unknown".
281
+ */
282
+ export function netRateBps(
283
+ previous: NetCounters | null | undefined,
284
+ next: NetCounters | null | undefined,
285
+ elapsedMs: number | null | undefined,
286
+ ): { rx: number; tx: number } | null {
287
+ if (previous === null || previous === undefined || next === null || next === undefined) return null
288
+ if (elapsedMs === null || elapsedMs === undefined || !Number.isFinite(elapsedMs) || elapsedMs <= 0) return null
289
+ const rx = next.rx - previous.rx
290
+ const tx = next.tx - previous.tx
291
+ if (rx < 0 || tx < 0) return null
292
+ const seconds = elapsedMs / 1000
293
+ return { rx: rx / seconds, tx: tx / seconds }
294
+ }
295
+
296
+ /** Bytes as a percentage of a total; null when either side is unknown. */
297
+ export function usedPercent(used: number | null, total: number | null): number | null {
298
+ if (used === null || total === null || total <= 0) return null
299
+ return Math.min(100, Math.max(0, (used / total) * 100))
300
+ }
package/src/monitor.ts ADDED
@@ -0,0 +1,203 @@
1
+ /**
2
+ * HostMonitor: the Host-side cache/sampler behind the monitor panel.
3
+ *
4
+ * One `pool.exec` per alias per sample (a handful of `/proc` reads; see
5
+ * `metrics.ts`). The panel polls while it is visible, but three things can ask
6
+ * within the same second (several browser tabs, a manual refresh, the first
7
+ * paint after a rail switch), so the sampler:
8
+ *
9
+ * - reuses a sample younger than `freshMs` (default 3 s, below the panel's 5 s
10
+ * poll) — a refresh storm costs one channel, not one per request;
11
+ * - joins an in-flight sample instead of opening a second channel for the same
12
+ * alias (the pool's own slot budget would otherwise queue them for up to 30 s);
13
+ * - keeps the previous counters so CPU% and the network rate are deltas over
14
+ * real elapsed time. The first sample has counters but no previous sample:
15
+ * those two values are null (unknown), never zero.
16
+ *
17
+ * `forget(alias)` is called from the two places a host's identity changes
18
+ * (host DELETE and host edit): a cached sample carries the old connection's
19
+ * counters, and using it after a re-dial would print a bogus rate.
20
+ */
21
+ import type { RemoteExecResult, RemoteHostMetrics } from './protocol.ts'
22
+ import {
23
+ METRICS_TIMEOUT_MS,
24
+ cpuPercent,
25
+ metricsCommand,
26
+ netRateBps,
27
+ parseMetrics,
28
+ usedPercent,
29
+ type CpuCounters,
30
+ type NetCounters,
31
+ } from './metrics.ts'
32
+
33
+ /** The slice of `RemotePool` the sampler needs (fake in gates, real at runtime). */
34
+ export interface MetricsExecutor {
35
+ exec(alias: string, command: string, opts?: { timeoutMs?: number }): Promise<RemoteExecResult>
36
+ }
37
+
38
+ export interface HostMonitorOptions {
39
+ /** Injectable clock (gates drive time without sleeping). */
40
+ now?: () => number
41
+ /** Snapshot reuse window. Deliberately below the panel's 5 s poll. */
42
+ freshMs?: number
43
+ }
44
+
45
+ /** Default reuse window: below the panel poll, above a refresh storm. */
46
+ export const DEFAULT_FRESH_MS = 3_000
47
+
48
+ interface CacheEntry {
49
+ snapshot: RemoteHostMetrics
50
+ /** Last counters a percentage/rate can be measured against. */
51
+ cpu: CpuCounters | null
52
+ net: NetCounters | null
53
+ /** When the counters above were read (null when they never were). */
54
+ counterAt: number | null
55
+ }
56
+
57
+ function messageOf(error: unknown): string {
58
+ return error instanceof Error ? error.message : String(error)
59
+ }
60
+
61
+ /** Every field null: an honest "we did not get an answer". */
62
+ export function emptyMetrics(
63
+ alias: string,
64
+ state: 'unknown' | 'error',
65
+ reason: string,
66
+ sampledAt: number,
67
+ ): RemoteHostMetrics {
68
+ return {
69
+ alias,
70
+ state,
71
+ reason,
72
+ sampledAt,
73
+ kernel: null,
74
+ cpuCores: null,
75
+ cpuModel: null,
76
+ ip: null,
77
+ uptimeSeconds: null,
78
+ load1: null,
79
+ load5: null,
80
+ load15: null,
81
+ cpuPercent: null,
82
+ memUsedBytes: null,
83
+ memTotalBytes: null,
84
+ memPercent: null,
85
+ diskUsedBytes: null,
86
+ diskTotalBytes: null,
87
+ diskPercent: null,
88
+ temperatureC: null,
89
+ netRxBps: null,
90
+ netTxBps: null,
91
+ }
92
+ }
93
+
94
+ export class HostMonitor {
95
+ private readonly pool: MetricsExecutor
96
+ private readonly now: () => number
97
+ private readonly freshMs: number
98
+ private readonly cache = new Map<string, CacheEntry>()
99
+ private readonly inflight = new Map<string, Promise<RemoteHostMetrics>>()
100
+ /**
101
+ * Bumped by `forget`. A probe that started before a host edit/delete must not
102
+ * write its answer into the cache afterwards — the counters belong to the old
103
+ * connection, and a re-created host with the same alias would briefly read a
104
+ * stale sample.
105
+ */
106
+ private readonly generations = new Map<string, number>()
107
+
108
+ constructor(pool: MetricsExecutor, options: HostMonitorOptions = {}) {
109
+ this.pool = pool
110
+ this.now = options.now ?? (() => Date.now())
111
+ this.freshMs = options.freshMs ?? DEFAULT_FRESH_MS
112
+ }
113
+
114
+ /** One sample for one alias; `force` bypasses the reuse window (manual refresh). */
115
+ async sample(alias: string, force = false): Promise<RemoteHostMetrics> {
116
+ const cached = this.cache.get(alias)
117
+ if (!force && cached !== undefined && this.now() - cached.snapshot.sampledAt < this.freshMs) {
118
+ return cached.snapshot
119
+ }
120
+ const running = this.inflight.get(alias)
121
+ if (running !== undefined) return running
122
+ // The finally-delete must only remove THIS task: a forced refresh may have
123
+ // replaced the map entry with a newer one while this one was running.
124
+ const task: Promise<RemoteHostMetrics> = this.probe(alias).finally(() => {
125
+ if (this.inflight.get(alias) === task) this.inflight.delete(alias)
126
+ })
127
+ this.inflight.set(alias, task)
128
+ return task
129
+ }
130
+
131
+ /** Drop everything known about one alias (host edited or deleted). */
132
+ forget(alias: string): void {
133
+ this.cache.delete(alias)
134
+ this.inflight.delete(alias)
135
+ this.generations.set(alias, (this.generations.get(alias) ?? 0) + 1)
136
+ }
137
+
138
+ private async probe(alias: string): Promise<RemoteHostMetrics> {
139
+ const generation = this.generations.get(alias) ?? 0
140
+ const startedAt = this.now()
141
+ let result: RemoteExecResult
142
+ try {
143
+ result = await this.pool.exec(alias, metricsCommand(), { timeoutMs: METRICS_TIMEOUT_MS })
144
+ } catch (error) {
145
+ return emptyMetrics(alias, 'error', messageOf(error), startedAt)
146
+ }
147
+ if (result.error !== undefined && result.error !== '') {
148
+ return emptyMetrics(alias, 'error', result.error, startedAt)
149
+ }
150
+
151
+ const parsed = parseMetrics(result.stdout, {
152
+ exitCode: result.exitCode,
153
+ timedOut: result.timedOut,
154
+ stderr: result.stderr,
155
+ })
156
+ const sampledAt = this.now()
157
+ const previous = this.cache.get(alias)
158
+ const elapsedMs = previous?.counterAt === null || previous?.counterAt === undefined
159
+ ? null
160
+ : Math.max(0, sampledAt - previous.counterAt)
161
+ const cpu = cpuPercent(previous?.cpu ?? null, parsed.cpu)
162
+ const rate = netRateBps(previous?.net ?? null, parsed.net, elapsedMs)
163
+
164
+ const snapshot: RemoteHostMetrics = {
165
+ alias,
166
+ state: parsed.state === 'ok' ? 'ok' : 'unknown',
167
+ ...(parsed.reason === undefined ? {} : { reason: parsed.reason }),
168
+ sampledAt,
169
+ kernel: parsed.kernel,
170
+ cpuCores: parsed.cpuCores,
171
+ cpuModel: parsed.cpuModel,
172
+ ip: parsed.ip,
173
+ uptimeSeconds: parsed.uptimeSeconds,
174
+ load1: parsed.load?.[0] ?? null,
175
+ load5: parsed.load?.[1] ?? null,
176
+ load15: parsed.load?.[2] ?? null,
177
+ cpuPercent: cpu,
178
+ memUsedBytes: parsed.memUsedBytes,
179
+ memTotalBytes: parsed.memTotalBytes,
180
+ memPercent: usedPercent(parsed.memUsedBytes, parsed.memTotalBytes),
181
+ diskUsedBytes: parsed.diskUsedBytes,
182
+ diskTotalBytes: parsed.diskTotalBytes,
183
+ diskPercent: usedPercent(parsed.diskUsedBytes, parsed.diskTotalBytes),
184
+ temperatureC: parsed.temperatureC,
185
+ netRxBps: rate?.rx ?? null,
186
+ netTxBps: rate?.tx ?? null,
187
+ }
188
+
189
+ // Counters survive an unknown answer: after a timeout the next successful
190
+ // sample still has a baseline to diff against, and the elapsed time is the
191
+ // real gap between the two counter reads (not a made-up poll interval).
192
+ const counters = parsed.cpu ?? previous?.cpu ?? null
193
+ const countersAt = parsed.cpu === null ? (previous?.counterAt ?? null) : sampledAt
194
+ const net = parsed.net ?? previous?.net ?? null
195
+ // A host mutation during the probe invalidates this answer's cache slot.
196
+ // The caller still gets the sample it asked for; the NEXT request starts
197
+ // from scratch instead of inheriting counters from the pre-edit connection.
198
+ if ((this.generations.get(alias) ?? 0) === generation) {
199
+ this.cache.set(alias, { snapshot, cpu: counters, net, counterAt: countersAt })
200
+ }
201
+ return snapshot
202
+ }
203
+ }
@@ -6,10 +6,12 @@
6
6
  */
7
7
  import { FileSystem, FsError, type FsErrorCode } from '@deepseek-ai/dsh-fs'
8
8
  import type {
9
+ FsDeleteOutcome,
9
10
  FsDirEntry,
10
11
  FsEditOutcome,
11
12
  FsEditRequest,
12
13
  FsInfo,
14
+ FsMoveOutcome,
13
15
  FsPathInfo,
14
16
  FsTarget,
15
17
  FsVersion,
@@ -320,6 +322,62 @@ export default class TransparentFileSystem extends FileSystem {
320
322
  return fs.editText(target, edit, expected, signal, this.remote.rewritePolicy(sandboxPolicy, world))
321
323
  }
322
324
 
325
+ /**
326
+ * alpha.3 added patch/delete/move to the FileSystem contract for the
327
+ * apply_patch tool. Local providers implement all three; the deliberately
328
+ * pinned protocol-2 remote backend (dsh-fs-ssh 0.2.1-rc.2) predates them, so
329
+ * remote targets get a typed error instead of a TypeError. The apply_patch
330
+ * tool is off by default in every stock preset (alpha.3 dsh-base and presets
331
+ * pin `applyPatch: false`), so this only matters when it is enabled.
332
+ */
333
+ private unsupportedRemote(what: string): FsError {
334
+ return new FsError(
335
+ `${what} is not supported on remote workspaces yet (fs-ssh protocol 2); run it in a local workspace`,
336
+ 'FS_IO_ERROR',
337
+ )
338
+ }
339
+
340
+ async patchText(
341
+ target: FsTarget,
342
+ hunks: Parameters<FileSystem['patchText']>[1],
343
+ expected?: { version: FsVersion },
344
+ signal?: AbortSignal,
345
+ sandboxPolicy?: SandboxExecutionPolicy,
346
+ ): Promise<FsEditOutcome> {
347
+ const { fs, world } = await this.backendOf(target)
348
+ if (typeof fs.patchText !== 'function') throw this.unsupportedRemote('apply_patch')
349
+ return fs.patchText(target, hunks, expected, signal, this.remote.rewritePolicy(sandboxPolicy, world))
350
+ }
351
+
352
+ async deleteFile(
353
+ target: FsTarget,
354
+ expected?: { version: FsVersion },
355
+ signal?: AbortSignal,
356
+ sandboxPolicy?: SandboxExecutionPolicy,
357
+ ): Promise<FsDeleteOutcome> {
358
+ const { fs, world } = await this.backendOf(target)
359
+ if (typeof fs.deleteFile !== 'function') throw this.unsupportedRemote('deleting files')
360
+ return fs.deleteFile(target, expected, signal, this.remote.rewritePolicy(sandboxPolicy, world))
361
+ }
362
+
363
+ async moveFile(
364
+ source: FsTarget,
365
+ destination: FsTarget,
366
+ options: Parameters<FileSystem['moveFile']>[2],
367
+ signal?: AbortSignal,
368
+ sandboxPolicy?: SandboxExecutionPolicy,
369
+ ): Promise<FsMoveOutcome> {
370
+ const { fs, world } = await this.backendOf(source)
371
+ const destinationWorld = this.worlds.get(destination)
372
+ const sameWorld =
373
+ destinationWorld !== undefined &&
374
+ destinationWorld.kind === world.kind &&
375
+ (world.kind === 'local' || (destinationWorld.kind === 'remote' && destinationWorld.id === world.id))
376
+ if (!sameWorld) throw new FsError('cannot move a file across local and remote worlds', 'FS_IO_ERROR')
377
+ if (typeof fs.moveFile !== 'function') throw this.unsupportedRemote('moving files')
378
+ return fs.moveFile(source, destination, options, signal, this.remote.rewritePolicy(sandboxPolicy, world))
379
+ }
380
+
323
381
  async watch(target: FsTarget, changed: (error?: Error) => void, signal: AbortSignal): Promise<() => Promise<void>> {
324
382
  const { fs } = await this.backendOf(target)
325
383
  return fs.watch(target, changed, signal)
package/src/protocol.ts CHANGED
@@ -38,6 +38,8 @@ export const REMOTE_API = {
38
38
  forwards: '/api/dsh-remote/forwards',
39
39
  /** Remote listening TCP sockets for the port panel (one bounded probe). */
40
40
  listenPorts: '/api/dsh-remote/listen-ports',
41
+ /** Live system metrics for the monitor panel (one bounded probe per host). */
42
+ metrics: '/api/dsh-remote/metrics',
41
43
  } as const
42
44
 
43
45
  /**
@@ -631,4 +633,59 @@ export interface RemoteListenPortsResult {
631
633
  ports: RemoteListenPort[]
632
634
  /** Why the probe could not be used, when it could not. */
633
635
  error?: string
634
- }
636
+ }
637
+
638
+ /**
639
+ * How one host metrics sample ended.
640
+ *
641
+ * `ok` = the probe answered and at least one metric was readable; `unknown` =
642
+ * the command ran but could not be trusted (timeout, missing markers, a host
643
+ * that is not Linux); `error` = the command never produced a usable answer
644
+ * (transport failure). `null` fields inside an `ok` sample mean "this host does
645
+ * not expose that metric" — the UI must render them as unknown, never as zero.
646
+ */
647
+ export type RemoteMetricsState = 'ok' | 'unknown' | 'error'
648
+
649
+ /**
650
+ * One host's live system metrics, sampled by the Host over the existing SSH
651
+ * channel (a single bounded POSIX probe; no helper and no Python on the remote).
652
+ *
653
+ * `cpuPercent`, `netRxBps` and `netTxBps` are deltas over the previous sample:
654
+ * the first sample has them null on purpose (a made-up 0% would be a lie). The
655
+ * Host caches a sample for a few seconds, so a poll storm costs one channel.
656
+ */
657
+ export interface RemoteHostMetrics {
658
+ alias: string
659
+ state: RemoteMetricsState
660
+ /** Why the state is not `ok`; never empty then. */
661
+ reason?: string
662
+ /** Host clock when the sample was taken (epoch ms). */
663
+ sampledAt: number
664
+ /** `uname -srm` (`Linux 6.1.0 x86_64`), or null when unreadable. */
665
+ kernel: string | null
666
+ cpuCores: number | null
667
+ cpuModel: string | null
668
+ ip: string | null
669
+ uptimeSeconds: number | null
670
+ load1: number | null
671
+ load5: number | null
672
+ load15: number | null
673
+ /** Busy CPU over the previous sample, 0–100. */
674
+ cpuPercent: number | null
675
+ memUsedBytes: number | null
676
+ memTotalBytes: number | null
677
+ memPercent: number | null
678
+ diskUsedBytes: number | null
679
+ diskTotalBytes: number | null
680
+ diskPercent: number | null
681
+ /** The first thermal zone in °C when the host exposes one (many VMs do not). */
682
+ temperatureC: number | null
683
+ /** Receive/transmit bytes per second since the previous sample. */
684
+ netRxBps: number | null
685
+ netTxBps: number | null
686
+ }
687
+
688
+ /** The monitor route's answer (`alias` omitted = every configured host). */
689
+ export interface RemoteMetricsResult {
690
+ hosts: RemoteHostMetrics[]
691
+ }