@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,337 @@
1
+ import { GROK_ENGINE_BROKER } from "../contracts/runtimeContractManifest.js";
2
+ import { sumEngineBrokerTurnUsage } from "./engineBrokerTurnAccounting.js";
3
+ /**
4
+ * The weight a cached prompt read carries against the token ceiling.
5
+ *
6
+ * The ceiling exists to bound spend, and a cached read is billed at a quarter
7
+ * of a fresh input token (xAI's published cached-input rate for the Grok 4
8
+ * family). Counting it at full weight made the ceiling a context-size limit
9
+ * instead: a writing or composing turn re-reads its whole conversation on
10
+ * every request, 85–90% of it from cache, and production turns died at a
11
+ * 1.1M "ceiling" having spent about a third of that. Fresh input, output and
12
+ * reasoning still count in full; the sealed usage and ledgers are unchanged
13
+ * and keep every cached token at its raw count.
14
+ */
15
+ export const GROK_CACHED_INPUT_TOKEN_WEIGHT = 0.25;
16
+ /** What one request's usage costs against `maxTokens`: everything at full weight except cached reads. */
17
+ export const grokCeilingTokens = (usage) => usage.total - usage.cacheRead + Math.ceil(usage.cacheRead * GROK_CACHED_INPUT_TOKEN_WEIGHT);
18
+ /**
19
+ * The proxy's per-turn spend gate.
20
+ *
21
+ * Every forwarded model request of one turn passes through {@link admit}
22
+ * *before* a bearer is attached, so the checks are hard for requests and
23
+ * elapsed time and between-requests for tokens:
24
+ *
25
+ * - `maxRequests`: request `maxRequests + 1` is refused; upstream never sees it.
26
+ * - `timeoutMs`: a request arriving after the deadline is refused (the broker's
27
+ * own timer additionally kills a worker that is mid-request).
28
+ * - `maxTokens`: checked against the running total of upstream-reported usage
29
+ * of the requests already answered. A request is admitted while that total is
30
+ * still below the ceiling, so the overshoot is bounded by exactly one
31
+ * request's usage — the last admitted one. Cached prompt reads count at
32
+ * {@link GROK_CACHED_INPUT_TOKEN_WEIGHT} ({@link grokCeilingTokens}); an
33
+ * uncached replay (P0 observed one at +55%) is fresh input and counts in full.
34
+ *
35
+ * The first limit that fires is sticky: every later request is refused with
36
+ * the same reason, and `onLimit` runs once.
37
+ *
38
+ * The token bound is only a bound if no request can be admitted on a total
39
+ * that an in-flight request has not yet reported into. So a turn has at most
40
+ * ONE upstream request in flight: a second request arriving before the first
41
+ * settled is refused (`busy`, HTTP 429) without being counted or tripping a
42
+ * limit. Grok's headless loop is sequential — every live capture (P1
43
+ * live-round1, P2 live) shows each request ending before the next starts — so
44
+ * this refuses only a worker that is not behaving like Grok. Tripping a limit
45
+ * (including the broker's timer) aborts that in-flight upstream call through
46
+ * its own `AbortSignal` rather than letting it run to completion.
47
+ */
48
+ export class GrokBrokerTurnMeter {
49
+ limits;
50
+ onLimit;
51
+ now;
52
+ startedAt;
53
+ timings = [];
54
+ tokens = 0;
55
+ reason = "none";
56
+ inFlight;
57
+ final;
58
+ activityAt;
59
+ constructor(limits, onLimit = () => undefined, now = Date.now) {
60
+ this.limits = limits;
61
+ this.onLimit = onLimit;
62
+ this.now = now;
63
+ this.startedAt = now();
64
+ this.activityAt = this.startedAt;
65
+ }
66
+ /** Returns the request index and its upstream abort signal when admitted, the limit that refused it, or `busy` while another request is in flight. */
67
+ admit() {
68
+ if (this.reason === "none") {
69
+ if (this.now() - this.startedAt >= this.limits.timeoutMs)
70
+ this.trip("timeout");
71
+ else if (this.timings.length >= this.limits.maxRequests)
72
+ this.trip("requests");
73
+ else if (this.tokens >= this.limits.maxTokens)
74
+ this.trip("tokens");
75
+ }
76
+ if (this.reason !== "none")
77
+ return { refused: this.reason };
78
+ if (this.inFlight !== undefined)
79
+ return { busy: true };
80
+ this.timings.push({ startedAt: new Date(this.now()).toISOString() });
81
+ // A new request means the previous answer was not the last one.
82
+ this.final = undefined;
83
+ this.activityAt = this.now();
84
+ const controller = new AbortController();
85
+ this.inFlight = { index: this.timings.length - 1, controller };
86
+ return { index: this.inFlight.index, signal: controller.signal };
87
+ }
88
+ /**
89
+ * Records one admitted request's end, its usage, and the tool-call names its
90
+ * response carried. A response without valid usage (absent, malformed,
91
+ * implausible, or a failed/aborted call) is charged a conservative estimate
92
+ * from the request body size, so a missing `usage` can never silently disable
93
+ * the token ceiling. `toolCalls` is observation only: it never affects
94
+ * admission, the running total, or any limit.
95
+ *
96
+ * `finalReply` is the answer text of a response that called no tool and
97
+ * stopped ({@link parseGrokFinalReply}). It is recorded only when the same
98
+ * response decoded to zero tool calls, and only for the request still the
99
+ * latest: it is what lets the broker end a turn whose worker has finished but
100
+ * not exited, and report finished work whose stdout the launcher refused.
101
+ */
102
+ settle(index, usage, requestBytes, toolCalls, finalReply) {
103
+ const timing = this.timings[index];
104
+ if (timing === undefined || timing.endedAt !== undefined)
105
+ return;
106
+ if (this.inFlight?.index === index)
107
+ this.inFlight = undefined;
108
+ timing.endedAt = new Date(this.now()).toISOString();
109
+ if (usage === undefined) {
110
+ timing.usage = estimateGrokRequestUsage(requestBytes);
111
+ timing.estimated = true;
112
+ }
113
+ else
114
+ timing.usage = usage;
115
+ if (toolCalls !== undefined)
116
+ timing.toolCalls = toolCalls;
117
+ this.tokens += grokCeilingTokens(timing.usage);
118
+ this.activityAt = this.now();
119
+ if (finalReply !== undefined && toolCalls !== undefined && toolCalls.length === 0 && index === this.timings.length - 1)
120
+ this.final = { index, text: finalReply, at: this.activityAt };
121
+ }
122
+ /** The turn's final reply, while no later request has been admitted. */
123
+ finalReply() { return this.final; }
124
+ /** Whether a model request is in flight right now. */
125
+ busy() { return this.inFlight !== undefined; }
126
+ /** When a model request last started or settled (the meter's construction before any). */
127
+ lastActivityAt() { return this.activityAt; }
128
+ /** Trips a limit from outside the request path (the broker's wall-clock timer). */
129
+ trip(reason) {
130
+ if (this.reason !== "none")
131
+ return;
132
+ this.reason = reason;
133
+ this.abortInFlight();
134
+ this.onLimit(reason);
135
+ }
136
+ /** Aborts the in-flight upstream call, if any (limit trip, or the broker ending the turn). */
137
+ abortInFlight() { this.inFlight?.controller.abort(); }
138
+ snapshot() {
139
+ const measured = this.timings.flatMap((timing) => timing.usage === undefined ? [] : [timing.usage]);
140
+ return { requests: this.timings.length, tokens: this.tokens, limitReason: this.reason, usage: sumEngineBrokerTurnUsage(measured), estimatedRequests: this.timings.filter((timing) => timing.estimated === true).length, timings: this.timings.map((timing) => Object.freeze({ ...timing })) };
141
+ }
142
+ }
143
+ const { requestUsageMaxTokens, missingUsageEstimate } = GROK_ENGINE_BROKER.turnLimits;
144
+ /** The charge for a request without valid usage: `ceil(bodyBytes / 2)` input plus a fixed output allowance. */
145
+ export const estimateGrokRequestUsage = (requestBytes) => {
146
+ const input = Math.ceil(Math.max(0, requestBytes) / missingUsageEstimate.inputBytesPerToken), output = missingUsageEstimate.outputTokens;
147
+ return { input, cacheRead: 0, cacheWrite: 0, output, total: input + output };
148
+ };
149
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
150
+ const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
151
+ /**
152
+ * Upstream-reported usage of one chat-completions response, or `undefined`.
153
+ *
154
+ * The proxy buffers the whole upstream body, so the last `usage` object of an
155
+ * SSE stream (`stream_options.include_usage`) or of a JSON body is available
156
+ * before the body is returned to the worker. OpenAI-shaped `prompt_tokens`
157
+ * include cached tokens; they are split into disjoint buckets here, and any
158
+ * reasoning tokens reported outside `completion_tokens` (visible as
159
+ * `total_tokens` above prompt + completion) are folded into `output` so the
160
+ * total invariant holds. A malformed block, or one whose total exceeds
161
+ * `GROK_ENGINE_BROKER.turnLimits.requestUsageMaxTokens`, is invalid: never
162
+ * zero-filled and never added — the meter charges an estimate instead.
163
+ */
164
+ export function parseGrokUpstreamUsage(body, contentType) {
165
+ let found;
166
+ for (const candidate of decodeUpstreamResponse(body, contentType) ?? []) {
167
+ if (!isRecord(candidate) || !isRecord(candidate.usage))
168
+ continue;
169
+ // Last usage block wins even when invalid: an implausible final report
170
+ // must not fall back to an earlier, smaller block (the request is then
171
+ // charged the estimate instead).
172
+ found = decodeOpenAiUsage(candidate.usage);
173
+ }
174
+ return found;
175
+ }
176
+ /**
177
+ * Every decodable JSON object of one upstream response: each `data:` event of
178
+ * an SSE stream, or the single body of a JSON response.
179
+ *
180
+ * `undefined` means *nothing* decoded — an unparseable or non-JSON response.
181
+ * Callers must keep that distinct from a decoded response that said nothing,
182
+ * because the ledger never fabricates an observation it did not make.
183
+ */
184
+ function decodeUpstreamResponse(body, contentType) {
185
+ const text = Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("utf8");
186
+ const candidates = [];
187
+ if (contentType?.includes("text/event-stream") === true || text.startsWith("data:")) {
188
+ for (const line of text.split(/\r?\n/u)) {
189
+ if (!line.startsWith("data:"))
190
+ continue;
191
+ const payload = line.slice(5).trim();
192
+ if (payload === "[DONE]" || payload.length === 0)
193
+ continue;
194
+ try {
195
+ candidates.push(JSON.parse(payload));
196
+ }
197
+ catch { /* a non-JSON event carries neither usage nor a tool call */ }
198
+ }
199
+ }
200
+ else {
201
+ try {
202
+ candidates.push(JSON.parse(text));
203
+ }
204
+ catch {
205
+ return undefined;
206
+ }
207
+ }
208
+ return candidates.length === 0 ? undefined : candidates;
209
+ }
210
+ /** At most this many names per request row; a longer list ends in {@link GROK_TOOL_CALL_TRUNCATED}. */
211
+ export const GROK_REQUEST_TOOL_CALLS_MAX = 16;
212
+ /** A `name` that is not a plain short identifier is counted, never passed through. */
213
+ export const GROK_TOOL_CALL_INVALID = "<invalid>";
214
+ export const GROK_TOOL_CALL_TRUNCATED = "<truncated>";
215
+ const TOOL_CALL_NAME = /^[A-Za-z0-9_.-]{1,64}$/u;
216
+ /**
217
+ * The tool-call NAMES one upstream response carried, and nothing else.
218
+ *
219
+ * Two live turns could not answer "did the model ever try `use_tool` or
220
+ * `search_tool`", because the per-request rows recorded timings and tokens but
221
+ * never an attempt. This is that answer, under four rules:
222
+ *
223
+ * - names only. No arguments, no message content, no tokens, no header. A
224
+ * `name` that is not a plain short identifier is recorded as
225
+ * {@link GROK_TOOL_CALL_INVALID} rather than passing provider bytes through;
226
+ * - bounded. At most {@link GROK_REQUEST_TOOL_CALLS_MAX} entries, the last being
227
+ * {@link GROK_TOOL_CALL_TRUNCATED} when the response carried more, so a
228
+ * pathological response cannot write an unbounded row;
229
+ * - absence stays absence. A decoded response that called nothing returns `[]`;
230
+ * a response that could not be decoded returns `undefined` and the row records
231
+ * no field at all;
232
+ * - one streaming call names itself in one delta and streams its arguments in
233
+ * the rest, so a repeat of the same `(choice, call)` index is that same call,
234
+ * not a second attempt.
235
+ */
236
+ export function parseGrokResponseToolNames(body, contentType) {
237
+ const candidates = decodeUpstreamResponse(body, contentType);
238
+ if (candidates === undefined)
239
+ return undefined;
240
+ const names = [], seen = new Set();
241
+ scan: for (const candidate of candidates) {
242
+ if (!isRecord(candidate) || !Array.isArray(candidate.choices))
243
+ continue;
244
+ for (const choice of candidate.choices) {
245
+ if (!isRecord(choice))
246
+ continue;
247
+ for (const source of [choice.delta, choice.message]) {
248
+ if (!isRecord(source) || !Array.isArray(source.tool_calls))
249
+ continue;
250
+ for (const call of source.tool_calls) {
251
+ if (!isRecord(call) || !isRecord(call.function))
252
+ continue;
253
+ const name = call.function.name;
254
+ // An arguments-only delta names nothing; it is not an attempt of its own.
255
+ if (typeof name !== "string" || name.length === 0)
256
+ continue;
257
+ if (typeof choice.index === "number" && typeof call.index === "number") {
258
+ const key = `${choice.index}:${call.index}`;
259
+ if (seen.has(key))
260
+ continue;
261
+ seen.add(key);
262
+ }
263
+ names.push(TOOL_CALL_NAME.test(name) ? name : GROK_TOOL_CALL_INVALID);
264
+ if (names.length > GROK_REQUEST_TOOL_CALLS_MAX)
265
+ break scan;
266
+ }
267
+ }
268
+ }
269
+ }
270
+ return names.length > GROK_REQUEST_TOOL_CALLS_MAX ? [...names.slice(0, GROK_REQUEST_TOOL_CALLS_MAX - 1), GROK_TOOL_CALL_TRUNCATED] : names;
271
+ }
272
+ /** The most of a final reply the broker reports; the rest is cut at a marker that says how much. */
273
+ export const GROK_FINAL_REPLY_MAX_BYTES = 64 * 1024;
274
+ /**
275
+ * The answer text of a response that *stopped*: every `delta.content` of a
276
+ * streamed response (or the `message.content` of a JSON one) in order, when
277
+ * some choice finished with `finish_reason: "stop"` and none with anything else.
278
+ *
279
+ * `undefined` means the response is not known to be final — undecodable, no
280
+ * finish reason, or one that asks for a tool. The caller additionally requires
281
+ * the same body to have decoded to zero tool calls. The text is bounded by
282
+ * {@link boundGrokFinalReply}, so a runaway answer can never make the turn's
283
+ * own report the thing that fails it.
284
+ */
285
+ export function parseGrokFinalReply(body, contentType) {
286
+ const candidates = decodeUpstreamResponse(body, contentType);
287
+ if (candidates === undefined)
288
+ return undefined;
289
+ let text = "", stopped = false;
290
+ for (const candidate of candidates) {
291
+ if (!isRecord(candidate) || !Array.isArray(candidate.choices))
292
+ continue;
293
+ for (const choice of candidate.choices) {
294
+ if (!isRecord(choice))
295
+ continue;
296
+ for (const source of [choice.delta, choice.message])
297
+ if (isRecord(source) && typeof source.content === "string")
298
+ text += source.content;
299
+ // Only `stop` is a finished answer: `length` was cut off mid-answer and
300
+ // `content_filter` withheld it, so neither is work done.
301
+ if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
302
+ if (choice.finish_reason !== "stop")
303
+ return undefined;
304
+ stopped = true;
305
+ }
306
+ }
307
+ }
308
+ return stopped ? boundGrokFinalReply(text) : undefined;
309
+ }
310
+ /** `text` whole when it fits {@link GROK_FINAL_REPLY_MAX_BYTES}, else its head and a marker naming what was cut — never a failure. */
311
+ export function boundGrokFinalReply(text, maxBytes = GROK_FINAL_REPLY_MAX_BYTES) {
312
+ const bytes = Buffer.byteLength(text, "utf8");
313
+ if (bytes <= maxBytes)
314
+ return text;
315
+ const marker = (cut) => `\n[… ${cut} bytes truncated by the Daimon broker …]`;
316
+ const budget = Math.max(0, maxBytes - Buffer.byteLength(marker(bytes)));
317
+ // Cut on a code point: a byte-counted window must not leave half a character behind.
318
+ const head = new TextDecoder("utf-8", { fatal: false }).decode(Buffer.from(text, "utf8").subarray(0, budget)).replace(/\uFFFD$/u, "");
319
+ return `${head}${marker(bytes - Buffer.byteLength(head, "utf8"))}`;
320
+ }
321
+ function decodeOpenAiUsage(usage) {
322
+ const prompt = count(usage.prompt_tokens), completion = count(usage.completion_tokens);
323
+ if (prompt === undefined || completion === undefined)
324
+ return undefined;
325
+ const details = isRecord(usage.prompt_tokens_details) ? usage.prompt_tokens_details : {};
326
+ const cached = details.cached_tokens === undefined ? 0 : count(details.cached_tokens);
327
+ const reported = usage.total_tokens === undefined ? prompt + completion : count(usage.total_tokens);
328
+ if (cached === undefined || reported === undefined || cached > prompt)
329
+ return undefined;
330
+ const total = Math.max(reported, prompt + completion);
331
+ const completionDetails = isRecord(usage.completion_tokens_details) ? usage.completion_tokens_details : {};
332
+ const reasoning = count(completionDetails.reasoning_tokens);
333
+ const output = total - prompt;
334
+ if (total > requestUsageMaxTokens)
335
+ return undefined;
336
+ return { input: prompt - cached, cacheRead: cached, cacheWrite: 0, output, total, ...(reasoning === undefined || reasoning > output ? {} : { reasoning }) };
337
+ }
@@ -0,0 +1,89 @@
1
+ import { type GrokWorkerConfigVariant } from "../contracts/grokBrokerTaskClock.js";
2
+ import { type GrokBrokerModelPolicy } from "./grokBrokerModelPolicy.js";
3
+ export { DAIMON_GROK_SYSTEM_PROMPT, GROK_WORKER_MAX_TURNS, GROK_WORKER_TOOL_IDS, GROK_WORKER_VISIBLE_TOOLS } from "../contracts/grokWorkerContract.js";
4
+ /**
5
+ * Bundled skills shipped by Grok CLI 1.0.34. Names are version-specific:
6
+ * `[skills] disabled` removed all ~2.1k skill tokens in the P0 matrix, and a
7
+ * CLI bump must re-derive this list rather than inherit it.
8
+ */
9
+ export declare const GROK_1_0_34_BUNDLED_SKILLS: readonly ["build-with-ai", "code-review", "create-skill", "create-workflow", "design", "docx", "execute-plan", "game-animation-frames", "game-asset-core", "game-character-consistency", "game-tilesets", "game-ui-icons", "imagine", "implement", "learn", "long-running-background-tasks", "pdf", "pptx", "pr-babysit", "resume-claude", "resume-codex", "resume-cursor", "review", "skill-design-principles", "statusline"];
10
+ /** The worker's only model id; the argv selects it and the proxy never sees another. */
11
+ export declare const GROK_BROKER_WORKER_MODEL_ID: "daimon-broker-grok";
12
+ /**
13
+ * Grok 1.0.34 sends a `session_title` model request before every headless
14
+ * turn, and no config key or environment variable disables it
15
+ * (`features.title_refresh` governs only the later refresh; verified against a
16
+ * loopback stub). `[models] session_summary` does select the model it uses, so
17
+ * the title goes to a hidden model whose endpoint is the broker's own provider
18
+ * proxy with a placeholder key that can never be a turn capability (shorter
19
+ * than the 40-character capability alphabet). The proxy refuses it before any
20
+ * capability lookup, isolation guard, credential read, or upstream call, and
21
+ * Grok falls back to the truncated prompt as the title. The endpoint is always
22
+ * listening while a worker runs, so the refusal is bounded by one loopback
23
+ * round trip rather than by a connect timeout, and a prompt-derived title is
24
+ * never delivered anywhere but Daimon's own proxy.
25
+ */
26
+ export declare const GROK_SESSION_TITLE_SINK_MODEL_ID: "daimon-session-title-disabled";
27
+ export declare const GROK_SESSION_TITLE_SINK_KEY: "session-title-disabled";
28
+ /**
29
+ * The turn-scoped proxy capability reaches the worker's only model through
30
+ * `env_key`, set by the native launcher. Grok 1.0.34 accepts
31
+ * `[auth_provider.<name>]` tables but never runs the helper for a custom model
32
+ * (verified against a loopback stub: no helper invocation and no Authorization
33
+ * header, with and without `args`, `api_backend`, `model_providers`, or a
34
+ * passwd-home config), while `env_key` attaches the bearer on every request.
35
+ * The capability is exactly as exposed as `DAIMON_MCP_CAPABILITY`: visible to
36
+ * the worker's own tool children, which run network-restricted, and revoked
37
+ * when the turn ends.
38
+ */
39
+ export declare const GROK_BROKER_PROVIDER_CAPABILITY_ENV: "DAIMON_PROVIDER_CAPABILITY";
40
+ type WorkerEndpoints = Readonly<{
41
+ proxyPort: number;
42
+ mcpUrl: string;
43
+ }>;
44
+ /**
45
+ * Sections shared by every Grok worker Daimon configures, broker or direct.
46
+ *
47
+ * Each toggle is either measured (skills −2.1k tokens, workflows −314, the
48
+ * per-turn `session_title` model request) or behavioural hardening that P0
49
+ * showed to be token-neutral and warning-free on 1.0.34.
50
+ */
51
+ export declare const renderGrokLeanBaseConfig: () => string;
52
+ /**
53
+ * `max_retries = 0` on the worker's own model, for the same reason its two
54
+ * siblings already carry it (the session-title sink above,
55
+ * `grokInferenceClientConfig.ts` for the evaluator): with Grok 1.0.34's
56
+ * default, a refused or failed request is retried with backoff **past 45 s**
57
+ * instead of failing in ~0.35 s, and the retries are blind — one live turn
58
+ * emitted the same refusal fifteen times over five minutes, spent $0, and died
59
+ * with no account of why. Only this model block was left on the default, so
60
+ * the one request path that spends money was also the only one that could
61
+ * stall a turn for minutes after its work was done. Daimon owns the retry
62
+ * decision here because the proxy is the thing being retried: a genuinely
63
+ * transient fault is already answered 503 and is the broker's to retry, and
64
+ * anything else is a refusal that repeating cannot fix. The worker instead
65
+ * fails fast and the turn reaches the host with a status.
66
+ */
67
+ /**
68
+ * The only source of broker worker `config.toml` bytes.
69
+ *
70
+ * Effort is declared here, not on the compiled launcher argv: the argv is one
71
+ * constant for every registration while effort is declared per deployment, and
72
+ * Grok 1.0.34 drops both `--reasoning-effort` and `[models]
73
+ * default_reasoning_effort` unless the model advertises effort support. A
74
+ * one-entry `reasoning_efforts` table makes the declared effort the model's
75
+ * default *and* its closed enum, so it reaches the request body and nothing
76
+ * else can be selected; the proxy then re-verifies it on every body.
77
+ */
78
+ export declare function renderGrokBrokerWorkerConfig(policy?: Partial<GrokBrokerModelPolicy>, variant?: GrokWorkerConfigVariant, slot?: number): string;
79
+ /** Explicit-endpoint variant for the local live probe; production bytes come only from the function above. */
80
+ export declare function renderGrokBrokerWorkerConfigWith(policy: GrokBrokerModelPolicy, endpoints: WorkerEndpoints): string;
81
+ export declare const grokBrokerWorkerConfigSha256: (policy?: Partial<GrokBrokerModelPolicy>, variant?: GrokWorkerConfigVariant, slot?: number) => string;
82
+ /** Validate the slot-zero template pin before deriving bytes for another canonical slot path. */
83
+ export declare function grokBrokerWorkerConfigPins(policy: GrokBrokerModelPolicy, slot?: number): Readonly<Record<GrokWorkerConfigVariant, string>>;
84
+ /**
85
+ * TypeScript mirror of the argv compiled into `native/engineBrokerLauncherCore.inc`.
86
+ * `native/launcherArgv.test.ts` parses the C source and fails on any divergence.
87
+ */
88
+ export declare const renderGrokBrokerWorkerArgs: (promptFile: string, cwd: string) => readonly string[];
89
+ //# sourceMappingURL=grokBrokerWorkerConfig.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokBrokerWorkerConfig.d.ts","sourceRoot":"","sources":["../../src/runtime/grokBrokerWorkerConfig.ts"],"names":[],"mappings":"AAGA,OAAO,EAA0B,KAAK,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAK3G,OAAO,EAA8B,KAAK,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAEpG,OAAO,EAAE,yBAAyB,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAEvJ;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,gaAK5B,CAAC;AAEZ,wFAAwF;AACxF,eAAO,MAAM,2BAA2B,EAAG,oBAA6B,CAAC;AAEzE;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,gCAAgC,EAAG,+BAAwC,CAAC;AACzF,eAAO,MAAM,2BAA2B,EAAG,wBAAiC,CAAC;AAM7E;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mCAAmC,EAAG,4BAAqC,CAAC;AAEzF,KAAK,eAAe,GAAG,QAAQ,CAAC;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAMvE;;;;;;GAMG;AACH,eAAO,MAAM,wBAAwB,QAAO,MAQhC,CAAC;AAEb;;;;;;;;;;;;;;GAcG;AACH;;;;;;;;;;GAUG;AACH,wBAAgB,4BAA4B,CAAC,MAAM,GAAE,OAAO,CAAC,qBAAqB,CAAM,EAAE,OAAO,GAAE,uBAAqC,EAAE,IAAI,SAAI,GAAG,MAAM,CAS1J;AAED,8GAA8G;AAC9G,wBAAgB,gCAAgC,CAAC,MAAM,EAAE,qBAAqB,EAAE,SAAS,EAAE,eAAe,GAAG,MAAM,CAgBlH;AAED,eAAO,MAAM,4BAA4B,GAAI,SAAQ,OAAO,CAAC,qBAAqB,CAAM,EAAE,UAAS,uBAAqC,EAAE,aAAQ,KAAG,MACrD,CAAC;AAEjG,iGAAiG;AACjG,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,qBAAqB,EAAE,IAAI,SAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAC,CAKrI;AAED;;;GAGG;AACH,eAAO,MAAM,0BAA0B,GAAI,YAAY,MAAM,EAAE,KAAK,MAAM,KAAG,SAAS,MAAM,EAU3F,CAAC"}
@@ -0,0 +1,154 @@
1
+ import { brokerTaskClockFileFor } from "./grokBrokerSlot.js";
2
+ import { createHash } from "node:crypto";
3
+ import path from "node:path";
4
+ import { GROK_BROKER_TASK_CLOCK } from "../contracts/grokBrokerTaskClock.js";
5
+ import { shellEnvironmentPolicyEntries } from "../contracts/shellEnvironmentPolicy.js";
6
+ import { GROK_ENGINE_BROKER } from "../contracts/runtimeContractManifest.js";
7
+ import { DAIMON_GROK_SYSTEM_PROMPT, GROK_WORKER_MAX_TURNS, GROK_WORKER_TOOL_IDS } from "../contracts/grokWorkerContract.js";
8
+ import { parseGrokBrokerModelPolicy } from "./grokBrokerModelPolicy.js";
9
+ export { DAIMON_GROK_SYSTEM_PROMPT, GROK_WORKER_MAX_TURNS, GROK_WORKER_TOOL_IDS, GROK_WORKER_VISIBLE_TOOLS } from "../contracts/grokWorkerContract.js";
10
+ /**
11
+ * Bundled skills shipped by Grok CLI 1.0.34. Names are version-specific:
12
+ * `[skills] disabled` removed all ~2.1k skill tokens in the P0 matrix, and a
13
+ * CLI bump must re-derive this list rather than inherit it.
14
+ */
15
+ export const GROK_1_0_34_BUNDLED_SKILLS = Object.freeze([
16
+ "build-with-ai", "code-review", "create-skill", "create-workflow", "design", "docx", "execute-plan",
17
+ "game-animation-frames", "game-asset-core", "game-character-consistency", "game-tilesets", "game-ui-icons",
18
+ "imagine", "implement", "learn", "long-running-background-tasks", "pdf", "pptx", "pr-babysit",
19
+ "resume-claude", "resume-codex", "resume-cursor", "review", "skill-design-principles", "statusline"
20
+ ]);
21
+ /** The worker's only model id; the argv selects it and the proxy never sees another. */
22
+ export const GROK_BROKER_WORKER_MODEL_ID = "daimon-broker-grok";
23
+ /**
24
+ * Grok 1.0.34 sends a `session_title` model request before every headless
25
+ * turn, and no config key or environment variable disables it
26
+ * (`features.title_refresh` governs only the later refresh; verified against a
27
+ * loopback stub). `[models] session_summary` does select the model it uses, so
28
+ * the title goes to a hidden model whose endpoint is the broker's own provider
29
+ * proxy with a placeholder key that can never be a turn capability (shorter
30
+ * than the 40-character capability alphabet). The proxy refuses it before any
31
+ * capability lookup, isolation guard, credential read, or upstream call, and
32
+ * Grok falls back to the truncated prompt as the title. The endpoint is always
33
+ * listening while a worker runs, so the refusal is bounded by one loopback
34
+ * round trip rather than by a connect timeout, and a prompt-derived title is
35
+ * never delivered anywhere but Daimon's own proxy.
36
+ */
37
+ export const GROK_SESSION_TITLE_SINK_MODEL_ID = "daimon-session-title-disabled";
38
+ export const GROK_SESSION_TITLE_SINK_KEY = "session-title-disabled";
39
+ const renderSessionTitleSink = (proxyPort) => [
40
+ `[model.${GROK_SESSION_TITLE_SINK_MODEL_ID}]`, 'model = "disabled"', `base_url = "http://127.0.0.1:${proxyPort}/v1"`, `api_key = "${GROK_SESSION_TITLE_SINK_KEY}"`,
41
+ "max_retries = 0", "hidden = true", ""
42
+ ];
43
+ /**
44
+ * The turn-scoped proxy capability reaches the worker's only model through
45
+ * `env_key`, set by the native launcher. Grok 1.0.34 accepts
46
+ * `[auth_provider.<name>]` tables but never runs the helper for a custom model
47
+ * (verified against a loopback stub: no helper invocation and no Authorization
48
+ * header, with and without `args`, `api_backend`, `model_providers`, or a
49
+ * passwd-home config), while `env_key` attaches the bearer on every request.
50
+ * The capability is exactly as exposed as `DAIMON_MCP_CAPABILITY`: visible to
51
+ * the worker's own tool children, which run network-restricted, and revoked
52
+ * when the turn ends.
53
+ */
54
+ export const GROK_BROKER_PROVIDER_CAPABILITY_ENV = "DAIMON_PROVIDER_CAPABILITY";
55
+ const PRODUCTION_ENDPOINTS = Object.freeze({
56
+ proxyPort: GROK_ENGINE_BROKER.providerProxy.port,
57
+ mcpUrl: `http://${GROK_ENGINE_BROKER.mcpFacade.host}:${GROK_ENGINE_BROKER.mcpFacade.port}${GROK_ENGINE_BROKER.mcpFacade.path}`
58
+ });
59
+ /**
60
+ * Sections shared by every Grok worker Daimon configures, broker or direct.
61
+ *
62
+ * Each toggle is either measured (skills −2.1k tokens, workflows −314, the
63
+ * per-turn `session_title` model request) or behavioural hardening that P0
64
+ * showed to be token-neutral and warning-free on 1.0.34.
65
+ */
66
+ export const renderGrokLeanBaseConfig = () => [
67
+ "[cli]", "auto_update = false", "use_leader = false", "show_tips = false", "",
68
+ "[features]", "telemetry = false", "title_refresh = false", "session_recap = false", "turn_summary = false",
69
+ "repo_status_in_system_prompt = false", "codebase_indexing = false", "backend_tools = false", "ask_user_question = false",
70
+ "image_gen = false", "video_gen = false", "web_fetch = false", "campaigns = false", "managed_config = false", "",
71
+ "[managed_mcps]", "enabled = false", "",
72
+ "[skills]", `disabled = [${GROK_1_0_34_BUNDLED_SKILLS.map((name) => JSON.stringify(name)).join(", ")}]`, "",
73
+ "[workflows]", "enabled = false", ""
74
+ ].join("\n");
75
+ /**
76
+ * `max_retries = 0` on the worker's own model, for the same reason its two
77
+ * siblings already carry it (the session-title sink above,
78
+ * `grokInferenceClientConfig.ts` for the evaluator): with Grok 1.0.34's
79
+ * default, a refused or failed request is retried with backoff **past 45 s**
80
+ * instead of failing in ~0.35 s, and the retries are blind — one live turn
81
+ * emitted the same refusal fifteen times over five minutes, spent $0, and died
82
+ * with no account of why. Only this model block was left on the default, so
83
+ * the one request path that spends money was also the only one that could
84
+ * stall a turn for minutes after its work was done. Daimon owns the retry
85
+ * decision here because the proxy is the thing being retried: a genuinely
86
+ * transient fault is already answered 503 and is the broker's to retry, and
87
+ * anything else is a refusal that repeating cannot fix. The worker instead
88
+ * fails fast and the turn reaches the host with a status.
89
+ */
90
+ /**
91
+ * The only source of broker worker `config.toml` bytes.
92
+ *
93
+ * Effort is declared here, not on the compiled launcher argv: the argv is one
94
+ * constant for every registration while effort is declared per deployment, and
95
+ * Grok 1.0.34 drops both `--reasoning-effort` and `[models]
96
+ * default_reasoning_effort` unless the model advertises effort support. A
97
+ * one-entry `reasoning_efforts` table makes the declared effort the model's
98
+ * default *and* its closed enum, so it reaches the request body and nothing
99
+ * else can be selected; the proxy then re-verifies it on every body.
100
+ */
101
+ export function renderGrokBrokerWorkerConfig(policy = {}, variant = "unclocked", slot = 0) {
102
+ if (variant !== "unclocked" && variant !== "clocked")
103
+ throw new TypeError("invalid Grok worker config variant");
104
+ const base = renderGrokBrokerWorkerConfigWith(parseGrokBrokerModelPolicy(policy), PRODUCTION_ENDPOINTS);
105
+ return variant === "unclocked" ? base : `${base}\n[shell_environment_policy]\n${shellEnvironmentPolicyEntries({
106
+ LD_PRELOAD: GROK_BROKER_TASK_CLOCK.preloadPath,
107
+ FAKETIME_TIMESTAMP_FILE: brokerTaskClockFileFor(slot),
108
+ FAKETIME_DONT_FAKE_MONOTONIC: "1",
109
+ LC_ALL: "C"
110
+ }).join("\n")}\n`;
111
+ }
112
+ /** Explicit-endpoint variant for the local live probe; production bytes come only from the function above. */
113
+ export function renderGrokBrokerWorkerConfigWith(policy, endpoints) {
114
+ const declared = parseGrokBrokerModelPolicy(policy);
115
+ const { proxyPort, mcpUrl } = endpoints;
116
+ if (!Number.isInteger(proxyPort) || proxyPort < 1 || proxyPort > 65_535 || !/^http:\/\/127\.0\.0\.1:\d{1,5}\/mcp$/u.test(mcpUrl)) {
117
+ throw new TypeError("invalid Grok broker worker configuration");
118
+ }
119
+ const label = `${declared.reasoningEffort[0].toUpperCase()}${declared.reasoningEffort.slice(1)}`;
120
+ return [
121
+ renderGrokLeanBaseConfig(),
122
+ "[models]", `default = "${GROK_BROKER_WORKER_MODEL_ID}"`, `default_reasoning_effort = "${declared.reasoningEffort}"`, `session_summary = "${GROK_SESSION_TITLE_SINK_MODEL_ID}"`, "",
123
+ ...renderSessionTitleSink(proxyPort),
124
+ `[model.${GROK_BROKER_WORKER_MODEL_ID}]`, `model = "${declared.model}"`, `base_url = "http://127.0.0.1:${proxyPort}/v1"`, `env_key = "${GROK_BROKER_PROVIDER_CAPABILITY_ENV}"`,
125
+ 'api_backend = "chat_completions"', "context_window = 131072", "supports_backend_search = false", "max_retries = 0", "",
126
+ `[[model.${GROK_BROKER_WORKER_MODEL_ID}.reasoning_efforts]]`, `value = "${declared.reasoningEffort}"`, `label = "${label}"`, "default = true", "",
127
+ "[mcp_servers.daimon]", `url = "${mcpUrl}"`, 'bearer_token_env_var = "DAIMON_MCP_CAPABILITY"', ""
128
+ ].join("\n");
129
+ }
130
+ export const grokBrokerWorkerConfigSha256 = (policy = {}, variant = "unclocked", slot = 0) => createHash("sha256").update(renderGrokBrokerWorkerConfig(policy, variant, slot)).digest("hex");
131
+ /** Validate the slot-zero template pin before deriving bytes for another canonical slot path. */
132
+ export function grokBrokerWorkerConfigPins(policy, slot = 0) {
133
+ const base = GROK_ENGINE_BROKER.worker.clockedConfigSha256[policy.model][policy.reasoningEffort];
134
+ if (grokBrokerWorkerConfigSha256(policy, "clocked", 0) !== base)
135
+ throw new Error("Grok clocked config template drifted from manifest");
136
+ return { unclocked: GROK_ENGINE_BROKER.worker.configSha256[policy.model][policy.reasoningEffort],
137
+ clocked: grokBrokerWorkerConfigSha256(policy, "clocked", slot) };
138
+ }
139
+ /**
140
+ * TypeScript mirror of the argv compiled into `native/engineBrokerLauncherCore.inc`.
141
+ * `native/launcherArgv.test.ts` parses the C source and fails on any divergence.
142
+ */
143
+ export const renderGrokBrokerWorkerArgs = (promptFile, cwd) => {
144
+ if (!path.posix.isAbsolute(promptFile) || !path.posix.isAbsolute(cwd))
145
+ throw new TypeError("invalid Grok broker worker path");
146
+ return [
147
+ "--sandbox", "daimon-strict", "--always-approve", "--no-subagents", "--prompt-file", promptFile,
148
+ "--no-memory", "--disable-web-search", "--no-plan", "--verbatim",
149
+ "--system-prompt-override", DAIMON_GROK_SYSTEM_PROMPT,
150
+ "--tools", GROK_WORKER_TOOL_IDS.join(","),
151
+ "--max-turns", String(GROK_WORKER_MAX_TURNS),
152
+ "--cwd", cwd, "--output-format", "streaming-messages-json", "--model", GROK_BROKER_WORKER_MODEL_ID
153
+ ];
154
+ };