dsh-mcviseron-plugin 0.6.1 → 0.6.2
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/CHANGELOG.md +10 -0
- package/README.en.md +1 -1
- package/README.md +7 -6
- package/docs/automation-task.md +1 -1
- package/docs/release.md +8 -6
- package/lib/auto-review-fix.js +124 -7
- package/lib/client.js +4 -4
- package/lib/index.js +257 -25
- package/lib/task-guard.js +122 -7
- package/package.json +1 -1
- package/src/client/locales.ts +4 -4
- package/src/components/auto-review-fix/index.ts +150 -6
- package/src/components/auto-review-fix/translate.ts +15 -2
- package/src/components/task-guard/index.ts +184 -9
package/src/client/locales.ts
CHANGED
|
@@ -61,7 +61,7 @@ export const zh = {
|
|
|
61
61
|
'form.unavailable': '无法读取插件设置:请确认 profile 中的插件条目 id 为 mcviseron',
|
|
62
62
|
'form.autoSave': '修改后自动保存',
|
|
63
63
|
'form.autoReview.translate': '翻译审批理由',
|
|
64
|
-
'form.autoReview.translateHint': '
|
|
64
|
+
'form.autoReview.translateHint': '英文审查理由会附上中文翻译,并写入审批事件;转手动后被拒时,自动审查理由会作为 notice 交回 AI',
|
|
65
65
|
'form.autoReview.keepPreset': '退出时保持权限预设',
|
|
66
66
|
'form.autoReview.keepPresetHint': '关闭 DSH 时不再把 Auto 会话改成完全访问',
|
|
67
67
|
'form.autoReview.timeout': '翻译超时(毫秒)',
|
|
@@ -85,7 +85,7 @@ export const zh = {
|
|
|
85
85
|
'form.taskGuard.sourceV4': 'v4',
|
|
86
86
|
'form.taskGuard.maxListItems': 'notice 最多列出任务数',
|
|
87
87
|
'form.taskGuard.detectStepIntent': '识别步骤意图',
|
|
88
|
-
'form.taskGuard.detectStepIntentHint': '
|
|
88
|
+
'form.taskGuard.detectStepIntentHint': '识别「Now I will …」等步骤意图,以及「All nets routed」「DRC passes」「原理图完成」等阶段完成语句;命中时提供可直接发送的 todo_write',
|
|
89
89
|
'form.taskGuard.translateTodo': '中文展示 todo 标题',
|
|
90
90
|
'form.taskGuard.translateTodoHint': '只影响 notice 展示,不改写模型写入的 todo',
|
|
91
91
|
'form.taskGuard.todoTimeout': 'todo 翻译超时(毫秒)',
|
|
@@ -157,7 +157,7 @@ export const en = {
|
|
|
157
157
|
'form.unavailable': 'Cannot read the plugin settings: check that the profile entry id is mcviseron',
|
|
158
158
|
'form.autoSave': 'Changes save automatically',
|
|
159
159
|
'form.autoReview.translate': 'Translate the approval reason',
|
|
160
|
-
'form.autoReview.translateHint': 'Appends a Chinese translation to the reviewer note and writes it into the approval event
|
|
160
|
+
'form.autoReview.translateHint': 'Appends a Chinese translation to the reviewer note and writes it into the approval event; a manual rejection returns the auto-review reason to the AI',
|
|
161
161
|
'form.autoReview.keepPreset': 'Keep the permission preset on shutdown',
|
|
162
162
|
'form.autoReview.keepPresetHint': 'Stops DSH from rewriting Auto sessions to Full access while exiting',
|
|
163
163
|
'form.autoReview.timeout': 'Translation timeout (ms)',
|
|
@@ -181,7 +181,7 @@ export const en = {
|
|
|
181
181
|
'form.taskGuard.sourceV4': 'v4',
|
|
182
182
|
'form.taskGuard.maxListItems': 'Maximum tasks listed in a notice',
|
|
183
183
|
'form.taskGuard.detectStepIntent': 'Detect step intent',
|
|
184
|
-
'form.taskGuard.detectStepIntentHint': 'Recognizes “Now I will
|
|
184
|
+
'form.taskGuard.detectStepIntentHint': 'Recognizes step intent (“Now I will …”) and completion statements (“All nets routed”, “DRC passes”); the notice carries a ready todo_write',
|
|
185
185
|
'form.taskGuard.translateTodo': 'Show todo titles in Chinese',
|
|
186
186
|
'form.taskGuard.translateTodoHint': 'Display-only; stored todos are never rewritten',
|
|
187
187
|
'form.taskGuard.todoTimeout': 'Todo translation timeout (ms)',
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
1
2
|
import type { Context } from '@deepseek-ai/cordis'
|
|
2
3
|
import {
|
|
3
4
|
chineseKey,
|
|
4
5
|
cleanTranslation,
|
|
5
6
|
clearTranslationCache,
|
|
6
|
-
|
|
7
|
+
isPredominantlyChinese,
|
|
7
8
|
englishText,
|
|
8
9
|
hasTranslation,
|
|
9
10
|
isAutoReviewText,
|
|
@@ -208,8 +209,9 @@ export async function decorateApprovalRequest(
|
|
|
208
209
|
const excerpt = reviewerExcerpt(english)
|
|
209
210
|
if (excerpt.length === 0 || excerpt.length > settings.maxChars) return request
|
|
210
211
|
// The reviewer already wrote this note in Chinese: appending a "translation"
|
|
211
|
-
// would duplicate the same text
|
|
212
|
-
|
|
212
|
+
// would duplicate the same text. A few quoted Chinese instructions or a
|
|
213
|
+
// Windows path inside an English note are not predominantly Chinese.
|
|
214
|
+
if (isPredominantlyChinese(excerpt)) return request
|
|
213
215
|
if (translationRoute(settings, request) === undefined) return request
|
|
214
216
|
|
|
215
217
|
const llm = serviceOf(scope, 'llm') as { stream?: (options: unknown) => unknown } | undefined
|
|
@@ -232,7 +234,138 @@ export async function decorateApprovalRequest(
|
|
|
232
234
|
}
|
|
233
235
|
|
|
234
236
|
/** Guard the approval seam so the escalation prompt carries a translation. */
|
|
235
|
-
|
|
237
|
+
/** One notice waiting for the denied tool's post-execute pass. */
|
|
238
|
+
interface RejectionNotice {
|
|
239
|
+
id: string
|
|
240
|
+
role: 'user'
|
|
241
|
+
content: [{ type: 'text'; text: string }]
|
|
242
|
+
source: Record<string, unknown>
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
interface RejectionRelay {
|
|
246
|
+
remember(key: string, notice: RejectionNotice): void
|
|
247
|
+
take(key: string): RejectionNotice | undefined
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Session id of an approval request / tool execution. */
|
|
251
|
+
function sessionIdOf(agent: unknown): string {
|
|
252
|
+
const session = (agent as { session?: { id?: unknown } } | undefined)?.session
|
|
253
|
+
return typeof session?.id === 'string' ? session.id : ''
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** DSH session format version, when the agent exposes it. */
|
|
257
|
+
function sessionVersion(agent: unknown): number | undefined {
|
|
258
|
+
const version = (agent as { session?: { header?: { version?: unknown } } } | undefined)?.session?.header?.version
|
|
259
|
+
return typeof version === 'number' ? version : undefined
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function rejectionKey(agent: unknown, callId: unknown): string {
|
|
263
|
+
if (typeof callId !== 'string' || callId === '') return ''
|
|
264
|
+
const sessionId = sessionIdOf(agent)
|
|
265
|
+
return sessionId === '' ? '' : sessionId + ':' + callId
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The localized reviewer reason, falling back to the audited text. */
|
|
269
|
+
function approvalReasonText(request: unknown): string {
|
|
270
|
+
const record = request as { reason?: unknown; displayReason?: unknown }
|
|
271
|
+
const display = record.displayReason
|
|
272
|
+
if (display !== null && typeof display === 'object' && !Array.isArray(display)) {
|
|
273
|
+
const key = chineseKey(display as LocaleText)
|
|
274
|
+
if (key !== undefined) {
|
|
275
|
+
const value = (display as Record<string, unknown>)[key]
|
|
276
|
+
if (typeof value === 'string' && value !== '') return value
|
|
277
|
+
}
|
|
278
|
+
const english = englishText(display as LocaleText)
|
|
279
|
+
if (english !== undefined && english !== '') return english
|
|
280
|
+
}
|
|
281
|
+
return typeof record.reason === 'string' ? record.reason : ''
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Whether this approval is the Auto-review denial that became manual approval. */
|
|
285
|
+
function isAutoReviewApproval(request: unknown): boolean {
|
|
286
|
+
const record = request as { reason?: unknown; displayReason?: unknown }
|
|
287
|
+
if (typeof record.reason === 'string' && isAutoReviewText(record.reason)) return true
|
|
288
|
+
const display = record.displayReason
|
|
289
|
+
if (display !== null && typeof display === 'object' && !Array.isArray(display)) {
|
|
290
|
+
const english = englishText(display as LocaleText)
|
|
291
|
+
if (english !== undefined && isAutoReviewText(english)) return true
|
|
292
|
+
}
|
|
293
|
+
return false
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function rejectionSource(agent: unknown, summary: string): Record<string, unknown> {
|
|
297
|
+
return sessionVersion(agent) === 3
|
|
298
|
+
? { kind: 'plugin', plugin: 'auto-review-fix', form: 'notice', summary }
|
|
299
|
+
: { kind: 'plugin:auto-review-fix', form: 'notice', summary }
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function buildRejectionNotice(agent: unknown, request: unknown): RejectionNotice | undefined {
|
|
303
|
+
const reason = approvalReasonText(request)
|
|
304
|
+
if (reason === '') return undefined
|
|
305
|
+
const toolName = typeof (request as { toolName?: unknown }).toolName === 'string' && (request as { toolName: string }).toolName !== ''
|
|
306
|
+
? (request as { toolName: string }).toolName
|
|
307
|
+
: '未知工具'
|
|
308
|
+
const text = [
|
|
309
|
+
'【审批被拒】工具 "' + toolName + '" 的人工审批被拒绝。',
|
|
310
|
+
'自动审查理由:',
|
|
311
|
+
reason,
|
|
312
|
+
'',
|
|
313
|
+
'请根据该理由调整方案,不要重复同一操作。',
|
|
314
|
+
].join('\n')
|
|
315
|
+
return {
|
|
316
|
+
id: randomUUID(),
|
|
317
|
+
role: 'user',
|
|
318
|
+
content: [{ type: 'text', text }],
|
|
319
|
+
source: rejectionSource(agent, '审批被拒 · ' + toolName),
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function createRejectionRelay(): RejectionRelay {
|
|
324
|
+
const notes = new Map<string, { notice: RejectionNotice; at: number }>()
|
|
325
|
+
const ttl = 120_000
|
|
326
|
+
return {
|
|
327
|
+
remember(key, notice) {
|
|
328
|
+
const now = Date.now()
|
|
329
|
+
for (const [oldKey, entry] of notes) if (now - entry.at > ttl) notes.delete(oldKey)
|
|
330
|
+
if (notes.size >= 50) {
|
|
331
|
+
const oldest = notes.keys().next().value
|
|
332
|
+
if (oldest !== undefined) notes.delete(oldest)
|
|
333
|
+
}
|
|
334
|
+
notes.set(key, { notice, at: now })
|
|
335
|
+
},
|
|
336
|
+
take(key) {
|
|
337
|
+
const entry = notes.get(key)
|
|
338
|
+
if (entry === undefined) return undefined
|
|
339
|
+
notes.delete(key)
|
|
340
|
+
return entry.notice
|
|
341
|
+
},
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const relayedContexts = new WeakSet<object>()
|
|
346
|
+
|
|
347
|
+
function installRejectionRelay(ctx: Context, relay: RejectionRelay): void {
|
|
348
|
+
const target = ctx as unknown as { on?: (event: string, handler: (...args: any[]) => any) => unknown }
|
|
349
|
+
if (typeof target.on !== 'function' || relayedContexts.has(ctx as unknown as object)) return
|
|
350
|
+
relayedContexts.add(ctx as unknown as object)
|
|
351
|
+
target.on.call(ctx, 'tools/post-execute', async (exec: any, result: any, next: () => Promise<any>) => {
|
|
352
|
+
const downstream = (await next()) ?? { kind: 'accept' }
|
|
353
|
+
if (result?.isError !== true) return downstream
|
|
354
|
+
const key = rejectionKey(exec?.agent, exec?.callId)
|
|
355
|
+
if (key === '') return downstream
|
|
356
|
+
const notice = relay.take(key)
|
|
357
|
+
if (notice === undefined) return downstream
|
|
358
|
+
return {
|
|
359
|
+
...downstream,
|
|
360
|
+
additionalContexts: [
|
|
361
|
+
...(Array.isArray(downstream.additionalContexts) ? downstream.additionalContexts : []),
|
|
362
|
+
notice,
|
|
363
|
+
],
|
|
364
|
+
}
|
|
365
|
+
})
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings, relay: RejectionRelay): void {
|
|
236
369
|
whenService(ctx, 'approval', (scope) => {
|
|
237
370
|
const approval = serviceOf(scope, 'approval') as { request?: unknown } | undefined
|
|
238
371
|
if (approval === null || typeof approval !== 'object') return
|
|
@@ -247,7 +380,14 @@ function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings):
|
|
|
247
380
|
} catch {
|
|
248
381
|
decorated = request
|
|
249
382
|
}
|
|
250
|
-
|
|
383
|
+
const outcome = await call.call(this, decorated)
|
|
384
|
+
if (outcome === 'rejected' && isAutoReviewApproval(decorated)) {
|
|
385
|
+
const request = decorated as { agent?: unknown; callId?: unknown }
|
|
386
|
+
const key = rejectionKey(request.agent, request.callId)
|
|
387
|
+
const notice = buildRejectionNotice(request.agent, decorated)
|
|
388
|
+
if (key !== '' && notice !== undefined) relay.remember(key, notice)
|
|
389
|
+
}
|
|
390
|
+
return outcome
|
|
251
391
|
}
|
|
252
392
|
try {
|
|
253
393
|
approval.request = wrapper
|
|
@@ -270,7 +410,11 @@ function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings):
|
|
|
270
410
|
export function installAutoReview(ctx: Context, config?: unknown): void {
|
|
271
411
|
const settings = normalizeConfig(config)
|
|
272
412
|
if (settings.keepPresetGuard) installPresetGuard(ctx)
|
|
273
|
-
if (settings.enabled)
|
|
413
|
+
if (settings.enabled) {
|
|
414
|
+
const relay = createRejectionRelay()
|
|
415
|
+
installRejectionRelay(ctx, relay)
|
|
416
|
+
installApprovalTranslation(ctx, settings, relay)
|
|
417
|
+
}
|
|
274
418
|
}
|
|
275
419
|
|
|
276
420
|
/** Test seam: forget every cached display translation. */
|
|
@@ -77,7 +77,7 @@ export function isAutoReviewText(text: string): boolean {
|
|
|
77
77
|
* translated ("Auto review denied this call: <reason>" -> "<reason>").
|
|
78
78
|
*/
|
|
79
79
|
export function reviewerExcerpt(text: string): string {
|
|
80
|
-
const match = /^\s*auto[\s\-_]*review\s+denied\s+this\s+call\s*[::.]?\s*/i.exec(text)
|
|
80
|
+
const match = /^\s*auto[\s\-_]*review\s+(?:denied\s+this\s+call|拒绝了此调用)\s*[::.]?\s*/i.exec(text)
|
|
81
81
|
if (match === null) return text.trim()
|
|
82
82
|
const rest = text.slice(match[0].length).trim()
|
|
83
83
|
return rest.length === 0 ? text.trim() : rest
|
|
@@ -95,11 +95,24 @@ export function hasTranslation(value: string): boolean {
|
|
|
95
95
|
return value.includes(TRANSLATION_LABEL)
|
|
96
96
|
}
|
|
97
97
|
|
|
98
|
-
/** Whether text already contains CJK characters
|
|
98
|
+
/** Whether text already contains CJK characters. */
|
|
99
99
|
export function containsCjk(text: string): boolean {
|
|
100
100
|
return /[\u3400-\u9fff\uf900-\ufaff]/.test(text)
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
+
/**
|
|
104
|
+
* Whether the reviewer wrote the note in Chinese. A few quoted Chinese
|
|
105
|
+
* instructions or a Windows path inside an English note ("... (\"这个提示框
|
|
106
|
+
* 似乎卡住了?\") ...") must not suppress translation; compare the number of
|
|
107
|
+
* Chinese characters with the number of English word tokens instead.
|
|
108
|
+
*/
|
|
109
|
+
export function isPredominantlyChinese(text: string): boolean {
|
|
110
|
+
const han = (text.match(/[\u3400-\u9fff\uf900-\ufaff]/g) ?? []).length
|
|
111
|
+
if (han === 0) return false
|
|
112
|
+
const englishWords = (text.match(/[A-Za-z][A-Za-z0-9_.-]*/g) ?? []).length
|
|
113
|
+
return englishWords <= Math.max(2, Math.ceil(han / 2))
|
|
114
|
+
}
|
|
115
|
+
|
|
103
116
|
/** Drop wrapping quotes, fences, and stray whitespace a model may add. */
|
|
104
117
|
export function cleanTranslation(raw: string): string {
|
|
105
118
|
let text = raw.trim()
|
|
@@ -37,8 +37,10 @@ export interface TaskGuardConfig {
|
|
|
37
37
|
maxListItems?: number
|
|
38
38
|
/**
|
|
39
39
|
* Watch the assistant's streamed text/reasoning for a step-intent phrase
|
|
40
|
-
* ("Now I will …", "接下来我会 …")
|
|
41
|
-
*
|
|
40
|
+
* ("Now I will …", "接下来我会 …") or a phase-completion statement
|
|
41
|
+
* ("All nets routed", "DRC passes", "原理图完成") and attach one targeted
|
|
42
|
+
* advisory notice with a ready todo_write payload per step. Defaults to
|
|
43
|
+
* `true`; advisory only.
|
|
42
44
|
*/
|
|
43
45
|
detectStepIntent?: boolean
|
|
44
46
|
/** Translate English todo titles in notices into Chinese for display. Defaults to `true`. */
|
|
@@ -215,7 +217,10 @@ const INTENT_MARKERS: RegExp[] = [
|
|
|
215
217
|
/\b(?:now|next|then)\s*,?\s*i(?:'ll| will| am going to|'m going to)\b([^\n]{2,160})/gi,
|
|
216
218
|
/\bi(?:'ll| will| am going to|'m going to)\s+(?:now\s+)?([^\n]{2,160})/gi,
|
|
217
219
|
/\blet me\s+(?:now\s+)?([^\n]{2,160})/gi,
|
|
220
|
+
/\b(?:now|next|then)\s+(?!i(?:'ll| will| am|'m)\b)([a-z][^\n]{2,160})/gi,
|
|
221
|
+
/\b(?:next step|next,)\s*[:\-]?\s*([^\n]{2,160})/gi,
|
|
218
222
|
/(?:接下来|下一步|现在|然后|下面)(?:我会|我将|我要|我来|就开始|开始|准备)([^\n。;;]{2,120})/g,
|
|
223
|
+
/(?:接下来|下一步|现在|然后|下面)(?:开始|进行|做|处理|继续|检查|运行|绘制|布局|布线|导出|放置|连接)([^\n。;;]{2,120})/g,
|
|
219
224
|
]
|
|
220
225
|
|
|
221
226
|
/** One matched step intent. */
|
|
@@ -242,9 +247,31 @@ function intentPhrases(text: string): string[] {
|
|
|
242
247
|
return found.map(item => item.phrase)
|
|
243
248
|
}
|
|
244
249
|
|
|
250
|
+
/** Cross-language phase keywords used to match text to a todo. */
|
|
251
|
+
const PHASE_PATTERNS: ReadonlyArray<{ id: string; pattern: RegExp }> = [
|
|
252
|
+
{ id: 'schematic', pattern: /schematic|原理图/ },
|
|
253
|
+
{ id: 'library', pattern: /library|footprint|器件库|元件库|封装/ },
|
|
254
|
+
{ id: 'board', pattern: /board\s*(?:outline|shape)|板框|边框|外形/ },
|
|
255
|
+
{ id: 'placement', pattern: /placement|layout|布局|摆放/ },
|
|
256
|
+
{ id: 'routing', pattern: /rout(?:e|ing|ed)|track|走线|布线|连线/ },
|
|
257
|
+
{ id: 'drc', pattern: /\bdrc\b|\berc\b|design[_ ]audit|校验|检查/ },
|
|
258
|
+
{ id: 'power', pattern: /power|电源|加粗/ },
|
|
259
|
+
{ id: 'copper', pattern: /copper|pour|铺铜|覆铜/ },
|
|
260
|
+
{ id: 'gerber', pattern: /gerber|export|导出|出图/ },
|
|
261
|
+
{ id: 'usb', pattern: /usb|type-?c/ },
|
|
262
|
+
{ id: 'mcu', pattern: /stm32|\bmcu\b|主控|单片机/ },
|
|
263
|
+
]
|
|
264
|
+
|
|
265
|
+
function phasesOf(value: string): Set<string> {
|
|
266
|
+
const phases = new Set<string>()
|
|
267
|
+
for (const { id, pattern } of PHASE_PATTERNS) if (pattern.test(value)) phases.add(id)
|
|
268
|
+
return phases
|
|
269
|
+
}
|
|
270
|
+
|
|
245
271
|
/**
|
|
246
272
|
* Match the last "Now I will ..." / "接下来我会 ..." phrase against pending
|
|
247
|
-
* todos.
|
|
273
|
+
* todos. Cross-language phase keywords ("PCB" vs "板框", "DRC" vs "校验")
|
|
274
|
+
* carry a match even when the literal tokens differ. Advisory only.
|
|
248
275
|
*
|
|
249
276
|
* @param text - streamed assistant text/reasoning for the current step.
|
|
250
277
|
* @param todos - the current plan.
|
|
@@ -258,11 +285,15 @@ export function detectStepIntent(text: string, todos: TodoItem[]): StepIntentMat
|
|
|
258
285
|
for (const phrase of phrases) {
|
|
259
286
|
const phraseNormalized = normalizeText(phrase)
|
|
260
287
|
const phraseTokens = new Set(tokensOf(phrase))
|
|
288
|
+
const phrasePhases = phasesOf(phrase)
|
|
261
289
|
for (const todo of todos) {
|
|
262
290
|
if (todo.status !== 'pending') continue
|
|
263
291
|
const contentNormalized = normalizeText(todo.content)
|
|
292
|
+
const todoPhases = phasesOf(todo.content)
|
|
264
293
|
let score = 0
|
|
265
|
-
if (
|
|
294
|
+
if ([...phrasePhases].some(phase => todoPhases.has(phase))) {
|
|
295
|
+
score = 1
|
|
296
|
+
} else if (contentNormalized.length >= 4 && (phraseNormalized.includes(contentNormalized) || contentNormalized.includes(phraseNormalized))) {
|
|
266
297
|
score = 1
|
|
267
298
|
} else {
|
|
268
299
|
const contentTokens = tokensOf(todo.content)
|
|
@@ -278,6 +309,86 @@ export function detectStepIntent(text: string, todos: TodoItem[]): StepIntentMat
|
|
|
278
309
|
return best
|
|
279
310
|
}
|
|
280
311
|
|
|
312
|
+
/** Completion wording that normally closes a phase (not partial progress). */
|
|
313
|
+
const COMPLETION_PATTERNS: readonly RegExp[] = [
|
|
314
|
+
/\ball\b[^.!?\n]{0,100}\b(?:routed|connected|placed|done|complete|completed)\b/i,
|
|
315
|
+
/\b(?:schematic|layout|placement|routing|board|design|work|check|drc|erc)\b[^.!?\n]{0,50}\b(?:complete|completed|done|finished|passed|passes|clean)\b/i,
|
|
316
|
+
/\b(?:drc|erc|check|validation)\b[^.!?\n]{0,40}\b(?:passes|passed|clean|0\s+(?:errors?|violations?))\b/i,
|
|
317
|
+
/(?:全部|所有)[^。!?\n]{0,50}(?:布通|连通|完成|通过)|(?:完成|已完成|搞定|通过|布通|连通|无(?:错误|违规)|0\s*(?:错误|违规))/,
|
|
318
|
+
]
|
|
319
|
+
|
|
320
|
+
function isCompletionSentence(sentence: string): boolean {
|
|
321
|
+
return COMPLETION_PATTERNS.some(pattern => pattern.test(sentence))
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Detect a completed phase from the assistant's own wording. With one active
|
|
326
|
+
* task, match that task; without one, match a pending task whose phase
|
|
327
|
+
* keywords occur in the sentence. Partial progress ("44/46 routed") does not
|
|
328
|
+
* match.
|
|
329
|
+
*
|
|
330
|
+
* @param text - streamed assistant text/reasoning for the current step.
|
|
331
|
+
* @param todos - the current plan.
|
|
332
|
+
* @returns the matched todo and the sentence that announced completion.
|
|
333
|
+
*/
|
|
334
|
+
export function detectCompletion(text: string, todos: TodoItem[]): { todo: TodoItem; phrase: string; score: number } | undefined {
|
|
335
|
+
if (text.length === 0 || todos.length === 0) return undefined
|
|
336
|
+
const active = todos.filter(todo => todo.status === 'in_progress')
|
|
337
|
+
if (active.length > 1) return undefined
|
|
338
|
+
const pool = active.length === 1 ? active : todos.filter(todo => todo.status === 'pending')
|
|
339
|
+
if (pool.length === 0) return undefined
|
|
340
|
+
const sentences = text.split(/(?<=[.!?。!?])\s+|\n+/).map(sentence => sentence.trim()).filter(sentence => sentence.length > 0)
|
|
341
|
+
for (const sentence of sentences) {
|
|
342
|
+
if (!isCompletionSentence(sentence)) continue
|
|
343
|
+
const sentencePhases = phasesOf(sentence)
|
|
344
|
+
let best: TodoItem | undefined
|
|
345
|
+
let bestScore = 0
|
|
346
|
+
for (const todo of pool) {
|
|
347
|
+
const todoPhases = phasesOf(todo.content)
|
|
348
|
+
let score = 0
|
|
349
|
+
for (const phase of sentencePhases) if (todoPhases.has(phase)) score += 1
|
|
350
|
+
if (score > bestScore) {
|
|
351
|
+
best = todo
|
|
352
|
+
bestScore = score
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (best === undefined && active.length === 1 && sentencePhases.size === 0) {
|
|
356
|
+
best = active[0]
|
|
357
|
+
bestScore = 0.5
|
|
358
|
+
}
|
|
359
|
+
if (best !== undefined) return { todo: best, phrase: sentence.slice(0, 120), score: bestScore }
|
|
360
|
+
}
|
|
361
|
+
return undefined
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Build a complete todo_write payload for a finished task: mark it completed,
|
|
366
|
+
* mark the next pending task in_progress, and keep every other status.
|
|
367
|
+
*
|
|
368
|
+
* @param todos - the current plan.
|
|
369
|
+
* @param matched - the task the completion sentence refers to.
|
|
370
|
+
* @returns the JSON payload, or undefined when more than one task is active.
|
|
371
|
+
*/
|
|
372
|
+
export function completionPayload(todos: TodoItem[], matched: TodoItem): string | undefined {
|
|
373
|
+
const active = todos.filter(todo => todo.status === 'in_progress')
|
|
374
|
+
if (active.length > 1) return undefined
|
|
375
|
+
const index = todos.findIndex(todo => todo.content === matched.content)
|
|
376
|
+
if (index < 0) return undefined
|
|
377
|
+
const next = todos.find((todo, at) => at > index && todo.status === 'pending')
|
|
378
|
+
?? todos.find((todo, at) => at !== index && todo.status === 'pending')
|
|
379
|
+
const updated = todos.map((todo, at) => ({
|
|
380
|
+
content: todo.content,
|
|
381
|
+
status: at === index
|
|
382
|
+
? 'completed' as const
|
|
383
|
+
: next !== undefined && todo.content === next.content
|
|
384
|
+
? 'in_progress' as const
|
|
385
|
+
: todo.status === 'in_progress' && at !== index
|
|
386
|
+
? 'completed' as const
|
|
387
|
+
: todo.status,
|
|
388
|
+
}))
|
|
389
|
+
return JSON.stringify({ todos: updated })
|
|
390
|
+
}
|
|
391
|
+
|
|
281
392
|
/** Display translation settings for one notice. */
|
|
282
393
|
interface NoticeContext {
|
|
283
394
|
readonly llm?: { stream?: (options: unknown) => unknown }
|
|
@@ -511,7 +622,20 @@ export function installTaskGuard(ctx: Context, input?: TaskGuardConfig): void {
|
|
|
511
622
|
// A "Now I will ..." / "接下来我会 ..." phrase that matches a pending todo is
|
|
512
623
|
// the strongest signal that the plan drifted; one advisory notice per step.
|
|
513
624
|
if (config.detectStepIntent && !state.intentNotifiedThisStep) {
|
|
514
|
-
const
|
|
625
|
+
const buffer = intentBuffers.get(sessionId) ?? ''
|
|
626
|
+
const completed = detectCompletion(buffer, state.todos)
|
|
627
|
+
if (completed !== undefined) {
|
|
628
|
+
state.intentNotifiedThisStep = true
|
|
629
|
+
const notice = await buildCompletionNotice(
|
|
630
|
+
state,
|
|
631
|
+
completed,
|
|
632
|
+
config,
|
|
633
|
+
sourceKindFor(exec.agent, config),
|
|
634
|
+
noticeContext(exec.agent, config, ctx),
|
|
635
|
+
)
|
|
636
|
+
return attachContext(downstream, notice)
|
|
637
|
+
}
|
|
638
|
+
const match = detectStepIntent(buffer, state.todos)
|
|
515
639
|
if (match !== undefined) {
|
|
516
640
|
state.intentNotifiedThisStep = true
|
|
517
641
|
const notice = await buildIntentNotice(
|
|
@@ -811,21 +935,34 @@ async function buildReminder(
|
|
|
811
935
|
const omitted = remaining.length - config.maxListItems
|
|
812
936
|
const items = omitted > 0 ? quoted + '\n… +' + omitted : quoted
|
|
813
937
|
|
|
938
|
+
const activeOne = active.length === 1 ? active[0] : undefined
|
|
939
|
+
const suggested = activeOne === undefined ? undefined : completionPayload(todos, activeOne)
|
|
940
|
+
|
|
814
941
|
const text = config.locale === 'en'
|
|
815
942
|
? [
|
|
816
943
|
'[Todo sync] ' + state.callsSinceWrite + ' tool calls have run since the last todo_write.',
|
|
817
944
|
'In progress: ' + activeText,
|
|
818
945
|
'Remaining:\n' + items,
|
|
819
|
-
|
|
946
|
+
activeOne === undefined
|
|
947
|
+
? 'If the current phase is finished, call todo_write: mark completed work completed and the next task in_progress (never leave pending work with no active task).'
|
|
948
|
+
: suggested === undefined
|
|
949
|
+
? 'If the current phase is finished, call todo_write: mark it completed and the next task in_progress (never leave pending work with no active task).'
|
|
950
|
+
: 'If the current phase is finished, send this todo_write now; if it is still running, keep that task in_progress and leave the list unchanged:',
|
|
951
|
+
suggested ?? '',
|
|
820
952
|
'(Tip: todo titles can be written in Chinese.)',
|
|
821
|
-
].join('\n')
|
|
953
|
+
].filter(line => line !== '').join('\n')
|
|
822
954
|
: [
|
|
823
955
|
'【todo 同步】距上次 todo_write 已过 ' + state.callsSinceWrite + ' 次工具调用。',
|
|
824
956
|
'进行中:' + activeText,
|
|
825
957
|
'剩余:\n' + items,
|
|
826
|
-
|
|
958
|
+
activeOne === undefined
|
|
959
|
+
? '如果当前阶段已经完成,请调用 todo_write:把已完成阶段标为 completed,并把下一阶段标为 in_progress(有剩余任务时不要留空)。'
|
|
960
|
+
: suggested === undefined
|
|
961
|
+
? '如果当前阶段已经完成,请调用 todo_write:把该阶段标为 completed,并把下一阶段标为 in_progress(有剩余任务时不要留空)。'
|
|
962
|
+
: '如果当前阶段已经完成,请直接发送以下 todo_write;如果仍在进行,请保持该待办为 in_progress,无需改动清单:',
|
|
963
|
+
suggested ?? '',
|
|
827
964
|
'(提示:todo 内容可以直接用中文书写。)',
|
|
828
|
-
].join('\n')
|
|
965
|
+
].filter(line => line !== '').join('\n')
|
|
829
966
|
|
|
830
967
|
const summary = config.locale === 'en'
|
|
831
968
|
? 'todo stale · ' + state.callsSinceWrite + ' calls'
|
|
@@ -834,6 +971,44 @@ async function buildReminder(
|
|
|
834
971
|
return createNotice(text, summary, sourceKind)
|
|
835
972
|
}
|
|
836
973
|
|
|
974
|
+
async function buildCompletionNotice(
|
|
975
|
+
state: SessionState,
|
|
976
|
+
match: { todo: TodoItem; phrase: string },
|
|
977
|
+
config: ResolvedConfig,
|
|
978
|
+
sourceKind: 'v3' | 'v4',
|
|
979
|
+
context: NoticeContext,
|
|
980
|
+
): Promise<NoticeMessage> {
|
|
981
|
+
const todos = state.todos ?? []
|
|
982
|
+
const [display] = await displayTodoContents([match.todo.content], context)
|
|
983
|
+
const suggested = completionPayload(todos, match.todo)
|
|
984
|
+
const phrase = truncate(match.phrase, 80)
|
|
985
|
+
const text = config.locale === 'en'
|
|
986
|
+
? [
|
|
987
|
+
'[Todo sync] The assistant text looks like a completed phase: "' + display + '".',
|
|
988
|
+
'Source: ' + phrase,
|
|
989
|
+
suggested === undefined
|
|
990
|
+
? 'If that phase is finished, call todo_write: mark it completed and the next task in_progress.'
|
|
991
|
+
: 'If that phase is finished, send this todo_write now:',
|
|
992
|
+
suggested ?? '',
|
|
993
|
+
'If it is still running, keep that task in_progress; do not mark it completed yet.',
|
|
994
|
+
'(Tip: todo titles can be written in Chinese.)',
|
|
995
|
+
].filter(line => line !== '').join('\n')
|
|
996
|
+
: [
|
|
997
|
+
'【todo 同步】检测到阶段完成:「' + display + '」',
|
|
998
|
+
'依据:' + phrase,
|
|
999
|
+
suggested === undefined
|
|
1000
|
+
? '如果该阶段已完成,请调用 todo_write:把该待办标为 completed,并把下一阶段标为 in_progress。'
|
|
1001
|
+
: '如果该阶段确实已完成,请直接发送以下 todo_write:',
|
|
1002
|
+
suggested ?? '',
|
|
1003
|
+
'如果仍在进行,请保持该待办为 in_progress,不要提前标 completed。',
|
|
1004
|
+
'(提示:todo 内容可以直接用中文书写。)',
|
|
1005
|
+
].filter(line => line !== '').join('\n')
|
|
1006
|
+
const summary = config.locale === 'en'
|
|
1007
|
+
? 'todo complete · ' + truncate(display, 40)
|
|
1008
|
+
: 'todo 完成 · ' + truncate(display, 40)
|
|
1009
|
+
return createNotice(text, summary, sourceKind)
|
|
1010
|
+
}
|
|
1011
|
+
|
|
837
1012
|
async function buildIntentNotice(
|
|
838
1013
|
state: SessionState,
|
|
839
1014
|
match: StepIntentMatch,
|