dsh-eplan 0.0.0-stage → 0.14.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/LICENSE +21 -0
- package/README.md +219 -3
- package/cordis.patch.yml +182 -0
- package/docs/INSTALL.md +86 -0
- package/docs/LESSONS.md +224 -0
- package/docs/interfaces.md +183 -0
- package/docs/merged-skills/eplan-setup.md +63 -0
- package/docs/merged-skills/eplan-troubleshooting.md +149 -0
- package/icon.png +0 -0
- package/icon.svg +13 -0
- package/knowledge/KNOWLEDGE.md +413 -0
- package/knowledge/symbols/BP.png +0 -0
- package/knowledge/symbols/CDPST.png +0 -0
- package/knowledge/symbols/CO.png +0 -0
- package/knowledge/symbols/FA3.png +0 -0
- package/knowledge/symbols/TLRO.png +0 -0
- package/knowledge/symbols/TLRU.png +0 -0
- package/knowledge/symbols/TOUL.png +0 -0
- package/knowledge/symbols/TOUR.png +0 -0
- package/knowledge/symbols/manifest.json +91 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/native/bridge/build.ps1 +73 -0
- package/native/bridge/src/Json.cs +383 -0
- package/native/bridge/src/Program.cs +1133 -0
- package/native/host/build.ps1 +74 -0
- package/native/host/src/ActionsTool.cs +225 -0
- package/native/host/src/BoxTool.cs +196 -0
- package/native/host/src/CheckTool.cs +186 -0
- package/native/host/src/Context.cs +169 -0
- package/native/host/src/DarkScheme.cs +111 -0
- package/native/host/src/DiagnoseTool.cs +115 -0
- package/native/host/src/Dispatcher.cs +51 -0
- package/native/host/src/DrawTool.cs +316 -0
- package/native/host/src/Entry.cs +111 -0
- package/native/host/src/ExportTool.cs +213 -0
- package/native/host/src/InspectTool.cs +367 -0
- package/native/host/src/KnowledgeTool.cs +166 -0
- package/native/host/src/LookTool.cs +257 -0
- package/native/host/src/OpLog.cs +289 -0
- package/native/host/src/PageCreateTool.cs +521 -0
- package/native/host/src/PageOpenTool.cs +62 -0
- package/native/host/src/PagesTool.cs +95 -0
- package/native/host/src/Paths.cs +91 -0
- package/native/host/src/PlacementEditTool.cs +234 -0
- package/native/host/src/ProbePropsTool.cs +152 -0
- package/native/host/src/ProjectCreateTool.cs +176 -0
- package/native/host/src/ProjectTool.cs +167 -0
- package/native/host/src/PropWriter.cs +70 -0
- package/native/host/src/PropsTool.cs +257 -0
- package/native/host/src/StatusTool.cs +168 -0
- package/native/host/src/SymbolInfoTool.cs +144 -0
- package/native/host/src/SymbolInsertTool.cs +261 -0
- package/native/host/src/SymbolsTool.cs +94 -0
- package/native/host/src/TagLocTool.cs +108 -0
- package/native/script/EplanMcpBootstrap.cs +221 -0
- package/native/script/build-symbol-gallery.mjs +231 -0
- package/native/script/prepare-install.ps1 +57 -0
- package/native/script/prune.mjs +132 -0
- package/native/script/verify-bootstrap.ps1 +62 -0
- package/package.json +53 -4
- package/preset/bootstrap.js +498 -0
- package/preset/experience-nudge.js +47 -0
- package/preset/image-budget.js +175 -0
- package/preset/knowledge-tool.js +180 -0
- package/preset/mcp-link.js +100 -0
- package/preset/prompt-surface.js +76 -0
- package/preset/restrict-tools.js +141 -0
- package/preset/skill-docs.js +181 -0
- package/preset/video-digest.js +294 -0
- package/preset/video-tool.js +92 -0
- package/server/compact.mjs +623 -0
- package/server/edit-args.mjs +67 -0
- package/server/fuzzy.mjs +57 -0
- package/server/launch-decision.mjs +26 -0
- package/server/measure.mjs +320 -0
- package/server/pdf.mjs +185 -0
- package/server/pdf2png.ps1 +99 -0
- package/server/server.mjs +3797 -0
- package/server/video.mjs +857 -0
- package/setup.mjs +223 -0
- package/skills/eplan-annotations/SKILL.md +55 -0
- package/skills/eplan-drawing/SKILL.md +206 -0
- package/skills/eplan-project/SKILL.md +41 -0
- package/skills/eplan-review/SKILL.md +80 -0
- package/skills/eplan-symbols/SKILL.md +142 -0
- package/test/check-docs.mjs +106 -0
- package/test/foreground.ps1 +21 -0
- package/test/smoke-all.mjs +229 -0
|
@@ -0,0 +1,3797 @@
|
|
|
1
|
+
// EPLAN 绘图 MCP 服务。
|
|
2
|
+
//
|
|
3
|
+
// 这个进程本身不懂 EPLAN:它只把工具调用翻译成桥接器(EplanBridge.exe)能读的
|
|
4
|
+
// 行协议,桥接器再用 .NET Remoting 把请求送进运行中的 EPLAN 进程。
|
|
5
|
+
// 真正的绘图逻辑在 native/host/src/ 下,跑在 EPLAN 内部。
|
|
6
|
+
//
|
|
7
|
+
// MCP (stdio) ◀──▶ server.mjs ◀──▶ EplanBridge.exe ◀──▶ EPLAN.exe
|
|
8
|
+
//
|
|
9
|
+
import { McpServer } from '@modelcontextprotocol/server'
|
|
10
|
+
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio'
|
|
11
|
+
import { execFileSync, spawn, spawnSync } from 'node:child_process'
|
|
12
|
+
import { tmpdir } from 'node:os'
|
|
13
|
+
import { mkdirSync, readdirSync, statSync } from 'node:fs'
|
|
14
|
+
import { appendFileSync, copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
15
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
16
|
+
import { fileURLToPath } from 'node:url'
|
|
17
|
+
import { randomUUID } from 'node:crypto'
|
|
18
|
+
import z from 'zod'
|
|
19
|
+
// 载荷收敛层:只改「回给模型的形状」,不碰任何 EPLAN 行为。
|
|
20
|
+
import { compactInspect, geometryProblems, appearanceReport, digest, RepeatMemo } from './compact.mjs'
|
|
21
|
+
import { closestSymbolNames } from './fuzzy.mjs'
|
|
22
|
+
import { decideLaunch } from './launch-decision.mjs'
|
|
23
|
+
import { normalizeEditArgs } from './edit-args.mjs'
|
|
24
|
+
|
|
25
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
26
|
+
const root = resolve(here, '..')
|
|
27
|
+
|
|
28
|
+
// 桥接器每次都编译成带时间戳的新文件(跑起来会被占用,同名覆盖必然失败),
|
|
29
|
+
// 所以启动时扫一遍目录取最新的那个。
|
|
30
|
+
function newestBridge() {
|
|
31
|
+
const dir = join(root, 'native', 'bridge', 'bin')
|
|
32
|
+
try {
|
|
33
|
+
const candidates = readdirSync(dir)
|
|
34
|
+
.filter((name) => /^EplanBridge.*\.exe$/i.test(name))
|
|
35
|
+
.map((name) => ({ name, time: statSync(join(dir, name)).mtimeMs }))
|
|
36
|
+
.sort((a, b) => b.time - a.time)
|
|
37
|
+
if (candidates.length > 0) return join(dir, candidates[0].name)
|
|
38
|
+
} catch {
|
|
39
|
+
// 目录不存在或读不了,退回约定名,让后面的启动报错带上下文。
|
|
40
|
+
}
|
|
41
|
+
return join(dir, 'EplanBridge.exe')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const DEFAULTS = {
|
|
45
|
+
bridgeExe: newestBridge(),
|
|
46
|
+
eplanExe: 'D:\\EPLAN\\Platform\\2.9.4\\Bin\\Eplan.exe',
|
|
47
|
+
eplanVariant: 'Electric P8',
|
|
48
|
+
symbolLibrary: 'GB_symbol',
|
|
49
|
+
// dark:把 EPLAN 的打印配色换成用户屏幕上的深色方案(黑底/黄符号/红导线/浅色图框)。
|
|
50
|
+
renderTheme: 'dark',
|
|
51
|
+
requestTimeoutMs: 290000,
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function loadConfig() {
|
|
55
|
+
// 配置放三个地方,按优先级找:
|
|
56
|
+
// 1. EPLAN_MCP_CONFIG —— 测试用,指一份假配置(比如故意给个不存在的桥接器路径),
|
|
57
|
+
// 验证「EPLAN 不可达时经验库仍然可用」。平时不设这个变量。
|
|
58
|
+
// 2. %LOCALAPPDATA%\eplan-mcp\eplan.config.json —— setup.mjs 写在用户目录里。
|
|
59
|
+
// 包目录会被 pnpm/npm 在升级时整体替换,写在那儿的话升一次级就得重跑 setup。
|
|
60
|
+
// 3. 包内的 server/eplan.config.json —— 老装法(0.12 及以前)与手工调试用。
|
|
61
|
+
const env = process.env.EPLAN_MCP_CONFIG
|
|
62
|
+
const userFile = process.env.LOCALAPPDATA
|
|
63
|
+
? join(process.env.LOCALAPPDATA, 'eplan-mcp', 'eplan.config.json')
|
|
64
|
+
: null
|
|
65
|
+
const legacyFile = join(here, 'eplan.config.json')
|
|
66
|
+
const file = [env, userFile, legacyFile].find((path) => path && existsSync(path))
|
|
67
|
+
if (!file) return { ...DEFAULTS }
|
|
68
|
+
try {
|
|
69
|
+
return { ...DEFAULTS, ...JSON.parse(readFileSync(file, 'utf8')) }
|
|
70
|
+
} catch (error) {
|
|
71
|
+
process.stderr.write(`[eplan-mcp] ${file} 解析失败,使用默认值: ${error.message}\n`)
|
|
72
|
+
return { ...DEFAULTS }
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const config = loadConfig()
|
|
77
|
+
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
// 经验库:本地文件,**不经过 EPLAN**。
|
|
80
|
+
//
|
|
81
|
+
// 为什么不放在宿主 DLL 里:`lesson` 原先走 桥接器 → EPLAN 宿主,EPLAN 没开就既读不到
|
|
82
|
+
// 也写不进。而 EPLAN 崩溃、被模态框卡死这两种最需要把教训记下来的时刻,恰恰就是它
|
|
83
|
+
// 不在正常状态的时候 —— 把经验库绑在 EPLAN 上,等于在最需要它的时候掉链子。
|
|
84
|
+
//
|
|
85
|
+
// 路径与宿主的 Paths.cs 保持一致:%LOCALAPPDATA%\eplan-mcp\knowledge\notes.jsonl。
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
const KNOWLEDGE_DIR = (() => {
|
|
88
|
+
const base = process.env.LOCALAPPDATA
|
|
89
|
+
const dir = base
|
|
90
|
+
? join(base, 'eplan-mcp', 'knowledge')
|
|
91
|
+
: join(tmpdir(), 'eplan-mcp', 'knowledge')
|
|
92
|
+
try {
|
|
93
|
+
mkdirSync(dir, { recursive: true })
|
|
94
|
+
} catch {
|
|
95
|
+
// 建不出来就让后面的读写自己报错,那里有更具体的上下文。
|
|
96
|
+
}
|
|
97
|
+
return dir
|
|
98
|
+
})()
|
|
99
|
+
|
|
100
|
+
/** 配置根目录:%LOCALAPPDATA%\eplan-mcp。给「用户能直接打开」的图片副本用。 */
|
|
101
|
+
function configDir() {
|
|
102
|
+
const base = process.env.LOCALAPPDATA
|
|
103
|
+
return base ? join(base, 'eplan-mcp') : join(tmpdir(), 'eplan-mcp')
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---------------------------------------------------------------------------
|
|
107
|
+
// 多用户冲突护栏。
|
|
108
|
+
//
|
|
109
|
+
// 2026-11-20 实测:同一个 Windows 用户开两个 EPLAN 实例(PID 33496 开 变频器控制、
|
|
110
|
+
// PID 12164 开 test),第二个实例再去开第一个实例的项目时,EPLAN 弹一个
|
|
111
|
+
// 「多用户冲突 / 数据库被另一用户单独锁定」的**模态框**。模态框会挡住 EPLAN 的
|
|
112
|
+
// 消息循环,MCP 调用只能干等到 290 秒超时,用户看到的现象是「卡死」。
|
|
113
|
+
//
|
|
114
|
+
// 桥接器(native\bridge\src\Program.cs:342-361)拿到多台 server 时只按 "P8" 挑第一个,
|
|
115
|
+
// 挑中哪个实例不确定,所以这种冲突会随机复发。这里在 open_project 之前先做两件
|
|
116
|
+
// 能确定的事:
|
|
117
|
+
// 1) 问当前连着的这个实例:项目是不是已经开着(开着就直接复用,不再开);
|
|
118
|
+
// 2) 看项目的 .edb 目录里 *.lck 是否还被别的进程握着 —— EPLAN 打开项目时会一直
|
|
119
|
+
// 握着这些锁文件(判定方法见下面 edbLockedByOther 的注释,别用 fs.open)。
|
|
120
|
+
// .lck 被占 + 本机不止一个 EPLAN ⇒ 再开必弹框,提前把话说清楚,别让调用等 290 秒。
|
|
121
|
+
//
|
|
122
|
+
// 注意:这里**不碰**锁文件本身,也不去杀进程 —— 只判断、只报错。
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
const DEFAULT_PROJECT_DIR = 'C:\\Users\\Public\\EPLAN\\Data\\项目\\Company name'
|
|
126
|
+
|
|
127
|
+
let eplanProcessCache = { at: 0, ids: [] }
|
|
128
|
+
|
|
129
|
+
/** 本机正在跑的 EPLAN.exe 进程号。tasklist 输出是纯 ASCII,绕开中文编码问题。 */
|
|
130
|
+
function eplanProcessIds() {
|
|
131
|
+
if (process.platform !== 'win32') return []
|
|
132
|
+
const now = Date.now()
|
|
133
|
+
if (now - eplanProcessCache.at < 5000) return eplanProcessCache.ids
|
|
134
|
+
let ids = []
|
|
135
|
+
try {
|
|
136
|
+
const out = execFileSync('tasklist', ['/NH', '/FO', 'CSV', '/FI', 'IMAGENAME eq EPLAN.exe'], {
|
|
137
|
+
encoding: 'utf8',
|
|
138
|
+
windowsHide: true,
|
|
139
|
+
timeout: 5000,
|
|
140
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
141
|
+
})
|
|
142
|
+
ids = String(out)
|
|
143
|
+
.split(/\r?\n/)
|
|
144
|
+
.map((line) => line.match(/^"EPLAN\.exe","(\d+)"/i))
|
|
145
|
+
.filter((match) => match !== null)
|
|
146
|
+
.map((match) => Number(match[1]))
|
|
147
|
+
} catch {
|
|
148
|
+
ids = []
|
|
149
|
+
}
|
|
150
|
+
eplanProcessCache = { at: now, ids }
|
|
151
|
+
return ids
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** 项目名/路径 → .elk 绝对路径(和宿主的默认目录保持一致)。 */
|
|
155
|
+
function projectElkPath(args) {
|
|
156
|
+
if (args.path) return resolve(args.path)
|
|
157
|
+
return resolve(args.dir ?? DEFAULT_PROJECT_DIR, `${args.name}.elk`)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 同名 .edb 目录:EPLAN 的项目数据库,锁文件都在里面。 */
|
|
161
|
+
function projectEdbDir(elkPath) {
|
|
162
|
+
const name = basename(elkPath).replace(/\.elk$/i, '')
|
|
163
|
+
return join(dirname(elkPath), `${name}.edb`)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 项目数据库的锁文件是否已经被别的进程打开。
|
|
168
|
+
*
|
|
169
|
+
* 不能拿 Node 的 fs.open 来判断:libuv 一律以「共享读写」打开,而 EPLAN 打开 .lck
|
|
170
|
+
* 时虽然也允许别人共享读,但 .NET 默认的 FileShare.Read 会因为「对方持有写权限」
|
|
171
|
+
* 而被拒 —— 两种判定相反的结论。真正稳定的判据是 FileShare.None:只要还有**任何**
|
|
172
|
+
* 进程握着这个文件,独占打开就必失败。Node 的 fs 没有 share 参数,所以借一次
|
|
173
|
+
* PowerShell/.NET 来问,脚本用 -EncodedCommand 传(避开中文路径的编码问题),
|
|
174
|
+
* 输出只有 FREE / LOCKED:... 这种 ASCII。
|
|
175
|
+
*
|
|
176
|
+
* 返回 true=被占用,false=没被占用,null=问不出来(目录不存在/超时)。
|
|
177
|
+
*/
|
|
178
|
+
function edbLockedByOther(elkPath) {
|
|
179
|
+
const dir = projectEdbDir(elkPath)
|
|
180
|
+
if (!existsSync(dir)) return null
|
|
181
|
+
const script = [
|
|
182
|
+
"$ErrorActionPreference='SilentlyContinue'",
|
|
183
|
+
`$dir='${dir.replace(/'/g, "''")}'`,
|
|
184
|
+
'$held=@()',
|
|
185
|
+
'foreach ($f in Get-ChildItem -LiteralPath $dir -Filter *.lck -Force) {',
|
|
186
|
+
" try { $fs=[System.IO.File]::Open($f.FullName,'Open','ReadWrite','None'); $fs.Close() }",
|
|
187
|
+
' catch { $held += $f.Name }',
|
|
188
|
+
'}',
|
|
189
|
+
"if ($held.Count -gt 0) { 'LOCKED:' + ($held -join ',') } else { 'FREE' }",
|
|
190
|
+
].join('\n')
|
|
191
|
+
try {
|
|
192
|
+
const encoded = Buffer.from(script, 'utf16le').toString('base64')
|
|
193
|
+
const out = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], {
|
|
194
|
+
encoding: 'utf8',
|
|
195
|
+
windowsHide: true,
|
|
196
|
+
timeout: 20000,
|
|
197
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
198
|
+
})
|
|
199
|
+
const text = String(out.stdout ?? '')
|
|
200
|
+
if (text.includes('LOCKED:')) return true
|
|
201
|
+
if (text.trim().endsWith('FREE')) return false
|
|
202
|
+
return null
|
|
203
|
+
} catch {
|
|
204
|
+
return null
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function samePath(a, b) {
|
|
209
|
+
try {
|
|
210
|
+
return resolve(a).toLowerCase() === resolve(b).toLowerCase()
|
|
211
|
+
} catch {
|
|
212
|
+
return false
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 开项目之前先问清楚:这个项目是不是已经在这个实例里开着?是不是被别的实例占着?
|
|
218
|
+
* 返回 { alreadyOpenHere } | { conflict } | {}
|
|
219
|
+
*/
|
|
220
|
+
async function projectPreflight(elkPath) {
|
|
221
|
+
let openProjects = []
|
|
222
|
+
try {
|
|
223
|
+
const status = await callBridge('status', {}, { timeoutMs: 20000 })
|
|
224
|
+
if (Array.isArray(status?.openProjects)) openProjects = status.openProjects
|
|
225
|
+
} catch {
|
|
226
|
+
// EPLAN 没开、或被别的模态框挡着:交给 project_open 自己报错,这里不抢答。
|
|
227
|
+
return {}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (openProjects.some((item) => item?.path && samePath(item.path, elkPath))) {
|
|
231
|
+
return { alreadyOpenHere: true }
|
|
232
|
+
}
|
|
233
|
+
if (!edbLockedByOther(elkPath)) return {}
|
|
234
|
+
|
|
235
|
+
const ids = eplanProcessIds()
|
|
236
|
+
// 只有本机确实不止一个 EPLAN 时才判定成冲突:单个实例 + 锁被占更像残留句柄,
|
|
237
|
+
// 那种情况让 EPLAN 自己去处理,不要拿一句「被占用」把人挡住。
|
|
238
|
+
if (ids.length < 2) return { lockedButAlone: true }
|
|
239
|
+
return { conflict: true, pids: ids }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function openProject(args) {
|
|
243
|
+
const elkPath = projectElkPath(args)
|
|
244
|
+
const preflight = await projectPreflight(elkPath)
|
|
245
|
+
|
|
246
|
+
if (preflight.alreadyOpenHere) {
|
|
247
|
+
return ok({
|
|
248
|
+
ok: true,
|
|
249
|
+
alreadyOpen: true,
|
|
250
|
+
path: elkPath,
|
|
251
|
+
note: '这个项目已经在当前 EPLAN 实例里打开了,不用再开;直接切页或读页就行。',
|
|
252
|
+
})
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (preflight.conflict) {
|
|
256
|
+
throw fail(
|
|
257
|
+
'PROJECT_LOCKED_BY_OTHER_INSTANCE',
|
|
258
|
+
`项目 ${basename(elkPath)} 现在被另一个 EPLAN 实例占着(本机有 ${preflight.pids.length} 个 EPLAN:pid ${preflight.pids.join('、')})。` +
|
|
259
|
+
'这时候再开必然弹「多用户冲突 / 数据库被另一用户单独锁定」,模态框会把后面的调用一起卡死,所以没有去开。',
|
|
260
|
+
'三条路选一条:① 就在已经打开它的那个 EPLAN 窗口里干活,别在这个实例里再开;' +
|
|
261
|
+
'② 关掉多余的 EPLAN,只留一个实例;' +
|
|
262
|
+
'③ 如果那个实例是用「专有」编辑模式打开的,在那里关掉项目、打开时把编辑模式选成「默认」重开 —— ' +
|
|
263
|
+
'EPLAN 的多用户共用只在「默认」模式下成立,「专有」等于独占,别的实例一律进不来。',
|
|
264
|
+
)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (preflight.lockedButAlone) {
|
|
268
|
+
process.stderr.write(
|
|
269
|
+
`[eplan-mcp] ${basename(elkPath)} 的 .lck 被占着,但本机只有一个 EPLAN;照常尝试打开。\n`,
|
|
270
|
+
)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return invoke('project_open', { name: args.name, path: args.path, dir: args.dir })
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const NOTES_FILE = join(KNOWLEDGE_DIR, 'notes.jsonl')
|
|
277
|
+
|
|
278
|
+
// 旧版本把经验放在 %TEMP% 下,而临时目录会被磁盘清理扫掉 —— 搬过来,旧文件不删。
|
|
279
|
+
function migrateNotes() {
|
|
280
|
+
try {
|
|
281
|
+
if (existsSync(NOTES_FILE)) return
|
|
282
|
+
const legacy = join(tmpdir(), 'eplan-mcp', 'knowledge', 'notes.jsonl')
|
|
283
|
+
if (!existsSync(legacy)) return
|
|
284
|
+
writeFileSync(NOTES_FILE, readFileSync(legacy))
|
|
285
|
+
} catch {
|
|
286
|
+
// 迁移是尽力而为,失败也只是少了几条旧记录,不该让工具调用报错。
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
migrateNotes()
|
|
290
|
+
|
|
291
|
+
// 只读尾部:经验库只增不减,读全量迟早会把一次 status 拖慢。
|
|
292
|
+
const NOTES_SCAN_LIMIT = 500
|
|
293
|
+
|
|
294
|
+
function readNotes() {
|
|
295
|
+
let text
|
|
296
|
+
try {
|
|
297
|
+
if (!existsSync(NOTES_FILE)) return { entries: [], truncated: false }
|
|
298
|
+
text = readFileSync(NOTES_FILE, 'utf8')
|
|
299
|
+
} catch {
|
|
300
|
+
return { entries: [], truncated: false }
|
|
301
|
+
}
|
|
302
|
+
const lines = text.split('\n').filter((line) => line.trim().length > 0)
|
|
303
|
+
const truncated = lines.length > NOTES_SCAN_LIMIT
|
|
304
|
+
const slice = truncated ? lines.slice(-NOTES_SCAN_LIMIT) : lines
|
|
305
|
+
const entries = []
|
|
306
|
+
for (const line of slice) {
|
|
307
|
+
try {
|
|
308
|
+
entries.push(JSON.parse(line))
|
|
309
|
+
} catch {
|
|
310
|
+
// 坏行跳过:一行写坏不该让整个经验库读不出来。
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return { entries, truncated }
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function listNotes({ query, limit } = {}) {
|
|
317
|
+
const { entries, truncated } = readNotes()
|
|
318
|
+
const needle = query && String(query).trim() ? String(query).trim().toLowerCase() : null
|
|
319
|
+
const max = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 200) : 20
|
|
320
|
+
|
|
321
|
+
const matched = []
|
|
322
|
+
for (let i = entries.length - 1; i >= 0 && matched.length < max; i -= 1) {
|
|
323
|
+
const entry = entries[i]
|
|
324
|
+
if (needle) {
|
|
325
|
+
const hay = [
|
|
326
|
+
entry?.text ?? '',
|
|
327
|
+
entry?.kind ?? '',
|
|
328
|
+
...(Array.isArray(entry?.tags) ? entry.tags : []),
|
|
329
|
+
]
|
|
330
|
+
.join(' ')
|
|
331
|
+
.toLowerCase()
|
|
332
|
+
if (!hay.includes(needle)) continue
|
|
333
|
+
}
|
|
334
|
+
matched.push(entry)
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
return {
|
|
338
|
+
...(needle ? { query: needle } : {}),
|
|
339
|
+
total: entries.length,
|
|
340
|
+
returned: matched.length,
|
|
341
|
+
newestFirst: true,
|
|
342
|
+
truncated,
|
|
343
|
+
notes: matched,
|
|
344
|
+
file: NOTES_FILE,
|
|
345
|
+
...(entries.length === 0
|
|
346
|
+
? { note: '还没有记录。踩到坑、或者验证出一条可行的做法时,用 lesson(action="add") 记一条。' }
|
|
347
|
+
: {}),
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function addNote({ text, kind, tags, project, page, scope, brief }) {
|
|
352
|
+
const body = typeof text === 'string' ? text.trim() : ''
|
|
353
|
+
if (body.length === 0) {
|
|
354
|
+
throw fail(
|
|
355
|
+
'BAD_ARGUMENT',
|
|
356
|
+
'text 不能为空。',
|
|
357
|
+
'写一句具体的话,比如「page_open 会抢焦点,自动出图不要用它」。',
|
|
358
|
+
)
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const entry = {
|
|
362
|
+
id: `n${Date.now()}${Math.floor(Math.random() * 1000)}`,
|
|
363
|
+
at: new Date().toISOString(),
|
|
364
|
+
text: body,
|
|
365
|
+
kind: kind || 'pitfall',
|
|
366
|
+
}
|
|
367
|
+
if (Array.isArray(tags)) {
|
|
368
|
+
const clean = tags.map((tag) => String(tag).trim()).filter((tag) => tag.length > 0)
|
|
369
|
+
if (clean.length > 0) entry.tags = clean
|
|
370
|
+
}
|
|
371
|
+
// scope 决定这条经验跟着谁走:general 对所有项目生效,project 只对 project 有用,
|
|
372
|
+
// preference 是要进用户偏好表的(旧文件里没有这个字段,读的时候按 general 兜底)。
|
|
373
|
+
const scopeValue = ['general', 'project', 'preference'].includes(scope) ? scope : project ? 'project' : 'general'
|
|
374
|
+
entry.scope = scopeValue
|
|
375
|
+
const briefText = typeof brief === 'string' ? brief.trim() : ''
|
|
376
|
+
entry.brief = (briefText || body).slice(0, 60)
|
|
377
|
+
if (project) entry.project = project
|
|
378
|
+
if (page) entry.page = page
|
|
379
|
+
|
|
380
|
+
try {
|
|
381
|
+
appendFileSync(NOTES_FILE, `${JSON.stringify(entry)}\n`, 'utf8')
|
|
382
|
+
} catch (error) {
|
|
383
|
+
// 静默失败最坏:模型以为记下来了,下次会话什么也读不到。
|
|
384
|
+
throw fail(
|
|
385
|
+
'NOTES_WRITE_FAILED',
|
|
386
|
+
`经验没有写进文件:${error.message}`,
|
|
387
|
+
`目标文件是 ${NOTES_FILE}。检查目录权限,或者这个位置是不是只读的。`,
|
|
388
|
+
)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
return { saved: true, entry, file: NOTES_FILE }
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// status 只带最近几条,够模型一眼看到前人的教训,又不至于把上下文顶掉。
|
|
395
|
+
// 只回 brief(≤60 字):经验越来越多,把全文塞进每次 status 是拿上下文换安慰。
|
|
396
|
+
function lessonsForStatus() {
|
|
397
|
+
const { total, notes, file } = listNotes({ limit: 5 })
|
|
398
|
+
return {
|
|
399
|
+
total,
|
|
400
|
+
recent: notes.map((entry) => ({
|
|
401
|
+
at: entry?.at ?? null,
|
|
402
|
+
kind: entry?.kind ?? 'pitfall',
|
|
403
|
+
scope: entry?.scope ?? 'general',
|
|
404
|
+
brief: entry?.brief || String(entry?.text ?? '').slice(0, 60),
|
|
405
|
+
})),
|
|
406
|
+
file,
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// ---------------------------------------------------------------------------
|
|
411
|
+
// 用户偏好:和「经验」分开存。
|
|
412
|
+
//
|
|
413
|
+
// 经验是「这条路走过,通/不通」;偏好是「这个人要什么」—— 窄版优先、画完必须
|
|
414
|
+
// 呈现、标注颜色怎么区分。两者混在 notes.jsonl 里,模型检索到的永远是最近 5 条
|
|
415
|
+
// 踩坑记录,偏好被埋掉。所以单独一份 JSON,每次 status 都带在前 10 条。
|
|
416
|
+
// ---------------------------------------------------------------------------
|
|
417
|
+
const PREFS_FILE = join(KNOWLEDGE_DIR, 'preferences.json')
|
|
418
|
+
const PREFS_MAX = 40
|
|
419
|
+
|
|
420
|
+
function readPreferences() {
|
|
421
|
+
try {
|
|
422
|
+
if (!existsSync(PREFS_FILE)) return []
|
|
423
|
+
const parsed = JSON.parse(readFileSync(PREFS_FILE, 'utf8'))
|
|
424
|
+
return Array.isArray(parsed?.entries) ? parsed.entries : []
|
|
425
|
+
} catch {
|
|
426
|
+
// 文件写坏就当没有:偏好读不出来不该让 status 失败。
|
|
427
|
+
return []
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function writePreferences(entries) {
|
|
432
|
+
const body = {
|
|
433
|
+
version: 1,
|
|
434
|
+
updatedAt: new Date().toISOString(),
|
|
435
|
+
file: PREFS_FILE,
|
|
436
|
+
entries,
|
|
437
|
+
}
|
|
438
|
+
try {
|
|
439
|
+
writeFileSync(PREFS_FILE, `${JSON.stringify(body, null, 2)}\n`, 'utf8')
|
|
440
|
+
} catch (error) {
|
|
441
|
+
throw fail(
|
|
442
|
+
'PREFS_WRITE_FAILED',
|
|
443
|
+
`偏好没有写进文件:${error.message}`,
|
|
444
|
+
`目标文件是 ${PREFS_FILE}。检查目录权限或磁盘状态。`,
|
|
445
|
+
)
|
|
446
|
+
}
|
|
447
|
+
return entries
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function addPreference({ text, source, weight, tags }) {
|
|
451
|
+
const body = typeof text === 'string' ? text.trim() : ''
|
|
452
|
+
if (body.length === 0) {
|
|
453
|
+
throw fail('BAD_ARGUMENT', 'preference 的 text 不能为空。', '写一句用户明确表达过的偏好,例如「做完一定要切到界面给我看」。')
|
|
454
|
+
}
|
|
455
|
+
const entries = readPreferences()
|
|
456
|
+
const index = entries.findIndex((entry) => String(entry?.text ?? '').trim() === body)
|
|
457
|
+
const entry = {
|
|
458
|
+
id: index >= 0 ? entries[index].id : `p${Date.now()}${Math.floor(Math.random() * 1000)}`,
|
|
459
|
+
text: body,
|
|
460
|
+
source: source || 'user',
|
|
461
|
+
weight: Number.isInteger(weight) && weight >= 1 && weight <= 10 ? weight : 5,
|
|
462
|
+
at: new Date().toISOString(),
|
|
463
|
+
}
|
|
464
|
+
if (Array.isArray(tags)) {
|
|
465
|
+
const clean = tags.map((tag) => String(tag).trim()).filter((tag) => tag.length > 0)
|
|
466
|
+
if (clean.length > 0) entry.tags = clean
|
|
467
|
+
}
|
|
468
|
+
if (index >= 0) entries[index] = entry
|
|
469
|
+
else entries.push(entry)
|
|
470
|
+
const kept = entries.slice(-PREFS_MAX)
|
|
471
|
+
writePreferences(kept)
|
|
472
|
+
return { saved: true, entry, total: kept.length, file: PREFS_FILE }
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function preferencesForStatus(limit = 10) {
|
|
476
|
+
const entries = readPreferences()
|
|
477
|
+
return {
|
|
478
|
+
total: entries.length,
|
|
479
|
+
// 高权重在前,同权重新的在前。
|
|
480
|
+
entries: [...entries]
|
|
481
|
+
.sort((a, b) => (b?.weight ?? 5) - (a?.weight ?? 5) || String(b?.at ?? '').localeCompare(String(a?.at ?? '')))
|
|
482
|
+
.slice(0, limit),
|
|
483
|
+
file: PREFS_FILE,
|
|
484
|
+
...(entries.length === 0
|
|
485
|
+
? { note: '还没有记录用户偏好。用户表达过明确的做事要求时,用 lesson(action="prefer") 记一条。' }
|
|
486
|
+
: {}),
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// ---------------------------------------------------------------------------
|
|
491
|
+
// 项目台账:多页 / 多会话并行时,先记「谁负责哪页」,再来画。
|
|
492
|
+
//
|
|
493
|
+
// 为什么放在本地文件而不是 EPLAN 里:台账要在 EPLAN 卡死、项目没开的时候也能读;
|
|
494
|
+
// 而且 EPLAN 的桥已经用命名 mutex 把调用串行了,这里只解决「谁负责哪页、画到哪」。
|
|
495
|
+
// ---------------------------------------------------------------------------
|
|
496
|
+
const PROJECTS_DIR = join(KNOWLEDGE_DIR, '..', 'projects')
|
|
497
|
+
|
|
498
|
+
function projectDir(project) {
|
|
499
|
+
const name = String(project ?? '').trim()
|
|
500
|
+
if (name.length === 0) {
|
|
501
|
+
throw fail('BAD_ARGUMENT', '台账动作需要 project。', '传项目名,例如 "test"。')
|
|
502
|
+
}
|
|
503
|
+
// 项目名会变成目录名:把 Windows 不允许的字符换掉,防止路径穿越。
|
|
504
|
+
return join(PROJECTS_DIR, name.replace(/[\\/:*?"<>|]/g, '_'))
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function readPlan(project) {
|
|
508
|
+
const file = join(projectDir(project), 'plan.jsonl')
|
|
509
|
+
try {
|
|
510
|
+
if (!existsSync(file)) return { entries: [], file }
|
|
511
|
+
const entries = []
|
|
512
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
513
|
+
if (!line.trim()) continue
|
|
514
|
+
try {
|
|
515
|
+
entries.push(JSON.parse(line))
|
|
516
|
+
} catch {
|
|
517
|
+
// 坏行跳过:一行写坏不该让整个台账读不出来。
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
return { entries, file }
|
|
521
|
+
} catch {
|
|
522
|
+
return { entries: [], file }
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function writePlan(project, items) {
|
|
527
|
+
const dir = projectDir(project)
|
|
528
|
+
mkdirSync(dir, { recursive: true })
|
|
529
|
+
const file = join(dir, 'plan.jsonl')
|
|
530
|
+
const now = new Date().toISOString()
|
|
531
|
+
const entries = items.map((item, index) => {
|
|
532
|
+
const row = item && typeof item === 'object' ? { ...item } : { page: String(item) }
|
|
533
|
+
return {
|
|
534
|
+
index,
|
|
535
|
+
page: row.page ?? row.name ?? `#${index + 1}`,
|
|
536
|
+
title: row.title ?? '',
|
|
537
|
+
status: row.status ?? 'todo',
|
|
538
|
+
owner: row.owner ?? '',
|
|
539
|
+
note: row.note ?? '',
|
|
540
|
+
updatedAt: now,
|
|
541
|
+
}
|
|
542
|
+
})
|
|
543
|
+
writeFileSync(file, entries.map((entry) => JSON.stringify(entry)).join('\n') + '\n', 'utf8')
|
|
544
|
+
return { saved: true, count: entries.length, file, entries }
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function readLocks(project) {
|
|
548
|
+
const file = join(projectDir(project), 'lock.json')
|
|
549
|
+
try {
|
|
550
|
+
if (!existsSync(file)) return { pages: {}, file }
|
|
551
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
552
|
+
return { pages: parsed?.pages ?? {}, file }
|
|
553
|
+
} catch {
|
|
554
|
+
return { pages: {}, file }
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function writeLocks(project, pages) {
|
|
559
|
+
const dir = projectDir(project)
|
|
560
|
+
mkdirSync(dir, { recursive: true })
|
|
561
|
+
const file = join(dir, 'lock.json')
|
|
562
|
+
writeFileSync(file, `${JSON.stringify({ updatedAt: new Date().toISOString(), pages }, null, 2)}\n`, 'utf8')
|
|
563
|
+
return file
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** 占位的有效期:会话崩了或被遗忘时,六小时后自动失效,不让人永久卡死。 */
|
|
567
|
+
const LOCK_TTL_MS = 6 * 3600 * 1000
|
|
568
|
+
|
|
569
|
+
const lockAge = (holder) => {
|
|
570
|
+
const at = Date.parse(holder?.at ?? '')
|
|
571
|
+
return Number.isFinite(at) ? Date.now() - at : Infinity
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function claimPage({ project, page, owner }) {
|
|
575
|
+
if (!page) throw fail('BAD_ARGUMENT', 'claim 需要 page。', '传页名,例如 "=MI/12"。')
|
|
576
|
+
const locks = readLocks(project)
|
|
577
|
+
const holder = locks.pages[page]
|
|
578
|
+
// 过期的占位不算占:否则一次崩掉的会话会把这一页永久锁住。
|
|
579
|
+
const stale = holder !== undefined && lockAge(holder) > LOCK_TTL_MS
|
|
580
|
+
if (holder && holder.owner && owner && holder.owner !== owner && !stale) {
|
|
581
|
+
throw fail(
|
|
582
|
+
'PAGE_LOCKED',
|
|
583
|
+
`页「${page}」正被 ${holder.owner} 占着(${holder.at})。`,
|
|
584
|
+
'换一页,或等对方 release;不要两个会话同时改同一页。',
|
|
585
|
+
)
|
|
586
|
+
}
|
|
587
|
+
locks.pages[page] = { owner: owner || 'unknown', at: new Date().toISOString() }
|
|
588
|
+
const file = writeLocks(project, locks.pages)
|
|
589
|
+
return { claimed: true, page, owner: locks.pages[page].owner, file, ...(stale ? { tookOverStale: page } : {}) }
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function releasePage({ project, page }) {
|
|
593
|
+
if (!page) throw fail('BAD_ARGUMENT', 'release 需要 page。', '传页名,例如 "=MI/12"。')
|
|
594
|
+
const locks = readLocks(project)
|
|
595
|
+
const existed = Boolean(locks.pages[page])
|
|
596
|
+
delete locks.pages[page]
|
|
597
|
+
const file = writeLocks(project, locks.pages)
|
|
598
|
+
return { released: existed, page, file }
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** 只返回没过期的占位,brief 用。 */
|
|
602
|
+
function activeLocks(project) {
|
|
603
|
+
const locks = readLocks(project)
|
|
604
|
+
const live = {}
|
|
605
|
+
for (const [page, holder] of Object.entries(locks.pages ?? {})) {
|
|
606
|
+
if (lockAge(holder) > LOCK_TTL_MS) continue
|
|
607
|
+
live[page] = holder
|
|
608
|
+
}
|
|
609
|
+
return live
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* 改页/删页的占用门。
|
|
614
|
+
*
|
|
615
|
+
* 比 page_create 的 6 小时 TTL 短得多:建页撞车会让两边的整页定义互相覆盖,
|
|
616
|
+
* 而改页撞车的代价小(重画一次就行),所以只挡「20 分钟内还活着」的占位,
|
|
617
|
+
* 一个已经关掉的会话留下的旧占位不该把这一页锁半天。
|
|
618
|
+
* 传给 page_edit / page_delete 的 force=true 可以明确接手。
|
|
619
|
+
*/
|
|
620
|
+
const CLAIM_GUARD_MS = 20 * 60 * 1000
|
|
621
|
+
|
|
622
|
+
function claimGuard(project, page, { force = false } = {}) {
|
|
623
|
+
if (!project || !page) return null
|
|
624
|
+
const locks = readLocks(project)
|
|
625
|
+
const holder = locks.pages[page]
|
|
626
|
+
const mine = holder?.owner === ownerTag()
|
|
627
|
+
if (holder && !mine && !force && lockAge(holder) < CLAIM_GUARD_MS) {
|
|
628
|
+
const minutes = Math.max(1, Math.round(lockAge(holder) / 60000))
|
|
629
|
+
throw fail(
|
|
630
|
+
'CLAIMED',
|
|
631
|
+
`页「${page}」正被 ${holder.owner} 占着(${minutes} 分钟前)。`,
|
|
632
|
+
'改别的页,或确认那个会话已经结束后传 force=true 接手;不要两个会话同时改同一页。',
|
|
633
|
+
)
|
|
634
|
+
}
|
|
635
|
+
writeLocks(project, { ...locks.pages, [page]: { owner: ownerTag(), at: new Date().toISOString() } })
|
|
636
|
+
return { claimed: true, page, ...(holder && !mine ? { tookOverFrom: holder.owner } : {}) }
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// ---------------------------------------------------------------------------
|
|
640
|
+
// 桥接器进程:常驻一个子进程,按行收发 JSON。
|
|
641
|
+
// EPLAN 崩了或桥接器自己重启,下一次调用会重新拉起。
|
|
642
|
+
// ---------------------------------------------------------------------------
|
|
643
|
+
|
|
644
|
+
let bridge = null
|
|
645
|
+
let bridgeBuffer = ''
|
|
646
|
+
const pending = new Map()
|
|
647
|
+
|
|
648
|
+
function fail(code, message, detail) {
|
|
649
|
+
const error = new Error(message)
|
|
650
|
+
error.code = code
|
|
651
|
+
if (detail !== undefined) error.detail = detail
|
|
652
|
+
return error
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function stopBridge(reason) {
|
|
656
|
+
if (!bridge) return
|
|
657
|
+
const child = bridge
|
|
658
|
+
bridge = null
|
|
659
|
+
for (const [, entry] of pending) {
|
|
660
|
+
clearTimeout(entry.timer)
|
|
661
|
+
entry.reject(fail('BRIDGE_EXITED', `桥接器已退出(${reason}),本次调用中断`))
|
|
662
|
+
}
|
|
663
|
+
pending.clear()
|
|
664
|
+
try {
|
|
665
|
+
child.kill()
|
|
666
|
+
} catch {
|
|
667
|
+
// 已经死了,忽略。
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function startBridge() {
|
|
672
|
+
if (bridge) return bridge
|
|
673
|
+
if (!existsSync(config.bridgeExe)) {
|
|
674
|
+
throw fail(
|
|
675
|
+
'BRIDGE_MISSING',
|
|
676
|
+
`找不到桥接器:${config.bridgeExe}。请先运行 native\\bridge\\build.ps1 编译。`,
|
|
677
|
+
)
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const child = spawn(config.bridgeExe, [], {
|
|
681
|
+
cwd: dirname(config.bridgeExe),
|
|
682
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
683
|
+
windowsHide: true,
|
|
684
|
+
})
|
|
685
|
+
bridge = child
|
|
686
|
+
bridgeBuffer = ''
|
|
687
|
+
|
|
688
|
+
child.stdout.setEncoding('utf8')
|
|
689
|
+
child.stdout.on('data', (chunk) => {
|
|
690
|
+
bridgeBuffer += chunk
|
|
691
|
+
let index
|
|
692
|
+
while ((index = bridgeBuffer.indexOf('\n')) >= 0) {
|
|
693
|
+
const line = bridgeBuffer.slice(0, index).trim()
|
|
694
|
+
bridgeBuffer = bridgeBuffer.slice(index + 1)
|
|
695
|
+
if (!line) continue
|
|
696
|
+
let message
|
|
697
|
+
try {
|
|
698
|
+
message = JSON.parse(line)
|
|
699
|
+
} catch {
|
|
700
|
+
process.stderr.write(`[eplan-mcp] 桥接器输出了非 JSON 行: ${line.slice(0, 400)}\n`)
|
|
701
|
+
continue
|
|
702
|
+
}
|
|
703
|
+
const entry = pending.get(message.id)
|
|
704
|
+
if (!entry) continue
|
|
705
|
+
pending.delete(message.id)
|
|
706
|
+
clearTimeout(entry.timer)
|
|
707
|
+
if (message.ok) entry.resolve(message.result)
|
|
708
|
+
else {
|
|
709
|
+
const { code = 'EPLAN_ERROR', message: text = 'EPLAN 返回失败', detail } = message.error ?? {}
|
|
710
|
+
entry.reject(fail(code, text, detail))
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
})
|
|
714
|
+
|
|
715
|
+
child.stderr.setEncoding('utf8')
|
|
716
|
+
child.stderr.on('data', (chunk) => process.stderr.write(`[eplan-bridge] ${chunk}`))
|
|
717
|
+
child.on('exit', (code, signal) => stopBridge(signal ?? `exit ${code}`))
|
|
718
|
+
child.on('error', (error) => stopBridge(`spawn 失败: ${error.message}`))
|
|
719
|
+
|
|
720
|
+
return child
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function callBridge(op, args, options = {}) {
|
|
724
|
+
const child = startBridge()
|
|
725
|
+
const id = randomUUID()
|
|
726
|
+
const timeoutMs = options.timeoutMs ?? config.requestTimeoutMs
|
|
727
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
728
|
+
const timer = setTimeout(() => {
|
|
729
|
+
pending.delete(id)
|
|
730
|
+
rejectPromise(
|
|
731
|
+
fail(
|
|
732
|
+
'EPLAN_TIMEOUT',
|
|
733
|
+
`调用 ${op} 超过 ${Math.round(timeoutMs / 1000)} 秒没有返回。EPLAN 可能弹出了对话框或被占用,请切到 EPLAN 窗口检查后重试。`,
|
|
734
|
+
),
|
|
735
|
+
)
|
|
736
|
+
}, timeoutMs)
|
|
737
|
+
|
|
738
|
+
pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer })
|
|
739
|
+
child.stdin.write(`${JSON.stringify({ id, op, args })}\n`, (error) => {
|
|
740
|
+
if (!error) return
|
|
741
|
+
pending.delete(id)
|
|
742
|
+
clearTimeout(timer)
|
|
743
|
+
rejectPromise(fail('BRIDGE_WRITE_FAILED', `无法写入桥接器: ${error.message}`))
|
|
744
|
+
})
|
|
745
|
+
})
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// ---------------------------------------------------------------------------
|
|
749
|
+
// 工具结果的统一形状:文本块里放 JSON,失败走 MCP 的 isError。
|
|
750
|
+
// ---------------------------------------------------------------------------
|
|
751
|
+
|
|
752
|
+
function ok(result) {
|
|
753
|
+
// 紧凑序列化而不是 2 空格缩进:一页 inspect 的缩进部分实测占 56%
|
|
754
|
+
// (80,924 → 35,865 字符),对模型没有任何信息增益。
|
|
755
|
+
return { content: [{ type: 'text', text: JSON.stringify(result) }] }
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
function failed(op, error, note = null) {
|
|
759
|
+
return {
|
|
760
|
+
isError: true,
|
|
761
|
+
content: [
|
|
762
|
+
{
|
|
763
|
+
type: 'text',
|
|
764
|
+
// 紧凑序列化:错误体要能一眼读完,缩进在这里只有坏处。
|
|
765
|
+
text: JSON.stringify({
|
|
766
|
+
ok: false,
|
|
767
|
+
op,
|
|
768
|
+
code: error.code ?? 'UNKNOWN',
|
|
769
|
+
message: error.message,
|
|
770
|
+
...(error.detail === undefined ? {} : { detail: error.detail }),
|
|
771
|
+
...(note ?? {}),
|
|
772
|
+
}),
|
|
773
|
+
},
|
|
774
|
+
],
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// ---------------------------------------------------------------------------
|
|
779
|
+
// 同参数同错误第二次就明说「别再试了,换这个做法」。
|
|
780
|
+
//
|
|
781
|
+
// 2026-11-24 session-400917a2:同一个不存在的符号连撞 8 次,每次 300 ms、外加一整轮
|
|
782
|
+
// 重新规划。重试本身不贵,贵的是它每次都以为「这次也许行」。这段不改错误、不加限制,
|
|
783
|
+
// 只是把「你已经在这条死路上」说出来,并给出下一步该做什么。
|
|
784
|
+
// ---------------------------------------------------------------------------
|
|
785
|
+
const REPEAT_WINDOW_MS = 5 * 60 * 1000
|
|
786
|
+
const repeatTally = new Map()
|
|
787
|
+
|
|
788
|
+
const REPEAT_ADVICE = {
|
|
789
|
+
OBJECT_NOT_FOUND:
|
|
790
|
+
'对象不在了或标识变了:先 page_inspect{format:"structure", view:"list"} 取当前的 objectId / deviceTag 再动。'
|
|
791
|
+
+ '整页删掉重建过之后,旧标识一定失效。',
|
|
792
|
+
SYMBOL_NOT_FOUND:
|
|
793
|
+
'这个名字在库里不存在,重试同一个名字不会有不同结果:改用错误里给的 candidates,'
|
|
794
|
+
+ '或 symbol_catalog{action:"visual"} 把候选画出来用眼睛认。',
|
|
795
|
+
PAGE_EXISTS: '页已经存在:换一个页号,或直接在这页上 page_edit —— 不要再 create 同一个名字。',
|
|
796
|
+
EPLAN_BLOCKED_BY_DIALOG:
|
|
797
|
+
'框还压着 EPLAN,所有调用都会被挡回来:让用户切过去关掉(或按 Esc),回一句再继续。不要自己重试。',
|
|
798
|
+
BAD_ARGUMENT: '参数形状不对,照错误里给的例子重写一次,不要在原参数上小改后再试。',
|
|
799
|
+
PLACEMENT_NOT_FOUND: '页面上没有这个对象:先 page_inspect view="list",别凭记忆写 id。',
|
|
800
|
+
UNKNOWN_OP: '宿主不认识这个操作:EPLAN 里加载的是旧宿主,只能等 EPLAN 重启后再用。',
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function repeatNote(op, args, error) {
|
|
804
|
+
const code = error.code ?? 'UNKNOWN'
|
|
805
|
+
let key
|
|
806
|
+
try {
|
|
807
|
+
key = `${op}|${JSON.stringify(args ?? null)}`
|
|
808
|
+
} catch {
|
|
809
|
+
key = `${op}|?`
|
|
810
|
+
}
|
|
811
|
+
const now = Date.now()
|
|
812
|
+
const prev = repeatTally.get(key)
|
|
813
|
+
const same = prev && prev.code === code && now - prev.at < REPEAT_WINDOW_MS
|
|
814
|
+
const count = same ? prev.count + 1 : 1
|
|
815
|
+
repeatTally.set(key, { code, count, at: now })
|
|
816
|
+
if (repeatTally.size > 200) {
|
|
817
|
+
for (const [oldKey, row] of repeatTally) {
|
|
818
|
+
if (now - row.at > REPEAT_WINDOW_MS) repeatTally.delete(oldKey)
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
if (count < 2) return null
|
|
822
|
+
return {
|
|
823
|
+
repeat: count,
|
|
824
|
+
stopRetrying: true,
|
|
825
|
+
nextStep: REPEAT_ADVICE[code] ?? '换个做法:先用 page_inspect / status 看清现场,再决定改哪一步。',
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
async function invoke(op, args) {
|
|
830
|
+
try {
|
|
831
|
+
return ok(await callBridge(op, args))
|
|
832
|
+
} catch (error) {
|
|
833
|
+
return failed(op, error, repeatNote(op, args, error))
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// status 的特殊之处:EPLAN 没开时它不该整条失败。
|
|
838
|
+
//
|
|
839
|
+
// 「先看一眼环境」是每次开工的第一步,如果 EPLAN 恰好没运行就只回一个错误,
|
|
840
|
+
// 模型连这台机器之前踩过什么坑都看不到 —— 而经验库本来就不依赖 EPLAN。
|
|
841
|
+
// 所以这里把不可达也当成一种可回答的状态,附带经验一起返回。
|
|
842
|
+
/**
|
|
843
|
+
* 「EPLAN 没就绪」时按**真实错误码**给下一步。
|
|
844
|
+
*
|
|
845
|
+
* 为什么必须按码分派:2026-11-27 session-0d24b269 里 brief 返回的阻塞原因是
|
|
846
|
+
* HOST_NOT_INSTALLED(EPLAN 里根本没注册宿主),nextSteps[0] 却一律是 launch。
|
|
847
|
+
* 模型照着去 launch,拉起一个本来就开着的 EPLAN,什么也没修好 —— 分支给错的代价
|
|
848
|
+
* 是一整轮调用加一次误判。真正的修法在注册宿主(setup.mjs),不在 launch。
|
|
849
|
+
*
|
|
850
|
+
* 每个码的首步都是「这件事只能这样做」,不是「再试一次」:
|
|
851
|
+
* HOST_NOT_INSTALLED 注册宿主(要 EPLAN 开着,跑 setup.mjs)
|
|
852
|
+
* EPLAN_NOT_RUNNING 拉起 EPLAN(launch)
|
|
853
|
+
* BRIDGE_MISSING 桥接器没编译出来
|
|
854
|
+
* EPLAN_BLOCKED_BY_DIALOG / EPLAN_TIMEOUT 等用户关掉对话框
|
|
855
|
+
* NO_PROJECT 开项目
|
|
856
|
+
* 不认识/没给码时退回 launch —— 那是「EPLAN 没开」这个最常见原因的下一步。
|
|
857
|
+
*/
|
|
858
|
+
const NOT_READY_STEPS = {
|
|
859
|
+
HOST_NOT_INSTALLED: () => [
|
|
860
|
+
'EPLAN 里还没有注册宿主:这一步只能由 setup 完成,**不是** launch 能解决的 —— 开着的 EPLAN 再拉一次还是同一个状态。',
|
|
861
|
+
'让用户在有 EPLAN 窗口的那台机器上跑一次 `node setup.mjs`(第 5 步「注册引导脚本」需要 EPLAN 正在运行);跑完再 status 一次。',
|
|
862
|
+
'注册失败时 EPLAN 窗口上会报原因,让用户念给你听;不要自己去改 EPLAN 安装目录或杀进程重来。',
|
|
863
|
+
],
|
|
864
|
+
EPLAN_NOT_RUNNING: (ctx) => [
|
|
865
|
+
'workspace{action:"launch"} —— 用正确的工作目录拉起 EPLAN 并等 Remoting 挂起(最多 60 秒)。'
|
|
866
|
+
+ '不要自己 spawn EPLAN.exe:工作目录不对它会 30~90 秒后静默退出,带 .elk 参数也不会加载项目。',
|
|
867
|
+
ctx.processes.length > 0
|
|
868
|
+
? `本机已经有 ${ctx.processes.length} 个 EPLAN(pid ${ctx.processes.join('、')})。如果只是想连现成的那个,等 30 秒再 status 一次;启动慢是常态。`
|
|
869
|
+
: '起完等 30~60 秒再 status 一次。',
|
|
870
|
+
'EPLAN 只有**加载了项目**才会让 API 返回 ready:不行就 workspace{action:"open_project", name:"<项目名>"}。',
|
|
871
|
+
],
|
|
872
|
+
BRIDGE_MISSING: () => [
|
|
873
|
+
'桥接器没编译出来:让用户跑一次 `node setup.mjs`(它会在本机重新编译宿主与桥接器)。'
|
|
874
|
+
+ '不要自己写配置或去找 .exe —— 每台机器都必须现编,拷别人的会 MissingMethodException。',
|
|
875
|
+
'编完再 status 一次;仍然报缺就说明编译失败,让用户把 setup 的输出贴过来。',
|
|
876
|
+
],
|
|
877
|
+
EPLAN_BLOCKED_BY_DIALOG: () => [
|
|
878
|
+
'EPLAN 被一个对话框压着,所有调用都会被挡回来:让用户切到 EPLAN 关掉它(或按 Esc),回一句再继续。',
|
|
879
|
+
'不要代用户点按钮,也不要连续重试 —— 框还在就一定会再被挡回来。',
|
|
880
|
+
],
|
|
881
|
+
EPLAN_TIMEOUT: () => [
|
|
882
|
+
'EPLAN 主线程没回话:多半是弹着对话框或在跑长命令。让用户看一眼 EPLAN 窗口上有没有框,处理掉再说。',
|
|
883
|
+
'等用户回话后再 status 一次;不要连着重试,也不会自己好。',
|
|
884
|
+
],
|
|
885
|
+
NO_PROJECT: () => [
|
|
886
|
+
'EPLAN 连着但没加载项目(API 只在项目加载后可用):workspace{action:"open_project", name:"<项目名>"}。',
|
|
887
|
+
'不知道项目名就问用户,不要自己建一个新项目顶上。',
|
|
888
|
+
],
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/** 没给码或不认识的码 → launch 那一组(最常见的「EPLAN 没开」)。 */
|
|
892
|
+
const DEFAULT_NOT_READY_CODE = 'EPLAN_NOT_RUNNING'
|
|
893
|
+
|
|
894
|
+
function notReadyFields({ message, code, processes }) {
|
|
895
|
+
const list = Array.isArray(processes) ? processes : []
|
|
896
|
+
const key = NOT_READY_STEPS[code] ? code : DEFAULT_NOT_READY_CODE
|
|
897
|
+
const steps = NOT_READY_STEPS[key]({ processes: list })
|
|
898
|
+
return {
|
|
899
|
+
ready: false,
|
|
900
|
+
blocked: true,
|
|
901
|
+
doNotRetry:
|
|
902
|
+
'readiness 不会因为再调一次 status 而改变。按 nextSteps 一步一来,期间不要重复调用 status / brief。',
|
|
903
|
+
nextSteps: steps,
|
|
904
|
+
...(code ? { eplanCode: code } : {}),
|
|
905
|
+
...(message ? { message } : {}),
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async function statusResult() {
|
|
910
|
+
let lessons
|
|
911
|
+
try {
|
|
912
|
+
lessons = lessonsForStatus()
|
|
913
|
+
} catch {
|
|
914
|
+
lessons = undefined
|
|
915
|
+
}
|
|
916
|
+
let preferences
|
|
917
|
+
try {
|
|
918
|
+
preferences = preferencesForStatus()
|
|
919
|
+
} catch {
|
|
920
|
+
preferences = undefined
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
try {
|
|
924
|
+
const result = await callBridge('status', {})
|
|
925
|
+
if (lessons) result.lessons = lessons
|
|
926
|
+
if (preferences) result.preferences = preferences
|
|
927
|
+
decorateInstances(result)
|
|
928
|
+
// 桥接通了但项目没加载也是 ready:false —— 这种最容易被当成「没事」继续往下调,
|
|
929
|
+
// 然后每一步都报 EPLAN_NOT_RUNNING。这里把话说透。
|
|
930
|
+
if (result.ready !== true) {
|
|
931
|
+
Object.assign(
|
|
932
|
+
result,
|
|
933
|
+
notReadyFields({
|
|
934
|
+
message:
|
|
935
|
+
(result.currentProject ?? null) === null
|
|
936
|
+
? 'EPLAN 连着,但没有加载任何项目(API 只在项目加载后可用)。'
|
|
937
|
+
: 'EPLAN 连着,但还没就绪。',
|
|
938
|
+
code: result.eplanCode,
|
|
939
|
+
processes: eplanProcessIds(),
|
|
940
|
+
}),
|
|
941
|
+
)
|
|
942
|
+
if (lessons) result.lessons = lessons
|
|
943
|
+
if (preferences) result.preferences = preferences
|
|
944
|
+
}
|
|
945
|
+
return ok(result)
|
|
946
|
+
} catch (error) {
|
|
947
|
+
const payload = {
|
|
948
|
+
...notReadyFields({
|
|
949
|
+
message: error.message,
|
|
950
|
+
code: error.code ?? 'UNKNOWN',
|
|
951
|
+
processes: eplanProcessIds(),
|
|
952
|
+
}),
|
|
953
|
+
eplan: {
|
|
954
|
+
reachable: false,
|
|
955
|
+
code: error.code ?? 'UNKNOWN',
|
|
956
|
+
message: error.message,
|
|
957
|
+
},
|
|
958
|
+
...(lessons ? { lessons } : {}),
|
|
959
|
+
...(preferences ? { preferences } : {}),
|
|
960
|
+
hint: '经验库不依赖 EPLAN,仍然可以读写(lesson / symbol_catalog 的 lookup)。',
|
|
961
|
+
}
|
|
962
|
+
decorateInstances(payload)
|
|
963
|
+
return ok(payload)
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
/**
|
|
968
|
+
* 把「本机有几个 EPLAN 在跑」告诉模型。
|
|
969
|
+
*
|
|
970
|
+
* 两个实例本身不是错,但同一个项目被其中一个用「专有」模式打开时,另一个再开它
|
|
971
|
+
* 就会弹多用户冲突框、把调用卡到超时。这个信息放在 status 里,模型第一步就能看见,
|
|
972
|
+
* 不用等到开项目失败了才知道机器上有两个窗口。
|
|
973
|
+
*/
|
|
974
|
+
function decorateInstances(result) {
|
|
975
|
+
const ids = eplanProcessIds()
|
|
976
|
+
if (ids.length === 0) return result
|
|
977
|
+
result.eplanProcesses = ids
|
|
978
|
+
if (ids.length > 1) {
|
|
979
|
+
result.instancesHint =
|
|
980
|
+
`本机有 ${ids.length} 个 EPLAN 实例在跑(pid ${ids.join('、')})。同一个项目只能被其中一个用「专有」模式独占;` +
|
|
981
|
+
'如果某个项目正在另一个实例里开着,在这个实例里再开它会弹「多用户冲突」并把调用卡住 —— ' +
|
|
982
|
+
'要么在那个窗口里继续,要么只留一个实例,要么在打开项目时把编辑模式选「默认」。'
|
|
983
|
+
}
|
|
984
|
+
return result
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* look 和别的工具不同:它把渲染出来的图**直接作为图片内容返回**。
|
|
989
|
+
*
|
|
990
|
+
* 为什么这样设计:模型看到的是图,不是「图片路径」。返回路径的话,
|
|
991
|
+
* 每次都得再叫一次 read_image,多一轮往返,而且很容易忘了看就直接宣布画好了。
|
|
992
|
+
* 一次调用同时拿到图和结构化数据,才不会出现「没看图就交活」。
|
|
993
|
+
*/
|
|
994
|
+
/**
|
|
995
|
+
* 写操作 + 展示,合成一次调用。
|
|
996
|
+
*
|
|
997
|
+
* reveal=true 时,写完之后由服务端接着 look 出图,把渲染结果一并返回。
|
|
998
|
+
*
|
|
999
|
+
* 跟随(2026-11-23 用户要求「动手时自动在 EPLAN 打开并定位到当前绘图页」):
|
|
1000
|
+
* 每次写成功后把那一页在 EPLAN 界面里打开(page_open),结果里带 follow 字段。
|
|
1001
|
+
* **只切软件内的当前页**:不抢前台、不最大化、不改窗口尺寸位置(focus 永远 false,
|
|
1002
|
+
* 2026-11-27 用户明确要求)。也不会因为跟随失败让这次写入失败。
|
|
1003
|
+
* 同一页在 2.5 秒内重复写只跟随一次;对话框挡着就记 blocked,不重试。
|
|
1004
|
+
*/
|
|
1005
|
+
const followOpts = { enabled: true, throttleMs: 2500 }
|
|
1006
|
+
let lastFollow = { page: null, at: 0 }
|
|
1007
|
+
|
|
1008
|
+
/** 把一页在 EPLAN 界面里打开;任何失败都只记下来,不抛。 */
|
|
1009
|
+
async function openInEplan(page, project) {
|
|
1010
|
+
try {
|
|
1011
|
+
const shown = await callBridge('page_open', { page, project, focus: false }, { timeoutMs: 20000 })
|
|
1012
|
+
return { page, visibleInTitle: shown?.visibleInTitle !== false, at: new Date().toISOString() }
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
const code = String(error?.code ?? '')
|
|
1015
|
+
return { page, error: code === 'EPLAN_BLOCKED_BY_DIALOG' ? 'blocked-by-dialog' : String(error?.message ?? error) }
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/** 写入后跟随:只跟随本次真正碰过的那一页。 */
|
|
1020
|
+
async function followWrite(op, args, result) {
|
|
1021
|
+
if (!followOpts.enabled || args?.dryRun === true || op === 'page_delete') return null
|
|
1022
|
+
const candidates = [
|
|
1023
|
+
typeof args?.page === 'string' ? args.page : null,
|
|
1024
|
+
typeof args?.name === 'string' ? args.name : null,
|
|
1025
|
+
typeof result?.page?.name === 'string' ? result.page.name : null,
|
|
1026
|
+
typeof result?.page === 'string' ? result.page : null,
|
|
1027
|
+
]
|
|
1028
|
+
const page = candidates.find((value) => typeof value === 'string' && value.length > 0)
|
|
1029
|
+
if (!page) return null
|
|
1030
|
+
const now = Date.now()
|
|
1031
|
+
if (page === lastFollow.page && now - lastFollow.at < followOpts.throttleMs) return null
|
|
1032
|
+
const followed = await openInEplan(page, args?.project)
|
|
1033
|
+
lastFollow = { page, at: Date.now() }
|
|
1034
|
+
if (result && typeof result === 'object') result.follow = followed
|
|
1035
|
+
return followed
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
async function invokeWrite(op, args) {
|
|
1039
|
+
try {
|
|
1040
|
+
const result = await callBridge(op, args)
|
|
1041
|
+
await followWrite(op, args, result)
|
|
1042
|
+
if (!args.reveal || args.dryRun) return ok(result)
|
|
1043
|
+
|
|
1044
|
+
const page = args.page ?? args.name ?? result?.page?.name ?? result?.page
|
|
1045
|
+
if (typeof page !== 'string' || page.length === 0) return ok(result)
|
|
1046
|
+
|
|
1047
|
+
const detail = {}
|
|
1048
|
+
|
|
1049
|
+
let shot = null
|
|
1050
|
+
try {
|
|
1051
|
+
shot = await callBridge('look', {
|
|
1052
|
+
page,
|
|
1053
|
+
project: args.project,
|
|
1054
|
+
width: args.width,
|
|
1055
|
+
theme: args.theme ?? config.renderTheme,
|
|
1056
|
+
})
|
|
1057
|
+
detail.imagePath = shot.imagePath
|
|
1058
|
+
detail.counts = shot.counts
|
|
1059
|
+
} catch (error) {
|
|
1060
|
+
detail.lookError = error.message
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
const merged = { ...result, reveal: detail }
|
|
1064
|
+
const blocks = [{ type: 'text', text: JSON.stringify(merged, null, 2) }]
|
|
1065
|
+
if (shot?.imagePath && existsSync(shot.imagePath)) {
|
|
1066
|
+
blocks.push({
|
|
1067
|
+
type: 'image',
|
|
1068
|
+
data: readFileSync(shot.imagePath).toString('base64'),
|
|
1069
|
+
mimeType: 'image/png',
|
|
1070
|
+
})
|
|
1071
|
+
}
|
|
1072
|
+
return { content: blocks }
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
return failed(op, error, repeatNote(op, args, error))
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
/**
|
|
1079
|
+
* 渲染一页并把图直接给模型。
|
|
1080
|
+
*
|
|
1081
|
+
* 文字部分只留「这页是什么 + 图在哪 + 下一步」,不再把整份 functions 列表塞进来:
|
|
1082
|
+
* 实测一页 32 个对象时那条文字有 8.8 KB,其中 90% 是 `name:"=+"` 的连接定义点和
|
|
1083
|
+
* 每一极重复的坐标 —— 模型要的只是图,列表想看再用 format=structure view=list 要
|
|
1084
|
+
* (2026-11-23 session-a18a4a7f 实测,一趟绘图里这条被发了 6 次)。
|
|
1085
|
+
*/
|
|
1086
|
+
async function invokeLook(args) {
|
|
1087
|
+
try {
|
|
1088
|
+
const result = await callBridge('look', { ...args, theme: args.theme ?? config.renderTheme })
|
|
1089
|
+
// 渲染图落在临时目录、文件名是页名换成下划线:给一份可读路径,
|
|
1090
|
+
// 用户和模型都能直接打开,不用去翻 temp(2026-11-16 反馈)。
|
|
1091
|
+
const visiblePath = keepVisible(result.imagePath)
|
|
1092
|
+
const detailed = args.detail === true || args.view === 'full'
|
|
1093
|
+
const summary = detailed
|
|
1094
|
+
? { ...result, visiblePath }
|
|
1095
|
+
: {
|
|
1096
|
+
page: result.page,
|
|
1097
|
+
project: result.project,
|
|
1098
|
+
pageType: result.pageType,
|
|
1099
|
+
pageSize: result.pageSize,
|
|
1100
|
+
theme: result.theme,
|
|
1101
|
+
imagePath: result.imagePath,
|
|
1102
|
+
visiblePath,
|
|
1103
|
+
imageBytes: result.imageBytes,
|
|
1104
|
+
renderMs: result.renderMs,
|
|
1105
|
+
counts: result.counts,
|
|
1106
|
+
...(result.graphicalConnections ? { connections: result.graphicalConnections.count ?? 0 } : {}),
|
|
1107
|
+
hint:
|
|
1108
|
+
'图就是这页现在的样子,直接看。要每个对象的坐标用 page_inspect{format:"structure",view:"list"};'
|
|
1109
|
+
+ '要引脚相对坐标用 view:"full";要完整原始字段给 detail:true。',
|
|
1110
|
+
}
|
|
1111
|
+
const blocks = [{ type: 'text', text: JSON.stringify(summary) }]
|
|
1112
|
+
const imagePath = result.imagePath
|
|
1113
|
+
if (args.image !== false && imagePath && existsSync(imagePath)) {
|
|
1114
|
+
blocks.push({
|
|
1115
|
+
type: 'image',
|
|
1116
|
+
data: readFileSync(imagePath).toString('base64'),
|
|
1117
|
+
mimeType: 'image/png',
|
|
1118
|
+
})
|
|
1119
|
+
}
|
|
1120
|
+
return { content: blocks }
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
return failed('look', error)
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/** 把渲染图抄到 %LOCALAPPDATA%\eplan-mcp\renders\,保留原文件名(已带 .png)。 */
|
|
1127
|
+
function keepVisible(imagePath) {
|
|
1128
|
+
if (!imagePath || !existsSync(imagePath)) return undefined
|
|
1129
|
+
try {
|
|
1130
|
+
const dir = join(configDir(), 'renders')
|
|
1131
|
+
mkdirSync(dir, { recursive: true })
|
|
1132
|
+
const target = join(dir, imagePath.split(/[\\/]/).pop())
|
|
1133
|
+
copyFileSync(imagePath, target)
|
|
1134
|
+
return target
|
|
1135
|
+
} catch {
|
|
1136
|
+
return undefined
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// ---------------------------------------------------------------------------
|
|
1141
|
+
// 工具定义:只留绘图流程真正需要的 8 个。
|
|
1142
|
+
// ---------------------------------------------------------------------------
|
|
1143
|
+
|
|
1144
|
+
// ---------------------------------------------------------------------------
|
|
1145
|
+
// PDF:把手册的页面渲染成图,交给模型用眼睛读。
|
|
1146
|
+
//
|
|
1147
|
+
// 为什么不是抽文字:这本 FR-D700 手册用的是没有 ToUnicode 映射的嵌入字体,
|
|
1148
|
+
// pdfjs 抽出来的中文全是乱码(实测 `琤慵ᢈ≥挶`)。换 Windows 自带的
|
|
1149
|
+
// Windows.Data.Pdf 渲染成 PNG,中文清清楚楚 —— 而且电气图本来就是看图更快。
|
|
1150
|
+
//
|
|
1151
|
+
// 渲染交给 PowerShell 脚本(server/pdf2png.ps1):WinRT 在 Node 里用不了,
|
|
1152
|
+
// 而 Windows 10/11 都自带这个引擎,不需要额外装任何东西。
|
|
1153
|
+
// ---------------------------------------------------------------------------
|
|
1154
|
+
|
|
1155
|
+
const PDF_RENDER_SCRIPT = join(here, 'pdf2png.ps1')
|
|
1156
|
+
// 一次 render 最多几页:模型线路一条 assistant 消息之后只接受 8 张新图,
|
|
1157
|
+
// 这里留余量(同样的限制在 preset 的 image-budget.js 里还兜着一层)。
|
|
1158
|
+
const PDF_MAX_PAGES_PER_CALL = 4
|
|
1159
|
+
|
|
1160
|
+
function renderPdfPages(pdfPath, from, to, scale) {
|
|
1161
|
+
const outDir = join(tmpdir(), 'eplan-mcp', 'pdf')
|
|
1162
|
+
mkdirSync(outDir, { recursive: true })
|
|
1163
|
+
|
|
1164
|
+
const result = spawnSync(
|
|
1165
|
+
'powershell.exe',
|
|
1166
|
+
[
|
|
1167
|
+
'-NoProfile',
|
|
1168
|
+
'-ExecutionPolicy', 'Bypass',
|
|
1169
|
+
'-File', PDF_RENDER_SCRIPT,
|
|
1170
|
+
'-Pdf', pdfPath,
|
|
1171
|
+
'-OutDir', outDir,
|
|
1172
|
+
'-From', String(from),
|
|
1173
|
+
'-To', String(to),
|
|
1174
|
+
'-Scale', String(scale),
|
|
1175
|
+
],
|
|
1176
|
+
{ encoding: 'utf8', timeout: 300000, windowsHide: true },
|
|
1177
|
+
)
|
|
1178
|
+
|
|
1179
|
+
const stdout = result.stdout ?? ''
|
|
1180
|
+
if (stdout.startsWith('ERROR|')) {
|
|
1181
|
+
const [, code, message] = stdout.trim().split('|')
|
|
1182
|
+
throw fail(code || 'PDF_ERROR', message || '渲染失败')
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
const match = stdout.match(/PAGES\|(\d+)/)
|
|
1186
|
+
if (!match) {
|
|
1187
|
+
throw fail(
|
|
1188
|
+
'PDF_RENDER_FAILED',
|
|
1189
|
+
`渲染 PDF 失败:${(result.stderr || stdout || '').slice(0, 400) || '没有输出'}`,
|
|
1190
|
+
)
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
// 路径自己算,不从 PowerShell 回读:中文路径经过管道会被控制台编码搅乱。
|
|
1194
|
+
const base = pdfPath.replace(/\\/g, '/').split('/').pop().replace(/\.pdf$/i, '')
|
|
1195
|
+
const numPages = Number(match[1])
|
|
1196
|
+
// 再抄一份到用户能直接双击打开的目录:临时目录里的文件名带中文页名,
|
|
1197
|
+
// 而且会被下一次 render 覆盖(2026-11-16 用户反馈「预览不来,这是无格式的文件」)。
|
|
1198
|
+
const visibleDir = join(configDir(), 'pdf-visible')
|
|
1199
|
+
try { mkdirSync(visibleDir, { recursive: true }) } catch {}
|
|
1200
|
+
const pages = []
|
|
1201
|
+
for (let index = from; index <= Math.min(to, numPages); index += 1) {
|
|
1202
|
+
const file = join(outDir, `${base}-p${String(index).padStart(3, '0')}.png`)
|
|
1203
|
+
if (!existsSync(file)) continue
|
|
1204
|
+
let visible = file
|
|
1205
|
+
try {
|
|
1206
|
+
visible = join(visibleDir, `${base}-p${String(index).padStart(3, '0')}.png`)
|
|
1207
|
+
copyFileSync(file, visible)
|
|
1208
|
+
} catch {
|
|
1209
|
+
visible = file
|
|
1210
|
+
}
|
|
1211
|
+
pages.push({ page: index, path: file, visiblePath: visible })
|
|
1212
|
+
}
|
|
1213
|
+
return { numPages, pages }
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
async function invokePdf(args) {
|
|
1217
|
+
try {
|
|
1218
|
+
const action = args.action ?? 'outline'
|
|
1219
|
+
const pdfPath = args.path
|
|
1220
|
+
|
|
1221
|
+
if (action === 'outline') {
|
|
1222
|
+
const { pdfOutline } = await import('./pdf.mjs')
|
|
1223
|
+
const outline = await pdfOutline(pdfPath)
|
|
1224
|
+
return ok({
|
|
1225
|
+
path: outline.path,
|
|
1226
|
+
numPages: outline.numPages,
|
|
1227
|
+
info: outline.info,
|
|
1228
|
+
// 文字抽不出来的页多半是整页扫描图,只能看图。
|
|
1229
|
+
pagesWithoutText: outline.scannedPages.slice(0, 60),
|
|
1230
|
+
hint:
|
|
1231
|
+
'先看 outline 定页范围,再用 action="render" 把关键页画成图看内容。' +
|
|
1232
|
+
'如果文字抽出来是乱码,说明 PDF 没写 ToUnicode 映射,直接看渲染图即可。',
|
|
1233
|
+
})
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
if (action === 'search') {
|
|
1237
|
+
const { pdfSearch } = await import('./pdf.mjs')
|
|
1238
|
+
const result = await pdfSearch(pdfPath, args.queries)
|
|
1239
|
+
if (result.hits.length === 0) {
|
|
1240
|
+
return ok({
|
|
1241
|
+
...result,
|
|
1242
|
+
hint: '一个都没搜到。可能是这本 PDF 的文字层是乱码(没有 ToUnicode 映射),搜不了;改用 action="render" 逐页看图。',
|
|
1243
|
+
})
|
|
1244
|
+
}
|
|
1245
|
+
return ok(result)
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
if (action === 'render') {
|
|
1249
|
+
const from = args.from ?? 1
|
|
1250
|
+
let to = args.to ?? from
|
|
1251
|
+
if (to - from + 1 > PDF_MAX_PAGES_PER_CALL) to = from + PDF_MAX_PAGES_PER_CALL - 1
|
|
1252
|
+
|
|
1253
|
+
const { numPages, pages } = renderPdfPages(pdfPath, from, to, args.scale ?? 2)
|
|
1254
|
+
const blocks = [
|
|
1255
|
+
{
|
|
1256
|
+
type: 'text',
|
|
1257
|
+
text: JSON.stringify(
|
|
1258
|
+
{
|
|
1259
|
+
path: pdfPath,
|
|
1260
|
+
numPages,
|
|
1261
|
+
rendered: pages.map((page) => page.page),
|
|
1262
|
+
imagePaths: pages.map((page) => page.visiblePath ?? page.path),
|
|
1263
|
+
tempPaths: pages.map((page) => page.path),
|
|
1264
|
+
note:
|
|
1265
|
+
`一次最多渲染 ${PDF_MAX_PAGES_PER_CALL} 页;要看更多就再调一次,换 from/to。` +
|
|
1266
|
+
'imagePaths 是带 .png 后缀、可直接双击打开的副本;tempPaths 是临时文件,会被下次渲染覆盖。',
|
|
1267
|
+
},
|
|
1268
|
+
null,
|
|
1269
|
+
2,
|
|
1270
|
+
),
|
|
1271
|
+
},
|
|
1272
|
+
]
|
|
1273
|
+
|
|
1274
|
+
for (const page of pages) {
|
|
1275
|
+
blocks.push({
|
|
1276
|
+
type: 'image',
|
|
1277
|
+
data: readFileSync(page.path).toString('base64'),
|
|
1278
|
+
mimeType: 'image/png',
|
|
1279
|
+
})
|
|
1280
|
+
}
|
|
1281
|
+
return { content: blocks }
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
throw fail('BAD_ARGUMENT', `不认识的 action:${action}。只支持 outline / search / render。`)
|
|
1285
|
+
} catch (error) {
|
|
1286
|
+
return failed('pdf', error)
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
const server = new McpServer({ name: 'eplan', version: '0.1.0' })
|
|
1291
|
+
|
|
1292
|
+
const point = z.array(z.number()).length(2).describe('页面坐标 [x, y],单位 mm')
|
|
1293
|
+
|
|
1294
|
+
// 每个工具都带这个参数:避免误写到用户正在画的那个项目上。
|
|
1295
|
+
// 宿主侧的 Context.Resolve 只认「已打开」的项目,名字对不上直接报错,不会猜。
|
|
1296
|
+
const project = z
|
|
1297
|
+
.string()
|
|
1298
|
+
.optional()
|
|
1299
|
+
.describe('目标项目名(如 test)或 .elk 完整路径。省略则用 EPLAN 当前激活的项目。写操作建议显式指定。')
|
|
1300
|
+
|
|
1301
|
+
// 写完立刻出图。默认关闭,因为纯数据操作不需要图。
|
|
1302
|
+
// 注意它**只出图、不切页**:切页会把用户正看着的界面换掉,那属于 open_page 的职责。
|
|
1303
|
+
const reveal = z
|
|
1304
|
+
.boolean()
|
|
1305
|
+
.optional()
|
|
1306
|
+
.describe('写完后把这一页渲染成图一并返回(不切换 EPLAN 里当前显示的页)。默认 false;想看图时设 true')
|
|
1307
|
+
|
|
1308
|
+
const width = z
|
|
1309
|
+
.number()
|
|
1310
|
+
.int()
|
|
1311
|
+
.min(400)
|
|
1312
|
+
.max(8000)
|
|
1313
|
+
.optional()
|
|
1314
|
+
.describe('reveal 出图的像素宽度,默认 2000')
|
|
1315
|
+
|
|
1316
|
+
// ---------------------------------------------------------------------------
|
|
1317
|
+
// 十二个工具。分四类:看(workspace / symbol_catalog / page_inspect)、
|
|
1318
|
+
// 画(page_create / page_edit / page_delete)、验收与交付(validate / export)、
|
|
1319
|
+
// 文档与历史(manual / operation_history / operation_rollback)。
|
|
1320
|
+
//
|
|
1321
|
+
// 为什么是 11 不是 16:同类功能给一个入口,模型少记一套名字。合并只发生在这一层,
|
|
1322
|
+
// 底下调用的宿主 op 一个都没改名 —— 那些是真机验证过的行为,动它没有收益只有风险。
|
|
1323
|
+
//
|
|
1324
|
+
// 每个带 action/format 的工具用「扁平 schema + handler 内校验」而不是
|
|
1325
|
+
// discriminatedUnion:MCP 客户端的 schema 投影对联合类型支持不一致,
|
|
1326
|
+
// 扁平结构在任何客户端都能正确显示参数,缺字段时报错信息还能教下一步。
|
|
1327
|
+
// ---------------------------------------------------------------------------
|
|
1328
|
+
|
|
1329
|
+
/** 必填项检查:缺了就抛一个教下一步的错误。 */
|
|
1330
|
+
function need(args, fields, action, example) {
|
|
1331
|
+
const missing = fields.filter((field) => args[field] === undefined || args[field] === null || args[field] === '')
|
|
1332
|
+
if (missing.length > 0) {
|
|
1333
|
+
throw fail(
|
|
1334
|
+
'BAD_ARGUMENT',
|
|
1335
|
+
`action="${action}" 缺少必填参数:${missing.join('、')}。`,
|
|
1336
|
+
`这个 action 需要 ${fields.join('、')}。${example ? `照这个写:${example}` : '完整参数见工具描述。'}`,
|
|
1337
|
+
)
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
/**
|
|
1342
|
+
* page_edit 的参数归一化在 server/edit-args.mjs(纯函数,单独测)。
|
|
1343
|
+
* 这里只留一句调用,别再往本文件里堆同义词判断。
|
|
1344
|
+
*/
|
|
1345
|
+
|
|
1346
|
+
// ---------------------------------------------------------------------------
|
|
1347
|
+
// 工具面收口 + 「一次拿全」。
|
|
1348
|
+
//
|
|
1349
|
+
// 12 个工具常驻的 schema 实测 17,379 字符,而一次会话通常只做四类活之一:
|
|
1350
|
+
// 画页、改页、验收、查库。模型手里攥着「改页」用不到的工具说明,既占提示词,
|
|
1351
|
+
// 也容易让它绕远路(比如为了看状态去翻 server.mjs)。所以按模式 enable/disable,
|
|
1352
|
+
// 切换时发 tools/list 变更通知——这是 SDK 注册句柄的真实停用,不是文字游戏:
|
|
1353
|
+
// 停用的工具会从 tools/list 消失,也不再进 PTC 的 SDK 声明。
|
|
1354
|
+
//
|
|
1355
|
+
// 顺带解决另一个实测问题:技能文件在会话 cwd 下读不到。这里返回的一律是绝对路径。
|
|
1356
|
+
// ---------------------------------------------------------------------------
|
|
1357
|
+
|
|
1358
|
+
const toolHandles = new Map()
|
|
1359
|
+
|
|
1360
|
+
function regTool(name, definition, handler) {
|
|
1361
|
+
// 把抛出来的错误统一成 {ok:false, code, message, detail}。
|
|
1362
|
+
// 不包这一层,SDK 只把 message 文本带出去,code(CLAIMED / BAD_ARGUMENT)
|
|
1363
|
+
// 就丢了,模型也没法照着 detail 改参数。
|
|
1364
|
+
const wrapped = async (...callArgs) => {
|
|
1365
|
+
try {
|
|
1366
|
+
return await handler(...callArgs)
|
|
1367
|
+
} catch (error) {
|
|
1368
|
+
return failed(name, error)
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
const handle = server.registerTool(name, definition, wrapped)
|
|
1372
|
+
if (handle !== undefined && handle !== null) toolHandles.set(name, handle)
|
|
1373
|
+
return handle
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
const SKILL_ROOT = join(root, 'skills')
|
|
1377
|
+
|
|
1378
|
+
/** 页名 → 页面尺寸(mm)。validate 的越界检查要用,从 pages 顺手缓存。 */
|
|
1379
|
+
const pageSizeCache = new Map()
|
|
1380
|
+
|
|
1381
|
+
// 同页单飞 + 幂等:实测一次会话里同一页被 page_create 建了 6 次、其中三次
|
|
1382
|
+
// 输出字节级相同(4748/10826/10612/1056),纯粹是重复劳动。
|
|
1383
|
+
const createInflight = new Map()
|
|
1384
|
+
const createMemo = new Map()
|
|
1385
|
+
const CREATE_IDEMPOTENT_MS = 3 * 60 * 1000
|
|
1386
|
+
|
|
1387
|
+
const ownerTag = () => `mcp:${process.pid}`
|
|
1388
|
+
|
|
1389
|
+
// ---------------------------------------------------------------------------
|
|
1390
|
+
// 常驻元件热表
|
|
1391
|
+
//
|
|
1392
|
+
// 为什么要有:PTC 每次 run_code 都是新进程,上一步查到的引脚坐标不会自动变成
|
|
1393
|
+
// 下一步可用的记忆;一页十几个符号就是十几次 symbol_catalog 往返。这里把本机
|
|
1394
|
+
// 实测过的引脚几何放进提示词常驻区:基线 8 条永远在,其余按使用频率动态进表。
|
|
1395
|
+
// 引脚写成 0 基下标:`0:(0,4)↑` = 第 0 个连接点位于 (0,4) mm、朝上。
|
|
1396
|
+
// ---------------------------------------------------------------------------
|
|
1397
|
+
const SYMBOL_USAGE_FILE = join(KNOWLEDGE_DIR, 'symbol-usage.json')
|
|
1398
|
+
|
|
1399
|
+
/** 基线:接线图里几乎每页都要用的节点与中断点(本机 SPECIAL / GB_symbol 实测)。 */
|
|
1400
|
+
const COMMON_SYMBOLS = [
|
|
1401
|
+
{ s: 'BP', lib: 'SPECIAL', v: '1/3/5/7', p: '0:(0,-1)↑ 1:(0,-1)↓', use: '中断点(竖排)' },
|
|
1402
|
+
{ s: 'CO', lib: 'SPECIAL', v: '0', p: '0:(0,0)→ 1:(0,0)↓', use: '连接点' },
|
|
1403
|
+
{ s: 'TLRU', lib: 'SPECIAL', v: '0/2', p: '0:(0,0)↓ 1:(0,0)← 2:(2,0)→', use: 'T 节点(左→右,下引)' },
|
|
1404
|
+
{ s: 'TOUR', lib: 'SPECIAL', v: '0/2', p: '0:(0,0)↓ 1:(0,0)↑ 2:(2,0)→', use: 'T 节点(上下通,右引)' },
|
|
1405
|
+
{ s: 'TLRO', lib: 'SPECIAL', v: '0/2', p: '0:(0,0)↑ 1:(0,0)← 2:(2,0)→', use: 'T 节点(左→右,上引)' },
|
|
1406
|
+
{ s: 'TOUL', lib: 'SPECIAL', v: '0/2', p: '0:(0,0)↓ 1:(0,0)↑ 2:(-2,0)←', use: 'T 节点(上下通,左引)' },
|
|
1407
|
+
{ s: 'CDPST', lib: 'SPECIAL', v: '0', p: '0:(0,4)↑ 1:(0,-4)↓', use: '电源引入点(上下各 4 mm)' },
|
|
1408
|
+
{
|
|
1409
|
+
s: 'FA3', lib: 'GB_symbol', v: '0',
|
|
1410
|
+
p: '0:(0,4)↑ 1:(0,-4)↓ 2:(8,4)↑ 3:(8,-4)↓ 4:(16,4)↑ 5:(16,-4)↓',
|
|
1411
|
+
use: '三极空开/断路器(极距 8 mm)',
|
|
1412
|
+
},
|
|
1413
|
+
]
|
|
1414
|
+
|
|
1415
|
+
/**
|
|
1416
|
+
* 每个模式的动作顺序:把「第一步做什么」写成一条可直接照抄的调用序列,
|
|
1417
|
+
* 省掉模型自己试探参数(2026-11-27 那次会话第一步就猜了个不存在的 mode="draw")。
|
|
1418
|
+
*
|
|
1419
|
+
* focus 的合法 mode 只有 page / edit / check / lib / all,这里再写一遍。
|
|
1420
|
+
*/
|
|
1421
|
+
const FOCUS_MODES = ['page', 'edit', 'check', 'lib', 'all']
|
|
1422
|
+
|
|
1423
|
+
const ACTION_PARAMS = {
|
|
1424
|
+
page: [
|
|
1425
|
+
'1) workspace.present{page, wait:true} —— 先把当前绘图板呈现出来(切页 + 出图),这是第一步',
|
|
1426
|
+
'2) page_create{page, nodes[], texts[], grid:4} —— 建新页;不要往已存在的页上叠加',
|
|
1427
|
+
'3) page_edit.insert_symbol{page, insert{symbol, library, variant, at, deviceTag}} —— 按单元补元件',
|
|
1428
|
+
'4) validate{page, expectDevices[]} —— 交付前跑一次',
|
|
1429
|
+
'5) page_inspect{page, format:"image", width:2000} —— 出图核对',
|
|
1430
|
+
'symbol_catalog.pins{symbols[]} 查引脚;symbol_catalog.search{filter} 查名字',
|
|
1431
|
+
],
|
|
1432
|
+
edit: [
|
|
1433
|
+
'1) workspace.present{page, wait:true} —— 先看清现在是什么样',
|
|
1434
|
+
'2) page_edit.relabel{page, select{deviceTag}, to} / relocate{page, select{objectId}, at:[x,y]}',
|
|
1435
|
+
'3) page_edit.insert_symbol{page, insert{symbol, at}} —— 只补一两个;整页请用 page_create',
|
|
1436
|
+
'4) validate{page} —— 改完必须验一次',
|
|
1437
|
+
],
|
|
1438
|
+
check: [
|
|
1439
|
+
'1) validate{page, expectDevices[]} —— 看 verdict 和 problems',
|
|
1440
|
+
'2) page_inspect{page, format:"image", width:2000} —— 亲眼看图',
|
|
1441
|
+
'3) export{kind:"png", pages:[page], theme:"light"} —— 要交付给别人时',
|
|
1442
|
+
],
|
|
1443
|
+
lib: [
|
|
1444
|
+
'symbol_catalog.search{filter, limit:200} —— 按名字查,中文概念直接查',
|
|
1445
|
+
'symbol_catalog.pins{symbols[]} —— 查引脚相对坐标与朝向',
|
|
1446
|
+
'symbol_catalog.visual{symbols[]} —— 一次把候选画出来用眼睛认',
|
|
1447
|
+
'symbol_catalog.lookup{symbol} / annotate{symbol, concept} —— 查/写语义',
|
|
1448
|
+
],
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
function readSymbolUsage() {
|
|
1452
|
+
try {
|
|
1453
|
+
return JSON.parse(readFileSync(SYMBOL_USAGE_FILE, 'utf8'))
|
|
1454
|
+
} catch {
|
|
1455
|
+
return {}
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
let usageCache = null
|
|
1460
|
+
function symbolUsage() {
|
|
1461
|
+
if (usageCache) return usageCache
|
|
1462
|
+
usageCache = readSymbolUsage()
|
|
1463
|
+
return usageCache
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
/** 记一次符号使用:pins 查过、或成功插入过都算。频率决定热表里的位置。 */
|
|
1467
|
+
function recordSymbolUse(names, library) {
|
|
1468
|
+
if (!Array.isArray(names) || names.length === 0) return
|
|
1469
|
+
const usage = symbolUsage()
|
|
1470
|
+
const now = Date.now()
|
|
1471
|
+
for (const name of names) {
|
|
1472
|
+
if (typeof name !== 'string' || name.length === 0) continue
|
|
1473
|
+
const key = `${library ?? ''}|${name}`
|
|
1474
|
+
const row = usage[key] ?? { name, library: library ?? null, count: 0, lastAt: 0 }
|
|
1475
|
+
row.count += 1
|
|
1476
|
+
row.lastAt = now
|
|
1477
|
+
usage[key] = row
|
|
1478
|
+
}
|
|
1479
|
+
try {
|
|
1480
|
+
writeFileSync(SYMBOL_USAGE_FILE, JSON.stringify(usage, null, 1), 'utf8')
|
|
1481
|
+
} catch (error) {
|
|
1482
|
+
process.stderr.write(`[eplan-mcp] 元件热表写不进去: ${error.message}\n`)
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
/**
|
|
1487
|
+
* 热表 = 基线 8 条 + 用过的符号里出现最多的若干条。
|
|
1488
|
+
* 每行压到「名 库 变体 引脚 用途」五个字段,免得把提示词撑爆。
|
|
1489
|
+
*/
|
|
1490
|
+
function warmSymbols(limit = 12) {
|
|
1491
|
+
const usage = symbolUsage()
|
|
1492
|
+
const seen = new Set(COMMON_SYMBOLS.map((item) => item.s))
|
|
1493
|
+
const used = Object.values(usage)
|
|
1494
|
+
.filter((row) => row && !seen.has(row.name))
|
|
1495
|
+
.sort((a, b) => b.count - a.count || b.lastAt - a.lastAt)
|
|
1496
|
+
.slice(0, Math.max(0, limit - COMMON_SYMBOLS.length))
|
|
1497
|
+
.map((row) => ({ s: row.name, lib: row.library ?? '?', v: '-', p: '已查过 pins,见 knowledge/symbol-usage.json', use: `用过 ${row.count} 次` }))
|
|
1498
|
+
return [...COMMON_SYMBOLS, ...used].map(
|
|
1499
|
+
(item) => `${item.s} | ${item.lib} | v${item.v} | ${item.p} | ${item.use}`,
|
|
1500
|
+
)
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
/**
|
|
1504
|
+
* 符号图鉴:knowledge/symbols/<名>.png,由 script/build-symbol-gallery.mjs 用 EPLAN
|
|
1505
|
+
* 真画一遍再逐张裁出来(不是拼图 —— 用户明确要求逐张发)。
|
|
1506
|
+
* 模型看着形状配引脚,比只看名字靠谱。
|
|
1507
|
+
*/
|
|
1508
|
+
const SYMBOL_GALLERY_DIR = (() => {
|
|
1509
|
+
// 图鉴随包走(script/build-symbol-gallery.mjs 生成到包内 knowledge/symbols),
|
|
1510
|
+
// 装到别的机器也能直接用;本地生成过就用本地那份覆盖。
|
|
1511
|
+
const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)))
|
|
1512
|
+
const shipped = join(packageRoot, 'knowledge', 'symbols')
|
|
1513
|
+
const local = join(KNOWLEDGE_DIR, 'symbols')
|
|
1514
|
+
return existsSync(local) ? local : shipped
|
|
1515
|
+
})()
|
|
1516
|
+
const GALLERY_CACHE = new Map()
|
|
1517
|
+
|
|
1518
|
+
function galleryPath(key) {
|
|
1519
|
+
if (!key) return null
|
|
1520
|
+
const file = join(SYMBOL_GALLERY_DIR, `${key}.png`)
|
|
1521
|
+
if (existsSync(file)) return file
|
|
1522
|
+
const shipped = join(dirname(dirname(fileURLToPath(import.meta.url))), 'knowledge', 'symbols', `${key}.png`)
|
|
1523
|
+
return existsSync(shipped) ? shipped : null
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
/** 按给定符号名返回图片块(逐张,最多 limit 张)。 */
|
|
1527
|
+
function galleryBlocks(keys, limit = 4) {
|
|
1528
|
+
const blocks = []
|
|
1529
|
+
for (const key of keys ?? []) {
|
|
1530
|
+
if (blocks.length >= limit) break
|
|
1531
|
+
const file = galleryPath(key)
|
|
1532
|
+
if (!file) continue
|
|
1533
|
+
let data = GALLERY_CACHE.get(file)
|
|
1534
|
+
if (!data) {
|
|
1535
|
+
try {
|
|
1536
|
+
data = readFileSync(file).toString('base64')
|
|
1537
|
+
GALLERY_CACHE.set(file, data)
|
|
1538
|
+
} catch {
|
|
1539
|
+
continue
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
blocks.push({ type: 'image', data, mimeType: 'image/png' })
|
|
1543
|
+
}
|
|
1544
|
+
return blocks
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
/** 热表里排在前面的、有图的符号名。 */
|
|
1548
|
+
function galleryKeys(limit = 4) {
|
|
1549
|
+
const keys = []
|
|
1550
|
+
for (const item of COMMON_SYMBOLS) {
|
|
1551
|
+
if (keys.length >= limit) break
|
|
1552
|
+
if (galleryPath(item.s)) keys.push(item.s)
|
|
1553
|
+
}
|
|
1554
|
+
return keys
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
/** 把一张工具结果换成「文字 + 逐张图」。 */
|
|
1558
|
+
function withImages(result, keys, limit = 4) {
|
|
1559
|
+
const images = galleryBlocks(keys, limit)
|
|
1560
|
+
if (images.length === 0) return result
|
|
1561
|
+
return { ...result, content: [...(result.content ?? []), ...images] }
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
/** 四种任务模式:工具子集、该读的技能、硬规则、调用预算。 */
|
|
1565
|
+
const TOOL_MODES = {
|
|
1566
|
+
page: {
|
|
1567
|
+
title: '画一页',
|
|
1568
|
+
tools: ['page_create', 'page_edit', 'page_inspect', 'validate', 'symbol_catalog'],
|
|
1569
|
+
skills: ['eplan-drawing', 'eplan-symbols'],
|
|
1570
|
+
budget: '6~10 次调用:建页骨架 1 次 → 按单元插(同类一批)→ validate → 出图核对 → 局部修,不要整页重画。',
|
|
1571
|
+
rules: [
|
|
1572
|
+
'先把参考拆成单元表:一行一个器件(位号 / 符号 / 引脚 / 接到哪),同类合并成一批再动手。',
|
|
1573
|
+
'一次提交一个单元或一批同类,插完立刻确认引脚同轴、有红线;不要整页画完再回头改。',
|
|
1574
|
+
'focus 已给常用元件引脚;只有表里没有的符号才 symbol_catalog action="pins"。',
|
|
1575
|
+
],
|
|
1576
|
+
},
|
|
1577
|
+
edit: {
|
|
1578
|
+
title: '改一页',
|
|
1579
|
+
tools: ['page_edit', 'page_inspect', 'validate', 'symbol_catalog'],
|
|
1580
|
+
skills: ['eplan-drawing', 'eplan-annotations'],
|
|
1581
|
+
budget: '2~3 次调用:page_edit → validate →(有问题再 page_edit)。改一处不要重建整页。',
|
|
1582
|
+
rules: [
|
|
1583
|
+
'只改需要改的对象;page_edit 的 relocate / relabel 比 delete+create 便宜,也不会丢别的对象。',
|
|
1584
|
+
'改完必须 validate 一次,把 problems 逐条处理完再交付。',
|
|
1585
|
+
'设备标识用 relabel,不要为了改一个标签重建整页。',
|
|
1586
|
+
],
|
|
1587
|
+
},
|
|
1588
|
+
check: {
|
|
1589
|
+
title: '验收交付',
|
|
1590
|
+
tools: ['validate', 'page_inspect', 'export'],
|
|
1591
|
+
skills: ['eplan-review', 'eplan-troubleshooting'],
|
|
1592
|
+
budget: '2 次调用:validate(看 problems)→ page_inspect format=image(看图核对)→ 必要时 export。',
|
|
1593
|
+
rules: [
|
|
1594
|
+
'交付前必须有两样证据:validate 的 problems 清单,和一张渲染图。只有其中一样不算验收。',
|
|
1595
|
+
'problems 里的 label_overlap 只影响可读性,可以不改;其余每条都要处理或明确说明为什么不改。',
|
|
1596
|
+
'export 一律 theme="light",深色底只用于自己看。',
|
|
1597
|
+
],
|
|
1598
|
+
},
|
|
1599
|
+
lib: {
|
|
1600
|
+
title: '查符号与手册',
|
|
1601
|
+
tools: ['symbol_catalog', 'manual'],
|
|
1602
|
+
skills: ['eplan-symbols'],
|
|
1603
|
+
budget: '1~3 次调用:search 定位 → pins 看引脚 / visual 看形状(一次一张样子表)。',
|
|
1604
|
+
rules: [
|
|
1605
|
+
'符号名只能来自 symbol_catalog 的返回,不要根据经验拼。',
|
|
1606
|
+
'search 一次最多 200 条,结果会带 truncated 和 matchedCount;要更窄就加 filter。',
|
|
1607
|
+
'中文概念搜不到是正常的(库里只有英文名):要么换成英文缩写,要么 visual 一次把候选画出来用眼睛认,别翻全表。',
|
|
1608
|
+
'手册里的端子定义可以用 manual action="render" 看原图,比抽文字可靠。',
|
|
1609
|
+
],
|
|
1610
|
+
},
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
let currentMode = 'all'
|
|
1614
|
+
|
|
1615
|
+
/** 生效当前模式:返回真正被启用/停用的工具名,以及该读的技能绝对路径。 */
|
|
1616
|
+
function applyFocus(mode) {
|
|
1617
|
+
const spec = mode === 'all' ? null : TOOL_MODES[mode]
|
|
1618
|
+
if (mode !== 'all' && spec === undefined) {
|
|
1619
|
+
throw fail(
|
|
1620
|
+
'BAD_ARGUMENT',
|
|
1621
|
+
`workspace 不认识 mode="${mode}"。`,
|
|
1622
|
+
`可选:${['all', ...Object.keys(TOOL_MODES)].join(' / ')}`,
|
|
1623
|
+
)
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
// 工具面**不再随模式增删**(2026-11-24 session-400917a2 的教训)。
|
|
1627
|
+
//
|
|
1628
|
+
// 原来这里按模式 disable 工具并发 tools/list_changed:切一次模式,run_code 的 SDK
|
|
1629
|
+
// 声明就变一次 —— ① 系统提示的前缀变了,整段缓存从顶到底作废;② 已经在写的程序
|
|
1630
|
+
// 里 tools.mcp__eplan__workspace 变成 unknown tool / is not a function 半路夭折
|
|
1631
|
+
// (那次白烧 1.5 分钟 + 一轮返工)。全开的代价只是提示词多 2 KB(19.5→21.5 KB),
|
|
1632
|
+
// 换来的是一段全程不变的稳定前缀。
|
|
1633
|
+
//
|
|
1634
|
+
// 模式仍然有用:它决定推荐用哪几个、给哪些必填参数和规则。只是不再限制可达性。
|
|
1635
|
+
const all = [...toolHandles.keys()]
|
|
1636
|
+
for (const [, handle] of toolHandles) handle.enable?.()
|
|
1637
|
+
const recommended = spec === null ? all : ['workspace', ...spec.tools]
|
|
1638
|
+
currentMode = mode
|
|
1639
|
+
|
|
1640
|
+
const payload = {
|
|
1641
|
+
mode,
|
|
1642
|
+
title: spec === null ? '全部工具' : spec.title,
|
|
1643
|
+
active: all,
|
|
1644
|
+
recommended,
|
|
1645
|
+
disabled: [],
|
|
1646
|
+
alwaysAvailable: true,
|
|
1647
|
+
}
|
|
1648
|
+
if (spec !== null) {
|
|
1649
|
+
payload.skills = spec.skills
|
|
1650
|
+
payload.budget = spec.budget
|
|
1651
|
+
payload.rules = spec.rules
|
|
1652
|
+
payload.params = ACTION_PARAMS[mode] ?? ACTION_PARAMS.page
|
|
1653
|
+
}
|
|
1654
|
+
// 常驻热表:引脚几何直接给出来,省掉「先 pins 再插」的往返。
|
|
1655
|
+
payload.symbols = warmSymbols()
|
|
1656
|
+
// 图鉴:紧跟这段文字逐张发常用符号的样子(不是拼图)。
|
|
1657
|
+
// 4 张:一步最多 8 张新图。
|
|
1658
|
+
const gallery = galleryKeys(4)
|
|
1659
|
+
if (gallery.length > 0) {
|
|
1660
|
+
payload.gallery = gallery
|
|
1661
|
+
payload.galleryNote = '按 gallery 的顺序,后面逐张是这几个常用符号的样子。'
|
|
1662
|
+
}
|
|
1663
|
+
payload.note =
|
|
1664
|
+
`工具一共 ${all.length} 个,全部可调(disabled 永远是空)。` +
|
|
1665
|
+
`recommended 是这个模式最该先用的几个,其余照样能调。` +
|
|
1666
|
+
`换模式:workspace action="focus" mode=${FOCUS_MODES.join('|')}。`
|
|
1667
|
+
return payload
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
const planStatusOf = (entries) => {
|
|
1671
|
+
const counts = {}
|
|
1672
|
+
for (const entry of entries ?? []) {
|
|
1673
|
+
const status = entry?.status ?? 'todo'
|
|
1674
|
+
counts[status] = (counts[status] ?? 0) + 1
|
|
1675
|
+
}
|
|
1676
|
+
return counts
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
/**
|
|
1680
|
+
* brief:一次调用拿到「开工需要的全部环境事实」。
|
|
1681
|
+
*
|
|
1682
|
+
* 替代以前的开局三连(status + list_pages + plan_get,实测各 1.6~2.4 KB),
|
|
1683
|
+
* 压到 1.5 KB 以内,并且带上「当前工具面模式」——模型不用猜自己能干什么。
|
|
1684
|
+
*/
|
|
1685
|
+
async function briefResult(args = {}) {
|
|
1686
|
+
const out = { mode: currentMode }
|
|
1687
|
+
|
|
1688
|
+
let status = null
|
|
1689
|
+
try {
|
|
1690
|
+
status = await callBridge('status', {})
|
|
1691
|
+
} catch (error) {
|
|
1692
|
+
out.ready = false
|
|
1693
|
+
out.eplan = { reachable: false, code: error.code ?? 'UNKNOWN', message: error.message }
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
if (status) {
|
|
1697
|
+
const project = status.currentProject ?? null
|
|
1698
|
+
out.ready = status.ready === true
|
|
1699
|
+
out.project = project?.name ?? null
|
|
1700
|
+
out.projectPath = project?.path ?? null
|
|
1701
|
+
out.pageCount = project?.pageCount ?? null
|
|
1702
|
+
out.locked = project?.isLocked === true
|
|
1703
|
+
out.readOnly = project?.isReadOnly === true
|
|
1704
|
+
out.visiblePage = status.visiblePage ?? null
|
|
1705
|
+
out.openProjects = (status.openProjects ?? []).map((item) => item?.name).filter(Boolean)
|
|
1706
|
+
out.symbolLibraries = status.symbolLibraries ?? []
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
const project = args.project ?? out.project ?? null
|
|
1710
|
+
if (project) {
|
|
1711
|
+
try {
|
|
1712
|
+
const listing = await callBridge('pages', { project, limit: 500 })
|
|
1713
|
+
const list = Array.isArray(listing) ? listing : (listing?.pages ?? [])
|
|
1714
|
+
out.pages = list.map((page) => page?.name).filter(Boolean)
|
|
1715
|
+
for (const page of list) {
|
|
1716
|
+
if (page?.name && Array.isArray(page.size)) pageSizeCache.set(`${project}|${page.name}`, page.size)
|
|
1717
|
+
}
|
|
1718
|
+
} catch (error) {
|
|
1719
|
+
out.pagesError = error.message
|
|
1720
|
+
}
|
|
1721
|
+
try {
|
|
1722
|
+
const plan = readPlan(project)
|
|
1723
|
+
out.plan = { count: plan.entries.length, byStatus: planStatusOf(plan.entries) }
|
|
1724
|
+
out.locks = readLocks(project).pages
|
|
1725
|
+
} catch {
|
|
1726
|
+
// 台账是桥本地的,读不到就不给,不影响开工。
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
const ids = eplanProcessIds()
|
|
1731
|
+
if (ids.length > 0) out.eplanProcesses = ids
|
|
1732
|
+
// 两个 EPLAN 实例时,另一个窗口里的页不会跟着更新;开工第一步就要看得见这件事。
|
|
1733
|
+
decorateInstances(out)
|
|
1734
|
+
|
|
1735
|
+
if (out.ready !== true) {
|
|
1736
|
+
// brief 是最容易「看到 ready:false 就再 brief 一次」的地方,指引跟前一步一样。
|
|
1737
|
+
Object.assign(
|
|
1738
|
+
out,
|
|
1739
|
+
notReadyFields({ message: out.eplan?.message, code: out.eplan?.code, processes: ids }),
|
|
1740
|
+
)
|
|
1741
|
+
} else {
|
|
1742
|
+
out.hint =
|
|
1743
|
+
'开工顺序:focus 选模式 → brief 看环境 → 按 mode 的 budget 干活。' +
|
|
1744
|
+
'页面上已标注 locks 的页别动(别人占着)。'
|
|
1745
|
+
}
|
|
1746
|
+
return out
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
// ---------------------------------------------------------------------------
|
|
1750
|
+
// 长操作 job 化:present(切页+出图)与 export(导出)。
|
|
1751
|
+
//
|
|
1752
|
+
// 为什么要 job:PTC 的 run_code 有 120 秒硬上限,present/export 一旦撞上 EPLAN
|
|
1753
|
+
// 模态框或大页渲图就会把整段程序杀掉,前面的调用全部作废(审计里两次 120 s
|
|
1754
|
+
// 超时都是 present)。所以这两个动作支持 wait:false:立刻回 jobId,结果用
|
|
1755
|
+
// workspace/operation_history 的 action="wait" 取。同一个 key 同时只跑一个任务,
|
|
1756
|
+
// 重复提交拿回同一个 jobId,不会排成两条。
|
|
1757
|
+
// ---------------------------------------------------------------------------
|
|
1758
|
+
const JOB_KEEP_MS = 15 * 60 * 1000
|
|
1759
|
+
// 同一个页最近一次「被对话框挡住 / 主线程没回话」的时刻。
|
|
1760
|
+
// 90 秒内不再重发同一个 present:连撞三次的代价是 80 秒 + 三圈模型回合。
|
|
1761
|
+
const STUCK_COOLDOWN_MS = 90 * 1000
|
|
1762
|
+
const recentStuck = new Map()
|
|
1763
|
+
const jobs = new Map()
|
|
1764
|
+
let jobSeq = 0
|
|
1765
|
+
|
|
1766
|
+
function markStuck(key) {
|
|
1767
|
+
if (key) recentStuck.set(key, Date.now())
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
function stuckRecently(key) {
|
|
1771
|
+
const at = recentStuck.get(key)
|
|
1772
|
+
if (!at) return false
|
|
1773
|
+
if (Date.now() - at > STUCK_COOLDOWN_MS) {
|
|
1774
|
+
recentStuck.delete(key)
|
|
1775
|
+
return false
|
|
1776
|
+
}
|
|
1777
|
+
return true
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
function gcJobs(now = Date.now()) {
|
|
1781
|
+
for (const [id, job] of jobs) {
|
|
1782
|
+
const endedAt = job.finishedAt ?? job.startedAt
|
|
1783
|
+
if (now - endedAt > JOB_KEEP_MS) jobs.delete(id)
|
|
1784
|
+
}
|
|
1785
|
+
for (const [key, at] of recentStuck) {
|
|
1786
|
+
if (now - at > STUCK_COOLDOWN_MS) recentStuck.delete(key)
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
function thatJob(jobId) {
|
|
1791
|
+
gcJobs()
|
|
1792
|
+
return jobs.get(jobId)
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
/** 起一个长任务;同 kind+key 已在跑就复用那个 job。 */
|
|
1796
|
+
function startJob({ kind, key, page, project, run }) {
|
|
1797
|
+
gcJobs()
|
|
1798
|
+
for (const job of jobs.values()) {
|
|
1799
|
+
if (job.state === 'running' && job.kind === kind && job.key === key) return { job, reused: true }
|
|
1800
|
+
}
|
|
1801
|
+
const job = {
|
|
1802
|
+
id: `${kind}-${++jobSeq}`,
|
|
1803
|
+
kind,
|
|
1804
|
+
key,
|
|
1805
|
+
page: page ?? null,
|
|
1806
|
+
project: project ?? null,
|
|
1807
|
+
state: 'running',
|
|
1808
|
+
startedAt: Date.now(),
|
|
1809
|
+
}
|
|
1810
|
+
jobs.set(job.id, job)
|
|
1811
|
+
run().then(
|
|
1812
|
+
(result) => {
|
|
1813
|
+
job.state = 'done'
|
|
1814
|
+
job.result = result
|
|
1815
|
+
job.finishedAt = Date.now()
|
|
1816
|
+
},
|
|
1817
|
+
(error) => {
|
|
1818
|
+
job.state = 'failed'
|
|
1819
|
+
job.error = { code: error.code ?? 'UNKNOWN', message: error.message, ...(error.detail ? { detail: error.detail } : {}) }
|
|
1820
|
+
job.finishedAt = Date.now()
|
|
1821
|
+
},
|
|
1822
|
+
)
|
|
1823
|
+
return { job, reused: false }
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
async function presentOnce({ page, project, width, theme }) {
|
|
1827
|
+
// 关键差别是**不重试**:连发 5 次 open_page 会被同一个对话框全部挡回去,
|
|
1828
|
+
// 每次白烧一轮。被挡就把「让用户按 Esc」原样带回,图照样给。
|
|
1829
|
+
//
|
|
1830
|
+
// focus 永远 false(2026-11-27 用户要求):present 只做「软件内切到这一页 + 出一张图」。
|
|
1831
|
+
// 不把 EPLAN 窗口提到前台、不最大化、不改窗口尺寸 —— 渲染比例由 EPLAN 自己的
|
|
1832
|
+
// GraphicPageEx 决定,与窗口状态无关,所以「静默全屏渲染」不需要动窗口。
|
|
1833
|
+
let opened
|
|
1834
|
+
try {
|
|
1835
|
+
opened = await callBridge('page_open', { page, project, focus: false })
|
|
1836
|
+
} catch (error) {
|
|
1837
|
+
opened = {
|
|
1838
|
+
ok: false,
|
|
1839
|
+
code: error.code ?? 'UNKNOWN',
|
|
1840
|
+
message: error.message,
|
|
1841
|
+
...(error.detail ? { detail: error.detail } : {}),
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
let shot = null
|
|
1845
|
+
try {
|
|
1846
|
+
shot = await callBridge('look', { page, project, width, theme })
|
|
1847
|
+
} catch (error) {
|
|
1848
|
+
shot = null
|
|
1849
|
+
opened = { ...opened, lookError: error.message }
|
|
1850
|
+
}
|
|
1851
|
+
const blocked = opened && opened.ok === false && opened.code === 'EPLAN_BLOCKED_BY_DIALOG'
|
|
1852
|
+
if (blocked) markStuck(`${project ?? ''}|${page}`)
|
|
1853
|
+
return {
|
|
1854
|
+
page,
|
|
1855
|
+
project,
|
|
1856
|
+
opened,
|
|
1857
|
+
// 「呈现」= 软件内当前页已经切到这一页,且出了一张图。与窗口是否在前台无关。
|
|
1858
|
+
visible: opened?.visibleInTitle === true,
|
|
1859
|
+
windowStateChanged: false,
|
|
1860
|
+
...(shot ? { imagePath: shot.imagePath, counts: shot.counts, theme, renderMs: shot.renderMs } : {}),
|
|
1861
|
+
...(blocked ? { blocked: true } : {}),
|
|
1862
|
+
...(blocked
|
|
1863
|
+
? {
|
|
1864
|
+
hint: 'EPLAN 正停在模态框或交互命令里,这次切页没有生效。让用户按 Esc 关掉后再说一声;不要连续重试 open_page。图已经渲好,可以先看图确认内容。',
|
|
1865
|
+
}
|
|
1866
|
+
: {}),
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
|
|
1870
|
+
function startPresent({ page, project, width, theme }) {
|
|
1871
|
+
const key = `${project ?? ''}|${page}`
|
|
1872
|
+
// 熔断:刚被挡过就别再发。返回一个「已失败」的 job,形状和其他 job 一样,
|
|
1873
|
+
// 模型看到的是同一套字段 + 一句「先让用户关框」,不会以为这是新任务。
|
|
1874
|
+
if (stuckRecently(key)) {
|
|
1875
|
+
const now = Date.now()
|
|
1876
|
+
const job = {
|
|
1877
|
+
id: `present-${++jobSeq}`,
|
|
1878
|
+
kind: 'present',
|
|
1879
|
+
key,
|
|
1880
|
+
page: page ?? null,
|
|
1881
|
+
project: project ?? null,
|
|
1882
|
+
state: 'failed',
|
|
1883
|
+
startedAt: now,
|
|
1884
|
+
finishedAt: now,
|
|
1885
|
+
blocked: true,
|
|
1886
|
+
error: {
|
|
1887
|
+
code: 'EPLAN_BLOCKED_BY_DIALOG',
|
|
1888
|
+
message: `上一次给「${page}」切页时被 EPLAN 的对话框挡住了,${Math.round(STUCK_COOLDOWN_MS / 1000)} 秒内不再重发。`,
|
|
1889
|
+
detail: '这次什么都没做。让用户切到 EPLAN 把框关掉(或按 Esc),回一句后再继续;不要换个参数绕过。',
|
|
1890
|
+
},
|
|
1891
|
+
}
|
|
1892
|
+
jobs.set(job.id, job)
|
|
1893
|
+
return { job, reused: true }
|
|
1894
|
+
}
|
|
1895
|
+
return startJob({
|
|
1896
|
+
kind: 'present',
|
|
1897
|
+
key,
|
|
1898
|
+
page,
|
|
1899
|
+
project,
|
|
1900
|
+
run: () => presentOnce({ page, project, width, theme }),
|
|
1901
|
+
})
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
function startExport(args) {
|
|
1905
|
+
return startJob({
|
|
1906
|
+
kind: 'export',
|
|
1907
|
+
key: `${args.project ?? ''}|${(args.pages ?? []).join(',')}|${args.kind ?? ''}`,
|
|
1908
|
+
project: args.project,
|
|
1909
|
+
run: () => callBridge('export', { ...args, theme: args.theme ?? config.renderTheme }),
|
|
1910
|
+
})
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
/** job 的一行摘要:running / done / failed 三种,字段按状态裁剪。 */
|
|
1914
|
+
function jobPayload(job, extra = {}) {
|
|
1915
|
+
const base = {
|
|
1916
|
+
jobId: job.id,
|
|
1917
|
+
kind: job.kind,
|
|
1918
|
+
state: job.state,
|
|
1919
|
+
...(job.page ? { page: job.page } : {}),
|
|
1920
|
+
...(job.project ? { project: job.project } : {}),
|
|
1921
|
+
elapsedMs: Math.max(0, (job.finishedAt ?? Date.now()) - job.startedAt),
|
|
1922
|
+
...extra,
|
|
1923
|
+
}
|
|
1924
|
+
if (job.state === 'failed') {
|
|
1925
|
+
return { ...base, error: job.error, hint: '这一任务失败了。EPLAN 被对话框挡住时先让用户按 Esc,不要连续重试。' }
|
|
1926
|
+
}
|
|
1927
|
+
if (job.state === 'running') {
|
|
1928
|
+
if (job.unresponsive) {
|
|
1929
|
+
return {
|
|
1930
|
+
...base,
|
|
1931
|
+
epanUnresponsive: true,
|
|
1932
|
+
hint:
|
|
1933
|
+
'EPLAN 主线程没回话(2 秒探针超时):几乎可以断定正压着一个模态框。'
|
|
1934
|
+
+ '别再 wait、也别重发同一个任务 —— 让用户切到 EPLAN 按 Esc 或点掉那个框,回一句后再继续。'
|
|
1935
|
+
+ '这一步没有任何东西被改坏,页面内容以最近一次渲染图为准。',
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
return {
|
|
1939
|
+
...base,
|
|
1940
|
+
hint: `还在跑(${Math.round(base.elapsedMs / 1000)} 秒)。稍后用 workspace({action:"wait", jobId:"${job.id}"}) 取结果;等的期间可以干别的,别重复提交同一个任务。`,
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
return { ...base, ...job.result }
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
/** 完成时把图作为 image 块一起给出(模型才能真的看图);export 没有图,只回文件清单。 */
|
|
1947
|
+
function jobBlocks(job, extra) {
|
|
1948
|
+
const blocks = [{ type: 'text', text: JSON.stringify(jobPayload(job, extra)) }]
|
|
1949
|
+
const imagePath = job.result?.imagePath
|
|
1950
|
+
if (job.kind === 'present' && job.state === 'done' && imagePath && existsSync(imagePath)) {
|
|
1951
|
+
blocks.push({ type: 'image', data: readFileSync(imagePath).toString('base64'), mimeType: 'image/png' })
|
|
1952
|
+
}
|
|
1953
|
+
return { content: blocks }
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
/**
|
|
1957
|
+
* EPLAN 主线程还答不答话。
|
|
1958
|
+
*
|
|
1959
|
+
* 模态框(含 EPLAN 自己的「硬件错误/存储器访问受阻」)会占住主线程,这时候连 status
|
|
1960
|
+
* 都回不来。用 2 秒的探针,不是用来杀任务,只用来**提前收摊**:
|
|
1961
|
+
* 2026-11-24 session-400917a2 里 present 卡在对话框后面,模型连 wait 三次,
|
|
1962
|
+
* 每次干等 25 秒(t4/5→t4/7 白烧 80 秒)。探针把「是不是卡住了」变成 2 秒内可知。
|
|
1963
|
+
*/
|
|
1964
|
+
async function eplanUnresponsive() {
|
|
1965
|
+
try {
|
|
1966
|
+
await callBridge('status', {}, { timeoutMs: 2000 })
|
|
1967
|
+
return false
|
|
1968
|
+
} catch {
|
|
1969
|
+
return true
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
async function settleJob(job, timeoutMs) {
|
|
1974
|
+
const startedAt = Date.now()
|
|
1975
|
+
const deadline = startedAt + timeoutMs
|
|
1976
|
+
let probed = false
|
|
1977
|
+
while (job.state === 'running' && Date.now() < deadline) {
|
|
1978
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 250))
|
|
1979
|
+
// 10 秒还没完就先探一次:跑得慢和卡死了是两件事,不能都让调用方干等。
|
|
1980
|
+
// (一次正常渲染是 1~3 秒;10 秒还在跑,多半是撞上了模态框。)
|
|
1981
|
+
if (!probed && Date.now() - startedAt > 10000 && job.state === 'running') {
|
|
1982
|
+
probed = true
|
|
1983
|
+
if (await eplanUnresponsive()) {
|
|
1984
|
+
job.unresponsive = true
|
|
1985
|
+
if (job.kind === 'present') markStuck(job.key)
|
|
1986
|
+
break
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
return job
|
|
1991
|
+
}
|
|
1992
|
+
|
|
1993
|
+
/**
|
|
1994
|
+
* 把一句备注并进已经序列化好的结果文本(不改变主结构)。
|
|
1995
|
+
* 解析不了就原样返回 —— 备注的价值不该用「弄坏正常结果」来换。
|
|
1996
|
+
*/
|
|
1997
|
+
function withNote(result, note) {
|
|
1998
|
+
if (!note || result?.isError) return result
|
|
1999
|
+
try {
|
|
2000
|
+
const block = result.content?.find?.((item) => item.type === 'text')
|
|
2001
|
+
const parsed = JSON.parse(block.text)
|
|
2002
|
+
if (!parsed || typeof parsed !== 'object') return result
|
|
2003
|
+
block.text = JSON.stringify({ ...parsed, ...note })
|
|
2004
|
+
} catch {
|
|
2005
|
+
// 不是 JSON 就保持原样。
|
|
2006
|
+
}
|
|
2007
|
+
return result
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
/**
|
|
2011
|
+
* 宿主还是旧版时,把 UNKNOWN_OP 翻成能照着做的话。
|
|
2012
|
+
*
|
|
2013
|
+
* 新增的 op 只有 EPLAN 重启后才会加载;在那之前调用不该只回一句
|
|
2014
|
+
* 「宿主不认识的操作」——模型会以为参数写错了,反复重试。
|
|
2015
|
+
*/
|
|
2016
|
+
function hostOutdated(result, op, fallback) {
|
|
2017
|
+
if (result?.isError !== true) return result
|
|
2018
|
+
try {
|
|
2019
|
+
const block = result.content?.find?.((item) => item.type === 'text')
|
|
2020
|
+
const parsed = JSON.parse(block.text)
|
|
2021
|
+
if (parsed?.code !== 'UNKNOWN_OP') return result
|
|
2022
|
+
parsed.code = 'HOST_OUTDATED'
|
|
2023
|
+
parsed.message = `EPLAN 里加载的还是旧宿主,不认识 ${op}。`
|
|
2024
|
+
parsed.detail = `新宿主已经编译好在 host\\bin,但只有 EPLAN 重新启动后才会加载。现在可以:${fallback}`
|
|
2025
|
+
block.text = JSON.stringify(parsed)
|
|
2026
|
+
} catch {
|
|
2027
|
+
// 解析不了就原样返回。
|
|
2028
|
+
}
|
|
2029
|
+
return result
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
regTool(
|
|
2033
|
+
'workspace',
|
|
2034
|
+
{
|
|
2035
|
+
title: '环境与项目',
|
|
2036
|
+
description:
|
|
2037
|
+
'环境与项目。开工先 focus 选模式,再 brief 一次拿全环境(项目、页清单、当前页、锁定、台账)。\n' +
|
|
2038
|
+
'status 详细状态;list_pages 列页;launch 把 EPLAN 拉起来(工作目录/独占/等 Remoting 都处理好了,别自己 spawn EPLAN.exe);\n' +
|
|
2039
|
+
'open/create_project 开建项目;\n' +
|
|
2040
|
+
'open_page 切页(focus=true 才提窗口);present 切页+提窗口+出图(wait:false 先回 jobId,再用 wait 取);\n' +
|
|
2041
|
+
'follow 跟随:写入后自动在 EPLAN 打开那一页(默认开,throttleMs 节流);\n' +
|
|
2042
|
+
'plan_get/plan_put 读写页台账;claim/release 占位防两个会话改同一页。',
|
|
2043
|
+
inputSchema: z.object({
|
|
2044
|
+
action: z
|
|
2045
|
+
.enum([
|
|
2046
|
+
'brief',
|
|
2047
|
+
'focus',
|
|
2048
|
+
'status',
|
|
2049
|
+
'list_pages',
|
|
2050
|
+
'launch',
|
|
2051
|
+
'open_project',
|
|
2052
|
+
'create_project',
|
|
2053
|
+
'open_page',
|
|
2054
|
+
'present',
|
|
2055
|
+
'wait',
|
|
2056
|
+
'plan_get',
|
|
2057
|
+
'plan_put',
|
|
2058
|
+
'claim',
|
|
2059
|
+
'release',
|
|
2060
|
+
'follow',
|
|
2061
|
+
])
|
|
2062
|
+
.describe('要做什么'),
|
|
2063
|
+
mode: z
|
|
2064
|
+
.enum(['page', 'edit', 'check', 'lib', 'all'])
|
|
2065
|
+
.optional()
|
|
2066
|
+
.describe('focus 的模式,只能是这五个之一:page 画页(默认)/ edit 改页 / check 验收 / lib 查库 / all 全开。没有别的取值'),
|
|
2067
|
+
project,
|
|
2068
|
+
page: z.string().optional().describe('页名,例如 "=MI/13"(present / claim 等用)'),
|
|
2069
|
+
jobId: z.string().optional().describe('wait 要等的 jobId(present/export wait:false 返回)'),
|
|
2070
|
+
owner: z.string().optional().describe('claim 的负责人;省略记为当前进程'),
|
|
2071
|
+
dryRun: z.boolean().optional().describe('create_project 只回报会建在哪、用哪个模板,不真的创建'),
|
|
2072
|
+
list: z
|
|
2073
|
+
.object({
|
|
2074
|
+
filter: z.string().optional().describe('页名子串'),
|
|
2075
|
+
limit: z.number().int().min(1).max(500).optional().describe('最多返回多少页,默认 100'),
|
|
2076
|
+
includePlacements: z.boolean().optional().describe('是否附带每页的放置统计,默认 false'),
|
|
2077
|
+
})
|
|
2078
|
+
.optional()
|
|
2079
|
+
.describe('list_pages 的选项'),
|
|
2080
|
+
open: z
|
|
2081
|
+
.object({
|
|
2082
|
+
name: z.string().optional().describe('项目名,例如 test'),
|
|
2083
|
+
path: z.string().optional().describe('.elk 完整路径,优先于 name'),
|
|
2084
|
+
dir: z.string().optional().describe('项目目录,省略用默认'),
|
|
2085
|
+
focus: z
|
|
2086
|
+
.boolean()
|
|
2087
|
+
.optional()
|
|
2088
|
+
.describe('把窗口提到最前,默认 false;只有用户说「打开给我看」才传 true'),
|
|
2089
|
+
})
|
|
2090
|
+
.optional()
|
|
2091
|
+
.describe('open_project / open_page 选项'),
|
|
2092
|
+
create: z
|
|
2093
|
+
.object({
|
|
2094
|
+
name: z.string().describe('新项目名'),
|
|
2095
|
+
template: z.string().optional().describe('.ept 模板路径;省略用 GB_tpl001.ept'),
|
|
2096
|
+
creator: z.string().optional().describe('写进 PROJ_CREATORLONGNAME'),
|
|
2097
|
+
dir: z.string().optional().describe('建在哪个目录'),
|
|
2098
|
+
dryRun: z.boolean().optional().describe('只回报会建在哪,不创建'),
|
|
2099
|
+
})
|
|
2100
|
+
.optional()
|
|
2101
|
+
.describe('create_project 选项'),
|
|
2102
|
+
force: z
|
|
2103
|
+
.boolean()
|
|
2104
|
+
.optional()
|
|
2105
|
+
.describe('launch 用:EPLAN 已经就绪时仍然再起一个实例(默认不,避免多实例抢项目锁)'),
|
|
2106
|
+
present: z
|
|
2107
|
+
.object({
|
|
2108
|
+
width: z.number().int().min(400).max(4000).optional().describe('渲图宽度,默认 2000'),
|
|
2109
|
+
theme: z.enum(['dark', 'light']).optional().describe('渲图配色,默认按配置(深色)'),
|
|
2110
|
+
wait: z
|
|
2111
|
+
.boolean()
|
|
2112
|
+
.optional()
|
|
2113
|
+
.describe('是否等出图,默认 true;false 立刻回 jobId,用 action="wait" 取'),
|
|
2114
|
+
waitMs: z
|
|
2115
|
+
.number()
|
|
2116
|
+
.int()
|
|
2117
|
+
.min(1000)
|
|
2118
|
+
.max(110000)
|
|
2119
|
+
.optional()
|
|
2120
|
+
.describe('最多等多少毫秒,默认 30000;等不到回 jobId 而不是报错'),
|
|
2121
|
+
})
|
|
2122
|
+
.optional()
|
|
2123
|
+
.describe('present 选项'),
|
|
2124
|
+
plan: z
|
|
2125
|
+
.array(
|
|
2126
|
+
z.object({
|
|
2127
|
+
page: z.string().optional(),
|
|
2128
|
+
title: z.string().optional(),
|
|
2129
|
+
status: z.enum(['todo', 'drawing', 'review', 'done']).optional(),
|
|
2130
|
+
owner: z.string().optional(),
|
|
2131
|
+
note: z.string().optional(),
|
|
2132
|
+
}),
|
|
2133
|
+
)
|
|
2134
|
+
.optional()
|
|
2135
|
+
.describe('plan_put 的页清单;传了就整体覆盖'),
|
|
2136
|
+
}).passthrough(),
|
|
2137
|
+
},
|
|
2138
|
+
async (args) => {
|
|
2139
|
+
// 兼容老的平铺写法:filter / limit / name / path / dir / template / items / width / theme 直接在顶层时照样认。
|
|
2140
|
+
const listOpts = args.list ?? {}
|
|
2141
|
+
const openOpts = args.open ?? {}
|
|
2142
|
+
const createOpts = args.create ?? {}
|
|
2143
|
+
const presentOpts = args.present ?? {}
|
|
2144
|
+
const planItems = args.plan ?? args.items
|
|
2145
|
+
|
|
2146
|
+
switch (args.action) {
|
|
2147
|
+
case 'brief':
|
|
2148
|
+
return ok(await briefResult({ project: args.project }))
|
|
2149
|
+
case 'focus': {
|
|
2150
|
+
const focused = applyFocus(args.mode ?? 'page')
|
|
2151
|
+
return withImages(ok(focused), focused.gallery ?? [], 4)
|
|
2152
|
+
}
|
|
2153
|
+
case 'status':
|
|
2154
|
+
return statusResult()
|
|
2155
|
+
case 'list_pages':
|
|
2156
|
+
return invoke('pages', {
|
|
2157
|
+
project: args.project,
|
|
2158
|
+
filter: listOpts.filter ?? args.filter,
|
|
2159
|
+
limit: listOpts.limit ?? args.limit,
|
|
2160
|
+
includePlacements: listOpts.includePlacements ?? args.includePlacements,
|
|
2161
|
+
})
|
|
2162
|
+
case 'open_project': {
|
|
2163
|
+
const name = openOpts.name ?? args.name
|
|
2164
|
+
const path = openOpts.path ?? args.path
|
|
2165
|
+
if (!name && !path) need({ name }, ['name'], 'open_project')
|
|
2166
|
+
return openProject({ ...args, name, path, dir: openOpts.dir ?? args.dir })
|
|
2167
|
+
}
|
|
2168
|
+
case 'create_project': {
|
|
2169
|
+
const name = createOpts.name ?? args.name
|
|
2170
|
+
const template = createOpts.template ?? args.template
|
|
2171
|
+
const creator = createOpts.creator ?? args.creator
|
|
2172
|
+
const dir = createOpts.dir ?? args.dir
|
|
2173
|
+
const dryRun = createOpts.dryRun ?? args.dryRun
|
|
2174
|
+
if (!name) need({ name }, ['name'], 'create_project')
|
|
2175
|
+
return invoke('project_create', {
|
|
2176
|
+
name,
|
|
2177
|
+
directory: dir,
|
|
2178
|
+
template,
|
|
2179
|
+
// 宿主按 AnyPropertyId 标识名收属性,创建者就是 PROJ_CREATORLONGNAME。
|
|
2180
|
+
...(creator ? { properties: { PROJ_CREATORLONGNAME: creator } } : {}),
|
|
2181
|
+
dryRun: dryRun === true,
|
|
2182
|
+
})
|
|
2183
|
+
}
|
|
2184
|
+
case 'launch': {
|
|
2185
|
+
// 自己 spawn EPLAN.exe 的坑:工作目录不对会在 30~90 秒后静默退出,带 .elk 参数
|
|
2186
|
+
// 启动也不会加载项目;而「进程起来了」不等于「API 通了」。
|
|
2187
|
+
// 桥接器里的 launch 已经把这些都处理对了(ShellExecute 起独立进程 + 轮询 Remoting
|
|
2188
|
+
// 最多 60 秒),这里只是把它暴露成一个 action。
|
|
2189
|
+
// 2026-11-23 session-a18a4a7f:模型不知道有这个,自己杀了又起起了又杀,花了 25 次调用。
|
|
2190
|
+
//
|
|
2191
|
+
// 先看是不是已经能用了:已经 ready 还去 launch,只会多开一个实例,然后就是
|
|
2192
|
+
// 「多用户冲突 / 数据库被另一用户单独锁定」那条老路。要真的重开必须 force:true。
|
|
2193
|
+
let current = null
|
|
2194
|
+
try {
|
|
2195
|
+
current = await callBridge('status', {}, { timeoutMs: 20000 })
|
|
2196
|
+
} catch {
|
|
2197
|
+
current = null
|
|
2198
|
+
}
|
|
2199
|
+
if (current?.ready === true && (openOpts.force ?? args.force) !== true) {
|
|
2200
|
+
return ok({
|
|
2201
|
+
alreadyRunning: true,
|
|
2202
|
+
ready: true,
|
|
2203
|
+
project: current.currentProject?.name ?? null,
|
|
2204
|
+
visiblePage: current.visiblePage ?? null,
|
|
2205
|
+
hint:
|
|
2206
|
+
'EPLAN 已经在跑而且 API 已经通了,不用 launch —— 直接干活就行(brief / open_page / page_create)。' +
|
|
2207
|
+
'确实要再起一个实例才传 force:true。',
|
|
2208
|
+
})
|
|
2209
|
+
}
|
|
2210
|
+
// 探测不到 ≠ 没在跑。
|
|
2211
|
+
//
|
|
2212
|
+
// status 20 秒没回话,最可能是 EPLAN 正启动中或压着模态框,而不是没开。
|
|
2213
|
+
// 如果这时候还去 launch,就会多起一个实例:两个 EPLAN 抢同一个项目/同一个数据目录,
|
|
2214
|
+
// 表现是两边轮流弹「硬件错误:存储器访问受阻」,谁都干不了活。
|
|
2215
|
+
// 2026-11-24 实测:一个会话把 status 超时当成「没开」,结果本机同时挂了两个 EPLAN。
|
|
2216
|
+
const force = (openOpts.force ?? args.force) === true
|
|
2217
|
+
const running = eplanProcessIds()
|
|
2218
|
+
const decision = decideLaunch({ ready: current?.ready === true, answered: current !== null, processes: running, force })
|
|
2219
|
+
if (decision === 'wait') {
|
|
2220
|
+
return ok({
|
|
2221
|
+
alreadyRunning: true,
|
|
2222
|
+
starting: true,
|
|
2223
|
+
ready: false,
|
|
2224
|
+
processes: running,
|
|
2225
|
+
hint:
|
|
2226
|
+
`本机已经有 EPLAN 进程(pid ${running.join(', ')}),只是 status 没回话 —— 多半还在启动,` +
|
|
2227
|
+
'或者被对话框压着。等 30~60 秒再 workspace{action:"status"} 一次,别开第二个实例:' +
|
|
2228
|
+
'两个实例抢同一个项目和数据目录会互相弹「硬件错误:存储器访问受阻」。' +
|
|
2229
|
+
'确实要再起一个才传 force:true。',
|
|
2230
|
+
})
|
|
2231
|
+
}
|
|
2232
|
+
const elk = args.project || args.name ? projectElkPath({ name: args.name ?? args.project, path: args.path, dir: args.dir }) : null
|
|
2233
|
+
let launched
|
|
2234
|
+
try {
|
|
2235
|
+
launched = await callBridge(
|
|
2236
|
+
'launch',
|
|
2237
|
+
{
|
|
2238
|
+
...(args.path ? { path: args.path } : {}),
|
|
2239
|
+
...(args.variant ? { variant: args.variant } : {}),
|
|
2240
|
+
...(elk ? { project: elk } : {}),
|
|
2241
|
+
},
|
|
2242
|
+
{ timeoutMs: 90000 },
|
|
2243
|
+
)
|
|
2244
|
+
} catch (error) {
|
|
2245
|
+
return failed('launch', error)
|
|
2246
|
+
}
|
|
2247
|
+
// 起完再看一眼状态:launch 已经等过 Remoting,这里只是把「通没通」说清楚。
|
|
2248
|
+
let ready = null
|
|
2249
|
+
try {
|
|
2250
|
+
const status = await callBridge('status', {}, { timeoutMs: 20000 })
|
|
2251
|
+
ready = status?.ready === true
|
|
2252
|
+
} catch {
|
|
2253
|
+
ready = false
|
|
2254
|
+
}
|
|
2255
|
+
return ok({
|
|
2256
|
+
launch: launched,
|
|
2257
|
+
projectPath: elk,
|
|
2258
|
+
ready,
|
|
2259
|
+
nextSteps: ready
|
|
2260
|
+
? ['已经能用了:接着 workspace{action:"brief"} 或直接干活。']
|
|
2261
|
+
: [
|
|
2262
|
+
'Remoting 还没挂起来:EPLAN 启动慢是常态,等 30~60 秒再 workspace{action:"status"} 一次,别连着重试。',
|
|
2263
|
+
elk ? `项目 ${basename(elk)} 没自动加载就 workspace{action:"open_project", name:"${basename(elk).replace(/\.elk$/i, '')}"}。` : '知道项目名的话用 workspace{action:"open_project", name:"<项目名>"} 打开。',
|
|
2264
|
+
],
|
|
2265
|
+
})
|
|
2266
|
+
}
|
|
2267
|
+
case 'open_page':
|
|
2268
|
+
need(args, ['page'], 'open_page')
|
|
2269
|
+
// focus 一律 false:切页只切软件内的当前页,不抢前台、不最大化。
|
|
2270
|
+
// 参数仍然接受(老调用不报错),但传 true 不会改变任何窗口状态。
|
|
2271
|
+
return invoke('page_open', {
|
|
2272
|
+
page: args.page,
|
|
2273
|
+
project: args.project,
|
|
2274
|
+
focus: false,
|
|
2275
|
+
})
|
|
2276
|
+
case 'follow': {
|
|
2277
|
+
// 跟随开关:写成功后自动在 EPLAN 打开那一页。enabled=false 就完全不动界面。
|
|
2278
|
+
if (typeof args.enabled === 'boolean') followOpts.enabled = args.enabled
|
|
2279
|
+
if (Number.isFinite(Number(args.throttleMs))) {
|
|
2280
|
+
followOpts.throttleMs = Math.min(Math.max(Number(args.throttleMs), 0), 30000)
|
|
2281
|
+
}
|
|
2282
|
+
// 立刻定位一次当前页(不带参数时用 status 里的 visiblePage),方便确认跟随生效。
|
|
2283
|
+
let moved = null
|
|
2284
|
+
if (args.page) moved = await openInEplan(args.page, args.project)
|
|
2285
|
+
return ok({ follow: { ...followOpts, lastPage: lastFollow.page, lastAt: lastFollow.at || null }, moved })
|
|
2286
|
+
}
|
|
2287
|
+
case 'present': {
|
|
2288
|
+
need(args, ['page'], 'present')
|
|
2289
|
+
const width = presentOpts.width ?? args.width ?? 2000
|
|
2290
|
+
const theme = presentOpts.theme ?? args.theme ?? config.renderTheme
|
|
2291
|
+
const { job, reused } = startPresent({ page: args.page, project: args.project, width, theme })
|
|
2292
|
+
// wait:false 立刻返回,绕开 run_code 的 120 秒硬砍;默认等 30 秒,等不到
|
|
2293
|
+
// 也返回 jobId 而不是报错,程序可以接着用 operation_history 取。
|
|
2294
|
+
if ((presentOpts.wait ?? args.wait) === false) {
|
|
2295
|
+
return ok(jobPayload(job, reused ? { reused: true } : {}))
|
|
2296
|
+
}
|
|
2297
|
+
const waitMs = Math.min(Math.max(Number(presentOpts.waitMs ?? args.waitMs ?? 30000), 1000), 110000)
|
|
2298
|
+
await settleJob(job, waitMs)
|
|
2299
|
+
return jobBlocks(job, reused ? { reused: true } : {})
|
|
2300
|
+
}
|
|
2301
|
+
case 'wait': {
|
|
2302
|
+
need(args, ['jobId'], 'wait')
|
|
2303
|
+
gcJobs()
|
|
2304
|
+
const job = thatJob(args.jobId)
|
|
2305
|
+
if (!job) {
|
|
2306
|
+
return ok({
|
|
2307
|
+
jobId: args.jobId,
|
|
2308
|
+
state: 'unknown',
|
|
2309
|
+
hint: '找不到这个 job:可能已完成并过了 15 分钟保留期,或 id 写错。jobId 来自 present/export 的返回。',
|
|
2310
|
+
})
|
|
2311
|
+
}
|
|
2312
|
+
const timeoutMs = Math.min(Math.max(Number(args.timeoutMs ?? 25000), 1000), 110000)
|
|
2313
|
+
await settleJob(job, timeoutMs)
|
|
2314
|
+
return job.state === 'done' && job.result?.imagePath
|
|
2315
|
+
? jobBlocks(job, { waitedMs: timeoutMs })
|
|
2316
|
+
: ok(jobPayload(job, { waitedMs: timeoutMs }))
|
|
2317
|
+
}
|
|
2318
|
+
case 'plan_get': {
|
|
2319
|
+
need(args, ['project'], 'plan_get')
|
|
2320
|
+
const plan = readPlan(args.project)
|
|
2321
|
+
const locks = readLocks(args.project)
|
|
2322
|
+
return ok({
|
|
2323
|
+
project: args.project,
|
|
2324
|
+
file: plan.file,
|
|
2325
|
+
count: plan.entries.length,
|
|
2326
|
+
entries: plan.entries,
|
|
2327
|
+
locks: locks.pages,
|
|
2328
|
+
})
|
|
2329
|
+
}
|
|
2330
|
+
case 'plan_put': {
|
|
2331
|
+
need(args, ['project'], 'plan_put')
|
|
2332
|
+
if (!Array.isArray(planItems)) {
|
|
2333
|
+
throw fail('BAD_ARGUMENT', 'plan_put 需要 plan 数组。', '每项至少给 page(或 title),可带 status/owner/note。')
|
|
2334
|
+
}
|
|
2335
|
+
return ok(writePlan(args.project, planItems))
|
|
2336
|
+
}
|
|
2337
|
+
case 'claim':
|
|
2338
|
+
need(args, ['project', 'page'], 'claim')
|
|
2339
|
+
return ok(claimPage({ project: args.project, page: args.page, owner: args.owner }))
|
|
2340
|
+
case 'release':
|
|
2341
|
+
need(args, ['project', 'page'], 'release')
|
|
2342
|
+
return ok(releasePage({ project: args.project, page: args.page }))
|
|
2343
|
+
default:
|
|
2344
|
+
throw fail(
|
|
2345
|
+
'BAD_ARGUMENT',
|
|
2346
|
+
`workspace 不认识 action="${args.action}"。`,
|
|
2347
|
+
'只支持 brief / focus / status / list_pages / launch / open_project / create_project / open_page / present / wait / plan_get / plan_put / claim / release / follow。',
|
|
2348
|
+
)
|
|
2349
|
+
}
|
|
2350
|
+
},
|
|
2351
|
+
)
|
|
2352
|
+
|
|
2353
|
+
// 中文概念 → 已知符号名。只收「本机符号库里亲手确认过」的组合(来自 COMMON_SYMBOLS
|
|
2354
|
+
// 的用途说明和 annotate 进知识库的记录),不凭经验编。
|
|
2355
|
+
// 目的:2026-11-23 session-a18a4a7f 里模型用「按钮」搜不到任何东西,只好翻 1000 多
|
|
2356
|
+
// 个符号名、再建 4 张试画页用眼睛认 —— 18 次调用全花在这上面。
|
|
2357
|
+
const SYMBOL_CONCEPTS = [
|
|
2358
|
+
{ match: ['中断点', '断点', '跳转'], symbols: ['BP'], note: 'SPECIAL,竖排;v1/3/5/7 是四个方向' },
|
|
2359
|
+
{ match: ['连接点', '节点'], symbols: ['CO', 'TLRU', 'TOUR', 'TLRO', 'TOUL'], note: 'CO 是单点,TLRU/TOUR/TLRO/TOUL 是 T 形分支' },
|
|
2360
|
+
{ match: ['电源', '引入点', '进线'], symbols: ['CDPST'], note: 'SPECIAL,上下各 4 mm' },
|
|
2361
|
+
{ match: ['空开', '断路器', '微型断路器', '三极'], symbols: ['FA3'], note: 'GB_symbol,三极,极距 8 mm' },
|
|
2362
|
+
{ match: ['端子', '端子排'], symbols: ['DCP', 'X2'], note: 'DCP 是端子连接点;X2 是端子排本体' },
|
|
2363
|
+
{ match: ['接地', 'PE'], symbols: ['ERDE'], note: '保护接地' },
|
|
2364
|
+
]
|
|
2365
|
+
|
|
2366
|
+
function conceptHits(keyword) {
|
|
2367
|
+
const text = String(keyword ?? '').trim()
|
|
2368
|
+
if (text.length === 0) return []
|
|
2369
|
+
return SYMBOL_CONCEPTS.filter((entry) => entry.match.some((word) => text.includes(word) || word.includes(text)))
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2372
|
+
/** 挑一个没被占用的临时页名:=TMP/90 起,往后找到空号为止。 */
|
|
2373
|
+
async function pickScratchPage(project) {
|
|
2374
|
+
let taken = new Set()
|
|
2375
|
+
try {
|
|
2376
|
+
const listing = await callBridge('pages', { project, limit: 500 })
|
|
2377
|
+
const list = Array.isArray(listing) ? listing : (listing?.pages ?? [])
|
|
2378
|
+
taken = new Set(list.map((page) => String(page?.name ?? page)))
|
|
2379
|
+
} catch {
|
|
2380
|
+
// 列不出页就按顺序试,撞名会由 page_create 报出来(下面有兜底提示)。
|
|
2381
|
+
}
|
|
2382
|
+
for (let number = 90; number <= 99; number += 1) {
|
|
2383
|
+
const candidate = `=TMP/${number}`
|
|
2384
|
+
if (!taken.has(candidate)) return candidate
|
|
2385
|
+
}
|
|
2386
|
+
throw fail(
|
|
2387
|
+
'SCRATCH_PAGE_EXHAUSTED',
|
|
2388
|
+
'=TMP/90~99 都被占了,没有空号建样子表。',
|
|
2389
|
+
'删掉几张没用的 =TMP 临时页再试(page_delete),或者直接用 page_inspect 看已有的页。',
|
|
2390
|
+
)
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
/**
|
|
2394
|
+
* 一张「符号样子表」:把若干符号按网格画到一张临时页上、每个上面标名字,渲一张图。
|
|
2395
|
+
*
|
|
2396
|
+
* 为什么值得做成一个 action:模型自己摸索出来的办法就是这个(建 =TMP 页 → 摆 28 个
|
|
2397
|
+
* 符号 → 渲图 → 用 ffmpeg 裁 6 张放大看),一次画图花了 18 次调用。这里把它压成 1 次,
|
|
2398
|
+
* 而且渲的是 EPLAN 自己画的图形,不是拼图。页用完就删(失败也删)。
|
|
2399
|
+
*/
|
|
2400
|
+
async function symbolVisualSheet({ project, symbols, library, cols = 6, width = 2400 }) {
|
|
2401
|
+
const list = (Array.isArray(symbols) ? symbols : []).filter((item) => typeof item === 'string' && item.length > 0)
|
|
2402
|
+
if (list.length === 0) {
|
|
2403
|
+
throw fail('BAD_ARGUMENT', 'visual 需要 symbols 数组。', '照这个写:symbol_catalog{action:"visual", symbols:["SON","SSA","KM2"]}。')
|
|
2404
|
+
}
|
|
2405
|
+
const capped = list.slice(0, 36)
|
|
2406
|
+
const perRow = Math.min(Math.max(cols, 2), 8)
|
|
2407
|
+
const dx = 34
|
|
2408
|
+
const dy = 48
|
|
2409
|
+
// 页名必须符合 =高层/页号(页号是数字),而且不能撞上已有的页 —— 先看现在有哪些页,
|
|
2410
|
+
// 挑一个空号;90~99 是留给这种临时页的(实测 =TMP/V1 会被 BAD_PAGE_NAME 拒绝)。
|
|
2411
|
+
const page = await pickScratchPage(project)
|
|
2412
|
+
const nodes = []
|
|
2413
|
+
const texts = []
|
|
2414
|
+
capped.forEach((symbol, index) => {
|
|
2415
|
+
const x = 30 + (index % perRow) * dx
|
|
2416
|
+
const y = 250 - Math.floor(index / perRow) * dy
|
|
2417
|
+
nodes.push({ symbol, ...(library ? { library } : {}), at: [x, y] })
|
|
2418
|
+
texts.push({ at: [x - 15, y + 14], text: symbol, height: 2.5 })
|
|
2419
|
+
})
|
|
2420
|
+
|
|
2421
|
+
let created = false
|
|
2422
|
+
try {
|
|
2423
|
+
// 整页渲一次再裁到元件所在的那块:420 mm 宽的页按 2400 px 出图只有 5.7 px/mm,
|
|
2424
|
+
// 一个 4 mm 的符号只有 23 px,认不出形状。按 4200 px(10 px/mm)渲、裁到布局区域,
|
|
2425
|
+
// 图既清楚又不把整页空白塞进上下文。
|
|
2426
|
+
const renderWidth = Math.max(4200, width)
|
|
2427
|
+
await callBridge('page_create', { project, name: page, type: 'Schematic', grid: 2, nodes, texts })
|
|
2428
|
+
created = true
|
|
2429
|
+
const shot = await callBridge('look', { project, page, width: renderWidth, theme: config.renderTheme })
|
|
2430
|
+
const render = shot ?? {}
|
|
2431
|
+
const full = render.imagePath
|
|
2432
|
+
if (!full || !existsSync(full)) {
|
|
2433
|
+
throw fail('RENDER_FAILED', '样子表渲不出图。', '可能这一页建出来了但渲染失败,试试 page_inspect format=image 直接看它。')
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
// 布局 → 裁剪框(mm)。EPLAN 的 y 向上,图片 y 向下,所以按页高翻转。
|
|
2437
|
+
const rows = Math.ceil(capped.length / perRow)
|
|
2438
|
+
const pageW = Number(render.pageSize?.[0] ?? 420)
|
|
2439
|
+
const pageH = Number(render.pageSize?.[1] ?? 297)
|
|
2440
|
+
const x0 = 30 - 15 - 6
|
|
2441
|
+
const x1 = 30 + (perRow - 1) * dx + 15 + 6
|
|
2442
|
+
const yTop = 250 + 14 + 10
|
|
2443
|
+
const yBottom = 250 - Math.max(0, rows - 1) * dy - 12
|
|
2444
|
+
const perMm = renderWidth / pageW
|
|
2445
|
+
const crop = {
|
|
2446
|
+
x: Math.max(0, Math.round(x0 * perMm)),
|
|
2447
|
+
y: Math.max(0, Math.round((pageH - yTop) * perMm)),
|
|
2448
|
+
w: Math.round((x1 - x0) * perMm),
|
|
2449
|
+
h: Math.round((yTop - yBottom) * perMm),
|
|
2450
|
+
}
|
|
2451
|
+
const cropped = await cropImage(full, crop, `vis-${page.replace(/[^0-9]/g, '') || 'x'}-${Date.now()}.png`)
|
|
2452
|
+
const imagePath = cropped.path ?? full
|
|
2453
|
+
|
|
2454
|
+
const meta = {
|
|
2455
|
+
page,
|
|
2456
|
+
cols: perRow,
|
|
2457
|
+
symbols: capped,
|
|
2458
|
+
missing: list.slice(capped.length),
|
|
2459
|
+
layout: `每行 ${perRow} 个,从左到右、从上到下,名字在该符号上方`,
|
|
2460
|
+
note: '这是 EPLAN 真渲染的临时页(已裁到元件区域),看完即删;按顺序对应 symbols 里的名字。',
|
|
2461
|
+
imagePath,
|
|
2462
|
+
...(cropped.error ? { cropError: cropped.error } : {}),
|
|
2463
|
+
render: { width: renderWidth, pageSize: render.pageSize, counts: render.counts },
|
|
2464
|
+
}
|
|
2465
|
+
const blocks = [{ type: 'text', text: JSON.stringify(meta) }]
|
|
2466
|
+
if (imagePath && existsSync(imagePath)) {
|
|
2467
|
+
blocks.push({ type: 'image', data: readFileSync(imagePath).toString('base64'), mimeType: 'image/png' })
|
|
2468
|
+
}
|
|
2469
|
+
return { content: blocks }
|
|
2470
|
+
} finally {
|
|
2471
|
+
if (created) {
|
|
2472
|
+
try {
|
|
2473
|
+
await callBridge('page_delete', { project, page })
|
|
2474
|
+
} catch {
|
|
2475
|
+
// 删不掉只留一页垃圾,不影响这次调用的结果;别让它把结果变成失败。
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
/**
|
|
2482
|
+
* 裁一张 PNG 到 box(像素)。失败就返回原图 —— 图在,只是没那么清楚,比整轮失败好。
|
|
2483
|
+
* ffmpeg 的位置复用 video.mjs 的查找逻辑(本机装在 Program Files 下,不在 PATH 里)。
|
|
2484
|
+
*/
|
|
2485
|
+
async function cropImage(source, box, name) {
|
|
2486
|
+
try {
|
|
2487
|
+
const { findBinary } = await import('./video.mjs')
|
|
2488
|
+
const ffmpeg = findBinary('ffmpeg')
|
|
2489
|
+
const outDir = join(tmpdir(), 'eplan-mcp', 'visual')
|
|
2490
|
+
mkdirSync(outDir, { recursive: true })
|
|
2491
|
+
const target = join(outDir, name)
|
|
2492
|
+
const result = spawnSync(
|
|
2493
|
+
ffmpeg,
|
|
2494
|
+
[
|
|
2495
|
+
'-hide_banner', '-loglevel', 'error', '-y',
|
|
2496
|
+
'-i', source,
|
|
2497
|
+
'-vf', `crop=${Math.max(2, box.w)}:${Math.max(2, box.h)}:${Math.max(0, box.x)}:${Math.max(0, box.y)}`,
|
|
2498
|
+
target,
|
|
2499
|
+
],
|
|
2500
|
+
{ encoding: 'utf8', timeout: 30000, windowsHide: true },
|
|
2501
|
+
)
|
|
2502
|
+
if (result.status === 0 && existsSync(target) && statSync(target).size > 0) return { path: target }
|
|
2503
|
+
return { path: source, error: String(result.stderr ?? '').trim().slice(0, 200) || 'crop 失败' }
|
|
2504
|
+
} catch (error) {
|
|
2505
|
+
return { path: source, error: String(error?.message ?? error).slice(0, 200) }
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
|
|
2509
|
+
|
|
2510
|
+
|
|
2511
|
+
regTool(
|
|
2512
|
+
'symbol_catalog',
|
|
2513
|
+
{
|
|
2514
|
+
title: '符号与元件',
|
|
2515
|
+
description:
|
|
2516
|
+
'查符号库与元件的工程含义。插任何元件之前先确认它存在、引脚在哪。\n' +
|
|
2517
|
+
'search 按名字查(query/filter/name/keyword 同义;offset 分页,一次最多 200 条);\n' +
|
|
2518
|
+
'pins 查引脚坐标与朝向;visual 把几个符号真画到临时页上渲一张图,用眼睛认形状(1 次调用,用完即删);\n' +
|
|
2519
|
+
'lookup 查已记录的语义;annotate 把你确认过的含义写回知识库。',
|
|
2520
|
+
inputSchema: z.object({
|
|
2521
|
+
action: z.enum(['search', 'pins', 'lookup', 'annotate', 'visual']).describe('要做什么'),
|
|
2522
|
+
project,
|
|
2523
|
+
library: z.string().optional().describe(`符号库名,默认 ${DEFAULTS.symbolLibrary}`),
|
|
2524
|
+
filter: z.string().optional().describe('search 的符号名子串;中文概念也行(按钮/空开/接地)'),
|
|
2525
|
+
query: z.string().optional().describe('filter 的别名'),
|
|
2526
|
+
name: z.string().optional().describe('filter 的别名'),
|
|
2527
|
+
keyword: z.string().optional().describe('filter 的别名'),
|
|
2528
|
+
limit: z.number().int().min(1).max(200).optional().describe('search 每页条数,默认 50,上限 200'),
|
|
2529
|
+
offset: z
|
|
2530
|
+
.number()
|
|
2531
|
+
.int()
|
|
2532
|
+
.min(0)
|
|
2533
|
+
.optional()
|
|
2534
|
+
.describe('search 的起始位置,默认 0;返回里带 nextOffset,到不了时会明说被 200 条上限挡住'),
|
|
2535
|
+
refresh: z.boolean().optional().describe('同参数且结果没变时默认回 unchanged;要强制重发传 true'),
|
|
2536
|
+
symbols: z.array(z.string()).optional().describe('pins 的符号名数组,例如 ["FA3","TLRU"];也接受单个 symbol。visual 用它指定要看哪些'),
|
|
2537
|
+
symbol: z.string().optional().describe('pins 的单个符号名(等价于 symbols:[name]);lookup / annotate 也用这个'),
|
|
2538
|
+
cols: z.number().int().min(2).max(8).optional().describe('visual 每行摆几个,默认 6'),
|
|
2539
|
+
width: z.number().int().min(600).max(6000).optional().describe('visual 出图宽度,默认 2400'),
|
|
2540
|
+
concept: z.string().optional().describe('annotate 的工程概念,例如 两极断路器'),
|
|
2541
|
+
usage: z.string().optional().describe('annotate 的用途说明'),
|
|
2542
|
+
}),
|
|
2543
|
+
},
|
|
2544
|
+
async (args) => {
|
|
2545
|
+
// 搜索关键词的四种写法收敛成一个(实测模型先试 query、再试 filter、再试 name)。
|
|
2546
|
+
const keyword = args.filter ?? args.query ?? args.name ?? args.keyword
|
|
2547
|
+
switch (args.action) {
|
|
2548
|
+
case 'search': {
|
|
2549
|
+
const want = Number.isFinite(args.limit) ? args.limit : 50
|
|
2550
|
+
const offset = Number.isFinite(args.offset) ? Math.max(0, args.offset) : 0
|
|
2551
|
+
// 中文概念先查本机的对应表:宿主的 filter 只认符号名子串,"按钮" 永远查不到东西。
|
|
2552
|
+
const concepts = conceptHits(keyword)
|
|
2553
|
+
const cjk = /[\u4e00-\u9fff]/.test(String(keyword ?? ''))
|
|
2554
|
+
if (cjk && concepts.length === 0) {
|
|
2555
|
+
return ok({
|
|
2556
|
+
library: args.library ?? DEFAULTS.symbolLibrary,
|
|
2557
|
+
matchedCount: 0,
|
|
2558
|
+
returned: 0,
|
|
2559
|
+
symbols: [],
|
|
2560
|
+
hint:
|
|
2561
|
+
`符号库里没有中文名,"${keyword}" 查不到东西是正常的。两条路:\n` +
|
|
2562
|
+
'① 用英文/缩写子串再查(例如 SON、KM2、FA);\n' +
|
|
2563
|
+
'② 直接 symbol_catalog{action:"visual", symbols:[...]} 把它们画出来用眼睛认(1 次调用)。',
|
|
2564
|
+
})
|
|
2565
|
+
}
|
|
2566
|
+
// 中文命中就直接给对应关系,不再去问宿主 —— 宿主的 filter 只认符号名子串,
|
|
2567
|
+
// 传中文进来它会当成「无过滤」,把 823 个符号全吐出来(实测第一批就是这么来的)。
|
|
2568
|
+
if (concepts.length > 0) {
|
|
2569
|
+
return ok({
|
|
2570
|
+
library: args.library ?? DEFAULTS.symbolLibrary,
|
|
2571
|
+
filter: keyword,
|
|
2572
|
+
matchedCount: concepts.reduce((sum, entry) => sum + entry.symbols.length, 0),
|
|
2573
|
+
concepts: concepts.map((entry) => ({ concept: entry.match[0], symbols: entry.symbols, note: entry.note })),
|
|
2574
|
+
hint:
|
|
2575
|
+
'concepts 是本机确认过的中文对应关系,直接用。要引脚用 pins,要形状用 visual;' +
|
|
2576
|
+
'没列到的概念就 visual 画出来看,别翻全表。',
|
|
2577
|
+
})
|
|
2578
|
+
}
|
|
2579
|
+
// 宿主的 SymbolsTool 只认 limit、不认 offset(每次都从第一个开始吐),
|
|
2580
|
+
// 所以这里按 offset+want 去取再本地切片;取不满就明说取不满,
|
|
2581
|
+
// 而不是像以前那样「换个 offset 还是同一批 200 个」。
|
|
2582
|
+
const fetchLimit = Math.min(200, Math.max(want, offset + want))
|
|
2583
|
+
let result
|
|
2584
|
+
try {
|
|
2585
|
+
result = await callBridge('symbols', {
|
|
2586
|
+
project: args.project,
|
|
2587
|
+
library: args.library,
|
|
2588
|
+
filter: keyword,
|
|
2589
|
+
limit: fetchLimit,
|
|
2590
|
+
})
|
|
2591
|
+
} catch (error) {
|
|
2592
|
+
return failed('symbols', error)
|
|
2593
|
+
}
|
|
2594
|
+
|
|
2595
|
+
const all = Array.isArray(result.symbols) ? result.symbols : []
|
|
2596
|
+
const matched = Number.isFinite(result.matchedCount) ? result.matchedCount : all.length
|
|
2597
|
+
const slice = all.slice(offset, offset + want)
|
|
2598
|
+
const reachable = offset + slice.length
|
|
2599
|
+
const nextOffset = reachable < matched ? reachable : null
|
|
2600
|
+
const blocked = nextOffset !== null && slice.length === 0
|
|
2601
|
+
|
|
2602
|
+
const key = `search|${args.project ?? ''}|${args.library ?? ''}|${keyword ?? ''}|${want}|${offset}`
|
|
2603
|
+
const { repeat, digest: stamp } = symbolMemo.check(key, slice)
|
|
2604
|
+
|
|
2605
|
+
const payload = {
|
|
2606
|
+
library: result.library ?? args.library ?? null,
|
|
2607
|
+
totalSymbols: result.totalSymbols ?? null,
|
|
2608
|
+
...(keyword ? { filter: keyword } : {}),
|
|
2609
|
+
matchedCount: matched,
|
|
2610
|
+
offset,
|
|
2611
|
+
limit: want,
|
|
2612
|
+
returned: slice.length,
|
|
2613
|
+
nextOffset,
|
|
2614
|
+
symbols: slice,
|
|
2615
|
+
digest: stamp,
|
|
2616
|
+
}
|
|
2617
|
+
if (blocked) {
|
|
2618
|
+
payload.paginationBlocked = true
|
|
2619
|
+
payload.hint =
|
|
2620
|
+
`宿主一次最多只吐 200 条,第 ${offset} 条之后取不到。要么用 filter 收窄(例如 filter="F1"),` +
|
|
2621
|
+
'要么直接 symbol_catalog action="pins" 查已知符号名。'
|
|
2622
|
+
} else if (repeat && args.refresh !== true) {
|
|
2623
|
+
payload.unchanged = true
|
|
2624
|
+
payload.hint = '这一页/这一批和上次完全一样,没有再发一遍内容。要强制重发传 refresh=true。'
|
|
2625
|
+
payload.symbols = []
|
|
2626
|
+
}
|
|
2627
|
+
return ok(payload)
|
|
2628
|
+
}
|
|
2629
|
+
case 'pins': {
|
|
2630
|
+
// 两个名字都收:老调用用 symbol(单个),批量用 symbols(数组)。
|
|
2631
|
+
// 原先只认 symbols,模型写 symbol 会连撞两次 BAD_ARGUMENT(2026-11-16 s1096 实测)。
|
|
2632
|
+
const list = args.symbols?.length ? args.symbols : args.symbol ? [args.symbol] : null
|
|
2633
|
+
if (!list) need(args, ['symbols'], 'pins')
|
|
2634
|
+
const pinned = await invoke('symbol_info', { project: args.project, library: args.library, symbols: list })
|
|
2635
|
+
// 查过就进热表:下次开工这几条直接常驻,不用再查(PTC 新进程没有上一步的记忆)。
|
|
2636
|
+
if (!pinned?.isError) recordSymbolUse(list, args.library)
|
|
2637
|
+
// 有图鉴的直接给样子:逐张(最多 4 张),配着引脚看比只读名字准。
|
|
2638
|
+
return withImages(pinned, list, 4)
|
|
2639
|
+
}
|
|
2640
|
+
case 'visual':
|
|
2641
|
+
return symbolVisualSheet({
|
|
2642
|
+
project: args.project,
|
|
2643
|
+
symbols: args.symbols?.length ? args.symbols : args.symbol ? [args.symbol] : [],
|
|
2644
|
+
library: args.library,
|
|
2645
|
+
cols: args.cols,
|
|
2646
|
+
width: args.width,
|
|
2647
|
+
})
|
|
2648
|
+
case 'lookup':
|
|
2649
|
+
return invoke('knowledge_get', {
|
|
2650
|
+
project: args.project,
|
|
2651
|
+
library: args.library,
|
|
2652
|
+
symbol: args.symbol,
|
|
2653
|
+
query: args.query ?? keyword,
|
|
2654
|
+
})
|
|
2655
|
+
case 'annotate':
|
|
2656
|
+
need(args, ['symbol'], 'annotate')
|
|
2657
|
+
return invoke('knowledge_annotate', {
|
|
2658
|
+
symbol: args.symbol,
|
|
2659
|
+
library: args.library,
|
|
2660
|
+
concept: args.concept,
|
|
2661
|
+
usage: args.usage,
|
|
2662
|
+
})
|
|
2663
|
+
default:
|
|
2664
|
+
throw fail(
|
|
2665
|
+
'BAD_ARGUMENT',
|
|
2666
|
+
`symbol_catalog 不认识 action="${args.action}"。`,
|
|
2667
|
+
'只支持 search / pins / visual / lookup / annotate。',
|
|
2668
|
+
)
|
|
2669
|
+
}
|
|
2670
|
+
},
|
|
2671
|
+
)
|
|
2672
|
+
|
|
2673
|
+
regTool(
|
|
2674
|
+
'page_create',
|
|
2675
|
+
{
|
|
2676
|
+
title: '新建页面(按单元摆元件)',
|
|
2677
|
+
description:
|
|
2678
|
+
'新建一页并摆元件与文字。先建页骨架,再按单元提交:一个器件或一批同类(12 个中断点、三极开关)各一次。\n' +
|
|
2679
|
+
'用 layout 声明行列,at 写 "列/行" 引用;改尺寸只改 layout 一处。\n' +
|
|
2680
|
+
'reveal=true 会渲一张图一并返回,但不切换当前页。页名用结构标识,例如 "=EB3+ET1/1"。',
|
|
2681
|
+
inputSchema: z.object({
|
|
2682
|
+
project,
|
|
2683
|
+
// name 和 page 二选一:其余工具都用 page,只有这里历史上叫 name。
|
|
2684
|
+
// 与其让模型写错一次再重试,不如两个都收。
|
|
2685
|
+
name: z.string().optional().describe('完整页名,例如 "=EB3+ET1/1"'),
|
|
2686
|
+
page: z.string().optional().describe('页名别名,等价于 name'),
|
|
2687
|
+
type: z
|
|
2688
|
+
.enum(['Schematic', 'Overview', 'Panel', 'SingleLine', 'Fluid'])
|
|
2689
|
+
.optional()
|
|
2690
|
+
.describe('页类型,默认 Schematic'),
|
|
2691
|
+
append: z
|
|
2692
|
+
.boolean()
|
|
2693
|
+
.optional()
|
|
2694
|
+
.describe('页已存在时接着往上画,而不是报 PAGE_EXISTS。默认 false'),
|
|
2695
|
+
nodes: z
|
|
2696
|
+
.array(
|
|
2697
|
+
z.object({
|
|
2698
|
+
symbol: z.string().describe('符号名,如 F1 / TLRU / CDPST'),
|
|
2699
|
+
library: z.string().optional().describe('符号库,默认 GB_symbol'),
|
|
2700
|
+
variant: z.number().int().optional().describe('变体号,默认 0;换方向是换变体,不是转角度'),
|
|
2701
|
+
at: z
|
|
2702
|
+
.union([point, z.string()])
|
|
2703
|
+
.describe('原点 [x, y];配合 layout 可写 "列/行",如 "0/bus"'),
|
|
2704
|
+
deviceTag: z.string().optional().describe('设备标识,如 -F4。会画成图上文字'),
|
|
2705
|
+
showDeviceTag: z.boolean().optional().describe('是否把设备标识画出来,默认 true'),
|
|
2706
|
+
}),
|
|
2707
|
+
)
|
|
2708
|
+
.optional()
|
|
2709
|
+
.describe('要摆的元件;按顺序插入,单个失败不影响其它,失败项见 nodesFailed'),
|
|
2710
|
+
texts: z
|
|
2711
|
+
.array(
|
|
2712
|
+
z.object({
|
|
2713
|
+
at: z
|
|
2714
|
+
.union([point, z.string()])
|
|
2715
|
+
.describe('文字包围盒左下角 [x, y];配合 layout 可写 "列/行"'),
|
|
2716
|
+
text: z.string().describe('文字内容'),
|
|
2717
|
+
height: z.number().optional().describe('字高 mm,默认 2.5'),
|
|
2718
|
+
}),
|
|
2719
|
+
)
|
|
2720
|
+
.optional()
|
|
2721
|
+
.describe('要写的文字标注'),
|
|
2722
|
+
grid: z
|
|
2723
|
+
.number()
|
|
2724
|
+
.optional()
|
|
2725
|
+
.describe('栅格间距 mm,默认 4;吸附结果在 snapped 里报回'),
|
|
2726
|
+
layout: z
|
|
2727
|
+
.object({
|
|
2728
|
+
columns: z.array(z.number()).describe('列的 x 坐标,按下标引用'),
|
|
2729
|
+
rows: z
|
|
2730
|
+
.union([z.array(z.number()), z.record(z.string(), z.number())])
|
|
2731
|
+
.describe('行的 y 坐标:数组按下标,对象按名字'),
|
|
2732
|
+
})
|
|
2733
|
+
.optional()
|
|
2734
|
+
.describe('声明式布局:给了之后 at 可写 "列/行" 代替绝对坐标,如 "0/bus";改尺寸只改 layout'),
|
|
2735
|
+
reveal,
|
|
2736
|
+
width,
|
|
2737
|
+
template: z.string().optional().describe('页面模板(宏文件)绝对路径'),
|
|
2738
|
+
dryRun: z.boolean().optional().describe('只校验并报告将创建什么,不写'),
|
|
2739
|
+
force: z
|
|
2740
|
+
.boolean()
|
|
2741
|
+
.optional()
|
|
2742
|
+
.describe('同定义重复提交默认不重建;要重建传 true'),
|
|
2743
|
+
theme: z.enum(['dark', 'light']).optional().describe('reveal 出图的配色,默认 dark'),
|
|
2744
|
+
}),
|
|
2745
|
+
},
|
|
2746
|
+
async (args) => {
|
|
2747
|
+
const name = args.name ?? args.page
|
|
2748
|
+
if (!name) throw fail('BAD_ARGUMENT', 'page_create 需要页名。', '用 name 或 page 传,例如 "=EB3+ET1/1"。')
|
|
2749
|
+
|
|
2750
|
+
const flightKey = `${args.project ?? ''}|${name}`
|
|
2751
|
+
const running = createInflight.get(flightKey)
|
|
2752
|
+
if (running !== undefined) {
|
|
2753
|
+
return ok({
|
|
2754
|
+
page: name,
|
|
2755
|
+
project: args.project ?? null,
|
|
2756
|
+
busy: true,
|
|
2757
|
+
code: 'PAGE_IN_PROGRESS',
|
|
2758
|
+
startedAt: running.startedAt,
|
|
2759
|
+
hint: '同一页已经有一次 page_create 在跑。等它返回;不要重复提交,也不要换个页名重来。',
|
|
2760
|
+
})
|
|
2761
|
+
}
|
|
2762
|
+
|
|
2763
|
+
// 幂等:完全相同的定义在短时间内重复提交,直接说「已经是这一版」,不再重建。
|
|
2764
|
+
const signature = digest({
|
|
2765
|
+
project: args.project ?? null,
|
|
2766
|
+
name,
|
|
2767
|
+
type: args.type ?? null,
|
|
2768
|
+
grid: args.grid ?? null,
|
|
2769
|
+
layout: args.layout ?? null,
|
|
2770
|
+
nodes: args.nodes ?? [],
|
|
2771
|
+
texts: args.texts ?? [],
|
|
2772
|
+
})
|
|
2773
|
+
const previous = createMemo.get(flightKey)
|
|
2774
|
+
if (args.force !== true && previous !== undefined && previous.signature === signature) {
|
|
2775
|
+
const ageSeconds = Math.round((Date.now() - previous.at) / 1000)
|
|
2776
|
+
if (ageSeconds < CREATE_IDEMPOTENT_MS / 1000) {
|
|
2777
|
+
return ok({
|
|
2778
|
+
page: name,
|
|
2779
|
+
project: args.project ?? null,
|
|
2780
|
+
unchanged: true,
|
|
2781
|
+
digest: signature,
|
|
2782
|
+
ageSeconds,
|
|
2783
|
+
hint: `这一页 ${ageSeconds} 秒前刚用完全相同的定义建过,没有重建。要强制重建传 force=true。`,
|
|
2784
|
+
})
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
|
|
2788
|
+
createInflight.set(flightKey, { startedAt: new Date().toISOString() })
|
|
2789
|
+
try {
|
|
2790
|
+
const result = await invokeWrite('page_create', { ...args, name })
|
|
2791
|
+
if (result.isError !== true) {
|
|
2792
|
+
createMemo.set(flightKey, { signature, at: Date.now() })
|
|
2793
|
+
// 自动占位:两个会话同时画同一页时,后来者会被 claim 挡住。
|
|
2794
|
+
let claim = null
|
|
2795
|
+
try {
|
|
2796
|
+
claim = claimPage({ project: args.project, page: name, owner: ownerTag() })
|
|
2797
|
+
} catch (error) {
|
|
2798
|
+
claim = { claimed: false, code: error.code ?? 'UNKNOWN', message: error.message }
|
|
2799
|
+
}
|
|
2800
|
+
if (claim?.claimed === false) {
|
|
2801
|
+
// 页面已经建好,但占位失败:必须让模型知道,否则另一个会话会覆盖。
|
|
2802
|
+
try {
|
|
2803
|
+
const text = result.content?.find?.((block) => block.type === 'text')?.text
|
|
2804
|
+
const parsed = text ? JSON.parse(text) : null
|
|
2805
|
+
if (parsed && typeof parsed === 'object') {
|
|
2806
|
+
parsed.claim = claim
|
|
2807
|
+
parsed.hint = `这一页已建好,但占位失败:${claim.message}。交付前先确认没有另一个会话在改同一页。`
|
|
2808
|
+
return ok(parsed)
|
|
2809
|
+
}
|
|
2810
|
+
} catch {
|
|
2811
|
+
// 解析不了就原样返回,不要把成功结果弄坏。
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
return result
|
|
2816
|
+
} finally {
|
|
2817
|
+
createInflight.delete(flightKey)
|
|
2818
|
+
}
|
|
2819
|
+
},
|
|
2820
|
+
)
|
|
2821
|
+
|
|
2822
|
+
// ---------------------------------------------------------------------------
|
|
2823
|
+
// 符号名写错时给候选。
|
|
2824
|
+
//
|
|
2825
|
+
// 2026-11-24 session-400917a2:模型认定「DCP」是电抗器,连撞 8 次 SYMBOL_NOT_FOUND,
|
|
2826
|
+
// 每次 260~370 ms,外加一整轮重新规划。错的不是重试次数,是错误信息只说「没有」,
|
|
2827
|
+
// 不说「库里有这些」。给候选 = 把一次失败变成一次可用的纠正。
|
|
2828
|
+
// ---------------------------------------------------------------------------
|
|
2829
|
+
const symbolNameCache = new Map()
|
|
2830
|
+
|
|
2831
|
+
/** 符号库全量名字(带缓存)。取不满就不缓存 —— 截断的名单会给出误导性的候选。 */
|
|
2832
|
+
async function symbolNameIndex(project, library) {
|
|
2833
|
+
const key = `${project ?? ''}|${library ?? ''}`
|
|
2834
|
+
const hit = symbolNameCache.get(key)
|
|
2835
|
+
if (hit) return hit
|
|
2836
|
+
try {
|
|
2837
|
+
const res = await callBridge('symbols', { project, library, limit: 2000 })
|
|
2838
|
+
const names = (Array.isArray(res?.symbols) ? res.symbols : []).map((item) => item?.name).filter(Boolean)
|
|
2839
|
+
const total = Number.isFinite(res?.totalSymbols) ? res.totalSymbols : null
|
|
2840
|
+
if (names.length > 0 && (total === null || names.length >= Math.min(total, 2000))) {
|
|
2841
|
+
symbolNameCache.set(key, names)
|
|
2842
|
+
}
|
|
2843
|
+
return names
|
|
2844
|
+
} catch {
|
|
2845
|
+
return []
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
|
|
2849
|
+
/** 把「库里没有 X」补成「库里没有 X,最接近的是 A / B」。 */
|
|
2850
|
+
async function symbolHint(result, symbol, library, project) {
|
|
2851
|
+
if (result?.isError !== true) return result
|
|
2852
|
+
try {
|
|
2853
|
+
const block = result.content?.find?.((item) => item.type === 'text')
|
|
2854
|
+
if (!block) return result
|
|
2855
|
+
const payload = JSON.parse(block.text)
|
|
2856
|
+
if (payload?.code !== 'SYMBOL_NOT_FOUND') return result
|
|
2857
|
+
const names = await symbolNameIndex(project, library)
|
|
2858
|
+
const candidates = closestSymbolNames(symbol, names)
|
|
2859
|
+
payload.candidates = candidates
|
|
2860
|
+
if (candidates.length > 0) {
|
|
2861
|
+
payload.message = `${payload.message} 库里有相近的名字:${candidates.join(' / ')}。改用其中之一,或先 pins 确认引脚。`
|
|
2862
|
+
payload.detail = '这些是编辑距离最近的几个,不是语义匹配 —— 形状对不对还要看 pins 或 visual。'
|
|
2863
|
+
payload.hint = '先 symbol_catalog{action:"pins",symbols:[候选]} 核引脚,再插;不要重复提交同一个不存在的名字。'
|
|
2864
|
+
} else if (names.length > 0) {
|
|
2865
|
+
payload.message = `${payload.message}(库里 ${names.length} 个符号里没有名字相近的。)`
|
|
2866
|
+
payload.detail =
|
|
2867
|
+
`「${symbol}」可能压根不叫这个名字,或属于别的符号库。`
|
|
2868
|
+
+ '下一步:symbol_catalog{action:"search", filter:"<英文缩写>"} 找名字,'
|
|
2869
|
+
+ '或 action:"visual" 把候选画出来用眼睛认(一次调用)。'
|
|
2870
|
+
payload.hint = '不要原样重试这一个名字。'
|
|
2871
|
+
}
|
|
2872
|
+
block.text = JSON.stringify(payload)
|
|
2873
|
+
} catch {
|
|
2874
|
+
// 结构对不上就原样返回,别用「弄坏错误信息」换候选。
|
|
2875
|
+
}
|
|
2876
|
+
return result
|
|
2877
|
+
}
|
|
2878
|
+
|
|
2879
|
+
regTool(
|
|
2880
|
+
'page_edit',
|
|
2881
|
+
{
|
|
2882
|
+
title: '修改页面',
|
|
2883
|
+
description:
|
|
2884
|
+
'改已有页。各 action 语义不同,别混用:\n' +
|
|
2885
|
+
'insert_symbol 补一两个元件(整页请用 page_create,快一个数量级);\n' +
|
|
2886
|
+
'set_properties 读写对象属性;\n' +
|
|
2887
|
+
'relocate 挪对象 / relabel 改标识 / delete_placement 删对象——都只动一个对象,不要重建整页;\n' +
|
|
2888
|
+
'draw_graphics 只画普通图形(标注框、说明文字、表格),**不参与连接**,别用它补线;\n' +
|
|
2889
|
+
'box 画黑箱(变频器/PLC 那种框):黄框 + 边缘连接点一次完成。\n' +
|
|
2890
|
+
'参数形状:选对象用 select{objectId|deviceTag|index}(objectId 来自 page_inspect view="list");\n' +
|
|
2891
|
+
'relocate 写 at:[x,y] 或 offset:[dx,dy];relabel 写 to:"-K2";draw_graphics 写 draw:[{kind,from,to}]。',
|
|
2892
|
+
inputSchema: z.object({
|
|
2893
|
+
action: z
|
|
2894
|
+
.enum(['insert_symbol', 'set_properties', 'relocate', 'relabel', 'delete_placement', 'draw_graphics', 'box'])
|
|
2895
|
+
.describe('插入 / 改属性 / 挪 / 改名 / 删 / 画图形 / 画黑箱'),
|
|
2896
|
+
project,
|
|
2897
|
+
page: z.string().optional().describe('目标页名(四个 action 都要)'),
|
|
2898
|
+
dryRun: z.boolean().optional().describe('只校验并返回将做什么,不写入'),
|
|
2899
|
+
force: z
|
|
2900
|
+
.boolean()
|
|
2901
|
+
.optional()
|
|
2902
|
+
.describe('这一页被另一个会话占着时仍要改:传 true 接手占位。默认 false,会被 CLAIMED 挡回'),
|
|
2903
|
+
// insert_symbol
|
|
2904
|
+
insert: z
|
|
2905
|
+
.object({
|
|
2906
|
+
symbol: z.string().describe('符号名,例如 FA3'),
|
|
2907
|
+
library: z.string().optional().describe(`符号库,默认 ${DEFAULTS.symbolLibrary}`),
|
|
2908
|
+
variant: z.number().int().min(0).optional().describe('变体号,默认 0;换方向是换变体,不是转角度'),
|
|
2909
|
+
at: point.describe('插入位置 [x, y],mm'),
|
|
2910
|
+
deviceTag: z.string().optional().describe('设备标识,例如 -K1'),
|
|
2911
|
+
props: z.record(z.string(), z.string()).optional().describe('额外属性,键为 EPLAN 属性名'),
|
|
2912
|
+
})
|
|
2913
|
+
.optional()
|
|
2914
|
+
.describe('insert_symbol 用'),
|
|
2915
|
+
// set_properties / relocate / relabel / delete_placement
|
|
2916
|
+
select: z
|
|
2917
|
+
.object({
|
|
2918
|
+
objectId: z.string().optional().describe('按对象标识定位(page_inspect view="list" 返回)'),
|
|
2919
|
+
deviceTag: z.string().optional().describe('按设备标识定位'),
|
|
2920
|
+
index: z
|
|
2921
|
+
.number()
|
|
2922
|
+
.int()
|
|
2923
|
+
.min(0)
|
|
2924
|
+
.optional()
|
|
2925
|
+
.describe('按 AllPlacements 下标(无名字的文字/图形)'),
|
|
2926
|
+
})
|
|
2927
|
+
.optional()
|
|
2928
|
+
.describe('定位条件,至少给一项(也可落在 page / project 上)'),
|
|
2929
|
+
at: point.optional().describe('relocate 的目标坐标 [x, y],绝对'),
|
|
2930
|
+
offset: point.optional().describe('relocate 的相对位移 [dx, dy],与 at 二选一'),
|
|
2931
|
+
// `to` 在 relabel 里是字符串(新标识),在 box 里是坐标。
|
|
2932
|
+
// 2026-11-24 实测:同一个键两种类型,模型写对了一种就必然错另一种,
|
|
2933
|
+
// 一次 schema 校验失败白丢一个回合。所以这里收 union,按 action 分派。
|
|
2934
|
+
to: z
|
|
2935
|
+
.union([z.string(), point])
|
|
2936
|
+
.optional()
|
|
2937
|
+
.describe('relabel 的新设备标识(字符串,例如 "-K2");box 的右下角坐标也可以直接写在这里([x,y])'),
|
|
2938
|
+
get: z.array(z.string()).optional().describe('set_properties 要读的属性名'),
|
|
2939
|
+
set: z.record(z.string(), z.string()).optional().describe('set_properties 要写的属性名与值'),
|
|
2940
|
+
// draw_graphics
|
|
2941
|
+
draw: z
|
|
2942
|
+
.array(
|
|
2943
|
+
z.object({
|
|
2944
|
+
kind: z.enum(['line', 'rect', 'text', 'polyline']).describe('图元类型'),
|
|
2945
|
+
from: point.optional().describe('line / rect 起点'),
|
|
2946
|
+
to: point.optional().describe('line / rect 终点'),
|
|
2947
|
+
at: point.optional().describe('text 的包围盒左下角'),
|
|
2948
|
+
points: z.array(point).min(2).optional().describe('polyline 的顶点'),
|
|
2949
|
+
text: z.string().optional().describe('text 的内容,支持换行'),
|
|
2950
|
+
height: z.number().optional().describe('text 字高 mm,默认 2.5'),
|
|
2951
|
+
width: z.number().optional().describe('线宽 mm,默认 0.2'),
|
|
2952
|
+
color: z
|
|
2953
|
+
.string()
|
|
2954
|
+
.optional()
|
|
2955
|
+
.describe('yellow / red / green / cyan / blue / magenta / black / gray,或 1-12'),
|
|
2956
|
+
}),
|
|
2957
|
+
)
|
|
2958
|
+
.optional()
|
|
2959
|
+
.describe('draw_graphics 的图元列表;画的是普通图形,不参与连接'),
|
|
2960
|
+
// box
|
|
2961
|
+
box: z
|
|
2962
|
+
.object({
|
|
2963
|
+
from: point.describe('左上角 [x, y],mm'),
|
|
2964
|
+
to: point.describe('右下角 [x, y],mm'),
|
|
2965
|
+
color: z.string().optional().describe('框线颜色,默认 yellow'),
|
|
2966
|
+
width: z.number().optional().describe('框线宽度 mm,默认 0.35'),
|
|
2967
|
+
deviceTag: z.string().optional().describe('黑箱的设备标识,例如 -U1;连接点代号按 -U1:SD 渲染'),
|
|
2968
|
+
pins: z
|
|
2969
|
+
.array(
|
|
2970
|
+
z.object({
|
|
2971
|
+
name: z.string().describe('连接点代号,例如 SD / RUN / PE'),
|
|
2972
|
+
side: z.enum(['top', 'bottom', 'left', 'right']).describe('挂在框的哪条边上'),
|
|
2973
|
+
at: z.number().optional().describe('沿边位置(上/下边是 x,左/右边是 y);省略则平均分布'),
|
|
2974
|
+
}),
|
|
2975
|
+
)
|
|
2976
|
+
.optional()
|
|
2977
|
+
.describe('边缘连接点;要渲染代号必须同时给 deviceTag'),
|
|
2978
|
+
})
|
|
2979
|
+
.optional()
|
|
2980
|
+
.describe('box 用;比 draw_graphics 手画矩形再补端子省一半步骤'),
|
|
2981
|
+
// 批量:一次调用提交多步同页操作。
|
|
2982
|
+
// 2026-11-24 实测:一页画下来 51 次 page_edit、平均 705 ms,每次还要一个模型回合
|
|
2983
|
+
// (≈13 秒生成)。同类操作(三个黑箱、十二个中断点)合成一次提交,省的是回合不是毫秒。
|
|
2984
|
+
ops: z
|
|
2985
|
+
.array(z.object({
|
|
2986
|
+
action: z
|
|
2987
|
+
.enum(['insert_symbol', 'set_properties', 'relocate', 'relabel', 'delete_placement', 'draw_graphics', 'box'])
|
|
2988
|
+
.describe('这一步做什么,和单次调用的 action 一样'),
|
|
2989
|
+
}).passthrough())
|
|
2990
|
+
.optional()
|
|
2991
|
+
.describe(
|
|
2992
|
+
'批量模式:一次提交多步,按数组顺序执行,字段规则与单次调用完全相同(page/project 在顶层写一次即可)。'
|
|
2993
|
+
+ '中途某步失败就停下并回报全部失败原因 —— 后面几步通常依赖前面插进去的对象。'
|
|
2994
|
+
+ '典型用法:三个 box + 十二个 insert_symbol 一次提交。',
|
|
2995
|
+
),
|
|
2996
|
+
}).passthrough(),
|
|
2997
|
+
},
|
|
2998
|
+
pageEditEntry,
|
|
2999
|
+
)
|
|
3000
|
+
|
|
3001
|
+
/**
|
|
3002
|
+
* page_edit 的入口:批量或单步。
|
|
3003
|
+
*
|
|
3004
|
+
* 原来这里是一个内联箭头函数,插不进批量分派;拆成具名函数之后单步路径一个字没改,
|
|
3005
|
+
* 批量只是把同一套 action 逻辑按顺序喂进去。
|
|
3006
|
+
*/
|
|
3007
|
+
async function pageEditEntry(rawArgs) {
|
|
3008
|
+
if (Array.isArray(rawArgs?.ops) && rawArgs.ops.length > 0) {
|
|
3009
|
+
return runPageEditBatch(rawArgs)
|
|
3010
|
+
}
|
|
3011
|
+
return runPageEditOnce(rawArgs)
|
|
3012
|
+
}
|
|
3013
|
+
|
|
3014
|
+
/** 批量:按顺序跑,某步失败就停 —— 后面几步通常依赖前面插进去的对象。 */
|
|
3015
|
+
async function runPageEditBatch(rawArgs) {
|
|
3016
|
+
const { ops, ...shared } = rawArgs
|
|
3017
|
+
const results = []
|
|
3018
|
+
for (let index = 0; index < ops.length; index += 1) {
|
|
3019
|
+
const step = { ...shared, ...(ops[index] ?? {}) }
|
|
3020
|
+
delete step.ops
|
|
3021
|
+
let outcome
|
|
3022
|
+
try {
|
|
3023
|
+
outcome = await runPageEditOnce(step)
|
|
3024
|
+
} catch (error) {
|
|
3025
|
+
results.push({
|
|
3026
|
+
index,
|
|
3027
|
+
action: step.action ?? null,
|
|
3028
|
+
ok: false,
|
|
3029
|
+
code: error?.code ?? 'UNKNOWN',
|
|
3030
|
+
error: error?.message ?? String(error),
|
|
3031
|
+
})
|
|
3032
|
+
break
|
|
3033
|
+
}
|
|
3034
|
+
const text = outcome?.content?.find?.((block) => block.type === 'text')?.text
|
|
3035
|
+
let payload = null
|
|
3036
|
+
try {
|
|
3037
|
+
payload = JSON.parse(text)
|
|
3038
|
+
} catch {
|
|
3039
|
+
payload = text ? String(text).slice(0, 200) : null
|
|
3040
|
+
}
|
|
3041
|
+
const failedStep = outcome?.isError === true || payload?.ok === false
|
|
3042
|
+
results.push({
|
|
3043
|
+
index,
|
|
3044
|
+
action: step.action ?? null,
|
|
3045
|
+
ok: !failedStep,
|
|
3046
|
+
...(failedStep ? { code: payload?.code ?? null, error: payload?.message ?? null, detail: payload?.detail ?? null } : {}),
|
|
3047
|
+
...(failedStep ? {} : { summary: summarizeEdit(payload) }),
|
|
3048
|
+
})
|
|
3049
|
+
if (failedStep) break
|
|
3050
|
+
}
|
|
3051
|
+
const done = results.filter((item) => item.ok).length
|
|
3052
|
+
const stopped = results.length < ops.length
|
|
3053
|
+
return ok({
|
|
3054
|
+
ok: results.every((item) => item.ok),
|
|
3055
|
+
mode: 'batch',
|
|
3056
|
+
total: ops.length,
|
|
3057
|
+
done,
|
|
3058
|
+
stoppedEarly: stopped,
|
|
3059
|
+
results,
|
|
3060
|
+
...(stopped
|
|
3061
|
+
? { hint: '停在第一个失败处,后面的步骤没有执行。改掉那一步再提交剩下的(已完成的不要重做)。' }
|
|
3062
|
+
: {}),
|
|
3063
|
+
})
|
|
3064
|
+
}
|
|
3065
|
+
|
|
3066
|
+
/** 批量结果里每步只留一句能核对的摘要,别把 8 份完整返回全塞回上下文。 */
|
|
3067
|
+
function summarizeEdit(payload) {
|
|
3068
|
+
if (!payload || typeof payload !== 'object') return null
|
|
3069
|
+
const keep = ['ok', 'page', 'op', 'symbol', 'library', 'variant', 'deviceTag', 'at', 'from', 'to', 'inserted', 'connections', 'objects']
|
|
3070
|
+
const out = {}
|
|
3071
|
+
for (const key of keep) {
|
|
3072
|
+
if (payload[key] !== undefined) out[key] = payload[key]
|
|
3073
|
+
}
|
|
3074
|
+
return Object.keys(out).length > 0 ? out : null
|
|
3075
|
+
}
|
|
3076
|
+
|
|
3077
|
+
async function runPageEditOnce(rawArgs) {
|
|
3078
|
+
// 先把同义写法收敛(draw/items/rects、type/kind、to/at…),再走后面的分支。
|
|
3079
|
+
const args = normalizeEditArgs(rawArgs)
|
|
3080
|
+
// 写操作前先过占用门:同一页正被另一个会话改时直接挡回去。
|
|
3081
|
+
// dryRun 只探路不写,不该被别人的占位挡住。
|
|
3082
|
+
let guard = null
|
|
3083
|
+
if (args.dryRun !== true && args.page) {
|
|
3084
|
+
guard = claimGuard(args.project, args.page, { force: args.force === true })
|
|
3085
|
+
}
|
|
3086
|
+
const guardNote = () => (guard?.tookOverFrom ? { claim: { tookOverFrom: guard.tookOverFrom } } : null)
|
|
3087
|
+
|
|
3088
|
+
switch (args.action) {
|
|
3089
|
+
case 'insert_symbol': {
|
|
3090
|
+
// 兼容老的平铺写法:symbol / library / variant / at 直接在顶层。
|
|
3091
|
+
const spec = args.insert ?? {}
|
|
3092
|
+
const symbolName = spec.symbol ?? (typeof args.symbol === 'string' ? args.symbol : undefined)
|
|
3093
|
+
const at = spec.at ?? args.at
|
|
3094
|
+
need({ page: args.page, symbol: symbolName, at }, ['page', 'symbol', 'at'], 'insert_symbol')
|
|
3095
|
+
const written = await invokeWrite('symbol_insert', {
|
|
3096
|
+
project: args.project,
|
|
3097
|
+
page: args.page,
|
|
3098
|
+
library: spec.library ?? args.library,
|
|
3099
|
+
symbol: symbolName,
|
|
3100
|
+
variant: spec.variant ?? args.variant,
|
|
3101
|
+
at,
|
|
3102
|
+
deviceTag: spec.deviceTag ?? args.deviceTag,
|
|
3103
|
+
props: spec.props ?? args.props,
|
|
3104
|
+
dryRun: args.dryRun,
|
|
3105
|
+
})
|
|
3106
|
+
return withNote(
|
|
3107
|
+
await symbolHint(written, symbolName, spec.library ?? args.library, args.project),
|
|
3108
|
+
guardNote(),
|
|
3109
|
+
)
|
|
3110
|
+
}
|
|
3111
|
+
case 'set_properties': {
|
|
3112
|
+
if (!args.get && !args.set) {
|
|
3113
|
+
throw fail('BAD_ARGUMENT', 'set_properties 既没给 get 也没给 set。', '给 get 读属性,或给 set 写属性。')
|
|
3114
|
+
}
|
|
3115
|
+
const selector = {
|
|
3116
|
+
page: args.page,
|
|
3117
|
+
deviceTag: args.select?.deviceTag ?? args.deviceTag,
|
|
3118
|
+
objectId: args.select?.objectId ?? args.objectId,
|
|
3119
|
+
project: args.project,
|
|
3120
|
+
}
|
|
3121
|
+
if (!selector.page && !selector.deviceTag && !selector.objectId && !selector.project) {
|
|
3122
|
+
throw fail(
|
|
3123
|
+
'BAD_ARGUMENT',
|
|
3124
|
+
'set_properties 没有定位条件。',
|
|
3125
|
+
'select 里给 objectId 或 deviceTag,或给 page / project。',
|
|
3126
|
+
)
|
|
3127
|
+
}
|
|
3128
|
+
return withNote(
|
|
3129
|
+
await invoke('props', { selector, get: args.get, set: args.set, dryRun: args.dryRun }),
|
|
3130
|
+
guardNote(),
|
|
3131
|
+
)
|
|
3132
|
+
}
|
|
3133
|
+
case 'relocate':
|
|
3134
|
+
case 'relabel':
|
|
3135
|
+
case 'delete_placement': {
|
|
3136
|
+
const selector = {
|
|
3137
|
+
page: args.page,
|
|
3138
|
+
project: args.project,
|
|
3139
|
+
objectId: args.select?.objectId ?? args.objectId,
|
|
3140
|
+
deviceTag: args.select?.deviceTag ?? args.deviceTag,
|
|
3141
|
+
index: args.select?.index ?? args.index,
|
|
3142
|
+
}
|
|
3143
|
+
const hasSelector = Boolean(selector.objectId || selector.deviceTag || selector.index !== undefined)
|
|
3144
|
+
if (!hasSelector) {
|
|
3145
|
+
throw fail(
|
|
3146
|
+
'BAD_ARGUMENT',
|
|
3147
|
+
`${args.action} 需要选择对象。`,
|
|
3148
|
+
'select 里给 objectId(page_inspect view="list" 有)/ deviceTag / index 之一。',
|
|
3149
|
+
)
|
|
3150
|
+
}
|
|
3151
|
+
if (args.action === 'relabel') {
|
|
3152
|
+
need({ to: args.to }, ['to'], 'relabel')
|
|
3153
|
+
if (typeof args.to !== 'string') {
|
|
3154
|
+
throw fail(
|
|
3155
|
+
'BAD_ARGUMENT',
|
|
3156
|
+
`relabel 的 to 要的是字符串设备标识,收到的是 ${JSON.stringify(args.to)}。`,
|
|
3157
|
+
'写成 to:"-K2"。坐标用 at:[x,y](relocate);box 的右下角才写 [x,y]。',
|
|
3158
|
+
)
|
|
3159
|
+
}
|
|
3160
|
+
return withNote(
|
|
3161
|
+
hostOutdated(
|
|
3162
|
+
await invoke('placement_relabel', { selector, to: args.to, dryRun: args.dryRun }),
|
|
3163
|
+
'placement_relabel',
|
|
3164
|
+
'用 set_properties 改不了设备标识;先重建这个元件(page_edit action="insert_symbol" 到同一位置会多出一个),或等 EPLAN 重启。',
|
|
3165
|
+
),
|
|
3166
|
+
guardNote(),
|
|
3167
|
+
)
|
|
3168
|
+
}
|
|
3169
|
+
if (args.action === 'delete_placement') {
|
|
3170
|
+
return withNote(
|
|
3171
|
+
hostOutdated(
|
|
3172
|
+
await invoke('placement_delete', { selector, dryRun: args.dryRun }),
|
|
3173
|
+
'placement_delete',
|
|
3174
|
+
'删一个对象现在只能整页重建,或等 EPLAN 重启后再删。',
|
|
3175
|
+
),
|
|
3176
|
+
guardNote(),
|
|
3177
|
+
)
|
|
3178
|
+
}
|
|
3179
|
+
const at = args.at ?? args.relocate?.at
|
|
3180
|
+
const offset = args.offset ?? args.relocate?.offset
|
|
3181
|
+
if (!at && !offset) {
|
|
3182
|
+
throw fail(
|
|
3183
|
+
'BAD_ARGUMENT',
|
|
3184
|
+
'relocate 需要 at [x, y] 或 offset [dx, dy]。',
|
|
3185
|
+
'绝对坐标用 at,只平移用 offset。照这个写:{action:"relocate", page:"=EB3+ET1/1", select:{objectId:"2545"}, at:[110,275]}。' +
|
|
3186
|
+
'objectId 从 page_inspect{format:"structure",view:"list"} 的 rows[].id 拿。',
|
|
3187
|
+
)
|
|
3188
|
+
}
|
|
3189
|
+
return withNote(
|
|
3190
|
+
hostOutdated(
|
|
3191
|
+
await invoke('placement_move', { selector, at, offset, dryRun: args.dryRun }),
|
|
3192
|
+
'placement_move',
|
|
3193
|
+
'现在只能删页重建或重新插入这个元件。',
|
|
3194
|
+
),
|
|
3195
|
+
guardNote(),
|
|
3196
|
+
)
|
|
3197
|
+
}
|
|
3198
|
+
case 'draw_graphics': {
|
|
3199
|
+
const items = args.draw ?? args.items
|
|
3200
|
+
need(
|
|
3201
|
+
{ page: args.page, draw: items },
|
|
3202
|
+
['page', 'draw'],
|
|
3203
|
+
'draw_graphics',
|
|
3204
|
+
'{action:"draw_graphics", page:"=EB3+ET1/1", draw:[{kind:"rect", from:[152,110], to:[196,204]}]};'
|
|
3205
|
+
+ 'kind 只能是 line / rect / text / polyline(写 type 也认)。',
|
|
3206
|
+
)
|
|
3207
|
+
return withNote(
|
|
3208
|
+
await invokeWrite('draw', {
|
|
3209
|
+
project: args.project,
|
|
3210
|
+
page: args.page,
|
|
3211
|
+
items,
|
|
3212
|
+
dryRun: args.dryRun,
|
|
3213
|
+
}),
|
|
3214
|
+
guardNote(),
|
|
3215
|
+
)
|
|
3216
|
+
}
|
|
3217
|
+
case 'box': {
|
|
3218
|
+
// 兼容老的平铺写法:from / to / deviceTag / pins 直接在顶层。
|
|
3219
|
+
const spec = args.box ?? args
|
|
3220
|
+
need({ page: args.page, from: spec.from, to: spec.to }, ['page', 'from', 'to'], 'box')
|
|
3221
|
+
return withNote(
|
|
3222
|
+
await invokeWrite('box', {
|
|
3223
|
+
project: args.project,
|
|
3224
|
+
page: args.page,
|
|
3225
|
+
from: spec.from,
|
|
3226
|
+
to: spec.to,
|
|
3227
|
+
color: spec.color,
|
|
3228
|
+
width: spec.width,
|
|
3229
|
+
deviceTag: spec.deviceTag,
|
|
3230
|
+
pins: spec.pins,
|
|
3231
|
+
dryRun: args.dryRun,
|
|
3232
|
+
}),
|
|
3233
|
+
guardNote(),
|
|
3234
|
+
)
|
|
3235
|
+
}
|
|
3236
|
+
default:
|
|
3237
|
+
throw fail(
|
|
3238
|
+
'BAD_ARGUMENT',
|
|
3239
|
+
`page_edit 不认识 action="${args.action}"。`,
|
|
3240
|
+
'可选:insert_symbol / set_properties / relocate / relabel / delete_placement / draw_graphics / box。' +
|
|
3241
|
+
'改一个已存在的对象(挪位置 / 改标识 / 删)用 relocate / relabel / delete_placement,别删整页重建。',
|
|
3242
|
+
)
|
|
3243
|
+
}
|
|
3244
|
+
}
|
|
3245
|
+
|
|
3246
|
+
regTool(
|
|
3247
|
+
'page_delete',
|
|
3248
|
+
{
|
|
3249
|
+
title: '删除页面',
|
|
3250
|
+
description:
|
|
3251
|
+
'删除一整页。用于清理试画留下的过程页。只删页,不改页里的单个对象;页不存在会报错,不会静默成功。',
|
|
3252
|
+
inputSchema: z.object({
|
|
3253
|
+
page: z.string().describe('页名,例如 =MCP/7'),
|
|
3254
|
+
project,
|
|
3255
|
+
dryRun: z.boolean().optional().describe('只报告会删掉什么(页里有多少元件),不真的删。默认 false'),
|
|
3256
|
+
force: z
|
|
3257
|
+
.boolean()
|
|
3258
|
+
.optional()
|
|
3259
|
+
.describe('这一页被另一个会话占着时仍要删:传 true 接手占位。默认 false,会被 CLAIMED 挡回'),
|
|
3260
|
+
}),
|
|
3261
|
+
},
|
|
3262
|
+
async (args) => {
|
|
3263
|
+
if (args.dryRun !== true && args.page) claimGuard(args.project, args.page, { force: args.force === true })
|
|
3264
|
+
const result = await invoke('page_delete', args)
|
|
3265
|
+
// 页没了,占位也没有意义:顺手释放,别让一个已删除的页名占着锁。
|
|
3266
|
+
if (result.isError !== true && args.dryRun !== true && args.page) {
|
|
3267
|
+
try {
|
|
3268
|
+
releasePage({ project: args.project, page: args.page })
|
|
3269
|
+
} catch {
|
|
3270
|
+
// 没有台账文件也无所谓,删除已经成功了。
|
|
3271
|
+
}
|
|
3272
|
+
}
|
|
3273
|
+
return result
|
|
3274
|
+
},
|
|
3275
|
+
)
|
|
3276
|
+
|
|
3277
|
+
// 同参数重复读的记忆:一页没改过时,第二次只回一句 unchanged,
|
|
3278
|
+
// 不再把整份结构重发一遍(实测 341 KB 里的大部分都是这种重复)。
|
|
3279
|
+
const inspectMemo = new RepeatMemo(64)
|
|
3280
|
+
const symbolMemo = new RepeatMemo(64)
|
|
3281
|
+
|
|
3282
|
+
regTool(
|
|
3283
|
+
'page_inspect',
|
|
3284
|
+
{
|
|
3285
|
+
title: '看页面',
|
|
3286
|
+
description:
|
|
3287
|
+
'看一页。format=image 出渲染图(与窗口是否可见无关),文字部分只回页名/图路径/计数;format=both 结构+图一起给。\n' +
|
|
3288
|
+
'structure 配 view 三档:summary(默认,计数/坐标范围/设备标识/几何问题,约 1~3 KB)、\n' +
|
|
3289
|
+
'list(一行一对象带坐标)、full(含引脚相对坐标,最全)。\n' +
|
|
3290
|
+
'返回形状永远是同一套字段(rows / count / problems);内容没变时只多一个 repeat:true 的提示,不会换成别的形状。problems 每条都带 fix。',
|
|
3291
|
+
inputSchema: z.object({
|
|
3292
|
+
format: z.enum(['structure', 'image', 'both']).describe('要结构、要图,还是都要'),
|
|
3293
|
+
project,
|
|
3294
|
+
page: z.string().describe('页名,例如 "=EB3+ET1/1"'),
|
|
3295
|
+
view: z
|
|
3296
|
+
.enum(['summary', 'list', 'full'])
|
|
3297
|
+
.optional()
|
|
3298
|
+
.describe('structure 的详细程度,默认 summary。要知道坐标用 list,要引脚相对坐标用 full'),
|
|
3299
|
+
only: z
|
|
3300
|
+
.array(z.enum(['Function', 'InterruptionPoint', 'Text', 'Rectangle']))
|
|
3301
|
+
.optional()
|
|
3302
|
+
.describe('只返回这些类型的对象,例如 ["Function"];list/full 生效'),
|
|
3303
|
+
limit: z.number().int().min(1).max(500).optional().describe('list/full 最多返回多少个对象,默认 200'),
|
|
3304
|
+
refresh: z
|
|
3305
|
+
.boolean()
|
|
3306
|
+
.optional()
|
|
3307
|
+
.describe('保留参数:内容没变时也总是回全量,这个开关现在只影响 digest 是否重算'),
|
|
3308
|
+
members: z
|
|
3309
|
+
.string()
|
|
3310
|
+
.optional()
|
|
3311
|
+
.describe('想查某个 EPLAN 类型的成员时填类名,例如 SymbolReference、Connection'),
|
|
3312
|
+
render: z
|
|
3313
|
+
.object({
|
|
3314
|
+
width: z.number().int().min(400).max(8000).optional().describe('图片像素宽度,默认 2000;看细节调到 3000~4000'),
|
|
3315
|
+
theme: z.enum(['dark', 'light']).optional().describe('配色,默认 dark;要白底交付图传 light'),
|
|
3316
|
+
image: z.boolean().optional().describe('是否真的返回图片,默认 true'),
|
|
3317
|
+
})
|
|
3318
|
+
.optional()
|
|
3319
|
+
.describe('出图选项(format=image / both 时有效)'),
|
|
3320
|
+
detail: z
|
|
3321
|
+
.boolean()
|
|
3322
|
+
.optional()
|
|
3323
|
+
.describe('format=image 时默认只给页名/图路径/计数;要连整份 functions 列表一起给就传 true'),
|
|
3324
|
+
}).passthrough(),
|
|
3325
|
+
},
|
|
3326
|
+
async (args) => {
|
|
3327
|
+
const view = args.view ?? 'summary'
|
|
3328
|
+
const renderOpts = args.render ?? {}
|
|
3329
|
+
const inspectArgs = { project: args.project, page: args.page, limit: args.limit, members: args.members }
|
|
3330
|
+
|
|
3331
|
+
const structureResult = async () => {
|
|
3332
|
+
const raw = await callBridge('inspect', inspectArgs)
|
|
3333
|
+
const compacted = compactInspect(raw, { view, only: args.only, limit: args.limit })
|
|
3334
|
+
const key = `${args.project ?? ''}|${args.page}|${view}|${args.limit ?? ''}|${(args.only ?? []).join(',')}`
|
|
3335
|
+
const { repeat, digest: stamp } = inspectMemo.check(key, raw)
|
|
3336
|
+
// 重复调用照常回全量:以前这里回一个 {unchanged:true} 的**不同形状**,
|
|
3337
|
+
// 调用方 `content[0].text` 里就没有 rows 了 —— 2026-11-27 session-6f4cd9cb
|
|
3338
|
+
// 第 26 步正是这么炸的(Cannot read properties of undefined)。
|
|
3339
|
+
// 现在只把「和上次一样」当一条提示加上去,形状永远一致。
|
|
3340
|
+
return {
|
|
3341
|
+
...compacted,
|
|
3342
|
+
digest: stamp,
|
|
3343
|
+
...(repeat ? { repeat: true, hint: '和上次查看相比内容没有变化;要节省上下文可以不再重复查这一页。' } : {}),
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
|
|
3347
|
+
if (args.format === 'structure') {
|
|
3348
|
+
try {
|
|
3349
|
+
return ok(await structureResult())
|
|
3350
|
+
} catch (error) {
|
|
3351
|
+
return failed('inspect', error)
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
3354
|
+
if (args.format === 'image') {
|
|
3355
|
+
return invokeLook({
|
|
3356
|
+
project: args.project,
|
|
3357
|
+
page: args.page,
|
|
3358
|
+
width: renderOpts.width ?? args.width,
|
|
3359
|
+
image: renderOpts.image ?? args.image,
|
|
3360
|
+
theme: renderOpts.theme ?? args.theme,
|
|
3361
|
+
detail: args.detail,
|
|
3362
|
+
view: args.view,
|
|
3363
|
+
})
|
|
3364
|
+
}
|
|
3365
|
+
if (args.format === 'both') {
|
|
3366
|
+
let structure
|
|
3367
|
+
try {
|
|
3368
|
+
structure = await structureResult()
|
|
3369
|
+
} catch (error) {
|
|
3370
|
+
return failed('inspect', error)
|
|
3371
|
+
}
|
|
3372
|
+
const shot = await invokeLook({
|
|
3373
|
+
project: args.project,
|
|
3374
|
+
page: args.page,
|
|
3375
|
+
width: renderOpts.width ?? args.width,
|
|
3376
|
+
image: renderOpts.image ?? args.image,
|
|
3377
|
+
theme: renderOpts.theme ?? args.theme,
|
|
3378
|
+
detail: args.detail,
|
|
3379
|
+
view: args.view,
|
|
3380
|
+
})
|
|
3381
|
+
return {
|
|
3382
|
+
content: [
|
|
3383
|
+
{ type: 'text', text: JSON.stringify(structure) },
|
|
3384
|
+
...shot.content.filter((block) => block.type !== 'text'),
|
|
3385
|
+
],
|
|
3386
|
+
}
|
|
3387
|
+
}
|
|
3388
|
+
throw fail('BAD_ARGUMENT', `page_inspect 不认识 format="${args.format}"。`, '只支持 structure / image / both。')
|
|
3389
|
+
},
|
|
3390
|
+
)
|
|
3391
|
+
|
|
3392
|
+
// 几何门禁的一条问题 → 一行能照着改的话。
|
|
3393
|
+
const formatGeometry = (problem) => `${problem.where}:${problem.detail}(${problem.fix})`
|
|
3394
|
+
|
|
3395
|
+
regTool(
|
|
3396
|
+
'validate',
|
|
3397
|
+
{
|
|
3398
|
+
title: '工程验收',
|
|
3399
|
+
description:
|
|
3400
|
+
'检查一页画得规不规范,并给出**能不能交付**的结论。EPLAN 不会因为画错而报错,所以交付前必须跑一次。\n' +
|
|
3401
|
+
'verdict 为 "pass" 才能交;"warn" 只有可读性问题(标签压字、设备标识重复);"fail" 有硬伤,必须改。\n' +
|
|
3402
|
+
'检查两部分:EPLAN 自己的(手绘假导线、设备标识重复、不在栅格、孤立引脚、共用连接点)' +
|
|
3403
|
+
'和几何的(符号本体重叠、文字压符号、超图框)。两条都过才算过。\n' +
|
|
3404
|
+
'appearance 是版面看相:按邻近关系分组,量组间空隙、同列间距、四边余量,' +
|
|
3405
|
+
'用户说「散 / 挤 / 丑 / 聚拢一点 / 线修长一点」时照它的 issues 改,不要整页重画(它不进 verdict)。',
|
|
3406
|
+
inputSchema: z.object({
|
|
3407
|
+
project,
|
|
3408
|
+
page: z.string().describe('要检查的页名'),
|
|
3409
|
+
grid: z.number().optional().describe('栅格间距 mm,默认 4'),
|
|
3410
|
+
pageSize: z
|
|
3411
|
+
.array(z.number())
|
|
3412
|
+
.optional()
|
|
3413
|
+
.describe('页面尺寸 [宽, 高] mm;省略时按页名自动查,查不到就跳过越界检查'),
|
|
3414
|
+
expectDevices: z
|
|
3415
|
+
.array(z.string())
|
|
3416
|
+
.optional()
|
|
3417
|
+
.describe(
|
|
3418
|
+
'意图清单里的器件标识,例如 ["-F11","-K21","-U4"]。给了就核对页上是否真的都在:' +
|
|
3419
|
+
'缺的进 errors,多出来的报在 intent.extraSample。器件清单不要靠看渲染图数。',
|
|
3420
|
+
),
|
|
3421
|
+
}),
|
|
3422
|
+
},
|
|
3423
|
+
async (args) => {
|
|
3424
|
+
const grid = Number.isFinite(args.grid) ? args.grid : 4
|
|
3425
|
+
|
|
3426
|
+
let host = null
|
|
3427
|
+
let hostError = null
|
|
3428
|
+
try {
|
|
3429
|
+
host = await callBridge('check', { project: args.project, page: args.page, grid })
|
|
3430
|
+
} catch (error) {
|
|
3431
|
+
hostError = { code: error.code ?? 'UNKNOWN', message: error.message }
|
|
3432
|
+
}
|
|
3433
|
+
|
|
3434
|
+
let raw = null
|
|
3435
|
+
try {
|
|
3436
|
+
raw = await callBridge('inspect', { project: args.project, page: args.page, limit: 500 })
|
|
3437
|
+
} catch {
|
|
3438
|
+
raw = null
|
|
3439
|
+
}
|
|
3440
|
+
|
|
3441
|
+
// 页面尺寸:先看缓存(brief / list_pages 会顺手填),没有再问一次。
|
|
3442
|
+
let pageSize = Array.isArray(args.pageSize) ? args.pageSize : null
|
|
3443
|
+
if (pageSize === null) {
|
|
3444
|
+
const key = `${args.project ?? ''}|${args.page}`
|
|
3445
|
+
pageSize = pageSizeCache.get(key) ?? null
|
|
3446
|
+
if (pageSize === null) {
|
|
3447
|
+
try {
|
|
3448
|
+
const listing = await callBridge('pages', { project: args.project, filter: args.page, limit: 5 })
|
|
3449
|
+
const list = Array.isArray(listing) ? listing : (listing?.pages ?? [])
|
|
3450
|
+
const hit = list.find((page) => page?.name === args.page && Array.isArray(page.size))
|
|
3451
|
+
if (hit) {
|
|
3452
|
+
pageSize = hit.size
|
|
3453
|
+
pageSizeCache.set(key, pageSize)
|
|
3454
|
+
}
|
|
3455
|
+
} catch {
|
|
3456
|
+
// 查不到就跳过越界检查,不影响其余项。
|
|
3457
|
+
}
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
|
|
3461
|
+
// 宿主已经查过的项,几何层不再重复报一遍:同一件事说三遍只会稀释注意力。
|
|
3462
|
+
const hostCovers = new Set()
|
|
3463
|
+
if ((host?.offGridSample ?? []).length > 0) hostCovers.add('off_grid')
|
|
3464
|
+
if ((host?.summary?.sharedPinPoints ?? 0) > 0) hostCovers.add('shared_pin_point')
|
|
3465
|
+
if ((host?.duplicateTags ?? []).length > 0) hostCovers.add('duplicate_symbol')
|
|
3466
|
+
|
|
3467
|
+
const geometry =
|
|
3468
|
+
raw === null
|
|
3469
|
+
? []
|
|
3470
|
+
: geometryProblems(raw, { grid, pageSize }).filter((problem) => !hostCovers.has(problem.kind))
|
|
3471
|
+
const geometryErrors = geometry.filter((problem) => problem.kind !== 'label_overlap')
|
|
3472
|
+
const geometryWarnings = geometry.filter((problem) => problem.kind === 'label_overlap')
|
|
3473
|
+
|
|
3474
|
+
const errors = [...(host?.problems ?? []), ...geometryErrors.map(formatGeometry)]
|
|
3475
|
+
const warnings = [...(host?.warnings ?? []), ...geometryWarnings.map(formatGeometry)]
|
|
3476
|
+
|
|
3477
|
+
// 看相:只给数字和建议,不进 errors/warnings —— 审美不是硬伤,
|
|
3478
|
+
// 但用户说「散 / 挤 / 丑」的时候,这里就是唯一能照做的依据。
|
|
3479
|
+
const appearance = raw === null ? null : appearanceReport(raw, { pageSize })
|
|
3480
|
+
|
|
3481
|
+
// 意图层:器件清单是不是齐的。这是机器能判的部分,不该让模型靠看渲染图数数。
|
|
3482
|
+
let intent = null
|
|
3483
|
+
if (Array.isArray(args.expectDevices) && args.expectDevices.length > 0) {
|
|
3484
|
+
const expected = [...new Set(args.expectDevices.map((tag) => String(tag).trim()).filter(Boolean))]
|
|
3485
|
+
// 器件名在 EPLAN 里带结构前缀(=+-F11),设备标识部分从第一个 "-" 开始。
|
|
3486
|
+
const tags = []
|
|
3487
|
+
for (const fn of raw?.functions ?? []) {
|
|
3488
|
+
const name = typeof fn?.name === 'string' ? fn.name : ''
|
|
3489
|
+
const cut = name.indexOf('-')
|
|
3490
|
+
if (cut >= 0) tags.push(name.slice(cut))
|
|
3491
|
+
}
|
|
3492
|
+
const unique = [...new Set(tags)]
|
|
3493
|
+
const matched = new Set()
|
|
3494
|
+
for (const tag of unique) {
|
|
3495
|
+
for (const want of expected) {
|
|
3496
|
+
if (tag === want || tag.startsWith(`${want}:`)) matched.add(want)
|
|
3497
|
+
}
|
|
3498
|
+
}
|
|
3499
|
+
const missing = expected.filter((want) => !matched.has(want))
|
|
3500
|
+
const extra = unique.filter((tag) => !expected.some((want) => tag === want || tag.startsWith(`${want}:`)))
|
|
3501
|
+
intent = {
|
|
3502
|
+
expected: expected.length,
|
|
3503
|
+
found: matched.size,
|
|
3504
|
+
missing,
|
|
3505
|
+
extraCount: extra.length,
|
|
3506
|
+
extraSample: extra.slice(0, 8),
|
|
3507
|
+
...(raw === null ? { skipped: '读不到页面结构,器件清单没核对' } : {}),
|
|
3508
|
+
}
|
|
3509
|
+
if (missing.length > 0) errors.push(`意图清单里的器件没找到:${missing.join('、')}`)
|
|
3510
|
+
}
|
|
3511
|
+
|
|
3512
|
+
const verdict = errors.length > 0 ? 'fail' : warnings.length > 0 ? 'warn' : 'pass'
|
|
3513
|
+
|
|
3514
|
+
const summary = host?.summary ?? {}
|
|
3515
|
+
return ok({
|
|
3516
|
+
page: args.page,
|
|
3517
|
+
project: args.project,
|
|
3518
|
+
verdict,
|
|
3519
|
+
...(intent === null ? {} : { intent }),
|
|
3520
|
+
counts: {
|
|
3521
|
+
...summary,
|
|
3522
|
+
offGrid: (host?.offGridSample ?? []).length,
|
|
3523
|
+
noTag: (host?.noTagSample ?? []).length,
|
|
3524
|
+
duplicateTagGroups: (host?.duplicateTags ?? []).length,
|
|
3525
|
+
geometryErrors: geometryErrors.length,
|
|
3526
|
+
geometryWarnings: geometryWarnings.length,
|
|
3527
|
+
},
|
|
3528
|
+
errors,
|
|
3529
|
+
warnings,
|
|
3530
|
+
info: host?.info ?? [],
|
|
3531
|
+
...(geometry.length > 0 ? { geometry: geometry.slice(0, 20) } : {}),
|
|
3532
|
+
...(appearance && appearance.items > 0
|
|
3533
|
+
? {
|
|
3534
|
+
appearance: {
|
|
3535
|
+
items: appearance.items,
|
|
3536
|
+
groups: appearance.groups,
|
|
3537
|
+
gaps: appearance.gaps ?? [],
|
|
3538
|
+
pitches: appearance.pitches ?? null,
|
|
3539
|
+
...(appearance.margins ? { margins: appearance.margins } : {}),
|
|
3540
|
+
...(appearance.issues?.length ? { issues: appearance.issues } : { issues: [] }),
|
|
3541
|
+
note:
|
|
3542
|
+
appearance.issues?.length
|
|
3543
|
+
? '这些是版面观感问题,不影响能不能交付;用户说「散 / 挤 / 丑」时按 issues 里的 fix 改,别整页重画。'
|
|
3544
|
+
: null,
|
|
3545
|
+
},
|
|
3546
|
+
}
|
|
3547
|
+
: {}),
|
|
3548
|
+
...(host?.offGridSample?.length ? { offGridSample: host.offGridSample.slice(0, 8) } : {}),
|
|
3549
|
+
...(host?.duplicateTags?.length ? { duplicateTags: host.duplicateTags } : {}),
|
|
3550
|
+
...(hostError ? { hostError } : {}),
|
|
3551
|
+
...(raw === null ? { geometrySkipped: '读不到页面结构,几何检查没跑' } : {}),
|
|
3552
|
+
hint:
|
|
3553
|
+
verdict === 'pass'
|
|
3554
|
+
? '可以交付。交付前再出一张图核对一眼。'
|
|
3555
|
+
: verdict === 'warn'
|
|
3556
|
+
? '能交付,但上面 warnings 里每条都值得看一眼:能改就改,改不了就在汇报里说明。'
|
|
3557
|
+
: '先修 errors,每条的括号里就是改法;修完重新 validate 一次。',
|
|
3558
|
+
})
|
|
3559
|
+
},
|
|
3560
|
+
)
|
|
3561
|
+
|
|
3562
|
+
regTool(
|
|
3563
|
+
'export',
|
|
3564
|
+
{
|
|
3565
|
+
title: '导出图纸',
|
|
3566
|
+
description:
|
|
3567
|
+
'把项目或指定页导出成 PNG / PDF / DXF。PNG 默认深色底;要交付给别人的白底图传 theme="light"。PDF/DXF 不受影响。\n' +
|
|
3568
|
+
'大项目或整本 PDF 可能超过 run_code 的 120 秒:传 wait:false 立刻回 jobId,再用 workspace({action:"wait"}) 取文件清单。',
|
|
3569
|
+
inputSchema: z.object({
|
|
3570
|
+
project,
|
|
3571
|
+
kind: z.enum(['png', 'pdf', 'dxf']).describe('导出格式'),
|
|
3572
|
+
pages: z.array(z.string()).optional().describe('页名列表;省略表示整个项目'),
|
|
3573
|
+
outDir: z.string().optional().describe('输出目录;省略则用项目目录下的 _eplan_export'),
|
|
3574
|
+
fileName: z.string().optional().describe('输出文件名(不含扩展名)'),
|
|
3575
|
+
theme: z
|
|
3576
|
+
.enum(['dark', 'light'])
|
|
3577
|
+
.optional()
|
|
3578
|
+
.describe('PNG 的配色,默认 dark;交付给别人的图纸一般要 light'),
|
|
3579
|
+
wait: z
|
|
3580
|
+
.boolean()
|
|
3581
|
+
.optional()
|
|
3582
|
+
.describe('是否等导出完成再返回,默认 true;false 立刻回 jobId,用 action="wait" 取'),
|
|
3583
|
+
waitMs: z
|
|
3584
|
+
.number()
|
|
3585
|
+
.int()
|
|
3586
|
+
.min(1000)
|
|
3587
|
+
.max(110000)
|
|
3588
|
+
.optional()
|
|
3589
|
+
.describe('最多等多少毫秒,默认 30000;等不到回 jobId 而不是报错'),
|
|
3590
|
+
}),
|
|
3591
|
+
},
|
|
3592
|
+
async (args) => {
|
|
3593
|
+
const { job, reused } = startExport(args)
|
|
3594
|
+
if (args.wait === false) return ok(jobPayload(job, reused ? { reused: true } : {}))
|
|
3595
|
+
const waitMs = Math.min(Math.max(Number(args.waitMs ?? 30000), 1000), 110000)
|
|
3596
|
+
await settleJob(job, waitMs)
|
|
3597
|
+
return jobBlocks(job, reused ? { reused: true } : { waitedMs: waitMs })
|
|
3598
|
+
},
|
|
3599
|
+
)
|
|
3600
|
+
|
|
3601
|
+
regTool(
|
|
3602
|
+
'manual',
|
|
3603
|
+
{
|
|
3604
|
+
title: '读手册',
|
|
3605
|
+
description:
|
|
3606
|
+
'把 PDF 手册的页面渲染成图给你看,用来搞清楚手册里有什么图、端子怎么定义。' +
|
|
3607
|
+
'文字层是乱码的 PDF(没有 ToUnicode 映射)也能正常看,因为走的是渲染不是抽文字。\n' +
|
|
3608
|
+
'action="outline":看总页数和目录,定页码范围。\n' +
|
|
3609
|
+
'action="search":搜关键词(文字层可读时才有用)。\n' +
|
|
3610
|
+
'action="render":把指定页画成图,一次最多 4 页(模型一步只收 8 张图,留余量)。',
|
|
3611
|
+
inputSchema: z.object({
|
|
3612
|
+
path: z.string().describe('PDF 绝对路径'),
|
|
3613
|
+
action: z.enum(['outline', 'search', 'render']).optional().describe('outline 看结构(默认);search 搜关键词;render 渲染成图'),
|
|
3614
|
+
from: z.number().int().min(1).optional().describe('render 的起始页,默认 1'),
|
|
3615
|
+
to: z.number().int().min(1).optional().describe('render 的结束页。一次最多 4 页'),
|
|
3616
|
+
scale: z.number().min(1).max(4).optional().describe('渲染倍率,默认 2。看图细节时可调 3'),
|
|
3617
|
+
queries: z.array(z.string()).optional().describe('search 要搜的关键词'),
|
|
3618
|
+
}),
|
|
3619
|
+
},
|
|
3620
|
+
async (args) => invokePdf(args),
|
|
3621
|
+
)
|
|
3622
|
+
|
|
3623
|
+
regTool(
|
|
3624
|
+
'operation_history',
|
|
3625
|
+
{
|
|
3626
|
+
title: '操作历史',
|
|
3627
|
+
description:
|
|
3628
|
+
'查这个项目上真实发生过的写操作(建页、插元件、改属性、画图、删页),含前后状态与能否回退。' +
|
|
3629
|
+
'记录由宿主在写操作落盘后自动追加,不需要你手动记。上下文丢了、想确认自己刚才改过什么、或者要撤回时用它。\n' +
|
|
3630
|
+
'action="wait":等一个 present 任务跑完并取回结果(含渲染图);present 传了 wait:false 后用它收尾。\n' +
|
|
3631
|
+
'记录只写不读、不自动进上下文,所以放心查。',
|
|
3632
|
+
inputSchema: z.object({
|
|
3633
|
+
action: z
|
|
3634
|
+
.enum(['list', 'wait'])
|
|
3635
|
+
.optional()
|
|
3636
|
+
.describe('list 查历史(默认);wait 等 present job 的结果'),
|
|
3637
|
+
project: z.string().optional().describe('只看某个项目;省略则用当前项目'),
|
|
3638
|
+
page: z.string().optional().describe('只看某一页'),
|
|
3639
|
+
operation_id: z.string().optional().describe('只看某一次操作,可拿到它完整的前后状态'),
|
|
3640
|
+
jobId: z.string().optional().describe('action="wait" 要等的 present jobId'),
|
|
3641
|
+
timeoutMs: z
|
|
3642
|
+
.number()
|
|
3643
|
+
.int()
|
|
3644
|
+
.min(1000)
|
|
3645
|
+
.max(110000)
|
|
3646
|
+
.optional()
|
|
3647
|
+
.describe('action="wait" 最多等多少毫秒,默认 25000;等不到会返回 state="running"'),
|
|
3648
|
+
limit: z.number().int().min(1).max(200).optional().describe('最多返回多少条,默认 30'),
|
|
3649
|
+
}),
|
|
3650
|
+
},
|
|
3651
|
+
async (args) => {
|
|
3652
|
+
if (args.action === 'wait') {
|
|
3653
|
+
need(args, ['jobId'], 'operation_history(wait)')
|
|
3654
|
+
gcJobs()
|
|
3655
|
+
const job = thatJob(args.jobId)
|
|
3656
|
+
if (!job) {
|
|
3657
|
+
return ok({
|
|
3658
|
+
jobId: args.jobId,
|
|
3659
|
+
state: 'unknown',
|
|
3660
|
+
hint: '找不到这个 job:可能已完成并过了保留期(15 分钟),或者 id 写错了。jobId 来自 present 的返回。',
|
|
3661
|
+
})
|
|
3662
|
+
}
|
|
3663
|
+
const timeoutMs = Math.min(Math.max(Number(args.timeoutMs ?? 25000), 1000), 110000)
|
|
3664
|
+
await settleJob(job, timeoutMs)
|
|
3665
|
+
// 图片文件在 job 完成时已落盘,这里直接按路径读,不额外占内存。
|
|
3666
|
+
if (job.state === 'done' && job.result?.imagePath) {
|
|
3667
|
+
return jobBlocks(job, { waitedMs: timeoutMs })
|
|
3668
|
+
}
|
|
3669
|
+
return ok(jobPayload(job, { waitedMs: timeoutMs }))
|
|
3670
|
+
}
|
|
3671
|
+
return invoke('op_history', {
|
|
3672
|
+
project: args.project,
|
|
3673
|
+
page: args.page,
|
|
3674
|
+
operation_id: args.operation_id,
|
|
3675
|
+
limit: args.limit,
|
|
3676
|
+
})
|
|
3677
|
+
},
|
|
3678
|
+
)
|
|
3679
|
+
|
|
3680
|
+
regTool(
|
|
3681
|
+
'operation_rollback',
|
|
3682
|
+
{
|
|
3683
|
+
title: '撤回操作',
|
|
3684
|
+
description:
|
|
3685
|
+
'按 operation_id 撤回一次写操作。能撤的只有:**建页**(删掉这次建的那页)、**插元件**(删掉这个对象)。' +
|
|
3686
|
+
'删页、画图元、改属性**撤不了** —— 删页之前没留快照,画图和改属性没有可靠的反向操作。' +
|
|
3687
|
+
'这几类会返回 undone:false 和原因,不会假装成功。' +
|
|
3688
|
+
'已经撤过的再撤会返回 alreadyUndone:true 但什么都不做。' +
|
|
3689
|
+
'**EPLAN API 的改动不进 GUI 撤销栈**,Ctrl+Z 对它们无效,这是唯一的退路。',
|
|
3690
|
+
inputSchema: z.object({
|
|
3691
|
+
operation_id: z.string().describe('operation_history 返回的操作 id'),
|
|
3692
|
+
}),
|
|
3693
|
+
},
|
|
3694
|
+
async (args) => {
|
|
3695
|
+
need(args, ['operation_id'], 'rollback')
|
|
3696
|
+
return invoke('op_rollback', { operation_id: args.operation_id })
|
|
3697
|
+
},
|
|
3698
|
+
)
|
|
3699
|
+
|
|
3700
|
+
/*
|
|
3701
|
+
--------------------------------------------------------------------------------
|
|
3702
|
+
经验文件:跨会话积累「什么路走不通、什么做法验证过」。
|
|
3703
|
+
--------------------------------------------------------------------------------
|
|
3704
|
+
和 symbol_catalog(action="annotate") 的区别:
|
|
3705
|
+
annotate 记「这个符号是什么」,按符号索引,同一个符号再记会覆盖;
|
|
3706
|
+
lesson 记「这个预设该怎么用」,只追加不覆盖,按时间倒序读。
|
|
3707
|
+
|
|
3708
|
+
为什么只追加:一条经验最值钱的部分常常是「当时是这么错的」。覆盖掉错误记录,
|
|
3709
|
+
下一个人还会再错一次。所以宁可留着一堆历史,也不做原地更新。
|
|
3710
|
+
*/
|
|
3711
|
+
regTool(
|
|
3712
|
+
'lesson',
|
|
3713
|
+
{
|
|
3714
|
+
title: '经验文件',
|
|
3715
|
+
description:
|
|
3716
|
+
'跨会话留存的经验:踩到的坑、验证过的做法、被用户纠正过的判断。\n' +
|
|
3717
|
+
'action="add":记一条。写上具体发生了什么、结论是什么,别写「注意 XX 」这种没信息量的话。\n' +
|
|
3718
|
+
'action="list":读回来,可按关键词过滤,最新在前。\n' +
|
|
3719
|
+
'**什么时候该记**:用户纠正了你、某个参数/动作名和你以为的不一样、某个做法第一次跑通。' +
|
|
3720
|
+
'**什么时候别记**:一次性的坐标、页名、项目名 —— 那些属于操作历史,不叫经验。\n' +
|
|
3721
|
+
'最近 5 条会随 workspace(action="status") 一起返回,不用特意去翻。' +
|
|
3722
|
+
'这个工具直接读写本地文件,**不需要 EPLAN 在运行**。',
|
|
3723
|
+
inputSchema: z.object({
|
|
3724
|
+
action: z.enum(['add', 'list', 'prefer']).describe('add 记经验,prefer 记用户偏好,list 读回来'),
|
|
3725
|
+
text: z.string().optional().describe('add 的内容。要具体:什么操作、什么现象、什么结论'),
|
|
3726
|
+
kind: z
|
|
3727
|
+
.enum(['pitfall', 'recipe', 'decision'])
|
|
3728
|
+
.optional()
|
|
3729
|
+
.describe('add 的分类:pitfall 踩坑 / recipe 验证过的做法 / decision 做过的取舍,默认 pitfall'),
|
|
3730
|
+
scope: z
|
|
3731
|
+
.enum(['general', 'project', 'preference'])
|
|
3732
|
+
.optional()
|
|
3733
|
+
.describe('add 的作用域:general 通用 / project 只对本项目 / preference 用户偏好,默认按有无 project 推断'),
|
|
3734
|
+
brief: z.string().optional().describe('add / prefer 的一句话摘要(≤60 字),给 status 用'),
|
|
3735
|
+
prefer: z
|
|
3736
|
+
.object({
|
|
3737
|
+
source: z
|
|
3738
|
+
.enum(['user', 'inferred'])
|
|
3739
|
+
.optional()
|
|
3740
|
+
.describe('user 用户明说过 / inferred 从行为推断,默认 user'),
|
|
3741
|
+
weight: z.number().int().min(1).max(10).optional().describe('权重 1–10,默认 5'),
|
|
3742
|
+
})
|
|
3743
|
+
.optional()
|
|
3744
|
+
.describe('prefer 的选项'),
|
|
3745
|
+
tags: z.array(z.string()).optional().describe('add 的标签,便于以后筛选,例如 ["focus", "page_open"]'),
|
|
3746
|
+
query: z.string().optional().describe('list 的关键词过滤'),
|
|
3747
|
+
limit: z.number().int().min(1).max(200).optional().describe('list 最多返回多少条,默认 20'),
|
|
3748
|
+
project: z.string().optional().describe('add 时可选:这条经验出自哪个项目'),
|
|
3749
|
+
page: z.string().optional().describe('add 时可选:出自哪一页'),
|
|
3750
|
+
}).passthrough(),
|
|
3751
|
+
},
|
|
3752
|
+
async (args) => {
|
|
3753
|
+
// 本地实现,不走桥接器:EPLAN 没开也要能记、能读。
|
|
3754
|
+
if (args.action === 'add') {
|
|
3755
|
+
return ok(
|
|
3756
|
+
addNote({
|
|
3757
|
+
text: args.text,
|
|
3758
|
+
kind: args.kind,
|
|
3759
|
+
tags: args.tags,
|
|
3760
|
+
project: args.project,
|
|
3761
|
+
page: args.page,
|
|
3762
|
+
scope: args.scope,
|
|
3763
|
+
brief: args.brief,
|
|
3764
|
+
}),
|
|
3765
|
+
)
|
|
3766
|
+
}
|
|
3767
|
+
if (args.action === 'prefer') {
|
|
3768
|
+
return ok(
|
|
3769
|
+
addPreference({
|
|
3770
|
+
text: args.text,
|
|
3771
|
+
source: args.prefer?.source ?? args.source,
|
|
3772
|
+
weight: args.prefer?.weight ?? args.weight,
|
|
3773
|
+
tags: args.tags,
|
|
3774
|
+
}),
|
|
3775
|
+
)
|
|
3776
|
+
}
|
|
3777
|
+
if (args.action === 'list') {
|
|
3778
|
+
return ok(listNotes({ query: args.query, limit: args.limit }))
|
|
3779
|
+
}
|
|
3780
|
+
throw fail('BAD_ARGUMENT', `lesson 不认识 action="${args.action}"。`, '只支持 add / list / prefer。')
|
|
3781
|
+
},
|
|
3782
|
+
)
|
|
3783
|
+
|
|
3784
|
+
// ---------------------------------------------------------------------------
|
|
3785
|
+
// 启动:stdio 是唯一的传输方式;stdout 留给协议,日志一律走 stderr。
|
|
3786
|
+
// ---------------------------------------------------------------------------
|
|
3787
|
+
|
|
3788
|
+
process.on('exit', () => stopBridge('进程退出'))
|
|
3789
|
+
process.on('SIGINT', () => {
|
|
3790
|
+
stopBridge('收到 SIGINT')
|
|
3791
|
+
process.exit(0)
|
|
3792
|
+
})
|
|
3793
|
+
|
|
3794
|
+
const transport = new StdioServerTransport()
|
|
3795
|
+
await server.connect(transport)
|
|
3796
|
+
process.stderr.write(`[eplan-mcp] 已启动,桥接器: ${config.bridgeExe}\n`)
|
|
3797
|
+
|