dsh-ssh-hub 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +271 -2
  3. package/cordis.patch.yml +16 -0
  4. package/icon.svg +3 -0
  5. package/lib/client.js +13975 -0
  6. package/lib/index.js +6908 -0
  7. package/lib/types/activity/history.d.ts +50 -0
  8. package/lib/types/alerting/notify.d.ts +89 -0
  9. package/lib/types/alerting/prompt-summary.d.ts +28 -0
  10. package/lib/types/alerting/rules.d.ts +135 -0
  11. package/lib/types/alerting/tools.d.ts +30 -0
  12. package/lib/types/audit/audit-log.d.ts +84 -0
  13. package/lib/types/audit/recorder.d.ts +50 -0
  14. package/lib/types/client/api.d.ts +222 -0
  15. package/lib/types/client/index.d.ts +45 -0
  16. package/lib/types/client/locales.d.ts +319 -0
  17. package/lib/types/client/native-panel.d.ts +70 -0
  18. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  19. package/lib/types/client/panel/DeployTab.d.ts +10 -0
  20. package/lib/types/client/panel/FleetTab.d.ts +10 -0
  21. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  22. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  23. package/lib/types/client/panel/LogsTab.d.ts +10 -0
  24. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  25. package/lib/types/client/panel/TerminalTab.d.ts +27 -0
  26. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  27. package/lib/types/client/panel/TunnelEditDialog.d.ts +15 -0
  28. package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
  29. package/lib/types/client/panel/controller.d.ts +253 -0
  30. package/lib/types/client/panel/helpers.d.ts +45 -0
  31. package/lib/types/client/panel/tabs.d.ts +62 -0
  32. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  33. package/lib/types/client/settings-binding.d.ts +71 -0
  34. package/lib/types/deploy/orchestrator.d.ts +158 -0
  35. package/lib/types/deploy/tools.d.ts +14 -0
  36. package/lib/types/dsh-home.d.ts +16 -0
  37. package/lib/types/engine/cluster.d.ts +19 -0
  38. package/lib/types/engine/connection-pool.d.ts +183 -0
  39. package/lib/types/engine/proxy-command.d.ts +36 -0
  40. package/lib/types/engine/pty.d.ts +32 -0
  41. package/lib/types/engine/sftp.d.ts +20 -0
  42. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  43. package/lib/types/engine/tunnel-discovery.d.ts +89 -0
  44. package/lib/types/engine/tunnel-remarks.d.ts +49 -0
  45. package/lib/types/engine/tunnel.d.ts +76 -0
  46. package/lib/types/engine.d.ts +103 -0
  47. package/lib/types/http.d.ts +59 -0
  48. package/lib/types/index.d.ts +128 -0
  49. package/lib/types/inspect/checks.d.ts +118 -0
  50. package/lib/types/inspect/inspection.d.ts +111 -0
  51. package/lib/types/inspect/tools.d.ts +50 -0
  52. package/lib/types/logs/search.d.ts +131 -0
  53. package/lib/types/logs/tools.d.ts +6 -0
  54. package/lib/types/loopback.d.ts +64 -0
  55. package/lib/types/monitor/loop.d.ts +133 -0
  56. package/lib/types/monitor/metrics.d.ts +151 -0
  57. package/lib/types/mount-once.d.ts +55 -0
  58. package/lib/types/protocol.d.ts +524 -0
  59. package/lib/types/routes.d.ts +82 -0
  60. package/lib/types/security/known-hosts.d.ts +153 -0
  61. package/lib/types/security/master-secret.d.ts +157 -0
  62. package/lib/types/security/redact.d.ts +44 -0
  63. package/lib/types/security/secrets.d.ts +70 -0
  64. package/lib/types/ssh-config.d.ts +42 -0
  65. package/lib/types/store.d.ts +183 -0
  66. package/lib/types/tool-surface.d.ts +72 -0
  67. package/lib/types/tools.d.ts +56 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +126 -6
  71. package/src/activity/history.ts +117 -0
  72. package/src/alerting/notify.ts +212 -0
  73. package/src/alerting/prompt-summary.ts +71 -0
  74. package/src/alerting/rules.ts +281 -0
  75. package/src/alerting/tools.ts +263 -0
  76. package/src/audit/audit-log.ts +199 -0
  77. package/src/audit/recorder.ts +73 -0
  78. package/src/client/api.ts +782 -0
  79. package/src/client/css-modules.d.ts +5 -0
  80. package/src/client/index.ts +150 -0
  81. package/src/client/locales.ts +654 -0
  82. package/src/client/native-panel.tsx +141 -0
  83. package/src/client/panel/ClusterTab.tsx +141 -0
  84. package/src/client/panel/DeployTab.tsx +314 -0
  85. package/src/client/panel/FleetTab.tsx +494 -0
  86. package/src/client/panel/HostFormDialog.tsx +289 -0
  87. package/src/client/panel/HostsTab.tsx +395 -0
  88. package/src/client/panel/LogsTab.tsx +208 -0
  89. package/src/client/panel/SshPanel.tsx +105 -0
  90. package/src/client/panel/TerminalTab.tsx +550 -0
  91. package/src/client/panel/TransferTab.tsx +238 -0
  92. package/src/client/panel/TunnelEditDialog.tsx +174 -0
  93. package/src/client/panel/TunnelsTab.tsx +328 -0
  94. package/src/client/panel/controller.ts +507 -0
  95. package/src/client/panel/helpers.ts +84 -0
  96. package/src/client/panel/panel.module.css +1734 -0
  97. package/src/client/panel/tabs.ts +52 -0
  98. package/src/client/panel/xterm.css.ts +2 -0
  99. package/src/client/settings-binding.ts +184 -0
  100. package/src/deploy/orchestrator.ts +326 -0
  101. package/src/deploy/tools.ts +225 -0
  102. package/src/dsh-home.ts +42 -0
  103. package/src/engine/cluster.ts +60 -0
  104. package/src/engine/connection-pool.ts +721 -0
  105. package/src/engine/proxy-command.ts +248 -0
  106. package/src/engine/pty.ts +78 -0
  107. package/src/engine/sftp.ts +229 -0
  108. package/src/engine/terminal-sessions.ts +280 -0
  109. package/src/engine/tunnel-discovery.ts +353 -0
  110. package/src/engine/tunnel-remarks.ts +120 -0
  111. package/src/engine/tunnel.ts +300 -0
  112. package/src/engine.ts +195 -0
  113. package/src/http.ts +127 -0
  114. package/src/index.ts +690 -0
  115. package/src/inspect/checks.ts +251 -0
  116. package/src/inspect/inspection.ts +321 -0
  117. package/src/inspect/tools.ts +366 -0
  118. package/src/logs/search.ts +251 -0
  119. package/src/logs/tools.ts +160 -0
  120. package/src/loopback.ts +119 -0
  121. package/src/monitor/loop.ts +265 -0
  122. package/src/monitor/metrics.ts +333 -0
  123. package/src/mount-once.ts +142 -0
  124. package/src/protocol.ts +534 -0
  125. package/src/routes.ts +998 -0
  126. package/src/security/known-hosts.ts +342 -0
  127. package/src/security/master-secret.ts +334 -0
  128. package/src/security/redact.ts +119 -0
  129. package/src/security/secrets.ts +152 -0
  130. package/src/ssh-config.ts +182 -0
  131. package/src/store.ts +757 -0
  132. package/src/tool-surface.ts +96 -0
  133. package/src/tools.ts +550 -0
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Family-shared tool-surface conventions for the packages that register
3
+ * model-facing tools.
4
+ *
5
+ * One home for the prompt-section placement and the visibility gate this
6
+ * family previously restated per package.
7
+ *
8
+ * Modelled on the official tool packages:
9
+ * - `@deepseek-ai/dsh-tool-subagent` renders its section through
10
+ * `tools.get(name, context.scope) === undefined ? '' : text`, so guidance
11
+ * disappears together with a restricted tool.
12
+ * - 21 of the 22 official tool packages register their tools GLOBALLY and gate
13
+ * them with a setting, not per agent. Only the Agent Teams tool package —
14
+ * whose tools belong to one membership — installs into each `agent.ctx`.
15
+ * This family follows the majority: registration stays global so the
16
+ * registry's per-scope `restrict()` mask (which filters inherited global
17
+ * tools and REJECTS scope-local names) can still withhold these tools.
18
+ *
19
+ * Structural types only: this copy lands in packages that do not all depend on
20
+ * the same SDK service packages.
21
+ */
22
+ /**
23
+ * Prompt-section order for each package's tool guidance.
24
+ *
25
+ * These sit in the family band between the deployment persona and the SDK's
26
+ * `PLAN_POLICY` (500). Values are owned here rather than written per package so
27
+ * the host plugins whose guidance shares one prompt cannot drift into an
28
+ * accidental tie.
29
+ */
30
+ export declare const PLUGIN_TOOL_SECTION_ORDERS: {
31
+ readonly ssh: 150;
32
+ readonly 'task-board': 200;
33
+ readonly agents: 220;
34
+ };
35
+ /** One plugin id keyed by {@link PLUGIN_TOOL_SECTION_ORDERS}. */
36
+ export type PluginToolSectionId = keyof typeof PLUGIN_TOOL_SECTION_ORDERS;
37
+ /**
38
+ * Order of an external provider extension's own guidance section, right after
39
+ * the band of the plugin it extends.
40
+ *
41
+ * An extension names itself, not the plugin it plugs into, so its order stays
42
+ * out of {@link PLUGIN_TOOL_SECTION_ORDERS}: every package's copy of this module
43
+ * then carries no provider id. The slot still has one owner and cannot collide
44
+ * with a host plugin's band.
45
+ */
46
+ export declare const EXTENSION_TOOL_SECTION_ORDER = 210;
47
+ /**
48
+ * The scoped tool lookup a section provider needs: the registry read for one
49
+ * assembly's scope. Matches `ctx.tools.get(name, scope)`.
50
+ */
51
+ export interface ScopedToolLookup {
52
+ get(name: string, scope?: unknown): unknown;
53
+ }
54
+ /** One assembly context carrying the scope the section is rendered for. */
55
+ export interface SectionScopeContext {
56
+ scope?: unknown;
57
+ }
58
+ /**
59
+ * Build a section provider that renders \`text\` only while at least one of
60
+ * \`toolNames\` is visible to the rendering scope.
61
+ *
62
+ * The native convention: a tool that a restriction, a preset, or a missing
63
+ * registry removed must not leave guidance behind telling the model to call it.
64
+ * An unreadable registry renders the text unchanged — guidance that outlives a
65
+ * momentary read failure is recoverable; guidance for a tool that is gone is
66
+ * not.
67
+ * @param tools - the scoped tool registry, when the deployment serves one.
68
+ * @param toolNames - registered names the guidance describes.
69
+ * @param text - the guidance rendered while they are reachable.
70
+ * @returns the section text provider.
71
+ */
72
+ export declare function visibleToolText(tools: ScopedToolLookup | undefined, toolNames: readonly string[], text: string): (context: SectionScopeContext) => string;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Agent tools: the DSH-native counterpart of ssh-skill's CLI. Every tool
3
+ * talks to the same engine the web UI uses, so a host configured in the GUI
4
+ * is immediately operable by any agent, and vice versa.
5
+ */
6
+ import type { SshEngine } from './engine.ts';
7
+ import type { ExecResult, SshAuthKind, SshHostSummary } from './protocol.ts';
8
+ import type { AuditRecorder } from './audit/recorder.ts';
9
+ /**
10
+ * One host row for the agent surface. The ProxyCommand STRING is deliberately
11
+ * projected to a boolean: the command may embed credentials for a bastion
12
+ * client, and the model only needs to know that the host goes through one.
13
+ */
14
+ export interface AgentHostRow {
15
+ alias: string;
16
+ host: string;
17
+ port: number;
18
+ user: string;
19
+ auth: SshAuthKind;
20
+ keyReady: boolean;
21
+ proxyJump: string[];
22
+ proxyCommandConfigured: boolean;
23
+ forwardAgent: boolean;
24
+ description?: string;
25
+ environment?: string;
26
+ tags: string[];
27
+ location?: string;
28
+ createdAt: number;
29
+ updatedAt: number;
30
+ }
31
+ /** Project one summary onto the agent-facing row shape. */
32
+ export declare function toAgentHostRow(host: SshHostSummary): AgentHostRow;
33
+ /** The host-list tool. */
34
+ export declare function sshListTool(engine: SshEngine): import("@deepseek-ai/dsh-tools").ToolDefinition;
35
+ /** The command-execution tool. */
36
+ export declare function sshExecTool(engine: SshEngine, audit?: AuditRecorder): import("@deepseek-ai/dsh-tools").ToolDefinition;
37
+ /**
38
+ * Redact an exec result before it leaves the tool.
39
+ *
40
+ * The output becomes model context and, in DSH, part of the session log —
41
+ * so a secret printed by `env` would be written into a transcript that
42
+ * outlives the session. The redaction is a safety net, not a guarantee:
43
+ * the remote host may hold secrets in shapes this does not recognise.
44
+ *
45
+ * @param result - the raw exec result.
46
+ * @returns the redacted result.
47
+ */
48
+ export declare function redactExecResult(result: ExecResult): ExecResult;
49
+ /** The upload tool. */
50
+ export declare function sshUploadTool(engine: SshEngine, audit?: AuditRecorder): import("@deepseek-ai/dsh-tools").ToolDefinition;
51
+ /** The download tool. */
52
+ export declare function sshDownloadTool(engine: SshEngine, audit?: AuditRecorder): import("@deepseek-ai/dsh-tools").ToolDefinition;
53
+ /** The tunnel tool. */
54
+ export declare function sshTunnelTool(engine: SshEngine, audit?: AuditRecorder): import("@deepseek-ai/dsh-tools").ToolDefinition;
55
+ /** The cluster tool. */
56
+ export declare function sshClusterTool(engine: SshEngine, audit?: AuditRecorder): import("@deepseek-ai/dsh-tools").ToolDefinition;
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "SSH terminal",
4
+ "description": "Run commands and transfer files on remote hosts."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "SSH 终端",
4
+ "description": "连远程主机执行命令并传文件"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,126 @@
1
- {
2
- "name": "dsh-ssh-hub",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dsh-ssh-hub",
3
+ "version": "0.2.0",
4
+ "description": "Server fleet operations hub for DeepSeek Harness: SSH transport (inherited from @linxin666/dsh-ssh) plus inspection, metrics/alerting, deployment orchestration, cross-host log search, credential hardening and audit trail.",
5
+ "icon": "./icon.svg",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/huanyu-a/dsh-ssh-hub.git"
10
+ },
11
+ "homepage": "https://github.com/huanyu-a/dsh-ssh-hub#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/huanyu-a/dsh-ssh-hub/issues"
14
+ },
15
+ "keywords": [
16
+ "dsh",
17
+ "deepseek-harness",
18
+ "dsh-plugin",
19
+ "ssh",
20
+ "fleet",
21
+ "inspection",
22
+ "alerting",
23
+ "deployment",
24
+ "sre",
25
+ "ops"
26
+ ],
27
+ "type": "module",
28
+ "main": "lib/index.js",
29
+ "types": "./lib/types/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./lib/types/index.d.ts",
33
+ "default": "./lib/index.js"
34
+ },
35
+ "./client": {
36
+ "types": "./lib/types/client/index.d.ts",
37
+ "default": "./lib/client.js"
38
+ },
39
+ "./src/*": "./src/*",
40
+ "./locale/en.json": "./locale/en.json",
41
+ "./locale/zh.json": "./locale/zh.json",
42
+ "./package.json": "./package.json"
43
+ },
44
+ "dsh": {
45
+ "engines": {
46
+ "dsh": ">=0.2.2-rc.3"
47
+ },
48
+ "bundle": {
49
+ "patch": "./cordis.patch.yml"
50
+ },
51
+ "client": {
52
+ "inject": [
53
+ "@deepseek-ai/dsh-client-locale",
54
+ "@deepseek-ai/dsh-client-ui-renderer",
55
+ "@deepseek-ai/dsh-client-ui-settings",
56
+ "@deepseek-ai/dsh-client-ui-layout"
57
+ ],
58
+ "platform": "web"
59
+ }
60
+ },
61
+ "scripts": {
62
+ "build": "npm run build:clean && npm run build:host && npm run build:client && npm run build:types",
63
+ "build:clean": "node -e \"require('node:fs').rmSync('lib',{recursive:true,force:true})\"",
64
+ "build:host": "node scripts/build-host.mjs",
65
+ "build:client": "node scripts/build-client.mjs",
66
+ "build:types": "tsc -p tsconfig.build.json",
67
+ "typecheck": "tsc --noEmit -p tsconfig.json",
68
+ "test": "vitest run",
69
+ "check": "npm run typecheck && npm run test && npm run build && npm run verify:client && npm run verify:contrast && npm run pack:check",
70
+ "verify:client": "node scripts/verify-client.mjs",
71
+ "verify:contrast": "node scripts/verify-contrast.mjs && node scripts/audit-text-contrast.mjs",
72
+ "preview": "node scripts/render-preview.mjs",
73
+ "pack:check": "node scripts/package-artifact.mjs",
74
+ "pack": "npm pack --pack-destination artifacts"
75
+ },
76
+ "engines": {
77
+ "node": "^22.19.0 || >=24"
78
+ },
79
+ "dependencies": {
80
+ "@deepseek-ai/schemastery": "^3.19.0",
81
+ "@xterm/addon-fit": "^0.11.0",
82
+ "@xterm/xterm": "^6.0.0",
83
+ "ssh2": "^1.17.0",
84
+ "ws": "^8.18.0"
85
+ },
86
+ "peerDependencies": {
87
+ "@deepseek-ai/dsh": ">=0.2.2-rc.3",
88
+ "react": "^18.2.0",
89
+ "react-dom": "^18.2.0"
90
+ },
91
+ "devDependencies": {
92
+ "@deepseek-ai/cordis": "^4.1.0",
93
+ "@deepseek-ai/dsh-client-locale": "^0.2.2-rc.3",
94
+ "@deepseek-ai/dsh-client-ui-layout": "^0.2.2-rc.3",
95
+ "@deepseek-ai/dsh-client-ui-renderer": "^0.2.2-rc.3",
96
+ "@deepseek-ai/dsh-client-ui-settings": "^0.2.2-rc.3",
97
+ "@deepseek-ai/dsh-client-ui-sidebar": "^0.2.2-rc.3",
98
+ "@deepseek-ai/dsh-client-ui-slots": "^0.2.2-rc.3",
99
+ "@deepseek-ai/dsh-host-webserver": "^0.2.2-rc.3",
100
+ "@deepseek-ai/dsh-llm": "^0.2.2-rc.3",
101
+ "@deepseek-ai/dsh-scope": "^0.2.2-rc.3",
102
+ "@deepseek-ai/dsh-settings": "^0.2.2-rc.3",
103
+ "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.3",
104
+ "@deepseek-ai/dsh-tools": "^0.2.2-rc.3",
105
+ "@types/node": "^22.20.0",
106
+ "@types/react": "~18.3.1",
107
+ "@types/react-dom": "~18.3.5",
108
+ "@types/ssh2": "^1.15.5",
109
+ "@types/ws": "^8.5.13",
110
+ "esbuild": "^0.25.0",
111
+ "typescript": "~5.7.2",
112
+ "vitest": "^4.0.0"
113
+ },
114
+ "allowScripts": {
115
+ "esbuild": true
116
+ },
117
+ "files": [
118
+ "lib/**/*.js",
119
+ "lib/**/*.d.ts",
120
+ "src",
121
+ "cordis.patch.yml",
122
+ "README.md",
123
+ "icon.svg",
124
+ "locale"
125
+ ]
126
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Activity history for the two surfaces that produce it: deployment runs and
3
+ * cross-host log searches.
4
+ *
5
+ * Both are append-only NDJSON files under the plugin's home, bounded the same
6
+ * way the metric tiers are: a hard cap on retained records, oldest dropped
7
+ * first. The panel reads them as history; nothing in the host half depends on
8
+ * them, so a missing or corrupt file degrades to "no history yet" rather than
9
+ * failing a route.
10
+ *
11
+ * Why persist at all: a deployment or a log search is an operator action with
12
+ * an outcome they need to look at *after* the panel has moved on. Keeping only
13
+ * the in-memory result would lose it on the next panel switch — and this is
14
+ * exactly the kind of record someone asks about a day later.
15
+ */
16
+
17
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
18
+ import { dirname, join } from 'node:path'
19
+
20
+ /** Records retained per history kind. */
21
+ const MAX_RECORDS = 100
22
+
23
+ /** One of the history files. */
24
+ export type HistoryKind = 'deploys' | 'logs'
25
+
26
+ /**
27
+ * Append-only JSON-lines history with a fixed retention window.
28
+ *
29
+ * Every write is a single `appendFileSync` of one line, so a crash mid-write
30
+ * can at worst truncate the newest record; `read()` skips unparsable lines
31
+ * instead of throwing, which keeps one bad line from hiding all the others.
32
+ */
33
+ export class ActivityHistory<T> {
34
+ private readonly file: string
35
+
36
+ /**
37
+ * @param root - the plugin's home directory.
38
+ * @param kind - which history file this instance owns.
39
+ */
40
+ constructor(root: string, private readonly kind: HistoryKind) {
41
+ this.file = join(root, `${kind}.jsonl`)
42
+ }
43
+
44
+ /** The file this history writes to. */
45
+ get path(): string {
46
+ return this.file
47
+ }
48
+
49
+ /**
50
+ * Append one record, trimming the file when it exceeds the cap.
51
+ * @param record - the record to store.
52
+ */
53
+ append(record: T): void {
54
+ try {
55
+ mkdirSync(dirname(this.file), { recursive: true })
56
+ appendFileSync(this.file, `${JSON.stringify(record)}\n`, 'utf8')
57
+ this.trim()
58
+ } catch {
59
+ // History is a convenience, never a precondition: a full disk must not
60
+ // turn a successful deployment into a failed request.
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Read the newest records first.
66
+ * @param limit - maximum records to return.
67
+ * @returns the records, newest first.
68
+ */
69
+ read(limit = 20): T[] {
70
+ if (!existsSync(this.file)) return []
71
+ let text: string
72
+ try {
73
+ text = readFileSync(this.file, 'utf8')
74
+ } catch {
75
+ return []
76
+ }
77
+ const records: T[] = []
78
+ for (const line of text.split('\n')) {
79
+ if (line.trim() === '') continue
80
+ try {
81
+ records.push(JSON.parse(line) as T)
82
+ } catch {
83
+ // A truncated trailing line is expected after a crash; skip it.
84
+ }
85
+ }
86
+ return records.slice(-Math.max(1, limit)).reverse()
87
+ }
88
+
89
+ /** Drop the oldest records once the file holds more than the cap. */
90
+ private trim(): void {
91
+ if (!existsSync(this.file)) return
92
+ let text: string
93
+ try {
94
+ text = readFileSync(this.file, 'utf8')
95
+ } catch {
96
+ return
97
+ }
98
+ const lines = text.split('\n').filter(line => line.trim() !== '')
99
+ if (lines.length <= MAX_RECORDS) return
100
+ try {
101
+ // Keep the newest records; rewriting is cheaper than an in-place edit
102
+ // and leaves a consistent file if it fails.
103
+ writeFileSync(this.file, `${lines.slice(-MAX_RECORDS).join('\n')}\n`, 'utf8')
104
+ } catch {
105
+ // Keep the larger file: retention is a courtesy, not a guarantee.
106
+ }
107
+ }
108
+
109
+ /** Forget every record (the panel's "clear history"). */
110
+ clear(): void {
111
+ try {
112
+ if (existsSync(this.file)) writeFileSync(this.file, '', 'utf8')
113
+ } catch {
114
+ // Same reasoning as append(): never fail a request over history.
115
+ }
116
+ }
117
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Outbound notification: a template-driven HTTP sender.
3
+ *
4
+ * A generic HTTP template with named placeholders covers Bark, Telegram,
5
+ * Lark/Feishu and WeCom without the plugin growing a dependency on each of
6
+ * them — the operator supplies the URL and the body shape, and the plugin
7
+ * substitutes the values.
8
+ *
9
+ * The template placeholders are the ones the operator actually reads:
10
+ * `#SERVER.NAME#`, `#SERVER.ALIAS#`, `#RULE.NAME#`, `#RULE.ID#`,
11
+ * `#VALUE#`, `#MESSAGE#`, `#STATE#`, `#TIME#`.
12
+ *
13
+ * An unknown placeholder is left AS IS rather than replaced with an empty
14
+ * string: a typo in a template must be visible, not silently blank.
15
+ */
16
+
17
+ import type { AlertNotification } from './rules.ts'
18
+
19
+ /** One notification channel. */
20
+ export interface NotifyChannel {
21
+ /** A stable name for the channel. */
22
+ id: string
23
+ /** The target URL. */
24
+ url: string
25
+ /** The HTTP method (default POST). */
26
+ method?: string
27
+ /** The body template, with placeholders. */
28
+ body?: string
29
+ /** Extra headers. */
30
+ headers?: Record<string, string>
31
+ /** The content type (default application/json). */
32
+ contentType?: string
33
+ }
34
+
35
+ /** The outcome of one delivery attempt. */
36
+ export interface NotifyOutcome {
37
+ channelId: string
38
+ ok: boolean
39
+ /** The HTTP status, when a response arrived. */
40
+ status?: number
41
+ /** The error message, when the attempt failed. */
42
+ error?: string
43
+ }
44
+
45
+ /**
46
+ * The placeholders a template may use.
47
+ *
48
+ * @param notification - the event to describe.
49
+ * @param extra - additional key/value pairs (a rule title, a value).
50
+ * @returns the placeholder map.
51
+ */
52
+ export function placeholders(
53
+ notification: AlertNotification,
54
+ extra: Record<string, string> = {},
55
+ ): Record<string, string> {
56
+ return {
57
+ '#SERVER.ALIAS#': notification.alias,
58
+ '#SERVER.NAME#': extra.serverName ?? notification.alias,
59
+ '#RULE.ID#': notification.ruleId,
60
+ '#RULE.NAME#': extra.ruleName ?? notification.ruleId,
61
+ '#VALUE#': notification.value,
62
+ '#STATE#': notification.kind === 'trigger' ? '触发' : '恢复',
63
+ '#MESSAGE#': extra.message ?? defaultMessage(notification),
64
+ '#TIME#': new Date(notification.at).toISOString(),
65
+ ...extra,
66
+ }
67
+ }
68
+
69
+ /** The default message when the template does not supply one. */
70
+ function defaultMessage(notification: AlertNotification): string {
71
+ return notification.kind === 'trigger'
72
+ ? `${notification.alias} 的 ${notification.title} 超出阈值(当前 ${notification.value})`
73
+ : `${notification.alias} 的 ${notification.title} 已恢复正常(当前 ${notification.value})`
74
+ }
75
+
76
+ /**
77
+ * Substitute the placeholders in a template.
78
+ *
79
+ * @param template - the template text.
80
+ * @param values - the placeholder values.
81
+ * @returns the substituted text; unknown placeholders are left as they are.
82
+ */
83
+ export function renderTemplate(template: string, values: Record<string, string>): string {
84
+ return template.replace(/#[A-Z0-9_.]+#/g, (match) => {
85
+ const value = values[match]
86
+ return value === undefined ? match : value
87
+ })
88
+ }
89
+
90
+ /**
91
+ * The built-in channel presets.
92
+ *
93
+ * Each preset is a starting point, not a fixed format: the operator can
94
+ * edit the URL and body to match their deployment.
95
+ */
96
+ export const NOTIFY_PRESETS: ReadonlyArray<{ id: string; title: string; channel: NotifyChannel }> = [
97
+ {
98
+ id: 'bark',
99
+ title: 'Bark (iOS)',
100
+ channel: {
101
+ id: 'bark',
102
+ url: 'https://api.day.app/YOUR_KEY',
103
+ method: 'GET',
104
+ body: '',
105
+ headers: {},
106
+ },
107
+ },
108
+ {
109
+ id: 'telegram',
110
+ title: 'Telegram',
111
+ channel: {
112
+ id: 'telegram',
113
+ url: 'https://api.telegram.org/botYOUR_TOKEN/sendMessage',
114
+ method: 'POST',
115
+ body: JSON.stringify({ chat_id: 'YOUR_CHAT_ID', text: '#MESSAGE#' }),
116
+ contentType: 'application/json',
117
+ },
118
+ },
119
+ {
120
+ id: 'lark',
121
+ title: '飞书 / Lark',
122
+ channel: {
123
+ id: 'lark',
124
+ url: 'https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_HOOK',
125
+ method: 'POST',
126
+ body: JSON.stringify({ msg_type: 'text', content: { text: '#MESSAGE#' } }),
127
+ contentType: 'application/json',
128
+ },
129
+ },
130
+ {
131
+ id: 'wecom',
132
+ title: '企业微信 / WeCom',
133
+ channel: {
134
+ id: 'wecom',
135
+ url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY',
136
+ method: 'POST',
137
+ body: JSON.stringify({ msgtype: 'text', text: { content: '#MESSAGE#' } }),
138
+ contentType: 'application/json',
139
+ },
140
+ },
141
+ ]
142
+
143
+ /**
144
+ * Send one notification to one channel.
145
+ *
146
+ * The fetch is deliberately fire-and-forget from the caller's point of
147
+ * view: a failing notification channel must not stop the inspection loop,
148
+ * but its failure IS reported so a broken channel is visible.
149
+ *
150
+ * @param channel - the channel to send to.
151
+ * @param notification - the event.
152
+ * @param extra - extra placeholder values.
153
+ * @returns the delivery outcome.
154
+ */
155
+ export async function notify(
156
+ channel: NotifyChannel,
157
+ notification: AlertNotification,
158
+ extra: Record<string, string> = {},
159
+ ): Promise<NotifyOutcome> {
160
+ const values = placeholders(notification, extra)
161
+ const method = (channel.method ?? 'POST').toUpperCase()
162
+ try {
163
+ let url = channel.url
164
+ const headers: Record<string, string> = { ...channel.headers }
165
+ let body: string | undefined
166
+ if (channel.body !== undefined && channel.body !== '') {
167
+ body = renderTemplate(channel.body, values)
168
+ headers['content-type'] = channel.contentType ?? 'application/json'
169
+ } else if (method === 'GET') {
170
+ // A GET channel carries the message in the query string.
171
+ const separator = url.includes('?') ? '&' : '?'
172
+ url = `${url}${separator}body=${encodeURIComponent(values['#MESSAGE#'] ?? '')}`
173
+ }
174
+ const response = await fetch(url, { method, headers, body })
175
+ if (!response.ok) {
176
+ const detail = await response.text().catch(() => '')
177
+ return {
178
+ channelId: channel.id,
179
+ ok: false,
180
+ status: response.status,
181
+ error: `notification failed with HTTP ${response.status}${detail === '' ? '' : `: ${detail.slice(0, 200)}`}`,
182
+ }
183
+ }
184
+ return { channelId: channel.id, ok: true, status: response.status }
185
+ } catch (error) {
186
+ return {
187
+ channelId: channel.id,
188
+ ok: false,
189
+ error: error instanceof Error ? error.message : String(error),
190
+ }
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Send one notification to every channel.
196
+ *
197
+ * @param channels - the channels.
198
+ * @param notification - the event.
199
+ * @param extra - extra placeholder values.
200
+ * @returns one outcome per channel.
201
+ */
202
+ export async function notifyAll(
203
+ channels: NotifyChannel[],
204
+ notification: AlertNotification,
205
+ extra: Record<string, string> = {},
206
+ ): Promise<NotifyOutcome[]> {
207
+ const outcomes: NotifyOutcome[] = []
208
+ for (const channel of channels) {
209
+ outcomes.push(await notify(channel, notification, extra))
210
+ }
211
+ return outcomes
212
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The alert summary the agent sees in its own prompt.
3
+ *
4
+ * A monitoring loop whose only output is a webhook is invisible to the agent
5
+ * working in this session: it can list hosts and run commands, but it has no
6
+ * way to know the fleet is already on fire unless it thinks to ask. This
7
+ * renders the current alert state into the plugin's prompt section, so a
8
+ * conversation that touches the fleet starts from the same picture the
9
+ * operator has.
10
+ *
11
+ * Deliberately quiet:
12
+ * - nothing firing, and the loop armed → one short line saying so;
13
+ * - nothing firing, loop NOT armed → a line that says the silence means
14
+ * nothing, because "no alerts" and "nothing is checking" are opposite
15
+ * facts that look identical in an empty list;
16
+ * - firing → the rule, the host and the value, newest first, bounded so a
17
+ * fleet-wide outage cannot flood the prompt.
18
+ */
19
+
20
+ import type { AlertEngine } from './rules.ts'
21
+ import type { Monitor } from '../monitor/loop.ts'
22
+
23
+ /** How many firing alerts the prompt names before summarising the rest. */
24
+ const MAX_LISTED = 8
25
+
26
+ /**
27
+ * Render the live alert state for the system prompt.
28
+ *
29
+ * @param alerts - the alert engine holding the per-rule state.
30
+ * @param monitor - the loop, consulted only to say whether the state is being advanced.
31
+ * @returns the summary text, or an empty string when there is nothing to say.
32
+ */
33
+ export function renderAlertSummary(alerts: AlertEngine, monitor: Monitor): string {
34
+ const rows = alerts.list()
35
+ const firing = rows.filter(row => row.state === 'firing')
36
+ const pending = rows.filter(row => row.state === 'pending')
37
+ const running = monitor.status().running
38
+
39
+ if (firing.length === 0 && pending.length === 0) {
40
+ if (!running) {
41
+ // The important line in the whole function: an empty alert list from a
42
+ // stopped loop is not evidence of health, and a model that reads it as
43
+ // such will confidently tell the operator the fleet is fine.
44
+ return '机群告警:无。注意 —— 监控循环当前未启动,这个「无」不代表健康。用 hub_monitor 查看状态。'
45
+ }
46
+ return ''
47
+ }
48
+
49
+ const lines: string[] = []
50
+ if (firing.length > 0) {
51
+ lines.push(`机群告警:${String(firing.length)} 条触发中。`)
52
+ for (const row of firing.slice(0, MAX_LISTED)) {
53
+ const value = row.lastValue === undefined || row.lastValue === null ? '—' : String(row.lastValue)
54
+ lines.push(`- [${row.state}] ${row.alias} · ${row.ruleId} = ${value}`)
55
+ }
56
+ if (firing.length > MAX_LISTED) {
57
+ lines.push(`- …另有 ${String(firing.length - MAX_LISTED)} 条,用 hub_alerts 查看全部。`)
58
+ }
59
+ }
60
+ if (pending.length > 0) {
61
+ // Pending is stated separately: it is not a failure yet, and folding it
62
+ // into "firing" would teach the model to report a blip as an outage.
63
+ lines.push(`另有 ${String(pending.length)} 条处于待确认(连续超限次数未达阈值)。`)
64
+ }
65
+ if (!running) {
66
+ // Alerts advanced by a manual hub_inspect are real but frozen: they stop
67
+ // updating until the loop runs again, and recovery will not be noticed.
68
+ lines.push('注意 —— 监控循环未启动,以上状态不会自动更新,恢复也不会被发现。')
69
+ }
70
+ return lines.join('\n')
71
+ }