@noopolis/daimon 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (330) hide show
  1. package/README.md +269 -51
  2. package/dist/contracts/attentionContract.d.ts +117 -0
  3. package/dist/contracts/attentionContract.d.ts.map +1 -0
  4. package/dist/contracts/attentionContract.js +14 -0
  5. package/dist/contracts/canonicalJson.d.ts +3 -0
  6. package/dist/contracts/canonicalJson.d.ts.map +1 -0
  7. package/dist/contracts/canonicalJson.js +54 -0
  8. package/dist/contracts/grokWorkerContract.d.ts +74 -0
  9. package/dist/contracts/grokWorkerContract.d.ts.map +1 -0
  10. package/dist/contracts/grokWorkerContract.js +88 -0
  11. package/dist/contracts/organizationRuntimeContract.d.ts +765 -0
  12. package/dist/contracts/organizationRuntimeContract.d.ts.map +1 -0
  13. package/dist/contracts/organizationRuntimeContract.js +121 -0
  14. package/dist/contracts/runtimeContractManifest.d.ts +1615 -0
  15. package/dist/contracts/runtimeContractManifest.d.ts.map +1 -0
  16. package/dist/contracts/runtimeContractManifest.js +181 -0
  17. package/dist/core/credentialRedaction.d.ts +4 -0
  18. package/dist/core/credentialRedaction.d.ts.map +1 -0
  19. package/dist/core/credentialRedaction.js +28 -0
  20. package/dist/mcp/toolServer.d.ts +19 -2
  21. package/dist/mcp/toolServer.d.ts.map +1 -1
  22. package/dist/mcp/toolServer.js +57 -17
  23. package/dist/observability/causalEvents.d.ts +3 -3
  24. package/dist/observability/causalEvents.d.ts.map +1 -1
  25. package/dist/observability/causalEvents.js +103 -15
  26. package/dist/observability/orgObserver.d.ts.map +1 -1
  27. package/dist/observability/orgObserver.js +3 -3
  28. package/dist/pi/agyHeadlessResult.d.ts +60 -0
  29. package/dist/pi/agyHeadlessResult.d.ts.map +1 -0
  30. package/dist/pi/agyHeadlessResult.js +95 -0
  31. package/dist/pi/cliChildOutput.d.ts +67 -0
  32. package/dist/pi/cliChildOutput.d.ts.map +1 -0
  33. package/dist/pi/cliChildOutput.js +269 -0
  34. package/dist/pi/cliEngineRun.d.ts +16 -0
  35. package/dist/pi/cliEngineRun.d.ts.map +1 -0
  36. package/dist/pi/cliEngineRun.js +27 -0
  37. package/dist/pi/cliEngineSpawn.d.ts +55 -0
  38. package/dist/pi/cliEngineSpawn.d.ts.map +1 -0
  39. package/dist/pi/cliEngineSpawn.js +164 -0
  40. package/dist/pi/cliEnvironment.d.ts +12 -0
  41. package/dist/pi/cliEnvironment.d.ts.map +1 -0
  42. package/dist/pi/cliEnvironment.js +32 -0
  43. package/dist/pi/cliMcpRegistration.d.ts +61 -0
  44. package/dist/pi/cliMcpRegistration.d.ts.map +1 -0
  45. package/dist/pi/cliMcpRegistration.js +75 -0
  46. package/dist/pi/cliProcess.d.ts +7 -0
  47. package/dist/pi/cliProcess.d.ts.map +1 -0
  48. package/dist/pi/cliProcess.js +132 -0
  49. package/dist/pi/cliSession.d.ts +84 -24
  50. package/dist/pi/cliSession.d.ts.map +1 -1
  51. package/dist/pi/cliSession.js +313 -158
  52. package/dist/pi/cliTurnMetering.d.ts +60 -0
  53. package/dist/pi/cliTurnMetering.d.ts.map +1 -0
  54. package/dist/pi/cliTurnMetering.js +60 -0
  55. package/dist/pi/codexFilesystemRules.d.ts +3 -0
  56. package/dist/pi/codexFilesystemRules.d.ts.map +1 -0
  57. package/dist/pi/codexFilesystemRules.js +28 -0
  58. package/dist/pi/codexHeadlessResult.d.ts +68 -0
  59. package/dist/pi/codexHeadlessResult.d.ts.map +1 -0
  60. package/dist/pi/codexHeadlessResult.js +122 -0
  61. package/dist/pi/codexRolloutUsage.d.ts +95 -0
  62. package/dist/pi/codexRolloutUsage.d.ts.map +1 -0
  63. package/dist/pi/codexRolloutUsage.js +221 -0
  64. package/dist/pi/engineWakeLimits.d.ts +39 -0
  65. package/dist/pi/engineWakeLimits.d.ts.map +1 -0
  66. package/dist/pi/engineWakeLimits.js +55 -0
  67. package/dist/pi/grokHeadlessResult.d.ts +36 -0
  68. package/dist/pi/grokHeadlessResult.d.ts.map +1 -0
  69. package/dist/pi/grokHeadlessResult.js +118 -0
  70. package/dist/pi/grokHomeMcpRegistration.d.ts +21 -0
  71. package/dist/pi/grokHomeMcpRegistration.d.ts.map +1 -0
  72. package/dist/pi/grokHomeMcpRegistration.js +57 -0
  73. package/dist/pi/grokSandbox.d.ts +11 -0
  74. package/dist/pi/grokSandbox.d.ts.map +1 -0
  75. package/dist/pi/grokSandbox.js +216 -0
  76. package/dist/pi/grokStreamUsage.d.ts +31 -0
  77. package/dist/pi/grokStreamUsage.d.ts.map +1 -0
  78. package/dist/pi/grokStreamUsage.js +51 -0
  79. package/dist/pi/piAgentHandle.d.ts +4 -3
  80. package/dist/pi/piAgentHandle.d.ts.map +1 -1
  81. package/dist/pi/piAgentHandle.js +37 -10
  82. package/dist/pi/piAgentWakeSupport.d.ts +35 -0
  83. package/dist/pi/piAgentWakeSupport.d.ts.map +1 -1
  84. package/dist/pi/piAgentWakeSupport.js +4 -0
  85. package/dist/pi/piHarness.d.ts +10 -1
  86. package/dist/pi/piHarness.d.ts.map +1 -1
  87. package/dist/pi/piHarness.js +61 -8
  88. package/dist/pi/prompts.d.ts +1 -0
  89. package/dist/pi/prompts.d.ts.map +1 -1
  90. package/dist/pi/prompts.js +24 -0
  91. package/dist/pi/turnTrace.d.ts.map +1 -1
  92. package/dist/pi/turnTrace.js +5 -8
  93. package/dist/pi/worldTrajectory.d.ts +1 -1
  94. package/dist/pi/worldTrajectory.d.ts.map +1 -1
  95. package/dist/pi/worldTrajectory.js +3 -3
  96. package/dist/runtime/agySubscriptionBootstrap.d.ts +16 -0
  97. package/dist/runtime/agySubscriptionBootstrap.d.ts.map +1 -0
  98. package/dist/runtime/agySubscriptionBootstrap.js +80 -0
  99. package/dist/runtime/agySubscriptionRealm.d.ts +38 -0
  100. package/dist/runtime/agySubscriptionRealm.d.ts.map +1 -0
  101. package/dist/runtime/agySubscriptionRealm.js +242 -0
  102. package/dist/runtime/attention.d.ts +21 -0
  103. package/dist/runtime/attention.d.ts.map +1 -0
  104. package/dist/runtime/attention.js +36 -0
  105. package/dist/runtime/attentionDispatcher.d.ts +66 -0
  106. package/dist/runtime/attentionDispatcher.d.ts.map +1 -0
  107. package/dist/runtime/attentionDispatcher.js +271 -0
  108. package/dist/runtime/cli.d.ts +7 -0
  109. package/dist/runtime/cli.d.ts.map +1 -0
  110. package/dist/runtime/cli.js +251 -0
  111. package/dist/runtime/codexSandboxProjection.d.ts +17 -0
  112. package/dist/runtime/codexSandboxProjection.d.ts.map +1 -0
  113. package/dist/runtime/codexSandboxProjection.js +40 -0
  114. package/dist/runtime/contract-manifest.json +1 -0
  115. package/dist/runtime/contract-manifest.sha256 +1 -0
  116. package/dist/runtime/contractManifest.d.ts +8 -0
  117. package/dist/runtime/contractManifest.d.ts.map +1 -0
  118. package/dist/runtime/contractManifest.js +4 -0
  119. package/dist/runtime/engineBrokerCapabilities.d.ts +30 -0
  120. package/dist/runtime/engineBrokerCapabilities.d.ts.map +1 -0
  121. package/dist/runtime/engineBrokerCapabilities.js +59 -0
  122. package/dist/runtime/engineBrokerControlClient.d.ts +44 -0
  123. package/dist/runtime/engineBrokerControlClient.d.ts.map +1 -0
  124. package/dist/runtime/engineBrokerControlClient.js +132 -0
  125. package/dist/runtime/engineBrokerCredentialJournal.d.ts +10 -0
  126. package/dist/runtime/engineBrokerCredentialJournal.d.ts.map +1 -0
  127. package/dist/runtime/engineBrokerCredentialJournal.js +17 -0
  128. package/dist/runtime/engineBrokerInferenceProtocol.d.ts +52 -0
  129. package/dist/runtime/engineBrokerInferenceProtocol.d.ts.map +1 -0
  130. package/dist/runtime/engineBrokerInferenceProtocol.js +65 -0
  131. package/dist/runtime/engineBrokerMcpCallLog.d.ts +160 -0
  132. package/dist/runtime/engineBrokerMcpCallLog.d.ts.map +1 -0
  133. package/dist/runtime/engineBrokerMcpCallLog.js +219 -0
  134. package/dist/runtime/engineBrokerMcpFacade.d.ts +56 -0
  135. package/dist/runtime/engineBrokerMcpFacade.d.ts.map +1 -0
  136. package/dist/runtime/engineBrokerMcpFacade.js +343 -0
  137. package/dist/runtime/engineBrokerNativeClient.d.ts +52 -0
  138. package/dist/runtime/engineBrokerNativeClient.d.ts.map +1 -0
  139. package/dist/runtime/engineBrokerNativeClient.js +151 -0
  140. package/dist/runtime/engineBrokerProtocol.d.ts +135 -0
  141. package/dist/runtime/engineBrokerProtocol.d.ts.map +1 -0
  142. package/dist/runtime/engineBrokerProtocol.js +274 -0
  143. package/dist/runtime/engineBrokerSealLedger.d.ts +70 -0
  144. package/dist/runtime/engineBrokerSealLedger.d.ts.map +1 -0
  145. package/dist/runtime/engineBrokerSealLedger.js +123 -0
  146. package/dist/runtime/engineBrokerService.d.ts +37 -0
  147. package/dist/runtime/engineBrokerService.d.ts.map +1 -0
  148. package/dist/runtime/engineBrokerService.js +138 -0
  149. package/dist/runtime/engineBrokerServiceCli.d.ts +5 -0
  150. package/dist/runtime/engineBrokerServiceCli.d.ts.map +1 -0
  151. package/dist/runtime/engineBrokerServiceCli.js +32 -0
  152. package/dist/runtime/engineBrokerServiceConfig.d.ts +50 -0
  153. package/dist/runtime/engineBrokerServiceConfig.d.ts.map +1 -0
  154. package/dist/runtime/engineBrokerServiceConfig.js +92 -0
  155. package/dist/runtime/engineBrokerSingleflight.d.ts +13 -0
  156. package/dist/runtime/engineBrokerSingleflight.d.ts.map +1 -0
  157. package/dist/runtime/engineBrokerSingleflight.js +24 -0
  158. package/dist/runtime/engineBrokerTurnAccounting.d.ts +76 -0
  159. package/dist/runtime/engineBrokerTurnAccounting.d.ts.map +1 -0
  160. package/dist/runtime/engineBrokerTurnAccounting.js +108 -0
  161. package/dist/runtime/engineBrokerTurnRegistry.d.ts +57 -0
  162. package/dist/runtime/engineBrokerTurnRegistry.d.ts.map +1 -0
  163. package/dist/runtime/engineBrokerTurnRegistry.js +158 -0
  164. package/dist/runtime/engineDispatcher.d.ts +36 -0
  165. package/dist/runtime/engineDispatcher.d.ts.map +1 -0
  166. package/dist/runtime/engineDispatcher.js +216 -0
  167. package/dist/runtime/engineReadiness.d.ts +23 -0
  168. package/dist/runtime/engineReadiness.d.ts.map +1 -0
  169. package/dist/runtime/engineReadiness.js +222 -0
  170. package/dist/runtime/grokAuthenticationError.d.ts +8 -0
  171. package/dist/runtime/grokAuthenticationError.d.ts.map +1 -0
  172. package/dist/runtime/grokAuthenticationError.js +20 -0
  173. package/dist/runtime/grokBrokerCredentialAuthority.d.ts +22 -0
  174. package/dist/runtime/grokBrokerCredentialAuthority.d.ts.map +1 -0
  175. package/dist/runtime/grokBrokerCredentialAuthority.js +124 -0
  176. package/dist/runtime/grokBrokerCredentialReader.d.ts +5 -0
  177. package/dist/runtime/grokBrokerCredentialReader.d.ts.map +1 -0
  178. package/dist/runtime/grokBrokerCredentialReader.js +37 -0
  179. package/dist/runtime/grokBrokerModelPolicy.d.ts +23 -0
  180. package/dist/runtime/grokBrokerModelPolicy.d.ts.map +1 -0
  181. package/dist/runtime/grokBrokerModelPolicy.js +28 -0
  182. package/dist/runtime/grokBrokerProjection.d.ts +106 -0
  183. package/dist/runtime/grokBrokerProjection.d.ts.map +1 -0
  184. package/dist/runtime/grokBrokerProjection.js +94 -0
  185. package/dist/runtime/grokBrokerProxy.d.ts +55 -0
  186. package/dist/runtime/grokBrokerProxy.d.ts.map +1 -0
  187. package/dist/runtime/grokBrokerProxy.js +262 -0
  188. package/dist/runtime/grokBrokerProxyRequest.d.ts +30 -0
  189. package/dist/runtime/grokBrokerProxyRequest.d.ts.map +1 -0
  190. package/dist/runtime/grokBrokerProxyRequest.js +74 -0
  191. package/dist/runtime/grokBrokerRealmLease.d.ts +4 -0
  192. package/dist/runtime/grokBrokerRealmLease.d.ts.map +1 -0
  193. package/dist/runtime/grokBrokerRealmLease.js +33 -0
  194. package/dist/runtime/grokBrokerRefresh.d.ts +2 -0
  195. package/dist/runtime/grokBrokerRefresh.d.ts.map +1 -0
  196. package/dist/runtime/grokBrokerRefresh.js +15 -0
  197. package/dist/runtime/grokBrokerTurnMeter.d.ts +128 -0
  198. package/dist/runtime/grokBrokerTurnMeter.d.ts.map +1 -0
  199. package/dist/runtime/grokBrokerTurnMeter.js +251 -0
  200. package/dist/runtime/grokBrokerWorkerConfig.d.ts +86 -0
  201. package/dist/runtime/grokBrokerWorkerConfig.d.ts.map +1 -0
  202. package/dist/runtime/grokBrokerWorkerConfig.js +135 -0
  203. package/dist/runtime/grokEngineBroker.d.ts +48 -0
  204. package/dist/runtime/grokEngineBroker.d.ts.map +1 -0
  205. package/dist/runtime/grokEngineBroker.js +114 -0
  206. package/dist/runtime/grokEngineBrokerLedger.d.ts +52 -0
  207. package/dist/runtime/grokEngineBrokerLedger.d.ts.map +1 -0
  208. package/dist/runtime/grokEngineBrokerLedger.js +114 -0
  209. package/dist/runtime/grokEngineBrokerMetering.d.ts +51 -0
  210. package/dist/runtime/grokEngineBrokerMetering.d.ts.map +1 -0
  211. package/dist/runtime/grokEngineBrokerMetering.js +34 -0
  212. package/dist/runtime/grokEngineBrokerTurn.d.ts +58 -0
  213. package/dist/runtime/grokEngineBrokerTurn.d.ts.map +1 -0
  214. package/dist/runtime/grokEngineBrokerTurn.js +165 -0
  215. package/dist/runtime/grokInferenceClientConfig.d.ts +41 -0
  216. package/dist/runtime/grokInferenceClientConfig.d.ts.map +1 -0
  217. package/dist/runtime/grokInferenceClientConfig.js +62 -0
  218. package/dist/runtime/grokInferenceGrants.d.ts +77 -0
  219. package/dist/runtime/grokInferenceGrants.d.ts.map +1 -0
  220. package/dist/runtime/grokInferenceGrants.js +116 -0
  221. package/dist/runtime/grokInferenceProxy.d.ts +29 -0
  222. package/dist/runtime/grokInferenceProxy.d.ts.map +1 -0
  223. package/dist/runtime/grokInferenceProxy.js +82 -0
  224. package/dist/runtime/grokInferenceProxyRequest.d.ts +23 -0
  225. package/dist/runtime/grokInferenceProxyRequest.d.ts.map +1 -0
  226. package/dist/runtime/grokInferenceProxyRequest.js +63 -0
  227. package/dist/runtime/grokSlotPreflightReceipt.d.ts +70 -0
  228. package/dist/runtime/grokSlotPreflightReceipt.d.ts.map +1 -0
  229. package/dist/runtime/grokSlotPreflightReceipt.js +101 -0
  230. package/dist/runtime/grokSubscriptionRealm.d.ts +4 -0
  231. package/dist/runtime/grokSubscriptionRealm.d.ts.map +1 -0
  232. package/dist/runtime/grokSubscriptionRealm.js +435 -0
  233. package/dist/runtime/grokSubscriptionRealmTypes.d.ts +26 -0
  234. package/dist/runtime/grokSubscriptionRealmTypes.d.ts.map +1 -0
  235. package/dist/runtime/grokSubscriptionRealmTypes.js +1 -0
  236. package/dist/runtime/grokWorkerAttestation.d.ts +170 -0
  237. package/dist/runtime/grokWorkerAttestation.d.ts.map +1 -0
  238. package/dist/runtime/grokWorkerAttestation.js +266 -0
  239. package/dist/runtime/grokWorkerDenyPlacement.d.ts +80 -0
  240. package/dist/runtime/grokWorkerDenyPlacement.d.ts.map +1 -0
  241. package/dist/runtime/grokWorkerDenyPlacement.js +128 -0
  242. package/dist/runtime/grokWorkerHomeAttestation.d.ts +30 -0
  243. package/dist/runtime/grokWorkerHomeAttestation.d.ts.map +1 -0
  244. package/dist/runtime/grokWorkerHomeAttestation.js +69 -0
  245. package/dist/runtime/grokWorkerSandboxProfile.d.ts +27 -0
  246. package/dist/runtime/grokWorkerSandboxProfile.d.ts.map +1 -0
  247. package/dist/runtime/grokWorkerSandboxProfile.js +44 -0
  248. package/dist/runtime/grokWorkerTmpAttestation.d.ts +55 -0
  249. package/dist/runtime/grokWorkerTmpAttestation.d.ts.map +1 -0
  250. package/dist/runtime/grokWorkerTmpAttestation.js +63 -0
  251. package/dist/runtime/index.d.ts +26 -0
  252. package/dist/runtime/index.d.ts.map +1 -0
  253. package/dist/runtime/index.js +23 -0
  254. package/dist/runtime/inferenceUsageLedger.d.ts +38 -0
  255. package/dist/runtime/inferenceUsageLedger.d.ts.map +1 -0
  256. package/dist/runtime/inferenceUsageLedger.js +53 -0
  257. package/dist/runtime/mcpToolResult.d.ts +127 -0
  258. package/dist/runtime/mcpToolResult.d.ts.map +1 -0
  259. package/dist/runtime/mcpToolResult.js +214 -0
  260. package/dist/runtime/moltnetMachineRead.d.ts +97 -0
  261. package/dist/runtime/moltnetMachineRead.d.ts.map +1 -0
  262. package/dist/runtime/moltnetMachineRead.js +183 -0
  263. package/dist/runtime/native/daimon-engine-broker +0 -0
  264. package/dist/runtime/organizationRuntime.d.ts +165 -0
  265. package/dist/runtime/organizationRuntime.d.ts.map +1 -0
  266. package/dist/runtime/organizationRuntime.js +3 -0
  267. package/dist/runtime/organizationRuntimeControl.d.ts +42 -0
  268. package/dist/runtime/organizationRuntimeControl.d.ts.map +1 -0
  269. package/dist/runtime/organizationRuntimeControl.js +235 -0
  270. package/dist/runtime/organizationRuntimeHost.d.ts +19 -0
  271. package/dist/runtime/organizationRuntimeHost.d.ts.map +1 -0
  272. package/dist/runtime/organizationRuntimeHost.js +359 -0
  273. package/dist/runtime/organizationRuntimeParsing.d.ts +6 -0
  274. package/dist/runtime/organizationRuntimeParsing.d.ts.map +1 -0
  275. package/dist/runtime/organizationRuntimeParsing.js +370 -0
  276. package/dist/runtime/organizationRuntimeReadiness.d.ts +12 -0
  277. package/dist/runtime/organizationRuntimeReadiness.d.ts.map +1 -0
  278. package/dist/runtime/organizationRuntimeReadiness.js +59 -0
  279. package/dist/runtime/physicalReadiness.d.ts +47 -0
  280. package/dist/runtime/physicalReadiness.d.ts.map +1 -0
  281. package/dist/runtime/physicalReadiness.js +142 -0
  282. package/dist/runtime/portableCredentialAuth.d.ts +6 -0
  283. package/dist/runtime/portableCredentialAuth.d.ts.map +1 -0
  284. package/dist/runtime/portableCredentialAuth.js +70 -0
  285. package/dist/runtime/portableCredentialMaterial.d.ts +8 -0
  286. package/dist/runtime/portableCredentialMaterial.d.ts.map +1 -0
  287. package/dist/runtime/portableCredentialMaterial.js +169 -0
  288. package/dist/runtime/productionAgentTools.d.ts +5 -0
  289. package/dist/runtime/productionAgentTools.d.ts.map +1 -0
  290. package/dist/runtime/productionAgentTools.js +328 -0
  291. package/dist/runtime/runtimeHomeLayout.d.ts +48 -0
  292. package/dist/runtime/runtimeHomeLayout.d.ts.map +1 -0
  293. package/dist/runtime/runtimeHomeLayout.js +84 -0
  294. package/dist/runtime/schedule.d.ts +40 -0
  295. package/dist/runtime/schedule.d.ts.map +1 -0
  296. package/dist/runtime/schedule.js +371 -0
  297. package/dist/runtime/storeCoordination.d.ts +23 -0
  298. package/dist/runtime/storeCoordination.d.ts.map +1 -0
  299. package/dist/runtime/storeCoordination.js +94 -0
  300. package/dist/runtime/toolResultSpill.d.ts +152 -0
  301. package/dist/runtime/toolResultSpill.d.ts.map +1 -0
  302. package/dist/runtime/toolResultSpill.js +351 -0
  303. package/dist/runtime/turnRequestLedger.d.ts +160 -0
  304. package/dist/runtime/turnRequestLedger.d.ts.map +1 -0
  305. package/dist/runtime/turnRequestLedger.js +249 -0
  306. package/dist/runtime/turnUsageLedger.d.ts +143 -0
  307. package/dist/runtime/turnUsageLedger.d.ts.map +1 -0
  308. package/dist/runtime/turnUsageLedger.js +203 -0
  309. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts +17 -0
  310. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts.map +1 -0
  311. package/dist/runtime/wakeAcceptanceProcessIdentity.js +50 -0
  312. package/dist/runtime/wakeAcceptanceReconciliation.d.ts +211 -0
  313. package/dist/runtime/wakeAcceptanceReconciliation.d.ts.map +1 -0
  314. package/dist/runtime/wakeAcceptanceReconciliation.js +289 -0
  315. package/dist/runtime/wakeAcceptanceRecord.d.ts +23 -0
  316. package/dist/runtime/wakeAcceptanceRecord.d.ts.map +1 -0
  317. package/dist/runtime/wakeAcceptanceRecord.js +56 -0
  318. package/dist/runtime/wakeAcceptanceRetention.d.ts +12 -0
  319. package/dist/runtime/wakeAcceptanceRetention.d.ts.map +1 -0
  320. package/dist/runtime/wakeAcceptanceRetention.js +12 -0
  321. package/dist/runtime/wakeAcceptanceStore.d.ts +113 -0
  322. package/dist/runtime/wakeAcceptanceStore.d.ts.map +1 -0
  323. package/dist/runtime/wakeAcceptanceStore.js +558 -0
  324. package/dist/runtime/wakeAcceptanceTypes.d.ts +179 -0
  325. package/dist/runtime/wakeAcceptanceTypes.d.ts.map +1 -0
  326. package/dist/runtime/wakeAcceptanceTypes.js +95 -0
  327. package/dist/runtime/wakeFuse.d.ts +69 -0
  328. package/dist/runtime/wakeFuse.d.ts.map +1 -0
  329. package/dist/runtime/wakeFuse.js +367 -0
  330. package/package.json +20 -9
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Per-wake engine bounds, and the one place they are decided.
3
+ *
4
+ * `maxToolTurns` mediates only daimon-MCP tool calls; Codex's own shell
5
+ * (`exec_command`) is never routed through that gate, so a single Codex turn
6
+ * previously had no ceiling at all — one production wake ran 23:32→23:42
7
+ * (unbounded wall clock) making 51 shell calls. Codex's `--json` stream
8
+ * reports token usage exactly once, on `turn.completed` — there is no
9
+ * incremental total to watch mid-turn (verified against a live multi-tool-call
10
+ * turn: `item.completed` fires once per tool call, but usage is reported only
11
+ * on the single terminal `turn.completed`) — so the token ceiling is the best
12
+ * bound obtainable from that wire shape: it converts an over-budget turn into
13
+ * an explicit, killed, named failure instead of a silent success, and the
14
+ * wall-clock timeout is what actually interrupts a runaway turn in progress.
15
+ *
16
+ * The names are engine-neutral: `DAIMON_ENGINE_WAKE_TIMEOUT_MS` and
17
+ * `DAIMON_ENGINE_WAKE_TOKEN_CEILING` bound Codex locally and are passed to the
18
+ * Grok broker as the wake's *lowering* limits (the broker refuses a value above
19
+ * its registration). The `DAIMON_CODEX_*` names remain aliases; setting both
20
+ * names of one bound to different values is refused rather than guessed.
21
+ */
22
+ export const DEFAULT_CODEX_WAKE_TIMEOUT_MS = 240_000;
23
+ export const DEFAULT_CODEX_WAKE_TOKEN_CEILING = 300_000;
24
+ export const DAIMON_ENGINE_WAKE_TIMEOUT_MS_ENV = "DAIMON_ENGINE_WAKE_TIMEOUT_MS";
25
+ export const DAIMON_ENGINE_WAKE_TOKEN_CEILING_ENV = "DAIMON_ENGINE_WAKE_TOKEN_CEILING";
26
+ export const DAIMON_CODEX_WAKE_TIMEOUT_MS_ENV = "DAIMON_CODEX_WAKE_TIMEOUT_MS";
27
+ export const DAIMON_CODEX_WAKE_TOKEN_CEILING_ENV = "DAIMON_CODEX_WAKE_TOKEN_CEILING";
28
+ const positiveInteger = (value, name) => {
29
+ const parsed = Number(value);
30
+ if (!Number.isSafeInteger(parsed) || parsed <= 0)
31
+ throw new Error(`${name} must be a positive integer`);
32
+ return parsed;
33
+ };
34
+ const declared = (environment, neutral, alias) => {
35
+ const primary = environment[neutral], legacy = environment[alias];
36
+ const value = primary === undefined ? undefined : positiveInteger(primary, neutral);
37
+ const aliased = legacy === undefined ? undefined : positiveInteger(legacy, alias);
38
+ if (value !== undefined && aliased !== undefined && value !== aliased)
39
+ throw new Error(`${neutral} and ${alias} disagree; set one`);
40
+ return value ?? aliased;
41
+ };
42
+ export const resolveCodexWakeTimeoutMs = (environment = process.env) => declared(environment, DAIMON_ENGINE_WAKE_TIMEOUT_MS_ENV, DAIMON_CODEX_WAKE_TIMEOUT_MS_ENV) ?? DEFAULT_CODEX_WAKE_TIMEOUT_MS;
43
+ export const resolveCodexWakeTokenCeiling = (environment = process.env) => declared(environment, DAIMON_ENGINE_WAKE_TOKEN_CEILING_ENV, DAIMON_CODEX_WAKE_TOKEN_CEILING_ENV) ?? DEFAULT_CODEX_WAKE_TOKEN_CEILING;
44
+ /**
45
+ * The limits a wake asks a broker to lower to: only the bounds the operator
46
+ * actually set, never the Codex defaults (a broker registration's declared
47
+ * limits already are the defaults there).
48
+ */
49
+ export const resolveEngineWakeLimitOverrides = (environment = process.env) => {
50
+ const timeoutMs = declared(environment, DAIMON_ENGINE_WAKE_TIMEOUT_MS_ENV, DAIMON_CODEX_WAKE_TIMEOUT_MS_ENV);
51
+ const maxTokens = declared(environment, DAIMON_ENGINE_WAKE_TOKEN_CEILING_ENV, DAIMON_CODEX_WAKE_TOKEN_CEILING_ENV);
52
+ if (timeoutMs === undefined && maxTokens === undefined)
53
+ return undefined;
54
+ return { ...(timeoutMs === undefined ? {} : { timeoutMs }), ...(maxTokens === undefined ? {} : { maxTokens }) };
55
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Token accounting for one turn, as the engine itself reported it.
3
+ *
4
+ * These are subscription-backed CLIs, so nothing here is billed: the counts are
5
+ * real quota consumption and `notionalUsd` is what the same turn would have cost
6
+ * at metered API rates. Kept away from anything named `cost` so a later reader
7
+ * cannot mistake it for a charge.
8
+ *
9
+ * Field provenance is the `streaming-messages-json` terminal `result` frame,
10
+ * which production hardcodes (`grokBrokerWorkerConfig.ts`). Its `result.usage`
11
+ * is the Messages API `message.usage` shape with three *disjoint* prompt-side
12
+ * buckets, so the full turn cost is
13
+ * `input_tokens + cache_read_input_tokens + cache_creation_input_tokens + output_tokens`.
14
+ */
15
+ export type GrokTurnUsage = Readonly<{
16
+ input: number;
17
+ output: number;
18
+ cacheRead: number;
19
+ cacheWrite: number;
20
+ total: number;
21
+ calls: number;
22
+ notionalUsd: number;
23
+ complete: boolean;
24
+ }>;
25
+ export type GrokHeadlessTurn = Readonly<{
26
+ text: string;
27
+ usage?: GrokTurnUsage;
28
+ }>;
29
+ /**
30
+ * Decode Grok's terminal message stream without treating progress messages as a
31
+ * reply, and extract the turn's own token accounting from the same frame.
32
+ */
33
+ export declare const decodeGrokHeadlessTurn: (output: string) => GrokHeadlessTurn;
34
+ /** Text-only view of {@link decodeGrokHeadlessTurn}, for callers that do not meter. */
35
+ export declare const decodeGrokHeadlessResult: (output: string) => string;
36
+ //# sourceMappingURL=grokHeadlessResult.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokHeadlessResult.d.ts","sourceRoot":"","sources":["../../src/pi/grokHeadlessResult.ts"],"names":[],"mappings":"AAYA;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,aAAa,GAAG,QAAQ,CAAC;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,OAAO,CAAC;CACnB,CAAC,CAAC;AAEH,MAAM,MAAM,gBAAgB,GAAG,QAAQ,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,aAAa,CAAA;CAAE,CAAC,CAAC;AA8DjF;;;GAGG;AACH,eAAO,MAAM,sBAAsB,GAAI,QAAQ,MAAM,KAAG,gBA+BvD,CAAC;AAEF,uFAAuF;AACvF,eAAO,MAAM,wBAAwB,GAAI,QAAQ,MAAM,KAAG,MAA6C,CAAC"}
@@ -0,0 +1,118 @@
1
+ const PUBLISHABLE_STOP_REASONS = new Set(["end_turn", "stop_sequence"]);
2
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ const invalidResult = (detail) => new Error(`Grok CLI returned no publishable terminal response: ${detail}`);
4
+ /**
5
+ * The four disjoint token buckets grok emits on `result.usage`. All four must be
6
+ * present and be non-negative safe integers; a renamed, stringified, negative,
7
+ * or fractional field rejects the whole block rather than silently contributing
8
+ * a zero, because a zero bucket is byte-indistinguishable from a real one.
9
+ */
10
+ const USAGE_TOKEN_FIELDS = ["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"];
11
+ const tokenCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
12
+ const nonNegativeAmount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
13
+ /**
14
+ * Extract per-turn usage from the terminal `result` frame.
15
+ *
16
+ * Advisory: a malformed or absent usage block yields `undefined` rather than
17
+ * failing a turn that published correctly, and never throws.
18
+ *
19
+ * `complete` is a stated heuristic, not a wire-observable signal. grok's own
20
+ * embedded documentation for this stream says any bucket it cannot account for
21
+ * "falls back to `0`, because the Messages API schema has no marker for
22
+ * incomplete or absent usage", and instructs consumers to "read an all-zero
23
+ * `usage` here as 'unknown', not 'free'". That is exactly the rule below. It
24
+ * cannot catch a *partially* zero-filled turn, which sums to a plausible total
25
+ * and is stamped `complete: true` while under-counting — so every count this
26
+ * decoder produces is a lower bound.
27
+ */
28
+ const decodeTurnUsage = (result) => {
29
+ if (!isRecord(result.usage))
30
+ return undefined;
31
+ const usage = result.usage;
32
+ const counts = USAGE_TOKEN_FIELDS.map((field) => tokenCount(usage[field]));
33
+ if (counts.some((count) => count === undefined))
34
+ return undefined;
35
+ const [input, output, cacheRead, cacheWrite] = counts;
36
+ const total = input + cacheRead + cacheWrite + output;
37
+ return { input, output, cacheRead, cacheWrite, total, calls: tokenCount(result.num_turns) ?? 0, notionalUsd: nonNegativeAmount(result.total_cost_usd), complete: total > 0 };
38
+ };
39
+ const decodeTerminalAssistant = (event) => {
40
+ if (event.type !== "assistant" || event.parent_tool_use_id !== null)
41
+ return undefined;
42
+ if (typeof event.session_id !== "string" || !isRecord(event.message))
43
+ throw invalidResult("invalid assistant event");
44
+ const message = event.message;
45
+ if (message.role !== "assistant" || typeof message.stop_reason !== "string" || !Array.isArray(message.content)) {
46
+ throw invalidResult("invalid assistant event");
47
+ }
48
+ if (!PUBLISHABLE_STOP_REASONS.has(message.stop_reason))
49
+ return { sessionId: event.session_id, stopReason: message.stop_reason, text: "" };
50
+ let text = "";
51
+ let textBlocks = 0;
52
+ for (const block of message.content) {
53
+ if (!isRecord(block) || typeof block.type !== "string")
54
+ throw invalidResult("invalid assistant content");
55
+ if (block.type === "thinking")
56
+ continue;
57
+ if (block.type !== "text" || typeof block.text !== "string")
58
+ throw invalidResult("invalid terminal content");
59
+ text += block.text;
60
+ textBlocks += 1;
61
+ }
62
+ if (textBlocks === 0 || text.trim().length === 0)
63
+ throw invalidResult("empty response");
64
+ return { sessionId: event.session_id, stopReason: message.stop_reason, text };
65
+ };
66
+ /**
67
+ * Decode Grok's terminal message stream without treating progress messages as a
68
+ * reply, and extract the turn's own token accounting from the same frame.
69
+ */
70
+ export const decodeGrokHeadlessTurn = (output) => {
71
+ const lines = output.split(/\r?\n/).filter((line) => line.length > 0);
72
+ if (lines.length === 0)
73
+ throw invalidResult("empty stream");
74
+ let finalAssistant;
75
+ let result;
76
+ for (const [index, line] of lines.entries()) {
77
+ let event;
78
+ try {
79
+ event = JSON.parse(line);
80
+ }
81
+ catch {
82
+ throw invalidResult("invalid JSON");
83
+ }
84
+ if (!isRecord(event) || typeof event.type !== "string")
85
+ throw invalidResult("invalid event");
86
+ if (event.type === "error") {
87
+ const rejection = asGrokAuthenticationRejected(JSON.stringify(event));
88
+ if (rejection !== undefined)
89
+ throw rejection;
90
+ throw invalidResult("engine error");
91
+ }
92
+ const assistant = decodeTerminalAssistant(event);
93
+ if (assistant !== undefined)
94
+ finalAssistant = assistant;
95
+ if (event.type === "result") {
96
+ if (index !== lines.length - 1)
97
+ throw invalidResult("non-terminal result");
98
+ result = event;
99
+ }
100
+ }
101
+ if (result === undefined || result.subtype !== "success" || result.is_error !== false)
102
+ throw invalidResult("unsuccessful result");
103
+ if (typeof result.stop_reason !== "string" || !PUBLISHABLE_STOP_REASONS.has(result.stop_reason))
104
+ throw invalidResult("non-terminal stop");
105
+ if ("errors" in result && (!Array.isArray(result.errors) || result.errors.length > 0))
106
+ throw invalidResult("engine error");
107
+ if (typeof result.result !== "string" || result.result.trim().length === 0)
108
+ throw invalidResult("empty response");
109
+ if (finalAssistant === undefined || finalAssistant.stopReason !== result.stop_reason ||
110
+ finalAssistant.sessionId !== result.session_id || finalAssistant.text !== result.result) {
111
+ throw invalidResult("terminal result mismatch");
112
+ }
113
+ const usage = decodeTurnUsage(result);
114
+ return usage === undefined ? { text: result.result.trim() } : { text: result.result.trim(), usage };
115
+ };
116
+ /** Text-only view of {@link decodeGrokHeadlessTurn}, for callers that do not meter. */
117
+ export const decodeGrokHeadlessResult = (output) => decodeGrokHeadlessTurn(output).text;
118
+ import { asGrokAuthenticationRejected } from "../runtime/grokAuthenticationError.js";
@@ -0,0 +1,21 @@
1
+ import type { CliMcpRegistration } from "./cliMcpRegistration.js";
2
+ /**
3
+ * Per-wake MCP registration for the direct (non-broker) Grok CLI path.
4
+ *
5
+ * `grok mcp add --scope project` writes `<cwd>/.grok/config.toml`, which Grok
6
+ * 1.0.34 skips entirely in an untrusted workspace — and Daimon keeps every
7
+ * workspace untrusted so cwd `AGENTS.md` and project skills never load. The
8
+ * endpoint therefore goes into the agent's own Daimon-owned `GROK_HOME`
9
+ * config, rendered from the same lean base the broker worker uses
10
+ * (`renderGrokLeanBaseConfig`), and is removed again after the turn by
11
+ * rewriting the base alone.
12
+ *
13
+ * There is no fallback to the operator's `~/.grok`: without an explicit
14
+ * `engineHomePath` the session refuses, rather than editing a human's config.
15
+ */
16
+ export declare function registerGrokHomeMcpServer(input: Readonly<{
17
+ engineHomePath: string | undefined;
18
+ endpoint: string;
19
+ verify?: () => Promise<void>;
20
+ }>): Promise<CliMcpRegistration>;
21
+ //# sourceMappingURL=grokHomeMcpRegistration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokHomeMcpRegistration.d.ts","sourceRoot":"","sources":["../../src/pi/grokHomeMcpRegistration.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAElE;;;;;;;;;;;;;GAaG;AACH,wBAAsB,yBAAyB,CAAC,KAAK,EAAE,QAAQ,CAAC;IAAE,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAepL"}
@@ -0,0 +1,57 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, rename, unlink } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { renderGrokLeanBaseConfig } from "../runtime/grokBrokerWorkerConfig.js";
6
+ /**
7
+ * Per-wake MCP registration for the direct (non-broker) Grok CLI path.
8
+ *
9
+ * `grok mcp add --scope project` writes `<cwd>/.grok/config.toml`, which Grok
10
+ * 1.0.34 skips entirely in an untrusted workspace — and Daimon keeps every
11
+ * workspace untrusted so cwd `AGENTS.md` and project skills never load. The
12
+ * endpoint therefore goes into the agent's own Daimon-owned `GROK_HOME`
13
+ * config, rendered from the same lean base the broker worker uses
14
+ * (`renderGrokLeanBaseConfig`), and is removed again after the turn by
15
+ * rewriting the base alone.
16
+ *
17
+ * There is no fallback to the operator's `~/.grok`: without an explicit
18
+ * `engineHomePath` the session refuses, rather than editing a human's config.
19
+ */
20
+ export async function registerGrokHomeMcpServer(input) {
21
+ const home = input.engineHomePath;
22
+ if (home === undefined || !path.isAbsolute(home)) {
23
+ throw new Error("Grok direct CLI sessions require a Daimon-owned GROK_HOME (engineHomePath): Grok 1.0.34 ignores project-scoped MCP servers in untrusted workspaces");
24
+ }
25
+ if (!/^http:\/\/127\.0\.0\.1:\d{1,5}\/[A-Za-z0-9/_-]*$/u.test(input.endpoint))
26
+ throw new Error("Grok MCP endpoint must be a loopback http URL");
27
+ await input.verify?.();
28
+ await writeConfig(home, `${renderGrokLeanBaseConfig()}[mcp_servers.daimon]\nurl = ${JSON.stringify(input.endpoint)}\n`);
29
+ let closePromise;
30
+ return {
31
+ close: () => closePromise ??= (async () => {
32
+ await input.verify?.();
33
+ await writeConfig(home, renderGrokLeanBaseConfig());
34
+ })()
35
+ };
36
+ }
37
+ async function writeConfig(home, text) {
38
+ await mkdir(home, { recursive: true, mode: 0o700 });
39
+ const directory = await lstat(home);
40
+ if (!directory.isDirectory() || directory.isSymbolicLink())
41
+ throw new Error("Grok engine home is not a private directory");
42
+ const target = path.join(home, "config.toml");
43
+ const temporary = path.join(home, `.config.toml.${randomUUID()}.tmp`);
44
+ let handle;
45
+ try {
46
+ handle = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
47
+ await handle.writeFile(text);
48
+ await handle.sync();
49
+ await handle.close();
50
+ handle = undefined;
51
+ await rename(temporary, target);
52
+ }
53
+ finally {
54
+ await handle?.close().catch(() => undefined);
55
+ await unlink(temporary).catch(() => undefined);
56
+ }
57
+ }
@@ -0,0 +1,11 @@
1
+ export declare const GROK_DAIMON_SANDBOX_PROFILE: "daimon-strict";
2
+ export interface GrokSandboxAuthority {
3
+ readonly command: string;
4
+ readonly commandArgs?: readonly string[];
5
+ readonly cwd: string;
6
+ readonly engineHomePath: string;
7
+ readonly protectedPaths: readonly string[];
8
+ readonly runtimeHomePath: string;
9
+ }
10
+ export declare function prepareAndVerifyGrokSandbox(authority: GrokSandboxAuthority): Promise<void>;
11
+ //# sourceMappingURL=grokSandbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokSandbox.d.ts","sourceRoot":"","sources":["../../src/pi/grokSandbox.ts"],"names":[],"mappings":"AAaA,eAAO,MAAM,2BAA2B,iBAA8B,CAAC;AAOvE,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;CAClC;AAED,wBAAsB,2BAA2B,CAC/C,SAAS,EAAE,oBAAoB,GAC9B,OAAO,CAAC,IAAI,CAAC,CAsCf"}
@@ -0,0 +1,216 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { constants } from "node:fs";
4
+ import { lstat, mkdir, open, realpath, rename, unlink } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { readChild } from "./cliChildOutput.js";
7
+ import { cliChildEnvironment } from "./cliEnvironment.js";
8
+ import { terminateChild, trackCliChild } from "./cliProcess.js";
9
+ import { renderGrokSandboxArgs } from "./cliEngineSpawn.js";
10
+ import { assertGrokWorkerDenyPathsPlaceable } from "../runtime/grokWorkerDenyPlacement.js";
11
+ import { GROK_WORKER_SANDBOX_EVENTS_RELATIVE_PATH, GROK_WORKER_SANDBOX_PROFILE, renderGrokWorkerSandboxProfile } from "../runtime/grokWorkerSandboxProfile.js";
12
+ export const GROK_DAIMON_SANDBOX_PROFILE = GROK_WORKER_SANDBOX_PROFILE;
13
+ const SANDBOX_CONFIG = "sandbox.toml";
14
+ /** Grok 1.0.34 logs sandbox events under `sessions/`; the root file stays empty. */
15
+ const SANDBOX_EVENTS = GROK_WORKER_SANDBOX_EVENTS_RELATIVE_PATH;
16
+ const MAX_EVENTS_BYTES = 16 * 1024 * 1024;
17
+ const ROTATE_EVENTS_BYTES = 8 * 1024 * 1024;
18
+ export async function prepareAndVerifyGrokSandbox(authority) {
19
+ const engineHome = await realpath(authority.engineHomePath);
20
+ const cwd = await realpath(authority.cwd);
21
+ await assertPrivateDirectory(engineHome);
22
+ const denied = [...new Set(await Promise.all(authority.protectedPaths.map((entry) => realpath(entry))))].sort();
23
+ if (denied.some((entry) => overlaps(entry, cwd) || overlaps(entry, engineHome))) {
24
+ throw unavailable();
25
+ }
26
+ // Grok 1.0.34 materializes every deny target inside bubblewrap as the uid it
27
+ // runs Grok under — here, this process's own — and refuses the whole profile
28
+ // if one cannot be resolved. Refusing now names the path; letting it through
29
+ // would kill every turn with a bare `bwrap: Can't create file at …`.
30
+ await assertGrokWorkerDenyPathsPlaceable(denied, { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 });
31
+ await writeProfile(engineHome, denied);
32
+ const beforeBytes = await eventFileSize(path.join(engineHome, SANDBOX_EVENTS));
33
+ const child = trackCliChild(spawn(authority.command, [
34
+ ...renderGrokSandboxArgs(authority.commandArgs, GROK_DAIMON_SANDBOX_PROFILE),
35
+ "--cwd", cwd,
36
+ "inspect"
37
+ ], {
38
+ cwd,
39
+ detached: process.platform !== "win32",
40
+ env: cliChildEnvironment([], authority.runtimeHomePath, {
41
+ engine: "grok",
42
+ engineHomePath: engineHome,
43
+ executablePath: authority.command
44
+ }),
45
+ stdio: ["ignore", "pipe", "pipe"]
46
+ }));
47
+ try {
48
+ await readChild(child, 10_000, []);
49
+ }
50
+ catch {
51
+ throw unavailable();
52
+ }
53
+ finally {
54
+ await terminateChild(child).catch(() => undefined);
55
+ }
56
+ await verifyEnforcementEvent(path.join(engineHome, SANDBOX_EVENTS), beforeBytes, cwd, denied);
57
+ await verifyProfile(engineHome, denied);
58
+ }
59
+ const profileText = (denied) => renderGrokWorkerSandboxProfile(denied);
60
+ async function writeProfile(engineHome, denied) {
61
+ const target = path.join(engineHome, SANDBOX_CONFIG);
62
+ const temporary = path.join(engineHome, `.${SANDBOX_CONFIG}.${randomUUID()}.tmp`);
63
+ let handle;
64
+ try {
65
+ handle = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow(), 0o600);
66
+ await handle.writeFile(profileText(denied));
67
+ await handle.chmod(0o600);
68
+ await handle.sync();
69
+ await handle.close();
70
+ handle = undefined;
71
+ await rename(temporary, target);
72
+ await syncDirectory(engineHome);
73
+ await verifyProfile(engineHome, denied);
74
+ }
75
+ catch {
76
+ throw unavailable();
77
+ }
78
+ finally {
79
+ await handle?.close().catch(() => undefined);
80
+ await unlink(temporary).catch(() => undefined);
81
+ }
82
+ }
83
+ async function verifyProfile(engineHome, denied) {
84
+ const file = path.join(engineHome, SANDBOX_CONFIG);
85
+ let handle;
86
+ try {
87
+ const before = await lstat(file);
88
+ assertPrivateFile(before, 64 * 1024);
89
+ handle = await open(file, constants.O_RDONLY | noFollow());
90
+ const opened = await handle.stat();
91
+ assertPrivateFile(opened, 64 * 1024);
92
+ if (!sameIdentity(before, opened) || await handle.readFile("utf8") !== profileText(denied))
93
+ throw new Error("changed");
94
+ const after = await handle.stat();
95
+ if (!sameIdentity(opened, after))
96
+ throw new Error("changed");
97
+ }
98
+ catch {
99
+ throw unavailable();
100
+ }
101
+ finally {
102
+ await handle?.close().catch(() => undefined);
103
+ }
104
+ }
105
+ async function verifyEnforcementEvent(file, beforeBytes, cwd, denied) {
106
+ let handle;
107
+ try {
108
+ const before = await lstat(file);
109
+ assertPrivateFile(before, MAX_EVENTS_BYTES);
110
+ if (before.size <= beforeBytes)
111
+ throw new Error("missing event");
112
+ handle = await open(file, constants.O_RDONLY | noFollow());
113
+ const opened = await handle.stat();
114
+ if (!sameIdentity(before, opened))
115
+ throw new Error("changed");
116
+ const bytes = await handle.readFile();
117
+ const after = await handle.stat();
118
+ if (!sameIdentity(opened, after))
119
+ throw new Error("changed");
120
+ const appended = bytes.subarray(beforeBytes).toString("utf8").trim().split("\n").filter(Boolean);
121
+ const event = JSON.parse(appended.at(-1) ?? "null");
122
+ const observedDenied = Array.isArray(event?.deny_paths)
123
+ ? event.deny_paths.filter((entry) => typeof entry === "string").sort()
124
+ : [];
125
+ if (event?.event_type !== "ProfileApplied" || event.profile !== GROK_DAIMON_SANDBOX_PROFILE
126
+ || event.enforced !== true || event.restrict_network !== true || event.workspace !== cwd
127
+ || !/^(?:linux\/landlock|macos\/seatbelt)$/u.test(String(event.platform ?? ""))
128
+ || JSON.stringify(observedDenied) !== JSON.stringify(denied))
129
+ throw new Error("not enforced");
130
+ bytes.fill(0);
131
+ }
132
+ catch {
133
+ throw unavailable();
134
+ }
135
+ finally {
136
+ await handle?.close().catch(() => undefined);
137
+ }
138
+ }
139
+ async function eventFileSize(file) {
140
+ try {
141
+ const entry = await lstat(file);
142
+ assertPrivateFile(entry, MAX_EVENTS_BYTES, true);
143
+ if (entry.size >= ROTATE_EVENTS_BYTES) {
144
+ await replaceWithEmptyPrivateFile(file);
145
+ return 0;
146
+ }
147
+ return Number(entry.size);
148
+ }
149
+ catch (error) {
150
+ if (error.code === "ENOENT") {
151
+ await mkdir(path.dirname(file), { mode: 0o700, recursive: true });
152
+ const handle = await open(file, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow(), 0o600);
153
+ try {
154
+ await handle.sync();
155
+ }
156
+ finally {
157
+ await handle.close();
158
+ }
159
+ await syncDirectory(path.dirname(file));
160
+ return 0;
161
+ }
162
+ throw unavailable();
163
+ }
164
+ }
165
+ async function replaceWithEmptyPrivateFile(file) {
166
+ const temporary = `${file}.${randomUUID()}.tmp`;
167
+ let handle;
168
+ try {
169
+ handle = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow(), 0o600);
170
+ await handle.sync();
171
+ await handle.close();
172
+ handle = undefined;
173
+ await rename(temporary, file);
174
+ await syncDirectory(path.dirname(file));
175
+ const entry = await lstat(file);
176
+ assertPrivateFile(entry, 0, true);
177
+ }
178
+ catch {
179
+ throw unavailable();
180
+ }
181
+ finally {
182
+ await handle?.close().catch(() => undefined);
183
+ await unlink(temporary).catch(() => undefined);
184
+ }
185
+ }
186
+ async function assertPrivateDirectory(directory) {
187
+ try {
188
+ const entry = await lstat(directory);
189
+ if (!entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.()
190
+ || (Number(entry.mode) & 0o777) !== 0o700)
191
+ throw new Error("unsafe");
192
+ }
193
+ catch {
194
+ throw unavailable();
195
+ }
196
+ }
197
+ async function syncDirectory(directory) {
198
+ const handle = await open(directory, constants.O_RDONLY);
199
+ try {
200
+ await handle.sync();
201
+ }
202
+ finally {
203
+ await handle.close();
204
+ }
205
+ }
206
+ const overlaps = (left, right) => left === right || left.startsWith(`${right}${path.sep}`) || right.startsWith(`${left}${path.sep}`);
207
+ const sameIdentity = (left, right) => left.dev === right.dev && left.ino === right.ino && left.mode === right.mode
208
+ && left.nlink === right.nlink && left.size === right.size && left.uid === right.uid && left.mtimeMs === right.mtimeMs;
209
+ const assertPrivateFile = (entry, maxBytes, allowEmpty = false) => {
210
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.()
211
+ || entry.nlink !== 1 || (Number(entry.mode) & 0o777) !== 0o600
212
+ || (!allowEmpty && entry.size < 1) || entry.size > maxBytes)
213
+ throw new Error("unsafe");
214
+ };
215
+ const noFollow = () => constants.O_NOFOLLOW ?? 0;
216
+ const unavailable = () => new Error("Grok kernel sandbox enforcement is unavailable");
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Per-request token accounting read off a Grok `streaming-messages-json`
3
+ * stream.
4
+ *
5
+ * Grok 1.0.34 puts the usage of each model request on that request's
6
+ * top-level `assistant` frame (`message.usage`, the same four disjoint
7
+ * Messages API buckets as the terminal `result.usage`), before any tool result
8
+ * of that request, and the per-request frames sum exactly to the terminal
9
+ * result (P0 host matrix). That makes the stream usable in two places the
10
+ * terminal frame is not: a turn that failed before its `result` frame, and a
11
+ * per-request ledger row.
12
+ *
13
+ * Never throws, and never invents a number: a usage block that is present but
14
+ * does not decode discards *all* requests, because one fabricated zero is
15
+ * byte-identical to a measured one.
16
+ */
17
+ export type GrokRequestUsage = Readonly<{
18
+ index: number;
19
+ input: number;
20
+ cacheRead: number;
21
+ cacheWrite: number;
22
+ output: number;
23
+ total: number;
24
+ }>;
25
+ export type GrokStreamUsage = Readonly<{
26
+ requests: readonly GrokRequestUsage[];
27
+ sessionId?: string;
28
+ reportedModels: readonly string[];
29
+ }>;
30
+ export declare const decodeGrokStreamUsage: (output: string) => GrokStreamUsage;
31
+ //# sourceMappingURL=grokStreamUsage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grokStreamUsage.d.ts","sourceRoot":"","sources":["../../src/pi/grokStreamUsage.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,gBAAgB,GAAG,QAAQ,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAChJ,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC;IAAE,QAAQ,EAAE,SAAS,gBAAgB,EAAE,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC,CAAC;AAkBzI,eAAO,MAAM,qBAAqB,GAAI,QAAQ,MAAM,KAAG,eAmBtD,CAAC"}
@@ -0,0 +1,51 @@
1
+ import { GROK_ENGINE_BROKER } from "../contracts/runtimeContractManifest.js";
2
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ const tokenCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
4
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9-]{0,63}$/u;
5
+ const MODEL_KEY = /^[a-z0-9][a-z0-9.-]{0,63}$/u;
6
+ const decodeUsage = (usage) => {
7
+ if (!isRecord(usage))
8
+ return undefined;
9
+ const input = tokenCount(usage.input_tokens), output = tokenCount(usage.output_tokens), cacheRead = tokenCount(usage.cache_read_input_tokens), cacheWrite = tokenCount(usage.cache_creation_input_tokens);
10
+ if (input === undefined || output === undefined || cacheRead === undefined || cacheWrite === undefined)
11
+ return undefined;
12
+ const total = input + cacheRead + cacheWrite + output;
13
+ // Beyond the model context window one request cannot have spent it: invalid, like a malformed block.
14
+ if (total > GROK_ENGINE_BROKER.turnLimits.requestUsageMaxTokens)
15
+ return undefined;
16
+ return { input, cacheRead, cacheWrite, output, total };
17
+ };
18
+ export const decodeGrokStreamUsage = (output) => {
19
+ const byMessage = new Map();
20
+ const reportedModels = new Set();
21
+ let sessionId, corrupt = false;
22
+ for (const line of output.split(/\r?\n/u)) {
23
+ if (line.trim().length === 0)
24
+ continue;
25
+ let event;
26
+ try {
27
+ event = JSON.parse(line);
28
+ }
29
+ catch {
30
+ continue;
31
+ }
32
+ if (!isRecord(event))
33
+ continue;
34
+ if (typeof event.session_id === "string" && SESSION_ID.test(event.session_id))
35
+ sessionId ??= event.session_id;
36
+ if (event.type === "result" && isRecord(event.modelUsage))
37
+ for (const key of Object.keys(event.modelUsage))
38
+ reportedModels.add(MODEL_KEY.test(key) ? key : "invalid");
39
+ if (event.type !== "assistant" || event.parent_tool_use_id !== null || !isRecord(event.message) || event.message.usage === undefined)
40
+ continue;
41
+ const decoded = decodeUsage(event.message.usage);
42
+ if (decoded === undefined || typeof event.message.id !== "string") {
43
+ corrupt = true;
44
+ continue;
45
+ }
46
+ // One request can surface as more than one frame of the same message; it is one request.
47
+ byMessage.set(event.message.id, decoded);
48
+ }
49
+ const requests = corrupt ? [] : [...byMessage.values()].map((usage, index) => Object.freeze({ index, ...usage }));
50
+ return { requests, ...(sessionId === undefined ? {} : { sessionId }), reportedModels: [...reportedModels].sort() };
51
+ };
@@ -6,7 +6,7 @@ import { persistPiTurnTrace, type PiTurnTraceModel } from "./turnTrace.js";
6
6
  import { type PiRawTrainingCaptureOptions, type PiRawTrainingCaptureRef } from "./rawTrainingCapture.js";
7
7
  import { type PiWorldToolContextRef } from "./worldNudge.js";
8
8
  import { type PiWorldTrajectoryIdentity } from "./worldTrajectory.js";
9
- import { type PiNativeSessionCreator, type PiSession, type PiSessionCreator, type PiSessionLike } from "./piAgentWakeSupport.js";
9
+ import { type PiNativeSessionCreator, type PiSession, type PiSessionCreator, type PiSessionLike, type PiWakeEnvironmentContextRef } from "./piAgentWakeSupport.js";
10
10
  import { type MemoryRuntime } from "@noopolis/mneme";
11
11
  export type { PiSession, PiSessionLike, PiSessionCreator, PiNativeSessionCreator } from "./piAgentWakeSupport.js";
12
12
  export type WakeAcceptanceInput = {
@@ -28,6 +28,7 @@ export declare class PiAgentHandle implements AgentHandle {
28
28
  private readonly rawTrainingCaptureOptions?;
29
29
  private readonly worldTrajectoryIdentity?;
30
30
  private readonly piSessionForRawCapture?;
31
+ private readonly wakeEnvironmentContext?;
31
32
  private state;
32
33
  private lastWakeAt;
33
34
  private lastError;
@@ -35,8 +36,8 @@ export declare class PiAgentHandle implements AgentHandle {
35
36
  private readonly stampTurnInputSubmitted;
36
37
  private readonly stampTurnOutputCompleted;
37
38
  private readonly persistTrace;
38
- constructor(id: string, session: PiSession, createSession: PiNativeSessionCreator, runtimeHomePath: string, traceModel: PiTurnTraceModel, memory?: MemoryRuntime, memoryToolContext?: PiMemoryToolContextRef, dependencies?: WakeAcceptanceInput, worldToolContext?: PiWorldToolContextRef, rawTrainingCaptureRef?: PiRawTrainingCaptureRef, rawTrainingCaptureOptions?: PiRawTrainingCaptureOptions, worldTrajectoryIdentity?: PiWorldTrajectoryIdentity, rawTrainingCaptureSession?: PiSession);
39
- constructor(id: string, session: PiSessionLike, createSession: PiSessionCreator, runtimeHomePath: string, traceModel: PiTurnTraceModel, memory?: MemoryRuntime, memoryToolContext?: PiMemoryToolContextRef, dependencies?: WakeAcceptanceInput, worldToolContext?: PiWorldToolContextRef, rawTrainingCaptureRef?: never, rawTrainingCaptureOptions?: never, worldTrajectoryIdentity?: PiWorldTrajectoryIdentity, rawTrainingCaptureSession?: never);
39
+ constructor(id: string, session: PiSession, createSession: PiNativeSessionCreator, runtimeHomePath: string, traceModel: PiTurnTraceModel, memory?: MemoryRuntime, memoryToolContext?: PiMemoryToolContextRef, dependencies?: WakeAcceptanceInput, worldToolContext?: PiWorldToolContextRef, rawTrainingCaptureRef?: PiRawTrainingCaptureRef, rawTrainingCaptureOptions?: PiRawTrainingCaptureOptions, worldTrajectoryIdentity?: PiWorldTrajectoryIdentity, rawTrainingCaptureSession?: PiSession, wakeEnvironmentContext?: PiWakeEnvironmentContextRef);
40
+ constructor(id: string, session: PiSessionLike, createSession: PiSessionCreator, runtimeHomePath: string, traceModel: PiTurnTraceModel, memory?: MemoryRuntime, memoryToolContext?: PiMemoryToolContextRef, dependencies?: WakeAcceptanceInput, worldToolContext?: PiWorldToolContextRef, rawTrainingCaptureRef?: never, rawTrainingCaptureOptions?: never, worldTrajectoryIdentity?: PiWorldTrajectoryIdentity, rawTrainingCaptureSession?: never, wakeEnvironmentContext?: PiWakeEnvironmentContextRef);
40
41
  wake(event: WakeEvent): Promise<WakeResult>;
41
42
  private runWake;
42
43
  status(): AgentStatus;