@decionis/agentsafe 0.1.0

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 (436) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +909 -0
  4. package/dist/Cli.d.ts +3 -0
  5. package/dist/Cli.d.ts.map +1 -0
  6. package/dist/Cli.js +150 -0
  7. package/dist/Cli.js.map +1 -0
  8. package/dist/Index.d.ts +104 -0
  9. package/dist/Index.d.ts.map +1 -0
  10. package/dist/Index.js +102 -0
  11. package/dist/Index.js.map +1 -0
  12. package/dist/Serve.d.ts +26 -0
  13. package/dist/Serve.d.ts.map +1 -0
  14. package/dist/Serve.js +143 -0
  15. package/dist/Serve.js.map +1 -0
  16. package/dist/TrustedExecutor.d.ts +66 -0
  17. package/dist/TrustedExecutor.d.ts.map +1 -0
  18. package/dist/TrustedExecutor.js +170 -0
  19. package/dist/TrustedExecutor.js.map +1 -0
  20. package/dist/Version.d.ts +6 -0
  21. package/dist/Version.d.ts.map +1 -0
  22. package/dist/Version.js +21 -0
  23. package/dist/Version.js.map +1 -0
  24. package/dist/adapters/AdapterActionHandler.d.ts +48 -0
  25. package/dist/adapters/AdapterActionHandler.d.ts.map +1 -0
  26. package/dist/adapters/AdapterActionHandler.js +148 -0
  27. package/dist/adapters/AdapterActionHandler.js.map +1 -0
  28. package/dist/adapters/EffectAdapter.d.ts +96 -0
  29. package/dist/adapters/EffectAdapter.d.ts.map +1 -0
  30. package/dist/adapters/EffectAdapter.js +16 -0
  31. package/dist/adapters/EffectAdapter.js.map +1 -0
  32. package/dist/adapters/EffectAwareGrantVerifier.d.ts +30 -0
  33. package/dist/adapters/EffectAwareGrantVerifier.d.ts.map +1 -0
  34. package/dist/adapters/EffectAwareGrantVerifier.js +38 -0
  35. package/dist/adapters/EffectAwareGrantVerifier.js.map +1 -0
  36. package/dist/adapters/EffectComparison.d.ts +20 -0
  37. package/dist/adapters/EffectComparison.d.ts.map +1 -0
  38. package/dist/adapters/EffectComparison.js +48 -0
  39. package/dist/adapters/EffectComparison.js.map +1 -0
  40. package/dist/adapters/EffectEvidenceBuilder.d.ts +60 -0
  41. package/dist/adapters/EffectEvidenceBuilder.d.ts.map +1 -0
  42. package/dist/adapters/EffectEvidenceBuilder.js +127 -0
  43. package/dist/adapters/EffectEvidenceBuilder.js.map +1 -0
  44. package/dist/adapters/EffectEvidenceRegister.d.ts +31 -0
  45. package/dist/adapters/EffectEvidenceRegister.d.ts.map +1 -0
  46. package/dist/adapters/EffectEvidenceRegister.js +21 -0
  47. package/dist/adapters/EffectEvidenceRegister.js.map +1 -0
  48. package/dist/adapters/JcsDigest.d.ts +43 -0
  49. package/dist/adapters/JcsDigest.d.ts.map +1 -0
  50. package/dist/adapters/JcsDigest.js +86 -0
  51. package/dist/adapters/JcsDigest.js.map +1 -0
  52. package/dist/adapters/banking/BankingAction.d.ts +146 -0
  53. package/dist/adapters/banking/BankingAction.d.ts.map +1 -0
  54. package/dist/adapters/banking/BankingAction.js +102 -0
  55. package/dist/adapters/banking/BankingAction.js.map +1 -0
  56. package/dist/adapters/banking/BankingAdapter.d.ts +60 -0
  57. package/dist/adapters/banking/BankingAdapter.d.ts.map +1 -0
  58. package/dist/adapters/banking/BankingAdapter.js +107 -0
  59. package/dist/adapters/banking/BankingAdapter.js.map +1 -0
  60. package/dist/adapters/banking/BankingHandlers.d.ts +24 -0
  61. package/dist/adapters/banking/BankingHandlers.d.ts.map +1 -0
  62. package/dist/adapters/banking/BankingHandlers.js +47 -0
  63. package/dist/adapters/banking/BankingHandlers.js.map +1 -0
  64. package/dist/adapters/banking/BankingIntentBinder.d.ts +47 -0
  65. package/dist/adapters/banking/BankingIntentBinder.d.ts.map +1 -0
  66. package/dist/adapters/banking/BankingIntentBinder.js +64 -0
  67. package/dist/adapters/banking/BankingIntentBinder.js.map +1 -0
  68. package/dist/adapters/banking/CoreBankingHttpAdapter.d.ts +55 -0
  69. package/dist/adapters/banking/CoreBankingHttpAdapter.d.ts.map +1 -0
  70. package/dist/adapters/banking/CoreBankingHttpAdapter.js +248 -0
  71. package/dist/adapters/banking/CoreBankingHttpAdapter.js.map +1 -0
  72. package/dist/adapters/banking/Currency.d.ts +10 -0
  73. package/dist/adapters/banking/Currency.d.ts.map +1 -0
  74. package/dist/adapters/banking/Currency.js +91 -0
  75. package/dist/adapters/banking/Currency.js.map +1 -0
  76. package/dist/adapters/banking/EffectProjections.d.ts +52 -0
  77. package/dist/adapters/banking/EffectProjections.d.ts.map +1 -0
  78. package/dist/adapters/banking/EffectProjections.js +140 -0
  79. package/dist/adapters/banking/EffectProjections.js.map +1 -0
  80. package/dist/adapters/banking/Iban.d.ts +18 -0
  81. package/dist/adapters/banking/Iban.d.ts.map +1 -0
  82. package/dist/adapters/banking/Iban.js +38 -0
  83. package/dist/adapters/banking/Iban.js.map +1 -0
  84. package/dist/adapters/banking/Money.d.ts +32 -0
  85. package/dist/adapters/banking/Money.d.ts.map +1 -0
  86. package/dist/adapters/banking/Money.js +81 -0
  87. package/dist/adapters/banking/Money.js.map +1 -0
  88. package/dist/adapters/banking/ReasonCodes.d.ts +19 -0
  89. package/dist/adapters/banking/ReasonCodes.d.ts.map +1 -0
  90. package/dist/adapters/banking/ReasonCodes.js +35 -0
  91. package/dist/adapters/banking/ReasonCodes.js.map +1 -0
  92. package/dist/audit/ChainJournal.d.ts +38 -0
  93. package/dist/audit/ChainJournal.d.ts.map +1 -0
  94. package/dist/audit/ChainJournal.js +97 -0
  95. package/dist/audit/ChainJournal.js.map +1 -0
  96. package/dist/audit/HashChain.d.ts +39 -0
  97. package/dist/audit/HashChain.d.ts.map +1 -0
  98. package/dist/audit/HashChain.js +63 -0
  99. package/dist/audit/HashChain.js.map +1 -0
  100. package/dist/audit/HashChainedAuditSink.d.ts +22 -0
  101. package/dist/audit/HashChainedAuditSink.d.ts.map +1 -0
  102. package/dist/audit/HashChainedAuditSink.js +26 -0
  103. package/dist/audit/HashChainedAuditSink.js.map +1 -0
  104. package/dist/audit/LineAuditSink.d.ts +19 -0
  105. package/dist/audit/LineAuditSink.d.ts.map +1 -0
  106. package/dist/audit/LineAuditSink.js +35 -0
  107. package/dist/audit/LineAuditSink.js.map +1 -0
  108. package/dist/cli/Arguments.d.ts +26 -0
  109. package/dist/cli/Arguments.d.ts.map +1 -0
  110. package/dist/cli/Arguments.js +66 -0
  111. package/dist/cli/Arguments.js.map +1 -0
  112. package/dist/cli/CliProcess.d.ts +29 -0
  113. package/dist/cli/CliProcess.d.ts.map +1 -0
  114. package/dist/cli/CliProcess.js +78 -0
  115. package/dist/cli/CliProcess.js.map +1 -0
  116. package/dist/cli/Commands.d.ts +8 -0
  117. package/dist/cli/Commands.d.ts.map +1 -0
  118. package/dist/cli/Commands.js +67 -0
  119. package/dist/cli/Commands.js.map +1 -0
  120. package/dist/cli/ConfigCommand.d.ts +7 -0
  121. package/dist/cli/ConfigCommand.d.ts.map +1 -0
  122. package/dist/cli/ConfigCommand.js +77 -0
  123. package/dist/cli/ConfigCommand.js.map +1 -0
  124. package/dist/cli/ConfigFile.d.ts +21 -0
  125. package/dist/cli/ConfigFile.d.ts.map +1 -0
  126. package/dist/cli/ConfigFile.js +57 -0
  127. package/dist/cli/ConfigFile.js.map +1 -0
  128. package/dist/cli/Credentials.d.ts +15 -0
  129. package/dist/cli/Credentials.d.ts.map +1 -0
  130. package/dist/cli/Credentials.js +51 -0
  131. package/dist/cli/Credentials.js.map +1 -0
  132. package/dist/cli/Doctor.d.ts +25 -0
  133. package/dist/cli/Doctor.d.ts.map +1 -0
  134. package/dist/cli/Doctor.js +211 -0
  135. package/dist/cli/Doctor.js.map +1 -0
  136. package/dist/cli/Help.d.ts +3 -0
  137. package/dist/cli/Help.d.ts.map +1 -0
  138. package/dist/cli/Help.js +38 -0
  139. package/dist/cli/Help.js.map +1 -0
  140. package/dist/cli/Init.d.ts +32 -0
  141. package/dist/cli/Init.d.ts.map +1 -0
  142. package/dist/cli/Init.js +163 -0
  143. package/dist/cli/Init.js.map +1 -0
  144. package/dist/cli/Login.d.ts +16 -0
  145. package/dist/cli/Login.d.ts.map +1 -0
  146. package/dist/cli/Login.js +74 -0
  147. package/dist/cli/Login.js.map +1 -0
  148. package/dist/cli/Proxy.d.ts +41 -0
  149. package/dist/cli/Proxy.d.ts.map +1 -0
  150. package/dist/cli/Proxy.js +161 -0
  151. package/dist/cli/Proxy.js.map +1 -0
  152. package/dist/cli/Status.d.ts +7 -0
  153. package/dist/cli/Status.d.ts.map +1 -0
  154. package/dist/cli/Status.js +64 -0
  155. package/dist/cli/Status.js.map +1 -0
  156. package/dist/cli/TestCommand.d.ts +36 -0
  157. package/dist/cli/TestCommand.d.ts.map +1 -0
  158. package/dist/cli/TestCommand.js +173 -0
  159. package/dist/cli/TestCommand.js.map +1 -0
  160. package/dist/config/ConfigKeys.d.ts +10 -0
  161. package/dist/config/ConfigKeys.d.ts.map +1 -0
  162. package/dist/config/ConfigKeys.js +105 -0
  163. package/dist/config/ConfigKeys.js.map +1 -0
  164. package/dist/config/ExecutorConfig.d.ts +254 -0
  165. package/dist/config/ExecutorConfig.d.ts.map +1 -0
  166. package/dist/config/ExecutorConfig.js +637 -0
  167. package/dist/config/ExecutorConfig.js.map +1 -0
  168. package/dist/containment/ContainmentProbe.d.ts +87 -0
  169. package/dist/containment/ContainmentProbe.d.ts.map +1 -0
  170. package/dist/containment/ContainmentProbe.js +103 -0
  171. package/dist/containment/ContainmentProbe.js.map +1 -0
  172. package/dist/credential/CredentialError.d.ts +6 -0
  173. package/dist/credential/CredentialError.d.ts.map +1 -0
  174. package/dist/credential/CredentialError.js +10 -0
  175. package/dist/credential/CredentialError.js.map +1 -0
  176. package/dist/credential/DownstreamCredential.d.ts +38 -0
  177. package/dist/credential/DownstreamCredential.d.ts.map +1 -0
  178. package/dist/credential/DownstreamCredential.js +2 -0
  179. package/dist/credential/DownstreamCredential.js.map +1 -0
  180. package/dist/credential/GrantOf.d.ts +10 -0
  181. package/dist/credential/GrantOf.d.ts.map +1 -0
  182. package/dist/credential/GrantOf.js +16 -0
  183. package/dist/credential/GrantOf.js.map +1 -0
  184. package/dist/credential/PrivateKeyJwtCredential.d.ts +43 -0
  185. package/dist/credential/PrivateKeyJwtCredential.d.ts.map +1 -0
  186. package/dist/credential/PrivateKeyJwtCredential.js +126 -0
  187. package/dist/credential/PrivateKeyJwtCredential.js.map +1 -0
  188. package/dist/credential/SignedRequestCredential.d.ts +112 -0
  189. package/dist/credential/SignedRequestCredential.d.ts.map +1 -0
  190. package/dist/credential/SignedRequestCredential.js +255 -0
  191. package/dist/credential/SignedRequestCredential.js.map +1 -0
  192. package/dist/credential/StaticHeaderCredential.d.ts +16 -0
  193. package/dist/credential/StaticHeaderCredential.d.ts.map +1 -0
  194. package/dist/credential/StaticHeaderCredential.js +21 -0
  195. package/dist/credential/StaticHeaderCredential.js.map +1 -0
  196. package/dist/egress/EgressError.d.ts +13 -0
  197. package/dist/egress/EgressError.d.ts.map +1 -0
  198. package/dist/egress/EgressError.js +16 -0
  199. package/dist/egress/EgressError.js.map +1 -0
  200. package/dist/egress/EgressPolicy.d.ts +55 -0
  201. package/dist/egress/EgressPolicy.d.ts.map +1 -0
  202. package/dist/egress/EgressPolicy.js +137 -0
  203. package/dist/egress/EgressPolicy.js.map +1 -0
  204. package/dist/egress/GlobalFetchLock.d.ts +16 -0
  205. package/dist/egress/GlobalFetchLock.d.ts.map +1 -0
  206. package/dist/egress/GlobalFetchLock.js +34 -0
  207. package/dist/egress/GlobalFetchLock.js.map +1 -0
  208. package/dist/egress/GuardedFetch.d.ts +56 -0
  209. package/dist/egress/GuardedFetch.d.ts.map +1 -0
  210. package/dist/egress/GuardedFetch.js +300 -0
  211. package/dist/egress/GuardedFetch.js.map +1 -0
  212. package/dist/egress/TcpProbe.d.ts +35 -0
  213. package/dist/egress/TcpProbe.d.ts.map +1 -0
  214. package/dist/egress/TcpProbe.js +45 -0
  215. package/dist/egress/TcpProbe.js.map +1 -0
  216. package/dist/gateway/Activation.d.ts +39 -0
  217. package/dist/gateway/Activation.d.ts.map +1 -0
  218. package/dist/gateway/Activation.js +61 -0
  219. package/dist/gateway/Activation.js.map +1 -0
  220. package/dist/gateway/BoundaryTest.d.ts +92 -0
  221. package/dist/gateway/BoundaryTest.d.ts.map +1 -0
  222. package/dist/gateway/BoundaryTest.js +349 -0
  223. package/dist/gateway/BoundaryTest.js.map +1 -0
  224. package/dist/gateway/DemoAuthority.d.ts +41 -0
  225. package/dist/gateway/DemoAuthority.d.ts.map +1 -0
  226. package/dist/gateway/DemoAuthority.js +66 -0
  227. package/dist/gateway/DemoAuthority.js.map +1 -0
  228. package/dist/gateway/ForwardHandler.d.ts +56 -0
  229. package/dist/gateway/ForwardHandler.d.ts.map +1 -0
  230. package/dist/gateway/ForwardHandler.js +111 -0
  231. package/dist/gateway/ForwardHandler.js.map +1 -0
  232. package/dist/gateway/Gateway.d.ts +142 -0
  233. package/dist/gateway/Gateway.d.ts.map +1 -0
  234. package/dist/gateway/Gateway.js +819 -0
  235. package/dist/gateway/Gateway.js.map +1 -0
  236. package/dist/gateway/GatewayConfig.d.ts +237 -0
  237. package/dist/gateway/GatewayConfig.d.ts.map +1 -0
  238. package/dist/gateway/GatewayConfig.js +706 -0
  239. package/dist/gateway/GatewayConfig.js.map +1 -0
  240. package/dist/gateway/GatewayMetrics.d.ts +26 -0
  241. package/dist/gateway/GatewayMetrics.d.ts.map +1 -0
  242. package/dist/gateway/GatewayMetrics.js +28 -0
  243. package/dist/gateway/GatewayMetrics.js.map +1 -0
  244. package/dist/gateway/GatewayReport.d.ts +74 -0
  245. package/dist/gateway/GatewayReport.d.ts.map +1 -0
  246. package/dist/gateway/GatewayReport.js +109 -0
  247. package/dist/gateway/GatewayReport.js.map +1 -0
  248. package/dist/gateway/InterceptedRequest.d.ts +53 -0
  249. package/dist/gateway/InterceptedRequest.d.ts.map +1 -0
  250. package/dist/gateway/InterceptedRequest.js +80 -0
  251. package/dist/gateway/InterceptedRequest.js.map +1 -0
  252. package/dist/gateway/RouteTable.d.ts +28 -0
  253. package/dist/gateway/RouteTable.d.ts.map +1 -0
  254. package/dist/gateway/RouteTable.js +72 -0
  255. package/dist/gateway/RouteTable.js.map +1 -0
  256. package/dist/gateway/Upstream.d.ts +46 -0
  257. package/dist/gateway/Upstream.d.ts.map +1 -0
  258. package/dist/gateway/Upstream.js +158 -0
  259. package/dist/gateway/Upstream.js.map +1 -0
  260. package/dist/handlers/ForwardRequestHandler.d.ts +26 -0
  261. package/dist/handlers/ForwardRequestHandler.d.ts.map +1 -0
  262. package/dist/handlers/ForwardRequestHandler.js +98 -0
  263. package/dist/handlers/ForwardRequestHandler.js.map +1 -0
  264. package/dist/handlers/HandlerRegistration.d.ts +37 -0
  265. package/dist/handlers/HandlerRegistration.d.ts.map +1 -0
  266. package/dist/handlers/HandlerRegistration.js +2 -0
  267. package/dist/handlers/HandlerRegistration.js.map +1 -0
  268. package/dist/handlers/JournaledActionHandler.d.ts +31 -0
  269. package/dist/handlers/JournaledActionHandler.d.ts.map +1 -0
  270. package/dist/handlers/JournaledActionHandler.js +63 -0
  271. package/dist/handlers/JournaledActionHandler.js.map +1 -0
  272. package/dist/http/ExecutorHttpServer.d.ts +33 -0
  273. package/dist/http/ExecutorHttpServer.d.ts.map +1 -0
  274. package/dist/http/ExecutorHttpServer.js +176 -0
  275. package/dist/http/ExecutorHttpServer.js.map +1 -0
  276. package/dist/http/GatewayHttpServer.d.ts +42 -0
  277. package/dist/http/GatewayHttpServer.d.ts.map +1 -0
  278. package/dist/http/GatewayHttpServer.js +195 -0
  279. package/dist/http/GatewayHttpServer.js.map +1 -0
  280. package/dist/http/RecordingTarget.d.ts +18 -0
  281. package/dist/http/RecordingTarget.d.ts.map +1 -0
  282. package/dist/http/RecordingTarget.js +71 -0
  283. package/dist/http/RecordingTarget.js.map +1 -0
  284. package/dist/http/RequestContext.d.ts +17 -0
  285. package/dist/http/RequestContext.d.ts.map +1 -0
  286. package/dist/http/RequestContext.js +19 -0
  287. package/dist/http/RequestContext.js.map +1 -0
  288. package/dist/http/Routes.d.ts +93 -0
  289. package/dist/http/Routes.d.ts.map +1 -0
  290. package/dist/http/Routes.js +46 -0
  291. package/dist/http/Routes.js.map +1 -0
  292. package/dist/http/TlsListener.d.ts +38 -0
  293. package/dist/http/TlsListener.d.ts.map +1 -0
  294. package/dist/http/TlsListener.js +52 -0
  295. package/dist/http/TlsListener.js.map +1 -0
  296. package/dist/identity/Authenticator.d.ts +58 -0
  297. package/dist/identity/Authenticator.d.ts.map +1 -0
  298. package/dist/identity/Authenticator.js +170 -0
  299. package/dist/identity/Authenticator.js.map +1 -0
  300. package/dist/identity/PeerIdentity.d.ts +24 -0
  301. package/dist/identity/PeerIdentity.d.ts.map +1 -0
  302. package/dist/identity/PeerIdentity.js +29 -0
  303. package/dist/identity/PeerIdentity.js.map +1 -0
  304. package/dist/identity/PrincipalRegistry.d.ts +102 -0
  305. package/dist/identity/PrincipalRegistry.d.ts.map +1 -0
  306. package/dist/identity/PrincipalRegistry.js +191 -0
  307. package/dist/identity/PrincipalRegistry.js.map +1 -0
  308. package/dist/identity/PrincipalsFile.d.ts +152 -0
  309. package/dist/identity/PrincipalsFile.d.ts.map +1 -0
  310. package/dist/identity/PrincipalsFile.js +125 -0
  311. package/dist/identity/PrincipalsFile.js.map +1 -0
  312. package/dist/identity/RateLimiter.d.ts +43 -0
  313. package/dist/identity/RateLimiter.d.ts.map +1 -0
  314. package/dist/identity/RateLimiter.js +84 -0
  315. package/dist/identity/RateLimiter.js.map +1 -0
  316. package/dist/identity/SeparationOfDuties.d.ts +11 -0
  317. package/dist/identity/SeparationOfDuties.d.ts.map +1 -0
  318. package/dist/identity/SeparationOfDuties.js +25 -0
  319. package/dist/identity/SeparationOfDuties.js.map +1 -0
  320. package/dist/identity/WorkloadJwtVerifier.d.ts +57 -0
  321. package/dist/identity/WorkloadJwtVerifier.d.ts.map +1 -0
  322. package/dist/identity/WorkloadJwtVerifier.js +145 -0
  323. package/dist/identity/WorkloadJwtVerifier.js.map +1 -0
  324. package/dist/incident/EvidenceExport.d.ts +128 -0
  325. package/dist/incident/EvidenceExport.d.ts.map +1 -0
  326. package/dist/incident/EvidenceExport.js +187 -0
  327. package/dist/incident/EvidenceExport.js.map +1 -0
  328. package/dist/incident/FileProbe.d.ts +22 -0
  329. package/dist/incident/FileProbe.d.ts.map +1 -0
  330. package/dist/incident/FileProbe.js +31 -0
  331. package/dist/incident/FileProbe.js.map +1 -0
  332. package/dist/incident/HaltSwitch.d.ts +95 -0
  333. package/dist/incident/HaltSwitch.d.ts.map +1 -0
  334. package/dist/incident/HaltSwitch.js +171 -0
  335. package/dist/incident/HaltSwitch.js.map +1 -0
  336. package/dist/incident/Metrics.d.ts +71 -0
  337. package/dist/incident/Metrics.d.ts.map +1 -0
  338. package/dist/incident/Metrics.js +146 -0
  339. package/dist/incident/Metrics.js.map +1 -0
  340. package/dist/incident/SecurityEvents.d.ts +182 -0
  341. package/dist/incident/SecurityEvents.d.ts.map +1 -0
  342. package/dist/incident/SecurityEvents.js +167 -0
  343. package/dist/incident/SecurityEvents.js.map +1 -0
  344. package/dist/journal/ExecutionJournal.d.ts +96 -0
  345. package/dist/journal/ExecutionJournal.d.ts.map +1 -0
  346. package/dist/journal/ExecutionJournal.js +100 -0
  347. package/dist/journal/ExecutionJournal.js.map +1 -0
  348. package/dist/journal/FileExecutionJournal.d.ts +38 -0
  349. package/dist/journal/FileExecutionJournal.d.ts.map +1 -0
  350. package/dist/journal/FileExecutionJournal.js +137 -0
  351. package/dist/journal/FileExecutionJournal.js.map +1 -0
  352. package/dist/journal/InMemoryExecutionJournal.d.ts +23 -0
  353. package/dist/journal/InMemoryExecutionJournal.d.ts.map +1 -0
  354. package/dist/journal/InMemoryExecutionJournal.js +47 -0
  355. package/dist/journal/InMemoryExecutionJournal.js.map +1 -0
  356. package/dist/journal/StartupReconciler.d.ts +47 -0
  357. package/dist/journal/StartupReconciler.d.ts.map +1 -0
  358. package/dist/journal/StartupReconciler.js +89 -0
  359. package/dist/journal/StartupReconciler.js.map +1 -0
  360. package/dist/limits/HardLimits.d.ts +63 -0
  361. package/dist/limits/HardLimits.d.ts.map +1 -0
  362. package/dist/limits/HardLimits.js +120 -0
  363. package/dist/limits/HardLimits.js.map +1 -0
  364. package/dist/logging/LineEmitter.d.ts +26 -0
  365. package/dist/logging/LineEmitter.d.ts.map +1 -0
  366. package/dist/logging/LineEmitter.js +36 -0
  367. package/dist/logging/LineEmitter.js.map +1 -0
  368. package/dist/posture/HostPosture.d.ts +60 -0
  369. package/dist/posture/HostPosture.d.ts.map +1 -0
  370. package/dist/posture/HostPosture.js +104 -0
  371. package/dist/posture/HostPosture.js.map +1 -0
  372. package/dist/posture/PostureChecks.d.ts +52 -0
  373. package/dist/posture/PostureChecks.d.ts.map +1 -0
  374. package/dist/posture/PostureChecks.js +172 -0
  375. package/dist/posture/PostureChecks.js.map +1 -0
  376. package/dist/secrets/CompositeSecretStore.d.ts +37 -0
  377. package/dist/secrets/CompositeSecretStore.d.ts.map +1 -0
  378. package/dist/secrets/CompositeSecretStore.js +99 -0
  379. package/dist/secrets/CompositeSecretStore.js.map +1 -0
  380. package/dist/secrets/EnvSecretStore.d.ts +18 -0
  381. package/dist/secrets/EnvSecretStore.d.ts.map +1 -0
  382. package/dist/secrets/EnvSecretStore.js +46 -0
  383. package/dist/secrets/EnvSecretStore.js.map +1 -0
  384. package/dist/secrets/FileSecretStore.d.ts +60 -0
  385. package/dist/secrets/FileSecretStore.d.ts.map +1 -0
  386. package/dist/secrets/FileSecretStore.js +180 -0
  387. package/dist/secrets/FileSecretStore.js.map +1 -0
  388. package/dist/secrets/Redactor.d.ts +32 -0
  389. package/dist/secrets/Redactor.d.ts.map +1 -0
  390. package/dist/secrets/Redactor.js +108 -0
  391. package/dist/secrets/Redactor.js.map +1 -0
  392. package/dist/secrets/SecretHandle.d.ts +34 -0
  393. package/dist/secrets/SecretHandle.d.ts.map +1 -0
  394. package/dist/secrets/SecretHandle.js +71 -0
  395. package/dist/secrets/SecretHandle.js.map +1 -0
  396. package/dist/secrets/SecretStore.d.ts +37 -0
  397. package/dist/secrets/SecretStore.d.ts.map +1 -0
  398. package/dist/secrets/SecretStore.js +12 -0
  399. package/dist/secrets/SecretStore.js.map +1 -0
  400. package/dist/service/AuthorityClients.d.ts +50 -0
  401. package/dist/service/AuthorityClients.d.ts.map +1 -0
  402. package/dist/service/AuthorityClients.js +83 -0
  403. package/dist/service/AuthorityClients.js.map +1 -0
  404. package/dist/service/EscalationResolver.d.ts +97 -0
  405. package/dist/service/EscalationResolver.d.ts.map +1 -0
  406. package/dist/service/EscalationResolver.js +196 -0
  407. package/dist/service/EscalationResolver.js.map +1 -0
  408. package/dist/service/Requests.d.ts +99 -0
  409. package/dist/service/Requests.d.ts.map +1 -0
  410. package/dist/service/Requests.js +42 -0
  411. package/dist/service/Requests.js.map +1 -0
  412. package/dist/service/ServiceError.d.ts +20 -0
  413. package/dist/service/ServiceError.d.ts.map +1 -0
  414. package/dist/service/ServiceError.js +25 -0
  415. package/dist/service/ServiceError.js.map +1 -0
  416. package/dist/service/TrustedExecutorService.d.ts +221 -0
  417. package/dist/service/TrustedExecutorService.d.ts.map +1 -0
  418. package/dist/service/TrustedExecutorService.js +1066 -0
  419. package/dist/service/TrustedExecutorService.js.map +1 -0
  420. package/dist/time/ClockSkewGuard.d.ts +25 -0
  421. package/dist/time/ClockSkewGuard.d.ts.map +1 -0
  422. package/dist/time/ClockSkewGuard.js +35 -0
  423. package/dist/time/ClockSkewGuard.js.map +1 -0
  424. package/dist/time/MonotonicClock.d.ts +35 -0
  425. package/dist/time/MonotonicClock.d.ts.map +1 -0
  426. package/dist/time/MonotonicClock.js +52 -0
  427. package/dist/time/MonotonicClock.js.map +1 -0
  428. package/dist/verify/VerifyAuditChain.d.ts +36 -0
  429. package/dist/verify/VerifyAuditChain.d.ts.map +1 -0
  430. package/dist/verify/VerifyAuditChain.js +109 -0
  431. package/dist/verify/VerifyAuditChain.js.map +1 -0
  432. package/dist/verify/VerifyEvidenceBundle.d.ts +50 -0
  433. package/dist/verify/VerifyEvidenceBundle.d.ts.map +1 -0
  434. package/dist/verify/VerifyEvidenceBundle.js +157 -0
  435. package/dist/verify/VerifyEvidenceBundle.js.map +1 -0
  436. package/package.json +80 -0
@@ -0,0 +1,1066 @@
1
+ import { AuditRecorder, CanonicalIntentHasher, ExecutionIntentSchema, IntentCapture, } from "@decionis/agent-safe-pipeline";
2
+ import { readFileSync } from "node:fs";
3
+ import { EffectEvidenceRegister } from "../adapters/EffectEvidenceRegister.js";
4
+ import { effectBlock } from "../adapters/AdapterActionHandler.js";
5
+ import { bindBankingAction, BindingError } from "../adapters/banking/BankingIntentBinder.js";
6
+ import { BankingAdapter, BankingActionError } from "../adapters/banking/BankingAdapter.js";
7
+ import { isBankingActionName } from "../adapters/banking/BankingAction.js";
8
+ import { HashChain } from "../audit/HashChain.js";
9
+ import { EVIDENCE_STREAM, HashChainedAuditSink } from "../audit/HashChainedAuditSink.js";
10
+ import { HaltSwitch } from "../incident/HaltSwitch.js";
11
+ import { InMemoryExecutionJournal } from "../journal/InMemoryExecutionJournal.js";
12
+ import { StartupReconciler } from "../journal/StartupReconciler.js";
13
+ import { HardLimits } from "../limits/HardLimits.js";
14
+ import { callerPrincipal, JournaledRegistry } from "../handlers/JournaledActionHandler.js";
15
+ import { clockSkewGuard } from "../time/ClockSkewGuard.js";
16
+ import { PrivateKeyJwtCredential } from "../credential/PrivateKeyJwtCredential.js";
17
+ import { SignedRequestCredential } from "../credential/SignedRequestCredential.js";
18
+ import { StaticHeaderCredential } from "../credential/StaticHeaderCredential.js";
19
+ import { EgressPolicy } from "../egress/EgressPolicy.js";
20
+ import { GuardedFetch } from "../egress/GuardedFetch.js";
21
+ import { PrincipalRegistry } from "../identity/PrincipalRegistry.js";
22
+ import { parsePrincipalsFile } from "../identity/PrincipalsFile.js";
23
+ import { assertSeparationOfDuties, separationViolated } from "../identity/SeparationOfDuties.js";
24
+ import { WorkloadJwtVerifier } from "../identity/WorkloadJwtVerifier.js";
25
+ import { executorMetrics } from "../incident/Metrics.js";
26
+ import { SecurityEvents } from "../incident/SecurityEvents.js";
27
+ import { EvidenceError, EvidenceExport, LineWindow, } from "../incident/EvidenceExport.js";
28
+ import { RequestContext } from "../http/RequestContext.js";
29
+ import { AuthorityClients } from "./AuthorityClients.js";
30
+ import { EscalationHandoffSchema, } from "./EscalationResolver.js";
31
+ import { ProposalRequestSchema, ReconciliationRequestSchema, } from "./Requests.js";
32
+ import { HaltRequestSchema, ResumeRequestSchema } from "./Requests.js";
33
+ import { ServiceError } from "./ServiceError.js";
34
+ /**
35
+ * The execution boundary as one process. In `ENFORCEMENT` it asks Decionis,
36
+ * and on an `ALLOW` claims the grant and executes once through the sealed
37
+ * registry; on anything else it answers with the verdict and no grant. An
38
+ * `ESCALATE` is handed back with what the caller needs to resume once a
39
+ * person has answered, in whichever shape the adopter configured. In
40
+ * `SHADOW` it asks what the authority would have decided about an action the
41
+ * caller runs itself, records the observation, and never executes. The grant
42
+ * token, the API keys, the caller token and the downstream credential never
43
+ * appear in a response or an audit line.
44
+ */
45
+ /** This package's own version, for a bundle to name what produced it. */
46
+ const PACKAGE_VERSION = "0.1.0";
47
+ /** The posture as reported, or an empty report when a test injected only a state. */
48
+ function reportOf(posture) {
49
+ const report = posture?.report;
50
+ return report ?? { mode: "ENFORCED", findings: [], failed: [], waived: [] };
51
+ }
52
+ /**
53
+ * What this process was told, minus every secret: addresses, modes, ceilings
54
+ * and thresholds. A digest over it says two replicas were configured the same
55
+ * way without putting the configuration itself in a bundle.
56
+ */
57
+ function nonSecretConfiguration(config) {
58
+ return {
59
+ mode: config.mode,
60
+ escalation: config.escalation.mode,
61
+ posture: config.posture.mode,
62
+ authority: config.authority.baseUrl,
63
+ downstream: {
64
+ url: config.downstream.url,
65
+ system: config.downstream.system,
66
+ operation: config.downstream.operation,
67
+ environment: config.downstream.environment,
68
+ credential_kind: config.downstream.credential.kind,
69
+ },
70
+ banking: {
71
+ adapter: config.banking.adapterId,
72
+ version: config.banking.adapterVersion,
73
+ on_effect_mismatch: config.banking.onEffectMismatch,
74
+ },
75
+ journal: { required: config.evidence.journalRequired, dir: config.evidence.journalDir },
76
+ halt: {
77
+ file: config.halt.file,
78
+ auth_failures: config.halt.authFailures === null
79
+ ? null
80
+ : `${config.halt.authFailures.count}/${config.halt.authFailures.windowSeconds}`,
81
+ egress_refusals: config.halt.egressRefusals === null
82
+ ? null
83
+ : `${config.halt.egressRefusals.count}/${config.halt.egressRefusals.windowSeconds}`,
84
+ },
85
+ limits: config.limits === null
86
+ ? null
87
+ : {
88
+ currencies: [...config.limits.singleMinor.keys()],
89
+ window_seconds: config.limits.windowSeconds,
90
+ },
91
+ max_clock_skew_ms: config.maxClockSkewMs,
92
+ };
93
+ }
94
+ /** An Ed25519 detached JWS over the manifest, from the configured key. */
95
+ async function signBundle(secrets, payload) {
96
+ const { importPKCS8, CompactSign } = await import("jose");
97
+ const pem = secrets.get("EXECUTOR_EVIDENCE_SIGNING_KEY").use((value) => value.toString("utf8"));
98
+ const key = await importPKCS8(pem, "EdDSA");
99
+ return await new CompactSign(payload).setProtectedHeader({ alg: "EdDSA" }).sign(key);
100
+ }
101
+ export class TrustedExecutorService {
102
+ config;
103
+ secrets;
104
+ capture;
105
+ registry;
106
+ registered;
107
+ clients;
108
+ posture;
109
+ egress;
110
+ evidence;
111
+ events;
112
+ chain;
113
+ metrics;
114
+ principals;
115
+ jwt;
116
+ credential;
117
+ audit;
118
+ journal;
119
+ haltSwitch;
120
+ limits;
121
+ unsubscribeMetrics;
122
+ hasher = new CanonicalIntentHasher();
123
+ recovery = null;
124
+ constructor(config, secrets, capture, registry, registered, clients, posture, egress,
125
+ /** Where an incident's evidence is written, when the configuration names a directory. */
126
+ evidence,
127
+ /** The security stream this service writes to; a test drives the halt through it. */
128
+ events, chain, metrics, principals,
129
+ /** The workload token verifier, when the configuration names a JWKS; the door uses it. */
130
+ jwt, credential, audit, journal, haltSwitch, limits, unsubscribeMetrics) {
131
+ this.config = config;
132
+ this.secrets = secrets;
133
+ this.capture = capture;
134
+ this.registry = registry;
135
+ this.registered = registered;
136
+ this.clients = clients;
137
+ this.posture = posture;
138
+ this.egress = egress;
139
+ this.evidence = evidence;
140
+ this.events = events;
141
+ this.chain = chain;
142
+ this.metrics = metrics;
143
+ this.principals = principals;
144
+ this.jwt = jwt;
145
+ this.credential = credential;
146
+ this.audit = audit;
147
+ this.journal = journal;
148
+ this.haltSwitch = haltSwitch;
149
+ this.limits = limits;
150
+ this.unsubscribeMetrics = unsubscribeMetrics;
151
+ }
152
+ /**
153
+ * Wires the boundary. `handlers` is the adopter's seam: it registers what
154
+ * this process can run, and the registry is sealed the moment it returns.
155
+ * Every credential is read from `secrets` at the moment of use.
156
+ */
157
+ static create(config, secrets, handlers, dependencies = {}) {
158
+ const emit = dependencies.emit ??
159
+ ((line) => {
160
+ process.stdout.write(`${line}\n`);
161
+ });
162
+ const events = dependencies.security ??
163
+ new SecurityEvents((line) => {
164
+ process.stderr.write(`${line}\n`);
165
+ });
166
+ const chain = dependencies.chain ?? new HashChain(EVIDENCE_STREAM);
167
+ // A bounded window of each stream, so an operator can take a bundle out
168
+ // of a running process during an incident without first arranging log
169
+ // export. The log pipeline is still the durable store, and the bundle
170
+ // says how many lines it no longer held.
171
+ const auditWindow = new LineWindow(config.evidence.windowLines);
172
+ const securityWindow = new LineWindow(config.evidence.windowLines);
173
+ events.tap((line) => securityWindow.push(line));
174
+ const audit = new AuditRecorder({
175
+ sink: new HashChainedAuditSink(auditWindow.tee(emit), chain),
176
+ failurePolicy: "REQUIRE_BEFORE_EXECUTION",
177
+ });
178
+ // Every connection this process opens, the authority's and the Presence
179
+ // service's included, goes through the one guarded fetch.
180
+ const readFile = dependencies.readFile ?? ((path) => readFileSync(path, "utf8"));
181
+ const egress = new GuardedFetch({
182
+ policy: EgressPolicy.fromConfig(config, readFile),
183
+ events,
184
+ maxResponseBytes: config.egress.maxResponseBytes,
185
+ ...(dependencies.fetch === undefined ? {} : { transport: dependencies.fetch }),
186
+ ...(dependencies.resolve === undefined ? {} : { resolve: dependencies.resolve }),
187
+ });
188
+ const credential = TrustedExecutorService.credential(config, secrets, egress.fetch);
189
+ const metrics = dependencies.metrics ?? executorMetrics();
190
+ const journal = dependencies.journal ?? new InMemoryExecutionJournal();
191
+ const halt = dependencies.halt ??
192
+ new HaltSwitch({
193
+ events,
194
+ haltFile: config.halt.file,
195
+ authFailures: config.halt.authFailures,
196
+ egressRefusals: config.halt.egressRefusals,
197
+ posture: dependencies.posture ?? { degraded: false },
198
+ });
199
+ // Every handler the registration accepts is wrapped, so the durable
200
+ // claim is not something an adopter can forget to write.
201
+ const registry = new JournaledRegistry(() => journal);
202
+ const effects = new EffectEvidenceRegister();
203
+ const registered = handlers({
204
+ registry,
205
+ downstream: config.downstream,
206
+ credential,
207
+ fetch: egress.fetch,
208
+ effects,
209
+ banking: config.banking,
210
+ });
211
+ registry.seal();
212
+ const principals = dependencies.principals ??
213
+ TrustedExecutorService.principals(config, secrets, readFile, registered, config.identity.jwt !== null);
214
+ const jwt = TrustedExecutorService.jwtVerifier(config, readFile, egress.fetch, events, principals.audiences());
215
+ assertSeparationOfDuties(principals.all, config.escalation.mode === "NONE" ? null : config.escalation.approverId);
216
+ if (principals.legacy)
217
+ events.emit({ event: "LEGACY_PRINCIPAL_MODE" });
218
+ else {
219
+ events.emit({
220
+ event: "PRINCIPALS_LOADED",
221
+ principals: principals.size,
222
+ proposers: principals.proposers.length,
223
+ operators: principals.operators.length,
224
+ });
225
+ if (config.production) {
226
+ for (const principal of principals.all) {
227
+ if (principal.credential.kind === "BEARER") {
228
+ events.emit({ event: "BEARER_PRINCIPAL_CONFIGURED", principal: principal.id });
229
+ }
230
+ }
231
+ }
232
+ }
233
+ // The authority's own answers carry the clock this boundary is bound to,
234
+ // so its fetch, and only its fetch, is measured.
235
+ const authorityFetch = clockSkewGuard(egress.fetch, {
236
+ maxSkewMs: config.maxClockSkewMs,
237
+ events,
238
+ observe: (skew) => metrics.clockSkew.set(skew),
239
+ onExceeded: (skew) => halt.halt("CLOCK_SKEW", `${skew}ms from the authority`),
240
+ });
241
+ const clients = new AuthorityClients({
242
+ config,
243
+ secrets,
244
+ registry,
245
+ audit,
246
+ events,
247
+ fetch: authorityFetch,
248
+ effects,
249
+ observer: { id: config.banking.adapterId, version: config.banking.adapterVersion },
250
+ ...(dependencies.presence === undefined ? {} : { presence: dependencies.presence }),
251
+ });
252
+ const posture = dependencies.posture ?? { degraded: false };
253
+ // How many times each credential became current from a changed file.
254
+ // During an incident "was this rotated inside the window?" is one of the
255
+ // first questions, and the count answers it without naming a value.
256
+ const rotations = new Map();
257
+ const unsubscribeRotations = config.secrets.required
258
+ .filter((name) => secrets.has(name))
259
+ .map((name) => secrets.onRotate(name, () => rotations.set(name, (rotations.get(name) ?? 0) + 1)));
260
+ const unsubscribeEvents = events.subscribe((event) => {
261
+ metrics.observe(event);
262
+ if (event.event === "AUTH_FAILED")
263
+ halt.recordAuthFailure();
264
+ if (event.event === "EGRESS_REFUSED")
265
+ halt.recordEgressRefusal();
266
+ if (event.event === "POSTURE_DRIFT")
267
+ halt.halt("POSTURE_DRIFT", `check ${event.check}`);
268
+ });
269
+ const evidence = new EvidenceExport({
270
+ dir: config.evidence.exportDir,
271
+ audit: auditWindow,
272
+ security: securityWindow,
273
+ packageVersion: PACKAGE_VERSION,
274
+ imageDigest: config.evidence.imageDigest,
275
+ // The report the process verified at start, or an empty one when a test
276
+ // injected a posture state rather than a checker.
277
+ posture: () => reportOf(dependencies.posture),
278
+ openAttempts: () => ({}),
279
+ heads: () => ({ [chain.stream]: chain.head, [events.chain.stream]: events.chain.head }),
280
+ configuration: () => nonSecretConfiguration(config),
281
+ secrets: () => config.secrets.required.map((name) => ({
282
+ name,
283
+ present: secrets.has(name),
284
+ rotations: rotations.get(name) ?? 0,
285
+ })),
286
+ ...(secrets.has("EXECUTOR_EVIDENCE_SIGNING_KEY")
287
+ ? { sign: async (payload) => await signBundle(secrets, payload) }
288
+ : {}),
289
+ ...(dependencies.clock === undefined
290
+ ? {}
291
+ : { clock: () => new Date(dependencies.clock()) }),
292
+ });
293
+ return new TrustedExecutorService(config, secrets, new IntentCapture({ ttlSeconds: config.intentTtlSeconds }), registry, registered, clients, posture, egress, evidence, events, chain, metrics, principals, jwt, credential, audit, journal, halt, config.limits === null
294
+ ? null
295
+ : new HardLimits(config.limits, dependencies.clock ?? (() => Date.now())), () => {
296
+ for (const stop of unsubscribeRotations)
297
+ stop();
298
+ unsubscribeEvents();
299
+ });
300
+ }
301
+ /** The credential the configuration's kind names, over the secret store and the guarded fetch. */
302
+ static credential(config, secrets, fetchImpl) {
303
+ const kind = config.downstream.credential;
304
+ switch (kind.kind) {
305
+ case "STATIC_HEADER":
306
+ return new StaticHeaderCredential(kind.header, () => secrets.get("DOWNSTREAM_CREDENTIAL"));
307
+ case "PRIVATE_KEY_JWT":
308
+ return new PrivateKeyJwtCredential({ ...kind, timeoutMs: config.downstream.timeoutMs }, () => secrets.get("DOWNSTREAM_PRIVATE_KEY"), fetchImpl);
309
+ case "SIGNED_REQUEST":
310
+ return new SignedRequestCredential(kind, () => secrets.get("DOWNSTREAM_SIGNING_KEY"));
311
+ }
312
+ }
313
+ static jwtVerifier(config, readFile, fetchImpl, events, named) {
314
+ const jwt = config.identity.jwt;
315
+ if (jwt === null)
316
+ return null;
317
+ let text;
318
+ try {
319
+ text = readFile(jwt.jwksFile);
320
+ }
321
+ catch {
322
+ throw new Error("JWKS_UNAVAILABLE: EXECUTOR_JWKS_FILE");
323
+ }
324
+ return new WorkloadJwtVerifier({
325
+ audiences: [jwt.audience, ...named],
326
+ keys: WorkloadJwtVerifier.parseJwks(text),
327
+ clockToleranceSeconds: jwt.clockToleranceSeconds,
328
+ ...(jwt.jwksUrl === null
329
+ ? {}
330
+ : {
331
+ refresh: {
332
+ url: jwt.jwksUrl,
333
+ fetch: fetchImpl,
334
+ intervalSeconds: jwt.refreshSeconds,
335
+ events,
336
+ },
337
+ }),
338
+ });
339
+ }
340
+ /** The principals file, or the legacy caller; either way checked against what this process runs. */
341
+ static principals(config, secrets, readFile, registered, jwtConfigured) {
342
+ const legacy = config.identity.legacy;
343
+ if (config.identity.principalsFile === null && legacy !== null) {
344
+ return PrincipalRegistry.legacy({
345
+ tenantId: legacy.tenantId,
346
+ actor: legacy.actor,
347
+ registeredActions: registered,
348
+ callerToken: () => secrets.get("EXECUTOR_CALLER_TOKEN").digestBytes(),
349
+ });
350
+ }
351
+ let text;
352
+ try {
353
+ text = readFile(config.identity.principalsFile ?? "");
354
+ }
355
+ catch {
356
+ throw new Error("PRINCIPALS_UNREADABLE: EXECUTOR_PRINCIPALS_FILE");
357
+ }
358
+ return PrincipalRegistry.fromEntries(parsePrincipalsFile(text), {
359
+ registeredActions: registered,
360
+ jwtConfigured,
361
+ mutualTls: config.listener.tls?.clientCaFile != null,
362
+ });
363
+ }
364
+ get mode() {
365
+ return this.config.mode;
366
+ }
367
+ get escalationMode() {
368
+ return this.config.escalation.mode;
369
+ }
370
+ /** The actions this process can run, for `/ready`. */
371
+ get actions() {
372
+ return this.registered.filter((action) => this.registry.has(action));
373
+ }
374
+ /** Stops following credential rotation and closes every outbound connection; the service answers nothing new after this. */
375
+ close() {
376
+ this.clients.close();
377
+ this.egress.close();
378
+ this.jwt?.stop();
379
+ if (this.credential instanceof PrivateKeyJwtCredential)
380
+ this.credential.close();
381
+ this.unsubscribeMetrics();
382
+ }
383
+ /** Identifiers, counts and heads for an operator; never a value. */
384
+ status(caller) {
385
+ const operator = this.operator(caller, "status");
386
+ this.events.emit({ event: "OPERATOR_ACTION", principal: operator.id, action: "status" });
387
+ return {
388
+ status: "ready",
389
+ mode: this.config.mode,
390
+ escalation: this.config.escalation.mode,
391
+ actions: this.actions,
392
+ posture: { degraded: this.posture.degraded },
393
+ principals: {
394
+ mode: this.principals.legacy ? "LEGACY" : "PRINCIPALS",
395
+ count: this.principals.size,
396
+ },
397
+ evidence: this.chain.head,
398
+ secrets: [...this.config.secrets.required],
399
+ halt: this.haltSwitch.current,
400
+ attempts: {
401
+ open: this.recovery?.attempts.length ?? 0,
402
+ unknown: this.recovery?.unknown ?? 0,
403
+ },
404
+ limits: this.limits === null
405
+ ? null
406
+ : {
407
+ currencies: [...this.limits.settings.singleMinor.keys()],
408
+ windowSeconds: this.limits.settings.windowCount === null &&
409
+ this.limits.settings.windowSumMinor === null
410
+ ? null
411
+ : this.limits.settings.windowSeconds,
412
+ },
413
+ };
414
+ }
415
+ /**
416
+ * What the last process left open, resolved before this one takes a
417
+ * request. Read-only: the provider is asked what it did, never told to do
418
+ * it again.
419
+ */
420
+ async recover() {
421
+ const report = await new StartupReconciler({
422
+ journal: this.journal,
423
+ registry: this.registry,
424
+ events: this.events,
425
+ }).recover();
426
+ this.recovery = report;
427
+ this.metrics.openAttempts.set(report.unknown, { state: "UNKNOWN" });
428
+ return report;
429
+ }
430
+ /**
431
+ * Readiness, which is not liveness: a halted executor is alive and
432
+ * deliberately not ready, and so is one that still does not know how an
433
+ * attempt ended when the deployment asked to wait for that.
434
+ */
435
+ readiness() {
436
+ const halt = this.haltSwitch.current;
437
+ const unknown = this.recovery?.unknown ?? 0;
438
+ const waiting = this.config.evidence.readyRequiresNoUnknownAttempts && unknown > 0;
439
+ return {
440
+ ready: !halt.halted && !waiting,
441
+ body: {
442
+ status: halt.halted ? "halted" : waiting ? "recovering" : "ready",
443
+ mode: this.config.mode,
444
+ escalation: this.config.escalation.mode,
445
+ actions: this.actions,
446
+ open_attempts: unknown,
447
+ ...(halt.halted ? { halt: { trigger: halt.trigger, since: halt.since } } : {}),
448
+ },
449
+ };
450
+ }
451
+ /** Stops the executor taking new work, on an operator's word and with a reason. */
452
+ halt(input, caller) {
453
+ const operator = this.operator(caller, "halt");
454
+ const parsed = HaltRequestSchema.safeParse(input);
455
+ if (!parsed.success)
456
+ throw new ServiceError(400, "REQUEST_INVALID");
457
+ this.events.emit({ event: "OPERATOR_ACTION", principal: operator.id, action: "halt" });
458
+ return this.haltSwitch.halt("OPERATOR", parsed.data.reason);
459
+ }
460
+ /** Lets work through again; refused while the cause of the halt still stands. */
461
+ resumeWork(input, caller) {
462
+ const operator = this.operator(caller, "resume");
463
+ const parsed = ResumeRequestSchema.safeParse(input);
464
+ if (!parsed.success)
465
+ throw new ServiceError(400, "REQUEST_INVALID");
466
+ this.events.emit({ event: "OPERATOR_ACTION", principal: operator.id, action: "resume" });
467
+ const resumed = this.haltSwitch.resume(parsed.data.reason);
468
+ if (!resumed.resumed)
469
+ throw new ServiceError(409, resumed.code ?? "NOT_HALTED");
470
+ return this.haltSwitch.current;
471
+ }
472
+ /** The attempts this process does not know the outcome of: identifiers and states only. */
473
+ openAttempts(caller) {
474
+ const operator = this.operator(caller, "status");
475
+ this.events.emit({ event: "OPERATOR_ACTION", principal: operator.id, action: "status" });
476
+ return { attempts: this.recovery?.attempts ?? [], unknown: this.recovery?.unknown ?? 0 };
477
+ }
478
+ /** Re-reads every secret file now, on an operator's word; the report names files, never values. */
479
+ async reloadSecrets(caller) {
480
+ const operator = this.operator(caller, "secrets.reload");
481
+ this.events.emit({
482
+ event: "OPERATOR_ACTION",
483
+ principal: operator.id,
484
+ action: "secrets.reload",
485
+ });
486
+ return await this.secrets.reload("OPERATOR");
487
+ }
488
+ metricsText(caller) {
489
+ const operator = this.operator(caller, "metrics");
490
+ this.events.emit({ event: "OPERATOR_ACTION", principal: operator.id, action: "metrics" });
491
+ return this.metrics.registry.render();
492
+ }
493
+ async propose(input, caller) {
494
+ const proposer = this.proposer(caller);
495
+ const parsed = ProposalRequestSchema.safeParse(input);
496
+ if (!parsed.success)
497
+ throw new ServiceError(400, "REQUEST_INVALID");
498
+ const request = parsed.data;
499
+ // An action this process cannot run is refused before any authority is
500
+ // asked: no dossier, no grant, for something that could never execute;
501
+ // then an action this principal may not propose, before it is captured.
502
+ if (!this.registry.has(request.proposal.action)) {
503
+ throw new ServiceError(422, "ACTION_NOT_REGISTERED");
504
+ }
505
+ if (!proposer.allowedActions.has(request.proposal.action)) {
506
+ throw new ServiceError(403, "ACTION_NOT_PERMITTED_FOR_PRINCIPAL");
507
+ }
508
+ if (separationViolated(proposer, this.config.escalation.mode === "NONE" ? null : this.config.escalation.approverId, this.principals.operators)) {
509
+ this.events.emit({ event: "SEPARATION_OF_DUTIES_VIOLATED", principal: proposer.id });
510
+ throw new ServiceError(422, "SEPARATION_OF_DUTIES_VIOLATED");
511
+ }
512
+ const captured = this.captureIntent(request, proposer);
513
+ // Every line this proposal causes names the proposer, whichever
514
+ // transport asked; the door's own scope, when there is one, agrees.
515
+ return await RequestContext.run({ principal: proposer.id }, async () => {
516
+ if (this.config.mode === "SHADOW") {
517
+ const observed = await this.observe(captured);
518
+ this.metrics.proposals.inc({ verdict: observed.verdict ?? "NONE" });
519
+ return observed;
520
+ }
521
+ // A halt and a ceiling are refusals this host makes on its own. Both
522
+ // are recorded as evidence and both happen before the authority is
523
+ // asked, so a refusal costs no dossier and no grant.
524
+ try {
525
+ this.assertNotHalted(captured);
526
+ this.assertWithinLimits(captured, "CHECK");
527
+ }
528
+ catch (error) {
529
+ if (error instanceof ServiceError)
530
+ await this.recordRefusal(captured, error.code);
531
+ throw error;
532
+ }
533
+ const answer = await this.enforceAfterPosture(captured);
534
+ this.metrics.proposals.inc({ verdict: answer.verdict ?? "NONE" });
535
+ return answer;
536
+ });
537
+ }
538
+ async enforceAfterPosture(captured) {
539
+ this.assertPosture();
540
+ return await this.enforce(captured);
541
+ }
542
+ /** The stop, checked after the intent is captured and before any authority is asked. */
543
+ assertNotHalted(captured) {
544
+ const halt = this.haltSwitch.current;
545
+ if (!halt.halted)
546
+ return;
547
+ throw new ServiceError(503, "EXECUTOR_HALTED", {
548
+ mode: this.config.mode,
549
+ intent_id: captured.intent.intentId,
550
+ intent_hash: captured.intentHash,
551
+ verdict: "BLOCK",
552
+ decision_id: null,
553
+ dossier_id: null,
554
+ reason_codes: ["EXECUTOR_HALTED"],
555
+ fail_closed: true,
556
+ outcome: "BLOCKED",
557
+ executed: false,
558
+ authorization: null,
559
+ finalization: null,
560
+ result: null,
561
+ effect: null,
562
+ recovery: null,
563
+ escalation: null,
564
+ }, 30);
565
+ }
566
+ /** The refusal itself is evidence: the same shape the executor uses for a blocked run. */
567
+ async recordRefusal(captured, reason) {
568
+ await this.audit.record({
569
+ eventType: "EXECUTION_BLOCKED",
570
+ captured,
571
+ reasonCodes: [reason],
572
+ });
573
+ }
574
+ /** The host's own ceilings, before the authority is asked and again before the run. */
575
+ assertWithinLimits(captured, stage) {
576
+ if (this.limits === null)
577
+ return;
578
+ const parameters = captured.intent.parameters;
579
+ const decision = stage === "CHECK" ? this.limits.check(parameters) : this.limits.commit(parameters);
580
+ if (decision.allowed)
581
+ return;
582
+ const value = HardLimits.monetaryValue(parameters);
583
+ this.events.emit({
584
+ event: "HARD_LIMIT_REFUSED",
585
+ code: decision.code,
586
+ currency: value === null || value === "INVALID" ? null : value.currency,
587
+ });
588
+ throw new ServiceError(422, decision.code);
589
+ }
590
+ async reconcile(input, caller) {
591
+ const proposer = this.proposer(caller);
592
+ const parsed = ReconciliationRequestSchema.safeParse(input);
593
+ if (!parsed.success)
594
+ throw new ServiceError(400, "REQUEST_INVALID");
595
+ // The caller presents the intent it was given; the hash is recomputed
596
+ // here, so a changed intent no longer matches its recovery reference,
597
+ // and the intent must be this principal's own.
598
+ const captured = this.presented(parsed.data.intent);
599
+ this.assertOwn(captured, proposer);
600
+ const outcome = await RequestContext.run({ principal: proposer.id }, () => this.clients.current().executor.reconcile(captured, parsed.data.reference));
601
+ // A resolved attempt is closed in the journal, so the next start does not
602
+ // ask the provider about it again.
603
+ if (outcome.outcome !== "UNKNOWN_AFTER_DISPATCH") {
604
+ try {
605
+ await this.journal.append({
606
+ record: "RECONCILED",
607
+ at: new Date().toISOString(),
608
+ intent_id: captured.intent.intentId,
609
+ intent_hash: captured.intentHash,
610
+ status: outcome.outcome,
611
+ source: "CALLER",
612
+ });
613
+ }
614
+ catch {
615
+ this.events.emit({ event: "JOURNAL_WRITE_FAILED", record: "RECONCILED" });
616
+ }
617
+ }
618
+ const effect = this.effect(captured, outcome.result);
619
+ return {
620
+ intent_id: captured.intent.intentId,
621
+ intent_hash: captured.intentHash,
622
+ outcome: outcome.outcome,
623
+ executed: outcome.executed,
624
+ recovered: "recovered" in outcome ? outcome.recovered : false,
625
+ reason_codes: [
626
+ ...("reason" in outcome ? [outcome.reason] : []),
627
+ ...TrustedExecutorService.effectReasons(effect),
628
+ ],
629
+ authorization: TrustedExecutorService.binding(outcome.authorization),
630
+ result: outcome.result,
631
+ effect,
632
+ };
633
+ }
634
+ /**
635
+ * Resumes an open escalation. One bounded lookup: if the person has
636
+ * answered, the authority evaluates the exact intent again and an `ALLOW`
637
+ * executes once; if not, the state comes back to be presented later. An
638
+ * intent past its lifetime is refused before anything is asked.
639
+ */
640
+ async resume(input, caller) {
641
+ const proposer = this.proposer(caller);
642
+ const parsed = EscalationHandoffSchema.safeParse(input);
643
+ if (!parsed.success)
644
+ throw new ServiceError(400, "REQUEST_INVALID");
645
+ if (this.config.mode === "SHADOW" || this.config.escalation.mode === "NONE") {
646
+ throw new ServiceError(409, "ESCALATION_NOT_CONFIGURED");
647
+ }
648
+ const captured = this.presented(parsed.data.intent);
649
+ this.assertOwn(captured, proposer);
650
+ if (Date.parse(captured.intent.expiresAt) <= Date.now()) {
651
+ throw new ServiceError(409, "INTENT_EXPIRED");
652
+ }
653
+ if (!this.registry.has(captured.intent.action)) {
654
+ throw new ServiceError(422, "ACTION_NOT_REGISTERED");
655
+ }
656
+ this.assertPosture();
657
+ return await RequestContext.run({ principal: proposer.id }, async () => {
658
+ try {
659
+ this.assertNotHalted(captured);
660
+ }
661
+ catch (error) {
662
+ if (error instanceof ServiceError)
663
+ await this.recordRefusal(captured, error.code);
664
+ throw error;
665
+ }
666
+ const { escalation, executor } = this.clients.current();
667
+ const resolution = await escalation.resume(captured, parsed.data);
668
+ if (resolution.kind === "DECISION") {
669
+ if (resolution.decision.verdict === "ALLOW" && !resolution.decision.failClosed) {
670
+ this.assertWithinLimits(captured, "COMMIT");
671
+ await this.openAttempt(captured, resolution.decision);
672
+ }
673
+ const outcome = await executor.run(captured, resolution.decision);
674
+ await this.closeAttempt(captured, resolution.decision, outcome);
675
+ this.metrics.executions.inc({ outcome: outcome.outcome });
676
+ return this.response(captured, resolution.decision, outcome, null);
677
+ }
678
+ if (resolution.kind === "PENDING") {
679
+ return this.held(captured, "ESCALATE", resolution.reasonCodes, false, {
680
+ ...resolution.handoff,
681
+ intent: captured.intent,
682
+ });
683
+ }
684
+ return this.held(captured, "BLOCK", resolution.reasonCodes, resolution.failClosed, null);
685
+ });
686
+ }
687
+ /**
688
+ * The attempt, on disk, before the executor may run it. A journal that
689
+ * cannot take the record refuses the proposal rather than executing
690
+ * something no one could reconcile afterwards; with
691
+ * `EXECUTOR_JOURNAL_REQUIRED=false`, outside production, the refusal is
692
+ * downgraded to an event so a developer can run without a volume.
693
+ */
694
+ async openAttempt(captured, decision) {
695
+ try {
696
+ await this.journal.append({
697
+ record: "ATTEMPT_OPENED",
698
+ at: new Date().toISOString(),
699
+ intent_id: captured.intent.intentId,
700
+ intent_hash: captured.intentHash,
701
+ idempotency_key: captured.intent.idempotencyKey,
702
+ decision_id: decision.decisionId ?? "",
703
+ dossier_id: decision.dossierId ?? "",
704
+ caller_principal: callerPrincipal(),
705
+ intent: captured.intent,
706
+ });
707
+ }
708
+ catch {
709
+ this.events.emit({ event: "JOURNAL_WRITE_FAILED", record: "ATTEMPT_OPENED" });
710
+ if (this.config.evidence.journalRequired) {
711
+ throw new ServiceError(503, "JOURNAL_UNAVAILABLE");
712
+ }
713
+ }
714
+ }
715
+ /**
716
+ * How the attempt ended, so the next start does not have to ask the
717
+ * provider. An outcome that is unknown is exactly what must not be closed:
718
+ * the attempt stays open, and the next start, or a caller's own
719
+ * reconciliation, resolves it by reading the provider.
720
+ */
721
+ async closeAttempt(captured, decision, outcome) {
722
+ if (decision.verdict !== "ALLOW" || decision.failClosed)
723
+ return;
724
+ if (outcome.outcome === "UNKNOWN_AFTER_DISPATCH")
725
+ return;
726
+ try {
727
+ await this.journal.append({
728
+ record: "ATTEMPT_CLOSED",
729
+ at: new Date().toISOString(),
730
+ intent_id: captured.intent.intentId,
731
+ intent_hash: captured.intentHash,
732
+ outcome: outcome.outcome,
733
+ executed: outcome.executed,
734
+ finalization: "finalization" in outcome ? outcome.finalization : null,
735
+ });
736
+ }
737
+ catch {
738
+ this.events.emit({ event: "JOURNAL_WRITE_FAILED", record: "ATTEMPT_CLOSED" });
739
+ }
740
+ }
741
+ /** A standing posture drift refuses new enforcement work; nothing that has started is touched. */
742
+ assertPosture() {
743
+ if (this.posture.degraded)
744
+ throw new ServiceError(503, "POSTURE_DEGRADED");
745
+ }
746
+ /** The proposer a call is made as: the caller the door authenticated, or the legacy caller when the service is used directly. */
747
+ proposer(caller) {
748
+ const principal = caller ?? (this.principals.legacy ? this.principals.proposers[0] : undefined);
749
+ if (principal === undefined || principal.role !== "PROPOSER") {
750
+ throw new ServiceError(403, "ROLE_FORBIDDEN");
751
+ }
752
+ if (principal.tenantId === null || principal.actor === null) {
753
+ throw new ServiceError(403, "ROLE_FORBIDDEN");
754
+ }
755
+ return principal;
756
+ }
757
+ operator(caller, scope) {
758
+ if (caller === undefined || caller.role !== "OPERATOR")
759
+ throw new ServiceError(403, "ROLE_FORBIDDEN");
760
+ if (!caller.scopes.has(scope))
761
+ throw new ServiceError(403, "SCOPE_FORBIDDEN");
762
+ return caller;
763
+ }
764
+ /** An intent presented back must be the caller's own: same principal, tenant, and actor. */
765
+ assertOwn(captured, proposer) {
766
+ const intent = captured.intent;
767
+ const own = intent.context["caller_principal"] === proposer.id &&
768
+ intent.tenantId === proposer.tenantId &&
769
+ intent.actor.id === proposer.actor.id &&
770
+ intent.actor.type === proposer.actor.type;
771
+ if (!own)
772
+ throw new ServiceError(403, "INTENT_PRINCIPAL_MISMATCH");
773
+ }
774
+ captureIntent(request, proposer) {
775
+ // A BEAP action carries its own canonical form in the parameters, so the
776
+ // transport's name and target are derived from it rather than trusted,
777
+ // and the digests the authority binds its grant to are computed here
778
+ // from the action itself. The proposal schema already refuses a
779
+ // caller-supplied context, so none of this can be presented from outside.
780
+ const bound = isBankingActionName(request.proposal.action)
781
+ ? this.bindBanking(request, proposer)
782
+ : null;
783
+ const trusted = {
784
+ tenantId: proposer.tenantId,
785
+ actor: proposer.actor,
786
+ downstreamTarget: {
787
+ system: this.config.downstream.system,
788
+ operation: this.config.downstream.operation,
789
+ environment: this.config.downstream.environment,
790
+ },
791
+ context: { caller_principal: proposer.id, ...(bound === null ? {} : bound.context) },
792
+ idempotencyKey: request.idempotency_key,
793
+ ...(request.correlation_id === undefined ? {} : { correlationId: request.correlation_id }),
794
+ ...(bound === null ? {} : { expectedEffectDigest: bound.expectedEffectDigest }),
795
+ };
796
+ const parameters = request.proposal.parameters ?? {};
797
+ try {
798
+ return this.capture.capture({ action: request.proposal.action, target: request.proposal.target, parameters }, trusted);
799
+ }
800
+ catch {
801
+ throw new ServiceError(400, "PROPOSAL_INVALID");
802
+ }
803
+ }
804
+ /**
805
+ * The banking binder. Every disagreement between what the caller said over
806
+ * the transport and what the canonical action says is a refusal before the
807
+ * authority is asked, so a mismatch costs no dossier and no grant.
808
+ */
809
+ bindBanking(request, proposer) {
810
+ try {
811
+ const bound = bindBankingAction({
812
+ action: request.proposal.action,
813
+ target: request.proposal.target,
814
+ parameters: request.proposal.parameters ?? {},
815
+ idempotencyKey: request.idempotency_key,
816
+ downstream: this.config.downstream,
817
+ actor: proposer.actor,
818
+ }, (action) => this.bankingDigests(action));
819
+ return { context: bound.context, expectedEffectDigest: bound.expectedEffectDigest };
820
+ }
821
+ catch (error) {
822
+ if (error instanceof BindingError)
823
+ throw new ServiceError(422, error.code);
824
+ if (error instanceof BankingActionError)
825
+ throw new ServiceError(422, error.code);
826
+ throw new ServiceError(422, "BANKING_ACTION_INVALID");
827
+ }
828
+ }
829
+ /**
830
+ * The two digests a banking intent is bound to, taken from the profile's
831
+ * own arithmetic. This reaches nothing: `prepare` is pure, which is why
832
+ * the transport it is handed refuses to be used.
833
+ */
834
+ bankingDigests(action) {
835
+ const prepared = new BankingAdapter({
836
+ id: this.config.banking.adapterId,
837
+ version: this.config.banking.adapterVersion,
838
+ transport: {
839
+ execute: () => Promise.reject(new BankingActionError("BANKING_PREPARE_ONLY")),
840
+ reconcile: () => Promise.reject(new BankingActionError("BANKING_PREPARE_ONLY")),
841
+ },
842
+ }).prepare(action);
843
+ return {
844
+ intentDigest: prepared.intentDigest,
845
+ expectedEffectDigest: prepared.expectedEffectDigest,
846
+ };
847
+ }
848
+ /**
849
+ * What the adapter observed, for the response and for the stream. An
850
+ * observation that does not match what was authorised is the institution's
851
+ * exception: it is named in the evidence, counted, and by default it stops
852
+ * the executor, because the next proposal would otherwise be made against
853
+ * a state nobody has reconciled.
854
+ */
855
+ effect(captured, result) {
856
+ const block = effectBlock(result);
857
+ if (block === null)
858
+ return null;
859
+ const comparison = block["comparison"];
860
+ const fields = Array.isArray(block["mismatched_fields"])
861
+ ? block["mismatched_fields"].filter((field) => typeof field === "string")
862
+ : [];
863
+ this.events.emit({
864
+ event: "EFFECT_OBSERVED",
865
+ intent_id: captured.intent.intentId,
866
+ comparison: comparison === "MATCH" || comparison === "MISMATCH" ? comparison : "PENDING",
867
+ confirmation: typeof block["confirmation"] === "string" ? block["confirmation"] : "UNKNOWN",
868
+ });
869
+ if (comparison === "PENDING") {
870
+ // Committed, and nothing has read the effect back. Worth alerting on:
871
+ // a provider that is always pending is a read-back that is not wired.
872
+ this.events.emit({
873
+ event: "EFFECT_PENDING_CONFIRMATION",
874
+ intent_id: captured.intent.intentId,
875
+ method: typeof block["observation_method"] === "string" ? block["observation_method"] : "UNKNOWN",
876
+ });
877
+ }
878
+ if (block["outcome"] === "FAILED") {
879
+ this.events.emit({
880
+ event: "PROVIDER_REFUSED",
881
+ intent_id: captured.intent.intentId,
882
+ code: TrustedExecutorService.effectReasons(block)[0] ?? "PROVIDER_REFUSED",
883
+ });
884
+ }
885
+ if (comparison !== "MISMATCH")
886
+ return block;
887
+ this.events.emit({
888
+ event: "EFFECT_MISMATCH",
889
+ intent_id: captured.intent.intentId,
890
+ fields: fields.slice(0, 16),
891
+ });
892
+ if (this.config.banking.onEffectMismatch === "HALT") {
893
+ this.haltSwitch.halt("EFFECT_MISMATCH", `${fields.length} field(s) differ from the grant`);
894
+ }
895
+ return block;
896
+ }
897
+ /** The reason codes an effect block contributes to the response. */
898
+ static effectReasons(effect) {
899
+ const codes = effect?.["reason_codes"];
900
+ if (!Array.isArray(codes))
901
+ return [];
902
+ return codes.filter((code) => typeof code === "string");
903
+ }
904
+ /** An intent the caller presents back, re-hashed rather than trusted. */
905
+ presented(intent) {
906
+ try {
907
+ return this.hasher.capture(ExecutionIntentSchema.parse(intent));
908
+ }
909
+ catch {
910
+ throw new ServiceError(400, "INTENT_INVALID");
911
+ }
912
+ }
913
+ async observe(captured) {
914
+ const shadow = this.clients.current().shadow;
915
+ if (shadow === null)
916
+ throw new ServiceError(500, "MODE_MISMATCH");
917
+ // The production action, if any, runs in the caller. What this process
918
+ // contributes in shadow is the observation and its evidence, never an
919
+ // execution and never a grant.
920
+ const comparison = await shadow.compare(captured, () => null);
921
+ const observation = comparison.observation;
922
+ return {
923
+ mode: "SHADOW",
924
+ intent_id: captured.intent.intentId,
925
+ intent_hash: captured.intentHash,
926
+ verdict: observation.verdict,
927
+ decision_id: observation.decisionId,
928
+ dossier_id: observation.dossierId,
929
+ reason_codes: observation.reasonCodes,
930
+ fail_closed: observation.status !== "OBSERVED",
931
+ outcome: observation.status,
932
+ executed: false,
933
+ authorization: null,
934
+ finalization: null,
935
+ result: null,
936
+ effect: null,
937
+ recovery: null,
938
+ escalation: null,
939
+ };
940
+ }
941
+ async enforce(captured) {
942
+ const { escalation, executor } = this.clients.current();
943
+ const decision = await escalation.evaluate(captured);
944
+ // Every decision goes through the executor, an ESCALATE or BLOCK included,
945
+ // so the audit stream carries the refusal as well as the execution.
946
+ if (decision.verdict === "ALLOW" && !decision.failClosed) {
947
+ this.assertWithinLimits(captured, "COMMIT");
948
+ await this.openAttempt(captured, decision);
949
+ }
950
+ const outcome = await executor.run(captured, decision);
951
+ await this.closeAttempt(captured, decision, outcome);
952
+ this.metrics.executions.inc({ outcome: outcome.outcome });
953
+ let handoff = null;
954
+ let unavailable = false;
955
+ if (decision.verdict === "ESCALATE" && !decision.failClosed) {
956
+ const state = await escalation.handoff(captured, decision);
957
+ if (state !== null)
958
+ handoff = { ...state, intent: captured.intent };
959
+ else if (this.config.escalation.mode !== "NONE")
960
+ unavailable = true;
961
+ }
962
+ return this.response(captured, decision, outcome, handoff, unavailable ? ["ESCALATION_HANDOFF_UNAVAILABLE"] : []);
963
+ }
964
+ response(captured, decision, outcome, handoff, extraReasonCodes = []) {
965
+ const effect = this.effect(captured, outcome.result);
966
+ // A finalization the authority did not take is the authority's lease
967
+ // recovery's problem now, and an operator should know it happened.
968
+ if ("finalization" in outcome && outcome.finalization === "PENDING") {
969
+ this.events.emit({
970
+ event: "FINALIZATION_PENDING",
971
+ intent_id: captured.intent.intentId,
972
+ outcome: outcome.outcome,
973
+ });
974
+ }
975
+ if ("finalization" in outcome && outcome.finalization !== null) {
976
+ this.metrics.finalizations.inc({ status: outcome.finalization });
977
+ }
978
+ return {
979
+ mode: "ENFORCEMENT",
980
+ intent_id: captured.intent.intentId,
981
+ intent_hash: captured.intentHash,
982
+ verdict: decision.verdict,
983
+ decision_id: decision.failClosed ? null : decision.decisionId,
984
+ dossier_id: decision.dossierId,
985
+ reason_codes: [
986
+ ...decision.reasonCodes,
987
+ ...("reason" in outcome && outcome.reason !== "DECISION_NOT_ALLOW" ? [outcome.reason] : []),
988
+ ...TrustedExecutorService.effectReasons(effect),
989
+ ...extraReasonCodes,
990
+ ],
991
+ fail_closed: decision.failClosed,
992
+ outcome: handoff === null ? outcome.outcome : "ESCALATE_PENDING",
993
+ executed: outcome.executed,
994
+ authorization: TrustedExecutorService.binding(outcome.authorization),
995
+ finalization: "finalization" in outcome ? outcome.finalization : null,
996
+ result: outcome.result,
997
+ effect,
998
+ recovery: outcome.outcome === "UNKNOWN_AFTER_DISPATCH"
999
+ ? { intent: captured.intent, reference: outcome.recovery }
1000
+ : null,
1001
+ escalation: handoff,
1002
+ };
1003
+ }
1004
+ /** A resumption that produced no new decision: still held, or refused. */
1005
+ held(captured, verdict, reasonCodes, failClosed, handoff) {
1006
+ return {
1007
+ mode: "ENFORCEMENT",
1008
+ intent_id: captured.intent.intentId,
1009
+ intent_hash: captured.intentHash,
1010
+ verdict,
1011
+ decision_id: null,
1012
+ dossier_id: null,
1013
+ reason_codes: reasonCodes,
1014
+ fail_closed: failClosed,
1015
+ outcome: handoff === null ? "BLOCKED" : "ESCALATE_PENDING",
1016
+ executed: false,
1017
+ authorization: null,
1018
+ finalization: null,
1019
+ result: null,
1020
+ effect: null,
1021
+ recovery: null,
1022
+ escalation: handoff,
1023
+ };
1024
+ }
1025
+ /**
1026
+ * The bundle: what this process can say about an incident, written where an
1027
+ * operator can pick it up. Only an operator holding the `evidence` scope
1028
+ * may ask, and the reason they give travels with it.
1029
+ */
1030
+ async exportEvidence(input, caller) {
1031
+ const operator = this.operator(caller, "evidence");
1032
+ const parsed = HaltRequestSchema.safeParse(input);
1033
+ if (!parsed.success)
1034
+ throw new ServiceError(400, "REQUEST_INVALID");
1035
+ if (!this.evidence.configured)
1036
+ throw new ServiceError(409, "EVIDENCE_DIR_NOT_CONFIGURED");
1037
+ let bundle;
1038
+ try {
1039
+ bundle = await this.evidence.export({
1040
+ principal: operator.id,
1041
+ reason: parsed.data.reason,
1042
+ });
1043
+ }
1044
+ catch (error) {
1045
+ throw new ServiceError(500, error instanceof EvidenceError ? error.code : "EVIDENCE_FAILED");
1046
+ }
1047
+ this.events.emit({
1048
+ event: "EVIDENCE_EXPORTED",
1049
+ principal: operator.id,
1050
+ files: bundle.manifest.files.length,
1051
+ signed: bundle.signature !== null,
1052
+ });
1053
+ return bundle;
1054
+ }
1055
+ static binding(authorization) {
1056
+ if (authorization === null)
1057
+ return null;
1058
+ return {
1059
+ decision_id: authorization.decisionId,
1060
+ dossier_id: authorization.dossierId,
1061
+ grant_id: authorization.grantId,
1062
+ expires_at: authorization.expiresAt,
1063
+ };
1064
+ }
1065
+ }
1066
+ //# sourceMappingURL=TrustedExecutorService.js.map