@morgan9668/dsh-task-notify 0.0.0-stage → 1.1.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/client.js ADDED
@@ -0,0 +1,402 @@
1
+ /**
2
+ * @morgan9668/dsh-task-notify — 浏览器半身。
3
+ *
4
+ * 参考 dsh-our-free-model 的可用实现,三件事必须完全对齐:
5
+ *
6
+ * 1. slot 名是 `settings.section`,用 `id`(不是 key),配 `order` 与 `label`;
7
+ * 2. `inject = ['slots', 'locale']`,数组形式;
8
+ * 3. 模块导出走 `module.exports`,文件末尾 `return module.exports`。
9
+ *
10
+ * 数据读写走插件自己的同源路由 `/api/task-notify/*`,与 our-free-model 的
11
+ * `/api/our-free-model/*` 是同一个套路:这些路由由同一个 host 进程提供,
12
+ * 不依赖 configForms 那套 scope 绑定。
13
+ */
14
+
15
+ window.__ModuleLoader__.load({
16
+ id: '@morgan9668/dsh-task-notify',
17
+ factory: require => {
18
+ const module = { exports: {} }
19
+ const exports = module.exports
20
+
21
+ const React = require('react')
22
+ const h = React.createElement
23
+ const { useState, useEffect, useCallback } = React
24
+
25
+ /** 与 Host 的 patch row id 一致。 */
26
+ const NS = 'task-notify'
27
+ /** 同源 API 前缀,必须与 index.js 的路由一致。 */
28
+ const API = '/api/task-notify'
29
+
30
+ const DICT = {
31
+ zh: { nav: '任务完成通知' },
32
+ en: { nav: 'Task completion notifier' },
33
+ }
34
+
35
+ /* ----------------------------- 样式 ----------------------------- */
36
+
37
+ const CSS = `
38
+ .tn-card { font-family: inherit; color: var(--dsh-text, inherit); }
39
+ .tn-row { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
40
+ .tn-label { font-size: 13px; opacity: .8; }
41
+ .tn-input { width: 100%; box-sizing: border-box; padding: 8px 10px; font-size: 13px;
42
+ font-family: inherit; color: inherit; border-radius: 6px; outline: none;
43
+ background: var(--dsh-input-bg, rgba(128,128,128,.1));
44
+ border: 1px solid var(--dsh-border, rgba(128,128,128,.3)); }
45
+ .tn-input:disabled { opacity: .5; }
46
+ .tn-block { border: 1px solid var(--dsh-border, rgba(128,128,128,.22));
47
+ border-radius: 8px; padding: 14px 16px; margin: 12px 0; }
48
+ .tn-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; }
49
+ .tn-name { font-size: 14px; font-weight: 600; }
50
+ .tn-badge { font-size: 11px; padding: 2px 8px; border-radius: 999px;
51
+ border: 1px solid currentColor; opacity: .8; }
52
+ .tn-badge.on { color: #1a9d55; }
53
+ .tn-hint { font-size: 12px; opacity: .62; line-height: 1.65; margin: 4px 0 10px; }
54
+ .tn-field { margin-bottom: 10px; }
55
+ .tn-field > .tn-label { display: block; margin-bottom: 4px; font-size: 12px; opacity: .72; }
56
+ .tn-btn { padding: 8px 16px; font-size: 13px; font-family: inherit; color: #fff;
57
+ background: var(--dsh-accent, #2b7fff); border: none; border-radius: 6px; cursor: pointer;
58
+ /* 「发送测试」四个字永不折行,也不被 flex 压缩成窄条。 */
59
+ white-space: nowrap; flex: none; }
60
+ .tn-btn:disabled { opacity: .6; cursor: default; }
61
+ .tn-status { font-size: 12.5px; margin-top: 10px; line-height: 1.6; }
62
+ .tn-ok { color: #1a9d55; } .tn-bad { color: #d64545; } .tn-warn { color: #c9821a; }
63
+ .tn-title { font-size: 16px; font-weight: 600; margin: 0 0 4px; }
64
+ .tn-sub { font-size: 12.5px; opacity: .65; margin: 0; line-height: 1.6; }
65
+ /* 标题区独占一行,不参与水平挤压,副标题可以自然折行。 */
66
+ .tn-header { display: block; margin-bottom: 14px; }
67
+ /* 左开关 + 右按钮:两端对齐、垂直居中。
68
+ 里面的 Toggle 是 <label>,默认带 margin-bottom,这里要抹掉,
69
+ 否则整行会偏向一侧。 */
70
+ .tn-row-split { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 10px; }
71
+ .tn-row-split > .tn-row { margin-bottom: 0; flex: 1 1 auto; min-width: 0; }
72
+ `
73
+
74
+ /* ---------------------------- 小工具 ---------------------------- */
75
+
76
+ function useStyles() {
77
+ useEffect(() => {
78
+ const style = document.createElement('style')
79
+ style.setAttribute('data-plugin', 'dsh-task-notify')
80
+ style.textContent = CSS
81
+ document.head.appendChild(style)
82
+ return () => style.remove()
83
+ }, [])
84
+ }
85
+
86
+ async function callApi(path, init) {
87
+ const response = await fetch(API + path, {
88
+ credentials: 'same-origin',
89
+ cache: 'no-store',
90
+ headers: { 'content-type': 'application/json' },
91
+ ...init,
92
+ })
93
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
94
+ return await response.json()
95
+ }
96
+
97
+ /* ---------------------------- 控件 ---------------------------- */
98
+
99
+ function Toggle({ label, checked, onChange, disabled }) {
100
+ return h(
101
+ 'label',
102
+ { className: 'tn-row', style: { cursor: disabled ? 'default' : 'pointer' } },
103
+ h('input', {
104
+ type: 'checkbox',
105
+ checked: checked === true,
106
+ disabled,
107
+ onChange: event => onChange(event.target.checked),
108
+ }),
109
+ h('span', { className: 'tn-label' }, label),
110
+ )
111
+ }
112
+
113
+ function Field({ label, value, placeholder, onCommit, disabled }) {
114
+ const [draft, setDraft] = useState(value ?? '')
115
+ useEffect(() => {
116
+ setDraft(value ?? '')
117
+ }, [value])
118
+ return h(
119
+ 'div',
120
+ { className: 'tn-field' },
121
+ h('span', { className: 'tn-label' }, label),
122
+ h('input', {
123
+ className: 'tn-input',
124
+ value: draft,
125
+ placeholder: placeholder ?? '',
126
+ disabled,
127
+ spellCheck: false,
128
+ onChange: event => setDraft(event.target.value),
129
+ onBlur: () => {
130
+ if (draft !== (value ?? '')) onCommit(draft.trim())
131
+ },
132
+ onKeyDown: event => {
133
+ if (event.key === 'Enter') event.currentTarget.blur()
134
+ },
135
+ }),
136
+ )
137
+ }
138
+
139
+ /* -------------------------- 设置页面 -------------------------- */
140
+
141
+ function SettingsPage() {
142
+ useStyles()
143
+ const [settings, setSettings] = useState(null)
144
+ const [error, setError] = useState('')
145
+ const [saving, setSaving] = useState(false)
146
+ const [saveMsg, setSaveMsg] = useState('')
147
+ const [testing, setTesting] = useState(false)
148
+ const [testMsg, setTestMsg] = useState('')
149
+
150
+ const load = useCallback(async () => {
151
+ try {
152
+ const data = await callApi('/settings')
153
+ setSettings(data.settings ?? {})
154
+ setError('')
155
+ } catch (e) {
156
+ setError(`读取配置失败:${e.message}`)
157
+ }
158
+ }, [])
159
+
160
+ useEffect(() => {
161
+ void load()
162
+ }, [load])
163
+
164
+ /** 按 path 写一个字段,服务端返回新配置。 */
165
+ const setPath = useCallback(
166
+ async (path, value) => {
167
+ setSaving(true)
168
+ setSaveMsg('保存中…')
169
+ try {
170
+ const data = await callApi('/settings', {
171
+ method: 'POST',
172
+ body: JSON.stringify({ path, value }),
173
+ })
174
+ setSettings(data.settings ?? settings)
175
+ setSaveMsg('已保存,立即生效')
176
+ } catch (e) {
177
+ setSaveMsg(`保存失败:${e.message}`)
178
+ } finally {
179
+ setSaving(false)
180
+ }
181
+ },
182
+ [settings],
183
+ )
184
+
185
+ const runTest = useCallback(async () => {
186
+ setTesting(true)
187
+ setTestMsg('')
188
+ try {
189
+ const data = await callApi('/test', { method: 'POST' })
190
+ const list = Array.isArray(data.results) ? data.results : []
191
+ if (list.length === 0) {
192
+ setTestMsg('没有已启用的渠道')
193
+ } else {
194
+ const failed = list.filter(entry => !entry.ok)
195
+ setTestMsg(
196
+ failed.length === 0
197
+ ? `${list.length} 个渠道均发送成功`
198
+ : failed.map(entry => `${entry.channel}:${entry.detail ?? '失败'}`).join(';'),
199
+ )
200
+ }
201
+ } catch (e) {
202
+ setTestMsg(`测试失败:${e.message}`)
203
+ } finally {
204
+ setTesting(false)
205
+ }
206
+ }, [])
207
+
208
+ if (error !== '') {
209
+ return h(
210
+ 'div',
211
+ { className: 'tn-card' },
212
+ h('p', { className: 'tn-title' }, '任务完成通知'),
213
+ h('p', { className: 'tn-status tn-bad' }, error),
214
+ )
215
+ }
216
+
217
+ if (settings === null) {
218
+ return h(
219
+ 'div',
220
+ { className: 'tn-card' },
221
+ h('p', { className: 'tn-title' }, '任务完成通知'),
222
+ h('p', { className: 'tn-sub' }, '读取配置中…'),
223
+ )
224
+ }
225
+
226
+ const channels = settings.channels ?? {}
227
+ const wecom = channels.wecom ?? {}
228
+ const feishu = channels.feishu ?? {}
229
+ const dingtalk = channels.dingtalk ?? {}
230
+ const wechat = channels.wechat ?? {}
231
+
232
+ const readyCount = [
233
+ wecom.enabled && wecom.webhook,
234
+ feishu.enabled && feishu.webhook,
235
+ dingtalk.enabled && dingtalk.webhook,
236
+ wechat.enabled && (wechat.serverchanSendKey || wechat.wxpusherAppToken),
237
+ ].filter(Boolean).length
238
+
239
+ const channelBlock = (name, kind, cfg, ready, hint, fields) =>
240
+ h(
241
+ 'div',
242
+ { className: 'tn-block' },
243
+ h(
244
+ 'div',
245
+ { className: 'tn-head' },
246
+ h('span', { className: 'tn-name' }, name),
247
+ h(
248
+ 'span',
249
+ { className: `tn-badge${ready ? ' on' : ''}` },
250
+ ready ? '已就绪' : '未启用',
251
+ ),
252
+ ),
253
+ h('p', { className: 'tn-hint' }, hint),
254
+ h(Toggle, {
255
+ label: `启用${name}`,
256
+ checked: cfg.enabled === true,
257
+ disabled: saving,
258
+ onChange: value => setPath(['channels', kind, 'enabled'], value),
259
+ }),
260
+ ...fields.map(([key, label, placeholder]) =>
261
+ h(Field, {
262
+ key,
263
+ label,
264
+ value: cfg[key] ?? '',
265
+ placeholder,
266
+ disabled: saving,
267
+ onCommit: value => setPath(['channels', kind, key], value),
268
+ }),
269
+ ),
270
+ )
271
+
272
+ return h(
273
+ 'div',
274
+ { className: 'tn-card' },
275
+ // 标题与副标题独占一行,不参与任何水平挤压。
276
+ h(
277
+ 'div',
278
+ { className: 'tn-header' },
279
+ h('p', { className: 'tn-title' }, '任务完成通知'),
280
+ h(
281
+ 'p',
282
+ { className: 'tn-sub' },
283
+ '每个回合结束后,把任务概要、耗时与 token 消耗推送到群机器人。',
284
+ readyCount > 0 ? ` 当前 ${readyCount} 个渠道就绪。` : ' 当前没有可用渠道。',
285
+ ),
286
+ ),
287
+
288
+ h(Toggle, {
289
+ label: '启用通知',
290
+ checked: settings.enabled !== false,
291
+ disabled: saving,
292
+ onChange: value => setPath(['enabled'], value),
293
+ }),
294
+ // 「子代理」这一行左侧是开关、右侧是发送测试按钮。
295
+ // 按钮 white-space: nowrap + flex: none,四个字不折行、不被压窄。
296
+ h(
297
+ 'div',
298
+ { className: 'tn-row-split' },
299
+ h(Toggle, {
300
+ label: '子代理会话也通知(默认关,避免刷屏)',
301
+ checked: settings.notifySubagents === true,
302
+ disabled: saving,
303
+ onChange: value => setPath(['notifySubagents'], value),
304
+ }),
305
+ h(
306
+ 'button',
307
+ { className: 'tn-btn', onClick: runTest, disabled: testing },
308
+ testing ? '发送中…' : '发送测试',
309
+ ),
310
+ ),
311
+
312
+ // 顺序按实际使用频率排:飞书、钉钉在前,企业微信与微信在后。
313
+ channelBlock(
314
+ '飞书',
315
+ 'feishu',
316
+ feishu,
317
+ Boolean(feishu.enabled && feishu.webhook),
318
+ '群 → 设置 → 群机器人 → 添加 → 自定义机器人 → 复制 Webhook;开了签名校验就把密钥填上。',
319
+ [
320
+ ['webhook', 'Webhook 地址', 'https://open.feishu.cn/open-apis/bot/v2/hook/...'],
321
+ ['secret', '签名密钥(可选)', '未开启签名校验则留空'],
322
+ ],
323
+ ),
324
+ channelBlock(
325
+ '钉钉',
326
+ 'dingtalk',
327
+ dingtalk,
328
+ Boolean(dingtalk.enabled && dingtalk.webhook),
329
+ '群 → 智能群助手 → 添加机器人 → 自定义 → 复制 Webhook。'
330
+ + '若安全设置选了「加签」,把密钥一并填上;选了「自定义关键词」则不用。',
331
+ [
332
+ ['webhook', 'Webhook 地址', 'https://oapi.dingtalk.com/robot/send?access_token=...'],
333
+ ['secret', '加签密钥(选了加签才填)', 'SEC...'],
334
+ ],
335
+ ),
336
+ channelBlock(
337
+ '企业微信',
338
+ 'wecom',
339
+ wecom,
340
+ Boolean(wecom.enabled && wecom.webhook),
341
+ '群 → 群机器人 → 添加机器人 → 创建 → 复制 Webhook 地址。',
342
+ [['webhook', 'Webhook 地址', 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...']],
343
+ ),
344
+ channelBlock(
345
+ '微信',
346
+ 'wechat',
347
+ wechat,
348
+ Boolean(wechat.enabled && (wechat.serverchanSendKey || wechat.wxpusherAppToken)),
349
+ '微信不开放第三方直接推送到个人号,需经服务号中转。个人主体无法自建服务号,所以用服务商通道:Server酱或 WxPusher。',
350
+ [
351
+ ['serverchanSendKey', 'Server酱 SendKey', 'SCT... 或 sctp...'],
352
+ ['wxpusherAppToken', '或 WxPusher appToken', 'AT_...'],
353
+ ],
354
+ ),
355
+
356
+ saveMsg !== '' &&
357
+ h(
358
+ 'div',
359
+ {
360
+ className: `tn-status ${saveMsg.startsWith('已保存') ? 'tn-ok' : saveMsg === '保存中…' ? 'tn-warn' : 'tn-bad'}`,
361
+ },
362
+ saveMsg,
363
+ ),
364
+ testMsg !== '' &&
365
+ h(
366
+ 'div',
367
+ { className: `tn-status ${testMsg.includes('成功') ? 'tn-ok' : 'tn-bad'}` },
368
+ testMsg,
369
+ ),
370
+ )
371
+ }
372
+
373
+ /* ---------------------------- 插件体 ---------------------------- */
374
+
375
+ const inject = ['slots', 'locale']
376
+
377
+ function apply(ctx) {
378
+ const t = ctx.locale.bind(NS)
379
+ ctx.effect(() => ctx.locale.register(NS, { zh: DICT.zh, en: DICT.en }), 'task-notify: dictionaries')
380
+
381
+ // settings.section 是设置页里的一个分区;id 决定它的命名空间,
382
+ // order 决定排序(our-free-model 用 35)。
383
+ ctx.slots.inject('settings.section', () =>
384
+ ctx.slots.register(
385
+ {
386
+ name: 'settings.section',
387
+ id: 'task-notify',
388
+ order: 36,
389
+ label: () => t('nav'),
390
+ locale: NS,
391
+ },
392
+ SettingsPage,
393
+ ),
394
+ )
395
+ }
396
+
397
+ exports.inject = inject
398
+ exports.apply = apply
399
+ exports.name = 'task-notify'
400
+ return module.exports
401
+ },
402
+ })
@@ -0,0 +1,63 @@
1
+ # @morgan9668/dsh-task-notify bundle patch.
2
+ #
3
+ # 一行 insert 即挂载 Host 半身。所有可调项都在下面这份 config 里,
4
+ # 也可以由你自己的 profile / home 补丁层按 id `task-notify` 覆盖
5
+ #(用户层优先级高于 bundle 层)。
6
+ #
7
+ # 渠道全部留空即为「未配置」:插件照常激活,但只在日志里说明没有可用渠道,
8
+ # 不发送任何请求。填好任一渠道后,测试通知可在设置页点「发送测试」触发。
9
+
10
+ - insert:
11
+ - id: task-notify
12
+ name: '@morgan9668/dsh-task-notify'
13
+ config:
14
+ # 总开关。false 时插件不发送任何通知。
15
+ enabled: true
16
+
17
+ # 只在这些回合结局下通知。
18
+ # completed / error / blocked / max-tokens / aborted
19
+ reasons:
20
+ - completed
21
+ - error
22
+ - blocked
23
+
24
+ # 子代理会话默认不通知,避免内部子任务刷屏。
25
+ notifySubagents: false
26
+
27
+ # 通知正文里回复摘要的最大字数(超出截断)。
28
+ maxExcerptChars: 400
29
+
30
+ # 单次 HTTP 请求超时(毫秒)。
31
+ timeoutMs: 8000
32
+
33
+ # ── 渠道配置 ────────────────────────────────────────────────
34
+ # 四个渠道互相独立,可同时开启;留空表示未启用。
35
+
36
+ channels:
37
+ # 微信:预留。需要 Server酱 SendKey 或 WxPusher appToken。
38
+ # 本方案不内置自建服务号,个人主体无法注册服务号。
39
+ wechat:
40
+ enabled: false
41
+ # 预留字段:serverchanSendKey / wxpusherAppToken
42
+ serverchanSendKey: ''
43
+ wxpusherAppToken: ''
44
+
45
+ # 企业微信群机器人 Webhook。
46
+ # 群设置 → 群机器人 → 添加 → 复制 Webhook 地址
47
+ wecom:
48
+ enabled: false
49
+ webhook: ''
50
+
51
+ # 飞书群机器人 Webhook。可选签名校验密钥。
52
+ # 群设置 → 群机器人 → 添加 → 复制 Webhook
53
+ feishu:
54
+ enabled: false
55
+ webhook: ''
56
+ secret: ''
57
+
58
+ # 钉钉群机器人 Webhook。钉钉要求加签,secret 必填。
59
+ # 群设置 → 智能群助手 → 添加机器人 → 自定义 → 复制 Webhook
60
+ dingtalk:
61
+ enabled: false
62
+ webhook: ''
63
+ secret: ''
package/docs/DETAIL.md ADDED
@@ -0,0 +1,76 @@
1
+ # 任务完成通知
2
+
3
+ 每个回合结束后,把 **任务概要 + 耗时 + token 消耗** 推送到你配置的群机器人。
4
+
5
+ 支持的渠道:**企业微信、飞书、钉钉**(个人都能免费开通),**微信**通道预留
6
+ Server酱 / WxPusher 凭据位。
7
+
8
+ ## 通知内容
9
+
10
+ 只报三块,不含会话 ID、git 分支这类噪音:
11
+
12
+ 1. **任务概要** —— 本轮最后一段回复(不含思考过程)+ 工具调用次数
13
+ 2. **耗时** —— `turn/start` 到 `turn/end` 的真实时间差,中文格式化(`3分12秒`)
14
+ 3. **token 消耗** —— 输入 / 输出 / 合计,有缓存命中会额外标注
15
+
16
+ ## 接入引导
17
+
18
+ ### 企业微信
19
+
20
+ 群 → 群机器人 → 添加机器人 → 创建 → 复制 Webhook。
21
+
22
+ ### 飞书
23
+
24
+ 群 → 设置 → 群机器人 → 添加 → 自定义机器人 → 复制 Webhook。
25
+ 开启签名校验的话,密钥一并填入。
26
+
27
+ ### 钉钉
28
+
29
+ 群 → 智能群助手 → 添加机器人 → 自定义 → 安全设置勾选**加签** → 复制 Webhook 与密钥。
30
+ 钉钉的加签是强制的,插件会自动补 `timestamp` 与 `sign`。
31
+
32
+ ### 微信
33
+
34
+ 微信不开放第三方推送到个人号,合规路径是经服务号中转:
35
+
36
+ - **Server酱**(`sct.ftqq.com`):微信扫码登录领 SendKey
37
+ - **WxPusher**(`wxpusher.zjiecode.com`):注册拿 appToken
38
+
39
+ 个人身份无法自建服务号——微信公众平台官方规则里,服务号主体只能是
40
+ 政府 / 媒体 / 企业 / 其他组织,个人不提供该选项。所以插件默认走服务商通道。
41
+
42
+ ## 诚实边界
43
+
44
+ | 情况 | 表现 |
45
+ |---|---|
46
+ | 上游没给 usage | 显示「本轮未提供用量数据」,**不填 0** |
47
+ | webhook 失效(HTTP 200 + 业务错误码) | 判为失败,带服务端原文 |
48
+ | 200 但正文不是 JSON | 记为「已送出不可确认」,不冒充成功 |
49
+ | 网络异常 / 超时 | 记日志,**绝不抛出,绝不阻塞 agent** |
50
+
51
+ ## 配置示例
52
+
53
+ ```yaml
54
+ - insert:
55
+ - id: task-notify
56
+ name: '@morgan9668/dsh-task-notify'
57
+ config:
58
+ enabled: true
59
+ reasons: [completed, error, blocked]
60
+ channels:
61
+ wecom:
62
+ enabled: true
63
+ webhook: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...'
64
+ feishu:
65
+ enabled: true
66
+ webhook: 'https://open.feishu.cn/open-apis/bot/v2/hook/...'
67
+ secret: ''
68
+ dingtalk:
69
+ enabled: true
70
+ webhook: 'https://oapi.dingtalk.com/robot/send?access_token=...'
71
+ secret: 'SEC...'
72
+ wechat:
73
+ enabled: false
74
+ serverchanSendKey: ''
75
+ wxpusherAppToken: ''
76
+ ```