@harrylabsj/kiwi 0.12.31 → 0.12.32

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 (307) hide show
  1. package/dist/a2a/node.d.ts +1 -0
  2. package/dist/a2a/node.js +170 -2
  3. package/dist/a2a/node.js.map +1 -1
  4. package/dist/a2a/reception/agent-runtime.d.ts +32 -1
  5. package/dist/a2a/reception/agent-runtime.js +420 -11
  6. package/dist/a2a/reception/agent-runtime.js.map +1 -1
  7. package/dist/a2a/reception/customer-memory-tools.d.ts +73 -0
  8. package/dist/a2a/reception/customer-memory-tools.js +17 -0
  9. package/dist/a2a/reception/customer-memory-tools.js.map +1 -0
  10. package/dist/a2a/reception/engine.d.ts +12 -0
  11. package/dist/a2a/reception/engine.js +42 -1
  12. package/dist/a2a/reception/engine.js.map +1 -1
  13. package/dist/a2a/reception/publish.d.ts +14 -1
  14. package/dist/a2a/reception/publish.js +62 -1
  15. package/dist/a2a/reception/publish.js.map +1 -1
  16. package/dist/a2a/reception/question-spec.d.ts +91 -0
  17. package/dist/a2a/reception/question-spec.js +260 -0
  18. package/dist/a2a/reception/question-spec.js.map +1 -0
  19. package/dist/a2a/reception/reply-outbox.d.ts +6 -0
  20. package/dist/a2a/reception/reply-outbox.js +44 -0
  21. package/dist/a2a/reception/reply-outbox.js.map +1 -1
  22. package/dist/a2a/reception/responder.d.ts +13 -1
  23. package/dist/a2a/reception/responder.js +26 -3
  24. package/dist/a2a/reception/responder.js.map +1 -1
  25. package/dist/a2a/reception/skill-catalog.d.ts +72 -0
  26. package/dist/a2a/reception/skill-catalog.js +85 -0
  27. package/dist/a2a/reception/skill-catalog.js.map +1 -0
  28. package/dist/a2a/reception/skill-contract.d.ts +70 -0
  29. package/dist/a2a/reception/skill-contract.js +183 -0
  30. package/dist/a2a/reception/skill-contract.js.map +1 -0
  31. package/dist/a2a/reception/types.d.ts +12 -0
  32. package/dist/a2a/server/customer-identity-gateway.d.ts +111 -0
  33. package/dist/a2a/server/customer-identity-gateway.js +441 -0
  34. package/dist/a2a/server/customer-identity-gateway.js.map +1 -0
  35. package/dist/a2a/server/merchant-handler.d.ts +34 -0
  36. package/dist/a2a/server/merchant-handler.js +439 -19
  37. package/dist/a2a/server/merchant-handler.js.map +1 -1
  38. package/dist/a2a/server/pipeline.js +74 -29
  39. package/dist/a2a/server/pipeline.js.map +1 -1
  40. package/dist/a2a/server/types.d.ts +2 -0
  41. package/dist/a2a/unit-alias.d.ts +3 -3
  42. package/dist/a2a/unit-alias.js +9 -5
  43. package/dist/a2a/unit-alias.js.map +1 -1
  44. package/dist/auth/merchant-sessions.d.ts +3 -0
  45. package/dist/auth/merchant-sessions.js +21 -5
  46. package/dist/auth/merchant-sessions.js.map +1 -1
  47. package/dist/buyer-core/a2a-knp.d.ts +4 -2
  48. package/dist/buyer-core/a2a-knp.js +5 -2
  49. package/dist/buyer-core/a2a-knp.js.map +1 -1
  50. package/dist/buyer-core/a2a-negotiator.d.ts +1 -0
  51. package/dist/buyer-core/a2a-negotiator.js +18 -11
  52. package/dist/buyer-core/a2a-negotiator.js.map +1 -1
  53. package/dist/buyer-core/a2a-quote-fetcher.d.ts +25 -0
  54. package/dist/buyer-core/a2a-quote-fetcher.js +82 -4
  55. package/dist/buyer-core/a2a-quote-fetcher.js.map +1 -1
  56. package/dist/buyer-core/a2a-quote-history.d.ts +94 -0
  57. package/dist/buyer-core/a2a-quote-history.js +149 -0
  58. package/dist/buyer-core/a2a-quote-history.js.map +1 -0
  59. package/dist/buyer-core/build-service.d.ts +19 -0
  60. package/dist/buyer-core/build-service.js +30 -1
  61. package/dist/buyer-core/build-service.js.map +1 -1
  62. package/dist/buyer-core/errors.d.ts +1 -1
  63. package/dist/buyer-core/errors.js +1 -0
  64. package/dist/buyer-core/errors.js.map +1 -1
  65. package/dist/buyer-core/open-inquiry-signer.d.ts +1 -0
  66. package/dist/buyer-core/open-inquiry-signer.js +5 -2
  67. package/dist/buyer-core/open-inquiry-signer.js.map +1 -1
  68. package/dist/buyer-core/protocol-recovery.d.ts +2 -1
  69. package/dist/buyer-core/protocol-recovery.js +14 -4
  70. package/dist/buyer-core/protocol-recovery.js.map +1 -1
  71. package/dist/buyer-core/service.d.ts +57 -5
  72. package/dist/buyer-core/service.js +275 -50
  73. package/dist/buyer-core/service.js.map +1 -1
  74. package/dist/buyer-core/store.d.ts +8 -0
  75. package/dist/buyer-core/store.js +37 -7
  76. package/dist/buyer-core/store.js.map +1 -1
  77. package/dist/cli.js +13 -2
  78. package/dist/cli.js.map +1 -1
  79. package/dist/cloud/bootstrap.js +141 -7
  80. package/dist/cloud/bootstrap.js.map +1 -1
  81. package/dist/commerce/receipt/dispatcher.d.ts +42 -0
  82. package/dist/commerce/receipt/dispatcher.js +68 -0
  83. package/dist/commerce/receipt/dispatcher.js.map +1 -0
  84. package/dist/commerce/receipt/receipts.d.ts +140 -0
  85. package/dist/commerce/receipt/receipts.js +247 -0
  86. package/dist/commerce/receipt/receipts.js.map +1 -0
  87. package/dist/config/profile.d.ts +2 -2
  88. package/dist/handoff/order-receipts.d.ts +62 -0
  89. package/dist/handoff/order-receipts.js +71 -0
  90. package/dist/handoff/order-receipts.js.map +1 -0
  91. package/dist/handoff/ucp-checkout/cart-channel.d.ts +2 -1
  92. package/dist/handoff/ucp-checkout/cart-channel.js +1 -0
  93. package/dist/handoff/ucp-checkout/cart-channel.js.map +1 -1
  94. package/dist/handoff/ucp-checkout/channel.d.ts +6 -0
  95. package/dist/handoff/ucp-checkout/channel.js +44 -0
  96. package/dist/handoff/ucp-checkout/channel.js.map +1 -1
  97. package/dist/http/cli.js +6 -0
  98. package/dist/http/cli.js.map +1 -1
  99. package/dist/http/merchant-management/api.d.ts +10 -0
  100. package/dist/http/merchant-management/api.js +443 -0
  101. package/dist/http/merchant-management/api.js.map +1 -1
  102. package/dist/http/merchant-management/draft-store.js +8 -6
  103. package/dist/http/merchant-management/draft-store.js.map +1 -1
  104. package/dist/http/merchant-management/page.js +2 -2
  105. package/dist/mcp/cli.js +6 -0
  106. package/dist/mcp/cli.js.map +1 -1
  107. package/dist/mcp/merchant-runtime-assembly.d.ts +20 -0
  108. package/dist/mcp/merchant-runtime-assembly.js +93 -3
  109. package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
  110. package/dist/mcp/merchant-server.d.ts +5 -0
  111. package/dist/mcp/merchant-server.js +12 -0
  112. package/dist/mcp/merchant-server.js.map +1 -1
  113. package/dist/mcp/tools.js +7 -1
  114. package/dist/mcp/tools.js.map +1 -1
  115. package/dist/merchant/application/actor.d.ts +1 -1
  116. package/dist/merchant/application/actor.js +15 -0
  117. package/dist/merchant/application/actor.js.map +1 -1
  118. package/dist/merchant/workbench-server.d.ts +1 -0
  119. package/dist/merchant/workbench-server.js +176 -2
  120. package/dist/merchant/workbench-server.js.map +1 -1
  121. package/dist/merchant-core/budget/background-budget.d.ts +132 -0
  122. package/dist/merchant-core/budget/background-budget.js +308 -0
  123. package/dist/merchant-core/budget/background-budget.js.map +1 -0
  124. package/dist/merchant-core/context-governance/actor-context.d.ts +56 -0
  125. package/dist/merchant-core/context-governance/actor-context.js +76 -0
  126. package/dist/merchant-core/context-governance/actor-context.js.map +1 -0
  127. package/dist/merchant-core/context-governance/authority.d.ts +39 -0
  128. package/dist/merchant-core/context-governance/authority.js +28 -0
  129. package/dist/merchant-core/context-governance/authority.js.map +1 -0
  130. package/dist/merchant-core/context-governance/context-guard.d.ts +104 -0
  131. package/dist/merchant-core/context-governance/context-guard.js +194 -0
  132. package/dist/merchant-core/context-governance/context-guard.js.map +1 -0
  133. package/dist/merchant-core/context-governance/data-use-grant.d.ts +91 -0
  134. package/dist/merchant-core/context-governance/data-use-grant.js +211 -0
  135. package/dist/merchant-core/context-governance/data-use-grant.js.map +1 -0
  136. package/dist/merchant-core/context-governance/feature-flags.d.ts +32 -0
  137. package/dist/merchant-core/context-governance/feature-flags.js +83 -0
  138. package/dist/merchant-core/context-governance/feature-flags.js.map +1 -0
  139. package/dist/merchant-core/context-governance/pilot-readiness.d.ts +39 -0
  140. package/dist/merchant-core/context-governance/pilot-readiness.js +141 -0
  141. package/dist/merchant-core/context-governance/pilot-readiness.js.map +1 -0
  142. package/dist/merchant-core/context-governance/source-governance.d.ts +157 -0
  143. package/dist/merchant-core/context-governance/source-governance.js +492 -0
  144. package/dist/merchant-core/context-governance/source-governance.js.map +1 -0
  145. package/dist/merchant-core/context-governance/types.d.ts +62 -0
  146. package/dist/merchant-core/context-governance/types.js +92 -0
  147. package/dist/merchant-core/context-governance/types.js.map +1 -0
  148. package/dist/merchant-core/customer-delivery/binding.d.ts +55 -0
  149. package/dist/merchant-core/customer-delivery/binding.js +121 -0
  150. package/dist/merchant-core/customer-delivery/binding.js.map +1 -0
  151. package/dist/merchant-core/customer-delivery/channel.d.ts +75 -0
  152. package/dist/merchant-core/customer-delivery/channel.js +157 -0
  153. package/dist/merchant-core/customer-delivery/channel.js.map +1 -0
  154. package/dist/merchant-core/customer-delivery/consent-repository.d.ts +50 -0
  155. package/dist/merchant-core/customer-delivery/consent-repository.js +160 -0
  156. package/dist/merchant-core/customer-delivery/consent-repository.js.map +1 -0
  157. package/dist/merchant-core/customer-delivery/dispatcher-loop.d.ts +68 -0
  158. package/dist/merchant-core/customer-delivery/dispatcher-loop.js +132 -0
  159. package/dist/merchant-core/customer-delivery/dispatcher-loop.js.map +1 -0
  160. package/dist/merchant-core/customer-delivery/dispatcher.d.ts +118 -0
  161. package/dist/merchant-core/customer-delivery/dispatcher.js +166 -0
  162. package/dist/merchant-core/customer-delivery/dispatcher.js.map +1 -0
  163. package/dist/merchant-core/customer-delivery/email-adapter.d.ts +31 -0
  164. package/dist/merchant-core/customer-delivery/email-adapter.js +90 -0
  165. package/dist/merchant-core/customer-delivery/email-adapter.js.map +1 -0
  166. package/dist/merchant-core/customer-delivery/gate.d.ts +37 -0
  167. package/dist/merchant-core/customer-delivery/gate.js +196 -0
  168. package/dist/merchant-core/customer-delivery/gate.js.map +1 -0
  169. package/dist/merchant-core/customer-delivery/reconciliation.d.ts +13 -0
  170. package/dist/merchant-core/customer-delivery/reconciliation.js +70 -0
  171. package/dist/merchant-core/customer-delivery/reconciliation.js.map +1 -0
  172. package/dist/merchant-core/customer-delivery/repository.d.ts +55 -0
  173. package/dist/merchant-core/customer-delivery/repository.js +235 -0
  174. package/dist/merchant-core/customer-delivery/repository.js.map +1 -0
  175. package/dist/merchant-core/customer-delivery/smtp-adapter.d.ts +30 -0
  176. package/dist/merchant-core/customer-delivery/smtp-adapter.js +183 -0
  177. package/dist/merchant-core/customer-delivery/smtp-adapter.js.map +1 -0
  178. package/dist/merchant-core/customer-delivery/stream-gate.d.ts +45 -0
  179. package/dist/merchant-core/customer-delivery/stream-gate.js +123 -0
  180. package/dist/merchant-core/customer-delivery/stream-gate.js.map +1 -0
  181. package/dist/merchant-core/customer-delivery/types.d.ts +103 -0
  182. package/dist/merchant-core/customer-delivery/types.js +32 -0
  183. package/dist/merchant-core/customer-delivery/types.js.map +1 -0
  184. package/dist/merchant-core/customer-delivery/weixin-adapter.d.ts +35 -0
  185. package/dist/merchant-core/customer-delivery/weixin-adapter.js +56 -0
  186. package/dist/merchant-core/customer-delivery/weixin-adapter.js.map +1 -0
  187. package/dist/merchant-core/customer-memory/auto-identity.d.ts +43 -0
  188. package/dist/merchant-core/customer-memory/auto-identity.js +163 -0
  189. package/dist/merchant-core/customer-memory/auto-identity.js.map +1 -0
  190. package/dist/merchant-core/customer-memory/grants.d.ts +72 -0
  191. package/dist/merchant-core/customer-memory/grants.js +224 -0
  192. package/dist/merchant-core/customer-memory/grants.js.map +1 -0
  193. package/dist/merchant-core/customer-memory/history.d.ts +51 -0
  194. package/dist/merchant-core/customer-memory/history.js +252 -0
  195. package/dist/merchant-core/customer-memory/history.js.map +1 -0
  196. package/dist/merchant-core/customer-memory/identity.d.ts +66 -0
  197. package/dist/merchant-core/customer-memory/identity.js +249 -0
  198. package/dist/merchant-core/customer-memory/identity.js.map +1 -0
  199. package/dist/merchant-core/customer-memory/maintenance.d.ts +51 -0
  200. package/dist/merchant-core/customer-memory/maintenance.js +67 -0
  201. package/dist/merchant-core/customer-memory/maintenance.js.map +1 -0
  202. package/dist/merchant-core/customer-memory/memory.d.ts +119 -0
  203. package/dist/merchant-core/customer-memory/memory.js +502 -0
  204. package/dist/merchant-core/customer-memory/memory.js.map +1 -0
  205. package/dist/merchant-core/customer-memory/private-transport.d.ts +10 -0
  206. package/dist/merchant-core/customer-memory/private-transport.js +108 -0
  207. package/dist/merchant-core/customer-memory/private-transport.js.map +1 -0
  208. package/dist/merchant-core/customer-memory/quote-history.d.ts +160 -0
  209. package/dist/merchant-core/customer-memory/quote-history.js +392 -0
  210. package/dist/merchant-core/customer-memory/quote-history.js.map +1 -0
  211. package/dist/merchant-core/customer-memory/reception-provider.d.ts +69 -0
  212. package/dist/merchant-core/customer-memory/reception-provider.js +250 -0
  213. package/dist/merchant-core/customer-memory/reception-provider.js.map +1 -0
  214. package/dist/merchant-core/customer-memory/reception-writer.d.ts +19 -0
  215. package/dist/merchant-core/customer-memory/reception-writer.js +32 -0
  216. package/dist/merchant-core/customer-memory/reception-writer.js.map +1 -0
  217. package/dist/merchant-core/customer-memory/types.d.ts +111 -0
  218. package/dist/merchant-core/customer-memory/types.js +58 -0
  219. package/dist/merchant-core/customer-memory/types.js.map +1 -0
  220. package/dist/merchant-core/followup/repository.d.ts +2 -1
  221. package/dist/merchant-core/followup/repository.js +29 -23
  222. package/dist/merchant-core/followup/repository.js.map +1 -1
  223. package/dist/merchant-core/learning/evaluation-fixtures.d.ts +38 -0
  224. package/dist/merchant-core/learning/evaluation-fixtures.js +83 -0
  225. package/dist/merchant-core/learning/evaluation-fixtures.js.map +1 -0
  226. package/dist/merchant-core/learning/evaluation-suite-v1.d.ts +56 -0
  227. package/dist/merchant-core/learning/evaluation-suite-v1.js +129 -0
  228. package/dist/merchant-core/learning/evaluation-suite-v1.js.map +1 -0
  229. package/dist/merchant-core/learning/evaluation.d.ts +84 -0
  230. package/dist/merchant-core/learning/evaluation.js +581 -0
  231. package/dist/merchant-core/learning/evaluation.js.map +1 -0
  232. package/dist/merchant-core/learning/initial-skills.d.ts +36 -0
  233. package/dist/merchant-core/learning/initial-skills.js +67 -0
  234. package/dist/merchant-core/learning/initial-skills.js.map +1 -0
  235. package/dist/merchant-core/learning/precheck.d.ts +33 -0
  236. package/dist/merchant-core/learning/precheck.js +56 -0
  237. package/dist/merchant-core/learning/precheck.js.map +1 -0
  238. package/dist/merchant-core/learning/real-evaluation-runner.d.ts +52 -0
  239. package/dist/merchant-core/learning/real-evaluation-runner.js +167 -0
  240. package/dist/merchant-core/learning/real-evaluation-runner.js.map +1 -0
  241. package/dist/merchant-core/learning/reception-skill-catalog.d.ts +39 -0
  242. package/dist/merchant-core/learning/reception-skill-catalog.js +145 -0
  243. package/dist/merchant-core/learning/reception-skill-catalog.js.map +1 -0
  244. package/dist/merchant-core/learning/recovery-gateway.d.ts +27 -0
  245. package/dist/merchant-core/learning/recovery-gateway.js +106 -0
  246. package/dist/merchant-core/learning/recovery-gateway.js.map +1 -0
  247. package/dist/merchant-core/learning/repository.d.ts +130 -0
  248. package/dist/merchant-core/learning/repository.js +588 -0
  249. package/dist/merchant-core/learning/repository.js.map +1 -0
  250. package/dist/merchant-core/learning/service.d.ts +262 -0
  251. package/dist/merchant-core/learning/service.js +1498 -0
  252. package/dist/merchant-core/learning/service.js.map +1 -0
  253. package/dist/merchant-core/learning/test-dispatch-gateway.d.ts +43 -0
  254. package/dist/merchant-core/learning/test-dispatch-gateway.js +145 -0
  255. package/dist/merchant-core/learning/test-dispatch-gateway.js.map +1 -0
  256. package/dist/merchant-core/learning/types.d.ts +217 -0
  257. package/dist/merchant-core/learning/types.js +52 -0
  258. package/dist/merchant-core/learning/types.js.map +1 -0
  259. package/dist/merchant-core/migrations/ledgers.d.ts +40 -0
  260. package/dist/merchant-core/migrations/ledgers.js +824 -0
  261. package/dist/merchant-core/migrations/ledgers.js.map +1 -0
  262. package/dist/merchant-core/migrations/runner.d.ts +55 -0
  263. package/dist/merchant-core/migrations/runner.js +114 -0
  264. package/dist/merchant-core/migrations/runner.js.map +1 -0
  265. package/dist/merchant-core/operations-jobs/advice-runner.d.ts +63 -0
  266. package/dist/merchant-core/operations-jobs/advice-runner.js +199 -0
  267. package/dist/merchant-core/operations-jobs/advice-runner.js.map +1 -0
  268. package/dist/merchant-core/operations-jobs/pilot-evidence.d.ts +64 -0
  269. package/dist/merchant-core/operations-jobs/pilot-evidence.js +109 -0
  270. package/dist/merchant-core/operations-jobs/pilot-evidence.js.map +1 -0
  271. package/dist/merchant-core/operations-jobs/pilot-metrics.d.ts +70 -0
  272. package/dist/merchant-core/operations-jobs/pilot-metrics.js +98 -0
  273. package/dist/merchant-core/operations-jobs/pilot-metrics.js.map +1 -0
  274. package/dist/merchant-core/operations-jobs/projection.d.ts +41 -0
  275. package/dist/merchant-core/operations-jobs/projection.js +158 -0
  276. package/dist/merchant-core/operations-jobs/projection.js.map +1 -0
  277. package/dist/merchant-core/operations-jobs/scheduler.d.ts +68 -0
  278. package/dist/merchant-core/operations-jobs/scheduler.js +233 -0
  279. package/dist/merchant-core/operations-jobs/scheduler.js.map +1 -0
  280. package/dist/merchant-core/operations-jobs/service.d.ts +260 -0
  281. package/dist/merchant-core/operations-jobs/service.js +922 -0
  282. package/dist/merchant-core/operations-jobs/service.js.map +1 -0
  283. package/dist/merchant-core/ops/facade.d.ts +10 -0
  284. package/dist/merchant-core/ops/facade.js +52 -0
  285. package/dist/merchant-core/ops/facade.js.map +1 -1
  286. package/dist/merchant-core/ops/schema.d.ts +1 -1
  287. package/dist/merchant-core/ops/schema.js +119 -2
  288. package/dist/merchant-core/ops/schema.js.map +1 -1
  289. package/dist/merchant-core/ops/surface.d.ts +37 -0
  290. package/dist/merchant-core/ops/surface.js +240 -0
  291. package/dist/merchant-core/ops/surface.js.map +1 -1
  292. package/dist/merchant-core/ownership/instance-ownership.d.ts +122 -0
  293. package/dist/merchant-core/ownership/instance-ownership.js +236 -0
  294. package/dist/merchant-core/ownership/instance-ownership.js.map +1 -0
  295. package/dist/merchant-core/ownership/runtime.d.ts +175 -0
  296. package/dist/merchant-core/ownership/runtime.js +422 -0
  297. package/dist/merchant-core/ownership/runtime.js.map +1 -0
  298. package/dist/merchant-core/storage/transaction.d.ts +102 -7
  299. package/dist/merchant-core/storage/transaction.js +274 -3
  300. package/dist/merchant-core/storage/transaction.js.map +1 -1
  301. package/dist/merchant-credential-rotation.d.ts +4 -1
  302. package/dist/merchant-credential-rotation.js +12 -8
  303. package/dist/merchant-credential-rotation.js.map +1 -1
  304. package/dist/merchant-runtime/manager.d.ts +2 -0
  305. package/dist/merchant-runtime/manager.js +5 -0
  306. package/dist/merchant-runtime/manager.js.map +1 -1
  307. package/package.json +1 -1
@@ -109,6 +109,12 @@ function explicitIntentItemSku(intent) {
109
109
  const sku = first.sku;
110
110
  return typeof sku === "string" && sku.trim() !== "" ? sku : undefined;
111
111
  }
112
+ function withHistorySku(intent, sku) {
113
+ const items = intent.items;
114
+ if (!Array.isArray(items) || items.length === 0)
115
+ return intent;
116
+ return { ...intent, items: [{ ...items[0], sku }, ...items.slice(1)] };
117
+ }
112
118
  /** 明确 SKU 的报价必须只包含该 SKU;商家换品/混入其他商品时拒绝接纳。 */
113
119
  function rejectQuoteForOtherSku(result, explicitSku) {
114
120
  if (explicitSku === undefined || result.status !== "succeeded")
@@ -166,6 +172,7 @@ export class KiwiBuyerService {
166
172
  quoteFetcher;
167
173
  negotiator;
168
174
  followsClient;
175
+ commerceReceipts;
169
176
  staleWake;
170
177
  staleWakeTimeoutMs;
171
178
  wakeAttemptAt = new Map();
@@ -188,6 +195,7 @@ export class KiwiBuyerService {
188
195
  this.merchantIndex = options.merchantIndex;
189
196
  this.quoteFetcher = options.quoteFetcher;
190
197
  this.negotiator = options.negotiator;
198
+ this.commerceReceipts = options.commerceReceipts;
191
199
  this.followsClient = options.followsClient;
192
200
  this.staleWake = options.staleWake;
193
201
  this.staleWakeTimeoutMs = options.staleWakeTimeoutMs ?? 5000;
@@ -386,8 +394,64 @@ export class KiwiBuyerService {
386
394
  }
387
395
  // ---- Northbound:kiwi_request_quotes --------------------------------------
388
396
  async requestQuotes(input) {
397
+ const useHistory = input.reuse_history === true && explicitIntentItemSku(input.intent) === undefined;
398
+ if (useHistory && input.merchant_ids?.length !== 1) {
399
+ throw new McpError("clarification_needed", "沿用上次规格需要恰好指定一个商家;请说明要沿用哪家店的报价。", {
400
+ reason: "history_merchant_required",
401
+ });
402
+ }
403
+ const idempotencyKey = input.idempotency_key ?? `req-${uuidv7()}`;
404
+ const requestDigest = contentDigest({
405
+ intent: input.intent,
406
+ merchant_ids: [...new Set(input.merchant_ids ?? [])].sort(),
407
+ reuse_history: useHistory,
408
+ });
409
+ const existing = this.store.findTaskByIdempotencyKey(this.ownerHash, idempotencyKey);
410
+ if (existing !== undefined)
411
+ return this.replayQuoteRequest(existing, input, requestDigest, useHistory);
412
+ // K3:历史解析发生在正式 RFQ 之前(A5)。显式新规格优先。
413
+ let effectiveIntent = input.intent;
414
+ let reusedHistory;
415
+ if (useHistory) {
416
+ const merchantId = input.merchant_ids[0];
417
+ const history = await this.resolveQuoteHistory({ merchant_id: merchantId });
418
+ if (history.status !== "ok" || history.candidates.length === 0) {
419
+ throw new McpError("clarification_needed", history.status === "unavailable"
420
+ ? "暂时无法读取本店历史报价(未授权或商家不支持);请直接说明商品和数量重新询价。"
421
+ : "本店没有可引用的历史报价;请直接说明商品和数量重新询价。", {
422
+ reason: history.status === "unavailable" ? "history_unavailable" : "history_empty",
423
+ merchant_id: merchantId,
424
+ });
425
+ }
426
+ if (history.candidates.length > 1) {
427
+ throw new McpError("clarification_needed", "上次有多款商品报价;请说明要沿用哪一款(可按 SKU 或商品名指明)。", {
428
+ reason: "history_ambiguous",
429
+ merchant_id: merchantId,
430
+ candidates: history.candidates.map((hit) => ({
431
+ sku: hit.sku,
432
+ quoted_at: hit.quoted_at,
433
+ ...(hit.valid_until !== undefined ? { valid_until: hit.valid_until } : {}),
434
+ price: hit.price,
435
+ })),
436
+ });
437
+ }
438
+ const hit = history.candidates[0];
439
+ effectiveIntent = withHistorySku(input.intent, hit.sku);
440
+ reusedHistory = {
441
+ merchant_id: merchantId,
442
+ sku: hit.sku,
443
+ quoted_at: hit.quoted_at,
444
+ price: hit.price,
445
+ quantity: hit.quantity,
446
+ unit: hit.unit,
447
+ negotiation_id: hit.negotiation_id,
448
+ offer_id: hit.offer_id,
449
+ ...(hit.valid_until !== undefined ? { valid_until: hit.valid_until } : {}),
450
+ note: "历史价格仅供参考(含时间与有效期);本次价格以正式报价为准。",
451
+ };
452
+ }
389
453
  // 契约校验(§5.2):CommerceIntent 必须合法;无效即拒绝,不落库。
390
- const intentErrors = validateCommerceIntent(input.intent);
454
+ const intentErrors = validateCommerceIntent(effectiveIntent);
391
455
  if (intentErrors.length > 0) {
392
456
  throw new McpError("contract_violation", `CommerceIntent 违反冻结契约:${intentErrors.join("; ")}`);
393
457
  }
@@ -396,7 +460,6 @@ export class KiwiBuyerService {
396
460
  await this.assertInquiryAvailable(input.merchant_ids);
397
461
  const policyId = this.policy.policy_id;
398
462
  const expiresAt = this.policy.expires_at;
399
- const idempotencyKey = input.idempotency_key ?? `req-${uuidv7()}`;
400
463
  const taskId = `task-${uuidv7()}`;
401
464
  const created = this.now();
402
465
  // 无 fetcher 时记录确定性 fan-out 槽位(§6.2 部分失败可解释);有 fetcher 时
@@ -415,6 +478,7 @@ export class KiwiBuyerService {
415
478
  task_kind: "request_quotes",
416
479
  status: "in_progress",
417
480
  idempotency_key: idempotencyKey,
481
+ quote_request_digest: requestDigest,
418
482
  intent_id: String(input.intent.intent_id),
419
483
  delegation_policy_id: policyId,
420
484
  created_at: created,
@@ -433,48 +497,15 @@ export class KiwiBuyerService {
433
497
  expires_at: expiresAt,
434
498
  resumable: true,
435
499
  candidates: preCandidates,
436
- intent: input.intent,
500
+ // 任务持久化**解析后**的意图(含 K3 历史解析出的显式 SKU);恢复/
501
+ // 重试用同一意图,出站 SKU 确定性一致(A5)。历史价格参考只在本次
502
+ // 响应返回(persistent-task 冻结契约不允许附加顶层字段)。
503
+ intent: effectiveIntent,
437
504
  }),
438
505
  };
439
506
  const { task: persisted, created: isCreated } = this.store.createTask(task);
440
507
  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 };
508
+ return this.replayQuoteRequest(persisted, input, requestDigest, useHistory);
478
509
  }
479
510
  for (const candidate of preCandidates) {
480
511
  this.store.addCandidate(taskId, candidate);
@@ -511,8 +542,8 @@ export class KiwiBuyerService {
511
542
  // 一旦调用 quoteFetcher,就不能把抛错解释成“没发送”:adapter 可能已
512
543
  // 写入/发送部分 RFQ。没有 receipt 时保守落为 non-retryable unknown。
513
544
  dispatchStarted = true;
514
- quotedResults = await this.quoteFetcher.requestQuotes(input.intent, merchantRecords, protocolContext);
515
- const explicitSku = explicitIntentItemSku(input.intent);
545
+ quotedResults = await this.quoteFetcher.requestQuotes(effectiveIntent, merchantRecords, protocolContext);
546
+ const explicitSku = explicitIntentItemSku(effectiveIntent);
516
547
  quotedResults = quotedResults.map((result) => rejectQuoteForOtherSku(result, explicitSku));
517
548
  dispatchOutcomeUnknown = quotedResults.some((result) => result.status === "failed" &&
518
549
  result.failure?.classification === "protocol_error" &&
@@ -596,13 +627,117 @@ export class KiwiBuyerService {
596
627
  const decoded = this.decodeTask(updated);
597
628
  // 冻结契约强制:持久任务记录必须满足 persistent-task/1.0 schema(§6.2)。
598
629
  assertNorthboundContractValid("persistent-task", decoded, "requestQuotes result");
599
- return { task: decoded, created: true };
630
+ return {
631
+ task: decoded,
632
+ created: true,
633
+ ...(reusedHistory !== undefined ? { reused_history: reusedHistory } : {}),
634
+ };
600
635
  });
601
636
  }
602
637
  protocolContext(task, requestedMerchants) {
603
638
  const intent = this.decodeTask(task).intent;
604
639
  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
640
  }
641
+ async replayQuoteRequest(persisted, input, requestDigest, useHistory) {
642
+ if (persisted.owner_hash !== this.ownerHash || persisted.task_kind !== "request_quotes") {
643
+ throw new McpError("task_not_found", "quote request does not belong to this session");
644
+ }
645
+ const task = this.decodeTask(persisted);
646
+ const original = task.intent;
647
+ const originalIntent = original !== null && typeof original === "object"
648
+ ? original
649
+ : undefined;
650
+ const originalSku = originalIntent === undefined ? undefined : explicitIntentItemSku(originalIntent);
651
+ const merchantIds = input.merchant_ids ?? [];
652
+ if (persisted.quote_request_digest !== undefined) {
653
+ if (persisted.quote_request_digest !== requestDigest) {
654
+ throw new McpError("idempotency_conflict", "same task key has a different quote request");
655
+ }
656
+ }
657
+ else if (useHistory || this.quoteFetcher?.recoverQuotes !== undefined) {
658
+ // Older tasks stored only the resolved SKU. Reconstruct it locally for replay.
659
+ const expectedIntent = useHistory && originalSku !== undefined
660
+ ? withHistorySku(input.intent, originalSku)
661
+ : input.intent;
662
+ if (originalIntent !== undefined && contentDigest(originalIntent) !== contentDigest(expectedIntent)) {
663
+ throw new McpError("idempotency_conflict", "same task key has different intent");
664
+ }
665
+ const selected = [...new Set(this.store.listCandidates(persisted.task_id).map((c) => c.merchant_id))].sort();
666
+ if (useHistory && selected.length === 0 && persisted.status === "in_progress") {
667
+ return { task, created: false }; // No saved target to use for legacy protocol recovery.
668
+ }
669
+ if ((useHistory || persisted.status !== "in_progress") &&
670
+ contentDigest(selected) !== contentDigest([...new Set(merchantIds)].sort())) {
671
+ throw new McpError("idempotency_conflict", "same task key has different selected merchants");
672
+ }
673
+ }
674
+ // Recovery reads existing protocol evidence and never dispatches a new RFQ.
675
+ if (this.quoteFetcher?.recoverQuotes === undefined ||
676
+ !["in_progress", "partial_success"].includes(persisted.status) ||
677
+ this.store.hasAgreementForTask(persisted.task_id)) {
678
+ return { task, created: false };
679
+ }
680
+ const originalCandidates = this.store.listCandidates(persisted.task_id);
681
+ const recovered = await this.quoteFetcher.recoverQuotes(this.protocolContext(persisted, merchantIds));
682
+ const explicitSku = originalIntent === undefined ? explicitIntentItemSku(input.intent) : originalSku;
683
+ const results = recovered.map((result) => rejectQuoteForOtherSku(result, explicitSku));
684
+ if (results.length === 0)
685
+ return { task, created: false };
686
+ return this.store.transaction(() => {
687
+ if (this.store.hasAgreementForTask(persisted.task_id) ||
688
+ contentDigest(this.store.listCandidates(persisted.task_id)) !== contentDigest(originalCandidates)) {
689
+ throw new McpError("idempotency_conflict", "task candidates or accepted agreement changed during recovery");
690
+ }
691
+ for (const result of results)
692
+ this.store.replaceRecoveredCandidate(persisted.task_id, result);
693
+ const candidates = this.northboundCandidates(persisted.task_id);
694
+ const status = candidates.length > 0 && candidates.every((candidate) => candidate.status === "succeeded")
695
+ ? "succeeded" : "partial_success";
696
+ const updated = this.store.updateTask(persisted.task_id, {
697
+ status,
698
+ payload: JSON.stringify({ ...task, status, updated_at: this.now(), candidates }),
699
+ }, persisted);
700
+ const decoded = this.decodeTask(updated);
701
+ assertNorthboundContractValid("persistent-task", decoded, "recovered quotes result");
702
+ return { task: decoded, created: false };
703
+ });
704
+ }
705
+ /**
706
+ * 买家识别与交易回执 · K2/K3:“沿用上次规格”前置查询——先解析目标商家,
707
+ * 再按本店授权查上次已发报价。唯一匹配时调用方把明确 SKU 和本次数量送入
708
+ * 标准 requestQuotes;无历史/多义/扩展不支持时由调用方澄清。
709
+ * 显式新规格优先:调用方带 skus 时按指定商品过滤。
710
+ */
711
+ async resolveQuoteHistory(input) {
712
+ const merchantId = input.merchant_id;
713
+ if (this.quoteFetcher?.queryQuoteHistory === undefined) {
714
+ return { status: "unavailable", merchant_id: merchantId, reason: "history_query_unsupported" };
715
+ }
716
+ const merchant = await this.merchantIndex?.resolveById(merchantId).catch(() => undefined);
717
+ if (merchant === undefined) {
718
+ return { status: "unavailable", merchant_id: merchantId, reason: "merchant_not_found" };
719
+ }
720
+ // 即席协议上下文:委托声明按当前时间派生(查询本身每次新 message ID,
721
+ // 无跨请求幂等绑定;正式 RFQ 的委托仍按任务上下文恒定派生)。
722
+ const context = {
723
+ taskId: `hist-${uuidv7()}`,
724
+ createdAt: this.now(),
725
+ intentBindingDigest: contentDigest({
726
+ merchant_id: merchantId,
727
+ principal: this.principal,
728
+ buyer: this.buyerAgentId,
729
+ }),
730
+ };
731
+ const result = await this.quoteFetcher.queryQuoteHistory(merchant, {
732
+ ...(input.skus !== undefined ? { skus: input.skus } : {}),
733
+ ...(input.limit !== undefined ? { limit: input.limit } : {}),
734
+ context,
735
+ });
736
+ if (result.status !== "ok") {
737
+ return { status: "unavailable", merchant_id: merchantId, reason: result.reason };
738
+ }
739
+ return { status: "ok", merchant_id: merchantId, candidates: result.candidates };
740
+ }
606
741
  // ---- Northbound:kiwi_get_task --------------------------------------------
607
742
  getTask(taskId) {
608
743
  const task = this.taskFor(taskId);
@@ -812,6 +947,7 @@ export class KiwiBuyerService {
812
947
  }
813
948
  const existingAgreement = this.store.findAgreementByTerms(input.task_id, termsDigest);
814
949
  let merchantAgreement;
950
+ let receiptBinding;
815
951
  if (existingAgreement === undefined) {
816
952
  const provenance = preCandidate.provenance ?? {};
817
953
  const isA2A = typeof provenance.a2a_endpoint === "string" && provenance.a2a_endpoint !== "";
@@ -853,6 +989,7 @@ export class KiwiBuyerService {
853
989
  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
990
  }
855
991
  merchantAgreement = checkedAgreement;
992
+ receiptBinding = accepted.receiptBinding;
856
993
  }
857
994
  }
858
995
  // review P1-2(A316 校准):短事务原子消费——事务内重读授权、写
@@ -1004,7 +1141,34 @@ export class KiwiBuyerService {
1004
1141
  });
1005
1142
  }
1006
1143
  }
1007
- return { task: this.decodeTask(updated), agreement, authorization };
1144
+ const committed = { task: this.decodeTask(updated), agreement, authorization };
1145
+ // K5:本地协议已提交且含有效 merchant_agreement → 上报“协议已接受
1146
+ // 并提交”。纯本地候选(无 merchant_agreement)不入队;上报失败不
1147
+ // 阻塞业务(outbox 退避重试,同 event_id 幂等补报)。
1148
+ const receipts = this.commerceReceipts;
1149
+ if (receipts !== undefined && merchantAgreement !== undefined && receiptBinding === receipts.binding) {
1150
+ const merchantAgreementId = String(merchantAgreement.agreement_id ?? "");
1151
+ const provenance = candidate.provenance;
1152
+ if (merchantAgreementId !== "" &&
1153
+ typeof provenance?.negotiation_id === "string" &&
1154
+ typeof provenance.offer_id === "string") {
1155
+ const intent = {
1156
+ event_id: `buyer-agreement:${agreementId}`,
1157
+ event_type: "buyer_agreement_accepted",
1158
+ merchant_id: String(candidate.merchant_id),
1159
+ negotiation_id: provenance.negotiation_id,
1160
+ merchant_agreement_id: merchantAgreementId,
1161
+ accepted_offer_id: provenance.offer_id,
1162
+ terms_digest: termsDigest,
1163
+ buyer_binding: receipts.binding,
1164
+ occurred_at: now,
1165
+ };
1166
+ this.store.setAgreementReceiptBinding(agreementId, receiptBinding);
1167
+ receipts.dispatcher.record(intent);
1168
+ receipts.dispatcher.kick();
1169
+ }
1170
+ }
1171
+ return committed;
1008
1172
  });
1009
1173
  }
1010
1174
  // ---- Northbound:kiwi_get_agreement ---------------------------------------
@@ -1058,12 +1222,16 @@ export class KiwiBuyerService {
1058
1222
  throw new McpError("authorization_denied", "Handoff 未获五层授权", { authorization });
1059
1223
  }
1060
1224
  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 };
1225
+ return this.store.transaction(() => {
1226
+ const handoffId = this.store.rememberHandoff(input.agreement_id, consumedBinding, `handoff-${uuidv7()}`);
1227
+ const handoffRef = {
1228
+ handoff_id: handoffId,
1229
+ destination_type: destination.destination_type,
1230
+ ...(destination.url !== null ? { url: destination.url } : {}),
1231
+ };
1232
+ this.enqueueHandoffReceipt(stored, handoffId);
1233
+ return { handoff_ref: handoffRef, authorization };
1234
+ });
1067
1235
  }
1068
1236
  // review P1-2(A316 校准):短事务原子消费——事务内重读审批、生成 ref、
1069
1237
  // 消费;同绑定重放返回**库里记录的同一 ref**(非虚构);失败 ROLLBACK
@@ -1092,6 +1260,8 @@ export class KiwiBuyerService {
1092
1260
  if (approval.status === "used") {
1093
1261
  const consumed = this.approvalConsumed(approval);
1094
1262
  if (consumed !== undefined && consumed.binding === consumedBinding) {
1263
+ // K6:重放返回库中同一 ref——补报同一 event_id(Catalog 幂等吸收)。
1264
+ this.enqueueHandoffReceipt(freshAgreement, consumed.ref);
1095
1265
  return {
1096
1266
  handoff_ref: {
1097
1267
  handoff_id: consumed.ref,
@@ -1116,9 +1286,64 @@ export class KiwiBuyerService {
1116
1286
  consumed: { ref: handoffRef.handoff_id, binding: consumedBinding, kind: "handoff" },
1117
1287
  }),
1118
1288
  });
1289
+ // K6:交接审批消费、handoff_ref 实际生成 → 上报“已生成交接记录”。
1290
+ this.enqueueHandoffReceipt(freshAgreement, handoffRef.handoff_id);
1119
1291
  return { handoff_ref: handoffRef, authorization };
1120
1292
  });
1121
1293
  }
1294
+ /**
1295
+ * K6:交接事实上报(被拒绝的审批与未实际生成的交接不会走到这里)。
1296
+ * 引用取自协议(磋商号 + 被接受报价 + 条款摘要);event_id 绑定
1297
+ * handoff_id(稳定、可重放);上报失败不阻塞交接。
1298
+ */
1299
+ enqueueHandoffReceipt(storedAgreement, handoffId) {
1300
+ const receipts = this.commerceReceipts;
1301
+ if (receipts === undefined)
1302
+ return;
1303
+ try {
1304
+ const payload = JSON.parse(storedAgreement.payload);
1305
+ if (typeof payload.agreement_id !== "string" ||
1306
+ this.store.agreementReceiptBinding(payload.agreement_id) !== receipts.binding)
1307
+ return;
1308
+ const merchantAgreementId = String(payload.merchant_agreement?.agreement_id ?? "");
1309
+ const negotiationId = typeof payload.negotiation_id === "string" ? payload.negotiation_id : undefined;
1310
+ if (merchantAgreementId === "" || negotiationId === undefined)
1311
+ return;
1312
+ let offerId;
1313
+ let merchantId;
1314
+ if (typeof payload.task_id === "string") {
1315
+ const candidate = this.store
1316
+ .listCandidates(payload.task_id)
1317
+ .find((c) => c.candidate_id === payload.accepted_candidate_id);
1318
+ const provenance = candidate?.provenance;
1319
+ if (typeof provenance?.offer_id === "string")
1320
+ offerId = provenance.offer_id;
1321
+ if (typeof candidate?.merchant_id === "string")
1322
+ merchantId = candidate.merchant_id;
1323
+ }
1324
+ if (merchantId === undefined || offerId === undefined)
1325
+ return;
1326
+ receipts.dispatcher.record({
1327
+ event_id: `buyer-handoff:${handoffId}`,
1328
+ event_type: "buyer_handoff_generated",
1329
+ merchant_id: merchantId,
1330
+ entry_type: "handoff_record",
1331
+ quote_ref: {
1332
+ negotiation_id: negotiationId,
1333
+ // 设计要求报价引用含磋商号与报价号;缺报价号(历史窗口)宁可少报。
1334
+ offer_id: offerId ?? "",
1335
+ ...(typeof payload.terms_digest === "string" ? { terms_digest: payload.terms_digest } : {}),
1336
+ },
1337
+ handoff_ref: handoffId,
1338
+ occurred_at: this.now(),
1339
+ });
1340
+ receipts.dispatcher.kick();
1341
+ }
1342
+ catch (error) {
1343
+ if (!(error instanceof SyntaxError))
1344
+ throw error;
1345
+ }
1346
+ }
1122
1347
  // ---- 持久审批(宿主适配面;kiwi_approve / kiwi_reject 为 MCP 工具)----------
1123
1348
  // ---- A 卡:handoff 意图(版本化、摘要不含自身、与 approval 同事务)----------
1124
1349
  /** 目的地归一:类型词表校验 + URL 归一(http/https、无凭据、无 fragment)。 */