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
@@ -0,0 +1,421 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import {
4
+ chineseKey,
5
+ cleanTranslation,
6
+ clearTranslationCache,
7
+ isPredominantlyChinese,
8
+ englishText,
9
+ hasTranslation,
10
+ isAutoReviewText,
11
+ reviewerExcerpt,
12
+ translateForDisplay,
13
+ translationRoute,
14
+ withTranslation,
15
+ TRANSLATION_LABEL,
16
+ type LocaleText,
17
+ type TranslationSettings,
18
+ } from './translate.ts'
19
+
20
+ /**
21
+ * Two independent guards for the DSH Auto-review permission preset.
22
+ *
23
+ * 1. **Shutdown preset guard** — the Auto-review package migrates every live
24
+ * Auto session to Full access in its disposal effect. That is correct when
25
+ * the plugin is removed while the Host keeps running, but during a whole-Host
26
+ * shutdown it silently rewrites the stored preset, so the next launch comes
27
+ * back as Full access. The guard drops `permissionPresets.set` writes while
28
+ * the root fiber is not ACTIVE.
29
+ *
30
+ * 2. **Approval-reason translation** — when a review denies a call, the Web
31
+ * approval prompt shows the reviewer's own English note. That note is audited
32
+ * reasoning and must not be edited, so this guard only appends a Chinese
33
+ * translation to the localized display value.
34
+ *
35
+ * Both guards are feature-detected and degrade to a no-op, so the component
36
+ * keeps working across DSH generations that add or remove either seam.
37
+ */
38
+
39
+ /** Cordis `FiberState.ACTIVE` (see `@deepseek-ai/cordis` FiberState). */
40
+ const FIBER_STATE_ACTIVE = 2
41
+
42
+ /** Settings actually used at runtime. */
43
+ export interface AutoReviewSettings extends TranslationSettings {
44
+ keepPresetGuard: boolean
45
+ }
46
+
47
+ /** Service objects already guarded in this process (survives plugin reloads). */
48
+ const guardedPresets = new WeakSet<object>()
49
+ const guardedApproval = new WeakSet<object>()
50
+
51
+ /** Read one boolean setting without trusting its type. */
52
+ function boolSetting(source: Record<string, unknown>, key: string, fallback: boolean): boolean {
53
+ const value = source[key]
54
+ return typeof value === 'boolean' ? value : fallback
55
+ }
56
+
57
+ /** Read one string setting without trusting its type. */
58
+ function stringSetting(source: Record<string, unknown>, key: string, fallback: string): string {
59
+ const value = source[key]
60
+ return typeof value === 'string' ? value.trim() : fallback
61
+ }
62
+
63
+ /** Read one bounded integer setting without trusting its type. */
64
+ function numberSetting(source: Record<string, unknown>, key: string, fallback: number, min: number, max: number): number {
65
+ const value = source[key]
66
+ if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
67
+ return Math.min(Math.max(Math.trunc(value), min), max)
68
+ }
69
+
70
+ /**
71
+ * Resolve the `autoReview` config group. The group is validated by the Host
72
+ * schema, but every field is re-validated here so a hand-written patch or an
73
+ * older settings document can never break the component.
74
+ *
75
+ * @param config - the raw config group, if any.
76
+ * @returns the settings used at runtime.
77
+ */
78
+ export function normalizeConfig(config?: unknown): AutoReviewSettings {
79
+ const source = config !== null && typeof config === 'object' && !Array.isArray(config)
80
+ ? config as Record<string, unknown>
81
+ : {}
82
+ const translate = boolSetting(source, 'translateApprovalReason', true)
83
+ return {
84
+ keepPresetGuard: boolSetting(source, 'keepPresetGuard', true),
85
+ enabled: translate,
86
+ timeoutMs: numberSetting(source, 'translateTimeoutMs', 6000, 500, 60000),
87
+ maxChars: numberSetting(source, 'translateMaxChars', 4000, 100, 20000),
88
+ provider: stringSetting(source, 'translateProvider', ''),
89
+ model: stringSetting(source, 'translateModel', ''),
90
+ }
91
+ }
92
+
93
+ /** Reach one optional host service through the scoped injection seam. */
94
+ function whenService(ctx: Context, name: string, run: (scope: Context) => void): void {
95
+ try {
96
+ const inject = (ctx as unknown as { inject?: (deps: string[], callback: (scope: Context) => void) => unknown }).inject
97
+ if (typeof inject === 'function') {
98
+ inject.call(ctx, [name], run)
99
+ return
100
+ }
101
+ const get = (ctx as unknown as { get?: (key: string) => unknown }).get
102
+ const service = typeof get === 'function' ? get.call(ctx, name) : undefined
103
+ if (service !== undefined) run(ctx)
104
+ } catch {
105
+ /* a host without the seam simply keeps the unguarded behaviour */
106
+ }
107
+ }
108
+
109
+ /** Resolve one service value from a scope or its service registry. */
110
+ function serviceOf(scope: Context, name: string): unknown {
111
+ try {
112
+ const direct = (scope as unknown as Record<string, unknown>)[name]
113
+ if (direct !== undefined) return direct
114
+ } catch {
115
+ /* fall through to the registry */
116
+ }
117
+ try {
118
+ const get = (scope as unknown as { get?: (key: string) => unknown }).get
119
+ return typeof get === 'function' ? get.call(scope, name) : undefined
120
+ } catch {
121
+ return undefined
122
+ }
123
+ }
124
+
125
+ /** Register one teardown on the scoped context when the host supports effects. */
126
+ function effectOf(scope: Context, setup: () => () => void, label: string): void {
127
+ try {
128
+ const effect = (scope as unknown as { effect?: (body: () => () => void, label: string) => unknown }).effect
129
+ if (typeof effect === 'function') effect.call(scope, setup, label)
130
+ } catch {
131
+ /* diagnostics-only: a host without effect() still gets the guard */
132
+ }
133
+ }
134
+
135
+ /** Whether the root fiber is still ACTIVE, read defensively. */
136
+ function rootIsActive(root: unknown): boolean {
137
+ try {
138
+ const fiber = (root as { fiber?: { state?: unknown } } | null)?.fiber
139
+ const state = fiber?.state
140
+ if (typeof state !== 'number') return true
141
+ return state === FIBER_STATE_ACTIVE
142
+ } catch {
143
+ return true
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Suppress `permissionPresets.set` while the whole Host is going away.
149
+ *
150
+ * The wrapper is deliberately *not* removed on unload. Unload order decides
151
+ * whether an unwrap would run before the Auto-review migration; keeping the
152
+ * wrapper installed makes the guard independent of mount order, plugin reloads,
153
+ * and disposal ordering. While the root fiber is ACTIVE the wrapper is a
154
+ * pass-through, so a normal runtime removal still behaves like the bare service.
155
+ */
156
+ function installPresetGuard(ctx: Context): void {
157
+ whenService(ctx, 'permissionPresets', (scope) => {
158
+ const presets = serviceOf(scope, 'permissionPresets') as { set?: unknown } | undefined
159
+ if (presets === null || typeof presets !== 'object') return
160
+ if (typeof presets.set !== 'function') return
161
+ if (guardedPresets.has(presets)) return
162
+ const original = presets.set as (session: unknown, name: string) => unknown
163
+ const root = (scope as unknown as { root?: unknown }).root
164
+ const wrapper = function (this: unknown, session: unknown, name: string): unknown {
165
+ if (!rootIsActive(root)) return undefined
166
+ return original.call(this, session, name)
167
+ }
168
+ try {
169
+ presets.set = wrapper
170
+ guardedPresets.add(presets)
171
+ } catch {
172
+ /* a frozen service definition keeps the unguarded behaviour */
173
+ }
174
+ })
175
+ }
176
+
177
+ /**
178
+ * Append a Chinese translation of the reviewer's English note to one approval
179
+ * request's `displayReason`, and to the audited `reason` as a clearly
180
+ * delimited appendix.
181
+ *
182
+ * The audited note keeps its original text as the leading prefix. The reason
183
+ * appendix exists because consumers that only observe the durable
184
+ * `approval/asked` event (the email reminder fallback) never see
185
+ * `displayReason`; without it the translation would be dropped there.
186
+ *
187
+ * @param scope - the scoped host context (may carry `llm`).
188
+ * @param settings - resolved component settings.
189
+ * @param request - the borrowed approval request; never mutated.
190
+ * @param translate - translation seam (replaceable in tests).
191
+ * @returns the request to hand to the approval service.
192
+ */
193
+ export async function decorateApprovalRequest(
194
+ scope: Context,
195
+ settings: AutoReviewSettings,
196
+ request: unknown,
197
+ translate: typeof translateForDisplay = translateForDisplay,
198
+ ): Promise<unknown> {
199
+ if (!settings.enabled || request === null || typeof request !== 'object') return request
200
+ const display = (request as { displayReason?: unknown }).displayReason
201
+ if (display === null || typeof display !== 'object' || Array.isArray(display)) return request
202
+ const record = display as LocaleText
203
+ const key = chineseKey(record)
204
+ if (key === undefined) return request
205
+ const english = englishText(record)
206
+ if (english === undefined || !isAutoReviewText(english)) return request
207
+ const localized = record[key]
208
+ if (typeof localized !== 'string' || hasTranslation(localized)) return request
209
+ const excerpt = reviewerExcerpt(english)
210
+ if (excerpt.length === 0 || excerpt.length > settings.maxChars) return request
211
+ // The reviewer already wrote this note in Chinese: appending a "translation"
212
+ // would duplicate the same text. A few quoted Chinese instructions or a
213
+ // Windows path inside an English note are not predominantly Chinese.
214
+ if (isPredominantlyChinese(excerpt)) return request
215
+ if (translationRoute(settings, request) === undefined) return request
216
+
217
+ const llm = serviceOf(scope, 'llm') as { stream?: (options: unknown) => unknown } | undefined
218
+ const translated = await translate(llm, settings, request, excerpt)
219
+ if (translated === undefined) return request
220
+ const cleaned = cleanTranslation(translated)
221
+ if (cleaned.length === 0 || !/[\u4e00-\u9fff]/.test(cleaned)) return request
222
+
223
+ const reasonValue = (request as { reason?: unknown }).reason
224
+ const originalReason = typeof reasonValue === 'string' ? reasonValue : ''
225
+ const reasonWithTranslation = originalReason !== '' && !originalReason.includes(TRANSLATION_LABEL)
226
+ ? withTranslation(originalReason, cleaned)
227
+ : originalReason
228
+
229
+ return {
230
+ ...(request as Record<string, unknown>),
231
+ ...(reasonWithTranslation !== originalReason ? { reason: reasonWithTranslation } : {}),
232
+ displayReason: { ...record, [key]: withTranslation(localized, cleaned) },
233
+ }
234
+ }
235
+
236
+ /** Guard the approval seam so the escalation prompt carries a translation. */
237
+ /** One notice waiting for the denied tool's post-execute pass. */
238
+ interface RejectionNotice {
239
+ id: string
240
+ role: 'user'
241
+ content: [{ type: 'text'; text: string }]
242
+ source: Record<string, unknown>
243
+ }
244
+
245
+ interface RejectionRelay {
246
+ remember(key: string, notice: RejectionNotice): void
247
+ take(key: string): RejectionNotice | undefined
248
+ }
249
+
250
+ /** Session id of an approval request / tool execution. */
251
+ function sessionIdOf(agent: unknown): string {
252
+ const session = (agent as { session?: { id?: unknown } } | undefined)?.session
253
+ return typeof session?.id === 'string' ? session.id : ''
254
+ }
255
+
256
+ /** DSH session format version, when the agent exposes it. */
257
+ function sessionVersion(agent: unknown): number | undefined {
258
+ const version = (agent as { session?: { header?: { version?: unknown } } } | undefined)?.session?.header?.version
259
+ return typeof version === 'number' ? version : undefined
260
+ }
261
+
262
+ function rejectionKey(agent: unknown, callId: unknown): string {
263
+ if (typeof callId !== 'string' || callId === '') return ''
264
+ const sessionId = sessionIdOf(agent)
265
+ return sessionId === '' ? '' : sessionId + ':' + callId
266
+ }
267
+
268
+ /** The localized reviewer reason, falling back to the audited text. */
269
+ function approvalReasonText(request: unknown): string {
270
+ const record = request as { reason?: unknown; displayReason?: unknown }
271
+ const display = record.displayReason
272
+ if (display !== null && typeof display === 'object' && !Array.isArray(display)) {
273
+ const key = chineseKey(display as LocaleText)
274
+ if (key !== undefined) {
275
+ const value = (display as Record<string, unknown>)[key]
276
+ if (typeof value === 'string' && value !== '') return value
277
+ }
278
+ const english = englishText(display as LocaleText)
279
+ if (english !== undefined && english !== '') return english
280
+ }
281
+ return typeof record.reason === 'string' ? record.reason : ''
282
+ }
283
+
284
+ /** Whether this approval is the Auto-review denial that became manual approval. */
285
+ function isAutoReviewApproval(request: unknown): boolean {
286
+ const record = request as { reason?: unknown; displayReason?: unknown }
287
+ if (typeof record.reason === 'string' && isAutoReviewText(record.reason)) return true
288
+ const display = record.displayReason
289
+ if (display !== null && typeof display === 'object' && !Array.isArray(display)) {
290
+ const english = englishText(display as LocaleText)
291
+ if (english !== undefined && isAutoReviewText(english)) return true
292
+ }
293
+ return false
294
+ }
295
+
296
+ function rejectionSource(agent: unknown, summary: string): Record<string, unknown> {
297
+ return sessionVersion(agent) === 3
298
+ ? { kind: 'plugin', plugin: 'auto-review-fix', form: 'notice', summary }
299
+ : { kind: 'plugin:auto-review-fix', form: 'notice', summary }
300
+ }
301
+
302
+ function buildRejectionNotice(agent: unknown, request: unknown): RejectionNotice | undefined {
303
+ const reason = approvalReasonText(request)
304
+ if (reason === '') return undefined
305
+ const toolName = typeof (request as { toolName?: unknown }).toolName === 'string' && (request as { toolName: string }).toolName !== ''
306
+ ? (request as { toolName: string }).toolName
307
+ : '未知工具'
308
+ const text = [
309
+ '【审批被拒】工具 "' + toolName + '" 的人工审批被拒绝。',
310
+ '自动审查理由:',
311
+ reason,
312
+ '',
313
+ '请根据该理由调整方案,不要重复同一操作。',
314
+ ].join('\n')
315
+ return {
316
+ id: randomUUID(),
317
+ role: 'user',
318
+ content: [{ type: 'text', text }],
319
+ source: rejectionSource(agent, '审批被拒 · ' + toolName),
320
+ }
321
+ }
322
+
323
+ function createRejectionRelay(): RejectionRelay {
324
+ const notes = new Map<string, { notice: RejectionNotice; at: number }>()
325
+ const ttl = 120_000
326
+ return {
327
+ remember(key, notice) {
328
+ const now = Date.now()
329
+ for (const [oldKey, entry] of notes) if (now - entry.at > ttl) notes.delete(oldKey)
330
+ if (notes.size >= 50) {
331
+ const oldest = notes.keys().next().value
332
+ if (oldest !== undefined) notes.delete(oldest)
333
+ }
334
+ notes.set(key, { notice, at: now })
335
+ },
336
+ take(key) {
337
+ const entry = notes.get(key)
338
+ if (entry === undefined) return undefined
339
+ notes.delete(key)
340
+ return entry.notice
341
+ },
342
+ }
343
+ }
344
+
345
+ const relayedContexts = new WeakSet<object>()
346
+
347
+ function installRejectionRelay(ctx: Context, relay: RejectionRelay): void {
348
+ const target = ctx as unknown as { on?: (event: string, handler: (...args: any[]) => any) => unknown }
349
+ if (typeof target.on !== 'function' || relayedContexts.has(ctx as unknown as object)) return
350
+ relayedContexts.add(ctx as unknown as object)
351
+ target.on.call(ctx, 'tools/post-execute', async (exec: any, result: any, next: () => Promise<any>) => {
352
+ const downstream = (await next()) ?? { kind: 'accept' }
353
+ if (result?.isError !== true) return downstream
354
+ const key = rejectionKey(exec?.agent, exec?.callId)
355
+ if (key === '') return downstream
356
+ const notice = relay.take(key)
357
+ if (notice === undefined) return downstream
358
+ return {
359
+ ...downstream,
360
+ additionalContexts: [
361
+ ...(Array.isArray(downstream.additionalContexts) ? downstream.additionalContexts : []),
362
+ notice,
363
+ ],
364
+ }
365
+ })
366
+ }
367
+
368
+ function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings, relay: RejectionRelay): void {
369
+ whenService(ctx, 'approval', (scope) => {
370
+ const approval = serviceOf(scope, 'approval') as { request?: unknown } | undefined
371
+ if (approval === null || typeof approval !== 'object') return
372
+ const original = approval.request
373
+ if (typeof original !== 'function') return
374
+ if (guardedApproval.has(approval)) return
375
+ const call = original as (this: unknown, request: unknown) => Promise<unknown>
376
+ const wrapper = async function (this: unknown, request: unknown): Promise<unknown> {
377
+ let decorated: unknown = request
378
+ try {
379
+ decorated = await decorateApprovalRequest(scope, settings, request)
380
+ } catch {
381
+ decorated = request
382
+ }
383
+ const outcome = await call.call(this, decorated)
384
+ if (outcome === 'rejected' && isAutoReviewApproval(decorated)) {
385
+ const request = decorated as { agent?: unknown; callId?: unknown }
386
+ const key = rejectionKey(request.agent, request.callId)
387
+ const notice = buildRejectionNotice(request.agent, decorated)
388
+ if (key !== '' && notice !== undefined) relay.remember(key, notice)
389
+ }
390
+ return outcome
391
+ }
392
+ try {
393
+ approval.request = wrapper
394
+ guardedApproval.add(approval)
395
+ } catch {
396
+ return
397
+ }
398
+ effectOf(scope, () => () => {
399
+ if (approval.request === wrapper) approval.request = call
400
+ }, 'mcviseron: restore approval.request')
401
+ })
402
+ }
403
+
404
+ /**
405
+ * Install the Auto-review hardening component.
406
+ *
407
+ * @param ctx - the master plugin context supplied by the Cordis loader.
408
+ * @param config - the `autoReview` config group (validated by hand as well).
409
+ */
410
+ export function installAutoReview(ctx: Context, config?: unknown): void {
411
+ const settings = normalizeConfig(config)
412
+ if (settings.keepPresetGuard) installPresetGuard(ctx)
413
+ if (settings.enabled) {
414
+ const relay = createRejectionRelay()
415
+ installRejectionRelay(ctx, relay)
416
+ installApprovalTranslation(ctx, settings, relay)
417
+ }
418
+ }
419
+
420
+ /** Test seam: forget every cached display translation. */
421
+ export { clearTranslationCache }
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Chinese display translation for an English tool-approval reason.
3
+ *
4
+ * DSH's Auto-review layer escalates a denied call to a human approval prompt and
5
+ * carries the reviewer's own English explanation in `displayReason`. That text
6
+ * is the reviewer's reasoning: it is audited and must stay byte-identical. This
7
+ * module therefore never rewrites it — it only *appends* a translation to the
8
+ * localized display value the Web client resolves for the active language.
9
+ *
10
+ * Every host seam is optional. A host without `approval.request`,
11
+ * `displayReason`, `llm`, or a session request route simply keeps showing the
12
+ * untranslated reason. Translation is cached per source string and bounded by a
13
+ * timeout so an approval can never be held open indefinitely.
14
+ */
15
+
16
+ /** Locale-text record used by `ctx.locale.resolveText` (a map of locale id to text). */
17
+ export type LocaleText = Record<string, string>
18
+
19
+ /** Resolved, validated settings for this component. */
20
+ export interface TranslationSettings {
21
+ enabled: boolean
22
+ timeoutMs: number
23
+ maxChars: number
24
+ provider: string
25
+ model: string
26
+ }
27
+
28
+ /** Marker that keeps the appended block visually separate from the audited text. */
29
+ export const TRANSLATION_LABEL = '【审查理由 · 中文翻译】'
30
+
31
+ /** Instruction for the display-only translator. */
32
+ const SYSTEM_PROMPT = [
33
+ 'You translate the internal reviewer notes of an AI tool-approval system into Simplified Chinese.',
34
+ 'Rules:',
35
+ '- Output the translation only: no preamble, no quotes, no Markdown fences.',
36
+ '- Keep tool names, file paths, identifiers, URLs, JSON and code exactly as written.',
37
+ '- Preserve meaning and ordering; do not summarize, add or omit anything.',
38
+ ].join('\n')
39
+
40
+ /** Bounded source-string cache; FIFO eviction, process lifetime. */
41
+ const CACHE_LIMIT = 256
42
+ const cache = new Map<string, string>()
43
+
44
+ /** Languages whose key is already a Chinese translation slot. */
45
+ const CHINESE_KEY = /^zh(?:[-_]|$)/i
46
+
47
+ /** Whether one value is a plain locale-text record rather than a string or array. */
48
+ function isLocaleText(value: unknown): value is LocaleText {
49
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
50
+ }
51
+
52
+ /** The localized key that already holds Chinese text, if this host defines one. */
53
+ export function chineseKey(display: LocaleText): string | undefined {
54
+ if (typeof display['zh'] === 'string') return 'zh'
55
+ for (const key of Object.keys(display)) {
56
+ if (CHINESE_KEY.test(key) && typeof display[key] === 'string') return key
57
+ }
58
+ return undefined
59
+ }
60
+
61
+ /** The English surface the reviewer's own wording lives on. */
62
+ export function englishText(display: LocaleText): string | undefined {
63
+ if (typeof display['en'] === 'string') return display['en']
64
+ const key = chineseKey(display)
65
+ if (key !== undefined) return undefined
66
+ for (const value of Object.values(display)) if (typeof value === 'string') return value
67
+ return undefined
68
+ }
69
+
70
+ /** Whether one display string is the Auto-review escalation this component targets. */
71
+ export function isAutoReviewText(text: string): boolean {
72
+ return /auto[\s\-_]*review/i.test(text)
73
+ }
74
+
75
+ /**
76
+ * Strip Auto-review's own English lead-in so only the reviewer's wording is
77
+ * translated ("Auto review denied this call: <reason>" -> "<reason>").
78
+ */
79
+ export function reviewerExcerpt(text: string): string {
80
+ const match = /^\s*auto[\s\-_]*review\s+(?:denied\s+this\s+call|拒绝了此调用)\s*[::.]?\s*/i.exec(text)
81
+ if (match === null) return text.trim()
82
+ const rest = text.slice(match[0].length).trim()
83
+ return rest.length === 0 ? text.trim() : rest
84
+ }
85
+
86
+ /** Compose the display value: the audited original, then the appended translation. */
87
+ export function withTranslation(original: string, translation: string): string {
88
+ return original.length === 0
89
+ ? `${TRANSLATION_LABEL}\n${translation}`
90
+ : `${original}\n\n${TRANSLATION_LABEL}\n${translation}`
91
+ }
92
+
93
+ /** Whether one display value already carries an appended translation. */
94
+ export function hasTranslation(value: string): boolean {
95
+ return value.includes(TRANSLATION_LABEL)
96
+ }
97
+
98
+ /** Whether text already contains CJK characters. */
99
+ export function containsCjk(text: string): boolean {
100
+ return /[\u3400-\u9fff\uf900-\ufaff]/.test(text)
101
+ }
102
+
103
+ /**
104
+ * Whether the reviewer wrote the note in Chinese. A few quoted Chinese
105
+ * instructions or a Windows path inside an English note ("... (\"这个提示框
106
+ * 似乎卡住了?\") ...") must not suppress translation; compare the number of
107
+ * Chinese characters with the number of English word tokens instead.
108
+ */
109
+ export function isPredominantlyChinese(text: string): boolean {
110
+ const han = (text.match(/[\u3400-\u9fff\uf900-\ufaff]/g) ?? []).length
111
+ if (han === 0) return false
112
+ const englishWords = (text.match(/[A-Za-z][A-Za-z0-9_.-]*/g) ?? []).length
113
+ return englishWords <= Math.max(2, Math.ceil(han / 2))
114
+ }
115
+
116
+ /** Drop wrapping quotes, fences, and stray whitespace a model may add. */
117
+ export function cleanTranslation(raw: string): string {
118
+ let text = raw.trim()
119
+ const fenced = /^\s*```[a-zA-Z]*\n([\s\S]*?)\n```\s*$/.exec(text)
120
+ const fencedBody = fenced?.[1]
121
+ if (fencedBody !== undefined) text = fencedBody.trim()
122
+ if (text.length >= 2) {
123
+ const first = text[0]
124
+ const last = text[text.length - 1]
125
+ if ((first === '"' && last === '"') || (first === "'" && last === "'") || (first === '「' && last === '」')) {
126
+ text = text.slice(1, -1).trim()
127
+ }
128
+ }
129
+ return text
130
+ }
131
+
132
+ /** Read the session's current request route without trusting any of it. */
133
+ function sessionRoute(request: unknown): { provider: string; model: string } | undefined {
134
+ try {
135
+ const agent = (request as { agent?: { session?: { requestHeader?: () => unknown } } } | null)?.agent
136
+ const header = typeof agent?.session?.requestHeader === 'function' ? agent.session.requestHeader() : undefined
137
+ const config = (header as { config?: { provider?: unknown; model?: unknown } } | null)?.config
138
+ const provider = config?.provider
139
+ const model = config?.model
140
+ if (typeof provider === 'string' && provider.length > 0 && typeof model === 'string' && model.length > 0) {
141
+ return { provider, model }
142
+ }
143
+ } catch {
144
+ /* a host without a readable header simply has no route */
145
+ }
146
+ return undefined
147
+ }
148
+
149
+ /** Choose the model route for the display translation. */
150
+ export function translationRoute(
151
+ settings: TranslationSettings,
152
+ request: unknown,
153
+ ): { provider: string; model: string } | undefined {
154
+ if (settings.provider.length > 0 && settings.model.length > 0) {
155
+ return { provider: settings.provider, model: settings.model }
156
+ }
157
+ return sessionRoute(request)
158
+ }
159
+
160
+ /** Collect one streamed translation, tolerating every chunk shape. */
161
+ async function readStream(stream: AsyncIterable<unknown>, controller: AbortController): Promise<string | undefined> {
162
+ let text = ''
163
+ for await (const chunk of stream) {
164
+ if (controller.signal.aborted) return undefined
165
+ const value = chunk as { type?: unknown; text?: unknown; reason?: { kind?: unknown } } | null
166
+ if (value === null || typeof value !== 'object') continue
167
+ if (value.type === 'text-delta' && typeof value.text === 'string') {
168
+ text += value.text
169
+ if (text.length > 16000) break
170
+ continue
171
+ }
172
+ if (value.type === 'finish') {
173
+ const kind = value.reason?.kind
174
+ if (typeof kind === 'string' && kind !== 'stop') return undefined
175
+ }
176
+ }
177
+ return text
178
+ }
179
+
180
+ /**
181
+ * Translate one English reviewer note into Chinese for display only.
182
+ *
183
+ * @param llm - the host `llm` service (`stream(options)` returning chunks).
184
+ * @param settings - resolved component settings.
185
+ * @param request - the borrowed approval request, read for its session route.
186
+ * @param text - the English text to translate.
187
+ * @returns the cleaned Chinese text, or `undefined` when translation is unavailable.
188
+ */
189
+ export async function translateForDisplay(
190
+ llm: { stream?: (options: unknown) => unknown } | undefined,
191
+ settings: TranslationSettings,
192
+ request: unknown,
193
+ text: string,
194
+ ): Promise<string | undefined> {
195
+ const source = text.trim()
196
+ if (source.length === 0 || source.length > settings.maxChars) return undefined
197
+ const cached = cache.get(source)
198
+ if (cached !== undefined) return cached
199
+ if (llm === undefined || typeof llm.stream !== 'function') return undefined
200
+ const route = translationRoute(settings, request)
201
+ if (route === undefined) return undefined
202
+
203
+ const controller = new AbortController()
204
+ const timer = setTimeout(() => controller.abort(new Error('translation timeout')), settings.timeoutMs)
205
+ try {
206
+ const stream = await llm.stream({
207
+ provider: route.provider,
208
+ model: route.model,
209
+ system: SYSTEM_PROMPT,
210
+ messages: [{ role: 'user', content: [{ type: 'text', text: source }] }],
211
+ temperature: 0,
212
+ signal: controller.signal,
213
+ })
214
+ if (stream === null || typeof stream !== 'object') return undefined
215
+ const collected = await readStream(stream as AsyncIterable<unknown>, controller)
216
+ if (collected === undefined) return undefined
217
+ const cleaned = cleanTranslation(collected)
218
+ if (cleaned.length === 0) return undefined
219
+ if (cache.size >= CACHE_LIMIT) {
220
+ const oldest = cache.keys().next()
221
+ if (oldest.done !== true) cache.delete(oldest.value)
222
+ }
223
+ cache.set(source, cleaned)
224
+ return cleaned
225
+ } catch {
226
+ return undefined
227
+ } finally {
228
+ clearTimeout(timer)
229
+ }
230
+ }
231
+
232
+ /** Test seam: forget every cached translation. */
233
+ export function clearTranslationCache(): void {
234
+ cache.clear()
235
+ }