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