dsh-team-bots 0.2.393 → 0.2.455

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.
Files changed (64) hide show
  1. package/package.json +4 -1
  2. package/scripts/doctor.mjs +14 -3
  3. package/src/api.js +30 -3
  4. package/src/config.js +105 -0
  5. package/src/db-migrations.js +20 -0
  6. package/src/db.js +4 -0
  7. package/src/feishu/channel.js +702 -0
  8. package/src/feishu/commands.js +20 -0
  9. package/src/feishu/format.js +56 -0
  10. package/src/feishu/index.js +19 -0
  11. package/src/feishu/store.js +205 -0
  12. package/src/service.js +7 -0
  13. package/src/services/bots.js +42 -0
  14. package/src/services/chat.js +6 -4
  15. package/src/services/core.js +153 -8
  16. package/src/services/external-trigger-schema.js +61 -0
  17. package/src/services/feishu.js +181 -0
  18. package/src/services/github-source.js +157 -0
  19. package/src/services/memory.js +122 -34
  20. package/src/services/projects.js +2 -0
  21. package/src/services/reason-codes.js +63 -0
  22. package/src/services/review-watchdog.js +30 -8
  23. package/src/services/run-finish.js +33 -9
  24. package/src/services/runs.js +48 -7
  25. package/src/services/runtime/context-window.js +53 -0
  26. package/src/services/runtime/prompt.js +149 -134
  27. package/src/services/runtime/sandbox-policy.js +65 -0
  28. package/src/services/runtime/session-continuity.js +38 -0
  29. package/src/services/runtime/session.js +155 -5
  30. package/src/services/scheduler.js +9 -2
  31. package/src/services/system.js +50 -2
  32. package/src/services/task-dispatch.js +40 -4
  33. package/src/services/task-notify.js +13 -8
  34. package/src/services/task-review.js +27 -0
  35. package/src/services/wechat-trigger-schema.js +62 -0
  36. package/src/services/wechat.js +129 -19
  37. package/src/tools.js +11 -2
  38. package/src/wechat/channel.js +130 -26
  39. package/src/wechat/commands.js +13 -1
  40. package/src/wechat/store.js +69 -18
  41. package/ui/app.js +6 -2
  42. package/ui/i18n/en/chat.js +1 -0
  43. package/ui/i18n/en/nav.js +5 -0
  44. package/ui/i18n/en/settings.js +25 -5
  45. package/ui/i18n/en/tasks.js +4 -0
  46. package/ui/i18n/en/wechat.js +25 -3
  47. package/ui/i18n/zh/chat.js +1 -0
  48. package/ui/i18n/zh/nav.js +5 -0
  49. package/ui/i18n/zh/settings.js +25 -5
  50. package/ui/i18n/zh/tasks.js +4 -0
  51. package/ui/i18n/zh/wechat.js +25 -3
  52. package/ui/modules/api.js +23 -1
  53. package/ui/modules/cards.js +15 -0
  54. package/ui/modules/chat.js +43 -2
  55. package/ui/modules/dom-morph.js +14 -7
  56. package/ui/modules/events-board.js +73 -23
  57. package/ui/modules/events-click.js +11 -0
  58. package/ui/modules/global-pages.js +138 -10
  59. package/ui/modules/settings.js +51 -9
  60. package/ui/modules/state.js +2 -0
  61. package/ui/styles/chat-cards.css +28 -0
  62. package/ui/styles/frame.css +27 -3
  63. package/ui/styles/global-config.css +28 -3
  64. package/ui/styles/surfaces.css +2 -0
@@ -4,10 +4,12 @@
4
4
  // 因此方法体内的 this 与拆分前完全一致。
5
5
 
6
6
  import { createRequire } from 'node:module'
7
+ import { effectiveWechatEnabled } from '../config.js'
7
8
  import { AppError, conflict } from '../errors.js'
8
9
  import { WechatIlinkError } from '../wechat/commands.js'
9
- import { jsonParse } from '../util.js'
10
+ import { jsonParse, nowIso } from '../util.js'
10
11
  import { answerFailed, answerReceipt, approvalCard, questionCard, wechatToken } from '../wechat/format.js'
12
+ import { recordWechatTriggerRow } from './wechat-trigger-schema.js'
11
13
 
12
14
  // 微信登录二维码:服务端直接出 SVG,UI 注入即可,无需前端 QR 库(vendor/qrcode,MIT)。
13
15
  // 依赖按需加载:二维码库缺失只影响扫码,不应让整个插件加载失败。
@@ -48,6 +50,53 @@ function toChannelError(service, action, error) {
48
50
 
49
51
  export const wechatMethods = {
50
52
 
53
+ /** 微信通道生效开关(DSHBOTS-334):通道页 settings 显式值 > patch.yml/env 默认。 */
54
+ wechatChannelEnabled() {
55
+ return effectiveWechatEnabled(this.config, key => this.store.setting(key))
56
+ },
57
+
58
+ /**
59
+ * 通道页启停开关(DSHBOTS-334):settings 落 '1'/'0' + 审计 + 即时对齐挂载态。
60
+ * 停用即停推(this.wechat 置 null,channelNotify 不再扇出到微信);启用按既有
61
+ * 绑定凭据恢复连接(绑定持久在 wechat-channel.sqlite,stop 不清凭据)。
62
+ */
63
+ async setWechatChannelEnabled(enabled, actor = this.actor()) {
64
+ this.store.setSetting('wechat_channel_enabled', enabled ? '1' : '0')
65
+ this.audit(actor, 'settings.update', 'settings', 'wechat_channel', { enabled: Boolean(enabled) })
66
+ await this.applyWechatChannelEnabled()
67
+ return this.wechatStatus()
68
+ },
69
+
70
+ /** 按生效开关即时对齐通道挂载:关=断开卸载;开=挂载并按既有绑定连接。 */
71
+ async applyWechatChannelEnabled() {
72
+ if (!this.wechatChannelEnabled()) {
73
+ if (!this.wechat) return
74
+ const channel = this.wechat
75
+ this.wechat = null
76
+ try {
77
+ await channel.stop()
78
+ } catch (error ) {
79
+ this.logger.warn?.(`[wechat] 通道停用清理失败: ${error?.message ?? error}`)
80
+ }
81
+ return
82
+ }
83
+ if (this.wechat) return
84
+ const { WechatStore } = await import('../wechat/store.js')
85
+ const { WechatChannel } = await import('../wechat/channel.js')
86
+ this._wechatStore ??= await new WechatStore(this.config.wechatDbPath).open()
87
+ const channel = new WechatChannel({
88
+ store: this._wechatStore,
89
+ // 挂载决策已由生效开关做出,通道内 enabled() 门禁按挂载口径放行。
90
+ config: { ...this.config, wechat: { ...this.config.wechat, enabled: true } },
91
+ log: this.logger,
92
+ })
93
+ channel.setService(this)
94
+ this.wechat = channel
95
+ await channel.start().catch(error => {
96
+ this.logger.warn?.(`[wechat] 通道启动失败: ${error?.message ?? error}`)
97
+ })
98
+ },
99
+
51
100
  // 微信状态会进 UI state:凭据类字段一律剥掉,只留 phase/是否登录/管理员等展示信息。
52
101
  wechatStatus() {
53
102
  const status = this.wechat?.status()
@@ -180,31 +229,92 @@ export const wechatMethods = {
180
229
  },
181
230
 
182
231
  // ===== DSHBOTS-215:微信问答回路 =====
183
- // 群聊提问/审批转发微信:只推纯文本镜像,状态仍由工作台卡片与群消息承载;
232
+ // 群聊提问/审批转发外部通道:只推纯文本镜像,状态仍由工作台卡片与群消息承载;
184
233
  // 管理员在微信的答复经 commands 的「答/批 <token> …」路由回原条目(见 wechatAnswerQuestion /
185
234
  // wechatDecideApproval)。转发失败只告警,不阻塞提问主流程。
235
+ // DSHBOTS-326:转发面从「微信单通道」扩为「各已启用通道」(微信/飞书),单通道失败不阻断另一通道。
186
236
 
187
- /** 提问转发微信(只推文本;token 取问题 id 末 6 位)。 */
237
+ /** 提问转发各已启用通道(只推文本;token 取问题 id 末 6 位)。
238
+ * 幂等收据键(A3/DSHBOTS-323):question:<row.id>——同条目重复转发在各通道存留期内被吸收
239
+ * (各通道 outbox 库彼此独立,同键在两套库里各自幂等,互不干扰)。
240
+ * DSHBOTS-326:出站经 channelNotify 扇出到微信与飞书,单通道失败不阻断另一通道。 */
188
241
  wechatQuestion(project, row, items) {
189
- if (!this.wechat || typeof this.wechat.notify !== 'function') return false
190
- try {
191
- this.wechat.notify(questionCard(project.name || project.key, row.bot_name ?? 'Bot', items, wechatToken(row.id)))
192
- return true
193
- } catch (error ) {
194
- this.logger.warn?.('dsh-team: 微信提问转发失败: %s', error?.message ?? error)
195
- return false
196
- }
242
+ const results = this.channelNotify?.(
243
+ questionCard(project.name || project.key, row.bot_name ?? 'Bot', items, wechatToken(row.id)),
244
+ { receiptKey: `question:${row.id}` },
245
+ ) ?? []
246
+ return results.some(result => result.ok)
197
247
  },
198
248
 
199
- /** 审批转发微信(只推文本;token 取审批 id 末 6 位)。 */
249
+ /** 审批转发各已启用通道(只推文本;token 取审批 id 末 6 位)。
250
+ * 幂等收据键(A3/DSHBOTS-323):approval:<row.id>(各通道 outbox 库内各自幂等)。
251
+ * DSHBOTS-326:出站经 channelNotify 扇出,单通道失败只留痕不阻断另一通道。 */
200
252
  wechatApproval(project, row) {
201
- if (!this.wechat || typeof this.wechat.notify !== 'function') return false
202
- try {
203
- this.wechat.notify(approvalCard(project.name || project.key, row.bot_name ?? 'Bot', row.tool_name, row.reason, wechatToken(row.id)))
204
- return true
205
- } catch (error ) {
206
- this.logger.warn?.('dsh-team: 微信审批转发失败: %s', error?.message ?? error)
207
- return false
253
+ const results = this.channelNotify?.(
254
+ approvalCard(project.name || project.key, row.bot_name ?? 'Bot', row.tool_name, row.reason, wechatToken(row.id)),
255
+ { receiptKey: `approval:${row.id}` },
256
+ ) ?? []
257
+ return results.some(result => result.ok)
258
+ },
259
+
260
+ /**
261
+ * 外发收据视图(A3/DSHBOTS-323):近 N 条带键推送的终态流水,可追责/可回放。
262
+ * 真值唯一来源是通道出站库(wechat-channel.sqlite,随备份走):sent=sent_at 在、
263
+ * gone=gave_up_at 在(last_error 带废弃原因)、pending=两者皆无。
264
+ * 通道未启用返回 available:false——「为什么没收到」在该态由通道页与 needsAttention 解释,
265
+ * 不在插件库建第二张收据表(反双真值)。
266
+ */
267
+ notifyReceiptsView(limit = 50) {
268
+ if (!this.wechat || typeof this.wechat.receipts !== 'function') {
269
+ return { available: false, reason: 'wechat-disabled', items: [] }
270
+ }
271
+ const items = this.wechat.receipts(limit).map(row => ({
272
+ receiptKey: row.receipt_key,
273
+ state: row.sent_at ? 'sent' : row.gave_up_at ? 'gone' : 'pending',
274
+ attempts: Number(row.attempts ?? 0),
275
+ lastError: row.last_error ?? null,
276
+ createdAt: row.created_at,
277
+ sentAt: row.sent_at ?? null,
278
+ gaveUpAt: row.gave_up_at ?? null,
279
+ }))
280
+ return { available: true, reason: null, items }
281
+ },
282
+
283
+ /**
284
+ * 入站 Trigger 留痕(B4-①/DSHBOTS-328):通道每条入站事件的处置记录——handled/
285
+ * filtered/rejected + route + reason,回答「这条微信为什么没有触发」。稳定 id 去重
286
+ * (native 主键),滚动封顶在 wechat-trigger-schema。读入(Trigger)与写出(notify
287
+ * 收据)两侧各自留痕、互不混表。
288
+ */
289
+ recordWechatTrigger({ nativeId, peerId, text, disposition, route = null, reason = null }) {
290
+ if (!nativeId) return 'skipped'
291
+ return recordWechatTriggerRow(this.store, {
292
+ id: `wechat:${nativeId}`,
293
+ received_at: nowIso(),
294
+ peer_id: peerId,
295
+ disposition,
296
+ route,
297
+ reason,
298
+ preview: String(text ?? ''),
299
+ })
300
+ },
301
+
302
+ wechatTriggersView(limit = 50) {
303
+ const rows = this.store.all(
304
+ 'SELECT id, received_at, peer_id, disposition, route, reason, preview FROM wechat_inbound ORDER BY received_at DESC LIMIT ?',
305
+ Math.max(1, Math.min(200, Number(limit) || 50)),
306
+ )
307
+ return {
308
+ count: rows.length,
309
+ items: rows.map(row => ({
310
+ id: row.id,
311
+ receivedAt: row.received_at,
312
+ peerId: row.peer_id,
313
+ disposition: row.disposition,
314
+ route: row.route,
315
+ reason: row.reason,
316
+ preview: row.preview,
317
+ })),
208
318
  }
209
319
  },
210
320
 
package/src/tools.js CHANGED
@@ -1,3 +1,11 @@
1
+ // 信赖边界(B6/DSHBOTS-327,吸收原型「外部文本只是数据」显式化):
2
+ // 本文件注册的全部 team_* 工具的鉴权只认结构化事实——宿主会话身份(ownerContextFor/
3
+ // memberContextFor 按 session_bindings 解析)、bot 行与运行上下文(applyBotToolPolicy)、
4
+ // bot.file_policy 三档沙箱(applyFilePolicy)。消息正文、引用摘录、微信文本、记忆内容、
5
+ // 提案说明一律是数据:没有任何代码路径把它们解析成权限、角色、模型或写范围。
6
+ // 工具 description 与失败引导文案是工具面契约,不可被提示词或外部文本改写(proto 五级
7
+ // 优先级的最高层);写范围兜底解析只发生在派单链的卡面描述(task-dispatch.ts),描述
8
+ // 只能由派单方(owner 工具/UI/总监 bot)写入,外部消息进不来。
1
9
  const stringOutput = {
2
10
  schema: { type: 'string' },
3
11
  render: (_args, value) => [{ type: 'text', text: String(value ?? '') }],
@@ -80,7 +88,7 @@ export function installTeamTools(ctx, service) {
80
88
  priority: { type: 'string', enum: ['urgent', 'high', 'medium', 'low', 'none'], description: 'Task priority (new tasks and card amendment on re-dispatch)' },
81
89
  write_scopes: { type: 'array', items: { type: 'string' }, description: 'Workspace-relative paths this task will modify (new tasks only); the scheduler runs tasks with disjoint scopes in parallel. Omit to parse a `写范围:`/`write_scopes:` line from the description instead' },
82
90
  force_duplicate: { type: 'boolean', description: 'Escape hatch (new tasks only): skip the same-write-scope duplicate check when an unfinished task in this project already declares identical write scopes. Use only when a second task on the same paths is intentional; every use is audited as dispatch_force_duplicate' },
83
- time_budget_minutes: { type: 'integer', description: 'Required delivery time limit in minutes (new tasks only, 1-10080): injected into the task prompt, and the run is aborted when the budget expires. The effective timeout is the smaller of this budget and the global run timeout. Omit to take the default budget (env DSH_TEAM_TASK_TIME_BUDGET_MINUTES > stall-watchdog minutes > fallback 20 minutes)' },
91
+ time_budget_minutes: { type: 'integer', description: 'Required delivery time limit in minutes (new tasks only, 1-10080): injected into the task prompt, and the run is aborted when the budget expires. The effective timeout is the smaller of this budget and the global run timeout. Omit to take the priority-tier budget (urgent/high 45, medium 30, low/none 15 minutes); non-dispatch task creation falls back to env DSH_TEAM_TASK_TIME_BUDGET_MINUTES > stall-watchdog minutes > 20 minutes' },
84
92
  parent_task_id: { type: 'string', description: 'Nest the new task as a subtask under this main task id (new tasks only): pass it when the main item cannot be finished in this run or a new closing condition emerged, so follow-up work lands as a product-grade card instead of a verbal note; also pass it to split a large task into parallel subtask cards for speed (independent parts, disjoint write_scopes, so the cards run concurrently). Must reference an existing task in the same project; self-reference is rejected. The backend validates' },
85
93
  task: { type: 'string', description: 'Existing task to re-dispatch, as KEY-N (for example DEMO-3). Omit to create a new task' },
86
94
  sandbox: { type: 'string', enum: ['inherit', 'workspace-write', 'read-only'], default: 'inherit', description: 'Sandbox tier for this task\'s runs (new tasks and re-dispatch); default inherit = follow the assignee bot\'s configured file policy, so a development task is never tightened to read-only unless the card says so. inherit also clears any stored override on re-dispatch. workspace-write/read-only must not be wider than that configuration (tighten-only; every run of the task starts under the effective tier, recorded as a sandbox_mode run event). Use read-only to run a development task in review mode' },
@@ -301,13 +309,14 @@ export function installTeamTools(ctx, service) {
301
309
 
302
310
  ctx.tools.register({
303
311
  name: 'team_memory_cleanup',
304
- description: 'Batch-deprecate stale memories in one scope: matched entries are archived (terminal — excluded from recall), each keeps its memory_events trail, and the batch is audited as memory.cleanup with the cleaned entries listed. Two criteria, combinable: `task` archives a closed card\'s process records (its 任务 KEY-N / KEY-N 交付记录 topics; the task must already be done or canceled); `topics` archives the explicitly listed topics — use it for older wordings that conflict with a newer final decision. Do not archive entries recording the user\'s explicit decisions. Director-only.',
312
+ description: 'Batch-deprecate stale memories in one scope: matched entries are archived (terminal — excluded from recall), each keeps its memory_events trail, and the batch is audited as memory.cleanup with the cleaned entries listed. Criteria (at least one required): `task` archives a closed card\'s process records (its 任务 KEY-N / KEY-N 交付记录 topics; the task must already be done or canceled); `topics` archives the explicitly listed topics — use it for older wordings that conflict with a newer final decision; `before` archives every active entry whose updated_at is strictly older than the given ISO timestamp — the one-shot bulk criterion for legacy backlog convergence. `before` combines with `topics`/`task` as an AND filter. Do not archive entries recording the user\'s explicit decisions. Director-only.',
305
313
  parameters: {
306
314
  type: 'object',
307
315
  properties: {
308
316
  scope: { type: 'string', enum: ['bot', 'project', 'team'], description: 'Which memory scope to clean: bot = your own, project = this project, team = whole team' },
309
317
  topics: { type: 'array', items: { type: 'string' }, description: 'Exact topic labels to archive in this scope' },
310
318
  task: { type: 'string', description: 'Closed card (KEY-N) whose process-record memories should be archived; rejected unless the task is done or canceled' },
319
+ before: { type: 'string', description: 'ISO timestamp cutoff (e.g. 2026-01-01T00:00:00.000Z): archive every active entry in this scope with updated_at strictly before it. Required when neither topics nor task is given; combining with topics/task intersects the criteria' },
311
320
  },
312
321
  required: ['scope'],
313
322
  additionalProperties: false,
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto'
2
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
3
  import { createRequire } from 'node:module'
3
4
  import { TencentIlinkTransport } from '../../vendor/wechat-ilink/index.js'
4
5
  import { handleCommand, isRetryable, outboundChunks, WechatBusinessError, WechatIlinkError } from './commands.js'
@@ -26,6 +27,36 @@ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
26
27
  /** 授权响应里可能出现的用户标识字段(vendor 的 confirmed 返回 userId=ilink_user_id)。 */
27
28
  const AUTH_USER_ID_KEYS = ['userId', 'ilink_user_id', 'ilinkUserId', 'peerId', 'wxid', 'from_user_id', 'fromUserId']
28
29
 
30
+ /**
31
+ * iLink 拒发观测(诊断辅助)。vendor 是上游编译产物保持原样(NOTICE 口径),
32
+ * 上游把所有 ret!=0 坍缩成同一句 "iLink rejected ...",凭证失效/频控/内容审核无法区分——
33
+ * ret 透出在本仓桥接层完成:makeTransport 注入的 fetch 被包装,克隆 sendmessage 的
34
+ * 2xx JSON 响应,ret!=0 时把 {ret, errmsg} 记进当前 sendTo 的 ALS 上下文;vendor 随后
35
+ * 抛出的 WechatIlinkError 经 attachRejectDetail 拼上 `(ret=N errmsg=...)`,outbox 的
36
+ * last_error 与 warn 日志即可对症。上下文随每次 sendTo 新建,无跨调用残留。
37
+ */
38
+ const ilinkRejectSlot = new AsyncLocalStorage ()
39
+
40
+ /** 只观测出站消息端点:其余端点(getupdates/getconfig/扫码授权)不在诊断范围。 */
41
+ function observeIlinkReject(baseFetch ) {
42
+ return async (url, init) => {
43
+ const response = await baseFetch(url, init)
44
+ const slot = ilinkRejectSlot.getStore()
45
+ if (slot && response.ok && new URL(String(url)).pathname.endsWith('/sendmessage')) {
46
+ try {
47
+ const reply = await response.clone().json()
48
+ if (typeof reply?.ret === 'number' && reply.ret !== 0) {
49
+ slot.ret = reply.ret
50
+ const errmsg = typeof reply.errmsg === 'string' && reply.errmsg.trim() ? reply.errmsg.trim()
51
+ : typeof reply.err_msg === 'string' && reply.err_msg.trim() ? reply.err_msg.trim() : null
52
+ if (errmsg) slot.errmsg = errmsg
53
+ }
54
+ } catch { /* 观测失败不影响原错误路径:vendor 抛什么仍是什么 */ }
55
+ }
56
+ return response
57
+ }
58
+ }
59
+
29
60
  /**
30
61
  * 个人微信(腾讯 iLink 官方协议)通道宿主:
31
62
  * 凭证持久化、扫码授权、长轮询生命周期、管理员指令路由、事件推送。
@@ -214,14 +245,17 @@ export class WechatChannel {
214
245
  this.phase = 'unbound'
215
246
  }
216
247
 
217
- makeTransport(credentials, extra = {}) {
248
+ makeTransport(credentials, extra = {}) {
249
+ // fetch 一律过拒发观测层:extra 传入的测试桩也不例外(...extra 展开会覆盖包装版,
250
+ // 故先解构取出,在实参处统一包装)。
251
+ const { fetch: extraFetch, ...rest } = extra
218
252
  return new TencentIlinkTransport({
219
253
  baseUrl: credentials?.baseUrl ?? 'https://ilinkai.weixin.qq.com',
220
254
  token: credentials?.token,
221
255
  botAgent: `DSHTeamBots/${PLUGIN_VERSION}`,
222
256
  clientVersion: PLUGIN_VERSION,
223
- fetch,
224
- ...extra,
257
+ fetch: observeIlinkReject(extraFetch ?? fetch),
258
+ ...rest,
225
259
  })
226
260
  }
227
261
 
@@ -292,9 +326,16 @@ export class WechatChannel {
292
326
  async handleBatch(messages, transport, signal) {
293
327
  let ok = true
294
328
  for (const message of messages) {
295
- if (!message.text) continue
329
+ if (!message.text) {
330
+ // Trigger 留痕(B4-①/DSHBOTS-328):无正文事件(图片/系统条目)也进观测面。
331
+ this.recordTrigger(message, 'filtered', 'no-text')
332
+ continue
333
+ }
296
334
  const key = message.messageId
297
- if (key && this.processedMessages.has(key)) continue
335
+ if (key && this.processedMessages.has(key)) {
336
+ this.recordTrigger(message, 'duplicate', 'processed-in-memory')
337
+ continue
338
+ }
298
339
  try {
299
340
  await this.onInbound(message, transport, signal)
300
341
  if (key) this.rememberProcessed(key)
@@ -306,6 +347,26 @@ export class WechatChannel {
306
347
  return ok
307
348
  }
308
349
 
350
+ /**
351
+ * 入站 Trigger 留痕(B4-①/DSHBOTS-328):每条入站事件的处置(handled/filtered/rejected/
352
+ * duplicate + route + reason)经 service.recordWechatTrigger 落插件库,稳定 id = wechat:<nativeId>。
353
+ * 只观测不改变路由语义;service 不在场(测试桩)时静默跳过。
354
+ */
355
+ recordTrigger(message, disposition, route, reason = null) {
356
+ try {
357
+ this.service?.recordWechatTrigger?.({
358
+ nativeId: message?.messageId ?? null,
359
+ peerId: message?.senderId ?? null,
360
+ text: message?.text ?? '',
361
+ disposition,
362
+ route,
363
+ reason,
364
+ })
365
+ } catch (error) {
366
+ this.log.warn?.(`[wechat] 触发留痕失败: ${this.errorText(error)}`)
367
+ }
368
+ }
369
+
309
370
  rememberProcessed(key) {
310
371
  this.processedMessages.add(key)
311
372
  if (this.processedMessages.size > PROCESSED_MEMORY_LIMIT) {
@@ -329,32 +390,40 @@ export class WechatChannel {
329
390
  this.store.saveAdminPeer(peerId)
330
391
  this.pendingAdmin = null
331
392
  this.log.info?.(`[wechat] 管理员已绑定(本次授权会话首条消息): ${peerId}`)
393
+ this.recordTrigger(message, 'handled', 'welcome')
332
394
  await this.sendTo(peerId, welcomeAdmin(), signal)
333
395
  await this.flushOutbox(transport, signal)
334
396
  return
335
397
  }
336
398
  if (peerId !== admin) {
337
399
  this.log.info?.(`[wechat] 忽略非管理员消息来自 ${peerId}`)
400
+ this.recordTrigger(message, 'filtered', 'non-admin', '发送者不是已绑定管理员')
338
401
  return
339
402
  }
403
+ // DSHBOTS-208 直达对话上下文:管理员会话绑定的项目 key(路由成功后由命令层回写)。
404
+ // ctx.trigger 由命令层回填分类(B4-①),成功/失败路径据此留痕;声明在 try 外供 catch 读取。
405
+ const ctx = {
406
+ boundKey: this.store.getDirectProjectKey?.() ?? null,
407
+ bind: key => this.store.saveDirectProjectKey?.(key),
408
+ // 上方已校验 peerId === admin(非管理员消息整条忽略),显式带过 fail-closed 命令门
409
+ isAdmin: true,
410
+ }
340
411
  try {
341
- // DSHBOTS-208 直达对话上下文:管理员会话绑定的项目 key(路由成功后由命令层回写)。
342
- const reply = await handleCommand(this.service, message.text, {
343
- boundKey: this.store.getDirectProjectKey?.() ?? null,
344
- bind: key => this.store.saveDirectProjectKey?.(key),
345
- // 上方已校验 peerId === admin(非管理员消息整条忽略),显式带过 fail-closed 命令门
346
- isAdmin: true,
347
- })
412
+ const reply = await handleCommand(this.service, message.text, ctx)
413
+ const trigger = ctx.trigger ?? { kind: 'chat', verb: null }
414
+ this.recordTrigger(message, 'handled', `${trigger.kind}${trigger.verb ? `:${trigger.verb}` : ''}`)
348
415
  await this.sendTo(peerId, reply, signal)
349
416
  } catch (error) {
350
417
  if (isBusinessError(error)) {
351
418
  // 业务性拒绝(如任务不存在、任务号非法):给用户可读提示即可,不算处理失败
352
419
  this.log.warn?.(`[wechat] 指令被拒绝: ${this.errorText(error)}`)
420
+ this.recordTrigger(message, 'rejected', 'command', this.errorText(error))
353
421
  await this.sendTo(peerId, String((error )?.message ?? '指令无法执行'), signal)
354
422
  .catch(sendError => this.log.warn?.(`[wechat] 提示发送失败: ${this.errorText(sendError)}`))
355
423
  return
356
424
  }
357
425
  this.log.warn?.(`[wechat] 指令执行失败: ${this.errorText(error)}`)
426
+ this.recordTrigger(message, 'failed', `command${ctx?.trigger?.verb ? `:${ctx.trigger.verb}` : ''}`, this.errorText(error))
358
427
  await this.sendTo(peerId, failureText(), signal)
359
428
  .catch(sendError => this.log.warn?.(`[wechat] 失败提示发送失败: ${this.errorText(sendError)}`))
360
429
  // 交给上层:这条没处理成功,cursor 不推进,下一轮还会重试
@@ -388,18 +457,37 @@ export class WechatChannel {
388
457
  if (!peer?.contextToken) throw new Error('尚无该联系人的会话凭证,等待对方发来消息')
389
458
  const body = String(text ?? '').trim()
390
459
  if (!body) return
391
- for (const chunk of outboundChunks(body)) {
392
- await this.transport.sendMessage({
393
- peerId,
394
- text: chunk,
395
- contextToken: peer.contextToken,
396
- clientId: randomUUID(),
397
- }, signal)
398
- }
460
+ // 拒发观测上下文:桥接 fetch 记录 ret!=0,vendor 抛错后由 attachRejectDetail 拼进文案
461
+ await ilinkRejectSlot.run({}, async () => {
462
+ try {
463
+ for (const chunk of outboundChunks(body)) {
464
+ await this.transport.sendMessage({
465
+ peerId,
466
+ text: chunk,
467
+ contextToken: peer.contextToken,
468
+ clientId: randomUUID(),
469
+ }, signal)
470
+ }
471
+ } catch (error) {
472
+ throw this.attachRejectDetail(error)
473
+ }
474
+ })
399
475
  }
400
476
 
401
- /** 对外事件推送入口:入队后经合批窗口合并发送;未连接时仅落盘,链接建立后由新事件触发。 */
402
- notify(text) {
477
+ /** vendor 抛错后把桥接层观测到的上游拒发码拼进文案(只处理带观测的 WechatIlinkError)。 */
478
+ attachRejectDetail(error) {
479
+ const observed = ilinkRejectSlot.getStore()
480
+ if (!observed || observed.ret === undefined || !(error instanceof WechatIlinkError)) return error
481
+ const suffix = ` (ret=${observed.ret}${observed.errmsg ? ` errmsg=${observed.errmsg}` : ''})`
482
+ return new WechatIlinkError(error.code, `${error.message}${suffix}`, error.retryable, { cause: error })
483
+ }
484
+
485
+ /**
486
+ * 对外事件推送入口:入队后经合批窗口合并发送;未连接时仅落盘,链接建立后由新事件触发。
487
+ * A3/DSHBOTS-323:可带 receiptKey 幂等收据键——同键在存留期内重复推送被吸收(duplicate),
488
+ * 调用方无需自建防重;不带键的旧形态行为不变。
489
+ */
490
+ notify(text, { receiptKey = null } = {}) {
403
491
  if (!this.enabled()) return
404
492
  const body = String(text ?? '').trim()
405
493
  if (!body) {
@@ -407,7 +495,11 @@ export class WechatChannel {
407
495
  return
408
496
  }
409
497
  try {
410
- this.store.enqueue(body)
498
+ const outcome = this.store.enqueue(body, receiptKey)
499
+ if (outcome === 'duplicate') {
500
+ this.log.warn?.(`[wechat] 重复推送已按收据键吸收(${receiptKey})`)
501
+ return
502
+ }
411
503
  } catch (error) {
412
504
  this.log.warn?.(`[wechat] 推送入队失败: ${this.errorText(error)}`)
413
505
  return
@@ -415,6 +507,16 @@ export class WechatChannel {
415
507
  if (this.phase === 'connected' && this.transport) this.scheduleOutboxFlush()
416
508
  }
417
509
 
510
+ /** 按 receipt_key 查收据终态(A3/DSHBOTS-323):sent/gone/pending,供插件运维视图同源读取。 */
511
+ receiptStates(keys) {
512
+ return this.store?.receiptStates?.(keys) ?? []
513
+ }
514
+
515
+ /** 近期带键收据流水(A3/DSHBOTS-323)。 */
516
+ receipts(limit = 50) {
517
+ return this.store?.receipts?.(limit) ?? []
518
+ }
519
+
418
520
  /** 合批窗口:窗口内的多次推送合并到同一次 flush,一轮并发任务事件只占一次消息额度。 */
419
521
  scheduleOutboxFlush() {
420
522
  if (this.flushTimer) return
@@ -462,12 +564,14 @@ export class WechatChannel {
462
564
  }
463
565
  }
464
566
 
465
- /** 失败记账:可重试错误计一次尝试,达到上限废弃;不可重试错误直接废弃。废弃后永不补发。 */
567
+ /** 失败记账:可重试错误计一次尝试,达到上限废弃;不可重试错误直接废弃。废弃后永不补发。
568
+ * 失败原因落 last_error(A3/DSHBOTS-323:sent/gone 终态可解释「为什么没收到」。 */
466
569
  recordOutboxFailure(item, error) {
467
570
  const retryable = isRetryable(error)
468
- const attempts = retryable ? this.store.markAttempt(item.id) : null
571
+ const reason = this.errorText(error)
572
+ const attempts = retryable ? this.store.markAttempt(item.id, reason) : null
469
573
  if (!retryable || (attempts ?? 0) >= OUTBOX_MAX_ATTEMPTS) {
470
- this.store.giveUp([item.id])
574
+ this.store.giveUp([item.id], reason)
471
575
  this.log.warn?.(
472
576
  `[wechat] 推送废弃(不再补发) id=${item.id}${retryable ? `(尝试 ${attempts}/${OUTBOX_MAX_ATTEMPTS} 次超限)` : '(不可重试)'}: ${this.errorText(error)}`,
473
577
  )
@@ -6,6 +6,9 @@ import {
6
6
  taskDetail, trHelp, unknownCommand,
7
7
  } from './format.js'
8
8
 
9
+ // 信赖边界(B6/DSHBOTS-327):微信文本只是数据——本文件只解析下方显式白名单指令
10
+ // (批/答/tr/bots/状态等固定模式),未命中指令的文本一律按群消息路由为数据;
11
+ // 写操作指令(reject/tr 与 答/批)必须过 admin-peer 门。自然语言不被解释成命令。
9
12
  /** 微信答复路由:答 <token> <选项或文字>(DSHBOTS-215)。token 为提问/审批 id 末 6 位。 */
10
13
  const ANSWER_PATTERN = /^(?:答|答复|回答|answer)\s+([A-Za-z0-9]{4,10})(?:\s+([\s\S]*))?$/i
11
14
 
@@ -53,7 +56,11 @@ function directorReceipt(bot) {
53
56
  */
54
57
  export async function handleCommand(service, rawText, ctx = null) {
55
58
  const body = String(rawText ?? '').trim()
56
- if (!body) return helpText()
59
+ if (!body) {
60
+ // Trigger 分类回填(B4-①/DSHBOTS-328):ctx.trigger 由通道侧读取留痕,不改变返回契约。
61
+ if (ctx) ctx.trigger = { kind: 'chat', verb: null }
62
+ return helpText()
63
+ }
57
64
 
58
65
  // DSHBOTS-249 固定指令:/ 前缀一律不进对话链路,未知 /xxx 回简短帮助提示。
59
66
  if (body.startsWith('/')) return handleFixedCommand(service, body, ctx)
@@ -63,11 +70,13 @@ export async function handleCommand(service, rawText, ctx = null) {
63
70
  const approval = APPROVAL_PATTERN.exec(body)
64
71
  if (approval && typeof (service ).wechatDecideApproval === 'function') {
65
72
  const decision = ['允许', 'allow'].includes(approval[2].toLowerCase()) ? 'allow' : 'reject'
73
+ if (ctx) ctx.trigger = { kind: 'approval', verb: decision === 'allow' ? 'approve' : 'reject', token: approval[1].toLowerCase() }
66
74
  return (service ).wechatDecideApproval(approval[1].toLowerCase(), decision, ctx?.boundKey ?? null)
67
75
  }
68
76
  const answer = ANSWER_PATTERN.exec(body)
69
77
  if (answer && typeof (service ).wechatAnswerQuestion === 'function') {
70
78
  const text = String(answer[2] ?? '').trim()
79
+ if (ctx) ctx.trigger = { kind: 'answer', verb: text ? 'answer' : 'help', token: answer[1].toLowerCase() }
71
80
  if (!text) return answerHelp()
72
81
  return (service ).wechatAnswerQuestion(answer[1].toLowerCase(), text, ctx?.boundKey ?? null)
73
82
  }
@@ -77,6 +86,7 @@ export async function handleCommand(service, rawText, ctx = null) {
77
86
 
78
87
  // DSHBOTS-208/258 任意交互:自由文本永远直达项目外 director 专属工作区(不随
79
88
  // direct_project_key 绑定或 active 项目数变化),首触回执、之后静默直达。
89
+ if (ctx) ctx.trigger = { kind: 'chat', verb: 'chat' }
80
90
  const chat = await service.wechatChat(null, body)
81
91
  // 项目外 director 通道:首触回执说明去向,之后静默直达(回复由运行回程推送),
82
92
  // 不回写项目绑定(通道是项目外的)。
@@ -106,6 +116,8 @@ async function handleFixedCommand(service, body, ctx) {
106
116
  if (!slash) return unknownCommand()
107
117
  const verb = slash[1].toLowerCase()
108
118
  const rest = String(slash[2] ?? '').trim()
119
+ // Trigger 分类回填(B4-①/DSHBOTS-328):固定指令带 verb,写操作门仍由 ADMIN_VERBS 把守。
120
+ if (ctx) ctx.trigger = { kind: 'fixed', verb }
109
121
 
110
122
  // 写操作权限门(fail-closed):未显式 isAdmin=true 一律拒绝(只读指令不设门)。
111
123
  if (ADMIN_VERBS.has(verb) && ctx?.isAdmin !== true) return adminDenied()