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