@ai-setting/roy-agent-core 1.7.61 → 1.7.62

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 (119) hide show
  1. package/dist/config/index.js +8 -8
  2. package/dist/env/agent/agent-component.js +41 -0
  3. package/dist/env/agent/index.js +18 -16
  4. package/dist/env/commands/index.js +8 -8
  5. package/dist/env/context/index.js +4 -4
  6. package/dist/env/debug/index.js +8 -8
  7. package/dist/env/error-reply.js +18 -0
  8. package/dist/env/event-source/cli-command-handler.js +17 -0
  9. package/dist/env/event-source/event-source-handlers.js +58 -0
  10. package/dist/env/event-source/event-store.js +18 -0
  11. package/dist/env/event-source/idempotency-key.js +20 -0
  12. package/dist/env/event-source/index.js +30 -25
  13. package/dist/env/hook/index.js +6 -6
  14. package/dist/env/index.js +52 -46
  15. package/dist/env/lark-mention-utils.js +9 -0
  16. package/dist/env/llm/index.js +9 -9
  17. package/dist/env/log-trace/index.js +8 -8
  18. package/dist/env/log-trace/logger.js +39 -0
  19. package/dist/env/mcp/index.js +9 -9
  20. package/dist/env/mcp/tool/index.js +2 -2
  21. package/dist/env/memory/index.js +9 -9
  22. package/dist/env/memory/plugin/index.js +2 -2
  23. package/dist/env/plugin/index.js +9 -9
  24. package/dist/env/prompt/index.js +8 -8
  25. package/dist/env/session/index.js +11 -11
  26. package/dist/env/session/storage/index.js +5 -5
  27. package/dist/env/skill/index.js +8 -8
  28. package/dist/env/task/delegate/delegate-tool.js +42 -0
  29. package/dist/env/task/delegate/index.js +13 -11
  30. package/dist/env/task/index.js +16 -15
  31. package/dist/env/task/mcp/index.js +4 -4
  32. package/dist/env/task/plugins/index.js +11 -11
  33. package/dist/env/task/plugins/lark-card-patch-notifier.js +42 -0
  34. package/dist/env/task/storage/index.js +4 -4
  35. package/dist/env/task/tools/index.js +4 -4
  36. package/dist/env/tool/built-in/index.js +4 -4
  37. package/dist/env/tool/index.js +12 -11
  38. package/dist/env/tool/types.js +1 -0
  39. package/dist/env/workflow/engine/index.js +13 -13
  40. package/dist/env/workflow/hooks/index.js +8 -8
  41. package/dist/env/workflow/index.js +23 -23
  42. package/dist/env/workflow/nodes/index.js +3 -3
  43. package/dist/env/workflow/plugins/index.js +9 -9
  44. package/dist/env/workflow/service/index.js +3 -3
  45. package/dist/env/workflow/storage/index.js +4 -4
  46. package/dist/env/workflow/tools/index.js +15 -15
  47. package/dist/env/workflow/utils/index.js +5 -5
  48. package/dist/index.js +70 -62
  49. package/dist/shared/@ai-setting/{roy-agent-core-dythsgkn.js → roy-agent-core-06jakebr.js} +2 -2
  50. package/dist/shared/@ai-setting/{roy-agent-core-jsn21cb9.js → roy-agent-core-084zthqx.js} +1 -1
  51. package/dist/shared/@ai-setting/{roy-agent-core-x1m0gs0q.js → roy-agent-core-2hkyp51n.js} +1 -1
  52. package/dist/shared/@ai-setting/{roy-agent-core-q212q0w1.js → roy-agent-core-2pma868e.js} +4 -4
  53. package/dist/shared/@ai-setting/{roy-agent-core-vmfk4m1v.js → roy-agent-core-2veqhrxa.js} +3 -3
  54. package/dist/shared/@ai-setting/{roy-agent-core-mw0bc9g6.js → roy-agent-core-32ck9rqt.js} +2 -2
  55. package/dist/shared/@ai-setting/{roy-agent-core-bdzdw1g3.js → roy-agent-core-33hn1beg.js} +1 -1
  56. package/dist/shared/@ai-setting/{roy-agent-core-2qkrpc7m.js → roy-agent-core-386wa4wy.js} +1 -1
  57. package/dist/shared/@ai-setting/{roy-agent-core-rnzm0tpf.js → roy-agent-core-48h4zh60.js} +4 -4
  58. package/dist/shared/@ai-setting/{roy-agent-core-yr5eqyhz.js → roy-agent-core-5bj0xfjk.js} +13 -27
  59. package/dist/shared/@ai-setting/{roy-agent-core-khc23qs1.js → roy-agent-core-5mrynf9g.js} +1 -1
  60. package/dist/shared/@ai-setting/{roy-agent-core-y0k9kaxz.js → roy-agent-core-6awgfh3x.js} +1 -1
  61. package/dist/shared/@ai-setting/{roy-agent-core-ygfjgk9b.js → roy-agent-core-6wxww10t.js} +2 -2
  62. package/dist/shared/@ai-setting/{roy-agent-core-xc0es9zc.js → roy-agent-core-79gyka2q.js} +2 -2
  63. package/dist/shared/@ai-setting/{roy-agent-core-expvav8a.js → roy-agent-core-7tce05jt.js} +1 -1
  64. package/dist/shared/@ai-setting/roy-agent-core-9nvyffxg.js +414 -0
  65. package/dist/shared/@ai-setting/{roy-agent-core-m2tv4pj0.js → roy-agent-core-9qgrc9dy.js} +158 -158
  66. package/dist/shared/@ai-setting/{roy-agent-core-z51jktet.js → roy-agent-core-a08dpf71.js} +17 -2
  67. package/dist/shared/@ai-setting/{roy-agent-core-22r4zmkw.js → roy-agent-core-a6cz4d23.js} +3 -3
  68. package/dist/shared/@ai-setting/{roy-agent-core-0f989bnp.js → roy-agent-core-anb53t3v.js} +3 -3
  69. package/dist/shared/@ai-setting/{roy-agent-core-ymcvsdzn.js → roy-agent-core-as0dd70m.js} +2 -2
  70. package/dist/shared/@ai-setting/{roy-agent-core-nd5171pv.js → roy-agent-core-bpvz1dqr.js} +8 -8
  71. package/dist/shared/@ai-setting/{roy-agent-core-aa514zm8.js → roy-agent-core-c4t4y18j.js} +5 -5
  72. package/dist/shared/@ai-setting/{roy-agent-core-sf9tsj0g.js → roy-agent-core-c57278kx.js} +1 -1
  73. package/dist/shared/@ai-setting/{roy-agent-core-e6k448ka.js → roy-agent-core-c8xvy6hj.js} +4 -4
  74. package/dist/shared/@ai-setting/{roy-agent-core-gtb4fj8j.js → roy-agent-core-cqpd41gf.js} +12 -10
  75. package/dist/shared/@ai-setting/{roy-agent-core-qgapy83x.js → roy-agent-core-cxpgd415.js} +6 -6
  76. package/dist/shared/@ai-setting/{roy-agent-core-g44nbgtt.js → roy-agent-core-dfqhc9ey.js} +2 -2
  77. package/dist/shared/@ai-setting/{roy-agent-core-cndvj1hv.js → roy-agent-core-fqandv0a.js} +9 -107
  78. package/dist/shared/@ai-setting/{roy-agent-core-4m5spt7m.js → roy-agent-core-fr296a53.js} +5 -5
  79. package/dist/shared/@ai-setting/{roy-agent-core-3p59ap0x.js → roy-agent-core-gc6wcd7z.js} +1 -1
  80. package/dist/shared/@ai-setting/{roy-agent-core-s7w47mnn.js → roy-agent-core-gjsvehfs.js} +1 -1
  81. package/dist/shared/@ai-setting/{roy-agent-core-9s3payp1.js → roy-agent-core-gtdtzbs7.js} +2 -2
  82. package/dist/shared/@ai-setting/{roy-agent-core-jrksyqb6.js → roy-agent-core-gz2jnaan.js} +7 -7
  83. package/dist/shared/@ai-setting/{roy-agent-core-6cyjps72.js → roy-agent-core-h3fwjbhp.js} +14 -14
  84. package/dist/shared/@ai-setting/{roy-agent-core-mhppywse.js → roy-agent-core-hczj1ryh.js} +4 -4
  85. package/dist/shared/@ai-setting/{roy-agent-core-qrjs2500.js → roy-agent-core-hfyxv2kx.js} +2 -2
  86. package/dist/shared/@ai-setting/{roy-agent-core-dg286rpd.js → roy-agent-core-hwkc0bg2.js} +1 -1
  87. package/dist/shared/@ai-setting/{roy-agent-core-bc3v8pw4.js → roy-agent-core-ja4sr63d.js} +6 -6
  88. package/dist/shared/@ai-setting/roy-agent-core-jagkferh.js +16 -0
  89. package/dist/shared/@ai-setting/roy-agent-core-jm136jzh.js +99 -0
  90. package/dist/shared/@ai-setting/{roy-agent-core-g5sw19fa.js → roy-agent-core-jw63js86.js} +1 -1
  91. package/dist/shared/@ai-setting/{roy-agent-core-8fy467qs.js → roy-agent-core-kmvw6b4v.js} +1 -1
  92. package/dist/shared/@ai-setting/{roy-agent-core-3bpntd80.js → roy-agent-core-kvq4a4p6.js} +2 -2
  93. package/dist/shared/@ai-setting/{roy-agent-core-yd85623y.js → roy-agent-core-m3w3ytxt.js} +2 -2
  94. package/dist/shared/@ai-setting/{roy-agent-core-64f22h1g.js → roy-agent-core-m880qz3y.js} +7 -1
  95. package/dist/shared/@ai-setting/{roy-agent-core-5knpegzr.js → roy-agent-core-mbwaxqs0.js} +3 -3
  96. package/dist/shared/@ai-setting/{roy-agent-core-tn96n4wz.js → roy-agent-core-mkpsz128.js} +4 -4
  97. package/dist/shared/@ai-setting/{roy-agent-core-9k8ms63r.js → roy-agent-core-mrrv80jy.js} +1 -1
  98. package/dist/shared/@ai-setting/{roy-agent-core-ytnedzks.js → roy-agent-core-nmn853z0.js} +333 -1332
  99. package/dist/shared/@ai-setting/roy-agent-core-p37kh0kt.js +155 -0
  100. package/dist/shared/@ai-setting/{roy-agent-core-60p2380d.js → roy-agent-core-p6a4v4fq.js} +1 -1
  101. package/dist/shared/@ai-setting/{roy-agent-core-hf0t8agb.js → roy-agent-core-p8rf4z89.js} +1 -1
  102. package/dist/shared/@ai-setting/roy-agent-core-pnj0zh25.js +0 -0
  103. package/dist/shared/@ai-setting/{roy-agent-core-dp1hp24k.js → roy-agent-core-prnry2mw.js} +3 -3
  104. package/dist/shared/@ai-setting/{roy-agent-core-qw5fpa24.js → roy-agent-core-qmqe8ds3.js} +3 -3
  105. package/dist/shared/@ai-setting/{roy-agent-core-j0x9yf96.js → roy-agent-core-sj4y3wdm.js} +3 -3
  106. package/dist/shared/@ai-setting/{roy-agent-core-xeqp659x.js → roy-agent-core-th92f833.js} +2 -2
  107. package/dist/shared/@ai-setting/{roy-agent-core-ajmgyawx.js → roy-agent-core-v7mwj8eq.js} +2 -2
  108. package/dist/shared/@ai-setting/{roy-agent-core-5565cvw8.js → roy-agent-core-vvb4cyyy.js} +5 -5
  109. package/dist/shared/@ai-setting/{roy-agent-core-qpqqx1wd.js → roy-agent-core-vwzan9v0.js} +2 -2
  110. package/dist/shared/@ai-setting/{roy-agent-core-pj5tfmn5.js → roy-agent-core-w2ev3z5q.js} +12 -14
  111. package/dist/shared/@ai-setting/roy-agent-core-w2h6xt6k.js +473 -0
  112. package/dist/shared/@ai-setting/{roy-agent-core-kfmrfaft.js → roy-agent-core-wzp4tbsn.js} +1 -1
  113. package/dist/shared/@ai-setting/{roy-agent-core-jsdqzfbj.js → roy-agent-core-x1d6edkh.js} +1 -1
  114. package/dist/shared/@ai-setting/{roy-agent-core-n1ck0x1r.js → roy-agent-core-ye4bfzqg.js} +11 -11
  115. package/dist/shared/@ai-setting/{roy-agent-core-p2dpcyrz.js → roy-agent-core-zjgckbdd.js} +2 -2
  116. package/dist/shared/@ai-setting/{roy-agent-core-a5nh5q6v.js → roy-agent-core-zy8vkbnk.js} +1 -1
  117. package/dist/test-utils/child-process-mock.js +23 -0
  118. package/dist/utils/temp-file-manager/index.js +2 -2
  119. package/package.json +61 -1
@@ -0,0 +1,414 @@
1
+ import {
2
+ normalizeLarkAtMentions
3
+ } from "./roy-agent-core-m880qz3y.js";
4
+ import {
5
+ createLogger,
6
+ init_logger
7
+ } from "./roy-agent-core-6awgfh3x.js";
8
+
9
+ // src/env/error-reply.ts
10
+ init_logger();
11
+ import { spawn } from "node:child_process";
12
+ var logger = createLogger("env:error-reply");
13
+ var UPSTREAM_RETRY_PATTERNS = [
14
+ /failed after \d+ attempts/i,
15
+ /endpoint is unavailable/i,
16
+ /upstream request failed/i,
17
+ /rate.?limit/i,
18
+ /\b429\b/,
19
+ /\b50[0234]\b/,
20
+ /service (is )?(temporarily )?unavailable/i,
21
+ /\beconn(reset|refused|aborted)\b/i,
22
+ /socket hang up/i,
23
+ /fetch failed/i,
24
+ /network error/i,
25
+ /overloaded/i
26
+ ];
27
+ var TIMEOUT_PATTERNS = [
28
+ /timeout/i,
29
+ /timed out/i,
30
+ /deadline exceeded/i,
31
+ /etimedout/i,
32
+ /aborted due to timeout/i
33
+ ];
34
+ var TRANSPORT_ABORT_PATTERNS = [
35
+ /requestabortederror/i,
36
+ /econnaborted/i,
37
+ /connection (was )?(aborted|reset|closed)/i,
38
+ /premature close/i
39
+ ];
40
+ var ABORT_PATTERNS = [
41
+ /\babort(?:ed|ing)?\b/i,
42
+ /operation was cancelled/i,
43
+ /operation was canceled/i,
44
+ /sigint/i,
45
+ /\binterrupted\b/i,
46
+ /exiting due to (signal|shutdown)/i
47
+ ];
48
+ var CONTEXT_PATTERNS = [
49
+ /context threshold/i,
50
+ /context (window|length|limit)/i,
51
+ /token limit/i,
52
+ /maximum context/i,
53
+ /ctrieve\b/,
54
+ /CTX_001/
55
+ ];
56
+ var ASK_USER_PATTERNS = [/__ASK_USER_ERROR__/];
57
+ function collectErrorText(error, depth = 0) {
58
+ const parts = [];
59
+ const push = (v) => {
60
+ if (typeof v === "string" && v.length > 0)
61
+ parts.push(v);
62
+ };
63
+ if (error === null || error === undefined)
64
+ return "";
65
+ if (typeof error === "string") {
66
+ push(error);
67
+ return parts.join(`
68
+ `);
69
+ }
70
+ if (typeof error !== "object") {
71
+ push(String(error));
72
+ return parts.join(`
73
+ `);
74
+ }
75
+ const e = error;
76
+ push(e.name);
77
+ push(e.message);
78
+ for (const key of ["statusCode", "status", "code"]) {
79
+ const v = e[key];
80
+ if (typeof v === "number" || typeof v === "string")
81
+ push(String(v));
82
+ }
83
+ if (depth < 3) {
84
+ const nested = collectErrorText(e.lastError, depth + 1);
85
+ if (nested)
86
+ parts.push(nested);
87
+ if (Array.isArray(e.errors)) {
88
+ for (const inner of e.errors.slice(-3)) {
89
+ const s = collectErrorText(inner, depth + 1);
90
+ if (s)
91
+ parts.push(s);
92
+ }
93
+ }
94
+ const cause = collectErrorText(e.cause, depth + 1);
95
+ if (cause)
96
+ parts.push(cause);
97
+ }
98
+ return parts.join(`
99
+ `);
100
+ }
101
+ function truncate(text, max) {
102
+ if (text.length <= max)
103
+ return text;
104
+ return text.slice(0, max) + "…";
105
+ }
106
+ var FAILURE_RULES = [
107
+ {
108
+ id: "ask_user",
109
+ kind: "ask_user",
110
+ names: ["AskUserError"],
111
+ patterns: ASK_USER_PATTERNS,
112
+ notify: false,
113
+ title: "等待用户回答",
114
+ reason: "agent 正在等待用户回答,不是失败。",
115
+ retryable: false
116
+ },
117
+ {
118
+ id: "context_overflow",
119
+ kind: "context_overflow",
120
+ names: ["ContextError"],
121
+ patterns: CONTEXT_PATTERNS,
122
+ notify: true,
123
+ title: "上下文超出限制",
124
+ reason: "这次对话的上下文超出模型窗口,自动压缩也未能恢复。建议新开一个会话继续,或先让我压缩当前会话。",
125
+ retryable: false
126
+ },
127
+ {
128
+ id: "timeout",
129
+ kind: "timeout",
130
+ names: ["TimeoutError"],
131
+ patterns: TIMEOUT_PATTERNS,
132
+ notify: true,
133
+ title: "执行超时",
134
+ reason: "本次执行等待响应超时(上游长时间未返回或网络卡住)。建议稍后重试,或把任务拆小一些。",
135
+ retryable: true
136
+ },
137
+ {
138
+ id: "upstream_retry",
139
+ kind: "upstream_retry",
140
+ names: ["AI_RetryError", "RetryError", "APICallError", "AI_APICallError"],
141
+ patterns: UPSTREAM_RETRY_PATTERNS,
142
+ notify: true,
143
+ title: "模型服务暂时不可用(重试已用尽)",
144
+ reason: "调用模型时上游持续返回错误(如 429 限流 / 503 不可用),自动重试多次后仍未成功。" + "这不是你的操作问题,也不是仓库代码的问题 —— 稍后重发一次即可。",
145
+ retryable: true
146
+ },
147
+ {
148
+ id: "upstream_aborted",
149
+ kind: "upstream_aborted",
150
+ names: ["RequestAbortedError"],
151
+ patterns: TRANSPORT_ABORT_PATTERNS,
152
+ unless: TIMEOUT_PATTERNS,
153
+ notify: true,
154
+ title: "与模型服务的连接中断",
155
+ reason: "请求在传输过程中被中断(连接被重置 / 代理提前关闭),不是你的操作问题。稍后重发一次即可。",
156
+ retryable: true
157
+ },
158
+ {
159
+ id: "aborted",
160
+ kind: "aborted",
161
+ names: ["AbortError", "AbortSignal"],
162
+ patterns: ABORT_PATTERNS,
163
+ unless: [...TIMEOUT_PATTERNS, ...TRANSPORT_ABORT_PATTERNS],
164
+ notify: true,
165
+ title: "执行被中断",
166
+ reason: "本次执行在完成前被中断(可能你手动取消了,或进程收到了停止信号)。你可以直接让我重新执行。",
167
+ retryable: true
168
+ }
169
+ ];
170
+ var UNKNOWN_RULE = {
171
+ id: "unknown",
172
+ kind: "unknown",
173
+ notify: true,
174
+ title: "执行异常失败",
175
+ reason: "本次执行遇到了未预期的异常,已中止。你可以重试;如果持续失败,请把这条消息里的技术细节发我。",
176
+ retryable: true
177
+ };
178
+ function ruleMatches(rule, name, text) {
179
+ const lowered = name.toLowerCase();
180
+ const nameHit = rule.names?.some((n) => n.toLowerCase() === lowered) ?? false;
181
+ const patternHit = rule.patterns?.some((p) => p.test(text)) ?? false;
182
+ if (!nameHit && !patternHit)
183
+ return false;
184
+ if (rule.unless?.some((p) => p.test(text)))
185
+ return false;
186
+ return true;
187
+ }
188
+ function getFailureRuleIds() {
189
+ return [...FAILURE_RULES.map((r) => r.id), UNKNOWN_RULE.id];
190
+ }
191
+ function classifyReactFailure(error) {
192
+ const text = collectErrorText(error);
193
+ const name = error && typeof error === "object" ? String(error.name ?? "") : "";
194
+ const technical = text ? truncate(text.replace(/\s*\n\s*/g, " | "), 400) : undefined;
195
+ const rule = FAILURE_RULES.find((r) => ruleMatches(r, name, text)) ?? UNKNOWN_RULE;
196
+ return {
197
+ kind: rule.kind,
198
+ ruleId: rule.id,
199
+ title: rule.title,
200
+ reason: rule.reason,
201
+ retryable: rule.retryable,
202
+ notify: rule.notify,
203
+ technical
204
+ };
205
+ }
206
+ var MAX_QUERY_PREVIEW = 200;
207
+ function buildFailureReplyMarkdown(info, opts) {
208
+ const lines = [];
209
+ lines.push(`❌ **${info.title}**`);
210
+ lines.push("");
211
+ lines.push(info.reason);
212
+ const query = opts?.query?.trim();
213
+ if (query) {
214
+ lines.push("");
215
+ lines.push(`> 原始请求:${truncate(query.replace(/\s+/g, " "), MAX_QUERY_PREVIEW)}`);
216
+ }
217
+ if (info.retryable) {
218
+ lines.push("");
219
+ lines.push("**你可以:** 直接再发一次(重发即可,无需额外操作)。");
220
+ } else {
221
+ lines.push("");
222
+ lines.push("**你可以:** 新开一个会话,或先让我压缩当前会话。");
223
+ }
224
+ const technical = info.technical;
225
+ if (technical) {
226
+ lines.push("");
227
+ lines.push(`> 技术细节:${truncate(technical, 300)}`);
228
+ }
229
+ return lines.join(`
230
+ `);
231
+ }
232
+ function extractReplyChannelFromEvent(envEvent) {
233
+ if (!envEvent || typeof envEvent !== "object")
234
+ return;
235
+ const e = envEvent;
236
+ const candidates = [
237
+ e.metadata?.replyChannel,
238
+ e.payload?.replyChannel
239
+ ];
240
+ for (const c of candidates) {
241
+ if (c && typeof c === "object") {
242
+ const ch = c;
243
+ if (ch.chatId || ch.messageId)
244
+ return ch;
245
+ }
246
+ }
247
+ return;
248
+ }
249
+ function isUsableChannel(ch) {
250
+ if (!ch)
251
+ return false;
252
+ if (!ch.chatId && !ch.messageId)
253
+ return false;
254
+ if (ch.type && !ch.type.toLowerCase().includes("lark"))
255
+ return false;
256
+ return true;
257
+ }
258
+ var repliedTriggers = new Map;
259
+ var CHAT_DEDUP_WINDOW_MS = 5 * 60000;
260
+ var MAX_DEDUP_ENTRIES = 1000;
261
+ function makeDedupKey(channel, info, explicit, now = Date.now()) {
262
+ if (explicit)
263
+ return explicit;
264
+ if (channel.messageId)
265
+ return `msg:${channel.messageId}`;
266
+ if (channel.chatId) {
267
+ const bucket = Math.floor(now / CHAT_DEDUP_WINDOW_MS);
268
+ return `chat:${channel.chatId}:${info.kind}:${bucket}`;
269
+ }
270
+ return "unknown";
271
+ }
272
+ function isDuplicate(key, now = Date.now()) {
273
+ const at = repliedTriggers.get(key);
274
+ if (at === undefined)
275
+ return false;
276
+ if (key.startsWith("chat:") && now - at >= CHAT_DEDUP_WINDOW_MS) {
277
+ repliedTriggers.delete(key);
278
+ return false;
279
+ }
280
+ return true;
281
+ }
282
+ function rememberTrigger(key, now = Date.now()) {
283
+ if (repliedTriggers.size >= MAX_DEDUP_ENTRIES) {
284
+ const oldest = repliedTriggers.keys().next().value;
285
+ if (oldest !== undefined)
286
+ repliedTriggers.delete(oldest);
287
+ }
288
+ repliedTriggers.set(key, now);
289
+ }
290
+ function __resetFailureReplyDedupForTest() {
291
+ repliedTriggers.clear();
292
+ }
293
+ var DEFAULT_REPLY_TIMEOUT_MS = 5000;
294
+ function spawnLarkReply(options) {
295
+ return new Promise((resolve, reject) => {
296
+ const { chatId, messageId, content, profile } = options;
297
+ const timeoutMs = options.timeoutMs ?? DEFAULT_REPLY_TIMEOUT_MS;
298
+ let settled = false;
299
+ let timer;
300
+ const finish = (err) => {
301
+ if (settled)
302
+ return;
303
+ settled = true;
304
+ if (timer)
305
+ clearTimeout(timer);
306
+ if (err)
307
+ reject(err);
308
+ else
309
+ resolve();
310
+ };
311
+ const normalizedContent = normalizeLarkAtMentions(content);
312
+ let args;
313
+ if (messageId) {
314
+ args = [
315
+ "im",
316
+ "+messages-reply",
317
+ "--message-id",
318
+ messageId,
319
+ "--markdown",
320
+ normalizedContent,
321
+ "--as",
322
+ "bot"
323
+ ];
324
+ } else if (chatId) {
325
+ args = [
326
+ "im",
327
+ "+messages-send",
328
+ "--chat-id",
329
+ chatId,
330
+ "--markdown",
331
+ normalizedContent,
332
+ "--as",
333
+ "bot"
334
+ ];
335
+ } else {
336
+ finish(new Error("No target specified for failure reply"));
337
+ return;
338
+ }
339
+ if (profile) {
340
+ args.unshift("--profile", profile);
341
+ }
342
+ let proc;
343
+ try {
344
+ proc = spawn("lark-cli", args, {
345
+ shell: false,
346
+ stdio: ["pipe", "pipe", "pipe"]
347
+ });
348
+ } catch (err) {
349
+ finish(err instanceof Error ? err : new Error(String(err)));
350
+ return;
351
+ }
352
+ timer = setTimeout(() => {
353
+ try {
354
+ proc.kill("SIGKILL");
355
+ } catch {}
356
+ finish(new Error(`lark-cli timed out after ${timeoutMs}ms`));
357
+ }, timeoutMs);
358
+ timer.unref?.();
359
+ let stderr = "";
360
+ proc.stdout?.on("data", () => {});
361
+ proc.stderr?.on("data", (data) => {
362
+ stderr += data.toString();
363
+ });
364
+ proc.on("close", (code) => {
365
+ if (code === 0)
366
+ finish();
367
+ else
368
+ finish(new Error(`lark-cli exited with code ${code}: ${stderr}`));
369
+ });
370
+ proc.on("error", (err) => finish(err));
371
+ });
372
+ }
373
+ async function notifyReactFailure(options) {
374
+ const info = classifyReactFailure(options.error);
375
+ if (!info.notify) {
376
+ logger.debug(`[#4418] 命中规则 ${info.ruleId}(非失败),不发失败说明` + (options.sessionId ? ` (session=${options.sessionId})` : ""));
377
+ return { sent: false, kind: info.kind, info, skipped: "not_a_failure" };
378
+ }
379
+ const channel = (isUsableChannel(options.replyChannel) ? options.replyChannel : undefined) ?? extractReplyChannelFromEvent(options.envEvent);
380
+ if (!isUsableChannel(channel)) {
381
+ const hasTrigger = Boolean(options.envEvent);
382
+ const noChannelMsg = `[#4418] React 中断(${info.kind}/${info.ruleId})无法定位 replyChannel,` + `飞书端收不到失败说明` + (hasTrigger ? " —— triggerEvent 存在但缺少 metadata.replyChannel" : "(本地执行,无 triggerEvent)") + (options.sessionId ? ` (session=${options.sessionId})` : "");
383
+ if (hasTrigger)
384
+ logger.warn(noChannelMsg);
385
+ else
386
+ logger.debug(noChannelMsg);
387
+ return { sent: false, kind: info.kind, info, skipped: "no_channel" };
388
+ }
389
+ const dedupKey = makeDedupKey(channel, info, options.dedupKey);
390
+ if (isDuplicate(dedupKey)) {
391
+ logger.info(`[#4418] React 中断(${info.kind})已回复过 ${dedupKey},跳过`);
392
+ return { sent: false, kind: info.kind, info, skipped: "duplicate" };
393
+ }
394
+ rememberTrigger(dedupKey);
395
+ const content = buildFailureReplyMarkdown(info, { query: options.query });
396
+ try {
397
+ await spawnLarkReply({
398
+ chatId: channel.chatId,
399
+ messageId: channel.messageId,
400
+ content,
401
+ profile: channel.profile,
402
+ timeoutMs: options.replyTimeoutMs
403
+ });
404
+ logger.info(`[#4418] React 中断(${info.kind}/${info.ruleId})已回飞书 ` + `(${channel.messageId ?? channel.chatId})`);
405
+ return { sent: true, kind: info.kind, info };
406
+ } catch (err) {
407
+ const errorMsg = err instanceof Error ? err.message : String(err);
408
+ repliedTriggers.delete(dedupKey);
409
+ logger.warn(`[#4418] React 中断(${info.kind}/${info.ruleId})回飞书失败(已忽略): ${errorMsg}`);
410
+ return { sent: false, kind: info.kind, info, error: errorMsg };
411
+ }
412
+ }
413
+
414
+ export { getFailureRuleIds, classifyReactFailure, buildFailureReplyMarkdown, __resetFailureReplyDedupForTest, notifyReactFailure };