@harrylabsj/kiwi-merchant-cloud 0.12.32 → 0.12.34

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 (264) hide show
  1. package/app/a2a/inquiry-nonce-store.d.ts +12 -1
  2. package/app/a2a/inquiry-nonce-store.js +49 -17
  3. package/app/a2a/inquiry-nonce-store.js.map +1 -1
  4. package/app/a2a/negotiate.d.ts +30 -1
  5. package/app/a2a/negotiate.js +121 -32
  6. package/app/a2a/negotiate.js.map +1 -1
  7. package/app/a2a/node.d.ts +3 -0
  8. package/app/a2a/node.js +13 -3
  9. package/app/a2a/node.js.map +1 -1
  10. package/app/a2a/open-inquiry-session.d.ts +1 -0
  11. package/app/a2a/open-inquiry-session.js +3 -1
  12. package/app/a2a/open-inquiry-session.js.map +1 -1
  13. package/app/a2a/open-inquiry-verifier.js +2 -2
  14. package/app/a2a/open-inquiry-verifier.js.map +1 -1
  15. package/app/a2a/server/errors.d.ts +4 -3
  16. package/app/a2a/server/errors.js +10 -2
  17. package/app/a2a/server/errors.js.map +1 -1
  18. package/app/a2a/server/merchant-handler.d.ts +41 -1
  19. package/app/a2a/server/merchant-handler.js +259 -89
  20. package/app/a2a/server/merchant-handler.js.map +1 -1
  21. package/app/a2a/server/merchant-procurement.d.ts +90 -0
  22. package/app/a2a/server/merchant-procurement.js +75 -0
  23. package/app/a2a/server/merchant-procurement.js.map +1 -0
  24. package/app/a2a/server/merchant-product-facts.d.ts +2 -0
  25. package/app/a2a/server/merchant-product-facts.js.map +1 -1
  26. package/app/a2a/server/negotiation-approvals.d.ts +11 -0
  27. package/app/a2a/server/negotiation-approvals.js +43 -0
  28. package/app/a2a/server/negotiation-approvals.js.map +1 -1
  29. package/app/a2a/server/pipeline.js +4 -1
  30. package/app/a2a/server/pipeline.js.map +1 -1
  31. package/app/a2a/server/server.js +4 -3
  32. package/app/a2a/server/server.js.map +1 -1
  33. package/app/a2a/server/types.d.ts +2 -1
  34. package/app/agent/alipay-native-view.d.ts +27 -0
  35. package/app/agent/alipay-native-view.js +113 -0
  36. package/app/agent/alipay-native-view.js.map +1 -0
  37. package/app/agent/buyer/buyer-tools.d.ts +20 -0
  38. package/app/agent/buyer/buyer-tools.js +241 -48
  39. package/app/agent/buyer/buyer-tools.js.map +1 -1
  40. package/app/agent/buyer/types.d.ts +1 -1
  41. package/app/agent/buyer/types.js.map +1 -1
  42. package/app/agent/chat-tui.js +16 -1
  43. package/app/agent/chat-tui.js.map +1 -1
  44. package/app/agent/kernel-builder.d.ts +2 -0
  45. package/app/agent/kernel-builder.js +14 -0
  46. package/app/agent/kernel-builder.js.map +1 -1
  47. package/app/agent/kernel.d.ts +8 -0
  48. package/app/agent/kernel.js +67 -1
  49. package/app/agent/kernel.js.map +1 -1
  50. package/app/buyer-core/a2a-accept-terms.d.ts +11 -0
  51. package/app/buyer-core/a2a-accept-terms.js +28 -0
  52. package/app/buyer-core/a2a-accept-terms.js.map +1 -0
  53. package/app/buyer-core/a2a-knp.d.ts +3 -0
  54. package/app/buyer-core/a2a-knp.js +3 -3
  55. package/app/buyer-core/a2a-knp.js.map +1 -1
  56. package/app/buyer-core/a2a-negotiator.d.ts +16 -0
  57. package/app/buyer-core/a2a-negotiator.js +53 -16
  58. package/app/buyer-core/a2a-negotiator.js.map +1 -1
  59. package/app/buyer-core/a2a-quote-fetcher.d.ts +0 -15
  60. package/app/buyer-core/a2a-quote-fetcher.js +10 -15
  61. package/app/buyer-core/a2a-quote-fetcher.js.map +1 -1
  62. package/app/buyer-core/merchant-index.d.ts +2 -2
  63. package/app/buyer-core/merchant-index.js +23 -5
  64. package/app/buyer-core/merchant-index.js.map +1 -1
  65. package/app/buyer-core/procurement/cases.d.ts +441 -0
  66. package/app/buyer-core/procurement/cases.js +457 -0
  67. package/app/buyer-core/procurement/cases.js.map +1 -0
  68. package/app/buyer-core/procurement/quote-comparison.d.ts +137 -0
  69. package/app/buyer-core/procurement/quote-comparison.js +106 -0
  70. package/app/buyer-core/procurement/quote-comparison.js.map +1 -0
  71. package/app/buyer-core/procurement/quote-normalizer.d.ts +45 -0
  72. package/app/buyer-core/procurement/quote-normalizer.js +153 -0
  73. package/app/buyer-core/procurement/quote-normalizer.js.map +1 -0
  74. package/app/buyer-core/procurement/requirements.d.ts +50 -0
  75. package/app/buyer-core/procurement/requirements.js +43 -0
  76. package/app/buyer-core/procurement/requirements.js.map +1 -0
  77. package/app/buyer-core/procurement/source-observation.d.ts +57 -0
  78. package/app/buyer-core/procurement/source-observation.js +54 -0
  79. package/app/buyer-core/procurement/source-observation.js.map +1 -0
  80. package/app/buyer-core/procurement/store.d.ts +21 -0
  81. package/app/buyer-core/procurement/store.js +68 -0
  82. package/app/buyer-core/procurement/store.js.map +1 -0
  83. package/app/buyer-core/protocol-recovery.d.ts +8 -0
  84. package/app/buyer-core/protocol-recovery.js +17 -2
  85. package/app/buyer-core/protocol-recovery.js.map +1 -1
  86. package/app/buyer-core/quote-quantity.d.ts +5 -0
  87. package/app/buyer-core/quote-quantity.js +15 -0
  88. package/app/buyer-core/quote-quantity.js.map +1 -0
  89. package/app/buyer-core/service.d.ts +71 -3
  90. package/app/buyer-core/service.js +271 -28
  91. package/app/buyer-core/service.js.map +1 -1
  92. package/app/buyer-core/store.d.ts +13 -0
  93. package/app/buyer-core/store.js +25 -3
  94. package/app/buyer-core/store.js.map +1 -1
  95. package/app/cli.js +13 -17
  96. package/app/cli.js.map +1 -1
  97. package/app/cloud/alipay-collection-http.d.ts +44 -0
  98. package/app/cloud/alipay-collection-http.js +111 -0
  99. package/app/cloud/alipay-collection-http.js.map +1 -0
  100. package/app/cloud/bootstrap.js +98 -12
  101. package/app/cloud/bootstrap.js.map +1 -1
  102. package/app/cloud/http-router.d.ts +2 -0
  103. package/app/cloud/http-router.js +5 -0
  104. package/app/cloud/http-router.js.map +1 -1
  105. package/app/cloud-sample/products.json +3 -3
  106. package/app/commerce/receipt/dispatcher.d.ts +2 -1
  107. package/app/commerce/receipt/dispatcher.js +18 -0
  108. package/app/commerce/receipt/dispatcher.js.map +1 -1
  109. package/app/commerce/receipt/receipts.d.ts +7 -0
  110. package/app/commerce/receipt/receipts.js +43 -5
  111. package/app/commerce/receipt/receipts.js.map +1 -1
  112. package/app/discovery/catalog-source/buyer-follows.d.ts +3 -3
  113. package/app/discovery/catalog-source/buyer-follows.js +6 -3
  114. package/app/discovery/catalog-source/buyer-follows.js.map +1 -1
  115. package/app/discovery/catalog-source/kiwi-record.d.ts +2 -0
  116. package/app/discovery/catalog-source/kiwi-record.js.map +1 -1
  117. package/app/discovery/catalog-source/kiwi-source.js +4 -0
  118. package/app/discovery/catalog-source/kiwi-source.js.map +1 -1
  119. package/app/handoff/alipay-collection.d.ts +23 -0
  120. package/app/handoff/alipay-collection.js +70 -0
  121. package/app/handoff/alipay-collection.js.map +1 -0
  122. package/app/handoff/order-receipts.js +2 -1
  123. package/app/handoff/order-receipts.js.map +1 -1
  124. package/app/handoff/ucp-checkout/channel.d.ts +1 -0
  125. package/app/handoff/ucp-checkout/channel.js +42 -17
  126. package/app/handoff/ucp-checkout/channel.js.map +1 -1
  127. package/app/http/customer-support-buyer.d.ts +24 -0
  128. package/app/http/customer-support-buyer.js +306 -0
  129. package/app/http/customer-support-buyer.js.map +1 -0
  130. package/app/http/merchant-management/api.d.ts +12 -0
  131. package/app/http/merchant-management/api.js +425 -6
  132. package/app/http/merchant-management/api.js.map +1 -1
  133. package/app/http/merchant-management/page.d.ts +2 -0
  134. package/app/http/merchant-management/page.js +630 -3
  135. package/app/http/merchant-management/page.js.map +1 -1
  136. package/app/http/server.js +9 -2
  137. package/app/http/server.js.map +1 -1
  138. package/app/mcp/cli.d.ts +3 -1
  139. package/app/mcp/cli.js +12 -2
  140. package/app/mcp/cli.js.map +1 -1
  141. package/app/mcp/merchant-runtime-assembly.d.ts +3 -0
  142. package/app/mcp/merchant-runtime-assembly.js +9 -8
  143. package/app/mcp/merchant-runtime-assembly.js.map +1 -1
  144. package/app/mcp/procurement-tools.d.ts +10 -0
  145. package/app/mcp/procurement-tools.js +173 -0
  146. package/app/mcp/procurement-tools.js.map +1 -0
  147. package/app/mcp/server.d.ts +4 -0
  148. package/app/mcp/server.js +63 -9
  149. package/app/mcp/server.js.map +1 -1
  150. package/app/mcp/tools.d.ts +4 -1
  151. package/app/mcp/tools.js +76 -27
  152. package/app/mcp/tools.js.map +1 -1
  153. package/app/mcp/types.d.ts +1 -0
  154. package/app/mcp/types.js.map +1 -1
  155. package/app/merchant/ai-runtime/owner-storage-admission.js.map +1 -1
  156. package/app/merchant/application/actor.d.ts +2 -0
  157. package/app/merchant/application/actor.js +6 -0
  158. package/app/merchant/application/actor.js.map +1 -1
  159. package/app/merchant/negotiation-ops.d.ts +2 -0
  160. package/app/merchant/negotiation-ops.js +4 -0
  161. package/app/merchant/negotiation-ops.js.map +1 -1
  162. package/app/merchant/weixin-channel.d.ts +224 -0
  163. package/app/merchant/weixin-channel.js +435 -0
  164. package/app/merchant/weixin-channel.js.map +1 -0
  165. package/app/merchant/weixin-owner-agent-profile.d.ts +8 -0
  166. package/app/merchant/weixin-owner-agent-profile.js +29 -0
  167. package/app/merchant/weixin-owner-agent-profile.js.map +1 -0
  168. package/app/merchant/weixin-owner-agent.d.ts +42 -0
  169. package/app/merchant/weixin-owner-agent.js +97 -0
  170. package/app/merchant/weixin-owner-agent.js.map +1 -0
  171. package/app/merchant/weixin-owner-conversation.d.ts +156 -0
  172. package/app/merchant/weixin-owner-conversation.js +559 -0
  173. package/app/merchant/weixin-owner-conversation.js.map +1 -0
  174. package/app/merchant/weixin-owner-digest.d.ts +30 -0
  175. package/app/merchant/weixin-owner-digest.js +30 -0
  176. package/app/merchant/weixin-owner-digest.js.map +1 -0
  177. package/app/merchant/weixin-owner-inventory.d.ts +28 -0
  178. package/app/merchant/weixin-owner-inventory.js +48 -0
  179. package/app/merchant/weixin-owner-inventory.js.map +1 -0
  180. package/app/merchant/weixin-owner-source.d.ts +22 -0
  181. package/app/merchant/weixin-owner-source.js +104 -0
  182. package/app/merchant/weixin-owner-source.js.map +1 -0
  183. package/app/merchant/workbench-server.d.ts +4 -0
  184. package/app/merchant/workbench-server.js +75 -9
  185. package/app/merchant/workbench-server.js.map +1 -1
  186. package/app/merchant-core/collection/alipay-store.d.ts +22 -0
  187. package/app/merchant-core/collection/alipay-store.js +125 -0
  188. package/app/merchant-core/collection/alipay-store.js.map +1 -0
  189. package/app/merchant-core/commercial/calculate.js +6 -6
  190. package/app/merchant-core/commercial/calculate.js.map +1 -1
  191. package/app/merchant-core/operating/repository.d.ts +0 -1
  192. package/app/merchant-core/operating/repository.js +2 -17
  193. package/app/merchant-core/operating/repository.js.map +1 -1
  194. package/app/merchant-core/operations-jobs/service.d.ts +11 -0
  195. package/app/merchant-core/operations-jobs/service.js +65 -34
  196. package/app/merchant-core/operations-jobs/service.js.map +1 -1
  197. package/app/merchant-core/opportunity/repository.d.ts +0 -1
  198. package/app/merchant-core/opportunity/repository.js +2 -17
  199. package/app/merchant-core/opportunity/repository.js.map +1 -1
  200. package/app/merchant-core/ops/surface.d.ts +1 -0
  201. package/app/merchant-core/ops/surface.js +9 -0
  202. package/app/merchant-core/ops/surface.js.map +1 -1
  203. package/app/merchant-core/orders/model.d.ts +1 -8
  204. package/app/merchant-core/orders/model.js +10 -2
  205. package/app/merchant-core/orders/model.js.map +1 -1
  206. package/app/merchant-core/orders/repository.d.ts +0 -1
  207. package/app/merchant-core/orders/repository.js +3 -18
  208. package/app/merchant-core/orders/repository.js.map +1 -1
  209. package/app/merchant-core/orders/service.js +34 -8
  210. package/app/merchant-core/orders/service.js.map +1 -1
  211. package/app/merchant-core/proposal/engine.js +2 -0
  212. package/app/merchant-core/proposal/engine.js.map +1 -1
  213. package/app/merchant-core/proposal/publish.d.ts +0 -6
  214. package/app/merchant-core/proposal/publish.js +37 -3
  215. package/app/merchant-core/proposal/publish.js.map +1 -1
  216. package/app/merchant-core/proposal/repository.d.ts +0 -7
  217. package/app/merchant-core/proposal/repository.js +8 -17
  218. package/app/merchant-core/proposal/repository.js.map +1 -1
  219. package/app/merchant-core/proposal/types.d.ts +1 -0
  220. package/app/merchant-core/proposal/types.js.map +1 -1
  221. package/app/merchant-core/rfq/policy.d.ts +1 -0
  222. package/app/merchant-core/rfq/policy.js +6 -7
  223. package/app/merchant-core/rfq/policy.js.map +1 -1
  224. package/app/merchant-core/rfq/repository.d.ts +0 -1
  225. package/app/merchant-core/rfq/repository.js +2 -17
  226. package/app/merchant-core/rfq/repository.js.map +1 -1
  227. package/app/merchant-core/rfq/service.d.ts +2 -1
  228. package/app/merchant-core/rfq/service.js +2 -4
  229. package/app/merchant-core/rfq/service.js.map +1 -1
  230. package/app/merchant-core/storage/transaction.d.ts +4 -11
  231. package/app/merchant-core/storage/transaction.js +43 -65
  232. package/app/merchant-core/storage/transaction.js.map +1 -1
  233. package/app/merchant-core/support/manual-service.d.ts +114 -0
  234. package/app/merchant-core/support/manual-service.js +300 -0
  235. package/app/merchant-core/support/manual-service.js.map +1 -0
  236. package/app/negotiation/domain/objects.d.ts +2 -0
  237. package/app/negotiation/domain/objects.js +3 -0
  238. package/app/negotiation/domain/objects.js.map +1 -1
  239. package/app/negotiation/ledger/store.d.ts +6 -0
  240. package/app/negotiation/ledger/store.js +28 -0
  241. package/app/negotiation/ledger/store.js.map +1 -1
  242. package/app/net/safe-http.d.ts +2 -0
  243. package/app/net/safe-http.js +1 -1
  244. package/app/net/safe-http.js.map +1 -1
  245. package/app/product-init.d.ts +1 -0
  246. package/app/product-init.js +4 -1
  247. package/app/product-init.js.map +1 -1
  248. package/app/trust/identity/message-signature.d.ts +1 -1
  249. package/app/trust/identity/message-signature.js +6 -1
  250. package/app/trust/identity/message-signature.js.map +1 -1
  251. package/app/trust/identity/nonce.d.ts +5 -0
  252. package/app/trust/identity/nonce.js +2 -0
  253. package/app/trust/identity/nonce.js.map +1 -1
  254. package/app/weixin/ilink-client.d.ts +3 -2
  255. package/app/weixin/ilink-client.js +58 -20
  256. package/app/weixin/ilink-client.js.map +1 -1
  257. package/app/weixin/types.d.ts +3 -1
  258. package/app/weixin/types.js.map +1 -1
  259. package/build-manifest.json +731 -386
  260. package/deployment-lock.json +85 -77
  261. package/package.json +7 -7
  262. package/runtime-package.json +13 -13
  263. package/shipping-sbom.cdx.json +150 -145
  264. package/shipping-source.json +12 -12
@@ -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 处理(向后兼容)。 */
@@ -178,6 +184,7 @@ export class KiwiBuyerService {
178
184
  wakeAttemptAt = new Map();
179
185
  wakeInFlight = new Map();
180
186
  now;
187
+ procurement;
181
188
  constructor(options) {
182
189
  this.store = options.store;
183
190
  this.principal = options.principal;
@@ -200,6 +207,191 @@ export class KiwiBuyerService {
200
207
  this.staleWake = options.staleWake;
201
208
  this.staleWakeTimeoutMs = options.staleWakeTimeoutMs ?? 5000;
202
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
+ }
203
395
  /**
204
396
  * Per-merchant singleflight + 60s cooldown. The probe never updates catalog
205
397
  * state; only a subsequent catalog read showing a merchant heartbeat may
@@ -361,8 +553,8 @@ export class KiwiBuyerService {
361
553
  return { follows };
362
554
  }
363
555
  /** 主动拉取关注更新(仅响应买家主动询问;事件仅为商家公开动态)。 */
364
- async getFollowUpdates() {
365
- const updates = await this.withFollows((client) => client.getUpdates());
556
+ async getFollowUpdates(watermarks) {
557
+ const updates = await this.withFollows((client) => client.getUpdates(watermarks));
366
558
  return { updates };
367
559
  }
368
560
  requireMerchantId(raw) {
@@ -395,15 +587,21 @@ export class KiwiBuyerService {
395
587
  // ---- Northbound:kiwi_request_quotes --------------------------------------
396
588
  async requestQuotes(input) {
397
589
  const useHistory = input.reuse_history === true && explicitIntentItemSku(input.intent) === undefined;
398
- if (useHistory && input.merchant_ids?.length !== 1) {
590
+ const merchants = input.merchant_ids ?? [];
591
+ if (useHistory && merchants.length !== 1) {
399
592
  throw new McpError("clarification_needed", "沿用上次规格需要恰好指定一个商家;请说明要沿用哪家店的报价。", {
400
593
  reason: "history_merchant_required",
401
594
  });
402
595
  }
596
+ if (merchants.length === 0) {
597
+ throw new McpError("clarification_needed", "发起询价需要至少指定一个商家;请先从搜索结果中选择可实时询价的商家。", {
598
+ reason: "merchant_required",
599
+ });
600
+ }
403
601
  const idempotencyKey = input.idempotency_key ?? `req-${uuidv7()}`;
404
602
  const requestDigest = contentDigest({
405
603
  intent: input.intent,
406
- merchant_ids: [...new Set(input.merchant_ids ?? [])].sort(),
604
+ merchant_ids: [...new Set(merchants)].sort(),
407
605
  reuse_history: useHistory,
408
606
  });
409
607
  const existing = this.store.findTaskByIdempotencyKey(this.ownerHash, idempotencyKey);
@@ -413,7 +611,7 @@ export class KiwiBuyerService {
413
611
  let effectiveIntent = input.intent;
414
612
  let reusedHistory;
415
613
  if (useHistory) {
416
- const merchantId = input.merchant_ids[0];
614
+ const merchantId = merchants[0];
417
615
  const history = await this.resolveQuoteHistory({ merchant_id: merchantId });
418
616
  if (history.status !== "ok" || history.candidates.length === 0) {
419
617
  throw new McpError("clarification_needed", history.status === "unavailable"
@@ -457,7 +655,8 @@ export class KiwiBuyerService {
457
655
  }
458
656
  // M0 硬门(merchant-buddy 第 0 版 §4/§5):仅有公开资料、无可路由 Agent 的
459
657
  // 商家不得进入 RFQ。服务层显式拒绝(不只靠宿主提示词),在创建任务/消息之前。
460
- await this.assertInquiryAvailable(input.merchant_ids);
658
+ quoteQuantity(effectiveIntent);
659
+ await this.assertInquiryAvailable(merchants);
461
660
  const policyId = this.policy.policy_id;
462
661
  const expiresAt = this.policy.expires_at;
463
662
  const taskId = `task-${uuidv7()}`;
@@ -465,7 +664,7 @@ export class KiwiBuyerService {
465
664
  // 无 fetcher 时记录确定性 fan-out 槽位(§6.2 部分失败可解释);有 fetcher 时
466
665
  // 只写真实结果,不预建槽位,避免候选重复。
467
666
  const preCandidates = this.quoteFetcher === undefined
468
- ? (input.merchant_ids ?? []).map((merchantId) => ({
667
+ ? merchants.map((merchantId) => ({
469
668
  candidate_id: `cand-${uuidv7()}`,
470
669
  merchant_id: merchantId,
471
670
  status: "pending",
@@ -515,7 +714,6 @@ export class KiwiBuyerService {
515
714
  let status = "in_progress";
516
715
  let quotedResults = [];
517
716
  if (this.quoteFetcher !== undefined) {
518
- const merchants = input.merchant_ids ?? [];
519
717
  const index = this.merchantIndex;
520
718
  let dispatchStarted = false;
521
719
  let dispatchOutcomeUnknown = false;
@@ -538,7 +736,7 @@ export class KiwiBuyerService {
538
736
  return { merchant_id: m, name: m, verified: false, capabilities: [] };
539
737
  }));
540
738
  catalogLookupCompleted = true;
541
- const protocolContext = this.protocolContext(persisted, merchants);
739
+ const protocolContext = { ...this.protocolContext(persisted, merchants), beforeSend: input.beforeSend };
542
740
  // 一旦调用 quoteFetcher,就不能把抛错解释成“没发送”:adapter 可能已
543
741
  // 写入/发送部分 RFQ。没有 receipt 时保守落为 non-retryable unknown。
544
742
  dispatchStarted = true;
@@ -768,6 +966,13 @@ export class KiwiBuyerService {
768
966
  if (task.expires_at !== undefined && Date.parse(task.expires_at) < Date.parse(this.now())) {
769
967
  throw new McpError("task_expired", `task ${input.task_id} expired`);
770
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
+ }
771
976
  const rounds = this.currentRounds(task);
772
977
  const maxRounds = this.policy.limits?.max_rounds ?? 3;
773
978
  if (input.action === "counter_offer") {
@@ -807,12 +1012,16 @@ export class KiwiBuyerService {
807
1012
  ? { questions: normalizeClarificationQuestions(input.questions, input.summary) }
808
1013
  : {}),
809
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
+ }
810
1020
  if (this.negotiator !== undefined) {
811
1021
  // review P1-2(A316 补充校准):counter 外发前的限额闸口——succeeded
812
1022
  // 候选逐一过 limitViolation(结构化事实),仅放行未被约束阻断的候选;
813
1023
  // 全部被阻断时显式拒绝(不存在合法还价对象)。clarification 无商业
814
1024
  // 承诺,不过商业闸。
815
- let gated = this.store.listCandidates(input.task_id);
816
1025
  if (input.action === "counter_offer") {
817
1026
  const succeeded = gated.filter((c) => c.status === "succeeded");
818
1027
  const passable = succeeded.filter((c) => this.limitViolation("counter_offer", {
@@ -837,12 +1046,24 @@ export class KiwiBuyerService {
837
1046
  constraints: {
838
1047
  ...(intent.constraints ?? {}),
839
1048
  target_unit_price: explicitTarget,
1049
+ ...(input.procurement_price_basis ? { kiwi_procurement_target_price_basis: input.procurement_price_basis } : {}),
840
1050
  },
841
1051
  };
842
1052
  // 商业闸通过后才占用槽位(被委托阻断的调用不消耗轮次)。
843
1053
  reservedSlot = this.store.reserveNegotiationSlot(input.task_id, slotKind, maxRounds);
844
1054
  step = { ...step, round: reservedSlot };
845
- 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
+ }
846
1067
  }
847
1068
  else {
848
1069
  // 无外发 negotiator(本地确定性模式)同样占用槽位:跨进程并发也不
@@ -850,12 +1071,25 @@ export class KiwiBuyerService {
850
1071
  reservedSlot = this.store.reserveNegotiationSlot(input.task_id, slotKind, maxRounds);
851
1072
  step = { ...step, round: reservedSlot };
852
1073
  }
1074
+ return this.recordNegotiationStep(input.task_id, step, slotKind, reservedSlot, input.expected_offer_digest);
1075
+ }
1076
+ recordNegotiationStep(taskId, step, action, round, expectedDigest) {
853
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 };
854
1086
  // 商家最新 offer-like 回复必须回写候选:否则 get_task 仍显示上一轮价,
855
1087
  // accept 也会绑定旧候选(2026-10-30 保温杯会话:接受 ¥151.05,协议
856
1088
  // digest 却指向 ¥159 初始报价)。
857
- if (step.merchant_offer !== undefined) {
858
- 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, {
859
1093
  offer_id: step.merchant_offer.offer_id,
860
1094
  merchant_reply_id: step.merchant_offer.reply_message_id,
861
1095
  reply_text: step.merchant_offer.reply_text,
@@ -867,18 +1101,11 @@ export class KiwiBuyerService {
867
1101
  }
868
1102
  // 并发下相邻槽位预留不改 payload;仍以事务内最新任务合并,避免覆盖
869
1103
  // 其他完成步骤。落步成功即释放本槽位(步本身开始计入轮次)。
870
- if (reservedSlot !== undefined) {
871
- this.store.releaseNegotiationSlot(input.task_id, slotKind, reservedSlot);
1104
+ if (round !== undefined) {
1105
+ this.store.releaseNegotiationSlot(taskId, action, round);
872
1106
  }
873
- const latest = this.taskFor(input.task_id);
874
- if (latest === undefined)
875
- throw new McpError("task_not_found", `task ${input.task_id} not found`);
876
- const latestDecoded = this.decodeTask(latest);
877
- const prior = Array.isArray(latestDecoded.steps)
878
- ? latestDecoded.steps
879
- : [];
880
1107
  const currentStatus = typeof latestDecoded.status === "string" ? latestDecoded.status : "in_progress";
881
- const updated = this.store.updateTask(input.task_id, {
1108
+ const updated = this.store.updateTask(taskId, {
882
1109
  status: currentStatus === "pending" ? "in_progress" : currentStatus,
883
1110
  payload: JSON.stringify({
884
1111
  ...latestDecoded,
@@ -945,12 +1172,16 @@ export class KiwiBuyerService {
945
1172
  if (acceptedTermsDigest(preCandidate) !== termsDigest) {
946
1173
  throw new McpError("approval_denied", "候选条款已变化,需重新获取报价");
947
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);
948
1181
  const existingAgreement = this.store.findAgreementByTerms(input.task_id, termsDigest);
949
1182
  let merchantAgreement;
950
1183
  let receiptBinding;
951
1184
  if (existingAgreement === undefined) {
952
- const provenance = preCandidate.provenance ?? {};
953
- const isA2A = typeof provenance.a2a_endpoint === "string" && provenance.a2a_endpoint !== "";
954
1185
  if (isA2A) {
955
1186
  // A2A must receive the merchant's agreement artifact. An offer-like
956
1187
  // reply that is not a conditional_offer cannot be remotely accepted by
@@ -962,7 +1193,7 @@ export class KiwiBuyerService {
962
1193
  // accept_nonbinding object as a conditional_offer (conditions: []).
963
1194
  // Both are remote-acceptable; do not require a synthetic conditional
964
1195
  // round or a price change just to obtain the merchant agreement.
965
- 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") {
966
1197
  throw new McpError("invalid_params", "A2A candidate latest reply is not an acceptable offer/conditional_offer; refusing to create a local agreement");
967
1198
  }
968
1199
  const accepted = await this.negotiator.acceptNonbinding({
@@ -988,6 +1219,7 @@ export class KiwiBuyerService {
988
1219
  || !checkedAgreement.accepted_by.includes("merchant")) {
989
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 });
990
1221
  }
1222
+ assertGenericA2AAgreement(checkedAgreement);
991
1223
  merchantAgreement = checkedAgreement;
992
1224
  receiptBinding = accepted.receiptBinding;
993
1225
  }
@@ -1185,6 +1417,18 @@ export class KiwiBuyerService {
1185
1417
  if (stored === undefined) {
1186
1418
  throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
1187
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);
1188
1432
  // URL 类目的地未显式给 url 时,回落到商家报价里的 handoff_destination:
1189
1433
  // 商家已经给出了真实购买入口,宿主无需(也常无法)猜一个 URL。
1190
1434
  let resolvedUrl = input.url;
@@ -1251,6 +1495,7 @@ export class KiwiBuyerService {
1251
1495
  if (freshAgreement === undefined) {
1252
1496
  throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
1253
1497
  }
1498
+ rejectCollectionHandoff(freshAgreement);
1254
1499
  this.assertHandoffIntentMatches({
1255
1500
  approval,
1256
1501
  task: freshTask,
@@ -2049,8 +2294,6 @@ export class KiwiBuyerService {
2049
2294
  * 目录暂不可达时不改变既有行为(跳过本门,走 fetcher 的部分失败语义)。
2050
2295
  */
2051
2296
  async assertInquiryAvailable(merchantIds) {
2052
- if (merchantIds === undefined || merchantIds.length === 0)
2053
- return;
2054
2297
  const index = this.merchantIndex;
2055
2298
  if (index === undefined)
2056
2299
  return;