@noopolis/daimon 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (422) hide show
  1. package/README.md +275 -51
  2. package/dist/contracts/attentionContract.d.ts +142 -0
  3. package/dist/contracts/attentionContract.d.ts.map +1 -0
  4. package/dist/contracts/attentionContract.js +21 -0
  5. package/dist/contracts/canonicalJson.d.ts +3 -0
  6. package/dist/contracts/canonicalJson.d.ts.map +1 -0
  7. package/dist/contracts/canonicalJson.js +54 -0
  8. package/dist/contracts/grokBrokerTaskClock.d.ts +18 -0
  9. package/dist/contracts/grokBrokerTaskClock.d.ts.map +1 -0
  10. package/dist/contracts/grokBrokerTaskClock.js +16 -0
  11. package/dist/contracts/grokWorkerContract.d.ts +74 -0
  12. package/dist/contracts/grokWorkerContract.d.ts.map +1 -0
  13. package/dist/contracts/grokWorkerContract.js +88 -0
  14. package/dist/contracts/organizationRuntimeContract.d.ts +841 -0
  15. package/dist/contracts/organizationRuntimeContract.d.ts.map +1 -0
  16. package/dist/contracts/organizationRuntimeContract.js +123 -0
  17. package/dist/contracts/runtimeContractManifest.d.ts +1822 -0
  18. package/dist/contracts/runtimeContractManifest.d.ts.map +1 -0
  19. package/dist/contracts/runtimeContractManifest.js +206 -0
  20. package/dist/contracts/shellEnvironmentPolicy.d.ts +3 -0
  21. package/dist/contracts/shellEnvironmentPolicy.d.ts.map +1 -0
  22. package/dist/contracts/shellEnvironmentPolicy.js +5 -0
  23. package/dist/contracts/wakeMomentContract.d.ts +61 -0
  24. package/dist/contracts/wakeMomentContract.d.ts.map +1 -0
  25. package/dist/contracts/wakeMomentContract.js +27 -0
  26. package/dist/core/credentialRedaction.d.ts +4 -0
  27. package/dist/core/credentialRedaction.d.ts.map +1 -0
  28. package/dist/core/credentialRedaction.js +28 -0
  29. package/dist/core/types.d.ts +2 -0
  30. package/dist/core/types.d.ts.map +1 -1
  31. package/dist/examples/jungianPlayAgent.d.ts +1 -0
  32. package/dist/examples/jungianPlayAgent.d.ts.map +1 -1
  33. package/dist/examples/jungianPlayAgent.js +6 -2
  34. package/dist/mcp/toolServer.d.ts +19 -2
  35. package/dist/mcp/toolServer.d.ts.map +1 -1
  36. package/dist/mcp/toolServer.js +57 -17
  37. package/dist/observability/causalEvents.d.ts +6 -6
  38. package/dist/observability/causalEvents.d.ts.map +1 -1
  39. package/dist/observability/causalEvents.js +107 -19
  40. package/dist/observability/orgObserver.d.ts.map +1 -1
  41. package/dist/observability/orgObserver.js +3 -3
  42. package/dist/pi/agyHeadlessResult.d.ts +60 -0
  43. package/dist/pi/agyHeadlessResult.d.ts.map +1 -0
  44. package/dist/pi/agyHeadlessResult.js +95 -0
  45. package/dist/pi/cliChildOutput.d.ts +67 -0
  46. package/dist/pi/cliChildOutput.d.ts.map +1 -0
  47. package/dist/pi/cliChildOutput.js +269 -0
  48. package/dist/pi/cliEngineRun.d.ts +16 -0
  49. package/dist/pi/cliEngineRun.d.ts.map +1 -0
  50. package/dist/pi/cliEngineRun.js +27 -0
  51. package/dist/pi/cliEngineSpawn.d.ts +55 -0
  52. package/dist/pi/cliEngineSpawn.d.ts.map +1 -0
  53. package/dist/pi/cliEngineSpawn.js +169 -0
  54. package/dist/pi/cliEnvironment.d.ts +12 -0
  55. package/dist/pi/cliEnvironment.d.ts.map +1 -0
  56. package/dist/pi/cliEnvironment.js +34 -0
  57. package/dist/pi/cliMcpRegistration.d.ts +61 -0
  58. package/dist/pi/cliMcpRegistration.d.ts.map +1 -0
  59. package/dist/pi/cliMcpRegistration.js +75 -0
  60. package/dist/pi/cliProcess.d.ts +7 -0
  61. package/dist/pi/cliProcess.d.ts.map +1 -0
  62. package/dist/pi/cliProcess.js +132 -0
  63. package/dist/pi/cliSession.d.ts +86 -24
  64. package/dist/pi/cliSession.d.ts.map +1 -1
  65. package/dist/pi/cliSession.js +251 -173
  66. package/dist/pi/cliSessionMcp.d.ts +9 -0
  67. package/dist/pi/cliSessionMcp.d.ts.map +1 -0
  68. package/dist/pi/cliSessionMcp.js +80 -0
  69. package/dist/pi/cliTurnMetering.d.ts +60 -0
  70. package/dist/pi/cliTurnMetering.d.ts.map +1 -0
  71. package/dist/pi/cliTurnMetering.js +60 -0
  72. package/dist/pi/codexFilesystemRules.d.ts +3 -0
  73. package/dist/pi/codexFilesystemRules.d.ts.map +1 -0
  74. package/dist/pi/codexFilesystemRules.js +28 -0
  75. package/dist/pi/codexHeadlessResult.d.ts +68 -0
  76. package/dist/pi/codexHeadlessResult.d.ts.map +1 -0
  77. package/dist/pi/codexHeadlessResult.js +122 -0
  78. package/dist/pi/codexRolloutUsage.d.ts +95 -0
  79. package/dist/pi/codexRolloutUsage.d.ts.map +1 -0
  80. package/dist/pi/codexRolloutUsage.js +221 -0
  81. package/dist/pi/engineTaskClock.d.ts +9 -0
  82. package/dist/pi/engineTaskClock.d.ts.map +1 -0
  83. package/dist/pi/engineTaskClock.js +28 -0
  84. package/dist/pi/engineWakeLimits.d.ts +39 -0
  85. package/dist/pi/engineWakeLimits.d.ts.map +1 -0
  86. package/dist/pi/engineWakeLimits.js +55 -0
  87. package/dist/pi/grokHeadlessResult.d.ts +36 -0
  88. package/dist/pi/grokHeadlessResult.d.ts.map +1 -0
  89. package/dist/pi/grokHeadlessResult.js +118 -0
  90. package/dist/pi/grokHomeMcpRegistration.d.ts +21 -0
  91. package/dist/pi/grokHomeMcpRegistration.d.ts.map +1 -0
  92. package/dist/pi/grokHomeMcpRegistration.js +58 -0
  93. package/dist/pi/grokSandbox.d.ts +11 -0
  94. package/dist/pi/grokSandbox.d.ts.map +1 -0
  95. package/dist/pi/grokSandbox.js +216 -0
  96. package/dist/pi/grokStreamUsage.d.ts +31 -0
  97. package/dist/pi/grokStreamUsage.d.ts.map +1 -0
  98. package/dist/pi/grokStreamUsage.js +51 -0
  99. package/dist/pi/memoryClock.d.ts +25 -0
  100. package/dist/pi/memoryClock.d.ts.map +1 -0
  101. package/dist/pi/memoryClock.js +18 -0
  102. package/dist/pi/piAgentHandle.d.ts +6 -3
  103. package/dist/pi/piAgentHandle.d.ts.map +1 -1
  104. package/dist/pi/piAgentHandle.js +42 -12
  105. package/dist/pi/piAgentWakeSupport.d.ts +35 -0
  106. package/dist/pi/piAgentWakeSupport.d.ts.map +1 -1
  107. package/dist/pi/piAgentWakeSupport.js +4 -0
  108. package/dist/pi/piHarness.d.ts +18 -3
  109. package/dist/pi/piHarness.d.ts.map +1 -1
  110. package/dist/pi/piHarness.js +83 -14
  111. package/dist/pi/prompts.d.ts +1 -0
  112. package/dist/pi/prompts.d.ts.map +1 -1
  113. package/dist/pi/prompts.js +24 -0
  114. package/dist/pi/taskClockProcess.d.ts +6 -0
  115. package/dist/pi/taskClockProcess.d.ts.map +1 -0
  116. package/dist/pi/taskClockProcess.js +8 -0
  117. package/dist/pi/turnCausal.d.ts +4 -2
  118. package/dist/pi/turnCausal.d.ts.map +1 -1
  119. package/dist/pi/turnCausal.js +4 -4
  120. package/dist/pi/turnTrace.d.ts.map +1 -1
  121. package/dist/pi/turnTrace.js +5 -8
  122. package/dist/pi/wakeAcceptance.d.ts +1 -1
  123. package/dist/pi/wakeAcceptance.d.ts.map +1 -1
  124. package/dist/pi/wakeAcceptance.js +2 -2
  125. package/dist/pi/worldTrajectory.d.ts +1 -1
  126. package/dist/pi/worldTrajectory.d.ts.map +1 -1
  127. package/dist/pi/worldTrajectory.js +3 -3
  128. package/dist/runtime/agySubscriptionBootstrap.d.ts +16 -0
  129. package/dist/runtime/agySubscriptionBootstrap.d.ts.map +1 -0
  130. package/dist/runtime/agySubscriptionBootstrap.js +80 -0
  131. package/dist/runtime/agySubscriptionRealm.d.ts +38 -0
  132. package/dist/runtime/agySubscriptionRealm.d.ts.map +1 -0
  133. package/dist/runtime/agySubscriptionRealm.js +242 -0
  134. package/dist/runtime/attention.d.ts +26 -0
  135. package/dist/runtime/attention.d.ts.map +1 -0
  136. package/dist/runtime/attention.js +49 -0
  137. package/dist/runtime/attentionDispatcher.d.ts +78 -0
  138. package/dist/runtime/attentionDispatcher.d.ts.map +1 -0
  139. package/dist/runtime/attentionDispatcher.js +365 -0
  140. package/dist/runtime/cli.d.ts +7 -0
  141. package/dist/runtime/cli.d.ts.map +1 -0
  142. package/dist/runtime/cli.js +256 -0
  143. package/dist/runtime/codexSandboxProjection.d.ts +17 -0
  144. package/dist/runtime/codexSandboxProjection.d.ts.map +1 -0
  145. package/dist/runtime/codexSandboxProjection.js +40 -0
  146. package/dist/runtime/contract-manifest.json +1 -0
  147. package/dist/runtime/contract-manifest.sha256 +1 -0
  148. package/dist/runtime/contractManifest.d.ts +8 -0
  149. package/dist/runtime/contractManifest.d.ts.map +1 -0
  150. package/dist/runtime/contractManifest.js +4 -0
  151. package/dist/runtime/engineBrokerCapabilities.d.ts +40 -0
  152. package/dist/runtime/engineBrokerCapabilities.d.ts.map +1 -0
  153. package/dist/runtime/engineBrokerCapabilities.js +69 -0
  154. package/dist/runtime/engineBrokerControlClient.d.ts +55 -0
  155. package/dist/runtime/engineBrokerControlClient.d.ts.map +1 -0
  156. package/dist/runtime/engineBrokerControlClient.js +228 -0
  157. package/dist/runtime/engineBrokerCredentialJournal.d.ts +12 -0
  158. package/dist/runtime/engineBrokerCredentialJournal.d.ts.map +1 -0
  159. package/dist/runtime/engineBrokerCredentialJournal.js +26 -0
  160. package/dist/runtime/engineBrokerInferenceProtocol.d.ts +53 -0
  161. package/dist/runtime/engineBrokerInferenceProtocol.d.ts.map +1 -0
  162. package/dist/runtime/engineBrokerInferenceProtocol.js +65 -0
  163. package/dist/runtime/engineBrokerMcpCallLog.d.ts +171 -0
  164. package/dist/runtime/engineBrokerMcpCallLog.d.ts.map +1 -0
  165. package/dist/runtime/engineBrokerMcpCallLog.js +231 -0
  166. package/dist/runtime/engineBrokerMcpFacade.d.ts +59 -0
  167. package/dist/runtime/engineBrokerMcpFacade.d.ts.map +1 -0
  168. package/dist/runtime/engineBrokerMcpFacade.js +346 -0
  169. package/dist/runtime/engineBrokerNativeClient.d.ts +52 -0
  170. package/dist/runtime/engineBrokerNativeClient.d.ts.map +1 -0
  171. package/dist/runtime/engineBrokerNativeClient.js +151 -0
  172. package/dist/runtime/engineBrokerProtocol.d.ts +167 -0
  173. package/dist/runtime/engineBrokerProtocol.d.ts.map +1 -0
  174. package/dist/runtime/engineBrokerProtocol.js +357 -0
  175. package/dist/runtime/engineBrokerSealLedger.d.ts +70 -0
  176. package/dist/runtime/engineBrokerSealLedger.d.ts.map +1 -0
  177. package/dist/runtime/engineBrokerSealLedger.js +132 -0
  178. package/dist/runtime/engineBrokerService.d.ts +43 -0
  179. package/dist/runtime/engineBrokerService.d.ts.map +1 -0
  180. package/dist/runtime/engineBrokerService.js +196 -0
  181. package/dist/runtime/engineBrokerServiceCli.d.ts +5 -0
  182. package/dist/runtime/engineBrokerServiceCli.d.ts.map +1 -0
  183. package/dist/runtime/engineBrokerServiceCli.js +32 -0
  184. package/dist/runtime/engineBrokerServiceConfig.d.ts +55 -0
  185. package/dist/runtime/engineBrokerServiceConfig.d.ts.map +1 -0
  186. package/dist/runtime/engineBrokerServiceConfig.js +130 -0
  187. package/dist/runtime/engineBrokerSingleflight.d.ts +13 -0
  188. package/dist/runtime/engineBrokerSingleflight.d.ts.map +1 -0
  189. package/dist/runtime/engineBrokerSingleflight.js +24 -0
  190. package/dist/runtime/engineBrokerTurnAccounting.d.ts +76 -0
  191. package/dist/runtime/engineBrokerTurnAccounting.d.ts.map +1 -0
  192. package/dist/runtime/engineBrokerTurnAccounting.js +108 -0
  193. package/dist/runtime/engineBrokerTurnRegistry.d.ts +57 -0
  194. package/dist/runtime/engineBrokerTurnRegistry.d.ts.map +1 -0
  195. package/dist/runtime/engineBrokerTurnRegistry.js +159 -0
  196. package/dist/runtime/engineDispatcher.d.ts +38 -0
  197. package/dist/runtime/engineDispatcher.d.ts.map +1 -0
  198. package/dist/runtime/engineDispatcher.js +228 -0
  199. package/dist/runtime/engineReadiness.d.ts +23 -0
  200. package/dist/runtime/engineReadiness.d.ts.map +1 -0
  201. package/dist/runtime/engineReadiness.js +222 -0
  202. package/dist/runtime/grokAuthenticationError.d.ts +8 -0
  203. package/dist/runtime/grokAuthenticationError.d.ts.map +1 -0
  204. package/dist/runtime/grokAuthenticationError.js +20 -0
  205. package/dist/runtime/grokBrokerCredentialAuthority.d.ts +23 -0
  206. package/dist/runtime/grokBrokerCredentialAuthority.d.ts.map +1 -0
  207. package/dist/runtime/grokBrokerCredentialAuthority.js +150 -0
  208. package/dist/runtime/grokBrokerCredentialReader.d.ts +6 -0
  209. package/dist/runtime/grokBrokerCredentialReader.d.ts.map +1 -0
  210. package/dist/runtime/grokBrokerCredentialReader.js +38 -0
  211. package/dist/runtime/grokBrokerModelPolicy.d.ts +23 -0
  212. package/dist/runtime/grokBrokerModelPolicy.d.ts.map +1 -0
  213. package/dist/runtime/grokBrokerModelPolicy.js +28 -0
  214. package/dist/runtime/grokBrokerProjection.d.ts +114 -0
  215. package/dist/runtime/grokBrokerProjection.d.ts.map +1 -0
  216. package/dist/runtime/grokBrokerProjection.js +101 -0
  217. package/dist/runtime/grokBrokerProviderClock.d.ts +26 -0
  218. package/dist/runtime/grokBrokerProviderClock.d.ts.map +1 -0
  219. package/dist/runtime/grokBrokerProviderClock.js +133 -0
  220. package/dist/runtime/grokBrokerProxy.d.ts +69 -0
  221. package/dist/runtime/grokBrokerProxy.d.ts.map +1 -0
  222. package/dist/runtime/grokBrokerProxy.js +326 -0
  223. package/dist/runtime/grokBrokerProxyJson.d.ts +10 -0
  224. package/dist/runtime/grokBrokerProxyJson.d.ts.map +1 -0
  225. package/dist/runtime/grokBrokerProxyJson.js +31 -0
  226. package/dist/runtime/grokBrokerProxyRequest.d.ts +30 -0
  227. package/dist/runtime/grokBrokerProxyRequest.d.ts.map +1 -0
  228. package/dist/runtime/grokBrokerProxyRequest.js +85 -0
  229. package/dist/runtime/grokBrokerRealmLease.d.ts +4 -0
  230. package/dist/runtime/grokBrokerRealmLease.d.ts.map +1 -0
  231. package/dist/runtime/grokBrokerRealmLease.js +33 -0
  232. package/dist/runtime/grokBrokerRefresh.d.ts +2 -0
  233. package/dist/runtime/grokBrokerRefresh.d.ts.map +1 -0
  234. package/dist/runtime/grokBrokerRefresh.js +15 -0
  235. package/dist/runtime/grokBrokerRunBudget.d.ts +20 -0
  236. package/dist/runtime/grokBrokerRunBudget.d.ts.map +1 -0
  237. package/dist/runtime/grokBrokerRunBudget.js +85 -0
  238. package/dist/runtime/grokBrokerSlot.d.ts +6 -0
  239. package/dist/runtime/grokBrokerSlot.d.ts.map +1 -0
  240. package/dist/runtime/grokBrokerSlot.js +21 -0
  241. package/dist/runtime/grokBrokerTaskClock.d.ts +32 -0
  242. package/dist/runtime/grokBrokerTaskClock.d.ts.map +1 -0
  243. package/dist/runtime/grokBrokerTaskClock.js +120 -0
  244. package/dist/runtime/grokBrokerTurnMeter.d.ts +180 -0
  245. package/dist/runtime/grokBrokerTurnMeter.d.ts.map +1 -0
  246. package/dist/runtime/grokBrokerTurnMeter.js +337 -0
  247. package/dist/runtime/grokBrokerWorkerConfig.d.ts +89 -0
  248. package/dist/runtime/grokBrokerWorkerConfig.d.ts.map +1 -0
  249. package/dist/runtime/grokBrokerWorkerConfig.js +154 -0
  250. package/dist/runtime/grokEngineBroker.d.ts +88 -0
  251. package/dist/runtime/grokEngineBroker.d.ts.map +1 -0
  252. package/dist/runtime/grokEngineBroker.js +202 -0
  253. package/dist/runtime/grokEngineBrokerLedger.d.ts +52 -0
  254. package/dist/runtime/grokEngineBrokerLedger.d.ts.map +1 -0
  255. package/dist/runtime/grokEngineBrokerLedger.js +114 -0
  256. package/dist/runtime/grokEngineBrokerMetering.d.ts +51 -0
  257. package/dist/runtime/grokEngineBrokerMetering.d.ts.map +1 -0
  258. package/dist/runtime/grokEngineBrokerMetering.js +34 -0
  259. package/dist/runtime/grokEngineBrokerTurn.d.ts +82 -0
  260. package/dist/runtime/grokEngineBrokerTurn.d.ts.map +1 -0
  261. package/dist/runtime/grokEngineBrokerTurn.js +348 -0
  262. package/dist/runtime/grokEngineBrokerTurnEnd.d.ts +88 -0
  263. package/dist/runtime/grokEngineBrokerTurnEnd.d.ts.map +1 -0
  264. package/dist/runtime/grokEngineBrokerTurnEnd.js +148 -0
  265. package/dist/runtime/grokInferenceClientConfig.d.ts +41 -0
  266. package/dist/runtime/grokInferenceClientConfig.d.ts.map +1 -0
  267. package/dist/runtime/grokInferenceClientConfig.js +62 -0
  268. package/dist/runtime/grokInferenceGrants.d.ts +77 -0
  269. package/dist/runtime/grokInferenceGrants.d.ts.map +1 -0
  270. package/dist/runtime/grokInferenceGrants.js +116 -0
  271. package/dist/runtime/grokInferenceProxy.d.ts +29 -0
  272. package/dist/runtime/grokInferenceProxy.d.ts.map +1 -0
  273. package/dist/runtime/grokInferenceProxy.js +85 -0
  274. package/dist/runtime/grokInferenceProxyRequest.d.ts +23 -0
  275. package/dist/runtime/grokInferenceProxyRequest.d.ts.map +1 -0
  276. package/dist/runtime/grokInferenceProxyRequest.js +63 -0
  277. package/dist/runtime/grokSlotPreflightReceipt.d.ts +70 -0
  278. package/dist/runtime/grokSlotPreflightReceipt.d.ts.map +1 -0
  279. package/dist/runtime/grokSlotPreflightReceipt.js +101 -0
  280. package/dist/runtime/grokSubscriptionRealm.d.ts +4 -0
  281. package/dist/runtime/grokSubscriptionRealm.d.ts.map +1 -0
  282. package/dist/runtime/grokSubscriptionRealm.js +435 -0
  283. package/dist/runtime/grokSubscriptionRealmTypes.d.ts +26 -0
  284. package/dist/runtime/grokSubscriptionRealmTypes.d.ts.map +1 -0
  285. package/dist/runtime/grokSubscriptionRealmTypes.js +1 -0
  286. package/dist/runtime/grokWorkerAttestation.d.ts +175 -0
  287. package/dist/runtime/grokWorkerAttestation.d.ts.map +1 -0
  288. package/dist/runtime/grokWorkerAttestation.js +266 -0
  289. package/dist/runtime/grokWorkerDenyPlacement.d.ts +80 -0
  290. package/dist/runtime/grokWorkerDenyPlacement.d.ts.map +1 -0
  291. package/dist/runtime/grokWorkerDenyPlacement.js +128 -0
  292. package/dist/runtime/grokWorkerHomeAttestation.d.ts +32 -0
  293. package/dist/runtime/grokWorkerHomeAttestation.d.ts.map +1 -0
  294. package/dist/runtime/grokWorkerHomeAttestation.js +75 -0
  295. package/dist/runtime/grokWorkerSandboxProfile.d.ts +27 -0
  296. package/dist/runtime/grokWorkerSandboxProfile.d.ts.map +1 -0
  297. package/dist/runtime/grokWorkerSandboxProfile.js +44 -0
  298. package/dist/runtime/grokWorkerTmpAttestation.d.ts +55 -0
  299. package/dist/runtime/grokWorkerTmpAttestation.d.ts.map +1 -0
  300. package/dist/runtime/grokWorkerTmpAttestation.js +63 -0
  301. package/dist/runtime/index.d.ts +31 -0
  302. package/dist/runtime/index.d.ts.map +1 -0
  303. package/dist/runtime/index.js +27 -0
  304. package/dist/runtime/inferenceUsageLedger.d.ts +38 -0
  305. package/dist/runtime/inferenceUsageLedger.d.ts.map +1 -0
  306. package/dist/runtime/inferenceUsageLedger.js +53 -0
  307. package/dist/runtime/mcpToolResult.d.ts +127 -0
  308. package/dist/runtime/mcpToolResult.d.ts.map +1 -0
  309. package/dist/runtime/mcpToolResult.js +214 -0
  310. package/dist/runtime/moltnetMachineRead.d.ts +97 -0
  311. package/dist/runtime/moltnetMachineRead.d.ts.map +1 -0
  312. package/dist/runtime/moltnetMachineRead.js +183 -0
  313. package/dist/runtime/native/daimon-engine-broker +0 -0
  314. package/dist/runtime/organizationRuntime.d.ts +168 -0
  315. package/dist/runtime/organizationRuntime.d.ts.map +1 -0
  316. package/dist/runtime/organizationRuntime.js +3 -0
  317. package/dist/runtime/organizationRuntimeAdmission.d.ts +6 -0
  318. package/dist/runtime/organizationRuntimeAdmission.d.ts.map +1 -0
  319. package/dist/runtime/organizationRuntimeAdmission.js +22 -0
  320. package/dist/runtime/organizationRuntimeControl.d.ts +51 -0
  321. package/dist/runtime/organizationRuntimeControl.d.ts.map +1 -0
  322. package/dist/runtime/organizationRuntimeControl.js +283 -0
  323. package/dist/runtime/organizationRuntimeHost.d.ts +19 -0
  324. package/dist/runtime/organizationRuntimeHost.d.ts.map +1 -0
  325. package/dist/runtime/organizationRuntimeHost.js +368 -0
  326. package/dist/runtime/organizationRuntimeParsing.d.ts +6 -0
  327. package/dist/runtime/organizationRuntimeParsing.d.ts.map +1 -0
  328. package/dist/runtime/organizationRuntimeParsing.js +373 -0
  329. package/dist/runtime/organizationRuntimeReadiness.d.ts +12 -0
  330. package/dist/runtime/organizationRuntimeReadiness.d.ts.map +1 -0
  331. package/dist/runtime/organizationRuntimeReadiness.js +67 -0
  332. package/dist/runtime/organizationRuntimeRecording.d.ts +7 -0
  333. package/dist/runtime/organizationRuntimeRecording.d.ts.map +1 -0
  334. package/dist/runtime/organizationRuntimeRecording.js +58 -0
  335. package/dist/runtime/physicalReadiness.d.ts +59 -0
  336. package/dist/runtime/physicalReadiness.d.ts.map +1 -0
  337. package/dist/runtime/physicalReadiness.js +176 -0
  338. package/dist/runtime/portableCredentialAuth.d.ts +6 -0
  339. package/dist/runtime/portableCredentialAuth.d.ts.map +1 -0
  340. package/dist/runtime/portableCredentialAuth.js +70 -0
  341. package/dist/runtime/portableCredentialMaterial.d.ts +8 -0
  342. package/dist/runtime/portableCredentialMaterial.d.ts.map +1 -0
  343. package/dist/runtime/portableCredentialMaterial.js +169 -0
  344. package/dist/runtime/productionAgentTools.d.ts +5 -0
  345. package/dist/runtime/productionAgentTools.d.ts.map +1 -0
  346. package/dist/runtime/productionAgentTools.js +336 -0
  347. package/dist/runtime/relocateRuntimeConfig.d.ts +14 -0
  348. package/dist/runtime/relocateRuntimeConfig.d.ts.map +1 -0
  349. package/dist/runtime/relocateRuntimeConfig.js +38 -0
  350. package/dist/runtime/runtimeHomeLayout.d.ts +48 -0
  351. package/dist/runtime/runtimeHomeLayout.d.ts.map +1 -0
  352. package/dist/runtime/runtimeHomeLayout.js +84 -0
  353. package/dist/runtime/schedule.d.ts +40 -0
  354. package/dist/runtime/schedule.d.ts.map +1 -0
  355. package/dist/runtime/schedule.js +376 -0
  356. package/dist/runtime/storeCoordination.d.ts +33 -0
  357. package/dist/runtime/storeCoordination.d.ts.map +1 -0
  358. package/dist/runtime/storeCoordination.js +117 -0
  359. package/dist/runtime/taskClock.d.ts +42 -0
  360. package/dist/runtime/taskClock.d.ts.map +1 -0
  361. package/dist/runtime/taskClock.js +102 -0
  362. package/dist/runtime/taskClockProcess.d.ts +17 -0
  363. package/dist/runtime/taskClockProcess.d.ts.map +1 -0
  364. package/dist/runtime/taskClockProcess.js +58 -0
  365. package/dist/runtime/toolResultSpill.d.ts +152 -0
  366. package/dist/runtime/toolResultSpill.d.ts.map +1 -0
  367. package/dist/runtime/toolResultSpill.js +351 -0
  368. package/dist/runtime/turnRequestLedger.d.ts +155 -0
  369. package/dist/runtime/turnRequestLedger.d.ts.map +1 -0
  370. package/dist/runtime/turnRequestLedger.js +251 -0
  371. package/dist/runtime/turnUsageLedger.d.ts +143 -0
  372. package/dist/runtime/turnUsageLedger.d.ts.map +1 -0
  373. package/dist/runtime/turnUsageLedger.js +203 -0
  374. package/dist/runtime/wakeAcceptanceClaimDiagnostics.d.ts +34 -0
  375. package/dist/runtime/wakeAcceptanceClaimDiagnostics.d.ts.map +1 -0
  376. package/dist/runtime/wakeAcceptanceClaimDiagnostics.js +79 -0
  377. package/dist/runtime/wakeAcceptanceIndex.d.ts +55 -0
  378. package/dist/runtime/wakeAcceptanceIndex.d.ts.map +1 -0
  379. package/dist/runtime/wakeAcceptanceIndex.js +158 -0
  380. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts +25 -0
  381. package/dist/runtime/wakeAcceptanceProcessIdentity.d.ts.map +1 -0
  382. package/dist/runtime/wakeAcceptanceProcessIdentity.js +54 -0
  383. package/dist/runtime/wakeAcceptanceReconciliation.d.ts +211 -0
  384. package/dist/runtime/wakeAcceptanceReconciliation.d.ts.map +1 -0
  385. package/dist/runtime/wakeAcceptanceReconciliation.js +289 -0
  386. package/dist/runtime/wakeAcceptanceRecord.d.ts +25 -0
  387. package/dist/runtime/wakeAcceptanceRecord.d.ts.map +1 -0
  388. package/dist/runtime/wakeAcceptanceRecord.js +58 -0
  389. package/dist/runtime/wakeAcceptanceRetention.d.ts +36 -0
  390. package/dist/runtime/wakeAcceptanceRetention.d.ts.map +1 -0
  391. package/dist/runtime/wakeAcceptanceRetention.js +38 -0
  392. package/dist/runtime/wakeAcceptanceStore.d.ts +113 -0
  393. package/dist/runtime/wakeAcceptanceStore.d.ts.map +1 -0
  394. package/dist/runtime/wakeAcceptanceStore.js +561 -0
  395. package/dist/runtime/wakeAcceptanceTypes.d.ts +179 -0
  396. package/dist/runtime/wakeAcceptanceTypes.d.ts.map +1 -0
  397. package/dist/runtime/wakeAcceptanceTypes.js +95 -0
  398. package/dist/runtime/wakeFuse.d.ts +124 -0
  399. package/dist/runtime/wakeFuse.d.ts.map +1 -0
  400. package/dist/runtime/wakeFuse.js +466 -0
  401. package/dist/runtime/wakeMomentFs.d.ts +27 -0
  402. package/dist/runtime/wakeMomentFs.d.ts.map +1 -0
  403. package/dist/runtime/wakeMomentFs.js +223 -0
  404. package/dist/runtime/wakeMomentHistory.d.ts +26 -0
  405. package/dist/runtime/wakeMomentHistory.d.ts.map +1 -0
  406. package/dist/runtime/wakeMomentHistory.js +109 -0
  407. package/dist/runtime/wakeMomentIo.d.ts +22 -0
  408. package/dist/runtime/wakeMomentIo.d.ts.map +1 -0
  409. package/dist/runtime/wakeMomentIo.js +114 -0
  410. package/dist/runtime/wakeMomentRecorder.d.ts +33 -0
  411. package/dist/runtime/wakeMomentRecorder.d.ts.map +1 -0
  412. package/dist/runtime/wakeMomentRecorder.js +81 -0
  413. package/dist/runtime/wakeMomentRetention.d.ts +7 -0
  414. package/dist/runtime/wakeMomentRetention.d.ts.map +1 -0
  415. package/dist/runtime/wakeMomentRetention.js +143 -0
  416. package/dist/runtime/wakeMomentRows.d.ts +8 -0
  417. package/dist/runtime/wakeMomentRows.d.ts.map +1 -0
  418. package/dist/runtime/wakeMomentRows.js +66 -0
  419. package/dist/runtime/wakeMomentSnapshot.d.ts +56 -0
  420. package/dist/runtime/wakeMomentSnapshot.d.ts.map +1 -0
  421. package/dist/runtime/wakeMomentSnapshot.js +248 -0
  422. package/package.json +22 -11
@@ -0,0 +1,336 @@
1
+ import { spawn, readyTaskClockEnvironment } from "./taskClockProcess.js";
2
+ import { createHash } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { lstat, open, readdir, rename, unlink } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
8
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
9
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
10
+ import { moltnetOperationResult, readMoltnetPages } from "./moltnetMachineRead.js";
11
+ import { McpToolCallError, MCP_TOOL_RESULT_MAX_BYTES, renderMcpToolResult, replayMcpReceipt } from "./mcpToolResult.js";
12
+ import { ensureRuntimeHomeDirectory } from "./runtimeHomeLayout.js";
13
+ import { capToolResult, resolveExemptToolNames, resolveToolResultMaxBytes, TOOL_OUTPUT_DIRECTORY_NAME } from "./toolResultSpill.js";
14
+ import { cliChildEnvironment } from "../pi/cliEnvironment.js";
15
+ import { taskClockChildEnvironment, taskClockProcessEnvironment, taskClockTimestamp } from "./taskClock.js";
16
+ const MAX_RESULT = 65_536;
17
+ const TIMEOUT = 10_000;
18
+ /**
19
+ * Action and delivery identifiers are prefixed with a hyphen, never a colon.
20
+ *
21
+ * Moltnet's machine protocol rejects any identifier that parses as a scoped
22
+ * agent id, and `ParseScopedAgentID` treats *every* `left:right` string as one
23
+ * (`moltnet/pkg/protocol/identity.go`). A `daimon:<digest>` delivery id
24
+ * therefore failed `delivery_id must be a local id`, and the CLI answered
25
+ * `error: invalid request` for every send an agent ever attempted.
26
+ */
27
+ const DAIMON_ACTION_ID_PREFIX = "daimon-";
28
+ export async function createProductionAgentTools(agent, wakeContext = {}) {
29
+ taskClockChildEnvironment();
30
+ for (const server of agent.mcp ?? [])
31
+ taskClockChildEnvironment(server.env);
32
+ readyTaskClockEnvironment(cliChildEnvironment([], agent.runtimeHomePath));
33
+ await ensureRuntimeHomeDirectory(agent.runtimeHomePath, "tool-state");
34
+ // Resolved once, at agent start: a malformed bound is a configuration error
35
+ // that should refuse the agent, not a surprise thrown from the middle of a
36
+ // tool call the model is waiting on.
37
+ const cap = { maxBytes: resolveToolResultMaxBytes(), exempt: resolveExemptToolNames() };
38
+ const tools = [...await Promise.all((agent.mcp ?? []).map((server) => mcpTools(agent, server, wakeContext, cap)))].flat();
39
+ if (agent.moltnet !== undefined)
40
+ tools.push(moltnetTool(agent, wakeContext), moltnetReadTool(agent));
41
+ if (new Set(tools.map((tool) => tool.name)).size !== tools.length)
42
+ throw new Error("compiled cognition tool names collide");
43
+ return tools;
44
+ }
45
+ async function mcpTools(agent, server, wakeContext, cap) {
46
+ const { client, close } = await connect(agent, server);
47
+ const listed = await client.listTools(undefined, { timeout: TIMEOUT });
48
+ if (Buffer.byteLength(JSON.stringify(listed)) > MAX_RESULT) {
49
+ await close();
50
+ throw new Error(`MCP server ${server.name} tool list exceeds bound`);
51
+ }
52
+ const available = new Map(listed.tools.map((tool) => [tool.name, tool]));
53
+ const undeclared = [...available.keys()].filter((name) => !server.tools.includes(name));
54
+ if (undeclared.length > 0) {
55
+ await close();
56
+ throw new Error(`MCP server ${server.name} exposed undeclared tools`);
57
+ }
58
+ const missing = server.tools.filter((name) => !available.has(name));
59
+ if (missing.length > 0) {
60
+ await close();
61
+ throw new Error(`MCP server ${server.name} omitted declared tools`);
62
+ }
63
+ await close();
64
+ return server.tools.map((name) => {
65
+ const declared = available.get(name);
66
+ return {
67
+ name: mcpToolName(server.name, name),
68
+ label: `${server.name}: ${name}`,
69
+ description: declared.description ?? `Call declared MCP tool ${server.name}/${name}`,
70
+ parameters: declared.inputSchema,
71
+ async execute(_id, params) {
72
+ if (!wakeContext.current)
73
+ throw new Error("MCP call requires an active wake");
74
+ const actionId = `${DAIMON_ACTION_ID_PREFIX}${createHash("sha256").update(JSON.stringify([wakeContext.current, agent.id, server.name, name, params])).digest("hex")}`;
75
+ const prior = await priorReceipt(agent, actionId);
76
+ if (prior !== undefined) {
77
+ const replayed = replayMcpReceipt(server.name, name, prior);
78
+ return { content: replayed.content, details: replayed.details };
79
+ }
80
+ const active = await connect(agent, server);
81
+ try {
82
+ const result = await active.client.callTool({ name, arguments: params }, undefined, { timeout: TIMEOUT });
83
+ const bytes = JSON.stringify(result);
84
+ const envelope = { kind: "mcp", agent_id: agent.id, engine: agent.engine.kind, delivery_id: actionId, server: server.name, tool: name, digest: digest(bytes) };
85
+ let rendered;
86
+ try {
87
+ // The SDK types this as a union with the pre-schema compatibility shape;
88
+ // only the three fields `McpUpstreamResult` names are ever read.
89
+ rendered = renderMcpToolResult({ server: server.name, tool: name, result: result, maxBytes: MCP_TOOL_RESULT_MAX_BYTES });
90
+ // Every tool result stays in the transcript for every *subsequent*
91
+ // model request of the wake, so one oversized answer is re-billed
92
+ // once per remaining request. Above the bound the full payload goes
93
+ // to disk and the model gets head+tail plus the path
94
+ // (`toolResultSpill.ts`); at or below it, this returns `rendered`
95
+ // itself and the passthrough contract is untouched.
96
+ rendered = await capToolResult({
97
+ toolName: mcpToolName(server.name, name),
98
+ rendered,
99
+ result: result,
100
+ maxBytes: cap.maxBytes,
101
+ exempt: cap.exempt,
102
+ spillDirectory: path.join(agent.runtimeHomePath, TOOL_OUTPUT_DIRECTORY_NAME),
103
+ spillId: actionId
104
+ });
105
+ }
106
+ catch (error) {
107
+ // The server's own reason is the receipt's payload as much as the
108
+ // model's: a replayed failure has to fail for the same stated cause.
109
+ if (error instanceof McpToolCallError)
110
+ await receipt(agent, { ...envelope, is_error: true, error: error.reason });
111
+ throw error;
112
+ }
113
+ await receipt(agent, { ...envelope, is_error: false, result: { content: rendered.content, details: rendered.details }, ...(rendered.truncated ? { truncated: true } : {}) });
114
+ return { content: rendered.content, details: rendered.details };
115
+ }
116
+ finally {
117
+ await active.close();
118
+ }
119
+ }
120
+ };
121
+ });
122
+ }
123
+ /**
124
+ * Reading a declared room is a native Moltnet machine operation. Without it an agent can
125
+ * only learn what a wake pushed at it, so any role that weighs several peers' messages
126
+ * has to be woken once per message instead of reading the room once.
127
+ *
128
+ * The whole payload goes in `details` as well as `content`, matching every other
129
+ * Daimon tool (`memoryTools.ts`, `worldTools.ts`). This tool was written by
130
+ * copying `moltnet_send`, whose useful payload genuinely *is* its details
131
+ * (`{"accepted":true}`) — but the MCP mount lowers `details` to
132
+ * `structuredContent` (`src/mcp/toolServer.ts`) and the engines render that in
133
+ * preference to `content`, so a read that put its messages only in `content`
134
+ * handed the model a bare `{"messages":5}` and dropped every message and the
135
+ * page cursor. It looked like a confused agent for a night; it was an empty tool.
136
+ */
137
+ function moltnetReadTool(agent) {
138
+ return {
139
+ name: "moltnet_read", label: "Read a scoped Moltnet room or DM", description: "Read recent messages from one room or DM declared for this agent.",
140
+ parameters: { type: "object", additionalProperties: false, required: ["network", "target"], properties: { network: { type: "string" }, target: { type: "string" }, limit: { type: "integer", minimum: 1, maximum: 100 }, before: { type: "string" }, after: { type: "string" } } },
141
+ async execute(_id, params) {
142
+ const input = params;
143
+ const network = agent.moltnet.networks.find((entry) => entry.id === input.network);
144
+ if (network === undefined)
145
+ throw new Error("Moltnet action exceeds declared scope");
146
+ const [kind, target] = input.target.split(":", 2);
147
+ if ((kind === "room" && !network.rooms.includes(target ?? "")) || (kind === "dm" && !network.dms) || !target || !["room", "dm"].includes(kind ?? ""))
148
+ throw new Error("Moltnet target is not declared");
149
+ const read = await readMoltnetPages({
150
+ requested: input.limit ?? 20, maxBytes: MAX_RESULT,
151
+ ...(input.before === undefined ? {} : { before: input.before }),
152
+ ...(input.after === undefined ? {} : { after: input.after }),
153
+ fetch: (request) => moltnetReadPage(agent, input.network, kind, target, request)
154
+ });
155
+ const payload = {
156
+ target: read.target ?? { kind, id: target },
157
+ messages: read.messages,
158
+ message_count: read.messages.length,
159
+ page: {
160
+ has_more: read.hasMore,
161
+ ...(read.nextBefore === undefined ? {} : { next_before: read.nextBefore }),
162
+ ...(read.nextAfter === undefined ? {} : { next_after: read.nextAfter })
163
+ },
164
+ ...(read.truncated === undefined ? {} : { truncated: read.truncated })
165
+ };
166
+ const bytes = JSON.stringify(payload);
167
+ if (Buffer.byteLength(bytes) > MAX_RESULT)
168
+ throw new Error("Moltnet read result exceeds bound");
169
+ return { content: [{ type: "text", text: bytes }], details: payload };
170
+ }
171
+ };
172
+ }
173
+ /** One `machine` read request, unwrapped onto the shape the pager consumes. */
174
+ async function moltnetReadPage(agent, networkId, kind, target, request) {
175
+ const correlationId = `${DAIMON_ACTION_ID_PREFIX}${createHash("sha256").update(JSON.stringify([agent.id, networkId, kind, target, request.limit, request.before ?? "", request.after ?? ""])).digest("hex")}`;
176
+ const response = await machine(agent.moltnet.cliPath, agent.moltnet.configPath, networkId, {
177
+ version: "moltnet.machine.v1", correlation_id: correlationId, operation: "read",
178
+ read: { target: { kind, id: target }, limit: request.limit, ...(request.before === undefined ? {} : { before: request.before }), ...(request.after === undefined ? {} : { after: request.after }) }
179
+ });
180
+ const result = moltnetOperationResult(response, "read", "read");
181
+ if (result?.page?.messages === undefined)
182
+ throw new Error("Moltnet read was not accepted");
183
+ const info = result.page.page ?? {};
184
+ return {
185
+ ...(result.target === undefined ? {} : { target: result.target }),
186
+ messages: result.page.messages,
187
+ hasMore: info.has_more === true,
188
+ ...(typeof info.next_before === "string" ? { nextBefore: info.next_before } : {}),
189
+ ...(typeof info.next_after === "string" ? { nextAfter: info.next_after } : {})
190
+ };
191
+ }
192
+ function moltnetTool(agent, wakeContext) {
193
+ return {
194
+ name: "moltnet_send", label: "Send a scoped Moltnet message", description: "Send to one room or DM declared for this agent.",
195
+ parameters: { type: "object", additionalProperties: false, required: ["network", "target", "text"], properties: { network: { type: "string" }, target: { type: "string" }, text: { type: "string", minLength: 1, maxLength: 2048 } } },
196
+ async execute(_id, params) {
197
+ const input = params;
198
+ const network = agent.moltnet.networks.find((entry) => entry.id === input.network);
199
+ if (network === undefined || Buffer.byteLength(input.text) > 2_048)
200
+ throw new Error("Moltnet action exceeds declared scope");
201
+ const [kind, target] = input.target.split(":", 2);
202
+ if ((kind === "room" && !network.rooms.includes(target ?? "")) || (kind === "dm" && !network.dms) || !target || !["room", "dm"].includes(kind ?? ""))
203
+ throw new Error("Moltnet target is not declared");
204
+ if (!wakeContext.current)
205
+ throw new Error("Moltnet send requires an active wake");
206
+ const deliveryId = `${DAIMON_ACTION_ID_PREFIX}${createHash("sha256").update(JSON.stringify([wakeContext.current, agent.id, input.network, input.target, input.text])).digest("hex")}`;
207
+ const prior = await priorReceipt(agent, deliveryId);
208
+ if (prior !== undefined) {
209
+ wakeContext.spokeFor = wakeContext.current;
210
+ const visible = typeof prior.at === "string" ? { ...prior, at: taskClockTimestamp(prior.at) } : prior;
211
+ return { content: [{ type: "text", text: JSON.stringify(visible) }], details: visible };
212
+ }
213
+ const response = await machine(agent.moltnet.cliPath, agent.moltnet.configPath, input.network, { version: "moltnet.machine.v1", correlation_id: deliveryId, operation: "send_nudge", send_nudge: { delivery_id: deliveryId, target: { kind, id: target }, body: input.text } });
214
+ const result = moltnetOperationResult(response, "send_nudge", "send");
215
+ if (result?.accepted !== true || typeof result.message_id !== "string")
216
+ throw new Error("Moltnet send was not accepted");
217
+ await receipt(agent, { kind: "moltnet", agent_id: agent.id, engine: agent.engine.kind, delivery_id: deliveryId, network: input.network, target: input.target, message_id: result.message_id });
218
+ // An explicit send and the bridge's terminal-text fallback share one
219
+ // publication slot (moltnet AGENTS.md); recording that this wake spoke
220
+ // lets the wake-completion path blank the terminal text so it is not
221
+ // echoed as a second message.
222
+ wakeContext.spokeFor = wakeContext.current;
223
+ return { content: [{ type: "text", text: JSON.stringify({ accepted: true, message_id: result.message_id }) }], details: { accepted: true } };
224
+ }
225
+ };
226
+ }
227
+ async function connect(agent, server) {
228
+ taskClockChildEnvironment(server.env);
229
+ const client = new Client({ name: "daimon-production", version: "0.2.1" });
230
+ const headers = server.authSecretEnv === undefined ? {} : { authorization: `Bearer ${requiredSecret(server.authSecretEnv)}` };
231
+ const transport = server.transport === "stdio"
232
+ ? new StdioClientTransport({ command: server.command, args: [...server.args], env: stringEnvironment(readyTaskClockEnvironment({ ...server.env, ...cliChildEnvironment([], agent.runtimeHomePath, { executablePath: server.command }) })) })
233
+ : server.transport === "sse" ? new SSEClientTransport(new URL(server.url), { requestInit: { headers } })
234
+ : new StreamableHTTPClientTransport(new URL(server.url), { requestInit: { headers } });
235
+ await client.connect(transport);
236
+ return { client, close: () => client.close() };
237
+ }
238
+ function requiredSecret(name) { const value = process.env[name]; if (!value)
239
+ throw new Error(`required MCP secret ${name} is missing`); return value; }
240
+ function receiptPath(agent, deliveryId) { return path.join(agent.runtimeHomePath, "tool-state", `${digest(deliveryId).slice(7)}.json`); }
241
+ async function receipt(agent, value) { const deliveryId = String(value.delivery_id); const file = receiptPath(agent, deliveryId); const temporary = `${file}.${process.pid}.${Date.now()}.tmp`; const bytes = `${JSON.stringify({ ...value, at: new Date().toISOString() })}\n`; if (Buffer.byteLength(bytes) > MAX_RESULT)
242
+ throw new Error("tool receipt exceeds bound"); const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); try {
243
+ await handle.writeFile(bytes);
244
+ await handle.sync();
245
+ }
246
+ finally {
247
+ await handle.close();
248
+ } try {
249
+ await rename(temporary, file);
250
+ await pruneReceipts(path.dirname(file));
251
+ const directory = await open(path.dirname(file), constants.O_RDONLY);
252
+ try {
253
+ await directory.sync();
254
+ }
255
+ finally {
256
+ await directory.close();
257
+ }
258
+ }
259
+ catch (error) {
260
+ await unlink(temporary).catch(() => undefined);
261
+ throw error;
262
+ } }
263
+ async function pruneReceipts(directory) { const candidates = await Promise.all((await readdir(directory)).filter((name) => /^[a-f0-9]{64}\.json$/u.test(name)).map(async (name) => ({ name, info: await lstat(path.join(directory, name)) }))); if (candidates.some(({ info }) => !info.isFile() || info.nlink !== 1))
264
+ throw new Error("tool receipt directory contains an unsafe entry"); for (const candidate of candidates.sort((left, right) => right.info.mtimeMs - left.info.mtimeMs || right.name.localeCompare(left.name)).slice(2048))
265
+ await unlink(path.join(directory, candidate.name)); }
266
+ async function priorReceipt(agent, deliveryId) { const file = receiptPath(agent, deliveryId); let handle; try {
267
+ handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
268
+ }
269
+ catch (error) {
270
+ if (error.code === "ENOENT")
271
+ return undefined;
272
+ throw error;
273
+ } try {
274
+ const entry = await handle.stat();
275
+ if (!entry.isFile() || entry.size > MAX_RESULT)
276
+ throw new Error("tool receipt is unsafe or exceeds bound");
277
+ const value = JSON.parse(await handle.readFile("utf8"));
278
+ if (value.delivery_id !== deliveryId || value.agent_id !== agent.id || value.engine !== agent.engine.kind)
279
+ throw new Error("tool receipt identity mismatch");
280
+ return value;
281
+ }
282
+ finally {
283
+ await handle.close();
284
+ } }
285
+ /**
286
+ * One request/response exchange with `moltnet machine`.
287
+ *
288
+ * Stdin is held open until the response line arrives. `moltnet machine` treats
289
+ * end-of-input as cancellation of everything still in flight, so ending stdin
290
+ * with the request — as this did — raced the send and lost: the CLI answered
291
+ * `{"error":{"code":"canceled"}}` and no message was ever delivered. The
292
+ * operation is complete once its line is on stdout, so closing stdin there can
293
+ * no longer cancel it.
294
+ */
295
+ async function machine(cli, config, network, request) {
296
+ const clockEnvironment = taskClockChildEnvironment();
297
+ return await new Promise((resolve, reject) => {
298
+ const child = spawn(cli, ["machine", "--config", config, "--network", network], { stdio: ["pipe", "pipe", "pipe"], env: taskClockProcessEnvironment(process.env, clockEnvironment) });
299
+ let output = "", error = "", settled = false;
300
+ const settle = (action) => { if (settled)
301
+ return; settled = true; clearTimeout(timer); action(); };
302
+ const timer = setTimeout(() => { child.kill("SIGKILL"); settle(() => reject(new Error("Moltnet machine timed out"))); }, TIMEOUT);
303
+ child.stdin.on("error", () => undefined);
304
+ child.stdout.on("data", (chunk) => {
305
+ output += chunk;
306
+ if (Buffer.byteLength(output) > MAX_RESULT) {
307
+ child.kill("SIGKILL");
308
+ settle(() => reject(new Error("Moltnet machine response exceeds bound")));
309
+ return;
310
+ }
311
+ const newline = output.indexOf("\n");
312
+ if (newline < 0)
313
+ return;
314
+ const line = output.slice(0, newline).trim();
315
+ if (line.length === 0)
316
+ return;
317
+ child.stdin.end();
318
+ settle(() => { try {
319
+ resolve(JSON.parse(line));
320
+ }
321
+ catch (cause) {
322
+ reject(cause);
323
+ } });
324
+ child.kill("SIGTERM");
325
+ });
326
+ child.stderr.on("data", (chunk) => { error += chunk; });
327
+ child.once("error", (cause) => settle(() => reject(cause)));
328
+ child.once("exit", () => settle(() => reject(new Error(`Moltnet machine failed: ${(error.slice(0, 1024) || "no response").trim()}`))));
329
+ child.stdin.write(`${JSON.stringify(request)}\n`);
330
+ });
331
+ }
332
+ function digest(value) { return `sha256:${createHash("sha256").update(value).digest("hex")}`; }
333
+ /** The mounted name of one declared MCP tool: the one place it is spelled. */
334
+ function mcpToolName(server, tool) { return `mcp_${safe(server)}_${safe(tool)}`; }
335
+ function safe(value) { return value.replace(/[^A-Za-z0-9_]/gu, "_").slice(0, 48); }
336
+ function stringEnvironment(value) { return Object.fromEntries(Object.entries(value).filter((entry) => entry[1] !== undefined)); }
@@ -0,0 +1,14 @@
1
+ import { type OrganizationRuntimeConfig } from "./organizationRuntime.js";
2
+ export type RuntimeConfigLocation = Readonly<{
3
+ workspace: string;
4
+ home: string;
5
+ memory: string;
6
+ /** Both paths are explicit: runtime config declares no control-token file. */
7
+ controlToken: Readonly<{
8
+ from: string;
9
+ to: string;
10
+ }>;
11
+ }>;
12
+ /** Rebase one memory-backed agent's path prefixes, preserving instructions verbatim. */
13
+ export declare function relocateRuntimeConfig(config: OrganizationRuntimeConfig, location: RuntimeConfigLocation): OrganizationRuntimeConfig;
14
+ //# sourceMappingURL=relocateRuntimeConfig.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relocateRuntimeConfig.d.ts","sourceRoot":"","sources":["../../src/runtime/relocateRuntimeConfig.ts"],"names":[],"mappings":"AACA,OAAO,EAAkC,KAAK,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAE1G,MAAM,MAAM,qBAAqB,GAAG,QAAQ,CAAC;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,8EAA8E;IAC9E,YAAY,EAAE,QAAQ,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACtD,CAAC,CAAC;AAEH,wFAAwF;AACxF,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,yBAAyB,EAAE,QAAQ,EAAE,qBAAqB,GAAG,yBAAyB,CA8BnI"}
@@ -0,0 +1,38 @@
1
+ import { posix } from "node:path";
2
+ import { parseOrganizationRuntimeConfig } from "./organizationRuntime.js";
3
+ /** Rebase one memory-backed agent's path prefixes, preserving instructions verbatim. */
4
+ export function relocateRuntimeConfig(config, location) {
5
+ const parsed = parseOrganizationRuntimeConfig(config);
6
+ const agent = parsed.agents[0];
7
+ if (parsed.agents.length !== 1 || !agent?.memory)
8
+ throw new TypeError("Relocation requires one memory-backed agent");
9
+ const mappings = [
10
+ [agent.workspacePath, location.workspace],
11
+ [agent.runtimeHomePath, location.home],
12
+ [agent.memory.runtimeHomePath, location.memory],
13
+ [location.controlToken.from, location.controlToken.to]
14
+ ];
15
+ for (const pair of mappings)
16
+ for (const value of pair) {
17
+ if (typeof value !== "string" || !posix.isAbsolute(value) || posix.normalize(value) !== value || value === "/" || value.endsWith("/") || value.includes("\\") || value.includes("\0")) {
18
+ throw new TypeError("Relocation paths must be canonical absolute POSIX paths other than root");
19
+ }
20
+ }
21
+ // Memory may live below home; the most specific source must own that subtree.
22
+ const ordered = [...mappings].sort(([a], [b]) => b.length - a.length);
23
+ if (new Set(ordered.map(([source]) => source)).size !== ordered.length)
24
+ throw new TypeError("Relocation source paths must be distinct");
25
+ const relocate = (value) => {
26
+ if (typeof value === "string") {
27
+ const mapping = ordered.find(([source]) => value === source || value.startsWith(`${source}/`));
28
+ return mapping ? mapping[1] + value.slice(mapping[0].length) : value;
29
+ }
30
+ if (Array.isArray(value))
31
+ return value.map(relocate);
32
+ if (value !== null && typeof value === "object") {
33
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, key === "instructions" ? item : relocate(item)]));
34
+ }
35
+ return value;
36
+ };
37
+ return parseOrganizationRuntimeConfig(relocate(parsed));
38
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Mode for every directory Daimon creates inside an agent's runtime home.
3
+ *
4
+ * A brokered Grok agent's runtime home is `0710`
5
+ * (`GROK_ENGINE_BROKER.worker.home.organizationRuntimeHome`) so its sandboxed
6
+ * worker can traverse into the setgid `tool-output/` spill directory. Traverse
7
+ * is all it may have: anything Daimon creates in that home — telemetry traces
8
+ * (prompts, replies, world trajectories), tool state, receipts, the engine's
9
+ * XDG directories and the private `.tmp` — stays `0700`, so a default
10
+ * `mkdir` (0755 under the usual umask) never turns a traversable home into a
11
+ * readable one.
12
+ */
13
+ export declare const RUNTIME_HOME_SUBDIRECTORY_MODE = 448;
14
+ /**
15
+ * The home itself, created if it is absent and otherwise left exactly as it is.
16
+ *
17
+ * Create-only is the whole contract here. A brokered Grok agent's home is
18
+ * deliberately `0710` and an organization's may be `0700`; which of the two is
19
+ * correct is `physicalReadiness.ts`'s judgement, made against the agent's
20
+ * declared engine, and a layout helper that "corrected" a traversable home to
21
+ * `0700` would break the worker's only route to its own spills.
22
+ */
23
+ export declare const ensureRuntimeHome: (runtimeHomePath: string) => Promise<string>;
24
+ /**
25
+ * One directory Daimon owns *below* a runtime home, private on every install.
26
+ *
27
+ * `mkdir(..., { mode })` decides nothing for a directory that already exists,
28
+ * and that is the common case rather than the exotic one: a `telemetry/` left
29
+ * at `0755` by a pre-branch Daimon, or pre-created by a deployment, stayed
30
+ * `0755` forever. Under a Grok agent's traversable `0710` home that is the
31
+ * worker reading its own agent's prompts, replies and causal history — the
32
+ * home is traverse-only precisely so that nothing but `tool-output/` is
33
+ * readable. `assertRuntimeDirectory` checks the home, and nothing checked what
34
+ * Daimon created inside it.
35
+ *
36
+ * So every level below the home is asserted and corrected on the way down,
37
+ * through a handle rather than a path: `O_DIRECTORY|O_NOFOLLOW` refuses a
38
+ * symlink planted where a directory belongs, and the `fchmod` that follows
39
+ * lands on the directory that was stat'd. A directory owned by anyone but the
40
+ * runtime user is **refused**, never widened and never silently accepted — the
41
+ * runtime cannot make someone else's directory private, and proceeding would
42
+ * write an agent's telemetry into it anyway.
43
+ *
44
+ * `owner` is a seam so both refusals are testable unprivileged, exactly as
45
+ * `physicalReadiness.ts`'s `RuntimeIdentity` is.
46
+ */
47
+ export declare function ensureRuntimeHomeDirectory(runtimeHomePath: string, relative: string, owner?: number): Promise<string>;
48
+ //# sourceMappingURL=runtimeHomeLayout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtimeHomeLayout.d.ts","sourceRoot":"","sources":["../../src/runtime/runtimeHomeLayout.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,8BAA8B,MAAQ,CAAC;AAEpD;;;;;;;;GAQG;AACH,eAAO,MAAM,iBAAiB,GAAU,iBAAiB,MAAM,KAAG,OAAO,CAAC,MAAM,CAG/E,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAsB,0BAA0B,CAAC,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,GAAE,MAAiC,GAAG,OAAO,CAAC,MAAM,CAAC,CAcrJ"}
@@ -0,0 +1,84 @@
1
+ import { constants } from "node:fs";
2
+ import { mkdir, open } from "node:fs/promises";
3
+ import path from "node:path";
4
+ /**
5
+ * Mode for every directory Daimon creates inside an agent's runtime home.
6
+ *
7
+ * A brokered Grok agent's runtime home is `0710`
8
+ * (`GROK_ENGINE_BROKER.worker.home.organizationRuntimeHome`) so its sandboxed
9
+ * worker can traverse into the setgid `tool-output/` spill directory. Traverse
10
+ * is all it may have: anything Daimon creates in that home — telemetry traces
11
+ * (prompts, replies, world trajectories), tool state, receipts, the engine's
12
+ * XDG directories and the private `.tmp` — stays `0700`, so a default
13
+ * `mkdir` (0755 under the usual umask) never turns a traversable home into a
14
+ * readable one.
15
+ */
16
+ export const RUNTIME_HOME_SUBDIRECTORY_MODE = 0o700;
17
+ /**
18
+ * The home itself, created if it is absent and otherwise left exactly as it is.
19
+ *
20
+ * Create-only is the whole contract here. A brokered Grok agent's home is
21
+ * deliberately `0710` and an organization's may be `0700`; which of the two is
22
+ * correct is `physicalReadiness.ts`'s judgement, made against the agent's
23
+ * declared engine, and a layout helper that "corrected" a traversable home to
24
+ * `0700` would break the worker's only route to its own spills.
25
+ */
26
+ export const ensureRuntimeHome = async (runtimeHomePath) => {
27
+ await mkdir(runtimeHomePath, { recursive: true, mode: RUNTIME_HOME_SUBDIRECTORY_MODE });
28
+ return runtimeHomePath;
29
+ };
30
+ /**
31
+ * One directory Daimon owns *below* a runtime home, private on every install.
32
+ *
33
+ * `mkdir(..., { mode })` decides nothing for a directory that already exists,
34
+ * and that is the common case rather than the exotic one: a `telemetry/` left
35
+ * at `0755` by a pre-branch Daimon, or pre-created by a deployment, stayed
36
+ * `0755` forever. Under a Grok agent's traversable `0710` home that is the
37
+ * worker reading its own agent's prompts, replies and causal history — the
38
+ * home is traverse-only precisely so that nothing but `tool-output/` is
39
+ * readable. `assertRuntimeDirectory` checks the home, and nothing checked what
40
+ * Daimon created inside it.
41
+ *
42
+ * So every level below the home is asserted and corrected on the way down,
43
+ * through a handle rather than a path: `O_DIRECTORY|O_NOFOLLOW` refuses a
44
+ * symlink planted where a directory belongs, and the `fchmod` that follows
45
+ * lands on the directory that was stat'd. A directory owned by anyone but the
46
+ * runtime user is **refused**, never widened and never silently accepted — the
47
+ * runtime cannot make someone else's directory private, and proceeding would
48
+ * write an agent's telemetry into it anyway.
49
+ *
50
+ * `owner` is a seam so both refusals are testable unprivileged, exactly as
51
+ * `physicalReadiness.ts`'s `RuntimeIdentity` is.
52
+ */
53
+ export async function ensureRuntimeHomeDirectory(runtimeHomePath, relative, owner = process.getuid?.() ?? -1) {
54
+ const segments = relative.split("/").filter((segment) => segment.length > 0);
55
+ if (segments.length === 0 || segments.some((segment) => segment === "." || segment === "..")) {
56
+ throw new Error(`runtime home subdirectory must name a path below the home: ${relative}`);
57
+ }
58
+ let current = await ensureRuntimeHome(runtimeHomePath);
59
+ for (const segment of segments) {
60
+ current = path.join(current, segment);
61
+ await mkdir(current, { mode: RUNTIME_HOME_SUBDIRECTORY_MODE }).catch((error) => {
62
+ if (error.code !== "EEXIST")
63
+ throw error;
64
+ });
65
+ await assertPrivateDirectory(current, owner);
66
+ }
67
+ return current;
68
+ }
69
+ const flag = (name) => constants[name] ?? 0;
70
+ async function assertPrivateDirectory(directory, owner) {
71
+ const handle = await open(directory, constants.O_RDONLY | flag("O_DIRECTORY") | flag("O_NOFOLLOW"));
72
+ try {
73
+ const entry = await handle.stat();
74
+ if (!entry.isDirectory())
75
+ throw new Error(`runtime home path is not a directory: ${directory}`);
76
+ if (entry.uid !== owner)
77
+ throw new Error(`runtime home subdirectory must be owned by the runtime user: ${directory}`);
78
+ if ((entry.mode & 0o7777) !== RUNTIME_HOME_SUBDIRECTORY_MODE)
79
+ await handle.chmod(RUNTIME_HOME_SUBDIRECTORY_MODE);
80
+ }
81
+ finally {
82
+ await handle.close();
83
+ }
84
+ }
@@ -0,0 +1,40 @@
1
+ import type { OrganizationRuntimeAgentConfig, OrganizationRuntimeSchedule } from "./organizationRuntime.js";
2
+ export declare const MAX_TIMER_DELAY_MS = 2147483647;
3
+ export type ScheduledOccurrence = Readonly<{
4
+ agentId: string;
5
+ deliveryId: string;
6
+ occurredAt: string;
7
+ prompt: string;
8
+ }>;
9
+ type ActiveSchedule = Exclude<OrganizationRuntimeSchedule, {
10
+ kind: "disabled";
11
+ }>;
12
+ type Timer = ReturnType<typeof setTimeout>;
13
+ export type ScheduleController = Readonly<{
14
+ start(): Promise<void>;
15
+ drain(agentId?: string): Promise<void>;
16
+ stop(): Promise<void>;
17
+ }>;
18
+ export type ScheduleControllerOptions = Readonly<{
19
+ acceptanceStorePath: string;
20
+ agents: readonly OrganizationRuntimeAgentConfig[];
21
+ /** False means the agent is busy; the durable latest-pending slot remains. */
22
+ accept(occurrence: ScheduledOccurrence): Promise<boolean | void>;
23
+ now?: () => number;
24
+ /** Draws the fractional jitter offset; defaults to `Math.random`. Injectable so tests can assert bounds/independence without real randomness. */
25
+ random?: () => number;
26
+ setTimer?: (callback: () => void, delayMs: number) => Timer;
27
+ clearTimer?: (timer: Timer) => void;
28
+ /** @internal Observable durability stages for focused crash-order tests. */
29
+ onPersistStageForTest?: (stage: "write" | "file-sync" | "rename" | "directory-sync") => void;
30
+ }>;
31
+ /** Schedules create durable pending occurrences; engine execution remains elsewhere. */
32
+ export declare function createScheduleController(options: ScheduleControllerOptions): ScheduleController;
33
+ export declare function occurrenceFor(agentId: string, schedule: ActiveSchedule, at: number): ScheduledOccurrence;
34
+ export declare function isCanonicalScheduleDeliveryId(value: string): boolean;
35
+ export declare function nextOccurrence(agentId: string, schedule: ActiveSchedule, anchor: number | undefined, from: number): number;
36
+ export declare function cronIsPossible(cron: string): boolean;
37
+ /** Independent per-arming offset in `[0, jitter_seconds * 1000]`; absent/zero jitter always yields exactly 0. */
38
+ export declare function jitterOffsetMs(schedule: ActiveSchedule | undefined, random: () => number): number;
39
+ export {};
40
+ //# sourceMappingURL=schedule.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schedule.d.ts","sourceRoot":"","sources":["../../src/runtime/schedule.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,8BAA8B,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAK5G,eAAO,MAAM,kBAAkB,aAAgB,CAAC;AAKhD,MAAM,MAAM,mBAAmB,GAAG,QAAQ,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AACxH,KAAK,cAAc,GAAG,OAAO,CAAC,2BAA2B,EAAE;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC;AAGjF,KAAK,KAAK,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC;AAE3C,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC;IAAE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,KAAK,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAAC,CAAC;AACrI,MAAM,MAAM,yBAAyB,GAAG,QAAQ,CAAC;IAC/C,mBAAmB,EAAE,MAAM,CAAC;IAC5B,MAAM,EAAE,SAAS,8BAA8B,EAAE,CAAC;IAClD,8EAA8E;IAC9E,MAAM,CAAC,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;IACjE,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,iJAAiJ;IACjJ,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,OAAO,EAAE,MAAM,KAAK,KAAK,CAAC;IAC5D,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACpC,4EAA4E;IAC5E,qBAAqB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,GAAG,WAAW,GAAG,QAAQ,GAAG,gBAAgB,KAAK,IAAI,CAAC;CAC9F,CAAC,CAAC;AAEH,wFAAwF;AACxF,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,kBAAkB,CA8F/F;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,EAAE,EAAE,EAAE,MAAM,GAAG,mBAAmB,CAIxG;AAED,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAKpE;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAY1H;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAA8E;AAEnI,iHAAiH;AACjH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,cAAc,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM,MAAM,GAAG,MAAM,CAKjG"}