dsh-ops-kit 0.0.0-stage → 0.3.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.
package/index.js ADDED
@@ -0,0 +1,3524 @@
1
+ /**
2
+ * dsh-ops-kit — a small server operations kit for DeepSeek Harness.
3
+ *
4
+ * Design notes
5
+ * - Zero dependencies: it shells out to the system `ssh` client, so it works on
6
+ * any host where you can already ssh by key (BatchMode; no password prompts).
7
+ * - Host inventory lives in `$DSH_HOME/ops-kit/hosts.json` (default
8
+ * `~/.dsh/ops-kit/hosts.json`), never in the profile.
9
+ * - Read-only checks are free; state-changing actions (service restart, docker
10
+ * restart) require an explicit `confirm: true`, and a short denylist guards
11
+ * the free-form `ops_run` tool.
12
+ *
13
+ * @module dsh-ops-kit
14
+ */
15
+
16
+ import { execFile, spawn } from 'node:child_process'
17
+ import { mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
18
+ import { homedir } from 'node:os'
19
+ import { dirname, join } from 'node:path'
20
+ import { promisify } from 'node:util'
21
+ import { createRequire } from 'node:module'
22
+ import { chmod } from 'node:fs/promises'
23
+
24
+ const run = promisify(execFile)
25
+
26
+ export const name = 'dsh-ops-kit'
27
+ export const inject = ['tools', 'webServer']
28
+
29
+ const MAX_OUTPUT = 8_000
30
+
31
+ /** Host context, set in apply; used for the optional AI diagnosis. */
32
+ let hostCtx = null
33
+
34
+ function kitDir() {
35
+ return join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'ops-kit')
36
+ }
37
+
38
+ function hostsFile() {
39
+ return join(kitDir(), 'hosts.json')
40
+ }
41
+
42
+ function historyFile() {
43
+ return join(kitDir(), 'history.json')
44
+ }
45
+
46
+ function secretsFile() {
47
+ return join(kitDir(), 'secrets.json')
48
+ }
49
+
50
+ /** Passwords live in a 0600 file next to the inventory; keys are still preferred. */
51
+ async function loadSecrets() {
52
+ try {
53
+ const data = JSON.parse(await readFile(secretsFile(), 'utf8'))
54
+ return data && typeof data === 'object' ? data : {}
55
+ } catch {
56
+ return {}
57
+ }
58
+ }
59
+
60
+ async function saveSecret(name, password) {
61
+ const all = await loadSecrets()
62
+ if (password) all[name] = { password: Buffer.from(String(password), 'utf8').toString('base64'), at: new Date().toISOString() }
63
+ else delete all[name]
64
+ await mkdir(kitDir(), { recursive: true })
65
+ await writeFile(secretsFile(), JSON.stringify(all, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
66
+ try { await chmod(secretsFile(), 0o600) } catch { /* best effort */ }
67
+ return all
68
+ }
69
+
70
+ const HISTORY_LIMIT = 100
71
+
72
+ async function loadHistory() {
73
+ try {
74
+ const raw = await readFile(historyFile(), 'utf8')
75
+ const data = JSON.parse(raw)
76
+ return Array.isArray(data.entries) ? data.entries : []
77
+ } catch {
78
+ return []
79
+ }
80
+ }
81
+
82
+ async function appendHistory(entries) {
83
+ const all = [...entries, ...(await loadHistory())].slice(0, HISTORY_LIMIT)
84
+ await mkdir(kitDir(), { recursive: true })
85
+ await writeFile(historyFile(), JSON.stringify({ entries: all }, null, 2) + '\n', 'utf8')
86
+ return all
87
+ }
88
+
89
+ async function loadHosts() {
90
+ try {
91
+ const raw = await readFile(hostsFile(), 'utf8')
92
+ const data = JSON.parse(raw)
93
+ return { hosts: Array.isArray(data.hosts) ? data.hosts : [], defaultHost: data.defaultHost }
94
+ } catch {
95
+ return { hosts: [], defaultHost: undefined }
96
+ }
97
+ }
98
+
99
+ async function saveHosts(data) {
100
+ await mkdir(dirname(hostsFile()), { recursive: true })
101
+ await writeFile(hostsFile(), JSON.stringify(data, null, 2) + '\n', 'utf8')
102
+ }
103
+
104
+ function pickHost(data, wanted) {
105
+ const name = (wanted ?? data.defaultHost ?? '').trim()
106
+ const list = data.hosts
107
+ if (list.length === 0) {
108
+ throw new Error('no hosts configured: call ops_hosts with action="add" first')
109
+ }
110
+ if (!name) {
111
+ if (list.length === 1) return list[0]
112
+ throw new Error(`host is required; configured hosts: ${list.map(h => h.name).join(', ')}`)
113
+ }
114
+ const found = list.find(h => h.name === name || h.host === name)
115
+ if (!found) throw new Error(`unknown host "${name}"; configured: ${list.map(h => h.name).join(', ')}`)
116
+ return found
117
+ }
118
+
119
+ function target(cfg) {
120
+ return `${cfg.user ? `${cfg.user}@` : ''}${cfg.host}`
121
+ }
122
+
123
+ let ssh2Module
124
+ /**
125
+ * Resolve ssh2 from the profile, not from this package: a locally linked bundle
126
+ * lives in the workspace, while profile dependencies (ssh2 among them) are
127
+ * installed next to the profile's own node_modules.
128
+ */
129
+ function loadSsh2() {
130
+ if (ssh2Module !== undefined) return ssh2Module
131
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
132
+ const bases = [
133
+ process.env.DSH_PROFILE_DIR ? join(process.env.DSH_PROFILE_DIR, 'package.json') : null,
134
+ join(home, 'profiles', process.env.DSH_PROFILE || 'desktop', 'package.json'),
135
+ import.meta.url,
136
+ ].filter(Boolean)
137
+ ssh2Module = null
138
+ for (const base of bases) {
139
+ try {
140
+ ssh2Module = createRequire(base)('ssh2')
141
+ break
142
+ } catch { /* try next base */ }
143
+ }
144
+ return ssh2Module
145
+ }
146
+
147
+ /** One password-authenticated command over SSH (no system ssh, no key needed). */
148
+ function sshPassword(cfg, password, command, timeoutMs = 20_000) {
149
+ const ssh2 = loadSsh2()
150
+ if (!ssh2) {
151
+ return Promise.resolve({ ok: false, code: 127, stdout: '', stderr: 'ssh2 is not installed in this profile; add it or use key authentication' })
152
+ }
153
+ return new Promise((resolve) => {
154
+ let stdout = ''
155
+ let stderr = ''
156
+ let settled = false
157
+ const done = (result) => {
158
+ if (settled) return
159
+ settled = true
160
+ clearTimeout(timer)
161
+ try { conn.end() } catch { /* ignore */ }
162
+ resolve(result)
163
+ }
164
+ const conn = new ssh2.Client()
165
+ const timer = setTimeout(() => done({ ok: false, code: 124, stdout, stderr: stderr + '\n(connect or command timed out)' }), timeoutMs)
166
+ timer.unref?.()
167
+ conn.on('ready', () => {
168
+ conn.exec(command, (error, stream) => {
169
+ if (error) return done({ ok: false, code: 1, stdout, stderr: String(error.message || error) })
170
+ stream.on('data', (chunk) => { stdout += chunk.toString('utf8') })
171
+ stream.stderr.on('data', (chunk) => { stderr += chunk.toString('utf8') })
172
+ stream.on('close', (code) => done({ ok: code === 0, code: code ?? 1, stdout, stderr }))
173
+ })
174
+ })
175
+ conn.on('error', (error) => done({ ok: false, code: 255, stdout, stderr: String(error.message || error) }))
176
+ try {
177
+ conn.connect({
178
+ host: cfg.host,
179
+ port: Number(cfg.port || 22),
180
+ username: cfg.user || process.env.USER,
181
+ password,
182
+ readyTimeout: Math.min(timeoutMs, 15_000),
183
+ keepaliveInterval: 15_000,
184
+ keepaliveCountMax: 3,
185
+ tryKeyboard: false,
186
+ })
187
+ } catch (error) {
188
+ done({ ok: false, code: 255, stdout, stderr: String(error.message || error) })
189
+ }
190
+ })
191
+ }
192
+
193
+ async function ssh(cfg, command, timeoutMs = 20_000) {
194
+ const secrets = await loadSecrets()
195
+ const secret = secrets[cfg.name]
196
+ if (secret && secret.password) {
197
+ const password = Buffer.from(secret.password, 'base64').toString('utf8')
198
+ return sshPassword(cfg, password, command, timeoutMs)
199
+ }
200
+ const args = [
201
+ '-o', 'BatchMode=yes',
202
+ '-o', 'ConnectTimeout=8',
203
+ '-o', 'StrictHostKeyChecking=accept-new',
204
+ '-o', 'ServerAliveInterval=15',
205
+ '-o', 'ServerAliveCountMax=3',
206
+ ]
207
+ if (cfg.port) args.push('-p', String(cfg.port))
208
+ if (cfg.key) args.push('-i', cfg.key)
209
+ args.push(target(cfg), command)
210
+ try {
211
+ const { stdout, stderr } = await run('ssh', args, { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 })
212
+ return { ok: true, code: 0, stdout, stderr }
213
+ } catch (error) {
214
+ if (error && (error.killed || error.signal === 'SIGTERM')) {
215
+ return { ok: false, code: 124, stdout: error.stdout ?? '', stderr: `命令超时(${Math.round(timeoutMs / 1000)}s)` }
216
+ }
217
+ return {
218
+ ok: false,
219
+ code: typeof error.code === 'number' ? error.code : 1,
220
+ stdout: error.stdout ?? '',
221
+ stderr: error.stderr ?? error.message ?? String(error),
222
+ }
223
+ }
224
+ }
225
+
226
+ function clip(text, limit = MAX_OUTPUT) {
227
+ const value = String(text ?? '')
228
+ return value.length > limit ? `${value.slice(0, limit)}\n… (${value.length - limit} bytes truncated)` : value
229
+ }
230
+
231
+ function cleanStderr(text) {
232
+ const lines = String(text ?? '').split(/\r?\n/).map(line => line.trim()).filter(Boolean)
233
+ return lines.filter(line => !line.startsWith('**') && !/post-quantum/i.test(line)).join('\n')
234
+ }
235
+
236
+ /** One actionable next step for the most common ssh failures. */
237
+ function hintFor(stderr, cfg) {
238
+ const text = String(stderr ?? '')
239
+ const addr = `${cfg?.user ? `${cfg.user}@` : ''}${cfg?.host ?? ''}`
240
+ if (/Permission denied|publickey/i.test(text)) {
241
+ return `目标机还没装你的公钥。先执行一次:ssh-copy-id -i ~/.ssh/id_ed25519.pub ${addr}`
242
+ }
243
+ if (/Could not resolve hostname/i.test(text)) return '主机名解析失败,检查 ops_hosts 里的地址。'
244
+ if (/timed out/i.test(text)) return '连接超时:检查网络、防火墙和端口是否放行。'
245
+ if (/Connection refused/i.test(text)) return '端口拒绝:目标机没开 SSH,或端口不对。'
246
+ if (/超时|timed out|timeout/i.test(text)) return '命令超时:减少读取行数,或稍后重试。'
247
+ return ''
248
+ }
249
+
250
+ function summary(result, cfg) {
251
+ const stderr = cleanStderr(result.stderr)
252
+ const hint = result.ok ? '' : hintFor(stderr, cfg)
253
+ return {
254
+ ok: result.ok,
255
+ code: result.code,
256
+ stdout: clip(result.stdout),
257
+ stderr: clip(stderr),
258
+ ...(hint ? { hint } : {}),
259
+ }
260
+ }
261
+
262
+ const STATUS_COMMAND = [
263
+ 'echo "## uptime"; uptime',
264
+ 'echo "## memory"; (free -h 2>/dev/null || vm_stat 2>/dev/null | head -5)',
265
+ 'echo "## disk"; df -h / 2>/dev/null | tail -1',
266
+ 'echo "## failed-units"; (systemctl --failed --no-legend 2>/dev/null || echo "systemd not available")',
267
+ 'echo "## docker"; (docker ps --format "{{.Names}}\\t{{.Status}}" 2>/dev/null || echo "docker not available")',
268
+ ].join('; ')
269
+
270
+ function runStatus(cfg) {
271
+ return ssh(cfg, Array.isArray(STATUS_COMMAND) ? STATUS_COMMAND.join('\n') : STATUS_COMMAND, 25_000)
272
+ }
273
+
274
+ function statusOf(cfg) {
275
+ return ssh(cfg, STATUS_COMMAND, 25_000)
276
+ }
277
+
278
+ function firstLines(text, count = 2) {
279
+ return String(text ?? '').split('\n').map(line => line.trim()).filter(Boolean).slice(0, count).join(' · ')
280
+ }
281
+
282
+ /** Check every configured host in parallel and record one history entry per host. */
283
+ async function statusAll() {
284
+ const data = await loadHosts()
285
+ if (data.hosts.length === 0) throw new Error('no hosts configured: ask the agent to call ops_hosts with action="add", or add one in the panel')
286
+ const started = Date.now()
287
+ const results = await Promise.all(data.hosts.map(async (cfg) => {
288
+ const t0 = Date.now()
289
+ const result = await statusOf(cfg)
290
+ return {
291
+ host: cfg.name,
292
+ address: target(cfg),
293
+ ok: result.ok,
294
+ code: result.code,
295
+ elapsedMs: Date.now() - t0,
296
+ output: clip(result.stdout, 4_000),
297
+ error: cleanStderr(clip(result.stderr, 1_000)),
298
+ hint: result.ok ? '' : hintFor(cleanStderr(result.stderr), cfg),
299
+ }
300
+ }))
301
+ const at = new Date().toISOString()
302
+ await appendHistory(results.map(row => ({
303
+ at,
304
+ host: row.host,
305
+ ok: row.ok,
306
+ code: row.code,
307
+ elapsedMs: row.elapsedMs,
308
+ summary: row.ok ? firstLines(row.output) : clip(row.error, 200),
309
+ })))
310
+ return { at, elapsedMs: Date.now() - started, results }
311
+ }
312
+
313
+ const DANGEROUS = [
314
+ /(^|[\s;|&])rm\s+(-[a-z]*\s+)*\/(\s|$)/i,
315
+ /(^|[\s;|&])mkfs(\.|\s)/i,
316
+ /(^|[\s;|&])dd\s+[^;|&]*of=\/dev\//i,
317
+ /(^|[\s;|&])(shutdown|reboot|halt|poweroff)(\s|$)/i,
318
+ /(^|[\s;|&])init\s+0(\s|$)/i,
319
+ ]
320
+
321
+ function looksDangerous(command) {
322
+ return DANGEROUS.some(rx => rx.test(command))
323
+ }
324
+
325
+ function asTool(def) {
326
+ return {
327
+ name: def.name,
328
+ description: def.description,
329
+ parameters: {
330
+ type: 'object',
331
+ properties: def.parameters ?? {},
332
+ additionalProperties: false,
333
+ },
334
+ output: {
335
+ schema: { type: 'object' },
336
+ render(_args, value) {
337
+ return [{ type: 'text', text: JSON.stringify(value, null, 2) }]
338
+ },
339
+ },
340
+ execute: def.execute,
341
+ }
342
+ }
343
+
344
+ function sendJson(res, status, value) {
345
+ const body = JSON.stringify(value)
346
+ res.writeHead(status, {
347
+ 'content-type': 'application/json; charset=utf-8',
348
+ 'cache-control': 'no-store',
349
+ 'content-length': Buffer.byteLength(body),
350
+ })
351
+ res.end(body)
352
+ }
353
+
354
+ /** Read a small JSON body from a Node request. */
355
+ function readBody(req, limit = 64 * 1024) {
356
+ return new Promise((resolve) => {
357
+ let size = 0
358
+ const chunks = []
359
+ req.on('data', (chunk) => {
360
+ size += chunk.length
361
+ if (size > limit) { resolve(null); req.destroy(); return }
362
+ chunks.push(chunk)
363
+ })
364
+ req.on('end', () => {
365
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) } catch { resolve({}) }
366
+ })
367
+ req.on('error', () => resolve({}))
368
+ })
369
+ }
370
+
371
+ /**
372
+ * The panel's JSON API: Node request/response handlers registered on the web
373
+ * server. Authentication reuses the same trust gate as DSH's own routes.
374
+ */
375
+ function createApiHandler({ connection } = {}) {
376
+ return async function apiHandler(req, res) {
377
+ const method = String(req.method || 'GET').toUpperCase()
378
+
379
+ if (connection && typeof connection.requestRejection === 'function') {
380
+ let rejection
381
+ try { rejection = await connection.requestRejection(req) } catch { rejection = 403 }
382
+ if (rejection === 401 || rejection === 403) {
383
+ sendJson(res, rejection, { error: 'unauthorized' })
384
+ return
385
+ }
386
+ }
387
+
388
+ const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
389
+ const route = url.pathname.replace(/^\/ops-kit\/api\/?/, '').replace(/\/$/, '')
390
+
391
+ try {
392
+ if (route === 'hosts' && method === 'GET') {
393
+ const data = await loadHosts()
394
+ sendJson(res, 200, { hosts: data.hosts, defaultHost: data.defaultHost ?? null, file: hostsFile() })
395
+ return
396
+ }
397
+
398
+ if (route === 'hosts' && method === 'POST') {
399
+ const body = (await readBody(req)) || {}
400
+ const data = await loadHosts()
401
+ if (body.action === 'update') {
402
+ const host = data.hosts.find(h => h.name === body.name)
403
+ if (!host) { sendJson(res, 404, { error: 'unknown host' }); return }
404
+ if (body.host) host.host = String(body.host)
405
+ if (body.user) host.user = String(body.user)
406
+ if (body.port) host.port = Number(body.port)
407
+ if (body.alias !== undefined) host.alias = body.alias ? String(body.alias) : null
408
+ if (body.key !== undefined) host.key = body.key ? String(body.key) : null
409
+ await saveHosts(data)
410
+ if (body.password) await saveSecret(host.name, body.password)
411
+ sendJson(res, 200, { updated: host, hosts: data.hosts })
412
+ return
413
+ }
414
+ if (body.action === 'remove') {
415
+ const before = data.hosts.length
416
+ data.hosts = data.hosts.filter(h => h.name !== body.name)
417
+ if (data.defaultHost === body.name) data.defaultHost = data.hosts[0]?.name ?? null
418
+ await saveHosts(data)
419
+ await saveSecret(body.name, null)
420
+ sendJson(res, 200, { removed: before - data.hosts.length, hosts: data.hosts, defaultHost: data.defaultHost ?? null })
421
+ return
422
+ }
423
+ if (!body.name || !body.host) {
424
+ sendJson(res, 400, { error: 'name and host are required' })
425
+ return
426
+ }
427
+ const row = {
428
+ name: String(body.name),
429
+ host: String(body.host),
430
+ user: body.user ? String(body.user) : process.env.USER ?? null,
431
+ port: Number(body.port ?? 22),
432
+ key: body.key ? String(body.key) : null,
433
+ sudo: body.sudo === true,
434
+ }
435
+ data.hosts = data.hosts.filter(h => h.name !== row.name)
436
+ data.hosts.push(row)
437
+ if (body.defaultHost === true || !data.defaultHost) data.defaultHost = row.name
438
+ await saveHosts(data)
439
+ if (body.password) await saveSecret(row.name, body.password)
440
+ const probe = await ssh(row, 'echo ok', 12_000)
441
+ sendJson(res, 200, {
442
+ added: row,
443
+ hosts: data.hosts,
444
+ defaultHost: data.defaultHost ?? null,
445
+ passwordStored: Boolean(body.password),
446
+ tested: { ok: probe.ok, code: probe.code, error: probe.ok ? '' : cleanStderr(probe.stderr) },
447
+ })
448
+ return
449
+ }
450
+
451
+ if (route === 'status' && method === 'GET') {
452
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
453
+ const started = Date.now()
454
+ const result = await statusOf(cfg)
455
+ sendJson(res, 200, {
456
+ host: cfg.name,
457
+ address: target(cfg),
458
+ ok: result.ok,
459
+ code: result.code,
460
+ elapsedMs: Date.now() - started,
461
+ output: clip(result.stdout, MAX_OUTPUT),
462
+ error: cleanStderr(clip(result.stderr, 2_000)),
463
+ hint: result.ok ? '' : hintFor(cleanStderr(result.stderr), cfg),
464
+ })
465
+ return
466
+ }
467
+
468
+ if (route === 'status-all' && method === 'GET') {
469
+ sendJson(res, 200, await statusAll())
470
+ return
471
+ }
472
+
473
+ if (route === 'history' && method === 'GET') {
474
+ const limit = Math.min(Number(url.searchParams.get('limit') ?? 20) || 20, HISTORY_LIMIT)
475
+ sendJson(res, 200, { entries: (await loadHistory()).slice(0, limit) })
476
+ return
477
+ }
478
+
479
+ if (route === 'alerts' && method === 'GET') {
480
+ const limit = Math.min(Number(url.searchParams.get('limit') ?? 20) || 20, ALERT_LIMIT)
481
+ sendJson(res, 200, { entries: (await loadAlerts()).slice(0, limit) })
482
+ return
483
+ }
484
+
485
+ if (route === 'config') {
486
+ if (method === 'GET') {
487
+ const state = await loadState()
488
+ sendJson(res, 200, { config: await loadConfig(), lastRunAt: state.lastRunAt ? new Date(state.lastRunAt).toISOString() : null })
489
+ return
490
+ }
491
+ if (method === 'POST') {
492
+ const body = (await readBody(req)) || {}
493
+ const patch = {}
494
+ if (typeof body.enabled === 'boolean') patch.enabled = body.enabled
495
+ if (typeof body.intervalMinutes === 'number') patch.intervalMinutes = Math.max(1, Math.min(Math.round(body.intervalMinutes), 1440))
496
+ if (typeof body.diskWarnPercent === 'number') patch.diskWarnPercent = Math.max(50, Math.min(Math.round(body.diskWarnPercent), 99))
497
+ if (typeof body.metricsMinutes === 'number') patch.metricsMinutes = Math.max(1, Math.min(Math.round(body.metricsMinutes), 60))
498
+ if (typeof body.aiEnabled === 'boolean') patch.aiEnabled = body.aiEnabled
499
+ if (typeof body.aiProvider === 'string') patch.aiProvider = body.aiProvider.slice(0, 80)
500
+ if (typeof body.aiModel === 'string') patch.aiModel = body.aiModel.slice(0, 120)
501
+ if (Array.isArray(body.quickCommands)) {
502
+ patch.quickCommands = body.quickCommands
503
+ .map(item => String(item ?? '').trim())
504
+ .filter(Boolean)
505
+ .slice(0, 12)
506
+ .map(item => item.slice(0, 160))
507
+ }
508
+ if (typeof body.timeoutSec === 'number') patch.timeoutSec = Math.max(5, Math.min(Math.round(body.timeoutSec), 300))
509
+ if (typeof body.scanSec === 'number') patch.scanSec = Math.max(10, Math.min(Math.round(body.scanSec), 600))
510
+ if (typeof body.actionSec === 'number') patch.actionSec = Math.max(10, Math.min(Math.round(body.actionSec), 600))
511
+ sendJson(res, 200, { config: Object.keys(patch).length ? await saveConfig(patch) : await loadConfig() })
512
+ return
513
+ }
514
+ }
515
+
516
+ if (route === 'run' && method === 'POST') {
517
+ sendJson(res, 200, await runScheduledPass(true))
518
+ return
519
+ }
520
+
521
+ if (route === 'exec' && method === 'POST') {
522
+ const body = (await readBody(req)) || {}
523
+ const command = String(body.command ?? '').trim()
524
+ if (!command) { sendJson(res, 400, { error: 'command is required' }); return }
525
+ if (looksDangerous(command) && body.confirm !== true) {
526
+ sendJson(res, 400, { error: 'command looks destructive; pass confirm=true' })
527
+ return
528
+ }
529
+ sendJson(res, 200, await batchRun(command, Array.isArray(body.hosts) ? body.hosts : undefined))
530
+ return
531
+ }
532
+
533
+ if (route === 'units' && method === 'GET') {
534
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
535
+ sendJson(res, 200, await listUnits(cfg))
536
+ return
537
+ }
538
+
539
+ if (route === 'containers' && method === 'GET') {
540
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
541
+ sendJson(res, 200, await listContainers(cfg))
542
+ return
543
+ }
544
+
545
+ if (route === 'service' && method === 'POST') {
546
+ const body = (await readBody(req)) || {}
547
+ const action = String(body.action ?? 'status')
548
+ if (['start', 'stop', 'restart'].includes(action) && body.confirm !== true) {
549
+ sendJson(res, 400, { error: 'changing a service needs confirm=true' })
550
+ return
551
+ }
552
+ const cfg = pickHost(await loadHosts(), body.host)
553
+ sendJson(res, 200, await hostAction('service', cfg, String(body.service ?? ''), action))
554
+ return
555
+ }
556
+
557
+ if (route === 'docker' && method === 'POST') {
558
+ const body = (await readBody(req)) || {}
559
+ const action = String(body.action ?? 'logs')
560
+ if (action === 'restart' && body.confirm !== true) {
561
+ sendJson(res, 400, { error: 'restarting a container needs confirm=true' })
562
+ return
563
+ }
564
+ const cfg = pickHost(await loadHosts(), body.host)
565
+ sendJson(res, 200, await hostAction('docker', cfg, String(body.container ?? ''), action))
566
+ return
567
+ }
568
+
569
+ if (route === 'metrics' && method === 'GET') {
570
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
571
+ const hours = Math.min(Math.max(Number(url.searchParams.get('hours') ?? 6) || 6, 1), 24 * 30)
572
+ const rows = await loadMetrics(cfg.name, Date.now() - hours * 3_600_000)
573
+ sendJson(res, 200, { host: cfg.name, hours, samples: rows })
574
+ return
575
+ }
576
+
577
+ if (route === 'inventory' && method === 'GET') {
578
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
579
+ const cached = await loadInventory(cfg.name)
580
+ if (cached) { sendJson(res, 200, cached); return }
581
+ sendJson(res, 200, await discover(cfg))
582
+ return
583
+ }
584
+
585
+ if (route === 'discover' && method === 'POST') {
586
+ const body = (await readBody(req)) || {}
587
+ const cfg = pickHost(await loadHosts(), body.host)
588
+ sendJson(res, 200, await discover(cfg))
589
+ return
590
+ }
591
+
592
+ if (route === 'app' && method === 'POST') {
593
+ const body = (await readBody(req)) || {}
594
+ const kind = String(body.kind ?? '')
595
+ if (!['service', 'docker'].includes(kind)) { sendJson(res, 400, { error: 'unsupported app kind' }); return }
596
+ const action = String(body.action ?? 'logs')
597
+ if (action !== 'logs' && body.confirm !== true) { sendJson(res, 400, { error: 'changing an app needs confirm=true' }); return }
598
+ const cfg = pickHost(await loadHosts(), body.host)
599
+ sendJson(res, 200, await hostAction(kind, cfg, String(body.name ?? ''), action))
600
+ return
601
+ }
602
+
603
+ if (route === 'cleanup' && method === 'POST') {
604
+ const body = (await readBody(req)) || {}
605
+ if (body.confirm !== true) { sendJson(res, 400, { error: 'cleanup needs confirm=true' }); return }
606
+ const cfg = pickHost(await loadHosts(), body.host)
607
+ sendJson(res, 200, await cleanupDisk(cfg))
608
+ return
609
+ }
610
+
611
+ if (route === 'file' && method === 'GET') {
612
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
613
+ sendJson(res, 200, await readRemoteFile(cfg, url.searchParams.get('path') ?? ''))
614
+ return
615
+ }
616
+
617
+ if (route === 'file' && method === 'POST') {
618
+ const body = (await readBody(req, 512 * 1024)) || {}
619
+ if (body.confirm !== true) { sendJson(res, 400, { error: 'writing a config needs confirm=true' }); return }
620
+ const cfg = pickHost(await loadHosts(), body.host)
621
+ sendJson(res, 200, await writeRemoteFile(cfg, String(body.path ?? ''), String(body.content ?? '')))
622
+ return
623
+ }
624
+
625
+ if (route === 'diagnose' && method === 'POST') {
626
+ const body = (await readBody(req)) || {}
627
+ const cfg = pickHost(await loadHosts(), body.host)
628
+ sendJson(res, 200, await diagnose(cfg, String(body.question ?? '')))
629
+ return
630
+ }
631
+
632
+ if (route === 'du' && method === 'POST') {
633
+ const body = (await readBody(req)) || {}
634
+ const cfg = pickHost(await loadHosts(), body.host)
635
+ sendJson(res, 200, await diskUsage(cfg, String(body.path ?? '/')))
636
+ return
637
+ }
638
+
639
+ if (route === 'ps' && method === 'GET') {
640
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
641
+ sendJson(res, 200, await processList(cfg, url.searchParams.get('sort') ?? 'cpu'))
642
+ return
643
+ }
644
+
645
+ if (route === 'kill' && method === 'POST') {
646
+ const body = (await readBody(req)) || {}
647
+ if (body.confirm !== true) { sendJson(res, 400, { error: 'killing a process needs confirm=true' }); return }
648
+ const cfg = pickHost(await loadHosts(), body.host)
649
+ sendJson(res, 200, await killProcess(cfg, body.pid, body.signal))
650
+ return
651
+ }
652
+
653
+ if (route === 'tail' && method === 'GET') {
654
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
655
+ sendJson(res, 200, await tailLog(cfg, url.searchParams.get('source') ?? '', url.searchParams.get('lines') ?? 200))
656
+ return
657
+ }
658
+
659
+ if (route === 'ssl' && method === 'POST') {
660
+ const body = (await readBody(req)) || {}
661
+ const cfg = pickHost(await loadHosts(), body.host)
662
+ sendJson(res, 200, await sslCheck(cfg, body.domain))
663
+ return
664
+ }
665
+
666
+ if (route === 'files' && method === 'GET') {
667
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
668
+ sendJson(res, 200, await listDir(cfg, url.searchParams.get('path') ?? '/'))
669
+ return
670
+ }
671
+
672
+ if (route === 'download' && method === 'GET') {
673
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
674
+ sendJson(res, 200, await downloadFile(cfg, url.searchParams.get('path') ?? ''))
675
+ return
676
+ }
677
+
678
+ if (route === 'upload' && method === 'POST') {
679
+ const body = (await readBody(req, 12 * 1024 * 1024)) || {}
680
+ const cfg = pickHost(await loadHosts(), body.host)
681
+ sendJson(res, 200, await uploadFile(cfg, String(body.path ?? ''), String(body.base64 ?? '')))
682
+ return
683
+ }
684
+
685
+ if (route === 'fs' && method === 'POST') {
686
+ const body = (await readBody(req)) || {}
687
+ const cfg = pickHost(await loadHosts(), body.host)
688
+ sendJson(res, 200, await fsAction(cfg, String(body.action ?? ''), String(body.path ?? ''), body.confirm))
689
+ return
690
+ }
691
+
692
+ if (route === 'conn' && method === 'GET') {
693
+ sendJson(res, 200, { connections: await loadConnections() })
694
+ return
695
+ }
696
+
697
+ if (route === 'test' && method === 'POST') {
698
+ const body = (await readBody(req)) || {}
699
+ const cfg = pickHost(await loadHosts(), body.host)
700
+ sendJson(res, 200, await testConnection(cfg))
701
+ return
702
+ }
703
+
704
+ if (route === 'install-key' && method === 'POST') {
705
+ const body = (await readBody(req)) || {}
706
+ const cfg = pickHost(await loadHosts(), body.host)
707
+ sendJson(res, 200, await installKey(cfg))
708
+ return
709
+ }
710
+
711
+ if (route === 'term/open' && method === 'POST') {
712
+ const body = (await readBody(req)) || {}
713
+ const cfg = pickHost(await loadHosts(), body.host)
714
+ sendJson(res, 200, await openTerminal(cfg, body.cols, body.rows))
715
+ return
716
+ }
717
+
718
+ if (route === 'term/poll' && method === 'GET') {
719
+ sendJson(res, 200, terminalPoll(url.searchParams.get('id') ?? '', url.searchParams.get('since') ?? 0))
720
+ return
721
+ }
722
+
723
+ if (route === 'term/input' && method === 'POST') {
724
+ const body = (await readBody(req)) || {}
725
+ sendJson(res, 200, terminalInput(String(body.id ?? ''), String(body.data ?? '')))
726
+ return
727
+ }
728
+
729
+ if (route === 'term/resize' && method === 'POST') {
730
+ const body = (await readBody(req)) || {}
731
+ sendJson(res, 200, terminalResize(String(body.id ?? ''), body.cols, body.rows))
732
+ return
733
+ }
734
+
735
+ if (route === 'term/close' && method === 'POST') {
736
+ const body = (await readBody(req)) || {}
737
+ sendJson(res, 200, terminalClose(String(body.id ?? '')))
738
+ return
739
+ }
740
+
741
+ if (route === 'ai-command' && method === 'POST') {
742
+ const body = (await readBody(req)) || {}
743
+ const cfg = pickHost(await loadHosts(), body.host)
744
+ sendJson(res, 200, await aiCommand(cfg, body.intent))
745
+ return
746
+ }
747
+
748
+ if (route === 'ask' && method === 'POST') {
749
+ const body = (await readBody(req)) || {}
750
+ const cfg = pickHost(await loadHosts(), body.host)
751
+ sendJson(res, 200, await askAboutHost(cfg, String(body.question ?? '')))
752
+ return
753
+ }
754
+
755
+ if (route === 'ai-models' && method === 'GET') {
756
+ const ctx = hostCtx
757
+ const llm = ctx ? (typeof ctx.get === 'function' ? (ctx.get('llm') ?? ctx.llm) : ctx.llm) : null
758
+ const defaults = ctx ? (typeof ctx.get === 'function' ? (ctx.get('agentDefaultModel') ?? ctx.agentDefaultModel) : ctx.agentDefaultModel) : null
759
+ const providers = await collectModels(llm)
760
+ const config = await loadConfig()
761
+ sendJson(res, 200, {
762
+ aiEnabled: config.aiEnabled !== false,
763
+ aiProvider: config.aiProvider || '',
764
+ aiModel: config.aiModel || '',
765
+ defaultSelection: defaults?.currentSelection?.() ?? null,
766
+ providers,
767
+ })
768
+ return
769
+ }
770
+
771
+ if (route === 'monitors' && method === 'GET') {
772
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
773
+ const all = await loadMonitors()
774
+ sendJson(res, 200, { host: cfg.name, monitors: all[cfg.name] || [] })
775
+ return
776
+ }
777
+
778
+ if (route === 'monitors' && method === 'POST') {
779
+ const body = (await readBody(req)) || {}
780
+ const cfg = pickHost(await loadHosts(), body.host)
781
+ const all = await loadMonitors()
782
+ const list = all[cfg.name] || []
783
+ if (body.action === 'remove') {
784
+ all[cfg.name] = list.filter(item => item.id !== body.id)
785
+ await saveMonitors(all)
786
+ sendJson(res, 200, { host: cfg.name, monitors: all[cfg.name] })
787
+ return
788
+ }
789
+ if (body.action === 'update' && body.id) {
790
+ const monitor = list.find(item => item.id === body.id)
791
+ if (!monitor) { sendJson(res, 404, { error: 'monitor not found' }); return }
792
+ if (body.type) monitor.type = ['http', 'port', 'process', 'service', 'script'].includes(body.type) ? body.type : monitor.type
793
+ if (body.target !== undefined) monitor.target = String(body.target).trim().slice(0, 200)
794
+ if (body.label !== undefined) monitor.label = String(body.label).trim().slice(0, 40)
795
+ if (body.intervalMinutes !== undefined) monitor.intervalMinutes = Math.max(1, Math.min(Number(body.intervalMinutes) || 5, 1440))
796
+ if (body.language !== undefined) monitor.language = ['shell', 'python', 'js'].includes(body.language) ? body.language : monitor.language
797
+ if (body.script !== undefined) monitor.script = String(body.script).slice(0, 4000)
798
+ await saveMonitors(all)
799
+ const result = await runMonitor(cfg, monitor)
800
+ monitor.last = result
801
+ monitor.lastOk = result.ok
802
+ await saveMonitors(all)
803
+ sendJson(res, 200, { host: cfg.name, monitors: all[cfg.name] })
804
+ return
805
+ }
806
+ if (body.action === 'test' && body.id) {
807
+ const monitor = list.find(item => item.id === body.id)
808
+ if (!monitor) { sendJson(res, 404, { error: 'monitor not found' }); return }
809
+ const result = await runMonitor(cfg, monitor)
810
+ monitor.last = result
811
+ monitor.lastOk = result.ok
812
+ await saveMonitors(all)
813
+ sendJson(res, 200, { host: cfg.name, id: monitor.id, result })
814
+ return
815
+ }
816
+ const monitor = {
817
+ id: `m${Date.now().toString(36)}`,
818
+ type: ['http', 'port', 'process', 'service', 'script'].includes(body.type) ? body.type : 'http',
819
+ target: String(body.target ?? '').trim().slice(0, 200),
820
+ label: String(body.label ?? '').trim().slice(0, 40),
821
+ intervalMinutes: Math.max(1, Math.min(Number(body.intervalMinutes) || 5, 1440)),
822
+ createdAt: new Date().toISOString(),
823
+ ...(['shell', 'python', 'js'].includes(body.language) ? { language: body.language } : {}),
824
+ ...(body.script ? { script: String(body.script).slice(0, 4000) } : {}),
825
+ }
826
+ if (monitor.type === 'script' ? !monitor.script : !monitor.target) {
827
+ sendJson(res, 400, { error: monitor.type === 'script' ? 'script is required' : 'target is required' })
828
+ return
829
+ }
830
+ all[cfg.name] = [...list, monitor]
831
+ await saveMonitors(all)
832
+ const result = await runMonitor(cfg, monitor)
833
+ all[cfg.name] = all[cfg.name].map(item => item.id === monitor.id ? { ...item, last: result, lastOk: result.ok } : item)
834
+ await saveMonitors(all)
835
+ sendJson(res, 200, { host: cfg.name, monitors: all[cfg.name] })
836
+ return
837
+ }
838
+
839
+ if (route === 'backups' && method === 'GET') {
840
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
841
+ const all = await loadJsonFile('backups.json', {})
842
+ sendJson(res, 200, { host: cfg.name, backups: all[cfg.name] || [] })
843
+ return
844
+ }
845
+
846
+ if (route === 'backups' && method === 'POST') {
847
+ const body = (await readBody(req)) || {}
848
+ const cfg = pickHost(await loadHosts(), body.host)
849
+ if (body.action === 'restore') { sendJson(res, 200, await restoreBackup(cfg, body.id)); return }
850
+ if (body.action === 'remove') {
851
+ const all = await loadJsonFile('backups.json', {})
852
+ const list = all[cfg.name] || []
853
+ const record = list.find(item => item.id === body.id)
854
+ if (record) await ssh(cfg, `rm -f ${q(record.file)}`, 30_000)
855
+ all[cfg.name] = list.filter(item => item.id !== body.id)
856
+ await saveJsonFile('backups.json', all)
857
+ sendJson(res, 200, { host: cfg.name, backups: all[cfg.name] })
858
+ return
859
+ }
860
+ sendJson(res, 200, await runBackup(cfg, body))
861
+ return
862
+ }
863
+
864
+ if (route === 'health' && method === 'GET') {
865
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
866
+ sendJson(res, 200, await computeHealth(cfg))
867
+ return
868
+ }
869
+
870
+ if (route === 'certs' && method === 'GET') {
871
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
872
+ sendJson(res, 200, { host: cfg.name, certs: await scanCerts(cfg) })
873
+ return
874
+ }
875
+
876
+ if (route === 'certs' && method === 'POST') {
877
+ const body = (await readBody(req)) || {}
878
+ const cfg = pickHost(await loadHosts(), body.host)
879
+ sendJson(res, 200, await renewCerts(cfg, body.dryRun !== false))
880
+ return
881
+ }
882
+
883
+ if (route === 'cron' && method === 'GET') {
884
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
885
+ sendJson(res, 200, { host: cfg.name, jobs: await listCron(cfg) })
886
+ return
887
+ }
888
+
889
+ if (route === 'cron' && method === 'POST') {
890
+ const body = (await readBody(req)) || {}
891
+ const cfg = pickHost(await loadHosts(), body.host)
892
+ if (body.action === 'remove') { sendJson(res, 200, await removeCron(cfg, body.index)); return }
893
+ sendJson(res, 200, await addCron(cfg, body))
894
+ return
895
+ }
896
+
897
+ if (route === 'file-history' && method === 'GET') {
898
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
899
+ sendJson(res, 200, { host: cfg.name, backups: await fileHistory(cfg, url.searchParams.get('path') ?? '') })
900
+ return
901
+ }
902
+
903
+ if (route === 'file-history' && method === 'POST') {
904
+ const body = (await readBody(req)) || {}
905
+ const cfg = pickHost(await loadHosts(), body.host)
906
+ if (body.action === 'restore') { sendJson(res, 200, await fileRestore(cfg, body.path, body.backup)); return }
907
+ sendJson(res, 200, await fileDiff(cfg, body.path, body.backup))
908
+ return
909
+ }
910
+
911
+ if (route === 'deploy' && method === 'GET') {
912
+ const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
913
+ const all = await loadJsonFile('deploys.json', {})
914
+ sendJson(res, 200, { host: cfg.name, jobs: all[cfg.name] || [] })
915
+ return
916
+ }
917
+
918
+ if (route === 'deploy' && method === 'POST') {
919
+ const body = (await readBody(req)) || {}
920
+ const cfg = pickHost(await loadHosts(), body.host)
921
+ const all = await loadJsonFile('deploys.json', {})
922
+ const list = all[cfg.name] || []
923
+ if (body.action === 'remove') {
924
+ all[cfg.name] = list.filter(item => item.id !== body.id)
925
+ await saveJsonFile('deploys.json', all)
926
+ sendJson(res, 200, { host: cfg.name, jobs: all[cfg.name] })
927
+ return
928
+ }
929
+ if (body.action === 'save') {
930
+ const job = { id: body.id || `d${Date.now().toString(36)}`, name: String(body.name || '发布').slice(0, 40), dir: body.dir, repo: body.repo || '', branch: body.branch || 'origin/main', build: body.build || '', restart: body.restart || '', health: body.health || '', rollback: body.rollback !== false }
931
+ all[cfg.name] = body.id ? list.map(item => item.id === body.id ? { ...item, ...job } : item) : [...list, job]
932
+ await saveJsonFile('deploys.json', all)
933
+ sendJson(res, 200, { host: cfg.name, jobs: all[cfg.name] })
934
+ return
935
+ }
936
+ const job = list.find(item => item.id === body.id) || body.job
937
+ if (!job) { sendJson(res, 404, { error: '发布任务不存在' }); return }
938
+ sendJson(res, 200, await runDeploy(cfg, job))
939
+ return
940
+ }
941
+
942
+ if (route === 'channels' && method === 'GET') {
943
+ const { channels } = await loadChannels()
944
+ sendJson(res, 200, { channels })
945
+ return
946
+ }
947
+
948
+ if (route === 'channels' && method === 'POST') {
949
+ const body = (await readBody(req)) || {}
950
+ const all = await loadChannels()
951
+ const list = all.channels
952
+ if (body.action === 'remove') {
953
+ all.channels = list.filter(item => item.id !== body.id)
954
+ await saveChannels(all)
955
+ sendJson(res, 200, { channels: all.channels })
956
+ return
957
+ }
958
+ if (body.action === 'test') {
959
+ const channel = list.find(item => item.id === body.id) || { type: body.type || 'webhook', url: body.url }
960
+ if (!channel?.url) { sendJson(res, 400, { error: 'webhook url is required' }); return }
961
+ sendJson(res, 200, await testChannel(channel))
962
+ return
963
+ }
964
+ const type = CHANNEL_TYPES.includes(body.type) ? body.type : 'webhook'
965
+ const url = String(body.url || '').trim()
966
+ if (!/^https?:\/\//.test(url)) { sendJson(res, 400, { error: 'webhook url must start with http(s)://' }); return }
967
+ const channel = {
968
+ id: body.id || `c${Date.now().toString(36)}`,
969
+ type,
970
+ name: String(body.name || type).slice(0, 40),
971
+ url,
972
+ events: Array.isArray(body.events) && body.events.length ? body.events : ['critical', 'warning'],
973
+ enabled: body.enabled !== false,
974
+ }
975
+ all.channels = body.id ? list.map(item => item.id === body.id ? { ...item, ...channel } : item) : [...list, channel]
976
+ await saveChannels(all)
977
+ sendJson(res, 200, { channels: all.channels })
978
+ return
979
+ }
980
+
981
+ sendJson(res, 404, { error: 'not found' })
982
+ } catch (error) {
983
+ sendJson(res, 500, { error: error?.message ?? String(error) })
984
+ }
985
+ }
986
+ }
987
+
988
+
989
+
990
+ const DEFAULT_CONFIG = {
991
+ enabled: true,
992
+ intervalMinutes: 10,
993
+ diskWarnPercent: 90,
994
+ metricsMinutes: 5,
995
+ timeoutSec: 25,
996
+ scanSec: 90,
997
+ actionSec: 45,
998
+ quickCommands: ['df -h', 'free -h', 'uptime', 'systemctl --failed', 'docker ps', 'tail -n 30 /var/log/messages'],
999
+ aiEnabled: true,
1000
+ aiProvider: '',
1001
+ aiModel: '',
1002
+ }
1003
+ const ALERT_LIMIT = 200
1004
+
1005
+ function configFile() { return join(kitDir(), 'config.json') }
1006
+ function stateFile() { return join(kitDir(), 'state.json') }
1007
+ function alertsFile() { return join(kitDir(), 'alerts.json') }
1008
+
1009
+ async function loadConfig() {
1010
+ try {
1011
+ const data = JSON.parse(await readFile(configFile(), 'utf8'))
1012
+ return { ...DEFAULT_CONFIG, ...data }
1013
+ } catch {
1014
+ return { ...DEFAULT_CONFIG }
1015
+ }
1016
+ }
1017
+
1018
+ async function saveConfig(patch) {
1019
+ const next = { ...(await loadConfig()), ...patch }
1020
+ await mkdir(kitDir(), { recursive: true })
1021
+ await writeFile(configFile(), JSON.stringify(next, null, 2) + '\n', 'utf8')
1022
+ return next
1023
+ }
1024
+
1025
+ async function loadState() {
1026
+ try {
1027
+ const data = JSON.parse(await readFile(stateFile(), 'utf8'))
1028
+ return { hosts: data.hosts ?? {}, lastRunAt: data.lastRunAt ?? 0 }
1029
+ } catch {
1030
+ return { hosts: {}, lastRunAt: 0 }
1031
+ }
1032
+ }
1033
+
1034
+ /** Merge-write the state file so concurrent passes do not clobber each other. */
1035
+ async function patchState(patch) {
1036
+ const current = await loadState()
1037
+ const next = { ...current, ...patch }
1038
+ await mkdir(kitDir(), { recursive: true })
1039
+ await writeFile(stateFile(), JSON.stringify(next, null, 2) + '\n', 'utf8')
1040
+ return next
1041
+ }
1042
+
1043
+ async function loadAlerts() {
1044
+ try {
1045
+ const data = JSON.parse(await readFile(alertsFile(), 'utf8'))
1046
+ return Array.isArray(data.entries) ? data.entries : []
1047
+ } catch {
1048
+ return []
1049
+ }
1050
+ }
1051
+
1052
+ async function appendAlerts(rows) {
1053
+ const list = (rows || []).filter(Boolean)
1054
+ const all = [...list, ...(await loadAlerts())].slice(0, ALERT_LIMIT)
1055
+ await mkdir(kitDir(), { recursive: true })
1056
+ await writeFile(alertsFile(), JSON.stringify({ entries: all }, null, 2) + '\n', 'utf8')
1057
+ if (list.length > 0) void dispatchAlerts(list).catch(() => {})
1058
+ return all
1059
+ }
1060
+
1061
+ /** Pull the numbers the alert rules care about out of the status text. */
1062
+ function parseStatus(output) {
1063
+ const text = String(output ?? '')
1064
+ const sections = sectionsOf(text)
1065
+ const section = (title) => String(sections[title] ?? '').trim()
1066
+ const disk = section('disk')
1067
+ const percent = Number((disk.match(/(\d+)%/) || [])[1] ?? NaN)
1068
+ const units = section('failed-units')
1069
+ .split('\n')
1070
+ .map(line => line.trim())
1071
+ .filter(line => line && !/systemd not available/i.test(line) && !line.startsWith('##'))
1072
+ const docker = section('docker')
1073
+ return {
1074
+ diskPercent: Number.isFinite(percent) ? percent : null,
1075
+ failedUnits: units,
1076
+ docker: /docker not available/i.test(docker) ? null : docker,
1077
+ }
1078
+ }
1079
+
1080
+ /** Compare one run with the previous snapshot and emit alerts for changes. */
1081
+ async function diffRun(results) {
1082
+ const config = await loadConfig()
1083
+ const state = await loadState()
1084
+ const rows = []
1085
+ for (const row of results) {
1086
+ const prev = state.hosts[row.host]
1087
+ const parsed = row.ok ? parseStatus(row.output) : null
1088
+ if (prev?.ok === true && !row.ok) {
1089
+ rows.push({ level: 'critical', kind: 'down', host: row.host, message: `${row.host} unreachable (exit ${row.code})` })
1090
+ }
1091
+ if (prev?.ok === false && row.ok) {
1092
+ rows.push({ level: 'info', kind: 'recovered', host: row.host, message: `${row.host} recovered` })
1093
+ }
1094
+ if (parsed && parsed.diskPercent !== null && parsed.diskPercent >= config.diskWarnPercent) {
1095
+ rows.push({
1096
+ level: parsed.diskPercent >= 95 ? 'critical' : 'warning',
1097
+ kind: 'disk',
1098
+ host: row.host,
1099
+ message: `disk ${parsed.diskPercent}% on ${row.host} (warn at ${config.diskWarnPercent}%)`,
1100
+ })
1101
+ }
1102
+ if (parsed && parsed.failedUnits.length > 0 && (prev?.failedUnits ?? 0) === 0) {
1103
+ rows.push({ level: 'warning', kind: 'units', host: row.host, message: `${parsed.failedUnits.length} failed systemd unit(s) on ${row.host}` })
1104
+ }
1105
+ state.hosts[row.host] = {
1106
+ ok: row.ok,
1107
+ at: new Date().toISOString(),
1108
+ diskPercent: parsed?.diskPercent ?? null,
1109
+ failedUnits: parsed?.failedUnits?.length ?? 0,
1110
+ }
1111
+ }
1112
+ await patchState({ hosts: state.hosts, lastRunAt: Date.now() })
1113
+ if (rows.length > 0) {
1114
+ const at = new Date().toISOString()
1115
+ await appendAlerts(rows.map(row => ({ at, ...row })))
1116
+ }
1117
+ return rows
1118
+ }
1119
+
1120
+ /** Sample cpu/mem/disk when the metrics interval elapsed. */
1121
+ async function runMetricsPass(force = false) {
1122
+ const config = await loadConfig()
1123
+ const state = await loadState()
1124
+ const interval = Math.max(1, Number(config.metricsMinutes ?? 5) || 5) * 60_000
1125
+ if (!force && Date.now() - (state.lastMetricsAt ?? 0) < interval) return null
1126
+ await patchState({ lastMetricsAt: Date.now() })
1127
+ return sampleAllMetrics()
1128
+ }
1129
+
1130
+ /** Run one scheduled pass when the interval elapsed; returns null when skipped. */
1131
+ async function runScheduledPass(force = false) {
1132
+ const config = await loadConfig()
1133
+ if (!config.enabled && !force) return null
1134
+ const state = await loadState()
1135
+ const interval = Math.max(1, Number(config.intervalMinutes) || 10) * 60_000
1136
+ if (!force && Date.now() - state.lastRunAt < interval) return null
1137
+ const out = await statusAll()
1138
+ const alerts = await diffRun(out.results)
1139
+ return { at: out.at, hosts: out.results.length, alerts }
1140
+ }
1141
+
1142
+
1143
+ /** Run one command on several hosts in parallel. */
1144
+ async function batchRun(command, hostNames) {
1145
+ const data = await loadHosts()
1146
+ const targets = hostNames && hostNames.length > 0
1147
+ ? data.hosts.filter(host => hostNames.includes(host.name))
1148
+ : data.hosts
1149
+ if (targets.length === 0) throw new Error('no matching hosts')
1150
+ const started = Date.now()
1151
+ const results = await Promise.all(targets.map(async (cfg) => {
1152
+ const t0 = Date.now()
1153
+ const result = await ssh(cfg, command, 30_000)
1154
+ return {
1155
+ host: cfg.name,
1156
+ ok: result.ok,
1157
+ code: result.code,
1158
+ elapsedMs: Date.now() - t0,
1159
+ stdout: clip(result.stdout, 4_000),
1160
+ stderr: cleanStderr(clip(result.stderr, 1_500)),
1161
+ }
1162
+ }))
1163
+ return { at: new Date().toISOString(), command, elapsedMs: Date.now() - started, results }
1164
+ }
1165
+
1166
+ /** Running systemd services on one host (bounded list). */
1167
+ async function listUnits(cfg) {
1168
+ const result = await ssh(cfg, "systemctl list-units --type=service --state=running --no-legend --no-pager 2>/dev/null | awk '{print $1}' | head -40", 15_000)
1169
+ return {
1170
+ host: cfg.name,
1171
+ ok: result.ok,
1172
+ units: result.ok
1173
+ ? result.stdout.split('\n').map(line => line.trim()).filter(Boolean)
1174
+ : [],
1175
+ error: result.ok ? '' : cleanStderr(result.stderr),
1176
+ }
1177
+ }
1178
+
1179
+ /** Container names on one host. */
1180
+ async function listContainers(cfg) {
1181
+ const result = await ssh(cfg, "docker ps -a --format '{{.Names}}' 2>/dev/null | head -40", 15_000)
1182
+ return {
1183
+ host: cfg.name,
1184
+ ok: result.ok,
1185
+ containers: result.ok ? result.stdout.split('\n').map(line => line.trim()).filter(Boolean) : [],
1186
+ error: result.ok ? '' : cleanStderr(result.stderr),
1187
+ }
1188
+ }
1189
+
1190
+ /** systemctl or docker action, with the same guard as the agent tools. */
1191
+ async function hostAction(kind, cfg, target, action) {
1192
+ const changing = ['start', 'stop', 'restart'].includes(action)
1193
+ const prefix = cfg.sudo ? 'sudo -n ' : ''
1194
+ let command
1195
+ if (kind === 'service') {
1196
+ command = action === 'logs'
1197
+ ? `${prefix}journalctl -u ${target} -n 60 --no-pager`
1198
+ : `${prefix}systemctl ${action} ${target}`
1199
+ } else {
1200
+ const safe = String(target).replace(/[^A-Za-z0-9_.-]/g, '')
1201
+ command = action === 'logs'
1202
+ ? `${prefix}docker logs --tail 80 ${safe}`
1203
+ : `${prefix}docker ${action} ${safe}`
1204
+ }
1205
+ const result = await ssh(cfg, command, 30_000)
1206
+ return { host: cfg.name, kind, target, action, changing, ...summary(result, cfg) }
1207
+ }
1208
+
1209
+
1210
+ const METRICS_LIMIT = 20000
1211
+
1212
+ function metricsFile() { return join(kitDir(), 'metrics.jsonl') }
1213
+ function inventoryFile() { return join(kitDir(), 'inventory.json') }
1214
+
1215
+ async function appendMetrics(samples) {
1216
+ await mkdir(kitDir(), { recursive: true })
1217
+ const lines = samples.map(sample => JSON.stringify(sample)).join('\n') + '\n'
1218
+ await writeFile(metricsFile(), lines, { flag: 'a' })
1219
+ }
1220
+
1221
+ async function loadMetrics(host, sinceMs = 0) {
1222
+ try {
1223
+ const text = await readFile(metricsFile(), 'utf8')
1224
+ const rows = []
1225
+ for (const line of text.split('\n')) {
1226
+ if (!line.trim()) continue
1227
+ let row
1228
+ try { row = JSON.parse(line) } catch { continue }
1229
+ if (row.host !== host) continue
1230
+ if (row.ts < sinceMs) continue
1231
+ rows.push(row)
1232
+ }
1233
+ return rows.slice(-METRICS_LIMIT)
1234
+ } catch {
1235
+ return []
1236
+ }
1237
+ }
1238
+
1239
+ const METRICS_COMMAND = `
1240
+ read -r _ u1 n1 s1 i1 w1 q1 sq1 st1 _ < /proc/stat
1241
+ sleep 1
1242
+ read -r _ u2 n2 s2 i2 w2 q2 sq2 st2 _ < /proc/stat
1243
+ t1=$((u1+n1+s1+i1+w1+q1+sq1+st1)); t2=$((u2+n2+s2+i2+w2+q2+sq2+st2))
1244
+ id1=$((i1+w1)); id2=$((i2+w2)); dt=$((t2-t1)); di=$((id2-id1))
1245
+ if [ "$dt" -gt 0 ]; then echo "CPU $((100 - di*100/dt))"; else echo "CPU 0"; fi
1246
+ awk '{print "LOAD "$1" "$2" "$3}' /proc/loadavg 2>/dev/null
1247
+ awk '/^MemTotal/{t=$2} /^MemAvailable/{a=$2} /^SwapTotal/{s=$2} /^SwapFree/{f=$2} END{print "MEM "t" "a" "s" "f}' /proc/meminfo 2>/dev/null
1248
+ df -P / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print "DISK "$5}'
1249
+ awk -F'[: ]+' '/^ *(eth|ens|enp|eno)/{rx+=$3;tx+=$11} END{print "NET "rx" "tx}' /proc/net/dev 2>/dev/null
1250
+ awk '{r+=$3; w+=$7} END{print "IO "r" "w}' /proc/diskstats 2>/dev/null
1251
+ echo "PROCS $(ls /proc 2>/dev/null | grep -c '^[0-9][0-9]*$')"
1252
+ awk '{print "UPTIME "int($1)}' /proc/uptime 2>/dev/null
1253
+ echo "TCP $(ss -H -tan state established 2>/dev/null | wc -l)"
1254
+ `
1255
+
1256
+ /** One rich metrics sample: cpu %, load, memory, swap, disk, net, io, procs, tcp. */
1257
+ async function sampleMetrics(cfg) {
1258
+ const result = await ssh(cfg, METRICS_COMMAND, 25_000)
1259
+ if (!result.ok) return { host: cfg.name, ts: Date.now(), ok: false }
1260
+ const read = (key) => {
1261
+ const match = result.stdout.match(new RegExp(`^${key} (.*)$`, 'm'))
1262
+ return match ? match[1].trim() : ''
1263
+ }
1264
+ const num = (value) => {
1265
+ const n = Number(value)
1266
+ return Number.isFinite(n) ? n : null
1267
+ }
1268
+ const load = read('LOAD').split(/\s+/).map(Number)
1269
+ const mem = read('MEM').split(/\s+/).map(Number)
1270
+ const net = read('NET').split(/\s+/).map(Number)
1271
+ const io = read('IO').split(/\s+/).map(Number)
1272
+ const memTotal = mem[0] || 0
1273
+ const memAvail = mem[1] || 0
1274
+ const swapTotal = mem[2] || 0
1275
+ const swapFree = mem[3] || 0
1276
+ return {
1277
+ host: cfg.name,
1278
+ ts: Date.now(),
1279
+ ok: true,
1280
+ cpu: num(read('CPU')),
1281
+ load1: num(load[0]),
1282
+ load5: num(load[1]),
1283
+ load15: num(load[2]),
1284
+ mem: memTotal > 0 ? Math.round(((memTotal - memAvail) / memTotal) * 100) : null,
1285
+ swap: swapTotal > 0 ? Math.round(((swapTotal - swapFree) / swapTotal) * 100) : 0,
1286
+ disk: num(read('DISK')),
1287
+ rx: Number.isFinite(net[0]) ? net[0] : null,
1288
+ tx: Number.isFinite(net[1]) ? net[1] : null,
1289
+ ioRead: Number.isFinite(io[0]) ? io[0] : null,
1290
+ ioWrite: Number.isFinite(io[1]) ? io[1] : null,
1291
+ procs: num(read('PROCS')),
1292
+ uptimeSec: num(read('UPTIME')),
1293
+ tcp: num(read('TCP')),
1294
+ }
1295
+ }
1296
+
1297
+ async function sampleAllMetrics() {
1298
+ const data = await loadHosts()
1299
+ const samples = []
1300
+ for (const cfg of data.hosts) {
1301
+ try { samples.push(await sampleMetrics(cfg)) } catch { /* keep going */ }
1302
+ }
1303
+ if (samples.length > 0) await appendMetrics(samples)
1304
+ return samples
1305
+ }
1306
+
1307
+ const INVENTORY_COMMAND = [
1308
+ 'echo "## ports"; (ss -lntp 2>/dev/null || netstat -lnt 2>/dev/null) | head -40',
1309
+ 'echo "## services"; systemctl list-units --type=service --state=running --no-legend --no-pager 2>/dev/null | awk \'{print $1}\' | head -40',
1310
+ 'echo "## docker"; docker ps -a --format "{{.Names}}\\t{{.Status}}\\t{{.Ports}}" 2>/dev/null | head -30',
1311
+ 'echo "## nginx"; (nginx -T 2>/dev/null | grep -E "^\\s*(server_name|listen|root)" | head -40)',
1312
+ 'echo "## java"; ps -eo pid,etime,cmd 2>/dev/null | grep -E "[j]ava" | head -12',
1313
+ 'echo "## crontab"; crontab -l 2>/dev/null | head -20',
1314
+ 'echo "## mounts"; df -h 2>/dev/null | head -12',
1315
+ 'echo "## configs"; for f in /etc/nginx/nginx.conf /etc/nginx/conf.d/*.conf /etc/my.cnf /etc/redis.conf /etc/redis/redis.conf /etc/systemd/system/nginx.service; do [ -f "$f" ] && echo "$f"; done',
1316
+ 'echo "## units"; for u in $(systemctl list-units --type=service --state=running --no-legend --no-pager 2>/dev/null | awk "{print \$1}" | head -30); do p=$(systemctl show -p FragmentPath --value "$u" 2>/dev/null); [ -n "$p" ] && [ "$p" != "/dev/null" ] && echo "$u|$p"; done',
1317
+ ].join('; ') + '; true'
1318
+
1319
+ function sectionsOf(text) {
1320
+ const map = {}
1321
+ for (const part of String(text ?? '').split(/^## /m).slice(1)) {
1322
+ const nl = part.indexOf('\n')
1323
+ const name = (nl === -1 ? part : part.slice(0, nl)).trim()
1324
+ map[name] = nl === -1 ? '' : part.slice(nl + 1).trim()
1325
+ }
1326
+ return map
1327
+ }
1328
+
1329
+ /** Read-only inventory: ports, services, containers, nginx sites, java, cron, mounts. */
1330
+ async function discover(cfg) {
1331
+ const result = await ssh(cfg, INVENTORY_COMMAND, 30_000)
1332
+ const text = result.ok ? result.stdout : ''
1333
+ const sections = sectionsOf(text)
1334
+ const lines = (title) => String(sections[title] ?? '').split('\n').map(line => line.trim()).filter(Boolean)
1335
+ const docker = lines('docker').map(line => {
1336
+ const [name, status, ports] = line.split('\t')
1337
+ return { name, status: status || '', ports: ports || '' }
1338
+ })
1339
+ const services = lines('services')
1340
+ const java = lines('java').map(line => {
1341
+ const match = line.match(/^(\d+)\s+(\S+)\s+(.*)$/)
1342
+ return match ? { pid: match[1], uptime: match[2], cmd: match[3].slice(0, 160) } : { pid: '', uptime: '', cmd: line.slice(0, 160) }
1343
+ })
1344
+ const nginx = lines('nginx')
1345
+ const unitPaths = Object.fromEntries(lines('units').map(line => {
1346
+ const [unit, path] = line.split('|')
1347
+ return [unit, path]
1348
+ }).filter(([unit, path]) => unit && path))
1349
+ const configFor = (unit) => {
1350
+ if (unit.startsWith('nginx')) return '/etc/nginx/nginx.conf'
1351
+ if (unit.startsWith('mysqld') || unit.startsWith('mysql')) return '/etc/my.cnf'
1352
+ if (unit.startsWith('redis')) return '/etc/redis.conf'
1353
+ return unitPaths[unit] || null
1354
+ }
1355
+ const apps = [
1356
+ ...docker.map(row => ({ kind: 'docker', name: row.name, status: row.status, ports: row.ports, config: null })),
1357
+ ...services.filter(name => !/^(systemd-|dbus|cron|crond|sshd|rsyslog|polkit|NetworkManager|auditd|tuned|chronyd|irqbalance|atd|rngd|rpcbind|gssproxy|firewalld|BT-FirewallServices|aegis|aliyun|cloudmonitor|getty|serial-getty|user@|postfix)/.test(name))
1358
+ .map(name => ({ kind: 'service', name, status: 'running', ports: '', config: configFor(name) })),
1359
+ ...java.map(row => ({ kind: 'java', name: `java pid ${row.pid}`, status: row.uptime, ports: '', config: null })),
1360
+ ]
1361
+ const portRows = lines('ports').filter(line => /^LISTEN/.test(line)).map(line => {
1362
+ const portMatch = line.match(/(?:\d{1,3}\.){3}\d{1,3}:(\d+)|\*:(\d+)|:(\d+)\s/)
1363
+ const port = portMatch ? Number(portMatch[1] || portMatch[2] || portMatch[3]) : null
1364
+ const procMatch = line.match(/users:\(\("([^"]+)"/)
1365
+ return { port, process: procMatch ? procMatch[1] : '', raw: line }
1366
+ }).filter(row => row.port)
1367
+
1368
+ const inventory = {
1369
+ host: cfg.name,
1370
+ alias: cfg.alias || null,
1371
+ at: new Date().toISOString(),
1372
+ ok: result.ok,
1373
+ error: result.ok ? '' : cleanStderr(result.stderr),
1374
+ ports: lines('ports'),
1375
+ services,
1376
+ docker,
1377
+ nginx,
1378
+ java,
1379
+ crontab: lines('crontab'),
1380
+ mounts: lines('mounts'),
1381
+ portsParsed: portRows,
1382
+ configs: lines('configs').map(path => ({ path, label: path.split('/').pop() })),
1383
+ unitPaths: Object.fromEntries(lines('units').map(line => {
1384
+ const [unit, path] = line.split('|')
1385
+ return [unit, path]
1386
+ }).filter(([unit, path]) => unit && path)),
1387
+ apps,
1388
+ }
1389
+ try {
1390
+ const all = JSON.parse(await readFile(inventoryFile(), 'utf8'))
1391
+ all[cfg.name] = inventory
1392
+ await writeFile(inventoryFile(), JSON.stringify(all, null, 2) + '\n', 'utf8')
1393
+ } catch {
1394
+ await writeFile(inventoryFile(), JSON.stringify({ [cfg.name]: inventory }, null, 2) + '\n', 'utf8')
1395
+ }
1396
+ return inventory
1397
+ }
1398
+
1399
+ async function loadInventory(host) {
1400
+ try {
1401
+ const all = JSON.parse(await readFile(inventoryFile(), 'utf8'))
1402
+ return all[host] ?? null
1403
+ } catch {
1404
+ return null
1405
+ }
1406
+ }
1407
+
1408
+
1409
+ /** Safe disk cleanup: rotate-capped logs, old compressed logs, journal vacuum. */
1410
+ async function cleanupDisk(cfg) {
1411
+ const command = [
1412
+ 'before=$(df -P / | awk \'NR==2{gsub("%","",$5);print $5}\')',
1413
+ 'journalctl --vacuum-size=200M >/dev/null 2>&1 || true',
1414
+ 'find /var/log -maxdepth 1 -type f \\( -name "*.gz" -o -name "*.old" -o -name "*.1" \\) -mtime +7 -delete 2>/dev/null || true',
1415
+ 'for f in /var/log/messages-* /var/log/secure-* /var/log/maillog-* /var/log/cron-*; do [ -f "$f" ] && truncate -s 0 "$f"; done 2>/dev/null || true',
1416
+ 'after=$(df -P / | awk \'NR==2{gsub("%","",$5);print $5}\')',
1417
+ 'echo "DISK_BEFORE $before"; echo "DISK_AFTER $after"; df -h / | tail -1',
1418
+ ].join('; ')
1419
+ const result = await ssh(cfg, command, 60_000)
1420
+ const read = (key) => {
1421
+ const match = result.stdout.match(new RegExp(`^${key} (\\d+)$`, 'm'))
1422
+ return match ? Number(match[1]) : null
1423
+ }
1424
+ return {
1425
+ host: cfg.name,
1426
+ ok: result.ok,
1427
+ before: read('DISK_BEFORE'),
1428
+ after: read('DISK_AFTER'),
1429
+ detail: clip(result.stdout, 2_000),
1430
+ error: result.ok ? '' : cleanStderr(result.stderr),
1431
+ }
1432
+ }
1433
+
1434
+
1435
+ const FILE_PREFIXES = ['/etc/nginx/', '/etc/redis', '/etc/my.cnf', '/etc/systemd/system/', '/etc/supervisord.d/', '/etc/supervisor/conf.d/', '/etc/hosts', '/opt/']
1436
+ const FILE_DENY = [/shadow/, /passwd/, /sudoers/, /\.pem$/, /\.key$/, /id_rsa/]
1437
+
1438
+ function fileAllowed(path) {
1439
+ const p = String(path || '').trim()
1440
+ if (!p.startsWith('/')) return false
1441
+ if (FILE_DENY.some(rx => rx.test(p))) return false
1442
+ return FILE_PREFIXES.some(prefix => p.startsWith(prefix))
1443
+ }
1444
+
1445
+ async function readRemoteFile(cfg, path) {
1446
+ if (!fileAllowed(path)) throw new Error('path is outside the editable configuration area')
1447
+ const sizeResult = await ssh(cfg, `stat -c%s ${JSON.stringify(path)} 2>/dev/null || echo 0`, 10_000)
1448
+ const size = Number(String(sizeResult.stdout || '0').trim()) || 0
1449
+ if (size > 512 * 1024) throw new Error(`文件太大(${Math.round(size / 1024)} KB),面板只编辑 512 KB 以内的配置`)
1450
+ const result = await ssh(cfg, `test -f ${JSON.stringify(path)} && base64 -w0 ${JSON.stringify(path)} 2>/dev/null || base64 ${JSON.stringify(path)} 2>/dev/null`, 25_000)
1451
+ if (!result.ok) throw new Error(cleanStderr(result.stderr) || 'cannot read file')
1452
+ const content = Buffer.from(result.stdout.replace(/\s+/g, ''), 'base64').toString('utf8')
1453
+ return { host: cfg.name, path, content: content.slice(0, 200_000), truncated: content.length > 200_000 }
1454
+ }
1455
+
1456
+ async function writeRemoteFile(cfg, path, content) {
1457
+ if (!fileAllowed(path)) throw new Error('path is outside the editable configuration area')
1458
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
1459
+ const backup = `${path}.bak.${stamp}`
1460
+ const encoded = Buffer.from(String(content), 'utf8').toString('base64')
1461
+ const command = [
1462
+ `cp -a ${JSON.stringify(path)} ${JSON.stringify(backup)}`,
1463
+ `printf %s ${JSON.stringify(encoded)} | base64 -d > ${JSON.stringify(path)}`,
1464
+ `echo "BACKUP ${backup}"`,
1465
+ 'wc -c < ' + JSON.stringify(path),
1466
+ ].join(' && ')
1467
+ const result = await ssh(cfg, command, 30_000)
1468
+ return { host: cfg.name, path, ok: result.ok, backup, bytes: Number(result.stdout.trim().split('\n').pop()) || null, error: result.ok ? '' : cleanStderr(result.stderr) }
1469
+ }
1470
+
1471
+
1472
+ /**
1473
+ * Rule-based diagnosis for one host, in plain language. `question` only nudges
1474
+ * which checks are reported first; every check runs on real command output.
1475
+ */
1476
+ /** Ask the harness LLM (the user's default model) to explain the gathered facts. */
1477
+ async function aiDiagnose(facts, question) {
1478
+ try {
1479
+ const prompt = [
1480
+ '你是服务器运维助手,面对的是不懂技术的用户。',
1481
+ '下面是一台服务器的真实检查数据:',
1482
+ '-----',
1483
+ facts,
1484
+ '-----',
1485
+ `用户的问题:${question || '这台服务器现在有什么问题?'}`,
1486
+ '请用简体中文回答,要求:',
1487
+ '1) 第一句直接给结论(正常 / 需要留意 / 有风险),不要客套;',
1488
+ '2) 然后用 2-4 条短句说明依据(引用上面的数字);',
1489
+ '3) 最后给 1-3 条建议,每条说明点哪里或做什么;',
1490
+ '4) 不要用 Markdown 标题和表格,不要超过 200 字,不要编造数据里没有的信息。',
1491
+ ].join('\n')
1492
+ const { text } = await llmText(prompt, 1500)
1493
+ const trimmed = text.trim()
1494
+ if (trimmed.length < 20) return { error: `回答过短(${trimmed.length} 字),可能是模型输出被截断` }
1495
+ return { text: trimmed }
1496
+ } catch (error) {
1497
+ return { error: String(error?.message || error) }
1498
+ }
1499
+ }
1500
+
1501
+ async function diagnose(cfg, question = '') {
1502
+ const asked = String(question || '')
1503
+ const wantSite = /网站|打不开|访问|80|443|nginx|web/i.test(asked)
1504
+ const wantSlow = /慢|卡|cpu|负载|load/i.test(asked)
1505
+
1506
+ const status = await statusOf(cfg)
1507
+ if (!status.ok) {
1508
+ return {
1509
+ host: cfg.name,
1510
+ alias: cfg.alias || null,
1511
+ level: 'bad',
1512
+ headline: '连不上这台服务器',
1513
+ summary: 'SSH 连接失败,下面的检查都做不了。先把它连上,其他问题才有意义。',
1514
+ sections: [{ title: '连接', status: 'bad', detail: cleanStderr(status.stderr) || `exit ${status.code}`, advice: hintFor(cleanStderr(status.stderr), cfg) }],
1515
+ actions: [],
1516
+ at: new Date().toISOString(),
1517
+ }
1518
+ }
1519
+
1520
+ const parsed = parseStatus(status.stdout)
1521
+ const text = status.stdout
1522
+ const inv = await loadInventory(cfg.name)
1523
+ const apps = inv?.apps || []
1524
+ const ports = inv?.portsParsed || []
1525
+ const nginx = apps.find(a => String(a.name).startsWith('nginx'))
1526
+ const mysql = apps.find(a => String(a.name).startsWith('mysql'))
1527
+ const redis = apps.find(a => String(a.name).startsWith('redis'))
1528
+ const has80 = ports.some(p => p.port === 80)
1529
+ const has443 = ports.some(p => p.port === 443)
1530
+ const memMatch = text.match(/Mem:\s+(\S+)\s+(\S+)\s+(\S+)/)
1531
+ const loadMatch = text.match(/load average:\s*([\d.]+)/)
1532
+
1533
+ const sections = []
1534
+ const actions = []
1535
+
1536
+ sections.push({
1537
+ title: '磁盘',
1538
+ status: parsed.diskPercent === null ? 'unknown' : parsed.diskPercent >= 90 ? 'bad' : parsed.diskPercent >= 75 ? 'warn' : 'ok',
1539
+ detail: parsed.diskPercent === null ? '没有读到使用率' : `已用 ${parsed.diskPercent}%(/ 分区)`,
1540
+ advice: parsed.diskPercent === null ? '' : parsed.diskPercent >= 90 ? '现在几乎写不进去了:日志会丢、数据库可能起不来,建议立刻清理' : parsed.diskPercent >= 75 ? '还没到危险线,但增长下去一两周内会满' : '余量充足',
1541
+ })
1542
+ if (parsed.diskPercent >= 75) actions.push({ id: 'cleanup', label: '清理日志' })
1543
+
1544
+ sections.push({
1545
+ title: '内存',
1546
+ status: !memMatch ? 'unknown' : (parseFloat(memMatch[2]) / Math.max(parseFloat(memMatch[1]), 0.001)) >= 0.9 ? 'bad' : (parseFloat(memMatch[2]) / Math.max(parseFloat(memMatch[1]), 0.001)) >= 0.8 ? 'warn' : 'ok',
1547
+ detail: memMatch ? `已用 ${memMatch[2]} / 共 ${memMatch[1]}` : '没有读到内存信息',
1548
+ advice: memMatch ? (parseFloat(memMatch[2]) / Math.max(parseFloat(memMatch[1]), 0.001)) >= 0.8 ? '内存偏紧,容易出现"服务莫名重启",可以去应用页看谁在占' : '内存还有余量' : '',
1549
+ })
1550
+
1551
+ sections.push({
1552
+ title: '服务',
1553
+ status: parsed.failedUnits.length ? 'bad' : 'ok',
1554
+ detail: parsed.failedUnits.length ? `${parsed.failedUnits.length} 个服务失败:${parsed.failedUnits.slice(0, 3).join('、')}` : '没有失败的 systemd 服务',
1555
+ advice: parsed.failedUnits.length ? '失败的服务不会自己恢复,建议逐个看日志再重启' : '',
1556
+ })
1557
+ if (parsed.failedUnits.length) actions.push({ id: 'goto-service', label: '去应用页处理' })
1558
+
1559
+ const siteStatus = has80 || has443 ? 'ok' : 'warn'
1560
+ sections.push({
1561
+ title: '网站',
1562
+ status: siteStatus,
1563
+ detail: [
1564
+ has80 ? '80 端口在监听' : '80 端口没监听',
1565
+ has443 ? '443(HTTPS)在监听' : '443 没监听',
1566
+ nginx ? 'nginx 在运行' : 'nginx 没找到',
1567
+ ].join(','),
1568
+ advice: siteStatus === 'ok' ? '网站入口正常' : '网站入口没起来,先确认 nginx 是否启动',
1569
+ })
1570
+ if (siteStatus !== 'ok' && nginx) actions.push({ id: 'restart:nginx.service', label: '重启 nginx' })
1571
+
1572
+ sections.push({
1573
+ title: '数据库 / 缓存',
1574
+ status: (mysql ? 'ok' : 'warn') ,
1575
+ detail: [mysql ? 'MySQL 在运行' : '没找到 MySQL', redis ? 'Redis 在运行' : '没找到 Redis'].join(','),
1576
+ advice: mysql ? '' : '如果业务用到数据库,这里没找到就要确认它是装在别处还是停了',
1577
+ })
1578
+
1579
+ if (wantSlow && loadMatch) {
1580
+ sections.push({
1581
+ title: '负载',
1582
+ status: parseFloat(loadMatch[1]) > 4 ? 'warn' : 'ok',
1583
+ detail: `最近一分钟负载 ${loadMatch[1]}`,
1584
+ advice: parseFloat(loadMatch[1]) > 4 ? '负载偏高,可能是某个进程在跑重活,去应用页看 CPU' : '负载不高',
1585
+ })
1586
+ }
1587
+
1588
+ const worst = sections.reduce((acc, item) => {
1589
+ const rank = { bad: 3, warn: 2, unknown: 1, ok: 0 }
1590
+ return rank[item.status] > rank[acc] ? item.status : acc
1591
+ }, 'ok')
1592
+
1593
+ const level = worst
1594
+ const headline = level === 'bad' ? '有需要马上处理的问题' : level === 'warn' ? '基本正常,但有一处要留意' : '一切正常'
1595
+ const problems = sections.filter(item => item.status === 'bad' || item.status === 'warn')
1596
+ const summary = level === 'ok'
1597
+ ? '磁盘、内存、服务、网站、数据库都正常,没有需要处理的。'
1598
+ : problems.map(item => `${item.title}:${item.detail}`).join(';') + '。'
1599
+
1600
+ const facts = [
1601
+ `主机:${cfg.alias ? cfg.alias + '(' + cfg.name + ')' : cfg.name} ${cfg.user || ''}@${cfg.host}`,
1602
+ `磁盘:${parsed.diskPercent === null ? '未知' : parsed.diskPercent + '%'}`,
1603
+ `内存:${memMatch ? memMatch[2] + '/' + memMatch[1] : '未知'}`,
1604
+ `负载:${loadMatch ? loadMatch[1] : '未知'}`,
1605
+ `失败服务:${parsed.failedUnits.length ? parsed.failedUnits.join('、') : '无'}`,
1606
+ `网站端口:${has80 ? '80 ' : ''}${has443 ? '443 ' : ''}${has80 || has443 ? '' : '未监听'}`,
1607
+ `应用:${apps.slice(0, 8).map(a => a.name).join('、') || '未采集'}`,
1608
+ ].join('\n')
1609
+ const aiResult = await aiDiagnose(facts, question)
1610
+ return {
1611
+ host: cfg.name,
1612
+ alias: cfg.alias || null,
1613
+ level,
1614
+ headline,
1615
+ summary,
1616
+ sections,
1617
+ actions,
1618
+ ai: aiResult?.text ?? null,
1619
+ aiError: aiResult?.error ?? null,
1620
+ at: new Date().toISOString(),
1621
+ }
1622
+ }
1623
+
1624
+
1625
+ /** Directory sizes one level below `path`, largest last. */
1626
+ async function diskUsage(cfg, path = '/') {
1627
+ const safe = String(path || '/').replace(/[;&|`$><\n]/g, '')
1628
+ const result = await ssh(cfg, `du -xh --max-depth=1 ${JSON.stringify(safe)} 2>/dev/null | sort -h | tail -25`, 45_000)
1629
+ const rows = String(result.stdout || '')
1630
+ .split('\n')
1631
+ .map(line => line.trim())
1632
+ .filter(Boolean)
1633
+ .map(line => {
1634
+ const [size, ...rest] = line.split('\t')
1635
+ return { size, path: rest.join('\t') }
1636
+ })
1637
+ .filter(row => row.path)
1638
+ return { host: cfg.name, path: safe, ok: result.ok, rows: rows.reverse(), error: result.ok ? '' : cleanStderr(result.stderr) }
1639
+ }
1640
+
1641
+ /** Top processes by CPU. */
1642
+ async function processList(cfg, sort = 'cpu', limit = 20) {
1643
+ const key = sort === 'mem' ? '-%mem' : '-%cpu'
1644
+ const command = `ps -eo pid,user,%cpu,%mem,etime,args --sort=${key} 2>/dev/null | head -${Math.min(Math.max(Number(limit) || 20, 5), 50)}`
1645
+ const result = await ssh(cfg, command, 20_000)
1646
+ const rows = String(result.stdout || '').split('\n').slice(1).map(line => {
1647
+ const match = line.trim().match(/^(\d+)\s+(\S+)\s+([\d.]+)\s+([\d.]+)\s+(\S+)\s+(.*)$/)
1648
+ if (!match) return null
1649
+ return { pid: Number(match[1]), user: match[2], cpu: Number(match[3]), mem: Number(match[4]), uptime: match[5], cmd: match[6].slice(0, 120) }
1650
+ }).filter(Boolean)
1651
+ return { host: cfg.name, ok: result.ok, rows, error: result.ok ? '' : cleanStderr(result.stderr) }
1652
+ }
1653
+
1654
+ /** Send one signal to a pid (TERM by default). */
1655
+ async function killProcess(cfg, pid, signal = 'TERM') {
1656
+ const safeSignal = ['TERM', 'KILL', 'HUP', 'STOP', 'CONT'].includes(String(signal).toUpperCase()) ? String(signal).toUpperCase() : 'TERM'
1657
+ if (!/^\d+$/.test(String(pid))) throw new Error('pid must be a number')
1658
+ const result = await ssh(cfg, `kill -${safeSignal} ${Number(pid)} 2>&1; echo EXIT:$?`, 15_000)
1659
+ return { host: cfg.name, pid: Number(pid), signal: safeSignal, ...summary(result, cfg) }
1660
+ }
1661
+
1662
+ /** Last N lines from a journal unit or a log file. */
1663
+ async function tailLog(cfg, source, lines = 200) {
1664
+ const n = Math.min(Math.max(Number(lines) || 200, 20), 1000)
1665
+ const raw = String(source || '')
1666
+ let command
1667
+ if (raw.startsWith('file:')) {
1668
+ const path = raw.slice(5)
1669
+ if (!/^\/[A-Za-z0-9._\/-]+$/.test(path)) throw new Error('bad log path')
1670
+ command = `tail -n ${n} ${JSON.stringify(path)} 2>&1`
1671
+ } else {
1672
+ const unit = raw.replace(/[^A-Za-z0-9@._:-]/g, '')
1673
+ command = `journalctl -u ${unit} -n ${n} --no-pager 2>&1`
1674
+ }
1675
+ const result = await ssh(cfg, command, 25_000)
1676
+ return { host: cfg.name, source: raw, ok: result.ok, lines: String(result.stdout || '').slice(0, 60_000), error: result.ok ? '' : cleanStderr(result.stderr) }
1677
+ }
1678
+
1679
+ /** TLS certificate expiry for a domain (checked from the host itself). */
1680
+ async function sslCheck(cfg, domain) {
1681
+ const host = String(domain || '').replace(/[^A-Za-z0-9.-]/g, '')
1682
+ if (!host) throw new Error('domain is required')
1683
+ const command = `echo | timeout 12 openssl s_client -servername ${host} -connect ${host}:443 2>/dev/null | openssl x509 -noout -subject -issuer -dates 2>/dev/null`
1684
+ const result = await ssh(cfg, command, 25_000)
1685
+ const text = String(result.stdout || '')
1686
+ const notAfter = (text.match(/notAfter=(.+)/) || [])[1] || ''
1687
+ const expire = notAfter ? new Date(notAfter) : null
1688
+ const days = expire && !Number.isNaN(expire.getTime()) ? Math.round((expire.getTime() - Date.now()) / 86_400_000) : null
1689
+ return {
1690
+ host: cfg.name,
1691
+ domain: host,
1692
+ ok: result.ok && Boolean(text.trim()),
1693
+ subject: (text.match(/subject=(.+)/) || [])[1] || '',
1694
+ issuer: (text.match(/issuer=(.+)/) || [])[1] || '',
1695
+ notAfter,
1696
+ daysLeft: days,
1697
+ error: result.ok ? '' : cleanStderr(result.stderr),
1698
+ }
1699
+ }
1700
+
1701
+
1702
+ const FS_DENY = [/^\/$/, /^\/etc$/, /^\/boot/, /^\/dev/, /^\/proc/, /^\/sys/, /^\/bin/, /^\/sbin/, /^\/lib/, /^\/usr$/, /shadow/, /passwd$/, /sudoers/]
1703
+
1704
+ function fsSafePath(path) {
1705
+ const p = String(path || '').trim()
1706
+ if (!p.startsWith('/')) throw new Error('path must be absolute')
1707
+ if (FS_DENY.some(rx => rx.test(p))) throw new Error(`refusing to touch ${p}`)
1708
+ return p
1709
+ }
1710
+
1711
+ /** Directory listing with size and mtime. */
1712
+ async function listDir(cfg, path) {
1713
+ const dir = String(path || '/').trim() || '/'
1714
+ const result = await ssh(cfg, `ls -la --time-style=+%Y-%m-%dT%H:%M ${JSON.stringify(dir)} 2>/dev/null`, 20_000)
1715
+ if (!result.ok) {
1716
+ return { host: cfg.name, path: dir, ok: false, entries: [], error: cleanStderr(result.stderr) || 'cannot list directory' }
1717
+ }
1718
+ const entries = String(result.stdout).split('\n').slice(1).map(line => {
1719
+ const m = line.match(/^([dl-])([rwxsStT-]{9})\.?\s+(\d+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(.*)$/)
1720
+ if (!m) return null
1721
+ const name = m[8]
1722
+ if (!name || name === '.' || name === '..') return null
1723
+ return {
1724
+ name,
1725
+ dir: m[1] === 'd',
1726
+ link: m[1] === 'l',
1727
+ size: Number(m[6]),
1728
+ owner: m[4],
1729
+ group: m[5],
1730
+ mtime: m[7],
1731
+ path: dir === '/' ? `/${name}` : `${dir}/${name}`,
1732
+ }
1733
+ }).filter(Boolean).sort((a, b) => (b.dir - a.dir) || a.name.localeCompare(b.name))
1734
+ return { host: cfg.name, path: dir, ok: true, entries, error: '' }
1735
+ }
1736
+
1737
+ /** Read a file as base64 (bounded). */
1738
+ async function downloadFile(cfg, path, limitMb = 8) {
1739
+ const target = fsSafePath(path)
1740
+ const sizeResult = await ssh(cfg, `stat -c%s ${JSON.stringify(target)} 2>/dev/null || echo 0`, 10_000)
1741
+ const size = Number(String(sizeResult.stdout || '0').trim()) || 0
1742
+ if (size > limitMb * 1024 * 1024) throw new Error(`file is ${Math.round(size / 1048576)} MB; the panel downloads at most ${limitMb} MB`)
1743
+ const result = await ssh(cfg, `base64 -w0 ${JSON.stringify(target)} 2>/dev/null || base64 ${JSON.stringify(target)}`, 60_000)
1744
+ if (!result.ok) throw new Error(cleanStderr(result.stderr) || 'cannot read file')
1745
+ return { host: cfg.name, path: target, size, base64: String(result.stdout).replace(/\s+/g, '') }
1746
+ }
1747
+
1748
+ /** Write a base64 payload, backing up an existing file. */
1749
+ async function uploadFile(cfg, path, base64, limitMb = 8) {
1750
+ const target = fsSafePath(path)
1751
+ const size = Math.floor((String(base64).length * 3) / 4)
1752
+ if (size > limitMb * 1024 * 1024) throw new Error(`payload is ${Math.round(size / 1048576)} MB; the panel uploads at most ${limitMb} MB`)
1753
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
1754
+ const command = [
1755
+ `if [ -f ${JSON.stringify(target)} ]; then cp -a ${JSON.stringify(target)} ${JSON.stringify(target + '.bak.' + stamp)}; fi`,
1756
+ `mkdir -p $(dirname ${JSON.stringify(target)})`,
1757
+ `printf %s ${JSON.stringify(String(base64))} | base64 -d > ${JSON.stringify(target)}`,
1758
+ `echo "SIZE $(stat -c%s ${JSON.stringify(target)})"`,
1759
+ ].join(' && ')
1760
+ const result = await ssh(cfg, command, 90_000)
1761
+ const sizeLine = String(result.stdout || '').match(/SIZE (\d+)/)
1762
+ return { host: cfg.name, path: target, ok: result.ok, bytes: sizeLine ? Number(sizeLine[1]) : null, error: result.ok ? '' : cleanStderr(result.stderr) }
1763
+ }
1764
+
1765
+ /** mkdir / delete inside a safe path. Delete needs confirm. */
1766
+ async function fsAction(cfg, action, path, confirm) {
1767
+ const target = fsSafePath(path)
1768
+ if (action === 'mkdir') {
1769
+ const result = await ssh(cfg, `mkdir -p ${JSON.stringify(target)} && echo OK`, 20_000)
1770
+ return { host: cfg.name, action, path: target, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
1771
+ }
1772
+ if (action === 'delete') {
1773
+ if (confirm !== true) throw new Error('deleting needs confirm=true')
1774
+ const result = await ssh(cfg, `rm -rf ${JSON.stringify(target)} && echo OK`, 30_000)
1775
+ return { host: cfg.name, action, path: target, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
1776
+ }
1777
+ throw new Error(`unknown action ${action}`)
1778
+ }
1779
+
1780
+
1781
+ /** Per-host connection facts, merged into state.json by patchState. */
1782
+ async function loadConnections() {
1783
+ const state = await loadState()
1784
+ return state.connections ?? {}
1785
+ }
1786
+
1787
+ async function recordConnection(host, ok, ms, error) {
1788
+ const state = await loadState()
1789
+ const previous = state.connections?.[host] ?? {}
1790
+ const connections = {
1791
+ ...(state.connections ?? {}),
1792
+ [host]: {
1793
+ ok,
1794
+ at: new Date().toISOString(),
1795
+ ms,
1796
+ error: ok ? '' : String(error || '').slice(0, 300),
1797
+ failures: ok ? 0 : (previous.failures ?? 0) + 1,
1798
+ },
1799
+ }
1800
+ await patchState({ connections })
1801
+ return connections[host]
1802
+ }
1803
+
1804
+ /** Wrap ssh() so every call updates the per-host connection record. */
1805
+ async function sshTracked(cfg, command, timeoutMs) {
1806
+ const started = Date.now()
1807
+ try {
1808
+ const result = await ssh(cfg, command, timeoutMs)
1809
+ await recordConnection(cfg.name, result.ok, Date.now() - started, result.ok ? '' : cleanStderr(result.stderr))
1810
+ return result
1811
+ } catch (error) {
1812
+ await recordConnection(cfg.name, false, Date.now() - started, String(error?.message || error))
1813
+ throw error
1814
+ }
1815
+ }
1816
+
1817
+ /** Explicit connection test: one round trip and its latency. */
1818
+ async function testConnection(cfg) {
1819
+ const started = Date.now()
1820
+ const result = await ssh(cfg, 'echo ok', 12_000)
1821
+ const ms = Date.now() - started
1822
+ const record = await recordConnection(cfg.name, result.ok, ms, result.ok ? '' : cleanStderr(result.stderr))
1823
+ return { host: cfg.name, alias: cfg.alias || null, ok: result.ok, ms, error: record.error, auth: await authKind(cfg) }
1824
+ }
1825
+
1826
+ async function authKind(cfg) {
1827
+ const secrets = await loadSecrets()
1828
+ return secrets[cfg.name]?.password ? 'password' : 'key'
1829
+ }
1830
+
1831
+ /** Append this machine's public key to the host's authorized_keys. */
1832
+ async function installKey(cfg) {
1833
+ const pubPath = join(homedir(), '.ssh', 'id_ed25519.pub')
1834
+ let pub
1835
+ try {
1836
+ pub = (await readFile(pubPath, 'utf8')).trim()
1837
+ } catch {
1838
+ throw new Error('no ~/.ssh/id_ed25519.pub on this machine; create one with ssh-keygen first')
1839
+ }
1840
+ if (!pub.startsWith('ssh-')) throw new Error('public key file does not look like an SSH key')
1841
+ const command = [
1842
+ 'mkdir -p ~/.ssh && chmod 700 ~/.ssh',
1843
+ `grep -qxF ${JSON.stringify(pub)} ~/.ssh/authorized_keys 2>/dev/null || echo ${JSON.stringify(pub)} >> ~/.ssh/authorized_keys`,
1844
+ 'chmod 600 ~/.ssh/authorized_keys',
1845
+ 'grep -c . ~/.ssh/authorized_keys',
1846
+ ].join(' && ')
1847
+ const result = await ssh(cfg, command, 20_000)
1848
+ return { host: cfg.name, ok: result.ok, keys: Number(String(result.stdout || '').trim().split('\n').pop()) || null, error: result.ok ? '' : cleanStderr(result.stderr) }
1849
+ }
1850
+
1851
+
1852
+ /* ---------- interactive SSH terminal (PTY) ---------- */
1853
+
1854
+ const termSessions = new Map()
1855
+ let termSeq = 0
1856
+
1857
+ function termSsh2() {
1858
+ const ssh2 = loadSsh2()
1859
+ if (!ssh2) throw new Error('ssh2 is not available in this profile; install it to use the terminal')
1860
+ return ssh2
1861
+ }
1862
+
1863
+ async function openTerminal(cfg, cols = 120, rows = 30) {
1864
+ const secrets = await loadSecrets()
1865
+ const secret = secrets[cfg.name]
1866
+ const id = `t${++termSeq}-${Date.now()}`
1867
+ const session = { id, host: cfg.name, buffer: '', seq: 0, closed: false, conn: null, stream: null, child: null, args: [] }
1868
+ const size = { cols: Math.max(40, Number(cols) || 120), rows: Math.max(10, Number(rows) || 30) }
1869
+
1870
+ const args = [
1871
+ '-tt',
1872
+ '-o', 'BatchMode=yes',
1873
+ '-o', 'ConnectTimeout=8',
1874
+ '-o', 'StrictHostKeyChecking=accept-new',
1875
+ '-o', 'ServerAliveInterval=15',
1876
+ '-o', 'ServerAliveCountMax=3',
1877
+ ]
1878
+ if (cfg.port) args.push('-p', String(cfg.port))
1879
+ if (cfg.key) args.push('-i', cfg.key)
1880
+ args.push(`${cfg.user ? cfg.user + '@' : ''}${cfg.host}`)
1881
+
1882
+ if (!secret?.password) {
1883
+ // Key / agent authentication: a real PTY comes from ssh -tt through pipes.
1884
+ const child = spawn('ssh', args, { env: { ...process.env, TERM: 'xterm-256color' } })
1885
+ session.child = child
1886
+ child.stdout.on('data', (chunk) => {
1887
+ session.buffer += chunk.toString('utf8')
1888
+ session.seq += 1
1889
+ if (session.buffer.length > 200_000) session.buffer = session.buffer.slice(-120_000)
1890
+ })
1891
+ child.stderr.on('data', (chunk) => { session.buffer += chunk.toString('utf8') })
1892
+ child.on('close', () => { session.closed = true })
1893
+ child.on('error', () => { session.closed = true })
1894
+ termSessions.set(id, session)
1895
+ return { id, host: cfg.name, seq: session.seq, transport: 'key' }
1896
+ }
1897
+
1898
+ const ssh2 = termSsh2()
1899
+ await new Promise((resolve, reject) => {
1900
+ const conn = new ssh2.Client()
1901
+ session.conn = conn
1902
+ const timer = setTimeout(() => reject(new Error('terminal connect timeout')), 15_000)
1903
+ conn.on('ready', () => {
1904
+ clearTimeout(timer)
1905
+ conn.shell({ term: 'xterm-256color', ...size }, (error, stream) => {
1906
+ if (error) return reject(error)
1907
+ session.stream = stream
1908
+ stream.on('data', (chunk) => {
1909
+ session.buffer += chunk.toString('utf8')
1910
+ session.seq += 1
1911
+ if (session.buffer.length > 200_000) session.buffer = session.buffer.slice(-120_000)
1912
+ })
1913
+ stream.stderr.on('data', (chunk) => { session.buffer += chunk.toString('utf8') })
1914
+ stream.on('close', () => { session.closed = true; try { conn.end() } catch {} })
1915
+ resolve()
1916
+ })
1917
+ })
1918
+ conn.on('error', (error) => { clearTimeout(timer); reject(error) })
1919
+ conn.connect({
1920
+ host: cfg.host,
1921
+ port: Number(cfg.port || 22),
1922
+ username: cfg.user || process.env.USER,
1923
+ password: Buffer.from(secret.password, 'base64').toString('utf8'),
1924
+ readyTimeout: 15_000,
1925
+ keepaliveInterval: 15_000,
1926
+ })
1927
+ })
1928
+
1929
+ termSessions.set(id, session)
1930
+ return { id, host: cfg.name, seq: session.seq, transport: 'password' }
1931
+ }
1932
+
1933
+ function terminalPoll(id, since = 0) {
1934
+ const session = termSessions.get(id)
1935
+ if (!session) return { error: 'session not found', closed: true }
1936
+ const offset = Math.max(0, Math.min(Number(since) || 0, session.buffer.length))
1937
+ return {
1938
+ data: session.buffer.slice(offset),
1939
+ offset: session.buffer.length,
1940
+ seq: session.seq,
1941
+ closed: session.closed,
1942
+ }
1943
+ }
1944
+
1945
+ function terminalInput(id, data) {
1946
+ const session = termSessions.get(id)
1947
+ if (!session) throw new Error('terminal session is not open')
1948
+ if (session.child) session.child.stdin.write(String(data))
1949
+ else if (session.stream) session.stream.write(String(data))
1950
+ else throw new Error('terminal session is not open')
1951
+ return { ok: true }
1952
+ }
1953
+
1954
+ function terminalResize(id, cols, rows) {
1955
+ const session = termSessions.get(id)
1956
+ if (!session) throw new Error('terminal session is not open')
1957
+ if (session.stream) session.stream.setWindow(Math.max(20, Number(rows) || 30), Math.max(40, Number(cols) || 120))
1958
+ return { ok: true }
1959
+ }
1960
+
1961
+ function terminalClose(id) {
1962
+ const session = termSessions.get(id)
1963
+ if (session) {
1964
+ try { session.stream?.end() } catch {}
1965
+ try { session.conn?.end() } catch {}
1966
+ try { session.child?.kill() } catch {}
1967
+ termSessions.delete(id)
1968
+ }
1969
+ return { ok: true }
1970
+ }
1971
+
1972
+ export const __terminal = { openTerminal, terminalPoll, terminalInput, terminalResize, terminalClose }
1973
+
1974
+
1975
+ /** Ask the harness model to turn a plain-language intent into one shell command. */
1976
+ async function aiCommand(cfg, intent) {
1977
+ const ask = String(intent || '').trim()
1978
+ if (!ask) throw new Error('intent is required')
1979
+
1980
+ const prompt = [
1981
+ 'You are a Linux operations assistant embedded in a terminal panel.',
1982
+ `Host: ${cfg.alias || cfg.name} (${cfg.user || 'root'}@${cfg.host}, port ${cfg.port || 22})`,
1983
+ `User said: ${ask}`,
1984
+ 'Reply with ONE JSON object and nothing else, using this shape:',
1985
+ '{"command":"<one shell command>","explanation":"<one short Chinese sentence>","dangerous":true|false}',
1986
+ 'Rules:',
1987
+ '- Always provide a command, even for a question: the command must obtain the answer (e.g. systemctl is-active mysqld).',
1988
+ '- The command must be a single line, no markdown, no leading $.',
1989
+ '- explanation: what the command does or what to look for, in Chinese, at most 40 characters.',
1990
+ '- dangerous: true when the command changes state (restart/stop/delete/write/install).',
1991
+ '- Never invent data; if the answer needs the server, the command gets it.',
1992
+ ].join('\n')
1993
+
1994
+ const { text, model: usedModel } = await llmText(prompt, 800)
1995
+
1996
+ const cleaned = text.replace(/```[a-z]*\n?/gi, '').trim()
1997
+ let parsed = null
1998
+ const jsonStart = cleaned.indexOf('{')
1999
+ const jsonEnd = cleaned.lastIndexOf('}')
2000
+ if (jsonStart >= 0 && jsonEnd > jsonStart) {
2001
+ try { parsed = JSON.parse(cleaned.slice(jsonStart, jsonEnd + 1)) } catch { parsed = null }
2002
+ }
2003
+
2004
+ const fallbackLine = cleaned.split('\n').map(line => line.trim()).filter(line => line && !line.startsWith('{')).sort((a, b) => b.length - a.length)[0] || ''
2005
+ const command = String(parsed?.command ?? fallbackLine ?? '').trim().replace(/^\$\s*/, '')
2006
+ const explanation = String(parsed?.explanation ?? '').trim()
2007
+ if (!command) throw new Error(`模型没有给出命令(finish=${finish || '无'} chunks=${chunks} 文本长度=${cleaned.length} 失败=${failure || '无'})`)
2008
+
2009
+ const dangerous = parsed?.dangerous === true || looksDangerous(command)
2010
+ || /\b(systemctl|service)\s+(restart|stop|start|reload|disable|enable)|\bkill(all)?\b|\breboot\b|\bshutdown\b|rm\s+-rf|DROP\s+DATABASE|>\s*\/etc\/|chmod\s+-R|chown\s+-R/i.test(command)
2011
+ return { host: cfg.name, intent: ask, command, explanation, dangerous, model: usedModel }
2012
+ }
2013
+
2014
+
2015
+
2016
+ /** Ask the harness model to turn a plain-language intent into one shell command. */
2017
+
2018
+ /** Resolve which provider/model the ops AI uses (config override, else DSH default). */
2019
+ async function aiSelection() {
2020
+ const config = await loadConfig()
2021
+ if (config.aiEnabled === false) throw new Error('AI 已在「设置 → AI 模型」里关闭')
2022
+ const ctx = hostCtx
2023
+ if (!ctx) throw new Error('AI is not available in this context')
2024
+ const llm = typeof ctx.get === 'function' ? (ctx.get('llm') ?? ctx.llm) : ctx.llm
2025
+ if (!llm || typeof llm.stream !== 'function') throw new Error('the harness has no LLM service available')
2026
+ if (config.aiProvider && config.aiModel) {
2027
+ return { llm, provider: config.aiProvider, model: config.aiModel, source: 'config' }
2028
+ }
2029
+ const defaults = typeof ctx.get === 'function' ? (ctx.get('agentDefaultModel') ?? ctx.agentDefaultModel) : ctx.agentDefaultModel
2030
+ const selection = defaults?.currentSelection?.()
2031
+ if (!selection?.provider || !selection?.model) throw new Error('no default model selected')
2032
+ return { llm, provider: selection.provider, model: selection.model, source: 'default' }
2033
+ }
2034
+
2035
+ /** One plain text completion through the selected model. */
2036
+ async function llmText(prompt, maxTokens = 800) {
2037
+ const { llm, provider, model } = await aiSelection()
2038
+ let text = ''
2039
+ for await (const chunk of llm.stream({
2040
+ provider,
2041
+ model,
2042
+ maxTokens,
2043
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
2044
+ })) {
2045
+ if (chunk?.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text
2046
+ }
2047
+ return { text: text.trim(), model: `${provider}/${model}` }
2048
+ }
2049
+
2050
+ function parseJsonReply(text) {
2051
+ const cleaned = String(text || '').replace(/```[a-z]*\n?/gi, '').trim()
2052
+ const start = cleaned.indexOf('{')
2053
+ const end = cleaned.lastIndexOf('}')
2054
+ if (start < 0 || end <= start) return null
2055
+ try { return JSON.parse(cleaned.slice(start, end + 1)) } catch { return null }
2056
+ }
2057
+
2058
+ /**
2059
+ * Agentic ops question: the model may run read-only commands itself, then
2060
+ * answer in plain language. State-changing commands are returned for the user
2061
+ * to confirm instead of being executed.
2062
+ */
2063
+ async function askAboutHost(cfg, question, maxRounds = 4) {
2064
+ const ask = String(question || '').trim()
2065
+ if (!ask) throw new Error('question is required')
2066
+ const transcript = []
2067
+ let model = ''
2068
+
2069
+ for (let round = 0; round < maxRounds; round += 1) {
2070
+ const history = transcript.length === 0
2071
+ ? '(no commands run yet)'
2072
+ : transcript.map((row, index) => `#${index + 1} $ ${row.command}\nexit=${row.code}\n${row.output}`).join('\n\n')
2073
+ const prompt = [
2074
+ 'You are a Linux ops assistant talking to a non-technical user.',
2075
+ `Host: ${cfg.alias || cfg.name} (${cfg.user || 'root'}@${cfg.host}:${cfg.port || 22})`,
2076
+ `User question: ${ask}`,
2077
+ 'You may run read-only commands to find the answer.',
2078
+ 'Reply with ONE JSON object, nothing else:',
2079
+ '{"action":"run","command":"<one read-only shell command>","why":"<short reason>"}',
2080
+ 'or',
2081
+ '{"action":"answer","text":"<answer in Chinese, at most 80 characters, no markdown>"}',
2082
+ 'Rules:',
2083
+ '- Prefer read-only commands (df, free, systemctl status/is-active, ps, ss, tail, grep, docker ps, du).',
2084
+ '- Never run commands that change state (restart/stop/delete/write/install); if the fix needs one, answer with what to do instead.',
2085
+ '- Keep the command single-line, no sudo, no pipes into files.',
2086
+ '- After at most 3 commands you must answer.',
2087
+ `Commands run so far:\n${history}`,
2088
+ ].join('\n')
2089
+
2090
+ const { text, model: usedModel } = await llmText(prompt, 600)
2091
+ model = usedModel || model
2092
+ if (!text.trim()) {
2093
+ const fallback = await llmText(`用中文简短回答这个问题(不超过 80 字,不要 markdown):${ask}\n已知信息:\n${history}`, 300)
2094
+ return { host: cfg.name, question: ask, answer: fallback.text || '(这次没有查出来,换个问法试试)', transcript, rounds: round + 1, model }
2095
+ }
2096
+ const reply = parseJsonReply(text)
2097
+ if (!reply) return { host: cfg.name, question: ask, answer: text || '(模型没有返回内容)', transcript, rounds: round + 1, model }
2098
+
2099
+ if (reply.action === 'answer') {
2100
+ return { host: cfg.name, question: ask, answer: String(reply.text || '').slice(0, 400), transcript, rounds: round + 1, model }
2101
+ }
2102
+
2103
+ if (reply.action === 'run') {
2104
+ const command = String(reply.command || '').trim()
2105
+ if (!command) continue
2106
+ const dangerous = looksDangerous(command)
2107
+ || /\b(systemctl|service)\s+(restart|stop|start|reload|disable|enable)|\bkill(all)?\b|\breboot\b|\bshutdown\b|rm\s+-rf|>\s*\/etc\//i.test(command)
2108
+ if (dangerous) {
2109
+ return {
2110
+ host: cfg.name,
2111
+ question: ask,
2112
+ answer: '这一步需要改动服务器,我没有自动执行。确认后可以点下面的按钮,或去终端手动执行。',
2113
+ needsConfirm: command,
2114
+ transcript,
2115
+ rounds: round + 1,
2116
+ model,
2117
+ }
2118
+ }
2119
+ const result = await ssh(cfg, command, 25_000)
2120
+ transcript.push({
2121
+ command,
2122
+ code: result.code,
2123
+ ok: result.ok,
2124
+ output: clip(`${result.stdout || ''}${result.stderr ? '\n' + cleanStderr(result.stderr) : ''}`.trim(), 1_500),
2125
+ })
2126
+ continue
2127
+ }
2128
+
2129
+ return { host: cfg.name, question: ask, answer: '(模型返回了无法识别的动作)', transcript, rounds: round + 1, model }
2130
+ }
2131
+
2132
+ return { host: cfg.name, question: ask, answer: '(这次没能得出结论,可以换个问法)', transcript, rounds: maxRounds, model }
2133
+ }
2134
+
2135
+
2136
+ /** Providers and their models, as the harness LLM service reports them. */
2137
+ async function collectModels(llm) {
2138
+ if (!llm || typeof llm.listProviders !== 'function') return []
2139
+ const providers = []
2140
+ for (const provider of llm.listProviders()) {
2141
+ let models = []
2142
+ try {
2143
+ const listed = await llm.listModels(provider.id)
2144
+ models = (listed || []).map(model => ({ id: model.id, name: model.name ?? model.id }))
2145
+ } catch { models = [] }
2146
+ providers.push({ id: provider.id, name: provider.name ?? provider.id, models })
2147
+ }
2148
+ return providers
2149
+ }
2150
+
2151
+
2152
+ /* ---------- service monitors (heartbeat / port / process / unit) ---------- */
2153
+
2154
+ function monitorsFile() { return join(kitDir(), 'monitors.json') }
2155
+
2156
+ async function loadMonitors() {
2157
+ try {
2158
+ const data = JSON.parse(await readFile(monitorsFile(), 'utf8'))
2159
+ return data && typeof data === 'object' ? data : {}
2160
+ } catch {
2161
+ return {}
2162
+ }
2163
+ }
2164
+
2165
+ async function saveMonitors(all) {
2166
+ await mkdir(kitDir(), { recursive: true })
2167
+ await writeFile(monitorsFile(), JSON.stringify(all, null, 2) + '\n', 'utf8')
2168
+ }
2169
+
2170
+ /** Run one check on a host; returns ok, latency and a short detail. */
2171
+ async function runMonitor(cfg, monitor) {
2172
+ const started = Date.now()
2173
+ const type = String(monitor.type || '')
2174
+ const target = String(monitor.target || '').trim()
2175
+ let command
2176
+ if (type === 'http') {
2177
+ command = `curl -s -o /dev/null -w '%{http_code} %{time_total}' --max-time 8 ${JSON.stringify(target)} 2>/dev/null || echo "000 0"`
2178
+ } else if (type === 'port') {
2179
+ const [host, port] = target.split(':')
2180
+ if (!host || !port) throw new Error('port monitor needs host:port')
2181
+ command = `timeout 4 bash -c '</dev/tcp/${host.replace(/[^A-Za-z0-9.-]/g, '')}/${Number(port)}' 2>/dev/null && echo OPEN || echo CLOSED`
2182
+ } else if (type === 'process') {
2183
+ command = `pgrep -f ${JSON.stringify(target)} >/dev/null 2>&1 && echo RUNNING || echo STOPPED`
2184
+ } else if (type === 'service') {
2185
+ command = `systemctl is-active ${target.replace(/[^A-Za-z0-9@._-]/g, '')} 2>/dev/null || true`
2186
+ } else if (type === 'script') {
2187
+ const language = ['shell', 'python', 'js'].includes(monitor.language) ? monitor.language : 'shell'
2188
+ const interpreter = language === 'python' ? 'python3' : language === 'js' ? 'node' : 'bash'
2189
+ const encoded = Buffer.from(String(monitor.script || ''), 'utf8').toString('base64')
2190
+ command = `f=$(mktemp); printf %s ${JSON.stringify(encoded)} | base64 -d > "$f"; ${interpreter} "$f"; rc=$?; rm -f "$f"; exit $rc`
2191
+ } else {
2192
+ throw new Error(`unknown monitor type ${type}`)
2193
+ }
2194
+
2195
+ const result = await ssh(cfg, command, 15_000)
2196
+ const ms = Date.now() - started
2197
+ const out = String(result.stdout || '').trim()
2198
+ let ok = false
2199
+ let detail = out
2200
+ if (type === 'http') {
2201
+ const [code, time] = out.split(/\s+/)
2202
+ ok = Number(code) >= 200 && Number(code) < 400
2203
+ detail = `HTTP ${code}${time ? ` · ${Math.round(Number(time) * 1000)}ms` : ''}`
2204
+ } else if (type === 'port') {
2205
+ ok = /OPEN/.test(out)
2206
+ detail = ok ? '端口开放' : '端口不通'
2207
+ } else if (type === 'process') {
2208
+ ok = /RUNNING/.test(out)
2209
+ detail = ok ? '进程存在' : '进程不存在'
2210
+ } else if (type === 'service') {
2211
+ ok = out === 'active'
2212
+ detail = out || 'unknown'
2213
+ } else if (type === 'script') {
2214
+ ok = result.code === 0
2215
+ detail = ok ? (out.split('\n').filter(Boolean).pop() || '脚本返回 0').slice(0, 120) : `exit ${result.code}${out ? ' · ' + out.split('\n').filter(Boolean).pop().slice(0, 80) : ''}`
2216
+ }
2217
+ return { at: new Date().toISOString(), ok, ms, detail, code: result.code }
2218
+ }
2219
+
2220
+ /** Run every monitor of every host that is due, and record alerts on change. */
2221
+ let monitorPassRunning = false
2222
+
2223
+ async function runMonitorPass(force = false) {
2224
+ if (monitorPassRunning) return { ran: 0, changed: [] }
2225
+ if (!force && !(await acquireLock('.monitor-pass.lock', 4 * 60_000))) return { ran: 0, changed: [] }
2226
+ monitorPassRunning = true
2227
+ try {
2228
+ const all = await loadMonitors()
2229
+ const hostsList = (await loadHosts()).hosts
2230
+ const state = await loadState()
2231
+ const lastRun = state.monitorLastRun ?? {}
2232
+ const changed = []
2233
+ let ran = 0
2234
+
2235
+ for (const cfg of hostsList) {
2236
+ const list = all[cfg.name] || []
2237
+ if (list.length === 0) continue
2238
+ for (const monitor of list) {
2239
+ const interval = Math.max(1, Number(monitor.intervalMinutes) || 5) * 60_000
2240
+ const previous = lastRun[monitor.id] ?? 0
2241
+ if (!force && Date.now() - previous < interval) continue
2242
+ let result
2243
+ try {
2244
+ result = await runMonitor(cfg, monitor)
2245
+ } catch (error) {
2246
+ result = { at: new Date().toISOString(), ok: false, ms: 0, detail: String(error?.message || error), code: 1 }
2247
+ }
2248
+ lastRun[monitor.id] = Date.now()
2249
+ ran += 1
2250
+ monitor.last = result
2251
+ const wasOk = monitor.lastOk
2252
+ monitor.lastOk = result.ok
2253
+ if (result.ok !== wasOk && wasOk !== undefined) {
2254
+ changed.push({
2255
+ at: result.at,
2256
+ level: result.ok ? 'info' : 'critical',
2257
+ kind: 'monitor',
2258
+ host: cfg.name,
2259
+ message: `${monitor.type} ${monitor.target} ${result.ok ? '恢复正常' : '检查失败'}(${result.detail})`,
2260
+ })
2261
+ } else if (result.ok === false && wasOk === false) {
2262
+ const recent = (await loadAlerts()).find(entry =>
2263
+ entry.host === cfg.name && entry.message === `${monitor.type} ${monitor.target} 仍然失败(${result.detail})`
2264
+ && Date.now() - new Date(entry.at || 0).getTime() < 30 * 60_000)
2265
+ if (recent) { monitor.last = result; continue }
2266
+ changed.push({
2267
+ at: result.at,
2268
+ level: 'warning',
2269
+ kind: 'monitor',
2270
+ host: cfg.name,
2271
+ message: `${monitor.type} ${monitor.target} 仍然失败(${result.detail})`,
2272
+ })
2273
+ }
2274
+ }
2275
+ }
2276
+
2277
+ if (ran > 0) {
2278
+ await saveMonitors(all)
2279
+ await patchState({ monitorLastRun: lastRun })
2280
+ if (changed.length) await appendAlerts(changed)
2281
+ }
2282
+ return { ran, changed }
2283
+ } finally {
2284
+ monitorPassRunning = false
2285
+ if (!force) await releaseLock('.monitor-pass.lock')
2286
+ }
2287
+ }
2288
+
2289
+
2290
+ /* ---------- backups, health, certificates, cron, file history, deploy ---------- */
2291
+
2292
+ const q = (value) => JSON.stringify(String(value ?? ''))
2293
+
2294
+ async function loadJsonFile(name, fallback) {
2295
+ try {
2296
+ const data = JSON.parse(await readFile(join(kitDir(), name), 'utf8'))
2297
+ return data && typeof data === 'object' ? data : fallback
2298
+ } catch {
2299
+ return fallback
2300
+ }
2301
+ }
2302
+
2303
+ async function saveJsonFile(name, value) {
2304
+ await mkdir(kitDir(), { recursive: true })
2305
+ await writeFile(join(kitDir(), name), JSON.stringify(value, null, 2) + '\n', 'utf8')
2306
+ }
2307
+
2308
+ /* ---- backups ---- */
2309
+
2310
+ async function runBackup(cfg, job) {
2311
+ const dir = String(job.dir || '/home/backup').replace(/\/+$/, '')
2312
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
2313
+ const keep = Math.max(1, Math.min(Number(job.keep) || 7, 90))
2314
+ const started = Date.now()
2315
+ let file
2316
+ let command
2317
+
2318
+ if (job.type === 'mysql') {
2319
+ const database = String(job.database || '').trim()
2320
+ const user = String(job.user || 'root').trim()
2321
+ const password = String(job.password || '')
2322
+ const scope = database ? `--databases ${q(database)}` : '--all-databases'
2323
+ file = `${dir}/mysql-${database || 'all'}-${stamp}.sql.gz`
2324
+ command = [
2325
+ `mkdir -p ${q(dir)}`,
2326
+ `MYSQL_PWD=${q(password)} mysqldump -u${q(user)} ${scope} --single-transaction --quick --routines 2>/tmp/.ops-bk.err | gzip > ${q(file)}`,
2327
+ `rc=${'$'}{PIPESTATUS[0]}`,
2328
+ `if [ ${'"'}${'$'}rc${'"'} -ne 0 ]; then cat /tmp/.ops-bk.err; rm -f ${q(file)}; exit ${'$'}rc; fi`,
2329
+ `stat -c %s ${q(file)} 2>/dev/null || wc -c < ${q(file)}`,
2330
+ ].join('\n')
2331
+ } else {
2332
+ const raw = String(job.path || '').replace(/\/+$/, '')
2333
+ if (!raw || raw === '/') {
2334
+ file = `${dir}/rootfs-${stamp}.tar.gz`
2335
+ command = `mkdir -p ${q(dir)} && tar --exclude=proc --exclude=sys --exclude=dev --exclude=run --exclude=tmp -czf ${q(file)} / 2>/dev/null; stat -c %s ${q(file)}`
2336
+ } else {
2337
+ const base = raw.split('/').pop()
2338
+ const parent = raw.split('/').slice(0, -1).join('/') || '/'
2339
+ file = `${dir}/dir-${base}-${stamp}.tar.gz`
2340
+ command = `mkdir -p ${q(dir)} && tar --exclude='*.log' --exclude='logs' --exclude='*.tmp' -czf ${q(file)} -C ${q(parent)} ${q(base)} 2>/dev/null; stat -c %s ${q(file)}`
2341
+ }
2342
+ }
2343
+
2344
+ const result = await ssh(cfg, command, 20 * 60_000)
2345
+ const size = Number(String(result.stdout || '').trim().split('\n').pop()) || 0
2346
+ const record = {
2347
+ id: `b${Date.now().toString(36)}`,
2348
+ host: cfg.name,
2349
+ type: job.type === 'mysql' ? 'mysql' : 'dir',
2350
+ target: job.type === 'mysql' ? (job.database || 'all') : (job.path || '/'),
2351
+ file,
2352
+ size,
2353
+ keep,
2354
+ at: new Date().toISOString(),
2355
+ ms: Date.now() - started,
2356
+ ok: result.ok && size > 0,
2357
+ error: result.ok ? '' : cleanStderr(result.stderr).slice(0, 400),
2358
+ }
2359
+
2360
+ const all = await loadJsonFile('backups.json', {})
2361
+ const list = [record, ...(all[cfg.name] || [])].slice(0, 200)
2362
+ all[cfg.name] = list
2363
+ await saveJsonFile('backups.json', all)
2364
+
2365
+ if (record.ok) {
2366
+ const expired = list.filter(item => item.ok && !item.removed && item.type === record.type && item.target === record.target).slice(keep)
2367
+ if (expired.length) {
2368
+ await ssh(cfg, expired.map(item => `rm -f ${q(item.file)}`).join('; '), 60_000)
2369
+ for (const item of expired) { item.removed = true; item.error = '已按保留策略清理' }
2370
+ await saveJsonFile('backups.json', all)
2371
+ record.rotated = expired.length
2372
+ }
2373
+ }
2374
+ return record
2375
+ }
2376
+
2377
+ async function restoreBackup(cfg, id) {
2378
+ const all = await loadJsonFile('backups.json', {})
2379
+ const record = (all[cfg.name] || []).find(item => item.id === id)
2380
+ if (!record) throw new Error('备份记录不存在')
2381
+ if (!record.ok) throw new Error('这条备份本身失败了,不能恢复')
2382
+ let command
2383
+ if (record.type === 'mysql') {
2384
+ const scope = record.target === 'all' ? '' : q(record.target)
2385
+ command = `gunzip -c ${q(record.file)} | MYSQL_PWD=${q('')} mysql ${scope ? '--database=' + scope : ''} 2>&1 | tail -5`
2386
+ } else {
2387
+ const parent = record.file.replace(/\/[^/]+$/, '')
2388
+ command = `tar -tzf ${q(record.file)} >/dev/null 2>&1 || { echo '备份文件损坏'; exit 1; }; tar -xzf ${q(record.file)} -C / 2>&1 | tail -3`
2389
+ }
2390
+ const result = await ssh(cfg, command, 20 * 60_000)
2391
+ record.restoredAt = new Date().toISOString()
2392
+ record.restoreOk = result.ok
2393
+ await saveJsonFile('backups.json', all)
2394
+ return { id, ok: result.ok, output: clip(`${result.stdout || ''}${cleanStderr(result.stderr)}`, 800) }
2395
+ }
2396
+
2397
+ /* ---- health score ---- */
2398
+
2399
+ const HEALTH_CHECKS = [
2400
+ { id: 'disk', weight: 22, label: '磁盘空间' },
2401
+ { id: 'mem', weight: 16, label: '内存' },
2402
+ { id: 'swap', weight: 8, label: '交换区' },
2403
+ { id: 'units', weight: 14, label: '系统服务' },
2404
+ { id: 'cert', weight: 12, label: '证书' },
2405
+ { id: 'backup', weight: 14, label: '备份' },
2406
+ { id: 'monitor', weight: 8, label: '服务监控' },
2407
+ { id: 'ssh', weight: 6, label: '登录安全' },
2408
+ ]
2409
+
2410
+ async function computeHealth(cfg) {
2411
+ const sample = await sampleMetrics(cfg)
2412
+ const issues = []
2413
+ let score = 100
2414
+ const detail = {}
2415
+
2416
+ const disk = Number(sample.disk ?? 0)
2417
+ detail.disk = disk
2418
+ if (disk >= 95) { score -= 22; issues.push({ id: 'disk', level: 'critical', text: `磁盘只剩 ${(100 - disk).toFixed(1)}%,随时会写满`, action: 'cleanup' }) }
2419
+ else if (disk >= 85) { score -= 12; issues.push({ id: 'disk', level: 'warning', text: `磁盘已用 ${disk}%,建议清理`, action: 'cleanup' }) }
2420
+
2421
+ const mem = Number(sample.mem ?? 0)
2422
+ detail.mem = mem
2423
+ if (mem >= 95) { score -= 16; issues.push({ id: 'mem', level: 'critical', text: `内存已用 ${mem}%,进程可能被杀`, action: 'ps' }) }
2424
+ else if (mem >= 88) { score -= 8; issues.push({ id: 'mem', level: 'warning', text: `内存已用 ${mem}%`, action: 'ps' }) }
2425
+
2426
+ const swap = Number(sample.swap ?? 0)
2427
+ detail.swap = swap
2428
+ if (swap >= 70) { score -= 6; issues.push({ id: 'swap', level: 'warning', text: `交换区已用 ${swap}%,说明内存吃紧`, action: 'ps' }) }
2429
+
2430
+ const units = await ssh(cfg, "systemctl list-units --state=failed --no-legend --no-pager 2>/dev/null | awk '{print $2}' | head -20; true", 20_000)
2431
+ const failed = String(units.stdout || '').split('\n').map(line => line.trim()).filter(Boolean)
2432
+ detail.failedUnits = failed
2433
+ if (failed.length) { score -= Math.min(14, failed.length * 6); issues.push({ id: 'units', level: 'critical', text: `${failed.length} 个服务启动失败:${failed.slice(0, 3).join('、')}`, action: 'units' }) }
2434
+
2435
+ const certs = await scanCerts(cfg).catch(() => [])
2436
+ detail.certs = certs
2437
+ const soonest = certs.filter(item => typeof item.days === 'number').sort((a, b) => a.days - b.days)[0]
2438
+ if (soonest) {
2439
+ if (soonest.days <= 3) { score -= 12; issues.push({ id: 'cert', level: 'critical', text: `${soonest.domain} 证书 ${soonest.days} 天后过期`, action: 'cert' }) }
2440
+ else if (soonest.days <= 14) { score -= 6; issues.push({ id: 'cert', level: 'warning', text: `${soonest.domain} 证书 ${soonest.days} 天后过期`, action: 'cert' }) }
2441
+ }
2442
+
2443
+ const backups = (await loadJsonFile('backups.json', {}))[cfg.name] || []
2444
+ const okBackups = backups.filter(item => item.ok && !item.removed)
2445
+ const newest = okBackups[0]
2446
+ detail.lastBackup = newest ? newest.at : null
2447
+ if (!newest) { score -= 14; issues.push({ id: 'backup', level: 'critical', text: '还没有任何备份,服务器坏了数据找不回来', action: 'backup' }) }
2448
+ else {
2449
+ const days = (Date.now() - new Date(newest.at).getTime()) / 86_400_000
2450
+ if (days > 3) { score -= 10; issues.push({ id: 'backup', level: 'warning', text: `上次备份是 ${Math.floor(days)} 天前`, action: 'backup' }) }
2451
+ }
2452
+
2453
+ const monitors = (await loadMonitors())[cfg.name] || []
2454
+ const failing = monitors.filter(item => item.lastOk === false)
2455
+ detail.monitors = { total: monitors.length, failing: failing.length }
2456
+ if (failing.length) { score -= Math.min(8, failing.length * 4); issues.push({ id: 'monitor', level: 'critical', text: `${failing.length} 个监控项检查失败:${failing.slice(0, 2).map(item => item.label || item.target).join('、')}`, action: 'monitor' }) }
2457
+
2458
+ const sshd = await ssh(cfg, "sshd -T 2>/dev/null | grep -E '^(permitrootlogin|passwordauthentication)' ; true", 15_000)
2459
+ const sshText = String(sshd.stdout || '')
2460
+ detail.ssh = sshText.trim()
2461
+ if (/permitrootlogin yes/i.test(sshText)) issues.push({ id: 'ssh', level: 'info', text: '允许 root 直接登录,建议改密钥登录', action: 'cert-more' })
2462
+
2463
+ score = Math.max(0, Math.min(100, score))
2464
+ const level = score >= 90 ? 'ok' : score >= 70 ? 'warn' : 'bad'
2465
+ return {
2466
+ host: cfg.name,
2467
+ score,
2468
+ level,
2469
+ sample,
2470
+ issues: issues.sort((a, b) => (a.level === 'critical' ? 0 : 1) - (b.level === 'critical' ? 0 : 1)),
2471
+ detail,
2472
+ }
2473
+ }
2474
+
2475
+ /* ---- certificates ---- */
2476
+
2477
+ async function scanCerts(cfg) {
2478
+ const discovered = await ssh(cfg, "nginx -T 2>/dev/null | grep -oP 'server_name\\s+\\K[^;]+' | tr ' ' '\\n' | grep -v '_' | sort -u | head -20; true", 20_000)
2479
+ const domains = String(discovered.stdout || '')
2480
+ .split('\n')
2481
+ .map(line => line.trim())
2482
+ .filter(line => line && !line.includes('localhost'))
2483
+ const unique = [...new Set(domains)].slice(0, 12)
2484
+ if (unique.length === 0) return []
2485
+ const command = unique.map(domain => {
2486
+ return `echo "==${domain}"; echo | timeout 8 openssl s_client -servername ${q(domain)} -connect ${q(domain)}:443 2>/dev/null | openssl x509 -noout -enddate -subject 2>/dev/null || echo "NO_CERT"`
2487
+ }).join('; ')
2488
+ const result = await ssh(cfg, command, 60_000)
2489
+ const out = String(result.stdout || '')
2490
+ const certs = []
2491
+ for (const chunk of out.split('==').slice(1)) {
2492
+ const [domain, ...rest] = chunk.split('\n')
2493
+ const body = rest.join('\n')
2494
+ const match = body.match(/notAfter=(.+)/)
2495
+ if (!match) { certs.push({ domain: domain.trim(), days: null, error: 'no certificate' }); continue }
2496
+ const expiry = new Date(match[1])
2497
+ const days = Math.round((expiry.getTime() - Date.now()) / 86_400_000)
2498
+ const subject = (body.match(/subject=(.+)/) || [])[1] || ''
2499
+ certs.push({ domain: domain.trim(), subject: subject.trim(), expiresAt: expiry.toISOString(), days, ok: days > 14 })
2500
+ }
2501
+ return certs
2502
+ }
2503
+
2504
+ async function renewCerts(cfg, dryRun = true) {
2505
+ const command = dryRun ? 'certbot renew --dry-run 2>&1 | tail -25' : 'certbot renew 2>&1 | tail -25'
2506
+ const result = await ssh(cfg, command, 10 * 60_000)
2507
+ return { ok: result.ok, dryRun, output: clip(`${result.stdout || ''}${cleanStderr(result.stderr)}`, 1500) }
2508
+ }
2509
+
2510
+ /* ---- cron ---- */
2511
+
2512
+ async function listCron(cfg) {
2513
+ const result = await ssh(cfg, 'crontab -l 2>/dev/null || true', 20_000)
2514
+ const lines = String(result.stdout || '').split('\n')
2515
+ const jobs = []
2516
+ lines.forEach((line, index) => {
2517
+ const text = line.trim()
2518
+ if (!text || text.startsWith('#')) return
2519
+ const parts = text.split(/\s+/)
2520
+ if (parts.length < 6) return
2521
+ jobs.push({ index, schedule: parts.slice(0, 5).join(' '), command: parts.slice(5).join(' '), raw: text })
2522
+ })
2523
+ return jobs
2524
+ }
2525
+
2526
+ async function writeCron(cfg, lines) {
2527
+ const encoded = Buffer.from(lines.join('\n') + '\n', 'utf8').toString('base64')
2528
+ const result = await ssh(cfg, `printf %s ${q(encoded)} | base64 -d | crontab - && crontab -l | wc -l`, 30_000)
2529
+ return { ok: result.ok, count: Number(String(result.stdout || '').trim()) || 0, error: result.ok ? '' : cleanStderr(result.stderr) }
2530
+ }
2531
+
2532
+ async function addCron(cfg, job) {
2533
+ const current = await ssh(cfg, 'crontab -l 2>/dev/null || true', 20_000)
2534
+ const lines = String(current.stdout || '').split('\n').filter(line => line.trim())
2535
+ const schedule = [job.minute ?? '0', job.hour ?? '3', job.day ?? '*', job.month ?? '*', job.weekday ?? '*'].join(' ')
2536
+ const line = `${schedule} ${String(job.command || '').trim()}`
2537
+ if (!job.command) throw new Error('command is required')
2538
+ return writeCron(cfg, [...lines, line])
2539
+ }
2540
+
2541
+ async function removeCron(cfg, index) {
2542
+ const current = await ssh(cfg, 'crontab -l 2>/dev/null || true', 20_000)
2543
+ const lines = String(current.stdout || '').split('\n')
2544
+ lines.splice(Number(index), 1)
2545
+ return writeCron(cfg, lines.filter(line => line.trim()))
2546
+ }
2547
+
2548
+ /* ---- config history ---- */
2549
+
2550
+ async function fileHistory(cfg, path) {
2551
+ const dir = path.replace(/\/[^/]+$/, '') || '/'
2552
+ const base = path.split('/').pop()
2553
+ const command = `find ${q(dir)} -maxdepth 1 -name ${q(base + '.bak.*')} -printf '%T@ %p\\n' 2>/dev/null | sort -rn | cut -d' ' -f2- | head -20; true`
2554
+ const result = await ssh(cfg, command, 20_000)
2555
+ return String(result.stdout || '').split('\n').map(line => line.trim()).filter(Boolean)
2556
+ }
2557
+
2558
+ async function fileDiff(cfg, path, backup) {
2559
+ const result = await ssh(cfg, `diff -u ${q(backup)} ${q(path)} | head -200; true`, 30_000)
2560
+ return { diff: String(result.stdout || '') }
2561
+ }
2562
+
2563
+ async function fileRestore(cfg, path, backup) {
2564
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
2565
+ const result = await ssh(cfg, `cp -p ${q(path)} ${q(path + '.bak.' + stamp)} 2>/dev/null; cp -p ${q(backup)} ${q(path)} && echo restored`, 30_000)
2566
+ return { ok: result.ok && /restored/.test(String(result.stdout || '')), output: clip(`${result.stdout || ''}${cleanStderr(result.stderr)}`, 500) }
2567
+ }
2568
+
2569
+ /* ---- deploy ---- */
2570
+
2571
+ async function runDeploy(cfg, job) {
2572
+ const dir = String(job.dir || '').trim()
2573
+ if (!dir) throw new Error('dir is required')
2574
+ const steps = []
2575
+ const run = async (label, command, timeoutMs = 10 * 60_000) => {
2576
+ const result = await ssh(cfg, `cd ${q(dir)} && ${command}`, timeoutMs)
2577
+ steps.push({ label, ok: result.ok, output: clip(`${result.stdout || ''}${cleanStderr(result.stderr)}`, 900) })
2578
+ return result.ok
2579
+ }
2580
+ const previous = await ssh(cfg, `cd ${q(dir)} && git rev-parse --short HEAD 2>/dev/null || true`, 20_000)
2581
+ const previousRev = String(previous.stdout || '').trim()
2582
+
2583
+ if (job.repo) {
2584
+ if (!(await run('拉取代码', `git fetch --all -q && git reset --hard ${q(job.branch || 'origin/main')} -q && git log -1 --oneline`))) {
2585
+ return { ok: false, steps, error: '拉取代码失败' }
2586
+ }
2587
+ }
2588
+ if (job.build) {
2589
+ if (!(await run('构建', job.build))) return { ok: false, steps, error: '构建失败,未重启服务' }
2590
+ }
2591
+ if (job.restart) {
2592
+ if (!(await run('重启服务', job.restart, 120_000))) return { ok: false, steps, error: '重启失败' }
2593
+ }
2594
+ if (job.health) {
2595
+ await new Promise(resolve => setTimeout(resolve, 3000))
2596
+ const health = await ssh(cfg, `curl -s -o /dev/null -w '%{http_code}' --max-time 10 ${q(job.health)} || echo 000`, 30_000)
2597
+ const code = String(health.stdout || '').trim()
2598
+ steps.push({ label: '健康检查', ok: Number(code) >= 200 && Number(code) < 400, output: `HTTP ${code}` })
2599
+ if (!(Number(code) >= 200 && Number(code) < 400)) {
2600
+ if (job.rollback !== false && previousRev) {
2601
+ await run('回滚', `git reset --hard ${q(previousRev)} -q && (${job.restart || 'true'})`, 180_000)
2602
+ }
2603
+ return { ok: false, steps, error: `健康检查失败(HTTP ${code})`, rolledBack: Boolean(previousRev) }
2604
+ }
2605
+ }
2606
+ return { ok: true, steps, previousRev }
2607
+ }
2608
+
2609
+
2610
+ /** Emit certificate-expiry alerts at 14/7/3 days, once per threshold per domain. */
2611
+ async function checkCertAlerts() {
2612
+ const state = await loadState()
2613
+ if (state.certLastRun && Date.now() - state.certLastRun < 20 * 60 * 60_000) return { skipped: true }
2614
+ const hostsList = (await loadHosts()).hosts
2615
+ const seen = state.certAlerts ?? {}
2616
+ const alerts = []
2617
+ for (const cfg of hostsList) {
2618
+ let certs = []
2619
+ try { certs = await scanCerts(cfg) } catch { continue }
2620
+ for (const cert of certs) {
2621
+ if (typeof cert.days !== 'number') continue
2622
+ const threshold = cert.days <= 3 ? 3 : cert.days <= 7 ? 7 : cert.days <= 14 ? 14 : 0
2623
+ if (!threshold) continue
2624
+ const key = `${cfg.name}:${cert.domain}:${threshold}`
2625
+ if (seen[key]) continue
2626
+ seen[key] = Date.now()
2627
+ alerts.push({
2628
+ at: new Date().toISOString(),
2629
+ level: threshold <= 3 ? 'critical' : 'warning',
2630
+ kind: 'cert',
2631
+ host: cfg.name,
2632
+ message: `${cert.domain} 证书还有 ${cert.days} 天过期,请续期(面板:服务器 → 概览 → 证书)`,
2633
+ })
2634
+ }
2635
+ }
2636
+ if (alerts.length) await appendAlerts(alerts)
2637
+ await patchState({ certLastRun: Date.now(), certAlerts: seen })
2638
+ return { alerts: alerts.length }
2639
+ }
2640
+
2641
+
2642
+ /* ---------- alert delivery (webhooks) ---------- */
2643
+
2644
+ function channelsFile() { return join(kitDir(), 'channels.json') }
2645
+
2646
+ async function loadChannels() {
2647
+ const all = await loadJsonFile('channels.json', { channels: [] })
2648
+ return Array.isArray(all.channels) ? all : { channels: [] }
2649
+ }
2650
+
2651
+ async function saveChannels(all) {
2652
+ await saveJsonFile('channels.json', all)
2653
+ }
2654
+
2655
+ const CHANNEL_TYPES = ['feishu', 'dingtalk', 'wecom', 'webhook']
2656
+
2657
+ function channelPayload(type, text, extra) {
2658
+ if (type === 'feishu') return { msg_type: 'text', content: { text } }
2659
+ if (type === 'dingtalk') return { msgtype: 'text', text: { content: text } }
2660
+ if (type === 'wecom') return { msgtype: 'text', text: { content: text } }
2661
+ return { text, ...extra }
2662
+ }
2663
+
2664
+ async function sendChannel(channel, text, extra) {
2665
+ if (!channel?.url) throw new Error('webhook url is missing')
2666
+ const response = await fetch(channel.url, {
2667
+ method: 'POST',
2668
+ headers: { 'content-type': 'application/json' },
2669
+ body: JSON.stringify(channelPayload(channel.type, text, extra)),
2670
+ signal: AbortSignal.timeout(10_000),
2671
+ })
2672
+ const body = await response.text().catch(() => '')
2673
+ return { ok: response.ok, status: response.status, body: body.slice(0, 300) }
2674
+ }
2675
+
2676
+ function alertLine(alert) {
2677
+ const time = new Date(alert.at || Date.now()).toLocaleString('zh-CN', { hour12: false })
2678
+ const level = alert.level === 'critical' ? '🔴 严重' : alert.level === 'warning' ? '🟠 警告' : '🔵 提示'
2679
+ return `${level}|${alert.host || ''}|${alert.message}\n${time}`
2680
+ }
2681
+
2682
+ /** Send new alerts to every enabled channel, deduplicating for 10 minutes. */
2683
+ async function dispatchAlerts(alerts) {
2684
+ const list = (alerts || []).filter(Boolean)
2685
+ if (list.length === 0) return { sent: 0 }
2686
+ const { channels } = await loadChannels()
2687
+ const enabled = channels.filter(channel => channel.enabled !== false)
2688
+ if (enabled.length === 0) return { sent: 0 }
2689
+
2690
+ const state = await loadState()
2691
+ const delivered = state.delivered ?? {}
2692
+ const now = Date.now()
2693
+ const fresh = list.filter(alert => {
2694
+ const key = `${alert.host}:${alert.level}:${alert.message}`.slice(0, 200)
2695
+ if (delivered[key] && now - delivered[key] < 10 * 60_000) return false
2696
+ delivered[key] = now
2697
+ return true
2698
+ })
2699
+ if (fresh.length === 0) return { sent: 0 }
2700
+
2701
+ const text = fresh.map(alertLine).join('\n\n')
2702
+ const results = []
2703
+ for (const channel of enabled) {
2704
+ const events = Array.isArray(channel.events) && channel.events.length ? channel.events : ['critical', 'warning']
2705
+ if (!fresh.some(alert => events.includes(alert.level))) continue
2706
+ try {
2707
+ const result = await sendChannel(channel, text, { alerts: fresh })
2708
+ results.push({ channel: channel.id, ...result })
2709
+ } catch (error) {
2710
+ results.push({ channel: channel.id, ok: false, error: String(error?.message || error) })
2711
+ }
2712
+ }
2713
+ await patchState({ delivered })
2714
+ return { sent: results.filter(item => item.ok).length, results }
2715
+ }
2716
+
2717
+ async function testChannel(channel) {
2718
+ const text = `✅ dsh-ops-kit 测试消息\n如果你看到这条,说明告警通道配置正确。\n${new Date().toLocaleString('zh-CN', { hour12: false })}`
2719
+ return sendChannel(channel, text, { test: true })
2720
+ }
2721
+
2722
+
2723
+ /** Coarse cross-instance lock: mkdir is atomic, stale locks expire. */
2724
+ async function acquireLock(name, ttlMs = 5 * 60_000) {
2725
+ const dir = join(kitDir(), name)
2726
+ try {
2727
+ await mkdir(dir, { recursive: false })
2728
+ return true
2729
+ } catch {
2730
+ try {
2731
+ const info = await stat(dir)
2732
+ if (Date.now() - info.mtimeMs > ttlMs) {
2733
+ await rm(dir, { recursive: true, force: true })
2734
+ await mkdir(dir, { recursive: false })
2735
+ return true
2736
+ }
2737
+ } catch { /* ignore */ }
2738
+ return false
2739
+ }
2740
+ }
2741
+
2742
+ async function releaseLock(name) {
2743
+ try { await rm(join(kitDir(), name), { recursive: true, force: true }) } catch { /* ignore */ }
2744
+ }
2745
+
2746
+ export function apply(ctx) {
2747
+ hostCtx = ctx
2748
+ const tools = [
2749
+ asTool({
2750
+ name: 'ops_hosts',
2751
+ description:
2752
+ 'List, add or remove SSH hosts in the ops inventory. Authentication uses a stored password '
2753
+ + '(0600 file) or your existing ssh key/agent; private keys are never copied.',
2754
+ parameters: {
2755
+ action: { type: 'string', enum: ['list', 'add', 'update', 'remove'], description: 'what to do; defaults to list' },
2756
+ name: { type: 'string', description: 'short host name used by the other ops tools' },
2757
+ host: { type: 'string', description: 'hostname or IP for action=add' },
2758
+ user: { type: 'string', description: 'ssh user; defaults to your local user name' },
2759
+ port: { type: 'number', description: 'ssh port; defaults to 22' },
2760
+ key: { type: 'string', description: 'private key path; omit to use ssh agent / default keys' },
2761
+ sudo: { type: 'boolean', description: 'run remote service actions through `sudo -n`' },
2762
+ defaultHost: { type: 'boolean', description: 'with action=add: make this the default host' },
2763
+ alias: { type: 'string', description: 'display name shown in the panel, such as 公司网站' },
2764
+ password: { type: 'string', description: 'with action=add: ssh password, stored locally in a 0600 file (prefer keys)' },
2765
+ },
2766
+ async execute(args = {}) {
2767
+ const data = await loadHosts()
2768
+ const action = args.action ?? 'list'
2769
+ if (action === 'update') {
2770
+ if (!args.name) throw new Error('action=update needs name')
2771
+ const host = data.hosts.find(h => h.name === args.name)
2772
+ if (!host) throw new Error(`unknown host ${args.name}`)
2773
+ if (args.host) host.host = String(args.host)
2774
+ if (args.user) host.user = String(args.user)
2775
+ if (args.port) host.port = Number(args.port)
2776
+ if (args.alias !== undefined) host.alias = String(args.alias)
2777
+ if (args.key !== undefined) host.key = args.key ? String(args.key) : null
2778
+ if (args.sudo !== undefined) host.sudo = args.sudo === true
2779
+ await saveHosts(data)
2780
+ if (args.password) await saveSecret(host.name, args.password)
2781
+ return { updated: host, hosts: data.hosts }
2782
+ }
2783
+ if (action === 'list') {
2784
+ return { hosts: data.hosts, defaultHost: data.defaultHost ?? null, file: hostsFile() }
2785
+ }
2786
+ if (action === 'add') {
2787
+ if (!args.name || !args.host) throw new Error('action=add needs both name and host')
2788
+ const row = {
2789
+ name: String(args.name),
2790
+ alias: args.alias ? String(args.alias) : null,
2791
+ host: String(args.host),
2792
+ user: args.user ?? process.env.USER ?? null,
2793
+ port: Number(args.port ?? 22),
2794
+ key: args.key ?? null,
2795
+ sudo: args.sudo === true,
2796
+ }
2797
+ data.hosts = data.hosts.filter(h => h.name !== row.name)
2798
+ data.hosts.push(row)
2799
+ if (args.defaultHost === true || !data.defaultHost) data.defaultHost = row.name
2800
+ await saveHosts(data)
2801
+ if (args.password) await saveSecret(row.name, args.password)
2802
+ const probe = await ssh(row, 'echo ok', 12_000)
2803
+ return { added: row, defaultHost: data.defaultHost ?? null, passwordStored: Boolean(args.password), tested: { ok: probe.ok, code: probe.code, error: probe.ok ? '' : cleanStderr(probe.stderr) }, file: hostsFile() }
2804
+ }
2805
+ if (action === 'remove') {
2806
+ if (!args.name) throw new Error('action=remove needs name')
2807
+ const before = data.hosts.length
2808
+ data.hosts = data.hosts.filter(h => h.name !== args.name)
2809
+ if (data.defaultHost === args.name) data.defaultHost = data.hosts[0]?.name ?? null
2810
+ await saveHosts(data)
2811
+ await saveSecret(args.name, null)
2812
+ return { removed: before - data.hosts.length, hosts: data.hosts, defaultHost: data.defaultHost ?? null }
2813
+ }
2814
+ throw new Error(`unknown action ${action}`)
2815
+ },
2816
+ }),
2817
+
2818
+ asTool({
2819
+ name: 'ops_status',
2820
+ description:
2821
+ 'One-screen health of a configured host: uptime and load, memory, root disk, failed systemd units, '
2822
+ + 'and Docker containers when Docker is present. Read-only.',
2823
+ parameters: {
2824
+ host: { type: 'string', description: 'host name from ops_hosts; defaults to the default host' },
2825
+ },
2826
+ async execute(args = {}) {
2827
+ const cfg = pickHost(await loadHosts(), args.host)
2828
+ const result = await statusOf(cfg)
2829
+ return { host: cfg.name, address: target(cfg), ...summary(result, cfg) }
2830
+ },
2831
+ }),
2832
+
2833
+ asTool({
2834
+ name: 'ops_check_all',
2835
+ description:
2836
+ 'Check every configured host in parallel and record the run in the local history file. '
2837
+ + 'Returns one bounded summary row per host (no full logs).',
2838
+ parameters: {},
2839
+ async execute() {
2840
+ const out = await statusAll()
2841
+ return {
2842
+ at: out.at,
2843
+ elapsedMs: out.elapsedMs,
2844
+ results: out.results.map(row => ({
2845
+ host: row.host,
2846
+ ok: row.ok,
2847
+ code: row.code,
2848
+ elapsedMs: row.elapsedMs,
2849
+ summary: row.ok ? firstLines(row.output) : clip(row.error, 300),
2850
+ ...(row.ok || !row.hint ? {} : { hint: row.hint }),
2851
+ })),
2852
+ }
2853
+ },
2854
+ }),
2855
+
2856
+ asTool({
2857
+ name: 'ops_alerts',
2858
+ description: 'Recent alerts produced by scheduled checks: host down, recovered, disk pressure, failed systemd units.',
2859
+ parameters: {
2860
+ limit: { type: 'number', description: 'how many entries; defaults to 20' },
2861
+ },
2862
+ async execute(args = {}) {
2863
+ const limit = Math.min(Number(args.limit ?? 20) || 20, ALERT_LIMIT)
2864
+ return { entries: (await loadAlerts()).slice(0, limit) }
2865
+ },
2866
+ }),
2867
+
2868
+ asTool({
2869
+ name: 'ops_config',
2870
+ description:
2871
+ 'Read or change the scheduled-check settings: enabled, intervalMinutes, diskWarnPercent. '
2872
+ + 'Called with no arguments it returns the effective configuration and the last run time.',
2873
+ parameters: {
2874
+ enabled: { type: 'boolean', description: 'turn scheduled checks on or off' },
2875
+ intervalMinutes: { type: 'number', description: 'minutes between automatic checks (1-1440)' },
2876
+ diskWarnPercent: { type: 'number', description: 'root-disk warning threshold in percent (50-99)' },
2877
+ metricsMinutes: { type: 'number', description: 'minutes between metric samples (1-60)' },
2878
+ timeoutSec: { type: 'number', description: 'default request timeout in seconds (5-300)' },
2879
+ scanSec: { type: 'number', description: 'inventory scan timeout in seconds (10-600)' },
2880
+ actionSec: { type: 'number', description: 'action/log timeout in seconds (10-600)' },
2881
+ quickCommands: { type: 'array', items: { type: 'string' }, description: 'custom quick commands shown under the terminal (max 12)' },
2882
+ aiEnabled: { type: 'boolean', description: 'turn the AI assistant on or off' },
2883
+ aiProvider: { type: 'string', description: 'provider id for the ops AI; empty means the DSH default model' },
2884
+ aiModel: { type: 'string', description: 'model id for the ops AI; empty means the DSH default model' },
2885
+ },
2886
+ async execute(args = {}) {
2887
+ const patch = {}
2888
+ if (typeof args.enabled === 'boolean') patch.enabled = args.enabled
2889
+ if (typeof args.intervalMinutes === 'number') patch.intervalMinutes = Math.max(1, Math.min(Math.round(args.intervalMinutes), 1440))
2890
+ if (typeof args.diskWarnPercent === 'number') patch.diskWarnPercent = Math.max(50, Math.min(Math.round(args.diskWarnPercent), 99))
2891
+ if (typeof args.metricsMinutes === 'number') patch.metricsMinutes = Math.max(1, Math.min(Math.round(args.metricsMinutes), 60))
2892
+ if (typeof args.timeoutSec === 'number') patch.timeoutSec = Math.max(5, Math.min(Math.round(args.timeoutSec), 300))
2893
+ if (typeof args.scanSec === 'number') patch.scanSec = Math.max(10, Math.min(Math.round(args.scanSec), 600))
2894
+ if (typeof args.actionSec === 'number') patch.actionSec = Math.max(10, Math.min(Math.round(args.actionSec), 600))
2895
+ if (typeof args.aiEnabled === 'boolean') patch.aiEnabled = args.aiEnabled
2896
+ if (typeof args.aiProvider === 'string') patch.aiProvider = args.aiProvider.slice(0, 80)
2897
+ if (typeof args.aiModel === 'string') patch.aiModel = args.aiModel.slice(0, 120)
2898
+ if (Array.isArray(args.quickCommands)) {
2899
+ patch.quickCommands = args.quickCommands.map(item => String(item ?? '').trim()).filter(Boolean).slice(0, 12).map(item => item.slice(0, 160))
2900
+ }
2901
+ const config = Object.keys(patch).length > 0 ? await saveConfig(patch) : await loadConfig()
2902
+ const state = await loadState()
2903
+ return {
2904
+ config,
2905
+ lastRunAt: state.lastRunAt ? new Date(state.lastRunAt).toISOString() : null,
2906
+ file: configFile(),
2907
+ }
2908
+ },
2909
+ }),
2910
+
2911
+ asTool({
2912
+ name: 'ops_metrics',
2913
+ description: 'CPU / memory / disk samples for one host from the local metrics history (sampled by the scheduler).',
2914
+ parameters: {
2915
+ host: { type: 'string', description: 'host name from ops_hosts; defaults to the default host' },
2916
+ hours: { type: 'number', description: 'window in hours; defaults to 6' },
2917
+ },
2918
+ async execute(args = {}) {
2919
+ const cfg = pickHost(await loadHosts(), args.host)
2920
+ const hours = Math.min(Math.max(Number(args.hours ?? 6) || 6, 1), 24 * 30)
2921
+ const rows = await loadMetrics(cfg.name, Date.now() - hours * 3_600_000)
2922
+ const last = rows[rows.length - 1] || null
2923
+ return { host: cfg.name, hours, samples: rows.length, last, recent: rows.slice(-24).map(r => ({ ts: r.ts, cpu: r.cpu, mem: r.mem, disk: r.disk })) }
2924
+ },
2925
+ }),
2926
+
2927
+ asTool({
2928
+ name: 'ops_inventory',
2929
+ description: 'Read-only inventory of a host: listening ports, running services, containers, nginx sites, java processes, crontab and mounts.',
2930
+ parameters: {
2931
+ host: { type: 'string', description: 'host name from ops_hosts; defaults to the default host' },
2932
+ refresh: { type: 'boolean', description: 're-scan the host instead of returning the cached inventory' },
2933
+ },
2934
+ async execute(args = {}) {
2935
+ const cfg = pickHost(await loadHosts(), args.host)
2936
+ const cached = args.refresh === true ? null : await loadInventory(cfg.name)
2937
+ const inv = cached ?? await discover(cfg)
2938
+ return {
2939
+ host: inv.host,
2940
+ at: inv.at,
2941
+ apps: inv.apps.slice(0, 30),
2942
+ ports: inv.ports.slice(0, 20),
2943
+ mounts: inv.mounts,
2944
+ crontab: inv.crontab.slice(0, 10),
2945
+ }
2946
+ },
2947
+ }),
2948
+
2949
+ asTool({
2950
+ name: 'ops_backup',
2951
+ description: 'Back up a MySQL database or a directory on a host, list backups, restore or delete one.',
2952
+ parameters: {
2953
+ host: { type: 'string', description: 'host name from ops_hosts' },
2954
+ action: { type: 'string', enum: ['list', 'backup', 'restore', 'remove'], description: 'defaults to list' },
2955
+ type: { type: 'string', enum: ['mysql', 'dir'], description: 'with action=backup' },
2956
+ database: { type: 'string', description: 'database name for mysql (empty = all)' },
2957
+ path: { type: 'string', description: 'directory to archive with type=dir' },
2958
+ dir: { type: 'string', description: 'where backups are stored on the server, default /home/backup' },
2959
+ keep: { type: 'number', description: 'how many backups to keep, default 7' },
2960
+ id: { type: 'string', description: 'backup id for restore/remove' },
2961
+ },
2962
+ async execute(args = {}) {
2963
+ const cfg = pickHost(await loadHosts(), args.host)
2964
+ const all = await loadJsonFile('backups.json', {})
2965
+ if ((args.action ?? 'list') === 'list') return { host: cfg.name, backups: all[cfg.name] || [] }
2966
+ if (args.action === 'restore') return restoreBackup(cfg, String(args.id ?? ''))
2967
+ if (args.action === 'remove') {
2968
+ const list = all[cfg.name] || []
2969
+ const record = list.find(item => item.id === args.id)
2970
+ if (record) await ssh(cfg, `rm -f ${q(record.file)}`, 30_000)
2971
+ all[cfg.name] = list.filter(item => item.id !== args.id)
2972
+ await saveJsonFile('backups.json', all)
2973
+ return { host: cfg.name, backups: all[cfg.name] }
2974
+ }
2975
+ return runBackup(cfg, args)
2976
+ },
2977
+ }),
2978
+
2979
+ asTool({
2980
+ name: 'ops_health',
2981
+ description: 'Score one host 0-100 and list the issues worth fixing first (disk, memory, failed units, certificates, backups, monitors).',
2982
+ parameters: { host: { type: 'string', description: 'host name from ops_hosts' } },
2983
+ async execute(args = {}) {
2984
+ const cfg = pickHost(await loadHosts(), args.host)
2985
+ return computeHealth(cfg)
2986
+ },
2987
+ }),
2988
+
2989
+ asTool({
2990
+ name: 'ops_cert',
2991
+ description: 'List TLS certificates of the sites on a host and their remaining days, or renew them with certbot (dry run by default).',
2992
+ parameters: {
2993
+ host: { type: 'string', description: 'host name from ops_hosts' },
2994
+ action: { type: 'string', enum: ['list', 'renew'], description: 'defaults to list' },
2995
+ dryRun: { type: 'boolean', description: 'with action=renew, default true' },
2996
+ },
2997
+ async execute(args = {}) {
2998
+ const cfg = pickHost(await loadHosts(), args.host)
2999
+ if (args.action === 'renew') return renewCerts(cfg, args.dryRun !== false)
3000
+ return { host: cfg.name, certs: await scanCerts(cfg) }
3001
+ },
3002
+ }),
3003
+
3004
+ asTool({
3005
+ name: 'ops_cron',
3006
+ description: 'List, add or remove crontab entries on a host.',
3007
+ parameters: {
3008
+ host: { type: 'string', description: 'host name from ops_hosts' },
3009
+ action: { type: 'string', enum: ['list', 'add', 'remove'], description: 'defaults to list' },
3010
+ command: { type: 'string', description: 'shell command for action=add' },
3011
+ minute: { type: 'string', description: 'minute field, default 0' },
3012
+ hour: { type: 'string', description: 'hour field, default 3' },
3013
+ day: { type: 'string', description: 'day of month, default *' },
3014
+ month: { type: 'string', description: 'month, default *' },
3015
+ weekday: { type: 'string', description: 'day of week, default *' },
3016
+ index: { type: 'number', description: 'line index for action=remove' },
3017
+ },
3018
+ async execute(args = {}) {
3019
+ const cfg = pickHost(await loadHosts(), args.host)
3020
+ if (args.action === 'add') return addCron(cfg, args)
3021
+ if (args.action === 'remove') return removeCron(cfg, args.index)
3022
+ return { host: cfg.name, jobs: await listCron(cfg) }
3023
+ },
3024
+ }),
3025
+
3026
+ asTool({
3027
+ name: 'ops_file_history',
3028
+ description: 'List the .bak.<ts> versions of a config file, show a diff, or restore one of them.',
3029
+ parameters: {
3030
+ host: { type: 'string', description: 'host name from ops_hosts' },
3031
+ path: { type: 'string', description: 'file path on the host' },
3032
+ action: { type: 'string', enum: ['list', 'diff', 'restore'], description: 'defaults to list' },
3033
+ backup: { type: 'string', description: 'backup file path for diff/restore' },
3034
+ },
3035
+ async execute(args = {}) {
3036
+ const cfg = pickHost(await loadHosts(), args.host)
3037
+ const path = String(args.path ?? '')
3038
+ if (args.action === 'diff') return fileDiff(cfg, path, String(args.backup ?? ''))
3039
+ if (args.action === 'restore') return fileRestore(cfg, path, String(args.backup ?? ''))
3040
+ return { host: cfg.name, backups: await fileHistory(cfg, path) }
3041
+ },
3042
+ }),
3043
+
3044
+ asTool({
3045
+ name: 'ops_channels',
3046
+ description: 'List, add, remove or test alert delivery channels (feishu / dingtalk / wecom / generic webhook).',
3047
+ parameters: {
3048
+ action: { type: 'string', enum: ['list', 'add', 'remove', 'test'], description: 'defaults to list' },
3049
+ type: { type: 'string', enum: ['feishu', 'dingtalk', 'wecom', 'webhook'] },
3050
+ url: { type: 'string', description: 'webhook URL' },
3051
+ name: { type: 'string', description: 'display name' },
3052
+ events: { type: 'array', items: { type: 'string' }, description: 'levels to send: critical / warning / info' },
3053
+ id: { type: 'string', description: 'channel id for remove/test' },
3054
+ },
3055
+ async execute(args = {}) {
3056
+ const all = await loadChannels()
3057
+ if ((args.action ?? 'list') === 'list') return { channels: all.channels }
3058
+ if (args.action === 'remove') {
3059
+ all.channels = all.channels.filter(item => item.id !== args.id)
3060
+ await saveChannels(all)
3061
+ return { channels: all.channels }
3062
+ }
3063
+ if (args.action === 'test') {
3064
+ const channel = all.channels.find(item => item.id === args.id)
3065
+ if (!channel) throw new Error('channel not found')
3066
+ return testChannel(channel)
3067
+ }
3068
+ const type = CHANNEL_TYPES.includes(args.type) ? args.type : 'webhook'
3069
+ if (!/^https?:\/\//.test(String(args.url || ''))) throw new Error('webhook url must start with http(s)://')
3070
+ const channel = {
3071
+ id: `c${Date.now().toString(36)}`,
3072
+ type,
3073
+ name: args.name || type,
3074
+ url: String(args.url),
3075
+ events: Array.isArray(args.events) && args.events.length ? args.events : ['critical', 'warning'],
3076
+ enabled: true,
3077
+ }
3078
+ all.channels = [...all.channels, channel]
3079
+ await saveChannels(all)
3080
+ return { channels: all.channels, channel }
3081
+ },
3082
+ }),
3083
+
3084
+ asTool({
3085
+ name: 'ops_deploy',
3086
+ description: 'Save and run a deploy job (git pull, build, restart, health check, auto rollback) on a host.',
3087
+ parameters: {
3088
+ host: { type: 'string', description: 'host name from ops_hosts' },
3089
+ action: { type: 'string', enum: ['list', 'save', 'remove', 'run'], description: 'defaults to list' },
3090
+ id: { type: 'string', description: 'job id for run/remove' },
3091
+ name: { type: 'string', description: 'job name' },
3092
+ jobDir: { type: 'string', description: 'project directory on the server' },
3093
+ repo: { type: 'string', description: 'git remote (optional, empty means no pull)' },
3094
+ branch: { type: 'string', description: 'branch, default origin/main' },
3095
+ build: { type: 'string', description: 'build command' },
3096
+ restart: { type: 'string', description: 'restart command' },
3097
+ health: { type: 'string', description: 'health check URL' },
3098
+ },
3099
+ async execute(args = {}) {
3100
+ const cfg = pickHost(await loadHosts(), args.host)
3101
+ const all = await loadJsonFile('deploys.json', {})
3102
+ const list = all[cfg.name] || []
3103
+ if ((args.action ?? 'list') === 'list') return { host: cfg.name, jobs: list }
3104
+ if (args.action === 'remove') {
3105
+ all[cfg.name] = list.filter(item => item.id !== args.id)
3106
+ await saveJsonFile('deploys.json', all)
3107
+ return { host: cfg.name, jobs: all[cfg.name] }
3108
+ }
3109
+ if (args.action === 'save') {
3110
+ const job = { id: args.id || `d${Date.now().toString(36)}`, name: args.name || '发布', dir: args.jobDir, repo: args.repo || '', branch: args.branch || 'origin/main', build: args.build || '', restart: args.restart || '', health: args.health || '', rollback: true }
3111
+ all[cfg.name] = args.id ? list.map(item => item.id === args.id ? { ...item, ...job } : item) : [...list, job]
3112
+ await saveJsonFile('deploys.json', all)
3113
+ return { host: cfg.name, jobs: all[cfg.name], job }
3114
+ }
3115
+ const job = list.find(item => item.id === args.id)
3116
+ if (!job) throw new Error('deploy job not found')
3117
+ return runDeploy(cfg, job)
3118
+ },
3119
+ }),
3120
+
3121
+ asTool({
3122
+ name: 'ops_monitors',
3123
+ description:
3124
+ 'List, add, remove or test service monitors on a host. Types: http (URL), port (host:port), '
3125
+ + 'process (command pattern), service (systemd unit).',
3126
+ parameters: {
3127
+ host: { type: 'string', description: 'host name from ops_hosts' },
3128
+ action: { type: 'string', enum: ['list', 'add', 'remove', 'test'], description: 'defaults to list' },
3129
+ type: { type: 'string', enum: ['http', 'port', 'process', 'service', 'script'], description: 'with action=add' },
3130
+ language: { type: 'string', enum: ['shell', 'python', 'js'], description: 'with type=script' },
3131
+ script: { type: 'string', description: 'with type=script: the script body' },
3132
+ target: { type: 'string', description: 'URL, host:port, process pattern or unit name' },
3133
+ label: { type: 'string', description: 'short display name' },
3134
+ intervalMinutes: { type: 'number', description: 'check interval; defaults to 5' },
3135
+ id: { type: 'string', description: 'with action=remove or test' },
3136
+ },
3137
+ async execute(args = {}) {
3138
+ const cfg = pickHost(await loadHosts(), args.host)
3139
+ const all = await loadMonitors()
3140
+ const list = all[cfg.name] || []
3141
+ if ((args.action ?? 'list') === 'list') return { host: cfg.name, monitors: list }
3142
+ if (args.action === 'remove') {
3143
+ all[cfg.name] = list.filter(item => item.id !== args.id)
3144
+ await saveMonitors(all)
3145
+ return { host: cfg.name, monitors: all[cfg.name] }
3146
+ }
3147
+ if (args.action === 'test') {
3148
+ const monitor = list.find(item => item.id === args.id)
3149
+ if (!monitor) throw new Error('monitor not found')
3150
+ const result = await runMonitor(cfg, monitor)
3151
+ return { host: cfg.name, id: monitor.id, result }
3152
+ }
3153
+ const monitor = {
3154
+ id: `m${Date.now().toString(36)}`,
3155
+ type: ['http', 'port', 'process', 'service', 'script'].includes(args.type) ? args.type : 'http',
3156
+ target: String(args.target ?? '').trim(),
3157
+ label: String(args.label ?? '').trim(),
3158
+ intervalMinutes: Math.max(1, Math.min(Number(args.intervalMinutes) || 5, 1440)),
3159
+ createdAt: new Date().toISOString(),
3160
+ ...(['shell', 'python', 'js'].includes(args.language) ? { language: args.language } : {}),
3161
+ ...(args.script ? { script: String(args.script).slice(0, 4000) } : {}),
3162
+ }
3163
+ if (monitor.type === 'script' ? !monitor.script : !monitor.target) {
3164
+ throw new Error(monitor.type === 'script' ? 'script is required' : 'target is required')
3165
+ }
3166
+ const result = await runMonitor(cfg, monitor)
3167
+ monitor.last = result
3168
+ monitor.lastOk = result.ok
3169
+ all[cfg.name] = [...list, monitor]
3170
+ await saveMonitors(all)
3171
+ return { host: cfg.name, monitor, result }
3172
+ },
3173
+ }),
3174
+
3175
+ asTool({
3176
+ name: 'ops_ai_models',
3177
+ description: 'List the providers and models the ops AI can use, plus which one is currently selected.',
3178
+ parameters: {},
3179
+ async execute() {
3180
+ const ctx = hostCtx
3181
+ const llm = ctx ? (typeof ctx.get === 'function' ? (ctx.get('llm') ?? ctx.llm) : ctx.llm) : null
3182
+ const defaults = ctx ? (typeof ctx.get === 'function' ? (ctx.get('agentDefaultModel') ?? ctx.agentDefaultModel) : ctx.agentDefaultModel) : null
3183
+ const config = await loadConfig()
3184
+ return {
3185
+ providers: await collectModels(llm),
3186
+ defaultSelection: defaults?.currentSelection?.() ?? null,
3187
+ config: { aiEnabled: config.aiEnabled !== false, aiProvider: config.aiProvider || '', aiModel: config.aiModel || '' },
3188
+ }
3189
+ },
3190
+ }),
3191
+
3192
+ asTool({
3193
+ name: 'ops_ask',
3194
+ description:
3195
+ 'Ask a plain-language question about a host. The model runs read-only commands itself and returns a short answer, '
3196
+ + 'plus the commands it ran. State-changing commands are returned as needsConfirm instead of executed.',
3197
+ parameters: {
3198
+ host: { type: 'string', description: 'host name from ops_hosts' },
3199
+ question: { type: 'string', description: 'what the user asked, e.g. mysql 运行了吗' },
3200
+ },
3201
+ async execute(args = {}) {
3202
+ const cfg = pickHost(await loadHosts(), args.host)
3203
+ return askAboutHost(cfg, String(args.question ?? ''))
3204
+ },
3205
+ }),
3206
+
3207
+ asTool({
3208
+ name: 'ops_ai_command',
3209
+ description: 'Turn a plain-language ops intent into ONE shell command for a host (no execution).',
3210
+ parameters: {
3211
+ host: { type: 'string', description: 'host name from ops_hosts' },
3212
+ intent: { type: 'string', description: 'what the user wants, in natural language' },
3213
+ },
3214
+ async execute(args = {}) {
3215
+ const cfg = pickHost(await loadHosts(), args.host)
3216
+ return aiCommand(cfg, String(args.intent ?? ''))
3217
+ },
3218
+ }),
3219
+
3220
+ asTool({
3221
+ name: 'ops_diagnose',
3222
+ description:
3223
+ 'Plain-language diagnosis of one host: disk, memory, failed services, web ports and app state, '
3224
+ + 'with suggested next actions. Optionally pass the user question to focus the checks.',
3225
+ parameters: {
3226
+ host: { type: 'string', description: 'host name from ops_hosts' },
3227
+ question: { type: 'string', description: 'what the user asked, e.g. 网站为什么打不开' },
3228
+ },
3229
+ async execute(args = {}) {
3230
+ const cfg = pickHost(await loadHosts(), args.host)
3231
+ return diagnose(cfg, String(args.question ?? ''))
3232
+ },
3233
+ }),
3234
+
3235
+ asTool({
3236
+ name: 'ops_files',
3237
+ description: 'List one directory on a host with sizes and mtimes.',
3238
+ parameters: {
3239
+ host: { type: 'string', description: 'host name from ops_hosts' },
3240
+ path: { type: 'string', description: 'absolute directory path; defaults to /' },
3241
+ },
3242
+ async execute(args = {}) {
3243
+ const cfg = pickHost(await loadHosts(), args.host)
3244
+ return listDir(cfg, String(args.path ?? '/'))
3245
+ },
3246
+ }),
3247
+
3248
+ asTool({
3249
+ name: 'ops_disk',
3250
+ description: 'Directory sizes one level below a path, largest first. Use it to find what filled the disk.',
3251
+ parameters: {
3252
+ host: { type: 'string', description: 'host name from ops_hosts' },
3253
+ path: { type: 'string', description: 'absolute path; defaults to /' },
3254
+ },
3255
+ async execute(args = {}) {
3256
+ const cfg = pickHost(await loadHosts(), args.host)
3257
+ return diskUsage(cfg, String(args.path ?? '/'))
3258
+ },
3259
+ }),
3260
+
3261
+ asTool({
3262
+ name: 'ops_ps',
3263
+ description: 'Top processes on a host by CPU or memory.',
3264
+ parameters: {
3265
+ host: { type: 'string', description: 'host name from ops_hosts' },
3266
+ sort: { type: 'string', enum: ['cpu', 'mem'], description: 'sort key; defaults to cpu' },
3267
+ },
3268
+ async execute(args = {}) {
3269
+ const cfg = pickHost(await loadHosts(), args.host)
3270
+ return processList(cfg, args.sort === 'mem' ? 'mem' : 'cpu')
3271
+ },
3272
+ }),
3273
+
3274
+ asTool({
3275
+ name: 'ops_kill',
3276
+ description: 'Send a signal (TERM by default, KILL when asked) to one pid. Requires confirm=true.',
3277
+ parameters: {
3278
+ host: { type: 'string', description: 'host name from ops_hosts' },
3279
+ pid: { type: 'number', description: 'process id' },
3280
+ signal: { type: 'string', enum: ['TERM', 'KILL', 'HUP'], description: 'signal; defaults to TERM' },
3281
+ confirm: { type: 'boolean', description: 'must be true' },
3282
+ },
3283
+ async execute(args = {}) {
3284
+ if (args.confirm !== true) throw new Error('killing a process needs confirm=true')
3285
+ const cfg = pickHost(await loadHosts(), args.host)
3286
+ return killProcess(cfg, args.pid, args.signal ?? 'TERM')
3287
+ },
3288
+ }),
3289
+
3290
+ asTool({
3291
+ name: 'ops_logs',
3292
+ description: 'Last N lines from a systemd unit or a log file on a host. Use source "nginx.service" or "file:/var/log/nginx/error.log".',
3293
+ parameters: {
3294
+ host: { type: 'string', description: 'host name from ops_hosts' },
3295
+ source: { type: 'string', description: 'unit name, or file:/absolute/path' },
3296
+ lines: { type: 'number', description: 'line count; defaults to 200' },
3297
+ },
3298
+ async execute(args = {}) {
3299
+ const cfg = pickHost(await loadHosts(), args.host)
3300
+ return tailLog(cfg, String(args.source ?? ''), args.lines ?? 200)
3301
+ },
3302
+ }),
3303
+
3304
+ asTool({
3305
+ name: 'ops_ssl',
3306
+ description: 'Check the TLS certificate a host serves for a domain: subject, issuer, expiry and days left.',
3307
+ parameters: {
3308
+ host: { type: 'string', description: 'host name from ops_hosts' },
3309
+ domain: { type: 'string', description: 'domain to check, e.g. example.com' },
3310
+ },
3311
+ async execute(args = {}) {
3312
+ const cfg = pickHost(await loadHosts(), args.host)
3313
+ return sslCheck(cfg, String(args.domain ?? ''))
3314
+ },
3315
+ }),
3316
+
3317
+ asTool({
3318
+ name: 'ops_config_file',
3319
+ description: 'Read one configuration file from a host (nginx, redis, my.cnf, systemd units, /opt).',
3320
+ parameters: {
3321
+ host: { type: 'string', description: 'host name from ops_hosts' },
3322
+ path: { type: 'string', description: 'absolute path inside the allowed config area' },
3323
+ },
3324
+ async execute(args = {}) {
3325
+ const cfg = pickHost(await loadHosts(), args.host)
3326
+ return readRemoteFile(cfg, String(args.path ?? ''))
3327
+ },
3328
+ }),
3329
+
3330
+ asTool({
3331
+ name: 'ops_save_config',
3332
+ description: 'Write one configuration file on a host after backing it up. Requires confirm=true.',
3333
+ parameters: {
3334
+ host: { type: 'string', description: 'host name from ops_hosts' },
3335
+ path: { type: 'string', description: 'absolute path inside the allowed config area' },
3336
+ content: { type: 'string', description: 'complete new file content' },
3337
+ confirm: { type: 'boolean', description: 'must be true' },
3338
+ },
3339
+ async execute(args = {}) {
3340
+ if (args.confirm !== true) throw new Error('writing a config needs confirm=true')
3341
+ const cfg = pickHost(await loadHosts(), args.host)
3342
+ return writeRemoteFile(cfg, String(args.path ?? ''), String(args.content ?? ''))
3343
+ },
3344
+ }),
3345
+
3346
+ asTool({
3347
+ name: 'ops_ssh_test',
3348
+ description: 'Test the SSH connection to one host and return ok, latency in ms, auth kind and the failure reason.',
3349
+ parameters: { host: { type: 'string', description: 'host name from ops_hosts' } },
3350
+ async execute(args = {}) {
3351
+ const cfg = pickHost(await loadHosts(), args.host)
3352
+ return testConnection(cfg)
3353
+ },
3354
+ }),
3355
+
3356
+ asTool({
3357
+ name: 'ops_ssh_install_key',
3358
+ description: 'Install this machine\'s ~/.ssh/id_ed25519.pub on a host (uses the stored password when present), so later connections need no password.',
3359
+ parameters: { host: { type: 'string', description: 'host name from ops_hosts' } },
3360
+ async execute(args = {}) {
3361
+ const cfg = pickHost(await loadHosts(), args.host)
3362
+ return installKey(cfg)
3363
+ },
3364
+ }),
3365
+
3366
+ asTool({
3367
+ name: 'ops_cleanup',
3368
+ description:
3369
+ 'Safe disk cleanup on one host: vacuum the systemd journal, truncate rotated messages/secure logs, '
3370
+ + 'delete compressed logs older than 7 days. Returns the disk percentage before and after.',
3371
+ parameters: {
3372
+ host: { type: 'string', description: 'host name from ops_hosts; defaults to the default host' },
3373
+ confirm: { type: 'boolean', description: 'must be true: this deletes log data' },
3374
+ },
3375
+ async execute(args = {}) {
3376
+ if (args.confirm !== true) throw new Error('cleanup deletes log data; rerun with confirm=true')
3377
+ const cfg = pickHost(await loadHosts(), args.host)
3378
+ return cleanupDisk(cfg)
3379
+ },
3380
+ }),
3381
+
3382
+ asTool({
3383
+ name: 'ops_batch',
3384
+ description:
3385
+ 'Run one command on several configured hosts in parallel and return a bounded result per host. '
3386
+ + 'Omit hosts to target every host. Destructive commands need confirm=true.',
3387
+ parameters: {
3388
+ command: { type: 'string', description: 'shell command to run on each host' },
3389
+ hosts: { type: 'array', items: { type: 'string' }, description: 'host names; omit for all hosts' },
3390
+ confirm: { type: 'boolean', description: 'required for destructive commands' },
3391
+ },
3392
+ async execute(args = {}) {
3393
+ const command = String(args.command ?? '').trim()
3394
+ if (!command) throw new Error('command is required')
3395
+ if (looksDangerous(command) && args.confirm !== true) {
3396
+ throw new Error('command looks destructive; rerun with confirm=true')
3397
+ }
3398
+ return batchRun(command, Array.isArray(args.hosts) ? args.hosts : undefined)
3399
+ },
3400
+ }),
3401
+
3402
+ asTool({
3403
+ name: 'ops_run',
3404
+ description:
3405
+ 'Run one shell command on a configured host over SSH and return stdout/stderr/exit code. '
3406
+ + 'Destructive commands (rm -rf /, mkfs, dd to a device, shutdown/reboot) need confirm=true.',
3407
+ parameters: {
3408
+ host: { type: 'string', description: 'host name from ops_hosts; defaults to the default host' },
3409
+ command: { type: 'string', description: 'shell command to run remotely' },
3410
+ timeoutMs: { type: 'number', description: 'timeout in milliseconds; defaults to 20000' },
3411
+ confirm: { type: 'boolean', description: 'required for destructive commands' },
3412
+ },
3413
+ async execute(args = {}) {
3414
+ const command = String(args.command ?? '').trim()
3415
+ if (!command) throw new Error('command is required')
3416
+ if (looksDangerous(command) && args.confirm !== true) {
3417
+ throw new Error('command looks destructive; rerun with confirm=true to execute it')
3418
+ }
3419
+ const cfg = pickHost(await loadHosts(), args.host)
3420
+ const result = await ssh(cfg, command, Number(args.timeoutMs ?? 20_000))
3421
+ return { host: cfg.name, command, ...summary(result) }
3422
+ },
3423
+ }),
3424
+
3425
+ asTool({
3426
+ name: 'ops_service',
3427
+ description:
3428
+ 'systemd service status, logs or lifecycle on a configured host. '
3429
+ + 'start/stop/restart need confirm=true.',
3430
+ parameters: {
3431
+ host: { type: 'string', description: 'host name from ops_hosts; defaults to the default host' },
3432
+ service: { type: 'string', description: 'unit name, such as nginx or my-api.service' },
3433
+ action: { type: 'string', enum: ['status', 'logs', 'start', 'stop', 'restart'], description: 'defaults to status' },
3434
+ lines: { type: 'number', description: 'with action=logs: how many journal lines; defaults to 50' },
3435
+ confirm: { type: 'boolean', description: 'required for start/stop/restart' },
3436
+ },
3437
+ async execute(args = {}) {
3438
+ const service = String(args.service ?? '').trim()
3439
+ if (!service) throw new Error('service is required')
3440
+ const action = args.action ?? 'status'
3441
+ if (['start', 'stop', 'restart'].includes(action) && args.confirm !== true) {
3442
+ throw new Error(`action=${action} changes state; rerun with confirm=true`)
3443
+ }
3444
+ const cfg = pickHost(await loadHosts(), args.host)
3445
+ const prefix = cfg.sudo ? 'sudo -n ' : ''
3446
+ const command = action === 'logs'
3447
+ ? `${prefix}journalctl -u ${service} -n ${Number(args.lines ?? 50)} --no-pager`
3448
+ : `${prefix}systemctl ${action} ${service}`
3449
+ const result = await ssh(cfg, command, 30_000)
3450
+ return { host: cfg.name, service, action, ...summary(result) }
3451
+ },
3452
+ }),
3453
+
3454
+ asTool({
3455
+ name: 'ops_docker',
3456
+ description:
3457
+ 'Docker overview on a configured host: containers, logs, inspect, or restart. '
3458
+ + 'restart needs confirm=true. Uses the host Docker socket; no Docker SDK.',
3459
+ parameters: {
3460
+ host: { type: 'string', description: 'host name from ops_hosts; defaults to the default host' },
3461
+ action: { type: 'string', enum: ['ps', 'logs', 'inspect', 'restart'], description: 'defaults to ps' },
3462
+ container: { type: 'string', description: 'container name or id; required except for ps' },
3463
+ lines: { type: 'number', description: 'with action=logs: tail lines; defaults to 80' },
3464
+ confirm: { type: 'boolean', description: 'required for restart' },
3465
+ },
3466
+ async execute(args = {}) {
3467
+ const action = args.action ?? 'ps'
3468
+ const container = String(args.container ?? '').trim()
3469
+ if (action !== 'ps' && !container) throw new Error('container is required')
3470
+ if (action === 'restart' && args.confirm !== true) {
3471
+ throw new Error('action=restart changes state; rerun with confirm=true')
3472
+ }
3473
+ const cfg = pickHost(await loadHosts(), args.host)
3474
+ const prefix = cfg.sudo ? 'sudo -n ' : ''
3475
+ const quoted = container.replace(/[^A-Za-z0-9_.-]/g, '')
3476
+ const command = {
3477
+ ps: `${prefix}docker ps -a --format "{{.Names}}\\t{{.Status}}\\t{{.Image}}"`,
3478
+ logs: `${prefix}docker logs --tail ${Number(args.lines ?? 80)} ${quoted}`,
3479
+ inspect: `${prefix}docker inspect --format '{{json .State}}' ${quoted}`,
3480
+ restart: `${prefix}docker restart ${quoted}`,
3481
+ }[action]
3482
+ const result = await ssh(cfg, command, 30_000)
3483
+ return { host: cfg.name, action, container: container || null, ...summary(result) }
3484
+ },
3485
+ }),
3486
+ ]
3487
+
3488
+ for (const tool of tools) {
3489
+ ctx.effect(() => ctx.tools.register(tool))
3490
+ }
3491
+
3492
+ ctx.inject(['webServer'], (inner) => {
3493
+ inner.effect(() => inner.webServer.register({
3494
+ kind: 'prefix',
3495
+ path: '/ops-kit/api',
3496
+ handler: createApiHandler({ connection: typeof ctx.get === 'function' ? ctx.get('connection') : undefined }),
3497
+ }))
3498
+ })
3499
+
3500
+ ctx.effect(() => () => {
3501
+ for (const id of [...termSessions.keys()]) terminalClose(id)
3502
+ })
3503
+
3504
+ ctx.effect(() => {
3505
+ const tick = () => {
3506
+ void runScheduledPass().catch(() => {})
3507
+ void runMetricsPass().catch(() => {})
3508
+ void runMonitorPass().catch(() => {})
3509
+ void checkCertAlerts().catch(() => {})
3510
+ }
3511
+ const previous = globalThis.__opsKitScheduler
3512
+ if (previous) { clearInterval(previous.handle); clearTimeout(previous.first) }
3513
+ const handle = setInterval(tick, 60_000)
3514
+ handle.unref?.()
3515
+ const first = setTimeout(tick, 20_000)
3516
+ first.unref?.()
3517
+ globalThis.__opsKitScheduler = { handle, first }
3518
+ return () => {
3519
+ clearInterval(handle)
3520
+ clearTimeout(first)
3521
+ if (globalThis.__opsKitScheduler?.handle === handle) globalThis.__opsKitScheduler = null
3522
+ }
3523
+ })
3524
+ }