@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
@@ -1,3 +1,4 @@
1
+ import { quoteQuantity } from "./quote-quantity.js";
1
2
  /**
2
3
  * Copyright 2026 harrylabsj
3
4
  *
@@ -28,14 +29,19 @@
28
29
  * 执行 seam(Phase 2 接线真实 merchant 网络):MerchantIndex / QuoteFetcher /
29
30
  * Negotiator 为可注入接口。v0.1 默认使用 Static 实现或由宿主注入。
30
31
  */
32
+ import { ProcurementCases, fail as procurementError } from "./procurement/cases.js";
33
+ import { asRecord, COSTS_KEY, REQUIREMENTS_KEY, projectRequirements, validTimestamp } from "./procurement/requirements.js";
34
+ import { missingBasis } from "./procurement/source-observation.js";
31
35
  import { contentDigest, sha256Hex } from "../negotiation/jcs.js";
32
36
  import { validateAcceptedNonbindingAgreement } from "../negotiation/domain/objects.js";
33
37
  import { randomBytes as cryptoRandomBytes } from "node:crypto";
34
38
  import { isDestinationType, isSessionDestinationType, isUrlDestinationType } from "../handoff/destination.js";
39
+ import { ALIPAY_PRIVATE_DISPLAY_REQUIRED, isAlipayCollectionAgreement, isAlipayCollectionDestination } from "../handoff/alipay-collection.js";
35
40
  import { uuidv7 } from "@earendil-works/pi-ai";
36
41
  import { assertNorthboundContractValid, validateCommerceIntent, validateEffectiveAuthorization, } from "../contracts/northbound-schema.js";
37
42
  import { CatalogSourceError } from "../discovery/catalog-source/errors.js";
38
43
  import { McpError } from "./errors.js";
44
+ import { assertGenericA2AAcceptTerms, assertGenericA2AAgreement, assertNoAlipayAccept } from "./a2a-accept-terms.js";
39
45
  import { failedSearchDiagnostics, legacySearchDiagnostics, notSearchedDiagnostics, } from "./network-search.js";
40
46
  import { TaskApprovalStore } from "./store.js";
41
47
  /** 离线态(与 merchant-index 同口径):未设置按 fresh 处理(向后兼容)。 */
@@ -109,6 +115,12 @@ function explicitIntentItemSku(intent) {
109
115
  const sku = first.sku;
110
116
  return typeof sku === "string" && sku.trim() !== "" ? sku : undefined;
111
117
  }
118
+ function withHistorySku(intent, sku) {
119
+ const items = intent.items;
120
+ if (!Array.isArray(items) || items.length === 0)
121
+ return intent;
122
+ return { ...intent, items: [{ ...items[0], sku }, ...items.slice(1)] };
123
+ }
112
124
  /** 明确 SKU 的报价必须只包含该 SKU;商家换品/混入其他商品时拒绝接纳。 */
113
125
  function rejectQuoteForOtherSku(result, explicitSku) {
114
126
  if (explicitSku === undefined || result.status !== "succeeded")
@@ -166,11 +178,13 @@ export class KiwiBuyerService {
166
178
  quoteFetcher;
167
179
  negotiator;
168
180
  followsClient;
181
+ commerceReceipts;
169
182
  staleWake;
170
183
  staleWakeTimeoutMs;
171
184
  wakeAttemptAt = new Map();
172
185
  wakeInFlight = new Map();
173
186
  now;
187
+ procurement;
174
188
  constructor(options) {
175
189
  this.store = options.store;
176
190
  this.principal = options.principal;
@@ -188,10 +202,196 @@ export class KiwiBuyerService {
188
202
  this.merchantIndex = options.merchantIndex;
189
203
  this.quoteFetcher = options.quoteFetcher;
190
204
  this.negotiator = options.negotiator;
205
+ this.commerceReceipts = options.commerceReceipts;
191
206
  this.followsClient = options.followsClient;
192
207
  this.staleWake = options.staleWake;
193
208
  this.staleWakeTimeoutMs = options.staleWakeTimeoutMs ?? 5000;
194
209
  }
210
+ companyProcurement(captureRoot) {
211
+ this.procurement ??= new ProcurementCases(this.store.openProcurementStore(), `company-procurement-v1:${this.ownerHash}`, {
212
+ now: this.now,
213
+ captureRoot,
214
+ coverage: async (query) => {
215
+ const status = (await this.search({ query })).network_search.status;
216
+ return status === "searching" ? "partial" : status;
217
+ },
218
+ candidate: (task, id) => this.taskFor(task) === undefined ? undefined :
219
+ this.store.listCandidates(task).find(candidate => id === undefined || candidate.candidate_id === id),
220
+ discover: async (query, merchantId, sku) => {
221
+ const result = await this.search({ query });
222
+ const merchant = result.merchants.find(record => record.merchant_id === merchantId);
223
+ const listing = merchant?.products?.find(product => product.listing_id === sku || product.attributes?.sku === sku);
224
+ const available = merchant?.matching_skus?.includes(sku) || listing !== undefined;
225
+ const model = listing?.attributes?.model ?? listing?.attributes?.model_number;
226
+ return { coverage: result.network_search.status === "searching" ? "partial" : result.network_search.status,
227
+ match: merchant && available ? { name: merchant.name, inquiry_available: merchant.inquiry_available,
228
+ product: typeof model === "string" ? { model } : undefined } : undefined };
229
+ },
230
+ });
231
+ return this.procurement;
232
+ }
233
+ procurementMode(action, merchant, allowAsk) {
234
+ const mode = this.policy.actions[action === "rfq" ? "inquiry_rfq" : action]?.mode;
235
+ const allowed = this.policy.limits?.allowed_merchants;
236
+ this.assertPolicyActive(Date.parse(this.now()));
237
+ if (mode === "never" || (allowed?.length && !allowed.includes(merchant))) {
238
+ throw new McpError("delegation_denied", "Procurement action is outside the delegation");
239
+ }
240
+ return allowAsk && mode === "auto";
241
+ }
242
+ async requestProcurementQuotes(input) {
243
+ const cases = this.companyProcurement();
244
+ const ref = input.procurement_ref;
245
+ const historical = cases.getCase(ref.case_id, ref.revision);
246
+ const source = historical.sources.find(entry => entry.id === ref.source_binding_id);
247
+ if (source?.channel !== "kiwi" || !source.merchant_id || source.inquiry_available !== true || input.merchant_ids?.length !== 1 ||
248
+ input.merchant_ids[0] !== source.merchant_id)
249
+ procurementError("RFQ_REQUIRES_ONE_DISCOVERED_KIWI_MERCHANT");
250
+ const merchant = source.merchant_id;
251
+ const { basis } = historical;
252
+ const items = Array.isArray(input.intent.items) ? input.intent.items : [];
253
+ const item = asRecord(items[0]);
254
+ const quantity = asRecord(item.quantity);
255
+ if (items.length !== 1 || item.sku !== source.variant || quantity.value !== basis.quantity || quantity.unit !== basis.unit ||
256
+ missingBasis(basis).length || typeof item.query !== "string" || !item.query.trim() || item.query.length > 128)
257
+ procurementError("RFQ_BASIS_MISMATCH");
258
+ const projection = projectRequirements(basis);
259
+ const intent = { intent_id: input.intent.intent_id, intent_type: input.intent.intent_type,
260
+ items: [{ query: item.query, sku: source.variant, quantity: { value: basis.quantity, unit: basis.unit } }],
261
+ constraints: { deadline: basis.delivery_before, currency: "CNY", [REQUIREMENTS_KEY]: projection } };
262
+ const invalid = validateCommerceIntent(intent);
263
+ if (invalid.length)
264
+ procurementError(invalid.join("; "));
265
+ const maxQuantity = this.policy.limits?.max_quantity;
266
+ const auto = this.policy.policy_id !== "dp-default" && this.policy.actions.inquiry_rfq?.mode === "auto" && !ref.replaces_source_id;
267
+ const sourceKey = contentDigest([merchant, source.variant, historical.basis_digest]);
268
+ const payload = { ref, merchant, intent, requested_intent_digest: contentDigest(input.intent), source_key: sourceKey, ...(ref.replaces_source_id ? { replaces_source_id: ref.replaces_source_id } : {}) };
269
+ const nativeKey = `company-rfq-${contentDigest([ref.case_id, input.idempotency_key])}`;
270
+ const guarded = cases.bindAction({ case_ref: ref, operation: "rfq", request_id: input.idempotency_key,
271
+ payload, approval_id: input.approval_id, auto,
272
+ rfqTaskMissing: () => !this.store.findTaskByIdempotencyKey(this.ownerHash, nativeKey),
273
+ validate: (current, resumingId) => {
274
+ this.procurementMode("rfq", merchant, true);
275
+ if (maxQuantity && (maxQuantity.unit !== basis.unit || (basis.quantity ?? Infinity) > maxQuantity.value)) {
276
+ throw new McpError("delegation_denied", "Procurement quantity exceeds delegation");
277
+ }
278
+ if (this.policy.limits?.allowed_currencies?.length && !this.policy.limits.allowed_currencies.includes("CNY")) {
279
+ throw new McpError("delegation_denied", "CNY is outside the delegation");
280
+ }
281
+ if (source.basis_digest !== current.basis_digest)
282
+ procurementError("SOURCE_BASIS_CHANGED");
283
+ const count = cases.followupCount(current.id, sourceKey, "rfq", resumingId);
284
+ if (!ref.replaces_source_id) {
285
+ if (source.task_id || count > 0)
286
+ procurementError("USE_TARGETED_REQUOTE");
287
+ return;
288
+ }
289
+ const old = current.sources.find(entry => entry.id === ref.replaces_source_id);
290
+ if (!old?.task_id || old.merchant_id !== merchant || old.variant !== source.variant || old.basis_digest !== current.basis_digest ||
291
+ current.sources.some(entry => entry.replaces_source_id === old.id))
292
+ procurementError("REQUOTE_BINDING_MISMATCH");
293
+ if (count >= Math.min(3, 1 + (this.policy.limits?.max_rounds ?? 2)))
294
+ procurementError("REQUOTE_LIMIT");
295
+ if (current.sources.length >= 20)
296
+ procurementError("SOURCE_LIMIT");
297
+ } });
298
+ const action = guarded.action;
299
+ if (action.status === "DONE")
300
+ return action.result;
301
+ if (action.status === "PENDING" || action.status === "APPROVED")
302
+ return this.actionApproval(action);
303
+ if (action.status === "REVOKED")
304
+ procurementError("PROCUREMENT_APPROVAL_REVOKED: submit a new request for approval");
305
+ const boundSource = ref.replaces_source_id ? { ...source,
306
+ id: `source-${action.id}`, replaces_source_id: ref.replaces_source_id, task_id: undefined, candidate_id: undefined } : source;
307
+ const result = await this.requestQuotes({ intent, merchant_ids: [merchant], idempotency_key: nativeKey, beforeSend: () => cases.assertDispatchable(action.id) });
308
+ const candidates = Array.isArray(result.task.candidates) ? result.task.candidates.map(asRecord) : [];
309
+ const candidate = candidates.find(entry => entry.status === "succeeded" && entry.merchant_id === merchant);
310
+ const taskId = String(result.task.task_id);
311
+ const status = result.task.status === "in_progress" ? "UNKNOWN" : "DONE";
312
+ // A concurrent reader may see the reserved task before its creator sends.
313
+ // Do not change the action or case revision underneath that sender.
314
+ if (!result.created && status === "UNKNOWN")
315
+ return { ...result, task_id: taskId, action_id: action.id, status };
316
+ return cases.completeAction(action.id, status, { ...result, task_id: taskId, action_id: action.id, status }, candidate || !ref.replaces_source_id ? { source: boundSource, task_id: taskId, candidate_id: typeof candidate?.candidate_id === "string" ? candidate.candidate_id : undefined } : undefined);
317
+ }
318
+ actionApproval(action) {
319
+ return { approval_required: { approval_id: action.id }, operation: action.operation, payload: action.payload, expires_at: action.expires_at };
320
+ }
321
+ async negotiateProcurement(input) {
322
+ const cases = this.companyProcurement();
323
+ const { snapshot } = cases.getComparison(input.comparison_ref.comparison_id, input.comparison_ref.revision);
324
+ const ref = { case_id: snapshot.case_id, revision: snapshot.case_revision };
325
+ const historical = cases.getCase(ref.case_id, ref.revision);
326
+ const source = historical.sources.find(entry => entry.channel === "kiwi" && entry.task_id === input.task_id && entry.candidate_id === input.candidate_id);
327
+ const row = snapshot.data.rows.find(entry => entry.source_id === source?.id);
328
+ const { approval_id: _approval, ...payloadInput } = input;
329
+ if (!source?.merchant_id || row?.offer_digest !== input.expected_offer_digest || row.price_kind !== "KNP_OFFER")
330
+ procurementError("TARGET_REQUIRED_OR_OFFER_CHANGED");
331
+ const merchant = source.merchant_id;
332
+ // Only fields validated against the snapshot may cross the merchant boundary.
333
+ // Keep the original request in the local approval and idempotency record.
334
+ const questions = input.questions?.map(({ field }) => ({ field }));
335
+ const target = input.target_unit_price;
336
+ const payload = { ...payloadInput, ref, source_key: contentDigest([merchant, source.variant, historical.basis_digest]),
337
+ merchant_id: merchant, proposed_terms: target ? { items: [{ sku: source.variant, quantity: { value: historical.basis.quantity, unit: historical.basis.unit },
338
+ unit_price: { currency: target.currency, amount_minor: target.amount_minor, basis: target.basis } }] } : undefined };
339
+ const guarded = cases.bindAction({ case_ref: ref, operation: input.action, request_id: input.request_id,
340
+ payload, approval_id: input.approval_id, auto: this.policy.policy_id !== "dp-default" && this.policy.actions[input.action]?.mode === "auto" &&
341
+ (input.action === "counter_offer" || input.questions?.every(question => !question.reason) === true), validate: current => {
342
+ this.procurementMode(input.action, merchant, true);
343
+ const candidate = this.store.listCandidates(input.task_id).find(entry => entry.candidate_id === input.candidate_id);
344
+ const provenance = asRecord(candidate?.provenance);
345
+ const terms = asRecord(provenance.latest_agreed_terms);
346
+ const costs = asRecord(asRecord(terms.price_terms)[COSTS_KEY]);
347
+ if (!this.taskFor(input.task_id) || !this.negotiator || current.basis_digest !== snapshot.basis_digest ||
348
+ candidate?.status !== "succeeded" || provenance.latest_terms_digest !== input.expected_offer_digest ||
349
+ !validTimestamp(terms.valid_until) || Date.parse(terms.valid_until) <= Date.parse(this.now()))
350
+ procurementError("CURRENT_OFFER_REQUIRED");
351
+ if (input.action === "counter_offer" && (!target || costs.native_basis !== target.basis))
352
+ procurementError("EXPLICIT_PRICE_BASIS_REQUIRED");
353
+ if (input.action === "clarification" && (!questions?.length || questions.some(question => !row.questions.some(draft => draft.field === question.field))))
354
+ procurementError("BOUND_QUESTIONS_REQUIRED");
355
+ if (cases.actions(current.id).some(action => action.request_id !== input.request_id &&
356
+ action.payload.task_id === input.task_id && (action.status === "UNKNOWN" || action.status === "IN_FLIGHT")))
357
+ procurementError("RECONCILE_PREVIOUS_ACTION");
358
+ } });
359
+ const { action } = guarded;
360
+ if (action.status === "DONE")
361
+ return action.result;
362
+ if (action.status === "PENDING" || action.status === "APPROVED")
363
+ return this.actionApproval(action);
364
+ const summary = input.action === "clarification" ? "请核对当前报价中的以下条件。" : `目标商品单价 CNY ${target.amount_minor} 分(${target.basis})`;
365
+ try {
366
+ if (!guarded.dispatch) {
367
+ const task = this.taskFor(input.task_id);
368
+ const candidate = task && this.store.listCandidates(input.task_id).find(entry => entry.candidate_id === input.candidate_id);
369
+ if (!action.round || !task || !candidate || !this.negotiator?.recoverNegotiation) {
370
+ return action.result ?? { action_id: action.id, status: "UNKNOWN" };
371
+ }
372
+ const taskBody = this.decodeTask(task);
373
+ const stored = (Array.isArray(taskBody.steps) ? taskBody.steps : [])
374
+ .find(step => step.action === input.action && step.round === action.round);
375
+ if (stored?.reply)
376
+ return cases.completeAction(action.id, "DONE", { task: taskBody, step: stored, action_id: action.id, status: "DONE" });
377
+ const step = await this.negotiator.recoverNegotiation(asRecord(taskBody.intent), { action: input.action, round: action.round, summary, questions }, candidate, this.protocolContext(task));
378
+ if (!step)
379
+ return action.result ?? { action_id: action.id, status: "UNKNOWN" };
380
+ const result = this.recordNegotiationStep(task.task_id, step, input.action, action.round, input.expected_offer_digest);
381
+ return cases.completeAction(action.id, "DONE", { ...result, action_id: action.id, status: "DONE" });
382
+ }
383
+ const result = await this.negotiate({ task_id: input.task_id, action: input.action, candidate_id: input.candidate_id,
384
+ summary, questions, target_unit_price: target, procurement_price_basis: target?.basis,
385
+ expected_offer_digest: input.expected_offer_digest, onReserved: round => cases.setActionRound(action.id, round),
386
+ beforeSend: () => cases.assertDispatchable(action.id) });
387
+ const status = result.step.reply || result.step.merchant_offer ? "DONE" : "UNKNOWN";
388
+ return cases.completeAction(action.id, status, { ...result, action_id: action.id, status });
389
+ }
390
+ catch (error) {
391
+ cases.completeAction(action.id, "UNKNOWN", { action_id: action.id, status: "UNKNOWN" });
392
+ throw error;
393
+ }
394
+ }
195
395
  /**
196
396
  * Per-merchant singleflight + 60s cooldown. The probe never updates catalog
197
397
  * state; only a subsequent catalog read showing a merchant heartbeat may
@@ -353,8 +553,8 @@ export class KiwiBuyerService {
353
553
  return { follows };
354
554
  }
355
555
  /** 主动拉取关注更新(仅响应买家主动询问;事件仅为商家公开动态)。 */
356
- async getFollowUpdates() {
357
- const updates = await this.withFollows((client) => client.getUpdates());
556
+ async getFollowUpdates(watermarks) {
557
+ const updates = await this.withFollows((client) => client.getUpdates(watermarks));
358
558
  return { updates };
359
559
  }
360
560
  requireMerchantId(raw) {
@@ -386,23 +586,85 @@ export class KiwiBuyerService {
386
586
  }
387
587
  // ---- Northbound:kiwi_request_quotes --------------------------------------
388
588
  async requestQuotes(input) {
589
+ const useHistory = input.reuse_history === true && explicitIntentItemSku(input.intent) === undefined;
590
+ const merchants = input.merchant_ids ?? [];
591
+ if (useHistory && merchants.length !== 1) {
592
+ throw new McpError("clarification_needed", "沿用上次规格需要恰好指定一个商家;请说明要沿用哪家店的报价。", {
593
+ reason: "history_merchant_required",
594
+ });
595
+ }
596
+ if (merchants.length === 0) {
597
+ throw new McpError("clarification_needed", "发起询价需要至少指定一个商家;请先从搜索结果中选择可实时询价的商家。", {
598
+ reason: "merchant_required",
599
+ });
600
+ }
601
+ const idempotencyKey = input.idempotency_key ?? `req-${uuidv7()}`;
602
+ const requestDigest = contentDigest({
603
+ intent: input.intent,
604
+ merchant_ids: [...new Set(merchants)].sort(),
605
+ reuse_history: useHistory,
606
+ });
607
+ const existing = this.store.findTaskByIdempotencyKey(this.ownerHash, idempotencyKey);
608
+ if (existing !== undefined)
609
+ return this.replayQuoteRequest(existing, input, requestDigest, useHistory);
610
+ // K3:历史解析发生在正式 RFQ 之前(A5)。显式新规格优先。
611
+ let effectiveIntent = input.intent;
612
+ let reusedHistory;
613
+ if (useHistory) {
614
+ const merchantId = merchants[0];
615
+ const history = await this.resolveQuoteHistory({ merchant_id: merchantId });
616
+ if (history.status !== "ok" || history.candidates.length === 0) {
617
+ throw new McpError("clarification_needed", history.status === "unavailable"
618
+ ? "暂时无法读取本店历史报价(未授权或商家不支持);请直接说明商品和数量重新询价。"
619
+ : "本店没有可引用的历史报价;请直接说明商品和数量重新询价。", {
620
+ reason: history.status === "unavailable" ? "history_unavailable" : "history_empty",
621
+ merchant_id: merchantId,
622
+ });
623
+ }
624
+ if (history.candidates.length > 1) {
625
+ throw new McpError("clarification_needed", "上次有多款商品报价;请说明要沿用哪一款(可按 SKU 或商品名指明)。", {
626
+ reason: "history_ambiguous",
627
+ merchant_id: merchantId,
628
+ candidates: history.candidates.map((hit) => ({
629
+ sku: hit.sku,
630
+ quoted_at: hit.quoted_at,
631
+ ...(hit.valid_until !== undefined ? { valid_until: hit.valid_until } : {}),
632
+ price: hit.price,
633
+ })),
634
+ });
635
+ }
636
+ const hit = history.candidates[0];
637
+ effectiveIntent = withHistorySku(input.intent, hit.sku);
638
+ reusedHistory = {
639
+ merchant_id: merchantId,
640
+ sku: hit.sku,
641
+ quoted_at: hit.quoted_at,
642
+ price: hit.price,
643
+ quantity: hit.quantity,
644
+ unit: hit.unit,
645
+ negotiation_id: hit.negotiation_id,
646
+ offer_id: hit.offer_id,
647
+ ...(hit.valid_until !== undefined ? { valid_until: hit.valid_until } : {}),
648
+ note: "历史价格仅供参考(含时间与有效期);本次价格以正式报价为准。",
649
+ };
650
+ }
389
651
  // 契约校验(§5.2):CommerceIntent 必须合法;无效即拒绝,不落库。
390
- const intentErrors = validateCommerceIntent(input.intent);
652
+ const intentErrors = validateCommerceIntent(effectiveIntent);
391
653
  if (intentErrors.length > 0) {
392
654
  throw new McpError("contract_violation", `CommerceIntent 违反冻结契约:${intentErrors.join("; ")}`);
393
655
  }
394
656
  // M0 硬门(merchant-buddy 第 0 版 §4/§5):仅有公开资料、无可路由 Agent 的
395
657
  // 商家不得进入 RFQ。服务层显式拒绝(不只靠宿主提示词),在创建任务/消息之前。
396
- await this.assertInquiryAvailable(input.merchant_ids);
658
+ quoteQuantity(effectiveIntent);
659
+ await this.assertInquiryAvailable(merchants);
397
660
  const policyId = this.policy.policy_id;
398
661
  const expiresAt = this.policy.expires_at;
399
- const idempotencyKey = input.idempotency_key ?? `req-${uuidv7()}`;
400
662
  const taskId = `task-${uuidv7()}`;
401
663
  const created = this.now();
402
664
  // 无 fetcher 时记录确定性 fan-out 槽位(§6.2 部分失败可解释);有 fetcher 时
403
665
  // 只写真实结果,不预建槽位,避免候选重复。
404
666
  const preCandidates = this.quoteFetcher === undefined
405
- ? (input.merchant_ids ?? []).map((merchantId) => ({
667
+ ? merchants.map((merchantId) => ({
406
668
  candidate_id: `cand-${uuidv7()}`,
407
669
  merchant_id: merchantId,
408
670
  status: "pending",
@@ -415,6 +677,7 @@ export class KiwiBuyerService {
415
677
  task_kind: "request_quotes",
416
678
  status: "in_progress",
417
679
  idempotency_key: idempotencyKey,
680
+ quote_request_digest: requestDigest,
418
681
  intent_id: String(input.intent.intent_id),
419
682
  delegation_policy_id: policyId,
420
683
  created_at: created,
@@ -433,48 +696,15 @@ export class KiwiBuyerService {
433
696
  expires_at: expiresAt,
434
697
  resumable: true,
435
698
  candidates: preCandidates,
436
- intent: input.intent,
699
+ // 任务持久化**解析后**的意图(含 K3 历史解析出的显式 SKU);恢复/
700
+ // 重试用同一意图,出站 SKU 确定性一致(A5)。历史价格参考只在本次
701
+ // 响应返回(persistent-task 冻结契约不允许附加顶层字段)。
702
+ intent: effectiveIntent,
437
703
  }),
438
704
  };
439
705
  const { task: persisted, created: isCreated } = this.store.createTask(task);
440
706
  if (!isCreated) {
441
- // idempotency_key is globally unique in the local store. It must never
442
- // become a side-channel that lets another session read/revive a task.
443
- if (persisted.owner_hash !== this.ownerHash) {
444
- throw new McpError("task_not_found", "idempotency key belongs to another session");
445
- }
446
- if (this.quoteFetcher?.recoverQuotes !== undefined) {
447
- const original = this.decodeTask(persisted).intent;
448
- if (original !== undefined && contentDigest(original) !== contentDigest(input.intent))
449
- throw new McpError("idempotency_conflict", "same task key has different intent");
450
- if (persisted.status !== "in_progress") {
451
- const selected = [...new Set(this.store.listCandidates(persisted.task_id).map(c => String(c.merchant_id)))].sort();
452
- const requested = [...new Set(input.merchant_ids ?? [])].sort();
453
- if (contentDigest(selected) !== contentDigest(requested))
454
- throw new McpError("idempotency_conflict", "same task key has different selected merchants");
455
- }
456
- }
457
- // Recovery can only read previously persisted protocol receipts/results, never send.
458
- if (this.quoteFetcher?.recoverQuotes !== undefined && ["in_progress", "partial_success"].includes(persisted.status) && !this.store.hasAgreementForTask(persisted.task_id)) {
459
- const originalCandidates = this.store.listCandidates(persisted.task_id);
460
- const recovered = await this.quoteFetcher.recoverQuotes(this.protocolContext(persisted, input.merchant_ids ?? []));
461
- const explicitSku = explicitIntentItemSku(input.intent);
462
- const results = recovered.map((result) => rejectQuoteForOtherSku(result, explicitSku));
463
- if (results.length > 0)
464
- return this.store.transaction(() => {
465
- if (this.store.hasAgreementForTask(persisted.task_id) || contentDigest(this.store.listCandidates(persisted.task_id)) !== contentDigest(originalCandidates))
466
- throw new McpError("idempotency_conflict", "task candidates or accepted agreement changed during recovery");
467
- for (const result of results)
468
- this.store.replaceRecoveredCandidate(persisted.task_id, result);
469
- const candidates = this.northboundCandidates(persisted.task_id);
470
- const status = candidates.length > 0 && candidates.every(c => c.status === "succeeded") ? "succeeded" : "partial_success";
471
- const updated = this.store.updateTask(persisted.task_id, { status, payload: JSON.stringify({ ...this.decodeTask(persisted), status, updated_at: this.now(), candidates }) }, persisted);
472
- const decoded = this.decodeTask(updated);
473
- assertNorthboundContractValid("persistent-task", decoded, "recovered quotes result");
474
- return { task: decoded, created: false };
475
- });
476
- }
477
- return { task: this.decodeTask(persisted), created: false };
707
+ return this.replayQuoteRequest(persisted, input, requestDigest, useHistory);
478
708
  }
479
709
  for (const candidate of preCandidates) {
480
710
  this.store.addCandidate(taskId, candidate);
@@ -484,7 +714,6 @@ export class KiwiBuyerService {
484
714
  let status = "in_progress";
485
715
  let quotedResults = [];
486
716
  if (this.quoteFetcher !== undefined) {
487
- const merchants = input.merchant_ids ?? [];
488
717
  const index = this.merchantIndex;
489
718
  let dispatchStarted = false;
490
719
  let dispatchOutcomeUnknown = false;
@@ -507,12 +736,12 @@ export class KiwiBuyerService {
507
736
  return { merchant_id: m, name: m, verified: false, capabilities: [] };
508
737
  }));
509
738
  catalogLookupCompleted = true;
510
- const protocolContext = this.protocolContext(persisted, merchants);
739
+ const protocolContext = { ...this.protocolContext(persisted, merchants), beforeSend: input.beforeSend };
511
740
  // 一旦调用 quoteFetcher,就不能把抛错解释成“没发送”:adapter 可能已
512
741
  // 写入/发送部分 RFQ。没有 receipt 时保守落为 non-retryable unknown。
513
742
  dispatchStarted = true;
514
- quotedResults = await this.quoteFetcher.requestQuotes(input.intent, merchantRecords, protocolContext);
515
- const explicitSku = explicitIntentItemSku(input.intent);
743
+ quotedResults = await this.quoteFetcher.requestQuotes(effectiveIntent, merchantRecords, protocolContext);
744
+ const explicitSku = explicitIntentItemSku(effectiveIntent);
516
745
  quotedResults = quotedResults.map((result) => rejectQuoteForOtherSku(result, explicitSku));
517
746
  dispatchOutcomeUnknown = quotedResults.some((result) => result.status === "failed" &&
518
747
  result.failure?.classification === "protocol_error" &&
@@ -596,13 +825,117 @@ export class KiwiBuyerService {
596
825
  const decoded = this.decodeTask(updated);
597
826
  // 冻结契约强制:持久任务记录必须满足 persistent-task/1.0 schema(§6.2)。
598
827
  assertNorthboundContractValid("persistent-task", decoded, "requestQuotes result");
599
- return { task: decoded, created: true };
828
+ return {
829
+ task: decoded,
830
+ created: true,
831
+ ...(reusedHistory !== undefined ? { reused_history: reusedHistory } : {}),
832
+ };
600
833
  });
601
834
  }
602
835
  protocolContext(task, requestedMerchants) {
603
836
  const intent = this.decodeTask(task).intent;
604
837
  return { taskId: task.task_id, createdAt: task.created_at, intentBindingDigest: contentDigest({ task_id: task.task_id, created_at: task.created_at, intent: intent ?? null, requested_merchants: requestedMerchants ?? null, policy: this.policy, principal: this.principal, buyer: this.buyerAgentId }) };
605
838
  }
839
+ async replayQuoteRequest(persisted, input, requestDigest, useHistory) {
840
+ if (persisted.owner_hash !== this.ownerHash || persisted.task_kind !== "request_quotes") {
841
+ throw new McpError("task_not_found", "quote request does not belong to this session");
842
+ }
843
+ const task = this.decodeTask(persisted);
844
+ const original = task.intent;
845
+ const originalIntent = original !== null && typeof original === "object"
846
+ ? original
847
+ : undefined;
848
+ const originalSku = originalIntent === undefined ? undefined : explicitIntentItemSku(originalIntent);
849
+ const merchantIds = input.merchant_ids ?? [];
850
+ if (persisted.quote_request_digest !== undefined) {
851
+ if (persisted.quote_request_digest !== requestDigest) {
852
+ throw new McpError("idempotency_conflict", "same task key has a different quote request");
853
+ }
854
+ }
855
+ else if (useHistory || this.quoteFetcher?.recoverQuotes !== undefined) {
856
+ // Older tasks stored only the resolved SKU. Reconstruct it locally for replay.
857
+ const expectedIntent = useHistory && originalSku !== undefined
858
+ ? withHistorySku(input.intent, originalSku)
859
+ : input.intent;
860
+ if (originalIntent !== undefined && contentDigest(originalIntent) !== contentDigest(expectedIntent)) {
861
+ throw new McpError("idempotency_conflict", "same task key has different intent");
862
+ }
863
+ const selected = [...new Set(this.store.listCandidates(persisted.task_id).map((c) => c.merchant_id))].sort();
864
+ if (useHistory && selected.length === 0 && persisted.status === "in_progress") {
865
+ return { task, created: false }; // No saved target to use for legacy protocol recovery.
866
+ }
867
+ if ((useHistory || persisted.status !== "in_progress") &&
868
+ contentDigest(selected) !== contentDigest([...new Set(merchantIds)].sort())) {
869
+ throw new McpError("idempotency_conflict", "same task key has different selected merchants");
870
+ }
871
+ }
872
+ // Recovery reads existing protocol evidence and never dispatches a new RFQ.
873
+ if (this.quoteFetcher?.recoverQuotes === undefined ||
874
+ !["in_progress", "partial_success"].includes(persisted.status) ||
875
+ this.store.hasAgreementForTask(persisted.task_id)) {
876
+ return { task, created: false };
877
+ }
878
+ const originalCandidates = this.store.listCandidates(persisted.task_id);
879
+ const recovered = await this.quoteFetcher.recoverQuotes(this.protocolContext(persisted, merchantIds));
880
+ const explicitSku = originalIntent === undefined ? explicitIntentItemSku(input.intent) : originalSku;
881
+ const results = recovered.map((result) => rejectQuoteForOtherSku(result, explicitSku));
882
+ if (results.length === 0)
883
+ return { task, created: false };
884
+ return this.store.transaction(() => {
885
+ if (this.store.hasAgreementForTask(persisted.task_id) ||
886
+ contentDigest(this.store.listCandidates(persisted.task_id)) !== contentDigest(originalCandidates)) {
887
+ throw new McpError("idempotency_conflict", "task candidates or accepted agreement changed during recovery");
888
+ }
889
+ for (const result of results)
890
+ this.store.replaceRecoveredCandidate(persisted.task_id, result);
891
+ const candidates = this.northboundCandidates(persisted.task_id);
892
+ const status = candidates.length > 0 && candidates.every((candidate) => candidate.status === "succeeded")
893
+ ? "succeeded" : "partial_success";
894
+ const updated = this.store.updateTask(persisted.task_id, {
895
+ status,
896
+ payload: JSON.stringify({ ...task, status, updated_at: this.now(), candidates }),
897
+ }, persisted);
898
+ const decoded = this.decodeTask(updated);
899
+ assertNorthboundContractValid("persistent-task", decoded, "recovered quotes result");
900
+ return { task: decoded, created: false };
901
+ });
902
+ }
903
+ /**
904
+ * 买家识别与交易回执 · K2/K3:“沿用上次规格”前置查询——先解析目标商家,
905
+ * 再按本店授权查上次已发报价。唯一匹配时调用方把明确 SKU 和本次数量送入
906
+ * 标准 requestQuotes;无历史/多义/扩展不支持时由调用方澄清。
907
+ * 显式新规格优先:调用方带 skus 时按指定商品过滤。
908
+ */
909
+ async resolveQuoteHistory(input) {
910
+ const merchantId = input.merchant_id;
911
+ if (this.quoteFetcher?.queryQuoteHistory === undefined) {
912
+ return { status: "unavailable", merchant_id: merchantId, reason: "history_query_unsupported" };
913
+ }
914
+ const merchant = await this.merchantIndex?.resolveById(merchantId).catch(() => undefined);
915
+ if (merchant === undefined) {
916
+ return { status: "unavailable", merchant_id: merchantId, reason: "merchant_not_found" };
917
+ }
918
+ // 即席协议上下文:委托声明按当前时间派生(查询本身每次新 message ID,
919
+ // 无跨请求幂等绑定;正式 RFQ 的委托仍按任务上下文恒定派生)。
920
+ const context = {
921
+ taskId: `hist-${uuidv7()}`,
922
+ createdAt: this.now(),
923
+ intentBindingDigest: contentDigest({
924
+ merchant_id: merchantId,
925
+ principal: this.principal,
926
+ buyer: this.buyerAgentId,
927
+ }),
928
+ };
929
+ const result = await this.quoteFetcher.queryQuoteHistory(merchant, {
930
+ ...(input.skus !== undefined ? { skus: input.skus } : {}),
931
+ ...(input.limit !== undefined ? { limit: input.limit } : {}),
932
+ context,
933
+ });
934
+ if (result.status !== "ok") {
935
+ return { status: "unavailable", merchant_id: merchantId, reason: result.reason };
936
+ }
937
+ return { status: "ok", merchant_id: merchantId, candidates: result.candidates };
938
+ }
606
939
  // ---- Northbound:kiwi_get_task --------------------------------------------
607
940
  getTask(taskId) {
608
941
  const task = this.taskFor(taskId);
@@ -633,6 +966,13 @@ export class KiwiBuyerService {
633
966
  if (task.expires_at !== undefined && Date.parse(task.expires_at) < Date.parse(this.now())) {
634
967
  throw new McpError("task_expired", `task ${input.task_id} expired`);
635
968
  }
969
+ const taskCandidates = this.store.listCandidates(input.task_id);
970
+ const eligibleTargets = taskCandidates.filter(candidate => candidate.status === "succeeded" || asRecord(candidate.provenance).a2a_endpoint !== undefined);
971
+ if (!input.candidate_id && eligibleTargets.length > 1)
972
+ throw new McpError("invalid_params", "TARGET_REQUIRED");
973
+ if (input.candidate_id && !eligibleTargets.some(candidate => candidate.candidate_id === input.candidate_id)) {
974
+ throw new McpError("invalid_params", "TARGET_REQUIRED");
975
+ }
636
976
  const rounds = this.currentRounds(task);
637
977
  const maxRounds = this.policy.limits?.max_rounds ?? 3;
638
978
  if (input.action === "counter_offer") {
@@ -672,12 +1012,16 @@ export class KiwiBuyerService {
672
1012
  ? { questions: normalizeClarificationQuestions(input.questions, input.summary) }
673
1013
  : {}),
674
1014
  };
1015
+ let gated = input.candidate_id ? eligibleTargets.filter(candidate => candidate.candidate_id === input.candidate_id) : taskCandidates;
1016
+ const allowedMerchants = this.policy.limits?.allowed_merchants;
1017
+ if (gated.length === 1 && allowedMerchants && !allowedMerchants.includes(String(gated[0].merchant_id))) {
1018
+ throw new McpError("delegation_denied", "该商家超出委托范围。");
1019
+ }
675
1020
  if (this.negotiator !== undefined) {
676
1021
  // review P1-2(A316 补充校准):counter 外发前的限额闸口——succeeded
677
1022
  // 候选逐一过 limitViolation(结构化事实),仅放行未被约束阻断的候选;
678
1023
  // 全部被阻断时显式拒绝(不存在合法还价对象)。clarification 无商业
679
1024
  // 承诺,不过商业闸。
680
- let gated = this.store.listCandidates(input.task_id);
681
1025
  if (input.action === "counter_offer") {
682
1026
  const succeeded = gated.filter((c) => c.status === "succeeded");
683
1027
  const passable = succeeded.filter((c) => this.limitViolation("counter_offer", {
@@ -702,12 +1046,24 @@ export class KiwiBuyerService {
702
1046
  constraints: {
703
1047
  ...(intent.constraints ?? {}),
704
1048
  target_unit_price: explicitTarget,
1049
+ ...(input.procurement_price_basis ? { kiwi_procurement_target_price_basis: input.procurement_price_basis } : {}),
705
1050
  },
706
1051
  };
707
1052
  // 商业闸通过后才占用槽位(被委托阻断的调用不消耗轮次)。
708
1053
  reservedSlot = this.store.reserveNegotiationSlot(input.task_id, slotKind, maxRounds);
709
1054
  step = { ...step, round: reservedSlot };
710
- step = await this.negotiator.negotiate(input.task_id, intentForNegotiator, step, gated, this.protocolContext(task));
1055
+ input.onReserved?.(reservedSlot);
1056
+ try {
1057
+ step = await this.negotiator.negotiate(input.task_id, intentForNegotiator, step, gated, { ...this.protocolContext(task), beforeSend: input.beforeSend });
1058
+ }
1059
+ catch (error) {
1060
+ // Only a confirmed pre-dispatch refusal can safely release the reserved round.
1061
+ if (error instanceof McpError && error.code === "clarification_needed" &&
1062
+ error.detail?.requestSent === false) {
1063
+ this.store.releaseNegotiationSlot(input.task_id, slotKind, reservedSlot);
1064
+ }
1065
+ throw error;
1066
+ }
711
1067
  }
712
1068
  else {
713
1069
  // 无外发 negotiator(本地确定性模式)同样占用槽位:跨进程并发也不
@@ -715,12 +1071,25 @@ export class KiwiBuyerService {
715
1071
  reservedSlot = this.store.reserveNegotiationSlot(input.task_id, slotKind, maxRounds);
716
1072
  step = { ...step, round: reservedSlot };
717
1073
  }
1074
+ return this.recordNegotiationStep(input.task_id, step, slotKind, reservedSlot, input.expected_offer_digest);
1075
+ }
1076
+ recordNegotiationStep(taskId, step, action, round, expectedDigest) {
718
1077
  return this.store.transaction(() => {
1078
+ const latest = this.taskFor(taskId);
1079
+ if (latest === undefined)
1080
+ throw new McpError("task_not_found", `task ${taskId} not found`);
1081
+ const latestDecoded = this.decodeTask(latest);
1082
+ const prior = Array.isArray(latestDecoded.steps) ? latestDecoded.steps : [];
1083
+ const recorded = prior.find(value => value.action === step.action && value.round === step.round);
1084
+ if (recorded)
1085
+ return { task: latestDecoded, step: recorded };
719
1086
  // 商家最新 offer-like 回复必须回写候选:否则 get_task 仍显示上一轮价,
720
1087
  // accept 也会绑定旧候选(2026-10-30 保温杯会话:接受 ¥151.05,协议
721
1088
  // digest 却指向 ¥159 初始报价)。
722
- if (step.merchant_offer !== undefined) {
723
- this.store.updateCandidateOffer(input.task_id, step.merchant_offer.candidate_id, {
1089
+ const update = step.merchant_offer;
1090
+ const candidate = update && this.store.listCandidates(taskId).find(entry => entry.candidate_id === update.candidate_id);
1091
+ if (step.merchant_offer !== undefined && (!expectedDigest || asRecord(candidate?.provenance).latest_terms_digest === expectedDigest)) {
1092
+ this.store.updateCandidateOffer(taskId, step.merchant_offer.candidate_id, {
724
1093
  offer_id: step.merchant_offer.offer_id,
725
1094
  merchant_reply_id: step.merchant_offer.reply_message_id,
726
1095
  reply_text: step.merchant_offer.reply_text,
@@ -732,18 +1101,11 @@ export class KiwiBuyerService {
732
1101
  }
733
1102
  // 并发下相邻槽位预留不改 payload;仍以事务内最新任务合并,避免覆盖
734
1103
  // 其他完成步骤。落步成功即释放本槽位(步本身开始计入轮次)。
735
- if (reservedSlot !== undefined) {
736
- this.store.releaseNegotiationSlot(input.task_id, slotKind, reservedSlot);
1104
+ if (round !== undefined) {
1105
+ this.store.releaseNegotiationSlot(taskId, action, round);
737
1106
  }
738
- const latest = this.taskFor(input.task_id);
739
- if (latest === undefined)
740
- throw new McpError("task_not_found", `task ${input.task_id} not found`);
741
- const latestDecoded = this.decodeTask(latest);
742
- const prior = Array.isArray(latestDecoded.steps)
743
- ? latestDecoded.steps
744
- : [];
745
1107
  const currentStatus = typeof latestDecoded.status === "string" ? latestDecoded.status : "in_progress";
746
- const updated = this.store.updateTask(input.task_id, {
1108
+ const updated = this.store.updateTask(taskId, {
747
1109
  status: currentStatus === "pending" ? "in_progress" : currentStatus,
748
1110
  payload: JSON.stringify({
749
1111
  ...latestDecoded,
@@ -810,11 +1172,16 @@ export class KiwiBuyerService {
810
1172
  if (acceptedTermsDigest(preCandidate) !== termsDigest) {
811
1173
  throw new McpError("approval_denied", "候选条款已变化,需重新获取报价");
812
1174
  }
1175
+ const provenance = asRecord(preCandidate.provenance);
1176
+ const isA2A = typeof provenance.a2a_endpoint === "string" && provenance.a2a_endpoint !== "";
1177
+ if (isA2A)
1178
+ assertGenericA2AAcceptTerms(provenance);
1179
+ else
1180
+ assertNoAlipayAccept(provenance.latest_agreed_terms);
813
1181
  const existingAgreement = this.store.findAgreementByTerms(input.task_id, termsDigest);
814
1182
  let merchantAgreement;
1183
+ let receiptBinding;
815
1184
  if (existingAgreement === undefined) {
816
- const provenance = preCandidate.provenance ?? {};
817
- const isA2A = typeof provenance.a2a_endpoint === "string" && provenance.a2a_endpoint !== "";
818
1185
  if (isA2A) {
819
1186
  // A2A must receive the merchant's agreement artifact. An offer-like
820
1187
  // reply that is not a conditional_offer cannot be remotely accepted by
@@ -826,7 +1193,7 @@ export class KiwiBuyerService {
826
1193
  // accept_nonbinding object as a conditional_offer (conditions: []).
827
1194
  // Both are remote-acceptable; do not require a synthetic conditional
828
1195
  // round or a price change just to obtain the merchant agreement.
829
- if (provenance.latest_offer_type !== "conditional_offer" && provenance.latest_offer_type !== "offer" && provenance.latest_offer_type !== "counter_offer" && provenance.latest_offer_type !== "counter_offer") {
1196
+ if (provenance.latest_offer_type !== "conditional_offer" && provenance.latest_offer_type !== "offer" && provenance.latest_offer_type !== "counter_offer") {
830
1197
  throw new McpError("invalid_params", "A2A candidate latest reply is not an acceptable offer/conditional_offer; refusing to create a local agreement");
831
1198
  }
832
1199
  const accepted = await this.negotiator.acceptNonbinding({
@@ -852,7 +1219,9 @@ export class KiwiBuyerService {
852
1219
  || !checkedAgreement.accepted_by.includes("merchant")) {
853
1220
  throw new McpError("internal_error", "A2A merchant agreement is not bound to the accepted terms; reconciliation required", { reconciliation_required: true, merchant_agreement: accepted.agreement });
854
1221
  }
1222
+ assertGenericA2AAgreement(checkedAgreement);
855
1223
  merchantAgreement = checkedAgreement;
1224
+ receiptBinding = accepted.receiptBinding;
856
1225
  }
857
1226
  }
858
1227
  // review P1-2(A316 校准):短事务原子消费——事务内重读授权、写
@@ -1004,7 +1373,34 @@ export class KiwiBuyerService {
1004
1373
  });
1005
1374
  }
1006
1375
  }
1007
- return { task: this.decodeTask(updated), agreement, authorization };
1376
+ const committed = { task: this.decodeTask(updated), agreement, authorization };
1377
+ // K5:本地协议已提交且含有效 merchant_agreement → 上报“协议已接受
1378
+ // 并提交”。纯本地候选(无 merchant_agreement)不入队;上报失败不
1379
+ // 阻塞业务(outbox 退避重试,同 event_id 幂等补报)。
1380
+ const receipts = this.commerceReceipts;
1381
+ if (receipts !== undefined && merchantAgreement !== undefined && receiptBinding === receipts.binding) {
1382
+ const merchantAgreementId = String(merchantAgreement.agreement_id ?? "");
1383
+ const provenance = candidate.provenance;
1384
+ if (merchantAgreementId !== "" &&
1385
+ typeof provenance?.negotiation_id === "string" &&
1386
+ typeof provenance.offer_id === "string") {
1387
+ const intent = {
1388
+ event_id: `buyer-agreement:${agreementId}`,
1389
+ event_type: "buyer_agreement_accepted",
1390
+ merchant_id: String(candidate.merchant_id),
1391
+ negotiation_id: provenance.negotiation_id,
1392
+ merchant_agreement_id: merchantAgreementId,
1393
+ accepted_offer_id: provenance.offer_id,
1394
+ terms_digest: termsDigest,
1395
+ buyer_binding: receipts.binding,
1396
+ occurred_at: now,
1397
+ };
1398
+ this.store.setAgreementReceiptBinding(agreementId, receiptBinding);
1399
+ receipts.dispatcher.record(intent);
1400
+ receipts.dispatcher.kick();
1401
+ }
1402
+ }
1403
+ return committed;
1008
1404
  });
1009
1405
  }
1010
1406
  // ---- Northbound:kiwi_get_agreement ---------------------------------------
@@ -1021,6 +1417,18 @@ export class KiwiBuyerService {
1021
1417
  if (stored === undefined) {
1022
1418
  throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
1023
1419
  }
1420
+ // Generic hosts cannot privately display this collection. Classify the stored
1421
+ // agreement independently of the requested type/URL, including legacy term shapes.
1422
+ const rejectCollectionHandoff = (agreement) => {
1423
+ const payload = this.parsePayload(agreement.payload);
1424
+ const merchant = asRecord(payload.merchant_agreement);
1425
+ if (isAlipayCollectionDestination(input.url) ||
1426
+ isAlipayCollectionAgreement(payload.agreed_terms, payload.handoff_destination) ||
1427
+ isAlipayCollectionAgreement(merchant.agreed_terms, merchant.handoff_destination)) {
1428
+ throw new McpError("authorization_denied", ALIPAY_PRIVATE_DISPLAY_REQUIRED);
1429
+ }
1430
+ };
1431
+ rejectCollectionHandoff(stored);
1024
1432
  // URL 类目的地未显式给 url 时,回落到商家报价里的 handoff_destination:
1025
1433
  // 商家已经给出了真实购买入口,宿主无需(也常无法)猜一个 URL。
1026
1434
  let resolvedUrl = input.url;
@@ -1058,12 +1466,16 @@ export class KiwiBuyerService {
1058
1466
  throw new McpError("authorization_denied", "Handoff 未获五层授权", { authorization });
1059
1467
  }
1060
1468
  if (input.approval_id === undefined) {
1061
- const handoffRef = {
1062
- handoff_id: `handoff-${uuidv7()}`,
1063
- destination_type: destination.destination_type,
1064
- ...(destination.url !== null ? { url: destination.url } : {}),
1065
- };
1066
- return { handoff_ref: handoffRef, authorization };
1469
+ return this.store.transaction(() => {
1470
+ const handoffId = this.store.rememberHandoff(input.agreement_id, consumedBinding, `handoff-${uuidv7()}`);
1471
+ const handoffRef = {
1472
+ handoff_id: handoffId,
1473
+ destination_type: destination.destination_type,
1474
+ ...(destination.url !== null ? { url: destination.url } : {}),
1475
+ };
1476
+ this.enqueueHandoffReceipt(stored, handoffId);
1477
+ return { handoff_ref: handoffRef, authorization };
1478
+ });
1067
1479
  }
1068
1480
  // review P1-2(A316 校准):短事务原子消费——事务内重读审批、生成 ref、
1069
1481
  // 消费;同绑定重放返回**库里记录的同一 ref**(非虚构);失败 ROLLBACK
@@ -1083,6 +1495,7 @@ export class KiwiBuyerService {
1083
1495
  if (freshAgreement === undefined) {
1084
1496
  throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
1085
1497
  }
1498
+ rejectCollectionHandoff(freshAgreement);
1086
1499
  this.assertHandoffIntentMatches({
1087
1500
  approval,
1088
1501
  task: freshTask,
@@ -1092,6 +1505,8 @@ export class KiwiBuyerService {
1092
1505
  if (approval.status === "used") {
1093
1506
  const consumed = this.approvalConsumed(approval);
1094
1507
  if (consumed !== undefined && consumed.binding === consumedBinding) {
1508
+ // K6:重放返回库中同一 ref——补报同一 event_id(Catalog 幂等吸收)。
1509
+ this.enqueueHandoffReceipt(freshAgreement, consumed.ref);
1095
1510
  return {
1096
1511
  handoff_ref: {
1097
1512
  handoff_id: consumed.ref,
@@ -1116,9 +1531,64 @@ export class KiwiBuyerService {
1116
1531
  consumed: { ref: handoffRef.handoff_id, binding: consumedBinding, kind: "handoff" },
1117
1532
  }),
1118
1533
  });
1534
+ // K6:交接审批消费、handoff_ref 实际生成 → 上报“已生成交接记录”。
1535
+ this.enqueueHandoffReceipt(freshAgreement, handoffRef.handoff_id);
1119
1536
  return { handoff_ref: handoffRef, authorization };
1120
1537
  });
1121
1538
  }
1539
+ /**
1540
+ * K6:交接事实上报(被拒绝的审批与未实际生成的交接不会走到这里)。
1541
+ * 引用取自协议(磋商号 + 被接受报价 + 条款摘要);event_id 绑定
1542
+ * handoff_id(稳定、可重放);上报失败不阻塞交接。
1543
+ */
1544
+ enqueueHandoffReceipt(storedAgreement, handoffId) {
1545
+ const receipts = this.commerceReceipts;
1546
+ if (receipts === undefined)
1547
+ return;
1548
+ try {
1549
+ const payload = JSON.parse(storedAgreement.payload);
1550
+ if (typeof payload.agreement_id !== "string" ||
1551
+ this.store.agreementReceiptBinding(payload.agreement_id) !== receipts.binding)
1552
+ return;
1553
+ const merchantAgreementId = String(payload.merchant_agreement?.agreement_id ?? "");
1554
+ const negotiationId = typeof payload.negotiation_id === "string" ? payload.negotiation_id : undefined;
1555
+ if (merchantAgreementId === "" || negotiationId === undefined)
1556
+ return;
1557
+ let offerId;
1558
+ let merchantId;
1559
+ if (typeof payload.task_id === "string") {
1560
+ const candidate = this.store
1561
+ .listCandidates(payload.task_id)
1562
+ .find((c) => c.candidate_id === payload.accepted_candidate_id);
1563
+ const provenance = candidate?.provenance;
1564
+ if (typeof provenance?.offer_id === "string")
1565
+ offerId = provenance.offer_id;
1566
+ if (typeof candidate?.merchant_id === "string")
1567
+ merchantId = candidate.merchant_id;
1568
+ }
1569
+ if (merchantId === undefined || offerId === undefined)
1570
+ return;
1571
+ receipts.dispatcher.record({
1572
+ event_id: `buyer-handoff:${handoffId}`,
1573
+ event_type: "buyer_handoff_generated",
1574
+ merchant_id: merchantId,
1575
+ entry_type: "handoff_record",
1576
+ quote_ref: {
1577
+ negotiation_id: negotiationId,
1578
+ // 设计要求报价引用含磋商号与报价号;缺报价号(历史窗口)宁可少报。
1579
+ offer_id: offerId ?? "",
1580
+ ...(typeof payload.terms_digest === "string" ? { terms_digest: payload.terms_digest } : {}),
1581
+ },
1582
+ handoff_ref: handoffId,
1583
+ occurred_at: this.now(),
1584
+ });
1585
+ receipts.dispatcher.kick();
1586
+ }
1587
+ catch (error) {
1588
+ if (!(error instanceof SyntaxError))
1589
+ throw error;
1590
+ }
1591
+ }
1122
1592
  // ---- 持久审批(宿主适配面;kiwi_approve / kiwi_reject 为 MCP 工具)----------
1123
1593
  // ---- A 卡:handoff 意图(版本化、摘要不含自身、与 approval 同事务)----------
1124
1594
  /** 目的地归一:类型词表校验 + URL 归一(http/https、无凭据、无 fragment)。 */
@@ -1824,8 +2294,6 @@ export class KiwiBuyerService {
1824
2294
  * 目录暂不可达时不改变既有行为(跳过本门,走 fetcher 的部分失败语义)。
1825
2295
  */
1826
2296
  async assertInquiryAvailable(merchantIds) {
1827
- if (merchantIds === undefined || merchantIds.length === 0)
1828
- return;
1829
2297
  const index = this.merchantIndex;
1830
2298
  if (index === undefined)
1831
2299
  return;