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.
@@ -31,6 +31,15 @@ export const DEFAULT_SESSION_END_CONFIG = {
31
31
  ].join('\n'),
32
32
  } as const
33
33
 
34
+ /** Model-facing policy: when the session-end action is appropriate. */
35
+ const SESSION_END_GUIDANCE = [
36
+ '[session-end action] set_session_end_action arms one one-shot action after this turn.',
37
+ 'Use it only when this turn changed DSH plugin host/client source, build output (lib/), cordis.patch.yml, profile loader entries, or a setting that is read only at startup, and the change has been built and verified.',
38
+ 'Do not arm it for ordinary project files, docs/README, tests-only changes, live-applied settings, EDA/MATLAB/STM32 project work, or todo-only changes. Do not arm it when nothing was built, installed, or loaded.',
39
+ 'Arm it during the turn, after verification and before the final answer. It runs after the final reply is fully displayed and waits for all running agent turns and background jobs.',
40
+ 'Use close only when the user explicitly asks to close DSH. Shutdown is user-only. If you are unsure whether a restart is required, ask the user instead of arming.',
41
+ ].join(' ')
42
+
34
43
  export const Config = z.object({
35
44
  enabled: z.boolean().default(DEFAULT_SESSION_END_CONFIG.enabled).volatile(),
36
45
  graceMs: z.number().min(0).max(15000).default(DEFAULT_SESSION_END_CONFIG.graceMs).volatile(),
@@ -81,9 +90,16 @@ export interface SessionEndDeps {
81
90
  log?: (message: string) => void
82
91
  }
83
92
 
93
+ export interface SessionEndGlobalAction extends SessionEndView {
94
+ sessionId: string
95
+ label: string
96
+ armedAt: number
97
+ }
98
+
84
99
  export interface SessionEndController {
85
100
  get(sessionId: string): SessionEndView
86
- set(sessionId: string, mode: SessionEndMode, requestedBy: 'user' | 'ai'): SessionEndView
101
+ list(): SessionEndGlobalAction[]
102
+ set(sessionId: string, mode: SessionEndMode, requestedBy: 'user' | 'ai', label?: string): SessionEndView
87
103
  onTurnStart(sessionId: string): void
88
104
  onTurnEnd(sessionId: string): void
89
105
  dispose(): void
@@ -92,6 +108,8 @@ export interface SessionEndController {
92
108
  interface Entry {
93
109
  mode: Exclude<SessionEndMode, 'off'>
94
110
  requestedBy: 'user' | 'ai'
111
+ label?: string
112
+ armedAt: number
95
113
  waiting: boolean
96
114
  runningAgents: number
97
115
  runningJobs: number
@@ -194,6 +212,7 @@ export function createSessionEndController(deps: SessionEndDeps = {}): SessionEn
194
212
  const log = deps.log ?? defaultLog
195
213
  const entries = new Map<string, Entry>()
196
214
  const timers = new Map<string, ReturnType<typeof setTimeout>>()
215
+ let dispatching = false
197
216
  const resolveTarget = deps.resolveTarget ?? (() => resolveRestartTarget(
198
217
  process.execPath,
199
218
  process.ppid,
@@ -249,7 +268,18 @@ export function createSessionEndController(deps: SessionEndDeps = {}): SessionEn
249
268
 
250
269
  const fire = (sessionId: string, entry: Entry): void => {
251
270
  cancel(sessionId)
252
- entries.delete(sessionId)
271
+ if (dispatching) {
272
+ entries.delete(sessionId)
273
+ return
274
+ }
275
+ // One process action wins. A second session must not schedule another
276
+ // restart/close task while the first is already leaving the process.
277
+ dispatching = true
278
+ for (const [id, timer] of timers) {
279
+ clearTimeout(timer)
280
+ timers.delete(id)
281
+ }
282
+ entries.clear()
253
283
  const mode = entry.mode
254
284
  try {
255
285
  if (mode === 'restart') {
@@ -300,7 +330,15 @@ export function createSessionEndController(deps: SessionEndDeps = {}): SessionEn
300
330
  get(sessionId) {
301
331
  return view(sessionId)
302
332
  },
303
- set(sessionId, mode, requestedBy) {
333
+ list() {
334
+ return [...entries.entries()].map(([sessionId, entry]) => ({
335
+ sessionId,
336
+ label: entry.label ?? '',
337
+ armedAt: entry.armedAt,
338
+ ...view(sessionId),
339
+ }))
340
+ },
341
+ set(sessionId, mode, requestedBy, label) {
304
342
  if (sessionId === '') throw new TypeError('sessionId must be non-empty')
305
343
  if (!enabled) throw new Error('session-end actions are disabled')
306
344
  if (!isSessionEndMode(mode)) throw new TypeError('unknown session-end mode: ' + String(mode))
@@ -315,6 +353,8 @@ export function createSessionEndController(deps: SessionEndDeps = {}): SessionEn
315
353
  entries.set(sessionId, {
316
354
  mode,
317
355
  requestedBy,
356
+ ...(label === undefined || label === '' ? {} : { label }),
357
+ armedAt: Date.now(),
318
358
  waiting: false,
319
359
  runningAgents: 0,
320
360
  runningJobs: 0,
@@ -322,12 +362,16 @@ export function createSessionEndController(deps: SessionEndDeps = {}): SessionEn
322
362
  return view(sessionId)
323
363
  },
324
364
  onTurnStart(sessionId) {
325
- // A new turn in the same session cancels a pending action. If the user
326
- // armed the action while idle, no timer exists yet, so the state survives
327
- // into the turn and fires at its end.
328
- if (!timers.has(sessionId)) return
365
+ // A new turn cancels only the pending timer; it keeps the armed entry so
366
+ // the action is rescheduled at this turn's end instead of being silently
367
+ // lost when the user follows up during the grace period.
368
+ const entry = entries.get(sessionId)
369
+ if (entry !== undefined) {
370
+ entry.waiting = false
371
+ entry.runningAgents = 0
372
+ entry.runningJobs = 0
373
+ }
329
374
  cancel(sessionId)
330
- entries.delete(sessionId)
331
375
  },
332
376
  onTurnEnd(sessionId) {
333
377
  const entry = entries.get(sessionId)
@@ -338,6 +382,7 @@ export function createSessionEndController(deps: SessionEndDeps = {}): SessionEn
338
382
  for (const timer of timers.values()) clearTimeout(timer)
339
383
  timers.clear()
340
384
  entries.clear()
385
+ dispatching = false
341
386
  },
342
387
  }
343
388
  }
@@ -371,6 +416,7 @@ function bodySessionId(body: unknown): string | undefined {
371
416
 
372
417
  /** Build the state and set routes for the composer control. */
373
418
  export function makeSessionEndRoutes(controller: SessionEndController): WebRoute[] {
419
+ const seen = new Set<string>()
374
420
  const state: WebRoute = {
375
421
  kind: 'exact',
376
422
  path: SESSION_END_API.state,
@@ -380,6 +426,10 @@ export function makeSessionEndRoutes(controller: SessionEndController): WebRoute
380
426
  if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: 'forbidden' })
381
427
  const sessionId = bodySessionId(await readJsonBody(req))
382
428
  if (sessionId === undefined) return json(res, 400, { ok: false, error: 'sessionId-required' })
429
+ if (!seen.has(sessionId)) {
430
+ seen.add(sessionId)
431
+ defaultLog('state request: session=' + sessionId)
432
+ }
383
433
  json(res, 200, { ok: true, ...controller.get(sessionId) })
384
434
  } catch (error) {
385
435
  json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })
@@ -406,7 +456,26 @@ export function makeSessionEndRoutes(controller: SessionEndController): WebRoute
406
456
  },
407
457
  }
408
458
 
409
- return [state, set]
459
+ const global: WebRoute = {
460
+ kind: 'exact',
461
+ path: SESSION_END_API.global,
462
+ handler: (req, res): void => {
463
+ if (req.method !== 'POST' && req.method !== 'GET') {
464
+ json(res, 405, { ok: false, error: 'method-not-allowed' })
465
+ return
466
+ }
467
+ if (!isLoopbackRequest(req)) {
468
+ json(res, 403, { ok: false, error: 'forbidden' })
469
+ return
470
+ }
471
+ json(res, 200, {
472
+ ok: true,
473
+ actions: controller.list().filter(action => action.requestedBy === 'ai' && action.mode !== 'off'),
474
+ })
475
+ },
476
+ }
477
+
478
+ return [state, set, global]
410
479
  }
411
480
 
412
481
  function serviceOf(ctx: Context, name: string): unknown {
@@ -424,6 +493,30 @@ function serviceOf(ctx: Context, name: string): unknown {
424
493
  }
425
494
  }
426
495
 
496
+ function installGuidance(ctx: Context): void {
497
+ const inject = (ctx as unknown as { inject?: (deps: string[], callback: (scope: Context) => void) => unknown }).inject
498
+ if (typeof inject !== 'function') return
499
+ try {
500
+ inject.call(ctx, ['systemPrompt'], (scope) => {
501
+ const systemPrompt = serviceOf(scope, 'systemPrompt') as {
502
+ section?: (section: { name: string; order: number; text: string }) => unknown
503
+ } | undefined
504
+ if (systemPrompt === undefined || typeof systemPrompt.section !== 'function') return
505
+ try {
506
+ systemPrompt.section({
507
+ name: 'plugin:mcviseron-session-end',
508
+ order: 230,
509
+ text: SESSION_END_GUIDANCE,
510
+ })
511
+ } catch (error) {
512
+ defaultLog('guidance registration failed: ' + (error instanceof Error ? error.message : String(error)))
513
+ }
514
+ })
515
+ } catch (error) {
516
+ defaultLog('guidance injection failed: ' + (error instanceof Error ? error.message : String(error)))
517
+ }
518
+ }
519
+
427
520
  const emailed = new Map<string, number>()
428
521
 
429
522
  function installAgentTool(ctx: Context, controller: SessionEndController, options: Required<SessionEndOptions>, log: (message: string) => void): void {
@@ -439,9 +532,10 @@ function installAgentTool(ctx: Context, controller: SessionEndController, option
439
532
  name: 'set_session_end_action',
440
533
  description: [
441
534
  'Set the action DSH performs after the current turn has fully finished.',
442
- 'Use restart only after changing DSH plugin code that requires a restart; use close to quit DSH.',
443
- 'The action is one-shot, starts off, and is visible to the user. A restart waits until all running agent turns and background jobs finish.',
444
- 'Shutdown is user-only and is not available through this tool. Do not arm an action for ordinary turns.',
535
+ 'WHEN TO USE: this turn changed DSH plugin host/client source, build output (lib/), cordis.patch.yml, profile loader entries, or a setting read only at startup, and the change is built and verified.',
536
+ 'WHEN NOT TO USE: ordinary project files, docs/README, tests-only changes, live-applied settings, EDA/MATLAB/STM32 work, todo-only changes, or when nothing was built/installed/loaded.',
537
+ 'Arm restart during the turn, after verification and before the final answer. It runs after the final reply is fully displayed and waits for all running agent turns and background jobs.',
538
+ 'Use close only when the user explicitly asks to close DSH. Shutdown is user-only. If unsure whether a restart is required, ask the user instead of arming.',
445
539
  ].join(' '),
446
540
  parameters: {
447
541
  action: {
@@ -459,11 +553,12 @@ function installAgentTool(ctx: Context, controller: SessionEndController, option
459
553
  schema: {
460
554
  type: 'object',
461
555
  additionalProperties: false,
556
+ required: ['ok', 'action', 'requestedBy', 'message'],
462
557
  properties: {
463
- ok: { type: 'boolean', required: true },
464
- action: { type: 'string', required: true, enum: ['off', 'restart', 'close'] },
465
- requestedBy: { type: 'string', required: true, enum: ['ai'] },
466
- message: { type: 'string', required: true },
558
+ ok: { type: 'boolean' },
559
+ action: { type: 'string', enum: ['off', 'restart', 'close'] },
560
+ requestedBy: { type: 'string', enum: ['ai'] },
561
+ message: { type: 'string' },
467
562
  },
468
563
  },
469
564
  render: (_args: unknown, value: { message?: unknown }) => [{
@@ -487,16 +582,29 @@ function installAgentTool(ctx: Context, controller: SessionEndController, option
487
582
  if (action === 'close' && !before.available.close) {
488
583
  throw new Error('close is unavailable in this host')
489
584
  }
490
- controller.set(sessionId, action, 'ai')
585
+ const session = exec.agent?.session as { header?: { title?: unknown; name?: unknown }; title?: unknown } | undefined
586
+ const title = session?.header?.title ?? session?.header?.name ?? session?.title
587
+ let label = typeof title === 'string' && title !== '' ? title : ''
588
+ if (label === '') {
589
+ try {
590
+ const titles = serviceOf(ctx, 'sessionTitle') as { get?: (value: unknown) => unknown } | undefined
591
+ const snapshot = titles?.get?.(session)
592
+ const folded = snapshot !== null && typeof snapshot === 'object'
593
+ ? (snapshot as { title?: unknown }).title
594
+ : undefined
595
+ if (typeof folded === 'string' && folded !== '') label = folded
596
+ } catch {
597
+ /* title is best-effort; the global notice falls back to the id */
598
+ }
599
+ }
600
+ controller.set(sessionId, action, 'ai', label)
491
601
  if (action !== 'off' && options.notifyEmailOnAi) {
492
602
  const key = sessionId + ':' + action
493
603
  const now = Date.now()
494
604
  const previous = emailed.get(key) ?? 0
495
605
  if (now - previous > 60_000) {
496
606
  emailed.set(key, now)
497
- const session = exec.agent?.session as { header?: { title?: unknown; name?: unknown }; title?: unknown } | undefined
498
- const title = session?.header?.title ?? session?.header?.name ?? session?.title
499
- const sessionName = typeof title === 'string' && title !== '' ? title : sessionId
607
+ const sessionName = label === '' ? sessionId : label
500
608
  void sendSessionEndEmail({
501
609
  settings: serviceOf(ctx, 'settings'),
502
610
  template: options,
@@ -590,13 +698,24 @@ export function apply(ctx: Context, config?: SessionEndConfig): void {
590
698
  }, 'mcviseron-session-end: routes')
591
699
 
592
700
  if (options.enabled) {
593
- ;(ctx as unknown as { on: (event: string, handler: (session: unknown, event: { type?: unknown }) => void) => unknown })
594
- .on('session/event', (session, event) => {
595
- const sessionId = sessionIdOf(session)
596
- if (sessionId === '') return
597
- if (event?.type === 'turn/start') controller.onTurnStart(sessionId)
598
- else if (event?.type === 'turn/end') controller.onTurnEnd(sessionId)
599
- })
701
+ const root = (ctx as unknown as { root?: unknown }).root
702
+ const eventBus = (root ?? ctx) as {
703
+ on?: (event: string, handler: (session: unknown, event: { type?: unknown }) => void) => unknown
704
+ }
705
+ if (typeof eventBus.on === 'function') {
706
+ ctx.effect(() => {
707
+ const dispose = eventBus.on?.('session/event', (session, event) => {
708
+ const sessionId = sessionIdOf(session)
709
+ if (sessionId === '') return
710
+ if (event?.type === 'turn/start') controller.onTurnStart(sessionId)
711
+ else if (event?.type === 'turn/end') controller.onTurnEnd(sessionId)
712
+ })
713
+ return () => {
714
+ if (typeof dispose === 'function') dispose()
715
+ }
716
+ }, 'mcviseron-session-end: session events')
717
+ }
718
+ installGuidance(ctx)
600
719
  installAgentTool(ctx, controller, options, log)
601
720
  }
602
721