@noopolis/daimon 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (330) hide show
  1. package/README.md +269 -51
  2. package/dist/contracts/attentionContract.d.ts +117 -0
  3. package/dist/contracts/attentionContract.d.ts.map +1 -0
  4. package/dist/contracts/attentionContract.js +14 -0
  5. package/dist/contracts/canonicalJson.d.ts +3 -0
  6. package/dist/contracts/canonicalJson.d.ts.map +1 -0
  7. package/dist/contracts/canonicalJson.js +54 -0
  8. package/dist/contracts/grokWorkerContract.d.ts +74 -0
  9. package/dist/contracts/grokWorkerContract.d.ts.map +1 -0
  10. package/dist/contracts/grokWorkerContract.js +88 -0
  11. package/dist/contracts/organizationRuntimeContract.d.ts +765 -0
  12. package/dist/contracts/organizationRuntimeContract.d.ts.map +1 -0
  13. package/dist/contracts/organizationRuntimeContract.js +121 -0
  14. package/dist/contracts/runtimeContractManifest.d.ts +1615 -0
  15. package/dist/contracts/runtimeContractManifest.d.ts.map +1 -0
  16. package/dist/contracts/runtimeContractManifest.js +181 -0
  17. package/dist/core/credentialRedaction.d.ts +4 -0
  18. package/dist/core/credentialRedaction.d.ts.map +1 -0
  19. package/dist/core/credentialRedaction.js +28 -0
  20. package/dist/mcp/toolServer.d.ts +19 -2
  21. package/dist/mcp/toolServer.d.ts.map +1 -1
  22. package/dist/mcp/toolServer.js +57 -17
  23. package/dist/observability/causalEvents.d.ts +3 -3
  24. package/dist/observability/causalEvents.d.ts.map +1 -1
  25. package/dist/observability/causalEvents.js +103 -15
  26. package/dist/observability/orgObserver.d.ts.map +1 -1
  27. package/dist/observability/orgObserver.js +3 -3
  28. package/dist/pi/agyHeadlessResult.d.ts +60 -0
  29. package/dist/pi/agyHeadlessResult.d.ts.map +1 -0
  30. package/dist/pi/agyHeadlessResult.js +95 -0
  31. package/dist/pi/cliChildOutput.d.ts +67 -0
  32. package/dist/pi/cliChildOutput.d.ts.map +1 -0
  33. package/dist/pi/cliChildOutput.js +269 -0
  34. package/dist/pi/cliEngineRun.d.ts +16 -0
  35. package/dist/pi/cliEngineRun.d.ts.map +1 -0
  36. package/dist/pi/cliEngineRun.js +27 -0
  37. package/dist/pi/cliEngineSpawn.d.ts +55 -0
  38. package/dist/pi/cliEngineSpawn.d.ts.map +1 -0
  39. package/dist/pi/cliEngineSpawn.js +164 -0
  40. package/dist/pi/cliEnvironment.d.ts +12 -0
  41. package/dist/pi/cliEnvironment.d.ts.map +1 -0
  42. package/dist/pi/cliEnvironment.js +32 -0
  43. package/dist/pi/cliMcpRegistration.d.ts +61 -0
  44. package/dist/pi/cliMcpRegistration.d.ts.map +1 -0
  45. package/dist/pi/cliMcpRegistration.js +75 -0
  46. package/dist/pi/cliProcess.d.ts +7 -0
  47. package/dist/pi/cliProcess.d.ts.map +1 -0
  48. package/dist/pi/cliProcess.js +132 -0
  49. package/dist/pi/cliSession.d.ts +84 -24
  50. package/dist/pi/cliSession.d.ts.map +1 -1
  51. package/dist/pi/cliSession.js +313 -158
  52. package/dist/pi/cliTurnMetering.d.ts +60 -0
  53. package/dist/pi/cliTurnMetering.d.ts.map +1 -0
  54. package/dist/pi/cliTurnMetering.js +60 -0
  55. package/dist/pi/codexFilesystemRules.d.ts +3 -0
  56. package/dist/pi/codexFilesystemRules.d.ts.map +1 -0
  57. package/dist/pi/codexFilesystemRules.js +28 -0
  58. package/dist/pi/codexHeadlessResult.d.ts +68 -0
  59. package/dist/pi/codexHeadlessResult.d.ts.map +1 -0
  60. package/dist/pi/codexHeadlessResult.js +122 -0
  61. package/dist/pi/codexRolloutUsage.d.ts +95 -0
  62. package/dist/pi/codexRolloutUsage.d.ts.map +1 -0
  63. package/dist/pi/codexRolloutUsage.js +221 -0
  64. package/dist/pi/engineWakeLimits.d.ts +39 -0
  65. package/dist/pi/engineWakeLimits.d.ts.map +1 -0
  66. package/dist/pi/engineWakeLimits.js +55 -0
  67. package/dist/pi/grokHeadlessResult.d.ts +36 -0
  68. package/dist/pi/grokHeadlessResult.d.ts.map +1 -0
  69. package/dist/pi/grokHeadlessResult.js +118 -0
  70. package/dist/pi/grokHomeMcpRegistration.d.ts +21 -0
  71. package/dist/pi/grokHomeMcpRegistration.d.ts.map +1 -0
  72. package/dist/pi/grokHomeMcpRegistration.js +57 -0
  73. package/dist/pi/grokSandbox.d.ts +11 -0
  74. package/dist/pi/grokSandbox.d.ts.map +1 -0
  75. package/dist/pi/grokSandbox.js +216 -0
  76. package/dist/pi/grokStreamUsage.d.ts +31 -0
  77. package/dist/pi/grokStreamUsage.d.ts.map +1 -0
  78. package/dist/pi/grokStreamUsage.js +51 -0
  79. package/dist/pi/piAgentHandle.d.ts +4 -3
  80. package/dist/pi/piAgentHandle.d.ts.map +1 -1
  81. package/dist/pi/piAgentHandle.js +37 -10
  82. package/dist/pi/piAgentWakeSupport.d.ts +35 -0
  83. package/dist/pi/piAgentWakeSupport.d.ts.map +1 -1
  84. package/dist/pi/piAgentWakeSupport.js +4 -0
  85. package/dist/pi/piHarness.d.ts +10 -1
  86. package/dist/pi/piHarness.d.ts.map +1 -1
  87. package/dist/pi/piHarness.js +61 -8
  88. package/dist/pi/prompts.d.ts +1 -0
  89. package/dist/pi/prompts.d.ts.map +1 -1
  90. package/dist/pi/prompts.js +24 -0
  91. package/dist/pi/turnTrace.d.ts.map +1 -1
  92. package/dist/pi/turnTrace.js +5 -8
  93. package/dist/pi/worldTrajectory.d.ts +1 -1
  94. package/dist/pi/worldTrajectory.d.ts.map +1 -1
  95. package/dist/pi/worldTrajectory.js +3 -3
  96. package/dist/runtime/agySubscriptionBootstrap.d.ts +16 -0
  97. package/dist/runtime/agySubscriptionBootstrap.d.ts.map +1 -0
  98. package/dist/runtime/agySubscriptionBootstrap.js +80 -0
  99. package/dist/runtime/agySubscriptionRealm.d.ts +38 -0
  100. package/dist/runtime/agySubscriptionRealm.d.ts.map +1 -0
  101. package/dist/runtime/agySubscriptionRealm.js +242 -0
  102. package/dist/runtime/attention.d.ts +21 -0
  103. package/dist/runtime/attention.d.ts.map +1 -0
  104. package/dist/runtime/attention.js +36 -0
  105. package/dist/runtime/attentionDispatcher.d.ts +66 -0
  106. package/dist/runtime/attentionDispatcher.d.ts.map +1 -0
  107. package/dist/runtime/attentionDispatcher.js +271 -0
  108. package/dist/runtime/cli.d.ts +7 -0
  109. package/dist/runtime/cli.d.ts.map +1 -0
  110. package/dist/runtime/cli.js +251 -0
  111. package/dist/runtime/codexSandboxProjection.d.ts +17 -0
  112. package/dist/runtime/codexSandboxProjection.d.ts.map +1 -0
  113. package/dist/runtime/codexSandboxProjection.js +40 -0
  114. package/dist/runtime/contract-manifest.json +1 -0
  115. package/dist/runtime/contract-manifest.sha256 +1 -0
  116. package/dist/runtime/contractManifest.d.ts +8 -0
  117. package/dist/runtime/contractManifest.d.ts.map +1 -0
  118. package/dist/runtime/contractManifest.js +4 -0
  119. package/dist/runtime/engineBrokerCapabilities.d.ts +30 -0
  120. package/dist/runtime/engineBrokerCapabilities.d.ts.map +1 -0
  121. package/dist/runtime/engineBrokerCapabilities.js +59 -0
  122. package/dist/runtime/engineBrokerControlClient.d.ts +44 -0
  123. package/dist/runtime/engineBrokerControlClient.d.ts.map +1 -0
  124. package/dist/runtime/engineBrokerControlClient.js +132 -0
  125. package/dist/runtime/engineBrokerCredentialJournal.d.ts +10 -0
  126. package/dist/runtime/engineBrokerCredentialJournal.d.ts.map +1 -0
  127. package/dist/runtime/engineBrokerCredentialJournal.js +17 -0
  128. package/dist/runtime/engineBrokerInferenceProtocol.d.ts +52 -0
  129. package/dist/runtime/engineBrokerInferenceProtocol.d.ts.map +1 -0
  130. package/dist/runtime/engineBrokerInferenceProtocol.js +65 -0
  131. package/dist/runtime/engineBrokerMcpCallLog.d.ts +160 -0
  132. package/dist/runtime/engineBrokerMcpCallLog.d.ts.map +1 -0
  133. package/dist/runtime/engineBrokerMcpCallLog.js +219 -0
  134. package/dist/runtime/engineBrokerMcpFacade.d.ts +56 -0
  135. package/dist/runtime/engineBrokerMcpFacade.d.ts.map +1 -0
  136. package/dist/runtime/engineBrokerMcpFacade.js +343 -0
  137. package/dist/runtime/engineBrokerNativeClient.d.ts +52 -0
  138. package/dist/runtime/engineBrokerNativeClient.d.ts.map +1 -0
  139. package/dist/runtime/engineBrokerNativeClient.js +151 -0
  140. package/dist/runtime/engineBrokerProtocol.d.ts +135 -0
  141. package/dist/runtime/engineBrokerProtocol.d.ts.map +1 -0
  142. package/dist/runtime/engineBrokerProtocol.js +274 -0
  143. package/dist/runtime/engineBrokerSealLedger.d.ts +70 -0
  144. package/dist/runtime/engineBrokerSealLedger.d.ts.map +1 -0
  145. package/dist/runtime/engineBrokerSealLedger.js +123 -0
  146. package/dist/runtime/engineBrokerService.d.ts +37 -0
  147. package/dist/runtime/engineBrokerService.d.ts.map +1 -0
  148. package/dist/runtime/engineBrokerService.js +138 -0
  149. package/dist/runtime/engineBrokerServiceCli.d.ts +5 -0
  150. package/dist/runtime/engineBrokerServiceCli.d.ts.map +1 -0
  151. package/dist/runtime/engineBrokerServiceCli.js +32 -0
  152. package/dist/runtime/engineBrokerServiceConfig.d.ts +50 -0
  153. package/dist/runtime/engineBrokerServiceConfig.d.ts.map +1 -0
  154. package/dist/runtime/engineBrokerServiceConfig.js +92 -0
  155. package/dist/runtime/engineBrokerSingleflight.d.ts +13 -0
  156. package/dist/runtime/engineBrokerSingleflight.d.ts.map +1 -0
  157. package/dist/runtime/engineBrokerSingleflight.js +24 -0
  158. package/dist/runtime/engineBrokerTurnAccounting.d.ts +76 -0
  159. package/dist/runtime/engineBrokerTurnAccounting.d.ts.map +1 -0
  160. package/dist/runtime/engineBrokerTurnAccounting.js +108 -0
  161. package/dist/runtime/engineBrokerTurnRegistry.d.ts +57 -0
  162. package/dist/runtime/engineBrokerTurnRegistry.d.ts.map +1 -0
  163. package/dist/runtime/engineBrokerTurnRegistry.js +158 -0
  164. package/dist/runtime/engineDispatcher.d.ts +36 -0
  165. package/dist/runtime/engineDispatcher.d.ts.map +1 -0
  166. package/dist/runtime/engineDispatcher.js +216 -0
  167. package/dist/runtime/engineReadiness.d.ts +23 -0
  168. package/dist/runtime/engineReadiness.d.ts.map +1 -0
  169. package/dist/runtime/engineReadiness.js +222 -0
  170. package/dist/runtime/grokAuthenticationError.d.ts +8 -0
  171. package/dist/runtime/grokAuthenticationError.d.ts.map +1 -0
  172. package/dist/runtime/grokAuthenticationError.js +20 -0
  173. package/dist/runtime/grokBrokerCredentialAuthority.d.ts +22 -0
  174. package/dist/runtime/grokBrokerCredentialAuthority.d.ts.map +1 -0
  175. package/dist/runtime/grokBrokerCredentialAuthority.js +124 -0
  176. package/dist/runtime/grokBrokerCredentialReader.d.ts +5 -0
  177. package/dist/runtime/grokBrokerCredentialReader.d.ts.map +1 -0
  178. package/dist/runtime/grokBrokerCredentialReader.js +37 -0
  179. package/dist/runtime/grokBrokerModelPolicy.d.ts +23 -0
  180. package/dist/runtime/grokBrokerModelPolicy.d.ts.map +1 -0
  181. package/dist/runtime/grokBrokerModelPolicy.js +28 -0
  182. package/dist/runtime/grokBrokerProjection.d.ts +106 -0
  183. package/dist/runtime/grokBrokerProjection.d.ts.map +1 -0
  184. package/dist/runtime/grokBrokerProjection.js +94 -0
  185. package/dist/runtime/grokBrokerProxy.d.ts +55 -0
  186. package/dist/runtime/grokBrokerProxy.d.ts.map +1 -0
  187. package/dist/runtime/grokBrokerProxy.js +262 -0
  188. package/dist/runtime/grokBrokerProxyRequest.d.ts +30 -0
  189. package/dist/runtime/grokBrokerProxyRequest.d.ts.map +1 -0
  190. package/dist/runtime/grokBrokerProxyRequest.js +74 -0
  191. package/dist/runtime/grokBrokerRealmLease.d.ts +4 -0
  192. package/dist/runtime/grokBrokerRealmLease.d.ts.map +1 -0
  193. package/dist/runtime/grokBrokerRealmLease.js +33 -0
  194. package/dist/runtime/grokBrokerRefresh.d.ts +2 -0
  195. package/dist/runtime/grokBrokerRefresh.d.ts.map +1 -0
  196. package/dist/runtime/grokBrokerRefresh.js +15 -0
  197. package/dist/runtime/grokBrokerTurnMeter.d.ts +128 -0
  198. package/dist/runtime/grokBrokerTurnMeter.d.ts.map +1 -0
  199. package/dist/runtime/grokBrokerTurnMeter.js +251 -0
  200. package/dist/runtime/grokBrokerWorkerConfig.d.ts +86 -0
  201. package/dist/runtime/grokBrokerWorkerConfig.d.ts.map +1 -0
  202. package/dist/runtime/grokBrokerWorkerConfig.js +135 -0
  203. package/dist/runtime/grokEngineBroker.d.ts +48 -0
  204. package/dist/runtime/grokEngineBroker.d.ts.map +1 -0
  205. package/dist/runtime/grokEngineBroker.js +114 -0
  206. package/dist/runtime/grokEngineBrokerLedger.d.ts +52 -0
  207. package/dist/runtime/grokEngineBrokerLedger.d.ts.map +1 -0
  208. package/dist/runtime/grokEngineBrokerLedger.js +114 -0
  209. package/dist/runtime/grokEngineBrokerMetering.d.ts +51 -0
  210. package/dist/runtime/grokEngineBrokerMetering.d.ts.map +1 -0
  211. package/dist/runtime/grokEngineBrokerMetering.js +34 -0
  212. package/dist/runtime/grokEngineBrokerTurn.d.ts +58 -0
  213. package/dist/runtime/grokEngineBrokerTurn.d.ts.map +1 -0
  214. package/dist/runtime/grokEngineBrokerTurn.js +165 -0
  215. package/dist/runtime/grokInferenceClientConfig.d.ts +41 -0
  216. package/dist/runtime/grokInferenceClientConfig.d.ts.map +1 -0
  217. package/dist/runtime/grokInferenceClientConfig.js +62 -0
  218. package/dist/runtime/grokInferenceGrants.d.ts +77 -0
  219. package/dist/runtime/grokInferenceGrants.d.ts.map +1 -0
  220. package/dist/runtime/grokInferenceGrants.js +116 -0
  221. package/dist/runtime/grokInferenceProxy.d.ts +29 -0
  222. package/dist/runtime/grokInferenceProxy.d.ts.map +1 -0
  223. package/dist/runtime/grokInferenceProxy.js +82 -0
  224. package/dist/runtime/grokInferenceProxyRequest.d.ts +23 -0
  225. package/dist/runtime/grokInferenceProxyRequest.d.ts.map +1 -0
  226. package/dist/runtime/grokInferenceProxyRequest.js +63 -0
  227. package/dist/runtime/grokSlotPreflightReceipt.d.ts +70 -0
  228. package/dist/runtime/grokSlotPreflightReceipt.d.ts.map +1 -0
  229. package/dist/runtime/grokSlotPreflightReceipt.js +101 -0
  230. package/dist/runtime/grokSubscriptionRealm.d.ts +4 -0
  231. package/dist/runtime/grokSubscriptionRealm.d.ts.map +1 -0
  232. package/dist/runtime/grokSubscriptionRealm.js +435 -0
  233. package/dist/runtime/grokSubscriptionRealmTypes.d.ts +26 -0
  234. package/dist/runtime/grokSubscriptionRealmTypes.d.ts.map +1 -0
  235. package/dist/runtime/grokSubscriptionRealmTypes.js +1 -0
  236. package/dist/runtime/grokWorkerAttestation.d.ts +170 -0
  237. package/dist/runtime/grokWorkerAttestation.d.ts.map +1 -0
  238. package/dist/runtime/grokWorkerAttestation.js +266 -0
  239. package/dist/runtime/grokWorkerDenyPlacement.d.ts +80 -0
  240. package/dist/runtime/grokWorkerDenyPlacement.d.ts.map +1 -0
  241. package/dist/runtime/grokWorkerDenyPlacement.js +128 -0
  242. package/dist/runtime/grokWorkerHomeAttestation.d.ts +30 -0
  243. package/dist/runtime/grokWorkerHomeAttestation.d.ts.map +1 -0
  244. package/dist/runtime/grokWorkerHomeAttestation.js +69 -0
  245. package/dist/runtime/grokWorkerSandboxProfile.d.ts +27 -0
  246. package/dist/runtime/grokWorkerSandboxProfile.d.ts.map +1 -0
  247. package/dist/runtime/grokWorkerSandboxProfile.js +44 -0
  248. package/dist/runtime/grokWorkerTmpAttestation.d.ts +55 -0
  249. package/dist/runtime/grokWorkerTmpAttestation.d.ts.map +1 -0
  250. package/dist/runtime/grokWorkerTmpAttestation.js +63 -0
  251. package/dist/runtime/index.d.ts +26 -0
  252. package/dist/runtime/index.d.ts.map +1 -0
  253. package/dist/runtime/index.js +23 -0
  254. package/dist/runtime/inferenceUsageLedger.d.ts +38 -0
  255. package/dist/runtime/inferenceUsageLedger.d.ts.map +1 -0
  256. package/dist/runtime/inferenceUsageLedger.js +53 -0
  257. package/dist/runtime/mcpToolResult.d.ts +127 -0
  258. package/dist/runtime/mcpToolResult.d.ts.map +1 -0
  259. package/dist/runtime/mcpToolResult.js +214 -0
  260. package/dist/runtime/moltnetMachineRead.d.ts +97 -0
  261. package/dist/runtime/moltnetMachineRead.d.ts.map +1 -0
  262. package/dist/runtime/moltnetMachineRead.js +183 -0
  263. package/dist/runtime/native/daimon-engine-broker +0 -0
  264. package/dist/runtime/organizationRuntime.d.ts +165 -0
  265. package/dist/runtime/organizationRuntime.d.ts.map +1 -0
  266. package/dist/runtime/organizationRuntime.js +3 -0
  267. package/dist/runtime/organizationRuntimeControl.d.ts +42 -0
  268. package/dist/runtime/organizationRuntimeControl.d.ts.map +1 -0
  269. package/dist/runtime/organizationRuntimeControl.js +235 -0
  270. package/dist/runtime/organizationRuntimeHost.d.ts +19 -0
  271. package/dist/runtime/organizationRuntimeHost.d.ts.map +1 -0
  272. package/dist/runtime/organizationRuntimeHost.js +359 -0
  273. package/dist/runtime/organizationRuntimeParsing.d.ts +6 -0
  274. package/dist/runtime/organizationRuntimeParsing.d.ts.map +1 -0
  275. package/dist/runtime/organizationRuntimeParsing.js +370 -0
  276. package/dist/runtime/organizationRuntimeReadiness.d.ts +12 -0
  277. package/dist/runtime/organizationRuntimeReadiness.d.ts.map +1 -0
  278. package/dist/runtime/organizationRuntimeReadiness.js +59 -0
  279. package/dist/runtime/physicalReadiness.d.ts +47 -0
  280. package/dist/runtime/physicalReadiness.d.ts.map +1 -0
  281. package/dist/runtime/physicalReadiness.js +142 -0
  282. package/dist/runtime/portableCredentialAuth.d.ts +6 -0
  283. package/dist/runtime/portableCredentialAuth.d.ts.map +1 -0
  284. package/dist/runtime/portableCredentialAuth.js +70 -0
  285. package/dist/runtime/portableCredentialMaterial.d.ts +8 -0
  286. package/dist/runtime/portableCredentialMaterial.d.ts.map +1 -0
  287. package/dist/runtime/portableCredentialMaterial.js +169 -0
  288. package/dist/runtime/productionAgentTools.d.ts +5 -0
  289. package/dist/runtime/productionAgentTools.d.ts.map +1 -0
  290. package/dist/runtime/productionAgentTools.js +328 -0
  291. package/dist/runtime/runtimeHomeLayout.d.ts +48 -0
  292. package/dist/runtime/runtimeHomeLayout.d.ts.map +1 -0
  293. package/dist/runtime/runtimeHomeLayout.js +84 -0
  294. package/dist/runtime/schedule.d.ts +40 -0
  295. package/dist/runtime/schedule.d.ts.map +1 -0
  296. package/dist/runtime/schedule.js +371 -0
  297. package/dist/runtime/storeCoordination.d.ts +23 -0
  298. package/dist/runtime/storeCoordination.d.ts.map +1 -0
  299. package/dist/runtime/storeCoordination.js +94 -0
  300. package/dist/runtime/toolResultSpill.d.ts +152 -0
  301. package/dist/runtime/toolResultSpill.d.ts.map +1 -0
  302. package/dist/runtime/toolResultSpill.js +351 -0
  303. package/dist/runtime/turnRequestLedger.d.ts +160 -0
  304. package/dist/runtime/turnRequestLedger.d.ts.map +1 -0
  305. package/dist/runtime/turnRequestLedger.js +249 -0
  306. package/dist/runtime/turnUsageLedger.d.ts +143 -0
  307. package/dist/runtime/turnUsageLedger.d.ts.map +1 -0
  308. package/dist/runtime/turnUsageLedger.js +203 -0
  309. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts +17 -0
  310. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts.map +1 -0
  311. package/dist/runtime/wakeAcceptanceProcessIdentity.js +50 -0
  312. package/dist/runtime/wakeAcceptanceReconciliation.d.ts +211 -0
  313. package/dist/runtime/wakeAcceptanceReconciliation.d.ts.map +1 -0
  314. package/dist/runtime/wakeAcceptanceReconciliation.js +289 -0
  315. package/dist/runtime/wakeAcceptanceRecord.d.ts +23 -0
  316. package/dist/runtime/wakeAcceptanceRecord.d.ts.map +1 -0
  317. package/dist/runtime/wakeAcceptanceRecord.js +56 -0
  318. package/dist/runtime/wakeAcceptanceRetention.d.ts +12 -0
  319. package/dist/runtime/wakeAcceptanceRetention.d.ts.map +1 -0
  320. package/dist/runtime/wakeAcceptanceRetention.js +12 -0
  321. package/dist/runtime/wakeAcceptanceStore.d.ts +113 -0
  322. package/dist/runtime/wakeAcceptanceStore.d.ts.map +1 -0
  323. package/dist/runtime/wakeAcceptanceStore.js +558 -0
  324. package/dist/runtime/wakeAcceptanceTypes.d.ts +179 -0
  325. package/dist/runtime/wakeAcceptanceTypes.d.ts.map +1 -0
  326. package/dist/runtime/wakeAcceptanceTypes.js +95 -0
  327. package/dist/runtime/wakeFuse.d.ts +69 -0
  328. package/dist/runtime/wakeFuse.d.ts.map +1 -0
  329. package/dist/runtime/wakeFuse.js +367 -0
  330. package/package.json +20 -9
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Token accounting for one AGY turn, as the engine itself reported it.
3
+ *
4
+ * Same shape and the same discipline as {@link import("./grokHeadlessResult.js").GrokTurnUsage},
5
+ * but AGY's envelope is *not* Grok's. Field provenance is the terminal frame of
6
+ * `agy --print … --output-format stream-json`:
7
+ *
8
+ * {"event":"result","result":{ "status":"SUCCESS", "response":"…",
9
+ * "num_turns":1,
10
+ * "usage":{"input_tokens":…, "output_tokens":…,
11
+ * "thinking_tokens":…, "cache_read_tokens":…, "total_tokens":…}}}
12
+ *
13
+ * Differences from Grok that this decoder exists to get right:
14
+ *
15
+ * - the prompt-side cache bucket is `cache_read_tokens`, **not**
16
+ * `cache_read_input_tokens`;
17
+ * - there is no `cache_creation_input_tokens` bucket at all, so `cacheWrite` is
18
+ * structurally absent and recorded as `0` — absent, not measured-as-zero;
19
+ * - there is no `total_cost_usd`, so `notionalUsd` is `0` for the same reason;
20
+ * - `thinking_tokens` has no Grok equivalent and is a **subset** of
21
+ * `output_tokens`, not a disjoint bucket. The captured plain turn is
22
+ * `input 13,722 + output 74 = 13,796 = total_tokens` with
23
+ * `thinking_tokens: 73`, so adding it would double-count reasoning tokens.
24
+ * It is therefore read only to be ignored;
25
+ * - AGY supplies its own `total_tokens`, which is cross-checked rather than
26
+ * trusted (see {@link decodeAgyTurnUsage});
27
+ * - `status: "SUCCESS"` replaces Grok's `subtype`/`is_error` pair.
28
+ *
29
+ * The terminal frame's `usage` is the sum over the turn's model steps, not the
30
+ * last step's: the captured tool turn sums three `step_update` frames
31
+ * (14,579 + 15,079 + 15,279 input) into `input_tokens: 44,937`. Reading a
32
+ * `step_update` would under-report every tool-using wake.
33
+ */
34
+ export type AgyTurnUsage = Readonly<{
35
+ input: number;
36
+ output: number;
37
+ cacheRead: number;
38
+ cacheWrite: number;
39
+ total: number;
40
+ calls: number;
41
+ notionalUsd: number;
42
+ complete: boolean;
43
+ }>;
44
+ export type AgyHeadlessTurn = Readonly<{
45
+ text: string;
46
+ usage?: AgyTurnUsage;
47
+ }>;
48
+ /**
49
+ * Decode AGY's `stream-json` NDJSON without treating a progress frame as a
50
+ * reply, and extract the turn's own token accounting from the same frame.
51
+ *
52
+ * Frames before the terminal one are `{"event":"init"|"step_update", …}`.
53
+ * Unrecognized `event` values are skipped rather than rejected: AGY owns this
54
+ * stream and a frame kind added later must not fail a turn that published.
55
+ * The terminal `result` frame must be the last line, exactly as with Grok.
56
+ */
57
+ export declare const decodeAgyHeadlessTurn: (output: string) => AgyHeadlessTurn;
58
+ /** Text-only view of {@link decodeAgyHeadlessTurn}, for callers that do not meter. */
59
+ export declare const decodeAgyHeadlessResult: (output: string) => string;
60
+ //# sourceMappingURL=agyHeadlessResult.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agyHeadlessResult.d.ts","sourceRoot":"","sources":["../../src/pi/agyHeadlessResult.ts"],"names":[],"mappings":"AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,MAAM,YAAY,GAAG,QAAQ,CAAC;IAClC,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,eAAe,GAAG,QAAQ,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,YAAY,CAAA;CAAE,CAAC,CAAC;AAqD/E;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,GAAI,QAAQ,MAAM,KAAG,eAkBtD,CAAC;AAEF,sFAAsF;AACtF,eAAO,MAAM,uBAAuB,GAAI,QAAQ,MAAM,KAAG,MAA4C,CAAC"}
@@ -0,0 +1,95 @@
1
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2
+ const invalidResult = (detail) => new Error(`AGY CLI returned no publishable terminal response: ${detail}`);
3
+ /**
4
+ * The three token buckets AGY emits on `result.usage`. All three must be
5
+ * present and be non-negative safe integers; a renamed, stringified, negative,
6
+ * or fractional field rejects the whole block rather than silently contributing
7
+ * a zero, because a zero bucket is byte-indistinguishable from a real one.
8
+ */
9
+ const USAGE_TOKEN_FIELDS = ["input_tokens", "output_tokens", "cache_read_tokens"];
10
+ const tokenCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
11
+ /**
12
+ * Extract per-turn usage from the terminal `result` frame.
13
+ *
14
+ * Advisory: a malformed or absent usage block yields `undefined` rather than
15
+ * failing a turn that published correctly, and never throws.
16
+ *
17
+ * `complete` follows exactly the honesty rule the Grok decoder states: AGY's
18
+ * envelope has no marker for incomplete or absent usage either, so an all-zero
19
+ * block reads as "unknown", not "free". It cannot catch a *partially*
20
+ * zero-filled turn, so every count this decoder produces is a lower bound.
21
+ *
22
+ * AGY additionally reports its own `total_tokens`. Neither side is trusted
23
+ * blindly: the derived sum `input + cacheRead + output` is compared against it,
24
+ * `total` is the larger of the two so a reconciliation failure can never
25
+ * under-report, and any disagreement clears `complete` so the record is
26
+ * rendered as an incomplete turn rather than a verified count. A `total_tokens`
27
+ * that is not a non-negative safe integer rejects the block outright, because
28
+ * an unreadable total is a total that cannot be reconciled.
29
+ */
30
+ const decodeAgyTurnUsage = (result) => {
31
+ if (!isRecord(result.usage))
32
+ return undefined;
33
+ const usage = result.usage;
34
+ const counts = USAGE_TOKEN_FIELDS.map((field) => tokenCount(usage[field]));
35
+ if (counts.some((count) => count === undefined))
36
+ return undefined;
37
+ const [input, output, cacheRead] = counts;
38
+ const reported = usage.total_tokens === undefined ? undefined : tokenCount(usage.total_tokens);
39
+ if (usage.total_tokens !== undefined && reported === undefined)
40
+ return undefined;
41
+ const derived = input + cacheRead + output;
42
+ return {
43
+ input,
44
+ output,
45
+ cacheRead,
46
+ cacheWrite: 0,
47
+ total: reported === undefined ? derived : Math.max(derived, reported),
48
+ calls: tokenCount(result.num_turns) ?? 0,
49
+ notionalUsd: 0,
50
+ complete: derived > 0 && (reported === undefined || reported === derived)
51
+ };
52
+ };
53
+ /**
54
+ * Decode AGY's `stream-json` NDJSON without treating a progress frame as a
55
+ * reply, and extract the turn's own token accounting from the same frame.
56
+ *
57
+ * Frames before the terminal one are `{"event":"init"|"step_update", …}`.
58
+ * Unrecognized `event` values are skipped rather than rejected: AGY owns this
59
+ * stream and a frame kind added later must not fail a turn that published.
60
+ * The terminal `result` frame must be the last line, exactly as with Grok.
61
+ */
62
+ export const decodeAgyHeadlessTurn = (output) => {
63
+ const lines = output.split(/\r?\n/).filter((line) => line.length > 0);
64
+ if (lines.length === 0)
65
+ throw invalidResult("empty stream");
66
+ let result;
67
+ for (const [index, line] of lines.entries()) {
68
+ let frame;
69
+ try {
70
+ frame = JSON.parse(line);
71
+ }
72
+ catch {
73
+ throw invalidResult("invalid JSON");
74
+ }
75
+ if (!isRecord(frame) || typeof frame.event !== "string")
76
+ throw invalidResult("invalid event");
77
+ if (frame.event !== "result")
78
+ continue;
79
+ if (index !== lines.length - 1)
80
+ throw invalidResult("non-terminal result");
81
+ if (!isRecord(frame.result))
82
+ throw invalidResult("invalid result event");
83
+ result = frame.result;
84
+ }
85
+ if (result === undefined)
86
+ throw invalidResult("no result frame");
87
+ if (result.status !== "SUCCESS")
88
+ throw invalidResult("unsuccessful result");
89
+ if (typeof result.response !== "string" || result.response.trim().length === 0)
90
+ throw invalidResult("empty response");
91
+ const usage = decodeAgyTurnUsage(result);
92
+ return usage === undefined ? { text: result.response.trim() } : { text: result.response.trim(), usage };
93
+ };
94
+ /** Text-only view of {@link decodeAgyHeadlessTurn}, for callers that do not meter. */
95
+ export const decodeAgyHeadlessResult = (output) => decodeAgyHeadlessTurn(output).text;
@@ -0,0 +1,67 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ import type { TurnUsageFailureReason } from "../runtime/turnUsageLedger.js";
3
+ import { type CodexTurnUsage } from "./codexHeadlessResult.js";
4
+ /** Maximum assistant reply bytes retained from stdout. */
5
+ export declare const CLI_ENGINE_MAX_OUTPUT_BYTES: number;
6
+ /** Diagnostic bytes retained from stderr for a failed child: its head and its tail together. */
7
+ export declare const CLI_ENGINE_MAX_DIAGNOSTIC_BYTES = 768;
8
+ export declare const tagCliChildFailure: <T>(error: T, reason: TurnUsageFailureReason) => T;
9
+ export declare const cliChildFailureReason: (error: unknown) => TurnUsageFailureReason | undefined;
10
+ /**
11
+ * One bounded window over a failed child's own output: its head AND its tail,
12
+ * with an explicit marker naming the bytes elided between them.
13
+ *
14
+ * A pure tail is the wrong end for the process this exists for. A worker that
15
+ * dies early prints its error first and then echoes its own input, so the tail
16
+ * is the echo: one live brokered turn reported 512 bytes of its own prompt
17
+ * read back, with the actual error already off the front and discarded. Both
18
+ * ends cost the same window, and the marker is the one oversized tool results
19
+ * already use (`toolResultSpill.ts`), so a reader meets one shape everywhere.
20
+ *
21
+ * The marker is paid for out of the same budget — it is sized against the
22
+ * largest count it could carry — so the result never exceeds `maxBytes`, and
23
+ * output that fits is returned byte-identical with no marker at all.
24
+ */
25
+ export declare const boundedDiagnosticWindow: (value: string, maxBytes: number) => string;
26
+ export declare const readChild: (child: ChildProcess, timeoutMs: number | undefined, secretValues: readonly string[], options?: Readonly<{
27
+ failureClassifier?: (diagnostic: string) => Error | undefined;
28
+ retainNdjson?: "codex";
29
+ retainStdoutTail?: boolean;
30
+ /** Overrides the generic wall-clock-timeout message so the caller can name which bound was hit. */
31
+ timeoutErrorMessage?: string;
32
+ /**
33
+ * Per-wake token ceiling for a Codex turn (`retainNdjson: "codex"` only).
34
+ * Codex's `--json` stream reports usage exactly once, on `turn.completed`
35
+ * — there is no incremental total to watch mid-turn — so this is
36
+ * enforced at the earliest and only moment the crossing is observable:
37
+ * the instant that frame is parsed off the stream. Crossing it kills the
38
+ * child immediately (rather than letting an over-budget turn resolve as
39
+ * a normal success) and fails the wake with a bound-named error.
40
+ */
41
+ codexTokenCeiling?: number;
42
+ /**
43
+ * Called once per parsed `turn.completed` frame (`retainNdjson: "codex"`
44
+ * only), with that frame's decoded usage — or `undefined` when the usage
45
+ * block is absent or malformed, which is never substituted with zeros.
46
+ *
47
+ * This is the only point at which a wake that is about to be killed — by
48
+ * the ceiling, by the wall clock, or by a non-zero exit — can still hand
49
+ * over what Codex reported it spent. Every path downstream of here either
50
+ * rejects or discards the stream, which is how a breached wake's usage
51
+ * used to survive only inside an error message.
52
+ */
53
+ onCodexTurnCompleted?: (usage: CodexTurnUsage | undefined) => void;
54
+ /**
55
+ * Called with the thread id from Codex's `thread.started` frame
56
+ * (`retainNdjson: "codex"` only), the first line of every `codex exec
57
+ * --json` stream — verified live against codex-cli 0.153.4:
58
+ * `{"type":"thread.started","thread_id":"01a076d3-…"}`.
59
+ *
60
+ * That id is the only key that ties this wake to the rollout Codex writes
61
+ * under `$CODEX_HOME/sessions/**`, where the per-model-request accounting
62
+ * lives. The frame stays out of the retained stream: the decoder's
63
+ * vocabulary and the retained-output budget are unchanged by reading it.
64
+ */
65
+ onCodexThreadStarted?: (threadId: string) => void;
66
+ }>) => Promise<string>;
67
+ //# sourceMappingURL=cliChildOutput.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cliChildOutput.d.ts","sourceRoot":"","sources":["../../src/pi/cliChildOutput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAIvD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAwB,KAAK,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAGrF,0DAA0D;AAC1D,eAAO,MAAM,2BAA2B,QAAY,CAAC;AACrD,gGAAgG;AAChG,eAAO,MAAM,+BAA+B,MAAM,CAAC;AAanD,eAAO,MAAM,kBAAkB,GAAI,CAAC,EAAE,OAAO,CAAC,EAAE,QAAQ,sBAAsB,KAAG,CAOhF,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,OAAO,OAAO,KAAG,sBAAsB,GAAG,SAGjE,CAAC;AAMhB;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,uBAAuB,GAAI,OAAO,MAAM,EAAE,UAAU,MAAM,KAAG,MAQzE,CAAC;AAUF,eAAO,MAAM,SAAS,GACpB,OAAO,YAAY,EACnB,WAAW,MAAM,GAAG,SAAS,EAC7B,cAAc,SAAS,MAAM,EAAE,EAC/B,UAAS,QAAQ,CAAC;IAChB,iBAAiB,CAAC,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,KAAK,GAAG,SAAS,CAAC;IAC9D,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,mGAAmG;IACnG,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;;;;OAQG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;;;;;;;;OAUG;IACH,oBAAoB,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,GAAG,SAAS,KAAK,IAAI,CAAC;IACnE;;;;;;;;;;OAUG;IACH,oBAAoB,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACnD,CAAM,KACN,OAAO,CAAC,MAAM,CAmLf,CAAC"}
@@ -0,0 +1,269 @@
1
+ import { redactCredentialText } from "../core/credentialRedaction.js";
2
+ import { headUtf8, tailUtf8 } from "../runtime/toolResultSpill.js";
3
+ import { decodeCodexTurnUsage } from "./codexHeadlessResult.js";
4
+ import { terminateChild, trackCliChild } from "./cliProcess.js";
5
+ /** Maximum assistant reply bytes retained from stdout. */
6
+ export const CLI_ENGINE_MAX_OUTPUT_BYTES = 64 * 1024;
7
+ /** Diagnostic bytes retained from stderr for a failed child: its head and its tail together. */
8
+ export const CLI_ENGINE_MAX_DIAGNOSTIC_BYTES = 768;
9
+ const CLI_ENGINE_FAILURE_SCAN_CHARS = 256;
10
+ /**
11
+ * Which bound or condition failed a wake, carried on the error object itself.
12
+ *
13
+ * The caller needs this to label the usage row a failed wake still owes the
14
+ * ledger, and matching on the message text would make that label depend on
15
+ * prose. The tag is a non-enumerable symbol property, so it never widens the
16
+ * error's serialized form and never reaches a diagnostic string.
17
+ */
18
+ const CLI_CHILD_FAILURE_REASON = Symbol("daimon.cliChildFailureReason");
19
+ export const tagCliChildFailure = (error, reason) => {
20
+ if (!(error instanceof Error))
21
+ return error;
22
+ // Labelling a failure must never become a second failure: a frozen or sealed
23
+ // error simply goes untagged and its row reads `unknown`.
24
+ try {
25
+ Object.defineProperty(error, CLI_CHILD_FAILURE_REASON, { configurable: true, enumerable: false, value: reason, writable: true });
26
+ }
27
+ catch { /* the reason is advisory; the failure it describes is not */ }
28
+ return error;
29
+ };
30
+ export const cliChildFailureReason = (error) => error instanceof Error
31
+ ? error[CLI_CHILD_FAILURE_REASON]
32
+ : undefined;
33
+ const redactChildOutput = (value, secretValues) => {
34
+ return redactCredentialText(value, secretValues, CLI_ENGINE_MAX_OUTPUT_BYTES);
35
+ };
36
+ /**
37
+ * One bounded window over a failed child's own output: its head AND its tail,
38
+ * with an explicit marker naming the bytes elided between them.
39
+ *
40
+ * A pure tail is the wrong end for the process this exists for. A worker that
41
+ * dies early prints its error first and then echoes its own input, so the tail
42
+ * is the echo: one live brokered turn reported 512 bytes of its own prompt
43
+ * read back, with the actual error already off the front and discarded. Both
44
+ * ends cost the same window, and the marker is the one oversized tool results
45
+ * already use (`toolResultSpill.ts`), so a reader meets one shape everywhere.
46
+ *
47
+ * The marker is paid for out of the same budget — it is sized against the
48
+ * largest count it could carry — so the result never exceeds `maxBytes`, and
49
+ * output that fits is returned byte-identical with no marker at all.
50
+ */
51
+ export const boundedDiagnosticWindow = (value, maxBytes) => {
52
+ const total = Buffer.byteLength(value, "utf8");
53
+ if (total <= maxBytes)
54
+ return value;
55
+ const budget = Math.max(0, maxBytes - Buffer.byteLength(elisionMarker(total), "utf8"));
56
+ const head = headUtf8(value, Math.floor(budget / 2));
57
+ const tail = tailUtf8(value, budget - Buffer.byteLength(head, "utf8"));
58
+ const elided = total - Buffer.byteLength(head, "utf8") - Buffer.byteLength(tail, "utf8");
59
+ return `${head}${elisionMarker(elided)}${tail}`;
60
+ };
61
+ const elisionMarker = (elided) => `[… ${elided} bytes elided …]`;
62
+ const childDiagnostic = (stdout, stderr, secretValues) => {
63
+ const output = stderr.trim().length > 0 ? stderr : stdout;
64
+ const redacted = redactCredentialText(output, secretValues, Number.MAX_SAFE_INTEGER).trim();
65
+ const bounded = boundedDiagnosticWindow(redacted, CLI_ENGINE_MAX_DIAGNOSTIC_BYTES).trim();
66
+ return bounded.length > 0 ? `: ${bounded}` : "";
67
+ };
68
+ export const readChild = (child, timeoutMs, secretValues, options = {}) => new Promise((resolve, reject) => {
69
+ trackCliChild(child);
70
+ const stdout = [];
71
+ let stdoutTail = Buffer.alloc(0);
72
+ let droppingStdoutLine = false;
73
+ // Both ends of stderr, retained as it streams: the head frozen once it is
74
+ // full, the tail sliding. A single sliding tail dropped the head at capture
75
+ // time, which is where the cause of an early death lives — no later window
76
+ // can recover what was never kept.
77
+ let stderrHead = Buffer.alloc(0);
78
+ let stderrTail = Buffer.alloc(0);
79
+ let stderrBytes = 0;
80
+ let stdoutBytes = 0;
81
+ let stdoutRemainder = Buffer.alloc(0);
82
+ let droppingNdjsonLine = false;
83
+ let ndjsonCalls = 0;
84
+ let settled = false;
85
+ let cleanupStarted = false;
86
+ let classifiedFailure;
87
+ let failureScanTail = "";
88
+ /**
89
+ * Each retained end carries its reported share PLUS one whole secret, which
90
+ * is the invariant that keeps exact redaction exact: a secret that reaches
91
+ * the reported window can extend at most its own length past that window's
92
+ * cut, so retaining that much more on each side means the redactor always
93
+ * sees the secret whole. Halving one shared budget instead broke it — a
94
+ * 2000-byte secret was cut in the middle and its tail fragment
95
+ * (`…qqq-secret-end`) reached the diagnostic verbatim.
96
+ */
97
+ const stderrSecretAllowance = Math.max(0, ...secretValues.map((secret) => Buffer.byteLength(secret, "utf8")));
98
+ const stderrHeadBytes = Math.floor(CLI_ENGINE_MAX_DIAGNOSTIC_BYTES / 2) + stderrSecretAllowance;
99
+ const stderrTailBytes = CLI_ENGINE_MAX_DIAGNOSTIC_BYTES - Math.floor(CLI_ENGINE_MAX_DIAGNOSTIC_BYTES / 2) + stderrSecretAllowance;
100
+ const settle = (action) => {
101
+ if (settled)
102
+ return;
103
+ settled = true;
104
+ if (timer !== undefined)
105
+ clearTimeout(timer);
106
+ action();
107
+ };
108
+ const abort = (error) => {
109
+ if (cleanupStarted)
110
+ return;
111
+ cleanupStarted = true;
112
+ void terminateChild(child).then(() => settle(() => reject(error)), (cleanupError) => settle(() => reject(cleanupError instanceof Error ? cleanupError : error)));
113
+ };
114
+ const classifyFailure = (chunk) => {
115
+ if (classifiedFailure !== undefined || options.failureClassifier === undefined)
116
+ return;
117
+ const diagnostic = `${failureScanTail}${chunk.toString("utf8")}`;
118
+ classifiedFailure = options.failureClassifier(diagnostic);
119
+ failureScanTail = diagnostic.slice(-CLI_ENGINE_FAILURE_SCAN_CHARS);
120
+ };
121
+ const retainStdout = (chunk) => {
122
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
123
+ classifyFailure(value);
124
+ if (options.retainNdjson !== undefined) {
125
+ let incoming = value;
126
+ if (droppingNdjsonLine) {
127
+ const newline = incoming.indexOf(0x0a);
128
+ if (newline < 0)
129
+ return;
130
+ droppingNdjsonLine = false;
131
+ incoming = incoming.subarray(newline + 1);
132
+ }
133
+ stdoutRemainder = Buffer.concat([stdoutRemainder, incoming]);
134
+ let newline;
135
+ while ((newline = stdoutRemainder.indexOf(0x0a)) >= 0) {
136
+ const line = stdoutRemainder.subarray(0, newline).toString("utf8");
137
+ stdoutRemainder = Buffer.from(stdoutRemainder.subarray(newline + 1));
138
+ let frame;
139
+ try {
140
+ const parsed = JSON.parse(line);
141
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
142
+ frame = parsed;
143
+ }
144
+ catch { /* decoder reports malformed retained protocol lines */ }
145
+ if (frame === undefined) {
146
+ stdout.push(Buffer.from(`${line}\n`));
147
+ continue;
148
+ }
149
+ if (frame.type === "thread.started" && typeof frame.thread_id === "string") {
150
+ options.onCodexThreadStarted?.(frame.thread_id);
151
+ continue;
152
+ }
153
+ const item = typeof frame.item === "object" && frame.item !== null && !Array.isArray(frame.item) ? frame.item : undefined;
154
+ if (frame.type === "item.completed" && (item?.type === "command_execution" || item?.type === "mcp_tool_call")) {
155
+ ndjsonCalls += 1;
156
+ stdout.push(Buffer.from(`${JSON.stringify({ type: frame.type, item: { type: item.type } })}\n`));
157
+ }
158
+ else if ((frame.type === "item.completed" && item?.type === "agent_message") || frame.type === "turn.completed" || frame.type === "turn.failed") {
159
+ if (frame.type === "turn.completed") {
160
+ // Decode and publish first, kill second: the ceiling breach is the
161
+ // one path guaranteed to destroy this stream, so the accounting
162
+ // has to leave the reader before the child does.
163
+ const usage = decodeCodexTurnUsage(frame, ndjsonCalls);
164
+ options.onCodexTurnCompleted?.(usage);
165
+ if (options.codexTokenCeiling !== undefined && usage !== undefined && usage.total >= options.codexTokenCeiling) {
166
+ abort(tagCliChildFailure(new Error(`Codex wake exceeded its ${options.codexTokenCeiling}-token per-wake ceiling (turn usage ${usage.total} tokens)`), "token_ceiling"));
167
+ return;
168
+ }
169
+ }
170
+ stdout.push(Buffer.from(`${line}\n`));
171
+ }
172
+ stdoutBytes = stdout.reduce((total, part) => total + part.length, 0);
173
+ if (stdoutBytes > CLI_ENGINE_MAX_OUTPUT_BYTES) {
174
+ abort(tagCliChildFailure(new Error(`CLI engine output exceeded ${CLI_ENGINE_MAX_OUTPUT_BYTES} bytes`), "output_limit"));
175
+ return;
176
+ }
177
+ }
178
+ if (stdoutRemainder.length > CLI_ENGINE_MAX_OUTPUT_BYTES) {
179
+ const prefix = stdoutRemainder.subarray(0, Math.min(stdoutRemainder.length, 4096)).toString("utf8");
180
+ if (/"type"\s*:\s*"item\.completed"/u.test(prefix)
181
+ && !/"type"\s*:\s*"agent_message"/u.test(prefix)) {
182
+ const toolType = prefix.match(/"type"\s*:\s*"(command_execution|mcp_tool_call)"/u)?.[1];
183
+ if (toolType !== undefined) {
184
+ ndjsonCalls += 1;
185
+ stdout.push(Buffer.from(`${JSON.stringify({ type: "item.completed", item: { type: toolType } })}\n`));
186
+ }
187
+ stdoutRemainder = Buffer.alloc(0);
188
+ droppingNdjsonLine = true;
189
+ }
190
+ else
191
+ abort(tagCliChildFailure(new Error(`CLI engine output exceeded ${CLI_ENGINE_MAX_OUTPUT_BYTES} bytes`), "output_limit"));
192
+ }
193
+ return;
194
+ }
195
+ if (options.retainStdoutTail === true) {
196
+ let remainder = value;
197
+ if (droppingStdoutLine) {
198
+ const newline = remainder.indexOf(0x0a);
199
+ if (newline < 0)
200
+ return;
201
+ droppingStdoutLine = false;
202
+ remainder = remainder.subarray(newline + 1);
203
+ }
204
+ const combined = Buffer.concat([stdoutTail, remainder]);
205
+ if (combined.length <= CLI_ENGINE_MAX_OUTPUT_BYTES) {
206
+ stdoutTail = combined;
207
+ return;
208
+ }
209
+ const overflow = combined.length - CLI_ENGINE_MAX_OUTPUT_BYTES;
210
+ if (combined[overflow - 1] === 0x0a) {
211
+ stdoutTail = Buffer.from(combined.subarray(overflow));
212
+ return;
213
+ }
214
+ const newline = combined.indexOf(0x0a, overflow);
215
+ stdoutTail = newline < 0 ? Buffer.alloc(0) : Buffer.from(combined.subarray(newline + 1));
216
+ droppingStdoutLine = newline < 0;
217
+ return;
218
+ }
219
+ stdoutBytes += value.length;
220
+ if (stdoutBytes > CLI_ENGINE_MAX_OUTPUT_BYTES) {
221
+ abort(tagCliChildFailure(new Error(`CLI engine output exceeded ${CLI_ENGINE_MAX_OUTPUT_BYTES} bytes`), "output_limit"));
222
+ return;
223
+ }
224
+ stdout.push(value);
225
+ };
226
+ const retainStderrWindow = (chunk) => {
227
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
228
+ classifyFailure(value);
229
+ stderrBytes += value.length;
230
+ if (stderrHead.length < stderrHeadBytes)
231
+ stderrHead = Buffer.concat([stderrHead, value.subarray(0, stderrHeadBytes - stderrHead.length)]);
232
+ if (value.length >= stderrTailBytes) {
233
+ stderrTail = Buffer.from(value.subarray(value.length - stderrTailBytes));
234
+ return;
235
+ }
236
+ const overflow = stderrTail.length + value.length - stderrTailBytes;
237
+ stderrTail = Buffer.concat([overflow > 0 ? stderrTail.subarray(overflow) : stderrTail, value]);
238
+ };
239
+ /**
240
+ * The retained stderr, reassembled exactly.
241
+ *
242
+ * Nothing was elided while the whole output fitted the budget, and then the
243
+ * two ends overlap: they tile the stream, so dropping the overlap from the
244
+ * tail rebuilds it byte-identically. Above the budget the ends are joined by
245
+ * the marker, which names how many bytes never reached this process at all.
246
+ */
247
+ const retainedStderr = () => {
248
+ const elided = stderrBytes - stderrHead.length - stderrTail.length;
249
+ if (elided <= 0)
250
+ return Buffer.concat([stderrHead, stderrTail.subarray(stderrHead.length + stderrTail.length - stderrBytes)]).toString("utf8");
251
+ return `${stderrHead.toString("utf8")}${elisionMarker(elided)}${stderrTail.toString("utf8")}`;
252
+ };
253
+ child.stdout?.on("data", retainStdout);
254
+ child.stderr?.on("data", retainStderrWindow);
255
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => abort(tagCliChildFailure(new Error(options.timeoutErrorMessage ?? "CLI engine timed out"), "wake_timeout")), timeoutMs);
256
+ child.once("error", abort);
257
+ child.once("close", (code, signal) => {
258
+ if (cleanupStarted)
259
+ return;
260
+ if (options.retainNdjson !== undefined && stdoutRemainder.length > 0)
261
+ stdout.push(stdoutRemainder);
262
+ const retainedStdout = options.retainStdoutTail === true ? stdoutTail : Buffer.concat(stdout);
263
+ if (code === 0) {
264
+ settle(() => resolve(redactChildOutput(retainedStdout.toString("utf8"), secretValues).trim()));
265
+ return;
266
+ }
267
+ settle(() => reject(tagCliChildFailure(classifiedFailure ?? new Error(`CLI engine exited ${code ?? signal}${childDiagnostic(retainedStdout.toString("utf8"), retainedStderr(), secretValues)}`), "engine_exit")));
268
+ });
269
+ });
@@ -0,0 +1,16 @@
1
+ import { type CliEngineKind } from "./cliSession.js";
2
+ export interface EngineRunResult {
3
+ readonly durationMs: number;
4
+ readonly outputChars: number;
5
+ readonly promptChars: number;
6
+ readonly text: string;
7
+ }
8
+ export declare const runEngineDetailed: (engine: CliEngineKind, prompt: string, paths: {
9
+ readonly workspacePath: string;
10
+ readonly runtimeHomePath?: string;
11
+ }) => Promise<EngineRunResult>;
12
+ export declare const runEngine: (engine: CliEngineKind, prompt: string, paths: {
13
+ readonly workspacePath: string;
14
+ readonly runtimeHomePath?: string;
15
+ }) => Promise<string>;
16
+ //# sourceMappingURL=cliEngineRun.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cliEngineRun.d.ts","sourceRoot":"","sources":["../../src/pi/cliEngineRun.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+C,KAAK,aAAa,EAAyB,MAAM,iBAAiB,CAAC;AAEzH,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,eAAO,MAAM,iBAAiB,GAC5B,QAAQ,aAAa,EACrB,QAAQ,MAAM,EACd,OAAO;IAAE,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAA;CAAE,KAC3E,OAAO,CAAC,eAAe,CAsBzB,CAAC;AAEF,eAAO,MAAM,SAAS,GACpB,QAAQ,aAAa,EACrB,QAAQ,MAAM,EACd,OAAO;IAAE,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAA;CAAE,KAC3E,OAAO,CAAC,MAAM,CAA0D,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { AGY_MAX_TOOL_TURNS, createCliSessionFactory } from "./cliSession.js";
2
+ export const runEngineDetailed = async (engine, prompt, paths) => {
3
+ const startedAt = Date.now();
4
+ const options = engine === "agy"
5
+ ? { engine, maxToolTurns: AGY_MAX_TOOL_TURNS, timeoutMs: 180_000 }
6
+ : { engine };
7
+ const { session } = await createCliSessionFactory(options)({
8
+ cwd: paths.workspacePath,
9
+ runtimeHomePath: paths.runtimeHomePath
10
+ });
11
+ let text = "";
12
+ const unsubscribe = session.subscribe((event) => {
13
+ if (event.type !== "turn_end")
14
+ return;
15
+ if (!("content" in event.message))
16
+ return;
17
+ text = Array.isArray(event.message.content)
18
+ ? event.message.content.filter((entry) => entry.type === "text").map((entry) => entry.text).join("")
19
+ : event.message.content;
20
+ });
21
+ await session.prompt(prompt);
22
+ unsubscribe();
23
+ session.dispose();
24
+ await session.disposeAsync?.();
25
+ return { durationMs: Date.now() - startedAt, outputChars: text.length, promptChars: prompt.length, text };
26
+ };
27
+ export const runEngine = async (engine, prompt, paths) => (await runEngineDetailed(engine, prompt, paths)).text;
@@ -0,0 +1,55 @@
1
+ import { type ChildProcess } from "node:child_process";
2
+ import type { CliEngineOptions, CliSessionInput } from "./cliSession.js";
3
+ export declare const GROK_STRICT_SANDBOX_PROFILE = "strict";
4
+ export declare const renderGrokSandboxArgs: (commandArgs: readonly string[] | undefined, profile: string) => string[];
5
+ /**
6
+ * Codex's `--json` stream is unconditional: it is the only output shape that
7
+ * carries `turn.completed.usage`, and an unmetered Codex turn is one whose
8
+ * subscription cost is invisible. The guarded arguments make this Daimon's
9
+ * security and metering boundary rather than a caller-controlled format.
10
+ *
11
+ * `model`/`reasoningEffort` come from parsed, bounded organization-runtime
12
+ * config, but are rendered defensively anyway: each is emitted as a single
13
+ * `--flag=value` argv token (never a bare flag followed by a separate value
14
+ * token), so a value that itself looks like a flag (e.g. `--sandbox`) can
15
+ * never be parsed as a second, independent argument — the same shape already
16
+ * used below for `mcp_servers.daimon.url=`. Omitting both fields leaves Codex's
17
+ * model defaults unchanged.
18
+ *
19
+ * The per-wake MCP server is always enabled and required. Otherwise Codex can
20
+ * continue a normal turn with only built-in tools after MCP startup fails.
21
+ * Subscription apps and installed plugins are not caller-declared tools.
22
+ * Disable their discovery per invocation, including with strict config: the
23
+ * CLI's defaults can otherwise add them even when user config is ignored.
24
+ */
25
+ export declare const renderCodexArgs: (options: Pick<CliEngineOptions, "commandArgs" | "model" | "reasoningEffort" | "codexSandbox" | "codexSandboxProtectedPaths" | "codexSandboxReadablePaths">, cwd: string, endpoint: string | undefined, sandbox?: string) => string[];
26
+ export declare const renderCodexPermissionProfile: (profileName: string, protectedPaths: readonly string[], readablePaths?: readonly string[], workspacePath?: string) => string;
27
+ /**
28
+ * AGY's headless invocation.
29
+ *
30
+ * `--output-format stream-json` is unconditional: it is the only shape that
31
+ * carries `result.usage`, and an AGY turn that is not metered is an AGY turn
32
+ * whose subscription cost is invisible (see `agyHeadlessResult.ts`).
33
+ *
34
+ * `--dangerously-skip-permissions` is required for tools to work at all. AGY's
35
+ * default headless permission mode is `request-review`, and there is no
36
+ * reviewer inside a container, so a tool call can never be approved without it;
37
+ * the live probe that proved AGY's MCP tool calling ran with exactly this flag
38
+ * and reported `permission_mode: always-proceed`. Every Daimon CLI agent mounts
39
+ * at least the protected bash tool (`piHarness.ts`), so there is no AGY wake
40
+ * for which this is unnecessary and no conditional worth forking behavior over.
41
+ *
42
+ * SECURITY: the flag also auto-approves AGY's own ~50 built-in tools —
43
+ * `run_command`, `write_to_file`, the browser tools — none of which Daimon
44
+ * mediates. Inside the container that is the exposure Codex already has
45
+ * (`--sandbox danger-full-access`), but unlike Grok there is no kernel-enforced
46
+ * per-agent profile confining it to this agent's own workspace and runtime
47
+ * home. `DAIMON_AGY_SANDBOX=1` opts into AGY's own terminal-restricting
48
+ * sandbox; it is off by default only because its interaction with the MCP
49
+ * transport could not be verified without spending the operator's subscription
50
+ * quota, and shipping an unverified default that silently disables every tool
51
+ * would be worse than shipping the exposure with this note on it.
52
+ */
53
+ export declare const renderAgyArgs: (options: Pick<CliEngineOptions, "commandArgs" | "timeoutMs">, prompt: string, sandbox?: boolean) => string[];
54
+ export declare const spawnEngine: (options: CliEngineOptions, prompt: string, input: CliSessionInput, endpoint: string | undefined, wakeId?: string) => ChildProcess;
55
+ //# sourceMappingURL=cliEngineSpawn.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cliEngineSpawn.d.ts","sourceRoot":"","sources":["../../src/pi/cliEngineSpawn.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAK9D,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEzE,eAAO,MAAM,2BAA2B,WAAW,CAAC;AAEpD,eAAO,MAAM,qBAAqB,GAChC,aAAa,SAAS,MAAM,EAAE,GAAG,SAAS,EAC1C,SAAS,MAAM,KACd,MAAM,EAAuE,CAAC;AAEjF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,eAAe,GAC1B,SAAS,IAAI,CAAC,gBAAgB,EAAE,aAAa,GAAG,OAAO,GAAG,iBAAiB,GAAG,cAAc,GAAG,4BAA4B,GAAG,2BAA2B,CAAC,EAC1J,KAAK,MAAM,EACX,UAAU,MAAM,GAAG,SAAS,EAC5B,UAAS,MAA+F,KACvG,MAAM,EAyBR,CAAC;AAEF,eAAO,MAAM,4BAA4B,GACvC,aAAa,MAAM,EACnB,gBAAgB,SAAS,MAAM,EAAE,EACjC,gBAAe,SAAS,MAAM,EAAO,EACrC,gBAAgB,MAAM,KACrB,MAUF,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,aAAa,GACxB,SAAS,IAAI,CAAC,gBAAgB,EAAE,aAAa,GAAG,WAAW,CAAC,EAC5D,QAAQ,MAAM,EACd,UAAS,OAAgD,KACxD,MAAM,EAOR,CAAC;AAEF,eAAO,MAAM,WAAW,GACtB,SAAS,gBAAgB,EACzB,QAAQ,MAAM,EACd,OAAO,eAAe,EACtB,UAAU,MAAM,GAAG,SAAS,EAC5B,SAAS,MAAM,KACd,YAyBF,CAAC"}