@actagent/feishu 2026.6.2

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