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,221 @@
|
|
|
1
|
+
// EPLAN 引导脚本:唯一一个装进 EPLAN 的东西。
|
|
2
|
+
//
|
|
3
|
+
// ── 为什么需要它 ────────────────────────────────────────────────
|
|
4
|
+
// EPLAN 自己的脚本编译器引用集是写死的(见 EplanEplApiScriptLogu.erx),只有
|
|
5
|
+
// mscorlib / System / System.Core / System.Drawing / System.XML / System.Xml.Linq /
|
|
6
|
+
// System.Windows.Forms / System.IO.Compression.FileSystem /
|
|
7
|
+
// Eplan.EplApi.Baseu / AFu / Guiu / RecorderToolsu / EServicesu。
|
|
8
|
+
// Eplan.EplApi.DataModelu.dll 和 HEServicesu.dll 都不在里面,
|
|
9
|
+
// 所以脚本里连 "DataModel" 这个命名空间都看不见,画不了图。
|
|
10
|
+
//
|
|
11
|
+
// 于是脚本只做一件事:反射加载我们自己的 EplanMcpHost.dll(它是用 csc 编的,
|
|
12
|
+
// 不受那个引用集约束),把 JSON 转交给它。脚本里不出现任何 DataModel 类型。
|
|
13
|
+
//
|
|
14
|
+
// ── 三个用 EPLAN 日志试出来的硬约束 ──────────────────────────────
|
|
15
|
+
// 1. ExecuteScript 动作只执行 [Start],**不注册** [DeclareAction]。
|
|
16
|
+
// 要注册必须用 RegisterScript 动作(参数 ScriptFile=<绝对路径>)。
|
|
17
|
+
// 2. [DeclareAction] 方法必须是**无参 void**。带 ActionCallingContext 参数虽然
|
|
18
|
+
// 能注册、能执行,但 ExecuteAction 会返回 false,而且 context.GetContextParameter()
|
|
19
|
+
// 返回 null(Remoting 的上下文传不进来)。
|
|
20
|
+
// 3. 因此请求/响应不能走 CallingContext,改用文件交换:
|
|
21
|
+
// 请求 C:\Users\Public\EPLAN\Data\eplan-mcp\ipc\request.json
|
|
22
|
+
// 响应 C:\Users\Public\EPLAN\Data\eplan-mcp\ipc\reply-<id>.json
|
|
23
|
+
// 脚本读走请求后立刻删除,处理完再写响应,客户端轮询响应文件。
|
|
24
|
+
//
|
|
25
|
+
// ── 热重载 ──────────────────────────────────────────────────────
|
|
26
|
+
// EPLAN 进程一旦 Assembly.LoadFrom 了某个 DLL,那个文件就被锁住,改代码后
|
|
27
|
+
// 覆盖不了。所以宿主目录里放的是带版本号的文件(EplanMcpHost-<ticks>.dll),
|
|
28
|
+
// 每次构建产生一个新文件名,旧的不动。本脚本每次调用都取目录里最新的那个,
|
|
29
|
+
// 和当前已加载的不是同一个就重新加载 —— 改完宿主代码重新构建即可生效,
|
|
30
|
+
// 不用重启 EPLAN。
|
|
31
|
+
public class EplanMcpBootstrap
|
|
32
|
+
{
|
|
33
|
+
// 宿主 DLL 目录。prepare-install.ps1 会自动改写这一行。
|
|
34
|
+
private const string HostDir = @"__HOST_DLL_DIR__";
|
|
35
|
+
|
|
36
|
+
private const string IpcDir = @"C:\Users\Public\EPLAN\Data\eplan-mcp\ipc";
|
|
37
|
+
private const string RequestPath = IpcDir + @"\request.json";
|
|
38
|
+
|
|
39
|
+
private static object _entry;
|
|
40
|
+
private static string _loadedPath;
|
|
41
|
+
|
|
42
|
+
[Eplan.EplApi.Scripting.Start]
|
|
43
|
+
public void Start(Eplan.EplApi.ApplicationFramework.ActionCallingContext context)
|
|
44
|
+
{
|
|
45
|
+
Log("引导脚本已加载,宿主目录: " + HostDir);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
[Eplan.EplApi.Scripting.DeclareAction("EplanMcpRun")]
|
|
49
|
+
public void Run()
|
|
50
|
+
{
|
|
51
|
+
string requestText;
|
|
52
|
+
string requestId = null;
|
|
53
|
+
|
|
54
|
+
try
|
|
55
|
+
{
|
|
56
|
+
if (!System.IO.Directory.Exists(IpcDir))
|
|
57
|
+
{
|
|
58
|
+
Log("IPC 目录不存在,动作被调用但无请求: " + IpcDir);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (!System.IO.File.Exists(RequestPath))
|
|
62
|
+
{
|
|
63
|
+
Log("没有待处理的请求文件,动作被调用但无内容。");
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 先读再删:删掉才能让"处理中"和"新请求"区分开,
|
|
68
|
+
// 也避免同一个请求被处理两次。
|
|
69
|
+
requestText = System.IO.File.ReadAllText(RequestPath, System.Text.Encoding.UTF8);
|
|
70
|
+
System.IO.File.Delete(RequestPath);
|
|
71
|
+
}
|
|
72
|
+
catch (System.Exception ex)
|
|
73
|
+
{
|
|
74
|
+
Log("读取请求失败: " + ex.GetType().Name + ": " + ex.Message);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 从请求里抠出 id,用来命名响应文件。手写解析,避免依赖 JSON 库。
|
|
79
|
+
try
|
|
80
|
+
{
|
|
81
|
+
int idStart = requestText.IndexOf("\"id\"", System.StringComparison.Ordinal);
|
|
82
|
+
if (idStart >= 0)
|
|
83
|
+
{
|
|
84
|
+
int colon = requestText.IndexOf(':', idStart);
|
|
85
|
+
int quote1 = requestText.IndexOf('"', colon + 1);
|
|
86
|
+
int quote2 = requestText.IndexOf('"', quote1 + 1);
|
|
87
|
+
if (quote1 > 0 && quote2 > quote1)
|
|
88
|
+
requestId = requestText.Substring(quote1 + 1, quote2 - quote1 - 1);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
catch { }
|
|
92
|
+
|
|
93
|
+
if (string.IsNullOrEmpty(requestId))
|
|
94
|
+
{
|
|
95
|
+
Log("请求里没有 id,放弃处理。");
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
string replyPath = System.IO.Path.Combine(IpcDir, "reply-" + requestId + ".json");
|
|
100
|
+
string replyText;
|
|
101
|
+
|
|
102
|
+
try
|
|
103
|
+
{
|
|
104
|
+
replyText = InvokeHost(requestText);
|
|
105
|
+
}
|
|
106
|
+
catch (System.Exception ex)
|
|
107
|
+
{
|
|
108
|
+
replyText = Fail("HOST_LOAD_FAILED",
|
|
109
|
+
"加载或调用宿主失败: " + ex.GetType().Name + ": " + ex.Message,
|
|
110
|
+
ex.ToString());
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// 先写临时文件再改名,避免客户端读到写了一半的 JSON。
|
|
114
|
+
string tempPath = replyPath + ".tmp";
|
|
115
|
+
try
|
|
116
|
+
{
|
|
117
|
+
System.IO.File.WriteAllText(tempPath, replyText, System.Text.Encoding.UTF8);
|
|
118
|
+
if (System.IO.File.Exists(replyPath)) System.IO.File.Delete(replyPath);
|
|
119
|
+
System.IO.File.Move(tempPath, replyPath);
|
|
120
|
+
}
|
|
121
|
+
catch (System.Exception ex)
|
|
122
|
+
{
|
|
123
|
+
Log("写响应失败: " + ex.GetType().Name + ": " + ex.Message + " → " + replyPath);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/// <summary>加载最新的宿主 DLL 并调用 Entry.Run(payload)。</summary>
|
|
128
|
+
private static string InvokeHost(string payload)
|
|
129
|
+
{
|
|
130
|
+
string newest = NewestHostDll();
|
|
131
|
+
if (newest == null)
|
|
132
|
+
throw new System.IO.FileNotFoundException("宿主目录里没有 EplanMcpHost-*.dll: " + HostDir);
|
|
133
|
+
|
|
134
|
+
// 构建出了新版本就换掉,实现热重载。
|
|
135
|
+
if (_entry == null || !string.Equals(newest, _loadedPath, System.StringComparison.OrdinalIgnoreCase))
|
|
136
|
+
{
|
|
137
|
+
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(newest);
|
|
138
|
+
System.Type entryType = assembly.GetType("EplanMcpHost.Entry", true);
|
|
139
|
+
_entry = System.Activator.CreateInstance(entryType);
|
|
140
|
+
_loadedPath = newest;
|
|
141
|
+
Log("宿主已加载: " + newest);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
System.Reflection.MethodInfo run = _entry.GetType().GetMethod("Run");
|
|
145
|
+
object result = run.Invoke(_entry, new object[] { payload });
|
|
146
|
+
return result as string;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/// <summary>取宿主目录里修改时间最新的 EplanMcpHost-*.dll。</summary>
|
|
150
|
+
private static string NewestHostDll()
|
|
151
|
+
{
|
|
152
|
+
if (!System.IO.Directory.Exists(HostDir)) return null;
|
|
153
|
+
|
|
154
|
+
string best = null;
|
|
155
|
+
System.DateTime bestTime = System.DateTime.MinValue;
|
|
156
|
+
string[] files = System.IO.Directory.GetFiles(HostDir, "EplanMcpHost-*.dll");
|
|
157
|
+
foreach (string file in files)
|
|
158
|
+
{
|
|
159
|
+
System.DateTime time = System.IO.File.GetLastWriteTimeUtc(file);
|
|
160
|
+
if (time > bestTime)
|
|
161
|
+
{
|
|
162
|
+
bestTime = time;
|
|
163
|
+
best = file;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return best;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private static string Fail(string code, string message, string detail)
|
|
170
|
+
{
|
|
171
|
+
System.Text.StringBuilder sb = new System.Text.StringBuilder();
|
|
172
|
+
sb.Append("{\"ok\":false,\"error\":{\"code\":");
|
|
173
|
+
sb.Append(Quote(code));
|
|
174
|
+
sb.Append(",\"message\":");
|
|
175
|
+
sb.Append(Quote(message));
|
|
176
|
+
if (detail != null)
|
|
177
|
+
{
|
|
178
|
+
sb.Append(",\"detail\":");
|
|
179
|
+
sb.Append(Quote(detail.Length > 4000 ? detail.Substring(0, 4000) : detail));
|
|
180
|
+
}
|
|
181
|
+
sb.Append("}}");
|
|
182
|
+
return sb.ToString();
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
private static string Quote(string text)
|
|
186
|
+
{
|
|
187
|
+
if (text == null) return "null";
|
|
188
|
+
System.Text.StringBuilder sb = new System.Text.StringBuilder("\"");
|
|
189
|
+
foreach (char c in text)
|
|
190
|
+
{
|
|
191
|
+
switch (c)
|
|
192
|
+
{
|
|
193
|
+
case '"': sb.Append("\\\""); break;
|
|
194
|
+
case '\\': sb.Append("\\\\"); break;
|
|
195
|
+
case '\n': sb.Append("\\n"); break;
|
|
196
|
+
case '\r': sb.Append("\\r"); break;
|
|
197
|
+
case '\t': sb.Append("\\t"); break;
|
|
198
|
+
default:
|
|
199
|
+
if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4"));
|
|
200
|
+
else sb.Append(c);
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
sb.Append('"');
|
|
205
|
+
return sb.ToString();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/// <summary>日志写到 Public 下的固定文件。EPLAN 的 Remoting 通道不能往 console 写。</summary>
|
|
209
|
+
private static void Log(string message)
|
|
210
|
+
{
|
|
211
|
+
try
|
|
212
|
+
{
|
|
213
|
+
string dir = @"C:\Users\Public\EPLAN\Data\eplan-mcp";
|
|
214
|
+
if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);
|
|
215
|
+
System.IO.File.AppendAllText(dir + @"\bootstrap.log",
|
|
216
|
+
System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + message + "\r\n",
|
|
217
|
+
System.Text.Encoding.UTF8);
|
|
218
|
+
}
|
|
219
|
+
catch { }
|
|
220
|
+
}
|
|
221
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// 生成「符号图鉴」:把常用符号在 EPLAN 里真画一遍,逐张导出成小图。
|
|
2
|
+
//
|
|
3
|
+
// 为什么要有:模型查元器件时看不到它长什么样,只能靠名字猜;用户要求「常用的几个图
|
|
4
|
+
// 在初始阶段就给出样子」。这里用 EPLAN 自己渲染,保证和真实库一致。
|
|
5
|
+
//
|
|
6
|
+
// 做法:建一张临时页 → 按网格插常用符号 → 渲染整页 → 按毫米坐标裁成单张 → 存进
|
|
7
|
+
// knowledge/symbols/。之后 focus / symbol_catalog(pins) 直接发这些图,不再麻烦 EPLAN。
|
|
8
|
+
//
|
|
9
|
+
// node native/script/build-symbol-gallery.mjs [--keep-page]
|
|
10
|
+
import { spawn } from 'node:child_process'
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
|
|
12
|
+
import { join, dirname } from 'node:path'
|
|
13
|
+
import { fileURLToPath } from 'node:url'
|
|
14
|
+
import { tmpdir } from 'node:os'
|
|
15
|
+
|
|
16
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
17
|
+
const root = join(here, '..', '..')
|
|
18
|
+
const OUT_DIR = join(root, 'knowledge', 'symbols')
|
|
19
|
+
const PAGE = '=JQR2623/900'
|
|
20
|
+
const keepPage = process.argv.includes('--keep-page')
|
|
21
|
+
|
|
22
|
+
// 常用符号:名字 / 库 / 变体 / 裁切框([宽, 高, 左边界占比],毫米,相对插入点)
|
|
23
|
+
// 左边界占比是必要的:三极开关从插入点往右长 16 mm,居中对齐会把第三极切掉。
|
|
24
|
+
const SYMBOLS = [
|
|
25
|
+
{ key: 'BP', library: 'SPECIAL', variant: 0, box: [30, 24, 0.5] },
|
|
26
|
+
{ key: 'CO', library: 'SPECIAL', variant: 0, box: [24, 24, 0.5] },
|
|
27
|
+
{ key: 'TLRU', library: 'SPECIAL', variant: 0, box: [30, 24, 0.5] },
|
|
28
|
+
{ key: 'TOUR', library: 'SPECIAL', variant: 0, box: [30, 24, 0.5] },
|
|
29
|
+
{ key: 'TLRO', library: 'SPECIAL', variant: 0, box: [30, 24, 0.5] },
|
|
30
|
+
{ key: 'TOUL', library: 'SPECIAL', variant: 0, box: [30, 24, 0.5] },
|
|
31
|
+
{ key: 'CDPST', library: 'SPECIAL', variant: 0, box: [24, 28, 0.5] },
|
|
32
|
+
{ key: 'FA3', library: 'GB_symbol', variant: 0, box: [30, 20, 0.2] },
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
const COLS = 4
|
|
36
|
+
const PITCH_X = 70
|
|
37
|
+
const PITCH_Y = 80
|
|
38
|
+
const ORIGIN = [70, 230]
|
|
39
|
+
|
|
40
|
+
// ── MCP 客户端 ────────────────────────────────────────────────────────────
|
|
41
|
+
const child = spawn(process.execPath, ['server/server.mjs'], { cwd: root, stdio: ['pipe', 'pipe', 'pipe'] })
|
|
42
|
+
let buffer = ''
|
|
43
|
+
const pending = new Map()
|
|
44
|
+
let nextId = 1
|
|
45
|
+
child.stdout.setEncoding('utf8')
|
|
46
|
+
child.stdout.on('data', (chunk) => {
|
|
47
|
+
buffer += chunk
|
|
48
|
+
let index
|
|
49
|
+
while ((index = buffer.indexOf('\n')) >= 0) {
|
|
50
|
+
const line = buffer.slice(0, index).trim()
|
|
51
|
+
buffer = buffer.slice(index + 1)
|
|
52
|
+
if (!line) continue
|
|
53
|
+
let message
|
|
54
|
+
try { message = JSON.parse(line) } catch { continue }
|
|
55
|
+
const resolve = pending.get(message.id)
|
|
56
|
+
if (resolve) { pending.delete(message.id); resolve(message) }
|
|
57
|
+
}
|
|
58
|
+
})
|
|
59
|
+
child.stderr.setEncoding('utf8')
|
|
60
|
+
child.stderr.on('data', (chunk) => process.stderr.write(`[server] ${chunk}`))
|
|
61
|
+
|
|
62
|
+
function request(method, params) {
|
|
63
|
+
const id = nextId++
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
const timer = setTimeout(() => reject(new Error(`${method} 超时`)), 180000)
|
|
66
|
+
pending.set(id, (message) => { clearTimeout(timer); resolve(message) })
|
|
67
|
+
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n')
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function call(tool, args) {
|
|
72
|
+
const reply = await request('tools/call', { name: tool, arguments: args })
|
|
73
|
+
const result = reply.result ?? {}
|
|
74
|
+
const text = (result.content ?? []).find((block) => block.type === 'text')?.text ?? ''
|
|
75
|
+
return { isError: result.isError === true, text, result }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 从工具返回里挖出第一个 JSON 对象(服务端通常会带一段说明文字)。 */
|
|
79
|
+
function jsonOf(text) {
|
|
80
|
+
const start = text.indexOf('{')
|
|
81
|
+
if (start < 0) return null
|
|
82
|
+
let depth = 0
|
|
83
|
+
for (let index = start; index < text.length; index += 1) {
|
|
84
|
+
if (text[index] === '{') depth += 1
|
|
85
|
+
if (text[index] === '}') {
|
|
86
|
+
depth -= 1
|
|
87
|
+
if (depth === 0) {
|
|
88
|
+
try { return JSON.parse(text.slice(start, index + 1)) } catch { return null }
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return null
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ── 主流程 ────────────────────────────────────────────────────────────────
|
|
96
|
+
try {
|
|
97
|
+
await request('initialize', { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'gallery', version: '0' } })
|
|
98
|
+
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n')
|
|
99
|
+
|
|
100
|
+
const status = await call('workspace', { action: 'status' })
|
|
101
|
+
const statusJson = jsonOf(status.text)
|
|
102
|
+
console.log('项目:', statusJson?.currentProject?.name ?? statusJson?.project ?? '(未知)', '当前页:', statusJson?.visiblePage ?? '?')
|
|
103
|
+
|
|
104
|
+
// 已存在的临时页先删掉,避免重复插入。
|
|
105
|
+
const del = await call('page_delete', { page: PAGE, force: true })
|
|
106
|
+
if (!del.isError) console.log('清理旧的图鉴页')
|
|
107
|
+
|
|
108
|
+
const created = await call('page_create', { name: PAGE })
|
|
109
|
+
console.log('建页:', created.isError ? `失败 ${created.text.slice(0, 200)}` : 'ok')
|
|
110
|
+
if (created.isError) throw new Error(created.text.slice(0, 300))
|
|
111
|
+
|
|
112
|
+
const placed = []
|
|
113
|
+
for (let index = 0; index < SYMBOLS.length; index += 1) {
|
|
114
|
+
const symbol = SYMBOLS[index]
|
|
115
|
+
const column = index % COLS
|
|
116
|
+
const row = Math.floor(index / COLS)
|
|
117
|
+
const at = [ORIGIN[0] + column * PITCH_X, ORIGIN[1] - row * PITCH_Y]
|
|
118
|
+
const inserted = await call('page_edit', {
|
|
119
|
+
action: 'insert_symbol',
|
|
120
|
+
page: PAGE,
|
|
121
|
+
insert: { symbol: symbol.key, library: symbol.library, variant: symbol.variant, at },
|
|
122
|
+
})
|
|
123
|
+
if (inserted.isError) {
|
|
124
|
+
console.log(`✗ ${symbol.key}: ${inserted.text.slice(0, 160)}`)
|
|
125
|
+
continue
|
|
126
|
+
}
|
|
127
|
+
placed.push({ ...symbol, at })
|
|
128
|
+
console.log(`✓ ${symbol.key} @ ${at.join(',')} mm`)
|
|
129
|
+
}
|
|
130
|
+
if (placed.length === 0) throw new Error('一个符号都没插进去,先看上面的错误')
|
|
131
|
+
|
|
132
|
+
const shot = await call('page_inspect', { format: 'image', page: PAGE, width: 4200 })
|
|
133
|
+
const shotJson = jsonOf(shot.text)
|
|
134
|
+
const imagePath = shotJson?.imagePath ?? shotJson?.image?.path
|
|
135
|
+
console.log('渲染:', imagePath ?? shot.text.slice(0, 200))
|
|
136
|
+
if (!imagePath || !existsSync(imagePath)) throw new Error('没拿到渲染图路径')
|
|
137
|
+
|
|
138
|
+
mkdirSync(OUT_DIR, { recursive: true })
|
|
139
|
+
const { execFile } = await import('node:child_process')
|
|
140
|
+
const run = (command, args) => new Promise((resolve) => execFile(command, args, { maxBuffer: 1 << 26 }, (error, stdout, stderr) => resolve({ error, stdout, stderr })))
|
|
141
|
+
|
|
142
|
+
// 页尺寸从渲染图反推:整页渲染时宽度对应纸宽毫米。
|
|
143
|
+
const pageJson = jsonOf((await call('page_inspect', { format: 'structure', page: PAGE, view: 'summary' })).text)
|
|
144
|
+
const paper = pageJson?.page?.size ?? pageJson?.size ?? [420, 297]
|
|
145
|
+
const png = readFileSync(imagePath)
|
|
146
|
+
const pngWidth = png.readUInt32BE(16)
|
|
147
|
+
const pngHeight = png.readUInt32BE(20)
|
|
148
|
+
const pxPerMm = pngWidth / paper[0]
|
|
149
|
+
console.log(`渲染图 ${pngWidth}x${pngHeight}px,纸 ${paper[0]}x${paper[1]}mm,${pxPerMm.toFixed(2)} px/mm`)
|
|
150
|
+
|
|
151
|
+
const manifest = []
|
|
152
|
+
for (const symbol of placed) {
|
|
153
|
+
const [boxW, boxH, leftRatio] = symbol.box
|
|
154
|
+
// 先切一个宽松的窗口,让 cropdetect 去掉黑边再收紧 —— 各种符号的原点偏移不一样,
|
|
155
|
+
// 写死像素框会把箭头切到边上(第一版就这样)。
|
|
156
|
+
const leftMm = symbol.at[0] - boxW * leftRatio
|
|
157
|
+
const bottomMm = symbol.at[1] - boxH * 0.5
|
|
158
|
+
const x = Math.max(0, Math.round(leftMm * pxPerMm))
|
|
159
|
+
const y = Math.max(0, Math.round((paper[1] - bottomMm - boxH) * pxPerMm))
|
|
160
|
+
const w = Math.round(boxW * pxPerMm)
|
|
161
|
+
const h = Math.round(boxH * pxPerMm)
|
|
162
|
+
const raw = join(tmpdir(), `gallery-${symbol.key}.png`)
|
|
163
|
+
const wide = await run('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', imagePath, '-vf', `crop=${w}:${h}:${x}:${y}`, '-y', raw])
|
|
164
|
+
if (wide.error || !existsSync(raw)) {
|
|
165
|
+
console.log(`✗ 切 ${symbol.key}: ${wide.stderr?.slice(0, 160)}`)
|
|
166
|
+
continue
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 去掉黑边:把这块导成灰度原始帧,自己在 Node 里找内容框。
|
|
170
|
+
// (ffmpeg 的 cropdetect 在这种纯黑底单帧上什么都不打印,不可靠。)
|
|
171
|
+
const gray = join(tmpdir(), `gallery-${symbol.key}.gray`)
|
|
172
|
+
const dumped = await run('ffmpeg', [
|
|
173
|
+
'-hide_banner', '-loglevel', 'error', '-i', imagePath,
|
|
174
|
+
'-vf', `crop=${w}:${h}:${x}:${y},format=gray`,
|
|
175
|
+
'-f', 'rawvideo', '-pix_fmt', 'gray', '-y', gray,
|
|
176
|
+
])
|
|
177
|
+
let contentBox = null
|
|
178
|
+
if (!dumped.error && existsSync(gray)) {
|
|
179
|
+
const pixels = readFileSync(gray)
|
|
180
|
+
let minX = w, minY = h, maxX = -1, maxY = -1
|
|
181
|
+
for (let row = 0; row < h; row += 1) {
|
|
182
|
+
for (let column = 0; column < w; column += 1) {
|
|
183
|
+
if (pixels[row * w + column] > 40) {
|
|
184
|
+
if (column < minX) minX = column
|
|
185
|
+
if (column > maxX) maxX = column
|
|
186
|
+
if (row < minY) minY = row
|
|
187
|
+
if (row > maxY) maxY = row
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (maxX > minX && maxY > minY) {
|
|
192
|
+
const pad = 8
|
|
193
|
+
const cx = Math.max(0, minX - pad)
|
|
194
|
+
const cy = Math.max(0, minY - pad)
|
|
195
|
+
contentBox = {
|
|
196
|
+
x: cx,
|
|
197
|
+
y: cy,
|
|
198
|
+
w: Math.min(w - cx, maxX - minX + 1 + pad * 2),
|
|
199
|
+
h: Math.min(h - cy, maxY - minY + 1 + pad * 2),
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const file = join(OUT_DIR, `${symbol.key}.png`)
|
|
205
|
+
const filters = []
|
|
206
|
+
if (contentBox) filters.push(`crop=${contentBox.w}:${contentBox.h}:${contentBox.x}:${contentBox.y}`)
|
|
207
|
+
// 小符号最多放大 2 倍:再大就只是把 1~2 px 的线糊开,反而看不清。
|
|
208
|
+
if (contentBox && contentBox.w < 200) filters.push('scale=iw*2:ih*2:flags=lanczos')
|
|
209
|
+
const cropped = await run('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', raw, '-vf', filters.join(','), '-y', file])
|
|
210
|
+
if (cropped.error || !existsSync(file)) {
|
|
211
|
+
console.log(`✗ 裁 ${symbol.key}: ${cropped.stderr?.slice(0, 160)}`)
|
|
212
|
+
continue
|
|
213
|
+
}
|
|
214
|
+
manifest.push({ key: symbol.key, library: symbol.library, variant: symbol.variant, file: `${symbol.key}.png`, box: [boxW, boxH] })
|
|
215
|
+
console.log(`✓ 出图 ${symbol.key}.png${contentBox ? ` (内容 ${contentBox.w}x${contentBox.h})` : ' (空图?)'}`)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
writeFileSync(join(OUT_DIR, 'manifest.json'), JSON.stringify({ generatedAt: new Date().toISOString(), page: PAGE, paper, pxPerMm, symbols: manifest }, null, 2), 'utf8')
|
|
219
|
+
console.log(`完成:${manifest.length} 张图 → ${OUT_DIR}`)
|
|
220
|
+
|
|
221
|
+
if (!keepPage) {
|
|
222
|
+
const removed = await call('page_delete', { page: PAGE, force: true })
|
|
223
|
+
console.log('清理临时页:', removed.isError ? `失败 ${removed.text.slice(0, 160)}` : 'ok')
|
|
224
|
+
}
|
|
225
|
+
} catch (error) {
|
|
226
|
+
console.error('失败:', error.message)
|
|
227
|
+
process.exitCode = 1
|
|
228
|
+
} finally {
|
|
229
|
+
child.stdin.end()
|
|
230
|
+
child.kill()
|
|
231
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# 生成装进 EPLAN 的引导脚本(把 HostDir 换成真实路径)。
|
|
2
|
+
#
|
|
3
|
+
# 两个"带版本号"的原因,都是 EPLAN 的缓存行为逼出来的:
|
|
4
|
+
# 1. 宿主 DLL 用 EplanMcpHost-<ticks>.dll。EPLAN 加载后锁住文件,覆盖会报 CS0016;
|
|
5
|
+
# 每次构建产生新文件名,引导脚本挑最新的,实现热重载。
|
|
6
|
+
# 2. 引导脚本本身也用 EplanMcpBootstrap-<ticks>.cs。RegisterScript 对**同一个路径**
|
|
7
|
+
# 会复用已编译的程序集,改了源码也不重新编译;换个文件名才强制重编译。
|
|
8
|
+
#
|
|
9
|
+
# 用法: powershell -NoProfile -ExecutionPolicy Bypass -File native\script\prepare-install.ps1
|
|
10
|
+
$ErrorActionPreference = 'Stop'
|
|
11
|
+
|
|
12
|
+
$root = Split-Path -Parent $PSScriptRoot
|
|
13
|
+
$source = Join-Path $PSScriptRoot 'EplanMcpBootstrap.cs'
|
|
14
|
+
$hostDir = Join-Path $root 'host\bin'
|
|
15
|
+
$stamp = [DateTime]::UtcNow.Ticks
|
|
16
|
+
$target = Join-Path $PSScriptRoot "EplanMcpBootstrap-$stamp.cs"
|
|
17
|
+
|
|
18
|
+
if (-not (Test-Path -LiteralPath $hostDir)) {
|
|
19
|
+
throw "宿主还没编译:$hostDir。先运行 native\host\build.ps1"
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
$latest = Get-ChildItem -LiteralPath $hostDir -Filter 'EplanMcpHost-*.dll' -ErrorAction SilentlyContinue |
|
|
23
|
+
Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1
|
|
24
|
+
if (-not $latest) {
|
|
25
|
+
throw "宿主还没编译:$hostDir 里没有 EplanMcpHost-*.dll。先运行 native\host\build.ps1"
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
$text = Get-Content -LiteralPath $source -Raw -Encoding UTF8
|
|
29
|
+
if ($text -notmatch '__HOST_DLL_DIR__') {
|
|
30
|
+
Write-Host '警告:模板里没有 __HOST_DLL_DIR__ 占位符,可能已经生成过。' -ForegroundColor Yellow
|
|
31
|
+
}
|
|
32
|
+
$text = $text.Replace('__HOST_DLL_DIR__', $hostDir)
|
|
33
|
+
|
|
34
|
+
# EPLAN 的脚本编译器读 UTF-8,带 BOM 最稳。
|
|
35
|
+
[System.IO.File]::WriteAllText($target, $text, (New-Object System.Text.UTF8Encoding($true)))
|
|
36
|
+
|
|
37
|
+
# 不要删历史引导脚本。
|
|
38
|
+
#
|
|
39
|
+
# 这些文件可能已经被 EPLAN 的 RegisterScript 记住了路径;删掉之后 EPLAN 每次启动
|
|
40
|
+
# 都会记一条 S046001「未找到指定的脚本文件」,并自动弹出「系统消息」框。
|
|
41
|
+
# 那个框占住 EPLAN 主线程,桥接器会预先检查到它,于是所有调用都返回
|
|
42
|
+
# EPLAN_BLOCKED_BY_DIALOG —— 2026-11-20 实测:几个失效注册就能让整条链路看起来像卡死。
|
|
43
|
+
# 一个文件 9 KB,留着比删掉便宜。
|
|
44
|
+
$scripts = @(Get-ChildItem -LiteralPath $PSScriptRoot -Filter 'EplanMcpBootstrap-*.cs')
|
|
45
|
+
if ($scripts.Count -gt 6) {
|
|
46
|
+
Write-Host "提示:已有 $($scripts.Count) 个历史引导脚本。EPLAN 里注册过的文件不要手动删;要清理先在 EPLAN 里取消注册。" -ForegroundColor DarkYellow
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
Write-Host "已生成: $(Split-Path -Leaf $target)" -ForegroundColor Green
|
|
50
|
+
Write-Host "将加载最新宿主: $($latest.Name)" -ForegroundColor Gray
|
|
51
|
+
Write-Host ''
|
|
52
|
+
Write-Host '下一步:用桥接器注册(推荐,不需要点鼠标):' -ForegroundColor Cyan
|
|
53
|
+
$json = '{"id":"i","op":"install","args":{"script":"' + ($target -replace '\\','\\\\') + '"}}'
|
|
54
|
+
Write-Host " native\bridge\bin\EplanBridge.exe --once '$json'"
|
|
55
|
+
Write-Host ''
|
|
56
|
+
Write-Host '注意:EPLAN 里「运行脚本」走的是 ExecuteScript,只执行 [Start],**不注册** [DeclareAction]。' -ForegroundColor DarkGray
|
|
57
|
+
Write-Host ' 要注册动作必须用 RegisterScript(桥接器的 install 操作就是干这个)。' -ForegroundColor DarkGray
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 清临时目录。
|
|
3
|
+
//
|
|
4
|
+
// %TEMP%\eplan-mcp 下三类东西一直是只增不减的:
|
|
5
|
+
// look\ 每次渲染一张 PNG;
|
|
6
|
+
// pdf\ 手册页面渲染出来的图,单个会话就能攒出几 MB;
|
|
7
|
+
// backups\ 旧版本写操作前复制的 .elk —— 那玩意儿只有 30 字节(真正数据在 .edb),
|
|
8
|
+
// 从来就不是备份,纯粹是垃圾。新版本已经不再产生它。
|
|
9
|
+
//
|
|
10
|
+
// ops\ 不动:那是 operation_rollback 的依据,按时间删等于毁掉回退能力。
|
|
11
|
+
// knowledge\ 不在临时目录(已迁到 %LOCALAPPDATA%),也不可能被这里扫到。
|
|
12
|
+
//
|
|
13
|
+
// node native/script/prune.mjs 按默认策略清
|
|
14
|
+
// node native/script/prune.mjs --dry-run 只报会删什么
|
|
15
|
+
// node native/script/prune.mjs --keep 50 改保留数量
|
|
16
|
+
import { existsSync, readdirSync, rmSync, statSync } from 'node:fs'
|
|
17
|
+
import { join } from 'node:path'
|
|
18
|
+
import { tmpdir } from 'node:os'
|
|
19
|
+
|
|
20
|
+
const args = process.argv.slice(2)
|
|
21
|
+
const dryRun = args.includes('--dry-run')
|
|
22
|
+
const keepIndex = args.indexOf('--keep')
|
|
23
|
+
const keep = keepIndex >= 0 ? Number(args[keepIndex + 1]) : 200
|
|
24
|
+
|
|
25
|
+
const root = join(tmpdir(), 'eplan-mcp')
|
|
26
|
+
const pruneReport = []
|
|
27
|
+
|
|
28
|
+
function sizeOf(path) {
|
|
29
|
+
try {
|
|
30
|
+
const stat = statSync(path)
|
|
31
|
+
return stat.isDirectory() ? 0 : stat.size
|
|
32
|
+
} catch {
|
|
33
|
+
return 0
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// 目录里文件太多时,按修改时间从旧到新删,直到只剩 keep 个。
|
|
38
|
+
function trimDir(name) {
|
|
39
|
+
const dir = join(root, name)
|
|
40
|
+
if (!existsSync(dir)) return
|
|
41
|
+
|
|
42
|
+
let entries
|
|
43
|
+
try {
|
|
44
|
+
entries = readdirSync(dir)
|
|
45
|
+
.map((entry) => ({ entry, path: join(dir, entry), time: statSync(join(dir, entry)).mtimeMs }))
|
|
46
|
+
.filter((item) => {
|
|
47
|
+
try {
|
|
48
|
+
return statSync(item.path).isFile()
|
|
49
|
+
} catch {
|
|
50
|
+
return false
|
|
51
|
+
}
|
|
52
|
+
})
|
|
53
|
+
.sort((a, b) => a.time - b.time)
|
|
54
|
+
} catch {
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const excess = entries.slice(0, Math.max(0, entries.length - keep))
|
|
59
|
+
let freed = 0
|
|
60
|
+
for (const item of excess) {
|
|
61
|
+
freed += sizeOf(item.path)
|
|
62
|
+
if (!dryRun) {
|
|
63
|
+
try {
|
|
64
|
+
rmSync(item.path, { force: true })
|
|
65
|
+
} catch {
|
|
66
|
+
// 正在被别的进程读着就跳过,下次再说。
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
pruneReport.push({
|
|
71
|
+
dir,
|
|
72
|
+
total: entries.length,
|
|
73
|
+
removed: excess.length,
|
|
74
|
+
freedBytes: freed,
|
|
75
|
+
...(dryRun ? { dryRun: true } : {}),
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// backups 是历史遗留:整个目录清掉,新版本不会再往里写。
|
|
80
|
+
function dropLegacyBackups() {
|
|
81
|
+
const dir = join(root, 'backups')
|
|
82
|
+
if (!existsSync(dir)) return
|
|
83
|
+
let count = 0
|
|
84
|
+
let freed = 0
|
|
85
|
+
try {
|
|
86
|
+
for (const entry of readdirSync(dir)) {
|
|
87
|
+
const path = join(dir, entry)
|
|
88
|
+
freed += sizeOf(path)
|
|
89
|
+
count += 1
|
|
90
|
+
if (!dryRun) {
|
|
91
|
+
try {
|
|
92
|
+
rmSync(path, { force: true })
|
|
93
|
+
} catch {}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (!dryRun && count > 0) {
|
|
97
|
+
try {
|
|
98
|
+
rmSync(dir, { recursive: true, force: true })
|
|
99
|
+
} catch {}
|
|
100
|
+
}
|
|
101
|
+
} catch {
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
pruneReport.push({
|
|
105
|
+
dir,
|
|
106
|
+
total: count,
|
|
107
|
+
removed: count,
|
|
108
|
+
freedBytes: freed,
|
|
109
|
+
legacy: true,
|
|
110
|
+
...(dryRun ? { dryRun: true } : {}),
|
|
111
|
+
})
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
trimDir('look')
|
|
115
|
+
trimDir('pdf')
|
|
116
|
+
dropLegacyBackups()
|
|
117
|
+
|
|
118
|
+
const freedTotal = pruneReport.reduce((sum, item) => sum + item.freedBytes, 0)
|
|
119
|
+
process.stdout.write(
|
|
120
|
+
`${JSON.stringify(
|
|
121
|
+
{
|
|
122
|
+
root,
|
|
123
|
+
keep,
|
|
124
|
+
dryRun,
|
|
125
|
+
freedBytes: freedTotal,
|
|
126
|
+
details: pruneReport,
|
|
127
|
+
untouched: ['ops(回退依据,不按时间删)'],
|
|
128
|
+
},
|
|
129
|
+
null,
|
|
130
|
+
2,
|
|
131
|
+
)}\n`,
|
|
132
|
+
)
|