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.
- package/CHANGELOG.md +22 -0
- package/README.en.md +33 -8
- package/README.md +47 -13
- package/docs/automation-task.md +1 -1
- package/docs/release.md +8 -6
- package/docs/session-end.md +97 -0
- package/lib/appearance.js +8 -2
- package/lib/auto-review-fix.js +124 -7
- package/lib/client.js +470 -65
- package/lib/index.js +12170 -100
- package/lib/restart.js +19 -0
- package/lib/task-guard.js +122 -7
- package/package.json +15 -13
- package/src/api.ts +6 -0
- package/src/client/ConfigForm.tsx +31 -1
- package/src/client/SessionEndControl.tsx +332 -0
- package/src/client/SettingsSection.tsx +25 -3
- package/src/client/index.ts +15 -0
- package/src/client/locales.ts +60 -4
- package/src/components/auto-review-fix/index.ts +150 -6
- package/src/components/auto-review-fix/translate.ts +15 -2
- package/src/components/task-guard/index.ts +184 -9
- package/src/index.ts +12 -1
- package/src/restart/index.ts +29 -0
- package/src/routes.ts +6 -0
- package/src/session-end/email.ts +163 -0
- package/src/session-end/index.ts +608 -0
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process'
|
|
2
|
+
import { appendFileSync, existsSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
6
|
+
import type { ServerResponse } from 'node:http'
|
|
7
|
+
import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
|
|
8
|
+
import z from '@deepseek-ai/schemastery'
|
|
9
|
+
import { SESSION_END_API } from '../api.ts'
|
|
10
|
+
import { isLoopbackRequest } from '../loopback.ts'
|
|
11
|
+
import { sendSessionEndEmail } from './email.ts'
|
|
12
|
+
import {
|
|
13
|
+
closeDesktop,
|
|
14
|
+
launchRestart,
|
|
15
|
+
resolveRestartTarget,
|
|
16
|
+
type RestartTarget,
|
|
17
|
+
} from '../restart/index.ts'
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_SESSION_END_CONFIG = {
|
|
20
|
+
enabled: true,
|
|
21
|
+
graceMs: 3000,
|
|
22
|
+
notifyEmailOnAi: true,
|
|
23
|
+
emailSubject: '[DSH 会话后动作] {{actionText}}',
|
|
24
|
+
emailBody: [
|
|
25
|
+
'AI 已请求在本轮会话结束后{{actionText}}。',
|
|
26
|
+
'',
|
|
27
|
+
'会话:{{sessionName}}',
|
|
28
|
+
'会话 ID:{{sessionId}}',
|
|
29
|
+
'时间:{{time}}',
|
|
30
|
+
'理由:{{reason}}',
|
|
31
|
+
].join('\n'),
|
|
32
|
+
} as const
|
|
33
|
+
|
|
34
|
+
export const Config = z.object({
|
|
35
|
+
enabled: z.boolean().default(DEFAULT_SESSION_END_CONFIG.enabled).volatile(),
|
|
36
|
+
graceMs: z.number().min(0).max(15000).default(DEFAULT_SESSION_END_CONFIG.graceMs).volatile(),
|
|
37
|
+
notifyEmailOnAi: z.boolean().default(DEFAULT_SESSION_END_CONFIG.notifyEmailOnAi).volatile(),
|
|
38
|
+
emailSubject: z.string().default(DEFAULT_SESSION_END_CONFIG.emailSubject).volatile(),
|
|
39
|
+
emailBody: z.string().default(DEFAULT_SESSION_END_CONFIG.emailBody).volatile(),
|
|
40
|
+
}).default(DEFAULT_SESSION_END_CONFIG)
|
|
41
|
+
|
|
42
|
+
export interface SessionEndOptions {
|
|
43
|
+
enabled?: boolean
|
|
44
|
+
graceMs?: number
|
|
45
|
+
notifyEmailOnAi?: boolean
|
|
46
|
+
emailSubject?: string
|
|
47
|
+
emailBody?: string
|
|
48
|
+
appPath?: string
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type SessionEndMode = 'off' | 'restart' | 'close' | 'shutdown'
|
|
52
|
+
export type SessionEndRequestedBy = 'none' | 'user' | 'ai'
|
|
53
|
+
|
|
54
|
+
export interface SessionEndView {
|
|
55
|
+
enabled: boolean
|
|
56
|
+
mode: SessionEndMode
|
|
57
|
+
requestedBy: SessionEndRequestedBy
|
|
58
|
+
waiting: boolean
|
|
59
|
+
runningAgents: number
|
|
60
|
+
runningJobs: number
|
|
61
|
+
available: { restart: boolean; close: boolean; shutdown: boolean }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface RunningTasks {
|
|
65
|
+
running: boolean
|
|
66
|
+
agents: number
|
|
67
|
+
jobs: number
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface SessionEndDeps {
|
|
71
|
+
enabled?: boolean
|
|
72
|
+
appPath?: string
|
|
73
|
+
platform?: NodeJS.Platform
|
|
74
|
+
graceMs?: number
|
|
75
|
+
pollMs?: number
|
|
76
|
+
resolveTarget?: () => RestartTarget | undefined
|
|
77
|
+
restart?: (target: RestartTarget) => void
|
|
78
|
+
close?: (target?: RestartTarget) => void
|
|
79
|
+
shutdown?: () => void
|
|
80
|
+
hasRunningTasks?: () => RunningTasks
|
|
81
|
+
log?: (message: string) => void
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface SessionEndController {
|
|
85
|
+
get(sessionId: string): SessionEndView
|
|
86
|
+
set(sessionId: string, mode: SessionEndMode, requestedBy: 'user' | 'ai'): SessionEndView
|
|
87
|
+
onTurnStart(sessionId: string): void
|
|
88
|
+
onTurnEnd(sessionId: string): void
|
|
89
|
+
dispose(): void
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
interface Entry {
|
|
93
|
+
mode: Exclude<SessionEndMode, 'off'>
|
|
94
|
+
requestedBy: 'user' | 'ai'
|
|
95
|
+
waiting: boolean
|
|
96
|
+
runningAgents: number
|
|
97
|
+
runningJobs: number
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const GRACE_MS = 3000
|
|
101
|
+
const POLL_MS = 2000
|
|
102
|
+
|
|
103
|
+
export function isSessionEndMode(value: unknown): value is SessionEndMode {
|
|
104
|
+
return value === 'off' || value === 'restart' || value === 'close' || value === 'shutdown'
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function sessionLogPath(): string {
|
|
108
|
+
return join(tmpdir(), 'dsh-mcviseron-session-end.log')
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function defaultLog(message: string): void {
|
|
112
|
+
try {
|
|
113
|
+
appendFileSync(sessionLogPath(), new Date().toISOString() + ' ' + message + '\n', 'utf8')
|
|
114
|
+
} catch {
|
|
115
|
+
/* diagnostics must never break the action */
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Run the Windows shutdown command; user-selected only. */
|
|
120
|
+
export function shutdownComputer(): void {
|
|
121
|
+
if (process.platform !== 'win32') throw new Error('shutdown is available only on Windows')
|
|
122
|
+
execFileSync('shutdown.exe', ['/s', '/t', '5', '/c', 'DSH session ended'], {
|
|
123
|
+
windowsHide: true,
|
|
124
|
+
timeout: 5000,
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function listAgents(service: unknown): Array<{ id?: unknown; status?: unknown; session?: { id?: unknown } }> {
|
|
129
|
+
try {
|
|
130
|
+
const list = (service as { list?: unknown } | undefined)?.list
|
|
131
|
+
if (typeof list !== 'function') return []
|
|
132
|
+
const value = list.call(service)
|
|
133
|
+
return Array.isArray(value) ? value as Array<{ id?: unknown; status?: unknown; session?: { id?: unknown } }> : []
|
|
134
|
+
} catch {
|
|
135
|
+
return []
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function listJobs(service: unknown, owner?: string): Array<{ id?: unknown; status?: unknown }> {
|
|
140
|
+
try {
|
|
141
|
+
const list = (service as { list?: unknown } | undefined)?.list
|
|
142
|
+
if (typeof list !== 'function') return []
|
|
143
|
+
const value = list.call(service, owner)
|
|
144
|
+
return Array.isArray(value) ? value as Array<{ id?: unknown; status?: unknown }> : []
|
|
145
|
+
} catch {
|
|
146
|
+
return []
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Count live agent turns and running background jobs. Subagent work is
|
|
152
|
+
* represented by a live agent turn; background jobs are collected both
|
|
153
|
+
* globally and per live owner so an idle owner's job still blocks a restart.
|
|
154
|
+
*/
|
|
155
|
+
export function inspectRunningTasks(agentService: unknown, jobService: unknown): RunningTasks {
|
|
156
|
+
const agents = listAgents(agentService)
|
|
157
|
+
const runningAgents = agents.filter(agent => agent.status === 'running')
|
|
158
|
+
const owners = new Set<string>()
|
|
159
|
+
for (const agent of agents) {
|
|
160
|
+
const id = typeof agent.id === 'string'
|
|
161
|
+
? agent.id
|
|
162
|
+
: typeof agent.session?.id === 'string' ? agent.session.id : ''
|
|
163
|
+
if (id !== '') owners.add(id)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const jobs = new Map<string, { id?: unknown; status?: unknown }>()
|
|
167
|
+
const collect = (owner?: string): void => {
|
|
168
|
+
for (const job of listJobs(jobService, owner)) {
|
|
169
|
+
const id = typeof job.id === 'string' ? job.id : ''
|
|
170
|
+
if (id !== '') jobs.set(id, job)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
collect(undefined)
|
|
174
|
+
for (const owner of owners) collect(owner)
|
|
175
|
+
const runningJobs = [...jobs.values()].filter(job => job.status === 'running' || job.status === 'stopping')
|
|
176
|
+
return {
|
|
177
|
+
running: runningAgents.length > 0 || runningJobs.length > 0,
|
|
178
|
+
agents: runningAgents.length,
|
|
179
|
+
jobs: runningJobs.length,
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Create the in-memory session-end state machine.
|
|
185
|
+
*
|
|
186
|
+
* @param deps - optional seams for tests and for the live desktop services.
|
|
187
|
+
* @returns the controller used by routes, the agent tool, and session events.
|
|
188
|
+
*/
|
|
189
|
+
export function createSessionEndController(deps: SessionEndDeps = {}): SessionEndController {
|
|
190
|
+
const platform = deps.platform ?? process.platform
|
|
191
|
+
const enabled = deps.enabled ?? true
|
|
192
|
+
const graceMs = deps.graceMs ?? GRACE_MS
|
|
193
|
+
const pollMs = deps.pollMs ?? POLL_MS
|
|
194
|
+
const log = deps.log ?? defaultLog
|
|
195
|
+
const entries = new Map<string, Entry>()
|
|
196
|
+
const timers = new Map<string, ReturnType<typeof setTimeout>>()
|
|
197
|
+
const resolveTarget = deps.resolveTarget ?? (() => resolveRestartTarget(
|
|
198
|
+
process.execPath,
|
|
199
|
+
process.ppid,
|
|
200
|
+
existsSync,
|
|
201
|
+
typeof deps.appPath === 'string' ? deps.appPath : '',
|
|
202
|
+
process.argv,
|
|
203
|
+
))
|
|
204
|
+
const hasRunningTasks = deps.hasRunningTasks ?? (() => ({ running: false, agents: 0, jobs: 0 }))
|
|
205
|
+
const restart = deps.restart ?? launchRestart
|
|
206
|
+
const close = deps.close ?? closeDesktop
|
|
207
|
+
const shutdown = deps.shutdown ?? shutdownComputer
|
|
208
|
+
|
|
209
|
+
const cancel = (sessionId: string): void => {
|
|
210
|
+
const timer = timers.get(sessionId)
|
|
211
|
+
if (timer === undefined) return
|
|
212
|
+
clearTimeout(timer)
|
|
213
|
+
timers.delete(sessionId)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const view = (sessionId: string): SessionEndView => {
|
|
217
|
+
const entry = entries.get(sessionId)
|
|
218
|
+
let available = { restart: false, close: platform === 'win32', shutdown: platform === 'win32' }
|
|
219
|
+
try {
|
|
220
|
+
const target = resolveTarget()
|
|
221
|
+
available = {
|
|
222
|
+
restart: target !== undefined,
|
|
223
|
+
close: target !== undefined || platform === 'win32',
|
|
224
|
+
shutdown: platform === 'win32',
|
|
225
|
+
}
|
|
226
|
+
} catch {
|
|
227
|
+
/* keep the conservative fallback */
|
|
228
|
+
}
|
|
229
|
+
return {
|
|
230
|
+
enabled,
|
|
231
|
+
mode: entry?.mode ?? 'off',
|
|
232
|
+
requestedBy: entry?.requestedBy ?? 'none',
|
|
233
|
+
waiting: entry?.waiting ?? false,
|
|
234
|
+
runningAgents: entry?.runningAgents ?? 0,
|
|
235
|
+
runningJobs: entry?.runningJobs ?? 0,
|
|
236
|
+
available,
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const schedule = (sessionId: string, delay: number): void => {
|
|
241
|
+
cancel(sessionId)
|
|
242
|
+
const timer = setTimeout(() => {
|
|
243
|
+
timers.delete(sessionId)
|
|
244
|
+
pump(sessionId)
|
|
245
|
+
}, delay) as ReturnType<typeof setTimeout> & { unref?: () => void }
|
|
246
|
+
timer.unref?.()
|
|
247
|
+
timers.set(sessionId, timer)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const fire = (sessionId: string, entry: Entry): void => {
|
|
251
|
+
cancel(sessionId)
|
|
252
|
+
entries.delete(sessionId)
|
|
253
|
+
const mode = entry.mode
|
|
254
|
+
try {
|
|
255
|
+
if (mode === 'restart') {
|
|
256
|
+
const target = resolveTarget()
|
|
257
|
+
if (target === undefined) {
|
|
258
|
+
log('restart skipped: desktop app unavailable (session ' + sessionId + ')')
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
restart(target)
|
|
262
|
+
} else if (mode === 'close') {
|
|
263
|
+
close(resolveTarget())
|
|
264
|
+
} else {
|
|
265
|
+
shutdown()
|
|
266
|
+
}
|
|
267
|
+
} catch (error) {
|
|
268
|
+
log(mode + ' failed (session ' + sessionId + '): ' + (error instanceof Error ? error.message : String(error)))
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const pump = (sessionId: string): void => {
|
|
273
|
+
const entry = entries.get(sessionId)
|
|
274
|
+
if (entry === undefined) return
|
|
275
|
+
|
|
276
|
+
// Only a restart waits for unrelated work. Closing DSH or shutting down the
|
|
277
|
+
// computer is an explicit destructive action and runs after the render grace.
|
|
278
|
+
if (entry.mode === 'restart') {
|
|
279
|
+
let tasks: RunningTasks
|
|
280
|
+
try {
|
|
281
|
+
tasks = hasRunningTasks()
|
|
282
|
+
} catch (error) {
|
|
283
|
+
log('task inspection failed (session ' + sessionId + '): ' + (error instanceof Error ? error.message : String(error)))
|
|
284
|
+
tasks = { running: false, agents: 0, jobs: 0 }
|
|
285
|
+
}
|
|
286
|
+
if (tasks.running) {
|
|
287
|
+
entry.waiting = true
|
|
288
|
+
entry.runningAgents = tasks.agents
|
|
289
|
+
entry.runningJobs = tasks.jobs
|
|
290
|
+
schedule(sessionId, pollMs)
|
|
291
|
+
return
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
entry.waiting = false
|
|
296
|
+
fire(sessionId, entry)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
return {
|
|
300
|
+
get(sessionId) {
|
|
301
|
+
return view(sessionId)
|
|
302
|
+
},
|
|
303
|
+
set(sessionId, mode, requestedBy) {
|
|
304
|
+
if (sessionId === '') throw new TypeError('sessionId must be non-empty')
|
|
305
|
+
if (!enabled) throw new Error('session-end actions are disabled')
|
|
306
|
+
if (!isSessionEndMode(mode)) throw new TypeError('unknown session-end mode: ' + String(mode))
|
|
307
|
+
if (requestedBy !== 'user' && requestedBy !== 'ai') throw new TypeError('requestedBy must be user or ai')
|
|
308
|
+
if (requestedBy === 'ai' && mode === 'shutdown') throw new Error('shutdown is user-only')
|
|
309
|
+
if (mode === 'shutdown' && platform !== 'win32') throw new Error('shutdown is available only on Windows')
|
|
310
|
+
if (mode === 'off') {
|
|
311
|
+
cancel(sessionId)
|
|
312
|
+
entries.delete(sessionId)
|
|
313
|
+
return view(sessionId)
|
|
314
|
+
}
|
|
315
|
+
entries.set(sessionId, {
|
|
316
|
+
mode,
|
|
317
|
+
requestedBy,
|
|
318
|
+
waiting: false,
|
|
319
|
+
runningAgents: 0,
|
|
320
|
+
runningJobs: 0,
|
|
321
|
+
})
|
|
322
|
+
return view(sessionId)
|
|
323
|
+
},
|
|
324
|
+
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
|
|
329
|
+
cancel(sessionId)
|
|
330
|
+
entries.delete(sessionId)
|
|
331
|
+
},
|
|
332
|
+
onTurnEnd(sessionId) {
|
|
333
|
+
const entry = entries.get(sessionId)
|
|
334
|
+
if (entry === undefined || timers.has(sessionId)) return
|
|
335
|
+
schedule(sessionId, graceMs)
|
|
336
|
+
},
|
|
337
|
+
dispose() {
|
|
338
|
+
for (const timer of timers.values()) clearTimeout(timer)
|
|
339
|
+
timers.clear()
|
|
340
|
+
entries.clear()
|
|
341
|
+
},
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
346
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
347
|
+
res.end(JSON.stringify(body))
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function readJsonBody(req: Parameters<WebRoute['handler']>[0]): Promise<unknown> {
|
|
351
|
+
const chunks: Buffer[] = []
|
|
352
|
+
let size = 0
|
|
353
|
+
for await (const chunk of req) {
|
|
354
|
+
const buffer = chunk as Buffer
|
|
355
|
+
size += buffer.length
|
|
356
|
+
if (size > 8 * 1024) return undefined
|
|
357
|
+
chunks.push(buffer)
|
|
358
|
+
}
|
|
359
|
+
try {
|
|
360
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
361
|
+
} catch {
|
|
362
|
+
return undefined
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function bodySessionId(body: unknown): string | undefined {
|
|
367
|
+
if (body === null || typeof body !== 'object') return undefined
|
|
368
|
+
const value = (body as { sessionId?: unknown }).sessionId
|
|
369
|
+
return typeof value === 'string' && value !== '' ? value : undefined
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Build the state and set routes for the composer control. */
|
|
373
|
+
export function makeSessionEndRoutes(controller: SessionEndController): WebRoute[] {
|
|
374
|
+
const state: WebRoute = {
|
|
375
|
+
kind: 'exact',
|
|
376
|
+
path: SESSION_END_API.state,
|
|
377
|
+
handler: async (req, res): Promise<void> => {
|
|
378
|
+
try {
|
|
379
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method-not-allowed' })
|
|
380
|
+
if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: 'forbidden' })
|
|
381
|
+
const sessionId = bodySessionId(await readJsonBody(req))
|
|
382
|
+
if (sessionId === undefined) return json(res, 400, { ok: false, error: 'sessionId-required' })
|
|
383
|
+
json(res, 200, { ok: true, ...controller.get(sessionId) })
|
|
384
|
+
} catch (error) {
|
|
385
|
+
json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
386
|
+
}
|
|
387
|
+
},
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const set: WebRoute = {
|
|
391
|
+
kind: 'exact',
|
|
392
|
+
path: SESSION_END_API.set,
|
|
393
|
+
handler: async (req, res): Promise<void> => {
|
|
394
|
+
try {
|
|
395
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method-not-allowed' })
|
|
396
|
+
if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: 'forbidden' })
|
|
397
|
+
const body = await readJsonBody(req)
|
|
398
|
+
const sessionId = bodySessionId(body)
|
|
399
|
+
if (sessionId === undefined) return json(res, 400, { ok: false, error: 'sessionId-required' })
|
|
400
|
+
const mode = (body as { mode?: unknown }).mode
|
|
401
|
+
if (!isSessionEndMode(mode)) return json(res, 400, { ok: false, error: 'mode-invalid' })
|
|
402
|
+
json(res, 200, { ok: true, ...controller.set(sessionId, mode, 'user') })
|
|
403
|
+
} catch (error) {
|
|
404
|
+
json(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
405
|
+
}
|
|
406
|
+
},
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
return [state, set]
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function serviceOf(ctx: Context, name: string): unknown {
|
|
413
|
+
try {
|
|
414
|
+
const direct = (ctx as unknown as Record<string, unknown>)[name]
|
|
415
|
+
if (direct !== undefined) return direct
|
|
416
|
+
} catch {
|
|
417
|
+
/* fall through */
|
|
418
|
+
}
|
|
419
|
+
try {
|
|
420
|
+
const get = (ctx as unknown as { get?: (key: string) => unknown }).get
|
|
421
|
+
return typeof get === 'function' ? get.call(ctx, name) : undefined
|
|
422
|
+
} catch {
|
|
423
|
+
return undefined
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const emailed = new Map<string, number>()
|
|
428
|
+
|
|
429
|
+
function installAgentTool(ctx: Context, controller: SessionEndController, options: Required<SessionEndOptions>, log: (message: string) => void): void {
|
|
430
|
+
const inject = (ctx as unknown as { inject?: (deps: string[], callback: (scope: Context) => void) => unknown }).inject
|
|
431
|
+
if (typeof inject !== 'function') return
|
|
432
|
+
try {
|
|
433
|
+
inject.call(ctx, ['tools'], (scope) => {
|
|
434
|
+
const tools = serviceOf(scope, 'tools') as {
|
|
435
|
+
register?: (definition: unknown) => (() => void) | undefined
|
|
436
|
+
} | undefined
|
|
437
|
+
if (tools === undefined || typeof tools.register !== 'function') return
|
|
438
|
+
const definition = {
|
|
439
|
+
name: 'set_session_end_action',
|
|
440
|
+
description: [
|
|
441
|
+
'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.',
|
|
445
|
+
].join(' '),
|
|
446
|
+
parameters: {
|
|
447
|
+
action: {
|
|
448
|
+
type: 'string',
|
|
449
|
+
required: true,
|
|
450
|
+
enum: ['restart', 'close', 'off'],
|
|
451
|
+
description: 'restart DSH after this turn, close DSH, or clear the pending action',
|
|
452
|
+
},
|
|
453
|
+
reason: {
|
|
454
|
+
type: 'string',
|
|
455
|
+
description: 'Optional short reason shown in the tool result; the user sees the same action in the composer',
|
|
456
|
+
},
|
|
457
|
+
},
|
|
458
|
+
output: {
|
|
459
|
+
schema: {
|
|
460
|
+
type: 'object',
|
|
461
|
+
additionalProperties: false,
|
|
462
|
+
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 },
|
|
467
|
+
},
|
|
468
|
+
},
|
|
469
|
+
render: (_args: unknown, value: { message?: unknown }) => [{
|
|
470
|
+
type: 'text',
|
|
471
|
+
text: typeof value?.message === 'string' ? value.message : 'session-end action updated',
|
|
472
|
+
}],
|
|
473
|
+
},
|
|
474
|
+
execute(args: { action?: unknown; reason?: unknown }, exec: { agent?: { session?: { id?: unknown } } }) {
|
|
475
|
+
const sessionId = exec.agent?.session?.id
|
|
476
|
+
if (typeof sessionId !== 'string' || sessionId === '') {
|
|
477
|
+
throw new Error('set_session_end_action requires an owning agent session')
|
|
478
|
+
}
|
|
479
|
+
const action = args.action
|
|
480
|
+
if (action !== 'off' && action !== 'restart' && action !== 'close') {
|
|
481
|
+
throw new Error('action must be restart, close, or off')
|
|
482
|
+
}
|
|
483
|
+
const before = controller.get(sessionId)
|
|
484
|
+
if (action === 'restart' && !before.available.restart) {
|
|
485
|
+
throw new Error('restart is unavailable in this host')
|
|
486
|
+
}
|
|
487
|
+
if (action === 'close' && !before.available.close) {
|
|
488
|
+
throw new Error('close is unavailable in this host')
|
|
489
|
+
}
|
|
490
|
+
controller.set(sessionId, action, 'ai')
|
|
491
|
+
if (action !== 'off' && options.notifyEmailOnAi) {
|
|
492
|
+
const key = sessionId + ':' + action
|
|
493
|
+
const now = Date.now()
|
|
494
|
+
const previous = emailed.get(key) ?? 0
|
|
495
|
+
if (now - previous > 60_000) {
|
|
496
|
+
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
|
|
500
|
+
void sendSessionEndEmail({
|
|
501
|
+
settings: serviceOf(ctx, 'settings'),
|
|
502
|
+
template: options,
|
|
503
|
+
sessionId,
|
|
504
|
+
sessionName,
|
|
505
|
+
action,
|
|
506
|
+
reason: typeof args.reason === 'string' ? args.reason : '',
|
|
507
|
+
}).then(result => {
|
|
508
|
+
if (!result.sent) log('email reminder skipped: ' + (result.reason ?? 'unknown'))
|
|
509
|
+
}).catch(error => {
|
|
510
|
+
log('email reminder failed: ' + (error instanceof Error ? error.message : String(error)))
|
|
511
|
+
})
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
const message = action === 'off'
|
|
515
|
+
? 'Session-end action cleared.'
|
|
516
|
+
: 'AI requested ' + action + ' after this turn'
|
|
517
|
+
+ (action === 'restart' ? '; it waits for running tasks.' : '.')
|
|
518
|
+
+ (typeof args.reason === 'string' && args.reason !== '' ? ' Reason: ' + args.reason : '')
|
|
519
|
+
return { ok: true, action, requestedBy: 'ai', message }
|
|
520
|
+
},
|
|
521
|
+
}
|
|
522
|
+
try {
|
|
523
|
+
const dispose = tools.register(definition)
|
|
524
|
+
const effect = (scope as unknown as { effect?: (setup: () => () => void, label: string) => unknown }).effect
|
|
525
|
+
if (typeof effect === 'function' && typeof dispose === 'function') {
|
|
526
|
+
effect.call(scope, () => () => { try { dispose() } catch { /* already disposed */ } }, 'mcviseron-session-end: tool')
|
|
527
|
+
}
|
|
528
|
+
} catch (error) {
|
|
529
|
+
defaultLog('tool registration failed: ' + (error instanceof Error ? error.message : String(error)))
|
|
530
|
+
}
|
|
531
|
+
})
|
|
532
|
+
} catch (error) {
|
|
533
|
+
defaultLog('tool injection failed: ' + (error instanceof Error ? error.message : String(error)))
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function sessionIdOf(session: unknown): string {
|
|
538
|
+
const id = (session as { id?: unknown } | undefined)?.id
|
|
539
|
+
return typeof id === 'string' ? id : ''
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export type SessionEndConfig = SessionEndOptions
|
|
543
|
+
|
|
544
|
+
/** Clamp the externally supplied options before wiring the controller. */
|
|
545
|
+
export function normalizeSessionEndOptions(input?: SessionEndConfig): Required<SessionEndOptions> {
|
|
546
|
+
const source = input !== null && typeof input === 'object' && !Array.isArray(input)
|
|
547
|
+
? input as Record<string, unknown>
|
|
548
|
+
: {}
|
|
549
|
+
const bool = (key: string, fallback: boolean): boolean => typeof source[key] === 'boolean' ? source[key] as boolean : fallback
|
|
550
|
+
const number = (key: string, fallback: number, min: number, max: number): number => {
|
|
551
|
+
const value = source[key]
|
|
552
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
|
|
553
|
+
return Math.min(Math.max(Math.trunc(value), min), max)
|
|
554
|
+
}
|
|
555
|
+
const string = (key: string, fallback: string): string => typeof source[key] === 'string' ? source[key] as string : fallback
|
|
556
|
+
return {
|
|
557
|
+
enabled: bool('enabled', DEFAULT_SESSION_END_CONFIG.enabled),
|
|
558
|
+
graceMs: number('graceMs', DEFAULT_SESSION_END_CONFIG.graceMs, 0, 15000),
|
|
559
|
+
notifyEmailOnAi: bool('notifyEmailOnAi', DEFAULT_SESSION_END_CONFIG.notifyEmailOnAi),
|
|
560
|
+
emailSubject: string('emailSubject', DEFAULT_SESSION_END_CONFIG.emailSubject),
|
|
561
|
+
emailBody: string('emailBody', DEFAULT_SESSION_END_CONFIG.emailBody),
|
|
562
|
+
appPath: string('appPath', ''),
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
export const inject = ['webServer']
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Mount the session-end routes, agent tool, and turn listener.
|
|
570
|
+
*
|
|
571
|
+
* @param ctx - the component context.
|
|
572
|
+
* @param config - optional desktop app path inherited from the restart group.
|
|
573
|
+
*/
|
|
574
|
+
export function apply(ctx: Context, config?: SessionEndConfig): void {
|
|
575
|
+
const options = normalizeSessionEndOptions(config)
|
|
576
|
+
const log = defaultLog
|
|
577
|
+
const controller = createSessionEndController({
|
|
578
|
+
enabled: options.enabled,
|
|
579
|
+
graceMs: options.graceMs,
|
|
580
|
+
appPath: options.appPath,
|
|
581
|
+
hasRunningTasks: () => inspectRunningTasks(serviceOf(ctx, 'agents'), serviceOf(ctx, 'jobs')),
|
|
582
|
+
})
|
|
583
|
+
|
|
584
|
+
const routes = makeSessionEndRoutes(controller)
|
|
585
|
+
ctx.effect(() => {
|
|
586
|
+
const disposers = routes.map(route => ctx.webServer.register(route))
|
|
587
|
+
return () => {
|
|
588
|
+
for (const dispose of disposers) dispose()
|
|
589
|
+
}
|
|
590
|
+
}, 'mcviseron-session-end: routes')
|
|
591
|
+
|
|
592
|
+
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
|
+
})
|
|
600
|
+
installAgentTool(ctx, controller, options, log)
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
try {
|
|
604
|
+
ctx.effect(() => () => controller.dispose(), 'mcviseron-session-end: timers')
|
|
605
|
+
} catch {
|
|
606
|
+
/* a host without effects still gets the controller */
|
|
607
|
+
}
|
|
608
|
+
}
|