dsh-notification-focus 0.0.0-stage → 0.3.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/LICENSE +22 -0
- package/README.md +160 -3
- package/THIRD_PARTY_NOTICES.md +78 -0
- package/approval-actions.js +496 -0
- package/assets/icon-transparent.png +0 -0
- package/assets/icon.ico +0 -0
- package/client.js +988 -0
- package/cordis.patch.yml +9 -0
- package/history-store.js +212 -0
- package/idle-prompt.js +188 -0
- package/index.js +2064 -0
- package/install-aumid.ps1 +225 -0
- package/install-notify-protocol.ps1 +42 -0
- package/notify-action-handler.ps1 +151 -0
- package/notify-action-hidden.vbs +26 -0
- package/package.json +77 -6
- package/pause-actions.js +274 -0
- package/play-file.ps1 +67 -0
- package/preview-sound.ps1 +62 -0
- package/speak.ps1 +59 -0
- package/state-store.js +344 -0
- package/uninstall-aumid.ps1 +107 -0
- package/uninstall-notify-protocol.ps1 +19 -0
package/index.js
ADDED
|
@@ -0,0 +1,2064 @@
|
|
|
1
|
+
// origin: opencode-agent/hy4-flash-free | 2026-11-23T21:29:00+08:00 | Host 半身(当前:四类通知 + 焦点/静音 + 审批拒绝 + 持久化)
|
|
2
|
+
|
|
3
|
+
// DSH 桌面通知插件 Host:四类通知 + 空闲/审批按钮 + 焦点门控 + 持久化。
|
|
4
|
+
// 权威状态见仓库根 HANDOFF-20261124-status.md;API 在 0.2.2-rc.5 实测核实。
|
|
5
|
+
|
|
6
|
+
import { spawn } from 'node:child_process'
|
|
7
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
8
|
+
import { appendFileSync, writeFileSync, unlinkSync, readFileSync, existsSync, watchFile, unwatchFile, readdirSync, statSync } from 'node:fs'
|
|
9
|
+
import { join } from 'node:path'
|
|
10
|
+
import { fileURLToPath } from 'node:url'
|
|
11
|
+
// 并行路线集成:全部默认关闭,未开时原有四类通知路径不变。
|
|
12
|
+
import { createStateStore } from './state-store.js'
|
|
13
|
+
import { createHistoryStore } from './history-store.js'
|
|
14
|
+
import {
|
|
15
|
+
isPauseButtonsEnabled, buildToastActions, formatActionXml,
|
|
16
|
+
createTokenVerifier, actionFilePath, parseActionFile, validateAction,
|
|
17
|
+
} from './pause-actions.js'
|
|
18
|
+
import {
|
|
19
|
+
buildFocusActionXml, createApprovalActionStore, validateRejectAction, validateApproveAction,
|
|
20
|
+
buildDecisionActionXml, APPROVE_OP, APPROVE_TOKEN_TTL_MS, escapeXmlAttribute,
|
|
21
|
+
} from './approval-actions.js'
|
|
22
|
+
import { createIdleTracker, DEFAULT_IDLE_THRESHOLD_MS } from './idle-prompt.js'
|
|
23
|
+
|
|
24
|
+
// 诊断开关(默认关):排障时设 DSH_NOTIFICATION_DIAG=1 重启即可开。
|
|
25
|
+
const DIAGNOSTICS = process.env.DSH_NOTIFICATION_DIAG === '1'
|
|
26
|
+
const DIAG_LOG = join(process.env.TEMP || process.cwd(), 'dsh-notification-host-diag.log')
|
|
27
|
+
|
|
28
|
+
// 试听(设置页改提示音时立刻响一次):独立路由 + 独立播放脚本,不经过 toast,
|
|
29
|
+
// 所以不会往通知中心留卡片。播放脚本用 PS 5.1 的 WinRT,和 toast 的 audio src 同源。
|
|
30
|
+
const PREVIEW_PATH = '/api/dsh-notify/preview'
|
|
31
|
+
const PREVIEW_SCRIPT = fileURLToPath(new URL('./preview-sound.ps1', import.meta.url))
|
|
32
|
+
// 连按方向键翻下拉时合并成一次,避免多个播放进程叠在一起。
|
|
33
|
+
const PREVIEW_MIN_GAP_MS = 250
|
|
34
|
+
let lastPreviewAt = 0
|
|
35
|
+
|
|
36
|
+
// 缺口 6:语音播报 + 本地音频旁路播放(都不是 toast 的 audio src,见调研结论)。
|
|
37
|
+
const SPEAK_SCRIPT = fileURLToPath(new URL('./speak.ps1', import.meta.url))
|
|
38
|
+
const PLAY_FILE_SCRIPT = fileURLToPath(new URL('./play-file.ps1', import.meta.url))
|
|
39
|
+
// 缺口 3/4:跳转具体会话 + 通知历史。
|
|
40
|
+
const HISTORY_PATH = '/api/dsh-notify/history'
|
|
41
|
+
const TEST_PATH = '/api/dsh-notify/test'
|
|
42
|
+
const NAVIGATE_PATH = '/api/dsh-notify/navigate'
|
|
43
|
+
const VOICES_PATH = '/api/dsh-notify/voices'
|
|
44
|
+
// 设置页渲染异常上报:始终注册(带 requestRejection 围栏),便于只读日志定位白屏。
|
|
45
|
+
const RENDER_ERROR_PATH = '/api/dsh-notify/render-error'
|
|
46
|
+
const RENDER_ERROR_LOG = join(process.env.TEMP || process.cwd(), 'dsh-notification-render-error.log')
|
|
47
|
+
|
|
48
|
+
// 审批卡片自动卸载(2026-11-26 复核子代理实证的路径):
|
|
49
|
+
// 我们从 prepend answerer 里 race 胜出返回 'rejected' 时,DSH 已经把这条 approval/request
|
|
50
|
+
// 转发给客户端(应用内卡片就是客户端 answerer),但那条远端事件永远没人结算 —— 所以卡片挂着。
|
|
51
|
+
// 网关自己就有取消链路:cancelRemoteEvent → 向客户端推 {type:'cancel'} → 客户端 abort 投递
|
|
52
|
+
// signal → PendingApproval.abort() → answerApproval 的 finally remove() → 卡片卸载。
|
|
53
|
+
// 这条路径正是 DSH 为"另一个客户端已裁决"设计的,所以不会重复审计、也不会二次弹窗。
|
|
54
|
+
// typertGateway 用可选注入拿(不写进顶层 inject,避免整插件被它门禁);拿不到就 fail-open。
|
|
55
|
+
let typertGateway = null
|
|
56
|
+
// 网关内部字段是 Map + 类方法,DSH 升级可能改名 → 每次调用前自检形状,不对就放弃(卡片维持现状)。
|
|
57
|
+
function dismissInAppApproval(req, gateway = typertGateway) {
|
|
58
|
+
try {
|
|
59
|
+
const gw = gateway
|
|
60
|
+
const map = gw?.pendingRemoteEvents
|
|
61
|
+
if (!(map instanceof Map) || typeof gw.cancelRemoteEvent !== 'function') {
|
|
62
|
+
actionDiag('in-app card dismiss skipped: gateway shape unknown')
|
|
63
|
+
return false
|
|
64
|
+
}
|
|
65
|
+
const callId = req?.callId
|
|
66
|
+
if (callId === undefined) { actionDiag('in-app card dismiss skipped: no callId'); return false }
|
|
67
|
+
for (const pending of [...map.values()]) {
|
|
68
|
+
const frame = pending?.frame
|
|
69
|
+
// 同一时刻可能有多个审批在飞;callId 是工具调用的唯一键,用它精确匹配这一条
|
|
70
|
+
if (!frame || frame.event !== 'approval/request') continue
|
|
71
|
+
if (frame.request?.callId !== callId) continue
|
|
72
|
+
gw.cancelRemoteEvent(pending, new Error('dsh-notification: approval decided from the toast'))
|
|
73
|
+
actionDiag('in-app card dismissed for callId=' + String(callId).slice(0, 40))
|
|
74
|
+
return true
|
|
75
|
+
}
|
|
76
|
+
actionDiag('in-app card dismiss: no forwarded request for callId=' + String(callId).slice(0, 40))
|
|
77
|
+
} catch (e) {
|
|
78
|
+
actionDiag('in-app card dismiss failed (fail-open): ' + (e?.message || String(e)))
|
|
79
|
+
}
|
|
80
|
+
return false
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// 焦点门控反向开关(默认关=行业惯例):设 DSH_NOTIFICATION_ALWAYS_NOTIFY=1 时,
|
|
84
|
+
// 审批/提问类通知也无视焦点、总是弹(对齐 Claude Code always / Codex notification_condition=always)。
|
|
85
|
+
// 默认按行业惯例:用户正看着该会话时不弹 OS toast(应用内卡片照常显示,不静默丢弃请求)。
|
|
86
|
+
let ALWAYS_NOTIFY = process.env.DSH_NOTIFICATION_ALWAYS_NOTIFY === '1'
|
|
87
|
+
|
|
88
|
+
// 点击回跳(实验性,默认关):设 DSH_NOTIFICATION_CLICK=1 开启 toast 点击→dsh:// 协议。
|
|
89
|
+
// 非打包 AUMID 的协议激活行为需真机验证,默认关避免影响已稳定通知。
|
|
90
|
+
let CLICK_ENABLED = process.env.DSH_NOTIFICATION_CLICK === '1'
|
|
91
|
+
|
|
92
|
+
// toast 暂停按钮(默认关):dshnotify:// → handler → 文件动作通道。
|
|
93
|
+
let PAUSE_BUTTONS = isPauseButtonsEnabled(process.env)
|
|
94
|
+
// 审批操作按钮(默认关,设置页可开):拒绝=一次性令牌在原 waterfall 内返回 rejected;
|
|
95
|
+
// 去 DSH 确认=仅 dsh://open 聚焦窗口。绝不产生 allowed-once。
|
|
96
|
+
let APPROVAL_BUTTONS = process.env.DSH_NOTIFICATION_APPROVAL_BUTTONS === '1'
|
|
97
|
+
// 🔴 高级选项:通知内"批准一次"默认关闭。默认只有导航/拒绝按钮,绝不产生授权按钮。
|
|
98
|
+
// 用户必须在设置页单独打开这个开关才会签发批准令牌(并在界面看到风险须知)。
|
|
99
|
+
let APPROVE_ENABLED = process.env.DSH_NOTIFICATION_APPROVE === '1'
|
|
100
|
+
|
|
101
|
+
// 空闲提醒(默认关):60s 无用户活动且无后台任务才提醒;阈值可用 env 改小便于验证。
|
|
102
|
+
let idleEnabled = process.env.DSH_NOTIFICATION_IDLE === '1'
|
|
103
|
+
let idleMs = (() => {
|
|
104
|
+
const v = Number(process.env.DSH_NOTIFICATION_IDLE_MS)
|
|
105
|
+
return Number.isFinite(v) && v >= 1000 && v <= 24 * 60 * 60 * 1000 ? v : DEFAULT_IDLE_THRESHOLD_MS
|
|
106
|
+
})()
|
|
107
|
+
const clampIdleMs = (v) => {
|
|
108
|
+
const n = Number(v)
|
|
109
|
+
return Number.isFinite(n) && n >= 1000 && n <= 24 * 60 * 60 * 1000 ? n : DEFAULT_IDLE_THRESHOLD_MS
|
|
110
|
+
}
|
|
111
|
+
// 空闲接线诊断(默认关):排障时 DSH_NOTIFICATION_IDLE_DIAG=1,写独立临时日志。
|
|
112
|
+
const IDLE_DIAG = process.env.DSH_NOTIFICATION_IDLE_DIAG === '1'
|
|
113
|
+
const IDLE_DIAG_FILE = join(process.env.TEMP || process.cwd(), 'dsh-notification-idle-diag.log')
|
|
114
|
+
function idleDiag(line) {
|
|
115
|
+
if (!IDLE_DIAG) return
|
|
116
|
+
try { appendFileSync(IDLE_DIAG_FILE, `[${new Date().toISOString()}] ${line}\n`, 'utf8') } catch { /* ignore */ }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// quiet hours:加载时解析一次,格式 'HH:MM-HH:MM'(如 '22:00-07:00'),非法则关闭。
|
|
120
|
+
const QUIET_RAW = process.env.DSH_NOTIFICATION_QUIET || ''
|
|
121
|
+
const QUIET_PARTS = /^(\d{1,2}:\d{2})-(\d{1,2}:\d{2})$/.exec(QUIET_RAW)
|
|
122
|
+
let QUIET_START = QUIET_PARTS ? QUIET_PARTS[1] : ''
|
|
123
|
+
let QUIET_END = QUIET_PARTS ? QUIET_PARTS[2] : ''
|
|
124
|
+
// 类型可配:逗号分隔的 kind 白名单(success/approval/needs-input/error),空=全开。
|
|
125
|
+
const TYPES_RAW = process.env.DSH_NOTIFICATION_TYPES || ''
|
|
126
|
+
let ALLOWED_TYPES = TYPES_RAW ? new Set(TYPES_RAW.split(',').map(s => s.trim()).filter(Boolean)) : null
|
|
127
|
+
|
|
128
|
+
// per-event 音效映射(Windows 系统音 ms-winsoundevent;两家官方都没有差异化,做成卖点)。
|
|
129
|
+
// 9 种可选音效(对标 BillCx330 的 9 种),None=静音。
|
|
130
|
+
const SOUND_CHOICES = [
|
|
131
|
+
'Notification.Default', 'Notification.IM', 'Notification.Mail',
|
|
132
|
+
'Notification.Reminder', 'Notification.LoopingCall', 'Notification.LoopingAlarm',
|
|
133
|
+
'Notification.LoopingAlarm2', 'Notification.LoopingCall2', 'None',
|
|
134
|
+
]
|
|
135
|
+
// 🔴 四个 Looping* 是 toast 专用音源,系统播放器放不出来(试听早就用系统 wav 近似兜底)。
|
|
136
|
+
// 通知投递路径也做同样兜底:选这些音效时 toast 设静音,后台播对应 %WINDIR%\Media\*.wav。
|
|
137
|
+
const LOOP_SOUND_FALLBACK = {
|
|
138
|
+
'Notification.LoopingCall': 'Ring01.wav',
|
|
139
|
+
'Notification.LoopingCall2': 'Ring02.wav',
|
|
140
|
+
'Notification.LoopingAlarm': 'Alarm01.wav',
|
|
141
|
+
'Notification.LoopingAlarm2': 'Alarm02.wav',
|
|
142
|
+
}
|
|
143
|
+
const DEFAULT_AUDIO_MAP = {
|
|
144
|
+
success: 'Notification.IM', // 完成:轻提示
|
|
145
|
+
approval: 'Notification.Reminder', // 审批:提醒感
|
|
146
|
+
'needs-input': 'Notification.Mail', // 提问:邮件感
|
|
147
|
+
error: 'Notification.Default', // 错误:标准警示
|
|
148
|
+
}
|
|
149
|
+
// 环境变量覆盖初始值(设置页已实现,运行时可改并落盘):DSH_NOTIFICATION_SOUNDS="success=Notification.IM,error=None"
|
|
150
|
+
let AUDIO_MAP = { ...DEFAULT_AUDIO_MAP }
|
|
151
|
+
try {
|
|
152
|
+
const rawSounds = process.env.DSH_NOTIFICATION_SOUNDS || ''
|
|
153
|
+
for (const pair of rawSounds.split(',')) {
|
|
154
|
+
const [k, v] = pair.split('=').map(s => s.trim())
|
|
155
|
+
if (k && SOUND_CHOICES.includes(v)) AUDIO_MAP[k] = v
|
|
156
|
+
}
|
|
157
|
+
} catch { /* fail-open:配置错误用默认 */ }
|
|
158
|
+
|
|
159
|
+
// 审批 6s 宽限(对齐 Claude permission_prompt):审批出现后等 6s,期间若已裁决则不弹。
|
|
160
|
+
// 设 DSH_NOTIFICATION_APPROVAL_GRACE_MS=0 可关闭。仅影响 toast,不影响应用内卡片。
|
|
161
|
+
let APPROVAL_GRACE_MS = (() => {
|
|
162
|
+
const v = Number(process.env.DSH_NOTIFICATION_APPROVAL_GRACE_MS)
|
|
163
|
+
return Number.isFinite(v) && v >= 0 ? v : 6000
|
|
164
|
+
})()
|
|
165
|
+
|
|
166
|
+
// snooze:临时静音截止时间(毫秒时间戳),进程内存,重启即失效。
|
|
167
|
+
let snoozeUntil = 0
|
|
168
|
+
// 插件启停总开关:设 false 时所有通知静默(设置页总开关 / 永久暂停共用)。
|
|
169
|
+
// 默认从环境变量读,进程内存态。
|
|
170
|
+
let enabled = process.env.DSH_NOTIFICATION_ENABLED !== '0'
|
|
171
|
+
|
|
172
|
+
// 🔔 按会话免打扰(只在设置页开关,不给 toast 加任何按钮):
|
|
173
|
+
// 命中会话的通知像全局静音一样直接丢弃——不弹 toast、不写历史、不播 TTS/自定义音。
|
|
174
|
+
// env 初值 DSH_NOTIFICATION_MUTED 逗号分隔(如 "sid-a,sid-b");设置页可改并落盘。
|
|
175
|
+
const SESSION_ID_RE = /^[A-Za-z0-9_.:-]{1,200}$/
|
|
176
|
+
const MAX_MUTED_SESSIONS = 200
|
|
177
|
+
function normalizeMutedSessions(value, trim) {
|
|
178
|
+
const out = []
|
|
179
|
+
const seen = new Set()
|
|
180
|
+
const list = Array.isArray(value) ? value : String(value || '').split(',')
|
|
181
|
+
for (const item of list) {
|
|
182
|
+
const sid = trim && typeof item === 'string' ? item.trim() : item
|
|
183
|
+
if (typeof sid !== 'string' || !SESSION_ID_RE.test(sid) || seen.has(sid)) continue
|
|
184
|
+
seen.add(sid)
|
|
185
|
+
out.push(sid)
|
|
186
|
+
if (out.length >= MAX_MUTED_SESSIONS) break
|
|
187
|
+
}
|
|
188
|
+
return out
|
|
189
|
+
}
|
|
190
|
+
let MUTED_SESSIONS = normalizeMutedSessions(process.env.DSH_NOTIFICATION_MUTED, true)
|
|
191
|
+
|
|
192
|
+
// 同步冷却窗:每会话最近一次"高优先级活动"(审批/needs-input/错误)时间戳。
|
|
193
|
+
// 完成通知(prio=0)投递前检查:若同会话 N ms 内有高优先级活动,跳过本次完成——
|
|
194
|
+
// 等价于"审批赢"但零定时器、零延迟。非完成类一律立即投递、不受此限。
|
|
195
|
+
const highPriorityAt = new Map() // sid -> timestamp(ms)
|
|
196
|
+
const COOLDOWN_MS = 5 * 1000
|
|
197
|
+
// 被焦点门控抑制的审批:挂起,等用户离开(away=true)时补发——修审计"漏报"bug。
|
|
198
|
+
// 静音(quiet/snooze)抑制的不入队(用户显式静音不该被绕过)。key -> {formatted, sid, at}
|
|
199
|
+
const suppressedApprovals = new Map()
|
|
200
|
+
function diag(line) {
|
|
201
|
+
if (!DIAGNOSTICS) return
|
|
202
|
+
try { appendFileSync(DIAG_LOG, `[${new Date().toISOString()}] ${line}\n`, 'utf8') } catch { /* ignore */ }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// 动作通道的诊断**常开**(不受 DIAGNOSTICS 控制):这是唯一一条"用户点了按钮却什么都不发生"
|
|
206
|
+
// 的路径,2026-11-26 首次真人点击拒绝时它静默失败,事后无法定位。只在处理动作文件时写一行,
|
|
207
|
+
// 频率等于用户点按钮的次数,不会刷日志。
|
|
208
|
+
const ACTION_DIAG_LOG = join(process.env.TEMP || process.cwd(), 'dsh-notification-action-diag.log')
|
|
209
|
+
function actionDiag(line) {
|
|
210
|
+
// 测试模式不写生产诊断文件,避免夹具污染真人点击日志
|
|
211
|
+
if (process.env.DSH_NOTIFICATION_NO_TOAST === '1') return
|
|
212
|
+
try { appendFileSync(ACTION_DIAG_LOG, `[${new Date().toISOString()}] ${line}\n`, 'utf8') } catch { /* ignore */ }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export const name = 'dsh-notification'
|
|
216
|
+
// 🔴 每会话独立的「待投递代」计数器(审计 #2)。原来是全局变量:两个会话在同一 tick
|
|
217
|
+
// 完成时,后一个会把前一个的待投递回调作废 → 前一条完成通知永久丢失(实测 2 条只弹 1 条)。
|
|
218
|
+
export function createGenerationGate() {
|
|
219
|
+
const map = new Map()
|
|
220
|
+
const key = (sid) => String(sid ?? '')
|
|
221
|
+
return {
|
|
222
|
+
bump(sid) { const k = key(sid); const n = (map.get(k) || 0) + 1; map.set(k, n); return n },
|
|
223
|
+
now(sid) { return map.get(key(sid)) || 0 },
|
|
224
|
+
drop(sid) { map.delete(key(sid)) },
|
|
225
|
+
clear() { map.clear() },
|
|
226
|
+
size() { return map.size },
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
export const __test = {
|
|
230
|
+
shouldNotify, makeApprovalAnswerer, isSubagent, sanitizeForToast,
|
|
231
|
+
xmlSafe, createGenerationGate,
|
|
232
|
+
dedupeKey, isQuietNow, isSnoozed, priorityOf, shouldNotifyNow, shouldSkipAsCompletion,
|
|
233
|
+
isTypeAllowed, audioFor, isFocusSuppressed, SOUND_CHOICES, DEFAULT_AUDIO_MAP,
|
|
234
|
+
dismissInAppApproval, // 仅测试:验证卡片卸载只依赖网关那一个形状
|
|
235
|
+
get TOAST_SCRIPT() { return TOAST_SCRIPT }, // getter:TOAST_SCRIPT 在本对象之后才初始化
|
|
236
|
+
// 仅供测试:模拟一次已通过令牌校验的拒绝点击,验证 prepend answerer 的 veto 真的生效
|
|
237
|
+
triggerReject(askedId) {
|
|
238
|
+
const waiters = rejectWaiters.get(askedId)
|
|
239
|
+
if (!Array.isArray(waiters) || waiters.length === 0) return false
|
|
240
|
+
const resolve = waiters.shift()
|
|
241
|
+
rejectWaiters.delete(askedId)
|
|
242
|
+
try { resolve('rejected') } catch { /* ignore */ }
|
|
243
|
+
return true
|
|
244
|
+
},
|
|
245
|
+
// 仅供测试:模拟一次已通过令牌校验的批准点击,验证 prepend answerer 真的返回 allowed-once
|
|
246
|
+
triggerApprove(askedId) {
|
|
247
|
+
const waiters = approveWaiters.get(askedId)
|
|
248
|
+
if (!Array.isArray(waiters) || waiters.length === 0) return false
|
|
249
|
+
const resolve = waiters.shift()
|
|
250
|
+
approveWaiters.delete(askedId)
|
|
251
|
+
try { resolve('allowed-once') } catch { /* ignore */ }
|
|
252
|
+
return true
|
|
253
|
+
},
|
|
254
|
+
format: { formatApproval, formatCompletion, formatNeedsInput, formatTurnProblem, formatIdle },
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// 阶段二要用 ctx.webServer / ctx.connection,必须声明 inject(Cordis 护栏:
|
|
258
|
+
// 直接读未声明的服务会抛 "cannot get property without inject" → Host fatal)。
|
|
259
|
+
// 通知投递仍用 node:child_process,不依赖 ctx.subprocess。
|
|
260
|
+
export const inject = ['webServer', 'connection']
|
|
261
|
+
|
|
262
|
+
// 网关是可选依赖:拿不到(或版本里没这个字段)只影响"卡片自动收掉",不影响通知与拒绝本身。
|
|
263
|
+
function wireOptionalGateway(ctx) {
|
|
264
|
+
try {
|
|
265
|
+
if (typeof ctx?.inject !== 'function') return // 测试替身没有 inject:保持现状
|
|
266
|
+
ctx.inject(['typertGateway'], (scope) => {
|
|
267
|
+
typertGateway = scope?.typertGateway || null
|
|
268
|
+
})
|
|
269
|
+
} catch { /* fail-open */ }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ==== 并行路线集成:持久化 + 动作令牌(默认零行为变化)====
|
|
273
|
+
// 持久化文件在 %LOCALAPPDATA% 外置,不存在/损坏时保留 env 基线(fail-open)。
|
|
274
|
+
const settingsStore = createStateStore()
|
|
275
|
+
let settingsGeneration = 0 // 启动期竞态守卫:用户先改过配置就不让旧磁盘值覆盖
|
|
276
|
+
// 启动期竞态修复:磁盘快照读完之前不写盘,否则会把 env 基线整份覆盖掉,
|
|
277
|
+
// 导致用户之前持久化的 quiet/sounds 等字段丢失(复查 P1)。
|
|
278
|
+
let settingsReady = Promise.resolve()
|
|
279
|
+
const persistSettings = () => {
|
|
280
|
+
// 🔴 竞态修复:generation 必须同步自增,否则启动期 load().then 会先跑(generation 仍为 0),
|
|
281
|
+
// 用磁盘旧值覆盖用户刚改的设置,随后又把被覆盖的值写回盘。
|
|
282
|
+
settingsGeneration++
|
|
283
|
+
return settingsReady.then(() => {
|
|
284
|
+
try {
|
|
285
|
+
return settingsStore.save({
|
|
286
|
+
enabled,
|
|
287
|
+
types: ALLOWED_TYPES ? [...ALLOWED_TYPES] : [],
|
|
288
|
+
sounds: { ...AUDIO_MAP },
|
|
289
|
+
quiet: { start: QUIET_START, end: QUIET_END },
|
|
290
|
+
snoozeUntil,
|
|
291
|
+
idleEnabled,
|
|
292
|
+
idleMs,
|
|
293
|
+
approvalGraceMs: APPROVAL_GRACE_MS,
|
|
294
|
+
alwaysNotify: ALWAYS_NOTIFY,
|
|
295
|
+
clickEnabled: CLICK_ENABLED,
|
|
296
|
+
pauseButtons: PAUSE_BUTTONS,
|
|
297
|
+
approvalButtons: APPROVAL_BUTTONS,
|
|
298
|
+
approveEnabled: APPROVE_ENABLED,
|
|
299
|
+
ttsEnabled: TTS_ENABLED,
|
|
300
|
+
ttsVoice: TTS_VOICE,
|
|
301
|
+
customSounds: { ...CUSTOM_SOUNDS },
|
|
302
|
+
historyEnabled: HISTORY_ENABLED,
|
|
303
|
+
mutedSessions: MUTED_SESSIONS.slice(),
|
|
304
|
+
})
|
|
305
|
+
} catch { return false /* fail-open:落盘失败不影响通知 */ }
|
|
306
|
+
})
|
|
307
|
+
}
|
|
308
|
+
// 暂停按钮的一次性令牌:只防重放,伪造最坏后果是改自己的静音/启停。
|
|
309
|
+
const actionVerifier = createTokenVerifier({ now: Date.now })
|
|
310
|
+
// 审批"拒绝":一次性令牌只绑定 askedId,裁决后立即 revoke;TTL 是"未裁决"时的兜底。
|
|
311
|
+
// 30 分钟而不是 2 分钟:这个按钮是给"人不在"的场景用的,真机实测 2 分钟时用户回来点已经过期,
|
|
312
|
+
// 点击静默无效(2026-11-26 首次真人点击事故)。
|
|
313
|
+
const REJECT_TOKEN_TTL_MS = 30 * 60 * 1000
|
|
314
|
+
const rejectStore = createApprovalActionStore({ ttlMs: REJECT_TOKEN_TTL_MS })
|
|
315
|
+
const rejectWaiters = new Map() // askedId -> [resolve]
|
|
316
|
+
// 🔴 2026-11-27 用户明确授权"真就地批准":批准只走下面这条短 TTL、强绑定的通道,
|
|
317
|
+
// 仍然只在原 waterfall 内兑现 'allowed-once',绝不调用 ctx.approval.decide/request。
|
|
318
|
+
// 风险已告知:令牌在 toast URI 里,同权限本机进程可重放;这是用户知情后的选择。
|
|
319
|
+
const approveStore = createApprovalActionStore({ ttlMs: APPROVE_TOKEN_TTL_MS })
|
|
320
|
+
const approveWaiters = new Map() // askedId -> [resolve]
|
|
321
|
+
// tool/call 的 arguments 是批准按钮唯一的参数来源(approval/asked 没有参数)。
|
|
322
|
+
// callId -> { raw, hash, at };只保留最近 512 条,避免长期运行内存膨胀。
|
|
323
|
+
const toolArgs = new Map()
|
|
324
|
+
|
|
325
|
+
// 跳具体会话:dsh://open 只全等匹配并聚焦窗口,不能带 sessionId。
|
|
326
|
+
// toast 正文改走 dshnotify://act?op=open&t=<token>&k=<sessionId>,Host 校验后交给 client 的
|
|
327
|
+
// uiWorkspace.openSession(id)。令牌只防重放,最坏后果是跳到一个会话,不授予任何能力。
|
|
328
|
+
const navVerifier = createTokenVerifier({ now: Date.now })
|
|
329
|
+
const pendingNavigation = { sessionId: '', at: 0 }
|
|
330
|
+
|
|
331
|
+
// 缺口 4/6:本地历史 + 语音播报/自定义音(均默认安全,历史只存固定模板结果)。
|
|
332
|
+
const historyStore = createHistoryStore()
|
|
333
|
+
let TTS_ENABLED = process.env.DSH_NOTIFICATION_TTS === '1'
|
|
334
|
+
let TTS_VOICE = process.env.DSH_NOTIFICATION_TTS_VOICE || ''
|
|
335
|
+
let CUSTOM_SOUNDS = {}
|
|
336
|
+
let HISTORY_ENABLED = true
|
|
337
|
+
|
|
338
|
+
function argsHash(raw) {
|
|
339
|
+
try { return createHash('sha256').update(String(raw ?? '')).digest('hex').slice(0, 16) } catch { return '' }
|
|
340
|
+
}
|
|
341
|
+
function rememberToolArgs(callId, raw) {
|
|
342
|
+
try {
|
|
343
|
+
if (typeof callId !== 'string' || !/^[A-Za-z0-9_.:-]{1,200}$/.test(callId)) return
|
|
344
|
+
toolArgs.set(callId, { raw: String(raw ?? ''), hash: argsHash(raw), at: Date.now() })
|
|
345
|
+
if (toolArgs.size > 512) toolArgs.delete(toolArgs.keys().next().value)
|
|
346
|
+
} catch { /* fail-open */ }
|
|
347
|
+
}
|
|
348
|
+
// 只展示净化后的命令摘要;模型/用户原文绝不直接进 toast XML。
|
|
349
|
+
function commandPreview(raw) {
|
|
350
|
+
try {
|
|
351
|
+
const obj = JSON.parse(String(raw || '{}'))
|
|
352
|
+
const cmd = obj.command ?? obj.cmd ?? obj.input ?? ''
|
|
353
|
+
return typeof cmd === 'string' ? sanitizeForToast(cmd).slice(0, 80) : ''
|
|
354
|
+
} catch { return '' }
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// 空闲提醒状态机:只由 client 活动上报 / 一轮回复完成重置,默认关。
|
|
358
|
+
let idleTracker = createIdleTracker({ thresholdMs: idleMs, enabled: idleEnabled })
|
|
359
|
+
// 设置页改了开关/阈值时重建状态机(createIdleTracker 的 enabled 在构造时捕获)
|
|
360
|
+
const rebuildIdleTracker = () => { idleTracker = createIdleTracker({ thresholdMs: idleMs, enabled: idleEnabled }) }
|
|
361
|
+
|
|
362
|
+
// 焦点状态:client 半身通过 POST /api/dsh-notify/focus 上报,Host 存内存。
|
|
363
|
+
// 结构 { away, sessionId, at };缺省 away=false(fail-open:拿不到上报就照弹,
|
|
364
|
+
// 绝不因为焦点探测失败而把该提醒的吞掉)。
|
|
365
|
+
let focusState = { away: false, sessionId: undefined, at: 0 }
|
|
366
|
+
const FOCUS_PATH = '/api/dsh-notify/focus'
|
|
367
|
+
const STATE_PATH = '/api/dsh-notify/state'
|
|
368
|
+
const DIAG_PATH = '/api/dsh-notify/diag'
|
|
369
|
+
const SNOOZE_PATH = '/api/dsh-notify/snooze'
|
|
370
|
+
const CONFIG_PATH = '/api/dsh-notify/config'
|
|
371
|
+
const IDLE_PATH = '/api/dsh-notify/idle'
|
|
372
|
+
const clientDiag = [] // client 上报的诊断(ring buffer,最多 50 条)
|
|
373
|
+
const FOCUS_FRESH_MS = 5 * 60 * 1000 // 上报超过 5 分钟视为陈旧,退化为 fail-open
|
|
374
|
+
|
|
375
|
+
// 阶段三:观察到的待处理审批(仅用于浮窗展示,不参与裁决)
|
|
376
|
+
const pendingApprovals = new Map() // key -> { toolName, reason, at, sessionId }
|
|
377
|
+
|
|
378
|
+
// 焦点门控纯函数(便于独立测试):返回 true = 该弹,false = 抑制。
|
|
379
|
+
// 规则:只有"焦点上报新鲜 + 用户明确在场 + 正在看的就是这个会话"才抑制;
|
|
380
|
+
// 其余一切情况(离开 / 看别的会话 / 状态陈旧 / 无上报)都返回 true(fail-open)。
|
|
381
|
+
function shouldNotify(fresh, away, focusSid, eventSid) {
|
|
382
|
+
if (!fresh) return true
|
|
383
|
+
if (away) return true
|
|
384
|
+
if (!focusSid || focusSid !== eventSid) return true
|
|
385
|
+
return false
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// ==== P0 集成的纯函数(可单测,不碰 fs/ctx/定时器)====
|
|
389
|
+
|
|
390
|
+
// 去重键纯封装:输出与历史逐字节一致,锁死"同会话不同 turn 都投递"的语义。
|
|
391
|
+
function dedupeKey(kind, sid, instance) {
|
|
392
|
+
return kind + ':' + sid + ':' + instance
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// 静音时段判定(支持跨午夜,如 22:00-07:00)。now 为 Date 实例或毫秒时间戳。
|
|
396
|
+
function isQuietNow(now, startHHMM, endHHMM) {
|
|
397
|
+
if (!startHHMM || !endHHMM) return false
|
|
398
|
+
const m = /^(\d{1,2}):(\d{2})$/.exec(String(startHHMM))
|
|
399
|
+
const n = /^(\d{1,2}):(\d{2})$/.exec(String(endHHMM))
|
|
400
|
+
if (!m || !n) return false // 配置非法 → fail-open(不静音)
|
|
401
|
+
const d = now instanceof Date ? now : new Date(now)
|
|
402
|
+
const cur = d.getHours() * 60 + d.getMinutes()
|
|
403
|
+
const s = (+m[1]) * 60 + (+m[2])
|
|
404
|
+
const e = (+n[1]) * 60 + (+n[2])
|
|
405
|
+
if (s === e) return false
|
|
406
|
+
return s < e ? (cur >= s && cur < e) : (cur >= s || cur < e) // 跨午夜
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// snooze 判定:now < until 即静音;until 非法/过期 → false(fail-open)。
|
|
410
|
+
function isSnoozed(now, snoozeUntil) {
|
|
411
|
+
const t = Number(snoozeUntil)
|
|
412
|
+
return Number.isFinite(t) && t > 0 && Number(now) < t
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// 通知优先级:完成=0,审批/needs-input/错误=1。非完成类永不被完成类覆盖。
|
|
416
|
+
function priorityOf(kind) {
|
|
417
|
+
return kind === 'success' || kind === 'completion' ? 0 : 1
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// 判断抑制是否由焦点造成(供"离开后补发"用):静音造成的抑制不补发。
|
|
421
|
+
function isFocusSuppressed(now, focus, quietActive, snoozeUntil, always, sid) {
|
|
422
|
+
if (quietActive || isSnoozed(now, snoozeUntil)) return false
|
|
423
|
+
if (always) return false
|
|
424
|
+
return shouldNotifyNow(now, focus, quietActive, snoozeUntil, always, sid) === false
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// 类型白名单判定:null=全开;否则 kind 必须在集合内。
|
|
428
|
+
function isTypeAllowed(kind, allowed) {
|
|
429
|
+
if (!allowed || !(allowed instanceof Set) || allowed.size === 0) return true
|
|
430
|
+
return allowed.has(String(kind))
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// 按通知类型选音效(per-event 差异化)。
|
|
434
|
+
function audioFor(kind) {
|
|
435
|
+
return AUDIO_MAP[kind] || 'Notification.IM'
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// 同步冷却窗判定:完成通知是否应因同会话最近的高优先级活动而跳过。
|
|
439
|
+
function shouldSkipAsCompletion(kind, sid, now, lastHighAt, cooldownMs) {
|
|
440
|
+
if (priorityOf(kind) !== 0) return false // 只有完成类受冷却
|
|
441
|
+
const t = Number(lastHighAt)
|
|
442
|
+
return Number.isFinite(t) && t > 0 && (Number(now) - t) < cooldownMs
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// 组合门控:静音(quiet/snooze) > 焦点门控 > ALWAYS_NOTIFY。
|
|
446
|
+
// snoozeUntil/quiet 由调用方传入当前值;返回 true=该弹,false=抑制。
|
|
447
|
+
function shouldNotifyNow(now, focus, quietActive, snoozeUntil, always, sid) {
|
|
448
|
+
if (quietActive) return false
|
|
449
|
+
if (isSnoozed(now, snoozeUntil)) return false
|
|
450
|
+
if (always) return true // ALWAYS_NOTIFY 只反选焦点门控,不能反选静音
|
|
451
|
+
const fresh = Number(now) - Number(focus?.at || 0) < FOCUS_FRESH_MS
|
|
452
|
+
return shouldNotify(fresh, focus?.away === true, focus?.sessionId, sid)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// 阶段三:approval/request waterfall 的"只观察 + 委派"answerer 工厂(纯函数,便于测试)。
|
|
456
|
+
// 硬约束(健康审核员 FINAL 放行条件):
|
|
457
|
+
// - fire-and-forget:绝不 await 通知,否则永不 settle 的通知会把 next() 挡住 → 审批卡死
|
|
458
|
+
// - catch 必须留痕(不能空吞)
|
|
459
|
+
// - finally 里必须 `return next()`:只调不 return → outcome=undefined → normalize 成
|
|
460
|
+
// 'unavailable' → 所有审批被意外否决(C2 测试 T9 已锁死此变体)
|
|
461
|
+
// - next() 每轮只调一次(cordis 有 called 守卫,调两次会抛错)
|
|
462
|
+
function makeApprovalAnswerer(send, log) {
|
|
463
|
+
return function approvalAnswerer(req, next) {
|
|
464
|
+
try {
|
|
465
|
+
void send(req).catch((err) => log('notify failed', err))
|
|
466
|
+
} catch (err) {
|
|
467
|
+
log('sync notify error', err)
|
|
468
|
+
} finally {
|
|
469
|
+
return next()
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// 状态:按会话缓冲最后一轮回复文本(turn/end 不带文本,必须从 assistant/message 取)
|
|
475
|
+
const drafts = new Map() // sessionId -> { turn, text }
|
|
476
|
+
// 去重账本:key = done:<sessionId>:<turn>,带 TTL + 容量上限
|
|
477
|
+
const seen = new Map() // key -> timestamp(ms)
|
|
478
|
+
const DEDUPE_TTL_MS = 30 * 60 * 1000
|
|
479
|
+
const MAX_SEEN = 1024
|
|
480
|
+
|
|
481
|
+
function isDuplicate(key) {
|
|
482
|
+
const now = Date.now()
|
|
483
|
+
const t = seen.get(key)
|
|
484
|
+
if (t !== undefined && now - t < DEDUPE_TTL_MS) return true
|
|
485
|
+
if (seen.size >= MAX_SEEN) {
|
|
486
|
+
for (const [k, v] of seen) if (now - v >= DEDUPE_TTL_MS) seen.delete(k)
|
|
487
|
+
if (seen.size >= MAX_SEEN) {
|
|
488
|
+
const oldest = seen.keys().next().value
|
|
489
|
+
if (oldest !== undefined) seen.delete(oldest)
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
seen.set(key, now)
|
|
493
|
+
return false
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// 把 assistant/message 的 content 里的 text 块拼成纯文本
|
|
497
|
+
function extractText(message) {
|
|
498
|
+
const content = message?.content
|
|
499
|
+
if (!Array.isArray(content)) return ''
|
|
500
|
+
let out = ''
|
|
501
|
+
for (const block of content) {
|
|
502
|
+
if (block?.type === 'text' && typeof block.text === 'string') out += block.text
|
|
503
|
+
}
|
|
504
|
+
return out
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// 把 DSH 的审批 reason 翻译成人话三元组(标题/副标题/正文),供 toast 分层显示。
|
|
508
|
+
// 纯函数,便于测试。输入示例:
|
|
509
|
+
// "escalate sandbox to danger-full-access: 用户明确要求在桌面创建 Word 文件,桌面路径在会话工作区之外"
|
|
510
|
+
// 输出:{ kind:'approval', title:'需要批准 · pwsh', subtitle:'DSH 想在工作区外写入文件', body:'用户请求在桌面创建 Word 文件' }
|
|
511
|
+
function formatApproval(toolName, reason) {
|
|
512
|
+
const tool = String(toolName || 'tool')
|
|
513
|
+
const raw = String(reason || '')
|
|
514
|
+
const modeMatch = raw.match(/escalate sandbox to\s+([\w-]+)\s*:\s*([\s\S]*)/i)
|
|
515
|
+
const mode = modeMatch ? modeMatch[1] : ''
|
|
516
|
+
const justification = sanitizeForToast(modeMatch ? modeMatch[2] : raw)
|
|
517
|
+
const modeText = {
|
|
518
|
+
'danger-full-access': 'DSH 想在工作区外写入文件',
|
|
519
|
+
'workspace-write': 'DSH 想扩大写入范围',
|
|
520
|
+
}
|
|
521
|
+
const subtitle = modeText[mode] || (mode ? 'DSH 请求提升权限:' + mode : 'DSH 需要你批准一项操作')
|
|
522
|
+
|
|
523
|
+
// 正文按行业惯例输出固定人话模板,不逐字展示模型自由生成的 justification
|
|
524
|
+
// (模型会写出"你再次要求提权…所以要一次 danger-full-access 批准"这类流水账+黑话)。
|
|
525
|
+
// 策略:识别意图关键词 → 固定模板;长路径/黑话一律不进正文。
|
|
526
|
+
let body
|
|
527
|
+
const j = justification
|
|
528
|
+
if (/桌面|desktop/i.test(j)) {
|
|
529
|
+
body = '目标:桌面(工作区外)'
|
|
530
|
+
} else if (/工作区外|outside.*workspace|workspace.*outside/i.test(j)) {
|
|
531
|
+
body = '目标:工作区外的路径'
|
|
532
|
+
} else if (/网络|network|联网/i.test(j)) {
|
|
533
|
+
body = '目标:网络访问'
|
|
534
|
+
} else if (j.length > 0 && !/\b(danger|full-access|escalat|sandbox|提权|批准|permission)\b/i.test(j)) {
|
|
535
|
+
// 没有黑话、也不是长流水账:保留清洗后的简短理由(截断到 80 字)
|
|
536
|
+
body = j.length > 80 ? j.slice(0, 80) + '…' : j
|
|
537
|
+
} else {
|
|
538
|
+
body = ''
|
|
539
|
+
}
|
|
540
|
+
return {
|
|
541
|
+
kind: 'approval',
|
|
542
|
+
title: '需要批准 · ' + tool,
|
|
543
|
+
subtitle,
|
|
544
|
+
body: body || '请回到 DSH 查看审批卡片',
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// XML 1.0 里非法的字符 + 孤立代理项(审计 R4)。这两类一旦进 toast XML,
|
|
549
|
+
// XmlDocument.LoadXml 会抛 0xC00CE508,整条通知静默消失,而失败只写进默认关闭的 diag。
|
|
550
|
+
const XML_ILLEGAL_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\uFFFE\uFFFF]/g
|
|
551
|
+
const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
|
|
552
|
+
function xmlSafe(text) {
|
|
553
|
+
return String(text ?? '').replace(LONE_SURROGATE_RE, '').replace(XML_ILLEGAL_RE, '')
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// 把 DSH 回复原文清洗成适合原生 toast 的纯文本摘要(对齐 Claude/Codex 的克制风格)。
|
|
557
|
+
// 去掉:emoji(各种 unicode 符号/表情区)、markdown 强调符、换行/制表、多余空白。
|
|
558
|
+
// 纯函数便于测试。注意:中文/日文等表意文字保留,只剥装饰性符号。
|
|
559
|
+
function sanitizeForToast(text) {
|
|
560
|
+
let s = String(text ?? '')
|
|
561
|
+
// 先剔除 XML 非法码点与孤立代理项(审计 R4:否则整条 toast 解析失败、静默丢失)
|
|
562
|
+
s = xmlSafe(s)
|
|
563
|
+
// 去 emoji / 装饰符号:用 unicode property escape(Node 支持),删掉 Extended_Pictographic + 杂项符号
|
|
564
|
+
try {
|
|
565
|
+
s = s.replace(/[\p{Extended_Pictographic}\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}\u{FE0F}\u{200D}\u{2190}-\u{21FF}\u{2900}-\u{297F}\u{2B00}-\u{2BFF}\u{1F1E6}-\u{1F1FF}]/gu, '')
|
|
566
|
+
} catch { /* 老 Node 不支持 property escape:退化为只删常见 emoji 区 */ s = s.replace(/[\uD83C-\uDBFF][\uDC00-\uDFFF]/g, '') }
|
|
567
|
+
s = s
|
|
568
|
+
.replace(/\*\*|__|`/g, '') // markdown 强调/代码符
|
|
569
|
+
.replace(/^#{1,6}\s*/gm, '') // markdown 标题符
|
|
570
|
+
.replace(/^\s*[-*+]\s+/gm, '') // markdown 列表符
|
|
571
|
+
.replace(/[\r\n\t]+/g, ' ') // 换行/制表 → 空格
|
|
572
|
+
.replace(/\s{2,}/g, ' ') // 连续空白压成一个
|
|
573
|
+
.trim()
|
|
574
|
+
// 截到 140 个码点(审计 R4:按 UTF-16 单元切会把代理对切成孤立代理项,XML 直接失败)
|
|
575
|
+
const cps = Array.from(s)
|
|
576
|
+
if (cps.length > 140) {
|
|
577
|
+
let cut = cps.slice(0, 140).join('')
|
|
578
|
+
const lastStop = Math.max(cut.lastIndexOf('。'), cut.lastIndexOf('!'), cut.lastIndexOf('?'), cut.lastIndexOf('. '), cut.lastIndexOf(' '))
|
|
579
|
+
if (lastStop > 80) cut = cut.slice(0, lastStop + (cut[lastStop] === ' ' ? 0 : 1))
|
|
580
|
+
s = cut.trim() + '…'
|
|
581
|
+
}
|
|
582
|
+
return s
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// 完成任务的三元组:标题=状态,副标题=会话名,正文=回复摘要
|
|
586
|
+
function formatCompletion(title, body) {
|
|
587
|
+
return {
|
|
588
|
+
kind: 'success',
|
|
589
|
+
title: '任务完成 · ' + String(title || 'DSH').slice(0, 40),
|
|
590
|
+
subtitle: '一轮工作已正常结束',
|
|
591
|
+
body: sanitizeForToast(body) || '回到 DSH 查看结果',
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// 子代理过滤(源码实证 SessionHeader:origin==='subagent' || delegationDepth>0)。
|
|
596
|
+
// 主会话通知已覆盖子代理工作,子代理自己不再弹,避免重复打扰。纯函数便于测试。
|
|
597
|
+
function isSubagent(session) {
|
|
598
|
+
const h = session?.header
|
|
599
|
+
return h?.origin === 'subagent' || ((h?.delegationDepth ?? 0) > 0)
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// needs-input(用户在场外提问 / 计划审阅)的三元组。
|
|
603
|
+
// 数据源:tool/call 的 arguments(JSON 文本)。纯函数便于测试。
|
|
604
|
+
function formatNeedsInput(sessionTitle, questions, toolName, isPlan) {
|
|
605
|
+
const first = Array.isArray(questions) ? questions[0] : undefined
|
|
606
|
+
const opts = Array.isArray(first?.options)
|
|
607
|
+
? first.options.map(o => o?.label).filter(Boolean) : []
|
|
608
|
+
const detail = String(first?.question || first?.detail || '')
|
|
609
|
+
.replace(/^\s*#+\s*/, '') // 计划标题行可能残留 markdown #(fail-safe)
|
|
610
|
+
.replace(/\s+/g, ' ').trim()
|
|
611
|
+
const options = opts.length ? '(' + opts.slice(0, 3).join(' / ') + ')' : ''
|
|
612
|
+
const tool = String(toolName || 'tool')
|
|
613
|
+
const subtitle = isPlan ? '计划待你审阅' : 'DSH 在等你输入'
|
|
614
|
+
return {
|
|
615
|
+
kind: 'needs-input',
|
|
616
|
+
title: ('等你回答 · ' + String(sessionTitle || 'DSH')).slice(0, 40),
|
|
617
|
+
subtitle,
|
|
618
|
+
body: sanitizeForToast(detail + options) || '请回到 DSH 查看提问(' + tool + ')',
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// 异常结束(error / max-tokens / blocked / aborted-hook / 未知 kind)的三元组。
|
|
623
|
+
// error 按 code 路由,不解析 message 文本(源码实证 dsh-llm/README.md:73)。纯函数便于测试。
|
|
624
|
+
function formatTurnProblem(reason, sessionTitle, draftText) {
|
|
625
|
+
const k = reason?.kind
|
|
626
|
+
const st = String(sessionTitle || 'DSH').slice(0, 24)
|
|
627
|
+
let title, subtitle, body
|
|
628
|
+
if (k === 'error') {
|
|
629
|
+
const code = String(reason?.error?.code || '')
|
|
630
|
+
// DSH 对非 HarnessError 返回 code='UNKNOWN'(dsh-llm harnessErrorCode);
|
|
631
|
+
// 此时标题显示会话名,避免难看的"出错 · UNKNOWN"
|
|
632
|
+
title = '出错 · ' + (code && code !== 'UNKNOWN' ? code.slice(0, 24) : st)
|
|
633
|
+
subtitle = '一轮工作失败'
|
|
634
|
+
body = String(reason?.error?.message || '').replace(/\s+/g, ' ').trim()
|
|
635
|
+
} else if (k === 'max-tokens') {
|
|
636
|
+
title = 'Token 用尽 · ' + st
|
|
637
|
+
subtitle = '一轮工作因长度上限停止'
|
|
638
|
+
body = '请回到 DSH 续写或换模型'
|
|
639
|
+
} else if (k === 'blocked') {
|
|
640
|
+
title = '被阻塞 · ' + st
|
|
641
|
+
subtitle = '一轮工作无法继续'
|
|
642
|
+
body = String(draftText || '').slice(0, 140)
|
|
643
|
+
} else if (k === 'aborted') {
|
|
644
|
+
title = '需要你关注 · ' + st
|
|
645
|
+
subtitle = 'DSH 工作被中断'
|
|
646
|
+
body = String(reason?.reason?.reason || '请回到 DSH 查看')
|
|
647
|
+
} else {
|
|
648
|
+
title = '需要你关注 · ' + st
|
|
649
|
+
subtitle = '一轮工作异常结束'
|
|
650
|
+
body = '请回到 DSH 查看'
|
|
651
|
+
}
|
|
652
|
+
return {
|
|
653
|
+
kind: 'error',
|
|
654
|
+
title: sanitizeForToast(title).slice(0, 40),
|
|
655
|
+
subtitle,
|
|
656
|
+
body: sanitizeForToast(body) || '请回到 DSH 查看',
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// 空闲提醒的固定人话三元组:不给模型自由文本,不暴露内部阈值/黑话。
|
|
661
|
+
function formatIdle(sessionTitle) {
|
|
662
|
+
return {
|
|
663
|
+
kind: 'idle',
|
|
664
|
+
title: ('等你继续 · ' + String(sessionTitle || 'DSH')).slice(0, 40),
|
|
665
|
+
subtitle: '这轮已经停下一段时间了',
|
|
666
|
+
body: '回到 DSH 继续,或开始新任务',
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// PowerShell 5.1 脚本:用 WinRT ToastNotificationManager 弹原生 toast。
|
|
671
|
+
// 传值走环境变量 + \uXXXX 纯 ASCII,绕开 PS 5.1 的 GBK 管道乱码;
|
|
672
|
+
// XML 转义用 SecurityElement::Escape 防注入。自建 AUMID 'DshNotification'(已注册)。
|
|
673
|
+
// 三行 text(标题/副标题/正文)+ 可配置音效。
|
|
674
|
+
// 🔴 故意不放 <image>:appLogoOverride 会变成正文大圆圈;鲸鱼改由 AUMID 身份链
|
|
675
|
+
// (纯路径 IconUri + 带 AUMID 属性的快捷方式 + 进程声明)显示在标题栏左侧小图标位。
|
|
676
|
+
const TOAST_SCRIPT = `$ErrorActionPreference = 'Stop'
|
|
677
|
+
# Declare this process AUMID: without it Windows cannot resolve toast identity -> blank attribution icon
|
|
678
|
+
Add-Type -TypeDefinition @'
|
|
679
|
+
using System;
|
|
680
|
+
using System.Runtime.InteropServices;
|
|
681
|
+
public static class DshAumid {
|
|
682
|
+
[DllImport("shell32.dll", SetLastError = true)]
|
|
683
|
+
public static extern void SetCurrentProcessExplicitAppUserModelID([MarshalAs(UnmanagedType.LPWStr)] string AppID);
|
|
684
|
+
}
|
|
685
|
+
'@
|
|
686
|
+
[DshAumid]::SetCurrentProcessExplicitAppUserModelID('DshNotification')
|
|
687
|
+
function Decode-UE([string]$s) {
|
|
688
|
+
if (-not $s) { return '' }
|
|
689
|
+
return [regex]::Replace($s, '\\\\u([0-9a-fA-F]{4})', {
|
|
690
|
+
param($m) [string][char][Convert]::ToInt32($m.Groups[1].Value, 16)
|
|
691
|
+
})
|
|
692
|
+
}
|
|
693
|
+
$t = [System.Security.SecurityElement]::Escape((Decode-UE $env:DSH_TOAST_TITLE))
|
|
694
|
+
$s = [System.Security.SecurityElement]::Escape((Decode-UE $env:DSH_TOAST_SUBTITLE))
|
|
695
|
+
$b = [System.Security.SecurityElement]::Escape((Decode-UE $env:DSH_TOAST_BODY))
|
|
696
|
+
$audio = $env:DSH_TOAST_AUDIO
|
|
697
|
+
if (-not $audio) { $audio = 'Notification.IM' }
|
|
698
|
+
$audioXml = if ($audio -eq 'None') { '<audio silent="true"/>' } else { '<audio src="ms-winsoundevent:' + $audio + '" loop="false"/>' }
|
|
699
|
+
# 点击回跳(实验性,默认关):点 toast 用协议激活拉起 DSH。非打包 AUMID 的协议激活行为
|
|
700
|
+
# 需真机验证——设 DSH_NOTIFICATION_CLICK=1 开启。launch 指向已注册的 dsh:// 协议。
|
|
701
|
+
$click = $env:DSH_TOAST_CLICK
|
|
702
|
+
$launchXml = ''
|
|
703
|
+
$launch = $env:DSH_TOAST_LAUNCH
|
|
704
|
+
if (-not $launch) { $launch = 'dsh://open' }
|
|
705
|
+
if ($click -eq '1') { $launchXml = ' activationType="protocol" launch="' + [System.Security.SecurityElement]::Escape($launch) + '"' }
|
|
706
|
+
# 审批通知驻留:scenario="reminder" 让 toast 停在屏幕上直到用户处理;duration="long" 是兜底(约 25s)。
|
|
707
|
+
# 未打包应用上平台可能忽略 reminder,此时至少 long 生效——fail-open,不影响投递本身。
|
|
708
|
+
$stickyXml = ''
|
|
709
|
+
if ($env:DSH_TOAST_STICKY -eq '1') { $stickyXml = ' scenario="reminder" duration="long"' }
|
|
710
|
+
# toast 按钮(默认关):XML 已由 Node 侧转义,这里只还原 unicode 转义,不再二次转义。
|
|
711
|
+
# 关闭时不追加任何内容,保证默认 toast XML 与改动前逐字节一致。
|
|
712
|
+
$bodyXml = $audioXml
|
|
713
|
+
if ($env:DSH_TOAST_ACTIONS) { $bodyXml = $audioXml + [Environment]::NewLine + (Decode-UE $env:DSH_TOAST_ACTIONS) }
|
|
714
|
+
$xml = @"
|
|
715
|
+
<toast$launchXml$stickyXml>
|
|
716
|
+
<visual><binding template="ToastGeneric">
|
|
717
|
+
<text>$t</text>
|
|
718
|
+
<text>$s</text>
|
|
719
|
+
<text>$b</text>
|
|
720
|
+
</binding></visual>
|
|
721
|
+
$bodyXml
|
|
722
|
+
</toast>
|
|
723
|
+
"@
|
|
724
|
+
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType=WindowsRuntime] | Out-Null
|
|
725
|
+
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom, ContentType=WindowsRuntime] | Out-Null
|
|
726
|
+
$doc = New-Object Windows.Data.Xml.Dom.XmlDocument
|
|
727
|
+
$doc.LoadXml($xml)
|
|
728
|
+
$toast = New-Object Windows.UI.Notifications.ToastNotification($doc)
|
|
729
|
+
$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('DshNotification')
|
|
730
|
+
$notifier.Show($toast)
|
|
731
|
+
`
|
|
732
|
+
|
|
733
|
+
// 统一投递入口:类型白名单过滤 + per-event 音效。三处通知共用。
|
|
734
|
+
// onDelivered 仅在类型通过白名单、真的要投递时调用——用于冷却窗标记(修审计 A:
|
|
735
|
+
// 被过滤掉的类型不能标记高优先级,否则会静默吞掉后续完成通知)。
|
|
736
|
+
function deliverTyped(formatted, opts = {}) {
|
|
737
|
+
if (!formatted) return
|
|
738
|
+
// 🔔 按会话免打扰:命中会话的通知像全局静音一样直接丢弃——不弹 toast、不写历史、
|
|
739
|
+
// 不播 TTS/自定义音,也不排队补发。只拦 OS toast;审批/提问的应用内卡片由 DSH 自己管,
|
|
740
|
+
// waterfall 与裁决逻辑完全不动。
|
|
741
|
+
const sid = opts.sessionId
|
|
742
|
+
if (typeof sid === 'string' && MUTED_SESSIONS.includes(sid)) {
|
|
743
|
+
diag('suppressed by muted session: ' + sid.slice(0, 40))
|
|
744
|
+
return
|
|
745
|
+
}
|
|
746
|
+
// 空闲提醒有自己的开关,不该被四类类型白名单误杀;其它类型照旧过滤。
|
|
747
|
+
if (!opts.skipTypeFilter && !isTypeAllowed(formatted.kind, ALLOWED_TYPES)) return
|
|
748
|
+
if (typeof opts.onDelivered === 'function') {
|
|
749
|
+
try { opts.onDelivered() } catch { /* fail-open */ }
|
|
750
|
+
}
|
|
751
|
+
const { onDelivered, actionsXml, skipTypeFilter, ...rest } = opts
|
|
752
|
+
// 🔴 跳具体会话:所有通知类型统一生成 launch(审批 builder 传入的显式值优先)。
|
|
753
|
+
// 之前只有审批通知带 sessionId,完成/提问/出错/空闲都只聚焦窗口。
|
|
754
|
+
if (CLICK_ENABLED && !rest.launch && typeof sid === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(sid)) {
|
|
755
|
+
const navToken = navVerifier.issue()
|
|
756
|
+
if (navToken) {
|
|
757
|
+
rest.launch = 'dshnotify://act?op=open&t=' + encodeURIComponent(navToken) + '&k=' + encodeURIComponent(sid)
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
let resolvedActions = actionsXml || ''
|
|
761
|
+
// 暂停按钮默认关;审批通知若显式传了"回到 DSH"按钮则以显式值为准(避免超过 5 个按钮)。
|
|
762
|
+
if (!resolvedActions && PAUSE_BUTTONS) {
|
|
763
|
+
try { resolvedActions = formatActionXml(buildToastActions({ token: actionVerifier.issue() })) } catch { /* fail-open */ }
|
|
764
|
+
}
|
|
765
|
+
// 历史:只记录固定人话模板的结果,禁止把模型/用户原文、token、凭据写进文件。
|
|
766
|
+
if (HISTORY_ENABLED && process.env.DSH_NOTIFICATION_NO_TOAST !== '1') {
|
|
767
|
+
try {
|
|
768
|
+
void historyStore.add({
|
|
769
|
+
ts: Date.now(),
|
|
770
|
+
kind: formatted.kind,
|
|
771
|
+
title: String(formatted.title || '').slice(0, 200),
|
|
772
|
+
subtitle: String(formatted.subtitle || '').slice(0, 300),
|
|
773
|
+
sessionId: opts.sessionId,
|
|
774
|
+
})
|
|
775
|
+
} catch { /* fail-open */ }
|
|
776
|
+
}
|
|
777
|
+
// 外部音/TTS 与 toast 同源会双响:启用任一就把 toast 音设为静音,由旁路脚本发声。
|
|
778
|
+
// 🔴 复查 P2:脚本文件缺失时不能把 toast 也静音(否则通知完全无声)。
|
|
779
|
+
const customPath = typeof CUSTOM_SOUNDS[formatted.kind] === 'string' ? CUSTOM_SOUNDS[formatted.kind] : ''
|
|
780
|
+
const selectedSound = audioFor(formatted.kind)
|
|
781
|
+
const loopWav = LOOP_SOUND_FALLBACK[selectedSound]
|
|
782
|
+
const loopPath = loopWav ? join(process.env.WINDIR || 'C:\\Windows', 'Media', loopWav) : ''
|
|
783
|
+
// 用户选了自定义文件优先;否则 Looping* 走系统 wav 近似(和试听一致),保证真有声音
|
|
784
|
+
const effectivePath = customPath || loopPath
|
|
785
|
+
const canPlayFile = !!effectivePath && existsSync(PLAY_FILE_SCRIPT) && existsSync(effectivePath)
|
|
786
|
+
const ttsWanted = TTS_ENABLED
|
|
787
|
+
const canSpeak = ttsWanted && existsSync(SPEAK_SCRIPT)
|
|
788
|
+
const tts = canSpeak
|
|
789
|
+
? { text: [formatted.title, formatted.subtitle, formatted.body].filter(Boolean).join('。'), voice: TTS_VOICE }
|
|
790
|
+
: null
|
|
791
|
+
if (ttsWanted && !canSpeak) diag('TTS skipped: speak.ps1 missing, keeping toast sound')
|
|
792
|
+
if (customPath && !canPlayFile) diag('custom audio skipped: script or audio file missing, keeping toast sound')
|
|
793
|
+
// NO_TOAST=1 是测试模式,不能把假日志写进生产诊断文件
|
|
794
|
+
if (loopPath && canPlayFile && !customPath && process.env.DSH_NOTIFICATION_NO_TOAST !== '1') {
|
|
795
|
+
actionDiag('loop sound fallback: ' + selectedSound + ' -> ' + loopPath)
|
|
796
|
+
}
|
|
797
|
+
return deliver(formatted.title, formatted.subtitle, formatted.body, {
|
|
798
|
+
audio: (canPlayFile || canSpeak) ? 'None' : selectedSound,
|
|
799
|
+
...rest,
|
|
800
|
+
actionsXml: resolvedActions,
|
|
801
|
+
...(effectivePath ? { audioFile: effectivePath } : {}),
|
|
802
|
+
...(tts ? { tts } : {}),
|
|
803
|
+
})
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// 把字符串编码成 \uXXXX 纯 ASCII(UTF-16 码元逐个编码)
|
|
807
|
+
function toUnicodeEscapes(s) {
|
|
808
|
+
let out = ''
|
|
809
|
+
const str = String(s ?? '')
|
|
810
|
+
for (let i = 0; i < str.length; i++) {
|
|
811
|
+
out += '\\u' + str.charCodeAt(i).toString(16).padStart(4, '0')
|
|
812
|
+
}
|
|
813
|
+
return out
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// 试听:响一次就够,不等子进程(最多 2.5s),失败只写诊断,绝不 throw 进 cordis fiber。
|
|
817
|
+
function previewSound(sound) {
|
|
818
|
+
if (sound === 'None') return false // 静音选项没有声音可试听,静默成功
|
|
819
|
+
if (process.env.DSH_NOTIFICATION_NO_TOAST === '1') return false // 测试期不真出声
|
|
820
|
+
const now = Date.now()
|
|
821
|
+
if (now - lastPreviewAt < PREVIEW_MIN_GAP_MS) return false // 快速翻选项时合并
|
|
822
|
+
lastPreviewAt = now
|
|
823
|
+
try {
|
|
824
|
+
const child = spawn(
|
|
825
|
+
'powershell.exe',
|
|
826
|
+
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', PREVIEW_SCRIPT, '-Sound', sound],
|
|
827
|
+
{ stdio: 'ignore', windowsHide: true },
|
|
828
|
+
)
|
|
829
|
+
child.on('error', (e) => diag('preview spawn error: ' + e.message))
|
|
830
|
+
child.on('exit', (code) => diag('preview exit code=' + code))
|
|
831
|
+
if (typeof child.unref === 'function') child.unref()
|
|
832
|
+
return true
|
|
833
|
+
} catch (e) {
|
|
834
|
+
diag('preview FAILED: ' + (e?.message || String(e)))
|
|
835
|
+
return false
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// 枚举本机已安装语音(TTS 下拉用)。读 stdout,超时 4s,失败返回空数组(fail-open)。
|
|
840
|
+
function listVoices() {
|
|
841
|
+
return new Promise((resolve) => {
|
|
842
|
+
let settled = false
|
|
843
|
+
const finish = (voices) => { if (!settled) { settled = true; resolve(voices) } }
|
|
844
|
+
try {
|
|
845
|
+
const child = spawn('powershell.exe', [
|
|
846
|
+
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', SPEAK_SCRIPT, '-List',
|
|
847
|
+
], { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })
|
|
848
|
+
let out = ''
|
|
849
|
+
child.stdout?.on('data', (c) => { out += c; if (out.length > 8192) child.kill() })
|
|
850
|
+
const timer = setTimeout(() => { try { child.kill() } catch { /* ignore */ } }, 4000)
|
|
851
|
+
child.on('error', () => { clearTimeout(timer); finish([]) })
|
|
852
|
+
child.on('close', () => {
|
|
853
|
+
clearTimeout(timer)
|
|
854
|
+
const names = String(out).split(/\r?\n/).map(s => s.trim()).filter(Boolean).slice(0, 32)
|
|
855
|
+
finish(names)
|
|
856
|
+
})
|
|
857
|
+
} catch { finish([]) }
|
|
858
|
+
})
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// 外部音频/TTS:与 toast 完全解耦的旁路播放。失败只写诊断;不 await、不占住 fiber。
|
|
862
|
+
// 文本/路径只走环境变量(不拼命令行),路径由 play-file.ps1 自己再校验一次。
|
|
863
|
+
function spawnExternalAudio(opts) {
|
|
864
|
+
if (process.env.DSH_NOTIFICATION_NO_TOAST === '1') return
|
|
865
|
+
const jobs = []
|
|
866
|
+
if (opts.audioFile && typeof opts.audioFile === 'string' && existsSync(PLAY_FILE_SCRIPT)) {
|
|
867
|
+
actionDiag('custom audio spawn: ' + String(opts.audioFile).slice(0, 120))
|
|
868
|
+
jobs.push([PLAY_FILE_SCRIPT, { DSH_NOTIFICATION_AUDIO_FILE: opts.audioFile }])
|
|
869
|
+
}
|
|
870
|
+
if (opts.tts && typeof opts.tts.text === 'string' && opts.tts.text && existsSync(SPEAK_SCRIPT)) {
|
|
871
|
+
jobs.push([SPEAK_SCRIPT, {
|
|
872
|
+
DSH_NOTIFICATION_TTS_TEXT: toUnicodeEscapes(opts.tts.text),
|
|
873
|
+
DSH_NOTIFICATION_TTS_VOICE: opts.tts.voice || '',
|
|
874
|
+
}])
|
|
875
|
+
}
|
|
876
|
+
for (const [script, extra] of jobs) {
|
|
877
|
+
try {
|
|
878
|
+
const child = spawn('powershell.exe', [
|
|
879
|
+
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script,
|
|
880
|
+
], { stdio: 'ignore', windowsHide: true, env: { ...process.env, ...extra } })
|
|
881
|
+
child.on('error', (e) => {
|
|
882
|
+
diag('external audio spawn error: ' + e.message)
|
|
883
|
+
actionDiag('external audio spawn error: ' + e.message)
|
|
884
|
+
})
|
|
885
|
+
child.on('exit', (code) => actionDiag('external audio exit=' + code))
|
|
886
|
+
if (typeof child.unref === 'function') child.unref()
|
|
887
|
+
} catch (e) {
|
|
888
|
+
diag('external audio FAILED: ' + (e?.message || String(e)))
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// 清掉上次进程异常退出留下的 toast 脚本(审计 #21)。只删 24 小时前的,
|
|
894
|
+
// 避免误删同机另一个实例正在解析的文件。
|
|
895
|
+
function cleanupStaleToastScripts() {
|
|
896
|
+
try {
|
|
897
|
+
const dir = process.env.TEMP || process.cwd()
|
|
898
|
+
for (const name of readdirSync(dir)) {
|
|
899
|
+
if (!/^dsh-notification-toast-\d+-[a-z0-9]+-[a-f0-9]{8}\.ps1$/.test(name)) continue
|
|
900
|
+
const p = join(dir, name)
|
|
901
|
+
try {
|
|
902
|
+
if (Date.now() - statSync(p).mtimeMs > 86400000) unlinkSync(p)
|
|
903
|
+
} catch { /* ignore */ }
|
|
904
|
+
}
|
|
905
|
+
} catch { /* ignore */ }
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
async function deliver(title, subtitle, body, opts = {}) {
|
|
909
|
+
// 兼容旧调用:deliver(title, body) 两参数时,第二个其实是 body
|
|
910
|
+
if (subtitle !== undefined && body === undefined) { body = subtitle; subtitle = '' }
|
|
911
|
+
// 兜底:标题(含会话名)/副标题/正文都可能绕过 sanitizeForToast(审批预览、空闲提醒等),
|
|
912
|
+
// 统一过一遍 XML 非法字符过滤,否则一条含 U+0001 的标题就能让整条 toast 静默消失(审计 R4)。
|
|
913
|
+
title = xmlSafe(title)
|
|
914
|
+
subtitle = xmlSafe(subtitle)
|
|
915
|
+
body = xmlSafe(body)
|
|
916
|
+
const audio = opts.audio || 'Notification.IM'
|
|
917
|
+
const actionsXml = opts.actionsXml || '' // 已由调用方生成并转义;空串=无按钮
|
|
918
|
+
// 测试开关:设 DSH_NOTIFICATION_NO_TOAST=1 时跳过 spawn(避免测试时真弹窗污染)
|
|
919
|
+
if (process.env.DSH_NOTIFICATION_NO_TOAST === '1') return
|
|
920
|
+
// 整个函数体都在 try 里:任何同步抛错(含 spawn 本身)都不能冲进 cordis fiber,
|
|
921
|
+
// 否则 Host 会 fatal load failure(已踩两次坑:inject 缺失、subprocess spec 形状)。
|
|
922
|
+
// 改用 Node 原生 child_process:Host 是普通 Node 进程,不依赖 DSH 的 subprocess 服务,
|
|
923
|
+
// 参数形状完全可控。fail-open:通知失败绝不影响会话。
|
|
924
|
+
let scriptPath
|
|
925
|
+
try {
|
|
926
|
+
diag('deliver spawn: ' + title.slice(0, 60))
|
|
927
|
+
// 🔴 真机修复:用 -File + 临时脚本文件,不用 -Command 内嵌。
|
|
928
|
+
// -Command 下 \uXXXX 正则的转义层数对不上 → 显示字面 "\u4efb\u52a1..."(一堆码)。
|
|
929
|
+
// 烟测证实 -File 方式解码正常(当时看到了正确的中文)。
|
|
930
|
+
// 🔴 每次投递一个独立脚本文件(审计 #3):原来共用 dsh-notification-toast-<pid>.ps1,
|
|
931
|
+
// 两条通知投递时间接近时,后一条会截断前一条正在被 PowerShell 解析的脚本,
|
|
932
|
+
// 先退出的 finally 又会删掉后一条还要用的文件 → 其中一条显示错内容或干脆不弹。
|
|
933
|
+
scriptPath = join(
|
|
934
|
+
process.env.TEMP || process.cwd(),
|
|
935
|
+
`dsh-notification-toast-${process.pid}-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}.ps1`,
|
|
936
|
+
)
|
|
937
|
+
// 🔴 PS 5.1 无 BOM + 非 ASCII 会按 GBK 解码:脚本里含中文注释时,
|
|
938
|
+
// 后面的 $launchXml / $audioXml 会被破坏(实测 launch 消失 = 点击回跳一直没生效)。
|
|
939
|
+
// 必须写 UTF-8 BOM。edit/write 工具改本文件后也要确认源码本身没丢 BOM 语义(源码是 JS,不受此限)。
|
|
940
|
+
writeFileSync(scriptPath, '\uFEFF' + TOAST_SCRIPT, 'utf8')
|
|
941
|
+
const child = spawn(
|
|
942
|
+
'powershell.exe',
|
|
943
|
+
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
|
|
944
|
+
{
|
|
945
|
+
cwd: process.env.TEMP || process.cwd(),
|
|
946
|
+
stdio: 'ignore',
|
|
947
|
+
windowsHide: true,
|
|
948
|
+
env: {
|
|
949
|
+
...process.env,
|
|
950
|
+
DSH_TOAST_TITLE: toUnicodeEscapes(title),
|
|
951
|
+
DSH_TOAST_SUBTITLE: toUnicodeEscapes(subtitle || ''),
|
|
952
|
+
DSH_TOAST_BODY: toUnicodeEscapes(body),
|
|
953
|
+
DSH_TOAST_AUDIO: audio || 'Notification.IM',
|
|
954
|
+
DSH_TOAST_CLICK: CLICK_ENABLED ? '1' : '0',
|
|
955
|
+
DSH_TOAST_LAUNCH: opts.launch || 'dsh://open',
|
|
956
|
+
DSH_TOAST_STICKY: opts.sticky ? '1' : '0',
|
|
957
|
+
// 关闭时连变量都不写入,保证默认态 env 与改动前一致
|
|
958
|
+
...(actionsXml ? { DSH_TOAST_ACTIONS: toUnicodeEscapes(actionsXml) } : {}),
|
|
959
|
+
},
|
|
960
|
+
},
|
|
961
|
+
)
|
|
962
|
+
// TTS / 本地自定义音:与 toast 并行、不等待;音频由脚本自己校验,失败不影响通知。
|
|
963
|
+
spawnExternalAudio(opts)
|
|
964
|
+
await new Promise((resolve) => {
|
|
965
|
+
const timer = setTimeout(resolve, 15000)
|
|
966
|
+
child.on('error', (e) => { diag('spawn error: ' + e.message); clearTimeout(timer); resolve() })
|
|
967
|
+
child.on('exit', (code) => { diag('spawn exit code=' + code); clearTimeout(timer); resolve() })
|
|
968
|
+
})
|
|
969
|
+
} catch (e) {
|
|
970
|
+
diag('deliver FAILED: ' + (e?.message || String(e)))
|
|
971
|
+
// fail-open:通知失败不影响会话,绝不 throw 进 cordis fiber
|
|
972
|
+
} finally {
|
|
973
|
+
if (scriptPath) { try { unlinkSync(scriptPath) } catch { /* ignore */ } }
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
export function apply(ctx) {
|
|
978
|
+
cleanupStaleToastScripts()
|
|
979
|
+
wireOptionalGateway(ctx)
|
|
980
|
+
// 启动时加载持久化设置:文件不存在/损坏时用 env 当前值作基线(对抗审查 P0 修复)。
|
|
981
|
+
const envBaseline = {
|
|
982
|
+
enabled,
|
|
983
|
+
types: ALLOWED_TYPES ? [...ALLOWED_TYPES] : [],
|
|
984
|
+
sounds: { ...AUDIO_MAP },
|
|
985
|
+
quiet: { start: QUIET_START, end: QUIET_END },
|
|
986
|
+
snoozeUntil,
|
|
987
|
+
idleEnabled,
|
|
988
|
+
idleMs,
|
|
989
|
+
approvalGraceMs: APPROVAL_GRACE_MS,
|
|
990
|
+
alwaysNotify: ALWAYS_NOTIFY,
|
|
991
|
+
clickEnabled: CLICK_ENABLED,
|
|
992
|
+
pauseButtons: PAUSE_BUTTONS,
|
|
993
|
+
approvalButtons: APPROVAL_BUTTONS,
|
|
994
|
+
approveEnabled: APPROVE_ENABLED,
|
|
995
|
+
ttsEnabled: TTS_ENABLED,
|
|
996
|
+
ttsVoice: TTS_VOICE,
|
|
997
|
+
customSounds: { ...CUSTOM_SOUNDS },
|
|
998
|
+
historyEnabled: HISTORY_ENABLED,
|
|
999
|
+
mutedSessions: MUTED_SESSIONS.slice(),
|
|
1000
|
+
}
|
|
1001
|
+
settingsReady = settingsStore.load(envBaseline)
|
|
1002
|
+
.then((s) => {
|
|
1003
|
+
if (settingsGeneration !== 0) return // 用户已在启动期改过配置:不让旧磁盘值反向覆盖
|
|
1004
|
+
try {
|
|
1005
|
+
enabled = s.enabled
|
|
1006
|
+
ALLOWED_TYPES = s.types.length ? new Set(s.types) : null
|
|
1007
|
+
AUDIO_MAP = { ...s.sounds }
|
|
1008
|
+
QUIET_START = s.quiet.start
|
|
1009
|
+
QUIET_END = s.quiet.end
|
|
1010
|
+
snoozeUntil = s.snoozeUntil
|
|
1011
|
+
if (typeof s.idleEnabled === 'boolean') idleEnabled = s.idleEnabled
|
|
1012
|
+
if (Number.isFinite(s.idleMs)) idleMs = clampIdleMs(s.idleMs)
|
|
1013
|
+
if (Number.isFinite(s.approvalGraceMs) && s.approvalGraceMs >= 0 && s.approvalGraceMs <= 60000) APPROVAL_GRACE_MS = s.approvalGraceMs
|
|
1014
|
+
if (typeof s.alwaysNotify === 'boolean') ALWAYS_NOTIFY = s.alwaysNotify
|
|
1015
|
+
if (typeof s.clickEnabled === 'boolean') CLICK_ENABLED = s.clickEnabled
|
|
1016
|
+
PAUSE_BUTTONS = false // 用户认为 5 个按钮太丑:界面已撤掉,配置文件也不再能打开它
|
|
1017
|
+
if (typeof s.approvalButtons === 'boolean') APPROVAL_BUTTONS = s.approvalButtons
|
|
1018
|
+
if (typeof s.approveEnabled === 'boolean') APPROVE_ENABLED = s.approveEnabled
|
|
1019
|
+
if (typeof s.ttsEnabled === 'boolean') TTS_ENABLED = s.ttsEnabled
|
|
1020
|
+
if (typeof s.ttsVoice === 'string') TTS_VOICE = s.ttsVoice
|
|
1021
|
+
if (s.customSounds && typeof s.customSounds === 'object') CUSTOM_SOUNDS = { ...s.customSounds }
|
|
1022
|
+
if (typeof s.historyEnabled === 'boolean') HISTORY_ENABLED = s.historyEnabled
|
|
1023
|
+
// 🔔 免打扰会话从磁盘恢复(load 以 envBaseline 为基线,文件缺失时保留 env 初值)
|
|
1024
|
+
if (Array.isArray(s.mutedSessions)) MUTED_SESSIONS = normalizeMutedSessions(s.mutedSessions, false)
|
|
1025
|
+
// 🔴 持久化恢复后必须同步 watcher:否则重启后按钮在、但没人消费动作文件(对抗审查 P0)
|
|
1026
|
+
syncActionWatcher()
|
|
1027
|
+
rebuildIdleTracker()
|
|
1028
|
+
} catch { /* fail-open:保留 env 值 */ }
|
|
1029
|
+
})
|
|
1030
|
+
// 🔴 复查 P1:historyStore.load() 之前生产从未调用 → 重启后内存为空,下一条通知
|
|
1031
|
+
// 把整份 history.json 覆盖成 1 条,"7 天/200 条"保留策略也等于没跑。这里启动时加载一次。
|
|
1032
|
+
.then(() => historyStore.load())
|
|
1033
|
+
.catch(() => {}) // 防止未来实现改动导致未处理 rejection
|
|
1034
|
+
|
|
1035
|
+
// /quiet 命令(用户一键静音入口)——用子 fiber 注册,主 fiber 的 inject 完全不动。
|
|
1036
|
+
// 根因修正:input 必须是 {hint:string}(传字符串会 TypeError → fiber FAILED → 通知全无)。
|
|
1037
|
+
// 子 fiber 隔离:即使 commands 服务某天不可用,也只有 /quiet 挂,四类通知照常。
|
|
1038
|
+
try {
|
|
1039
|
+
ctx.inject(['commands'], (scoped) => {
|
|
1040
|
+
scoped.effect(() => scoped.commands.register({
|
|
1041
|
+
name: 'quiet',
|
|
1042
|
+
description: '静音 DSH 通知 N 分钟(默认 30;/quiet 0 取消)',
|
|
1043
|
+
input: { hint: '分钟数(可选,0=取消静音)' },
|
|
1044
|
+
handler: ({ rawInput } = {}) => {
|
|
1045
|
+
try {
|
|
1046
|
+
const m = Number(String(rawInput ?? '').trim() || 30)
|
|
1047
|
+
const minutes = Number.isFinite(m) && m >= 0 && m <= 1440 ? m : 30
|
|
1048
|
+
snoozeUntil = minutes === 0 ? 0 : Date.now() + minutes * 60 * 1000
|
|
1049
|
+
persistSettings()
|
|
1050
|
+
return { kind: 'success', text: minutes === 0 ? '已取消静音' : `已静音 ${minutes} 分钟` }
|
|
1051
|
+
} catch { return { kind: 'success', text: '静音设置失败' } }
|
|
1052
|
+
},
|
|
1053
|
+
}), 'dsh-notification: quiet command')
|
|
1054
|
+
})
|
|
1055
|
+
} catch { /* commands 不可用:子 fiber 注册失败不影响主通知 */ }
|
|
1056
|
+
|
|
1057
|
+
// Host ↔ Client 通信路由:client 上报焦点/在场状态。
|
|
1058
|
+
// 必须自带 requestRejection 围栏:注册更长的 /api 路径会绕开内核鉴权(实测)。
|
|
1059
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1060
|
+
kind: 'exact',
|
|
1061
|
+
path: FOCUS_PATH,
|
|
1062
|
+
handler: (req, res) => {
|
|
1063
|
+
try {
|
|
1064
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1065
|
+
if (rejection !== undefined) {
|
|
1066
|
+
res.statusCode = rejection
|
|
1067
|
+
res.end()
|
|
1068
|
+
return
|
|
1069
|
+
}
|
|
1070
|
+
if (req.method === 'GET') {
|
|
1071
|
+
res.statusCode = 200
|
|
1072
|
+
res.setHeader('content-type', 'application/json')
|
|
1073
|
+
res.end(JSON.stringify(focusState))
|
|
1074
|
+
return
|
|
1075
|
+
}
|
|
1076
|
+
if (req.method !== 'POST') {
|
|
1077
|
+
res.statusCode = 405
|
|
1078
|
+
res.end()
|
|
1079
|
+
return
|
|
1080
|
+
}
|
|
1081
|
+
let raw = ''
|
|
1082
|
+
req.on('data', (chunk) => {
|
|
1083
|
+
raw += chunk
|
|
1084
|
+
if (raw.length > 8192) req.destroy() // 防滥用
|
|
1085
|
+
})
|
|
1086
|
+
req.on('end', () => {
|
|
1087
|
+
try {
|
|
1088
|
+
const body = JSON.parse(raw)
|
|
1089
|
+
focusState = {
|
|
1090
|
+
away: body.away === true,
|
|
1091
|
+
sessionId: typeof body.sessionId === 'string' ? body.sessionId : undefined,
|
|
1092
|
+
at: Date.now(),
|
|
1093
|
+
}
|
|
1094
|
+
// 修审计"漏报":用户离开后补发此前因在场而挂起的审批 toast。
|
|
1095
|
+
if (focusState.away && suppressedApprovals.size > 0) {
|
|
1096
|
+
for (const [k, item] of suppressedApprovals) {
|
|
1097
|
+
// 只补 5 分钟内的、且仍未被裁决的
|
|
1098
|
+
if (Date.now() - item.at > 5 * 60 * 1000 || !pendingApprovals.has(k)) { suppressedApprovals.delete(k); continue }
|
|
1099
|
+
// 🔴 审计 #4:补发前必须再判一次总开关/静音。用户可能在这段时间里关掉了通知、
|
|
1100
|
+
// 或进了静音时段——原来这条路径直接 deliverTyped,会出现"我明明关了它还在弹"。
|
|
1101
|
+
if (!enabled || isQuietNow(Date.now(), QUIET_START, QUIET_END) || isSnoozed(Date.now(), snoozeUntil)) {
|
|
1102
|
+
suppressedApprovals.delete(k)
|
|
1103
|
+
continue
|
|
1104
|
+
}
|
|
1105
|
+
const { actionsXml, launch, preview } = buildApprovalToast(k)
|
|
1106
|
+
const shown = preview ? { ...item.formatted, body: (item.formatted.body + ' · 将执行:' + preview).slice(0, 140) } : item.formatted
|
|
1107
|
+
void deliverTyped(shown, {
|
|
1108
|
+
onDelivered: () => markHighPriority(item.sid),
|
|
1109
|
+
sticky: true, // 补发的审批同样驻留
|
|
1110
|
+
sessionId: item.sid,
|
|
1111
|
+
launch,
|
|
1112
|
+
...(actionsXml ? { actionsXml } : {}),
|
|
1113
|
+
})
|
|
1114
|
+
suppressedApprovals.delete(k)
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
res.statusCode = 200
|
|
1118
|
+
res.end('ok')
|
|
1119
|
+
} catch {
|
|
1120
|
+
res.statusCode = 400
|
|
1121
|
+
res.end()
|
|
1122
|
+
}
|
|
1123
|
+
})
|
|
1124
|
+
} catch {
|
|
1125
|
+
// 路由异常不能冲进 fiber
|
|
1126
|
+
try { res.statusCode = 500; res.end() } catch { /* ignore */ }
|
|
1127
|
+
}
|
|
1128
|
+
},
|
|
1129
|
+
}), 'dsh-notification: focus route')
|
|
1130
|
+
|
|
1131
|
+
// 阶段三:浮窗数据源——client 轮询此路由拿当前待处理审批(只读,不裁决)。
|
|
1132
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1133
|
+
kind: 'exact',
|
|
1134
|
+
path: STATE_PATH,
|
|
1135
|
+
handler: (req, res) => {
|
|
1136
|
+
try {
|
|
1137
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1138
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1139
|
+
if (req.method !== 'GET') { res.statusCode = 405; res.end(); return }
|
|
1140
|
+
const cutoff = Date.now() - 5 * 60 * 1000
|
|
1141
|
+
const items = []
|
|
1142
|
+
for (const [key, v] of pendingApprovals) {
|
|
1143
|
+
if (v.at >= cutoff) items.push(v) // 5 分钟过期,避免陈旧审批常驻
|
|
1144
|
+
else pendingApprovals.delete(key)
|
|
1145
|
+
}
|
|
1146
|
+
res.statusCode = 200
|
|
1147
|
+
res.setHeader('content-type', 'application/json')
|
|
1148
|
+
res.end(JSON.stringify({ approvals: items, at: Date.now() }))
|
|
1149
|
+
} catch {
|
|
1150
|
+
try { res.statusCode = 500; res.end() } catch { /* ignore */ }
|
|
1151
|
+
}
|
|
1152
|
+
},
|
|
1153
|
+
}), 'dsh-notification: state route')
|
|
1154
|
+
|
|
1155
|
+
// snooze:临时静音 N 分钟(POST {minutes}),GET 读状态。带 requestRejection 围栏。
|
|
1156
|
+
// 优先级最高:静音期间所有通知丢弃、不排队、解除后不补发;ALWAYS_NOTIFY 不能反选。
|
|
1157
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1158
|
+
kind: 'exact',
|
|
1159
|
+
path: SNOOZE_PATH,
|
|
1160
|
+
handler: (req, res) => {
|
|
1161
|
+
try {
|
|
1162
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1163
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1164
|
+
if (req.method === 'GET') {
|
|
1165
|
+
res.statusCode = 200
|
|
1166
|
+
res.setHeader('content-type', 'application/json')
|
|
1167
|
+
res.end(JSON.stringify({ snoozeUntil, now: Date.now(), quiet: QUIET_START + '-' + QUIET_END }))
|
|
1168
|
+
return
|
|
1169
|
+
}
|
|
1170
|
+
if (req.method !== 'POST') { res.statusCode = 405; res.end(); return }
|
|
1171
|
+
let raw = ''
|
|
1172
|
+
req.on('data', (chunk) => { raw += chunk; if (raw.length > 2048) req.destroy() })
|
|
1173
|
+
req.on('end', () => {
|
|
1174
|
+
try {
|
|
1175
|
+
const body = JSON.parse(raw)
|
|
1176
|
+
const minutes = body.minutes === 0 ? 0 : Number(body.minutes)
|
|
1177
|
+
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) { res.statusCode = 400; res.end(); return }
|
|
1178
|
+
snoozeUntil = minutes === 0 ? 0 : Date.now() + minutes * 60 * 1000
|
|
1179
|
+
persistSettings()
|
|
1180
|
+
res.statusCode = 200
|
|
1181
|
+
res.setHeader('content-type', 'application/json')
|
|
1182
|
+
res.end(JSON.stringify({ snoozeUntil }))
|
|
1183
|
+
} catch { res.statusCode = 400; res.end() }
|
|
1184
|
+
})
|
|
1185
|
+
} catch {
|
|
1186
|
+
try { res.statusCode = 500; res.end() } catch { /* ignore */ }
|
|
1187
|
+
}
|
|
1188
|
+
},
|
|
1189
|
+
}), 'dsh-notification: snooze route')
|
|
1190
|
+
|
|
1191
|
+
// 文件动作通道:handler 原子写动作文件,这里校验后应用。
|
|
1192
|
+
// 按需注册 watcher(设置页开关可即时生效,不用重启);测试模式 NO_TOAST 下不注册,
|
|
1193
|
+
// 否则 watchFile 的定时器会把测试进程挂住。绝不为外部 handler 新增无 requestRejection 的 HTTP 路由。
|
|
1194
|
+
const actionFile = actionFilePath({ temp: process.env.TEMP || process.cwd() })
|
|
1195
|
+
let lastActionHash = ''
|
|
1196
|
+
let actionWatcherDispose = null
|
|
1197
|
+
// 批准动作的 binding 字段不在 pause-actions 的归一化里,单独严格解析。
|
|
1198
|
+
const parseApproveActionFile = (raw) => {
|
|
1199
|
+
try {
|
|
1200
|
+
if (typeof raw !== 'string' || raw.length > 2048) return null
|
|
1201
|
+
const obj = JSON.parse(raw)
|
|
1202
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return null
|
|
1203
|
+
return {
|
|
1204
|
+
op: obj.op, token: obj.token, key: obj.key,
|
|
1205
|
+
callId: obj.callId, sessionId: obj.sessionId,
|
|
1206
|
+
toolName: obj.toolName, argsHash: obj.argsHash,
|
|
1207
|
+
}
|
|
1208
|
+
} catch { return null }
|
|
1209
|
+
}
|
|
1210
|
+
// 点击按钮带的是 askedId,但 answerer 可能先用 callId 登记 waiter(先到的是 waterfall,
|
|
1211
|
+
// 后到的才是 approval/asked)。两种键都要能找到同一个 waiter 数组。
|
|
1212
|
+
const waiterKeyFor = (askedId, map) => {
|
|
1213
|
+
if (Array.isArray(map.get(askedId)) && map.get(askedId).length) return askedId
|
|
1214
|
+
for (const [key, p] of pendingApprovals) {
|
|
1215
|
+
if (p.askedId === askedId && Array.isArray(map.get(key)) && map.get(key).length) return key
|
|
1216
|
+
}
|
|
1217
|
+
return askedId
|
|
1218
|
+
}
|
|
1219
|
+
const onAction = () => {
|
|
1220
|
+
if (!PAUSE_BUTTONS && !APPROVAL_BUTTONS && !CLICK_ENABLED) return // 都关时不消费任何动作文件
|
|
1221
|
+
let raw
|
|
1222
|
+
try { raw = readFileSync(actionFile, 'utf8') } catch { return }
|
|
1223
|
+
const hash = raw.length + ':' + raw
|
|
1224
|
+
if (hash === lastActionHash) return
|
|
1225
|
+
const parsed = parseActionFile(raw)
|
|
1226
|
+
// 审批拒绝:只在原 waterfall 内兑现 rejected;绝不产生授权,也不调用 decide/request
|
|
1227
|
+
if (parsed && parsed.op === 'reject') {
|
|
1228
|
+
if (!APPROVAL_BUTTONS) {
|
|
1229
|
+
actionDiag('reject click ignored: approval buttons are off')
|
|
1230
|
+
lastActionHash = hash
|
|
1231
|
+
try { unlinkSync(actionFile) } catch { /* ignore */ }
|
|
1232
|
+
return
|
|
1233
|
+
}
|
|
1234
|
+
const verdict = validateRejectAction(parsed, { store: rejectStore })
|
|
1235
|
+
const wKey = verdict.ok ? waiterKeyFor(verdict.key, rejectWaiters) : verdict.key
|
|
1236
|
+
// 诊断要如实反映 waiter 数量(审计 #16):以前校验失败时强制写 0,
|
|
1237
|
+
// 排障时会误判成"没有待审批",实际只是令牌不合法。
|
|
1238
|
+
const waiters = rejectWaiters.get(wKey)
|
|
1239
|
+
const pending = Array.isArray(waiters) ? waiters.length : 0
|
|
1240
|
+
if (verdict.ok && pending > 0) {
|
|
1241
|
+
const resolve = waiters.shift()
|
|
1242
|
+
rejectWaiters.delete(wKey)
|
|
1243
|
+
try { resolve('rejected') } catch { /* ignore */ }
|
|
1244
|
+
actionDiag(`reject delivered: asked=${String(verdict.key).slice(0, 24)} waiters=${pending}`)
|
|
1245
|
+
} else {
|
|
1246
|
+
// 令牌过期 / 键不匹配 / waiter 已被消费:这里过去完全静默,用户点了按钮却毫无反应
|
|
1247
|
+
actionDiag(`reject dropped: verdict=${verdict.ok ? 'ok' : verdict.reason} waiters=${pending}`)
|
|
1248
|
+
}
|
|
1249
|
+
lastActionHash = hash
|
|
1250
|
+
try { unlinkSync(actionFile) } catch { /* ignore */ }
|
|
1251
|
+
return
|
|
1252
|
+
}
|
|
1253
|
+
// 审批"批准"(2026-11-27 用户知情授权):只在原 waterfall 内兑现 allowed-once。
|
|
1254
|
+
// 令牌绑定 askedId+callId+sessionId+toolName+argsHash,TTL ≤120s,单次消费。
|
|
1255
|
+
if (parsed && parsed.op === APPROVE_OP) {
|
|
1256
|
+
// 双闸门:审批按钮 + 用户单独开启的高级批准开关。默认都不产生授权。
|
|
1257
|
+
if (!APPROVAL_BUTTONS || !APPROVE_ENABLED) {
|
|
1258
|
+
actionDiag('approve click ignored: approval buttons or approve opt-in are off')
|
|
1259
|
+
lastActionHash = hash
|
|
1260
|
+
try { unlinkSync(actionFile) } catch { /* ignore */ }
|
|
1261
|
+
return
|
|
1262
|
+
}
|
|
1263
|
+
const verdict = validateApproveAction(parseApproveActionFile(raw), { store: approveStore })
|
|
1264
|
+
const wKey = verdict.ok ? waiterKeyFor(verdict.key, approveWaiters) : verdict.key
|
|
1265
|
+
const waiters = approveWaiters.get(wKey)
|
|
1266
|
+
const pending = Array.isArray(waiters) ? waiters.length : 0
|
|
1267
|
+
if (verdict.ok && pending > 0) {
|
|
1268
|
+
const resolve = waiters.shift()
|
|
1269
|
+
approveWaiters.delete(wKey)
|
|
1270
|
+
try { resolve('allowed-once') } catch { /* ignore */ }
|
|
1271
|
+
actionDiag(`approve delivered: asked=${String(verdict.key).slice(0, 24)} waiters=${pending}`)
|
|
1272
|
+
} else {
|
|
1273
|
+
actionDiag(`approve dropped: verdict=${verdict.ok ? 'ok' : verdict.reason} waiters=${pending}`)
|
|
1274
|
+
// 🔴 审计 #6:批准令牌 TTL 120s,但审批 toast 是驻留的。用户 2 分钟后才点「批准」时
|
|
1275
|
+
// 令牌已过期,原先完全静默(点了没反应、卡片也不收)。这里退化为「跳回该会话」,
|
|
1276
|
+
// 至少让人看见卡片还在等自己确认——绝不产生授权。
|
|
1277
|
+
try {
|
|
1278
|
+
const asked = typeof parsed.key === 'string' ? parsed.key : ''
|
|
1279
|
+
const rec = asked ? pendingApprovals.get(asked) : null
|
|
1280
|
+
const targetSid = rec && typeof rec.sessionId === 'string' ? rec.sessionId : ''
|
|
1281
|
+
if (!verdict.ok && verdict.reason === 'token-invalid' && targetSid) {
|
|
1282
|
+
pendingNavigation.sessionId = targetSid
|
|
1283
|
+
pendingNavigation.at = Date.now()
|
|
1284
|
+
actionDiag('approve expired -> navigation queued: session=' + targetSid.slice(0, 24))
|
|
1285
|
+
}
|
|
1286
|
+
} catch { /* ignore */ }
|
|
1287
|
+
}
|
|
1288
|
+
lastActionHash = hash
|
|
1289
|
+
try { unlinkSync(actionFile) } catch { /* ignore */ }
|
|
1290
|
+
return
|
|
1291
|
+
}
|
|
1292
|
+
// 跳具体会话:令牌只防重放;sessionId 形状严格校验,只作为数据交给 client。
|
|
1293
|
+
if (parsed && parsed.op === 'open') {
|
|
1294
|
+
if (!CLICK_ENABLED) {
|
|
1295
|
+
actionDiag('open click ignored: click-back is off')
|
|
1296
|
+
lastActionHash = hash
|
|
1297
|
+
try { unlinkSync(actionFile) } catch { /* ignore */ }
|
|
1298
|
+
return
|
|
1299
|
+
}
|
|
1300
|
+
const key = parsed.key
|
|
1301
|
+
const okKey = typeof key === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(key)
|
|
1302
|
+
const okToken = typeof parsed.token === 'string' && navVerifier.consume(parsed.token, Date.now())
|
|
1303
|
+
if (okKey && okToken) {
|
|
1304
|
+
pendingNavigation.sessionId = key
|
|
1305
|
+
pendingNavigation.at = Date.now()
|
|
1306
|
+
actionDiag('navigation target queued: session=' + String(key).slice(0, 24))
|
|
1307
|
+
} else {
|
|
1308
|
+
actionDiag('navigation dropped: bad-key=' + !okKey + ' bad-token=' + !okToken)
|
|
1309
|
+
}
|
|
1310
|
+
lastActionHash = hash
|
|
1311
|
+
try { unlinkSync(actionFile) } catch { /* ignore */ }
|
|
1312
|
+
return
|
|
1313
|
+
}
|
|
1314
|
+
const res = validateAction(parsed, { verifier: actionVerifier, now: Date.now() })
|
|
1315
|
+
if (!res.ok) return // fail-closed:非法/重放一律忽略
|
|
1316
|
+
lastActionHash = hash
|
|
1317
|
+
const a = res.action
|
|
1318
|
+
if (a.op === 'snooze') {
|
|
1319
|
+
snoozeUntil = Date.now() + a.minutes * 60 * 1000
|
|
1320
|
+
} else if (a.op === 'off') {
|
|
1321
|
+
enabled = false
|
|
1322
|
+
} else if (a.op === 'on') {
|
|
1323
|
+
enabled = true
|
|
1324
|
+
}
|
|
1325
|
+
// 校验通过、应用之后才删:避免误删非法文件或并发写入的新动作。
|
|
1326
|
+
try { unlinkSync(actionFile) } catch { /* ignore */ }
|
|
1327
|
+
persistSettings() // 与设置页共用同一快照,off 才能跨重启真正永久
|
|
1328
|
+
}
|
|
1329
|
+
const syncActionWatcher = () => {
|
|
1330
|
+
const want = (PAUSE_BUTTONS || APPROVAL_BUTTONS || CLICK_ENABLED) && process.env.DSH_NOTIFICATION_NO_TOAST !== '1'
|
|
1331
|
+
try {
|
|
1332
|
+
if (want && !actionWatcherDispose) {
|
|
1333
|
+
actionWatcherDispose = ctx.effect(() => {
|
|
1334
|
+
watchFile(actionFile, { interval: 1000 }, () => onAction())
|
|
1335
|
+
return () => { try { unwatchFile(actionFile) } catch { /* ignore */ } }
|
|
1336
|
+
})
|
|
1337
|
+
} else if (!want && actionWatcherDispose) {
|
|
1338
|
+
const dispose = actionWatcherDispose
|
|
1339
|
+
actionWatcherDispose = null
|
|
1340
|
+
try { dispose() } catch { /* ignore */ }
|
|
1341
|
+
}
|
|
1342
|
+
} catch { actionWatcherDispose = null } // fail-open:监听失败只影响按钮,不影响通知
|
|
1343
|
+
}
|
|
1344
|
+
syncActionWatcher()
|
|
1345
|
+
|
|
1346
|
+
// 空闲提醒:client 上报活动/空闲,Host 用同一状态机判定。带 requestRejection 围栏。
|
|
1347
|
+
// active=true → 重置空闲起点;active=false → 在门控通过后判定是否弹一次。
|
|
1348
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1349
|
+
kind: 'exact',
|
|
1350
|
+
path: IDLE_PATH,
|
|
1351
|
+
handler: (req, res) => {
|
|
1352
|
+
idleDiag('request ' + req.method + ' ' + req.url)
|
|
1353
|
+
try {
|
|
1354
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1355
|
+
if (rejection !== undefined) { idleDiag('rejected ' + rejection); res.statusCode = rejection; res.end(); return }
|
|
1356
|
+
if (req.method !== 'POST') { res.statusCode = 405; res.end(); return }
|
|
1357
|
+
let raw = ''
|
|
1358
|
+
req.on('data', (chunk) => { raw += chunk; if (raw.length > 2048) req.destroy() })
|
|
1359
|
+
req.on('end', () => {
|
|
1360
|
+
try {
|
|
1361
|
+
const body = JSON.parse(raw)
|
|
1362
|
+
const sid = typeof body.sessionId === 'string' ? body.sessionId : undefined
|
|
1363
|
+
idleDiag('recv active=' + body.active + ' sid=' + sid + ' idleEnabled=' + idleEnabled)
|
|
1364
|
+
if (body.active === true) {
|
|
1365
|
+
// 🔴 用户活动只用来让 client 推迟计时,**不重新武装一次性令牌**。
|
|
1366
|
+
// 否则"动一下鼠标 → 又停 3 秒 → 再弹"会变成骚扰(Claude 社区 issue #486
|
|
1367
|
+
// 把 idle_prompt 每 60 秒重复触发明确判为 bug 并加了去重)。
|
|
1368
|
+
// 重新武装只发生在下一轮 turn/end completed(见下方会话事件)。
|
|
1369
|
+
idleDiag('activity ignored for rearm')
|
|
1370
|
+
res.statusCode = 200
|
|
1371
|
+
res.end('ok')
|
|
1372
|
+
return
|
|
1373
|
+
}
|
|
1374
|
+
if (body.active !== false) { res.statusCode = 400; res.end(); return }
|
|
1375
|
+
// gate 唯一来源:总开关/静音/焦点门控;后台忙另查,且后台忙不消费一次性令牌。
|
|
1376
|
+
// 不强依赖 sid:当前没有可识别会话时也应能提醒(标题退化为 DSH)。
|
|
1377
|
+
const gate = idleEnabled && shouldDeliverIdle()
|
|
1378
|
+
idleDiag('gate=' + gate + ' snapshot=' + JSON.stringify(idleTracker.snapshot()))
|
|
1379
|
+
void (async () => {
|
|
1380
|
+
try {
|
|
1381
|
+
const backgroundActive = sid ? await hasLiveBackground(sid) : false
|
|
1382
|
+
const fired = idleTracker.evaluate(backgroundActive, gate)
|
|
1383
|
+
idleDiag('background=' + backgroundActive + ' fired=' + fired)
|
|
1384
|
+
if (!fired) return
|
|
1385
|
+
const title = typeof body.sessionTitle === 'string' && body.sessionTitle
|
|
1386
|
+
? body.sessionTitle.slice(0, 40) : 'DSH'
|
|
1387
|
+
const idleFormatted = formatIdle(title)
|
|
1388
|
+
// 空闲提醒由自己的开关控制(不经过类型白名单),但要和其它通知一样
|
|
1389
|
+
// 写历史、支持 TTS/自定义音(复查 P2:之前走裸 deliver() 三者都不生效)
|
|
1390
|
+
void deliverTyped(idleFormatted, {
|
|
1391
|
+
skipTypeFilter: true,
|
|
1392
|
+
sessionId: body.sessionId,
|
|
1393
|
+
})
|
|
1394
|
+
} catch { /* fail-open:空闲提醒失败不影响会话 */ }
|
|
1395
|
+
})()
|
|
1396
|
+
res.statusCode = 200
|
|
1397
|
+
res.end('ok')
|
|
1398
|
+
} catch { res.statusCode = 400; res.end() }
|
|
1399
|
+
})
|
|
1400
|
+
} catch { try { res.statusCode = 500; res.end() } catch { /* ignore */ } }
|
|
1401
|
+
},
|
|
1402
|
+
}), 'dsh-notification: idle route')
|
|
1403
|
+
|
|
1404
|
+
// 配置:设置页读写类型白名单 + 音效(内存态,重启失效)。带 requestRejection 围栏。
|
|
1405
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1406
|
+
kind: 'exact',
|
|
1407
|
+
path: CONFIG_PATH,
|
|
1408
|
+
handler: (req, res) => {
|
|
1409
|
+
try {
|
|
1410
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1411
|
+
if (req.method === 'POST') {
|
|
1412
|
+
actionDiag('config req method=POST rejection=' + (rejection === undefined ? 'none' : rejection))
|
|
1413
|
+
}
|
|
1414
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1415
|
+
const snapshot = () => ({
|
|
1416
|
+
enabled, types: ALLOWED_TYPES ? [...ALLOWED_TYPES] : [], sounds: { ...AUDIO_MAP },
|
|
1417
|
+
choices: SOUND_CHOICES, snoozeUntil, idleMs, idleEnabled,
|
|
1418
|
+
quietStart: QUIET_START, quietEnd: QUIET_END,
|
|
1419
|
+
approvalGraceMs: APPROVAL_GRACE_MS, alwaysNotify: ALWAYS_NOTIFY,
|
|
1420
|
+
clickEnabled: CLICK_ENABLED, pauseButtons: PAUSE_BUTTONS, approvalButtons: APPROVAL_BUTTONS,
|
|
1421
|
+
approveEnabled: APPROVE_ENABLED,
|
|
1422
|
+
ttsEnabled: TTS_ENABLED, ttsVoice: TTS_VOICE, customSounds: { ...CUSTOM_SOUNDS },
|
|
1423
|
+
historyEnabled: HISTORY_ENABLED, mutedSessions: [...MUTED_SESSIONS],
|
|
1424
|
+
})
|
|
1425
|
+
if (req.method === 'GET') {
|
|
1426
|
+
res.statusCode = 200
|
|
1427
|
+
res.setHeader('content-type', 'application/json')
|
|
1428
|
+
res.end(JSON.stringify(snapshot()))
|
|
1429
|
+
return
|
|
1430
|
+
}
|
|
1431
|
+
if (req.method !== 'POST') { res.statusCode = 405; res.end(); return }
|
|
1432
|
+
let raw = ''
|
|
1433
|
+
// 🔔 免打扰列表最多 200 个 sessionId(单个最长 200 字符),放宽上限避免多会话保存被截断
|
|
1434
|
+
req.on('data', (chunk) => { raw += chunk; if (raw.length > 65536) req.destroy() })
|
|
1435
|
+
req.on('end', () => {
|
|
1436
|
+
try {
|
|
1437
|
+
const body = JSON.parse(raw)
|
|
1438
|
+
const VALID = ['success', 'approval', 'needs-input', 'error', 'idle']
|
|
1439
|
+
if (typeof body.enabled === 'boolean') enabled = body.enabled
|
|
1440
|
+
if (Array.isArray(body.types)) {
|
|
1441
|
+
ALLOWED_TYPES = body.types.length ? new Set(body.types.filter(t => VALID.includes(t))) : null
|
|
1442
|
+
}
|
|
1443
|
+
if (body.sounds && typeof body.sounds === 'object') {
|
|
1444
|
+
for (const k of VALID) if (SOUND_CHOICES.includes(body.sounds[k])) AUDIO_MAP[k] = body.sounds[k]
|
|
1445
|
+
}
|
|
1446
|
+
// 空闲提醒:界面可开关 + 改阈值(默认仍由 env 决定初始状态)
|
|
1447
|
+
let idleChanged = false
|
|
1448
|
+
if (typeof body.idleEnabled === 'boolean' && body.idleEnabled !== idleEnabled) {
|
|
1449
|
+
idleEnabled = body.idleEnabled
|
|
1450
|
+
idleChanged = true
|
|
1451
|
+
}
|
|
1452
|
+
if (body.idleMs !== undefined) {
|
|
1453
|
+
const next = clampIdleMs(body.idleMs)
|
|
1454
|
+
if (next !== idleMs) { idleMs = next; idleChanged = true }
|
|
1455
|
+
}
|
|
1456
|
+
if (idleChanged) rebuildIdleTracker()
|
|
1457
|
+
// 静音时段 / 审批宽限 / 在场也提醒:界面可改,严格校验
|
|
1458
|
+
if (typeof body.quietStart === 'string') QUIET_START = /^([01]?\d|2[0-3]):[0-5]\d$/.test(body.quietStart) ? body.quietStart : ''
|
|
1459
|
+
if (typeof body.quietEnd === 'string') QUIET_END = /^([01]?\d|2[0-3]):[0-5]\d$/.test(body.quietEnd) ? body.quietEnd : ''
|
|
1460
|
+
if (body.approvalGraceMs !== undefined) {
|
|
1461
|
+
const g = Number(body.approvalGraceMs)
|
|
1462
|
+
if (Number.isFinite(g) && g >= 0 && g <= 60000) APPROVAL_GRACE_MS = g
|
|
1463
|
+
}
|
|
1464
|
+
if (typeof body.alwaysNotify === 'boolean') ALWAYS_NOTIFY = body.alwaysNotify
|
|
1465
|
+
if (typeof body.clickEnabled === 'boolean') CLICK_ENABLED = body.clickEnabled
|
|
1466
|
+
if (typeof body.approvalButtons === 'boolean') APPROVAL_BUTTONS = body.approvalButtons
|
|
1467
|
+
if (typeof body.approveEnabled === 'boolean') APPROVE_ENABLED = body.approveEnabled
|
|
1468
|
+
if (typeof body.ttsEnabled === 'boolean') TTS_ENABLED = body.ttsEnabled
|
|
1469
|
+
if (typeof body.ttsVoice === 'string' && /^[A-Za-z0-9 .()\-]{0,100}$/.test(body.ttsVoice)) TTS_VOICE = body.ttsVoice
|
|
1470
|
+
if (body.customSounds && typeof body.customSounds === 'object') {
|
|
1471
|
+
const next = {}
|
|
1472
|
+
for (const k of VALID) {
|
|
1473
|
+
const p = body.customSounds[k]
|
|
1474
|
+
// 允许中文路径;只挡控制字符、URL、通配符、UNC、引号,并要求绝对路径
|
|
1475
|
+
if (typeof p === 'string' && p.length <= 4096 && p.length > 0
|
|
1476
|
+
&& !p.includes('://') && !p.startsWith('\\\\')
|
|
1477
|
+
&& !/[\u0000-\u001f\u007f*?"<>|]/.test(p)
|
|
1478
|
+
&& /^[A-Za-z]:[\\\/][^\u0000-\u001f*?"<>|]+$/.test(p)) next[k] = p
|
|
1479
|
+
}
|
|
1480
|
+
CUSTOM_SOUNDS = next
|
|
1481
|
+
}
|
|
1482
|
+
if (typeof body.historyEnabled === 'boolean') HISTORY_ENABLED = body.historyEnabled
|
|
1483
|
+
// 🔔 按会话免打扰:必须是数组;元素按 sessionId 形状严格过滤、去重、最多 200 个
|
|
1484
|
+
if (Array.isArray(body.mutedSessions)) MUTED_SESSIONS = normalizeMutedSessions(body.mutedSessions, false)
|
|
1485
|
+
syncActionWatcher() // 开关变化时立即注册/注销动作文件监听
|
|
1486
|
+
const keys = Object.keys(body).join(',')
|
|
1487
|
+
void persistSettings().then((ok) => {
|
|
1488
|
+
actionDiag('config persist ok=' + ok + ' keys=' + keys)
|
|
1489
|
+
})
|
|
1490
|
+
actionDiag('config POST keys: ' + keys + ' sounds=' + JSON.stringify(AUDIO_MAP))
|
|
1491
|
+
res.statusCode = 200
|
|
1492
|
+
res.setHeader('content-type', 'application/json')
|
|
1493
|
+
res.end(JSON.stringify(snapshot()))
|
|
1494
|
+
} catch {
|
|
1495
|
+
actionDiag('config POST parse FAILED rawLen=' + raw.length)
|
|
1496
|
+
res.statusCode = 400; res.end()
|
|
1497
|
+
}
|
|
1498
|
+
})
|
|
1499
|
+
} catch { try { res.statusCode = 500; res.end() } catch { /* ignore */ } }
|
|
1500
|
+
},
|
|
1501
|
+
}), 'dsh-notification: config route')
|
|
1502
|
+
|
|
1503
|
+
// 「发送测试通知」:新用户装完只能等真实任务才能确认插件是否生效,这里给一个
|
|
1504
|
+
// 明确的自检入口。与其它路由同一套鉴权围栏;只发一条固定文案的示例提醒。
|
|
1505
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1506
|
+
kind: 'exact',
|
|
1507
|
+
path: TEST_PATH,
|
|
1508
|
+
handler: (req, res) => {
|
|
1509
|
+
try {
|
|
1510
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1511
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1512
|
+
if (req.method !== 'POST') { res.statusCode = 405; res.end(); return }
|
|
1513
|
+
res.statusCode = 200
|
|
1514
|
+
res.setHeader('content-type', 'application/json')
|
|
1515
|
+
res.end(JSON.stringify({ ok: true }))
|
|
1516
|
+
// 不走 shouldDeliver 门控:测试入口就是要在"静音/不在场/关掉类型"时也能看到效果,
|
|
1517
|
+
// 但受总开关与 NO_TOAST 约束(用户明确关闭时不该被打扰)。
|
|
1518
|
+
if (enabled && process.env.DSH_NOTIFICATION_NO_TOAST !== '1') {
|
|
1519
|
+
void deliverTyped(formatCompletion('测试通知(来自设置页)', '看到这条说明通知链路是通的。'), { skipTypeFilter: true })
|
|
1520
|
+
}
|
|
1521
|
+
} catch { try { res.statusCode = 500; res.end() } catch { /* ignore */ } }
|
|
1522
|
+
},
|
|
1523
|
+
}), 'dsh-notification: test route')
|
|
1524
|
+
// 试听:设置页改提示音时让用户立刻听到"这是什么声音"。只播声音,不产生通知。
|
|
1525
|
+
// 与其它路由同一套鉴权围栏;只接受已知音效,非法值 400,绝不把用户输入拼进命令行。
|
|
1526
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1527
|
+
kind: 'exact',
|
|
1528
|
+
path: PREVIEW_PATH,
|
|
1529
|
+
handler: (req, res) => {
|
|
1530
|
+
try {
|
|
1531
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1532
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1533
|
+
if (req.method !== 'POST') { res.statusCode = 405; res.end(); return }
|
|
1534
|
+
let raw = ''
|
|
1535
|
+
req.on('data', (c) => { raw += c; if (raw.length > 1024) req.destroy() })
|
|
1536
|
+
req.on('end', () => {
|
|
1537
|
+
try {
|
|
1538
|
+
const body = JSON.parse(raw || '{}')
|
|
1539
|
+
const sound = String(body.sound || '')
|
|
1540
|
+
if (!SOUND_CHOICES.includes(sound)) { res.statusCode = 400; res.end(); return }
|
|
1541
|
+
const played = previewSound(sound)
|
|
1542
|
+
res.statusCode = 200
|
|
1543
|
+
res.setHeader('content-type', 'application/json')
|
|
1544
|
+
res.end(JSON.stringify({ ok: true, sound, played }))
|
|
1545
|
+
} catch { res.statusCode = 400; res.end() }
|
|
1546
|
+
})
|
|
1547
|
+
} catch { try { res.statusCode = 500; res.end() } catch { /* ignore */ } }
|
|
1548
|
+
},
|
|
1549
|
+
}), 'dsh-notification: preview route')
|
|
1550
|
+
|
|
1551
|
+
// 缺口 4:通知历史。GET 读列表;POST {op:'clear'} 清空。同一 requestRejection 围栏。
|
|
1552
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1553
|
+
kind: 'exact',
|
|
1554
|
+
path: HISTORY_PATH,
|
|
1555
|
+
handler: (req, res) => {
|
|
1556
|
+
try {
|
|
1557
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1558
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1559
|
+
res.setHeader('content-type', 'application/json')
|
|
1560
|
+
if (req.method === 'GET') {
|
|
1561
|
+
res.statusCode = 200
|
|
1562
|
+
res.end(JSON.stringify({ enabled: HISTORY_ENABLED, items: historyStore.list() }))
|
|
1563
|
+
return
|
|
1564
|
+
}
|
|
1565
|
+
if (req.method !== 'POST') { res.statusCode = 405; res.end(); return }
|
|
1566
|
+
let raw = ''
|
|
1567
|
+
req.on('data', (c) => { raw += c; if (raw.length > 512) req.destroy() })
|
|
1568
|
+
req.on('end', () => {
|
|
1569
|
+
try {
|
|
1570
|
+
const body = JSON.parse(raw || '{}')
|
|
1571
|
+
if (body.op !== 'clear') { res.statusCode = 400; res.end(); return }
|
|
1572
|
+
void historyStore.clear()
|
|
1573
|
+
res.statusCode = 200
|
|
1574
|
+
res.end(JSON.stringify({ enabled: HISTORY_ENABLED, items: [] }))
|
|
1575
|
+
} catch { res.statusCode = 400; res.end() }
|
|
1576
|
+
})
|
|
1577
|
+
} catch { try { res.statusCode = 500; res.end() } catch { /* ignore */ } }
|
|
1578
|
+
},
|
|
1579
|
+
}), 'dsh-notification: history route')
|
|
1580
|
+
|
|
1581
|
+
// 缺口 3:client 轮询待跳转会话(一次性消费)。只放 sessionId,不放任何权限信息。
|
|
1582
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1583
|
+
kind: 'exact',
|
|
1584
|
+
path: NAVIGATE_PATH,
|
|
1585
|
+
handler: (req, res) => {
|
|
1586
|
+
try {
|
|
1587
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1588
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1589
|
+
if (req.method !== 'GET') { res.statusCode = 405; res.end(); return }
|
|
1590
|
+
res.statusCode = 200
|
|
1591
|
+
res.setHeader('content-type', 'application/json')
|
|
1592
|
+
const sid = Date.now() - pendingNavigation.at < 60000 ? pendingNavigation.sessionId : ''
|
|
1593
|
+
pendingNavigation.sessionId = ''
|
|
1594
|
+
pendingNavigation.at = 0
|
|
1595
|
+
res.end(JSON.stringify({ sessionId: sid }))
|
|
1596
|
+
} catch { try { res.statusCode = 500; res.end() } catch { /* ignore */ } }
|
|
1597
|
+
},
|
|
1598
|
+
}), 'dsh-notification: navigate route')
|
|
1599
|
+
|
|
1600
|
+
// TTS 语音列表:只从本机已安装语音读取,不联网。
|
|
1601
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1602
|
+
kind: 'exact',
|
|
1603
|
+
path: VOICES_PATH,
|
|
1604
|
+
handler: (req, res) => {
|
|
1605
|
+
try {
|
|
1606
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1607
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1608
|
+
if (req.method !== 'GET') { res.statusCode = 405; res.end(); return }
|
|
1609
|
+
void listVoices().then((voices) => {
|
|
1610
|
+
try {
|
|
1611
|
+
res.statusCode = 200
|
|
1612
|
+
res.setHeader('content-type', 'application/json')
|
|
1613
|
+
res.end(JSON.stringify({ voices }))
|
|
1614
|
+
} catch { /* ignore */ }
|
|
1615
|
+
})
|
|
1616
|
+
} catch { try { res.statusCode = 500; res.end() } catch { /* ignore */ } }
|
|
1617
|
+
},
|
|
1618
|
+
}), 'dsh-notification: voices route')
|
|
1619
|
+
|
|
1620
|
+
// 设置页渲染异常上报:白屏时从只读日志就能看到堆栈,不用用户开 DevTools。
|
|
1621
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1622
|
+
kind: 'exact',
|
|
1623
|
+
path: RENDER_ERROR_PATH,
|
|
1624
|
+
handler: (req, res) => {
|
|
1625
|
+
try {
|
|
1626
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1627
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1628
|
+
if (req.method !== 'POST') { res.statusCode = 405; res.end(); return }
|
|
1629
|
+
let raw = ''
|
|
1630
|
+
req.on('data', (c) => { raw += c; if (raw.length > 4096) req.destroy() })
|
|
1631
|
+
req.on('end', () => {
|
|
1632
|
+
try {
|
|
1633
|
+
const body = JSON.parse(raw || '{}')
|
|
1634
|
+
const msg = String(body.msg || '').replace(/[\r\n]+/g, ' ').slice(0, 2000)
|
|
1635
|
+
if (msg) appendFileSync(RENDER_ERROR_LOG, `[${new Date().toISOString()}] ${msg}\n`, 'utf8')
|
|
1636
|
+
res.statusCode = 200
|
|
1637
|
+
res.end('ok')
|
|
1638
|
+
} catch { res.statusCode = 400; res.end() }
|
|
1639
|
+
})
|
|
1640
|
+
} catch { try { res.statusCode = 500; res.end() } catch { /* ignore */ } }
|
|
1641
|
+
},
|
|
1642
|
+
}), 'dsh-notification: render-error route')
|
|
1643
|
+
|
|
1644
|
+
// 诊断:client 半身上报关键节点;GET 读取(仅 DIAGNOSTICS 开启时注册)
|
|
1645
|
+
if (DIAGNOSTICS) ctx.effect(() => ctx.webServer.register({
|
|
1646
|
+
kind: 'exact',
|
|
1647
|
+
path: DIAG_PATH,
|
|
1648
|
+
handler: (req, res) => {
|
|
1649
|
+
try {
|
|
1650
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1651
|
+
if (rejection !== undefined) { res.statusCode = rejection; res.end(); return }
|
|
1652
|
+
if (req.method === 'GET') {
|
|
1653
|
+
res.statusCode = 200
|
|
1654
|
+
res.setHeader('content-type', 'application/json')
|
|
1655
|
+
res.end(JSON.stringify({ lines: clientDiag, at: Date.now() }))
|
|
1656
|
+
return
|
|
1657
|
+
}
|
|
1658
|
+
if (req.method === 'POST') {
|
|
1659
|
+
let raw = ''
|
|
1660
|
+
req.on('data', (c) => { raw += c; if (raw.length > 4096) req.destroy() })
|
|
1661
|
+
req.on('end', () => {
|
|
1662
|
+
try {
|
|
1663
|
+
const b = JSON.parse(raw)
|
|
1664
|
+
clientDiag.push(String(b.msg || '').replace(/[\r\n]+/g, ' ').slice(0, 200))
|
|
1665
|
+
if (clientDiag.length > 50) clientDiag.shift()
|
|
1666
|
+
diag('CLIENT: ' + String(b.msg || '').slice(0, 200))
|
|
1667
|
+
res.statusCode = 200; res.end('ok')
|
|
1668
|
+
} catch { res.statusCode = 400; res.end() }
|
|
1669
|
+
})
|
|
1670
|
+
return
|
|
1671
|
+
}
|
|
1672
|
+
res.statusCode = 405; res.end()
|
|
1673
|
+
} catch { try { res.statusCode = 500; res.end() } catch { /* ignore */ } }
|
|
1674
|
+
},
|
|
1675
|
+
}), 'dsh-notification: diag route')
|
|
1676
|
+
|
|
1677
|
+
// 阶段三审批通知的核心:弹 toast + 记 pending。
|
|
1678
|
+
// 真机修复(2026-11-24):
|
|
1679
|
+
// ① 焦点门控按行业惯例:在场抑制、离开后补发(见 suppressedApprovals)——审批仍记 pending 不丢;
|
|
1680
|
+
// ② 触发源从 approval/request answerer 改为 session/event 的 approval/asked(durable)。
|
|
1681
|
+
// 原因:内置 answerer(remote 桥接 / ACP / 默认 UI)会截胡 waterfall——它们返回 outcome
|
|
1682
|
+
// 而不调 next(),后注册的 answerer 根本轮不到(源码实证 dsh-api-remotes/lib/index.js:245+、
|
|
1683
|
+
// README "sibling listener order is not a policy-priority mechanism")。
|
|
1684
|
+
// approval/asked 是 session.append 的审计事件,不经 waterfall,一定能收到。
|
|
1685
|
+
// 统一投递门控:静音(quiet/snooze) > 焦点 > ALWAYS_NOTIFY。三处投递共用。
|
|
1686
|
+
// 静音期间事件丢弃、不排队、解除后不补发(Industry: quiet catch-up 要避免爆发补发)。
|
|
1687
|
+
const shouldDeliver = (sid) => {
|
|
1688
|
+
if (!enabled) return false // 插件总开关关闭(设置页/永久暂停)——最高优先级,ALWAYS_NOTIFY 不能反选
|
|
1689
|
+
const now = Date.now()
|
|
1690
|
+
const quietActive = isQuietNow(now, QUIET_START, QUIET_END)
|
|
1691
|
+
return shouldNotifyNow(now, focusState, quietActive, snoozeUntil, ALWAYS_NOTIFY, sid)
|
|
1692
|
+
}
|
|
1693
|
+
// 空闲提醒专用门控:不经过焦点门控——"看着会话但没输入"正是要提醒的场景。
|
|
1694
|
+
// 但仍受总开关 / quiet / snooze 约束,静音优先级不变。
|
|
1695
|
+
const shouldDeliverIdle = () => {
|
|
1696
|
+
if (!enabled) return false
|
|
1697
|
+
const now = Date.now()
|
|
1698
|
+
return !isQuietNow(now, QUIET_START, QUIET_END) && !isSnoozed(now, snoozeUntil)
|
|
1699
|
+
}
|
|
1700
|
+
// 高优先级活动投递前打时间戳(审批/needs-input/错误),供完成通知冷却窗判断。
|
|
1701
|
+
const markHighPriority = (sid) => { if (sid) highPriorityAt.set(sid, Date.now()) }
|
|
1702
|
+
|
|
1703
|
+
// 后台未排空抑制(DSH 版 held-back Stop):问 workspace/session-activity,
|
|
1704
|
+
// 若有 turn 以外的活动(subagent/job/schedule)说明后台还在跑 → 压住完成通知,
|
|
1705
|
+
// debounce 重试至空或超时(5s)。全程 fail-open:查不到/出错/超时一律照弹。
|
|
1706
|
+
const BG_RETRY_MS = 500
|
|
1707
|
+
const BG_MAX_RETRY = 10
|
|
1708
|
+
// 🔴 每会话独立计数(审计 #2):原来是一个全局变量,两会话在同一 tick 完成时后一个会把
|
|
1709
|
+
// 前一个的待投递回调作废,导致前一条完成通知永久丢失(实测 2 条只弹 1 条、历史也缺)。
|
|
1710
|
+
const bg = createGenerationGate()
|
|
1711
|
+
const bumpBgGeneration = (sid) => bg.bump(sid)
|
|
1712
|
+
const bgGenerationNow = (sid) => bg.now(sid)
|
|
1713
|
+
const hasLiveBackground = async (sid) => {
|
|
1714
|
+
try {
|
|
1715
|
+
const activity = await ctx.waterfall('workspace/session-activity', { sessionId: sid }, () => Promise.resolve([]))
|
|
1716
|
+
if (!Array.isArray(activity)) return false
|
|
1717
|
+
// 只等"后台",忽略当前 turn 族(turn/end 时它通常已 idle)
|
|
1718
|
+
return activity.some((a) => a && a.kind !== 'turn')
|
|
1719
|
+
} catch { return false } // fail-open:拿不到活动状态就当没有后台
|
|
1720
|
+
}
|
|
1721
|
+
// 完成通知等后台排空后投递;回调里重新求值门控(焦点/静音可能已变)。
|
|
1722
|
+
const deliverCompletionWhenIdle = (sid, makeFormatted) => {
|
|
1723
|
+
const gen = bumpBgGeneration(sid)
|
|
1724
|
+
let tries = 0
|
|
1725
|
+
const attempt = async () => {
|
|
1726
|
+
if (gen !== bgGenerationNow(sid)) return // 已失效(同一会话被处置/被新通知取代)
|
|
1727
|
+
try {
|
|
1728
|
+
if (await hasLiveBackground(sid)) {
|
|
1729
|
+
if (tries++ < BG_MAX_RETRY) { setTimeout(attempt, BG_RETRY_MS); return }
|
|
1730
|
+
// 超时仍忙 → fail-open 照弹
|
|
1731
|
+
}
|
|
1732
|
+
} catch { /* fail-open */ }
|
|
1733
|
+
if (gen !== bgGenerationNow(sid)) return
|
|
1734
|
+
// 重新求值门控(flush 时用当时的状态,不用调度时快照)
|
|
1735
|
+
if (!shouldDeliver(sid)) return
|
|
1736
|
+
if (shouldSkipAsCompletion('success', sid, Date.now(), highPriorityAt.get(sid), COOLDOWN_MS)) return
|
|
1737
|
+
try {
|
|
1738
|
+
const formatted = makeFormatted()
|
|
1739
|
+
void deliverTyped(formatted, { sessionId: sid })
|
|
1740
|
+
} catch { /* fail-open */ }
|
|
1741
|
+
}
|
|
1742
|
+
void attempt()
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
// 审批 toast 的按钮/回跳参数统一构造。批准令牌只有在拿到 tool/call 参数时才签发;
|
|
1746
|
+
// 参数缺失就 fail-closed 不出批准按钮(绝不盲批)。
|
|
1747
|
+
const buildApprovalToast = (pendingKey) => {
|
|
1748
|
+
const p = pendingApprovals.get(pendingKey) || {}
|
|
1749
|
+
const askedId = p.askedId
|
|
1750
|
+
const sid = p.sessionId
|
|
1751
|
+
const callId = typeof pendingKey === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(pendingKey) ? pendingKey : ''
|
|
1752
|
+
const argsRec = callId ? toolArgs.get(callId) : null
|
|
1753
|
+
const toolName = String(p.toolName || '')
|
|
1754
|
+
const preview = argsRec ? commandPreview(argsRec.raw) : ''
|
|
1755
|
+
// 🔴 看不到实际命令就不签发批准令牌、不显示批准按钮(防止盲批)
|
|
1756
|
+
const binding = (preview && argsRec && typeof askedId === 'string' && typeof sid === 'string'
|
|
1757
|
+
&& /^[A-Za-z0-9_.-]{1,80}$/.test(toolName) && /^[a-f0-9]{16}$/.test(argsRec.hash))
|
|
1758
|
+
? { callId, sessionId: sid, toolName, argsHash: argsRec.hash }
|
|
1759
|
+
: null
|
|
1760
|
+
let token = ''
|
|
1761
|
+
let approveToken = ''
|
|
1762
|
+
if (APPROVAL_BUTTONS && typeof askedId === 'string') {
|
|
1763
|
+
token = rejectStore.issue(askedId, REJECT_TOKEN_TTL_MS)
|
|
1764
|
+
// 🔴 高级开关默认关:没打开就绝不签发批准令牌,toast 上不会出现批准按钮。
|
|
1765
|
+
if (binding && APPROVE_ENABLED) approveToken = approveStore.issue(askedId, APPROVE_TOKEN_TTL_MS, binding)
|
|
1766
|
+
}
|
|
1767
|
+
const actionsXml = token
|
|
1768
|
+
? buildDecisionActionXml({ askedId, token, approveToken, binding })
|
|
1769
|
+
: (APPROVAL_BUTTONS ? buildFocusActionXml() : '')
|
|
1770
|
+
let launch = 'dsh://open'
|
|
1771
|
+
if (CLICK_ENABLED && typeof sid === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(sid)) {
|
|
1772
|
+
const navToken = navVerifier.issue()
|
|
1773
|
+
if (navToken) {
|
|
1774
|
+
launch = 'dshnotify://act?op=open&t=' + encodeURIComponent(navToken) + '&k=' + encodeURIComponent(sid)
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
return { actionsXml, launch, preview }
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
const fireApprovalNotice = (info) => {
|
|
1781
|
+
const key = info.callId || info.toolName || 'unknown'
|
|
1782
|
+
if (pendingApprovals.has(key)) return // asked 与 request 可能都触发,去重
|
|
1783
|
+
diag('approval notice fired: ' + JSON.stringify({ key, toolName: info.toolName }))
|
|
1784
|
+
pendingApprovals.set(key, {
|
|
1785
|
+
key,
|
|
1786
|
+
toolName: info.toolName || 'tool',
|
|
1787
|
+
reason: typeof info.reason === 'string' ? info.reason : '',
|
|
1788
|
+
at: Date.now(),
|
|
1789
|
+
sessionId: info.sessionId,
|
|
1790
|
+
askedId: info.id,
|
|
1791
|
+
})
|
|
1792
|
+
// 门控在 fire() 里求值(grace 后状态可能已变);审批仍记 pending——绝不静默丢弃请求。
|
|
1793
|
+
// approval/asked.reason 含 "escalate sandbox to danger-full-access: ..." → formatApproval 翻成人话
|
|
1794
|
+
const formatted = formatApproval(info.toolName, info.reason)
|
|
1795
|
+
const fire = () => {
|
|
1796
|
+
// 宽限期内用户可能已裁决(pending 被 decided 删除)→ 不再弹
|
|
1797
|
+
if (!pendingApprovals.has(key)) { diag('approval toast skipped: already decided during grace'); return }
|
|
1798
|
+
// answerer 先到时没有 sessionId;6s 后 approval/asked 已把它补进 pending——
|
|
1799
|
+
// 必须从 pending 取最新值,否则焦点门控拿到 undefined 会 fail-open(在会话里也弹)。
|
|
1800
|
+
const sid = pendingApprovals.get(key)?.sessionId ?? info.sessionId
|
|
1801
|
+
if (!shouldDeliver(sid)) {
|
|
1802
|
+
// 修审计"漏报":若仅因焦点抑制(用户在场),挂起,等离开后补发;静音抑制不挂起。
|
|
1803
|
+
const now = Date.now()
|
|
1804
|
+
const quietActive = isQuietNow(now, QUIET_START, QUIET_END)
|
|
1805
|
+
if (isFocusSuppressed(now, focusState, quietActive, snoozeUntil, ALWAYS_NOTIFY, sid)) {
|
|
1806
|
+
suppressedApprovals.set(key, { formatted, sid, at: now })
|
|
1807
|
+
diag('approval toast parked (in-session), will deliver on away')
|
|
1808
|
+
}
|
|
1809
|
+
return
|
|
1810
|
+
}
|
|
1811
|
+
// 审批按钮(默认关):拒绝 + 去 DSH 确认;拿到实际参数时才追加「批准一次」。
|
|
1812
|
+
const { actionsXml, launch, preview } = buildApprovalToast(key)
|
|
1813
|
+
const shown = preview ? { ...formatted, body: (formatted.body + ' · 将执行:' + preview).slice(0, 140) } : formatted
|
|
1814
|
+
void deliverTyped(shown, {
|
|
1815
|
+
onDelivered: () => markHighPriority(sid),
|
|
1816
|
+
sticky: true, // 审批:驻留到用户处理,别几秒就滑走
|
|
1817
|
+
sessionId: sid,
|
|
1818
|
+
launch,
|
|
1819
|
+
...(actionsXml ? { actionsXml } : {}),
|
|
1820
|
+
})
|
|
1821
|
+
}
|
|
1822
|
+
if (APPROVAL_GRACE_MS > 0) setTimeout(fire, APPROVAL_GRACE_MS)
|
|
1823
|
+
else fire()
|
|
1824
|
+
}
|
|
1825
|
+
// answerer 仅作备用观察(可能被截胡,不依赖它):只补 pending,不重复弹 toast
|
|
1826
|
+
const notifyApproval = (req) => {
|
|
1827
|
+
diag('approval/request(answerer, may be pre-empted): ' + JSON.stringify({ callId: req?.callId, toolName: req?.toolName }))
|
|
1828
|
+
if (!req?.callId || !pendingApprovals.has(req.callId)) {
|
|
1829
|
+
fireApprovalNotice({ callId: req?.callId, toolName: req?.toolName, reason: req?.reason })
|
|
1830
|
+
}
|
|
1831
|
+
return Promise.resolve()
|
|
1832
|
+
}
|
|
1833
|
+
const logWarn = (msg, err) => {
|
|
1834
|
+
try { ctx.logger.warn('[dsh-notification] ' + msg, err) } catch { /* logger 缺失也不能抛 */ }
|
|
1835
|
+
}
|
|
1836
|
+
// 审批"拒绝"通道(用户已授权推翻方案 A):prepend 排在所有内置 answerer 前。
|
|
1837
|
+
// 只对"本插件弹了带拒绝按钮的 toast"的请求生效;其余一律 next(),零行为变化。
|
|
1838
|
+
// 🔴 只在原 waterfall 内返回 'rejected';绝不调用 ctx.approval.decide/request(会重复审计)。
|
|
1839
|
+
// next() 立即启动原链(应用内卡片照常显示),所以没有任何审批会卡住等 toast 点击。
|
|
1840
|
+
ctx.on('approval/request', (req, next) => {
|
|
1841
|
+
try {
|
|
1842
|
+
const key = req?.callId
|
|
1843
|
+
// 🔴 不能要求 pendingApprovals 已存在:answerer 常常先于 approval/asked 事件运行,
|
|
1844
|
+
// 之前这里直接 next() 导致 waiter 永不创建(点击后 waiters=0)。
|
|
1845
|
+
if (!key || !APPROVAL_BUTTONS) return next()
|
|
1846
|
+
const askedId = pendingApprovals.get(key)?.askedId
|
|
1847
|
+
// 🔴 不要求 waiters 已非空:这里就是创建 waiter 的地方。
|
|
1848
|
+
// 之前 `waiters.length === 0 → next()` 让否决分支成为死代码(对抗审查 P0)。
|
|
1849
|
+
// askedId 可能还没出现,先用 callId 建 waiter;asked 事件到达后再把同一数组挂到 askedId。
|
|
1850
|
+
const waiterKey = askedId || key
|
|
1851
|
+
let waiters = rejectWaiters.get(waiterKey)
|
|
1852
|
+
if (!Array.isArray(waiters)) { waiters = []; rejectWaiters.set(waiterKey, waiters) }
|
|
1853
|
+
if (waiterKey !== key) rejectWaiters.set(key, waiters)
|
|
1854
|
+
let approvers = approveWaiters.get(waiterKey)
|
|
1855
|
+
if (!Array.isArray(approvers)) { approvers = []; approveWaiters.set(waiterKey, approvers) }
|
|
1856
|
+
if (waiterKey !== key) approveWaiters.set(key, approvers)
|
|
1857
|
+
const ui = Promise.resolve().then(next) // 只调一次 next()
|
|
1858
|
+
const veto = new Promise((resolve) => { waiters.push(resolve) })
|
|
1859
|
+
// 🔴 无条件创建 waiter:审批请求到达时 toast 还没弹(6s 宽限),不能在这时用
|
|
1860
|
+
// "是否已签发令牌"做时序闸门,否则批准承诺会被丢弃、按钮点了无效。
|
|
1861
|
+
// 真正的闸门是 onAction 里的 validateApproveAction(令牌只在双开关+绑定合法时签发)。
|
|
1862
|
+
const grant = new Promise((resolve) => { approvers.push(resolve) })
|
|
1863
|
+
return Promise.race([
|
|
1864
|
+
ui,
|
|
1865
|
+
veto.then(() => {
|
|
1866
|
+
// 通知里点了拒绝:顺手把已经弹出来的应用内卡片收掉(否则它挂着等一次永远不会发生的点击)
|
|
1867
|
+
dismissInAppApproval(req)
|
|
1868
|
+
return 'rejected'
|
|
1869
|
+
}),
|
|
1870
|
+
grant.then(() => {
|
|
1871
|
+
// 通知里点了「批准一次」:同样收掉应用内卡片;裁决只在原 waterfall 内兑现。
|
|
1872
|
+
dismissInAppApproval(req)
|
|
1873
|
+
return 'allowed-once'
|
|
1874
|
+
}),
|
|
1875
|
+
])
|
|
1876
|
+
} catch { return next() } // fail-open:异常一律透传
|
|
1877
|
+
}, { prepend: true })
|
|
1878
|
+
|
|
1879
|
+
ctx.on('approval/request', makeApprovalAnswerer(notifyApproval, logWarn))
|
|
1880
|
+
|
|
1881
|
+
ctx.on('session/event', (session, event) => {
|
|
1882
|
+
try {
|
|
1883
|
+
// 子代理过滤:主会话通知已覆盖子代理工作,子代理自己不弹(避免重复打扰)。
|
|
1884
|
+
// 但 approval/asked 仍要处理:answerer 可能已为子代理建了 pending,
|
|
1885
|
+
// 不清掉的话 6s 宽限后会弹一条没有 sessionId 的 toast(焦点门控 fail-open → 在会话里也弹)。
|
|
1886
|
+
const subagent = isSubagent(session)
|
|
1887
|
+
if (subagent && event.type !== 'approval/asked') return
|
|
1888
|
+
// 审批事件关联(源码实证 2026-10-15):
|
|
1889
|
+
// approval/asked 事件 = { id: UUID, callId?, toolName, reason? }
|
|
1890
|
+
// approval/decided 事件 = { id: UUID, outcome } ← 没有 callId
|
|
1891
|
+
// approval/request req = { toolName, callId, reason?, ... } ← 没有 id
|
|
1892
|
+
// 所以:ask/request 只能用 callId 关联;decided 只能用 askedId(UUID) 反查。
|
|
1893
|
+
// callId 可选:缺失时用 toolName 兜底 key(notifyApproval 里已这么存)。
|
|
1894
|
+
if (event.type === 'approval/asked') {
|
|
1895
|
+
const callId = event.data?.callId
|
|
1896
|
+
// 子代理审批:answerer 路径拿不到 session.header,只能靠这里清掉它建的 pending
|
|
1897
|
+
if (subagent) {
|
|
1898
|
+
const k = (callId !== undefined && pendingApprovals.has(callId)) ? callId
|
|
1899
|
+
: (event.data?.toolName && pendingApprovals.has(event.data.toolName) ? event.data.toolName : undefined)
|
|
1900
|
+
if (k !== undefined) pendingApprovals.delete(k)
|
|
1901
|
+
return
|
|
1902
|
+
}
|
|
1903
|
+
const key = (callId !== undefined && pendingApprovals.has(callId))
|
|
1904
|
+
? callId
|
|
1905
|
+
: (event.data?.toolName && pendingApprovals.has(event.data.toolName) ? event.data.toolName : undefined)
|
|
1906
|
+
if (key !== undefined) {
|
|
1907
|
+
// answerer 先收到过:补 askedId + sessionId
|
|
1908
|
+
const p = pendingApprovals.get(key)
|
|
1909
|
+
p.askedId = event.data?.id
|
|
1910
|
+
p.sessionId = session?.id
|
|
1911
|
+
if (typeof event.data?.reason === 'string') p.reason = event.data.reason
|
|
1912
|
+
// 拒绝通道:askedId 一出现就登记 waiter,answerer 紧接着就会被 waterfall 调用。
|
|
1913
|
+
// 只在没有登记过时才建空数组:若 answerer 已经先塞进 resolve,这里覆盖会把否决指针冲掉。
|
|
1914
|
+
if (APPROVAL_BUTTONS && typeof p.askedId === 'string') {
|
|
1915
|
+
// answerer 可能已用 callId 建好 waiter;把同一数组挂到 askedId,按钮点击才能兑现
|
|
1916
|
+
const linkedReject = rejectWaiters.get(key)
|
|
1917
|
+
if (Array.isArray(linkedReject) && linkedReject.length) rejectWaiters.set(p.askedId, linkedReject)
|
|
1918
|
+
else if (!rejectWaiters.has(p.askedId)) rejectWaiters.set(p.askedId, [])
|
|
1919
|
+
const linkedApprove = approveWaiters.get(key)
|
|
1920
|
+
if (Array.isArray(linkedApprove) && linkedApprove.length) approveWaiters.set(p.askedId, linkedApprove)
|
|
1921
|
+
else if (!approveWaiters.has(p.askedId)) approveWaiters.set(p.askedId, [])
|
|
1922
|
+
}
|
|
1923
|
+
} else {
|
|
1924
|
+
// 🔴 关键:answerer 被截胡时,asked 是唯一信号——用它新建 pending 并弹 toast
|
|
1925
|
+
diag('approval/asked as primary source (answerer was pre-empted): ' + JSON.stringify({ id: event.data?.id, callId, toolName: event.data?.toolName }))
|
|
1926
|
+
fireApprovalNotice({
|
|
1927
|
+
id: event.data?.id,
|
|
1928
|
+
callId,
|
|
1929
|
+
toolName: event.data?.toolName,
|
|
1930
|
+
reason: event.data?.reason,
|
|
1931
|
+
sessionId: session?.id,
|
|
1932
|
+
})
|
|
1933
|
+
if (APPROVAL_BUTTONS && typeof event.data?.id === 'string' && !rejectWaiters.has(event.data.id)) rejectWaiters.set(event.data.id, [])
|
|
1934
|
+
if (APPROVAL_BUTTONS && typeof event.data?.id === 'string' && !approveWaiters.has(event.data.id)) approveWaiters.set(event.data.id, [])
|
|
1935
|
+
}
|
|
1936
|
+
return
|
|
1937
|
+
}
|
|
1938
|
+
if (event.type === 'approval/decided') {
|
|
1939
|
+
const id = event.data?.id
|
|
1940
|
+
// decided 不带 callId → 用 askedId 线性反查;先记下 callId 再删 pending
|
|
1941
|
+
const decidedKeys = []
|
|
1942
|
+
for (const [key, p] of pendingApprovals) {
|
|
1943
|
+
if (p.askedId === id) { decidedKeys.push(key); pendingApprovals.delete(key); break }
|
|
1944
|
+
}
|
|
1945
|
+
// 拒绝/批准通道收口:裁决后令牌和 waiter(askedId + callId 两种键)立即失效
|
|
1946
|
+
if (typeof id === 'string') {
|
|
1947
|
+
rejectWaiters.delete(id)
|
|
1948
|
+
approveWaiters.delete(id)
|
|
1949
|
+
for (const key of decidedKeys) { rejectWaiters.delete(key); approveWaiters.delete(key) }
|
|
1950
|
+
try { rejectStore.revokeKey(id) } catch { /* ignore */ }
|
|
1951
|
+
try { approveStore.revokeKey(id) } catch { /* ignore */ }
|
|
1952
|
+
}
|
|
1953
|
+
return
|
|
1954
|
+
}
|
|
1955
|
+
// needs-input:DSH 没有专用提问事件,唯一信号是 tool/call + 工具名。
|
|
1956
|
+
// 官方 UI 同款分类(dsh-client-ui-chat/lib/client.js:10516):ask_user_question /
|
|
1957
|
+
// request_user_input 是提问,exit_plan_mode 是计划审阅。旧版阻塞式提问也走 tool/call。
|
|
1958
|
+
if (event.type === 'tool/call') {
|
|
1959
|
+
// 批准按钮的参数来源:按 callId 记录下来(approval/asked 本身没有参数)。
|
|
1960
|
+
rememberToolArgs(event.data?.callId, event.data?.arguments)
|
|
1961
|
+
const name = event.data?.name
|
|
1962
|
+
const isQuestion = name === 'ask_user_question' || name === 'request_user_input'
|
|
1963
|
+
const isPlan = name === 'exit_plan_mode'
|
|
1964
|
+
if (!isQuestion && !isPlan) return
|
|
1965
|
+
const sid = session?.id
|
|
1966
|
+
if (!sid) return
|
|
1967
|
+
const callId = event.data?.callId
|
|
1968
|
+
// callId 可能缺失(旧版提问)→ 用 toolName 兜底,避免同会话多个无 callId 提问被误去重(修审计 E)
|
|
1969
|
+
const key = dedupeKey('need', sid, callId || name)
|
|
1970
|
+
if (isDuplicate(key)) return
|
|
1971
|
+
let questions, detail
|
|
1972
|
+
try {
|
|
1973
|
+
const args = JSON.parse(event.data?.arguments || '{}')
|
|
1974
|
+
questions = args.questions || args.question
|
|
1975
|
+
detail = args.plan || args.detail
|
|
1976
|
+
} catch { /* args 不是 JSON:fail-open,用兜底文案 */ }
|
|
1977
|
+
// 计划审阅取 plan 的首个 # 标题行;普通提问取 questions[0].question。
|
|
1978
|
+
if (isPlan && typeof detail === 'string') {
|
|
1979
|
+
const heading = detail.split('\n').find(l => /^\s*#\s+/.test(l))
|
|
1980
|
+
questions = [{ question: (heading || detail).replace(/^\s*#+\s*/, '').slice(0, 140) }]
|
|
1981
|
+
}
|
|
1982
|
+
// 统一门控(同审批):在场/静音时不弹 OS toast(应用内提问卡片照常显示)。
|
|
1983
|
+
if (!shouldDeliver(sid)) return
|
|
1984
|
+
const title = session?.header?.title || 'DSH'
|
|
1985
|
+
const formatted = formatNeedsInput(title, questions, name, isPlan)
|
|
1986
|
+
void deliverTyped(formatted, { onDelivered: () => markHighPriority(sid), sessionId: sid })
|
|
1987
|
+
return
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
if (event.type === 'assistant/message') {
|
|
1991
|
+
const text = extractText(event.data?.message)
|
|
1992
|
+
if (!text) return
|
|
1993
|
+
const turn = event.data?.turn
|
|
1994
|
+
const sid = session?.id
|
|
1995
|
+
if (!sid) return
|
|
1996
|
+
const prev = drafts.get(sid)
|
|
1997
|
+
// 同一轮多条 assistant/message 取最后一个有文本的(与官方折叠逻辑一致)
|
|
1998
|
+
if (!prev || prev.turn !== turn || text.length >= prev.text.length) {
|
|
1999
|
+
drafts.set(sid, { turn, text })
|
|
2000
|
+
}
|
|
2001
|
+
return
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
if (event.type === 'turn/end') {
|
|
2005
|
+
const reason = event.data?.reason
|
|
2006
|
+
const sid = session?.id
|
|
2007
|
+
if (!sid) return
|
|
2008
|
+
// 一轮回复结束 = 新的空闲起点(对齐 Claude idle_prompt:完成回复后才计时)
|
|
2009
|
+
if (idleEnabled && reason?.kind === 'completed') idleTracker.markActivity()
|
|
2010
|
+
const draft = drafts.get(sid)
|
|
2011
|
+
drafts.delete(sid) // 无论哪种 reason 都清草稿,避免串到下一轮
|
|
2012
|
+
const turn = event.data?.turn
|
|
2013
|
+
const kind = reason?.kind
|
|
2014
|
+
// 判定是否值得提醒:completed 正常弹;error/max-tokens/blocked/未知kind 必弹;
|
|
2015
|
+
// aborted 仅 hook 类(如账号登出)弹;interrupted/forked/user-abort 不弹。
|
|
2016
|
+
const isCompleted = kind === 'completed'
|
|
2017
|
+
const isProblem = kind === 'error' || kind === 'max-tokens' || kind === 'blocked'
|
|
2018
|
+
|| (kind === 'aborted' && reason?.reason?.kind === 'hook')
|
|
2019
|
+
|| !['completed', 'aborted', 'interrupted', 'forked'].includes(kind)
|
|
2020
|
+
if (!isCompleted && !isProblem) return
|
|
2021
|
+
const key = dedupeKey(isCompleted ? 'done' : 'problem', sid, turn)
|
|
2022
|
+
if (isDuplicate(key)) return
|
|
2023
|
+
// 统一门控(静音 > 焦点 > ALWAYS_NOTIFY);在场/静音时不弹,其余 fail-open 照弹。
|
|
2024
|
+
if (!shouldDeliver(sid)) return
|
|
2025
|
+
// 同步冷却窗:完成通知若在同会话最近 5s 内有高优先级活动则跳过(审批/提问/错误赢)。
|
|
2026
|
+
// 注意:isDuplicate 的 key 已在上面消费——被焦点/静音/冷却抑制的事件不补发(行业惯例)。
|
|
2027
|
+
if (isCompleted) {
|
|
2028
|
+
if (shouldSkipAsCompletion('success', sid, Date.now(), highPriorityAt.get(sid), COOLDOWN_MS)) return
|
|
2029
|
+
}
|
|
2030
|
+
// 注意(修审计 B):错误类不再标记高优先级——错误后重试成功应正常弹完成,
|
|
2031
|
+
// 否则用户只看到错误、永远看不到成功。冷却窗只服务于"审批/提问压完成"。
|
|
2032
|
+
const title = session?.header?.title || 'DSH'
|
|
2033
|
+
const draftText = draft?.text || '任务已完成'
|
|
2034
|
+
if (isCompleted) {
|
|
2035
|
+
// 完成通知:等后台排空再弹(DSH 版 held-back Stop),回调里重求值门控。
|
|
2036
|
+
deliverCompletionWhenIdle(sid, () => formatCompletion(title, draftText.slice(0, 200)))
|
|
2037
|
+
} else {
|
|
2038
|
+
// 错误类:高优先级,立即投递(不等待后台)
|
|
2039
|
+
const formatted = formatTurnProblem(reason, title, draft?.text)
|
|
2040
|
+
void deliverTyped(formatted, { sessionId: sid })
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
} catch {
|
|
2044
|
+
// 通知逻辑绝不 throw 进 cordis fiber
|
|
2045
|
+
}
|
|
2046
|
+
})
|
|
2047
|
+
|
|
2048
|
+
ctx.on('session/disposed', (session) => {
|
|
2049
|
+
bg.drop(session?.id) // 关掉这个会话的待投递,别的会话不受影响(审计 #2)
|
|
2050
|
+
highPriorityAt.delete(session?.id)
|
|
2051
|
+
drafts.delete(session?.id)
|
|
2052
|
+
})
|
|
2053
|
+
|
|
2054
|
+
ctx.effect(() => () => {
|
|
2055
|
+
bg.clear() // 让所有待触发的后台重试回调失效
|
|
2056
|
+
drafts.clear()
|
|
2057
|
+
seen.clear()
|
|
2058
|
+
pendingApprovals.clear()
|
|
2059
|
+
highPriorityAt.clear()
|
|
2060
|
+
suppressedApprovals.clear()
|
|
2061
|
+
rejectWaiters.clear()
|
|
2062
|
+
})
|
|
2063
|
+
}
|
|
2064
|
+
|