@zxlll/dsh-integration-env 0.0.0-stage → 0.1.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,764 @@
1
+ /**
2
+ * Host 半:把「集成环境」面板里配置的实例,变成 DSH 可读的 HTTP 接口 + 系统提示 + 5 个 agent 工具。
3
+ *
4
+ * 职责:
5
+ * 1. `POST /integration-env/api`:同源接口,`{ method, payload }` 分发到 catalog / 实例增删改测试 /
6
+ * 会话勾选 / 默认启用 / 提示预览。
7
+ * 2. 系统提示 section(order 58):按会话动态渲染【集成环境】块。
8
+ * 3. 5 个 agent 工具:integration_env_list / _nacos / _mysql / _redis / _test。
9
+ *
10
+ * 只 import `node:` 内置模块与同目录 lib/ 文件,不依赖任何 @deepseek-ai 包。
11
+ */
12
+ import { KIND_IDS, KINDS, getKind, kindLabel, mongoTarget, summarize } from './lib/kinds.js'
13
+ import {
14
+ buildEnvBlock,
15
+ createStore,
16
+ effectiveActiveIds,
17
+ enabledEntries,
18
+ publicInstance,
19
+ renderSystemSection,
20
+ resolveInstance,
21
+ sortInstances,
22
+ } from './lib/store.js'
23
+ import { runMysql } from './lib/mysql.js'
24
+ import { runNacos } from './lib/nacos.js'
25
+ import { runRedis } from './lib/redis.js'
26
+ import { tcpProbe, withTimeout } from './lib/probe.js'
27
+
28
+ /** Loader 行 id。 */
29
+ export const name = 'integration-env'
30
+
31
+ /** 依赖的 Host 服务:HTTP 路由、同源校验、系统提示、工具注册。 */
32
+ export const inject = ['webServer', 'connection', 'systemPrompt', 'tools']
33
+
34
+ const API_PATH = '/integration-env/api'
35
+ const MAX_BODY_BYTES = 1 << 20
36
+ const TEST_TIMEOUT_MS = 5000
37
+ /**
38
+ * 工具结果里单块文本的上限。DSH 只把 `output.render` 的返回值交给模型,
39
+ * 因此 render 必须输出真实数据;这里只是防止单个配置/结果把上下文撑爆。
40
+ */
41
+ const MAX_CONFIG_CHARS = 20000
42
+
43
+ /** 超长文本截断并说明,避免模型以为内容就这么多。 */
44
+ function truncateText(text, limit) {
45
+ const value = String(text ?? '')
46
+ if (value.length <= limit) return value
47
+ return `${value.slice(0, limit)}\n...(已截断,原文 ${value.length} 字符,上限 ${limit})`
48
+ }
49
+
50
+ /** MySQL 行结果转成紧凑表格文本,供模型直接阅读。 */
51
+ function formatRows(columns, rows, limit = 200) {
52
+ const head = `| ${columns.join(' | ')} |`
53
+ const divider = `| ${columns.map(() => '---').join(' | ')} |`
54
+ const body = rows.slice(0, limit).map((row) =>
55
+ `| ${row.map((cell) => (cell === null ? 'NULL' : String(cell))).join(' | ')} |`)
56
+ return truncateText([head, divider, ...body].join('\n'), MAX_CONFIG_CHARS)
57
+ }
58
+
59
+ /** kind → 该类型应使用的工具名(kind 不匹配时提示模型)。 */
60
+ const TOOL_NAME_BY_KIND = {
61
+ mysql: 'integration_env_mysql',
62
+ nacos: 'integration_env_nacos',
63
+ redis: 'integration_env_redis',
64
+ }
65
+
66
+ // ─────────────────────────── HTTP 基础 ───────────────────────────
67
+
68
+ function sendJson(res, status, value) {
69
+ const body = JSON.stringify(value)
70
+ res.writeHead(status, {
71
+ 'content-type': 'application/json; charset=utf-8',
72
+ 'cache-control': 'no-store',
73
+ 'content-length': Buffer.byteLength(body),
74
+ })
75
+ res.end(body)
76
+ }
77
+
78
+ function readJsonBody(req) {
79
+ return new Promise((resolvePromise, reject) => {
80
+ const chunks = []
81
+ let size = 0
82
+ req.on('data', (chunk) => {
83
+ size += chunk.length
84
+ if (size > MAX_BODY_BYTES) {
85
+ reject(new Error('请求体过大(上限 1MB)'))
86
+ req.destroy()
87
+ return
88
+ }
89
+ chunks.push(chunk)
90
+ })
91
+ req.on('end', () => {
92
+ const text = Buffer.concat(chunks).toString('utf8')
93
+ if (!text.trim()) {
94
+ resolvePromise({})
95
+ return
96
+ }
97
+ try {
98
+ resolvePromise(JSON.parse(text))
99
+ } catch (error) {
100
+ reject(new Error(`请求体不是合法 JSON:${error.message}`))
101
+ }
102
+ })
103
+ req.on('error', reject)
104
+ })
105
+ }
106
+
107
+ // ─────────────────────────── 实例测试(§4.4) ───────────────────────────
108
+
109
+ /** 按 kind 跑一次真实连通测试,返回 `{ detail }`;失败抛 Error。 */
110
+ async function runKindTest(kindId, instance) {
111
+ if (kindId === 'mysql') {
112
+ const result = await runMysql(instance, {
113
+ action: 'query',
114
+ sql: 'SELECT VERSION() AS version, @@character_set_connection AS charset',
115
+ limit: 1,
116
+ })
117
+ const row = Array.isArray(result.rows?.[0]) ? result.rows[0] : []
118
+ const version = row[0] === undefined || row[0] === null ? '' : String(row[0])
119
+ const charset = row[1] === undefined || row[1] === null ? '' : String(row[1])
120
+ return { detail: `MySQL ${version || '连接成功'}${charset ? ` · ${charset}` : ''}` }
121
+ }
122
+ if (kindId === 'nacos') {
123
+ // 先只验证登录:Nacos 3.x 的控制台接口不一定在同端口,不能因为拿不到 server_state 就判定连不通。
124
+ const auth = await runNacos(instance, { action: 'login_only' })
125
+ const who = auth.authenticated ? '登录成功' : '未配置账号(匿名)'
126
+ try {
127
+ const result = await runNacos(instance, { action: 'server_info' })
128
+ const state = result.state
129
+ const version = state && typeof state === 'object' ? state.version : undefined
130
+ return { detail: `Nacos ${version || '服务可访问'}(${who})` }
131
+ } catch (error) {
132
+ const reason = String(error?.message ?? '').split('原始响应:')[0].trim()
133
+ return { detail: `${who};控制台状态接口不可用:${reason.slice(0, 160)}` }
134
+ }
135
+ }
136
+ if (kindId === 'redis') {
137
+ const result = await runRedis(instance, { action: 'info' })
138
+ const version = result.info?.redis_version
139
+ const database = instance.config?.database ?? 0
140
+ return { detail: `Redis ${version || '连接成功'} · db${database}` }
141
+ }
142
+ throw new Error(`该类型 v1 只支持在面板里配置与连通探测(kind=${kindId})。`)
143
+ }
144
+
145
+ /**
146
+ * 测试一个实例。失败也返回 `{ ok:false }`,不抛异常。
147
+ * @returns `{ ok, latencyMs, detail?, error?, kind, summary }`
148
+ */
149
+ export async function testInstance(instance) {
150
+ const kind = getKind(instance?.kind)
151
+ const base = { kind: instance?.kind ?? '', summary: summarize(instance) }
152
+ if (!kind) {
153
+ return { ok: false, latencyMs: 0, error: `未知的实例类型「${instance?.kind ?? ''}」。`, ...base }
154
+ }
155
+ const startedAt = Date.now()
156
+ if (!kind.connectable) {
157
+ const target = kind.id === 'mongodb'
158
+ ? mongoTarget(instance.config?.uri)
159
+ : {
160
+ host: String(instance.config?.host ?? '').trim(),
161
+ port: Number(instance.config?.port ?? 1883),
162
+ }
163
+ if (!target.host) {
164
+ return { ok: false, latencyMs: 0, error: '实例缺少主机地址,请先在面板里补全。', ...base }
165
+ }
166
+ const probe = await tcpProbe(target.host, target.port, 2000)
167
+ if (!probe.ok) {
168
+ return { ok: false, latencyMs: probe.latencyMs, error: probe.error ?? '端口不可达', ...base }
169
+ }
170
+ return {
171
+ ok: true,
172
+ latencyMs: probe.latencyMs,
173
+ detail: '端口可达(v1 仅做连通性探测)',
174
+ ...base,
175
+ }
176
+ }
177
+ try {
178
+ const outcome = await withTimeout(
179
+ runKindTest(kind.id, instance),
180
+ TEST_TIMEOUT_MS,
181
+ `连接超时(${TEST_TIMEOUT_MS}ms):${summarize(instance)}`,
182
+ )
183
+ return {
184
+ ok: true,
185
+ latencyMs: Date.now() - startedAt,
186
+ detail: outcome.detail,
187
+ ...base,
188
+ }
189
+ } catch (error) {
190
+ return {
191
+ ok: false,
192
+ latencyMs: Date.now() - startedAt,
193
+ error: error?.message ?? String(error),
194
+ ...base,
195
+ }
196
+ }
197
+ }
198
+
199
+ // ─────────────────────────── HTTP 方法分发 ───────────────────────────
200
+
201
+ /** 构造 JSON-RPC 风格的方法表。 */
202
+ function createDispatcher(store) {
203
+ return {
204
+ async catalog(payload) {
205
+ return store.catalog(payload)
206
+ },
207
+ async 'instance.save'(payload) {
208
+ return store.saveInstance(payload)
209
+ },
210
+ async 'instance.delete'(payload) {
211
+ return store.deleteInstance(payload)
212
+ },
213
+ async 'instance.test'(payload) {
214
+ const target = await store.resolveTestTarget(payload)
215
+ return testInstance(target)
216
+ },
217
+ async 'session.setActive'(payload) {
218
+ return store.setActive(payload)
219
+ },
220
+ async 'session.toggle'(payload) {
221
+ return store.toggle(payload)
222
+ },
223
+ async 'defaults.set'(payload) {
224
+ return store.setDefaults(payload)
225
+ },
226
+ async 'prompt.preview'(payload) {
227
+ return store.promptPreview(payload)
228
+ },
229
+ }
230
+ }
231
+
232
+ // ─────────────────────────── Agent 工具 ───────────────────────────
233
+
234
+ function sessionIdOfExec(exec) {
235
+ // `Agent.id` 是身份本体;`agent.session.id` 是同一份头的派生读法,留作兜底。
236
+ const id = exec?.agent?.id ?? exec?.agent?.session?.id
237
+ return typeof id === 'string' ? id : ''
238
+ }
239
+
240
+ /** 解析实例并检查启用状态 / kind 匹配(§7.6)。 */
241
+ async function requireInstance(store, needle, expectedKind) {
242
+ const state = await store.readState()
243
+ const instance = resolveInstance(state, needle)
244
+ if (expectedKind && instance.kind !== expectedKind) {
245
+ const toolName = TOOL_NAME_BY_KIND[instance.kind]
246
+ throw new Error(toolName
247
+ ? `实例「${instance.name}」是 ${kindLabel(instance.kind)} 类型,请改用 ${toolName}。`
248
+ : `实例「${instance.name}」是 ${kindLabel(instance.kind)} 类型,该类型 v1 只支持在面板里配置与连通探测。`)
249
+ }
250
+ if (instance.enabled === false) {
251
+ throw new Error(`实例「${instance.name}」已停用;请让用户在右侧「集成环境」面板启用它。`)
252
+ }
253
+ return instance
254
+ }
255
+
256
+ /** integration_env_list。 */
257
+ function makeListTool(store) {
258
+ return {
259
+ name: 'integration_env_list',
260
+ description: '列出 DSH 集成环境里配置的实例,以及本会话已启用的实例。开始任何 Nacos / MySQL / Redis / MongoDB / MQTT 相关操作前先调用它。',
261
+ parameters: {
262
+ type: 'object',
263
+ properties: {
264
+ kind: {
265
+ type: 'string',
266
+ enum: KIND_IDS,
267
+ description: '只列出某个类型(可选)',
268
+ },
269
+ includeInactive: {
270
+ type: 'boolean',
271
+ description: '是否包含已停用的实例,默认 false',
272
+ },
273
+ },
274
+ required: [],
275
+ },
276
+ output: {
277
+ schema: {
278
+ type: 'object',
279
+ properties: {
280
+ session: {
281
+ type: 'object',
282
+ properties: {
283
+ id: { type: 'string' },
284
+ activeIds: { type: 'array', items: { type: 'string' } },
285
+ },
286
+ required: ['id', 'activeIds'],
287
+ },
288
+ instances: {
289
+ type: 'array',
290
+ items: {
291
+ type: 'object',
292
+ properties: {
293
+ id: { type: 'string' },
294
+ kind: { type: 'string' },
295
+ kindLabel: { type: 'string' },
296
+ name: { type: 'string' },
297
+ note: { type: 'string' },
298
+ enabled: { type: 'boolean' },
299
+ summary: { type: 'string' },
300
+ activeForSession: { type: 'boolean' },
301
+ readOnly: { oneOf: [{ type: 'boolean' }, { type: 'null' }] },
302
+ },
303
+ required: ['id', 'kind', 'kindLabel', 'name', 'note', 'enabled', 'summary', 'activeForSession', 'readOnly'],
304
+ },
305
+ },
306
+ kinds: {
307
+ type: 'array',
308
+ items: {
309
+ type: 'object',
310
+ properties: {
311
+ id: { type: 'string' },
312
+ label: { type: 'string' },
313
+ connectable: { type: 'boolean' },
314
+ },
315
+ required: ['id', 'label', 'connectable'],
316
+ },
317
+ },
318
+ },
319
+ required: ['session', 'instances', 'kinds'],
320
+ },
321
+ render(_args, value) {
322
+ const instances = Array.isArray(value?.instances) ? value.instances : []
323
+ const session = value?.session ?? { id: '', activeIds: [] }
324
+ if (instances.length === 0) {
325
+ return [{
326
+ type: 'text',
327
+ text: '还没有配置任何集成环境实例。请让用户在右侧「集成环境」面板添加实例后再继续。',
328
+ }]
329
+ }
330
+ const activeNames = instances
331
+ .filter((instance) => instance.activeForSession && instance.enabled)
332
+ .map((instance) => `${instance.name}(${instance.kindLabel})`)
333
+ const activeText = activeNames.length > 0
334
+ ? `本会话启用 ${activeNames.length} 个:${activeNames.join('、')}`
335
+ : '本会话未启用实例'
336
+ // 模型要用这些名字调用工具,必须把实例清单(含 name / id / 摘要)真实给出。
337
+ const rows = instances.map((instance) => {
338
+ const flags = [
339
+ instance.activeForSession ? '本会话启用' : '本会话未启用',
340
+ instance.enabled ? '' : '已停用',
341
+ instance.readOnly === false ? '可写' : '',
342
+ ].filter(Boolean).join(',')
343
+ return `- ${instance.name}(${instance.kindLabel}):${instance.summary || '(无摘要)'}|id=${instance.id}|${flags}`
344
+ })
345
+ return [{
346
+ type: 'text',
347
+ text: `集成环境共 ${instances.length} 个实例(会话 ${session.id || '(未提供)'});${activeText}。\n${rows.join('\n')}`,
348
+ }]
349
+ },
350
+ },
351
+ async execute(args, exec) {
352
+ const state = await store.readState()
353
+ const sessionId = sessionIdOfExec(exec)
354
+ const requestedKind = typeof args?.kind === 'string' && args.kind ? args.kind : ''
355
+ if (requestedKind && !getKind(requestedKind)) {
356
+ throw new Error(`未知的类型「${requestedKind}」,可用:${KIND_IDS.join('、')}。`)
357
+ }
358
+ const includeInactive = args?.includeInactive === true
359
+ const activeSet = new Set(effectiveActiveIds(state, sessionId))
360
+ const instances = sortInstances(state.instances)
361
+ .filter((instance) => (requestedKind ? instance.kind === requestedKind : true))
362
+ .filter((instance) => includeInactive || instance.enabled !== false)
363
+ .map((instance) => {
364
+ const kind = getKind(instance.kind)
365
+ return {
366
+ id: instance.id,
367
+ kind: instance.kind,
368
+ kindLabel: kindLabel(instance.kind),
369
+ name: instance.name,
370
+ note: instance.note ?? '',
371
+ enabled: instance.enabled !== false,
372
+ summary: summarize(instance),
373
+ activeForSession: activeSet.has(instance.id),
374
+ readOnly: (kind?.fields ?? []).some((field) => field.key === 'readOnly')
375
+ ? instance.config?.readOnly !== false
376
+ : null,
377
+ }
378
+ })
379
+ return {
380
+ session: { id: sessionId, activeIds: [...activeSet] },
381
+ instances,
382
+ kinds: KINDS.map((kind) => ({ id: kind.id, label: kind.label, connectable: kind.connectable })),
383
+ }
384
+ },
385
+ }
386
+ }
387
+
388
+ /** integration_env_nacos。 */
389
+ function makeNacosTool(store) {
390
+ return {
391
+ name: 'integration_env_nacos',
392
+ description: '读取 Nacos 的配置、服务列表或服务实例。instance 传实例名(数据库叫法同右侧面板显示的名字)。',
393
+ parameters: {
394
+ type: 'object',
395
+ properties: {
396
+ instance: { type: 'string', description: '实例名或 id' },
397
+ action: {
398
+ type: 'string',
399
+ enum: ['get_config', 'list_namespaces', 'list_services', 'list_instances', 'server_info'],
400
+ description: '要执行的动作',
401
+ },
402
+ dataId: { type: 'string', description: '配置 dataId(get_config 必填)' },
403
+ group: { type: 'string', description: '分组,默认用实例配置(DEFAULT_GROUP)' },
404
+ namespace: { type: 'string', description: '命名空间 ID,默认用实例配置(public 留空)' },
405
+ serviceName: { type: 'string', description: '服务名(list_instances 必填)' },
406
+ pageNo: { type: 'integer', description: '页码,默认 1' },
407
+ pageSize: { type: 'integer', description: '每页条数,默认 20' },
408
+ },
409
+ required: ['instance', 'action'],
410
+ },
411
+ output: {
412
+ schema: {
413
+ type: 'object',
414
+ properties: {
415
+ action: { type: 'string' },
416
+ dataId: { type: 'string' },
417
+ group: { type: 'string' },
418
+ namespace: { type: 'string' },
419
+ content: { type: 'string' },
420
+ path: { type: 'string' },
421
+ requestedGroup: { type: 'string' },
422
+ warning: { type: 'string' },
423
+ namespaces: { type: 'array', items: {} },
424
+ pageNo: { type: 'integer' },
425
+ pageSize: { type: 'integer' },
426
+ namespaceId: { type: 'string' },
427
+ count: { type: 'integer' },
428
+ services: { type: 'array', items: {} },
429
+ serviceName: { type: 'string' },
430
+ groupName: { type: 'string' },
431
+ hosts: { type: 'array', items: {} },
432
+ state: {},
433
+ },
434
+ required: ['action'],
435
+ },
436
+ render(args, value) {
437
+ const action = value?.action ?? args?.action ?? ''
438
+ // 分组回退时补一句提示,避免模型以为用的是实例配置的分组。
439
+ const groupNote = value?.warning ? `\n注意:${value.warning}` : ''
440
+ switch (action) {
441
+ case 'get_config': {
442
+ // 关键:DSH 只把 render 的返回值交给模型。这里必须给出配置正文,
443
+ // 只报「N 字符」会让模型完全看不到配置内容(历史 bug)。
444
+ const content = String(value?.content ?? '')
445
+ const header = `Nacos 配置 ${value?.dataId ?? ''}(group=${value?.group ?? ''},namespace=${value?.namespace || 'public'}):${content.length} 字符`
446
+ return [{
447
+ type: 'text',
448
+ text: `${header}${groupNote}\n\n${truncateText(content, MAX_CONFIG_CHARS)}`,
449
+ }]
450
+ }
451
+ case 'list_namespaces':
452
+ return [{
453
+ type: 'text',
454
+ text: `Nacos 命名空间:${Array.isArray(value?.namespaces) ? value.namespaces.length : 0} 个。`
455
+ + '\n' + JSON.stringify(value?.namespaces ?? [], null, 2),
456
+ }]
457
+ case 'list_services':
458
+ return [{
459
+ type: 'text',
460
+ text: `Nacos 服务列表:第 ${value?.pageNo ?? 1} 页,共 ${value?.count ?? 0} 个服务。`
461
+ + '\n' + JSON.stringify(value?.services ?? [], null, 2),
462
+ }]
463
+ case 'list_instances':
464
+ return [{
465
+ type: 'text',
466
+ text: `Nacos 服务 ${value?.serviceName ?? ''}:${Array.isArray(value?.hosts) ? value.hosts.length : 0} 个实例。${groupNote}`
467
+ + '\n' + JSON.stringify(value?.hosts ?? [], null, 2),
468
+ }]
469
+ case 'server_info':
470
+ return [{
471
+ type: 'text',
472
+ text: 'Nacos 服务状态:\n' + JSON.stringify(value?.state ?? {}, null, 2),
473
+ }]
474
+ default:
475
+ return [{ type: 'text', text: 'Nacos 请求完成。' }]
476
+ }
477
+ },
478
+ },
479
+ async execute(args) {
480
+ const instance = await requireInstance(store, args?.instance, 'nacos')
481
+ return runNacos(instance, args ?? {})
482
+ },
483
+ }
484
+ }
485
+
486
+ /** integration_env_mysql。 */
487
+ function makeMysqlTool(store) {
488
+ return {
489
+ name: 'integration_env_mysql',
490
+ description: '在指定的 MySQL 实例上执行只读 SQL(默认只读,写语句会被拒绝)。',
491
+ parameters: {
492
+ type: 'object',
493
+ properties: {
494
+ instance: { type: 'string', description: '实例名或 id' },
495
+ action: {
496
+ type: 'string',
497
+ enum: ['query', 'databases', 'tables', 'describe'],
498
+ description: '要执行的动作',
499
+ },
500
+ sql: { type: 'string', description: 'SQL 语句(action=query 时必填)' },
501
+ table: { type: 'string', description: '表名(action=describe 时可用)' },
502
+ database: { type: 'string', description: '覆盖实例默认数据库' },
503
+ limit: { type: 'integer', description: '返回行数上限,默认 200,最大 1000' },
504
+ },
505
+ required: ['instance', 'action'],
506
+ },
507
+ output: {
508
+ schema: {
509
+ type: 'object',
510
+ properties: {
511
+ columns: { type: 'array', items: { type: 'string' } },
512
+ rows: {
513
+ type: 'array',
514
+ items: {
515
+ type: 'array',
516
+ items: { oneOf: [{ type: 'string' }, { type: 'number' }, { type: 'null' }] },
517
+ },
518
+ },
519
+ rowCount: { type: 'integer' },
520
+ truncated: { type: 'boolean' },
521
+ database: { type: 'string' },
522
+ affectedRows: { type: 'integer' },
523
+ },
524
+ required: ['columns', 'rows', 'rowCount', 'truncated', 'database'],
525
+ },
526
+ render(_args, value) {
527
+ const columns = Array.isArray(value?.columns) ? value.columns : []
528
+ const rows = Array.isArray(value?.rows) ? value.rows : []
529
+ const lines = [
530
+ `MySQL 返回 ${value?.rowCount ?? rows.length} 行 / ${columns.length} 列${value?.truncated ? '(已按 limit 截断)' : ''}`,
531
+ `数据库:${value?.database ?? ''}`,
532
+ ]
533
+ if (columns.length > 0 && rows.length > 0) {
534
+ // 模型只能看到 render 的返回值,必须带上实际数据行。
535
+ lines.push('', formatRows(columns, rows))
536
+ } else if (columns.length > 0) {
537
+ lines.push('', `列:${columns.join(', ')}`, '(无数据行)')
538
+ }
539
+ return [{ type: 'text', text: lines.join('\n') }]
540
+ },
541
+ },
542
+ async execute(args) {
543
+ const instance = await requireInstance(store, args?.instance, 'mysql')
544
+ return runMysql(instance, args ?? {})
545
+ },
546
+ }
547
+ }
548
+
549
+ /** integration_env_redis。 */
550
+ function makeRedisTool(store) {
551
+ return {
552
+ name: 'integration_env_redis',
553
+ description: '在指定的 Redis 实例上执行只读命令(INFO / SCAN / GET / TYPE / TTL)。',
554
+ parameters: {
555
+ type: 'object',
556
+ properties: {
557
+ instance: { type: 'string', description: '实例名或 id' },
558
+ action: {
559
+ type: 'string',
560
+ enum: ['info', 'scan', 'get', 'type', 'ttl'],
561
+ description: '要执行的动作',
562
+ },
563
+ pattern: { type: 'string', description: "scan 的匹配模式,默认 '*'" },
564
+ key: { type: 'string', description: 'get / type / ttl 必填的 key' },
565
+ cursor: { type: 'string', description: "scan 游标,默认 '0'" },
566
+ count: { type: 'integer', description: 'scan 每次返回条数,默认 100,最大 1000' },
567
+ },
568
+ required: ['instance', 'action'],
569
+ },
570
+ output: {
571
+ schema: {
572
+ type: 'object',
573
+ properties: {
574
+ action: { type: 'string' },
575
+ info: { type: 'object' },
576
+ cursor: { type: 'string' },
577
+ keys: { type: 'array', items: { type: 'string' } },
578
+ truncated: { type: 'boolean' },
579
+ key: { type: 'string' },
580
+ value: { oneOf: [{ type: 'string' }, { type: 'null' }] },
581
+ type: { type: 'string' },
582
+ ttl: { type: 'integer' },
583
+ },
584
+ required: ['action'],
585
+ },
586
+ render(_args, value) {
587
+ switch (value?.action) {
588
+ case 'info':
589
+ return [{
590
+ type: 'text',
591
+ // INFO 字段很多,只挑模型常用的几项 + 完整键值压缩呈现,避免整段 INFO 撑爆上下文。
592
+ text: `Redis ${value?.info?.redis_version ?? '连接成功'}:已读取 INFO。\n`
593
+ + '```\n' + truncateText(Object.entries(value?.info ?? {})
594
+ .map(([key, val]) => `${key}: ${val}`)
595
+ .join('\n'), MAX_CONFIG_CHARS) + '\n```',
596
+ }]
597
+ case 'scan':
598
+ return [{
599
+ type: 'text',
600
+ text: `SCAN 返回 ${Array.isArray(value?.keys) ? value.keys.length : 0} 个 key,cursor=${value?.cursor ?? '0'}${value?.truncated ? '(还有下一页)' : ''}。\n`
601
+ + (Array.isArray(value?.keys) && value.keys.length > 0
602
+ ? truncateText(value.keys.join('\n'), MAX_CONFIG_CHARS)
603
+ : '(无匹配 key)'),
604
+ }]
605
+ case 'get':
606
+ return [{
607
+ type: 'text',
608
+ text: `GET ${value?.key ?? ''} → ${value?.value === null
609
+ ? '(nil)'
610
+ : `${String(value?.value ?? '').length} 字符\n\n${truncateText(value?.value, MAX_CONFIG_CHARS)}`}`,
611
+ }]
612
+ case 'type':
613
+ return [{ type: 'text', text: `TYPE ${value?.key ?? ''} → ${value?.type ?? ''}。` }]
614
+ case 'ttl':
615
+ return [{ type: 'text', text: `TTL ${value?.key ?? ''} → ${value?.ttl ?? -1}。` }]
616
+ default:
617
+ return [{ type: 'text', text: 'Redis 命令完成。' }]
618
+ }
619
+ },
620
+ },
621
+ async execute(args) {
622
+ const instance = await requireInstance(store, args?.instance, 'redis')
623
+ return runRedis(instance, args ?? {})
624
+ },
625
+ }
626
+ }
627
+
628
+ /** integration_env_test。 */
629
+ function makeTestTool(store) {
630
+ return {
631
+ name: 'integration_env_test',
632
+ description: '测试一个集成环境实例的连通性。',
633
+ parameters: {
634
+ type: 'object',
635
+ properties: {
636
+ instance: { type: 'string', description: '实例名或 id' },
637
+ },
638
+ required: ['instance'],
639
+ },
640
+ output: {
641
+ schema: {
642
+ type: 'object',
643
+ properties: {
644
+ ok: { type: 'boolean' },
645
+ latencyMs: { type: 'number' },
646
+ detail: { type: 'string' },
647
+ error: { type: 'string' },
648
+ kind: { type: 'string' },
649
+ summary: { type: 'string' },
650
+ },
651
+ required: ['ok', 'latencyMs'],
652
+ },
653
+ render(_args, value) {
654
+ const summary = value?.summary || '实例'
655
+ if (value?.ok) {
656
+ return [{
657
+ type: 'text',
658
+ text: `${summary} 连通正常(${value?.latencyMs ?? 0}ms):${value?.detail ?? ''}`,
659
+ }]
660
+ }
661
+ return [{
662
+ type: 'text',
663
+ text: `${summary} 连接失败(${value?.latencyMs ?? 0}ms):${value?.error ?? '未知错误'}`,
664
+ }]
665
+ },
666
+ },
667
+ async execute(args) {
668
+ const instance = await requireInstance(store, args?.instance)
669
+ return testInstance(instance)
670
+ },
671
+ }
672
+ }
673
+
674
+ /** 5 个工具定义(供 apply 注册)。 */
675
+ function buildToolDefinitions(store) {
676
+ return [
677
+ makeListTool(store),
678
+ makeNacosTool(store),
679
+ makeMysqlTool(store),
680
+ makeRedisTool(store),
681
+ makeTestTool(store),
682
+ ]
683
+ }
684
+
685
+ // ─────────────────────────── 插件入口 ───────────────────────────
686
+
687
+ /**
688
+ * 注册 HTTP 路由、系统提示与 5 个工具;所有注册都包在 `ctx.effect()` 里。
689
+ * @param ctx - Host 插件上下文。
690
+ * @param config - bundle 行 config,可含 `dataFile`。
691
+ */
692
+ export function apply(ctx, config) {
693
+ const store = createStore(config)
694
+ const dispatch = createDispatcher(store)
695
+
696
+ ctx.effect(() => ctx.webServer.register({
697
+ kind: 'exact',
698
+ path: API_PATH,
699
+ handler: async (req, res) => {
700
+ const rejection = typeof ctx.connection?.requestRejection === 'function'
701
+ ? ctx.connection.requestRejection({ headers: req.headers })
702
+ : undefined
703
+ if (rejection !== undefined) {
704
+ const message = rejection === 401
705
+ ? '未通过浏览器鉴权:请用打开 DSH 页面的同一浏览器会话访问(刷新页面后重试)。'
706
+ : '请求被拒绝:只接受同源、本机浏览器的请求。'
707
+ sendJson(res, rejection, { ok: false, error: { code: 'forbidden', message } })
708
+ return
709
+ }
710
+ if (req.method !== 'POST') {
711
+ sendJson(res, 405, { ok: false, error: { code: 'bad-request', message: '仅支持 POST 请求。' } })
712
+ return
713
+ }
714
+ let payload
715
+ try {
716
+ payload = await readJsonBody(req)
717
+ } catch (error) {
718
+ sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: error.message } })
719
+ return
720
+ }
721
+ const method = String(payload?.method ?? '')
722
+ const handler = Object.prototype.hasOwnProperty.call(dispatch, method) ? dispatch[method] : undefined
723
+ if (typeof handler !== 'function') {
724
+ sendJson(res, 200, {
725
+ ok: false,
726
+ error: { code: 'unknown-method', message: `未知方法:${method || '(空)'}` },
727
+ })
728
+ return
729
+ }
730
+ try {
731
+ const value = await handler.call(dispatch, payload?.payload ?? {})
732
+ sendJson(res, 200, { ok: true, value })
733
+ } catch (error) {
734
+ sendJson(res, 200, {
735
+ ok: false,
736
+ error: { code: error?.code ?? 'internal', message: error?.message ?? String(error) },
737
+ })
738
+ }
739
+ },
740
+ }))
741
+
742
+ ctx.effect(() => ctx.systemPrompt.section({
743
+ name: 'integration-env',
744
+ order: 58,
745
+ text: (context) => {
746
+ const sessionId = typeof context?.scope?.id === 'string' ? context.scope.id : ''
747
+ return store.buildSystemSection(sessionId)
748
+ },
749
+ }))
750
+
751
+ for (const definition of buildToolDefinitions(store)) {
752
+ ctx.effect(() => ctx.tools.register(definition))
753
+ }
754
+ }
755
+
756
+ // 导出内部函数,便于 check-host.mjs 直接断言(不影响插件运行)。
757
+ export const internals = {
758
+ createDispatcher,
759
+ testInstance,
760
+ buildEnvBlock,
761
+ renderSystemSection,
762
+ publicInstance,
763
+ enabledEntries,
764
+ }