@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
@@ -0,0 +1,1280 @@
1
+ /**
2
+ * Copyright 2026 harrylabsj
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /** A210 local-only owner host. Official SDK loop + explicit trusted business
17
+ * capabilities; absent provider/facts/budget/verifier configuration fails closed.
18
+ * Dual switch CLI default off; no public owner endpoint or default business approval.
19
+ */
20
+ import { createHash } from "node:crypto";
21
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, realpathSync, statSync, writeFileSync, chmodSync, } from "node:fs";
22
+ import { join, resolve, sep } from "node:path";
23
+ import { contentDigest } from "../../negotiation/jcs.js";
24
+ import { assertOwnerStorageAdmission, assertOwnerStorageReady, guardOwnerStorage, requireOwnerProvider, } from "./owner-storage-admission.js";
25
+ import { createOwnerRequestGate, guardOwnerModels } from "./owner-provider-guard.js";
26
+ import { createFileGrantResolver } from "./owner-file-grant.js";
27
+ import { executeApprovedCandidate, WriteApprovalCandidateStore, } from "../../agent/merchant/action-candidate.js";
28
+ import { OwnerBusinessHost } from "./owner-business-host.js";
29
+ export function readOwnerSessionSwitches(env) {
30
+ const on = (v) => v === "true" || v === "1";
31
+ return {
32
+ ownerEnabled: on(env.KIWI_OWNER_SESSION_ENABLED),
33
+ aiRuntimeEnabled: on(env.KIWI_AI_RUNTIME_ENABLED),
34
+ };
35
+ }
36
+ export function ownerSessionFullyEnabled(s) {
37
+ return s.ownerEnabled && s.aiRuntimeEnabled;
38
+ }
39
+ // ── 身份/目录派生(opaque 精确比较 + sha256 独立派生)────────────────────────
40
+ export function assertOpaqueMerchantId(merchantId) {
41
+ if (typeof merchantId !== "string" || merchantId.length === 0 || merchantId.length > 256) {
42
+ throw new OwnerSessionError("invalid_merchant_id", "merchantId 必须是非空字符串(≤256)");
43
+ }
44
+ return merchantId;
45
+ }
46
+ export function merchantDirName(merchantId) {
47
+ return createHash("sha256").update(merchantId, "utf8").digest("hex");
48
+ }
49
+ export function merchantStorageDir(storageRoot, merchantId) {
50
+ assertOpaqueMerchantId(merchantId);
51
+ const base = resolve(storageRoot, "merchants");
52
+ const dir = resolve(base, merchantDirName(merchantId));
53
+ if (!dir.startsWith(base + sep))
54
+ throw new OwnerSessionError("storage_path_escape", "存储路径越界");
55
+ return dir;
56
+ }
57
+ function ensurePrivateDir(dir) {
58
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
59
+ chmodSync(dir, 0o700);
60
+ if ((statSync(dir).mode & 0o777) !== 0o700) {
61
+ throw new OwnerSessionError("data_dir_permission", `目录权限必须 0700:${dir}`);
62
+ }
63
+ }
64
+ function writePrivateJson(file, value) {
65
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
66
+ const fd = openSync(tmp, "w", 0o600);
67
+ try {
68
+ writeFileSync(fd, JSON.stringify(value, null, 2), "utf8");
69
+ }
70
+ finally {
71
+ closeSync(fd);
72
+ }
73
+ renameSync(tmp, file); // 原子 rename 只防半写
74
+ chmodSync(file, 0o600);
75
+ }
76
+ function readPrivateJson(file) {
77
+ if (!existsSync(file))
78
+ return undefined;
79
+ try {
80
+ return JSON.parse(readFileSync(file, "utf8"));
81
+ }
82
+ catch {
83
+ return undefined; // 坏文件按缺失处理(unknown 语义,不猜)
84
+ }
85
+ }
86
+ export function checkFileGrant(grantFile, merchantId, principal) {
87
+ assertOpaqueMerchantId(merchantId);
88
+ let result;
89
+ try {
90
+ result = createFileGrantResolver({ merchantId, principal }).readStrong(grantFile);
91
+ }
92
+ catch {
93
+ return { ok: false, code: "grant_unknown" };
94
+ }
95
+ if (!result.ok)
96
+ return {
97
+ ok: false,
98
+ code: result.code === "grant_principal_mismatch" ? "grant_merchant_mismatch" : result.code,
99
+ };
100
+ return {
101
+ ok: true,
102
+ grant: {
103
+ merchantId: result.grant.merchantId,
104
+ principal: result.grant.principal,
105
+ ...(result.grant.grantedAt === null ? {} : { granted_at: result.grant.grantedAt }),
106
+ },
107
+ };
108
+ }
109
+ export class OwnerSessionError extends Error {
110
+ code;
111
+ constructor(code, message) {
112
+ super(message);
113
+ this.code = code;
114
+ }
115
+ }
116
+ /**
117
+ * 业务 key:kind + argsHash(参数内容绑定,非调用次数)。
118
+ * A202-R3:argsHash 复用冻结的 contentDigest(JCS canonical,嵌套全层级
119
+ * 可见)——不再自造 JSON replacer(旧实现根层键白名单致嵌套同名键变化不可见)。
120
+ */
121
+ export function businessKey(kind, args) {
122
+ return `${kind}:${contentDigest(args).slice(7, 39)}`; // sha256: 后取 32 hex
123
+ }
124
+ function isProcessAlive(pid) {
125
+ try {
126
+ process.kill(pid, 0); // 信号 0 = 存活探测
127
+ return true;
128
+ }
129
+ catch (err) {
130
+ const code = err.code;
131
+ return code === "EPERM"; // EPERM=存在但无权
132
+ }
133
+ }
134
+ function acquireAdmissionLock(dir, merchantId) {
135
+ const lockPath = join(dir, "admission.lock");
136
+ const ownershipToken = createHash("sha256")
137
+ .update(`${merchantId}:${process.pid}:${Date.now()}:${Math.random()}`)
138
+ .digest("hex");
139
+ const write = () => {
140
+ const fd = openSync(lockPath, "wx", 0o600); // O_EXCL 原子
141
+ try {
142
+ writeFileSync(fd, JSON.stringify({
143
+ pid: process.pid,
144
+ started_at: new Date().toISOString(),
145
+ merchant_id: merchantId,
146
+ module: "a199-local-owner-session",
147
+ ownership_token: ownershipToken,
148
+ }, null, 2));
149
+ }
150
+ finally {
151
+ closeSync(fd);
152
+ }
153
+ chmodSync(lockPath, 0o600);
154
+ };
155
+ try {
156
+ write();
157
+ }
158
+ catch (err) {
159
+ if (err.code !== "EEXIST") {
160
+ throw new OwnerSessionError("admission_lock_failed", `准入锁创建失败:${String(err)}`);
161
+ }
162
+ const existing = readPrivateJson(lockPath);
163
+ if (existing === undefined ||
164
+ !Number.isSafeInteger(existing.pid) ||
165
+ existing.pid < 1 ||
166
+ typeof existing.ownership_token !== "string")
167
+ throw new OwnerSessionError("admission_unknown", "unreadable admission lock");
168
+ if (isProcessAlive(existing.pid)) {
169
+ // 同进程重复 open / 另一进程并存:都是单 writer 违规(A178 返修 C2)。
170
+ const who = existing.pid === process.pid ? "本进程已有实例" : `另一 writer(pid ${existing.pid})`;
171
+ throw new OwnerSessionError("admission_writer_active", `${who}已持有该数据目录准入锁——单 writer 语义拒绝`);
172
+ }
173
+ // A202-R2:崩溃残留接管前 fail-closed 再核——O_EXCL 若被并发接管方先建
174
+ //(EEXIST)则视为新的活跃锁拒绝(不覆盖、不猜测)。
175
+ try {
176
+ rmSync(lockPath, { force: true });
177
+ }
178
+ catch {
179
+ /* ignore */
180
+ }
181
+ try {
182
+ write();
183
+ }
184
+ catch (err2) {
185
+ if (err2.code === "EEXIST") {
186
+ throw new OwnerSessionError("admission_writer_active", "接管竞态:准入锁已被并发方重建——单 writer 语义拒绝");
187
+ }
188
+ throw new OwnerSessionError("admission_lock_failed", `准入锁接管失败:${String(err2)}`);
189
+ }
190
+ }
191
+ return ownershipToken;
192
+ }
193
+ /** A202-R2:release 仅当锁内 ownership_token == 自身 token 才删(幂等;旧实例不能删新锁)。 */
194
+ function releaseAdmissionLock(dir, ownershipToken) {
195
+ const lockPath = join(dir, "admission.lock");
196
+ const existing = readPrivateJson(lockPath);
197
+ if (existing === undefined)
198
+ return; // 幂等:锁已不在
199
+ if (existing.ownership_token !== ownershipToken)
200
+ return; // 新持有者的锁——不得删
201
+ rmSync(lockPath, { force: true });
202
+ }
203
+ /** Local diagnostic, not a business retry signal. Only retryAccounting may consume it. */
204
+ export class OwnerAccountingFailure extends OwnerSessionError {
205
+ operationId;
206
+ leaseId;
207
+ usedTokens;
208
+ budgetError;
209
+ businessError;
210
+ journalErrors;
211
+ budgetSettled;
212
+ businessOutcome;
213
+ cause;
214
+ constructor(operationId, leaseId, usedTokens, businessOutcome, budgetError, businessError, journalErrors, budgetSettled) {
215
+ super("owner_accounting_failed", "owner accounting incomplete; retry accounting only, never redrive business");
216
+ this.operationId = operationId;
217
+ this.leaseId = leaseId;
218
+ this.usedTokens = usedTokens;
219
+ this.budgetError = budgetError;
220
+ this.businessError = businessError;
221
+ this.journalErrors = journalErrors;
222
+ this.budgetSettled = budgetSettled;
223
+ this.name = "OwnerAccountingFailure";
224
+ this.businessOutcome = Object.freeze(structuredClone(businessOutcome));
225
+ this.journalErrors = Object.freeze([...journalErrors]);
226
+ this.cause = new AggregateError([businessError, ...journalErrors, budgetError].filter((error) => error !== undefined), "owner business and accounting diagnostics");
227
+ }
228
+ }
229
+ export class LocalMerchantOwnerSession {
230
+ sessionFile;
231
+ recoveredApprovalCount = 0;
232
+ operationsFile;
233
+ dataDir;
234
+ ownershipToken;
235
+ nowFn;
236
+ input;
237
+ grant;
238
+ queue = Promise.resolve();
239
+ released = false;
240
+ activeTurn = false;
241
+ journalInitialized = false;
242
+ accountingFailures = new WeakMap();
243
+ constructor(input) {
244
+ if (!ownerSessionFullyEnabled(input.switches ?? readOwnerSessionSwitches(process.env)))
245
+ throw new OwnerSessionError("owner_session_disabled", "both owner switches must be explicitly enabled");
246
+ this.input = {
247
+ ...input,
248
+ sdkRuntime: input.sdkRuntime === undefined
249
+ ? undefined
250
+ : { ...input.sdkRuntime, tools: input.sdkRuntime.tools.map((t) => ({ ...t })) },
251
+ };
252
+ assertOpaqueMerchantId(input.merchantId);
253
+ this.grant = createFileGrantResolver({
254
+ merchantId: input.merchantId,
255
+ principal: input.principal,
256
+ });
257
+ this.assertGrant();
258
+ assertOwnerStorageAdmission(input.storageAdmission, input);
259
+ this.nowFn = input.now ?? (() => new Date().toISOString());
260
+ this.dataDir = merchantStorageDir(input.storageRoot, input.merchantId);
261
+ ensurePrivateDir(this.dataDir);
262
+ this.ownershipToken = acquireAdmissionLock(this.dataDir, input.merchantId);
263
+ this.operationsFile = join(this.dataDir, "operations.json");
264
+ this.sessionFile = join(this.dataDir, "session.sqlite");
265
+ this.journalInitialized =
266
+ existsSync(join(this.dataDir, "admission.json")) || existsSync(this.sessionFile);
267
+ try {
268
+ writePrivateJson(join(this.dataDir, "admission.json"), {
269
+ merchant_id: input.merchantId,
270
+ opened_at: this.nowFn(),
271
+ module: "a210-local-owner",
272
+ });
273
+ // Pre-create privately BEFORE SDK opens. No process-wide umask mutation.
274
+ if (!existsSync(this.sessionFile))
275
+ closeSync(openSync(this.sessionFile, "wx", 0o600));
276
+ chmodSync(this.sessionFile, 0o600);
277
+ if ((statSync(this.sessionFile).mode & 0o777) !== 0o600)
278
+ throw new OwnerSessionError("session_permission", "session must be private");
279
+ this.recoverOperations();
280
+ // Bound real store only; never expire an arbitrary same-principal store.
281
+ if (input.approvals !== undefined)
282
+ this.recoveredApprovalCount = this.expireForRecovery();
283
+ }
284
+ catch (error) {
285
+ releaseAdmissionLock(this.dataDir, this.ownershipToken);
286
+ throw error;
287
+ }
288
+ }
289
+ assertGrant() {
290
+ if (this.released)
291
+ throw new OwnerSessionError("session_closed", "session released");
292
+ const g = this.grant.readStrong(this.input.grantFile);
293
+ if (!g.ok)
294
+ throw new OwnerSessionError(g.code, g.message);
295
+ }
296
+ store() {
297
+ const s = this.input.approvals;
298
+ if (!(s instanceof WriteApprovalCandidateStore) ||
299
+ s.ownerStorageFile === undefined ||
300
+ !realpathSync(s.ownerStorageFile).startsWith(realpathSync(this.dataDir) + sep))
301
+ throw new OwnerSessionError("approval_store_missing", "real persistent approval store required");
302
+ if (s?.ownerBinding?.merchantId !== this.input.merchantId ||
303
+ s.ownerBinding.principal !== this.input.principal)
304
+ throw new OwnerSessionError("approval_store_binding_missing", "bound owner approval store required");
305
+ if (typeof s.expireForRecovery !== "function" ||
306
+ typeof s.expireDue !== "function" ||
307
+ typeof s.claimForExecution !== "function" ||
308
+ typeof s.markExecuted !== "function" ||
309
+ typeof s.supersede !== "function")
310
+ throw new OwnerSessionError("approval_store_missing", "real owner approval store required");
311
+ return s;
312
+ }
313
+ get operationsPath() {
314
+ return this.operationsFile;
315
+ }
316
+ readOperations() {
317
+ if (!existsSync(this.operationsFile)) {
318
+ if (this.journalInitialized)
319
+ throw new OwnerSessionError("operations_unknown", "operation journal missing");
320
+ return { operations: {} };
321
+ }
322
+ const data = readPrivateJson(this.operationsFile);
323
+ if (data === undefined ||
324
+ data.operations === null ||
325
+ typeof data.operations !== "object" ||
326
+ Array.isArray(data.operations))
327
+ throw new OwnerSessionError("operations_unknown", "invalid operation journal");
328
+ for (const rec of Object.values(data.operations))
329
+ if (rec === null ||
330
+ rec.merchant_id !== this.input.merchantId ||
331
+ typeof rec.business_key !== "string")
332
+ throw new OwnerSessionError("operations_unknown", "invalid operation binding");
333
+ return data;
334
+ }
335
+ writeOperations(ops) {
336
+ writePrivateJson(this.operationsFile, ops);
337
+ this.journalInitialized = true;
338
+ }
339
+ recoverOperations() {
340
+ const ops = this.readOperations();
341
+ for (const rec of Object.values(ops.operations))
342
+ if (rec.state === "reserved" || rec.state === "pending") {
343
+ rec.state = "reconciliation";
344
+ rec.updated_at = this.nowFn();
345
+ }
346
+ this.writeOperations(ops);
347
+ }
348
+ expireForRecovery() {
349
+ if (this.activeTurn)
350
+ throw new OwnerSessionError("session_busy", "session busy; wait turn completion");
351
+ this.assertGrant();
352
+ const n = this.store().expireForRecovery();
353
+ this.recoverOperations();
354
+ return n;
355
+ }
356
+ submitTurn(input) {
357
+ // Copy inputs at the trusted local API boundary, before asynchronous queue.
358
+ const snapshot = structuredClone(input);
359
+ const run = async () => {
360
+ this.activeTurn = true;
361
+ try {
362
+ return await this.doSubmitTurn(snapshot);
363
+ }
364
+ finally {
365
+ this.activeTurn = false;
366
+ }
367
+ };
368
+ const queued = this.queue.then(run, run);
369
+ this.queue = queued.then(() => undefined, () => undefined);
370
+ return queued;
371
+ }
372
+ /** Deterministic committed dispatch, same queue as SDK turns; no second agent loop. */
373
+ submitCommittedOperation(permit) {
374
+ const run = async () => {
375
+ this.activeTurn = true;
376
+ try {
377
+ return await this.doCommittedOperation(permit);
378
+ }
379
+ finally {
380
+ this.activeTurn = false;
381
+ }
382
+ };
383
+ const queued = this.queue.then(run, run);
384
+ this.queue = queued.then(() => undefined, () => undefined);
385
+ return queued;
386
+ }
387
+ businessAuthority(binding) {
388
+ this.assertGrant();
389
+ const host = this.input.businessHost;
390
+ if (!(host instanceof OwnerBusinessHost) ||
391
+ binding.merchantId !== this.input.merchantId ||
392
+ binding.principal !== this.input.principal)
393
+ throw new OwnerSessionError("business_binding_mismatch", "business authority required");
394
+ host.verify(binding);
395
+ return host;
396
+ }
397
+ businessGrantDigest() {
398
+ this.assertGrant();
399
+ const grant = this.grant.readStrong(this.input.grantFile);
400
+ if (!grant.ok)
401
+ throw new OwnerSessionError(grant.code, grant.message);
402
+ return grant.grant.digest;
403
+ }
404
+ /** Trusted local recovery only: no business execution, provider call, new lease or JSON permit. */
405
+ retryAccounting(failure) {
406
+ const run = async () => {
407
+ this.activeTurn = true;
408
+ try {
409
+ const context = this.accountingFailures.get(failure);
410
+ if (context === undefined)
411
+ throw new OwnerSessionError("accounting_recovery_unknown", "accounting recovery requires this live session's failure");
412
+ this.assertGrant();
413
+ const journal = this.readOperations();
414
+ const record = journal.operations[context.operationId];
415
+ if (this.businessGrantDigest() !== context.grantDigest ||
416
+ record === undefined ||
417
+ record.operation_id !== context.operationId ||
418
+ record.merchant_id !== this.input.merchantId ||
419
+ record.principal_id !== this.input.principal ||
420
+ record.budget_lease_id !== context.leaseId ||
421
+ record.budget_charged_tokens !==
422
+ context.usedTokens ||
423
+ context.expectedRecord === undefined ||
424
+ contentDigest(record) !== context.expectedRecord)
425
+ throw new OwnerSessionError("accounting_recovery_unknown", "accounting recovery binding is unknown; manual reconciliation required");
426
+ if (record.business_binding !== undefined)
427
+ this.businessAuthority(record.business_binding);
428
+ if (context.completed)
429
+ return context.businessOutcome;
430
+ if (record.budget_accounting_state !== "pending")
431
+ throw new OwnerSessionError("accounting_recovery_unknown", "accounting recovery state is unknown");
432
+ return await this.completeAccounting(context, true);
433
+ }
434
+ finally {
435
+ this.activeTurn = false;
436
+ }
437
+ };
438
+ const queued = this.queue.then(run, run);
439
+ this.queue = queued.then(() => undefined, () => undefined);
440
+ return queued;
441
+ }
442
+ async completeAccounting(context, recovering = false) {
443
+ context.businessOutcome = Object.freeze(structuredClone(context.businessOutcome));
444
+ let budgetError;
445
+ let budgetSettled = context.budgetSettled === true;
446
+ if (!budgetSettled) {
447
+ try {
448
+ await context.budget.settle({ leaseId: context.leaseId, usedTokens: context.usedTokens });
449
+ context.budgetSettled = true;
450
+ budgetSettled = true;
451
+ }
452
+ catch (error) {
453
+ budgetError = error;
454
+ }
455
+ }
456
+ if (budgetSettled) {
457
+ try {
458
+ const journal = this.readOperations();
459
+ const record = journal.operations[context.operationId];
460
+ if (record === undefined ||
461
+ record.operation_id !== context.operationId ||
462
+ record.merchant_id !== this.input.merchantId ||
463
+ record.principal_id !== this.input.principal ||
464
+ record.budget_lease_id !== context.leaseId ||
465
+ context.expectedRecord === undefined ||
466
+ contentDigest(record) !== context.expectedRecord)
467
+ throw new OwnerSessionError("accounting_journal_unknown", "accounting journal binding is unknown");
468
+ if (recovering) {
469
+ if (this.businessGrantDigest() !== context.grantDigest)
470
+ throw new OwnerSessionError("accounting_recovery_unknown", "accounting recovery grant changed");
471
+ if (record.business_binding !== undefined)
472
+ this.businessAuthority(record.business_binding);
473
+ }
474
+ record.budget_accounting_state = "settled";
475
+ this.writeOperations(journal);
476
+ context.expectedRecord = contentDigest(record);
477
+ context.completed = true;
478
+ return context.businessOutcome;
479
+ }
480
+ catch (error) {
481
+ context.journalErrors.push(error);
482
+ }
483
+ }
484
+ const failure = new OwnerAccountingFailure(context.operationId, context.leaseId, context.usedTokens, context.businessOutcome, budgetError, context.businessError, context.journalErrors, budgetSettled);
485
+ this.accountingFailures.set(failure, context);
486
+ throw failure;
487
+ }
488
+ assertBusinessRecord(rec, binding) {
489
+ if (rec.operation_id !== binding.operationId ||
490
+ rec.merchant_id !== binding.merchantId ||
491
+ rec.principal_id !== binding.principal ||
492
+ rec.candidate_id !== binding.candidateId ||
493
+ rec.kind !== binding.kind ||
494
+ rec.args_hash !== contentDigest(binding.arguments) ||
495
+ rec.business_key !== businessKey(binding.kind, binding.arguments) ||
496
+ contentDigest(rec.business_binding) !== contentDigest(binding))
497
+ throw new OwnerSessionError("operation_binding_unknown", "complete journal binding required");
498
+ }
499
+ applyBusinessReceipt(operationId, before, receipt, grantDigest) {
500
+ const binding = before.business_binding;
501
+ this.assertBusinessRecord(before, binding);
502
+ this.businessAuthority(binding); // strong grant/subject after await, even for unknown
503
+ if (this.businessGrantDigest() !== grantDigest)
504
+ throw new OwnerSessionError("grant_changed_during_read", "grant changed during receipt await");
505
+ const journal = this.readOperations();
506
+ const fresh = journal.operations[operationId];
507
+ if (fresh === undefined ||
508
+ contentDigest(fresh) !== contentDigest(before) ||
509
+ !["pending", "reconciliation"].includes(fresh.state))
510
+ throw new OwnerSessionError("operation_changed_during_read", "journal changed during receipt await");
511
+ if (receipt.status === "applied" &&
512
+ contentDigest(receipt.binding) === contentDigest(binding) &&
513
+ receipt.source === binding.authoritySource &&
514
+ receipt.resultingMoneyAuthorityVersion === binding.expectedMoneyAuthorityVersion + 1 &&
515
+ receipt.receiptRef) {
516
+ fresh.state = "settled";
517
+ fresh.reconciliation = {
518
+ decided_at: this.nowFn(),
519
+ outcome: "settled_with_evidence",
520
+ evidence: receipt.receiptRef,
521
+ };
522
+ fresh.updated_at = this.nowFn();
523
+ this.writeOperations(journal);
524
+ }
525
+ return structuredClone(fresh);
526
+ }
527
+ reconcileCommittedOperation(operationId) {
528
+ const run = async () => {
529
+ this.activeTurn = true;
530
+ try {
531
+ this.assertGrant();
532
+ const rec = this.readOperations().operations[operationId];
533
+ if (!rec?.business_binding ||
534
+ rec.operation_id !== operationId ||
535
+ rec.state !== "reconciliation")
536
+ throw new OwnerSessionError("operation_binding_unknown", "no reconcilable committed binding");
537
+ const before = structuredClone(rec);
538
+ this.assertBusinessRecord(before, before.business_binding);
539
+ const host = this.businessAuthority(before.business_binding);
540
+ const grantDigest = this.businessGrantDigest();
541
+ const receipt = await host.read(before.business_binding);
542
+ return this.applyBusinessReceipt(operationId, before, receipt, grantDigest);
543
+ }
544
+ finally {
545
+ this.activeTurn = false;
546
+ }
547
+ };
548
+ const queued = this.queue.then(run, run);
549
+ this.queue = queued.then(() => undefined, () => undefined);
550
+ return queued;
551
+ }
552
+ async doCommittedOperation(permit) {
553
+ const reject = (code) => ({ ok: false, code, message: code });
554
+ let binding;
555
+ let host;
556
+ let store;
557
+ try {
558
+ this.assertGrant();
559
+ if (!(this.input.businessHost instanceof OwnerBusinessHost))
560
+ return reject("business_authority_missing");
561
+ host = this.input.businessHost;
562
+ binding = host.inspect(permit);
563
+ this.businessAuthority(binding);
564
+ store = this.store();
565
+ }
566
+ catch {
567
+ return reject("committed_proof_invalid");
568
+ }
569
+ const operationId = binding.operationId;
570
+ const key = businessKey(binding.kind, binding.arguments);
571
+ if (binding.preconditions.business_key !== key)
572
+ return reject("candidate_binding_mismatch");
573
+ const records = this.readOperations().operations;
574
+ const old = records[operationId];
575
+ if (old?.budget_accounting_state === "pending")
576
+ return reject("owner_accounting_reconciliation");
577
+ if (old) {
578
+ try {
579
+ this.assertBusinessRecord(old, binding);
580
+ }
581
+ catch {
582
+ return reject("operation_binding_mismatch");
583
+ }
584
+ if (contentDigest(old.business_binding) !== contentDigest(binding))
585
+ return reject("operation_binding_mismatch");
586
+ return old.state === "settled"
587
+ ? { ok: true, operationId, state: "settled", turnSummary: "previous_authoritative_receipt" }
588
+ : { ok: false, operationId, state: "reconciliation", reason: "unknown_result_no_redrive" };
589
+ }
590
+ // Unknown history cannot be bypassed by a changed target/args/candidate/op.
591
+ if (Object.values(records).some((r) => (r.state !== "settled" || r.budget_accounting_state === "pending") &&
592
+ (r.business_key === key ||
593
+ (r.business_binding?.kind === binding.kind && r.business_binding.sku === binding.sku))))
594
+ return reject("operation_reconciliation");
595
+ store.expireDue();
596
+ if (store.get(binding.candidateId)?.status !== "approved")
597
+ return reject("needs_approval");
598
+ const budget = this.input.budgetGate;
599
+ if (!budget)
600
+ return reject("budget_gate_missing");
601
+ const grantDigest = this.businessGrantDigest();
602
+ const lease = await budget.acquire({
603
+ merchantId: this.input.merchantId,
604
+ estimatedTokens: host.reservationTokens,
605
+ });
606
+ if (!lease.allowed)
607
+ return reject("budget_denied");
608
+ let effectEntered = false;
609
+ let businessError;
610
+ const journalErrors = [];
611
+ let expectedRecord;
612
+ let businessOutcome;
613
+ try {
614
+ this.businessAuthority(binding);
615
+ const journal = this.readOperations();
616
+ if (journal.operations[operationId])
617
+ throw new Error("operation_already_reserved");
618
+ journal.operations[operationId] = {
619
+ operation_id: operationId,
620
+ merchant_id: binding.merchantId,
621
+ principal_id: binding.principal,
622
+ candidate_id: binding.candidateId,
623
+ business_binding: structuredClone(binding),
624
+ business_key: key,
625
+ kind: binding.kind,
626
+ args_hash: contentDigest(binding.arguments),
627
+ ...{ budget_lease_id: lease.leaseId, budget_reservation_tokens: host.reservationTokens },
628
+ state: "reserved",
629
+ budget_accounting_state: "pending",
630
+ created_at: this.nowFn(),
631
+ updated_at: this.nowFn(),
632
+ };
633
+ this.writeOperations(journal);
634
+ const outcome = await executeApprovedCandidate(store, binding.candidateId, {
635
+ readPreconditions: async () => {
636
+ this.businessAuthority(binding);
637
+ const fresh = await host.fresh(binding);
638
+ this.businessAuthority(binding);
639
+ return fresh;
640
+ },
641
+ execute: async (approvedArgs) => {
642
+ this.businessAuthority(binding);
643
+ if (contentDigest(approvedArgs) !== contentDigest(binding.arguments))
644
+ throw new Error("stored_arguments_changed");
645
+ const ops = this.readOperations();
646
+ const rec = ops.operations[operationId];
647
+ if (!rec ||
648
+ rec.state !== "reserved" ||
649
+ contentDigest(rec.business_binding) !== contentDigest(binding))
650
+ throw new Error("operation_binding_changed");
651
+ rec.state = "pending";
652
+ rec.updated_at = this.nowFn();
653
+ this.writeOperations(ops);
654
+ effectEntered = true;
655
+ await host.execute(binding, permit); // PATCH/readback alone is not a historical receipt.
656
+ this.businessAuthority(binding);
657
+ const before = structuredClone(this.readOperations().operations[operationId]);
658
+ if (contentDigest(before) !== contentDigest(rec))
659
+ throw new Error("operation_changed_during_write");
660
+ const grantDigest = this.businessGrantDigest();
661
+ const receipt = await host.read(binding);
662
+ const applied = this.applyBusinessReceipt(operationId, before, receipt, grantDigest);
663
+ return applied.state === "settled"
664
+ ? { applied: true }
665
+ : { ok: false, error: "operation_reconciliation" };
666
+ },
667
+ });
668
+ const ops = this.readOperations();
669
+ const rec = ops.operations[operationId];
670
+ if (outcome.kind !== "executed" || rec.state !== "settled") {
671
+ rec.state = "reconciliation";
672
+ rec.updated_at = this.nowFn();
673
+ this.writeOperations(ops);
674
+ businessOutcome = {
675
+ ok: false,
676
+ operationId,
677
+ state: "reconciliation",
678
+ reason: "unknown_result_no_redrive",
679
+ };
680
+ }
681
+ else {
682
+ businessOutcome = {
683
+ ok: true,
684
+ operationId,
685
+ state: "settled",
686
+ turnSummary: "authoritative_exact_money_receipt",
687
+ };
688
+ }
689
+ }
690
+ catch (error) {
691
+ businessError = error;
692
+ try {
693
+ const ops = this.readOperations();
694
+ const rec = ops.operations[operationId];
695
+ if (rec && rec.state !== "settled") {
696
+ rec.state = "reconciliation";
697
+ rec.updated_at = this.nowFn();
698
+ this.writeOperations(ops);
699
+ }
700
+ }
701
+ catch (error) {
702
+ journalErrors.push(error);
703
+ /* preserve unreadable journal, never replace */
704
+ }
705
+ businessOutcome = {
706
+ ok: false,
707
+ operationId,
708
+ state: "reconciliation",
709
+ reason: "unknown_result_no_redrive",
710
+ };
711
+ }
712
+ finally {
713
+ // An uncertain business window never discounts its conservative reservation to zero.
714
+ try {
715
+ const ops = this.readOperations();
716
+ const rec = ops.operations[operationId];
717
+ if (rec) {
718
+ Object.assign(rec, {
719
+ budget_charged_tokens: effectEntered ? host.reservationTokens : 0,
720
+ budget_usage_known: !effectEntered,
721
+ });
722
+ this.writeOperations(ops);
723
+ expectedRecord = contentDigest(rec);
724
+ }
725
+ }
726
+ catch (error) {
727
+ journalErrors.push(error);
728
+ /* settlement still runs */
729
+ }
730
+ }
731
+ return await this.completeAccounting({
732
+ budget,
733
+ operationId,
734
+ leaseId: lease.leaseId,
735
+ usedTokens: effectEntered ? host.reservationTokens : 0,
736
+ businessOutcome,
737
+ businessError,
738
+ journalErrors,
739
+ grantDigest,
740
+ expectedRecord,
741
+ });
742
+ }
743
+ async doSubmitTurn(input) {
744
+ const reject = (code) => ({ ok: false, code, message: code });
745
+ try {
746
+ this.assertGrant();
747
+ }
748
+ catch (e) {
749
+ return reject(e instanceof OwnerSessionError ? e.code : "grant_unknown");
750
+ }
751
+ // Business writes only enter through a committed capability, never model input.
752
+ if (String(input.mode) === "operation")
753
+ return reject("committed_dispatch_required");
754
+ if (this.input.budgetGate === undefined)
755
+ return reject("budget_gate_missing");
756
+ const runtime = this.input.sdkRuntime;
757
+ if (runtime === undefined || this.input.effectRunner !== undefined)
758
+ return reject("sdk_runtime_configuration_required");
759
+ if (!Number.isSafeInteger(runtime.reservationTokens) ||
760
+ runtime.reservationTokens < 1 ||
761
+ !Number.isSafeInteger(runtime.maxRequests) ||
762
+ runtime.maxRequests < 1 ||
763
+ runtime.maxRequests > 4 ||
764
+ !Number.isSafeInteger(runtime.timeoutMs) ||
765
+ runtime.timeoutMs < 1 ||
766
+ runtime.timeoutMs > 30000)
767
+ return reject("sdk_runtime_configuration_invalid");
768
+ if (runtime.model === undefined ||
769
+ typeof runtime.models?.getModel !== "function" ||
770
+ runtime.models.getModel(runtime.model.provider, runtime.model.modelId) === undefined)
771
+ return reject("sdk_model_configuration_required");
772
+ const mode = input.mode === "operation" ? "operation" : "converse";
773
+ const kind = input.kind ?? "submit_turn";
774
+ const args = input.args ?? { text: input.text };
775
+ const key = businessKey(kind, args);
776
+ let store;
777
+ let candidateId;
778
+ let tool;
779
+ if (mode === "operation") {
780
+ try {
781
+ store = this.store();
782
+ }
783
+ catch {
784
+ return reject("approval_store_binding_missing");
785
+ }
786
+ tool = runtime.tools.find((t) => t.name === kind);
787
+ if (tool === undefined ||
788
+ typeof tool.readFresh !== "function" ||
789
+ typeof tool.execute !== "function")
790
+ return reject("business_source_configuration_required");
791
+ candidateId = input.approval?.candidateId;
792
+ if (!candidateId)
793
+ return reject("needs_approval");
794
+ store.expireDue();
795
+ const candidate = store.get(candidateId);
796
+ if (candidate?.status !== "approved")
797
+ return reject("needs_approval");
798
+ const pre = candidate.preconditions;
799
+ if (candidate.tool !== kind ||
800
+ contentDigest(candidate.arguments) !== contentDigest(args) ||
801
+ pre.merchant_id !== this.input.merchantId ||
802
+ pre.principal !== this.input.principal ||
803
+ pre.business_key !== key)
804
+ return reject("candidate_binding_mismatch");
805
+ }
806
+ const existing = Object.values(this.readOperations().operations).filter((r) => r.business_key === key);
807
+ if (existing.some((r) => r.budget_accounting_state === "pending"))
808
+ return reject("owner_accounting_reconciliation");
809
+ if (existing.some((r) => r.state !== "settled"))
810
+ return reject("operation_reconciliation");
811
+ if (mode === "operation" &&
812
+ existing.some((r) => r.reconciliation?.outcome !== "settled_no_new_effect" ||
813
+ r.candidate_id === candidateId))
814
+ return reject("operation_already_applied_or_new_approval_required");
815
+ const grantDigest = this.businessGrantDigest();
816
+ const decision = await this.input.budgetGate.acquire({
817
+ merchantId: this.input.merchantId,
818
+ estimatedTokens: runtime.reservationTokens,
819
+ });
820
+ if (!decision.allowed)
821
+ return reject("budget_denied");
822
+ // Everything after acquisition, including IO, stays inside this finally.
823
+ let usedTokens = 0;
824
+ let enteredSdk = false;
825
+ let usageKnown = false;
826
+ const operationId = `op_${createHash("sha256").update(`${this.input.merchantId}:${this.nowFn()}:${Math.random()}`).digest("hex").slice(0, 24)}`;
827
+ let toolSucceeded = false;
828
+ let toolRefused = false;
829
+ let effectUnknown = false;
830
+ let businessError;
831
+ const journalErrors = [];
832
+ let expectedRecord;
833
+ let businessOutcome;
834
+ try {
835
+ const ops = this.readOperations();
836
+ ops.operations[operationId] = {
837
+ operation_id: operationId,
838
+ merchant_id: this.input.merchantId,
839
+ principal_id: this.input.principal,
840
+ ...{
841
+ budget_lease_id: decision.leaseId,
842
+ budget_reservation_tokens: runtime.reservationTokens,
843
+ },
844
+ business_key: key,
845
+ kind,
846
+ args_hash: contentDigest(args),
847
+ state: "reserved",
848
+ budget_accounting_state: "pending",
849
+ created_at: this.nowFn(),
850
+ updated_at: this.nowFn(),
851
+ ...(candidateId === undefined ? {} : { candidate_id: candidateId }),
852
+ };
853
+ this.writeOperations(ops);
854
+ const setState = (state) => {
855
+ const journal = this.readOperations();
856
+ const rec = journal.operations[operationId];
857
+ if (rec === undefined)
858
+ throw new OwnerSessionError("operations_unknown", "operation missing");
859
+ rec.state = state;
860
+ rec.updated_at = this.nowFn();
861
+ this.writeOperations(journal);
862
+ };
863
+ const host = {
864
+ historyStrong: async (limit) => this.history(limit),
865
+ invokeTool: async (call) => {
866
+ this.assertGrant();
867
+ if (mode !== "operation" ||
868
+ store === undefined ||
869
+ candidateId === undefined ||
870
+ tool === undefined ||
871
+ toolSucceeded ||
872
+ effectUnknown ||
873
+ call.tool !== kind ||
874
+ contentDigest(call.args) !== contentDigest(args) ||
875
+ !this.checkExecutionValid(operationId, "reserved")) {
876
+ toolRefused = true;
877
+ return {
878
+ isError: true,
879
+ content: [{ type: "text", text: "candidate_binding_mismatch" }],
880
+ };
881
+ }
882
+ const activeTool = tool;
883
+ const audit = this.readOperations();
884
+ Object.assign(audit.operations[operationId], {
885
+ sdk_task_id: call.taskId,
886
+ sdk_conversation_id: call.conversationId,
887
+ sdk_call_id: call.callId,
888
+ });
889
+ this.writeOperations(audit);
890
+ const outcome = await executeApprovedCandidate(store, candidateId, {
891
+ readPreconditions: async () => {
892
+ this.assertGrant();
893
+ const facts = await activeTool.readFresh(call.args);
894
+ if (facts === null || typeof facts !== "object" || Array.isArray(facts))
895
+ throw new Error("business_source_unknown");
896
+ this.assertGrant();
897
+ // Identity/business slots are host-bound, never model/source labels.
898
+ return {
899
+ ...facts,
900
+ merchant_id: this.input.merchantId,
901
+ principal: this.input.principal,
902
+ business_key: key,
903
+ };
904
+ },
905
+ execute: async (approvedArgs) => {
906
+ this.assertGrant();
907
+ setState("pending"); // durable intent before entering effect window
908
+ effectUnknown = true;
909
+ const result = await activeTool.execute(approvedArgs, operationId);
910
+ if (!result.known)
911
+ return { ok: false, error: "operation_reconciliation" };
912
+ effectUnknown = false;
913
+ if (result.result.isError)
914
+ return { ok: false, error: "tool_refused" };
915
+ toolSucceeded = true;
916
+ setState("settled");
917
+ return { result: result.result };
918
+ },
919
+ });
920
+ if (outcome.kind !== "executed") {
921
+ toolRefused = true;
922
+ return {
923
+ isError: true,
924
+ content: [
925
+ { type: "text", text: effectUnknown ? "operation_reconciliation" : outcome.kind },
926
+ ],
927
+ };
928
+ }
929
+ return outcome.output.result;
930
+ },
931
+ };
932
+ enteredSdk = true;
933
+ usedTokens = runtime.reservationTokens; // uncertainty never releases to zero
934
+ const outcome = await defaultPiDurableEffectRunner({
935
+ operationId,
936
+ businessKey: key,
937
+ text: input.text,
938
+ sdk: {
939
+ sessionFile: this.sessionFile,
940
+ history: (limit) => this.history(limit),
941
+ hostGate: () => {
942
+ throw new Error("legacy gate disabled");
943
+ },
944
+ host,
945
+ mode,
946
+ runtime,
947
+ checkGrant: () => this.assertGrant(),
948
+ storageAdmission: this.input.storageAdmission,
949
+ },
950
+ });
951
+ if (outcome.usedTokens !== undefined &&
952
+ Number.isSafeInteger(outcome.usedTokens) &&
953
+ outcome.usedTokens >= 0) {
954
+ // Confirmed SDK completion with valid observed usage and no unresolved
955
+ // effect uses measured billing; conservative reservation remains unknown.
956
+ usageKnown = outcome.known && !effectUnknown;
957
+ usedTokens =
958
+ outcome.known && !effectUnknown
959
+ ? outcome.usedTokens
960
+ : Math.max(runtime.reservationTokens, outcome.usedTokens);
961
+ }
962
+ const known = outcome.known && !effectUnknown && (mode === "converse" || toolSucceeded);
963
+ setState(known || (outcome.known && toolRefused && !effectUnknown) ? "settled" : "reconciliation");
964
+ // Explicit known no-effect refusal may be retried only with a new normal approval.
965
+ if (outcome.known && toolRefused && !effectUnknown && !toolSucceeded) {
966
+ const journal = this.readOperations();
967
+ journal.operations[operationId].reconciliation = {
968
+ decided_at: this.nowFn(),
969
+ outcome: "settled_no_new_effect",
970
+ };
971
+ this.writeOperations(journal);
972
+ businessOutcome = reject("tool_not_executed");
973
+ }
974
+ else {
975
+ businessOutcome = known
976
+ ? { ok: true, operationId, state: "settled", turnSummary: outcome.summary }
977
+ : {
978
+ ok: false,
979
+ operationId,
980
+ state: "reconciliation",
981
+ reason: "unknown_result_no_redrive",
982
+ };
983
+ }
984
+ }
985
+ catch (error) {
986
+ businessError = error;
987
+ // Journal IO failure is unknown and must never create an empty replacement.
988
+ try {
989
+ const ops = this.readOperations();
990
+ const rec = ops.operations[operationId];
991
+ if (rec !== undefined) {
992
+ rec.state = "reconciliation";
993
+ rec.updated_at = this.nowFn();
994
+ this.writeOperations(ops);
995
+ }
996
+ }
997
+ catch (error) {
998
+ journalErrors.push(error);
999
+ /* preserve existing evidence */
1000
+ }
1001
+ businessOutcome = {
1002
+ ok: false,
1003
+ operationId,
1004
+ state: "reconciliation",
1005
+ reason: "unknown_result_no_redrive",
1006
+ };
1007
+ }
1008
+ finally {
1009
+ try {
1010
+ const journal = this.readOperations();
1011
+ const record = journal.operations[operationId];
1012
+ if (record !== undefined) {
1013
+ Object.assign(record, {
1014
+ budget_usage_known: !enteredSdk || usageKnown,
1015
+ budget_charged_tokens: enteredSdk ? usedTokens : 0,
1016
+ });
1017
+ this.writeOperations(journal);
1018
+ expectedRecord = contentDigest(record);
1019
+ }
1020
+ }
1021
+ catch (error) {
1022
+ journalErrors.push(error);
1023
+ /* settlement must still run exactly once even with journal IO failure */
1024
+ }
1025
+ }
1026
+ return await this.completeAccounting({
1027
+ budget: this.input.budgetGate,
1028
+ operationId,
1029
+ leaseId: decision.leaseId,
1030
+ usedTokens: enteredSdk ? usedTokens : 0,
1031
+ businessOutcome,
1032
+ businessError,
1033
+ journalErrors,
1034
+ grantDigest,
1035
+ expectedRecord,
1036
+ });
1037
+ }
1038
+ checkExecutionValid(operationId, expectedState) {
1039
+ this.assertGrant();
1040
+ return this.readOperations().operations[operationId]?.state === expectedState;
1041
+ }
1042
+ async history(limit = 50) {
1043
+ this.assertGrant();
1044
+ if (this.input.storageAdmission === undefined)
1045
+ throw new OwnerSessionError("storage_capability_required", "storage capability required");
1046
+ requireOwnerProvider(this.input.storageAdmission);
1047
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
1048
+ throw new RangeError("invalid history limit");
1049
+ const [{ Harness, createRegistry }, { openNodeSqliteStorage }, { BACKGROUND_CONTEXT }, { createModels },] = await Promise.all([
1050
+ import("@earendil-works/pi-durable"),
1051
+ import("@earendil-works/pi-durable/storage/sqlite/node"),
1052
+ import("@earendil-works/chord/context"),
1053
+ import("@earendil-works/pi-ai/models"),
1054
+ ]);
1055
+ const harness = await Harness.open(guardOwnerStorage(await openNodeSqliteStorage(this.sessionFile), this.input.storageAdmission), { models: createModels(), registry: createRegistry() }, BACKGROUND_CONTEXT);
1056
+ try {
1057
+ const conversation = await harness.root(BACKGROUND_CONTEXT);
1058
+ const page = await conversation.entries({}, limit, undefined, BACKGROUND_CONTEXT);
1059
+ this.assertGrant();
1060
+ return page.items.map((e) => JSON.stringify(e));
1061
+ }
1062
+ finally {
1063
+ await harness.close(BACKGROUND_CONTEXT);
1064
+ }
1065
+ }
1066
+ reconcileOperation(operationId, _outcome) {
1067
+ this.assertGrant();
1068
+ const ops = this.readOperations();
1069
+ const rec = ops.operations[operationId];
1070
+ if (rec?.principal_id !== this.input.principal)
1071
+ throw new OwnerSessionError("operation_binding_unknown", "operation principal binding missing or different");
1072
+ if (rec?.business_binding !== undefined)
1073
+ throw new OwnerSessionError("async_business_receipt_required", "committed business uses only async authoritative receipt");
1074
+ if (rec === undefined || rec.state !== "reconciliation")
1075
+ throw new OwnerSessionError("not_in_reconciliation", "operation not reconcilable");
1076
+ let result;
1077
+ try {
1078
+ result = this.input.reconciliationVerifier?.query?.({
1079
+ operationId,
1080
+ merchantId: this.input.merchantId,
1081
+ principal: this.input.principal,
1082
+ businessKey: rec.business_key,
1083
+ });
1084
+ }
1085
+ catch {
1086
+ result = undefined;
1087
+ }
1088
+ this.assertGrant();
1089
+ if (result !== undefined &&
1090
+ result.source === this.input.reconciliationVerifier?.source &&
1091
+ typeof result.source === "string" &&
1092
+ result.source.length > 0 &&
1093
+ typeof result.receiptRef === "string" &&
1094
+ result.receiptRef.length > 0 &&
1095
+ result.operationId === operationId &&
1096
+ result.merchantId === this.input.merchantId &&
1097
+ result.principal === this.input.principal &&
1098
+ result.businessKey === rec.business_key &&
1099
+ (result.outcome === "confirmed_applied" || result.outcome === "confirmed_not_applied")) {
1100
+ rec.state = "settled";
1101
+ rec.reconciliation = {
1102
+ decided_at: this.nowFn(),
1103
+ outcome: result.outcome === "confirmed_applied"
1104
+ ? "settled_with_evidence"
1105
+ : "settled_no_new_effect",
1106
+ evidence: result.receiptRef,
1107
+ };
1108
+ }
1109
+ else
1110
+ rec.reconciliation = { decided_at: this.nowFn(), outcome: "requires_manual_review" };
1111
+ rec.updated_at = this.nowFn();
1112
+ this.writeOperations(ops);
1113
+ return rec;
1114
+ }
1115
+ hasUnresolvedForBusinessKey(kind, args) {
1116
+ this.assertGrant();
1117
+ const key = businessKey(kind, args);
1118
+ return Object.values(this.readOperations().operations).some((r) => r.business_key === key && r.state !== "settled");
1119
+ }
1120
+ storageFiles() {
1121
+ this.assertGrant();
1122
+ return {
1123
+ operations: existsSync(this.operationsFile),
1124
+ session: existsSync(this.sessionFile),
1125
+ admission: existsSync(join(this.dataDir, "admission.json")),
1126
+ lock: existsSync(join(this.dataDir, "admission.lock")),
1127
+ };
1128
+ }
1129
+ release() {
1130
+ if (this.activeTurn)
1131
+ throw new OwnerSessionError("session_busy", "session busy; wait turn completion");
1132
+ if (!this.released) {
1133
+ releaseAdmissionLock(this.dataDir, this.ownershipToken);
1134
+ this.released = true;
1135
+ }
1136
+ }
1137
+ }
1138
+ function totalUsage(usage) {
1139
+ let sum = 0;
1140
+ for (const entry of [...Object.values(usage.models), ...Object.values(usage.tools)]) {
1141
+ if (!Number.isSafeInteger(entry.totalTokens) || entry.totalTokens < 0)
1142
+ throw new Error("usage_unknown");
1143
+ sum += entry.totalTokens;
1144
+ }
1145
+ if (!Number.isSafeInteger(sum))
1146
+ throw new Error("usage_unknown");
1147
+ return sum;
1148
+ }
1149
+ /** Official loop only. No default faux, local counter, custom loop or self-approval. */
1150
+ export const defaultPiDurableEffectRunner = async ({ text, sdk }) => {
1151
+ if (sdk.runtime === undefined ||
1152
+ sdk.host === undefined ||
1153
+ sdk.mode === undefined ||
1154
+ sdk.checkGrant === undefined ||
1155
+ sdk.storageAdmission === undefined)
1156
+ throw new OwnerSessionError("sdk_runtime_configuration_required", "trusted SDK configuration required");
1157
+ const runtime = sdk.runtime;
1158
+ const [{ Harness, defineExtension, hook, GenerationTask }, { openNodeSqliteStorage }, { BACKGROUND_CONTEXT, withAbortSignal }, { createOwnerSdkRegistry },] = await Promise.all([
1159
+ import("@earendil-works/pi-durable"),
1160
+ import("@earendil-works/pi-durable/storage/sqlite/node"),
1161
+ import("@earendil-works/chord/context"),
1162
+ import("./owner-sdk-tools.js"),
1163
+ ]);
1164
+ const checkGrant = sdk.checkGrant;
1165
+ const admission = sdk.storageAdmission;
1166
+ // Before normal storage/Harness.open/openTasks (which can write recovery state).
1167
+ assertOwnerStorageReady(admission);
1168
+ let boundConversationId;
1169
+ let usageBefore = 0;
1170
+ let currentSpend;
1171
+ let historyReader;
1172
+ const bridge = createOwnerSdkRegistry({
1173
+ mode: sdk.mode,
1174
+ tools: runtime.tools,
1175
+ host: {
1176
+ invokeTool: async (call) => {
1177
+ checkGrant();
1178
+ if (call.conversationId !== boundConversationId)
1179
+ throw new Error("conversation_binding_mismatch");
1180
+ if (currentSpend === undefined || (await currentSpend()) >= runtime.reservationTokens)
1181
+ throw new Error("turn_budget_exhausted");
1182
+ return sdk.host.invokeTool(call);
1183
+ },
1184
+ historyStrong: async (limit) => {
1185
+ checkGrant();
1186
+ if (historyReader === undefined)
1187
+ throw new Error("history unavailable");
1188
+ const rows = await historyReader(limit);
1189
+ checkGrant();
1190
+ return rows;
1191
+ },
1192
+ },
1193
+ });
1194
+ bridge.registry.install(defineExtension({
1195
+ name: "kiwi-owner-turn-bound",
1196
+ hooks: [
1197
+ hook(GenerationTask, {
1198
+ beforeRequest: async (_request, api) => {
1199
+ checkGrant();
1200
+ requireOwnerProvider(admission, api.conversationId);
1201
+ },
1202
+ }),
1203
+ ],
1204
+ }));
1205
+ const harness = await Harness.open(guardOwnerStorage(await openNodeSqliteStorage(sdk.sessionFile), admission), {
1206
+ models: guardOwnerModels(runtime.models, admission, checkGrant, createOwnerRequestGate({
1207
+ maxRequests: runtime.maxRequests,
1208
+ reservationTokens: runtime.reservationTokens,
1209
+ currentSpend: async () => {
1210
+ if (currentSpend === undefined)
1211
+ throw new Error("usage_unknown");
1212
+ return currentSpend();
1213
+ },
1214
+ })),
1215
+ registry: bridge.registry,
1216
+ settings: {
1217
+ retry: { enabled: false },
1218
+ compaction: { enabled: false },
1219
+ stream: { maxRetries: 0, timeoutMs: runtime.timeoutMs },
1220
+ },
1221
+ }, BACKGROUND_CONTEXT);
1222
+ let usedTokens;
1223
+ try {
1224
+ const context = withAbortSignal(AbortSignal.timeout(runtime.timeoutMs), BACKGROUND_CONTEXT);
1225
+ const conversation = await harness.root(context, { agent: { model: runtime.model } });
1226
+ requireOwnerProvider(admission, conversation.id);
1227
+ boundConversationId = conversation.id;
1228
+ historyReader = async (limit) => (await conversation.entries({}, limit, undefined, context)).items.map((e) => JSON.stringify(e));
1229
+ usageBefore = totalUsage(await harness.usage(context));
1230
+ currentSpend = async () => {
1231
+ const spend = totalUsage(await harness.usage(context)) - usageBefore;
1232
+ if (!Number.isSafeInteger(spend) || spend < 0)
1233
+ throw new Error("usage_unknown");
1234
+ return spend;
1235
+ };
1236
+ const submission = await conversation.submit({ type: "input", content: text }, context);
1237
+ const result = await submission.wait(context);
1238
+ usedTokens = totalUsage(await harness.usage(context)) - usageBefore;
1239
+ if (!Number.isSafeInteger(usedTokens) || usedTokens < 0)
1240
+ throw new Error("usage_unknown");
1241
+ return {
1242
+ known: result.status === "done",
1243
+ summary: `submission ${submission.id}: ${result.status}`,
1244
+ usedTokens,
1245
+ };
1246
+ }
1247
+ catch {
1248
+ try {
1249
+ usedTokens = totalUsage(await harness.usage(BACKGROUND_CONTEXT)) - usageBefore;
1250
+ }
1251
+ catch {
1252
+ /* keep unknown usage */
1253
+ }
1254
+ return {
1255
+ known: false,
1256
+ summary: "sdk_result_unknown",
1257
+ ...(usedTokens === undefined ? {} : { usedTokens }),
1258
+ };
1259
+ }
1260
+ finally {
1261
+ await harness.close(BACKGROUND_CONTEXT);
1262
+ }
1263
+ };
1264
+ export function defineOwnerTool(def) {
1265
+ return {
1266
+ name: def.name,
1267
+ label: def.label,
1268
+ description: def.description,
1269
+ parameters: def.parameters,
1270
+ async run(args) {
1271
+ // 每次执行强读 grant(撤销后效果 0:授权失败抛 authorization_lost)。
1272
+ const check = checkFileGrant(def.grantFile, def.merchantId, def.principal);
1273
+ if (!check.ok) {
1274
+ throw new OwnerSessionError("authorization_lost", `grant check failed: ${check.code}(工具效果 0)`);
1275
+ }
1276
+ return def.execute(args);
1277
+ },
1278
+ };
1279
+ }
1280
+ //# sourceMappingURL=owner-session.js.map