@noopolis/daimon 0.1.2 → 0.2.1

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 (422) hide show
  1. package/README.md +275 -51
  2. package/dist/contracts/attentionContract.d.ts +142 -0
  3. package/dist/contracts/attentionContract.d.ts.map +1 -0
  4. package/dist/contracts/attentionContract.js +21 -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/grokBrokerTaskClock.d.ts +18 -0
  9. package/dist/contracts/grokBrokerTaskClock.d.ts.map +1 -0
  10. package/dist/contracts/grokBrokerTaskClock.js +16 -0
  11. package/dist/contracts/grokWorkerContract.d.ts +74 -0
  12. package/dist/contracts/grokWorkerContract.d.ts.map +1 -0
  13. package/dist/contracts/grokWorkerContract.js +88 -0
  14. package/dist/contracts/organizationRuntimeContract.d.ts +841 -0
  15. package/dist/contracts/organizationRuntimeContract.d.ts.map +1 -0
  16. package/dist/contracts/organizationRuntimeContract.js +123 -0
  17. package/dist/contracts/runtimeContractManifest.d.ts +1822 -0
  18. package/dist/contracts/runtimeContractManifest.d.ts.map +1 -0
  19. package/dist/contracts/runtimeContractManifest.js +206 -0
  20. package/dist/contracts/shellEnvironmentPolicy.d.ts +3 -0
  21. package/dist/contracts/shellEnvironmentPolicy.d.ts.map +1 -0
  22. package/dist/contracts/shellEnvironmentPolicy.js +5 -0
  23. package/dist/contracts/wakeMomentContract.d.ts +61 -0
  24. package/dist/contracts/wakeMomentContract.d.ts.map +1 -0
  25. package/dist/contracts/wakeMomentContract.js +27 -0
  26. package/dist/core/credentialRedaction.d.ts +4 -0
  27. package/dist/core/credentialRedaction.d.ts.map +1 -0
  28. package/dist/core/credentialRedaction.js +28 -0
  29. package/dist/core/types.d.ts +2 -0
  30. package/dist/core/types.d.ts.map +1 -1
  31. package/dist/examples/jungianPlayAgent.d.ts +1 -0
  32. package/dist/examples/jungianPlayAgent.d.ts.map +1 -1
  33. package/dist/examples/jungianPlayAgent.js +6 -2
  34. package/dist/mcp/toolServer.d.ts +19 -2
  35. package/dist/mcp/toolServer.d.ts.map +1 -1
  36. package/dist/mcp/toolServer.js +57 -17
  37. package/dist/observability/causalEvents.d.ts +6 -6
  38. package/dist/observability/causalEvents.d.ts.map +1 -1
  39. package/dist/observability/causalEvents.js +107 -19
  40. package/dist/observability/orgObserver.d.ts.map +1 -1
  41. package/dist/observability/orgObserver.js +3 -3
  42. package/dist/pi/agyHeadlessResult.d.ts +60 -0
  43. package/dist/pi/agyHeadlessResult.d.ts.map +1 -0
  44. package/dist/pi/agyHeadlessResult.js +95 -0
  45. package/dist/pi/cliChildOutput.d.ts +67 -0
  46. package/dist/pi/cliChildOutput.d.ts.map +1 -0
  47. package/dist/pi/cliChildOutput.js +269 -0
  48. package/dist/pi/cliEngineRun.d.ts +16 -0
  49. package/dist/pi/cliEngineRun.d.ts.map +1 -0
  50. package/dist/pi/cliEngineRun.js +27 -0
  51. package/dist/pi/cliEngineSpawn.d.ts +55 -0
  52. package/dist/pi/cliEngineSpawn.d.ts.map +1 -0
  53. package/dist/pi/cliEngineSpawn.js +169 -0
  54. package/dist/pi/cliEnvironment.d.ts +12 -0
  55. package/dist/pi/cliEnvironment.d.ts.map +1 -0
  56. package/dist/pi/cliEnvironment.js +34 -0
  57. package/dist/pi/cliMcpRegistration.d.ts +61 -0
  58. package/dist/pi/cliMcpRegistration.d.ts.map +1 -0
  59. package/dist/pi/cliMcpRegistration.js +75 -0
  60. package/dist/pi/cliProcess.d.ts +7 -0
  61. package/dist/pi/cliProcess.d.ts.map +1 -0
  62. package/dist/pi/cliProcess.js +132 -0
  63. package/dist/pi/cliSession.d.ts +86 -24
  64. package/dist/pi/cliSession.d.ts.map +1 -1
  65. package/dist/pi/cliSession.js +251 -173
  66. package/dist/pi/cliSessionMcp.d.ts +9 -0
  67. package/dist/pi/cliSessionMcp.d.ts.map +1 -0
  68. package/dist/pi/cliSessionMcp.js +80 -0
  69. package/dist/pi/cliTurnMetering.d.ts +60 -0
  70. package/dist/pi/cliTurnMetering.d.ts.map +1 -0
  71. package/dist/pi/cliTurnMetering.js +60 -0
  72. package/dist/pi/codexFilesystemRules.d.ts +3 -0
  73. package/dist/pi/codexFilesystemRules.d.ts.map +1 -0
  74. package/dist/pi/codexFilesystemRules.js +28 -0
  75. package/dist/pi/codexHeadlessResult.d.ts +68 -0
  76. package/dist/pi/codexHeadlessResult.d.ts.map +1 -0
  77. package/dist/pi/codexHeadlessResult.js +122 -0
  78. package/dist/pi/codexRolloutUsage.d.ts +95 -0
  79. package/dist/pi/codexRolloutUsage.d.ts.map +1 -0
  80. package/dist/pi/codexRolloutUsage.js +221 -0
  81. package/dist/pi/engineTaskClock.d.ts +9 -0
  82. package/dist/pi/engineTaskClock.d.ts.map +1 -0
  83. package/dist/pi/engineTaskClock.js +28 -0
  84. package/dist/pi/engineWakeLimits.d.ts +39 -0
  85. package/dist/pi/engineWakeLimits.d.ts.map +1 -0
  86. package/dist/pi/engineWakeLimits.js +55 -0
  87. package/dist/pi/grokHeadlessResult.d.ts +36 -0
  88. package/dist/pi/grokHeadlessResult.d.ts.map +1 -0
  89. package/dist/pi/grokHeadlessResult.js +118 -0
  90. package/dist/pi/grokHomeMcpRegistration.d.ts +21 -0
  91. package/dist/pi/grokHomeMcpRegistration.d.ts.map +1 -0
  92. package/dist/pi/grokHomeMcpRegistration.js +58 -0
  93. package/dist/pi/grokSandbox.d.ts +11 -0
  94. package/dist/pi/grokSandbox.d.ts.map +1 -0
  95. package/dist/pi/grokSandbox.js +216 -0
  96. package/dist/pi/grokStreamUsage.d.ts +31 -0
  97. package/dist/pi/grokStreamUsage.d.ts.map +1 -0
  98. package/dist/pi/grokStreamUsage.js +51 -0
  99. package/dist/pi/memoryClock.d.ts +25 -0
  100. package/dist/pi/memoryClock.d.ts.map +1 -0
  101. package/dist/pi/memoryClock.js +18 -0
  102. package/dist/pi/piAgentHandle.d.ts +6 -3
  103. package/dist/pi/piAgentHandle.d.ts.map +1 -1
  104. package/dist/pi/piAgentHandle.js +42 -12
  105. package/dist/pi/piAgentWakeSupport.d.ts +35 -0
  106. package/dist/pi/piAgentWakeSupport.d.ts.map +1 -1
  107. package/dist/pi/piAgentWakeSupport.js +4 -0
  108. package/dist/pi/piHarness.d.ts +18 -3
  109. package/dist/pi/piHarness.d.ts.map +1 -1
  110. package/dist/pi/piHarness.js +83 -14
  111. package/dist/pi/prompts.d.ts +1 -0
  112. package/dist/pi/prompts.d.ts.map +1 -1
  113. package/dist/pi/prompts.js +24 -0
  114. package/dist/pi/taskClockProcess.d.ts +6 -0
  115. package/dist/pi/taskClockProcess.d.ts.map +1 -0
  116. package/dist/pi/taskClockProcess.js +8 -0
  117. package/dist/pi/turnCausal.d.ts +4 -2
  118. package/dist/pi/turnCausal.d.ts.map +1 -1
  119. package/dist/pi/turnCausal.js +4 -4
  120. package/dist/pi/turnTrace.d.ts.map +1 -1
  121. package/dist/pi/turnTrace.js +5 -8
  122. package/dist/pi/wakeAcceptance.d.ts +1 -1
  123. package/dist/pi/wakeAcceptance.d.ts.map +1 -1
  124. package/dist/pi/wakeAcceptance.js +2 -2
  125. package/dist/pi/worldTrajectory.d.ts +1 -1
  126. package/dist/pi/worldTrajectory.d.ts.map +1 -1
  127. package/dist/pi/worldTrajectory.js +3 -3
  128. package/dist/runtime/agySubscriptionBootstrap.d.ts +16 -0
  129. package/dist/runtime/agySubscriptionBootstrap.d.ts.map +1 -0
  130. package/dist/runtime/agySubscriptionBootstrap.js +80 -0
  131. package/dist/runtime/agySubscriptionRealm.d.ts +38 -0
  132. package/dist/runtime/agySubscriptionRealm.d.ts.map +1 -0
  133. package/dist/runtime/agySubscriptionRealm.js +242 -0
  134. package/dist/runtime/attention.d.ts +26 -0
  135. package/dist/runtime/attention.d.ts.map +1 -0
  136. package/dist/runtime/attention.js +49 -0
  137. package/dist/runtime/attentionDispatcher.d.ts +78 -0
  138. package/dist/runtime/attentionDispatcher.d.ts.map +1 -0
  139. package/dist/runtime/attentionDispatcher.js +365 -0
  140. package/dist/runtime/cli.d.ts +7 -0
  141. package/dist/runtime/cli.d.ts.map +1 -0
  142. package/dist/runtime/cli.js +256 -0
  143. package/dist/runtime/codexSandboxProjection.d.ts +17 -0
  144. package/dist/runtime/codexSandboxProjection.d.ts.map +1 -0
  145. package/dist/runtime/codexSandboxProjection.js +40 -0
  146. package/dist/runtime/contract-manifest.json +1 -0
  147. package/dist/runtime/contract-manifest.sha256 +1 -0
  148. package/dist/runtime/contractManifest.d.ts +8 -0
  149. package/dist/runtime/contractManifest.d.ts.map +1 -0
  150. package/dist/runtime/contractManifest.js +4 -0
  151. package/dist/runtime/engineBrokerCapabilities.d.ts +40 -0
  152. package/dist/runtime/engineBrokerCapabilities.d.ts.map +1 -0
  153. package/dist/runtime/engineBrokerCapabilities.js +69 -0
  154. package/dist/runtime/engineBrokerControlClient.d.ts +55 -0
  155. package/dist/runtime/engineBrokerControlClient.d.ts.map +1 -0
  156. package/dist/runtime/engineBrokerControlClient.js +228 -0
  157. package/dist/runtime/engineBrokerCredentialJournal.d.ts +12 -0
  158. package/dist/runtime/engineBrokerCredentialJournal.d.ts.map +1 -0
  159. package/dist/runtime/engineBrokerCredentialJournal.js +26 -0
  160. package/dist/runtime/engineBrokerInferenceProtocol.d.ts +53 -0
  161. package/dist/runtime/engineBrokerInferenceProtocol.d.ts.map +1 -0
  162. package/dist/runtime/engineBrokerInferenceProtocol.js +65 -0
  163. package/dist/runtime/engineBrokerMcpCallLog.d.ts +171 -0
  164. package/dist/runtime/engineBrokerMcpCallLog.d.ts.map +1 -0
  165. package/dist/runtime/engineBrokerMcpCallLog.js +231 -0
  166. package/dist/runtime/engineBrokerMcpFacade.d.ts +59 -0
  167. package/dist/runtime/engineBrokerMcpFacade.d.ts.map +1 -0
  168. package/dist/runtime/engineBrokerMcpFacade.js +346 -0
  169. package/dist/runtime/engineBrokerNativeClient.d.ts +52 -0
  170. package/dist/runtime/engineBrokerNativeClient.d.ts.map +1 -0
  171. package/dist/runtime/engineBrokerNativeClient.js +151 -0
  172. package/dist/runtime/engineBrokerProtocol.d.ts +167 -0
  173. package/dist/runtime/engineBrokerProtocol.d.ts.map +1 -0
  174. package/dist/runtime/engineBrokerProtocol.js +357 -0
  175. package/dist/runtime/engineBrokerSealLedger.d.ts +70 -0
  176. package/dist/runtime/engineBrokerSealLedger.d.ts.map +1 -0
  177. package/dist/runtime/engineBrokerSealLedger.js +132 -0
  178. package/dist/runtime/engineBrokerService.d.ts +43 -0
  179. package/dist/runtime/engineBrokerService.d.ts.map +1 -0
  180. package/dist/runtime/engineBrokerService.js +196 -0
  181. package/dist/runtime/engineBrokerServiceCli.d.ts +5 -0
  182. package/dist/runtime/engineBrokerServiceCli.d.ts.map +1 -0
  183. package/dist/runtime/engineBrokerServiceCli.js +32 -0
  184. package/dist/runtime/engineBrokerServiceConfig.d.ts +55 -0
  185. package/dist/runtime/engineBrokerServiceConfig.d.ts.map +1 -0
  186. package/dist/runtime/engineBrokerServiceConfig.js +130 -0
  187. package/dist/runtime/engineBrokerSingleflight.d.ts +13 -0
  188. package/dist/runtime/engineBrokerSingleflight.d.ts.map +1 -0
  189. package/dist/runtime/engineBrokerSingleflight.js +24 -0
  190. package/dist/runtime/engineBrokerTurnAccounting.d.ts +76 -0
  191. package/dist/runtime/engineBrokerTurnAccounting.d.ts.map +1 -0
  192. package/dist/runtime/engineBrokerTurnAccounting.js +108 -0
  193. package/dist/runtime/engineBrokerTurnRegistry.d.ts +57 -0
  194. package/dist/runtime/engineBrokerTurnRegistry.d.ts.map +1 -0
  195. package/dist/runtime/engineBrokerTurnRegistry.js +159 -0
  196. package/dist/runtime/engineDispatcher.d.ts +38 -0
  197. package/dist/runtime/engineDispatcher.d.ts.map +1 -0
  198. package/dist/runtime/engineDispatcher.js +228 -0
  199. package/dist/runtime/engineReadiness.d.ts +23 -0
  200. package/dist/runtime/engineReadiness.d.ts.map +1 -0
  201. package/dist/runtime/engineReadiness.js +222 -0
  202. package/dist/runtime/grokAuthenticationError.d.ts +8 -0
  203. package/dist/runtime/grokAuthenticationError.d.ts.map +1 -0
  204. package/dist/runtime/grokAuthenticationError.js +20 -0
  205. package/dist/runtime/grokBrokerCredentialAuthority.d.ts +23 -0
  206. package/dist/runtime/grokBrokerCredentialAuthority.d.ts.map +1 -0
  207. package/dist/runtime/grokBrokerCredentialAuthority.js +150 -0
  208. package/dist/runtime/grokBrokerCredentialReader.d.ts +6 -0
  209. package/dist/runtime/grokBrokerCredentialReader.d.ts.map +1 -0
  210. package/dist/runtime/grokBrokerCredentialReader.js +38 -0
  211. package/dist/runtime/grokBrokerModelPolicy.d.ts +23 -0
  212. package/dist/runtime/grokBrokerModelPolicy.d.ts.map +1 -0
  213. package/dist/runtime/grokBrokerModelPolicy.js +28 -0
  214. package/dist/runtime/grokBrokerProjection.d.ts +114 -0
  215. package/dist/runtime/grokBrokerProjection.d.ts.map +1 -0
  216. package/dist/runtime/grokBrokerProjection.js +101 -0
  217. package/dist/runtime/grokBrokerProviderClock.d.ts +26 -0
  218. package/dist/runtime/grokBrokerProviderClock.d.ts.map +1 -0
  219. package/dist/runtime/grokBrokerProviderClock.js +133 -0
  220. package/dist/runtime/grokBrokerProxy.d.ts +69 -0
  221. package/dist/runtime/grokBrokerProxy.d.ts.map +1 -0
  222. package/dist/runtime/grokBrokerProxy.js +326 -0
  223. package/dist/runtime/grokBrokerProxyJson.d.ts +10 -0
  224. package/dist/runtime/grokBrokerProxyJson.d.ts.map +1 -0
  225. package/dist/runtime/grokBrokerProxyJson.js +31 -0
  226. package/dist/runtime/grokBrokerProxyRequest.d.ts +30 -0
  227. package/dist/runtime/grokBrokerProxyRequest.d.ts.map +1 -0
  228. package/dist/runtime/grokBrokerProxyRequest.js +85 -0
  229. package/dist/runtime/grokBrokerRealmLease.d.ts +4 -0
  230. package/dist/runtime/grokBrokerRealmLease.d.ts.map +1 -0
  231. package/dist/runtime/grokBrokerRealmLease.js +33 -0
  232. package/dist/runtime/grokBrokerRefresh.d.ts +2 -0
  233. package/dist/runtime/grokBrokerRefresh.d.ts.map +1 -0
  234. package/dist/runtime/grokBrokerRefresh.js +15 -0
  235. package/dist/runtime/grokBrokerRunBudget.d.ts +20 -0
  236. package/dist/runtime/grokBrokerRunBudget.d.ts.map +1 -0
  237. package/dist/runtime/grokBrokerRunBudget.js +85 -0
  238. package/dist/runtime/grokBrokerSlot.d.ts +6 -0
  239. package/dist/runtime/grokBrokerSlot.d.ts.map +1 -0
  240. package/dist/runtime/grokBrokerSlot.js +21 -0
  241. package/dist/runtime/grokBrokerTaskClock.d.ts +32 -0
  242. package/dist/runtime/grokBrokerTaskClock.d.ts.map +1 -0
  243. package/dist/runtime/grokBrokerTaskClock.js +120 -0
  244. package/dist/runtime/grokBrokerTurnMeter.d.ts +180 -0
  245. package/dist/runtime/grokBrokerTurnMeter.d.ts.map +1 -0
  246. package/dist/runtime/grokBrokerTurnMeter.js +337 -0
  247. package/dist/runtime/grokBrokerWorkerConfig.d.ts +89 -0
  248. package/dist/runtime/grokBrokerWorkerConfig.d.ts.map +1 -0
  249. package/dist/runtime/grokBrokerWorkerConfig.js +154 -0
  250. package/dist/runtime/grokEngineBroker.d.ts +88 -0
  251. package/dist/runtime/grokEngineBroker.d.ts.map +1 -0
  252. package/dist/runtime/grokEngineBroker.js +202 -0
  253. package/dist/runtime/grokEngineBrokerLedger.d.ts +52 -0
  254. package/dist/runtime/grokEngineBrokerLedger.d.ts.map +1 -0
  255. package/dist/runtime/grokEngineBrokerLedger.js +114 -0
  256. package/dist/runtime/grokEngineBrokerMetering.d.ts +51 -0
  257. package/dist/runtime/grokEngineBrokerMetering.d.ts.map +1 -0
  258. package/dist/runtime/grokEngineBrokerMetering.js +34 -0
  259. package/dist/runtime/grokEngineBrokerTurn.d.ts +82 -0
  260. package/dist/runtime/grokEngineBrokerTurn.d.ts.map +1 -0
  261. package/dist/runtime/grokEngineBrokerTurn.js +348 -0
  262. package/dist/runtime/grokEngineBrokerTurnEnd.d.ts +88 -0
  263. package/dist/runtime/grokEngineBrokerTurnEnd.d.ts.map +1 -0
  264. package/dist/runtime/grokEngineBrokerTurnEnd.js +148 -0
  265. package/dist/runtime/grokInferenceClientConfig.d.ts +41 -0
  266. package/dist/runtime/grokInferenceClientConfig.d.ts.map +1 -0
  267. package/dist/runtime/grokInferenceClientConfig.js +62 -0
  268. package/dist/runtime/grokInferenceGrants.d.ts +77 -0
  269. package/dist/runtime/grokInferenceGrants.d.ts.map +1 -0
  270. package/dist/runtime/grokInferenceGrants.js +116 -0
  271. package/dist/runtime/grokInferenceProxy.d.ts +29 -0
  272. package/dist/runtime/grokInferenceProxy.d.ts.map +1 -0
  273. package/dist/runtime/grokInferenceProxy.js +85 -0
  274. package/dist/runtime/grokInferenceProxyRequest.d.ts +23 -0
  275. package/dist/runtime/grokInferenceProxyRequest.d.ts.map +1 -0
  276. package/dist/runtime/grokInferenceProxyRequest.js +63 -0
  277. package/dist/runtime/grokSlotPreflightReceipt.d.ts +70 -0
  278. package/dist/runtime/grokSlotPreflightReceipt.d.ts.map +1 -0
  279. package/dist/runtime/grokSlotPreflightReceipt.js +101 -0
  280. package/dist/runtime/grokSubscriptionRealm.d.ts +4 -0
  281. package/dist/runtime/grokSubscriptionRealm.d.ts.map +1 -0
  282. package/dist/runtime/grokSubscriptionRealm.js +435 -0
  283. package/dist/runtime/grokSubscriptionRealmTypes.d.ts +26 -0
  284. package/dist/runtime/grokSubscriptionRealmTypes.d.ts.map +1 -0
  285. package/dist/runtime/grokSubscriptionRealmTypes.js +1 -0
  286. package/dist/runtime/grokWorkerAttestation.d.ts +175 -0
  287. package/dist/runtime/grokWorkerAttestation.d.ts.map +1 -0
  288. package/dist/runtime/grokWorkerAttestation.js +266 -0
  289. package/dist/runtime/grokWorkerDenyPlacement.d.ts +80 -0
  290. package/dist/runtime/grokWorkerDenyPlacement.d.ts.map +1 -0
  291. package/dist/runtime/grokWorkerDenyPlacement.js +128 -0
  292. package/dist/runtime/grokWorkerHomeAttestation.d.ts +32 -0
  293. package/dist/runtime/grokWorkerHomeAttestation.d.ts.map +1 -0
  294. package/dist/runtime/grokWorkerHomeAttestation.js +75 -0
  295. package/dist/runtime/grokWorkerSandboxProfile.d.ts +27 -0
  296. package/dist/runtime/grokWorkerSandboxProfile.d.ts.map +1 -0
  297. package/dist/runtime/grokWorkerSandboxProfile.js +44 -0
  298. package/dist/runtime/grokWorkerTmpAttestation.d.ts +55 -0
  299. package/dist/runtime/grokWorkerTmpAttestation.d.ts.map +1 -0
  300. package/dist/runtime/grokWorkerTmpAttestation.js +63 -0
  301. package/dist/runtime/index.d.ts +31 -0
  302. package/dist/runtime/index.d.ts.map +1 -0
  303. package/dist/runtime/index.js +27 -0
  304. package/dist/runtime/inferenceUsageLedger.d.ts +38 -0
  305. package/dist/runtime/inferenceUsageLedger.d.ts.map +1 -0
  306. package/dist/runtime/inferenceUsageLedger.js +53 -0
  307. package/dist/runtime/mcpToolResult.d.ts +127 -0
  308. package/dist/runtime/mcpToolResult.d.ts.map +1 -0
  309. package/dist/runtime/mcpToolResult.js +214 -0
  310. package/dist/runtime/moltnetMachineRead.d.ts +97 -0
  311. package/dist/runtime/moltnetMachineRead.d.ts.map +1 -0
  312. package/dist/runtime/moltnetMachineRead.js +183 -0
  313. package/dist/runtime/native/daimon-engine-broker +0 -0
  314. package/dist/runtime/organizationRuntime.d.ts +168 -0
  315. package/dist/runtime/organizationRuntime.d.ts.map +1 -0
  316. package/dist/runtime/organizationRuntime.js +3 -0
  317. package/dist/runtime/organizationRuntimeAdmission.d.ts +6 -0
  318. package/dist/runtime/organizationRuntimeAdmission.d.ts.map +1 -0
  319. package/dist/runtime/organizationRuntimeAdmission.js +22 -0
  320. package/dist/runtime/organizationRuntimeControl.d.ts +51 -0
  321. package/dist/runtime/organizationRuntimeControl.d.ts.map +1 -0
  322. package/dist/runtime/organizationRuntimeControl.js +283 -0
  323. package/dist/runtime/organizationRuntimeHost.d.ts +19 -0
  324. package/dist/runtime/organizationRuntimeHost.d.ts.map +1 -0
  325. package/dist/runtime/organizationRuntimeHost.js +368 -0
  326. package/dist/runtime/organizationRuntimeParsing.d.ts +6 -0
  327. package/dist/runtime/organizationRuntimeParsing.d.ts.map +1 -0
  328. package/dist/runtime/organizationRuntimeParsing.js +373 -0
  329. package/dist/runtime/organizationRuntimeReadiness.d.ts +12 -0
  330. package/dist/runtime/organizationRuntimeReadiness.d.ts.map +1 -0
  331. package/dist/runtime/organizationRuntimeReadiness.js +67 -0
  332. package/dist/runtime/organizationRuntimeRecording.d.ts +7 -0
  333. package/dist/runtime/organizationRuntimeRecording.d.ts.map +1 -0
  334. package/dist/runtime/organizationRuntimeRecording.js +58 -0
  335. package/dist/runtime/physicalReadiness.d.ts +59 -0
  336. package/dist/runtime/physicalReadiness.d.ts.map +1 -0
  337. package/dist/runtime/physicalReadiness.js +176 -0
  338. package/dist/runtime/portableCredentialAuth.d.ts +6 -0
  339. package/dist/runtime/portableCredentialAuth.d.ts.map +1 -0
  340. package/dist/runtime/portableCredentialAuth.js +70 -0
  341. package/dist/runtime/portableCredentialMaterial.d.ts +8 -0
  342. package/dist/runtime/portableCredentialMaterial.d.ts.map +1 -0
  343. package/dist/runtime/portableCredentialMaterial.js +169 -0
  344. package/dist/runtime/productionAgentTools.d.ts +5 -0
  345. package/dist/runtime/productionAgentTools.d.ts.map +1 -0
  346. package/dist/runtime/productionAgentTools.js +336 -0
  347. package/dist/runtime/relocateRuntimeConfig.d.ts +14 -0
  348. package/dist/runtime/relocateRuntimeConfig.d.ts.map +1 -0
  349. package/dist/runtime/relocateRuntimeConfig.js +38 -0
  350. package/dist/runtime/runtimeHomeLayout.d.ts +48 -0
  351. package/dist/runtime/runtimeHomeLayout.d.ts.map +1 -0
  352. package/dist/runtime/runtimeHomeLayout.js +84 -0
  353. package/dist/runtime/schedule.d.ts +40 -0
  354. package/dist/runtime/schedule.d.ts.map +1 -0
  355. package/dist/runtime/schedule.js +376 -0
  356. package/dist/runtime/storeCoordination.d.ts +33 -0
  357. package/dist/runtime/storeCoordination.d.ts.map +1 -0
  358. package/dist/runtime/storeCoordination.js +117 -0
  359. package/dist/runtime/taskClock.d.ts +42 -0
  360. package/dist/runtime/taskClock.d.ts.map +1 -0
  361. package/dist/runtime/taskClock.js +102 -0
  362. package/dist/runtime/taskClockProcess.d.ts +17 -0
  363. package/dist/runtime/taskClockProcess.d.ts.map +1 -0
  364. package/dist/runtime/taskClockProcess.js +58 -0
  365. package/dist/runtime/toolResultSpill.d.ts +152 -0
  366. package/dist/runtime/toolResultSpill.d.ts.map +1 -0
  367. package/dist/runtime/toolResultSpill.js +351 -0
  368. package/dist/runtime/turnRequestLedger.d.ts +155 -0
  369. package/dist/runtime/turnRequestLedger.d.ts.map +1 -0
  370. package/dist/runtime/turnRequestLedger.js +251 -0
  371. package/dist/runtime/turnUsageLedger.d.ts +143 -0
  372. package/dist/runtime/turnUsageLedger.d.ts.map +1 -0
  373. package/dist/runtime/turnUsageLedger.js +203 -0
  374. package/dist/runtime/wakeAcceptanceClaimDiagnostics.d.ts +34 -0
  375. package/dist/runtime/wakeAcceptanceClaimDiagnostics.d.ts.map +1 -0
  376. package/dist/runtime/wakeAcceptanceClaimDiagnostics.js +79 -0
  377. package/dist/runtime/wakeAcceptanceIndex.d.ts +55 -0
  378. package/dist/runtime/wakeAcceptanceIndex.d.ts.map +1 -0
  379. package/dist/runtime/wakeAcceptanceIndex.js +158 -0
  380. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts +25 -0
  381. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts.map +1 -0
  382. package/dist/runtime/wakeAcceptanceProcessIdentity.js +54 -0
  383. package/dist/runtime/wakeAcceptanceReconciliation.d.ts +211 -0
  384. package/dist/runtime/wakeAcceptanceReconciliation.d.ts.map +1 -0
  385. package/dist/runtime/wakeAcceptanceReconciliation.js +289 -0
  386. package/dist/runtime/wakeAcceptanceRecord.d.ts +25 -0
  387. package/dist/runtime/wakeAcceptanceRecord.d.ts.map +1 -0
  388. package/dist/runtime/wakeAcceptanceRecord.js +58 -0
  389. package/dist/runtime/wakeAcceptanceRetention.d.ts +36 -0
  390. package/dist/runtime/wakeAcceptanceRetention.d.ts.map +1 -0
  391. package/dist/runtime/wakeAcceptanceRetention.js +38 -0
  392. package/dist/runtime/wakeAcceptanceStore.d.ts +113 -0
  393. package/dist/runtime/wakeAcceptanceStore.d.ts.map +1 -0
  394. package/dist/runtime/wakeAcceptanceStore.js +561 -0
  395. package/dist/runtime/wakeAcceptanceTypes.d.ts +179 -0
  396. package/dist/runtime/wakeAcceptanceTypes.d.ts.map +1 -0
  397. package/dist/runtime/wakeAcceptanceTypes.js +95 -0
  398. package/dist/runtime/wakeFuse.d.ts +124 -0
  399. package/dist/runtime/wakeFuse.d.ts.map +1 -0
  400. package/dist/runtime/wakeFuse.js +466 -0
  401. package/dist/runtime/wakeMomentFs.d.ts +27 -0
  402. package/dist/runtime/wakeMomentFs.d.ts.map +1 -0
  403. package/dist/runtime/wakeMomentFs.js +223 -0
  404. package/dist/runtime/wakeMomentHistory.d.ts +26 -0
  405. package/dist/runtime/wakeMomentHistory.d.ts.map +1 -0
  406. package/dist/runtime/wakeMomentHistory.js +109 -0
  407. package/dist/runtime/wakeMomentIo.d.ts +22 -0
  408. package/dist/runtime/wakeMomentIo.d.ts.map +1 -0
  409. package/dist/runtime/wakeMomentIo.js +114 -0
  410. package/dist/runtime/wakeMomentRecorder.d.ts +33 -0
  411. package/dist/runtime/wakeMomentRecorder.d.ts.map +1 -0
  412. package/dist/runtime/wakeMomentRecorder.js +81 -0
  413. package/dist/runtime/wakeMomentRetention.d.ts +7 -0
  414. package/dist/runtime/wakeMomentRetention.d.ts.map +1 -0
  415. package/dist/runtime/wakeMomentRetention.js +143 -0
  416. package/dist/runtime/wakeMomentRows.d.ts +8 -0
  417. package/dist/runtime/wakeMomentRows.d.ts.map +1 -0
  418. package/dist/runtime/wakeMomentRows.js +66 -0
  419. package/dist/runtime/wakeMomentSnapshot.d.ts +56 -0
  420. package/dist/runtime/wakeMomentSnapshot.d.ts.map +1 -0
  421. package/dist/runtime/wakeMomentSnapshot.js +248 -0
  422. package/package.json +22 -11
@@ -0,0 +1,150 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createHash } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { mkdir, open, rename, unlink } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { readGrokBrokerCredential } from "./grokBrokerCredentialReader.js";
7
+ import { refreshGrokBrokerCredential } from "./grokBrokerRefresh.js";
8
+ import { EngineBrokerGenerationFence, EngineBrokerSingleflight } from "./engineBrokerSingleflight.js";
9
+ import { BROKER_CREDENTIAL_MAX_ANCESTORS, parseBrokerCredentialJournal, recoverBrokerCredentialJournal } from "./engineBrokerCredentialJournal.js";
10
+ export class DurableGrokBrokerCredentialAuthority {
11
+ command;
12
+ home;
13
+ authFile;
14
+ flight = new EngineBrokerSingleflight();
15
+ fence = new EngineBrokerGenerationFence();
16
+ stale = false;
17
+ initialized = false;
18
+ staleWrite;
19
+ lastDigest;
20
+ generation = 0;
21
+ ancestorDigests = [];
22
+ constructor(command, home, authFile = path.join(home, "auth.json")) {
23
+ this.command = command;
24
+ this.home = home;
25
+ this.authFile = authFile;
26
+ }
27
+ async initialize() {
28
+ if (this.initialized)
29
+ return;
30
+ const credential = await readGrokBrokerCredential(this.authFile);
31
+ this.lastDigest = credential.digest;
32
+ const file = path.join(this.home, ".daimon-broker", "credential-journal.json");
33
+ let handle;
34
+ try {
35
+ handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
36
+ const stat = await handle.stat();
37
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size > 65536)
38
+ throw unavailable();
39
+ const journal = parseBrokerCredentialJournal(JSON.parse(await handle.readFile("utf8")));
40
+ this.generation = journal.generation;
41
+ if (recoverBrokerCredentialJournal(journal, credential.digest) === "stale") {
42
+ await this.markStale();
43
+ throw unavailable();
44
+ }
45
+ this.ancestorDigests = [...new Set([...(journal.ancestorDigests ?? []), journal.sourceDigest])]
46
+ .filter((digest) => digest !== credential.digest);
47
+ if (journal.state === "refreshing") {
48
+ // The durable credential still matches the pre-exchange source. Settle
49
+ // before serving it so writeback and drain need no subsequent refresh.
50
+ // No exchange completed: preserve the generation and existing lineage.
51
+ await this.write({ state: "promoted", generation: journal.generation,
52
+ sourceDigest: credential.digest, promotedDigest: credential.digest });
53
+ }
54
+ this.fence.restore(journal.generation);
55
+ }
56
+ catch (error) {
57
+ // Only a missing journal on open is an unjournaled bootstrap. A failed
58
+ // recovery write (including ENOENT) must never publish readiness.
59
+ if (handle !== undefined || error.code !== "ENOENT")
60
+ throw unavailable();
61
+ }
62
+ finally {
63
+ await handle?.close().catch(() => undefined);
64
+ }
65
+ this.initialized = true;
66
+ }
67
+ async accessToken(forceRefresh) {
68
+ if (!this.initialized)
69
+ await this.initialize();
70
+ if (this.stale)
71
+ throw unavailable();
72
+ if (!forceRefresh)
73
+ return (await readGrokBrokerCredential(this.authFile)).accessToken;
74
+ return this.refresh();
75
+ }
76
+ async refreshAfterRejection(rejectedTokenDigest) { if (!/^[a-f0-9]{64}$/u.test(rejectedTokenDigest))
77
+ throw unavailable(); return this.refresh(rejectedTokenDigest); }
78
+ refresh(rejectedTokenDigest) {
79
+ return this.flight.run(async () => {
80
+ if (this.stale)
81
+ throw unavailable();
82
+ const generation = this.fence.snapshot();
83
+ const before = await readGrokBrokerCredential(this.authFile);
84
+ if (rejectedTokenDigest !== undefined && createHash("sha256").update(before.accessToken).digest("hex") !== rejectedTokenDigest)
85
+ return before.accessToken;
86
+ // Never spend a refresh whose lineage cannot be persisted. Advancing expiry
87
+ // normally clears the history, so this bound applies to one expiry epoch.
88
+ const ancestors = [...new Set([...this.ancestorDigests, before.digest])];
89
+ if (ancestors.length > BROKER_CREDENTIAL_MAX_ANCESTORS)
90
+ throw unavailable();
91
+ try {
92
+ await this.write({ state: "refreshing", generation, sourceDigest: before.digest });
93
+ await refreshGrokBrokerCredential(this.command, this.home);
94
+ const after = await readGrokBrokerCredential(this.authFile);
95
+ if (after.digest === before.digest)
96
+ throw unavailable();
97
+ const next = this.fence.promote(generation);
98
+ this.generation = next;
99
+ const ancestorDigests = before.expiresAt !== undefined && after.expiresAt !== undefined && after.expiresAt > before.expiresAt ? [] : ancestors;
100
+ await this.write({ state: "promoted", generation: next, sourceDigest: before.digest, promotedDigest: after.digest, ancestorDigests });
101
+ this.ancestorDigests = ancestorDigests;
102
+ this.lastDigest = after.digest;
103
+ return after.accessToken;
104
+ }
105
+ catch {
106
+ await this.markStale();
107
+ throw unavailable();
108
+ }
109
+ });
110
+ }
111
+ async markRejected(rejectedTokenDigest) { if (rejectedTokenDigest !== undefined) {
112
+ if (!/^[a-f0-9]{64}$/u.test(rejectedTokenDigest))
113
+ throw unavailable();
114
+ const current = await readGrokBrokerCredential(this.authFile);
115
+ if (createHash("sha256").update(current.accessToken).digest("hex") !== rejectedTokenDigest)
116
+ throw unavailable();
117
+ } if (!this.stale)
118
+ await this.markStale(); throw unavailable(); }
119
+ isStale() { return this.stale; }
120
+ markStale() { if (this.staleWrite)
121
+ return this.staleWrite; this.stale = true; this.fence.markStale(); return this.staleWrite = (async () => { const rejected = this.lastDigest ?? (await readGrokBrokerCredential(this.authFile)).digest; await this.write({ state: "stale", generation: this.generation, sourceDigest: rejected, promotedDigest: rejected }); })(); }
122
+ async write(value) {
123
+ const root = path.join(this.home, ".daimon-broker");
124
+ await mkdir(root, { recursive: true, mode: 0o700 });
125
+ const file = path.join(root, "credential-journal.json");
126
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
127
+ const handle = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
128
+ try {
129
+ await handle.writeFile(`${JSON.stringify({ version: "noopolis.daimon.broker-credential-journal.v1", ancestorDigests: this.ancestorDigests, ...value })}\n`);
130
+ await handle.sync();
131
+ }
132
+ finally {
133
+ await handle.close();
134
+ }
135
+ try {
136
+ await rename(temporary, file);
137
+ const directory = await open(root, constants.O_RDONLY);
138
+ try {
139
+ await directory.sync();
140
+ }
141
+ finally {
142
+ await directory.close();
143
+ }
144
+ }
145
+ finally {
146
+ await unlink(temporary).catch(() => undefined);
147
+ }
148
+ }
149
+ }
150
+ const unavailable = () => new Error("Grok broker credential authority unavailable");
@@ -0,0 +1,6 @@
1
+ export declare function readGrokBrokerCredential(file: string): Promise<Readonly<{
2
+ accessToken: string;
3
+ digest: string;
4
+ expiresAt?: number;
5
+ }>>;
6
+ //# sourceMappingURL=grokBrokerCredentialReader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerCredentialReader.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerCredentialReader.ts"],"names":[],"mappings":"AAIA,wBAAsB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAW3I"}
@@ -0,0 +1,38 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open } from "node:fs/promises";
4
+ export async function readGrokBrokerCredential(file) {
5
+ let handle;
6
+ let bytes;
7
+ try {
8
+ const before = await lstat(file);
9
+ assertFile(before);
10
+ handle = await open(file, constants.O_RDONLY | noFollow());
11
+ const opened = await handle.stat();
12
+ assertFile(opened);
13
+ if (before.dev !== opened.dev || before.ino !== opened.ino)
14
+ throw new Error();
15
+ bytes = await handle.readFile();
16
+ if (bytes.length > 64 * 1024)
17
+ throw new Error();
18
+ const after = await handle.stat();
19
+ if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs)
20
+ throw new Error();
21
+ const root = JSON.parse(bytes.toString("utf8"));
22
+ const rows = Object.values(root).filter((value) => value !== null && typeof value === "object" && !Array.isArray(value));
23
+ if (rows.length !== 1 || typeof rows[0].key !== "string" || rows[0].key.length < 32 || typeof rows[0].refresh_token !== "string" || rows[0].refresh_token.length < 16)
24
+ throw new Error();
25
+ const expiresAt = typeof rows[0].expires_at === "string" ? Date.parse(rows[0].expires_at) : NaN;
26
+ return { accessToken: rows[0].key, digest: createHash("sha256").update(bytes).digest("hex"), ...(Number.isFinite(expiresAt) ? { expiresAt } : {}) };
27
+ }
28
+ catch {
29
+ throw new Error("Grok broker credential authority unavailable");
30
+ }
31
+ finally {
32
+ bytes?.fill(0);
33
+ await handle?.close().catch(() => undefined);
34
+ }
35
+ }
36
+ function assertFile(entry) { if (!entry.isFile() || entry.isSymbolicLink() || Number(entry.uid) !== process.getuid?.() || Number(entry.nlink) !== 1 || (Number(entry.mode) & 0o777) !== 0o600 || Number(entry.size) < 2 || Number(entry.size) > 64 * 1024)
37
+ throw new Error(); }
38
+ function noFollow() { return constants.O_NOFOLLOW ?? 0; }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The closed model and reasoning-effort vocabulary a Grok broker worker may be
3
+ * declared with.
4
+ *
5
+ * Both halves of one declaration are consumed from this single parser: the
6
+ * worker `config.toml` renderer (`grokBrokerWorkerConfig.ts`) writes them into
7
+ * the worker's only custom model, and the provider proxy
8
+ * (`grokBrokerProxyRequest.ts`) refuses any request body that does not carry
9
+ * exactly them. Nothing is inherited: Grok 1.0.34 silently drops an effort for
10
+ * a model that does not declare effort support, and its embedded catalog
11
+ * default for `grok-4.6` is `high`.
12
+ */
13
+ import { GROK_BROKER_MODELS, GROK_BROKER_REASONING_EFFORTS } from "../contracts/grokWorkerContract.js";
14
+ export { GROK_BROKER_MODELS, GROK_BROKER_REASONING_EFFORTS };
15
+ export type GrokBrokerModel = (typeof GROK_BROKER_MODELS)[number];
16
+ export type GrokBrokerReasoningEffort = (typeof GROK_BROKER_REASONING_EFFORTS)[number];
17
+ export type GrokBrokerModelPolicy = Readonly<{
18
+ model: GrokBrokerModel;
19
+ reasoningEffort: GrokBrokerReasoningEffort;
20
+ }>;
21
+ export declare const DEFAULT_GROK_BROKER_MODEL_POLICY: GrokBrokerModelPolicy;
22
+ export declare function parseGrokBrokerModelPolicy(value?: unknown): GrokBrokerModelPolicy;
23
+ //# sourceMappingURL=grokBrokerModelPolicy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerModelPolicy.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerModelPolicy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AAEvG,OAAO,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,CAAC;AAC7D,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;AAClE,MAAM,MAAM,yBAAyB,GAAG,CAAC,OAAO,6BAA6B,CAAC,CAAC,MAAM,CAAC,CAAC;AACvF,MAAM,MAAM,qBAAqB,GAAG,QAAQ,CAAC;IAAE,KAAK,EAAE,eAAe,CAAC;IAAC,eAAe,EAAE,yBAAyB,CAAA;CAAE,CAAC,CAAC;AAErH,eAAO,MAAM,gCAAgC,EAAE,qBAAoF,CAAC;AAEpI,wBAAgB,0BAA0B,CAAC,KAAK,GAAE,OAAY,GAAG,qBAAqB,CAUrF"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The closed model and reasoning-effort vocabulary a Grok broker worker may be
3
+ * declared with.
4
+ *
5
+ * Both halves of one declaration are consumed from this single parser: the
6
+ * worker `config.toml` renderer (`grokBrokerWorkerConfig.ts`) writes them into
7
+ * the worker's only custom model, and the provider proxy
8
+ * (`grokBrokerProxyRequest.ts`) refuses any request body that does not carry
9
+ * exactly them. Nothing is inherited: Grok 1.0.34 silently drops an effort for
10
+ * a model that does not declare effort support, and its embedded catalog
11
+ * default for `grok-4.6` is `high`.
12
+ */
13
+ import { GROK_BROKER_MODELS, GROK_BROKER_REASONING_EFFORTS } from "../contracts/grokWorkerContract.js";
14
+ export { GROK_BROKER_MODELS, GROK_BROKER_REASONING_EFFORTS };
15
+ export const DEFAULT_GROK_BROKER_MODEL_POLICY = Object.freeze({ model: "grok-4.6", reasoningEffort: "low" });
16
+ export function parseGrokBrokerModelPolicy(value = {}) {
17
+ if (value === null || typeof value !== "object" || Array.isArray(value))
18
+ throw new TypeError("invalid Grok broker model policy");
19
+ const input = value;
20
+ if (Object.keys(input).some((key) => key !== "model" && key !== "reasoningEffort"))
21
+ throw new TypeError("invalid Grok broker model policy");
22
+ const model = input.model ?? DEFAULT_GROK_BROKER_MODEL_POLICY.model;
23
+ const reasoningEffort = input.reasoningEffort ?? DEFAULT_GROK_BROKER_MODEL_POLICY.reasoningEffort;
24
+ if (!GROK_BROKER_MODELS.includes(model) || !GROK_BROKER_REASONING_EFFORTS.includes(reasoningEffort)) {
25
+ throw new TypeError("invalid Grok broker model policy");
26
+ }
27
+ return Object.freeze({ model: model, reasoningEffort: reasoningEffort });
28
+ }
@@ -0,0 +1,114 @@
1
+ import { GROK_BROKER_TASK_CLOCK, type GrokWorkerConfigVariant } from "../contracts/grokBrokerTaskClock.js";
2
+ import { type EngineBrokerServiceRegistration } from "./engineBrokerServiceConfig.js";
3
+ import { type EngineBrokerTurnLimits } from "./engineBrokerTurnAccounting.js";
4
+ import type { GrokBrokerModel, GrokBrokerReasoningEffort } from "./grokBrokerModelPolicy.js";
5
+ import { GROK_WORKER_SANDBOX_PROFILE } from "./grokWorkerSandboxProfile.js";
6
+ export declare const GROK_BROKER_PROJECTION_VERSION: "noopolis.daimon.grok-broker-projection.v3";
7
+ /**
8
+ * Everything a consumer (Spawnfile provisioning, Paideia's native adapter, the
9
+ * root slot supervisor) needs to know about one brokered Grok agent's slot,
10
+ * computed by Daimon from the same renderers and collectors the broker attests
11
+ * against. It never reads credentials, runs a worker, or touches the realm.
12
+ */
13
+ export type OrganizationGrokBrokerProjection = Readonly<{
14
+ version: typeof GROK_BROKER_PROJECTION_VERSION;
15
+ agentId: string;
16
+ workspacePath: string;
17
+ runtimeHomePath: string;
18
+ workerUid: number;
19
+ slot: number;
20
+ profilePath: string;
21
+ profileSha256: string;
22
+ denyPaths: readonly string[];
23
+ workerConfigSha256: string;
24
+ workerConfigVariant: GrokWorkerConfigVariant;
25
+ taskClock?: Omit<typeof GROK_BROKER_TASK_CLOCK, "directoryPath" | "timestampFilePath"> & Readonly<{
26
+ directoryPath: string;
27
+ timestampFilePath: string;
28
+ }>;
29
+ systemPromptSha256: string;
30
+ grokCliVersion: string;
31
+ grokExecutableSha256: string;
32
+ nativeAbiVersion: number;
33
+ model: GrokBrokerModel;
34
+ reasoningEffort: GrokBrokerReasoningEffort;
35
+ limits: EngineBrokerTurnLimits;
36
+ usageLedgerPath: string;
37
+ /** The container seccomp profile the worker must run under (the pinned default-plus-userns profile bubblewrap needs). */
38
+ seccompProfileSha256: string;
39
+ attestation: Readonly<{
40
+ platform: "linux/landlock";
41
+ enforced: true;
42
+ restrictNetwork: true;
43
+ profileName: typeof GROK_WORKER_SANDBOX_PROFILE;
44
+ sandboxRuntime: "bubblewrap";
45
+ eventsPath: string;
46
+ }>;
47
+ }>;
48
+ export type OrganizationGrokBrokerProjectionOptions = Readonly<{
49
+ /** Clocked configs require an isolated clock directory per slot. Defaults to the unchanged production bytes. */
50
+ workerConfigVariant?: GrokWorkerConfigVariant;
51
+ /** Deployment-assigned slot identity. */
52
+ slot: number;
53
+ workerUid: number;
54
+ /** The worker's home; its `GROK_HOME` is `<workerHomePath>/.grok`. */
55
+ workerHomePath: string;
56
+ architecture: "arm64" | "x64";
57
+ usageLedgerPath: string;
58
+ limits: EngineBrokerTurnLimits;
59
+ /**
60
+ * The deny entry that protects the durable wake-acceptance store: the store
61
+ * itself, or a directory containing it.
62
+ *
63
+ * Grok 1.0.34 materializes every deny target inside bubblewrap **as the
64
+ * worker uid**, so a target whose parent directory the worker cannot search
65
+ * is unplaceable and makes Grok refuse the whole profile — every turn of that
66
+ * worker then fails, not just that path. Deployments that keep the store
67
+ * under a private `state` directory (`2000:2000 0700`) therefore declare that
68
+ * directory here: it covers the store, nothing else lives there, and lifting
69
+ * the mask adds the worker no reach, where opening the parent with `o+x`
70
+ * would. The caller is the one party that knows both the layout and the
71
+ * modes; whoever recomputes this projection must pass the same value or the
72
+ * digests will not match, which is the intended fail-closed outcome.
73
+ */
74
+ acceptanceStorePath: string;
75
+ /** Evaluator and host-bind paths the deployment must keep from the worker (R4). */
76
+ denyPaths?: readonly string[];
77
+ /** sha256 of the seccomp profile bytes the deployment runs the worker under. */
78
+ seccompProfileSha256: string;
79
+ /** When the caller already holds a rendered profile digest, it must equal Daimon's. */
80
+ profileSha256?: string;
81
+ }>;
82
+ /**
83
+ * Resolve the public Grok broker projection for one agent.
84
+ *
85
+ * Paths are taken as given, never resolved: the caller (Spawnfile provisioning)
86
+ * must supply canonical, non-symlink paths — the fixed tmpfs/workspace roots it
87
+ * creates — and its provisioning must verify they are not symlinks before a
88
+ * slot is used; the broker's own attestation re-checks the worker home at
89
+ * every turn.
90
+ *
91
+ * Deterministic and I/O-free on purpose: its digest
92
+ * ({@link grokBrokerProjectionSha256}) is what the slot preflight receipt
93
+ * binds, so the supervisor that writes the receipt and the evaluator that reads
94
+ * it must compute byte-equal projections from the same inputs.
95
+ *
96
+ * The agent must be a Grok agent that *declares* its model and reasoning
97
+ * effort; nothing is defaulted. The deny list is Daimon's own protected set for
98
+ * this agent (realm, bootstrap, peers, and the mask covering the acceptance
99
+ * store) plus the caller's evaluator paths, sorted and deduplicated exactly as
100
+ * the profile renderer does. A supplied `profileSha256` that differs is
101
+ * refused.
102
+ */
103
+ export declare function resolveOrganizationGrokBrokerProjection(config: unknown, agentId: string, options: OrganizationGrokBrokerProjectionOptions): OrganizationGrokBrokerProjection;
104
+ /** sha256 over the projection's canonical JSON; what a slot preflight receipt binds. */
105
+ export declare const grokBrokerProjectionSha256: (projection: OrganizationGrokBrokerProjection) => string;
106
+ /** The `service.json` v2 registration a deployment provisions for this projection, validated by the broker's own parser. */
107
+ export declare function grokBrokerServiceRegistrationFor(projection: OrganizationGrokBrokerProjection): Readonly<Record<string, unknown>>;
108
+ /**
109
+ * Refuses a provisioned registration that does not describe this projection:
110
+ * any differing member — a weaker profile digest, another model, raised
111
+ * limits, a different ledger — is a mismatch, never a merge.
112
+ */
113
+ export declare function verifyGrokBrokerRegistrationMatchesProjection(registration: EngineBrokerServiceRegistration, projection: OrganizationGrokBrokerProjection): void;
114
+ //# sourceMappingURL=grokBrokerProjection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerProjection.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerProjection.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,KAAK,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAQ3G,OAAO,EAAkC,KAAK,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACtH,OAAO,EAA+B,KAAK,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AAE3G,OAAO,KAAK,EAAE,eAAe,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAC7F,OAAO,EAAE,2BAA2B,EAA2F,MAAM,+BAA+B,CAAC;AAGrK,eAAO,MAAM,8BAA8B,6CAAuC,CAAC;AAEnF;;;;;GAKG;AACH,MAAM,MAAM,gCAAgC,GAAG,QAAQ,CAAC;IACtD,OAAO,EAAE,OAAO,8BAA8B,CAAC;IAC/C,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B,kBAAkB,EAAE,MAAM,CAAC;IAC3B,mBAAmB,EAAE,uBAAuB,CAAC;IAC7C,SAAS,CAAC,EAAE,IAAI,CAAC,OAAO,sBAAsB,EAAE,eAAe,GAAG,mBAAmB,CAAC,GAAG,QAAQ,CAAC;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,iBAAiB,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxJ,kBAAkB,EAAE,MAAM,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC;IACvB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,gBAAgB,EAAE,MAAM,CAAC;IACzB,KAAK,EAAE,eAAe,CAAC;IACvB,eAAe,EAAE,yBAAyB,CAAC;IAC3C,MAAM,EAAE,sBAAsB,CAAC;IAC/B,eAAe,EAAE,MAAM,CAAC;IACxB,yHAAyH;IACzH,oBAAoB,EAAE,MAAM,CAAC;IAC7B,WAAW,EAAE,QAAQ,CAAC;QAAE,QAAQ,EAAE,gBAAgB,CAAC;QAAC,QAAQ,EAAE,IAAI,CAAC;QAAC,eAAe,EAAE,IAAI,CAAC;QAAC,WAAW,EAAE,OAAO,2BAA2B,CAAC;QAAC,cAAc,EAAE,YAAY,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACjM,CAAC,CAAC;AAEH,MAAM,MAAM,uCAAuC,GAAG,QAAQ,CAAC;IAC7D,gHAAgH;IAChH,mBAAmB,CAAC,EAAE,uBAAuB,CAAC;IAC9C,yCAAyC;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,OAAO,GAAG,KAAK,CAAC;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,sBAAsB,CAAC;IAC/B;;;;;;;;;;;;;;OAcG;IACH,mBAAmB,EAAE,MAAM,CAAC;IAC5B,mFAAmF;IACnF,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,gFAAgF;IAChF,oBAAoB,EAAE,MAAM,CAAC;IAC7B,uFAAuF;IACvF,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,uCAAuC,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,uCAAuC,GAAG,gCAAgC,CAkC5K;AAED,wFAAwF;AACxF,eAAO,MAAM,0BAA0B,GAAI,YAAY,gCAAgC,KAAG,MACpB,CAAC;AAEvE,4HAA4H;AAC5H,wBAAgB,gCAAgC,CAAC,UAAU,EAAE,gCAAgC,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAQhI;AAED;;;;GAIG;AACH,wBAAgB,6CAA6C,CAAC,YAAY,EAAE,+BAA+B,EAAE,UAAU,EAAE,gCAAgC,GAAG,IAAI,CAG/J"}
@@ -0,0 +1,101 @@
1
+ import { brokerTaskClockFileFor } from "./grokBrokerSlot.js";
2
+ import { GROK_BROKER_TASK_CLOCK } from "../contracts/grokBrokerTaskClock.js";
3
+ import { createHash } from "node:crypto";
4
+ import path from "node:path";
5
+ import { canonicalJson } from "../contracts/canonicalJson.js";
6
+ import { DAIMON_GROK_SYSTEM_PROMPT } from "../contracts/grokWorkerContract.js";
7
+ import { GROK_ENGINE_BROKER } from "../contracts/runtimeContractManifest.js";
8
+ import { grokSandboxProtectedPaths } from "./engineDispatcher.js";
9
+ import { parseEngineBrokerServiceConfig } from "./engineBrokerServiceConfig.js";
10
+ import { parseEngineBrokerTurnLimits } from "./engineBrokerTurnAccounting.js";
11
+ import { grokBrokerWorkerConfigPins, grokBrokerWorkerConfigSha256 } from "./grokBrokerWorkerConfig.js";
12
+ import { GROK_WORKER_SANDBOX_PROFILE, grokWorkerEventsPathFor, renderGrokWorkerSandboxProfile, grokWorkerSandboxProfileSha256 } from "./grokWorkerSandboxProfile.js";
13
+ import { parseOrganizationRuntimeConfig } from "./organizationRuntime.js";
14
+ export const GROK_BROKER_PROJECTION_VERSION = GROK_ENGINE_BROKER.projectionVersion;
15
+ /**
16
+ * Resolve the public Grok broker projection for one agent.
17
+ *
18
+ * Paths are taken as given, never resolved: the caller (Spawnfile provisioning)
19
+ * must supply canonical, non-symlink paths — the fixed tmpfs/workspace roots it
20
+ * creates — and its provisioning must verify they are not symlinks before a
21
+ * slot is used; the broker's own attestation re-checks the worker home at
22
+ * every turn.
23
+ *
24
+ * Deterministic and I/O-free on purpose: its digest
25
+ * ({@link grokBrokerProjectionSha256}) is what the slot preflight receipt
26
+ * binds, so the supervisor that writes the receipt and the evaluator that reads
27
+ * it must compute byte-equal projections from the same inputs.
28
+ *
29
+ * The agent must be a Grok agent that *declares* its model and reasoning
30
+ * effort; nothing is defaulted. The deny list is Daimon's own protected set for
31
+ * this agent (realm, bootstrap, peers, and the mask covering the acceptance
32
+ * store) plus the caller's evaluator paths, sorted and deduplicated exactly as
33
+ * the profile renderer does. A supplied `profileSha256` that differs is
34
+ * refused.
35
+ */
36
+ export function resolveOrganizationGrokBrokerProjection(config, agentId, options) {
37
+ const parsed = parseOrganizationRuntimeConfig(config);
38
+ const agent = parsed.agents.find((entry) => entry.id === agentId);
39
+ if (agent === undefined || agent.engine.kind !== "grok")
40
+ throw new Error("Grok broker projection requires a known Grok agent");
41
+ if (agent.engine.model === undefined || agent.engine.reasoningEffort === undefined)
42
+ throw new Error("Grok broker projection requires a declared model and reasoning effort");
43
+ for (const [label, value] of [["workerHomePath", options.workerHomePath], ["acceptanceStorePath", options.acceptanceStorePath]]) {
44
+ if (!path.posix.isAbsolute(value) || path.posix.normalize(value) !== value || value === "/" || value.endsWith("/"))
45
+ throw new Error(`Grok broker projection requires a canonical absolute ${label}`);
46
+ }
47
+ if (!/^[a-f0-9]{64}$/u.test(options.seccompProfileSha256))
48
+ throw new Error("Grok broker projection requires a seccomp profile sha256");
49
+ const model = agent.engine.model, reasoningEffort = agent.engine.reasoningEffort;
50
+ const denyPaths = [...new Set([...grokSandboxProtectedPaths(agent.id, parsed.agents, [options.acceptanceStorePath]), ...(options.denyPaths ?? [])])].sort();
51
+ renderGrokWorkerSandboxProfile(denyPaths);
52
+ const profileSha256 = grokWorkerSandboxProfileSha256(denyPaths);
53
+ if (options.profileSha256 !== undefined && options.profileSha256 !== profileSha256)
54
+ throw new Error("Grok broker projection profile digest mismatch");
55
+ const workerConfigVariant = options.workerConfigVariant ?? "unclocked";
56
+ const workerConfigSha256 = grokBrokerWorkerConfigSha256({ model, reasoningEffort }, workerConfigVariant, options.slot);
57
+ const pin = grokBrokerWorkerConfigPins({ model, reasoningEffort }, options.slot)[workerConfigVariant];
58
+ if (workerConfigVariant === "clocked" && denyPaths.some((denied) => [brokerTaskClockFileFor(options.slot), GROK_BROKER_TASK_CLOCK.preloadPath].some((file) => file === denied || file.startsWith(`${denied}/`))))
59
+ throw new Error("Grok broker task clock path is denied");
60
+ if (workerConfigSha256 !== pin)
61
+ throw new Error("Grok broker projection worker config drifted from the manifest");
62
+ if (createHash("sha256").update(DAIMON_GROK_SYSTEM_PROMPT).digest("hex") !== GROK_ENGINE_BROKER.worker.systemPromptSha256)
63
+ throw new Error("Grok broker projection system prompt drifted from the manifest");
64
+ const artifact = GROK_ENGINE_BROKER.grokCliArtifacts[options.architecture];
65
+ if (artifact === undefined)
66
+ throw new Error("Grok broker projection requires a pinned architecture");
67
+ const profilePath = path.posix.join(options.workerHomePath, ".grok", "sandbox.toml");
68
+ const projection = {
69
+ version: GROK_BROKER_PROJECTION_VERSION, agentId, workspacePath: agent.workspacePath, runtimeHomePath: agent.runtimeHomePath,
70
+ workerUid: options.workerUid, slot: options.slot, profilePath, profileSha256, denyPaths, workerConfigSha256, workerConfigVariant,
71
+ ...(workerConfigVariant === "clocked" ? { taskClock: { ...GROK_BROKER_TASK_CLOCK, directoryPath: path.posix.dirname(brokerTaskClockFileFor(options.slot)), timestampFilePath: brokerTaskClockFileFor(options.slot) } } : {}),
72
+ systemPromptSha256: GROK_ENGINE_BROKER.worker.systemPromptSha256, grokCliVersion: GROK_ENGINE_BROKER.grokCliVersion, grokExecutableSha256: artifact.sha256,
73
+ nativeAbiVersion: GROK_ENGINE_BROKER.nativeAbiVersion, model, reasoningEffort, limits: parseEngineBrokerTurnLimits(options.limits), usageLedgerPath: options.usageLedgerPath, seccompProfileSha256: options.seccompProfileSha256,
74
+ attestation: { platform: "linux/landlock", enforced: true, restrictNetwork: true, profileName: GROK_WORKER_SANDBOX_PROFILE, sandboxRuntime: "bubblewrap", eventsPath: grokWorkerEventsPathFor(profilePath) }
75
+ };
76
+ // The registration this projection implies must itself be a valid v2 service.json entry.
77
+ grokBrokerServiceRegistrationFor(projection);
78
+ return projection;
79
+ }
80
+ /** sha256 over the projection's canonical JSON; what a slot preflight receipt binds. */
81
+ export const grokBrokerProjectionSha256 = (projection) => createHash("sha256").update(canonicalJson(projection)).digest("hex");
82
+ /** The `service.json` v2 registration a deployment provisions for this projection, validated by the broker's own parser. */
83
+ export function grokBrokerServiceRegistrationFor(projection) {
84
+ const registration = {
85
+ agentId: projection.agentId, slot: projection.slot, workerUid: projection.workerUid, workspace: projection.workspacePath,
86
+ profilePath: projection.profilePath, eventsPath: projection.attestation.eventsPath, profileSha256: projection.profileSha256,
87
+ usageLedgerPath: projection.usageLedgerPath, limits: projection.limits, model: { id: projection.model, reasoningEffort: projection.reasoningEffort }
88
+ };
89
+ parseEngineBrokerServiceConfig({ version: "noopolis.daimon.engine-broker-service.v2", credentialHome: GROK_ENGINE_BROKER.credentialHomePath, turnStore: GROK_ENGINE_BROKER.turnStorePath, registrations: [registration] });
90
+ return registration;
91
+ }
92
+ /**
93
+ * Refuses a provisioned registration that does not describe this projection:
94
+ * any differing member — a weaker profile digest, another model, raised
95
+ * limits, a different ledger — is a mismatch, never a merge.
96
+ */
97
+ export function verifyGrokBrokerRegistrationMatchesProjection(registration, projection) {
98
+ const expected = parseEngineBrokerServiceConfig({ version: "noopolis.daimon.engine-broker-service.v2", credentialHome: GROK_ENGINE_BROKER.credentialHomePath, turnStore: GROK_ENGINE_BROKER.turnStorePath, registrations: [grokBrokerServiceRegistrationFor(projection)] }).registrations[0];
99
+ if (canonicalJson(expected) !== canonicalJson(registration))
100
+ throw new Error("Grok broker registration does not match its projection");
101
+ }
@@ -0,0 +1,26 @@
1
+ export type GrokBrokerProviderClockObservation = Readonly<{
2
+ requests: number;
3
+ linesRewritten: number;
4
+ requestsWithoutDateLine: number;
5
+ /** Date-like message lines outside the injected block; absent on older seals. */
6
+ linesIgnored?: number;
7
+ /** The last rewritten line's dates; null until a line is rewritten. */
8
+ injectedDate: string | null;
9
+ taskDate: string | null;
10
+ }>;
11
+ export declare class GrokBrokerProviderClockRefusal extends Error {
12
+ readonly reason: "task_clock_date_format" | "task_clock_date_range" | "request_body_rejected";
13
+ constructor(reason: "task_clock_date_format" | "task_clock_date_range" | "request_body_rejected");
14
+ }
15
+ /** One processClock, owned by one turn; never reads the broker's ambient TZ. */
16
+ export declare class GrokBrokerProviderClock {
17
+ private readonly now;
18
+ private readonly offsetMs;
19
+ private observation;
20
+ constructor(processClock: string, now?: () => number);
21
+ rewrite(body: Uint8Array): Uint8Array;
22
+ snapshot(): GrokBrokerProviderClockObservation;
23
+ }
24
+ /** Closed, dates-only observation on the v3 terminal frame and durable seal. */
25
+ export declare function parseGrokBrokerProviderClockObservation(value: unknown): GrokBrokerProviderClockObservation;
26
+ //# sourceMappingURL=grokBrokerProviderClock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerProviderClock.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerProviderClock.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,kCAAkC,GAAG,QAAQ,CAAC;IACxD,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,uBAAuB,EAAE,MAAM,CAAC;IAChC,iFAAiF;IACjF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,uEAAuE;IACvE,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB,CAAC,CAAC;AAEH,qBAAa,8BAA+B,SAAQ,KAAK;IAC3C,QAAQ,CAAC,MAAM,EAAE,wBAAwB,GAAG,uBAAuB,GAAG,uBAAuB;gBAApF,MAAM,EAAE,wBAAwB,GAAG,uBAAuB,GAAG,uBAAuB;CAG1G;AAOD,gFAAgF;AAChF,qBAAa,uBAAuB;IAOA,OAAO,CAAC,QAAQ,CAAC,GAAG;IANtD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,WAAW,CAGjB;gBAEU,YAAY,EAAE,MAAM,EAAmB,GAAG,GAAE,MAAM,MAAyB;IAIvF,OAAO,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU;IAuErC,QAAQ,IAAI,kCAAkC;CAG/C;AAKD,gFAAgF;AAChF,wBAAgB,uCAAuC,CAAC,KAAK,EAAE,OAAO,GAAG,kCAAkC,CAuB1G"}
@@ -0,0 +1,133 @@
1
+ import { parseBrokerProcessClock } from "./grokBrokerTaskClock.js";
2
+ import { parseGrokBrokerProxyJson } from "./grokBrokerProxyJson.js";
3
+ export class GrokBrokerProviderClockRefusal extends Error {
4
+ reason;
5
+ constructor(reason) {
6
+ super(`grok broker proxy refused: ${reason}`);
7
+ this.reason = reason;
8
+ }
9
+ }
10
+ const DATE = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/u;
11
+ const DATE_LINE = /^Today's date: ([0-9]{4}-[0-9]{2}-[0-9]{2})$/u;
12
+ const DATE_LIKE = /today['’]?s\s+date\b/iu;
13
+ const MAX_TASK_MS = 253_402_300_799_999;
14
+ /** One processClock, owned by one turn; never reads the broker's ambient TZ. */
15
+ export class GrokBrokerProviderClock {
16
+ now;
17
+ offsetMs;
18
+ observation = {
19
+ requests: 0, linesRewritten: 0, requestsWithoutDateLine: 0, linesIgnored: 0,
20
+ injectedDate: null, taskDate: null
21
+ };
22
+ constructor(processClock, now = () => Date.now()) {
23
+ this.now = now;
24
+ this.offsetMs = Math.round(Number(parseBrokerProcessClock(processClock)) * 1000);
25
+ }
26
+ rewrite(body) {
27
+ this.observation = { ...this.observation, requests: this.observation.requests + 1 };
28
+ let parsed;
29
+ try {
30
+ parsed = parseGrokBrokerProxyJson(body);
31
+ }
32
+ catch {
33
+ throw new GrokBrokerProviderClockRefusal("request_body_rejected");
34
+ }
35
+ const taskMs = this.now() + this.offsetMs;
36
+ if (!Number.isSafeInteger(taskMs) || taskMs < 0 || taskMs > MAX_TASK_MS) {
37
+ throw new GrokBrokerProviderClockRefusal("task_clock_date_range");
38
+ }
39
+ // The native launcher pins TZ=UTC. Compute once per request, including
40
+ // history resends; a long turn may cross midnight between requests.
41
+ const taskDate = new Date(taskMs).toISOString().slice(0, 10);
42
+ let lines = 0;
43
+ let ignored = 0;
44
+ let injectedDate = null;
45
+ const countIgnored = (text) => text.split(/\r\n|\r|\n/u).filter((line) => DATE_LIKE.test(line)).length;
46
+ const rewriteText = (text, injected) => {
47
+ const block = injected ? /<user_info>([\s\S]*?)<\/user_info>/u.exec(text) : null;
48
+ if (block === null) {
49
+ ignored += countIgnored(text);
50
+ return text;
51
+ }
52
+ const before = text.slice(0, block.index), after = text.slice(block.index + block[0].length);
53
+ ignored += countIgnored(before) + countIgnored(after);
54
+ const rewritten = block[1].split(/(\r\n|\r|\n)/u).map((line) => {
55
+ if (!DATE_LIKE.test(line))
56
+ return line;
57
+ const match = DATE_LINE.exec(line);
58
+ if (match === null)
59
+ throw new GrokBrokerProviderClockRefusal("task_clock_date_format");
60
+ lines++;
61
+ injectedDate = match[1];
62
+ return `Today's date: ${taskDate}`;
63
+ }).join("");
64
+ return `${before}<user_info>${rewritten}</user_info>${after}`;
65
+ };
66
+ if (Array.isArray(parsed.value.messages)) {
67
+ let firstUser = true;
68
+ for (const message of parsed.value.messages) {
69
+ if (!isRecord(message))
70
+ continue;
71
+ const injected = message.role === "user" && firstUser;
72
+ if (message.role === "user")
73
+ firstUser = false;
74
+ if (typeof message.content === "string") {
75
+ message.content = rewriteText(message.content, injected);
76
+ }
77
+ else if (Array.isArray(message.content)) {
78
+ const parts = message.content.filter((part) => isRecord(part) && part.type === "text" && typeof part.text === "string");
79
+ // A block or date can straddle text parts. Replacements have exactly
80
+ // the same width, so slicing restores every original part boundary.
81
+ const rewritten = rewriteText(parts.map((part) => part.text).join(""), injected);
82
+ let start = 0;
83
+ for (const part of parts) {
84
+ const end = start + part.text.length;
85
+ part.text = rewritten.slice(start, end);
86
+ start = end;
87
+ }
88
+ }
89
+ }
90
+ }
91
+ // Commit only after the entire body passes: a refused request rewrites no
92
+ // lines upstream, even when an earlier line had the recognized format.
93
+ this.observation = {
94
+ requests: this.observation.requests,
95
+ linesRewritten: this.observation.linesRewritten + lines,
96
+ requestsWithoutDateLine: this.observation.requestsWithoutDateLine + (lines === 0 ? 1 : 0),
97
+ linesIgnored: (this.observation.linesIgnored ?? 0) + ignored,
98
+ injectedDate: lines === 0 ? this.observation.injectedDate : injectedDate,
99
+ taskDate: lines === 0 ? this.observation.taskDate : taskDate
100
+ };
101
+ return lines === 0 ? parsed.body : Buffer.from(JSON.stringify(parsed.value));
102
+ }
103
+ snapshot() {
104
+ return { ...this.observation };
105
+ }
106
+ }
107
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
108
+ /** Closed, dates-only observation on the v3 terminal frame and durable seal. */
109
+ export function parseGrokBrokerProviderClockObservation(value) {
110
+ if (!isRecord(value))
111
+ throw new TypeError("invalid broker frame");
112
+ const fields = ["requests", "linesRewritten", "requestsWithoutDateLine", "injectedDate", "taskDate"];
113
+ if (Object.keys(value).some((key) => !fields.includes(key) && key !== "linesIgnored") ||
114
+ fields.some((key) => !Object.hasOwn(value, key))) {
115
+ throw new TypeError("invalid broker frame");
116
+ }
117
+ for (const key of [...fields.slice(0, 3), ...(Object.hasOwn(value, "linesIgnored") ? ["linesIgnored"] : [])]) {
118
+ if (!Number.isSafeInteger(value[key]) || value[key] < 0) {
119
+ throw new TypeError("invalid broker frame");
120
+ }
121
+ }
122
+ const result = value;
123
+ if (result.requestsWithoutDateLine > result.requests ||
124
+ (result.linesRewritten > 0 && result.requestsWithoutDateLine === result.requests)) {
125
+ throw new TypeError("invalid broker frame");
126
+ }
127
+ for (const date of [result.injectedDate, result.taskDate]) {
128
+ if (result.linesRewritten === 0 ? date !== null : typeof date !== "string" || !DATE.test(date)) {
129
+ throw new TypeError("invalid broker frame");
130
+ }
131
+ }
132
+ return { ...result };
133
+ }