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.
Files changed (44) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/CONTRIBUTING.md +60 -0
  3. package/LICENSE +202 -0
  4. package/README.en.md +146 -0
  5. package/README.md +287 -2
  6. package/SECURITY.md +38 -0
  7. package/cordis.patch.yml +12 -0
  8. package/docs/automation-task.md +63 -0
  9. package/docs/migration-from-standalone.md +115 -0
  10. package/docs/release.md +85 -0
  11. package/lib/appearance.js +320 -0
  12. package/lib/auto-review-fix.js +453 -0
  13. package/lib/client.js +1266 -0
  14. package/lib/index.js +1701 -0
  15. package/lib/restart.js +226 -0
  16. package/lib/task-guard.js +736 -0
  17. package/package.json +148 -4
  18. package/scripts/repair-profile.mjs +77 -0
  19. package/src/api.ts +5 -0
  20. package/src/appearance/index.ts +103 -0
  21. package/src/auto-review-fix/index.ts +45 -0
  22. package/src/client/AppearanceScheduleRow.tsx +112 -0
  23. package/src/client/ConfigForm.tsx +284 -0
  24. package/src/client/FallbackRestartRow.tsx +23 -0
  25. package/src/client/RestartCard.tsx +108 -0
  26. package/src/client/SettingsSection.tsx +110 -0
  27. package/src/client/bridge.ts +131 -0
  28. package/src/client/driver.ts +166 -0
  29. package/src/client/index.ts +114 -0
  30. package/src/client/locales.ts +193 -0
  31. package/src/client/primitives.d.ts +15 -0
  32. package/src/client/section-presence.ts +33 -0
  33. package/src/client/styles.ts +154 -0
  34. package/src/components/auto-review-fix/index.ts +421 -0
  35. package/src/components/auto-review-fix/translate.ts +235 -0
  36. package/src/components/task-guard/index.ts +1077 -0
  37. package/src/index.ts +71 -0
  38. package/src/loopback.ts +48 -0
  39. package/src/namespace.ts +7 -0
  40. package/src/restart/index.ts +268 -0
  41. package/src/routes.ts +228 -0
  42. package/src/schedule.ts +125 -0
  43. package/src/task-guard/index.ts +52 -0
  44. package/src/volatile.ts +32 -0
package/lib/index.js ADDED
@@ -0,0 +1,1701 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/index.ts
8
+ import z5 from "@deepseek-ai/schemastery";
9
+
10
+ // src/appearance/index.ts
11
+ var appearance_exports = {};
12
+ __export(appearance_exports, {
13
+ Config: () => Config,
14
+ apply: () => apply,
15
+ inject: () => inject
16
+ });
17
+ import z from "@deepseek-ai/schemastery";
18
+
19
+ // src/loopback.ts
20
+ function isIPv4Loopback(value) {
21
+ const parts = value.split(".");
22
+ return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
23
+ }
24
+ function isLoopbackAddress(address) {
25
+ if (address === void 0) return false;
26
+ const normalized = address.toLowerCase();
27
+ if (normalized === "::1") return true;
28
+ if (normalized.startsWith("::ffff:")) return isIPv4Loopback(normalized.slice("::ffff:".length));
29
+ return isIPv4Loopback(normalized);
30
+ }
31
+ function isLoopbackHostname(hostname) {
32
+ if (hostname === "localhost" || hostname === "[::1]") return true;
33
+ return isIPv4Loopback(hostname);
34
+ }
35
+ function isLoopbackRequest(request) {
36
+ if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
37
+ const host = request.headers.host;
38
+ if (typeof host !== "string") return false;
39
+ let hostUrl;
40
+ try {
41
+ hostUrl = new URL("http://" + host);
42
+ } catch {
43
+ return false;
44
+ }
45
+ if (!isLoopbackHostname(hostUrl.hostname)) return false;
46
+ if (request.headers["sec-fetch-site"] === "cross-site") return false;
47
+ const origin = request.headers.origin;
48
+ if (origin === void 0) return true;
49
+ try {
50
+ return new URL(origin).host === hostUrl.host;
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ // src/routes.ts
57
+ import { SettingsConflictError } from "@deepseek-ai/dsh-settings";
58
+
59
+ // src/api.ts
60
+ var MCVISERON_API = {
61
+ describe: "/api/dsh-mcviseron/settings/describe",
62
+ mutate: "/api/dsh-mcviseron/settings/mutate"
63
+ };
64
+
65
+ // src/namespace.ts
66
+ var MCVISERON_SETTINGS_NAMESPACE = "mcviseron";
67
+
68
+ // src/schedule.ts
69
+ var DEFAULT_SCHEDULE_CONFIG = {
70
+ enabled: false,
71
+ lightStart: "08:00",
72
+ lightEnd: "23:00"
73
+ };
74
+ var TIME_OF_DAY = /^([01]\d|2[0-3]):([0-5]\d)$/;
75
+ function parseTimeOfDay(value) {
76
+ const match = TIME_OF_DAY.exec(value);
77
+ if (match === null) return void 0;
78
+ return Number(match[1]) * 60 + Number(match[2]);
79
+ }
80
+ function normalizeScheduleConfig(input) {
81
+ const record = input !== null && typeof input === "object" ? input : {};
82
+ const lightStart = typeof record.lightStart === "string" && parseTimeOfDay(record.lightStart) !== void 0 ? record.lightStart : DEFAULT_SCHEDULE_CONFIG.lightStart;
83
+ const lightEnd = typeof record.lightEnd === "string" && parseTimeOfDay(record.lightEnd) !== void 0 ? record.lightEnd : DEFAULT_SCHEDULE_CONFIG.lightEnd;
84
+ const enabled = typeof record.enabled === "boolean" ? record.enabled : DEFAULT_SCHEDULE_CONFIG.enabled;
85
+ return { enabled, lightStart, lightEnd };
86
+ }
87
+
88
+ // src/volatile.ts
89
+ function isVolatileLike(value) {
90
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
91
+ if (typeof value.get !== "function") return false;
92
+ return Object.getOwnPropertySymbols(value).length > 0 || Object.keys(value).every((key) => key === "get");
93
+ }
94
+ function toPlain(value) {
95
+ if (isVolatileLike(value)) return toPlain(value.get());
96
+ if (Array.isArray(value)) return value.map((item) => toPlain(item));
97
+ if (value !== null && typeof value === "object") {
98
+ const result = {};
99
+ for (const [key, child] of Object.entries(value)) result[key] = toPlain(child);
100
+ return result;
101
+ }
102
+ return value;
103
+ }
104
+
105
+ // src/routes.ts
106
+ var MAX_BODY_BYTES = 8 * 1024;
107
+ var FIELD_RULES = {
108
+ enabled: { type: "boolean" },
109
+ lightStart: { type: "time" },
110
+ lightEnd: { type: "time" },
111
+ "autoReviewFix.keepPresetGuard": { type: "boolean" },
112
+ "autoReviewFix.translateApprovalReason": { type: "boolean" },
113
+ "autoReviewFix.translateTimeoutMs": { type: "number", min: 500, max: 6e4 },
114
+ "autoReviewFix.translateMaxChars": { type: "number", min: 100, max: 2e4 },
115
+ "autoReviewFix.translateProvider": { type: "string" },
116
+ "autoReviewFix.translateModel": { type: "string" },
117
+ "taskGuard.enabled": { type: "boolean" },
118
+ "taskGuard.locale": { type: "enum", values: ["zh", "en"] },
119
+ "taskGuard.staleAfterCalls": { type: "number", min: 1, max: 1e3 },
120
+ "taskGuard.repeatEveryCalls": { type: "number", min: 0, max: 1e3 },
121
+ "taskGuard.blockAfterCalls": { type: "number", min: 0, max: 1e4 },
122
+ "taskGuard.rejectMissingActive": { type: "boolean" },
123
+ "taskGuard.sourceKind": { type: "enum", values: ["auto", "v3", "v4"] },
124
+ "taskGuard.maxListItems": { type: "number", min: 1, max: 100 },
125
+ "taskGuard.detectStepIntent": { type: "boolean" },
126
+ "taskGuard.translateTodoContent": { type: "boolean" },
127
+ "taskGuard.todoTranslationTimeoutMs": { type: "number", min: 500, max: 15e3 },
128
+ "taskGuard.include": { type: "strings" },
129
+ "taskGuard.exclude": { type: "strings" },
130
+ "restart.enabled": { type: "boolean" },
131
+ "restart.appPath": { type: "string" }
132
+ };
133
+ function ruleFor(path) {
134
+ if (!Array.isArray(path) || path.length === 0 || path.length > 2) return void 0;
135
+ if (!path.every((part) => typeof part === "string")) return void 0;
136
+ return FIELD_RULES[path.join(".")];
137
+ }
138
+ function validFieldValue(rule, value) {
139
+ switch (rule.type) {
140
+ case "boolean":
141
+ return typeof value === "boolean";
142
+ case "time":
143
+ return typeof value === "string" && parseTimeOfDay(value) !== void 0;
144
+ case "string":
145
+ return typeof value === "string";
146
+ case "number":
147
+ return typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) && value >= rule.min && value <= rule.max;
148
+ case "enum":
149
+ return typeof value === "string" && rule.values.includes(value);
150
+ case "strings":
151
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
152
+ }
153
+ }
154
+ function isRecord(value) {
155
+ return value !== null && typeof value === "object" && !Array.isArray(value);
156
+ }
157
+ function json(res, status, body) {
158
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "referrer-policy": "no-referrer" });
159
+ res.end(JSON.stringify(body));
160
+ }
161
+ async function readJsonBody(req) {
162
+ const chunks = [];
163
+ let size = 0;
164
+ for await (const chunk of req) {
165
+ const buffer = chunk;
166
+ size += buffer.length;
167
+ if (size > MAX_BODY_BYTES) return void 0;
168
+ chunks.push(buffer);
169
+ }
170
+ try {
171
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
172
+ } catch {
173
+ return void 0;
174
+ }
175
+ }
176
+ function isSettingsConflict(error) {
177
+ if (error instanceof SettingsConflictError) return true;
178
+ return error?.code === "SETTINGS_CONFLICT";
179
+ }
180
+ function unwrapValue(value) {
181
+ if (value === null || value === void 0) return value;
182
+ if (typeof value === "object" && typeof value.get === "function") {
183
+ try {
184
+ return value.get();
185
+ } catch {
186
+ return void 0;
187
+ }
188
+ }
189
+ return value;
190
+ }
191
+ function toPluginView(descriptor) {
192
+ const plain = toPlain(unwrapValue(descriptor.value));
193
+ const record = isRecord(plain) ? plain : {};
194
+ return {
195
+ ns: String(descriptor.ns),
196
+ value: {
197
+ ...normalizeScheduleConfig(plain),
198
+ autoReviewFix: isRecord(record.autoReviewFix) ? record.autoReviewFix : {},
199
+ taskGuard: isRecord(record.taskGuard) ? record.taskGuard : {},
200
+ restart: isRecord(record.restart) ? record.restart : {}
201
+ },
202
+ revision: descriptor.revision
203
+ };
204
+ }
205
+ function findView(settings) {
206
+ return settings.describe({ redactSecrets: true }).find((descriptor) => String(descriptor.ns) === MCVISERON_SETTINGS_NAMESPACE);
207
+ }
208
+ function makeSettingsRoutes(settings) {
209
+ const describe = {
210
+ kind: "exact",
211
+ path: MCVISERON_API.describe,
212
+ handler: async (req, res) => {
213
+ if (req.method !== "POST") return json(res, 405, { ok: false, error: "method-not-allowed" });
214
+ if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: "forbidden" });
215
+ const descriptor = findView(settings);
216
+ json(res, 200, {
217
+ ok: true,
218
+ value: {
219
+ namespaces: descriptor === void 0 ? [] : [toPluginView(descriptor)],
220
+ writable: settings.writable !== false
221
+ }
222
+ });
223
+ }
224
+ };
225
+ const mutate = {
226
+ kind: "exact",
227
+ path: MCVISERON_API.mutate,
228
+ handler: async (req, res) => {
229
+ if (req.method !== "POST") return json(res, 405, { ok: false, error: "method-not-allowed" });
230
+ if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: "forbidden" });
231
+ const body = await readJsonBody(req);
232
+ if (body === void 0 || typeof body !== "object" || body === null) {
233
+ return json(res, 400, { ok: false, code: "settings-rejected", message: "unreadable JSON body" });
234
+ }
235
+ const record = body;
236
+ if (record.ns !== MCVISERON_SETTINGS_NAMESPACE || !Array.isArray(record.ops)) {
237
+ return json(res, 400, { ok: false, code: "settings-rejected", message: "malformed settings request" });
238
+ }
239
+ const ops = record.ops;
240
+ const valid = ops.every((op) => {
241
+ if (op.op !== "set" && op.op !== "unset") return false;
242
+ const rule = ruleFor(op.path);
243
+ if (rule === void 0) return false;
244
+ if (op.op === "unset") return true;
245
+ return validFieldValue(rule, op.value);
246
+ });
247
+ if (!valid) {
248
+ return json(res, 400, { ok: false, code: "settings-rejected", message: "malformed settings operation" });
249
+ }
250
+ const expectedRevision = typeof record.expectedRevision === "number" ? record.expectedRevision : void 0;
251
+ try {
252
+ await settings.mutate(MCVISERON_SETTINGS_NAMESPACE, ops, expectedRevision);
253
+ } catch (error) {
254
+ if (isSettingsConflict(error)) {
255
+ return json(res, 200, { ok: false, code: "settings-conflict", message: error instanceof Error ? error.message : "settings conflict" });
256
+ }
257
+ const message = error instanceof Error ? error.message : String(error);
258
+ return json(res, 200, { ok: false, code: "settings-rejected", message });
259
+ }
260
+ const descriptor = findView(settings);
261
+ if (descriptor === void 0) {
262
+ return json(res, 200, { ok: false, code: "internal", message: "mcviseron settings namespace was disposed" });
263
+ }
264
+ json(res, 200, { ok: true, value: toPluginView(descriptor) });
265
+ }
266
+ };
267
+ return [describe, mutate];
268
+ }
269
+
270
+ // src/appearance/index.ts
271
+ var Config = z.object({
272
+ enabled: z.boolean().default(DEFAULT_SCHEDULE_CONFIG.enabled).volatile(),
273
+ lightStart: z.string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/).default(DEFAULT_SCHEDULE_CONFIG.lightStart).volatile(),
274
+ lightEnd: z.string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/).default(DEFAULT_SCHEDULE_CONFIG.lightEnd).volatile()
275
+ }).default({ ...DEFAULT_SCHEDULE_CONFIG });
276
+ var DIAGNOSTICS_PATH = "/api/dsh-mcviseron/diagnostics";
277
+ var inject = ["webServer"];
278
+ function apply(ctx, _config) {
279
+ ctx.effect(() => ctx.webServer.register({
280
+ kind: "exact",
281
+ path: DIAGNOSTICS_PATH,
282
+ handler: async (req, res) => {
283
+ try {
284
+ if (req.method !== "GET" && req.method !== "POST") return json(res, 405, { ok: false, error: "method-not-allowed" });
285
+ if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: "forbidden" });
286
+ const modules = ctx.get?.("clientModules");
287
+ const graph = typeof modules?.graph === "function" ? modules.graph() : void 0;
288
+ const batches = Array.isArray(graph?.batches) ? graph.batches : [];
289
+ const rows = [];
290
+ const batchSummary = [];
291
+ for (const batch of batches) {
292
+ const entries = batch?.descriptor?.entries ?? batch?.entries ?? [];
293
+ batchSummary.push({ phase: batch?.descriptor?.phase, count: entries.length });
294
+ for (const row of entries) rows.push(row);
295
+ }
296
+ const mcviseronRows = rows.filter((row) => JSON.stringify(row).includes("mcviseron"));
297
+ const loaderEntries = [];
298
+ const loader = ctx.loader;
299
+ for (const entry of loader?.entries?.() ?? []) {
300
+ if (String(entry.options?.name ?? "").includes("mcviseron")) {
301
+ loaderEntries.push({ name: entry.options?.name, disabled: Boolean(entry.disabled), fiber: Boolean(entry.fiber) });
302
+ }
303
+ }
304
+ json(res, 200, {
305
+ ok: true,
306
+ clientPath: modules?.clientPath?.("dsh-mcviseron-plugin") ?? null,
307
+ graphKeys: graph !== void 0 ? Object.keys(graph) : null,
308
+ batches: batchSummary,
309
+ mcviseronRows,
310
+ loaderEntries,
311
+ release: modules?.release ?? null
312
+ });
313
+ } catch (error) {
314
+ json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
315
+ }
316
+ }
317
+ }), "mcviseron-appearance: client diagnostics");
318
+ ctx.inject(["settings"], (sctx) => {
319
+ const settings = sctx.settings;
320
+ if (typeof settings.configure === "function") {
321
+ ctx.effect(() => settings.configure({ auto: false }), "mcviseron-appearance: settings page policy");
322
+ }
323
+ sctx.effect(() => {
324
+ const disposers = makeSettingsRoutes(settings).map((route) => ctx.webServer.register(route));
325
+ return () => {
326
+ for (const dispose of disposers) dispose();
327
+ };
328
+ }, "mcviseron-appearance: settings bridge");
329
+ });
330
+ }
331
+
332
+ // src/auto-review-fix/index.ts
333
+ var auto_review_fix_exports = {};
334
+ __export(auto_review_fix_exports, {
335
+ Config: () => Config2,
336
+ DEFAULT_AUTO_REVIEW_CONFIG: () => DEFAULT_AUTO_REVIEW_CONFIG,
337
+ apply: () => apply2
338
+ });
339
+ import z2 from "@deepseek-ai/schemastery";
340
+
341
+ // src/components/auto-review-fix/index.ts
342
+ import { randomUUID } from "node:crypto";
343
+
344
+ // src/components/auto-review-fix/translate.ts
345
+ var TRANSLATION_LABEL = "\u3010\u5BA1\u67E5\u7406\u7531 \xB7 \u4E2D\u6587\u7FFB\u8BD1\u3011";
346
+ var SYSTEM_PROMPT = [
347
+ "You translate the internal reviewer notes of an AI tool-approval system into Simplified Chinese.",
348
+ "Rules:",
349
+ "- Output the translation only: no preamble, no quotes, no Markdown fences.",
350
+ "- Keep tool names, file paths, identifiers, URLs, JSON and code exactly as written.",
351
+ "- Preserve meaning and ordering; do not summarize, add or omit anything."
352
+ ].join("\n");
353
+ var CACHE_LIMIT = 256;
354
+ var cache = /* @__PURE__ */ new Map();
355
+ var CHINESE_KEY = /^zh(?:[-_]|$)/i;
356
+ function chineseKey(display) {
357
+ if (typeof display["zh"] === "string") return "zh";
358
+ for (const key of Object.keys(display)) {
359
+ if (CHINESE_KEY.test(key) && typeof display[key] === "string") return key;
360
+ }
361
+ return void 0;
362
+ }
363
+ function englishText(display) {
364
+ if (typeof display["en"] === "string") return display["en"];
365
+ const key = chineseKey(display);
366
+ if (key !== void 0) return void 0;
367
+ for (const value of Object.values(display)) if (typeof value === "string") return value;
368
+ return void 0;
369
+ }
370
+ function isAutoReviewText(text) {
371
+ return /auto[\s\-_]*review/i.test(text);
372
+ }
373
+ function reviewerExcerpt(text) {
374
+ const match = /^\s*auto[\s\-_]*review\s+(?:denied\s+this\s+call|拒绝了此调用)\s*[::.]?\s*/i.exec(text);
375
+ if (match === null) return text.trim();
376
+ const rest = text.slice(match[0].length).trim();
377
+ return rest.length === 0 ? text.trim() : rest;
378
+ }
379
+ function withTranslation(original, translation) {
380
+ return original.length === 0 ? `${TRANSLATION_LABEL}
381
+ ${translation}` : `${original}
382
+
383
+ ${TRANSLATION_LABEL}
384
+ ${translation}`;
385
+ }
386
+ function hasTranslation(value) {
387
+ return value.includes(TRANSLATION_LABEL);
388
+ }
389
+ function isPredominantlyChinese(text) {
390
+ const han = (text.match(/[\u3400-\u9fff\uf900-\ufaff]/g) ?? []).length;
391
+ if (han === 0) return false;
392
+ const englishWords = (text.match(/[A-Za-z][A-Za-z0-9_.-]*/g) ?? []).length;
393
+ return englishWords <= Math.max(2, Math.ceil(han / 2));
394
+ }
395
+ function cleanTranslation(raw) {
396
+ let text = raw.trim();
397
+ const fenced = /^\s*```[a-zA-Z]*\n([\s\S]*?)\n```\s*$/.exec(text);
398
+ const fencedBody = fenced?.[1];
399
+ if (fencedBody !== void 0) text = fencedBody.trim();
400
+ if (text.length >= 2) {
401
+ const first = text[0];
402
+ const last = text[text.length - 1];
403
+ if (first === '"' && last === '"' || first === "'" && last === "'" || first === "\u300C" && last === "\u300D") {
404
+ text = text.slice(1, -1).trim();
405
+ }
406
+ }
407
+ return text;
408
+ }
409
+ function sessionRoute(request) {
410
+ try {
411
+ const agent = request?.agent;
412
+ const header = typeof agent?.session?.requestHeader === "function" ? agent.session.requestHeader() : void 0;
413
+ const config = header?.config;
414
+ const provider = config?.provider;
415
+ const model = config?.model;
416
+ if (typeof provider === "string" && provider.length > 0 && typeof model === "string" && model.length > 0) {
417
+ return { provider, model };
418
+ }
419
+ } catch {
420
+ }
421
+ return void 0;
422
+ }
423
+ function translationRoute(settings, request) {
424
+ if (settings.provider.length > 0 && settings.model.length > 0) {
425
+ return { provider: settings.provider, model: settings.model };
426
+ }
427
+ return sessionRoute(request);
428
+ }
429
+ async function readStream(stream, controller) {
430
+ let text = "";
431
+ for await (const chunk of stream) {
432
+ if (controller.signal.aborted) return void 0;
433
+ const value = chunk;
434
+ if (value === null || typeof value !== "object") continue;
435
+ if (value.type === "text-delta" && typeof value.text === "string") {
436
+ text += value.text;
437
+ if (text.length > 16e3) break;
438
+ continue;
439
+ }
440
+ if (value.type === "finish") {
441
+ const kind = value.reason?.kind;
442
+ if (typeof kind === "string" && kind !== "stop") return void 0;
443
+ }
444
+ }
445
+ return text;
446
+ }
447
+ async function translateForDisplay(llm, settings, request, text) {
448
+ const source = text.trim();
449
+ if (source.length === 0 || source.length > settings.maxChars) return void 0;
450
+ const cached = cache.get(source);
451
+ if (cached !== void 0) return cached;
452
+ if (llm === void 0 || typeof llm.stream !== "function") return void 0;
453
+ const route = translationRoute(settings, request);
454
+ if (route === void 0) return void 0;
455
+ const controller = new AbortController();
456
+ const timer = setTimeout(() => controller.abort(new Error("translation timeout")), settings.timeoutMs);
457
+ try {
458
+ const stream = await llm.stream({
459
+ provider: route.provider,
460
+ model: route.model,
461
+ system: SYSTEM_PROMPT,
462
+ messages: [{ role: "user", content: [{ type: "text", text: source }] }],
463
+ temperature: 0,
464
+ signal: controller.signal
465
+ });
466
+ if (stream === null || typeof stream !== "object") return void 0;
467
+ const collected = await readStream(stream, controller);
468
+ if (collected === void 0) return void 0;
469
+ const cleaned = cleanTranslation(collected);
470
+ if (cleaned.length === 0) return void 0;
471
+ if (cache.size >= CACHE_LIMIT) {
472
+ const oldest = cache.keys().next();
473
+ if (oldest.done !== true) cache.delete(oldest.value);
474
+ }
475
+ cache.set(source, cleaned);
476
+ return cleaned;
477
+ } catch {
478
+ return void 0;
479
+ } finally {
480
+ clearTimeout(timer);
481
+ }
482
+ }
483
+
484
+ // src/components/auto-review-fix/index.ts
485
+ var FIBER_STATE_ACTIVE = 2;
486
+ var guardedPresets = /* @__PURE__ */ new WeakSet();
487
+ var guardedApproval = /* @__PURE__ */ new WeakSet();
488
+ function boolSetting(source, key, fallback) {
489
+ const value = source[key];
490
+ return typeof value === "boolean" ? value : fallback;
491
+ }
492
+ function stringSetting(source, key, fallback) {
493
+ const value = source[key];
494
+ return typeof value === "string" ? value.trim() : fallback;
495
+ }
496
+ function numberSetting(source, key, fallback, min, max) {
497
+ const value = source[key];
498
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
499
+ return Math.min(Math.max(Math.trunc(value), min), max);
500
+ }
501
+ function normalizeConfig(config) {
502
+ const source = config !== null && typeof config === "object" && !Array.isArray(config) ? config : {};
503
+ const translate = boolSetting(source, "translateApprovalReason", true);
504
+ return {
505
+ keepPresetGuard: boolSetting(source, "keepPresetGuard", true),
506
+ enabled: translate,
507
+ timeoutMs: numberSetting(source, "translateTimeoutMs", 6e3, 500, 6e4),
508
+ maxChars: numberSetting(source, "translateMaxChars", 4e3, 100, 2e4),
509
+ provider: stringSetting(source, "translateProvider", ""),
510
+ model: stringSetting(source, "translateModel", "")
511
+ };
512
+ }
513
+ function whenService(ctx, name, run) {
514
+ try {
515
+ const inject3 = ctx.inject;
516
+ if (typeof inject3 === "function") {
517
+ inject3.call(ctx, [name], run);
518
+ return;
519
+ }
520
+ const get = ctx.get;
521
+ const service = typeof get === "function" ? get.call(ctx, name) : void 0;
522
+ if (service !== void 0) run(ctx);
523
+ } catch {
524
+ }
525
+ }
526
+ function serviceOf(scope, name) {
527
+ try {
528
+ const direct = scope[name];
529
+ if (direct !== void 0) return direct;
530
+ } catch {
531
+ }
532
+ try {
533
+ const get = scope.get;
534
+ return typeof get === "function" ? get.call(scope, name) : void 0;
535
+ } catch {
536
+ return void 0;
537
+ }
538
+ }
539
+ function effectOf(scope, setup, label) {
540
+ try {
541
+ const effect = scope.effect;
542
+ if (typeof effect === "function") effect.call(scope, setup, label);
543
+ } catch {
544
+ }
545
+ }
546
+ function rootIsActive(root) {
547
+ try {
548
+ const fiber = root?.fiber;
549
+ const state = fiber?.state;
550
+ if (typeof state !== "number") return true;
551
+ return state === FIBER_STATE_ACTIVE;
552
+ } catch {
553
+ return true;
554
+ }
555
+ }
556
+ function installPresetGuard(ctx) {
557
+ whenService(ctx, "permissionPresets", (scope) => {
558
+ const presets = serviceOf(scope, "permissionPresets");
559
+ if (presets === null || typeof presets !== "object") return;
560
+ if (typeof presets.set !== "function") return;
561
+ if (guardedPresets.has(presets)) return;
562
+ const original = presets.set;
563
+ const root = scope.root;
564
+ const wrapper = function(session, name) {
565
+ if (!rootIsActive(root)) return void 0;
566
+ return original.call(this, session, name);
567
+ };
568
+ try {
569
+ presets.set = wrapper;
570
+ guardedPresets.add(presets);
571
+ } catch {
572
+ }
573
+ });
574
+ }
575
+ async function decorateApprovalRequest(scope, settings, request, translate = translateForDisplay) {
576
+ if (!settings.enabled || request === null || typeof request !== "object") return request;
577
+ const display = request.displayReason;
578
+ if (display === null || typeof display !== "object" || Array.isArray(display)) return request;
579
+ const record = display;
580
+ const key = chineseKey(record);
581
+ if (key === void 0) return request;
582
+ const english = englishText(record);
583
+ if (english === void 0 || !isAutoReviewText(english)) return request;
584
+ const localized = record[key];
585
+ if (typeof localized !== "string" || hasTranslation(localized)) return request;
586
+ const excerpt = reviewerExcerpt(english);
587
+ if (excerpt.length === 0 || excerpt.length > settings.maxChars) return request;
588
+ if (isPredominantlyChinese(excerpt)) return request;
589
+ if (translationRoute(settings, request) === void 0) return request;
590
+ const llm = serviceOf(scope, "llm");
591
+ const translated = await translate(llm, settings, request, excerpt);
592
+ if (translated === void 0) return request;
593
+ const cleaned = cleanTranslation(translated);
594
+ if (cleaned.length === 0 || !/[\u4e00-\u9fff]/.test(cleaned)) return request;
595
+ const reasonValue = request.reason;
596
+ const originalReason = typeof reasonValue === "string" ? reasonValue : "";
597
+ const reasonWithTranslation = originalReason !== "" && !originalReason.includes(TRANSLATION_LABEL) ? withTranslation(originalReason, cleaned) : originalReason;
598
+ return {
599
+ ...request,
600
+ ...reasonWithTranslation !== originalReason ? { reason: reasonWithTranslation } : {},
601
+ displayReason: { ...record, [key]: withTranslation(localized, cleaned) }
602
+ };
603
+ }
604
+ function sessionIdOf(agent) {
605
+ const session = agent?.session;
606
+ return typeof session?.id === "string" ? session.id : "";
607
+ }
608
+ function sessionVersion(agent) {
609
+ const version = agent?.session?.header?.version;
610
+ return typeof version === "number" ? version : void 0;
611
+ }
612
+ function rejectionKey(agent, callId) {
613
+ if (typeof callId !== "string" || callId === "") return "";
614
+ const sessionId = sessionIdOf(agent);
615
+ return sessionId === "" ? "" : sessionId + ":" + callId;
616
+ }
617
+ function approvalReasonText(request) {
618
+ const record = request;
619
+ const display = record.displayReason;
620
+ if (display !== null && typeof display === "object" && !Array.isArray(display)) {
621
+ const key = chineseKey(display);
622
+ if (key !== void 0) {
623
+ const value = display[key];
624
+ if (typeof value === "string" && value !== "") return value;
625
+ }
626
+ const english = englishText(display);
627
+ if (english !== void 0 && english !== "") return english;
628
+ }
629
+ return typeof record.reason === "string" ? record.reason : "";
630
+ }
631
+ function isAutoReviewApproval(request) {
632
+ const record = request;
633
+ if (typeof record.reason === "string" && isAutoReviewText(record.reason)) return true;
634
+ const display = record.displayReason;
635
+ if (display !== null && typeof display === "object" && !Array.isArray(display)) {
636
+ const english = englishText(display);
637
+ if (english !== void 0 && isAutoReviewText(english)) return true;
638
+ }
639
+ return false;
640
+ }
641
+ function rejectionSource(agent, summary) {
642
+ return sessionVersion(agent) === 3 ? { kind: "plugin", plugin: "auto-review-fix", form: "notice", summary } : { kind: "plugin:auto-review-fix", form: "notice", summary };
643
+ }
644
+ function buildRejectionNotice(agent, request) {
645
+ const reason = approvalReasonText(request);
646
+ if (reason === "") return void 0;
647
+ const toolName = typeof request.toolName === "string" && request.toolName !== "" ? request.toolName : "\u672A\u77E5\u5DE5\u5177";
648
+ const text = [
649
+ '\u3010\u5BA1\u6279\u88AB\u62D2\u3011\u5DE5\u5177 "' + toolName + '" \u7684\u4EBA\u5DE5\u5BA1\u6279\u88AB\u62D2\u7EDD\u3002',
650
+ "\u81EA\u52A8\u5BA1\u67E5\u7406\u7531\uFF1A",
651
+ reason,
652
+ "",
653
+ "\u8BF7\u6839\u636E\u8BE5\u7406\u7531\u8C03\u6574\u65B9\u6848\uFF0C\u4E0D\u8981\u91CD\u590D\u540C\u4E00\u64CD\u4F5C\u3002"
654
+ ].join("\n");
655
+ return {
656
+ id: randomUUID(),
657
+ role: "user",
658
+ content: [{ type: "text", text }],
659
+ source: rejectionSource(agent, "\u5BA1\u6279\u88AB\u62D2 \xB7 " + toolName)
660
+ };
661
+ }
662
+ function createRejectionRelay() {
663
+ const notes = /* @__PURE__ */ new Map();
664
+ const ttl = 12e4;
665
+ return {
666
+ remember(key, notice) {
667
+ const now = Date.now();
668
+ for (const [oldKey, entry] of notes) if (now - entry.at > ttl) notes.delete(oldKey);
669
+ if (notes.size >= 50) {
670
+ const oldest = notes.keys().next().value;
671
+ if (oldest !== void 0) notes.delete(oldest);
672
+ }
673
+ notes.set(key, { notice, at: now });
674
+ },
675
+ take(key) {
676
+ const entry = notes.get(key);
677
+ if (entry === void 0) return void 0;
678
+ notes.delete(key);
679
+ return entry.notice;
680
+ }
681
+ };
682
+ }
683
+ var relayedContexts = /* @__PURE__ */ new WeakSet();
684
+ function installRejectionRelay(ctx, relay) {
685
+ const target = ctx;
686
+ if (typeof target.on !== "function" || relayedContexts.has(ctx)) return;
687
+ relayedContexts.add(ctx);
688
+ target.on.call(ctx, "tools/post-execute", async (exec, result, next) => {
689
+ const downstream = await next() ?? { kind: "accept" };
690
+ if (result?.isError !== true) return downstream;
691
+ const key = rejectionKey(exec?.agent, exec?.callId);
692
+ if (key === "") return downstream;
693
+ const notice = relay.take(key);
694
+ if (notice === void 0) return downstream;
695
+ return {
696
+ ...downstream,
697
+ additionalContexts: [
698
+ ...Array.isArray(downstream.additionalContexts) ? downstream.additionalContexts : [],
699
+ notice
700
+ ]
701
+ };
702
+ });
703
+ }
704
+ function installApprovalTranslation(ctx, settings, relay) {
705
+ whenService(ctx, "approval", (scope) => {
706
+ const approval = serviceOf(scope, "approval");
707
+ if (approval === null || typeof approval !== "object") return;
708
+ const original = approval.request;
709
+ if (typeof original !== "function") return;
710
+ if (guardedApproval.has(approval)) return;
711
+ const call = original;
712
+ const wrapper = async function(request) {
713
+ let decorated = request;
714
+ try {
715
+ decorated = await decorateApprovalRequest(scope, settings, request);
716
+ } catch {
717
+ decorated = request;
718
+ }
719
+ const outcome = await call.call(this, decorated);
720
+ if (outcome === "rejected" && isAutoReviewApproval(decorated)) {
721
+ const request2 = decorated;
722
+ const key = rejectionKey(request2.agent, request2.callId);
723
+ const notice = buildRejectionNotice(request2.agent, decorated);
724
+ if (key !== "" && notice !== void 0) relay.remember(key, notice);
725
+ }
726
+ return outcome;
727
+ };
728
+ try {
729
+ approval.request = wrapper;
730
+ guardedApproval.add(approval);
731
+ } catch {
732
+ return;
733
+ }
734
+ effectOf(scope, () => () => {
735
+ if (approval.request === wrapper) approval.request = call;
736
+ }, "mcviseron: restore approval.request");
737
+ });
738
+ }
739
+ function installAutoReview(ctx, config) {
740
+ const settings = normalizeConfig(config);
741
+ if (settings.keepPresetGuard) installPresetGuard(ctx);
742
+ if (settings.enabled) {
743
+ const relay = createRejectionRelay();
744
+ installRejectionRelay(ctx, relay);
745
+ installApprovalTranslation(ctx, settings, relay);
746
+ }
747
+ }
748
+
749
+ // src/auto-review-fix/index.ts
750
+ var DEFAULT_AUTO_REVIEW_CONFIG = {
751
+ keepPresetGuard: true,
752
+ translateApprovalReason: true,
753
+ translateTimeoutMs: 6e3,
754
+ translateMaxChars: 4e3,
755
+ translateProvider: "",
756
+ translateModel: ""
757
+ };
758
+ var Config2 = z2.object({
759
+ keepPresetGuard: z2.boolean().default(DEFAULT_AUTO_REVIEW_CONFIG.keepPresetGuard).volatile(),
760
+ translateApprovalReason: z2.boolean().default(DEFAULT_AUTO_REVIEW_CONFIG.translateApprovalReason).volatile(),
761
+ translateTimeoutMs: z2.number().min(500).max(6e4).default(DEFAULT_AUTO_REVIEW_CONFIG.translateTimeoutMs).volatile(),
762
+ translateMaxChars: z2.number().min(100).max(2e4).default(DEFAULT_AUTO_REVIEW_CONFIG.translateMaxChars).volatile(),
763
+ translateProvider: z2.string().default(DEFAULT_AUTO_REVIEW_CONFIG.translateProvider).volatile(),
764
+ translateModel: z2.string().default(DEFAULT_AUTO_REVIEW_CONFIG.translateModel).volatile()
765
+ }).default(DEFAULT_AUTO_REVIEW_CONFIG);
766
+ function apply2(ctx, config) {
767
+ installAutoReview(ctx, toPlain(config));
768
+ }
769
+
770
+ // src/restart/index.ts
771
+ var restart_exports = {};
772
+ __export(restart_exports, {
773
+ Config: () => Config3,
774
+ DEFAULT_RESTART_CONFIG: () => DEFAULT_RESTART_CONFIG,
775
+ RESTART_API: () => RESTART_API,
776
+ apply: () => apply3,
777
+ deriveDesktopAppPath: () => deriveDesktopAppPath,
778
+ inject: () => inject2,
779
+ makeRestartRoutes: () => makeRestartRoutes,
780
+ makeTaskScript: () => makeTaskScript,
781
+ resolveRestartTarget: () => resolveRestartTarget
782
+ });
783
+ import { execFileSync } from "node:child_process";
784
+ import { appendFileSync, existsSync } from "node:fs";
785
+ import { tmpdir } from "node:os";
786
+ import { basename, dirname, join, resolve } from "node:path";
787
+ import z3 from "@deepseek-ai/schemastery";
788
+ var DEFAULT_RESTART_CONFIG = { enabled: true, appPath: "" };
789
+ var Config3 = z3.object({
790
+ enabled: z3.boolean().default(DEFAULT_RESTART_CONFIG.enabled).volatile(),
791
+ /** Optional explicit application executable; empty derives it from the Host process. */
792
+ appPath: z3.string().default(DEFAULT_RESTART_CONFIG.appPath).volatile()
793
+ }).default(DEFAULT_RESTART_CONFIG);
794
+ var RESTART_API = {
795
+ status: "/api/dsh-mcviseron/restart/status",
796
+ execute: "/api/dsh-mcviseron/restart/execute"
797
+ };
798
+ function resolveRestartTarget(execPath, parentPid, exists, override = "", argv = [], platform = process.platform) {
799
+ if (platform !== "win32") return void 0;
800
+ if (!Number.isSafeInteger(parentPid) || parentPid <= 0) return void 0;
801
+ const configured = typeof override === "string" ? override.trim() : "";
802
+ const candidate = configured !== "" ? configured : deriveDesktopAppPath(execPath, argv, exists);
803
+ if (candidate === "" || !exists(candidate)) return void 0;
804
+ const name = basename(candidate).toLowerCase();
805
+ if (name === "node" || name === "node.exe") return void 0;
806
+ return { mainPid: parentPid, hostPid: process.pid, exePath: candidate };
807
+ }
808
+ function deriveDesktopAppPath(execPath, argv, exists) {
809
+ const isNode = (value) => /^node(\.exe)?$/i.test(basename(value));
810
+ if (!isNode(execPath)) return execPath;
811
+ const argv0 = argv[0] ?? "";
812
+ if (argv0 !== "" && argv0 !== execPath && !isNode(argv0) && exists(argv0)) return argv0;
813
+ const runtimeDir = argv[2] ?? "";
814
+ if (runtimeDir === "") return execPath;
815
+ const candidate = join(resolve(runtimeDir, "../../.."), "DeepSeek Harness.exe");
816
+ return exists(candidate) ? candidate : execPath;
817
+ }
818
+ var RESTART_TASK_NAME = "DSH-MCviseron-Restart";
819
+ var RESTART_DELAY_SECONDS = 6;
820
+ function restartLogPath() {
821
+ return join(tmpdir(), "dsh-mcviseron-restart.log");
822
+ }
823
+ function makeTaskScript(target, taskName, delaySeconds) {
824
+ const quote = (value) => "'" + value.replace(/'/g, "''") + "'";
825
+ return [
826
+ "$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name",
827
+ `$action = New-ScheduledTaskAction -Execute ${quote(target.exePath)} -WorkingDirectory ${quote(dirname(target.exePath))}`,
828
+ `$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(${delaySeconds})`,
829
+ "$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited",
830
+ `Register-ScheduledTask -TaskName ${quote(taskName)} -Action $action -Trigger $trigger -Principal $principal -Force | Out-Null`,
831
+ ""
832
+ ].join("\n");
833
+ }
834
+ function launchHelper(target) {
835
+ const logFile = restartLogPath();
836
+ try {
837
+ execFileSync("powershell.exe", [
838
+ "-NoProfile",
839
+ "-NonInteractive",
840
+ "-WindowStyle",
841
+ "Hidden",
842
+ "-Command",
843
+ makeTaskScript(target, RESTART_TASK_NAME, RESTART_DELAY_SECONDS)
844
+ ], { windowsHide: true, timeout: 2e4, encoding: "utf8" });
845
+ appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: scheduled ${target.exePath} in ${RESTART_DELAY_SECONDS}s
846
+ `, "utf8");
847
+ } catch (error) {
848
+ const message = error instanceof Error ? error.message : String(error);
849
+ appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: task registration failed: ${message}
850
+ `, "utf8");
851
+ throw new Error("cannot schedule the restart task: " + message, { cause: error });
852
+ }
853
+ setTimeout(() => {
854
+ try {
855
+ process.kill(target.mainPid);
856
+ appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: kill sent to ${target.mainPid}
857
+ `, "utf8");
858
+ } catch (error) {
859
+ appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: kill failed: ${error instanceof Error ? error.message : String(error)}
860
+ `, "utf8");
861
+ }
862
+ }, 700);
863
+ }
864
+ function json2(res, status, body) {
865
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
866
+ res.end(JSON.stringify(body));
867
+ }
868
+ async function readJsonBody2(req) {
869
+ const chunks = [];
870
+ let size = 0;
871
+ for await (const chunk of req) {
872
+ const buffer = chunk;
873
+ size += buffer.length;
874
+ if (size > 8 * 1024) return void 0;
875
+ chunks.push(buffer);
876
+ }
877
+ try {
878
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
879
+ } catch {
880
+ return void 0;
881
+ }
882
+ }
883
+ function makeRestartRoutes(deps) {
884
+ let lastLaunch = Number.NEGATIVE_INFINITY;
885
+ const now = deps.now ?? (() => Date.now());
886
+ const status = {
887
+ kind: "exact",
888
+ path: RESTART_API.status,
889
+ handler: async (req, res) => {
890
+ try {
891
+ if (req.method !== "GET" && req.method !== "POST") return json2(res, 405, { ok: false, error: "method-not-allowed" });
892
+ if (!isLoopbackRequest(req)) return json2(res, 403, { ok: false, error: "forbidden" });
893
+ const target = deps.target();
894
+ json2(res, 200, target === void 0 ? { ok: true, available: false, reason: "desktop-app-unavailable" } : { ok: true, available: true, appPath: target.exePath, mainPid: target.mainPid });
895
+ } catch (error) {
896
+ json2(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
897
+ }
898
+ }
899
+ };
900
+ const execute = {
901
+ kind: "exact",
902
+ path: RESTART_API.execute,
903
+ handler: async (req, res) => {
904
+ try {
905
+ if (req.method !== "POST") return json2(res, 405, { ok: false, error: "method-not-allowed" });
906
+ if (!isLoopbackRequest(req)) return json2(res, 403, { ok: false, error: "forbidden" });
907
+ const body = await readJsonBody2(req);
908
+ if (body === void 0 || typeof body !== "object" || body === null || body.confirm !== true) {
909
+ return json2(res, 400, { ok: false, error: "confirmation-required" });
910
+ }
911
+ const latest = now();
912
+ if (latest - lastLaunch < 5e3) return json2(res, 429, { ok: false, error: "restart-already-scheduled" });
913
+ const target = deps.target();
914
+ if (target === void 0) return json2(res, 409, { ok: false, error: "desktop-app-unavailable" });
915
+ deps.launch(target);
916
+ lastLaunch = latest;
917
+ json2(res, 200, { ok: true, restarting: true, appPath: target.exePath });
918
+ } catch (error) {
919
+ json2(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
920
+ }
921
+ }
922
+ };
923
+ return [status, execute];
924
+ }
925
+ var inject2 = ["webServer"];
926
+ function apply3(ctx, config) {
927
+ const plain = toPlain(config) ?? {};
928
+ if (plain.enabled === false) return;
929
+ const appPath = typeof plain.appPath === "string" ? plain.appPath : "";
930
+ const routes = makeRestartRoutes({
931
+ target: () => resolveRestartTarget(process.execPath, process.ppid, existsSync, appPath, process.argv),
932
+ launch: launchHelper
933
+ });
934
+ ctx.effect(() => {
935
+ const disposers = routes.map((route) => ctx.webServer.register(route));
936
+ return () => {
937
+ for (const dispose of disposers) dispose();
938
+ };
939
+ }, "mcviseron-restart: restart routes");
940
+ }
941
+
942
+ // src/task-guard/index.ts
943
+ var task_guard_exports = {};
944
+ __export(task_guard_exports, {
945
+ Config: () => Config4,
946
+ DEFAULT_TASK_GUARD_CONFIG: () => DEFAULT_TASK_GUARD_CONFIG,
947
+ apply: () => apply4
948
+ });
949
+ import z4 from "@deepseek-ai/schemastery";
950
+
951
+ // src/components/task-guard/index.ts
952
+ import { randomUUID as randomUUID2 } from "node:crypto";
953
+ var SUMMARY_MAX_CHARS = 120;
954
+ var DEFAULT_EXCLUDES = ["todo_write", "ask_user_question"];
955
+ var STATUSES = /* @__PURE__ */ new Set(["pending", "in_progress", "completed"]);
956
+ var CONFIG_KEYS = /* @__PURE__ */ new Set([
957
+ "enabled",
958
+ "locale",
959
+ "staleAfterCalls",
960
+ "repeatEveryCalls",
961
+ "blockAfterCalls",
962
+ "rejectMissingActive",
963
+ "sourceKind",
964
+ "include",
965
+ "exclude",
966
+ "maxListItems",
967
+ "detectStepIntent",
968
+ "translateTodoContent",
969
+ "todoTranslationTimeoutMs"
970
+ ]);
971
+ function containsCjk(text) {
972
+ return /[\u3400-\u9fff\uf900-\ufaff]/.test(text);
973
+ }
974
+ function normalizeText(value) {
975
+ return value.toLowerCase().replace(/[\`*_#>\[\](){}]+/g, " ").replace(/\s+/g, " ").trim();
976
+ }
977
+ function tokensOf(value) {
978
+ const normalized = normalizeText(value);
979
+ const tokens = [];
980
+ for (const token of normalized.split(/[^a-z0-9\u4e00-\u9fff]+/)) {
981
+ if (token.length >= 3) tokens.push(token);
982
+ }
983
+ const chars = Array.from(normalized).filter((char) => /[\u4e00-\u9fff]/.test(char));
984
+ for (let index = 0; index + 1 < chars.length; index += 1) tokens.push(chars[index] + chars[index + 1]);
985
+ return tokens;
986
+ }
987
+ var INTENT_MARKERS = [
988
+ /\b(?:now|next|then)\s*,?\s*i(?:'ll| will| am going to|'m going to)\b([^\n]{2,160})/gi,
989
+ /\bi(?:'ll| will| am going to|'m going to)\s+(?:now\s+)?([^\n]{2,160})/gi,
990
+ /\blet me\s+(?:now\s+)?([^\n]{2,160})/gi,
991
+ /\b(?:now|next|then)\s+(?!i(?:'ll| will| am|'m)\b)([a-z][^\n]{2,160})/gi,
992
+ /\b(?:next step|next,)\s*[:\-]?\s*([^\n]{2,160})/gi,
993
+ /(?:接下来|下一步|现在|然后|下面)(?:我会|我将|我要|我来|就开始|开始|准备)([^\n。;;]{2,120})/g,
994
+ /(?:接下来|下一步|现在|然后|下面)(?:开始|进行|做|处理|继续|检查|运行|绘制|布局|布线|导出|放置|连接)([^\n。;;]{2,120})/g
995
+ ];
996
+ function intentPhrases(text) {
997
+ const found = [];
998
+ for (const marker of INTENT_MARKERS) {
999
+ marker.lastIndex = 0;
1000
+ let match = marker.exec(text);
1001
+ while (match !== null) {
1002
+ const raw = (match[1] ?? "").trim();
1003
+ const phrase = raw.replace(/^[::,\-\s]+/, "").split(/[.。!!??;;\n]/)[0].trim();
1004
+ if (phrase.length >= 2) found.push({ index: match.index, phrase });
1005
+ match = marker.exec(text);
1006
+ }
1007
+ }
1008
+ found.sort((left, right) => left.index - right.index);
1009
+ return found.map((item) => item.phrase);
1010
+ }
1011
+ var PHASE_PATTERNS = [
1012
+ { id: "schematic", pattern: /schematic|原理图/ },
1013
+ { id: "library", pattern: /library|footprint|器件库|元件库|封装/ },
1014
+ { id: "board", pattern: /board\s*(?:outline|shape)|板框|边框|外形/ },
1015
+ { id: "placement", pattern: /placement|layout|布局|摆放/ },
1016
+ { id: "routing", pattern: /rout(?:e|ing|ed)|track|走线|布线|连线/ },
1017
+ { id: "drc", pattern: /\bdrc\b|\berc\b|design[_ ]audit|校验|检查/ },
1018
+ { id: "power", pattern: /power|电源|加粗/ },
1019
+ { id: "copper", pattern: /copper|pour|铺铜|覆铜/ },
1020
+ { id: "gerber", pattern: /gerber|export|导出|出图/ },
1021
+ { id: "usb", pattern: /usb|type-?c/ },
1022
+ { id: "mcu", pattern: /stm32|\bmcu\b|主控|单片机/ }
1023
+ ];
1024
+ function phasesOf(value) {
1025
+ const phases = /* @__PURE__ */ new Set();
1026
+ for (const { id, pattern } of PHASE_PATTERNS) if (pattern.test(value)) phases.add(id);
1027
+ return phases;
1028
+ }
1029
+ function detectStepIntent(text, todos) {
1030
+ if (text.length === 0 || todos.length === 0) return void 0;
1031
+ const phrases = intentPhrases(text).slice(-3);
1032
+ if (phrases.length === 0) return void 0;
1033
+ let best;
1034
+ for (const phrase of phrases) {
1035
+ const phraseNormalized = normalizeText(phrase);
1036
+ const phraseTokens = new Set(tokensOf(phrase));
1037
+ const phrasePhases = phasesOf(phrase);
1038
+ for (const todo of todos) {
1039
+ if (todo.status !== "pending") continue;
1040
+ const contentNormalized = normalizeText(todo.content);
1041
+ const todoPhases = phasesOf(todo.content);
1042
+ let score = 0;
1043
+ if ([...phrasePhases].some((phase) => todoPhases.has(phase))) {
1044
+ score = 1;
1045
+ } else if (contentNormalized.length >= 4 && (phraseNormalized.includes(contentNormalized) || contentNormalized.includes(phraseNormalized))) {
1046
+ score = 1;
1047
+ } else {
1048
+ const contentTokens = tokensOf(todo.content);
1049
+ if (contentTokens.length === 0) continue;
1050
+ let shared = 0;
1051
+ for (const token of contentTokens) if (phraseTokens.has(token)) shared += 1;
1052
+ score = shared / contentTokens.length;
1053
+ if (shared < 2 && score < 0.6) continue;
1054
+ }
1055
+ if (score >= 0.6 && (best === void 0 || score > best.score)) best = { todo, phrase, score };
1056
+ }
1057
+ }
1058
+ return best;
1059
+ }
1060
+ var COMPLETION_PATTERNS = [
1061
+ /\ball\b[^.!?\n]{0,100}\b(?:routed|connected|placed|done|complete|completed)\b/i,
1062
+ /\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,
1063
+ /\b(?:drc|erc|check|validation)\b[^.!?\n]{0,40}\b(?:passes|passed|clean|0\s+(?:errors?|violations?))\b/i,
1064
+ /(?:全部|所有)[^。!?\n]{0,50}(?:布通|连通|完成|通过)|(?:完成|已完成|搞定|通过|布通|连通|无(?:错误|违规)|0\s*(?:错误|违规))/
1065
+ ];
1066
+ function isCompletionSentence(sentence) {
1067
+ return COMPLETION_PATTERNS.some((pattern) => pattern.test(sentence));
1068
+ }
1069
+ function detectCompletion(text, todos) {
1070
+ if (text.length === 0 || todos.length === 0) return void 0;
1071
+ const active = todos.filter((todo) => todo.status === "in_progress");
1072
+ if (active.length > 1) return void 0;
1073
+ const pool = active.length === 1 ? active : todos.filter((todo) => todo.status === "pending");
1074
+ if (pool.length === 0) return void 0;
1075
+ const sentences = text.split(/(?<=[.!?。!?])\s+|\n+/).map((sentence) => sentence.trim()).filter((sentence) => sentence.length > 0);
1076
+ for (const sentence of sentences) {
1077
+ if (!isCompletionSentence(sentence)) continue;
1078
+ const sentencePhases = phasesOf(sentence);
1079
+ let best;
1080
+ let bestScore = 0;
1081
+ for (const todo of pool) {
1082
+ const todoPhases = phasesOf(todo.content);
1083
+ let score = 0;
1084
+ for (const phase of sentencePhases) if (todoPhases.has(phase)) score += 1;
1085
+ if (score > bestScore) {
1086
+ best = todo;
1087
+ bestScore = score;
1088
+ }
1089
+ }
1090
+ if (best === void 0 && active.length === 1 && sentencePhases.size === 0) {
1091
+ best = active[0];
1092
+ bestScore = 0.5;
1093
+ }
1094
+ if (best !== void 0) return { todo: best, phrase: sentence.slice(0, 120), score: bestScore };
1095
+ }
1096
+ return void 0;
1097
+ }
1098
+ function completionPayload(todos, matched) {
1099
+ const active = todos.filter((todo) => todo.status === "in_progress");
1100
+ if (active.length > 1) return void 0;
1101
+ const index = todos.findIndex((todo) => todo.content === matched.content);
1102
+ if (index < 0) return void 0;
1103
+ const next = todos.find((todo, at) => at > index && todo.status === "pending") ?? todos.find((todo, at) => at !== index && todo.status === "pending");
1104
+ const updated = todos.map((todo, at) => ({
1105
+ content: todo.content,
1106
+ status: at === index ? "completed" : next !== void 0 && todo.content === next.content ? "in_progress" : todo.status === "in_progress" && at !== index ? "completed" : todo.status
1107
+ }));
1108
+ return JSON.stringify({ todos: updated });
1109
+ }
1110
+ function serviceOf2(scope, name) {
1111
+ try {
1112
+ const direct = scope[name];
1113
+ if (direct !== void 0) return direct;
1114
+ } catch {
1115
+ }
1116
+ try {
1117
+ const get = scope.get;
1118
+ return typeof get === "function" ? get.call(scope, name) : void 0;
1119
+ } catch {
1120
+ return void 0;
1121
+ }
1122
+ }
1123
+ function sessionRoute2(agent) {
1124
+ try {
1125
+ const read = agent?.session?.requestHeader;
1126
+ const header = typeof read === "function" ? read.call(agent?.session) : void 0;
1127
+ const config = header?.config;
1128
+ const provider = config?.provider;
1129
+ const model = config?.model;
1130
+ if (typeof provider === "string" && provider.length > 0 && typeof model === "string" && model.length > 0) {
1131
+ return { provider, model };
1132
+ }
1133
+ } catch {
1134
+ }
1135
+ return void 0;
1136
+ }
1137
+ function noticeContext(agent, config, ctx) {
1138
+ const route = sessionRoute2(agent);
1139
+ const llm = serviceOf2(ctx, "llm");
1140
+ return {
1141
+ llm,
1142
+ route,
1143
+ translate: config.translateTodoContent && route !== void 0 && llm !== void 0,
1144
+ timeoutMs: config.todoTranslationTimeoutMs
1145
+ };
1146
+ }
1147
+ var TRANSLATION_CACHE_LIMIT = 256;
1148
+ var translationCache = /* @__PURE__ */ new Map();
1149
+ function parseStringArray(raw) {
1150
+ const start = raw.indexOf("[");
1151
+ const end = raw.lastIndexOf("]");
1152
+ if (start < 0 || end <= start) return void 0;
1153
+ try {
1154
+ const value = JSON.parse(raw.slice(start, end + 1));
1155
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
1156
+ } catch {
1157
+ }
1158
+ return void 0;
1159
+ }
1160
+ async function translateBatch(contents, context) {
1161
+ if (context.llm === void 0 || typeof context.llm.stream !== "function" || context.route === void 0) return void 0;
1162
+ const controller = new AbortController();
1163
+ const timer = setTimeout(() => controller.abort(new Error("todo translation timeout")), context.timeoutMs);
1164
+ try {
1165
+ const stream = await context.llm.stream({
1166
+ provider: context.route.provider,
1167
+ model: context.route.model,
1168
+ 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.",
1169
+ messages: [{ role: "user", content: [{ type: "text", text: JSON.stringify(contents) }] }],
1170
+ temperature: 0,
1171
+ signal: controller.signal
1172
+ });
1173
+ if (stream === null || typeof stream !== "object") return void 0;
1174
+ let text = "";
1175
+ for await (const chunk of stream) {
1176
+ if (controller.signal.aborted) return void 0;
1177
+ if (chunk?.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
1178
+ if (chunk?.type === "finish") {
1179
+ const kind = chunk.reason?.kind;
1180
+ if (typeof kind === "string" && kind !== "stop") return void 0;
1181
+ }
1182
+ }
1183
+ const parsed = parseStringArray(text);
1184
+ if (parsed === void 0 || parsed.length !== contents.length) return void 0;
1185
+ return parsed;
1186
+ } catch {
1187
+ return void 0;
1188
+ } finally {
1189
+ clearTimeout(timer);
1190
+ }
1191
+ }
1192
+ async function withTimeout(value, ms) {
1193
+ let timer;
1194
+ const timeout = new Promise((resolve2) => {
1195
+ timer = setTimeout(() => resolve2(void 0), ms);
1196
+ timer.unref?.();
1197
+ });
1198
+ try {
1199
+ return await Promise.race([value, timeout]);
1200
+ } finally {
1201
+ if (timer !== void 0) clearTimeout(timer);
1202
+ }
1203
+ }
1204
+ async function displayTodoContents(contents, context) {
1205
+ if (!context.translate) return contents;
1206
+ const pending = [];
1207
+ const seen = /* @__PURE__ */ new Set();
1208
+ for (const content of contents) {
1209
+ if (containsCjk(content) || translationCache.has(content) || seen.has(content)) continue;
1210
+ seen.add(content);
1211
+ pending.push(content);
1212
+ }
1213
+ if (pending.length > 0) {
1214
+ const translated = await withTimeout(translateBatch(pending, context), context.timeoutMs + 250);
1215
+ if (translated !== void 0) {
1216
+ for (let index = 0; index < pending.length; index += 1) {
1217
+ const value = translated[index];
1218
+ if (typeof value !== "string" || value.trim() === "") continue;
1219
+ if (translationCache.size >= TRANSLATION_CACHE_LIMIT) {
1220
+ const oldest = translationCache.keys().next();
1221
+ if (oldest.done !== true) translationCache.delete(oldest.value);
1222
+ }
1223
+ translationCache.set(pending[index], value.trim());
1224
+ }
1225
+ }
1226
+ }
1227
+ return contents.map((content) => {
1228
+ const translated = translationCache.get(content);
1229
+ if (translated === void 0 || containsCjk(content)) return content;
1230
+ return translated + "\uFF08" + content + "\uFF09";
1231
+ });
1232
+ }
1233
+ function suggestedTodoPayload(todos, matched) {
1234
+ const active = todos.filter((todo) => todo.status === "in_progress");
1235
+ if (active.length > 1) return void 0;
1236
+ const next = todos.map((todo) => ({
1237
+ content: todo.content,
1238
+ status: todo.content === matched.content ? "in_progress" : todo.status === "in_progress" ? "completed" : todo.status
1239
+ }));
1240
+ return JSON.stringify({ todos: next });
1241
+ }
1242
+ function installTaskGuard(ctx, input) {
1243
+ const config = resolveConfig(input);
1244
+ const bus = ctx;
1245
+ const sessions = /* @__PURE__ */ new Map();
1246
+ const intentBuffers = /* @__PURE__ */ new Map();
1247
+ bus.on("tools/pre-execute", async (exec, next) => {
1248
+ if (!config.enabled) return next();
1249
+ if (exec.name === "todo_write") {
1250
+ const todos = readTodos(exec.arguments);
1251
+ if (config.rejectMissingActive && todos !== null && leavesPendingWithoutActive(todos)) {
1252
+ return { kind: "deny", reason: denyMissingActive(todos, config) };
1253
+ }
1254
+ return next();
1255
+ }
1256
+ if (config.blockAfterCalls > 0 && exec.parent === void 0 && isTracked(exec.name, config)) {
1257
+ const state = sessions.get(sessionIdOf2(exec.agent));
1258
+ if (state?.todos != null && hasUnfinished(state.todos) && state.callsSinceWrite >= config.blockAfterCalls) {
1259
+ return { kind: "deny", reason: denyStale(state, config) };
1260
+ }
1261
+ }
1262
+ return next();
1263
+ });
1264
+ bus.on("tools/post-execute", async (exec, result, next) => {
1265
+ const downstream = await next();
1266
+ if (!config.enabled) return downstream;
1267
+ if (exec.name === "todo_write") {
1268
+ if (result.isError) return downstream;
1269
+ const todos = readTodos(exec.arguments);
1270
+ if (todos === null) return downstream;
1271
+ const sessionId2 = sessionIdOf2(exec.agent);
1272
+ if (sessionId2 !== "") {
1273
+ resetState(sessions, sessionId2, todos);
1274
+ intentBuffers.delete(sessionId2);
1275
+ }
1276
+ if (!config.rejectMissingActive && leavesPendingWithoutActive(todos)) {
1277
+ const notice = await noticeMissingActive(
1278
+ todos,
1279
+ config,
1280
+ sourceKindFor(exec.agent, config),
1281
+ noticeContext(exec.agent, config, ctx)
1282
+ );
1283
+ return attachContext(downstream, notice);
1284
+ }
1285
+ return downstream;
1286
+ }
1287
+ if (exec.parent !== void 0 || result.isError || !isTracked(exec.name, config)) return downstream;
1288
+ const sessionId = sessionIdOf2(exec.agent);
1289
+ if (sessionId === "") return downstream;
1290
+ const state = sessions.get(sessionId);
1291
+ if (state?.todos == null || !hasUnfinished(state.todos)) return downstream;
1292
+ state.callsSinceWrite += 1;
1293
+ if (config.detectStepIntent && !state.intentNotifiedThisStep) {
1294
+ const buffer = intentBuffers.get(sessionId) ?? "";
1295
+ const completed = detectCompletion(buffer, state.todos);
1296
+ if (completed !== void 0) {
1297
+ state.intentNotifiedThisStep = true;
1298
+ const notice = await buildCompletionNotice(
1299
+ state,
1300
+ completed,
1301
+ config,
1302
+ sourceKindFor(exec.agent, config),
1303
+ noticeContext(exec.agent, config, ctx)
1304
+ );
1305
+ return attachContext(downstream, notice);
1306
+ }
1307
+ const match = detectStepIntent(buffer, state.todos);
1308
+ if (match !== void 0) {
1309
+ state.intentNotifiedThisStep = true;
1310
+ const notice = await buildIntentNotice(
1311
+ state,
1312
+ match,
1313
+ config,
1314
+ sourceKindFor(exec.agent, config),
1315
+ noticeContext(exec.agent, config, ctx)
1316
+ );
1317
+ return attachContext(downstream, notice);
1318
+ }
1319
+ }
1320
+ if (state.reminderDeliveredThisStep) return downstream;
1321
+ const threshold = config.staleAfterCalls + state.remindersSent * config.repeatEveryCalls;
1322
+ if (state.callsSinceWrite < threshold) return downstream;
1323
+ if (config.repeatEveryCalls === 0 && state.remindersSent > 0) return downstream;
1324
+ const reminder = await buildReminder(
1325
+ state,
1326
+ config,
1327
+ sourceKindFor(exec.agent, config),
1328
+ noticeContext(exec.agent, config, ctx)
1329
+ );
1330
+ if (reminder === void 0) return downstream;
1331
+ state.remindersSent += 1;
1332
+ state.reminderDeliveredThisStep = true;
1333
+ return attachContext(downstream, reminder);
1334
+ });
1335
+ bus.on("agent/pre-step", async (payload, next) => {
1336
+ const sessionId = sessionIdOf2(payload.agent);
1337
+ if (sessionId !== "") intentBuffers.delete(sessionId);
1338
+ const state = sessions.get(sessionId);
1339
+ if (state !== void 0) {
1340
+ state.reminderDeliveredThisStep = false;
1341
+ state.intentNotifiedThisStep = false;
1342
+ }
1343
+ return next();
1344
+ });
1345
+ bus.on("agent/assistant-stream", (payload) => {
1346
+ if (!config.enabled || !config.detectStepIntent) return;
1347
+ const frame = payload?.frame;
1348
+ if (frame === null || typeof frame !== "object" || frame.type !== "chunk") return;
1349
+ const chunk = frame.chunk;
1350
+ if (chunk === null || typeof chunk !== "object") return;
1351
+ if (chunk.type !== "text-delta" && chunk.type !== "reasoning-delta") return;
1352
+ if (typeof chunk.text !== "string" || chunk.text === "") return;
1353
+ const attemptId = typeof frame.attemptId === "string" ? frame.attemptId : "";
1354
+ const separator = attemptId.lastIndexOf(":");
1355
+ const sessionId = separator > 0 ? attemptId.slice(0, separator) : "";
1356
+ if (sessionId === "") return;
1357
+ const next = ((intentBuffers.get(sessionId) ?? "") + chunk.text).slice(-4e3);
1358
+ intentBuffers.set(sessionId, next);
1359
+ });
1360
+ bus.on("session/event", (session, event) => {
1361
+ const sessionId = sessionIdOf2({ session });
1362
+ if (sessionId === "") return;
1363
+ if (event.type === "turn/start" || event.type === "turn/end") {
1364
+ sessions.delete(sessionId);
1365
+ intentBuffers.delete(sessionId);
1366
+ return;
1367
+ }
1368
+ if (event.type === "todo/write") {
1369
+ const todos = readTodos(event.data);
1370
+ if (todos !== null) resetState(sessions, sessionId, todos);
1371
+ intentBuffers.delete(sessionId);
1372
+ }
1373
+ });
1374
+ }
1375
+ function resolveConfig(input) {
1376
+ if (input !== void 0 && (input === null || typeof input !== "object" || Array.isArray(input))) {
1377
+ throw new TypeError("task-guard: config must be an object");
1378
+ }
1379
+ const raw = input ?? {};
1380
+ for (const key of Object.keys(raw)) {
1381
+ if (!CONFIG_KEYS.has(key)) throw new TypeError(`task-guard: unknown config field "${key}"`);
1382
+ }
1383
+ const enabled = readBoolean(raw.enabled, true, "enabled");
1384
+ const locale = readLocale(raw.locale);
1385
+ const staleAfterCalls = readInteger(raw.staleAfterCalls, 5, 1, "staleAfterCalls");
1386
+ const repeatEveryCalls = readInteger(raw.repeatEveryCalls, 4, 0, "repeatEveryCalls");
1387
+ const blockAfterCalls = readInteger(raw.blockAfterCalls, 0, 0, "blockAfterCalls");
1388
+ const rejectMissingActive = readBoolean(raw.rejectMissingActive, false, "rejectMissingActive");
1389
+ const sourceKind = readSourceKind(raw.sourceKind);
1390
+ const maxListItems = readInteger(raw.maxListItems, 6, 1, "maxListItems");
1391
+ const detectStepIntent2 = readBoolean(raw.detectStepIntent, true, "detectStepIntent");
1392
+ const translateTodoContent = readBoolean(raw.translateTodoContent, true, "translateTodoContent");
1393
+ const todoTranslationTimeoutMs = readInteger(raw.todoTranslationTimeoutMs, 3e3, 500, "todoTranslationTimeoutMs");
1394
+ const include = compilePatterns(readStringArray(raw.include, [], "include"));
1395
+ const exclude = compilePatterns(readStringArray(raw.exclude, DEFAULT_EXCLUDES, "exclude"));
1396
+ if (blockAfterCalls > 0 && blockAfterCalls <= staleAfterCalls) {
1397
+ throw new TypeError("task-guard: blockAfterCalls must be greater than staleAfterCalls");
1398
+ }
1399
+ return {
1400
+ enabled,
1401
+ locale,
1402
+ staleAfterCalls,
1403
+ repeatEveryCalls,
1404
+ blockAfterCalls,
1405
+ rejectMissingActive,
1406
+ sourceKind,
1407
+ include,
1408
+ exclude,
1409
+ maxListItems,
1410
+ detectStepIntent: detectStepIntent2,
1411
+ translateTodoContent,
1412
+ todoTranslationTimeoutMs
1413
+ };
1414
+ }
1415
+ function readBoolean(value, fallback, field) {
1416
+ if (value === void 0) return fallback;
1417
+ if (typeof value !== "boolean") throw new TypeError(`task-guard: ${field} must be a boolean`);
1418
+ return value;
1419
+ }
1420
+ function readLocale(value) {
1421
+ if (value === void 0) return "zh";
1422
+ if (value !== "zh" && value !== "en") throw new TypeError('task-guard: locale must be "zh" or "en"');
1423
+ return value;
1424
+ }
1425
+ function readSourceKind(value) {
1426
+ if (value === void 0) return "auto";
1427
+ if (value !== "auto" && value !== "v3" && value !== "v4") {
1428
+ throw new TypeError('task-guard: sourceKind must be "auto", "v3", or "v4"');
1429
+ }
1430
+ return value;
1431
+ }
1432
+ function readInteger(value, fallback, minimum, field) {
1433
+ if (value === void 0) return fallback;
1434
+ if (!Number.isInteger(value) || value < minimum) {
1435
+ throw new TypeError(`task-guard: ${field} must be an integer >= ${minimum}`);
1436
+ }
1437
+ return value;
1438
+ }
1439
+ function readStringArray(value, fallback, field) {
1440
+ if (value === void 0) return [...fallback];
1441
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item.length === 0)) {
1442
+ throw new TypeError(`task-guard: ${field} must be an array of non-empty strings`);
1443
+ }
1444
+ return [...value];
1445
+ }
1446
+ function compilePatterns(patterns) {
1447
+ return patterns.map((pattern) => {
1448
+ const escaped = pattern.replace(/[|\\{}()[\]^$+?.]/g, String.raw`\$&`);
1449
+ return new RegExp(`^${escaped.replaceAll("*", ".*")}$`);
1450
+ });
1451
+ }
1452
+ function isTracked(toolName, config) {
1453
+ if (config.include.length > 0 && !config.include.some((pattern) => pattern.test(toolName))) return false;
1454
+ return !config.exclude.some((pattern) => pattern.test(toolName));
1455
+ }
1456
+ function readTodos(value) {
1457
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
1458
+ const record = value;
1459
+ if (Object.keys(record).some((key) => key !== "todos")) return null;
1460
+ if (!Array.isArray(record.todos)) return null;
1461
+ const todos = [];
1462
+ const seen = /* @__PURE__ */ new Set();
1463
+ for (const item of record.todos) {
1464
+ if (item === null || typeof item !== "object" || Array.isArray(item)) return null;
1465
+ const entry = item;
1466
+ if (Object.keys(entry).some((key) => key !== "content" && key !== "status")) return null;
1467
+ if (typeof entry.content !== "string" || typeof entry.status !== "string" || !STATUSES.has(entry.status)) {
1468
+ return null;
1469
+ }
1470
+ const content = entry.content.trim();
1471
+ if (content === "" || seen.has(content)) return null;
1472
+ seen.add(content);
1473
+ todos.push({ content, status: entry.status });
1474
+ }
1475
+ return todos;
1476
+ }
1477
+ function resetState(sessions, sessionId, todos) {
1478
+ sessions.set(sessionId, {
1479
+ todos: todos.map((todo) => ({ ...todo })),
1480
+ callsSinceWrite: 0,
1481
+ remindersSent: 0,
1482
+ reminderDeliveredThisStep: false,
1483
+ intentNotifiedThisStep: false
1484
+ });
1485
+ }
1486
+ function sessionIdOf2(agent) {
1487
+ const id = agent?.session?.id;
1488
+ return typeof id === "string" && id !== "" ? id : "";
1489
+ }
1490
+ function sourceKindFor(agent, config) {
1491
+ if (config.sourceKind !== "auto") return config.sourceKind;
1492
+ const version = agent?.session?.header?.version;
1493
+ return typeof version === "number" && version < 4 ? "v3" : "v4";
1494
+ }
1495
+ function hasUnfinished(todos) {
1496
+ return todos.some((todo) => todo.status !== "completed");
1497
+ }
1498
+ function leavesPendingWithoutActive(todos) {
1499
+ const pending = todos.some((todo) => todo.status === "pending");
1500
+ const active = todos.some((todo) => todo.status === "in_progress");
1501
+ return pending && !active;
1502
+ }
1503
+ function denyMissingActive(todos, config) {
1504
+ const pending = todos.filter((todo) => todo.status === "pending").length;
1505
+ if (config.locale === "en") {
1506
+ 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.`;
1507
+ }
1508
+ 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`;
1509
+ }
1510
+ async function noticeMissingActive(todos, config, sourceKind, context) {
1511
+ const pending = todos.filter((todo) => todo.status === "pending").length;
1512
+ const completed = todos.some((todo) => todo.status === "completed");
1513
+ const remaining = todos.filter((todo) => todo.status !== "completed");
1514
+ const display = await displayTodoContents(remaining.map((todo) => todo.content), context);
1515
+ const quoted = remaining.slice(0, config.maxListItems).map((todo, index) => (todo.status === "in_progress" ? "[~] " : "[ ] ") + truncate(display[index], 60)).join("\n");
1516
+ const omitted = remaining.length - config.maxListItems;
1517
+ const items = omitted > 0 ? quoted + "\n\u2026 +" + omitted : quoted;
1518
+ 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";
1519
+ return createNotice(text, config.locale === "en" ? "todo has no active task" : "todo \u6CA1\u6709\u8FDB\u884C\u4E2D\u4EFB\u52A1", sourceKind);
1520
+ }
1521
+ function denyStale(state, config) {
1522
+ if (config.locale === "en") {
1523
+ 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.`;
1524
+ }
1525
+ 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`;
1526
+ }
1527
+ async function buildReminder(state, config, sourceKind, context) {
1528
+ const todos = state.todos;
1529
+ if (todos === null) return void 0;
1530
+ const remaining = todos.filter((todo) => todo.status !== "completed");
1531
+ if (remaining.length === 0) return void 0;
1532
+ const active = todos.filter((todo) => todo.status === "in_progress");
1533
+ const activeDisplay = await displayTodoContents(active.map((todo) => todo.content), context);
1534
+ const activeText = active.length === 0 ? config.locale === "en" ? "(none)" : "\uFF08\u65E0\uFF09" : activeDisplay.join(config.locale === "en" ? ", " : "\u3001");
1535
+ const display = await displayTodoContents(remaining.map((todo) => todo.content), context);
1536
+ const quoted = remaining.slice(0, config.maxListItems).map((todo, index) => (todo.status === "in_progress" ? "[~] " : "[ ] ") + truncate(display[index], 60)).join("\n");
1537
+ const omitted = remaining.length - config.maxListItems;
1538
+ const items = omitted > 0 ? quoted + "\n\u2026 +" + omitted : quoted;
1539
+ const activeOne = active.length === 1 ? active[0] : void 0;
1540
+ const suggested = activeOne === void 0 ? void 0 : completionPayload(todos, activeOne);
1541
+ const text = config.locale === "en" ? [
1542
+ "[Todo sync] " + state.callsSinceWrite + " tool calls have run since the last todo_write.",
1543
+ "In progress: " + activeText,
1544
+ "Remaining:\n" + items,
1545
+ 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:",
1546
+ suggested ?? "",
1547
+ "(Tip: todo titles can be written in Chinese.)"
1548
+ ].filter((line) => line !== "").join("\n") : [
1549
+ "\u3010todo \u540C\u6B65\u3011\u8DDD\u4E0A\u6B21 todo_write \u5DF2\u8FC7 " + state.callsSinceWrite + " \u6B21\u5DE5\u5177\u8C03\u7528\u3002",
1550
+ "\u8FDB\u884C\u4E2D\uFF1A" + activeText,
1551
+ "\u5269\u4F59\uFF1A\n" + items,
1552
+ 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",
1553
+ suggested ?? "",
1554
+ "\uFF08\u63D0\u793A\uFF1Atodo \u5185\u5BB9\u53EF\u4EE5\u76F4\u63A5\u7528\u4E2D\u6587\u4E66\u5199\u3002\uFF09"
1555
+ ].filter((line) => line !== "").join("\n");
1556
+ const summary = config.locale === "en" ? "todo stale \xB7 " + state.callsSinceWrite + " calls" : "todo \u672A\u66F4\u65B0 \xB7 " + state.callsSinceWrite + " \u6B21\u8C03\u7528";
1557
+ return createNotice(text, summary, sourceKind);
1558
+ }
1559
+ async function buildCompletionNotice(state, match, config, sourceKind, context) {
1560
+ const todos = state.todos ?? [];
1561
+ const [display] = await displayTodoContents([match.todo.content], context);
1562
+ const suggested = completionPayload(todos, match.todo);
1563
+ const phrase = truncate(match.phrase, 80);
1564
+ const text = config.locale === "en" ? [
1565
+ '[Todo sync] The assistant text looks like a completed phase: "' + display + '".',
1566
+ "Source: " + phrase,
1567
+ 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:",
1568
+ suggested ?? "",
1569
+ "If it is still running, keep that task in_progress; do not mark it completed yet.",
1570
+ "(Tip: todo titles can be written in Chinese.)"
1571
+ ].filter((line) => line !== "").join("\n") : [
1572
+ "\u3010todo \u540C\u6B65\u3011\u68C0\u6D4B\u5230\u9636\u6BB5\u5B8C\u6210\uFF1A\u300C" + display + "\u300D",
1573
+ "\u4F9D\u636E\uFF1A" + phrase,
1574
+ 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",
1575
+ suggested ?? "",
1576
+ "\u5982\u679C\u4ECD\u5728\u8FDB\u884C\uFF0C\u8BF7\u4FDD\u6301\u8BE5\u5F85\u529E\u4E3A in_progress\uFF0C\u4E0D\u8981\u63D0\u524D\u6807 completed\u3002",
1577
+ "\uFF08\u63D0\u793A\uFF1Atodo \u5185\u5BB9\u53EF\u4EE5\u76F4\u63A5\u7528\u4E2D\u6587\u4E66\u5199\u3002\uFF09"
1578
+ ].filter((line) => line !== "").join("\n");
1579
+ const summary = config.locale === "en" ? "todo complete \xB7 " + truncate(display, 40) : "todo \u5B8C\u6210 \xB7 " + truncate(display, 40);
1580
+ return createNotice(text, summary, sourceKind);
1581
+ }
1582
+ async function buildIntentNotice(state, match, config, sourceKind, context) {
1583
+ const todos = state.todos ?? [];
1584
+ const [display] = await displayTodoContents([match.todo.content], context);
1585
+ const suggested = suggestedTodoPayload(todos, match.todo);
1586
+ const phrase = truncate(match.phrase, 60);
1587
+ const text = config.locale === "en" ? [
1588
+ '[Todo sync] Your reasoning says "' + phrase + '", which matches the pending todo "' + display + '", but that task is not in_progress.',
1589
+ 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:",
1590
+ suggested ?? "",
1591
+ "(Tip: todo titles can be written in Chinese.)"
1592
+ ].filter((line) => line !== "").join("\n") : [
1593
+ "\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",
1594
+ 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",
1595
+ suggested ?? "",
1596
+ "\uFF08\u63D0\u793A\uFF1Atodo \u5185\u5BB9\u53EF\u4EE5\u76F4\u63A5\u7528\u4E2D\u6587\u4E66\u5199\u3002\uFF09"
1597
+ ].filter((line) => line !== "").join("\n");
1598
+ const summary = config.locale === "en" ? "todo intent \xB7 " + truncate(phrase, 40) : "todo \u610F\u56FE \xB7 " + truncate(phrase, 40);
1599
+ return createNotice(text, summary, sourceKind);
1600
+ }
1601
+ function truncate(value, max) {
1602
+ return value.length <= max ? value : `${value.slice(0, max - 1)}\u2026`;
1603
+ }
1604
+ function createNotice(text, summary, sourceKind) {
1605
+ const boundedSummary = summary.length <= SUMMARY_MAX_CHARS ? summary : `${summary.slice(0, SUMMARY_MAX_CHARS - 1)}\u2026`;
1606
+ const source = sourceKind === "v3" ? { kind: "plugin", plugin: "task-guard", form: "notice", summary: boundedSummary } : { kind: "plugin:task-guard", form: "notice", summary: boundedSummary };
1607
+ return deepFreeze({
1608
+ id: randomUUID2(),
1609
+ role: "user",
1610
+ content: [{ type: "text", text }],
1611
+ source
1612
+ });
1613
+ }
1614
+ function attachContext(decision, context) {
1615
+ return {
1616
+ ...decision,
1617
+ additionalContexts: [context, ...decision.additionalContexts ?? []]
1618
+ };
1619
+ }
1620
+ function deepFreeze(value) {
1621
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
1622
+ Object.freeze(value);
1623
+ for (const key of Object.keys(value)) deepFreeze(value[key]);
1624
+ }
1625
+ return value;
1626
+ }
1627
+
1628
+ // src/task-guard/index.ts
1629
+ var DEFAULT_TASK_GUARD_CONFIG = {
1630
+ enabled: true,
1631
+ locale: "zh",
1632
+ staleAfterCalls: 5,
1633
+ repeatEveryCalls: 4,
1634
+ blockAfterCalls: 0,
1635
+ rejectMissingActive: false,
1636
+ sourceKind: "auto",
1637
+ maxListItems: 6,
1638
+ detectStepIntent: true,
1639
+ translateTodoContent: true,
1640
+ todoTranslationTimeoutMs: 3e3,
1641
+ include: [],
1642
+ exclude: ["todo_write", "ask_user_question"]
1643
+ };
1644
+ var Config4 = z4.object({
1645
+ enabled: z4.boolean().default(DEFAULT_TASK_GUARD_CONFIG.enabled).volatile(),
1646
+ locale: z4.union(["zh", "en"]).default(DEFAULT_TASK_GUARD_CONFIG.locale).volatile(),
1647
+ staleAfterCalls: z4.number().min(1).default(DEFAULT_TASK_GUARD_CONFIG.staleAfterCalls).volatile(),
1648
+ repeatEveryCalls: z4.number().min(0).default(DEFAULT_TASK_GUARD_CONFIG.repeatEveryCalls).volatile(),
1649
+ blockAfterCalls: z4.number().min(0).default(DEFAULT_TASK_GUARD_CONFIG.blockAfterCalls).volatile(),
1650
+ rejectMissingActive: z4.boolean().default(DEFAULT_TASK_GUARD_CONFIG.rejectMissingActive).volatile(),
1651
+ sourceKind: z4.union(["auto", "v3", "v4"]).default(DEFAULT_TASK_GUARD_CONFIG.sourceKind).volatile(),
1652
+ maxListItems: z4.number().min(1).default(DEFAULT_TASK_GUARD_CONFIG.maxListItems).volatile(),
1653
+ detectStepIntent: z4.boolean().default(DEFAULT_TASK_GUARD_CONFIG.detectStepIntent).volatile(),
1654
+ translateTodoContent: z4.boolean().default(DEFAULT_TASK_GUARD_CONFIG.translateTodoContent).volatile(),
1655
+ todoTranslationTimeoutMs: z4.number().min(500).max(15e3).default(DEFAULT_TASK_GUARD_CONFIG.todoTranslationTimeoutMs).volatile(),
1656
+ include: z4.array(z4.string()).default(DEFAULT_TASK_GUARD_CONFIG.include).volatile(),
1657
+ exclude: z4.array(z4.string()).default(DEFAULT_TASK_GUARD_CONFIG.exclude).volatile()
1658
+ }).default(DEFAULT_TASK_GUARD_CONFIG);
1659
+ function apply4(ctx, config) {
1660
+ installTaskGuard(ctx, toPlain(config));
1661
+ }
1662
+
1663
+ // src/index.ts
1664
+ var Config5 = z5.object({
1665
+ enabled: z5.boolean().default(DEFAULT_SCHEDULE_CONFIG.enabled).volatile(),
1666
+ lightStart: z5.string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/).default(DEFAULT_SCHEDULE_CONFIG.lightStart).volatile(),
1667
+ lightEnd: z5.string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/).default(DEFAULT_SCHEDULE_CONFIG.lightEnd).volatile(),
1668
+ autoReviewFix: Config2,
1669
+ taskGuard: Config4,
1670
+ restart: Config3
1671
+ }).default({
1672
+ enabled: DEFAULT_SCHEDULE_CONFIG.enabled,
1673
+ lightStart: DEFAULT_SCHEDULE_CONFIG.lightStart,
1674
+ lightEnd: DEFAULT_SCHEDULE_CONFIG.lightEnd,
1675
+ autoReviewFix: DEFAULT_AUTO_REVIEW_CONFIG,
1676
+ taskGuard: DEFAULT_TASK_GUARD_CONFIG,
1677
+ restart: DEFAULT_RESTART_CONFIG
1678
+ });
1679
+ function mount(ctx, component, config) {
1680
+ try {
1681
+ ctx.plugin.call(ctx, component, config);
1682
+ } catch (error) {
1683
+ const logger = ctx.logger;
1684
+ logger?.warn?.(new Error("mcviseron: cannot mount a component", { cause: error }));
1685
+ }
1686
+ }
1687
+ function apply5(ctx, rawConfig) {
1688
+ const config = toPlain(rawConfig) ?? {};
1689
+ mount(ctx, appearance_exports, {
1690
+ enabled: config.enabled ?? DEFAULT_SCHEDULE_CONFIG.enabled,
1691
+ lightStart: config.lightStart ?? DEFAULT_SCHEDULE_CONFIG.lightStart,
1692
+ lightEnd: config.lightEnd ?? DEFAULT_SCHEDULE_CONFIG.lightEnd
1693
+ });
1694
+ mount(ctx, auto_review_fix_exports, toPlain(config.autoReviewFix) ?? DEFAULT_AUTO_REVIEW_CONFIG);
1695
+ mount(ctx, task_guard_exports, toPlain(config.taskGuard) ?? DEFAULT_TASK_GUARD_CONFIG);
1696
+ mount(ctx, restart_exports, toPlain(config.restart) ?? DEFAULT_RESTART_CONFIG);
1697
+ }
1698
+ export {
1699
+ Config5 as Config,
1700
+ apply5 as apply
1701
+ };