@tavlo-dsh/dsh-plugin-hooks 0.0.0-stage → 0.1.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.
@@ -0,0 +1,999 @@
1
+ /**
2
+ * Bridge connecting DSH 0.2.2-rc.1 Cordis events & session events to all 19 hook mount points.
3
+ * Waterfall listeners (`approval/request`, `user-questions/request`, `tools/pre-execute`) use
4
+ * `{ prepend: true }`, run side effects asynchronously, and immediately call `next()`.
5
+ */
6
+
7
+ import { randomUUID } from 'node:crypto'
8
+ import path from 'node:path'
9
+ import { getMountPoint } from './hook-catalog.js'
10
+ import { matchesScriptMatcher } from './script-runner.js'
11
+
12
+ const DEDUP_TTL_MS = 5000
13
+ const MAX_SESSION_META = 500
14
+ const DEFAULT_TURN_COMPLETE_DEBOUNCE_MS = 1200
15
+
16
+ function safeBasename(rawPath) {
17
+ if (typeof rawPath !== 'string' || !rawPath.trim()) return ''
18
+ const cleaned = rawPath.trim().replace(/[\\/]+$/, '')
19
+ if (!cleaned) return ''
20
+ return path.win32.basename(cleaned) || path.posix.basename(cleaned) || ''
21
+ }
22
+
23
+ function sanitizeSummaryText(raw, maxLen = 160) {
24
+ if (typeof raw !== 'string') return ''
25
+ return raw.replace(/[\r\n\t\x00-\x1f\x7f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, maxLen)
26
+ }
27
+
28
+ function isSubagentSession(session) {
29
+ if (!session || typeof session !== 'object') return false
30
+ const header = session.header
31
+ if (!header || typeof header !== 'object') return false
32
+ if (header.origin === 'subagent') return true
33
+ if (typeof header.delegationDepth === 'number' && header.delegationDepth > 0) return true
34
+ return false
35
+ }
36
+
37
+ /**
38
+ * Create the DSH event bridge.
39
+ */
40
+ export function createDshHookBridge({
41
+ ctx,
42
+ configStore,
43
+ scriptRunner,
44
+ dispatcher,
45
+ logger,
46
+ now = Date.now,
47
+ turnCompleteDebounceMs = DEFAULT_TURN_COMPLETE_DEBOUNCE_MS,
48
+ } = {}) {
49
+ const sessionMeta = new Map()
50
+ const recentKeys = new Map()
51
+ const approvalCallIds = new Map()
52
+ const subagentSessionIds = new Set()
53
+ const activeSubagentsByParent = new Map()
54
+ const pendingTurnCompleted = new Map()
55
+ const disposers = []
56
+ let jobsServiceSubscribed = false
57
+ let disposed = false
58
+
59
+ function resolveLiveAgent(sessionId) {
60
+ if (typeof sessionId !== 'string' || !sessionId) return undefined
61
+ try {
62
+ return ctx?.get?.('agents')?.get?.(sessionId)
63
+ } catch {
64
+ return undefined
65
+ }
66
+ }
67
+
68
+ function resolveLiveSession(sessionId) {
69
+ if (typeof sessionId !== 'string' || !sessionId) return undefined
70
+ const agent = resolveLiveAgent(sessionId)
71
+ if (agent?.session) return agent.session
72
+ try {
73
+ return ctx?.get?.('sessions')?.get?.(sessionId)
74
+ } catch {
75
+ return undefined
76
+ }
77
+ }
78
+
79
+ function isSubagentById(sessionId) {
80
+ if (typeof sessionId !== 'string' || !sessionId) return false
81
+ if (subagentSessionIds.has(sessionId)) return true
82
+ const session = resolveLiveSession(sessionId)
83
+ if (isSubagentSession(session)) {
84
+ subagentSessionIds.add(sessionId)
85
+ return true
86
+ }
87
+ return false
88
+ }
89
+
90
+ function getLiveGoal(agent) {
91
+ if (!agent) return undefined
92
+ try {
93
+ return ctx?.get?.('goals')?.get?.(agent)
94
+ } catch {
95
+ return undefined
96
+ }
97
+ }
98
+
99
+ function willAutoContinueGoal(agent) {
100
+ const goal = getLiveGoal(agent)
101
+ if (!goal || goal.phase !== 'active' || goal.activation !== 'armed') return false
102
+ if (typeof goal.maxGoalRounds === 'number' && typeof goal.roundsStarted === 'number') {
103
+ return goal.roundsStarted < goal.maxGoalRounds
104
+ }
105
+ return true
106
+ }
107
+
108
+ function getTurnContinueReason(sessionId, session) {
109
+ if (isSubagentSession(session) || isSubagentById(sessionId)) return 'subagent'
110
+ const agent = resolveLiveAgent(sessionId)
111
+ if (agent?.inbox?.hasPending) return 'inbox-pending'
112
+ if (willAutoContinueGoal(agent)) return 'goal-armed'
113
+ if (sessionId && (activeSubagentsByParent.get(sessionId)?.size ?? 0) > 0) return 'subagent-active'
114
+ return null
115
+ }
116
+
117
+ function recordDiagnostic(kind, payload) {
118
+ try {
119
+ scriptRunner?.recordTriggerLog?.({
120
+ kind,
121
+ ...payload,
122
+ })
123
+ } catch {
124
+ // Never let diagnostics break event flow
125
+ }
126
+ }
127
+
128
+ function cancelPendingTurnCompleted(sessionId, cancelReason) {
129
+ if (typeof sessionId !== 'string' || !sessionId) return
130
+ const pending = pendingTurnCompleted.get(sessionId)
131
+ if (!pending) return
132
+ clearTimeout(pending.timer)
133
+ pendingTurnCompleted.delete(sessionId)
134
+ if (cancelReason && cancelReason !== 'dispose') {
135
+ recordDiagnostic('skip', {
136
+ mountPointId: 'turn.completed',
137
+ sessionId,
138
+ turn: pending.turn ?? null,
139
+ reason: cancelReason,
140
+ summary: `Cancelled debounced turn.completed (${cancelReason})`,
141
+ })
142
+ }
143
+ }
144
+
145
+ function rememberSessionMeta(sessionId, { cwd, title } = {}) {
146
+ if (typeof sessionId !== 'string' || !sessionId) return
147
+ const prev = sessionMeta.get(sessionId) ?? {}
148
+ sessionMeta.set(sessionId, {
149
+ cwd: cwd ?? prev.cwd,
150
+ title: title ?? prev.title,
151
+ updatedAt: now(),
152
+ })
153
+ if (sessionMeta.size > MAX_SESSION_META) {
154
+ const oldestKey = sessionMeta.keys().next().value
155
+ if (oldestKey) sessionMeta.delete(oldestKey)
156
+ }
157
+ }
158
+
159
+ function resolveSessionLabels(sessionId, fallbackCwd) {
160
+ const cached = sessionId ? sessionMeta.get(sessionId) : undefined
161
+ const cwd = fallbackCwd || cached?.cwd
162
+ let projectName = safeBasename(cwd)
163
+ if (!projectName && sessionId) {
164
+ try {
165
+ const workspaces = ctx?.get?.('workspaceRegistry')?.list?.() ?? []
166
+ const matched = workspaces.find(
167
+ (ws) => Array.isArray(ws?.sessionIds) && ws.sessionIds.includes(sessionId),
168
+ )
169
+ projectName = sanitizeSummaryText(matched?.title, 64) || safeBasename(matched?.path)
170
+ } catch {
171
+ // Ignore unavailable workspace registry
172
+ }
173
+ }
174
+ return {
175
+ sessionTitle: cached?.title ? sanitizeSummaryText(cached.title, 80) : undefined,
176
+ projectName: projectName || 'DSH Workspace',
177
+ }
178
+ }
179
+
180
+ function claimDedup(key) {
181
+ if (!key) return true
182
+ const current = now()
183
+ for (const [k, expiresAt] of recentKeys) {
184
+ if (expiresAt <= current) recentKeys.delete(k)
185
+ }
186
+ const existing = recentKeys.get(key)
187
+ if (existing && existing > current) {
188
+ return false
189
+ }
190
+ recentKeys.set(key, current + DEDUP_TTL_MS)
191
+ return true
192
+ }
193
+
194
+ async function runMountScripts(mountPointId, mpConfig, hookEvent, { dryRun = false } = {}) {
195
+ const mpDef = getMountPoint(mountPointId)
196
+ const scripts = Array.isArray(mpConfig?.scripts) ? mpConfig.scripts : []
197
+ const eligible = scripts.filter(
198
+ (script) =>
199
+ script.enabled &&
200
+ (!mpDef?.supportsMatcher || matchesScriptMatcher(script.matcher, hookEvent)),
201
+ )
202
+ if (eligible.length === 0) {
203
+ return { suppressed: false, directive: null, scriptsRun: 0, logs: [] }
204
+ }
205
+
206
+ const results = await Promise.allSettled(
207
+ eligible.map((script) => scriptRunner.executeScript(script, hookEvent, { dryRun })),
208
+ )
209
+
210
+ let suppressed = false
211
+ let mergedDirective = null
212
+ const logs = []
213
+
214
+ for (const res of results) {
215
+ if (res.status !== 'fulfilled' || !res.value) continue
216
+ const entry = res.value
217
+ logs.push(entry)
218
+ if (entry.suppressed) suppressed = true
219
+ if (entry.directive && typeof entry.directive === 'object') {
220
+ mergedDirective = { ...(mergedDirective ?? {}), ...entry.directive }
221
+ }
222
+ }
223
+
224
+ return { suppressed, directive: mergedDirective, scriptsRun: eligible.length, logs }
225
+ }
226
+
227
+ async function triggerMountPoint(mountPointId, context = {}, { force = false } = {}) {
228
+ if (disposed) return { skipped: true, reason: 'disposed' }
229
+ const mpDef = getMountPoint(mountPointId)
230
+ if (!mpDef) return { skipped: true, reason: 'unknown-mount-point' }
231
+
232
+ const { config } = configStore.getSnapshot()
233
+ const mpConfig = config.mountPoints?.[mountPointId]
234
+ if (!force && !mpConfig?.enabled) {
235
+ return { skipped: true, reason: 'disabled' }
236
+ }
237
+
238
+ const sessionId = typeof context.sessionId === 'string' ? context.sessionId : undefined
239
+ const labels = resolveSessionLabels(sessionId, context.cwd)
240
+ const eventId = context.eventId || randomUUID()
241
+ const timestamp = new Date(now()).toISOString()
242
+ const turn = typeof context.turn === 'number' && Number.isFinite(context.turn) ? context.turn : undefined
243
+
244
+ const hookEvent = {
245
+ eventId,
246
+ hookPoint: mountPointId,
247
+ category: mpDef.category,
248
+ timestamp,
249
+ sessionId,
250
+ sessionTitle: context.sessionTitle || labels.sessionTitle,
251
+ projectName: context.projectName || labels.projectName,
252
+ summary: sanitizeSummaryText(context.summary) || (mpDef.nameZh ?? mpDef.nameEn),
253
+ toolName: context.toolName ? sanitizeSummaryText(context.toolName, 80) : undefined,
254
+ reason: context.reason ? sanitizeSummaryText(context.reason, 160) : undefined,
255
+ approvalId: context.approvalId ? String(context.approvalId) : undefined,
256
+ bellEnabled: Boolean(mpConfig?.bellEnabled ?? mpDef.defaultBell),
257
+ ...(turn !== undefined ? { turn } : {}),
258
+ }
259
+
260
+ const startedAt = now()
261
+ const scriptOutcome = await runMountScripts(mountPointId, mpConfig, hookEvent, { dryRun: force })
262
+ if (scriptOutcome.suppressed && !force) {
263
+ recordDiagnostic('trigger', {
264
+ mountPointId,
265
+ sessionId: sessionId ?? null,
266
+ turn: turn ?? null,
267
+ reason: hookEvent.reason ?? null,
268
+ summary: hookEvent.summary,
269
+ suppressed: true,
270
+ scriptsRun: scriptOutcome.scriptsRun,
271
+ dispatched: false,
272
+ })
273
+ return {
274
+ skipped: true,
275
+ reason: 'suppressed',
276
+ suppressed: true,
277
+ eventId,
278
+ elapsedMs: Math.max(0, now() - startedAt),
279
+ }
280
+ }
281
+
282
+ let dispatchResult = null
283
+ if (!scriptOutcome.suppressed) {
284
+ dispatchResult = await dispatcher.dispatch(hookEvent, scriptOutcome.directive ?? undefined)
285
+ }
286
+
287
+ recordDiagnostic('trigger', {
288
+ mountPointId,
289
+ sessionId: sessionId ?? null,
290
+ turn: turn ?? null,
291
+ reason: hookEvent.reason ?? null,
292
+ summary: hookEvent.summary,
293
+ suppressed: scriptOutcome.suppressed,
294
+ scriptsRun: scriptOutcome.scriptsRun,
295
+ dispatched: Boolean(dispatchResult?.dispatched),
296
+ ...(context.goalPhase ? { goalPhase: context.goalPhase } : {}),
297
+ })
298
+
299
+ return {
300
+ ok: true,
301
+ eventId,
302
+ mountPointId,
303
+ suppressed: scriptOutcome.suppressed,
304
+ scriptsRun: scriptOutcome.scriptsRun,
305
+ elapsedMs: Math.max(0, now() - startedAt),
306
+ dispatch: dispatchResult,
307
+ logs: scriptRunner.getLogs(),
308
+ }
309
+ }
310
+
311
+ function safeAsync(label, fn) {
312
+ if (disposed) return
313
+ void Promise.resolve()
314
+ .then(fn)
315
+ .catch((error) => {
316
+ logger?.warn?.(`tavlo-hooks: ${label} error: ${error?.message || error}`)
317
+ })
318
+ }
319
+
320
+ function listen(eventName, handler, options = { global: true }) {
321
+ if (!ctx?.on) return
322
+ const dispose = ctx.on(eventName, handler, options)
323
+ if (typeof dispose === 'function') disposers.push(dispose)
324
+ }
325
+
326
+ function attachJobsService(jobsService) {
327
+ if (typeof jobsService?.events?.subscribe !== 'function') return null
328
+ if (jobsServiceSubscribed) return null
329
+ jobsServiceSubscribed = true
330
+ const unsub = jobsService.events.subscribe({ owners: 'all' }, (jobEvent) => {
331
+ if (disposed || !jobEvent || jobEvent.type !== 'settled') return
332
+ if (jobEvent.awaited === true || jobEvent.cause === 'teardown') return
333
+ const job = jobEvent.job
334
+ const ownerId = typeof job?.owner === 'string' && job.owner ? job.owner : undefined
335
+ if (ownerId && isSubagentById(ownerId)) return
336
+ const jobId = job?.id ? String(job.id) : undefined
337
+ if (jobId && !claimDedup(`job-settled:${jobId}`)) return
338
+ const status = job?.status || 'completed'
339
+ const label = job?.label ? sanitizeSummaryText(job.label, 64) : '后台任务'
340
+ const ownerSession = ownerId ? resolveLiveSession(ownerId) : undefined
341
+ safeAsync('jobs:settled', async () => {
342
+ await triggerMountPoint('job.settled', {
343
+ sessionId: ownerId,
344
+ cwd: ownerSession?.header?.cwd,
345
+ reason: status,
346
+ summary: `后台任务「${label}」已结束 (${status})`,
347
+ })
348
+ })
349
+ })
350
+ return () => {
351
+ jobsServiceSubscribed = false
352
+ try {
353
+ unsub?.()
354
+ } catch {
355
+ // ignore unsubscribe errors
356
+ }
357
+ }
358
+ }
359
+
360
+ function mount() {
361
+ if (!ctx?.on) return dispose
362
+
363
+ if (typeof ctx?.inject === 'function') {
364
+ const jobsFork = ctx.inject(['jobs'], (childCtx) => {
365
+ const cleanup = attachJobsService(childCtx?.jobs)
366
+ if (cleanup) childCtx.effect(() => cleanup, 'tavlo-hooks: jobs events')
367
+ })
368
+ if (typeof jobsFork?.dispose === 'function') {
369
+ disposers.push(() => {
370
+ jobsServiceSubscribed = false
371
+ return jobsFork.dispose()
372
+ })
373
+ }
374
+ } else {
375
+ const jobsCleanup = attachJobsService(ctx?.get?.('jobs'))
376
+ if (jobsCleanup) disposers.push(jobsCleanup)
377
+ }
378
+
379
+ listen('agent/status', ({ agent, status } = {}) => {
380
+ if (status === 'running') {
381
+ const sid = agent?.id ?? agent?.session?.id
382
+ if (sid) cancelPendingTurnCompleted(sid, 'agent-running')
383
+ }
384
+ })
385
+
386
+ // 1. Waterfall listeners: MUST prepend, run side effects async, and IMMEDIATELY return next()
387
+ listen(
388
+ 'approval/request',
389
+ (req, next) => {
390
+ try {
391
+ safeAsync('approval/request', async () => {
392
+ const session = req?.agent?.session
393
+ const sessionId = session?.id
394
+ const callId = req?.callId ? String(req.callId) : undefined
395
+ const toolName = req?.toolName ? String(req.toolName) : 'tool'
396
+ const dedupKey = callId ? `approval:${callId}` : undefined
397
+ if (!claimDedup(dedupKey)) return
398
+ rememberSessionMeta(sessionId, { cwd: session?.header?.cwd })
399
+ const reasonText =
400
+ req?.displayReason?.zh || req?.displayReason?.en || req?.reason || ''
401
+ const summary = reasonText
402
+ ? `${toolName}: ${reasonText}`
403
+ : `工具 ${toolName} 需要您的审批`
404
+ if (req?.signal && callId) {
405
+ req.signal.addEventListener(
406
+ 'abort',
407
+ () => {
408
+ dispatcher.dismissApproval?.(callId)
409
+ },
410
+ { once: true },
411
+ )
412
+ }
413
+ await triggerMountPoint('approval.request', {
414
+ sessionId,
415
+ cwd: session?.header?.cwd,
416
+ toolName,
417
+ reason: reasonText,
418
+ approvalId: callId,
419
+ summary,
420
+ })
421
+ })
422
+ } catch {
423
+ // Never block approval waterfall
424
+ }
425
+ return next()
426
+ },
427
+ { prepend: true, global: true },
428
+ )
429
+
430
+ listen(
431
+ 'user-questions/request',
432
+ (request, next) => {
433
+ try {
434
+ safeAsync('user-questions/request', async () => {
435
+ const session = request?.agent?.session
436
+ const sessionId = session?.id
437
+ const callId = request?.wait?.callId ? String(request.wait.callId) : undefined
438
+ rememberSessionMeta(sessionId, { cwd: session?.header?.cwd })
439
+ const firstQuestion = Array.isArray(request?.questions) ? request.questions[0] : null
440
+ const qText = firstQuestion?.header || firstQuestion?.question || 'Agent 需要您的确认或输入'
441
+ if (request?.signal && callId) {
442
+ request.signal.addEventListener(
443
+ 'abort',
444
+ () => {
445
+ dispatcher.dismissApproval?.(callId)
446
+ },
447
+ { once: true },
448
+ )
449
+ }
450
+ await triggerMountPoint('user.question', {
451
+ sessionId,
452
+ cwd: session?.header?.cwd,
453
+ approvalId: callId,
454
+ summary: qText,
455
+ })
456
+ })
457
+ } catch {
458
+ // Never block user-questions waterfall
459
+ }
460
+ return next()
461
+ },
462
+ { prepend: true, global: true },
463
+ )
464
+
465
+ listen(
466
+ 'tools/pre-execute',
467
+ (exec, next) => {
468
+ try {
469
+ safeAsync('tools/pre-execute', async () => {
470
+ const session = exec?.agent?.session
471
+ const sessionId = session?.id
472
+ const toolName = exec?.name ? String(exec.name) : 'tool'
473
+ rememberSessionMeta(sessionId, { cwd: session?.header?.cwd })
474
+ await triggerMountPoint('tool.pre', {
475
+ sessionId,
476
+ cwd: session?.header?.cwd,
477
+ toolName,
478
+ summary: `准备执行工具 ${toolName}`,
479
+ })
480
+ })
481
+ } catch {
482
+ // Never block tools/pre-execute waterfall
483
+ }
484
+ return next()
485
+ },
486
+ { prepend: true, global: true },
487
+ )
488
+
489
+ // 2. Tool results
490
+ listen('tools/result', (exec, result) => {
491
+ safeAsync('tools/result', async () => {
492
+ const session = exec?.agent?.session
493
+ const sessionId = session?.id
494
+ const toolName = exec?.name ? String(exec.name) : 'tool'
495
+ rememberSessionMeta(sessionId, { cwd: session?.header?.cwd })
496
+ if (result?.isError) {
497
+ const errCode = result?.error?.info?.code || 'tool-error'
498
+ await triggerMountPoint('tool.failure', {
499
+ sessionId,
500
+ cwd: session?.header?.cwd,
501
+ toolName,
502
+ reason: errCode,
503
+ summary: `工具 ${toolName} 执行失败 (${errCode})`,
504
+ })
505
+ } else {
506
+ await triggerMountPoint('tool.post', {
507
+ sessionId,
508
+ cwd: session?.header?.cwd,
509
+ toolName,
510
+ summary: `工具 ${toolName} 执行完成`,
511
+ })
512
+ }
513
+ })
514
+ })
515
+
516
+ // 3. Session & Agent lifecycle
517
+ listen('session/created', (session) => {
518
+ try {
519
+ const sessionId = session?.id
520
+ if (isSubagentSession(session)) {
521
+ if (sessionId) subagentSessionIds.add(sessionId)
522
+ return
523
+ }
524
+ safeAsync('session/created', async () => {
525
+ rememberSessionMeta(sessionId, { cwd: session?.header?.cwd })
526
+ if (!claimDedup(sessionId ? `session-start:${sessionId}` : undefined)) return
527
+ await triggerMountPoint('session.start', {
528
+ sessionId,
529
+ cwd: session?.header?.cwd,
530
+ summary: '新会话已创建',
531
+ })
532
+ })
533
+ } catch {
534
+ // Sync throw vetoes session creation; never throw here
535
+ }
536
+ })
537
+
538
+ listen('agent/created', ({ agent, source } = {}) => {
539
+ const session = agent?.session
540
+ const sessionId = session?.id
541
+ if (isSubagentSession(session)) {
542
+ if (sessionId) subagentSessionIds.add(sessionId)
543
+ return
544
+ }
545
+ safeAsync('agent/created', async () => {
546
+ rememberSessionMeta(sessionId, { cwd: session?.header?.cwd })
547
+ if (!claimDedup(sessionId ? `session-start:${sessionId}` : undefined)) return
548
+ await triggerMountPoint('session.start', {
549
+ sessionId,
550
+ cwd: session?.header?.cwd,
551
+ reason: source,
552
+ summary: source ? `会话已启动 (${source})` : '会话已启动',
553
+ })
554
+ })
555
+ })
556
+
557
+ listen('session/disposed', (session) => {
558
+ const sessionId = session?.id
559
+ const wasSubagent = isSubagentSession(session) || isSubagentById(sessionId)
560
+ if (sessionId) {
561
+ cancelPendingTurnCompleted(sessionId, 'session-disposed')
562
+ activeSubagentsByParent.delete(sessionId)
563
+ subagentSessionIds.delete(sessionId)
564
+ }
565
+ if (wasSubagent) {
566
+ if (sessionId) sessionMeta.delete(sessionId)
567
+ return
568
+ }
569
+ safeAsync('session/disposed', async () => {
570
+ if (!claimDedup(sessionId ? `session-end:${sessionId}` : undefined)) return
571
+ await triggerMountPoint('session.end', {
572
+ sessionId,
573
+ cwd: session?.header?.cwd,
574
+ summary: '会话已结束',
575
+ })
576
+ if (sessionId) sessionMeta.delete(sessionId)
577
+ })
578
+ })
579
+
580
+ listen('agent/disposed', ({ agent } = {}) => {
581
+ const session = agent?.session
582
+ const sessionId = session?.id
583
+ const wasSubagent = isSubagentSession(session) || isSubagentById(sessionId)
584
+ if (sessionId) {
585
+ cancelPendingTurnCompleted(sessionId, 'session-disposed')
586
+ activeSubagentsByParent.delete(sessionId)
587
+ subagentSessionIds.delete(sessionId)
588
+ }
589
+ if (wasSubagent) {
590
+ if (sessionId) sessionMeta.delete(sessionId)
591
+ return
592
+ }
593
+ safeAsync('agent/disposed', async () => {
594
+ if (!claimDedup(sessionId ? `session-end:${sessionId}` : undefined)) return
595
+ await triggerMountPoint('session.end', {
596
+ sessionId,
597
+ cwd: session?.header?.cwd,
598
+ summary: 'Agent 已释放',
599
+ })
600
+ if (sessionId) sessionMeta.delete(sessionId)
601
+ })
602
+ })
603
+
604
+ listen('agent/error', ({ agent, turn, error } = {}) => {
605
+ const session = agent?.session
606
+ const sessionId = session?.id
607
+ if (isSubagentSession(session) || isSubagentById(sessionId)) return
608
+ safeAsync('agent/error', async () => {
609
+ rememberSessionMeta(sessionId, { cwd: session?.header?.cwd })
610
+ if (!claimDedup(sessionId ? `turn-failed:${sessionId}:${turn ?? ''}` : undefined)) return
611
+ const code = error?.code || error?.name || 'agent-error'
612
+ await triggerMountPoint('turn.failed', {
613
+ sessionId,
614
+ cwd: session?.header?.cwd,
615
+ turn: typeof turn === 'number' ? turn : undefined,
616
+ reason: String(code),
617
+ summary: `执行出错 (${code})`,
618
+ })
619
+ })
620
+ })
621
+
622
+ listen('agent-loop/config-start-failed', ({ sessionId, error } = {}) => {
623
+ safeAsync('agent-loop/config-start-failed', async () => {
624
+ const code = error?.code || error?.name || 'config-start-failed'
625
+ await triggerMountPoint('turn.failed', {
626
+ sessionId,
627
+ reason: String(code),
628
+ summary: `会话启动配置失败 (${code})`,
629
+ })
630
+ })
631
+ })
632
+
633
+ // 4. Session event stream (turn/start, turn/end, approval/*, job/settled, compaction/end, session/title)
634
+ listen('session/event', (session, event) => {
635
+ const sessionId = session?.id
636
+ if (!event || typeof event !== 'object') return
637
+
638
+ const subagent = isSubagentSession(session) || isSubagentById(sessionId)
639
+ if (subagent && sessionId) subagentSessionIds.add(sessionId)
640
+
641
+ if (event.type === 'turn/start' && !subagent && sessionId) {
642
+ cancelPendingTurnCompleted(sessionId, 'next-turn-started')
643
+ }
644
+
645
+ safeAsync('session/event', async () => {
646
+ rememberSessionMeta(sessionId, { cwd: session?.header?.cwd })
647
+
648
+ if (event.type === 'session/title' && typeof event.data?.title === 'string') {
649
+ rememberSessionMeta(sessionId, { title: event.data.title })
650
+ return
651
+ }
652
+
653
+ if (event.type === 'approval/asked') {
654
+ const approvalId = event.data?.id ? String(event.data.id) : undefined
655
+ const callId = event.data?.callId ? String(event.data.callId) : undefined
656
+ if (approvalId && callId) approvalCallIds.set(approvalId, callId)
657
+ if (callId && !claimDedup(`approval:${callId}`)) return
658
+ const toolName = event.data?.toolName ? String(event.data.toolName) : 'tool'
659
+ await triggerMountPoint('approval.request', {
660
+ sessionId,
661
+ cwd: session?.header?.cwd,
662
+ toolName,
663
+ reason: event.data?.reason,
664
+ approvalId: approvalId ?? callId,
665
+ summary: event.data?.reason ? `${toolName}: ${event.data.reason}` : `工具 ${toolName} 等待审批`,
666
+ })
667
+ return
668
+ }
669
+
670
+ if (event.type === 'approval/decided') {
671
+ const approvalId = event.data?.id ? String(event.data.id) : undefined
672
+ if (approvalId) {
673
+ dispatcher.dismissApproval?.(approvalId)
674
+ const mappedCallId = approvalCallIds.get(approvalId)
675
+ if (mappedCallId) {
676
+ approvalCallIds.delete(approvalId)
677
+ dispatcher.dismissApproval?.(mappedCallId)
678
+ }
679
+ }
680
+ return
681
+ }
682
+
683
+ if (subagent) return
684
+
685
+ if (event.type === 'turn/start') {
686
+ await triggerMountPoint('turn.start', {
687
+ sessionId,
688
+ cwd: session?.header?.cwd,
689
+ turn: typeof event.data?.turn === 'number' ? event.data.turn : undefined,
690
+ summary: `第 ${event.data?.turn ?? ''} 轮开始执行`.trim(),
691
+ })
692
+ return
693
+ }
694
+
695
+ if (event.type === 'turn/end') {
696
+ const turn = typeof event.data?.turn === 'number' ? event.data.turn : undefined
697
+ const kind = event.data?.reason?.kind
698
+ if (kind === 'completed') {
699
+ const skipReason = getTurnContinueReason(sessionId, session)
700
+ if (skipReason) {
701
+ recordDiagnostic('skip', {
702
+ mountPointId: 'turn.completed',
703
+ sessionId: sessionId ?? null,
704
+ turn: turn ?? null,
705
+ reason: skipReason,
706
+ summary: `Skipped turn.completed (${skipReason})`,
707
+ })
708
+ return
709
+ }
710
+
711
+ const cwd = session?.header?.cwd
712
+ const fireCompleted = async () => {
713
+ if (disposed) return
714
+ const liveAgent = resolveLiveAgent(sessionId)
715
+ if (liveAgent?.status === 'running') {
716
+ recordDiagnostic('skip', {
717
+ mountPointId: 'turn.completed',
718
+ sessionId: sessionId ?? null,
719
+ turn: turn ?? null,
720
+ reason: 'agent-running',
721
+ summary: 'Skipped turn.completed (agent-running)',
722
+ })
723
+ return
724
+ }
725
+ const lateSkip = getTurnContinueReason(sessionId, session)
726
+ if (lateSkip) {
727
+ recordDiagnostic('skip', {
728
+ mountPointId: 'turn.completed',
729
+ sessionId: sessionId ?? null,
730
+ turn: turn ?? null,
731
+ reason: lateSkip,
732
+ summary: `Skipped turn.completed (${lateSkip})`,
733
+ })
734
+ return
735
+ }
736
+ const goal = getLiveGoal(liveAgent)
737
+ await triggerMountPoint('turn.completed', {
738
+ sessionId,
739
+ cwd,
740
+ turn,
741
+ goalPhase: goal?.phase,
742
+ reason: goal?.phase === 'complete' ? 'goal-completed' : 'completed',
743
+ summary: goal?.phase === 'complete' ? '目标任务已完成' : '当前回合已完成',
744
+ })
745
+ }
746
+
747
+ if (sessionId && turnCompleteDebounceMs > 0) {
748
+ cancelPendingTurnCompleted(sessionId, 'superseded')
749
+ const timer = setTimeout(() => {
750
+ pendingTurnCompleted.delete(sessionId)
751
+ safeAsync('turn/end:debounced', fireCompleted)
752
+ }, turnCompleteDebounceMs)
753
+ timer.unref?.()
754
+ pendingTurnCompleted.set(sessionId, { timer, turn })
755
+ } else {
756
+ await fireCompleted()
757
+ }
758
+ } else if (kind === 'error') {
759
+ if (sessionId) cancelPendingTurnCompleted(sessionId, 'turn-error')
760
+ if (!claimDedup(sessionId ? `turn-failed:${sessionId}:${event.data?.turn ?? ''}` : undefined)) return
761
+ const errCode = event.data?.reason?.error?.code || 'error'
762
+ await triggerMountPoint('turn.failed', {
763
+ sessionId,
764
+ cwd: session?.header?.cwd,
765
+ turn,
766
+ reason: String(errCode),
767
+ summary: `回合执行失败 (${errCode})`,
768
+ })
769
+ } else if (kind === 'blocked' || kind === 'max-tokens' || kind === 'aborted' || kind === 'interrupted') {
770
+ if (sessionId) cancelPendingTurnCompleted(sessionId, `turn-${kind}`)
771
+ await triggerMountPoint('turn.attention', {
772
+ sessionId,
773
+ cwd: session?.header?.cwd,
774
+ turn,
775
+ reason: kind,
776
+ summary: `回合因 ${kind} 暂停,请查看`,
777
+ })
778
+ }
779
+ return
780
+ }
781
+
782
+ if (event.type === 'job/settled') {
783
+ if (jobsServiceSubscribed) return
784
+ if (event.data?.awaited === true || event.data?.cause === 'teardown') return
785
+ const jobId = event.data?.jobId ? String(event.data.jobId) : undefined
786
+ if (jobId && !claimDedup(`job-settled:${jobId}`)) return
787
+ const status = event.data?.status || 'completed'
788
+ const label = event.data?.label ? sanitizeSummaryText(event.data.label, 64) : '后台任务'
789
+ await triggerMountPoint('job.settled', {
790
+ sessionId,
791
+ cwd: session?.header?.cwd,
792
+ reason: status,
793
+ summary: `后台任务「${label}」已结束 (${status})`,
794
+ })
795
+ return
796
+ }
797
+
798
+ if (event.type === 'compaction/end') {
799
+ const hasError = Boolean(event.data?.error)
800
+ await triggerMountPoint('compaction.end', {
801
+ sessionId,
802
+ cwd: session?.header?.cwd,
803
+ reason: hasError ? 'error' : 'completed',
804
+ summary: hasError ? '上下文压缩出现异常' : '上下文压缩已完成',
805
+ })
806
+ }
807
+ })
808
+ })
809
+
810
+ // 5. Subsystems: subagent, workflow, goal, account
811
+ listen('subagent/start', (info) => {
812
+ if (typeof info?.id === 'string' && info.id) {
813
+ subagentSessionIds.add(info.id)
814
+ }
815
+ const parentId = typeof info?.parentSessionId === 'string' && info.parentSessionId ? info.parentSessionId : undefined
816
+ const childKey = typeof info?.runId === 'string' && info.runId
817
+ ? info.runId
818
+ : typeof info?.id === 'string' && info.id
819
+ ? info.id
820
+ : undefined
821
+ if (parentId && childKey) {
822
+ let activeSet = activeSubagentsByParent.get(parentId)
823
+ if (!activeSet) {
824
+ activeSet = new Set()
825
+ activeSubagentsByParent.set(parentId, activeSet)
826
+ }
827
+ activeSet.add(childKey)
828
+ }
829
+ safeAsync('subagent/start', async () => {
830
+ await triggerMountPoint('subagent.start', {
831
+ sessionId: parentId,
832
+ summary: '子 Agent 已启动',
833
+ })
834
+ })
835
+ })
836
+
837
+ listen('subagent/end', (info) => {
838
+ const parentId = typeof info?.parentSessionId === 'string' && info.parentSessionId ? info.parentSessionId : undefined
839
+ const childKey = typeof info?.runId === 'string' && info.runId
840
+ ? info.runId
841
+ : typeof info?.id === 'string' && info.id
842
+ ? info.id
843
+ : undefined
844
+ if (parentId && childKey) {
845
+ const activeSet = activeSubagentsByParent.get(parentId)
846
+ if (activeSet) {
847
+ activeSet.delete(childKey)
848
+ if (activeSet.size === 0) activeSubagentsByParent.delete(parentId)
849
+ }
850
+ }
851
+ safeAsync('subagent/end', async () => {
852
+ await triggerMountPoint('subagent.end', {
853
+ sessionId: parentId,
854
+ reason: info?.stopReason,
855
+ summary: info?.stopReason ? `子 Agent 已结束 (${info.stopReason})` : '子 Agent 已完成',
856
+ })
857
+ })
858
+ })
859
+
860
+ listen('workflow/start', (info) => {
861
+ safeAsync('workflow/start', async () => {
862
+ const wfName = info?.meta?.name ? sanitizeSummaryText(info.meta.name, 64) : ''
863
+ await triggerMountPoint('workflow.start', {
864
+ summary: wfName ? `工作流 ${wfName} 已启动` : '工作流已启动',
865
+ })
866
+ })
867
+ })
868
+
869
+ listen('workflow/end', (info, result) => {
870
+ safeAsync('workflow/end', async () => {
871
+ const wfName = info?.meta?.name ? sanitizeSummaryText(info.meta.name, 64) : ''
872
+ const reason = result?.stopReason || 'completed'
873
+ await triggerMountPoint('workflow.end', {
874
+ reason,
875
+ summary: wfName ? `工作流 ${wfName} 已结束 (${reason})` : `工作流已结束 (${reason})`,
876
+ })
877
+ })
878
+ })
879
+
880
+ listen('goal/changed', ({ agent } = {}) => {
881
+ safeAsync('goal/changed', async () => {
882
+ const session = agent?.session
883
+ await triggerMountPoint('goal.changed', {
884
+ sessionId: session?.id,
885
+ cwd: session?.header?.cwd,
886
+ summary: '目标状态已变更',
887
+ })
888
+ })
889
+ })
890
+
891
+ listen('goal/activation-changed', (payload) => {
892
+ safeAsync('goal/activation-changed', async () => {
893
+ await triggerMountPoint('goal.changed', {
894
+ sessionId: payload?.sessionId,
895
+ summary: '目标激活状态已变更',
896
+ })
897
+ })
898
+ })
899
+
900
+ listen('deepseek-account/session-expired', () => {
901
+ safeAsync('deepseek-account/session-expired', async () => {
902
+ await triggerMountPoint('account.attention', {
903
+ reason: 'session-expired',
904
+ summary: 'DeepSeek 账号会话已过期,请重新登录',
905
+ })
906
+ })
907
+ })
908
+
909
+ const onModelSignIn = () => {
910
+ safeAsync('deepseek-account/model-sign-in-required', async () => {
911
+ await triggerMountPoint('account.attention', {
912
+ reason: 'model-sign-in-required',
913
+ summary: '当前模型需要账号登录后继续使用',
914
+ })
915
+ })
916
+ }
917
+ listen('deepseek-account/model-sign-in-required', onModelSignIn)
918
+ listen('model-sign-in-required', onModelSignIn)
919
+
920
+ return dispose
921
+ }
922
+
923
+ function dispose() {
924
+ disposed = true
925
+ jobsServiceSubscribed = false
926
+ for (const pending of pendingTurnCompleted.values()) {
927
+ clearTimeout(pending.timer)
928
+ }
929
+ pendingTurnCompleted.clear()
930
+ while (disposers.length > 0) {
931
+ const fn = disposers.pop()
932
+ try {
933
+ fn?.()
934
+ } catch {
935
+ // ignore disposer errors
936
+ }
937
+ }
938
+ sessionMeta.clear()
939
+ recentKeys.clear()
940
+ approvalCallIds.clear()
941
+ subagentSessionIds.clear()
942
+ activeSubagentsByParent.clear()
943
+ }
944
+
945
+ async function testMountPoint(mountPointId) {
946
+ const mpDef = getMountPoint(mountPointId)
947
+ if (!mpDef) {
948
+ throw new Error(`Unknown mount point: ${mountPointId}`)
949
+ }
950
+ return triggerMountPoint(
951
+ mountPointId,
952
+ {
953
+ projectName: 'demo-project',
954
+ toolName: mpDef.supportsMatcher ? 'bash' : undefined,
955
+ reason: 'test-trigger',
956
+ summary: `测试触发挂载点:${mpDef.nameZh}`,
957
+ },
958
+ { force: true },
959
+ )
960
+ }
961
+
962
+ async function testScript(mountPointId, scriptId) {
963
+ const mpDef = getMountPoint(mountPointId)
964
+ if (!mpDef) {
965
+ throw new Error(`Unknown mount point: ${mountPointId}`)
966
+ }
967
+ const { config } = configStore.getSnapshot()
968
+ const script = config.mountPoints?.[mountPointId]?.scripts?.find((s) => s.id === scriptId)
969
+ if (!script) {
970
+ throw new Error(`Unknown script: ${scriptId}`)
971
+ }
972
+ const entry = await scriptRunner.executeScript(
973
+ script,
974
+ {
975
+ eventId: randomUUID(),
976
+ hookPoint: mountPointId,
977
+ category: mpDef.category,
978
+ timestamp: new Date(now()).toISOString(),
979
+ projectName: 'demo-project',
980
+ toolName: mpDef.supportsMatcher ? 'bash' : undefined,
981
+ reason: 'script-test',
982
+ summary: `测试运行脚本:${script.name}`,
983
+ },
984
+ { dryRun: true },
985
+ )
986
+ return {
987
+ ...entry,
988
+ logs: scriptRunner.getLogs(),
989
+ }
990
+ }
991
+
992
+ return {
993
+ mount,
994
+ dispose,
995
+ triggerMountPoint,
996
+ testMountPoint,
997
+ testScript,
998
+ }
999
+ }