dsh-mcviseron-plugin 0.0.0-stage → 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 +222 -0
- package/CONTRIBUTING.md +60 -0
- package/LICENSE +202 -0
- package/README.en.md +146 -0
- package/README.md +287 -2
- package/SECURITY.md +38 -0
- package/cordis.patch.yml +12 -0
- package/docs/automation-task.md +63 -0
- package/docs/migration-from-standalone.md +115 -0
- package/docs/release.md +85 -0
- package/lib/appearance.js +320 -0
- package/lib/auto-review-fix.js +453 -0
- package/lib/client.js +1266 -0
- package/lib/index.js +1701 -0
- package/lib/restart.js +226 -0
- package/lib/task-guard.js +736 -0
- package/package.json +148 -4
- package/scripts/repair-profile.mjs +77 -0
- package/src/api.ts +5 -0
- package/src/appearance/index.ts +103 -0
- package/src/auto-review-fix/index.ts +45 -0
- package/src/client/AppearanceScheduleRow.tsx +112 -0
- package/src/client/ConfigForm.tsx +284 -0
- package/src/client/FallbackRestartRow.tsx +23 -0
- package/src/client/RestartCard.tsx +108 -0
- package/src/client/SettingsSection.tsx +110 -0
- package/src/client/bridge.ts +131 -0
- package/src/client/driver.ts +166 -0
- package/src/client/index.ts +114 -0
- package/src/client/locales.ts +193 -0
- package/src/client/primitives.d.ts +15 -0
- package/src/client/section-presence.ts +33 -0
- package/src/client/styles.ts +154 -0
- package/src/components/auto-review-fix/index.ts +421 -0
- package/src/components/auto-review-fix/translate.ts +235 -0
- package/src/components/task-guard/index.ts +1077 -0
- package/src/index.ts +71 -0
- package/src/loopback.ts +48 -0
- package/src/namespace.ts +7 -0
- package/src/restart/index.ts +268 -0
- package/src/routes.ts +228 -0
- package/src/schedule.ts +125 -0
- package/src/task-guard/index.ts +52 -0
- package/src/volatile.ts +32 -0
|
@@ -0,0 +1,1077 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Public component configuration. Every field is optional; invalid values fail
|
|
6
|
+
* at plugin load instead of degrading.
|
|
7
|
+
*/
|
|
8
|
+
export interface TaskGuardConfig {
|
|
9
|
+
/** Master switch. Defaults to `true`. */
|
|
10
|
+
enabled?: boolean
|
|
11
|
+
/** Language of the model-facing guard text. Defaults to `zh`. */
|
|
12
|
+
locale?: 'zh' | 'en'
|
|
13
|
+
/** Successful tool calls allowed after a `todo_write` before the first notice. Defaults to 5. */
|
|
14
|
+
staleAfterCalls?: number
|
|
15
|
+
/** Tool calls between later notices; `0` sends the first notice only. Defaults to 4. */
|
|
16
|
+
repeatEveryCalls?: number
|
|
17
|
+
/** Hard stop after this many stale calls; `0` disables blocking. Defaults to 0. */
|
|
18
|
+
blockAfterCalls?: number
|
|
19
|
+
/**
|
|
20
|
+
* Reject a `todo_write` that leaves pending work with no `in_progress` task.
|
|
21
|
+
* Off by default: the default mode only adds an advisory notice, so a write
|
|
22
|
+
* is never turned into a tool error.
|
|
23
|
+
*/
|
|
24
|
+
rejectMissingActive?: boolean
|
|
25
|
+
/**
|
|
26
|
+
* Notice source kind. `auto` (default) reads `session.header.version`:
|
|
27
|
+
* format v3 uses `{ kind: 'plugin', plugin: 'task-guard' }`, v4 uses
|
|
28
|
+
* `{ kind: 'plugin:task-guard' }`. Force `v3`/`v4` only for unusual
|
|
29
|
+
* deployments.
|
|
30
|
+
*/
|
|
31
|
+
sourceKind?: 'auto' | 'v3' | 'v4'
|
|
32
|
+
/** Only these tool names advance the stale counter; empty covers every tool. */
|
|
33
|
+
include?: string[]
|
|
34
|
+
/** Tool names that never advance the stale counter. Defaults to `todo_write`, `ask_user_question`. */
|
|
35
|
+
exclude?: string[]
|
|
36
|
+
/** Remaining items quoted in a notice. Defaults to 6. */
|
|
37
|
+
maxListItems?: number
|
|
38
|
+
/**
|
|
39
|
+
* Watch the assistant's streamed text/reasoning for a step-intent phrase
|
|
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.
|
|
44
|
+
*/
|
|
45
|
+
detectStepIntent?: boolean
|
|
46
|
+
/** Translate English todo titles in notices into Chinese for display. Defaults to `true`. */
|
|
47
|
+
translateTodoContent?: boolean
|
|
48
|
+
/** Timeout for one batch todo translation, 500–15000ms. Defaults to 3000. */
|
|
49
|
+
todoTranslationTimeoutMs?: number
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type TodoStatus = 'pending' | 'in_progress' | 'completed'
|
|
53
|
+
|
|
54
|
+
interface TodoItem {
|
|
55
|
+
content: string
|
|
56
|
+
status: TodoStatus
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface PluginSourceV4 {
|
|
60
|
+
kind: 'plugin:task-guard'
|
|
61
|
+
form: 'notice'
|
|
62
|
+
summary: string
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface PluginSourceV3 {
|
|
66
|
+
kind: 'plugin'
|
|
67
|
+
plugin: 'task-guard'
|
|
68
|
+
form: 'notice'
|
|
69
|
+
summary: string
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
type PluginSource = PluginSourceV4 | PluginSourceV3
|
|
73
|
+
|
|
74
|
+
interface NoticeMessage {
|
|
75
|
+
id: string
|
|
76
|
+
role: 'user'
|
|
77
|
+
content: [{ type: 'text'; text: string }]
|
|
78
|
+
source: PluginSource
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface AgentLike {
|
|
82
|
+
readonly session?: {
|
|
83
|
+
readonly id?: unknown
|
|
84
|
+
readonly header?: { readonly version?: unknown }
|
|
85
|
+
readonly requestHeader?: () => unknown
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** One transient assistant frame (see `agent/assistant-stream`). */
|
|
90
|
+
interface AssistantFrame {
|
|
91
|
+
readonly type?: unknown
|
|
92
|
+
readonly attemptId?: unknown
|
|
93
|
+
readonly chunk?: { readonly type?: unknown; readonly text?: unknown; readonly reason?: { readonly kind?: unknown } }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
interface AssistantStreamPayload {
|
|
97
|
+
readonly frame?: AssistantFrame
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface ToolExecutionLike {
|
|
101
|
+
readonly name: string
|
|
102
|
+
readonly arguments: unknown
|
|
103
|
+
readonly parent?: unknown
|
|
104
|
+
readonly agent?: AgentLike
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
interface ToolResultLike {
|
|
108
|
+
readonly isError: boolean
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
type PreToolDecision =
|
|
112
|
+
| { kind: 'allow' }
|
|
113
|
+
| { kind: 'deny'; reason: string }
|
|
114
|
+
| { kind: 'ask'; reason?: string }
|
|
115
|
+
|
|
116
|
+
interface PostToolDecision {
|
|
117
|
+
readonly kind: 'accept' | 'block'
|
|
118
|
+
readonly additionalContexts?: NoticeMessage[]
|
|
119
|
+
readonly [key: string]: unknown
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
interface PreStepPayload {
|
|
123
|
+
agent: AgentLike
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The subset of the Cordis plugin context this component needs. */
|
|
127
|
+
export interface TaskGuardBus {
|
|
128
|
+
on(
|
|
129
|
+
event: 'tools/pre-execute',
|
|
130
|
+
listener: (exec: ToolExecutionLike, next: () => Promise<PreToolDecision>) => Promise<PreToolDecision>,
|
|
131
|
+
): unknown
|
|
132
|
+
on(
|
|
133
|
+
event: 'tools/post-execute',
|
|
134
|
+
listener: (exec: ToolExecutionLike, result: ToolResultLike, next: () => Promise<PostToolDecision>) => Promise<PostToolDecision>,
|
|
135
|
+
): unknown
|
|
136
|
+
on(
|
|
137
|
+
event: 'agent/pre-step',
|
|
138
|
+
listener: (payload: PreStepPayload, next: () => Promise<unknown>) => Promise<unknown>,
|
|
139
|
+
): unknown
|
|
140
|
+
on(
|
|
141
|
+
event: 'session/event',
|
|
142
|
+
listener: (session: { id?: unknown }, event: { type: string; data?: unknown }) => void,
|
|
143
|
+
): unknown
|
|
144
|
+
on(
|
|
145
|
+
event: 'agent/assistant-stream',
|
|
146
|
+
listener: (payload: AssistantStreamPayload) => void,
|
|
147
|
+
): unknown
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
interface SessionState {
|
|
151
|
+
todos: TodoItem[] | null
|
|
152
|
+
callsSinceWrite: number
|
|
153
|
+
remindersSent: number
|
|
154
|
+
reminderDeliveredThisStep: boolean
|
|
155
|
+
/** One step-intent notice per step at most. */
|
|
156
|
+
intentNotifiedThisStep: boolean
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
interface ResolvedConfig {
|
|
160
|
+
enabled: boolean
|
|
161
|
+
locale: 'zh' | 'en'
|
|
162
|
+
staleAfterCalls: number
|
|
163
|
+
repeatEveryCalls: number
|
|
164
|
+
blockAfterCalls: number
|
|
165
|
+
rejectMissingActive: boolean
|
|
166
|
+
sourceKind: 'auto' | 'v3' | 'v4'
|
|
167
|
+
include: RegExp[]
|
|
168
|
+
exclude: RegExp[]
|
|
169
|
+
maxListItems: number
|
|
170
|
+
detectStepIntent: boolean
|
|
171
|
+
translateTodoContent: boolean
|
|
172
|
+
todoTranslationTimeoutMs: number
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const SUMMARY_MAX_CHARS = 120
|
|
176
|
+
const DEFAULT_EXCLUDES = ['todo_write', 'ask_user_question']
|
|
177
|
+
const STATUSES: ReadonlySet<string> = new Set(['pending', 'in_progress', 'completed'])
|
|
178
|
+
const CONFIG_KEYS: ReadonlySet<string> = new Set([
|
|
179
|
+
'enabled',
|
|
180
|
+
'locale',
|
|
181
|
+
'staleAfterCalls',
|
|
182
|
+
'repeatEveryCalls',
|
|
183
|
+
'blockAfterCalls',
|
|
184
|
+
'rejectMissingActive',
|
|
185
|
+
'sourceKind',
|
|
186
|
+
'include',
|
|
187
|
+
'exclude',
|
|
188
|
+
'maxListItems',
|
|
189
|
+
'detectStepIntent',
|
|
190
|
+
'translateTodoContent',
|
|
191
|
+
'todoTranslationTimeoutMs',
|
|
192
|
+
])
|
|
193
|
+
|
|
194
|
+
/** Whether text already contains CJK characters (no translation needed). */
|
|
195
|
+
function containsCjk(text: string): boolean {
|
|
196
|
+
return /[\u3400-\u9fff\uf900-\ufaff]/.test(text)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Lowercase and strip markdown noise for token comparison. */
|
|
200
|
+
function normalizeText(value: string): string {
|
|
201
|
+
return value.toLowerCase().replace(/[\`*_#>\[\](){}]+/g, ' ').replace(/\s+/g, ' ').trim()
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Comparable tokens: latin words of 3+ chars plus CJK bigrams. */
|
|
205
|
+
function tokensOf(value: string): string[] {
|
|
206
|
+
const normalized = normalizeText(value)
|
|
207
|
+
const tokens: string[] = []
|
|
208
|
+
for (const token of normalized.split(/[^a-z0-9\u4e00-\u9fff]+/)) {
|
|
209
|
+
if (token.length >= 3) tokens.push(token)
|
|
210
|
+
}
|
|
211
|
+
const chars = Array.from(normalized).filter(char => /[\u4e00-\u9fff]/.test(char))
|
|
212
|
+
for (let index = 0; index + 1 < chars.length; index += 1) tokens.push(chars[index] + chars[index + 1])
|
|
213
|
+
return tokens
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const INTENT_MARKERS: RegExp[] = [
|
|
217
|
+
/\b(?:now|next|then)\s*,?\s*i(?:'ll| will| am going to|'m going to)\b([^\n]{2,160})/gi,
|
|
218
|
+
/\bi(?:'ll| will| am going to|'m going to)\s+(?:now\s+)?([^\n]{2,160})/gi,
|
|
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,
|
|
222
|
+
/(?:接下来|下一步|现在|然后|下面)(?:我会|我将|我要|我来|就开始|开始|准备)([^\n。;;]{2,120})/g,
|
|
223
|
+
/(?:接下来|下一步|现在|然后|下面)(?:开始|进行|做|处理|继续|检查|运行|绘制|布局|布线|导出|放置|连接)([^\n。;;]{2,120})/g,
|
|
224
|
+
]
|
|
225
|
+
|
|
226
|
+
/** One matched step intent. */
|
|
227
|
+
export interface StepIntentMatch {
|
|
228
|
+
todo: TodoItem
|
|
229
|
+
phrase: string
|
|
230
|
+
score: number
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** The step-intent phrases found in streamed text, in stream order. */
|
|
234
|
+
function intentPhrases(text: string): string[] {
|
|
235
|
+
const found: Array<{ index: number; phrase: string }> = []
|
|
236
|
+
for (const marker of INTENT_MARKERS) {
|
|
237
|
+
marker.lastIndex = 0
|
|
238
|
+
let match = marker.exec(text)
|
|
239
|
+
while (match !== null) {
|
|
240
|
+
const raw = (match[1] ?? '').trim()
|
|
241
|
+
const phrase = raw.replace(/^[::,\-\s]+/, '').split(/[.。!!??;;\n]/)[0].trim()
|
|
242
|
+
if (phrase.length >= 2) found.push({ index: match.index, phrase })
|
|
243
|
+
match = marker.exec(text)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
found.sort((left, right) => left.index - right.index)
|
|
247
|
+
return found.map(item => item.phrase)
|
|
248
|
+
}
|
|
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
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Match the last "Now I will ..." / "接下来我会 ..." phrase against pending
|
|
273
|
+
* todos. Cross-language phase keywords ("PCB" vs "板框", "DRC" vs "校验")
|
|
274
|
+
* carry a match even when the literal tokens differ. Advisory only.
|
|
275
|
+
*
|
|
276
|
+
* @param text - streamed assistant text/reasoning for the current step.
|
|
277
|
+
* @param todos - the current plan.
|
|
278
|
+
* @returns the best pending match, if any.
|
|
279
|
+
*/
|
|
280
|
+
export function detectStepIntent(text: string, todos: TodoItem[]): StepIntentMatch | undefined {
|
|
281
|
+
if (text.length === 0 || todos.length === 0) return undefined
|
|
282
|
+
const phrases = intentPhrases(text).slice(-3)
|
|
283
|
+
if (phrases.length === 0) return undefined
|
|
284
|
+
let best: StepIntentMatch | undefined
|
|
285
|
+
for (const phrase of phrases) {
|
|
286
|
+
const phraseNormalized = normalizeText(phrase)
|
|
287
|
+
const phraseTokens = new Set(tokensOf(phrase))
|
|
288
|
+
const phrasePhases = phasesOf(phrase)
|
|
289
|
+
for (const todo of todos) {
|
|
290
|
+
if (todo.status !== 'pending') continue
|
|
291
|
+
const contentNormalized = normalizeText(todo.content)
|
|
292
|
+
const todoPhases = phasesOf(todo.content)
|
|
293
|
+
let score = 0
|
|
294
|
+
if ([...phrasePhases].some(phase => todoPhases.has(phase))) {
|
|
295
|
+
score = 1
|
|
296
|
+
} else if (contentNormalized.length >= 4 && (phraseNormalized.includes(contentNormalized) || contentNormalized.includes(phraseNormalized))) {
|
|
297
|
+
score = 1
|
|
298
|
+
} else {
|
|
299
|
+
const contentTokens = tokensOf(todo.content)
|
|
300
|
+
if (contentTokens.length === 0) continue
|
|
301
|
+
let shared = 0
|
|
302
|
+
for (const token of contentTokens) if (phraseTokens.has(token)) shared += 1
|
|
303
|
+
score = shared / contentTokens.length
|
|
304
|
+
if (shared < 2 && score < 0.6) continue
|
|
305
|
+
}
|
|
306
|
+
if (score >= 0.6 && (best === undefined || score > best.score)) best = { todo, phrase, score }
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return best
|
|
310
|
+
}
|
|
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
|
+
|
|
392
|
+
/** Display translation settings for one notice. */
|
|
393
|
+
interface NoticeContext {
|
|
394
|
+
readonly llm?: { stream?: (options: unknown) => unknown }
|
|
395
|
+
readonly route?: { provider: string; model: string }
|
|
396
|
+
readonly translate: boolean
|
|
397
|
+
readonly timeoutMs: number
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function serviceOf(scope: Context, name: string): unknown {
|
|
401
|
+
try {
|
|
402
|
+
const direct = (scope as unknown as Record<string, unknown>)[name]
|
|
403
|
+
if (direct !== undefined) return direct
|
|
404
|
+
} catch {
|
|
405
|
+
/* fall through to the registry */
|
|
406
|
+
}
|
|
407
|
+
try {
|
|
408
|
+
const get = (scope as unknown as { get?: (key: string) => unknown }).get
|
|
409
|
+
return typeof get === 'function' ? get.call(scope, name) : undefined
|
|
410
|
+
} catch {
|
|
411
|
+
return undefined
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function sessionRoute(agent: AgentLike | undefined): { provider: string; model: string } | undefined {
|
|
416
|
+
try {
|
|
417
|
+
const read = agent?.session?.requestHeader
|
|
418
|
+
const header = typeof read === 'function' ? read.call(agent?.session) : undefined
|
|
419
|
+
const config = (header as { config?: { provider?: unknown; model?: unknown } } | null)?.config
|
|
420
|
+
const provider = config?.provider
|
|
421
|
+
const model = config?.model
|
|
422
|
+
if (typeof provider === 'string' && provider.length > 0 && typeof model === 'string' && model.length > 0) {
|
|
423
|
+
return { provider, model }
|
|
424
|
+
}
|
|
425
|
+
} catch {
|
|
426
|
+
/* a host without a readable header simply has no route */
|
|
427
|
+
}
|
|
428
|
+
return undefined
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function noticeContext(agent: AgentLike | undefined, config: ResolvedConfig, ctx: Context): NoticeContext {
|
|
432
|
+
const route = sessionRoute(agent)
|
|
433
|
+
const llm = serviceOf(ctx, 'llm') as NoticeContext['llm']
|
|
434
|
+
return {
|
|
435
|
+
llm,
|
|
436
|
+
route,
|
|
437
|
+
translate: config.translateTodoContent && route !== undefined && llm !== undefined,
|
|
438
|
+
timeoutMs: config.todoTranslationTimeoutMs,
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const TRANSLATION_CACHE_LIMIT = 256
|
|
443
|
+
const translationCache = new Map<string, string>()
|
|
444
|
+
|
|
445
|
+
function parseStringArray(raw: string): string[] | undefined {
|
|
446
|
+
const start = raw.indexOf('[')
|
|
447
|
+
const end = raw.lastIndexOf(']')
|
|
448
|
+
if (start < 0 || end <= start) return undefined
|
|
449
|
+
try {
|
|
450
|
+
const value = JSON.parse(raw.slice(start, end + 1)) as unknown
|
|
451
|
+
if (Array.isArray(value) && value.every(item => typeof item === 'string')) return value as string[]
|
|
452
|
+
} catch {
|
|
453
|
+
/* malformed model output falls back to the original titles */
|
|
454
|
+
}
|
|
455
|
+
return undefined
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
async function translateBatch(contents: string[], context: NoticeContext): Promise<string[] | undefined> {
|
|
459
|
+
if (context.llm === undefined || typeof context.llm.stream !== 'function' || context.route === undefined) return undefined
|
|
460
|
+
const controller = new AbortController()
|
|
461
|
+
const timer = setTimeout(() => controller.abort(new Error('todo translation timeout')), context.timeoutMs)
|
|
462
|
+
try {
|
|
463
|
+
const stream = await context.llm.stream({
|
|
464
|
+
provider: context.route.provider,
|
|
465
|
+
model: context.route.model,
|
|
466
|
+
system: 'Translate the items of a software todo list into Simplified Chinese. Output only a JSON array of strings with the same length and order. Keep code, file paths, identifiers, acronyms and URLs exactly as written.',
|
|
467
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: JSON.stringify(contents) }] }],
|
|
468
|
+
temperature: 0,
|
|
469
|
+
signal: controller.signal,
|
|
470
|
+
})
|
|
471
|
+
if (stream === null || typeof stream !== 'object') return undefined
|
|
472
|
+
let text = ''
|
|
473
|
+
for await (const chunk of stream as AsyncIterable<{ type?: unknown; text?: unknown; reason?: { kind?: unknown } }>) {
|
|
474
|
+
if (controller.signal.aborted) return undefined
|
|
475
|
+
if (chunk?.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text
|
|
476
|
+
if (chunk?.type === 'finish') {
|
|
477
|
+
const kind = chunk.reason?.kind
|
|
478
|
+
if (typeof kind === 'string' && kind !== 'stop') return undefined
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const parsed = parseStringArray(text)
|
|
482
|
+
if (parsed === undefined || parsed.length !== contents.length) return undefined
|
|
483
|
+
return parsed
|
|
484
|
+
} catch {
|
|
485
|
+
return undefined
|
|
486
|
+
} finally {
|
|
487
|
+
clearTimeout(timer)
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** Race a promise against a hard timeout so a stalled stream cannot delay a notice. */
|
|
492
|
+
async function withTimeout<T>(value: Promise<T>, ms: number): Promise<T | undefined> {
|
|
493
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
494
|
+
const timeout = new Promise<undefined>((resolve) => {
|
|
495
|
+
timer = setTimeout(() => resolve(undefined), ms)
|
|
496
|
+
timer.unref?.()
|
|
497
|
+
})
|
|
498
|
+
try {
|
|
499
|
+
return await Promise.race([value, timeout])
|
|
500
|
+
} finally {
|
|
501
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** Translate English todo titles for display as "中文(English)". */
|
|
506
|
+
async function displayTodoContents(contents: string[], context: NoticeContext): Promise<string[]> {
|
|
507
|
+
if (!context.translate) return contents
|
|
508
|
+
const pending: string[] = []
|
|
509
|
+
const seen = new Set<string>()
|
|
510
|
+
for (const content of contents) {
|
|
511
|
+
if (containsCjk(content) || translationCache.has(content) || seen.has(content)) continue
|
|
512
|
+
seen.add(content)
|
|
513
|
+
pending.push(content)
|
|
514
|
+
}
|
|
515
|
+
if (pending.length > 0) {
|
|
516
|
+
const translated = await withTimeout(translateBatch(pending, context), context.timeoutMs + 250)
|
|
517
|
+
if (translated !== undefined) {
|
|
518
|
+
for (let index = 0; index < pending.length; index += 1) {
|
|
519
|
+
const value = translated[index]
|
|
520
|
+
if (typeof value !== 'string' || value.trim() === '') continue
|
|
521
|
+
if (translationCache.size >= TRANSLATION_CACHE_LIMIT) {
|
|
522
|
+
const oldest = translationCache.keys().next()
|
|
523
|
+
if (oldest.done !== true) translationCache.delete(oldest.value)
|
|
524
|
+
}
|
|
525
|
+
translationCache.set(pending[index], value.trim())
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
return contents.map((content) => {
|
|
530
|
+
const translated = translationCache.get(content)
|
|
531
|
+
if (translated === undefined || containsCjk(content)) return content
|
|
532
|
+
return translated + '(' + content + ')'
|
|
533
|
+
})
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** A ready-to-send todo_write payload for the matched pending task. */
|
|
537
|
+
function suggestedTodoPayload(todos: TodoItem[], matched: TodoItem): string | undefined {
|
|
538
|
+
const active = todos.filter(todo => todo.status === 'in_progress')
|
|
539
|
+
if (active.length > 1) return undefined
|
|
540
|
+
const next = todos.map(todo => ({
|
|
541
|
+
content: todo.content,
|
|
542
|
+
status: todo.content === matched.content ? 'in_progress' : todo.status === 'in_progress' ? 'completed' : todo.status,
|
|
543
|
+
}))
|
|
544
|
+
return JSON.stringify({ todos: next })
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Install the todo plan guard on the master plugin context.
|
|
549
|
+
*
|
|
550
|
+
* The guard never rewrites the model's plan on its own: it observes
|
|
551
|
+
* `todo_write`, attaches advisory notices to tool results, and optionally
|
|
552
|
+
* refuses writes or calls when configured to be strict.
|
|
553
|
+
*
|
|
554
|
+
* @param ctx - the master plugin context.
|
|
555
|
+
* @param input - the `taskGuard` config group.
|
|
556
|
+
*/
|
|
557
|
+
export function installTaskGuard(ctx: Context, input?: TaskGuardConfig): void {
|
|
558
|
+
const config = resolveConfig(input)
|
|
559
|
+
const bus = ctx as unknown as TaskGuardBus
|
|
560
|
+
const sessions = new Map<string, SessionState>()
|
|
561
|
+
const intentBuffers = new Map<string, string>()
|
|
562
|
+
|
|
563
|
+
bus.on('tools/pre-execute', async (exec, next) => {
|
|
564
|
+
if (!config.enabled) return next()
|
|
565
|
+
|
|
566
|
+
if (exec.name === 'todo_write') {
|
|
567
|
+
const todos = readTodos(exec.arguments)
|
|
568
|
+
if (config.rejectMissingActive && todos !== null && leavesPendingWithoutActive(todos)) {
|
|
569
|
+
return { kind: 'deny', reason: denyMissingActive(todos, config) }
|
|
570
|
+
}
|
|
571
|
+
return next()
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
if (config.blockAfterCalls > 0 && exec.parent === undefined && isTracked(exec.name, config)) {
|
|
575
|
+
const state = sessions.get(sessionIdOf(exec.agent))
|
|
576
|
+
if (
|
|
577
|
+
state?.todos != null &&
|
|
578
|
+
hasUnfinished(state.todos) &&
|
|
579
|
+
state.callsSinceWrite >= config.blockAfterCalls
|
|
580
|
+
) {
|
|
581
|
+
return { kind: 'deny', reason: denyStale(state, config) }
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
return next()
|
|
586
|
+
})
|
|
587
|
+
|
|
588
|
+
bus.on('tools/post-execute', async (exec, result, next) => {
|
|
589
|
+
const downstream = await next()
|
|
590
|
+
if (!config.enabled) return downstream
|
|
591
|
+
|
|
592
|
+
if (exec.name === 'todo_write') {
|
|
593
|
+
if (result.isError) return downstream
|
|
594
|
+
const todos = readTodos(exec.arguments)
|
|
595
|
+
if (todos === null) return downstream
|
|
596
|
+
const sessionId = sessionIdOf(exec.agent)
|
|
597
|
+
if (sessionId !== '') {
|
|
598
|
+
resetState(sessions, sessionId, todos)
|
|
599
|
+
intentBuffers.delete(sessionId)
|
|
600
|
+
}
|
|
601
|
+
if (!config.rejectMissingActive && leavesPendingWithoutActive(todos)) {
|
|
602
|
+
const notice = await noticeMissingActive(
|
|
603
|
+
todos,
|
|
604
|
+
config,
|
|
605
|
+
sourceKindFor(exec.agent, config),
|
|
606
|
+
noticeContext(exec.agent, config, ctx),
|
|
607
|
+
)
|
|
608
|
+
return attachContext(downstream, notice)
|
|
609
|
+
}
|
|
610
|
+
return downstream
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
if (exec.parent !== undefined || result.isError || !isTracked(exec.name, config)) return downstream
|
|
614
|
+
|
|
615
|
+
const sessionId = sessionIdOf(exec.agent)
|
|
616
|
+
if (sessionId === '') return downstream
|
|
617
|
+
const state = sessions.get(sessionId)
|
|
618
|
+
if (state?.todos == null || !hasUnfinished(state.todos)) return downstream
|
|
619
|
+
|
|
620
|
+
state.callsSinceWrite += 1
|
|
621
|
+
|
|
622
|
+
// A "Now I will ..." / "接下来我会 ..." phrase that matches a pending todo is
|
|
623
|
+
// the strongest signal that the plan drifted; one advisory notice per step.
|
|
624
|
+
if (config.detectStepIntent && !state.intentNotifiedThisStep) {
|
|
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)
|
|
639
|
+
if (match !== undefined) {
|
|
640
|
+
state.intentNotifiedThisStep = true
|
|
641
|
+
const notice = await buildIntentNotice(
|
|
642
|
+
state,
|
|
643
|
+
match,
|
|
644
|
+
config,
|
|
645
|
+
sourceKindFor(exec.agent, config),
|
|
646
|
+
noticeContext(exec.agent, config, ctx),
|
|
647
|
+
)
|
|
648
|
+
return attachContext(downstream, notice)
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
if (state.reminderDeliveredThisStep) return downstream
|
|
653
|
+
|
|
654
|
+
const threshold = config.staleAfterCalls + state.remindersSent * config.repeatEveryCalls
|
|
655
|
+
if (state.callsSinceWrite < threshold) return downstream
|
|
656
|
+
if (config.repeatEveryCalls === 0 && state.remindersSent > 0) return downstream
|
|
657
|
+
|
|
658
|
+
const reminder = await buildReminder(
|
|
659
|
+
state,
|
|
660
|
+
config,
|
|
661
|
+
sourceKindFor(exec.agent, config),
|
|
662
|
+
noticeContext(exec.agent, config, ctx),
|
|
663
|
+
)
|
|
664
|
+
if (reminder === undefined) return downstream
|
|
665
|
+
|
|
666
|
+
state.remindersSent += 1
|
|
667
|
+
state.reminderDeliveredThisStep = true
|
|
668
|
+
return attachContext(downstream, reminder)
|
|
669
|
+
})
|
|
670
|
+
|
|
671
|
+
bus.on('agent/pre-step', async (payload, next) => {
|
|
672
|
+
const sessionId = sessionIdOf(payload.agent)
|
|
673
|
+
if (sessionId !== '') intentBuffers.delete(sessionId)
|
|
674
|
+
const state = sessions.get(sessionId)
|
|
675
|
+
if (state !== undefined) {
|
|
676
|
+
state.reminderDeliveredThisStep = false
|
|
677
|
+
state.intentNotifiedThisStep = false
|
|
678
|
+
}
|
|
679
|
+
return next()
|
|
680
|
+
})
|
|
681
|
+
|
|
682
|
+
bus.on('agent/assistant-stream', (payload) => {
|
|
683
|
+
if (!config.enabled || !config.detectStepIntent) return
|
|
684
|
+
const frame = payload?.frame
|
|
685
|
+
if (frame === null || typeof frame !== 'object' || frame.type !== 'chunk') return
|
|
686
|
+
const chunk = frame.chunk
|
|
687
|
+
if (chunk === null || typeof chunk !== 'object') return
|
|
688
|
+
if (chunk.type !== 'text-delta' && chunk.type !== 'reasoning-delta') return
|
|
689
|
+
if (typeof chunk.text !== 'string' || chunk.text === '') return
|
|
690
|
+
const attemptId = typeof frame.attemptId === 'string' ? frame.attemptId : ''
|
|
691
|
+
const separator = attemptId.lastIndexOf(':')
|
|
692
|
+
const sessionId = separator > 0 ? attemptId.slice(0, separator) : ''
|
|
693
|
+
if (sessionId === '') return
|
|
694
|
+
const next = ((intentBuffers.get(sessionId) ?? '') + chunk.text).slice(-4000)
|
|
695
|
+
intentBuffers.set(sessionId, next)
|
|
696
|
+
})
|
|
697
|
+
|
|
698
|
+
bus.on('session/event', (session, event) => {
|
|
699
|
+
const sessionId = sessionIdOf({ session })
|
|
700
|
+
if (sessionId === '') return
|
|
701
|
+
|
|
702
|
+
if (event.type === 'turn/start' || event.type === 'turn/end') {
|
|
703
|
+
sessions.delete(sessionId)
|
|
704
|
+
intentBuffers.delete(sessionId)
|
|
705
|
+
return
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
if (event.type === 'todo/write') {
|
|
709
|
+
const todos = readTodos(event.data)
|
|
710
|
+
if (todos !== null) resetState(sessions, sessionId, todos)
|
|
711
|
+
intentBuffers.delete(sessionId)
|
|
712
|
+
}
|
|
713
|
+
})
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function resolveConfig(input?: TaskGuardConfig): ResolvedConfig {
|
|
717
|
+
if (input !== undefined && (input === null || typeof input !== 'object' || Array.isArray(input))) {
|
|
718
|
+
throw new TypeError('task-guard: config must be an object')
|
|
719
|
+
}
|
|
720
|
+
const raw = (input ?? {}) as Record<string, unknown>
|
|
721
|
+
for (const key of Object.keys(raw)) {
|
|
722
|
+
if (!CONFIG_KEYS.has(key)) throw new TypeError(`task-guard: unknown config field "${key}"`)
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
const enabled = readBoolean(raw.enabled, true, 'enabled')
|
|
726
|
+
const locale = readLocale(raw.locale)
|
|
727
|
+
const staleAfterCalls = readInteger(raw.staleAfterCalls, 5, 1, 'staleAfterCalls')
|
|
728
|
+
const repeatEveryCalls = readInteger(raw.repeatEveryCalls, 4, 0, 'repeatEveryCalls')
|
|
729
|
+
const blockAfterCalls = readInteger(raw.blockAfterCalls, 0, 0, 'blockAfterCalls')
|
|
730
|
+
const rejectMissingActive = readBoolean(raw.rejectMissingActive, false, 'rejectMissingActive')
|
|
731
|
+
const sourceKind = readSourceKind(raw.sourceKind)
|
|
732
|
+
const maxListItems = readInteger(raw.maxListItems, 6, 1, 'maxListItems')
|
|
733
|
+
const detectStepIntent = readBoolean(raw.detectStepIntent, true, 'detectStepIntent')
|
|
734
|
+
const translateTodoContent = readBoolean(raw.translateTodoContent, true, 'translateTodoContent')
|
|
735
|
+
const todoTranslationTimeoutMs = readInteger(raw.todoTranslationTimeoutMs, 3000, 500, 'todoTranslationTimeoutMs')
|
|
736
|
+
const include = compilePatterns(readStringArray(raw.include, [], 'include'))
|
|
737
|
+
const exclude = compilePatterns(readStringArray(raw.exclude, DEFAULT_EXCLUDES, 'exclude'))
|
|
738
|
+
|
|
739
|
+
if (blockAfterCalls > 0 && blockAfterCalls <= staleAfterCalls) {
|
|
740
|
+
throw new TypeError('task-guard: blockAfterCalls must be greater than staleAfterCalls')
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
return {
|
|
744
|
+
enabled,
|
|
745
|
+
locale,
|
|
746
|
+
staleAfterCalls,
|
|
747
|
+
repeatEveryCalls,
|
|
748
|
+
blockAfterCalls,
|
|
749
|
+
rejectMissingActive,
|
|
750
|
+
sourceKind,
|
|
751
|
+
include,
|
|
752
|
+
exclude,
|
|
753
|
+
maxListItems,
|
|
754
|
+
detectStepIntent,
|
|
755
|
+
translateTodoContent,
|
|
756
|
+
todoTranslationTimeoutMs,
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
function readBoolean(value: unknown, fallback: boolean, field: string): boolean {
|
|
761
|
+
if (value === undefined) return fallback
|
|
762
|
+
if (typeof value !== 'boolean') throw new TypeError(`task-guard: ${field} must be a boolean`)
|
|
763
|
+
return value
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function readLocale(value: unknown): 'zh' | 'en' {
|
|
767
|
+
if (value === undefined) return 'zh'
|
|
768
|
+
if (value !== 'zh' && value !== 'en') throw new TypeError('task-guard: locale must be "zh" or "en"')
|
|
769
|
+
return value
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function readSourceKind(value: unknown): 'auto' | 'v3' | 'v4' {
|
|
773
|
+
if (value === undefined) return 'auto'
|
|
774
|
+
if (value !== 'auto' && value !== 'v3' && value !== 'v4') {
|
|
775
|
+
throw new TypeError('task-guard: sourceKind must be "auto", "v3", or "v4"')
|
|
776
|
+
}
|
|
777
|
+
return value
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function readInteger(value: unknown, fallback: number, minimum: number, field: string): number {
|
|
781
|
+
if (value === undefined) return fallback
|
|
782
|
+
if (!Number.isInteger(value) || (value as number) < minimum) {
|
|
783
|
+
throw new TypeError(`task-guard: ${field} must be an integer >= ${minimum}`)
|
|
784
|
+
}
|
|
785
|
+
return value as number
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
function readStringArray(value: unknown, fallback: string[], field: string): string[] {
|
|
789
|
+
if (value === undefined) return [...fallback]
|
|
790
|
+
if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || item.length === 0)) {
|
|
791
|
+
throw new TypeError(`task-guard: ${field} must be an array of non-empty strings`)
|
|
792
|
+
}
|
|
793
|
+
return [...value]
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function compilePatterns(patterns: string[]): RegExp[] {
|
|
797
|
+
return patterns.map((pattern) => {
|
|
798
|
+
const escaped = pattern.replace(/[|\\{}()[\]^$+?.]/g, String.raw`\$&`)
|
|
799
|
+
return new RegExp(`^${escaped.replaceAll('*', '.*')}$`)
|
|
800
|
+
})
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function isTracked(toolName: string, config: ResolvedConfig): boolean {
|
|
804
|
+
if (config.include.length > 0 && !config.include.some((pattern) => pattern.test(toolName))) return false
|
|
805
|
+
return !config.exclude.some((pattern) => pattern.test(toolName))
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
function readTodos(value: unknown): TodoItem[] | null {
|
|
809
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return null
|
|
810
|
+
const record = value as Record<string, unknown>
|
|
811
|
+
if (Object.keys(record).some((key) => key !== 'todos')) return null
|
|
812
|
+
if (!Array.isArray(record.todos)) return null
|
|
813
|
+
|
|
814
|
+
const todos: TodoItem[] = []
|
|
815
|
+
const seen = new Set<string>()
|
|
816
|
+
for (const item of record.todos) {
|
|
817
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) return null
|
|
818
|
+
const entry = item as Record<string, unknown>
|
|
819
|
+
if (Object.keys(entry).some((key) => key !== 'content' && key !== 'status')) return null
|
|
820
|
+
if (typeof entry.content !== 'string' || typeof entry.status !== 'string' || !STATUSES.has(entry.status)) {
|
|
821
|
+
return null
|
|
822
|
+
}
|
|
823
|
+
const content = entry.content.trim()
|
|
824
|
+
if (content === '' || seen.has(content)) return null
|
|
825
|
+
seen.add(content)
|
|
826
|
+
todos.push({ content, status: entry.status as TodoStatus })
|
|
827
|
+
}
|
|
828
|
+
return todos
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function resetState(sessions: Map<string, SessionState>, sessionId: string, todos: TodoItem[]): void {
|
|
832
|
+
sessions.set(sessionId, {
|
|
833
|
+
todos: todos.map((todo) => ({ ...todo })),
|
|
834
|
+
callsSinceWrite: 0,
|
|
835
|
+
remindersSent: 0,
|
|
836
|
+
reminderDeliveredThisStep: false,
|
|
837
|
+
intentNotifiedThisStep: false,
|
|
838
|
+
})
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
function sessionIdOf(agent: AgentLike | undefined): string {
|
|
842
|
+
const id = agent?.session?.id
|
|
843
|
+
return typeof id === 'string' && id !== '' ? id : ''
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* Format v3 used `{ kind: 'plugin', plugin }`; v4 retired that wrapper for
|
|
848
|
+
* producer-owned kinds such as `plugin:task-guard`. `session.header.version`
|
|
849
|
+
* is present on both generations (3 on 0.1.5, 4 on 0.2.x).
|
|
850
|
+
*/
|
|
851
|
+
function sourceKindFor(agent: AgentLike | undefined, config: ResolvedConfig): 'v3' | 'v4' {
|
|
852
|
+
if (config.sourceKind !== 'auto') return config.sourceKind
|
|
853
|
+
const version = agent?.session?.header?.version
|
|
854
|
+
return typeof version === 'number' && version < 4 ? 'v3' : 'v4'
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
function hasUnfinished(todos: TodoItem[]): boolean {
|
|
858
|
+
return todos.some((todo) => todo.status !== 'completed')
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
function leavesPendingWithoutActive(todos: TodoItem[]): boolean {
|
|
862
|
+
const pending = todos.some((todo) => todo.status === 'pending')
|
|
863
|
+
const active = todos.some((todo) => todo.status === 'in_progress')
|
|
864
|
+
return pending && !active
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function denyMissingActive(todos: TodoItem[], config: ResolvedConfig): string {
|
|
868
|
+
const pending = todos.filter((todo) => todo.status === 'pending').length
|
|
869
|
+
if (config.locale === 'en') {
|
|
870
|
+
return `todo_write rejected: ${pending} task(s) are still pending but no task is in_progress. While work remains, keep exactly one task in_progress. Resend the COMPLETE list with the next task you are about to work on marked in_progress, and finished tasks marked completed.`
|
|
871
|
+
}
|
|
872
|
+
return `todo_write 未执行:清单里还有 ${pending} 个待办,但没有任何 in_progress 任务。只要还有工作,就必须保持恰好一个任务为 in_progress。请重新提交完整清单:把已完成的阶段标为 completed,并把下一阶段标为 in_progress。`
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
async function noticeMissingActive(
|
|
876
|
+
todos: TodoItem[],
|
|
877
|
+
config: ResolvedConfig,
|
|
878
|
+
sourceKind: 'v3' | 'v4',
|
|
879
|
+
context: NoticeContext,
|
|
880
|
+
): Promise<NoticeMessage> {
|
|
881
|
+
const pending = todos.filter((todo) => todo.status === 'pending').length
|
|
882
|
+
const completed = todos.some((todo) => todo.status === 'completed')
|
|
883
|
+
const remaining = todos.filter((todo) => todo.status !== 'completed')
|
|
884
|
+
const display = await displayTodoContents(remaining.map((todo) => todo.content), context)
|
|
885
|
+
const quoted = remaining
|
|
886
|
+
.slice(0, config.maxListItems)
|
|
887
|
+
.map((todo, index) => (todo.status === 'in_progress' ? '[~] ' : '[ ] ') + truncate(display[index], 60))
|
|
888
|
+
.join('\n')
|
|
889
|
+
const omitted = remaining.length - config.maxListItems
|
|
890
|
+
const items = omitted > 0 ? quoted + '\n… +' + omitted : quoted
|
|
891
|
+
const text = config.locale === 'en'
|
|
892
|
+
? (completed
|
|
893
|
+
? '[Todo sync] A task was marked completed, but ' + pending + ' task(s) remain pending and no task is in_progress. Mark the next task in_progress before continuing, or clear the list / mark everything completed if this work is finished.'
|
|
894
|
+
: '[Todo sync] No task is in_progress while ' + pending + ' task(s) are pending. Mark the task you are about to start as in_progress.')
|
|
895
|
+
+ '\n\nRemaining:\n' + items
|
|
896
|
+
+ '\n\n(Tip: todo titles can be written in Chinese.)'
|
|
897
|
+
: (completed
|
|
898
|
+
? '【todo 同步】已有任务被标为 completed,但清单里还有 ' + pending + ' 个待办,且没有任何 in_progress 任务。继续之前请把下一阶段标为 in_progress;如果本次工作已经结束,请清空清单或把任务全部标为 completed。'
|
|
899
|
+
: '【todo 同步】清单里还有 ' + pending + ' 个待办,但还没有任何 in_progress 任务。请把即将开始的阶段标为 in_progress。')
|
|
900
|
+
+ '\n\n剩余:\n' + items
|
|
901
|
+
+ '\n\n(提示:todo 内容可以直接用中文书写。)'
|
|
902
|
+
return createNotice(text, config.locale === 'en' ? 'todo has no active task' : 'todo 没有进行中任务', sourceKind)
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
function denyStale(state: SessionState, config: ResolvedConfig): string {
|
|
906
|
+
if (config.locale === 'en') {
|
|
907
|
+
return `task-guard paused this call: ${state.callsSinceWrite} tool calls have run since the last todo_write and unfinished tasks remain. Call todo_write first — mark finished tasks completed and the next task in_progress — then retry the operation.`
|
|
908
|
+
}
|
|
909
|
+
return `task-guard 已暂停本次工具调用:距上次 todo_write 已过 ${state.callsSinceWrite} 次工具调用,但仍有未完成的待办。请先调用 todo_write 更新清单(已完成标为 completed,下一阶段标为 in_progress),然后重试刚才的操作。`
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
async function buildReminder(
|
|
913
|
+
state: SessionState,
|
|
914
|
+
config: ResolvedConfig,
|
|
915
|
+
sourceKind: 'v3' | 'v4',
|
|
916
|
+
context: NoticeContext,
|
|
917
|
+
): Promise<NoticeMessage | undefined> {
|
|
918
|
+
const todos = state.todos
|
|
919
|
+
if (todos === null) return undefined
|
|
920
|
+
|
|
921
|
+
const remaining = todos.filter((todo) => todo.status !== 'completed')
|
|
922
|
+
if (remaining.length === 0) return undefined
|
|
923
|
+
|
|
924
|
+
const active = todos.filter((todo) => todo.status === 'in_progress')
|
|
925
|
+
const activeDisplay = await displayTodoContents(active.map((todo) => todo.content), context)
|
|
926
|
+
const activeText = active.length === 0
|
|
927
|
+
? (config.locale === 'en' ? '(none)' : '(无)')
|
|
928
|
+
: activeDisplay.join(config.locale === 'en' ? ', ' : '、')
|
|
929
|
+
|
|
930
|
+
const display = await displayTodoContents(remaining.map((todo) => todo.content), context)
|
|
931
|
+
const quoted = remaining
|
|
932
|
+
.slice(0, config.maxListItems)
|
|
933
|
+
.map((todo, index) => (todo.status === 'in_progress' ? '[~] ' : '[ ] ') + truncate(display[index], 60))
|
|
934
|
+
.join('\n')
|
|
935
|
+
const omitted = remaining.length - config.maxListItems
|
|
936
|
+
const items = omitted > 0 ? quoted + '\n… +' + omitted : quoted
|
|
937
|
+
|
|
938
|
+
const activeOne = active.length === 1 ? active[0] : undefined
|
|
939
|
+
const suggested = activeOne === undefined ? undefined : completionPayload(todos, activeOne)
|
|
940
|
+
|
|
941
|
+
const text = config.locale === 'en'
|
|
942
|
+
? [
|
|
943
|
+
'[Todo sync] ' + state.callsSinceWrite + ' tool calls have run since the last todo_write.',
|
|
944
|
+
'In progress: ' + activeText,
|
|
945
|
+
'Remaining:\n' + items,
|
|
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 ?? '',
|
|
952
|
+
'(Tip: todo titles can be written in Chinese.)',
|
|
953
|
+
].filter(line => line !== '').join('\n')
|
|
954
|
+
: [
|
|
955
|
+
'【todo 同步】距上次 todo_write 已过 ' + state.callsSinceWrite + ' 次工具调用。',
|
|
956
|
+
'进行中:' + activeText,
|
|
957
|
+
'剩余:\n' + items,
|
|
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 ?? '',
|
|
964
|
+
'(提示:todo 内容可以直接用中文书写。)',
|
|
965
|
+
].filter(line => line !== '').join('\n')
|
|
966
|
+
|
|
967
|
+
const summary = config.locale === 'en'
|
|
968
|
+
? 'todo stale · ' + state.callsSinceWrite + ' calls'
|
|
969
|
+
: 'todo 未更新 · ' + state.callsSinceWrite + ' 次调用'
|
|
970
|
+
|
|
971
|
+
return createNotice(text, summary, sourceKind)
|
|
972
|
+
}
|
|
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
|
+
|
|
1012
|
+
async function buildIntentNotice(
|
|
1013
|
+
state: SessionState,
|
|
1014
|
+
match: StepIntentMatch,
|
|
1015
|
+
config: ResolvedConfig,
|
|
1016
|
+
sourceKind: 'v3' | 'v4',
|
|
1017
|
+
context: NoticeContext,
|
|
1018
|
+
): Promise<NoticeMessage> {
|
|
1019
|
+
const todos = state.todos ?? []
|
|
1020
|
+
const [display] = await displayTodoContents([match.todo.content], context)
|
|
1021
|
+
const suggested = suggestedTodoPayload(todos, match.todo)
|
|
1022
|
+
const phrase = truncate(match.phrase, 60)
|
|
1023
|
+
const text = config.locale === 'en'
|
|
1024
|
+
? [
|
|
1025
|
+
'[Todo sync] Your reasoning says "' + phrase + '", which matches the pending todo "' + display + '", but that task is not in_progress.',
|
|
1026
|
+
suggested === undefined
|
|
1027
|
+
? 'Mark it in_progress before continuing and keep the finished phase completed.'
|
|
1028
|
+
: 'If the previous phase is done, send this todo_write now:',
|
|
1029
|
+
suggested ?? '',
|
|
1030
|
+
'(Tip: todo titles can be written in Chinese.)',
|
|
1031
|
+
].filter(line => line !== '').join('\n')
|
|
1032
|
+
: [
|
|
1033
|
+
'【todo 同步】你在思考中提到「' + phrase + '」,匹配到待办「' + display + '」,但它还不是 in_progress。',
|
|
1034
|
+
suggested === undefined
|
|
1035
|
+
? '继续之前请把该待办标为 in_progress,并把已完成阶段标为 completed。'
|
|
1036
|
+
: '如果上一阶段已经完成,请直接发送:',
|
|
1037
|
+
suggested ?? '',
|
|
1038
|
+
'(提示:todo 内容可以直接用中文书写。)',
|
|
1039
|
+
].filter(line => line !== '').join('\n')
|
|
1040
|
+
const summary = config.locale === 'en'
|
|
1041
|
+
? 'todo intent · ' + truncate(phrase, 40)
|
|
1042
|
+
: 'todo 意图 · ' + truncate(phrase, 40)
|
|
1043
|
+
return createNotice(text, summary, sourceKind)
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
function truncate(value: string, max: number): string {
|
|
1047
|
+
return value.length <= max ? value : `${value.slice(0, max - 1)}…`
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
function createNotice(text: string, summary: string, sourceKind: 'v3' | 'v4'): NoticeMessage {
|
|
1051
|
+
const boundedSummary = summary.length <= SUMMARY_MAX_CHARS ? summary : `${summary.slice(0, SUMMARY_MAX_CHARS - 1)}…`
|
|
1052
|
+
const source: PluginSource =
|
|
1053
|
+
sourceKind === 'v3'
|
|
1054
|
+
? { kind: 'plugin', plugin: 'task-guard', form: 'notice', summary: boundedSummary }
|
|
1055
|
+
: { kind: 'plugin:task-guard', form: 'notice', summary: boundedSummary }
|
|
1056
|
+
return deepFreeze({
|
|
1057
|
+
id: randomUUID(),
|
|
1058
|
+
role: 'user',
|
|
1059
|
+
content: [{ type: 'text', text }],
|
|
1060
|
+
source,
|
|
1061
|
+
})
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
function attachContext(decision: PostToolDecision, context: NoticeMessage): PostToolDecision {
|
|
1065
|
+
return {
|
|
1066
|
+
...decision,
|
|
1067
|
+
additionalContexts: [context, ...(decision.additionalContexts ?? [])],
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
function deepFreeze<T>(value: T): T {
|
|
1072
|
+
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
1073
|
+
Object.freeze(value)
|
|
1074
|
+
for (const key of Object.keys(value)) deepFreeze((value as Record<string, unknown>)[key])
|
|
1075
|
+
}
|
|
1076
|
+
return value
|
|
1077
|
+
}
|