@harrylabsj/kiwi 0.12.3 → 0.12.4

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 (347) hide show
  1. package/contracts/kiwi-contracts.lock.json +1 -1
  2. package/dist/a2a/client/client.d.ts +3 -1
  3. package/dist/a2a/client/client.js +23 -14
  4. package/dist/a2a/client/client.js.map +1 -1
  5. package/dist/a2a/client/types.d.ts +1 -1
  6. package/dist/a2a/client/url-policy.d.ts +2 -1
  7. package/dist/a2a/client/url-policy.js +5 -2
  8. package/dist/a2a/client/url-policy.js.map +1 -1
  9. package/dist/a2a/negotiate.js +68 -27
  10. package/dist/a2a/negotiate.js.map +1 -1
  11. package/dist/a2a/server/merchant-handler.d.ts +0 -6
  12. package/dist/a2a/server/merchant-handler.js +591 -474
  13. package/dist/a2a/server/merchant-handler.js.map +1 -1
  14. package/dist/a2a/server/pipeline.d.ts +1 -0
  15. package/dist/a2a/server/pipeline.js +48 -10
  16. package/dist/a2a/server/pipeline.js.map +1 -1
  17. package/dist/a2a/task/poller.d.ts +3 -0
  18. package/dist/a2a/task/poller.js +3 -0
  19. package/dist/a2a/task/poller.js.map +1 -1
  20. package/dist/agent/buyer/buyer-tools.d.ts +1 -1
  21. package/dist/agent/buyer/buyer-tools.js +37 -1
  22. package/dist/agent/buyer/buyer-tools.js.map +1 -1
  23. package/dist/agent/buyer/scheduler.d.ts +3 -0
  24. package/dist/agent/buyer/scheduler.js +25 -5
  25. package/dist/agent/buyer/scheduler.js.map +1 -1
  26. package/dist/agent/buyer/search-loop.js +6 -2
  27. package/dist/agent/buyer/search-loop.js.map +1 -1
  28. package/dist/agent/buyer/task-store.d.ts +12 -0
  29. package/dist/agent/buyer/task-store.js +101 -14
  30. package/dist/agent/buyer/task-store.js.map +1 -1
  31. package/dist/agent/kernel.d.ts +11 -0
  32. package/dist/agent/kernel.js +345 -273
  33. package/dist/agent/kernel.js.map +1 -1
  34. package/dist/agent/kiwi-tool.d.ts +11 -12
  35. package/dist/agent/merchant/action-candidate.d.ts +7 -0
  36. package/dist/agent/merchant/action-candidate.js +54 -9
  37. package/dist/agent/merchant/action-candidate.js.map +1 -1
  38. package/dist/agent/negotiation-chat.js +36 -8
  39. package/dist/agent/negotiation-chat.js.map +1 -1
  40. package/dist/agent/session.js +8 -0
  41. package/dist/agent/session.js.map +1 -1
  42. package/dist/agent/write-gate.d.ts +4 -0
  43. package/dist/agent/write-gate.js +22 -20
  44. package/dist/agent/write-gate.js.map +1 -1
  45. package/dist/buyer-core/a2a-knp.d.ts +1 -8
  46. package/dist/buyer-core/a2a-knp.js +15 -2
  47. package/dist/buyer-core/a2a-knp.js.map +1 -1
  48. package/dist/buyer-core/a2a-negotiator.d.ts +24 -19
  49. package/dist/buyer-core/a2a-negotiator.js +90 -24
  50. package/dist/buyer-core/a2a-negotiator.js.map +1 -1
  51. package/dist/buyer-core/a2a-quote-fetcher.d.ts +15 -3
  52. package/dist/buyer-core/a2a-quote-fetcher.js +131 -55
  53. package/dist/buyer-core/a2a-quote-fetcher.js.map +1 -1
  54. package/dist/buyer-core/build-service.d.ts +2 -0
  55. package/dist/buyer-core/build-service.js +28 -2
  56. package/dist/buyer-core/build-service.js.map +1 -1
  57. package/dist/buyer-core/errors.js +1 -1
  58. package/dist/buyer-core/negotiator.d.ts +0 -15
  59. package/dist/buyer-core/negotiator.js +3 -0
  60. package/dist/buyer-core/negotiator.js.map +1 -1
  61. package/dist/buyer-core/protocol-recovery.d.ts +67 -0
  62. package/dist/buyer-core/protocol-recovery.js +328 -0
  63. package/dist/buyer-core/protocol-recovery.js.map +1 -0
  64. package/dist/buyer-core/service.d.ts +53 -2
  65. package/dist/buyer-core/service.js +584 -74
  66. package/dist/buyer-core/service.js.map +1 -1
  67. package/dist/buyer-core/store.d.ts +27 -2
  68. package/dist/buyer-core/store.js +131 -26
  69. package/dist/buyer-core/store.js.map +1 -1
  70. package/dist/cli.js +208 -21
  71. package/dist/cli.js.map +1 -1
  72. package/dist/cloud/binding/enrollment-challenge.d.ts +1 -0
  73. package/dist/cloud/binding/enrollment-challenge.js +84 -33
  74. package/dist/cloud/binding/enrollment-challenge.js.map +1 -1
  75. package/dist/cloud/binding/enrollment-heartbeat.d.ts +2 -0
  76. package/dist/cloud/binding/enrollment-heartbeat.js +6 -2
  77. package/dist/cloud/binding/enrollment-heartbeat.js.map +1 -1
  78. package/dist/cloud/binding/proofs.d.ts +5 -0
  79. package/dist/cloud/binding/proofs.js +14 -1
  80. package/dist/cloud/binding/proofs.js.map +1 -1
  81. package/dist/cloud/binding/runtime-challenge.d.ts +2 -0
  82. package/dist/cloud/binding/runtime-challenge.js +20 -8
  83. package/dist/cloud/binding/runtime-challenge.js.map +1 -1
  84. package/dist/cloud/binding/store-lock.d.ts +13 -0
  85. package/dist/cloud/binding/store-lock.js +77 -0
  86. package/dist/cloud/binding/store-lock.js.map +1 -0
  87. package/dist/cloud/bootstrap.js +5 -2
  88. package/dist/cloud/bootstrap.js.map +1 -1
  89. package/dist/cloud/catalog-client.d.ts +4 -0
  90. package/dist/cloud/catalog-client.js +106 -29
  91. package/dist/cloud/catalog-client.js.map +1 -1
  92. package/dist/cloud/connect-service.d.ts +6 -0
  93. package/dist/cloud/connect-service.js +360 -120
  94. package/dist/cloud/connect-service.js.map +1 -1
  95. package/dist/cloud/onboarding/catalog-pipeline.d.ts +32 -1
  96. package/dist/cloud/onboarding/catalog-pipeline.js +80 -19
  97. package/dist/cloud/onboarding/catalog-pipeline.js.map +1 -1
  98. package/dist/cloud/onboarding/store.js +12 -4
  99. package/dist/cloud/onboarding/store.js.map +1 -1
  100. package/dist/cloud/product-import-tabular.js +12 -0
  101. package/dist/cloud/product-import-tabular.js.map +1 -1
  102. package/dist/commerce/http-client.d.ts +30 -1
  103. package/dist/commerce/http-client.js +11 -7
  104. package/dist/commerce/http-client.js.map +1 -1
  105. package/dist/commerce/types.d.ts +2 -1
  106. package/dist/commerce/types.js.map +1 -1
  107. package/dist/counterparty/a2a-direct/index.js +2 -20
  108. package/dist/counterparty/a2a-direct/index.js.map +1 -1
  109. package/dist/counterparty/channel.d.ts +2 -1
  110. package/dist/counterparty/channel.js.map +1 -1
  111. package/dist/counterparty/shopping-cli-hosted/index.js +2 -24
  112. package/dist/counterparty/shopping-cli-hosted/index.js.map +1 -1
  113. package/dist/demo/demo-runner.d.ts +1 -1
  114. package/dist/demo/demo-runner.js +3 -6
  115. package/dist/demo/demo-runner.js.map +1 -1
  116. package/dist/discovery/catalog-source/cloud-card.d.ts +4 -3
  117. package/dist/discovery/catalog-source/cloud-card.js +28 -25
  118. package/dist/discovery/catalog-source/cloud-card.js.map +1 -1
  119. package/dist/discovery/catalog-source/kiwi-source.d.ts +5 -19
  120. package/dist/discovery/catalog-source/kiwi-source.js +15 -12
  121. package/dist/discovery/catalog-source/kiwi-source.js.map +1 -1
  122. package/dist/discovery/catalog-source/register.js +22 -12
  123. package/dist/discovery/catalog-source/register.js.map +1 -1
  124. package/dist/discovery/catalog-source/source.d.ts +3 -17
  125. package/dist/discovery/catalog-source/source.js +11 -8
  126. package/dist/discovery/catalog-source/source.js.map +1 -1
  127. package/dist/discovery/catalog-source/types.d.ts +3 -2
  128. package/dist/discovery/catalog-source/types.js +0 -15
  129. package/dist/discovery/catalog-source/types.js.map +1 -1
  130. package/dist/discovery/merchant-subscriptions.d.ts +4 -0
  131. package/dist/discovery/merchant-subscriptions.js +72 -23
  132. package/dist/discovery/merchant-subscriptions.js.map +1 -1
  133. package/dist/discovery/resolve.d.ts +7 -3
  134. package/dist/discovery/resolve.js +62 -30
  135. package/dist/discovery/resolve.js.map +1 -1
  136. package/dist/discovery/ucp/resolver.d.ts +3 -17
  137. package/dist/discovery/ucp/resolver.js +9 -3
  138. package/dist/discovery/ucp/resolver.js.map +1 -1
  139. package/dist/fanout/disclosure.js +27 -10
  140. package/dist/fanout/disclosure.js.map +1 -1
  141. package/dist/fanout/orchestrator.js +38 -24
  142. package/dist/fanout/orchestrator.js.map +1 -1
  143. package/dist/fs/atomic-write.d.ts +11 -0
  144. package/dist/fs/atomic-write.js +67 -10
  145. package/dist/fs/atomic-write.js.map +1 -1
  146. package/dist/handoff/order-record.js +25 -3
  147. package/dist/handoff/order-record.js.map +1 -1
  148. package/dist/handoff/ucp-checkout/channel.js +2 -1
  149. package/dist/handoff/ucp-checkout/channel.js.map +1 -1
  150. package/dist/handoff/ucp-checkout/client.d.ts +1 -0
  151. package/dist/handoff/ucp-checkout/client.js +48 -37
  152. package/dist/handoff/ucp-checkout/client.js.map +1 -1
  153. package/dist/handoff/url-safety.js +3 -0
  154. package/dist/handoff/url-safety.js.map +1 -1
  155. package/dist/http/bounded-ip-rate-limit.d.ts +10 -0
  156. package/dist/http/bounded-ip-rate-limit.js +37 -0
  157. package/dist/http/bounded-ip-rate-limit.js.map +1 -0
  158. package/dist/http/cli.js +23 -0
  159. package/dist/http/cli.js.map +1 -1
  160. package/dist/http/merchant-feed-api.js +8 -1
  161. package/dist/http/merchant-feed-api.js.map +1 -1
  162. package/dist/http/merchant-management/api.js +20 -1
  163. package/dist/http/merchant-management/api.js.map +1 -1
  164. package/dist/http/merchant-management/reconciliation-worker.js +5 -2
  165. package/dist/http/merchant-management/reconciliation-worker.js.map +1 -1
  166. package/dist/http/merchant-management/trusted-page.js +1 -1
  167. package/dist/http/merchant-management/trusted-page.js.map +1 -1
  168. package/dist/http/merchant-server.js +2 -1
  169. package/dist/http/merchant-server.js.map +1 -1
  170. package/dist/http/server.d.ts +15 -0
  171. package/dist/http/server.js +107 -9
  172. package/dist/http/server.js.map +1 -1
  173. package/dist/mcp/merchant-rfq-tools.d.ts +6 -4
  174. package/dist/mcp/merchant-rfq-tools.js +2 -0
  175. package/dist/mcp/merchant-rfq-tools.js.map +1 -1
  176. package/dist/mcp/merchant-runtime-assembly.js +1 -18
  177. package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
  178. package/dist/mcp/merchant-server.d.ts +0 -22
  179. package/dist/mcp/merchant-server.js +25 -2
  180. package/dist/mcp/merchant-server.js.map +1 -1
  181. package/dist/mcp/types.d.ts +1 -1
  182. package/dist/mcp/types.js +1 -1
  183. package/dist/merchant/ai-runtime/config.d.ts +99 -0
  184. package/dist/merchant/ai-runtime/config.js +187 -0
  185. package/dist/merchant/ai-runtime/config.js.map +1 -0
  186. package/dist/merchant/ai-runtime/gate.d.ts +142 -0
  187. package/dist/merchant/ai-runtime/gate.js +343 -0
  188. package/dist/merchant/ai-runtime/gate.js.map +1 -0
  189. package/dist/merchant/ai-runtime/owner-authoritative-receipts.d.ts +5 -0
  190. package/dist/merchant/ai-runtime/owner-authoritative-receipts.js +53 -0
  191. package/dist/merchant/ai-runtime/owner-authoritative-receipts.js.map +1 -0
  192. package/dist/merchant/ai-runtime/owner-budget-gate.d.ts +10 -0
  193. package/dist/merchant/ai-runtime/owner-budget-gate.js +37 -0
  194. package/dist/merchant/ai-runtime/owner-budget-gate.js.map +1 -0
  195. package/dist/merchant/ai-runtime/owner-business-config.d.ts +33 -0
  196. package/dist/merchant/ai-runtime/owner-business-config.js +93 -0
  197. package/dist/merchant/ai-runtime/owner-business-config.js.map +1 -0
  198. package/dist/merchant/ai-runtime/owner-business-host.d.ts +24 -0
  199. package/dist/merchant/ai-runtime/owner-business-host.js +114 -0
  200. package/dist/merchant/ai-runtime/owner-business-host.js.map +1 -0
  201. package/dist/merchant/ai-runtime/owner-business-proof-contract.d.ts +26 -0
  202. package/dist/merchant/ai-runtime/owner-business-proof-contract.js +2 -0
  203. package/dist/merchant/ai-runtime/owner-business-proof-contract.js.map +1 -0
  204. package/dist/merchant/ai-runtime/owner-committed-proof.d.ts +55 -0
  205. package/dist/merchant/ai-runtime/owner-committed-proof.js +141 -0
  206. package/dist/merchant/ai-runtime/owner-committed-proof.js.map +1 -0
  207. package/dist/merchant/ai-runtime/owner-factory-config.d.ts +30 -0
  208. package/dist/merchant/ai-runtime/owner-factory-config.js +99 -0
  209. package/dist/merchant/ai-runtime/owner-factory-config.js.map +1 -0
  210. package/dist/merchant/ai-runtime/owner-file-grant.d.ts +71 -0
  211. package/dist/merchant/ai-runtime/owner-file-grant.js +118 -0
  212. package/dist/merchant/ai-runtime/owner-file-grant.js.map +1 -0
  213. package/dist/merchant/ai-runtime/owner-local-readonly-host.d.ts +17 -0
  214. package/dist/merchant/ai-runtime/owner-local-readonly-host.js +116 -0
  215. package/dist/merchant/ai-runtime/owner-local-readonly-host.js.map +1 -0
  216. package/dist/merchant/ai-runtime/owner-operation-reader.d.ts +24 -0
  217. package/dist/merchant/ai-runtime/owner-operation-reader.js +62 -0
  218. package/dist/merchant/ai-runtime/owner-operation-reader.js.map +1 -0
  219. package/dist/merchant/ai-runtime/owner-provider-guard.d.ts +9 -0
  220. package/dist/merchant/ai-runtime/owner-provider-guard.js +127 -0
  221. package/dist/merchant/ai-runtime/owner-provider-guard.js.map +1 -0
  222. package/dist/merchant/ai-runtime/owner-readonly-facts.d.ts +26 -0
  223. package/dist/merchant/ai-runtime/owner-readonly-facts.js +72 -0
  224. package/dist/merchant/ai-runtime/owner-readonly-facts.js.map +1 -0
  225. package/dist/merchant/ai-runtime/owner-sdk-tools.d.ts +43 -0
  226. package/dist/merchant/ai-runtime/owner-sdk-tools.js +83 -0
  227. package/dist/merchant/ai-runtime/owner-sdk-tools.js.map +1 -0
  228. package/dist/merchant/ai-runtime/owner-session.d.ts +341 -0
  229. package/dist/merchant/ai-runtime/owner-session.js +1280 -0
  230. package/dist/merchant/ai-runtime/owner-session.js.map +1 -0
  231. package/dist/merchant/ai-runtime/owner-storage-admission.d.ts +35 -0
  232. package/dist/merchant/ai-runtime/owner-storage-admission.js +324 -0
  233. package/dist/merchant/ai-runtime/owner-storage-admission.js.map +1 -0
  234. package/dist/merchant/ai-runtime/owner-trusted-factory.d.ts +44 -0
  235. package/dist/merchant/ai-runtime/owner-trusted-factory.js +185 -0
  236. package/dist/merchant/ai-runtime/owner-trusted-factory.js.map +1 -0
  237. package/dist/merchant/ai-runtime/sqlite-budget-store.d.ts +68 -0
  238. package/dist/merchant/ai-runtime/sqlite-budget-store.js +335 -0
  239. package/dist/merchant/ai-runtime/sqlite-budget-store.js.map +1 -0
  240. package/dist/merchant/ai-runtime/status.d.ts +64 -0
  241. package/dist/merchant/ai-runtime/status.js +56 -0
  242. package/dist/merchant/ai-runtime/status.js.map +1 -0
  243. package/dist/merchant/application/service.d.ts +1 -1
  244. package/dist/merchant/application/service.js +7 -8
  245. package/dist/merchant/application/service.js.map +1 -1
  246. package/dist/merchant/grant-store.js +9 -4
  247. package/dist/merchant/grant-store.js.map +1 -1
  248. package/dist/merchant/promotion-store.js +1 -0
  249. package/dist/merchant/promotion-store.js.map +1 -1
  250. package/dist/merchant/stats-store.js +13 -7
  251. package/dist/merchant/stats-store.js.map +1 -1
  252. package/dist/merchant/workbench-service.d.ts +1 -0
  253. package/dist/merchant/workbench-service.js +28 -11
  254. package/dist/merchant/workbench-service.js.map +1 -1
  255. package/dist/merchant-core/commands.d.ts +3 -0
  256. package/dist/merchant-core/commands.js +39 -2
  257. package/dist/merchant-core/commands.js.map +1 -1
  258. package/dist/merchant-core/executor.d.ts +2 -0
  259. package/dist/merchant-core/executor.js +1 -1
  260. package/dist/merchant-core/executor.js.map +1 -1
  261. package/dist/merchant-core/operations.d.ts +2 -2
  262. package/dist/merchant-core/operations.js +11 -9
  263. package/dist/merchant-core/operations.js.map +1 -1
  264. package/dist/merchant-core/product-import.js +1 -1
  265. package/dist/merchant-core/product-import.js.map +1 -1
  266. package/dist/merchant-core/rfq/pending-candidates.d.ts +14 -0
  267. package/dist/merchant-core/rfq/pending-candidates.js +11 -0
  268. package/dist/merchant-core/rfq/pending-candidates.js.map +1 -0
  269. package/dist/merchant-core/rfq/release-coordinator.d.ts +9 -2
  270. package/dist/merchant-core/rfq/release-coordinator.js +32 -14
  271. package/dist/merchant-core/rfq/release-coordinator.js.map +1 -1
  272. package/dist/merchant-core/rfq/repository.d.ts +4 -7
  273. package/dist/merchant-core/rfq/repository.js +10 -24
  274. package/dist/merchant-core/rfq/repository.js.map +1 -1
  275. package/dist/merchant-core/rfq/service.d.ts +5 -2
  276. package/dist/merchant-core/rfq/service.js +4 -3
  277. package/dist/merchant-core/rfq/service.js.map +1 -1
  278. package/dist/merchant-gateway/entry-server.js +25 -1
  279. package/dist/merchant-gateway/entry-server.js.map +1 -1
  280. package/dist/merchant-gateway/pinned-fetch.d.ts +9 -2
  281. package/dist/merchant-gateway/pinned-fetch.js +63 -27
  282. package/dist/merchant-gateway/pinned-fetch.js.map +1 -1
  283. package/dist/merchant-runtime/manager.d.ts +5 -2
  284. package/dist/merchant-runtime/manager.js +40 -11
  285. package/dist/merchant-runtime/manager.js.map +1 -1
  286. package/dist/negotiation/context-map/store.js +4 -13
  287. package/dist/negotiation/context-map/store.js.map +1 -1
  288. package/dist/negotiation/domain/common.js +33 -2
  289. package/dist/negotiation/domain/common.js.map +1 -1
  290. package/dist/negotiation/domain/envelope.d.ts +2 -5
  291. package/dist/negotiation/domain/envelope.js +36 -9
  292. package/dist/negotiation/domain/envelope.js.map +1 -1
  293. package/dist/negotiation/domain/objects.js +14 -0
  294. package/dist/negotiation/domain/objects.js.map +1 -1
  295. package/dist/negotiation/idempotency/store.d.ts +4 -1
  296. package/dist/negotiation/idempotency/store.js +80 -52
  297. package/dist/negotiation/idempotency/store.js.map +1 -1
  298. package/dist/negotiation/idempotency/types.d.ts +7 -1
  299. package/dist/negotiation/idempotency/types.js +1 -1
  300. package/dist/negotiation/idempotency/types.js.map +1 -1
  301. package/dist/negotiation/jcs.js +11 -16
  302. package/dist/negotiation/jcs.js.map +1 -1
  303. package/dist/negotiation/ledger/store.d.ts +15 -9
  304. package/dist/negotiation/ledger/store.js +201 -65
  305. package/dist/negotiation/ledger/store.js.map +1 -1
  306. package/dist/negotiation/recovery/recover.js +30 -30
  307. package/dist/negotiation/recovery/recover.js.map +1 -1
  308. package/dist/negotiation/recovery/types.d.ts +3 -3
  309. package/dist/net/request-budget.d.ts +17 -0
  310. package/dist/net/request-budget.js +63 -0
  311. package/dist/net/request-budget.js.map +1 -0
  312. package/dist/operator/controller.d.ts +1 -1
  313. package/dist/operator/controller.js +23 -12
  314. package/dist/operator/controller.js.map +1 -1
  315. package/dist/operator/runner.d.ts +69 -0
  316. package/dist/operator/runner.js +260 -39
  317. package/dist/operator/runner.js.map +1 -1
  318. package/dist/operator/strategy.d.ts +2 -0
  319. package/dist/operator/strategy.js +11 -0
  320. package/dist/operator/strategy.js.map +1 -1
  321. package/dist/privacy/workbench-retention.js +28 -10
  322. package/dist/privacy/workbench-retention.js.map +1 -1
  323. package/dist/product-init.js +25 -4
  324. package/dist/product-init.js.map +1 -1
  325. package/dist/product-publish.js +3 -102
  326. package/dist/product-publish.js.map +1 -1
  327. package/dist/runtime/foreground.d.ts +1 -1
  328. package/dist/runtime/foreground.js +3 -0
  329. package/dist/runtime/foreground.js.map +1 -1
  330. package/dist/runtime/model.js +4 -0
  331. package/dist/runtime/model.js.map +1 -1
  332. package/dist/supervisor/manage.js +109 -35
  333. package/dist/supervisor/manage.js.map +1 -1
  334. package/dist/trust/identity/jws.js +46 -5
  335. package/dist/trust/identity/jws.js.map +1 -1
  336. package/dist/trust/identity/message-signature.js +15 -2
  337. package/dist/trust/identity/message-signature.js.map +1 -1
  338. package/dist/trust/records/store.d.ts +8 -1
  339. package/dist/trust/records/store.js +68 -6
  340. package/dist/trust/records/store.js.map +1 -1
  341. package/dist/weixin/channel.d.ts +4 -0
  342. package/dist/weixin/channel.js +17 -3
  343. package/dist/weixin/channel.js.map +1 -1
  344. package/dist/weixin/cli-weixin.js +8 -2
  345. package/dist/weixin/cli-weixin.js.map +1 -1
  346. package/package.json +32 -8
  347. package/scripts/check-install-toolchain.mjs +69 -0
@@ -46,6 +46,18 @@ function utcNow() {
46
46
  function policyActionMode(policy, action) {
47
47
  return policy.actions[action]?.mode ?? "never";
48
48
  }
49
+ /** review P1-2:宽容 JSON 解析(非 JSON 返回 undefined,不抛)。 */
50
+ function safeParseJson(text) {
51
+ if (text === undefined || text === "")
52
+ return {};
53
+ try {
54
+ const parsed = JSON.parse(text);
55
+ return parsed !== null && typeof parsed === "object" ? parsed : {};
56
+ }
57
+ catch {
58
+ return {};
59
+ }
60
+ }
49
61
  export class KiwiBuyerService {
50
62
  store;
51
63
  principal;
@@ -228,7 +240,35 @@ export class KiwiBuyerService {
228
240
  };
229
241
  const { task: persisted, created: isCreated } = this.store.createTask(task);
230
242
  if (!isCreated) {
231
- // 幂等命中:相同 idempotency_key 的重复提交返回原任务,不产生重复写入(§6.2)。
243
+ if (this.quoteFetcher?.recoverQuotes !== undefined) {
244
+ const original = this.decodeTask(persisted).intent;
245
+ if (original !== undefined && contentDigest(original) !== contentDigest(input.intent))
246
+ throw new McpError("idempotency_conflict", "same task key has different intent");
247
+ if (persisted.status !== "in_progress") {
248
+ const selected = [...new Set(this.store.listCandidates(persisted.task_id).map(c => String(c.merchant_id)))].sort();
249
+ const requested = [...new Set(input.merchant_ids ?? [])].sort();
250
+ if (contentDigest(selected) !== contentDigest(requested))
251
+ throw new McpError("idempotency_conflict", "same task key has different selected merchants");
252
+ }
253
+ }
254
+ // Recovery can only read previously persisted protocol receipts/results, never send.
255
+ if (this.quoteFetcher?.recoverQuotes !== undefined && ["in_progress", "partial_success"].includes(persisted.status) && !this.store.hasAgreementForTask(persisted.task_id)) {
256
+ const originalCandidates = this.store.listCandidates(persisted.task_id);
257
+ const results = await this.quoteFetcher.recoverQuotes(this.protocolContext(persisted, input.merchant_ids ?? []));
258
+ if (results.length > 0)
259
+ return this.store.transaction(() => {
260
+ if (this.store.hasAgreementForTask(persisted.task_id) || contentDigest(this.store.listCandidates(persisted.task_id)) !== contentDigest(originalCandidates))
261
+ throw new McpError("idempotency_conflict", "task candidates or accepted agreement changed during recovery");
262
+ for (const result of results)
263
+ this.store.replaceRecoveredCandidate(persisted.task_id, result);
264
+ const candidates = this.northboundCandidates(persisted.task_id);
265
+ const status = candidates.length > 0 && candidates.every(c => c.status === "succeeded") ? "succeeded" : "partial_success";
266
+ const updated = this.store.updateTask(persisted.task_id, { status, payload: JSON.stringify({ ...this.decodeTask(persisted), status, updated_at: this.now(), candidates }) }, persisted);
267
+ const decoded = this.decodeTask(updated);
268
+ assertNorthboundContractValid("persistent-task", decoded, "recovered quotes result");
269
+ return { task: decoded, created: false };
270
+ });
271
+ }
232
272
  return { task: this.decodeTask(persisted), created: false };
233
273
  }
234
274
  for (const candidate of preCandidates) {
@@ -237,6 +277,7 @@ export class KiwiBuyerService {
237
277
  // 真实 fan-out 交给注入的 QuoteFetcher(Phase 2 接线 A2A/UCP)。v0.1 无 fetcher
238
278
  // 时任务保持 in_progress + resumable,可恢复;有 fetcher 时按部分失败语义回写。
239
279
  let status = "in_progress";
280
+ let quotedResults = [];
240
281
  if (this.quoteFetcher !== undefined) {
241
282
  const merchants = input.merchant_ids ?? [];
242
283
  const index = this.merchantIndex;
@@ -256,36 +297,35 @@ export class KiwiBuyerService {
256
297
  }
257
298
  return { merchant_id: m, name: m, verified: false, capabilities: [] };
258
299
  }));
259
- const results = await this.quoteFetcher.requestQuotes(input.intent, merchantRecords);
300
+ const results = await this.quoteFetcher.requestQuotes(input.intent, merchantRecords, this.protocolContext(persisted, input.merchant_ids ?? []));
260
301
  const successes = results.filter((r) => r.status === "succeeded").length;
261
302
  if (results.length > 0) {
262
- for (const r of results) {
263
- this.store.addCandidate(taskId, {
264
- candidate_id: `cand-${uuidv7()}`,
265
- merchant_id: r.merchant_id,
266
- status: r.status,
267
- provenance: r.provenance,
268
- failure: r.failure,
269
- retryable: r.status === "failed" ? (r.failure?.retryable ?? false) : false,
270
- });
271
- }
303
+ quotedResults = results;
272
304
  status = successes === results.length ? "succeeded" : "partial_success";
273
305
  }
274
306
  }
275
- const updated = this.store.updateTask(taskId, {
276
- status,
277
- resumable: true,
278
- payload: JSON.stringify({
279
- ...this.decodeTask(task),
307
+ return this.store.transaction(() => {
308
+ for (const r of quotedResults)
309
+ this.store.addCandidate(taskId, { candidate_id: `cand-${uuidv7()}`, merchant_id: r.merchant_id, status: r.status, provenance: r.provenance, terms: r.terms, failure: r.failure, retryable: r.status === "failed" ? (r.failure?.retryable ?? false) : false });
310
+ const updated = this.store.updateTask(taskId, {
280
311
  status,
281
- updated_at: this.now(),
282
- candidates: this.store.listCandidates(taskId),
283
- }),
312
+ resumable: true,
313
+ payload: JSON.stringify({
314
+ ...this.decodeTask(task),
315
+ status,
316
+ updated_at: this.now(),
317
+ candidates: this.northboundCandidates(taskId),
318
+ }),
319
+ }, persisted);
320
+ const decoded = this.decodeTask(updated);
321
+ // 冻结契约强制:持久任务记录必须满足 persistent-task/1.0 schema(§6.2)。
322
+ assertNorthboundContractValid("persistent-task", decoded, "requestQuotes result");
323
+ return { task: decoded, created: true };
284
324
  });
285
- const decoded = this.decodeTask(updated);
286
- // 冻结契约强制:持久任务记录必须满足 persistent-task/1.0 schema(§6.2)。
287
- assertNorthboundContractValid("persistent-task", decoded, "requestQuotes result");
288
- return { task: decoded, created: true };
325
+ }
326
+ protocolContext(task, requestedMerchants) {
327
+ const intent = this.decodeTask(task).intent;
328
+ 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 }) };
289
329
  }
290
330
  // ---- Northbound:kiwi_get_task --------------------------------------------
291
331
  getTask(taskId) {
@@ -299,6 +339,10 @@ export class KiwiBuyerService {
299
339
  }
300
340
  // ---- Northbound:kiwi_negotiate -------------------------------------------
301
341
  async negotiate(input) {
342
+ if (input.action !== "counter_offer" && input.action !== "clarification")
343
+ throw new McpError("invalid_params", "invalid negotiation action");
344
+ if (input.action === "clarification")
345
+ throw new McpError("invalid_params", "clarification is not supported by the current negotiator");
302
346
  const task = this.store.getTask(input.task_id);
303
347
  if (task === undefined)
304
348
  throw new McpError("task_not_found", `task ${input.task_id} not found`);
@@ -320,7 +364,28 @@ export class KiwiBuyerService {
320
364
  summary: input.summary,
321
365
  };
322
366
  if (this.negotiator !== undefined) {
323
- step = await this.negotiator.negotiate(input.task_id, {}, step, this.store.listCandidates(input.task_id));
367
+ // review P1-2(A316 补充校准):counter 外发前的限额闸口——succeeded
368
+ // 候选逐一过 limitViolation(结构化事实),仅放行未被约束阻断的候选;
369
+ // 全部被阻断时显式拒绝(不存在合法还价对象)。clarification 无商业
370
+ // 承诺,不过商业闸。
371
+ let gated = this.store.listCandidates(input.task_id);
372
+ if (input.action === "counter_offer") {
373
+ const succeeded = gated.filter((c) => c.status === "succeeded");
374
+ const passable = succeeded.filter((c) => this.limitViolation("counter_offer", {
375
+ taskId: input.task_id,
376
+ candidateId: String(c.candidate_id),
377
+ }) === undefined);
378
+ if (succeeded.length > 0 && passable.length === 0) {
379
+ throw new McpError("delegation_denied", "counter_offer 被委托约束阻断:全部报价候选超出 limits(fail-closed)");
380
+ }
381
+ const passableIds = new Set(passable.map((c) => String(c.candidate_id)));
382
+ gated = gated.filter((c) => c.status !== "succeeded" || passableIds.has(String(c.candidate_id)));
383
+ }
384
+ // review P1-2(A327 校准):negotiator 需要任务**真实意图**(quantity
385
+ // 与 unit 从 intent 透传到外发 wire)——此前传空 intent {},gate 拿到
386
+ // quantity=1/unit=undefined,max_quantity.unit 可能误拒或漏配。
387
+ const decodedForIntent = this.decodeTask(task);
388
+ step = await this.negotiator.negotiate(input.task_id, (decodedForIntent.intent ?? {}), step, gated, this.protocolContext(task));
324
389
  }
325
390
  const decoded = this.decodeTask(task);
326
391
  const prior = Array.isArray(decoded.steps)
@@ -331,7 +396,7 @@ export class KiwiBuyerService {
331
396
  const updated = this.store.updateTask(input.task_id, {
332
397
  status: currentStatus === "pending" ? "in_progress" : currentStatus,
333
398
  payload: JSON.stringify({ ...decoded, steps, updated_at: this.now() }),
334
- });
399
+ }, task);
335
400
  return { task: this.decodeTask(updated), step };
336
401
  }
337
402
  // ---- Northbound:kiwi_accept_agreement ------------------------------------
@@ -349,52 +414,173 @@ export class KiwiBuyerService {
349
414
  throw new McpError("invalid_params", `candidate ${input.candidate_id} not found on task`);
350
415
  }
351
416
  const termsDigest = contentDigest(candidate);
417
+ // review P1-2(A316 校准):消费绑定 = 结构化 canonical digest(无分隔符
418
+ // 歧义);同逻辑重放的唯一判据,换候选/摘要/任务都是不同绑定。
419
+ const consumedBinding = this.consumeBinding({
420
+ task_id: input.task_id,
421
+ candidate_id: input.candidate_id,
422
+ terms_digest: termsDigest,
423
+ });
352
424
  const authorization = await this.evaluateAuthorization("accept_nonbinding", {
353
425
  taskId: input.task_id,
354
426
  candidateId: input.candidate_id,
355
427
  candidateDigest: termsDigest,
356
428
  approvalId: input.approval_id,
429
+ approvalConsumedBinding: consumedBinding,
357
430
  });
358
431
  if (authorization.effective_decision !== "granted") {
359
432
  throw new McpError("authorization_denied", "AcceptNonbinding 未获五层授权", {
360
433
  authorization,
361
434
  });
362
435
  }
363
- const agreementId = `agreement-${uuidv7()}`;
364
436
  const now = this.now();
365
- const agreement = {
366
- agreement_id: agreementId,
367
- task_id: input.task_id,
368
- negotiation_id: candidate.provenance
369
- ?.negotiation_id,
370
- terms_digest: termsDigest,
371
- created_at: now,
372
- binding_effect: "nonbinding",
373
- creates_order: false,
374
- reserves_inventory: false,
375
- authorizes_payment: false,
376
- accepted_candidate_id: input.candidate_id,
377
- authorization_id: authorization.authorization_id,
378
- };
379
- this.store.createAgreement({
380
- agreement_id: agreementId,
381
- task_id: input.task_id,
382
- negotiation_id: agreement.negotiation_id,
383
- terms_digest: termsDigest,
384
- created_at: now,
385
- expires_at: undefined,
386
- payload: JSON.stringify(agreement),
387
- });
388
- const updated = this.store.updateTask(input.task_id, {
389
- status: "succeeded",
390
- payload: JSON.stringify({
391
- ...this.decodeTask(task),
437
+ // review P1-2(A316 校准):短事务原子消费——事务内重读授权、写
438
+ // agreement/task/used 及可重放结果;任何失败 ROLLBACK(无部分提交、
439
+ // 无事后补偿、不烧毁有效批准——同绑定重试重新进入本事务)。node:sqlite
440
+ // 同步执行 + BEGIN IMMEDIATE 写锁,进程内/跨连接均互斥。
441
+ return this.store.transaction(() => {
442
+ const freshTask = this.store.getTask(input.task_id);
443
+ if (freshTask === undefined) {
444
+ throw new McpError("task_not_found", `task ${input.task_id} not found`);
445
+ }
446
+ if (input.approval_id !== undefined) {
447
+ const fresh = this.store.getApproval(input.approval_id);
448
+ if (fresh === undefined) {
449
+ throw new McpError("approval_required", `approval ${input.approval_id} 不存在`, {
450
+ approval_id: input.approval_id,
451
+ });
452
+ }
453
+ // review P1-2(A325 收口):事务内 **fresh 授权强核**——同短事务
454
+ // (无外部 await)重核 approved 状态/task/action/digest/有效期与
455
+ // 候选最新状态;跨连接 await 窗口的撤销/改绑在此收口(源审纵深:
456
+ // 不宣称 BEGIN 本身等于权限重核,这里是显式逐项复核)。
457
+ if (fresh.task_id !== input.task_id) {
458
+ throw new McpError("approval_denied", `approval ${input.approval_id} 属于任务 ${fresh.task_id},与请求任务 ${input.task_id} 不一致`);
459
+ }
460
+ if (fresh.action !== "accept_nonbinding") {
461
+ throw new McpError("approval_denied", `approval ${input.approval_id} 动作=${fresh.action} 与 accept 不一致`);
462
+ }
463
+ // review P1-2(A327 校准):审批未绑定候选摘要(undefined)不得跳过
464
+ // 校验放行——fail-closed。
465
+ if (fresh.candidate_digest === undefined) {
466
+ throw new McpError("approval_denied", `approval ${input.approval_id} 未绑定候选摘要(digest 缺失,fail-closed)`);
467
+ }
468
+ if (fresh.candidate_digest !== termsDigest) {
469
+ throw new McpError("approval_denied", `approval ${input.approval_id} 绑定候选摘要与当前候选不一致`);
470
+ }
471
+ if (fresh.expires_at !== undefined &&
472
+ Date.parse(fresh.expires_at) < Date.parse(this.now())) {
473
+ throw new McpError("approval_denied", `approval ${input.approval_id} 已过期`);
474
+ }
475
+ // review P1-2(A327 校准):候选**内容与状态**重核——some(ID) 只证
476
+ // 明 ID 存在,不证明内容/状态未变;事务内重取候选、重算摘要并核对
477
+ // 仍为 succeeded(锁外 termsDigest 不能默认仍是最新)。
478
+ const freshCandidates = this.store.listCandidates(input.task_id);
479
+ const freshCandidate = freshCandidates.find((c) => c.candidate_id === input.candidate_id);
480
+ if (freshCandidate === undefined) {
481
+ throw new McpError("invalid_params", `candidate ${input.candidate_id} 已不存在于任务(候选状态已推进)`);
482
+ }
483
+ if (freshCandidate.status !== "succeeded") {
484
+ throw new McpError("authorization_denied", `候选状态已推进为 ${freshCandidate.status},不再可接受`);
485
+ }
486
+ if (contentDigest(freshCandidate) !== termsDigest) {
487
+ throw new McpError("approval_denied", "候选内容已变化(fresh 摘要与审批绑定不一致),需重新审批");
488
+ }
489
+ if (fresh.status === "used") {
490
+ const consumed = this.approvalConsumed(fresh);
491
+ if (consumed !== undefined &&
492
+ consumed.binding === consumedBinding) {
493
+ // 同逻辑重放:返回库里既有的同一 agreement(非虚构结果)。
494
+ const existing = consumed.ref.startsWith("agreement-")
495
+ ? this.store.getAgreement(consumed.ref)
496
+ : undefined;
497
+ if (existing === undefined) {
498
+ throw new McpError("approval_denied", `approval ${input.approval_id} 已消费但绑定效果不可读;需要人工对账`);
499
+ }
500
+ return {
501
+ task: this.decodeTask(this.store.getTask(input.task_id)),
502
+ agreement: JSON.parse(existing.payload),
503
+ authorization,
504
+ };
505
+ }
506
+ throw new McpError("approval_denied", `approval ${input.approval_id} 已被消费(一次性),且请求内容不同`);
507
+ }
508
+ if (fresh.status !== "approved") {
509
+ // review P1-2(A325 收口):消费时点必须仍是 approved——跨连接
510
+ // await 窗口内被 deny/回退到 pending 的审批不得消费。
511
+ throw new McpError("approval_denied", `approval ${input.approval_id} 状态=${fresh.status},消费时点必须为 approved`);
512
+ }
513
+ }
514
+ // review P1-2(A331 校准):候选 fresh 强核对**所有真实消费分支**生效
515
+ //——此前仅 approval 分支覆盖,合法 auto(无审批)路径仍旧 snapshot。
516
+ // 同短事务内重取候选:ID 仍在、状态仍 succeeded、**重算 contentDigest
517
+ // 与本次绑定 termsDigest 一致**(锁外旧 snapshot 不能默认最新)。
518
+ // 任务/候选 expiry 按既有合同(上方 task.expires_at 检查)核,不新加 TTL。
519
+ const freshCandidate = this.store
520
+ .listCandidates(input.task_id)
521
+ .find((c) => c.candidate_id === input.candidate_id);
522
+ if (freshCandidate === undefined) {
523
+ throw new McpError("invalid_params", `candidate ${input.candidate_id} 已不存在于任务(候选状态已推进)`);
524
+ }
525
+ if (freshCandidate.status !== "succeeded") {
526
+ throw new McpError("authorization_denied", `候选状态已推进为 ${freshCandidate.status},不再可接受`);
527
+ }
528
+ if (contentDigest(freshCandidate) !== termsDigest) {
529
+ throw new McpError("approval_denied", "候选内容已变化(fresh 摘要与本次绑定不一致),需重新获取报价");
530
+ }
531
+ // 崩溃孤儿复用:事务内查同 (task, terms_digest) 既有 agreement(此前
532
+ // 崩溃留下的已提交行)——复用同一 ID,效果恰一次。
533
+ const orphan = this.store.findAgreementByTerms(input.task_id, termsDigest);
534
+ const agreementId = orphan !== undefined ? orphan.agreement_id : `agreement-${uuidv7()}`;
535
+ const agreement = {
392
536
  agreement_id: agreementId,
537
+ task_id: input.task_id,
538
+ negotiation_id: candidate.provenance
539
+ ?.negotiation_id,
540
+ terms_digest: termsDigest,
541
+ created_at: now,
542
+ binding_effect: "nonbinding",
543
+ creates_order: false,
544
+ reserves_inventory: false,
545
+ authorizes_payment: false,
546
+ accepted_candidate_id: input.candidate_id,
547
+ authorization_id: authorization.authorization_id,
548
+ };
549
+ if (orphan === undefined) {
550
+ this.store.createAgreement({
551
+ agreement_id: agreementId,
552
+ task_id: input.task_id,
553
+ negotiation_id: agreement.negotiation_id,
554
+ terms_digest: termsDigest,
555
+ created_at: now,
556
+ expires_at: undefined,
557
+ payload: JSON.stringify(agreement),
558
+ });
559
+ }
560
+ const updated = this.store.updateTask(input.task_id, {
393
561
  status: "succeeded",
394
- updated_at: now,
395
- }),
562
+ payload: JSON.stringify({
563
+ ...this.decodeTask(freshTask),
564
+ agreement_id: agreementId,
565
+ status: "succeeded",
566
+ updated_at: now,
567
+ }),
568
+ }, freshTask);
569
+ if (input.approval_id !== undefined) {
570
+ const approval = this.store.getApproval(input.approval_id);
571
+ if (approval !== undefined) {
572
+ this.store.setApproval(approval.task_id, {
573
+ ...approval,
574
+ status: "used",
575
+ authorization_json: JSON.stringify({
576
+ ...safeParseJson(approval.authorization_json),
577
+ consumed: { ref: agreementId, binding: consumedBinding, kind: "agreement" },
578
+ }),
579
+ });
580
+ }
581
+ }
582
+ return { task: this.decodeTask(updated), agreement, authorization };
396
583
  });
397
- return { task: this.decodeTask(updated), agreement, authorization };
398
584
  }
399
585
  // ---- Northbound:kiwi_get_agreement ---------------------------------------
400
586
  getAgreement(agreementId) {
@@ -410,19 +596,66 @@ export class KiwiBuyerService {
410
596
  if (stored === undefined) {
411
597
  throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
412
598
  }
599
+ // review P1-2(A316 校准):handoff 消费绑定 = 结构化 canonical digest
600
+ //(agreement/destination/url),无分隔符歧义。
601
+ const consumedBinding = this.consumeBinding({
602
+ agreement_id: input.agreement_id,
603
+ destination_type: input.destination_type,
604
+ url: input.url ?? null,
605
+ });
413
606
  const authorization = await this.evaluateAuthorization("handoff", {
414
607
  taskId: stored.task_id,
415
608
  approvalId: input.approval_id,
609
+ approvalConsumedBinding: consumedBinding,
416
610
  });
417
611
  if (authorization.effective_decision !== "granted") {
418
612
  throw new McpError("authorization_denied", "Handoff 未获五层授权", { authorization });
419
613
  }
420
- const handoffRef = {
421
- handoff_id: `handoff-${uuidv7()}`,
422
- destination_type: input.destination_type,
423
- ...(input.url !== undefined ? { url: input.url } : {}),
424
- };
425
- return { handoff_ref: handoffRef, authorization };
614
+ if (input.approval_id === undefined) {
615
+ const handoffRef = {
616
+ handoff_id: `handoff-${uuidv7()}`,
617
+ destination_type: input.destination_type,
618
+ ...(input.url !== undefined ? { url: input.url } : {}),
619
+ };
620
+ return { handoff_ref: handoffRef, authorization };
621
+ }
622
+ // review P1-2(A316 校准):短事务原子消费——事务内重读审批、生成 ref、
623
+ // 消费;同绑定重放返回**库里记录的同一 ref**(非虚构);失败 ROLLBACK
624
+ // 不烧毁审批。
625
+ return this.store.transaction(() => {
626
+ const approval = this.store.getApproval(input.approval_id);
627
+ if (approval === undefined) {
628
+ throw new McpError("invalid_params", `approval ${input.approval_id} 不存在`);
629
+ }
630
+ if (approval.status === "used") {
631
+ const consumed = this.approvalConsumed(approval);
632
+ if (consumed !== undefined && consumed.binding === consumedBinding) {
633
+ return {
634
+ handoff_ref: {
635
+ handoff_id: consumed.ref,
636
+ destination_type: input.destination_type,
637
+ ...(input.url !== undefined ? { url: input.url } : {}),
638
+ },
639
+ authorization,
640
+ };
641
+ }
642
+ throw new McpError("approval_denied", `approval ${input.approval_id} 已被消费(一次性),且请求内容不同`);
643
+ }
644
+ const handoffRef = {
645
+ handoff_id: `handoff-${uuidv7()}`,
646
+ destination_type: input.destination_type,
647
+ ...(input.url !== undefined ? { url: input.url } : {}),
648
+ };
649
+ this.store.setApproval(approval.task_id, {
650
+ ...approval,
651
+ status: "used",
652
+ authorization_json: JSON.stringify({
653
+ ...safeParseJson(approval.authorization_json),
654
+ consumed: { ref: handoffRef.handoff_id, binding: consumedBinding, kind: "handoff" },
655
+ }),
656
+ });
657
+ return { handoff_ref: handoffRef, authorization };
658
+ });
426
659
  }
427
660
  // ---- 持久审批(宿主适配面;kiwi_approve / kiwi_reject 为 MCP 工具)----------
428
661
  /** 创建 pending 审批记录(ASK 动作触发)。返回持久 approval_id。 */
@@ -447,15 +680,16 @@ export class KiwiBuyerService {
447
680
  const stored = this.store.getApproval(input.approval_id);
448
681
  if (stored === undefined)
449
682
  throw new McpError("invalid_params", `approval ${input.approval_id} not found`);
450
- if (stored.expires_at !== undefined && Date.parse(stored.expires_at) < Date.parse(this.now())) {
683
+ if (stored.status !== "pending" || this.approvalConsumed(stored) !== undefined) {
684
+ throw new McpError("approval_denied", `approval ${input.approval_id} 状态=${stored.status},只能批准未消费的 pending 审批`);
685
+ }
686
+ const decidedAt = this.now();
687
+ if (stored.expires_at !== undefined && (!Number.isFinite(Date.parse(stored.expires_at)) || Date.parse(stored.expires_at) < Date.parse(decidedAt))) {
451
688
  throw new McpError("approval_denied", `approval ${input.approval_id} 已过期`);
452
689
  }
453
- this.store.setApproval(stored.task_id, {
454
- ...stored,
455
- status: "approved",
456
- decided_at: this.now(),
457
- authorization_json: JSON.stringify(input.authorization),
458
- });
690
+ if (!this.store.approvePending(stored, JSON.stringify(input.authorization), decidedAt)) {
691
+ throw new McpError("approval_denied", `approval ${input.approval_id} 已改变或过期,不能覆盖既有决定`);
692
+ }
459
693
  }
460
694
  /** 拒绝一个 pending 审批(deny 路径;deny 优先,§5.5)。 */
461
695
  rejectApproval(input) {
@@ -559,6 +793,44 @@ export class KiwiBuyerService {
559
793
  reason: `approval ${approval.approval_id} 动作=${approval.action} 与请求 ${action} 不一致`,
560
794
  };
561
795
  }
796
+ else if (approval.task_id !== opts.taskId) {
797
+ // review P1-2:审批必须属于当前任务——跨任务重放他任务的批准即拒。
798
+ layers.runtime_approval = {
799
+ status: "denied",
800
+ reason: `approval ${approval.approval_id} 属于任务 ${approval.task_id},与请求任务 ${opts.taskId} 不一致`,
801
+ };
802
+ }
803
+ else if (
804
+ // review P1-2:候选绑定——批准时的 digest 与当前候选不一致(含批准时
805
+ // 未绑定候选)即拒;对照 auth/merchant-oauth.ts 的既有比对纪律。
806
+ (opts.candidateDigest !== undefined &&
807
+ (approval.candidate_digest === undefined ||
808
+ approval.candidate_digest !== opts.candidateDigest))) {
809
+ layers.runtime_approval = {
810
+ status: "denied",
811
+ reason: `approval ${approval.approval_id} 未绑定当前候选(digest 不一致)`,
812
+ };
813
+ }
814
+ else if (approval.status === "used") {
815
+ // review P1-2(A316 校准):一次性消费——已消费审批只在「同逻辑重放」
816
+ //(canonical digest 绑定完全一致)时放行,调用方返回**库里既有**的
817
+ // 同一效果;换 candidate/digest/action/target 一律拒绝。
818
+ const consumed = this.approvalConsumed(approval);
819
+ if (opts.approvalConsumedBinding !== undefined &&
820
+ consumed !== undefined &&
821
+ consumed.binding === opts.approvalConsumedBinding) {
822
+ layers.runtime_approval = {
823
+ status: "allowed",
824
+ reason: `idempotent replay of consumed approval ${approval.approval_id} (same binding)`,
825
+ };
826
+ }
827
+ else {
828
+ layers.runtime_approval = {
829
+ status: "denied",
830
+ reason: `approval ${approval.approval_id} 已被消费(一次性),且请求内容不同`,
831
+ };
832
+ }
833
+ }
562
834
  else if (approval.status === "pending") {
563
835
  throw new McpError("approval_required", `approval ${approval.approval_id} 待审批`, {
564
836
  approval_id: approval.approval_id,
@@ -582,8 +854,11 @@ export class KiwiBuyerService {
582
854
  }
583
855
  }
584
856
  // AUTO:delegation 层默认 allowed。
585
- // 硬约束(limits):只对已解析的约束做 deny。
586
- const denyReason = this.limitViolation(action, opts);
857
+ // 硬约束(limits):review P1-2 起对 accept 类动作核验候选价格/商家/币种/数量。
858
+ const denyReason = this.limitViolation(action, {
859
+ taskId: opts.taskId,
860
+ candidateId: opts.candidateId,
861
+ });
587
862
  if (denyReason !== undefined) {
588
863
  layers.merchant_hard_policy = { status: "denied", reason: denyReason };
589
864
  }
@@ -610,7 +885,109 @@ export class KiwiBuyerService {
610
885
  }
611
886
  return authorization;
612
887
  }
613
- limitViolation(action, _opts) {
888
+ /**
889
+ * review P1-2(A319 校准):**实际外发 counter 提案**的限额门——对最终
890
+ * 结构化提案(而非旧候选)核验币种/单位/数量总量/单价/合计/安全 minor/
891
+ * 商家白名单/deadline。由 negotiator 在 sendMessage 前调用;返回 undefined
892
+ * = 放行。
893
+ */
894
+ checkCounterProposalLimits(proposal) {
895
+ const limits = this.policy.limits;
896
+ if (limits === undefined)
897
+ return undefined;
898
+ if (limits.deadline !== undefined &&
899
+ Date.parse(limits.deadline) < Date.parse(this.now())) {
900
+ return `delegation deadline ${limits.deadline} 已过期`;
901
+ }
902
+ if (limits.allowed_merchants !== undefined &&
903
+ !limits.allowed_merchants.includes(proposal.merchant_id)) {
904
+ return `merchant ${proposal.merchant_id} 不在 allowed_merchants`;
905
+ }
906
+ const terms = {
907
+ currency: proposal.currency,
908
+ items: [
909
+ {
910
+ sku: proposal.sku,
911
+ quantity_value: proposal.quantity_value,
912
+ ...(proposal.quantity_unit !== undefined ? { quantity_unit: proposal.quantity_unit } : {}),
913
+ unit_price_minor: proposal.unit_price_minor,
914
+ },
915
+ ],
916
+ total_price_minor: proposal.total_price_minor,
917
+ };
918
+ return this.termsFactsViolation(terms);
919
+ }
920
+ /** 结构化报价事实的约束核验(accept/counter 共用;缺事实 fail-closed)。 */
921
+ termsFactsViolation(terms) {
922
+ const limits = this.policy.limits;
923
+ if (limits === undefined)
924
+ return undefined;
925
+ if (typeof terms.currency !== "string" || terms.currency === "") {
926
+ return "结构化报价缺币种,无法核验委托约束(fail-closed)";
927
+ }
928
+ if (limits.allowed_currencies !== undefined &&
929
+ !limits.allowed_currencies.includes(terms.currency)) {
930
+ return `币种 ${terms.currency} 不在 allowed_currencies`;
931
+ }
932
+ if (!Array.isArray(terms.items) || terms.items.length === 0) {
933
+ return "结构化报价无明细行,无法核验委托约束(fail-closed)";
934
+ }
935
+ for (const item of terms.items) {
936
+ if (!Number.isSafeInteger(item.unit_price_minor) || item.unit_price_minor < 0) {
937
+ return "明细单价不是安全整数 minor(拒绝非整数货币)";
938
+ }
939
+ if (typeof item.quantity_value !== "number" ||
940
+ !Number.isFinite(item.quantity_value) ||
941
+ item.quantity_value <= 0) {
942
+ return "明细数量必须为正数(KNP number>0)";
943
+ }
944
+ }
945
+ if (!Number.isSafeInteger(terms.total_price_minor) || terms.total_price_minor < 0) {
946
+ return "总价不是安全整数 minor(拒绝非整数货币)";
947
+ }
948
+ if (limits.max_quantity !== undefined &&
949
+ typeof limits.max_quantity.unit === "string" &&
950
+ limits.max_quantity.unit !== "") {
951
+ const bad = terms.items.find((it) => typeof it.quantity_unit !== "string" ||
952
+ it.quantity_unit === "" ||
953
+ it.quantity_unit !== limits.max_quantity.unit);
954
+ if (bad !== undefined) {
955
+ return `明细数量单位缺失或与 max_quantity.unit(${limits.max_quantity.unit}) 不一致`;
956
+ }
957
+ }
958
+ if (limits.max_unit_price !== undefined) {
959
+ if (limits.max_unit_price.currency !== terms.currency) {
960
+ return `max_unit_price 币种(${limits.max_unit_price.currency})与报价币种(${terms.currency})不绑定`;
961
+ }
962
+ const over = terms.items.find((it) => it.unit_price_minor > limits.max_unit_price.amount_minor);
963
+ if (over !== undefined) {
964
+ return `单价 ${over.unit_price_minor} minor 超过 max_unit_price ${limits.max_unit_price.amount_minor}`;
965
+ }
966
+ }
967
+ if (limits.max_total_price !== undefined) {
968
+ if (limits.max_total_price.currency !== terms.currency) {
969
+ return `max_total_price 币种(${limits.max_total_price.currency})与报价币种(${terms.currency})不绑定`;
970
+ }
971
+ const computed = terms.items.reduce((sum, it) => sum + it.unit_price_minor * it.quantity_value, 0);
972
+ if (!Number.isSafeInteger(computed)) {
973
+ return "总价明细合计不是安全整数 minor(拒绝非整数货币)";
974
+ }
975
+ if (computed !== terms.total_price_minor) {
976
+ return "结构化报价总价与明细合计不一致(不可信报价)";
977
+ }
978
+ if (terms.total_price_minor > limits.max_total_price.amount_minor) {
979
+ return `总价 ${terms.total_price_minor} minor 超过 max_total_price ${limits.max_total_price.amount_minor}`;
980
+ }
981
+ }
982
+ if (limits.max_quantity !== undefined) {
983
+ const totalQty = terms.items.reduce((sum, it) => sum + it.quantity_value, 0);
984
+ if (!Number.isFinite(totalQty) || totalQty > limits.max_quantity.value) {
985
+ return `数量总量 ${totalQty} 超过 max_quantity ${limits.max_quantity.value}`;
986
+ }
987
+ }
988
+ return undefined;
989
+ }
990
+ limitViolation(action, opts = {}) {
614
991
  const limits = this.policy.limits;
615
992
  if (limits === undefined)
616
993
  return undefined;
@@ -620,8 +997,141 @@ export class KiwiBuyerService {
620
997
  }
621
998
  if (action === "payment")
622
999
  return "payment 恒为 never";
1000
+ // review P1-2(返修):accept 类动作的约束核验**只信结构化报价事实**
1001
+ // (候选.terms,KNP offer 投影)。reply_text 正则/parseFloat 不是权威
1002
+ // 报价——格式可变、无币种/单位约束;缺事实即 fail-closed 拒绝。
1003
+ if (action === "accept_nonbinding" || action === "counter_offer") {
1004
+ // review P1-2(A316 补充校准):counter_offer 外发与 accept 同一限额
1005
+ // 闸口——还价同样不得越委托约束。
1006
+ const { taskId, candidateId } = opts;
1007
+ if (taskId === undefined || candidateId === undefined) {
1008
+ return "accept 缺少任务/候选上下文,无法核验 limits";
1009
+ }
1010
+ const candidate = this.store
1011
+ .listCandidates(taskId)
1012
+ .find((c) => c.candidate_id === candidateId);
1013
+ if (candidate === undefined)
1014
+ return `候选 ${candidateId} 不存在于任务 ${taskId}`;
1015
+ const merchantId = typeof candidate.merchant_id === "string" ? candidate.merchant_id : undefined;
1016
+ if (limits.allowed_merchants !== undefined &&
1017
+ !limits.allowed_merchants.includes(merchantId ?? "")) {
1018
+ return `merchant ${merchantId ?? "unknown"} 不在 allowed_merchants`;
1019
+ }
1020
+ const needsFacts = limits.max_unit_price !== undefined ||
1021
+ limits.max_total_price !== undefined ||
1022
+ limits.allowed_currencies !== undefined ||
1023
+ limits.max_quantity !== undefined;
1024
+ if (!needsFacts)
1025
+ return undefined;
1026
+ const terms = candidate.terms;
1027
+ if (terms === undefined) {
1028
+ return "候选无结构化报价事实(terms 缺失),无法核验委托约束(fail-closed)";
1029
+ }
1030
+ if (typeof terms.currency !== "string" || terms.currency === "") {
1031
+ return "结构化报价缺币种,无法核验委托约束(fail-closed)";
1032
+ }
1033
+ if (limits.allowed_currencies !== undefined &&
1034
+ !limits.allowed_currencies.includes(terms.currency)) {
1035
+ return `币种 ${terms.currency} 不在 allowed_currencies`;
1036
+ }
1037
+ if (!Array.isArray(terms.items) || terms.items.length === 0) {
1038
+ return "结构化报价无明细行,无法核验委托约束(fail-closed)";
1039
+ }
1040
+ // money 必须安全整数 minor;quantity 为 KNP number>0(允许小数数量)
1041
+ for (const item of terms.items) {
1042
+ if (!Number.isSafeInteger(item.unit_price_minor) ||
1043
+ item.unit_price_minor < 0) {
1044
+ return "明细单价不是安全整数 minor(拒绝非整数货币)";
1045
+ }
1046
+ if (typeof item.quantity_value !== "number" || !Number.isFinite(item.quantity_value) || item.quantity_value <= 0) {
1047
+ return "明细数量必须为正数(KNP number>0)";
1048
+ }
1049
+ }
1050
+ if (!Number.isSafeInteger(terms.total_price_minor) ||
1051
+ terms.total_price_minor < 0) {
1052
+ return "总价不是安全整数 minor(拒绝非整数货币)";
1053
+ }
1054
+ // 单位绑定:声明了 limit 单位时,明细**缺失 unit 也拒**(缺失不能视
1055
+ // 为匹配——否则无单位行绕过声明单位约束);不一致同样拒。
1056
+ if (limits.max_quantity !== undefined &&
1057
+ typeof limits.max_quantity.unit === "string" &&
1058
+ limits.max_quantity.unit !== "") {
1059
+ const bad = terms.items.find((it) => typeof it.quantity_unit !== "string" ||
1060
+ it.quantity_unit === "" ||
1061
+ it.quantity_unit !== limits.max_quantity.unit);
1062
+ if (bad !== undefined) {
1063
+ return `明细数量单位缺失或与 max_quantity.unit(${limits.max_quantity.unit}) 不一致`;
1064
+ }
1065
+ }
1066
+ if (limits.max_unit_price !== undefined) {
1067
+ if (limits.max_unit_price.currency !== terms.currency) {
1068
+ return `max_unit_price 币种(${limits.max_unit_price.currency})与报价币种(${terms.currency})不绑定`;
1069
+ }
1070
+ const over = terms.items.find((it) => it.unit_price_minor > limits.max_unit_price.amount_minor);
1071
+ if (over !== undefined) {
1072
+ return `单价 ${over.unit_price_minor} minor 超过 max_unit_price ${limits.max_unit_price.amount_minor}`;
1073
+ }
1074
+ }
1075
+ if (limits.max_total_price !== undefined) {
1076
+ if (limits.max_total_price.currency !== terms.currency) {
1077
+ return `max_total_price 币种(${limits.max_total_price.currency})与报价币种(${terms.currency})不绑定`;
1078
+ }
1079
+ const computed = terms.items.reduce((sum, it) => sum + it.unit_price_minor * it.quantity_value, 0);
1080
+ if (!Number.isSafeInteger(computed)) {
1081
+ return "总价明细合计不是安全整数 minor(拒绝非整数货币)";
1082
+ }
1083
+ if (computed !== terms.total_price_minor) {
1084
+ return "结构化报价总价与明细合计不一致(不可信报价)";
1085
+ }
1086
+ if (terms.total_price_minor > limits.max_total_price.amount_minor) {
1087
+ return `总价 ${terms.total_price_minor} minor 超过 max_total_price ${limits.max_total_price.amount_minor}`;
1088
+ }
1089
+ }
1090
+ if (limits.max_quantity !== undefined) {
1091
+ // review P1-2(A316 补充校准):max_quantity 按**总量**聚合(多明细
1092
+ // 行合计),不是逐行放行。
1093
+ const totalQty = terms.items.reduce((sum, it) => sum + it.quantity_value, 0);
1094
+ if (!Number.isFinite(totalQty) || totalQty > limits.max_quantity.value) {
1095
+ return `数量总量 ${totalQty} 超过 max_quantity ${limits.max_quantity.value}`;
1096
+ }
1097
+ }
1098
+ }
623
1099
  return undefined;
624
1100
  }
1101
+ /**
1102
+ * review P1-2(A316 校准):消费记录复用既有 authorization_json 私有字段
1103
+ *(不新增列/不迁移)。binding 是结构化 canonical digest(无分隔符歧义)。
1104
+ */
1105
+ approvalConsumed(stored) {
1106
+ if (stored?.authorization_json === undefined)
1107
+ return undefined;
1108
+ try {
1109
+ const parsed = JSON.parse(stored.authorization_json);
1110
+ const consumed = parsed.consumed;
1111
+ if (consumed !== undefined &&
1112
+ typeof consumed === "object" &&
1113
+ consumed !== null &&
1114
+ typeof consumed.ref === "string" &&
1115
+ consumed.ref !== "" &&
1116
+ typeof consumed.binding === "string" &&
1117
+ consumed.binding !== "") {
1118
+ return { ref: consumed.ref, binding: consumed.binding };
1119
+ }
1120
+ }
1121
+ catch {
1122
+ // authorization_json 非 JSON(如宿主写入的其他形状)→ 视为无消费记录
1123
+ }
1124
+ return undefined;
1125
+ }
1126
+ /** 消费绑定:结构化 canonical digest(contentDigest,无分隔符歧义)。 */
1127
+ consumeBinding(parts) {
1128
+ return contentDigest(parts);
1129
+ }
1130
+ /** 北向候选投影:剥离内部结构化报价事实(persistent-task 冻结契约
1131
+ * additionalProperties:false;terms 只在授权层内部使用,不出 wire)。 */
1132
+ northboundCandidates(taskId) {
1133
+ return this.store.listCandidates(taskId).map(({ terms: _terms, ...rest }) => rest);
1134
+ }
625
1135
  firstQuery(intent) {
626
1136
  const items = Array.isArray(intent.items) ? intent.items : [];
627
1137
  const first = items[0] ?? {};
@@ -647,7 +1157,7 @@ export class KiwiBuyerService {
647
1157
  updated_at: task.updated_at,
648
1158
  expires_at: task.expires_at,
649
1159
  resumable: task.resumable,
650
- candidates: this.store.listCandidates(task.task_id),
1160
+ candidates: this.northboundCandidates(task.task_id),
651
1161
  approval: this.store.listApprovalsByTask(task.task_id)[0],
652
1162
  };
653
1163
  }