dsh-ensp 0.1.3 → 0.1.7

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/dsh/index.mjs CHANGED
@@ -1,13 +1,23 @@
1
1
  /**
2
2
  * DeepSeek Harness plugin row.
3
3
  *
4
- * The plugin is a thin adapter: it registers the same operations the CLI and the
5
- * MCP server expose as **model tools**, so an agent can drive an eNSP lab directly
6
- * inside a Harness session. No behaviour lives here — everything delegates to
7
- * `src/core`, which keeps the three front-ends from drifting apart.
4
+ * A thin adapter: it publishes the same operations the CLI and the MCP server
5
+ * expose as **model tools**, so an agent can drive an eNSP lab inside a Harness
6
+ * session. No behaviour lives here; everything delegates to `src/core`.
8
7
  *
9
- * It publishes no service of its own; it only consumes `tools`, so no `isolate`
10
- * realm is required.
8
+ * ## Tool contract
9
+ *
10
+ * `ctx.tools.register` wants a shape that differs from the MCP schema in two ways,
11
+ * and getting either wrong fails activation with a schema complaint rather than a
12
+ * stack trace:
13
+ *
14
+ * - `parameters` is a **flat map of field name to field schema**, not a JSON
15
+ * Schema object with `properties`.
16
+ * - `output` is **required** and pairs a closed `schema` with a `render`
17
+ * function that turns the handler's value into content blocks.
18
+ *
19
+ * The helpers below mirror what the first-party plugins do, so the two front-ends
20
+ * stay readable side by side.
11
21
  *
12
22
  * @module dsh-ensp/dsh
13
23
  */
@@ -15,8 +25,16 @@
15
25
  import { readFile, readdir } from 'node:fs/promises'
16
26
  import path from 'node:path'
17
27
 
18
- import { buildTopology, twoPcLab, twoPcLabConfig, autoLayout, MODEL_SPECS } from '../core/build.mjs'
28
+ import { buildTopology, twoPcLab, twoPcLabConfig, autoLayout } from '../core/build.mjs'
19
29
  import { readTopology, writeTopology, summarise } from '../core/topology.mjs'
30
+ import {
31
+ LAB_IDS,
32
+ buildScenarioTopology,
33
+ hasLab,
34
+ labAddressing,
35
+ labDevices,
36
+ } from '../core/labs.mjs'
37
+ import { checkTopologySupport } from '../core/compat.mjs'
20
38
  import {
21
39
  enspPid,
22
40
  locateWindow,
@@ -27,21 +45,89 @@ import {
27
45
  } from '../core/launcher.mjs'
28
46
  import { calibrateAnchors, inspectAnchors } from '../core/calibrate.mjs'
29
47
  import { pushConfig, pushConfigMany, queryDevice } from '../core/provision.mjs'
30
- import { SCENARIOS, renderScenario, searchScenarios, byLevel } from '../core/presets.mjs'
48
+ import { SCENARIOS, SCENARIO_IDS, renderScenario, searchScenarios, byLevel } from '../core/presets.mjs'
49
+ import { VERSION } from '../core/version.mjs'
31
50
 
32
51
  /** Declared hard dependency: the tool registry. */
33
52
  export const inject = ['tools']
34
53
 
35
54
  export const name = 'ensp'
36
55
 
56
+ // ---------------------------------------------------------------- schema helpers
57
+ //
58
+ // `req()` marks a field as required for the *author*, and `obj()` compiles the
59
+ // marker away into the JSON-Schema form the validator accepts: a top-level
60
+ // `required` array of names, never a `required: true` on the leaf.
61
+ //
62
+ // Leaving the marker on the leaf fails activation with
63
+ // unsupported JSON schema: schema.properties.x.required is not supported on type "boolean"
64
+
65
+ const str = (description) => ({ type: 'string', ...(description ? { description } : {}) })
66
+ const num = (description) => ({ type: 'number', ...(description ? { description } : {}) })
67
+ const bool = (description) => ({ type: 'boolean', ...(description ? { description } : {}) })
68
+ const arr = (description) => ({ type: 'array', items: { type: 'object' }, ...(description ? { description } : {}) })
69
+
70
+ /** Mark an output field required. The marker is consumed by `obj()`. */
71
+ const req = (node) => Object.assign(node, { required: true })
72
+
73
+ /**
74
+ * Turn an author-facing property map into a closed JSON Schema object,
75
+ * hoisting every leaf `required: true` into the object-level array.
76
+ */
77
+ function compileObject(properties) {
78
+ const compiled = {}
79
+ const required = []
80
+ for (const key of Object.keys(properties ?? {})) {
81
+ const child = properties[key]
82
+ if (child && typeof child === 'object' && child.required === true) required.push(key)
83
+ compiled[key] = stripRequired(child)
84
+ }
85
+ const schema = { type: 'object', additionalProperties: false, properties: compiled }
86
+ if (required.length) schema.required = required
87
+ return schema
88
+ }
89
+
90
+ /** Deep-copy a node without the internal `required` marker. */
91
+ function stripRequired(node) {
92
+ if (node === null || typeof node !== 'object') return node
93
+ if (Array.isArray(node)) return node.map(stripRequired)
94
+ const out = {}
95
+ for (const [key, value] of Object.entries(node)) {
96
+ if (key === 'required') continue
97
+ out[key] = stripRequired(value)
98
+ }
99
+ return out
100
+ }
101
+
102
+ /** Declare a closed output object. */
103
+ const obj = (properties) => compileObject(properties)
104
+
105
+ /** One plain text content block. */
106
+ const text = (value) => [{ type: 'text', text: String(value) }]
107
+
108
+ /** Render a JSON payload for display without depending on any UI helper. */
109
+ const showJson = (value) => text(JSON.stringify(value, null, 2))
110
+
37
111
  /**
38
- * Register the tools.
112
+ * Register one tool with the harness.
39
113
  *
40
- * Each tool returns compact JSON rather than prose so the model can branch on the
41
- * result. Failures are returned as `{ isError: true }` content instead of thrown,
42
- * because a thrown tool error gives the model nothing to act on.
114
+ * @param {object} tools - `ctx.tools`
115
+ * @param {object} definition - `{ name, description, parameters, output, execute }`
116
+ */
117
+ function add(tools, definition) {
118
+ const { execute, ...rest } = definition
119
+ return tools.register({
120
+ ...rest,
121
+ async execute(args) {
122
+ return execute(args ?? {})
123
+ },
124
+ })
125
+ }
126
+
127
+ /**
128
+ * Build the plugin.
43
129
  *
44
- * @param {object} ctx - Cordis context carrying `tools`
130
+ * @param {object} ctx - Cordis context carrying the declared services.
45
131
  */
46
132
  export function apply(ctx) {
47
133
  const tools = ctx.tools
@@ -50,81 +136,102 @@ export function apply(ctx) {
50
136
  return
51
137
  }
52
138
 
53
- const register = (definition, handler) => {
54
- tools.register({
55
- ...definition,
56
- async execute(args) {
57
- try {
58
- const value = await handler(args ?? {})
59
- return { content: [{ type: 'text', text: JSON.stringify(value, null, 2) }] }
60
- } catch (error) {
61
- return {
62
- content: [{ type: 'text', text: `error: ${error.message}` }],
63
- isError: true,
64
- }
65
- }
66
- },
67
- })
68
- }
139
+ /* ------------------------------------------------------------------ status */
69
140
 
70
- register(
71
- {
72
- name: 'ensp_status',
73
- description:
74
- 'Report eNSP state: running or not, window handle, calibrated toolbar anchors, and ' +
75
- 'per-device console readiness when a topology path is supplied.',
76
- parameters: {
77
- type: 'object',
78
- properties: { topology: { type: 'string' } },
79
- additionalProperties: false,
141
+ add(tools, {
142
+ name: 'ensp_status',
143
+ description:
144
+ 'Report eNSP state: whether the client is running, its window handle, and the calibrated toolbar anchors. '
145
+ + 'With a topology path, also polls every device console and reports which ones answer VRP.',
146
+ parameters: {
147
+ topology: str('Optional .topo path; when set, each console is probed (max 4s each).'),
148
+ },
149
+ output: {
150
+ schema: obj({
151
+ running: req(bool()),
152
+ pid: req(num()),
153
+ hwnd: req(str()),
154
+ anchors: req(str()),
155
+ devices: req(str()),
156
+ error: req(str()),
157
+ }),
158
+ render(args, value) {
159
+ if (!value.running) return text('eNSP is not running.')
160
+ const lines = [`eNSP running, pid ${value.pid}, hwnd ${value.hwnd || '(no frame)'}`]
161
+ if (value.anchors) lines.push(value.anchors)
162
+ if (value.devices) lines.push('', value.devices)
163
+ if (value.error) lines.push('', value.error)
164
+ return text(lines.join('\n'))
80
165
  },
81
166
  },
82
- async ({ topology }) => {
167
+ async execute({ topology }) {
83
168
  const pid = enspPid()
84
169
  if (!pid) return { running: false }
85
170
  const hwnd = locateWindow(pid)
86
- const out = { running: true, pid, hwnd }
171
+ let anchors = ''
87
172
  if (hwnd) {
88
173
  const a = calibrateAnchors(hwnd)
89
- out.anchors = { start: a.start, stop: a.stop, method: a.method }
174
+ anchors = `toolbar anchors (${a.method}): start ${JSON.stringify(a.start)}, stop ${JSON.stringify(a.stop)}`
90
175
  }
176
+ let devices = ''
91
177
  if (topology) {
92
178
  const topo = await readTopology(topology)
93
- out.devices = await Promise.all(
179
+ const rows = await Promise.all(
94
180
  topo.devices
95
181
  .filter((d) => d.comPort)
96
182
  .map(async (d) => {
97
183
  const r = await waitForConsole({ port: d.comPort, timeoutMs: 4000 })
98
- return { name: d.name, port: d.comPort, ready: r.ready, prompt: r.prompt }
184
+ return `${r.ready ? 'ready' : 'no answer'} ${d.name} :${d.comPort} ${r.prompt ?? ''}`.trimEnd()
99
185
  }),
100
186
  )
187
+ devices = rows.join('\n')
101
188
  }
102
- return out
103
- },
104
- )
105
-
106
- register(
107
- {
108
- name: 'ensp_build_topology',
109
- description:
110
- 'Generate a .topo file. preset "two-pc" builds the two-PC/one-switch lab; otherwise ' +
111
- 'pass devices and links (links use VRP interface names).',
112
- parameters: {
113
- type: 'object',
114
- properties: {
115
- path: { type: 'string' },
116
- preset: { type: 'string', enum: ['two-pc'] },
117
- vlan: { type: 'number' },
118
- devices: { type: 'array', items: { type: 'object' } },
119
- links: { type: 'array', items: { type: 'object' } },
120
- },
121
- required: ['path'],
122
- additionalProperties: false,
189
+ return { running: true, pid, hwnd: hwnd ?? '', anchors, devices }
190
+ },
191
+ })
192
+
193
+ /* -------------------------------------------------------------- build topo */
194
+
195
+ add(tools, {
196
+ name: 'ensp_build_topology',
197
+ description:
198
+ 'Generate a .topo file eNSP can open. Use preset "two-pc" for the built-in two-PC lab, '
199
+ + 'scenario for the topology behind a scenario id, or pass devices and links (links use VRP '
200
+ + 'interface names such as GigabitEthernet0/0/0).',
201
+ parameters: {
202
+ path: str('Output .topo path.'),
203
+ preset: str('"two-pc" for the built-in lab.'),
204
+ scenario: str('Scenario id with a topology blueprint, e.g. "ospf-single".'),
205
+ vlan: num('VLAN id for the two-pc preset (default 10).'),
206
+ devices: arr('Device list: [{ name, model, x, y }].'),
207
+ links: arr('Link list: [{ a, aPort, b, bPort }].'),
208
+ },
209
+ output: {
210
+ schema: obj({
211
+ path: req(str()),
212
+ devices: req(num()),
213
+ links: req(num()),
214
+ consoles: req(str()),
215
+ error: req(str()),
216
+ }),
217
+ render(args, value) {
218
+ if (value.error) return text(value.error)
219
+ return text(
220
+ `wrote ${value.path}\n${value.devices} devices, ${value.links} links\nconsoles: ${value.consoles}`,
221
+ )
123
222
  },
124
223
  },
125
- async (args) => {
224
+ async execute(args) {
225
+ if (!args.path) throw new Error('path is required')
126
226
  let topo
127
- if (args.preset === 'two-pc' || (!args.devices && !args.links)) {
227
+ if (args.scenario) {
228
+ if (!hasLab(args.scenario)) {
229
+ throw new Error(
230
+ `scenario "${args.scenario}" has no topology blueprint; ${LAB_IDS.length} of ${SCENARIO_IDS.length} have one`,
231
+ )
232
+ }
233
+ topo = buildScenarioTopology(args.scenario)
234
+ } else if (args.preset === 'two-pc' || (!args.devices && !args.links)) {
128
235
  topo = twoPcLab({ vlan: args.vlan ?? 10 })
129
236
  } else {
130
237
  const b = buildTopology()
@@ -132,47 +239,81 @@ export function apply(ctx) {
132
239
  for (const l of args.links ?? []) b.link(l.a, l.aPort, l.b, l.bPort)
133
240
  topo = autoLayout(b.finish())
134
241
  }
135
- await writeTopology(path.resolve(args.path), topo)
136
- return { path: path.resolve(args.path), ...summarise(topo) }
137
- },
138
- )
139
-
140
- register(
141
- {
142
- name: 'ensp_open',
143
- description: 'Launch eNSP (or reuse it) and open a topology file.',
144
- parameters: {
145
- type: 'object',
146
- properties: { topology: { type: 'string' } },
147
- required: ['topology'],
148
- additionalProperties: false,
242
+ const target = path.resolve(args.path)
243
+ await writeTopology(target, topo)
244
+ const info = summarise(topo)
245
+ const detail = args.scenario
246
+ ? '\n' + labDevices(args.scenario).join('\n')
247
+ : ''
248
+ const support = checkTopologySupport(topo)
249
+ const warning = support.ok
250
+ ? ''
251
+ : '\nWARNING: this machine cannot start ' +
252
+ support.blocked.map((b) => `${b.name} (${b.model}: ${b.reason})`).join(', ') +
253
+ ' -- eNSP will open the file and then quit'
254
+ return {
255
+ path: target,
256
+ devices: info.devices,
257
+ links: info.links,
258
+ consoles: JSON.stringify(info.consoles) + detail + warning,
259
+ }
260
+ },
261
+ })
262
+
263
+ /* ------------------------------------------------------------------- open */
264
+
265
+ add(tools, {
266
+ name: 'ensp_open',
267
+ description: 'Launch the eNSP client (or reuse the running one) and open a topology file.',
268
+ parameters: { topology: str('Absolute path to a .topo file.') },
269
+ output: {
270
+ schema: obj({
271
+ pid: req(num()),
272
+ hwnd: req(str()),
273
+ reused: req(bool()),
274
+ error: req(str()),
275
+ }),
276
+ render(args, value) {
277
+ return text(`eNSP pid ${value.pid}, hwnd ${value.hwnd}${value.reused ? ' (reused)' : ' (launched)'}`)
149
278
  },
150
279
  },
151
- async ({ topology }) => {
280
+ async execute({ topology }) {
281
+ if (!topology) throw new Error('topology is required')
152
282
  const r = await launchEnsp({ topology: path.resolve(topology) })
153
283
  return { pid: r.pid, hwnd: r.hwnd, reused: Boolean(r.reused) }
154
284
  },
155
- )
156
-
157
- register(
158
- {
159
- name: 'ensp_start',
160
- description:
161
- 'Boot every device. Calibrates the toolbar by colour, clicks start, then polls each ' +
162
- 'console until VRP answers (readiness measured per device, never a fixed sleep). ' +
163
- 'Minimises the window afterwards unless keepWindow is true.',
164
- parameters: {
165
- type: 'object',
166
- properties: {
167
- topology: { type: 'string' },
168
- perDeviceTimeoutMs: { type: 'number' },
169
- keepWindow: { type: 'boolean' },
170
- },
171
- required: ['topology'],
172
- additionalProperties: false,
285
+ })
286
+
287
+ /* ------------------------------------------------------------------ start */
288
+
289
+ add(tools, {
290
+ name: 'ensp_start',
291
+ description:
292
+ 'Boot every device in a topology. Calibrates the toolbar by colour, clicks start, then polls each '
293
+ + 'console until VRP answers, so readiness is measured per device rather than assumed. The window is '
294
+ + 'minimised afterwards unless keepWindow is true.',
295
+ parameters: {
296
+ topology: str('Absolute path to the .topo file that is currently open.'),
297
+ perDeviceTimeoutMs: num('Per-device readiness ceiling in ms (default 240000).'),
298
+ keepWindow: bool('Leave the eNSP window visible after starting.'),
299
+ },
300
+ output: {
301
+ schema: obj({
302
+ allReady: req(bool()),
303
+ ready: req(num()),
304
+ total: req(num()),
305
+ anchors: req(str()),
306
+ devices: req(str()),
307
+ error: req(str()),
308
+ }),
309
+ render(args, value) {
310
+ if (value.error) return text(value.error)
311
+ const head = `${value.ready}/${value.total} devices ready${value.allReady ? '' : ' (some did not answer)'}`
312
+ return text([head, value.anchors, '', value.devices].filter(Boolean).join('\n'))
173
313
  },
174
314
  },
175
- async (args) => {
315
+ async execute(args) {
316
+ if (!args.topology) throw new Error('topology is required')
176
317
  const topo = await readTopology(path.resolve(args.topology))
177
318
  const hwnd = locateWindow(enspPid())
178
319
  if (!hwnd) throw new Error('eNSP window not found; call ensp_open first')
@@ -186,49 +327,76 @@ export function apply(ctx) {
186
327
  allReady: r.allReady,
187
328
  ready: r.ready,
188
329
  total: r.total,
189
- anchors: r.anchors,
190
- devices: r.devices.map((d) => ({ name: d.name, port: d.port, ready: d.ready, prompt: d.prompt })),
330
+ anchors: `toolbar anchors (${r.anchors?.method ?? 'default'}): ${JSON.stringify(r.anchors?.start ?? {})}`,
331
+ devices: r.devices
332
+ .map((d) => `${d.ready ? 'ready' : 'no answer'} ${d.name} :${d.port} ${d.prompt ?? ''}`.trimEnd())
333
+ .join('\n'),
191
334
  }
192
335
  },
193
- )
336
+ })
194
337
 
195
- register(
196
- {
197
- name: 'ensp_stop',
198
- description: 'Shut down all devices in the running topology.',
199
- parameters: { type: 'object', properties: {}, additionalProperties: false },
338
+ /* ------------------------------------------------------------------- stop */
339
+
340
+ add(tools, {
341
+ name: 'ensp_stop',
342
+ description: 'Shut down every device in the running topology.',
343
+ parameters: {},
344
+ output: {
345
+ schema: obj({
346
+ ok: req(bool()),
347
+ anchors: req(str()),
348
+ error: req(str()),
349
+ }),
350
+ render(args, value) {
351
+ if (value.error) return text(value.error)
352
+ return text(`shutdown requested for all devices\n${value.anchors}`)
353
+ },
200
354
  },
201
- async () => {
355
+ async execute() {
202
356
  const hwnd = locateWindow(enspPid())
203
357
  if (!hwnd) throw new Error('eNSP window not found')
204
358
  const r = stopAllDevices(hwnd)
205
- return { clicked: r.ok, anchors: r.anchors }
206
- },
207
- )
208
-
209
- register(
210
- {
211
- name: 'ensp_apply',
212
- description:
213
- 'Push a configuration script to one device, one command at a time. The first error ' +
214
- 'aborts the batch and reports the line, the command and the raw device output.',
215
- parameters: {
216
- type: 'object',
217
- properties: {
218
- device: { type: 'string' },
219
- port: { type: 'number' },
220
- script: { type: 'string' },
221
- save: { type: 'boolean' },
222
- },
223
- required: ['device', 'port', 'script'],
224
- additionalProperties: false,
359
+ return { ok: r.ok, anchors: `anchors (${r.anchors?.method ?? 'default'}): ${JSON.stringify(r.anchors?.stop ?? {})}` }
360
+ },
361
+ })
362
+
363
+ /* ------------------------------------------------------------------ apply */
364
+
365
+ add(tools, {
366
+ name: 'ensp_apply',
367
+ description:
368
+ 'Push a configuration script to one device, one command at a time. Each command is confirmed by its '
369
+ + 'prompt before the next is sent; the first error aborts the batch and reports the line, the command '
370
+ + 'and the raw device output.',
371
+ parameters: {
372
+ device: str('Device name, used in the report.'),
373
+ port: num('Console TCP port from the .topo file.'),
374
+ script: str('Configuration text; blank lines and ! / # comments are skipped.'),
375
+ save: bool('Run save at the end.'),
376
+ },
377
+ output: {
378
+ schema: obj({
379
+ ok: req(bool()),
380
+ applied: req(num()),
381
+ total: req(num()),
382
+ saved: req(bool()),
383
+ failedAt: req(str()),
384
+ error: req(str()),
385
+ }),
386
+ render(args, value) {
387
+ if (value.error) return text(value.error)
388
+ if (value.ok) {
389
+ return text(`${args.device}: ${value.applied}/${value.total} commands applied${value.saved ? ', saved' : ''}`)
390
+ }
391
+ return text(`${args.device}: stopped after ${value.applied}/${value.total} commands\n${value.failedAt}`)
225
392
  },
226
393
  },
227
- async (args) => {
394
+ async execute(args) {
395
+ if (!args.port) throw new Error('port is required')
228
396
  const r = await pushConfig({
229
- device: args.device,
397
+ device: args.device ?? 'device',
230
398
  port: args.port,
231
- script: args.script,
399
+ script: args.script ?? '',
232
400
  save: Boolean(args.save),
233
401
  })
234
402
  return {
@@ -236,29 +404,40 @@ export function apply(ctx) {
236
404
  applied: r.applied,
237
405
  total: r.total,
238
406
  saved: r.saved,
239
- failedAt: r.failedAt,
240
- durationMs: r.durationMs,
407
+ failedAt: r.failedAt
408
+ ? `line ${r.failedAt.line}: ${r.failedAt.command}\n ${r.failedAt.error}\n ${(r.failedAt.output ?? '').trim().split('\n').slice(-6).join('\n ')}`
409
+ : '',
241
410
  }
242
411
  },
243
- )
244
-
245
- register(
246
- {
247
- name: 'ensp_apply_dir',
248
- description: 'Push one .cfg per device from a directory, matched by file name to device name.',
249
- parameters: {
250
- type: 'object',
251
- properties: {
252
- directory: { type: 'string' },
253
- topology: { type: 'string' },
254
- save: { type: 'boolean' },
255
- concurrency: { type: 'number' },
256
- },
257
- required: ['directory', 'topology'],
258
- additionalProperties: false,
412
+ })
413
+
414
+ /* -------------------------------------------------------------- apply dir */
415
+
416
+ add(tools, {
417
+ name: 'ensp_apply_dir',
418
+ description:
419
+ 'Push one .cfg per device from a directory, matching file names to device names. Devices are '
420
+ + 'configured concurrently and one failure does not stop the others.',
421
+ parameters: {
422
+ directory: str('Directory containing <device>.cfg files.'),
423
+ topology: str('Topology that maps device names to console ports.'),
424
+ save: bool('Run save on each device afterwards.'),
425
+ concurrency: num('How many devices to configure at once (default 3).'),
426
+ },
427
+ output: {
428
+ schema: obj({
429
+ configured: req(num()),
430
+ total: req(num()),
431
+ results: req(str()),
432
+ error: req(str()),
433
+ }),
434
+ render(args, value) {
435
+ if (value.error) return text(value.error)
436
+ return text(`${value.configured}/${value.total} devices configured\n\n${value.results}`)
259
437
  },
260
438
  },
261
- async (args) => {
439
+ async execute(args) {
440
+ if (!args.directory || !args.topology) throw new Error('directory and topology are required')
262
441
  const topo = await readTopology(path.resolve(args.topology))
263
442
  const consoles = new Map(topo.devices.filter((d) => d.comPort).map((d) => [d.name, d.comPort]))
264
443
  const files = (await readdir(args.directory)).filter((f) => /\.(cfg|txt)$/i.test(f))
@@ -277,111 +456,170 @@ export function apply(ctx) {
277
456
  return {
278
457
  configured: results.filter((r) => r.ok).length,
279
458
  total: results.length,
280
- results: results.map((r) => ({ device: r.device, ok: r.ok, applied: r.applied, failedAt: r.failedAt })),
459
+ results: results
460
+ .map((r) =>
461
+ r.ok
462
+ ? `ok ${r.device} ${r.applied}/${r.total}`
463
+ : `FAIL ${r.device} line ${r.failedAt?.line}: ${r.failedAt?.command} -> ${r.failedAt?.error}`,
464
+ )
465
+ .join('\n'),
281
466
  }
282
467
  },
283
- )
284
-
285
- register(
286
- {
287
- name: 'ensp_query',
288
- description: 'Run one read-only command on a device console and return its output.',
289
- parameters: {
290
- type: 'object',
291
- properties: { port: { type: 'number' }, command: { type: 'string' } },
292
- required: ['port', 'command'],
293
- additionalProperties: false,
468
+ })
469
+
470
+ /* ------------------------------------------------------------------ query */
471
+
472
+ add(tools, {
473
+ name: 'ensp_query',
474
+ description: 'Run one read-only command on a device console and return its output.',
475
+ parameters: {
476
+ port: num('Console TCP port.'),
477
+ command: str('One VRP command, e.g. "display ip routing-table".'),
478
+ },
479
+ output: {
480
+ schema: obj({
481
+ ok: req(bool()),
482
+ output: req(str()),
483
+ error: req(str()),
484
+ }),
485
+ render(args, value) {
486
+ if (!value.ok) return text(`${args.command} failed: ${value.error ?? 'unknown error'}`)
487
+ return text(value.output)
294
488
  },
295
489
  },
296
- async ({ port, command }) => {
297
- const r = await queryDevice({ port, command })
298
- return { ok: r.ok, output: r.output, error: r.error }
299
- },
300
- )
301
-
302
- register(
303
- {
304
- name: 'ensp_scenarios',
305
- description:
306
- 'List or search the 23 built-in scenarios. Each is a skeleton (what to create, in what ' +
307
- 'order, how to verify) rather than a command dump.',
308
- parameters: {
309
- type: 'object',
310
- properties: {
311
- search: { type: 'string' },
312
- level: { type: 'string', enum: ['basic', 'intermediate', 'advanced'] },
313
- },
314
- additionalProperties: false,
490
+ async execute(args) {
491
+ if (!args.port || !args.command) throw new Error('port and command are required')
492
+ const r = await queryDevice({ port: args.port, command: args.command })
493
+ return { ok: r.ok, output: r.output, error: r.error ?? '' }
494
+ },
495
+ })
496
+
497
+ /* -------------------------------------------------------------- scenarios */
498
+
499
+ add(tools, {
500
+ name: 'ensp_scenarios',
501
+ description:
502
+ 'List or search the ' + SCENARIO_IDS.length + ' built-in configuration scenarios. Each is a skeleton: what to create, in what '
503
+ + 'order, and the command that proves it worked, rather than a command dump.',
504
+ parameters: {
505
+ search: str('Keyword filter, e.g. "ospf" or "vlan".'),
506
+ level: str('One of basic, intermediate, advanced.'),
507
+ },
508
+ output: {
509
+ schema: obj({
510
+ count: req(num()),
511
+ list: req(str()),
512
+ error: req(str()),
513
+ }),
514
+ render(args, value) {
515
+ return text(value.list || '(no scenario matched)')
315
516
  },
316
517
  },
317
- async ({ search, level }) => {
518
+ async execute({ search, level }) {
318
519
  const groups = byLevel()
319
- let ids = level ? groups[level] ?? [] : Object.keys(SCENARIOS)
520
+ let ids = level && groups[level] ? groups[level] : Object.keys(SCENARIOS)
320
521
  if (search) {
321
522
  const matched = new Set(searchScenarios(search).map((h) => h.id))
322
523
  ids = ids.filter((id) => matched.has(id))
323
524
  }
324
- return ids.map((id) => ({
325
- id,
326
- title: SCENARIOS[id].title,
327
- level: SCENARIOS[id].level,
328
- goal: SCENARIOS[id].goal,
329
- }))
330
- },
331
- )
332
-
333
- register(
334
- {
335
- name: 'ensp_scenario',
336
- description: 'Return one scenario as a step-by-step brief with pitfalls.',
337
- parameters: {
338
- type: 'object',
339
- properties: { id: { type: 'string' } },
340
- required: ['id'],
341
- additionalProperties: false,
525
+ return {
526
+ count: ids.length,
527
+ list: ids
528
+ .map((id) => `${id.padEnd(24)} ${SCENARIOS[id].title} [${SCENARIOS[id].level}]`)
529
+ .join('\n'),
530
+ }
531
+ },
532
+ })
533
+
534
+ add(tools, {
535
+ name: 'ensp_scenario',
536
+ description: 'Return one scenario as a step-by-step brief with verification commands and pitfalls.',
537
+ parameters: { id: str('Scenario id, e.g. "ospf-single".') },
538
+ output: {
539
+ schema: obj({
540
+ id: req(str()),
541
+ brief: req(str()),
542
+ error: req(str()),
543
+ }),
544
+ render(args, value) {
545
+ return text(value.brief)
342
546
  },
343
547
  },
344
- async ({ id }) => {
548
+ async execute({ id }) {
345
549
  if (!SCENARIOS[id]) throw new Error(`unknown scenario "${id}"`)
346
- return { id, brief: renderScenario(id) }
347
- },
348
- )
349
-
350
- register(
351
- {
352
- name: 'ensp_preset_config',
353
- description: 'Return the configuration text for the built-in two-PC lab.',
354
- parameters: {
355
- type: 'object',
356
- properties: { vlan: { type: 'number' } },
357
- additionalProperties: false,
550
+ const brief = hasLab(id)
551
+ ? renderScenario(id) + `\n\n可生成拓扑: ensp_build_topology { path: "${id}.topo", scenario: "${id}" }`
552
+ : renderScenario(id)
553
+ return { id, brief }
554
+ },
555
+ })
556
+
557
+ /* ---------------------------------------------------------- preset config */
558
+
559
+ add(tools, {
560
+ name: 'ensp_preset_config',
561
+ description: 'Return the configuration text for the built-in two-PC lab.',
562
+ parameters: { vlan: num('VLAN id (default 10).') },
563
+ output: {
564
+ schema: obj({
565
+ script: req(str()),
566
+ error: req(str()),
567
+ }),
568
+ render(args, value) {
569
+ return text(value.script)
358
570
  },
359
571
  },
360
- async ({ vlan }) => ({ script: twoPcLabConfig({ vlan: vlan ?? 10 }) }),
361
- )
572
+ async execute({ vlan }) {
573
+ return { script: twoPcLabConfig({ vlan: vlan ?? 10 }) }
574
+ },
575
+ })
362
576
 
363
- register(
364
- {
365
- name: 'ensp_probe',
366
- description:
367
- 'Re-measure the toolbar anchors and report every colour cluster. Run after an eNSP ' +
368
- 'upgrade or a display-scaling change.',
369
- parameters: { type: 'object', properties: {}, additionalProperties: false },
577
+ /* ------------------------------------------------------------------ probe */
578
+
579
+ add(tools, {
580
+ name: 'ensp_probe',
581
+ description:
582
+ 'Re-measure the toolbar anchors and report every colour cluster. Run this after an eNSP upgrade or a '
583
+ + 'change of display scaling; results are cached per window size otherwise.',
584
+ parameters: {},
585
+ output: {
586
+ schema: obj({
587
+ window: req(str()),
588
+ start: req(str()),
589
+ stop: req(str()),
590
+ method: req(str()),
591
+ clusters: req(str()),
592
+ error: req(str()),
593
+ }),
594
+ render(args, value) {
595
+ if (value.error) return text(value.error)
596
+ return text(
597
+ `window ${value.window}\nanchors (${value.method}): start ${value.start}, stop ${value.stop}\n\n${value.clusters}`,
598
+ )
599
+ },
370
600
  },
371
- async () => {
601
+ async execute() {
372
602
  const hwnd = locateWindow(enspPid())
373
603
  if (!hwnd) throw new Error('eNSP window not found')
374
- return inspectAnchors(hwnd)
604
+ const r = inspectAnchors(hwnd)
605
+ const resolved = r.resolved ?? { start: {}, stop: {}, method: 'none' }
606
+ return {
607
+ window: r.window ?? '(unknown)',
608
+ start: JSON.stringify(resolved.start),
609
+ stop: JSON.stringify(resolved.stop),
610
+ method: resolved.method,
611
+ clusters: [
612
+ `green (${r.green.length}): ` + r.green.map((c) => `${c.x},${c.y} ${c.w}x${c.h}`).join(' | '),
613
+ `red (${r.red.length}): ` + r.red.map((c) => `${c.x},${c.y} ${c.w}x${c.h}`).join(' | '),
614
+ ].join('\n'),
615
+ }
375
616
  },
376
- )
617
+ })
377
618
  }
378
619
 
379
620
  /** Model metadata for the plugin row. */
380
621
  export const dsh = {
381
622
  name: 'dsh-ensp',
382
- version: '0.1.0',
623
+ version: VERSION,
383
624
  description: 'Automate Huawei eNSP labs: build topology, boot devices, push config with verification.',
384
- tools: ['ensp_status', 'ensp_build_topology', 'ensp_open', 'ensp_start', 'ensp_stop', 'ensp_apply', 'ensp_apply_dir', 'ensp_query', 'ensp_scenarios', 'ensp_scenario', 'ensp_preset_config', 'ensp_probe'],
385
625
  }
386
-
387
- export { MODEL_SPECS }