@harrylabsj/kiwi 0.12.2 → 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 (352) 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/negotiation-observer.d.ts +3 -0
  249. package/dist/merchant/negotiation-observer.js +33 -19
  250. package/dist/merchant/negotiation-observer.js.map +1 -1
  251. package/dist/merchant/operations-report.js +7 -3
  252. package/dist/merchant/operations-report.js.map +1 -1
  253. package/dist/merchant/promotion-store.js +1 -0
  254. package/dist/merchant/promotion-store.js.map +1 -1
  255. package/dist/merchant/stats-store.js +13 -7
  256. package/dist/merchant/stats-store.js.map +1 -1
  257. package/dist/merchant/workbench-service.d.ts +1 -0
  258. package/dist/merchant/workbench-service.js +28 -11
  259. package/dist/merchant/workbench-service.js.map +1 -1
  260. package/dist/merchant-core/commands.d.ts +3 -0
  261. package/dist/merchant-core/commands.js +39 -2
  262. package/dist/merchant-core/commands.js.map +1 -1
  263. package/dist/merchant-core/executor.d.ts +2 -0
  264. package/dist/merchant-core/executor.js +1 -1
  265. package/dist/merchant-core/executor.js.map +1 -1
  266. package/dist/merchant-core/operations.d.ts +2 -2
  267. package/dist/merchant-core/operations.js +11 -9
  268. package/dist/merchant-core/operations.js.map +1 -1
  269. package/dist/merchant-core/product-import.js +1 -1
  270. package/dist/merchant-core/product-import.js.map +1 -1
  271. package/dist/merchant-core/rfq/pending-candidates.d.ts +14 -0
  272. package/dist/merchant-core/rfq/pending-candidates.js +11 -0
  273. package/dist/merchant-core/rfq/pending-candidates.js.map +1 -0
  274. package/dist/merchant-core/rfq/release-coordinator.d.ts +9 -2
  275. package/dist/merchant-core/rfq/release-coordinator.js +32 -14
  276. package/dist/merchant-core/rfq/release-coordinator.js.map +1 -1
  277. package/dist/merchant-core/rfq/repository.d.ts +4 -7
  278. package/dist/merchant-core/rfq/repository.js +10 -24
  279. package/dist/merchant-core/rfq/repository.js.map +1 -1
  280. package/dist/merchant-core/rfq/service.d.ts +5 -2
  281. package/dist/merchant-core/rfq/service.js +4 -3
  282. package/dist/merchant-core/rfq/service.js.map +1 -1
  283. package/dist/merchant-gateway/entry-server.js +25 -1
  284. package/dist/merchant-gateway/entry-server.js.map +1 -1
  285. package/dist/merchant-gateway/pinned-fetch.d.ts +9 -2
  286. package/dist/merchant-gateway/pinned-fetch.js +63 -27
  287. package/dist/merchant-gateway/pinned-fetch.js.map +1 -1
  288. package/dist/merchant-runtime/manager.d.ts +5 -2
  289. package/dist/merchant-runtime/manager.js +40 -11
  290. package/dist/merchant-runtime/manager.js.map +1 -1
  291. package/dist/negotiation/context-map/store.js +4 -13
  292. package/dist/negotiation/context-map/store.js.map +1 -1
  293. package/dist/negotiation/domain/common.js +33 -2
  294. package/dist/negotiation/domain/common.js.map +1 -1
  295. package/dist/negotiation/domain/envelope.d.ts +2 -5
  296. package/dist/negotiation/domain/envelope.js +36 -9
  297. package/dist/negotiation/domain/envelope.js.map +1 -1
  298. package/dist/negotiation/domain/objects.js +14 -0
  299. package/dist/negotiation/domain/objects.js.map +1 -1
  300. package/dist/negotiation/idempotency/store.d.ts +4 -1
  301. package/dist/negotiation/idempotency/store.js +80 -52
  302. package/dist/negotiation/idempotency/store.js.map +1 -1
  303. package/dist/negotiation/idempotency/types.d.ts +7 -1
  304. package/dist/negotiation/idempotency/types.js +1 -1
  305. package/dist/negotiation/idempotency/types.js.map +1 -1
  306. package/dist/negotiation/jcs.js +11 -16
  307. package/dist/negotiation/jcs.js.map +1 -1
  308. package/dist/negotiation/ledger/store.d.ts +15 -9
  309. package/dist/negotiation/ledger/store.js +201 -65
  310. package/dist/negotiation/ledger/store.js.map +1 -1
  311. package/dist/negotiation/recovery/recover.js +30 -30
  312. package/dist/negotiation/recovery/recover.js.map +1 -1
  313. package/dist/negotiation/recovery/types.d.ts +3 -3
  314. package/dist/net/request-budget.d.ts +17 -0
  315. package/dist/net/request-budget.js +63 -0
  316. package/dist/net/request-budget.js.map +1 -0
  317. package/dist/operator/controller.d.ts +1 -1
  318. package/dist/operator/controller.js +23 -12
  319. package/dist/operator/controller.js.map +1 -1
  320. package/dist/operator/runner.d.ts +69 -0
  321. package/dist/operator/runner.js +260 -39
  322. package/dist/operator/runner.js.map +1 -1
  323. package/dist/operator/strategy.d.ts +2 -0
  324. package/dist/operator/strategy.js +11 -0
  325. package/dist/operator/strategy.js.map +1 -1
  326. package/dist/privacy/workbench-retention.js +28 -10
  327. package/dist/privacy/workbench-retention.js.map +1 -1
  328. package/dist/product-init.js +25 -4
  329. package/dist/product-init.js.map +1 -1
  330. package/dist/product-publish.js +3 -102
  331. package/dist/product-publish.js.map +1 -1
  332. package/dist/runtime/foreground.d.ts +1 -1
  333. package/dist/runtime/foreground.js +3 -0
  334. package/dist/runtime/foreground.js.map +1 -1
  335. package/dist/runtime/model.js +4 -0
  336. package/dist/runtime/model.js.map +1 -1
  337. package/dist/supervisor/manage.js +109 -35
  338. package/dist/supervisor/manage.js.map +1 -1
  339. package/dist/trust/identity/jws.js +46 -5
  340. package/dist/trust/identity/jws.js.map +1 -1
  341. package/dist/trust/identity/message-signature.js +15 -2
  342. package/dist/trust/identity/message-signature.js.map +1 -1
  343. package/dist/trust/records/store.d.ts +8 -1
  344. package/dist/trust/records/store.js +68 -6
  345. package/dist/trust/records/store.js.map +1 -1
  346. package/dist/weixin/channel.d.ts +4 -0
  347. package/dist/weixin/channel.js +17 -3
  348. package/dist/weixin/channel.js.map +1 -1
  349. package/dist/weixin/cli-weixin.js +8 -2
  350. package/dist/weixin/cli-weixin.js.map +1 -1
  351. package/package.json +32 -8
  352. package/scripts/check-install-toolchain.mjs +69 -0
@@ -37,7 +37,7 @@ import { groundingReads } from "./context/grounding.js";
37
37
  import { MERCHANT_GROUNDING_RULES, merchantGroundingContext } from "./merchant/merchant-grounding.js";
38
38
  import { SkillRegistry } from "./skills/registry.js";
39
39
  import { buildSkillTools } from "./skills/tools.js";
40
- import { DeterministicNegotiationRunner } from "../operator/runner.js";
40
+ import { DeterministicNegotiationRunner, UnknownFencePersistenceError } from "../operator/runner.js";
41
41
  import { MemoryStore } from "./memory/store.js";
42
42
  import { MemoryError } from "./memory/types.js";
43
43
  import { PrivateVault } from "./memory/vault.js";
@@ -317,6 +317,17 @@ export class AgentKernel {
317
317
  // claim→fail 并饿死队尾 live 消息。连续失败达上限后进入冷却窗口,
318
318
  // 窗口内跳过,窗口后允许一次重试;成功/共识时清除。
319
319
  stalledNegotiations = new Map();
320
+ /**
321
+ * review P1-4 R1(A342):本地 unknown 围栏**持久化失败**(存储故障)后的
322
+ * 同 host 明确停机集合(fail-closed)。kernel 每 tick 新建 runner——
323
+ * runner 的进程内 Map 跨 tick 即失,持久化又失败时没有任何屏障能挡住
324
+ * 「failed claim 重领 → 再次 submit」。本集合挂在 kernel 生命周期上(跨
325
+ * tick 有效):停机消息在 pending 过滤与 prepare skipKeys 中跳过,修复
326
+ * 存储并人工对账前不再自动重驱。边界如实声明:kernel 进程重启且存储仍
327
+ * 不可写时无持久屏障(物理存储全坏/重启不可声称已保证);不造跨网
328
+ * exactly-once,不改协议/远程 API。
329
+ */
330
+ haltedNegotiations = new Set();
320
331
  constructor(options) {
321
332
  this.profile = options.profile;
322
333
  this.paths = options.paths;
@@ -351,6 +362,21 @@ export class AgentKernel {
351
362
  this.turnId = options.turnId;
352
363
  }
353
364
  static async open(options) {
365
+ const clock = () => {
366
+ let value;
367
+ try {
368
+ value = (options.now ?? (() => new Date().toISOString()))();
369
+ }
370
+ catch {
371
+ throw new AgentSessionError("invalid clock configuration: callback failed");
372
+ }
373
+ const timestamp = typeof value === "string" ? Date.parse(value) : Number.NaN;
374
+ if (!Number.isFinite(timestamp))
375
+ throw new AgentSessionError("invalid clock configuration: expected a valid timestamp");
376
+ return new Date(timestamp).toISOString();
377
+ };
378
+ // Reject invalid trusted configuration before files, database handles or timers exist.
379
+ clock();
354
380
  const paths = options.paths ?? ensureAgentPaths(options.profile.agent_id);
355
381
  // 会话来自不同模型(如 fake→deepseek)时重置:旧模型的消息会让新模型首轮
356
382
  // 产生空响应(模型没有返回任何文本)。模型变更 = 新的对话历史。
@@ -370,270 +396,268 @@ export class AgentKernel {
370
396
  }
371
397
  }
372
398
  const db = openAgentDatabase(paths.db);
373
- const vault = options.vault ?? new PrivateVault();
374
- const store = new MemoryStore({ db, vault, ...(options.now ? { now: options.now } : {}) });
375
- const principal = store.ensurePrincipal({
376
- principal_id: options.profile.agent_id,
377
- owner_id: options.profile.owner_id,
378
- role: options.profile.role,
379
- });
380
- store.bindPrincipal(principal.principal_id);
381
- let mainSessionManager;
382
399
  try {
383
- mainSessionManager = openMainSessionManager(paths, paths.dir, options.eventSessionId ?? MAIN_SESSION_ID);
384
- }
385
- catch (err) {
386
- db.close(); // never leak the SQLite handle on a fail-closed open
387
- throw err;
388
- }
389
- // Buyer capability pack (v0.3.0-B): task store + scheduler + tools.
390
- // All clocks are normalized to UTC ISO (SQLite compares timestamps
391
- // lexicographically; mixed offsets would silently break due checks).
392
- const clock = () => new Date(Date.parse((options.now ?? (() => new Date().toISOString()))())).toISOString();
393
- const modeRef = { value: options.mode ?? DEFAULT_AGENT_MODE };
394
- const pendingHooks = new Map();
395
- const turnId = { current: MAIN_SESSION_ID };
396
- const registerPendingHooks = (id, hooks) => {
397
- pendingHooks.set(id, hooks);
398
- };
399
- const hostSequence = { value: 0 };
400
- const hostSink = options.eventSink === undefined ? undefined : new SerializedEventSink(options.eventSink);
401
- const emitEvent = options.eventSink === undefined
402
- ? undefined
403
- : async (type, data) => {
404
- hostSequence.value += 1;
405
- await emitHostEvent(hostSink, {
406
- eventId: `host-${hostSequence.value}`,
407
- sessionId: options.eventSessionId ?? MAIN_SESSION_ID,
408
- sequence: hostSequence.value,
409
- type,
410
- occurredAt: clock(),
411
- data: sanitizeHostEventData(type, data),
412
- });
413
- };
414
- const approvals = new WriteApprovalCandidateStore({
415
- db,
416
- principalId: principal.principal_id,
417
- now: clock,
418
- });
419
- const registerPending = (id, hooks) => {
420
- registerPendingHooks(id, hooks);
421
- const candidate = approvals.get(id);
422
- void emitEvent?.("candidate_update", {
423
- candidate_id: id,
424
- status: candidate?.status ?? "pending_approval",
425
- preview: publicCandidatePreview(candidate),
426
- });
427
- };
428
- // Execution hooks are deliberately process-local. Invalidate durable
429
- // candidates before wiring tools so a restarted kernel never exposes a
430
- // /pending item that its /approve path cannot execute.
431
- approvals.expireForRecovery();
432
- let taskStore;
433
- let scheduler;
434
- let supplierScheduler;
435
- let buyerTools = [];
436
- let merchantTools = [];
437
- let merchantSkillTools = [];
438
- let merchantIntelligence;
439
- const merchantSkillRegistry = options.profile.role === "merchant" &&
440
- options.profile.merchant_experience?.enabled === true &&
441
- options.profile.merchant_experience.skills === true
442
- ? SkillRegistry.fromDir(path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../skills/merchant"), "merchant")
443
- : new SkillRegistry([]);
444
- merchantSkillTools = buildSkillTools(merchantSkillRegistry);
445
- let handoffRuntime;
446
- if (options.profile.role === "buyer" && options.connector !== undefined) {
447
- taskStore = new BuyerTaskStore({
448
- db,
449
- principalId: principal.principal_id,
450
- now: clock,
451
- vault,
452
- });
453
- scheduler = new TaskScheduler({
454
- store: taskStore,
455
- connectors: [options.connector],
456
- now: clock,
457
- // CD #28:配置 catalog 时调度器定时重搜同样 catalog-first。
458
- ...(options.catalog !== undefined
459
- ? { catalogSource: new KiwiCatalogSource({ baseUrl: options.catalog }) }
460
- : {}),
400
+ const vault = options.vault ?? new PrivateVault();
401
+ const store = new MemoryStore({ db, vault, now: clock });
402
+ const principal = store.ensurePrincipal({
403
+ principal_id: options.profile.agent_id,
404
+ owner_id: options.profile.owner_id,
405
+ role: options.profile.role,
461
406
  });
462
- // M1:Buyer-owned supplier pull scheduler(pull-relationship §7.1/§8)。
463
- // 与 TaskScheduler 同一 DB、同一 tick 串行链;catalogSource 不可得时仍可
464
- // 做 Agent Card / UCP Profile 直拉(容错:可选依赖缺省不阻塞构造)。
465
- // trustStore 落 agent data dir(trust/ 子目录,首次观察时创建)。
466
- // 同一 store 也注入 buyer 工具:RFQ 成功后的 supplier_save_suggested
467
- // 本地建议要查已有关系(§13 M0)。
468
- const supplierStore = new SupplierRelationshipStore({
407
+ store.bindPrincipal(principal.principal_id);
408
+ const mainSessionManager = openMainSessionManager(paths, paths.dir, options.eventSessionId ?? MAIN_SESSION_ID);
409
+ // Buyer capability pack (v0.3.0-B): task store + scheduler + tools.
410
+ // All clocks are normalized to UTC ISO (SQLite compares timestamps
411
+ // lexicographically; mixed offsets would silently break due checks).
412
+ const modeRef = { value: options.mode ?? DEFAULT_AGENT_MODE };
413
+ const pendingHooks = new Map();
414
+ const turnId = { current: MAIN_SESSION_ID };
415
+ const registerPendingHooks = (id, hooks) => {
416
+ pendingHooks.set(id, hooks);
417
+ };
418
+ const hostSequence = { value: 0 };
419
+ const hostSink = options.eventSink === undefined ? undefined : new SerializedEventSink(options.eventSink);
420
+ const emitEvent = options.eventSink === undefined
421
+ ? undefined
422
+ : async (type, data) => {
423
+ hostSequence.value += 1;
424
+ await emitHostEvent(hostSink, {
425
+ eventId: `host-${hostSequence.value}`,
426
+ sessionId: options.eventSessionId ?? MAIN_SESSION_ID,
427
+ sequence: hostSequence.value,
428
+ type,
429
+ occurredAt: clock(),
430
+ data: sanitizeHostEventData(type, data),
431
+ });
432
+ };
433
+ const approvals = new WriteApprovalCandidateStore({
469
434
  db,
470
435
  principalId: principal.principal_id,
471
436
  now: clock,
472
437
  });
473
- supplierScheduler = new SupplierScheduler({
474
- store: supplierStore,
475
- now: clock,
476
- ...(options.catalog !== undefined
477
- ? { catalogSource: new KiwiCatalogSource({ baseUrl: options.catalog }) }
478
- : {}),
479
- trustStore: new TrustRecordStore({ dir: path.dirname(paths.db), now: clock }),
480
- ...(options.allowLoopback === true ? { allowLoopback: true } : {}),
481
- });
482
- // v0.7.0 KTH:handoff 存储(Ledger 事件 + 执行幂等)落在 agent data dir,
483
- // 注入 buyer 工具(handoff_agreement 工具挂载)。
484
- const handoffDir = path.dirname(paths.db);
485
- const handoffLedger = new HandoffEventStore({ dir: handoffDir, now: clock });
486
- const handoffIdempotency = new HandoffIdempotencyStore({ dir: handoffDir, now: clock });
487
- handoffRuntime = { ledger: handoffLedger, idempotency: handoffIdempotency };
488
- buyerTools = buildBuyerTools({
489
- store: taskStore,
490
- connector: options.connector,
491
- profile: options.profile,
492
- ...(options.commerceClient !== undefined ? { commerceClient: options.commerceClient } : {}),
493
- ...(options.broker !== undefined ? { broker: options.broker } : {}),
494
- ...(options.catalog !== undefined
495
- ? {
496
- catalog: options.catalog,
497
- // CD #27 wiring:buyer kernel 配置 catalog 时注入 KiwiCatalogSource,
498
- // search_listings / shortlist_listing 工具才挂载(历史教训:工具
499
- // 只在测试里可达,运行时从未注入——dead code)。
500
- catalogSource: new KiwiCatalogSource({ baseUrl: options.catalog }),
501
- }
502
- : {}),
503
- approvals,
504
- mode: () => modeRef.value,
505
- registerPending,
506
- now: clock,
507
- recordNegotiation: (input) => rememberNegotiation(store, input),
508
- handoff: { ledger: handoffLedger, idempotency: handoffIdempotency },
509
- supplierStore,
510
- });
511
- }
512
- else if (options.profile.role === "merchant" &&
513
- options.merchantClient !== undefined &&
514
- options.broker !== undefined) {
515
- if (options.profile.merchant_experience?.enabled === true &&
516
- options.profile.merchant_experience.intelligence !== false) {
517
- merchantIntelligence = new DefaultMerchantIntelligenceBackend({
518
- merchant_id: principal.owner_id,
519
- data_dir: path.dirname(paths.db),
520
- // 口径修复(V2 阶段二遗留核查):presentation enrich 以
521
- // context.principalId 作为商家读取键(merchant_id 口径),backend 的
522
- // principal 校验键必须同口径——用 agent_id 会让 digest/catalog 展示
523
- // 在真实商家 profile(agent_id ≠ owner_id)下必然校验失败/读空。
524
- principal_id: principal.owner_id,
525
- merchant_client: options.merchantClient,
526
- approvals,
527
- ...(options.merchantAnalyticsSource !== undefined
528
- ? { analytics_source: options.merchantAnalyticsSource }
438
+ const registerPending = (id, hooks) => {
439
+ registerPendingHooks(id, hooks);
440
+ const candidate = approvals.get(id);
441
+ void emitEvent?.("candidate_update", {
442
+ candidate_id: id,
443
+ status: candidate?.status ?? "pending_approval",
444
+ preview: publicCandidatePreview(candidate),
445
+ });
446
+ };
447
+ // Execution hooks are deliberately process-local. Invalidate durable
448
+ // candidates before wiring tools so a restarted kernel never exposes a
449
+ // /pending item that its /approve path cannot execute.
450
+ approvals.expireForRecovery();
451
+ let taskStore;
452
+ let scheduler;
453
+ let supplierScheduler;
454
+ let buyerTools = [];
455
+ let merchantTools = [];
456
+ let merchantSkillTools = [];
457
+ let merchantIntelligence;
458
+ const merchantSkillRegistry = options.profile.role === "merchant" &&
459
+ options.profile.merchant_experience?.enabled === true &&
460
+ options.profile.merchant_experience.skills === true
461
+ ? SkillRegistry.fromDir(path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../skills/merchant"), "merchant")
462
+ : new SkillRegistry([]);
463
+ merchantSkillTools = buildSkillTools(merchantSkillRegistry);
464
+ let handoffRuntime;
465
+ if (options.profile.role === "buyer" && options.connector !== undefined) {
466
+ taskStore = new BuyerTaskStore({
467
+ db,
468
+ principalId: principal.principal_id,
469
+ now: clock,
470
+ vault,
471
+ });
472
+ scheduler = new TaskScheduler({
473
+ store: taskStore,
474
+ connectors: [options.connector],
475
+ now: clock,
476
+ // CD #28:配置 catalog 时调度器定时重搜同样 catalog-first。
477
+ ...(options.catalog !== undefined
478
+ ? { catalogSource: new KiwiCatalogSource({ baseUrl: options.catalog }) }
529
479
  : {}),
480
+ });
481
+ // M1:Buyer-owned supplier pull scheduler(pull-relationship §7.1/§8)。
482
+ // 与 TaskScheduler 同一 DB、同一 tick 串行链;catalogSource 不可得时仍可
483
+ // 做 Agent Card / UCP Profile 直拉(容错:可选依赖缺省不阻塞构造)。
484
+ // trustStore 落 agent data dir(trust/ 子目录,首次观察时创建)。
485
+ // 同一 store 也注入 buyer 工具:RFQ 成功后的 supplier_save_suggested
486
+ // 本地建议要查已有关系(§13 M0)。
487
+ const supplierStore = new SupplierRelationshipStore({
488
+ db,
489
+ principalId: principal.principal_id,
530
490
  now: clock,
531
491
  });
492
+ supplierScheduler = new SupplierScheduler({
493
+ store: supplierStore,
494
+ now: clock,
495
+ ...(options.catalog !== undefined
496
+ ? { catalogSource: new KiwiCatalogSource({ baseUrl: options.catalog }) }
497
+ : {}),
498
+ trustStore: new TrustRecordStore({ dir: path.dirname(paths.db), now: clock }),
499
+ ...(options.allowLoopback === true ? { allowLoopback: true } : {}),
500
+ });
501
+ // v0.7.0 KTH:handoff 存储(Ledger 事件 + 执行幂等)落在 agent data dir,
502
+ // 注入 buyer 工具(handoff_agreement 工具挂载)。
503
+ const handoffDir = path.dirname(paths.db);
504
+ const handoffLedger = new HandoffEventStore({ dir: handoffDir, now: clock });
505
+ const handoffIdempotency = new HandoffIdempotencyStore({ dir: handoffDir, now: clock });
506
+ handoffRuntime = { ledger: handoffLedger, idempotency: handoffIdempotency };
507
+ buyerTools = buildBuyerTools({
508
+ store: taskStore,
509
+ connector: options.connector,
510
+ profile: options.profile,
511
+ ...(options.commerceClient !== undefined ? { commerceClient: options.commerceClient } : {}),
512
+ ...(options.broker !== undefined ? { broker: options.broker } : {}),
513
+ ...(options.catalog !== undefined
514
+ ? {
515
+ catalog: options.catalog,
516
+ // CD #27 wiring:buyer kernel 配置 catalog 时注入 KiwiCatalogSource,
517
+ // search_listings / shortlist_listing 工具才挂载(历史教训:工具
518
+ // 只在测试里可达,运行时从未注入——dead code)。
519
+ catalogSource: new KiwiCatalogSource({ baseUrl: options.catalog }),
520
+ }
521
+ : {}),
522
+ approvals,
523
+ mode: () => modeRef.value,
524
+ registerPending,
525
+ now: clock,
526
+ recordNegotiation: (input) => rememberNegotiation(store, input),
527
+ handoff: { ledger: handoffLedger, idempotency: handoffIdempotency },
528
+ supplierStore,
529
+ });
532
530
  }
533
- merchantTools = buildMerchantTools({
531
+ else if (options.profile.role === "merchant" &&
532
+ options.merchantClient !== undefined &&
533
+ options.broker !== undefined) {
534
+ if (options.profile.merchant_experience?.enabled === true &&
535
+ options.profile.merchant_experience.intelligence !== false) {
536
+ merchantIntelligence = new DefaultMerchantIntelligenceBackend({
537
+ merchant_id: principal.owner_id,
538
+ data_dir: path.dirname(paths.db),
539
+ // 口径修复(V2 阶段二遗留核查):presentation enrich 以
540
+ // context.principalId 作为商家读取键(merchant_id 口径),backend 的
541
+ // principal 校验键必须同口径——用 agent_id 会让 digest/catalog 展示
542
+ // 在真实商家 profile(agent_id ≠ owner_id)下必然校验失败/读空。
543
+ principal_id: principal.owner_id,
544
+ merchant_client: options.merchantClient,
545
+ approvals,
546
+ ...(options.merchantAnalyticsSource !== undefined
547
+ ? { analytics_source: options.merchantAnalyticsSource }
548
+ : {}),
549
+ now: clock,
550
+ });
551
+ }
552
+ merchantTools = buildMerchantTools({
553
+ profile: options.profile,
554
+ merchantClient: options.merchantClient,
555
+ // Negotiation token (commerceClient) is optional: absent → 磋商工具
556
+ // fail closed,目录/库存只读与审批式写工具照常可用(见 §15.3/§15.4)。
557
+ ...(options.commerceClient !== undefined ? { commerceClient: options.commerceClient } : {}),
558
+ broker: options.broker,
559
+ principalId: principal.principal_id,
560
+ approvals,
561
+ mode: () => modeRef.value,
562
+ registerPending,
563
+ now: clock,
564
+ privateValues: () => listRestrictedValues(store),
565
+ ...(merchantIntelligence !== undefined ? { intelligence: merchantIntelligence } : {}),
566
+ ...(emitEvent !== undefined ? { emitEvent } : {}),
567
+ // 商家 A2A 节点 ledger 基础目录(<dataDir>/a2a)——LedgerStore 会再拼
568
+ // /ledger 到 <dataDir>/a2a/ledger,list_a2a_negotiations 用。
569
+ a2aLedgerDir: path.join(path.dirname(paths.db), "a2a"),
570
+ });
571
+ }
572
+ const base = baseSystemPrompt(options.profile, principal, merchantSkillRegistry.names.length > 0 ? merchantSkillRegistry : undefined);
573
+ let briefing;
574
+ // §18.1 对位:0.87 的请求超时走 settings(providerRetry.timeoutMs /
575
+ // httpIdleTimeoutMs),kernel 侧另有 Promise.race 兜底。inMemory 设置避免
576
+ // 读写用户 ~/.pi/agent 的全局配置。
577
+ const settingsManager = SettingsManager.inMemory({
578
+ retry: {
579
+ provider: {
580
+ timeoutMs: options.profile.runtime.turn_timeout_seconds * 1000,
581
+ },
582
+ },
583
+ httpIdleTimeoutMs: options.profile.runtime.turn_timeout_seconds * 1000,
584
+ });
585
+ const modelRuntime = withPromptCacheRetention(options.modelRuntime ?? (await buildModelRuntime(options)), options.profile.merchant_experience?.prompt_cache_retention);
586
+ const kiwiTools = [
587
+ ...buildMemoryTools(store, { turnId: () => turnId.current }),
588
+ ...buyerTools,
589
+ ...merchantTools,
590
+ ...merchantSkillTools,
591
+ ];
592
+ const customTools = kiwiTools.map((tool) => ({
593
+ name: tool.name,
594
+ label: tool.label,
595
+ description: tool.description,
596
+ parameters: tool.parameters,
597
+ // 0.87 harness declares six execute parameters (toolContext/invocation/
598
+ // context trailing); every kiwi tool implements only (id, params), so
599
+ // the adapter forwards exactly those two.
600
+ execute: async (toolCallId, params) => tool.execute(toolCallId, params),
601
+ }));
602
+ const { session: agentSession } = await createAgentSession({
603
+ cwd: paths.dir,
604
+ model: options.model,
605
+ modelRuntime: modelRuntime,
606
+ settingsManager,
607
+ sessionManager: mainSessionManager.manager,
608
+ customTools,
609
+ noTools: "builtin",
610
+ resourceLoader: {
611
+ getExtensions: () => ({ extensions: [], errors: [], runtime: createExtensionRuntime() }),
612
+ getSkills: () => ({ skills: [], diagnostics: [] }),
613
+ getPrompts: () => ({ prompts: [], diagnostics: [] }),
614
+ getThemes: () => ({ themes: [], diagnostics: [] }),
615
+ getAgentsFiles: () => ({ agentsFiles: [] }),
616
+ // 每次 rebuild 都会读取:briefing setter 改字段后由下一 turn 生效。
617
+ getSystemPrompt: () => (briefing === undefined ? base : `${base}\n\n${briefing}`),
618
+ getSystemPromptSource: () => undefined,
619
+ getAppendSystemPrompt: () => [],
620
+ getAppendSystemPromptSources: () => [],
621
+ extendResources: () => { },
622
+ reload: async () => { },
623
+ },
624
+ ...(options.thinkingLevel !== undefined ? { thinkingLevel: options.thinkingLevel } : {}),
625
+ });
626
+ const unsubscribeSessionEvents = emitEvent === undefined
627
+ ? undefined
628
+ : attachSessionHostEvents(agentSession, emitEvent);
629
+ const kernel = new AgentKernel({
534
630
  profile: options.profile,
535
- merchantClient: options.merchantClient,
536
- // Negotiation token (commerceClient) is optional: absent → 磋商工具
537
- // fail closed,目录/库存只读与审批式写工具照常可用(见 §15.3/§15.4)。
538
- ...(options.commerceClient !== undefined ? { commerceClient: options.commerceClient } : {}),
539
- broker: options.broker,
540
- principalId: principal.principal_id,
631
+ paths,
632
+ db,
633
+ store,
634
+ principal,
635
+ session: agentSession,
541
636
  approvals,
542
- mode: () => modeRef.value,
543
- registerPending,
637
+ ...(handoffRuntime !== undefined ? { handoffRuntime } : {}),
638
+ modeRef,
639
+ pendingHooks,
640
+ turnId,
544
641
  now: clock,
545
- privateValues: () => listRestrictedValues(store),
546
- ...(merchantIntelligence !== undefined ? { intelligence: merchantIntelligence } : {}),
547
- ...(emitEvent !== undefined ? { emitEvent } : {}),
548
- // 商家 A2A 节点 ledger 基础目录(<dataDir>/a2a)——LedgerStore 会再拼
549
- // /ledger 到 <dataDir>/a2a/ledger,list_a2a_negotiations 用。
550
- a2aLedgerDir: path.join(path.dirname(paths.db), "a2a"),
642
+ ...(taskStore !== undefined ? { taskStore } : {}),
643
+ ...(scheduler !== undefined ? { scheduler } : {}),
644
+ ...(supplierScheduler !== undefined ? { supplierScheduler } : {}),
645
+ ...(options.commerceClient !== undefined ? { commerceClient: options.commerceClient } : {}),
646
+ ...(options.merchantClient !== undefined ? { merchantClient: options.merchantClient } : {}),
647
+ ...(options.broker !== undefined ? { broker: options.broker } : {}),
648
+ ...(merchantIntelligence !== undefined ? { merchantIntelligence } : {}),
649
+ emitEvent,
650
+ ...(unsubscribeSessionEvents !== undefined ? { unsubscribeSessionEvents } : {}),
551
651
  });
652
+ kernel.briefingSetter = (value) => {
653
+ briefing = value;
654
+ };
655
+ return kernel;
656
+ }
657
+ catch (error) {
658
+ db.close();
659
+ throw error;
552
660
  }
553
- const base = baseSystemPrompt(options.profile, principal, merchantSkillRegistry.names.length > 0 ? merchantSkillRegistry : undefined);
554
- let briefing;
555
- // §18.1 对位:0.87 的请求超时走 settings(providerRetry.timeoutMs /
556
- // httpIdleTimeoutMs),kernel 侧另有 Promise.race 兜底。inMemory 设置避免
557
- // 读写用户 ~/.pi/agent 的全局配置。
558
- const settingsManager = SettingsManager.inMemory({
559
- retry: {
560
- provider: {
561
- timeoutMs: options.profile.runtime.turn_timeout_seconds * 1000,
562
- },
563
- },
564
- httpIdleTimeoutMs: options.profile.runtime.turn_timeout_seconds * 1000,
565
- });
566
- const modelRuntime = withPromptCacheRetention(options.modelRuntime ?? (await buildModelRuntime(options)), options.profile.merchant_experience?.prompt_cache_retention);
567
- const kiwiTools = [
568
- ...buildMemoryTools(store, { turnId: () => turnId.current }),
569
- ...buyerTools,
570
- ...merchantTools,
571
- ...merchantSkillTools,
572
- ];
573
- const customTools = kiwiTools.map((tool) => ({
574
- name: tool.name,
575
- label: tool.label,
576
- description: tool.description,
577
- parameters: tool.parameters,
578
- // 0.87 harness declares six execute parameters (toolContext/invocation/
579
- // context trailing); every kiwi tool implements only (id, params), so
580
- // the adapter forwards exactly those two.
581
- execute: async (toolCallId, params) => tool.execute(toolCallId, params),
582
- }));
583
- const { session: agentSession } = await createAgentSession({
584
- cwd: paths.dir,
585
- model: options.model,
586
- modelRuntime: modelRuntime,
587
- settingsManager,
588
- sessionManager: mainSessionManager.manager,
589
- customTools,
590
- noTools: "builtin",
591
- resourceLoader: {
592
- getExtensions: () => ({ extensions: [], errors: [], runtime: createExtensionRuntime() }),
593
- getSkills: () => ({ skills: [], diagnostics: [] }),
594
- getPrompts: () => ({ prompts: [], diagnostics: [] }),
595
- getThemes: () => ({ themes: [], diagnostics: [] }),
596
- getAgentsFiles: () => ({ agentsFiles: [] }),
597
- // 每次 rebuild 都会读取:briefing setter 改字段后由下一 turn 生效。
598
- getSystemPrompt: () => (briefing === undefined ? base : `${base}\n\n${briefing}`),
599
- getSystemPromptSource: () => undefined,
600
- getAppendSystemPrompt: () => [],
601
- getAppendSystemPromptSources: () => [],
602
- extendResources: () => { },
603
- reload: async () => { },
604
- },
605
- ...(options.thinkingLevel !== undefined ? { thinkingLevel: options.thinkingLevel } : {}),
606
- });
607
- const unsubscribeSessionEvents = emitEvent === undefined
608
- ? undefined
609
- : attachSessionHostEvents(agentSession, emitEvent);
610
- const kernel = new AgentKernel({
611
- profile: options.profile,
612
- paths,
613
- db,
614
- store,
615
- principal,
616
- session: agentSession,
617
- approvals,
618
- ...(handoffRuntime !== undefined ? { handoffRuntime } : {}),
619
- modeRef,
620
- pendingHooks,
621
- turnId,
622
- now: clock,
623
- ...(taskStore !== undefined ? { taskStore } : {}),
624
- ...(scheduler !== undefined ? { scheduler } : {}),
625
- ...(supplierScheduler !== undefined ? { supplierScheduler } : {}),
626
- ...(options.commerceClient !== undefined ? { commerceClient: options.commerceClient } : {}),
627
- ...(options.merchantClient !== undefined ? { merchantClient: options.merchantClient } : {}),
628
- ...(options.broker !== undefined ? { broker: options.broker } : {}),
629
- ...(merchantIntelligence !== undefined ? { merchantIntelligence } : {}),
630
- emitEvent,
631
- ...(unsubscribeSessionEvents !== undefined ? { unsubscribeSessionEvents } : {}),
632
- });
633
- kernel.briefingSetter = (value) => {
634
- briefing = value;
635
- };
636
- return kernel;
637
661
  }
638
662
  briefingSetter = () => undefined;
639
663
  /**
@@ -647,14 +671,34 @@ export class AgentKernel {
647
671
  const handoffs = [];
648
672
  for (const negotiationId of this.handoffRuntime.ledger.listNegotiations()) {
649
673
  const events = this.handoffRuntime.ledger.events(negotiationId).map((event) => this.handoffRuntime.ledger.resolvePayload(event));
674
+ // Local groups preserve event order and first-appearance output order.
675
+ // No cache survives this negotiation or this getter invocation.
676
+ const candidateGroups = new Map();
677
+ const handoffGroups = new Map();
678
+ for (const event of events) {
679
+ if (event.handoff_candidate_id !== undefined) {
680
+ const group = candidateGroups.get(event.handoff_candidate_id);
681
+ if (group === undefined)
682
+ candidateGroups.set(event.handoff_candidate_id, [event]);
683
+ else
684
+ group.push(event);
685
+ }
686
+ if (event.handoff_id !== undefined) {
687
+ const group = handoffGroups.get(event.handoff_id);
688
+ if (group === undefined)
689
+ handoffGroups.set(event.handoff_id, [event]);
690
+ else
691
+ group.push(event);
692
+ }
693
+ }
650
694
  const seenCandidates = new Set();
651
695
  const seenHandoffs = new Set();
652
696
  for (const event of events) {
653
697
  if (event.handoff_candidate_id !== undefined &&
654
698
  !seenCandidates.has(event.handoff_candidate_id)) {
655
699
  seenCandidates.add(event.handoff_candidate_id);
656
- const lifecycle = foldCandidateLifecycle(events.filter((e) => e.handoff_candidate_id === event.handoff_candidate_id));
657
- const candidateEvents = events.filter((e) => e.handoff_candidate_id === event.handoff_candidate_id);
700
+ const candidateEvents = candidateGroups.get(event.handoff_candidate_id);
701
+ const lifecycle = foldCandidateLifecycle(candidateEvents);
658
702
  const created = candidateEvents.find((e) => e.event_kind === "handoff_candidate_created");
659
703
  const embedded = created?.outcome.kind === "ok"
660
704
  ? created.outcome.result?.candidate
@@ -678,7 +722,7 @@ export class AgentKernel {
678
722
  seenHandoffs.add(event.handoff_id);
679
723
  handoffs.push({
680
724
  handoff_id: event.handoff_id,
681
- delivery: deliveryState(events.filter((e) => e.handoff_id === event.handoff_id)) ?? "?",
725
+ delivery: deliveryState(handoffGroups.get(event.handoff_id)) ?? "?",
682
726
  });
683
727
  }
684
728
  }
@@ -973,6 +1017,9 @@ export class AgentKernel {
973
1017
  const settledKey = (message) => `${message.conversation_id}:${message.message_id}`;
974
1018
  // 审查 P2-I:冷却窗口内的消息跳过(连续失败达上限后暂停自动处理)。
975
1019
  const stalled = this.stalledNegotiations;
1020
+ // review P1-4 R1(A342):本地围栏持久化失败后的同 host 停机集合
1021
+ //(fail-closed)——见下 submit 错误分支与字段声明处注释。
1022
+ const halted = this.haltedNegotiations;
976
1023
  const isStalled = (message) => {
977
1024
  const entry = stalled.get(settledKey(message));
978
1025
  // 达到连续失败上限才进入冷却(上限前的失败继续重试计数)
@@ -984,7 +1031,7 @@ export class AgentKernel {
984
1031
  return false;
985
1032
  return nowMs - sinceMs < AUTOPILOT_STALL_COOLDOWN_MS;
986
1033
  };
987
- if (pending.every((m) => this.settledNegotiations.has(settledKey(m)) || isStalled(m))) {
1034
+ if (pending.every((m) => this.settledNegotiations.has(settledKey(m)) || isStalled(m) || halted.has(settledKey(m)))) {
988
1035
  return undefined;
989
1036
  }
990
1037
  // Never let an abandoned/settled message at the head of the pending list
@@ -1008,24 +1055,32 @@ export class AgentKernel {
1008
1055
  .map(([key]) => key));
1009
1056
  // Buyer: negotiate toward the linked task's goal (quantity / target unit
1010
1057
  // price / budget) instead of the profile defaults.
1011
- let hints;
1012
- const firstPending = pending.find((m) => !settledKeys.has(settledKey(m)) && !stalledKeys.has(settledKey(m)));
1013
- if (firstPending !== undefined &&
1014
- this.profile.role === "buyer" &&
1015
- this.taskStore !== undefined) {
1016
- const link = this.taskStore.linkByConversation(firstPending.conversation_id);
1017
- if (link !== undefined) {
1018
- const task = this.taskStore.getTask(link.task_id);
1019
- if (task !== undefined)
1020
- hints = taskNegotiationHints(this.taskStore, task);
1021
- }
1022
- }
1023
- const runner = new DeterministicNegotiationRunner(this.profile, this.commerceClient);
1058
+ // review P1-4(A336 返修):hints 由 prepare **实际选中的目标**经
1059
+ // hintsFor 回调现产——kernel 第一次 list 与 prepare 第二次 list 之间
1060
+ // pending 可重排/变更,静态预取 hints 会把 B 的会话/任务 hints 串用到
1061
+ // C(A334 实证缺口)。回调绑定实际 (conversation, message, task)。
1062
+ // review P1-4(A327 补充):持久 unknown 围栏挂在 agent 数据目录——
1063
+ // submit 网络异常(结果未知)的消息在本进程与重启后均被 prepare 跳过,
1064
+ // 授权对账(clearUnknown)为唯一解除路径。
1065
+ const runner = new DeterministicNegotiationRunner(this.profile, this.commerceClient, {
1066
+ unknownFenceDir: path.join(this.paths.dir, "submit-unknown"),
1067
+ });
1068
+ const hintsFor = (target) => {
1069
+ if (this.profile.role !== "buyer" || this.taskStore === undefined)
1070
+ return undefined;
1071
+ const link = this.taskStore.linkByConversation(target.conversation_id);
1072
+ if (link === undefined)
1073
+ return undefined;
1074
+ const task = this.taskStore.getTask(link.task_id);
1075
+ return task === undefined ? undefined : taskNegotiationHints(this.taskStore, task);
1076
+ };
1024
1077
  const prepared = await runner
1025
1078
  .prepare({
1026
- ...(hints !== undefined ? { hints } : {}),
1027
- ...(settledKeys.size > 0 || stalledKeys.size > 0
1028
- ? { skipKeys: new Set([...settledKeys, ...stalledKeys]) }
1079
+ hintsFor,
1080
+ // review P1-4 R1(A342):停机集合同样进 skipKeys——下一 tick 新
1081
+ // runner 空 Map 时 prepare 不再重领已停机消息(重驱缝收口)。
1082
+ ...(settledKeys.size > 0 || stalledKeys.size > 0 || halted.size > 0
1083
+ ? { skipKeys: new Set([...settledKeys, ...stalledKeys, ...halted]) }
1029
1084
  : {}),
1030
1085
  })
1031
1086
  .catch(() => undefined);
@@ -1046,9 +1101,26 @@ export class AgentKernel {
1046
1101
  await runner.abandon(prepared, "negotiation already settled").catch(() => undefined);
1047
1102
  return undefined;
1048
1103
  }
1049
- const outcome = await runner.submit(prepared).catch(() => undefined);
1050
- if (outcome === undefined)
1051
- return "磋商处理失败(网关异常),下一轮自动重试。";
1104
+ const submitted = await runner
1105
+ .submit(prepared)
1106
+ .catch((err) => err);
1107
+ // review P1-4 R1(A342 返修):本地围栏持久化失败(存储故障)必须与普通
1108
+ // 网关 unknown 分层——吞成同一文案时,下一 tick 新 runner 空 Map + 旧
1109
+ // 文件无此条目 + failClaim 后 failed 可重领 = 再次 submit(A341 实证)。
1110
+ // 登记同 host 明确停机状态(fail-closed,跨 tick 有效;kernel 重启且
1111
+ // 存储仍不可写的物理边界如实声明,不声称全网恰一次),不再自动重驱。
1112
+ if (submitted instanceof UnknownFencePersistenceError) {
1113
+ this.haltedNegotiations.add(settledKey(prepared.binding));
1114
+ return (`磋商提交结果未知且本地围栏持久化失败(存储故障):已 fail-closed 停止 ` +
1115
+ `${convId} 的自动处理——修复存储并人工对账前不再重驱,不产生重复操作。`);
1116
+ }
1117
+ // review P1-4(返修):submit 抛错 = 结果未知(效果可能已发生)——claim
1118
+ // 不释放,等待网关 stale TTL 重新置 pending 后按原 idempotency key 对账;
1119
+ // 文案不再承诺「下一轮自动重试」(消息在 TTL 前不会重新出现在待处理列表)。
1120
+ if (submitted instanceof Error) {
1121
+ return "磋商提交结果未知(网关异常):已保留处理中的声明,待其恢复后按原键对账,不重复生成操作。";
1122
+ }
1123
+ const outcome = submitted;
1052
1124
  const bindingKey = settledKey(prepared.binding);
1053
1125
  // 审查 P2-I:权威门确定性拒绝(settlement failed)→ 连续失败计数;
1054
1126
  // 达上限进入冷却窗口(窗口内跳过、窗口后重试一次),并清空"已结算"