@openclaw/feishu 2026.10.1-beta.2 → 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 (151) hide show
  1. package/dist/.setup/{app-registration-BB6TubaW.mjs → app-registration-DQOq5urV.mjs} +13 -32
  2. package/dist/.setup/{channel-CX62T71S.mjs → channel-CjGGyrdx.mjs} +87 -174
  3. package/dist/.setup/{channel.runtime-COiaq-Rv.mjs → channel.runtime-SaC_uTPM.mjs} +57 -74
  4. package/dist/.setup/{chat-BdyvImsY.mjs → chat-fC3dvxFs.mjs} +16 -28
  5. package/dist/.setup/{client-BsBVWJzN.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-B1B9ogdd.mjs → doctor-contract-oIpUWtNO.mjs} +23 -20
  8. package/dist/.setup/{monitor-7DvwUs4Y.mjs → monitor-Yt__BUki.mjs} +33 -54
  9. package/dist/.setup/{monitor.account-7xVu7XWY.mjs → monitor.account-CVz16781.mjs} +377 -664
  10. package/dist/.setup/{probe-B9o7iey6.mjs → probe-DXnFxq5j.mjs} +14 -17
  11. package/dist/.setup/{reply-delivery-result-Bt-BWBEA.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-DmzX9S01.mjs → setup-api-B_LFQQ-Q.mjs} +1 -1
  14. package/dist/.setup/{subagent-hooks-CUXg0pC-.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 +2 -2
  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 +91 -0
  26. package/node_modules/@openclaw/fs-safe/README.md +1 -1
  27. package/node_modules/@openclaw/fs-safe/dist/advanced.d.ts +1 -0
  28. package/node_modules/@openclaw/fs-safe/dist/advanced.js +1 -0
  29. package/node_modules/@openclaw/fs-safe/dist/archive-durability.js +1 -1
  30. package/node_modules/@openclaw/fs-safe/dist/archive-entry.js +7 -3
  31. package/node_modules/@openclaw/fs-safe/dist/archive-merge.js +4 -4
  32. package/node_modules/@openclaw/fs-safe/dist/archive-parser.wasm +0 -0
  33. package/node_modules/@openclaw/fs-safe/dist/archive-read.js +5 -4
  34. package/node_modules/@openclaw/fs-safe/dist/archive-staging.d.ts +1 -1
  35. package/node_modules/@openclaw/fs-safe/dist/archive-staging.js +22 -38
  36. package/node_modules/@openclaw/fs-safe/dist/copy-path-admission.d.ts +17 -0
  37. package/node_modules/@openclaw/fs-safe/dist/copy-path-admission.js +117 -0
  38. package/node_modules/@openclaw/fs-safe/dist/copy-root-file-sync.d.ts +38 -0
  39. package/node_modules/@openclaw/fs-safe/dist/copy-root-file-sync.js +195 -0
  40. package/node_modules/@openclaw/fs-safe/dist/create.d.ts +1 -0
  41. package/node_modules/@openclaw/fs-safe/dist/create.js +4 -1
  42. package/node_modules/@openclaw/fs-safe/dist/entry-publication.js +3 -1
  43. package/node_modules/@openclaw/fs-safe/dist/errors.d.ts +2 -0
  44. package/node_modules/@openclaw/fs-safe/dist/errors.js +5 -0
  45. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-acquire.d.ts +3 -0
  46. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-acquire.js +57 -11
  47. package/node_modules/@openclaw/fs-safe/dist/guarded-mutation.js +5 -5
  48. package/node_modules/@openclaw/fs-safe/dist/guest-native-python.js +52 -5
  49. package/node_modules/@openclaw/fs-safe/dist/guest.js +1 -1
  50. package/node_modules/@openclaw/fs-safe/dist/index.d.ts +1 -1
  51. package/node_modules/@openclaw/fs-safe/dist/index.js +1 -1
  52. package/node_modules/@openclaw/fs-safe/dist/native-binding.d.ts +4 -0
  53. package/node_modules/@openclaw/fs-safe/dist/native-move-fallback.d.ts +3 -0
  54. package/node_modules/@openclaw/fs-safe/dist/native-move-fallback.js +54 -0
  55. package/node_modules/@openclaw/fs-safe/dist/native-noreplace.d.ts +8 -0
  56. package/node_modules/@openclaw/fs-safe/dist/native-noreplace.js +55 -0
  57. package/node_modules/@openclaw/fs-safe/dist/native-operations.d.ts +0 -1
  58. package/node_modules/@openclaw/fs-safe/dist/native-operations.js +22 -26
  59. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write-windows.js +5 -1
  60. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write.d.ts +1 -1
  61. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write.js +12 -2
  62. package/node_modules/@openclaw/fs-safe/dist/native-rename-outcome.js +3 -1
  63. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.d.ts +1 -1
  64. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.js +52 -6
  65. package/node_modules/@openclaw/fs-safe/dist/permission-exec.js +2 -1
  66. package/node_modules/@openclaw/fs-safe/dist/pinned-write-input.d.ts +2 -0
  67. package/node_modules/@openclaw/fs-safe/dist/pinned-write-input.js +17 -0
  68. package/node_modules/@openclaw/fs-safe/dist/pinned-write-types.d.ts +6 -1
  69. package/node_modules/@openclaw/fs-safe/dist/pinned-write.js +1 -1
  70. package/node_modules/@openclaw/fs-safe/dist/private-temp-workspace.js +2 -2
  71. package/node_modules/@openclaw/fs-safe/dist/publish-file-failure.d.ts +5 -0
  72. package/node_modules/@openclaw/fs-safe/dist/publish-file-failure.js +1 -0
  73. package/node_modules/@openclaw/fs-safe/dist/publish-file.d.ts +2 -0
  74. package/node_modules/@openclaw/fs-safe/dist/publish-file.js +35 -2
  75. package/node_modules/@openclaw/fs-safe/dist/replace-directory.js +6 -5
  76. package/node_modules/@openclaw/fs-safe/dist/replace-file-copy-fallback.js +1 -4
  77. package/node_modules/@openclaw/fs-safe/dist/replace-file-descriptor.js +6 -0
  78. package/node_modules/@openclaw/fs-safe/dist/root-create-input.d.ts +15 -1
  79. package/node_modules/@openclaw/fs-safe/dist/root-create-input.js +4 -0
  80. package/node_modules/@openclaw/fs-safe/dist/root-directory-entry.js +1 -1
  81. package/node_modules/@openclaw/fs-safe/dist/root-directory-list.d.ts +0 -1
  82. package/node_modules/@openclaw/fs-safe/dist/root-directory-list.js +6 -12
  83. package/node_modules/@openclaw/fs-safe/dist/root-errors.js +25 -4
  84. package/node_modules/@openclaw/fs-safe/dist/root-impl.js +18 -18
  85. package/node_modules/@openclaw/fs-safe/dist/root-move-noreplace.d.ts +4 -2
  86. package/node_modules/@openclaw/fs-safe/dist/root-move-noreplace.js +13 -17
  87. package/node_modules/@openclaw/fs-safe/dist/root-paths.js +1 -1
  88. package/node_modules/@openclaw/fs-safe/dist/root-walk.js +4 -4
  89. package/node_modules/@openclaw/fs-safe/dist/root-write-verification.d.ts +10 -1
  90. package/node_modules/@openclaw/fs-safe/dist/root-write-verification.js +20 -0
  91. package/node_modules/@openclaw/fs-safe/dist/secure-temp-dir.js +19 -7
  92. package/node_modules/@openclaw/fs-safe/dist/sibling-staged-file.js +18 -3
  93. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-acquire.js +25 -3
  94. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-admission.d.ts +2 -0
  95. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-retained.d.ts +14 -0
  96. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-retained.js +187 -0
  97. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock.js +15 -1
  98. package/node_modules/@openclaw/fs-safe/dist/staged-file-settlement.js +4 -1
  99. package/node_modules/@openclaw/fs-safe/dist/temp-directory-diagnostics.d.ts +10 -0
  100. package/node_modules/@openclaw/fs-safe/dist/temp-directory-diagnostics.js +29 -0
  101. package/node_modules/@openclaw/fs-safe/dist/temp-target.js +1 -1
  102. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-admission.js +6 -6
  103. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.d.ts +4 -4
  104. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.js +17 -16
  105. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-descriptor.js +20 -28
  106. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-owner.d.ts +1 -0
  107. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-owner.js +27 -4
  108. package/node_modules/@openclaw/fs-safe/dist/walk.js +2 -13
  109. package/node_modules/@openclaw/fs-safe/dist/watch-native.d.ts +2 -2
  110. package/node_modules/@openclaw/fs-safe/dist/watch-native.js +3 -1
  111. package/node_modules/@openclaw/fs-safe/dist/watch-rescan.js +3 -9
  112. package/node_modules/@openclaw/fs-safe/dist/watch.js +2 -3
  113. package/node_modules/@openclaw/fs-safe/docs/advanced.md +1 -0
  114. package/node_modules/@openclaw/fs-safe/docs/archive.md +5 -1
  115. package/node_modules/@openclaw/fs-safe/docs/atomic.md +11 -3
  116. package/node_modules/@openclaw/fs-safe/docs/contributing.md +1 -1
  117. package/node_modules/@openclaw/fs-safe/docs/copy.md +109 -1
  118. package/node_modules/@openclaw/fs-safe/docs/durability.md +50 -5
  119. package/node_modules/@openclaw/fs-safe/docs/errors.md +37 -0
  120. package/node_modules/@openclaw/fs-safe/docs/guest.md +21 -4
  121. package/node_modules/@openclaw/fs-safe/docs/native-helper.md +5 -3
  122. package/node_modules/@openclaw/fs-safe/docs/native.md +39 -6
  123. package/node_modules/@openclaw/fs-safe/docs/path-scope.md +4 -0
  124. package/node_modules/@openclaw/fs-safe/docs/public-api.md +3 -1
  125. package/node_modules/@openclaw/fs-safe/docs/sidecar-lock.md +46 -8
  126. package/node_modules/@openclaw/fs-safe/docs/staged-file.md +10 -3
  127. package/node_modules/@openclaw/fs-safe/docs/temp.md +12 -0
  128. package/node_modules/@openclaw/fs-safe/docs/watch.md +6 -3
  129. package/node_modules/@openclaw/fs-safe/docs/writing.md +40 -11
  130. package/node_modules/@openclaw/fs-safe/package.json +16 -16
  131. package/node_modules/@openclaw/fs-safe-darwin-arm64/fs-safe-native.node +0 -0
  132. package/node_modules/@openclaw/fs-safe-darwin-arm64/package.json +1 -1
  133. package/node_modules/@openclaw/fs-safe-darwin-x64/fs-safe-native.node +0 -0
  134. package/node_modules/@openclaw/fs-safe-darwin-x64/package.json +1 -1
  135. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/fs-safe-native.node +0 -0
  136. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/package.json +1 -1
  137. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/fs-safe-native.node +0 -0
  138. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/package.json +1 -1
  139. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/fs-safe-native.node +0 -0
  140. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/package.json +1 -1
  141. package/node_modules/@openclaw/fs-safe-linux-x64-musl/fs-safe-native.node +0 -0
  142. package/node_modules/@openclaw/fs-safe-linux-x64-musl/package.json +1 -1
  143. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/fs-safe-native.node +0 -0
  144. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/package.json +1 -1
  145. package/node_modules/follow-redirects/index.js +10 -1
  146. package/node_modules/follow-redirects/package.json +1 -1
  147. package/package.json +5 -5
  148. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-arbitration.d.ts +0 -17
  149. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-arbitration.js +0 -66
  150. package/node_modules/@openclaw/fs-safe/dist/root-move-preflight.d.ts +0 -7
  151. package/node_modules/@openclaw/fs-safe/dist/root-move-preflight.js +0 -16
package/dist/api.js CHANGED
@@ -1,11 +1,11 @@
1
- import { a as parseFeishuTargetId, i as parseFeishuDirectConversationId, n as buildFeishuModelOverrideParentCandidates, r as parseFeishuConversationId, t as buildFeishuConversationId } from "./.setup/conversation-id-C1ofUfU8.mjs";
2
- import { a as setFeishuNamedAccountEnabled, i as feishuSetupAdapter, n as feishuSetupWizard, r as runFeishuLogin, t as feishuPlugin } from "./.setup/channel-CX62T71S.mjs";
3
- import { J as feishuExternalToolResult, K as registerFeishuDriveTools, Q as assertFeishuApiSuccess, X as createFeishuToolClient, Y as unknownToolActionResult, Z as resolveFeishuToolAccount, dt as chunkFeishuMarkdown, gt as visitFeishuMarkdown, mt as parseFeishuMarkdown, q as registerFeishuTool } from "./.setup/reply-delivery-result-Bt-BWBEA.mjs";
1
+ import { a as parseFeishuTargetId, i as parseFeishuDirectConversationId, n as buildFeishuModelOverrideParentCandidates, r as parseFeishuConversationId, t as buildFeishuConversationId } from "./.setup/conversation-id-D00i9uy5.mjs";
2
+ import { a as setFeishuNamedAccountEnabled, i as feishuSetupAdapter, n as feishuSetupWizard, r as runFeishuLogin, t as feishuPlugin } from "./.setup/channel-CjGGyrdx.mjs";
3
+ import { $ as assertFeishuApiSuccess, J as registerFeishuTool, Q as resolveFeishuToolAccount, X as unknownToolActionResult, Y as feishuExternalToolResult, Z as createFeishuToolClient, _t as visitFeishuMarkdown, ft as chunkFeishuMarkdown, ht as parseFeishuMarkdown, q as registerFeishuDriveTools } from "./.setup/reply-delivery-result-iCCrdxE1.mjs";
4
4
  import { t as getFeishuRuntime } from "./.setup/runtime-C5JxBWZp.mjs";
5
- import { f as resolveConfiguredHttpTimeoutMs, r as createFeishuClient } from "./.setup/client-BsBVWJzN.mjs";
6
- import { o as registerFeishuChatTools } from "./.setup/chat-BdyvImsY.mjs";
7
- import { n as getFeishuThreadBindingManager, t as createFeishuThreadBindingManager } from "./.setup/thread-bindings-jW2x5VuN.mjs";
8
- import { n as handleFeishuSubagentEnded, t as handleFeishuSubagentDeliveryTarget } from "./.setup/subagent-hooks-CUXg0pC-.mjs";
5
+ import { f as resolveConfiguredHttpTimeoutMs, r as createFeishuClient } from "./.setup/client-wwr8PGPH.mjs";
6
+ import { o as registerFeishuChatTools } from "./.setup/chat-fC3dvxFs.mjs";
7
+ import { n as getFeishuThreadBindingManager, t as createFeishuThreadBindingManager } from "./.setup/thread-bindings-DdNLxoL3.mjs";
8
+ import { n as handleFeishuSubagentEnded, t as handleFeishuSubagentDeliveryTarget } from "./.setup/subagent-hooks-9Pc1-k37.mjs";
9
9
  import { optionalPositiveIntegerSchema } from "openclaw/plugin-sdk/channel-actions";
10
10
  import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
11
11
  import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, readStringValue, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
@@ -179,16 +179,7 @@ function calculateAdaptiveColumnWidths(blocks, tableBlockId, getBlockMap) {
179
179
  const cellIds = normalizeChildBlockIds(tableBlock.children);
180
180
  const blockMap = getBlockMap();
181
181
  function getCellText(cellId) {
182
- const cell = blockMap.get(cellId);
183
- let text = "";
184
- const childIds = normalizeChildBlockIds(cell?.children);
185
- for (const childId of childIds) {
186
- const child = blockMap.get(childId);
187
- if (child?.text?.elements) {
188
- for (const elem of child.text.elements) if (elem.text_run?.content) text += elem.text_run.content;
189
- }
190
- }
191
- return text;
182
+ return normalizeChildBlockIds(blockMap.get(cellId)?.children).flatMap((childId) => blockMap.get(childId)?.text?.elements ?? []).map((element) => element.text_run?.content ?? "").join("");
192
183
  }
193
184
  function getWeightedLength(text) {
194
185
  let length = 0;
@@ -196,12 +187,9 @@ function calculateAdaptiveColumnWidths(blocks, tableBlockId, getBlockMap) {
196
187
  return length;
197
188
  }
198
189
  const maxLengths = Array.from({ length: column_size }, () => 0);
199
- for (let row = 0; row < row_size; row++) for (let col = 0; col < column_size; col++) {
200
- const cellId = cellIds[row * column_size + col];
201
- if (cellId) {
202
- const length = getWeightedLength(getCellText(cellId));
203
- maxLengths[col] = Math.max(maxLengths[col] ?? 0, length);
204
- }
190
+ for (const [index, cellId] of cellIds.slice(0, row_size * column_size).entries()) if (cellId) {
191
+ const col = index % column_size;
192
+ maxLengths[col] = Math.max(maxLengths[col] ?? 0, getWeightedLength(getCellText(cellId)));
205
193
  }
206
194
  const totalLength = maxLengths.reduce((a, b) => a + b, 0);
207
195
  if (totalLength === 0) {
@@ -311,34 +299,13 @@ async function patchTable(client, params) {
311
299
  //#endregion
312
300
  //#region extensions/feishu/src/docx-batch-insert.ts
313
301
  const BATCH_SIZE = 1e3;
314
- function normalizeChildIds$1(children) {
315
- if (Array.isArray(children)) return children;
316
- const child = readStringValue(children);
317
- return child ? [child] : void 0;
318
- }
319
302
  function toDescendantBlock(block) {
320
- const children = normalizeChildIds$1(block.children);
303
+ const child = readStringValue(block.children);
321
304
  return {
322
305
  ...block,
323
- ...children ? { children } : {}
306
+ ...child ? { children: [child] } : {}
324
307
  };
325
308
  }
326
- function collectDescendants(blockMap, rootId) {
327
- const result = [];
328
- const visited = /* @__PURE__ */ new Set();
329
- function collect(blockId) {
330
- if (visited.has(blockId)) return;
331
- visited.add(blockId);
332
- const block = blockMap.get(blockId);
333
- if (!block) return;
334
- result.push(block);
335
- const children = block.children;
336
- if (Array.isArray(children)) for (const childId of children) collect(childId);
337
- else if (typeof children === "string") collect(children);
338
- }
339
- collect(rootId);
340
- return result;
341
- }
342
309
  async function insertDocxDescendants(client, docToken, descendants, firstLevelBlockIds, parentBlockId = docToken, index = -1) {
343
310
  if (descendants.length === 0) return [];
344
311
  const res = await client.docx.documentBlockDescendant.create({
@@ -366,7 +333,16 @@ async function insertBlocksInBatches(client, docToken, blocks, firstLevelBlockId
366
333
  const blockMap = /* @__PURE__ */ new Map();
367
334
  for (const block of blocks) if (block.block_id) blockMap.set(block.block_id, block);
368
335
  for (const firstLevelId of firstLevelBlockIds) {
369
- const newBlocks = collectDescendants(blockMap, firstLevelId).filter((b) => b.block_id && !usedBlockIds.has(b.block_id));
336
+ const newBlocks = [];
337
+ const collect = (blockId) => {
338
+ const block = blockMap.get(blockId);
339
+ if (!block || usedBlockIds.has(blockId)) return;
340
+ usedBlockIds.add(blockId);
341
+ newBlocks.push(block);
342
+ const children = block.children;
343
+ for (const childId of typeof children === "string" ? [children] : children ?? []) collect(childId);
344
+ };
345
+ collect(firstLevelId);
370
346
  if (newBlocks.length > 1e3) throw new Error(`Block "${firstLevelId}" has ${newBlocks.length} descendants, which exceeds the Feishu API limit of ${BATCH_SIZE} blocks per request. Please split the content into smaller sections.`);
371
347
  if (currentBatch.blocks.length + newBlocks.length > 1e3 && currentBatch.blocks.length > 0) {
372
348
  batches.push(currentBatch);
@@ -376,10 +352,7 @@ async function insertBlocksInBatches(client, docToken, blocks, firstLevelBlockId
376
352
  };
377
353
  }
378
354
  currentBatch.firstLevelIds.push(firstLevelId);
379
- for (const block of newBlocks) {
380
- currentBatch.blocks.push(block);
381
- if (block.block_id) usedBlockIds.add(block.block_id);
382
- }
355
+ currentBatch.blocks.push(...newBlocks);
383
356
  }
384
357
  if (currentBatch.blocks.length > 0) batches.push(currentBatch);
385
358
  let currentIndex = startIndex;
@@ -457,13 +430,8 @@ const STABLE_LINE_CONTAINER_TYPES = /* @__PURE__ */ new Set([
457
430
  "code"
458
431
  ]);
459
432
  function resolveRemoteImageUrl(value) {
460
- if (!value) return;
461
- try {
462
- const url = new URL(value);
463
- return url.protocol === "http:" || url.protocol === "https:" ? value : void 0;
464
- } catch {
465
- return;
466
- }
433
+ const url = URL.parse(value ?? "");
434
+ return url?.protocol === "http:" || url?.protocol === "https:" ? value : void 0;
467
435
  }
468
436
  function collectMarkdownImages(root) {
469
437
  const definitions = /* @__PURE__ */ new Map();
@@ -486,20 +454,11 @@ function splitSourceAtOffsets(source, offsets) {
486
454
  chunks.push(source.slice(start));
487
455
  return chunks;
488
456
  }
489
- function headingOffsets(source, root) {
457
+ function blockStartOffsets(root, include = () => true) {
490
458
  const offsets = [];
491
459
  for (const node of root.children ?? []) {
492
- if (node.type !== "heading" || node.depth === void 0 || node.depth > 2) continue;
493
460
  const offset = node.position?.start.offset;
494
- if (offset !== void 0 && source[offset] === "#") offsets.push(offset);
495
- }
496
- return offsets;
497
- }
498
- function blockBreakOffsets(root) {
499
- const offsets = [];
500
- for (const block of root.children ?? []) {
501
- const blockStart = block.position?.start.offset;
502
- if (blockStart !== void 0 && blockStart > 0) offsets.push(blockStart);
461
+ if (offset !== void 0 && include(node, offset)) offsets.push(offset);
503
462
  }
504
463
  return offsets;
505
464
  }
@@ -528,15 +487,10 @@ function lineBreakOffsets(source) {
528
487
  function nearestOffset(offsets, target, sourceLength) {
529
488
  return offsets.filter((offset) => offset > 0 && offset < sourceLength).toSorted((left, right) => Math.abs(left - target) - Math.abs(right - target) || left - right);
530
489
  }
531
- function isStableParagraphBreak(source, offset) {
532
- const before = parseFeishuMarkdown(source.slice(0, offset)).children?.at(-1);
533
- const after = parseFeishuMarkdown(source.slice(offset)).children?.[0];
534
- return before?.type === "paragraph" && after?.type === "paragraph";
535
- }
536
- function isStableContainerBreak(source, offset, containerType) {
490
+ function isStableBreak(source, offset, blockType) {
537
491
  const before = parseFeishuMarkdown(source.slice(0, offset)).children;
538
492
  const after = parseFeishuMarkdown(source.slice(offset)).children;
539
- return before?.length === 1 && after?.length === 1 && before[0]?.type === containerType && after[0]?.type === containerType;
493
+ return (blockType === "paragraph" || before?.length === 1 && after?.length === 1) && before?.at(-1)?.type === blockType && after?.[0]?.type === blockType;
540
494
  }
541
495
  function splitTableAtRow(source, root, target) {
542
496
  const table = root.children?.length === 1 ? root.children[0] : void 0;
@@ -561,7 +515,7 @@ function createDocxMarkdownChunk(markdown) {
561
515
  }
562
516
  function createDocxMarkdownPlan(markdown) {
563
517
  const root = parseFeishuMarkdown(markdown);
564
- return { chunks: splitSourceAtOffsets(markdown, headingOffsets(markdown, root)).map((chunk) => chunk === markdown ? {
518
+ return { chunks: splitSourceAtOffsets(markdown, blockStartOffsets(root, (node, offset) => node.type === "heading" && node.depth !== void 0 && node.depth <= 2 && markdown[offset] === "#")).map((chunk) => chunk === markdown ? {
565
519
  markdown,
566
520
  images: collectMarkdownImages(root)
567
521
  } : createDocxMarkdownChunk(chunk)) };
@@ -570,16 +524,16 @@ function splitDocxMarkdownBySize(markdown, maxChars) {
570
524
  if (markdown.length <= maxChars) return [markdown];
571
525
  const root = parseFeishuMarkdown(markdown);
572
526
  const target = Math.min(markdown.length - 1, Math.max(1, maxChars));
573
- const splitOffset = nearestOffset(blockBreakOffsets(root), target, markdown.length)[0];
527
+ const splitOffset = nearestOffset(blockStartOffsets(root), target, markdown.length)[0];
574
528
  if (splitOffset !== void 0) return [markdown.slice(0, splitOffset), markdown.slice(splitOffset)];
575
- const paragraphOffset = nearestOffset(paragraphBreakOffsets(markdown, root), target, markdown.length).slice(0, MAX_BREAK_PROBES).find((offset) => isStableParagraphBreak(markdown, offset));
529
+ const paragraphOffset = nearestOffset(paragraphBreakOffsets(markdown, root), target, markdown.length).slice(0, MAX_BREAK_PROBES).find((offset) => isStableBreak(markdown, offset, "paragraph"));
576
530
  if (paragraphOffset !== void 0) return [markdown.slice(0, paragraphOffset), markdown.slice(paragraphOffset)];
577
531
  if (root.children?.length === 1 && root.children[0]?.type === "code" && isFencedCodeSource(markdown)) return chunkFeishuMarkdown(markdown, maxChars);
578
532
  const tableChunks = splitTableAtRow(markdown, root, target);
579
533
  if (tableChunks) return tableChunks;
580
534
  const containerType = root.children?.length === 1 ? root.children[0]?.type : void 0;
581
535
  if (containerType && STABLE_LINE_CONTAINER_TYPES.has(containerType)) {
582
- const containerOffset = nearestOffset(lineBreakOffsets(markdown), target, markdown.length).slice(0, MAX_BREAK_PROBES).find((offset) => isStableContainerBreak(markdown, offset, containerType));
536
+ const containerOffset = nearestOffset(lineBreakOffsets(markdown), target, markdown.length).slice(0, MAX_BREAK_PROBES).find((offset) => isStableBreak(markdown, offset, containerType));
583
537
  if (containerOffset !== void 0) return [markdown.slice(0, containerOffset), markdown.slice(containerOffset)];
584
538
  }
585
539
  return [markdown];
@@ -628,21 +582,6 @@ function resolveImageLocalPath(image) {
628
582
  if (unambiguousPath || absolutePath && existsSync(candidate)) return candidate;
629
583
  if (absolutePath) throw new Error(`File not found: "${candidate}". If you intended to pass image binary data, use a data URI instead: data:image/jpeg;base64,...`);
630
584
  }
631
- async function resolveRemoteUpload(input) {
632
- const fetched = await getFeishuRuntime().channel.media.readRemoteMediaBuffer({
633
- url: input.url,
634
- maxBytes: input.maxBytes,
635
- ...input.remoteReadTimeoutMs !== void 0 ? {
636
- responseHeaderTimeoutMs: input.remoteReadTimeoutMs,
637
- readIdleTimeoutMs: input.remoteReadTimeoutMs
638
- } : {}
639
- });
640
- const urlFileName = new URL(input.url).pathname.split("/").pop() || "upload.bin";
641
- return {
642
- buffer: fetched.buffer,
643
- fileName: input.fileName ?? fetched.fileName ?? urlFileName
644
- };
645
- }
646
585
  async function resolveDocxUploadInput(input) {
647
586
  const sources = [
648
587
  input.url && "url",
@@ -650,16 +589,27 @@ async function resolveDocxUploadInput(input) {
650
589
  input.image && "image"
651
590
  ].filter((source) => Boolean(source));
652
591
  if (sources.length !== 1) throw new Error(sources.length === 0 ? "Either url, file_path, or image (base64/data URI) must be provided" : `Provide only one upload source; got: ${sources.join(", ")}`);
653
- if (input.url) return await resolveRemoteUpload({
654
- ...input,
655
- url: input.url
656
- });
657
- if (input.filePath) return await resolveLocalUpload(input.filePath, input.maxBytes, input.localRoots, input.fileName);
592
+ if (input.url) {
593
+ const fetched = await getFeishuRuntime().channel.media.readRemoteMediaBuffer({
594
+ url: input.url,
595
+ maxBytes: input.maxBytes,
596
+ ...input.remoteReadTimeoutMs !== void 0 ? {
597
+ responseHeaderTimeoutMs: input.remoteReadTimeoutMs,
598
+ readIdleTimeoutMs: input.remoteReadTimeoutMs
599
+ } : {}
600
+ });
601
+ const urlFileName = new URL(input.url).pathname.split("/").pop() || "upload.bin";
602
+ return {
603
+ buffer: fetched.buffer,
604
+ fileName: input.fileName ?? fetched.fileName ?? urlFileName
605
+ };
606
+ }
607
+ if (input.filePath) return resolveLocalUpload(input.filePath, input.maxBytes, input.localRoots, input.fileName);
658
608
  const image = input.image;
659
609
  if (!image) throw new Error("Image input must not be empty");
660
610
  if (image.startsWith("data:")) return resolveDataUriImage(image, input.maxBytes, input.fileName);
661
611
  const localPath = resolveImageLocalPath(image);
662
- if (localPath) return await resolveLocalUpload(localPath, input.maxBytes, input.localRoots, input.fileName);
612
+ if (localPath) return resolveLocalUpload(localPath, input.maxBytes, input.localRoots, input.fileName);
663
613
  return {
664
614
  buffer: decodeBase64Image({
665
615
  payload: image,
@@ -754,9 +704,8 @@ function normalizeConvertedBlockTree(blocks, firstLevelIds) {
754
704
  rootIds: uniqueRootIds
755
705
  };
756
706
  }
757
- async function insertBlocks(client, docToken, blocks, parentBlockId) {
707
+ async function insertBlocks(client, docToken, blocks, blockId) {
758
708
  const cleaned = blocks.filter((block) => !UNSUPPORTED_CREATE_TYPES.has(block.block_type));
759
- const blockId = parentBlockId ?? docToken;
760
709
  const allInserted = [];
761
710
  for (const block of cleaned) {
762
711
  const res = await client.docx.documentBlockChildren.create({
@@ -771,50 +720,37 @@ async function insertBlocks(client, docToken, blocks, parentBlockId) {
771
720
  }
772
721
  return allInserted;
773
722
  }
774
- async function convertMarkdownWithFallback(client, chunk, depth = 0) {
775
- try {
776
- return {
777
- ...await convertMarkdown(client, chunk.markdown),
778
- images: chunk.images
779
- };
780
- } catch (error) {
781
- if (depth >= MAX_CONVERT_RETRY_DEPTH || chunk.markdown.length < 2) throw error;
782
- const splitTarget = Math.max(256, Math.floor(chunk.markdown.length / 2));
783
- const chunks = splitDocxMarkdownBySize(chunk.markdown, splitTarget).map(createDocxMarkdownChunk);
784
- if (chunks.length <= 1) throw error;
785
- const blocks = [];
786
- const firstLevelBlockIds = [];
787
- const images = [];
788
- for (const fallbackChunk of chunks) {
789
- const converted = await convertMarkdownWithFallback(client, fallbackChunk, depth + 1);
790
- blocks.push(...converted.blocks);
791
- firstLevelBlockIds.push(...converted.firstLevelBlockIds);
792
- images.push(...converted.images);
723
+ /** Convert markdown in chunks to avoid document.convert content size limits. */
724
+ async function chunkedConvertMarkdown(client, chunks, depth = 0) {
725
+ const result = {
726
+ blocks: [],
727
+ firstLevelBlockIds: [],
728
+ images: []
729
+ };
730
+ for (const chunk of chunks) {
731
+ let converted;
732
+ try {
733
+ converted = {
734
+ ...await convertMarkdown(client, chunk.markdown),
735
+ images: chunk.images
736
+ };
737
+ } catch (error) {
738
+ if (depth >= MAX_CONVERT_RETRY_DEPTH || chunk.markdown.length < 2) throw error;
739
+ const splitTarget = Math.max(256, Math.floor(chunk.markdown.length / 2));
740
+ const fallbackChunks = splitDocxMarkdownBySize(chunk.markdown, splitTarget).map(createDocxMarkdownChunk);
741
+ if (fallbackChunks.length <= 1) throw error;
742
+ converted = await chunkedConvertMarkdown(client, fallbackChunks, depth + 1);
793
743
  }
794
- return {
795
- blocks,
796
- firstLevelBlockIds,
797
- images
744
+ const { blocks, firstLevelBlockIds, images } = converted;
745
+ const { orderedBlocks, rootIds } = depth === 0 ? normalizeConvertedBlockTree(blocks, firstLevelBlockIds) : {
746
+ orderedBlocks: blocks,
747
+ rootIds: firstLevelBlockIds
798
748
  };
749
+ result.blocks.push(...orderedBlocks);
750
+ result.firstLevelBlockIds.push(...rootIds);
751
+ result.images.push(...images);
799
752
  }
800
- }
801
- /** Convert markdown in chunks to avoid document.convert content size limits */
802
- async function chunkedConvertMarkdown(client, chunks) {
803
- const allBlocks = [];
804
- const allRootIds = [];
805
- const allImages = [];
806
- for (const chunk of chunks) {
807
- const { blocks, firstLevelBlockIds, images } = await convertMarkdownWithFallback(client, chunk);
808
- const { orderedBlocks, rootIds } = normalizeConvertedBlockTree(blocks, firstLevelBlockIds);
809
- allBlocks.push(...orderedBlocks);
810
- allRootIds.push(...rootIds);
811
- allImages.push(...images);
812
- }
813
- return {
814
- blocks: allBlocks,
815
- firstLevelBlockIds: allRootIds,
816
- images: allImages
817
- };
753
+ return result;
818
754
  }
819
755
  async function deleteBlockChildren(client, docToken, parentId, startIndex, endIndex) {
820
756
  const res = await client.docx.documentBlockChildren.batchDelete({
@@ -829,6 +765,17 @@ async function deleteBlockChildren(client, docToken, parentId, startIndex, endIn
829
765
  });
830
766
  assertFeishuApiSuccess(res);
831
767
  }
768
+ async function deleteChildBlock(client, docToken, parentId, blockId) {
769
+ const children = await client.docx.documentBlockChildren.get({ path: {
770
+ document_id: docToken,
771
+ block_id: parentId
772
+ } });
773
+ assertFeishuApiSuccess(children);
774
+ const index = (children.data?.items ?? []).findIndex((item) => item.block_id === blockId);
775
+ if (index === -1) return false;
776
+ await deleteBlockChildren(client, docToken, parentId, index, index + 1);
777
+ return true;
778
+ }
832
779
  async function clearDocumentContent(client, docToken) {
833
780
  const existing = await client.docx.documentBlock.list({ path: { document_id: docToken } });
834
781
  assertFeishuApiSuccess(existing);
@@ -836,16 +783,28 @@ async function clearDocumentContent(client, docToken) {
836
783
  if (childIds.length > 0) await deleteBlockChildren(client, docToken, docToken, 0, childIds.length);
837
784
  return childIds.length;
838
785
  }
839
- async function uploadImageToDocx(client, blockId, imageBuffer, fileName, docToken) {
786
+ async function uploadDocxMedia(client, kind, parentNode, upload, docToken) {
840
787
  const fileToken = (await client.drive.media.uploadAll({ data: {
841
- file_name: fileName,
842
- parent_type: "docx_image",
843
- parent_node: blockId,
844
- size: imageBuffer.length,
845
- file: imageBuffer,
788
+ file_name: upload.fileName,
789
+ parent_type: kind === "image" ? "docx_image" : "docx_file",
790
+ parent_node: parentNode,
791
+ size: upload.buffer.length,
792
+ file: upload.buffer,
846
793
  ...docToken ? { extra: JSON.stringify({ drive_route_token: docToken }) } : {}
847
794
  } }))?.file_token;
848
- if (!fileToken) throw new Error("Image upload failed: no file_token returned");
795
+ if (!fileToken) throw new Error(`${kind === "image" ? "Image" : "File"} upload failed: no file_token returned`);
796
+ return fileToken;
797
+ }
798
+ async function uploadImageToDocx(client, blockId, upload, docToken) {
799
+ const fileToken = await uploadDocxMedia(client, "image", blockId, upload, docToken);
800
+ const patchRes = await client.docx.documentBlock.patch({
801
+ path: {
802
+ document_id: docToken,
803
+ block_id: blockId
804
+ },
805
+ data: { replace_image: { token: fileToken } }
806
+ });
807
+ assertFeishuApiSuccess(patchRes);
849
808
  return fileToken;
850
809
  }
851
810
  async function processImages(client, docToken, images, insertedBlocks, maxBytes, imageReadTimeoutMs) {
@@ -857,20 +816,11 @@ async function processImages(client, docToken, images, insertedBlocks, maxBytes,
857
816
  const blockId = imageBlocks[i]?.block_id;
858
817
  if (!url || !blockId) continue;
859
818
  try {
860
- const upload = await resolveDocxUploadInput({
819
+ await uploadImageToDocx(client, blockId, await resolveDocxUploadInput({
861
820
  url,
862
821
  maxBytes,
863
822
  remoteReadTimeoutMs: imageReadTimeoutMs
864
- });
865
- const fileToken = await uploadImageToDocx(client, blockId, upload.buffer, upload.fileName, docToken);
866
- const patchRes = await client.docx.documentBlock.patch({
867
- path: {
868
- document_id: docToken,
869
- block_id: blockId
870
- },
871
- data: { replace_image: { token: fileToken } }
872
- });
873
- assertFeishuApiSuccess(patchRes);
823
+ }), docToken);
874
824
  processed++;
875
825
  } catch (err) {
876
826
  console.error(`Failed to process image ${url}:`, err);
@@ -924,19 +874,10 @@ async function uploadImageBlock(client, { doc_token: docToken, parent_block_id:
924
874
  if (insertRes.code !== 0) throw new Error(`Failed to create image block: ${insertRes.msg}`);
925
875
  const imageBlockId = insertRes.data?.children?.find((b) => b.block_type === 27)?.block_id;
926
876
  if (!imageBlockId) throw new Error("Failed to create image block");
927
- const fileToken = await uploadImageToDocx(client, imageBlockId, upload.buffer, upload.fileName, docToken);
928
- const patchRes = await client.docx.documentBlock.patch({
929
- path: {
930
- document_id: docToken,
931
- block_id: imageBlockId
932
- },
933
- data: { replace_image: { token: fileToken } }
934
- });
935
- assertFeishuApiSuccess(patchRes);
936
877
  return {
937
878
  success: true,
938
879
  block_id: imageBlockId,
939
- file_token: fileToken,
880
+ file_token: await uploadImageToDocx(client, imageBlockId, upload, docToken),
940
881
  file_name: upload.fileName,
941
882
  size: upload.buffer.length
942
883
  };
@@ -947,25 +888,10 @@ async function uploadFileBlock(client, { doc_token: docToken, parent_block_id: p
947
888
  const { orderedBlocks } = normalizeConvertedBlockTree(converted.blocks, converted.firstLevelBlockIds);
948
889
  const placeholderBlock = (await insertBlocks(client, docToken, orderedBlocks, blockId))[0];
949
890
  if (!placeholderBlock?.block_id) throw new Error("Failed to create placeholder block for file upload");
950
- const parentId = placeholderBlock.parent_id ?? blockId;
951
- const childrenRes = await client.docx.documentBlockChildren.get({ path: {
952
- document_id: docToken,
953
- block_id: parentId
954
- } });
955
- assertFeishuApiSuccess(childrenRes);
956
- const placeholderIdx = (childrenRes.data?.items ?? []).findIndex((item) => item.block_id === placeholderBlock.block_id);
957
- if (placeholderIdx >= 0) await deleteBlockChildren(client, docToken, parentId, placeholderIdx, placeholderIdx + 1);
958
- const fileToken = (await client.drive.media.uploadAll({ data: {
959
- file_name: upload.fileName,
960
- parent_type: "docx_file",
961
- parent_node: docToken,
962
- size: upload.buffer.length,
963
- file: upload.buffer
964
- } }))?.file_token;
965
- if (!fileToken) throw new Error("File upload failed: no file_token returned");
891
+ await deleteChildBlock(client, docToken, placeholderBlock.parent_id ?? blockId, placeholderBlock.block_id);
966
892
  return {
967
893
  success: true,
968
- file_token: fileToken,
894
+ file_token: await uploadDocxMedia(client, "file", docToken, upload),
969
895
  file_name: upload.fileName,
970
896
  size: upload.buffer.length,
971
897
  note: "File uploaded to drive. Use the file_token to reference it. Direct file block creation is not supported by the Feishu API."
@@ -1008,41 +934,36 @@ async function readDoc(client, docToken) {
1008
934
  ...hint && { hint }
1009
935
  };
1010
936
  }
1011
- async function createDoc(client, title, folderToken, options) {
937
+ async function createDoc(client, params, requesterOpenId) {
1012
938
  const res = await client.docx.document.create({ data: {
1013
- title,
1014
- folder_token: folderToken
939
+ title: params.title,
940
+ folder_token: params.folder_token
1015
941
  } });
1016
942
  assertFeishuApiSuccess(res);
1017
943
  const doc = res.data?.document;
1018
944
  const docToken = doc?.document_id;
1019
945
  if (!docToken) throw new Error("Document creation succeeded but no document_id was returned");
1020
- const shouldGrantToRequester = options?.grantToRequester !== false;
1021
- const requesterOpenId = options?.requesterOpenId?.trim();
946
+ const shouldGrantToRequester = params.grant_to_requester !== false;
1022
947
  const requesterPermType = "edit";
1023
948
  let requesterPermissionAdded = false;
1024
- let requesterPermissionSkippedReason;
1025
949
  let requesterPermissionError;
1026
- if (shouldGrantToRequester) {
1027
- if (!requesterOpenId) requesterPermissionSkippedReason = "trusted requester identity unavailable";
1028
- else try {
1029
- const permissionRes = await client.drive.permissionMember.create({
1030
- path: { token: docToken },
1031
- params: {
1032
- type: "docx",
1033
- need_notification: false
1034
- },
1035
- data: {
1036
- member_type: "openid",
1037
- member_id: requesterOpenId,
1038
- perm: requesterPermType
1039
- }
1040
- });
1041
- assertFeishuApiSuccess(permissionRes);
1042
- requesterPermissionAdded = true;
1043
- } catch (err) {
1044
- requesterPermissionError = formatErrorMessage(err);
1045
- }
950
+ if (shouldGrantToRequester && requesterOpenId) try {
951
+ const permissionRes = await client.drive.permissionMember.create({
952
+ path: { token: docToken },
953
+ params: {
954
+ type: "docx",
955
+ need_notification: false
956
+ },
957
+ data: {
958
+ member_type: "openid",
959
+ member_id: requesterOpenId,
960
+ perm: requesterPermType
961
+ }
962
+ });
963
+ assertFeishuApiSuccess(permissionRes);
964
+ requesterPermissionAdded = true;
965
+ } catch (err) {
966
+ requesterPermissionError = formatErrorMessage(err);
1046
967
  }
1047
968
  return {
1048
969
  document_id: docToken,
@@ -1052,7 +973,7 @@ async function createDoc(client, title, folderToken, options) {
1052
973
  requester_permission_added: requesterPermissionAdded,
1053
974
  ...requesterOpenId && { requester_open_id: requesterOpenId },
1054
975
  requester_perm_type: requesterPermType,
1055
- ...requesterPermissionSkippedReason && { requester_permission_skipped_reason: requesterPermissionSkippedReason },
976
+ ...!requesterOpenId && { requester_permission_skipped_reason: "trusted requester identity unavailable" },
1056
977
  ...requesterPermissionError && { requester_permission_error: requesterPermissionError }
1057
978
  }
1058
979
  };
@@ -1168,42 +1089,6 @@ async function writeTableCells(client, docToken, tableBlockId, values) {
1168
1089
  }
1169
1090
  };
1170
1091
  }
1171
- async function updateBlock(client, docToken, blockId, content) {
1172
- await getBlock(client, docToken, blockId);
1173
- const res = await client.docx.documentBlock.patch({
1174
- path: {
1175
- document_id: docToken,
1176
- block_id: blockId
1177
- },
1178
- data: { update_text_elements: { elements: [{ text_run: { content } }] } }
1179
- });
1180
- assertFeishuApiSuccess(res);
1181
- return {
1182
- success: true,
1183
- block_id: blockId
1184
- };
1185
- }
1186
- async function deleteBlock(client, docToken, blockId) {
1187
- const { block } = await getBlock(client, docToken, blockId);
1188
- const parentId = block?.parent_id ?? docToken;
1189
- const children = await client.docx.documentBlockChildren.get({ path: {
1190
- document_id: docToken,
1191
- block_id: parentId
1192
- } });
1193
- assertFeishuApiSuccess(children);
1194
- const index = (children.data?.items ?? []).findIndex((item) => item.block_id === blockId);
1195
- if (index === -1) throw new Error("Block not found");
1196
- await deleteBlockChildren(client, docToken, parentId, index, index + 1);
1197
- return {
1198
- success: true,
1199
- deleted_block_id: blockId
1200
- };
1201
- }
1202
- async function listBlocks(client, docToken) {
1203
- const res = await client.docx.documentBlock.list({ path: { document_id: docToken } });
1204
- assertFeishuApiSuccess(res);
1205
- return { blocks: res.data?.items ?? [] };
1206
- }
1207
1092
  async function getBlock(client, docToken, blockId) {
1208
1093
  const res = await client.docx.documentBlock.get({ path: {
1209
1094
  document_id: docToken,
@@ -1212,24 +1097,6 @@ async function getBlock(client, docToken, blockId) {
1212
1097
  assertFeishuApiSuccess(res);
1213
1098
  return { block: res.data?.block };
1214
1099
  }
1215
- async function listAppScopes(client) {
1216
- const res = await client.application.scope.list({});
1217
- assertFeishuApiSuccess(res);
1218
- const scopes = res.data?.scopes ?? [];
1219
- const granted = scopes.filter((s) => s.grant_status === 1);
1220
- const pending = scopes.filter((s) => s.grant_status !== 1);
1221
- return {
1222
- granted: granted.map((s) => ({
1223
- name: s.scope_name,
1224
- type: s.scope_type
1225
- })),
1226
- pending: pending.map((s) => ({
1227
- name: s.scope_name,
1228
- type: s.scope_type
1229
- })),
1230
- summary: `${granted.length} granted, ${pending.length} pending`
1231
- };
1232
- }
1233
1100
  function registerFeishuDocTools(api) {
1234
1101
  registerFeishuTool(api, {
1235
1102
  family: "doc",
@@ -1260,14 +1127,37 @@ function registerFeishuDocTools(api) {
1260
1127
  case "write":
1261
1128
  case "append":
1262
1129
  case "insert": return feishuExternalToolResult(await editDoc(client, p, mediaMaxBytes, imageReadTimeoutMs, api.logger));
1263
- case "create": return feishuExternalToolResult(await createDoc(client, p.title, p.folder_token, {
1264
- grantToRequester: p.grant_to_requester,
1265
- requesterOpenId: trustedRequesterOpenId
1266
- }));
1267
- case "list_blocks": return feishuExternalToolResult(await listBlocks(client, p.doc_token));
1130
+ case "create": return feishuExternalToolResult(await createDoc(client, p, trustedRequesterOpenId));
1131
+ case "list_blocks": {
1132
+ const res = await client.docx.documentBlock.list({ path: { document_id: p.doc_token } });
1133
+ assertFeishuApiSuccess(res);
1134
+ return feishuExternalToolResult({ blocks: res.data?.items ?? [] });
1135
+ }
1268
1136
  case "get_block": return feishuExternalToolResult(await getBlock(client, p.doc_token, p.block_id));
1269
- case "update_block": return feishuExternalToolResult(await updateBlock(client, p.doc_token, p.block_id, p.content));
1270
- case "delete_block": return feishuExternalToolResult(await deleteBlock(client, p.doc_token, p.block_id));
1137
+ case "update_block": {
1138
+ await getBlock(client, p.doc_token, p.block_id);
1139
+ const res = await client.docx.documentBlock.patch({
1140
+ path: {
1141
+ document_id: p.doc_token,
1142
+ block_id: p.block_id
1143
+ },
1144
+ data: { update_text_elements: { elements: [{ text_run: { content: p.content } }] } }
1145
+ });
1146
+ assertFeishuApiSuccess(res);
1147
+ return feishuExternalToolResult({
1148
+ success: true,
1149
+ block_id: p.block_id
1150
+ });
1151
+ }
1152
+ case "delete_block": {
1153
+ const { block } = await getBlock(client, p.doc_token, p.block_id);
1154
+ const parentId = block?.parent_id ?? p.doc_token;
1155
+ if (!await deleteChildBlock(client, p.doc_token, parentId, p.block_id)) throw new Error("Block not found");
1156
+ return feishuExternalToolResult({
1157
+ success: true,
1158
+ deleted_block_id: p.block_id
1159
+ });
1160
+ }
1271
1161
  case "create_table":
1272
1162
  case "create_table_with_values": return feishuExternalToolResult(await createTable(client, p));
1273
1163
  case "write_table_cells": return feishuExternalToolResult(await writeTableCells(client, p.doc_token, p.table_block_id, p.values));
@@ -1305,15 +1195,29 @@ function registerFeishuDocTools(api) {
1305
1195
  parameters: Type.Object({}),
1306
1196
  createExecute(ctx, cfg) {
1307
1197
  return async (_params) => {
1308
- const result = await listAppScopes(createFeishuToolClient({
1198
+ const res = await createFeishuToolClient({
1309
1199
  cfg,
1310
1200
  defaultAccountId: ctx.agentAccountId,
1311
1201
  requiredTool: {
1312
1202
  family: "scopes",
1313
1203
  label: "App Scopes"
1314
1204
  }
1315
- }));
1316
- return feishuExternalToolResult(result);
1205
+ }).application.scope.list({});
1206
+ assertFeishuApiSuccess(res);
1207
+ const scopes = res.data?.scopes ?? [];
1208
+ const granted = scopes.filter((s) => s.grant_status === 1);
1209
+ const pending = scopes.filter((s) => s.grant_status !== 1);
1210
+ return feishuExternalToolResult({
1211
+ granted: granted.map((s) => ({
1212
+ name: s.scope_name,
1213
+ type: s.scope_type
1214
+ })),
1215
+ pending: pending.map((s) => ({
1216
+ name: s.scope_name,
1217
+ type: s.scope_type
1218
+ })),
1219
+ summary: `${granted.length} granted, ${pending.length} pending`
1220
+ });
1317
1221
  };
1318
1222
  }
1319
1223
  });
@@ -1758,63 +1662,53 @@ function isPlaceholderBitableRecord(fields) {
1758
1662
  async function cleanupNewBitable(client, appToken, tableId, tableName, logger) {
1759
1663
  let cleanedRows = 0;
1760
1664
  let cleanedFields = 0;
1761
- const fieldsRes = await client.bitable.appTableField.list({ path: {
1665
+ const tablePath = {
1762
1666
  app_token: appToken,
1763
1667
  table_id: tableId
1764
- } });
1668
+ };
1669
+ const fieldsRes = await client.bitable.appTableField.list({ path: tablePath });
1765
1670
  if (fieldsRes.code === 0 && fieldsRes.data?.items) {
1766
1671
  const primaryField = fieldsRes.data.items.find((f) => f.is_primary);
1767
- if (primaryField?.field_id) try {
1768
- ensureLarkSuccess(await client.bitable.appTableField.update({
1769
- path: {
1770
- app_token: appToken,
1771
- table_id: tableId,
1772
- field_id: primaryField.field_id
1773
- },
1774
- data: {
1775
- field_name: tableName.length <= 20 ? tableName : "Name",
1776
- type: 1
1777
- }
1778
- }), "bitable.appTableField.update");
1779
- cleanedFields++;
1780
- } catch (err) {
1781
- logger.debug(`Failed to rename primary field: ${String(err)}`);
1782
- }
1783
1672
  const defaultFieldsToDelete = fieldsRes.data.items.filter((f) => !f.is_primary && DEFAULT_CLEANUP_FIELD_TYPES.has(f.type ?? 0));
1784
- for (const field of defaultFieldsToDelete) if (field.field_id) try {
1785
- ensureLarkSuccess(await client.bitable.appTableField.delete({ path: {
1786
- app_token: appToken,
1787
- table_id: tableId,
1788
- field_id: field.field_id
1789
- } }), "bitable.appTableField.delete");
1790
- cleanedFields++;
1791
- } catch (err) {
1792
- logger.debug(`Failed to delete default field ${field.field_name}: ${String(err)}`);
1673
+ for (const field of [primaryField, ...defaultFieldsToDelete]) {
1674
+ if (!field?.field_id) continue;
1675
+ const isPrimary = field === primaryField;
1676
+ const operation = isPrimary ? "update" : "delete";
1677
+ try {
1678
+ const path = {
1679
+ ...tablePath,
1680
+ field_id: field.field_id
1681
+ };
1682
+ ensureLarkSuccess(isPrimary ? await client.bitable.appTableField.update({
1683
+ path,
1684
+ data: {
1685
+ field_name: tableName.length <= 20 ? tableName : "Name",
1686
+ type: 1
1687
+ }
1688
+ }) : await client.bitable.appTableField.delete({ path }), `bitable.appTableField.${operation}`);
1689
+ cleanedFields++;
1690
+ } catch (err) {
1691
+ const failure = isPrimary ? "rename primary field" : `delete default field ${field.field_name}`;
1692
+ logger.debug(`Failed to ${failure}: ${String(err)}`);
1693
+ }
1793
1694
  }
1794
1695
  }
1795
1696
  const recordsRes = await client.bitable.appTableRecord.list({
1796
- path: {
1797
- app_token: appToken,
1798
- table_id: tableId
1799
- },
1697
+ path: tablePath,
1800
1698
  params: { page_size: 100 }
1801
1699
  });
1802
1700
  if (recordsRes.code === 0 && recordsRes.data?.items) {
1803
1701
  const emptyRecordIds = recordsRes.data.items.filter((r) => isPlaceholderBitableRecord(r.fields)).map((r) => r.record_id).filter((id) => Boolean(id));
1804
1702
  if (emptyRecordIds.length > 0) try {
1805
1703
  ensureLarkSuccess(await client.bitable.appTableRecord.batchDelete({
1806
- path: {
1807
- app_token: appToken,
1808
- table_id: tableId
1809
- },
1704
+ path: tablePath,
1810
1705
  data: { records: emptyRecordIds }
1811
1706
  }), "bitable.appTableRecord.batchDelete");
1812
1707
  cleanedRows = emptyRecordIds.length;
1813
1708
  } catch {
1814
1709
  for (const recordId of emptyRecordIds) try {
1815
1710
  ensureLarkSuccess(await client.bitable.appTableRecord.delete({ path: {
1816
- app_token: appToken,
1817
- table_id: tableId,
1711
+ ...tablePath,
1818
1712
  record_id: recordId
1819
1713
  } }), "bitable.appTableRecord.delete");
1820
1714
  cleanedRows++;
@@ -1838,17 +1732,15 @@ async function createApp(client, name, folderToken, logger) {
1838
1732
  if (!appToken) throw new Error("Failed to create Bitable: no app_token returned");
1839
1733
  const log = logger ?? { debug: () => {} };
1840
1734
  let tableId;
1841
- let cleanedRows = 0;
1842
- let cleanedFields = 0;
1735
+ let cleanup = {
1736
+ cleanedRows: 0,
1737
+ cleanedFields: 0
1738
+ };
1843
1739
  try {
1844
1740
  const tablesRes = await client.bitable.appTable.list({ path: { app_token: appToken } });
1845
1741
  if (tablesRes.code === 0) {
1846
1742
  tableId = tablesRes.data?.items?.[0]?.table_id;
1847
- if (tableId) {
1848
- const cleanup = await cleanupNewBitable(client, appToken, tableId, name, log);
1849
- cleanedRows = cleanup.cleanedRows;
1850
- cleanedFields = cleanup.cleanedFields;
1851
- }
1743
+ if (tableId) cleanup = await cleanupNewBitable(client, appToken, tableId, name, log);
1852
1744
  }
1853
1745
  } catch (err) {
1854
1746
  log.debug(`Cleanup failed (non-critical): ${String(err)}`);
@@ -1858,8 +1750,8 @@ async function createApp(client, name, folderToken, logger) {
1858
1750
  table_id: tableId,
1859
1751
  name: res.data?.app?.name,
1860
1752
  url: res.data?.app?.url,
1861
- cleaned_placeholder_rows: cleanedRows,
1862
- cleaned_default_fields: cleanedFields,
1753
+ cleaned_placeholder_rows: cleanup.cleanedRows,
1754
+ cleaned_default_fields: cleanup.cleanedFields,
1863
1755
  hint: tableId ? `Table created. Use app_token="${appToken}" and table_id="${tableId}" for other bitable tools.` : "Application created, but table metadata was not retrieved. Inspect the existing application using the returned app_token or URL; do not create it again."
1864
1756
  };
1865
1757
  }