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,736 @@
|
|
|
1
|
+
// src/task-guard/index.ts
|
|
2
|
+
import z from "@deepseek-ai/schemastery";
|
|
3
|
+
|
|
4
|
+
// src/components/task-guard/index.ts
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
var SUMMARY_MAX_CHARS = 120;
|
|
7
|
+
var DEFAULT_EXCLUDES = ["todo_write", "ask_user_question"];
|
|
8
|
+
var STATUSES = /* @__PURE__ */ new Set(["pending", "in_progress", "completed"]);
|
|
9
|
+
var CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
10
|
+
"enabled",
|
|
11
|
+
"locale",
|
|
12
|
+
"staleAfterCalls",
|
|
13
|
+
"repeatEveryCalls",
|
|
14
|
+
"blockAfterCalls",
|
|
15
|
+
"rejectMissingActive",
|
|
16
|
+
"sourceKind",
|
|
17
|
+
"include",
|
|
18
|
+
"exclude",
|
|
19
|
+
"maxListItems",
|
|
20
|
+
"detectStepIntent",
|
|
21
|
+
"translateTodoContent",
|
|
22
|
+
"todoTranslationTimeoutMs"
|
|
23
|
+
]);
|
|
24
|
+
function containsCjk(text) {
|
|
25
|
+
return /[\u3400-\u9fff\uf900-\ufaff]/.test(text);
|
|
26
|
+
}
|
|
27
|
+
function normalizeText(value) {
|
|
28
|
+
return value.toLowerCase().replace(/[\`*_#>\[\](){}]+/g, " ").replace(/\s+/g, " ").trim();
|
|
29
|
+
}
|
|
30
|
+
function tokensOf(value) {
|
|
31
|
+
const normalized = normalizeText(value);
|
|
32
|
+
const tokens = [];
|
|
33
|
+
for (const token of normalized.split(/[^a-z0-9\u4e00-\u9fff]+/)) {
|
|
34
|
+
if (token.length >= 3) tokens.push(token);
|
|
35
|
+
}
|
|
36
|
+
const chars = Array.from(normalized).filter((char) => /[\u4e00-\u9fff]/.test(char));
|
|
37
|
+
for (let index = 0; index + 1 < chars.length; index += 1) tokens.push(chars[index] + chars[index + 1]);
|
|
38
|
+
return tokens;
|
|
39
|
+
}
|
|
40
|
+
var INTENT_MARKERS = [
|
|
41
|
+
/\b(?:now|next|then)\s*,?\s*i(?:'ll| will| am going to|'m going to)\b([^\n]{2,160})/gi,
|
|
42
|
+
/\bi(?:'ll| will| am going to|'m going to)\s+(?:now\s+)?([^\n]{2,160})/gi,
|
|
43
|
+
/\blet me\s+(?:now\s+)?([^\n]{2,160})/gi,
|
|
44
|
+
/\b(?:now|next|then)\s+(?!i(?:'ll| will| am|'m)\b)([a-z][^\n]{2,160})/gi,
|
|
45
|
+
/\b(?:next step|next,)\s*[:\-]?\s*([^\n]{2,160})/gi,
|
|
46
|
+
/(?:接下来|下一步|现在|然后|下面)(?:我会|我将|我要|我来|就开始|开始|准备)([^\n。;;]{2,120})/g,
|
|
47
|
+
/(?:接下来|下一步|现在|然后|下面)(?:开始|进行|做|处理|继续|检查|运行|绘制|布局|布线|导出|放置|连接)([^\n。;;]{2,120})/g
|
|
48
|
+
];
|
|
49
|
+
function intentPhrases(text) {
|
|
50
|
+
const found = [];
|
|
51
|
+
for (const marker of INTENT_MARKERS) {
|
|
52
|
+
marker.lastIndex = 0;
|
|
53
|
+
let match = marker.exec(text);
|
|
54
|
+
while (match !== null) {
|
|
55
|
+
const raw = (match[1] ?? "").trim();
|
|
56
|
+
const phrase = raw.replace(/^[::,\-\s]+/, "").split(/[.。!!??;;\n]/)[0].trim();
|
|
57
|
+
if (phrase.length >= 2) found.push({ index: match.index, phrase });
|
|
58
|
+
match = marker.exec(text);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
found.sort((left, right) => left.index - right.index);
|
|
62
|
+
return found.map((item) => item.phrase);
|
|
63
|
+
}
|
|
64
|
+
var PHASE_PATTERNS = [
|
|
65
|
+
{ id: "schematic", pattern: /schematic|原理图/ },
|
|
66
|
+
{ id: "library", pattern: /library|footprint|器件库|元件库|封装/ },
|
|
67
|
+
{ id: "board", pattern: /board\s*(?:outline|shape)|板框|边框|外形/ },
|
|
68
|
+
{ id: "placement", pattern: /placement|layout|布局|摆放/ },
|
|
69
|
+
{ id: "routing", pattern: /rout(?:e|ing|ed)|track|走线|布线|连线/ },
|
|
70
|
+
{ id: "drc", pattern: /\bdrc\b|\berc\b|design[_ ]audit|校验|检查/ },
|
|
71
|
+
{ id: "power", pattern: /power|电源|加粗/ },
|
|
72
|
+
{ id: "copper", pattern: /copper|pour|铺铜|覆铜/ },
|
|
73
|
+
{ id: "gerber", pattern: /gerber|export|导出|出图/ },
|
|
74
|
+
{ id: "usb", pattern: /usb|type-?c/ },
|
|
75
|
+
{ id: "mcu", pattern: /stm32|\bmcu\b|主控|单片机/ }
|
|
76
|
+
];
|
|
77
|
+
function phasesOf(value) {
|
|
78
|
+
const phases = /* @__PURE__ */ new Set();
|
|
79
|
+
for (const { id, pattern } of PHASE_PATTERNS) if (pattern.test(value)) phases.add(id);
|
|
80
|
+
return phases;
|
|
81
|
+
}
|
|
82
|
+
function detectStepIntent(text, todos) {
|
|
83
|
+
if (text.length === 0 || todos.length === 0) return void 0;
|
|
84
|
+
const phrases = intentPhrases(text).slice(-3);
|
|
85
|
+
if (phrases.length === 0) return void 0;
|
|
86
|
+
let best;
|
|
87
|
+
for (const phrase of phrases) {
|
|
88
|
+
const phraseNormalized = normalizeText(phrase);
|
|
89
|
+
const phraseTokens = new Set(tokensOf(phrase));
|
|
90
|
+
const phrasePhases = phasesOf(phrase);
|
|
91
|
+
for (const todo of todos) {
|
|
92
|
+
if (todo.status !== "pending") continue;
|
|
93
|
+
const contentNormalized = normalizeText(todo.content);
|
|
94
|
+
const todoPhases = phasesOf(todo.content);
|
|
95
|
+
let score = 0;
|
|
96
|
+
if ([...phrasePhases].some((phase) => todoPhases.has(phase))) {
|
|
97
|
+
score = 1;
|
|
98
|
+
} else if (contentNormalized.length >= 4 && (phraseNormalized.includes(contentNormalized) || contentNormalized.includes(phraseNormalized))) {
|
|
99
|
+
score = 1;
|
|
100
|
+
} else {
|
|
101
|
+
const contentTokens = tokensOf(todo.content);
|
|
102
|
+
if (contentTokens.length === 0) continue;
|
|
103
|
+
let shared = 0;
|
|
104
|
+
for (const token of contentTokens) if (phraseTokens.has(token)) shared += 1;
|
|
105
|
+
score = shared / contentTokens.length;
|
|
106
|
+
if (shared < 2 && score < 0.6) continue;
|
|
107
|
+
}
|
|
108
|
+
if (score >= 0.6 && (best === void 0 || score > best.score)) best = { todo, phrase, score };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return best;
|
|
112
|
+
}
|
|
113
|
+
var COMPLETION_PATTERNS = [
|
|
114
|
+
/\ball\b[^.!?\n]{0,100}\b(?:routed|connected|placed|done|complete|completed)\b/i,
|
|
115
|
+
/\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,
|
|
116
|
+
/\b(?:drc|erc|check|validation)\b[^.!?\n]{0,40}\b(?:passes|passed|clean|0\s+(?:errors?|violations?))\b/i,
|
|
117
|
+
/(?:全部|所有)[^。!?\n]{0,50}(?:布通|连通|完成|通过)|(?:完成|已完成|搞定|通过|布通|连通|无(?:错误|违规)|0\s*(?:错误|违规))/
|
|
118
|
+
];
|
|
119
|
+
function isCompletionSentence(sentence) {
|
|
120
|
+
return COMPLETION_PATTERNS.some((pattern) => pattern.test(sentence));
|
|
121
|
+
}
|
|
122
|
+
function detectCompletion(text, todos) {
|
|
123
|
+
if (text.length === 0 || todos.length === 0) return void 0;
|
|
124
|
+
const active = todos.filter((todo) => todo.status === "in_progress");
|
|
125
|
+
if (active.length > 1) return void 0;
|
|
126
|
+
const pool = active.length === 1 ? active : todos.filter((todo) => todo.status === "pending");
|
|
127
|
+
if (pool.length === 0) return void 0;
|
|
128
|
+
const sentences = text.split(/(?<=[.!?。!?])\s+|\n+/).map((sentence) => sentence.trim()).filter((sentence) => sentence.length > 0);
|
|
129
|
+
for (const sentence of sentences) {
|
|
130
|
+
if (!isCompletionSentence(sentence)) continue;
|
|
131
|
+
const sentencePhases = phasesOf(sentence);
|
|
132
|
+
let best;
|
|
133
|
+
let bestScore = 0;
|
|
134
|
+
for (const todo of pool) {
|
|
135
|
+
const todoPhases = phasesOf(todo.content);
|
|
136
|
+
let score = 0;
|
|
137
|
+
for (const phase of sentencePhases) if (todoPhases.has(phase)) score += 1;
|
|
138
|
+
if (score > bestScore) {
|
|
139
|
+
best = todo;
|
|
140
|
+
bestScore = score;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (best === void 0 && active.length === 1 && sentencePhases.size === 0) {
|
|
144
|
+
best = active[0];
|
|
145
|
+
bestScore = 0.5;
|
|
146
|
+
}
|
|
147
|
+
if (best !== void 0) return { todo: best, phrase: sentence.slice(0, 120), score: bestScore };
|
|
148
|
+
}
|
|
149
|
+
return void 0;
|
|
150
|
+
}
|
|
151
|
+
function completionPayload(todos, matched) {
|
|
152
|
+
const active = todos.filter((todo) => todo.status === "in_progress");
|
|
153
|
+
if (active.length > 1) return void 0;
|
|
154
|
+
const index = todos.findIndex((todo) => todo.content === matched.content);
|
|
155
|
+
if (index < 0) return void 0;
|
|
156
|
+
const next = todos.find((todo, at) => at > index && todo.status === "pending") ?? todos.find((todo, at) => at !== index && todo.status === "pending");
|
|
157
|
+
const updated = todos.map((todo, at) => ({
|
|
158
|
+
content: todo.content,
|
|
159
|
+
status: at === index ? "completed" : next !== void 0 && todo.content === next.content ? "in_progress" : todo.status === "in_progress" && at !== index ? "completed" : todo.status
|
|
160
|
+
}));
|
|
161
|
+
return JSON.stringify({ todos: updated });
|
|
162
|
+
}
|
|
163
|
+
function serviceOf(scope, name) {
|
|
164
|
+
try {
|
|
165
|
+
const direct = scope[name];
|
|
166
|
+
if (direct !== void 0) return direct;
|
|
167
|
+
} catch {
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const get = scope.get;
|
|
171
|
+
return typeof get === "function" ? get.call(scope, name) : void 0;
|
|
172
|
+
} catch {
|
|
173
|
+
return void 0;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function sessionRoute(agent) {
|
|
177
|
+
try {
|
|
178
|
+
const read = agent?.session?.requestHeader;
|
|
179
|
+
const header = typeof read === "function" ? read.call(agent?.session) : void 0;
|
|
180
|
+
const config = header?.config;
|
|
181
|
+
const provider = config?.provider;
|
|
182
|
+
const model = config?.model;
|
|
183
|
+
if (typeof provider === "string" && provider.length > 0 && typeof model === "string" && model.length > 0) {
|
|
184
|
+
return { provider, model };
|
|
185
|
+
}
|
|
186
|
+
} catch {
|
|
187
|
+
}
|
|
188
|
+
return void 0;
|
|
189
|
+
}
|
|
190
|
+
function noticeContext(agent, config, ctx) {
|
|
191
|
+
const route = sessionRoute(agent);
|
|
192
|
+
const llm = serviceOf(ctx, "llm");
|
|
193
|
+
return {
|
|
194
|
+
llm,
|
|
195
|
+
route,
|
|
196
|
+
translate: config.translateTodoContent && route !== void 0 && llm !== void 0,
|
|
197
|
+
timeoutMs: config.todoTranslationTimeoutMs
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
var TRANSLATION_CACHE_LIMIT = 256;
|
|
201
|
+
var translationCache = /* @__PURE__ */ new Map();
|
|
202
|
+
function parseStringArray(raw) {
|
|
203
|
+
const start = raw.indexOf("[");
|
|
204
|
+
const end = raw.lastIndexOf("]");
|
|
205
|
+
if (start < 0 || end <= start) return void 0;
|
|
206
|
+
try {
|
|
207
|
+
const value = JSON.parse(raw.slice(start, end + 1));
|
|
208
|
+
if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
|
|
209
|
+
} catch {
|
|
210
|
+
}
|
|
211
|
+
return void 0;
|
|
212
|
+
}
|
|
213
|
+
async function translateBatch(contents, context) {
|
|
214
|
+
if (context.llm === void 0 || typeof context.llm.stream !== "function" || context.route === void 0) return void 0;
|
|
215
|
+
const controller = new AbortController();
|
|
216
|
+
const timer = setTimeout(() => controller.abort(new Error("todo translation timeout")), context.timeoutMs);
|
|
217
|
+
try {
|
|
218
|
+
const stream = await context.llm.stream({
|
|
219
|
+
provider: context.route.provider,
|
|
220
|
+
model: context.route.model,
|
|
221
|
+
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.",
|
|
222
|
+
messages: [{ role: "user", content: [{ type: "text", text: JSON.stringify(contents) }] }],
|
|
223
|
+
temperature: 0,
|
|
224
|
+
signal: controller.signal
|
|
225
|
+
});
|
|
226
|
+
if (stream === null || typeof stream !== "object") return void 0;
|
|
227
|
+
let text = "";
|
|
228
|
+
for await (const chunk of stream) {
|
|
229
|
+
if (controller.signal.aborted) return void 0;
|
|
230
|
+
if (chunk?.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
|
|
231
|
+
if (chunk?.type === "finish") {
|
|
232
|
+
const kind = chunk.reason?.kind;
|
|
233
|
+
if (typeof kind === "string" && kind !== "stop") return void 0;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const parsed = parseStringArray(text);
|
|
237
|
+
if (parsed === void 0 || parsed.length !== contents.length) return void 0;
|
|
238
|
+
return parsed;
|
|
239
|
+
} catch {
|
|
240
|
+
return void 0;
|
|
241
|
+
} finally {
|
|
242
|
+
clearTimeout(timer);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
async function withTimeout(value, ms) {
|
|
246
|
+
let timer;
|
|
247
|
+
const timeout = new Promise((resolve) => {
|
|
248
|
+
timer = setTimeout(() => resolve(void 0), ms);
|
|
249
|
+
timer.unref?.();
|
|
250
|
+
});
|
|
251
|
+
try {
|
|
252
|
+
return await Promise.race([value, timeout]);
|
|
253
|
+
} finally {
|
|
254
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
async function displayTodoContents(contents, context) {
|
|
258
|
+
if (!context.translate) return contents;
|
|
259
|
+
const pending = [];
|
|
260
|
+
const seen = /* @__PURE__ */ new Set();
|
|
261
|
+
for (const content of contents) {
|
|
262
|
+
if (containsCjk(content) || translationCache.has(content) || seen.has(content)) continue;
|
|
263
|
+
seen.add(content);
|
|
264
|
+
pending.push(content);
|
|
265
|
+
}
|
|
266
|
+
if (pending.length > 0) {
|
|
267
|
+
const translated = await withTimeout(translateBatch(pending, context), context.timeoutMs + 250);
|
|
268
|
+
if (translated !== void 0) {
|
|
269
|
+
for (let index = 0; index < pending.length; index += 1) {
|
|
270
|
+
const value = translated[index];
|
|
271
|
+
if (typeof value !== "string" || value.trim() === "") continue;
|
|
272
|
+
if (translationCache.size >= TRANSLATION_CACHE_LIMIT) {
|
|
273
|
+
const oldest = translationCache.keys().next();
|
|
274
|
+
if (oldest.done !== true) translationCache.delete(oldest.value);
|
|
275
|
+
}
|
|
276
|
+
translationCache.set(pending[index], value.trim());
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return contents.map((content) => {
|
|
281
|
+
const translated = translationCache.get(content);
|
|
282
|
+
if (translated === void 0 || containsCjk(content)) return content;
|
|
283
|
+
return translated + "\uFF08" + content + "\uFF09";
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
function suggestedTodoPayload(todos, matched) {
|
|
287
|
+
const active = todos.filter((todo) => todo.status === "in_progress");
|
|
288
|
+
if (active.length > 1) return void 0;
|
|
289
|
+
const next = todos.map((todo) => ({
|
|
290
|
+
content: todo.content,
|
|
291
|
+
status: todo.content === matched.content ? "in_progress" : todo.status === "in_progress" ? "completed" : todo.status
|
|
292
|
+
}));
|
|
293
|
+
return JSON.stringify({ todos: next });
|
|
294
|
+
}
|
|
295
|
+
function installTaskGuard(ctx, input) {
|
|
296
|
+
const config = resolveConfig(input);
|
|
297
|
+
const bus = ctx;
|
|
298
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
299
|
+
const intentBuffers = /* @__PURE__ */ new Map();
|
|
300
|
+
bus.on("tools/pre-execute", async (exec, next) => {
|
|
301
|
+
if (!config.enabled) return next();
|
|
302
|
+
if (exec.name === "todo_write") {
|
|
303
|
+
const todos = readTodos(exec.arguments);
|
|
304
|
+
if (config.rejectMissingActive && todos !== null && leavesPendingWithoutActive(todos)) {
|
|
305
|
+
return { kind: "deny", reason: denyMissingActive(todos, config) };
|
|
306
|
+
}
|
|
307
|
+
return next();
|
|
308
|
+
}
|
|
309
|
+
if (config.blockAfterCalls > 0 && exec.parent === void 0 && isTracked(exec.name, config)) {
|
|
310
|
+
const state = sessions.get(sessionIdOf(exec.agent));
|
|
311
|
+
if (state?.todos != null && hasUnfinished(state.todos) && state.callsSinceWrite >= config.blockAfterCalls) {
|
|
312
|
+
return { kind: "deny", reason: denyStale(state, config) };
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return next();
|
|
316
|
+
});
|
|
317
|
+
bus.on("tools/post-execute", async (exec, result, next) => {
|
|
318
|
+
const downstream = await next();
|
|
319
|
+
if (!config.enabled) return downstream;
|
|
320
|
+
if (exec.name === "todo_write") {
|
|
321
|
+
if (result.isError) return downstream;
|
|
322
|
+
const todos = readTodos(exec.arguments);
|
|
323
|
+
if (todos === null) return downstream;
|
|
324
|
+
const sessionId2 = sessionIdOf(exec.agent);
|
|
325
|
+
if (sessionId2 !== "") {
|
|
326
|
+
resetState(sessions, sessionId2, todos);
|
|
327
|
+
intentBuffers.delete(sessionId2);
|
|
328
|
+
}
|
|
329
|
+
if (!config.rejectMissingActive && leavesPendingWithoutActive(todos)) {
|
|
330
|
+
const notice = await noticeMissingActive(
|
|
331
|
+
todos,
|
|
332
|
+
config,
|
|
333
|
+
sourceKindFor(exec.agent, config),
|
|
334
|
+
noticeContext(exec.agent, config, ctx)
|
|
335
|
+
);
|
|
336
|
+
return attachContext(downstream, notice);
|
|
337
|
+
}
|
|
338
|
+
return downstream;
|
|
339
|
+
}
|
|
340
|
+
if (exec.parent !== void 0 || result.isError || !isTracked(exec.name, config)) return downstream;
|
|
341
|
+
const sessionId = sessionIdOf(exec.agent);
|
|
342
|
+
if (sessionId === "") return downstream;
|
|
343
|
+
const state = sessions.get(sessionId);
|
|
344
|
+
if (state?.todos == null || !hasUnfinished(state.todos)) return downstream;
|
|
345
|
+
state.callsSinceWrite += 1;
|
|
346
|
+
if (config.detectStepIntent && !state.intentNotifiedThisStep) {
|
|
347
|
+
const buffer = intentBuffers.get(sessionId) ?? "";
|
|
348
|
+
const completed = detectCompletion(buffer, state.todos);
|
|
349
|
+
if (completed !== void 0) {
|
|
350
|
+
state.intentNotifiedThisStep = true;
|
|
351
|
+
const notice = await buildCompletionNotice(
|
|
352
|
+
state,
|
|
353
|
+
completed,
|
|
354
|
+
config,
|
|
355
|
+
sourceKindFor(exec.agent, config),
|
|
356
|
+
noticeContext(exec.agent, config, ctx)
|
|
357
|
+
);
|
|
358
|
+
return attachContext(downstream, notice);
|
|
359
|
+
}
|
|
360
|
+
const match = detectStepIntent(buffer, state.todos);
|
|
361
|
+
if (match !== void 0) {
|
|
362
|
+
state.intentNotifiedThisStep = true;
|
|
363
|
+
const notice = await buildIntentNotice(
|
|
364
|
+
state,
|
|
365
|
+
match,
|
|
366
|
+
config,
|
|
367
|
+
sourceKindFor(exec.agent, config),
|
|
368
|
+
noticeContext(exec.agent, config, ctx)
|
|
369
|
+
);
|
|
370
|
+
return attachContext(downstream, notice);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (state.reminderDeliveredThisStep) return downstream;
|
|
374
|
+
const threshold = config.staleAfterCalls + state.remindersSent * config.repeatEveryCalls;
|
|
375
|
+
if (state.callsSinceWrite < threshold) return downstream;
|
|
376
|
+
if (config.repeatEveryCalls === 0 && state.remindersSent > 0) return downstream;
|
|
377
|
+
const reminder = await buildReminder(
|
|
378
|
+
state,
|
|
379
|
+
config,
|
|
380
|
+
sourceKindFor(exec.agent, config),
|
|
381
|
+
noticeContext(exec.agent, config, ctx)
|
|
382
|
+
);
|
|
383
|
+
if (reminder === void 0) return downstream;
|
|
384
|
+
state.remindersSent += 1;
|
|
385
|
+
state.reminderDeliveredThisStep = true;
|
|
386
|
+
return attachContext(downstream, reminder);
|
|
387
|
+
});
|
|
388
|
+
bus.on("agent/pre-step", async (payload, next) => {
|
|
389
|
+
const sessionId = sessionIdOf(payload.agent);
|
|
390
|
+
if (sessionId !== "") intentBuffers.delete(sessionId);
|
|
391
|
+
const state = sessions.get(sessionId);
|
|
392
|
+
if (state !== void 0) {
|
|
393
|
+
state.reminderDeliveredThisStep = false;
|
|
394
|
+
state.intentNotifiedThisStep = false;
|
|
395
|
+
}
|
|
396
|
+
return next();
|
|
397
|
+
});
|
|
398
|
+
bus.on("agent/assistant-stream", (payload) => {
|
|
399
|
+
if (!config.enabled || !config.detectStepIntent) return;
|
|
400
|
+
const frame = payload?.frame;
|
|
401
|
+
if (frame === null || typeof frame !== "object" || frame.type !== "chunk") return;
|
|
402
|
+
const chunk = frame.chunk;
|
|
403
|
+
if (chunk === null || typeof chunk !== "object") return;
|
|
404
|
+
if (chunk.type !== "text-delta" && chunk.type !== "reasoning-delta") return;
|
|
405
|
+
if (typeof chunk.text !== "string" || chunk.text === "") return;
|
|
406
|
+
const attemptId = typeof frame.attemptId === "string" ? frame.attemptId : "";
|
|
407
|
+
const separator = attemptId.lastIndexOf(":");
|
|
408
|
+
const sessionId = separator > 0 ? attemptId.slice(0, separator) : "";
|
|
409
|
+
if (sessionId === "") return;
|
|
410
|
+
const next = ((intentBuffers.get(sessionId) ?? "") + chunk.text).slice(-4e3);
|
|
411
|
+
intentBuffers.set(sessionId, next);
|
|
412
|
+
});
|
|
413
|
+
bus.on("session/event", (session, event) => {
|
|
414
|
+
const sessionId = sessionIdOf({ session });
|
|
415
|
+
if (sessionId === "") return;
|
|
416
|
+
if (event.type === "turn/start" || event.type === "turn/end") {
|
|
417
|
+
sessions.delete(sessionId);
|
|
418
|
+
intentBuffers.delete(sessionId);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
if (event.type === "todo/write") {
|
|
422
|
+
const todos = readTodos(event.data);
|
|
423
|
+
if (todos !== null) resetState(sessions, sessionId, todos);
|
|
424
|
+
intentBuffers.delete(sessionId);
|
|
425
|
+
}
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
function resolveConfig(input) {
|
|
429
|
+
if (input !== void 0 && (input === null || typeof input !== "object" || Array.isArray(input))) {
|
|
430
|
+
throw new TypeError("task-guard: config must be an object");
|
|
431
|
+
}
|
|
432
|
+
const raw = input ?? {};
|
|
433
|
+
for (const key of Object.keys(raw)) {
|
|
434
|
+
if (!CONFIG_KEYS.has(key)) throw new TypeError(`task-guard: unknown config field "${key}"`);
|
|
435
|
+
}
|
|
436
|
+
const enabled = readBoolean(raw.enabled, true, "enabled");
|
|
437
|
+
const locale = readLocale(raw.locale);
|
|
438
|
+
const staleAfterCalls = readInteger(raw.staleAfterCalls, 5, 1, "staleAfterCalls");
|
|
439
|
+
const repeatEveryCalls = readInteger(raw.repeatEveryCalls, 4, 0, "repeatEveryCalls");
|
|
440
|
+
const blockAfterCalls = readInteger(raw.blockAfterCalls, 0, 0, "blockAfterCalls");
|
|
441
|
+
const rejectMissingActive = readBoolean(raw.rejectMissingActive, false, "rejectMissingActive");
|
|
442
|
+
const sourceKind = readSourceKind(raw.sourceKind);
|
|
443
|
+
const maxListItems = readInteger(raw.maxListItems, 6, 1, "maxListItems");
|
|
444
|
+
const detectStepIntent2 = readBoolean(raw.detectStepIntent, true, "detectStepIntent");
|
|
445
|
+
const translateTodoContent = readBoolean(raw.translateTodoContent, true, "translateTodoContent");
|
|
446
|
+
const todoTranslationTimeoutMs = readInteger(raw.todoTranslationTimeoutMs, 3e3, 500, "todoTranslationTimeoutMs");
|
|
447
|
+
const include = compilePatterns(readStringArray(raw.include, [], "include"));
|
|
448
|
+
const exclude = compilePatterns(readStringArray(raw.exclude, DEFAULT_EXCLUDES, "exclude"));
|
|
449
|
+
if (blockAfterCalls > 0 && blockAfterCalls <= staleAfterCalls) {
|
|
450
|
+
throw new TypeError("task-guard: blockAfterCalls must be greater than staleAfterCalls");
|
|
451
|
+
}
|
|
452
|
+
return {
|
|
453
|
+
enabled,
|
|
454
|
+
locale,
|
|
455
|
+
staleAfterCalls,
|
|
456
|
+
repeatEveryCalls,
|
|
457
|
+
blockAfterCalls,
|
|
458
|
+
rejectMissingActive,
|
|
459
|
+
sourceKind,
|
|
460
|
+
include,
|
|
461
|
+
exclude,
|
|
462
|
+
maxListItems,
|
|
463
|
+
detectStepIntent: detectStepIntent2,
|
|
464
|
+
translateTodoContent,
|
|
465
|
+
todoTranslationTimeoutMs
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
function readBoolean(value, fallback, field) {
|
|
469
|
+
if (value === void 0) return fallback;
|
|
470
|
+
if (typeof value !== "boolean") throw new TypeError(`task-guard: ${field} must be a boolean`);
|
|
471
|
+
return value;
|
|
472
|
+
}
|
|
473
|
+
function readLocale(value) {
|
|
474
|
+
if (value === void 0) return "zh";
|
|
475
|
+
if (value !== "zh" && value !== "en") throw new TypeError('task-guard: locale must be "zh" or "en"');
|
|
476
|
+
return value;
|
|
477
|
+
}
|
|
478
|
+
function readSourceKind(value) {
|
|
479
|
+
if (value === void 0) return "auto";
|
|
480
|
+
if (value !== "auto" && value !== "v3" && value !== "v4") {
|
|
481
|
+
throw new TypeError('task-guard: sourceKind must be "auto", "v3", or "v4"');
|
|
482
|
+
}
|
|
483
|
+
return value;
|
|
484
|
+
}
|
|
485
|
+
function readInteger(value, fallback, minimum, field) {
|
|
486
|
+
if (value === void 0) return fallback;
|
|
487
|
+
if (!Number.isInteger(value) || value < minimum) {
|
|
488
|
+
throw new TypeError(`task-guard: ${field} must be an integer >= ${minimum}`);
|
|
489
|
+
}
|
|
490
|
+
return value;
|
|
491
|
+
}
|
|
492
|
+
function readStringArray(value, fallback, field) {
|
|
493
|
+
if (value === void 0) return [...fallback];
|
|
494
|
+
if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item.length === 0)) {
|
|
495
|
+
throw new TypeError(`task-guard: ${field} must be an array of non-empty strings`);
|
|
496
|
+
}
|
|
497
|
+
return [...value];
|
|
498
|
+
}
|
|
499
|
+
function compilePatterns(patterns) {
|
|
500
|
+
return patterns.map((pattern) => {
|
|
501
|
+
const escaped = pattern.replace(/[|\\{}()[\]^$+?.]/g, String.raw`\$&`);
|
|
502
|
+
return new RegExp(`^${escaped.replaceAll("*", ".*")}$`);
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
function isTracked(toolName, config) {
|
|
506
|
+
if (config.include.length > 0 && !config.include.some((pattern) => pattern.test(toolName))) return false;
|
|
507
|
+
return !config.exclude.some((pattern) => pattern.test(toolName));
|
|
508
|
+
}
|
|
509
|
+
function readTodos(value) {
|
|
510
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
|
|
511
|
+
const record = value;
|
|
512
|
+
if (Object.keys(record).some((key) => key !== "todos")) return null;
|
|
513
|
+
if (!Array.isArray(record.todos)) return null;
|
|
514
|
+
const todos = [];
|
|
515
|
+
const seen = /* @__PURE__ */ new Set();
|
|
516
|
+
for (const item of record.todos) {
|
|
517
|
+
if (item === null || typeof item !== "object" || Array.isArray(item)) return null;
|
|
518
|
+
const entry = item;
|
|
519
|
+
if (Object.keys(entry).some((key) => key !== "content" && key !== "status")) return null;
|
|
520
|
+
if (typeof entry.content !== "string" || typeof entry.status !== "string" || !STATUSES.has(entry.status)) {
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
const content = entry.content.trim();
|
|
524
|
+
if (content === "" || seen.has(content)) return null;
|
|
525
|
+
seen.add(content);
|
|
526
|
+
todos.push({ content, status: entry.status });
|
|
527
|
+
}
|
|
528
|
+
return todos;
|
|
529
|
+
}
|
|
530
|
+
function resetState(sessions, sessionId, todos) {
|
|
531
|
+
sessions.set(sessionId, {
|
|
532
|
+
todos: todos.map((todo) => ({ ...todo })),
|
|
533
|
+
callsSinceWrite: 0,
|
|
534
|
+
remindersSent: 0,
|
|
535
|
+
reminderDeliveredThisStep: false,
|
|
536
|
+
intentNotifiedThisStep: false
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
function sessionIdOf(agent) {
|
|
540
|
+
const id = agent?.session?.id;
|
|
541
|
+
return typeof id === "string" && id !== "" ? id : "";
|
|
542
|
+
}
|
|
543
|
+
function sourceKindFor(agent, config) {
|
|
544
|
+
if (config.sourceKind !== "auto") return config.sourceKind;
|
|
545
|
+
const version = agent?.session?.header?.version;
|
|
546
|
+
return typeof version === "number" && version < 4 ? "v3" : "v4";
|
|
547
|
+
}
|
|
548
|
+
function hasUnfinished(todos) {
|
|
549
|
+
return todos.some((todo) => todo.status !== "completed");
|
|
550
|
+
}
|
|
551
|
+
function leavesPendingWithoutActive(todos) {
|
|
552
|
+
const pending = todos.some((todo) => todo.status === "pending");
|
|
553
|
+
const active = todos.some((todo) => todo.status === "in_progress");
|
|
554
|
+
return pending && !active;
|
|
555
|
+
}
|
|
556
|
+
function denyMissingActive(todos, config) {
|
|
557
|
+
const pending = todos.filter((todo) => todo.status === "pending").length;
|
|
558
|
+
if (config.locale === "en") {
|
|
559
|
+
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.`;
|
|
560
|
+
}
|
|
561
|
+
return `todo_write \u672A\u6267\u884C\uFF1A\u6E05\u5355\u91CC\u8FD8\u6709 ${pending} \u4E2A\u5F85\u529E\uFF0C\u4F46\u6CA1\u6709\u4EFB\u4F55 in_progress \u4EFB\u52A1\u3002\u53EA\u8981\u8FD8\u6709\u5DE5\u4F5C\uFF0C\u5C31\u5FC5\u987B\u4FDD\u6301\u6070\u597D\u4E00\u4E2A\u4EFB\u52A1\u4E3A in_progress\u3002\u8BF7\u91CD\u65B0\u63D0\u4EA4\u5B8C\u6574\u6E05\u5355\uFF1A\u628A\u5DF2\u5B8C\u6210\u7684\u9636\u6BB5\u6807\u4E3A completed\uFF0C\u5E76\u628A\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\u3002`;
|
|
562
|
+
}
|
|
563
|
+
async function noticeMissingActive(todos, config, sourceKind, context) {
|
|
564
|
+
const pending = todos.filter((todo) => todo.status === "pending").length;
|
|
565
|
+
const completed = todos.some((todo) => todo.status === "completed");
|
|
566
|
+
const remaining = todos.filter((todo) => todo.status !== "completed");
|
|
567
|
+
const display = await displayTodoContents(remaining.map((todo) => todo.content), context);
|
|
568
|
+
const quoted = remaining.slice(0, config.maxListItems).map((todo, index) => (todo.status === "in_progress" ? "[~] " : "[ ] ") + truncate(display[index], 60)).join("\n");
|
|
569
|
+
const omitted = remaining.length - config.maxListItems;
|
|
570
|
+
const items = omitted > 0 ? quoted + "\n\u2026 +" + omitted : quoted;
|
|
571
|
+
const text = config.locale === "en" ? (completed ? "[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." : "[Todo sync] No task is in_progress while " + pending + " task(s) are pending. Mark the task you are about to start as in_progress.") + "\n\nRemaining:\n" + items + "\n\n(Tip: todo titles can be written in Chinese.)" : (completed ? "\u3010todo \u540C\u6B65\u3011\u5DF2\u6709\u4EFB\u52A1\u88AB\u6807\u4E3A completed\uFF0C\u4F46\u6E05\u5355\u91CC\u8FD8\u6709 " + pending + " \u4E2A\u5F85\u529E\uFF0C\u4E14\u6CA1\u6709\u4EFB\u4F55 in_progress \u4EFB\u52A1\u3002\u7EE7\u7EED\u4E4B\u524D\u8BF7\u628A\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\uFF1B\u5982\u679C\u672C\u6B21\u5DE5\u4F5C\u5DF2\u7ECF\u7ED3\u675F\uFF0C\u8BF7\u6E05\u7A7A\u6E05\u5355\u6216\u628A\u4EFB\u52A1\u5168\u90E8\u6807\u4E3A completed\u3002" : "\u3010todo \u540C\u6B65\u3011\u6E05\u5355\u91CC\u8FD8\u6709 " + pending + " \u4E2A\u5F85\u529E\uFF0C\u4F46\u8FD8\u6CA1\u6709\u4EFB\u4F55 in_progress \u4EFB\u52A1\u3002\u8BF7\u628A\u5373\u5C06\u5F00\u59CB\u7684\u9636\u6BB5\u6807\u4E3A in_progress\u3002") + "\n\n\u5269\u4F59\uFF1A\n" + items + "\n\n\uFF08\u63D0\u793A\uFF1Atodo \u5185\u5BB9\u53EF\u4EE5\u76F4\u63A5\u7528\u4E2D\u6587\u4E66\u5199\u3002\uFF09";
|
|
572
|
+
return createNotice(text, config.locale === "en" ? "todo has no active task" : "todo \u6CA1\u6709\u8FDB\u884C\u4E2D\u4EFB\u52A1", sourceKind);
|
|
573
|
+
}
|
|
574
|
+
function denyStale(state, config) {
|
|
575
|
+
if (config.locale === "en") {
|
|
576
|
+
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 \u2014 mark finished tasks completed and the next task in_progress \u2014 then retry the operation.`;
|
|
577
|
+
}
|
|
578
|
+
return `task-guard \u5DF2\u6682\u505C\u672C\u6B21\u5DE5\u5177\u8C03\u7528\uFF1A\u8DDD\u4E0A\u6B21 todo_write \u5DF2\u8FC7 ${state.callsSinceWrite} \u6B21\u5DE5\u5177\u8C03\u7528\uFF0C\u4F46\u4ECD\u6709\u672A\u5B8C\u6210\u7684\u5F85\u529E\u3002\u8BF7\u5148\u8C03\u7528 todo_write \u66F4\u65B0\u6E05\u5355\uFF08\u5DF2\u5B8C\u6210\u6807\u4E3A completed\uFF0C\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\uFF09\uFF0C\u7136\u540E\u91CD\u8BD5\u521A\u624D\u7684\u64CD\u4F5C\u3002`;
|
|
579
|
+
}
|
|
580
|
+
async function buildReminder(state, config, sourceKind, context) {
|
|
581
|
+
const todos = state.todos;
|
|
582
|
+
if (todos === null) return void 0;
|
|
583
|
+
const remaining = todos.filter((todo) => todo.status !== "completed");
|
|
584
|
+
if (remaining.length === 0) return void 0;
|
|
585
|
+
const active = todos.filter((todo) => todo.status === "in_progress");
|
|
586
|
+
const activeDisplay = await displayTodoContents(active.map((todo) => todo.content), context);
|
|
587
|
+
const activeText = active.length === 0 ? config.locale === "en" ? "(none)" : "\uFF08\u65E0\uFF09" : activeDisplay.join(config.locale === "en" ? ", " : "\u3001");
|
|
588
|
+
const display = await displayTodoContents(remaining.map((todo) => todo.content), context);
|
|
589
|
+
const quoted = remaining.slice(0, config.maxListItems).map((todo, index) => (todo.status === "in_progress" ? "[~] " : "[ ] ") + truncate(display[index], 60)).join("\n");
|
|
590
|
+
const omitted = remaining.length - config.maxListItems;
|
|
591
|
+
const items = omitted > 0 ? quoted + "\n\u2026 +" + omitted : quoted;
|
|
592
|
+
const activeOne = active.length === 1 ? active[0] : void 0;
|
|
593
|
+
const suggested = activeOne === void 0 ? void 0 : completionPayload(todos, activeOne);
|
|
594
|
+
const text = config.locale === "en" ? [
|
|
595
|
+
"[Todo sync] " + state.callsSinceWrite + " tool calls have run since the last todo_write.",
|
|
596
|
+
"In progress: " + activeText,
|
|
597
|
+
"Remaining:\n" + items,
|
|
598
|
+
activeOne === void 0 ? "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)." : suggested === void 0 ? "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)." : "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:",
|
|
599
|
+
suggested ?? "",
|
|
600
|
+
"(Tip: todo titles can be written in Chinese.)"
|
|
601
|
+
].filter((line) => line !== "").join("\n") : [
|
|
602
|
+
"\u3010todo \u540C\u6B65\u3011\u8DDD\u4E0A\u6B21 todo_write \u5DF2\u8FC7 " + state.callsSinceWrite + " \u6B21\u5DE5\u5177\u8C03\u7528\u3002",
|
|
603
|
+
"\u8FDB\u884C\u4E2D\uFF1A" + activeText,
|
|
604
|
+
"\u5269\u4F59\uFF1A\n" + items,
|
|
605
|
+
activeOne === void 0 ? "\u5982\u679C\u5F53\u524D\u9636\u6BB5\u5DF2\u7ECF\u5B8C\u6210\uFF0C\u8BF7\u8C03\u7528 todo_write\uFF1A\u628A\u5DF2\u5B8C\u6210\u9636\u6BB5\u6807\u4E3A completed\uFF0C\u5E76\u628A\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\uFF08\u6709\u5269\u4F59\u4EFB\u52A1\u65F6\u4E0D\u8981\u7559\u7A7A\uFF09\u3002" : suggested === void 0 ? "\u5982\u679C\u5F53\u524D\u9636\u6BB5\u5DF2\u7ECF\u5B8C\u6210\uFF0C\u8BF7\u8C03\u7528 todo_write\uFF1A\u628A\u8BE5\u9636\u6BB5\u6807\u4E3A completed\uFF0C\u5E76\u628A\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\uFF08\u6709\u5269\u4F59\u4EFB\u52A1\u65F6\u4E0D\u8981\u7559\u7A7A\uFF09\u3002" : "\u5982\u679C\u5F53\u524D\u9636\u6BB5\u5DF2\u7ECF\u5B8C\u6210\uFF0C\u8BF7\u76F4\u63A5\u53D1\u9001\u4EE5\u4E0B todo_write\uFF1B\u5982\u679C\u4ECD\u5728\u8FDB\u884C\uFF0C\u8BF7\u4FDD\u6301\u8BE5\u5F85\u529E\u4E3A in_progress\uFF0C\u65E0\u9700\u6539\u52A8\u6E05\u5355\uFF1A",
|
|
606
|
+
suggested ?? "",
|
|
607
|
+
"\uFF08\u63D0\u793A\uFF1Atodo \u5185\u5BB9\u53EF\u4EE5\u76F4\u63A5\u7528\u4E2D\u6587\u4E66\u5199\u3002\uFF09"
|
|
608
|
+
].filter((line) => line !== "").join("\n");
|
|
609
|
+
const summary = config.locale === "en" ? "todo stale \xB7 " + state.callsSinceWrite + " calls" : "todo \u672A\u66F4\u65B0 \xB7 " + state.callsSinceWrite + " \u6B21\u8C03\u7528";
|
|
610
|
+
return createNotice(text, summary, sourceKind);
|
|
611
|
+
}
|
|
612
|
+
async function buildCompletionNotice(state, match, config, sourceKind, context) {
|
|
613
|
+
const todos = state.todos ?? [];
|
|
614
|
+
const [display] = await displayTodoContents([match.todo.content], context);
|
|
615
|
+
const suggested = completionPayload(todos, match.todo);
|
|
616
|
+
const phrase = truncate(match.phrase, 80);
|
|
617
|
+
const text = config.locale === "en" ? [
|
|
618
|
+
'[Todo sync] The assistant text looks like a completed phase: "' + display + '".',
|
|
619
|
+
"Source: " + phrase,
|
|
620
|
+
suggested === void 0 ? "If that phase is finished, call todo_write: mark it completed and the next task in_progress." : "If that phase is finished, send this todo_write now:",
|
|
621
|
+
suggested ?? "",
|
|
622
|
+
"If it is still running, keep that task in_progress; do not mark it completed yet.",
|
|
623
|
+
"(Tip: todo titles can be written in Chinese.)"
|
|
624
|
+
].filter((line) => line !== "").join("\n") : [
|
|
625
|
+
"\u3010todo \u540C\u6B65\u3011\u68C0\u6D4B\u5230\u9636\u6BB5\u5B8C\u6210\uFF1A\u300C" + display + "\u300D",
|
|
626
|
+
"\u4F9D\u636E\uFF1A" + phrase,
|
|
627
|
+
suggested === void 0 ? "\u5982\u679C\u8BE5\u9636\u6BB5\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u8C03\u7528 todo_write\uFF1A\u628A\u8BE5\u5F85\u529E\u6807\u4E3A completed\uFF0C\u5E76\u628A\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\u3002" : "\u5982\u679C\u8BE5\u9636\u6BB5\u786E\u5B9E\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u76F4\u63A5\u53D1\u9001\u4EE5\u4E0B todo_write\uFF1A",
|
|
628
|
+
suggested ?? "",
|
|
629
|
+
"\u5982\u679C\u4ECD\u5728\u8FDB\u884C\uFF0C\u8BF7\u4FDD\u6301\u8BE5\u5F85\u529E\u4E3A in_progress\uFF0C\u4E0D\u8981\u63D0\u524D\u6807 completed\u3002",
|
|
630
|
+
"\uFF08\u63D0\u793A\uFF1Atodo \u5185\u5BB9\u53EF\u4EE5\u76F4\u63A5\u7528\u4E2D\u6587\u4E66\u5199\u3002\uFF09"
|
|
631
|
+
].filter((line) => line !== "").join("\n");
|
|
632
|
+
const summary = config.locale === "en" ? "todo complete \xB7 " + truncate(display, 40) : "todo \u5B8C\u6210 \xB7 " + truncate(display, 40);
|
|
633
|
+
return createNotice(text, summary, sourceKind);
|
|
634
|
+
}
|
|
635
|
+
async function buildIntentNotice(state, match, config, sourceKind, context) {
|
|
636
|
+
const todos = state.todos ?? [];
|
|
637
|
+
const [display] = await displayTodoContents([match.todo.content], context);
|
|
638
|
+
const suggested = suggestedTodoPayload(todos, match.todo);
|
|
639
|
+
const phrase = truncate(match.phrase, 60);
|
|
640
|
+
const text = config.locale === "en" ? [
|
|
641
|
+
'[Todo sync] Your reasoning says "' + phrase + '", which matches the pending todo "' + display + '", but that task is not in_progress.',
|
|
642
|
+
suggested === void 0 ? "Mark it in_progress before continuing and keep the finished phase completed." : "If the previous phase is done, send this todo_write now:",
|
|
643
|
+
suggested ?? "",
|
|
644
|
+
"(Tip: todo titles can be written in Chinese.)"
|
|
645
|
+
].filter((line) => line !== "").join("\n") : [
|
|
646
|
+
"\u3010todo \u540C\u6B65\u3011\u4F60\u5728\u601D\u8003\u4E2D\u63D0\u5230\u300C" + phrase + "\u300D\uFF0C\u5339\u914D\u5230\u5F85\u529E\u300C" + display + "\u300D\uFF0C\u4F46\u5B83\u8FD8\u4E0D\u662F in_progress\u3002",
|
|
647
|
+
suggested === void 0 ? "\u7EE7\u7EED\u4E4B\u524D\u8BF7\u628A\u8BE5\u5F85\u529E\u6807\u4E3A in_progress\uFF0C\u5E76\u628A\u5DF2\u5B8C\u6210\u9636\u6BB5\u6807\u4E3A completed\u3002" : "\u5982\u679C\u4E0A\u4E00\u9636\u6BB5\u5DF2\u7ECF\u5B8C\u6210\uFF0C\u8BF7\u76F4\u63A5\u53D1\u9001\uFF1A",
|
|
648
|
+
suggested ?? "",
|
|
649
|
+
"\uFF08\u63D0\u793A\uFF1Atodo \u5185\u5BB9\u53EF\u4EE5\u76F4\u63A5\u7528\u4E2D\u6587\u4E66\u5199\u3002\uFF09"
|
|
650
|
+
].filter((line) => line !== "").join("\n");
|
|
651
|
+
const summary = config.locale === "en" ? "todo intent \xB7 " + truncate(phrase, 40) : "todo \u610F\u56FE \xB7 " + truncate(phrase, 40);
|
|
652
|
+
return createNotice(text, summary, sourceKind);
|
|
653
|
+
}
|
|
654
|
+
function truncate(value, max) {
|
|
655
|
+
return value.length <= max ? value : `${value.slice(0, max - 1)}\u2026`;
|
|
656
|
+
}
|
|
657
|
+
function createNotice(text, summary, sourceKind) {
|
|
658
|
+
const boundedSummary = summary.length <= SUMMARY_MAX_CHARS ? summary : `${summary.slice(0, SUMMARY_MAX_CHARS - 1)}\u2026`;
|
|
659
|
+
const source = sourceKind === "v3" ? { kind: "plugin", plugin: "task-guard", form: "notice", summary: boundedSummary } : { kind: "plugin:task-guard", form: "notice", summary: boundedSummary };
|
|
660
|
+
return deepFreeze({
|
|
661
|
+
id: randomUUID(),
|
|
662
|
+
role: "user",
|
|
663
|
+
content: [{ type: "text", text }],
|
|
664
|
+
source
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
function attachContext(decision, context) {
|
|
668
|
+
return {
|
|
669
|
+
...decision,
|
|
670
|
+
additionalContexts: [context, ...decision.additionalContexts ?? []]
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
function deepFreeze(value) {
|
|
674
|
+
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
675
|
+
Object.freeze(value);
|
|
676
|
+
for (const key of Object.keys(value)) deepFreeze(value[key]);
|
|
677
|
+
}
|
|
678
|
+
return value;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// src/volatile.ts
|
|
682
|
+
function isVolatileLike(value) {
|
|
683
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
684
|
+
if (typeof value.get !== "function") return false;
|
|
685
|
+
return Object.getOwnPropertySymbols(value).length > 0 || Object.keys(value).every((key) => key === "get");
|
|
686
|
+
}
|
|
687
|
+
function toPlain(value) {
|
|
688
|
+
if (isVolatileLike(value)) return toPlain(value.get());
|
|
689
|
+
if (Array.isArray(value)) return value.map((item) => toPlain(item));
|
|
690
|
+
if (value !== null && typeof value === "object") {
|
|
691
|
+
const result = {};
|
|
692
|
+
for (const [key, child] of Object.entries(value)) result[key] = toPlain(child);
|
|
693
|
+
return result;
|
|
694
|
+
}
|
|
695
|
+
return value;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// src/task-guard/index.ts
|
|
699
|
+
var DEFAULT_TASK_GUARD_CONFIG = {
|
|
700
|
+
enabled: true,
|
|
701
|
+
locale: "zh",
|
|
702
|
+
staleAfterCalls: 5,
|
|
703
|
+
repeatEveryCalls: 4,
|
|
704
|
+
blockAfterCalls: 0,
|
|
705
|
+
rejectMissingActive: false,
|
|
706
|
+
sourceKind: "auto",
|
|
707
|
+
maxListItems: 6,
|
|
708
|
+
detectStepIntent: true,
|
|
709
|
+
translateTodoContent: true,
|
|
710
|
+
todoTranslationTimeoutMs: 3e3,
|
|
711
|
+
include: [],
|
|
712
|
+
exclude: ["todo_write", "ask_user_question"]
|
|
713
|
+
};
|
|
714
|
+
var Config = z.object({
|
|
715
|
+
enabled: z.boolean().default(DEFAULT_TASK_GUARD_CONFIG.enabled).volatile(),
|
|
716
|
+
locale: z.union(["zh", "en"]).default(DEFAULT_TASK_GUARD_CONFIG.locale).volatile(),
|
|
717
|
+
staleAfterCalls: z.number().min(1).default(DEFAULT_TASK_GUARD_CONFIG.staleAfterCalls).volatile(),
|
|
718
|
+
repeatEveryCalls: z.number().min(0).default(DEFAULT_TASK_GUARD_CONFIG.repeatEveryCalls).volatile(),
|
|
719
|
+
blockAfterCalls: z.number().min(0).default(DEFAULT_TASK_GUARD_CONFIG.blockAfterCalls).volatile(),
|
|
720
|
+
rejectMissingActive: z.boolean().default(DEFAULT_TASK_GUARD_CONFIG.rejectMissingActive).volatile(),
|
|
721
|
+
sourceKind: z.union(["auto", "v3", "v4"]).default(DEFAULT_TASK_GUARD_CONFIG.sourceKind).volatile(),
|
|
722
|
+
maxListItems: z.number().min(1).default(DEFAULT_TASK_GUARD_CONFIG.maxListItems).volatile(),
|
|
723
|
+
detectStepIntent: z.boolean().default(DEFAULT_TASK_GUARD_CONFIG.detectStepIntent).volatile(),
|
|
724
|
+
translateTodoContent: z.boolean().default(DEFAULT_TASK_GUARD_CONFIG.translateTodoContent).volatile(),
|
|
725
|
+
todoTranslationTimeoutMs: z.number().min(500).max(15e3).default(DEFAULT_TASK_GUARD_CONFIG.todoTranslationTimeoutMs).volatile(),
|
|
726
|
+
include: z.array(z.string()).default(DEFAULT_TASK_GUARD_CONFIG.include).volatile(),
|
|
727
|
+
exclude: z.array(z.string()).default(DEFAULT_TASK_GUARD_CONFIG.exclude).volatile()
|
|
728
|
+
}).default(DEFAULT_TASK_GUARD_CONFIG);
|
|
729
|
+
function apply(ctx, config) {
|
|
730
|
+
installTaskGuard(ctx, toPlain(config));
|
|
731
|
+
}
|
|
732
|
+
export {
|
|
733
|
+
Config,
|
|
734
|
+
DEFAULT_TASK_GUARD_CONFIG,
|
|
735
|
+
apply
|
|
736
|
+
};
|