dsh-ensp 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tools.mjs ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * The single tool table.
3
+ *
4
+ * Both front ends publish the same operations: the MCP server as JSON Schema
5
+ * `inputSchema` objects, the DSH plugin as a flat `parameters` map. Keeping two
6
+ * copies of the wording meant every behaviour change had to be written twice and
7
+ * the two versions drifted in places nobody notices until a model reads the
8
+ * wrong one.
9
+ *
10
+ * This module holds only what both sides must agree on: the tool name, one
11
+ * description, and the parameter nodes as plain JSON Schema. It deliberately
12
+ * holds no handlers: the two front ends return different shapes (MCP returns raw
13
+ * objects, DSH returns rendered text blocks through a required `output` schema),
14
+ * so the `run` / `execute` implementations stay with their own adapter.
15
+ *
16
+ * @module dsh-ensp/tools
17
+ */
18
+
19
+ import { MODEL_SPECS } from './core/build.mjs'
20
+ import { SCENARIO_IDS } from './core/presets.mjs'
21
+
22
+ /**
23
+ * Every tool this package publishes, in publication order.
24
+ *
25
+ * `params` is a flat field map: the key is the argument name and the value is the
26
+ * JSON Schema node for that argument. Enumerations and nested object shapes are
27
+ * written inline as ordinary schema nodes.
28
+ */
29
+ export const TOOL_SPECS = [
30
+ {
31
+ name: 'ensp_status',
32
+ description:
33
+ 'Report eNSP state: whether the client is running, its window handle, and the calibrated toolbar anchors. '
34
+ + 'With a topology path, also polls every device console and reports which ones answer VRP.',
35
+ params: {
36
+ topology: { type: 'string', description: 'Optional .topo path; when set, each console is probed (max 4s each).' },
37
+ },
38
+ },
39
+ {
40
+ name: 'ensp_build_topology',
41
+ description:
42
+ 'Generate a .topo file eNSP can open. Use preset "two-pc" for the built-in two-PC/one-switch lab, '
43
+ + 'scenario to build the topology behind a scenario id, or pass devices and links explicitly '
44
+ + '(links use VRP interface names such as GigabitEthernet0/0/0). Returns the written path and a summary.',
45
+ params: {
46
+ path: { type: 'string', description: 'Output .topo path.' },
47
+ preset: { type: 'string', enum: ['two-pc'], description: '"two-pc" for the built-in lab.' },
48
+ scenario: { type: 'string', description: 'Scenario id with a topology blueprint, e.g. "ospf-single".' },
49
+ vlan: { type: 'number', description: 'VLAN id for the two-pc preset (default 10).' },
50
+ subnet: { type: 'string', description: 'for preset two-pc (default 192.168.10)' },
51
+ devices: {
52
+ type: 'array',
53
+ description: 'Device list: [{ name, model, x, y }].',
54
+ items: {
55
+ type: 'object',
56
+ properties: {
57
+ name: { type: 'string' },
58
+ model: { type: 'string', enum: Object.keys(MODEL_SPECS) },
59
+ x: { type: 'number' },
60
+ y: { type: 'number' },
61
+ pc: { type: 'object', properties: { ip: { type: 'string' }, gateway: { type: 'string' } } },
62
+ },
63
+ },
64
+ },
65
+ links: {
66
+ type: 'array',
67
+ description: 'Link list: [{ a, aPort, b, bPort }]; ports use VRP interface names.',
68
+ items: {
69
+ type: 'object',
70
+ properties: {
71
+ a: { type: 'string' },
72
+ aPort: { type: 'string' },
73
+ b: { type: 'string' },
74
+ bPort: { type: 'string' },
75
+ },
76
+ },
77
+ },
78
+ },
79
+ },
80
+ {
81
+ name: 'ensp_open',
82
+ description:
83
+ 'Launch eNSP (or reuse the running instance) and open a topology file. '
84
+ + 'Returns the process id and window handle needed by the other tools.',
85
+ params: {
86
+ topology: { type: 'string', description: 'Absolute path to a .topo file.' },
87
+ },
88
+ },
89
+ {
90
+ name: 'ensp_start',
91
+ description:
92
+ 'Boot every device in a topology. Calibrates the toolbar by colour, clicks start, then polls each '
93
+ + 'console until VRP answers, so readiness is measured per device rather than assumed. The window is '
94
+ + 'minimised afterwards unless keepWindow is true.',
95
+ params: {
96
+ topology: { type: 'string', description: 'Absolute path to the .topo file that is currently open.' },
97
+ hwnd: { type: 'string', description: 'optional; located automatically' },
98
+ perDeviceTimeoutMs: { type: 'number', description: 'Per-device readiness ceiling in ms (default 240000).' },
99
+ keepWindow: { type: 'boolean', description: 'Leave the eNSP window visible after starting.' },
100
+ },
101
+ },
102
+ {
103
+ name: 'ensp_stop',
104
+ description: 'Shut down every device in the running topology.',
105
+ params: {
106
+ hwnd: { type: 'string', description: 'optional; located automatically' },
107
+ },
108
+ },
109
+ {
110
+ name: 'ensp_apply',
111
+ description:
112
+ 'Push a configuration script to one device, one command at a time. Each command is confirmed by its '
113
+ + 'prompt before the next is sent; the first error aborts the batch and reports the line, the command '
114
+ + 'and the raw device output.',
115
+ params: {
116
+ device: { type: 'string', description: 'Device name, used in the report.' },
117
+ port: { type: 'number', description: 'Console TCP port from the .topo file.' },
118
+ script: { type: 'string', description: 'Configuration text; blank lines and ! / # comments are skipped.' },
119
+ save: { type: 'boolean', description: 'Run save at the end.' },
120
+ },
121
+ },
122
+ {
123
+ name: 'ensp_apply_dir',
124
+ description:
125
+ 'Push one .cfg per device from a directory, matching file names to device names. Devices are '
126
+ + 'configured concurrently and one failure does not stop the others.',
127
+ params: {
128
+ directory: { type: 'string', description: 'Directory containing <device>.cfg files.' },
129
+ topology: { type: 'string', description: 'Topology that maps device names to console ports.' },
130
+ save: { type: 'boolean', description: 'Run save on each device afterwards.' },
131
+ concurrency: { type: 'number', description: 'How many devices to configure at once (default 3).' },
132
+ },
133
+ },
134
+ {
135
+ name: 'ensp_query',
136
+ description: 'Run one read-only command on a device console and return its output.',
137
+ params: {
138
+ port: { type: 'number', description: 'Console TCP port.' },
139
+ command: { type: 'string', description: 'One VRP command, e.g. "display ip routing-table".' },
140
+ },
141
+ },
142
+ {
143
+ name: 'ensp_probe',
144
+ description:
145
+ 'Re-measure the toolbar anchors and report every colour cluster. Run this after an eNSP upgrade or a '
146
+ + 'change of display scaling; results are cached per window size otherwise.',
147
+ params: {
148
+ hwnd: { type: 'string', description: 'optional; located automatically' },
149
+ },
150
+ },
151
+ {
152
+ name: 'ensp_show',
153
+ description:
154
+ 'Bring the eNSP window back to the front. Use it after ensp_start minimised the window and you want to '
155
+ + 'watch the lab while it is being configured. Reports whether the window was restored out of the '
156
+ + 'taskbar and whether it ended up in front.',
157
+ params: {
158
+ hwnd: { type: 'string', description: 'optional; located automatically' },
159
+ },
160
+ },
161
+ {
162
+ name: 'ensp_scenarios',
163
+ description:
164
+ 'List or search the built-in configuration scenarios (' + SCENARIO_IDS.length + ' of them, mirroring the labs '
165
+ + 'shipped with eNSP plus verified project scenarios). Each entry is a skeleton: what to create, in what '
166
+ + 'order, and the command that proves it worked, rather than a command dump. Pass syllabus instead to '
167
+ + 'search the vendor manual chapter index: where a topic is taught, and which display command that '
168
+ + 'chapter uses to prove its result.',
169
+ params: {
170
+ search: { type: 'string', description: 'Keyword filter, e.g. "ospf" or "vlan".' },
171
+ level: { type: 'string', enum: ['basic', 'intermediate', 'advanced'], description: 'One of basic, intermediate, advanced.' },
172
+ syllabus: { type: 'string', description: 'Keyword to search the vendor manual chapter index, e.g. "MPLS".' },
173
+ },
174
+ },
175
+ {
176
+ name: 'ensp_scenario',
177
+ description:
178
+ 'Return one scenario as a step-by-step brief: ordered direction, the verification command for each '
179
+ + 'step, and the known pitfalls. Use this to plan a configuration before touching any device.',
180
+ params: {
181
+ id: { type: 'string', description: 'Scenario id, e.g. "ospf-single".' },
182
+ },
183
+ },
184
+ {
185
+ name: 'ensp_images',
186
+ description:
187
+ 'Report which plugin device images this installation has, and install one where it is needed. '
188
+ + 'Plugin models (USG6000V, NE40E, NE5000E, NE9000, CX, CE6800, CE12800) ship an image that the '
189
+ + 'eNSP installer may not have included: the client then opens a topology that uses them, renders it, '
190
+ + 'and quits by itself. The destination path is read from the model\'s own VirtualBox template, so it '
191
+ + 'is correct on any machine. Call with no arguments to see what is missing; pass model and source to '
192
+ + 'install one.',
193
+ params: {
194
+ model: { type: 'string', description: 'plugin model, e.g. "USG6000V"; omit to list every one' },
195
+ source: { type: 'string', description: 'path to the image file to install for that model' },
196
+ overwrite: { type: 'boolean', description: 'replace an image that is already in place' },
197
+ },
198
+ },
199
+ {
200
+ name: 'ensp_doctor',
201
+ description:
202
+ 'Check whether this machine can actually run a lab before starting anything: eNSP and '
203
+ + 'VirtualBox presence, missing device images, console ports already in use, free memory, and '
204
+ + 'whether synthetic mouse input reaches this session at all. Every failing check comes with a '
205
+ + 'fix. Never starts eNSP, so it is safe to run first.',
206
+ params: {
207
+ topology: { type: 'string', description: 'optional .topo path, so the device images it needs can be checked' },
208
+ deep: { type: 'boolean', description: 'run the slow input-injection probe (default true)' },
209
+ },
210
+ },
211
+ {
212
+ name: 'ensp_verify',
213
+ description:
214
+ 'Run a scenario\'s acceptance checks against a lab that is already running. Curated scenarios '
215
+ + 'assert on what each device reports (OSPF Full, BGP Established, VRRP Master); the rest '
216
+ + 'only run each verification command and cannot check its output, which the summary reports '
217
+ + 'as unverified (ok is null) rather than passed.',
218
+ params: {
219
+ scenario: { type: 'string', description: 'scenario id, e.g. "ospf-single"' },
220
+ topology: { type: 'string', description: 'the .topo file that is running, used for console ports' },
221
+ timeout: { type: 'number', description: 'per-command timeout in ms (default 25000)' },
222
+ wait: { type: 'number', description: 'how long a failing assertion may keep being retried, in ms (default 60000)' },
223
+ },
224
+ },
225
+ {
226
+ name: 'ensp_preset_config',
227
+ description:
228
+ 'Return configuration text. Without a scenario it is the built-in two-PC lab; with one it is that scenario blueprint addressing plan, which covers interfaces and addresses only, so routing and policy still come from the scenario steps.',
229
+ params: {
230
+ vlan: { type: 'number', description: 'VLAN id for the two-PC lab (default 10).' },
231
+ scenario: {
232
+ type: 'string',
233
+ description: 'Scenario id whose addressing plan to emit instead of the two-PC lab.',
234
+ enum: SCENARIO_IDS,
235
+ },
236
+ },
237
+ },
238
+ {
239
+ name: 'ensp_report',
240
+ description:
241
+ 'Write a Word (.docx) delivery report for one scenario of a running lab. It reads each device\'s running '
242
+ + 'configuration, reruns the acceptance checks and keeps their full output, then lays it out in six '
243
+ + 'chapters: purpose, topology and addressing, configuration, verification, problems and conclusion, '
244
+ + 'appendix. The verdict at the top is the same three-state verdict ensp_verify gives, so a lab whose '
245
+ + 'checks had no assertion is reported as unverified rather than passed.',
246
+ params: {
247
+ scenario: { type: 'string', description: 'scenario id, e.g. "ospf-single"', enum: SCENARIO_IDS },
248
+ topology: { type: 'string', description: 'the .topo file that is running, used for devices and console ports' },
249
+ out: { type: 'string', description: 'where to write the .docx (default "<scenario>-report.docx")' },
250
+ timeout: { type: 'number', description: 'per-command timeout in ms (default 25000)' },
251
+ wait: { type: 'number', description: 'how long a failing assertion may keep being retried, in ms (default 60000)' },
252
+ },
253
+ },
254
+ ]
255
+
256
+ /** Registry-time name list, in publication order. */
257
+ export const TOOL_NAMES = TOOL_SPECS.map((t) => t.name)
258
+
259
+ /**
260
+ * Build a closed JSON Schema object for MCP's `inputSchema`.
261
+ *
262
+ * The properties are deep-copied so neither front end can mutate the shared
263
+ * table, and `required` stays empty: the two adapters disagree about which
264
+ * arguments are mandatory, and their handlers already report a missing one with
265
+ * a message that names it.
266
+ *
267
+ * @param {object} params - flat field map from a `TOOL_SPECS` entry
268
+ */
269
+ export function toInputSchema(params) {
270
+ return { type: 'object', properties: structuredClone(params), required: [] }
271
+ }
package/screenshots.json DELETED
@@ -1,3 +0,0 @@
1
- [
2
- "assets/screenshot-topology.png"
3
- ]
@@ -1,196 +0,0 @@
1
- /**
2
- * Regenerate `src/core/knowledge.json`.
3
- *
4
- * Usage:
5
- * node scripts/gen-knowledge.mjs <source.json> [more.json ...]
6
- *
7
- * The source is any array of `{ n, type, stem, options: [{key, text}], answer,
8
- * analysis, topics }`. It is not part of this package; what ships is the index
9
- * this script produces, so the transformation has to be reproducible and
10
- * reviewable by anyone who has the source.
11
- *
12
- * Two rules shape the output, and both exist because the obvious version of this
13
- * script produced a worse index:
14
- *
15
- * 1. **One topic per question.** Upstream tags are unreliable: a question
16
- * about OSPF LSA types carries `ospf` and `security` both, and honouring every
17
- * tag files the same fact under two headings. Score the text against topic
18
- * keywords and keep the best match.
19
- * 2. **Drop "which is wrong" questions.** Once the distractors are removed, the
20
- * surviving string is a false statement, which is worse than no material.
21
- */
22
-
23
- import { readFileSync, writeFileSync } from 'node:fs'
24
- import { fileURLToPath } from 'node:url'
25
- import path from 'node:path'
26
-
27
- /** Topic tag -> the scenarios that teach it. */
28
- const TOPIC_SCENARIOS = {
29
- ospf: ['ospf-single', 'ospf-multi-area', 'ospf-stub-nssa', 'ospf-lsa-types', 'ospf-virtual-link', 'ospf-troubleshooting'],
30
- bgp: ['bgp-ebgp-ibgp', 'bgp-route-reflector', 'bgp-attributes', 'bgp-aggregation', 'bgp-troubleshooting'],
31
- isis: ['isis-multi-level'],
32
- switching: [
33
- 'vlan-access',
34
- 'trunk-interconnect',
35
- 'stp-rstp',
36
- 'mstp-load-balance',
37
- 'link-aggregation',
38
- 'super-vlan',
39
- 'port-security',
40
- 'port-isolation',
41
- 'stack-istack',
42
- ],
43
- multicast: ['multicast-pim-sm'],
44
- mpls: ['mpls-basic', 'mpls-l3vpn'],
45
- ipv6: ['ipv6', 'ospfv3-ipv6'],
46
- qos: ['qos-basics'],
47
- management: ['network-management'],
48
- reliability: ['vrrp-basics', 'bfd-fast-convergence', 'firewall-hrp', 'dual-homed-isp'],
49
- security: ['acl-filter', 'aaa-local', 'ipsec-vpn', 'firewall-zones', 'firewall-hrp', 'arp-security', 'dhcp-snooping', 'port-security'],
50
- }
51
-
52
- /** Keywords that decide which topic a question belongs to. */
53
- const TOPIC_TERMS = {
54
- ospf: ['ospf', 'lsa', 'abr', 'asbr', 'nssa', 'stub', 'router-id'],
55
- bgp: ['bgp', 'as-path', 'ibgp', 'ebgp', 'community', 'aggregator', 'med', 'local-preference'],
56
- isis: ['is-is', 'isis', 'level-1', 'level-2', 'dis', 'lsp', 'att'],
57
- switching: ['vlan', 'mstp', 'rstp', 'stp', 'eth-trunk', '端口隔离', '端口安全', '堆叠', '根桥', 'bpdu'],
58
- multicast: ['pim', 'igmp', '组播', 'rpf', 'spt'],
59
- mpls: ['mpls', 'ldp', 'lsr', '标签', 'vpn-instance'],
60
- ipv6: ['ipv6', 'ospfv3', 'slaac'],
61
- qos: ['qos', '队列', '拥塞', '流量监管', '优先级映射'],
62
- management: ['网络管理', '网管', 'snmp', 'ntp', '日志', 'info-center', 'netconf', 'telemetry'],
63
- reliability: ['vrrp', 'bfd', 'hrp', '双机热备', '主备'],
64
- security: ['acl', '安全区域', 'security-policy', 'ipsec', 'ike', 'aaa', 'radius', '防火墙', 'nat'],
65
- }
66
-
67
- /** A question phrased this way keeps only a false statement once stripped. */
68
- const NEGATIVE = /错误的是|不正确的是|不属于|不支持|不能|无需/
69
-
70
- /**
71
- * Points kept per topic.
72
- *
73
- * The brief renders at most ten of them, so this cap is about how much depth a
74
- * topic carries into the index, not about screen space. It has to be generous:
75
- * every source that feeds the index contributes its own best rows, and a tight
76
- * cap lets a later source push out an earlier one entirely.
77
- */
78
- const MAX_POINTS = 24
79
-
80
- /** A question must score at least this many keyword hits to be filed at all. */
81
- const MIN_SCORE = 2
82
-
83
- const clean = (s) => String(s ?? '').replace(/\s+/g, ' ').trim()
84
- const clip = (s, n) => (s.length <= n ? s : s.slice(0, n - 1).replace(/[,,、;;:: .]*$/, '') + '…')
85
-
86
- /**
87
- * The answer as readable text.
88
- *
89
- * A bare key list (`A,C`) teaches nothing, so every chosen option is spelled out.
90
- * When the option text is unusable the explanation carries the fact instead: it
91
- * is the part a reader can actually learn from, and dropping the question because
92
- * its options came back blank throws away the answer along with them. Returns ''
93
- * only when neither source says anything.
94
- */
95
- function answerText(q) {
96
- const keys = clean(q.answer).toUpperCase().match(/[A-Z]/g)
97
- const picked = (q.options || []).filter(
98
- (o) => keys?.includes(String(o.key).toUpperCase()) && clean(o.text).replace(/^[.、\s]*$/, ''),
99
- )
100
- if (picked.length) {
101
- return picked.map((o) => `${o.key}. ${clip(clean(o.text), 70)}`).join(' / ')
102
- }
103
- const explained = clean(q.analysis)
104
- if (explained.length >= 12) return clip(explained, 130)
105
- if (q.type === '判断题') return clean(q.answer) || ''
106
- return ''
107
- }
108
-
109
- /**
110
- * Build the index.
111
- *
112
- * Two sources feed one topic's points: the keyword pass over the raw questions,
113
- * and `carry` rows that are already in the shipped shape (`{topic, n, q, a}`).
114
- * The carry path exists because the index is built from more than one source
115
- * over time, and rebuilding from a single source would silently drop whatever
116
- * the other one contributed.
117
- *
118
- * @param {Array<object>} source raw questions
119
- * @param {Array<{topic: string, n: number, q: string, a: string}>} [carry] points to keep as-is
120
- * @returns {object}
121
- */
122
- export function buildIndex(source, carry = []) {
123
- const perTopic = {}
124
- for (const q of source) {
125
- const answer = answerText(q)
126
- if (!answer) continue
127
- const stem = clean(q.stem)
128
- if (NEGATIVE.test(stem)) continue
129
- const hay = (stem + ' ' + clean(q.analysis)).toLowerCase()
130
- let best = null
131
- let bestScore = 0
132
- for (const [topic, terms] of Object.entries(TOPIC_TERMS)) {
133
- const score = terms.reduce((sum, t) => sum + (hay.split(t).length - 1), 0)
134
- if (score > bestScore) {
135
- bestScore = score
136
- best = topic
137
- }
138
- }
139
- if (!best || bestScore < MIN_SCORE) continue
140
- ;(perTopic[best] ||= []).push({ n: q.n, q: clip(stem, 90), a: answer, score: bestScore })
141
- }
142
-
143
- const topics = {}
144
- for (const topic of new Set([...Object.keys(perTopic), ...carry.map((c) => c.topic)])) {
145
- const rows = perTopic[topic] || []
146
- // Highest keyword score first, then the shortest stem: a one-line question
147
- // states a fact, while a long one describes a scene.
148
- const ranked = rows.slice().sort((a, b) => b.score - a.score || a.q.length - b.q.length)
149
- const seen = new Set()
150
- const points = []
151
- // Carried points go first. They were already reviewed when they shipped, so a
152
- // later source adds to them rather than displacing them; the alternative
153
- // silently traded an established fact for a new one that scored higher.
154
- for (const c of carry) {
155
- if (c.topic !== topic) continue
156
- if (points.length >= MAX_POINTS) break
157
- const key = c.q.slice(0, 40) + '|' + c.a.slice(0, 30)
158
- if (seen.has(key)) continue
159
- seen.add(key)
160
- points.push({ n: c.n, q: c.q, a: c.a })
161
- }
162
- for (const r of ranked) {
163
- if (points.length >= MAX_POINTS) break
164
- const key = r.q.slice(0, 40) + '|' + r.a.slice(0, 30)
165
- if (seen.has(key)) continue
166
- seen.add(key)
167
- points.push({ n: r.n, q: r.q, a: r.a })
168
- }
169
- topics[topic] = { scenarios: TOPIC_SCENARIOS[topic], points }
170
- }
171
-
172
- return {
173
- version: 1,
174
- topics,
175
- }
176
- }
177
-
178
- const invokedDirectly =
179
- process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
180
-
181
- if (invokedDirectly) {
182
- const args = process.argv.slice(2)
183
- const carryPath = args.find((a) => a.startsWith('--carry='))?.slice('--carry='.length)
184
- const sourcePaths = args.filter((a) => !a.startsWith('--'))
185
- if (!sourcePaths.length) {
186
- console.error('usage: node scripts/gen-knowledge.mjs [--carry=index.json] <source.json> [more.json ...]')
187
- process.exit(2)
188
- }
189
- const source = sourcePaths.flatMap((p) => JSON.parse(readFileSync(p, 'utf8')))
190
- const carry = carryPath ? JSON.parse(readFileSync(carryPath, 'utf8')) : []
191
- const index = buildIndex(source, carry)
192
- const target = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'core', 'knowledge.json')
193
- writeFileSync(target, JSON.stringify(index, null, 1) + '\n', 'utf8')
194
- const total = Object.values(index.topics).reduce((sum, t) => sum + t.points.length, 0)
195
- console.log(`wrote src/core/knowledge.json (${total} points from ${source.length} questions)`)
196
- }