@noopolis/daimon 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (422) hide show
  1. package/README.md +275 -51
  2. package/dist/contracts/attentionContract.d.ts +142 -0
  3. package/dist/contracts/attentionContract.d.ts.map +1 -0
  4. package/dist/contracts/attentionContract.js +21 -0
  5. package/dist/contracts/canonicalJson.d.ts +3 -0
  6. package/dist/contracts/canonicalJson.d.ts.map +1 -0
  7. package/dist/contracts/canonicalJson.js +54 -0
  8. package/dist/contracts/grokBrokerTaskClock.d.ts +18 -0
  9. package/dist/contracts/grokBrokerTaskClock.d.ts.map +1 -0
  10. package/dist/contracts/grokBrokerTaskClock.js +16 -0
  11. package/dist/contracts/grokWorkerContract.d.ts +74 -0
  12. package/dist/contracts/grokWorkerContract.d.ts.map +1 -0
  13. package/dist/contracts/grokWorkerContract.js +88 -0
  14. package/dist/contracts/organizationRuntimeContract.d.ts +841 -0
  15. package/dist/contracts/organizationRuntimeContract.d.ts.map +1 -0
  16. package/dist/contracts/organizationRuntimeContract.js +123 -0
  17. package/dist/contracts/runtimeContractManifest.d.ts +1822 -0
  18. package/dist/contracts/runtimeContractManifest.d.ts.map +1 -0
  19. package/dist/contracts/runtimeContractManifest.js +206 -0
  20. package/dist/contracts/shellEnvironmentPolicy.d.ts +3 -0
  21. package/dist/contracts/shellEnvironmentPolicy.d.ts.map +1 -0
  22. package/dist/contracts/shellEnvironmentPolicy.js +5 -0
  23. package/dist/contracts/wakeMomentContract.d.ts +61 -0
  24. package/dist/contracts/wakeMomentContract.d.ts.map +1 -0
  25. package/dist/contracts/wakeMomentContract.js +27 -0
  26. package/dist/core/credentialRedaction.d.ts +4 -0
  27. package/dist/core/credentialRedaction.d.ts.map +1 -0
  28. package/dist/core/credentialRedaction.js +28 -0
  29. package/dist/core/types.d.ts +2 -0
  30. package/dist/core/types.d.ts.map +1 -1
  31. package/dist/examples/jungianPlayAgent.d.ts +1 -0
  32. package/dist/examples/jungianPlayAgent.d.ts.map +1 -1
  33. package/dist/examples/jungianPlayAgent.js +6 -2
  34. package/dist/mcp/toolServer.d.ts +19 -2
  35. package/dist/mcp/toolServer.d.ts.map +1 -1
  36. package/dist/mcp/toolServer.js +57 -17
  37. package/dist/observability/causalEvents.d.ts +6 -6
  38. package/dist/observability/causalEvents.d.ts.map +1 -1
  39. package/dist/observability/causalEvents.js +107 -19
  40. package/dist/observability/orgObserver.d.ts.map +1 -1
  41. package/dist/observability/orgObserver.js +3 -3
  42. package/dist/pi/agyHeadlessResult.d.ts +60 -0
  43. package/dist/pi/agyHeadlessResult.d.ts.map +1 -0
  44. package/dist/pi/agyHeadlessResult.js +95 -0
  45. package/dist/pi/cliChildOutput.d.ts +67 -0
  46. package/dist/pi/cliChildOutput.d.ts.map +1 -0
  47. package/dist/pi/cliChildOutput.js +269 -0
  48. package/dist/pi/cliEngineRun.d.ts +16 -0
  49. package/dist/pi/cliEngineRun.d.ts.map +1 -0
  50. package/dist/pi/cliEngineRun.js +27 -0
  51. package/dist/pi/cliEngineSpawn.d.ts +55 -0
  52. package/dist/pi/cliEngineSpawn.d.ts.map +1 -0
  53. package/dist/pi/cliEngineSpawn.js +169 -0
  54. package/dist/pi/cliEnvironment.d.ts +12 -0
  55. package/dist/pi/cliEnvironment.d.ts.map +1 -0
  56. package/dist/pi/cliEnvironment.js +34 -0
  57. package/dist/pi/cliMcpRegistration.d.ts +61 -0
  58. package/dist/pi/cliMcpRegistration.d.ts.map +1 -0
  59. package/dist/pi/cliMcpRegistration.js +75 -0
  60. package/dist/pi/cliProcess.d.ts +7 -0
  61. package/dist/pi/cliProcess.d.ts.map +1 -0
  62. package/dist/pi/cliProcess.js +132 -0
  63. package/dist/pi/cliSession.d.ts +86 -24
  64. package/dist/pi/cliSession.d.ts.map +1 -1
  65. package/dist/pi/cliSession.js +251 -173
  66. package/dist/pi/cliSessionMcp.d.ts +9 -0
  67. package/dist/pi/cliSessionMcp.d.ts.map +1 -0
  68. package/dist/pi/cliSessionMcp.js +80 -0
  69. package/dist/pi/cliTurnMetering.d.ts +60 -0
  70. package/dist/pi/cliTurnMetering.d.ts.map +1 -0
  71. package/dist/pi/cliTurnMetering.js +60 -0
  72. package/dist/pi/codexFilesystemRules.d.ts +3 -0
  73. package/dist/pi/codexFilesystemRules.d.ts.map +1 -0
  74. package/dist/pi/codexFilesystemRules.js +28 -0
  75. package/dist/pi/codexHeadlessResult.d.ts +68 -0
  76. package/dist/pi/codexHeadlessResult.d.ts.map +1 -0
  77. package/dist/pi/codexHeadlessResult.js +122 -0
  78. package/dist/pi/codexRolloutUsage.d.ts +95 -0
  79. package/dist/pi/codexRolloutUsage.d.ts.map +1 -0
  80. package/dist/pi/codexRolloutUsage.js +221 -0
  81. package/dist/pi/engineTaskClock.d.ts +9 -0
  82. package/dist/pi/engineTaskClock.d.ts.map +1 -0
  83. package/dist/pi/engineTaskClock.js +28 -0
  84. package/dist/pi/engineWakeLimits.d.ts +39 -0
  85. package/dist/pi/engineWakeLimits.d.ts.map +1 -0
  86. package/dist/pi/engineWakeLimits.js +55 -0
  87. package/dist/pi/grokHeadlessResult.d.ts +36 -0
  88. package/dist/pi/grokHeadlessResult.d.ts.map +1 -0
  89. package/dist/pi/grokHeadlessResult.js +118 -0
  90. package/dist/pi/grokHomeMcpRegistration.d.ts +21 -0
  91. package/dist/pi/grokHomeMcpRegistration.d.ts.map +1 -0
  92. package/dist/pi/grokHomeMcpRegistration.js +58 -0
  93. package/dist/pi/grokSandbox.d.ts +11 -0
  94. package/dist/pi/grokSandbox.d.ts.map +1 -0
  95. package/dist/pi/grokSandbox.js +216 -0
  96. package/dist/pi/grokStreamUsage.d.ts +31 -0
  97. package/dist/pi/grokStreamUsage.d.ts.map +1 -0
  98. package/dist/pi/grokStreamUsage.js +51 -0
  99. package/dist/pi/memoryClock.d.ts +25 -0
  100. package/dist/pi/memoryClock.d.ts.map +1 -0
  101. package/dist/pi/memoryClock.js +18 -0
  102. package/dist/pi/piAgentHandle.d.ts +6 -3
  103. package/dist/pi/piAgentHandle.d.ts.map +1 -1
  104. package/dist/pi/piAgentHandle.js +42 -12
  105. package/dist/pi/piAgentWakeSupport.d.ts +35 -0
  106. package/dist/pi/piAgentWakeSupport.d.ts.map +1 -1
  107. package/dist/pi/piAgentWakeSupport.js +4 -0
  108. package/dist/pi/piHarness.d.ts +18 -3
  109. package/dist/pi/piHarness.d.ts.map +1 -1
  110. package/dist/pi/piHarness.js +83 -14
  111. package/dist/pi/prompts.d.ts +1 -0
  112. package/dist/pi/prompts.d.ts.map +1 -1
  113. package/dist/pi/prompts.js +24 -0
  114. package/dist/pi/taskClockProcess.d.ts +6 -0
  115. package/dist/pi/taskClockProcess.d.ts.map +1 -0
  116. package/dist/pi/taskClockProcess.js +8 -0
  117. package/dist/pi/turnCausal.d.ts +4 -2
  118. package/dist/pi/turnCausal.d.ts.map +1 -1
  119. package/dist/pi/turnCausal.js +4 -4
  120. package/dist/pi/turnTrace.d.ts.map +1 -1
  121. package/dist/pi/turnTrace.js +5 -8
  122. package/dist/pi/wakeAcceptance.d.ts +1 -1
  123. package/dist/pi/wakeAcceptance.d.ts.map +1 -1
  124. package/dist/pi/wakeAcceptance.js +2 -2
  125. package/dist/pi/worldTrajectory.d.ts +1 -1
  126. package/dist/pi/worldTrajectory.d.ts.map +1 -1
  127. package/dist/pi/worldTrajectory.js +3 -3
  128. package/dist/runtime/agySubscriptionBootstrap.d.ts +16 -0
  129. package/dist/runtime/agySubscriptionBootstrap.d.ts.map +1 -0
  130. package/dist/runtime/agySubscriptionBootstrap.js +80 -0
  131. package/dist/runtime/agySubscriptionRealm.d.ts +38 -0
  132. package/dist/runtime/agySubscriptionRealm.d.ts.map +1 -0
  133. package/dist/runtime/agySubscriptionRealm.js +242 -0
  134. package/dist/runtime/attention.d.ts +26 -0
  135. package/dist/runtime/attention.d.ts.map +1 -0
  136. package/dist/runtime/attention.js +49 -0
  137. package/dist/runtime/attentionDispatcher.d.ts +78 -0
  138. package/dist/runtime/attentionDispatcher.d.ts.map +1 -0
  139. package/dist/runtime/attentionDispatcher.js +365 -0
  140. package/dist/runtime/cli.d.ts +7 -0
  141. package/dist/runtime/cli.d.ts.map +1 -0
  142. package/dist/runtime/cli.js +256 -0
  143. package/dist/runtime/codexSandboxProjection.d.ts +17 -0
  144. package/dist/runtime/codexSandboxProjection.d.ts.map +1 -0
  145. package/dist/runtime/codexSandboxProjection.js +40 -0
  146. package/dist/runtime/contract-manifest.json +1 -0
  147. package/dist/runtime/contract-manifest.sha256 +1 -0
  148. package/dist/runtime/contractManifest.d.ts +8 -0
  149. package/dist/runtime/contractManifest.d.ts.map +1 -0
  150. package/dist/runtime/contractManifest.js +4 -0
  151. package/dist/runtime/engineBrokerCapabilities.d.ts +40 -0
  152. package/dist/runtime/engineBrokerCapabilities.d.ts.map +1 -0
  153. package/dist/runtime/engineBrokerCapabilities.js +69 -0
  154. package/dist/runtime/engineBrokerControlClient.d.ts +55 -0
  155. package/dist/runtime/engineBrokerControlClient.d.ts.map +1 -0
  156. package/dist/runtime/engineBrokerControlClient.js +228 -0
  157. package/dist/runtime/engineBrokerCredentialJournal.d.ts +12 -0
  158. package/dist/runtime/engineBrokerCredentialJournal.d.ts.map +1 -0
  159. package/dist/runtime/engineBrokerCredentialJournal.js +26 -0
  160. package/dist/runtime/engineBrokerInferenceProtocol.d.ts +53 -0
  161. package/dist/runtime/engineBrokerInferenceProtocol.d.ts.map +1 -0
  162. package/dist/runtime/engineBrokerInferenceProtocol.js +65 -0
  163. package/dist/runtime/engineBrokerMcpCallLog.d.ts +171 -0
  164. package/dist/runtime/engineBrokerMcpCallLog.d.ts.map +1 -0
  165. package/dist/runtime/engineBrokerMcpCallLog.js +231 -0
  166. package/dist/runtime/engineBrokerMcpFacade.d.ts +59 -0
  167. package/dist/runtime/engineBrokerMcpFacade.d.ts.map +1 -0
  168. package/dist/runtime/engineBrokerMcpFacade.js +346 -0
  169. package/dist/runtime/engineBrokerNativeClient.d.ts +52 -0
  170. package/dist/runtime/engineBrokerNativeClient.d.ts.map +1 -0
  171. package/dist/runtime/engineBrokerNativeClient.js +151 -0
  172. package/dist/runtime/engineBrokerProtocol.d.ts +167 -0
  173. package/dist/runtime/engineBrokerProtocol.d.ts.map +1 -0
  174. package/dist/runtime/engineBrokerProtocol.js +357 -0
  175. package/dist/runtime/engineBrokerSealLedger.d.ts +70 -0
  176. package/dist/runtime/engineBrokerSealLedger.d.ts.map +1 -0
  177. package/dist/runtime/engineBrokerSealLedger.js +132 -0
  178. package/dist/runtime/engineBrokerService.d.ts +43 -0
  179. package/dist/runtime/engineBrokerService.d.ts.map +1 -0
  180. package/dist/runtime/engineBrokerService.js +196 -0
  181. package/dist/runtime/engineBrokerServiceCli.d.ts +5 -0
  182. package/dist/runtime/engineBrokerServiceCli.d.ts.map +1 -0
  183. package/dist/runtime/engineBrokerServiceCli.js +32 -0
  184. package/dist/runtime/engineBrokerServiceConfig.d.ts +55 -0
  185. package/dist/runtime/engineBrokerServiceConfig.d.ts.map +1 -0
  186. package/dist/runtime/engineBrokerServiceConfig.js +130 -0
  187. package/dist/runtime/engineBrokerSingleflight.d.ts +13 -0
  188. package/dist/runtime/engineBrokerSingleflight.d.ts.map +1 -0
  189. package/dist/runtime/engineBrokerSingleflight.js +24 -0
  190. package/dist/runtime/engineBrokerTurnAccounting.d.ts +76 -0
  191. package/dist/runtime/engineBrokerTurnAccounting.d.ts.map +1 -0
  192. package/dist/runtime/engineBrokerTurnAccounting.js +108 -0
  193. package/dist/runtime/engineBrokerTurnRegistry.d.ts +57 -0
  194. package/dist/runtime/engineBrokerTurnRegistry.d.ts.map +1 -0
  195. package/dist/runtime/engineBrokerTurnRegistry.js +159 -0
  196. package/dist/runtime/engineDispatcher.d.ts +38 -0
  197. package/dist/runtime/engineDispatcher.d.ts.map +1 -0
  198. package/dist/runtime/engineDispatcher.js +228 -0
  199. package/dist/runtime/engineReadiness.d.ts +23 -0
  200. package/dist/runtime/engineReadiness.d.ts.map +1 -0
  201. package/dist/runtime/engineReadiness.js +222 -0
  202. package/dist/runtime/grokAuthenticationError.d.ts +8 -0
  203. package/dist/runtime/grokAuthenticationError.d.ts.map +1 -0
  204. package/dist/runtime/grokAuthenticationError.js +20 -0
  205. package/dist/runtime/grokBrokerCredentialAuthority.d.ts +23 -0
  206. package/dist/runtime/grokBrokerCredentialAuthority.d.ts.map +1 -0
  207. package/dist/runtime/grokBrokerCredentialAuthority.js +150 -0
  208. package/dist/runtime/grokBrokerCredentialReader.d.ts +6 -0
  209. package/dist/runtime/grokBrokerCredentialReader.d.ts.map +1 -0
  210. package/dist/runtime/grokBrokerCredentialReader.js +38 -0
  211. package/dist/runtime/grokBrokerModelPolicy.d.ts +23 -0
  212. package/dist/runtime/grokBrokerModelPolicy.d.ts.map +1 -0
  213. package/dist/runtime/grokBrokerModelPolicy.js +28 -0
  214. package/dist/runtime/grokBrokerProjection.d.ts +114 -0
  215. package/dist/runtime/grokBrokerProjection.d.ts.map +1 -0
  216. package/dist/runtime/grokBrokerProjection.js +101 -0
  217. package/dist/runtime/grokBrokerProviderClock.d.ts +26 -0
  218. package/dist/runtime/grokBrokerProviderClock.d.ts.map +1 -0
  219. package/dist/runtime/grokBrokerProviderClock.js +133 -0
  220. package/dist/runtime/grokBrokerProxy.d.ts +69 -0
  221. package/dist/runtime/grokBrokerProxy.d.ts.map +1 -0
  222. package/dist/runtime/grokBrokerProxy.js +326 -0
  223. package/dist/runtime/grokBrokerProxyJson.d.ts +10 -0
  224. package/dist/runtime/grokBrokerProxyJson.d.ts.map +1 -0
  225. package/dist/runtime/grokBrokerProxyJson.js +31 -0
  226. package/dist/runtime/grokBrokerProxyRequest.d.ts +30 -0
  227. package/dist/runtime/grokBrokerProxyRequest.d.ts.map +1 -0
  228. package/dist/runtime/grokBrokerProxyRequest.js +85 -0
  229. package/dist/runtime/grokBrokerRealmLease.d.ts +4 -0
  230. package/dist/runtime/grokBrokerRealmLease.d.ts.map +1 -0
  231. package/dist/runtime/grokBrokerRealmLease.js +33 -0
  232. package/dist/runtime/grokBrokerRefresh.d.ts +2 -0
  233. package/dist/runtime/grokBrokerRefresh.d.ts.map +1 -0
  234. package/dist/runtime/grokBrokerRefresh.js +15 -0
  235. package/dist/runtime/grokBrokerRunBudget.d.ts +20 -0
  236. package/dist/runtime/grokBrokerRunBudget.d.ts.map +1 -0
  237. package/dist/runtime/grokBrokerRunBudget.js +85 -0
  238. package/dist/runtime/grokBrokerSlot.d.ts +6 -0
  239. package/dist/runtime/grokBrokerSlot.d.ts.map +1 -0
  240. package/dist/runtime/grokBrokerSlot.js +21 -0
  241. package/dist/runtime/grokBrokerTaskClock.d.ts +32 -0
  242. package/dist/runtime/grokBrokerTaskClock.d.ts.map +1 -0
  243. package/dist/runtime/grokBrokerTaskClock.js +120 -0
  244. package/dist/runtime/grokBrokerTurnMeter.d.ts +180 -0
  245. package/dist/runtime/grokBrokerTurnMeter.d.ts.map +1 -0
  246. package/dist/runtime/grokBrokerTurnMeter.js +337 -0
  247. package/dist/runtime/grokBrokerWorkerConfig.d.ts +89 -0
  248. package/dist/runtime/grokBrokerWorkerConfig.d.ts.map +1 -0
  249. package/dist/runtime/grokBrokerWorkerConfig.js +154 -0
  250. package/dist/runtime/grokEngineBroker.d.ts +88 -0
  251. package/dist/runtime/grokEngineBroker.d.ts.map +1 -0
  252. package/dist/runtime/grokEngineBroker.js +202 -0
  253. package/dist/runtime/grokEngineBrokerLedger.d.ts +52 -0
  254. package/dist/runtime/grokEngineBrokerLedger.d.ts.map +1 -0
  255. package/dist/runtime/grokEngineBrokerLedger.js +114 -0
  256. package/dist/runtime/grokEngineBrokerMetering.d.ts +51 -0
  257. package/dist/runtime/grokEngineBrokerMetering.d.ts.map +1 -0
  258. package/dist/runtime/grokEngineBrokerMetering.js +34 -0
  259. package/dist/runtime/grokEngineBrokerTurn.d.ts +82 -0
  260. package/dist/runtime/grokEngineBrokerTurn.d.ts.map +1 -0
  261. package/dist/runtime/grokEngineBrokerTurn.js +348 -0
  262. package/dist/runtime/grokEngineBrokerTurnEnd.d.ts +88 -0
  263. package/dist/runtime/grokEngineBrokerTurnEnd.d.ts.map +1 -0
  264. package/dist/runtime/grokEngineBrokerTurnEnd.js +148 -0
  265. package/dist/runtime/grokInferenceClientConfig.d.ts +41 -0
  266. package/dist/runtime/grokInferenceClientConfig.d.ts.map +1 -0
  267. package/dist/runtime/grokInferenceClientConfig.js +62 -0
  268. package/dist/runtime/grokInferenceGrants.d.ts +77 -0
  269. package/dist/runtime/grokInferenceGrants.d.ts.map +1 -0
  270. package/dist/runtime/grokInferenceGrants.js +116 -0
  271. package/dist/runtime/grokInferenceProxy.d.ts +29 -0
  272. package/dist/runtime/grokInferenceProxy.d.ts.map +1 -0
  273. package/dist/runtime/grokInferenceProxy.js +85 -0
  274. package/dist/runtime/grokInferenceProxyRequest.d.ts +23 -0
  275. package/dist/runtime/grokInferenceProxyRequest.d.ts.map +1 -0
  276. package/dist/runtime/grokInferenceProxyRequest.js +63 -0
  277. package/dist/runtime/grokSlotPreflightReceipt.d.ts +70 -0
  278. package/dist/runtime/grokSlotPreflightReceipt.d.ts.map +1 -0
  279. package/dist/runtime/grokSlotPreflightReceipt.js +101 -0
  280. package/dist/runtime/grokSubscriptionRealm.d.ts +4 -0
  281. package/dist/runtime/grokSubscriptionRealm.d.ts.map +1 -0
  282. package/dist/runtime/grokSubscriptionRealm.js +435 -0
  283. package/dist/runtime/grokSubscriptionRealmTypes.d.ts +26 -0
  284. package/dist/runtime/grokSubscriptionRealmTypes.d.ts.map +1 -0
  285. package/dist/runtime/grokSubscriptionRealmTypes.js +1 -0
  286. package/dist/runtime/grokWorkerAttestation.d.ts +175 -0
  287. package/dist/runtime/grokWorkerAttestation.d.ts.map +1 -0
  288. package/dist/runtime/grokWorkerAttestation.js +266 -0
  289. package/dist/runtime/grokWorkerDenyPlacement.d.ts +80 -0
  290. package/dist/runtime/grokWorkerDenyPlacement.d.ts.map +1 -0
  291. package/dist/runtime/grokWorkerDenyPlacement.js +128 -0
  292. package/dist/runtime/grokWorkerHomeAttestation.d.ts +32 -0
  293. package/dist/runtime/grokWorkerHomeAttestation.d.ts.map +1 -0
  294. package/dist/runtime/grokWorkerHomeAttestation.js +75 -0
  295. package/dist/runtime/grokWorkerSandboxProfile.d.ts +27 -0
  296. package/dist/runtime/grokWorkerSandboxProfile.d.ts.map +1 -0
  297. package/dist/runtime/grokWorkerSandboxProfile.js +44 -0
  298. package/dist/runtime/grokWorkerTmpAttestation.d.ts +55 -0
  299. package/dist/runtime/grokWorkerTmpAttestation.d.ts.map +1 -0
  300. package/dist/runtime/grokWorkerTmpAttestation.js +63 -0
  301. package/dist/runtime/index.d.ts +31 -0
  302. package/dist/runtime/index.d.ts.map +1 -0
  303. package/dist/runtime/index.js +27 -0
  304. package/dist/runtime/inferenceUsageLedger.d.ts +38 -0
  305. package/dist/runtime/inferenceUsageLedger.d.ts.map +1 -0
  306. package/dist/runtime/inferenceUsageLedger.js +53 -0
  307. package/dist/runtime/mcpToolResult.d.ts +127 -0
  308. package/dist/runtime/mcpToolResult.d.ts.map +1 -0
  309. package/dist/runtime/mcpToolResult.js +214 -0
  310. package/dist/runtime/moltnetMachineRead.d.ts +97 -0
  311. package/dist/runtime/moltnetMachineRead.d.ts.map +1 -0
  312. package/dist/runtime/moltnetMachineRead.js +183 -0
  313. package/dist/runtime/native/daimon-engine-broker +0 -0
  314. package/dist/runtime/organizationRuntime.d.ts +168 -0
  315. package/dist/runtime/organizationRuntime.d.ts.map +1 -0
  316. package/dist/runtime/organizationRuntime.js +3 -0
  317. package/dist/runtime/organizationRuntimeAdmission.d.ts +6 -0
  318. package/dist/runtime/organizationRuntimeAdmission.d.ts.map +1 -0
  319. package/dist/runtime/organizationRuntimeAdmission.js +22 -0
  320. package/dist/runtime/organizationRuntimeControl.d.ts +51 -0
  321. package/dist/runtime/organizationRuntimeControl.d.ts.map +1 -0
  322. package/dist/runtime/organizationRuntimeControl.js +283 -0
  323. package/dist/runtime/organizationRuntimeHost.d.ts +19 -0
  324. package/dist/runtime/organizationRuntimeHost.d.ts.map +1 -0
  325. package/dist/runtime/organizationRuntimeHost.js +368 -0
  326. package/dist/runtime/organizationRuntimeParsing.d.ts +6 -0
  327. package/dist/runtime/organizationRuntimeParsing.d.ts.map +1 -0
  328. package/dist/runtime/organizationRuntimeParsing.js +373 -0
  329. package/dist/runtime/organizationRuntimeReadiness.d.ts +12 -0
  330. package/dist/runtime/organizationRuntimeReadiness.d.ts.map +1 -0
  331. package/dist/runtime/organizationRuntimeReadiness.js +67 -0
  332. package/dist/runtime/organizationRuntimeRecording.d.ts +7 -0
  333. package/dist/runtime/organizationRuntimeRecording.d.ts.map +1 -0
  334. package/dist/runtime/organizationRuntimeRecording.js +58 -0
  335. package/dist/runtime/physicalReadiness.d.ts +59 -0
  336. package/dist/runtime/physicalReadiness.d.ts.map +1 -0
  337. package/dist/runtime/physicalReadiness.js +176 -0
  338. package/dist/runtime/portableCredentialAuth.d.ts +6 -0
  339. package/dist/runtime/portableCredentialAuth.d.ts.map +1 -0
  340. package/dist/runtime/portableCredentialAuth.js +70 -0
  341. package/dist/runtime/portableCredentialMaterial.d.ts +8 -0
  342. package/dist/runtime/portableCredentialMaterial.d.ts.map +1 -0
  343. package/dist/runtime/portableCredentialMaterial.js +169 -0
  344. package/dist/runtime/productionAgentTools.d.ts +5 -0
  345. package/dist/runtime/productionAgentTools.d.ts.map +1 -0
  346. package/dist/runtime/productionAgentTools.js +336 -0
  347. package/dist/runtime/relocateRuntimeConfig.d.ts +14 -0
  348. package/dist/runtime/relocateRuntimeConfig.d.ts.map +1 -0
  349. package/dist/runtime/relocateRuntimeConfig.js +38 -0
  350. package/dist/runtime/runtimeHomeLayout.d.ts +48 -0
  351. package/dist/runtime/runtimeHomeLayout.d.ts.map +1 -0
  352. package/dist/runtime/runtimeHomeLayout.js +84 -0
  353. package/dist/runtime/schedule.d.ts +40 -0
  354. package/dist/runtime/schedule.d.ts.map +1 -0
  355. package/dist/runtime/schedule.js +376 -0
  356. package/dist/runtime/storeCoordination.d.ts +33 -0
  357. package/dist/runtime/storeCoordination.d.ts.map +1 -0
  358. package/dist/runtime/storeCoordination.js +117 -0
  359. package/dist/runtime/taskClock.d.ts +42 -0
  360. package/dist/runtime/taskClock.d.ts.map +1 -0
  361. package/dist/runtime/taskClock.js +102 -0
  362. package/dist/runtime/taskClockProcess.d.ts +17 -0
  363. package/dist/runtime/taskClockProcess.d.ts.map +1 -0
  364. package/dist/runtime/taskClockProcess.js +58 -0
  365. package/dist/runtime/toolResultSpill.d.ts +152 -0
  366. package/dist/runtime/toolResultSpill.d.ts.map +1 -0
  367. package/dist/runtime/toolResultSpill.js +351 -0
  368. package/dist/runtime/turnRequestLedger.d.ts +155 -0
  369. package/dist/runtime/turnRequestLedger.d.ts.map +1 -0
  370. package/dist/runtime/turnRequestLedger.js +251 -0
  371. package/dist/runtime/turnUsageLedger.d.ts +143 -0
  372. package/dist/runtime/turnUsageLedger.d.ts.map +1 -0
  373. package/dist/runtime/turnUsageLedger.js +203 -0
  374. package/dist/runtime/wakeAcceptanceClaimDiagnostics.d.ts +34 -0
  375. package/dist/runtime/wakeAcceptanceClaimDiagnostics.d.ts.map +1 -0
  376. package/dist/runtime/wakeAcceptanceClaimDiagnostics.js +79 -0
  377. package/dist/runtime/wakeAcceptanceIndex.d.ts +55 -0
  378. package/dist/runtime/wakeAcceptanceIndex.d.ts.map +1 -0
  379. package/dist/runtime/wakeAcceptanceIndex.js +158 -0
  380. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts +25 -0
  381. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts.map +1 -0
  382. package/dist/runtime/wakeAcceptanceProcessIdentity.js +54 -0
  383. package/dist/runtime/wakeAcceptanceReconciliation.d.ts +211 -0
  384. package/dist/runtime/wakeAcceptanceReconciliation.d.ts.map +1 -0
  385. package/dist/runtime/wakeAcceptanceReconciliation.js +289 -0
  386. package/dist/runtime/wakeAcceptanceRecord.d.ts +25 -0
  387. package/dist/runtime/wakeAcceptanceRecord.d.ts.map +1 -0
  388. package/dist/runtime/wakeAcceptanceRecord.js +58 -0
  389. package/dist/runtime/wakeAcceptanceRetention.d.ts +36 -0
  390. package/dist/runtime/wakeAcceptanceRetention.d.ts.map +1 -0
  391. package/dist/runtime/wakeAcceptanceRetention.js +38 -0
  392. package/dist/runtime/wakeAcceptanceStore.d.ts +113 -0
  393. package/dist/runtime/wakeAcceptanceStore.d.ts.map +1 -0
  394. package/dist/runtime/wakeAcceptanceStore.js +561 -0
  395. package/dist/runtime/wakeAcceptanceTypes.d.ts +179 -0
  396. package/dist/runtime/wakeAcceptanceTypes.d.ts.map +1 -0
  397. package/dist/runtime/wakeAcceptanceTypes.js +95 -0
  398. package/dist/runtime/wakeFuse.d.ts +124 -0
  399. package/dist/runtime/wakeFuse.d.ts.map +1 -0
  400. package/dist/runtime/wakeFuse.js +466 -0
  401. package/dist/runtime/wakeMomentFs.d.ts +27 -0
  402. package/dist/runtime/wakeMomentFs.d.ts.map +1 -0
  403. package/dist/runtime/wakeMomentFs.js +223 -0
  404. package/dist/runtime/wakeMomentHistory.d.ts +26 -0
  405. package/dist/runtime/wakeMomentHistory.d.ts.map +1 -0
  406. package/dist/runtime/wakeMomentHistory.js +109 -0
  407. package/dist/runtime/wakeMomentIo.d.ts +22 -0
  408. package/dist/runtime/wakeMomentIo.d.ts.map +1 -0
  409. package/dist/runtime/wakeMomentIo.js +114 -0
  410. package/dist/runtime/wakeMomentRecorder.d.ts +33 -0
  411. package/dist/runtime/wakeMomentRecorder.d.ts.map +1 -0
  412. package/dist/runtime/wakeMomentRecorder.js +81 -0
  413. package/dist/runtime/wakeMomentRetention.d.ts +7 -0
  414. package/dist/runtime/wakeMomentRetention.d.ts.map +1 -0
  415. package/dist/runtime/wakeMomentRetention.js +143 -0
  416. package/dist/runtime/wakeMomentRows.d.ts +8 -0
  417. package/dist/runtime/wakeMomentRows.d.ts.map +1 -0
  418. package/dist/runtime/wakeMomentRows.js +66 -0
  419. package/dist/runtime/wakeMomentSnapshot.d.ts +56 -0
  420. package/dist/runtime/wakeMomentSnapshot.d.ts.map +1 -0
  421. package/dist/runtime/wakeMomentSnapshot.js +248 -0
  422. package/package.json +22 -11
@@ -1,130 +1,71 @@
1
- import { randomUUID } from "node:crypto";
2
- import { createServer } from "node:http";
3
- import { spawn } from "node:child_process";
4
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
- import { createPiToolMcpServer } from "../mcp/toolServer.js";
6
- import { redactTraceText } from "./turnTrace.js";
7
- const childEnvironment = (redactedNames) => {
8
- const redacted = new Set(redactedNames);
9
- return Object.fromEntries(Object.entries(process.env).filter(([name]) => !redacted.has(name)));
1
+ import { startMcp } from "./cliSessionMcp.js";
2
+ import { reportEngineTaskClockGap } from "./engineTaskClock.js";
3
+ import { redactCredentialError, redactCredentialText } from "../core/credentialRedaction.js";
4
+ import { asGrokAuthenticationRejected, classifyGrokAuthenticationDiagnostic, GrokSubscriptionAuthenticationRejectedError } from "../runtime/grokAuthenticationError.js";
5
+ import { readChild } from "./cliChildOutput.js";
6
+ import { cliChildEnvironment } from "./cliEnvironment.js";
7
+ import { spawnEngine } from "./cliEngineSpawn.js";
8
+ import { registerCliMcpServer, renderAgyMcpAddArgs, renderAgyMcpRemoveArgs } from "./cliMcpRegistration.js";
9
+ import { registerGrokHomeMcpServer } from "./grokHomeMcpRegistration.js";
10
+ import { decodeAgyHeadlessTurn } from "./agyHeadlessResult.js";
11
+ import { createCliTurnMeter, decodeCodexTurn, failedTurnOutcome, publishTurnRequests, publishTurnUsage } from "./cliTurnMetering.js";
12
+ import { decodeGrokHeadlessResult } from "./grokHeadlessResult.js";
13
+ import { terminateChild } from "./cliProcess.js";
14
+ import { ensureRuntimeHome, ensureRuntimeHomeDirectory } from "../runtime/runtimeHomeLayout.js";
15
+ /**
16
+ * The per-wake tool-call bound for AGY, and the one place it is decided.
17
+ *
18
+ * Codex and Grok leave this `undefined` — their only bound is the wake
19
+ * deadline. AGY does not get that treatment, for a measured reason: its
20
+ * terminal usage frame is the *sum* over the turn's model steps, and each tool
21
+ * step resends the whole context. The live capture is 13,796 total tokens for a
22
+ * tool-free turn and 45,381 for a turn with a single call against an
23
+ * empty-schema tool — one call roughly triples the wake. An unbounded loop on
24
+ * the one engine whose subscription quota is currently the operator's only
25
+ * working credential is a cost hazard, not a capability.
26
+ *
27
+ * 16 is chosen so a realistic wake is never truncated (read a few declared MCP
28
+ * tools, then send one or two Moltnet messages) while the worst case is bounded
29
+ * at roughly a quarter-million tokens instead of "whatever fits in 180s". The
30
+ * bound degrades gracefully rather than failing the wake: exceeding it returns
31
+ * `McpToolTurnLimitError` to the model as a tool *error*, so the agent can still
32
+ * finish its turn and reply.
33
+ */
34
+ export const AGY_MAX_TOOL_TURNS = 16;
35
+ 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";
36
+ export const prepareCliRuntimeHome = async (runtimeHomePath) => {
37
+ if (runtimeHomePath === undefined)
38
+ return;
39
+ await ensureRuntimeHome(runtimeHomePath);
40
+ await Promise.all([".config", ".local/share", ".local/state", ".cache", ".tmp"]
41
+ .map((relative) => ensureRuntimeHomeDirectory(runtimeHomePath, relative)));
10
42
  };
11
43
  const childSecretValues = (redactedNames) => redactedNames
12
44
  .map((name) => process.env[name])
13
45
  .filter((value) => typeof value === "string" && value.length > 0);
14
- const redactChildOutput = (value, secretValues) => {
15
- let redacted = redactTraceText(value);
16
- for (const secret of secretValues)
17
- redacted = redacted.split(secret).join("[REDACTED]");
18
- return redacted;
19
- };
20
- const childDiagnostic = (stdout, stderr, secretValues) => {
21
- const output = stderr.trim().length > 0 ? stderr : stdout;
22
- const redacted = redactChildOutput(output, secretValues).trim();
23
- return redacted.length > 0 ? `: ${redacted}` : "";
24
- };
25
- const terminate = (child) => {
26
- if (!child.killed)
27
- child.kill("SIGTERM");
28
- };
29
- export const readChild = (child, timeoutMs, secretValues) => new Promise((resolve, reject) => {
30
- const stdout = [];
31
- const stderr = [];
32
- child.stdout?.on("data", (chunk) => stdout.push(chunk));
33
- child.stderr?.on("data", (chunk) => stderr.push(chunk));
34
- const timer = setTimeout(() => {
35
- terminate(child);
36
- reject(new Error("CLI engine timed out"));
37
- }, timeoutMs);
38
- child.once("error", (error) => {
39
- clearTimeout(timer);
40
- reject(error);
41
- });
42
- child.once("close", (code, signal) => {
43
- clearTimeout(timer);
44
- if (code === 0) {
45
- resolve(Buffer.concat(stdout).toString("utf8").trim());
46
- }
47
- else {
48
- reject(new Error(`CLI engine exited ${code ?? signal}${childDiagnostic(Buffer.concat(stdout).toString("utf8"), Buffer.concat(stderr).toString("utf8"), secretValues)}`));
49
- }
50
- });
51
- });
52
- const startMcp = async (tools, maxToolTurns, wakeDeadline, onToolsMounted) => {
53
- onToolsMounted?.(tools);
54
- const mcpServer = createPiToolMcpServer(tools, { maxToolTurns, wakeDeadline });
55
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });
56
- await mcpServer.connect(transport);
57
- const httpServer = createServer((request, response) => {
58
- void transport.handleRequest(request, response);
59
- });
46
+ const captureCleanup = async (current, action) => {
60
47
  try {
61
- await new Promise((resolve, reject) => {
62
- httpServer.once("error", reject);
63
- httpServer.listen(0, "127.0.0.1", () => resolve());
64
- });
48
+ await action();
65
49
  }
66
50
  catch (error) {
67
- await transport.close().catch(() => undefined);
68
- await mcpServer.close().catch(() => undefined);
69
- throw error;
70
- }
71
- const address = httpServer.address();
72
- if (address === null || typeof address === "string") {
73
- await new Promise((resolve) => httpServer.close(() => resolve()));
74
- await transport.close();
75
- await mcpServer.close();
76
- throw new Error("MCP server did not receive an ephemeral port");
77
- }
78
- const close = async () => {
79
- await transport.close().catch(() => undefined);
80
- await mcpServer.close().catch(() => undefined);
81
- await new Promise((resolve) => httpServer.close(() => resolve()));
82
- };
83
- return { endpoint: `http://127.0.0.1:${address.port}/mcp`, close };
84
- };
85
- const addGrokServer = async (endpoint, cwd, env, command, commandArgs, secretValues) => {
86
- const child = spawn(command, [...commandArgs, "mcp", "add", "--transport", "http", "--scope", "project", "daimon", endpoint], {
87
- cwd,
88
- env,
89
- stdio: ["ignore", "pipe", "pipe"]
90
- });
91
- await readChild(child, 30_000, secretValues);
92
- };
93
- export const renderCodexArgs = (options, cwd, endpoint, sandbox = process.env.DAIMON_CODEX_SANDBOX ?? "danger-full-access") => [...(options.commandArgs ?? []), "exec", "--sandbox", sandbox, "--skip-git-repo-check", "--color", "never", "-C", cwd,
94
- "-c", `mcp_servers.daimon.url=${endpoint}`, "-"];
95
- export const spawnEngine = (options, prompt, input, endpoint) => {
96
- const command = options.command ?? options.engine;
97
- const env = childEnvironment([
98
- ...(options.redactedEnvironmentNames ?? []),
99
- ...(input.daimonSecretEnvironmentNames ?? [])
100
- ]);
101
- if (options.engine === "codex") {
102
- const args = renderCodexArgs(options, input.cwd, endpoint);
103
- const child = spawn(command, args, { cwd: input.cwd, env, stdio: ["pipe", "pipe", "pipe"] });
104
- child.stdin.on("error", () => undefined);
105
- child.stdin.write(prompt);
106
- child.stdin.end();
107
- return child;
51
+ return current ?? error;
108
52
  }
109
- if (options.engine === "grok") {
110
- return spawn(command, [...(options.commandArgs ?? []), "--single", prompt, "--max-turns", String(options.maxToolTurns), "--no-memory",
111
- "--disable-web-search", "--cwd", input.cwd, "--output-format", "plain"], {
112
- cwd: input.cwd,
113
- env,
114
- stdio: ["ignore", "pipe", "pipe"]
115
- });
116
- }
117
- return spawn(command, [...(options.commandArgs ?? []), "--print", prompt, "--print-timeout", `${options.timeoutMs}ms`], {
118
- cwd: input.cwd,
119
- env,
120
- stdio: ["ignore", "pipe", "pipe"]
121
- });
53
+ return current;
122
54
  };
55
+ export { terminateChild } from "./cliProcess.js";
56
+ export { CLI_ENGINE_MAX_DIAGNOSTIC_BYTES, CLI_ENGINE_MAX_OUTPUT_BYTES, readChild } from "./cliChildOutput.js";
123
57
  class CliSession {
124
58
  options;
125
59
  input;
126
60
  listeners = new Set();
61
+ setupChildren = new Set();
127
62
  disposed = false;
63
+ activeChild;
64
+ activeMount;
65
+ activeBrokerTurn;
66
+ mcpRegistration;
67
+ disposePromise;
68
+ wakeId;
128
69
  constructor(options, input) {
129
70
  this.options = options;
130
71
  this.input = input;
@@ -133,60 +74,216 @@ class CliSession {
133
74
  this.listeners.add(listener);
134
75
  return () => this.listeners.delete(listener);
135
76
  }
77
+ bindWake(event) {
78
+ this.wakeId = event?.id;
79
+ }
136
80
  async prompt(text) {
137
81
  if (this.disposed)
138
82
  throw new Error("CLI session is disposed");
139
- const deadline = Date.now() + this.options.timeoutMs;
140
- const secretValues = childSecretValues([
83
+ reportEngineTaskClockGap(this.options.engine);
84
+ await prepareCliRuntimeHome(this.input.runtimeHomePath);
85
+ const deadline = this.options.timeoutMs === undefined ? undefined : Date.now() + this.options.timeoutMs;
86
+ const environmentSecretValues = childSecretValues([
141
87
  ...(this.options.redactedEnvironmentNames ?? []),
142
88
  ...(this.input.daimonSecretEnvironmentNames ?? [])
143
89
  ]);
144
- const needsMcp = this.options.engine !== "agy";
145
- const mount = needsMcp
146
- ? await startMcp(this.input.customTools ?? [], this.options.maxToolTurns, deadline, this.options.onToolsMounted)
147
- : undefined;
90
+ const stagedCredentialSecrets = await this.options.credentialSecretValues?.() ?? [];
91
+ const secretValues = [...environmentSecretValues, ...stagedCredentialSecrets];
92
+ let mount;
93
+ let registration;
94
+ let turnUsage;
95
+ // Kept beside the decoded turn so a wake that never reaches its decoder
96
+ // still owes the ledger the usage Codex already reported (`cliTurnMetering.ts`).
97
+ const meter = createCliTurnMeter();
98
+ // Codex's own `thread.started` frame, carried out of the stream so the
99
+ // wake's rollout can be found by identity rather than by recency.
100
+ let codexThreadId;
101
+ let instrumented = false;
102
+ const instrument = async () => {
103
+ if (instrumented)
104
+ return;
105
+ instrumented = true;
106
+ await publishTurnRequests(this.options.onCodexTurnRequests, codexThreadId);
107
+ };
148
108
  let child;
109
+ let output;
110
+ let cleanupFailure;
111
+ let promptFailure;
149
112
  try {
150
- if (this.options.engine === "grok" && mount !== undefined) {
151
- await addGrokServer(mount.endpoint, this.input.cwd, childEnvironment([
152
- ...(this.options.redactedEnvironmentNames ?? []),
153
- ...(this.input.daimonSecretEnvironmentNames ?? [])
154
- ]), this.options.command ?? "grok", this.options.commandArgs ?? [], secretValues);
113
+ // Every CLI engine mounts the same tool surface. AGY used to be the one
114
+ // exception (`toolAccess: "none"`), which is exactly what made an AGY
115
+ // agent unable to reach Moltnet or a declared MCP server, and so unable
116
+ // to take part in an organization at all.
117
+ mount = await startMcp(this.input.customTools ?? [], this.options.maxToolTurns, deadline, this.options.onToolsMounted, (started) => {
118
+ this.activeMount = started;
119
+ if (this.disposed)
120
+ void started.close();
121
+ });
122
+ this.ensureLive();
123
+ if (this.options.engine === "grok" && this.options.grokBrokerTurn !== undefined && mount !== undefined) {
124
+ const controller = new AbortController();
125
+ this.activeBrokerTurn = controller;
126
+ try {
127
+ output = await this.options.grokBrokerTurn(`${this.options.identityPrompt ?? ""}${text}`, mount.endpoint, controller.signal);
128
+ }
129
+ finally {
130
+ if (this.activeBrokerTurn === controller)
131
+ this.activeBrokerTurn = undefined;
132
+ }
155
133
  }
156
- child = spawnEngine(this.options, text, this.input, mount?.endpoint);
157
- const output = await readChild(child, Math.max(1, deadline - Date.now()), secretValues);
158
- for (const listener of this.listeners)
159
- listener({
160
- type: "turn_end",
161
- message: {
162
- role: "assistant",
163
- content: [{ type: "text", text: output }],
164
- api: "openai-completions",
165
- provider: "openai",
166
- model: "cli",
167
- usage: {
168
- input: 0,
169
- output: 0,
170
- cacheRead: 0,
171
- cacheWrite: 0,
172
- totalTokens: 0,
173
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
174
- },
175
- stopReason: "stop",
176
- timestamp: Date.now()
177
- },
178
- toolResults: []
134
+ else {
135
+ if (this.options.engine === "grok" && mount !== undefined) {
136
+ await this.options.verifyExecutable?.();
137
+ registration = await registerGrokHomeMcpServer({
138
+ engineHomePath: this.options.engineHomePath,
139
+ endpoint: mount.endpoint,
140
+ ...(this.options.verifyGrokSandbox !== undefined ? { verify: this.options.verifyGrokSandbox } : {})
141
+ });
142
+ this.mcpRegistration = registration;
143
+ }
144
+ else if (this.options.engine === "agy" && mount !== undefined) {
145
+ await this.options.verifyExecutable?.();
146
+ registration = await registerCliMcpServer({
147
+ addArgs: renderAgyMcpAddArgs(this.options.commandArgs, mount.endpoint),
148
+ removeArgs: renderAgyMcpRemoveArgs(this.options.commandArgs),
149
+ command: this.options.command ?? this.options.engine,
150
+ cwd: this.input.cwd,
151
+ env: cliChildEnvironment([
152
+ ...(this.options.redactedEnvironmentNames ?? []),
153
+ ...(this.input.daimonSecretEnvironmentNames ?? [])
154
+ ], this.input.runtimeHomePath, {
155
+ ...(this.options.dbusSessionBusAddress !== undefined ? { dbusSessionBusAddress: this.options.dbusSessionBusAddress } : {}),
156
+ engine: this.options.engine,
157
+ executablePath: this.options.command,
158
+ engineHomePath: this.options.engineHomePath
159
+ }),
160
+ onChild: (setupChild) => { this.setupChildren.add(setupChild); },
161
+ onChildSettled: (setupChild) => this.setupChildren.delete(setupChild),
162
+ secretValues
163
+ });
164
+ this.mcpRegistration = registration;
165
+ }
166
+ this.ensureLive();
167
+ await this.options.verifyRuntimePaths?.();
168
+ await this.options.verifyExecutable?.();
169
+ await this.options.verifyGrokSandbox?.();
170
+ child = spawnEngine(this.options, `${this.options.identityPrompt ?? ""}${text}`, this.input, mount?.endpoint, this.wakeId);
171
+ this.activeChild = child;
172
+ // Attach terminal listeners synchronously. A fast local sentinel may
173
+ // exit before an asynchronous post-spawn authority recheck completes.
174
+ const outputPromise = readChild(child, deadline === undefined ? undefined : Math.max(1, deadline - Date.now()), secretValues, {
175
+ failureClassifier: this.options.engine === "grok" ? classifyGrokAuthenticationDiagnostic : undefined,
176
+ retainNdjson: this.options.engine === "codex" ? "codex" : undefined,
177
+ retainStdoutTail: this.options.engine === "grok",
178
+ timeoutErrorMessage: this.options.engine === "codex" && this.options.timeoutMs !== undefined
179
+ ? `Codex wake exceeded its ${this.options.timeoutMs}ms per-wake wall-clock bound`
180
+ : undefined,
181
+ codexTokenCeiling: this.options.engine === "codex" ? this.options.codexTokenCeiling : undefined,
182
+ onCodexTurnCompleted: meter.observeCodexTurnCompleted,
183
+ onCodexThreadStarted: (threadId) => { codexThreadId = threadId; }
179
184
  });
185
+ void outputPromise.catch(() => undefined);
186
+ await this.options.verifyRuntimePaths?.();
187
+ await this.options.verifyExecutable?.();
188
+ const childOutput = await outputPromise;
189
+ if (this.options.engine === "grok")
190
+ output = decodeGrokHeadlessResult(childOutput);
191
+ else if (this.options.engine === "codex") {
192
+ const decoded = decodeCodexTurn(childOutput);
193
+ output = decoded.text;
194
+ turnUsage = decoded.usage;
195
+ }
196
+ else if (this.options.engine === "agy") {
197
+ const decoded = decodeAgyHeadlessTurn(childOutput);
198
+ output = decoded.text;
199
+ turnUsage = decoded.usage;
200
+ }
201
+ else
202
+ output = childOutput;
203
+ }
204
+ }
205
+ catch (error) {
206
+ promptFailure = error;
180
207
  }
181
208
  finally {
182
- if (child !== undefined)
183
- terminate(child);
184
- await mount?.close();
209
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { if (child !== undefined)
210
+ await terminateChild(child); });
211
+ if (this.activeChild === child)
212
+ this.activeChild = undefined;
213
+ let registrationClosed = registration === undefined;
214
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { await registration?.close(); registrationClosed = true; });
215
+ if (registrationClosed && this.mcpRegistration === registration)
216
+ this.mcpRegistration = undefined;
217
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { await mount?.close(); });
218
+ if (this.activeMount === mount)
219
+ this.activeMount = undefined;
220
+ }
221
+ const refreshedCredentialSecrets = await this.options.credentialSecretValues?.().catch(() => []) ?? [];
222
+ const finalSecrets = [...secretValues, ...refreshedCredentialSecrets];
223
+ // A wake that Codex reported usage for is metered whether or not it goes on
224
+ // to publish. Every throw below this point used to drop that spend on the
225
+ // floor, so a breached ceiling, an expired wall clock, a non-zero exit, or
226
+ // a turn judged unpublishable all cost money the ledger never saw.
227
+ const failure = promptFailure ?? cleanupFailure;
228
+ if (failure !== undefined) {
229
+ await publishTurnUsage(this.options.onTurnUsage, turnUsage ?? meter.reported(), failedTurnOutcome(failure));
230
+ // A wake that failed still made model requests and still paid for them,
231
+ // so its per-request shape is measured on exactly the paths its spend is.
232
+ await instrument();
185
233
  }
234
+ if (promptFailure !== undefined) {
235
+ const authRejection = this.options.engine === "grok" ? asGrokAuthenticationRejected(promptFailure) : undefined;
236
+ if (authRejection !== undefined)
237
+ throw new GrokSubscriptionAuthenticationRejectedError(cleanupFailure === undefined ? undefined : redactCredentialError(cleanupFailure, finalSecrets));
238
+ if (cleanupFailure !== undefined)
239
+ throw redactCredentialError(cleanupFailure, finalSecrets);
240
+ throw redactCredentialError(promptFailure, finalSecrets);
241
+ }
242
+ if (cleanupFailure !== undefined) {
243
+ if (this.options.engine === "grok" && asGrokAuthenticationRejected(cleanupFailure) !== undefined) {
244
+ throw new GrokSubscriptionAuthenticationRejectedError();
245
+ }
246
+ throw redactCredentialError(cleanupFailure, finalSecrets);
247
+ }
248
+ if (output === undefined)
249
+ return;
250
+ output = redactCredentialText(output, finalSecrets, 64 * 1024);
251
+ for (const listener of this.listeners)
252
+ listener({
253
+ type: "turn_end",
254
+ message: {
255
+ role: "assistant", content: [{ type: "text", text: output }], api: "openai-completions", provider: "openai", model: "cli",
256
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
257
+ stopReason: "stop", timestamp: Date.now()
258
+ }, toolResults: []
259
+ });
260
+ // Meter only after the turn has published.
261
+ await publishTurnUsage(this.options.onTurnUsage, turnUsage ?? meter.reported(), { status: "completed" });
262
+ await instrument();
186
263
  }
187
264
  dispose() {
188
265
  this.disposed = true;
189
266
  this.listeners.clear();
267
+ this.disposePromise ??= this.quiesce();
268
+ }
269
+ async disposeAsync() {
270
+ this.dispose();
271
+ await this.disposePromise;
272
+ }
273
+ ensureLive() {
274
+ if (this.disposed)
275
+ throw new Error("CLI session is disposed");
276
+ }
277
+ async quiesce() {
278
+ let cleanupFailure;
279
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { if (this.activeChild !== undefined)
280
+ await terminateChild(this.activeChild); });
281
+ this.activeBrokerTurn?.abort();
282
+ cleanupFailure = await captureCleanup(cleanupFailure, () => Promise.all([...this.setupChildren].map((child) => terminateChild(child))).then(() => undefined));
283
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { await this.mcpRegistration?.close(); });
284
+ cleanupFailure = await captureCleanup(cleanupFailure, async () => { await this.activeMount?.close(); });
285
+ if (cleanupFailure !== undefined)
286
+ throw cleanupFailure;
190
287
  }
191
288
  }
192
289
  export const createCliSessionFactory = (options) => async (input) => {
@@ -196,29 +293,10 @@ export const createCliSessionFactory = (options) => async (input) => {
196
293
  session: new CliSession(options, {
197
294
  cwd: input.cwd,
198
295
  customTools: input.customTools,
199
- daimonSecretEnvironmentNames: input.daimonSecretEnvironmentNames
296
+ daimonSecretEnvironmentNames: input.daimonSecretEnvironmentNames,
297
+ runtimeHomePath: input.runtimeHomePath
200
298
  })
201
299
  };
202
300
  };
203
- export const runEngineDetailed = async (engine, prompt, paths) => {
204
- const startedAt = Date.now();
205
- const options = engine === "agy"
206
- ? { engine, maxToolTurns: 1, timeoutMs: 180_000, toolAccess: "none" }
207
- : { engine, maxToolTurns: 2, timeoutMs: 180_000 };
208
- const session = new CliSession(options, { cwd: paths.workspacePath });
209
- let text = "";
210
- const unsubscribe = session.subscribe((event) => {
211
- if (event.type !== "turn_end")
212
- return;
213
- if (!("content" in event.message))
214
- return;
215
- text = Array.isArray(event.message.content)
216
- ? event.message.content.filter((entry) => entry.type === "text").map((entry) => entry.text).join("")
217
- : event.message.content;
218
- });
219
- await session.prompt(prompt);
220
- unsubscribe();
221
- session.dispose();
222
- return { durationMs: Date.now() - startedAt, outputChars: text.length, promptChars: prompt.length, text };
223
- };
224
- export const runEngine = async (engine, prompt, paths) => (await runEngineDetailed(engine, prompt, paths)).text;
301
+ export { runEngine, runEngineDetailed } from "./cliEngineRun.js";
302
+ export { renderAgyArgs, renderCodexArgs, spawnEngine } from "./cliEngineSpawn.js";
@@ -0,0 +1,9 @@
1
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ export declare const startMcp: (tools: ToolDefinition[], maxToolTurns: number | undefined, wakeDeadline: number | undefined, onToolsMounted: ((tools: readonly ToolDefinition[]) => void) | undefined, onStarted: (mount: {
3
+ endpoint: string;
4
+ close: () => Promise<void>;
5
+ }) => void) => Promise<{
6
+ endpoint: string;
7
+ close: () => Promise<void>;
8
+ }>;
9
+ //# sourceMappingURL=cliSessionMcp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cliSessionMcp.d.ts","sourceRoot":"","sources":["../../src/pi/cliSessionMcp.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEtE,eAAO,MAAM,QAAQ,GACnB,OAAO,cAAc,EAAE,EACvB,cAAc,MAAM,GAAG,SAAS,EAChC,cAAc,MAAM,GAAG,SAAS,EAChC,gBAAgB,CAAC,CAAC,KAAK,EAAE,SAAS,cAAc,EAAE,KAAK,IAAI,CAAC,GAAG,SAAS,EACxE,WAAW,CAAC,KAAK,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,KAAK,IAAI,KAC3E,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAkE1D,CAAC"}
@@ -0,0 +1,80 @@
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
+ export const startMcp = async (tools, maxToolTurns, wakeDeadline, onToolsMounted, onStarted) => {
6
+ onToolsMounted?.(tools);
7
+ const mcpServer = createPiToolMcpServer(tools, { maxToolTurns, wakeDeadline });
8
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });
9
+ const httpServer = createServer((request, response) => {
10
+ void transport.handleRequest(request, response);
11
+ });
12
+ let lifecycle = "starting";
13
+ let cancelled = false;
14
+ let endpoint = "";
15
+ let closePromise;
16
+ let settleStartup;
17
+ const startupSettled = new Promise((resolve) => { settleStartup = resolve; });
18
+ const close = () => closePromise ??= (async () => {
19
+ cancelled = true;
20
+ if (lifecycle !== "closed")
21
+ lifecycle = "closing";
22
+ // `listen()` begins synchronously but its callback is pending. Waiting for
23
+ // startup prevents dispose from returning while that callback can still bind.
24
+ await startupSettled;
25
+ await transport.close().catch(() => undefined);
26
+ await mcpServer.close().catch(() => undefined);
27
+ // `close` only stops accepting and then waits for every open connection,
28
+ // including the ones the transport has no record of and so cannot end (a
29
+ // socket opened before `initialize`, or a client pool's idle keep-alive
30
+ // socket, which relaying a turn through the broker MCP facade leaves
31
+ // behind). That wait is unbounded and sits on the wake's own completion
32
+ // path: measured, one such connection parked a finished broker turn with
33
+ // its result in hand and published nothing. By here this one wake's engine
34
+ // has returned, failed or been cancelled, so anything still connected is a
35
+ // leftover — see `AGENTS.md`, and the facade, which bounds itself the same
36
+ // way.
37
+ if (httpServer.listening)
38
+ await new Promise((resolve) => { httpServer.close(() => resolve()); httpServer.closeAllConnections(); });
39
+ lifecycle = "closed";
40
+ })();
41
+ const mount = { get endpoint() { return endpoint; }, close };
42
+ onStarted(mount);
43
+ let startupError;
44
+ try {
45
+ if (cancelled)
46
+ throw new Error("MCP startup was cancelled");
47
+ await mcpServer.connect(transport);
48
+ if (cancelled)
49
+ throw new Error("MCP startup was cancelled");
50
+ await new Promise((resolve, reject) => {
51
+ const onError = (error) => reject(error);
52
+ httpServer.once("error", onError);
53
+ httpServer.listen(0, "127.0.0.1", () => {
54
+ httpServer.off("error", onError);
55
+ // A disposer can run from a Server.prototype.listen interceptor before
56
+ // this callback. Never publish the server as live in that interleaving.
57
+ if (!cancelled)
58
+ lifecycle = "listening";
59
+ resolve();
60
+ });
61
+ });
62
+ if (cancelled)
63
+ throw new Error("MCP startup was cancelled");
64
+ const address = httpServer.address();
65
+ if (address === null || typeof address === "string") {
66
+ throw new Error("MCP server did not receive an ephemeral port");
67
+ }
68
+ endpoint = `http://127.0.0.1:${address.port}/mcp`;
69
+ return mount;
70
+ }
71
+ catch (error) {
72
+ startupError = error;
73
+ throw error;
74
+ }
75
+ finally {
76
+ settleStartup();
77
+ if (cancelled || startupError !== undefined)
78
+ await close();
79
+ }
80
+ };
@@ -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"}