@xi4z/dsh-utils-notify 0.0.0-stage → 0.7.0

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/src/index.ts ADDED
@@ -0,0 +1,1126 @@
1
+ /**
2
+ * `dsh-utils` notify component: push a message through a Gotify gateway when a
3
+ * session finishes a turn, or when the agent is blocked on an approval or a
4
+ * question.
5
+ *
6
+ * The gateway is addressed by URL, so the component works from any machine that
7
+ * can reach it over the internet: one device token, one app token, no local
8
+ * NapCat/OneBot service required. Every message carries the sending device's
9
+ * name so multiple machines sharing one gateway stay distinguishable.
10
+ *
11
+ * Wiring (all read from the session log, never from a waterfall the root
12
+ * context cannot receive):
13
+ *
14
+ * session/event -> accumulate the finished turn's reason + final assistant text
15
+ * agent/status -> the idle edge is the moment the whole task is done
16
+ * tool/call -> ask_user_question / exit_plan_mode is the "parked waiting
17
+ * for a human" signal, debounced; tool/result cancels it
18
+ * approval/asked -> the agent is blocked on a yes/no decision, debounced;
19
+ * approval/decided (auto-decided) cancels it
20
+ *
21
+ * Delivery is plain `fetch` to `POST {gotifyUrl}/message`; no WebSocket, no
22
+ * heartbeat, no extra dependency. The legacy OneBot path is kept for
23
+ * compatibility but Gotify is the default outlet.
24
+ *
25
+ * The bundle mounts this component under the entry id `dsh-notify`
26
+ * (`dsh-utils/notify`); that entry id is also its settings namespace, so the
27
+ * browser half renders a live configuration page for it. Every Config field is
28
+ * volatile: the component re-reads the values on each event, so a save in the
29
+ * settings page takes effect without a restart.
30
+ *
31
+ * Ported from `@local/dsh-plugin-qq-notify` 0.2.0 — same message
32
+ * templates, same environment overrides (`DSH_QQ_NOTIFY_*`), same delivery
33
+ * semantics — with the settings schema, live config reads, and the
34
+ * `dsh-utils` bundle wiring added.
35
+ *
36
+ * @module dsh-utils/notify
37
+ */
38
+
39
+ import { appendFileSync } from 'node:fs'
40
+ import { hostname } from 'node:os'
41
+ import type { Context } from '@deepseek-ai/cordis'
42
+ import type {} from '@deepseek-ai/dsh-agent'
43
+ import z from '@deepseek-ai/schemastery'
44
+
45
+ export const name = 'dsh-notify'
46
+ export const inject = ['agents']
47
+
48
+ /** Turn-end reasons a deployment may subscribe to. */
49
+ export const NOTIFY_REASONS = ['completed', 'error', 'aborted', 'blocked'] as const
50
+ export type NotifyReason = (typeof NOTIFY_REASONS)[number]
51
+
52
+ /** One delivery target: an independent gateway credential / series. */
53
+ export interface NotifyTarget {
54
+ readonly name: string
55
+ readonly url: string
56
+ readonly token: string
57
+ readonly priority: number
58
+ readonly devices: readonly string[]
59
+ }
60
+
61
+ /** Defaults applied when a Config field or an environment override is absent. */
62
+ const DEFAULTS = {
63
+ enabled: true,
64
+ /** 'gotify' = 统一网关(每个系列一把 token,公网可达);'onebot' = 历史直连,保留兼容。 */
65
+ transport: 'gotify',
66
+ endpoint: 'http://127.0.0.1:3000',
67
+ token: '',
68
+ targetType: 'private',
69
+ targetId: '',
70
+ /** transport=gotify 时使用;targets 非空时作为默认目标的兜底。 */
71
+ gotifyUrl: '',
72
+ gotifyToken: '',
73
+ gotifyPriority: 3,
74
+ /** 追加到每个 Gotify 请求上的头(反代 Basic Auth、自定义路由等)。 */
75
+ gotifyHeaders: {} as Record<string, string>,
76
+ /** 多目标:每个目标是一把独立的网关凭据/系列;devices 非空时只有命中的设备才投递。 */
77
+ targets: [] as readonly NotifyTarget[],
78
+ /** 设备标识:默认取主机名;deviceLabel 是给人看的名字(默认同 deviceName)。 */
79
+ deviceName: '',
80
+ deviceLabel: '',
81
+ /** 是否把设备名加到 Gotify 标题前缀(正文本就能带 {device})。 */
82
+ deviceInTitle: false,
83
+ notifyOnReasons: ['completed', 'error', 'aborted'] as readonly NotifyReason[],
84
+ notifyOnApproval: true,
85
+ notifyOnQuestion: true,
86
+ /** 提问/审批先等这么久;期间若拿到结果(人已在 UI 回答/策略已自动裁决)就取消推送。 */
87
+ questionDelayMs: 2500,
88
+ approvalDelayMs: 3000,
89
+ includeSubagents: false,
90
+ summaryChars: 120,
91
+ timeoutMs: 8000,
92
+ /** 默认只记日志不发消息:确认配置无误后再关。 */
93
+ dryRun: true,
94
+ traceFile: '',
95
+ /** Mustache-lite message templates; empty means the built-in default. */
96
+ template: '',
97
+ approvalTemplate: '',
98
+ questionTemplate: '',
99
+ } as const
100
+
101
+ /** Environment overrides, so a deployment can inject secrets without editing the patch. */
102
+ const ENV = {
103
+ endpoint: 'DSH_QQ_NOTIFY_URL',
104
+ token: 'DSH_QQ_NOTIFY_TOKEN',
105
+ targetType: 'DSH_QQ_NOTIFY_TARGET_TYPE',
106
+ targetId: 'DSH_QQ_NOTIFY_TARGET_ID',
107
+ gotifyUrl: 'DSH_QQ_NOTIFY_GOTIFY_URL',
108
+ gotifyToken: 'DSH_QQ_NOTIFY_GOTIFY_TOKEN',
109
+ deviceName: 'DSH_QQ_NOTIFY_DEVICE',
110
+ deviceLabel: 'DSH_QQ_NOTIFY_DEVICE_LABEL',
111
+ targets: 'DSH_QQ_NOTIFY_TARGETS',
112
+ gotifyHeaders: 'DSH_QQ_NOTIFY_GOTIFY_HEADERS',
113
+ } as const
114
+
115
+ /** Values that must be parsed as JSON when they come from the environment. */
116
+ const ENV_JSON: ReadonlySet<string> = new Set(['targets', 'gotifyHeaders'])
117
+
118
+ /**
119
+ * Settings-page schema. Every key is volatile: the Loader hands `apply` live
120
+ * references and the component re-reads them on use, so the configuration page
121
+ * writes take effect immediately.
122
+ */
123
+ export const Config = z.object({
124
+ enabled: z.boolean().default(DEFAULTS.enabled).description('Master switch for this device.').volatile(),
125
+ transport: z.union(['gotify', 'onebot']).default(DEFAULTS.transport).description('Delivery outlet; onebot is legacy.').volatile(),
126
+ endpoint: z.string().default(DEFAULTS.endpoint).description('Legacy OneBot HTTP endpoint.').volatile(),
127
+ token: z.string().default(DEFAULTS.token).description('Legacy OneBot access token.').volatile(),
128
+ targetType: z.union(['private', 'group']).default(DEFAULTS.targetType).description('Legacy OneBot recipient kind.').volatile(),
129
+ targetId: z.string().default(DEFAULTS.targetId).description('Legacy OneBot recipient id.').volatile(),
130
+ gotifyUrl: z.string().default(DEFAULTS.gotifyUrl).description('Gotify gateway base URL.').volatile(),
131
+ gotifyToken: z.string().default(DEFAULTS.gotifyToken).description('Gotify application token; supports ${ENV} references.').volatile(),
132
+ gotifyPriority: z.natural().default(DEFAULTS.gotifyPriority).description('Default message priority.').volatile(),
133
+ gotifyHeaders: z.any().default({}).description('Extra request headers for the gateway.').volatile(),
134
+ targets: z.any().default([]).description('Multiple gateway targets; supports ${ENV} in url/token and urlEnv/tokenEnv.').volatile(),
135
+ deviceName: z.string().default(DEFAULTS.deviceName).description('Device identity; empty = hostname.').volatile(),
136
+ deviceLabel: z.string().default(DEFAULTS.deviceLabel).description('Human-readable device name for {device}.').volatile(),
137
+ deviceInTitle: z.boolean().default(DEFAULTS.deviceInTitle).description('Prefix the Gotify title with the device label.').volatile(),
138
+ notifyOnReasons: z.array(z.union(NOTIFY_REASONS)).default([...DEFAULTS.notifyOnReasons]).description('Turn-end reasons that notify.').volatile(),
139
+ notifyOnApproval: z.boolean().default(DEFAULTS.notifyOnApproval).description('Notify when an approval decision is pending.').volatile(),
140
+ notifyOnQuestion: z.boolean().default(DEFAULTS.notifyOnQuestion).description('Notify when a question is waiting for you.').volatile(),
141
+ questionDelayMs: z.natural().default(DEFAULTS.questionDelayMs).description('Question debounce; an answer inside it suppresses the push.').volatile(),
142
+ approvalDelayMs: z.natural().default(DEFAULTS.approvalDelayMs).description('Approval debounce; an automatic decision inside it suppresses the push.').volatile(),
143
+ includeSubagents: z.boolean().default(DEFAULTS.includeSubagents).description('Also notify sessions that are not roots.').volatile(),
144
+ summaryChars: z.natural().default(DEFAULTS.summaryChars).description('Plain-text budget for {reply}.').volatile(),
145
+ timeoutMs: z.natural().min(100).default(DEFAULTS.timeoutMs).description('Single HTTP timeout; one retry follows.').volatile(),
146
+ dryRun: z.boolean().default(DEFAULTS.dryRun).description('Log the payload instead of sending it.').volatile(),
147
+ traceFile: z.string().default(DEFAULTS.traceFile).description('Optional JSONL diagnostics file.').volatile(),
148
+ template: z.string().default(DEFAULTS.template).description('Turn-end message template; empty = built-in default.').volatile(),
149
+ questionTemplate: z.string().default(DEFAULTS.questionTemplate).description('Question message template; empty = built-in default.').volatile(),
150
+ approvalTemplate: z.string().default(DEFAULTS.approvalTemplate).description('Approval message template; empty = built-in default.').volatile(),
151
+ })
152
+
153
+ /** Volatile Config fields arrive as live references; `.get()` snapshots. */
154
+ interface VolatileRef<T> {
155
+ get(): T
156
+ }
157
+
158
+ /** One setting as the Loader supplies it: a live reference, or a plain value in tests. */
159
+ type MaybeRef<T> = T | VolatileRef<T>
160
+
161
+ /** The runtime shape `apply` receives (every field volatile, every field optional). */
162
+ export interface NotifyConfig {
163
+ readonly enabled?: MaybeRef<boolean>
164
+ readonly transport?: MaybeRef<string>
165
+ readonly endpoint?: MaybeRef<string>
166
+ readonly token?: MaybeRef<string>
167
+ readonly targetType?: MaybeRef<string>
168
+ readonly targetId?: MaybeRef<string>
169
+ readonly gotifyUrl?: MaybeRef<string>
170
+ readonly gotifyToken?: MaybeRef<string>
171
+ readonly gotifyPriority?: MaybeRef<number>
172
+ readonly gotifyHeaders?: MaybeRef<unknown>
173
+ readonly targets?: MaybeRef<unknown>
174
+ readonly deviceName?: MaybeRef<string>
175
+ readonly deviceLabel?: MaybeRef<string>
176
+ readonly deviceInTitle?: MaybeRef<boolean>
177
+ readonly notifyOnReasons?: MaybeRef<readonly string[]>
178
+ readonly notifyOnApproval?: MaybeRef<boolean>
179
+ readonly notifyOnQuestion?: MaybeRef<boolean>
180
+ readonly questionDelayMs?: MaybeRef<number>
181
+ readonly approvalDelayMs?: MaybeRef<number>
182
+ readonly includeSubagents?: MaybeRef<boolean>
183
+ readonly summaryChars?: MaybeRef<number>
184
+ readonly timeoutMs?: MaybeRef<number>
185
+ readonly dryRun?: MaybeRef<boolean>
186
+ readonly traceFile?: MaybeRef<string>
187
+ readonly template?: MaybeRef<string>
188
+ readonly questionTemplate?: MaybeRef<string>
189
+ readonly approvalTemplate?: MaybeRef<string>
190
+ }
191
+
192
+ /** Normalized options with every default applied. */
193
+ interface Options {
194
+ enabled: boolean
195
+ transport: 'gotify' | 'onebot'
196
+ endpoint: string
197
+ token: string
198
+ targetType: 'private' | 'group'
199
+ targetId: string
200
+ gotifyUrl: string
201
+ gotifyToken: string
202
+ gotifyPriority: number
203
+ gotifyHeaders: Readonly<Record<string, string>>
204
+ targets: readonly NotifyTarget[]
205
+ deviceName: string
206
+ deviceLabel: string
207
+ deviceInTitle: boolean
208
+ notifyOnReasons: readonly NotifyReason[]
209
+ notifyOnApproval: boolean
210
+ notifyOnQuestion: boolean
211
+ questionDelayMs: number
212
+ approvalDelayMs: number
213
+ includeSubagents: boolean
214
+ summaryChars: number
215
+ timeoutMs: number
216
+ dryRun: boolean
217
+ traceFile: string
218
+ template: string
219
+ questionTemplate: string
220
+ approvalTemplate: string
221
+ }
222
+
223
+ /** Reading a Loader volatile reference, or a plain value, as one concrete value. */
224
+ function unwrap<T>(value: MaybeRef<T> | undefined): T | undefined {
225
+ if (value !== null && typeof value === 'object' && typeof (value as VolatileRef<T>).get === 'function') {
226
+ return (value as VolatileRef<T>).get()
227
+ }
228
+ return value as T | undefined
229
+ }
230
+
231
+ /** A trimmed non-empty string, or the fallback. */
232
+ function str(value: unknown, fallback = ''): string {
233
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback
234
+ }
235
+
236
+ /** A string that preserves its own whitespace (templates). */
237
+ function text(value: unknown, fallback = ''): string {
238
+ return typeof value === 'string' ? value : fallback
239
+ }
240
+
241
+ /** Read one environment variable, trimmed; unset or blank yields ''. */
242
+ function envValue(name: string): string {
243
+ const found = process.env[name]
244
+ return typeof found === 'string' ? found.trim() : ''
245
+ }
246
+
247
+ /**
248
+ * Expand `${NAME}` and `${NAME:-fallback}` references against the process
249
+ * environment, so a deployment can keep gateway secrets outside the patch file.
250
+ * An unset or blank variable expands to the fallback (or to ''), leaving the
251
+ * target without a token instead of sending the literal reference.
252
+ */
253
+ export function expandEnv(value: unknown): string {
254
+ return String(value ?? '').replace(/\${([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?}/g, (_whole, name: string, fallback?: string) => {
255
+ const found = envValue(name)
256
+ return found !== '' ? found : (fallback ?? '')
257
+ })
258
+ }
259
+
260
+ /** A finite number at or above `minimum`, or the fallback. */
261
+ function num(value: unknown, fallback: number, minimum = 0): number {
262
+ const parsed = Number(value)
263
+ return Number.isFinite(parsed) && parsed >= minimum ? parsed : fallback
264
+ }
265
+
266
+ /** A boolean, accepting the YAML/env spellings `'true'` / `'false'`. */
267
+ function bool(value: unknown, fallback: boolean): boolean {
268
+ if (typeof value === 'boolean') return value
269
+ if (value === 'true') return true
270
+ if (value === 'false') return false
271
+ return fallback
272
+ }
273
+
274
+ /** The OS hostname, or 'unknown' when the platform refuses. */
275
+ function safeHostname(): string {
276
+ try {
277
+ return hostname() || 'unknown'
278
+ } catch {
279
+ return 'unknown'
280
+ }
281
+ }
282
+
283
+ /** Keep only string/number request headers; ignore everything else. */
284
+ export function normalizeHeaders(raw: unknown): Record<string, string> {
285
+ const out: Record<string, string> = {}
286
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out
287
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
288
+ if (typeof key !== 'string' || key.trim() === '') continue
289
+ if (typeof value !== 'string' && typeof value !== 'number') continue
290
+ out[key.trim()] = expandEnv(value)
291
+ }
292
+ return out
293
+ }
294
+
295
+ /**
296
+ * Normalize `targets` into a predictable list; bad entries are dropped.
297
+ * A target with only one of url/token is kept so delivery can warn about the
298
+ * exact target name instead of silently disappearing.
299
+ */
300
+ export function normalizeTargets(raw: unknown, fallbackPriority = 3): NotifyTarget[] {
301
+ if (!Array.isArray(raw)) return []
302
+ const out: NotifyTarget[] = []
303
+ for (const entry of raw) {
304
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
305
+ const record = entry as Record<string, unknown>
306
+ let url = typeof record.url === 'string' ? expandEnv(record.url).trim() : ''
307
+ let token = typeof record.token === 'string' ? expandEnv(record.token).trim() : ''
308
+ // `urlEnv` / `tokenEnv` name the variable outright; they win over the
309
+ // literal reference form and keep per-target secrets out of the patch file.
310
+ if (typeof record.urlEnv === 'string' && record.urlEnv.trim() !== '') url = envValue(record.urlEnv.trim())
311
+ if (typeof record.tokenEnv === 'string' && record.tokenEnv.trim() !== '') token = envValue(record.tokenEnv.trim())
312
+ if (!url && !token) continue
313
+ out.push({
314
+ name: typeof record.name === 'string' && record.name.trim() !== ''
315
+ ? record.name.trim()
316
+ : `target-${out.length + 1}`,
317
+ url,
318
+ token,
319
+ priority: Number.isFinite(record.priority) ? Number(record.priority) : fallbackPriority,
320
+ devices: Array.isArray(record.devices)
321
+ ? record.devices.filter((device): device is string => typeof device === 'string' && device.trim() !== '').map((device) => device.trim())
322
+ : [],
323
+ })
324
+ }
325
+ return out
326
+ }
327
+
328
+ /** A target with no `devices` list applies everywhere; otherwise match name or label. */
329
+ export function targetMatchesDevice(target: NotifyTarget, cfg: Pick<Options, 'deviceName' | 'deviceLabel'>): boolean {
330
+ if (!target || !Array.isArray(target.devices) || target.devices.length === 0) return true
331
+ return target.devices.includes(cfg.deviceName) || target.devices.includes(cfg.deviceLabel)
332
+ }
333
+
334
+ /**
335
+ * Resolve the live Config into one concrete option set: defaults, then the
336
+ * settings values, then the environment overrides (so a deployment can keep
337
+ * secrets out of the patch file).
338
+ */
339
+ export function normalizeOptions(config: NotifyConfig | undefined): Options {
340
+ const value = <T>(key: keyof NotifyConfig): T | undefined => unwrap<T>(config?.[key] as MaybeRef<T> | undefined)
341
+ const options: Options = {
342
+ enabled: bool(value<boolean>('enabled'), DEFAULTS.enabled),
343
+ transport: value<string>('transport') === 'onebot' ? 'onebot' : 'gotify',
344
+ endpoint: str(expandEnv(value<string>('endpoint')), DEFAULTS.endpoint),
345
+ token: str(expandEnv(value<string>('token')), DEFAULTS.token),
346
+ targetType: value<string>('targetType') === 'group' ? 'group' : 'private',
347
+ targetId: str(expandEnv(value<string>('targetId')), DEFAULTS.targetId),
348
+ gotifyUrl: str(expandEnv(value<string>('gotifyUrl')), DEFAULTS.gotifyUrl),
349
+ gotifyToken: str(expandEnv(value<string>('gotifyToken')), DEFAULTS.gotifyToken),
350
+ gotifyPriority: num(value<number>('gotifyPriority'), DEFAULTS.gotifyPriority),
351
+ gotifyHeaders: normalizeHeaders(value<unknown>('gotifyHeaders')),
352
+ targets: normalizeTargets(value<unknown>('targets'), num(value<number>('gotifyPriority'), DEFAULTS.gotifyPriority)),
353
+ deviceName: str(value<string>('deviceName')),
354
+ deviceLabel: str(value<string>('deviceLabel')),
355
+ deviceInTitle: bool(value<boolean>('deviceInTitle'), DEFAULTS.deviceInTitle),
356
+ notifyOnReasons: reasonsOf(value<readonly string[]>('notifyOnReasons')),
357
+ notifyOnApproval: bool(value<boolean>('notifyOnApproval'), DEFAULTS.notifyOnApproval),
358
+ notifyOnQuestion: bool(value<boolean>('notifyOnQuestion'), DEFAULTS.notifyOnQuestion),
359
+ questionDelayMs: num(value<number>('questionDelayMs'), DEFAULTS.questionDelayMs),
360
+ approvalDelayMs: num(value<number>('approvalDelayMs'), DEFAULTS.approvalDelayMs),
361
+ includeSubagents: bool(value<boolean>('includeSubagents'), DEFAULTS.includeSubagents),
362
+ summaryChars: num(value<number>('summaryChars'), DEFAULTS.summaryChars, 1),
363
+ timeoutMs: num(value<number>('timeoutMs'), DEFAULTS.timeoutMs, 1),
364
+ dryRun: bool(value<boolean>('dryRun'), DEFAULTS.dryRun),
365
+ traceFile: str(value<string>('traceFile'), DEFAULTS.traceFile),
366
+ template: text(value<string>('template'), DEFAULTS.template),
367
+ questionTemplate: text(value<string>('questionTemplate'), DEFAULTS.questionTemplate),
368
+ approvalTemplate: text(value<string>('approvalTemplate'), DEFAULTS.approvalTemplate),
369
+ }
370
+ for (const [key, envKey] of Object.entries(ENV)) {
371
+ const raw = process.env[envKey]
372
+ if (typeof raw !== 'string' || raw.trim() === '') continue
373
+ if (ENV_JSON.has(key)) {
374
+ try {
375
+ const parsed: unknown = JSON.parse(raw)
376
+ if (key === 'targets') options.targets = normalizeTargets(parsed, options.gotifyPriority)
377
+ else options.gotifyHeaders = normalizeHeaders(parsed)
378
+ } catch {
379
+ // A malformed JSON env var must not stop the component; keep the YAML value.
380
+ }
381
+ } else if (key === 'targetType') {
382
+ options.targetType = raw.trim() === 'group' ? 'group' : 'private'
383
+ } else if (key === 'deviceName' || key === 'deviceLabel') {
384
+ options[key] = raw.trim()
385
+ } else {
386
+ const target = key as keyof Options
387
+ if (target === 'targets' || target === 'gotifyHeaders') continue
388
+ ;(options as unknown as Record<string, string>)[target] = raw.trim()
389
+ }
390
+ }
391
+ // Device identity: an empty value falls back to the OS hostname, which is
392
+ // what makes notifications from several machines distinguishable.
393
+ options.deviceName = options.deviceName || safeHostname()
394
+ options.deviceLabel = options.deviceLabel || options.deviceName
395
+ options.targets = options.targets.length > 0
396
+ ? options.targets
397
+ : [{
398
+ name: 'default',
399
+ url: options.gotifyUrl,
400
+ token: options.gotifyToken,
401
+ priority: options.gotifyPriority,
402
+ devices: [],
403
+ }]
404
+ return options
405
+ }
406
+
407
+ /** Keep only known reasons; an empty list falls back to the defaults. */
408
+ function reasonsOf(raw: readonly string[] | undefined): readonly NotifyReason[] {
409
+ const kept = Array.isArray(raw) ? raw.filter((reason): reason is NotifyReason => (NOTIFY_REASONS as readonly string[]).includes(reason)) : []
410
+ return kept.length > 0 ? kept : DEFAULTS.notifyOnReasons
411
+ }
412
+
413
+ /** Join the text blocks of one assistant message. */
414
+ function textOf(content: unknown): string {
415
+ if (!Array.isArray(content)) return ''
416
+ const parts: string[] = []
417
+ for (const block of content) {
418
+ if (block && typeof block === 'object' && (block as { type?: string; text?: unknown }).type === 'text') {
419
+ const value = (block as { text?: unknown }).text
420
+ if (typeof value === 'string' && value.trim() !== '') parts.push(value.trim())
421
+ }
422
+ }
423
+ return parts.join('\n')
424
+ }
425
+
426
+ /** Flatten to one line and cut at `limit` characters (ellipsis included). */
427
+ function truncate(value: unknown, limit: number): string {
428
+ const flat = String(value ?? '').replace(/\s+/g, ' ').trim()
429
+ return flat.length <= limit ? flat : `${flat.slice(0, Math.max(0, limit - 1))}…`
430
+ }
431
+
432
+ /**
433
+ * Turn assistant Markdown into a short plain-text snippet for the gateway.
434
+ *
435
+ * Fenced code blocks are dropped entirely (they are long and unreadable once
436
+ * flattened); inline code keeps its text; emphasis markers, headings, list
437
+ * bullets, table pipes and HTML tags are removed. Single underscores are left
438
+ * alone so `session_id` survives. The result is then cut at `limit`, preferring
439
+ * a sentence boundary when one is reasonably close to the end.
440
+ */
441
+ export function plain(text: unknown, limit = 120): string {
442
+ let value = String(text ?? '').replace(/\r\n?/g, '\n')
443
+ value = value.replace(/```[\s\S]*?```/g, ' ')
444
+ value = value.replace(/```[\s\S]*$/g, ' ')
445
+ value = value.replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
446
+ value = value.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
447
+ value = value.replace(/^\s{0,3}#{1,6}\s+/gm, '')
448
+ value = value.replace(/^\s{0,3}>\s?/gm, '')
449
+ value = value.replace(/^\s{0,3}[-*+]\s+/gm, '')
450
+ value = value.replace(/^\s{0,3}\d+[.)]\s+/gm, '')
451
+ // Markdown table rows: drop the whole row (two or more pipes) rather than
452
+ // flattening cells into an unreadable "a b 1 2".
453
+ value = value.replace(/^[^\n]*\|[^\n]*\|[^\n]*$/gm, ' ')
454
+ value = value.replace(/\|/g, ' ')
455
+ value = value.replace(/^\s*([-*_])\1{2,}\s*$/gm, ' ')
456
+ value = value.replace(/`{1,3}([^`]*)`{1,3}/g, '$1')
457
+ value = value.replace(/(\*\*|__)(.*?)\1/g, '$2')
458
+ value = value.replace(/~~(.*?)~~/g, '$1')
459
+ value = value.replace(/(?<![\w*])\*(?=\S)([^*]*?)(?<=\S)\*(?![\w*])/g, '$1')
460
+ // Underscore emphasis only when it is not inside an identifier (session_id).
461
+ value = value.replace(/(?<![\w])_(?=\S)([^_]*?)(?<=\S)_(?![\w])/g, '$1')
462
+ value = value.replace(/<[^>\n]{1,80}>/g, ' ')
463
+ value = value.replace(/\s+/g, ' ').trim()
464
+ if (value.length <= limit) return value
465
+ const head = value.slice(0, limit)
466
+ const cut = Math.max(head.lastIndexOf('。'), head.lastIndexOf('!'), head.lastIndexOf('?'),
467
+ head.lastIndexOf('.'), head.lastIndexOf('!'), head.lastIndexOf('?'))
468
+ const kept = cut >= Math.floor(limit * 0.6) ? head.slice(0, cut + 1) : head.slice(0, Math.max(0, limit - 1))
469
+ return `${kept.trimEnd()}…`
470
+ }
471
+
472
+ /** Chinese labels for the four turn-end reasons. */
473
+ const REASON_LABEL: Readonly<Record<string, string>> = {
474
+ completed: '完成',
475
+ error: '出错',
476
+ aborted: '被中止',
477
+ blocked: '被阻塞',
478
+ }
479
+
480
+ /** The model-facing tool whose call means the task is parked waiting for a human. */
481
+ const ASK_USER_TOOL = 'ask_user_question'
482
+ /** Plan-mode exit also raises a review question through the unlogged channel. */
483
+ const EXIT_PLAN_TOOL = 'exit_plan_mode'
484
+
485
+ /** One question parsed out of an `ask_user_question` tool call. */
486
+ export interface ParsedQuestion {
487
+ readonly question: string
488
+ readonly detail?: string
489
+ readonly header?: string
490
+ readonly options: readonly string[]
491
+ }
492
+
493
+ /** Parse `ask_user_question` tool arguments defensively (older logs, odd providers). */
494
+ export function parseQuestions(raw: unknown): ParsedQuestion[] {
495
+ let parsed: unknown
496
+ try {
497
+ parsed = JSON.parse(String(raw ?? ''))
498
+ } catch {
499
+ return []
500
+ }
501
+ const list = (parsed as { questions?: unknown } | null)?.questions
502
+ if (!Array.isArray(list)) return []
503
+ const out: ParsedQuestion[] = []
504
+ for (const entry of list) {
505
+ if (!entry || typeof entry !== 'object') continue
506
+ const record = entry as Record<string, unknown>
507
+ if (typeof record.question !== 'string') continue
508
+ out.push({
509
+ question: record.question,
510
+ ...(typeof record.detail === 'string' ? { detail: record.detail } : {}),
511
+ ...(typeof record.header === 'string' ? { header: record.header } : {}),
512
+ options: Array.isArray(record.options)
513
+ ? record.options
514
+ .filter((option): option is { label: string } => !!option && typeof option === 'object' && typeof (option as { label?: unknown }).label === 'string')
515
+ .map((option) => option.label)
516
+ : [],
517
+ })
518
+ }
519
+ return out
520
+ }
521
+
522
+ /** Parse `exit_plan_mode` tool arguments into the reviewed plan text. */
523
+ export function parsePlan(raw: unknown): string | undefined {
524
+ try {
525
+ const parsed: unknown = JSON.parse(String(raw ?? ''))
526
+ const plan = (parsed as { plan?: unknown } | null)?.plan
527
+ return typeof plan === 'string' ? plan : undefined
528
+ } catch {
529
+ return undefined
530
+ }
531
+ }
532
+
533
+ /** Placeholder syntax: `{name}`. Unknown placeholders are left untouched. */
534
+ const PLACEHOLDER = /\{([a-zA-Z][a-zA-Z0-9_]*)\}/g
535
+
536
+ /**
537
+ * Fill a template. A line containing only a label whose value is empty
538
+ * (`目录: ` / `回复: `) is dropped, so one template serves every outcome.
539
+ */
540
+ export function fill(template: string, values: Readonly<Record<string, unknown>>): string {
541
+ return String(template)
542
+ .replace(PLACEHOLDER, (whole, key: string) => (Object.hasOwn(values, key) ? String(values[key] ?? '') : whole))
543
+ .split('\n')
544
+ .map((line) => line.replace(/[ \t]+$/, ''))
545
+ .filter((line) => !/^[^::]*[::]$/.test(line))
546
+ .join('\n')
547
+ .trim()
548
+ }
549
+
550
+ /** Local date/time placeholders. */
551
+ function stamp(): { date: string; time: string } {
552
+ const now = new Date()
553
+ const pad = (value: number): string => String(value).padStart(2, '0')
554
+ return {
555
+ date: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`,
556
+ time: `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`,
557
+ }
558
+ }
559
+
560
+ /** Default turn-end template. */
561
+ export const DEFAULT_TEMPLATE = [
562
+ '[DSH] 会话{status}',
563
+ '设备: {device}',
564
+ '会话: {sessionId}',
565
+ '目录: {cwd}',
566
+ '结果: {status}',
567
+ '错误: {error}',
568
+ '回复: {reply}',
569
+ ].join('\n')
570
+
571
+ /** Default question template. */
572
+ export const DEFAULT_QUESTION_TEMPLATE = [
573
+ '[DSH] 需要你回答',
574
+ '设备: {device}',
575
+ '会话: {sessionId}',
576
+ '目录: {cwd}',
577
+ '问题: {question}',
578
+ '补充: {detail}',
579
+ '选项: {options}',
580
+ ].join('\n')
581
+
582
+ /** Default approval template. */
583
+ export const DEFAULT_APPROVAL_TEMPLATE = [
584
+ '[DSH] 需要授权',
585
+ '设备: {device}',
586
+ '会话: {sessionId}',
587
+ '目录: {cwd}',
588
+ '操作: {tool}',
589
+ '原因: {reason}',
590
+ ].join('\n')
591
+
592
+ /** Inputs for a turn-end message. */
593
+ export interface TurnMessageInput {
594
+ readonly sessionId: unknown
595
+ readonly cwd?: string
596
+ readonly reason?: string
597
+ readonly error?: string
598
+ readonly reply?: string
599
+ readonly summaryChars?: number
600
+ readonly template?: string
601
+ readonly device?: string
602
+ readonly host?: string
603
+ }
604
+
605
+ /** Compact body of a turn-completion message. */
606
+ export function renderMessage(input: TurnMessageInput): string {
607
+ const values: Record<string, unknown> = {
608
+ sessionId: String(input.sessionId).replace(/^session-/, '').slice(0, 8),
609
+ cwd: input.cwd ?? '',
610
+ status: REASON_LABEL[input.reason ?? ''] ?? String(input.reason ?? ''),
611
+ kind: input.reason ?? '',
612
+ reply: plain(input.reply, input.summaryChars ?? 120),
613
+ error: plain(input.error, 120),
614
+ device: input.device ?? '',
615
+ host: input.host ?? input.device ?? '',
616
+ ...stamp(),
617
+ }
618
+ return fill(input.template || DEFAULT_TEMPLATE, values) || `[DSH] 会话${values.status}`
619
+ }
620
+
621
+ /** Inputs for a question-request message. */
622
+ export interface QuestionMessageInput {
623
+ readonly sessionId: unknown
624
+ readonly cwd?: string
625
+ readonly question?: string
626
+ readonly detail?: string
627
+ readonly options?: string
628
+ readonly template?: string
629
+ readonly device?: string
630
+ readonly host?: string
631
+ }
632
+
633
+ /** Compact body of a question-request message (the agent is blocked on you). */
634
+ export function renderQuestionMessage(input: QuestionMessageInput): string {
635
+ const values: Record<string, unknown> = {
636
+ sessionId: String(input.sessionId).replace(/^session-/, '').slice(0, 8),
637
+ cwd: input.cwd ?? '',
638
+ question: plain(input.question, 200),
639
+ detail: plain(input.detail, 160),
640
+ options: plain(input.options, 160),
641
+ device: input.device ?? '',
642
+ host: input.host ?? input.device ?? '',
643
+ ...stamp(),
644
+ }
645
+ return fill(input.template || DEFAULT_QUESTION_TEMPLATE, values) || '[DSH] 需要你回答'
646
+ }
647
+
648
+ /** Inputs for an approval-request message. */
649
+ export interface ApprovalMessageInput {
650
+ readonly sessionId: unknown
651
+ readonly cwd?: string
652
+ readonly toolName?: string
653
+ readonly reason?: string
654
+ readonly template?: string
655
+ readonly device?: string
656
+ readonly host?: string
657
+ }
658
+
659
+ /** Compact body of an approval-request message. */
660
+ export function renderApprovalMessage(input: ApprovalMessageInput): string {
661
+ const values: Record<string, unknown> = {
662
+ sessionId: String(input.sessionId).replace(/^session-/, '').slice(0, 8),
663
+ cwd: input.cwd ?? '',
664
+ tool: input.toolName ?? '',
665
+ reason: plain(input.reason, 200),
666
+ device: input.device ?? '',
667
+ host: input.host ?? input.device ?? '',
668
+ ...stamp(),
669
+ }
670
+ return fill(input.template || DEFAULT_APPROVAL_TEMPLATE, values) || '[DSH] 需要授权'
671
+ }
672
+
673
+ /** One diagnostic trace sink; empty path disables tracing. */
674
+ type Trace = (stage: string, data?: Record<string, unknown>) => void
675
+
676
+ /** Build a trace sink that appends JSONL to `file` (read live, so the setting is hot). */
677
+ function makeTrace(file: () => string): Trace {
678
+ return (stage, data = {}) => {
679
+ const path = file()
680
+ if (!path) return
681
+ try {
682
+ appendFileSync(path, `${JSON.stringify({ t: new Date().toISOString(), stage, ...data })}\n`)
683
+ } catch {
684
+ // Diagnostics must never break notification delivery.
685
+ }
686
+ }
687
+ }
688
+
689
+ /** The OneBot endpoint slice `callAction` needs. */
690
+ export interface OneBotEndpoint {
691
+ readonly endpoint: string
692
+ readonly token: string
693
+ readonly timeoutMs: number
694
+ }
695
+
696
+ /** POST one OneBot 11 action; throws on transport failure or a non-ok retcode. */
697
+ export async function callAction(cfg: OneBotEndpoint, action: string, body: unknown): Promise<unknown> {
698
+ const base = cfg.endpoint.endsWith('/') ? cfg.endpoint : `${cfg.endpoint}/`
699
+ const url = new URL(action, base)
700
+ const headers: Record<string, string> = { 'content-type': 'application/json' }
701
+ if (cfg.token) headers.authorization = `Bearer ${cfg.token}`
702
+ const response = await fetch(url, {
703
+ method: 'POST',
704
+ headers,
705
+ body: JSON.stringify(body),
706
+ signal: AbortSignal.timeout(cfg.timeoutMs),
707
+ })
708
+ const raw = await response.text()
709
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${truncate(raw, 200)}`)
710
+ let parsed: unknown
711
+ try {
712
+ parsed = JSON.parse(raw)
713
+ } catch {
714
+ return raw
715
+ }
716
+ if (parsed && typeof parsed === 'object' && (parsed as { status?: unknown }).status === 'failed') {
717
+ const record = parsed as { retcode?: unknown; message?: unknown; wording?: unknown }
718
+ throw new Error(`OneBot retcode ${String(record.retcode)}: ${truncate(String(record.message ?? record.wording ?? ''), 200)}`)
719
+ }
720
+ return parsed
721
+ }
722
+
723
+ /** Context slice the delivery helpers log through. */
724
+ interface DeliveryContext {
725
+ readonly logger: {
726
+ info(format: unknown, ...param: unknown[]): void
727
+ warn(format: unknown, ...param: unknown[]): void
728
+ }
729
+ }
730
+
731
+ /**
732
+ * 经 Gotify 网关投递。把渲染好的正文拆成「首行作标题、其余作正文」,
733
+ * relay 端再拼回 `标题\n正文`,与直连模式输出一致。
734
+ *
735
+ * One message can fan out to several targets (several gateways, or several
736
+ * app tokens / recipients). Targets may be pinned to devices, so the same
737
+ * config can be shared by every machine and each one only sends to its own
738
+ * recipients. Failures are isolated per target.
739
+ */
740
+ async function deliverViaGotify(ctx: DeliveryContext, cfg: Options, payload: string, trace: Trace): Promise<void> {
741
+ const targets = cfg.targets.filter((target) => targetMatchesDevice(target, cfg))
742
+ if (targets.length === 0) {
743
+ ctx.logger.warn(`dsh-notify: no gotify target matches device "${cfg.deviceLabel}", skipping send`)
744
+ trace('deliver', { mode: 'skip', why: 'no target for device', device: cfg.deviceLabel })
745
+ return
746
+ }
747
+
748
+ const [title, ...rest] = String(payload).split('\n')
749
+ const finalTitle = cfg.deviceInTitle ? `[${cfg.deviceLabel}] ${title}` : title
750
+ const message = rest.join('\n')
751
+
752
+ const results = await Promise.allSettled(
753
+ targets.map((target) => sendGotifyTarget(ctx, cfg, target, finalTitle, message, trace)),
754
+ )
755
+ logGotifyFailures(ctx, cfg, results)
756
+ }
757
+
758
+ /** Fire one Gotify POST at one target, retrying once on transient failure. */
759
+ async function sendGotifyTarget(
760
+ ctx: DeliveryContext,
761
+ cfg: Options,
762
+ target: NotifyTarget,
763
+ title: string,
764
+ message: string,
765
+ trace: Trace,
766
+ ): Promise<void> {
767
+ if (cfg.dryRun) {
768
+ ctx.logger.info(
769
+ `dsh-notify: dryRun, would POST gotify target=${target.name} url=${target.url} `
770
+ + `device=${cfg.deviceLabel} ${JSON.stringify({ title, message, priority: target.priority })}`,
771
+ )
772
+ trace('deliver', { mode: 'dryRun', transport: 'gotify', target: target.name, device: cfg.deviceLabel })
773
+ return
774
+ }
775
+ if (!target.url || !target.token) {
776
+ ctx.logger.warn(`dsh-notify: target "${target.name}" is missing url or token, skipping`)
777
+ trace('deliver', { mode: 'skip', why: 'target config missing', target: target.name })
778
+ return
779
+ }
780
+
781
+ const url = `${target.url.replace(/\/+$/, '')}/message`
782
+ const body = { title, message, priority: target.priority }
783
+ // Custom headers come first so the auth/content headers cannot be clobbered.
784
+ const headers = { ...cfg.gotifyHeaders, 'content-type': 'application/json', 'X-Gotify-Key': target.token }
785
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
786
+ try {
787
+ const response = await fetch(url, {
788
+ method: 'POST',
789
+ headers,
790
+ body: JSON.stringify(body),
791
+ signal: AbortSignal.timeout(cfg.timeoutMs),
792
+ })
793
+ const raw = await response.text()
794
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${raw.slice(0, 160)}`)
795
+ ctx.logger.info(`dsh-notify: delivered via gotify target=${target.name} device=${cfg.deviceLabel} (${title})`)
796
+ trace('deliver', { mode: 'ok', transport: 'gotify', target: target.name, attempt })
797
+ return
798
+ } catch (error) {
799
+ trace('deliver', {
800
+ mode: 'fail', transport: 'gotify', target: target.name, attempt, error: errorMessage(error),
801
+ })
802
+ if (attempt === 2) throw error
803
+ await new Promise((resolve) => setTimeout(resolve, 400))
804
+ }
805
+ }
806
+ }
807
+
808
+ /** Log a per-target summary without leaking tokens. */
809
+ function logGotifyFailures(ctx: DeliveryContext, cfg: Options, results: readonly PromiseSettledResult<void>[]): void {
810
+ const failed = results.filter((result) => result.status === 'rejected')
811
+ if (failed.length === 0) return
812
+ const detail = failed
813
+ .map((result) => String((result as PromiseRejectedResult).reason?.message ?? (result as PromiseRejectedResult).reason))
814
+ .join('; ')
815
+ ctx.logger.warn(`dsh-notify: ${failed.length}/${results.length} gotify target(s) failed on ${cfg.deviceLabel}: ${detail}`)
816
+ }
817
+
818
+ /** One delivery attempt with a single retry for transient failures. */
819
+ async function deliver(ctx: DeliveryContext, cfg: Options, payload: string, trace: Trace): Promise<void> {
820
+ if (cfg.transport === 'gotify') return deliverViaGotify(ctx, cfg, payload, trace)
821
+ const action = cfg.targetType === 'group' ? 'send_group_msg' : 'send_private_msg'
822
+ // Segment form: the text is never parsed as CQ codes, so a reply containing
823
+ // `[CQ:at,qq=all]` cannot inject an action into the group.
824
+ const message = [{ type: 'text', data: { text: payload } }]
825
+ const body = cfg.targetType === 'group'
826
+ ? { group_id: cfg.targetId, message }
827
+ : { user_id: cfg.targetId, message }
828
+
829
+ if (cfg.dryRun) {
830
+ ctx.logger.info(`dsh-notify: dryRun, would POST ${action} ${JSON.stringify(body)}`)
831
+ trace('deliver', { mode: 'dryRun', action, targetId: cfg.targetId })
832
+ return
833
+ }
834
+ if (!cfg.targetId) {
835
+ ctx.logger.warn('dsh-notify: targetId is empty, skipping send')
836
+ trace('deliver', { mode: 'skip', why: 'targetId empty' })
837
+ return
838
+ }
839
+
840
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
841
+ try {
842
+ await callAction(cfg, action, body)
843
+ ctx.logger.info(`dsh-notify: delivered ${action} to ${cfg.targetType} ${cfg.targetId}`)
844
+ trace('deliver', { mode: 'ok', action, targetId: cfg.targetId, attempt })
845
+ return
846
+ } catch (error) {
847
+ trace('deliver', { mode: 'fail', action, attempt, error: errorMessage(error) })
848
+ if (attempt === 2) {
849
+ ctx.logger.warn(`dsh-notify: delivery failed after ${attempt} attempts: ${errorMessage(error)}`)
850
+ return
851
+ }
852
+ await new Promise((resolve) => setTimeout(resolve, 300))
853
+ }
854
+ }
855
+ }
856
+
857
+ /** Read `error.message` off an unknown thrown value. */
858
+ function errorMessage(error: unknown): string {
859
+ return error instanceof Error ? error.message : String(error)
860
+ }
861
+
862
+ /** Structural slice of the session a listener reads. */
863
+ interface SessionLike {
864
+ readonly id: string
865
+ readonly header?: { readonly cwd?: string }
866
+ }
867
+
868
+ /** Structural slice of the session log event envelope. */
869
+ interface EventEnvelopeLike {
870
+ readonly type?: string
871
+ readonly data?: unknown
872
+ }
873
+
874
+ /** Structural slice of one session log event's payload. */
875
+ interface EventDataLike {
876
+ readonly turn?: unknown
877
+ readonly callId?: unknown
878
+ readonly name?: unknown
879
+ readonly arguments?: unknown
880
+ readonly id?: unknown
881
+ readonly toolName?: unknown
882
+ readonly reason?: { readonly kind?: string; readonly error?: { readonly message?: string } }
883
+ readonly message?: {
884
+ readonly content?: unknown
885
+ readonly toolCallId?: unknown
886
+ }
887
+ }
888
+
889
+ /** Structural slice of one agent. */
890
+ interface AgentLike {
891
+ readonly id: string
892
+ readonly session?: { readonly header?: { readonly cwd?: string } }
893
+ }
894
+
895
+ /**
896
+ * Structural slice of the agent registry. 0.2.2 exposes `list()`; older host
897
+ * lines expose `roots()` for the same live agents, so both are read.
898
+ */
899
+ interface AgentRegistryLike {
900
+ roots?(): readonly AgentLike[]
901
+ list?(): readonly AgentLike[]
902
+ }
903
+
904
+ /** Per-session record of the most recent finished turn. */
905
+ interface TurnState {
906
+ turn: unknown
907
+ reason?: string
908
+ error?: string
909
+ reply: string
910
+ notified: boolean
911
+ }
912
+
913
+ /**
914
+ * Activate the component.
915
+ * @param ctx - host Cordis context.
916
+ * @param config - row config from cordis.patch.yml or the settings document;
917
+ * volatile fields arrive as live references.
918
+ */
919
+ export function apply(ctx: Context, config: NotifyConfig = {}): void {
920
+ const read = (): Options => normalizeOptions(config)
921
+ const trace = makeTrace(() => normalizeOptions(config).traceFile)
922
+ const logger = ctx.logger
923
+
924
+ const initial = read()
925
+ const targetSummary = initial.targets
926
+ .filter((target) => targetMatchesDevice(target, initial))
927
+ .map((target) => target.name)
928
+ .join(',') || '<none>'
929
+ logger.info(
930
+ `dsh-notify: active (device=${initial.deviceLabel}, transport=${initial.transport}, targets=${targetSummary}, `
931
+ + `reasons=${initial.notifyOnReasons.join(',')}, approval=${initial.notifyOnApproval}, dryRun=${initial.dryRun})`,
932
+ )
933
+ trace('activate', {
934
+ deviceName: initial.deviceName,
935
+ deviceLabel: initial.deviceLabel,
936
+ transport: initial.transport,
937
+ targets: initial.targets.map((target) => target.name),
938
+ reasons: initial.notifyOnReasons,
939
+ notifyOnApproval: initial.notifyOnApproval,
940
+ dryRun: initial.dryRun,
941
+ })
942
+
943
+ /** Per-session record of the most recent finished turn. */
944
+ const turns = new Map<string, TurnState>()
945
+
946
+ /**
947
+ * Get (or seed) the record for one session. State must not depend on having
948
+ * seen `turn/start`: a component activated mid-turn never sees it.
949
+ */
950
+ const stateOf = (id: string): TurnState => {
951
+ let current = turns.get(id)
952
+ if (!current) {
953
+ current = { turn: undefined, reason: undefined, error: undefined, reply: '', notified: false }
954
+ turns.set(id, current)
955
+ }
956
+ return current
957
+ }
958
+
959
+ /** Debounce timers keyed by call/approval id; a matching result cancels them. */
960
+ const pending = new Map<string, ReturnType<typeof setTimeout>>()
961
+ const schedule = (key: string, delayMs: number, produce: () => string): void => {
962
+ if (pending.has(key)) return
963
+ const timer = setTimeout(() => {
964
+ pending.delete(key)
965
+ try {
966
+ void deliver(ctx as unknown as DeliveryContext, read(), produce(), trace)
967
+ } catch (error) {
968
+ trace('schedule-error', { key, error: errorMessage(error) })
969
+ }
970
+ }, Number(delayMs) > 0 ? Number(delayMs) : 2500)
971
+ pending.set(key, timer)
972
+ }
973
+ const cancel = (key: string): void => {
974
+ const timer = pending.get(key)
975
+ if (timer !== undefined) {
976
+ clearTimeout(timer)
977
+ pending.delete(key)
978
+ }
979
+ }
980
+
981
+ const onSessionEvent = (session: SessionLike, event: EventEnvelopeLike): void => {
982
+ const cfg = read()
983
+ if (!cfg.enabled) return
984
+ const id = session.id
985
+ // SessionEvent is an envelope: { type, seq, time, data }. Tolerate a bare
986
+ // payload too, so a shape change degrades instead of silently no-op'ing.
987
+ const data = (event.data ?? event) as EventDataLike
988
+ switch (event.type) {
989
+ case 'turn/start':
990
+ turns.set(id, { turn: data.turn, reason: undefined, error: undefined, reply: '', notified: false })
991
+ break
992
+ case 'assistant/message':
993
+ stateOf(id).reply = textOf(data.message?.content)
994
+ break
995
+ case 'turn/end': {
996
+ const current = stateOf(id)
997
+ current.turn = data.turn
998
+ current.reason = data.reason?.kind ?? 'unknown'
999
+ current.error = data.reason?.error?.message
1000
+ trace('turn/end', { sessionId: id, turn: data.turn, reason: data.reason?.kind })
1001
+ break
1002
+ }
1003
+ // 用户提问:会话日志里没有 user-questions 事件,工具调用本身就是"挂起等人"的信号。
1004
+ case 'tool/call': {
1005
+ if (!cfg.notifyOnQuestion) break
1006
+ const callId = String(data.callId ?? '')
1007
+ if (!callId) break
1008
+ if (data.name === ASK_USER_TOOL) {
1009
+ trace('wait/question', { sessionId: id, callId })
1010
+ schedule(`q:${callId}`, cfg.questionDelayMs, () => {
1011
+ const questions = parseQuestions(data.arguments)
1012
+ return renderQuestionMessage({
1013
+ sessionId: id,
1014
+ cwd: session.header?.cwd,
1015
+ question: questions[0]?.question,
1016
+ detail: questions[0]?.detail,
1017
+ options: (questions[0]?.options ?? []).join(' / '),
1018
+ template: cfg.questionTemplate,
1019
+ device: cfg.deviceLabel,
1020
+ host: cfg.deviceName,
1021
+ })
1022
+ })
1023
+ } else if (data.name === EXIT_PLAN_TOOL) {
1024
+ trace('wait/plan', { sessionId: id, callId })
1025
+ schedule(`p:${callId}`, cfg.questionDelayMs, () => renderQuestionMessage({
1026
+ sessionId: id,
1027
+ cwd: session.header?.cwd,
1028
+ question: '计划已提交,等待你确认',
1029
+ detail: parsePlan(data.arguments),
1030
+ template: cfg.questionTemplate,
1031
+ device: cfg.deviceLabel,
1032
+ host: cfg.deviceName,
1033
+ }))
1034
+ }
1035
+ break
1036
+ }
1037
+ case 'tool/result': {
1038
+ const callId = String(data.message?.toolCallId ?? data.callId ?? '')
1039
+ if (callId) {
1040
+ cancel(`q:${callId}`)
1041
+ cancel(`p:${callId}`)
1042
+ }
1043
+ break
1044
+ }
1045
+ // 审批:日志里有 approval/asked;短时间内拿到 decided 说明是自动裁决,不必打扰。
1046
+ case 'approval/asked': {
1047
+ if (!cfg.notifyOnApproval) break
1048
+ const askId = String(data.id ?? '')
1049
+ if (!askId) break
1050
+ trace('wait/approval', { sessionId: id, toolName: data.toolName })
1051
+ schedule(`a:${askId}`, cfg.approvalDelayMs, () => renderApprovalMessage({
1052
+ sessionId: id,
1053
+ cwd: session.header?.cwd,
1054
+ toolName: typeof data.toolName === 'string' ? data.toolName : undefined,
1055
+ reason: typeof (data as { reason?: unknown }).reason === 'string' ? (data as { reason: string }).reason : undefined,
1056
+ template: cfg.approvalTemplate,
1057
+ device: cfg.deviceLabel,
1058
+ host: cfg.deviceName,
1059
+ }))
1060
+ break
1061
+ }
1062
+ case 'approval/decided': {
1063
+ cancel(`a:${String(data.id ?? '')}`)
1064
+ break
1065
+ }
1066
+ default:
1067
+ break
1068
+ }
1069
+ }
1070
+
1071
+ const onAgentStatus = (payload: { agent: AgentLike; status: string }): void => {
1072
+ const cfg = read()
1073
+ if (!cfg.enabled) return
1074
+ // Only the idle edge matters. It is not paired with a `running` edge on
1075
+ // purpose: a component activated mid-turn never saw that edge, and
1076
+ // `turn/end` already marks exactly one notify-worthy turn.
1077
+ if (payload.status !== 'idle') return
1078
+ const agent = payload.agent
1079
+
1080
+ let isRoot = true
1081
+ try {
1082
+ const registry = ctx.agents as unknown as AgentRegistryLike
1083
+ const roots = registry.roots?.() ?? registry.list?.() ?? []
1084
+ isRoot = roots.some((root) => root.id === agent.id)
1085
+ } catch (error) {
1086
+ trace('roots-error', { error: errorMessage(error) })
1087
+ }
1088
+
1089
+ const state = turns.get(agent.id)
1090
+ trace('agent/idle', {
1091
+ sessionId: agent.id,
1092
+ isRoot,
1093
+ turn: state?.turn,
1094
+ reason: state?.reason,
1095
+ notified: state?.notified,
1096
+ matched: state ? cfg.notifyOnReasons.includes(state.reason as NotifyReason) : false,
1097
+ })
1098
+
1099
+ if (!cfg.includeSubagents && !isRoot) return
1100
+ if (!state || state.notified) return
1101
+ if (!cfg.notifyOnReasons.includes(state.reason as NotifyReason)) return
1102
+ state.notified = true
1103
+
1104
+ const payloadText = renderMessage({
1105
+ sessionId: agent.id,
1106
+ cwd: agent.session?.header?.cwd,
1107
+ reason: state.reason,
1108
+ error: state.error,
1109
+ reply: state.reply,
1110
+ summaryChars: cfg.summaryChars,
1111
+ template: cfg.template,
1112
+ device: cfg.deviceLabel,
1113
+ host: cfg.deviceName,
1114
+ })
1115
+ void deliver(ctx as unknown as DeliveryContext, cfg, payloadText, trace)
1116
+ }
1117
+
1118
+ const disposeSession = ctx.on('session/event', onSessionEvent as never)
1119
+ const disposeStatus = ctx.on('agent/status', onAgentStatus as never)
1120
+ ctx.effect(() => () => {
1121
+ if (typeof disposeSession === 'function') disposeSession()
1122
+ if (typeof disposeStatus === 'function') disposeStatus()
1123
+ for (const timer of pending.values()) clearTimeout(timer)
1124
+ pending.clear()
1125
+ })
1126
+ }