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.
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,181 @@
1
+ // 按需加载的绘图技能:只在本预设作用域内可见,不和其它 skill 混在一起。
2
+ //
3
+ // 为什么不用文件系统技能目录:
4
+ // 文件系统 provider 扫的是 project / user / bundled 三个根,注册进去的技能会出现在
5
+ // **所有模式**的技能目录里 —— 那就是污染。这里改用 ctx.skills.register(),
6
+ // 它把技能登记到「调用上下文所在的层」;预设的插件挂在预设自己的作用域上,
7
+ // 所以登记结果只有本模式看得见。
8
+ //
9
+ // 为什么单独一个工具而不是复用经验手册:
10
+ // 两者都是按需加载,但粒度不同 —— 技能是「整篇读一遍照着做」(画法、符号语义、标注层次),
11
+ // 手册是「按关键词命中一条」(错误码、装机)。合并成一个大文件会让每次加载都带上无关内容。
12
+ //
13
+ // compaction 之后自动补回:压缩会把 skill 的正文从上下文里摘掉,模型于是「忘了怎么画」。
14
+ // 这里记住本会话加载过哪些技能,压缩结束时把它们的正文重新注入一次。
15
+ import { existsSync, readFileSync } from 'node:fs'
16
+ import { dirname, join } from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
18
+
19
+ export const name = 'eplan-skill-docs'
20
+
21
+ export const inject = ['skills', 'tools']
22
+
23
+ const here = dirname(fileURLToPath(import.meta.url))
24
+ const SKILL_ROOT = join(here, '..', 'skills')
25
+
26
+ /** 技能清单:名字即目录名,目录里是 SKILL.md。 */
27
+ const SKILLS = [
28
+ {
29
+ name: 'eplan-drawing',
30
+ title: '画法:从意图到坐标',
31
+ whenToUse: '开始摆元件之前;拿不准哪些是 EPLAN 的硬约束、哪些只是参考图的风格时。',
32
+ description:
33
+ '把「这张图要表达什么」变成能画进 EPLAN 的坐标:红线为什么自动生成、栅格怎么取、'
34
+ + '声明式布局怎么写、摆好没摆好怎么用数字判断,以及常见画法错误各自的后果。',
35
+ },
36
+ {
37
+ name: 'eplan-symbols',
38
+ title: '符号与引脚几何',
39
+ whenToUse: '选元件、查引脚坐标、判断两个引脚会不会自动连线、中文搜不到符号时。',
40
+ description:
41
+ '符号库清单与常用元件的引脚相对坐标、变体与方向的关系、中文概念对应表,'
42
+ + '以及「先查再插」的查证方法。',
43
+ },
44
+ {
45
+ name: 'eplan-annotations',
46
+ title: '标注:谁渲染、在哪、什么颜色',
47
+ whenToUse: '补文字、调标签位置、出现重影或叠字时。',
48
+ description:
49
+ '设备标识、连接点代号、手写文字、跨页引用这四类「字」分别由谁渲染、落在哪里、'
50
+ + '深色/浅色主题下的颜色,以及三种实测过的坑。',
51
+ },
52
+ {
53
+ name: 'eplan-review',
54
+ title: '审查契约:什么时候才算画完',
55
+ whenToUse: '准备交付之前;判断一条差异该修还是可放行时。',
56
+ description:
57
+ '放行的三条硬条件、差异必须落进 intent 还是 style、机器能判的先用机器判,'
58
+ + '以及常见的不合格审查做法。',
59
+ },
60
+ {
61
+ name: 'eplan-project',
62
+ title: '多页项目的拆分与闭环',
63
+ whenToUse: '用户要建整个项目、一次画多页,或需要多会话并行改同一个项目时。',
64
+ description:
65
+ '先有页清单再逐页闭环、页号命名规则、台账与占位的用法,以及一页一个功能块的拆分建议。',
66
+ },
67
+ ]
68
+
69
+ const bodyCache = new Map()
70
+
71
+ /** 读一篇技能正文;文件不在就返回一段可读的说明,不让工具直接失败。 */
72
+ function readSkillBody(name) {
73
+ if (bodyCache.has(name)) return bodyCache.get(name)
74
+ const path = join(SKILL_ROOT, name, 'SKILL.md')
75
+ let body
76
+ try {
77
+ const raw = existsSync(path) ? readFileSync(path, 'utf8') : ''
78
+ // 去掉 YAML frontmatter:技能注册时正文就是正文,不再带一遍元数据。
79
+ body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim()
80
+ } catch {
81
+ body = ''
82
+ }
83
+ if (body.length === 0) body = `(技能 ${name} 的正文缺失,请让维护者检查 skills/${name}/SKILL.md)`
84
+ bodyCache.set(name, body)
85
+ return body
86
+ }
87
+
88
+ /** 清缓存:文件改过之后下一次读能拿到新内容。 */
89
+ export function invalidateSkillCache() {
90
+ bodyCache.clear()
91
+ }
92
+
93
+ export function apply(ctx) {
94
+ // 注册到本作用域:只有选择本预设的 agent 能看到这几个技能。
95
+ for (const skill of SKILLS) {
96
+ ctx.effect(
97
+ () => ctx.skills.register({
98
+ name: skill.name,
99
+ description: skill.description,
100
+ whenToUse: skill.whenToUse,
101
+ // 模型可以调;用户也可以用 /eplan-drawing 直接呼出。
102
+ invocation: { modelInvocable: true, userInvocable: true },
103
+ provider: 'eplan',
104
+ resourceBase: { kind: 'directory', path: join(SKILL_ROOT, skill.name) },
105
+ content: () => readSkillBody(skill.name),
106
+ }),
107
+ `eplan: skill ${skill.name}`,
108
+ )
109
+ }
110
+
111
+ // ── compaction 之后自动补回 ────────────────────────────────────────────
112
+ // 压缩会把技能正文从上下文里摘掉,模型于是忘了画法。记住本会话加载过哪些,
113
+ // 压缩结束时(以及之后第一次进入步之前)重新注入一次。
114
+ const loaded = new Map() // sessionId → Set<skillName>
115
+ const pending = new Set() // sessionId 待补注入
116
+
117
+ const keyOf = (agent) => String(agent?.session?.id ?? 'unknown')
118
+
119
+ // 记录模型真正加载过的技能:skill 工具的成功结果里带 name。
120
+ ctx.on('tools/post-execute', async (exec, result, next) => {
121
+ const decision = await next()
122
+ try {
123
+ if (exec?.name !== 'skill') return decision
124
+ if (decision?.kind !== 'accept' || !Array.isArray(decision.content)) return decision
125
+ const text = decision.content
126
+ .filter((block) => block?.type === 'text')
127
+ .map((block) => String(block.text ?? ''))
128
+ .join('\n')
129
+ const hit = SKILLS.find((skill) => text.includes(`skill ${skill.name}`) || text.includes(skill.name))
130
+ if (!hit) return decision
131
+ const key = keyOf(exec?.agent)
132
+ const set = loaded.get(key) ?? new Set()
133
+ set.add(hit.name)
134
+ loaded.set(key, set)
135
+ } catch {
136
+ // 记录失败不能影响工具本身的返回。
137
+ }
138
+ return decision
139
+ })
140
+
141
+ ctx.on('session/event', (session, event) => {
142
+ if (event?.type !== 'compaction/end') return
143
+ const key = String(session?.header?.id ?? session?.id ?? 'unknown')
144
+ if ((loaded.get(key)?.size ?? 0) > 0) pending.add(key)
145
+ })
146
+
147
+ ctx.on('agent/pre-step', async (payload, next) => {
148
+ const decision = await next()
149
+ if (decision.kind !== 'enter') return decision
150
+ const key = keyOf(payload?.agent)
151
+ if (!pending.has(key)) return decision
152
+ pending.delete(key)
153
+ const names = [...(loaded.get(key) ?? [])]
154
+ if (names.length === 0) return decision
155
+
156
+ const text = names
157
+ .map((name) => {
158
+ const meta = SKILLS.find((skill) => skill.name === name)
159
+ return `## ${meta?.title ?? name}(${name})\n\n${readSkillBody(name)}`
160
+ })
161
+ .join('\n\n')
162
+
163
+ return {
164
+ ...decision,
165
+ messages: [
166
+ ...decision.messages,
167
+ {
168
+ role: 'user',
169
+ source: { kind: 'skill-invocation', form: 'instructions' },
170
+ content: [{
171
+ type: 'text',
172
+ text: `<system-reminder>\n上下文压缩之后重新附上本会话已加载的绘图技能正文:\n\n${text}\n</system-reminder>`,
173
+ }],
174
+ },
175
+ ],
176
+ }
177
+ })
178
+ }
179
+
180
+ /** 测试用:技能清单就是注册出去的那一份,别让测试自己抄。 */
181
+ export const SKILL_MANIFEST = Object.freeze(SKILLS.map(({ name, title, description }) => ({ name, title, description })))
@@ -0,0 +1,294 @@
1
+ // 视频「发送即摘要」:用户一发录屏,就在进入模型之前把它换成预处理好的摘要。
2
+ //
3
+ // 为什么不靠模型自己调 video():
4
+ // 实测 248 s 录屏,模型拿到的是「文件句柄 + 一个 video(path) 工具」,于是一路
5
+ // 调 video、抽帧、放大、再抽帧 —— 26 步 0 页。用户要求:第一次输入就该是切分好的内容。
6
+ //
7
+ // 机制:监听 agent/pre-step(瀑布),在把消息交给模型之前,把 content 里的视频
8
+ // (file 附件块,或文本里 @ 出来的路径)换成 [摘要文字 + 每个阶段一张图]。
9
+ // 用户原来打的字保持原样。
10
+ //
11
+ // 注入形态(2026-11-27 改):
12
+ // 以前把摘要文字塞进**用户消息**的 content,等于替用户说话,模型会把它当用户命令,
13
+ // 用户也会看到「画面阶段(逐张给图,不拼图)」「已预处理完毕:不要再反复调 video()」
14
+ // 这种写给模型的括号注释。现在拆成两半:
15
+ // * 图 + 一句话的位置说明 → 单独一条 source.kind = 'video-digest' 的消息;
16
+ // * 面向模型的操作提示 → 系统提示词里的固定段落(见 persona),不进对话流。
17
+ // 用户原消息一个字都不改。
18
+ //
19
+ // 分工:
20
+ // server/video.mjs —— 只算事实:探测、切阶段、取图、量响度、切语音片段
21
+ // 本文件 —— 接 DSH 服务:转写(speechToText)、存图(attachments)、改消息
22
+ import { existsSync, readFileSync } from 'node:fs'
23
+ import { basename, extname, isAbsolute, resolve } from 'node:path'
24
+ import { digest as analyzeDigest, decodeWav, encodeWav } from '../server/video.mjs'
25
+
26
+ export const name = 'video-digest'
27
+
28
+ const VIDEO_EXTENSIONS = new Set(['.mp4', '.mkv', '.mov', '.avi', '.wmv', '.flv', '.webm', '.m4v', '.mpg', '.mpeg', '.ts'])
29
+ // 一步最多 8 张新图(服务端硬限制);开工注入与环境一起进入的那一轮留足余量。
30
+ const DEFAULT_MAX_IMAGES = 4
31
+
32
+ /** 附件名是不是视频。file 块只有 name / bytes / sha256,没有 mediaType。 */
33
+ function isVideoName(name) {
34
+ return VIDEO_EXTENSIONS.has(extname(String(name ?? '')).toLowerCase())
35
+ }
36
+
37
+ /**
38
+ * 文本里 @ 出来的视频路径。
39
+ *
40
+ * 为什么要有这条:真实用法是用户在输入框里打 `@C:\...\xxx.mp4`(或直接粘路径),
41
+ * DSH 把它变成一段**纯文本**,不是 file 附件块 —— 2026-11-23 session-a18a4a7f 里
42
+ * 第一次发录屏就是这样,于是 file 块那条路根本没触发,模型只好自己调 video(),
43
+ * 白多一轮,图还丢了(图在 console.log 里被 JSON.stringify 掉)。
44
+ */
45
+ export function videoPathsInText(text) {
46
+ if (typeof text !== 'string' || text.length === 0) return []
47
+ const EXT = 'mp4|mkv|mov|avi|wmv|flv|webm|m4v|mpe?g|ts'
48
+ const ROOT = '(?:[A-Za-z]:[\\\\/]|\\\\\\\\)'
49
+ // 三种写法,按可信度从高到低:
50
+ // ① 带引号的(路径里可以有空格):@"D:\录像\第一讲 01.mp4"
51
+ // ② @ 开头的:允许空格 —— DSH 的 @ 引用本来就支持带空格的路径
52
+ // ③ 裸写的:不允许空格,遇到空白/引号/中文标点就停
53
+ const patterns = [
54
+ new RegExp(`"(${ROOT}[^"]*?\\.(?:${EXT}))"`, 'gi'),
55
+ new RegExp(`@(${ROOT}[^\\r\\n"'<>|?*。,;、]*?\\.(?:${EXT}))\\b`, 'gi'),
56
+ new RegExp(`(${ROOT}[^\\s"'<>|?*\\r\\n]*?\\.(?:${EXT}))\\b`, 'gi'),
57
+ ]
58
+ const found = []
59
+ for (const pattern of patterns) {
60
+ for (const match of text.matchAll(pattern)) {
61
+ const raw = match[1].replace(/[)\]}>,.;]+$/, '')
62
+ if (raw.length === 0) continue
63
+ if (!found.includes(raw)) found.push(raw)
64
+ }
65
+ }
66
+ return found
67
+ }
68
+
69
+ /**
70
+ * 逐段转写。失败必须带出原因 —— 旧的实现把 error 丢掉,只留空字符串,
71
+ * 模型看到「有音频、有 1 步、没文字」只能去抽帧猜(2026-11-23 实测)。
72
+ */
73
+ async function transcribeSpans(ctx, spans, audioPath, { language, signal } = {}) {
74
+ const service = ctx.get('speechToText')
75
+ if (!service) {
76
+ return spans.map((span) => ({ ...span, text: '', error: '本机没有语音转写服务(speechToText 未启用)' }))
77
+ }
78
+ const samples = decodeWav(readFileSync(audioPath))
79
+ const out = []
80
+ let prepared = false
81
+ for (const span of spans) {
82
+ const from = Math.max(0, Math.floor(span.t0 * 16000))
83
+ const to = Math.min(samples.length, Math.ceil(span.t1 * 16000))
84
+ if (to - from < 1600) {
85
+ out.push({ ...span, text: '', error: '片段短于 0.1 秒' })
86
+ continue
87
+ }
88
+ const audio = encodeWav(samples.subarray(from, to))
89
+ try {
90
+ let spec
91
+ try {
92
+ spec = service.resolve({ audio, ...(language ? { language } : {}) })
93
+ } catch (error) {
94
+ out.push({ ...span, text: '', error: `转写参数无法解析:${error.message}` })
95
+ continue
96
+ }
97
+ let result
98
+ try {
99
+ result = await service.transcribe(spec, signal ?? new AbortController().signal)
100
+ } catch (error) {
101
+ if (prepared) throw error
102
+ prepared = true
103
+ service.prepare?.(spec.provider.info.id, {})
104
+ result = await service.transcribe(spec, signal ?? new AbortController().signal)
105
+ }
106
+ const text = String(result?.text ?? '').trim()
107
+ out.push({ ...span, text, ...(text ? {} : { error: '转写返回空文本' }) })
108
+ } catch (error) {
109
+ out.push({ ...span, text: '', error: String(error?.message ?? error) })
110
+ }
111
+ }
112
+ return out
113
+ }
114
+
115
+ /**
116
+ * 跑一次视频摘要并拼成 content 块(文字 + 逐张图)。
117
+ * @returns {Promise<{blocks: object[], digest: object}>}
118
+ */
119
+ export async function buildDigest(ctx, path, { at = null, maxImages = DEFAULT_MAX_IMAGES, language, signal } = {}) {
120
+ const result = await analyzeDigest(path, {
121
+ maxPages: Math.min(Math.max(maxImages, 1), 8),
122
+ at,
123
+ transcribe: (spans, audioPath) => transcribeSpans(ctx, spans, audioPath, { language, signal }),
124
+ })
125
+
126
+ // 只要「某一秒的那张图」,而且摘要是缓存命中的 → 只发那一张 + 一行说明。
127
+ //
128
+ // 2026-11-24 session-400917a2:模型用 video({path, at:245/500/565/700/742}) 连要 5 张图,
129
+ // 每次都把 3.5 KB 的全量摘要重发一遍(前后 17.6 KB 重复上下文)。它要的是图,不是摘要。
130
+ const frameOnly = at !== null && result.cached === true && result.extra.length > 0
131
+ const shots = frameOnly
132
+ ? result.extra.map((item) => item.shot)
133
+ : [...result.pages.map((page) => page.shot), ...result.extra.map((item) => item.shot)]
134
+
135
+ const attachments = ctx.get('attachments')
136
+ const blocks = []
137
+ let images = []
138
+ if (attachments && shots.length > 0) {
139
+ const asImage = (shot) => ({
140
+ data: readFileSync(shot.path),
141
+ mediaType: shot.mimeType ?? 'image/png',
142
+ name: basename(shot.path),
143
+ })
144
+ try {
145
+ images = await attachments.saveImages(shots.map(asImage))
146
+ } catch (error) {
147
+ // 图片总量超限时逐张退让,一张都进不去就只给路径 —— 绝不因此让整轮失败。
148
+ images = []
149
+ for (const shot of shots) {
150
+ try {
151
+ const [saved] = await attachments.saveImages([asImage(shot)])
152
+ images.push(saved)
153
+ } catch {
154
+ break
155
+ }
156
+ }
157
+ result.text += `\n(部分图片因总量限制没进上下文:${error.message})`
158
+ }
159
+ }
160
+
161
+ if (frameOnly) {
162
+ const shotAt = result.extra[0]
163
+ blocks.push({
164
+ type: 'text',
165
+ text: `录屏 ${clockOf(result.meta.duration)} 的 ${clockOf(shotAt.t)} 这一帧。`,
166
+ })
167
+ } else {
168
+ blocks.push({ type: 'text', text: result.text })
169
+ }
170
+ for (let index = 0; index < images.length; index += 1) {
171
+ blocks.push({ type: 'image', attachment: images[index] })
172
+ }
173
+ return { blocks, digest: result, frameOnly, meta: result.meta }
174
+ }
175
+
176
+ /** 秒 → m:ss;本地一份,别为了一个格式化去 import 整条管线。 */
177
+ function clockOf(seconds) {
178
+ const total = Math.max(0, Math.round(Number(seconds) || 0))
179
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`
180
+ }
181
+
182
+ /** 摘要失败时的一句话:路径留着,模型还能自己试一次。 */
183
+ function failureBlocks(path, error) {
184
+ return [{
185
+ type: 'text',
186
+ text: `[视频「${basename(path)}」预处理失败:${String(error?.message ?? error)}。`
187
+ + `可以直接用 video({path:"${path}"}) 再试一次,或先问用户要关键页的截图。]`,
188
+ }]
189
+ }
190
+
191
+ /** 同一份文件只摘要一次(用户可能在同一轮里又 @ 了一次)。 */
192
+ async function digestForPath(ctx, path, { cache, signal }) {
193
+ const key = `path:${path.toLowerCase()}`
194
+ const hit = cache.get(key)
195
+ if (hit) return hit
196
+ let entry
197
+ try {
198
+ entry = await buildDigest(ctx, path, { signal })
199
+ } catch (error) {
200
+ entry = { blocks: failureBlocks(path, error) }
201
+ }
202
+ cache.set(key, entry)
203
+ return entry
204
+ }
205
+
206
+ /**
207
+ * 一条用户消息 → { userMessage, digestMessage }。
208
+ *
209
+ * userMessage 只删掉「视频附件块」和「@ 路径那段纯文本里的路径本身」,
210
+ * 用户打的其它字一律原样保留;摘要单独成一条消息,不再顶替用户说话。
211
+ */
212
+ async function splitMessage(ctx, message, { cache, signal }) {
213
+ let changed = false
214
+ const kept = []
215
+ const digestContent = []
216
+
217
+ for (const block of message.content) {
218
+ // ① file 附件块:视频
219
+ if (block.type === 'file' && isVideoName(block.attachment?.name)) {
220
+ const id = String(block.attachment.attachmentId ?? block.attachment.name)
221
+ let entry = cache.get(id)
222
+ if (!entry) {
223
+ const path = ctx.get('attachments')?.fileHostPath?.(block.attachment)
224
+ if (!path) {
225
+ digestContent.push({ type: 'text', text: `[视频「${block.attachment.name}」已上传,但当前环境拿不到可读路径,无法预处理。]` })
226
+ changed = true
227
+ continue
228
+ }
229
+ entry = await digestForPath(ctx, path, { cache, signal })
230
+ cache.set(id, entry)
231
+ }
232
+ digestContent.push(...entry.blocks)
233
+ changed = true
234
+ continue
235
+ }
236
+
237
+ // ② 文本块里 @ 出来的视频路径:保留用户原话,摘要另起一条
238
+ if (block.type === 'text' && !String(block.text ?? '').includes('<video-digest>')) {
239
+ const paths = videoPathsInText(block.text)
240
+ .map((raw) => (isAbsolute(raw) ? raw : resolve(raw)))
241
+ .filter((path) => existsSync(path))
242
+ if (paths.length > 0) {
243
+ for (const path of [...new Set(paths)]) {
244
+ const entry = await digestForPath(ctx, path, { cache, signal })
245
+ digestContent.push(...entry.blocks)
246
+ }
247
+ changed = true
248
+ }
249
+ }
250
+
251
+ kept.push(block)
252
+ }
253
+
254
+ if (!changed) return null
255
+ return {
256
+ userMessage: kept.some((block) => block.type === 'text' && String(block.text ?? '').trim().length > 0) || kept.length > 0
257
+ ? { ...message, content: kept }
258
+ : null,
259
+ digestMessage: digestContent.length > 0
260
+ ? { role: 'user', source: { kind: 'video-digest', form: 'snapshot' }, content: digestContent }
261
+ : null,
262
+ }
263
+ }
264
+
265
+ export function apply(ctx) {
266
+ const cache = new Map()
267
+ ctx.on('agent/pre-step', async (payload, next) => {
268
+ const decision = await next()
269
+ if (decision.kind !== 'enter') return decision
270
+ let touched = false
271
+ const messages = []
272
+ for (const message of decision.messages) {
273
+ // 只看真正的用户输入;摘要自己那条、系统提醒、技能注入一律不碰。
274
+ const isDirect = message.role === 'user' && (message.source?.kind === 'user' || message.source?.kind === undefined)
275
+ if (!isDirect) {
276
+ messages.push(message)
277
+ continue
278
+ }
279
+ try {
280
+ const split = await splitMessage(ctx, message, { cache, signal: payload.signal })
281
+ if (split) {
282
+ if (split.userMessage) messages.push(split.userMessage)
283
+ if (split.digestMessage) messages.push(split.digestMessage)
284
+ touched = true
285
+ continue
286
+ }
287
+ } catch {
288
+ // 摘要出任何问题都不能挡住这一轮:退回原消息,模型还有 video() 可用。
289
+ }
290
+ messages.push(message)
291
+ }
292
+ return touched ? { ...decision, messages } : decision
293
+ }, { prepend: true })
294
+ }
@@ -0,0 +1,92 @@
1
+ // video(path):录屏 → 「阶段 + 每阶段一张图 + 讲解文字」。
2
+ //
3
+ // 现在摘要的主体在 video-digest.js(发送视频时自动跑一次),这个工具只负责两件事:
4
+ // 1. 用户后来又提到路径、或自动摘要失败时,手动跑同一套摘要;
5
+ // 2. 需要某个具体时间点的整页图时,用 at 取一张。
6
+ // 图片逐张返回,绝不拼成一张拼图(2026-11-23 用户要求)。
7
+ import { buildDigest } from './video-digest.js'
8
+
9
+ export const name = 'video-tool'
10
+
11
+ // Cordis 只有 inject 之后才会把 services 挂到 ctx 上;tools 是必须的。
12
+ // attachments / speechToText 用 ctx.get 取,取不到就降级。
13
+ export const inject = ['tools']
14
+
15
+ export function apply(ctx) {
16
+ ctx.tools.register({
17
+ name: 'video',
18
+ description: [
19
+ '录屏摘要:按画面变化切成若干阶段,每阶段给一张最稳的整页图(逐张返回,不拼图),并把讲解语音转成文字。',
20
+ '视频在发送时已经被预处理过一次,摘要会直接出现在对话里——通常不用再调用它。',
21
+ '摘要按「文件 + 大小 + 修改时间」缓存:命中时只做取图,不重新解码、不重新转写,秒回。',
22
+ '只要某一秒的画面就用 at:命中缓存时只回那一张图和一行说明,不会把 3.5 KB 摘要重发一遍。',
23
+ '没有讲解会明确写「讲解:无」;转写失败会写明原因,不要靠不断取帧来猜画面。',
24
+ ].join(''),
25
+ parameters: {
26
+ type: 'object',
27
+ additionalProperties: false,
28
+ required: ['path'],
29
+ properties: {
30
+ path: { type: 'string', description: '视频文件的绝对路径(mp4/mkv/mov 等 ffmpeg 能读的格式)。' },
31
+ at: { type: 'number', description: '额外取这个时间点(秒)的一张整页图;只在需要看清某一刻时给。' },
32
+ maxImages: { type: 'integer', description: '阶段图最多几张,默认 6,上限 8(一步最多 8 张图;自动摘要那次只用 4 张,把额度留给符号图鉴)。' },
33
+ language: { type: 'string', description: '语音语言提示,如 zh / en;不给就用 DSH 的默认设置。' },
34
+ },
35
+ },
36
+ output: {
37
+ schema: { type: 'object' },
38
+ render: (_args, value) => value.content,
39
+ },
40
+ async execute(args, exec) {
41
+ const maxImages = Math.min(Math.max(args.maxImages ?? 6, 1), 8)
42
+ const { blocks } = await buildDigest(ctx, args.path, {
43
+ at: typeof args.at === 'number' ? args.at : null,
44
+ maxImages,
45
+ language: args.language,
46
+ signal: exec?.signal,
47
+ })
48
+ return { content: blocks }
49
+ },
50
+ })
51
+
52
+ // 量图:把截图/录屏帧里的像素换算成毫米。
53
+ // 挂在预设工具上而不是 MCP:它跟 EPLAN 无关,也不该占 MCP 工具面的固定成本。
54
+ ctx.tools.register({
55
+ name: 'measure',
56
+ description: [
57
+ '量图:把截图或录屏帧里的像素距离换算成毫米,替代手工数字数格子。',
58
+ '顺序:先 calibrate(两个已知点的像素坐标 + 真实毫米 → px/mm),再 edges(找竖线/横线,给出像素与 mm),',
59
+ 'grid(从线的间距推栅格/极距)。分辨率低于 8 px/mm 时 calibrate 会直接给 warning,别硬量。',
60
+ '只量像素,不改任何文件和 EPLAN。',
61
+ ].join(''),
62
+ parameters: {
63
+ type: 'object',
64
+ additionalProperties: false,
65
+ required: ['path', 'action'],
66
+ properties: {
67
+ path: { type: 'string', description: '图片绝对路径(png/jpg/bmp 等 ffmpeg 能读的格式)。' },
68
+ action: { type: 'string', enum: ['calibrate', 'edges', 'grid'], description: 'calibrate 定比例;edges 找线;grid 推间距。' },
69
+ from: { type: 'array', items: { type: 'number' }, description: 'calibrate:第一点的像素坐标 [x, y]。' },
70
+ to: { type: 'array', items: { type: 'number' }, description: 'calibrate:第二点的像素坐标 [x, y]。' },
71
+ mm: { type: 'number', description: 'calibrate:这两点之间的真实距离(毫米)。' },
72
+ axis: { type: 'string', enum: ['x', 'y', 'both'], description: 'edges/grid 的扫描方向,默认 both。' },
73
+ pxPerMm: { type: 'number', description: 'edges/grid 换算用:来自 calibrate 的 pxPerMm。不给就只报像素。' },
74
+ originPx: { type: 'array', items: { type: 'number' }, description: '像素原点 [x, y];默认左下角 (0, 图高)。' },
75
+ originMm: { type: 'array', items: { type: 'number' }, description: '毫米原点 [x, y],默认 [0, 0]。' },
76
+ flipY: { type: 'boolean', description: '图片 Y 向下、EPLAN Y 向上时翻转,默认 true。' },
77
+ region: { type: 'array', items: { type: 'number' }, description: '只扫这个矩形 [x0, y0, x1, y1](像素)。' },
78
+ threshold: { type: 'number', description: '明暗跳变阈值 0-255,默认自动(Otsu)。线找不全就降到 16。' },
79
+ minGapPx: { type: 'number', description: '相邻线的最小像素间隔,默认 3。' },
80
+ },
81
+ },
82
+ output: {
83
+ schema: { type: 'object' },
84
+ render: (_args, value) => value.content,
85
+ },
86
+ async execute(args) {
87
+ const { measure } = await import('../server/measure.mjs')
88
+ const payload = await measure(args)
89
+ return { content: [{ type: 'text', text: JSON.stringify(payload) }] }
90
+ },
91
+ })
92
+ }