dsh-mcviseron-plugin 0.6.4 → 0.6.6

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.
@@ -0,0 +1,183 @@
1
+ import { SESSION_END_API } from '../api.ts'
2
+
3
+ export interface GlobalSessionEndAction {
4
+ sessionId: string
5
+ label: string
6
+ mode: 'restart' | 'close' | 'shutdown'
7
+ requestedBy: 'ai'
8
+ armedAt: number
9
+ waiting: boolean
10
+ runningAgents: number
11
+ runningJobs: number
12
+ }
13
+
14
+ const HOST_ID = 'mcviseron-session-end-global'
15
+ const FALLBACK_TOP = 56
16
+ const MIN_TOP = 120
17
+
18
+ /** Human label for one AI-armed process action. */
19
+ export function globalNoticeText(action: GlobalSessionEndAction): string {
20
+ const name = action.label.trim() !== '' ? action.label : '会话 …' + action.sessionId.slice(-6)
21
+ const mode = action.mode === 'restart' ? '自动重启' : action.mode === 'close' ? '自动关闭 DSH' : '关闭电脑'
22
+ return '「' + name + '」已启用 AI 会话' + mode
23
+ }
24
+
25
+ export function globalNoticeKey(action: GlobalSessionEndAction): string {
26
+ return action.sessionId + ':' + action.mode + ':' + String(action.armedAt)
27
+ }
28
+
29
+ function navigationBottom(): number {
30
+ for (const selector of ['header', '[role="banner"]']) {
31
+ const element = document.querySelector(selector)
32
+ if (element === null) continue
33
+ const rect = element.getBoundingClientRect()
34
+ if (rect.height > 0 && rect.top <= 8) return Math.round(rect.bottom)
35
+ }
36
+ return FALLBACK_TOP
37
+ }
38
+
39
+ function placeBelowNavigation(host: HTMLDivElement): void {
40
+ // A header that spans the whole app would otherwise put the fixed card below
41
+ // the viewport. Use a bounded nav measurement and a fixed floor; the card is
42
+ // always visibly below the top bar.
43
+ const measured = navigationBottom()
44
+ const nav = measured > 0 && measured < 240 ? measured : 56
45
+ host.style.top = String(Math.max(nav + 48, MIN_TOP)) + 'px'
46
+ }
47
+
48
+ function ensureHost(): HTMLDivElement | undefined {
49
+ if (typeof document === 'undefined') return undefined
50
+ const existing = document.getElementById(HOST_ID)
51
+ if (existing !== null) return existing as HTMLDivElement
52
+ const host = document.createElement('div')
53
+ host.id = HOST_ID
54
+ host.setAttribute('role', 'status')
55
+ host.setAttribute('aria-live', 'polite')
56
+ host.style.cssText = [
57
+ 'position:fixed',
58
+ 'top:56px',
59
+ 'right:12px',
60
+ 'z-index:10000',
61
+ 'display:flex',
62
+ 'flex-direction:column',
63
+ 'gap:8px',
64
+ 'max-width:min(380px,calc(100vw - 24px))',
65
+ 'pointer-events:none',
66
+ ].join(';')
67
+ placeBelowNavigation(host)
68
+ document.body.appendChild(host)
69
+ return host
70
+ }
71
+
72
+ function card(action: GlobalSessionEndAction, dismiss: () => void): HTMLDivElement {
73
+ const element = document.createElement('div')
74
+ element.style.cssText = [
75
+ 'pointer-events:auto',
76
+ 'display:flex',
77
+ 'align-items:flex-start',
78
+ 'gap:9px',
79
+ 'padding:10px 11px',
80
+ 'border-radius:12px',
81
+ 'border:1px solid var(--dsw-alias-state-warn-primary, rgba(227,179,65,.65))',
82
+ 'background:var(--dsw-alias-bg-layer-2, #1f2023)',
83
+ 'color:var(--dsw-alias-label-primary, #f2f3f5)',
84
+ 'box-shadow:var(--dsw-elevation-prominent, 0 8px 28px rgba(0,0,0,.35))',
85
+ 'font-size:12px',
86
+ 'line-height:1.45',
87
+ ].join(';')
88
+
89
+ const dot = document.createElement('span')
90
+ dot.setAttribute('aria-hidden', 'true')
91
+ dot.style.cssText = 'flex:none;width:8px;height:8px;margin-top:4px;border-radius:50%;background:var(--dsw-alias-state-warn-primary,#e3b341)'
92
+
93
+ const body = document.createElement('div')
94
+ body.style.cssText = 'flex:1;min-width:0'
95
+ const title = document.createElement('div')
96
+ title.textContent = globalNoticeText(action)
97
+ title.style.cssText = 'font-weight:600'
98
+ const hint = document.createElement('div')
99
+ hint.textContent = action.waiting
100
+ ? '正在等待任务结束' + (action.runningAgents + action.runningJobs > 0
101
+ ? ' · ' + String(action.runningAgents) + ' 个会话 / ' + String(action.runningJobs) + ' 个任务'
102
+ : '')
103
+ : '本轮最终回复后执行'
104
+ hint.style.cssText = 'margin-top:2px;color:var(--dsw-alias-label-secondary,#a8adb7);font-size:11px'
105
+ body.append(title, hint)
106
+
107
+ const close = document.createElement('button')
108
+ close.type = 'button'
109
+ close.setAttribute('aria-label', '关闭提示')
110
+ close.textContent = '×'
111
+ close.style.cssText = [
112
+ 'flex:none',
113
+ 'border:0',
114
+ 'background:transparent',
115
+ 'color:var(--dsw-alias-label-tertiary,#8b919c)',
116
+ 'cursor:pointer',
117
+ 'font-size:16px',
118
+ 'line-height:1',
119
+ 'padding:0 2px',
120
+ ].join(';')
121
+ close.addEventListener('click', dismiss)
122
+
123
+ element.append(dot, body, close)
124
+ return element
125
+ }
126
+
127
+ export function startSessionEndGlobalNotice(): () => void {
128
+ if (typeof document === 'undefined' || typeof fetch !== 'function') return () => {}
129
+ let stopped = false
130
+ let timer: ReturnType<typeof setInterval> | undefined
131
+ const dismissed = new Set<string>()
132
+
133
+ const clear = (): void => {
134
+ document.getElementById(HOST_ID)?.remove()
135
+ }
136
+
137
+ const render = (actions: GlobalSessionEndAction[]): void => {
138
+ const active = new Set(actions.map(globalNoticeKey))
139
+ for (const key of dismissed) if (!active.has(key)) dismissed.delete(key)
140
+ const visible = actions.filter(action => !dismissed.has(globalNoticeKey(action)))
141
+ if (visible.length === 0) {
142
+ clear()
143
+ return
144
+ }
145
+ const host = ensureHost()
146
+ if (host === undefined) return
147
+ placeBelowNavigation(host)
148
+ host.replaceChildren(...visible.map(action => card(action, () => {
149
+ dismissed.add(globalNoticeKey(action))
150
+ render(actions)
151
+ })))
152
+ }
153
+
154
+ const poll = async (): Promise<void> => {
155
+ try {
156
+ const response = await fetch(SESSION_END_API.global, {
157
+ method: 'POST',
158
+ credentials: 'same-origin',
159
+ cache: 'no-store',
160
+ })
161
+ if (stopped) return
162
+ const body = await response.json() as { ok?: boolean; actions?: GlobalSessionEndAction[] }
163
+ if (stopped || body.ok !== true || !Array.isArray(body.actions)) return
164
+ render(body.actions.filter(action => action.requestedBy === 'ai'))
165
+ } catch {
166
+ /* a transient poll failure leaves the last notice in place */
167
+ }
168
+ }
169
+
170
+ const onResize = (): void => {
171
+ const host = document.getElementById(HOST_ID) as HTMLDivElement | null
172
+ if (host !== null) placeBelowNavigation(host)
173
+ }
174
+ window.addEventListener('resize', onResize)
175
+ void poll()
176
+ timer = setInterval(() => { void poll() }, 2000)
177
+ return () => {
178
+ stopped = true
179
+ if (timer !== undefined) clearInterval(timer)
180
+ window.removeEventListener('resize', onResize)
181
+ clear()
182
+ }
183
+ }
@@ -120,6 +120,10 @@ export function SettingsSection({ t }: SettingsSectionProps) {
120
120
  <span style={pageStyles.componentName}>{t('page.components.restart')}</span>
121
121
  <span style={pageStyles.componentHint}>{t('page.components.restartHint')}</span>
122
122
  </div>
123
+ <div style={pageStyles.componentRow}>
124
+ <span style={pageStyles.componentName}>{t('page.components.authCookie')}</span>
125
+ <span style={pageStyles.componentHint}>{t('page.components.authCookieHint')}</span>
126
+ </div>
123
127
  <div style={pageStyles.componentRow}>
124
128
  <span style={pageStyles.componentName}>{t('page.components.sessionEnd')}</span>
125
129
  <span style={pageStyles.componentHint}>{t('page.components.sessionEndHint')}</span>
@@ -3,6 +3,7 @@ import type {} from '@deepseek-ai/dsh-client-locale/client'
3
3
  import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
4
4
  import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
5
5
  import type {} from '@deepseek-ai/dsh-client-ui-slots'
6
+ import { AUTH_COOKIE_API } from '../api.ts'
6
7
  import { AppearanceScheduleRow } from './AppearanceScheduleRow.tsx'
7
8
  import { FallbackRestartRow } from './FallbackRestartRow.tsx'
8
9
  import { SessionEndControl } from './SessionEndControl.tsx'
@@ -12,6 +13,7 @@ import { en, zh, type McviseronKey } from './locales.ts'
12
13
  import { sectionPresence } from './section-presence.ts'
13
14
 
14
15
  const NS = 'mcviseron'
16
+ let authCookiePruneStarted = false
15
17
 
16
18
  declare module '@deepseek-ai/dsh-client-ui-slots' {
17
19
  interface LocaleNamespaceMap {
@@ -77,6 +79,19 @@ function registerSafely(
77
79
  * @param ctx - client cordis context.
78
80
  */
79
81
  export function apply(ctx: ClientContext): void {
82
+ if (!authCookiePruneStarted) {
83
+ authCookiePruneStarted = true
84
+ try {
85
+ void fetch(AUTH_COOKIE_API.prune, {
86
+ method: 'POST',
87
+ credentials: 'same-origin',
88
+ cache: 'no-store',
89
+ }).catch(() => {})
90
+ } catch {
91
+ /* a shell without fetch still loads the rest of the plugin */
92
+ }
93
+ }
94
+
80
95
  try {
81
96
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'mcviseron: dictionaries')
82
97
  } catch (error) {
@@ -25,7 +25,7 @@ export const zh = {
25
25
  'restart.confirm': '确定要重启 DeepSeek Harness 吗?正在运行的任务会被中断。',
26
26
  'sessionEnd.label': '会话后重启',
27
27
  'sessionEnd.hint': '本轮最终回复完整显示后执行;AI 需要重启插件时可自动设置。',
28
- 'sessionEnd.off': '关闭',
28
+ 'sessionEnd.off': '不做操作',
29
29
  'sessionEnd.restart': '重启 DSH',
30
30
  'sessionEnd.close': '关闭 DSH',
31
31
  'sessionEnd.shutdown': '关闭电脑',
@@ -73,6 +73,11 @@ export const zh = {
73
73
  'form.failed': '保存失败',
74
74
  'form.unavailable': '无法读取插件设置:请确认 profile 中的插件条目 id 为 mcviseron',
75
75
  'form.autoSave': '修改后自动保存',
76
+ 'form.autoReview.reviewGuard': '裁剪 Auto review 上下文',
77
+ 'form.autoReview.reviewGuardHint': '只压缩 reviewer 的历史;当前动作、工程约束和人类指令保留,避免长会话把审查模型撑爆',
78
+ 'form.autoReview.reviewMaxHistory': '审查历史上限(字符)',
79
+ 'form.autoReview.reviewMaxHistoryHint': '默认 120000;超出后旧工具调用会折叠成摘要',
80
+ 'form.autoReview.reviewKeepRecent': '保留最近历史条数',
76
81
  'form.autoReview.translate': '翻译审批理由',
77
82
  'form.autoReview.translateHint': '英文审查理由会附上中文翻译,并写入审批事件;转手动后被拒时,自动审查理由会作为 notice 交回 AI',
78
83
  'form.autoReview.keepPreset': '退出时保持权限预设',
@@ -108,6 +113,8 @@ export const zh = {
108
113
  'page.tab.sessionEnd': '会话后动作',
109
114
  'page.sessionEnd.title': '会话后动作',
110
115
  'page.sessionEnd.description': '本轮最终回复完整显示后执行一次动作;重启会等待所有会话与后台任务结束,设置页的重启不受此约束。',
116
+ 'page.components.authCookie': '认证 cookie 清理',
117
+ 'page.components.authCookieHint': '自动运行,无设置',
111
118
  'page.components.sessionEnd': '会话后动作',
112
119
  'page.components.sessionEndHint': '输入框左侧的「会话后重启」下拉',
113
120
  'form.sessionEnd.enabled': '启用会话后动作',
@@ -149,7 +156,7 @@ export const en = {
149
156
  'restart.confirm': 'Restart DeepSeek Harness now? Running tasks will be interrupted.',
150
157
  'sessionEnd.label': 'Restart after session',
151
158
  'sessionEnd.hint': 'Runs after the final reply is fully displayed; the AI can arm it when a plugin change needs a restart.',
152
- 'sessionEnd.off': 'Off',
159
+ 'sessionEnd.off': 'No action',
153
160
  'sessionEnd.restart': 'Restart DSH',
154
161
  'sessionEnd.close': 'Close DSH',
155
162
  'sessionEnd.shutdown': 'Shut down PC',
@@ -197,6 +204,11 @@ export const en = {
197
204
  'form.failed': 'Save failed',
198
205
  'form.unavailable': 'Cannot read the plugin settings: check that the profile entry id is mcviseron',
199
206
  'form.autoSave': 'Changes save automatically',
207
+ 'form.autoReview.reviewGuard': 'Trim the Auto-review context',
208
+ 'form.autoReview.reviewGuardHint': 'Compacts only the reviewer history; the pending action, project constraints and human instructions stay',
209
+ 'form.autoReview.reviewMaxHistory': 'Reviewer history limit (chars)',
210
+ 'form.autoReview.reviewMaxHistoryHint': 'Defaults to 120000; older tool calls collapse into a summary',
211
+ 'form.autoReview.reviewKeepRecent': 'Recent entries to keep',
200
212
  'form.autoReview.translate': 'Translate the approval reason',
201
213
  'form.autoReview.translateHint': 'Appends a Chinese translation to the reviewer note and writes it into the approval event; a manual rejection returns the auto-review reason to the AI',
202
214
  'form.autoReview.keepPreset': 'Keep the permission preset on shutdown',
@@ -232,6 +244,8 @@ export const en = {
232
244
  'page.tab.sessionEnd': 'After-session action',
233
245
  'page.sessionEnd.title': 'After-session action',
234
246
  'page.sessionEnd.description': 'One action after the final reply is fully displayed. A restart waits for every running conversation and background job; the Settings restart button is not delayed.',
247
+ 'page.components.authCookie': 'Auth-cookie cleanup',
248
+ 'page.components.authCookieHint': 'Runs automatically; no settings',
235
249
  'page.components.sessionEnd': 'After-session action',
236
250
  'page.components.sessionEndHint': 'The “Restart after session” dropdown left of the composer',
237
251
  'form.sessionEnd.enabled': 'Enable after-session actions',
@@ -1,5 +1,5 @@
1
1
  declare module '@deepseek-ai/dsh-client-ui-primitives' {
2
- import type { ReactElement } from 'react'
2
+ import type { CSSProperties, ReactElement, ReactNode } from 'react'
3
3
 
4
4
  export interface SwitchProps {
5
5
  checked: boolean
@@ -12,4 +12,40 @@ declare module '@deepseek-ai/dsh-client-ui-primitives' {
12
12
 
13
13
  /** The official settings switch supplied by the DSH client shell. */
14
14
  export function Switch(props: SwitchProps): ReactElement | null
15
+
16
+ export interface IconProps {
17
+ className?: string
18
+ style?: CSSProperties
19
+ }
20
+
21
+ export function IconChevronDownOutlineRegular(props?: IconProps): ReactElement
22
+ export function IconClockOutlineRegular(props?: IconProps): ReactElement
23
+ export function IconCloseOutlineRegular(props?: IconProps): ReactElement
24
+ export function IconCloseCircleFillRegular(props?: IconProps): ReactElement
25
+ export function IconRefreshOutlineRegular(props?: IconProps): ReactElement
26
+ export function IconStopFillRegular(props?: IconProps): ReactElement
27
+
28
+ export interface MenuItem {
29
+ id: string
30
+ label: ReactNode
31
+ disabled?: boolean
32
+ icon?: ReactNode
33
+ danger?: boolean
34
+ }
35
+
36
+ export interface MenuProps {
37
+ open: boolean
38
+ anchor: ReactNode
39
+ items?: readonly MenuItem[]
40
+ selectedId?: string
41
+ onSelect?: (id: string) => void
42
+ onClose: () => void
43
+ align?: 'start' | 'end'
44
+ side?: 'bottom' | 'top' | 'right'
45
+ portal?: boolean
46
+ selection?: 'check' | 'fill'
47
+ }
48
+
49
+ /** The official anchored dropdown menu and its keyboard/portal behavior. */
50
+ export function Menu(props: MenuProps): ReactElement
15
51
  }
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import type { Context } from '@deepseek-ai/cordis'
3
+ import { installReviewContextGuard, type ReviewContextSettings } from './review-context.ts'
3
4
  import {
4
5
  chineseKey,
5
6
  cleanTranslation,
@@ -42,6 +43,7 @@ const FIBER_STATE_ACTIVE = 2
42
43
  /** Settings actually used at runtime. */
43
44
  export interface AutoReviewSettings extends TranslationSettings {
44
45
  keepPresetGuard: boolean
46
+ reviewContext: ReviewContextSettings
45
47
  }
46
48
 
47
49
  /** Service objects already guarded in this process (survives plugin reloads). */
@@ -87,6 +89,11 @@ export function normalizeConfig(config?: unknown): AutoReviewSettings {
87
89
  maxChars: numberSetting(source, 'translateMaxChars', 4000, 100, 20000),
88
90
  provider: stringSetting(source, 'translateProvider', ''),
89
91
  model: stringSetting(source, 'translateModel', ''),
92
+ reviewContext: {
93
+ enabled: boolSetting(source, 'reviewContextGuard', true),
94
+ maxHistoryChars: numberSetting(source, 'reviewMaxHistoryChars', 120000, 20000, 600000),
95
+ keepRecentEntries: numberSetting(source, 'reviewKeepRecentEntries', 16, 4, 64),
96
+ },
90
97
  }
91
98
  }
92
99
 
@@ -410,6 +417,7 @@ function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings,
410
417
  export function installAutoReview(ctx: Context, config?: unknown): void {
411
418
  const settings = normalizeConfig(config)
412
419
  if (settings.keepPresetGuard) installPresetGuard(ctx)
420
+ if (settings.reviewContext.enabled) installReviewContextGuard(ctx, settings.reviewContext)
413
421
  if (settings.enabled) {
414
422
  const relay = createRejectionRelay()
415
423
  installRejectionRelay(ctx, relay)
@@ -0,0 +1,285 @@
1
+ import { appendFileSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import type { Context } from '@deepseek-ai/cordis'
5
+
6
+ /**
7
+ * Auto review serializes the whole session surface into FILTERED_HISTORY and
8
+ * asks the reviewer model to judge one pending call. A long session can exceed
9
+ * the reviewer's context window before it even starts. This module projects
10
+ * only the reviewer request: current action, project instructions, and every
11
+ * human/direct-parent instruction stay; old tool calls and oversized payloads
12
+ * are compacted.
13
+ */
14
+
15
+ export interface ReviewContextSettings {
16
+ enabled: boolean
17
+ maxHistoryChars: number
18
+ keepRecentEntries: number
19
+ }
20
+
21
+ export interface ReviewOptions {
22
+ system?: unknown
23
+ messages?: unknown
24
+ [key: string]: unknown
25
+ }
26
+
27
+ interface ReviewMessage {
28
+ role?: unknown
29
+ content?: unknown
30
+ [key: string]: unknown
31
+ }
32
+
33
+ const REVIEW_MARKER = 'REVIEW_POLICY'
34
+ const REVIEW_MARKER_2 = 'final authorization reviewer'
35
+ const HISTORY_HEADER = 'FILTERED_HISTORY\n\n'
36
+ const PROJECT_HEADER = 'PROJECT_INSTRUCTIONS\n\n'
37
+ const ACTION_HEADER = '\n\nPENDING_ACTION\n\n'
38
+ const USER_TEXT_CHARS = 4_000
39
+ const TOOL_ARGUMENT_CHARS = 2_000
40
+ const PROJECT_MAX_CHARS = 40_000
41
+
42
+ function record(value: unknown): value is Record<string, unknown> {
43
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
44
+ }
45
+
46
+ function textOf(message: unknown): string | undefined {
47
+ if (!record(message) || !Array.isArray(message.content)) return undefined
48
+ const texts: string[] = []
49
+ for (const block of message.content) {
50
+ if (!record(block) || block.type !== 'text' || typeof block.text !== 'string') return undefined
51
+ texts.push(block.text)
52
+ }
53
+ return texts.join('')
54
+ }
55
+
56
+ /** Detect the exact one-message request shape Auto review sends to llm.stream. */
57
+ export function isAutoReviewRequest(options: unknown): options is ReviewOptions {
58
+ if (!record(options)) return false
59
+ const system = options.system
60
+ if (typeof system !== 'string' || !system.includes(REVIEW_MARKER) || !system.includes(REVIEW_MARKER_2)) return false
61
+ if (!Array.isArray(options.messages) || options.messages.length === 0) return false
62
+ const text = textOf(options.messages[0])
63
+ return text !== undefined && text.includes(HISTORY_HEADER) && text.includes(ACTION_HEADER)
64
+ }
65
+
66
+ function truncateText(text: string, limit: number): string {
67
+ if (text.length <= limit) return text
68
+ return text.slice(0, limit) + '\n…[' + String(text.length - limit) + ' characters omitted]'
69
+ }
70
+
71
+ function compactBlock(block: unknown): unknown {
72
+ if (!record(block)) return { type: 'text', text: '[non-text history block omitted from reviewer context]' }
73
+ if (block.type === 'text' && typeof block.text === 'string') {
74
+ return { ...block, text: truncateText(block.text, USER_TEXT_CHARS) }
75
+ }
76
+ return {
77
+ type: 'text',
78
+ text: '[' + String(block.type ?? 'attachment') + ' omitted from reviewer context]',
79
+ }
80
+ }
81
+
82
+ function compactEntry(entry: unknown): unknown {
83
+ if (!record(entry)) return { kind: 'summary', role: 'fact', content: [{ type: 'text', text: '[invalid history entry omitted]' }] }
84
+ if (entry.kind === 'user-message' && Array.isArray(entry.content)) {
85
+ return { ...entry, content: entry.content.map(compactBlock) }
86
+ }
87
+ if (entry.kind === 'tool-call') {
88
+ const value = entry.arguments
89
+ if (typeof value === 'string') {
90
+ return { ...entry, arguments: truncateText(value, TOOL_ARGUMENT_CHARS) }
91
+ }
92
+ if (value !== undefined) {
93
+ let rendered: string
94
+ try {
95
+ rendered = JSON.stringify(value) ?? ''
96
+ } catch {
97
+ rendered = ''
98
+ }
99
+ return { ...entry, arguments: truncateText(rendered, TOOL_ARGUMENT_CHARS) }
100
+ }
101
+ }
102
+ return entry
103
+ }
104
+
105
+ function protectedEntry(entry: unknown): boolean {
106
+ if (!record(entry)) return false
107
+ return entry.role === 'human-instruction' || entry.role === 'direct-parent-instruction'
108
+ }
109
+
110
+ function summaryEntry(omitted: number, originalChars: number): Record<string, unknown> {
111
+ return {
112
+ kind: 'summary',
113
+ role: 'fact',
114
+ content: [{
115
+ type: 'text',
116
+ text: '[auto-review-fix] ' + String(omitted)
117
+ + ' earlier history entries omitted from the reviewer context (original history '
118
+ + String(originalChars) + ' chars). Current action and human instructions are retained.',
119
+ }],
120
+ }
121
+ }
122
+
123
+ function jsonLength(value: unknown): number {
124
+ try {
125
+ return JSON.stringify(value)?.length ?? 0
126
+ } catch {
127
+ return Number.MAX_SAFE_INTEGER
128
+ }
129
+ }
130
+
131
+ /** Compact and bound one history array while preserving authorization entries. */
132
+ export function boundEntries(entries: unknown[], maxChars: number, keepRecent: number): unknown[] {
133
+ const normalized = entries.map(compactEntry)
134
+ const originalChars = jsonLength(normalized)
135
+ const recentStart = Math.max(0, normalized.length - Math.max(1, keepRecent))
136
+ const selected = normalized.filter((entry, index) => protectedEntry(entry) || index >= recentStart)
137
+ let omitted = normalized.length - selected.length
138
+ while (selected.length > 1 && jsonLength(selected) > maxChars) {
139
+ const at = selected.findIndex(entry => !protectedEntry(entry))
140
+ if (at < 0) selected.shift()
141
+ else selected.splice(at, 1)
142
+ omitted += 1
143
+ }
144
+ if (omitted > 0) selected.unshift(summaryEntry(omitted, originalChars))
145
+ return selected
146
+ }
147
+
148
+ function parseArray(text: string): unknown[] | undefined {
149
+ try {
150
+ const value = JSON.parse(text) as unknown
151
+ return Array.isArray(value) ? value : undefined
152
+ } catch {
153
+ return undefined
154
+ }
155
+ }
156
+
157
+ function logTrim(originalChars: number, nextChars: number, originalEntries: number, nextEntries: number): void {
158
+ try {
159
+ appendFileSync(
160
+ join(tmpdir(), 'dsh-mcviseron-auto-review.log'),
161
+ new Date().toISOString() + ' review context trimmed: ' + String(originalChars) + ' -> '
162
+ + String(nextChars) + ' chars, history ' + String(originalEntries) + ' -> ' + String(nextEntries) + '\n',
163
+ 'utf8',
164
+ )
165
+ } catch {
166
+ /* diagnostics must never break the reviewer request */
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Return a copy of a reviewer request with bounded FILTERED_HISTORY and compact
172
+ * project instructions. Non-review requests and malformed requests are returned
173
+ * byte-for-byte unchanged.
174
+ */
175
+ export function trimReviewRequest<T extends ReviewOptions>(options: T, settings: ReviewContextSettings): T {
176
+ if (!settings.enabled || !isAutoReviewRequest(options)) return options
177
+ const messages = options.messages as ReviewMessage[]
178
+ const message = messages[0]
179
+ const text = textOf(message)
180
+ if (text === undefined) return options
181
+
182
+ const projectAt = text.indexOf(PROJECT_HEADER)
183
+ const historyAt = text.indexOf(HISTORY_HEADER, projectAt + 1)
184
+ const actionAt = text.indexOf(ACTION_HEADER, historyAt + 1)
185
+ if (projectAt < 0 || historyAt < 0 || actionAt < 0) return options
186
+
187
+ const projectJson = text.slice(projectAt + PROJECT_HEADER.length, historyAt - 2)
188
+ const historyJson = text.slice(historyAt + HISTORY_HEADER.length, actionAt)
189
+ const project = parseArray(projectJson)
190
+ const history = parseArray(historyJson)
191
+ if (project === undefined || history === undefined) return options
192
+
193
+ const nextProject = boundEntries(project, PROJECT_MAX_CHARS, 4)
194
+ const nextHistory = boundEntries(history, settings.maxHistoryChars, settings.keepRecentEntries)
195
+ const nextText = text.slice(0, projectAt)
196
+ + PROJECT_HEADER + JSON.stringify(nextProject)
197
+ + HISTORY_HEADER + JSON.stringify(nextHistory)
198
+ + text.slice(actionAt)
199
+ if (nextText === text) return options
200
+
201
+ logTrim(text.length, nextText.length, history.length, nextHistory.length)
202
+ const content = [{ type: 'text', text: nextText }]
203
+ return {
204
+ ...options,
205
+ messages: [
206
+ { ...message, content },
207
+ ...messages.slice(1),
208
+ ],
209
+ }
210
+ }
211
+
212
+ const guardedLlms = new WeakMap<object, { settings: ReviewContextSettings }>()
213
+
214
+ function whenService(ctx: Context, name: string, run: (scope: Context) => void): void {
215
+ try {
216
+ const inject = (ctx as unknown as { inject?: (deps: string[], callback: (scope: Context) => void) => unknown }).inject
217
+ if (typeof inject === 'function') {
218
+ inject.call(ctx, [name], run)
219
+ return
220
+ }
221
+ const get = (ctx as unknown as { get?: (key: string) => unknown }).get
222
+ if (typeof get === 'function' && get.call(ctx, name) !== undefined) run(ctx)
223
+ } catch {
224
+ /* a host without the seam keeps the original llm.stream */
225
+ }
226
+ }
227
+
228
+ function serviceOf(scope: Context, name: string): unknown {
229
+ try {
230
+ const direct = (scope as unknown as Record<string, unknown>)[name]
231
+ if (direct !== undefined) return direct
232
+ } catch {
233
+ /* fall through */
234
+ }
235
+ try {
236
+ const get = (scope as unknown as { get?: (key: string) => unknown }).get
237
+ return typeof get === 'function' ? get.call(scope, name) : undefined
238
+ } catch {
239
+ return undefined
240
+ }
241
+ }
242
+
243
+ function effectOf(scope: Context, setup: () => () => void, label: string): void {
244
+ try {
245
+ const effect = (scope as unknown as { effect?: (body: () => () => void, label: string) => unknown }).effect
246
+ if (typeof effect === 'function') effect.call(scope, setup, label)
247
+ } catch {
248
+ /* a host without effect() still gets the wrapper */
249
+ }
250
+ }
251
+
252
+ /** Wrap llm.stream, but only rewrite requests that carry the Auto-review policy. */
253
+ export function installReviewContextGuard(ctx: Context, settings: ReviewContextSettings): void {
254
+ if (!settings.enabled) return
255
+ whenService(ctx, 'llm', (scope) => {
256
+ const llm = serviceOf(scope, 'llm') as { stream?: unknown } | undefined
257
+ if (llm === null || typeof llm !== 'object' || typeof llm.stream !== 'function') return
258
+ const existing = guardedLlms.get(llm)
259
+ if (existing !== undefined) {
260
+ existing.settings = settings
261
+ return
262
+ }
263
+ const original = llm.stream as (this: unknown, options: unknown) => unknown
264
+ const state = { settings }
265
+ const wrapper = function (this: unknown, options: unknown): unknown {
266
+ let next = options
267
+ try {
268
+ next = trimReviewRequest(options as ReviewOptions, state.settings)
269
+ } catch {
270
+ next = options
271
+ }
272
+ return original.call(this, next)
273
+ }
274
+ try {
275
+ llm.stream = wrapper
276
+ guardedLlms.set(llm, state)
277
+ } catch {
278
+ return
279
+ }
280
+ effectOf(scope, () => () => {
281
+ if (llm.stream === wrapper) llm.stream = original
282
+ guardedLlms.delete(llm)
283
+ }, 'mcviseron: restore llm.stream')
284
+ })
285
+ }
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { Context } from '@deepseek-ai/cordis'
2
2
  import z from '@deepseek-ai/schemastery'
3
3
  import * as appearance from './appearance/index.ts'
4
+ import * as authCookie from './auth-cookie/index.ts'
4
5
  import * as autoReviewFix from './auto-review-fix/index.ts'
5
6
  import { DEFAULT_AUTO_REVIEW_CONFIG } from './auto-review-fix/index.ts'
6
7
  import * as restart from './restart/index.ts'
@@ -65,6 +66,7 @@ function mount(ctx: Context, component: unknown, config: unknown): void {
65
66
  */
66
67
  export function apply(ctx: Context, rawConfig?: MasterConfig): void {
67
68
  const config = (toPlain(rawConfig) ?? {}) as MasterConfig
69
+ mount(ctx, authCookie, {})
68
70
  mount(ctx, appearance, {
69
71
  enabled: config.enabled ?? DEFAULT_SCHEDULE_CONFIG.enabled,
70
72
  lightStart: config.lightStart ?? DEFAULT_SCHEDULE_CONFIG.lightStart,