@noopolis/daimon 0.1.1 → 0.2.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 (404) hide show
  1. package/README.md +307 -45
  2. package/dist/contracts/attentionContract.d.ts +117 -0
  3. package/dist/contracts/attentionContract.d.ts.map +1 -0
  4. package/dist/contracts/attentionContract.js +14 -0
  5. package/dist/contracts/canonicalJson.d.ts +3 -0
  6. package/dist/contracts/canonicalJson.d.ts.map +1 -0
  7. package/dist/contracts/canonicalJson.js +54 -0
  8. package/dist/contracts/grokWorkerContract.d.ts +74 -0
  9. package/dist/contracts/grokWorkerContract.d.ts.map +1 -0
  10. package/dist/contracts/grokWorkerContract.js +88 -0
  11. package/dist/contracts/organizationRuntimeContract.d.ts +765 -0
  12. package/dist/contracts/organizationRuntimeContract.d.ts.map +1 -0
  13. package/dist/contracts/organizationRuntimeContract.js +121 -0
  14. package/dist/contracts/runtimeContractManifest.d.ts +1615 -0
  15. package/dist/contracts/runtimeContractManifest.d.ts.map +1 -0
  16. package/dist/contracts/runtimeContractManifest.js +181 -0
  17. package/dist/core/credentialRedaction.d.ts +4 -0
  18. package/dist/core/credentialRedaction.d.ts.map +1 -0
  19. package/dist/core/credentialRedaction.js +28 -0
  20. package/dist/core/siblingBuildFreshness.d.ts +21 -0
  21. package/dist/core/siblingBuildFreshness.d.ts.map +1 -0
  22. package/dist/core/siblingBuildFreshness.js +25 -0
  23. package/dist/core/types.d.ts +10 -1
  24. package/dist/core/types.d.ts.map +1 -1
  25. package/dist/examples/exampleCausalId.d.ts +3 -0
  26. package/dist/examples/exampleCausalId.d.ts.map +1 -0
  27. package/dist/examples/exampleCausalId.js +8 -0
  28. package/dist/examples/jungian-play-org.js +3 -2
  29. package/dist/examples/jungian-triad-org.js +3 -2
  30. package/dist/examples/jungianPlayAgent.d.ts +1 -1
  31. package/dist/examples/jungianPlayAgent.d.ts.map +1 -1
  32. package/dist/examples/jungianPlayAgent.js +1 -1
  33. package/dist/examples/jungianProfiles.d.ts +1 -1
  34. package/dist/examples/jungianProfiles.d.ts.map +1 -1
  35. package/dist/examples/jungianTriadProfiles.d.ts +1 -1
  36. package/dist/examples/jungianTriadProfiles.d.ts.map +1 -1
  37. package/dist/examples/pi-agent.js +3 -2
  38. package/dist/examples/pi-memory-org.js +6 -5
  39. package/dist/index.d.ts +1 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +1 -0
  42. package/dist/mcp/toolServer.d.ts +31 -0
  43. package/dist/mcp/toolServer.d.ts.map +1 -0
  44. package/dist/mcp/toolServer.js +145 -0
  45. package/dist/observability/causalEvents.d.ts +118 -0
  46. package/dist/observability/causalEvents.d.ts.map +1 -0
  47. package/dist/observability/causalEvents.js +223 -0
  48. package/dist/observability/controlCausal.d.ts +117 -0
  49. package/dist/observability/controlCausal.d.ts.map +1 -0
  50. package/dist/observability/controlCausal.js +107 -0
  51. package/dist/observability/emitCausalFixture.d.ts +25 -0
  52. package/dist/observability/emitCausalFixture.d.ts.map +1 -0
  53. package/dist/observability/emitCausalFixture.js +98 -0
  54. package/dist/observability/index.d.ts +2 -0
  55. package/dist/observability/index.d.ts.map +1 -1
  56. package/dist/observability/index.js +2 -0
  57. package/dist/observability/orgObserver.d.ts.map +1 -1
  58. package/dist/observability/orgObserver.js +3 -3
  59. package/dist/pi/agyHeadlessResult.d.ts +60 -0
  60. package/dist/pi/agyHeadlessResult.d.ts.map +1 -0
  61. package/dist/pi/agyHeadlessResult.js +95 -0
  62. package/dist/pi/cliChildOutput.d.ts +67 -0
  63. package/dist/pi/cliChildOutput.d.ts.map +1 -0
  64. package/dist/pi/cliChildOutput.js +269 -0
  65. package/dist/pi/cliEngineRun.d.ts +16 -0
  66. package/dist/pi/cliEngineRun.d.ts.map +1 -0
  67. package/dist/pi/cliEngineRun.js +27 -0
  68. package/dist/pi/cliEngineSpawn.d.ts +55 -0
  69. package/dist/pi/cliEngineSpawn.d.ts.map +1 -0
  70. package/dist/pi/cliEngineSpawn.js +164 -0
  71. package/dist/pi/cliEnvironment.d.ts +12 -0
  72. package/dist/pi/cliEnvironment.d.ts.map +1 -0
  73. package/dist/pi/cliEnvironment.js +32 -0
  74. package/dist/pi/cliMcpRegistration.d.ts +61 -0
  75. package/dist/pi/cliMcpRegistration.d.ts.map +1 -0
  76. package/dist/pi/cliMcpRegistration.js +75 -0
  77. package/dist/pi/cliProcess.d.ts +7 -0
  78. package/dist/pi/cliProcess.d.ts.map +1 -0
  79. package/dist/pi/cliProcess.js +132 -0
  80. package/dist/pi/cliSession.d.ts +106 -0
  81. package/dist/pi/cliSession.d.ts.map +1 -0
  82. package/dist/pi/cliSession.js +379 -0
  83. package/dist/pi/cliTurnMetering.d.ts +60 -0
  84. package/dist/pi/cliTurnMetering.d.ts.map +1 -0
  85. package/dist/pi/cliTurnMetering.js +60 -0
  86. package/dist/pi/codexFilesystemRules.d.ts +3 -0
  87. package/dist/pi/codexFilesystemRules.d.ts.map +1 -0
  88. package/dist/pi/codexFilesystemRules.js +28 -0
  89. package/dist/pi/codexHeadlessResult.d.ts +68 -0
  90. package/dist/pi/codexHeadlessResult.d.ts.map +1 -0
  91. package/dist/pi/codexHeadlessResult.js +122 -0
  92. package/dist/pi/codexRolloutUsage.d.ts +95 -0
  93. package/dist/pi/codexRolloutUsage.d.ts.map +1 -0
  94. package/dist/pi/codexRolloutUsage.js +221 -0
  95. package/dist/pi/engineWakeLimits.d.ts +39 -0
  96. package/dist/pi/engineWakeLimits.d.ts.map +1 -0
  97. package/dist/pi/engineWakeLimits.js +55 -0
  98. package/dist/pi/grokHeadlessResult.d.ts +36 -0
  99. package/dist/pi/grokHeadlessResult.d.ts.map +1 -0
  100. package/dist/pi/grokHeadlessResult.js +118 -0
  101. package/dist/pi/grokHomeMcpRegistration.d.ts +21 -0
  102. package/dist/pi/grokHomeMcpRegistration.d.ts.map +1 -0
  103. package/dist/pi/grokHomeMcpRegistration.js +57 -0
  104. package/dist/pi/grokSandbox.d.ts +11 -0
  105. package/dist/pi/grokSandbox.d.ts.map +1 -0
  106. package/dist/pi/grokSandbox.js +216 -0
  107. package/dist/pi/grokStreamUsage.d.ts +31 -0
  108. package/dist/pi/grokStreamUsage.d.ts.map +1 -0
  109. package/dist/pi/grokStreamUsage.js +51 -0
  110. package/dist/pi/index.d.ts +5 -0
  111. package/dist/pi/index.d.ts.map +1 -1
  112. package/dist/pi/index.js +5 -0
  113. package/dist/pi/memoryTools.d.ts +55 -1
  114. package/dist/pi/memoryTools.d.ts.map +1 -1
  115. package/dist/pi/memoryTools.js +144 -24
  116. package/dist/pi/modelRegistry.d.ts +13 -0
  117. package/dist/pi/modelRegistry.d.ts.map +1 -0
  118. package/dist/pi/modelRegistry.js +19 -0
  119. package/dist/pi/piAgentHandle.d.ts +46 -0
  120. package/dist/pi/piAgentHandle.d.ts.map +1 -0
  121. package/dist/pi/piAgentHandle.js +351 -0
  122. package/dist/pi/piAgentWakeSupport.d.ts +103 -0
  123. package/dist/pi/piAgentWakeSupport.d.ts.map +1 -0
  124. package/dist/pi/piAgentWakeSupport.js +151 -0
  125. package/dist/pi/piHarness.d.ts +40 -5
  126. package/dist/pi/piHarness.d.ts.map +1 -1
  127. package/dist/pi/piHarness.js +151 -256
  128. package/dist/pi/prompts.d.ts +10 -0
  129. package/dist/pi/prompts.d.ts.map +1 -0
  130. package/dist/pi/prompts.js +63 -0
  131. package/dist/pi/rawTrainingCapture.d.ts +59 -0
  132. package/dist/pi/rawTrainingCapture.d.ts.map +1 -0
  133. package/dist/pi/rawTrainingCapture.js +175 -0
  134. package/dist/pi/turnCausal.d.ts +73 -0
  135. package/dist/pi/turnCausal.d.ts.map +1 -0
  136. package/dist/pi/turnCausal.js +75 -0
  137. package/dist/pi/turnTrace.d.ts +128 -0
  138. package/dist/pi/turnTrace.d.ts.map +1 -0
  139. package/dist/pi/turnTrace.js +138 -0
  140. package/dist/pi/wakeAcceptance.d.ts +49 -0
  141. package/dist/pi/wakeAcceptance.d.ts.map +1 -0
  142. package/dist/pi/wakeAcceptance.js +281 -0
  143. package/dist/pi/wakeAcceptanceFs.d.ts +44 -0
  144. package/dist/pi/wakeAcceptanceFs.d.ts.map +1 -0
  145. package/dist/pi/wakeAcceptanceFs.js +318 -0
  146. package/dist/pi/wakeAcceptanceSchema.d.ts +75 -0
  147. package/dist/pi/wakeAcceptanceSchema.d.ts.map +1 -0
  148. package/dist/pi/wakeAcceptanceSchema.js +265 -0
  149. package/dist/pi/wakeModes.d.ts +9 -0
  150. package/dist/pi/wakeModes.d.ts.map +1 -0
  151. package/dist/pi/wakeModes.js +19 -0
  152. package/dist/pi/worldNudge.d.ts +22 -0
  153. package/dist/pi/worldNudge.d.ts.map +1 -0
  154. package/dist/pi/worldNudge.js +62 -0
  155. package/dist/pi/worldToolProtocol.d.ts +13 -0
  156. package/dist/pi/worldToolProtocol.d.ts.map +1 -0
  157. package/dist/pi/worldToolProtocol.js +49 -0
  158. package/dist/pi/worldTools.d.ts +32 -0
  159. package/dist/pi/worldTools.d.ts.map +1 -0
  160. package/dist/pi/worldTools.js +373 -0
  161. package/dist/pi/worldTrajectory.d.ts +52 -0
  162. package/dist/pi/worldTrajectory.d.ts.map +1 -0
  163. package/dist/pi/worldTrajectory.js +131 -0
  164. package/dist/runtime/agySubscriptionBootstrap.d.ts +16 -0
  165. package/dist/runtime/agySubscriptionBootstrap.d.ts.map +1 -0
  166. package/dist/runtime/agySubscriptionBootstrap.js +80 -0
  167. package/dist/runtime/agySubscriptionRealm.d.ts +38 -0
  168. package/dist/runtime/agySubscriptionRealm.d.ts.map +1 -0
  169. package/dist/runtime/agySubscriptionRealm.js +242 -0
  170. package/dist/runtime/attention.d.ts +21 -0
  171. package/dist/runtime/attention.d.ts.map +1 -0
  172. package/dist/runtime/attention.js +36 -0
  173. package/dist/runtime/attentionDispatcher.d.ts +66 -0
  174. package/dist/runtime/attentionDispatcher.d.ts.map +1 -0
  175. package/dist/runtime/attentionDispatcher.js +271 -0
  176. package/dist/runtime/cli.d.ts +7 -0
  177. package/dist/runtime/cli.d.ts.map +1 -0
  178. package/dist/runtime/cli.js +251 -0
  179. package/dist/runtime/codexSandboxProjection.d.ts +17 -0
  180. package/dist/runtime/codexSandboxProjection.d.ts.map +1 -0
  181. package/dist/runtime/codexSandboxProjection.js +40 -0
  182. package/dist/runtime/contract-manifest.json +1 -0
  183. package/dist/runtime/contract-manifest.sha256 +1 -0
  184. package/dist/runtime/contractManifest.d.ts +8 -0
  185. package/dist/runtime/contractManifest.d.ts.map +1 -0
  186. package/dist/runtime/contractManifest.js +4 -0
  187. package/dist/runtime/engineBrokerCapabilities.d.ts +30 -0
  188. package/dist/runtime/engineBrokerCapabilities.d.ts.map +1 -0
  189. package/dist/runtime/engineBrokerCapabilities.js +59 -0
  190. package/dist/runtime/engineBrokerControlClient.d.ts +44 -0
  191. package/dist/runtime/engineBrokerControlClient.d.ts.map +1 -0
  192. package/dist/runtime/engineBrokerControlClient.js +132 -0
  193. package/dist/runtime/engineBrokerCredentialJournal.d.ts +10 -0
  194. package/dist/runtime/engineBrokerCredentialJournal.d.ts.map +1 -0
  195. package/dist/runtime/engineBrokerCredentialJournal.js +17 -0
  196. package/dist/runtime/engineBrokerInferenceProtocol.d.ts +52 -0
  197. package/dist/runtime/engineBrokerInferenceProtocol.d.ts.map +1 -0
  198. package/dist/runtime/engineBrokerInferenceProtocol.js +65 -0
  199. package/dist/runtime/engineBrokerMcpCallLog.d.ts +160 -0
  200. package/dist/runtime/engineBrokerMcpCallLog.d.ts.map +1 -0
  201. package/dist/runtime/engineBrokerMcpCallLog.js +219 -0
  202. package/dist/runtime/engineBrokerMcpFacade.d.ts +56 -0
  203. package/dist/runtime/engineBrokerMcpFacade.d.ts.map +1 -0
  204. package/dist/runtime/engineBrokerMcpFacade.js +343 -0
  205. package/dist/runtime/engineBrokerNativeClient.d.ts +52 -0
  206. package/dist/runtime/engineBrokerNativeClient.d.ts.map +1 -0
  207. package/dist/runtime/engineBrokerNativeClient.js +151 -0
  208. package/dist/runtime/engineBrokerProtocol.d.ts +135 -0
  209. package/dist/runtime/engineBrokerProtocol.d.ts.map +1 -0
  210. package/dist/runtime/engineBrokerProtocol.js +274 -0
  211. package/dist/runtime/engineBrokerSealLedger.d.ts +70 -0
  212. package/dist/runtime/engineBrokerSealLedger.d.ts.map +1 -0
  213. package/dist/runtime/engineBrokerSealLedger.js +123 -0
  214. package/dist/runtime/engineBrokerService.d.ts +37 -0
  215. package/dist/runtime/engineBrokerService.d.ts.map +1 -0
  216. package/dist/runtime/engineBrokerService.js +138 -0
  217. package/dist/runtime/engineBrokerServiceCli.d.ts +5 -0
  218. package/dist/runtime/engineBrokerServiceCli.d.ts.map +1 -0
  219. package/dist/runtime/engineBrokerServiceCli.js +32 -0
  220. package/dist/runtime/engineBrokerServiceConfig.d.ts +50 -0
  221. package/dist/runtime/engineBrokerServiceConfig.d.ts.map +1 -0
  222. package/dist/runtime/engineBrokerServiceConfig.js +92 -0
  223. package/dist/runtime/engineBrokerSingleflight.d.ts +13 -0
  224. package/dist/runtime/engineBrokerSingleflight.d.ts.map +1 -0
  225. package/dist/runtime/engineBrokerSingleflight.js +24 -0
  226. package/dist/runtime/engineBrokerTurnAccounting.d.ts +76 -0
  227. package/dist/runtime/engineBrokerTurnAccounting.d.ts.map +1 -0
  228. package/dist/runtime/engineBrokerTurnAccounting.js +108 -0
  229. package/dist/runtime/engineBrokerTurnRegistry.d.ts +57 -0
  230. package/dist/runtime/engineBrokerTurnRegistry.d.ts.map +1 -0
  231. package/dist/runtime/engineBrokerTurnRegistry.js +158 -0
  232. package/dist/runtime/engineDispatcher.d.ts +36 -0
  233. package/dist/runtime/engineDispatcher.d.ts.map +1 -0
  234. package/dist/runtime/engineDispatcher.js +216 -0
  235. package/dist/runtime/engineReadiness.d.ts +23 -0
  236. package/dist/runtime/engineReadiness.d.ts.map +1 -0
  237. package/dist/runtime/engineReadiness.js +222 -0
  238. package/dist/runtime/grokAuthenticationError.d.ts +8 -0
  239. package/dist/runtime/grokAuthenticationError.d.ts.map +1 -0
  240. package/dist/runtime/grokAuthenticationError.js +20 -0
  241. package/dist/runtime/grokBrokerCredentialAuthority.d.ts +22 -0
  242. package/dist/runtime/grokBrokerCredentialAuthority.d.ts.map +1 -0
  243. package/dist/runtime/grokBrokerCredentialAuthority.js +124 -0
  244. package/dist/runtime/grokBrokerCredentialReader.d.ts +5 -0
  245. package/dist/runtime/grokBrokerCredentialReader.d.ts.map +1 -0
  246. package/dist/runtime/grokBrokerCredentialReader.js +37 -0
  247. package/dist/runtime/grokBrokerModelPolicy.d.ts +23 -0
  248. package/dist/runtime/grokBrokerModelPolicy.d.ts.map +1 -0
  249. package/dist/runtime/grokBrokerModelPolicy.js +28 -0
  250. package/dist/runtime/grokBrokerProjection.d.ts +106 -0
  251. package/dist/runtime/grokBrokerProjection.d.ts.map +1 -0
  252. package/dist/runtime/grokBrokerProjection.js +94 -0
  253. package/dist/runtime/grokBrokerProxy.d.ts +55 -0
  254. package/dist/runtime/grokBrokerProxy.d.ts.map +1 -0
  255. package/dist/runtime/grokBrokerProxy.js +262 -0
  256. package/dist/runtime/grokBrokerProxyRequest.d.ts +30 -0
  257. package/dist/runtime/grokBrokerProxyRequest.d.ts.map +1 -0
  258. package/dist/runtime/grokBrokerProxyRequest.js +74 -0
  259. package/dist/runtime/grokBrokerRealmLease.d.ts +4 -0
  260. package/dist/runtime/grokBrokerRealmLease.d.ts.map +1 -0
  261. package/dist/runtime/grokBrokerRealmLease.js +33 -0
  262. package/dist/runtime/grokBrokerRefresh.d.ts +2 -0
  263. package/dist/runtime/grokBrokerRefresh.d.ts.map +1 -0
  264. package/dist/runtime/grokBrokerRefresh.js +15 -0
  265. package/dist/runtime/grokBrokerTurnMeter.d.ts +128 -0
  266. package/dist/runtime/grokBrokerTurnMeter.d.ts.map +1 -0
  267. package/dist/runtime/grokBrokerTurnMeter.js +251 -0
  268. package/dist/runtime/grokBrokerWorkerConfig.d.ts +86 -0
  269. package/dist/runtime/grokBrokerWorkerConfig.d.ts.map +1 -0
  270. package/dist/runtime/grokBrokerWorkerConfig.js +135 -0
  271. package/dist/runtime/grokEngineBroker.d.ts +48 -0
  272. package/dist/runtime/grokEngineBroker.d.ts.map +1 -0
  273. package/dist/runtime/grokEngineBroker.js +114 -0
  274. package/dist/runtime/grokEngineBrokerLedger.d.ts +52 -0
  275. package/dist/runtime/grokEngineBrokerLedger.d.ts.map +1 -0
  276. package/dist/runtime/grokEngineBrokerLedger.js +114 -0
  277. package/dist/runtime/grokEngineBrokerMetering.d.ts +51 -0
  278. package/dist/runtime/grokEngineBrokerMetering.d.ts.map +1 -0
  279. package/dist/runtime/grokEngineBrokerMetering.js +34 -0
  280. package/dist/runtime/grokEngineBrokerTurn.d.ts +58 -0
  281. package/dist/runtime/grokEngineBrokerTurn.d.ts.map +1 -0
  282. package/dist/runtime/grokEngineBrokerTurn.js +165 -0
  283. package/dist/runtime/grokInferenceClientConfig.d.ts +41 -0
  284. package/dist/runtime/grokInferenceClientConfig.d.ts.map +1 -0
  285. package/dist/runtime/grokInferenceClientConfig.js +62 -0
  286. package/dist/runtime/grokInferenceGrants.d.ts +77 -0
  287. package/dist/runtime/grokInferenceGrants.d.ts.map +1 -0
  288. package/dist/runtime/grokInferenceGrants.js +116 -0
  289. package/dist/runtime/grokInferenceProxy.d.ts +29 -0
  290. package/dist/runtime/grokInferenceProxy.d.ts.map +1 -0
  291. package/dist/runtime/grokInferenceProxy.js +82 -0
  292. package/dist/runtime/grokInferenceProxyRequest.d.ts +23 -0
  293. package/dist/runtime/grokInferenceProxyRequest.d.ts.map +1 -0
  294. package/dist/runtime/grokInferenceProxyRequest.js +63 -0
  295. package/dist/runtime/grokSlotPreflightReceipt.d.ts +70 -0
  296. package/dist/runtime/grokSlotPreflightReceipt.d.ts.map +1 -0
  297. package/dist/runtime/grokSlotPreflightReceipt.js +101 -0
  298. package/dist/runtime/grokSubscriptionRealm.d.ts +4 -0
  299. package/dist/runtime/grokSubscriptionRealm.d.ts.map +1 -0
  300. package/dist/runtime/grokSubscriptionRealm.js +435 -0
  301. package/dist/runtime/grokSubscriptionRealmTypes.d.ts +26 -0
  302. package/dist/runtime/grokSubscriptionRealmTypes.d.ts.map +1 -0
  303. package/dist/runtime/grokSubscriptionRealmTypes.js +1 -0
  304. package/dist/runtime/grokWorkerAttestation.d.ts +170 -0
  305. package/dist/runtime/grokWorkerAttestation.d.ts.map +1 -0
  306. package/dist/runtime/grokWorkerAttestation.js +266 -0
  307. package/dist/runtime/grokWorkerDenyPlacement.d.ts +80 -0
  308. package/dist/runtime/grokWorkerDenyPlacement.d.ts.map +1 -0
  309. package/dist/runtime/grokWorkerDenyPlacement.js +128 -0
  310. package/dist/runtime/grokWorkerHomeAttestation.d.ts +30 -0
  311. package/dist/runtime/grokWorkerHomeAttestation.d.ts.map +1 -0
  312. package/dist/runtime/grokWorkerHomeAttestation.js +69 -0
  313. package/dist/runtime/grokWorkerSandboxProfile.d.ts +27 -0
  314. package/dist/runtime/grokWorkerSandboxProfile.d.ts.map +1 -0
  315. package/dist/runtime/grokWorkerSandboxProfile.js +44 -0
  316. package/dist/runtime/grokWorkerTmpAttestation.d.ts +55 -0
  317. package/dist/runtime/grokWorkerTmpAttestation.d.ts.map +1 -0
  318. package/dist/runtime/grokWorkerTmpAttestation.js +63 -0
  319. package/dist/runtime/index.d.ts +26 -0
  320. package/dist/runtime/index.d.ts.map +1 -0
  321. package/dist/runtime/index.js +23 -0
  322. package/dist/runtime/inferenceUsageLedger.d.ts +38 -0
  323. package/dist/runtime/inferenceUsageLedger.d.ts.map +1 -0
  324. package/dist/runtime/inferenceUsageLedger.js +53 -0
  325. package/dist/runtime/mcpToolResult.d.ts +127 -0
  326. package/dist/runtime/mcpToolResult.d.ts.map +1 -0
  327. package/dist/runtime/mcpToolResult.js +214 -0
  328. package/dist/runtime/moltnetMachineRead.d.ts +97 -0
  329. package/dist/runtime/moltnetMachineRead.d.ts.map +1 -0
  330. package/dist/runtime/moltnetMachineRead.js +183 -0
  331. package/dist/runtime/native/daimon-engine-broker +0 -0
  332. package/dist/runtime/organizationRuntime.d.ts +165 -0
  333. package/dist/runtime/organizationRuntime.d.ts.map +1 -0
  334. package/dist/runtime/organizationRuntime.js +3 -0
  335. package/dist/runtime/organizationRuntimeControl.d.ts +42 -0
  336. package/dist/runtime/organizationRuntimeControl.d.ts.map +1 -0
  337. package/dist/runtime/organizationRuntimeControl.js +235 -0
  338. package/dist/runtime/organizationRuntimeHost.d.ts +19 -0
  339. package/dist/runtime/organizationRuntimeHost.d.ts.map +1 -0
  340. package/dist/runtime/organizationRuntimeHost.js +359 -0
  341. package/dist/runtime/organizationRuntimeParsing.d.ts +6 -0
  342. package/dist/runtime/organizationRuntimeParsing.d.ts.map +1 -0
  343. package/dist/runtime/organizationRuntimeParsing.js +370 -0
  344. package/dist/runtime/organizationRuntimeReadiness.d.ts +12 -0
  345. package/dist/runtime/organizationRuntimeReadiness.d.ts.map +1 -0
  346. package/dist/runtime/organizationRuntimeReadiness.js +59 -0
  347. package/dist/runtime/physicalReadiness.d.ts +47 -0
  348. package/dist/runtime/physicalReadiness.d.ts.map +1 -0
  349. package/dist/runtime/physicalReadiness.js +142 -0
  350. package/dist/runtime/portableCredentialAuth.d.ts +6 -0
  351. package/dist/runtime/portableCredentialAuth.d.ts.map +1 -0
  352. package/dist/runtime/portableCredentialAuth.js +70 -0
  353. package/dist/runtime/portableCredentialMaterial.d.ts +8 -0
  354. package/dist/runtime/portableCredentialMaterial.d.ts.map +1 -0
  355. package/dist/runtime/portableCredentialMaterial.js +169 -0
  356. package/dist/runtime/productionAgentTools.d.ts +5 -0
  357. package/dist/runtime/productionAgentTools.d.ts.map +1 -0
  358. package/dist/runtime/productionAgentTools.js +328 -0
  359. package/dist/runtime/runtimeHomeLayout.d.ts +48 -0
  360. package/dist/runtime/runtimeHomeLayout.d.ts.map +1 -0
  361. package/dist/runtime/runtimeHomeLayout.js +84 -0
  362. package/dist/runtime/schedule.d.ts +40 -0
  363. package/dist/runtime/schedule.d.ts.map +1 -0
  364. package/dist/runtime/schedule.js +371 -0
  365. package/dist/runtime/storeCoordination.d.ts +23 -0
  366. package/dist/runtime/storeCoordination.d.ts.map +1 -0
  367. package/dist/runtime/storeCoordination.js +94 -0
  368. package/dist/runtime/toolResultSpill.d.ts +152 -0
  369. package/dist/runtime/toolResultSpill.d.ts.map +1 -0
  370. package/dist/runtime/toolResultSpill.js +351 -0
  371. package/dist/runtime/turnRequestLedger.d.ts +160 -0
  372. package/dist/runtime/turnRequestLedger.d.ts.map +1 -0
  373. package/dist/runtime/turnRequestLedger.js +249 -0
  374. package/dist/runtime/turnUsageLedger.d.ts +143 -0
  375. package/dist/runtime/turnUsageLedger.d.ts.map +1 -0
  376. package/dist/runtime/turnUsageLedger.js +203 -0
  377. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts +17 -0
  378. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts.map +1 -0
  379. package/dist/runtime/wakeAcceptanceProcessIdentity.js +50 -0
  380. package/dist/runtime/wakeAcceptanceReconciliation.d.ts +211 -0
  381. package/dist/runtime/wakeAcceptanceReconciliation.d.ts.map +1 -0
  382. package/dist/runtime/wakeAcceptanceReconciliation.js +289 -0
  383. package/dist/runtime/wakeAcceptanceRecord.d.ts +23 -0
  384. package/dist/runtime/wakeAcceptanceRecord.d.ts.map +1 -0
  385. package/dist/runtime/wakeAcceptanceRecord.js +56 -0
  386. package/dist/runtime/wakeAcceptanceRetention.d.ts +12 -0
  387. package/dist/runtime/wakeAcceptanceRetention.d.ts.map +1 -0
  388. package/dist/runtime/wakeAcceptanceRetention.js +12 -0
  389. package/dist/runtime/wakeAcceptanceStore.d.ts +113 -0
  390. package/dist/runtime/wakeAcceptanceStore.d.ts.map +1 -0
  391. package/dist/runtime/wakeAcceptanceStore.js +558 -0
  392. package/dist/runtime/wakeAcceptanceTypes.d.ts +179 -0
  393. package/dist/runtime/wakeAcceptanceTypes.d.ts.map +1 -0
  394. package/dist/runtime/wakeAcceptanceTypes.js +95 -0
  395. package/dist/runtime/wakeFuse.d.ts +69 -0
  396. package/dist/runtime/wakeFuse.d.ts.map +1 -0
  397. package/dist/runtime/wakeFuse.js +367 -0
  398. package/package.json +25 -17
  399. package/dist/examples/mixed-engine-org.d.ts +0 -2
  400. package/dist/examples/mixed-engine-org.d.ts.map +0 -1
  401. package/dist/examples/mixed-engine-org.js +0 -351
  402. package/dist/examples/mixedEngineCli.d.ts +0 -15
  403. package/dist/examples/mixedEngineCli.d.ts.map +0 -1
  404. package/dist/examples/mixedEngineCli.js +0 -174
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engineBrokerService.d.ts","sourceRoot":"","sources":["../../src/runtime/engineBrokerService.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AAGlH,OAAO,EAA6B,KAAK,wBAAwB,EAAE,KAAK,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AACpI,MAAM,WAAW,yBAAyB;IACxC,IAAI,CAAC,OAAO,EAAC,MAAM,EAAC,MAAM,EAAC,MAAM,EAAC,MAAM,EAAC,MAAM,EAAC,WAAW,EAAC,MAAM,EAAC,MAAM,CAAC,EAAC,WAAW,EAAC,MAAM,CAAC,EAAC,8BAA8B,GAAE,OAAO,CAAC,QAAQ,CAAC;QAAC,IAAI,EAAC,MAAM,CAAC;QAAA,SAAS,EAAC,MAAM,CAAC;QAAA,SAAS,EAAC,MAAM,CAAC;QAAA,eAAe,EAAC,MAAM,CAAA;KAAC,CAAC,GAAC,0BAA0B,CAAC,CAAC;IACpP,SAAS,IAAG,QAAQ,CAAC;QAAC,iBAAiB,EAAC,MAAM,CAAC;QAAA,aAAa,EAAC,MAAM,CAAC;QAAA,aAAa,EAAC,MAAM,CAAC;QAAA,eAAe,EAAC,OAAO,CAAC;QAAA,UAAU,EAAC,OAAO,CAAC;QAAA,eAAe,EAAC,OAAO,CAAA;KAAC,CAAC,CAAC;IAC9J,KAAK,IAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACtB,yJAAyJ;IACzJ,qBAAqB,CAAC,CAAC,OAAO,EAAC,yBAAyB,GAAE,wBAAwB,CAAC;IACnF,qBAAqB,CAAC,CAAC,OAAO,EAAC,MAAM,GAAE,OAAO,CAAC;CAChD;AAED,wBAAgB,wBAAwB,CAAC,MAAM,EAAC,yBAAyB,EAAC,UAAU,SAAyC;;;;;;GAE5H;AACD,wBAAsB,oCAAoC,CAAC,MAAM,EAAC,yBAAyB,EAAC,UAAU,EAAC,MAAM,EAAC,WAAW,EAAC,MAAM;;;;;;GAK/H"}
@@ -0,0 +1,138 @@
1
+ import { chmod, lstat, unlink } from "node:fs/promises";
2
+ import { createServer } from "node:net";
3
+ import { encodeEngineBrokerFrame, EngineBrokerFrameDecoder, parseEngineBrokerRequest } from "./engineBrokerProtocol.js";
4
+ import { EngineBrokerTurnFailure } from "./grokEngineBroker.js";
5
+ import { GROK_INFERENCE_PROXY_BASE_URL } from "./engineBrokerInferenceProtocol.js";
6
+ import { GrokInferenceGrantRefused } from "./grokInferenceGrants.js";
7
+ export function startEngineBrokerService(broker, socketPath = "/run/daimon-engine-broker/backend.sock") {
8
+ return startEngineBrokerServiceWithIdentity(broker, socketPath, 2100);
9
+ }
10
+ export async function startEngineBrokerServiceWithIdentity(broker, socketPath, expectedUid) {
11
+ if (process.getuid?.() !== expectedUid)
12
+ throw new Error("engine broker service requires broker identity");
13
+ await removeOwnedSocket(socketPath, expectedUid);
14
+ const active = new Map(), connections = new Set();
15
+ const server = createServer((socket) => { connections.add(socket); socket.once("close", () => connections.delete(socket)); handle(socket, broker, active); });
16
+ await listen(server, socketPath);
17
+ try {
18
+ await chmod(socketPath, 0o600);
19
+ await verifySocket(socketPath, expectedUid);
20
+ }
21
+ catch (error) {
22
+ await closeServer(server, connections);
23
+ await unlink(socketPath).catch(() => undefined);
24
+ throw error;
25
+ }
26
+ let closed = false;
27
+ return { close: async () => { if (closed)
28
+ return; closed = true; for (const controller of active.values())
29
+ controller.abort(); const results = await Promise.allSettled([closeServer(server, connections), broker.close()]); await unlink(socketPath).catch(() => undefined); const failures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []); if (failures.length)
30
+ throw new AggregateError(failures, "engine broker service shutdown failed"); }, health: () => ({ activeTurns: active.size, socketPath }) };
31
+ }
32
+ /**
33
+ * A connection error is a client that went away, never a reason to take the
34
+ * broker down with it.
35
+ *
36
+ * Without this listener an accepted socket that emits `error` had none, and
37
+ * node turns an unhandled `error` on a stream into an uncaught exception — so a
38
+ * single departing client killed the whole service and every other in-flight
39
+ * turn with it. That is reachable from the ordinary cancellation path: the
40
+ * client destroys its socket on abort, this side aborts the turn, the engine
41
+ * rejects, and this side then writes a `failed` frame to a peer that is already
42
+ * gone. On Linux that write/read races an RST and surfaces as ECONNRESET; macOS
43
+ * closes cleanly enough that the error never arrives, which is why this was
44
+ * invisible until the suite ran in a container.
45
+ *
46
+ * Treated exactly like `close`: abort whatever turn this connection owned and
47
+ * drop the socket. The turn's own result is already unreachable — its only
48
+ * reader has disconnected.
49
+ */
50
+ function handleSocketError(socket, owned) { socket.on("error", () => { owned()?.controller.abort(); socket.destroy(); }); }
51
+ function handle(socket, broker, active) { const decoder = new EngineBrokerFrameDecoder(); let started = false, owned; handleSocketError(socket, () => owned); socket.once("close", () => owned?.controller.abort()); socket.on("data", (chunk) => { try {
52
+ for (const value of decoder.push(chunk)) {
53
+ const request = parseEngineBrokerRequest(value);
54
+ if (request.kind === "health") {
55
+ if (started)
56
+ throw new Error();
57
+ started = true;
58
+ const ready = broker.readiness();
59
+ if (ready.providerProxyPort !== 43123 || ready.mcpFacadePort !== 43124 || ready.registrations < 1 || ready.credentialStale || !ready.realmLease || !ready.workerIsolation)
60
+ throw new Error();
61
+ return send(socket, { version: request.version, kind: "ready", requestId: request.requestId, brokerUid: 2100, providerProxyPort: 43123, mcpFacadePort: 43124, registrations: ready.registrations, credentialStale: false, realmLease: true, workerIsolation: true });
62
+ }
63
+ if (request.kind === "cancel_turn") {
64
+ active.get(request.turnId)?.abort();
65
+ continue;
66
+ }
67
+ if (request.kind === "request_inference_grant" || request.kind === "release_inference_grant") {
68
+ if (started)
69
+ throw new Error();
70
+ started = true;
71
+ serveInferenceGrant(socket, broker, request);
72
+ continue;
73
+ }
74
+ if (started || active.has(request.turnId))
75
+ throw new Error();
76
+ started = true;
77
+ const controller = new AbortController();
78
+ owned = { turnId: request.turnId, controller };
79
+ active.set(request.turnId, controller);
80
+ socket.write(encodeEngineBrokerFrame({ version: request.version, kind: "accepted", requestId: request.requestId, turnId: request.turnId }));
81
+ void broker.turn(request.agentId, request.wakeId, request.prompt, request.mcpEndpoint, controller.signal, request.limits).then((result) => send(socket, { version: request.version, kind: "completed", requestId: request.requestId, turnId: request.turnId, text: result.text, workerPid: result.workerPid, workerUid: result.workerUid, workerStartTime: result.workerStartTime, outcome: "completed", usage: result.usage, model: result.model, requests: result.requests, limitReason: "none" }), (error) => failed(socket, request, error, controller.signal.aborted)).finally(() => { if (active.get(request.turnId) === controller)
82
+ active.delete(request.turnId); owned = undefined; });
83
+ }
84
+ }
85
+ catch {
86
+ socket.destroy();
87
+ } }); }
88
+ /**
89
+ * Every failure the broker raises for a known registration carries its
90
+ * accounting (a wake that tried to raise a limit: `usage: null`, zero
91
+ * requests). A failure with no registration behind it (unknown agent, closed
92
+ * broker) has no declared model to report, so it is refused as a bare
93
+ * connection close and the client reports the broker unavailable.
94
+ */
95
+ function failed(socket, request, error, aborted) {
96
+ const accounting = error instanceof EngineBrokerTurnFailure ? error.accounting : undefined;
97
+ if (accounting === undefined) {
98
+ socket.destroy();
99
+ return;
100
+ }
101
+ const code = error instanceof EngineBrokerTurnFailure ? error.code : aborted ? "cancelled" : "engine_failed";
102
+ send(socket, { version: request.version, kind: "failed", requestId: request.requestId, turnId: request.turnId, code, ...(error instanceof EngineBrokerTurnFailure && error.diagnostic ? { diagnostic: error.diagnostic } : {}), ...(error instanceof EngineBrokerTurnFailure && error.mcpCalls ? { mcpCalls: error.mcpCalls } : {}), outcome: "failed", usage: accounting.usage, model: accounting.model, requests: accounting.requests, limitReason: accounting.limitReason });
103
+ }
104
+ /** One grant verb per connection, answered and closed; any failure becomes a closed-code refusal and never touches turn state. */
105
+ function serveInferenceGrant(socket, broker, request) {
106
+ const refuse = (code) => send(socket, { version: request.version, kind: "inference_grant_refused", requestId: request.requestId, code });
107
+ try {
108
+ if (request.kind === "release_inference_grant") {
109
+ if (!broker.releaseInferenceGrant)
110
+ return refuse("unavailable");
111
+ return send(socket, { version: request.version, kind: "inference_grant_released", requestId: request.requestId, grantId: request.grantId, released: broker.releaseInferenceGrant(request.grantId) });
112
+ }
113
+ if (!broker.requestInferenceGrant)
114
+ return refuse("unavailable");
115
+ const grant = broker.requestInferenceGrant({ model: request.model, reasoningEffort: request.reasoningEffort, purpose: request.purpose });
116
+ send(socket, { version: request.version, kind: "inference_grant", requestId: request.requestId, grantId: grant.grantId, token: grant.token, baseUrl: GROK_INFERENCE_PROXY_BASE_URL, model: grant.policy.model, reasoningEffort: grant.policy.reasoningEffort, purpose: grant.purpose, expiresAt: new Date(grant.expiresAt).toISOString(), limits: grant.limits });
117
+ }
118
+ catch (error) {
119
+ refuse(error instanceof GrokInferenceGrantRefused ? error.code : "unavailable");
120
+ }
121
+ }
122
+ function send(socket, response) { if (!socket.destroyed)
123
+ socket.end(encodeEngineBrokerFrame(response)); }
124
+ async function removeOwnedSocket(file, uid) { try {
125
+ const entry = await lstat(file);
126
+ if (!entry.isSocket() || Number(entry.uid) !== uid)
127
+ throw new Error("unsafe broker socket");
128
+ await unlink(file);
129
+ }
130
+ catch (error) {
131
+ if (error.code !== "ENOENT")
132
+ throw error;
133
+ } }
134
+ async function verifySocket(file, uid) { const entry = await lstat(file); if (!entry.isSocket() || Number(entry.uid) !== uid || (Number(entry.mode) & 0o777) !== 0o600)
135
+ throw new Error("unsafe broker socket"); }
136
+ function listen(server, file) { return new Promise((resolve, reject) => { server.once("error", reject); server.listen(file, () => { server.off("error", reject); resolve(); }); }); }
137
+ function closeServer(server, connections) { for (const socket of connections)
138
+ socket.destroy(); return new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve())); }
@@ -0,0 +1,5 @@
1
+ import { parseEngineBrokerServiceConfig } from "./engineBrokerServiceConfig.js";
2
+ export { parseEngineBrokerServiceConfig };
3
+ export declare const ENGINE_BROKER_SERVICE_CONFIG = "/etc/daimon-engine-broker/service.json";
4
+ export declare function runEngineBrokerServiceCli(): Promise<void>;
5
+ //# sourceMappingURL=engineBrokerServiceCli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engineBrokerServiceCli.d.ts","sourceRoot":"","sources":["../../src/runtime/engineBrokerServiceCli.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;AAGhF,OAAO,EAAE,8BAA8B,EAAE,CAAC;AAE1C,eAAO,MAAM,4BAA4B,2CAA2C,CAAC;AAGrF,wBAAsB,yBAAyB,IAAG,OAAO,CAAC,IAAI,CAAC,CAO9D"}
@@ -0,0 +1,32 @@
1
+ import { constants } from "node:fs";
2
+ import { open } from "node:fs/promises";
3
+ import { startEngineBrokerService } from "./engineBrokerService.js";
4
+ import { parseEngineBrokerServiceConfig } from "./engineBrokerServiceConfig.js";
5
+ import { startGrokEngineBroker } from "./grokEngineBroker.js";
6
+ export { parseEngineBrokerServiceConfig };
7
+ export const ENGINE_BROKER_SERVICE_CONFIG = "/etc/daimon-engine-broker/service.json";
8
+ const MAX_CONFIG_BYTES = 65_536;
9
+ export async function runEngineBrokerServiceCli() {
10
+ if (process.getuid?.() !== 2100)
11
+ throw new Error("engine broker service requires broker identity");
12
+ const config = parseEngineBrokerServiceConfig(await readRootConfig(ENGINE_BROKER_SERVICE_CONFIG));
13
+ const broker = await startGrokEngineBroker({ grokCommand: "/usr/local/bin/grok", nativeClient: "/opt/daimon/bin/daimon-engine-broker", credentialHome: config.credentialHome, turnStore: config.turnStore, registrations: config.registrations, ...(config.inferenceLedgerPath === undefined ? {} : { inferenceLedgerPath: config.inferenceLedgerPath }) });
14
+ const service = await startEngineBrokerService(broker);
15
+ let stopping;
16
+ const stop = () => { stopping ??= service.close(); return stopping; };
17
+ const onSignal = () => { void stop().catch(() => { process.exitCode = 1; }); };
18
+ process.once("SIGINT", onSignal);
19
+ process.once("SIGTERM", onSignal);
20
+ }
21
+ async function readRootConfig(file) { const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW); try {
22
+ const stat = await handle.stat();
23
+ if (!stat.isFile() || stat.uid !== 0 || stat.gid !== 2100 || (stat.mode & 0o777) !== 0o440 || stat.size < 2 || stat.size > MAX_CONFIG_BYTES)
24
+ throw new Error("unsafe engine broker service config");
25
+ const bytes = await handle.readFile();
26
+ if (bytes.length > MAX_CONFIG_BYTES)
27
+ throw new Error("unsafe engine broker service config");
28
+ return JSON.parse(bytes.toString("utf8"));
29
+ }
30
+ finally {
31
+ await handle.close();
32
+ } }
@@ -0,0 +1,50 @@
1
+ import { type EngineBrokerTurnLimits } from "./engineBrokerTurnAccounting.js";
2
+ import { type GrokBrokerModelPolicy } from "./grokBrokerModelPolicy.js";
3
+ export declare const ENGINE_BROKER_SERVICE_V1: "noopolis.daimon.engine-broker-service.v1";
4
+ export declare const ENGINE_BROKER_SERVICE_V2: "noopolis.daimon.engine-broker-service.v2";
5
+ /** One root-provisioned broker slot. Every field is fixed at provisioning time; a wake can only lower `limits`. */
6
+ export type EngineBrokerServiceRegistration = Readonly<{
7
+ agentId: string;
8
+ slot: number;
9
+ workerUid: number;
10
+ workspace: string;
11
+ profilePath: string;
12
+ eventsPath: string;
13
+ profileSha256: string;
14
+ /** Per-slot usage ledger the broker appends turn rows to; per-request rows go to `requests.jsonl` and per-turn seals to `turns.jsonl` beside it. */
15
+ usageLedgerPath: string;
16
+ limits: EngineBrokerTurnLimits;
17
+ model: GrokBrokerModelPolicy;
18
+ }>;
19
+ /**
20
+ * `inferenceLedgerPath` (v2, optional) is where evaluator inference grants
21
+ * append their rows (`inferenceUsageLedger.ts`). Without it the broker refuses
22
+ * every grant request. It can never be a subject ledger: not any
23
+ * registration's usage ledger or its `requests.jsonl`, and not the container
24
+ * ledger the wake fuse sums.
25
+ */
26
+ export type EngineBrokerServiceConfig = Readonly<{
27
+ credentialHome: string;
28
+ turnStore: string;
29
+ registrations: readonly EngineBrokerServiceRegistration[];
30
+ inferenceLedgerPath?: string;
31
+ }>;
32
+ /** The per-request stream written beside a registration's usage ledger. */
33
+ export declare const engineBrokerRequestLedgerPathFor: (usageLedgerPath: string) => string;
34
+ /**
35
+ * The per-turn seal stream written beside the other two
36
+ * (`engineBrokerSealLedger.ts`): the operator-visible half of a sealed terminal
37
+ * response, for the turn whose response never reaches a client.
38
+ */
39
+ export declare const engineBrokerSealLedgerPathFor: (usageLedgerPath: string) => string;
40
+ /**
41
+ * Strict `service.json` parser.
42
+ *
43
+ * v2 requires every registration to declare its usage ledger, limits and model
44
+ * (`model.id`/`model.reasoningEffort` from the closed lists); unknown keys at
45
+ * any level are refused. v1 is still accepted and receives today's defaults:
46
+ * the container ledger, {@link DEFAULT_GROK_BROKER_TURN_LIMITS}, and
47
+ * `grok-4.6`/`low`.
48
+ */
49
+ export declare function parseEngineBrokerServiceConfig(value: unknown): EngineBrokerServiceConfig;
50
+ //# sourceMappingURL=engineBrokerServiceConfig.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engineBrokerServiceConfig.d.ts","sourceRoot":"","sources":["../../src/runtime/engineBrokerServiceConfig.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgE,KAAK,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AAC5I,OAAO,EAAuF,KAAK,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAK7J,eAAO,MAAM,wBAAwB,EAAG,0CAAmD,CAAC;AAC5F,eAAO,MAAM,wBAAwB,EAAG,0CAAmD,CAAC;AAE5F,mHAAmH;AACnH,MAAM,MAAM,+BAA+B,GAAG,QAAQ,CAAC;IACrD,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IACpI,oJAAoJ;IACpJ,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,sBAAsB,CAAC;IAC/B,KAAK,EAAE,qBAAqB,CAAC;CAC9B,CAAC,CAAC;AACH;;;;;;GAMG;AACH,MAAM,MAAM,yBAAyB,GAAG,QAAQ,CAAC;IAAE,cAAc,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,SAAS,+BAA+B,EAAE,CAAC;IAAC,mBAAmB,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAczL,2EAA2E;AAC3E,eAAO,MAAM,gCAAgC,GAAI,iBAAiB,MAAM,KAAG,MAAgF,CAAC;AAE5J;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,GAAI,iBAAiB,MAAM,KAAG,MAA6E,CAAC;AAEtJ;;;;;;;;GAQG;AACH,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,OAAO,GAAG,yBAAyB,CA6BxF"}
@@ -0,0 +1,92 @@
1
+ import path from "node:path";
2
+ import { DEFAULT_GROK_BROKER_TURN_LIMITS, parseEngineBrokerTurnLimits } from "./engineBrokerTurnAccounting.js";
3
+ import { DEFAULT_GROK_BROKER_MODEL_POLICY, GROK_BROKER_MODELS, GROK_BROKER_REASONING_EFFORTS } from "./grokBrokerModelPolicy.js";
4
+ import { grokWorkerEventsPathFor } from "./grokWorkerSandboxProfile.js";
5
+ import { TURN_REQUEST_LEDGER } from "./turnRequestLedger.js";
6
+ import { TURN_USAGE_LEDGER } from "./turnUsageLedger.js";
7
+ export const ENGINE_BROKER_SERVICE_V1 = "noopolis.daimon.engine-broker-service.v1";
8
+ export const ENGINE_BROKER_SERVICE_V2 = "noopolis.daimon.engine-broker-service.v2";
9
+ const V1_REGISTRATION = ["agentId", "slot", "workerUid", "workspace", "profilePath", "eventsPath", "profileSha256"];
10
+ const V2_REGISTRATION = [...V1_REGISTRATION, "usageLedgerPath", "limits", "model"];
11
+ const invalid = () => new TypeError("invalid engine broker service config");
12
+ const plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13
+ const exact = (value, fields) => { if (Object.keys(value).length !== fields.length || fields.some((field) => !Object.hasOwn(value, field)))
14
+ throw invalid(); };
15
+ /**
16
+ * Absolute and canonical: no `.`/`..`/empty components and no trailing slash.
17
+ * The native launcher derives HOME, GROK_HOME and TMPDIR from the registered
18
+ * home and refuses a non-canonical one, so the broker's view must match it.
19
+ */
20
+ const absolute = (item) => typeof item === "string" && item.length > 1 && item.startsWith("/") && !item.endsWith("/") && path.posix.normalize(item) === item && !item.split("/").slice(1).some((part) => part === "." || part === "..") && !item.includes("\0");
21
+ /** The per-request stream written beside a registration's usage ledger. */
22
+ export const engineBrokerRequestLedgerPathFor = (usageLedgerPath) => path.posix.join(path.posix.dirname(usageLedgerPath), "requests.jsonl");
23
+ /**
24
+ * The per-turn seal stream written beside the other two
25
+ * (`engineBrokerSealLedger.ts`): the operator-visible half of a sealed terminal
26
+ * response, for the turn whose response never reaches a client.
27
+ */
28
+ export const engineBrokerSealLedgerPathFor = (usageLedgerPath) => path.posix.join(path.posix.dirname(usageLedgerPath), "turns.jsonl");
29
+ /**
30
+ * Strict `service.json` parser.
31
+ *
32
+ * v2 requires every registration to declare its usage ledger, limits and model
33
+ * (`model.id`/`model.reasoningEffort` from the closed lists); unknown keys at
34
+ * any level are refused. v1 is still accepted and receives today's defaults:
35
+ * the container ledger, {@link DEFAULT_GROK_BROKER_TURN_LIMITS}, and
36
+ * `grok-4.6`/`low`.
37
+ */
38
+ export function parseEngineBrokerServiceConfig(value) {
39
+ if (!plain(value))
40
+ throw invalid();
41
+ const v2 = value.version === ENGINE_BROKER_SERVICE_V2;
42
+ if (!v2 && value.version !== ENGINE_BROKER_SERVICE_V1)
43
+ throw invalid();
44
+ const top = ["version", "credentialHome", "turnStore", "registrations"];
45
+ exact(value, v2 && Object.hasOwn(value, "inferenceLedgerPath") ? [...top, "inferenceLedgerPath"] : top);
46
+ if (!absolute(value.credentialHome) || !absolute(value.turnStore) || !Array.isArray(value.registrations) || value.registrations.length === 0)
47
+ throw invalid();
48
+ const seen = new Set(), slots = new Set();
49
+ const registrations = value.registrations.map((entry) => {
50
+ if (!plain(entry))
51
+ throw invalid();
52
+ exact(entry, v2 ? V2_REGISTRATION : V1_REGISTRATION);
53
+ const { agentId, slot, workerUid, workspace, profilePath, eventsPath, profileSha256 } = entry;
54
+ if (typeof agentId !== "string" || !agentId.trim() || seen.has(agentId) || !Number.isSafeInteger(slot) || slot < 0 || slots.has(slot) || !Number.isSafeInteger(workerUid) || workerUid < 2200 || !absolute(workspace) || !absolute(profilePath) || !absolute(eventsPath) || typeof profileSha256 !== "string" || !/^[a-f0-9]{64}$/u.test(profileSha256) || eventsPath !== grokWorkerEventsPathFor(profilePath) || !profilePath.endsWith("/sandbox.toml"))
55
+ throw invalid();
56
+ seen.add(agentId);
57
+ slots.add(slot);
58
+ const base = { agentId, slot: slot, workerUid: workerUid, workspace, profilePath, eventsPath, profileSha256 };
59
+ if (!v2)
60
+ return { ...base, usageLedgerPath: TURN_USAGE_LEDGER.filePath, limits: DEFAULT_GROK_BROKER_TURN_LIMITS, model: DEFAULT_GROK_BROKER_MODEL_POLICY };
61
+ const usageLedgerPath = entry.usageLedgerPath;
62
+ if (!ledgerPath(usageLedgerPath) || usageLedgerPath === engineBrokerRequestLedgerPathFor(usageLedgerPath) || usageLedgerPath === engineBrokerSealLedgerPathFor(usageLedgerPath))
63
+ throw invalid();
64
+ let limits;
65
+ try {
66
+ limits = parseEngineBrokerTurnLimits(entry.limits);
67
+ }
68
+ catch {
69
+ throw invalid();
70
+ }
71
+ return { ...base, usageLedgerPath, limits, model: parseServiceModel(entry.model) };
72
+ });
73
+ const base = { credentialHome: value.credentialHome, turnStore: value.turnStore, registrations };
74
+ if (!Object.hasOwn(value, "inferenceLedgerPath"))
75
+ return base;
76
+ const inferenceLedgerPath = value.inferenceLedgerPath;
77
+ if (!ledgerPath(inferenceLedgerPath))
78
+ throw invalid();
79
+ const subject = new Set([TURN_USAGE_LEDGER.filePath, TURN_REQUEST_LEDGER.filePath, ...registrations.flatMap((entry) => [entry.usageLedgerPath, engineBrokerRequestLedgerPathFor(entry.usageLedgerPath), engineBrokerSealLedgerPathFor(entry.usageLedgerPath)])]);
80
+ if (subject.has(inferenceLedgerPath))
81
+ throw invalid();
82
+ return { ...base, inferenceLedgerPath };
83
+ }
84
+ const ledgerPath = (item) => absolute(item) && item.endsWith(".jsonl") && path.posix.normalize(item) === item;
85
+ function parseServiceModel(value) {
86
+ if (!plain(value))
87
+ throw invalid();
88
+ exact(value, ["id", "reasoningEffort"]);
89
+ if (!GROK_BROKER_MODELS.includes(value.id) || !GROK_BROKER_REASONING_EFFORTS.includes(value.reasoningEffort))
90
+ throw invalid();
91
+ return Object.freeze({ model: value.id, reasoningEffort: value.reasoningEffort });
92
+ }
@@ -0,0 +1,13 @@
1
+ export declare class EngineBrokerSingleflight<T> {
2
+ private active;
3
+ run(operation: () => Promise<T>): Promise<T>;
4
+ }
5
+ export declare class EngineBrokerGenerationFence {
6
+ private generation;
7
+ private stale;
8
+ restore(generation: number): void;
9
+ snapshot(): number;
10
+ promote(expected: number): number;
11
+ markStale(): void;
12
+ }
13
+ //# sourceMappingURL=engineBrokerSingleflight.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engineBrokerSingleflight.d.ts","sourceRoot":"","sources":["../../src/runtime/engineBrokerSingleflight.ts"],"names":[],"mappings":"AAAA,qBAAa,wBAAwB,CAAC,CAAC;IACrC,OAAO,CAAC,MAAM,CAAyB;IACvC,GAAG,CAAC,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAM7C;AAED,qBAAa,2BAA2B;IACtC,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,UAAU,EAAC,MAAM,GAAE,IAAI;IAC/B,QAAQ,IAAI,MAAM;IAClB,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM;IACjC,SAAS,IAAI,IAAI;CAClB"}
@@ -0,0 +1,24 @@
1
+ export class EngineBrokerSingleflight {
2
+ active;
3
+ run(operation) {
4
+ if (this.active !== undefined)
5
+ return this.active;
6
+ const current = operation();
7
+ this.active = current;
8
+ void current.then(() => { if (this.active === current)
9
+ this.active = undefined; }, () => { if (this.active === current)
10
+ this.active = undefined; });
11
+ return current;
12
+ }
13
+ }
14
+ export class EngineBrokerGenerationFence {
15
+ generation = 0;
16
+ stale = false;
17
+ restore(generation) { if (this.stale || this.generation !== 0 || !Number.isSafeInteger(generation) || generation < 0)
18
+ throw new Error("broker credential generation conflict"); this.generation = generation; }
19
+ snapshot() { if (this.stale)
20
+ throw new Error("broker credential authority is stale"); return this.generation; }
21
+ promote(expected) { if (this.stale || expected !== this.generation)
22
+ throw new Error("broker credential generation conflict"); return ++this.generation; }
23
+ markStale() { this.stale = true; }
24
+ }
@@ -0,0 +1,76 @@
1
+ import type { GrokBrokerModel } from "./grokBrokerModelPolicy.js";
2
+ /**
3
+ * Numeric-only accounting the Grok engine broker seals beside every terminal
4
+ * turn response, and the per-turn limits it enforces.
5
+ *
6
+ * The broker is the single writer of this data (turn registry record, control
7
+ * response, usage ledger row). Nothing engine-controlled and non-numeric is
8
+ * persisted: `model` is a member of the closed declared list, never the
9
+ * provider's own string, and `limitReason` is a closed vocabulary.
10
+ *
11
+ * Buckets are disjoint and `total = input + cacheRead + cacheWrite + output`.
12
+ * `reasoning` is reported only when the source separates it; it is already
13
+ * inside `output` and never added to `total`.
14
+ */
15
+ export type EngineBrokerTurnUsage = Readonly<{
16
+ input: number;
17
+ cacheRead: number;
18
+ cacheWrite: number;
19
+ output: number;
20
+ total: number;
21
+ reasoning?: number;
22
+ }>;
23
+ export declare const ENGINE_BROKER_LIMIT_REASONS: readonly ["tokens", "requests", "timeout", "none"];
24
+ export type EngineBrokerLimitReason = (typeof ENGINE_BROKER_LIMIT_REASONS)[number];
25
+ export type EngineBrokerTurnLimits = Readonly<{
26
+ maxRequests: number;
27
+ maxTokens: number;
28
+ timeoutMs: number;
29
+ }>;
30
+ export type EngineBrokerTurnLimitOverrides = Readonly<Partial<EngineBrokerTurnLimits>>;
31
+ export type EngineBrokerTurnAccounting = Readonly<{
32
+ outcome: "completed" | "failed";
33
+ usage: EngineBrokerTurnUsage | null;
34
+ model: GrokBrokerModel;
35
+ requests: number;
36
+ limitReason: EngineBrokerLimitReason;
37
+ }>;
38
+ /**
39
+ * Bounds every declared limit must sit inside, and the v1 defaults, both from
40
+ * the runtime contract manifest. `maxRequests` stays at or below the
41
+ * launcher's compiled `--max-turns` backstop, so the broker ceiling is the one
42
+ * that fires first.
43
+ */
44
+ export declare const ENGINE_BROKER_LIMIT_BOUNDS: {
45
+ readonly maxRequests: readonly [1, 48];
46
+ readonly maxTokens: readonly [1, 10000000];
47
+ readonly timeoutMs: readonly [1000, 3600000];
48
+ };
49
+ /** What a v1 `service.json` registration gets; equal to the Codex per-wake defaults. */
50
+ export declare const DEFAULT_GROK_BROKER_TURN_LIMITS: EngineBrokerTurnLimits;
51
+ type JsonRecord = Record<string, unknown>;
52
+ /** Exactly `{maxRequests, maxTokens, timeoutMs}`, each inside its bound. */
53
+ export declare function parseEngineBrokerTurnLimits(value: unknown, label?: string): EngineBrokerTurnLimits;
54
+ /** A non-empty subset of the limit keys, each inside its bound. */
55
+ export declare function parseEngineBrokerTurnLimitOverrides(value: unknown, label?: string): EngineBrokerTurnLimitOverrides;
56
+ /**
57
+ * The limits one turn runs under: the registration's, lowered by the wake.
58
+ * A wake can never raise a declared limit; asking to is refused rather than
59
+ * clamped, so a misconfigured caller learns it instead of silently getting less.
60
+ */
61
+ export declare function lowerEngineBrokerTurnLimits(declared: EngineBrokerTurnLimits, overrides: EngineBrokerTurnLimitOverrides | undefined): EngineBrokerTurnLimits;
62
+ /** Four disjoint buckets plus an optional reasoning split; the total invariant is re-checked. */
63
+ export declare function parseEngineBrokerTurnUsage(value: unknown, label?: string): EngineBrokerTurnUsage;
64
+ export declare const sumEngineBrokerTurnUsage: (items: readonly EngineBrokerTurnUsage[]) => EngineBrokerTurnUsage | null;
65
+ /** Validates the accounting members of a v2 terminal response against its kind. */
66
+ export declare function parseEngineBrokerTurnAccounting(value: JsonRecord, kind: "completed" | "failed"): EngineBrokerTurnAccounting;
67
+ /**
68
+ * Maps a provider-reported model key onto the declared closed-list model.
69
+ *
70
+ * Grok 1.0.34 reports `grok-4.6` usage under `grok-4.6-build` (P0). The exact
71
+ * declared id and its `-build` alias are accepted; anything else is a
72
+ * different model and yields `undefined`.
73
+ */
74
+ export declare const mapGrokReportedModel: (reported: string, declared: GrokBrokerModel) => GrokBrokerModel | undefined;
75
+ export {};
76
+ //# sourceMappingURL=engineBrokerTurnAccounting.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engineBrokerTurnAccounting.d.ts","sourceRoot":"","sources":["../../src/runtime/engineBrokerTurnAccounting.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAElE;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,qBAAqB,GAAG,QAAQ,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAC1J,eAAO,MAAM,2BAA2B,oDAA6C,CAAC;AACtF,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,2BAA2B,CAAC,CAAC,MAAM,CAAC,CAAC;AACnF,MAAM,MAAM,sBAAsB,GAAG,QAAQ,CAAC;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAC7G,MAAM,MAAM,8BAA8B,GAAG,QAAQ,CAAC,OAAO,CAAC,sBAAsB,CAAC,CAAC,CAAC;AACvF,MAAM,MAAM,0BAA0B,GAAG,QAAQ,CAAC;IAChD,OAAO,EAAE,WAAW,GAAG,QAAQ,CAAC;IAChC,KAAK,EAAE,qBAAqB,GAAG,IAAI,CAAC;IACpC,KAAK,EAAE,eAAe,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,uBAAuB,CAAC;CACtC,CAAC,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B;;;;CAAuC,CAAC;AAE/E,wFAAwF;AACxF,eAAO,MAAM,+BAA+B,EAAE,sBAAuF,CAAC;AAGtI,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAY1C,4EAA4E;AAC5E,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,SAA8B,GAAG,sBAAsB,CAGvH;AAED,mEAAmE;AACnE,wBAAgB,mCAAmC,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,SAA8B,GAAG,8BAA8B,CAKvI;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,sBAAsB,EAAE,SAAS,EAAE,8BAA8B,GAAG,SAAS,GAAG,sBAAsB,CAO3J;AAED,iGAAiG;AACjG,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,SAA6B,GAAG,qBAAqB,CAUpH;AAED,eAAO,MAAM,wBAAwB,GAAI,OAAO,SAAS,qBAAqB,EAAE,KAAG,qBAAqB,GAAG,IAK1G,CAAC;AAEF,mFAAmF;AACnF,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,WAAW,GAAG,QAAQ,GAAG,0BAA0B,CAS3H;AAED;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,GAAI,UAAU,MAAM,EAAE,UAAU,eAAe,KAAG,eAAe,GAAG,SACnB,CAAC"}
@@ -0,0 +1,108 @@
1
+ import { GROK_BROKER_MODELS } from "../contracts/grokWorkerContract.js";
2
+ import { GROK_ENGINE_BROKER } from "../contracts/runtimeContractManifest.js";
3
+ export const ENGINE_BROKER_LIMIT_REASONS = GROK_ENGINE_BROKER.turnLimits.limitReasons;
4
+ /**
5
+ * Bounds every declared limit must sit inside, and the v1 defaults, both from
6
+ * the runtime contract manifest. `maxRequests` stays at or below the
7
+ * launcher's compiled `--max-turns` backstop, so the broker ceiling is the one
8
+ * that fires first.
9
+ */
10
+ export const ENGINE_BROKER_LIMIT_BOUNDS = GROK_ENGINE_BROKER.turnLimits.bounds;
11
+ /** What a v1 `service.json` registration gets; equal to the Codex per-wake defaults. */
12
+ export const DEFAULT_GROK_BROKER_TURN_LIMITS = Object.freeze({ ...GROK_ENGINE_BROKER.turnLimits.v1Defaults });
13
+ const LIMIT_KEYS = ["maxRequests", "maxTokens", "timeoutMs"];
14
+ const plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
15
+ const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
16
+ const invalid = (label) => new TypeError(`invalid ${label}`);
17
+ const limitValue = (key, value, label) => {
18
+ const [minimum, maximum] = ENGINE_BROKER_LIMIT_BOUNDS[key];
19
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum || value > maximum)
20
+ throw invalid(label);
21
+ return value;
22
+ };
23
+ /** Exactly `{maxRequests, maxTokens, timeoutMs}`, each inside its bound. */
24
+ export function parseEngineBrokerTurnLimits(value, label = "engine broker turn limits") {
25
+ if (!plain(value) || Object.keys(value).length !== LIMIT_KEYS.length || LIMIT_KEYS.some((key) => !Object.hasOwn(value, key)))
26
+ throw invalid(label);
27
+ return Object.freeze({ maxRequests: limitValue("maxRequests", value.maxRequests, label), maxTokens: limitValue("maxTokens", value.maxTokens, label), timeoutMs: limitValue("timeoutMs", value.timeoutMs, label) });
28
+ }
29
+ /** A non-empty subset of the limit keys, each inside its bound. */
30
+ export function parseEngineBrokerTurnLimitOverrides(value, label = "engine broker turn limits") {
31
+ if (!plain(value) || Object.keys(value).length === 0 || Object.keys(value).some((key) => !LIMIT_KEYS.includes(key)))
32
+ throw invalid(label);
33
+ const result = {};
34
+ for (const key of LIMIT_KEYS)
35
+ if (Object.hasOwn(value, key))
36
+ result[key] = limitValue(key, value[key], label);
37
+ return Object.freeze(result);
38
+ }
39
+ /**
40
+ * The limits one turn runs under: the registration's, lowered by the wake.
41
+ * A wake can never raise a declared limit; asking to is refused rather than
42
+ * clamped, so a misconfigured caller learns it instead of silently getting less.
43
+ */
44
+ export function lowerEngineBrokerTurnLimits(declared, overrides) {
45
+ if (overrides === undefined)
46
+ return declared;
47
+ for (const key of LIMIT_KEYS) {
48
+ const requested = overrides[key];
49
+ if (requested !== undefined && requested > declared[key])
50
+ throw new RangeError(`engine broker turn limit ${key} may only be lowered`);
51
+ }
52
+ return Object.freeze({ maxRequests: overrides.maxRequests ?? declared.maxRequests, maxTokens: overrides.maxTokens ?? declared.maxTokens, timeoutMs: overrides.timeoutMs ?? declared.timeoutMs });
53
+ }
54
+ /** Four disjoint buckets plus an optional reasoning split; the total invariant is re-checked. */
55
+ export function parseEngineBrokerTurnUsage(value, label = "engine broker turn usage") {
56
+ const required = ["input", "cacheRead", "cacheWrite", "output", "total"];
57
+ if (!plain(value))
58
+ throw invalid(label);
59
+ const keys = Object.keys(value);
60
+ if (required.some((key) => !Object.hasOwn(value, key)) || keys.some((key) => !required.includes(key) && key !== "reasoning"))
61
+ throw invalid(label);
62
+ if (![value.input, value.cacheRead, value.cacheWrite, value.output, value.total].every(count))
63
+ throw invalid(label);
64
+ const usage = value;
65
+ if (usage.total !== usage.input + usage.cacheRead + usage.cacheWrite + usage.output)
66
+ throw invalid(label);
67
+ if (usage.reasoning !== undefined && (!count(usage.reasoning) || usage.reasoning > usage.output))
68
+ throw invalid(label);
69
+ return Object.freeze({ input: usage.input, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite, output: usage.output, total: usage.total, ...(usage.reasoning === undefined ? {} : { reasoning: usage.reasoning }) });
70
+ }
71
+ export const sumEngineBrokerTurnUsage = (items) => {
72
+ if (items.length === 0)
73
+ return null;
74
+ const sum = (pick) => items.reduce((total, usage) => total + pick(usage), 0);
75
+ const reasoning = items.every((usage) => usage.reasoning !== undefined) ? { reasoning: sum((usage) => usage.reasoning ?? 0) } : {};
76
+ return Object.freeze({ input: sum((usage) => usage.input), cacheRead: sum((usage) => usage.cacheRead), cacheWrite: sum((usage) => usage.cacheWrite), output: sum((usage) => usage.output), total: sum((usage) => usage.total), ...reasoning });
77
+ };
78
+ /** Validates the accounting members of a v2 terminal response against its kind. */
79
+ export function parseEngineBrokerTurnAccounting(value, kind) {
80
+ if (value.outcome !== kind)
81
+ throw invalid("broker frame");
82
+ if (!GROK_BROKER_MODELS.includes(value.model))
83
+ throw invalid("broker frame");
84
+ if (!count(value.requests) || value.requests > 1_024)
85
+ throw invalid("broker frame");
86
+ if (!ENGINE_BROKER_LIMIT_REASONS.includes(value.limitReason))
87
+ throw invalid("broker frame");
88
+ if (kind === "completed" && value.limitReason !== "none")
89
+ throw invalid("broker frame");
90
+ let usage = null;
91
+ if (value.usage !== null) {
92
+ try {
93
+ usage = parseEngineBrokerTurnUsage(value.usage);
94
+ }
95
+ catch {
96
+ throw invalid("broker frame");
97
+ }
98
+ }
99
+ return { outcome: kind, usage, model: value.model, requests: value.requests, limitReason: value.limitReason };
100
+ }
101
+ /**
102
+ * Maps a provider-reported model key onto the declared closed-list model.
103
+ *
104
+ * Grok 1.0.34 reports `grok-4.6` usage under `grok-4.6-build` (P0). The exact
105
+ * declared id and its `-build` alias are accepted; anything else is a
106
+ * different model and yields `undefined`.
107
+ */
108
+ export const mapGrokReportedModel = (reported, declared) => reported === declared || reported === `${declared}-build` ? declared : undefined;
@@ -0,0 +1,57 @@
1
+ import { type EngineBrokerRequest, type EngineBrokerTerminalResponse } from "./engineBrokerProtocol.js";
2
+ import type { GrokBrokerModel } from "./grokBrokerModelPolicy.js";
3
+ import { type BrokerTurnLedgerLines } from "./grokEngineBrokerLedger.js";
4
+ type Start = Extract<EngineBrokerRequest, {
5
+ kind: "start_turn";
6
+ }>;
7
+ type Terminal = EngineBrokerTerminalResponse;
8
+ export declare const ENGINE_BROKER_TURN_RECORD_V1: "noopolis.daimon.engine-broker-turn.v1";
9
+ export declare const ENGINE_BROKER_TURN_RECORD_V2: "noopolis.daimon.engine-broker-turn.v2";
10
+ type Observed = Readonly<{
11
+ version: typeof ENGINE_BROKER_TURN_RECORD_V1 | typeof ENGINE_BROKER_TURN_RECORD_V2;
12
+ digest: string;
13
+ state: "active" | "terminal";
14
+ bootId: string;
15
+ response?: Terminal;
16
+ ledger?: BrokerTurnLedgerLines;
17
+ }>;
18
+ /**
19
+ * Durable per-turn state. Record v2 stores the terminal response *with* its
20
+ * sealed accounting (usage, outcome, model, requests, limitReason), so a replay
21
+ * returns exactly what was metered and never meters again: metering happens
22
+ * only on the path that returned `"start"`.
23
+ */
24
+ export declare class EngineBrokerTurnRegistry {
25
+ private readonly root;
26
+ private readonly bootId;
27
+ private readonly syncDirectoryOf;
28
+ /** `syncDirectoryOf` is injectable only so the post-publish failure path can be exercised under test. */
29
+ constructor(root: string, bootId?: string, syncDirectoryOf?: (directory: string) => Promise<void>);
30
+ /** `model` is the registration's declared model, used only to upgrade a v1 record on replay. */
31
+ begin(request: Start, model: GrokBrokerModel): Promise<"start" | {
32
+ replay: Terminal;
33
+ ledger: BrokerTurnLedgerLines;
34
+ }>;
35
+ /**
36
+ * `ledger` is the exact ledger bytes this turn owes, sealed with it so a replay can finish an interrupted append.
37
+ *
38
+ * The rename is the publish point. A failure before it rejects (nothing was
39
+ * published); a failure after it — the directory fsync — must not, because
40
+ * the terminal record is already the visible truth and a caller that saw a
41
+ * rejection would believe the turn unsealed and write a contradicting
42
+ * record over it. That durability gap is reported as `directorySynced: false`
43
+ * instead: the record is published but may not survive a power loss.
44
+ */
45
+ finish(request: Start, response: Terminal, ledger?: BrokerTurnLedgerLines): Promise<Readonly<{
46
+ directorySynced: boolean;
47
+ }>>;
48
+ }
49
+ /**
50
+ * Strict record parser. v2 accepts exactly `{version,digest,state,bootId}`
51
+ * plus `response` and its sealed `ledger` bytes when terminal, and the response must be a v2 terminal frame.
52
+ * v1 records keep their historical looser shape and are upgraded on read: no
53
+ * usage (`null`), zero requests, `limitReason: "none"`, the declared model.
54
+ */
55
+ export declare function parseEngineBrokerTurnRecord(text: string, model: GrokBrokerModel): Observed;
56
+ export {};
57
+ //# sourceMappingURL=engineBrokerTurnRegistry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engineBrokerTurnRegistry.d.ts","sourceRoot":"","sources":["../../src/runtime/engineBrokerTurnRegistry.ts"],"names":[],"mappings":"AAIA,OAAO,EAAkE,KAAK,mBAAmB,EAAE,KAAK,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AACxK,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAwD,KAAK,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAE/H,KAAK,KAAK,GAAG,OAAO,CAAC,mBAAmB,EAAE;IAAE,IAAI,EAAE,YAAY,CAAA;CAAE,CAAC,CAAC;AAClE,KAAK,QAAQ,GAAG,4BAA4B,CAAC;AAC7C,eAAO,MAAM,4BAA4B,EAAG,uCAAgD,CAAC;AAC7F,eAAO,MAAM,4BAA4B,EAAG,uCAAgD,CAAC;AAK7F,KAAK,QAAQ,GAAG,QAAQ,CAAC;IAAE,OAAO,EAAE,OAAO,4BAA4B,GAAG,OAAO,4BAA4B,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,QAAQ,GAAG,UAAU,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAAC,MAAM,CAAC,EAAE,qBAAqB,CAAA;CAAE,CAAC,CAAC;AAEpO;;;;;GAKG;AACH,qBAAa,wBAAwB;IAEvB,OAAO,CAAC,QAAQ,CAAC,IAAI;IAAS,OAAO,CAAC,QAAQ,CAAC,MAAM;IAAqB,OAAO,CAAC,QAAQ,CAAC,eAAe;IADtH,yGAAyG;gBAC5E,IAAI,EAAE,MAAM,EAAkB,MAAM,GAAC,MAAmB,EAAkB,eAAe,GAAC,CAAC,SAAS,EAAC,MAAM,KAAG,OAAO,CAAC,IAAI,CAAe;IACtK,gGAAgG;IAC1F,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,GAAG;QAAE,MAAM,EAAE,QAAQ,CAAC;QAAC,MAAM,EAAE,qBAAqB,CAAA;KAAE,CAAC;IAW3H;;;;;;;;;OASG;IACG,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,GAAE,qBAAgD,GAAG,OAAO,CAAC,QAAQ,CAAC;QAAE,eAAe,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAO5J;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,GAAG,QAAQ,CAyB1F"}