dsh-mcviseron-plugin 0.6.1 → 0.6.3

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.
@@ -37,8 +37,10 @@ export interface TaskGuardConfig {
37
37
  maxListItems?: number
38
38
  /**
39
39
  * Watch the assistant's streamed text/reasoning for a step-intent phrase
40
- * ("Now I will …", "接下来我会 …") that matches a pending todo, and attach one
41
- * targeted advisory notice per step. Defaults to `true`; advisory only.
40
+ * ("Now I will …", "接下来我会 …") or a phase-completion statement
41
+ * ("All nets routed", "DRC passes", "原理图完成") and attach one targeted
42
+ * advisory notice with a ready todo_write payload per step. Defaults to
43
+ * `true`; advisory only.
42
44
  */
43
45
  detectStepIntent?: boolean
44
46
  /** Translate English todo titles in notices into Chinese for display. Defaults to `true`. */
@@ -215,7 +217,10 @@ const INTENT_MARKERS: RegExp[] = [
215
217
  /\b(?:now|next|then)\s*,?\s*i(?:'ll| will| am going to|'m going to)\b([^\n]{2,160})/gi,
216
218
  /\bi(?:'ll| will| am going to|'m going to)\s+(?:now\s+)?([^\n]{2,160})/gi,
217
219
  /\blet me\s+(?:now\s+)?([^\n]{2,160})/gi,
220
+ /\b(?:now|next|then)\s+(?!i(?:'ll| will| am|'m)\b)([a-z][^\n]{2,160})/gi,
221
+ /\b(?:next step|next,)\s*[:\-]?\s*([^\n]{2,160})/gi,
218
222
  /(?:接下来|下一步|现在|然后|下面)(?:我会|我将|我要|我来|就开始|开始|准备)([^\n。;;]{2,120})/g,
223
+ /(?:接下来|下一步|现在|然后|下面)(?:开始|进行|做|处理|继续|检查|运行|绘制|布局|布线|导出|放置|连接)([^\n。;;]{2,120})/g,
219
224
  ]
220
225
 
221
226
  /** One matched step intent. */
@@ -242,9 +247,31 @@ function intentPhrases(text: string): string[] {
242
247
  return found.map(item => item.phrase)
243
248
  }
244
249
 
250
+ /** Cross-language phase keywords used to match text to a todo. */
251
+ const PHASE_PATTERNS: ReadonlyArray<{ id: string; pattern: RegExp }> = [
252
+ { id: 'schematic', pattern: /schematic|原理图/ },
253
+ { id: 'library', pattern: /library|footprint|器件库|元件库|封装/ },
254
+ { id: 'board', pattern: /board\s*(?:outline|shape)|板框|边框|外形/ },
255
+ { id: 'placement', pattern: /placement|layout|布局|摆放/ },
256
+ { id: 'routing', pattern: /rout(?:e|ing|ed)|track|走线|布线|连线/ },
257
+ { id: 'drc', pattern: /\bdrc\b|\berc\b|design[_ ]audit|校验|检查/ },
258
+ { id: 'power', pattern: /power|电源|加粗/ },
259
+ { id: 'copper', pattern: /copper|pour|铺铜|覆铜/ },
260
+ { id: 'gerber', pattern: /gerber|export|导出|出图/ },
261
+ { id: 'usb', pattern: /usb|type-?c/ },
262
+ { id: 'mcu', pattern: /stm32|\bmcu\b|主控|单片机/ },
263
+ ]
264
+
265
+ function phasesOf(value: string): Set<string> {
266
+ const phases = new Set<string>()
267
+ for (const { id, pattern } of PHASE_PATTERNS) if (pattern.test(value)) phases.add(id)
268
+ return phases
269
+ }
270
+
245
271
  /**
246
272
  * Match the last "Now I will ..." / "接下来我会 ..." phrase against pending
247
- * todos. Advisory only: the caller decides whether to attach a notice.
273
+ * todos. Cross-language phase keywords ("PCB" vs "板框", "DRC" vs "校验")
274
+ * carry a match even when the literal tokens differ. Advisory only.
248
275
  *
249
276
  * @param text - streamed assistant text/reasoning for the current step.
250
277
  * @param todos - the current plan.
@@ -258,11 +285,15 @@ export function detectStepIntent(text: string, todos: TodoItem[]): StepIntentMat
258
285
  for (const phrase of phrases) {
259
286
  const phraseNormalized = normalizeText(phrase)
260
287
  const phraseTokens = new Set(tokensOf(phrase))
288
+ const phrasePhases = phasesOf(phrase)
261
289
  for (const todo of todos) {
262
290
  if (todo.status !== 'pending') continue
263
291
  const contentNormalized = normalizeText(todo.content)
292
+ const todoPhases = phasesOf(todo.content)
264
293
  let score = 0
265
- if (contentNormalized.length >= 4 && (phraseNormalized.includes(contentNormalized) || contentNormalized.includes(phraseNormalized))) {
294
+ if ([...phrasePhases].some(phase => todoPhases.has(phase))) {
295
+ score = 1
296
+ } else if (contentNormalized.length >= 4 && (phraseNormalized.includes(contentNormalized) || contentNormalized.includes(phraseNormalized))) {
266
297
  score = 1
267
298
  } else {
268
299
  const contentTokens = tokensOf(todo.content)
@@ -278,6 +309,86 @@ export function detectStepIntent(text: string, todos: TodoItem[]): StepIntentMat
278
309
  return best
279
310
  }
280
311
 
312
+ /** Completion wording that normally closes a phase (not partial progress). */
313
+ const COMPLETION_PATTERNS: readonly RegExp[] = [
314
+ /\ball\b[^.!?\n]{0,100}\b(?:routed|connected|placed|done|complete|completed)\b/i,
315
+ /\b(?:schematic|layout|placement|routing|board|design|work|check|drc|erc)\b[^.!?\n]{0,50}\b(?:complete|completed|done|finished|passed|passes|clean)\b/i,
316
+ /\b(?:drc|erc|check|validation)\b[^.!?\n]{0,40}\b(?:passes|passed|clean|0\s+(?:errors?|violations?))\b/i,
317
+ /(?:全部|所有)[^。!?\n]{0,50}(?:布通|连通|完成|通过)|(?:完成|已完成|搞定|通过|布通|连通|无(?:错误|违规)|0\s*(?:错误|违规))/,
318
+ ]
319
+
320
+ function isCompletionSentence(sentence: string): boolean {
321
+ return COMPLETION_PATTERNS.some(pattern => pattern.test(sentence))
322
+ }
323
+
324
+ /**
325
+ * Detect a completed phase from the assistant's own wording. With one active
326
+ * task, match that task; without one, match a pending task whose phase
327
+ * keywords occur in the sentence. Partial progress ("44/46 routed") does not
328
+ * match.
329
+ *
330
+ * @param text - streamed assistant text/reasoning for the current step.
331
+ * @param todos - the current plan.
332
+ * @returns the matched todo and the sentence that announced completion.
333
+ */
334
+ export function detectCompletion(text: string, todos: TodoItem[]): { todo: TodoItem; phrase: string; score: number } | undefined {
335
+ if (text.length === 0 || todos.length === 0) return undefined
336
+ const active = todos.filter(todo => todo.status === 'in_progress')
337
+ if (active.length > 1) return undefined
338
+ const pool = active.length === 1 ? active : todos.filter(todo => todo.status === 'pending')
339
+ if (pool.length === 0) return undefined
340
+ const sentences = text.split(/(?<=[.!?。!?])\s+|\n+/).map(sentence => sentence.trim()).filter(sentence => sentence.length > 0)
341
+ for (const sentence of sentences) {
342
+ if (!isCompletionSentence(sentence)) continue
343
+ const sentencePhases = phasesOf(sentence)
344
+ let best: TodoItem | undefined
345
+ let bestScore = 0
346
+ for (const todo of pool) {
347
+ const todoPhases = phasesOf(todo.content)
348
+ let score = 0
349
+ for (const phase of sentencePhases) if (todoPhases.has(phase)) score += 1
350
+ if (score > bestScore) {
351
+ best = todo
352
+ bestScore = score
353
+ }
354
+ }
355
+ if (best === undefined && active.length === 1 && sentencePhases.size === 0) {
356
+ best = active[0]
357
+ bestScore = 0.5
358
+ }
359
+ if (best !== undefined) return { todo: best, phrase: sentence.slice(0, 120), score: bestScore }
360
+ }
361
+ return undefined
362
+ }
363
+
364
+ /**
365
+ * Build a complete todo_write payload for a finished task: mark it completed,
366
+ * mark the next pending task in_progress, and keep every other status.
367
+ *
368
+ * @param todos - the current plan.
369
+ * @param matched - the task the completion sentence refers to.
370
+ * @returns the JSON payload, or undefined when more than one task is active.
371
+ */
372
+ export function completionPayload(todos: TodoItem[], matched: TodoItem): string | undefined {
373
+ const active = todos.filter(todo => todo.status === 'in_progress')
374
+ if (active.length > 1) return undefined
375
+ const index = todos.findIndex(todo => todo.content === matched.content)
376
+ if (index < 0) return undefined
377
+ const next = todos.find((todo, at) => at > index && todo.status === 'pending')
378
+ ?? todos.find((todo, at) => at !== index && todo.status === 'pending')
379
+ const updated = todos.map((todo, at) => ({
380
+ content: todo.content,
381
+ status: at === index
382
+ ? 'completed' as const
383
+ : next !== undefined && todo.content === next.content
384
+ ? 'in_progress' as const
385
+ : todo.status === 'in_progress' && at !== index
386
+ ? 'completed' as const
387
+ : todo.status,
388
+ }))
389
+ return JSON.stringify({ todos: updated })
390
+ }
391
+
281
392
  /** Display translation settings for one notice. */
282
393
  interface NoticeContext {
283
394
  readonly llm?: { stream?: (options: unknown) => unknown }
@@ -511,7 +622,20 @@ export function installTaskGuard(ctx: Context, input?: TaskGuardConfig): void {
511
622
  // A "Now I will ..." / "接下来我会 ..." phrase that matches a pending todo is
512
623
  // the strongest signal that the plan drifted; one advisory notice per step.
513
624
  if (config.detectStepIntent && !state.intentNotifiedThisStep) {
514
- const match = detectStepIntent(intentBuffers.get(sessionId) ?? '', state.todos)
625
+ const buffer = intentBuffers.get(sessionId) ?? ''
626
+ const completed = detectCompletion(buffer, state.todos)
627
+ if (completed !== undefined) {
628
+ state.intentNotifiedThisStep = true
629
+ const notice = await buildCompletionNotice(
630
+ state,
631
+ completed,
632
+ config,
633
+ sourceKindFor(exec.agent, config),
634
+ noticeContext(exec.agent, config, ctx),
635
+ )
636
+ return attachContext(downstream, notice)
637
+ }
638
+ const match = detectStepIntent(buffer, state.todos)
515
639
  if (match !== undefined) {
516
640
  state.intentNotifiedThisStep = true
517
641
  const notice = await buildIntentNotice(
@@ -811,21 +935,34 @@ async function buildReminder(
811
935
  const omitted = remaining.length - config.maxListItems
812
936
  const items = omitted > 0 ? quoted + '\n… +' + omitted : quoted
813
937
 
938
+ const activeOne = active.length === 1 ? active[0] : undefined
939
+ const suggested = activeOne === undefined ? undefined : completionPayload(todos, activeOne)
940
+
814
941
  const text = config.locale === 'en'
815
942
  ? [
816
943
  '[Todo sync] ' + state.callsSinceWrite + ' tool calls have run since the last todo_write.',
817
944
  'In progress: ' + activeText,
818
945
  'Remaining:\n' + items,
819
- 'If the current phase is not finished yet, ignore this reminder. The moment it is finished, call todo_write: mark it completed and the next task in_progress (never leave pending work with no active task).',
946
+ activeOne === undefined
947
+ ? 'If the current phase is finished, call todo_write: mark completed work completed and the next task in_progress (never leave pending work with no active task).'
948
+ : suggested === undefined
949
+ ? 'If the current phase is finished, call todo_write: mark it completed and the next task in_progress (never leave pending work with no active task).'
950
+ : 'If the current phase is finished, send this todo_write now; if it is still running, keep that task in_progress and leave the list unchanged:',
951
+ suggested ?? '',
820
952
  '(Tip: todo titles can be written in Chinese.)',
821
- ].join('\n')
953
+ ].filter(line => line !== '').join('\n')
822
954
  : [
823
955
  '【todo 同步】距上次 todo_write 已过 ' + state.callsSinceWrite + ' 次工具调用。',
824
956
  '进行中:' + activeText,
825
957
  '剩余:\n' + items,
826
- '如果当前阶段还没完成,请忽略本提醒;一旦完成,请立刻调用 todo_write:把该阶段标为 completed,并把下一阶段标为 in_progress(有剩余任务时不要留空)。',
958
+ activeOne === undefined
959
+ ? '如果当前阶段已经完成,请调用 todo_write:把已完成阶段标为 completed,并把下一阶段标为 in_progress(有剩余任务时不要留空)。'
960
+ : suggested === undefined
961
+ ? '如果当前阶段已经完成,请调用 todo_write:把该阶段标为 completed,并把下一阶段标为 in_progress(有剩余任务时不要留空)。'
962
+ : '如果当前阶段已经完成,请直接发送以下 todo_write;如果仍在进行,请保持该待办为 in_progress,无需改动清单:',
963
+ suggested ?? '',
827
964
  '(提示:todo 内容可以直接用中文书写。)',
828
- ].join('\n')
965
+ ].filter(line => line !== '').join('\n')
829
966
 
830
967
  const summary = config.locale === 'en'
831
968
  ? 'todo stale · ' + state.callsSinceWrite + ' calls'
@@ -834,6 +971,44 @@ async function buildReminder(
834
971
  return createNotice(text, summary, sourceKind)
835
972
  }
836
973
 
974
+ async function buildCompletionNotice(
975
+ state: SessionState,
976
+ match: { todo: TodoItem; phrase: string },
977
+ config: ResolvedConfig,
978
+ sourceKind: 'v3' | 'v4',
979
+ context: NoticeContext,
980
+ ): Promise<NoticeMessage> {
981
+ const todos = state.todos ?? []
982
+ const [display] = await displayTodoContents([match.todo.content], context)
983
+ const suggested = completionPayload(todos, match.todo)
984
+ const phrase = truncate(match.phrase, 80)
985
+ const text = config.locale === 'en'
986
+ ? [
987
+ '[Todo sync] The assistant text looks like a completed phase: "' + display + '".',
988
+ 'Source: ' + phrase,
989
+ suggested === undefined
990
+ ? 'If that phase is finished, call todo_write: mark it completed and the next task in_progress.'
991
+ : 'If that phase is finished, send this todo_write now:',
992
+ suggested ?? '',
993
+ 'If it is still running, keep that task in_progress; do not mark it completed yet.',
994
+ '(Tip: todo titles can be written in Chinese.)',
995
+ ].filter(line => line !== '').join('\n')
996
+ : [
997
+ '【todo 同步】检测到阶段完成:「' + display + '」',
998
+ '依据:' + phrase,
999
+ suggested === undefined
1000
+ ? '如果该阶段已完成,请调用 todo_write:把该待办标为 completed,并把下一阶段标为 in_progress。'
1001
+ : '如果该阶段确实已完成,请直接发送以下 todo_write:',
1002
+ suggested ?? '',
1003
+ '如果仍在进行,请保持该待办为 in_progress,不要提前标 completed。',
1004
+ '(提示:todo 内容可以直接用中文书写。)',
1005
+ ].filter(line => line !== '').join('\n')
1006
+ const summary = config.locale === 'en'
1007
+ ? 'todo complete · ' + truncate(display, 40)
1008
+ : 'todo 完成 · ' + truncate(display, 40)
1009
+ return createNotice(text, summary, sourceKind)
1010
+ }
1011
+
837
1012
  async function buildIntentNotice(
838
1013
  state: SessionState,
839
1014
  match: StepIntentMatch,
package/src/index.ts CHANGED
@@ -4,6 +4,8 @@ import * as appearance from './appearance/index.ts'
4
4
  import * as autoReviewFix from './auto-review-fix/index.ts'
5
5
  import { DEFAULT_AUTO_REVIEW_CONFIG } from './auto-review-fix/index.ts'
6
6
  import * as restart from './restart/index.ts'
7
+ import * as sessionEnd from './session-end/index.ts'
8
+ import { DEFAULT_SESSION_END_CONFIG } from './session-end/index.ts'
7
9
  import { DEFAULT_RESTART_CONFIG } from './restart/index.ts'
8
10
  import * as taskGuard from './task-guard/index.ts'
9
11
  import { DEFAULT_TASK_GUARD_CONFIG } from './task-guard/index.ts'
@@ -24,6 +26,7 @@ export const Config = z.object({
24
26
  autoReviewFix: autoReviewFix.Config,
25
27
  taskGuard: taskGuard.Config,
26
28
  restart: restart.Config,
29
+ sessionEnd: sessionEnd.Config,
27
30
  }).default({
28
31
  enabled: DEFAULT_SCHEDULE_CONFIG.enabled,
29
32
  lightStart: DEFAULT_SCHEDULE_CONFIG.lightStart,
@@ -31,6 +34,7 @@ export const Config = z.object({
31
34
  autoReviewFix: DEFAULT_AUTO_REVIEW_CONFIG,
32
35
  taskGuard: DEFAULT_TASK_GUARD_CONFIG,
33
36
  restart: DEFAULT_RESTART_CONFIG,
37
+ sessionEnd: DEFAULT_SESSION_END_CONFIG,
34
38
  })
35
39
 
36
40
  export interface MasterConfig {
@@ -40,6 +44,7 @@ export interface MasterConfig {
40
44
  autoReviewFix?: unknown
41
45
  taskGuard?: unknown
42
46
  restart?: unknown
47
+ sessionEnd?: unknown
43
48
  }
44
49
 
45
50
  /** Mount one component without letting a missing service fail the master entry. */
@@ -67,5 +72,11 @@ export function apply(ctx: Context, rawConfig?: MasterConfig): void {
67
72
  })
68
73
  mount(ctx, autoReviewFix, toPlain(config.autoReviewFix) ?? DEFAULT_AUTO_REVIEW_CONFIG)
69
74
  mount(ctx, taskGuard, toPlain(config.taskGuard) ?? DEFAULT_TASK_GUARD_CONFIG)
70
- mount(ctx, restart, toPlain(config.restart) ?? DEFAULT_RESTART_CONFIG)
75
+ const restartConfig = (toPlain(config.restart) ?? DEFAULT_RESTART_CONFIG) as { appPath?: unknown }
76
+ mount(ctx, restart, restartConfig)
77
+ const sessionEndConfig = (toPlain(config.sessionEnd) ?? DEFAULT_SESSION_END_CONFIG) as Record<string, unknown>
78
+ mount(ctx, sessionEnd, {
79
+ ...sessionEndConfig,
80
+ appPath: typeof restartConfig.appPath === 'string' ? restartConfig.appPath : '',
81
+ })
71
82
  }
@@ -135,6 +135,35 @@ export function makeTaskScript(target: RestartTarget, taskName: string, delaySec
135
135
  ].join('\n')
136
136
  }
137
137
 
138
+ /**
139
+ * Schedule the desktop app to start again, then close its Electron main process.
140
+ * Exported for the session-end action; the settings route keeps its own throttle.
141
+ * @param target - resolved desktop executable and PIDs.
142
+ */
143
+ export function launchRestart(target: RestartTarget): void {
144
+ launchHelper(target)
145
+ }
146
+
147
+ /**
148
+ * Close the desktop app without relaunching it.
149
+ * @param target - resolved desktop target, when available.
150
+ */
151
+ export function closeDesktop(target?: RestartTarget): void {
152
+ const pid = target?.mainPid ?? process.ppid
153
+ setTimeout(() => {
154
+ try {
155
+ if (target !== undefined || process.platform === 'win32') process.kill(pid)
156
+ else process.exit(0)
157
+ } catch {
158
+ try {
159
+ process.exit(0)
160
+ } catch {
161
+ /* the host is already gone */
162
+ }
163
+ }
164
+ }, 300)
165
+ }
166
+
138
167
  /** Register the direct-launch task, then close the Electron main process. */
139
168
  function launchHelper(target: RestartTarget): void {
140
169
  const logFile = restartLogPath()
package/src/routes.ts CHANGED
@@ -63,6 +63,11 @@ const FIELD_RULES: Record<string, FieldRule> = {
63
63
  'taskGuard.exclude': { type: 'strings' },
64
64
  'restart.enabled': { type: 'boolean' },
65
65
  'restart.appPath': { type: 'string' },
66
+ 'sessionEnd.enabled': { type: 'boolean' },
67
+ 'sessionEnd.graceMs': { type: 'number', min: 0, max: 15000 },
68
+ 'sessionEnd.notifyEmailOnAi': { type: 'boolean' },
69
+ 'sessionEnd.emailSubject': { type: 'string' },
70
+ 'sessionEnd.emailBody': { type: 'string' },
66
71
  }
67
72
 
68
73
  function ruleFor(path: unknown): FieldRule | undefined {
@@ -146,6 +151,7 @@ function toPluginView(descriptor: SettingsBridgeView): Record<string, unknown> {
146
151
  autoReviewFix: isRecord(record.autoReviewFix) ? record.autoReviewFix : {},
147
152
  taskGuard: isRecord(record.taskGuard) ? record.taskGuard : {},
148
153
  restart: isRecord(record.restart) ? record.restart : {},
154
+ sessionEnd: isRecord(record.sessionEnd) ? record.sessionEnd : {},
149
155
  },
150
156
  revision: descriptor.revision,
151
157
  }
@@ -0,0 +1,163 @@
1
+ import nodemailer from 'nodemailer'
2
+ import { toPlain } from '../volatile.ts'
3
+ import {
4
+ DEFAULT_SESSION_END_CONFIG,
5
+ type SessionEndOptions,
6
+ } from './index.ts'
7
+
8
+ /**
9
+ * Optional integration with dsh-email-notify.
10
+ *
11
+ * The email plugin does not expose a notification service, so this module
12
+ * reads its public settings namespace (the same SMTP account the user already
13
+ * configured) and sends one custom message through nodemailer. It never
14
+ * modifies the email plugin and sends nothing when the plugin is absent,
15
+ * disabled, or missing any sendable SMTP field.
16
+ */
17
+
18
+ export interface EmailNotifyConfig {
19
+ smtpHost: string
20
+ smtpPort: number
21
+ smtpSecure: boolean
22
+ smtpUser: string
23
+ smtpPassword: string
24
+ mailFrom: string
25
+ mailTo: string
26
+ }
27
+
28
+ export interface SessionEndEmailInput {
29
+ settings: unknown
30
+ template: SessionEndOptions
31
+ sessionId: string
32
+ sessionName: string
33
+ action: 'restart' | 'close'
34
+ reason: string
35
+ now?: () => Date
36
+ sendMail?: (email: EmailNotifyConfig, message: { subject: string; text: string }) => Promise<void>
37
+ }
38
+
39
+ export interface SessionEndEmailResult {
40
+ sent: boolean
41
+ reason?: string
42
+ }
43
+
44
+ interface SettingsFace {
45
+ describe?: (options?: { redactSecrets?: boolean }) => unknown
46
+ }
47
+
48
+ function text(value: unknown): string {
49
+ return typeof value === 'string' ? value.trim() : ''
50
+ }
51
+
52
+ function readNumber(value: unknown, fallback: number): number {
53
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 65535
54
+ ? Math.trunc(value)
55
+ : fallback
56
+ }
57
+
58
+ /** Extract the live email-notify config from one settings describe view. */
59
+ export function emailNotifyConfigFromView(view: unknown): EmailNotifyConfig | undefined {
60
+ if (view === null || typeof view !== 'object' || Array.isArray(view)) return undefined
61
+ const value = toPlain((view as { value?: unknown }).value)
62
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
63
+ const source = value as Record<string, unknown>
64
+ if (source.enabled === false) return undefined
65
+ const smtpHost = text(source.smtpHost)
66
+ const smtpUser = text(source.smtpUser)
67
+ const smtpPassword = text(source.smtpPassword)
68
+ const mailTo = text(source.mailTo)
69
+ const mailFrom = text(source.mailFrom) || smtpUser
70
+ if (smtpHost === '' || smtpUser === '' || smtpPassword === '' || mailTo === '' || mailFrom === '') return undefined
71
+ return {
72
+ smtpHost,
73
+ smtpPort: readNumber(source.smtpPort, 465),
74
+ smtpSecure: source.smtpSecure !== false,
75
+ smtpUser,
76
+ smtpPassword,
77
+ mailFrom,
78
+ mailTo,
79
+ }
80
+ }
81
+
82
+ /** Read the dsh-email-notify namespace from the live settings service. */
83
+ export function resolveEmailNotifyConfig(settings: unknown): EmailNotifyConfig | undefined {
84
+ const describe = (settings as SettingsFace | undefined)?.describe
85
+ if (typeof describe !== 'function') return undefined
86
+ try {
87
+ const views = describe.call(settings, { redactSecrets: false })
88
+ if (!Array.isArray(views)) return undefined
89
+ const view = views.find(item => String((item as { ns?: unknown })?.ns ?? '') === 'email-notify')
90
+ return emailNotifyConfigFromView(view)
91
+ } catch {
92
+ return undefined
93
+ }
94
+ }
95
+
96
+ function actionText(action: 'restart' | 'close'): string {
97
+ return action === 'restart' ? '重启 DeepSeek Harness' : '关闭 DeepSeek Harness'
98
+ }
99
+
100
+ /** Render the custom subject/body with the same simple placeholder model. */
101
+ export function renderSessionEndEmail(
102
+ template: SessionEndOptions,
103
+ input: {
104
+ sessionId: string
105
+ sessionName: string
106
+ action: 'restart' | 'close'
107
+ reason: string
108
+ now: Date
109
+ },
110
+ ): { subject: string; text: string } {
111
+ const vars: Record<string, string> = {
112
+ action: input.action,
113
+ actionText: actionText(input.action),
114
+ sessionId: input.sessionId,
115
+ sessionName: input.sessionName === '' ? input.sessionId : input.sessionName,
116
+ time: input.now.toLocaleString('zh-CN', { hour12: false }),
117
+ reason: input.reason === '' ? '(未提供)' : input.reason,
118
+ }
119
+ const render = (source: string): string => source.replace(/\{\{([a-zA-Z]+)\}\}/g, (_match, key: string) => vars[key] ?? '')
120
+ return {
121
+ subject: render(template.emailSubject ?? DEFAULT_SESSION_END_CONFIG.emailSubject),
122
+ text: render(template.emailBody ?? DEFAULT_SESSION_END_CONFIG.emailBody),
123
+ }
124
+ }
125
+
126
+ async function defaultSendMail(email: EmailNotifyConfig, message: { subject: string; text: string }): Promise<void> {
127
+ const transport = nodemailer.createTransport({
128
+ host: email.smtpHost,
129
+ port: email.smtpPort,
130
+ secure: email.smtpSecure,
131
+ auth: { user: email.smtpUser, pass: email.smtpPassword },
132
+ })
133
+ await transport.sendMail({
134
+ from: email.mailFrom,
135
+ to: email.mailTo,
136
+ subject: message.subject,
137
+ text: message.text,
138
+ })
139
+ }
140
+
141
+ /**
142
+ * Send the AI-armed session-end reminder when email-notify is configured.
143
+ * Never throws: email is an optional side channel and must not block the tool.
144
+ */
145
+ export async function sendSessionEndEmail(input: SessionEndEmailInput): Promise<SessionEndEmailResult> {
146
+ if (input.template.notifyEmailOnAi === false) return { sent: false, reason: 'disabled' }
147
+ const email = resolveEmailNotifyConfig(input.settings)
148
+ if (email === undefined) return { sent: false, reason: 'email-notify-unavailable' }
149
+ const now = input.now?.() ?? new Date()
150
+ const rendered = renderSessionEndEmail(input.template, {
151
+ sessionId: input.sessionId,
152
+ sessionName: input.sessionName,
153
+ action: input.action,
154
+ reason: input.reason,
155
+ now,
156
+ })
157
+ try {
158
+ await (input.sendMail ?? defaultSendMail)(email, rendered)
159
+ return { sent: true }
160
+ } catch (error) {
161
+ return { sent: false, reason: error instanceof Error ? error.message : String(error) }
162
+ }
163
+ }