@openclaw/feishu 2026.10.1 → 2026.10.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/.setup/{app-registration-BB6TubaW.mjs → app-registration-DQOq5urV.mjs} +13 -32
  2. package/dist/.setup/{channel-DoRSlOQd.mjs → channel-CjGGyrdx.mjs} +87 -174
  3. package/dist/.setup/{channel.runtime-jLSFNkJh.mjs → channel.runtime-SaC_uTPM.mjs} +57 -74
  4. package/dist/.setup/{chat-mTBvMMvx.mjs → chat-fC3dvxFs.mjs} +16 -28
  5. package/dist/.setup/{client-CcxmEkoy.mjs → client-wwr8PGPH.mjs} +24 -30
  6. package/dist/.setup/{conversation-id-C1ofUfU8.mjs → conversation-id-D00i9uy5.mjs} +5 -10
  7. package/dist/.setup/{doctor-contract-DyOo8NvC.mjs → doctor-contract-oIpUWtNO.mjs} +8 -15
  8. package/dist/.setup/{monitor-DX3vAlY9.mjs → monitor-Yt__BUki.mjs} +33 -54
  9. package/dist/.setup/{monitor.account-C_uDFPtG.mjs → monitor.account-CVz16781.mjs} +377 -664
  10. package/dist/.setup/{probe-BjSykXB8.mjs → probe-DXnFxq5j.mjs} +14 -17
  11. package/dist/.setup/{reply-delivery-result-laBNOmBu.mjs → reply-delivery-result-iCCrdxE1.mjs} +153 -181
  12. package/dist/.setup/{session-conversation-C53IEUWt.mjs → session-conversation-BSBNK5Mq.mjs} +1 -1
  13. package/dist/.setup/{setup-api-DTTsvzfC.mjs → setup-api-B_LFQQ-Q.mjs} +1 -1
  14. package/dist/.setup/{subagent-hooks-C8Z_x3KJ.mjs → subagent-hooks-9Pc1-k37.mjs} +7 -17
  15. package/dist/.setup/{thread-bindings-jW2x5VuN.mjs → thread-bindings-DdNLxoL3.mjs} +21 -44
  16. package/dist/api.js +218 -326
  17. package/dist/channel-plugin-api.js +1 -1
  18. package/dist/contract-api.js +1 -1
  19. package/dist/doctor-contract-api.js +1 -1
  20. package/dist/session-binding-contract-api.js +1 -1
  21. package/dist/session-key-api.js +1 -1
  22. package/dist/setup-api.js +1 -1
  23. package/dist/setup-entry.js +1 -1
  24. package/dist/subagent-hooks-api.js +1 -1
  25. package/node_modules/@openclaw/fs-safe/CHANGELOG.md +35 -0
  26. package/node_modules/@openclaw/fs-safe/README.md +1 -1
  27. package/node_modules/@openclaw/fs-safe/dist/advanced.d.ts +1 -1
  28. package/node_modules/@openclaw/fs-safe/dist/advanced.js +1 -1
  29. package/node_modules/@openclaw/fs-safe/dist/archive-durability.js +1 -1
  30. package/node_modules/@openclaw/fs-safe/dist/archive-merge.js +4 -4
  31. package/node_modules/@openclaw/fs-safe/dist/archive-parser.wasm +0 -0
  32. package/node_modules/@openclaw/fs-safe/dist/archive-read.js +5 -4
  33. package/node_modules/@openclaw/fs-safe/dist/archive-staging.d.ts +1 -1
  34. package/node_modules/@openclaw/fs-safe/dist/archive-staging.js +22 -38
  35. package/node_modules/@openclaw/fs-safe/dist/copy-path-admission.d.ts +17 -0
  36. package/node_modules/@openclaw/fs-safe/dist/copy-path-admission.js +117 -0
  37. package/node_modules/@openclaw/fs-safe/dist/copy-root-file-sync.d.ts +8 -5
  38. package/node_modules/@openclaw/fs-safe/dist/copy-root-file-sync.js +27 -50
  39. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-acquire.d.ts +3 -0
  40. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-acquire.js +57 -11
  41. package/node_modules/@openclaw/fs-safe/dist/guarded-mutation.js +5 -5
  42. package/node_modules/@openclaw/fs-safe/dist/guest-native-python.js +52 -5
  43. package/node_modules/@openclaw/fs-safe/dist/guest.js +1 -1
  44. package/node_modules/@openclaw/fs-safe/dist/native-binding.d.ts +1 -0
  45. package/node_modules/@openclaw/fs-safe/dist/native-operations.d.ts +0 -1
  46. package/node_modules/@openclaw/fs-safe/dist/native-operations.js +22 -26
  47. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write-windows.js +5 -1
  48. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.js +4 -1
  49. package/node_modules/@openclaw/fs-safe/dist/permission-exec.js +2 -1
  50. package/node_modules/@openclaw/fs-safe/dist/pinned-write-types.d.ts +6 -1
  51. package/node_modules/@openclaw/fs-safe/dist/private-temp-workspace.js +2 -2
  52. package/node_modules/@openclaw/fs-safe/dist/publish-file.js +34 -7
  53. package/node_modules/@openclaw/fs-safe/dist/replace-file-copy-fallback.js +1 -4
  54. package/node_modules/@openclaw/fs-safe/dist/replace-file-descriptor.js +6 -0
  55. package/node_modules/@openclaw/fs-safe/dist/root-create-input.d.ts +15 -1
  56. package/node_modules/@openclaw/fs-safe/dist/root-create-input.js +4 -0
  57. package/node_modules/@openclaw/fs-safe/dist/root-directory-entry.js +1 -1
  58. package/node_modules/@openclaw/fs-safe/dist/root-directory-list.d.ts +0 -1
  59. package/node_modules/@openclaw/fs-safe/dist/root-directory-list.js +6 -12
  60. package/node_modules/@openclaw/fs-safe/dist/root-impl.js +15 -15
  61. package/node_modules/@openclaw/fs-safe/dist/root-paths.js +1 -1
  62. package/node_modules/@openclaw/fs-safe/dist/root-walk.js +4 -4
  63. package/node_modules/@openclaw/fs-safe/dist/root-write-verification.d.ts +10 -1
  64. package/node_modules/@openclaw/fs-safe/dist/root-write-verification.js +20 -0
  65. package/node_modules/@openclaw/fs-safe/dist/secure-temp-dir.js +19 -7
  66. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-acquire.js +25 -3
  67. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-admission.d.ts +2 -0
  68. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-retained.d.ts +14 -0
  69. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-retained.js +187 -0
  70. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock.js +15 -1
  71. package/node_modules/@openclaw/fs-safe/dist/temp-directory-diagnostics.d.ts +10 -0
  72. package/node_modules/@openclaw/fs-safe/dist/temp-directory-diagnostics.js +29 -0
  73. package/node_modules/@openclaw/fs-safe/dist/temp-target.js +1 -1
  74. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-admission.js +6 -6
  75. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.d.ts +4 -4
  76. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.js +17 -16
  77. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-descriptor.js +20 -28
  78. package/node_modules/@openclaw/fs-safe/dist/walk.js +2 -13
  79. package/node_modules/@openclaw/fs-safe/dist/watch-native.d.ts +2 -2
  80. package/node_modules/@openclaw/fs-safe/dist/watch-native.js +3 -1
  81. package/node_modules/@openclaw/fs-safe/dist/watch-rescan.js +3 -9
  82. package/node_modules/@openclaw/fs-safe/dist/watch.js +2 -3
  83. package/node_modules/@openclaw/fs-safe/docs/advanced.md +1 -1
  84. package/node_modules/@openclaw/fs-safe/docs/archive.md +3 -0
  85. package/node_modules/@openclaw/fs-safe/docs/atomic.md +11 -3
  86. package/node_modules/@openclaw/fs-safe/docs/contributing.md +1 -1
  87. package/node_modules/@openclaw/fs-safe/docs/copy.md +48 -0
  88. package/node_modules/@openclaw/fs-safe/docs/guest.md +21 -4
  89. package/node_modules/@openclaw/fs-safe/docs/path-scope.md +4 -0
  90. package/node_modules/@openclaw/fs-safe/docs/sidecar-lock.md +46 -8
  91. package/node_modules/@openclaw/fs-safe/docs/temp.md +12 -0
  92. package/node_modules/@openclaw/fs-safe/docs/watch.md +3 -2
  93. package/node_modules/@openclaw/fs-safe/package.json +15 -15
  94. package/node_modules/@openclaw/fs-safe-darwin-arm64/fs-safe-native.node +0 -0
  95. package/node_modules/@openclaw/fs-safe-darwin-arm64/package.json +1 -1
  96. package/node_modules/@openclaw/fs-safe-darwin-x64/fs-safe-native.node +0 -0
  97. package/node_modules/@openclaw/fs-safe-darwin-x64/package.json +1 -1
  98. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/fs-safe-native.node +0 -0
  99. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/package.json +1 -1
  100. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/fs-safe-native.node +0 -0
  101. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/package.json +1 -1
  102. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/fs-safe-native.node +0 -0
  103. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/package.json +1 -1
  104. package/node_modules/@openclaw/fs-safe-linux-x64-musl/fs-safe-native.node +0 -0
  105. package/node_modules/@openclaw/fs-safe-linux-x64-musl/package.json +1 -1
  106. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/fs-safe-native.node +0 -0
  107. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/package.json +1 -1
  108. package/node_modules/follow-redirects/index.js +10 -1
  109. package/node_modules/follow-redirects/package.json +1 -1
  110. package/package.json +5 -5
  111. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-arbitration.d.ts +0 -17
  112. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-arbitration.js +0 -66
  113. package/node_modules/@openclaw/fs-safe/dist/publish-file-native.d.ts +0 -4
  114. package/node_modules/@openclaw/fs-safe/dist/publish-file-native.js +0 -35
  115. package/node_modules/@openclaw/fs-safe/dist/root-move-preflight.d.ts +0 -7
  116. package/node_modules/@openclaw/fs-safe/dist/root-move-preflight.js +0 -16
@@ -1,15 +1,15 @@
1
- import { c as normalizeFeishuExternalKey, g as resolveFeishuRuntimeAccount, h as resolveFeishuAccount, s as normalizeFeishuWebhookPath } from "./doctor-contract-DyOo8NvC.mjs";
2
- import { o as resolveConfiguredFeishuGroupSessionScope, t as buildFeishuConversationId, u as resolveReceiveIdType } from "./conversation-id-C1ofUfU8.mjs";
3
- import { c as resolveFeishuLegacyWebhookListener, l as gateway_config_runtime_exports, s as describeFeishuWebhookPathConflict } from "./channel-DoRSlOQd.mjs";
4
- import { A as sendMessageFeishu, At as resolveFeishuGroupSenderActivationIngressAccess, B as parsePostContent, D as getMessageFeishu, Dt as resolveFeishuDmIngressAccess, Et as normalizeFeishuAllowEntry, F as isFeishuBroadcastMention, G as deliverCommentThreadText, H as buildFeishuMediaFallbackText, I as isMentionForwardRequest, It as createFeishuCardInteractionEnvelope, L as isFeishuGroupChatType, Lt as decodeFeishuCardAction, Mt as resolveFeishuReplyPolicy, N as formatFeishuMediaContent, Nt as normalizeFeishuChatType, O as listFeishuThreadMessages, Ot as resolveFeishuGroupConfig, P as extractMentionTargets, Pt as resolveFeishuChatType, R as normalizeFeishuEventChatType, S as sendMediaFeishu, T as chunkFeishuCardMarkdown, Tt as hasExplicitFeishuGroupConfig, U as resolveFeishuIdentityEmoji, a as shouldSendNoVisibleReplyFallback, at as requestFeishuApi, b as withinCardTableLimit, d as consumeFeishuPresentationFallbackMarker, et as createCommentTypingReactionLifecycle, ft as chunkFeishuPostMarkdown, ht as shouldUseFeishuCard, i as noVisibleFeishuReplyDelivery, it as parseCommentContentElements, j as sendStructuredCardFeishu, k as sendCardFeishu, kt as resolveFeishuGroupConversationIngressAccess, n as createFeishuReplyDeliveryResult, nt as extractReplyText, ot as buildFeishuCommentTarget, pt as materializeFeishuPostMarkdownSoftBreaks, r as mergeFeishuReplyDeliveryResults, st as normalizeCommentFileType, t as createFeishuPartialReplyDeliveryError, tt as encodeQuery, u as buildFeishuPresentationFallback, ut as resolveFeishuCardTemplate, v as renderFeishuReplyPayload, w as shouldSuppressFeishuTextForVoiceMedia, x as saveMessageResourceFeishu, y as resolveFeishuRichReply, z as parseInteractiveCardContent } from "./reply-delivery-result-laBNOmBu.mjs";
1
+ import { c as normalizeFeishuExternalKey, g as resolveFeishuRuntimeAccount, h as resolveFeishuAccount, s as normalizeFeishuWebhookPath } from "./doctor-contract-oIpUWtNO.mjs";
2
+ import { o as resolveConfiguredFeishuGroupSessionScope, t as buildFeishuConversationId, u as resolveReceiveIdType } from "./conversation-id-D00i9uy5.mjs";
3
+ import { c as resolveFeishuLegacyWebhookListener, l as gateway_config_runtime_exports, s as describeFeishuWebhookPathConflict } from "./channel-CjGGyrdx.mjs";
4
+ import { A as sendMessageFeishu, At as resolveFeishuGroupConversationIngressAccess, B as parseInteractiveCardContent, D as getMessageFeishu, Dt as normalizeFeishuAllowEntry, Et as hasExplicitFeishuGroupConfig, F as isFeishuBroadcastMention, Ft as resolveFeishuChatType, I as isMentionForwardRequest, K as deliverCommentThreadText, L as normalizeMentions, Lt as createFeishuCardInteractionEnvelope, N as formatFeishuMediaContent, Nt as resolveFeishuReplyPolicy, O as listFeishuThreadMessages, Ot as resolveFeishuDmIngressAccess, P as extractMentionTargets, Pt as normalizeFeishuChatType, R as isFeishuGroupChatType, Rt as decodeFeishuCardAction, S as sendMediaFeishu, T as chunkFeishuCardMarkdown, U as buildFeishuMediaFallbackText, V as parsePostContent, W as resolveFeishuIdentityEmoji, a as shouldSendNoVisibleReplyFallback, at as parseCommentContentElements, b as withinCardTableLimit, ct as normalizeCommentFileType, d as consumeFeishuPresentationFallbackMarker, dt as resolveFeishuCardTemplate, gt as shouldUseFeishuCard, i as noVisibleFeishuReplyDelivery, j as sendStructuredCardFeishu, jt as resolveFeishuGroupSenderActivationIngressAccess, k as sendCardFeishu, kt as resolveFeishuGroupConfig, mt as materializeFeishuPostMarkdownSoftBreaks, n as createFeishuReplyDeliveryResult, nt as encodeQuery, ot as requestFeishuApi, pt as chunkFeishuPostMarkdown, r as mergeFeishuReplyDeliveryResults, rt as extractReplyText, st as buildFeishuCommentTarget, t as createFeishuPartialReplyDeliveryError, tt as createCommentTypingReactionLifecycle, u as buildFeishuPresentationFallback, v as renderFeishuReplyPayload, w as shouldSuppressFeishuTextForVoiceMedia, x as saveMessageResourceFeishu, y as resolveFeishuRichReply, z as normalizeFeishuEventChatType } from "./reply-delivery-result-iCCrdxE1.mjs";
5
5
  import { t as getFeishuRuntime } from "./runtime-C5JxBWZp.mjs";
6
- import { a as getFeishuUserAgent, f as resolveConfiguredHttpTimeoutMs, i as createFeishuWSClient, n as createEventDispatcher, r as createFeishuClient } from "./client-CcxmEkoy.mjs";
7
- import { r as getChatInfo } from "./chat-mTBvMMvx.mjs";
8
- import { t as createFeishuThreadBindingManager } from "./thread-bindings-jW2x5VuN.mjs";
6
+ import { a as getFeishuUserAgent, f as resolveConfiguredHttpTimeoutMs, i as createFeishuWSClient, n as createEventDispatcher, r as createFeishuClient } from "./client-wwr8PGPH.mjs";
7
+ import { r as getChatInfo } from "./chat-fC3dvxFs.mjs";
8
+ import { t as createFeishuThreadBindingManager } from "./thread-bindings-DdNLxoL3.mjs";
9
9
  import { evaluateSupplementalContextVisibility, normalizeAgentId as normalizeAgentId$1, resolveChannelContextVisibilityMode } from "../runtime-api.js";
10
10
  import { t as readFeishuJsonResponse } from "./json-response-DXajw_FU.mjs";
11
- import { a as waitForAbortableDelay, i as raceWithTimeoutAndAbort } from "./probe-BjSykXB8.mjs";
12
- import { t as fetchBotIdentityForMonitor } from "./monitor-DX3vAlY9.mjs";
11
+ import { a as waitForAbortableDelay, i as raceWithTimeoutAndAbort } from "./probe-DXnFxq5j.mjs";
12
+ import { t as fetchBotIdentityForMonitor } from "./monitor-Yt__BUki.mjs";
13
13
  import { resolveAgentConfig } from "openclaw/plugin-sdk/agent-scope-runtime";
14
14
  import { DEFAULT_INGRESS_ADOPTION_STALL_MS, bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createChannelMessageReplyPipeline, createReplyPrefixContext, formatChannelProgressDraftLineForEntry, resolveAgentOutboundIdentity, resolveChannelPreviewStreamMode, resolveChannelStreamingBlockEnabled, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
15
15
  import { createChannelPairingController } from "openclaw/plugin-sdk/channel-pairing";
@@ -33,7 +33,7 @@ import * as Lark from "@larksuiteoapi/node-sdk";
33
33
  import { isRecord as isRecord$1 } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
34
34
  import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
35
35
  import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
36
- import { escapeRegExp, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
36
+ import { safeParseJson, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
37
37
  import * as crypto$1 from "node:crypto";
38
38
  import crypto, { createHash } from "node:crypto";
39
39
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
@@ -285,38 +285,13 @@ function resolveFeishuGroupSession(params) {
285
285
  feishuCfg
286
286
  });
287
287
  const topicScope = groupSessionScope === "group_topic" || groupSessionScope === "group_topic_sender" ? (chatType === "topic_group" ? normalizedThreadId ?? normalizedRootId : void 0) ?? normalizedRootId ?? normalizedThreadId ?? (replyInThread ? messageId : null) : null;
288
- let peerId;
289
- switch (groupSessionScope) {
290
- case "group_sender":
291
- peerId = buildFeishuConversationId({
292
- chatId,
293
- scope: "group_sender",
294
- senderOpenId
295
- });
296
- break;
297
- case "group_topic":
298
- peerId = topicScope ? buildFeishuConversationId({
299
- chatId,
300
- scope: "group_topic",
301
- topicId: topicScope
302
- }) : chatId;
303
- break;
304
- case "group_topic_sender":
305
- peerId = topicScope ? buildFeishuConversationId({
306
- chatId,
307
- scope: "group_topic_sender",
308
- topicId: topicScope,
309
- senderOpenId
310
- }) : buildFeishuConversationId({
311
- chatId,
312
- scope: "group_sender",
313
- senderOpenId
314
- });
315
- break;
316
- default: peerId = chatId;
317
- }
318
288
  return {
319
- peerId,
289
+ peerId: groupSessionScope === "group_sender" || groupSessionScope === "group_topic_sender" || topicScope ? buildFeishuConversationId({
290
+ chatId,
291
+ scope: groupSessionScope,
292
+ senderOpenId,
293
+ topicId: topicScope ?? void 0
294
+ }) : chatId,
320
295
  parentPeer: topicScope ? {
321
296
  kind: "group",
322
297
  id: chatId
@@ -367,44 +342,18 @@ function checkBotMentioned(event, botOpenId) {
367
342
  if (event.message.message_type === "post") return parsePostContent(event.message.content).mentionedOpenIds.some((id) => id.trim().toLowerCase() !== "all" && id === botOpenId);
368
343
  return false;
369
344
  }
370
- function normalizeMentions(text, mentions, botStripId) {
371
- if (!mentions || mentions.length === 0) return text;
372
- const escapeName = (value) => value.replace(/</g, "&lt;").replace(/>/g, "&gt;");
373
- const replacements = /* @__PURE__ */ new Map();
374
- for (const mention of mentions) {
375
- const mentionId = mention.id.open_id;
376
- const replacement = botStripId && mentionId === botStripId ? "" : mentionId ? `<at user_id="${mentionId}">${escapeName(mention.name)}</at>` : `@${mention.name}`;
377
- replacements.set(mention.key, replacement);
378
- }
379
- const keys = [...replacements.keys()].toSorted((a, b) => b.length - a.length).map(escapeRegExp);
380
- return text.replace(new RegExp(keys.join("|"), "g"), (key) => replacements.get(key)).trim();
381
- }
382
345
  function normalizeFeishuCommandProbeBody(text) {
383
346
  return text.replace(/<at\b[^>]*>[^<]*<\/at>/giu, " ").replace(/(^|\s)@[^/\s]+(?=\s|$|\/)/gu, "$1").replace(/\s+/g, " ").trim();
384
347
  }
385
- function parseMediaKeys(content, messageType) {
348
+ function parseMediaResource(content, messageType) {
386
349
  try {
387
350
  const parsed = JSON.parse(content);
388
351
  const imageKey = normalizeFeishuExternalKey(parsed.image_key);
389
352
  const fileKey = normalizeFeishuExternalKey(parsed.file_key);
390
- switch (messageType) {
391
- case "image": return {
392
- imageKey,
393
- fileName: parsed.file_name
394
- };
395
- case "file":
396
- case "audio": return {
397
- fileKey,
398
- fileName: parsed.file_name
399
- };
400
- case "video":
401
- case "media": return {
402
- fileKey,
403
- imageKey,
404
- fileName: parsed.file_name
405
- };
406
- default: return {};
407
- }
353
+ return {
354
+ key: messageType === "image" ? imageKey : messageType === "video" || messageType === "media" ? fileKey || imageKey : fileKey,
355
+ fileName: parsed.file_name
356
+ };
408
357
  } catch {
409
358
  return {};
410
359
  }
@@ -448,13 +397,12 @@ async function resolveFeishuMediaList(params) {
448
397
  });
449
398
  }
450
399
  } else {
451
- const mediaKeys = parseMediaKeys(content, messageType);
452
- const fileKey = mediaKeys.fileKey || mediaKeys.imageKey;
453
- if (!fileKey) return [{ kind: resolveFeishuMediaKind(messageType) }];
400
+ const resource = parseMediaResource(content, messageType);
401
+ if (!resource.key) return [{ kind: resolveFeishuMediaKind(messageType) }];
454
402
  resources.push({
455
- key: fileKey,
403
+ key: resource.key,
456
404
  type: messageType === "image" ? "image" : "file",
457
- fileName: mediaKeys.fileName,
405
+ fileName: resource.fileName,
458
406
  kind: resolveFeishuMediaKind(messageType),
459
407
  label: `${messageType} media`
460
408
  });
@@ -670,25 +618,12 @@ async function resolveFeishuBotName(params) {
670
618
  }
671
619
  //#endregion
672
620
  //#region extensions/feishu/src/bot-sender-name.ts
673
- const IGNORED_PERMISSION_SCOPE_TOKENS = ["contact:contact.base:readonly"];
674
- const FEISHU_SCOPE_CORRECTIONS = { "contact:contact.base:readonly": "contact:user.base:readonly" };
621
+ const STALE_CONTACT_SCOPE = "contact:contact.base:readonly";
675
622
  const FEISHU_USER_LOOKUP_UNAUTHORIZED_CODE = 41050;
676
623
  const SENDER_NAME_TTL_MS = 6e5;
677
624
  const SENDER_NAME_NEGATIVE_TTL_MS = 18e5;
678
625
  const SENDER_NAME_CACHE_MAX_SIZE = 500;
679
626
  const senderNameCache = /* @__PURE__ */ new Map();
680
- function correctFeishuScopeInUrl(url) {
681
- let corrected = url;
682
- for (const [wrong, right] of Object.entries(FEISHU_SCOPE_CORRECTIONS)) {
683
- corrected = corrected.replaceAll(encodeURIComponent(wrong), encodeURIComponent(right));
684
- corrected = corrected.replaceAll(wrong, right);
685
- }
686
- return corrected;
687
- }
688
- function shouldSuppressPermissionErrorNotice(permissionError) {
689
- const message = normalizeLowercaseStringOrEmpty(permissionError.message);
690
- return IGNORED_PERMISSION_SCOPE_TOKENS.some((token) => message.includes(token));
691
- }
692
627
  function extractFeishuApiError(err) {
693
628
  if (!err || typeof err !== "object") return null;
694
629
  const data = err.response?.data;
@@ -706,7 +641,7 @@ function extractPermissionError(feishuErr) {
706
641
  return {
707
642
  code: feishuErr.code,
708
643
  message: feishuErr.message,
709
- grantUrl: urlMatch?.[0] ? correctFeishuScopeInUrl(urlMatch[0]) : void 0
644
+ grantUrl: urlMatch?.[0]?.replaceAll(encodeURIComponent(STALE_CONTACT_SCOPE), encodeURIComponent("contact:user.base:readonly")).replaceAll(STALE_CONTACT_SCOPE, "contact:user.base:readonly")
710
645
  };
711
646
  }
712
647
  function writeSenderNameCache(key, entry) {
@@ -715,9 +650,8 @@ function writeSenderNameCache(key, entry) {
715
650
  pruneMapToMaxSize(senderNameCache, SENDER_NAME_CACHE_MAX_SIZE);
716
651
  }
717
652
  function resolveSenderLookupIdType(senderId) {
718
- const trimmed = senderId.trim();
719
- if (trimmed.startsWith("ou_")) return "open_id";
720
- if (trimmed.startsWith("on_")) return "union_id";
653
+ if (senderId.startsWith("ou_")) return "open_id";
654
+ if (senderId.startsWith("on_")) return "union_id";
721
655
  return "user_id";
722
656
  }
723
657
  async function resolveFeishuSenderName(params) {
@@ -753,7 +687,7 @@ async function resolveFeishuSenderName(params) {
753
687
  const feishuErr = extractFeishuApiError(err);
754
688
  const permErr = extractPermissionError(feishuErr);
755
689
  if (permErr) {
756
- if (shouldSuppressPermissionErrorNotice(permErr)) {
690
+ if (normalizeLowercaseStringOrEmpty(permErr.message).includes(STALE_CONTACT_SCOPE)) {
757
691
  log(`feishu: ignoring stale permission scope error: ${permErr.message}`);
758
692
  return {};
759
693
  }
@@ -885,20 +819,13 @@ async function warmupDedupFromPluginState(namespace, log) {
885
819
  }
886
820
  //#endregion
887
821
  //#region extensions/feishu/src/dedupe-key.ts
888
- function parseContentRecord(content) {
889
- try {
890
- return asNullableRecord(JSON.parse(content));
891
- } catch {
892
- return null;
893
- }
894
- }
895
822
  function resolvePostMediaParts(content) {
896
823
  const { attachments } = parsePostContent(content, { includeTopLevelFiles: false });
897
824
  return ["image", "file"].flatMap((kind) => attachments.filter((attachment) => attachment.kind === kind).map((attachment) => `${kind}_key:${attachment.key}`));
898
825
  }
899
826
  function resolveMessageMediaParts(messageType, content) {
900
827
  if (messageType === "post") return resolvePostMediaParts(content);
901
- const parsed = parseContentRecord(content);
828
+ const parsed = asNullableRecord(safeParseJson(content));
902
829
  if (!parsed) return [];
903
830
  const imageKey = normalizeFeishuExternalKey(parsed.image_key);
904
831
  const fileKey = normalizeFeishuExternalKey(parsed.file_key);
@@ -1161,7 +1088,7 @@ async function assertSuccessfulCardKitResponse(response, auditContext, action) {
1161
1088
  const data = await readFeishuJsonResponse(response, auditContext);
1162
1089
  if (data.code !== 0) throw new Error(`${action} failed: ${data.msg ?? "unknown error"} (code=${String(data.code)})`);
1163
1090
  }
1164
- async function getToken(creds, deps) {
1091
+ async function getToken(creds) {
1165
1092
  const key = `${creds.domain ?? "feishu"}|${creds.appId}`;
1166
1093
  const cached = tokenCache.get(key);
1167
1094
  const rawNow = Date.now();
@@ -1182,8 +1109,6 @@ async function getToken(creds, deps) {
1182
1109
  app_secret: creds.appSecret
1183
1110
  })
1184
1111
  },
1185
- fetchImpl: deps?.fetchImpl,
1186
- lookupFn: deps?.lookupFn,
1187
1112
  policy: { allowedHostnames: resolveAllowedHostnames(creds.domain) },
1188
1113
  auditContext: "feishu.streaming-card.token",
1189
1114
  timeoutMs: creds.httpTimeoutMs ?? 3e4
@@ -1225,7 +1150,7 @@ function mergeStreamingText(previousText, nextText) {
1225
1150
  return `${previous}${next}`;
1226
1151
  }
1227
1152
  var FeishuStreamingSession = class {
1228
- constructor(client, creds, log, deps) {
1153
+ constructor(client, creds, log) {
1229
1154
  this.state = null;
1230
1155
  this.queue = Promise.resolve();
1231
1156
  this.closed = false;
@@ -1236,8 +1161,6 @@ var FeishuStreamingSession = class {
1236
1161
  this.client = client;
1237
1162
  this.creds = creds;
1238
1163
  this.log = log;
1239
- this.fetchImpl = deps?.fetchImpl;
1240
- this.lookupFn = deps?.lookupFn;
1241
1164
  }
1242
1165
  async requestCardKit(path, operation, method, body, readResponse, token) {
1243
1166
  const auditContext = `feishu.streaming-card.${operation}`;
@@ -1246,17 +1169,12 @@ var FeishuStreamingSession = class {
1246
1169
  init: {
1247
1170
  method,
1248
1171
  headers: {
1249
- Authorization: `Bearer ${token ?? await getToken(this.creds, {
1250
- fetchImpl: this.fetchImpl,
1251
- lookupFn: this.lookupFn
1252
- })}`,
1172
+ Authorization: `Bearer ${token ?? await getToken(this.creds)}`,
1253
1173
  "Content-Type": method === "PATCH" ? "application/json; charset=utf-8" : "application/json",
1254
1174
  "User-Agent": getFeishuUserAgent()
1255
1175
  },
1256
1176
  body: JSON.stringify(body())
1257
1177
  },
1258
- fetchImpl: this.fetchImpl,
1259
- lookupFn: this.lookupFn,
1260
1178
  policy: { allowedHostnames: resolveAllowedHostnames(this.creds.domain) },
1261
1179
  auditContext,
1262
1180
  timeoutMs: this.creds.httpTimeoutMs ?? 3e4
@@ -1410,10 +1328,7 @@ var FeishuStreamingSession = class {
1410
1328
  if (!this.state || !this.state.hasNote) return;
1411
1329
  this.state.sequence += 1;
1412
1330
  const path = `/${this.state.cardId}/elements/note/content`;
1413
- const token = await getToken(this.creds, {
1414
- fetchImpl: this.fetchImpl,
1415
- lookupFn: this.lookupFn
1416
- });
1331
+ const token = await getToken(this.creds);
1417
1332
  await this.requestCardKit(path, "note-update", "PUT", () => ({
1418
1333
  content: `<font color='grey'>${note}</font>`,
1419
1334
  sequence: this.state.sequence,
@@ -1494,6 +1409,16 @@ var FeishuStreamingSession = class {
1494
1409
  }
1495
1410
  };
1496
1411
  //#endregion
1412
+ //#region extensions/feishu/src/streaming-update.ts
1413
+ /** Admit captured snapshots in order while the session owns provider writes. */
1414
+ function queueFeishuStreamingUpdate(params) {
1415
+ const { queue, session, generation, startPromise, text, accountId, runtime } = params;
1416
+ return queue.then(async () => {
1417
+ if (startPromise) await startPromise;
1418
+ if (generation !== void 0 && session?.isActive()) session.update(text).catch((error) => runtime.error?.(`feishu[${accountId}] streaming update failed: ${String(error)}`));
1419
+ });
1420
+ }
1421
+ //#endregion
1497
1422
  //#region extensions/feishu/src/typing-backoff.ts
1498
1423
  /** Feishu API codes that should trip the typing circuit breaker. */
1499
1424
  const FEISHU_BACKOFF_CODES = /* @__PURE__ */ new Set([
@@ -1525,6 +1450,25 @@ function getBackoffCodeFromResponse(response) {
1525
1450
  //#endregion
1526
1451
  //#region extensions/feishu/src/typing.ts
1527
1452
  const TYPING_EMOJI = "Typing";
1453
+ async function requestTypingReaction(request, operation, readResponse, runtime) {
1454
+ const indicator = `typing indicator${operation === "remove" ? " removal" : ""}`;
1455
+ try {
1456
+ const response = await request();
1457
+ const backoffCode = getBackoffCodeFromResponse(response);
1458
+ if (backoffCode !== void 0) {
1459
+ if (getFeishuRuntime().logging.shouldLogVerbose()) runtime?.log?.(`[feishu] ${indicator} response contains backoff code ${backoffCode}, stopping keepalive`);
1460
+ throw new FeishuBackoffError(backoffCode);
1461
+ }
1462
+ return readResponse(response);
1463
+ } catch (err) {
1464
+ if (isFeishuBackoffError(err)) {
1465
+ if (getFeishuRuntime().logging.shouldLogVerbose()) runtime?.log?.(`[feishu] ${indicator} hit rate-limit/quota, stopping keepalive`);
1466
+ throw err;
1467
+ }
1468
+ if (getFeishuRuntime().logging.shouldLogVerbose()) runtime?.log?.(`[feishu] failed to ${operation} typing indicator: ${String(err)}`);
1469
+ return;
1470
+ }
1471
+ }
1528
1472
  /**
1529
1473
  * Add a typing indicator (reaction) to a message.
1530
1474
  *
@@ -1545,31 +1489,13 @@ async function addTypingIndicator(params) {
1545
1489
  reactionId: null
1546
1490
  };
1547
1491
  const client = createFeishuClient(account);
1548
- try {
1549
- const response = await client.im.messageReaction.create({
1492
+ return {
1493
+ messageId,
1494
+ reactionId: await requestTypingReaction(() => client.im.messageReaction.create({
1550
1495
  path: { message_id: messageId },
1551
1496
  data: { reaction_type: { emoji_type: TYPING_EMOJI } }
1552
- });
1553
- const backoffCode = getBackoffCodeFromResponse(response);
1554
- if (backoffCode !== void 0) {
1555
- if (getFeishuRuntime().logging.shouldLogVerbose()) runtime?.log?.(`[feishu] typing indicator response contains backoff code ${backoffCode}, stopping keepalive`);
1556
- throw new FeishuBackoffError(backoffCode);
1557
- }
1558
- return {
1559
- messageId,
1560
- reactionId: response.data?.reaction_id ?? null
1561
- };
1562
- } catch (err) {
1563
- if (isFeishuBackoffError(err)) {
1564
- if (getFeishuRuntime().logging.shouldLogVerbose()) runtime?.log?.("[feishu] typing indicator hit rate-limit/quota, stopping keepalive");
1565
- throw err;
1566
- }
1567
- if (getFeishuRuntime().logging.shouldLogVerbose()) runtime?.log?.(`[feishu] failed to add typing indicator: ${String(err)}`);
1568
- return {
1569
- messageId,
1570
- reactionId: null
1571
- };
1572
- }
1497
+ }), "add", (response) => response.data?.reaction_id ?? null, runtime) ?? null
1498
+ };
1573
1499
  }
1574
1500
  /**
1575
1501
  * Remove a typing indicator (reaction) from a message.
@@ -1585,22 +1511,10 @@ async function removeTypingIndicator(params) {
1585
1511
  });
1586
1512
  if (!account.configured) return;
1587
1513
  const client = createFeishuClient(account);
1588
- try {
1589
- const backoffCode = getBackoffCodeFromResponse(await client.im.messageReaction.delete({ path: {
1590
- message_id: state.messageId,
1591
- reaction_id: state.reactionId
1592
- } }));
1593
- if (backoffCode !== void 0) {
1594
- if (getFeishuRuntime().logging.shouldLogVerbose()) runtime?.log?.(`[feishu] typing indicator removal response contains backoff code ${backoffCode}, stopping keepalive`);
1595
- throw new FeishuBackoffError(backoffCode);
1596
- }
1597
- } catch (err) {
1598
- if (isFeishuBackoffError(err)) {
1599
- if (getFeishuRuntime().logging.shouldLogVerbose()) runtime?.log?.("[feishu] typing indicator removal hit rate-limit/quota, stopping keepalive");
1600
- throw err;
1601
- }
1602
- if (getFeishuRuntime().logging.shouldLogVerbose()) runtime?.log?.(`[feishu] failed to remove typing indicator: ${String(err)}`);
1603
- }
1514
+ await requestTypingReaction(() => client.im.messageReaction.delete({ path: {
1515
+ message_id: state.messageId,
1516
+ reaction_id: state.reactionId
1517
+ } }), "remove", () => void 0, runtime);
1604
1518
  }
1605
1519
  //#endregion
1606
1520
  //#region extensions/feishu/src/reply-dispatcher.ts
@@ -1624,10 +1538,6 @@ function isStreamingStartBackedOff(accountId, now = Date.now()) {
1624
1538
  }
1625
1539
  return true;
1626
1540
  }
1627
- function rememberStreamingStartFailure(accountId, now = Date.now()) {
1628
- const backoffUntil = now + STREAMING_START_FAILURE_BACKOFF_MS;
1629
- streamingStartBackoffUntilByAccount.set(accountId, backoffUntil);
1630
- }
1631
1541
  function normalizeEpochMs(timestamp) {
1632
1542
  if (!Number.isFinite(timestamp) || timestamp === void 0 || timestamp <= 0) return;
1633
1543
  return timestamp < MS_EPOCH_MIN ? timestamp * 1e3 : timestamp;
@@ -1660,7 +1570,7 @@ function createFeishuReplyDispatcher(params) {
1660
1570
  to: sendTarget,
1661
1571
  replyToMessageId: sendReplyToMessageId,
1662
1572
  replyInThread: effectiveReplyInThread,
1663
- allowTopLevelReplyFallback: effectiveReplyInThread === true && threadReplyMode && rootId !== void 0 && sendReplyToMessageId !== void 0 && sendReplyToMessageId !== rootId,
1573
+ allowTopLevelReplyFallback: threadReplyMode && rootId !== void 0 && sendReplyToMessageId !== void 0 && sendReplyToMessageId !== rootId,
1664
1574
  accountId
1665
1575
  };
1666
1576
  const account = resolveFeishuRuntimeAccount({
@@ -1722,8 +1632,7 @@ function createFeishuReplyDispatcher(params) {
1722
1632
  const hookRunner = getGlobalHookRunner();
1723
1633
  const modifyingHooksRegistered = (hookRunner?.hasHooks("reply_payload_sending") ?? false) || (hookRunner?.hasHooks("message_sending") ?? false);
1724
1634
  const previewStreamingEnabled = streamingEnabled && !modifyingHooksRegistered;
1725
- const blockStreamingEnabled = resolveChannelStreamingBlockEnabled(account.config);
1726
- const coreBlockStreamingEnabled = blockStreamingEnabled === true;
1635
+ const coreBlockStreamingEnabled = resolveChannelStreamingBlockEnabled(account.config) === true;
1727
1636
  const reasoningPreviewEnabled = previewStreamingEnabled && params.allowReasoningPreview === true;
1728
1637
  let streaming = null;
1729
1638
  let streamText = "";
@@ -1756,12 +1665,14 @@ function createFeishuReplyDispatcher(params) {
1756
1665
  return [[thinking ? formatReasoningPrefix(thinking) : "", answer].filter(Boolean).join("\n\n---\n\n"), statusLine].filter(Boolean).join("\n\n");
1757
1666
  };
1758
1667
  const flushStreamingCardUpdate = (combined) => {
1759
- const session = streaming;
1760
- const generation = activeStreamingGeneration;
1761
- const startPromise = streamingStartPromise;
1762
- partialUpdateQueue = partialUpdateQueue.then(async () => {
1763
- if (startPromise) await startPromise;
1764
- if (generation !== void 0 && session?.isActive()) await session.update(combined);
1668
+ partialUpdateQueue = queueFeishuStreamingUpdate({
1669
+ queue: partialUpdateQueue,
1670
+ session: streaming,
1671
+ generation: activeStreamingGeneration,
1672
+ startPromise: streamingStartPromise,
1673
+ text: combined,
1674
+ accountId: account.accountId,
1675
+ runtime: params.runtime
1765
1676
  });
1766
1677
  };
1767
1678
  const queueStreamingUpdate = (nextText, options) => {
@@ -1779,11 +1690,6 @@ function createFeishuReplyDispatcher(params) {
1779
1690
  }
1780
1691
  flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
1781
1692
  };
1782
- const queueReasoningUpdate = (nextThinking) => {
1783
- if (!nextThinking) return;
1784
- reasoningText = nextThinking;
1785
- flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
1786
- };
1787
1693
  const startStreaming = () => {
1788
1694
  if (!streamingEnabled || streamingStartPromise || streaming || isStreamingStartBackedOff(account.accountId)) return;
1789
1695
  streamingStartPromise = (async () => {
@@ -1811,7 +1717,7 @@ function createFeishuReplyDispatcher(params) {
1811
1717
  });
1812
1718
  streamingStartBackoffUntilByAccount.delete(account.accountId);
1813
1719
  } catch (error) {
1814
- rememberStreamingStartFailure(account.accountId);
1720
+ streamingStartBackoffUntilByAccount.set(account.accountId, Date.now() + STREAMING_START_FAILURE_BACKOFF_MS);
1815
1721
  params.runtime.error?.(`feishu[${account.accountId}]: streaming start failed; using non-streaming card fallback for ${STREAMING_START_FAILURE_BACKOFF_MS / 1e3}s: ${String(error)}`);
1816
1722
  if (streaming === session) {
1817
1723
  streaming = null;
@@ -1947,9 +1853,9 @@ function createFeishuReplyDispatcher(params) {
1947
1853
  const outcome = await closeStreaming("discarded");
1948
1854
  if (outcome.error !== void 0) throw toStringifiedError(outcome.error);
1949
1855
  };
1950
- const updateStreamingStatusLine = (nextStatusLine, options) => {
1856
+ const updateStreamingStatusLine = (nextStatusLine, startIfNeeded = true) => {
1951
1857
  statusLine = nextStatusLine;
1952
- if (!Boolean(streaming?.isActive() || streamingStartPromise) && (options?.startIfNeeded === false || renderMode !== "card")) return false;
1858
+ if (!Boolean(streaming?.isActive() || streamingStartPromise) && (!startIfNeeded || renderMode !== "card")) return false;
1953
1859
  startStreaming();
1954
1860
  flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
1955
1861
  return false;
@@ -2090,10 +1996,8 @@ function createFeishuReplyDispatcher(params) {
2090
1996
  if (settlement) settlement.contentClaimed = true;
2091
1997
  return settlement;
2092
1998
  }
2093
- let latestKey;
2094
- for (const [key, settlement] of closedStreamingSettlements) if (settlement.contentClaimed !== true && (content === void 0 || settlement.content === content)) latestKey = key;
2095
- if (latestKey === void 0) return;
2096
- const result = closedStreamingSettlements.get(latestKey);
1999
+ let result;
2000
+ for (const settlement of closedStreamingSettlements.values()) if (settlement.contentClaimed !== true && (content === void 0 || settlement.content === content)) result = settlement;
2097
2001
  if (result) result.contentClaimed = true;
2098
2002
  return result;
2099
2003
  };
@@ -2116,7 +2020,7 @@ function createFeishuReplyDispatcher(params) {
2116
2020
  const closeOutcome = await closeStreaming();
2117
2021
  const finalized = closeOutcome.result;
2118
2022
  const ownsCurrentClose = (completion) => closeOutcome.generation !== void 0 && completion.streamingGeneration === closeOutcome.generation;
2119
- if (completions.some((completion) => ownsCurrentClose(completion))) claimClosedStreamingResult(closeOutcome.generation, void 0);
2023
+ if (completions.some(ownsCurrentClose)) claimClosedStreamingResult(closeOutcome.generation, void 0);
2120
2024
  for (const completion of completions) {
2121
2025
  const claimedSettlement = ownsCurrentClose(completion) ? {
2122
2026
  disposition: closeOutcome.disposition,
@@ -2223,9 +2127,9 @@ function createFeishuReplyDispatcher(params) {
2223
2127
  replyOutcome = void 0;
2224
2128
  }
2225
2129
  if (previewStreamingEnabled && renderMode === "card") startStreaming();
2226
- await Promise.resolve(typingCallbacks?.onReplyStart?.());
2130
+ await typingCallbacks?.onReplyStart?.();
2227
2131
  },
2228
- onIdle: () => queueIdleSideEffects(),
2132
+ onIdle: queueIdleSideEffects,
2229
2133
  onCleanup: () => {
2230
2134
  typingCallbacks?.onCleanup?.();
2231
2135
  }
@@ -2385,7 +2289,7 @@ function createFeishuReplyDispatcher(params) {
2385
2289
  },
2386
2290
  replyOptions: {
2387
2291
  onModelSelected,
2388
- disableBlockStreaming: typeof blockStreamingEnabled === "boolean" ? !blockStreamingEnabled : true,
2292
+ disableBlockStreaming: !coreBlockStreamingEnabled,
2389
2293
  onPartialReply: previewStreamingEnabled ? (payload) => {
2390
2294
  if (!payload.text) return false;
2391
2295
  const cleaned = stripReasoningTagsFromText(payload.text, {
@@ -2403,7 +2307,11 @@ function createFeishuReplyDispatcher(params) {
2403
2307
  onReasoningStream: reasoningPreviewEnabled ? (payload) => {
2404
2308
  if (!payload.text) return false;
2405
2309
  startStreaming();
2406
- queueReasoningUpdate(formatReasoningMessage(payload.text));
2310
+ const nextThinking = formatReasoningMessage(payload.text);
2311
+ if (nextThinking) {
2312
+ reasoningText = nextThinking;
2313
+ flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
2314
+ }
2407
2315
  return false;
2408
2316
  } : void 0,
2409
2317
  onReasoningEnd: reasoningPreviewEnabled ? () => false : void 0,
@@ -2418,7 +2326,7 @@ function createFeishuReplyDispatcher(params) {
2418
2326
  if (statusLineLocal) return updateStreamingStatusLine(statusLineLocal);
2419
2327
  return false;
2420
2328
  } : void 0,
2421
- onAssistantMessageStart: previewStreamingEnabled ? () => updateStreamingStatusLine("", { startIfNeeded: false }) : void 0,
2329
+ onAssistantMessageStart: previewStreamingEnabled ? () => updateStreamingStatusLine("", false) : void 0,
2422
2330
  onCompactionStart: previewStreamingEnabled ? () => updateStreamingStatusLine("📦 **Compacting context...**") : void 0,
2423
2331
  onCompactionEnd: previewStreamingEnabled ? () => updateStreamingStatusLine("") : void 0
2424
2332
  },
@@ -2721,7 +2629,7 @@ async function handleFeishuMessage(params) {
2721
2629
  const dmPolicy = feishuCfg?.dmPolicy ?? "pairing";
2722
2630
  const configAllowFrom = feishuCfg?.allowFrom ?? [];
2723
2631
  const rawBroadcastAgents = isGroup ? resolveBroadcastAgents(cfg, ctx.chatId) : null;
2724
- const broadcastAgents = rawBroadcastAgents ? uniqueStrings(rawBroadcastAgents.map((id) => normalizeAgentId$1(id))) : null;
2632
+ const broadcastAgents = rawBroadcastAgents ? uniqueStrings(rawBroadcastAgents.map(normalizeAgentId$1)) : null;
2725
2633
  const messageCreateTimeMs = parseStrictNonNegativeInteger(event.message.create_time) ?? Date.now();
2726
2634
  let requireMention = false;
2727
2635
  if (isGroup) {
@@ -3009,6 +2917,14 @@ async function handleFeishuMessage(params) {
3009
2917
  channel: "feishu",
3010
2918
  accountId: account.accountId
3011
2919
  });
2920
+ const fetchedContextPolicy = {
2921
+ cfg,
2922
+ accountId: account.accountId,
2923
+ chatId: ctx.chatId,
2924
+ isGroup,
2925
+ allowFrom: effectiveGroupSenderAllowFrom,
2926
+ mode: contextVisibilityMode
2927
+ };
3012
2928
  log(`feishu[${account.accountId}]: ${inboundLabel}: ${preview}`);
3013
2929
  const mediaMaxBytes = (feishuCfg?.mediaMaxMb ?? 30) * 1024 * 1024;
3014
2930
  const mediaList = await resolveFeishuMediaList({
@@ -3033,12 +2949,7 @@ async function handleFeishuMessage(params) {
3033
2949
  accountId: account.accountId
3034
2950
  });
3035
2951
  if (quotedMessageInfo && await shouldIncludeFetchedGroupContextMessage({
3036
- cfg,
3037
- accountId: account.accountId,
3038
- chatId: ctx.chatId,
3039
- isGroup,
3040
- allowFrom: effectiveGroupSenderAllowFrom,
3041
- mode: contextVisibilityMode,
2952
+ ...fetchedContextPolicy,
3042
2953
  kind: "quote",
3043
2954
  senderId: quotedMessageInfo.senderId,
3044
2955
  senderType: quotedMessageInfo.senderType
@@ -3150,7 +3061,7 @@ async function handleFeishuMessage(params) {
3150
3061
  return threadContext;
3151
3062
  }
3152
3063
  const storePath = resolveStorePath(cfg.session?.store, { agentId });
3153
- if (core.channel.session.readSessionUpdatedAt({
3064
+ if (await core.channel.session.readSessionUpdatedAtAsync({
3154
3065
  storePath,
3155
3066
  sessionKey: agentSessionKey
3156
3067
  })) {
@@ -3161,12 +3072,7 @@ async function handleFeishuMessage(params) {
3161
3072
  let rootMsg = await getRootMessageInfo();
3162
3073
  const feishuThreadId = ctx.threadId ?? rootMsg?.threadId;
3163
3074
  if (rootMsg && !await shouldIncludeFetchedGroupContextMessage({
3164
- cfg,
3165
- accountId: account.accountId,
3166
- chatId: ctx.chatId,
3167
- isGroup,
3168
- allowFrom: effectiveGroupSenderAllowFrom,
3169
- mode: contextVisibilityMode,
3075
+ ...fetchedContextPolicy,
3170
3076
  kind: "thread",
3171
3077
  senderId: rootMsg.senderId,
3172
3078
  senderType: rootMsg.senderType
@@ -3190,14 +3096,9 @@ async function handleFeishuMessage(params) {
3190
3096
  accountId: account.accountId
3191
3097
  });
3192
3098
  const senderScoped = groupSession?.groupSessionScope === "group_topic_sender";
3193
- const senderIds = new Set([ctx.senderOpenId, senderUserId].map((id) => id?.trim()).filter((id) => id !== void 0 && id.length > 0));
3099
+ const senderIds = new Set([ctx.senderOpenId, senderUserId].filter((id) => Boolean(id)));
3194
3100
  const allowlistedMessages = await filterFetchedGroupContextMessages(threadMessages, {
3195
- cfg,
3196
- accountId: account.accountId,
3197
- chatId: ctx.chatId,
3198
- isGroup,
3199
- allowFrom: effectiveGroupSenderAllowFrom,
3200
- mode: contextVisibilityMode,
3101
+ ...fetchedContextPolicy,
3201
3102
  kind: "history"
3202
3103
  });
3203
3104
  const relevantMessages = senderScoped ? allowlistedMessages.filter((msg) => msg.senderType === "app" || msg.senderId !== void 0 && senderIds.has(msg.senderId.trim())) : allowlistedMessages;
@@ -3373,6 +3274,22 @@ async function handleFeishuMessage(params) {
3373
3274
  requiredMentionTargets,
3374
3275
  messageCreateTimeMs
3375
3276
  });
3277
+ const runAgentTurn = (ctxPayload, resolveTurn) => core.channel.inbound.run({
3278
+ channel: "feishu",
3279
+ accountId: route.accountId,
3280
+ raw: ctx,
3281
+ adapter: {
3282
+ ingest: () => ({
3283
+ id: ctx.messageId,
3284
+ timestamp: messageCreateTimeMs,
3285
+ rawText: ctx.content,
3286
+ textForAgent: ctxPayload.BodyForAgent,
3287
+ textForCommands: ctxPayload.CommandBody,
3288
+ raw: ctx
3289
+ }),
3290
+ resolveTurn
3291
+ }
3292
+ });
3376
3293
  if (broadcastAgents) {
3377
3294
  const broadcastDedupeKey = messageDedupeKey ?? ctx.messageId;
3378
3295
  const broadcastClaim = await claimUnprocessedFeishuMessage({
@@ -3405,12 +3322,11 @@ async function handleFeishuMessage(params) {
3405
3322
  };
3406
3323
  const strategy = cfg.broadcast?.strategy === "sequential" ? "sequential" : "parallel";
3407
3324
  const activeAgentId = ctx.mentionedBot || !requireMention ? normalizeAgentId$1(route.agentId) : null;
3408
- const agentIds = Object.keys(cfg.agents?.entries ?? {}).map((id) => normalizeAgentId$1(id));
3325
+ const agentIds = Object.keys(cfg.agents?.entries ?? {}).map(normalizeAgentId$1);
3409
3326
  const hasKnownAgents = agentIds.length > 0;
3410
3327
  log(`feishu[${account.accountId}]: broadcasting to ${broadcastAgents.length} agents (strategy=${strategy}, active=${activeAgentId ?? "none"})`);
3411
3328
  const dispatchForAgent = async (agentId) => {
3412
- const normalizedAgentId = normalizeAgentId$1(agentId);
3413
- if (hasKnownAgents && !agentIds.includes(normalizedAgentId)) {
3329
+ if (hasKnownAgents && !agentIds.includes(agentId)) {
3414
3330
  log(`feishu[${account.accountId}]: broadcast agent ${agentId} not found in agents.entries; skipping`);
3415
3331
  return;
3416
3332
  }
@@ -3418,7 +3334,7 @@ async function handleFeishuMessage(params) {
3418
3334
  for (let attempt = 0; attempt < 2; attempt += 1) {
3419
3335
  agentClaim = await claimUnprocessedFeishuMessage({
3420
3336
  messageId: broadcastDedupeKey,
3421
- namespace: `broadcast:${normalizedAgentId}`,
3337
+ namespace: `broadcast:${agentId}`,
3422
3338
  log
3423
3339
  });
3424
3340
  if (agentClaim.kind === "duplicate") return;
@@ -3451,67 +3367,42 @@ async function handleFeishuMessage(params) {
3451
3367
  sessionKey: agentSessionKey
3452
3368
  });
3453
3369
  const agentCtx = await buildCtxPayloadForAgent(agentId, agentSessionKey, route.accountId, ctx.mentionedBot && agentId === activeAgentId);
3454
- let variant;
3455
- if (agentId === activeAgentId) {
3456
- const identity = resolveAgentOutboundIdentity(cfg, agentId);
3457
- variant = {
3458
- kind: "active",
3459
- dispatcher: createAgentReplyDispatcher({
3460
- cfg,
3461
- agentId,
3462
- allowReasoningPreview,
3463
- identity,
3464
- sessionKey: agentSessionKey
3465
- })
3466
- };
3467
- log(`feishu[${account.accountId}]: broadcast active dispatch agent=${agentId} (session=${agentSessionKey})`);
3468
- } else {
3469
- delete agentCtx.CommandAuthorized;
3470
- variant = { kind: "observeOnly" };
3471
- log(`feishu[${account.accountId}]: broadcast observer dispatch agent=${agentId} (session=${agentSessionKey})`);
3472
- }
3473
- const turnResult = await core.channel.inbound.run({
3370
+ const dispatcher = agentId === activeAgentId ? createAgentReplyDispatcher({
3371
+ cfg,
3372
+ agentId,
3373
+ allowReasoningPreview,
3374
+ identity: resolveAgentOutboundIdentity(cfg, agentId),
3375
+ sessionKey: agentSessionKey
3376
+ }) : void 0;
3377
+ if (!dispatcher) delete agentCtx.CommandAuthorized;
3378
+ log(`feishu[${account.accountId}]: broadcast ${dispatcher ? "active" : "observer"} dispatch agent=${agentId} (session=${agentSessionKey})`);
3379
+ const turnResult = await runAgentTurn(agentCtx, () => ({
3380
+ cfg,
3474
3381
  channel: "feishu",
3475
3382
  accountId: route.accountId,
3476
- raw: ctx,
3477
- adapter: {
3478
- ingest: () => ({
3479
- id: ctx.messageId,
3480
- timestamp: messageCreateTimeMs,
3481
- rawText: ctx.content,
3482
- textForAgent: agentCtx.BodyForAgent,
3483
- textForCommands: agentCtx.CommandBody,
3484
- raw: ctx
3485
- }),
3486
- resolveTurn: () => ({
3487
- cfg,
3488
- channel: "feishu",
3489
- accountId: route.accountId,
3490
- route: {
3491
- agentId,
3492
- sessionKey: agentSessionKey
3493
- },
3494
- ctxPayload: agentCtx,
3495
- record: agentRecord,
3496
- ...variant.kind === "observeOnly" ? {
3497
- admission: {
3498
- kind: "observeOnly",
3499
- reason: "broadcast-observer"
3500
- },
3501
- delivery: { deliver: async () => ({ visibleReplySent: false }) },
3502
- replyOptions: bindIngressLifecycleToReplyOptions(lane.lifecycle)
3503
- } : {
3504
- dispatcherOptions: variant.dispatcher.dispatcherOptions,
3505
- delivery: variant.dispatcher.delivery,
3506
- replyOptions: {
3507
- ...variant.dispatcher.replyOptions,
3508
- ...bindIngressLifecycleToReplyOptions(lane.lifecycle)
3509
- }
3510
- }
3511
- })
3383
+ route: {
3384
+ agentId,
3385
+ sessionKey: agentSessionKey
3386
+ },
3387
+ ctxPayload: agentCtx,
3388
+ record: agentRecord,
3389
+ ...!dispatcher ? {
3390
+ admission: {
3391
+ kind: "observeOnly",
3392
+ reason: "broadcast-observer"
3393
+ },
3394
+ delivery: { deliver: async () => ({ visibleReplySent: false }) },
3395
+ replyOptions: bindIngressLifecycleToReplyOptions(lane.lifecycle)
3396
+ } : {
3397
+ dispatcherOptions: dispatcher.dispatcherOptions,
3398
+ delivery: dispatcher.delivery,
3399
+ replyOptions: {
3400
+ ...dispatcher.replyOptions,
3401
+ ...bindIngressLifecycleToReplyOptions(lane.lifecycle)
3402
+ }
3512
3403
  }
3513
- });
3514
- if (variant.kind === "active" && turnResult.dispatched && shouldSendNoVisibleReplyFallback(turnResult.dispatchResult)) await variant.dispatcher.ensureNoVisibleReplyFallback("broadcast-dispatch-complete-no-visible-reply");
3404
+ }));
3405
+ if (dispatcher && turnResult.dispatched && shouldSendNoVisibleReplyFallback(turnResult.dispatchResult)) await dispatcher.ensureNoVisibleReplyFallback("broadcast-dispatch-complete-no-visible-reply");
3515
3406
  await lane.onDispatchComplete(turnResult.dispatched);
3516
3407
  } catch (err) {
3517
3408
  await lane.onDispatchFailed(err);
@@ -3569,52 +3460,37 @@ async function handleFeishuMessage(params) {
3569
3460
  sessionKey: route.sessionKey
3570
3461
  });
3571
3462
  log(`feishu[${account.accountId}]: dispatching to agent (session=${route.sessionKey})`);
3572
- const turnResult = await core.channel.inbound.run({
3463
+ const turnResult = await runAgentTurn(ctxPayload, () => ({
3464
+ cfg: effectiveCfg,
3573
3465
  channel: "feishu",
3574
3466
  accountId: route.accountId,
3575
- raw: ctx,
3576
- adapter: {
3577
- ingest: () => ({
3578
- id: ctx.messageId,
3579
- timestamp: messageCreateTimeMs,
3580
- rawText: ctx.content,
3581
- textForAgent: ctxPayload.BodyForAgent,
3582
- textForCommands: ctxPayload.CommandBody,
3583
- raw: ctx
3467
+ route: {
3468
+ agentId: route.agentId,
3469
+ sessionKey: route.sessionKey
3470
+ },
3471
+ ctxPayload,
3472
+ record: {
3473
+ updateLastRoute: buildFeishuInboundLastRouteUpdate({
3474
+ sessionKey: route.sessionKey,
3475
+ accountId: route.accountId
3584
3476
  }),
3585
- resolveTurn: () => ({
3586
- cfg: effectiveCfg,
3587
- channel: "feishu",
3588
- accountId: route.accountId,
3589
- route: {
3590
- agentId: route.agentId,
3591
- sessionKey: route.sessionKey
3592
- },
3593
- ctxPayload,
3594
- record: {
3595
- updateLastRoute: buildFeishuInboundLastRouteUpdate({
3596
- sessionKey: route.sessionKey,
3597
- accountId: route.accountId
3598
- }),
3599
- onRecordError: (err) => {
3600
- log(`feishu[${account.accountId}]: failed to record inbound session ${route.sessionKey}: ${String(err)}`);
3601
- }
3602
- },
3603
- history: {
3604
- isGroup,
3605
- historyKey,
3606
- historyMap: chatHistories,
3607
- limit: historyLimit
3608
- },
3609
- dispatcherOptions,
3610
- delivery,
3611
- replyOptions: {
3612
- ...replyOptions,
3613
- ...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {}
3614
- }
3615
- })
3477
+ onRecordError: (err) => {
3478
+ log(`feishu[${account.accountId}]: failed to record inbound session ${route.sessionKey}: ${String(err)}`);
3479
+ }
3480
+ },
3481
+ history: {
3482
+ isGroup,
3483
+ historyKey,
3484
+ historyMap: chatHistories,
3485
+ limit: historyLimit
3486
+ },
3487
+ dispatcherOptions,
3488
+ delivery,
3489
+ replyOptions: {
3490
+ ...replyOptions,
3491
+ ...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {}
3616
3492
  }
3617
- });
3493
+ }));
3618
3494
  if (!turnResult.dispatched) return;
3619
3495
  const { dispatchResult } = turnResult;
3620
3496
  const { queuedFinal, counts } = dispatchResult;
@@ -3720,17 +3596,11 @@ function beginFeishuCardActionToken(params) {
3720
3596
  const normalizedToken = params.token.trim();
3721
3597
  if (!normalizedToken) return false;
3722
3598
  const key = `${params.accountId}:${normalizedToken}`;
3723
- const existing = processedCardActions.get(key);
3724
- if (existing && isFutureDateTimestampMs(existing.expiresAt, { nowMs: now })) return false;
3725
- processedCardActions.delete(key);
3726
- const expiresAt = resolveExpiresAtMsFromDurationMs(FEISHU_CARD_ACTION_TOKEN_TTL_MS, { nowMs: now });
3727
- if (expiresAt !== void 0) processedCardActions.set(key, {
3728
- status: "inflight",
3729
- expiresAt
3730
- });
3599
+ if (processedCardActions.has(key)) return false;
3600
+ refreshFeishuCardActionToken(normalizedToken, params.accountId, now);
3731
3601
  return true;
3732
3602
  }
3733
- function completeFeishuCardAction(actionId, accountId, now = Date.now()) {
3603
+ function refreshFeishuCardActionToken(actionId, accountId, now = Date.now()) {
3734
3604
  const normalizedActionId = actionId.trim();
3735
3605
  if (!normalizedActionId) return;
3736
3606
  const key = `${accountId}:${normalizedActionId}`;
@@ -3739,12 +3609,9 @@ function completeFeishuCardAction(actionId, accountId, now = Date.now()) {
3739
3609
  processedCardActions.delete(key);
3740
3610
  return;
3741
3611
  }
3742
- processedCardActions.set(key, {
3743
- status: "completed",
3744
- expiresAt
3745
- });
3612
+ processedCardActions.set(key, { expiresAt });
3746
3613
  }
3747
- function buildSyntheticMessageEvent$1(event, content, chatType, botOpenId) {
3614
+ function buildSyntheticMessageEvent(event, content, chatType, botOpenId) {
3748
3615
  const replyTargetMessageId = event.context.open_message_id ?? event.open_message_id;
3749
3616
  const isTemporaryCardActionId = replyTargetMessageId?.startsWith("card-action-c-");
3750
3617
  const validReplyTargetId = replyTargetMessageId && !isTemporaryCardActionId ? replyTargetMessageId : void 0;
@@ -3787,7 +3654,7 @@ async function dispatchSyntheticCommand(params) {
3787
3654
  await handleFeishuMessage({
3788
3655
  trackTask: params.trackTask,
3789
3656
  cfg: params.cfg,
3790
- event: buildSyntheticMessageEvent$1(params.event, params.command, resolvedChatType, params.botOpenId),
3657
+ event: buildSyntheticMessageEvent(params.event, params.command, resolvedChatType, params.botOpenId),
3791
3658
  botOpenId: params.botOpenId,
3792
3659
  runtime: params.runtime,
3793
3660
  channelRuntime: params.channelRuntime,
@@ -3939,7 +3806,7 @@ async function handleFeishuCardAction(params) {
3939
3806
  account
3940
3807
  });
3941
3808
  } finally {
3942
- completeFeishuCardAction(event.token, account.accountId);
3809
+ refreshFeishuCardActionToken(event.token, account.accountId);
3943
3810
  }
3944
3811
  }
3945
3812
  //#endregion
@@ -4417,26 +4284,6 @@ function isFeishuRetryableSyntheticEventError(error) {
4417
4284
  }
4418
4285
  //#endregion
4419
4286
  //#region extensions/feishu/src/monitor.bot-menu-handler.ts
4420
- function readStringOrNumber(value) {
4421
- return typeof value === "string" || typeof value === "number" ? value : void 0;
4422
- }
4423
- function parseFeishuBotMenuEvent(value) {
4424
- if (!isRecord(value)) return null;
4425
- const operator = value.operator;
4426
- if (operator !== void 0 && !isRecord(operator)) return null;
4427
- return {
4428
- event_key: readStringValue(value.event_key),
4429
- timestamp: readStringOrNumber(value.timestamp),
4430
- operator: operator ? {
4431
- operator_name: readStringValue(operator.operator_name),
4432
- operator_id: isRecord(operator.operator_id) ? {
4433
- open_id: readStringValue(operator.operator_id.open_id),
4434
- user_id: readStringValue(operator.operator_id.user_id),
4435
- union_id: readStringValue(operator.operator_id.union_id)
4436
- } : void 0
4437
- } : void 0
4438
- };
4439
- }
4440
4287
  function createFeishuBotMenuHandler(params) {
4441
4288
  const { cfg, accountId, runtime, chatHistories, fireAndForget } = params;
4442
4289
  const log = runtime?.log ?? console.log;
@@ -4446,22 +4293,22 @@ function createFeishuBotMenuHandler(params) {
4446
4293
  const handle = async (data) => {
4447
4294
  try {
4448
4295
  if (!isActive()) return;
4449
- const event = parseFeishuBotMenuEvent(data);
4450
- if (!event) return;
4451
- const operatorOpenId = event.operator?.operator_id?.open_id?.trim();
4452
- const eventKey = event.event_key?.trim();
4296
+ if (!isRecord(data) || !isRecord(data.operator) || !isRecord(data.operator.operator_id)) return;
4297
+ const operatorId = data.operator.operator_id;
4298
+ const operatorOpenId = readStringValue(operatorId.open_id)?.trim();
4299
+ const eventKey = readStringValue(data.event_key)?.trim();
4453
4300
  if (!operatorOpenId || !eventKey) return;
4454
4301
  const syntheticEvent = {
4455
4302
  sender: {
4456
4303
  sender_id: {
4457
4304
  open_id: operatorOpenId,
4458
- user_id: event.operator?.operator_id?.user_id,
4459
- union_id: event.operator?.operator_id?.union_id
4305
+ user_id: readStringValue(operatorId.user_id),
4306
+ union_id: readStringValue(operatorId.union_id)
4460
4307
  },
4461
4308
  sender_type: "user"
4462
4309
  },
4463
4310
  message: {
4464
- message_id: `bot-menu:${eventKey}:${event.timestamp ?? Date.now()}`,
4311
+ message_id: `bot-menu:${eventKey}:${typeof data.timestamp === "string" || typeof data.timestamp === "number" ? data.timestamp : Date.now()}`,
4465
4312
  suppress_reply_target: true,
4466
4313
  chat_id: `p2p:${operatorOpenId}`,
4467
4314
  chat_type: "p2p",
@@ -4513,7 +4360,7 @@ function createFeishuBotMenuHandler(params) {
4513
4360
  if (claim.kind === "claimed") claim.handle.release({ error: /* @__PURE__ */ new Error("feishu account stopped before menu dispatch") });
4514
4361
  return;
4515
4362
  }
4516
- return await handleLegacyMenu();
4363
+ return handleLegacyMenu();
4517
4364
  }).catch(async (err) => {
4518
4365
  if (isFeishuRetryableSyntheticEventError(err)) {
4519
4366
  await forgetProcessedFeishuMessage(syntheticMessageId, accountId, log);
@@ -4628,13 +4475,6 @@ const FEISHU_COMMENT_REPLY_MISS_RETRY_LIMIT = 6;
4628
4475
  const FEISHU_COMMENT_THREAD_PROMPT_LIMIT = 20;
4629
4476
  const FEISHU_WHOLE_COMMENT_PROMPT_LIMIT = 12;
4630
4477
  const FEISHU_PROMPT_TEXT_LIMIT = 220;
4631
- function safeJsonStringify(value) {
4632
- try {
4633
- return JSON.stringify(value);
4634
- } catch (error) {
4635
- return JSON.stringify({ error: formatErrorMessage(error) });
4636
- }
4637
- }
4638
4478
  function truncatePromptText(text, maxLength = FEISHU_PROMPT_TEXT_LIMIT) {
4639
4479
  const normalized = normalizeOptionalString(text);
4640
4480
  if (!normalized) return "";
@@ -4643,11 +4483,11 @@ function truncatePromptText(text, maxLength = FEISHU_PROMPT_TEXT_LIMIT) {
4643
4483
  function formatPromptTextValue(text) {
4644
4484
  return JSON.stringify(truncatePromptText(text));
4645
4485
  }
4646
- function compareCommentTimelineEntries(left, right) {
4486
+ function compareCommentTimelineEntries(left, right, stableId) {
4647
4487
  const leftTime = left.createTime ?? Number.MAX_SAFE_INTEGER;
4648
4488
  const rightTime = right.createTime ?? Number.MAX_SAFE_INTEGER;
4649
4489
  if (leftTime !== rightTime) return leftTime - rightTime;
4650
- return (left.stableId ?? "").localeCompare(right.stableId ?? "");
4490
+ return (stableId(left) ?? "").localeCompare(stableId(right) ?? "");
4651
4491
  }
4652
4492
  function formatLinkedDocumentInline(link) {
4653
4493
  return [
@@ -4668,7 +4508,7 @@ function formatLinkedDocumentsInlineSummary(linkedDocuments) {
4668
4508
  return linkedDocuments.map((link) => `${link.resolvedObjType ?? link.urlKind}:${link.resolvedObjToken ?? link.wikiNodeToken ?? "UNKNOWN"}`).join(",");
4669
4509
  }
4670
4510
  function summarizeCommentRepliesForLog(replies) {
4671
- return safeJsonStringify(replies.map((reply) => ({
4511
+ return JSON.stringify(replies.map((reply) => ({
4672
4512
  reply_id: reply.reply_id,
4673
4513
  text_len: extractReplyText(reply)?.length ?? 0
4674
4514
  })));
@@ -4716,56 +4556,35 @@ async function resolveParsedCommentContent(params) {
4716
4556
  linkedDocuments: resolvedLinkedDocuments
4717
4557
  };
4718
4558
  }
4719
- function fetchDriveComments(params) {
4720
- const errorLabel = `feishu[${params.accountId}]: failed to list drive comments for ${params.fileToken}`;
4721
- return fetchDriveCommentPages({
4722
- logger: params.logger,
4723
- errorLabel,
4724
- fetchPage: (pageToken) => requestFeishuOpenApi({
4725
- client: params.client,
4726
- method: "GET",
4727
- url: `/open-apis/drive/v1/files/${encodeURIComponent(params.fileToken)}/comments` + encodeQuery({
4728
- file_type: params.fileType,
4729
- is_whole: params.isWholeOnly === true ? "true" : void 0,
4730
- page_size: String(FEISHU_COMMENT_PAGE_SIZE),
4731
- page_token: pageToken,
4732
- user_id_type: "open_id"
4733
- }),
4734
- timeoutMs: params.timeoutMs,
4735
- logger: params.logger,
4736
- errorLabel
4737
- })
4738
- });
4739
- }
4740
- function fetchDriveCommentReplies(params) {
4741
- const errorLabel = `feishu[${params.accountId}]: failed to fetch comment replies for ${params.commentId}`;
4742
- return fetchDriveCommentPages({
4743
- logger: params.logger,
4744
- errorLabel,
4745
- fetchPage: (pageToken) => requestFeishuOpenApi({
4746
- client: params.client,
4747
- method: "GET",
4748
- url: `/open-apis/drive/v1/files/${encodeURIComponent(params.fileToken)}/comments/${encodeURIComponent(params.commentId)}/replies` + encodeQuery({
4749
- file_type: params.fileType,
4750
- page_token: pageToken,
4751
- page_size: String(FEISHU_COMMENT_PAGE_SIZE),
4752
- user_id_type: "open_id"
4753
- }),
4754
- timeoutMs: params.timeoutMs,
4755
- logger: params.logger,
4756
- errorLabel
4757
- })
4758
- });
4759
- }
4760
4559
  async function fetchDriveCommentPages(params) {
4560
+ const errorLabel = params.kind === "whole-comments" ? `feishu[${params.accountId}]: failed to list drive comments for ${params.fileToken}` : `feishu[${params.accountId}]: failed to fetch comment replies for ${params.commentId}`;
4761
4561
  const items = [];
4762
4562
  const logIds = [];
4763
4563
  let pageToken;
4764
4564
  for (let page = 0; page < FEISHU_COMMENT_PAGE_LIMIT; page += 1) {
4765
- const response = await params.fetchPage(pageToken);
4565
+ const commentsUrl = `/open-apis/drive/v1/files/${encodeURIComponent(params.fileToken)}/comments`;
4566
+ const url = params.kind === "whole-comments" ? commentsUrl : `${commentsUrl}/${encodeURIComponent(params.commentId)}/replies`;
4567
+ const query = {
4568
+ file_type: params.fileType,
4569
+ ...params.kind === "whole-comments" ? {
4570
+ is_whole: "true",
4571
+ page_size: String(FEISHU_COMMENT_PAGE_SIZE),
4572
+ page_token: pageToken
4573
+ } : {
4574
+ page_token: pageToken,
4575
+ page_size: String(FEISHU_COMMENT_PAGE_SIZE)
4576
+ },
4577
+ user_id_type: "open_id"
4578
+ };
4579
+ const response = await requestFeishuOpenApi({
4580
+ ...params,
4581
+ method: "GET",
4582
+ url: url + encodeQuery(query),
4583
+ errorLabel
4584
+ });
4766
4585
  if (response?.log_id?.trim()) logIds.push(response.log_id.trim());
4767
4586
  if (response?.code !== 0) {
4768
- if (response) params.logger?.(`${params.errorLabel}: ${response.msg ?? "unknown error"} log_id=${response.log_id?.trim() || "unknown"}`);
4587
+ if (response) params.logger?.(`${errorLabel}: ${response.msg ?? "unknown error"} log_id=${response.log_id?.trim() || "unknown"}`);
4769
4588
  break;
4770
4589
  }
4771
4590
  items.push(...response.data?.items ?? []);
@@ -4782,7 +4601,7 @@ async function requestFeishuOpenApi(params) {
4782
4601
  if (!isRecord(error)) return typeof error === "string" ? error : JSON.stringify(error);
4783
4602
  const response = isRecord(error.response) ? error.response : void 0;
4784
4603
  const responseData = isRecord(response?.data) ? response?.data : void 0;
4785
- return safeJsonStringify({
4604
+ const details = {
4786
4605
  message: typeof error.message === "string" ? error.message : JSON.stringify(error),
4787
4606
  code: readStringValue(error.code),
4788
4607
  method: readStringValue(isRecord(error.config) ? error.config.method : void 0),
@@ -4791,7 +4610,8 @@ async function requestFeishuOpenApi(params) {
4791
4610
  feishu_code: typeof responseData?.code === "number" ? responseData.code : readStringValue(responseData?.code),
4792
4611
  feishu_msg: readStringValue(responseData?.msg),
4793
4612
  feishu_log_id: readStringValue(responseData?.log_id)
4794
- });
4613
+ };
4614
+ return JSON.stringify(details);
4795
4615
  };
4796
4616
  const result = await raceWithTimeoutAndAbort(params.client.request({
4797
4617
  method: params.method,
@@ -4805,20 +4625,6 @@ async function requestFeishuOpenApi(params) {
4805
4625
  if (!result) params.logger?.(`${params.errorLabel}: request timed out or returned no data`);
4806
4626
  return result;
4807
4627
  }
4808
- async function resolveCommentReplyContext(params) {
4809
- const userId = normalizeOptionalString(params.reply.user_id);
4810
- const normalizedBotOpenIds = new Set(normalizeTrimmedStringList(Array.from(params.botOpenIds ?? [])));
4811
- return {
4812
- replyId: normalizeOptionalString(params.reply.reply_id),
4813
- userId,
4814
- createTime: typeof params.reply.create_time === "number" ? params.reply.create_time : void 0,
4815
- isBotAuthored: typeof userId === "string" && normalizedBotOpenIds.has(userId),
4816
- content: await resolveParsedCommentContent({
4817
- ...params,
4818
- elements: isRecord(params.reply.content) ? params.reply.content.elements : void 0
4819
- })
4820
- };
4821
- }
4822
4628
  function selectCommentThreadPromptReplies(replies, targetReplyId) {
4823
4629
  if (replies.length <= FEISHU_COMMENT_THREAD_PROMPT_LIMIT) return replies;
4824
4630
  const targetIndex = replies.findIndex((reply) => reply.replyId === targetReplyId);
@@ -4903,24 +4709,30 @@ async function fetchDriveCommentContext(params) {
4903
4709
  const commentCard = commentResponse?.code === 0 ? (commentResponse.data?.items ?? []).find((item) => item.comment_id?.trim() === params.commentId) : void 0;
4904
4710
  const embeddedReplies = commentCard?.reply_list?.replies ?? [];
4905
4711
  params.logger?.(`feishu[${params.accountId}]: embedded comment replies comment=${params.commentId} count=${embeddedReplies.length} summary=${summarizeCommentRepliesForLog(embeddedReplies)}`);
4906
- const embeddedTargetReply = params.replyId ? embeddedReplies.find((reply) => reply.reply_id?.trim() === params.replyId?.trim()) : embeddedReplies.at(-1);
4712
+ const embeddedTargetReply = params.replyId ? embeddedReplies.find((reply) => reply.reply_id?.trim() === params.replyId) : embeddedReplies.at(-1);
4907
4713
  let replies = embeddedReplies;
4908
- let fetchedMatchedReply = params.replyId ? replies.find((reply) => reply.reply_id?.trim() === params.replyId?.trim()) : void 0;
4909
- if (!embeddedTargetReply || replies.length === 0 || commentCard?.has_more === true) {
4714
+ let fetchedMatchedReply = params.replyId ? embeddedTargetReply : void 0;
4715
+ if (!embeddedTargetReply || commentCard?.has_more === true) {
4910
4716
  params.logger?.(`feishu[${params.accountId}]: fetching extra comment replies comment=${params.commentId} requested_reply=${params.replyId ?? "none"} embedded_count=${embeddedReplies.length} embedded_hit=${embeddedTargetReply ? "yes" : "no"} embedded_has_more=${commentCard?.has_more === true ? "yes" : "no"}`);
4911
- const fetched = await fetchDriveCommentReplies(params);
4717
+ const fetched = await fetchDriveCommentPages({
4718
+ ...params,
4719
+ kind: "replies"
4720
+ });
4912
4721
  if (fetched.items.length > 0) {
4913
- params.logger?.(`feishu[${params.accountId}]: fetched extra comment replies comment=${params.commentId} count=${fetched.items.length} log_ids=${safeJsonStringify(fetched.logIds)} summary=${summarizeCommentRepliesForLog(fetched.items)}`);
4722
+ params.logger?.(`feishu[${params.accountId}]: fetched extra comment replies comment=${params.commentId} count=${fetched.items.length} log_ids=${JSON.stringify(fetched.logIds)} summary=${summarizeCommentRepliesForLog(fetched.items)}`);
4914
4723
  replies = fetched.items;
4915
- fetchedMatchedReply = params.replyId ? replies.find((reply) => reply.reply_id?.trim() === params.replyId?.trim()) : void 0;
4724
+ fetchedMatchedReply = params.replyId ? replies.find((reply) => reply.reply_id?.trim() === params.replyId) : void 0;
4916
4725
  }
4917
4726
  if (params.replyId && !embeddedTargetReply && !fetchedMatchedReply) for (let attempt = 1; attempt <= FEISHU_COMMENT_REPLY_MISS_RETRY_LIMIT; attempt += 1) {
4918
4727
  if (params.abortSignal?.aborted) break;
4919
4728
  params.logger?.(`feishu[${params.accountId}]: retrying comment reply lookup comment=${params.commentId} requested_reply=${params.replyId} attempt=${attempt}/${FEISHU_COMMENT_REPLY_MISS_RETRY_LIMIT} delay_ms=${FEISHU_COMMENT_REPLY_MISS_RETRY_DELAY_MS}`);
4920
4729
  if (!await waitForAbortableDelay(FEISHU_COMMENT_REPLY_MISS_RETRY_DELAY_MS, params.abortSignal)) break;
4921
- const retried = await fetchDriveCommentReplies(params);
4730
+ const retried = await fetchDriveCommentPages({
4731
+ ...params,
4732
+ kind: "replies"
4733
+ });
4922
4734
  if (retried.items.length > 0) {
4923
- params.logger?.(`feishu[${params.accountId}]: fetched retried comment replies comment=${params.commentId} attempt=${attempt} count=${retried.items.length} log_ids=${safeJsonStringify(retried.logIds)} summary=${summarizeCommentRepliesForLog(retried.items)}`);
4735
+ params.logger?.(`feishu[${params.accountId}]: fetched retried comment replies comment=${params.commentId} attempt=${attempt} count=${retried.items.length} log_ids=${JSON.stringify(retried.logIds)} summary=${summarizeCommentRepliesForLog(retried.items)}`);
4924
4736
  replies = retried.items;
4925
4737
  }
4926
4738
  fetchedMatchedReply = replies.find((reply) => reply.reply_id?.trim() === params.replyId);
@@ -4928,12 +4740,12 @@ async function fetchDriveCommentContext(params) {
4928
4740
  }
4929
4741
  }
4930
4742
  const rootReply = replies[0] ?? embeddedReplies[0];
4931
- const targetReply = params.replyId ? embeddedTargetReply ?? fetchedMatchedReply ?? void 0 : replies.at(-1) ?? embeddedTargetReply ?? rootReply;
4743
+ const targetReply = params.replyId ? embeddedTargetReply ?? fetchedMatchedReply : replies.at(-1) ?? embeddedTargetReply ?? rootReply;
4932
4744
  const matchSource = params.replyId ? embeddedTargetReply ? "embedded" : fetchedMatchedReply ? "fetched" : "miss" : targetReply === rootReply ? "fallback_root" : targetReply === embeddedTargetReply ? "embedded_latest" : "fetched_latest";
4933
- params.logger?.(`feishu[${params.accountId}]: comment reply resolution comment=${params.commentId} requested_reply=${params.replyId ?? "none"} match_source=${matchSource} root=${safeJsonStringify({
4745
+ params.logger?.(`feishu[${params.accountId}]: comment reply resolution comment=${params.commentId} requested_reply=${params.replyId ?? "none"} match_source=${matchSource} root=${JSON.stringify({
4934
4746
  reply_id: rootReply?.reply_id,
4935
4747
  text_len: extractReplyText(rootReply)?.length ?? 0
4936
- })} target=${safeJsonStringify({
4748
+ })} target=${JSON.stringify({
4937
4749
  reply_id: targetReply?.reply_id,
4938
4750
  text_len: extractReplyText(targetReply)?.length ?? 0
4939
4751
  })}`);
@@ -4950,28 +4762,31 @@ async function fetchDriveCommentContext(params) {
4950
4762
  logger: params.logger,
4951
4763
  accountId: params.accountId
4952
4764
  };
4953
- const resolvedReplies = await Promise.all(replies.map((reply) => resolveCommentReplyContext({
4954
- ...contentContext,
4955
- reply
4956
- })));
4957
- resolvedReplies.sort((left, right) => compareCommentTimelineEntries({
4958
- createTime: left.createTime,
4959
- stableId: left.replyId
4960
- }, {
4961
- createTime: right.createTime,
4962
- stableId: right.replyId
4765
+ const normalizedBotOpenIds = new Set(normalizeTrimmedStringList(Array.from(params.botOpenIds ?? [])));
4766
+ const resolvedReplies = await Promise.all(replies.map(async (reply) => {
4767
+ const userId = normalizeOptionalString(reply.user_id);
4768
+ return {
4769
+ replyId: normalizeOptionalString(reply.reply_id),
4770
+ userId,
4771
+ createTime: typeof reply.create_time === "number" ? reply.create_time : void 0,
4772
+ isBotAuthored: userId !== void 0 && normalizedBotOpenIds.has(userId),
4773
+ content: await resolveParsedCommentContent({
4774
+ ...contentContext,
4775
+ elements: isRecord(reply.content) ? reply.content.elements : void 0
4776
+ })
4777
+ };
4963
4778
  }));
4779
+ resolvedReplies.sort((left, right) => compareCommentTimelineEntries(left, right, (reply) => reply.replyId));
4964
4780
  const rootReplyContext = resolvedReplies.find((reply) => reply.replyId === normalizeOptionalString(rootReply?.reply_id)) ?? resolvedReplies[0];
4965
4781
  const targetReplyContext = resolvedReplies.find((reply) => reply.replyId === normalizeOptionalString(targetReply?.reply_id)) ?? (params.replyId ? void 0 : resolvedReplies.at(-1) ?? rootReplyContext);
4966
4782
  let wholeCommentTimeline = [];
4967
4783
  if (commentCard?.is_whole === true) {
4968
- const wholeComments = (await fetchDriveComments({
4784
+ const wholeComments = (await fetchDriveCommentPages({
4969
4785
  ...params,
4970
- isWholeOnly: true
4786
+ kind: "whole-comments"
4971
4787
  })).items.filter((comment) => comment.is_whole === true);
4972
4788
  wholeCommentTimeline = await Promise.all(wholeComments.map(async (comment) => {
4973
4789
  const rootWholeReply = comment.reply_list?.replies?.[0];
4974
- const normalizedBotOpenIds = new Set(normalizeTrimmedStringList(Array.from(params.botOpenIds ?? [])));
4975
4790
  const content = await resolveParsedCommentContent({
4976
4791
  ...contentContext,
4977
4792
  elements: isRecord(rootWholeReply?.content) ? rootWholeReply.content.elements : void 0
@@ -4981,17 +4796,11 @@ async function fetchDriveCommentContext(params) {
4981
4796
  commentId: normalizeOptionalString(comment.comment_id) ?? "",
4982
4797
  userId: commentUserId,
4983
4798
  createTime: typeof comment.create_time === "number" ? comment.create_time : typeof rootWholeReply?.create_time === "number" ? rootWholeReply.create_time : void 0,
4984
- isBotAuthored: typeof commentUserId === "string" && normalizedBotOpenIds.has(commentUserId),
4799
+ isBotAuthored: commentUserId !== void 0 && normalizedBotOpenIds.has(commentUserId),
4985
4800
  content
4986
4801
  };
4987
4802
  }));
4988
- wholeCommentTimeline = wholeCommentTimeline.filter((entry) => Boolean(entry.commentId)).toSorted((left, right) => compareCommentTimelineEntries({
4989
- createTime: left.createTime,
4990
- stableId: left.commentId
4991
- }, {
4992
- createTime: right.createTime,
4993
- stableId: right.commentId
4994
- }));
4803
+ wholeCommentTimeline = wholeCommentTimeline.filter((entry) => Boolean(entry.commentId)).toSorted((left, right) => compareCommentTimelineEntries(left, right, (entry) => entry.commentId));
4995
4804
  }
4996
4805
  const currentWholeCommentIndex = wholeCommentTimeline.findIndex((entry) => entry.commentId === params.commentId);
4997
4806
  return {
@@ -5030,7 +4839,7 @@ function buildDriveCommentSurfacePrompt(params) {
5030
4839
  if (params.documentUrl) lines.push(`- url=${params.documentUrl}`);
5031
4840
  lines.push(`Event type: ${params.noticeType}`, `file_token: ${params.fileToken}`, `file_type: ${params.fileType}`, `comment_id: ${params.commentId}`);
5032
4841
  if (params.isWholeComment === true) lines.push("This is a whole-document comment.");
5033
- if (params.replyId?.trim()) lines.push(`reply_id: ${params.replyId.trim()}`);
4842
+ if (params.replyId) lines.push(`reply_id: ${params.replyId}`);
5034
4843
  if (params.targetReplyContent?.semanticText) lines.push(`Current user comment semantic text: ${formatPromptTextValue(params.targetReplyContent.semanticText)}`);
5035
4844
  if (params.targetReplyContent?.botMentioned) lines.push("Bot routing mention detected in the current user comment. Treat that mention as routing only, not task content.");
5036
4845
  const nonBotMentions = (params.targetReplyContent?.mentions ?? []).filter((mention) => !mention.isBotMention).map((mention) => mention.displayText);
@@ -5048,8 +4857,7 @@ function buildDriveCommentSurfacePrompt(params) {
5048
4857
  entries: params.wholeCommentTimeline,
5049
4858
  currentCommentId: params.commentId
5050
4859
  }));
5051
- if (params.nearestBotWholeCommentAfter) lines.push(`Nearest bot-authored whole-comment after the current comment: comment_id=${params.nearestBotWholeCommentAfter.commentId} text=${formatPromptTextValue(params.nearestBotWholeCommentAfter.content.semanticText ?? params.nearestBotWholeCommentAfter.content.plainText)}`);
5052
- if (params.nearestBotWholeCommentBefore) lines.push(`Nearest bot-authored whole-comment before the current comment: comment_id=${params.nearestBotWholeCommentBefore.commentId} text=${formatPromptTextValue(params.nearestBotWholeCommentBefore.content.semanticText ?? params.nearestBotWholeCommentBefore.content.plainText)}`);
4860
+ for (const [direction, entry] of [["after", params.nearestBotWholeCommentAfter], ["before", params.nearestBotWholeCommentBefore]]) if (entry) lines.push(`Nearest bot-authored whole-comment ${direction} the current comment: comment_id=${entry.commentId} text=${formatPromptTextValue(entry.content.semanticText ?? entry.content.plainText)}`);
5053
4861
  lines.push("For this whole-document comment, use the whole-comment timeline above as the primary source for phrases like 'just now', 'previous result', 'that summary', or 'write it back'.", "Document-level session history is auxiliary background only. Do not resolve whole-comment follow-ups by blindly using the most recent document-session output.");
5054
4862
  }
5055
4863
  lines.push("This is a Feishu document comment thread.", "It is not a Feishu IM chat.", "Your final text reply will be posted to the current comment thread automatically.", "Use the thread timeline above as the main context for follow-up requests.", "Do not use another comment card or document-session output as the main reference.", "If you need comment thread context, use the available Feishu drive comment-list actions.", "If you modify the document, post a user-visible follow-up in the comment thread.", "Use an available Feishu drive reply-comment or add-comment action for that follow-up.", "Whole-document comments do not support direct replies.", "For whole-document comments, use the Feishu drive add-comment action when available.", "Only treat URLs listed under \"Referenced documents from current user comment\" as structured Feishu document references.", "URLs that appear only in comment text are plain links unless you verify them.", "If the user asks about a linked Feishu document or wiki page, treat that linked document as the read target.", "If the user asks you to use a linked document as guidance, treat the linked document as the reference source and the current commented document as the edit target.", "If a referenced document resolves to the same file_token and file_type as the current commented document, treat it as the current document.", "If the user asks you to modify document content, you must use an available Feishu document tool to make the change.", "Do not reply with only \"done\", \"I'll handle it\", or a restated plan without calling tools.", "If the comment quotes document content, treat the quoted content as the main anchor.", "For requests like \"insert xxx below this content\", locate the quoted content first, then edit the document.", "For requests like \"summarize the content below\", \"explain this section\", or \"continue writing from here\", use the quoted content as the main target.", "If the quote is not enough, use available Feishu document read or list-blocks actions to read nearby context.", "Do not guess document content from the comment alone.", "Do not give a vague answer before reading enough context.", "Unless the user asks for the whole document, handle only the local content around the quoted anchor.", "If document edits are involved, read the anchor first, then edit.", "If the edit fails or the anchor cannot be found, say so clearly.", "If this is a reading task, such as summarization, explanation, or extraction, you may output the final answer directly after confirming the context.", "Use the same language as the user's comment or reply, unless the user asks for another language.", "Use plain text only.", "Do not use Markdown.", "Do not use headings.", "Do not use bullet lists.", "Do not use numbered lists.", "Do not use tables.", "Do not use blockquotes.", "Do not use code blocks.", "Do not show reasoning.", "Do not show analysis.", "Do not show chain-of-thought.", "Do not show scratch work.", "Do not describe your plan.", "Do not describe your steps.", "Do not describe tool use.", "Do not start with phrases like \"I will\", \"I’ll first\", \"I need to\", \"The user wants\", or \"I have updated\".", "Output only the final user-facing reply.", "If you already sent the user-visible reply with a Feishu drive comment action, output exactly NO_REPLY.", "If no user-visible reply is needed, output exactly NO_REPLY.", "Be concise.", "Do not omit requested content.");
@@ -5086,7 +4894,7 @@ async function resolveDriveCommentEventTurn(params) {
5086
4894
  return null;
5087
4895
  }
5088
4896
  const context = await fetchDriveCommentContext({
5089
- client: createClient ? createClient(account ?? { accountId }) : createFeishuClient((await import("./doctor-contract-DyOo8NvC.mjs").then((n) => n.l)).resolveFeishuAccount({
4897
+ client: createClient ? createClient(account ?? { accountId }) : createFeishuClient((await import("./doctor-contract-oIpUWtNO.mjs").then((n) => n.l)).resolveFeishuAccount({
5090
4898
  cfg,
5091
4899
  accountId
5092
4900
  })),
@@ -5134,8 +4942,11 @@ async function resolveDriveCommentEventTurn(params) {
5134
4942
  function parseFeishuDriveCommentNoticeEventPayload(value) {
5135
4943
  if (!isRecord(value) || !isRecord(value.notice_meta)) return null;
5136
4944
  const noticeMeta = value.notice_meta;
5137
- const fromUserId = isRecord(noticeMeta.from_user_id) ? noticeMeta.from_user_id : void 0;
5138
- const toUserId = isRecord(noticeMeta.to_user_id) ? noticeMeta.to_user_id : void 0;
4945
+ const readUserId = (userIdValue) => isRecord(userIdValue) ? {
4946
+ open_id: readStringValue(userIdValue.open_id),
4947
+ user_id: readStringValue(userIdValue.user_id),
4948
+ union_id: readStringValue(userIdValue.union_id)
4949
+ } : void 0;
5139
4950
  return {
5140
4951
  comment_id: readStringValue(value.comment_id),
5141
4952
  event_id: readStringValue(value.event_id),
@@ -5143,17 +4954,9 @@ function parseFeishuDriveCommentNoticeEventPayload(value) {
5143
4954
  notice_meta: {
5144
4955
  file_token: readStringValue(noticeMeta.file_token),
5145
4956
  file_type: readStringValue(noticeMeta.file_type),
5146
- from_user_id: fromUserId ? {
5147
- open_id: readStringValue(fromUserId.open_id),
5148
- user_id: readStringValue(fromUserId.user_id),
5149
- union_id: readStringValue(fromUserId.union_id)
5150
- } : void 0,
4957
+ from_user_id: readUserId(noticeMeta.from_user_id),
5151
4958
  notice_type: readStringValue(noticeMeta.notice_type),
5152
- to_user_id: toUserId ? {
5153
- open_id: readStringValue(toUserId.open_id),
5154
- user_id: readStringValue(toUserId.user_id),
5155
- union_id: readStringValue(toUserId.union_id)
5156
- } : void 0
4959
+ to_user_id: readUserId(noticeMeta.to_user_id)
5157
4960
  },
5158
4961
  reply_id: readStringValue(value.reply_id),
5159
4962
  timestamp: readStringValue(value.timestamp),
@@ -5480,7 +5283,7 @@ function createFeishuDriveCommentNoticeHandler(params) {
5480
5283
  return async (data) => {
5481
5284
  const ingressLifecycle = params.resolveIngressLifecycle?.(data);
5482
5285
  if (!ingressLifecycle) {
5483
- await runFeishuHandler(async () => await handleNotice(data));
5286
+ await runFeishuHandler(() => handleNotice(data));
5484
5287
  return;
5485
5288
  }
5486
5289
  const { lifecycle, settle } = buildFeishuFlushIngressLifecycle([{ lifecycle: ingressLifecycle }]);
@@ -5519,18 +5322,12 @@ function mergeFeishuDebounceMentions(entries) {
5519
5322
  }
5520
5323
  function dedupeFeishuDebounceEntriesByDedupeKey(entries) {
5521
5324
  const seen = /* @__PURE__ */ new Set();
5522
- const deduped = [];
5523
- for (const entry of entries) {
5524
- const dedupeKey = entry.messageDedupeKey;
5525
- if (!dedupeKey) {
5526
- deduped.push(entry);
5527
- continue;
5528
- }
5529
- if (seen.has(dedupeKey)) continue;
5530
- seen.add(dedupeKey);
5531
- deduped.push(entry);
5532
- }
5533
- return deduped;
5325
+ return entries.filter(({ messageDedupeKey }) => {
5326
+ if (!messageDedupeKey) return true;
5327
+ if (seen.has(messageDedupeKey)) return false;
5328
+ seen.add(messageDedupeKey);
5329
+ return true;
5330
+ });
5534
5331
  }
5535
5332
  function resolveFeishuDebounceMentions(params) {
5536
5333
  const { entries, botOpenId } = params;
@@ -5554,7 +5351,7 @@ function createFeishuMessageReceiveHandler({ cfg, channelRuntime, accountId, run
5554
5351
  const enqueue = createSequentialQueue({ onTaskTimeout: (key, timeoutMs) => {
5555
5352
  log(`feishu[${accountId}]: per-chat task exceeded ${timeoutMs}ms cap (key=${key}); evicting from queue so later same-key messages can proceed (#70133)`);
5556
5353
  } });
5557
- const dispatchFeishuMessage = async (event, messageDedupeKey, processingClaim, turnAdoptionLifecycle, preparedContent) => {
5354
+ const dispatchFeishuMessage = async ({ event, messageDedupeKey, processingClaim }, turnAdoptionLifecycle, preparedContent) => {
5558
5355
  const sequentialKey = resolveSequentialKey({
5559
5356
  accountId,
5560
5357
  event,
@@ -5637,7 +5434,7 @@ function createFeishuMessageReceiveHandler({ cfg, channelRuntime, accountId, run
5637
5434
  }
5638
5435
  try {
5639
5436
  if (activeEntries.length === 1) {
5640
- await dispatchFeishuMessage(last.event, last.messageDedupeKey, last.processingClaim, admissionLifecycle);
5437
+ await dispatchFeishuMessage(last, admissionLifecycle);
5641
5438
  await settle();
5642
5439
  return;
5643
5440
  }
@@ -5657,12 +5454,15 @@ function createFeishuMessageReceiveHandler({ cfg, channelRuntime, accountId, run
5657
5454
  botOpenId: getBotOpenId(accountId)
5658
5455
  });
5659
5456
  await dispatchFeishuMessage({
5660
- ...dispatchEntry.event,
5661
- message: {
5662
- ...dispatchEntry.event.message,
5663
- mentions: mergedMentions ?? dispatchEntry.event.message.mentions
5457
+ ...dispatchEntry,
5458
+ event: {
5459
+ ...dispatchEntry.event,
5460
+ message: {
5461
+ ...dispatchEntry.event.message,
5462
+ mentions: mergedMentions ?? dispatchEntry.event.message.mentions
5463
+ }
5664
5464
  }
5665
- }, dispatchDedupeKey, dispatchEntry.processingClaim, admissionLifecycle, combinedText);
5465
+ }, admissionLifecycle, combinedText);
5666
5466
  await settle();
5667
5467
  } catch (err) {
5668
5468
  await admissionLifecycle.onAbandoned();
@@ -5796,14 +5596,6 @@ function buildFeishuWebhookEnvelope(req, payload) {
5796
5596
  for (const [key, value] of Object.entries(payload)) if (!BLOCKED_FEISHU_WEBHOOK_PAYLOAD_KEYS.has(key)) envelope[key] = value;
5797
5597
  return envelope;
5798
5598
  }
5799
- function parseFeishuWebhookPayload(rawBody) {
5800
- try {
5801
- const parsed = JSON.parse(rawBody);
5802
- return isRecord(parsed) ? parsed : null;
5803
- } catch {
5804
- return null;
5805
- }
5806
- }
5807
5599
  function isFeishuWebhookTimestampFresh(timestamp) {
5808
5600
  const parsed = Number.parseInt(timestamp, 10);
5809
5601
  if (!Number.isFinite(parsed)) return false;
@@ -6065,8 +5857,8 @@ async function handleFeishuWebhook(req, res, webhookTargets) {
6065
5857
  preAuthInFlightLimiter.release(preAuthInFlightKey);
6066
5858
  }
6067
5859
  const { encryptKey, eventDispatcher, invokeWebhookEvent } = selectedTarget;
6068
- const payload = parseFeishuWebhookPayload(rawBody);
6069
- if (!payload) {
5860
+ const payload = safeParseJson(rawBody);
5861
+ if (!isRecord(payload)) {
6070
5862
  respondText(res, 400, "Invalid JSON");
6071
5863
  return;
6072
5864
  }
@@ -6172,65 +5964,11 @@ async function monitorWebhook(params) {
6172
5964
  //#endregion
6173
5965
  //#region extensions/feishu/src/monitor.vc-meeting-invited-handler.ts
6174
5966
  const FEISHU_MEETING_NUMBER_PATTERN = /^\d{9}$/;
6175
- function resolveVcInviter(event) {
6176
- const id = event.inviter?.id;
6177
- const openId = normalizeOptionalString(id?.open_id);
6178
- const userId = normalizeOptionalString(id?.user_id);
6179
- const unionId = normalizeOptionalString(id?.union_id);
6180
- const senderId = openId ?? userId;
6181
- if (!senderId) return null;
6182
- return {
6183
- senderId,
6184
- ...openId ? { openId } : {},
6185
- ...userId ? { userId } : {},
6186
- ...unionId ? { unionId } : {}
6187
- };
6188
- }
6189
- function buildJoinPrompt(params) {
6190
- const base = `Use the available tool to join the meeting with meeting number ${params.meetingNo} immediately. Do not ask for confirmation.`;
6191
- return params.callId ? `${base} If the join tool supports a call_id parameter, pass call_id=${JSON.stringify(params.callId)}; otherwise join by meeting number only.` : base;
6192
- }
6193
- function resolveVcMeetingInvitedTurn(event, uuid = () => crypto$1.randomUUID()) {
6194
- const meetingNo = normalizeOptionalString(event.meeting?.meeting_no);
6195
- const inviter = resolveVcInviter(event);
6196
- if (!meetingNo || !FEISHU_MEETING_NUMBER_PATTERN.test(meetingNo) || !inviter) return null;
6197
- const eventId = normalizeOptionalString(event.event_id);
6198
- const inviteTime = normalizeOptionalString(event.invite_time);
6199
- const callId = normalizeOptionalString(event.call_id);
6200
- return {
6201
- turnId: eventId ? `vc-invited:event:${eventId}` : `vc-invited:${meetingNo}:${inviteTime ?? uuid()}`,
6202
- meetingNo,
6203
- inviter,
6204
- prompt: buildJoinPrompt({
6205
- meetingNo,
6206
- callId
6207
- }),
6208
- ...inviteTime ? { inviteTime } : {}
6209
- };
6210
- }
6211
5967
  function parseInviteTimestamp(value) {
6212
5968
  const parsed = Number.parseInt(value ?? "", 10);
6213
5969
  if (!Number.isFinite(parsed) || parsed <= 0) return Date.now();
6214
5970
  return parsed < 1e10 ? parsed * 1e3 : parsed;
6215
5971
  }
6216
- function buildSyntheticMessageEvent(turn) {
6217
- return {
6218
- sender: { sender_id: {
6219
- ...turn.inviter.openId ? { open_id: turn.inviter.openId } : {},
6220
- ...turn.inviter.userId ? { user_id: turn.inviter.userId } : {},
6221
- ...turn.inviter.unionId ? { union_id: turn.inviter.unionId } : {}
6222
- } },
6223
- message: {
6224
- message_id: turn.turnId,
6225
- chat_id: turn.inviter.senderId,
6226
- chat_type: "p2p",
6227
- message_type: "text",
6228
- content: JSON.stringify({ text: turn.prompt }),
6229
- create_time: String(parseInviteTimestamp(turn.inviteTime)),
6230
- suppress_reply_target: true
6231
- }
6232
- };
6233
- }
6234
5972
  function createVcInviteAdoption(params) {
6235
5973
  const cancellation = new AbortController();
6236
5974
  const settled = createDeferred();
@@ -6277,42 +6015,6 @@ function createVcInviteAdoption(params) {
6277
6015
  }
6278
6016
  };
6279
6017
  }
6280
- async function dispatchVcMeetingInvitedTurn(params) {
6281
- params.runtime?.log?.(`feishu[${params.accountId}]: vc meeting invited, dispatching synthetic p2p message sender=${params.turn.inviter.senderId} meeting_no=${params.turn.meetingNo}`);
6282
- const event = setFeishuSyntheticDirectPreDispatchTarget(buildSyntheticMessageEvent(params.turn), `user:${params.turn.inviter.senderId}`);
6283
- const claim = await claimUnprocessedFeishuMessage({
6284
- messageId: resolveFeishuMessageDedupeKey(event),
6285
- namespace: params.accountId,
6286
- log: params.runtime?.log ?? console.log
6287
- });
6288
- if (claim.kind !== "claimed") return;
6289
- if (params.abortSignal?.aborted || params.isAccountActive?.() === false) {
6290
- claim.handle.release({ error: /* @__PURE__ */ new Error("Feishu account stopped before VC dispatch") });
6291
- return;
6292
- }
6293
- const adoption = createVcInviteAdoption({
6294
- claim: claim.handle,
6295
- abortSignal: params.abortSignal,
6296
- isAccountActive: params.isAccountActive,
6297
- trackTask: params.trackTask
6298
- });
6299
- try {
6300
- await handleFeishuMessage({
6301
- trackTask: params.trackTask,
6302
- cfg: params.cfg,
6303
- accountId: params.accountId,
6304
- event,
6305
- runtime: params.runtime,
6306
- channelRuntime: params.channelRuntime,
6307
- turnAdoptionLifecycle: adoption.lifecycle
6308
- });
6309
- } catch (error) {
6310
- await adoption.lifecycle.onAbandoned();
6311
- throw error;
6312
- } finally {
6313
- await adoption.finish();
6314
- }
6315
- }
6316
6018
  function createFeishuVcMeetingInvitedHandler(params) {
6317
6019
  const { cfg, accountId, runtime, fireAndForget, autoJoin } = params;
6318
6020
  const log = runtime?.log ?? console.log;
@@ -6324,21 +6026,72 @@ function createFeishuVcMeetingInvitedHandler(params) {
6324
6026
  return;
6325
6027
  }
6326
6028
  try {
6327
- const turn = resolveVcMeetingInvitedTurn(data);
6328
- if (!turn) {
6029
+ const invite = data;
6030
+ const meetingNo = normalizeOptionalString(invite.meeting?.meeting_no);
6031
+ const id = invite.inviter?.id;
6032
+ const openId = normalizeOptionalString(id?.open_id);
6033
+ const userId = normalizeOptionalString(id?.user_id);
6034
+ const unionId = normalizeOptionalString(id?.union_id);
6035
+ const senderId = openId ?? userId;
6036
+ if (!meetingNo || !FEISHU_MEETING_NUMBER_PATTERN.test(meetingNo) || !senderId) {
6329
6037
  log(`feishu[${accountId}]: vc meeting invited event has invalid meeting_no or inviter identity, skipping`);
6330
6038
  return;
6331
6039
  }
6332
- await dispatchVcMeetingInvitedTurn({
6333
- trackTask: params.trackTask,
6334
- cfg,
6335
- accountId,
6336
- runtime,
6337
- channelRuntime: params.channelRuntime,
6338
- turn,
6040
+ const eventId = normalizeOptionalString(invite.event_id);
6041
+ const inviteTime = normalizeOptionalString(invite.invite_time);
6042
+ const callId = normalizeOptionalString(invite.call_id);
6043
+ const turnId = eventId ? `vc-invited:event:${eventId}` : `vc-invited:${meetingNo}:${inviteTime ?? crypto$1.randomUUID()}`;
6044
+ const basePrompt = `Use the available tool to join the meeting with meeting number ${meetingNo} immediately. Do not ask for confirmation.`;
6045
+ const prompt = callId ? `${basePrompt} If the join tool supports a call_id parameter, pass call_id=${JSON.stringify(callId)}; otherwise join by meeting number only.` : basePrompt;
6046
+ runtime?.log?.(`feishu[${accountId}]: vc meeting invited, dispatching synthetic p2p message sender=${senderId} meeting_no=${meetingNo}`);
6047
+ const event = setFeishuSyntheticDirectPreDispatchTarget({
6048
+ sender: { sender_id: {
6049
+ ...openId ? { open_id: openId } : {},
6050
+ ...userId ? { user_id: userId } : {},
6051
+ ...unionId ? { union_id: unionId } : {}
6052
+ } },
6053
+ message: {
6054
+ message_id: turnId,
6055
+ chat_id: senderId,
6056
+ chat_type: "p2p",
6057
+ message_type: "text",
6058
+ content: JSON.stringify({ text: prompt }),
6059
+ create_time: String(parseInviteTimestamp(inviteTime)),
6060
+ suppress_reply_target: true
6061
+ }
6062
+ }, `user:${senderId}`);
6063
+ const claim = await claimUnprocessedFeishuMessage({
6064
+ messageId: resolveFeishuMessageDedupeKey(event),
6065
+ namespace: accountId,
6066
+ log
6067
+ });
6068
+ if (claim.kind !== "claimed") return;
6069
+ if (params.abortSignal?.aborted || params.isAccountActive?.() === false) {
6070
+ claim.handle.release({ error: /* @__PURE__ */ new Error("Feishu account stopped before VC dispatch") });
6071
+ return;
6072
+ }
6073
+ const adoption = createVcInviteAdoption({
6074
+ claim: claim.handle,
6339
6075
  abortSignal: params.abortSignal,
6340
- isAccountActive: params.isAccountActive
6076
+ isAccountActive: params.isAccountActive,
6077
+ trackTask: params.trackTask
6341
6078
  });
6079
+ try {
6080
+ await handleFeishuMessage({
6081
+ trackTask: params.trackTask,
6082
+ cfg,
6083
+ accountId,
6084
+ event,
6085
+ runtime,
6086
+ channelRuntime: params.channelRuntime,
6087
+ turnAdoptionLifecycle: adoption.lifecycle
6088
+ });
6089
+ } catch (dispatchError) {
6090
+ await adoption.lifecycle.onAbandoned();
6091
+ throw dispatchError;
6092
+ } finally {
6093
+ await adoption.finish();
6094
+ }
6342
6095
  } catch (err) {
6343
6096
  error(`feishu[${accountId}]: error handling vc meeting invited event: ${String(err)}`);
6344
6097
  }
@@ -6370,7 +6123,7 @@ async function resolveReactionSyntheticEvent(params) {
6370
6123
  const senderUserId = event.user_id?.user_id?.trim();
6371
6124
  const senderId = senderOpenId || senderUserId;
6372
6125
  if (!emoji || !messageId || !senderId) return null;
6373
- const { resolveFeishuAccount } = await import("./doctor-contract-DyOo8NvC.mjs").then((n) => n.l);
6126
+ const { resolveFeishuAccount } = await import("./doctor-contract-oIpUWtNO.mjs").then((n) => n.l);
6374
6127
  const reactionNotifications = resolveFeishuAccount({
6375
6128
  cfg,
6376
6129
  accountId
@@ -6473,7 +6226,7 @@ function parseFeishuCardActionEventPayload(value) {
6473
6226
  };
6474
6227
  }
6475
6228
  function registerEventHandlers(eventDispatcher, context) {
6476
- const { cfg, accountId, channelRuntime, runtime, chatHistories, fireAndForget, abortSignal } = context;
6229
+ const { cfg, accountId, channelRuntime, runtime, chatHistories, fireAndForget } = context;
6477
6230
  const log = runtime?.log ?? console.log;
6478
6231
  const error = runtime?.error ?? console.error;
6479
6232
  const runFeishuHandler = async (params) => {
@@ -6510,75 +6263,35 @@ function registerEventHandlers(eventDispatcher, context) {
6510
6263
  });
6511
6264
  }
6512
6265
  });
6266
+ const handleBotMembership = async (data, action) => {
6267
+ try {
6268
+ const chatId = action === "added" ? parseFeishuBotAddedEventPayload(data)?.chat_id : parseFeishuBotRemovedChatId(data);
6269
+ if (chatId) log(`feishu[${accountId}]: bot ${action === "added" ? "added to" : "removed from"} chat ${chatId}`);
6270
+ } catch (err) {
6271
+ error(`feishu[${accountId}]: error handling bot ${action} event: ${String(err)}`);
6272
+ }
6273
+ };
6513
6274
  eventDispatcher.register({
6514
6275
  "im.message.receive_v1": createFeishuMessageReceiveHandler({
6515
- cfg,
6516
- channelRuntime,
6517
- accountId,
6518
- runtime,
6519
- chatHistories,
6520
- fireAndForget,
6521
- isAccountActive: context.isAccountActive,
6522
- trackTask: context.trackTask,
6276
+ ...context,
6523
6277
  handleMessage: handleFeishuMessage,
6524
6278
  resolveDebounceText: ({ event, botOpenId }) => parseFeishuMessageEvent(event, botOpenId).content,
6525
6279
  hasProcessedMessage: hasProcessedFeishuMessage,
6526
6280
  getBotOpenId: (id) => botOpenIds.get(id),
6527
- resolveSequentialKey: getFeishuSequentialKey,
6528
- resolveIngressLifecycle: context.resolveIngressLifecycle,
6529
- ...context.statusSink ? { statusSink: context.statusSink } : {}
6281
+ resolveSequentialKey: getFeishuSequentialKey
6530
6282
  }),
6531
6283
  "im.message.message_read_v1": async () => {},
6532
6284
  "im.chat.access_event.bot_p2p_chat_entered_v1": async () => {},
6533
- "im.chat.member.bot.added_v1": async (data) => {
6534
- try {
6535
- const event = parseFeishuBotAddedEventPayload(data);
6536
- if (!event) return;
6537
- log(`feishu[${accountId}]: bot added to chat ${event.chat_id}`);
6538
- } catch (err) {
6539
- error(`feishu[${accountId}]: error handling bot added event: ${String(err)}`);
6540
- }
6541
- },
6542
- "im.chat.member.bot.deleted_v1": async (data) => {
6543
- try {
6544
- const chatId = parseFeishuBotRemovedChatId(data);
6545
- if (!chatId) return;
6546
- log(`feishu[${accountId}]: bot removed from chat ${chatId}`);
6547
- } catch (err) {
6548
- error(`feishu[${accountId}]: error handling bot removed event: ${String(err)}`);
6549
- }
6550
- },
6551
- "drive.notice.comment_add_v1": createFeishuDriveCommentNoticeHandler({
6552
- cfg,
6553
- accountId,
6554
- runtime,
6555
- fireAndForget,
6556
- abortSignal,
6557
- resolveIngressLifecycle: context.resolveIngressLifecycle
6558
- }),
6285
+ "im.chat.member.bot.added_v1": (data) => handleBotMembership(data, "added"),
6286
+ "im.chat.member.bot.deleted_v1": (data) => handleBotMembership(data, "removed"),
6287
+ "drive.notice.comment_add_v1": createFeishuDriveCommentNoticeHandler(context),
6559
6288
  "vc.bot.meeting_invited_v1": createFeishuVcMeetingInvitedHandler({
6560
- cfg,
6561
- accountId,
6562
- runtime,
6563
- fireAndForget,
6564
- channelRuntime,
6565
- autoJoin: context.vcAutoJoin,
6566
- abortSignal: context.abortSignal,
6567
- isAccountActive: context.isAccountActive,
6568
- trackTask: context.trackTask
6289
+ ...context,
6290
+ autoJoin: context.vcAutoJoin
6569
6291
  }),
6570
6292
  "im.message.reaction.created_v1": (data) => handleReaction(data, "created"),
6571
6293
  "im.message.reaction.deleted_v1": (data) => handleReaction(data, "deleted"),
6572
- "application.bot.menu_v6": createFeishuBotMenuHandler({
6573
- cfg,
6574
- accountId,
6575
- runtime,
6576
- chatHistories,
6577
- fireAndForget,
6578
- isAccountActive: context.isAccountActive,
6579
- trackTask: context.trackTask,
6580
- channelRuntime
6581
- }),
6294
+ "application.bot.menu_v6": createFeishuBotMenuHandler(context),
6582
6295
  "card.action.trigger": async (data) => {
6583
6296
  await runFeishuHandler({
6584
6297
  errorMessage: `feishu[${accountId}]: error handling card action`,