dsh-eplan 0.0.0-stage → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -3
  3. package/cordis.patch.yml +182 -0
  4. package/docs/INSTALL.md +86 -0
  5. package/docs/LESSONS.md +224 -0
  6. package/docs/interfaces.md +183 -0
  7. package/docs/merged-skills/eplan-setup.md +63 -0
  8. package/docs/merged-skills/eplan-troubleshooting.md +149 -0
  9. package/icon.png +0 -0
  10. package/icon.svg +13 -0
  11. package/knowledge/KNOWLEDGE.md +413 -0
  12. package/knowledge/symbols/BP.png +0 -0
  13. package/knowledge/symbols/CDPST.png +0 -0
  14. package/knowledge/symbols/CO.png +0 -0
  15. package/knowledge/symbols/FA3.png +0 -0
  16. package/knowledge/symbols/TLRO.png +0 -0
  17. package/knowledge/symbols/TLRU.png +0 -0
  18. package/knowledge/symbols/TOUL.png +0 -0
  19. package/knowledge/symbols/TOUR.png +0 -0
  20. package/knowledge/symbols/manifest.json +91 -0
  21. package/locale/en.json +6 -0
  22. package/locale/zh.json +6 -0
  23. package/native/bridge/build.ps1 +73 -0
  24. package/native/bridge/src/Json.cs +383 -0
  25. package/native/bridge/src/Program.cs +1133 -0
  26. package/native/host/build.ps1 +74 -0
  27. package/native/host/src/ActionsTool.cs +225 -0
  28. package/native/host/src/BoxTool.cs +196 -0
  29. package/native/host/src/CheckTool.cs +186 -0
  30. package/native/host/src/Context.cs +169 -0
  31. package/native/host/src/DarkScheme.cs +111 -0
  32. package/native/host/src/DiagnoseTool.cs +115 -0
  33. package/native/host/src/Dispatcher.cs +51 -0
  34. package/native/host/src/DrawTool.cs +316 -0
  35. package/native/host/src/Entry.cs +111 -0
  36. package/native/host/src/ExportTool.cs +213 -0
  37. package/native/host/src/InspectTool.cs +367 -0
  38. package/native/host/src/KnowledgeTool.cs +166 -0
  39. package/native/host/src/LookTool.cs +257 -0
  40. package/native/host/src/OpLog.cs +289 -0
  41. package/native/host/src/PageCreateTool.cs +521 -0
  42. package/native/host/src/PageOpenTool.cs +62 -0
  43. package/native/host/src/PagesTool.cs +95 -0
  44. package/native/host/src/Paths.cs +91 -0
  45. package/native/host/src/PlacementEditTool.cs +234 -0
  46. package/native/host/src/ProbePropsTool.cs +152 -0
  47. package/native/host/src/ProjectCreateTool.cs +176 -0
  48. package/native/host/src/ProjectTool.cs +167 -0
  49. package/native/host/src/PropWriter.cs +70 -0
  50. package/native/host/src/PropsTool.cs +257 -0
  51. package/native/host/src/StatusTool.cs +168 -0
  52. package/native/host/src/SymbolInfoTool.cs +144 -0
  53. package/native/host/src/SymbolInsertTool.cs +261 -0
  54. package/native/host/src/SymbolsTool.cs +94 -0
  55. package/native/host/src/TagLocTool.cs +108 -0
  56. package/native/script/EplanMcpBootstrap.cs +221 -0
  57. package/native/script/build-symbol-gallery.mjs +231 -0
  58. package/native/script/prepare-install.ps1 +57 -0
  59. package/native/script/prune.mjs +132 -0
  60. package/native/script/verify-bootstrap.ps1 +62 -0
  61. package/package.json +53 -4
  62. package/preset/bootstrap.js +498 -0
  63. package/preset/experience-nudge.js +47 -0
  64. package/preset/image-budget.js +175 -0
  65. package/preset/knowledge-tool.js +180 -0
  66. package/preset/mcp-link.js +100 -0
  67. package/preset/prompt-surface.js +76 -0
  68. package/preset/restrict-tools.js +141 -0
  69. package/preset/skill-docs.js +181 -0
  70. package/preset/video-digest.js +294 -0
  71. package/preset/video-tool.js +92 -0
  72. package/server/compact.mjs +623 -0
  73. package/server/edit-args.mjs +67 -0
  74. package/server/fuzzy.mjs +57 -0
  75. package/server/launch-decision.mjs +26 -0
  76. package/server/measure.mjs +320 -0
  77. package/server/pdf.mjs +185 -0
  78. package/server/pdf2png.ps1 +99 -0
  79. package/server/server.mjs +3797 -0
  80. package/server/video.mjs +857 -0
  81. package/setup.mjs +223 -0
  82. package/skills/eplan-annotations/SKILL.md +55 -0
  83. package/skills/eplan-drawing/SKILL.md +206 -0
  84. package/skills/eplan-project/SKILL.md +41 -0
  85. package/skills/eplan-review/SKILL.md +80 -0
  86. package/skills/eplan-symbols/SKILL.md +142 -0
  87. package/test/check-docs.mjs +106 -0
  88. package/test/foreground.ps1 +21 -0
  89. package/test/smoke-all.mjs +229 -0
@@ -0,0 +1,175 @@
1
+ /**
2
+ * 一步最多能带几张图:在工具这一层自己守住,别等模型服务端 400。
3
+ *
4
+ * 实测(2026-11-16,session-a24d40d3):deepseek-v4.1-flash 在一条 assistant 消息之后
5
+ * 最多接受 8 张新图。那次模型在同一步里先 video(maxFrames:8)、再 video(maxFrames:12),
6
+ * 20 张一起进请求,整轮直接 INVALID_REQUEST —— 程序白跑,用户只看到红字报错。
7
+ *
8
+ * 这个插件在 tools/post-execute 里数图,两条通路一起盖:
9
+ * - decision.content:普通工具结果里的图片块;
10
+ * - decision.additionalContexts:PTC 子调用(video 等)的图,会另起一条 user 消息进下一轮。
11
+ * 每出现一条 step/start 就清零:服务端窗口是「最后一条 assistant 消息之后」,而每个 step
12
+ * 就是一次新的请求。超额的图就地换成一行文字(原图路径 + 怎么看)—— 图本来已经落盘,
13
+ * 换文字不丢信息,只是让模型下一轮用 read_image 单独看,比整轮失败好得多。
14
+ *
15
+ * 计数宁可偏严:子调用和顶层结果各记一次时,模型拿到的图更少但不会报错,
16
+ * 而且每条被换掉的图都带着路径,下一轮补得回来。
17
+ *
18
+ * 为什么在工具层而不是提示词里:提示词只能说「别多调」,管不住模型真的调两次;
19
+ * 这里按实际返回的图片块计数,任何来源(MCP、原生工具、子代理)都盖得住。
20
+ */
21
+
22
+ export const name = 'eplan-image-budget'
23
+
24
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
25
+ import { homedir } from 'node:os'
26
+ import { join } from 'node:path'
27
+
28
+ /** 一步里实际可以放进上下文的图片上限。8 是服务端硬限制,留 2 张余量给用户自己贴的图。 */
29
+ const BUDGET = 6
30
+
31
+ /** 附件 → 宿主路径 → 执行世界路径。缺服务时只给提示文字,不当成失败。 */
32
+ function imagePath(ctx, block) {
33
+ try {
34
+ const attachments = ctx.get('attachments')
35
+ const fsService = ctx.get('fs')
36
+ if (typeof attachments?.imageHostPath !== 'function') return undefined
37
+ if (typeof fsService?.processPathFromHostPath !== 'function') return undefined
38
+ const host = attachments.imageHostPath(block.attachment)
39
+ if (host === undefined) return undefined
40
+ return fsService.processPathFromHostPath(host)
41
+ } catch {
42
+ return undefined
43
+ }
44
+ }
45
+
46
+ /**
47
+ * 给用户/模型一个**带 .png 后缀**的副本路径。
48
+ *
49
+ * 附件仓库里的对象是 sha256 名字、没有扩展名:Windows 双击打不开,
50
+ * 图片查看器和聊天界面预览也认不出(2026-11-16 用户反馈「这是无格式的文件」)。
51
+ * 所以抄一份到 eplan-mcp\images\ 下,按 mediaType 补后缀。
52
+ */
53
+ function visibleCopy(ctx, block) {
54
+ const source = imagePath(ctx, block)
55
+ if (!source) return undefined
56
+ try {
57
+ const dir = join(configDir(), 'images')
58
+ mkdirSync(dir, { recursive: true })
59
+ const mediaType = block.attachment?.mediaType ?? 'image/png'
60
+ const ext = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '.webp', 'image/gif': '.gif' }[mediaType] ?? '.png'
61
+ const id = String(block.attachment?.attachmentId ?? Date.now()).replace(/^sha256:/, '').slice(0, 16)
62
+ const target = join(dir, `budget-${id}${ext}`)
63
+ if (!existsSync(target)) writeFileSync(target, readFileSync(source))
64
+ return target
65
+ } catch {
66
+ return undefined
67
+ }
68
+ }
69
+
70
+ /** 和 server.mjs 用同一个配置目录:%LOCALAPPDATA%\eplan-mcp。 */
71
+ function configDir() {
72
+ const base = process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')
73
+ return join(base, 'eplan-mcp')
74
+ }
75
+
76
+ function omission(ctx, block, ordinal) {
77
+ const path = visibleCopy(ctx, block)
78
+ const where = path
79
+ ? `原图已另存为 ${path}`
80
+ : '原图这一轮没取出来'
81
+ return {
82
+ type: 'text',
83
+ text: `[第 ${ordinal} 张图没放进上下文:一步最多 ${BUDGET} 张。${where};要看就用 read_image 打开这个 .png,或下一轮再取。]`,
84
+ }
85
+ }
86
+
87
+ const isImage = (block) => block?.type === 'image'
88
+ const hasImage = (blocks) => Array.isArray(blocks) && blocks.some(isImage)
89
+
90
+ export function apply(ctx) {
91
+ if (typeof ctx.on !== 'function') return
92
+
93
+ /** sessionId → 本步已放行的图片数。 */
94
+ const spent = new Map()
95
+ /** sessionId → 本步开始前(pre-step 注入)已经塞进消息里的图片数。 */
96
+ const pendingPreStep = new Map()
97
+ const keyOf = (session) => {
98
+ const id = session?.header?.id ?? session?.id
99
+ return id === undefined ? 'unknown' : String(id)
100
+ }
101
+
102
+ const countImages = (messages) => (messages ?? []).reduce(
103
+ (sum, message) => sum + (Array.isArray(message?.content) ? message.content.filter(isImage).length : 0),
104
+ 0,
105
+ )
106
+
107
+ // 视频摘要是在 pre-step 里直接把图塞进消息的(video-digest.js),不经过工具结果,
108
+ // 所以要在这里先记上,否则「摘要 4 张 + focus 4 张」= 8 张刚好顶满服务端上限,再来一张就 400。
109
+ // prepend:true 让它排在 video-digest 外层,next() 回来时已经能看到注入后的消息。
110
+ ctx.on('agent/pre-step', async (payload, next) => {
111
+ const decision = await next()
112
+ if (decision?.kind !== 'enter') return decision
113
+ pendingPreStep.set(keyOf(payload?.agent?.session), countImages(decision.messages))
114
+ return decision
115
+ }, { prepend: true })
116
+
117
+ ctx.on('session/event', (session, event) => {
118
+ if (event?.type !== 'step/start') return
119
+ // pre-step 在 step/start 之前跑,所以这里才把「已经发出去的图」记进本步额度。
120
+ const key = keyOf(session)
121
+ const carried = pendingPreStep.get(key) ?? 0
122
+ pendingPreStep.delete(key)
123
+ if (carried > 0) spent.set(key, carried)
124
+ else spent.delete(key)
125
+ })
126
+
127
+ ctx.on('tools/post-execute', async (exec, result, next) => {
128
+ const decision = await next()
129
+ // 只有 accept 且真的带了 content 数组才动;带 value 的决策以值为准,改 content 没用。
130
+ if (decision?.kind !== 'accept' || !Array.isArray(decision.content)) return decision
131
+
132
+ const content = decision.content
133
+ const contexts = Array.isArray(decision.additionalContexts) ? decision.additionalContexts : []
134
+ if (!hasImage(content) && !contexts.some((message) => hasImage(message?.content))) {
135
+ return decision
136
+ }
137
+
138
+ const key = keyOf(exec?.agent?.session)
139
+ const used = spent.get(key) ?? 0
140
+ let budget = BUDGET - used
141
+ let kept = 0
142
+ let dropped = 0
143
+
144
+ const rewrite = (blocks) => blocks.map((block) => {
145
+ if (!isImage(block)) return block
146
+ if (budget > 0) {
147
+ budget -= 1
148
+ kept += 1
149
+ return block
150
+ }
151
+ dropped += 1
152
+ return omission(ctx, block, kept + dropped)
153
+ })
154
+
155
+ // 先算再判断:改动只有一次,kept / dropped 也只在这次改写里累加。
156
+ const rewrittenContent = hasImage(content) ? rewrite(content) : content
157
+ const rewrittenContexts = contexts.map((message) => (
158
+ hasImage(message?.content) ? { ...message, content: rewrite(message.content) } : message
159
+ ))
160
+
161
+ // 顶层结果与 PTC 子调用的图会分别经过这里,同一步里累计。计数偏严不会报错。
162
+ spent.set(key, used + kept)
163
+
164
+ if (dropped === 0) return decision
165
+
166
+ ctx.logger?.info?.(
167
+ `eplan: ${exec.name} 返回 ${kept + dropped} 张图,本步只剩 ${kept} 张额度,其余换成路径文字`,
168
+ )
169
+ return {
170
+ ...decision,
171
+ content: rewrittenContent,
172
+ ...(contexts.length > 0 ? { additionalContexts: rewrittenContexts } : {}),
173
+ }
174
+ })
175
+ }
@@ -0,0 +1,180 @@
1
+ // 经验手册:一份按关键词查的 Markdown,模型用 `manual` 一样的检索而不是把全文塞进上下文。
2
+ //
3
+ // 为什么要做成工具而不是技能文档:
4
+ // 技能文档是「按需加载的一整段指令」,一加载就是几千字;而排错时模型要的是
5
+ // 「这个错误码怎么办」那一条。所以这里做成检索,只回命中的条目。
6
+ //
7
+ // 为什么和技能分开:
8
+ // 技能文档(skills/)回答「怎么画」,这份手册回答「出错了怎么办、这机器怎么装」。
9
+ // 两者都按需加载,但检索粒度不同:技能整篇读,手册按条命中。
10
+ //
11
+ // 文件格式(knowledge/KNOWLEDGE.md):
12
+ // ## 条目标题
13
+ //
14
+ // 关键词: 逗号, 分隔, 的, 词
15
+ //
16
+ // ...正文...
17
+ import { existsSync, readFileSync } from 'node:fs'
18
+ import { dirname, join, resolve } from 'node:path'
19
+ import { fileURLToPath } from 'node:url'
20
+
21
+ export const name = 'eplan-knowledge'
22
+
23
+ export const inject = ['tools']
24
+
25
+ const here = dirname(fileURLToPath(import.meta.url))
26
+ const KNOWLEDGE_FILE = join(here, '..', 'knowledge', 'KNOWLEDGE.md')
27
+
28
+ /** 一条经验条目:标题 + 关键词 + 正文。 */
29
+ function parseEntries(text) {
30
+ const lines = text.split(/\r?\n/)
31
+ const entries = []
32
+ let current = null
33
+ let inFence = false
34
+ for (const raw of lines) {
35
+ // 代码块里的 ## 不算标题。
36
+ if (/^\s*```/.test(raw)) inFence = !inFence
37
+ const heading = !inFence && /^##\s+(.+?)\s*$/.exec(raw)
38
+ if (heading) {
39
+ if (current) entries.push(current)
40
+ current = { title: heading[1], keywords: [], body: [] }
41
+ continue
42
+ }
43
+ if (!current) continue
44
+ const kw = /^\s*关键词[::]\s*(.*)$/.exec(raw)
45
+ if (kw && current.keywords.length === 0) {
46
+ current.keywords = kw[1]
47
+ .split(/[,,、;;]/)
48
+ .map((word) => word.trim())
49
+ .filter(Boolean)
50
+ continue
51
+ }
52
+ current.body.push(raw)
53
+ }
54
+ if (current) entries.push(current)
55
+ return entries
56
+ .map((entry) => ({ ...entry, body: entry.body.join('\n').replace(/^\s*\n+|\n+\s*$/g, '') }))
57
+ .filter((entry) => entry.body.length > 0 || entry.keywords.length > 0)
58
+ }
59
+
60
+ let cache = null
61
+ function loadEntries() {
62
+ if (cache) return cache
63
+ if (!existsSync(KNOWLEDGE_FILE)) return []
64
+ try {
65
+ cache = parseEntries(readFileSync(KNOWLEDGE_FILE, 'utf8'))
66
+ } catch {
67
+ cache = []
68
+ }
69
+ return cache
70
+ }
71
+
72
+ /** 命中打分:标题命中权重最高,关键词次之,正文最低。 */
73
+ function score(entry, terms) {
74
+ const title = entry.title.toLowerCase()
75
+ const keywords = entry.keywords.join(' ').toLowerCase()
76
+ const body = entry.body.toLowerCase()
77
+ let total = 0
78
+ for (const term of terms) {
79
+ if (title.includes(term)) total += 6
80
+ if (entry.keywords.some((word) => word.toLowerCase().includes(term))) total += 4
81
+ if (body.includes(term)) total += 1
82
+ }
83
+ return total
84
+ }
85
+
86
+ function search(query, limit) {
87
+ const entries = loadEntries()
88
+ const text = String(query ?? '').trim()
89
+ if (text.length === 0) {
90
+ return { query: text, total: entries.length, returned: 0, entries: [] }
91
+ }
92
+ // 整串先当一次;再按空白/标点切词,让「HOST_NOT_INSTALLED 装不上」这种混合查询也能中。
93
+ const terms = [...new Set([text.toLowerCase(), ...text.toLowerCase().split(/[\s,,、;;()()/]+/).filter(Boolean)])]
94
+ const ranked = entries
95
+ .map((entry) => ({ entry, score: score(entry, terms) }))
96
+ .filter((row) => row.score > 0)
97
+ .sort((a, b) => b.score - a.score)
98
+ return {
99
+ query: text,
100
+ total: entries.length,
101
+ returned: Math.min(ranked.length, limit),
102
+ entries: ranked.slice(0, limit).map((row) => ({
103
+ title: row.entry.title,
104
+ keywords: row.entry.keywords,
105
+ body: row.entry.body,
106
+ })),
107
+ }
108
+ }
109
+
110
+ /** 目录:只回标题和关键词,方便看全貌再决定查哪条。 */
111
+ function outline() {
112
+ const entries = loadEntries()
113
+ return {
114
+ total: entries.length,
115
+ entries: entries.map((entry) => ({ title: entry.title, keywords: entry.keywords })),
116
+ }
117
+ }
118
+
119
+ export function apply(ctx) {
120
+ ctx.tools.register({
121
+ // 名字叫 handbook 而不是 manual:`manual` 已经是 MCP 那个「读 PDF 手册」的工具,
122
+ // 同名会互相顶掉(scoped 注册覆盖 global 的话,读手册的能力就静默消失了)。
123
+ name: 'handbook',
124
+ description: [
125
+ '经验手册:按关键词查「踩过的坑、错误码怎么处理、这台机器怎么装、某个现象是什么原因」。',
126
+ '',
127
+ 'action="search"(默认):传 query,只回命中的条目(最多 limit 条),不占整篇的上下文。',
128
+ 'action="section":传 title,取回某一条的完整正文。',
129
+ 'action="outline":只列全部条目的标题和关键词,用来先看有什么。',
130
+ '',
131
+ '什么时候该查:任何工具返回了你不认识的错误码、调用卡住不返回、画出来和预期不一样、',
132
+ '要确认某个参数或动作名的正确写法。先查这里,比试探性重试便宜得多。',
133
+ '查不到再走技能文档或问用户。',
134
+ ].join(''),
135
+ parameters: {
136
+ type: 'object',
137
+ additionalProperties: false,
138
+ required: ['action'],
139
+ properties: {
140
+ action: {
141
+ type: 'string',
142
+ enum: ['search', 'section', 'outline'],
143
+ description: 'search 按关键词查;section 取一条全文;outline 列全部标题。',
144
+ },
145
+ query: { type: 'string', description: 'search 的关键词,可以是错误码、动作名、中文现象描述,空格分隔多个。' },
146
+ title: { type: 'string', description: 'section 的条目标题(来自 search 或 outline 的 title)。' },
147
+ limit: { type: 'integer', description: 'search 最多回几条,默认 3,上限 8。' },
148
+ },
149
+ },
150
+ output: {
151
+ schema: { type: 'object' },
152
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
153
+ },
154
+ async execute(args) {
155
+ const entries = loadEntries()
156
+ if (entries.length === 0) {
157
+ return { ok: false, message: '经验手册还没生成(knowledge/KNOWLEDGE.md 不存在)。' }
158
+ }
159
+ if (args.action === 'outline') return outline()
160
+ if (args.action === 'section') {
161
+ const wanted = String(args.title ?? '').trim().toLowerCase()
162
+ const hit = entries.find((entry) => entry.title.toLowerCase() === wanted)
163
+ ?? entries.find((entry) => entry.title.toLowerCase().includes(wanted))
164
+ if (!hit) return { ok: false, message: `没有标题为「${args.title}」的条目。用 action="outline" 看全部标题。` }
165
+ return { title: hit.title, keywords: hit.keywords, body: hit.body }
166
+ }
167
+ const limit = Math.min(Math.max(Number(args.limit) || 3, 1), 8)
168
+ const result = search(args.query, limit)
169
+ return result.returned === 0
170
+ ? { ...result, hint: '没有命中。换成更短的关键词(错误码 / 动作名 / 一个名词),或用 action="outline" 看全部标题。' }
171
+ : result
172
+ },
173
+ })
174
+ }
175
+
176
+ /** 测试用:直接暴露解析结果,别让测试自己去读文件格式。 */
177
+ export const __testing = { parseEntries, search, outline, KNOWLEDGE_FILE: resolve(KNOWLEDGE_FILE) }
178
+
179
+ /** 工具名同时被测试与文档引用,导出一份避免抄错。 */
180
+ export const TOOL_NAME = 'handbook'
@@ -0,0 +1,100 @@
1
+ /**
2
+ * EPLAN MCP 的挂载层:把 server/server.mjs 接到 DSH 的 MCP 客户端上。
3
+ *
4
+ * 为什么不是一个 static 的 @deepseek-ai/dsh-mcp-client 行:
5
+ * MCP 客户端要的是「可执行文件 + 参数」的绝对路径,而包装到哪台机器、哪个目录
6
+ * 是装的时候才知道的。写死在 cordis.patch.yml 里就只有作者那台机器能跑。
7
+ * 这里在装配时按 __dirname 算出自己的路径,再用 ctx.plugin 把 MCP 客户端挂上,
8
+ * 于是 link: 装、github: 装、npm 装都是同一份配置。
9
+ *
10
+ * 顺带解决另一个问题:node 解释器。桌面版 DSH 的 process.execPath 是
11
+ * DeepSeek Harness.exe(Electron),当 node 用需要 ELECTRON_RUN_AS_NODE=1;
12
+ * 而装了 Node.js 的机器直接用 node.exe 更省事。两种都能处理,见 resolveNode()。
13
+ */
14
+ import { existsSync } from 'node:fs'
15
+ import { dirname, join } from 'node:path'
16
+ import { fileURLToPath } from 'node:url'
17
+
18
+ export const name = 'eplan-mcp-link'
19
+
20
+ // 不在这里静态 import @deepseek-ai/dsh-mcp-client:那样解析失败会让**整个模块**
21
+ // 加载失败,预设里挂在这一行上的一切跟着消失,用户看到的是「这个模式不见了」。
22
+ // 改成 apply 里动态 import 并且吞掉失败:最坏情况是 EPLAN 工具没挂上,
23
+ // 预设本身照常出现,日志里有一行能看懂的原因。
24
+ const MCP_CLIENT = '@deepseek-ai/dsh-mcp-client'
25
+
26
+ const here = dirname(fileURLToPath(import.meta.url))
27
+
28
+ /** PATH 里第一个能用的 node,找不到就返回 null。 */
29
+ function nodeOnPath() {
30
+ const paths = (process.env.PATH ?? '').split(';').filter(Boolean)
31
+ const names = process.platform === 'win32' ? ['node.exe'] : ['node']
32
+ for (const dir of paths) {
33
+ for (const name of names) {
34
+ const candidate = join(dir, name)
35
+ try {
36
+ if (existsSync(candidate)) return candidate
37
+ } catch {
38
+ // PATH 里可能有读不了的目录,跳过。
39
+ }
40
+ }
41
+ }
42
+ return null
43
+ }
44
+
45
+ /**
46
+ * 选一个能跑 server.mjs 的解释器。
47
+ * 返回 { command, env }:env 只放「必须多给的环境变量」,不整份复制 process.env,
48
+ * 交给 MCP 客户端自己决定怎么合并(它默认继承父进程环境)。
49
+ */
50
+ function resolveNode() {
51
+ const explicit = process.env.EPLAN_MCP_NODE
52
+ if (explicit && existsSync(explicit)) return { command: explicit, env: {} }
53
+
54
+ // 常规 node 进程(dsh 从命令行起的):execPath 本身就是 node。
55
+ const exe = process.execPath
56
+ if (exe && /[\\/]node(\.exe)?$/i.test(exe)) return { command: exe, env: {} }
57
+
58
+ const fromPath = nodeOnPath()
59
+ if (fromPath) return { command: fromPath, env: {} }
60
+
61
+ // 最后一条路:Electron 自带的 node。--remote 之外只需要这个开关。
62
+ return { command: exe, env: { ELECTRON_RUN_AS_NODE: '1' } }
63
+ }
64
+
65
+ export async function apply(ctx) {
66
+ const server = join(here, '..', 'server', 'server.mjs')
67
+ if (!existsSync(server)) {
68
+ process.stderr.write(`[eplan] 缺少 MCP 服务端 ${server}(包装坏了?重装一次 dsh-eplan)\n`)
69
+ return
70
+ }
71
+
72
+ let McpClient
73
+ try {
74
+ McpClient = await import(MCP_CLIENT)
75
+ } catch (error) {
76
+ // 预设本身必须还能用:这里只少一组工具,不是少一个模式。
77
+ process.stderr.write(
78
+ `[eplan] 挂不上 MCP 客户端(${MCP_CLIENT}): ${error instanceof Error ? error.message : String(error)}\n` +
79
+ `[eplan] EPLAN 工具这次不可用;预设其它部分照常。检查 DSH 版本是否与 peerDependencies 匹配。\n`,
80
+ )
81
+ return
82
+ }
83
+
84
+ const { command, env } = resolveNode()
85
+
86
+ ctx.plugin(McpClient, {
87
+ serverName: 'eplan',
88
+ transport: 'stdio',
89
+ command,
90
+ args: [server],
91
+ ...(Object.keys(env).length > 0 ? { env } : {}),
92
+ // 一张复杂页的 validate / 出图能跑几分钟,默认 60 秒会误杀。
93
+ toolCallTimeoutMs: 300000,
94
+ // EPLAN 没开会连不上:这里不抛,让预设照常起来,由 workspace(status)
95
+ // 给「EPLAN 没在运行,先跑 node setup.mjs」这类可执行的提示。
96
+ failOnStartupError: false,
97
+ })
98
+
99
+ process.stderr.write(`[eplan] MCP 服务端: ${server}\n[eplan] 解释器: ${command}\n`)
100
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * 系统提示词的收敛层:把宿主注入的、与绘图无关的段落全部遮掉,只留这个模式真正需要的一份。
3
+ *
4
+ * 部署时系统提示词由三层拼起来:
5
+ * 1. 宿主基座(身份、通用工具说明、交付约定、运行时上下文…)
6
+ * 2. PTC 执行器(「run_code 是唯一能直接调的工具」+ 整份 SDK 声明)
7
+ * 3. 本预设(persona 散文 + 下面这些供给)
8
+ *
9
+ * 第 1 层里有大量与本模式无关、且会直接暴露实现细节的段落。用户看到的是模型复述出来的
10
+ * 那些句子,所以要按 section 名逐条遮蔽,而不是「大致删一删」。
11
+ *
12
+ * 遮蔽方式:注册同名空 section。文本为空时 renderPrompt 会整段丢掉;
13
+ * 遮蔽必须在同一作用域内、且名字与宿主注册的一致。
14
+ *
15
+ * 保留:tool:read(本模式确实挂 read)、tool:subagent、tool:goal、tool:ask_user_question。
16
+ * 遮掉:所有终端/web/job/workflow/skill 相关的通用说明、运行时上下文的内外路径说明、
17
+ * 以及「交付文件链接」这类纯样式约定。
18
+ */
19
+
20
+ export const name = 'eplan-prompt-surface'
21
+
22
+ export const inject = ['systemPrompt']
23
+
24
+ /**
25
+ * [section 名, SECTION_ORDERS 键] —— 两者都必须是宿主真实注册过的名字。
26
+ * 拿不到 order 就跳过,不让一条遮蔽失败拖垮整个预设。
27
+ */
28
+ const SHADOWED = [
29
+ // 身份:本模式有自己的身份,不要那条通用的「AI agent powered by ...」。
30
+ ['harness:identity', 'HARNESS_IDENTITY'],
31
+ // 宿主没有挂这些工具,通用说明只会把模型引向不存在的能力。
32
+ ['tool:bash', 'TOOL_BASH'],
33
+ ['tool:pwsh', 'TOOL_PWSH'],
34
+ ['tool:glob', 'TOOL_GLOB'],
35
+ ['tool:grep', 'TOOL_GREP'],
36
+ ['tool:jobs', 'TOOL_JOBS'],
37
+ ['tool:web-search', 'TOOL_WEB_SEARCH'],
38
+ ['tool:web-fetch', 'TOOL_WEB_FETCH'],
39
+ ['tool:workflow', 'TOOL_WORKFLOW'],
40
+ ['tool:report', 'TOOL_REPORT'],
41
+ // 交付文件的链接样式约定:本模式交付的是图,不是文件清单。
42
+ ['deliverables:file-references', 'DELIVERABLE_FILE_REFERENCES'],
43
+ ]
44
+
45
+ export function apply(ctx) {
46
+ const sp = ctx.systemPrompt
47
+
48
+ for (const [section, key] of SHADOWED) {
49
+ try {
50
+ const order = sp.getSectionOrder(key)
51
+ if (typeof order !== 'number') {
52
+ ctx.logger?.warn?.(`eplan: no section order for ${key}, skip ${section}`)
53
+ continue
54
+ }
55
+ ctx.effect(
56
+ () => sp.section({ name: section, order, text: '', interpolate: false }),
57
+ `eplan: shadow ${section}`,
58
+ )
59
+ } catch (error) {
60
+ // 同层已有同名 section 时只告警,不让整个预设装配失败。
61
+ ctx.logger?.warn?.(
62
+ `eplan: cannot shadow ${section}: ${error instanceof Error ? error.message : String(error)}`,
63
+ )
64
+ }
65
+ }
66
+
67
+ // 运行时上下文(工作目录/沙箱策略/审批策略/源目录/GUI 地址)逐条遮掉:
68
+ // 这些值对绘图没有用,而「实现 checkout」和「Web GUI URL」两行纯粹是漏信息。
69
+ // suppressRuntimeContext 只影响可选上下文,必需注册的会被 refreshContext 恢复,
70
+ // 所以这里再补一层 per-context 空文本。
71
+ try {
72
+ ctx.effect(() => sp.suppressRuntimeContext(), 'eplan: suppress runtime context')
73
+ } catch (error) {
74
+ ctx.logger?.warn?.(`eplan: suppressRuntimeContext failed: ${String(error?.message ?? error)}`)
75
+ }
76
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * 把用不到的工具从作用域里遮掉,只留 EPLAN 需要的那一小组。
3
+ *
4
+ * 为什么要单独挂一行插件:bash/pwsh 的安装器、工作目录、MCP 资源、goal 的创建工具
5
+ * 都是 profile / host 级注册的;预设内部没法在 cordis.patch.yml 里逐条声明「不要」,
6
+ * 只能在 preset 自己的作用域里用 tools.restrict 遮。
7
+ *
8
+ * 为什么要在三个时机各扫一遍:
9
+ * - apply 期:遮掉已经注册的(基础工具、pwsh7 安装器等);
10
+ * - agent/created:子 agent 装配前再补一次;
11
+ * - turn/start:bili(billion-context)的 acp_* / decompress / search_context
12
+ * 是在 proxy ready 之后才 tools.register 的,apply 时它们还不存在。
13
+ * 老版本只在 apply 期点名这四个名字 → tools.restrict 抛 unknown global tool →
14
+ * 这里把未知名字剔掉后 deny 变空 → 整次调用静默失效,一条限制都没盖上。
15
+ * 实测 EPLAN 会话的工具表因此漏到 31/32 条(2026-11-09 复盘)。
16
+ *
17
+ * PTC 模式下这条更重要:SDK 声明是从「作用域内可见工具」生成的,漏进来的工具
18
+ * 不只是多占提示词,还会变成 run_code 程序里可调用的绑定。
19
+ *
20
+ * 代价(必须写清楚):decompress 被遮之后,被压缩的内容模型再也取不回来。
21
+ * 所以压缩前要确认范围,宁可晚一点压,不要压了又想反悔。
22
+ */
23
+
24
+ export const name = 'eplan-restrict-tools';
25
+
26
+ export const inject = ['tools'];
27
+
28
+ /**
29
+ * 必须遮掉的宿主工具;遮不掉要报错,说明预设基线和本机环境对不上。
30
+ * 只放真正的宿主内核工具:working_directory 由 dsh-base 的 tool-working-directory 行提供。
31
+ *
32
+ * 下面三个是「可选 profile 插件」才提供的,精简 bundles / 关掉 primary runtime 时会消失,
33
+ * 不能当作基线(审计 M3):load_workspace_dependencies 由 dsh-web-app 门控在 desktop +
34
+ * DSH_PRIMARY_RUNTIME;pwsh7_install / pwsh7_status 来自 profile bundle dsh-win-pwsh7。
35
+ * 它们在 DENY_OPTIONAL 里照样会被遮,缺了只打 info,不报红。
36
+ */
37
+ const DENY_REQUIRED = ['working_directory'];
38
+
39
+ /** 可选遮掉:只列本 preset 不提供的名字;preset 自己注册的 read / read_image /
40
+ * ask_user_question / goal_* / subagent / video / handbook / MCP 工具不要列,否则会被一起遮掉。
41
+ * ⚠ `skill` 也不在 DENY 里:skill-docs.js 把绘图技能注册在本作用域,
42
+ * 遮掉 skill 工具就等于把按需加载技能的唯一入口关掉。
43
+ * bili 异步注册,没装或还没注册上都不算错。compress 不在里面,保留。 */
44
+ const DENY_OPTIONAL = [
45
+ 'edit', 'write', 'glob', 'grep', 'pwsh', 'workflow',
46
+ 'todo_write', 'present', 'plugin_manager',
47
+ 'schedule_create', 'schedule_list', 'schedule_view', 'schedule_edit',
48
+ 'team_task_create', 'team_task_list', 'team_task_get', 'team_task_update',
49
+ 'cordis_inspect_list', 'cordis_inspect_query',
50
+ 'load_workspace_dependencies', 'pwsh7_install', 'pwsh7_status',
51
+ 'subagent_fork', 'interrupt_agent', 'list_agents', 'send_message', 'wait_agent',
52
+ 'job_kill', 'job_list', 'job_output',
53
+ 'web_fetch', 'web_search',
54
+ 'ops_discover_tools', 'acp_status', 'acp_cache', 'decompress', 'search_context',
55
+ 'list_mcp_resources', 'list_mcp_resource_templates', 'read_mcp_resource'
56
+ ];
57
+
58
+ /** 测试用:导出真实清单,别让测试自己抄一份(抄过一次就跟不上插件了)。 */
59
+ export const DENY_LISTS = Object.freeze({
60
+ required: [...DENY_REQUIRED],
61
+ optional: [...DENY_OPTIONAL],
62
+ });
63
+
64
+ /**
65
+ * 从 restrict 的报错里取出它不认识的名字。
66
+ * 报错形如 `tools.restrict() names unknown global tool "a", "b"; known global
67
+ * tools: ...` —— 分号前就是全部未知名字。
68
+ */
69
+ const unknownNames = (error) => {
70
+ const text = error instanceof Error ? error.message : String(error);
71
+ if (!text.includes('names unknown global tool')) return [];
72
+ return [...text.split(';')[0].matchAll(/"([^"]+)"/g)].map((match) => match[1]);
73
+ };
74
+
75
+ export function apply(ctx) {
76
+ const tools = ctx.tools;
77
+ if (typeof tools?.restrict !== 'function') return;
78
+
79
+ const applied = new Set();
80
+ const missing = new Set();
81
+ const disposers = [];
82
+ let reportedRequired = false;
83
+ let reportedOptional = false;
84
+
85
+ const sweepDeny = () => {
86
+ const wanted = [...DENY_REQUIRED, ...DENY_OPTIONAL].filter((tool) => !applied.has(tool));
87
+ let deny = wanted;
88
+
89
+ // 一次报错只会指出「不认识的名字」;剔掉它们再试,直到没得可遮或本轮清空。
90
+ for (let round = 0; round < 2 && deny.length > 0; round += 1) {
91
+ try {
92
+ // 直接调、直接拿 disposer:包在 ctx.effect 里的话,restrict 抛出的
93
+ // 「unknown global tool」会被 Cordis 的 effect 通道吞掉,拿不到名字。
94
+ disposers.push(tools.restrict({ deny }));
95
+ for (const tool of deny) {
96
+ applied.add(tool);
97
+ missing.delete(tool);
98
+ }
99
+ deny = [];
100
+ } catch (error) {
101
+ const unknown = unknownNames(error);
102
+ if (unknown.length === 0) {
103
+ ctx.logger?.error?.(`eplan: tools.restrict failed: ${String(error?.message ?? error)}`);
104
+ return;
105
+ }
106
+ for (const tool of unknown) if (wanted.includes(tool)) missing.add(tool);
107
+ deny = deny.filter((tool) => !unknown.includes(tool));
108
+ }
109
+ }
110
+
111
+ if (!reportedRequired) {
112
+ const absent = DENY_REQUIRED.filter((tool) => missing.has(tool));
113
+ if (absent.length > 0) {
114
+ reportedRequired = true;
115
+ ctx.logger?.error?.(`eplan: required tool not available: ${absent.join(', ')}`);
116
+ }
117
+ }
118
+ if (!reportedOptional) {
119
+ const absent = [...missing].filter((tool) => !DENY_REQUIRED.includes(tool));
120
+ if (absent.length > 0) {
121
+ reportedOptional = true;
122
+ ctx.logger?.info?.(`eplan: optional deny not present (plugin absent?): ${absent.join(', ')}`);
123
+ }
124
+ }
125
+ };
126
+
127
+ sweepDeny();
128
+ ctx.on?.('agent/created', () => sweepDeny());
129
+ ctx.on?.('session/event', (session, event) => {
130
+ if (event?.type !== 'turn/start') return;
131
+ sweepDeny();
132
+ });
133
+
134
+ ctx.effect(() => () => {
135
+ for (const dispose of disposers.splice(0)) {
136
+ try {
137
+ dispose();
138
+ } catch {}
139
+ }
140
+ }, 'eplan: restrict tools');
141
+ }