@dsh-ray/lark-channel 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (344) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +207 -2
  3. package/bin/dsh-lark-setup.js +37 -0
  4. package/bin/dsh-ray-setup.js +34 -0
  5. package/bin/dsh-supervised-growth-setup.js +34 -0
  6. package/cordis.patch.yml +23 -0
  7. package/docs/operations.md +133 -0
  8. package/docs/progress-security.md +125 -0
  9. package/docs/rsi-setup.md +216 -0
  10. package/docs/setup.md +358 -0
  11. package/docs/supervised-growth.md +95 -0
  12. package/lib/adapter.d.ts +185 -0
  13. package/lib/adapter.d.ts.map +1 -0
  14. package/lib/adapter.js +2072 -0
  15. package/lib/adapter.js.map +1 -0
  16. package/lib/answer-card.d.ts +40 -0
  17. package/lib/answer-card.d.ts.map +1 -0
  18. package/lib/answer-card.js +262 -0
  19. package/lib/answer-card.js.map +1 -0
  20. package/lib/approval.d.ts +26 -0
  21. package/lib/approval.d.ts.map +1 -0
  22. package/lib/approval.js +104 -0
  23. package/lib/approval.js.map +1 -0
  24. package/lib/business-cli-install.d.ts +9 -0
  25. package/lib/business-cli-install.d.ts.map +1 -0
  26. package/lib/business-cli-install.js +367 -0
  27. package/lib/business-cli-install.js.map +1 -0
  28. package/lib/business-environment.d.ts +2 -0
  29. package/lib/business-environment.d.ts.map +1 -0
  30. package/lib/business-environment.js +16 -0
  31. package/lib/business-environment.js.map +1 -0
  32. package/lib/business-skill.d.ts +32 -0
  33. package/lib/business-skill.d.ts.map +1 -0
  34. package/lib/business-skill.js +202 -0
  35. package/lib/business-skill.js.map +1 -0
  36. package/lib/command-card.d.ts +3 -0
  37. package/lib/command-card.d.ts.map +1 -0
  38. package/lib/command-card.js +480 -0
  39. package/lib/command-card.js.map +1 -0
  40. package/lib/config.d.ts +32 -0
  41. package/lib/config.d.ts.map +1 -0
  42. package/lib/config.js +115 -0
  43. package/lib/config.js.map +1 -0
  44. package/lib/group-thread.d.ts +20 -0
  45. package/lib/group-thread.d.ts.map +1 -0
  46. package/lib/group-thread.js +36 -0
  47. package/lib/group-thread.js.map +1 -0
  48. package/lib/index.d.ts +34 -0
  49. package/lib/index.d.ts.map +1 -0
  50. package/lib/index.js +53 -0
  51. package/lib/index.js.map +1 -0
  52. package/lib/launchd-control.d.ts +24 -0
  53. package/lib/launchd-control.d.ts.map +1 -0
  54. package/lib/launchd-control.js +68 -0
  55. package/lib/launchd-control.js.map +1 -0
  56. package/lib/launchd-identity.d.ts +34 -0
  57. package/lib/launchd-identity.d.ts.map +1 -0
  58. package/lib/launchd-identity.js +184 -0
  59. package/lib/launchd-identity.js.map +1 -0
  60. package/lib/launchd-target-lock.d.ts +6 -0
  61. package/lib/launchd-target-lock.d.ts.map +1 -0
  62. package/lib/launchd-target-lock.js +48 -0
  63. package/lib/launchd-target-lock.js.map +1 -0
  64. package/lib/launchd.d.ts +62 -0
  65. package/lib/launchd.d.ts.map +1 -0
  66. package/lib/launchd.js +370 -0
  67. package/lib/launchd.js.map +1 -0
  68. package/lib/model-picker.d.ts +24 -0
  69. package/lib/model-picker.d.ts.map +1 -0
  70. package/lib/model-picker.js +95 -0
  71. package/lib/model-picker.js.map +1 -0
  72. package/lib/normalize.d.ts +12 -0
  73. package/lib/normalize.d.ts.map +1 -0
  74. package/lib/normalize.js +85 -0
  75. package/lib/normalize.js.map +1 -0
  76. package/lib/permission-picker.d.ts +29 -0
  77. package/lib/permission-picker.d.ts.map +1 -0
  78. package/lib/permission-picker.js +145 -0
  79. package/lib/permission-picker.js.map +1 -0
  80. package/lib/progress.d.ts +34 -0
  81. package/lib/progress.d.ts.map +1 -0
  82. package/lib/progress.js +354 -0
  83. package/lib/progress.js.map +1 -0
  84. package/lib/resident.d.ts +13 -0
  85. package/lib/resident.d.ts.map +1 -0
  86. package/lib/resident.js +41 -0
  87. package/lib/resident.js.map +1 -0
  88. package/lib/rsi-authority-config.d.ts +29 -0
  89. package/lib/rsi-authority-config.d.ts.map +1 -0
  90. package/lib/rsi-authority-config.js +233 -0
  91. package/lib/rsi-authority-config.js.map +1 -0
  92. package/lib/rsi-authority-resources.d.ts +36 -0
  93. package/lib/rsi-authority-resources.d.ts.map +1 -0
  94. package/lib/rsi-authority-resources.js +139 -0
  95. package/lib/rsi-authority-resources.js.map +1 -0
  96. package/lib/rsi-authority-runtime.d.ts +51 -0
  97. package/lib/rsi-authority-runtime.d.ts.map +1 -0
  98. package/lib/rsi-authority-runtime.js +496 -0
  99. package/lib/rsi-authority-runtime.js.map +1 -0
  100. package/lib/rsi-bootstrap-manifest.d.ts +53 -0
  101. package/lib/rsi-bootstrap-manifest.d.ts.map +1 -0
  102. package/lib/rsi-bootstrap-manifest.js +507 -0
  103. package/lib/rsi-bootstrap-manifest.js.map +1 -0
  104. package/lib/rsi-bootstrap.d.ts +61 -0
  105. package/lib/rsi-bootstrap.d.ts.map +1 -0
  106. package/lib/rsi-bootstrap.js +597 -0
  107. package/lib/rsi-bootstrap.js.map +1 -0
  108. package/lib/rsi-build.d.ts +76 -0
  109. package/lib/rsi-build.d.ts.map +1 -0
  110. package/lib/rsi-build.js +210 -0
  111. package/lib/rsi-build.js.map +1 -0
  112. package/lib/rsi-host-authorities.d.ts +18 -0
  113. package/lib/rsi-host-authorities.d.ts.map +1 -0
  114. package/lib/rsi-host-authorities.js +129 -0
  115. package/lib/rsi-host-authorities.js.map +1 -0
  116. package/lib/rsi-host-update.d.ts +179 -0
  117. package/lib/rsi-host-update.d.ts.map +1 -0
  118. package/lib/rsi-host-update.js +568 -0
  119. package/lib/rsi-host-update.js.map +1 -0
  120. package/lib/rsi-install-inputs.d.ts +45 -0
  121. package/lib/rsi-install-inputs.d.ts.map +1 -0
  122. package/lib/rsi-install-inputs.js +345 -0
  123. package/lib/rsi-install-inputs.js.map +1 -0
  124. package/lib/rsi-install.d.ts +117 -0
  125. package/lib/rsi-install.d.ts.map +1 -0
  126. package/lib/rsi-install.js +791 -0
  127. package/lib/rsi-install.js.map +1 -0
  128. package/lib/rsi-linux-cgroup-roots.d.ts +3 -0
  129. package/lib/rsi-linux-cgroup-roots.d.ts.map +1 -0
  130. package/lib/rsi-linux-cgroup-roots.js +3 -0
  131. package/lib/rsi-linux-cgroup-roots.js.map +1 -0
  132. package/lib/rsi-linux-creation-build.d.ts +36 -0
  133. package/lib/rsi-linux-creation-build.d.ts.map +1 -0
  134. package/lib/rsi-linux-creation-build.js +213 -0
  135. package/lib/rsi-linux-creation-build.js.map +1 -0
  136. package/lib/rsi-linux-native-materialize.d.ts +31 -0
  137. package/lib/rsi-linux-native-materialize.d.ts.map +1 -0
  138. package/lib/rsi-linux-native-materialize.js +162 -0
  139. package/lib/rsi-linux-native-materialize.js.map +1 -0
  140. package/lib/rsi-linux-native-relocation.d.ts +124 -0
  141. package/lib/rsi-linux-native-relocation.d.ts.map +1 -0
  142. package/lib/rsi-linux-native-relocation.js +1571 -0
  143. package/lib/rsi-linux-native-relocation.js.map +1 -0
  144. package/lib/rsi-linux-native-resources.d.ts +97 -0
  145. package/lib/rsi-linux-native-resources.d.ts.map +1 -0
  146. package/lib/rsi-linux-native-resources.js +521 -0
  147. package/lib/rsi-linux-native-resources.js.map +1 -0
  148. package/lib/rsi-linux-repository-bootstrap.d.ts +17 -0
  149. package/lib/rsi-linux-repository-bootstrap.d.ts.map +1 -0
  150. package/lib/rsi-linux-repository-bootstrap.js +317 -0
  151. package/lib/rsi-linux-repository-bootstrap.js.map +1 -0
  152. package/lib/rsi-linux-runner-states.d.ts +20 -0
  153. package/lib/rsi-linux-runner-states.d.ts.map +1 -0
  154. package/lib/rsi-linux-runner-states.js +70 -0
  155. package/lib/rsi-linux-runner-states.js.map +1 -0
  156. package/lib/rsi-linux-runtime-bootstrap.d.ts +10 -0
  157. package/lib/rsi-linux-runtime-bootstrap.d.ts.map +1 -0
  158. package/lib/rsi-linux-runtime-bootstrap.js +38 -0
  159. package/lib/rsi-linux-runtime-bootstrap.js.map +1 -0
  160. package/lib/rsi-linux-source-build.d.ts +28 -0
  161. package/lib/rsi-linux-source-build.d.ts.map +1 -0
  162. package/lib/rsi-linux-source-build.js +43 -0
  163. package/lib/rsi-linux-source-build.js.map +1 -0
  164. package/lib/rsi-local-activation.d.ts +78 -0
  165. package/lib/rsi-local-activation.d.ts.map +1 -0
  166. package/lib/rsi-local-activation.js +486 -0
  167. package/lib/rsi-local-activation.js.map +1 -0
  168. package/lib/rsi-local-cohort.d.ts +70 -0
  169. package/lib/rsi-local-cohort.d.ts.map +1 -0
  170. package/lib/rsi-local-cohort.js +810 -0
  171. package/lib/rsi-local-cohort.js.map +1 -0
  172. package/lib/rsi-local-install.d.ts +70 -0
  173. package/lib/rsi-local-install.d.ts.map +1 -0
  174. package/lib/rsi-local-install.js +363 -0
  175. package/lib/rsi-local-install.js.map +1 -0
  176. package/lib/rsi-local-pair-install.d.ts +53 -0
  177. package/lib/rsi-local-pair-install.d.ts.map +1 -0
  178. package/lib/rsi-local-pair-install.js +215 -0
  179. package/lib/rsi-local-pair-install.js.map +1 -0
  180. package/lib/rsi-local-profile-update.d.ts +25 -0
  181. package/lib/rsi-local-profile-update.d.ts.map +1 -0
  182. package/lib/rsi-local-profile-update.js +226 -0
  183. package/lib/rsi-local-profile-update.js.map +1 -0
  184. package/lib/rsi-local-roots-extension.d.ts +11 -0
  185. package/lib/rsi-local-roots-extension.d.ts.map +1 -0
  186. package/lib/rsi-local-roots-extension.js +31 -0
  187. package/lib/rsi-local-roots-extension.js.map +1 -0
  188. package/lib/rsi-local-update-build.d.ts +37 -0
  189. package/lib/rsi-local-update-build.d.ts.map +1 -0
  190. package/lib/rsi-local-update-build.js +75 -0
  191. package/lib/rsi-local-update-build.js.map +1 -0
  192. package/lib/rsi-local-update.d.ts +39 -0
  193. package/lib/rsi-local-update.d.ts.map +1 -0
  194. package/lib/rsi-local-update.js +205 -0
  195. package/lib/rsi-local-update.js.map +1 -0
  196. package/lib/rsi-memory-learning.d.ts +36 -0
  197. package/lib/rsi-memory-learning.d.ts.map +1 -0
  198. package/lib/rsi-memory-learning.js +111 -0
  199. package/lib/rsi-memory-learning.js.map +1 -0
  200. package/lib/rsi-native-install.d.ts +38 -0
  201. package/lib/rsi-native-install.d.ts.map +1 -0
  202. package/lib/rsi-native-install.js +312 -0
  203. package/lib/rsi-native-install.js.map +1 -0
  204. package/lib/rsi-native-launchd.d.ts +7 -0
  205. package/lib/rsi-native-launchd.d.ts.map +1 -0
  206. package/lib/rsi-native-launchd.js +49 -0
  207. package/lib/rsi-native-launchd.js.map +1 -0
  208. package/lib/rsi-native-profile.d.ts +76 -0
  209. package/lib/rsi-native-profile.d.ts.map +1 -0
  210. package/lib/rsi-native-profile.js +530 -0
  211. package/lib/rsi-native-profile.js.map +1 -0
  212. package/lib/rsi-native-runtime-bootstrap.d.ts +44 -0
  213. package/lib/rsi-native-runtime-bootstrap.d.ts.map +1 -0
  214. package/lib/rsi-native-runtime-bootstrap.js +619 -0
  215. package/lib/rsi-native-runtime-bootstrap.js.map +1 -0
  216. package/lib/rsi-ordinary-use-learning.d.ts +60 -0
  217. package/lib/rsi-ordinary-use-learning.d.ts.map +1 -0
  218. package/lib/rsi-ordinary-use-learning.js +103 -0
  219. package/lib/rsi-ordinary-use-learning.js.map +1 -0
  220. package/lib/rsi-owner-profile.d.ts +37 -0
  221. package/lib/rsi-owner-profile.d.ts.map +1 -0
  222. package/lib/rsi-owner-profile.js +178 -0
  223. package/lib/rsi-owner-profile.js.map +1 -0
  224. package/lib/rsi-plugin-creation.d.ts +46 -0
  225. package/lib/rsi-plugin-creation.d.ts.map +1 -0
  226. package/lib/rsi-plugin-creation.js +227 -0
  227. package/lib/rsi-plugin-creation.js.map +1 -0
  228. package/lib/rsi-plugin-revision.d.ts +38 -0
  229. package/lib/rsi-plugin-revision.d.ts.map +1 -0
  230. package/lib/rsi-plugin-revision.js +221 -0
  231. package/lib/rsi-plugin-revision.js.map +1 -0
  232. package/lib/rsi-profile.d.ts +81 -0
  233. package/lib/rsi-profile.d.ts.map +1 -0
  234. package/lib/rsi-profile.js +551 -0
  235. package/lib/rsi-profile.js.map +1 -0
  236. package/lib/rsi-release-build.d.ts +59 -0
  237. package/lib/rsi-release-build.d.ts.map +1 -0
  238. package/lib/rsi-release-build.js +219 -0
  239. package/lib/rsi-release-build.js.map +1 -0
  240. package/lib/rsi-scanner-retirement-config.d.ts +34 -0
  241. package/lib/rsi-scanner-retirement-config.d.ts.map +1 -0
  242. package/lib/rsi-scanner-retirement-config.js +272 -0
  243. package/lib/rsi-scanner-retirement-config.js.map +1 -0
  244. package/lib/rsi-scanner-retirement-runtime.d.ts +23 -0
  245. package/lib/rsi-scanner-retirement-runtime.d.ts.map +1 -0
  246. package/lib/rsi-scanner-retirement-runtime.js +98 -0
  247. package/lib/rsi-scanner-retirement-runtime.js.map +1 -0
  248. package/lib/rsi-scanner-retirement-stage.d.ts +55 -0
  249. package/lib/rsi-scanner-retirement-stage.d.ts.map +1 -0
  250. package/lib/rsi-scanner-retirement-stage.js +181 -0
  251. package/lib/rsi-scanner-retirement-stage.js.map +1 -0
  252. package/lib/rsi-scanner-retirement-transition.d.ts +57 -0
  253. package/lib/rsi-scanner-retirement-transition.d.ts.map +1 -0
  254. package/lib/rsi-scanner-retirement-transition.js +330 -0
  255. package/lib/rsi-scanner-retirement-transition.js.map +1 -0
  256. package/lib/rsi-service-environment.d.ts +6 -0
  257. package/lib/rsi-service-environment.d.ts.map +1 -0
  258. package/lib/rsi-service-environment.js +113 -0
  259. package/lib/rsi-service-environment.js.map +1 -0
  260. package/lib/rsi-service-setup.d.ts +10 -0
  261. package/lib/rsi-service-setup.d.ts.map +1 -0
  262. package/lib/rsi-service-setup.js +34 -0
  263. package/lib/rsi-service-setup.js.map +1 -0
  264. package/lib/rsi-setup.d.ts +92 -0
  265. package/lib/rsi-setup.d.ts.map +1 -0
  266. package/lib/rsi-setup.js +908 -0
  267. package/lib/rsi-setup.js.map +1 -0
  268. package/lib/rsi-source-maintenance.d.ts +33 -0
  269. package/lib/rsi-source-maintenance.d.ts.map +1 -0
  270. package/lib/rsi-source-maintenance.js +407 -0
  271. package/lib/rsi-source-maintenance.js.map +1 -0
  272. package/lib/rsi-source-update.d.ts +26 -0
  273. package/lib/rsi-source-update.d.ts.map +1 -0
  274. package/lib/rsi-source-update.js +276 -0
  275. package/lib/rsi-source-update.js.map +1 -0
  276. package/lib/rsi-source.d.ts +34 -0
  277. package/lib/rsi-source.d.ts.map +1 -0
  278. package/lib/rsi-source.js +487 -0
  279. package/lib/rsi-source.js.map +1 -0
  280. package/lib/rsi-systemd-bootstrap.d.ts +46 -0
  281. package/lib/rsi-systemd-bootstrap.d.ts.map +1 -0
  282. package/lib/rsi-systemd-bootstrap.js +271 -0
  283. package/lib/rsi-systemd-bootstrap.js.map +1 -0
  284. package/lib/sdk.d.ts +216 -0
  285. package/lib/sdk.d.ts.map +1 -0
  286. package/lib/sdk.js +1990 -0
  287. package/lib/sdk.js.map +1 -0
  288. package/lib/service.d.ts +63 -0
  289. package/lib/service.d.ts.map +1 -0
  290. package/lib/service.js +599 -0
  291. package/lib/service.js.map +1 -0
  292. package/lib/setup-business.d.ts +49 -0
  293. package/lib/setup-business.d.ts.map +1 -0
  294. package/lib/setup-business.js +335 -0
  295. package/lib/setup-business.js.map +1 -0
  296. package/lib/setup-materialization.d.ts +15 -0
  297. package/lib/setup-materialization.d.ts.map +1 -0
  298. package/lib/setup-materialization.js +221 -0
  299. package/lib/setup-materialization.js.map +1 -0
  300. package/lib/setup-profile.d.ts +23 -0
  301. package/lib/setup-profile.d.ts.map +1 -0
  302. package/lib/setup-profile.js +1248 -0
  303. package/lib/setup-profile.js.map +1 -0
  304. package/lib/setup.d.ts +298 -0
  305. package/lib/setup.d.ts.map +1 -0
  306. package/lib/setup.js +3310 -0
  307. package/lib/setup.js.map +1 -0
  308. package/lib/supervised-growth-profile.d.ts +111 -0
  309. package/lib/supervised-growth-profile.d.ts.map +1 -0
  310. package/lib/supervised-growth-profile.js +903 -0
  311. package/lib/supervised-growth-profile.js.map +1 -0
  312. package/lib/supervised-growth-setup.d.ts +201 -0
  313. package/lib/supervised-growth-setup.d.ts.map +1 -0
  314. package/lib/supervised-growth-setup.js +1005 -0
  315. package/lib/supervised-growth-setup.js.map +1 -0
  316. package/lib/systemd.d.ts +70 -0
  317. package/lib/systemd.d.ts.map +1 -0
  318. package/lib/systemd.js +308 -0
  319. package/lib/systemd.js.map +1 -0
  320. package/lib/tool-approval.d.ts +22 -0
  321. package/lib/tool-approval.d.ts.map +1 -0
  322. package/lib/tool-approval.js +107 -0
  323. package/lib/tool-approval.js.map +1 -0
  324. package/lib/types.d.ts +351 -0
  325. package/lib/types.d.ts.map +1 -0
  326. package/lib/types.js +11 -0
  327. package/lib/types.js.map +1 -0
  328. package/lib/user-question.d.ts +31 -0
  329. package/lib/user-question.d.ts.map +1 -0
  330. package/lib/user-question.js +161 -0
  331. package/lib/user-question.js.map +1 -0
  332. package/lib/version.d.ts +2 -0
  333. package/lib/version.d.ts.map +1 -0
  334. package/lib/version.js +2 -0
  335. package/lib/version.js.map +1 -0
  336. package/lib/windows-task.d.ts +42 -0
  337. package/lib/windows-task.d.ts.map +1 -0
  338. package/lib/windows-task.js +143 -0
  339. package/lib/windows-task.js.map +1 -0
  340. package/lib/ws-card-callback.d.ts +7 -0
  341. package/lib/ws-card-callback.d.ts.map +1 -0
  342. package/lib/ws-card-callback.js +51 -0
  343. package/lib/ws-card-callback.js.map +1 -0
  344. package/package.json +169 -3
package/lib/sdk.js ADDED
@@ -0,0 +1,1990 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { Readable } from 'node:stream';
3
+ import { AppType, Client, defaultHttpInstance, Domain, EventDispatcher, LoggerLevel, WSClient, normalize, normalizeCardAction, } from '@larksuiteoapi/node-sdk';
4
+ import { LarkTransportError, } from './types.js';
5
+ import { renderLarkAnswerElements } from './answer-card.js';
6
+ import { installLarkCardCallbackBridge } from './ws-card-callback.js';
7
+ const LARK_PROGRESS_API = '/open-apis/im/v1/message_cot';
8
+ const LARK_MESSAGE_RESOURCE_API = '/open-apis/im/v1/messages';
9
+ const LARK_MESSAGE_API = '/open-apis/im/v1/messages';
10
+ const LARK_FILE_API = '/open-apis/im/v1/files';
11
+ const LARK_ERROR_BODY_MAX_BYTES = 16 * 1_024;
12
+ export const LARK_TEXT_FILE_MAX_BYTES = 1_048_576;
13
+ const LARK_FILE_UPLOAD_RESPONSE_MAX_BYTES = 65_536;
14
+ const LARK_FILE_UPLOAD_MULTIPART_OVERHEAD_BYTES = 4_096;
15
+ const larkResourceIdentifier = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,255}$/u;
16
+ const larkTextFileName = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
17
+ const LARK_READ_RECEIPT_ID_LIMIT = 100;
18
+ const LARK_READ_TIME = /^[0-9]{1,15}$/u;
19
+ /**
20
+ * Normalize the DM-only `im.message.message_read_v1` event.
21
+ *
22
+ * The SDK EventMap handler receives the event body directly; accept an
23
+ * `event` wrapper too so a webhook-normalized shape cannot silently become a
24
+ * read receipt for the wrong ids. Malformed/oversized events are ignored.
25
+ */
26
+ export function normalizeReadReceipt(raw) {
27
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
28
+ return null;
29
+ const outer = raw;
30
+ const nested = outer['event'];
31
+ const body = (nested !== null && typeof nested === 'object' && !Array.isArray(nested)
32
+ ? nested : outer);
33
+ const ids = body['message_id_list'];
34
+ if (!Array.isArray(ids) || ids.length === 0 || ids.length > LARK_READ_RECEIPT_ID_LIMIT)
35
+ return null;
36
+ const messageIds = new Set();
37
+ for (const id of ids) {
38
+ if (typeof id !== 'string' || !larkResourceIdentifier.test(id))
39
+ return null;
40
+ messageIds.add(id);
41
+ }
42
+ if (messageIds.size === 0)
43
+ return null;
44
+ const reader = body['reader'];
45
+ if (reader === null || typeof reader !== 'object' || Array.isArray(reader))
46
+ return null;
47
+ const readTime = reader['read_time'];
48
+ if (typeof readTime !== 'string' || !LARK_READ_TIME.test(readTime))
49
+ return null;
50
+ const readAt = Number(readTime);
51
+ if (!Number.isSafeInteger(readAt) || readAt < 0)
52
+ return null;
53
+ const readerId = reader['reader_id'];
54
+ const openId = readerId !== null && typeof readerId === 'object' && !Array.isArray(readerId)
55
+ ? readerId['open_id'] : undefined;
56
+ if (openId !== undefined && (typeof openId !== 'string' || !larkResourceIdentifier.test(openId)))
57
+ return null;
58
+ return Object.freeze({ messageIds: Object.freeze([...messageIds]), readAt,
59
+ ...(openId === undefined ? {} : { readerOpenId: openId }) });
60
+ }
61
+ class LarkImageResponseValidationError extends Error {
62
+ }
63
+ function imageResponseValidationError(message) {
64
+ return new LarkImageResponseValidationError(message);
65
+ }
66
+ function assertResourceIdentifier(value, field) {
67
+ if (!larkResourceIdentifier.test(value)) {
68
+ throw new Error(`lark-channel: invalid ${field} identifier`);
69
+ }
70
+ return value;
71
+ }
72
+ export function createLarkImageResourceRequest(messageId, fileKey, options) {
73
+ const message = assertResourceIdentifier(messageId, 'message');
74
+ const resource = assertResourceIdentifier(fileKey, 'image resource');
75
+ if (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1
76
+ || !Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1) {
77
+ throw new Error('lark-channel: invalid image resource request limits');
78
+ }
79
+ return {
80
+ method: 'GET',
81
+ url: `${LARK_MESSAGE_RESOURCE_API}/${encodeURIComponent(message)}/resources/${encodeURIComponent(resource)}`,
82
+ params: { type: 'image' },
83
+ responseType: 'stream',
84
+ timeout: options.timeoutMs,
85
+ signal: options.signal,
86
+ maxRedirects: 0,
87
+ maxContentLength: options.maxBytes,
88
+ maxBodyLength: options.maxBytes,
89
+ $return_headers: true,
90
+ };
91
+ }
92
+ function responseHeader(headers, name) {
93
+ if ('get' in headers && typeof headers.get === 'function')
94
+ return headers.get(name);
95
+ const record = headers;
96
+ const expected = name.toLowerCase();
97
+ for (const [header, value] of Object.entries(record)) {
98
+ if (header.toLowerCase() === expected)
99
+ return value;
100
+ }
101
+ return undefined;
102
+ }
103
+ function declaredContentLength(headers) {
104
+ const value = responseHeader(headers, 'content-length');
105
+ if (value === undefined)
106
+ return undefined;
107
+ const text = Array.isArray(value) ? value[0] : value;
108
+ if ((typeof text !== 'string' && typeof text !== 'number') || !/^\d+$/u.test(String(text))) {
109
+ throw imageResponseValidationError('lark-channel: invalid image resource content length');
110
+ }
111
+ const length = Number(text);
112
+ if (!Number.isSafeInteger(length)) {
113
+ throw imageResponseValidationError('lark-channel: invalid image resource content length');
114
+ }
115
+ return length;
116
+ }
117
+ function imageMediaType(data) {
118
+ if (data.length >= 8
119
+ && data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47
120
+ && data[4] === 0x0d && data[5] === 0x0a && data[6] === 0x1a && data[7] === 0x0a)
121
+ return 'image/png';
122
+ if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff)
123
+ return 'image/jpeg';
124
+ if (data.length >= 6) {
125
+ const signature = Buffer.from(data.subarray(0, 6)).toString('ascii');
126
+ if (signature === 'GIF87a' || signature === 'GIF89a')
127
+ return 'image/gif';
128
+ }
129
+ if (data.length >= 12
130
+ && Buffer.from(data.subarray(0, 4)).toString('ascii') === 'RIFF'
131
+ && Buffer.from(data.subarray(8, 12)).toString('ascii') === 'WEBP')
132
+ return 'image/webp';
133
+ return undefined;
134
+ }
135
+ function declaredImageMediaType(headers) {
136
+ const value = responseHeader(headers, 'content-type');
137
+ if (value === undefined)
138
+ return undefined;
139
+ if (typeof value !== 'string') {
140
+ throw imageResponseValidationError('lark-channel: invalid image resource content type');
141
+ }
142
+ const mediaType = value.split(';', 1)[0].trim().toLowerCase();
143
+ if (mediaType === 'application/octet-stream')
144
+ return undefined;
145
+ if (mediaType === 'image/gif' || mediaType === 'image/jpeg'
146
+ || mediaType === 'image/png' || mediaType === 'image/webp')
147
+ return mediaType;
148
+ throw imageResponseValidationError('lark-channel: unsupported image resource content type');
149
+ }
150
+ function abortReason(signal) {
151
+ return signal.reason instanceof Error ? signal.reason : new Error('lark-channel: image resource request aborted');
152
+ }
153
+ function boundedHttpOptions(options, hardTimeoutMs, lifecycleSignal) {
154
+ const source = options;
155
+ const requestedTimeout = source?.timeout;
156
+ const timeout = typeof requestedTimeout === 'number' && Number.isFinite(requestedTimeout) && requestedTimeout > 0
157
+ ? Math.min(requestedTimeout, hardTimeoutMs)
158
+ : hardTimeoutMs;
159
+ const hardTimeoutSignal = AbortSignal.timeout(hardTimeoutMs);
160
+ const signal = source?.signal === undefined
161
+ ? AbortSignal.any([hardTimeoutSignal, lifecycleSignal])
162
+ : AbortSignal.any([source.signal, hardTimeoutSignal, lifecycleSignal]);
163
+ return { ...source, timeout, signal };
164
+ }
165
+ function asSdkHttpResult(request) {
166
+ // The SDK's HttpInstance contract describes its response-interceptor output
167
+ // as R. Axios 1.19 leaves that conditional generic unresolved for arbitrary
168
+ // R even though defaultHttpInstance installs exactly that interceptor.
169
+ return request;
170
+ }
171
+ /**
172
+ * The SDK's token manager calls `httpInstance.post()` before the resource
173
+ * request exists, so request-local Axios limits cannot cover a cache miss.
174
+ * Keep each SDK client's complete HTTP stack bounded instead.
175
+ */
176
+ function boundedHttpInstance(hardTimeoutMs, lifecycleSignal) {
177
+ if (!Number.isSafeInteger(hardTimeoutMs) || hardTimeoutMs < 1) {
178
+ throw new Error('lark-channel: invalid HTTP timeout');
179
+ }
180
+ return {
181
+ request(options) {
182
+ return asSdkHttpResult(defaultHttpInstance.request(boundedHttpOptions(options, hardTimeoutMs, lifecycleSignal)));
183
+ },
184
+ get(url, options) {
185
+ return asSdkHttpResult(defaultHttpInstance.get(url, boundedHttpOptions(options, hardTimeoutMs, lifecycleSignal)));
186
+ },
187
+ delete(url, options) {
188
+ return asSdkHttpResult(defaultHttpInstance.delete(url, boundedHttpOptions(options, hardTimeoutMs, lifecycleSignal)));
189
+ },
190
+ head(url, options) {
191
+ return asSdkHttpResult(defaultHttpInstance.head(url, boundedHttpOptions(options, hardTimeoutMs, lifecycleSignal)));
192
+ },
193
+ options(url, options) {
194
+ return asSdkHttpResult(defaultHttpInstance.options(url, boundedHttpOptions(options, hardTimeoutMs, lifecycleSignal)));
195
+ },
196
+ post(url, data, options) {
197
+ return asSdkHttpResult(defaultHttpInstance.post(url, data, boundedHttpOptions(options, hardTimeoutMs, lifecycleSignal)));
198
+ },
199
+ put(url, data, options) {
200
+ return asSdkHttpResult(defaultHttpInstance.put(url, data, boundedHttpOptions(options, hardTimeoutMs, lifecycleSignal)));
201
+ },
202
+ patch(url, data, options) {
203
+ return asSdkHttpResult(defaultHttpInstance.patch(url, data, boundedHttpOptions(options, hardTimeoutMs, lifecycleSignal)));
204
+ },
205
+ };
206
+ }
207
+ /**
208
+ * The official SDK accepts an AbortSignal only on its low-level request API.
209
+ * Race every SDK operation locally as well: an SDK/token-manager promise that
210
+ * ignores that signal must never retain a Delivery lease past this deadline.
211
+ * A later transport rejection is deliberately observed and discarded.
212
+ */
213
+ function awaitBoundedSdkRequest(signal, request) {
214
+ return new Promise((resolve, reject) => {
215
+ let settled = false;
216
+ const finish = (complete) => {
217
+ if (settled)
218
+ return false;
219
+ settled = true;
220
+ signal.removeEventListener('abort', abort);
221
+ complete();
222
+ return true;
223
+ };
224
+ const abort = () => { finish(() => reject(abortReason(signal))); };
225
+ signal.addEventListener('abort', abort, { once: true });
226
+ if (signal.aborted) {
227
+ abort();
228
+ return;
229
+ }
230
+ let pending;
231
+ try {
232
+ pending = request();
233
+ }
234
+ catch (error) {
235
+ finish(() => reject(error));
236
+ return;
237
+ }
238
+ void pending.then(value => { finish(() => resolve(value)); }, error => { finish(() => reject(error)); });
239
+ });
240
+ }
241
+ function awaitImageResourceRequest(signal, request) {
242
+ return new Promise((resolve, reject) => {
243
+ let settled = false;
244
+ const finish = (complete) => {
245
+ if (settled)
246
+ return false;
247
+ settled = true;
248
+ signal.removeEventListener('abort', abort);
249
+ complete();
250
+ return true;
251
+ };
252
+ const abort = () => { finish(() => reject(abortReason(signal))); };
253
+ signal.addEventListener('abort', abort, { once: true });
254
+ if (signal.aborted) {
255
+ abort();
256
+ return;
257
+ }
258
+ let pending;
259
+ try {
260
+ pending = request();
261
+ }
262
+ catch (error) {
263
+ finish(() => reject(error));
264
+ return;
265
+ }
266
+ void pending.then(response => {
267
+ if (!finish(() => resolve(response)) && response.data instanceof Readable)
268
+ response.data.destroy();
269
+ }, error => {
270
+ // The outer abort is authoritative. This rejection handler intentionally
271
+ // consumes a later Axios/token failure so credential-bearing request
272
+ // metadata can never surface as an unhandled rejection.
273
+ finish(() => reject(error));
274
+ });
275
+ });
276
+ }
277
+ export async function readLarkImageResourceResponse(response, options) {
278
+ if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1) {
279
+ response.data.destroy();
280
+ throw imageResponseValidationError('lark-channel: invalid image resource byte limit');
281
+ }
282
+ if (options.signal.aborted) {
283
+ response.data.destroy();
284
+ throw abortReason(options.signal);
285
+ }
286
+ let declaredLength;
287
+ let declaredType;
288
+ try {
289
+ declaredLength = declaredContentLength(response.headers);
290
+ declaredType = declaredImageMediaType(response.headers);
291
+ }
292
+ catch (error) {
293
+ response.data.destroy();
294
+ throw error;
295
+ }
296
+ if (declaredLength !== undefined && declaredLength > options.maxBytes) {
297
+ response.data.destroy();
298
+ throw imageResponseValidationError('lark-channel: image resource exceeds its byte limit');
299
+ }
300
+ const chunks = [];
301
+ let bytes = 0;
302
+ const abort = () => response.data.destroy(abortReason(options.signal));
303
+ options.signal.addEventListener('abort', abort, { once: true });
304
+ try {
305
+ for await (const value of response.data) {
306
+ if (options.signal.aborted)
307
+ throw abortReason(options.signal);
308
+ if (!(value instanceof Uint8Array)) {
309
+ throw imageResponseValidationError('lark-channel: invalid image resource stream chunk');
310
+ }
311
+ bytes += value.byteLength;
312
+ if (bytes > options.maxBytes) {
313
+ response.data.destroy();
314
+ throw imageResponseValidationError('lark-channel: image resource exceeds its byte limit');
315
+ }
316
+ chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
317
+ }
318
+ }
319
+ catch (error) {
320
+ if (options.signal.aborted)
321
+ throw abortReason(options.signal);
322
+ throw error;
323
+ }
324
+ finally {
325
+ options.signal.removeEventListener('abort', abort);
326
+ }
327
+ if (options.signal.aborted)
328
+ throw abortReason(options.signal);
329
+ if (declaredLength !== undefined && declaredLength !== bytes) {
330
+ throw new Error('lark-channel: image resource length does not match its response header');
331
+ }
332
+ const data = new Uint8Array(Buffer.concat(chunks, bytes));
333
+ const detectedType = imageMediaType(data);
334
+ if (detectedType === undefined) {
335
+ throw imageResponseValidationError('lark-channel: image resource has an unsupported byte signature');
336
+ }
337
+ if (declaredType !== undefined && declaredType !== detectedType) {
338
+ throw imageResponseValidationError('lark-channel: image resource content type does not match its bytes');
339
+ }
340
+ if (options.signal.aborted)
341
+ throw abortReason(options.signal);
342
+ return { data, mediaType: detectedType };
343
+ }
344
+ /** Provider-safe UTF-8 budget for the complete serialized approval card. */
345
+ export const LARK_APPROVAL_CARD_MAX_BYTES = 28 * 1_024;
346
+ function providerFailureCode(code) {
347
+ if (code === 99991400 || code === 230020)
348
+ return 'rate_limited';
349
+ if (code === 230027 || code === 234009 || code === 99991663
350
+ || code === 99991672 || code === 99991676 || code === 99991679)
351
+ return 'permission_denied';
352
+ if (code === 200530 || code === 234001 || code === 234006
353
+ || code === 234007 || code === 234008 || code === 234011)
354
+ return 'format_error';
355
+ return undefined;
356
+ }
357
+ const silentLogger = {
358
+ error() { },
359
+ warn() { },
360
+ info() { },
361
+ debug() { },
362
+ trace() { },
363
+ };
364
+ const MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1_000;
365
+ function retryAfter(headers) {
366
+ const value = headers === undefined ? undefined : responseHeader(headers, 'retry-after');
367
+ const delaySeconds = typeof value === 'number' && Number.isSafeInteger(value)
368
+ ? value
369
+ : typeof value === 'string' && /^\d+$/.test(value.trim())
370
+ ? Number(value.trim())
371
+ : Number.NaN;
372
+ const delayMs = delaySeconds * 1_000;
373
+ return Number.isSafeInteger(delayMs) && delayMs >= 0 && delayMs <= MAX_RETRY_AFTER_MS
374
+ ? delayMs
375
+ : undefined;
376
+ }
377
+ export function classifyLarkSdkFailure(error) {
378
+ const shape = error !== null && typeof error === 'object' ? error : {};
379
+ const status = typeof shape.response?.status === 'number' ? shape.response.status : undefined;
380
+ if (status === 429) {
381
+ const delay = retryAfter(shape.response?.headers);
382
+ return { code: 'rate_limited', ...(delay === undefined ? {} : { retryAfterMs: delay }) };
383
+ }
384
+ const responseData = shape.response?.data;
385
+ const responseCode = responseData !== null && typeof responseData === 'object' && !Array.isArray(responseData)
386
+ ? responseData.code
387
+ : undefined;
388
+ const providerCode = providerFailureCode(responseCode) ?? providerFailureCode(shape.code);
389
+ if (providerCode !== undefined) {
390
+ const delay = providerCode === 'rate_limited' ? retryAfter(shape.response?.headers) : undefined;
391
+ return { code: providerCode, ...(delay === undefined ? {} : { retryAfterMs: delay }) };
392
+ }
393
+ if (status === 401 || status === 403)
394
+ return { code: 'permission_denied' };
395
+ if (status !== undefined && status >= 400 && status < 500)
396
+ return { code: 'format_error' };
397
+ if (shape.code === 'ETIMEDOUT' || shape.code === 'ECONNABORTED')
398
+ return { code: 'send_timeout' };
399
+ return { code: 'unknown' };
400
+ }
401
+ async function streamedProviderFailureCode(stream, signal) {
402
+ if (signal.aborted) {
403
+ stream.destroy();
404
+ return undefined;
405
+ }
406
+ const chunks = [];
407
+ let bytes = 0;
408
+ let exceeded = false;
409
+ const abort = () => stream.destroy();
410
+ signal.addEventListener('abort', abort, { once: true });
411
+ try {
412
+ for await (const value of stream) {
413
+ if (!(value instanceof Uint8Array)) {
414
+ stream.destroy();
415
+ return undefined;
416
+ }
417
+ bytes += value.byteLength;
418
+ if (bytes > LARK_ERROR_BODY_MAX_BYTES) {
419
+ exceeded = true;
420
+ stream.destroy();
421
+ break;
422
+ }
423
+ chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
424
+ }
425
+ }
426
+ catch {
427
+ return undefined;
428
+ }
429
+ finally {
430
+ signal.removeEventListener('abort', abort);
431
+ }
432
+ if (exceeded || signal.aborted)
433
+ return undefined;
434
+ try {
435
+ const value = JSON.parse(Buffer.concat(chunks, bytes).toString('utf8'));
436
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
437
+ ? value.code
438
+ : undefined;
439
+ }
440
+ catch {
441
+ return undefined;
442
+ }
443
+ }
444
+ export async function classifyLarkImageSdkFailure(error, signal) {
445
+ const shape = error !== null && typeof error === 'object' ? error : {};
446
+ const stream = shape.response?.data instanceof Readable ? shape.response.data : undefined;
447
+ if (stream === undefined)
448
+ return classifyLarkSdkFailure(error);
449
+ const status = typeof shape.response?.status === 'number' ? shape.response.status : undefined;
450
+ if (status !== 400) {
451
+ stream.destroy();
452
+ return classifyLarkSdkFailure(error);
453
+ }
454
+ const code = await streamedProviderFailureCode(stream, signal);
455
+ const classified = providerFailureCode(code);
456
+ if (classified === undefined)
457
+ return classifyLarkSdkFailure(error);
458
+ const delay = classified === 'rate_limited' ? retryAfter(shape.response?.headers) : undefined;
459
+ return { code: classified, ...(delay === undefined ? {} : { retryAfterMs: delay }) };
460
+ }
461
+ export function larkRequestUuid(idempotencyKey) {
462
+ return createHash('sha256').update(idempotencyKey).digest('hex').slice(0, 32);
463
+ }
464
+ export function createLarkProgressRequest(chatId, options, signal) {
465
+ return {
466
+ method: 'POST',
467
+ url: `${LARK_PROGRESS_API}?receive_id_type=chat_id`,
468
+ data: {
469
+ receive_id: chatId,
470
+ origin_message_id: options.replyTo,
471
+ cot_hidden: options.hidden,
472
+ enable_badge: false,
473
+ update_feed_rank: false,
474
+ },
475
+ ...(signal === undefined ? {} : { signal }),
476
+ };
477
+ }
478
+ export function writeLarkProgressRequest(handle, events, signal) {
479
+ return {
480
+ method: 'PUT',
481
+ url: LARK_PROGRESS_API,
482
+ data: {
483
+ cot_id: handle.cotId,
484
+ message_id: handle.messageId,
485
+ events: events.map(event => ({
486
+ event_type: event.eventType,
487
+ content: event.content,
488
+ timestamp: event.timestamp,
489
+ })),
490
+ },
491
+ ...(signal === undefined ? {} : { signal }),
492
+ };
493
+ }
494
+ export function createLarkTextFileUploadRequest(input) {
495
+ const maxBytes = input.maxBytes ?? LARK_TEXT_FILE_MAX_BYTES;
496
+ if (!Number.isSafeInteger(input.timeoutMs) || input.timeoutMs < 1
497
+ || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > LARK_TEXT_FILE_MAX_BYTES) {
498
+ throw new LarkTransportError('format_error', 'lark-channel: invalid text file upload limits');
499
+ }
500
+ if (typeof input.name !== 'string' || !larkTextFileName.test(input.name) || input.name.includes('..')) {
501
+ throw new LarkTransportError('format_error', 'lark-channel: invalid text file attachment name');
502
+ }
503
+ if (input.mediaType !== 'text/plain' && input.mediaType !== 'text/markdown') {
504
+ throw new LarkTransportError('format_error', 'lark-channel: unsupported text file attachment media type');
505
+ }
506
+ if (typeof input.text !== 'string' || input.text.length === 0) {
507
+ throw new LarkTransportError('format_error', 'lark-channel: text file attachment must be non-empty');
508
+ }
509
+ const file = Buffer.from(input.text, 'utf8');
510
+ if (file.byteLength === 0 || file.byteLength > maxBytes) {
511
+ throw new LarkTransportError('format_error', 'lark-channel: text file attachment exceeds byte limit');
512
+ }
513
+ return {
514
+ method: 'POST',
515
+ url: LARK_FILE_API,
516
+ headers: { 'Content-Type': 'multipart/form-data' },
517
+ data: {
518
+ file_type: 'stream',
519
+ file_name: input.name,
520
+ file,
521
+ },
522
+ timeout: input.timeoutMs,
523
+ signal: input.signal,
524
+ maxRedirects: 0,
525
+ maxContentLength: LARK_FILE_UPLOAD_RESPONSE_MAX_BYTES,
526
+ maxBodyLength: file.byteLength + LARK_FILE_UPLOAD_MULTIPART_OVERHEAD_BYTES,
527
+ };
528
+ }
529
+ function createLarkMessageSendRequest(chatId, rendered, uuid, options, signal) {
530
+ if (options.replyTo === undefined) {
531
+ return {
532
+ method: 'POST',
533
+ url: LARK_MESSAGE_API,
534
+ params: { receive_id_type: 'chat_id' },
535
+ data: { receive_id: chatId, msg_type: rendered.msgType, content: rendered.content, uuid },
536
+ ...(signal === undefined ? {} : { signal }),
537
+ };
538
+ }
539
+ const replyTo = assertResourceIdentifier(options.replyTo, 'reply message');
540
+ return {
541
+ method: 'POST',
542
+ url: `${LARK_MESSAGE_API}/${encodeURIComponent(replyTo)}/reply`,
543
+ data: {
544
+ msg_type: rendered.msgType,
545
+ content: rendered.content,
546
+ uuid,
547
+ ...(options.replyInThread === undefined ? {} : { reply_in_thread: options.replyInThread }),
548
+ },
549
+ ...(signal === undefined ? {} : { signal }),
550
+ };
551
+ }
552
+ export function createLarkFileMessageRequest(chatId, fileKey, options = {}, signal) {
553
+ const rendered = renderLarkMessage({ fileKey });
554
+ const uuid = larkRequestUuid(options.requestKey ?? `${chatId}:${rendered.content}`);
555
+ return createLarkMessageSendRequest(chatId, rendered, uuid, options, signal ?? options.signal);
556
+ }
557
+ function createLarkReactionRequest(messageId, emojiType, signal) {
558
+ const message = assertResourceIdentifier(messageId, 'message');
559
+ return {
560
+ method: 'POST',
561
+ url: `${LARK_MESSAGE_API}/${encodeURIComponent(message)}/reactions`,
562
+ data: { reaction_type: { emoji_type: emojiType } },
563
+ signal,
564
+ };
565
+ }
566
+ export function createLarkRawCardUpdateRequest(messageId, card, signal) {
567
+ const message = assertResourceIdentifier(messageId, 'message');
568
+ return {
569
+ method: 'PATCH',
570
+ url: `${LARK_MESSAGE_API}/${encodeURIComponent(message)}`,
571
+ data: { content: JSON.stringify(card) },
572
+ signal,
573
+ };
574
+ }
575
+ export const LARK_MODEL_PICKER_CONTROLS = Object.freeze({
576
+ provider: 'model_provider',
577
+ model: 'model_route',
578
+ effort: 'model_effort',
579
+ confirm: 'model_confirm',
580
+ });
581
+ export const LARK_PERMISSION_PICKER_CONTROLS = Object.freeze({
582
+ ask: 'permission_ask',
583
+ auto: 'permission_auto',
584
+ full: 'permission_full',
585
+ });
586
+ function surfaceContainer(tone, elements, padding = '12px 12px 12px 12px', verticalSpacing = '6px') {
587
+ return {
588
+ tag: 'interactive_container',
589
+ behaviors: [],
590
+ width: 'fill',
591
+ corner_radius: '8px',
592
+ has_border: true,
593
+ border_color: `${tone}-200`,
594
+ background_style: `${tone}-50`,
595
+ padding,
596
+ direction: 'vertical',
597
+ vertical_spacing: verticalSpacing,
598
+ elements,
599
+ };
600
+ }
601
+ function equalButtonColumnSet(left, right) {
602
+ return {
603
+ tag: 'column_set',
604
+ flex_mode: 'bisect',
605
+ horizontal_spacing: '8px',
606
+ columns: [
607
+ { tag: 'column', width: 'weighted', weight: 1, elements: [left] },
608
+ { tag: 'column', width: 'weighted', weight: 1, elements: [right] },
609
+ ],
610
+ };
611
+ }
612
+ export function renderLarkMessage(input) {
613
+ if ('text' in input)
614
+ return { msgType: 'text', content: JSON.stringify({ text: input.text }) };
615
+ if ('fileKey' in input) {
616
+ if (typeof input.fileKey !== 'string' || !larkResourceIdentifier.test(input.fileKey)) {
617
+ throw new LarkTransportError('format_error', 'lark-channel: invalid file identifier');
618
+ }
619
+ return { msgType: 'file', content: JSON.stringify({ file_key: input.fileKey }) };
620
+ }
621
+ if ('commandCard' in input) {
622
+ const card = input.commandCard;
623
+ const elements = [];
624
+ if (card.metrics !== undefined && card.metrics.length > 0) {
625
+ elements.push({
626
+ tag: 'column_set',
627
+ flex_mode: 'bisect',
628
+ horizontal_spacing: '8px',
629
+ columns: card.metrics.map(metric => ({
630
+ tag: 'column',
631
+ width: 'weighted',
632
+ weight: 1,
633
+ background_style: 'grey-50',
634
+ padding: '10px 12px 10px 12px',
635
+ direction: 'vertical',
636
+ vertical_spacing: '4px',
637
+ elements: [
638
+ { tag: 'div', text_size: 'notation', text: { tag: 'plain_text', content: metric.label, text_color: 'grey' } },
639
+ { tag: 'div', text: { tag: 'plain_text', content: metric.value } },
640
+ ],
641
+ })),
642
+ });
643
+ }
644
+ for (const section of card.sections) {
645
+ const tone = section.tone ?? 'grey';
646
+ const sectionElements = [];
647
+ if (section.heading !== undefined) {
648
+ sectionElements.push({
649
+ tag: 'markdown',
650
+ content: tone === 'grey'
651
+ ? `**${section.heading}**`
652
+ : `**<font color='${tone}'>${section.heading}</font>**`,
653
+ text_align: 'left',
654
+ });
655
+ }
656
+ for (const item of section.items) {
657
+ if (item.kind === 'markdown') {
658
+ sectionElements.push({ tag: 'markdown', content: item.content, text_align: 'left' });
659
+ }
660
+ else {
661
+ sectionElements.push({
662
+ tag: 'div',
663
+ ...(item.notation ? { text_size: 'notation' } : {}),
664
+ text: {
665
+ tag: 'plain_text',
666
+ content: item.content,
667
+ ...(item.notation ? { text_color: 'grey' } : {}),
668
+ },
669
+ });
670
+ }
671
+ }
672
+ if (sectionElements.length > 0) {
673
+ elements.push(surfaceContainer(tone, sectionElements));
674
+ }
675
+ }
676
+ if (card.footer !== undefined) {
677
+ elements.push({
678
+ tag: 'div',
679
+ text_size: 'notation',
680
+ icon: { tag: 'standard_icon', token: 'info_outlined', color: 'grey' },
681
+ text: { tag: 'plain_text', content: card.footer, text_color: 'grey' },
682
+ });
683
+ }
684
+ return {
685
+ msgType: 'interactive',
686
+ content: JSON.stringify({
687
+ schema: '2.0',
688
+ config: {
689
+ compact_width: false,
690
+ width_mode: 'fill',
691
+ summary: { content: card.summary },
692
+ },
693
+ header: {
694
+ template: card.template,
695
+ title: { tag: 'plain_text', content: card.title },
696
+ ...(card.subtitle === undefined ? {} : { subtitle: { tag: 'plain_text', content: card.subtitle } }),
697
+ icon: { tag: 'standard_icon', token: card.iconToken },
698
+ },
699
+ body: {
700
+ padding: '12px 12px 16px 12px',
701
+ direction: 'vertical',
702
+ vertical_spacing: '8px',
703
+ elements,
704
+ },
705
+ }),
706
+ };
707
+ }
708
+ if ('userQuestion' in input) {
709
+ const question = input.userQuestion;
710
+ const optionButton = (option, index) => {
711
+ const markers = [
712
+ ...(question.multiSelect && option.selected === true ? ['✓ 已选'] : []),
713
+ ...(option.recommended === true ? ['推荐'] : []),
714
+ ];
715
+ const value = option.value;
716
+ return {
717
+ tag: 'button',
718
+ name: `user_question_option_${index + 1}`,
719
+ type: option.recommended === true || (question.multiSelect && option.selected === true)
720
+ ? 'primary'
721
+ : 'default',
722
+ width: 'fill',
723
+ text: { tag: 'plain_text', content: markers.length === 0
724
+ ? option.label
725
+ : `${markers.join(' · ')}:${option.label}` },
726
+ value,
727
+ behaviors: [{ type: 'callback', value }],
728
+ };
729
+ };
730
+ const submitButton = question.submitValue === undefined
731
+ ? undefined
732
+ : {
733
+ tag: 'button',
734
+ name: 'user_question_submit',
735
+ type: 'primary',
736
+ width: 'fill',
737
+ icon: { tag: 'standard_icon', token: 'done_outlined' },
738
+ text: { tag: 'plain_text', content: question.multiSelect ? '提交已选答案' : '提交答案' },
739
+ value: question.submitValue,
740
+ behaviors: [{ type: 'callback', value: question.submitValue }],
741
+ };
742
+ const cancelButton = question.cancelValue === undefined
743
+ ? undefined
744
+ : {
745
+ tag: 'button',
746
+ name: 'user_question_cancel',
747
+ type: 'default',
748
+ width: 'fill',
749
+ icon: { tag: 'standard_icon', token: 'close_outlined' },
750
+ text: { tag: 'plain_text', content: '取消本次问题' },
751
+ value: question.cancelValue,
752
+ behaviors: [{ type: 'callback', value: question.cancelValue }],
753
+ };
754
+ const questionSurface = surfaceContainer('blue', [
755
+ { tag: 'div', text: { tag: 'plain_text', content: question.question } },
756
+ ...(question.detail === undefined ? [] : [
757
+ { tag: 'div', text_size: 'notation', text: { tag: 'plain_text', content: question.detail, text_color: 'grey' } },
758
+ ]),
759
+ ...(question.expectsText ? [{
760
+ tag: 'div',
761
+ text_size: 'notation',
762
+ icon: { tag: 'standard_icon', token: 'edit_outlined', color: 'blue' },
763
+ text: { tag: 'plain_text', content: '如需输入其他答案,请直接回复这张问题卡片。', text_color: 'blue' },
764
+ }] : []),
765
+ ]);
766
+ const answeredElements = question.answered === undefined || question.answered.length === 0
767
+ ? []
768
+ : [surfaceContainer('grey', question.answered.map(answered => ({
769
+ tag: 'div',
770
+ text_size: 'notation',
771
+ text: { tag: 'plain_text', content: `已答摘要:${answered.title}:${answered.answer}`, text_color: 'grey' },
772
+ })), '10px 12px 10px 12px', '4px')];
773
+ const optionElements = question.options.map((option, index) => {
774
+ const button = optionButton(option, index);
775
+ if (option.description === undefined)
776
+ return button;
777
+ return surfaceContainer('grey', [
778
+ { tag: 'div', text_size: 'notation', text: { tag: 'plain_text', content: option.description, text_color: 'grey' } },
779
+ button,
780
+ ], '10px 12px 10px 12px', '6px');
781
+ });
782
+ const actionElements = submitButton !== undefined && cancelButton !== undefined
783
+ ? [equalButtonColumnSet(submitButton, cancelButton)]
784
+ : [
785
+ ...(submitButton === undefined ? [] : [submitButton]),
786
+ ...(cancelButton === undefined ? [] : [cancelButton]),
787
+ ];
788
+ return {
789
+ msgType: 'interactive',
790
+ content: JSON.stringify({
791
+ schema: '2.0',
792
+ config: {
793
+ update_multi: true,
794
+ enable_forward_interaction: false,
795
+ summary: { content: '智能体正在等待您的选择或补充回答' },
796
+ },
797
+ header: {
798
+ template: 'blue',
799
+ title: { tag: 'plain_text', content: question.title },
800
+ subtitle: { tag: 'plain_text', content: `问题 ${question.position} / ${question.total}` },
801
+ icon: { tag: 'standard_icon', token: 'chat_outlined' },
802
+ },
803
+ body: {
804
+ padding: '12px 12px 16px 12px',
805
+ direction: 'vertical',
806
+ vertical_spacing: '8px',
807
+ elements: [
808
+ questionSurface,
809
+ ...answeredElements,
810
+ ...optionElements,
811
+ ...actionElements,
812
+ ],
813
+ },
814
+ }),
815
+ };
816
+ }
817
+ if ('userQuestionResult' in input) {
818
+ const result = input.userQuestionResult;
819
+ const presentation = {
820
+ answered: {
821
+ template: 'green',
822
+ icon: 'done_outlined',
823
+ title: '已收到您的回答',
824
+ detail: '回答已交给智能体,正在继续处理。',
825
+ summary: '智能体已收到您的回答并将继续处理',
826
+ },
827
+ cancelled: {
828
+ template: 'grey',
829
+ icon: 'close_outlined',
830
+ title: '本次问题已取消',
831
+ detail: '该问题已取消,智能体不会继续等待此回答。',
832
+ summary: '本次问题已取消,智能体不再等待回答',
833
+ },
834
+ resolved: {
835
+ template: 'blue',
836
+ icon: 'info_outlined',
837
+ title: '本次问题已处理',
838
+ detail: '该问题已在其他已授权终端完成处理。',
839
+ summary: '本次问题已由已授权终端处理完成',
840
+ },
841
+ }[result.status];
842
+ return {
843
+ msgType: 'interactive',
844
+ content: JSON.stringify({
845
+ schema: '2.0',
846
+ config: {
847
+ update_multi: true,
848
+ enable_forward_interaction: false,
849
+ summary: { content: presentation.summary },
850
+ },
851
+ header: {
852
+ template: presentation.template,
853
+ title: { tag: 'plain_text', content: presentation.title },
854
+ subtitle: { tag: 'plain_text', content: presentation.detail },
855
+ icon: { tag: 'standard_icon', token: presentation.icon },
856
+ },
857
+ body: {
858
+ padding: '12px 12px 16px 12px',
859
+ direction: 'vertical',
860
+ vertical_spacing: '8px',
861
+ elements: [
862
+ surfaceContainer(presentation.template, [
863
+ { tag: 'div', text: { tag: 'plain_text', content: result.summary } },
864
+ ]),
865
+ ],
866
+ },
867
+ }),
868
+ };
869
+ }
870
+ if ('permissionPicker' in input) {
871
+ const picker = input.permissionPicker;
872
+ const level = (key, label, description) => {
873
+ const current = picker.current === key;
874
+ const value = picker.callbackValues[key];
875
+ const full = key === 'full';
876
+ const tone = full ? 'orange' : current ? 'blue' : 'grey';
877
+ const titleMarkdown = full
878
+ ? `**<font color='orange'>${current ? '✓ ' : ''}${label}</font>**`
879
+ : current
880
+ ? `**<font color='blue'>✓ ${label}</font>**`
881
+ : `**${label}**`;
882
+ return surfaceContainer(tone, [
883
+ { tag: 'markdown', content: titleMarkdown, text_align: 'left' },
884
+ { tag: 'markdown', content: `<font color='grey'>${description}</font>`, text_size: 'notation', text_align: 'left' },
885
+ {
886
+ tag: 'button',
887
+ name: LARK_PERMISSION_PICKER_CONTROLS[key],
888
+ type: full ? 'danger' : current ? 'primary' : 'default',
889
+ width: 'fill',
890
+ icon: { tag: 'standard_icon', token: full ? 'warning_outlined' : current ? 'done_outlined' : 'safe_outlined' },
891
+ text: { tag: 'plain_text', content: current ? '✓ 当前档位' : '选择此档位' },
892
+ value,
893
+ behaviors: [{ type: 'callback', value }],
894
+ ...(full ? { confirm: {
895
+ title: { tag: 'plain_text', content: '确认开启完全访问权限?' },
896
+ text: { tag: 'plain_text', content: '开启后可访问互联网和电脑上的任何文件,并关闭逐次审批。' },
897
+ } } : {}),
898
+ },
899
+ ]);
900
+ };
901
+ return {
902
+ msgType: 'interactive',
903
+ content: JSON.stringify({
904
+ schema: '2.0',
905
+ config: {
906
+ enable_forward_interaction: false,
907
+ summary: { content: '请选择当前会话的运行权限模式' },
908
+ },
909
+ header: {
910
+ template: 'blue',
911
+ title: { tag: 'plain_text', content: picker.title },
912
+ subtitle: { tag: 'plain_text', content: picker.body },
913
+ icon: { tag: 'standard_icon', token: 'safe_outlined' },
914
+ },
915
+ body: {
916
+ padding: '12px 12px 16px 12px',
917
+ direction: 'vertical',
918
+ vertical_spacing: '8px',
919
+ elements: [
920
+ level('ask', '请求批准(ask)', '编辑外部文件和使用互联网时始终询问'),
921
+ level('auto', '帮我批准(auto)', '仅对检测到的风险操作请求批准'),
922
+ level('full', '完全访问权限(full)', '不受限制地访问互联网和电脑上的任何文件,并关闭逐次审批'),
923
+ ],
924
+ },
925
+ }),
926
+ };
927
+ }
928
+ if ('modelSelectionResult' in input) {
929
+ const result = input.modelSelectionResult;
930
+ const presentation = result.status === 'pending'
931
+ ? {
932
+ template: 'blue',
933
+ color: 'blue',
934
+ background: 'blue-50',
935
+ title: '模型选择已提交',
936
+ subtitle: '正在验证;验证成功后将从下一条消息生效,并保留当前上下文。',
937
+ summary: '模型选择已提交,正在验证中',
938
+ }
939
+ : result.status === 'selected'
940
+ ? {
941
+ template: 'green',
942
+ color: 'green',
943
+ background: 'green-50',
944
+ title: '模型切换成功',
945
+ subtitle: '已完成验证;下一条消息起生效,并保留当前上下文。',
946
+ summary: '模型切换已生效,下一条消息启用',
947
+ }
948
+ : {
949
+ template: 'orange',
950
+ color: 'orange',
951
+ background: 'orange-50',
952
+ title: '模型切换未生效',
953
+ subtitle: result.explanation,
954
+ summary: '模型切换未生效,请查看说明详情',
955
+ };
956
+ const field = (label, value) => ({
957
+ tag: 'column',
958
+ width: 'weighted',
959
+ weight: 1,
960
+ background_style: presentation.background,
961
+ padding: '12px 12px 12px 12px',
962
+ direction: 'vertical',
963
+ vertical_spacing: '4px',
964
+ elements: [
965
+ { tag: 'markdown', content: `**<font color='${presentation.color}'>${label}</font>**`, text_align: 'left' },
966
+ { tag: 'div', text: { tag: 'plain_text', content: value } },
967
+ ],
968
+ });
969
+ return {
970
+ msgType: 'interactive',
971
+ content: JSON.stringify({
972
+ schema: '2.0',
973
+ config: {
974
+ compact_width: false,
975
+ update_multi: true,
976
+ enable_forward_interaction: false,
977
+ summary: { content: presentation.summary },
978
+ },
979
+ header: {
980
+ template: presentation.template,
981
+ title: { tag: 'plain_text', content: presentation.title },
982
+ subtitle: { tag: 'plain_text', content: presentation.subtitle },
983
+ icon: { tag: 'standard_icon', token: 'myai_colorful' },
984
+ },
985
+ body: {
986
+ padding: '12px 12px 16px 12px',
987
+ elements: [{
988
+ tag: 'column_set',
989
+ flex_mode: 'flow',
990
+ horizontal_spacing: '8px',
991
+ columns: [
992
+ field('Provider', result.provider),
993
+ field('模型', result.model),
994
+ field('Effort', result.effort),
995
+ ],
996
+ }],
997
+ },
998
+ }),
999
+ };
1000
+ }
1001
+ if ('modelPicker' in input) {
1002
+ const picker = input.modelPicker;
1003
+ const callback = (action) => picker.callbackValues[action];
1004
+ const select = (name, placeholder, options, initial, action) => {
1005
+ const value = callback(action);
1006
+ // Lark resolves `initial_option` against the option's displayed text, not its
1007
+ // callback value, so a route-shaped or synthetic initial value never matches and
1008
+ // the client silently falls back to the first option. Address the selection by its
1009
+ // 1-based `initial_index`, and only add the textual form when that label identifies
1010
+ // exactly one option, because `initial_option` overrides `initial_index`. An initial
1011
+ // value absent from `options` preselects nothing.
1012
+ const selected = initial === undefined
1013
+ ? -1
1014
+ : options.findIndex(option => option.value === initial);
1015
+ const label = selected < 0 ? undefined : options[selected].label;
1016
+ const unambiguous = label !== undefined
1017
+ && options.filter(option => option.label === label).length === 1;
1018
+ return {
1019
+ tag: 'select_static',
1020
+ name,
1021
+ width: 'fill',
1022
+ placeholder: { tag: 'plain_text', content: placeholder },
1023
+ options: options.map(option => ({
1024
+ text: { tag: 'plain_text', content: option.label },
1025
+ value: option.value,
1026
+ })),
1027
+ value,
1028
+ behaviors: [{ type: 'callback', value }],
1029
+ ...(selected < 0 ? {} : { initial_index: selected + 1 }),
1030
+ ...(unambiguous ? { initial_option: label } : {}),
1031
+ };
1032
+ };
1033
+ const confirmValue = callback('confirm');
1034
+ // Layout follows the card style guide: header carries "what this is" (title + subtitle + icon),
1035
+ // each of the three selects sits in its own bordered surface so the groups read as blocks
1036
+ // instead of a flat run of markdown labels, and the single primary button is the only focus.
1037
+ const field = (label, hint, control, last = false) => ({
1038
+ tag: 'interactive_container',
1039
+ behaviors: [],
1040
+ width: 'fill',
1041
+ corner_radius: '8px',
1042
+ has_border: true,
1043
+ border_color: 'blue-100',
1044
+ background_style: 'blue-50',
1045
+ padding: '12px 12px 12px 12px',
1046
+ direction: 'vertical',
1047
+ vertical_spacing: '4px',
1048
+ // A trailing container keeps no bottom margin, so the card does not end on dead space.
1049
+ margin: last ? '0px 0px 12px 0px' : '0px 0px 8px 0px',
1050
+ elements: [
1051
+ { tag: 'markdown', content: `**<font color='blue'>${label}</font>**`, text_align: 'left' },
1052
+ { tag: 'markdown', content: `<font color='grey'>${hint}</font>`, text_size: 'notation', text_align: 'left' },
1053
+ control,
1054
+ ],
1055
+ });
1056
+ return {
1057
+ msgType: 'interactive',
1058
+ content: JSON.stringify({
1059
+ schema: '2.0',
1060
+ config: {
1061
+ update_multi: true,
1062
+ enable_forward_interaction: false,
1063
+ summary: { content: '请选择当前会话使用的模型路由与档位' },
1064
+ },
1065
+ header: {
1066
+ template: 'blue',
1067
+ title: { tag: 'plain_text', content: picker.title },
1068
+ subtitle: { tag: 'plain_text', content: picker.body },
1069
+ icon: { tag: 'standard_icon', token: 'myai_colorful' },
1070
+ },
1071
+ body: { padding: '12px 12px 20px 12px', elements: [
1072
+ field('分组 / Provider', '先选分组,模型与 effort 会随之更新', select(LARK_MODEL_PICKER_CONTROLS.provider, '请选择模型分组', picker.providerOptions, picker.initialProvider, 'provider')),
1073
+ field('模型', '该分组下当前可用的模型', select(LARK_MODEL_PICKER_CONTROLS.model, '请选择模型', picker.modelOptions, picker.initialModel, 'model')),
1074
+ field('Effort 程度', '仅对支持 effort 档位的模型生效', select(LARK_MODEL_PICKER_CONTROLS.effort, '请选择 effort', picker.effortOptions, picker.initialEffort, 'effort'), true),
1075
+ { tag: 'button', name: LARK_MODEL_PICKER_CONTROLS.confirm, type: 'primary', width: 'fill',
1076
+ icon: { tag: 'standard_icon', token: 'done_outlined' },
1077
+ text: { tag: 'plain_text', content: '确认选择' }, value: confirmValue,
1078
+ behaviors: [{ type: 'callback', value: confirmValue }] },
1079
+ ] },
1080
+ }),
1081
+ };
1082
+ }
1083
+ if ('approval' in input) {
1084
+ const fieldLabels = {
1085
+ op: '变更类型',
1086
+ ruleId: '规则 ID',
1087
+ scopeKey: '作用域',
1088
+ situation: '适用情境',
1089
+ guidance: '建议行为',
1090
+ generation: '规则代次',
1091
+ expectedVersion: '预期版本',
1092
+ reason: '变更原因',
1093
+ evaluation: '效果评估',
1094
+ baseline: '采纳前基线',
1095
+ evidence: '证据',
1096
+ };
1097
+ const operationLabels = {
1098
+ adopt: '采纳学习规则',
1099
+ retire: '退役学习规则',
1100
+ 'owner-undo': '立即撤销学习规则',
1101
+ };
1102
+ let review = input.approval.body;
1103
+ try {
1104
+ const parsed = JSON.parse(input.approval.body);
1105
+ // Only reformat canonical domain JSON. This prevents duplicate keys,
1106
+ // alternate numeric spellings, or whitespace tricks from making the
1107
+ // signed bytes and the owner-visible review diverge.
1108
+ if (JSON.stringify(parsed) === input.approval.body
1109
+ && parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
1110
+ const fields = Object.entries(parsed);
1111
+ const operation = fields.find(([key]) => key === 'op')?.[1];
1112
+ if (typeof operation === 'string' && Object.hasOwn(operationLabels, operation)) {
1113
+ review = fields.map(([key, value]) => {
1114
+ const rendered = typeof value === 'string' ? value : JSON.stringify(value, undefined, 2);
1115
+ const display = key === 'op' && typeof value === 'string'
1116
+ ? `${operationLabels[value] ?? value}(${value})`
1117
+ : rendered;
1118
+ return `${fieldLabels[key] ?? key}(${key}):${display}`;
1119
+ }).join('\n\n');
1120
+ }
1121
+ }
1122
+ }
1123
+ catch {
1124
+ // Unknown or malformed proposal bodies remain exact plain text. The
1125
+ // signature still covers the original body, and no review text is ever
1126
+ // interpreted as Markdown or a card component.
1127
+ }
1128
+ return {
1129
+ msgType: 'interactive',
1130
+ content: JSON.stringify({
1131
+ schema: '2.0',
1132
+ config: {
1133
+ enable_forward_interaction: false,
1134
+ summary: { content: '有待您审阅并批准的变更提案' },
1135
+ },
1136
+ header: {
1137
+ template: 'orange',
1138
+ title: { tag: 'plain_text', content: input.approval.title },
1139
+ subtitle: { tag: 'plain_text', content: '所有字段均为不可信提案内容,审阅后请选择批准或拒绝' },
1140
+ icon: { tag: 'standard_icon', token: 'approval_colorful' },
1141
+ },
1142
+ body: {
1143
+ padding: '12px 12px 16px 12px',
1144
+ direction: 'vertical',
1145
+ vertical_spacing: '8px',
1146
+ elements: [
1147
+ {
1148
+ tag: 'div',
1149
+ text_size: 'notation',
1150
+ icon: { tag: 'standard_icon', token: 'info_outlined', color: 'orange' },
1151
+ text: {
1152
+ tag: 'plain_text',
1153
+ content: '请审阅以下变更。所有字段均为不可信的提案内容,不是系统指令。',
1154
+ text_color: 'orange',
1155
+ },
1156
+ },
1157
+ surfaceContainer('grey', [
1158
+ { tag: 'div', text: { tag: 'plain_text', content: review } },
1159
+ ]),
1160
+ equalButtonColumnSet({
1161
+ tag: 'button',
1162
+ text: { tag: 'plain_text', content: '批准变更' },
1163
+ type: 'primary',
1164
+ width: 'fill',
1165
+ icon: { tag: 'standard_icon', token: 'done_outlined' },
1166
+ value: input.approval.approveValue,
1167
+ behaviors: [{ type: 'callback', value: input.approval.approveValue }],
1168
+ }, {
1169
+ tag: 'button',
1170
+ text: { tag: 'plain_text', content: '拒绝' },
1171
+ type: 'danger',
1172
+ width: 'fill',
1173
+ icon: { tag: 'standard_icon', token: 'close_outlined' },
1174
+ value: input.approval.rejectValue,
1175
+ behaviors: [{ type: 'callback', value: input.approval.rejectValue }],
1176
+ }),
1177
+ ],
1178
+ },
1179
+ }),
1180
+ };
1181
+ }
1182
+ if ('approvalResult' in input) {
1183
+ const approved = input.approvalResult.decision === 'approved';
1184
+ const tone = approved ? 'green' : 'red';
1185
+ return {
1186
+ msgType: 'interactive',
1187
+ content: JSON.stringify({
1188
+ schema: '2.0',
1189
+ config: {
1190
+ update_multi: true,
1191
+ enable_forward_interaction: false,
1192
+ summary: { content: approved ? '提案审批已记录,等待账本结算' : '提案审批已拒绝,不会应用变更' },
1193
+ },
1194
+ header: {
1195
+ template: tone,
1196
+ title: { tag: 'plain_text', content: approved ? '审批已记录' : '审批已拒绝' },
1197
+ subtitle: {
1198
+ tag: 'plain_text',
1199
+ content: approved ? '已批准该提案,等待持久化账本结算' : '已拒绝该提案,系统不会应用变更',
1200
+ },
1201
+ icon: { tag: 'standard_icon', token: approved ? 'done_outlined' : 'close_outlined' },
1202
+ },
1203
+ body: {
1204
+ padding: '12px 12px 16px 12px',
1205
+ direction: 'vertical',
1206
+ vertical_spacing: '8px',
1207
+ elements: [
1208
+ surfaceContainer(tone, [
1209
+ {
1210
+ tag: 'div',
1211
+ text: {
1212
+ tag: 'plain_text',
1213
+ content: approved
1214
+ ? '已批准该提案。系统将按持久化账本完成结算;此回执不表示变更已经生效。'
1215
+ : '已拒绝该提案,系统不会应用这项变更。',
1216
+ },
1217
+ },
1218
+ { tag: 'div', text: { tag: 'plain_text', content: `提案 ID:${input.approvalResult.proposalId}` } },
1219
+ ]),
1220
+ ],
1221
+ },
1222
+ }),
1223
+ };
1224
+ }
1225
+ if ('approvalApplication' in input) {
1226
+ const terminal = input.approvalApplication;
1227
+ const presentation = {
1228
+ applied: {
1229
+ template: 'green',
1230
+ icon: 'done_outlined',
1231
+ title: '变更已实际生效',
1232
+ detail: '领域账本已完成原子结算。',
1233
+ summary: '变更已实际生效,领域账本已完成结算',
1234
+ },
1235
+ conflicted: {
1236
+ template: 'yellow',
1237
+ icon: 'warning_outlined',
1238
+ title: '变更未生效:证据或状态冲突',
1239
+ detail: '审批决定已记录,但领域账本拒绝应用过期或冲突的变更。',
1240
+ summary: '变更未生效:证据或状态存在冲突',
1241
+ },
1242
+ expired: {
1243
+ template: 'grey',
1244
+ icon: 'time_outlined',
1245
+ title: '变更未生效:审批已过期',
1246
+ detail: '该提案已经过期,领域账本没有应用变更。',
1247
+ summary: '变更未生效:该提案审批已过期',
1248
+ },
1249
+ rejected: {
1250
+ template: 'red',
1251
+ icon: 'close_outlined',
1252
+ title: '变更已拒绝',
1253
+ detail: 'owner 已拒绝该提案,领域账本没有应用变更。',
1254
+ summary: '变更已拒绝,领域账本未应用变更',
1255
+ },
1256
+ }[terminal.status];
1257
+ const operation = {
1258
+ adopt: '采纳学习规则',
1259
+ retire: '退役学习规则',
1260
+ 'owner-undo': '撤销学习规则',
1261
+ }[terminal.operation];
1262
+ const exactRule = terminal.ruleId === undefined
1263
+ ? []
1264
+ : [
1265
+ { tag: 'div', text: { tag: 'plain_text', content: `规则 ID:${terminal.ruleId}` } },
1266
+ ...(terminal.resultingRuleVersion === undefined ? [] : [{
1267
+ tag: 'div',
1268
+ text: {
1269
+ tag: 'plain_text',
1270
+ content: `规则版本:${terminal.resultingRuleVersion};状态:${terminal.ruleStatus ?? '未知'}`,
1271
+ },
1272
+ }]),
1273
+ ];
1274
+ const undo = terminal.status === 'applied' && terminal.operation === 'adopt'
1275
+ && terminal.ruleId !== undefined && terminal.resultingRuleVersion !== undefined
1276
+ ? [{
1277
+ tag: 'div',
1278
+ text_size: 'notation',
1279
+ icon: { tag: 'standard_icon', token: 'info_outlined', color: 'grey' },
1280
+ text: {
1281
+ tag: 'plain_text',
1282
+ content: `可撤销入口:在当前 owner 会话中要求“撤销规则 ${terminal.ruleId} 版本 ${terminal.resultingRuleVersion}”。系统只会创建一张独立的二次审批,不会直接退役规则。`,
1283
+ text_color: 'grey',
1284
+ },
1285
+ }]
1286
+ : [];
1287
+ return {
1288
+ msgType: 'interactive',
1289
+ content: JSON.stringify({
1290
+ schema: '2.0',
1291
+ config: {
1292
+ update_multi: true,
1293
+ enable_forward_interaction: false,
1294
+ summary: { content: presentation.summary },
1295
+ },
1296
+ header: {
1297
+ template: presentation.template,
1298
+ title: { tag: 'plain_text', content: presentation.title },
1299
+ subtitle: { tag: 'plain_text', content: presentation.detail },
1300
+ icon: { tag: 'standard_icon', token: presentation.icon },
1301
+ },
1302
+ body: {
1303
+ padding: '12px 12px 16px 12px',
1304
+ direction: 'vertical',
1305
+ vertical_spacing: '8px',
1306
+ elements: [
1307
+ surfaceContainer('grey', [
1308
+ { tag: 'div', text: { tag: 'plain_text', content: `操作:${operation}(${terminal.operation})` } },
1309
+ { tag: 'div', text: { tag: 'plain_text', content: `Policy 提案:${terminal.policyProposalId}` } },
1310
+ { tag: 'div', text: { tag: 'plain_text', content: `领域提案:${terminal.localProposalId}` } },
1311
+ ...exactRule,
1312
+ ]),
1313
+ ...undo,
1314
+ ],
1315
+ },
1316
+ }),
1317
+ };
1318
+ }
1319
+ if ('automationIncident' in input) {
1320
+ const incident = input.automationIncident;
1321
+ const state = {
1322
+ open: {
1323
+ template: 'red',
1324
+ icon: 'warning_outlined',
1325
+ title: '自动化故障已打开',
1326
+ detail: '该自动化仍处于故障状态。',
1327
+ summary: '自动化故障已打开,仍处于故障状态',
1328
+ },
1329
+ recovering: {
1330
+ template: 'blue',
1331
+ icon: 'refresh_outlined',
1332
+ title: '自动化故障恢复中',
1333
+ detail: '已启动受控探针,尚未确认恢复。',
1334
+ summary: '自动化故障恢复中,受控探针运行中',
1335
+ },
1336
+ resolved: {
1337
+ template: 'green',
1338
+ icon: 'done_outlined',
1339
+ title: '自动化故障已恢复',
1340
+ detail: '同一故障代次已通过实际运行确认恢复。',
1341
+ summary: '自动化故障已恢复,运行验证已通过',
1342
+ },
1343
+ }[incident.state];
1344
+ return {
1345
+ msgType: 'interactive',
1346
+ content: JSON.stringify({
1347
+ schema: '2.0',
1348
+ config: {
1349
+ update_multi: true,
1350
+ enable_forward_interaction: false,
1351
+ summary: { content: state.summary },
1352
+ },
1353
+ header: {
1354
+ template: state.template,
1355
+ title: { tag: 'plain_text', content: state.title },
1356
+ subtitle: { tag: 'plain_text', content: state.detail },
1357
+ icon: { tag: 'standard_icon', token: state.icon },
1358
+ },
1359
+ body: {
1360
+ padding: '12px 12px 16px 12px',
1361
+ direction: 'vertical',
1362
+ vertical_spacing: '8px',
1363
+ elements: [
1364
+ surfaceContainer('grey', [
1365
+ { tag: 'div', text: { tag: 'plain_text', content: `自动化:${incident.automationId}` } },
1366
+ {
1367
+ tag: 'div',
1368
+ text: {
1369
+ tag: 'plain_text',
1370
+ content: `阶段:${incident.stage};故障:${incident.failureCode}(${incident.failureClass}/${incident.failurePhase})`,
1371
+ },
1372
+ },
1373
+ {
1374
+ tag: 'div',
1375
+ text: {
1376
+ tag: 'plain_text',
1377
+ content: `副作用:${incident.sideEffectState};重试:${incident.retryability}`,
1378
+ },
1379
+ },
1380
+ ]),
1381
+ {
1382
+ tag: 'div',
1383
+ text_size: 'notation',
1384
+ icon: { tag: 'standard_icon', token: 'info_outlined', color: 'grey' },
1385
+ text: {
1386
+ tag: 'plain_text',
1387
+ content: `Incident ${incident.incidentId} · generation ${incident.lifecycleGeneration} · revision ${incident.incidentRevision}`,
1388
+ text_color: 'grey',
1389
+ },
1390
+ },
1391
+ ],
1392
+ },
1393
+ }),
1394
+ };
1395
+ }
1396
+ if ('toolApprovalResult' in input) {
1397
+ const result = input.toolApprovalResult;
1398
+ const presentation = {
1399
+ 'allowed-once': {
1400
+ template: 'green',
1401
+ icon: 'done_outlined',
1402
+ title: '已允许本次操作,任务继续中',
1403
+ detail: '本次授权已生效。工具执行结果将在任务后续消息中提供。',
1404
+ summary: '已允许本次操作,任务继续中',
1405
+ },
1406
+ rejected: {
1407
+ template: 'red',
1408
+ icon: 'close_outlined',
1409
+ title: '已拒绝本次操作',
1410
+ detail: '本次审批未授权工具执行。',
1411
+ summary: '已拒绝本次工具调用授权',
1412
+ },
1413
+ cancelled: {
1414
+ template: 'grey',
1415
+ icon: 'info_outlined',
1416
+ title: '本次审批已取消',
1417
+ detail: '本次审批未授权工具执行,已停止等待确认。',
1418
+ summary: '本次工具审批已取消',
1419
+ },
1420
+ expired: {
1421
+ template: 'grey',
1422
+ icon: 'time_outlined',
1423
+ title: '本次审批已超时',
1424
+ detail: '有效期已过,本次审批未授权工具执行。',
1425
+ summary: '本次工具审批已超时',
1426
+ },
1427
+ unavailable: {
1428
+ template: 'grey',
1429
+ icon: 'info_outlined',
1430
+ title: '本次审批已结束',
1431
+ detail: '会话或连接已结束,本次审批未授权工具执行。',
1432
+ summary: '本次工具审批已结束',
1433
+ },
1434
+ }[result.status];
1435
+ return {
1436
+ msgType: 'interactive',
1437
+ content: JSON.stringify({
1438
+ schema: '2.0',
1439
+ config: {
1440
+ update_multi: true,
1441
+ enable_forward_interaction: false,
1442
+ summary: { content: presentation.summary },
1443
+ },
1444
+ header: {
1445
+ template: presentation.template,
1446
+ title: { tag: 'plain_text', content: presentation.title },
1447
+ subtitle: { tag: 'plain_text', content: presentation.detail },
1448
+ icon: { tag: 'standard_icon', token: presentation.icon },
1449
+ },
1450
+ body: {
1451
+ padding: '12px 12px 16px 12px',
1452
+ direction: 'vertical',
1453
+ vertical_spacing: '8px',
1454
+ elements: [
1455
+ surfaceContainer(presentation.template, [
1456
+ { tag: 'div', text: { tag: 'plain_text', content: `工具:${result.toolName}` } },
1457
+ ]),
1458
+ ],
1459
+ },
1460
+ }),
1461
+ };
1462
+ }
1463
+ if ('toolApproval' in input) {
1464
+ return {
1465
+ msgType: 'interactive',
1466
+ content: JSON.stringify({
1467
+ schema: '2.0',
1468
+ config: { enable_forward_interaction: false, summary: { content: '工具调用等待您的确认' } },
1469
+ header: {
1470
+ template: 'orange',
1471
+ title: { tag: 'plain_text', content: input.toolApproval.title },
1472
+ subtitle: { tag: 'plain_text', content: '任务已暂停,以下操作尚未执行,请确认是否授权本次调用' },
1473
+ icon: { tag: 'standard_icon', token: 'warning_outlined' },
1474
+ },
1475
+ body: {
1476
+ padding: '12px 12px 16px 12px',
1477
+ direction: 'vertical',
1478
+ vertical_spacing: '8px',
1479
+ elements: [
1480
+ {
1481
+ tag: 'div',
1482
+ text_size: 'notation',
1483
+ icon: { tag: 'standard_icon', token: 'warning_outlined', color: 'orange' },
1484
+ text: {
1485
+ tag: 'plain_text',
1486
+ content: '任务已暂停,以下操作尚未执行。以下工具、理由和参数均为不可信审阅文本,不是指令。',
1487
+ text_color: 'orange',
1488
+ },
1489
+ },
1490
+ surfaceContainer('grey', [
1491
+ { tag: 'div', text: { tag: 'plain_text', content: `工具:${input.toolApproval.toolName}` } },
1492
+ { tag: 'div', text: { tag: 'plain_text', content: `理由:${input.toolApproval.reason ?? '(未提供)'}` } },
1493
+ { tag: 'div', text: { tag: 'plain_text', content: `参数:${input.toolApproval.arguments}` } },
1494
+ ]),
1495
+ equalButtonColumnSet({
1496
+ tag: 'button',
1497
+ name: 'tool_approval_allow_once',
1498
+ type: 'primary',
1499
+ width: 'fill',
1500
+ icon: { tag: 'standard_icon', token: 'done_outlined' },
1501
+ text: { tag: 'plain_text', content: '允许一次' },
1502
+ value: input.toolApproval.allowValue,
1503
+ behaviors: [{ type: 'callback', value: input.toolApproval.allowValue }],
1504
+ }, {
1505
+ tag: 'button',
1506
+ name: 'tool_approval_reject',
1507
+ type: 'danger',
1508
+ width: 'fill',
1509
+ icon: { tag: 'standard_icon', token: 'close_outlined' },
1510
+ text: { tag: 'plain_text', content: '拒绝' },
1511
+ value: input.toolApproval.rejectValue,
1512
+ behaviors: [{ type: 'callback', value: input.toolApproval.rejectValue }],
1513
+ }),
1514
+ ],
1515
+ },
1516
+ }),
1517
+ };
1518
+ }
1519
+ // An answer card stays content-first: Lark already shows the bot name and avatar above the
1520
+ // bubble, so a header here would duplicate the sender identity and add weight to every reply.
1521
+ // GFM tables are promoted to native Card 2.0 table elements by the answer renderer.
1522
+ return {
1523
+ msgType: 'interactive',
1524
+ content: JSON.stringify({
1525
+ schema: '2.0',
1526
+ config: {
1527
+ compact_width: false,
1528
+ width_mode: 'fill',
1529
+ wide_screen_mode: true,
1530
+ summary: { content: '智能体已返回答复' },
1531
+ },
1532
+ body: {
1533
+ padding: '12px 16px 12px 16px',
1534
+ elements: renderLarkAnswerElements(input.markdown),
1535
+ },
1536
+ }),
1537
+ };
1538
+ }
1539
+ function escapedPattern(value) {
1540
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
1541
+ }
1542
+ function safeNormalizedContent(message) {
1543
+ // SDK 1.73 renders a folder's file_key into content but, unlike every
1544
+ // supported resource kind, omits it from `resources`.
1545
+ if (message.rawContentType === 'folder')
1546
+ return '[Folder attachment]';
1547
+ let content = message.content;
1548
+ if (message.resources.length === 1 && message.resources[0]?.type === 'image'
1549
+ && content.trim() === `![image](${message.resources[0].fileKey})`)
1550
+ return '';
1551
+ for (const resource of message.resources) {
1552
+ const key = resource.fileKey;
1553
+ if (resource.type === 'image') {
1554
+ content = content.replaceAll(`![image](${key})`, '[Image attachment]');
1555
+ }
1556
+ else {
1557
+ const tag = resource.type;
1558
+ content = content.replace(new RegExp(`<${tag}\\b[^>]*\\bkey="${escapedPattern(key)}"[^>]*/>`, 'gu'), `[${tag[0].toUpperCase()}${tag.slice(1)} attachment]`);
1559
+ }
1560
+ // Defense in depth for future SDK renderings: a provider capability key
1561
+ // is never user-facing text and must not cross into the model prompt.
1562
+ content = content.replaceAll(key, '[redacted-resource]');
1563
+ }
1564
+ return content.trim();
1565
+ }
1566
+ /** Feishu event payloads mark an application sender as `bot`; the message API may say `app`. */
1567
+ export function rawSenderIsBot(raw) {
1568
+ const senderType = raw?.sender?.sender_type;
1569
+ return typeof senderType === 'string' && ['app', 'bot'].includes(senderType.toLowerCase());
1570
+ }
1571
+ export function toSafeLarkMessage(message, senderIsBot = false) {
1572
+ return {
1573
+ messageId: message.messageId,
1574
+ chatId: message.chatId,
1575
+ chatType: message.chatType,
1576
+ senderId: message.senderId,
1577
+ ...(senderIsBot ? { senderIsBot: true } : {}),
1578
+ content: safeNormalizedContent(message),
1579
+ rawContentType: message.rawContentType,
1580
+ resources: message.resources,
1581
+ mentionAll: message.mentionAll,
1582
+ mentionedBot: message.mentionedBot,
1583
+ createTime: message.createTime,
1584
+ ...(message.rootId === undefined ? {} : { rootId: message.rootId }),
1585
+ ...(message.threadId === undefined ? {} : { threadId: message.threadId }),
1586
+ ...(message.replyToMessageId === undefined ? {} : { replyToMessageId: message.replyToMessageId }),
1587
+ };
1588
+ }
1589
+ function providerError(result, kind = 'message') {
1590
+ const classified = providerFailureCode(result.code);
1591
+ if (classified === 'permission_denied') {
1592
+ return new LarkTransportError('permission_denied', 'Lark rejected the application credential or permission');
1593
+ }
1594
+ if (classified === 'rate_limited' || /rate|frequency|too many/iu.test(result.msg ?? '')) {
1595
+ return new LarkTransportError('rate_limited', kind === 'upload' ? 'Lark rate limited the file upload' : 'Lark rate limited the message');
1596
+ }
1597
+ if (classified === 'format_error') {
1598
+ return new LarkTransportError('format_error', kind === 'upload' ? 'Lark rejected the file upload format' : 'Lark rejected the message card format');
1599
+ }
1600
+ if (kind === 'upload') {
1601
+ return new LarkTransportError('upload_failed', `Lark rejected the file upload with code ${String(result.code ?? 'missing')}`);
1602
+ }
1603
+ return new LarkTransportError('unknown', `Lark rejected the message with code ${String(result.code ?? 'missing')}`);
1604
+ }
1605
+ export class OfficialLarkTransport {
1606
+ client;
1607
+ imageClient;
1608
+ dispatcher;
1609
+ ws;
1610
+ handshakeTimeoutMs;
1611
+ requestTimeoutMs;
1612
+ imageDownloadTimeoutMs;
1613
+ lifecycleController = new AbortController();
1614
+ handlers;
1615
+ identity;
1616
+ pendingHandshake;
1617
+ constructor(options) {
1618
+ const domain = options.domain === 'lark' ? Domain.Lark : Domain.Feishu;
1619
+ const shared = { appId: options.appId, appSecret: options.appSecret, domain,
1620
+ logger: silentLogger, loggerLevel: LoggerLevel.error, source: 'dsh-ray-lark-channel' };
1621
+ this.handshakeTimeoutMs = options.handshakeTimeoutMs;
1622
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
1623
+ this.imageDownloadTimeoutMs = options.imageDownloadTimeoutMs;
1624
+ this.client = new Client({
1625
+ ...shared,
1626
+ appType: AppType.SelfBuild,
1627
+ httpInstance: boundedHttpInstance(this.requestTimeoutMs, this.lifecycleController.signal),
1628
+ });
1629
+ this.imageClient = new Client({
1630
+ ...shared,
1631
+ appType: AppType.SelfBuild,
1632
+ httpInstance: boundedHttpInstance(options.imageDownloadTimeoutMs, this.lifecycleController.signal),
1633
+ });
1634
+ this.dispatcher = new EventDispatcher({ logger: silentLogger, loggerLevel: LoggerLevel.error });
1635
+ this.dispatcher.register({
1636
+ 'im.message.receive_v1': async (raw) => {
1637
+ if (this.handlers === undefined || this.identity === undefined)
1638
+ return;
1639
+ const message = await normalize(raw, {
1640
+ botIdentity: this.identity,
1641
+ stripBotMentions: true,
1642
+ });
1643
+ await this.handlers.message(toSafeLarkMessage(message, rawSenderIsBot(raw)));
1644
+ },
1645
+ 'im.message.message_read_v1': async (raw) => {
1646
+ if (this.handlers?.readReceipt === undefined)
1647
+ return;
1648
+ const receipt = normalizeReadReceipt(raw);
1649
+ if (receipt === null)
1650
+ return;
1651
+ try {
1652
+ this.handlers.readReceipt(receipt);
1653
+ }
1654
+ catch {
1655
+ // A read fact is best-effort; one malformed consumer must not stop the WS loop.
1656
+ }
1657
+ },
1658
+ 'card.action.trigger': async (raw) => {
1659
+ if (this.handlers === undefined)
1660
+ return;
1661
+ const action = normalizeCardAction(raw);
1662
+ if (action === null)
1663
+ return;
1664
+ return await this.handlers.cardAction({
1665
+ messageId: action.messageId,
1666
+ chatId: action.chatId,
1667
+ operatorId: action.operator.openId,
1668
+ value: action.action.value,
1669
+ tag: action.action.tag,
1670
+ ...(action.action.name === undefined ? {} : { name: action.action.name }),
1671
+ ...(action.action.option === undefined ? {} : { option: action.action.option }),
1672
+ });
1673
+ },
1674
+ });
1675
+ this.ws = new WSClient({
1676
+ ...shared,
1677
+ autoReconnect: true,
1678
+ handshakeTimeoutMs: options.handshakeTimeoutMs,
1679
+ onReady: () => this.pendingHandshake?.resolve(),
1680
+ onError: error => {
1681
+ const normalized = new LarkTransportError('not_connected', 'Lark WebSocket connection failed');
1682
+ if (this.pendingHandshake !== undefined)
1683
+ this.pendingHandshake.reject(normalized);
1684
+ else
1685
+ this.handlers?.error(normalized);
1686
+ void error;
1687
+ },
1688
+ onReconnecting: () => this.handlers?.reconnecting(),
1689
+ onReconnected: () => this.handlers?.reconnected(),
1690
+ });
1691
+ installLarkCardCallbackBridge(this.ws);
1692
+ }
1693
+ subscribe(handlers) {
1694
+ if (this.handlers !== undefined)
1695
+ throw new Error('lark-channel: transport is already subscribed');
1696
+ this.handlers = handlers;
1697
+ return () => { if (this.handlers === handlers)
1698
+ this.handlers = undefined; };
1699
+ }
1700
+ async connect() {
1701
+ this.identity = await this.fetchBotIdentity();
1702
+ await new Promise((resolve, reject) => {
1703
+ let settled = false;
1704
+ const timer = setTimeout(() => {
1705
+ if (settled)
1706
+ return;
1707
+ settled = true;
1708
+ this.pendingHandshake = undefined;
1709
+ this.ws.close({ force: true });
1710
+ reject(new LarkTransportError('not_connected', 'Lark WebSocket handshake timed out'));
1711
+ }, this.handshakeTimeoutMs + 1_000);
1712
+ timer.unref?.();
1713
+ this.pendingHandshake = {
1714
+ resolve: () => {
1715
+ if (settled)
1716
+ return;
1717
+ settled = true;
1718
+ clearTimeout(timer);
1719
+ this.pendingHandshake = undefined;
1720
+ resolve();
1721
+ },
1722
+ reject: error => {
1723
+ if (settled)
1724
+ return;
1725
+ settled = true;
1726
+ clearTimeout(timer);
1727
+ this.pendingHandshake = undefined;
1728
+ reject(error);
1729
+ },
1730
+ };
1731
+ void this.ws.start({ eventDispatcher: this.dispatcher }).catch(error => {
1732
+ void error;
1733
+ this.pendingHandshake?.reject(new LarkTransportError('not_connected', 'Lark WebSocket startup failed'));
1734
+ });
1735
+ });
1736
+ }
1737
+ async disconnect() {
1738
+ this.lifecycleController.abort(new Error('lark-channel: transport stopped'));
1739
+ this.pendingHandshake?.reject(new LarkTransportError('not_connected', 'Lark transport stopped'));
1740
+ this.ws.close({ force: true });
1741
+ }
1742
+ requestDeadline(callerSignal) {
1743
+ const controller = new AbortController();
1744
+ const timer = setTimeout(() => controller.abort(new Error('lark-channel: OpenAPI request deadline exceeded')), this.requestTimeoutMs);
1745
+ timer.unref?.();
1746
+ const timeoutSignal = controller.signal;
1747
+ const signals = callerSignal === undefined
1748
+ ? [timeoutSignal, this.lifecycleController.signal]
1749
+ : [callerSignal, timeoutSignal, this.lifecycleController.signal];
1750
+ return { signal: AbortSignal.any(signals), timeoutSignal, dispose: () => clearTimeout(timer) };
1751
+ }
1752
+ async boundedSdkRequest(request, failureMessage, callerSignal) {
1753
+ const deadline = this.requestDeadline(callerSignal);
1754
+ let started = false;
1755
+ try {
1756
+ return await awaitBoundedSdkRequest(deadline.signal, () => {
1757
+ started = true;
1758
+ return request(deadline.signal);
1759
+ });
1760
+ }
1761
+ catch (error) {
1762
+ if (deadline.timeoutSignal.aborted) {
1763
+ // A timeout can happen after the provider has accepted the request.
1764
+ // The Delivery adapter deliberately maps send_timeout to unknown_after_send.
1765
+ throw new LarkTransportError('send_timeout', `${failureMessage} timed out`);
1766
+ }
1767
+ if (callerSignal?.aborted || this.lifecycleController.signal.aborted) {
1768
+ if (started) {
1769
+ throw new LarkTransportError('unknown', `${failureMessage} outcome is unknown after cancellation`);
1770
+ }
1771
+ throw new LarkTransportError('not_connected', `${failureMessage} was cancelled`);
1772
+ }
1773
+ if (error instanceof LarkTransportError)
1774
+ throw error;
1775
+ const classified = classifyLarkSdkFailure(error);
1776
+ throw new LarkTransportError(classified.code, `${failureMessage} failed`, classified.retryAfterMs);
1777
+ }
1778
+ finally {
1779
+ deadline.dispose();
1780
+ }
1781
+ }
1782
+ async downloadMessageImage(messageId, fileKey, options) {
1783
+ const timeoutSignal = AbortSignal.timeout(this.imageDownloadTimeoutMs);
1784
+ const signal = AbortSignal.any([options.signal, timeoutSignal, this.lifecycleController.signal]);
1785
+ let response;
1786
+ try {
1787
+ response = await awaitImageResourceRequest(signal, async () => await this.imageClient.request(createLarkImageResourceRequest(messageId, fileKey, {
1788
+ maxBytes: options.maxBytes, timeoutMs: this.imageDownloadTimeoutMs, signal,
1789
+ })));
1790
+ }
1791
+ catch (error) {
1792
+ if (options.signal.aborted) {
1793
+ throw new LarkTransportError('not_connected', 'Lark image resource request was cancelled');
1794
+ }
1795
+ if (this.lifecycleController.signal.aborted) {
1796
+ throw new LarkTransportError('not_connected', 'Lark image resource request was cancelled');
1797
+ }
1798
+ if (timeoutSignal.aborted) {
1799
+ throw new LarkTransportError('send_timeout', 'Lark image resource request timed out');
1800
+ }
1801
+ const classified = await classifyLarkImageSdkFailure(error, signal);
1802
+ if (options.signal.aborted || this.lifecycleController.signal.aborted) {
1803
+ throw new LarkTransportError('not_connected', 'Lark image resource request was cancelled');
1804
+ }
1805
+ if (timeoutSignal.aborted) {
1806
+ throw new LarkTransportError('send_timeout', 'Lark image resource request timed out');
1807
+ }
1808
+ throw new LarkTransportError(classified.code, 'Lark image resource request failed', classified.retryAfterMs);
1809
+ }
1810
+ try {
1811
+ const image = await readLarkImageResourceResponse(response, { maxBytes: options.maxBytes, signal });
1812
+ if (options.signal.aborted || this.lifecycleController.signal.aborted) {
1813
+ throw new LarkTransportError('not_connected', 'Lark image resource request was cancelled');
1814
+ }
1815
+ if (timeoutSignal.aborted) {
1816
+ throw new LarkTransportError('send_timeout', 'Lark image resource request timed out');
1817
+ }
1818
+ return image;
1819
+ }
1820
+ catch (error) {
1821
+ if (options.signal.aborted) {
1822
+ throw new LarkTransportError('not_connected', 'Lark image resource request was cancelled');
1823
+ }
1824
+ if (this.lifecycleController.signal.aborted) {
1825
+ throw new LarkTransportError('not_connected', 'Lark image resource request was cancelled');
1826
+ }
1827
+ if (timeoutSignal.aborted) {
1828
+ throw new LarkTransportError('send_timeout', 'Lark image resource request timed out');
1829
+ }
1830
+ const classified = error instanceof LarkImageResponseValidationError
1831
+ ? { code: 'format_error' }
1832
+ : classifyLarkSdkFailure(error);
1833
+ const message = classified.code === 'format_error'
1834
+ ? 'Lark image resource response failed validation'
1835
+ : 'Lark image resource response could not be read';
1836
+ throw new LarkTransportError(classified.code, message, classified.retryAfterMs);
1837
+ }
1838
+ }
1839
+ async readCalendarEventPage(input) {
1840
+ if (!/^[\s\S]{1,512}$/u.test(input.calendarId) || input.calendarId.trim() !== input.calendarId || /[\p{Cc}]/u.test(input.calendarId)
1841
+ || !Number.isSafeInteger(input.startTime) || !Number.isSafeInteger(input.endTime) || input.startTime < 0 || input.endTime <= input.startTime
1842
+ || !Number.isSafeInteger(input.pageSize) || input.pageSize < 1 || input.pageSize > 1_000
1843
+ || (input.pageToken !== undefined && (input.pageToken.length === 0 || input.pageToken.length > 4_096 || /[\p{Cc}]/u.test(input.pageToken)))) {
1844
+ throw new LarkTransportError('format_error', 'Lark calendar request is invalid');
1845
+ }
1846
+ if (input.signal.aborted || this.lifecycleController.signal.aborted) {
1847
+ throw new LarkTransportError('not_connected', 'Lark calendar request was cancelled');
1848
+ }
1849
+ return await this.boundedSdkRequest(async (deadlineSignal) => {
1850
+ const params = new URLSearchParams({ page_size: String(input.pageSize), start_time: String(input.startTime), end_time: String(input.endTime) });
1851
+ if (input.pageToken !== undefined)
1852
+ params.set('page_token', input.pageToken);
1853
+ const response = await this.client.request({
1854
+ url: `/open-apis/calendar/v4/calendars/${encodeURIComponent(input.calendarId)}/events?${params.toString()}`,
1855
+ method: 'GET', signal: deadlineSignal,
1856
+ maxContentLength: 1_048_576, maxBodyLength: 1_048_576,
1857
+ });
1858
+ if (response !== null && typeof response === 'object' && 'code' in response) {
1859
+ const code = response.code;
1860
+ if (code !== undefined && code !== 0)
1861
+ throw providerError({ code: typeof code === 'number' ? code : undefined, msg: undefined });
1862
+ }
1863
+ const data = response !== null && typeof response === 'object' && 'data' in response
1864
+ ? response.data : undefined;
1865
+ if (data === undefined)
1866
+ throw new LarkTransportError('unknown', 'Lark calendar response omitted data');
1867
+ return data;
1868
+ }, 'Lark calendar request', input.signal);
1869
+ }
1870
+ async addReaction(messageId, emojiType) {
1871
+ return await this.boundedSdkRequest(async (deadlineSignal) => {
1872
+ const response = await this.client.request(createLarkReactionRequest(messageId, emojiType, deadlineSignal));
1873
+ if (response.code !== undefined && response.code !== 0) {
1874
+ throw providerError({ code: response.code, msg: response.msg });
1875
+ }
1876
+ const reactionId = response.data?.reaction_id;
1877
+ if (reactionId === undefined || reactionId === '') {
1878
+ throw new LarkTransportError('unknown', 'Lark accepted reaction omitted reaction identity');
1879
+ }
1880
+ return reactionId;
1881
+ }, 'Lark reaction request');
1882
+ }
1883
+ async createProgress(chatId, options) {
1884
+ return await this.boundedSdkRequest(async (deadlineSignal) => {
1885
+ const response = await this.client.request(createLarkProgressRequest(chatId, options, deadlineSignal));
1886
+ if (response.code !== undefined && response.code !== 0) {
1887
+ throw providerError({ code: response.code, msg: response.msg });
1888
+ }
1889
+ const cotId = response.data?.cot_id;
1890
+ const messageId = response.data?.message_id;
1891
+ if (cotId === undefined || messageId === undefined) {
1892
+ throw new LarkTransportError('unknown', 'Lark accepted progress request omitted progress identity');
1893
+ }
1894
+ return { cotId, messageId };
1895
+ }, 'Lark progress request');
1896
+ }
1897
+ async writeProgress(handle, events) {
1898
+ await this.boundedSdkRequest(async (deadlineSignal) => {
1899
+ const response = await this.client.request(writeLarkProgressRequest(handle, events, deadlineSignal));
1900
+ if (response.code !== undefined && response.code !== 0) {
1901
+ throw providerError({ code: response.code, msg: response.msg });
1902
+ }
1903
+ }, 'Lark progress update');
1904
+ }
1905
+ async updateRawCard(messageId, card, signal) {
1906
+ if (signal.aborted || this.lifecycleController.signal.aborted) {
1907
+ throw new LarkTransportError('not_connected', 'Lark card update was cancelled');
1908
+ }
1909
+ await this.boundedSdkRequest(async (deadlineSignal) => {
1910
+ const response = await this.client.request(createLarkRawCardUpdateRequest(messageId, card, deadlineSignal));
1911
+ if (response.code !== undefined && response.code !== 0) {
1912
+ throw providerError({ code: response.code, msg: response.msg });
1913
+ }
1914
+ }, 'Lark card update', signal);
1915
+ }
1916
+ async uploadTextFile(input) {
1917
+ if (input.signal.aborted || this.lifecycleController.signal.aborted) {
1918
+ throw new LarkTransportError('not_connected', 'Lark file upload was cancelled');
1919
+ }
1920
+ const maxBytes = input.maxBytes ?? LARK_TEXT_FILE_MAX_BYTES;
1921
+ // Validate input bounds and build the payload once before entering boundedSdkRequest / acquiring token.
1922
+ const baseRequest = createLarkTextFileUploadRequest({
1923
+ name: input.name,
1924
+ mediaType: input.mediaType,
1925
+ text: input.text,
1926
+ timeoutMs: this.requestTimeoutMs,
1927
+ maxBytes,
1928
+ signal: input.signal,
1929
+ });
1930
+ try {
1931
+ return await this.boundedSdkRequest(async (deadlineSignal) => {
1932
+ const response = await this.client.request({ ...baseRequest, signal: deadlineSignal });
1933
+ if (response === null || typeof response !== 'object') {
1934
+ throw new LarkTransportError('upload_failed', 'Lark file upload response was invalid');
1935
+ }
1936
+ if (response.code !== undefined && response.code !== 0) {
1937
+ throw providerError({ code: response.code, msg: response.msg }, 'upload');
1938
+ }
1939
+ const fileKey = response.data?.file_key;
1940
+ if (typeof fileKey !== 'string' || !larkResourceIdentifier.test(fileKey)) {
1941
+ throw new LarkTransportError('upload_failed', 'Lark file upload response omitted valid file identity');
1942
+ }
1943
+ return fileKey;
1944
+ }, 'Lark file upload', input.signal);
1945
+ }
1946
+ catch (error) {
1947
+ if (input.signal.aborted || this.lifecycleController.signal.aborted) {
1948
+ throw new LarkTransportError('not_connected', 'Lark file upload was cancelled');
1949
+ }
1950
+ if (error instanceof LarkTransportError) {
1951
+ if (error.code === 'unknown') {
1952
+ throw new LarkTransportError('upload_failed', 'Lark file upload failed');
1953
+ }
1954
+ throw error;
1955
+ }
1956
+ throw new LarkTransportError('upload_failed', 'Lark file upload failed');
1957
+ }
1958
+ }
1959
+ async send(chatId, input, options = {}) {
1960
+ if (options.signal?.aborted || this.lifecycleController.signal.aborted) {
1961
+ throw new LarkTransportError('not_connected', 'Lark SDK request was cancelled');
1962
+ }
1963
+ const rendered = renderLarkMessage(input);
1964
+ const uuid = larkRequestUuid(options.requestKey ?? `${chatId}:${rendered.content}`);
1965
+ return await this.boundedSdkRequest(async (deadlineSignal) => {
1966
+ const response = await this.client.request(createLarkMessageSendRequest(chatId, rendered, uuid, options, deadlineSignal));
1967
+ if (response.code !== 0)
1968
+ throw providerError({ code: response.code, msg: response.msg });
1969
+ const messageId = response.data?.message_id;
1970
+ if (messageId === undefined)
1971
+ throw new LarkTransportError('unknown', 'Lark accepted response omitted message identity');
1972
+ return { messageId };
1973
+ }, 'Lark SDK request', options.signal);
1974
+ }
1975
+ async fetchBotIdentity() {
1976
+ return await this.boundedSdkRequest(async (deadlineSignal) => {
1977
+ const response = await this.client.request({
1978
+ url: '/open-apis/bot/v3/info', method: 'GET', signal: deadlineSignal,
1979
+ });
1980
+ if (response.bot?.open_id === undefined) {
1981
+ throw new LarkTransportError('permission_denied', 'Lark bot identity is unavailable');
1982
+ }
1983
+ return { openId: response.bot.open_id, name: response.bot.app_name ?? 'bot' };
1984
+ }, 'Lark bot identity request');
1985
+ }
1986
+ }
1987
+ export function createOfficialLarkTransport(options) {
1988
+ return new OfficialLarkTransport(options);
1989
+ }
1990
+ //# sourceMappingURL=sdk.js.map