@harrylabsj/kiwi 0.12.31 → 0.12.33

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 (467) hide show
  1. package/README.md +8 -0
  2. package/dist/a2a/inquiry-nonce-store.d.ts +12 -1
  3. package/dist/a2a/inquiry-nonce-store.js +49 -17
  4. package/dist/a2a/inquiry-nonce-store.js.map +1 -1
  5. package/dist/a2a/negotiate.d.ts +30 -1
  6. package/dist/a2a/negotiate.js +121 -32
  7. package/dist/a2a/negotiate.js.map +1 -1
  8. package/dist/a2a/node.d.ts +4 -0
  9. package/dist/a2a/node.js +182 -4
  10. package/dist/a2a/node.js.map +1 -1
  11. package/dist/a2a/open-inquiry-session.d.ts +1 -0
  12. package/dist/a2a/open-inquiry-session.js +3 -1
  13. package/dist/a2a/open-inquiry-session.js.map +1 -1
  14. package/dist/a2a/open-inquiry-verifier.js +2 -2
  15. package/dist/a2a/open-inquiry-verifier.js.map +1 -1
  16. package/dist/a2a/reception/agent-runtime.d.ts +32 -1
  17. package/dist/a2a/reception/agent-runtime.js +420 -11
  18. package/dist/a2a/reception/agent-runtime.js.map +1 -1
  19. package/dist/a2a/reception/customer-memory-tools.d.ts +73 -0
  20. package/dist/a2a/reception/customer-memory-tools.js +17 -0
  21. package/dist/a2a/reception/customer-memory-tools.js.map +1 -0
  22. package/dist/a2a/reception/engine.d.ts +12 -0
  23. package/dist/a2a/reception/engine.js +42 -1
  24. package/dist/a2a/reception/engine.js.map +1 -1
  25. package/dist/a2a/reception/publish.d.ts +14 -1
  26. package/dist/a2a/reception/publish.js +62 -1
  27. package/dist/a2a/reception/publish.js.map +1 -1
  28. package/dist/a2a/reception/question-spec.d.ts +91 -0
  29. package/dist/a2a/reception/question-spec.js +260 -0
  30. package/dist/a2a/reception/question-spec.js.map +1 -0
  31. package/dist/a2a/reception/reply-outbox.d.ts +6 -0
  32. package/dist/a2a/reception/reply-outbox.js +44 -0
  33. package/dist/a2a/reception/reply-outbox.js.map +1 -1
  34. package/dist/a2a/reception/responder.d.ts +13 -1
  35. package/dist/a2a/reception/responder.js +26 -3
  36. package/dist/a2a/reception/responder.js.map +1 -1
  37. package/dist/a2a/reception/skill-catalog.d.ts +72 -0
  38. package/dist/a2a/reception/skill-catalog.js +85 -0
  39. package/dist/a2a/reception/skill-catalog.js.map +1 -0
  40. package/dist/a2a/reception/skill-contract.d.ts +70 -0
  41. package/dist/a2a/reception/skill-contract.js +183 -0
  42. package/dist/a2a/reception/skill-contract.js.map +1 -0
  43. package/dist/a2a/reception/types.d.ts +12 -0
  44. package/dist/a2a/server/customer-identity-gateway.d.ts +111 -0
  45. package/dist/a2a/server/customer-identity-gateway.js +441 -0
  46. package/dist/a2a/server/customer-identity-gateway.js.map +1 -0
  47. package/dist/a2a/server/errors.d.ts +4 -3
  48. package/dist/a2a/server/errors.js +10 -2
  49. package/dist/a2a/server/errors.js.map +1 -1
  50. package/dist/a2a/server/merchant-handler.d.ts +75 -1
  51. package/dist/a2a/server/merchant-handler.js +676 -86
  52. package/dist/a2a/server/merchant-handler.js.map +1 -1
  53. package/dist/a2a/server/merchant-procurement.d.ts +90 -0
  54. package/dist/a2a/server/merchant-procurement.js +75 -0
  55. package/dist/a2a/server/merchant-procurement.js.map +1 -0
  56. package/dist/a2a/server/merchant-product-facts.d.ts +2 -0
  57. package/dist/a2a/server/merchant-product-facts.js.map +1 -1
  58. package/dist/a2a/server/negotiation-approvals.d.ts +11 -0
  59. package/dist/a2a/server/negotiation-approvals.js +43 -0
  60. package/dist/a2a/server/negotiation-approvals.js.map +1 -1
  61. package/dist/a2a/server/pipeline.js +78 -30
  62. package/dist/a2a/server/pipeline.js.map +1 -1
  63. package/dist/a2a/server/server.js +4 -3
  64. package/dist/a2a/server/server.js.map +1 -1
  65. package/dist/a2a/server/types.d.ts +4 -1
  66. package/dist/a2a/unit-alias.d.ts +3 -3
  67. package/dist/a2a/unit-alias.js +9 -5
  68. package/dist/a2a/unit-alias.js.map +1 -1
  69. package/dist/agent/alipay-native-view.d.ts +27 -0
  70. package/dist/agent/alipay-native-view.js +113 -0
  71. package/dist/agent/alipay-native-view.js.map +1 -0
  72. package/dist/agent/buyer/buyer-tools.d.ts +20 -0
  73. package/dist/agent/buyer/buyer-tools.js +241 -48
  74. package/dist/agent/buyer/buyer-tools.js.map +1 -1
  75. package/dist/agent/buyer/types.d.ts +1 -1
  76. package/dist/agent/buyer/types.js.map +1 -1
  77. package/dist/agent/chat-tui.js +16 -1
  78. package/dist/agent/chat-tui.js.map +1 -1
  79. package/dist/agent/kernel-builder.d.ts +2 -0
  80. package/dist/agent/kernel-builder.js +14 -0
  81. package/dist/agent/kernel-builder.js.map +1 -1
  82. package/dist/agent/kernel.d.ts +8 -0
  83. package/dist/agent/kernel.js +67 -1
  84. package/dist/agent/kernel.js.map +1 -1
  85. package/dist/auth/merchant-sessions.d.ts +3 -0
  86. package/dist/auth/merchant-sessions.js +21 -5
  87. package/dist/auth/merchant-sessions.js.map +1 -1
  88. package/dist/buyer-core/a2a-accept-terms.d.ts +11 -0
  89. package/dist/buyer-core/a2a-accept-terms.js +28 -0
  90. package/dist/buyer-core/a2a-accept-terms.js.map +1 -0
  91. package/dist/buyer-core/a2a-knp.d.ts +7 -2
  92. package/dist/buyer-core/a2a-knp.js +8 -5
  93. package/dist/buyer-core/a2a-knp.js.map +1 -1
  94. package/dist/buyer-core/a2a-negotiator.d.ts +17 -0
  95. package/dist/buyer-core/a2a-negotiator.js +70 -26
  96. package/dist/buyer-core/a2a-negotiator.js.map +1 -1
  97. package/dist/buyer-core/a2a-quote-fetcher.d.ts +25 -15
  98. package/dist/buyer-core/a2a-quote-fetcher.js +92 -19
  99. package/dist/buyer-core/a2a-quote-fetcher.js.map +1 -1
  100. package/dist/buyer-core/a2a-quote-history.d.ts +94 -0
  101. package/dist/buyer-core/a2a-quote-history.js +149 -0
  102. package/dist/buyer-core/a2a-quote-history.js.map +1 -0
  103. package/dist/buyer-core/build-service.d.ts +19 -0
  104. package/dist/buyer-core/build-service.js +30 -1
  105. package/dist/buyer-core/build-service.js.map +1 -1
  106. package/dist/buyer-core/errors.d.ts +1 -1
  107. package/dist/buyer-core/errors.js +1 -0
  108. package/dist/buyer-core/errors.js.map +1 -1
  109. package/dist/buyer-core/merchant-index.d.ts +2 -2
  110. package/dist/buyer-core/merchant-index.js +23 -5
  111. package/dist/buyer-core/merchant-index.js.map +1 -1
  112. package/dist/buyer-core/open-inquiry-signer.d.ts +1 -0
  113. package/dist/buyer-core/open-inquiry-signer.js +5 -2
  114. package/dist/buyer-core/open-inquiry-signer.js.map +1 -1
  115. package/dist/buyer-core/procurement/cases.d.ts +441 -0
  116. package/dist/buyer-core/procurement/cases.js +457 -0
  117. package/dist/buyer-core/procurement/cases.js.map +1 -0
  118. package/dist/buyer-core/procurement/quote-comparison.d.ts +137 -0
  119. package/dist/buyer-core/procurement/quote-comparison.js +106 -0
  120. package/dist/buyer-core/procurement/quote-comparison.js.map +1 -0
  121. package/dist/buyer-core/procurement/quote-normalizer.d.ts +45 -0
  122. package/dist/buyer-core/procurement/quote-normalizer.js +153 -0
  123. package/dist/buyer-core/procurement/quote-normalizer.js.map +1 -0
  124. package/dist/buyer-core/procurement/requirements.d.ts +50 -0
  125. package/dist/buyer-core/procurement/requirements.js +43 -0
  126. package/dist/buyer-core/procurement/requirements.js.map +1 -0
  127. package/dist/buyer-core/procurement/source-observation.d.ts +57 -0
  128. package/dist/buyer-core/procurement/source-observation.js +54 -0
  129. package/dist/buyer-core/procurement/source-observation.js.map +1 -0
  130. package/dist/buyer-core/procurement/store.d.ts +21 -0
  131. package/dist/buyer-core/procurement/store.js +68 -0
  132. package/dist/buyer-core/procurement/store.js.map +1 -0
  133. package/dist/buyer-core/protocol-recovery.d.ts +10 -1
  134. package/dist/buyer-core/protocol-recovery.js +31 -6
  135. package/dist/buyer-core/protocol-recovery.js.map +1 -1
  136. package/dist/buyer-core/quote-quantity.d.ts +5 -0
  137. package/dist/buyer-core/quote-quantity.js +15 -0
  138. package/dist/buyer-core/quote-quantity.js.map +1 -0
  139. package/dist/buyer-core/service.d.ts +128 -8
  140. package/dist/buyer-core/service.js +543 -75
  141. package/dist/buyer-core/service.js.map +1 -1
  142. package/dist/buyer-core/store.d.ts +21 -0
  143. package/dist/buyer-core/store.js +62 -10
  144. package/dist/buyer-core/store.js.map +1 -1
  145. package/dist/cli.js +26 -19
  146. package/dist/cli.js.map +1 -1
  147. package/dist/cloud/alipay-collection-http.d.ts +44 -0
  148. package/dist/cloud/alipay-collection-http.js +111 -0
  149. package/dist/cloud/alipay-collection-http.js.map +1 -0
  150. package/dist/cloud/bootstrap.js +218 -19
  151. package/dist/cloud/bootstrap.js.map +1 -1
  152. package/dist/cloud/http-router.d.ts +2 -0
  153. package/dist/cloud/http-router.js +5 -0
  154. package/dist/cloud/http-router.js.map +1 -1
  155. package/dist/commerce/receipt/dispatcher.d.ts +43 -0
  156. package/dist/commerce/receipt/dispatcher.js +86 -0
  157. package/dist/commerce/receipt/dispatcher.js.map +1 -0
  158. package/dist/commerce/receipt/receipts.d.ts +147 -0
  159. package/dist/commerce/receipt/receipts.js +285 -0
  160. package/dist/commerce/receipt/receipts.js.map +1 -0
  161. package/dist/config/profile.d.ts +2 -2
  162. package/dist/discovery/catalog-source/buyer-follows.d.ts +3 -3
  163. package/dist/discovery/catalog-source/buyer-follows.js +6 -3
  164. package/dist/discovery/catalog-source/buyer-follows.js.map +1 -1
  165. package/dist/discovery/catalog-source/kiwi-record.d.ts +2 -0
  166. package/dist/discovery/catalog-source/kiwi-record.js.map +1 -1
  167. package/dist/discovery/catalog-source/kiwi-source.js +4 -0
  168. package/dist/discovery/catalog-source/kiwi-source.js.map +1 -1
  169. package/dist/handoff/alipay-collection.d.ts +23 -0
  170. package/dist/handoff/alipay-collection.js +70 -0
  171. package/dist/handoff/alipay-collection.js.map +1 -0
  172. package/dist/handoff/order-receipts.d.ts +62 -0
  173. package/dist/handoff/order-receipts.js +72 -0
  174. package/dist/handoff/order-receipts.js.map +1 -0
  175. package/dist/handoff/ucp-checkout/cart-channel.d.ts +2 -1
  176. package/dist/handoff/ucp-checkout/cart-channel.js +1 -0
  177. package/dist/handoff/ucp-checkout/cart-channel.js.map +1 -1
  178. package/dist/handoff/ucp-checkout/channel.d.ts +7 -0
  179. package/dist/handoff/ucp-checkout/channel.js +79 -10
  180. package/dist/handoff/ucp-checkout/channel.js.map +1 -1
  181. package/dist/http/cli.js +6 -0
  182. package/dist/http/cli.js.map +1 -1
  183. package/dist/http/merchant-management/api.d.ts +18 -0
  184. package/dist/http/merchant-management/api.js +752 -3
  185. package/dist/http/merchant-management/api.js.map +1 -1
  186. package/dist/http/merchant-management/draft-store.js +8 -6
  187. package/dist/http/merchant-management/draft-store.js.map +1 -1
  188. package/dist/http/merchant-management/page.d.ts +1 -0
  189. package/dist/http/merchant-management/page.js +335 -5
  190. package/dist/http/merchant-management/page.js.map +1 -1
  191. package/dist/http/server.js +9 -2
  192. package/dist/http/server.js.map +1 -1
  193. package/dist/mcp/cli.d.ts +3 -1
  194. package/dist/mcp/cli.js +18 -2
  195. package/dist/mcp/cli.js.map +1 -1
  196. package/dist/mcp/merchant-runtime-assembly.d.ts +20 -0
  197. package/dist/mcp/merchant-runtime-assembly.js +94 -11
  198. package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
  199. package/dist/mcp/merchant-server.d.ts +5 -0
  200. package/dist/mcp/merchant-server.js +12 -0
  201. package/dist/mcp/merchant-server.js.map +1 -1
  202. package/dist/mcp/procurement-tools.d.ts +10 -0
  203. package/dist/mcp/procurement-tools.js +173 -0
  204. package/dist/mcp/procurement-tools.js.map +1 -0
  205. package/dist/mcp/server.d.ts +4 -0
  206. package/dist/mcp/server.js +63 -9
  207. package/dist/mcp/server.js.map +1 -1
  208. package/dist/mcp/tools.d.ts +4 -1
  209. package/dist/mcp/tools.js +83 -28
  210. package/dist/mcp/tools.js.map +1 -1
  211. package/dist/mcp/types.d.ts +1 -0
  212. package/dist/mcp/types.js.map +1 -1
  213. package/dist/merchant/application/actor.d.ts +3 -1
  214. package/dist/merchant/application/actor.js +21 -0
  215. package/dist/merchant/application/actor.js.map +1 -1
  216. package/dist/merchant/negotiation-ops.d.ts +2 -0
  217. package/dist/merchant/negotiation-ops.js +4 -0
  218. package/dist/merchant/negotiation-ops.js.map +1 -1
  219. package/dist/merchant/weixin-channel.d.ts +68 -0
  220. package/dist/merchant/weixin-channel.js +313 -0
  221. package/dist/merchant/weixin-channel.js.map +1 -0
  222. package/dist/merchant/workbench-server.d.ts +1 -0
  223. package/dist/merchant/workbench-server.js +189 -2
  224. package/dist/merchant/workbench-server.js.map +1 -1
  225. package/dist/merchant-core/budget/background-budget.d.ts +132 -0
  226. package/dist/merchant-core/budget/background-budget.js +308 -0
  227. package/dist/merchant-core/budget/background-budget.js.map +1 -0
  228. package/dist/merchant-core/collection/alipay-store.d.ts +22 -0
  229. package/dist/merchant-core/collection/alipay-store.js +125 -0
  230. package/dist/merchant-core/collection/alipay-store.js.map +1 -0
  231. package/dist/merchant-core/commercial/calculate.js +6 -6
  232. package/dist/merchant-core/commercial/calculate.js.map +1 -1
  233. package/dist/merchant-core/context-governance/actor-context.d.ts +56 -0
  234. package/dist/merchant-core/context-governance/actor-context.js +76 -0
  235. package/dist/merchant-core/context-governance/actor-context.js.map +1 -0
  236. package/dist/merchant-core/context-governance/authority.d.ts +39 -0
  237. package/dist/merchant-core/context-governance/authority.js +28 -0
  238. package/dist/merchant-core/context-governance/authority.js.map +1 -0
  239. package/dist/merchant-core/context-governance/context-guard.d.ts +104 -0
  240. package/dist/merchant-core/context-governance/context-guard.js +194 -0
  241. package/dist/merchant-core/context-governance/context-guard.js.map +1 -0
  242. package/dist/merchant-core/context-governance/data-use-grant.d.ts +91 -0
  243. package/dist/merchant-core/context-governance/data-use-grant.js +211 -0
  244. package/dist/merchant-core/context-governance/data-use-grant.js.map +1 -0
  245. package/dist/merchant-core/context-governance/feature-flags.d.ts +32 -0
  246. package/dist/merchant-core/context-governance/feature-flags.js +83 -0
  247. package/dist/merchant-core/context-governance/feature-flags.js.map +1 -0
  248. package/dist/merchant-core/context-governance/pilot-readiness.d.ts +39 -0
  249. package/dist/merchant-core/context-governance/pilot-readiness.js +141 -0
  250. package/dist/merchant-core/context-governance/pilot-readiness.js.map +1 -0
  251. package/dist/merchant-core/context-governance/source-governance.d.ts +157 -0
  252. package/dist/merchant-core/context-governance/source-governance.js +492 -0
  253. package/dist/merchant-core/context-governance/source-governance.js.map +1 -0
  254. package/dist/merchant-core/context-governance/types.d.ts +62 -0
  255. package/dist/merchant-core/context-governance/types.js +92 -0
  256. package/dist/merchant-core/context-governance/types.js.map +1 -0
  257. package/dist/merchant-core/customer-delivery/binding.d.ts +55 -0
  258. package/dist/merchant-core/customer-delivery/binding.js +121 -0
  259. package/dist/merchant-core/customer-delivery/binding.js.map +1 -0
  260. package/dist/merchant-core/customer-delivery/channel.d.ts +75 -0
  261. package/dist/merchant-core/customer-delivery/channel.js +157 -0
  262. package/dist/merchant-core/customer-delivery/channel.js.map +1 -0
  263. package/dist/merchant-core/customer-delivery/consent-repository.d.ts +50 -0
  264. package/dist/merchant-core/customer-delivery/consent-repository.js +160 -0
  265. package/dist/merchant-core/customer-delivery/consent-repository.js.map +1 -0
  266. package/dist/merchant-core/customer-delivery/dispatcher-loop.d.ts +68 -0
  267. package/dist/merchant-core/customer-delivery/dispatcher-loop.js +132 -0
  268. package/dist/merchant-core/customer-delivery/dispatcher-loop.js.map +1 -0
  269. package/dist/merchant-core/customer-delivery/dispatcher.d.ts +118 -0
  270. package/dist/merchant-core/customer-delivery/dispatcher.js +166 -0
  271. package/dist/merchant-core/customer-delivery/dispatcher.js.map +1 -0
  272. package/dist/merchant-core/customer-delivery/email-adapter.d.ts +31 -0
  273. package/dist/merchant-core/customer-delivery/email-adapter.js +90 -0
  274. package/dist/merchant-core/customer-delivery/email-adapter.js.map +1 -0
  275. package/dist/merchant-core/customer-delivery/gate.d.ts +37 -0
  276. package/dist/merchant-core/customer-delivery/gate.js +196 -0
  277. package/dist/merchant-core/customer-delivery/gate.js.map +1 -0
  278. package/dist/merchant-core/customer-delivery/reconciliation.d.ts +13 -0
  279. package/dist/merchant-core/customer-delivery/reconciliation.js +70 -0
  280. package/dist/merchant-core/customer-delivery/reconciliation.js.map +1 -0
  281. package/dist/merchant-core/customer-delivery/repository.d.ts +55 -0
  282. package/dist/merchant-core/customer-delivery/repository.js +235 -0
  283. package/dist/merchant-core/customer-delivery/repository.js.map +1 -0
  284. package/dist/merchant-core/customer-delivery/smtp-adapter.d.ts +30 -0
  285. package/dist/merchant-core/customer-delivery/smtp-adapter.js +183 -0
  286. package/dist/merchant-core/customer-delivery/smtp-adapter.js.map +1 -0
  287. package/dist/merchant-core/customer-delivery/stream-gate.d.ts +45 -0
  288. package/dist/merchant-core/customer-delivery/stream-gate.js +123 -0
  289. package/dist/merchant-core/customer-delivery/stream-gate.js.map +1 -0
  290. package/dist/merchant-core/customer-delivery/types.d.ts +103 -0
  291. package/dist/merchant-core/customer-delivery/types.js +32 -0
  292. package/dist/merchant-core/customer-delivery/types.js.map +1 -0
  293. package/dist/merchant-core/customer-delivery/weixin-adapter.d.ts +35 -0
  294. package/dist/merchant-core/customer-delivery/weixin-adapter.js +56 -0
  295. package/dist/merchant-core/customer-delivery/weixin-adapter.js.map +1 -0
  296. package/dist/merchant-core/customer-memory/auto-identity.d.ts +43 -0
  297. package/dist/merchant-core/customer-memory/auto-identity.js +163 -0
  298. package/dist/merchant-core/customer-memory/auto-identity.js.map +1 -0
  299. package/dist/merchant-core/customer-memory/grants.d.ts +72 -0
  300. package/dist/merchant-core/customer-memory/grants.js +224 -0
  301. package/dist/merchant-core/customer-memory/grants.js.map +1 -0
  302. package/dist/merchant-core/customer-memory/history.d.ts +51 -0
  303. package/dist/merchant-core/customer-memory/history.js +252 -0
  304. package/dist/merchant-core/customer-memory/history.js.map +1 -0
  305. package/dist/merchant-core/customer-memory/identity.d.ts +66 -0
  306. package/dist/merchant-core/customer-memory/identity.js +249 -0
  307. package/dist/merchant-core/customer-memory/identity.js.map +1 -0
  308. package/dist/merchant-core/customer-memory/maintenance.d.ts +51 -0
  309. package/dist/merchant-core/customer-memory/maintenance.js +67 -0
  310. package/dist/merchant-core/customer-memory/maintenance.js.map +1 -0
  311. package/dist/merchant-core/customer-memory/memory.d.ts +119 -0
  312. package/dist/merchant-core/customer-memory/memory.js +502 -0
  313. package/dist/merchant-core/customer-memory/memory.js.map +1 -0
  314. package/dist/merchant-core/customer-memory/private-transport.d.ts +10 -0
  315. package/dist/merchant-core/customer-memory/private-transport.js +108 -0
  316. package/dist/merchant-core/customer-memory/private-transport.js.map +1 -0
  317. package/dist/merchant-core/customer-memory/quote-history.d.ts +160 -0
  318. package/dist/merchant-core/customer-memory/quote-history.js +392 -0
  319. package/dist/merchant-core/customer-memory/quote-history.js.map +1 -0
  320. package/dist/merchant-core/customer-memory/reception-provider.d.ts +69 -0
  321. package/dist/merchant-core/customer-memory/reception-provider.js +250 -0
  322. package/dist/merchant-core/customer-memory/reception-provider.js.map +1 -0
  323. package/dist/merchant-core/customer-memory/reception-writer.d.ts +19 -0
  324. package/dist/merchant-core/customer-memory/reception-writer.js +32 -0
  325. package/dist/merchant-core/customer-memory/reception-writer.js.map +1 -0
  326. package/dist/merchant-core/customer-memory/types.d.ts +111 -0
  327. package/dist/merchant-core/customer-memory/types.js +58 -0
  328. package/dist/merchant-core/customer-memory/types.js.map +1 -0
  329. package/dist/merchant-core/followup/repository.d.ts +2 -1
  330. package/dist/merchant-core/followup/repository.js +29 -23
  331. package/dist/merchant-core/followup/repository.js.map +1 -1
  332. package/dist/merchant-core/learning/evaluation-fixtures.d.ts +38 -0
  333. package/dist/merchant-core/learning/evaluation-fixtures.js +83 -0
  334. package/dist/merchant-core/learning/evaluation-fixtures.js.map +1 -0
  335. package/dist/merchant-core/learning/evaluation-suite-v1.d.ts +56 -0
  336. package/dist/merchant-core/learning/evaluation-suite-v1.js +129 -0
  337. package/dist/merchant-core/learning/evaluation-suite-v1.js.map +1 -0
  338. package/dist/merchant-core/learning/evaluation.d.ts +84 -0
  339. package/dist/merchant-core/learning/evaluation.js +581 -0
  340. package/dist/merchant-core/learning/evaluation.js.map +1 -0
  341. package/dist/merchant-core/learning/initial-skills.d.ts +36 -0
  342. package/dist/merchant-core/learning/initial-skills.js +67 -0
  343. package/dist/merchant-core/learning/initial-skills.js.map +1 -0
  344. package/dist/merchant-core/learning/precheck.d.ts +33 -0
  345. package/dist/merchant-core/learning/precheck.js +56 -0
  346. package/dist/merchant-core/learning/precheck.js.map +1 -0
  347. package/dist/merchant-core/learning/real-evaluation-runner.d.ts +52 -0
  348. package/dist/merchant-core/learning/real-evaluation-runner.js +167 -0
  349. package/dist/merchant-core/learning/real-evaluation-runner.js.map +1 -0
  350. package/dist/merchant-core/learning/reception-skill-catalog.d.ts +39 -0
  351. package/dist/merchant-core/learning/reception-skill-catalog.js +145 -0
  352. package/dist/merchant-core/learning/reception-skill-catalog.js.map +1 -0
  353. package/dist/merchant-core/learning/recovery-gateway.d.ts +27 -0
  354. package/dist/merchant-core/learning/recovery-gateway.js +106 -0
  355. package/dist/merchant-core/learning/recovery-gateway.js.map +1 -0
  356. package/dist/merchant-core/learning/repository.d.ts +130 -0
  357. package/dist/merchant-core/learning/repository.js +588 -0
  358. package/dist/merchant-core/learning/repository.js.map +1 -0
  359. package/dist/merchant-core/learning/service.d.ts +262 -0
  360. package/dist/merchant-core/learning/service.js +1498 -0
  361. package/dist/merchant-core/learning/service.js.map +1 -0
  362. package/dist/merchant-core/learning/test-dispatch-gateway.d.ts +43 -0
  363. package/dist/merchant-core/learning/test-dispatch-gateway.js +145 -0
  364. package/dist/merchant-core/learning/test-dispatch-gateway.js.map +1 -0
  365. package/dist/merchant-core/learning/types.d.ts +217 -0
  366. package/dist/merchant-core/learning/types.js +52 -0
  367. package/dist/merchant-core/learning/types.js.map +1 -0
  368. package/dist/merchant-core/migrations/ledgers.d.ts +40 -0
  369. package/dist/merchant-core/migrations/ledgers.js +824 -0
  370. package/dist/merchant-core/migrations/ledgers.js.map +1 -0
  371. package/dist/merchant-core/migrations/runner.d.ts +55 -0
  372. package/dist/merchant-core/migrations/runner.js +114 -0
  373. package/dist/merchant-core/migrations/runner.js.map +1 -0
  374. package/dist/merchant-core/operating/repository.d.ts +0 -1
  375. package/dist/merchant-core/operating/repository.js +2 -17
  376. package/dist/merchant-core/operating/repository.js.map +1 -1
  377. package/dist/merchant-core/operations-jobs/advice-runner.d.ts +63 -0
  378. package/dist/merchant-core/operations-jobs/advice-runner.js +199 -0
  379. package/dist/merchant-core/operations-jobs/advice-runner.js.map +1 -0
  380. package/dist/merchant-core/operations-jobs/pilot-evidence.d.ts +64 -0
  381. package/dist/merchant-core/operations-jobs/pilot-evidence.js +109 -0
  382. package/dist/merchant-core/operations-jobs/pilot-evidence.js.map +1 -0
  383. package/dist/merchant-core/operations-jobs/pilot-metrics.d.ts +70 -0
  384. package/dist/merchant-core/operations-jobs/pilot-metrics.js +98 -0
  385. package/dist/merchant-core/operations-jobs/pilot-metrics.js.map +1 -0
  386. package/dist/merchant-core/operations-jobs/projection.d.ts +41 -0
  387. package/dist/merchant-core/operations-jobs/projection.js +158 -0
  388. package/dist/merchant-core/operations-jobs/projection.js.map +1 -0
  389. package/dist/merchant-core/operations-jobs/scheduler.d.ts +68 -0
  390. package/dist/merchant-core/operations-jobs/scheduler.js +233 -0
  391. package/dist/merchant-core/operations-jobs/scheduler.js.map +1 -0
  392. package/dist/merchant-core/operations-jobs/service.d.ts +260 -0
  393. package/dist/merchant-core/operations-jobs/service.js +922 -0
  394. package/dist/merchant-core/operations-jobs/service.js.map +1 -0
  395. package/dist/merchant-core/opportunity/repository.d.ts +0 -1
  396. package/dist/merchant-core/opportunity/repository.js +2 -17
  397. package/dist/merchant-core/opportunity/repository.js.map +1 -1
  398. package/dist/merchant-core/ops/facade.d.ts +10 -0
  399. package/dist/merchant-core/ops/facade.js +52 -0
  400. package/dist/merchant-core/ops/facade.js.map +1 -1
  401. package/dist/merchant-core/ops/schema.d.ts +1 -1
  402. package/dist/merchant-core/ops/schema.js +119 -2
  403. package/dist/merchant-core/ops/schema.js.map +1 -1
  404. package/dist/merchant-core/ops/surface.d.ts +37 -0
  405. package/dist/merchant-core/ops/surface.js +240 -0
  406. package/dist/merchant-core/ops/surface.js.map +1 -1
  407. package/dist/merchant-core/orders/model.d.ts +1 -8
  408. package/dist/merchant-core/orders/model.js +10 -2
  409. package/dist/merchant-core/orders/model.js.map +1 -1
  410. package/dist/merchant-core/orders/repository.d.ts +0 -1
  411. package/dist/merchant-core/orders/repository.js +3 -18
  412. package/dist/merchant-core/orders/repository.js.map +1 -1
  413. package/dist/merchant-core/orders/service.js +34 -8
  414. package/dist/merchant-core/orders/service.js.map +1 -1
  415. package/dist/merchant-core/ownership/instance-ownership.d.ts +122 -0
  416. package/dist/merchant-core/ownership/instance-ownership.js +236 -0
  417. package/dist/merchant-core/ownership/instance-ownership.js.map +1 -0
  418. package/dist/merchant-core/ownership/runtime.d.ts +175 -0
  419. package/dist/merchant-core/ownership/runtime.js +422 -0
  420. package/dist/merchant-core/ownership/runtime.js.map +1 -0
  421. package/dist/merchant-core/proposal/engine.js +2 -0
  422. package/dist/merchant-core/proposal/engine.js.map +1 -1
  423. package/dist/merchant-core/proposal/publish.d.ts +0 -6
  424. package/dist/merchant-core/proposal/publish.js +37 -3
  425. package/dist/merchant-core/proposal/publish.js.map +1 -1
  426. package/dist/merchant-core/proposal/repository.d.ts +0 -7
  427. package/dist/merchant-core/proposal/repository.js +8 -17
  428. package/dist/merchant-core/proposal/repository.js.map +1 -1
  429. package/dist/merchant-core/proposal/types.d.ts +1 -0
  430. package/dist/merchant-core/proposal/types.js.map +1 -1
  431. package/dist/merchant-core/rfq/policy.d.ts +1 -0
  432. package/dist/merchant-core/rfq/policy.js +6 -7
  433. package/dist/merchant-core/rfq/policy.js.map +1 -1
  434. package/dist/merchant-core/rfq/repository.d.ts +0 -1
  435. package/dist/merchant-core/rfq/repository.js +2 -17
  436. package/dist/merchant-core/rfq/repository.js.map +1 -1
  437. package/dist/merchant-core/rfq/service.d.ts +2 -1
  438. package/dist/merchant-core/rfq/service.js +2 -4
  439. package/dist/merchant-core/rfq/service.js.map +1 -1
  440. package/dist/merchant-core/storage/transaction.d.ts +95 -7
  441. package/dist/merchant-core/storage/transaction.js +251 -2
  442. package/dist/merchant-core/storage/transaction.js.map +1 -1
  443. package/dist/merchant-credential-rotation.d.ts +4 -1
  444. package/dist/merchant-credential-rotation.js +12 -8
  445. package/dist/merchant-credential-rotation.js.map +1 -1
  446. package/dist/merchant-runtime/manager.d.ts +2 -0
  447. package/dist/merchant-runtime/manager.js +5 -0
  448. package/dist/merchant-runtime/manager.js.map +1 -1
  449. package/dist/negotiation/domain/objects.d.ts +2 -0
  450. package/dist/negotiation/domain/objects.js +3 -0
  451. package/dist/negotiation/domain/objects.js.map +1 -1
  452. package/dist/negotiation/ledger/store.d.ts +4 -0
  453. package/dist/negotiation/ledger/store.js +20 -0
  454. package/dist/negotiation/ledger/store.js.map +1 -1
  455. package/dist/product-init.d.ts +1 -0
  456. package/dist/product-init.js +4 -1
  457. package/dist/product-init.js.map +1 -1
  458. package/dist/trust/identity/message-signature.d.ts +1 -1
  459. package/dist/trust/identity/message-signature.js +6 -1
  460. package/dist/trust/identity/message-signature.js.map +1 -1
  461. package/dist/trust/identity/nonce.d.ts +5 -0
  462. package/dist/trust/identity/nonce.js +2 -0
  463. package/dist/trust/identity/nonce.js.map +1 -1
  464. package/dist/weixin/ilink-client.d.ts +3 -2
  465. package/dist/weixin/ilink-client.js +9 -2
  466. package/dist/weixin/ilink-client.js.map +1 -1
  467. package/package.json +2 -2
@@ -38,6 +38,7 @@
38
38
  * operation_id 查询路径(§11.1),绝不当作失败自动重做。
39
39
  */
40
40
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
41
+ import { MerchantWeixinError } from "../../merchant/weixin-channel.js";
41
42
  import { contentHash } from "../../agent/merchant/action-candidate.js";
42
43
  import { ADMIN_SESSION_COOKIE } from "../../auth/merchant-sessions.js";
43
44
  import { FileListingPublicationError, } from "../../cloud/file-listing-publication.js";
@@ -45,7 +46,7 @@ import { parseProductTable, ProductTableError, productTableDigest, } from "../..
45
46
  import { convertTabularImport, renderImportTemplateCsv, renderImportTemplateXlsx, TABULAR_IMPORT_MAX_BYTES, } from "../../cloud/product-import-tabular.js";
46
47
  import { normalizeTradePlatformRules, } from "../../handoff/trade-platform-rules.js";
47
48
  import { MerchantImportDraftStore } from "./draft-store.js";
48
- import { ActorContextError, assertVerifiedActor, createVerifiedActorContext, hasPermission, } from "../../merchant/application/actor.js";
49
+ import { ActorContextError, assertVerifiedActor, createVerifiedActorContext, hasPermission, isDirectMerchantOwner, } from "../../merchant/application/actor.js";
49
50
  import { MANAGEMENT_API_MAJOR, MANAGEMENT_ERROR_STATUS, ManagementError, MerchantApplicationService, } from "../../merchant/application/service.js";
50
51
  import { managementRequestDigest, MerchantManagementOperationStore } from "./operation-store.js";
51
52
  import { OnboardingStore } from "../../cloud/onboarding/store.js";
@@ -57,13 +58,19 @@ import { checkStepSubmission, planWizard, WIZARD_STEPS } from "../../cloud/onboa
57
58
  import { createWorkbenchProblem } from "./problem.js";
58
59
  import { WorkbenchConfirmationError, } from "./webauthn-confirmation.js";
59
60
  import { MerchantWorkbenchError, } from "../../merchant/workbench-service.js";
61
+ import { NegotiationOpsError } from "../../merchant/negotiation-ops.js";
60
62
  import { NEGOTIATION_STATUS_FILTERS, } from "../../merchant/negotiation-observer.js";
61
63
  import { parseReportPeriod, } from "../../merchant/operations-report.js";
64
+ import { AlipayCollectionConflict, isBoundedAlipayQrPng, } from "../../merchant-core/collection/alipay-store.js";
62
65
  import { OrderFactError } from "../../merchant-core/orders/model.js";
63
66
  import { OperatingPlanError } from "../../merchant-core/operating/types.js";
64
67
  import { OpportunityError } from "../../merchant-core/opportunity/types.js";
65
68
  import { ProposalError } from "../../merchant-core/proposal/types.js";
66
69
  import { FollowUpError } from "../../merchant-core/followup/types.js";
70
+ import { GovernanceRuntimeError } from "../../merchant-core/ownership/runtime.js";
71
+ import { InstanceOwnershipError } from "../../merchant-core/ownership/instance-ownership.js";
72
+ import { LearningError } from "../../merchant-core/learning/types.js";
73
+ import { OperationsJobsError } from "../../merchant-core/operations-jobs/service.js";
67
74
  import { parseExactMoney, WorkbenchMoneyError, WORKBENCH_CURRENCY_TABLE_VERSION, } from "../../merchant/application/money.js";
68
75
  import { CONNECTION_PAIRING_SAFE_CODES } from "../../cloud/connect-service.js";
69
76
  import { EXACT_PRODUCT_TOOLS } from "../../merchant/exact-product-executors.js";
@@ -77,6 +84,8 @@ import { WorkbenchEventProjectionError, } from "./event-projection.js";
77
84
  import { GRANT_ACTIONS, MerchantGrantError, } from "../../merchant/grant-store.js";
78
85
  const API_PREFIX = "/merchant/api";
79
86
  const WORKBENCH_API_PREFIX = "/merchant/api/v1";
87
+ const ALIPAY_COLLECTION_PATH = "/collection/alipay";
88
+ const ALIPAY_APPROVAL_PATH = `${ALIPAY_COLLECTION_PATH}/approvals`;
80
89
  const CATALOG_CONNECTION_SAFE_CODES = new Set([
81
90
  "PUBLICATION_NOT_ACTIVE", "PUBLICATION_NOT_VERIFIED", "CATALOG_UNREACHABLE",
82
91
  "CATALOG_MISMATCH", "BINDING_MERCHANT_MISMATCH", "BINDING_CLAIM_EXPIRED",
@@ -113,6 +122,77 @@ async function resolvePlatformRules(options) {
113
122
  return normalizeTradePlatformRules(undefined);
114
123
  }
115
124
  }
125
+ function alipayCollectionSummary(config) {
126
+ const mask = (value) => {
127
+ const letters = Array.from(value);
128
+ return letters.length > 1 ? `${letters[0]}***` : "***";
129
+ };
130
+ return {
131
+ version: config?.version ?? null,
132
+ enabled: config?.enabled ?? false,
133
+ recipient_masked: config === undefined ? null : mask(config.recipient),
134
+ account_masked: config?.account === undefined ? null : mask(config.account),
135
+ has_qr: config?.qrPngBase64 !== undefined,
136
+ };
137
+ }
138
+ function alipayFields(body, allowed) {
139
+ const fields = requireObject(body, "body");
140
+ if (Object.keys(fields).some((key) => !allowed.includes(key))) {
141
+ // Field names are also user input; never echo them on this settings surface.
142
+ throw new ManagementError("invalid_input", "支付宝收款请求包含不支持的字段");
143
+ }
144
+ return fields;
145
+ }
146
+ function alipayExpectedVersion(value) {
147
+ if (value === null || (typeof value === "string" && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/.test(value)))
148
+ return value;
149
+ throw new ManagementError("invalid_input", "需要有效的收款配置版本(首次设置为 null)");
150
+ }
151
+ function alipayCollectionInput(fields) {
152
+ const enabled = fields["enabled"];
153
+ const recipient = requireString(fields["recipient"], "recipient").trim();
154
+ const account = fields["account"] === undefined ? undefined : requireString(fields["account"], "account").trim();
155
+ const qrPngBase64 = fields["qr_png_base64"];
156
+ if (typeof enabled !== "boolean" || recipient.length > 80 || /[\p{Cc}\p{Cf}\p{Cs}]/u.test(recipient)) {
157
+ throw new ManagementError("invalid_input", "收款主体名称或启用状态无效");
158
+ }
159
+ if (account !== undefined && (account.length > 128 || !/^(?:\+?[0-9]{5,20}|[A-Za-z0-9._+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+)$/.test(account))) {
160
+ throw new ManagementError("invalid_input", "支付宝账号须为手机号或邮箱");
161
+ }
162
+ if (qrPngBase64 !== undefined && !isBoundedAlipayQrPng(qrPngBase64)) {
163
+ throw new ManagementError("invalid_input", "仅支持不超过 256 KiB、宽高不超过 1024 像素的静态 PNG");
164
+ }
165
+ if (account === undefined && qrPngBase64 === undefined) {
166
+ throw new ManagementError("invalid_input", "请填写支付宝账号或上传官方静态收款码");
167
+ }
168
+ return { enabled, recipient, ...(account === undefined ? {} : { account }), ...(qrPngBase64 === undefined ? {} : { qrPngBase64 }) };
169
+ }
170
+ function deliveryField(body, key) {
171
+ const value = body[key];
172
+ if (typeof value !== "string" || value.trim() === "") {
173
+ throw new ManagementError("invalid_input", `${key} must be a non-empty string`);
174
+ }
175
+ return value;
176
+ }
177
+ function deliveryNumber(body, key) {
178
+ const value = body[key];
179
+ if (!Number.isSafeInteger(value)) {
180
+ throw new ManagementError("invalid_input", `${key} must be an integer`);
181
+ }
182
+ return value;
183
+ }
184
+ function deliveryCall(work) {
185
+ try {
186
+ return work();
187
+ }
188
+ catch (err) {
189
+ const code = err?.code;
190
+ if (typeof code === "string" && code !== "") {
191
+ throw new ManagementError("invalid_input", err instanceof Error ? err.message : code);
192
+ }
193
+ throw err;
194
+ }
195
+ }
116
196
  export function createMerchantManagementApiHandler(options) {
117
197
  const log = options.log ??
118
198
  ((line) => {
@@ -123,6 +203,7 @@ export function createMerchantManagementApiHandler(options) {
123
203
  // CSRF 进程密钥:令牌 = HMAC(sessionId, key)。重启后页面重新拉取 /session
124
204
  // 即可取到新令牌;跨进程不可推导,持 Cookie 者本就可推导(CSRF 威胁模型成立)。
125
205
  const csrfKey = randomBytes(32);
206
+ const alipayPreviewKey = randomBytes(32);
126
207
  const baseDeps = {
127
208
  merchantId: options.merchantId,
128
209
  generation: options.generation,
@@ -180,10 +261,19 @@ export function createMerchantManagementApiHandler(options) {
180
261
  writeJson(res, 404, errorBody("not_found", "unknown management api path"));
181
262
  return;
182
263
  }
264
+ if (pathname === `${API_PREFIX}/internal/customer-identity` && method === "POST") {
265
+ const result = await options.receiveCustomerIdentity?.(req.headers["x-kiwi-identity-channel-token"], () => readJsonBody(req));
266
+ writeJson(res, result?.status ?? 404, result?.body ?? { ok: false });
267
+ return;
268
+ }
183
269
  if (pathname === WORKBENCH_API_PREFIX || pathname.startsWith(`${WORKBENCH_API_PREFIX}/`)) {
184
270
  const requestId = `req_${randomBytes(12).toString("hex")}`;
185
271
  const rest = pathname === WORKBENCH_API_PREFIX ? "/" : pathname.slice(WORKBENCH_API_PREFIX.length);
186
272
  try {
273
+ if (rest === "/channels/weixin" || rest.startsWith("/channels/weixin/")) {
274
+ await routeWeixin(req, res, method, rest);
275
+ return;
276
+ }
187
277
  if (method === "GET") {
188
278
  await routeWorkbenchV1Get(req, res, url, rest, requestId);
189
279
  return;
@@ -227,9 +317,178 @@ export function createMerchantManagementApiHandler(options) {
227
317
  }
228
318
  writeJson(res, 404, errorBody("not_found", "unknown management api path"));
229
319
  }
320
+ async function routeWeixin(req, res, method, rest) {
321
+ const channel = options.weixinChannel;
322
+ if (channel === undefined)
323
+ throw new ManagementError("not_found", "微信通道未启用。");
324
+ const auth = requireActor(req);
325
+ const actor = assertVerifiedActor(auth.ctx, now());
326
+ if (actor.merchantId !== options.merchantId)
327
+ throw new ManagementError("not_found", "微信通道不存在。");
328
+ if (actor.role !== "owner")
329
+ throw new ManagementError("forbidden", "仅店主可管理微信通道。");
330
+ const base = "/channels/weixin";
331
+ if (method === "GET" && rest === base) {
332
+ writeJson(res, 200, channel.status());
333
+ return;
334
+ }
335
+ const action = rest.slice(base.length + 1);
336
+ if (method !== "POST" || !["begin", "poll", "cancel", "disconnect"].includes(action)) {
337
+ throw new ManagementError("not_found", "微信通道路由不存在。");
338
+ }
339
+ assertWriteGuards(req, auth.sessionId);
340
+ let fields;
341
+ try {
342
+ fields = objectFields(await readJsonBody(req, 2048), action === "poll" ? ["attempt_id", "verify_code"] : action === "cancel" ? ["attempt_id"] : []);
343
+ }
344
+ catch (error) {
345
+ if (error instanceof BodyTooLarge || error instanceof ManagementError) {
346
+ throw new ManagementError("invalid_input", "微信通道请求字段无效或请求过大。");
347
+ }
348
+ throw error;
349
+ }
350
+ const owner = {
351
+ sessionId: auth.sessionId,
352
+ generation: actor.generation,
353
+ current: () => {
354
+ if (actor.generation !== options.generation())
355
+ return false;
356
+ const session = options.sessions.getSession(auth.sessionId);
357
+ return session?.role === "owner" && session.merchant_id === options.merchantId &&
358
+ session.principal_id === actor.actorId;
359
+ },
360
+ };
361
+ try {
362
+ if (action === "begin") {
363
+ writeJson(res, 200, await channel.begin(owner));
364
+ }
365
+ else if (action === "disconnect") {
366
+ await channel.disconnect(owner);
367
+ writeJson(res, 200, { status: "disconnected" });
368
+ }
369
+ else {
370
+ const id = requireString(fields["attempt_id"], "attempt_id");
371
+ if (action === "cancel") {
372
+ channel.cancel(owner, id);
373
+ writeJson(res, 200, { status: "cancelled" });
374
+ }
375
+ else {
376
+ const code = fields["verify_code"];
377
+ writeJson(res, 200, await channel.poll(owner, id, code === undefined ? undefined : requireString(code, "verify_code")));
378
+ }
379
+ }
380
+ }
381
+ catch (error) {
382
+ if (error instanceof MerchantWeixinError)
383
+ throw new ManagementError(error.code, error.message);
384
+ throw error;
385
+ }
386
+ }
230
387
  // ── 只读路由(认证即鉴权入口;业务授权在服务层逐次复核)────────────────
231
388
  /** Workbench v1 读取面复用同一应用服务;未实现路由明确失败,不返回假数据。 */
389
+ function governanceRouteDisabled(rest) {
390
+ if (rest.startsWith("/learning/"))
391
+ return options.governance?.flags.learning_enabled !== true;
392
+ if (rest.startsWith("/automation/"))
393
+ return options.governance?.flags.jobs_enabled !== true;
394
+ return false;
395
+ }
396
+ function writeGoverned(work) {
397
+ if (options.governance === undefined) {
398
+ throw new ManagementError("conflict", "governance runtime is not initialized");
399
+ }
400
+ try {
401
+ return options.governance.write(work);
402
+ }
403
+ catch (error) {
404
+ if (error instanceof GovernanceRuntimeError || error instanceof InstanceOwnershipError) {
405
+ throw new ManagementError("conflict", "governance ownership is not held by this process");
406
+ }
407
+ throw error;
408
+ }
409
+ }
410
+ function requireAlipayCollectionOwner(req) {
411
+ const auth = requireActor(req);
412
+ const ctx = assertVerifiedActor(auth.ctx, now());
413
+ if (ctx.merchantId !== options.merchantId) {
414
+ throw new ManagementError("not_found", "resource does not belong to this merchant");
415
+ }
416
+ if (!isDirectMerchantOwner(ctx, options.alipayCollectionOwnerActorId)) {
417
+ throw new ManagementError("forbidden", "支付宝收款设置仅限直接登录的商家管理员");
418
+ }
419
+ return auth;
420
+ }
421
+ function requireAlipayCollection() {
422
+ const store = options.alipayCollection;
423
+ if (store === undefined || store.merchantId !== options.merchantId) {
424
+ throw new ManagementError("unavailable", "支付宝收款设置暂不可用");
425
+ }
426
+ return store;
427
+ }
428
+ function requireAlipayApprovals() {
429
+ const approvals = options.alipayNegotiationApprovals;
430
+ if (approvals === undefined)
431
+ throw new ManagementError("unavailable", "支付宝报价审批暂不可用");
432
+ return approvals;
433
+ }
232
434
  async function routeWorkbenchV1Get(req, res, url, rest, requestId) {
435
+ if (rest === ALIPAY_COLLECTION_PATH) {
436
+ requireAlipayCollectionOwner(req);
437
+ const store = requireAlipayCollection();
438
+ try {
439
+ writeJson(res, 200, alipayCollectionSummary(store.current()), { "x-request-id": requestId });
440
+ }
441
+ catch {
442
+ throw new ManagementError("unavailable", "支付宝收款设置暂不可用");
443
+ }
444
+ return;
445
+ }
446
+ if (rest === ALIPAY_APPROVAL_PATH) {
447
+ requireAlipayCollectionOwner(req);
448
+ const store = requireAlipayCollection();
449
+ const approvals = requireAlipayApprovals();
450
+ try {
451
+ const items = store.current()?.enabled === true ? approvals.listApprovals("pending")
452
+ .filter((item) => item.currency === "CNY").slice(0, 100).map((item) => ({
453
+ approval_id: item.approval_id, negotiation_id: item.negotiation_id,
454
+ sku: item.sku, quantity: item.quantity, unit: item.unit ?? null,
455
+ buyer_offer_minor: item.buyer_offer_minor, currency: item.currency, expires_at: item.expires_at ?? null,
456
+ })) : [];
457
+ writeJson(res, 200, { items }, { "x-request-id": requestId });
458
+ }
459
+ catch {
460
+ throw new ManagementError("unavailable", "支付宝报价审批暂不可用");
461
+ }
462
+ return;
463
+ }
464
+ if (governanceRouteDisabled(rest)) {
465
+ writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench API 路由不存在或尚未实现。");
466
+ return;
467
+ }
468
+ if (options.customerDeliveries !== undefined && rest === "/delivery/unknown") {
469
+ const auth = requireActor(req);
470
+ authorizeOrThrow(auth.ctx, "followups:read");
471
+ writeJson(res, 200, {
472
+ deliveries: options.customerDeliveries.listByStatus(auth.ctx.merchantId, "UNKNOWN"),
473
+ reconciliation_audit: options.customerDeliveries.listReconciliationAudit(auth.ctx.merchantId),
474
+ }, { "x-request-id": requestId });
475
+ return;
476
+ }
477
+ if (options.deliveryConsent !== undefined && rest.startsWith("/delivery/")) {
478
+ const auth = requireActor(req);
479
+ authorizeOrThrow(auth.ctx, "followups:read");
480
+ if (rest === "/delivery/bindings") {
481
+ writeJson(res, 200, { bindings: options.deliveryConsent.listBindings(auth.ctx.merchantId) }, { "x-request-id": requestId });
482
+ return;
483
+ }
484
+ if (rest === "/delivery/subscriptions") {
485
+ const bindingId = url.searchParams.get("binding_id") ?? undefined;
486
+ writeJson(res, 200, {
487
+ subscriptions: options.deliveryConsent.listSubscriptions(auth.ctx.merchantId, bindingId),
488
+ }, { "x-request-id": requestId });
489
+ return;
490
+ }
491
+ }
233
492
  if (rest === "/products/publication-status") {
234
493
  const auth = requireActor(req);
235
494
  authorizeOrThrow(auth.ctx, "products:import");
@@ -710,10 +969,309 @@ export function createMerchantManagementApiHandler(options) {
710
969
  writeJson(res, 200, { orders: ops.listOrders() }, { "x-request-id": requestId });
711
970
  return;
712
971
  }
972
+ if (rest === "/learning/corrections") {
973
+ const auth = requireActor(req);
974
+ authorizeOrThrow(auth.ctx, "learning:read");
975
+ writeJson(res, 200, { corrections: ops.listCorrections() }, { "x-request-id": requestId });
976
+ return;
977
+ }
978
+ const recoveryMatch = /^\/learning\/evaluations\/([^/]+)\/recovery$/.exec(rest);
979
+ if (recoveryMatch !== null) {
980
+ const auth = requireActor(req);
981
+ authorizeOrThrow(auth.ctx, "learning:review");
982
+ writeJson(res, 200, ops.getEvaluationRecovery(pathSegment(recoveryMatch[1] ?? ""), {
983
+ actor_id: auth.ctx.actorId, merchant_id: auth.ctx.merchantId, auth_method: auth.ctx.authMethod, permissions: [...auth.ctx.permissions],
984
+ }), { "x-request-id": requestId });
985
+ return;
986
+ }
987
+ const correctionMatch = /^\/learning\/corrections\/([^/]+)$/.exec(rest);
988
+ if (correctionMatch !== null) {
989
+ const auth = requireActor(req);
990
+ authorizeOrThrow(auth.ctx, "learning:read");
991
+ writeJson(res, 200, ops.getCorrection(pathSegment(correctionMatch[1] ?? "")), {
992
+ "x-request-id": requestId,
993
+ });
994
+ return;
995
+ }
996
+ if (rest === "/learning/candidates") {
997
+ const auth = requireActor(req);
998
+ authorizeOrThrow(auth.ctx, "learning:read");
999
+ writeJson(res, 200, { candidates: ops.listCandidates() }, { "x-request-id": requestId });
1000
+ return;
1001
+ }
1002
+ const candidateMatch = /^\/learning\/candidates\/([^/]+)$/.exec(rest);
1003
+ if (candidateMatch !== null) {
1004
+ const auth = requireActor(req);
1005
+ authorizeOrThrow(auth.ctx, "learning:read");
1006
+ writeJson(res, 200, ops.getCandidate(pathSegment(candidateMatch[1] ?? "")), {
1007
+ "x-request-id": requestId,
1008
+ });
1009
+ return;
1010
+ }
1011
+ if (rest === "/learning/reviews") {
1012
+ const auth = requireActor(req);
1013
+ authorizeOrThrow(auth.ctx, "learning:read");
1014
+ writeJson(res, 200, { reviews: ops.listReviews() }, { "x-request-id": requestId });
1015
+ return;
1016
+ }
1017
+ const reviewMatch = /^\/learning\/reviews\/([^/]+)$/.exec(rest);
1018
+ if (reviewMatch !== null) {
1019
+ const auth = requireActor(req);
1020
+ authorizeOrThrow(auth.ctx, "learning:read");
1021
+ writeJson(res, 200, ops.getReview(pathSegment(reviewMatch[1] ?? "")), {
1022
+ "x-request-id": requestId,
1023
+ });
1024
+ return;
1025
+ }
1026
+ if (rest === "/learning/releases/active") {
1027
+ const auth = requireActor(req);
1028
+ authorizeOrThrow(auth.ctx, "learning:read");
1029
+ const skillKey = url.searchParams.get("skill_key");
1030
+ if (skillKey === null || skillKey.trim() === "") {
1031
+ throw new ManagementError("invalid_input", "skill_key query parameter is required");
1032
+ }
1033
+ writeJson(res, 200, ops.getActiveRelease(skillKey));
1034
+ return;
1035
+ }
1036
+ if (rest === "/learning/releases") {
1037
+ const auth = requireActor(req);
1038
+ authorizeOrThrow(auth.ctx, "learning:read");
1039
+ const skillKey = url.searchParams.get("skill_key") ?? undefined;
1040
+ writeJson(res, 200, { releases: ops.listReleases(skillKey) }, {
1041
+ "x-request-id": requestId,
1042
+ });
1043
+ return;
1044
+ }
1045
+ const releaseMatch = /^\/learning\/releases\/([^/]+)$/.exec(rest);
1046
+ if (releaseMatch !== null) {
1047
+ const auth = requireActor(req);
1048
+ authorizeOrThrow(auth.ctx, "learning:read");
1049
+ writeJson(res, 200, ops.getRelease(pathSegment(releaseMatch[1] ?? "")), {
1050
+ "x-request-id": requestId,
1051
+ });
1052
+ return;
1053
+ }
1054
+ if (rest === "/automation/rules") {
1055
+ const auth = requireActor(req);
1056
+ authorizeOrThrow(auth.ctx, "followups:read");
1057
+ writeJson(res, 200, { rules: ops.listRules() }, { "x-request-id": requestId });
1058
+ return;
1059
+ }
1060
+ const ruleMatch = /^\/automation\/rules\/([^/]+)$/.exec(rest);
1061
+ if (ruleMatch !== null) {
1062
+ const auth = requireActor(req);
1063
+ authorizeOrThrow(auth.ctx, "followups:read");
1064
+ writeJson(res, 200, ops.getRule(pathSegment(ruleMatch[1] ?? "")), {
1065
+ "x-request-id": requestId,
1066
+ });
1067
+ return;
1068
+ }
1069
+ if (rest === "/automation/artifacts") {
1070
+ const auth = requireActor(req);
1071
+ authorizeOrThrow(auth.ctx, "followups:read");
1072
+ const taskId = url.searchParams.get("task_id") ?? undefined;
1073
+ writeJson(res, 200, { artifacts: ops.listArtifacts(taskId) }, {
1074
+ "x-request-id": requestId,
1075
+ });
1076
+ return;
1077
+ }
713
1078
  }
714
1079
  writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench API 路由不存在或尚未实现。");
715
1080
  }
1081
+ function alipayPreviewMac(auth, expectedVersion, draft, expiry) {
1082
+ return createHmac("sha256", alipayPreviewKey).update(JSON.stringify([
1083
+ auth.sessionId, auth.ctx.actorId, auth.ctx.merchantId, auth.ctx.generation, expectedVersion, draft, expiry,
1084
+ ])).digest("base64url");
1085
+ }
1086
+ async function writeAlipayCollection(req, res, requestId, action) {
1087
+ try {
1088
+ const auth = requireAlipayCollectionOwner(req);
1089
+ assertWriteGuards(req, auth.sessionId);
1090
+ const store = requireAlipayCollection();
1091
+ const allowed = action === "disable" ? ["expected_version", "confirm_disable"]
1092
+ : ["expected_version", "enabled", "recipient", "account", "qr_png_base64"];
1093
+ if (action === "save")
1094
+ allowed.push("confirmation_ref", "confirm_owner_rights");
1095
+ const fields = alipayFields(await readJsonBody(req), allowed);
1096
+ const expectedVersion = alipayExpectedVersion(fields["expected_version"]);
1097
+ if (auth.ctx.generation !== requireAlipayCollectionOwner(req).ctx.generation) {
1098
+ throw new AlipayCollectionConflict();
1099
+ }
1100
+ const current = store.current();
1101
+ if ((current?.version ?? null) !== expectedVersion)
1102
+ throw new AlipayCollectionConflict();
1103
+ if (action === "disable") {
1104
+ if (fields["confirm_disable"] !== true)
1105
+ throw new ManagementError("invalid_input", "请明确确认停用收款方式");
1106
+ if (current?.enabled !== true)
1107
+ throw new AlipayCollectionConflict();
1108
+ const { version, ...details } = current;
1109
+ const disabled = store.replace(version, { ...details, enabled: false }, auth.ctx.actorId, now().toISOString());
1110
+ writeJson(res, 200, alipayCollectionSummary(disabled), { "x-request-id": requestId });
1111
+ return;
1112
+ }
1113
+ const draft = alipayCollectionInput(fields);
1114
+ if (action === "preview") {
1115
+ const expiry = now().getTime() + CONFIRMATION_TTL_MS;
1116
+ const token = `${expiry}.${alipayPreviewMac(auth, expectedVersion, draft, expiry)}`;
1117
+ writeJson(res, 200, { ...alipayCollectionSummary(draft), confirmation_ref: token }, { "x-request-id": requestId });
1118
+ return;
1119
+ }
1120
+ if (fields["confirm_owner_rights"] !== true) {
1121
+ throw new ManagementError("invalid_input", "请明确确认你有权使用该收款主体及账号或收款码");
1122
+ }
1123
+ const token = fields["confirmation_ref"];
1124
+ const parsed = typeof token === "string" ? /^(\d{1,15})\.([A-Za-z0-9_-]{43})$/.exec(token) : null;
1125
+ if (parsed === null || Number(parsed[1]) <= now().getTime() || !timingSafeEqual(Buffer.from(parsed[2]), Buffer.from(alipayPreviewMac(auth, expectedVersion, draft, Number(parsed[1]))))) {
1126
+ throw new ManagementError("precondition_changed", "收款信息、会话或确认有效期已变化,请重新预览");
1127
+ }
1128
+ const result = store.replace(expectedVersion, draft, auth.ctx.actorId, now().toISOString());
1129
+ writeJson(res, 200, alipayCollectionSummary(result), { "x-request-id": requestId });
1130
+ }
1131
+ catch (error) {
1132
+ if (error instanceof ManagementError || error instanceof ActorContextError)
1133
+ throw error;
1134
+ if (error instanceof AlipayCollectionConflict)
1135
+ throw new ManagementError("precondition_changed", error.message);
1136
+ if (error instanceof BodyTooLarge) {
1137
+ writeJson(res, 413, errorBody("invalid_input", "request body too large"), { "x-request-id": requestId });
1138
+ return;
1139
+ }
1140
+ // No unexpected exception (including SQLite diagnostics) is reflected or logged here.
1141
+ throw new ManagementError("unavailable", "支付宝收款设置暂不可用");
1142
+ }
1143
+ }
1144
+ async function approveAlipayTotal(req, res, requestId) {
1145
+ const auth = requireAlipayCollectionOwner(req);
1146
+ assertWriteGuards(req, auth.sessionId);
1147
+ const approvals = requireAlipayApprovals();
1148
+ const store = requireAlipayCollection();
1149
+ try {
1150
+ const fields = alipayFields(await readJsonBody(req), [
1151
+ "approval_id", "expected_version", "approved_minor", "alipay_total_minor", "confirm_final_total",
1152
+ ]);
1153
+ const approvalId = requireString(fields["approval_id"], "approval_id");
1154
+ const expectedVersion = alipayExpectedVersion(fields["expected_version"]);
1155
+ const approvedMinor = requirePositiveInteger(fields["approved_minor"], "approved_minor");
1156
+ const totalMinor = requirePositiveInteger(fields["alipay_total_minor"], "alipay_total_minor");
1157
+ if (!Number.isSafeInteger(approvedMinor) || !Number.isSafeInteger(totalMinor)) {
1158
+ throw new ManagementError("invalid_input", "单价与最终应付总额必须是安全整数分");
1159
+ }
1160
+ if (fields["confirm_final_total"] !== true) {
1161
+ throw new ManagementError("invalid_input", "请明确确认包含适用运费、税费及其他费用的 CNY 最终应付总额");
1162
+ }
1163
+ const current = store.current();
1164
+ if (auth.ctx.generation !== requireAlipayCollectionOwner(req).ctx.generation ||
1165
+ current?.enabled !== true || current.version !== expectedVersion)
1166
+ throw new AlipayCollectionConflict();
1167
+ const pending = approvals.listApprovals("pending").find((item) => item.approval_id === approvalId && item.currency === "CNY");
1168
+ if (pending === undefined)
1169
+ throw new ManagementError("not_found", "未找到待审批的人民币报价");
1170
+ const subtotal = approvedMinor * pending.quantity;
1171
+ if (subtotal <= 0 || !Number.isSafeInteger(subtotal) || totalMinor < subtotal) {
1172
+ throw new ManagementError("invalid_input", "最终应付总额不得低于已确认单价与数量计算的商品小计");
1173
+ }
1174
+ const receipt = approvals.approve({
1175
+ approval_id: approvalId, approved_minor: approvedMinor, alipay_total_minor: totalMinor, actor: auth.ctx.actorId,
1176
+ });
1177
+ writeJson(res, 200, {
1178
+ approval_id: receipt.approval_id, status: receipt.status,
1179
+ approved_minor: receipt.approved_minor, alipay_total_minor: receipt.alipay_total_minor,
1180
+ }, { "x-request-id": requestId });
1181
+ }
1182
+ catch (error) {
1183
+ if (error instanceof ManagementError || error instanceof ActorContextError)
1184
+ throw error;
1185
+ if (error instanceof AlipayCollectionConflict)
1186
+ throw new ManagementError("precondition_changed", error.message);
1187
+ if (error instanceof BodyTooLarge) {
1188
+ writeJson(res, 413, errorBody("invalid_input", "request body too large"), { "x-request-id": requestId });
1189
+ return;
1190
+ }
1191
+ if (error instanceof NegotiationOpsError) {
1192
+ if (error.code === "not_found" || error.code === "conflict") {
1193
+ throw new ManagementError("precondition_changed", "待审批报价已变更,请刷新后再试");
1194
+ }
1195
+ if (error.code === "forbidden" || error.code === "invalid_request") {
1196
+ throw new ManagementError("invalid_input", "金额不符合当前报价规则,请核对后再试");
1197
+ }
1198
+ }
1199
+ throw new ManagementError("unavailable", "支付宝报价审批暂不可用");
1200
+ }
1201
+ }
716
1202
  async function routeWorkbenchV1Post(req, res, rest, requestId, url) {
1203
+ if (rest === ALIPAY_APPROVAL_PATH) {
1204
+ await approveAlipayTotal(req, res, requestId);
1205
+ return;
1206
+ }
1207
+ if (rest === ALIPAY_COLLECTION_PATH || rest === `${ALIPAY_COLLECTION_PATH}/preview` || rest === `${ALIPAY_COLLECTION_PATH}/disable`) {
1208
+ await writeAlipayCollection(req, res, requestId, rest.endsWith("/preview") ? "preview" : rest.endsWith("/disable") ? "disable" : "save");
1209
+ return;
1210
+ }
1211
+ if (governanceRouteDisabled(rest)) {
1212
+ writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench API 路由不存在或尚未实现。");
1213
+ return;
1214
+ }
1215
+ if (options.deliveryConsent !== undefined && rest.startsWith("/delivery/")) {
1216
+ const auth = requireActor(req);
1217
+ assertWriteGuards(req, auth.sessionId);
1218
+ authorizeOrThrow(auth.ctx, "followups:manage");
1219
+ const body = await readJsonBody(req);
1220
+ const fields = objectFields(body, [
1221
+ "channel",
1222
+ "address_ref",
1223
+ "proof_ref",
1224
+ "expected_epoch",
1225
+ "binding_id",
1226
+ "purpose",
1227
+ "max_per_day",
1228
+ "expires_at",
1229
+ "consent_evidence_ref",
1230
+ "verified_not_executed",
1231
+ "channel_idempotent",
1232
+ ]);
1233
+ const retryMatch = /^\/delivery\/unknown\/([^/]+)\/retry$/.exec(rest);
1234
+ if (retryMatch !== null) {
1235
+ if (options.customerDeliveries === undefined) {
1236
+ writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "投递记录不可用。");
1237
+ return;
1238
+ }
1239
+ // The deployed SMTP adapter cannot prove non-execution or deduplicate a retry.
1240
+ // Keep UNKNOWN available for inspection until a trusted reconciliation adapter exists.
1241
+ throw new ManagementError("precondition_changed", "渠道尚未提供可验证的未发送回执,结果未知的通知不能重发");
1242
+ }
1243
+ if (rest === "/delivery/bindings") {
1244
+ writeJson(res, 201, deliveryCall(() => options.deliveryConsent.createBinding({
1245
+ merchant_id: auth.ctx.merchantId,
1246
+ channel: deliveryField(fields, "channel"),
1247
+ address_ref: deliveryField(fields, "address_ref"),
1248
+ proof_ref: deliveryField(fields, "proof_ref"),
1249
+ })), { "x-request-id": requestId });
1250
+ return;
1251
+ }
1252
+ const revokeBindingMatch = /^\/delivery\/bindings\/([^/]+)\/revoke$/.exec(rest);
1253
+ if (revokeBindingMatch !== null) {
1254
+ writeJson(res, 200, deliveryCall(() => options.deliveryConsent.revokeBinding(auth.ctx.merchantId, pathSegment(revokeBindingMatch[1] ?? ""), deliveryNumber(fields, "expected_epoch"))), { "x-request-id": requestId });
1255
+ return;
1256
+ }
1257
+ if (rest === "/delivery/subscriptions") {
1258
+ const expiresAt = typeof fields["expires_at"] === "string" ? fields["expires_at"] : null;
1259
+ writeJson(res, 201, deliveryCall(() => options.deliveryConsent.createSubscription({
1260
+ merchant_id: auth.ctx.merchantId,
1261
+ binding_id: deliveryField(fields, "binding_id"),
1262
+ purpose: deliveryField(fields, "purpose"),
1263
+ max_per_day: deliveryNumber(fields, "max_per_day"),
1264
+ expires_at: expiresAt,
1265
+ consent_evidence_ref: deliveryField(fields, "consent_evidence_ref"),
1266
+ })), { "x-request-id": requestId });
1267
+ return;
1268
+ }
1269
+ const unsubscribeMatch = /^\/delivery\/subscriptions\/([^/]+)\/unsubscribe$/.exec(rest);
1270
+ if (unsubscribeMatch !== null) {
1271
+ writeJson(res, 200, deliveryCall(() => options.deliveryConsent.unsubscribe(auth.ctx.merchantId, pathSegment(unsubscribeMatch[1] ?? ""), deliveryNumber(fields, "expected_epoch"))), { "x-request-id": requestId });
1272
+ return;
1273
+ }
1274
+ }
717
1275
  if (options.merchantOperations !== undefined) {
718
1276
  const ops = options.merchantOperations;
719
1277
  const readOpsBody = async () => {
@@ -859,6 +1417,163 @@ export function createMerchantManagementApiHandler(options) {
859
1417
  writeJson(res, 200, ops.assessOrderContribution(pathSegment(orderContributionMatch[1] ?? ""), body), { "x-request-id": requestId });
860
1418
  return;
861
1419
  }
1420
+ if (rest === "/learning/corrections") {
1421
+ const auth = requireActor(req);
1422
+ assertWriteGuards(req, auth.sessionId);
1423
+ authorizeOrThrow(auth.ctx, "learning:manage");
1424
+ const { body, idempotencyKey } = await readOpsBody();
1425
+ writeJson(res, 201, writeGoverned(() => ops.submitCorrection(body, {
1426
+ actor_id: auth.ctx.actorId,
1427
+ merchant_id: auth.ctx.merchantId,
1428
+ auth_method: auth.ctx.authMethod,
1429
+ permissions: [...auth.ctx.permissions],
1430
+ }, idempotencyKey)), { "x-request-id": requestId });
1431
+ return;
1432
+ }
1433
+ const recoveryMatch = /^\/learning\/evaluations\/([^/]+)\/recovery$/.exec(rest);
1434
+ if (recoveryMatch !== null) {
1435
+ const auth = requireActor(req);
1436
+ assertWriteGuards(req, auth.sessionId);
1437
+ authorizeOrThrow(auth.ctx, "learning:review");
1438
+ const { body } = await readOpsBody();
1439
+ let result;
1440
+ try {
1441
+ result = await ops.resolveEvaluationRecovery(pathSegment(recoveryMatch[1] ?? ""), body, {
1442
+ actor_id: auth.ctx.actorId, merchant_id: auth.ctx.merchantId, auth_method: auth.ctx.authMethod, permissions: [...auth.ctx.permissions],
1443
+ });
1444
+ }
1445
+ catch (error) {
1446
+ if (error instanceof GovernanceRuntimeError || error instanceof InstanceOwnershipError) {
1447
+ throw new ManagementError("conflict", "governance ownership is not held by this process");
1448
+ }
1449
+ throw error;
1450
+ }
1451
+ writeJson(res, 200, result, { "x-request-id": requestId });
1452
+ return;
1453
+ }
1454
+ const promoteCorrectionMatch = /^\/learning\/corrections\/([^/]+)\/promote$/.exec(rest);
1455
+ if (promoteCorrectionMatch !== null) {
1456
+ const auth = requireActor(req);
1457
+ assertWriteGuards(req, auth.sessionId);
1458
+ authorizeOrThrow(auth.ctx, "learning:manage");
1459
+ const { body, idempotencyKey } = await readOpsBody();
1460
+ writeJson(res, 200, writeGoverned(() => ops.promoteCorrection(pathSegment(promoteCorrectionMatch[1] ?? ""), body, {
1461
+ actor_id: auth.ctx.actorId,
1462
+ merchant_id: auth.ctx.merchantId,
1463
+ auth_method: auth.ctx.authMethod,
1464
+ permissions: [...auth.ctx.permissions],
1465
+ }, idempotencyKey)), { "x-request-id": requestId });
1466
+ return;
1467
+ }
1468
+ if (rest === "/learning/candidates") {
1469
+ const auth = requireActor(req);
1470
+ assertWriteGuards(req, auth.sessionId);
1471
+ authorizeOrThrow(auth.ctx, "learning:manage");
1472
+ const { body, idempotencyKey } = await readOpsBody();
1473
+ writeJson(res, 201, writeGoverned(() => ops.proposeCandidate(body, {
1474
+ actor_id: auth.ctx.actorId,
1475
+ merchant_id: auth.ctx.merchantId,
1476
+ auth_method: auth.ctx.authMethod,
1477
+ permissions: [...auth.ctx.permissions],
1478
+ }, idempotencyKey)), { "x-request-id": requestId });
1479
+ return;
1480
+ }
1481
+ const reviseCandidateMatch = /^\/learning\/candidates\/([^/]+)\/revise$/.exec(rest);
1482
+ if (reviseCandidateMatch !== null) {
1483
+ const auth = requireActor(req);
1484
+ assertWriteGuards(req, auth.sessionId);
1485
+ authorizeOrThrow(auth.ctx, "learning:manage");
1486
+ const { body, idempotencyKey } = await readOpsBody();
1487
+ writeJson(res, 200, writeGoverned(() => ops.reviseCandidate(pathSegment(reviseCandidateMatch[1] ?? ""), body, {
1488
+ actor_id: auth.ctx.actorId,
1489
+ merchant_id: auth.ctx.merchantId,
1490
+ auth_method: auth.ctx.authMethod,
1491
+ permissions: [...auth.ctx.permissions],
1492
+ }, idempotencyKey)), { "x-request-id": requestId });
1493
+ return;
1494
+ }
1495
+ const reviewCandidateMatch = /^\/learning\/candidates\/([^/]+)\/review$/.exec(rest);
1496
+ if (reviewCandidateMatch !== null) {
1497
+ const auth = requireActor(req);
1498
+ assertWriteGuards(req, auth.sessionId);
1499
+ authorizeOrThrow(auth.ctx, "learning:review");
1500
+ const { body, idempotencyKey } = await readOpsBody();
1501
+ writeJson(res, 200, writeGoverned(() => ops.reviewCandidate(pathSegment(reviewCandidateMatch[1] ?? ""), body, {
1502
+ actor_id: auth.ctx.actorId,
1503
+ merchant_id: auth.ctx.merchantId,
1504
+ auth_method: auth.ctx.authMethod,
1505
+ permissions: [...auth.ctx.permissions],
1506
+ }, idempotencyKey)), { "x-request-id": requestId });
1507
+ return;
1508
+ }
1509
+ if (rest === "/learning/releases/publish") {
1510
+ const auth = requireActor(req);
1511
+ assertWriteGuards(req, auth.sessionId);
1512
+ authorizeOrThrow(auth.ctx, "learning:publish");
1513
+ const { body, idempotencyKey } = await readOpsBody();
1514
+ writeJson(res, 201, writeGoverned(() => ops.publishRelease(body, {
1515
+ actor_id: auth.ctx.actorId,
1516
+ merchant_id: auth.ctx.merchantId,
1517
+ auth_method: auth.ctx.authMethod,
1518
+ permissions: [...auth.ctx.permissions],
1519
+ }, idempotencyKey)), { "x-request-id": requestId });
1520
+ return;
1521
+ }
1522
+ const rollbackReleaseMatch = /^\/learning\/releases\/([^/]+)\/rollback$/.exec(rest);
1523
+ if (rollbackReleaseMatch !== null) {
1524
+ const auth = requireActor(req);
1525
+ assertWriteGuards(req, auth.sessionId);
1526
+ authorizeOrThrow(auth.ctx, "learning:publish");
1527
+ const { body, idempotencyKey } = await readOpsBody();
1528
+ writeJson(res, 200, writeGoverned(() => ops.rollbackRelease(pathSegment(rollbackReleaseMatch[1] ?? ""), body, {
1529
+ actor_id: auth.ctx.actorId,
1530
+ merchant_id: auth.ctx.merchantId,
1531
+ auth_method: auth.ctx.authMethod,
1532
+ permissions: [...auth.ctx.permissions],
1533
+ }, idempotencyKey)), { "x-request-id": requestId });
1534
+ return;
1535
+ }
1536
+ const revokeReleaseMatch = /^\/learning\/releases\/([^/]+)\/revoke$/.exec(rest);
1537
+ if (revokeReleaseMatch !== null) {
1538
+ const auth = requireActor(req);
1539
+ assertWriteGuards(req, auth.sessionId);
1540
+ authorizeOrThrow(auth.ctx, "learning:publish");
1541
+ const { body, idempotencyKey } = await readOpsBody();
1542
+ writeJson(res, 200, writeGoverned(() => ops.revokeRelease(pathSegment(revokeReleaseMatch[1] ?? ""), body, {
1543
+ actor_id: auth.ctx.actorId,
1544
+ merchant_id: auth.ctx.merchantId,
1545
+ auth_method: auth.ctx.authMethod,
1546
+ permissions: [...auth.ctx.permissions],
1547
+ }, idempotencyKey)), { "x-request-id": requestId });
1548
+ return;
1549
+ }
1550
+ if (rest === "/automation/rules/prepare") {
1551
+ const auth = requireActor(req);
1552
+ assertWriteGuards(req, auth.sessionId);
1553
+ authorizeOrThrow(auth.ctx, "followups:manage");
1554
+ const { body } = await readOpsBody();
1555
+ writeJson(res, 201, writeGoverned(() => ops.prepareRule(body)), { "x-request-id": requestId });
1556
+ return;
1557
+ }
1558
+ if (rest === "/automation/rules/activate") {
1559
+ const auth = requireActor(req);
1560
+ assertWriteGuards(req, auth.sessionId);
1561
+ authorizeOrThrow(auth.ctx, "followups:manage");
1562
+ const { body } = await readOpsBody();
1563
+ writeJson(res, 201, writeGoverned(() => ops.activateRule(body)), { "x-request-id": requestId });
1564
+ return;
1565
+ }
1566
+ const pauseRuleMatch = /^\/automation\/rules\/([^/]+)\/pause$/.exec(rest);
1567
+ if (pauseRuleMatch !== null) {
1568
+ const auth = requireActor(req);
1569
+ assertWriteGuards(req, auth.sessionId);
1570
+ authorizeOrThrow(auth.ctx, "followups:manage");
1571
+ const { body } = await readOpsBody();
1572
+ writeJson(res, 200, writeGoverned(() => ops.pauseRule(pathSegment(pauseRuleMatch[1] ?? ""), body)), {
1573
+ "x-request-id": requestId,
1574
+ });
1575
+ return;
1576
+ }
862
1577
  }
863
1578
  const publicationCommitMatch = /^\/products\/publication-drafts\/(flp_[a-z0-9]+_[0-9a-f]{12})\/commit$/.exec(rest);
864
1579
  if (rest === "/products/publication-drafts" || publicationCommitMatch !== null) {
@@ -1978,6 +2693,8 @@ export function createMerchantManagementApiHandler(options) {
1978
2693
  role: auth.session.role,
1979
2694
  expires_at: auth.session.expires_at,
1980
2695
  csrf_token: csrfTokenFor(auth.sessionId),
2696
+ can_manage_alipay_collection: options.alipayCollection?.merchantId === auth.ctx.merchantId &&
2697
+ auth.ctx.merchantId === options.merchantId && isDirectMerchantOwner(auth.ctx, options.alipayCollectionOwnerActorId),
1981
2698
  });
1982
2699
  return;
1983
2700
  }
@@ -3085,6 +3802,11 @@ export function createMerchantManagementApiHandler(options) {
3085
3802
  try {
3086
3803
  // 落盘前再刷一次运营规则:运营新增平台后无需重启实例即可提交。
3087
3804
  await options.marketplacePlatforms?.();
3805
+ if (importChannel.currentTable().digest !== (draft.base_digest ?? "")) {
3806
+ operations.release(begun.operationId);
3807
+ respondError(res, new ManagementError("precondition_changed", "product table changed since draft creation"));
3808
+ return;
3809
+ }
3088
3810
  const written = importChannel.commit(table);
3089
3811
  const marked = options.drafts.markCommitted(auth.ctx.merchantId, draftId);
3090
3812
  if (!marked) {
@@ -3418,12 +4140,12 @@ export function createMerchantManagementApiHandler(options) {
3418
4140
  return expected.length === actual.length && timingSafeEqual(expected, actual);
3419
4141
  }
3420
4142
  // ── 输入与输出辅助 ─────────────────────────────────────────────────
3421
- async function readJsonBody(req) {
4143
+ async function readJsonBody(req, maxBytes = MAX_BODY_BYTES) {
3422
4144
  const chunks = [];
3423
4145
  let size = 0;
3424
4146
  for await (const chunk of req) {
3425
4147
  size += chunk.length;
3426
- if (size > MAX_BODY_BYTES)
4148
+ if (size > maxBytes)
3427
4149
  throw new BodyTooLarge();
3428
4150
  chunks.push(chunk);
3429
4151
  }
@@ -3775,6 +4497,33 @@ function respondWorkbenchError(res, error, requestId) {
3775
4497
  writeWorkbenchProblem(res, code, requestId, "经营请求未完成", error instanceof Error ? error.message : "经营请求未完成");
3776
4498
  return;
3777
4499
  }
4500
+ if (error instanceof OperationsJobsError) {
4501
+ const mapping = {
4502
+ validation: "VALIDATION_ERROR",
4503
+ not_found: "RESOURCE_NOT_FOUND",
4504
+ conflict: "VERSION_CONFLICT",
4505
+ version_conflict: "VERSION_CONFLICT",
4506
+ invalid_transition: "VERSION_CONFLICT",
4507
+ budget_exhausted: "RATE_LIMITED",
4508
+ idempotency_conflict: "IDEMPOTENCY_KEY_REUSED",
4509
+ };
4510
+ writeWorkbenchProblem(res, mapping[error.code], requestId, "经营任务请求未完成", error.message);
4511
+ return;
4512
+ }
4513
+ if (error instanceof LearningError) {
4514
+ const mapping = {
4515
+ validation: "VALIDATION_ERROR",
4516
+ sensitive_content: "VALIDATION_ERROR",
4517
+ unsupported_capability: "VALIDATION_ERROR",
4518
+ access_denied: "PERMISSION_REVOKED",
4519
+ not_found: "RESOURCE_NOT_FOUND",
4520
+ version_conflict: "VERSION_CONFLICT",
4521
+ idempotency_conflict: "IDEMPOTENCY_KEY_REUSED",
4522
+ schema_unavailable: "DEPENDENCY_UNAVAILABLE",
4523
+ };
4524
+ writeWorkbenchProblem(res, mapping[error.code], requestId, "学习请求未完成", error.message);
4525
+ return;
4526
+ }
3778
4527
  if (error instanceof WorkbenchEventProjectionError) {
3779
4528
  writeWorkbenchProblem(res, "VALIDATION_ERROR", requestId, "事件游标无效", error.message);
3780
4529
  return;