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.
@@ -0,0 +1,9 @@
1
+ # origin: opencode-agent/hy4-flash-free | 2026-11-23T21:28:30+08:00 | bundle patch:把插件插入 loader
2
+ # 注意:这里的 name 必须是「本机安装的那个包名」(本地 link 安装是 dsh-notification-focus)。
3
+ # 发布时由仓库根的 tools/build-publish.mjs 自动改写成发布包名,不要手改发布物(dist/ 或 tgz)。
4
+ # 顶层数组;insert 条目必须有 id(0.2.2-rc.5 实测 ensureInsertIds 规则)
5
+ - insert:
6
+ - id: dsh-notification
7
+ name: 'dsh-notification-focus'
8
+ config: {}
9
+
@@ -0,0 +1,212 @@
1
+ // origin: opencode-agent/hy4-flash-free | 2026-11-27T09:08:48+08:00 | 通知历史本地存储
2
+
3
+ // 设计目标(对齐 state-store.js 的成熟模式):
4
+ // 1. 绝不 throw:文件损坏 / 权限不足 / 路径不对一律 fail-open 回 {v:1, items:[]};
5
+ // 2. 只存白名单字段(ts/kind/title/subtitle/sessionId),任何 token/key/secret 等字段一律丢弃;
6
+ // 3. 原子写:临时文件 + rename,写入串行化,失败清理临时文件并返回 false;
7
+ // 4. 严格 schema:kind 必须合法、ts 必须是有限整数且不超过 now+60000;
8
+ // 5. 内部不写日志、不联网、不读凭据。
9
+
10
+ import * as nodeFs from 'node:fs'
11
+ import * as nodePath from 'node:path'
12
+ import { homedir } from 'node:os'
13
+
14
+ export const VALID_KINDS = Object.freeze(['success', 'approval', 'needs-input', 'error', 'idle'])
15
+ export const DEFAULT_MAX_ITEMS = 200
16
+ export const DEFAULT_RETENTION_DAYS = 7
17
+
18
+ const DAY_MS = 24 * 60 * 60 * 1000
19
+ const TITLE_LIMIT = 200
20
+ const SUBTITLE_LIMIT = 300
21
+ const TS_FUTURE_SLACK = 60 * 1000
22
+ const SESSION_RE = /^[A-Za-z0-9_.:-]{1,200}$/
23
+ const ALLOWED_KEYS = Object.freeze(['ts', 'kind', 'title', 'subtitle', 'sessionId'])
24
+
25
+ function isPlainObject(v) {
26
+ return v !== null && typeof v === 'object' && !Array.isArray(v)
27
+ }
28
+
29
+ // 默认路径在仓库外:Windows 用 %LOCALAPPDATA%\dsh-notification\history.json,
30
+ // 其他平台用 $XDG_DATA_HOME/dsh-notification/history.json(逻辑参考 state-store.js)。
31
+ export function resolveDefaultPath(pathImpl, env, platform) {
32
+ const P = pathImpl || nodePath
33
+ const E = env || process.env
34
+ const plat = platform || process.platform
35
+ let base
36
+ if (plat === 'win32') {
37
+ base = E.LOCALAPPDATA
38
+ || (E.USERPROFILE ? P.join(E.USERPROFILE, 'AppData', 'Local') : P.join(homedir(), 'AppData', 'Local'))
39
+ } else {
40
+ base = E.XDG_DATA_HOME || P.join(E.HOME || homedir(), '.local', 'share')
41
+ }
42
+ return P.join(base, 'dsh-notification', 'history.json')
43
+ }
44
+
45
+ // 同时兼容 promise 风格(fs.promises)和同步替身(内存 fs)。
46
+ function pickFn(fs, asyncName, syncName) {
47
+ if (!fs) return null
48
+ if (typeof fs[asyncName] === 'function') return fs[asyncName].bind(fs)
49
+ if (typeof fs[syncName] === 'function') return fs[syncName].bind(fs)
50
+ return null
51
+ }
52
+
53
+ const REAL_FS = {
54
+ readFile: nodeFs.promises.readFile,
55
+ writeFile: nodeFs.promises.writeFile,
56
+ rename: nodeFs.promises.rename,
57
+ mkdir: nodeFs.promises.mkdir,
58
+ unlink: nodeFs.promises.unlink,
59
+ }
60
+
61
+ // 校验 + 白名单裁剪:返回全新对象或 null(表示整项非法)。
62
+ // upperTs 由调用方决定:add 用 now+60s,load 用 MAX_SAFE_INTEGER(不因时钟漂移丢旧项)。
63
+ function sanitizeItem(item, upperTs) {
64
+ if (!isPlainObject(item)) return null
65
+ if (!VALID_KINDS.includes(item.kind)) return null
66
+ if (!Number.isInteger(item.ts) || item.ts < 0 || item.ts > upperTs) return null
67
+
68
+ const out = {
69
+ ts: item.ts,
70
+ kind: item.kind,
71
+ title: typeof item.title === 'string' ? item.title.slice(0, TITLE_LIMIT) : '',
72
+ subtitle: typeof item.subtitle === 'string' ? item.subtitle.slice(0, SUBTITLE_LIMIT) : '',
73
+ }
74
+ if (typeof item.sessionId === 'string' && SESSION_RE.test(item.sessionId)) {
75
+ out.sessionId = item.sessionId
76
+ }
77
+ // 只输出白名单键,天然挡掉 token / apiKey / password / __proto__ 等。
78
+ for (const k of Object.keys(out)) {
79
+ if (!ALLOWED_KEYS.includes(k)) delete out[k]
80
+ }
81
+ return out
82
+ }
83
+
84
+ function sortTruncate(arr, maxItems) {
85
+ return arr.slice().sort((a, b) => b.ts - a.ts).slice(0, maxItems)
86
+ }
87
+
88
+ export function createHistoryStore(options = {}) {
89
+ const {
90
+ fs = REAL_FS,
91
+ path = nodePath,
92
+ filePath,
93
+ now = () => Date.now(),
94
+ maxItems,
95
+ retentionDays,
96
+ pid = process.pid,
97
+ } = options
98
+ const target = filePath || resolveDefaultPath(path, process.env, process.platform)
99
+
100
+ const limit = Number.isFinite(maxItems) && maxItems > 0 ? Math.floor(maxItems) : DEFAULT_MAX_ITEMS
101
+ const retention = Number.isFinite(retentionDays) && retentionDays >= 0
102
+ ? retentionDays
103
+ : DEFAULT_RETENTION_DAYS
104
+
105
+ const readFn = pickFn(fs, 'readFile', 'readFileSync')
106
+ const writeFn = pickFn(fs, 'writeFile', 'writeFileSync')
107
+ const renameFn = pickFn(fs, 'rename', 'renameSync')
108
+ const mkdirFn = pickFn(fs, 'mkdir', 'mkdirSync')
109
+ const unlinkFn = pickFn(fs, 'unlink', 'unlinkSync')
110
+
111
+ let seq = 0
112
+ let items = []
113
+ let queue = Promise.resolve() // 写入串行化:并发 add/clear 不会互相踩踏
114
+
115
+ function currentTime() {
116
+ try {
117
+ const n = typeof now === 'function' ? now() : now
118
+ return Number.isFinite(n) ? n : 0
119
+ } catch {
120
+ return 0
121
+ }
122
+ }
123
+
124
+ function tempPath() {
125
+ seq += 1
126
+ return `${target}.tmp-${pid}-${currentTime()}-${seq}`
127
+ }
128
+
129
+ async function ensureDir() {
130
+ if (!mkdirFn) return // 内存替身不需要建目录
131
+ await mkdirFn(path.dirname(target), { recursive: true })
132
+ }
133
+
134
+ // 原子写:临时文件 + rename;失败清理临时文件,返回 false(不抛)。
135
+ async function writeItems(listItems) {
136
+ if (!writeFn || !renameFn) return false
137
+ const json = JSON.stringify({ v: 1, items: listItems })
138
+ const tmp = tempPath()
139
+ try {
140
+ await ensureDir()
141
+ await writeFn(tmp, json, { encoding: 'utf8', mode: 0o600, flush: true })
142
+ await renameFn(tmp, target)
143
+ return true
144
+ } catch {
145
+ try { if (unlinkFn) await unlinkFn(tmp) } catch { /* ignore */ }
146
+ return false
147
+ }
148
+ }
149
+
150
+ const empty = () => ({ v: 1, items: [] })
151
+
152
+ // 读取:任何错误都 fail-open 回空列表,绝不 reject。
153
+ async function load() {
154
+ try {
155
+ if (!readFn) { items = []; return empty() }
156
+ const raw = await readFn(target, 'utf8')
157
+ if (typeof raw !== 'string' || raw.length === 0) { items = []; return empty() }
158
+ let parsed
159
+ try {
160
+ parsed = JSON.parse(raw)
161
+ } catch {
162
+ items = []; return empty() // 损坏 JSON
163
+ }
164
+ if (!isPlainObject(parsed) || !Array.isArray(parsed.items)) {
165
+ items = []; return empty() // null / [] / 字符串 / 非数组 items
166
+ }
167
+ const cutoff = currentTime() - retention * DAY_MS
168
+ const cleaned = []
169
+ for (const rawItem of parsed.items) {
170
+ const it = sanitizeItem(rawItem, Number.MAX_SAFE_INTEGER)
171
+ if (it && it.ts >= cutoff) cleaned.push(it)
172
+ }
173
+ items = sortTruncate(cleaned, limit)
174
+ return { v: 1, items: items.slice() }
175
+ } catch {
176
+ items = []
177
+ return empty() // 权限 / 路径 / 磁盘错误
178
+ }
179
+ }
180
+
181
+ // 新增:先同步校验(非法项直接 false),再排队原子写;写失败不修改内存基线。
182
+ function add(item) {
183
+ const clean = sanitizeItem(item, currentTime() + TS_FUTURE_SLACK)
184
+ if (!clean) return Promise.resolve(false)
185
+ const job = queue.then(async () => {
186
+ const next = sortTruncate([...items, clean], limit)
187
+ const ok = await writeItems(next)
188
+ if (ok) items = next
189
+ return ok
190
+ })
191
+ queue = job.catch(() => true) // 双保险:即便未来引入 reject 也不阻塞队列
192
+ return job
193
+ }
194
+
195
+ // 清空:写空列表(不删文件),串行化,永不 throw。
196
+ function clear() {
197
+ const job = queue.then(async () => {
198
+ const ok = await writeItems([])
199
+ if (ok) items = []
200
+ return ok
201
+ })
202
+ queue = job.catch(() => true)
203
+ return job
204
+ }
205
+
206
+ // 当前内存项的降序副本;外部修改返回值不会影响存储内部。
207
+ function list() {
208
+ return items.slice()
209
+ }
210
+
211
+ return { filePath: target, load, add, clear, list }
212
+ }
package/idle-prompt.js ADDED
@@ -0,0 +1,188 @@
1
+ // origin: opencode-agent/hy4-flash-free | 2026-11-26T11:30:25+08:00 | 空闲提醒判定核心:纯函数 + 一次性状态机(已接入 Host/client,默认关闭)
2
+
3
+ /**
4
+ * 空闲提醒(idle_prompt)判定核心。
5
+ *
6
+ * 设计约束(与 docs/IDLE-PROMPT-DESIGN.md 一致):
7
+ * 1. 默认关闭:仅在 DSH_NOTIFICATION_IDLE=1 时允许触发;本模块被导入本身零副作用。
8
+ * 2. 门控不可绕过:shouldFireIdle 的 gate 参数必须来自集成层的 shouldDeliver(sid)
9
+ * (enabled > quiet/snooze > 焦点 > ALWAYS_NOTIFY)。gate !== true 一律不触发。
10
+ * 3. 不重复打扰:一次 markActivity() 开启一个窗口,窗口内最多触发一次;
11
+ * 只有新的用户活动(markActivity)才重新武装。
12
+ * 4. 后台忙抑制:复用 workspace/session-activity 语义(见 hasLiveBackground),
13
+ * backgroundActive=true 时不触发,且**不消费**一次性令牌(后台排空后可再判定)。
14
+ * 5. 时间可注入:所有时间来自参数 / now 注入,便于单测;无定时器、无副作用、无系统钩子。
15
+ *
16
+ * 本文件只导出判定逻辑,不弹 toast、不注册路由、不读写磁盘/环境以外的状态。
17
+ */
18
+
19
+ /** 默认空闲阈值:60 秒(对齐 Claude Code messageIdleNotifThresholdMs=60000)。 */
20
+ export const DEFAULT_IDLE_THRESHOLD_MS = 60 * 1000
21
+
22
+ /** 功能开关环境变量名(仅字符串 '1' 开启,其余一律关闭)。 */
23
+ export const IDLE_ENV_FLAG = 'DSH_NOTIFICATION_IDLE'
24
+
25
+ /** 把任意输入收敛成有限数字;非法输入返回 null(用于 fail-closed,不误报)。 */
26
+ function finiteOrNull(value) {
27
+ const n = Number(value)
28
+ return Number.isFinite(n) ? n : null
29
+ }
30
+
31
+ /**
32
+ * 纯判定:距最后一次用户活动是否已达到阈值。
33
+ *
34
+ * @param {number} now 当前时间(毫秒时间戳)
35
+ * @param {number} lastActivityAt 最后一次用户活动时间(毫秒时间戳)
36
+ * @param {number} [thresholdMs] 阈值,默认 60000
37
+ * @returns {boolean} 达到/超过阈值才为 true
38
+ *
39
+ * fail-closed 规则(宁可不提醒,也不打扰):
40
+ * - 任一入参非有限数字 → false
41
+ * - 阈值 < 0 → false
42
+ * - 时钟回拨(now < lastActivityAt)→ false
43
+ */
44
+ export function isIdle(now, lastActivityAt, thresholdMs = DEFAULT_IDLE_THRESHOLD_MS) {
45
+ const n = finiteOrNull(now)
46
+ const a = finiteOrNull(lastActivityAt)
47
+ const t = finiteOrNull(thresholdMs)
48
+ if (n === null || a === null || t === null) return false
49
+ if (t < 0) return false
50
+ if (n < a) return false
51
+ return n - a >= t
52
+ }
53
+
54
+ /**
55
+ * 纯判定:这一刻是否该弹空闲提醒。
56
+ *
57
+ * @param {object} args
58
+ * @param {number} args.now
59
+ * @param {number} args.lastActivityAt
60
+ * @param {number} [args.thresholdMs]
61
+ * @param {boolean} [args.backgroundActive] 后台是否仍有活动(workspace/session-activity)
62
+ * @param {boolean} [args.gate] 集成层门控结果(feature flag && shouldDeliver(sid));默认 false
63
+ * @param {boolean} [args.alreadyFired] 当前窗口是否已触发过(一次性语义)
64
+ * @returns {boolean}
65
+ *
66
+ * 优先级(先便宜的后贵:门控 → 一次性 → 后台 → 时间):
67
+ * gate 未显式给 true → false(静音/在场/总开关绝不被绕过)
68
+ * 已触发过 → false
69
+ * 后台忙 → false
70
+ * 未到阈值 → false
71
+ */
72
+ export function shouldFireIdle({
73
+ now,
74
+ lastActivityAt,
75
+ thresholdMs = DEFAULT_IDLE_THRESHOLD_MS,
76
+ backgroundActive = false,
77
+ gate = false,
78
+ alreadyFired = false,
79
+ } = {}) {
80
+ if (gate !== true) return false
81
+ if (alreadyFired === true) return false
82
+ if (Boolean(backgroundActive)) return false
83
+ return isIdle(now, lastActivityAt, thresholdMs)
84
+ }
85
+
86
+ /**
87
+ * 功能开关读取(默认关闭)。
88
+ *
89
+ * 只有 process.env.DSH_NOTIFICATION_IDLE === '1' 才返回 true。
90
+ * 允许显式传入 env 对象注入,便于单测;无 process 的环境(浏览器)按关闭处理。
91
+ */
92
+ export function isIdleFeatureEnabled(env) {
93
+ let source = env
94
+ if (source === undefined) {
95
+ source = (typeof process !== 'undefined' && process && process.env) ? process.env : {}
96
+ }
97
+ return source && source[IDLE_ENV_FLAG] === '1'
98
+ }
99
+
100
+ /**
101
+ * 把 time source 收敛成函数:可注入函数(可控时钟)或固定数值(冻结时钟)。
102
+ * 未注入时用 Date.now。
103
+ */
104
+ function makeClock(now) {
105
+ if (typeof now === 'function') return () => Number(now())
106
+ const fixed = finiteOrNull(now)
107
+ if (fixed !== null) return () => fixed
108
+ return () => Date.now()
109
+ }
110
+
111
+ /**
112
+ * 一次性状态机:ARMED(待触发)→ FIRED(已触发,锁死)→ markActivity() → ARMED。
113
+ *
114
+ * createIdleTracker({ thresholdMs, now, enabled })
115
+ * .markActivity([at]) 记录用户活动(或一轮回复完成),重置一次性令牌
116
+ * .evaluate(backgroundActive, gate) 判定并原子地消费一次性令牌
117
+ * .isFired() / .snapshot() 可观测状态(诊断/测试)
118
+ *
119
+ * @param {object} [opts]
120
+ * @param {number} [opts.thresholdMs] 默认 60000
121
+ * @param {Function|number} [opts.now] 注入时钟(函数或固定时间戳)
122
+ * @param {boolean} [opts.enabled] 默认读 DSH_NOTIFICATION_IDLE(默认关);
123
+ * 集成层可显式传 true/false 覆盖。
124
+ */
125
+ export function createIdleTracker({ thresholdMs = DEFAULT_IDLE_THRESHOLD_MS, now, enabled } = {}) {
126
+ const clock = makeClock(now)
127
+ const featureOn = enabled === undefined ? isIdleFeatureEnabled() : Boolean(enabled)
128
+
129
+ let lastActivityAt = clock()
130
+ let fired = false
131
+
132
+ return {
133
+ /** 记录一次用户活动:重置空闲起点 + 解锁一次性令牌。 */
134
+ markActivity(at) {
135
+ const stamp = at === undefined ? clock() : finiteOrNull(at)
136
+ lastActivityAt = stamp === null ? clock() : stamp
137
+ fired = false
138
+ return lastActivityAt
139
+ },
140
+
141
+ /**
142
+ * 求值一次。返回 true 表示本次真的触发了(令牌被原子消费)。
143
+ *
144
+ * gate 必须显式传 true(集成层已确认 feature flag + shouldDeliver(sid) 都通过);
145
+ * 默认 false 是 fail-closed:忘传门控时绝不会打扰用户。
146
+ */
147
+ evaluate(backgroundActive, gate = false) {
148
+ if (!featureOn) return false
149
+ const fire = shouldFireIdle({
150
+ now: clock(),
151
+ lastActivityAt,
152
+ thresholdMs,
153
+ backgroundActive,
154
+ gate,
155
+ alreadyFired: fired,
156
+ })
157
+ if (fire) fired = true
158
+ return fire
159
+ },
160
+
161
+ /** 当前窗口是否已触发过。 */
162
+ isFired() {
163
+ return fired
164
+ },
165
+
166
+ /** 只读快照,便于诊断与断言。 */
167
+ snapshot() {
168
+ const current = clock()
169
+ return {
170
+ lastActivityAt,
171
+ fired,
172
+ thresholdMs,
173
+ enabled: featureOn,
174
+ elapsedMs: current >= lastActivityAt ? current - lastActivityAt : 0,
175
+ }
176
+ },
177
+ }
178
+ }
179
+
180
+ // 供测试/集成层显式引用的默认值(无副作用)。
181
+ export const __idle = {
182
+ isIdle,
183
+ shouldFireIdle,
184
+ isIdleFeatureEnabled,
185
+ createIdleTracker,
186
+ DEFAULT_IDLE_THRESHOLD_MS,
187
+ IDLE_ENV_FLAG,
188
+ }