dsh-docx-format 0.0.0-stage → 1.0.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/index.js ADDED
@@ -0,0 +1,729 @@
1
+ /**
2
+ * dsh-docx-format — 让 DSH 生成的所有 .docx 自动套用《通用公文格式规范》。
3
+ *
4
+ * 三层能力:
5
+ * 1) docx_format 工具:模型可显式调用,apply(规范化)/ check(只体检)。
6
+ * 2) systemPrompt 段:把格式硬规则写进提示词,模型一开始就知道该怎么排版。
7
+ * 3) tools/result 观察者:任何工具产出 .docx 路径后,自动排队规范化(默认只处理本次会话新写的文件)。
8
+ *
9
+ * 白名单(本版新增):当前会话最后一条用户消息命中 skipRequestKeywords(默认「实验报告」)时,
10
+ * 整个插件不介入 —— 不排队、不改文件、工具调用直接返回 skipped。
11
+ *
12
+ * 真实排版逻辑在 lib/docxfmt.py(python-docx),本文件只做进程调用与调度。
13
+ */
14
+ import { existsSync, statSync } from 'node:fs'
15
+ import { spawn } from 'node:child_process'
16
+ import { isAbsolute, resolve } from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
18
+ import path from 'node:path'
19
+
20
+ export const name = 'dsh-docx-format'
21
+
22
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
23
+ const ENGINE = path.join(HERE, 'lib', 'docxfmt.py')
24
+ const READER = path.join(HERE, 'lib', 'docx_read.py')
25
+ const LOADED_AT = Date.now()
26
+
27
+ const DEFAULTS = {
28
+ autoFormat: true,
29
+ formatExisting: false,
30
+ debounceMs: 1200,
31
+ timeoutMs: 120000,
32
+ python: '',
33
+ maxFilesPerTurn: 8,
34
+ skipPatterns: ['*格式要求*', '*模板*', '~$*', '*/node_modules/*'],
35
+ // 用户请求文字白名单:命中即整个插件不运行(不是只跳过某个文件)
36
+ skipRequestKeywords: ['实验报告'],
37
+ prompt: { enabled: true, order: 3260 },
38
+ tool: { enabled: true },
39
+ defaults: {},
40
+ }
41
+
42
+ /* ------------------------------------------------------------------ 配置 */
43
+
44
+ function normalizeConfig(config) {
45
+ const cfg = { ...DEFAULTS, ...(config ?? {}) }
46
+ cfg.skipPatterns = Array.isArray(cfg.skipPatterns) ? cfg.skipPatterns.map(String) : DEFAULTS.skipPatterns
47
+ cfg.skipRequestKeywords = Array.isArray(cfg.skipRequestKeywords)
48
+ ? cfg.skipRequestKeywords.map(String).map((s) => s.trim()).filter(Boolean)
49
+ : DEFAULTS.skipRequestKeywords
50
+ cfg.prompt = { ...DEFAULTS.prompt, ...(config?.prompt ?? {}) }
51
+ cfg.tool = { ...DEFAULTS.tool, ...(config?.tool ?? {}) }
52
+ cfg.defaults = config?.defaults && typeof config.defaults === 'object' ? config.defaults : {}
53
+ const n = Number(cfg.debounceMs)
54
+ cfg.debounceMs = Number.isFinite(n) && n >= 0 ? n : DEFAULTS.debounceMs
55
+ const t = Number(cfg.timeoutMs)
56
+ cfg.timeoutMs = Number.isFinite(t) && t > 0 ? t : DEFAULTS.timeoutMs
57
+ const m = Number(cfg.maxFilesPerTurn)
58
+ cfg.maxFilesPerTurn = Number.isFinite(m) && m > 0 ? Math.floor(m) : DEFAULTS.maxFilesPerTurn
59
+ return cfg
60
+ }
61
+
62
+ /* --------------------------------------------------------------- 解释器 */
63
+
64
+ function pythonCandidates(cfg) {
65
+ const list = []
66
+ if (cfg.python) list.push(cfg.python)
67
+ if (process.env.DSH_DOCX_PYTHON) list.push(process.env.DSH_DOCX_PYTHON)
68
+ const home = process.env.USERPROFILE || process.env.HOME || ''
69
+ if (home) {
70
+ list.push(path.join(home, '.dsh', 'dsh-runtimes', 'dsh-primary-runtime', 'dependencies', 'python', 'python.exe'))
71
+ }
72
+ list.push('python', 'python3')
73
+ return list
74
+ }
75
+
76
+ function resolvePython(cfg) {
77
+ for (const c of pythonCandidates(cfg)) {
78
+ if (c === 'python' || c === 'python3') return c
79
+ if (existsSync(c)) return c
80
+ }
81
+ return 'python'
82
+ }
83
+
84
+ /* ----------------------------------------------------------- 调用引擎 */
85
+
86
+ function runScript(python, script, args, timeoutMs) {
87
+ return new Promise((done) => {
88
+ const env = { ...process.env, PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' }
89
+ const child = spawn(python, [script, ...args], { env, windowsHide: true })
90
+ let out = ''
91
+ let err = ''
92
+ let settled = false
93
+ const finish = (value) => {
94
+ if (settled) return
95
+ settled = true
96
+ done(value)
97
+ }
98
+ const timer = setTimeout(() => {
99
+ try { child.kill() } catch { /* ignore */ }
100
+ finish({ ok: false, code: 'timeout', message: 'docxfmt 超时:' + timeoutMs + 'ms' })
101
+ }, timeoutMs)
102
+ child.stdout.setEncoding('utf8')
103
+ child.stderr.setEncoding('utf8')
104
+ child.stdout.on('data', (chunk) => { out += chunk })
105
+ child.stderr.on('data', (chunk) => { err += chunk })
106
+ child.on('error', (e) => {
107
+ clearTimeout(timer)
108
+ finish({ ok: false, code: 'spawn', message: '无法启动 python:' + (e?.message ?? String(e)) })
109
+ })
110
+ child.on('close', (code) => {
111
+ clearTimeout(timer)
112
+ finish({ ok: true, code, stdout: out, stderr: err })
113
+ })
114
+ })
115
+ }
116
+
117
+ function runEngine(python, args, timeoutMs) {
118
+ return runScript(python, ENGINE, args, timeoutMs)
119
+ }
120
+
121
+ /**
122
+ * DSH 要求工具返回值「可无损 JSON 化」:对象里带值为 undefined 的键会让
123
+ * JSON.stringify → parse 后丢键,校验直接报 `value is not lossless JSON`。
124
+ * docx_format 旧版把 `skipReason: skipped[0]?.skipReason` 直接放进去,
125
+ * 非跳过场景 key 存在但值是 undefined —— 于是每次正常调用都被判 invalid。
126
+ */
127
+ function stripUndefined(value) {
128
+ if (Array.isArray(value)) return value.map(stripUndefined)
129
+ if (value && typeof value === 'object') {
130
+ const out = {}
131
+ for (const [key, item] of Object.entries(value)) {
132
+ if (item !== undefined) out[key] = stripUndefined(item)
133
+ }
134
+ return out
135
+ }
136
+ return value
137
+ }
138
+
139
+ function parseReport(stdout) {
140
+ const text = String(stdout ?? '').trim()
141
+ if (text === '') return undefined
142
+ const start = text.indexOf('{')
143
+ if (start < 0) return undefined
144
+ try {
145
+ return JSON.parse(text.slice(start))
146
+ } catch {
147
+ return undefined
148
+ }
149
+ }
150
+
151
+ async function formatOne(cfg, python, target, mode, recursive) {
152
+ const args = [target, '--mode', mode, '--json']
153
+ if (recursive) args.push('--recursive')
154
+ if (cfg.defaults && Object.keys(cfg.defaults).length > 0) args.push('--config', JSON.stringify(cfg.defaults))
155
+ const run = await runEngine(python, args, cfg.timeoutMs)
156
+ if (!run.ok) return { ok: false, path: target, mode, message: run.message, changed: 0, violations: 0 }
157
+ const report = parseReport(run.stdout)
158
+ if (!report) {
159
+ const detail = (run.stderr || run.stdout || '').trim().split('\n').slice(-4).join(' | ')
160
+ return { ok: false, path: target, mode, message: 'docxfmt 输出无法解析:' + detail, changed: 0, violations: 0 }
161
+ }
162
+ const files = Array.isArray(report.files) ? report.files : [report]
163
+ const fixes = files.reduce((n, f) => n + (Number(f.violations) || 0), 0)
164
+ const changedFiles = files.filter((f) => f.changed === true).length
165
+ const skipped = files.filter((f) => f.skipped === true)
166
+ return stripUndefined({
167
+ ok: files.every((f) => f.ok !== false),
168
+ path: report.path ?? target,
169
+ mode,
170
+ changed: mode === 'apply' ? fixes : 0,
171
+ violations: mode === 'check' ? fixes : 0,
172
+ fixes,
173
+ changedFiles,
174
+ skipped: skipped.length,
175
+ skipReason: skipped[0]?.skipReason,
176
+ files,
177
+ warnings: files.flatMap((f) => (Array.isArray(f.warnings) ? f.warnings : [])),
178
+ })
179
+ }
180
+
181
+ /* --------------------------------------------------------- 路径采集 */
182
+
183
+ const BT = String.fromCharCode(96)
184
+ const DOCX_RE = new RegExp(
185
+ '[A-Za-z]:[\\\\/][^\\n\\"' + BT + '<>|,。;:、()()\\[\\]{}]*?\\.docx'
186
+ + '|[^\\s\\"' + BT + '<>|,。;:、()()\\[\\]{}]+\\.docx',
187
+ 'gi',
188
+ )
189
+
190
+ function wildcardToRegExp(pattern) {
191
+ const escaped = String(pattern).replace(/[{}.*+?^$()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
192
+ return new RegExp('^' + escaped + '$', 'i')
193
+ }
194
+
195
+ function isSkipped(file, patterns) {
196
+ const normalized = file.replace(/\\/g, '/')
197
+ return patterns.some((p) => {
198
+ try {
199
+ return wildcardToRegExp(p.replace(/\\/g, '/')).test(normalized)
200
+ } catch {
201
+ return false
202
+ }
203
+ })
204
+ }
205
+
206
+ function collectStrings(value, out, depth = 0) {
207
+ if (depth > 3 || out.length > 200) return
208
+ if (typeof value === 'string') { out.push(value); return }
209
+ if (Array.isArray(value)) { for (const item of value) collectStrings(item, out, depth + 1); return }
210
+ if (value && typeof value === 'object') {
211
+ for (const item of Object.values(value)) collectStrings(item, out, depth + 1)
212
+ }
213
+ }
214
+
215
+ function extractDocxPaths(exec, result) {
216
+ const strings = []
217
+ collectStrings(exec?.arguments, strings)
218
+ collectStrings(result?.content, strings)
219
+ const found = new Set()
220
+ for (const text of strings) {
221
+ const matches = String(text).match(DOCX_RE)
222
+ if (!matches) continue
223
+ for (const raw of matches) {
224
+ const candidate = raw.replace(/^[((“"'【\[]+/, '').trim()
225
+ if (!candidate || candidate.startsWith('http')) continue
226
+ found.add(candidate)
227
+ }
228
+ }
229
+ return [...found]
230
+ }
231
+
232
+ /* -------------------------------------------------- 请求文字白名单 */
233
+
234
+ /** 从一个 Message 里拼出纯文本(只取 text block)。 */
235
+ function messageText(message) {
236
+ const parts = []
237
+ const content = message?.content
238
+ if (Array.isArray(content)) {
239
+ for (const block of content) {
240
+ if (block && block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
241
+ }
242
+ }
243
+ if (typeof message?.text === 'string') parts.push(message.text)
244
+ return parts.join('\n').trim()
245
+ }
246
+
247
+ /** 最后一条 user 消息的文本;失败一律返回 ''。 */
248
+ function lastUserText(session) {
249
+ try {
250
+ const messages = session.deriveMessages?.() ?? []
251
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
252
+ const m = messages[i]
253
+ if (m?.role !== 'user') continue
254
+ const text = messageText(m)
255
+ if (text !== '') return text
256
+ }
257
+ } catch { /* ignore */ }
258
+ return ''
259
+ }
260
+
261
+ function matchKeyword(text, keywords) {
262
+ if (!text || !Array.isArray(keywords)) return undefined
263
+ for (const kw of keywords) {
264
+ if (kw && text.includes(kw)) return kw
265
+ }
266
+ return undefined
267
+ }
268
+
269
+ /* ------------------------------------------------------------ 插件主体 */
270
+
271
+ export function apply(ctx, config) {
272
+ const cfg = normalizeConfig(config)
273
+ const python = resolvePython(cfg)
274
+ const queue = []
275
+ const seen = new Map()
276
+ const formattedByUs = new Set()
277
+ /** sessionId -> { seq, text } 最近用户请求文字缓存(避免反复 deriveMessages) */
278
+ const requestCache = new Map()
279
+ let timer
280
+ let running = false
281
+
282
+ const log = (level, ...args) => {
283
+ try { ctx.logger?.[level]?.(...args) } catch { /* ignore */ }
284
+ }
285
+
286
+ /* ---- 会话 / 请求文字 ---- */
287
+
288
+ const sessionsService = () => {
289
+ try {
290
+ const svc = ctx.get('sessions')
291
+ return svc && typeof svc.get === 'function' ? svc : undefined
292
+ } catch {
293
+ return undefined
294
+ }
295
+ }
296
+
297
+ const sessionById = (sessionId) => {
298
+ if (!sessionId) return undefined
299
+ const svc = sessionsService()
300
+ if (svc) {
301
+ try {
302
+ const found = svc.get(sessionId)
303
+ if (found) return found
304
+ } catch { /* ignore */ }
305
+ }
306
+ return undefined
307
+ }
308
+
309
+ /** 缓存失效判断:同一会话 seq 未变则复用上次预算的文本。 */
310
+ const requestTextOf = (sessionId) => {
311
+ if (!sessionId) return ''
312
+ const session = sessionById(sessionId)
313
+ if (session) {
314
+ let seq
315
+ try { seq = Number(session.seq ?? -1) } catch { seq = -1 }
316
+ const cached = requestCache.get(sessionId)
317
+ if (cached && cached.seq === seq) return cached.text
318
+ const text = lastUserText(session)
319
+ requestCache.set(sessionId, { seq, text })
320
+ return text
321
+ }
322
+ return requestCache.get(sessionId)?.text ?? ''
323
+ }
324
+
325
+ /** 命中白名单则返回 { keyword, text },否则 undefined。 */
326
+ const requestWhitelistHit = (sessionId) => {
327
+ if (cfg.skipRequestKeywords.length === 0) return undefined
328
+ const text = requestTextOf(sessionId)
329
+ const keyword = matchKeyword(text, cfg.skipRequestKeywords)
330
+ if (!keyword) return undefined
331
+ return { keyword, text }
332
+ }
333
+
334
+ /* ---- 文件排队 ---- */
335
+
336
+ const resolveCandidate = (candidate) => {
337
+ if (isAbsolute(candidate)) return candidate
338
+ const roots = []
339
+ try { if (ctx.baseDir) roots.push(ctx.baseDir) } catch { /* ignore */ }
340
+ roots.push(process.cwd())
341
+ for (const root of roots) {
342
+ const joined = resolve(root, candidate)
343
+ if (existsSync(joined)) return joined
344
+ }
345
+ return resolve(process.cwd(), candidate)
346
+ }
347
+
348
+ const enqueue = (candidate, sessionId) => {
349
+ const file = resolveCandidate(candidate)
350
+ if (!file.toLowerCase().endsWith('.docx')) return
351
+ if (!existsSync(file)) return
352
+ if (isSkipped(file, cfg.skipPatterns)) return
353
+ if (formattedByUs.has(file)) return
354
+ let stat
355
+ try { stat = statSync(file) } catch { return }
356
+ if (!cfg.formatExisting && stat.mtimeMs < LOADED_AT) return
357
+ const key = file.toLowerCase()
358
+ if (seen.get(key) === stat.mtimeMs) return
359
+ seen.set(key, stat.mtimeMs)
360
+ if (queue.some((item) => item.file.toLowerCase() === key)) return
361
+ queue.push({ file, sessionId })
362
+ log('info', '[docx-format] queued ' + file)
363
+ }
364
+
365
+ const schedule = () => {
366
+ if (timer) clearTimeout(timer)
367
+ timer = setTimeout(() => {
368
+ timer = undefined
369
+ if (running) return
370
+ void drain()
371
+ }, cfg.debounceMs)
372
+ try { timer.unref?.() } catch { /* ignore */ }
373
+ }
374
+
375
+ const drain = async () => {
376
+ running = true
377
+ try {
378
+ let handled = 0
379
+ while (queue.length > 0 && handled < cfg.maxFilesPerTurn) {
380
+ const job = queue.shift()
381
+ // 出队时再判一次白名单:用户可能在这期间改了要求
382
+ const hit = requestWhitelistHit(job.sessionId)
383
+ if (hit) {
384
+ log('info', '[docx-format] skip ' + job.file + ' — 请求文字含「' + hit.keyword + '」')
385
+ continue
386
+ }
387
+ formattedByUs.add(job.file)
388
+ const report = await formatOne(cfg, python, job.file, 'apply', false)
389
+ handled += 1
390
+ if (report.ok) {
391
+ log('info', '[docx-format] ' + (report.skipped > 0 ? 'skipped ' : 'formatted ') + report.path
392
+ + ' (' + report.changed + ' fixes, ' + report.violations + ' violations)')
393
+ } else {
394
+ log('warn', '[docx-format] failed ' + job.file + ': ' + (report.message ?? 'unknown'))
395
+ }
396
+ }
397
+ } finally {
398
+ running = false
399
+ if (queue.length > 0) schedule()
400
+ }
401
+ }
402
+
403
+ /* ------------------------------------------------- docx_format 工具 */
404
+ const outputSchema = {
405
+ type: 'object',
406
+ properties: {
407
+ ok: { type: 'boolean' },
408
+ path: { type: 'string' },
409
+ mode: { type: 'string' },
410
+ changed: { type: 'integer' },
411
+ violations: { type: 'integer' },
412
+ fixes: { type: 'integer' },
413
+ changedFiles: { type: 'integer' },
414
+ skipped: { type: 'integer' },
415
+ skipReason: { type: 'string' },
416
+ warnings: { type: 'array', items: { type: 'string' } },
417
+ message: { type: 'string' },
418
+ files: { type: 'array', items: { type: 'object', additionalProperties: true } },
419
+ },
420
+ required: ['ok', 'path', 'mode', 'changed', 'violations'],
421
+ additionalProperties: true,
422
+ }
423
+
424
+ const renderReport = (value) => {
425
+ const files = Array.isArray(value?.files) ? value.files : []
426
+ const lines = []
427
+ if (value?.message) lines.push(value.message)
428
+ if (value?.skipped > 0 && files.length <= 1) {
429
+ lines.push('[SKIP] ' + value.path + ' — 白名单命中,未处理(' + (value.skipReason ?? '') + ')')
430
+ return [{ type: 'text', text: lines.join('\n') }]
431
+ }
432
+ if (files.length <= 1) {
433
+ const head = value.ok === false
434
+ ? ('执行失败:' + (value.message ?? '未知错误'))
435
+ : value.mode === 'check'
436
+ ? (value.violations > 0 ? '格式偏差 ' + value.violations + ' 处' : '格式完全符合要求')
437
+ : (value.changed > 0 ? '已修正 ' + value.changed + ' 处' : '无需修改')
438
+ lines.push('[' + (value.ok ? 'OK' : 'FAIL') + '] ' + value.path + ' — ' + head)
439
+ const only = files[0]
440
+ if (only?.rules) {
441
+ for (const [rule, info] of Object.entries(only.rules)) {
442
+ const sample = info?.samples?.[0]
443
+ lines.push(' - ' + rule + ' x' + info.count
444
+ + (sample ? (': ' + sample.where + ' ' + (sample.current ?? '') + ' -> ' + (sample.expected ?? '')) : ''))
445
+ }
446
+ }
447
+ } else {
448
+ lines.push('[' + (value.ok ? 'OK' : 'FAIL') + '] ' + files.length + ' 个文件,修正 '
449
+ + value.changed + ' 处,偏差 ' + value.violations + ' 处'
450
+ + (value.skipped ? (',跳过 ' + value.skipped + ' 个') : ''))
451
+ for (const f of files) {
452
+ lines.push(' - ' + (f.skipped ? 'SKIP' : (f.ok ? 'OK' : 'FAIL')) + ' ' + f.path
453
+ + (f.skipped ? ' (' + (f.skipReason ?? '') + ')' : ' (fixes ' + f.violations + ')'))
454
+ }
455
+ }
456
+ return [{ type: 'text', text: lines.join('\n') }]
457
+ }
458
+
459
+ const toolDefinition = {
460
+ name: 'docx_format',
461
+ description: [
462
+ '把 .docx 规范化为《通用公文格式规范》:方正小标宋简体二号标题、仿宋三号正文、',
463
+ '固定行距 29 磅、首行缩进 2 字符(w:firstLineChars)、段前段后 0 磅、页边距 3.6/3.0/2.7/2.7cm、',
464
+ '表格单元格水平垂直居中与“— 1 —”页码。',
465
+ 'mode=apply 直接改文件(幂等,可重复调用);mode=check 只报告偏差不改文件。',
466
+ '用户请求含“实验报告”等白名单关键词时插件整体停用,本工具会直接返回 skipped;确实需要格式化时传 force=true。',
467
+ ].join(''),
468
+ parameters: {
469
+ type: 'object',
470
+ properties: {
471
+ path: { type: 'string', description: '要处理的 .docx 文件或目录(绝对路径最稳)。' },
472
+ mode: { type: 'string', enum: ['apply', 'check'], description: 'apply=规范化并写回;check=只体检。默认 apply。' },
473
+ recursive: { type: 'boolean', description: 'path 是目录时是否递归子目录。默认 false。' },
474
+ force: { type: 'boolean', description: '忽略请求文字白名单强制处理。默认 false。' },
475
+ },
476
+ required: ['path'],
477
+ additionalProperties: false,
478
+ },
479
+ output: { schema: outputSchema, render: (_args, value) => renderReport(value) },
480
+ async execute(args, exec) {
481
+ const known = new Set(['path', 'mode', 'recursive', 'force'])
482
+ for (const key of Object.keys(args ?? {})) {
483
+ if (!known.has(key)) throw new Error('docx_format: 未知参数 ' + key)
484
+ }
485
+ const target = typeof args?.path === 'string' ? args.path.trim() : ''
486
+ if (!target) throw new Error('docx_format: 缺少 path')
487
+ const mode = args?.mode === 'check' ? 'check' : 'apply'
488
+ const recursive = args?.recursive === true
489
+ const file = resolveCandidate(target)
490
+ if (!existsSync(file)) throw new Error('docx_format: 路径不存在 ' + file)
491
+ if (args?.force !== true) {
492
+ const hit = requestWhitelistHit(exec?.agent?.id)
493
+ if (hit) {
494
+ const reason = '请求文字含白名单关键词「' + hit.keyword + '」,本插件停用'
495
+ log('info', '[docx-format] tool skip ' + file + ' — ' + reason)
496
+ return { ok: true, path: file, mode, changed: 0, violations: 0, fixes: 0,
497
+ changedFiles: 0, skipped: 1, skipReason: reason, warnings: [], files: [] }
498
+ }
499
+ }
500
+ const report = await formatOne(cfg, python, file, mode, recursive)
501
+ if (report.ok && report.changed > 0 && mode === 'apply') formattedByUs.add(file.toLowerCase())
502
+ return report
503
+ },
504
+ }
505
+
506
+ /* ------------------------------------------------------ docx_read 工具 */
507
+
508
+ const readSchema = {
509
+ type: 'object',
510
+ properties: {
511
+ ok: { type: 'boolean' },
512
+ path: { type: 'string' },
513
+ total_chars: { type: 'number' },
514
+ paragraphs: { type: 'number' },
515
+ tables: { type: 'number' },
516
+ offset: { type: 'number' },
517
+ next_offset: { type: 'number' },
518
+ truncated: { type: 'boolean' },
519
+ text: { type: 'string' },
520
+ error: { type: 'string' },
521
+ notes: { type: 'array', items: { type: 'string' } },
522
+ },
523
+ required: ['ok', 'path'],
524
+ additionalProperties: true,
525
+ }
526
+
527
+ const renderRead = (_args, value) => {
528
+ if (!value?.ok) {
529
+ return [{ type: 'text', text: '[FAIL] ' + (value?.path ?? '') + ' — ' + (value?.error ?? '未知错误') }]
530
+ }
531
+ const head = '[OK] ' + value.path + ' — ' + value.total_chars + ' 字 / '
532
+ + value.paragraphs + ' 段 / ' + value.tables + ' 表'
533
+ + (value.offset > 0 ? '(从第 ' + value.offset + ' 字开始)' : '')
534
+ const parts = [head]
535
+ if (Array.isArray(value.notes) && value.notes.length > 0) parts.push('注:' + value.notes.join(';'))
536
+ parts.push('')
537
+ parts.push(value.text ?? '')
538
+ if (value.truncated && typeof value.next_offset === 'number') {
539
+ parts.push('')
540
+ parts.push('…(还有 ' + Math.max(0, value.total_chars - value.next_offset)
541
+ + ' 字未读,继续读就再调一次并把 offset 设为 ' + value.next_offset + ')')
542
+ }
543
+ return [{ type: 'text', text: parts.join('\n') }]
544
+ }
545
+
546
+ const readDefinition = {
547
+ name: 'docx_read',
548
+ description: [
549
+ '读取 .docx 的正文纯文本(自动解包 word/document.xml,只用 Python 标准库,',
550
+ '不需要 python-docx、不需要联网、不会改动原文件)。段落按原顺序输出,表格按「[表] 单元格 | 单元格」输出。',
551
+ '长文档分页:返回 next_offset,需要后续内容时再调一次并传 offset=next_offset。',
552
+ '注意:这个工具只读文字,不含图片与脚注;PPT/Excel/PDF 不要用它。',
553
+ ].join(''),
554
+ parameters: {
555
+ type: 'object',
556
+ properties: {
557
+ path: { type: 'string', description: '.docx 的绝对路径' },
558
+ offset: { type: 'number', description: '从第几个字符开始读,默认 0' },
559
+ max_chars: { type: 'number', description: '本次最多返回多少字符,默认 12000,上限 60000' },
560
+ },
561
+ required: ['path'],
562
+ additionalProperties: false,
563
+ },
564
+ output: { schema: readSchema, render: renderRead },
565
+ async execute(args) {
566
+ const known = new Set(['path', 'offset', 'max_chars'])
567
+ for (const key of Object.keys(args ?? {})) {
568
+ if (!known.has(key)) throw new Error('docx_read: 未知参数 ' + key)
569
+ }
570
+ const target = typeof args?.path === 'string' ? args.path.trim() : ''
571
+ if (!target) throw new Error('docx_read: 缺少 path')
572
+ const file = resolveCandidate(target)
573
+ if (!existsSync(file)) throw new Error('docx_read: 文件不存在 ' + file)
574
+ if (!file.toLowerCase().endsWith('.docx')) throw new Error('docx_read: 只支持 .docx,收到 ' + file)
575
+ const offset = Math.max(0, Math.floor(Number(args?.offset ?? 0)) || 0)
576
+ const requested = Math.floor(Number(args?.max_chars ?? 12000)) || 12000
577
+ const maxChars = Math.min(60000, Math.max(200, requested))
578
+ const run = await runScript(python, READER,
579
+ [file, '--offset', String(offset), '--max-chars', String(maxChars), '--json'], cfg.timeoutMs)
580
+ if (!run.ok) return stripUndefined({ ok: false, path: file, error: run.message })
581
+ const parsed = parseReport(run.stdout)
582
+ if (!parsed) {
583
+ const detail = (run.stderr || run.stdout || '').trim().split('\n').slice(-3).join(' | ')
584
+ return stripUndefined({ ok: false, path: file, error: 'docx_read 输出无法解析:' + detail })
585
+ }
586
+ if (parsed.ok === false) {
587
+ return stripUndefined({
588
+ ok: false, path: file,
589
+ error: parsed.error ?? '抽取失败',
590
+ notes: Array.isArray(parsed.notes) ? parsed.notes : [],
591
+ })
592
+ }
593
+ return stripUndefined({
594
+ ok: true,
595
+ path: parsed.path ?? file,
596
+ total_chars: Number(parsed.total_chars) || 0,
597
+ paragraphs: Number(parsed.paragraphs) || 0,
598
+ tables: Number(parsed.tables) || 0,
599
+ offset: Number(parsed.offset) || 0,
600
+ next_offset: parsed.next_offset ?? undefined,
601
+ truncated: parsed.truncated === true,
602
+ text: String(parsed.text ?? ''),
603
+ notes: Array.isArray(parsed.notes) ? parsed.notes : [],
604
+ })
605
+ },
606
+ }
607
+
608
+ /* ------------------------------------------------------ 提示词规则 */
609
+ const promptText = () => [
610
+ '## Word 公文格式(dsh-docx-format 已启用)',
611
+ '',
612
+ '本会话任何 .docx 都必须符合《通用公文格式规范》,生成的文档会被自动规范化。',
613
+ '写代码生成 docx 时直接照下面这套参数排,不要等插件事后修。',
614
+ '',
615
+ '### 段落(硬规则)',
616
+ '- 所有段落 `w:spacing w:before="0" w:after="0"`,段前段后一律 0 磅、0 行;行距固定值 29 磅(`line=580 lineRule="exact"`)。',
617
+ '- 需要“空一行”时插入真正的空段落,且该空段落的字体/字号/对齐/缩进要与前后文**完全一致**(等于手工回车继承出来的效果):',
618
+ ' 标题上空 2 行、标题下空 1 行 → 段落标记写成方正小标宋简体 二号(22pt)、居中、无首行缩进(`w:pPr/w:rPr` 里写 `w:rFonts` 与 `w:sz=44`);',
619
+ ' 正文/附件/落款之间的空行 → 仿宋 三号(16pt)、两端对齐、首行缩进 2 字符(`w:firstLineChars="200"`、`w:sz=32`)。',
620
+ ' **不要**用段前/段后间距凑高度,也不要让空行落成默认宋体小四左对齐。',
621
+ '',
622
+ '### 缩进(只有特殊缩进,普通缩进一律 0)',
623
+ '- 正文/标题:`<w:ind w:firstLineChars="200"/>`(2 字符,可留 `w:firstLine="640"` 兜底),左/右/悬挂缩进一律 0。',
624
+ ' 禁止写成 `Pt(32)` 之类磅值。',
625
+ '- 附件条目按“手工换行分段落”排,每段只设首行缩进,左/右/悬挂全 0:',
626
+ ' 「附件:1.……」第一段 `firstLineChars="200"`(2 字符);该条目的折行续行单独成段、`firstLineChars="600"`(6 字符);',
627
+ ' 多附件的「2.……」起始段 `firstLineChars="500"`(5 字符)、它的续行仍是 6 字符。',
628
+ ' 不要在附件行写 `leftChars/hangingChars`——Word 会把悬挂量反向加到折行上(折行跑到 8 字符)。',
629
+ '',
630
+ '### 字体字号',
631
+ '- 大标题:方正小标宋简体 二号(22pt),居中。',
632
+ '- 正文:仿宋 三号(16pt),两端对齐。一级标题 黑体三号、二级 楷体三号、三级 仿宋三号,',
633
+ ' 编号形如「一、」「(一)」「1.」(全角点,序号后不加空格)。',
634
+ '- 数字与字母一律 Times New Roman;破折号「——」用 TNR;时间冒号半角。',
635
+ '- 页边距:上 3.6cm / 下 3.0cm / 左 2.7cm / 右 2.7cm。',
636
+ '',
637
+ '### 表格',
638
+ '- 表标题:方正小标宋简体 二号,居中,固定 29 磅;表标题与表格之间插一行空段(行高最小值 0、字号 5 号/10.5pt)。',
639
+ '- 表头 黑体小四(12pt),表内容 仿宋小四(12pt);两字词语中间加两个半角空格(`姓 名`)。',
640
+ '- **每一个单元格的每一段都水平居中**(含表头和内容,`w:jc w:val="center"`),并清掉单元格内的左/右/首行缩进;',
641
+ ' 单元格垂直居中(`w:vAlign w:val="center"`),段落单倍行距。只居中表头不算合规。',
642
+ '- 表格整体居中、无文字环绕;外边框 1.5 磅、内边框 0.5 磅;行高最小值 0.7cm。',
643
+ '',
644
+ '### 图片',
645
+ '- 图片单独成段(不要和正文挤在同一段):**居中**(`w:jc w:val="center"`)、**无缩进**(首行/左/右/悬挂全 0)、**单倍行距**',
646
+ ' (`w:line="240" w:lineRule="auto"`,不要套 29 磅固定值),段前段后仍为 0 磅。',
647
+ '- 图片宽度不超过版心(15.6cm);图注若需要,另起一段居中写「图 1 xxx」。',
648
+ '',
649
+ '### 落款(默认不写)',
650
+ '- **用户没有明确要求署名/日期时,一律不生成落款段落**,写完正文就结束,不要自拟单位名、不要编日期。',
651
+ '- 用户明确要求落款时才写:正文后空两行(两个空段落),右对齐;',
652
+ ' 日期写「2026年10月27日」并在末尾留两个全角空格;署名与日期右边缘对齐(需盖章时署名居中于日期)。',
653
+ '',
654
+ '### 其它',
655
+ '- 页码:页脚居中「— 1 —」,宋体四号(14pt),两侧破折号各留一个空格。',
656
+ '- 附件:正文里「附件:1.xxx」前空一行、首行缩进 2 字符、下与落款空两行;多附件用「2.」等序号,',
657
+ ' 条目之间不再插空行;每条自成一个缩进阶梯(2 / 6 / 5 / 6 字符),靠**真正的分段**实现而不是悬挂缩进:',
658
+ ' 第 1 段 2 字符(「附件:1.」行首)、第 2 段 6 字符(上一段的折行续行)、第 3 段 5 字符(「2.」)、第 4 段 6 字符……',
659
+ ' 折行点由 Word 排版实测得到(`Range.Information(wdFirstCharacterLineNumber)`),插件会自动把长条目拆成多段;',
660
+ ' 引擎(Word/WPS)不可用时退回“首行缩进 2/5 字符、不自动拆段”,折行留给使用者手工换行。',
661
+ ' 文件末尾「附件1」黑体三号、无缩进、无冒号,其下与附件标题空一行。',
662
+ '',
663
+ '### 白名单',
664
+ '- 用户这条要求里出现「实验报告」时,本插件整体停用:不要套用公文格式,按普通报告排版(可直接用默认样式)。',
665
+ '',
666
+ '生成 docx 之后,若不确定版面,调用 docx_format(mode=check 先体检,mode=apply 修复)。',
667
+ '',
668
+ '### 读已有 docx',
669
+ '- 要读 .docx 正文,调用 `docx_read`(path=绝对路径)。不要用 read 工具(会报 binary file),',
670
+ ' 不要 pip install python-docx,不要上网搜。长文档用返回的 next_offset 续读。',
671
+ ].join('\n')
672
+
673
+ if (cfg.tool.enabled) {
674
+ ctx.inject(['tools'], (scope) => {
675
+ scope.effect(() => scope.tools.register(toolDefinition), 'docx-format: docx_format tool')
676
+ scope.effect(() => scope.tools.register(readDefinition), 'docx-format: docx_read tool')
677
+ })
678
+ }
679
+
680
+ if (cfg.prompt.enabled) {
681
+ ctx.inject(['systemPrompt'], (scope) => {
682
+ scope.effect(
683
+ () => scope.systemPrompt.section({
684
+ name: 'dsh-docx-format',
685
+ order: cfg.prompt.order,
686
+ interpolate: false,
687
+ text: promptText,
688
+ }),
689
+ 'docx-format: prompt section',
690
+ )
691
+ })
692
+ }
693
+
694
+ // 缓存用户请求文字(sessions 服务不可用时的兜底来源)
695
+ try {
696
+ ctx.on('session/event', (session, event) => {
697
+ if (event?.type !== 'user/message') return
698
+ const text = messageText(event.data)
699
+ if (text === '') return
700
+ let seq = -1
701
+ try { seq = Number(session?.seq ?? -1) } catch { /* ignore */ }
702
+ requestCache.set(session?.id ?? 'unknown', { seq, text })
703
+ })
704
+ } catch { /* 事件不可用就只依赖 sessions 服务 */ }
705
+
706
+ if (cfg.autoFormat) {
707
+ ctx.inject(['tools'], (scope) => {
708
+ scope.effect(
709
+ () => scope.on('tools/result', (exec, result) => {
710
+ if (exec?.name === 'docx_format') return
711
+ if (result?.isError === true) return
712
+ const sessionId = exec?.agent?.id
713
+ const hit = requestWhitelistHit(sessionId)
714
+ if (hit) {
715
+ log('info', '[docx-format] whitelist hit 「' + hit.keyword + '」 — 本条请求不自动格式化')
716
+ return
717
+ }
718
+ for (const candidate of extractDocxPaths(exec, result)) enqueue(candidate, sessionId)
719
+ schedule()
720
+ }),
721
+ 'docx-format: auto format on tools/result',
722
+ )
723
+ })
724
+ }
725
+
726
+ log('info', '[docx-format] ready python=' + python
727
+ + ' autoFormat=' + cfg.autoFormat
728
+ + ' whitelist=' + JSON.stringify(cfg.skipRequestKeywords))
729
+ }