@gakr-gakr/feishu 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/api.ts +32 -0
  2. package/autobot.plugin.json +180 -0
  3. package/channel-entry.ts +20 -0
  4. package/channel-plugin-api.ts +1 -0
  5. package/contract-api.ts +16 -0
  6. package/index.ts +82 -0
  7. package/package.json +62 -0
  8. package/runtime-api.ts +55 -0
  9. package/secret-contract-api.ts +5 -0
  10. package/security-contract-api.ts +1 -0
  11. package/session-key-api.ts +1 -0
  12. package/setup-api.ts +3 -0
  13. package/setup-entry.ts +13 -0
  14. package/skills/feishu-doc/SKILL.md +211 -0
  15. package/skills/feishu-doc/references/block-types.md +103 -0
  16. package/skills/feishu-drive/SKILL.md +97 -0
  17. package/skills/feishu-perm/SKILL.md +119 -0
  18. package/skills/feishu-wiki/SKILL.md +113 -0
  19. package/src/accounts.ts +333 -0
  20. package/src/agent-config.ts +21 -0
  21. package/src/app-registration.ts +331 -0
  22. package/src/approval-auth.ts +25 -0
  23. package/src/async.ts +104 -0
  24. package/src/audio-preflight.runtime.ts +9 -0
  25. package/src/bitable.ts +762 -0
  26. package/src/bot-content.ts +485 -0
  27. package/src/bot-runtime-api.ts +12 -0
  28. package/src/bot-sender-name.ts +125 -0
  29. package/src/bot.ts +1703 -0
  30. package/src/card-action.ts +447 -0
  31. package/src/card-interaction.ts +159 -0
  32. package/src/card-test-helpers.ts +54 -0
  33. package/src/card-ux-approval.ts +65 -0
  34. package/src/card-ux-launcher.ts +121 -0
  35. package/src/card-ux-shared.ts +33 -0
  36. package/src/channel-runtime-api.ts +16 -0
  37. package/src/channel.runtime.ts +47 -0
  38. package/src/channel.ts +1423 -0
  39. package/src/chat-schema.ts +25 -0
  40. package/src/chat.ts +188 -0
  41. package/src/client-timeout.ts +42 -0
  42. package/src/client.ts +262 -0
  43. package/src/comment-dispatcher-runtime-api.ts +6 -0
  44. package/src/comment-dispatcher.ts +107 -0
  45. package/src/comment-handler-runtime-api.ts +3 -0
  46. package/src/comment-handler.ts +303 -0
  47. package/src/comment-reaction.ts +259 -0
  48. package/src/comment-shared.ts +406 -0
  49. package/src/comment-target.ts +44 -0
  50. package/src/config-schema.ts +335 -0
  51. package/src/conversation-id.ts +199 -0
  52. package/src/dedup-runtime-api.ts +1 -0
  53. package/src/dedup.ts +141 -0
  54. package/src/dedupe-key.ts +72 -0
  55. package/src/directory.static.ts +61 -0
  56. package/src/directory.ts +124 -0
  57. package/src/doc-schema.ts +182 -0
  58. package/src/docx-batch-insert.ts +223 -0
  59. package/src/docx-color-text.ts +154 -0
  60. package/src/docx-table-ops.ts +316 -0
  61. package/src/docx-types.ts +38 -0
  62. package/src/docx.ts +1596 -0
  63. package/src/drive-schema.ts +92 -0
  64. package/src/drive.ts +829 -0
  65. package/src/dynamic-agent.ts +143 -0
  66. package/src/event-types.ts +45 -0
  67. package/src/external-keys.ts +19 -0
  68. package/src/lifecycle.test-support.ts +220 -0
  69. package/src/media.ts +1105 -0
  70. package/src/mention-target.types.ts +5 -0
  71. package/src/mention.ts +114 -0
  72. package/src/message-action-contract.ts +13 -0
  73. package/src/monitor-state-runtime-api.ts +7 -0
  74. package/src/monitor-transport-runtime-api.ts +10 -0
  75. package/src/monitor.account.ts +492 -0
  76. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +219 -0
  77. package/src/monitor.bot-identity.ts +86 -0
  78. package/src/monitor.bot-menu-handler.ts +165 -0
  79. package/src/monitor.bot-menu.lifecycle.test-support.ts +224 -0
  80. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +264 -0
  81. package/src/monitor.card-action.lifecycle.test-support.ts +421 -0
  82. package/src/monitor.comment-notice-handler.ts +105 -0
  83. package/src/monitor.comment.ts +1386 -0
  84. package/src/monitor.message-handler.ts +350 -0
  85. package/src/monitor.reaction.lifecycle.test-support.ts +68 -0
  86. package/src/monitor.startup.ts +74 -0
  87. package/src/monitor.state.ts +170 -0
  88. package/src/monitor.synthetic-error.ts +18 -0
  89. package/src/monitor.test-mocks.ts +46 -0
  90. package/src/monitor.transport.ts +451 -0
  91. package/src/monitor.ts +100 -0
  92. package/src/outbound-runtime-api.ts +1 -0
  93. package/src/outbound.ts +785 -0
  94. package/src/perm-schema.ts +52 -0
  95. package/src/perm.ts +170 -0
  96. package/src/pins.ts +108 -0
  97. package/src/policy.ts +321 -0
  98. package/src/post.ts +275 -0
  99. package/src/probe.ts +166 -0
  100. package/src/processing-claims.ts +59 -0
  101. package/src/qr-terminal.ts +1 -0
  102. package/src/reactions.ts +123 -0
  103. package/src/reasoning-preview.ts +28 -0
  104. package/src/reply-dispatcher-runtime-api.ts +7 -0
  105. package/src/reply-dispatcher.ts +748 -0
  106. package/src/runtime.ts +9 -0
  107. package/src/secret-contract.ts +145 -0
  108. package/src/secret-input.ts +1 -0
  109. package/src/security-audit-shared.ts +69 -0
  110. package/src/security-audit.ts +1 -0
  111. package/src/send-result.ts +80 -0
  112. package/src/send-target.ts +35 -0
  113. package/src/send.ts +861 -0
  114. package/src/sequential-key.ts +28 -0
  115. package/src/sequential-queue.ts +86 -0
  116. package/src/session-conversation.ts +42 -0
  117. package/src/session-route.ts +48 -0
  118. package/src/setup-core.ts +51 -0
  119. package/src/setup-surface.ts +618 -0
  120. package/src/streaming-card.ts +571 -0
  121. package/src/subagent-hooks.ts +413 -0
  122. package/src/targets.ts +97 -0
  123. package/src/thread-bindings.ts +331 -0
  124. package/src/tool-account.ts +93 -0
  125. package/src/tool-factory-test-harness.ts +79 -0
  126. package/src/tool-result.ts +16 -0
  127. package/src/tools-config.ts +22 -0
  128. package/src/types.ts +106 -0
  129. package/src/typing.ts +214 -0
  130. package/src/wiki-schema.ts +69 -0
  131. package/src/wiki.ts +270 -0
  132. package/subagent-hooks-api.ts +31 -0
  133. package/tsconfig.json +16 -0
@@ -0,0 +1,748 @@
1
+ import { formatReasoningMessage } from "autobot/plugin-sdk/agent-runtime";
2
+ import { logTypingFailure } from "autobot/plugin-sdk/channel-feedback";
3
+ import { createChannelMessageReplyPipeline } from "autobot/plugin-sdk/channel-message";
4
+ import {
5
+ formatChannelProgressDraftLineForEntry,
6
+ isChannelProgressDraftWorkToolName,
7
+ } from "autobot/plugin-sdk/channel-streaming";
8
+ import {
9
+ resolveSendableOutboundReplyParts,
10
+ resolveTextChunksWithFallback,
11
+ sendMediaWithLeadingCaption,
12
+ } from "autobot/plugin-sdk/reply-payload";
13
+ import { stripReasoningTagsFromText } from "autobot/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
+ }