@nanodoc/pdflux-dsh-plugin 0.0.0-stage → 0.2.7-rc.8

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 (204) hide show
  1. package/README.md +4 -2
  2. package/cordis.patch.yml +12 -0
  3. package/docs/DETAIL.en.md +3 -0
  4. package/docs/DETAIL.zh.md +3 -0
  5. package/docs/preview.zh.png +0 -0
  6. package/icon.svg +9 -0
  7. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/78-EUC-H.bcmap +0 -0
  8. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/78-EUC-V.bcmap +0 -0
  9. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/78-H.bcmap +0 -0
  10. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/78-RKSJ-H.bcmap +0 -0
  11. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/78-RKSJ-V.bcmap +0 -0
  12. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/78-V.bcmap +0 -0
  13. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/78ms-RKSJ-H.bcmap +0 -0
  14. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/78ms-RKSJ-V.bcmap +0 -0
  15. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/83pv-RKSJ-H.bcmap +0 -0
  16. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/90ms-RKSJ-H.bcmap +0 -0
  17. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/90ms-RKSJ-V.bcmap +0 -0
  18. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/90msp-RKSJ-H.bcmap +0 -0
  19. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/90msp-RKSJ-V.bcmap +0 -0
  20. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/90pv-RKSJ-H.bcmap +0 -0
  21. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/90pv-RKSJ-V.bcmap +0 -0
  22. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Add-H.bcmap +0 -0
  23. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Add-RKSJ-H.bcmap +0 -0
  24. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Add-RKSJ-V.bcmap +0 -0
  25. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Add-V.bcmap +0 -0
  26. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-CNS1-0.bcmap +0 -0
  27. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-CNS1-1.bcmap +0 -0
  28. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-CNS1-2.bcmap +0 -0
  29. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-CNS1-3.bcmap +0 -0
  30. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-CNS1-4.bcmap +0 -0
  31. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-CNS1-5.bcmap +0 -0
  32. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-CNS1-6.bcmap +0 -0
  33. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-CNS1-UCS2.bcmap +0 -0
  34. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-GB1-0.bcmap +0 -0
  35. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-GB1-1.bcmap +0 -0
  36. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-GB1-2.bcmap +0 -0
  37. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-GB1-3.bcmap +0 -0
  38. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-GB1-4.bcmap +0 -0
  39. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-GB1-5.bcmap +0 -0
  40. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-GB1-UCS2.bcmap +0 -0
  41. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Japan1-0.bcmap +0 -0
  42. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Japan1-1.bcmap +0 -0
  43. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Japan1-2.bcmap +0 -0
  44. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Japan1-3.bcmap +0 -0
  45. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Japan1-4.bcmap +0 -0
  46. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Japan1-5.bcmap +0 -0
  47. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Japan1-6.bcmap +0 -0
  48. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Japan1-UCS2.bcmap +0 -0
  49. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Korea1-0.bcmap +0 -0
  50. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Korea1-1.bcmap +0 -0
  51. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Korea1-2.bcmap +0 -0
  52. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Adobe-Korea1-UCS2.bcmap +0 -0
  53. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/B5-H.bcmap +0 -0
  54. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/B5-V.bcmap +0 -0
  55. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/B5pc-H.bcmap +0 -0
  56. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/B5pc-V.bcmap +0 -0
  57. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/CNS-EUC-H.bcmap +0 -0
  58. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/CNS-EUC-V.bcmap +0 -0
  59. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/CNS1-H.bcmap +0 -0
  60. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/CNS1-V.bcmap +0 -0
  61. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/CNS2-H.bcmap +0 -0
  62. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/CNS2-V.bcmap +3 -0
  63. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/ETHK-B5-H.bcmap +0 -0
  64. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/ETHK-B5-V.bcmap +0 -0
  65. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/ETen-B5-H.bcmap +0 -0
  66. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/ETen-B5-V.bcmap +0 -0
  67. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/ETenms-B5-H.bcmap +3 -0
  68. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/ETenms-B5-V.bcmap +0 -0
  69. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/EUC-H.bcmap +0 -0
  70. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/EUC-V.bcmap +0 -0
  71. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Ext-H.bcmap +0 -0
  72. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Ext-RKSJ-H.bcmap +0 -0
  73. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Ext-RKSJ-V.bcmap +0 -0
  74. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Ext-V.bcmap +0 -0
  75. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GB-EUC-H.bcmap +0 -0
  76. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GB-EUC-V.bcmap +0 -0
  77. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GB-H.bcmap +4 -0
  78. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GB-V.bcmap +0 -0
  79. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBK-EUC-H.bcmap +0 -0
  80. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBK-EUC-V.bcmap +0 -0
  81. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBK2K-H.bcmap +0 -0
  82. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBK2K-V.bcmap +0 -0
  83. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBKp-EUC-H.bcmap +0 -0
  84. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBKp-EUC-V.bcmap +0 -0
  85. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBT-EUC-H.bcmap +0 -0
  86. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBT-EUC-V.bcmap +0 -0
  87. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBT-H.bcmap +0 -0
  88. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBT-V.bcmap +0 -0
  89. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBTpc-EUC-H.bcmap +0 -0
  90. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBTpc-EUC-V.bcmap +0 -0
  91. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBpc-EUC-H.bcmap +0 -0
  92. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/GBpc-EUC-V.bcmap +0 -0
  93. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/H.bcmap +0 -0
  94. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKdla-B5-H.bcmap +0 -0
  95. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKdla-B5-V.bcmap +0 -0
  96. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKdlb-B5-H.bcmap +0 -0
  97. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKdlb-B5-V.bcmap +0 -0
  98. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKgccs-B5-H.bcmap +0 -0
  99. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKgccs-B5-V.bcmap +0 -0
  100. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKm314-B5-H.bcmap +0 -0
  101. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKm314-B5-V.bcmap +0 -0
  102. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKm471-B5-H.bcmap +0 -0
  103. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKm471-B5-V.bcmap +0 -0
  104. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKscs-B5-H.bcmap +0 -0
  105. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/HKscs-B5-V.bcmap +0 -0
  106. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Hankaku.bcmap +0 -0
  107. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Hiragana.bcmap +0 -0
  108. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSC-EUC-H.bcmap +0 -0
  109. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSC-EUC-V.bcmap +0 -0
  110. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSC-H.bcmap +0 -0
  111. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSC-Johab-H.bcmap +0 -0
  112. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSC-Johab-V.bcmap +0 -0
  113. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSC-V.bcmap +0 -0
  114. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSCms-UHC-H.bcmap +0 -0
  115. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSCms-UHC-HW-H.bcmap +0 -0
  116. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSCms-UHC-HW-V.bcmap +0 -0
  117. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSCms-UHC-V.bcmap +0 -0
  118. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSCpc-EUC-H.bcmap +0 -0
  119. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/KSCpc-EUC-V.bcmap +0 -0
  120. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Katakana.bcmap +0 -0
  121. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/LICENSE +36 -0
  122. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/NWP-H.bcmap +0 -0
  123. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/NWP-V.bcmap +0 -0
  124. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/RKSJ-H.bcmap +0 -0
  125. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/RKSJ-V.bcmap +0 -0
  126. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/Roman.bcmap +0 -0
  127. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniCNS-UCS2-H.bcmap +0 -0
  128. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniCNS-UCS2-V.bcmap +0 -0
  129. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniCNS-UTF16-H.bcmap +0 -0
  130. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniCNS-UTF16-V.bcmap +0 -0
  131. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniCNS-UTF32-H.bcmap +0 -0
  132. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniCNS-UTF32-V.bcmap +0 -0
  133. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniCNS-UTF8-H.bcmap +0 -0
  134. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniCNS-UTF8-V.bcmap +0 -0
  135. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniGB-UCS2-H.bcmap +0 -0
  136. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniGB-UCS2-V.bcmap +0 -0
  137. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniGB-UTF16-H.bcmap +0 -0
  138. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniGB-UTF16-V.bcmap +0 -0
  139. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniGB-UTF32-H.bcmap +0 -0
  140. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniGB-UTF32-V.bcmap +0 -0
  141. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniGB-UTF8-H.bcmap +0 -0
  142. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniGB-UTF8-V.bcmap +0 -0
  143. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UCS2-H.bcmap +0 -0
  144. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UCS2-HW-H.bcmap +0 -0
  145. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UCS2-HW-V.bcmap +0 -0
  146. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UCS2-V.bcmap +0 -0
  147. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UTF16-H.bcmap +0 -0
  148. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UTF16-V.bcmap +0 -0
  149. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UTF32-H.bcmap +0 -0
  150. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UTF32-V.bcmap +0 -0
  151. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UTF8-H.bcmap +0 -0
  152. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS-UTF8-V.bcmap +0 -0
  153. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS2004-UTF16-H.bcmap +0 -0
  154. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS2004-UTF16-V.bcmap +0 -0
  155. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS2004-UTF32-H.bcmap +0 -0
  156. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS2004-UTF32-V.bcmap +0 -0
  157. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS2004-UTF8-H.bcmap +0 -0
  158. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJIS2004-UTF8-V.bcmap +0 -0
  159. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJISPro-UCS2-HW-V.bcmap +0 -0
  160. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJISPro-UCS2-V.bcmap +0 -0
  161. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJISPro-UTF8-V.bcmap +0 -0
  162. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJISX0213-UTF32-H.bcmap +0 -0
  163. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJISX0213-UTF32-V.bcmap +0 -0
  164. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJISX02132004-UTF32-H.bcmap +0 -0
  165. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniJISX02132004-UTF32-V.bcmap +0 -0
  166. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniKS-UCS2-H.bcmap +0 -0
  167. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniKS-UCS2-V.bcmap +0 -0
  168. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniKS-UTF16-H.bcmap +0 -0
  169. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniKS-UTF16-V.bcmap +0 -0
  170. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniKS-UTF32-H.bcmap +0 -0
  171. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniKS-UTF32-V.bcmap +0 -0
  172. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniKS-UTF8-H.bcmap +0 -0
  173. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/UniKS-UTF8-V.bcmap +0 -0
  174. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/V.bcmap +0 -0
  175. package/lib/assets/pdf-document-viewer/assets/pdf.js/cmaps/WP-Symbol.bcmap +0 -0
  176. package/lib/assets/pdf-document-viewer/assets/pdf.js/locale/en-GB/viewer.ftl +653 -0
  177. package/lib/assets/pdf-document-viewer/assets/pdf.js/locale/en-US/viewer.ftl +692 -0
  178. package/lib/assets/pdf-document-viewer/assets/pdf.js/locale/ja/viewer.ftl +611 -0
  179. package/lib/assets/pdf-document-viewer/assets/pdf.js/locale/ko/viewer.ftl +641 -0
  180. package/lib/assets/pdf-document-viewer/assets/pdf.js/locale/locale.json +1 -0
  181. package/lib/assets/pdf-document-viewer/assets/pdf.js/locale/zh-CN/viewer.ftl +641 -0
  182. package/lib/assets/pdf-document-viewer/assets/pdf.js/locale/zh-TW/viewer.ftl +641 -0
  183. package/lib/assets/pdf-document-viewer/assets/pdflux.wasm +0 -0
  184. package/lib/assets/pdf-document-viewer/assets/words.txt +135798 -0
  185. package/lib/assets/pdf-document-viewer/style.css +1 -0
  186. package/lib/assets/pdf-document-viewer/worker/pdf.sandbox.mjs +21 -0
  187. package/lib/assets/pdf-document-viewer/worker/pdf.worker.mjs +58352 -0
  188. package/lib/assets/pdf-document-viewer/worker/pdflux.worker.js +74 -0
  189. package/lib/assets/pdflux-preview-sdk/style.css +1 -0
  190. package/lib/client.js +76036 -0
  191. package/lib/index.js +2367 -0
  192. package/lib/pure.js +484 -0
  193. package/lib/types/client/index.d.ts +3 -0
  194. package/lib/types/config.d.ts +44 -0
  195. package/lib/types/errors.d.ts +8 -0
  196. package/lib/types/index.d.ts +11 -0
  197. package/lib/types/region.d.ts +9 -0
  198. package/lib/types/registry.d.ts +29 -0
  199. package/lib/types/rs-client.d.ts +129 -0
  200. package/lib/types/skill.d.ts +15 -0
  201. package/lib/types/sources.d.ts +50 -0
  202. package/locale/en.json +7 -0
  203. package/locale/zh.json +7 -0
  204. package/package.json +111 -4
package/lib/index.js ADDED
@@ -0,0 +1,2367 @@
1
+ // src/index.ts
2
+ import { defineDomain, domainTable } from "@deepseek-ai/dsh-storage-domain";
3
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
4
+ import { existsSync as existsSync3 } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { z as z2 } from "zod";
7
+
8
+ // src/config.ts
9
+ import z from "@deepseek-ai/schemastery";
10
+
11
+ // src/region.ts
12
+ var GATEWAY_BY_LANGUAGE = {
13
+ zh: "https://nanodoc-gateway-cn.test.paodingai.com",
14
+ en: "https://nanodoc-gateway.test.paodingai.com"
15
+ };
16
+ var API_KEY_REF_BY_LANGUAGE = {
17
+ zh: "NANODOC_API_KEY_ZH",
18
+ en: "NANODOC_API_KEY_EN"
19
+ };
20
+ function isPluginLanguage(value) {
21
+ return value === "zh" || value === "en";
22
+ }
23
+ function languageFromBaseUrl(baseUrl) {
24
+ const lower = baseUrl.toLowerCase();
25
+ return lower.includes("gateway-cn") || lower.includes("-cn.") ? "zh" : "en";
26
+ }
27
+ function resolvePluginLanguage(language2, baseUrl) {
28
+ if (isPluginLanguage(language2)) return language2;
29
+ return languageFromBaseUrl(baseUrl);
30
+ }
31
+
32
+ // src/config.ts
33
+ var DEFAULT_CONFIG = {
34
+ language: "",
35
+ baseUrl: GATEWAY_BY_LANGUAGE.en,
36
+ nanodocApiKeyRefZh: API_KEY_REF_BY_LANGUAGE.zh,
37
+ nanodocApiKeyRefEn: API_KEY_REF_BY_LANGUAGE.en,
38
+ pollIntervalMs: 2e3,
39
+ maxWaitSeconds: 60,
40
+ maxFileMB: 200,
41
+ requireUploadApproval: false
42
+ };
43
+ var Config = z.object({
44
+ language: z.string().default(DEFAULT_CONFIG.language).volatile(),
45
+ baseUrl: z.string().default(DEFAULT_CONFIG.baseUrl).volatile(),
46
+ nanodocApiKeyRefZh: z.string().role("credential-ref").default(DEFAULT_CONFIG.nanodocApiKeyRefZh).volatile(),
47
+ nanodocApiKeyRefEn: z.string().role("credential-ref").default(DEFAULT_CONFIG.nanodocApiKeyRefEn).volatile(),
48
+ pollIntervalMs: z.natural().default(DEFAULT_CONFIG.pollIntervalMs).volatile(),
49
+ maxWaitSeconds: z.natural().default(DEFAULT_CONFIG.maxWaitSeconds).volatile(),
50
+ maxFileMB: z.natural().default(DEFAULT_CONFIG.maxFileMB).volatile(),
51
+ requireUploadApproval: z.boolean().default(DEFAULT_CONFIG.requireUploadApproval).volatile()
52
+ });
53
+
54
+ // src/errors.ts
55
+ var PdfluxError = class extends Error {
56
+ code;
57
+ constructor(code, message, options) {
58
+ super(message);
59
+ this.name = "PdfluxError";
60
+ this.code = code;
61
+ if (options?.cause !== void 0) this.cause = options.cause;
62
+ }
63
+ };
64
+ function isPdfluxError(value) {
65
+ return value instanceof PdfluxError;
66
+ }
67
+
68
+ // src/registry.ts
69
+ import { createHash } from "node:crypto";
70
+ function normalizeOrigin(origin) {
71
+ return origin.replace(/\/+$/, "");
72
+ }
73
+ function resolveServiceBaseUrl(configured) {
74
+ const trimmed = configured.trim().replace(/\/+$/, "");
75
+ if (!trimmed) return trimmed;
76
+ let parsed;
77
+ try {
78
+ parsed = new URL(trimmed);
79
+ } catch {
80
+ return trimmed;
81
+ }
82
+ if (!trimmed.toLowerCase().includes("nanodoc")) return trimmed;
83
+ return `${parsed.origin}/nanodoc/dsh`;
84
+ }
85
+ function contentKey(fileBytes, parser, baseUrl, explicit) {
86
+ if (explicit && explicit.length > 0) return `explicit:${explicit}`;
87
+ const digest = createHash("sha256").update(fileBytes).digest("hex");
88
+ return `${digest}:${parser}:${normalizeOrigin(baseUrl)}`;
89
+ }
90
+ var DocumentRegistry = class {
91
+ constructor(documents, idem) {
92
+ this.documents = documents;
93
+ this.idem = idem;
94
+ }
95
+ async register(record) {
96
+ const stored = {
97
+ ...record,
98
+ backend_origin: record.backend_origin ? normalizeOrigin(record.backend_origin) : void 0
99
+ };
100
+ await this.documents.put(stored.document_id, stored);
101
+ await this.idem.put(stored.content_key, {
102
+ document_id: stored.document_id,
103
+ content_key: stored.content_key,
104
+ created_at: stored.created_at
105
+ });
106
+ }
107
+ lookup(documentId) {
108
+ return this.documents.get(documentId);
109
+ }
110
+ lookupIdem(key) {
111
+ return this.idem.get(key)?.document_id;
112
+ }
113
+ };
114
+
115
+ // src/rs-client.ts
116
+ var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed"]);
117
+ function isTerminalState(state) {
118
+ return TERMINAL.has(state);
119
+ }
120
+ function statusToCode(status) {
121
+ if (status === 400) return "INVALID_INPUT";
122
+ if (status === 404) return "DOCUMENT_NOT_FOUND";
123
+ if (status === 413) return "FILE_TOO_LARGE";
124
+ if (status >= 500) return "UPSTREAM_UNAVAILABLE";
125
+ return "BAD_RESPONSE";
126
+ }
127
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
128
+ function extractErrorMessage(body, fallback) {
129
+ if (!body || typeof body !== "object") return fallback;
130
+ const record = body;
131
+ if (typeof record.message === "string" && record.message) return record.message;
132
+ if (typeof record.error === "string" && record.error) return record.error;
133
+ if (record.error && typeof record.error === "object") {
134
+ const nested = record.error;
135
+ if (typeof nested.message === "string" && nested.message) return nested.message;
136
+ if (typeof nested.code === "string" && nested.code) return nested.code;
137
+ }
138
+ return fallback;
139
+ }
140
+ async function readErrorMessage(res) {
141
+ const fallback = `HTTP ${res.status}`;
142
+ const contentType = res.headers.get("content-type") ?? "";
143
+ try {
144
+ if (contentType.includes("application/json")) {
145
+ return extractErrorMessage(await res.json(), fallback);
146
+ }
147
+ const text2 = (await res.text()).trim();
148
+ return text2 || fallback;
149
+ } catch {
150
+ return fallback;
151
+ }
152
+ }
153
+ var RsClient = class {
154
+ resolveBaseUrl;
155
+ getApiKey;
156
+ fetchImpl;
157
+ maxRetries;
158
+ retryBaseMs;
159
+ sleep;
160
+ constructor(options) {
161
+ const source = options.baseUrl;
162
+ this.resolveBaseUrl = typeof source === "function" ? () => resolveServiceBaseUrl(source()) : () => resolveServiceBaseUrl(source);
163
+ this.getApiKey = options.getApiKey;
164
+ this.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));
165
+ this.maxRetries = options.maxRetries ?? 2;
166
+ this.retryBaseMs = options.retryBaseMs ?? 200;
167
+ this.sleep = options.sleep ?? defaultSleep;
168
+ }
169
+ get baseUrl() {
170
+ return this.resolveBaseUrl();
171
+ }
172
+ async request(path4, init, signal, apiKey) {
173
+ const url = `${this.resolveBaseUrl()}${path4}`;
174
+ const headers = new Headers(init.headers);
175
+ const key = apiKey ?? (this.getApiKey ? await this.getApiKey() : void 0);
176
+ if (key && !headers.has("Authorization")) {
177
+ headers.set("Authorization", `Bearer ${key}`);
178
+ }
179
+ let lastError;
180
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
181
+ if (signal?.aborted) throw signal.reason ?? new PdfluxError("UPSTREAM_UNAVAILABLE", "aborted");
182
+ try {
183
+ const res = await this.fetchImpl(url, { ...init, headers, signal });
184
+ if (res.status >= 500 && attempt < this.maxRetries) {
185
+ lastError = new PdfluxError("UPSTREAM_UNAVAILABLE", `upstream ${res.status}`);
186
+ await this.sleep(this.retryBaseMs * 2 ** attempt);
187
+ continue;
188
+ }
189
+ return res;
190
+ } catch (err) {
191
+ lastError = err;
192
+ if (attempt < this.maxRetries) {
193
+ await this.sleep(this.retryBaseMs * 2 ** attempt);
194
+ continue;
195
+ }
196
+ }
197
+ }
198
+ throw new PdfluxError("UPSTREAM_UNAVAILABLE", "pdflux-rs preview service is unreachable", { cause: lastError });
199
+ }
200
+ async expectJson(res) {
201
+ if (!res.ok) {
202
+ throw new PdfluxError(statusToCode(res.status), await readErrorMessage(res));
203
+ }
204
+ try {
205
+ return await res.json();
206
+ } catch (err) {
207
+ throw new PdfluxError("BAD_RESPONSE", "invalid JSON from preview service", { cause: err });
208
+ }
209
+ }
210
+ async createDocument(file, apiKey, signal) {
211
+ if (!apiKey) {
212
+ throw new PdfluxError("NANODOC_KEY_MISSING", "NanoDoc API key is required");
213
+ }
214
+ const form = new FormData();
215
+ form.append("file", new Blob([file.bytes], { type: "application/pdf" }), file.name);
216
+ form.append("parsers", "nanodoc");
217
+ form.append("nanodoc_api_key", apiKey);
218
+ const res = await this.request("/api/documents", { method: "POST", body: form }, signal, apiKey);
219
+ const payload = await this.expectJson(res);
220
+ const item = payload.items?.[0];
221
+ if (!item?.id) throw new PdfluxError("BAD_RESPONSE", "create response had no document item");
222
+ return item;
223
+ }
224
+ async getDocument(id, signal) {
225
+ const res = await this.request(`/api/documents/${encodeURIComponent(id)}`, { method: "GET" }, signal);
226
+ return this.expectJson(res);
227
+ }
228
+ async getMarkdown(id, signal) {
229
+ const res = await this.request(`/api/documents/${encodeURIComponent(id)}/markdown`, { method: "GET" }, signal);
230
+ if (res.status === 404) {
231
+ throw new PdfluxError("DOCUMENT_NOT_READY", "markdown is not ready");
232
+ }
233
+ if (!res.ok) {
234
+ throw new PdfluxError(statusToCode(res.status), await readErrorMessage(res));
235
+ }
236
+ return res.text();
237
+ }
238
+ async getMarkdownBlocks(id, signal) {
239
+ const res = await this.request(
240
+ `/api/documents/${encodeURIComponent(id)}/markdown-blocks`,
241
+ { method: "GET" },
242
+ signal
243
+ );
244
+ if (res.status === 404) {
245
+ throw new PdfluxError("DOCUMENT_NOT_READY", "markdown blocks are not ready");
246
+ }
247
+ const body = await this.expectJson(res);
248
+ if (!Array.isArray(body)) {
249
+ throw new PdfluxError("BAD_RESPONSE", "markdown-blocks response was not an array");
250
+ }
251
+ return body;
252
+ }
253
+ async waitForTerminal(id, options) {
254
+ const deadline = Date.now() + options.timeoutMs;
255
+ for (; ; ) {
256
+ const item = await this.getDocument(id, options.signal);
257
+ if (isTerminalState(item.status)) return item;
258
+ if (Date.now() >= deadline) return item;
259
+ await this.sleep(Math.min(options.pollIntervalMs, Math.max(0, deadline - Date.now())));
260
+ }
261
+ }
262
+ async getTranslationLayout(id, signal) {
263
+ const res = await this.request(
264
+ `/api/documents/${encodeURIComponent(id)}/translation/layout`,
265
+ { method: "GET" },
266
+ signal
267
+ );
268
+ const body = await this.expectJson(res);
269
+ const blocks = Array.isArray(body.blocks) ? body.blocks : Array.isArray(body.missing) ? body.missing : [];
270
+ return {
271
+ document_id: body.document_id || id,
272
+ target_lang: body.target_lang,
273
+ status: body.status,
274
+ complete: body.complete === true,
275
+ blocks,
276
+ missing: Array.isArray(body.missing) ? body.missing : blocks,
277
+ pages: body.pages
278
+ };
279
+ }
280
+ async getTranslation(id, targetLang, signal) {
281
+ const job = await this.getTranslationJob(id, targetLang, signal);
282
+ if (!job) return null;
283
+ return {
284
+ document_id: job.document_id,
285
+ target_lang: job.target_lang,
286
+ status: job.status,
287
+ complete: job.complete,
288
+ blocks: job.blocks,
289
+ missing: job.missing,
290
+ pages: job.pages,
291
+ markdown_url: job.markdown_url,
292
+ html_url: job.html_url,
293
+ docx_url: job.docx_url,
294
+ excel_url: job.excel_url,
295
+ translate_url: job.translate_url
296
+ };
297
+ }
298
+ async getTranslationJob(id, targetLang, signal) {
299
+ const qs = new URLSearchParams({ target_lang: targetLang });
300
+ const res = await this.request(
301
+ `/api/documents/${encodeURIComponent(id)}/translation?${qs}`,
302
+ { method: "GET" },
303
+ signal
304
+ );
305
+ if (res.status === 404) return null;
306
+ const body = await this.expectJson(res);
307
+ const missing = Array.isArray(body.missing) ? body.missing : [];
308
+ const blocks = Array.isArray(body.blocks) ? body.blocks : missing;
309
+ const rawPages = Array.isArray(body.pages) ? body.pages : [];
310
+ const pages = rawPages.map((page) => ({
311
+ page: page.page,
312
+ elements: Array.isArray(page.elements) ? page.elements : []
313
+ }));
314
+ return {
315
+ document_id: body.document_id || id,
316
+ target_lang: body.target_lang || targetLang,
317
+ status: body.status || "succeeded",
318
+ complete: body.complete === true || body.status === "succeeded",
319
+ blocks,
320
+ missing,
321
+ pages,
322
+ markdown_url: typeof body.markdown_url === "string" ? body.markdown_url : void 0,
323
+ html_url: typeof body.html_url === "string" ? body.html_url : void 0,
324
+ docx_url: typeof body.docx_url === "string" ? body.docx_url : void 0,
325
+ excel_url: typeof body.excel_url === "string" ? body.excel_url : void 0,
326
+ translate_url: typeof body.translate_url === "string" ? body.translate_url : void 0
327
+ };
328
+ }
329
+ async importTranslation(id, targetLang, translations, signal) {
330
+ const res = await this.request(
331
+ `/api/documents/${encodeURIComponent(id)}/translation`,
332
+ {
333
+ method: "PUT",
334
+ headers: { "content-type": "application/json" },
335
+ body: JSON.stringify({
336
+ target_lang: targetLang,
337
+ translations
338
+ })
339
+ },
340
+ signal
341
+ );
342
+ const body = await this.expectJson(res);
343
+ return {
344
+ document_id: body.document_id || id,
345
+ target_lang: body.target_lang || targetLang,
346
+ status: body.status,
347
+ complete: body.complete === true,
348
+ missing: Array.isArray(body.missing) ? body.missing : [],
349
+ message: body.message,
350
+ error: body.error,
351
+ markdown_url: typeof body.markdown_url === "string" ? body.markdown_url : void 0,
352
+ html_url: typeof body.html_url === "string" ? body.html_url : void 0,
353
+ docx_url: typeof body.docx_url === "string" ? body.docx_url : void 0,
354
+ excel_url: typeof body.excel_url === "string" ? body.excel_url : void 0,
355
+ translate_url: typeof body.translate_url === "string" ? body.translate_url : void 0
356
+ };
357
+ }
358
+ };
359
+ function absoluteDownloadUrl(baseUrl, pathOrUrl) {
360
+ if (/^https?:\/\//i.test(pathOrUrl)) return pathOrUrl;
361
+ const base = baseUrl.replace(/\/+$/, "");
362
+ return pathOrUrl.startsWith("/") ? `${base}${pathOrUrl}` : `${base}/${pathOrUrl}`;
363
+ }
364
+
365
+ // src/tools/index.ts
366
+ import { defineTool } from "@deepseek-ai/dsh-tools";
367
+
368
+ // src/block-citations.ts
369
+ function blockCiteUrl(previewUrl, block) {
370
+ const sep = previewUrl.includes("?") ? "&" : "?";
371
+ return `${previewUrl}${sep}block=${encodeURIComponent(block)}`;
372
+ }
373
+ function blockCitation(previewUrl, citationNumber, block) {
374
+ return `[![[${citationNumber}]](about:blank)](${blockCiteUrl(previewUrl, block)})`;
375
+ }
376
+ function formatCiteMarkdown(blocks, previewUrl, language2 = "zh") {
377
+ return blocks.map((block, index) => {
378
+ const page = block.page != null ? language2 === "en" ? `page ${block.page}` : `\u7B2C ${block.page} \u9875` : language2 === "en" ? "page unknown" : "\u9875\u7801\u672A\u77E5";
379
+ const citation = blockCitation(previewUrl, index + 1, block.id);
380
+ const header = `### block=${block.id} ${citation}\uFF08${page} \xB7 ${block.type}\uFF09`;
381
+ if (block.translation !== void 0) {
382
+ const source = block.content.trim();
383
+ const translated = block.translation.trim();
384
+ const sourceLabel = language2 === "en" ? "Source" : "\u539F\u6587";
385
+ const translatedLabel = language2 === "en" ? "Translation" : "\u8BD1\u6587";
386
+ return `${header}
387
+
388
+ ${sourceLabel}\uFF1A${source}
389
+
390
+ ${translatedLabel}\uFF1A${translated}`;
391
+ }
392
+ return `${header}
393
+
394
+ ${block.content.trim()}`;
395
+ }).join("\n\n");
396
+ }
397
+
398
+ // src/i18n.ts
399
+ function langOf(config) {
400
+ return resolvePluginLanguage(config.language.get(), config.baseUrl.get());
401
+ }
402
+ function L(lang, zh, en) {
403
+ return lang === "zh" ? zh : en;
404
+ }
405
+
406
+ // src/document-address.ts
407
+ var RESOURCE_PROTOCOL = "pdflux-result";
408
+ var RESOURCE_PREFIX = `dsh-resource://${RESOURCE_PROTOCOL}/`;
409
+ function documentAddress(documentId) {
410
+ return `${RESOURCE_PREFIX}${encodeURIComponent(documentId)}`;
411
+ }
412
+ function documentHref(documentId, params = {}) {
413
+ const search = new URLSearchParams();
414
+ if (params.view) search.set("view", params.view);
415
+ if (params.lang) search.set("lang", params.lang);
416
+ if (params.block) search.set("block", params.block);
417
+ const query = search.toString();
418
+ return query ? `${documentAddress(documentId)}?${query}` : documentAddress(documentId);
419
+ }
420
+
421
+ // src/sources.ts
422
+ import path from "node:path";
423
+ var PDF_MAGIC = "%PDF-";
424
+ function hasPdfMagic(bytes) {
425
+ if (bytes.length < PDF_MAGIC.length) return false;
426
+ for (let i = 0; i < PDF_MAGIC.length; i++) {
427
+ if (bytes[i] !== PDF_MAGIC.charCodeAt(i)) return false;
428
+ }
429
+ return true;
430
+ }
431
+ function basename(path4) {
432
+ const clean = path4.replace(/[/\\]+$/, "");
433
+ const idx = Math.max(clean.lastIndexOf("/"), clean.lastIndexOf("\\"));
434
+ return idx >= 0 ? clean.slice(idx + 1) : clean;
435
+ }
436
+ function assertPdfName(name2) {
437
+ if (!name2.toLowerCase().endsWith(".pdf")) {
438
+ throw new PdfluxError("UNSUPPORTED_FORMAT", `only PDF files are supported (got "${name2}")`);
439
+ }
440
+ }
441
+ function finish(name2, bytes, maxBytes) {
442
+ if (bytes.byteLength > maxBytes) {
443
+ throw new PdfluxError("FILE_TOO_LARGE", `file exceeds the ${Math.round(maxBytes / 1024 / 1024)} MiB limit`);
444
+ }
445
+ if (!hasPdfMagic(bytes)) {
446
+ throw new PdfluxError("UNSUPPORTED_FORMAT", `"${name2}" is not a valid PDF (missing %PDF- header)`);
447
+ }
448
+ return { name: name2, bytes };
449
+ }
450
+ async function loadPath(spec, deps) {
451
+ if (!deps.fs) throw new PdfluxError("SERVICE_UNAVAILABLE", "workspace filesystem service is unavailable");
452
+ const name2 = basename(spec.path);
453
+ assertPdfName(name2);
454
+ const target = await resolveWorkspaceFile(spec.path, deps.fs, deps.cwd, deps.signal);
455
+ let bytes;
456
+ try {
457
+ bytes = await deps.fs.readBytes(target, deps.signal, deps.maxBytes);
458
+ } catch (err) {
459
+ const code = err.code;
460
+ if (code === "FS_TOO_LARGE") throw new PdfluxError("FILE_TOO_LARGE", `file exceeds the size limit`, { cause: err });
461
+ if (code === "FS_NOT_FOUND" || code === "ENOENT") {
462
+ throw new PdfluxError("INVALID_INPUT", `file not found: ${spec.path}`, { cause: err });
463
+ }
464
+ throw err;
465
+ }
466
+ return finish(name2, bytes, deps.maxBytes);
467
+ }
468
+ async function loadAttachment(spec, deps) {
469
+ if (!deps.attachments) throw new PdfluxError("SERVICE_UNAVAILABLE", "attachment service is unavailable");
470
+ const ref = spec.attachment;
471
+ if (!ref || typeof ref.attachmentId !== "string" || typeof ref.name !== "string" || typeof ref.bytes !== "number") {
472
+ throw new PdfluxError("ATTACHMENT_REF_INCOMPLETE", "attachment reference must include attachmentId, name and bytes");
473
+ }
474
+ assertPdfName(ref.name);
475
+ const chunks = [];
476
+ let total = 0;
477
+ for await (const chunk of deps.attachments.readFileStream(ref, deps.signal)) {
478
+ total += chunk.byteLength;
479
+ if (total > deps.maxBytes) throw new PdfluxError("FILE_TOO_LARGE", "file exceeds the size limit");
480
+ chunks.push(chunk);
481
+ }
482
+ const bytes = new Uint8Array(total);
483
+ let offset = 0;
484
+ for (const chunk of chunks) {
485
+ bytes.set(chunk, offset);
486
+ offset += chunk.byteLength;
487
+ }
488
+ return finish(ref.name, bytes, deps.maxBytes);
489
+ }
490
+ async function loadSource(spec, deps) {
491
+ if ("path" in spec) return loadPath(spec, deps);
492
+ return loadAttachment(spec, deps);
493
+ }
494
+ async function resolveWorkspaceFile(input, fs, cwd, signal) {
495
+ if (!cwd) throw new PdfluxError("INVALID_INPUT", "session workspace is required");
496
+ const paths = /^[A-Za-z]:[\\/]/.test(cwd) ? path.win32 : path.posix;
497
+ const absolute = paths.resolve(cwd, input);
498
+ const relative = paths.relative(cwd, absolute);
499
+ if (!relative || relative === ".." || relative.startsWith(`..${paths.sep}`) || paths.isAbsolute(relative)) {
500
+ throw new PdfluxError("INVALID_INPUT", "PDF must be inside the session workspace");
501
+ }
502
+ if (!fs.lstat) throw new PdfluxError("INVALID_INPUT", "filesystem cannot verify workspace paths");
503
+ let current = cwd;
504
+ for (const part of relative.split(paths.sep)) {
505
+ current = paths.join(current, part);
506
+ const info = await fs.lstat(current, { cwd }, signal);
507
+ if (info?.type === "symlink") throw new PdfluxError("INVALID_INPUT", "symlink PDF paths are not supported");
508
+ }
509
+ return fs.resolve(absolute, { cwd });
510
+ }
511
+
512
+ // src/routes.ts
513
+ import { createReadStream, existsSync as existsSync2, statSync } from "node:fs";
514
+ import path3 from "node:path";
515
+ import { fileURLToPath } from "node:url";
516
+
517
+ // src/result-cache.ts
518
+ import { createHash as createHash2 } from "node:crypto";
519
+ import { existsSync } from "node:fs";
520
+ import {
521
+ mkdir,
522
+ readFile,
523
+ readdir,
524
+ rename,
525
+ rm,
526
+ stat,
527
+ utimes,
528
+ writeFile
529
+ } from "node:fs/promises";
530
+ import os from "node:os";
531
+ import path2 from "node:path";
532
+ var RESULT_CACHE_VERSION = 1;
533
+ var DEFAULT_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
534
+ var DEFAULT_MAX_TOTAL_BYTES = 2 * 1024 * 1024 * 1024;
535
+ var DEFAULT_MAX_ENTRY_BYTES = 512 * 1024 * 1024;
536
+ function envInt(name2, fallback) {
537
+ const raw = process.env[name2];
538
+ if (!raw) return fallback;
539
+ const n = Number(raw);
540
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
541
+ }
542
+ function defaultCacheRoot(plugin, rootOverride) {
543
+ const root = rootOverride || process.env.DSH_PLUGIN_CACHE_ROOT || path2.join(os.homedir(), ".dsh", "plugin-cache");
544
+ return path2.join(root, plugin);
545
+ }
546
+ function normalizeCacheOrigin(origin) {
547
+ return origin.replace(/\/+$/, "");
548
+ }
549
+ function cacheKey(origin, upstreamPath) {
550
+ const material = `${normalizeCacheOrigin(origin)}
551
+ ${upstreamPath}`;
552
+ return createHash2("sha256").update(material).digest("hex");
553
+ }
554
+ function pickResponseHeaders(headers) {
555
+ const out = {};
556
+ const contentType = headers.get("content-type");
557
+ const contentDisposition = headers.get("content-disposition");
558
+ const acceptRanges = headers.get("accept-ranges");
559
+ const etag = headers.get("etag");
560
+ const lastModified = headers.get("last-modified");
561
+ const rangeUnit = headers.get("x-range-unit");
562
+ if (contentType) out["content-type"] = contentType;
563
+ if (contentDisposition) out["content-disposition"] = contentDisposition;
564
+ if (acceptRanges) out["accept-ranges"] = acceptRanges;
565
+ if (etag) out.etag = etag;
566
+ if (lastModified) out["last-modified"] = lastModified;
567
+ if (rangeUnit) out["x-range-unit"] = rangeUnit;
568
+ return out;
569
+ }
570
+ function parseByteRanges(rangeHeader, size) {
571
+ const trimmed = rangeHeader.trim();
572
+ if (!trimmed.toLowerCase().startsWith("bytes=")) return { ok: false };
573
+ const specs = trimmed.slice(6).split(",").map((part) => part.trim()).filter(Boolean);
574
+ if (specs.length === 0) return { ok: false };
575
+ const ranges = [];
576
+ for (const spec of specs) {
577
+ const m = /^(\d*)-(\d*)$/.exec(spec);
578
+ if (!m) return { ok: false };
579
+ const startRaw = m[1];
580
+ const endRaw = m[2];
581
+ let start;
582
+ let end;
583
+ if (startRaw === "" && endRaw === "") return { ok: false };
584
+ if (startRaw === "") {
585
+ const suffix = Number(endRaw);
586
+ if (!Number.isFinite(suffix) || suffix <= 0) return { ok: false };
587
+ start = Math.max(0, size - suffix);
588
+ end = size - 1;
589
+ } else {
590
+ start = Number(startRaw);
591
+ end = endRaw === "" ? size - 1 : Number(endRaw);
592
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return { ok: false };
593
+ }
594
+ if (start < 0 || end < start || start >= size) return { ok: false };
595
+ if (end >= size) end = size - 1;
596
+ ranges.push({ start, end });
597
+ }
598
+ return { ok: true, ranges };
599
+ }
600
+ function sliceBodyForRanges(body, ranges) {
601
+ const size = body.byteLength;
602
+ if (ranges.length === 1) {
603
+ const range = ranges[0];
604
+ return {
605
+ status: 206,
606
+ body: body.subarray(range.start, range.end + 1),
607
+ contentRange: `bytes ${range.start}-${range.end}/${size}`
608
+ };
609
+ }
610
+ const parts = ranges.map((range) => body.subarray(range.start, range.end + 1));
611
+ const contentRange = `bytes ${ranges.map((range) => `${range.start}-${range.end}`).join(",")}/${size}`;
612
+ return {
613
+ status: 206,
614
+ body: Buffer.concat(parts),
615
+ contentRange
616
+ };
617
+ }
618
+ var ResultCache = class {
619
+ rootDir;
620
+ ttlMs;
621
+ maxTotalBytes;
622
+ maxEntryBytes;
623
+ now;
624
+ inflight = /* @__PURE__ */ new Map();
625
+ constructor(options) {
626
+ this.rootDir = options.rootDir ?? defaultCacheRoot(options.plugin);
627
+ this.ttlMs = options.ttlMs ?? envInt("DSH_PLUGIN_CACHE_TTL_MS", DEFAULT_TTL_MS);
628
+ this.maxTotalBytes = options.maxTotalBytes ?? envInt("DSH_PLUGIN_CACHE_MAX_BYTES", DEFAULT_MAX_TOTAL_BYTES);
629
+ this.maxEntryBytes = options.maxEntryBytes ?? envInt("DSH_PLUGIN_CACHE_MAX_ENTRY_BYTES", DEFAULT_MAX_ENTRY_BYTES);
630
+ this.now = options.now ?? Date.now;
631
+ }
632
+ entryDir(key) {
633
+ return path2.join(this.rootDir, key);
634
+ }
635
+ async get(key) {
636
+ const dir = this.entryDir(key);
637
+ const metaPath = path2.join(dir, "meta.json");
638
+ const bodyPath = path2.join(dir, "body");
639
+ if (!existsSync(metaPath) || !existsSync(bodyPath)) return null;
640
+ try {
641
+ const meta = JSON.parse(await readFile(metaPath, "utf8"));
642
+ if (meta.version !== RESULT_CACHE_VERSION || meta.key !== key) {
643
+ await this.delete(key);
644
+ return null;
645
+ }
646
+ const age = this.now() - meta.cachedAt;
647
+ if (age < 0 || age > this.ttlMs) {
648
+ await this.delete(key);
649
+ return null;
650
+ }
651
+ const bodyStat = await stat(bodyPath);
652
+ if (bodyStat.size !== meta.size) {
653
+ await this.delete(key);
654
+ return null;
655
+ }
656
+ const body = await readFile(bodyPath);
657
+ meta.lastAccess = this.now();
658
+ await writeFile(metaPath, `${JSON.stringify(meta)}
659
+ `, "utf8");
660
+ try {
661
+ await utimes(bodyPath, /* @__PURE__ */ new Date(), new Date(meta.lastAccess));
662
+ } catch {
663
+ }
664
+ return { meta, bodyPath, body };
665
+ } catch {
666
+ await this.delete(key);
667
+ return null;
668
+ }
669
+ }
670
+ async put(key, input) {
671
+ if (input.status !== 200) return null;
672
+ if (input.body.byteLength > this.maxEntryBytes) return null;
673
+ await mkdir(this.rootDir, { recursive: true });
674
+ const dir = this.entryDir(key);
675
+ const tmpDir = `${dir}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
676
+ const now = this.now();
677
+ const meta = {
678
+ version: RESULT_CACHE_VERSION,
679
+ key,
680
+ origin: normalizeCacheOrigin(input.origin),
681
+ upstreamPath: input.upstreamPath,
682
+ status: 200,
683
+ size: input.body.byteLength,
684
+ cachedAt: now,
685
+ lastAccess: now,
686
+ responseHeaders: pickResponseHeaders(input.headers)
687
+ };
688
+ try {
689
+ await mkdir(tmpDir, { recursive: true });
690
+ await writeFile(path2.join(tmpDir, "body"), input.body);
691
+ await writeFile(path2.join(tmpDir, "meta.json"), `${JSON.stringify(meta)}
692
+ `, "utf8");
693
+ await rm(dir, { recursive: true, force: true });
694
+ await rename(tmpDir, dir);
695
+ } catch {
696
+ await rm(tmpDir, { recursive: true, force: true }).catch(() => {
697
+ });
698
+ return null;
699
+ }
700
+ await this.enforceQuota();
701
+ return { meta, bodyPath: path2.join(dir, "body"), body: input.body };
702
+ }
703
+ async delete(key) {
704
+ await rm(this.entryDir(key), { recursive: true, force: true }).catch(() => {
705
+ });
706
+ }
707
+ async enforceQuota() {
708
+ let entries;
709
+ try {
710
+ const names = await readdir(this.rootDir);
711
+ entries = [];
712
+ for (const name2 of names) {
713
+ if (name2.includes(".")) continue;
714
+ const dir = path2.join(this.rootDir, name2);
715
+ const metaPath = path2.join(dir, "meta.json");
716
+ const bodyPath = path2.join(dir, "body");
717
+ try {
718
+ const meta = JSON.parse(await readFile(metaPath, "utf8"));
719
+ const bodyStat = await stat(bodyPath);
720
+ entries.push({
721
+ key: name2,
722
+ size: bodyStat.size,
723
+ lastAccess: meta.lastAccess || meta.cachedAt || 0
724
+ });
725
+ } catch {
726
+ await rm(dir, { recursive: true, force: true }).catch(() => {
727
+ });
728
+ }
729
+ }
730
+ } catch {
731
+ return;
732
+ }
733
+ let total = entries.reduce((sum, entry) => sum + entry.size, 0);
734
+ if (total <= this.maxTotalBytes) return;
735
+ entries.sort((a, b) => a.lastAccess - b.lastAccess);
736
+ const target = Math.floor(this.maxTotalBytes * 0.9);
737
+ for (const entry of entries) {
738
+ if (total <= target) break;
739
+ await this.delete(entry.key);
740
+ total -= entry.size;
741
+ }
742
+ }
743
+ async getOrFetch(args) {
744
+ const key = cacheKey(args.origin, args.upstreamPath);
745
+ const existing = await this.get(key);
746
+ if (existing) return { hit: existing, fromCache: true };
747
+ let pending = this.inflight.get(key);
748
+ if (!pending) {
749
+ pending = (async () => {
750
+ const full = await args.fetchFull(args.signal);
751
+ if (full.status === 200) {
752
+ const hit = await this.put(key, {
753
+ origin: args.origin,
754
+ upstreamPath: args.upstreamPath,
755
+ status: full.status,
756
+ headers: full.headers,
757
+ body: full.body
758
+ });
759
+ if (hit) return { kind: "hit", hit, fromCache: false };
760
+ }
761
+ return { kind: "bypass", full };
762
+ })().finally(() => {
763
+ this.inflight.delete(key);
764
+ });
765
+ this.inflight.set(key, pending);
766
+ }
767
+ const result = await pending;
768
+ if (result.kind === "hit") return { hit: result.hit, fromCache: result.fromCache };
769
+ return { bypass: result.full };
770
+ }
771
+ };
772
+ function serveCacheHit(req, res, hit, fromCache) {
773
+ const headers = {
774
+ "x-dsh-cache": fromCache ? "hit" : "miss",
775
+ "accept-ranges": hit.meta.responseHeaders["accept-ranges"] || "bytes"
776
+ };
777
+ const contentType = hit.meta.responseHeaders["content-type"];
778
+ const contentDisposition = hit.meta.responseHeaders["content-disposition"];
779
+ const etag = hit.meta.responseHeaders.etag;
780
+ const lastModified = hit.meta.responseHeaders["last-modified"];
781
+ const rangeUnit = hit.meta.responseHeaders["x-range-unit"];
782
+ if (contentType) headers["content-type"] = contentType;
783
+ if (contentDisposition) headers["content-disposition"] = contentDisposition;
784
+ if (etag) headers.etag = etag;
785
+ if (lastModified) headers["last-modified"] = lastModified;
786
+ if (rangeUnit) headers["x-range-unit"] = rangeUnit;
787
+ const rangeHeader = typeof req.headers.range === "string" ? req.headers.range : void 0;
788
+ if (!rangeHeader) {
789
+ headers["content-length"] = String(hit.body.byteLength);
790
+ res.writeHead(200, headers);
791
+ if (req.method === "HEAD") {
792
+ res.end();
793
+ return;
794
+ }
795
+ res.end(hit.body);
796
+ return;
797
+ }
798
+ const parsed = parseByteRanges(rangeHeader, hit.body.byteLength);
799
+ if (!parsed.ok) {
800
+ headers["content-range"] = `bytes */${hit.body.byteLength}`;
801
+ headers["content-length"] = "0";
802
+ res.writeHead(416, headers);
803
+ res.end();
804
+ return;
805
+ }
806
+ const sliced = sliceBodyForRanges(hit.body, parsed.ranges);
807
+ headers["content-range"] = sliced.contentRange;
808
+ headers["content-length"] = String(sliced.body.byteLength);
809
+ if (typeof req.headers["x-range-unit"] === "string" && !headers["x-range-unit"]) {
810
+ headers["x-range-unit"] = req.headers["x-range-unit"];
811
+ }
812
+ res.writeHead(sliced.status, headers);
813
+ if (req.method === "HEAD") {
814
+ res.end();
815
+ return;
816
+ }
817
+ res.end(sliced.body);
818
+ }
819
+
820
+ // src/routes.ts
821
+ var PLUGIN_API_PREFIX = "/pdflux/api";
822
+ var DOCUMENTS_PREFIX = `${PLUGIN_API_PREFIX}/documents`;
823
+ var ASSETS_PREFIX = "/pdflux/assets";
824
+ var HOP_BY_HOP = /* @__PURE__ */ new Set([
825
+ "connection",
826
+ "keep-alive",
827
+ "proxy-authenticate",
828
+ "proxy-authorization",
829
+ "te",
830
+ "trailers",
831
+ "transfer-encoding",
832
+ "upgrade",
833
+ "host",
834
+ "content-length"
835
+ ]);
836
+ var SKIP_REQUEST_HEADERS = /* @__PURE__ */ new Set([
837
+ ...HOP_BY_HOP,
838
+ "accept-encoding",
839
+ "cookie",
840
+ "authorization",
841
+ "origin",
842
+ "referer"
843
+ ]);
844
+ var SKIP_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
845
+ ...HOP_BY_HOP,
846
+ "content-encoding",
847
+ "content-length"
848
+ ]);
849
+ var EXPORT_FORMATS = /* @__PURE__ */ new Set(["markdown", "html", "docx", "excel"]);
850
+ function defaultAssetsRoot() {
851
+ return path3.resolve(path3.dirname(fileURLToPath(import.meta.url)), "assets");
852
+ }
853
+ function parseDocumentApiPath(pathname, search = "") {
854
+ if (!pathname.startsWith(`${DOCUMENTS_PREFIX}/`)) return null;
855
+ const rest = pathname.slice(DOCUMENTS_PREFIX.length + 1);
856
+ const parts = rest.split("/").filter(Boolean).map((part) => {
857
+ try {
858
+ return decodeURIComponent(part);
859
+ } catch {
860
+ return null;
861
+ }
862
+ });
863
+ if (parts.some((part) => part == null)) return null;
864
+ const [id, a, b, c] = parts;
865
+ if (!id || id.includes("\\") || id.includes("..") || id.includes("\0")) return null;
866
+ if (!a) return { kind: "detail", id };
867
+ if (a === "file" && !b) return { kind: "file", id };
868
+ if (a === "file" && b === "range-index" && !c) return { kind: "range-index", id };
869
+ if (EXPORT_FORMATS.has(a) && !b) return { kind: "export", id, format: a };
870
+ if (a === "markdown-blocks" && !b) return { kind: "markdown-blocks", id };
871
+ if (a === "nano" && !b) return { kind: "nano", id };
872
+ if (a === "interdoc" && !b) return { kind: "interdoc", id };
873
+ if (a === "translation" && !b) return { kind: "translation", id, search };
874
+ if (a === "translation" && b === "layout" && !c) return { kind: "translation-layout", id };
875
+ if (a === "translation" && EXPORT_FORMATS.has(b) && !c) {
876
+ return { kind: "translation-export", id, format: b, search };
877
+ }
878
+ return null;
879
+ }
880
+ function rewriteDocumentUrls(item, documentId) {
881
+ const base = `${DOCUMENTS_PREFIX}/${encodeURIComponent(documentId)}`;
882
+ return {
883
+ ...item,
884
+ document_url: item.document_url ? `${base}/file` : item.document_url,
885
+ markdown_url: `${base}/markdown`,
886
+ markdown_blocks_url: `${base}/markdown-blocks`,
887
+ html_url: `${base}/html`,
888
+ docx_url: `${base}/docx`,
889
+ excel_url: `${base}/excel`,
890
+ nano_url: `${base}/nano`,
891
+ interdoc_url: `${base}/interdoc`,
892
+ translation_url: `${base}/translation`,
893
+ translation_layout_url: `${base}/translation/layout`,
894
+ file_url: `${base}/file`
895
+ };
896
+ }
897
+ function pluginDocumentDownloadUrls(documentId) {
898
+ const base = `${DOCUMENTS_PREFIX}/${encodeURIComponent(documentId)}`;
899
+ return {
900
+ markdown_url: `${base}/markdown`,
901
+ html_url: `${base}/html`,
902
+ docx_url: `${base}/docx`,
903
+ excel_url: `${base}/excel`
904
+ };
905
+ }
906
+ function pluginTranslationDownloadUrls(documentId, targetLang) {
907
+ const base = `${DOCUMENTS_PREFIX}/${encodeURIComponent(documentId)}`;
908
+ const lang = encodeURIComponent(targetLang);
909
+ return {
910
+ markdown_url: `${base}/translation/markdown?target_lang=${lang}`,
911
+ html_url: `${base}/translation/html?target_lang=${lang}`,
912
+ docx_url: `${base}/translation/docx?target_lang=${lang}`,
913
+ excel_url: `${base}/translation/excel?target_lang=${lang}`
914
+ };
915
+ }
916
+ function bindClientAbort(req, res, controller) {
917
+ const onAbort = () => {
918
+ if (!res.writableFinished) controller.abort();
919
+ };
920
+ req.on("aborted", onAbort);
921
+ res.on("close", onAbort);
922
+ return () => {
923
+ req.off("aborted", onAbort);
924
+ res.off("close", onAbort);
925
+ };
926
+ }
927
+ function sendJson(res, status, body) {
928
+ const payload = JSON.stringify(body);
929
+ res.writeHead(status, {
930
+ "content-type": "application/json; charset=utf-8",
931
+ "content-length": Buffer.byteLength(payload)
932
+ });
933
+ res.end(payload);
934
+ }
935
+ async function readRequestJson(req) {
936
+ const chunks = [];
937
+ for await (const chunk of req) {
938
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
939
+ }
940
+ const text2 = Buffer.concat(chunks).toString("utf8").trim();
941
+ if (!text2) return null;
942
+ return JSON.parse(text2);
943
+ }
944
+ function publicConfig(deps) {
945
+ const baseUrl = deps.config.baseUrl.get();
946
+ return {
947
+ nanodocApiKeyRefZh: deps.config.nanodocApiKeyRefZh.get(),
948
+ nanodocApiKeyRefEn: deps.config.nanodocApiKeyRefEn.get(),
949
+ baseUrl,
950
+ language: resolvePluginLanguage(deps.config.language.get(), baseUrl)
951
+ };
952
+ }
953
+ function rejectIfUnauthorized(deps, req, res) {
954
+ const rejection = deps.connection?.requestRejection({ headers: req.headers });
955
+ if (!rejection) return false;
956
+ res.writeHead(rejection);
957
+ res.end();
958
+ return true;
959
+ }
960
+ async function resolveBackend(deps, record) {
961
+ const current = normalizeOrigin(resolveServiceBaseUrl(deps.config.baseUrl.get()));
962
+ if (!record.backend_origin) {
963
+ await deps.registry.register({ ...record, backend_origin: current });
964
+ return { ok: true, origin: current };
965
+ }
966
+ const origin = normalizeOrigin(record.backend_origin);
967
+ if (origin !== current) {
968
+ return {
969
+ ok: false,
970
+ status: 409,
971
+ message: resolvePluginLanguage(deps.config.language.get(), deps.config.baseUrl.get()) === "en" ? `Registered service (${origin}) differs from current config (${current}); switch back or create a new convert` : `\u4EFB\u52A1\u767B\u8BB0\u7684\u670D\u52A1\uFF08${origin}\uFF09\u4E0E\u5F53\u524D\u914D\u7F6E\uFF08${current}\uFF09\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u5207\u6362\u56DE\u539F\u670D\u52A1\u6216\u91CD\u65B0\u521B\u5EFA\u8F6C\u6362`
972
+ };
973
+ }
974
+ return { ok: true, origin };
975
+ }
976
+ function requestHeaders(req) {
977
+ const headers = new Headers();
978
+ for (const [name2, value] of Object.entries(req.headers)) {
979
+ if (value == null || SKIP_REQUEST_HEADERS.has(name2.toLowerCase())) continue;
980
+ if (Array.isArray(value)) {
981
+ for (const item of value) headers.append(name2, item);
982
+ } else {
983
+ headers.set(name2, value);
984
+ }
985
+ }
986
+ return headers;
987
+ }
988
+ async function buildUpstreamHeaders(deps, req, options) {
989
+ const headers = requestHeaders(req);
990
+ if (options?.dropRange) headers.delete("range");
991
+ headers.set("accept-encoding", "identity");
992
+ const key = deps.resolveApiKey ? await deps.resolveApiKey() : void 0;
993
+ if (key) headers.set("Authorization", `Bearer ${key}`);
994
+ return headers;
995
+ }
996
+ async function readUpstreamBody(upstream) {
997
+ if (!upstream.body) return Buffer.alloc(0);
998
+ const reader = upstream.body.getReader();
999
+ const chunks = [];
1000
+ for (; ; ) {
1001
+ const { done, value } = await reader.read();
1002
+ if (done) break;
1003
+ chunks.push(Buffer.from(value));
1004
+ }
1005
+ return Buffer.concat(chunks);
1006
+ }
1007
+ async function proxyUpstream(deps, req, res, origin, upstreamPath) {
1008
+ const fetchImpl = deps.fetchImpl ?? ((input, init) => fetch(input, init));
1009
+ const controller = new AbortController();
1010
+ const unbind = bindClientAbort(req, res, controller);
1011
+ try {
1012
+ const headersOut = await buildUpstreamHeaders(deps, req);
1013
+ const upstream = await fetchImpl(`${origin}${upstreamPath}`, {
1014
+ method: req.method,
1015
+ headers: headersOut,
1016
+ signal: controller.signal
1017
+ });
1018
+ const headers = { "x-dsh-cache": "bypass" };
1019
+ upstream.headers.forEach((value, key) => {
1020
+ if (SKIP_RESPONSE_HEADERS.has(key.toLowerCase())) return;
1021
+ headers[key] = value;
1022
+ });
1023
+ res.writeHead(upstream.status, headers);
1024
+ if (!upstream.body) {
1025
+ res.end();
1026
+ return;
1027
+ }
1028
+ const reader = upstream.body.getReader();
1029
+ for (; ; ) {
1030
+ const { done, value } = await reader.read();
1031
+ if (done) break;
1032
+ if (!res.write(Buffer.from(value))) {
1033
+ await new Promise((resolve) => res.once("drain", resolve));
1034
+ }
1035
+ }
1036
+ res.end();
1037
+ } catch (err) {
1038
+ if (controller.signal.aborted || res.headersSent) {
1039
+ if (!res.writableEnded) res.end();
1040
+ return;
1041
+ }
1042
+ sendJson(res, 502, {
1043
+ status: "error",
1044
+ message: err instanceof Error ? err.message : String(err)
1045
+ });
1046
+ } finally {
1047
+ unbind();
1048
+ }
1049
+ }
1050
+ async function proxyCached(deps, req, res, origin, upstreamPath) {
1051
+ const cache = deps.resultCache;
1052
+ if (!cache) {
1053
+ await proxyUpstream(deps, req, res, origin, upstreamPath);
1054
+ return;
1055
+ }
1056
+ const fetchImpl = deps.fetchImpl ?? ((input, init) => fetch(input, init));
1057
+ const controller = new AbortController();
1058
+ const unbind = bindClientAbort(req, res, controller);
1059
+ try {
1060
+ const result = await cache.getOrFetch({
1061
+ origin,
1062
+ upstreamPath,
1063
+ signal: controller.signal,
1064
+ fetchFull: async (signal) => {
1065
+ const headersOut = await buildUpstreamHeaders(deps, req, { dropRange: true });
1066
+ const upstream = await fetchImpl(`${origin}${upstreamPath}`, {
1067
+ method: "GET",
1068
+ headers: headersOut,
1069
+ signal
1070
+ });
1071
+ const body = await readUpstreamBody(upstream);
1072
+ return { status: upstream.status, headers: upstream.headers, body };
1073
+ }
1074
+ });
1075
+ if ("hit" in result) {
1076
+ serveCacheHit(req, res, result.hit, result.fromCache);
1077
+ return;
1078
+ }
1079
+ const headers = { "x-dsh-cache": "bypass" };
1080
+ result.bypass.headers.forEach((value, key) => {
1081
+ if (SKIP_RESPONSE_HEADERS.has(key.toLowerCase())) return;
1082
+ headers[key] = value;
1083
+ });
1084
+ headers["content-length"] = String(result.bypass.body.byteLength);
1085
+ res.writeHead(result.bypass.status, headers);
1086
+ if (req.method === "HEAD") {
1087
+ res.end();
1088
+ return;
1089
+ }
1090
+ res.end(result.bypass.body);
1091
+ } catch (err) {
1092
+ if (controller.signal.aborted || res.headersSent) {
1093
+ if (!res.writableEnded) res.end();
1094
+ return;
1095
+ }
1096
+ sendJson(res, 502, {
1097
+ status: "error",
1098
+ message: err instanceof Error ? err.message : String(err)
1099
+ });
1100
+ } finally {
1101
+ unbind();
1102
+ }
1103
+ }
1104
+ async function handleDocumentRequest(deps, req, res, pathname, search) {
1105
+ if (rejectIfUnauthorized(deps, req, res)) return;
1106
+ if (req.method !== "GET" && req.method !== "HEAD") {
1107
+ res.writeHead(405, { allow: "GET, HEAD" });
1108
+ res.end();
1109
+ return;
1110
+ }
1111
+ const parsed = parseDocumentApiPath(pathname, search);
1112
+ if (!parsed) {
1113
+ res.writeHead(404);
1114
+ res.end();
1115
+ return;
1116
+ }
1117
+ const record = deps.registry.lookup(parsed.id);
1118
+ if (!record) {
1119
+ sendJson(res, 404, { status: "error", message: "unknown document id" });
1120
+ return;
1121
+ }
1122
+ const backend = await resolveBackend(deps, record);
1123
+ if (!backend.ok) {
1124
+ sendJson(res, backend.status, { status: "error", message: backend.message });
1125
+ return;
1126
+ }
1127
+ const encodedId = encodeURIComponent(parsed.id);
1128
+ if (parsed.kind === "detail") {
1129
+ const fetchImpl = deps.fetchImpl ?? ((input, init) => fetch(input, init));
1130
+ const controller = new AbortController();
1131
+ const unbind = bindClientAbort(req, res, controller);
1132
+ try {
1133
+ const headersOut = await buildUpstreamHeaders(deps, req);
1134
+ const upstream = await fetchImpl(`${backend.origin}/api/documents/${encodedId}`, {
1135
+ method: "GET",
1136
+ headers: headersOut,
1137
+ signal: controller.signal
1138
+ });
1139
+ const text2 = await upstream.text();
1140
+ if (!upstream.ok) {
1141
+ res.writeHead(upstream.status, { "content-type": upstream.headers.get("content-type") || "application/json" });
1142
+ res.end(text2);
1143
+ return;
1144
+ }
1145
+ const item = JSON.parse(text2);
1146
+ sendJson(res, 200, rewriteDocumentUrls(item, parsed.id));
1147
+ } catch (err) {
1148
+ if (controller.signal.aborted || res.headersSent) {
1149
+ if (!res.writableEnded) res.end();
1150
+ return;
1151
+ }
1152
+ sendJson(res, 502, { status: "error", message: err instanceof Error ? err.message : String(err) });
1153
+ } finally {
1154
+ unbind();
1155
+ }
1156
+ return;
1157
+ }
1158
+ if (parsed.kind === "range-index") {
1159
+ await proxyCached(deps, req, res, backend.origin, `/api/documents/${encodedId}/file/range-index`);
1160
+ return;
1161
+ }
1162
+ if (parsed.kind === "export") {
1163
+ await proxyCached(deps, req, res, backend.origin, `/api/documents/${encodedId}/${parsed.format}`);
1164
+ return;
1165
+ }
1166
+ if (parsed.kind === "markdown-blocks" || parsed.kind === "nano" || parsed.kind === "interdoc") {
1167
+ await proxyCached(deps, req, res, backend.origin, `/api/documents/${encodedId}/${parsed.kind}`);
1168
+ return;
1169
+ }
1170
+ if (parsed.kind === "translation-layout") {
1171
+ await proxyCached(deps, req, res, backend.origin, `/api/documents/${encodedId}/translation/layout`);
1172
+ return;
1173
+ }
1174
+ if (parsed.kind === "translation") {
1175
+ await proxyUpstream(
1176
+ deps,
1177
+ req,
1178
+ res,
1179
+ backend.origin,
1180
+ `/api/documents/${encodedId}/translation${parsed.search}`
1181
+ );
1182
+ return;
1183
+ }
1184
+ if (parsed.kind === "translation-export") {
1185
+ const query = parsed.search || "";
1186
+ await proxyCached(
1187
+ deps,
1188
+ req,
1189
+ res,
1190
+ backend.origin,
1191
+ `/api/documents/${encodedId}/translation/${parsed.format}${query.startsWith("?") || query === "" ? query : `?${query}`}`
1192
+ );
1193
+ return;
1194
+ }
1195
+ await proxyCached(deps, req, res, backend.origin, `/api/documents/${encodedId}/file`);
1196
+ }
1197
+ function contentTypeFor(filePath) {
1198
+ switch (path3.extname(filePath).toLowerCase()) {
1199
+ case ".js":
1200
+ case ".mjs":
1201
+ return "text/javascript; charset=utf-8";
1202
+ case ".css":
1203
+ return "text/css; charset=utf-8";
1204
+ case ".wasm":
1205
+ return "application/wasm";
1206
+ case ".json":
1207
+ case ".map":
1208
+ return "application/json; charset=utf-8";
1209
+ case ".woff":
1210
+ return "font/woff";
1211
+ case ".woff2":
1212
+ return "font/woff2";
1213
+ case ".ttf":
1214
+ return "font/ttf";
1215
+ case ".png":
1216
+ return "image/png";
1217
+ case ".svg":
1218
+ return "image/svg+xml";
1219
+ default:
1220
+ return "application/octet-stream";
1221
+ }
1222
+ }
1223
+ function resolveAssetPath(assetsRoot, pathname) {
1224
+ if (!pathname.startsWith(`${ASSETS_PREFIX}/`)) return null;
1225
+ let relative;
1226
+ try {
1227
+ relative = decodeURIComponent(pathname.slice(ASSETS_PREFIX.length + 1));
1228
+ } catch {
1229
+ return null;
1230
+ }
1231
+ if (!relative || relative.includes("\0")) return null;
1232
+ const root = path3.resolve(assetsRoot);
1233
+ const target = path3.resolve(root, relative);
1234
+ if (target !== root && !target.startsWith(root + path3.sep)) return null;
1235
+ if (!existsSync2(target) || !statSync(target).isFile()) return null;
1236
+ return target;
1237
+ }
1238
+ function handleAssetRequest(deps, req, res, pathname) {
1239
+ if (req.method !== "GET" && req.method !== "HEAD") {
1240
+ res.writeHead(405, { allow: "GET, HEAD" });
1241
+ res.end();
1242
+ return;
1243
+ }
1244
+ const filePath = resolveAssetPath(deps.assetsRoot ?? defaultAssetsRoot(), pathname);
1245
+ if (!filePath) {
1246
+ res.writeHead(404);
1247
+ res.end();
1248
+ return;
1249
+ }
1250
+ const stat2 = statSync(filePath);
1251
+ res.writeHead(200, {
1252
+ "content-type": contentTypeFor(filePath),
1253
+ "content-length": stat2.size,
1254
+ "cache-control": "public, max-age=31536000, immutable"
1255
+ });
1256
+ if (req.method === "HEAD") {
1257
+ res.end();
1258
+ return;
1259
+ }
1260
+ createReadStream(filePath).pipe(res);
1261
+ }
1262
+ function requestUrl(req) {
1263
+ try {
1264
+ return new URL(req.url || "/", "http://localhost");
1265
+ } catch {
1266
+ return new URL("/", "http://localhost");
1267
+ }
1268
+ }
1269
+ function registerRoutes(ctx, deps) {
1270
+ ctx.effect(() => ctx.webServer.register({
1271
+ kind: "exact",
1272
+ path: `${PLUGIN_API_PREFIX}/config`,
1273
+ handler: (req, res) => {
1274
+ if (rejectIfUnauthorized(deps, req, res)) return;
1275
+ if (req.method === "GET") {
1276
+ sendJson(res, 200, publicConfig(deps));
1277
+ return;
1278
+ }
1279
+ if (req.method !== "PUT") {
1280
+ res.writeHead(405, { allow: "GET, PUT" });
1281
+ res.end();
1282
+ return;
1283
+ }
1284
+ if (!deps.updateConfig && !deps.updateBaseUrl) {
1285
+ sendJson(res, 501, { message: "\u8BED\u8A00\u914D\u7F6E\u5199\u5165\u672A\u542F\u7528" });
1286
+ return;
1287
+ }
1288
+ void (async () => {
1289
+ try {
1290
+ const body = await readRequestJson(req);
1291
+ const patch = body && typeof body === "object" ? body : {};
1292
+ if (!isPluginLanguage(patch.language)) {
1293
+ sendJson(res, 400, { message: "\u8BF7\u6C42\u4F53\u9700\u8981 language\uFF08zh \u6216 en\uFF09" });
1294
+ return;
1295
+ }
1296
+ const language2 = patch.language;
1297
+ const baseUrl = GATEWAY_BY_LANGUAGE[language2];
1298
+ if (deps.updateConfig) {
1299
+ await deps.updateConfig({ language: language2, baseUrl });
1300
+ } else {
1301
+ await deps.updateBaseUrl(baseUrl);
1302
+ }
1303
+ sendJson(res, 200, publicConfig(deps));
1304
+ } catch (err) {
1305
+ const message = err instanceof Error ? err.message : "\u4FDD\u5B58\u8BED\u8A00\u5931\u8D25";
1306
+ sendJson(res, 500, { message });
1307
+ }
1308
+ })();
1309
+ }
1310
+ }), "pdflux: config route");
1311
+ ctx.effect(() => ctx.webServer.register({
1312
+ kind: "prefix",
1313
+ path: DOCUMENTS_PREFIX,
1314
+ handler: (req, res) => {
1315
+ const url = requestUrl(req);
1316
+ void handleDocumentRequest(deps, req, res, url.pathname, url.search);
1317
+ }
1318
+ }), "pdflux: document proxy routes");
1319
+ ctx.effect(() => ctx.webServer.register({
1320
+ kind: "prefix",
1321
+ path: ASSETS_PREFIX,
1322
+ handler: (req, res) => {
1323
+ handleAssetRequest(deps, req, res, requestUrl(req).pathname);
1324
+ }
1325
+ }), "pdflux: asset routes");
1326
+ }
1327
+
1328
+ // src/tools/index.ts
1329
+ function logFailedDocument(deps, documentId, error) {
1330
+ if (!error) return;
1331
+ deps.logger?.debug("pdflux: document %s failed: %s", documentId, error);
1332
+ }
1333
+ function text(value) {
1334
+ return [{ type: "text", text: value }];
1335
+ }
1336
+ function nextActionOf(state) {
1337
+ if (state === "succeeded") return "export";
1338
+ if (state === "failed") return "report_failure";
1339
+ return "wait";
1340
+ }
1341
+ function assertRegistered(deps, id) {
1342
+ const record = deps.registry.lookup(id);
1343
+ if (!record) throw new PdfluxError("DOCUMENT_NOT_FOUND", "unknown document id");
1344
+ return record;
1345
+ }
1346
+ function parseTargetLang(raw) {
1347
+ if (typeof raw !== "string" || !raw.trim()) {
1348
+ throw new PdfluxError("INVALID_INPUT", "target_lang is required");
1349
+ }
1350
+ const normalized = raw.trim().toLowerCase();
1351
+ if (normalized === "zh" || normalized === "zh-cn" || normalized === "cn" || normalized === "chinese") {
1352
+ return "zh";
1353
+ }
1354
+ if (normalized === "en" || normalized === "en-us" || normalized === "english") {
1355
+ return "en";
1356
+ }
1357
+ return normalized;
1358
+ }
1359
+ function ensureParsed(item) {
1360
+ if (!isTerminalState(item.status)) {
1361
+ throw new PdfluxError("DOCUMENT_NOT_READY", `document is still ${item.status}`);
1362
+ }
1363
+ if (item.status === "failed") {
1364
+ throw new PdfluxError("DOCUMENT_FAILED", "document failed; create a new convert instead");
1365
+ }
1366
+ }
1367
+ var TRANSLATE_BATCH_SIZE = 10;
1368
+ function takeTranslateBatch(items) {
1369
+ const total_count = items.length;
1370
+ return {
1371
+ total_count,
1372
+ batch: items.slice(0, TRANSLATE_BATCH_SIZE)
1373
+ };
1374
+ }
1375
+ function slimBlocks(blocks) {
1376
+ return blocks.map((block) => {
1377
+ const out = {
1378
+ key: block.key,
1379
+ index: block.index,
1380
+ page: block.page,
1381
+ element_type: block.element_type,
1382
+ text: block.text
1383
+ };
1384
+ if (block.cell_key) out.cell_key = block.cell_key;
1385
+ return out;
1386
+ });
1387
+ }
1388
+ function renderTranslatePayload(header, field, items) {
1389
+ return text(`${header}
1390
+
1391
+ ${field}=${JSON.stringify(items ?? [])}`);
1392
+ }
1393
+ function translationDownloadUrls(documentId, targetLang) {
1394
+ return {
1395
+ translate_url: documentHref(documentId, { view: "translate", lang: targetLang }),
1396
+ ...pluginTranslationDownloadUrls(documentId, targetLang)
1397
+ };
1398
+ }
1399
+ function elementTranslationText(element) {
1400
+ if (typeof element.translation === "string" && element.translation.trim()) {
1401
+ return element.translation;
1402
+ }
1403
+ if (element.cell_translations && typeof element.cell_translations === "object") {
1404
+ return Object.values(element.cell_translations).join(" ");
1405
+ }
1406
+ return "";
1407
+ }
1408
+ function formatTranslationCiteMarkdown(pages, translateUrl, language2) {
1409
+ const blocks = pages.flatMap(
1410
+ (page) => page.elements.map((element) => ({
1411
+ id: `${page.page}-${element.index}`,
1412
+ page: page.page,
1413
+ type: element.element_type,
1414
+ content: element.text ?? "",
1415
+ translation: elementTranslationText(element)
1416
+ }))
1417
+ );
1418
+ return formatCiteMarkdown(blocks, translateUrl, language2);
1419
+ }
1420
+ function translationsFromArgs(raw) {
1421
+ if (!Array.isArray(raw) || raw.length === 0) {
1422
+ throw new PdfluxError("INVALID_INPUT", "translations must be a non-empty array");
1423
+ }
1424
+ const out = {};
1425
+ for (const item of raw) {
1426
+ if (typeof item !== "object" || item === null || Array.isArray(item)) {
1427
+ throw new PdfluxError("INVALID_INPUT", "each translation item must be an object");
1428
+ }
1429
+ const row = item;
1430
+ if (typeof row.key !== "string" || !row.key.trim()) {
1431
+ throw new PdfluxError("INVALID_INPUT", "translation.key is required");
1432
+ }
1433
+ if (typeof row.translation !== "string") {
1434
+ throw new PdfluxError("INVALID_INPUT", "translation.translation must be a string");
1435
+ }
1436
+ out[row.key.trim()] = row.translation;
1437
+ }
1438
+ return out;
1439
+ }
1440
+ function registerTools(ctx, deps) {
1441
+ const { config } = deps;
1442
+ const maxWaitSeconds = config.maxWaitSeconds.get();
1443
+ const lang = langOf(config);
1444
+ const l = (zh, en) => L(lang, zh, en);
1445
+ const sourceParam = {
1446
+ oneOf: [
1447
+ {
1448
+ type: "object",
1449
+ additionalProperties: false,
1450
+ properties: {
1451
+ path: { type: "string", required: true, description: l("\u4F1A\u8BDD\u5DE5\u4F5C\u533A\u5185\u7684\u6587\u4EF6\u8DEF\u5F84\uFF08\u76EE\u524D\u53EA\u652F\u6301 PDF\uFF09", "Workspace file path (PDF only)") }
1452
+ }
1453
+ },
1454
+ {
1455
+ type: "object",
1456
+ additionalProperties: false,
1457
+ properties: {
1458
+ attachment: {
1459
+ type: "object",
1460
+ additionalProperties: false,
1461
+ required: true,
1462
+ description: l("\u4F1A\u8BDD\u9644\u4EF6\u7684 durable \u5F15\u7528\uFF08FileAttachmentRef\uFF09", "Durable session attachment ref (FileAttachmentRef)"),
1463
+ properties: {
1464
+ attachmentId: { type: "string", required: true, description: l("\u9644\u4EF6 ID\uFF08sha256:...\uFF09", "Attachment ID (sha256:...)") },
1465
+ name: { type: "string", required: true, description: l("\u9644\u4EF6\u6587\u4EF6\u540D", "Attachment file name") },
1466
+ bytes: { type: "integer", required: true, description: l("\u9644\u4EF6\u5B57\u8282\u6570", "Attachment byte size") }
1467
+ }
1468
+ }
1469
+ }
1470
+ }
1471
+ ]
1472
+ };
1473
+ const createTool = defineTool({
1474
+ name: "pdflux_convert_create",
1475
+ description: l(
1476
+ "\u521B\u5EFA\u4E00\u4EFD PDF \u89E3\u6790\u5BFC\u51FA\u4EFB\u52A1\uFF08NanoDoc\uFF09\u3002\u8FD4\u56DE document_id \u4E0E\u521D\u59CB state\u3002\u4E0A\u4F20\u5C5E\u4E8E\u6570\u636E\u5916\u53D1\uFF0C\u53EF\u80FD\u89E6\u53D1\u5BA1\u6279\u3002",
1477
+ "Create a PDF parse/export job (NanoDoc). Returns document_id and initial state. Upload may require approval."
1478
+ ),
1479
+ parameters: {
1480
+ source: { ...sourceParam, required: true, description: l("\u5F85\u8F6C\u6362\u7684 PDF", "PDF to convert") },
1481
+ idempotency_key: { type: "string", description: l("\u53EF\u9009\u5E42\u7B49\u952E\uFF1B\u76F8\u540C\u952E\u8FD4\u56DE\u540C\u4E00 document_id", "Optional idempotency key; same key returns the same document_id") }
1482
+ },
1483
+ output: {
1484
+ schema: {
1485
+ type: "object",
1486
+ additionalProperties: false,
1487
+ properties: {
1488
+ document_id: { type: "string", required: true },
1489
+ state: { type: "string", required: true },
1490
+ deduped: { type: "boolean", required: true },
1491
+ filename: { type: "string", required: true },
1492
+ bytes: { type: "integer", required: true },
1493
+ parser: { type: "string", required: true }
1494
+ }
1495
+ },
1496
+ render(_args, value) {
1497
+ return text(l(
1498
+ `\u8F6C\u6362\u4EFB\u52A1\u5DF2\u521B\u5EFA\uFF1Adocument_id=${value.document_id}\uFF0Cstate=${value.state}${value.deduped ? "\uFF08\u590D\u7528\u5DF2\u6709\u4EFB\u52A1\uFF09" : ""}\u3002\u6587\u4EF6\uFF1A${value.filename}(${value.bytes}B)\uFF0Cparser=${value.parser}\u3002\u4E0B\u4E00\u6B65\u8BF7\u8C03\u7528 pdflux_convert_status \u7B49\u5F85\u7ED3\u679C\u3002`,
1499
+ `Convert job created: document_id=${value.document_id}, state=${value.state}${value.deduped ? " (reused)" : ""}. File: ${value.filename}(${value.bytes}B), parser=${value.parser}. Next: call pdflux_convert_status.`
1500
+ ));
1501
+ },
1502
+ presentationMeta(_args, value) {
1503
+ return {
1504
+ document_id: value.document_id,
1505
+ state: value.state,
1506
+ deduped: value.deduped,
1507
+ filename: value.filename,
1508
+ parser: value.parser
1509
+ };
1510
+ }
1511
+ },
1512
+ timeoutMs: 3e5,
1513
+ async execute(args, exec) {
1514
+ const signal = exec.signal;
1515
+ const cwd = exec.agent?.session.header.cwd;
1516
+ const maxBytes = config.maxFileMB.get() * 1024 * 1024;
1517
+ const parser = "nanodoc";
1518
+ const file = await loadSource(args.source, {
1519
+ fs: deps.fs,
1520
+ attachments: deps.attachments,
1521
+ maxBytes,
1522
+ signal,
1523
+ cwd
1524
+ });
1525
+ const baseUrl = resolveServiceBaseUrl(config.baseUrl.get());
1526
+ const key = contentKey(file.bytes, parser, baseUrl, args.idempotency_key);
1527
+ const previous = deps.registry.lookupIdem(key);
1528
+ if (previous) {
1529
+ try {
1530
+ const existing = await deps.client.getDocument(previous, signal);
1531
+ if (existing.status !== "failed") {
1532
+ return {
1533
+ document_id: previous,
1534
+ state: existing.status,
1535
+ deduped: true,
1536
+ filename: file.name,
1537
+ bytes: file.bytes.byteLength,
1538
+ parser
1539
+ };
1540
+ }
1541
+ logFailedDocument(deps, existing.id, existing.error);
1542
+ } catch (err) {
1543
+ if (!isPdfluxError(err) || err.code !== "DOCUMENT_NOT_FOUND") throw err;
1544
+ }
1545
+ }
1546
+ const apiKey = await deps.resolveApiKey();
1547
+ if (!apiKey) {
1548
+ const keyLang = langOf(config);
1549
+ const keyRef = keyLang === "zh" ? config.nanodocApiKeyRefZh.get() : config.nanodocApiKeyRefEn.get();
1550
+ throw new PdfluxError(
1551
+ "NANODOC_KEY_MISSING",
1552
+ l(
1553
+ `NanoDoc API key \u672A\u914D\u7F6E\uFF08\u51ED\u636E\u5F15\u7528\uFF1A${keyRef}\uFF09\u3002\u8BF7\u5728 Plugins \u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u914D\u7F6E\u5BF9\u5E94\u73AF\u5883\u7684 NanoDoc API Key \u540E\u91CD\u8BD5\u3002`,
1554
+ `NanoDoc API key is not configured (ref: ${keyRef}). Set the key for the current environment in Plugins settings and retry.`
1555
+ )
1556
+ );
1557
+ }
1558
+ const item = await deps.client.createDocument(file, apiKey, signal);
1559
+ await deps.registry.register({
1560
+ document_id: item.id,
1561
+ filename: file.name,
1562
+ parser,
1563
+ created_at: Date.now(),
1564
+ content_key: key,
1565
+ backend_origin: baseUrl
1566
+ });
1567
+ return {
1568
+ document_id: item.id,
1569
+ state: item.status,
1570
+ deduped: false,
1571
+ filename: file.name,
1572
+ bytes: file.bytes.byteLength,
1573
+ parser
1574
+ };
1575
+ }
1576
+ });
1577
+ const statusTool = defineTool({
1578
+ name: "pdflux_convert_status",
1579
+ description: l(
1580
+ "\u67E5\u8BE2\u8F6C\u6362\u4EFB\u52A1\u72B6\u6001\uFF1Bwait_seconds \u5185\u5728 Host \u5185\u8F6E\u8BE2\u76F4\u5230\u7EC8\u6001\u6216\u8D85\u65F6\u3002next_action \u6307\u793A\u4E0B\u4E00\u6B65\uFF08wait/export/report_failure\uFF09\u3002",
1581
+ "Query convert status; poll inside the Host until terminal or timeout within wait_seconds. next_action is wait/export/report_failure."
1582
+ ),
1583
+ parameters: {
1584
+ document_id: { type: "string", required: true, description: l("\u6587\u6863\u4EFB\u52A1 ID", "Document job ID") },
1585
+ wait_seconds: { type: "integer", description: l(`\u672C\u6B21\u6700\u957F\u7B49\u5F85\u79D2\u6570\uFF0C\u4E0D\u8D85\u8FC7 ${maxWaitSeconds}`, `Max wait seconds for this call, \u2264 ${maxWaitSeconds}`) }
1586
+ },
1587
+ output: {
1588
+ schema: {
1589
+ type: "object",
1590
+ additionalProperties: false,
1591
+ properties: {
1592
+ document_id: { type: "string", required: true },
1593
+ state: { type: "string", required: true },
1594
+ message: { type: "string" },
1595
+ next_action: { type: "string", required: true, enum: ["wait", "export", "report_failure"] }
1596
+ }
1597
+ },
1598
+ render(_args, value) {
1599
+ if (value.state === "failed") return text(l(`\u8F6C\u6362\u5931\u8D25\uFF08document_id=${value.document_id}\uFF09\u3002\u8BF7\u91CD\u8BD5\u6216\u6362\u7528\u53EF\u89E3\u6790\u7684\u6587\u4EF6\u3002`, `Convert failed (document_id=${value.document_id}). Retry or use a parseable file.`));
1600
+ if (value.state === "succeeded") return text(l(`\u8F6C\u6362\u5B8C\u6210\uFF08document_id=${value.document_id}\uFF09\u3002\u53EF\u8C03\u7528 pdflux_convert_export \u83B7\u53D6\u4E0B\u8F7D\u94FE\u63A5\u3002`, `Convert completed (document_id=${value.document_id}). Call pdflux_convert_export for downloads.`));
1601
+ return text(l(`\u8F6C\u6362\u8FDB\u884C\u4E2D\uFF08state=${value.state}\uFF09\u3002\u8BF7\u7A0D\u540E\u518D\u6B21\u8C03\u7528 pdflux_convert_status\u3002`, `Convert in progress (state=${value.state}). Call pdflux_convert_status again shortly.`));
1602
+ },
1603
+ presentationMeta(_args, value) {
1604
+ return { document_id: value.document_id, state: value.state, next_action: value.next_action };
1605
+ }
1606
+ },
1607
+ timeoutMs: maxWaitSeconds * 1e3 + 15e3,
1608
+ isConcurrencySafe: () => true,
1609
+ async execute(args, exec) {
1610
+ assertRegistered(deps, args.document_id);
1611
+ const waitCap = config.maxWaitSeconds.get();
1612
+ const waitSeconds = args.wait_seconds ?? 0;
1613
+ if (waitSeconds < 0 || waitSeconds > waitCap) {
1614
+ throw new PdfluxError("INVALID_INPUT", l(`wait_seconds \u5FC5\u987B\u5728 0 \u5230 ${waitCap} \u4E4B\u95F4`, `wait_seconds must be between 0 and ${waitCap}`));
1615
+ }
1616
+ let item;
1617
+ if (waitSeconds > 0) {
1618
+ item = await deps.client.waitForTerminal(args.document_id, {
1619
+ pollIntervalMs: config.pollIntervalMs.get(),
1620
+ timeoutMs: waitSeconds * 1e3,
1621
+ signal: exec.signal
1622
+ });
1623
+ } else {
1624
+ item = await deps.client.getDocument(args.document_id, exec.signal);
1625
+ }
1626
+ if (item.status === "failed") logFailedDocument(deps, item.id, item.error);
1627
+ const out = {
1628
+ document_id: item.id,
1629
+ state: item.status,
1630
+ next_action: nextActionOf(item.status)
1631
+ };
1632
+ if (item.status !== "failed" && item.message) out.message = item.message;
1633
+ return out;
1634
+ }
1635
+ });
1636
+ const exportTool = defineTool({
1637
+ name: "pdflux_convert_export",
1638
+ description: l(
1639
+ "\u83B7\u53D6\u8F6C\u6362\u7ED3\u679C\u9884\u89C8\u94FE\u63A5\uFF0C\u4EE5\u53CA Markdown / HTML / DOCX / Excel \u4E0B\u8F7D\u5730\u5740\uFF1B\u53EF\u9009\u8FD4\u56DE\u5E26\u5B8C\u6574\u5F15\u7528\u89D2\u6807\u7684 Markdown \u6B63\u6587\u3002",
1640
+ "Get preview link and Markdown/HTML/DOCX/Excel downloads; optionally include Markdown body with citation markers."
1641
+ ),
1642
+ parameters: {
1643
+ document_id: { type: "string", required: true, description: l("\u6587\u6863\u4EFB\u52A1 ID", "Document job ID") },
1644
+ include_markdown: {
1645
+ type: "boolean",
1646
+ description: l("\u662F\u5426\u5728\u7ED3\u679C\u4E2D\u9644\u5E26 Markdown \u6B63\u6587\uFF0C\u9ED8\u8BA4 true", "Include Markdown body in the result (default true)")
1647
+ }
1648
+ },
1649
+ output: {
1650
+ schema: {
1651
+ type: "object",
1652
+ additionalProperties: false,
1653
+ properties: {
1654
+ document_id: { type: "string", required: true },
1655
+ preview_url: { type: "string", required: true },
1656
+ markdown_url: { type: "string", required: true },
1657
+ html_url: { type: "string", required: true },
1658
+ docx_url: { type: "string", required: true },
1659
+ excel_url: { type: "string", required: true },
1660
+ markdown: { type: "string" },
1661
+ expires_at: { type: "integer" },
1662
+ retention_hours: { type: "integer" }
1663
+ }
1664
+ },
1665
+ render(_args, value) {
1666
+ const lines = [
1667
+ value.markdown ? value.markdown : l("\u6587\u6863\u5DF2\u8F6C\u6362\u5B8C\u6210\uFF0C\u53EF\u901A\u8FC7\u4E0B\u65B9\u6309\u94AE\u4E0B\u8F7D\u5404\u683C\u5F0F\u6587\u4EF6\u3002", "Document converted; download formats via the buttons below."),
1668
+ "",
1669
+ value.markdown ? l(
1670
+ "\u6BCF\u6BB5\u6807\u9898\u5728 block=\u2026 \u540E\u9762\u5DF2\u5E26\u5B8C\u6574\u5F15\u7528\u89D2\u6807\uFF08[![[\u5E8F\u53F7]](about:blank)](\u2026?block=\u2026)\uFF09\u3002\u56DE\u7B54\u6587\u6863\u5185\u5BB9\u65F6\uFF0C\u628A\u8BE5\u89D2\u6807\u539F\u6837\u590D\u5236\u5230\u5F15\u7528\u5185\u5BB9\u540E\u9762\uFF1B\u4E0D\u8981\u6539\u5199\u94FE\u63A5\uFF0C\u4E5F\u4E0D\u8981\u81EA\u5DF1\u62FC query\u3002",
1671
+ "Each heading already includes a full citation marker after block=\u2026. When citing content, copy that marker verbatim; do not rewrite links or invent query strings."
1672
+ ) : "",
1673
+ l(`\u6700\u7EC8\u56DE\u590D\u672B\u5C3E\u8BF7\u9644\u4E0A\uFF1A[\u67E5\u770B\u6587\u6863\u9884\u89C8](${value.preview_url})`, `End the final reply with: [View document preview](${value.preview_url})`),
1674
+ l("\u4E0D\u8981\u628A markdown_url / html_url / docx_url / excel_url \u5199\u8FDB\u56DE\u590D\uFF1B\u4E0B\u8F7D\u6309\u94AE\u4F1A\u81EA\u52A8\u663E\u793A\u5728\u6700\u7EC8\u56DE\u590D\u4E0B\u65B9\u3002", "Do not paste download URLs into the reply; download buttons appear under the final reply.")
1675
+ ].filter((line) => line !== "");
1676
+ return text(lines.join("\n"));
1677
+ },
1678
+ presentationMeta(_args, value) {
1679
+ return {
1680
+ document_id: value.document_id,
1681
+ chars: value.markdown?.length ?? 0,
1682
+ markdown_url: value.markdown_url,
1683
+ html_url: value.html_url,
1684
+ docx_url: value.docx_url,
1685
+ excel_url: value.excel_url,
1686
+ ...typeof value.expires_at === "number" ? { expires_at: value.expires_at } : {},
1687
+ ...typeof value.retention_hours === "number" ? { retention_hours: value.retention_hours } : {}
1688
+ };
1689
+ }
1690
+ },
1691
+ timeoutMs: 12e4,
1692
+ isConcurrencySafe: () => true,
1693
+ async execute(args, exec) {
1694
+ assertRegistered(deps, args.document_id);
1695
+ const item = await deps.client.getDocument(args.document_id, exec.signal);
1696
+ if (!isTerminalState(item.status)) {
1697
+ throw new PdfluxError("DOCUMENT_NOT_READY", `document is still ${item.status}`);
1698
+ }
1699
+ if (item.status === "failed") {
1700
+ logFailedDocument(deps, item.id, item.error);
1701
+ throw new PdfluxError("DOCUMENT_FAILED", "document failed; create a new convert instead");
1702
+ }
1703
+ const includeMarkdown = args.include_markdown !== false;
1704
+ const previewUrl = documentAddress(args.document_id);
1705
+ let markdown;
1706
+ if (includeMarkdown) {
1707
+ const blocks = await deps.client.getMarkdownBlocks(args.document_id, exec.signal);
1708
+ markdown = formatCiteMarkdown(
1709
+ blocks.map((block) => ({
1710
+ id: block.id,
1711
+ page: block.page,
1712
+ type: block.type,
1713
+ content: block.content
1714
+ })),
1715
+ previewUrl,
1716
+ lang
1717
+ );
1718
+ }
1719
+ const downloads = pluginDocumentDownloadUrls(args.document_id);
1720
+ const out = {
1721
+ document_id: args.document_id,
1722
+ preview_url: previewUrl,
1723
+ ...downloads
1724
+ };
1725
+ if (typeof item.expires_at === "number") out.expires_at = item.expires_at;
1726
+ if (typeof item.retention_hours === "number") out.retention_hours = item.retention_hours;
1727
+ if (markdown !== void 0) out.markdown = markdown;
1728
+ return out;
1729
+ }
1730
+ });
1731
+ const translateBlocksTool = defineTool({
1732
+ name: "pdflux_translate_blocks",
1733
+ description: l(
1734
+ `\u89E3\u6790\u5B8C\u6210\u540E\u62C9\u53D6\u5F85\u7FFB\u8BD1\u5143\u7D20\u5757\uFF08\u6BCF\u6279\u6700\u591A ${TRANSLATE_BATCH_SIZE} \u6761\uFF0C\u5E76\u544A\u77E5\u5F85\u8BD1\u603B\u6570\uFF09\u3002\u82E5\u8BE5\u8BED\u79CD\u5DF2\u6709\u672A\u5B8C\u6210\u56DE\u586B\uFF0C\u4ECE missing \u4E2D\u53D6\u672C\u6279\u3002\u53EA\u7FFB\u8BD1\u672C\u6279\u540E\u7ACB\u5373\u8C03\u7528 pdflux_translate_submit\u3002`,
1735
+ `After parsing, fetch blocks to translate (\u2264${TRANSLATE_BATCH_SIZE} per batch, with total_count). Resume from missing when a job is incomplete. Translate this batch then call pdflux_translate_submit immediately.`
1736
+ ),
1737
+ parameters: {
1738
+ document_id: { type: "string", required: true, description: l("\u6587\u6863\u4EFB\u52A1 ID", "Document job ID") },
1739
+ target_lang: {
1740
+ type: "string",
1741
+ required: true,
1742
+ description: l("\u76EE\u6807\u8BED\u8A00\uFF0C\u5982 en / zh", "Target language, e.g. en / zh")
1743
+ }
1744
+ },
1745
+ output: {
1746
+ schema: {
1747
+ type: "object",
1748
+ additionalProperties: false,
1749
+ properties: {
1750
+ document_id: { type: "string", required: true },
1751
+ target_lang: { type: "string", required: true },
1752
+ complete: { type: "boolean", required: true },
1753
+ total_count: { type: "integer", required: true },
1754
+ block_count: { type: "integer", required: true },
1755
+ blocks: { type: "array", required: true },
1756
+ markdown: { type: "string" },
1757
+ translate_url: { type: "string" },
1758
+ markdown_url: { type: "string" },
1759
+ html_url: { type: "string" },
1760
+ docx_url: { type: "string" },
1761
+ excel_url: { type: "string" },
1762
+ next_action: {
1763
+ type: "string",
1764
+ required: true,
1765
+ enum: ["translate", "wait", "done"]
1766
+ }
1767
+ }
1768
+ },
1769
+ render(_args, value) {
1770
+ if (value.complete) {
1771
+ if (value.translate_url) {
1772
+ const lines = [
1773
+ value.markdown ? value.markdown : l(`\u7FFB\u8BD1\u5DF2\u5B8C\u6210\uFF08document_id=${value.document_id}\uFF0Clang=${value.target_lang}\uFF09\u3002`, `Translation completed (document_id=${value.document_id}, lang=${value.target_lang}).`),
1774
+ "",
1775
+ value.markdown ? l("\u6BCF\u6BB5\u6807\u9898\u5728 block=\u2026 \u540E\u9762\u5DF2\u5E26\u5B8C\u6574\u5F15\u7528\u89D2\u6807\u3002\u56DE\u7B54\u8BD1\u6587\u5185\u5BB9\u65F6\uFF0C\u628A\u8BE5\u89D2\u6807\u539F\u6837\u590D\u5236\u5230\u5F15\u7528\u5185\u5BB9\u540E\u9762\uFF1B\u4E0D\u8981\u6539\u5199\u94FE\u63A5\uFF0C\u4E5F\u4E0D\u8981\u81EA\u5DF1\u62FC query\u3002", "Each heading already includes a full citation marker. When citing translations, copy that marker verbatim.") : "",
1776
+ l(`\u6700\u7EC8\u56DE\u590D\u672B\u5C3E\u9644\u4E0A\uFF1A[\u67E5\u770B\u7FFB\u8BD1\u7ED3\u679C](${value.translate_url})\u3002`, `End with: [View translation](${value.translate_url}).`),
1777
+ l("\u4E0D\u8981\u628A markdown_url / html_url / docx_url / excel_url \u5199\u8FDB\u56DE\u590D\uFF1B\u8BD1\u540E\u4E0B\u8F7D\u6309\u94AE\u4F1A\u81EA\u52A8\u663E\u793A\u3002", "Do not paste download URLs into the reply; translated download buttons appear automatically.")
1778
+ ].filter((line) => line !== "");
1779
+ return text(lines.join("\n"));
1780
+ }
1781
+ return text(l(
1782
+ `\u6587\u6863\u6CA1\u6709\u9700\u8981\u7FFB\u8BD1\u7684\u6B63\u6587\uFF08document_id=${value.document_id}\uFF0Clang=${value.target_lang}\uFF09\u3002`,
1783
+ `No body text needs translation (document_id=${value.document_id}, lang=${value.target_lang}).`
1784
+ ));
1785
+ }
1786
+ if (value.next_action === "wait") {
1787
+ return text(l(
1788
+ `\u8BD1\u6587\u5DF2\u9F50\uFF0C\u6B63\u5728\u751F\u6210\u8BD1\u540E\u6587\u4EF6\uFF08document_id=${value.document_id}\uFF0Clang=${value.target_lang}\uFF09\u3002\u8BF7\u7A0D\u540E\u518D\u6B21\u8C03\u7528 pdflux_translate_blocks \u7B49\u5F85\u5B8C\u6210\u3002`,
1789
+ `Translations are ready; rendering output files (document_id=${value.document_id}, lang=${value.target_lang}). Call pdflux_translate_blocks again shortly.`
1790
+ ));
1791
+ }
1792
+ return renderTranslatePayload(
1793
+ l(
1794
+ `\u5F85\u8BD1\u5171 ${value.total_count} \u6761\uFF1B\u672C\u6279 ${value.block_count} \u6761\uFF08\u6BCF\u6279\u6700\u591A ${TRANSLATE_BATCH_SIZE} \u6761\uFF09\uFF08document_id=${value.document_id}\uFF0Clang=${value.target_lang}\uFF09\u3002\u8BF7\u53EA\u7FFB\u8BD1\u4E0B\u65B9\u672C\u6279 blocks \u7684 text\uFF0C\u4FDD\u7559 key\uFF0C\u7ACB\u5373\u8C03\u7528 pdflux_translate_submit\uFF1B\u4E0D\u8981\u5F00 subagent\uFF0C\u4E0D\u8981\u5199\u6587\u4EF6\u5207\u5757\u3002`,
1795
+ `${value.total_count} blocks total; this batch ${value.block_count} (\u2264${TRANSLATE_BATCH_SIZE}) (document_id=${value.document_id}, lang=${value.target_lang}). Translate only this batch\u2019s text, keep keys, then call pdflux_translate_submit immediately.`
1796
+ ),
1797
+ "blocks",
1798
+ value.blocks
1799
+ );
1800
+ },
1801
+ presentationMeta(_args, value) {
1802
+ return {
1803
+ document_id: value.document_id,
1804
+ target_lang: value.target_lang,
1805
+ complete: value.complete,
1806
+ total_count: value.total_count,
1807
+ block_count: value.block_count,
1808
+ next_action: value.next_action,
1809
+ markdown_url: value.complete ? value.markdown_url ?? "" : "",
1810
+ html_url: value.complete ? value.html_url ?? "" : "",
1811
+ docx_url: value.complete ? value.docx_url ?? "" : "",
1812
+ excel_url: value.complete ? value.excel_url ?? "" : ""
1813
+ };
1814
+ }
1815
+ },
1816
+ timeoutMs: 6e4,
1817
+ isConcurrencySafe: () => true,
1818
+ async execute(args, exec) {
1819
+ assertRegistered(deps, args.document_id);
1820
+ const targetLang = parseTargetLang(args.target_lang);
1821
+ const item = await deps.client.getDocument(args.document_id, exec.signal);
1822
+ ensureParsed(item);
1823
+ const existing = await deps.client.getTranslationJob(args.document_id, targetLang, exec.signal);
1824
+ if (existing?.complete) {
1825
+ const downloads = translationDownloadUrls(args.document_id, targetLang);
1826
+ return {
1827
+ document_id: args.document_id,
1828
+ target_lang: targetLang,
1829
+ complete: true,
1830
+ total_count: 0,
1831
+ block_count: 0,
1832
+ blocks: [],
1833
+ markdown: formatTranslationCiteMarkdown(existing.pages, downloads.translate_url, lang),
1834
+ ...downloads,
1835
+ next_action: "done"
1836
+ };
1837
+ }
1838
+ if (existing && !existing.complete && (existing.missing?.length ?? 0) === 0) {
1839
+ return {
1840
+ document_id: args.document_id,
1841
+ target_lang: targetLang,
1842
+ complete: false,
1843
+ total_count: 0,
1844
+ block_count: 0,
1845
+ blocks: [],
1846
+ next_action: "wait"
1847
+ };
1848
+ }
1849
+ const blocks = existing && !existing.complete && (existing.missing?.length ?? 0) > 0 ? existing.missing ?? [] : (await deps.client.getTranslationLayout(args.document_id, exec.signal)).blocks;
1850
+ if (blocks.length === 0) {
1851
+ return {
1852
+ document_id: args.document_id,
1853
+ target_lang: targetLang,
1854
+ complete: true,
1855
+ total_count: 0,
1856
+ block_count: 0,
1857
+ blocks: [],
1858
+ next_action: "done"
1859
+ };
1860
+ }
1861
+ const { total_count, batch } = takeTranslateBatch(slimBlocks(blocks));
1862
+ return {
1863
+ document_id: args.document_id,
1864
+ target_lang: targetLang,
1865
+ complete: false,
1866
+ total_count,
1867
+ block_count: batch.length,
1868
+ blocks: batch,
1869
+ next_action: "translate"
1870
+ };
1871
+ }
1872
+ });
1873
+ const translateSubmitTool = defineTool({
1874
+ name: "pdflux_translate_submit",
1875
+ description: l(
1876
+ `\u628A\u672C\u6279\u7FFB\u8BD1\u7ED3\u679C\u56DE\u4F20\u7ED9 pdflux \u670D\u52A1\u3002\u82E5\u672A\u5B8C\u6210\uFF0Cmissing \u6700\u591A\u8FD4\u56DE ${TRANSLATE_BATCH_SIZE} \u6761\u5E76\u544A\u77E5\u5269\u4F59\u603B\u6570\uFF1B\u53EA\u8BD1\u672C\u6279\u540E\u518D\u6B21 submit\uFF0C\u76F4\u5230 complete=true\u3002`,
1877
+ `Submit this batch of translations. If incomplete, missing returns \u2264${TRANSLATE_BATCH_SIZE} items with remaining count; translate only that batch and submit again until complete=true.`
1878
+ ),
1879
+ parameters: {
1880
+ document_id: { type: "string", required: true, description: l("\u6587\u6863\u4EFB\u52A1 ID", "Document job ID") },
1881
+ target_lang: {
1882
+ type: "string",
1883
+ required: true,
1884
+ description: l("\u76EE\u6807\u8BED\u8A00\uFF0C\u5982 en / zh", "Target language, e.g. en / zh")
1885
+ },
1886
+ translations: {
1887
+ type: "array",
1888
+ required: true,
1889
+ description: l(
1890
+ `\u672C\u6279\u7FFB\u8BD1\u6761\u76EE\uFF08\u5EFA\u8BAE\u4E0D\u8D85\u8FC7 ${TRANSLATE_BATCH_SIZE} \u6761\uFF09\uFF1B\u6BCF\u9879\u542B key\uFF08\u4E0E blocks.key \u4E00\u81F4\uFF09\u548C translation`,
1891
+ `This batch of translations (prefer \u2264${TRANSLATE_BATCH_SIZE}); each item has key (same as blocks.key) and translation`
1892
+ ),
1893
+ items: {
1894
+ type: "object",
1895
+ additionalProperties: false,
1896
+ properties: {
1897
+ key: { type: "string", required: true, description: l("\u5757 key\uFF0C\u5982 e12 \u6216 e12c0-1", "Block key, e.g. e12 or e12c0-1") },
1898
+ translation: { type: "string", required: true, description: l("\u8BD1\u6587", "Translated text") }
1899
+ }
1900
+ }
1901
+ }
1902
+ },
1903
+ output: {
1904
+ schema: {
1905
+ type: "object",
1906
+ additionalProperties: false,
1907
+ properties: {
1908
+ document_id: { type: "string", required: true },
1909
+ target_lang: { type: "string", required: true },
1910
+ complete: { type: "boolean", required: true },
1911
+ status: { type: "string", required: true },
1912
+ missing_count: { type: "integer", required: true },
1913
+ batch_count: { type: "integer", required: true },
1914
+ missing: { type: "array", required: true },
1915
+ markdown: { type: "string" },
1916
+ translate_url: { type: "string" },
1917
+ markdown_url: { type: "string" },
1918
+ html_url: { type: "string" },
1919
+ docx_url: { type: "string" },
1920
+ excel_url: { type: "string" },
1921
+ expires_at: { type: "integer" },
1922
+ retention_hours: { type: "integer" },
1923
+ next_action: {
1924
+ type: "string",
1925
+ required: true,
1926
+ enum: ["translate_more", "wait", "done"]
1927
+ }
1928
+ }
1929
+ },
1930
+ render(_args, value) {
1931
+ if (value.complete) {
1932
+ const lines = [
1933
+ value.markdown ? value.markdown : l(`\u7FFB\u8BD1\u5DF2\u5168\u90E8\u5B8C\u6210\uFF08document_id=${value.document_id}\uFF0Clang=${value.target_lang}\uFF09\u3002`, `All translations completed (document_id=${value.document_id}, lang=${value.target_lang}).`),
1934
+ "",
1935
+ value.markdown ? l("\u6BCF\u6BB5\u6807\u9898\u5728 block=\u2026 \u540E\u9762\u5DF2\u5E26\u5B8C\u6574\u5F15\u7528\u89D2\u6807\u3002\u56DE\u7B54\u8BD1\u6587\u5185\u5BB9\u65F6\uFF0C\u628A\u8BE5\u89D2\u6807\u539F\u6837\u590D\u5236\u5230\u5F15\u7528\u5185\u5BB9\u540E\u9762\uFF1B\u4E0D\u8981\u6539\u5199\u94FE\u63A5\uFF0C\u4E5F\u4E0D\u8981\u81EA\u5DF1\u62FC query\u3002", "Each heading already includes a full citation marker. When citing translations, copy that marker verbatim.") : "",
1936
+ l(`\u6700\u7EC8\u56DE\u590D\u672B\u5C3E\u9644\u4E0A\uFF1A[\u67E5\u770B\u7FFB\u8BD1\u7ED3\u679C](${value.translate_url})\u3002`, `End with: [View translation](${value.translate_url}).`),
1937
+ l("\u4E0D\u8981\u628A markdown_url / html_url / docx_url / excel_url \u5199\u8FDB\u56DE\u590D\uFF1B\u8BD1\u540E\u4E0B\u8F7D\u6309\u94AE\u4F1A\u81EA\u52A8\u663E\u793A\u3002", "Do not paste download URLs into the reply; translated download buttons appear automatically.")
1938
+ ].filter((line) => line !== "");
1939
+ return text(lines.join("\n"));
1940
+ }
1941
+ if (value.next_action === "wait") {
1942
+ return text(l(
1943
+ `\u8BD1\u6587\u5DF2\u9F50\uFF0C\u6B63\u5728\u751F\u6210\u8BD1\u540E\u6587\u4EF6\uFF08document_id=${value.document_id}\uFF0Clang=${value.target_lang}\uFF09\u3002\u8BF7\u7A0D\u540E\u8C03\u7528 pdflux_translate_blocks \u7B49\u5F85\u5B8C\u6210\u3002`,
1944
+ `Translations are ready; rendering output files (document_id=${value.document_id}, lang=${value.target_lang}). Call pdflux_translate_blocks again shortly.`
1945
+ ));
1946
+ }
1947
+ return renderTranslatePayload(
1948
+ l(
1949
+ `\u8FD8\u6709 ${value.missing_count} \u6761\u672A\u8BD1\u5B8C\uFF1B\u672C\u6279 ${value.batch_count} \u6761\uFF08\u6BCF\u6279\u6700\u591A ${TRANSLATE_BATCH_SIZE} \u6761\uFF09\u3002\u8BF7\u53EA\u7FFB\u8BD1\u4E0B\u65B9\u672C\u6279 missing \u7684 text\uFF0C\u4FDD\u7559 key\uFF0C\u7ACB\u5373\u518D\u6B21\u8C03\u7528 pdflux_translate_submit\uFF1B\u4E0D\u8981\u5F00 subagent\uFF0C\u4E0D\u8981\u5199\u6587\u4EF6\u5207\u5757\u3002`,
1950
+ `${value.missing_count} remaining; this batch ${value.batch_count} (\u2264${TRANSLATE_BATCH_SIZE}). Translate only this missing batch\u2019s text, keep keys, then call pdflux_translate_submit again.`
1951
+ ),
1952
+ "missing",
1953
+ value.missing
1954
+ );
1955
+ },
1956
+ presentationMeta(_args, value) {
1957
+ return {
1958
+ document_id: value.document_id,
1959
+ target_lang: value.target_lang,
1960
+ complete: value.complete,
1961
+ missing_count: value.missing_count,
1962
+ batch_count: value.batch_count,
1963
+ next_action: value.next_action,
1964
+ markdown_url: value.complete ? value.markdown_url ?? "" : "",
1965
+ html_url: value.complete ? value.html_url ?? "" : "",
1966
+ docx_url: value.complete ? value.docx_url ?? "" : "",
1967
+ excel_url: value.complete ? value.excel_url ?? "" : "",
1968
+ ...value.complete && typeof value.expires_at === "number" ? { expires_at: value.expires_at } : {},
1969
+ ...value.complete && typeof value.retention_hours === "number" ? { retention_hours: value.retention_hours } : {}
1970
+ };
1971
+ }
1972
+ },
1973
+ timeoutMs: 12e4,
1974
+ isConcurrencySafe: () => true,
1975
+ async execute(args, exec) {
1976
+ assertRegistered(deps, args.document_id);
1977
+ const targetLang = parseTargetLang(args.target_lang);
1978
+ const item = await deps.client.getDocument(args.document_id, exec.signal);
1979
+ ensureParsed(item);
1980
+ const translations = translationsFromArgs(args.translations);
1981
+ const result = await deps.client.importTranslation(
1982
+ args.document_id,
1983
+ targetLang,
1984
+ translations,
1985
+ exec.signal
1986
+ );
1987
+ if (result.complete) {
1988
+ const downloads = translationDownloadUrls(args.document_id, targetLang);
1989
+ const job = await deps.client.getTranslationJob(args.document_id, targetLang, exec.signal);
1990
+ return {
1991
+ document_id: args.document_id,
1992
+ target_lang: targetLang,
1993
+ complete: true,
1994
+ status: result.status,
1995
+ missing_count: 0,
1996
+ batch_count: 0,
1997
+ missing: [],
1998
+ markdown: job ? formatTranslationCiteMarkdown(job.pages, downloads.translate_url, lang) : void 0,
1999
+ ...downloads,
2000
+ expires_at: typeof item.expires_at === "number" ? item.expires_at : void 0,
2001
+ retention_hours: typeof item.retention_hours === "number" ? item.retention_hours : void 0,
2002
+ next_action: "done"
2003
+ };
2004
+ }
2005
+ if ((result.missing?.length ?? 0) === 0) {
2006
+ return {
2007
+ document_id: args.document_id,
2008
+ target_lang: targetLang,
2009
+ complete: false,
2010
+ status: result.status,
2011
+ missing_count: 0,
2012
+ batch_count: 0,
2013
+ missing: [],
2014
+ next_action: "wait"
2015
+ };
2016
+ }
2017
+ const { total_count, batch } = takeTranslateBatch(slimBlocks(result.missing));
2018
+ return {
2019
+ document_id: args.document_id,
2020
+ target_lang: targetLang,
2021
+ complete: false,
2022
+ status: result.status,
2023
+ missing_count: total_count,
2024
+ batch_count: batch.length,
2025
+ missing: batch,
2026
+ next_action: "translate_more"
2027
+ };
2028
+ }
2029
+ });
2030
+ ctx.tools.register(createTool);
2031
+ ctx.tools.register(statusTool);
2032
+ ctx.tools.register(exportTool);
2033
+ ctx.tools.register(translateBlocksTool);
2034
+ ctx.tools.register(translateSubmitTool);
2035
+ }
2036
+
2037
+ // src/skill.ts
2038
+ var SKILL_NAME = "pdflux-convert";
2039
+ var TRANSLATE_SKILL_NAME = "pdflux-translate";
2040
+ var CONVERT_ZH = {
2041
+ description: "\u628A PDF \u89E3\u6790\u5E76\u5BFC\u51FA\u4E3A Markdown\u3001HTML\u3001DOCX\u3001Excel\uFF0C\u5E76\u63D0\u4F9B\u4E0B\u8F7D\u94FE\u63A5\uFF08\u7FFB\u8BD1\u89C1 pdflux-translate\uFF09",
2042
+ markdown: `# pdflux-convert
2043
+
2044
+ ## \u4F55\u65F6\u4F7F\u7528
2045
+ - \u7528\u6237\u8981\u6C42\u628A PDF \u8F6C\u6210 Markdown / HTML / Word(DOCX) / Excel\uFF0C\u6216\u9700\u8981\u4E0B\u8F7D\u89E3\u6790\u540E\u7684\u7ED3\u679C\u6587\u4EF6\u3002
2046
+ - \u7528\u6237\u8BF4\u300C\u5BFC\u51FA\u300D\u300C\u8F6C\u6362\u300D\u300C\u4E0B\u8F7D md/html/docx/xlsx\u300D\u7B49\u3002
2047
+ - \u7528\u6237\u8BE2\u95EE\u5DF2\u8F6C\u6362\u6587\u6863\u7684\u6B63\u6587\u5185\u5BB9\u3001\u67D0\u6BB5\u6587\u5B57\u3001\u67D0\u4E2A\u6570\u636E\u6216\u51FA\u5904\u3002
2048
+ - \u82E5\u7528\u6237\u540C\u65F6\u8981\u6C42\u7FFB\u8BD1\uFF0C\u5148\u5B8C\u6210\u672C\u6D41\u7A0B\uFF0C\u518D\u6309 \`pdflux-translate\` skill \u7EE7\u7EED\u3002
2049
+
2050
+ ## \u6D41\u7A0B
2051
+ 1. \u7528 pdflux_convert_create \u521B\u5EFA\u4EFB\u52A1\u3002\u5DE5\u4F5C\u533A\u672C\u5730\u6587\u4EF6\u7528 \`path\`\uFF0C\u4F1A\u8BDD\u9644\u4EF6\u7528 \`attachment\`\uFF08\u542B attachmentId/name/bytes\uFF09\u3002\u76EE\u524D\u53EA\u652F\u6301 PDF\uFF0C\u8D70 NanoDoc \u89E3\u6790\u3002
2052
+ 2. \u7528 pdflux_convert_status \u7B49\u5F85\uFF1B\u8FD4\u56DE next_action \u4E3A \`wait\` \u65F6\u518D\u6B21\u8C03\u7528\uFF08wait_seconds \u4E0D\u8D85\u8FC7 60\uFF09\uFF0C\u6700\u591A 10 \u6B21\u540E\u5411\u7528\u6237\u8BF4\u660E\u4ECD\u5728\u5904\u7406\u3002next_action \u4E3A \`report_failure\` \u65F6\u544A\u77E5\u7528\u6237\u89E3\u6790\u5931\u8D25\uFF0C\u5EFA\u8BAE\u91CD\u8BD5\u6216\u6362\u7528\u53EF\u89E3\u6790\u7684\u6587\u4EF6\u3002
2053
+ 3. \u7528 pdflux_convert_export \u83B7\u53D6\u9884\u89C8\u94FE\u63A5\u4E0E\u5404\u683C\u5F0F\u4E0B\u8F7D\u5730\u5740\u3002\u56DE\u7B54\u6587\u6863\u5185\u5BB9\u65F6\u5FC5\u987B\u8BFB\u53D6\u8FD4\u56DE\u7684 Markdown\uFF1A\u6BCF\u6BB5\u6807\u9898\u5F62\u5982 \`### block=<id> [![[\u5E8F\u53F7]](about:blank)](<preview_url>?block=<id>)\uFF08\u7B2C N \u9875 \xB7 type\uFF09\`\uFF0C\u6807\u9898\u91CC\u5DF2\u7ECF\u5E26\u597D\u5B8C\u6574\u5F15\u7528\u89D2\u6807\u3002
2054
+ 4. \u56DE\u590D\u4E2D\u5F15\u7528\u7684\u6BCF\u4E2A\u6570\u636E\u540E\uFF0C\u628A\u8BE5\u6BB5\u6807\u9898\u91CC\u7684\u5F15\u7528\u89D2\u6807\u539F\u6837\u590D\u5236\u8FC7\u53BB\uFF0C\u4F8B\u5982 \`\u8425\u4E1A\u6536\u5165[![[1]](about:blank)](<preview_url>?block=1-0)\`\u3002\u4E0D\u8981\u6539\u5199\u94FE\u63A5\uFF0C\u4E0D\u8981\u81EA\u5DF1\u62FC \`?block=\`\uFF0C\u4E0D\u8981\u53E6\u8D77\u5E8F\u53F7\u3002\u7528\u6237\u70B9\u51FB\u540E\u53F3\u4FA7\u539F\u751F\u9884\u89C8\u9875\u4F1A\u5B9A\u4F4D\u5E76\u6FC0\u6D3B\u8BE5\u5143\u7D20\u5757\u3002
2055
+ 5. \u5B8C\u6210\u8F6C\u6362\u6216\u5185\u5BB9\u56DE\u7B54\u540E\uFF0C\u5728\u6700\u7EC8\u56DE\u590D\u7684\u6700\u540E\u5355\u72EC\u4E00\u884C\u8F93\u51FA Markdown \u94FE\u63A5\uFF1A[\u67E5\u770B\u6587\u6863\u9884\u89C8](preview_url)\u3002preview_url \u6765\u81EA pdflux_convert_export\uFF08\`dsh-resource://pdflux-result/...\`\uFF09\uFF0C\u539F\u6837\u4F7F\u7528\u3002DSH \u4F1A\u5728\u53F3\u4FA7\u6253\u5F00\u539F\u751F\u9884\u89C8\u9875\u7B7E\u3002\u4E0D\u8981\u628A markdown_url / html_url / docx_url / excel_url \u5199\u8FDB\u56DE\u590D\uFF1B\u4E0B\u8F7D\u6309\u94AE\u4F1A\u81EA\u52A8\u663E\u793A\u5728\u6700\u7EC8\u56DE\u590D\u4E0B\u65B9\u3002
2056
+
2057
+ ## \u8F93\u51FA\u6A21\u677F
2058
+ \u7B80\u8981\u8BF4\u660E\u5DF2\u5BFC\u51FA\u54EA\u4E9B\u683C\u5F0F\uFF0C\u6216\u6309\u6587\u6863\u5185\u5BB9\u4F5C\u7B54\u5E76\u9644\u5F15\u7528\u89D2\u6807\uFF0C\u518D\u9644\u4E0A\u9884\u89C8\u94FE\u63A5\u3002
2059
+
2060
+ \u793A\u4F8B\uFF1A\u8425\u4E1A\u6536\u5165\u4E3A 1,234 \u4E07\u5143[![[1]](about:blank)](<preview_url>?block=1-0)\u3002
2061
+
2062
+ [\u67E5\u770B\u6587\u6863\u9884\u89C8](<\u5DE5\u5177\u8FD4\u56DE\u7684 preview_url>)
2063
+
2064
+ ## \u7EA6\u675F
2065
+ - \u4E0D\u81C6\u6D4B\u672A\u8FD4\u56DE\u7684\u6B63\u6587\u5185\u5BB9\u3002
2066
+ - \u5F15\u7528\u6587\u6863\u5185\u5BB9\u65F6\u5E26\u4E0A\u539F\u6587\u6458\u5F55\uFF0C\u5E76\u9644\u4E0A\u8BE5\u6BB5\u6807\u9898\u91CC\u5DF2\u7ED9\u597D\u7684\u5F15\u7528\u89D2\u6807\u3002
2067
+ - \u5F15\u7528\u89D2\u6807\u5FC5\u987B\u4ECE pdflux_convert_export \u8FD4\u56DE\u7684 Markdown \u539F\u6837\u590D\u5236\uFF1B\u4E0D\u5199 \xB9\xB2\xB3 \u8FD9\u7C7B\u4E0A\u6807\u6570\u5B57\uFF0C\u4E5F\u4E0D\u5199\u4E0D\u5E26\u94FE\u63A5\u7684 [1]\u3002
2068
+ - \u4E0D\u590D\u8FF0\u539F\u59CB JSON\uFF1B\u7528\u6458\u8981\u4E0E\u4E0B\u8F7D\u5165\u53E3\u8868\u8FBE\u3002
2069
+ - \u4E0D\u8981\u628A\u4E0B\u8F7D URL \u660E\u6587\u5199\u8FDB\u56DE\u590D\u6B63\u6587\u3002
2070
+ `
2071
+ };
2072
+ var CONVERT_EN = {
2073
+ description: "Parse a PDF and export Markdown, HTML, DOCX, and Excel with download links (see pdflux-translate for translation)",
2074
+ markdown: `# pdflux-convert
2075
+
2076
+ ## When to use
2077
+ - The user asks to convert a PDF to Markdown / HTML / Word(DOCX) / Excel, or needs downloadable parse outputs.
2078
+ - Phrases like \u201Cexport\u201D, \u201Cconvert\u201D, \u201Cdownload md/html/docx/xlsx\u201D.
2079
+ - Questions about the converted document body, a passage, a figure, or its source.
2080
+ - If translation is also requested, finish this flow first, then continue with \`pdflux-translate\`.
2081
+
2082
+ ## Flow
2083
+ 1. Create a job with pdflux_convert_create. Use \`path\` for workspace files and \`attachment\` (attachmentId/name/bytes) for session attachments. PDF only via NanoDoc.
2084
+ 2. Poll with pdflux_convert_status; when next_action is \`wait\`, call again (wait_seconds \u2264 60). After at most 10 waits, tell the user it is still running. On \`report_failure\`, say parsing failed.
2085
+ 3. Call pdflux_convert_export for preview and download URLs. When answering content, read the returned Markdown: each heading looks like \`### block=<id> [![[n]](about:blank)](<preview_url>?block=<id>) (page N \xB7 type)\` and already includes the citation marker.
2086
+ 4. After each cited fact, copy that heading\u2019s citation marker verbatim, e.g. \`Revenue[![[1]](about:blank)](<preview_url>?block=1-0)\`.
2087
+ 5. End the final reply with one Markdown link line: [View document preview](preview_url). Use preview_url from pdflux_convert_export (\`dsh-resource://pdflux-result/...\`) unchanged. Do not paste download URLs into the reply body.
2088
+
2089
+ ## Output template
2090
+ Briefly list exported formats, or answer from the document with citation markers, then the preview link.
2091
+
2092
+ Example: Revenue is 12.34 million[![[1]](about:blank)](<preview_url>?block=1-0).
2093
+
2094
+ [View document preview](<preview_url from the tool>)
2095
+
2096
+ ## Constraints
2097
+ - Do not invent body text that was not returned.
2098
+ - When citing document content, include the excerpt and the citation marker from that section heading.
2099
+ - Copy citation markers from the export Markdown verbatim; no bare superscripts or unlinked [1].
2100
+ - Do not dump raw JSON.
2101
+ - Do not put download URLs in the reply body.
2102
+ `
2103
+ };
2104
+ var TRANSLATE_ZH = {
2105
+ description: "\u89E3\u6790\u5B8C\u6210\u540E\u7FFB\u8BD1\u6210\u6307\u5B9A\u8BED\u8A00\uFF0C\u5B8C\u6210\u540E\u7ED9\u51FA\u7FFB\u8BD1\u5BF9\u7167\u9875\u4E0E\u8BD1\u540E\u6587\u4EF6\u4E0B\u8F7D",
2106
+ markdown: `# pdflux-translate
2107
+
2108
+ ## \u4F55\u65F6\u4F7F\u7528
2109
+ - \u7528\u6237\u8981\u6C42\u628A\u5DF2\u89E3\u6790\uFF08\u6216\u521A\u4E0A\u4F20\uFF09\u7684 PDF \u7FFB\u8BD1\u6210\u82F1\u6587 / \u4E2D\u6587\u7B49\u3002
2110
+ - \u7528\u6237\u8BF4\u300C\u7FFB\u8BD1\u300D\u300C\u8BD1\u6210\u82F1\u6587\u300D\u300C\u5BF9\u7167\u7FFB\u8BD1\u300D\u7B49\u3002
2111
+ - \u7528\u6237\u8BE2\u95EE\u5DF2\u7FFB\u8BD1\u6587\u6863\u7684\u8BD1\u6587\u5185\u5BB9\u3001\u67D0\u6BB5\u6587\u5B57\u6216\u51FA\u5904\u3002
2112
+
2113
+ ## \u6D41\u7A0B
2114
+ 1. \u82E5\u8FD8\u6CA1\u6709 document_id\uFF1A\u5148\u6309 \`pdflux-convert\` \u5B8C\u6210 create + status\uFF0C\u76F4\u5230 state=succeeded\u3002\u4E0D\u5FC5\u518D\u8C03\u7528 export\uFF1B\u7FFB\u8BD1\u5B8C\u6210\u540E\u4F1A\u76F4\u63A5\u7ED9\u51FA\u8BD1\u540E Markdown/HTML/DOCX/Excel \u4E0B\u8F7D\u3002
2115
+ 2. \u8C03\u7528 pdflux_translate_blocks\uFF0C\u4F20\u5165 document_id \u4E0E target_lang\uFF08\u5982 \`en\` / \`zh\`\uFF09\u3002\u5DE5\u5177\u6BCF\u6B21\u6700\u591A\u8FD4\u56DE 10 \u6761\u5F85\u8BD1 blocks\uFF0C\u5E76\u544A\u77E5\u5F85\u8BD1\u603B\u6570 total_count\u3002
2116
+ 3. \u82E5 next_action=done\uFF1A\u8BD1\u540E\u6587\u4EF6\u5DF2\u5C31\u7EEA\uFF1B\u82E5\u8FD4\u56DE\u4E86 Markdown\uFF0C\u53EF\u76F4\u63A5\u636E\u6B64\u56DE\u7B54\u8BD1\u6587\u5185\u5BB9\u3002\u8DF3\u5230\u7B2C 7 \u6B65\u3002
2117
+ 4. \u82E5 next_action=wait\uFF1A\u8BD1\u6587\u5DF2\u9F50\uFF0C\u670D\u52A1\u7AEF\u6B63\u5728\u751F\u6210\u8BD1\u540E\u6587\u4EF6\u3002\u7A0D\u540E\u518D\u6B21\u8C03\u7528 pdflux_translate_blocks\uFF08\u6216 submit \u540C\u53C2\u8F6E\u8BE2\uFF09\u7B49\u5F85 complete=true / next_action=done\uFF0C\u4E0D\u8981\u518D\u7FFB\u8BD1\u3002
2118
+ 5. \u82E5 next_action=translate\uFF1A\u7531\u4F60\uFF08\u672C\u4F1A\u8BDD\u6A21\u578B\uFF09\u53EA\u7FFB\u8BD1\u8FD4\u56DE\u7684\u672C\u6279 blocks\uFF08\u226410 \u6761\uFF09\u3002\u6BCF\u6761\u4FDD\u7559\u539F key\uFF0C\u8BD1\u6587\u5199\u5165 translation\u3002\u8BD1\u5B8C\u672C\u6279\u540E\u7ACB\u5373\u8C03\u7528 pdflux_translate_submit\uFF0C\u4E0D\u8981\u5148\u89C4\u5212\u5168\u91CF\u5207\u5757\u3002
2119
+ 6. \u8C03\u7528 pdflux_translate_submit \u56DE\u4F20\u672C\u6279\u3002\u82E5 next_action=translate_more\uFF1Amissing \u540C\u6837\u6700\u591A 10 \u6761\u5E76\u5E26\u5269\u4F59\u603B\u6570 missing_count\uFF1B\u53EA\u7FFB\u8BD1\u672C\u6279 missing\uFF0C\u518D\u6B21 submit\u3002\u82E5 next_action=wait\uFF1A\u540C\u7B2C 4 \u6B65\uFF0C\u7B49 render\u3002\u91CD\u590D\u76F4\u5230 complete=true / next_action=done\u3002\u5757\u9F50\u4E0D\u7B49\u4E8E\u5B8C\u6210\uFF1B\u987B\u7B49\u8BD1\u540E\u4EA7\u7269\u843D\u76D8\u3002
2120
+ 7. \u7FFB\u8BD1\u5B8C\u6210\u540E\u5DE5\u5177\u4F1A\u8FD4\u56DE\u5E26\u5B8C\u6574\u5F15\u7528\u89D2\u6807\u7684 Markdown\uFF1A\`### block=<id> [![[\u5E8F\u53F7]](about:blank)](<translate_url>&block=<id>)\uFF08\u7B2C N \u9875 \xB7 type\uFF09\`\uFF0C\u6B63\u6587\u542B\u539F\u6587/\u8BD1\u6587\u3002\u56DE\u7B54\u8BD1\u6587\u5185\u5BB9\u65F6\uFF0C\u628A\u8BE5\u6BB5\u6807\u9898\u91CC\u7684\u5F15\u7528\u89D2\u6807\u539F\u6837\u590D\u5236\u5230\u5F15\u7528\u5185\u5BB9\u540E\u9762\uFF1B\u4E0D\u8981\u6539\u5199\u94FE\u63A5\uFF0C\u4E0D\u8981\u81EA\u5DF1\u62FC query\u3002
2121
+ 8. \u5B8C\u6210\u540E\u5728\u6700\u7EC8\u56DE\u590D\u672B\u5C3E\u5355\u72EC\u4E00\u884C\u8F93\u51FA\uFF1A[\u67E5\u770B\u7FFB\u8BD1\u7ED3\u679C](translate_url)\u3002translate_url \u6765\u81EA\u5DE5\u5177\u8FD4\u56DE\u503C\uFF08\`dsh-resource://pdflux-result/...?view=translate&lang=...\`\uFF09\uFF0C\u539F\u6837\u4F7F\u7528\uFF0C\u4E0D\u8981\u5220\u6539\u67E5\u8BE2\u53C2\u6570\u3002DSH \u4F1A\u5728\u53F3\u4FA7\u6253\u5F00\u539F\u751F\u7FFB\u8BD1\u5BF9\u7167\u9875\u7B7E\u3002\u4E0D\u8981\u628A markdown_url / html_url / docx_url / excel_url \u5199\u8FDB\u56DE\u590D\uFF1B\u8BD1\u540E\u4E0B\u8F7D\u6309\u94AE\u4F1A\u81EA\u52A8\u663E\u793A\u3002
2122
+
2123
+ ## \u7FFB\u8BD1\u8981\u6C42
2124
+ - \u5FE0\u5B9E\u539F\u6587\uFF0C\u4FDD\u7559\u4E13\u6709\u540D\u8BCD\u3001\u6570\u5B57\u3001\u5355\u4F4D\u3002
2125
+ - \u4E0D\u8981\u6539 key\uFF1B\u8868\u683C\u5355\u5143\u683C key \u5F62\u5982 \`e12c0-1\`\u3002
2126
+ - \u4E0D\u8981\u628A blocks / missing \u7684\u539F\u59CB JSON \u6574\u6BB5\u8D34\u8FDB\u5BF9\u7528\u6237\u7684\u56DE\u590D\u3002
2127
+
2128
+ ## \u8F93\u51FA\u6A21\u677F
2129
+ \u7B80\u8981\u8BF4\u660E\u76EE\u6807\u8BED\u8A00\u4E0E\u5B8C\u6210\u60C5\u51B5\uFF0C\u6216\u6309\u8BD1\u6587\u5185\u5BB9\u4F5C\u7B54\u5E76\u9644\u5F15\u7528\u89D2\u6807\uFF0C\u518D\u9644\u4E0A\u7FFB\u8BD1\u7ED3\u679C\u94FE\u63A5\u3002
2130
+
2131
+ \u793A\u4F8B\uFF1AOperating revenue is 12.34 million[![[1]](about:blank)](<translate_url>&block=1-0)\u3002
2132
+
2133
+ [\u67E5\u770B\u7FFB\u8BD1\u7ED3\u679C](<\u5DE5\u5177\u8FD4\u56DE\u7684 translate_url>)
2134
+
2135
+ ## \u7EA6\u675F
2136
+ - \u7FFB\u8BD1\u4E0E\u63D0\u4EA4\u53EA\u5728\u672C\u4F1A\u8BDD\u7528 pdflux_translate_blocks / pdflux_translate_submit \u5B8C\u6210\uFF1B\u7981\u6B62\u4E3A\u7FFB\u8BD1\u5F00 subagent / workflow\uFF0C\u7981\u6B62\u5199 chunk \u6587\u4EF6\u6216 curl \u540E\u7AEF\u3002
2137
+ - \u6BCF\u6279\u53EA\u5904\u7406\u5DE5\u5177\u8FD4\u56DE\u7684 \u226410 \u6761\uFF1B\u6536\u5230\u672C\u6279\u540E\u7ACB\u5373\u8BD1\u5E76 submit\uFF0C\u518D\u5904\u7406\u4E0B\u4E00\u6279\u3002
2138
+ - \u4E0D\u81C6\u6D4B\u672A\u8FD4\u56DE\u7684\u8BD1\u6587\u5185\u5BB9\u3002
2139
+ - \u5F15\u7528\u8BD1\u6587\u65F6\u5E26\u4E0A\u539F\u6587/\u8BD1\u6587\u6458\u5F55\uFF0C\u5E76\u9644\u4E0A\u8BE5\u6BB5\u6807\u9898\u91CC\u5DF2\u7ED9\u597D\u7684\u5F15\u7528\u89D2\u6807\u3002
2140
+ - \u5F15\u7528\u89D2\u6807\u5FC5\u987B\u4ECE\u7FFB\u8BD1\u5B8C\u6210\u5DE5\u5177\u8FD4\u56DE\u7684 Markdown \u539F\u6837\u590D\u5236\uFF1B\u4E0D\u5199 \xB9\xB2\xB3 \u8FD9\u7C7B\u4E0A\u6807\u6570\u5B57\uFF0C\u4E5F\u4E0D\u5199\u4E0D\u5E26\u94FE\u63A5\u7684 [1]\u3002
2141
+ `
2142
+ };
2143
+ var TRANSLATE_EN = {
2144
+ description: "After parsing, translate into a target language and provide the bilingual view plus translated downloads",
2145
+ markdown: `# pdflux-translate
2146
+
2147
+ ## When to use
2148
+ - The user asks to translate an already-parsed (or just-uploaded) PDF into English / Chinese / etc.
2149
+ - Phrases like \u201Ctranslate\u201D, \u201Cinto English\u201D, \u201Cbilingual translation\u201D.
2150
+ - Questions about translated text or its source.
2151
+
2152
+ ## Flow
2153
+ 1. If there is no document_id yet: finish \`pdflux-convert\` create + status until state=succeeded. No need to export first; translated downloads come after translation.
2154
+ 2. Call pdflux_translate_blocks with document_id and target_lang (e.g. \`en\` / \`zh\`). Each call returns at most 10 blocks plus total_count.
2155
+ 3. If next_action=done: translated files are ready; if Markdown is returned, answer from it. Jump to step 7.
2156
+ 4. If next_action=wait: translations are complete and the server is rendering files. Call again later; do not translate more.
2157
+ 5. If next_action=translate: translate only this batch (\u226410). Keep each key; put text in translation. Immediately call pdflux_translate_submit.
2158
+ 6. After submit, if next_action=translate_more: translate the next missing batch (\u226410) and submit again. If next_action=wait: same as step 4. Repeat until complete=true / next_action=done.
2159
+ 7. Completed tools return Markdown with citation markers like \`### block=<id> [![[n]](about:blank)](<translate_url>&block=<id>) (page N \xB7 type)\`. Copy markers verbatim when citing.
2160
+ 8. End with: [View translation](translate_url). Use the tool\u2019s translate_url (\`dsh-resource://pdflux-result/...?view=translate&lang=...\`) unchanged.
2161
+
2162
+ ## Translation requirements
2163
+ - Stay faithful; keep proper nouns, numbers, and units.
2164
+ - Do not change keys; table cell keys look like \`e12c0-1\`.
2165
+ - Do not paste raw blocks/missing JSON into the user reply.
2166
+
2167
+ ## Output template
2168
+ State the target language and status, or answer from the translation with citation markers, then the translation link.
2169
+
2170
+ Example: Operating revenue is 12.34 million[![[1]](about:blank)](<translate_url>&block=1-0).
2171
+
2172
+ [View translation](<translate_url from the tool>)
2173
+
2174
+ ## Constraints
2175
+ - Translate and submit only with pdflux_translate_blocks / pdflux_translate_submit in this session; no subagents, chunk files, or direct backend curls.
2176
+ - Handle only the \u226410 items returned each time; translate and submit immediately before the next batch.
2177
+ - Do not invent missing translations.
2178
+ - When citing, include excerpts plus the heading\u2019s citation marker.
2179
+ `
2180
+ };
2181
+ function skillForLanguage(language2) {
2182
+ return language2 === "zh" ? CONVERT_ZH : CONVERT_EN;
2183
+ }
2184
+ function translateSkillForLanguage(language2) {
2185
+ return language2 === "zh" ? TRANSLATE_ZH : TRANSLATE_EN;
2186
+ }
2187
+ var SKILL_DESCRIPTION = CONVERT_ZH.description;
2188
+ var SKILL_MARKDOWN = CONVERT_ZH.markdown;
2189
+ var TRANSLATE_SKILL_DESCRIPTION = TRANSLATE_ZH.description;
2190
+ var TRANSLATE_SKILL_MARKDOWN = TRANSLATE_ZH.markdown;
2191
+
2192
+ // src/index.ts
2193
+ var name = "pdflux";
2194
+ var inject = ["tools", "skills", "credentials", "storageDomain", "webServer", "connection", "attachments", "fs"];
2195
+ var documentRecordSchema = z2.object({
2196
+ document_id: z2.string(),
2197
+ filename: z2.string(),
2198
+ parser: z2.string(),
2199
+ created_at: z2.number(),
2200
+ content_key: z2.string(),
2201
+ backend_origin: z2.string().optional()
2202
+ });
2203
+ var idemRecordSchema = z2.object({
2204
+ document_id: z2.string(),
2205
+ content_key: z2.string(),
2206
+ created_at: z2.number()
2207
+ });
2208
+ function adaptTable(table) {
2209
+ return {
2210
+ get: (key) => table.get(key),
2211
+ put: (key, value) => table.put(key, value)
2212
+ };
2213
+ }
2214
+ async function apply(ctx, config = Config({})) {
2215
+ const resolveApiKey = async () => {
2216
+ const language2 = resolvePluginLanguage(config.language.get(), config.baseUrl.get());
2217
+ const ref = language2 === "zh" ? config.nanodocApiKeyRefZh.get() : config.nanodocApiKeyRefEn.get();
2218
+ const hit = await ctx.credentials.resolve(credentialRef(ref));
2219
+ return hit?.value;
2220
+ };
2221
+ const client = new RsClient({
2222
+ baseUrl: () => config.baseUrl.get(),
2223
+ getApiKey: resolveApiKey
2224
+ });
2225
+ const domain = await ctx.storageDomain.open(
2226
+ defineDomain({
2227
+ name: "pdflux",
2228
+ version: 1,
2229
+ tables: {
2230
+ documents: domainTable(documentRecordSchema),
2231
+ idempotency: domainTable(idemRecordSchema)
2232
+ }
2233
+ })
2234
+ );
2235
+ ctx.effect(() => () => {
2236
+ void domain.close().catch(() => {
2237
+ });
2238
+ }, "pdflux: storage domain");
2239
+ const registry = new DocumentRegistry(
2240
+ adaptTable(domain.table("documents")),
2241
+ adaptTable(domain.table("idempotency"))
2242
+ );
2243
+ registerTools(ctx, {
2244
+ client,
2245
+ config,
2246
+ registry,
2247
+ fs: ctx.fs,
2248
+ attachments: ctx.attachments,
2249
+ resolveApiKey,
2250
+ logger: ctx.logger
2251
+ });
2252
+ const registerSkills = (language2) => {
2253
+ const skill = skillForLanguage(language2);
2254
+ const translateSkill = translateSkillForLanguage(language2);
2255
+ const disposeConvert = ctx.skills.register({
2256
+ name: SKILL_NAME,
2257
+ description: skill.description,
2258
+ source: "bundled",
2259
+ content: skill.markdown
2260
+ });
2261
+ const disposeTranslate = ctx.skills.register({
2262
+ name: TRANSLATE_SKILL_NAME,
2263
+ description: translateSkill.description,
2264
+ source: "bundled",
2265
+ content: translateSkill.markdown
2266
+ });
2267
+ return () => {
2268
+ disposeConvert();
2269
+ disposeTranslate();
2270
+ };
2271
+ };
2272
+ let disposeSkills = registerSkills(resolvePluginLanguage(config.language.get(), config.baseUrl.get()));
2273
+ const refreshSkills = (language2) => {
2274
+ disposeSkills();
2275
+ disposeSkills = registerSkills(language2);
2276
+ };
2277
+ const resultCache = new ResultCache({ plugin: "pdflux" });
2278
+ const assetsRoot = defaultAssetsRoot();
2279
+ if (!existsSync3(join(assetsRoot, "pdf-document-viewer"))) {
2280
+ ctx.logger?.warn?.(
2281
+ "[pdflux] missing lib/assets/pdf-document-viewer; rebuild and reinstall the plugin so PDF preview can load worker assets"
2282
+ );
2283
+ }
2284
+ const updateConfig = async (patch) => {
2285
+ const raw = ctx.fiber.rawConfig;
2286
+ const snapshot = {
2287
+ nanodocApiKeyRefZh: config.nanodocApiKeyRefZh.get(),
2288
+ nanodocApiKeyRefEn: config.nanodocApiKeyRefEn.get(),
2289
+ pollIntervalMs: config.pollIntervalMs.get(),
2290
+ maxWaitSeconds: config.maxWaitSeconds.get(),
2291
+ maxFileMB: config.maxFileMB.get(),
2292
+ requireUploadApproval: config.requireUploadApproval.get(),
2293
+ language: config.language.get(),
2294
+ baseUrl: config.baseUrl.get(),
2295
+ ...raw && typeof raw === "object" ? raw : {},
2296
+ ...patch.language ? { language: patch.language } : {},
2297
+ ...patch.baseUrl ? { baseUrl: patch.baseUrl } : {}
2298
+ };
2299
+ const entry = ctx.fiber.entry;
2300
+ if (entry) {
2301
+ const legacy = { ...entry.options };
2302
+ await entry.update({ config: snapshot });
2303
+ entry.parent.tree.commit({
2304
+ id: entry.options.id,
2305
+ group: entry.parent,
2306
+ options: entry.options,
2307
+ legacy
2308
+ });
2309
+ } else {
2310
+ await ctx.fiber.update(snapshot);
2311
+ }
2312
+ if (patch.language) refreshSkills(patch.language);
2313
+ };
2314
+ registerRoutes(ctx, {
2315
+ config,
2316
+ registry,
2317
+ connection: ctx.connection,
2318
+ resultCache,
2319
+ assetsRoot,
2320
+ updateConfig,
2321
+ resolveApiKey
2322
+ });
2323
+ ctx.on("tools/pre-execute", async (exec, next) => {
2324
+ if (!config.requireUploadApproval.get()) return next();
2325
+ if (exec?.name === "pdflux_convert_create") {
2326
+ const args = exec.arguments;
2327
+ const fs = ctx.fs;
2328
+ let fileDesc;
2329
+ if ("attachment" in args.source) {
2330
+ fileDesc = `${args.source.attachment.name} (${args.source.attachment.bytes} B)`;
2331
+ } else {
2332
+ const target = await resolveWorkspaceFile(args.source.path, fs, exec.agent?.session.header.cwd, exec.signal);
2333
+ const info = await fs.stat?.(target, exec.signal);
2334
+ fileDesc = `${args.source.path} (${info?.size === void 0 ? language === "en" ? "size unknown" : "\u5927\u5C0F\u672A\u77E5" : `${info.size} B`})`;
2335
+ }
2336
+ const reason = `${fileDesc}; destination: ${config.baseUrl.get()}`;
2337
+ return {
2338
+ kind: "ask",
2339
+ reason,
2340
+ displayReason: {
2341
+ en: `Upload file to PDFlux? ${reason}`,
2342
+ zh: `\u5C06\u6587\u4EF6\u4E0A\u4F20\u5230 PDFlux \u8F6C\u6362\u670D\u52A1\uFF1F${reason}`
2343
+ }
2344
+ };
2345
+ }
2346
+ return next();
2347
+ });
2348
+ }
2349
+ export {
2350
+ Config,
2351
+ DocumentRegistry,
2352
+ PdfluxError,
2353
+ RsClient,
2354
+ absoluteDownloadUrl,
2355
+ apply,
2356
+ assertPdfName,
2357
+ contentKey,
2358
+ hasPdfMagic,
2359
+ inject,
2360
+ isPdfluxError,
2361
+ isTerminalState,
2362
+ loadSource,
2363
+ name,
2364
+ normalizeOrigin,
2365
+ resolveServiceBaseUrl,
2366
+ resolveWorkspaceFile
2367
+ };