@kodelyth/feishu 2026.5.42 → 2026.6.1

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 (192) hide show
  1. package/klaw.plugin.json +1712 -47
  2. package/package.json +17 -4
  3. package/api.ts +0 -32
  4. package/channel-entry.ts +0 -20
  5. package/channel-plugin-api.ts +0 -1
  6. package/contract-api.ts +0 -16
  7. package/index.ts +0 -82
  8. package/runtime-api.ts +0 -52
  9. package/secret-contract-api.ts +0 -5
  10. package/security-contract-api.ts +0 -1
  11. package/session-key-api.ts +0 -1
  12. package/setup-api.ts +0 -3
  13. package/setup-entry.test.ts +0 -19
  14. package/setup-entry.ts +0 -13
  15. package/src/accounts.test.ts +0 -480
  16. package/src/accounts.ts +0 -333
  17. package/src/agent-config.ts +0 -21
  18. package/src/app-registration.ts +0 -331
  19. package/src/approval-auth.test.ts +0 -24
  20. package/src/approval-auth.ts +0 -25
  21. package/src/async.test.ts +0 -35
  22. package/src/async.ts +0 -104
  23. package/src/audio-preflight.runtime.ts +0 -9
  24. package/src/bitable.test.ts +0 -136
  25. package/src/bitable.ts +0 -762
  26. package/src/bot-content.ts +0 -485
  27. package/src/bot-group-name.test.ts +0 -116
  28. package/src/bot-runtime-api.ts +0 -12
  29. package/src/bot-sender-name.ts +0 -125
  30. package/src/bot.broadcast.test.ts +0 -523
  31. package/src/bot.card-action.test.ts +0 -552
  32. package/src/bot.checkBotMentioned.test.ts +0 -265
  33. package/src/bot.helpers.test.ts +0 -135
  34. package/src/bot.stripBotMention.test.ts +0 -126
  35. package/src/bot.test.ts +0 -3671
  36. package/src/bot.ts +0 -1703
  37. package/src/card-action.ts +0 -447
  38. package/src/card-interaction.test.ts +0 -131
  39. package/src/card-interaction.ts +0 -159
  40. package/src/card-test-helpers.ts +0 -54
  41. package/src/card-ux-approval.ts +0 -65
  42. package/src/card-ux-launcher.test.ts +0 -106
  43. package/src/card-ux-launcher.ts +0 -121
  44. package/src/card-ux-shared.ts +0 -33
  45. package/src/channel-runtime-api.ts +0 -16
  46. package/src/channel.runtime.ts +0 -47
  47. package/src/channel.test.ts +0 -1151
  48. package/src/channel.ts +0 -1423
  49. package/src/chat-schema.ts +0 -25
  50. package/src/chat.test.ts +0 -240
  51. package/src/chat.ts +0 -188
  52. package/src/client-timeout.ts +0 -42
  53. package/src/client.test.ts +0 -447
  54. package/src/client.ts +0 -262
  55. package/src/comment-dispatcher-runtime-api.ts +0 -6
  56. package/src/comment-dispatcher.test.ts +0 -185
  57. package/src/comment-dispatcher.ts +0 -107
  58. package/src/comment-handler-runtime-api.ts +0 -3
  59. package/src/comment-handler.test.ts +0 -592
  60. package/src/comment-handler.ts +0 -303
  61. package/src/comment-reaction.test.ts +0 -138
  62. package/src/comment-reaction.ts +0 -259
  63. package/src/comment-shared.test.ts +0 -183
  64. package/src/comment-shared.ts +0 -406
  65. package/src/comment-target.ts +0 -44
  66. package/src/config-schema.test.ts +0 -326
  67. package/src/config-schema.ts +0 -335
  68. package/src/conversation-id.test.ts +0 -18
  69. package/src/conversation-id.ts +0 -199
  70. package/src/dedup-runtime-api.ts +0 -1
  71. package/src/dedup.ts +0 -141
  72. package/src/dedupe-key.ts +0 -72
  73. package/src/directory.static.ts +0 -61
  74. package/src/directory.test.ts +0 -141
  75. package/src/directory.ts +0 -124
  76. package/src/doc-schema.ts +0 -182
  77. package/src/docx-batch-insert.test.ts +0 -116
  78. package/src/docx-batch-insert.ts +0 -223
  79. package/src/docx-color-text.ts +0 -154
  80. package/src/docx-table-ops.test.ts +0 -53
  81. package/src/docx-table-ops.ts +0 -316
  82. package/src/docx-types.ts +0 -38
  83. package/src/docx.account-selection.test.ts +0 -95
  84. package/src/docx.test.ts +0 -701
  85. package/src/docx.ts +0 -1596
  86. package/src/drive-schema.ts +0 -92
  87. package/src/drive.test.ts +0 -1237
  88. package/src/drive.ts +0 -829
  89. package/src/dynamic-agent.test.ts +0 -155
  90. package/src/dynamic-agent.ts +0 -143
  91. package/src/event-types.ts +0 -45
  92. package/src/external-keys.test.ts +0 -20
  93. package/src/external-keys.ts +0 -19
  94. package/src/lifecycle.test-support.ts +0 -220
  95. package/src/media.test.ts +0 -955
  96. package/src/media.ts +0 -1105
  97. package/src/mention-target.types.ts +0 -5
  98. package/src/mention.ts +0 -114
  99. package/src/message-action-contract.ts +0 -13
  100. package/src/monitor-state-runtime-api.ts +0 -7
  101. package/src/monitor-transport-runtime-api.ts +0 -10
  102. package/src/monitor.account.ts +0 -492
  103. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  104. package/src/monitor.bot-identity.ts +0 -86
  105. package/src/monitor.bot-menu-handler.ts +0 -165
  106. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  107. package/src/monitor.bot-menu.test.ts +0 -188
  108. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  109. package/src/monitor.card-action.lifecycle.test-support.ts +0 -421
  110. package/src/monitor.cleanup.test.ts +0 -383
  111. package/src/monitor.comment-notice-handler.ts +0 -105
  112. package/src/monitor.comment.test.ts +0 -967
  113. package/src/monitor.comment.ts +0 -1386
  114. package/src/monitor.lifecycle.test.ts +0 -4
  115. package/src/monitor.message-handler.ts +0 -350
  116. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  117. package/src/monitor.reaction.test.ts +0 -739
  118. package/src/monitor.startup.test.ts +0 -213
  119. package/src/monitor.startup.ts +0 -74
  120. package/src/monitor.state.defaults.test.ts +0 -46
  121. package/src/monitor.state.ts +0 -170
  122. package/src/monitor.synthetic-error.ts +0 -18
  123. package/src/monitor.test-mocks.ts +0 -46
  124. package/src/monitor.transport.ts +0 -451
  125. package/src/monitor.ts +0 -100
  126. package/src/monitor.webhook-e2e.test.ts +0 -279
  127. package/src/monitor.webhook-security.test.ts +0 -389
  128. package/src/monitor.webhook.test-helpers.ts +0 -116
  129. package/src/outbound-runtime-api.ts +0 -1
  130. package/src/outbound.test.ts +0 -1118
  131. package/src/outbound.ts +0 -785
  132. package/src/perm-schema.ts +0 -52
  133. package/src/perm.ts +0 -170
  134. package/src/pins.ts +0 -108
  135. package/src/policy.test.ts +0 -223
  136. package/src/policy.ts +0 -318
  137. package/src/post.test.ts +0 -105
  138. package/src/post.ts +0 -275
  139. package/src/probe.test.ts +0 -283
  140. package/src/probe.ts +0 -166
  141. package/src/processing-claims.ts +0 -59
  142. package/src/qr-terminal.ts +0 -1
  143. package/src/reactions.ts +0 -123
  144. package/src/reasoning-preview.test.ts +0 -113
  145. package/src/reasoning-preview.ts +0 -28
  146. package/src/reply-dispatcher-runtime-api.ts +0 -7
  147. package/src/reply-dispatcher.test.ts +0 -1513
  148. package/src/reply-dispatcher.ts +0 -748
  149. package/src/runtime.ts +0 -9
  150. package/src/secret-contract.ts +0 -145
  151. package/src/secret-input.ts +0 -1
  152. package/src/security-audit-shared.ts +0 -69
  153. package/src/security-audit.test.ts +0 -59
  154. package/src/security-audit.ts +0 -1
  155. package/src/send-result.ts +0 -80
  156. package/src/send-target.test.ts +0 -86
  157. package/src/send-target.ts +0 -35
  158. package/src/send.reply-fallback.test.ts +0 -417
  159. package/src/send.test.ts +0 -621
  160. package/src/send.ts +0 -861
  161. package/src/sequential-key.test.ts +0 -72
  162. package/src/sequential-key.ts +0 -25
  163. package/src/sequential-queue.test.ts +0 -165
  164. package/src/sequential-queue.ts +0 -86
  165. package/src/session-conversation.ts +0 -42
  166. package/src/session-route.ts +0 -48
  167. package/src/setup-core.ts +0 -51
  168. package/src/setup-surface.test.ts +0 -484
  169. package/src/setup-surface.ts +0 -618
  170. package/src/streaming-card.test.ts +0 -397
  171. package/src/streaming-card.ts +0 -571
  172. package/src/subagent-hooks.test.ts +0 -627
  173. package/src/subagent-hooks.ts +0 -413
  174. package/src/targets.ts +0 -97
  175. package/src/test-support/lifecycle-test-support.ts +0 -454
  176. package/src/thread-bindings.test.ts +0 -180
  177. package/src/thread-bindings.ts +0 -331
  178. package/src/tool-account-routing.test.ts +0 -250
  179. package/src/tool-account.test.ts +0 -44
  180. package/src/tool-account.ts +0 -93
  181. package/src/tool-factory-test-harness.ts +0 -79
  182. package/src/tool-result.test.ts +0 -32
  183. package/src/tool-result.ts +0 -16
  184. package/src/tools-config.test.ts +0 -21
  185. package/src/tools-config.ts +0 -22
  186. package/src/types.ts +0 -106
  187. package/src/typing.test.ts +0 -144
  188. package/src/typing.ts +0 -214
  189. package/src/wiki-schema.ts +0 -69
  190. package/src/wiki.ts +0 -270
  191. package/subagent-hooks-api.ts +0 -31
  192. package/tsconfig.json +0 -16
@@ -1,748 +0,0 @@
1
- import { formatReasoningMessage } from "klaw/plugin-sdk/agent-runtime";
2
- import { logTypingFailure } from "klaw/plugin-sdk/channel-feedback";
3
- import { createChannelMessageReplyPipeline } from "klaw/plugin-sdk/channel-message";
4
- import {
5
- formatChannelProgressDraftLineForEntry,
6
- isChannelProgressDraftWorkToolName,
7
- } from "klaw/plugin-sdk/channel-streaming";
8
- import {
9
- resolveSendableOutboundReplyParts,
10
- resolveTextChunksWithFallback,
11
- sendMediaWithLeadingCaption,
12
- } from "klaw/plugin-sdk/reply-payload";
13
- import { stripReasoningTagsFromText } from "klaw/plugin-sdk/text-chunking";
14
- import { resolveFeishuRuntimeAccount } from "./accounts.js";
15
- import { createFeishuClient } from "./client.js";
16
- import { sendMediaFeishu, shouldSuppressFeishuTextForVoiceMedia } from "./media.js";
17
- import {
18
- createReplyPrefixContext,
19
- type ClawdbotConfig,
20
- type OutboundIdentity,
21
- type ReplyPayload,
22
- type RuntimeEnv,
23
- } from "./reply-dispatcher-runtime-api.js";
24
- import { getFeishuRuntime } from "./runtime.js";
25
- import { sendMessageFeishu, sendStructuredCardFeishu, type CardHeaderConfig } from "./send.js";
26
- import { FeishuStreamingSession, mergeStreamingText } from "./streaming-card.js";
27
- import { resolveReceiveIdType } from "./targets.js";
28
- import { addTypingIndicator, removeTypingIndicator, type TypingIndicatorState } from "./typing.js";
29
-
30
- /** Detect if text contains markdown elements that benefit from card rendering */
31
- function shouldUseCard(text: string): boolean {
32
- return /```[\s\S]*?```/.test(text) || /\|.+\|[\r\n]+\|[-:| ]+\|/.test(text);
33
- }
34
-
35
- /** Maximum age (ms) for a message to receive a typing indicator reaction.
36
- * Messages older than this are likely replays after context compaction (#30418). */
37
- const TYPING_INDICATOR_MAX_AGE_MS = 2 * 60_000;
38
- const MS_EPOCH_MIN = 1_000_000_000_000;
39
- const STREAMING_START_FAILURE_BACKOFF_MS = 60_000;
40
- const streamingStartBackoffUntilByAccount = new Map<string, number>();
41
-
42
- function isStreamingStartBackedOff(accountId: string, now = Date.now()): boolean {
43
- const backoffUntil = streamingStartBackoffUntilByAccount.get(accountId);
44
- if (backoffUntil === undefined) {
45
- return false;
46
- }
47
- if (backoffUntil <= now) {
48
- streamingStartBackoffUntilByAccount.delete(accountId);
49
- return false;
50
- }
51
- return true;
52
- }
53
-
54
- function rememberStreamingStartFailure(accountId: string, now = Date.now()): number {
55
- const backoffUntil = now + STREAMING_START_FAILURE_BACKOFF_MS;
56
- streamingStartBackoffUntilByAccount.set(accountId, backoffUntil);
57
- return backoffUntil;
58
- }
59
-
60
- function formatMediaFallbackText(text: string | undefined, mediaUrl: string): string {
61
- const trimmedText = text?.trim() ?? "";
62
- const attachmentText = `📎 ${mediaUrl}`;
63
- return trimmedText ? `${trimmedText}\n\n${attachmentText}` : attachmentText;
64
- }
65
-
66
- export function clearFeishuStreamingStartBackoffForTests() {
67
- streamingStartBackoffUntilByAccount.clear();
68
- }
69
-
70
- function normalizeEpochMs(timestamp: number | undefined): number | undefined {
71
- if (!Number.isFinite(timestamp) || timestamp === undefined || timestamp <= 0) {
72
- return undefined;
73
- }
74
- // Defensive normalization: some payloads use seconds, others milliseconds.
75
- // Values below 1e12 are treated as epoch-seconds.
76
- return timestamp < MS_EPOCH_MIN ? timestamp * 1000 : timestamp;
77
- }
78
-
79
- /** Build a card header from agent identity config. */
80
- function resolveCardHeader(
81
- agentId: string,
82
- identity: OutboundIdentity | undefined,
83
- ): CardHeaderConfig | undefined {
84
- const name = identity?.name?.trim() || (agentId === "main" ? "" : agentId);
85
- const emoji = identity?.emoji?.trim();
86
- const title = (emoji ? `${emoji} ${name}` : name).trim();
87
- if (!title) {
88
- return undefined;
89
- }
90
- return {
91
- title,
92
- template: identity?.theme ?? "blue",
93
- };
94
- }
95
-
96
- /** Build a card note footer from agent identity and model context. */
97
- function resolveCardNote(
98
- agentId: string,
99
- identity: OutboundIdentity | undefined,
100
- prefixCtx: { model?: string; provider?: string },
101
- ): string {
102
- const name = identity?.name?.trim() || agentId;
103
- const parts: string[] = [`Agent: ${name}`];
104
- if (prefixCtx.model) {
105
- parts.push(`Model: ${prefixCtx.model}`);
106
- }
107
- if (prefixCtx.provider) {
108
- parts.push(`Provider: ${prefixCtx.provider}`);
109
- }
110
- return parts.join(" | ");
111
- }
112
-
113
- type CreateFeishuReplyDispatcherParams = {
114
- cfg: ClawdbotConfig;
115
- agentId: string;
116
- runtime: RuntimeEnv;
117
- chatId: string;
118
- allowReasoningPreview?: boolean;
119
- replyToMessageId?: string;
120
- /** When true, preserve typing indicator on reply target but send messages without reply metadata */
121
- skipReplyToInMessages?: boolean;
122
- replyInThread?: boolean;
123
- /** True when inbound message is already inside a thread/topic context */
124
- threadReply?: boolean;
125
- rootId?: string;
126
- accountId?: string;
127
- identity?: OutboundIdentity;
128
- /** Epoch ms when the inbound message was created. Used to suppress typing
129
- * indicators on old/replayed messages after context compaction (#30418). */
130
- messageCreateTimeMs?: number;
131
- };
132
-
133
- export function createFeishuReplyDispatcher(params: CreateFeishuReplyDispatcherParams) {
134
- const core = getFeishuRuntime();
135
- const {
136
- cfg,
137
- agentId,
138
- chatId,
139
- replyToMessageId,
140
- skipReplyToInMessages,
141
- replyInThread,
142
- threadReply,
143
- rootId,
144
- accountId,
145
- identity,
146
- } = params;
147
- const sendReplyToMessageId = skipReplyToInMessages ? undefined : replyToMessageId;
148
- const threadReplyMode = threadReply === true;
149
- const effectiveReplyInThread = threadReplyMode ? true : replyInThread;
150
- const allowTopLevelReplyFallback =
151
- effectiveReplyInThread === true &&
152
- threadReplyMode &&
153
- rootId !== undefined &&
154
- sendReplyToMessageId !== undefined &&
155
- sendReplyToMessageId !== rootId;
156
- const account = resolveFeishuRuntimeAccount({ cfg, accountId });
157
- const prefixContext = createReplyPrefixContext({ cfg, agentId });
158
-
159
- let typingState: TypingIndicatorState | null = null;
160
- const { typingCallbacks } = createChannelMessageReplyPipeline({
161
- cfg,
162
- agentId,
163
- channel: "feishu",
164
- accountId,
165
- typing: {
166
- start: async () => {
167
- // Check if typing indicator is enabled (default: true)
168
- if (!(account.config.typingIndicator ?? true)) {
169
- return;
170
- }
171
- if (!replyToMessageId) {
172
- return;
173
- }
174
- // Skip typing indicator for old messages — likely replays after context
175
- // compaction that would flood users with stale notifications (#30418).
176
- const messageCreateTimeMs = normalizeEpochMs(params.messageCreateTimeMs);
177
- if (
178
- messageCreateTimeMs !== undefined &&
179
- Date.now() - messageCreateTimeMs > TYPING_INDICATOR_MAX_AGE_MS
180
- ) {
181
- return;
182
- }
183
- // Feishu reactions persist until explicitly removed, so skip keepalive
184
- // re-adds when a reaction already exists. Re-adding the same emoji
185
- // triggers a new push notification for every call (#28660).
186
- if (typingState?.reactionId) {
187
- return;
188
- }
189
- typingState = await addTypingIndicator({
190
- cfg,
191
- messageId: replyToMessageId,
192
- accountId,
193
- runtime: params.runtime,
194
- });
195
- },
196
- stop: async () => {
197
- if (!typingState) {
198
- return;
199
- }
200
- await removeTypingIndicator({
201
- cfg,
202
- state: typingState,
203
- accountId,
204
- runtime: params.runtime,
205
- });
206
- typingState = null;
207
- },
208
- onStartError: (err) =>
209
- logTypingFailure({
210
- log: (message) => params.runtime.log?.(message),
211
- channel: "feishu",
212
- action: "start",
213
- error: err,
214
- }),
215
- onStopError: (err) =>
216
- logTypingFailure({
217
- log: (message) => params.runtime.log?.(message),
218
- channel: "feishu",
219
- action: "stop",
220
- error: err,
221
- }),
222
- },
223
- });
224
-
225
- const textChunkLimit = core.channel.text.resolveTextChunkLimit(cfg, "feishu", accountId, {
226
- fallbackLimit: 4000,
227
- });
228
- const chunkMode = core.channel.text.resolveChunkMode(cfg, "feishu");
229
- const tableMode = core.channel.text.resolveMarkdownTableMode({ cfg, channel: "feishu" });
230
- const renderMode = account.config?.renderMode ?? "auto";
231
- const streamingEnabled = account.config?.streaming !== false && renderMode !== "raw";
232
- const coreBlockStreamingEnabled = account.config?.blockStreaming === true;
233
- const reasoningPreviewEnabled = streamingEnabled && params.allowReasoningPreview === true;
234
-
235
- let streaming: FeishuStreamingSession | null = null;
236
- let streamText = "";
237
- let lastPartial = "";
238
- let reasoningText = "";
239
- let statusLine = "";
240
- let snapshotBaseText = "";
241
- let lastSnapshotTextLength = 0;
242
- const deliveredFinalTexts = new Set<string>();
243
- let partialUpdateQueue: Promise<void> = Promise.resolve();
244
- let streamingStartPromise: Promise<void> | null = null;
245
- let streamingClosedForReply = false;
246
- let streamingCloseErroredForReply = false;
247
- type StreamTextUpdateMode = "snapshot" | "delta";
248
-
249
- const formatReasoningPrefix = (thinking: string): string => {
250
- if (!thinking) {
251
- return "";
252
- }
253
- const withoutLabel = thinking.replace(/^(?:Reasoning:|Thinking\.{0,3})\s*/u, "");
254
- const plain = withoutLabel.replace(/^_(.*)_$/gm, "$1");
255
- const lines = plain.split("\n").map((line) => `> ${line}`);
256
- return `> 💭 **Thinking**\n${lines.join("\n")}`;
257
- };
258
-
259
- const buildCombinedStreamText = (thinking: string, answer: string): string => {
260
- const parts: string[] = [];
261
- if (thinking) {
262
- parts.push(formatReasoningPrefix(thinking));
263
- }
264
- if (thinking && answer) {
265
- parts.push("\n\n---\n\n");
266
- }
267
- if (answer) {
268
- parts.push(answer);
269
- }
270
- if (statusLine) {
271
- parts.push(parts.length > 0 ? `\n\n${statusLine}` : statusLine);
272
- }
273
- return parts.join("");
274
- };
275
-
276
- const flushStreamingCardUpdate = (combined: string) => {
277
- partialUpdateQueue = partialUpdateQueue.then(async () => {
278
- if (streamingStartPromise) {
279
- await streamingStartPromise;
280
- }
281
- if (streaming?.isActive()) {
282
- await streaming.update(combined);
283
- }
284
- });
285
- };
286
-
287
- const queueStreamingUpdate = (
288
- nextText: string,
289
- options?: {
290
- dedupeWithLastPartial?: boolean;
291
- mode?: StreamTextUpdateMode;
292
- },
293
- ) => {
294
- if (!nextText) {
295
- return;
296
- }
297
- if (options?.dedupeWithLastPartial && nextText === lastPartial) {
298
- return;
299
- }
300
- if (options?.dedupeWithLastPartial) {
301
- lastPartial = nextText;
302
- }
303
- const mode = options?.mode ?? "snapshot";
304
- if (mode === "delta") {
305
- streamText = `${streamText}${nextText}`;
306
- } else {
307
- const currentSnapshotText = snapshotBaseText
308
- ? streamText.slice(snapshotBaseText.length)
309
- : streamText;
310
- const startsNewSnapshotBlock =
311
- lastSnapshotTextLength >= 20 &&
312
- nextText.length < lastSnapshotTextLength * 0.5 &&
313
- !currentSnapshotText.includes(nextText);
314
- if (startsNewSnapshotBlock) {
315
- snapshotBaseText = streamText;
316
- streamText = `${snapshotBaseText}${nextText}`;
317
- } else {
318
- streamText = `${snapshotBaseText}${mergeStreamingText(currentSnapshotText, nextText)}`;
319
- }
320
- lastSnapshotTextLength = nextText.length;
321
- }
322
- flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
323
- };
324
-
325
- const queueReasoningUpdate = (nextThinking: string) => {
326
- if (!nextThinking) {
327
- return;
328
- }
329
- reasoningText = nextThinking;
330
- flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
331
- };
332
-
333
- const startStreaming = () => {
334
- if (
335
- !streamingEnabled ||
336
- streamingStartPromise ||
337
- streaming ||
338
- isStreamingStartBackedOff(account.accountId)
339
- ) {
340
- return;
341
- }
342
- streamingStartPromise = (async () => {
343
- const creds =
344
- account.appId && account.appSecret
345
- ? { appId: account.appId, appSecret: account.appSecret, domain: account.domain }
346
- : null;
347
- if (!creds) {
348
- return;
349
- }
350
-
351
- streaming = new FeishuStreamingSession(createFeishuClient(account), creds, (message) =>
352
- params.runtime.log?.(`feishu[${account.accountId}] ${message}`),
353
- );
354
- try {
355
- const cardHeader = resolveCardHeader(agentId, identity);
356
- const cardNote = resolveCardNote(agentId, identity, prefixContext.prefixContext);
357
- await streaming.start(chatId, resolveReceiveIdType(chatId), {
358
- replyToMessageId,
359
- replyInThread: effectiveReplyInThread,
360
- rootId,
361
- header: cardHeader,
362
- note: cardNote,
363
- });
364
- streamingStartBackoffUntilByAccount.delete(account.accountId);
365
- } catch (error) {
366
- rememberStreamingStartFailure(account.accountId);
367
- params.runtime.error?.(
368
- `feishu[${account.accountId}]: streaming start failed; using non-streaming card fallback for ${
369
- STREAMING_START_FAILURE_BACKOFF_MS / 1000
370
- }s: ${String(error)}`,
371
- );
372
- streaming = null;
373
- streamingStartPromise = null;
374
- }
375
- })();
376
- };
377
-
378
- const closeStreaming = async (options?: { markClosedForReply?: boolean }) => {
379
- try {
380
- if (streamingStartPromise) {
381
- await streamingStartPromise;
382
- }
383
- await partialUpdateQueue;
384
- if (streaming?.isActive()) {
385
- statusLine = "";
386
- const text = buildCombinedStreamText(reasoningText, streamText);
387
- const finalNote = resolveCardNote(agentId, identity, prefixContext.prefixContext);
388
- await streaming.close(text, { note: finalNote });
389
- // Track the raw streamed text so the duplicate-final check in deliver()
390
- // can skip the redundant text delivery that arrives after onIdle closes
391
- // the streaming card.
392
- if (streamText) {
393
- deliveredFinalTexts.add(streamText);
394
- if (options?.markClosedForReply !== false && !streamingCloseErroredForReply) {
395
- streamingClosedForReply = true;
396
- }
397
- }
398
- }
399
- } finally {
400
- streaming = null;
401
- streamingStartPromise = null;
402
- partialUpdateQueue = Promise.resolve();
403
- streamText = "";
404
- lastPartial = "";
405
- reasoningText = "";
406
- statusLine = "";
407
- snapshotBaseText = "";
408
- lastSnapshotTextLength = 0;
409
- }
410
- };
411
-
412
- const updateStreamingStatusLine = (nextStatusLine: string) => {
413
- statusLine = nextStatusLine;
414
- if (!streaming?.isActive() && !streamingStartPromise && renderMode !== "card") {
415
- return;
416
- }
417
- startStreaming();
418
- flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
419
- };
420
-
421
- const sendChunkedTextReply = async (params: {
422
- text: string;
423
- useCard: boolean;
424
- infoKind?: string;
425
- sendChunk: (params: { chunk: string; isFirst: boolean }) => Promise<void>;
426
- }) => {
427
- const chunkSource = params.useCard
428
- ? params.text
429
- : core.channel.text.convertMarkdownTables(params.text, tableMode);
430
- const chunks = resolveTextChunksWithFallback(
431
- chunkSource,
432
- core.channel.text.chunkTextWithMode(chunkSource, textChunkLimit, chunkMode),
433
- );
434
- for (const [index, chunk] of chunks.entries()) {
435
- await params.sendChunk({
436
- chunk,
437
- isFirst: index === 0,
438
- });
439
- }
440
- if (params.infoKind === "final") {
441
- deliveredFinalTexts.add(params.text);
442
- }
443
- };
444
-
445
- const sendMediaReplies = async (payload: ReplyPayload, options?: { fallbackText?: string }) => {
446
- const mediaUrls = resolveSendableOutboundReplyParts(payload).mediaUrls;
447
- let sentFallbackText = false;
448
- await sendMediaWithLeadingCaption({
449
- mediaUrls,
450
- caption: "",
451
- send: async ({ mediaUrl }) => {
452
- const result = await sendMediaFeishu({
453
- cfg,
454
- to: chatId,
455
- mediaUrl,
456
- replyToMessageId: sendReplyToMessageId,
457
- replyInThread: effectiveReplyInThread,
458
- accountId,
459
- ...(payload.audioAsVoice === true ? { audioAsVoice: true } : {}),
460
- });
461
- if (result?.voiceIntentDegradedToFile && options?.fallbackText && !sentFallbackText) {
462
- sentFallbackText = true;
463
- await sendChunkedTextReply({
464
- text: options.fallbackText,
465
- useCard: false,
466
- infoKind: "final",
467
- sendChunk: async ({ chunk }) => {
468
- await sendMessageFeishu({
469
- cfg,
470
- to: chatId,
471
- text: chunk,
472
- replyToMessageId: sendReplyToMessageId,
473
- replyInThread: effectiveReplyInThread,
474
- allowTopLevelReplyFallback,
475
- accountId,
476
- });
477
- },
478
- });
479
- }
480
- },
481
- onError:
482
- options?.fallbackText === undefined
483
- ? undefined
484
- : async ({ mediaUrl }) => {
485
- const fallbackText = formatMediaFallbackText(
486
- sentFallbackText ? undefined : options.fallbackText,
487
- mediaUrl,
488
- );
489
- sentFallbackText = true;
490
- await sendChunkedTextReply({
491
- text: fallbackText,
492
- useCard: false,
493
- infoKind: "final",
494
- sendChunk: async ({ chunk }) => {
495
- await sendMessageFeishu({
496
- cfg,
497
- to: chatId,
498
- text: chunk,
499
- replyToMessageId: sendReplyToMessageId,
500
- replyInThread: effectiveReplyInThread,
501
- allowTopLevelReplyFallback,
502
- accountId,
503
- });
504
- },
505
- });
506
- },
507
- });
508
- };
509
-
510
- const { dispatcher, replyOptions, markDispatchIdle } =
511
- core.channel.reply.createReplyDispatcherWithTyping({
512
- responsePrefix: prefixContext.responsePrefix,
513
- responsePrefixContextProvider: prefixContext.responsePrefixContextProvider,
514
- humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, agentId),
515
- onReplyStart: async () => {
516
- deliveredFinalTexts.clear();
517
- streamingClosedForReply = false;
518
- streamingCloseErroredForReply = false;
519
- if (streamingEnabled && renderMode === "card") {
520
- startStreaming();
521
- }
522
- await typingCallbacks?.onReplyStart?.();
523
- },
524
- deliver: async (payload: ReplyPayload, info) => {
525
- const payloadText =
526
- payload.isReasoning && payload.text ? formatReasoningMessage(payload.text) : payload.text;
527
- const reply = resolveSendableOutboundReplyParts({ ...payload, text: payloadText });
528
- const text = reply.text;
529
- const hasText = reply.hasText;
530
- const hasMedia = reply.hasMedia;
531
- const hasVoiceMedia =
532
- hasMedia &&
533
- reply.mediaUrls.some((mediaUrl) =>
534
- shouldSuppressFeishuTextForVoiceMedia({
535
- mediaUrl,
536
- ...(payload.audioAsVoice === true ? { audioAsVoice: true } : {}),
537
- }),
538
- );
539
- const useCard =
540
- hasText &&
541
- (renderMode === "card" ||
542
- (info?.kind === "block" && coreBlockStreamingEnabled && renderMode !== "raw") ||
543
- (renderMode === "auto" && shouldUseCard(text)));
544
- const skipTextForDuplicateFinal =
545
- info?.kind === "final" && hasText && deliveredFinalTexts.has(text);
546
- const skipTextForClosedStreamingFinal =
547
- info?.kind === "final" &&
548
- hasText &&
549
- streamingClosedForReply &&
550
- !streamingCloseErroredForReply &&
551
- streamingEnabled &&
552
- useCard;
553
- const shouldDeliverText =
554
- hasText &&
555
- !hasVoiceMedia &&
556
- !skipTextForDuplicateFinal &&
557
- !skipTextForClosedStreamingFinal;
558
-
559
- if (!shouldDeliverText && !hasMedia) {
560
- return;
561
- }
562
-
563
- if (shouldDeliverText) {
564
- if (info?.kind === "block") {
565
- // Drop internal block chunks unless we can safely consume them as
566
- // streaming-card fallback content.
567
- if (!(streamingEnabled && useCard)) {
568
- return;
569
- }
570
- startStreaming();
571
- if (streamingStartPromise) {
572
- await streamingStartPromise;
573
- }
574
- }
575
-
576
- if (info?.kind === "final" && streamingEnabled && useCard) {
577
- startStreaming();
578
- if (streamingStartPromise) {
579
- await streamingStartPromise;
580
- }
581
- }
582
-
583
- if (streaming?.isActive()) {
584
- if (info?.kind === "block") {
585
- // Some runtimes emit block payloads without onPartial/final callbacks.
586
- // Mirror block text into streamText so onIdle close still sends content.
587
- queueStreamingUpdate(text, { mode: "delta", dedupeWithLastPartial: true });
588
- }
589
- if (info?.kind === "final") {
590
- streamText = text;
591
- snapshotBaseText = "";
592
- lastSnapshotTextLength = text.length;
593
- flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
594
- }
595
- // Send media even when streaming handled the text
596
- if (hasMedia) {
597
- await sendMediaReplies(payload);
598
- }
599
- return;
600
- }
601
-
602
- if (useCard) {
603
- const cardHeader = resolveCardHeader(agentId, identity);
604
- const cardNote = resolveCardNote(agentId, identity, prefixContext.prefixContext);
605
- await sendChunkedTextReply({
606
- text,
607
- useCard: true,
608
- infoKind: info?.kind,
609
- sendChunk: async ({ chunk }) => {
610
- await sendStructuredCardFeishu({
611
- cfg,
612
- to: chatId,
613
- text: chunk,
614
- replyToMessageId: sendReplyToMessageId,
615
- replyInThread: effectiveReplyInThread,
616
- allowTopLevelReplyFallback,
617
- accountId,
618
- header: cardHeader,
619
- note: cardNote,
620
- });
621
- },
622
- });
623
- } else {
624
- await sendChunkedTextReply({
625
- text,
626
- useCard: false,
627
- infoKind: info?.kind,
628
- sendChunk: async ({ chunk }) => {
629
- await sendMessageFeishu({
630
- cfg,
631
- to: chatId,
632
- text: chunk,
633
- replyToMessageId: sendReplyToMessageId,
634
- replyInThread: effectiveReplyInThread,
635
- allowTopLevelReplyFallback,
636
- accountId,
637
- });
638
- },
639
- });
640
- }
641
- }
642
-
643
- if (hasMedia) {
644
- await sendMediaReplies(
645
- payload,
646
- hasVoiceMedia && hasText ? { fallbackText: text } : undefined,
647
- );
648
- }
649
- },
650
- onError: async (error, info) => {
651
- streamingCloseErroredForReply = true;
652
- streamingClosedForReply = false;
653
- params.runtime.error?.(
654
- `feishu[${account.accountId}] ${info.kind} reply failed: ${String(error)}`,
655
- );
656
- await closeStreaming({ markClosedForReply: false });
657
- typingCallbacks?.onIdle?.();
658
- },
659
- onIdle: async () => {
660
- await closeStreaming();
661
- typingCallbacks?.onIdle?.();
662
- },
663
- onCleanup: () => {
664
- typingCallbacks?.onCleanup?.();
665
- },
666
- });
667
-
668
- return {
669
- dispatcher,
670
- replyOptions: {
671
- ...replyOptions,
672
- onModelSelected: prefixContext.onModelSelected,
673
- disableBlockStreaming:
674
- typeof account.config?.blockStreaming === "boolean" ? !account.config.blockStreaming : true,
675
- onPartialReply: streamingEnabled
676
- ? (payload: ReplyPayload) => {
677
- if (!payload.text) {
678
- return;
679
- }
680
- const cleaned = stripReasoningTagsFromText(payload.text, {
681
- mode: "strict",
682
- trim: "both",
683
- });
684
- if (!cleaned) {
685
- return;
686
- }
687
- queueStreamingUpdate(cleaned, {
688
- dedupeWithLastPartial: true,
689
- mode: "snapshot",
690
- });
691
- }
692
- : undefined,
693
- onReasoningStream: reasoningPreviewEnabled
694
- ? (payload: ReplyPayload) => {
695
- if (!payload.text) {
696
- return;
697
- }
698
- startStreaming();
699
- queueReasoningUpdate(formatReasoningMessage(payload.text));
700
- }
701
- : undefined,
702
- onReasoningEnd: reasoningPreviewEnabled ? () => {} : undefined,
703
- onToolStart: streamingEnabled
704
- ? (payload: {
705
- name?: string;
706
- phase?: string;
707
- args?: Record<string, unknown>;
708
- detailMode?: "explain" | "raw";
709
- }) => {
710
- if (!isChannelProgressDraftWorkToolName(payload.name)) {
711
- return;
712
- }
713
- const statusLine = formatChannelProgressDraftLineForEntry(
714
- account.config,
715
- {
716
- event: "tool",
717
- name: payload.name,
718
- phase: payload.phase,
719
- args: payload.args,
720
- },
721
- {
722
- detailMode: payload.detailMode,
723
- },
724
- );
725
- if (statusLine) {
726
- updateStreamingStatusLine(statusLine);
727
- }
728
- }
729
- : undefined,
730
- onAssistantMessageStart: streamingEnabled
731
- ? () => {
732
- updateStreamingStatusLine("");
733
- }
734
- : undefined,
735
- onCompactionStart: streamingEnabled
736
- ? () => {
737
- updateStreamingStatusLine("📦 **Compacting context...**");
738
- }
739
- : undefined,
740
- onCompactionEnd: streamingEnabled
741
- ? () => {
742
- updateStreamingStatusLine("");
743
- }
744
- : undefined,
745
- },
746
- markDispatchIdle,
747
- };
748
- }