@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,69 @@
1
+ import { type GrokBrokerRunBudget } from "./grokBrokerRunBudget.js";
2
+ import { type IncomingMessage, type ServerResponse } from "node:http";
3
+ import { EngineBrokerCapabilities } from "./engineBrokerCapabilities.js";
4
+ import { type GrokBrokerModelPolicy } from "./grokBrokerModelPolicy.js";
5
+ import { authorizeGrokBrokerProxyRequest } from "./grokBrokerProxyRequest.js";
6
+ import { type GrokBrokerTurnMeter } from "./grokBrokerTurnMeter.js";
7
+ import type { GrokInferenceGrants } from "./grokInferenceGrants.js";
8
+ import { type GrokBrokerProviderClock } from "./grokBrokerProviderClock.js";
9
+ /** One running turn as the proxy sees it: its declared model/effort and its spend gate. */
10
+ export type GrokBrokerProxyTurn = Readonly<{
11
+ policy: GrokBrokerModelPolicy;
12
+ meter: GrokBrokerTurnMeter;
13
+ clock?: GrokBrokerProviderClock;
14
+ }>;
15
+ export type GrokBrokerCredentialAuthority = Readonly<{
16
+ accessToken(forceRefresh: boolean): Promise<string>;
17
+ refreshAfterRejection?(rejectedTokenDigest: string): Promise<string>;
18
+ markRejected(rejectedTokenDigest?: string): Promise<void>;
19
+ isStale?(): boolean;
20
+ }>;
21
+ export type GrokBrokerUpstream = (request: ReturnType<typeof authorizeGrokBrokerProxyRequest>, signal?: AbortSignal) => Promise<Readonly<{
22
+ status: number;
23
+ headers: Readonly<Record<string, string>>;
24
+ body: Uint8Array;
25
+ }>>;
26
+ /**
27
+ * `policy` is the fallback declared model/effort (closed list); a registered
28
+ * turn's own policy wins. A request whose turn has no registered meter is
29
+ * refused like one without an isolation guard: nothing is forwarded unmetered.
30
+ * `listenPort` exists for tests that must not contend for the production port.
31
+ *
32
+ * `grants` are evaluator inference grants (`grokInferenceGrants.ts`): a bearer
33
+ * carrying the grant prefix is looked up only there and served by
34
+ * `grokInferenceProxy.ts`; every other bearer is looked up only among turn
35
+ * capabilities. Without `grants` a prefixed bearer is simply refused.
36
+ */
37
+ export declare function startGrokBrokerProxy(authority: GrokBrokerCredentialAuthority, upstream?: GrokBrokerUpstream, policy?: GrokBrokerModelPolicy, listenPort?: number, grants?: GrokInferenceGrants, runBudget?: GrokBrokerRunBudget): Promise<{
38
+ port: number;
39
+ close: () => Promise<void>;
40
+ capabilities: EngineBrokerCapabilities;
41
+ registerIsolationGuard(turnId: string, guard: () => Promise<void>): void;
42
+ revokeIsolationGuard(turnId: string): void;
43
+ registerTurn(turnId: string, turn: GrokBrokerProxyTurn): void;
44
+ revokeTurn(turnId: string): void;
45
+ serve: (request: IncomingMessage, response: ServerResponse) => Promise<void>;
46
+ }>;
47
+ /** @internal The production request handler, usable without opening a socket. */
48
+ export declare function createGrokBrokerProxyHandler(authority: GrokBrokerCredentialAuthority, upstream?: GrokBrokerUpstream, policy?: GrokBrokerModelPolicy, grants?: GrokInferenceGrants, runBudget?: GrokBrokerRunBudget): {
49
+ capabilities: EngineBrokerCapabilities;
50
+ registerIsolationGuard(turnId: string, guard: () => Promise<void>): void;
51
+ revokeIsolationGuard(turnId: string): void;
52
+ registerTurn(turnId: string, turn: GrokBrokerProxyTurn): void;
53
+ revokeTurn(turnId: string): void;
54
+ serve: (request: IncomingMessage, response: ServerResponse) => Promise<void>;
55
+ };
56
+ /**
57
+ * A refusal the caller must not retry.
58
+ *
59
+ * Every internal refusal used to collapse into one bare 503. Grok treats 503 as
60
+ * transient and blind-retries the same request (observed: 14 retries, ~141k
61
+ * estimated tokens, then `exit 1`), so a policy miss burned a turn's budget and
62
+ * reported itself as an engine crash. Policy refusals now answer 400 with a
63
+ * reason, and only genuinely transient faults keep 503.
64
+ */
65
+ export declare class GrokBrokerProxyRefusal extends Error {
66
+ readonly reason: string;
67
+ constructor(reason: string);
68
+ }
69
+ //# sourceMappingURL=grokBrokerProxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerProxy.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerProxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAExF,OAAO,EAAgB,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAIpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAAgE,KAAK,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACtI,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAE9E,OAAO,EAA2E,KAAK,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAG7I,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EAAkC,KAAK,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAE5G,2FAA2F;AAC3F,MAAM,MAAM,mBAAmB,GAAG,QAAQ,CAAC;IACzC,MAAM,EAAE,qBAAqB,CAAC;IAC9B,KAAK,EAAE,mBAAmB,CAAC;IAC3B,KAAK,CAAC,EAAE,uBAAuB,CAAC;CACjC,CAAC,CAAC;AAEH,MAAM,MAAM,6BAA6B,GAAG,QAAQ,CAAC;IAAE,WAAW,CAAC,YAAY,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAAC,qBAAqB,CAAC,CAAC,mBAAmB,EAAC,MAAM,GAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAAC,YAAY,CAAC,mBAAmB,CAAC,EAAC,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,OAAO,CAAC,IAAI,OAAO,CAAA;CAAE,CAAC,CAAC;AACjQ,MAAM,MAAM,kBAAkB,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,OAAO,+BAA+B,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAAC,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC,CAAC;AAE3N;;;;;;;;;;GAUG;AACH,wBAAsB,oBAAoB,CACxC,SAAS,EAAE,6BAA6B,EAAE,QAAQ,GAAE,kBAAoC,EACxF,MAAM,GAAE,qBAAwD,EAAE,UAAU,SAAS,EACrF,MAAM,CAAC,EAAE,mBAAmB,EAAE,SAAS,CAAC,EAAE,mBAAmB;;;;mCAoC5B,MAAM,SAAS,MAAM,OAAO,CAAC,IAAI,CAAC;iCACpC,MAAM;yBACd,MAAM,QAAQ,mBAAmB;uBAMnC,MAAM;qBACR,eAAe,YAAY,cAAc;GA5B7D;AAED,iFAAiF;AACjF,wBAAgB,4BAA4B,CAC1C,SAAS,EAAE,6BAA6B,EAAE,QAAQ,GAAE,kBAAoC,EACxF,MAAM,GAAE,qBAAwD,EAAE,MAAM,CAAC,EAAE,mBAAmB,EAAE,SAAS,CAAC,EAAE,mBAAmB;;mCAc9F,MAAM,SAAS,MAAM,OAAO,CAAC,IAAI,CAAC;iCACpC,MAAM;yBACd,MAAM,QAAQ,mBAAmB;uBAMnC,MAAM;qBACR,eAAe,YAAY,cAAc;EAI7D;AAED;;;;;;;;GAQG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IACnC,QAAQ,CAAC,MAAM,EAAE,MAAM;gBAAd,MAAM,EAAE,MAAM;CACpC"}
@@ -0,0 +1,326 @@
1
+ import { GrokBrokerRunLimit } from "./grokBrokerRunBudget.js";
2
+ import { createHash } from "node:crypto";
3
+ import { createServer } from "node:http";
4
+ import { redactCredentialText } from "../core/credentialRedaction.js";
5
+ import { CLI_ENGINE_MAX_DIAGNOSTIC_BYTES } from "../pi/cliChildOutput.js";
6
+ import { EngineBrokerCapabilities } from "./engineBrokerCapabilities.js";
7
+ import { ENGINE_BROKER_AUTH_STALE } from "./engineBrokerProtocol.js";
8
+ import { DEFAULT_GROK_BROKER_MODEL_POLICY, parseGrokBrokerModelPolicy } from "./grokBrokerModelPolicy.js";
9
+ import { authorizeGrokBrokerProxyRequest } from "./grokBrokerProxyRequest.js";
10
+ import { GROK_SESSION_TITLE_SINK_KEY } from "./grokBrokerWorkerConfig.js";
11
+ import { parseGrokFinalReply, parseGrokResponseToolNames, parseGrokUpstreamUsage } from "./grokBrokerTurnMeter.js";
12
+ import { GROK_ENGINE_BROKER } from "../contracts/runtimeContractManifest.js";
13
+ import { serveGrokInferenceGrant } from "./grokInferenceProxy.js";
14
+ import { GrokBrokerProviderClockRefusal } from "./grokBrokerProviderClock.js";
15
+ /**
16
+ * `policy` is the fallback declared model/effort (closed list); a registered
17
+ * turn's own policy wins. A request whose turn has no registered meter is
18
+ * refused like one without an isolation guard: nothing is forwarded unmetered.
19
+ * `listenPort` exists for tests that must not contend for the production port.
20
+ *
21
+ * `grants` are evaluator inference grants (`grokInferenceGrants.ts`): a bearer
22
+ * carrying the grant prefix is looked up only there and served by
23
+ * `grokInferenceProxy.ts`; every other bearer is looked up only among turn
24
+ * capabilities. Without `grants` a prefixed bearer is simply refused.
25
+ */
26
+ export async function startGrokBrokerProxy(authority, upstream = defaultUpstream, policy = DEFAULT_GROK_BROKER_MODEL_POLICY, listenPort = 43_123, grants, runBudget) {
27
+ const handler = createGrokBrokerProxyHandler(authority, upstream, policy, grants, runBudget);
28
+ const server = createServer((request, response) => { void handler.serve(request, response); });
29
+ await new Promise((resolve, reject) => {
30
+ server.once("error", reject);
31
+ server.listen(listenPort, "127.0.0.1", () => { server.off("error", reject); resolve(); });
32
+ });
33
+ const address = server.address();
34
+ return {
35
+ ...handler, port: address.port,
36
+ close: () => new Promise((resolve, reject) => {
37
+ server.close((error) => error === undefined ? resolve() : reject(error));
38
+ // A worker's idle pooled socket otherwise leaves close() without a bound.
39
+ server.closeAllConnections();
40
+ })
41
+ };
42
+ }
43
+ /** @internal The production request handler, usable without opening a socket. */
44
+ export function createGrokBrokerProxyHandler(authority, upstream = defaultUpstream, policy = DEFAULT_GROK_BROKER_MODEL_POLICY, grants, runBudget) {
45
+ const admittedUpstream = async (request, signal) => {
46
+ signal?.throwIfAborted();
47
+ await runBudget?.reserve();
48
+ signal?.throwIfAborted();
49
+ return upstream(request, signal);
50
+ };
51
+ const declared = parseGrokBrokerModelPolicy(policy);
52
+ const capabilities = new EngineBrokerCapabilities();
53
+ const guards = new Map();
54
+ const turns = new Map();
55
+ return {
56
+ capabilities,
57
+ registerIsolationGuard(turnId, guard) { guards.set(turnId, guard); },
58
+ revokeIsolationGuard(turnId) { guards.delete(turnId); },
59
+ registerTurn(turnId, turn) {
60
+ turns.set(turnId, {
61
+ policy: parseGrokBrokerModelPolicy(turn.policy), meter: turn.meter,
62
+ ...(turn.clock === undefined ? {} : { clock: turn.clock })
63
+ });
64
+ },
65
+ revokeTurn(turnId) { turns.delete(turnId); },
66
+ serve: (request, response) => serve(request, response, authority, admittedUpstream, capabilities, guards, turns, declared, grants)
67
+ };
68
+ }
69
+ /**
70
+ * A refusal the caller must not retry.
71
+ *
72
+ * Every internal refusal used to collapse into one bare 503. Grok treats 503 as
73
+ * transient and blind-retries the same request (observed: 14 retries, ~141k
74
+ * estimated tokens, then `exit 1`), so a policy miss burned a turn's budget and
75
+ * reported itself as an engine crash. Policy refusals now answer 400 with a
76
+ * reason, and only genuinely transient faults keep 503.
77
+ */
78
+ export class GrokBrokerProxyRefusal extends Error {
79
+ reason;
80
+ constructor(reason) {
81
+ super(`grok broker proxy refused: ${reason}`);
82
+ this.reason = reason;
83
+ }
84
+ }
85
+ async function serve(request, response, authority, upstream, capabilities, guards, turns, fallback, grants) {
86
+ let settle;
87
+ let titleSink = false;
88
+ // Every credential this request holds, kept only for this request and only so
89
+ // that a fault's own words can be redacted against them exactly as the CLI
90
+ // child and launcher diagnostics are. Nothing reads them but {@link brokerFaultCause}.
91
+ const secrets = [];
92
+ try {
93
+ let body = await readBody(request);
94
+ const headers = Object.fromEntries(Object.entries(request.headers).map(([key, value]) => [key, Array.isArray(value) ? value[0] : value]));
95
+ titleSink = headers.authorization === `Bearer ${GROK_SESSION_TITLE_SINK_KEY}`;
96
+ const match = headers.authorization?.match(/^Bearer ([A-Za-z0-9_-]{40,})$/u);
97
+ if (match)
98
+ secrets.push(match[1]);
99
+ if (match && match[1].startsWith(GROK_ENGINE_BROKER.inferenceGrants.tokenPrefix)) {
100
+ if (!grants)
101
+ throw new GrokBrokerProxyRefusal("inference_grants_unavailable");
102
+ return await serveGrokInferenceGrant({ method: request.method ?? "", pathname: new URL(request.url ?? "/", "http://127.0.0.1").pathname, headers, body, token: match[1] }, response, grants, authority, upstream);
103
+ }
104
+ const scope = match ? capabilities.inspectToken(match[1]) : undefined;
105
+ if (!scope)
106
+ throw new GrokBrokerProxyRefusal("unknown_capability");
107
+ const guard = guards.get(scope.turnId), turn = turns.get(scope.turnId);
108
+ if (!guard || !turn)
109
+ throw new GrokBrokerProxyRefusal("no_active_turn");
110
+ try {
111
+ await guard();
112
+ }
113
+ catch (error) {
114
+ throw new GrokBrokerProxyRefusal("worker_isolation_unverified");
115
+ }
116
+ // Neutralize engine context before the existing body gate or bearer read.
117
+ // The clock belongs to this turn, never to the slot's installed variant.
118
+ try {
119
+ if (turn.clock !== undefined)
120
+ body = Buffer.from(turn.clock.rewrite(body));
121
+ }
122
+ catch (error) {
123
+ if (error instanceof GrokBrokerProviderClockRefusal)
124
+ throw new GrokBrokerProxyRefusal(error.reason);
125
+ throw error;
126
+ }
127
+ // A fenced realm is not a transient fault: the credential is gone until an
128
+ // operator re-logs in, and 503 made Grok blind-retry it (observed: fifteen
129
+ // retries over five minutes, $0 spent, nothing learned). Named, 400, and
130
+ // checked before the credential read, so the miss costs one round trip.
131
+ if (authority.isStale?.() === true)
132
+ throw new GrokBrokerProxyRefusal(ENGINE_BROKER_AUTH_STALE);
133
+ let token = await authority.accessToken(false);
134
+ secrets.push(token);
135
+ const rejectedDigest = createHash("sha256").update(token).digest("hex");
136
+ let prepared = authorizeRequestOrRefuse({ method: request.method ?? "", pathname: new URL(request.url ?? "/", "http://127.0.0.1").pathname, headers, body }, capabilities, token, turn.policy ?? fallback);
137
+ token = "";
138
+ // The spend gate runs after the body is proven a real lean worker request
139
+ // (a refused session-title body never counts) and before any upstream call.
140
+ const admission = turn.meter.admit();
141
+ if ("refused" in admission) {
142
+ response.writeHead(429, { "content-type": "application/json", "cache-control": "no-store" });
143
+ response.end(JSON.stringify({ error: "turn limit reached", limit: admission.refused }));
144
+ return;
145
+ }
146
+ if ("busy" in admission) {
147
+ response.writeHead(429, { "content-type": "application/json", "cache-control": "no-store" });
148
+ response.end('{"error":"turn request in flight"}');
149
+ return;
150
+ }
151
+ settle = (usage, toolCalls, finalReply) => { turn.meter.settle(admission.index, usage, body.byteLength, toolCalls, finalReply); settle = undefined; };
152
+ let result = await upstream(prepared, admission.signal);
153
+ if (result.status === 401) {
154
+ token = authority.refreshAfterRejection ? await authority.refreshAfterRejection(rejectedDigest) : await authority.accessToken(true);
155
+ secrets.push(token);
156
+ const refreshedDigest = createHash("sha256").update(token).digest("hex");
157
+ prepared = { ...prepared, headers: { ...prepared.headers, authorization: `Bearer ${token}` } };
158
+ token = "";
159
+ result = await upstream(prepared, admission.signal);
160
+ if (result.status === 401)
161
+ await authority.markRejected(refreshedDigest);
162
+ }
163
+ // Names only, bounded, and never a reason to fail the request: the response
164
+ // is already buffered here for its usage block, so what the model tried to
165
+ // call is in hand. A decoder fault records no attempt rather than a false
166
+ // empty one, and never disturbs the turn.
167
+ // A successful answer that called nothing and stopped is the turn's final
168
+ // reply: the broker ends a worker that finished but did not exit on it
169
+ // (`grokEngineBrokerTurnEnd.ts`), and reports it when the launcher refused
170
+ // the worker's stdout. Observation only, exactly like the tool names.
171
+ settle?.(usageOrEstimate(result.body, result.headers["content-type"]), toolCallsOrNothing(result.body, result.headers["content-type"]), result.status === 200 ? finalReplyOrNothing(result.body, result.headers["content-type"]) : undefined);
172
+ response.writeHead(result.status, { "content-type": result.headers["content-type"] ?? "application/json", "cache-control": "no-store" });
173
+ response.end(result.body);
174
+ }
175
+ catch (error) {
176
+ settle?.(undefined);
177
+ if (error instanceof GrokBrokerRunLimit) {
178
+ response.writeHead(429, { "content-type": "application/json", "cache-control": "no-store" });
179
+ response.end('{"error":"run_request_limit"}');
180
+ return;
181
+ }
182
+ // Name the refusal on the broker's own stderr (reason code only, never a body
183
+ // or a token) so a failing turn is diagnosable without a stub harness —
184
+ // except for the two requests every healthy turn makes anyway.
185
+ // The request that *discovers* the fence throws an ordinary error from the
186
+ // credential authority, so it is promoted to the same named refusal: one
187
+ // stale realm must not read as one transient fault plus fourteen retries.
188
+ const fenced = !(error instanceof GrokBrokerProxyRefusal) && authority.isStale?.() === true;
189
+ const refused = error instanceof GrokBrokerProxyRefusal || fenced;
190
+ const refusal = error instanceof GrokBrokerProxyRefusal ? error.reason : fenced ? ENGINE_BROKER_AUTH_STALE : "broker_unavailable";
191
+ // A named refusal is its own account; anything else used to reach the log as
192
+ // the bare word `broker_unavailable`, which names nothing — so it carries the
193
+ // fault's own class and message, and nothing else, beside it.
194
+ const named = refused ? refusal : `${refusal} (${brokerFaultCause(error, secrets)})`;
195
+ if (!titleSink && !expectedWorkerProbe(request))
196
+ process.stderr.write(`[grok-proxy] refused: ${named}\n`);
197
+ // Grok's own session-title call is refused by design, and keeps the transient
198
+ // 503 shape it has always had. Forcing 400 and 503 on it were both observed
199
+ // to end the turn `exit=0, result: success`, so the shape is kept because it
200
+ // is the one every live capture was taken with, not because a 4xx there ends
201
+ // Grok's session — it does not.
202
+ if (titleSink) {
203
+ response.writeHead(503, { "content-type": "application/json", "cache-control": "no-store" });
204
+ response.end('{"error":"broker unavailable"}');
205
+ return;
206
+ }
207
+ if (refused) {
208
+ response.writeHead(400, { "content-type": "application/json", "cache-control": "no-store" });
209
+ response.end(JSON.stringify({ error: "broker refused this request", reason: refusal }));
210
+ return;
211
+ }
212
+ response.writeHead(503, { "content-type": "application/json", "cache-control": "no-store" });
213
+ response.end('{"error":"broker unavailable"}');
214
+ }
215
+ finally {
216
+ secrets.length = 0;
217
+ }
218
+ }
219
+ /**
220
+ * A non-refusal fault, named on one bounded line.
221
+ *
222
+ * `broker_unavailable` on its own carries no diagnostic content at all, and it
223
+ * is answered 503, which Grok blind-retries: one live turn emitted it fifteen
224
+ * times over five minutes, spent $0 — so no upstream call ever succeeded — and
225
+ * died with no account of why. The error's own class and message are the whole
226
+ * of what is logged: never a request body, bearer, capability, session id or
227
+ * header. It is redacted exactly as the failed CLI child and the launcher's
228
+ * worker diagnostic are — `redactCredentialText` with this request's own
229
+ * capabilities as exact secrets and the same `CLI_ENGINE_MAX_DIAGNOSTIC_BYTES`
230
+ * bound — and flattened to one line, because it travels on a log line. Naming
231
+ * a fault must never be able to fail the response that reports it, so a value
232
+ * that cannot even be described degrades to a marker.
233
+ *
234
+ * One level of `cause` is named too, because the fault this exists for names
235
+ * nothing without it: every failed `fetch` to the provider is `TypeError:
236
+ * fetch failed`, and which fault it was — `ENOTFOUND`, `ECONNREFUSED`, a TLS
237
+ * refusal, an abort — is only in the cause. An errno error whose message is
238
+ * empty is named by its `code`.
239
+ */
240
+ const brokerFaultCause = (error, secrets) => {
241
+ try {
242
+ const described = `${describeFault(error)}${error instanceof Error && error.cause !== undefined && error.cause !== null ? ` <- ${describeFault(error.cause)}` : ""}`;
243
+ const flattened = described.replace(/[\u0000-\u001f\u007f]+/gu, " ").replace(/\s+/gu, " ").trim();
244
+ const named = redactCredentialText(flattened, secrets, CLI_ENGINE_MAX_DIAGNOSTIC_BYTES).trim();
245
+ return named.length === 0 ? "unnamed" : named;
246
+ }
247
+ catch {
248
+ return "unnameable";
249
+ }
250
+ };
251
+ /** One value's class and words: an error's own, or the type of whatever else was thrown. */
252
+ const describeFault = (error) => {
253
+ if (!(error instanceof Error))
254
+ return `${typeof error}: ${String(error)}`;
255
+ const code = error.code;
256
+ const words = error.message.length > 0 ? error.message : typeof code === "string" ? code : "(no message)";
257
+ return `${error.constructor?.name ?? error.name}: ${words}`;
258
+ };
259
+ /**
260
+ * The unauthenticated connectivity probe Grok sends before its own requests: a
261
+ * bare `GET /` with no Authorization header, which has no capability to look up
262
+ * and answers 400.
263
+ *
264
+ * It and the per-turn `session_title` POST are the only two requests a healthy
265
+ * turn makes that this proxy does not forward, and both used to print the same
266
+ * `refused: unknown_capability` line as a real policy miss — so every healthy
267
+ * turn read as two refusals and cost a live investigation. They answer exactly
268
+ * as before; they simply stop claiming a refusal on the broker's stderr, which
269
+ * is left for the misses that are actually worth reading.
270
+ */
271
+ const expectedWorkerProbe = (request) => request.headers.authorization === undefined && (request.method ?? "") === "GET" &&
272
+ new URL(request.url ?? "/", "http://127.0.0.1").pathname === "/";
273
+ /**
274
+ * Upstream-reported usage, or the documented conservative estimate.
275
+ *
276
+ * The decoder faulting must not fail the request that already cost real
277
+ * money: the upstream call succeeded, the worker is owed its answer, and a
278
+ * 503 here would throw away a paid response and have Grok buy it again. The
279
+ * `undefined` this returns is not "no usage" — `GrokBrokerTurnMeter.settle`
280
+ * charges it `ceil(bodyBytes/2) + 4096` and marks the row
281
+ * `usage_source: "estimated"`, so the token ceiling still counts it and no
282
+ * fabricated zero ever reaches a ledger.
283
+ */
284
+ const usageOrEstimate = (body, contentType) => {
285
+ try {
286
+ return parseGrokUpstreamUsage(body, contentType);
287
+ }
288
+ catch {
289
+ return undefined;
290
+ }
291
+ };
292
+ /** Instrumentation must never fail a turn: a throwing decoder records nothing, exactly as an undecodable response does. */
293
+ const toolCallsOrNothing = (body, contentType) => {
294
+ try {
295
+ return parseGrokResponseToolNames(body, contentType);
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ };
301
+ /** Instrumentation must never fail a turn: a throwing decoder reports no final reply. */
302
+ const finalReplyOrNothing = (body, contentType) => {
303
+ try {
304
+ return parseGrokFinalReply(body, contentType);
305
+ }
306
+ catch {
307
+ return undefined;
308
+ }
309
+ };
310
+ /** The body gate, refused non-retryably: a rejected body is a policy miss, never a transient fault. */
311
+ function authorizeRequestOrRefuse(...args) {
312
+ try {
313
+ return authorizeGrokBrokerProxyRequest(...args);
314
+ }
315
+ catch {
316
+ throw new GrokBrokerProxyRefusal("request_body_rejected");
317
+ }
318
+ }
319
+ async function readBody(request) { const chunks = []; let bytes = 0; for await (const chunk of request) {
320
+ const value = Buffer.from(chunk);
321
+ bytes += value.length;
322
+ if (bytes > 2 * 1024 * 1024)
323
+ throw new Error("too large");
324
+ chunks.push(value);
325
+ } return Buffer.concat(chunks); }
326
+ const defaultUpstream = async (request, signal) => { const result = await fetch(request.url, { method: "POST", headers: request.headers, body: Buffer.from(request.body), ...(signal === undefined ? {} : { signal }) }); return { status: result.status, headers: { "content-type": result.headers.get("content-type") ?? "application/json" }, body: new Uint8Array(await result.arrayBuffer()) }; };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Preserve ordinary JSON bytes, including whitespace and escaping. Ambiguous
3
+ * duplicate members still normalize to the validated values, as the spend gate
4
+ * requires: an upstream parser must never select a different model or tool set.
5
+ */
6
+ export declare function parseGrokBrokerProxyJson(body: Uint8Array): {
7
+ value: Record<string, unknown>;
8
+ body: Uint8Array;
9
+ };
10
+ //# sourceMappingURL=grokBrokerProxyJson.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerProxyJson.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerProxyJson.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,UAAU,GAAG;IAC1D,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,IAAI,EAAE,UAAU,CAAC;CAClB,CAuBA"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Preserve ordinary JSON bytes, including whitespace and escaping. Ambiguous
3
+ * duplicate members still normalize to the validated values, as the spend gate
4
+ * requires: an upstream parser must never select a different model or tool set.
5
+ */
6
+ export function parseGrokBrokerProxyJson(body) {
7
+ const source = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(body);
8
+ let properties = 0;
9
+ const value = JSON.parse(source, (key, entry) => {
10
+ if (key === "__proto__")
11
+ throw new Error("broker proxy request rejected");
12
+ if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
13
+ properties += Object.keys(entry).length;
14
+ }
15
+ return entry;
16
+ });
17
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
18
+ throw new Error("broker proxy request rejected");
19
+ }
20
+ // JSON.parse established the grammar. Match whole string tokens (including
21
+ // escaped quotes), so a colon inside message content cannot count as a key.
22
+ let sourceProperties = 0;
23
+ for (const token of source.matchAll(/"(?:[^"\\]|\\[\s\S])*"\s*(:)?/gu)) {
24
+ if (token[1] !== undefined)
25
+ sourceProperties++;
26
+ }
27
+ return {
28
+ value: value,
29
+ body: sourceProperties === properties ? body : Buffer.from(JSON.stringify(value))
30
+ };
31
+ }
@@ -0,0 +1,30 @@
1
+ import type { EngineBrokerCapabilities } from "./engineBrokerCapabilities.js";
2
+ import { type GrokBrokerModelPolicy } from "./grokBrokerModelPolicy.js";
3
+ export type GrokBrokerProxyInput = Readonly<{
4
+ method: string;
5
+ pathname: string;
6
+ headers: Readonly<Record<string, string | undefined>>;
7
+ body: Uint8Array;
8
+ agentId?: string;
9
+ turnId?: string;
10
+ }>;
11
+ export type GrokBrokerUpstreamRequest = Readonly<{
12
+ url: "https://cli-chat-proxy.grok.com/v1/chat/completions";
13
+ headers: Readonly<Record<string, string>>;
14
+ body: Uint8Array;
15
+ }>;
16
+ /**
17
+ * Authorizes one worker request and rebuilds it for the provider.
18
+ *
19
+ * Everything that decides spend is checked here, before a bearer is attached
20
+ * and before any upstream call:
21
+ * - the client version is exactly the pinned Grok CLI (`GROK_ENGINE_BROKER.grokCliVersion`);
22
+ * - the body model and `reasoning_effort` are exactly the declared policy, and
23
+ * the model override header follows that declaration instead of a constant;
24
+ * - the offered tool names are exactly the lean visible set. Grok 1.0.34 turns
25
+ * an unmappable `--tools` entry into its full 19-tool set, and its per-turn
26
+ * `session_title` request carries a single forced tool; both are refused.
27
+ */
28
+ export declare function authorizeGrokBrokerProxyRequest(input: GrokBrokerProxyInput, capabilities: EngineBrokerCapabilities, bearer: string, policy?: GrokBrokerModelPolicy): GrokBrokerUpstreamRequest;
29
+ export declare function exactLeanTools(tools: unknown): boolean;
30
+ //# sourceMappingURL=grokBrokerProxyRequest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerProxyRequest.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerProxyRequest.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,EAAgE,KAAK,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAGtI,MAAM,MAAM,oBAAoB,GAAG,QAAQ,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;IAAC,IAAI,EAAE,UAAU,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAC9L,MAAM,MAAM,yBAAyB,GAAG,QAAQ,CAAC;IAAE,GAAG,EAAE,qDAAqD,CAAC;IAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAAC,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC;AAE9K;;;;;;;;;;;GAWG;AACH,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,oBAAoB,EAAE,YAAY,EAAE,wBAAwB,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAE,qBAAwD,GAAG,yBAAyB,CAmChO;AASD,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAStD"}
@@ -0,0 +1,85 @@
1
+ import { GROK_ENGINE_BROKER } from "../contracts/runtimeContractManifest.js";
2
+ import { GROK_WORKER_VISIBLE_TOOLS } from "../contracts/grokWorkerContract.js";
3
+ import { DEFAULT_GROK_BROKER_MODEL_POLICY, parseGrokBrokerModelPolicy } from "./grokBrokerModelPolicy.js";
4
+ const MAX_BODY = 2 * 1024 * 1024;
5
+ /**
6
+ * Authorizes one worker request and rebuilds it for the provider.
7
+ *
8
+ * Everything that decides spend is checked here, before a bearer is attached
9
+ * and before any upstream call:
10
+ * - the client version is exactly the pinned Grok CLI (`GROK_ENGINE_BROKER.grokCliVersion`);
11
+ * - the body model and `reasoning_effort` are exactly the declared policy, and
12
+ * the model override header follows that declaration instead of a constant;
13
+ * - the offered tool names are exactly the lean visible set. Grok 1.0.34 turns
14
+ * an unmappable `--tools` entry into its full 19-tool set, and its per-turn
15
+ * `session_title` request carries a single forced tool; both are refused.
16
+ */
17
+ export function authorizeGrokBrokerProxyRequest(input, capabilities, bearer, policy = DEFAULT_GROK_BROKER_MODEL_POLICY) {
18
+ const declared = parseGrokBrokerModelPolicy(policy);
19
+ if (input.method !== "POST" || input.pathname !== "/v1/chat/completions" || input.body.byteLength < 2 || input.body.byteLength > MAX_BODY)
20
+ throw new Error("broker proxy request rejected");
21
+ const authorization = input.headers.authorization;
22
+ const match = authorization?.match(/^Bearer ([A-Za-z0-9_-]{40,})$/u);
23
+ if (match === null || match === undefined)
24
+ throw new Error("broker proxy request rejected");
25
+ const scope = capabilities.authorizeToken(match[1]);
26
+ if (scope === undefined || (input.agentId !== undefined && scope.agentId !== input.agentId) || (input.turnId !== undefined && scope.turnId !== input.turnId))
27
+ throw new Error("broker proxy request rejected");
28
+ if (!bearer || /[\r\n]/u.test(bearer))
29
+ throw new Error("broker credential authority unavailable");
30
+ const clientVersion = input.headers["x-grok-client-version"];
31
+ if (clientVersion !== GROK_ENGINE_BROKER.grokCliVersion)
32
+ throw new Error("broker proxy request rejected");
33
+ let parsed;
34
+ // `__proto__` is refused at any depth: JSON.parse makes it an ordinary own
35
+ // member, but an upstream JavaScript parser may treat it as a prototype.
36
+ try {
37
+ parsed = JSON.parse(Buffer.from(input.body).toString("utf8"), (key, value) => {
38
+ if (key === "__proto__")
39
+ throw new Error("broker proxy request rejected");
40
+ return value;
41
+ });
42
+ }
43
+ catch {
44
+ throw new Error("broker proxy request rejected");
45
+ }
46
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || parsed.stream !== true || !Array.isArray(parsed.messages))
47
+ throw new Error("broker proxy request rejected");
48
+ if (parsed.model !== declared.model || parsed.reasoning_effort !== declared.reasoningEffort)
49
+ throw new Error("broker proxy request rejected");
50
+ if (!exactLeanTools(parsed.tools))
51
+ throw new Error("broker proxy request rejected");
52
+ if (Object.keys(parsed).some((key) => !LEAN_BODY_MEMBERS.has(key)) || !validStreamOptions(parsed.stream_options))
53
+ throw new Error("broker proxy request rejected");
54
+ // Keep origin/main's production handling: UTF-8 replacement decoding, then
55
+ // serialize the validated object (including last-member-wins duplicates).
56
+ // Only a clocked turn takes the stricter date rewrite before this gate.
57
+ return {
58
+ url: "https://cli-chat-proxy.grok.com/v1/chat/completions",
59
+ headers: {
60
+ authorization: `Bearer ${bearer}`, "content-type": "application/json",
61
+ "x-xai-token-auth": "xai-grok-cli", "x-grok-model-override": declared.model,
62
+ "x-grok-client-version": clientVersion, "x-grok-client-identifier": "grok-shell"
63
+ },
64
+ body: Buffer.from(JSON.stringify(parsed))
65
+ };
66
+ }
67
+ /** Top-level members of a Grok 1.0.34 lean worker chat-completions body (live stub capture). */
68
+ const LEAN_BODY_MEMBERS = new Set(["messages", "model", "reasoning_effort", "stream", "stream_options", "tools"]);
69
+ /** Members of each lean tool `function` entry (live stub capture). */
70
+ const LEAN_FUNCTION_MEMBERS = new Set(["description", "name", "parameters"]);
71
+ const validStreamOptions = (value) => value === undefined
72
+ || (value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every((key) => key === "include_usage") && typeof value.include_usage === "boolean");
73
+ export function exactLeanTools(tools) {
74
+ if (!Array.isArray(tools) || tools.length !== GROK_WORKER_VISIBLE_TOOLS.length)
75
+ return false;
76
+ const names = tools.map((tool) => {
77
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool) || tool.type !== "function" || Object.keys(tool).some((key) => key !== "type" && key !== "function"))
78
+ return undefined;
79
+ const fn = tool.function;
80
+ if (fn === null || typeof fn !== "object" || Array.isArray(fn) || Object.keys(fn).some((key) => !LEAN_FUNCTION_MEMBERS.has(key)))
81
+ return undefined;
82
+ return fn.name;
83
+ });
84
+ return JSON.stringify([...names].sort()) === JSON.stringify(GROK_WORKER_VISIBLE_TOOLS);
85
+ }
@@ -0,0 +1,4 @@
1
+ export declare function acquireGrokBrokerRealmLease(root: string, flock?: string): Promise<Readonly<{
2
+ close(): Promise<void>;
3
+ }>>;
4
+ //# sourceMappingURL=grokBrokerRealmLease.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerRealmLease.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerRealmLease.ts"],"names":[],"mappings":"AAMA,wBAAsB,2BAA2B,CAAC,IAAI,EAAC,MAAM,EAAC,KAAK,SAAQ,GAAE,OAAO,CAAC,QAAQ,CAAC;IAAC,KAAK,IAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAAC,CAAC,CAAC,CAGtH"}
@@ -0,0 +1,33 @@
1
+ import { spawnRealTime as spawn } from "./taskClockProcess.js";
2
+ import { constants } from "node:fs";
3
+ import { open } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { terminateChild, trackCliChild } from "../pi/cliProcess.js";
6
+ export async function acquireGrokBrokerRealmLease(root, flock = "flock") {
7
+ const handle = await open(path.join(root, ".daimon-broker-lease"), constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW, 0o600);
8
+ let child;
9
+ try {
10
+ const stat = await handle.stat();
11
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || stat.nlink !== 1 || (stat.mode & 0o777) !== 0o600)
12
+ throw new Error();
13
+ child = trackCliChild(spawn("/bin/sh", ["-c", '"$1" --exclusive --nonblock --conflict-exit-code 73 3 || exit 73; printf "ready\\n"; IFS= read -r _hold || :', "daimon-grok-broker-lease", flock], { detached: process.platform !== "win32", env: { PATH: process.env.PATH, LANG: "C", LC_ALL: "C", TZ: "UTC" }, stdio: ["pipe", "pipe", "ignore", handle.fd] }));
14
+ await ready(child);
15
+ let closed = false;
16
+ return { close: async () => { if (closed)
17
+ return; closed = true; const exited = new Promise((resolve) => { if (child.exitCode !== null || child.signalCode !== null)
18
+ return resolve(true); child.once("close", () => resolve(true)); setTimeout(() => resolve(false), 500); }); child.stdin?.end(); if (!await exited)
19
+ await terminateChild(child); } };
20
+ }
21
+ catch {
22
+ if (child)
23
+ await terminateChild(child).catch(() => undefined);
24
+ throw new Error("Grok broker realm is already in use or cannot be leased");
25
+ }
26
+ finally {
27
+ await handle.close();
28
+ }
29
+ }
30
+ function ready(child) { return new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error()), 5000); const fail = () => { clearTimeout(timer); reject(new Error()); }; child.once("error", fail); child.once("close", fail); child.stdout?.once("data", (chunk) => { clearTimeout(timer); if (chunk.toString() === "ready\n")
31
+ resolve();
32
+ else
33
+ reject(new Error()); }); }); }
@@ -0,0 +1,2 @@
1
+ export declare function refreshGrokBrokerCredential(command: string, grokHome: string, timeoutMs?: number): Promise<void>;
2
+ //# sourceMappingURL=grokBrokerRefresh.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerRefresh.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerRefresh.ts"],"names":[],"mappings":"AAIA,wBAAsB,2BAA2B,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAKtH"}
@@ -0,0 +1,15 @@
1
+ import { spawnRealTime as spawn } from "./taskClockProcess.js";
2
+ import { readChild } from "../pi/cliChildOutput.js";
3
+ import { terminateChild, trackCliChild } from "../pi/cliProcess.js";
4
+ export async function refreshGrokBrokerCredential(command, grokHome, timeoutMs = 15_000) {
5
+ const child = trackCliChild(spawn(command, ["models"], { detached: process.platform !== "win32", env: { GROK_HOME: grokHome, HOME: grokHome, PATH: process.env.PATH, LANG: "C", LC_ALL: "C", TZ: "UTC" }, stdio: ["ignore", "pipe", "pipe"] }));
6
+ try {
7
+ await readChild(child, timeoutMs, []);
8
+ }
9
+ catch {
10
+ throw new Error("Grok broker credential refresh failed");
11
+ }
12
+ finally {
13
+ await terminateChild(child).catch(() => undefined);
14
+ }
15
+ }