@v587d/capital-generation 2.29.0 → 2.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +3 -3
  3. package/THIRD_PARTY_NOTICES.md +16 -0
  4. package/automation/package.json +1 -1
  5. package/chart-ui/package.json +1 -1
  6. package/config/package.json +1 -1
  7. package/lib/collector-runtime.js +56 -1
  8. package/lib/data-collector/catalog-taxonomy.d.ts +1 -1
  9. package/lib/data-collector/catalog-taxonomy.js +33 -0
  10. package/lib/data-collector/dataset-tools.js +4 -2
  11. package/lib/data-collector/describe.d.ts +2 -0
  12. package/lib/data-collector/describe.js +2 -0
  13. package/lib/data-collector/store.d.ts +11 -0
  14. package/lib/data-collector/store.js +80 -1
  15. package/lib/data-collector/tools.d.ts +1 -1
  16. package/lib/data-collector/tools.js +10 -9
  17. package/lib/python-runtime/errors.d.ts +1 -1
  18. package/lib/python-runtime/errors.js +2 -0
  19. package/lib/python-runtime/manager.d.ts +28 -1
  20. package/lib/python-runtime/manager.js +141 -5
  21. package/lib/python-runtime/probe.d.ts +24 -0
  22. package/lib/python-runtime/probe.js +66 -50
  23. package/lib/sources/csindex-http.d.ts +4 -0
  24. package/lib/sources/csindex-http.js +233 -0
  25. package/lib/sources/eastmoney-http.js +1504 -1
  26. package/lib/sources/fuyao-rest.js +168 -8
  27. package/lib/sources/official-http.d.ts +4 -0
  28. package/lib/sources/official-http.js +477 -0
  29. package/lib/sources/python-remote.d.ts +25 -0
  30. package/lib/sources/python-remote.js +461 -0
  31. package/lib/sources/sina-http.d.ts +2 -0
  32. package/lib/sources/sina-http.js +484 -0
  33. package/lib/sources/tencent-http.js +23 -8
  34. package/lib/sources/ths-http.d.ts +2 -0
  35. package/lib/sources/ths-http.js +517 -0
  36. package/lib/time/tools.js +19 -0
  37. package/lib/web-retriever/local-fetch.d.ts +1 -1
  38. package/lib/web-retriever/local-fetch.js +1 -1
  39. package/lib/web-retriever/sources.d.ts +7 -0
  40. package/lib/web-retriever/sources.js +46 -21
  41. package/lib/web-retriever/throttle.d.ts +8 -0
  42. package/lib/web-retriever/throttle.js +13 -0
  43. package/lib/web-retriever/tools.js +1 -1
  44. package/lib/web-retriever/wind-client.d.ts +1 -1
  45. package/lib/web-retriever/wind-client.js +1 -1
  46. package/package.json +1 -1
  47. package/preset/capital-generation/agent.patch.yml +7 -5
  48. package/preset/capital-generation/skills/capital-data-protocol/SKILL.md +16 -16
  49. package/python/scripts/baostock_stock_basic.py +129 -0
  50. package/python/scripts/baostock_valuation_history.py +141 -0
  51. package/python/scripts/pbc_social_financing.py +291 -0
  52. package/python/vendor/baostock/LICENSE +19 -0
  53. package/python/vendor/baostock/__init__.py +42 -0
  54. package/python/vendor/baostock/common/__init__.py +0 -0
  55. package/python/vendor/baostock/common/contants.py +189 -0
  56. package/python/vendor/baostock/common/context.py +4 -0
  57. package/python/vendor/baostock/corpreport/__init__.py +0 -0
  58. package/python/vendor/baostock/corpreport/corp_performance.py +202 -0
  59. package/python/vendor/baostock/data/__init__.py +0 -0
  60. package/python/vendor/baostock/data/messageheader.py +17 -0
  61. package/python/vendor/baostock/data/msg.py +21 -0
  62. package/python/vendor/baostock/data/resultset.py +200 -0
  63. package/python/vendor/baostock/demo/__init__.py +0 -0
  64. package/python/vendor/baostock/demo/demo_A_stock_5mk-data.py +34 -0
  65. package/python/vendor/baostock/demo/demo_A_stock_k_data.py +36 -0
  66. package/python/vendor/baostock/demo/demo_AllStock.py +27 -0
  67. package/python/vendor/baostock/demo/demo_Balance_data.py +22 -0
  68. package/python/vendor/baostock/demo/demo_CashFlow_data.py +22 -0
  69. package/python/vendor/baostock/demo/demo_Dividend_data.py +35 -0
  70. package/python/vendor/baostock/demo/demo_Dupont_data.py +25 -0
  71. package/python/vendor/baostock/demo/demo_Forecast_report.py +24 -0
  72. package/python/vendor/baostock/demo/demo_Growth_data.py +22 -0
  73. package/python/vendor/baostock/demo/demo_Index_k_data.py +39 -0
  74. package/python/vendor/baostock/demo/demo_Operation_data.py +22 -0
  75. package/python/vendor/baostock/demo/demo_PerformanceExpress_report.py +25 -0
  76. package/python/vendor/baostock/demo/demo_Profit_data.py +22 -0
  77. package/python/vendor/baostock/demo/demo_TradeDates.py +27 -0
  78. package/python/vendor/baostock/demo/demo_adjust_factor_data.py +23 -0
  79. package/python/vendor/baostock/demo/demo_assignDayData.py +23 -0
  80. package/python/vendor/baostock/demo/demo_daily_adjust_factor_data.py +28 -0
  81. package/python/vendor/baostock/demo/demo_daily_k_4_AStock.py +28 -0
  82. package/python/vendor/baostock/demo/demo_daily_k_4_ETF.py +28 -0
  83. package/python/vendor/baostock/demo/demo_depositRate_data.py +26 -0
  84. package/python/vendor/baostock/demo/demo_hs300_stocks.py +26 -0
  85. package/python/vendor/baostock/demo/demo_loanRate_data.py +26 -0
  86. package/python/vendor/baostock/demo/demo_moneySupplyDataMonth_data.py +26 -0
  87. package/python/vendor/baostock/demo/demo_moneySupplyDataYear_data.py +26 -0
  88. package/python/vendor/baostock/demo/demo_requiredReserveRatio_data.py +26 -0
  89. package/python/vendor/baostock/demo/demo_set_API_key.py +37 -0
  90. package/python/vendor/baostock/demo/demo_stockBasic_data.py +27 -0
  91. package/python/vendor/baostock/demo/demo_stock_Valuation_indicator_data.py +34 -0
  92. package/python/vendor/baostock/demo/demo_stock_industry.py +26 -0
  93. package/python/vendor/baostock/demo/demo_sz50stocks.py +26 -0
  94. package/python/vendor/baostock/demo/demo_zz500_stock.py +26 -0
  95. package/python/vendor/baostock/evaluation/__init__.py +0 -0
  96. package/python/vendor/baostock/evaluation/season_index.py +758 -0
  97. package/python/vendor/baostock/login/__init__.py +0 -0
  98. package/python/vendor/baostock/login/loginout.py +230 -0
  99. package/python/vendor/baostock/macroscopic/__init__.py +0 -0
  100. package/python/vendor/baostock/macroscopic/economic_data.py +723 -0
  101. package/python/vendor/baostock/metadata/__init__.py +0 -0
  102. package/python/vendor/baostock/metadata/stock_metadata.py +207 -0
  103. package/python/vendor/baostock/security/__init__.py +0 -0
  104. package/python/vendor/baostock/security/history.py +265 -0
  105. package/python/vendor/baostock/security/sectorinfo.py +1024 -0
  106. package/python/vendor/baostock/util/__init__.py +0 -0
  107. package/python/vendor/baostock/util/socketutil.py +97 -0
  108. package/python/vendor/baostock/util/stringutil.py +83 -0
  109. package/python/vendor/et_xmlfile/LICENSE +23 -0
  110. package/python/vendor/et_xmlfile/LICENSE.python +298 -0
  111. package/python/vendor/et_xmlfile/__init__.py +8 -0
  112. package/python/vendor/et_xmlfile/incremental_tree.py +917 -0
  113. package/python/vendor/et_xmlfile/xmlfile.py +158 -0
  114. package/python/vendor/openpyxl/LICENSE +23 -0
  115. package/python/vendor/openpyxl/__init__.py +19 -0
  116. package/python/vendor/openpyxl/_constants.py +13 -0
  117. package/python/vendor/openpyxl/cell/__init__.py +4 -0
  118. package/python/vendor/openpyxl/cell/_writer.py +136 -0
  119. package/python/vendor/openpyxl/cell/cell.py +332 -0
  120. package/python/vendor/openpyxl/cell/read_only.py +136 -0
  121. package/python/vendor/openpyxl/cell/rich_text.py +202 -0
  122. package/python/vendor/openpyxl/cell/text.py +184 -0
  123. package/python/vendor/openpyxl/chart/_3d.py +105 -0
  124. package/python/vendor/openpyxl/chart/__init__.py +19 -0
  125. package/python/vendor/openpyxl/chart/_chart.py +199 -0
  126. package/python/vendor/openpyxl/chart/area_chart.py +106 -0
  127. package/python/vendor/openpyxl/chart/axis.py +401 -0
  128. package/python/vendor/openpyxl/chart/bar_chart.py +144 -0
  129. package/python/vendor/openpyxl/chart/bubble_chart.py +67 -0
  130. package/python/vendor/openpyxl/chart/chartspace.py +195 -0
  131. package/python/vendor/openpyxl/chart/data_source.py +246 -0
  132. package/python/vendor/openpyxl/chart/descriptors.py +43 -0
  133. package/python/vendor/openpyxl/chart/error_bar.py +62 -0
  134. package/python/vendor/openpyxl/chart/label.py +127 -0
  135. package/python/vendor/openpyxl/chart/layout.py +74 -0
  136. package/python/vendor/openpyxl/chart/legend.py +75 -0
  137. package/python/vendor/openpyxl/chart/line_chart.py +129 -0
  138. package/python/vendor/openpyxl/chart/marker.py +90 -0
  139. package/python/vendor/openpyxl/chart/picture.py +35 -0
  140. package/python/vendor/openpyxl/chart/pie_chart.py +177 -0
  141. package/python/vendor/openpyxl/chart/pivot.py +65 -0
  142. package/python/vendor/openpyxl/chart/plotarea.py +162 -0
  143. package/python/vendor/openpyxl/chart/print_settings.py +57 -0
  144. package/python/vendor/openpyxl/chart/radar_chart.py +55 -0
  145. package/python/vendor/openpyxl/chart/reader.py +32 -0
  146. package/python/vendor/openpyxl/chart/reference.py +124 -0
  147. package/python/vendor/openpyxl/chart/scatter_chart.py +53 -0
  148. package/python/vendor/openpyxl/chart/series.py +197 -0
  149. package/python/vendor/openpyxl/chart/series_factory.py +41 -0
  150. package/python/vendor/openpyxl/chart/shapes.py +89 -0
  151. package/python/vendor/openpyxl/chart/stock_chart.py +54 -0
  152. package/python/vendor/openpyxl/chart/surface_chart.py +119 -0
  153. package/python/vendor/openpyxl/chart/text.py +78 -0
  154. package/python/vendor/openpyxl/chart/title.py +76 -0
  155. package/python/vendor/openpyxl/chart/trendline.py +98 -0
  156. package/python/vendor/openpyxl/chart/updown_bars.py +31 -0
  157. package/python/vendor/openpyxl/chartsheet/__init__.py +3 -0
  158. package/python/vendor/openpyxl/chartsheet/chartsheet.py +107 -0
  159. package/python/vendor/openpyxl/chartsheet/custom.py +61 -0
  160. package/python/vendor/openpyxl/chartsheet/properties.py +28 -0
  161. package/python/vendor/openpyxl/chartsheet/protection.py +41 -0
  162. package/python/vendor/openpyxl/chartsheet/publish.py +58 -0
  163. package/python/vendor/openpyxl/chartsheet/relation.py +97 -0
  164. package/python/vendor/openpyxl/chartsheet/views.py +51 -0
  165. package/python/vendor/openpyxl/comments/__init__.py +4 -0
  166. package/python/vendor/openpyxl/comments/author.py +21 -0
  167. package/python/vendor/openpyxl/comments/comment_sheet.py +211 -0
  168. package/python/vendor/openpyxl/comments/comments.py +62 -0
  169. package/python/vendor/openpyxl/comments/shape_writer.py +112 -0
  170. package/python/vendor/openpyxl/compat/__init__.py +54 -0
  171. package/python/vendor/openpyxl/compat/abc.py +8 -0
  172. package/python/vendor/openpyxl/compat/numbers.py +43 -0
  173. package/python/vendor/openpyxl/compat/product.py +17 -0
  174. package/python/vendor/openpyxl/compat/singleton.py +40 -0
  175. package/python/vendor/openpyxl/compat/strings.py +25 -0
  176. package/python/vendor/openpyxl/descriptors/__init__.py +58 -0
  177. package/python/vendor/openpyxl/descriptors/base.py +272 -0
  178. package/python/vendor/openpyxl/descriptors/container.py +41 -0
  179. package/python/vendor/openpyxl/descriptors/excel.py +112 -0
  180. package/python/vendor/openpyxl/descriptors/namespace.py +12 -0
  181. package/python/vendor/openpyxl/descriptors/nested.py +129 -0
  182. package/python/vendor/openpyxl/descriptors/sequence.py +136 -0
  183. package/python/vendor/openpyxl/descriptors/serialisable.py +240 -0
  184. package/python/vendor/openpyxl/descriptors/slots.py +18 -0
  185. package/python/vendor/openpyxl/drawing/__init__.py +4 -0
  186. package/python/vendor/openpyxl/drawing/colors.py +435 -0
  187. package/python/vendor/openpyxl/drawing/connector.py +144 -0
  188. package/python/vendor/openpyxl/drawing/drawing.py +92 -0
  189. package/python/vendor/openpyxl/drawing/effect.py +407 -0
  190. package/python/vendor/openpyxl/drawing/fill.py +425 -0
  191. package/python/vendor/openpyxl/drawing/geometry.py +584 -0
  192. package/python/vendor/openpyxl/drawing/graphic.py +177 -0
  193. package/python/vendor/openpyxl/drawing/image.py +65 -0
  194. package/python/vendor/openpyxl/drawing/line.py +144 -0
  195. package/python/vendor/openpyxl/drawing/picture.py +144 -0
  196. package/python/vendor/openpyxl/drawing/properties.py +174 -0
  197. package/python/vendor/openpyxl/drawing/relation.py +17 -0
  198. package/python/vendor/openpyxl/drawing/spreadsheet_drawing.py +382 -0
  199. package/python/vendor/openpyxl/drawing/text.py +717 -0
  200. package/python/vendor/openpyxl/drawing/xdr.py +33 -0
  201. package/python/vendor/openpyxl/formatting/__init__.py +3 -0
  202. package/python/vendor/openpyxl/formatting/formatting.py +114 -0
  203. package/python/vendor/openpyxl/formatting/rule.py +291 -0
  204. package/python/vendor/openpyxl/formula/__init__.py +3 -0
  205. package/python/vendor/openpyxl/formula/tokenizer.py +446 -0
  206. package/python/vendor/openpyxl/formula/translate.py +166 -0
  207. package/python/vendor/openpyxl/packaging/__init__.py +3 -0
  208. package/python/vendor/openpyxl/packaging/core.py +115 -0
  209. package/python/vendor/openpyxl/packaging/custom.py +289 -0
  210. package/python/vendor/openpyxl/packaging/extended.py +137 -0
  211. package/python/vendor/openpyxl/packaging/interface.py +56 -0
  212. package/python/vendor/openpyxl/packaging/manifest.py +194 -0
  213. package/python/vendor/openpyxl/packaging/relationship.py +158 -0
  214. package/python/vendor/openpyxl/packaging/workbook.py +185 -0
  215. package/python/vendor/openpyxl/pivot/__init__.py +1 -0
  216. package/python/vendor/openpyxl/pivot/cache.py +965 -0
  217. package/python/vendor/openpyxl/pivot/fields.py +326 -0
  218. package/python/vendor/openpyxl/pivot/record.py +111 -0
  219. package/python/vendor/openpyxl/pivot/table.py +1261 -0
  220. package/python/vendor/openpyxl/reader/__init__.py +1 -0
  221. package/python/vendor/openpyxl/reader/drawings.py +71 -0
  222. package/python/vendor/openpyxl/reader/excel.py +349 -0
  223. package/python/vendor/openpyxl/reader/strings.py +44 -0
  224. package/python/vendor/openpyxl/reader/workbook.py +133 -0
  225. package/python/vendor/openpyxl/styles/__init__.py +11 -0
  226. package/python/vendor/openpyxl/styles/alignment.py +62 -0
  227. package/python/vendor/openpyxl/styles/borders.py +103 -0
  228. package/python/vendor/openpyxl/styles/builtins.py +1397 -0
  229. package/python/vendor/openpyxl/styles/cell_style.py +206 -0
  230. package/python/vendor/openpyxl/styles/colors.py +172 -0
  231. package/python/vendor/openpyxl/styles/differential.py +95 -0
  232. package/python/vendor/openpyxl/styles/fills.py +224 -0
  233. package/python/vendor/openpyxl/styles/fonts.py +113 -0
  234. package/python/vendor/openpyxl/styles/named_styles.py +282 -0
  235. package/python/vendor/openpyxl/styles/numbers.py +200 -0
  236. package/python/vendor/openpyxl/styles/protection.py +17 -0
  237. package/python/vendor/openpyxl/styles/proxy.py +62 -0
  238. package/python/vendor/openpyxl/styles/styleable.py +151 -0
  239. package/python/vendor/openpyxl/styles/stylesheet.py +274 -0
  240. package/python/vendor/openpyxl/styles/table.py +94 -0
  241. package/python/vendor/openpyxl/utils/__init__.py +17 -0
  242. package/python/vendor/openpyxl/utils/bound_dictionary.py +26 -0
  243. package/python/vendor/openpyxl/utils/cell.py +240 -0
  244. package/python/vendor/openpyxl/utils/dataframe.py +87 -0
  245. package/python/vendor/openpyxl/utils/datetime.py +140 -0
  246. package/python/vendor/openpyxl/utils/escape.py +43 -0
  247. package/python/vendor/openpyxl/utils/exceptions.py +34 -0
  248. package/python/vendor/openpyxl/utils/formulas.py +24 -0
  249. package/python/vendor/openpyxl/utils/indexed_list.py +49 -0
  250. package/python/vendor/openpyxl/utils/inference.py +60 -0
  251. package/python/vendor/openpyxl/utils/protection.py +22 -0
  252. package/python/vendor/openpyxl/utils/units.py +108 -0
  253. package/python/vendor/openpyxl/workbook/__init__.py +4 -0
  254. package/python/vendor/openpyxl/workbook/_writer.py +197 -0
  255. package/python/vendor/openpyxl/workbook/child.py +166 -0
  256. package/python/vendor/openpyxl/workbook/defined_name.py +189 -0
  257. package/python/vendor/openpyxl/workbook/external_link/__init__.py +3 -0
  258. package/python/vendor/openpyxl/workbook/external_link/external.py +190 -0
  259. package/python/vendor/openpyxl/workbook/external_reference.py +18 -0
  260. package/python/vendor/openpyxl/workbook/function_group.py +36 -0
  261. package/python/vendor/openpyxl/workbook/properties.py +151 -0
  262. package/python/vendor/openpyxl/workbook/protection.py +163 -0
  263. package/python/vendor/openpyxl/workbook/smart_tags.py +56 -0
  264. package/python/vendor/openpyxl/workbook/views.py +155 -0
  265. package/python/vendor/openpyxl/workbook/web.py +98 -0
  266. package/python/vendor/openpyxl/workbook/workbook.py +438 -0
  267. package/python/vendor/openpyxl/worksheet/__init__.py +1 -0
  268. package/python/vendor/openpyxl/worksheet/_read_only.py +190 -0
  269. package/python/vendor/openpyxl/worksheet/_reader.py +472 -0
  270. package/python/vendor/openpyxl/worksheet/_write_only.py +160 -0
  271. package/python/vendor/openpyxl/worksheet/_writer.py +390 -0
  272. package/python/vendor/openpyxl/worksheet/cell_range.py +512 -0
  273. package/python/vendor/openpyxl/worksheet/cell_watch.py +34 -0
  274. package/python/vendor/openpyxl/worksheet/controls.py +107 -0
  275. package/python/vendor/openpyxl/worksheet/copier.py +70 -0
  276. package/python/vendor/openpyxl/worksheet/custom.py +35 -0
  277. package/python/vendor/openpyxl/worksheet/datavalidation.py +202 -0
  278. package/python/vendor/openpyxl/worksheet/dimensions.py +306 -0
  279. package/python/vendor/openpyxl/worksheet/drawing.py +14 -0
  280. package/python/vendor/openpyxl/worksheet/errors.py +93 -0
  281. package/python/vendor/openpyxl/worksheet/filters.py +486 -0
  282. package/python/vendor/openpyxl/worksheet/formula.py +51 -0
  283. package/python/vendor/openpyxl/worksheet/header_footer.py +270 -0
  284. package/python/vendor/openpyxl/worksheet/hyperlink.py +46 -0
  285. package/python/vendor/openpyxl/worksheet/merge.py +141 -0
  286. package/python/vendor/openpyxl/worksheet/ole.py +133 -0
  287. package/python/vendor/openpyxl/worksheet/page.py +174 -0
  288. package/python/vendor/openpyxl/worksheet/pagebreak.py +94 -0
  289. package/python/vendor/openpyxl/worksheet/picture.py +8 -0
  290. package/python/vendor/openpyxl/worksheet/print_settings.py +184 -0
  291. package/python/vendor/openpyxl/worksheet/properties.py +97 -0
  292. package/python/vendor/openpyxl/worksheet/protection.py +120 -0
  293. package/python/vendor/openpyxl/worksheet/related.py +17 -0
  294. package/python/vendor/openpyxl/worksheet/scenario.py +105 -0
  295. package/python/vendor/openpyxl/worksheet/smart_tag.py +78 -0
  296. package/python/vendor/openpyxl/worksheet/table.py +385 -0
  297. package/python/vendor/openpyxl/worksheet/views.py +155 -0
  298. package/python/vendor/openpyxl/worksheet/worksheet.py +907 -0
  299. package/python/vendor/openpyxl/writer/__init__.py +1 -0
  300. package/python/vendor/openpyxl/writer/excel.py +295 -0
  301. package/python/vendor/openpyxl/writer/theme.py +291 -0
  302. package/python/vendor/openpyxl/xml/__init__.py +42 -0
  303. package/python/vendor/openpyxl/xml/constants.py +129 -0
  304. package/python/vendor/openpyxl/xml/functions.py +87 -0
  305. package/watchlist/package.json +1 -1
@@ -44,6 +44,7 @@ const datasetRefSchema = () => jsonObject({
44
44
  captured_at: { type: 'integer' },
45
45
  retention_until: { type: 'integer' },
46
46
  params_digest: { type: 'string' },
47
+ envelope: { type: 'object', additionalProperties: true },
47
48
  time_coverage: {
48
49
  type: 'object',
49
50
  properties: {
@@ -117,7 +118,7 @@ function resolveCapability(hub, value) {
117
118
  if (available.length === 0) {
118
119
  throw capabilityError('capability_catalog_empty', '当前没有任何已注册的数据能力(数据源注册没有生效)。注意:缺凭据**不会**让目录变空——同花顺能力始终在目录里,只在取数那一刻点名 FUYAO_API_KEY 失败。本工具此刻对任何名字都会失败——不要反复重试,也不要编造能力名;请把该状态回告主 Agent,必要时用 dc_status 核对 registered_capability_count / registered_topics 与 api_key。');
119
120
  }
120
- throw capabilityError('capability_unknown', `未注册的能力 "${name}"。目录按九个主题分片,下面是索引;先按 topic 取分片,再原样复制名字:\n${hub.catalogIndex()}\n不要自行编造、缩写或改写。`);
121
+ throw capabilityError('capability_unknown', `未注册的能力 "${name}"。目录按十个主题分片,下面是索引;先按 topic 取分片,再原样复制名字:\n${hub.catalogIndex()}\n不要自行编造、缩写或改写。`);
121
122
  }
122
123
  return name;
123
124
  }
@@ -126,7 +127,7 @@ function resolveCatalogTopic(hub, value) {
126
127
  if (value === undefined || value === null)
127
128
  return undefined;
128
129
  if (typeof value !== 'string') {
129
- throw capabilityError('capability_scope_invalid', `topic 必须是字符串(收到 ${Array.isArray(value) ? 'array' : typeof value})。省略 topic 取九行索引,或从索引里选一个 topic 原样传入。`);
130
+ throw capabilityError('capability_scope_invalid', `topic 必须是字符串(收到 ${Array.isArray(value) ? 'array' : typeof value})。省略 topic 取十行索引,或从索引里选一个 topic 原样传入。`);
130
131
  }
131
132
  const topic = value.trim();
132
133
  if (topic.length === 0)
@@ -135,7 +136,7 @@ function resolveCatalogTopic(hub, value) {
135
136
  const match = entries.find((entry) => entry.topic === topic);
136
137
  if (!match) {
137
138
  const available = entries.map((entry) => `${entry.topic}(${entry.label},${entry.count}条)`).join('、');
138
- throw capabilityError('capability_scope_invalid', `未知 topic "${topic}"。可用 topic:${available || '(当前目录为空)'}。请从 list_capabilities() 的索引里原样选一个 topic,再调用 list_capabilities({ "topic": "<topic>" });不要编造。需要全量就九片分别取,不要用 all。`);
139
+ throw capabilityError('capability_scope_invalid', `未知 topic "${topic}"。可用 topic:${available || '(当前目录为空)'}。请从 list_capabilities() 的索引里原样选一个 topic,再调用 list_capabilities({ "topic": "<topic>" });不要编造。需要全量就十片分别取,不要用 all。`);
139
140
  }
140
141
  return match.topic;
141
142
  }
@@ -145,7 +146,7 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
145
146
  return;
146
147
  const retryBudget = new UpstreamRetryBudget();
147
148
  const registrations = [
148
- tool('request_data', '向数据管道请求数据:宿主先按 capability+params 校验当前 session 的已验证 manifest;force_refresh=false 或省略且命中未过期、满足该来源缓存新鲜度的 Dataset 时直接返回已有 DatasetRef,不访问上游;force_refresh=true 才重新取数并生成新的不可变 Dataset(默认保留 7 天),绝不覆盖旧 Dataset。明确要现在/最新的行情快照时请用 force_refresh=true,7 天是保留期而非实时新鲜度。本工具只返回 DatasetRef(dataset_id / artifact_ref / schema / row_count / captured_at / retention_until 等元数据),绝不返回原始数据行。capability 必须是 list_capabilities 返回的短能力名(如 ticker_search / quote / history / trading_calendar),params 必须按 describe_capability({ capability }) 返回的 input_schema 填写。若返回 request_params_invalid,先重新调用 describe_capability({ capability: "<当前能力名>" }),再按 schema 修正并重试一次;不要凭记忆猜参数。可重试上游失败(限流、网络、超时、5xx)对同一 capability 最多 3 次尝试;返回 upstream_retry_exhausted 后停止重试,改用等价能力或回告主 Agent,不要用 wait_agent 等上游恢复。task_id 必须由主 Agent 在本轮委派前确定,并在所有子 Agent 与最终报告中原样复用;不要由 data_collector 自行生成。相同 capability+params 的并发请求合并为同一次执行。当前 workspace 只读或落盘失败时抛错 workspace_not_writable(绝不退化为内存假成功)。请求归属自动记为当前 delegated child session,不接收 requester_agent_id 参数。', jsonObject({
149
+ tool('request_data', '向数据管道请求数据:宿主先按 capability+params 校验当前 session 的已验证 manifest;force_refresh=false 或省略且命中未过期、满足该来源缓存新鲜度的 Dataset 时直接返回已有 DatasetRef,不访问上游;force_refresh=true 才重新取数并生成新的不可变 Dataset(默认保留 7 天),绝不覆盖旧 Dataset。明确要现在/最新的行情快照时请用 force_refresh=true,7 天是保留期而非实时新鲜度。本工具只返回 DatasetRef(dataset_id / artifact_ref / schema / row_count / captured_at / retention_until 等元数据,以及 envelope——响应根级的日期/钳制标记/计算时间等标量,若有),绝不返回原始数据行。envelope 是核对口径用的(例如 requested_date_clamped=true 表示上游把请求日夹到了最近交易日),不是行数据、不能 query。capability 必须是 list_capabilities 返回的短能力名(如 ticker_search / quote / history / trading_calendar),params 必须按 describe_capability({ capability }) 返回的 input_schema 填写。若返回 request_params_invalid,先重新调用 describe_capability({ capability: "<当前能力名>" }),再按 schema 修正并重试一次;不要凭记忆猜参数。可重试上游失败(限流、网络、超时、5xx)对同一 capability 最多 3 次尝试;返回 upstream_retry_exhausted 后停止重试,改用等价能力或回告主 Agent,不要用 wait_agent 等上游恢复。task_id 必须由主 Agent 在本轮委派前确定,并在所有子 Agent 与最终报告中原样复用;不要由 data_collector 自行生成。相同 capability+params 的并发请求合并为同一次执行。当前 workspace 只读或落盘失败时抛错 workspace_not_writable(绝不退化为内存假成功)。请求归属自动记为当前 delegated child session,不接收 requester_agent_id 参数。', jsonObject({
149
150
  capability: { type: 'string' },
150
151
  params: freeObject,
151
152
  force_refresh: { type: 'boolean' },
@@ -196,11 +197,11 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
196
197
  throw requestParamsError(error, requestedCapability) ?? error;
197
198
  }
198
199
  }),
199
- tool('list_capabilities', '发现数据能力目录。不传 topic:返回九行主题索引 `topic|中文|条数|码点|例子`,先看哪个主题包含所需能力;传 topic:返回该主题的 `capability|summary|paginated` 行。按问题需要取片,不设片数上限:复杂/跨资产问题建议第一步九片全取,单一资产按需取;同一 session 已有结果不要重复调用,多个 topic 在同一条消息里并发调用(本工具纯读、可并发)。片数是结果,不是配额;单片 <2048 是体积预算。目录刻意不含 schema;选定能力后用 describe_capability 取完整契约。request_data 的 capability 必须以目录为准,不要编造。未知 topic 返回 capability_scope_invalid 并列出可用主题。', jsonObject({
200
+ tool('list_capabilities', '发现数据能力目录。不传 topic:返回十行主题索引 `topic|中文|条数|码点|例子`,先看哪个主题包含所需能力;传 topic:返回该主题的 `capability|summary|paginated` 行。按问题需要取片,不设片数上限:复杂/跨资产问题建议第一步十片全取,单一资产按需取;同一 session 已有结果不要重复调用,多个 topic 在同一条消息里并发调用(本工具纯读、可并发)。片数是结果,不是配额;单片 <2048 是体积预算。目录刻意不含 schema;选定能力后用 describe_capability 取完整契约。request_data 的 capability 必须以目录为准,不要编造。未知 topic 返回 capability_scope_invalid 并列出可用主题。', jsonObject({
200
201
  topic: {
201
202
  type: 'string',
202
203
  enum: [...CATALOG_TOPICS],
203
- description: '可选。省略返回九行主题索引;给出 topic 返回该主题的能力目录。一次只取需要的主题,不要拉全部。',
204
+ description: '可选。省略返回十行主题索引;给出 topic 返回该主题的能力目录。一次只取需要的主题,不要拉全部。',
204
205
  },
205
206
  }), { type: 'string' }, async (args, exec) => {
206
207
  authorizedSession(ctx, exec, 'list_capabilities', DATA_COLLECTION_PRESET_IDS);
@@ -210,7 +211,7 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
210
211
  const topic = resolveCatalogTopic(hub, args.topic);
211
212
  return topic === undefined ? hub.catalogIndex() : hub.capabilityDirectory(topic);
212
213
  }, { concurrencySafe: true }),
213
- tool('describe_capability', '读取**一个**能力的完整契约:description(单位、null 语义、时间与分页口径)、input_schema(params 的取值与约束)、output_fields(返回字段的逐行字典 `路径:类型[:说明]`,类型后缀 `?` 为可为 null、`[].` 为数组元素的字段)与 paginated。request_data 的 params 必须按这里返回的 input_schema 填写;request_data 若返回 request_params_invalid,应回到这里重新读取后再重试。一个能力描述一次即可:结果已在本 session 历史里,重复描述同一个能力只会白占上下文;需要几个能力就**在同一条消息里一次发出多个调用**(本工具是纯读、可并发执行,框架会把它们放进并发池、在同一个下一步一起返回),但一次仍只传**一个**名字,不要用逗号把多个名字塞进一条调用。错误按 code 引导:capability_required(没给名字,先 list_capabilities())、capability_invalid(不是字符串/超长/含逗号,改为目录中的单个名字)、capability_catalog_empty(数据源未注册,别重试,回告主 Agent)、capability_unknown(名字不存在,错误里回九行索引,按 topic 取分片后原样复制)。', jsonObject({ capability: { type: 'string' } }, ['capability']), jsonObject({
214
+ tool('describe_capability', '读取**一个**能力的完整契约:description(单位、null 语义、时间与分页口径)、input_schema(params 的取值与约束)、output_fields(返回字段的逐行字典 `路径:类型[:说明]`,类型后缀 `?` 为可为 null、`[].` 为数组元素的字段)与 paginated。request_data 的 params 必须按这里返回的 input_schema 填写;request_data 若返回 request_params_invalid,应回到这里重新读取后再重试。一个能力描述一次即可:结果已在本 session 历史里,重复描述同一个能力只会白占上下文;需要几个能力就**在同一条消息里一次发出多个调用**(本工具是纯读、可并发执行,框架会把它们放进并发池、在同一个下一步一起返回),但一次仍只传**一个**名字,不要用逗号把多个名字塞进一条调用。错误按 code 引导:capability_required(没给名字,先 list_capabilities())、capability_invalid(不是字符串/超长/含逗号,改为目录中的单个名字)、capability_catalog_empty(数据源未注册,别重试,回告主 Agent)、capability_unknown(名字不存在,错误里回十行索引,按 topic 取分片后原样复制)。', jsonObject({ capability: { type: 'string' } }, ['capability']), jsonObject({
214
215
  capability: { type: 'string' },
215
216
  summary: { type: 'string' },
216
217
  paginated: { type: 'boolean' },
@@ -226,7 +227,7 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
226
227
  return detail;
227
228
  }, { concurrencySafe: true }),
228
229
  ...(diagnostics ? [
229
- tool('dc_status', '诊断工具:返回数据管道运行状态 —— at/call 为本次真实执行的时间戳与计数(防伪)、api_key 为**本次调用现取**的凭据解析结果(present/source,不含密钥值)、registered_capability_count 与 registered_topics 为当前注册规模(九片 topic/label/count 汇总;**不返回全部能力名**,名字从 `list_capabilities` 分片取)、agent_tool_policy 为工具面收敛的现场记录(preset_id / root / outcome / allowed / denied / failed:`outcome=restricted` 是组合期那次减名字的账,`guard-denied` 是一次调用真的被调用级闸门拦下(`ocr` 的 url 形态、`write` / `edit`、角色的 `interrupt_agent`),`not-capital` / `skipped` / `unavailable` / `pending` 是四种没生效的原因;`root=true` 是用户手开出来的会话。工具面本身由该 preset 挂的工具行决定,allowed 恒为空。排查"某个 Agent 为什么看得见、或为什么用不了某颗工具"用)、session_identity 为最近的工具授权判据现场(tool / via=preset|topology / preset_id / allowed;`via:"topology"` 表示 registry 读不到身份、回落到"必须是被委派的子会话"这一旧判据)。数据源注册不依赖 key:api_key.present=false 时同花顺能力仍在目录里,但每次取数会点名 FUYAO_API_KEY 失败。排障时优先调用。', jsonObject(), jsonObject({
230
+ tool('dc_status', '诊断工具:返回数据管道运行状态 —— at/call 为本次真实执行的时间戳与计数(防伪)、api_key 为**本次调用现取**的凭据解析结果(present/source,不含密钥值)、registered_capability_count 与 registered_topics 为当前注册规模(十片 topic/label/count 汇总;**不返回全部能力名**,名字从 `list_capabilities` 分片取)、agent_tool_policy 为工具面收敛的现场记录(preset_id / root / outcome / allowed / denied / failed:`outcome=restricted` 是组合期那次减名字的账,`guard-denied` 是一次调用真的被调用级闸门拦下(`ocr` 的 url 形态、`write` / `edit`、角色的 `interrupt_agent`),`not-capital` / `skipped` / `unavailable` / `pending` 是四种没生效的原因;`root=true` 是用户手开出来的会话。工具面本身由该 preset 挂的工具行决定,allowed 恒为空。排查"某个 Agent 为什么看得见、或为什么用不了某颗工具"用)、session_identity 为最近的工具授权判据现场(tool / via=preset|topology / preset_id / allowed;`via:"topology"` 表示 registry 读不到身份、回落到"必须是被委派的子会话"这一旧判据)。数据源注册不依赖 key:api_key.present=false 时同花顺能力仍在目录里,但每次取数会点名 FUYAO_API_KEY 失败。排障时优先调用。', jsonObject(), jsonObject({
230
231
  at: { type: 'integer' },
231
232
  call: { type: 'integer' },
232
233
  api_key: jsonObject({ present: { type: 'boolean' }, source: { oneOf: [{ type: 'string' }, { type: 'null' }] }, error: { oneOf: [{ type: 'string' }, { type: 'null' }] } }, ['present']),
@@ -292,5 +293,5 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
292
293
  export const DATASET_REF_FIELDS = [
293
294
  'dataset_id', 'task_id', 'session_id', 'artifact_ref', 'format',
294
295
  'capability', 'source_label', 'schema', 'row_count', 'captured_at',
295
- 'retention_until', 'params_digest', 'time_coverage',
296
+ 'retention_until', 'params_digest', 'time_coverage', 'envelope',
296
297
  ];
@@ -1,4 +1,4 @@
1
- export type PythonRuntimeErrorCode = 'unsupported-platform' | 'manifest-invalid' | 'runtime-not-ready' | 'runtime-locked' | 'pnpm-missing' | 'network' | 'not-found' | 'disk-space' | 'permission' | 'probe-failed' | 'timeout' | 'cancelled' | 'pack-invalid' | 'busy' | 'invalid-request' | 'unknown';
1
+ export type PythonRuntimeErrorCode = 'unsupported-platform' | 'manifest-invalid' | 'runtime-not-ready' | 'data-runtime-not-ready' | 'runtime-locked' | 'pnpm-missing' | 'network' | 'not-found' | 'disk-space' | 'permission' | 'probe-failed' | 'script-failed' | 'timeout' | 'cancelled' | 'pack-invalid' | 'busy' | 'invalid-request' | 'unknown';
2
2
  export declare class PythonRuntimeError extends Error {
3
3
  readonly code: PythonRuntimeErrorCode;
4
4
  readonly diagnostics?: string;
@@ -2,6 +2,7 @@ const MESSAGES = {
2
2
  'unsupported-platform': '当前平台不在 Python 运行时的支持矩阵内。',
3
3
  'manifest-invalid': 'Python 运行时 manifest 不可读或字段不合法。',
4
4
  'runtime-not-ready': '分析环境尚未准备;请先在设置页准备,或运行 python-runtime CLI。',
5
+ 'data-runtime-not-ready': '分析环境(base pack)尚未安装;请在插件设置 → 分析环境里安装 base pack 后重试。',
5
6
  'runtime-locked': '另一个进程正在安装 Python 运行时,请稍后重试。',
6
7
  'pnpm-missing': '找不到可用的 pnpm;DSH 的包管理器不可用,无法自动安装运行时。',
7
8
  'network': '无法连接 npm registry;请检查网络/代理,或使用离线运行时包。',
@@ -9,6 +10,7 @@ const MESSAGES = {
9
10
  'disk-space': '磁盘空间不足,无法安装 Python 运行时。',
10
11
  'permission': '没有权限写入或执行 Python 运行时缓存目录。',
11
12
  'probe-failed': 'Python 运行时自检失败。',
13
+ 'script-failed': 'Python 数据脚本执行失败。',
12
14
  timeout: 'Python 运行时操作超时。',
13
15
  cancelled: 'Python 运行时操作已取消。',
14
16
  'pack-invalid': '运行时包内容与 manifest 不一致。',
@@ -1,6 +1,6 @@
1
1
  import { type PlatformFacts } from './platform.js';
2
2
  import { runPnpm, type PnpmInvocation } from './pnpm.js';
3
- import { probePython } from './probe.js';
3
+ import { probePython, type WorkerProcessRunner } from './probe.js';
4
4
  import type { PackName, PrepareJob, ProbeReport, RuntimeHandle, RuntimeManifest, RuntimeStatus } from './types.js';
5
5
  interface LoggerLike {
6
6
  info?(message: string): void;
@@ -20,6 +20,20 @@ export interface PythonRuntimeManagerOptions {
20
20
  now?: () => Date;
21
21
  runPnpm?: typeof runPnpm;
22
22
  probePython?: typeof probePython;
23
+ runWorkerProcess?: WorkerProcessRunner;
24
+ }
25
+ export interface RunDataScriptOptions {
26
+ /** Script id: the file name without `.py` under `python/scripts/`. */
27
+ script: string;
28
+ /** Written to the run directory as `input.json`; scripts validate it themselves. */
29
+ params?: Record<string, unknown>;
30
+ timeoutMs?: number;
31
+ signal?: AbortSignal;
32
+ }
33
+ export interface DataScriptResult {
34
+ rows: unknown[];
35
+ pythonVersion: string;
36
+ durationMs: number;
23
37
  }
24
38
  export declare class PythonRuntimeManager {
25
39
  readonly manifest: RuntimeManifest;
@@ -35,6 +49,7 @@ export declare class PythonRuntimeManager {
35
49
  private readonly now;
36
50
  private readonly runPnpm;
37
51
  private readonly probePython;
52
+ private readonly runWorker;
38
53
  private readonly jobs;
39
54
  private activeJobId?;
40
55
  private pnpmInvocation?;
@@ -54,6 +69,18 @@ export declare class PythonRuntimeManager {
54
69
  private validateProbe;
55
70
  /** Re-run the self-check against the installed packs; `parquet` also verifies pyarrow. */
56
71
  verify(packs?: unknown): Promise<ProbeReport>;
72
+ /** Base pack must be installed and intact; a missing runtime is a call-time failure, never a boot gate. */
73
+ private resolveDataRuntime;
74
+ /** Quote a JSON value for a script's `input.json`: no `undefined`, no non-finite numbers. */
75
+ private static serializeParams;
76
+ /**
77
+ * Run one fixed repo data script in an isolated run directory and return the rows it wrote.
78
+ *
79
+ * The child only ever sees a copied repo script and `input.json`; its whole working set lives under
80
+ * `<cacheRoot>/data-runs/<script>-<uuid>/` and is removed afterwards. `python/vendor` rides along as
81
+ * an extra `--site-packages` entry so no pip/venv/pack is involved.
82
+ */
83
+ runDataScript(options: RunDataScriptOptions): Promise<DataScriptResult>;
57
84
  resolve(packs?: unknown): Promise<RuntimeHandle>;
58
85
  remove(pack: PackName): Promise<void>;
59
86
  dispose(): Promise<void>;
@@ -1,15 +1,43 @@
1
- import { chmod, mkdir, rename, rm, stat } from 'node:fs/promises';
1
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { join, resolve } from 'node:path';
4
- import { pathToFileURL } from 'node:url';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
5
  import { PythonRuntimeError, isPythonRuntimeError, messageOf } from './errors.js';
6
6
  import { withInstallLock } from './lock.js';
7
7
  import { normalizePackNames, packTarget } from './manifest.js';
8
8
  import { availableBytes, directoryBytes, exists, isInside, lockRoot, packRoot, readJson, readyFileShape, readyPath, removeStaleStaging, resolveDshHome, runtimeRoot, safeRelative, stagingRoot, storeRoot, writeJsonAtomic, } from './paths.js';
9
- import { findPnpmCli } from './platform.js';
9
+ import { findPnpmCli, pythonFlags } from './platform.js';
10
10
  import { classifyPnpmFailure, installArgs, runPnpm, writeInstallProject } from './pnpm.js';
11
- import { probePython } from './probe.js';
11
+ import { probePython, runWorkerProcess } from './probe.js';
12
+ import { pythonChildEnv } from './child-env.js';
12
13
  const PACK_ORDER = ['base', 'parquet'];
14
+ /** Fixed data scripts live in the repo (never model-supplied code); ids map 1:1 to `python/scripts/<id>.py`. */
15
+ const DATA_SCRIPT_DIR = fileURLToPath(new URL('../../python/scripts', import.meta.url));
16
+ /** Pure-Python packages for those scripts; absolute so the child never depends on cwd. */
17
+ const PYTHON_VENDOR_DIR = fileURLToPath(new URL('../../python/vendor', import.meta.url));
18
+ const DATA_SCRIPT_ID = /^[a-z0-9_]+$/u;
19
+ const DATA_RUN_DIR = 'data-runs';
20
+ const DIAGNOSTIC_TAIL_CHARS = 2_000;
21
+ function recordOf(value) {
22
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
23
+ }
24
+ function diagnosticTail(...values) {
25
+ const text = values.map((value) => value?.trim() ?? '').filter((value) => value !== '').join('\n');
26
+ if (text === '')
27
+ return undefined;
28
+ return text.length <= DIAGNOSTIC_TAIL_CHARS ? text : `…${text.slice(-DIAGNOSTIC_TAIL_CHARS)}`;
29
+ }
30
+ /** Scripts print one concise stderr line; it beats the worker's generic "analysis.py exited with N". */
31
+ function lastStderrLine(value) {
32
+ const line = (value ?? '').split(/\r?\n/u).map((item) => item.trim()).filter((item) => item !== '').at(-1);
33
+ if (line === undefined)
34
+ return undefined;
35
+ return line.length <= 500 ? line : `…${line.slice(-500)}`;
36
+ }
37
+ function failureDiagnostics(worker, failure) {
38
+ const traceback = typeof failure?.traceback === 'string' ? failure.traceback : undefined;
39
+ return diagnosticTail(worker.stderr, worker.stdout, traceback);
40
+ }
13
41
  function nowIso(now) {
14
42
  return now().toISOString();
15
43
  }
@@ -49,6 +77,7 @@ export class PythonRuntimeManager {
49
77
  now;
50
78
  runPnpm;
51
79
  probePython;
80
+ runWorker;
52
81
  jobs = new Map();
53
82
  activeJobId;
54
83
  pnpmInvocation;
@@ -66,6 +95,7 @@ export class PythonRuntimeManager {
66
95
  this.now = options.now ?? (() => new Date());
67
96
  this.runPnpm = options.runPnpm ?? runPnpm;
68
97
  this.probePython = options.probePython ?? probePython;
98
+ this.runWorker = options.runWorkerProcess ?? runWorkerProcess;
69
99
  }
70
100
  targetId() {
71
101
  if (this.target.target === null || !this.target.supported) {
@@ -456,6 +486,112 @@ export class PythonRuntimeManager {
456
486
  }
457
487
  return report;
458
488
  }
489
+ /** Base pack must be installed and intact; a missing runtime is a call-time failure, never a boot gate. */
490
+ async resolveDataRuntime() {
491
+ try {
492
+ return await this.resolve(['base']);
493
+ }
494
+ catch (error) {
495
+ if (isPythonRuntimeError(error) && (error.code === 'runtime-not-ready' || error.code === 'pack-invalid' || error.code === 'unsupported-platform')) {
496
+ throw new PythonRuntimeError('data-runtime-not-ready', undefined, error.message);
497
+ }
498
+ throw error;
499
+ }
500
+ }
501
+ /** Quote a JSON value for a script's `input.json`: no `undefined`, no non-finite numbers. */
502
+ static serializeParams(params) {
503
+ return JSON.stringify(params ?? {});
504
+ }
505
+ /**
506
+ * Run one fixed repo data script in an isolated run directory and return the rows it wrote.
507
+ *
508
+ * The child only ever sees a copied repo script and `input.json`; its whole working set lives under
509
+ * `<cacheRoot>/data-runs/<script>-<uuid>/` and is removed afterwards. `python/vendor` rides along as
510
+ * an extra `--site-packages` entry so no pip/venv/pack is involved.
511
+ */
512
+ async runDataScript(options) {
513
+ const script = typeof options?.script === 'string' ? options.script : '';
514
+ if (!DATA_SCRIPT_ID.test(script)) {
515
+ throw new PythonRuntimeError('invalid-request', `固定数据脚本名不合法:${JSON.stringify(script)}`);
516
+ }
517
+ const scriptFile = `${script}.py`;
518
+ let source;
519
+ try {
520
+ source = await readFile(join(DATA_SCRIPT_DIR, scriptFile), 'utf8');
521
+ }
522
+ catch (error) {
523
+ throw new PythonRuntimeError('pack-invalid', `固定数据脚本缺失:${scriptFile}(${messageOf(error)})`);
524
+ }
525
+ const timeoutMs = options?.timeoutMs ?? this.manifest.limits.probeTimeoutMs;
526
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
527
+ throw new PythonRuntimeError('invalid-request', 'timeoutMs 必须是正整数。');
528
+ }
529
+ const signal = options?.signal;
530
+ const handle = await this.resolveDataRuntime();
531
+ const runRoot = join(this.cacheRoot, DATA_RUN_DIR);
532
+ const runDir = join(runRoot, `${script}-${randomUUID()}`);
533
+ const homeDir = join(runDir, 'home');
534
+ const tempDir = join(runDir, 'tmp');
535
+ try {
536
+ await mkdir(runRoot, { recursive: true, mode: 0o700 });
537
+ await removeStaleStaging(runRoot);
538
+ await mkdir(runDir, { recursive: true, mode: 0o700 });
539
+ await mkdir(homeDir, { recursive: true, mode: 0o700 });
540
+ await mkdir(tempDir, { recursive: true, mode: 0o700 });
541
+ await writeFile(join(runDir, scriptFile), source, { encoding: 'utf8', mode: 0o600 });
542
+ await writeFile(join(runDir, 'request.json'), JSON.stringify({ script: scriptFile, args: [] }), 'utf8');
543
+ await writeFile(join(runDir, 'input.json'), PythonRuntimeManager.serializeParams(options?.params), 'utf8');
544
+ const sitePackages = [...handle.sitePackages];
545
+ if (await exists(PYTHON_VENDOR_DIR))
546
+ sitePackages.push(PYTHON_VENDOR_DIR);
547
+ const env = pythonChildEnv({ pythonDir: dirname(handle.python), homeDir, tempDir, baseEnv: process.env });
548
+ const args = [
549
+ ...pythonFlags,
550
+ this.workerPath,
551
+ 'run',
552
+ ...sitePackages.flatMap((item) => ['--site-packages', item]),
553
+ '--run-dir',
554
+ runDir,
555
+ ];
556
+ const worker = await this.runWorker({
557
+ python: handle.python,
558
+ args,
559
+ cwd: runDir,
560
+ env,
561
+ timeoutMs,
562
+ ...(signal === undefined ? {} : { signal }),
563
+ });
564
+ if (worker.spawnError !== undefined) {
565
+ throw new PythonRuntimeError('script-failed', `启动 Python 失败:${worker.spawnError}`, diagnosticTail(worker.stderr));
566
+ }
567
+ if (worker.timedOut)
568
+ throw new PythonRuntimeError('timeout', `Python 数据脚本超时(${scriptFile})。`, diagnosticTail(worker.stderr));
569
+ if (worker.aborted)
570
+ throw new PythonRuntimeError('cancelled', undefined, diagnosticTail(worker.stderr));
571
+ const executed = recordOf(await readJson(join(runDir, 'result.json')));
572
+ if (executed === undefined) {
573
+ throw new PythonRuntimeError('script-failed', `数据脚本没有写出 result.json(退出码 ${String(worker.code)})。`, diagnosticTail(worker.stderr || worker.stdout));
574
+ }
575
+ const failure = recordOf(executed.error);
576
+ if (executed.ok !== true) {
577
+ const workerMessage = typeof failure?.message === 'string' && failure.message.trim() !== '' ? failure.message.trim() : undefined;
578
+ const message = lastStderrLine(worker.stderr) ?? workerMessage ?? `数据脚本退出码 ${String(worker.code)}。`;
579
+ throw new PythonRuntimeError('script-failed', message, failureDiagnostics(worker, failure));
580
+ }
581
+ const output = recordOf(await readJson(join(runDir, 'out.json')));
582
+ if (output === undefined || !Array.isArray(output.rows)) {
583
+ throw new PythonRuntimeError('script-failed', `数据脚本没有写出 out.json({"rows":[...]})。`, diagnosticTail(worker.stderr));
584
+ }
585
+ return {
586
+ rows: output.rows,
587
+ pythonVersion: typeof executed.python === 'string' ? executed.python : handle.pythonVersion,
588
+ durationMs: typeof executed.durationMs === 'number' && Number.isFinite(executed.durationMs) ? executed.durationMs : 0,
589
+ };
590
+ }
591
+ finally {
592
+ await rm(runDir, { recursive: true, force: true }).catch(() => undefined);
593
+ }
594
+ }
459
595
  async resolve(packs = ['base']) {
460
596
  const names = normalizePackNames(packs);
461
597
  const target = this.targetId();
@@ -9,5 +9,29 @@ export interface ProbeOptions {
9
9
  signal?: AbortSignal;
10
10
  env?: Record<string, string | undefined>;
11
11
  }
12
+ export interface WorkerProcessOptions {
13
+ python: string;
14
+ /** Full argv after the interpreter path: worker script, subcommand and its flags. */
15
+ args: string[];
16
+ cwd: string;
17
+ env: Record<string, string>;
18
+ timeoutMs: number;
19
+ signal?: AbortSignal;
20
+ }
21
+ export interface WorkerProcessResult {
22
+ code: number | null;
23
+ stdout: string;
24
+ stderr: string;
25
+ timedOut: boolean;
26
+ aborted: boolean;
27
+ /** Set when the child could not be started at all; no exit code exists in that case. */
28
+ spawnError?: string;
29
+ }
30
+ export type WorkerProcessRunner = (options: WorkerProcessOptions) => Promise<WorkerProcessResult>;
31
+ /**
32
+ * Spawn the private interpreter once. Timeout kills the whole child tree, abort behaves the same
33
+ * without becoming an error here: callers map the flags to their own `timeout` / `cancelled` codes.
34
+ */
35
+ export declare function runWorkerProcess(options: WorkerProcessOptions): Promise<WorkerProcessResult>;
12
36
  /** Run the private interpreter once and require its self-check JSON. */
13
37
  export declare function probePython(options: ProbeOptions): Promise<ProbeReport>;
@@ -3,6 +3,54 @@ import { mkdir } from 'node:fs/promises';
3
3
  import { PythonRuntimeError } from './errors.js';
4
4
  import { pythonChildEnv } from './child-env.js';
5
5
  import { detachedChild, killTree, pythonFlags } from './platform.js';
6
+ /** Tail kept per stream; probes and scripts only ever surface the end of a traceback. */
7
+ const OUTPUT_LIMIT = 64 * 1024;
8
+ /**
9
+ * Spawn the private interpreter once. Timeout kills the whole child tree, abort behaves the same
10
+ * without becoming an error here: callers map the flags to their own `timeout` / `cancelled` codes.
11
+ */
12
+ export async function runWorkerProcess(options) {
13
+ return await new Promise((resolvePromise) => {
14
+ let stdout = '';
15
+ let stderr = '';
16
+ let timedOut = false;
17
+ let settled = false;
18
+ const child = spawn(options.python, options.args, {
19
+ cwd: options.cwd,
20
+ env: options.env,
21
+ stdio: ['ignore', 'pipe', 'pipe'],
22
+ windowsHide: true,
23
+ detached: detachedChild,
24
+ });
25
+ const timer = setTimeout(() => {
26
+ timedOut = true;
27
+ void killTree(child.pid, child, 'SIGTERM');
28
+ setTimeout(() => { void killTree(child.pid, child, 'SIGKILL'); }, 2_000).unref?.();
29
+ }, options.timeoutMs);
30
+ timer.unref?.();
31
+ const abort = () => { void killTree(child.pid, child, 'SIGTERM'); };
32
+ options.signal?.addEventListener('abort', abort, { once: true });
33
+ const finish = (code) => {
34
+ if (settled)
35
+ return;
36
+ settled = true;
37
+ clearTimeout(timer);
38
+ options.signal?.removeEventListener('abort', abort);
39
+ resolvePromise({ code, stdout, stderr, timedOut, aborted: options.signal?.aborted === true });
40
+ };
41
+ child.stdout?.on('data', (chunk) => { stdout = (stdout + chunk.toString('utf8')).slice(-OUTPUT_LIMIT); });
42
+ child.stderr?.on('data', (chunk) => { stderr = (stderr + chunk.toString('utf8')).slice(-OUTPUT_LIMIT); });
43
+ child.once('error', (error) => {
44
+ if (settled)
45
+ return;
46
+ settled = true;
47
+ clearTimeout(timer);
48
+ options.signal?.removeEventListener('abort', abort);
49
+ resolvePromise({ code: null, stdout, stderr, timedOut, aborted: options.signal?.aborted === true, spawnError: String(error) });
50
+ });
51
+ child.once('close', (code) => finish(code));
52
+ });
53
+ }
6
54
  function parseReport(output) {
7
55
  const line = output.split(/\r?\n/u).map((item) => item.trim()).filter(Boolean).at(-1);
8
56
  if (line === undefined)
@@ -47,55 +95,23 @@ export async function probePython(options) {
47
95
  'probe',
48
96
  ...options.sitePackages.flatMap((path) => ['--site-packages', path]),
49
97
  ];
50
- return await new Promise((resolvePromise, reject) => {
51
- let stdout = '';
52
- let stderr = '';
53
- let timedOut = false;
54
- let settled = false;
55
- const child = spawn(options.python, args, {
56
- cwd: options.tempDir,
57
- env,
58
- stdio: ['ignore', 'pipe', 'pipe'],
59
- windowsHide: true,
60
- detached: detachedChild,
61
- });
62
- const timer = setTimeout(() => {
63
- timedOut = true;
64
- void killTree(child.pid, child, 'SIGTERM');
65
- setTimeout(() => { void killTree(child.pid, child, 'SIGKILL'); }, 2_000).unref?.();
66
- }, options.timeoutMs);
67
- timer.unref?.();
68
- const abort = () => { void killTree(child.pid, child, 'SIGTERM'); };
69
- options.signal?.addEventListener('abort', abort, { once: true });
70
- const finish = (code) => {
71
- if (settled)
72
- return;
73
- settled = true;
74
- clearTimeout(timer);
75
- options.signal?.removeEventListener('abort', abort);
76
- if (timedOut)
77
- return reject(new PythonRuntimeError('timeout', 'Python probe 超时。', stderr));
78
- if (options.signal?.aborted === true)
79
- return reject(new PythonRuntimeError('cancelled', undefined, stderr));
80
- if (code !== 0)
81
- return reject(new PythonRuntimeError('probe-failed', `Python probe 退出码 ${String(code)}。`, stderr || stdout));
82
- try {
83
- resolvePromise(parseReport(stdout));
84
- }
85
- catch (error) {
86
- reject(error);
87
- }
88
- };
89
- child.stdout?.on('data', (chunk) => { stdout = (stdout + chunk.toString('utf8')).slice(-64 * 1024); });
90
- child.stderr?.on('data', (chunk) => { stderr = (stderr + chunk.toString('utf8')).slice(-64 * 1024); });
91
- child.once('error', (error) => {
92
- if (settled)
93
- return;
94
- settled = true;
95
- clearTimeout(timer);
96
- options.signal?.removeEventListener('abort', abort);
97
- reject(new PythonRuntimeError('probe-failed', `启动 Python 失败:${String(error)}`));
98
- });
99
- child.once('close', (code) => finish(code));
98
+ const result = await runWorkerProcess({
99
+ python: options.python,
100
+ args,
101
+ cwd: options.tempDir,
102
+ env,
103
+ timeoutMs: options.timeoutMs,
104
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
100
105
  });
106
+ if (result.spawnError !== undefined) {
107
+ throw new PythonRuntimeError('probe-failed', `启动 Python 失败:${result.spawnError}`);
108
+ }
109
+ if (result.timedOut)
110
+ throw new PythonRuntimeError('timeout', 'Python probe 超时。', result.stderr);
111
+ if (result.aborted)
112
+ throw new PythonRuntimeError('cancelled', undefined, result.stderr);
113
+ if (result.code !== 0) {
114
+ throw new PythonRuntimeError('probe-failed', `Python probe 退出码 ${String(result.code)}。`, result.stderr || result.stdout);
115
+ }
116
+ return parseReport(result.stdout);
101
117
  }
@@ -0,0 +1,4 @@
1
+ /** 中证指数官网 csindex-home JSON:指数 PE(TTM) 日序列。官网 JSON 没有 PB/静态 PE/股息率,
2
+ * 那些只在 oss-ch 的 {code}indicator.xls 里,本仓无 xls 解析依赖,所以这一能力只承诺 pe_ttm。 */
3
+ import type { DataSource } from '../data-collector/hub.js';
4
+ export declare function createCsindexSources(): DataSource[];