@noopolis/daimon 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (404) hide show
  1. package/README.md +307 -45
  2. package/dist/contracts/attentionContract.d.ts +117 -0
  3. package/dist/contracts/attentionContract.d.ts.map +1 -0
  4. package/dist/contracts/attentionContract.js +14 -0
  5. package/dist/contracts/canonicalJson.d.ts +3 -0
  6. package/dist/contracts/canonicalJson.d.ts.map +1 -0
  7. package/dist/contracts/canonicalJson.js +54 -0
  8. package/dist/contracts/grokWorkerContract.d.ts +74 -0
  9. package/dist/contracts/grokWorkerContract.d.ts.map +1 -0
  10. package/dist/contracts/grokWorkerContract.js +88 -0
  11. package/dist/contracts/organizationRuntimeContract.d.ts +765 -0
  12. package/dist/contracts/organizationRuntimeContract.d.ts.map +1 -0
  13. package/dist/contracts/organizationRuntimeContract.js +121 -0
  14. package/dist/contracts/runtimeContractManifest.d.ts +1615 -0
  15. package/dist/contracts/runtimeContractManifest.d.ts.map +1 -0
  16. package/dist/contracts/runtimeContractManifest.js +181 -0
  17. package/dist/core/credentialRedaction.d.ts +4 -0
  18. package/dist/core/credentialRedaction.d.ts.map +1 -0
  19. package/dist/core/credentialRedaction.js +28 -0
  20. package/dist/core/siblingBuildFreshness.d.ts +21 -0
  21. package/dist/core/siblingBuildFreshness.d.ts.map +1 -0
  22. package/dist/core/siblingBuildFreshness.js +25 -0
  23. package/dist/core/types.d.ts +10 -1
  24. package/dist/core/types.d.ts.map +1 -1
  25. package/dist/examples/exampleCausalId.d.ts +3 -0
  26. package/dist/examples/exampleCausalId.d.ts.map +1 -0
  27. package/dist/examples/exampleCausalId.js +8 -0
  28. package/dist/examples/jungian-play-org.js +3 -2
  29. package/dist/examples/jungian-triad-org.js +3 -2
  30. package/dist/examples/jungianPlayAgent.d.ts +1 -1
  31. package/dist/examples/jungianPlayAgent.d.ts.map +1 -1
  32. package/dist/examples/jungianPlayAgent.js +1 -1
  33. package/dist/examples/jungianProfiles.d.ts +1 -1
  34. package/dist/examples/jungianProfiles.d.ts.map +1 -1
  35. package/dist/examples/jungianTriadProfiles.d.ts +1 -1
  36. package/dist/examples/jungianTriadProfiles.d.ts.map +1 -1
  37. package/dist/examples/pi-agent.js +3 -2
  38. package/dist/examples/pi-memory-org.js +6 -5
  39. package/dist/index.d.ts +1 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +1 -0
  42. package/dist/mcp/toolServer.d.ts +31 -0
  43. package/dist/mcp/toolServer.d.ts.map +1 -0
  44. package/dist/mcp/toolServer.js +145 -0
  45. package/dist/observability/causalEvents.d.ts +118 -0
  46. package/dist/observability/causalEvents.d.ts.map +1 -0
  47. package/dist/observability/causalEvents.js +223 -0
  48. package/dist/observability/controlCausal.d.ts +117 -0
  49. package/dist/observability/controlCausal.d.ts.map +1 -0
  50. package/dist/observability/controlCausal.js +107 -0
  51. package/dist/observability/emitCausalFixture.d.ts +25 -0
  52. package/dist/observability/emitCausalFixture.d.ts.map +1 -0
  53. package/dist/observability/emitCausalFixture.js +98 -0
  54. package/dist/observability/index.d.ts +2 -0
  55. package/dist/observability/index.d.ts.map +1 -1
  56. package/dist/observability/index.js +2 -0
  57. package/dist/observability/orgObserver.d.ts.map +1 -1
  58. package/dist/observability/orgObserver.js +3 -3
  59. package/dist/pi/agyHeadlessResult.d.ts +60 -0
  60. package/dist/pi/agyHeadlessResult.d.ts.map +1 -0
  61. package/dist/pi/agyHeadlessResult.js +95 -0
  62. package/dist/pi/cliChildOutput.d.ts +67 -0
  63. package/dist/pi/cliChildOutput.d.ts.map +1 -0
  64. package/dist/pi/cliChildOutput.js +269 -0
  65. package/dist/pi/cliEngineRun.d.ts +16 -0
  66. package/dist/pi/cliEngineRun.d.ts.map +1 -0
  67. package/dist/pi/cliEngineRun.js +27 -0
  68. package/dist/pi/cliEngineSpawn.d.ts +55 -0
  69. package/dist/pi/cliEngineSpawn.d.ts.map +1 -0
  70. package/dist/pi/cliEngineSpawn.js +164 -0
  71. package/dist/pi/cliEnvironment.d.ts +12 -0
  72. package/dist/pi/cliEnvironment.d.ts.map +1 -0
  73. package/dist/pi/cliEnvironment.js +32 -0
  74. package/dist/pi/cliMcpRegistration.d.ts +61 -0
  75. package/dist/pi/cliMcpRegistration.d.ts.map +1 -0
  76. package/dist/pi/cliMcpRegistration.js +75 -0
  77. package/dist/pi/cliProcess.d.ts +7 -0
  78. package/dist/pi/cliProcess.d.ts.map +1 -0
  79. package/dist/pi/cliProcess.js +132 -0
  80. package/dist/pi/cliSession.d.ts +106 -0
  81. package/dist/pi/cliSession.d.ts.map +1 -0
  82. package/dist/pi/cliSession.js +379 -0
  83. package/dist/pi/cliTurnMetering.d.ts +60 -0
  84. package/dist/pi/cliTurnMetering.d.ts.map +1 -0
  85. package/dist/pi/cliTurnMetering.js +60 -0
  86. package/dist/pi/codexFilesystemRules.d.ts +3 -0
  87. package/dist/pi/codexFilesystemRules.d.ts.map +1 -0
  88. package/dist/pi/codexFilesystemRules.js +28 -0
  89. package/dist/pi/codexHeadlessResult.d.ts +68 -0
  90. package/dist/pi/codexHeadlessResult.d.ts.map +1 -0
  91. package/dist/pi/codexHeadlessResult.js +122 -0
  92. package/dist/pi/codexRolloutUsage.d.ts +95 -0
  93. package/dist/pi/codexRolloutUsage.d.ts.map +1 -0
  94. package/dist/pi/codexRolloutUsage.js +221 -0
  95. package/dist/pi/engineWakeLimits.d.ts +39 -0
  96. package/dist/pi/engineWakeLimits.d.ts.map +1 -0
  97. package/dist/pi/engineWakeLimits.js +55 -0
  98. package/dist/pi/grokHeadlessResult.d.ts +36 -0
  99. package/dist/pi/grokHeadlessResult.d.ts.map +1 -0
  100. package/dist/pi/grokHeadlessResult.js +118 -0
  101. package/dist/pi/grokHomeMcpRegistration.d.ts +21 -0
  102. package/dist/pi/grokHomeMcpRegistration.d.ts.map +1 -0
  103. package/dist/pi/grokHomeMcpRegistration.js +57 -0
  104. package/dist/pi/grokSandbox.d.ts +11 -0
  105. package/dist/pi/grokSandbox.d.ts.map +1 -0
  106. package/dist/pi/grokSandbox.js +216 -0
  107. package/dist/pi/grokStreamUsage.d.ts +31 -0
  108. package/dist/pi/grokStreamUsage.d.ts.map +1 -0
  109. package/dist/pi/grokStreamUsage.js +51 -0
  110. package/dist/pi/index.d.ts +5 -0
  111. package/dist/pi/index.d.ts.map +1 -1
  112. package/dist/pi/index.js +5 -0
  113. package/dist/pi/memoryTools.d.ts +55 -1
  114. package/dist/pi/memoryTools.d.ts.map +1 -1
  115. package/dist/pi/memoryTools.js +144 -24
  116. package/dist/pi/modelRegistry.d.ts +13 -0
  117. package/dist/pi/modelRegistry.d.ts.map +1 -0
  118. package/dist/pi/modelRegistry.js +19 -0
  119. package/dist/pi/piAgentHandle.d.ts +46 -0
  120. package/dist/pi/piAgentHandle.d.ts.map +1 -0
  121. package/dist/pi/piAgentHandle.js +351 -0
  122. package/dist/pi/piAgentWakeSupport.d.ts +103 -0
  123. package/dist/pi/piAgentWakeSupport.d.ts.map +1 -0
  124. package/dist/pi/piAgentWakeSupport.js +151 -0
  125. package/dist/pi/piHarness.d.ts +40 -5
  126. package/dist/pi/piHarness.d.ts.map +1 -1
  127. package/dist/pi/piHarness.js +151 -256
  128. package/dist/pi/prompts.d.ts +10 -0
  129. package/dist/pi/prompts.d.ts.map +1 -0
  130. package/dist/pi/prompts.js +63 -0
  131. package/dist/pi/rawTrainingCapture.d.ts +59 -0
  132. package/dist/pi/rawTrainingCapture.d.ts.map +1 -0
  133. package/dist/pi/rawTrainingCapture.js +175 -0
  134. package/dist/pi/turnCausal.d.ts +73 -0
  135. package/dist/pi/turnCausal.d.ts.map +1 -0
  136. package/dist/pi/turnCausal.js +75 -0
  137. package/dist/pi/turnTrace.d.ts +128 -0
  138. package/dist/pi/turnTrace.d.ts.map +1 -0
  139. package/dist/pi/turnTrace.js +138 -0
  140. package/dist/pi/wakeAcceptance.d.ts +49 -0
  141. package/dist/pi/wakeAcceptance.d.ts.map +1 -0
  142. package/dist/pi/wakeAcceptance.js +281 -0
  143. package/dist/pi/wakeAcceptanceFs.d.ts +44 -0
  144. package/dist/pi/wakeAcceptanceFs.d.ts.map +1 -0
  145. package/dist/pi/wakeAcceptanceFs.js +318 -0
  146. package/dist/pi/wakeAcceptanceSchema.d.ts +75 -0
  147. package/dist/pi/wakeAcceptanceSchema.d.ts.map +1 -0
  148. package/dist/pi/wakeAcceptanceSchema.js +265 -0
  149. package/dist/pi/wakeModes.d.ts +9 -0
  150. package/dist/pi/wakeModes.d.ts.map +1 -0
  151. package/dist/pi/wakeModes.js +19 -0
  152. package/dist/pi/worldNudge.d.ts +22 -0
  153. package/dist/pi/worldNudge.d.ts.map +1 -0
  154. package/dist/pi/worldNudge.js +62 -0
  155. package/dist/pi/worldToolProtocol.d.ts +13 -0
  156. package/dist/pi/worldToolProtocol.d.ts.map +1 -0
  157. package/dist/pi/worldToolProtocol.js +49 -0
  158. package/dist/pi/worldTools.d.ts +32 -0
  159. package/dist/pi/worldTools.d.ts.map +1 -0
  160. package/dist/pi/worldTools.js +373 -0
  161. package/dist/pi/worldTrajectory.d.ts +52 -0
  162. package/dist/pi/worldTrajectory.d.ts.map +1 -0
  163. package/dist/pi/worldTrajectory.js +131 -0
  164. package/dist/runtime/agySubscriptionBootstrap.d.ts +16 -0
  165. package/dist/runtime/agySubscriptionBootstrap.d.ts.map +1 -0
  166. package/dist/runtime/agySubscriptionBootstrap.js +80 -0
  167. package/dist/runtime/agySubscriptionRealm.d.ts +38 -0
  168. package/dist/runtime/agySubscriptionRealm.d.ts.map +1 -0
  169. package/dist/runtime/agySubscriptionRealm.js +242 -0
  170. package/dist/runtime/attention.d.ts +21 -0
  171. package/dist/runtime/attention.d.ts.map +1 -0
  172. package/dist/runtime/attention.js +36 -0
  173. package/dist/runtime/attentionDispatcher.d.ts +66 -0
  174. package/dist/runtime/attentionDispatcher.d.ts.map +1 -0
  175. package/dist/runtime/attentionDispatcher.js +271 -0
  176. package/dist/runtime/cli.d.ts +7 -0
  177. package/dist/runtime/cli.d.ts.map +1 -0
  178. package/dist/runtime/cli.js +251 -0
  179. package/dist/runtime/codexSandboxProjection.d.ts +17 -0
  180. package/dist/runtime/codexSandboxProjection.d.ts.map +1 -0
  181. package/dist/runtime/codexSandboxProjection.js +40 -0
  182. package/dist/runtime/contract-manifest.json +1 -0
  183. package/dist/runtime/contract-manifest.sha256 +1 -0
  184. package/dist/runtime/contractManifest.d.ts +8 -0
  185. package/dist/runtime/contractManifest.d.ts.map +1 -0
  186. package/dist/runtime/contractManifest.js +4 -0
  187. package/dist/runtime/engineBrokerCapabilities.d.ts +30 -0
  188. package/dist/runtime/engineBrokerCapabilities.d.ts.map +1 -0
  189. package/dist/runtime/engineBrokerCapabilities.js +59 -0
  190. package/dist/runtime/engineBrokerControlClient.d.ts +44 -0
  191. package/dist/runtime/engineBrokerControlClient.d.ts.map +1 -0
  192. package/dist/runtime/engineBrokerControlClient.js +132 -0
  193. package/dist/runtime/engineBrokerCredentialJournal.d.ts +10 -0
  194. package/dist/runtime/engineBrokerCredentialJournal.d.ts.map +1 -0
  195. package/dist/runtime/engineBrokerCredentialJournal.js +17 -0
  196. package/dist/runtime/engineBrokerInferenceProtocol.d.ts +52 -0
  197. package/dist/runtime/engineBrokerInferenceProtocol.d.ts.map +1 -0
  198. package/dist/runtime/engineBrokerInferenceProtocol.js +65 -0
  199. package/dist/runtime/engineBrokerMcpCallLog.d.ts +160 -0
  200. package/dist/runtime/engineBrokerMcpCallLog.d.ts.map +1 -0
  201. package/dist/runtime/engineBrokerMcpCallLog.js +219 -0
  202. package/dist/runtime/engineBrokerMcpFacade.d.ts +56 -0
  203. package/dist/runtime/engineBrokerMcpFacade.d.ts.map +1 -0
  204. package/dist/runtime/engineBrokerMcpFacade.js +343 -0
  205. package/dist/runtime/engineBrokerNativeClient.d.ts +52 -0
  206. package/dist/runtime/engineBrokerNativeClient.d.ts.map +1 -0
  207. package/dist/runtime/engineBrokerNativeClient.js +151 -0
  208. package/dist/runtime/engineBrokerProtocol.d.ts +135 -0
  209. package/dist/runtime/engineBrokerProtocol.d.ts.map +1 -0
  210. package/dist/runtime/engineBrokerProtocol.js +274 -0
  211. package/dist/runtime/engineBrokerSealLedger.d.ts +70 -0
  212. package/dist/runtime/engineBrokerSealLedger.d.ts.map +1 -0
  213. package/dist/runtime/engineBrokerSealLedger.js +123 -0
  214. package/dist/runtime/engineBrokerService.d.ts +37 -0
  215. package/dist/runtime/engineBrokerService.d.ts.map +1 -0
  216. package/dist/runtime/engineBrokerService.js +138 -0
  217. package/dist/runtime/engineBrokerServiceCli.d.ts +5 -0
  218. package/dist/runtime/engineBrokerServiceCli.d.ts.map +1 -0
  219. package/dist/runtime/engineBrokerServiceCli.js +32 -0
  220. package/dist/runtime/engineBrokerServiceConfig.d.ts +50 -0
  221. package/dist/runtime/engineBrokerServiceConfig.d.ts.map +1 -0
  222. package/dist/runtime/engineBrokerServiceConfig.js +92 -0
  223. package/dist/runtime/engineBrokerSingleflight.d.ts +13 -0
  224. package/dist/runtime/engineBrokerSingleflight.d.ts.map +1 -0
  225. package/dist/runtime/engineBrokerSingleflight.js +24 -0
  226. package/dist/runtime/engineBrokerTurnAccounting.d.ts +76 -0
  227. package/dist/runtime/engineBrokerTurnAccounting.d.ts.map +1 -0
  228. package/dist/runtime/engineBrokerTurnAccounting.js +108 -0
  229. package/dist/runtime/engineBrokerTurnRegistry.d.ts +57 -0
  230. package/dist/runtime/engineBrokerTurnRegistry.d.ts.map +1 -0
  231. package/dist/runtime/engineBrokerTurnRegistry.js +158 -0
  232. package/dist/runtime/engineDispatcher.d.ts +36 -0
  233. package/dist/runtime/engineDispatcher.d.ts.map +1 -0
  234. package/dist/runtime/engineDispatcher.js +216 -0
  235. package/dist/runtime/engineReadiness.d.ts +23 -0
  236. package/dist/runtime/engineReadiness.d.ts.map +1 -0
  237. package/dist/runtime/engineReadiness.js +222 -0
  238. package/dist/runtime/grokAuthenticationError.d.ts +8 -0
  239. package/dist/runtime/grokAuthenticationError.d.ts.map +1 -0
  240. package/dist/runtime/grokAuthenticationError.js +20 -0
  241. package/dist/runtime/grokBrokerCredentialAuthority.d.ts +22 -0
  242. package/dist/runtime/grokBrokerCredentialAuthority.d.ts.map +1 -0
  243. package/dist/runtime/grokBrokerCredentialAuthority.js +124 -0
  244. package/dist/runtime/grokBrokerCredentialReader.d.ts +5 -0
  245. package/dist/runtime/grokBrokerCredentialReader.d.ts.map +1 -0
  246. package/dist/runtime/grokBrokerCredentialReader.js +37 -0
  247. package/dist/runtime/grokBrokerModelPolicy.d.ts +23 -0
  248. package/dist/runtime/grokBrokerModelPolicy.d.ts.map +1 -0
  249. package/dist/runtime/grokBrokerModelPolicy.js +28 -0
  250. package/dist/runtime/grokBrokerProjection.d.ts +106 -0
  251. package/dist/runtime/grokBrokerProjection.d.ts.map +1 -0
  252. package/dist/runtime/grokBrokerProjection.js +94 -0
  253. package/dist/runtime/grokBrokerProxy.d.ts +55 -0
  254. package/dist/runtime/grokBrokerProxy.d.ts.map +1 -0
  255. package/dist/runtime/grokBrokerProxy.js +262 -0
  256. package/dist/runtime/grokBrokerProxyRequest.d.ts +30 -0
  257. package/dist/runtime/grokBrokerProxyRequest.d.ts.map +1 -0
  258. package/dist/runtime/grokBrokerProxyRequest.js +74 -0
  259. package/dist/runtime/grokBrokerRealmLease.d.ts +4 -0
  260. package/dist/runtime/grokBrokerRealmLease.d.ts.map +1 -0
  261. package/dist/runtime/grokBrokerRealmLease.js +33 -0
  262. package/dist/runtime/grokBrokerRefresh.d.ts +2 -0
  263. package/dist/runtime/grokBrokerRefresh.d.ts.map +1 -0
  264. package/dist/runtime/grokBrokerRefresh.js +15 -0
  265. package/dist/runtime/grokBrokerTurnMeter.d.ts +128 -0
  266. package/dist/runtime/grokBrokerTurnMeter.d.ts.map +1 -0
  267. package/dist/runtime/grokBrokerTurnMeter.js +251 -0
  268. package/dist/runtime/grokBrokerWorkerConfig.d.ts +86 -0
  269. package/dist/runtime/grokBrokerWorkerConfig.d.ts.map +1 -0
  270. package/dist/runtime/grokBrokerWorkerConfig.js +135 -0
  271. package/dist/runtime/grokEngineBroker.d.ts +48 -0
  272. package/dist/runtime/grokEngineBroker.d.ts.map +1 -0
  273. package/dist/runtime/grokEngineBroker.js +114 -0
  274. package/dist/runtime/grokEngineBrokerLedger.d.ts +52 -0
  275. package/dist/runtime/grokEngineBrokerLedger.d.ts.map +1 -0
  276. package/dist/runtime/grokEngineBrokerLedger.js +114 -0
  277. package/dist/runtime/grokEngineBrokerMetering.d.ts +51 -0
  278. package/dist/runtime/grokEngineBrokerMetering.d.ts.map +1 -0
  279. package/dist/runtime/grokEngineBrokerMetering.js +34 -0
  280. package/dist/runtime/grokEngineBrokerTurn.d.ts +58 -0
  281. package/dist/runtime/grokEngineBrokerTurn.d.ts.map +1 -0
  282. package/dist/runtime/grokEngineBrokerTurn.js +165 -0
  283. package/dist/runtime/grokInferenceClientConfig.d.ts +41 -0
  284. package/dist/runtime/grokInferenceClientConfig.d.ts.map +1 -0
  285. package/dist/runtime/grokInferenceClientConfig.js +62 -0
  286. package/dist/runtime/grokInferenceGrants.d.ts +77 -0
  287. package/dist/runtime/grokInferenceGrants.d.ts.map +1 -0
  288. package/dist/runtime/grokInferenceGrants.js +116 -0
  289. package/dist/runtime/grokInferenceProxy.d.ts +29 -0
  290. package/dist/runtime/grokInferenceProxy.d.ts.map +1 -0
  291. package/dist/runtime/grokInferenceProxy.js +82 -0
  292. package/dist/runtime/grokInferenceProxyRequest.d.ts +23 -0
  293. package/dist/runtime/grokInferenceProxyRequest.d.ts.map +1 -0
  294. package/dist/runtime/grokInferenceProxyRequest.js +63 -0
  295. package/dist/runtime/grokSlotPreflightReceipt.d.ts +70 -0
  296. package/dist/runtime/grokSlotPreflightReceipt.d.ts.map +1 -0
  297. package/dist/runtime/grokSlotPreflightReceipt.js +101 -0
  298. package/dist/runtime/grokSubscriptionRealm.d.ts +4 -0
  299. package/dist/runtime/grokSubscriptionRealm.d.ts.map +1 -0
  300. package/dist/runtime/grokSubscriptionRealm.js +435 -0
  301. package/dist/runtime/grokSubscriptionRealmTypes.d.ts +26 -0
  302. package/dist/runtime/grokSubscriptionRealmTypes.d.ts.map +1 -0
  303. package/dist/runtime/grokSubscriptionRealmTypes.js +1 -0
  304. package/dist/runtime/grokWorkerAttestation.d.ts +170 -0
  305. package/dist/runtime/grokWorkerAttestation.d.ts.map +1 -0
  306. package/dist/runtime/grokWorkerAttestation.js +266 -0
  307. package/dist/runtime/grokWorkerDenyPlacement.d.ts +80 -0
  308. package/dist/runtime/grokWorkerDenyPlacement.d.ts.map +1 -0
  309. package/dist/runtime/grokWorkerDenyPlacement.js +128 -0
  310. package/dist/runtime/grokWorkerHomeAttestation.d.ts +30 -0
  311. package/dist/runtime/grokWorkerHomeAttestation.d.ts.map +1 -0
  312. package/dist/runtime/grokWorkerHomeAttestation.js +69 -0
  313. package/dist/runtime/grokWorkerSandboxProfile.d.ts +27 -0
  314. package/dist/runtime/grokWorkerSandboxProfile.d.ts.map +1 -0
  315. package/dist/runtime/grokWorkerSandboxProfile.js +44 -0
  316. package/dist/runtime/grokWorkerTmpAttestation.d.ts +55 -0
  317. package/dist/runtime/grokWorkerTmpAttestation.d.ts.map +1 -0
  318. package/dist/runtime/grokWorkerTmpAttestation.js +63 -0
  319. package/dist/runtime/index.d.ts +26 -0
  320. package/dist/runtime/index.d.ts.map +1 -0
  321. package/dist/runtime/index.js +23 -0
  322. package/dist/runtime/inferenceUsageLedger.d.ts +38 -0
  323. package/dist/runtime/inferenceUsageLedger.d.ts.map +1 -0
  324. package/dist/runtime/inferenceUsageLedger.js +53 -0
  325. package/dist/runtime/mcpToolResult.d.ts +127 -0
  326. package/dist/runtime/mcpToolResult.d.ts.map +1 -0
  327. package/dist/runtime/mcpToolResult.js +214 -0
  328. package/dist/runtime/moltnetMachineRead.d.ts +97 -0
  329. package/dist/runtime/moltnetMachineRead.d.ts.map +1 -0
  330. package/dist/runtime/moltnetMachineRead.js +183 -0
  331. package/dist/runtime/native/daimon-engine-broker +0 -0
  332. package/dist/runtime/organizationRuntime.d.ts +165 -0
  333. package/dist/runtime/organizationRuntime.d.ts.map +1 -0
  334. package/dist/runtime/organizationRuntime.js +3 -0
  335. package/dist/runtime/organizationRuntimeControl.d.ts +42 -0
  336. package/dist/runtime/organizationRuntimeControl.d.ts.map +1 -0
  337. package/dist/runtime/organizationRuntimeControl.js +235 -0
  338. package/dist/runtime/organizationRuntimeHost.d.ts +19 -0
  339. package/dist/runtime/organizationRuntimeHost.d.ts.map +1 -0
  340. package/dist/runtime/organizationRuntimeHost.js +359 -0
  341. package/dist/runtime/organizationRuntimeParsing.d.ts +6 -0
  342. package/dist/runtime/organizationRuntimeParsing.d.ts.map +1 -0
  343. package/dist/runtime/organizationRuntimeParsing.js +370 -0
  344. package/dist/runtime/organizationRuntimeReadiness.d.ts +12 -0
  345. package/dist/runtime/organizationRuntimeReadiness.d.ts.map +1 -0
  346. package/dist/runtime/organizationRuntimeReadiness.js +59 -0
  347. package/dist/runtime/physicalReadiness.d.ts +47 -0
  348. package/dist/runtime/physicalReadiness.d.ts.map +1 -0
  349. package/dist/runtime/physicalReadiness.js +142 -0
  350. package/dist/runtime/portableCredentialAuth.d.ts +6 -0
  351. package/dist/runtime/portableCredentialAuth.d.ts.map +1 -0
  352. package/dist/runtime/portableCredentialAuth.js +70 -0
  353. package/dist/runtime/portableCredentialMaterial.d.ts +8 -0
  354. package/dist/runtime/portableCredentialMaterial.d.ts.map +1 -0
  355. package/dist/runtime/portableCredentialMaterial.js +169 -0
  356. package/dist/runtime/productionAgentTools.d.ts +5 -0
  357. package/dist/runtime/productionAgentTools.d.ts.map +1 -0
  358. package/dist/runtime/productionAgentTools.js +328 -0
  359. package/dist/runtime/runtimeHomeLayout.d.ts +48 -0
  360. package/dist/runtime/runtimeHomeLayout.d.ts.map +1 -0
  361. package/dist/runtime/runtimeHomeLayout.js +84 -0
  362. package/dist/runtime/schedule.d.ts +40 -0
  363. package/dist/runtime/schedule.d.ts.map +1 -0
  364. package/dist/runtime/schedule.js +371 -0
  365. package/dist/runtime/storeCoordination.d.ts +23 -0
  366. package/dist/runtime/storeCoordination.d.ts.map +1 -0
  367. package/dist/runtime/storeCoordination.js +94 -0
  368. package/dist/runtime/toolResultSpill.d.ts +152 -0
  369. package/dist/runtime/toolResultSpill.d.ts.map +1 -0
  370. package/dist/runtime/toolResultSpill.js +351 -0
  371. package/dist/runtime/turnRequestLedger.d.ts +160 -0
  372. package/dist/runtime/turnRequestLedger.d.ts.map +1 -0
  373. package/dist/runtime/turnRequestLedger.js +249 -0
  374. package/dist/runtime/turnUsageLedger.d.ts +143 -0
  375. package/dist/runtime/turnUsageLedger.d.ts.map +1 -0
  376. package/dist/runtime/turnUsageLedger.js +203 -0
  377. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts +17 -0
  378. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts.map +1 -0
  379. package/dist/runtime/wakeAcceptanceProcessIdentity.js +50 -0
  380. package/dist/runtime/wakeAcceptanceReconciliation.d.ts +211 -0
  381. package/dist/runtime/wakeAcceptanceReconciliation.d.ts.map +1 -0
  382. package/dist/runtime/wakeAcceptanceReconciliation.js +289 -0
  383. package/dist/runtime/wakeAcceptanceRecord.d.ts +23 -0
  384. package/dist/runtime/wakeAcceptanceRecord.d.ts.map +1 -0
  385. package/dist/runtime/wakeAcceptanceRecord.js +56 -0
  386. package/dist/runtime/wakeAcceptanceRetention.d.ts +12 -0
  387. package/dist/runtime/wakeAcceptanceRetention.d.ts.map +1 -0
  388. package/dist/runtime/wakeAcceptanceRetention.js +12 -0
  389. package/dist/runtime/wakeAcceptanceStore.d.ts +113 -0
  390. package/dist/runtime/wakeAcceptanceStore.d.ts.map +1 -0
  391. package/dist/runtime/wakeAcceptanceStore.js +558 -0
  392. package/dist/runtime/wakeAcceptanceTypes.d.ts +179 -0
  393. package/dist/runtime/wakeAcceptanceTypes.d.ts.map +1 -0
  394. package/dist/runtime/wakeAcceptanceTypes.js +95 -0
  395. package/dist/runtime/wakeFuse.d.ts +69 -0
  396. package/dist/runtime/wakeFuse.d.ts.map +1 -0
  397. package/dist/runtime/wakeFuse.js +367 -0
  398. package/package.json +25 -17
  399. package/dist/examples/mixed-engine-org.d.ts +0 -2
  400. package/dist/examples/mixed-engine-org.d.ts.map +0 -1
  401. package/dist/examples/mixed-engine-org.js +0 -351
  402. package/dist/examples/mixedEngineCli.d.ts +0 -15
  403. package/dist/examples/mixedEngineCli.d.ts.map +0 -1
  404. package/dist/examples/mixedEngineCli.js +0 -174
@@ -0,0 +1,379 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ import { createPiToolMcpServer } from "../mcp/toolServer.js";
5
+ import { redactCredentialError, redactCredentialText } from "../core/credentialRedaction.js";
6
+ import { asGrokAuthenticationRejected, classifyGrokAuthenticationDiagnostic, GrokSubscriptionAuthenticationRejectedError } from "../runtime/grokAuthenticationError.js";
7
+ import { readChild } from "./cliChildOutput.js";
8
+ import { cliChildEnvironment } from "./cliEnvironment.js";
9
+ import { spawnEngine } from "./cliEngineSpawn.js";
10
+ import { registerCliMcpServer, renderAgyMcpAddArgs, renderAgyMcpRemoveArgs } from "./cliMcpRegistration.js";
11
+ import { registerGrokHomeMcpServer } from "./grokHomeMcpRegistration.js";
12
+ import { decodeAgyHeadlessTurn } from "./agyHeadlessResult.js";
13
+ import { createCliTurnMeter, decodeCodexTurn, failedTurnOutcome, publishTurnRequests, publishTurnUsage } from "./cliTurnMetering.js";
14
+ import { decodeGrokHeadlessResult } from "./grokHeadlessResult.js";
15
+ import { terminateChild } from "./cliProcess.js";
16
+ import { ensureRuntimeHome, ensureRuntimeHomeDirectory } from "../runtime/runtimeHomeLayout.js";
17
+ /**
18
+ * The per-wake tool-call bound for AGY, and the one place it is decided.
19
+ *
20
+ * Codex and Grok leave this `undefined` — their only bound is the wake
21
+ * deadline. AGY does not get that treatment, for a measured reason: its
22
+ * terminal usage frame is the *sum* over the turn's model steps, and each tool
23
+ * step resends the whole context. The live capture is 13,796 total tokens for a
24
+ * tool-free turn and 45,381 for a turn with a single call against an
25
+ * empty-schema tool — one call roughly triples the wake. An unbounded loop on
26
+ * the one engine whose subscription quota is currently the operator's only
27
+ * working credential is a cost hazard, not a capability.
28
+ *
29
+ * 16 is chosen so a realistic wake is never truncated (read a few declared MCP
30
+ * tools, then send one or two Moltnet messages) while the worst case is bounded
31
+ * at roughly a quarter-million tokens instead of "whatever fits in 180s". The
32
+ * bound degrades gracefully rather than failing the wake: exceeding it returns
33
+ * `McpToolTurnLimitError` to the model as a tool *error*, so the agent can still
34
+ * finish its turn and reply.
35
+ */
36
+ export const AGY_MAX_TOOL_TURNS = 16;
37
+ export { DAIMON_CODEX_WAKE_TIMEOUT_MS_ENV, DAIMON_CODEX_WAKE_TOKEN_CEILING_ENV, DAIMON_ENGINE_WAKE_TIMEOUT_MS_ENV, DAIMON_ENGINE_WAKE_TOKEN_CEILING_ENV, DEFAULT_CODEX_WAKE_TIMEOUT_MS, DEFAULT_CODEX_WAKE_TOKEN_CEILING, resolveCodexWakeTimeoutMs, resolveCodexWakeTokenCeiling, resolveEngineWakeLimitOverrides } from "./engineWakeLimits.js";
38
+ export const prepareCliRuntimeHome = async (runtimeHomePath) => {
39
+ if (runtimeHomePath === undefined)
40
+ return;
41
+ await ensureRuntimeHome(runtimeHomePath);
42
+ await Promise.all([".config", ".local/share", ".local/state", ".cache", ".tmp"]
43
+ .map((relative) => ensureRuntimeHomeDirectory(runtimeHomePath, relative)));
44
+ };
45
+ const childSecretValues = (redactedNames) => redactedNames
46
+ .map((name) => process.env[name])
47
+ .filter((value) => typeof value === "string" && value.length > 0);
48
+ const captureCleanup = async (current, action) => {
49
+ try {
50
+ await action();
51
+ }
52
+ catch (error) {
53
+ return current ?? error;
54
+ }
55
+ return current;
56
+ };
57
+ export { terminateChild } from "./cliProcess.js";
58
+ export { CLI_ENGINE_MAX_DIAGNOSTIC_BYTES, CLI_ENGINE_MAX_OUTPUT_BYTES, readChild } from "./cliChildOutput.js";
59
+ const startMcp = async (tools, maxToolTurns, wakeDeadline, onToolsMounted, onStarted) => {
60
+ onToolsMounted?.(tools);
61
+ const mcpServer = createPiToolMcpServer(tools, { maxToolTurns, wakeDeadline });
62
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });
63
+ const httpServer = createServer((request, response) => {
64
+ void transport.handleRequest(request, response);
65
+ });
66
+ let lifecycle = "starting";
67
+ let cancelled = false;
68
+ let endpoint = "";
69
+ let closePromise;
70
+ let settleStartup;
71
+ const startupSettled = new Promise((resolve) => { settleStartup = resolve; });
72
+ const close = () => closePromise ??= (async () => {
73
+ cancelled = true;
74
+ if (lifecycle !== "closed")
75
+ lifecycle = "closing";
76
+ // `listen()` begins synchronously but its callback is pending. Waiting for
77
+ // startup prevents dispose from returning while that callback can still bind.
78
+ await startupSettled;
79
+ await transport.close().catch(() => undefined);
80
+ await mcpServer.close().catch(() => undefined);
81
+ // `close` only stops accepting and then waits for every open connection,
82
+ // including the ones the transport has no record of and so cannot end (a
83
+ // socket opened before `initialize`, or a client pool's idle keep-alive
84
+ // socket, which relaying a turn through the broker MCP facade leaves
85
+ // behind). That wait is unbounded and sits on the wake's own completion
86
+ // path: measured, one such connection parked a finished broker turn with
87
+ // its result in hand and published nothing. By here this one wake's engine
88
+ // has returned, failed or been cancelled, so anything still connected is a
89
+ // leftover — see `AGENTS.md`, and the facade, which bounds itself the same
90
+ // way.
91
+ if (httpServer.listening)
92
+ await new Promise((resolve) => { httpServer.close(() => resolve()); httpServer.closeAllConnections(); });
93
+ lifecycle = "closed";
94
+ })();
95
+ const mount = { get endpoint() { return endpoint; }, close };
96
+ onStarted(mount);
97
+ let startupError;
98
+ try {
99
+ if (cancelled)
100
+ throw new Error("MCP startup was cancelled");
101
+ await mcpServer.connect(transport);
102
+ if (cancelled)
103
+ throw new Error("MCP startup was cancelled");
104
+ await new Promise((resolve, reject) => {
105
+ const onError = (error) => reject(error);
106
+ httpServer.once("error", onError);
107
+ httpServer.listen(0, "127.0.0.1", () => {
108
+ httpServer.off("error", onError);
109
+ // A disposer can run from a Server.prototype.listen interceptor before
110
+ // this callback. Never publish the server as live in that interleaving.
111
+ if (!cancelled)
112
+ lifecycle = "listening";
113
+ resolve();
114
+ });
115
+ });
116
+ if (cancelled)
117
+ throw new Error("MCP startup was cancelled");
118
+ const address = httpServer.address();
119
+ if (address === null || typeof address === "string") {
120
+ throw new Error("MCP server did not receive an ephemeral port");
121
+ }
122
+ endpoint = `http://127.0.0.1:${address.port}/mcp`;
123
+ return mount;
124
+ }
125
+ catch (error) {
126
+ startupError = error;
127
+ throw error;
128
+ }
129
+ finally {
130
+ settleStartup();
131
+ if (cancelled || startupError !== undefined)
132
+ await close();
133
+ }
134
+ };
135
+ class CliSession {
136
+ options;
137
+ input;
138
+ listeners = new Set();
139
+ setupChildren = new Set();
140
+ disposed = false;
141
+ activeChild;
142
+ activeMount;
143
+ activeBrokerTurn;
144
+ mcpRegistration;
145
+ disposePromise;
146
+ wakeId;
147
+ constructor(options, input) {
148
+ this.options = options;
149
+ this.input = input;
150
+ }
151
+ subscribe(listener) {
152
+ this.listeners.add(listener);
153
+ return () => this.listeners.delete(listener);
154
+ }
155
+ bindWake(event) {
156
+ this.wakeId = event?.id;
157
+ }
158
+ async prompt(text) {
159
+ if (this.disposed)
160
+ throw new Error("CLI session is disposed");
161
+ await prepareCliRuntimeHome(this.input.runtimeHomePath);
162
+ const deadline = this.options.timeoutMs === undefined ? undefined : Date.now() + this.options.timeoutMs;
163
+ const environmentSecretValues = childSecretValues([
164
+ ...(this.options.redactedEnvironmentNames ?? []),
165
+ ...(this.input.daimonSecretEnvironmentNames ?? [])
166
+ ]);
167
+ const stagedCredentialSecrets = await this.options.credentialSecretValues?.() ?? [];
168
+ const secretValues = [...environmentSecretValues, ...stagedCredentialSecrets];
169
+ let mount;
170
+ let registration;
171
+ let turnUsage;
172
+ // Kept beside the decoded turn so a wake that never reaches its decoder
173
+ // still owes the ledger the usage Codex already reported (`cliTurnMetering.ts`).
174
+ const meter = createCliTurnMeter();
175
+ // Codex's own `thread.started` frame, carried out of the stream so the
176
+ // wake's rollout can be found by identity rather than by recency.
177
+ let codexThreadId;
178
+ let instrumented = false;
179
+ const instrument = async () => {
180
+ if (instrumented)
181
+ return;
182
+ instrumented = true;
183
+ await publishTurnRequests(this.options.onCodexTurnRequests, codexThreadId);
184
+ };
185
+ let child;
186
+ let output;
187
+ let cleanupFailure;
188
+ let promptFailure;
189
+ try {
190
+ // Every CLI engine mounts the same tool surface. AGY used to be the one
191
+ // exception (`toolAccess: "none"`), which is exactly what made an AGY
192
+ // agent unable to reach Moltnet or a declared MCP server, and so unable
193
+ // to take part in an organization at all.
194
+ mount = await startMcp(this.input.customTools ?? [], this.options.maxToolTurns, deadline, this.options.onToolsMounted, (started) => {
195
+ this.activeMount = started;
196
+ if (this.disposed)
197
+ void started.close();
198
+ });
199
+ this.ensureLive();
200
+ if (this.options.engine === "grok" && this.options.grokBrokerTurn !== undefined && mount !== undefined) {
201
+ const controller = new AbortController();
202
+ this.activeBrokerTurn = controller;
203
+ try {
204
+ output = await this.options.grokBrokerTurn(`${this.options.identityPrompt ?? ""}${text}`, mount.endpoint, controller.signal);
205
+ }
206
+ finally {
207
+ if (this.activeBrokerTurn === controller)
208
+ this.activeBrokerTurn = undefined;
209
+ }
210
+ }
211
+ else {
212
+ if (this.options.engine === "grok" && mount !== undefined) {
213
+ await this.options.verifyExecutable?.();
214
+ registration = await registerGrokHomeMcpServer({
215
+ engineHomePath: this.options.engineHomePath,
216
+ endpoint: mount.endpoint,
217
+ ...(this.options.verifyGrokSandbox !== undefined ? { verify: this.options.verifyGrokSandbox } : {})
218
+ });
219
+ this.mcpRegistration = registration;
220
+ }
221
+ else if (this.options.engine === "agy" && mount !== undefined) {
222
+ await this.options.verifyExecutable?.();
223
+ registration = await registerCliMcpServer({
224
+ addArgs: renderAgyMcpAddArgs(this.options.commandArgs, mount.endpoint),
225
+ removeArgs: renderAgyMcpRemoveArgs(this.options.commandArgs),
226
+ command: this.options.command ?? this.options.engine,
227
+ cwd: this.input.cwd,
228
+ env: cliChildEnvironment([
229
+ ...(this.options.redactedEnvironmentNames ?? []),
230
+ ...(this.input.daimonSecretEnvironmentNames ?? [])
231
+ ], this.input.runtimeHomePath, {
232
+ ...(this.options.dbusSessionBusAddress !== undefined ? { dbusSessionBusAddress: this.options.dbusSessionBusAddress } : {}),
233
+ engine: this.options.engine,
234
+ executablePath: this.options.command,
235
+ engineHomePath: this.options.engineHomePath
236
+ }),
237
+ onChild: (setupChild) => { this.setupChildren.add(setupChild); },
238
+ onChildSettled: (setupChild) => this.setupChildren.delete(setupChild),
239
+ secretValues
240
+ });
241
+ this.mcpRegistration = registration;
242
+ }
243
+ this.ensureLive();
244
+ await this.options.verifyRuntimePaths?.();
245
+ await this.options.verifyExecutable?.();
246
+ await this.options.verifyGrokSandbox?.();
247
+ child = spawnEngine(this.options, `${this.options.identityPrompt ?? ""}${text}`, this.input, mount?.endpoint, this.wakeId);
248
+ this.activeChild = child;
249
+ // Attach terminal listeners synchronously. A fast local sentinel may
250
+ // exit before an asynchronous post-spawn authority recheck completes.
251
+ const outputPromise = readChild(child, deadline === undefined ? undefined : Math.max(1, deadline - Date.now()), secretValues, {
252
+ failureClassifier: this.options.engine === "grok" ? classifyGrokAuthenticationDiagnostic : undefined,
253
+ retainNdjson: this.options.engine === "codex" ? "codex" : undefined,
254
+ retainStdoutTail: this.options.engine === "grok",
255
+ timeoutErrorMessage: this.options.engine === "codex" && this.options.timeoutMs !== undefined
256
+ ? `Codex wake exceeded its ${this.options.timeoutMs}ms per-wake wall-clock bound`
257
+ : undefined,
258
+ codexTokenCeiling: this.options.engine === "codex" ? this.options.codexTokenCeiling : undefined,
259
+ onCodexTurnCompleted: meter.observeCodexTurnCompleted,
260
+ onCodexThreadStarted: (threadId) => { codexThreadId = threadId; }
261
+ });
262
+ void outputPromise.catch(() => undefined);
263
+ await this.options.verifyRuntimePaths?.();
264
+ await this.options.verifyExecutable?.();
265
+ const childOutput = await outputPromise;
266
+ if (this.options.engine === "grok")
267
+ output = decodeGrokHeadlessResult(childOutput);
268
+ else if (this.options.engine === "codex") {
269
+ const decoded = decodeCodexTurn(childOutput);
270
+ output = decoded.text;
271
+ turnUsage = decoded.usage;
272
+ }
273
+ else if (this.options.engine === "agy") {
274
+ const decoded = decodeAgyHeadlessTurn(childOutput);
275
+ output = decoded.text;
276
+ turnUsage = decoded.usage;
277
+ }
278
+ else
279
+ output = childOutput;
280
+ }
281
+ }
282
+ catch (error) {
283
+ promptFailure = error;
284
+ }
285
+ finally {
286
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { if (child !== undefined)
287
+ await terminateChild(child); });
288
+ if (this.activeChild === child)
289
+ this.activeChild = undefined;
290
+ let registrationClosed = registration === undefined;
291
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { await registration?.close(); registrationClosed = true; });
292
+ if (registrationClosed && this.mcpRegistration === registration)
293
+ this.mcpRegistration = undefined;
294
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { await mount?.close(); });
295
+ if (this.activeMount === mount)
296
+ this.activeMount = undefined;
297
+ }
298
+ const refreshedCredentialSecrets = await this.options.credentialSecretValues?.().catch(() => []) ?? [];
299
+ const finalSecrets = [...secretValues, ...refreshedCredentialSecrets];
300
+ // A wake that Codex reported usage for is metered whether or not it goes on
301
+ // to publish. Every throw below this point used to drop that spend on the
302
+ // floor, so a breached ceiling, an expired wall clock, a non-zero exit, or
303
+ // a turn judged unpublishable all cost money the ledger never saw.
304
+ const failure = promptFailure ?? cleanupFailure;
305
+ if (failure !== undefined) {
306
+ await publishTurnUsage(this.options.onTurnUsage, turnUsage ?? meter.reported(), failedTurnOutcome(failure));
307
+ // A wake that failed still made model requests and still paid for them,
308
+ // so its per-request shape is measured on exactly the paths its spend is.
309
+ await instrument();
310
+ }
311
+ if (promptFailure !== undefined) {
312
+ const authRejection = this.options.engine === "grok" ? asGrokAuthenticationRejected(promptFailure) : undefined;
313
+ if (authRejection !== undefined)
314
+ throw new GrokSubscriptionAuthenticationRejectedError(cleanupFailure === undefined ? undefined : redactCredentialError(cleanupFailure, finalSecrets));
315
+ if (cleanupFailure !== undefined)
316
+ throw redactCredentialError(cleanupFailure, finalSecrets);
317
+ throw redactCredentialError(promptFailure, finalSecrets);
318
+ }
319
+ if (cleanupFailure !== undefined) {
320
+ if (this.options.engine === "grok" && asGrokAuthenticationRejected(cleanupFailure) !== undefined) {
321
+ throw new GrokSubscriptionAuthenticationRejectedError();
322
+ }
323
+ throw redactCredentialError(cleanupFailure, finalSecrets);
324
+ }
325
+ if (output === undefined)
326
+ return;
327
+ output = redactCredentialText(output, finalSecrets, 64 * 1024);
328
+ for (const listener of this.listeners)
329
+ listener({
330
+ type: "turn_end",
331
+ message: {
332
+ role: "assistant", content: [{ type: "text", text: output }], api: "openai-completions", provider: "openai", model: "cli",
333
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
334
+ stopReason: "stop", timestamp: Date.now()
335
+ }, toolResults: []
336
+ });
337
+ // Meter only after the turn has published.
338
+ await publishTurnUsage(this.options.onTurnUsage, turnUsage ?? meter.reported(), { status: "completed" });
339
+ await instrument();
340
+ }
341
+ dispose() {
342
+ this.disposed = true;
343
+ this.listeners.clear();
344
+ this.disposePromise ??= this.quiesce();
345
+ }
346
+ async disposeAsync() {
347
+ this.dispose();
348
+ await this.disposePromise;
349
+ }
350
+ ensureLive() {
351
+ if (this.disposed)
352
+ throw new Error("CLI session is disposed");
353
+ }
354
+ async quiesce() {
355
+ let cleanupFailure;
356
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { if (this.activeChild !== undefined)
357
+ await terminateChild(this.activeChild); });
358
+ this.activeBrokerTurn?.abort();
359
+ cleanupFailure = await captureCleanup(cleanupFailure, () => Promise.all([...this.setupChildren].map((child) => terminateChild(child))).then(() => undefined));
360
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { await this.mcpRegistration?.close(); });
361
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { await this.activeMount?.close(); });
362
+ if (cleanupFailure !== undefined)
363
+ throw cleanupFailure;
364
+ }
365
+ }
366
+ export const createCliSessionFactory = (options) => async (input) => {
367
+ if (input.cwd === undefined)
368
+ throw new Error("CLI session cwd is required");
369
+ return {
370
+ session: new CliSession(options, {
371
+ cwd: input.cwd,
372
+ customTools: input.customTools,
373
+ daimonSecretEnvironmentNames: input.daimonSecretEnvironmentNames,
374
+ runtimeHomePath: input.runtimeHomePath
375
+ })
376
+ };
377
+ };
378
+ export { runEngine, runEngineDetailed } from "./cliEngineRun.js";
379
+ export { renderAgyArgs, renderCodexArgs, spawnEngine } from "./cliEngineSpawn.js";
@@ -0,0 +1,60 @@
1
+ import type { AgyTurnUsage } from "./agyHeadlessResult.js";
2
+ import { type CodexHeadlessTurn, type CodexTurnUsage } from "./codexHeadlessResult.js";
3
+ import type { TurnUsageOutcome } from "../runtime/turnUsageLedger.js";
4
+ /**
5
+ * What one CLI turn owes the usage ledger, and the rules for when it owes
6
+ * nothing.
7
+ *
8
+ * A wake that fails spends exactly the money a wake that publishes spends, so
9
+ * the engine's reported usage is metered on both paths and the row's outcome
10
+ * says which. A Codex wake that breached its per-wake token ceiling used to
11
+ * record nothing at all: the tokens it burned survived only as a number
12
+ * interpolated into the error message, and a timeout, a killed child, or a
13
+ * non-zero exit lost the figure entirely.
14
+ *
15
+ * The counterweight is that a number is never invented. A zero-filled row is
16
+ * byte-identical to a real zero and would silently poison every aggregate
17
+ * computed over the ledger, so "the engine reported nothing" stays absent.
18
+ */
19
+ export type CliTurnMeter = Readonly<{
20
+ /** Wire this to `readChild`'s `onCodexTurnCompleted`. */
21
+ observeCodexTurnCompleted: (usage: CodexTurnUsage | undefined) => void;
22
+ /**
23
+ * The usage Codex reported mid-stream, for a wake that never reached its
24
+ * decoder.
25
+ *
26
+ * Trustworthy only under `decodeCodexHeadlessTurn`'s own rule: exactly one
27
+ * `turn.completed` frame. Codex may omit, repeat, or follow that frame with
28
+ * another, and two completions leave no defensible answer for which one the
29
+ * wake actually spent — so this declines rather than guessing, and no frame
30
+ * at all means nothing was reported and nothing is written.
31
+ */
32
+ reported: () => CodexTurnUsage | undefined;
33
+ }>;
34
+ export declare const createCliTurnMeter: () => CliTurnMeter;
35
+ /**
36
+ * A turn Codex reported usage for but that the decoder refuses to publish is
37
+ * still a turn that spent tokens. Tagging the rejection is what lets the
38
+ * ledger row name why the wake failed instead of matching on message prose.
39
+ */
40
+ export declare const decodeCodexTurn: (output: string) => CodexHeadlessTurn;
41
+ /** The failed row's marker, named by the bound that actually fired. */
42
+ export declare const failedTurnOutcome: (failure: unknown) => TurnUsageOutcome;
43
+ /**
44
+ * Advisory: metering never fails, delays, or rewrites the wake it describes —
45
+ * the same ordering rule the Grok engine broker states in
46
+ * `finishBrokerTurnWithUsage`.
47
+ */
48
+ export declare const publishTurnUsage: (sink: ((usage: AgyTurnUsage | CodexTurnUsage, outcome: TurnUsageOutcome) => Promise<void>) | undefined, usage: AgyTurnUsage | CodexTurnUsage | undefined, outcome: TurnUsageOutcome) => Promise<void>;
49
+ /**
50
+ * Advisory per-request instrumentation, under the same ordering rule as
51
+ * {@link publishTurnUsage}: it never fails, delays, or rewrites the wake it
52
+ * describes.
53
+ *
54
+ * No thread id means Codex never announced one — an engine that is not Codex,
55
+ * a child killed before its first frame, or a future stream that renamed the
56
+ * event. Nothing is written in that case, because the alternative is guessing
57
+ * which rollout on disk belongs to this wake.
58
+ */
59
+ export declare const publishTurnRequests: (sink: ((threadId: string) => Promise<void>) | undefined, threadId: string | undefined) => Promise<void>;
60
+ //# sourceMappingURL=cliTurnMetering.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cliTurnMetering.d.ts","sourceRoot":"","sources":["../../src/pi/cliTurnMetering.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAE3D,OAAO,EAA2B,KAAK,iBAAiB,EAAE,KAAK,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAChH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAEtE;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,YAAY,GAAG,QAAQ,CAAC;IAClC,yDAAyD;IACzD,yBAAyB,EAAE,CAAC,KAAK,EAAE,cAAc,GAAG,SAAS,KAAK,IAAI,CAAC;IACvE;;;;;;;;;OASG;IACH,QAAQ,EAAE,MAAM,cAAc,GAAG,SAAS,CAAC;CAC5C,CAAC,CAAC;AAEH,eAAO,MAAM,kBAAkB,QAAO,YAUrC,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,MAAM,KAAG,iBAGhD,CAAC;AAEF,uEAAuE;AACvE,eAAO,MAAM,iBAAiB,GAAI,SAAS,OAAO,KAAG,gBACwB,CAAC;AAE9E;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,GAC3B,MAAM,CAAC,CAAC,KAAK,EAAE,YAAY,GAAG,cAAc,EAAE,OAAO,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,SAAS,EACtG,OAAO,YAAY,GAAG,cAAc,GAAG,SAAS,EAChD,SAAS,gBAAgB,KACxB,OAAO,CAAC,IAAI,CAGd,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,mBAAmB,GAC9B,MAAM,CAAC,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,SAAS,EACvD,UAAU,MAAM,GAAG,SAAS,KAC3B,OAAO,CAAC,IAAI,CAGd,CAAC"}
@@ -0,0 +1,60 @@
1
+ import { cliChildFailureReason, tagCliChildFailure } from "./cliChildOutput.js";
2
+ import { decodeCodexHeadlessTurn } from "./codexHeadlessResult.js";
3
+ export const createCliTurnMeter = () => {
4
+ let usage;
5
+ let completions = 0;
6
+ return {
7
+ observeCodexTurnCompleted: (reported) => {
8
+ completions += 1;
9
+ if (reported !== undefined)
10
+ usage = reported;
11
+ },
12
+ reported: () => (completions === 1 ? usage : undefined)
13
+ };
14
+ };
15
+ /**
16
+ * A turn Codex reported usage for but that the decoder refuses to publish is
17
+ * still a turn that spent tokens. Tagging the rejection is what lets the
18
+ * ledger row name why the wake failed instead of matching on message prose.
19
+ */
20
+ export const decodeCodexTurn = (output) => {
21
+ try {
22
+ return decodeCodexHeadlessTurn(output);
23
+ }
24
+ catch (error) {
25
+ throw tagCliChildFailure(error, "turn_rejected");
26
+ }
27
+ };
28
+ /** The failed row's marker, named by the bound that actually fired. */
29
+ export const failedTurnOutcome = (failure) => ({ status: "failed", reason: cliChildFailureReason(failure) ?? "unknown" });
30
+ /**
31
+ * Advisory: metering never fails, delays, or rewrites the wake it describes —
32
+ * the same ordering rule the Grok engine broker states in
33
+ * `finishBrokerTurnWithUsage`.
34
+ */
35
+ export const publishTurnUsage = async (sink, usage, outcome) => {
36
+ if (usage === undefined)
37
+ return;
38
+ try {
39
+ await sink?.(usage, outcome).catch(() => undefined);
40
+ }
41
+ catch { /* advisory */ }
42
+ };
43
+ /**
44
+ * Advisory per-request instrumentation, under the same ordering rule as
45
+ * {@link publishTurnUsage}: it never fails, delays, or rewrites the wake it
46
+ * describes.
47
+ *
48
+ * No thread id means Codex never announced one — an engine that is not Codex,
49
+ * a child killed before its first frame, or a future stream that renamed the
50
+ * event. Nothing is written in that case, because the alternative is guessing
51
+ * which rollout on disk belongs to this wake.
52
+ */
53
+ export const publishTurnRequests = async (sink, threadId) => {
54
+ if (threadId === undefined)
55
+ return;
56
+ try {
57
+ await sink?.(threadId).catch(() => undefined);
58
+ }
59
+ catch { /* advisory */ }
60
+ };
@@ -0,0 +1,3 @@
1
+ /** Codex mounts deny roots read-only; a second deny below one cannot create parents. */
2
+ export declare function codexFilesystemRules(protectedPaths: readonly string[], readablePaths: readonly string[], workspacePath?: string): Record<string, "read" | "deny">;
3
+ //# sourceMappingURL=codexFilesystemRules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codexFilesystemRules.d.ts","sourceRoot":"","sources":["../../src/pi/codexFilesystemRules.ts"],"names":[],"mappings":"AAIA,wFAAwF;AACxF,wBAAgB,oBAAoB,CAClC,cAAc,EAAE,SAAS,MAAM,EAAE,EAAE,aAAa,EAAE,SAAS,MAAM,EAAE,EAAE,aAAa,CAAC,EAAE,MAAM,GAC1F,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAqBjC"}
@@ -0,0 +1,28 @@
1
+ import path from "node:path";
2
+ /** Codex mounts deny roots read-only; a second deny below one cannot create parents. */
3
+ export function codexFilesystemRules(protectedPaths, readablePaths, workspacePath) {
4
+ const explicit = new Map();
5
+ // Agent roots are canonical, but shared acceptance paths may contain `..`
6
+ // or trailing separators. Compare the same absolute locations Codex uses.
7
+ for (const readablePath of readablePaths)
8
+ explicit.set(path.resolve(readablePath), "read");
9
+ for (const protectedPath of protectedPaths)
10
+ explicit.set(path.resolve(protectedPath), "deny");
11
+ const effective = new Map([
12
+ ...(workspacePath === undefined ? [] : [[path.resolve(workspacePath), "write"]]),
13
+ ...explicit
14
+ ]);
15
+ return Object.fromEntries([...explicit].filter(([target, permission]) => {
16
+ if (permission !== "deny")
17
+ return true;
18
+ let ancestor = path.dirname(target);
19
+ while (ancestor !== target) {
20
+ const inherited = effective.get(ancestor);
21
+ if (inherited !== undefined)
22
+ return inherited !== "deny";
23
+ target = ancestor;
24
+ ancestor = path.dirname(target);
25
+ }
26
+ return true;
27
+ }));
28
+ }
@@ -0,0 +1,68 @@
1
+ type JsonRecord = Readonly<Record<string, unknown>>;
2
+ /**
3
+ * Token accounting for one Codex turn, from the terminal frame emitted by
4
+ * `codex exec --json`:
5
+ *
6
+ * {"type":"turn.completed","usage":{"input_tokens":…,
7
+ * "cached_input_tokens":…,"cache_write_input_tokens":…,
8
+ * "output_tokens":…,"reasoning_output_tokens":…}}
9
+ *
10
+ * Codex's reconciled session total proves `cached_input_tokens` is a subset of
11
+ * `input_tokens`: total is `input + output`, unlike AGY's disjoint cache-read
12
+ * bucket. Adding cacheRead would over-count every cached turn. Likewise,
13
+ * `reasoning_output_tokens` is a subset of `output_tokens`; it is read only to
14
+ * validate that relationship, never added. Codex reports cache writes, but no
15
+ * cost, so `cacheWrite` is measured while `notionalUsd: 0` means absent, not
16
+ * free. `calls` counts completed command/MCP tools; Codex exposes no AGY-like
17
+ * model-step count, so this is explicitly a tool-call count.
18
+ */
19
+ export type CodexTurnUsage = Readonly<{
20
+ input: number;
21
+ output: number;
22
+ cacheRead: number;
23
+ cacheWrite: number;
24
+ total: number;
25
+ calls: number;
26
+ notionalUsd: number;
27
+ complete: boolean;
28
+ }>;
29
+ export type CodexHeadlessTurn = Readonly<{
30
+ text: string;
31
+ usage?: CodexTurnUsage;
32
+ }>;
33
+ /**
34
+ * Advisory usage decoding: an absent or malformed block is `undefined`, never
35
+ * a failed published turn and never a zero-filled record. Every field must be
36
+ * a non-negative safe integer because a substituted zero is byte-identical to
37
+ * a real zero. `complete` requires a non-zero derived total and valid subset
38
+ * relationships. As with AGY, every emitted count remains a lower bound.
39
+ */
40
+ export declare const decodeCodexTurnUsage: (frame: JsonRecord, calls: number) => CodexTurnUsage | undefined;
41
+ /**
42
+ * Decode Codex's NDJSON stream without mistaking tool/progress items for the
43
+ * reply. Unknown envelopes and item types are skipped because Codex owns the
44
+ * vocabulary and a future frame must not fail a turn that published.
45
+ * A Codex turn that spent subscription money and produced a reply must reach
46
+ * the organization: uncertainty about accounting degrades to `usage:
47
+ * undefined` and never discards publishable text. Unlike AGY's stricter
48
+ * envelope, Codex may omit, repeat, or follow `turn.completed` with another
49
+ * frame, so only exactly one completion frame supplies trustworthy usage.
50
+ *
51
+ * Success is decided from the terminal frame, not from whether a reply was
52
+ * published: `engineDispatcher.ts`'s runtime envelope tells every agent its
53
+ * terminal response is a private note to the runtime, not an outward
54
+ * message, and that it may "leave it empty". A `turn.completed` with no
55
+ * `agent_message` is therefore a sanctioned silent success — `text: ""`,
56
+ * never a thrown failure — and its usage still reaches the ledger exactly as
57
+ * a spoken turn's would; do not reinstate throwing on empty text, it would
58
+ * both misreport a clean turn as failed and drop its usage from the ledger
59
+ * silently. Only `turn.failed` with no reply already published, or a stream
60
+ * with neither terminal frame at all (a truncated or killed child), reject
61
+ * the turn; the latter gets its own detail string so a genuinely truncated
62
+ * stream is never confused with a legitimately silent one.
63
+ */
64
+ export declare const decodeCodexHeadlessTurn: (output: string) => CodexHeadlessTurn;
65
+ /** Text-only view of {@link decodeCodexHeadlessTurn}, for callers that do not meter. */
66
+ export declare const decodeCodexHeadlessResult: (output: string) => string;
67
+ export {};
68
+ //# sourceMappingURL=codexHeadlessResult.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codexHeadlessResult.d.ts","sourceRoot":"","sources":["../../src/pi/codexHeadlessResult.ts"],"names":[],"mappings":"AAAA,KAAK,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAQpD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,cAAc,GAAG,QAAQ,CAAC;IACpC,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,iBAAiB,GAAG,QAAQ,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,cAAc,CAAA;CAAE,CAAC,CAAC;AA0BnF;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,GAAI,OAAO,UAAU,EAAE,OAAO,MAAM,KAAG,cAAc,GAAG,SAmBxF,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,uBAAuB,GAAI,QAAQ,MAAM,KAAG,iBAiCxD,CAAC;AAEF,wFAAwF;AACxF,eAAO,MAAM,yBAAyB,GAAI,QAAQ,MAAM,KAAG,MAA8C,CAAC"}