@ouro.bot/cli 0.1.0-alpha.105 → 0.1.0-alpha.1057

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 (800) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +196 -30
  3. package/RepairGuide.ouro/agent.json +5 -0
  4. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  5. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  6. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  7. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  8. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  9. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  12. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  13. package/assets/bluebubbles-host +264 -0
  14. package/assets/sanctuary-host-launcher.sh +16 -0
  15. package/changelog.json +6476 -16
  16. package/deploy/unraid/Dockerfile +71 -0
  17. package/deploy/unraid/INSTALL.md +64 -0
  18. package/deploy/unraid/README.txt +3032 -0
  19. package/deploy/unraid/audit-container-spec.sh +4 -0
  20. package/deploy/unraid/container-runtime.json +1 -0
  21. package/deploy/unraid/credit-gateway.md +95 -0
  22. package/deploy/unraid/docker-man-template-transaction.mjs +727 -0
  23. package/deploy/unraid/docker-man-template-xml.cjs +105 -0
  24. package/deploy/unraid/github_known_hosts +3 -0
  25. package/deploy/unraid/install.sh +274 -0
  26. package/deploy/unraid/migrate-sanctuary-bundle.mjs +63 -0
  27. package/deploy/unraid/ouro-events/bootstrap-spool.sh +92 -0
  28. package/deploy/unraid/ouro-events/emit-event.mjs +310 -0
  29. package/deploy/unraid/ouro-events/emit-usenet-event.sh +54 -0
  30. package/deploy/unraid/ouro-events/install-usenet-guard.sh +435 -0
  31. package/deploy/unraid/ouro-events/usenet-health.sh +176 -0
  32. package/deploy/unraid/ouro-sync-ssh +98 -0
  33. package/deploy/unraid/ouro-sync.sudoers +3 -0
  34. package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
  35. package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
  36. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  37. package/deploy/unraid/sanctuary-authority-installation.json +36 -0
  38. package/deploy/unraid/sanctuary-authority-service.sh +30 -0
  39. package/deploy/unraid/sanctuary-butler-upgrade.mjs +1523 -0
  40. package/deploy/unraid/sanctuary-deployment-target.mjs +710 -0
  41. package/deploy/unraid/sanctuary-replay-gate.mjs +2528 -0
  42. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  43. package/deploy/unraid/sanctuary-sync-cutover.sh +1039 -0
  44. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2088 -0
  45. package/deploy/unraid/sanctuary-unit16-run.sh +570 -0
  46. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  47. package/deploy/unraid/sanctuary.ouro/agent.json +67 -0
  48. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  49. package/deploy/unraid/sanctuary.ouro/awaiting/house-care-sweep.md +17 -0
  50. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  51. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  52. package/deploy/unraid/sanctuary.ouro/mcp/media-mcp.mjs +2255 -0
  53. package/deploy/unraid/sanctuary.ouro/product/PRODUCT.md +13 -0
  54. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
  55. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
  56. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +7 -0
  57. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +7 -0
  58. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +15 -0
  59. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +3 -0
  60. package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
  61. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +239 -0
  62. package/deploy/unraid/sanctuary.xml +30 -0
  63. package/dist/a2a/card.js +57 -0
  64. package/dist/a2a/client.js +290 -0
  65. package/dist/a2a/config.js +50 -0
  66. package/dist/a2a/delegated-command-grants.js +93 -0
  67. package/dist/a2a/delegated-command.js +197 -0
  68. package/dist/a2a/delegation-stores.js +56 -0
  69. package/dist/a2a/did-resolution.js +205 -0
  70. package/dist/a2a/escalation-grants.js +84 -0
  71. package/dist/a2a/escalation-wiring.js +60 -0
  72. package/dist/a2a/identity.js +258 -0
  73. package/dist/a2a/inbound-share.js +131 -0
  74. package/dist/a2a/mission-result-wire.js +265 -0
  75. package/dist/a2a/onboarding.js +133 -0
  76. package/dist/a2a/operator-trust.js +399 -0
  77. package/dist/a2a/outbox-client.js +59 -0
  78. package/dist/a2a/outbox-store.js +188 -0
  79. package/dist/a2a/outbox-wire.js +106 -0
  80. package/dist/a2a/pin-store.js +167 -0
  81. package/dist/a2a/refusals.js +53 -0
  82. package/dist/a2a/relay-client.js +106 -0
  83. package/dist/a2a/relay-config-vault.js +64 -0
  84. package/dist/a2a/relay-contacts.js +120 -0
  85. package/dist/a2a/relay-inbox.js +360 -0
  86. package/dist/a2a/relay-retirements.js +89 -0
  87. package/dist/a2a/replay-grant-holders.js +33 -0
  88. package/dist/a2a/replay-harness.js +188 -0
  89. package/dist/a2a/resolution-proof.js +53 -0
  90. package/dist/a2a/sealed-chat.js +114 -0
  91. package/dist/a2a/seen-ledger.js +214 -0
  92. package/dist/a2a/server.js +808 -0
  93. package/dist/a2a/task-store.js +69 -0
  94. package/dist/a2a/transport.js +100 -0
  95. package/dist/a2a/trust-commands.js +203 -0
  96. package/dist/a2a/trusted-files.js +185 -0
  97. package/dist/a2a/types.js +3 -0
  98. package/dist/arc/attention-types.js +8 -0
  99. package/dist/arc/cares.js +360 -0
  100. package/dist/arc/episodes.js +118 -0
  101. package/dist/arc/evolution.js +490 -0
  102. package/dist/arc/flight-recorder.js +1034 -0
  103. package/dist/arc/intentions.js +134 -0
  104. package/dist/arc/json-store.js +117 -0
  105. package/dist/arc/obligations.js +386 -0
  106. package/dist/arc/packets.js +336 -0
  107. package/dist/arc/presence.js +185 -0
  108. package/dist/arc/task-lifecycle.js +57 -0
  109. package/dist/commerce/store.js +755 -0
  110. package/dist/commerce/types.js +3 -0
  111. package/dist/gateway/keys.js +117 -0
  112. package/dist/gateway/server.js +429 -0
  113. package/dist/heart/active-work.js +674 -68
  114. package/dist/heart/agent-entry.js +253 -3
  115. package/dist/heart/approval-files.js +113 -0
  116. package/dist/heart/approval-store.js +960 -0
  117. package/dist/heart/attachments/image-normalize.js +201 -0
  118. package/dist/heart/attachments/materialize.js +97 -0
  119. package/dist/heart/attachments/originals.js +88 -0
  120. package/dist/heart/attachments/render.js +29 -0
  121. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  122. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  123. package/dist/heart/attachments/sources/index.js +18 -0
  124. package/dist/heart/attachments/sources/telegram.js +71 -0
  125. package/dist/heart/attachments/store.js +132 -0
  126. package/dist/heart/attachments/types.js +93 -0
  127. package/dist/heart/auth/auth-flow.js +589 -0
  128. package/dist/heart/auth/github-device-login.js +104 -0
  129. package/dist/heart/autonomy-budget.js +478 -0
  130. package/dist/heart/awaiting/a2a-await-delivery.js +109 -0
  131. package/dist/heart/awaiting/await-alert.js +152 -0
  132. package/dist/heart/awaiting/await-expiry.js +143 -0
  133. package/dist/heart/awaiting/await-loader.js +91 -0
  134. package/dist/heart/awaiting/await-parser.js +152 -0
  135. package/dist/heart/awaiting/await-runtime-state.js +130 -0
  136. package/dist/heart/awaiting/await-scheduler.js +403 -0
  137. package/dist/heart/background-operations.js +281 -0
  138. package/dist/heart/bluebubbles-host-account.js +78 -0
  139. package/dist/heart/bridges/manager.js +137 -17
  140. package/dist/heart/bridges/store.js +14 -2
  141. package/dist/heart/bundle-state.js +168 -0
  142. package/dist/heart/commitments.js +44 -18
  143. package/dist/heart/config-registry.js +331 -0
  144. package/dist/heart/config.js +179 -131
  145. package/dist/heart/context-loss-gauntlet.js +387 -0
  146. package/dist/heart/context-loss-sentinel.js +1204 -0
  147. package/dist/heart/core.js +2397 -636
  148. package/dist/heart/cross-chat-delivery.js +9 -22
  149. package/dist/heart/daemon/agent-config-check.js +474 -0
  150. package/dist/heart/daemon/agent-discovery.js +304 -3
  151. package/dist/heart/daemon/agent-home.js +409 -0
  152. package/dist/heart/daemon/agent-service.js +542 -0
  153. package/dist/heart/daemon/agentic-repair.js +547 -0
  154. package/dist/heart/daemon/await-private-wake.js +59 -0
  155. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  156. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  157. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  158. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  159. package/dist/heart/daemon/boot-sync-probe.js +223 -0
  160. package/dist/heart/daemon/cadence.js +180 -0
  161. package/dist/heart/daemon/cli-arg-redaction.js +26 -0
  162. package/dist/heart/daemon/cli-defaults.js +949 -0
  163. package/dist/heart/daemon/cli-desk.js +331 -0
  164. package/dist/heart/daemon/cli-exec.js +9497 -0
  165. package/dist/heart/daemon/cli-help.js +780 -0
  166. package/dist/heart/daemon/cli-parse.js +3473 -0
  167. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  168. package/dist/heart/daemon/cli-render.js +819 -0
  169. package/dist/heart/daemon/cli-types.js +8 -0
  170. package/dist/heart/daemon/compile-cache.js +69 -0
  171. package/dist/heart/daemon/connect-bay.js +323 -0
  172. package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
  173. package/dist/heart/daemon/container-healthcheck.js +112 -0
  174. package/dist/heart/daemon/container-runtime.js +97 -0
  175. package/dist/heart/daemon/container-spec-auditor-main.js +187 -0
  176. package/dist/heart/daemon/container-spec-auditor.js +257 -0
  177. package/dist/heart/daemon/daemon-bootstrap-startup.js +115 -0
  178. package/dist/heart/daemon/daemon-cli.js +29 -2373
  179. package/dist/heart/daemon/daemon-entry.js +1109 -11
  180. package/dist/heart/daemon/daemon-health.js +186 -0
  181. package/dist/heart/daemon/daemon-rollup.js +57 -0
  182. package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
  183. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  184. package/dist/heart/daemon/daemon.js +2146 -104
  185. package/dist/heart/daemon/desk-admin.js +420 -0
  186. package/dist/heart/daemon/dns-workflow.js +394 -0
  187. package/dist/heart/daemon/doctor-types.js +8 -0
  188. package/dist/heart/daemon/doctor.js +1816 -0
  189. package/dist/heart/daemon/freshness.js +345 -0
  190. package/dist/heart/daemon/habit-private-wake.js +61 -0
  191. package/dist/heart/daemon/health-monitor.js +154 -11
  192. package/dist/heart/daemon/home-filesystem.js +93 -0
  193. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  194. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  195. package/dist/heart/daemon/http-health-probe.js +80 -0
  196. package/dist/heart/daemon/human-command-screens.js +234 -0
  197. package/dist/heart/daemon/human-readiness.js +114 -0
  198. package/dist/heart/daemon/inner-status.js +78 -0
  199. package/dist/heart/daemon/interactive-repair.js +394 -0
  200. package/dist/heart/daemon/launchd.js +40 -8
  201. package/dist/heart/daemon/linux-service.js +359 -0
  202. package/dist/heart/daemon/log-tailer.js +79 -10
  203. package/dist/heart/daemon/logs-prune.js +132 -0
  204. package/dist/heart/daemon/mcp-canary.js +525 -0
  205. package/dist/heart/daemon/message-router.js +65 -5
  206. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  207. package/dist/heart/daemon/os-cron-deps.js +139 -0
  208. package/dist/heart/daemon/os-cron.js +45 -15
  209. package/dist/heart/daemon/ouro-bot-entry.js +8 -3
  210. package/dist/heart/daemon/ouro-entry.js +11 -3
  211. package/dist/heart/daemon/plugin-cli.js +432 -0
  212. package/dist/heart/daemon/presence-daemon.js +263 -0
  213. package/dist/heart/daemon/presence-roster.js +217 -0
  214. package/dist/heart/daemon/presence.js +380 -0
  215. package/dist/heart/daemon/process-manager.js +763 -61
  216. package/dist/heart/daemon/provider-discovery.js +171 -0
  217. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  218. package/dist/heart/daemon/prunable-bundle.js +144 -0
  219. package/dist/heart/daemon/pulse.js +511 -0
  220. package/dist/heart/daemon/readiness-repair.js +365 -0
  221. package/dist/heart/daemon/run-hooks.js +2 -0
  222. package/dist/heart/daemon/runtime-logging.js +48 -14
  223. package/dist/heart/daemon/runtime-metadata.js +2 -30
  224. package/dist/heart/daemon/runtime-mode.js +13 -2
  225. package/dist/heart/daemon/safe-mode.js +161 -0
  226. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2662 -0
  227. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1832 -0
  228. package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
  229. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +956 -0
  230. package/dist/heart/daemon/sanctuary-authority-codec.js +86 -0
  231. package/dist/heart/daemon/sanctuary-authority-epoch.js +291 -0
  232. package/dist/heart/daemon/sanctuary-authority-installation.js +161 -0
  233. package/dist/heart/daemon/sanctuary-authority-ledger.js +241 -0
  234. package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +1348 -0
  235. package/dist/heart/daemon/sanctuary-authority-vault-migration.js +79 -0
  236. package/dist/heart/daemon/sanctuary-bundle-migration.js +974 -0
  237. package/dist/heart/daemon/sanctuary-host-authority.js +1008 -0
  238. package/dist/heart/daemon/sanctuary-host-detached-supervisor.js +493 -0
  239. package/dist/heart/daemon/sanctuary-host-executor.js +670 -0
  240. package/dist/heart/daemon/sanctuary-host-linux-kernel.js +334 -0
  241. package/dist/heart/daemon/sanctuary-host-supervisor-entry.js +207 -0
  242. package/dist/heart/daemon/sanctuary-host-supervisor.js +95 -0
  243. package/dist/heart/daemon/sanctuary-package-management.js +113 -0
  244. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
  245. package/dist/heart/daemon/sanctuary-scheduler-origin.js +132 -0
  246. package/dist/heart/daemon/sanctuary-telegram-authority-entry.js +475 -0
  247. package/dist/heart/daemon/sanctuary-telegram-authority-gateway.js +585 -0
  248. package/dist/heart/daemon/sanctuary-telegram-authority-service.js +676 -0
  249. package/dist/heart/daemon/sense-manager.js +877 -58
  250. package/dist/heart/daemon/session-id-resolver.js +131 -0
  251. package/dist/heart/daemon/skill-management-installer.js +1 -1
  252. package/dist/heart/daemon/socket-client.js +180 -12
  253. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  254. package/dist/heart/daemon/startup-tui.js +339 -0
  255. package/dist/heart/daemon/supercronic-supervisor.js +282 -0
  256. package/dist/heart/daemon/task-scheduler.js +117 -39
  257. package/dist/heart/daemon/terminal-ui.js +503 -0
  258. package/dist/heart/daemon/thoughts.js +138 -54
  259. package/dist/heart/daemon/up-progress.js +366 -0
  260. package/dist/heart/daemon/vault-items.js +56 -0
  261. package/dist/heart/delegation.js +1 -4
  262. package/dist/heart/external-events/router.js +1531 -0
  263. package/dist/heart/failure-reports.js +336 -0
  264. package/dist/heart/file-lock.js +109 -0
  265. package/dist/heart/frontend-approval-runtime.js +506 -0
  266. package/dist/heart/frontend-journal.js +215 -0
  267. package/dist/heart/frontend-session-service.js +271 -0
  268. package/dist/heart/frontend-socket-client.js +173 -0
  269. package/dist/heart/frontend-socket.js +434 -0
  270. package/dist/heart/frontend-turn-errors.js +20 -0
  271. package/dist/heart/habits/habit-cancel.js +810 -0
  272. package/dist/heart/habits/habit-lifecycle.js +1327 -0
  273. package/dist/heart/habits/habit-migration.js +194 -0
  274. package/dist/heart/habits/habit-parser.js +278 -0
  275. package/dist/heart/habits/habit-runtime-state.js +93 -0
  276. package/dist/heart/habits/habit-scheduler.js +667 -0
  277. package/dist/heart/habits/habit-session-summary.js +318 -0
  278. package/dist/heart/habits/habit-session.js +636 -0
  279. package/dist/heart/{daemon → hatch}/hatch-flow.js +68 -62
  280. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  281. package/dist/heart/{daemon → hatch}/specialist-prompt.js +13 -9
  282. package/dist/heart/{daemon → hatch}/specialist-tools.js +100 -20
  283. package/dist/heart/identity.js +264 -59
  284. package/dist/heart/kept-notes.js +289 -0
  285. package/dist/heart/kicks.js +1 -1
  286. package/dist/heart/machine-identity.js +175 -0
  287. package/dist/heart/mail-import-discovery.js +356 -0
  288. package/dist/heart/mailbox/mailbox-http-hooks.js +99 -0
  289. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  290. package/dist/heart/mailbox/mailbox-http-routes.js +406 -0
  291. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  292. package/dist/heart/mailbox/mailbox-http-transport.js +272 -0
  293. package/dist/heart/mailbox/mailbox-http.js +99 -0
  294. package/dist/heart/mailbox/mailbox-read.js +41 -0
  295. package/dist/heart/mailbox/mailbox-supervision.js +131 -0
  296. package/dist/heart/mailbox/mailbox-types.js +27 -0
  297. package/dist/heart/mailbox/mailbox-view.js +197 -0
  298. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  299. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  300. package/dist/heart/mailbox/readers/mail.js +375 -0
  301. package/dist/heart/mailbox/readers/runtime-readers.js +823 -0
  302. package/dist/heart/mailbox/readers/sessions.js +231 -0
  303. package/dist/heart/mailbox/readers/shared.js +111 -0
  304. package/dist/heart/mcp/mcp-server.js +760 -0
  305. package/dist/heart/migrate-config.js +100 -0
  306. package/dist/heart/model-capabilities.js +83 -16
  307. package/dist/heart/optional-packages.js +77 -0
  308. package/dist/heart/orientation-frame.js +376 -0
  309. package/dist/heart/platform.js +81 -0
  310. package/dist/heart/primitives.js +1 -1
  311. package/dist/heart/private-runtime/decision-renderer.js +158 -0
  312. package/dist/heart/private-runtime/index.js +18 -0
  313. package/dist/heart/private-runtime/ledger.js +212 -0
  314. package/dist/heart/private-runtime/policy.js +295 -0
  315. package/dist/heart/private-runtime/types.js +2 -0
  316. package/dist/heart/progress-story.js +1 -1
  317. package/dist/heart/provider-attempt.js +137 -0
  318. package/dist/heart/provider-binding-resolver.js +273 -0
  319. package/dist/heart/provider-credentials.js +449 -0
  320. package/dist/heart/provider-failover.js +311 -0
  321. package/dist/heart/provider-models.js +96 -0
  322. package/dist/heart/provider-ping.js +266 -0
  323. package/dist/heart/provider-readiness-cache.js +119 -0
  324. package/dist/heart/provider-visibility.js +188 -0
  325. package/dist/heart/providers/account-pool.js +676 -0
  326. package/dist/heart/providers/anthropic-token.js +131 -0
  327. package/dist/heart/providers/anthropic.js +287 -72
  328. package/dist/heart/providers/azure.js +27 -12
  329. package/dist/heart/providers/error-classification.js +129 -0
  330. package/dist/heart/providers/github-copilot.js +121 -38
  331. package/dist/heart/providers/minimax-vlm.js +189 -0
  332. package/dist/heart/providers/minimax.js +26 -8
  333. package/dist/heart/providers/openai-codex-token.js +349 -0
  334. package/dist/heart/providers/openai-codex.js +55 -40
  335. package/dist/heart/providers/openai-compatible.js +177 -0
  336. package/dist/heart/quota/fleet-readings.js +222 -0
  337. package/dist/heart/quota/tranche.js +59 -0
  338. package/dist/heart/reach-channel.js +85 -0
  339. package/dist/heart/reply-style.js +52 -0
  340. package/dist/heart/run-ledger.js +247 -0
  341. package/dist/heart/runtime-capability-check.js +170 -0
  342. package/dist/heart/runtime-credentials.js +647 -0
  343. package/dist/heart/runtime-cwd.js +87 -0
  344. package/dist/heart/sense-truth.js +26 -4
  345. package/dist/heart/session-activity.js +94 -24
  346. package/dist/heart/session-events.js +1596 -0
  347. package/dist/heart/session-playback-cli-main.js +5 -0
  348. package/dist/heart/session-playback-cli.js +36 -0
  349. package/dist/heart/session-playback.js +231 -0
  350. package/dist/heart/session-redaction-repair-cli-main.js +31 -0
  351. package/dist/heart/session-redaction-repair.js +552 -0
  352. package/dist/heart/session-stats-cli-main.js +5 -0
  353. package/dist/heart/session-stats.js +183 -0
  354. package/dist/heart/session-transcript.js +133 -0
  355. package/dist/heart/shelf-claims.js +82 -0
  356. package/dist/heart/shepherd/custody-types.js +2 -0
  357. package/dist/heart/shepherd/mandates.js +352 -0
  358. package/dist/heart/shepherd/operation-commands.js +19 -0
  359. package/dist/heart/shepherd/operations.js +135 -0
  360. package/dist/heart/shepherd/supervision.js +114 -0
  361. package/dist/heart/shepherd/types.js +2 -0
  362. package/dist/heart/shepherd-config.js +123 -0
  363. package/dist/heart/source-grounding.js +313 -0
  364. package/dist/heart/start-of-turn-packet.js +372 -0
  365. package/dist/heart/steward-policy.js +656 -0
  366. package/dist/heart/streaming.js +624 -206
  367. package/dist/heart/structured-output.js +196 -0
  368. package/dist/heart/sync-classification.js +176 -0
  369. package/dist/heart/sync-health.js +152 -0
  370. package/dist/heart/sync-lock.js +431 -0
  371. package/dist/heart/sync.js +1579 -0
  372. package/dist/heart/target-resolution.js +11 -7
  373. package/dist/heart/tempo.js +93 -0
  374. package/dist/heart/temporal-view.js +41 -0
  375. package/dist/heart/timeouts.js +101 -0
  376. package/dist/heart/tool-activity-callbacks.js +59 -0
  377. package/dist/heart/tool-approval.js +382 -0
  378. package/dist/heart/tool-description.js +155 -0
  379. package/dist/heart/tool-friction.js +55 -0
  380. package/dist/heart/tool-images.js +42 -0
  381. package/dist/heart/tool-loop.js +206 -0
  382. package/dist/heart/tool-output-budget.js +41 -0
  383. package/dist/heart/turn-context.js +503 -0
  384. package/dist/heart/turn-execution-lease.js +30 -0
  385. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  386. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +3 -2
  387. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  388. package/dist/heart/versioning/ouro-recovery-launcher.js +76 -0
  389. package/dist/heart/versioning/ouro-version-manager.js +432 -0
  390. package/dist/heart/versioning/release-sources.js +173 -0
  391. package/dist/heart/versioning/self-update-defaults.js +358 -0
  392. package/dist/heart/versioning/self-update.js +205 -0
  393. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  394. package/dist/heart/{daemon → versioning}/update-checker.js +6 -1
  395. package/dist/heart/versioning/update-hooks.js +154 -0
  396. package/dist/heart/versioning/update-state.js +126 -0
  397. package/dist/heart/versioning/updater-launchd.js +150 -0
  398. package/dist/heart/versioning/version-intent.js +114 -0
  399. package/dist/heart/work-card.js +380 -0
  400. package/dist/mailbox-ui/assets/index-Dbska1tZ.js +1 -0
  401. package/dist/mailbox-ui/assets/index-DsiKaPyH.css +1 -0
  402. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
  403. package/dist/mailbox-ui/index.html +16 -0
  404. package/dist/mailroom/attention.js +167 -0
  405. package/dist/mailroom/autonomy.js +209 -0
  406. package/dist/mailroom/azure-sdk.js +27 -0
  407. package/dist/mailroom/blob-store.js +889 -0
  408. package/dist/mailroom/body-cache.js +61 -0
  409. package/dist/mailroom/cache-sync-cli.js +58 -0
  410. package/dist/mailroom/core.js +805 -0
  411. package/dist/mailroom/entry.js +160 -0
  412. package/dist/mailroom/file-store.js +568 -0
  413. package/dist/mailroom/hosted-cache-sync.js +384 -0
  414. package/dist/mailroom/mbox-import.js +393 -0
  415. package/dist/mailroom/migration.js +164 -0
  416. package/dist/mailroom/outbound.js +380 -0
  417. package/dist/mailroom/policy.js +263 -0
  418. package/dist/mailroom/reader.js +291 -0
  419. package/dist/mailroom/search-cache.js +513 -0
  420. package/dist/mailroom/search-relevance.js +319 -0
  421. package/dist/mailroom/smtp-ingress.js +176 -0
  422. package/dist/mailroom/source-state.js +176 -0
  423. package/dist/mailroom/thread.js +109 -0
  424. package/dist/mailroom/travel-extract.js +89 -0
  425. package/dist/mind/bundle-manifest.js +25 -2
  426. package/dist/mind/context.js +328 -139
  427. package/dist/mind/desk-section.js +362 -0
  428. package/dist/mind/diary-integrity.js +60 -0
  429. package/dist/mind/{memory.js → diary.js} +68 -77
  430. package/dist/mind/embedding-provider.js +60 -0
  431. package/dist/mind/file-state.js +179 -0
  432. package/dist/mind/friend-link-codes.js +209 -0
  433. package/dist/mind/friend-merge.js +336 -0
  434. package/dist/mind/house-names.js +43 -0
  435. package/dist/mind/{associative-recall.js → note-search.js} +47 -58
  436. package/dist/mind/obligation-steering.js +36 -130
  437. package/dist/mind/outbound-record.js +168 -0
  438. package/dist/mind/pending.js +36 -10
  439. package/dist/mind/prompt-budget.js +479 -0
  440. package/dist/mind/prompt-refresh.js +3 -2
  441. package/dist/mind/prompt.js +1209 -218
  442. package/dist/mind/provenance-trust.js +26 -0
  443. package/dist/mind/record-paths.js +312 -0
  444. package/dist/mind/scrutiny.js +173 -0
  445. package/dist/mind/session-transaction.js +622 -0
  446. package/dist/mind/where-am-i.js +122 -0
  447. package/dist/nerves/cli-logging.js +7 -1
  448. package/dist/nerves/coverage/audit-rules.js +15 -6
  449. package/dist/nerves/coverage/audit.js +28 -2
  450. package/dist/nerves/coverage/cli.js +1 -1
  451. package/dist/nerves/coverage/contract.js +5 -5
  452. package/dist/nerves/coverage/file-completeness.js +146 -5
  453. package/dist/nerves/coverage/run-artifacts.js +55 -35
  454. package/dist/nerves/coverage/source-scanner.js +4 -4
  455. package/dist/nerves/event-buffer.js +111 -0
  456. package/dist/nerves/index.js +293 -9
  457. package/dist/nerves/observation.js +20 -0
  458. package/dist/nerves/redact.js +79 -0
  459. package/dist/nerves/review/cli-main.js +5 -0
  460. package/dist/nerves/review/cli.js +156 -0
  461. package/dist/nerves/review/core.js +159 -0
  462. package/dist/nerves/runtime.js +17 -1
  463. package/dist/repertoire/ado-client.js +15 -56
  464. package/dist/repertoire/ado-semantic.js +16 -10
  465. package/dist/repertoire/api-client.js +97 -0
  466. package/dist/repertoire/bitwarden-native.js +458 -0
  467. package/dist/repertoire/bitwarden-store.js +1296 -0
  468. package/dist/repertoire/bundle-templates.js +71 -0
  469. package/dist/repertoire/bw-installer.js +268 -0
  470. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  471. package/dist/repertoire/coding/context-pack.js +331 -0
  472. package/dist/repertoire/coding/feedback.js +54 -22
  473. package/dist/repertoire/coding/index.js +15 -3
  474. package/dist/repertoire/coding/manager.js +159 -10
  475. package/dist/repertoire/coding/spawner.js +40 -11
  476. package/dist/repertoire/coding/tools.js +133 -18
  477. package/dist/repertoire/coding/workbench-client.js +272 -0
  478. package/dist/repertoire/coding/workbench-manager.js +346 -0
  479. package/dist/repertoire/commerce-errors.js +109 -0
  480. package/dist/repertoire/commerce-self-test.js +156 -0
  481. package/dist/repertoire/credential-access.js +183 -0
  482. package/dist/repertoire/desk/classifier.js +362 -0
  483. package/dist/repertoire/duffel-client.js +185 -0
  484. package/dist/repertoire/github-client.js +14 -55
  485. package/dist/repertoire/graph-client.js +11 -52
  486. package/dist/repertoire/guardrails.js +1498 -25
  487. package/dist/repertoire/house-sweep.js +471 -0
  488. package/dist/repertoire/mcp-client.js +58 -5
  489. package/dist/repertoire/mcp-manager.js +427 -139
  490. package/dist/repertoire/mcp-tools.js +148 -0
  491. package/dist/repertoire/mcp-write-guard.js +46 -0
  492. package/dist/repertoire/plugin-mcp.js +175 -0
  493. package/dist/repertoire/plugins.js +253 -0
  494. package/dist/repertoire/relationship-authorization.js +322 -0
  495. package/dist/repertoire/sanctuary-container-policy.js +50 -0
  496. package/dist/repertoire/shell-sessions.js +135 -0
  497. package/dist/repertoire/skills.js +48 -4
  498. package/dist/repertoire/stripe-client.js +163 -0
  499. package/dist/repertoire/tool-arguments.js +182 -0
  500. package/dist/repertoire/tool-limits.js +20 -0
  501. package/dist/repertoire/tool-results.js +29 -0
  502. package/dist/repertoire/tools-a2a.js +742 -0
  503. package/dist/repertoire/tools-app-sessions.js +331 -0
  504. package/dist/repertoire/tools-attachments.js +322 -0
  505. package/dist/repertoire/tools-awaiting.js +897 -0
  506. package/dist/repertoire/tools-base.js +85 -1168
  507. package/dist/repertoire/tools-bluebubbles.js +2 -0
  508. package/dist/repertoire/tools-bridge.js +144 -0
  509. package/dist/repertoire/tools-bundle.js +917 -0
  510. package/dist/repertoire/tools-commerce.js +253 -0
  511. package/dist/repertoire/tools-config.js +186 -0
  512. package/dist/repertoire/tools-continuity.js +588 -0
  513. package/dist/repertoire/tools-credential.js +383 -0
  514. package/dist/repertoire/tools-escalation.js +84 -0
  515. package/dist/repertoire/tools-evolution.js +527 -0
  516. package/dist/repertoire/tools-files.js +463 -0
  517. package/dist/repertoire/tools-flight.js +290 -0
  518. package/dist/repertoire/tools-flow.js +119 -0
  519. package/dist/repertoire/tools-friend-link.js +57 -0
  520. package/dist/repertoire/tools-github.js +3 -8
  521. package/dist/repertoire/tools-habits.js +103 -0
  522. package/dist/repertoire/tools-house-care.js +174 -0
  523. package/dist/repertoire/tools-mail.js +1828 -0
  524. package/dist/repertoire/tools-notes.js +501 -0
  525. package/dist/repertoire/tools-obligations.js +182 -0
  526. package/dist/repertoire/tools-orientation.js +31 -0
  527. package/dist/repertoire/tools-record.js +482 -0
  528. package/dist/repertoire/tools-rsvp.js +139 -0
  529. package/dist/repertoire/tools-runtime.js +238 -0
  530. package/dist/repertoire/tools-sanctuary-host.js +202 -0
  531. package/dist/repertoire/tools-session.js +1141 -0
  532. package/dist/repertoire/tools-shell.js +229 -0
  533. package/dist/repertoire/tools-shepherd-guidance.js +171 -0
  534. package/dist/repertoire/tools-shepherd.js +325 -0
  535. package/dist/repertoire/tools-steward-policy.js +147 -0
  536. package/dist/repertoire/tools-stripe.js +224 -0
  537. package/dist/repertoire/tools-surface.js +369 -0
  538. package/dist/repertoire/tools-teams.js +50 -39
  539. package/dist/repertoire/tools-telegram-contacts.js +37 -0
  540. package/dist/repertoire/tools-travel.js +125 -0
  541. package/dist/repertoire/tools-trip.js +982 -0
  542. package/dist/repertoire/tools-unraid.js +556 -0
  543. package/dist/repertoire/tools-user-profile.js +146 -0
  544. package/dist/repertoire/tools-vault.js +40 -0
  545. package/dist/repertoire/tools-voice-local.js +198 -0
  546. package/dist/repertoire/tools-voice.js +145 -0
  547. package/dist/repertoire/tools-web.js +230 -0
  548. package/dist/repertoire/tools.js +527 -156
  549. package/dist/repertoire/travel-api-client.js +360 -0
  550. package/dist/repertoire/unraid-client.js +155 -0
  551. package/dist/repertoire/unraid-restart.js +339 -0
  552. package/dist/repertoire/user-profile.js +131 -0
  553. package/dist/repertoire/vault-setup.js +298 -0
  554. package/dist/repertoire/vault-unlock.js +700 -0
  555. package/dist/rsvp/aisleplanner-client.js +354 -0
  556. package/dist/rsvp/cli.js +936 -0
  557. package/dist/rsvp/config.js +327 -0
  558. package/dist/rsvp/cutover.js +453 -0
  559. package/dist/rsvp/diagnostics.js +232 -0
  560. package/dist/rsvp/diff-renderer.js +176 -0
  561. package/dist/rsvp/habit-policy.js +110 -0
  562. package/dist/rsvp/habit-stage.js +123 -0
  563. package/dist/rsvp/incident-bundle.js +97 -0
  564. package/dist/rsvp/migration.js +204 -0
  565. package/dist/rsvp/native-habit-runner.js +630 -0
  566. package/dist/rsvp/outbound-state.js +628 -0
  567. package/dist/rsvp/query.js +118 -0
  568. package/dist/rsvp/replay.js +233 -0
  569. package/dist/rsvp/snapshot.js +232 -0
  570. package/dist/rsvp/spend-ledger.js +175 -0
  571. package/dist/scripts/claude-code-hook.js +41 -0
  572. package/dist/scripts/claude-code-stop-hook.js +47 -0
  573. package/dist/senses/a2a-entry.js +140 -0
  574. package/dist/senses/acp-server.js +386 -0
  575. package/dist/senses/app-sessions/client.js +558 -0
  576. package/dist/senses/app-sessions/sense.js +156 -0
  577. package/dist/senses/app-sessions/store.js +151 -0
  578. package/dist/senses/app-sessions-entry.js +72 -0
  579. package/dist/senses/attention-queue.js +186 -0
  580. package/dist/senses/await-turn-message.js +65 -0
  581. package/dist/senses/bluebubbles/active-turns.js +216 -0
  582. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  583. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  584. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +393 -43
  585. package/dist/senses/bluebubbles/context-packet.js +207 -0
  586. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  587. package/dist/senses/bluebubbles/entry.js +90 -0
  588. package/dist/senses/bluebubbles/host-account-verifier.js +88 -0
  589. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +21 -3
  590. package/dist/senses/bluebubbles/index.js +4054 -0
  591. package/dist/senses/bluebubbles/latest-turn.js +311 -0
  592. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -71
  593. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +159 -28
  594. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +24 -13
  595. package/dist/senses/bluebubbles/outbound-state.js +335 -0
  596. package/dist/senses/bluebubbles/processed-log.js +133 -0
  597. package/dist/senses/bluebubbles/reaction-policy.js +47 -0
  598. package/dist/senses/bluebubbles/replay.js +284 -0
  599. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  600. package/dist/senses/bluebubbles/semantic-receipts.js +1986 -0
  601. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  602. package/dist/senses/bluebubbles/webhook-registration.js +257 -0
  603. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  604. package/dist/senses/cli/bracketed-paste.js +82 -0
  605. package/dist/senses/cli/image-paste.js +287 -0
  606. package/dist/senses/cli/image-ref-navigation.js +75 -0
  607. package/dist/senses/cli/ink-app.js +156 -0
  608. package/dist/senses/cli/inline-diff.js +64 -0
  609. package/dist/senses/cli/input-keys.js +174 -0
  610. package/dist/senses/cli/kill-ring.js +86 -0
  611. package/dist/senses/cli/message-list.js +51 -0
  612. package/dist/senses/cli/ouro-tui.js +607 -0
  613. package/dist/senses/cli/spinner-imperative.js +135 -0
  614. package/dist/senses/cli/spinner.js +101 -0
  615. package/dist/senses/cli/status-line.js +60 -0
  616. package/dist/senses/cli/streaming-markdown.js +526 -0
  617. package/dist/senses/cli/tool-display.js +85 -0
  618. package/dist/senses/cli/tool-render.js +85 -0
  619. package/dist/senses/cli/tui-store.js +252 -0
  620. package/dist/senses/cli/virtual-list.js +35 -0
  621. package/dist/senses/cli-entry.js +60 -8
  622. package/dist/senses/cli.js +608 -318
  623. package/dist/senses/commands.js +66 -3
  624. package/dist/senses/context-packet-ledger.js +371 -0
  625. package/dist/senses/context-packets.js +154 -0
  626. package/dist/senses/habit-lifecycle-guard.js +24 -0
  627. package/dist/senses/habit-turn-message.js +160 -0
  628. package/dist/senses/ingress-evidence.js +2 -0
  629. package/dist/senses/mail-entry.js +68 -0
  630. package/dist/senses/mail.js +524 -0
  631. package/dist/senses/pipeline.js +1190 -252
  632. package/dist/senses/private-runtime-worker.js +857 -0
  633. package/dist/senses/private-runtime.js +1671 -0
  634. package/dist/senses/proactive-content-guard.js +51 -0
  635. package/dist/senses/root-host-approval-port.js +345 -0
  636. package/dist/senses/root-host-approval-runtime.js +393 -0
  637. package/dist/senses/sanctuary-authority-resident.js +102 -0
  638. package/dist/senses/sanctuary-download-credit-presentation.js +31 -0
  639. package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
  640. package/dist/senses/sanctuary-grounding.js +118 -0
  641. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +12 -0
  642. package/dist/senses/sanctuary-health-acceptance-probe.js +786 -0
  643. package/dist/senses/sanctuary-health-runner.js +106 -0
  644. package/dist/senses/sanctuary-health.js +442 -0
  645. package/dist/senses/sanctuary-house.js +97 -0
  646. package/dist/senses/sanctuary-install-state-contract.js +169 -0
  647. package/dist/senses/sanctuary-interactive-control.js +410 -0
  648. package/dist/senses/sanctuary-media-catalog-contract.js +268 -0
  649. package/dist/senses/sanctuary-media-optimization.js +517 -0
  650. package/dist/senses/sanctuary-runtime.js +390 -0
  651. package/dist/senses/sanctuary-sab.js +85 -0
  652. package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
  653. package/dist/senses/shared-turn.js +832 -0
  654. package/dist/senses/shepherd/agent-presentation.js +88 -0
  655. package/dist/senses/shepherd/attention-page.js +166 -0
  656. package/dist/senses/shepherd/attention-sidebar.js +76 -0
  657. package/dist/senses/shepherd/attention.js +295 -0
  658. package/dist/senses/shepherd/checkin-config.js +76 -0
  659. package/dist/senses/shepherd/checkin-store.js +386 -0
  660. package/dist/senses/shepherd/client.js +196 -0
  661. package/dist/senses/shepherd/cmux.js +483 -0
  662. package/dist/senses/shepherd/composer.js +336 -0
  663. package/dist/senses/shepherd/copilot-app.js +648 -0
  664. package/dist/senses/shepherd/feedback-reply.js +108 -0
  665. package/dist/senses/shepherd/feedback-source.js +20 -0
  666. package/dist/senses/shepherd/feedback-store.js +331 -0
  667. package/dist/senses/shepherd/feedback-submit.js +182 -0
  668. package/dist/senses/shepherd/feedback-worker.js +208 -0
  669. package/dist/senses/shepherd/guidance.js +273 -0
  670. package/dist/senses/shepherd/herdr.js +427 -0
  671. package/dist/senses/shepherd/host.js +17 -0
  672. package/dist/senses/shepherd/human-decision-guard.js +29 -0
  673. package/dist/senses/shepherd/judge-evaluation-command.js +183 -0
  674. package/dist/senses/shepherd/judge-evaluation-entry.js +13 -0
  675. package/dist/senses/shepherd/judge-evaluation.js +155 -0
  676. package/dist/senses/shepherd/judge.js +210 -0
  677. package/dist/senses/shepherd/notice-outbox.js +262 -0
  678. package/dist/senses/shepherd/observation-publisher.js +320 -0
  679. package/dist/senses/shepherd/operations-defaults.js +86 -0
  680. package/dist/senses/shepherd/operations.js +159 -0
  681. package/dist/senses/shepherd/owner-notice.js +490 -0
  682. package/dist/senses/shepherd/prompt-state.js +60 -0
  683. package/dist/senses/shepherd/recovery.js +543 -0
  684. package/dist/senses/shepherd/redact.js +66 -0
  685. package/dist/senses/shepherd/returns.js +79 -0
  686. package/dist/senses/shepherd/sense.js +849 -0
  687. package/dist/senses/shepherd/shepherd-judge-corpus-v1.json +170 -0
  688. package/dist/senses/shepherd/surface.js +123 -0
  689. package/dist/senses/shepherd/target-binding.js +13 -0
  690. package/dist/senses/shepherd/terminal-process.js +147 -0
  691. package/dist/senses/shepherd-entry.js +98 -0
  692. package/dist/senses/surface-tool.js +109 -0
  693. package/dist/senses/teams-entry.js +70 -8
  694. package/dist/senses/teams-image.js +119 -0
  695. package/dist/senses/teams.js +998 -337
  696. package/dist/senses/telegram-admission.js +718 -0
  697. package/dist/senses/telegram-approval-runtime.js +793 -0
  698. package/dist/senses/telegram-attachments.js +186 -0
  699. package/dist/senses/telegram-audit-ledger.js +220 -0
  700. package/dist/senses/telegram-authority-transport.js +231 -0
  701. package/dist/senses/telegram-client.js +1755 -0
  702. package/dist/senses/telegram-effect-adapter.js +904 -0
  703. package/dist/senses/telegram-entry.js +86 -0
  704. package/dist/senses/telegram-handoff.js +154 -0
  705. package/dist/senses/telegram.js +2474 -0
  706. package/dist/senses/terminal-handoff.js +44 -0
  707. package/dist/senses/trust-gate.js +104 -9
  708. package/dist/senses/voice/audio-playback.js +237 -0
  709. package/dist/senses/voice/audio-routing.js +119 -0
  710. package/dist/senses/voice/call-auth.js +250 -0
  711. package/dist/senses/voice/elevenlabs.js +202 -0
  712. package/dist/senses/voice/floor-control.js +431 -0
  713. package/dist/senses/voice/floor-controller.js +115 -0
  714. package/dist/senses/voice/golden-path.js +116 -0
  715. package/dist/senses/voice/index.js +29 -0
  716. package/dist/senses/voice/local-audio-control.js +344 -0
  717. package/dist/senses/voice/local-audio-devices.js +516 -0
  718. package/dist/senses/voice/local-audio-disclosure.js +174 -0
  719. package/dist/senses/voice/local-audio-identity.js +103 -0
  720. package/dist/senses/voice/local-audio-join.js +325 -0
  721. package/dist/senses/voice/local-audio-mute.js +199 -0
  722. package/dist/senses/voice/local-audio-notify.js +124 -0
  723. package/dist/senses/voice/local-audio-prompts.js +116 -0
  724. package/dist/senses/voice/local-audio-transport.js +427 -0
  725. package/dist/senses/voice/local-audio.js +281 -0
  726. package/dist/senses/voice/local-media-stream.js +145 -0
  727. package/dist/senses/voice/meeting.js +113 -0
  728. package/dist/senses/voice/outbound.js +190 -0
  729. package/dist/senses/voice/phone.js +33 -0
  730. package/dist/senses/voice/playback.js +139 -0
  731. package/dist/senses/voice/process-guards.js +51 -0
  732. package/dist/senses/voice/realtime-eval.js +496 -0
  733. package/dist/senses/voice/realtime-tool-schema.js +195 -0
  734. package/dist/senses/voice/realtime-trace.js +531 -0
  735. package/dist/senses/voice/transcript.js +70 -0
  736. package/dist/senses/voice/turn.js +191 -0
  737. package/dist/senses/voice/twilio-phone-runtime.js +836 -0
  738. package/dist/senses/voice/twilio-phone.js +5454 -0
  739. package/dist/senses/voice/types.js +2 -0
  740. package/dist/senses/voice/whisper.js +161 -0
  741. package/dist/senses/voice-entry.js +83 -0
  742. package/dist/senses/voice-realtime-eval-command.js +99 -0
  743. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  744. package/dist/senses/voice-twilio-entry.js +87 -0
  745. package/dist/trips/core.js +138 -0
  746. package/dist/trips/store.js +265 -0
  747. package/dist/util/frontmatter.js +69 -0
  748. package/npm-shrinkwrap.json +8728 -0
  749. package/package.json +80 -14
  750. package/skills/agent-commerce.md +113 -0
  751. package/skills/browser-navigation.md +117 -0
  752. package/skills/commerce-setup-guide.md +116 -0
  753. package/skills/commerce-setup.md +84 -0
  754. package/skills/configure-dev-tools.md +99 -0
  755. package/skills/travel-planning.md +138 -0
  756. package/dist/heart/daemon/auth-flow.js +0 -430
  757. package/dist/heart/daemon/ouro-path-installer.js +0 -260
  758. package/dist/heart/daemon/ouro-version-manager.js +0 -171
  759. package/dist/heart/daemon/update-hooks.js +0 -138
  760. package/dist/heart/obligations.js +0 -197
  761. package/dist/heart/safe-workspace.js +0 -381
  762. package/dist/heart/session-recall.js +0 -116
  763. package/dist/mind/friends/channel.js +0 -84
  764. package/dist/mind/friends/group-context.js +0 -144
  765. package/dist/mind/friends/resolver.js +0 -84
  766. package/dist/mind/friends/store-file.js +0 -190
  767. package/dist/mind/friends/store.js +0 -4
  768. package/dist/mind/friends/tokens.js +0 -26
  769. package/dist/mind/friends/trust-explanation.js +0 -74
  770. package/dist/mind/friends/types.js +0 -29
  771. package/dist/repertoire/tasks/board.js +0 -134
  772. package/dist/repertoire/tasks/index.js +0 -224
  773. package/dist/repertoire/tasks/lifecycle.js +0 -80
  774. package/dist/repertoire/tasks/middleware.js +0 -65
  775. package/dist/repertoire/tasks/parser.js +0 -173
  776. package/dist/repertoire/tasks/scanner.js +0 -132
  777. package/dist/repertoire/tasks/transitions.js +0 -144
  778. package/dist/senses/bluebubbles-entry.js +0 -13
  779. package/dist/senses/bluebubbles.js +0 -1181
  780. package/dist/senses/debug-activity.js +0 -154
  781. package/dist/senses/inner-dialog-worker.js +0 -90
  782. package/dist/senses/inner-dialog.js +0 -533
  783. package/subagents/README.md +0 -7
  784. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  785. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  786. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  787. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  788. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  789. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  790. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  791. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  792. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  793. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  794. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  795. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  796. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  797. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  798. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  799. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  800. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -34,43 +34,476 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.OuroDaemon = void 0;
37
+ exports.messageFromHabitPokeError = messageFromHabitPokeError;
38
+ exports.parseOrphanPidsFromPs = parseOrphanPidsFromPs;
39
+ exports.filterPidfilePidsToActualOrphans = filterPidfilePidsToActualOrphans;
40
+ exports.mergeUniqueOrphanPids = mergeUniqueOrphanPids;
41
+ exports.waitForOrphanProcessesToSettle = waitForOrphanProcessesToSettle;
42
+ exports.assertOrphanCleanupComplete = assertOrphanCleanupComplete;
43
+ exports.drainOrphanProcessesBeforeStartup = drainOrphanProcessesBeforeStartup;
44
+ exports.killOrphanProcesses = killOrphanProcesses;
45
+ exports.writePidfile = writePidfile;
46
+ exports.handleAgentSenseTurn = handleAgentSenseTurn;
47
+ exports.handleAgentAskTurn = handleAgentAskTurn;
37
48
  const fs = __importStar(require("fs"));
38
49
  const net = __importStar(require("net"));
50
+ const os = __importStar(require("os"));
39
51
  const path = __importStar(require("path"));
52
+ const node_crypto_1 = require("node:crypto");
40
53
  const identity_1 = require("../identity");
54
+ const agent_discovery_1 = require("./agent-discovery");
41
55
  const runtime_1 = require("../../nerves/runtime");
42
56
  const runtime_metadata_1 = require("./runtime-metadata");
43
57
  const runtime_mode_1 = require("./runtime-mode");
44
- const update_hooks_1 = require("./update-hooks");
58
+ const update_hooks_1 = require("../versioning/update-hooks");
45
59
  const bundle_meta_1 = require("./hooks/bundle-meta");
60
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
46
61
  const bundle_manifest_1 = require("../../mind/bundle-manifest");
47
- const update_checker_1 = require("./update-checker");
48
- const staged_restart_1 = require("./staged-restart");
62
+ const update_checker_1 = require("../versioning/update-checker");
49
63
  const child_process_1 = require("child_process");
50
64
  const pending_1 = require("../../mind/pending");
51
- const channel_1 = require("../../mind/friends/channel");
65
+ const agent_service_1 = require("./agent-service");
66
+ const friends_1 = require("@ouro.bot/friends");
52
67
  const mcp_manager_1 = require("../../repertoire/mcp-manager");
68
+ const mcp_tools_1 = require("../../repertoire/mcp-tools");
69
+ const mailbox_http_1 = require("../mailbox/mailbox-http");
70
+ const mailbox_types_1 = require("../mailbox/mailbox-types");
71
+ const mailbox_read_1 = require("../mailbox/mailbox-read");
72
+ const mailbox_view_1 = require("../mailbox/mailbox-view");
73
+ const provider_visibility_1 = require("../provider-visibility");
74
+ const provider_binding_resolver_1 = require("../provider-binding-resolver");
75
+ const private_runtime_1 = require("../private-runtime");
76
+ const socket_client_1 = require("./socket-client");
77
+ const flight_recorder_1 = require("../../arc/flight-recorder");
78
+ const await_private_wake_1 = require("./await-private-wake");
79
+ const habit_private_wake_1 = require("./habit-private-wake");
80
+ const habit_parser_1 = require("../habits/habit-parser");
81
+ const habit_runtime_state_1 = require("../habits/habit-runtime-state");
82
+ const router_1 = require("../external-events/router");
83
+ const habit_policy_1 = require("../../rsvp/habit-policy");
84
+ const container_runtime_1 = require("./container-runtime");
85
+ const habit_session_1 = require("../habits/habit-session");
86
+ const turn_execution_lease_1 = require("../turn-execution-lease");
87
+ const frontend_session_service_1 = require("../frontend-session-service");
88
+ const frontend_socket_1 = require("../frontend-socket");
89
+ const frontend_journal_1 = require("../frontend-journal");
90
+ const frontend_approval_runtime_1 = require("../frontend-approval-runtime");
91
+ const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
92
+ /**
93
+ * Defense-in-depth: detect if we're running under vitest. The pidfile lives
94
+ * at a hardcoded path under the user's real ~/.ouro-cli/ — there's no DI
95
+ * seam to redirect it. So when a test creates a real OuroDaemon and calls
96
+ * start(), the daemon's killOrphanProcesses() reads the REAL pidfile,
97
+ * ps-verifies the PIDs, and SIGTERMs the production daemon. We saw this
98
+ * cause an outage on 2026-04-08 (alpha.265 daemon killed 93s after startup
99
+ * by a vitest test that called daemon.start()).
100
+ *
101
+ * Both killOrphanProcesses() and writePidfile() short-circuit under vitest
102
+ * to make the production pidfile sacred. Tests that need to verify these
103
+ * functions' behavior should use the extracted pure helpers
104
+ * (parseOrphanPidsFromPs, filterPidfilePidsToActualOrphans).
105
+ */
106
+ function isVitestProcess() {
107
+ /* v8 ignore next -- defensive: process and process.argv always exist in node @preserve */
108
+ if (typeof process === "undefined" || !Array.isArray(process.argv))
109
+ return false;
110
+ return process.argv.some((arg) => typeof arg === "string" && arg.includes("vitest"));
111
+ }
112
+ function messageFromHabitPokeError(error) {
113
+ if (error instanceof Error)
114
+ return error.message;
115
+ /* v8 ignore next -- defensive fallback for hostile/non-Error throws from filesystem or parsers @preserve */
116
+ return String(error);
117
+ }
118
+ /**
119
+ * Scan `ps -eo pid,ppid,command` output for daemon-owned entry points whose
120
+ * parent has died (PPID reparented to init/PID 1). Returns the list of PIDs
121
+ * that are safe to SIGTERM — true orphans, not children of live sibling
122
+ * daemons running from worktrees, test suites, or other users of the harness.
123
+ *
124
+ * Exported so unit tests can exercise the filter without shelling out.
125
+ */
126
+ function parseOrphanPidsFromPs(psOutput, selfPid) {
127
+ const orphans = [];
128
+ for (const line of psOutput.split("\n")) {
129
+ // Explicitly exclude MCP server processes — they share a harness entry
130
+ // point but are not daemon children and must never be killed.
131
+ if (line.includes("mcp-serve") || line.includes("mcp serve"))
132
+ continue;
133
+ // Match only daemon-owned JS entry points.
134
+ if (!line.includes("agent-entry.js")
135
+ && !line.includes("daemon-entry.js")
136
+ && !line.includes("bluebubbles/entry.js")
137
+ && !line.includes("mail-entry.js")
138
+ && !line.includes("teams-entry.js")
139
+ && !line.includes("a2a-entry.js")
140
+ && !line.includes("telegram-entry.js")
141
+ && !line.includes("voice-entry.js"))
142
+ continue;
143
+ // Parse `<pid> <ppid> <command...>`. ps pads these with leading spaces.
144
+ // Regex guarantees both groups are \d+ so parseInt can't produce NaN.
145
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s/);
146
+ if (!match)
147
+ continue;
148
+ const pid = parseInt(match[1], 10);
149
+ const ppid = parseInt(match[2], 10);
150
+ if (pid === selfPid)
151
+ continue;
152
+ // CRITICAL: only kill processes whose parent is init (PID 1). A live
153
+ // PPID means the process belongs to another daemon instance (parallel
154
+ // test run, sibling worktree, another user of /tmp/ouroboros-daemon.sock).
155
+ // Killing those will crash unrelated harnesses — we saw this in B6
156
+ // when a vitest worker's daemon killed a production agent's children.
157
+ if (ppid !== 1)
158
+ continue;
159
+ orphans.push(pid);
160
+ }
161
+ return orphans;
162
+ }
163
+ /**
164
+ * Given a list of PIDs from the pidfile, return only those that are actual
165
+ * orphans (PPID reparented to init/PID 1). Protects against a polluted
166
+ * pidfile killing a PID that the OS has reassigned to an unrelated process.
167
+ *
168
+ * Implementation: shells out to `ps -p <csv> -o pid,ppid` for a batch lookup.
169
+ * Returns the empty list if ps fails — safer to skip cleanup than to
170
+ * wildcard-kill on a bad read.
171
+ *
172
+ * Exported for direct unit coverage.
173
+ */
174
+ function filterPidfilePidsToActualOrphans(candidatePids, psRunner = runPsCheck) {
175
+ if (candidatePids.length === 0)
176
+ return [];
177
+ const psOutput = psRunner(candidatePids);
178
+ if (psOutput === null)
179
+ return [];
180
+ const survivingOrphans = [];
181
+ // `ps -p x,y,z -o pid,ppid` emits a header line then one row per found PID.
182
+ // PIDs not found (already exited) are silently omitted — which is the
183
+ // correct behavior for us: we only want to kill live orphans.
184
+ for (const line of psOutput.split("\n")) {
185
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
186
+ if (!match)
187
+ continue;
188
+ const pid = parseInt(match[1], 10);
189
+ const ppid = parseInt(match[2], 10);
190
+ if (ppid !== 1)
191
+ continue;
192
+ if (!candidatePids.includes(pid))
193
+ continue;
194
+ survivingOrphans.push(pid);
195
+ }
196
+ return survivingOrphans;
197
+ }
198
+ function mergeUniqueOrphanPids(...sources) {
199
+ const merged = [];
200
+ const seen = new Set();
201
+ for (const source of sources) {
202
+ for (const pid of source) {
203
+ if (seen.has(pid))
204
+ continue;
205
+ seen.add(pid);
206
+ merged.push(pid);
207
+ }
208
+ }
209
+ return merged;
210
+ }
211
+ const ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS = 5_000;
212
+ const ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS = 50;
213
+ /* v8 ignore start -- process liveness probe; pure wait behavior covered via injected deps @preserve */
214
+ function defaultIsPidAlive(pid) {
215
+ try {
216
+ process.kill(pid, 0);
217
+ return true;
218
+ }
219
+ catch (error) {
220
+ return error.code === "EPERM";
221
+ }
222
+ }
223
+ /* v8 ignore stop */
224
+ /* v8 ignore start -- real timer wiring; wait behavior covered via injected sleep @preserve */
225
+ async function defaultSettleSleep(ms) {
226
+ await new Promise((resolve) => setTimeout(resolve, ms));
227
+ }
228
+ /* v8 ignore stop */
229
+ async function waitForOrphanProcessesToSettle(pids, deps = {}) {
230
+ if (pids.length === 0)
231
+ return [];
232
+ const isPidAlive = deps.isPidAlive ?? defaultIsPidAlive;
233
+ const now = deps.now ?? Date.now;
234
+ const sleep = deps.sleep ?? defaultSettleSleep;
235
+ const timeoutMs = deps.timeoutMs ?? ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS;
236
+ const pollIntervalMs = deps.pollIntervalMs ?? ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS;
237
+ const deadline = now() + timeoutMs;
238
+ let survivors = pids.filter(isPidAlive);
239
+ while (survivors.length > 0 && now() < deadline) {
240
+ await sleep(pollIntervalMs);
241
+ survivors = pids.filter(isPidAlive);
242
+ }
243
+ return survivors;
244
+ }
245
+ function assertOrphanCleanupComplete(survivingPids) {
246
+ if (survivingPids.length === 0)
247
+ return;
248
+ const errorReason = `refusing startup while ${survivingPids.length} orphaned Ouro processes remain: ${survivingPids.join(", ")}`;
249
+ (0, runtime_1.emitNervesEvent)({
250
+ level: "error",
251
+ component: "daemon",
252
+ event: "daemon.orphan_cleanup_incomplete",
253
+ message: errorReason,
254
+ meta: { survivingPids },
255
+ });
256
+ throw new Error(errorReason);
257
+ }
258
+ const ORPHAN_CLEANUP_MAX_SIGNAL_PASSES = 8;
259
+ async function drainOrphanProcessesBeforeStartup(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH, deps = {}) {
260
+ const signalOrphans = deps.signalOrphans ?? killOrphanProcesses;
261
+ const settleOrphans = deps.settleOrphans ?? waitForOrphanProcessesToSettle;
262
+ const maxSignalPasses = deps.maxSignalPasses ?? ORPHAN_CLEANUP_MAX_SIGNAL_PASSES;
263
+ for (let pass = 0; pass < maxSignalPasses; pass += 1) {
264
+ const signaledPids = signalOrphans(socketPath);
265
+ if (signaledPids.length === 0)
266
+ return;
267
+ const survivingPids = await settleOrphans(signaledPids);
268
+ assertOrphanCleanupComplete(survivingPids);
269
+ }
270
+ const errorReason = `orphan cleanup did not reach a fixed point after ${maxSignalPasses} signaling round(s)`;
271
+ (0, runtime_1.emitNervesEvent)({
272
+ level: "error",
273
+ component: "daemon",
274
+ event: "daemon.orphan_cleanup_not_converged",
275
+ message: errorReason,
276
+ meta: { maxSignalPasses },
277
+ });
278
+ throw new Error(errorReason);
279
+ }
280
+ /* v8 ignore start -- shells out to ps; covered by filterPidfilePidsToActualOrphans unit tests via injected runner @preserve */
281
+ function runPsCheck(pids) {
282
+ try {
283
+ const csv = pids.join(",");
284
+ return (0, child_process_1.execSync)(`ps -p ${csv} -o pid=,ppid=`, { encoding: "utf-8", timeout: 5000 });
285
+ }
286
+ catch {
287
+ // ps returns non-zero when none of the requested PIDs exist. Treat as
288
+ // "no survivors" rather than an error.
289
+ return "";
290
+ }
291
+ }
292
+ /* v8 ignore stop */
293
+ /**
294
+ * Kill all ouro processes from the previous daemon instance using the pidfile.
295
+ * On startup, reads PIDs from ~/.ouro-cli/daemon.pids, kills them all, then
296
+ * deletes the file. The new daemon writes its own PIDs after spawning.
297
+ *
298
+ * Safety: pidfile contents are verified before being killed — each PID must
299
+ * be an actual orphan (PPID reparented to init/PID 1) via
300
+ * `filterPidfilePidsToActualOrphans`. Otherwise a polluted pidfile (written
301
+ * by a test, or a crashed daemon whose PIDs have since been reused by the
302
+ * OS) could SIGTERM unrelated processes.
303
+ *
304
+ * Falls back to ps-based scanning scoped to true orphans (PPID=1) if the
305
+ * pidfile doesn't exist (first run, previous daemon crashed before writing,
306
+ * manual cleanup). The scope is narrow on purpose — see parseOrphanPidsFromPs.
307
+ */
308
+ /* v8 ignore start -- process lifecycle: uses kill/ps, tested via deployment @preserve */
309
+ function isProductionDaemonSocketPath(socketPath) {
310
+ return socketPath === socket_client_1.DEFAULT_DAEMON_SOCKET_PATH;
311
+ }
312
+ function killOrphanProcesses(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
313
+ if (!isProductionDaemonSocketPath(socketPath)) {
314
+ (0, runtime_1.emitNervesEvent)({
315
+ level: "warn",
316
+ component: "daemon",
317
+ event: "daemon.orphan_cleanup_nonproduction_blocked",
318
+ message: "blocked orphan cleanup for non-production daemon socket",
319
+ meta: { socketPath, pidfilePath: PIDFILE_PATH },
320
+ });
321
+ return [];
322
+ }
323
+ if (isVitestProcess()) {
324
+ (0, runtime_1.emitNervesEvent)({
325
+ level: "warn",
326
+ component: "daemon",
327
+ event: "daemon.orphan_cleanup_test_blocked",
328
+ message: "blocked killOrphanProcesses from touching real pidfile under vitest",
329
+ meta: { pidfilePath: PIDFILE_PATH },
330
+ });
331
+ return [];
332
+ }
333
+ try {
334
+ let pidfileOrphans = [];
335
+ let scanOrphans = [];
336
+ // Primary: read pidfile from previous daemon
337
+ try {
338
+ const raw = fs.readFileSync(PIDFILE_PATH, "utf-8");
339
+ const candidates = raw.split("\n")
340
+ .map((s) => parseInt(s.trim(), 10))
341
+ .filter((n) => !isNaN(n) && n !== process.pid);
342
+ // Verify each candidate is an actual live orphan before killing. See
343
+ // docstring above for why this matters.
344
+ pidfileOrphans = filterPidfilePidsToActualOrphans(candidates);
345
+ fs.unlinkSync(PIDFILE_PATH);
346
+ }
347
+ catch {
348
+ // No pidfile — the ps scan below still covers true orphans.
349
+ }
350
+ // Always supplement the pidfile with the scoped ps scan. A stale or
351
+ // partial pidfile can otherwise kill one old daemon while leaving a
352
+ // sibling PPID=1 daemon alive without a socket.
353
+ try {
354
+ const result = (0, child_process_1.execSync)("ps -eo pid,ppid,command", { encoding: "utf-8", timeout: 5000 });
355
+ scanOrphans = parseOrphanPidsFromPs(result, process.pid);
356
+ }
357
+ catch (error) {
358
+ const detail = error instanceof Error ? error.message : String(error);
359
+ throw new Error(`could not discover orphaned Ouro processes: ${detail}`);
360
+ }
361
+ const pidsToKill = mergeUniqueOrphanPids(pidfileOrphans, scanOrphans);
362
+ if (pidsToKill.length > 0) {
363
+ for (const pid of pidsToKill) {
364
+ try {
365
+ process.kill(pid, "SIGTERM");
366
+ }
367
+ catch { /* already exited */ }
368
+ }
369
+ (0, runtime_1.emitNervesEvent)({
370
+ component: "daemon",
371
+ event: "daemon.orphan_cleanup",
372
+ message: `killed ${pidsToKill.length} orphaned ouro processes`,
373
+ meta: { pids: pidsToKill },
374
+ });
375
+ }
376
+ return pidsToKill;
377
+ }
378
+ catch (error) {
379
+ (0, runtime_1.emitNervesEvent)({
380
+ level: "error",
381
+ component: "daemon",
382
+ event: "daemon.orphan_cleanup_error",
383
+ message: "failed to clean up orphaned ouro processes",
384
+ meta: { error: error instanceof Error ? error.message : String(error) },
385
+ });
386
+ throw error instanceof Error ? error : new Error(String(error));
387
+ }
388
+ }
389
+ /**
390
+ * Write all managed PIDs (daemon + children) to the pidfile.
391
+ * Called after all agents and senses are spawned.
392
+ */
393
+ function writePidfile(extraPids = [], socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
394
+ if (!isProductionDaemonSocketPath(socketPath)) {
395
+ (0, runtime_1.emitNervesEvent)({
396
+ level: "warn",
397
+ component: "daemon",
398
+ event: "daemon.write_pidfile_nonproduction_blocked",
399
+ message: "blocked production pidfile write for non-production daemon socket",
400
+ meta: { socketPath, pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
401
+ });
402
+ return;
403
+ }
404
+ if (isVitestProcess()) {
405
+ (0, runtime_1.emitNervesEvent)({
406
+ level: "warn",
407
+ component: "daemon",
408
+ event: "daemon.write_pidfile_test_blocked",
409
+ message: "blocked writePidfile from clobbering real pidfile under vitest",
410
+ meta: { pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
411
+ });
412
+ return;
413
+ }
414
+ try {
415
+ const pids = [process.pid, ...extraPids].filter(Boolean);
416
+ fs.mkdirSync(path.dirname(PIDFILE_PATH), { recursive: true });
417
+ fs.writeFileSync(PIDFILE_PATH, pids.join("\n") + "\n", "utf-8");
418
+ }
419
+ catch { /* best effort */ }
420
+ }
421
+ function readSocketIdentity(socketPath) {
422
+ try {
423
+ const stats = fs.lstatSync(socketPath);
424
+ return {
425
+ dev: stats.dev,
426
+ ino: stats.ino,
427
+ ctimeMs: stats.ctimeMs,
428
+ };
429
+ }
430
+ catch {
431
+ return null;
432
+ }
433
+ }
434
+ function sameSocketIdentity(left, right) {
435
+ if (!left || !right)
436
+ return false;
437
+ return left.dev === right.dev && left.ino === right.ino && left.ctimeMs === right.ctimeMs;
438
+ }
53
439
  function buildWorkerRows(snapshots) {
54
440
  return snapshots.map((snapshot) => ({
55
441
  agent: snapshot.name,
56
442
  worker: snapshot.channel,
443
+ autoStart: snapshot.autoStart ?? true,
57
444
  status: snapshot.status,
58
445
  pid: snapshot.pid,
59
446
  restartCount: snapshot.restartCount,
60
447
  startedAt: snapshot.startedAt,
448
+ lastExitCode: snapshot.lastExitCode ?? null,
449
+ lastSignal: snapshot.lastSignal ?? null,
450
+ errorReason: snapshot.errorReason ?? null,
451
+ fixHint: snapshot.fixHint ?? null,
61
452
  }));
62
453
  }
454
+ function unhealthySenseRows(senses) {
455
+ return senses.filter((row) => {
456
+ if (!row.enabled)
457
+ return false;
458
+ if (row.status === "disabled" || row.status === "not_attached")
459
+ return false;
460
+ if (row.status === "interactive" || row.status === "running")
461
+ return false;
462
+ return true;
463
+ });
464
+ }
465
+ function isParkedWorker(row) {
466
+ return row.autoStart === false && row.status === "stopped";
467
+ }
468
+ function unhealthyWorkerRows(workers) {
469
+ return workers.filter((row) => !isParkedWorker(row) && row.status !== "running");
470
+ }
471
+ function unhealthyHealthChecks(healthChecks) {
472
+ return healthChecks.filter((row) => row.status !== "ok");
473
+ }
474
+ function overviewHealth(workers, senses, healthChecks = []) {
475
+ if (unhealthyWorkerRows(workers).length > 0)
476
+ return "warn";
477
+ if (unhealthySenseRows(senses).length > 0)
478
+ return "warn";
479
+ if (unhealthyHealthChecks(healthChecks).length > 0)
480
+ return "warn";
481
+ return "ok";
482
+ }
63
483
  function formatStatusSummary(payload) {
64
- if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0) {
484
+ if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0 && (payload.healthChecks ?? []).length === 0) {
65
485
  return "no managed agents";
66
486
  }
67
- const rows = [
68
- ...payload.workers.map((row) => `${row.agent}/${row.worker}:${row.status}`),
69
- ...payload.senses
70
- .filter((row) => row.enabled)
71
- .map((row) => `${row.agent}/${row.sense}:${row.status}`),
487
+ const degraded = [
488
+ ...unhealthyWorkerRows(payload.workers)
489
+ .map((row) => `worker:${row.agent}/${row.worker}:${row.status}`),
490
+ ...unhealthySenseRows(payload.senses)
491
+ .map((row) => `sense:${row.agent}/${row.sense}:${row.status}`),
492
+ ...(payload.healthChecks ?? [])
493
+ .filter((row) => row.status !== "ok")
494
+ .map((row) => `health-check:${row.name}:${row.status}`),
72
495
  ];
73
- const detail = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
496
+ const detail = degraded.length > 0 ? `\tdegraded=${degraded.join(",")}` : "";
497
+ if (!detail) {
498
+ const rows = [
499
+ ...payload.workers.map((row) => `${row.agent}/${row.worker}:${row.status}`),
500
+ ...payload.senses
501
+ .filter((row) => row.enabled)
502
+ .map((row) => `${row.agent}/${row.sense}:${row.status}`),
503
+ ];
504
+ const items = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
505
+ return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${items}`;
506
+ }
74
507
  return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${detail}`;
75
508
  }
76
509
  function parseIncomingCommand(raw) {
@@ -90,6 +523,101 @@ function parseIncomingCommand(raw) {
90
523
  }
91
524
  return parsed;
92
525
  }
526
+ function isValidSenseReviveCommand(command) {
527
+ return typeof command.agent === "string"
528
+ && typeof command.sense === "string"
529
+ && typeof command.reason === "string";
530
+ }
531
+ function isValidTaskPokeCommand(command) {
532
+ return typeof command.agent === "string"
533
+ && command.agent.trim().length > 0
534
+ && typeof command.taskId === "string"
535
+ && command.taskId.trim().length > 0;
536
+ }
537
+ function isValidHabitPokeCommand(command) {
538
+ return typeof command.agent === "string"
539
+ && command.agent.trim().length > 0
540
+ && typeof command.habitName === "string"
541
+ && command.habitName.trim().length > 0;
542
+ }
543
+ function isValidHabitProbeCommand(command) {
544
+ return typeof command.agent === "string"
545
+ && command.agent.trim().length > 0
546
+ && typeof command.habitName === "string"
547
+ && command.habitName.trim().length > 0
548
+ && (command.noSend === undefined || command.noSend === true);
549
+ }
550
+ function taskIdFromTaskPokePrivateWakeCommand(command) {
551
+ if (command.kind !== "private.wake" || command.triggerSource !== "task-poke")
552
+ return null;
553
+ const taskRef = command.originRefs?.find((ref) => ref.kind === "task" && typeof ref.id === "string");
554
+ if (!taskRef || typeof taskRef.id !== "string")
555
+ return null;
556
+ const trimmed = taskRef.id.trim();
557
+ return trimmed.length > 0 ? trimmed : null;
558
+ }
559
+ /**
560
+ * Handle agent.senseTurn command: runs a full agent turn via the daemon process.
561
+ * Dynamic import lazy-loads shared-turn. Hot-reload works because ouro dev
562
+ * restarts the daemon process (fresh module cache).
563
+ */
564
+ async function handleAgentSenseTurn(command, runtime) {
565
+ return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
566
+ try {
567
+ const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
568
+ setAgentName(command.agent);
569
+ const { runSenseTurn } = await Promise.resolve().then(() => __importStar(require("../../senses/shared-turn")));
570
+ const result = await runSenseTurn({
571
+ agentName: command.agent,
572
+ channel: command.channel,
573
+ sessionKey: command.sessionKey,
574
+ friendId: command.friendId,
575
+ userMessage: command.message,
576
+ ...(runtime?.socketPath ? { toolContext: { daemonSocketPath: runtime.socketPath } } : {}),
577
+ // Per-turn, per-agent runtime MCP injection (e.g. Workbench's ouro_workbench).
578
+ // Scoped to THIS turn only — never stored as module state, so a concurrent
579
+ // turn for a different agent cannot inherit these servers.
580
+ ...(command.runtimeMcp ? { runtimeMcpServers: command.runtimeMcp } : {}),
581
+ });
582
+ return {
583
+ ok: true,
584
+ message: result.response,
585
+ data: { ponderDeferred: result.ponderDeferred },
586
+ };
587
+ }
588
+ catch (error) {
589
+ /* v8 ignore next -- branch: String(error) fallback only for non-Error throws @preserve */
590
+ const errorMessage = error instanceof Error ? error.message : String(error);
591
+ return { ok: false, error: `sense turn failed: ${errorMessage}` };
592
+ }
593
+ });
594
+ }
595
+ async function handleAgentAskTurn(command, runtime) {
596
+ /* v8 ignore start -- ask command parameter defaults are legacy MCP compatibility; send_message shares the primary path @preserve */
597
+ const question = typeof command.question === "string" ? command.question : "";
598
+ if (!question.trim())
599
+ return { ok: false, error: "Missing required parameter: question" };
600
+ const channel = typeof command.channel === "string" && command.channel.trim() ? command.channel.trim() : "mcp";
601
+ const sessionKey = typeof command.sessionKey === "string" && command.sessionKey.trim()
602
+ ? command.sessionKey.trim()
603
+ : `agent-ask:${command.friendId}`;
604
+ /* v8 ignore stop */
605
+ return handleAgentSenseTurn({
606
+ kind: "agent.senseTurn",
607
+ agent: command.agent,
608
+ friendId: command.friendId,
609
+ channel,
610
+ sessionKey,
611
+ message: question,
612
+ }, runtime);
613
+ }
614
+ /* v8 ignore start -- platform default: tests inject the launcher, and the launcher itself is production wiring @preserve */
615
+ function defaultSelfUpdateLauncher() {
616
+ if (process.platform === "darwin")
617
+ return null;
618
+ return async () => (await Promise.resolve().then(() => __importStar(require("../versioning/self-update-defaults")))).launchUnattendedSelfUpdate();
619
+ }
620
+ /* v8 ignore stop */
93
621
  class OuroDaemon {
94
622
  socketPath;
95
623
  processManager;
@@ -98,7 +626,36 @@ class OuroDaemon {
98
626
  router;
99
627
  senseManager;
100
628
  bundlesRoot;
629
+ mode;
101
630
  server = null;
631
+ mailboxServer = null;
632
+ frontendSocketServer = null;
633
+ socketIdentity = null;
634
+ senseAutostartTimer = null;
635
+ externalEventReconcileTimer = null;
636
+ externalEventReconcileRunning = false;
637
+ constructedAtMs = Date.now();
638
+ mailboxServerFactory;
639
+ frontendSocketPath;
640
+ frontendSessionService;
641
+ frontendSocketServerFactory;
642
+ privateRuntimePolicyDeps;
643
+ onStopCommandComplete;
644
+ externalEventRoot;
645
+ privilegedEventSpoolRoot;
646
+ privilegedEventScanner;
647
+ externalEventScanCache = new router_1.ExternalEventScanCache();
648
+ rsvpHabitRunner;
649
+ nativeHabitRunner;
650
+ nativeHabitMatch;
651
+ nativeHabitClaims = new Set();
652
+ authenticatedSchedulerPokes = new WeakMap();
653
+ schedulerFireVerifier;
654
+ schedulerFireConsumer;
655
+ orphanStartupDrain;
656
+ socketAnswering;
657
+ externalEventSourceReadiness;
658
+ selfUpdateLauncher;
102
659
  constructor(options) {
103
660
  this.socketPath = options.socketPath;
104
661
  this.processManager = options.processManager;
@@ -107,6 +664,128 @@ class OuroDaemon {
107
664
  this.router = options.router;
108
665
  this.senseManager = options.senseManager ?? null;
109
666
  this.bundlesRoot = options.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
667
+ this.mode = options.mode ?? "production";
668
+ this.mailboxServerFactory = options.mailboxServerFactory ?? this.createDefaultMailboxServer.bind(this);
669
+ this.frontendSocketPath = options.frontendSocketPath ?? (0, frontend_socket_1.frontendSocketPathForDaemon)(this.socketPath);
670
+ /* v8 ignore next -- path-only default adapter; frontend service tests inject and verify the same root contract @preserve */
671
+ const frontendAgentRoot = (agent) => path.join(this.bundlesRoot, `${agent}.ouro`);
672
+ this.frontendSessionService = options.frontendSessionService ?? new frontend_session_service_1.FrontendSessionService({
673
+ journal: new frontend_journal_1.FrontendJournalStore({ agentRoot: frontendAgentRoot }),
674
+ authority: (0, frontend_approval_runtime_1.createFrontendApprovalRuntime)({
675
+ agentRoot: frontendAgentRoot,
676
+ settleApproval: frontend_approval_runtime_1.settleFrontendApproval,
677
+ }),
678
+ });
679
+ this.frontendSocketServerFactory = options.frontendSocketServerFactory ?? frontend_socket_1.startFrontendSocketServer;
680
+ this.privateRuntimePolicyDeps = options.privateRuntimePolicyDeps ?? {};
681
+ this.onStopCommandComplete = options.onStopCommandComplete ?? null;
682
+ this.externalEventRoot = options.externalEventRoot ?? null;
683
+ this.privilegedEventSpoolRoot = options.privilegedEventSpoolRoot ?? "/run/ouro-events";
684
+ this.privilegedEventScanner = options.privilegedEventScanner ?? router_1.scanPrivilegedEventSpool;
685
+ this.rsvpHabitRunner = options.rsvpHabitRunner;
686
+ this.nativeHabitRunner = options.nativeHabitRunner;
687
+ this.nativeHabitMatch = options.nativeHabitMatch;
688
+ this.schedulerFireVerifier = options.schedulerFireVerifier;
689
+ this.schedulerFireConsumer = options.schedulerFireConsumer;
690
+ this.orphanStartupDrain = options.orphanStartupDrain ?? drainOrphanProcessesBeforeStartup;
691
+ this.socketAnswering = options.socketAnswering ?? socket_client_1.checkDaemonSocketAlive;
692
+ this.selfUpdateLauncher = options.selfUpdateLauncher !== undefined ? options.selfUpdateLauncher : defaultSelfUpdateLauncher();
693
+ this.externalEventSourceReadiness = options.externalEventSourceReadiness ?? (async (agent, source) => {
694
+ const { ensureSanctuarySourceRuntimeReady } = await Promise.resolve().then(() => __importStar(require("../../senses/sanctuary-runtime")));
695
+ await ensureSanctuarySourceRuntimeReady(agent, source);
696
+ });
697
+ }
698
+ /* v8 ignore start -- default mailbox server wiring: production-only path, tests inject mailboxServerFactory stub instead. startMailboxHttpServer itself has full coverage in mailbox-http.test.ts @preserve */
699
+ createDefaultMailboxServer() {
700
+ return (0, mailbox_http_1.startMailboxHttpServer)({
701
+ host: "127.0.0.1",
702
+ port: mailbox_types_1.MAILBOX_DEFAULT_PORT,
703
+ bundlesRoot: this.bundlesRoot,
704
+ readMachineState: () => (0, mailbox_read_1.readMailboxMachineState)({ bundlesRoot: this.bundlesRoot }),
705
+ readMachineView: ({ machine }) => {
706
+ const overview = this.buildStatusPayload().overview;
707
+ return (0, mailbox_view_1.buildMailboxMachineView)({
708
+ machine,
709
+ daemon: {
710
+ status: overview.daemon,
711
+ health: overview.health,
712
+ mode: overview.mode,
713
+ socketPath: overview.socketPath,
714
+ mailboxUrl: overview.mailboxUrl,
715
+ entryPath: overview.entryPath,
716
+ workerCount: overview.workerCount,
717
+ senseCount: overview.senseCount,
718
+ },
719
+ });
720
+ },
721
+ readAgentState: (agentName) => (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot }),
722
+ readAgentView: (agentName) => {
723
+ const agent = (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot });
724
+ return (0, mailbox_view_1.buildMailboxAgentView)({
725
+ agent,
726
+ viewer: { kind: "human" },
727
+ });
728
+ },
729
+ });
730
+ }
731
+ /* v8 ignore stop */
732
+ buildStatusPayload() {
733
+ const snapshots = this.processManager.listAgentSnapshots();
734
+ const workers = buildWorkerRows(snapshots);
735
+ const senses = this.senseManager?.listSenseRows() ?? [];
736
+ const healthChecks = this.overlaySchedulerHealth(this.healthMonitor.getLastResults?.() ?? []);
737
+ const repoRoot = (0, identity_1.getRepoRoot)();
738
+ const sync = (0, agent_discovery_1.listBundleSyncRows)({ bundlesRoot: this.bundlesRoot });
739
+ const agents = (0, agent_discovery_1.listAllBundleAgents)({ bundlesRoot: this.bundlesRoot });
740
+ const providerAgents = (0, agent_discovery_1.listEnabledBundleAgents)({ bundlesRoot: this.bundlesRoot });
741
+ const providers = providerAgents.flatMap((agentName) => (0, provider_visibility_1.providerVisibilityStatusRows)((0, provider_visibility_1.buildAgentProviderVisibility)({
742
+ agentName,
743
+ agentRoot: path.join(this.bundlesRoot, `${agentName}.ouro`),
744
+ })));
745
+ const externalEvents = (0, router_1.listExternalEventStatus)(this.externalEventRoot ?? (0, router_1.getExternalEventRoot)());
746
+ const mailboxUrl = this.mailboxServer?.origin ?? "http://127.0.0.1:0";
747
+ return {
748
+ overview: {
749
+ daemon: "running",
750
+ health: overviewHealth(workers, senses, healthChecks),
751
+ socketPath: this.socketPath,
752
+ mailboxUrl,
753
+ outlookUrl: mailboxUrl,
754
+ ...(0, runtime_metadata_1.getRuntimeMetadata)(),
755
+ workerCount: workers.length,
756
+ senseCount: senses.length,
757
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
758
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
759
+ },
760
+ workers,
761
+ senses,
762
+ ...(healthChecks.length > 0 ? { healthChecks } : {}),
763
+ sync,
764
+ agents,
765
+ ...(providers.length > 0 ? { providers } : {}),
766
+ ...(externalEvents.length > 0 ? { externalEvents } : {}),
767
+ };
768
+ }
769
+ overlaySchedulerHealth(healthChecks) {
770
+ const degradedJobs = this.scheduler.listDegradedJobs?.() ?? [];
771
+ if (degradedJobs.length === 0)
772
+ return healthChecks;
773
+ const cronHealth = {
774
+ name: "cron-health",
775
+ status: "warn",
776
+ message: `cron jobs degraded; timer fallback active: ${degradedJobs
777
+ .map((job) => `${job.id} (${job.reason})`)
778
+ .join(", ")}`,
779
+ };
780
+ const next = healthChecks.map((check) => ({ ...check }));
781
+ const existingIndex = next.findIndex((check) => check.name === "cron-health");
782
+ if (existingIndex === -1) {
783
+ next.push(cronHealth);
784
+ }
785
+ else {
786
+ next[existingIndex] = cronHealth;
787
+ }
788
+ return next;
110
789
  }
111
790
  async start() {
112
791
  if (this.server)
@@ -117,65 +796,236 @@ class OuroDaemon {
117
796
  message: "starting daemon server",
118
797
  meta: { socketPath: this.socketPath },
119
798
  });
799
+ try {
800
+ await this.startInner();
801
+ }
802
+ catch (err) {
803
+ // Emit a paired terminating event (`_error`) so the nerves audit's
804
+ // start_end_pairing rule is satisfied when startup throws mid-sequence
805
+ // and `stop()` (which emits `server_end`) is never called.
806
+ (0, runtime_1.emitNervesEvent)({
807
+ level: "error",
808
+ component: "daemon",
809
+ event: "daemon.server_error",
810
+ message: "daemon start failed",
811
+ meta: {
812
+ error: err instanceof Error ? err.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(err),
813
+ },
814
+ });
815
+ throw err;
816
+ }
817
+ }
818
+ async startInner() {
819
+ // A replacement always stops the old daemon first (ouro up, launchd bootout,
820
+ // staged restart). A daemon that still answers is live, not orphaned: never
821
+ // kill its processes or unlink its socket, whatever HOME this one runs under.
822
+ if (await this.socketAnswering(this.socketPath)) {
823
+ (0, runtime_1.emitNervesEvent)({
824
+ level: "error",
825
+ component: "daemon",
826
+ event: "daemon.socket_already_served",
827
+ message: "another daemon already answers on this socket; refusing to start",
828
+ meta: { socketPath: this.socketPath },
829
+ });
830
+ throw new Error(`another daemon already answers on ${this.socketPath}; stop it with ouro stop, or start this one with its own --socket`);
831
+ }
832
+ const containerPolicy = (0, container_runtime_1.readContainerRuntimePolicy)();
120
833
  // Register update hooks and apply pending updates before starting agents
121
834
  (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
835
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
122
836
  const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
123
- await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
837
+ if (containerPolicy?.updates !== "disabled")
838
+ await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
124
839
  // Start periodic update checker (polls npm registry every 30 minutes)
125
- const bundlesRoot = this.bundlesRoot;
126
- const daemon = this;
127
- (0, update_checker_1.startUpdateChecker)({
128
- currentVersion,
129
- deps: {
130
- distTag: "alpha",
131
- fetchRegistryJson: /* v8 ignore next -- integration: real HTTP fetch @preserve */ async () => {
132
- const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
133
- return res.json();
134
- },
135
- },
136
- onUpdate: /* v8 ignore start -- integration: real npm install + process spawn @preserve */ async (result) => {
137
- if (!result.latestVersion)
138
- return;
139
- await (0, staged_restart_1.performStagedRestart)(result.latestVersion, {
140
- execSync: (cmd) => (0, child_process_1.execSync)(cmd, { stdio: "inherit" }),
141
- spawnSync: child_process_1.spawnSync,
142
- resolveNewCodePath: (_version) => {
143
- try {
144
- const resolved = (0, child_process_1.execSync)(`node -e "console.log(require.resolve('@ouro.bot/cli/package.json'))"`, { encoding: "utf-8" }).trim();
145
- return resolved ? path.dirname(resolved) : null;
146
- }
147
- catch {
148
- return null;
149
- }
840
+ // Skip in dev mode — dev builds should not auto-update from npm
841
+ if (this.mode === "dev" || containerPolicy?.updates === "disabled") {
842
+ (0, runtime_1.emitNervesEvent)({
843
+ component: "daemon",
844
+ event: "daemon.update_checker_skip",
845
+ message: "skipping update checker in dev mode",
846
+ meta: { reason: this.mode === "dev" ? "dev mode" : "container policy" },
847
+ });
848
+ }
849
+ else {
850
+ const launchSelfUpdate = this.selfUpdateLauncher;
851
+ (0, update_checker_1.startUpdateChecker)({
852
+ currentVersion,
853
+ ...(launchSelfUpdate ? {
854
+ onUpdate: async (update) => {
855
+ const outcome = await launchSelfUpdate();
856
+ (0, runtime_1.emitNervesEvent)({
857
+ component: "daemon",
858
+ event: "daemon.self_update_launched",
859
+ message: "update checker saw a newer release and asked the unattended updater to run",
860
+ meta: { currentVersion, latestVersion: update.latestVersion ?? null, outcome },
861
+ });
150
862
  },
151
- gracefulShutdown: () => daemon.stop(),
152
- nodePath: process.execPath,
153
- bundlesRoot,
154
- });
155
- },
156
- /* v8 ignore stop */
863
+ } : {}),
864
+ deps: {
865
+ distTag: update_checker_1.CLI_UPDATE_DIST_TAG,
866
+ /* v8 ignore start -- integration: real HTTP fetch @preserve */
867
+ fetchRegistryJson: async () => {
868
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
869
+ return res.json();
870
+ },
871
+ /* v8 ignore stop */
872
+ },
873
+ });
874
+ }
875
+ // MCP connections are lazily initialized per-agent during senseTurn
876
+ // (daemon manages multiple agents; agent identity must be set before loading MCP config)
877
+ await this.orphanStartupDrain(this.socketPath);
878
+ await this.openCommandSocket();
879
+ this.triggerAutoStartAgents();
880
+ this.triggerAutoStartSensesWhenAgentsSettled();
881
+ // Not awaited: a startup external event can run a long private turn, and
882
+ // that turn must never hold senses such as Telegram down at boot.
883
+ void this.reconcileExternalEvents().catch((error) => {
884
+ (0, runtime_1.emitNervesEvent)({
885
+ level: "warn",
886
+ component: "daemon",
887
+ event: "daemon.external_event_startup_reconcile_error",
888
+ message: "startup external-event reconciliation failed",
889
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- reconciliation failures are Error objects @preserve */ String(error) },
890
+ });
157
891
  });
158
- // Pre-initialize MCP connections so they're ready for the first command (non-blocking)
159
- /* v8 ignore next -- catch callback: getSharedMcpManager logs errors internally @preserve */
160
- (0, mcp_manager_1.getSharedMcpManager)().catch(() => { });
161
- await this.processManager.startAutoStartAgents();
162
- await this.senseManager?.startAutoStartSenses();
892
+ this.externalEventReconcileTimer = setInterval(() => {
893
+ void this.reconcileExternalEvents();
894
+ }, 1_000);
895
+ this.externalEventReconcileTimer.unref?.();
896
+ // Write all managed PIDs to disk so the next daemon can clean up
897
+ /* v8 ignore start -- pidfile write: collects PIDs from process managers @preserve */
898
+ const agentPids = this.processManager.listAgentSnapshots().map((s) => s.pid).filter((p) => p !== null);
899
+ const sensePids = this.senseManager?.listManagedPids?.() ?? [];
900
+ writePidfile([...agentPids, ...sensePids], this.socketPath);
901
+ /* v8 ignore stop */
163
902
  this.scheduler.start?.();
164
903
  await this.scheduler.reconcile?.();
165
904
  await this.drainPendingBundleMessages();
166
905
  await this.drainPendingSenseMessages();
906
+ // startInner is only reachable when this.server is null (guarded in
907
+ // start()), and stop() nulls out this.mailboxServer alongside this.server,
908
+ // so mailboxServer is guaranteed unset here — no need for a guard.
909
+ try {
910
+ this.mailboxServer = await this.mailboxServerFactory();
911
+ }
912
+ catch (error) {
913
+ (0, runtime_1.emitNervesEvent)({
914
+ level: "warn",
915
+ component: "daemon",
916
+ event: "daemon.mailbox_start_failed",
917
+ message: `Mailbox server failed to start: ${String(error)}`,
918
+ meta: { port: mailbox_types_1.MAILBOX_DEFAULT_PORT },
919
+ });
920
+ }
921
+ try {
922
+ this.frontendSocketServer = await this.frontendSocketServerFactory({
923
+ socketPath: this.frontendSocketPath,
924
+ service: this.frontendSessionService,
925
+ });
926
+ }
927
+ catch (error) {
928
+ (0, runtime_1.emitNervesEvent)({
929
+ level: "warn",
930
+ component: "daemon",
931
+ event: "daemon.frontend_socket_start_failed",
932
+ message: `Frontend socket failed to start: ${String(error)}`,
933
+ meta: { socketPath: this.frontendSocketPath },
934
+ });
935
+ }
936
+ }
937
+ triggerAutoStartAgents() {
938
+ if (this.processManager.triggerAutoStartAgents) {
939
+ this.processManager.triggerAutoStartAgents();
940
+ return;
941
+ }
942
+ void this.processManager.startAutoStartAgents().catch((error) => {
943
+ (0, runtime_1.emitNervesEvent)({
944
+ level: "error",
945
+ component: "daemon",
946
+ event: "daemon.agent_autostart_error",
947
+ message: "agent autostart failed after daemon socket opened",
948
+ meta: { error: error instanceof Error ? error.message : String(error) },
949
+ });
950
+ });
951
+ }
952
+ triggerAutoStartSenses() {
953
+ /* v8 ignore next -- defensive: callers already check senseManager before delegating here @preserve */
954
+ if (!this.senseManager)
955
+ return;
956
+ if (this.senseManager.triggerAutoStartSenses) {
957
+ this.senseManager.triggerAutoStartSenses();
958
+ return;
959
+ }
960
+ void this.senseManager.startAutoStartSenses().catch((error) => {
961
+ (0, runtime_1.emitNervesEvent)({
962
+ level: "error",
963
+ component: "daemon",
964
+ event: "daemon.sense_autostart_error",
965
+ message: "sense autostart failed after daemon socket opened",
966
+ meta: { error: error instanceof Error ? error.message : String(error) },
967
+ });
968
+ });
969
+ }
970
+ triggerAutoStartSensesWhenAgentsSettled() {
971
+ if (!this.senseManager)
972
+ return;
973
+ const waitingOnAgents = this.processManager.listAgentSnapshots()
974
+ .some((snapshot) => snapshot.status === "starting");
975
+ if (!waitingOnAgents) {
976
+ this.triggerAutoStartSenses();
977
+ return;
978
+ }
979
+ this.senseAutostartTimer = setTimeout(() => {
980
+ this.senseAutostartTimer = null;
981
+ this.triggerAutoStartSensesWhenAgentsSettled();
982
+ }, 250);
983
+ }
984
+ async openCommandSocket() {
167
985
  if (fs.existsSync(this.socketPath)) {
168
986
  fs.unlinkSync(this.socketPath);
169
987
  }
170
- this.server = net.createServer((connection) => {
988
+ // allowHalfOpen: true lets the server keep its writable side open after
989
+ // the client sends FIN. Without this, when a client calls `client.end()`
990
+ // after writing a command, node closes the server's writable side
991
+ // automatically — so a long-running response (like an agent.senseTurn
992
+ // LLM turn that takes 5+ seconds) never reaches the client. The
993
+ // socket-client fix in #303/#334 also removed client.end() on the
994
+ // sending side, but this option is defense in depth: even if a future
995
+ // caller half-closes, the server still writes its response correctly.
996
+ this.server = net.createServer({ allowHalfOpen: true }, (connection) => {
171
997
  let raw = "";
172
998
  let responded = false;
999
+ /* v8 ignore start — connection error handler requires real socket error @preserve */
1000
+ connection.on("error", (err) => {
1001
+ (0, runtime_1.emitNervesEvent)({
1002
+ level: "warn",
1003
+ component: "daemon",
1004
+ event: "daemon.connection_error",
1005
+ message: "socket connection error",
1006
+ meta: { error: err.message, code: err.code ?? null },
1007
+ });
1008
+ });
1009
+ /* v8 ignore stop */
173
1010
  const flushResponse = async () => {
174
1011
  if (responded)
175
1012
  return;
176
1013
  responded = true;
177
1014
  const response = await this.handleRawPayload(raw);
178
- connection.end(response);
1015
+ try {
1016
+ connection.end(response);
1017
+ /* v8 ignore start — EPIPE catch requires real socket disconnect @preserve */
1018
+ }
1019
+ catch (err) {
1020
+ (0, runtime_1.emitNervesEvent)({
1021
+ level: "warn",
1022
+ component: "daemon",
1023
+ event: "daemon.connection_end_error",
1024
+ message: "failed to send response to client (EPIPE)",
1025
+ meta: { error: err instanceof Error ? err.message : String(err) },
1026
+ });
1027
+ }
1028
+ /* v8 ignore stop */
179
1029
  };
180
1030
  connection.on("data", (chunk) => {
181
1031
  raw += chunk.toString("utf-8");
@@ -188,7 +1038,23 @@ class OuroDaemon {
188
1038
  const server = this.server;
189
1039
  await new Promise((resolve, reject) => {
190
1040
  server.once("error", reject);
191
- server.listen(this.socketPath, () => resolve());
1041
+ server.listen(this.socketPath, () => {
1042
+ // Replace the one-time error listener with a persistent one after successful listen
1043
+ server.removeAllListeners("error");
1044
+ this.socketIdentity = readSocketIdentity(this.socketPath);
1045
+ /* v8 ignore start — server error after listen requires real socket race condition @preserve */
1046
+ server.on("error", (err) => {
1047
+ (0, runtime_1.emitNervesEvent)({
1048
+ level: "error",
1049
+ component: "daemon",
1050
+ event: "daemon.server_error",
1051
+ message: "daemon server error after listen",
1052
+ meta: { error: err.message, code: err.code ?? null },
1053
+ });
1054
+ });
1055
+ /* v8 ignore stop */
1056
+ resolve();
1057
+ });
192
1058
  });
193
1059
  }
194
1060
  async drainPendingBundleMessages() {
@@ -240,7 +1106,7 @@ class OuroDaemon {
240
1106
  }
241
1107
  }
242
1108
  /** Drains per-sense pending dirs for always-on senses across all agents. */
243
- static ALWAYS_ON_SENSES = new Set((0, channel_1.getAlwaysOnSenseNames)());
1109
+ static ALWAYS_ON_SENSES = new Set((0, friends_1.getAlwaysOnSenseNames)());
244
1110
  async drainPendingSenseMessages() {
245
1111
  if (!fs.existsSync(this.bundlesRoot))
246
1112
  return;
@@ -327,26 +1193,116 @@ class OuroDaemon {
327
1193
  }
328
1194
  }
329
1195
  async stop() {
1196
+ // Must be named `_end` (not `_stop`) to satisfy the nerves audit's
1197
+ // start/end pairing rule — see src/nerves/coverage/audit-rules.ts.
1198
+ // This is the counterpart to `daemon.server_start` emitted at line 480.
330
1199
  (0, runtime_1.emitNervesEvent)({
331
1200
  component: "daemon",
332
- event: "daemon.server_stop",
1201
+ event: "daemon.server_end",
333
1202
  message: "stopping daemon server",
334
1203
  meta: { socketPath: this.socketPath },
335
1204
  });
1205
+ this.frontendSessionService.cancelAllTurns();
1206
+ if (this.frontendSocketServer) {
1207
+ await this.frontendSocketServer.stop();
1208
+ this.frontendSocketServer = null;
1209
+ }
1210
+ this.frontendSessionService.close?.();
336
1211
  (0, update_checker_1.stopUpdateChecker)();
337
- (0, mcp_manager_1.shutdownSharedMcpManager)();
338
1212
  this.scheduler.stop?.();
339
- await this.processManager.stopAll();
340
- await this.senseManager?.stopAll();
1213
+ this.healthMonitor.stopPeriodicChecks?.();
1214
+ if (this.senseAutostartTimer) {
1215
+ clearTimeout(this.senseAutostartTimer);
1216
+ this.senseAutostartTimer = null;
1217
+ }
1218
+ if (this.externalEventReconcileTimer) {
1219
+ clearInterval(this.externalEventReconcileTimer);
1220
+ this.externalEventReconcileTimer = null;
1221
+ }
1222
+ const workerStopTasks = [
1223
+ Promise.resolve().then(() => this.processManager.stopAll()),
1224
+ Promise.resolve().then(() => (0, mcp_manager_1.shutdownSharedMcpManager)()),
1225
+ ];
1226
+ if (this.senseManager) {
1227
+ workerStopTasks.push(Promise.resolve().then(() => this.senseManager.stopAll()));
1228
+ }
1229
+ const workerStopResults = await Promise.allSettled(workerStopTasks);
1230
+ const workerStopFailures = workerStopResults.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
341
1231
  if (this.server) {
342
- await new Promise((resolve) => {
343
- this.server?.close(() => resolve());
344
- });
1232
+ // DO NOT `await` server.close() here. server.close() resolves only
1233
+ // after every open connection has closed. When stop() is invoked
1234
+ // from the daemon.stop command handler, the calling client's
1235
+ // connection is STILL open — its flushResponse() is currently
1236
+ // awaiting THIS function. Awaiting close() creates a deadlock:
1237
+ //
1238
+ // client → flushResponse → handleRawPayload → daemon.stop case
1239
+ // → stop() → await server.close() (waits for client's connection)
1240
+ // → client's connection waits for flushResponse to call
1241
+ // connection.end() → DEADLOCK
1242
+ //
1243
+ // Both processes sit in kevent forever. Verified live on
1244
+ // 2026-04-08: alpha.268 daemon hung at `daemon.server_end` log
1245
+ // line for 5+ minutes after a client sent daemon.stop, while the
1246
+ // client (alpha.270 ouro up) hung waiting for the response.
1247
+ //
1248
+ // This regressed when #303/#334/#339 stopped half-closing the
1249
+ // client socket and switched the server to allowHalfOpen: true.
1250
+ // Previously, the client called .end() after writing its command,
1251
+ // which (with allowHalfOpen: false) caused node to auto-tear-down
1252
+ // the server's writable side — incidentally unblocking
1253
+ // server.close() before the response was sent. The half-close
1254
+ // breakage masked this deadlock; the fix exposed it.
1255
+ //
1256
+ // Solution: fire close() and let it complete asynchronously. Once
1257
+ // stop() returns, the daemon.stop case returns its response,
1258
+ // flushResponse() calls connection.end(response), the connection
1259
+ // closes, and server.close()'s pending callback fires. The event
1260
+ // loop drains and the daemon exits cleanly.
1261
+ this.server.close();
345
1262
  this.server = null;
346
1263
  }
347
- if (fs.existsSync(this.socketPath)) {
1264
+ if (this.mailboxServer) {
1265
+ await this.mailboxServer.stop();
1266
+ this.mailboxServer = null;
1267
+ }
1268
+ const socketPathExists = fs.existsSync(this.socketPath);
1269
+ const currentSocketIdentity = socketPathExists ? readSocketIdentity(this.socketPath) : null;
1270
+ if (sameSocketIdentity(this.socketIdentity, currentSocketIdentity)) {
348
1271
  fs.unlinkSync(this.socketPath);
349
1272
  }
1273
+ else if (socketPathExists) {
1274
+ const expectedSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...this.socketIdentity };
1275
+ const actualSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...currentSocketIdentity };
1276
+ (0, runtime_1.emitNervesEvent)({
1277
+ level: "warn",
1278
+ component: "daemon",
1279
+ event: "daemon.socket_cleanup_skipped",
1280
+ message: "skipped daemon socket cleanup because the socket path no longer belongs to this daemon",
1281
+ meta: {
1282
+ socketPath: this.socketPath,
1283
+ expectedDev: expectedSocketIdentity.dev,
1284
+ expectedIno: expectedSocketIdentity.ino,
1285
+ expectedCtimeMs: expectedSocketIdentity.ctimeMs,
1286
+ actualDev: actualSocketIdentity.dev,
1287
+ actualIno: actualSocketIdentity.ino,
1288
+ actualCtimeMs: actualSocketIdentity.ctimeMs,
1289
+ },
1290
+ });
1291
+ }
1292
+ this.socketIdentity = null;
1293
+ if (workerStopFailures.length > 0) {
1294
+ const errorReason = `daemon shutdown could not drain ${workerStopFailures.length} managed worker group(s)`;
1295
+ (0, runtime_1.emitNervesEvent)({
1296
+ level: "error",
1297
+ component: "daemon",
1298
+ event: "daemon.worker_shutdown_error",
1299
+ message: errorReason,
1300
+ meta: {
1301
+ failures: workerStopFailures.map((error) => error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error rejection @preserve */ String(error)),
1302
+ },
1303
+ });
1304
+ throw new AggregateError(workerStopFailures, errorReason);
1305
+ }
350
1306
  }
351
1307
  async handleRawPayload(raw) {
352
1308
  try {
@@ -368,38 +1324,673 @@ class OuroDaemon {
368
1324
  message: "handling daemon command",
369
1325
  meta: { kind: command.kind },
370
1326
  });
1327
+ try {
1328
+ return await this.handleCommandInner(command);
1329
+ /* v8 ignore start — command error catch tested in daemon-command-error.test; instanceof branches defensive @preserve */
1330
+ }
1331
+ catch (error) {
1332
+ (0, runtime_1.emitNervesEvent)({
1333
+ level: "error",
1334
+ component: "daemon",
1335
+ event: "daemon.command_error",
1336
+ message: "unexpected error handling daemon command",
1337
+ meta: {
1338
+ kind: command.kind,
1339
+ error: error instanceof Error ? error.message : String(error),
1340
+ stack: error instanceof Error ? error.stack ?? null : null,
1341
+ },
1342
+ });
1343
+ throw error;
1344
+ }
1345
+ /* v8 ignore stop */
1346
+ }
1347
+ hasManagedPrivateRuntime(agent) {
1348
+ return this.processManager.listAgentSnapshots().some((snapshot) => snapshot.name === agent && snapshot.channel === "private-runtime");
1349
+ }
1350
+ buildPrivateRuntimeWakeRequest(command) {
1351
+ if (command.kind === "inner.wake") {
1352
+ return {
1353
+ agent: command.agent,
1354
+ origin: "daemon.private.wake",
1355
+ reason: "legacy inner.wake compatibility alias",
1356
+ providerLane: "inner",
1357
+ triggerSource: "legacy",
1358
+ budgetClass: "interactive",
1359
+ originRefs: [{ kind: "daemon-command", id: "inner.wake" }],
1360
+ };
1361
+ }
1362
+ const hasNoSendCapability = command.originRefs?.some((ref) => ref.kind === "capability" && ref.id === "no-send") ?? false;
1363
+ if ((command.noSend === true) !== hasNoSendCapability) {
1364
+ throw new Error("private-runtime no-send capability does not match its bound origin reference");
1365
+ }
1366
+ return {
1367
+ agent: command.agent,
1368
+ origin: "daemon.private.wake",
1369
+ reason: command.reason ?? "manual private-runtime wake",
1370
+ providerLane: "inner",
1371
+ triggerSource: command.triggerSource ?? "manual",
1372
+ budgetClass: command.budgetClass ?? "interactive",
1373
+ ...(command.idempotencyKey ? { idempotencyKey: command.idempotencyKey } : {}),
1374
+ originRefs: command.originRefs ?? [{ kind: "daemon-command", id: "private.wake" }],
1375
+ };
1376
+ }
1377
+ buildAwaitPrivateWakeCommand(command) {
1378
+ return (0, await_private_wake_1.buildAwaitPrivateWakeCommand)({
1379
+ agent: command.agent,
1380
+ awaitName: command.awaitName,
1381
+ triggerSource: "await-poke",
1382
+ });
1383
+ }
1384
+ buildTaskPokePrivateWakeCommand(command, receiptId) {
1385
+ return {
1386
+ kind: "private.wake",
1387
+ agent: command.agent,
1388
+ reason: `task poke ${command.taskId}`,
1389
+ triggerSource: "task-poke",
1390
+ budgetClass: "scheduled",
1391
+ idempotencyKey: `task-poke:${command.agent}:${command.taskId}:${receiptId}`,
1392
+ originRefs: [
1393
+ { kind: "task", id: command.taskId },
1394
+ { kind: "queue-receipt", id: receiptId },
1395
+ { kind: "daemon-command", id: "task.poke" },
1396
+ ],
1397
+ };
1398
+ }
1399
+ buildExternalEventPrivateWakeCommand(command, receiptId, generation, attemptCount) {
1400
+ return {
1401
+ kind: "private.wake",
1402
+ agent: command.agent,
1403
+ reason: `external event ${command.source}/${command.eventType}`,
1404
+ triggerSource: "external-event",
1405
+ budgetClass: "interactive",
1406
+ idempotencyKey: `external-event:${command.agent}:${command.source}:${command.eventId}:generation:${generation}:attempt:${attemptCount}`,
1407
+ originRefs: [
1408
+ { kind: "external-event", id: command.eventId, source: command.source, eventType: command.eventType },
1409
+ { kind: "queue-receipt", id: receiptId },
1410
+ { kind: "daemon-command", id: "external.event.submit" },
1411
+ ],
1412
+ };
1413
+ }
1414
+ resolveHabitDispatch(options) {
1415
+ const agentRoot = path.join(this.bundlesRoot, `${options.agent}.ouro`);
1416
+ const habitPath = path.join(agentRoot, "habits", `${options.habitName}.md`);
1417
+ const isRsvp = (0, habit_policy_1.isRsvpHabitName)(options.habitName);
1418
+ let readFailure = null;
1419
+ let habit;
1420
+ if (!fs.existsSync(habitPath)) {
1421
+ readFailure = "missing";
1422
+ habit = (0, habit_parser_1.createDegradedHabitFile)(habitPath, "read_error", "", "habit file not found");
1423
+ }
1424
+ else {
1425
+ try {
1426
+ habit = (0, habit_runtime_state_1.applyHabitRuntimeState)(agentRoot, (0, habit_parser_1.parseHabitFile)(fs.readFileSync(habitPath, "utf-8"), habitPath));
1427
+ }
1428
+ catch (error) {
1429
+ readFailure = "read";
1430
+ habit = (0, habit_parser_1.createDegradedHabitFile)(habitPath, "read_error", "", messageFromHabitPokeError(error));
1431
+ }
1432
+ }
1433
+ if (habit.status !== "active") {
1434
+ let skipReason = `habit status ${habit.status} is non-executable`;
1435
+ if (isRsvp && habit.status === "degraded") {
1436
+ if (readFailure === "missing") {
1437
+ skipReason = "RSVP habit file not found";
1438
+ }
1439
+ else {
1440
+ skipReason = `RSVP habit metadata invalid: ${habit.degradedDetail ?? habit.degradedReason}`;
1441
+ }
1442
+ }
1443
+ else if (readFailure === "missing"
1444
+ && options.source === "habit-poke"
1445
+ && options.trigger !== "manual"
1446
+ && options.trigger !== "poke") {
1447
+ skipReason = "habit file not found";
1448
+ }
1449
+ return { kind: "skipped", habit, skipReason };
1450
+ }
1451
+ if (isRsvp && !habit.rsvp) {
1452
+ return {
1453
+ kind: "skipped",
1454
+ habit,
1455
+ skipReason: "RSVP habit metadata is required before private runtime wake",
1456
+ };
1457
+ }
1458
+ if (options.trigger === "poke" || options.trigger === "manual") {
1459
+ return { kind: "ready", habit };
1460
+ }
1461
+ if (typeof options.occurrenceId === "string" && options.occurrenceId.trim().length > 0) {
1462
+ return { kind: "ready", habit, occurrenceId: options.occurrenceId.trim() };
1463
+ }
1464
+ if (habit.cadence === null) {
1465
+ return { kind: "skipped", habit, skipReason: "habit has no cadence" };
1466
+ }
1467
+ if (habit.lastRun === null) {
1468
+ return { kind: "ready", habit, occurrenceId: `${options.trigger}:first-run:${habit.cadence}` };
1469
+ }
1470
+ return {
1471
+ kind: "ready",
1472
+ habit,
1473
+ occurrenceId: `${options.trigger}:last-run:${habit.lastRun}:cadence:${habit.cadence}`,
1474
+ };
1475
+ }
1476
+ emitHabitDispatchSkipped(options) {
1477
+ (0, runtime_1.emitNervesEvent)({
1478
+ level: "warn",
1479
+ component: "daemon",
1480
+ event: "daemon.habit_dispatch_skipped",
1481
+ message: "habit dispatch rejected by current lifecycle state",
1482
+ meta: {
1483
+ agent: options.agent,
1484
+ habitName: options.habitName,
1485
+ trigger: options.trigger,
1486
+ status: options.resolution.habit.status,
1487
+ degradedReason: options.resolution.habit.status === "degraded"
1488
+ ? options.resolution.habit.degradedReason
1489
+ : null,
1490
+ detail: options.resolution.habit.status === "degraded"
1491
+ ? options.resolution.habit.degradedDetail
1492
+ : null,
1493
+ reason: options.resolution.skipReason,
1494
+ },
1495
+ });
1496
+ }
1497
+ emitHabitDispatchReady(options) {
1498
+ (0, runtime_1.emitNervesEvent)({
1499
+ component: "daemon",
1500
+ event: "daemon.habit_dispatch_ready",
1501
+ message: "habit dispatch accepted by current lifecycle state",
1502
+ meta: {
1503
+ agent: options.agent,
1504
+ habitName: options.habitName,
1505
+ trigger: options.trigger,
1506
+ status: options.resolution.habit.status,
1507
+ occurrenceId: options.resolution.occurrenceId ?? null,
1508
+ },
1509
+ });
1510
+ }
1511
+ skippedHabitDispatchResponse(options) {
1512
+ return {
1513
+ ok: true,
1514
+ message: `skipped scheduled habit ${options.habitName} for ${options.agent}: ${options.skipReason}`,
1515
+ };
1516
+ }
1517
+ async runNativeRsvpHabit(command, trigger, occurrenceId, noSend = false) {
1518
+ const runner = this.rsvpHabitRunner ?? (async (input) => {
1519
+ const { runNativeRsvpHabit } = await Promise.resolve().then(() => __importStar(require("../../rsvp/native-habit-runner")));
1520
+ return runNativeRsvpHabit(input);
1521
+ });
1522
+ const result = await runner({
1523
+ agent: command.agent,
1524
+ bundlesRoot: this.bundlesRoot,
1525
+ habitName: command.habitName,
1526
+ trigger,
1527
+ ...(occurrenceId ? { occurrenceId } : {}),
1528
+ ...(noSend ? { noSend: true } : {}),
1529
+ });
1530
+ if (noSend) {
1531
+ const payload = result.payload;
1532
+ const status = payload?.status;
1533
+ const transportInvocationCount = payload?.transportInvocationCount;
1534
+ const contractError = "native RSVP habit probe violated the immutable no-send result contract";
1535
+ if (!result.ok) {
1536
+ return {
1537
+ ok: false,
1538
+ error: result.message,
1539
+ data: {
1540
+ ok: false,
1541
+ noSend: true,
1542
+ status: typeof status === "string" ? status : "degraded",
1543
+ transportInvocationCount: null,
1544
+ error: result.message,
1545
+ },
1546
+ };
1547
+ }
1548
+ if (payload?.noSend !== true
1549
+ || typeof status !== "string"
1550
+ || typeof transportInvocationCount !== "number"
1551
+ || transportInvocationCount !== 0) {
1552
+ return {
1553
+ ok: false,
1554
+ error: contractError,
1555
+ data: {
1556
+ ok: false,
1557
+ noSend: true,
1558
+ status: typeof status === "string" ? status : "degraded",
1559
+ transportInvocationCount: null,
1560
+ error: contractError,
1561
+ },
1562
+ };
1563
+ }
1564
+ return {
1565
+ ok: true,
1566
+ message: result.message,
1567
+ data: { noSend: true, status, transportInvocationCount: 0 },
1568
+ };
1569
+ }
1570
+ return {
1571
+ ok: result.ok,
1572
+ message: result.message,
1573
+ data: result,
1574
+ };
1575
+ }
1576
+ buildPrivateRuntimeWorkerWakeMessage(command, decision, externalEvent) {
1577
+ const awaitName = (0, await_private_wake_1.awaitNameFromPrivateWakeCommand)(command);
1578
+ if (awaitName) {
1579
+ return {
1580
+ type: "await",
1581
+ awaitName,
1582
+ privateTurnDecision: decision,
1583
+ };
1584
+ }
1585
+ const taskId = taskIdFromTaskPokePrivateWakeCommand(command);
1586
+ if (taskId) {
1587
+ return {
1588
+ type: "poke",
1589
+ taskId,
1590
+ privateTurnDecision: decision,
1591
+ };
1592
+ }
1593
+ const habitMessage = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
1594
+ if (habitMessage) {
1595
+ return {
1596
+ type: "habit",
1597
+ habitName: habitMessage.habitName,
1598
+ trigger: habitMessage.trigger,
1599
+ ...(habitMessage.noSend ? { noSend: true } : {}),
1600
+ privateTurnDecision: decision,
1601
+ };
1602
+ }
1603
+ return { type: "message", privateTurnDecision: decision, ...(externalEvent ? { externalEvent } : {}) };
1604
+ }
1605
+ queueOperatorCliMessageForPrivateRuntime(command) {
1606
+ if (command.kind !== "private.wake" || command.triggerSource !== "operator-cli")
1607
+ return;
1608
+ const receiptId = command.originRefs?.find((ref) => ref.kind === "daemon-receipt")?.id;
1609
+ if (!receiptId)
1610
+ return;
1611
+ const messages = this.router.peekInbox?.(command.agent) ?? [];
1612
+ const routed = messages.find((message) => message.id === receiptId);
1613
+ if (!routed)
1614
+ return;
1615
+ const pendingDir = path.join(this.bundlesRoot, `${command.agent}.ouro`, "state", "pending", pending_1.PRIVATE_RUNTIME_PENDING.friendId, pending_1.PRIVATE_RUNTIME_PENDING.channel, pending_1.PRIVATE_RUNTIME_PENDING.key);
1616
+ const queuedAtMs = Date.parse(routed.queuedAt);
1617
+ (0, pending_1.queuePendingMessageOnce)(pendingDir, {
1618
+ from: routed.from,
1619
+ content: routed.content,
1620
+ timestamp: Number.isFinite(queuedAtMs) ? queuedAtMs : Date.now(),
1621
+ mode: "relay",
1622
+ requestId: routed.id,
1623
+ packetId: `operator-cli:${command.agent}:${routed.id}`,
1624
+ });
1625
+ }
1626
+ queueExternalEventForPrivateRuntime(record, quiet = false) {
1627
+ const pendingDir = path.join(this.bundlesRoot, `${record.agent}.ouro`, "state", "pending", pending_1.PRIVATE_RUNTIME_PENDING.friendId, pending_1.PRIVATE_RUNTIME_PENDING.channel, pending_1.PRIVATE_RUNTIME_PENDING.key);
1628
+ const originKey = `${record.source}:${record.eventId}`;
1629
+ const parsedReceivedAt = Date.parse(record.receivedAt);
1630
+ (0, pending_1.queuePendingMessageOnce)(pendingDir, {
1631
+ from: "ouro-external-event",
1632
+ friendId: "ouro-external-event",
1633
+ channel: "external-event",
1634
+ key: originKey,
1635
+ content: (0, router_1.buildExternalEventMessage)(record),
1636
+ timestamp: Number.isFinite(parsedReceivedAt) ? parsedReceivedAt : Date.now(),
1637
+ delegatedFrom: {
1638
+ friendId: "ouro-external-event",
1639
+ channel: "external-event",
1640
+ key: originKey,
1641
+ },
1642
+ obligationStatus: "pending",
1643
+ mode: "relay",
1644
+ packetId: `external-event:${record.agent}:${record.source}:${record.eventId}:generation:${record.generation}:attempt:${record.attemptCount}`,
1645
+ });
1646
+ if (!quiet) {
1647
+ (0, runtime_1.emitNervesEvent)({
1648
+ component: "daemon",
1649
+ event: "daemon.external_event_private_runtime_queued",
1650
+ message: "queued external event for private-runtime attention",
1651
+ meta: {
1652
+ agent: record.agent,
1653
+ source: record.source,
1654
+ eventType: record.eventType,
1655
+ eventId: record.eventId,
1656
+ pendingDir,
1657
+ },
1658
+ });
1659
+ }
1660
+ }
1661
+ externalEventRootPath() {
1662
+ return this.externalEventRoot ?? (0, router_1.getExternalEventRoot)();
1663
+ }
1664
+ externalEventLease(record) {
1665
+ /* v8 ignore next -- dispatcher calls this only with the record returned by claimExternalEvent @preserve */
1666
+ if (!record.claimOwner)
1667
+ throw new Error("External event dispatch requires a claimed receipt");
1668
+ return {
1669
+ schemaVersion: 1,
1670
+ recordPath: record.recordPath,
1671
+ agent: record.agent,
1672
+ source: record.source,
1673
+ eventId: record.eventId,
1674
+ generation: record.generation,
1675
+ observationRevision: record.observationRevision,
1676
+ claimOwner: record.claimOwner,
1677
+ };
1678
+ }
1679
+ async dispatchExternalEvents(records) {
1680
+ const claimed = [];
1681
+ let failureClass;
1682
+ try {
1683
+ for (const key of new Set(records.map((record) => `${record.agent}\0${record.source}`))) {
1684
+ const [agent, source] = key.split("\0");
1685
+ await this.externalEventSourceReadiness(agent, source);
1686
+ }
1687
+ for (const record of records) {
1688
+ const owner = `external-event:${record.agent}:${record.source}:${record.eventId}:generation:${record.generation}:attempt:${record.attemptCount + 1}`;
1689
+ claimed.push((0, router_1.claimExternalEvent)(record.recordPath, { owner, expectedVersion: record.version, expectedGeneration: record.generation }));
1690
+ }
1691
+ const primary = claimed[0];
1692
+ const [primaryLease, ...relatedEvents] = claimed.map((record) => this.externalEventLease(record));
1693
+ const lease = { ...primaryLease, ...(relatedEvents.length > 0 ? { relatedEvents } : {}) };
1694
+ const receipt = {
1695
+ id: `external-event:${primary.agent}:${primary.source}:${primary.eventId}:generation:${primary.generation}:attempt:${primary.attemptCount}`,
1696
+ queuedAt: primary.updatedAt,
1697
+ };
1698
+ const wake = await this.handlePrivateRuntimeWake(this.buildExternalEventPrivateWakeCommand({
1699
+ kind: "external.event.submit",
1700
+ agent: primary.agent,
1701
+ source: primary.source,
1702
+ eventType: primary.eventType,
1703
+ eventId: primary.eventId,
1704
+ }, receipt.id, primary.generation, primary.attemptCount), () => {
1705
+ const batched = claimed.length > 1;
1706
+ for (const record of claimed)
1707
+ this.queueExternalEventForPrivateRuntime(record, batched);
1708
+ if (batched) {
1709
+ (0, runtime_1.emitNervesEvent)({
1710
+ component: "daemon",
1711
+ event: "daemon.external_event_private_runtime_batch_queued",
1712
+ message: "queued an external-event batch for private-runtime attention",
1713
+ meta: { agent: primary.agent, source: primary.source, eventCount: claimed.length },
1714
+ });
1715
+ }
1716
+ }, lease);
1717
+ failureClass = wake.denialCode === "managed_runtime_unavailable"
1718
+ ? "managed_runtime_unavailable"
1719
+ : wake.data?.decision?.denialCode === "provider_lane_unavailable"
1720
+ ? "provider_lane_unavailable"
1721
+ : undefined;
1722
+ const denied = !wake.ok || wake.data?.decision?.executable === false;
1723
+ if (denied)
1724
+ throw new Error(wake.error ?? wake.message ?? /* v8 ignore next -- daemon wake responses always carry an error or message @preserve */ "external-event private turn was denied");
1725
+ return { events: claimed, event: primary, receipt, wake };
1726
+ }
1727
+ catch (error) {
1728
+ for (const record of claimed) {
1729
+ (0, router_1.settleExternalEventFailureIfOwned)(record.recordPath, {
1730
+ owner: record.claimOwner, expectedGeneration: record.generation,
1731
+ error: failureClass ? `external-event private-runtime dispatch failed: ${failureClass}` : "external-event private-runtime dispatch failed",
1732
+ ...(failureClass ? { failureClass } : {}),
1733
+ });
1734
+ }
1735
+ throw error;
1736
+ }
1737
+ }
1738
+ dispatchExternalEvent(record) {
1739
+ return this.dispatchExternalEvents([record]);
1740
+ }
1741
+ async reconcileExternalEvents() {
1742
+ /* v8 ignore next -- re-entrancy guard is exercised only by overlapping real timer callbacks @preserve */
1743
+ if (this.externalEventReconcileRunning)
1744
+ return;
1745
+ this.externalEventReconcileRunning = true;
1746
+ try {
1747
+ const now = new Date().toISOString();
1748
+ if (fs.existsSync(this.privilegedEventSpoolRoot)) {
1749
+ this.privilegedEventScanner({ spoolRoot: this.privilegedEventSpoolRoot, eventRoot: this.externalEventRootPath() });
1750
+ }
1751
+ const scanned = this.externalEventScanCache.scan(this.externalEventRootPath());
1752
+ const readinessKeys = new Set();
1753
+ for (const { record: candidate } of scanned) {
1754
+ if (!candidate)
1755
+ continue;
1756
+ if (candidate.dispatchEnabled === false)
1757
+ continue;
1758
+ const retryDue = candidate.executionState === "retry_wait" && candidate.nextAttemptAt !== null && Date.parse(candidate.nextAttemptAt) <= Date.parse(now);
1759
+ const leaseExpired = candidate.executionState === "running" && candidate.claimExpiresAt !== null && Date.parse(candidate.claimExpiresAt) <= Date.parse(now);
1760
+ const recoverableDeadLetter = candidate.executionState === "dead_letter"
1761
+ && (0, router_1.externalEventRecoveryFailure)(candidate) !== null
1762
+ && candidate.recoveryGrant?.generation !== candidate.generation;
1763
+ const dispatchable = candidate.executionState === "received" || candidate.executionState === "queued" || retryDue || leaseExpired || recoverableDeadLetter;
1764
+ if (dispatchable && (candidate.source === "sanctuary-health" || candidate.source === "sanctuary-usenet"))
1765
+ readinessKeys.add(`${candidate.agent}\0${candidate.source}`);
1766
+ }
1767
+ const blockedReadinessKeys = new Set();
1768
+ for (const key of readinessKeys) {
1769
+ const [agent, source] = key.split("\0");
1770
+ try {
1771
+ await this.externalEventSourceReadiness(agent, source);
1772
+ }
1773
+ catch (error) {
1774
+ blockedReadinessKeys.add(key);
1775
+ (0, runtime_1.emitNervesEvent)({
1776
+ level: "warn",
1777
+ component: "daemon",
1778
+ event: "daemon.external_event_readiness_blocked",
1779
+ message: "external-event reconciliation is waiting for source runtime readiness",
1780
+ meta: { agent, source, error: (error instanceof Error ? error.message : String(error)).slice(0, 1_000) },
1781
+ });
1782
+ }
1783
+ }
1784
+ const dueRecords = [];
1785
+ const providerEvidenceByAgent = new Map();
1786
+ const runtimeEvidenceByAgent = new Map();
1787
+ const recoveredByClass = new Map();
1788
+ for (const { record: scannedRecord } of scanned) {
1789
+ if (!scannedRecord)
1790
+ continue;
1791
+ let record = scannedRecord;
1792
+ if (record.dispatchEnabled === false)
1793
+ continue;
1794
+ if (blockedReadinessKeys.has(`${record.agent}\0${record.source}`))
1795
+ continue;
1796
+ if (record.executionState === "dead_letter") {
1797
+ const failure = (0, router_1.externalEventRecoveryFailure)(record);
1798
+ if (!failure || record.recoveryGrant?.generation === record.generation)
1799
+ continue;
1800
+ let evidence = null;
1801
+ try {
1802
+ if (failure.class === "provider_lane_unavailable") {
1803
+ if (!providerEvidenceByAgent.has(record.agent)) {
1804
+ providerEvidenceByAgent.set(record.agent, null);
1805
+ const binding = (0, provider_binding_resolver_1.resolveEffectiveProviderBinding)({
1806
+ agentName: record.agent,
1807
+ agentRoot: path.join(this.bundlesRoot, `${record.agent}.ouro`),
1808
+ lane: "inner",
1809
+ });
1810
+ providerEvidenceByAgent.set(record.agent, binding.ok && binding.binding.credential.status === "present"
1811
+ && binding.binding.readiness.status === "ready" && binding.binding.readiness.checkedAt
1812
+ ? { observedAt: binding.binding.readiness.checkedAt }
1813
+ : null);
1814
+ }
1815
+ const current = providerEvidenceByAgent.get(record.agent);
1816
+ const readinessIsCurrentBoot = current && Date.parse(current.observedAt) >= this.constructedAtMs;
1817
+ if (current && ((0, router_1.isExactLegacyProviderRecoveryFailure)(record)
1818
+ ? readinessIsCurrentBoot
1819
+ : Date.parse(current.observedAt) > Date.parse(failure.failedAt))) {
1820
+ evidence = { class: failure.class, observedAt: current.observedAt };
1821
+ }
1822
+ }
1823
+ else if (failure.class === "execution_lease_expired") {
1824
+ if (!runtimeEvidenceByAgent.has(record.agent)) {
1825
+ const snapshot = this.processManager.listAgentSnapshots().find((candidate) => candidate.name === record.agent && candidate.channel === "private-runtime"
1826
+ && candidate.status === "running" && candidate.pid !== null && candidate.startedAt !== null);
1827
+ runtimeEvidenceByAgent.set(record.agent, snapshot?.startedAt ? { observedAt: snapshot.startedAt } : null);
1828
+ }
1829
+ const current = runtimeEvidenceByAgent.get(record.agent);
1830
+ if (current && Date.parse(current.observedAt) > Date.parse(failure.failedAt)) {
1831
+ evidence = { class: failure.class, observedAt: current.observedAt };
1832
+ }
1833
+ }
1834
+ else if (this.hasManagedPrivateRuntime(record.agent) && Date.parse(now) > Date.parse(failure.failedAt)) {
1835
+ evidence = { class: failure.class, observedAt: now };
1836
+ }
1837
+ if (!evidence)
1838
+ continue;
1839
+ const revival = (0, router_1.reviveExternalEventAfterRecovery)(record.recordPath, { expectedVersion: record.version, expectedGeneration: record.generation, evidence, now: () => now, quiet: true });
1840
+ record = revival.record;
1841
+ recoveredByClass.set(failure.class, (recoveredByClass.get(failure.class) ?? 0) + 1);
1842
+ }
1843
+ catch (error) {
1844
+ (0, runtime_1.emitNervesEvent)({
1845
+ level: "warn",
1846
+ component: "daemon",
1847
+ event: "daemon.external_event_recovery_error",
1848
+ message: "external event dead-letter recovery check failed",
1849
+ meta: { agent: record.agent, source: record.source, eventId: record.eventId, generation: record.generation, error: error instanceof Error ? error.message : String(error) },
1850
+ });
1851
+ continue;
1852
+ }
1853
+ }
1854
+ if (record.executionState === "running" && record.claimExpiresAt && Date.parse(record.claimExpiresAt) <= Date.parse(now)) {
1855
+ record = (0, router_1.reconcileExternalEvent)(record.recordPath);
1856
+ }
1857
+ const due = record.executionState === "received"
1858
+ || record.executionState === "queued"
1859
+ || (record.executionState === "retry_wait" && record.nextAttemptAt !== null && Date.parse(record.nextAttemptAt) <= Date.parse(now));
1860
+ if (due)
1861
+ dueRecords.push(record);
1862
+ }
1863
+ if (recoveredByClass.size > 0) {
1864
+ (0, runtime_1.emitNervesEvent)({
1865
+ component: "daemon",
1866
+ event: "daemon.external_event_recovery_batch",
1867
+ message: "requeued external events after cached infrastructure recovery evidence",
1868
+ meta: { recovered: Object.fromEntries(recoveredByClass) },
1869
+ });
1870
+ }
1871
+ const batches = new Map();
1872
+ for (const record of dueRecords) {
1873
+ const key = `${record.agent}\0${record.source}`;
1874
+ const batch = batches.get(key) ?? [];
1875
+ batch.push(record);
1876
+ batches.set(key, batch);
1877
+ }
1878
+ for (const records of batches.values()) {
1879
+ for (let offset = 0; offset < records.length; offset += 32) {
1880
+ const batch = records.slice(offset, offset + 32);
1881
+ try {
1882
+ await this.dispatchExternalEvents(batch);
1883
+ }
1884
+ catch (error) {
1885
+ (0, runtime_1.emitNervesEvent)({
1886
+ level: "warn",
1887
+ component: "daemon",
1888
+ event: "daemon.external_event_dispatch_error",
1889
+ message: "external event dispatch failed",
1890
+ meta: { recordPath: batch[0].recordPath, batchSize: batch.length, error: error instanceof Error ? error.message : /* v8 ignore next -- dispatch failures are Error objects @preserve */ String(error) },
1891
+ });
1892
+ }
1893
+ }
1894
+ }
1895
+ }
1896
+ finally {
1897
+ this.externalEventReconcileRunning = false;
1898
+ }
1899
+ }
1900
+ async handlePrivateRuntimeWake(command, beforeDispatch, externalEvent) {
1901
+ if (!this.hasManagedPrivateRuntime(command.agent)) {
1902
+ return {
1903
+ ok: false,
1904
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
1905
+ denialCode: "managed_runtime_unavailable",
1906
+ };
1907
+ }
1908
+ const decision = await (0, private_runtime_1.requestPrivateTurnDecision)(this.buildPrivateRuntimeWakeRequest(command), {
1909
+ bundlesRoot: this.bundlesRoot,
1910
+ ...this.privateRuntimePolicyDeps,
1911
+ });
1912
+ if (!decision.executable) {
1913
+ return {
1914
+ ok: true,
1915
+ message: `private-runtime wake denied for ${command.agent}: ${decision.deniedReason}`,
1916
+ ...(decision.denialCode ? { denialCode: decision.denialCode } : {}),
1917
+ data: { decision },
1918
+ };
1919
+ }
1920
+ this.queueOperatorCliMessageForPrivateRuntime(command);
1921
+ await beforeDispatch?.(decision);
1922
+ await this.processManager.startAgent(command.agent);
1923
+ const message = this.buildPrivateRuntimeWorkerWakeMessage(command, decision, externalEvent);
1924
+ if (this.processManager.dispatchToAgent)
1925
+ await this.processManager.dispatchToAgent(command.agent, message);
1926
+ else
1927
+ this.processManager.sendToAgent?.(command.agent, message);
1928
+ return {
1929
+ ok: true,
1930
+ message: `woke private runtime for ${command.agent}`,
1931
+ data: { decision },
1932
+ };
1933
+ }
1934
+ async handleCommandInner(command) {
371
1935
  switch (command.kind) {
372
1936
  case "daemon.start":
373
1937
  await this.start();
374
1938
  return { ok: true, message: "daemon started" };
375
1939
  case "daemon.stop":
376
- await this.stop();
1940
+ try {
1941
+ await this.stop();
1942
+ }
1943
+ finally {
1944
+ await this.onStopCommandComplete?.();
1945
+ }
377
1946
  return { ok: true, message: "daemon stopped" };
378
- case "daemon.status": {
379
- const snapshots = this.processManager.listAgentSnapshots();
380
- const workers = buildWorkerRows(snapshots);
381
- const senses = this.senseManager?.listSenseRows() ?? [];
382
- const repoRoot = (0, identity_1.getRepoRoot)();
383
- const data = {
384
- overview: {
385
- daemon: "running",
386
- health: workers.every((worker) => worker.status === "running") ? "ok" : "warn",
387
- socketPath: this.socketPath,
388
- ...(0, runtime_metadata_1.getRuntimeMetadata)(),
389
- workerCount: workers.length,
390
- senseCount: senses.length,
391
- entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
392
- mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
1947
+ case "daemon.restart": {
1948
+ // Restart is "stop + let launchctl respawn." Under launchctl's KeepAlive
1949
+ // policy the process is auto-restarted on exit, so daemon.restart and
1950
+ // daemon.stop differ only in intent + audit trail. In dev (no launchctl),
1951
+ // the process simply exits — same observable behavior as daemon.stop.
1952
+ (0, runtime_1.emitNervesEvent)({
1953
+ component: "daemon",
1954
+ event: "daemon.restart_requested",
1955
+ message: "daemon restart requested",
1956
+ meta: {
1957
+ reason: command.reason ?? null,
1958
+ requestedBy: command.requestedBy ?? null,
393
1959
  },
394
- workers,
395
- senses,
1960
+ });
1961
+ try {
1962
+ await this.stop();
1963
+ }
1964
+ finally {
1965
+ await this.onStopCommandComplete?.();
1966
+ }
1967
+ return {
1968
+ ok: true,
1969
+ message: "daemon restarting — launchctl will respawn",
396
1970
  };
1971
+ }
1972
+ case "daemon.status": {
1973
+ const data = this.buildStatusPayload();
397
1974
  return {
398
1975
  ok: true,
399
1976
  summary: formatStatusSummary(data),
400
1977
  data,
401
1978
  };
402
1979
  }
1980
+ case "daemon.shepherd_stopped": {
1981
+ if (typeof command.agent !== "string" || !this.senseManager?.shepherdStoppedProof) {
1982
+ return { ok: false, error: "Shepherd lifecycle proof is unavailable" };
1983
+ }
1984
+ const data = this.senseManager.shepherdStoppedProof(command.agent);
1985
+ return { ok: true, data };
1986
+ }
1987
+ case "daemon.shepherd_quiesce": {
1988
+ if (typeof command.agent !== "string" || !this.senseManager?.quiesceShepherd) {
1989
+ return { ok: false, error: "Shepherd lifecycle control is unavailable" };
1990
+ }
1991
+ const data = await this.senseManager.quiesceShepherd(command.agent);
1992
+ return { ok: true, data };
1993
+ }
403
1994
  case "daemon.health": {
404
1995
  const checks = await this.healthMonitor.runChecks();
405
1996
  const summary = checks.map((check) => `${check.name}:${check.status}:${check.message}`).join("\n");
@@ -412,15 +2003,115 @@ class OuroDaemon {
412
2003
  message: "log streaming available via ouro logs",
413
2004
  data: { logDir: "~/AgentBundles/<agent>.ouro/state/daemon/logs" },
414
2005
  };
2006
+ case "daemon.sense_revive": {
2007
+ if (!isValidSenseReviveCommand(command)) {
2008
+ return {
2009
+ ok: false,
2010
+ error: "Invalid daemon.sense_revive payload: expected string fields 'agent', 'sense', and 'reason'.",
2011
+ };
2012
+ }
2013
+ const revivedSenseRow = await this.senseManager?.reviveSense?.(command.agent, command.sense);
2014
+ if (revivedSenseRow) {
2015
+ return {
2016
+ ok: true,
2017
+ message: `revived ${command.agent}/${command.sense}`,
2018
+ data: revivedSenseRow,
2019
+ };
2020
+ }
2021
+ const managedSenseSnapshots = this.processManager.listAgentSnapshots()
2022
+ .filter((snapshot) => snapshot.name.startsWith(`${command.agent}:`));
2023
+ if (managedSenseSnapshots.length === 0) {
2024
+ return {
2025
+ ok: false,
2026
+ error: `No managed agent '${command.agent}' is registered with daemon-managed senses.`,
2027
+ };
2028
+ }
2029
+ const exactTargetName = `${command.agent}:${command.sense}`;
2030
+ const target = managedSenseSnapshots.find((snapshot) => snapshot.name === exactTargetName)
2031
+ ?? managedSenseSnapshots.find((snapshot) => snapshot.channel === command.sense);
2032
+ if (!target) {
2033
+ return {
2034
+ ok: false,
2035
+ error: `No managed sense '${command.sense}' is registered for agent '${command.agent}'.`,
2036
+ };
2037
+ }
2038
+ this.processManager.resetAgentFailureState(target.name);
2039
+ await this.processManager.startAgent(target.name);
2040
+ const freshSnapshot = this.processManager.listAgentSnapshots()
2041
+ .find((snapshot) => snapshot.name === target.name) ?? target;
2042
+ return {
2043
+ ok: true,
2044
+ message: `revived ${command.agent}/${command.sense}`,
2045
+ data: freshSnapshot,
2046
+ };
2047
+ }
415
2048
  case "agent.start":
416
2049
  await this.processManager.startAgent(command.agent);
417
2050
  return { ok: true, message: `started ${command.agent}` };
418
2051
  case "agent.stop":
419
2052
  await this.processManager.stopAgent?.(command.agent);
420
2053
  return { ok: true, message: `stopped ${command.agent}` };
421
- case "agent.restart":
422
- await this.processManager.restartAgent?.(command.agent);
423
- return { ok: true, message: `restarted ${command.agent}` };
2054
+ case "agent.restart": {
2055
+ if (!this.processManager.restartAgent) {
2056
+ return { ok: false, error: "Managed agent restart is not available." };
2057
+ }
2058
+ const managedSnapshot = this.processManager.listAgentSnapshots()
2059
+ .find((snapshot) => snapshot.name === command.agent);
2060
+ if (!managedSnapshot) {
2061
+ return { ok: false, error: `Unknown managed agent '${command.agent}'.` };
2062
+ }
2063
+ if (managedSnapshot.autoStart === false && managedSnapshot.status === "stopped") {
2064
+ return { ok: true, message: `restart skipped for parked non-autostart agent '${command.agent}'` };
2065
+ }
2066
+ const restartWork = command.skipConfigCheck === true
2067
+ ? this.processManager.restartAgent(command.agent, { skipConfigCheck: true })
2068
+ : this.processManager.restartAgent(command.agent);
2069
+ void restartWork.catch((error) => {
2070
+ (0, runtime_1.emitNervesEvent)({
2071
+ level: "error",
2072
+ component: "daemon",
2073
+ event: "daemon.agent_restart_request_error",
2074
+ message: "managed agent restart failed after request acknowledgement",
2075
+ meta: {
2076
+ agent: command.agent,
2077
+ error: error instanceof Error ? error.message : String(error),
2078
+ },
2079
+ });
2080
+ });
2081
+ return { ok: true, message: `restart requested for ${command.agent}` };
2082
+ }
2083
+ case "agent.ask":
2084
+ return handleAgentAskTurn(command, { socketPath: this.socketPath });
2085
+ case "agent.status":
2086
+ return (0, agent_service_1.handleAgentStatus)(command);
2087
+ case "agent.catchup":
2088
+ return (0, agent_service_1.handleAgentCatchup)(command);
2089
+ case "agent.delegate":
2090
+ return (0, agent_service_1.handleAgentDelegate)(command);
2091
+ case "agent.getContext":
2092
+ return (0, agent_service_1.handleAgentGetContext)(command);
2093
+ case "agent.searchFacts":
2094
+ return (0, agent_service_1.handleAgentSearchFacts)(command);
2095
+ case "agent.getTask":
2096
+ return (0, agent_service_1.handleAgentGetTask)(command);
2097
+ case "agent.checkScope":
2098
+ return (0, agent_service_1.handleAgentCheckScope)(command);
2099
+ case "agent.requestDecision":
2100
+ return (0, agent_service_1.handleAgentRequestDecision)(command);
2101
+ case "agent.checkGuidance":
2102
+ return (0, agent_service_1.handleAgentCheckGuidance)(command);
2103
+ case "agent.reportProgress":
2104
+ return (0, agent_service_1.handleAgentReportProgress)(command);
2105
+ case "agent.reportBlocker":
2106
+ return (0, agent_service_1.handleAgentReportBlocker)(command);
2107
+ case "agent.reportComplete":
2108
+ return (0, agent_service_1.handleAgentReportComplete)(command);
2109
+ case "agent.senseTurn":
2110
+ return handleAgentSenseTurn(command, { socketPath: this.socketPath });
2111
+ /* v8 ignore stop */
2112
+ case "agent.shepherdFeedback":
2113
+ case "agent.shepherdFeedbackStatus":
2114
+ return (await Promise.resolve().then(() => __importStar(require("../../senses/shepherd/feedback-submit")))).executeFeedbackCommand(command);
424
2115
  case "cron.list": {
425
2116
  const jobs = this.scheduler.listJobs();
426
2117
  const summary = jobs.length === 0
@@ -429,10 +2120,28 @@ class OuroDaemon {
429
2120
  return { ok: true, summary, data: jobs };
430
2121
  }
431
2122
  case "cron.trigger": {
2123
+ const habitResult = await this.scheduler.triggerHabitJob?.(command.jobId);
2124
+ if (habitResult?.ok) {
2125
+ return { ok: true, message: habitResult.message };
2126
+ }
432
2127
  const result = await this.scheduler.triggerJob(command.jobId);
433
2128
  return { ok: result.ok, message: result.message };
434
2129
  }
435
2130
  case "message.send": {
2131
+ // Pure queue-only delivery. We DO NOT wake the recipient — that was
2132
+ // the 2026-05-11 $50 bleed. The Claude Code post-tool-use hook
2133
+ // (cli-exec.ts) intentionally sends only message.send for tool-use
2134
+ // events to avoid waking the agent on every tool call. The hook's
2135
+ // intent was completely defeated by this handler calling
2136
+ // `sendToAgent({type: "message"})`, which woke the private runtime
2137
+ // worker on EVERY message.send anyway. ~30 message.send/min × the
2138
+ // 3-turn instinct-loop cap = ~90 turns/min sustained for hours.
2139
+ //
2140
+ // Callers that want immediate processing must send `private.wake`
2141
+ // explicitly after message.send. The CLI `ouro msg` does so
2142
+ // (lifecycle-boundary delivery should wake); the hook does so
2143
+ // only on session-start / stop, not per tool-use; the API does
2144
+ // not (notifications go to the queue).
436
2145
  const receipt = await this.router.send({
437
2146
  from: command.from,
438
2147
  to: command.to,
@@ -441,7 +2150,6 @@ class OuroDaemon {
441
2150
  sessionId: command.sessionId,
442
2151
  taskRef: command.taskRef,
443
2152
  });
444
- this.processManager.sendToAgent?.(command.to, { type: "message" });
445
2153
  return { ok: true, message: `queued message ${receipt.id}`, data: receipt };
446
2154
  }
447
2155
  case "message.poll": {
@@ -452,13 +2160,127 @@ class OuroDaemon {
452
2160
  data: messages,
453
2161
  };
454
2162
  }
455
- case "inner.wake":
456
- await this.processManager.startAgent(command.agent);
457
- this.processManager.sendToAgent?.(command.agent, { type: "message" });
2163
+ case "external.event.submit": {
2164
+ const record = (0, router_1.recordExternalEvent)({
2165
+ agent: command.agent,
2166
+ source: command.source,
2167
+ eventType: command.eventType,
2168
+ eventId: command.eventId,
2169
+ summary: command.summary,
2170
+ evidence: command.evidence,
2171
+ payloadPath: command.payloadPath,
2172
+ priority: command.priority,
2173
+ observationRevision: command.observationRevision,
2174
+ transition: command.transition,
2175
+ }, {
2176
+ ...(this.externalEventRoot ? { root: this.externalEventRoot } : {}),
2177
+ dispatchEnabled: command.wake !== false,
2178
+ });
2179
+ if (!record.shouldWake || command.wake === false) {
2180
+ return {
2181
+ ok: true,
2182
+ message: `updated external event ${record.source}/${record.eventId} without wake`,
2183
+ data: { event: record, receipt: null, wake: null },
2184
+ };
2185
+ }
2186
+ const dispatched = await this.dispatchExternalEvent(record);
2187
+ return {
2188
+ ok: true,
2189
+ message: `queued external event ${record.source}/${record.eventId} as ${dispatched.receipt.id}; ${dispatched.wake.message ?? "wake skipped"}`,
2190
+ data: dispatched,
2191
+ };
2192
+ }
2193
+ case "external.event.repair": {
2194
+ if (this.externalEventReconcileRunning)
2195
+ return { ok: false, error: "external event reconciliation is already active; repair made no changes" };
2196
+ this.externalEventReconcileRunning = true;
2197
+ try {
2198
+ try {
2199
+ const result = (0, router_1.repairExternalEventsFromManifest)(command.manifestPath, { root: this.externalEventRootPath() });
2200
+ return { ok: result.failed.length === 0, message: `external event repair applied=${result.applied.length} alreadyApplied=${result.alreadyApplied.length} failed=${result.failed.length} pending=${result.pending.length}`, data: result };
2201
+ }
2202
+ catch (error) {
2203
+ const message = (error instanceof Error ? error.message : /* v8 ignore next -- defensive: repair parser and filesystem dependencies throw Error instances @preserve */ String(error)).slice(0, 1_000);
2204
+ const result = { applied: [], alreadyApplied: [], failed: [{ identity: "<manifest>", error: message }], pending: [] };
2205
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "daemon", event: "daemon.external_event_repair", message: "rejected external event repair manifest", meta: { applied: 0, alreadyApplied: 0, failed: 1, pending: 0 } });
2206
+ return { ok: false, error: `external event repair rejected: ${message}`, data: result };
2207
+ }
2208
+ }
2209
+ finally {
2210
+ this.externalEventReconcileRunning = false;
2211
+ }
2212
+ }
2213
+ case "private.decisions": {
2214
+ const requestedLimit = Number.isInteger(command.limit) && command.limit && command.limit > 0 ? command.limit : 20;
2215
+ const limit = Math.min(requestedLimit, 1000);
2216
+ const ledgerPath = (0, private_runtime_1.privateTurnLedgerPath)(command.agent, { bundlesRoot: this.bundlesRoot });
2217
+ const ledgerExists = fs.existsSync(ledgerPath);
2218
+ let decisions;
2219
+ try {
2220
+ decisions = ledgerExists ? (0, private_runtime_1.readPrivateTurnLedger)(ledgerPath) : [];
2221
+ }
2222
+ catch {
2223
+ return {
2224
+ ok: false,
2225
+ error: `private-runtime decision ledger is malformed: ${ledgerPath}; repair or remove malformed JSONL rows before reading decisions`,
2226
+ };
2227
+ }
2228
+ const guidance = ledgerExists
2229
+ ? undefined
2230
+ : `No private-runtime decision ledger exists for ${command.agent}; run an explicit private-runtime trigger or check ${path.dirname(ledgerPath)}.`;
2231
+ const payload = (0, private_runtime_1.buildPrivateDecisionReadPayload)({
2232
+ agent: command.agent,
2233
+ ledgerPath,
2234
+ decisions,
2235
+ limit,
2236
+ ...(guidance ? { guidance } : {}),
2237
+ });
458
2238
  return {
459
2239
  ok: true,
460
- message: `woke inner dialog for ${command.agent}`,
2240
+ summary: (0, private_runtime_1.privateDecisionCountSummary)(payload.decisions.length),
2241
+ ...(guidance ? { message: guidance } : {}),
2242
+ data: payload,
461
2243
  };
2244
+ }
2245
+ case "inner.wake":
2246
+ return this.handlePrivateRuntimeWake(command);
2247
+ case "private.wake": {
2248
+ const scheduledHabit = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
2249
+ if (!scheduledHabit || !this.hasManagedPrivateRuntime(command.agent)) {
2250
+ return this.handlePrivateRuntimeWake(command);
2251
+ }
2252
+ const occurrenceRef = command.originRefs?.find((ref) => ref.kind === "habit-occurrence");
2253
+ const occurrenceId = typeof occurrenceRef?.id === "string" && occurrenceRef.id.trim().length > 0
2254
+ ? occurrenceRef.id.trim()
2255
+ : undefined;
2256
+ const resolution = this.resolveHabitDispatch({
2257
+ agent: command.agent,
2258
+ habitName: scheduledHabit.habitName,
2259
+ trigger: scheduledHabit.trigger,
2260
+ source: "private-wake",
2261
+ ...(occurrenceId ? { occurrenceId } : {}),
2262
+ });
2263
+ if (resolution.kind === "skipped") {
2264
+ this.emitHabitDispatchSkipped({
2265
+ agent: command.agent,
2266
+ habitName: scheduledHabit.habitName,
2267
+ trigger: scheduledHabit.trigger,
2268
+ resolution,
2269
+ });
2270
+ return this.skippedHabitDispatchResponse({
2271
+ agent: command.agent,
2272
+ habitName: scheduledHabit.habitName,
2273
+ skipReason: resolution.skipReason,
2274
+ });
2275
+ }
2276
+ this.emitHabitDispatchReady({
2277
+ agent: command.agent,
2278
+ habitName: scheduledHabit.habitName,
2279
+ trigger: scheduledHabit.trigger,
2280
+ resolution,
2281
+ });
2282
+ return this.handlePrivateRuntimeWake(command);
2283
+ }
462
2284
  case "chat.connect":
463
2285
  await this.processManager.startAgent(command.agent);
464
2286
  return {
@@ -466,6 +2288,12 @@ class OuroDaemon {
466
2288
  message: `connected to ${command.agent}`,
467
2289
  };
468
2290
  case "task.poke": {
2291
+ if (!isValidTaskPokeCommand(command)) {
2292
+ return {
2293
+ ok: false,
2294
+ error: "Invalid task.poke payload: expected non-empty string fields 'agent' and 'taskId'.",
2295
+ };
2296
+ }
469
2297
  const receipt = await this.router.send({
470
2298
  from: "ouro-poke",
471
2299
  to: command.agent,
@@ -474,39 +2302,253 @@ class OuroDaemon {
474
2302
  taskRef: command.taskId,
475
2303
  });
476
2304
  await this.scheduler.recordTaskRun?.(command.agent, command.taskId);
477
- this.processManager.sendToAgent?.(command.agent, { type: "poke", taskId: command.taskId });
2305
+ await this.handlePrivateRuntimeWake(this.buildTaskPokePrivateWakeCommand(command, receipt.id));
478
2306
  return {
479
2307
  ok: true,
480
2308
  message: `queued poke ${receipt.id}`,
481
2309
  data: receipt,
482
2310
  };
483
2311
  }
484
- case "mcp.list": {
485
- const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)();
486
- if (!mcpManager) {
487
- return { ok: true, data: [], message: "no MCP servers configured" };
488
- }
489
- return { ok: true, data: mcpManager.listAllTools() };
490
- }
491
- case "mcp.call": {
492
- const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)();
493
- if (!mcpCallManager) {
494
- return { ok: false, error: "no MCP servers configured" };
495
- }
2312
+ case "habit.scheduler-fire": {
2313
+ if (!this.schedulerFireVerifier || !this.schedulerFireConsumer)
2314
+ return { ok: false, error: "authenticated scheduler fire is unavailable" };
2315
+ let origin;
496
2316
  try {
497
- const parsedArgs = command.args ? JSON.parse(command.args) : {};
498
- const result = await mcpCallManager.callTool(command.server, command.tool, parsedArgs);
499
- return { ok: true, data: result };
2317
+ origin = this.schedulerFireVerifier(command);
2318
+ this.schedulerFireConsumer(origin);
500
2319
  }
501
2320
  catch (error) {
502
- /* v8 ignore next -- defensive: callTool errors are always Error instances @preserve */
503
2321
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
504
2322
  }
2323
+ const poke = { kind: "habit.poke", agent: command.agent, habitName: command.habitName, trigger: "cron", occurrenceId: origin.occurrenceId };
2324
+ this.authenticatedSchedulerPokes.set(poke, origin);
2325
+ try {
2326
+ return await this.handleCommand(poke);
2327
+ }
2328
+ finally {
2329
+ this.authenticatedSchedulerPokes.delete(poke);
2330
+ }
2331
+ }
2332
+ case "habit.poke": {
2333
+ if (!isValidHabitPokeCommand(command)) {
2334
+ return {
2335
+ ok: false,
2336
+ error: "Invalid habit.poke payload: expected non-empty string fields 'agent' and 'habitName'.",
2337
+ };
2338
+ }
2339
+ const trigger = command.trigger ?? "poke";
2340
+ if (!(0, flight_recorder_1.isHabitRunTrigger)(trigger)) {
2341
+ return { ok: false, error: `invalid habit trigger: ${String(trigger)}` };
2342
+ }
2343
+ const schedulerOrigin = this.authenticatedSchedulerPokes.get(command);
2344
+ if (command.agent === "sanctuary" && command.habitName === "sanctuary-health" && trigger === "cron" && !schedulerOrigin) {
2345
+ return { ok: false, error: "Sanctuary cron habit requires authenticated Supercronic provenance" };
2346
+ }
2347
+ if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
2348
+ return {
2349
+ ok: false,
2350
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
2351
+ };
2352
+ }
2353
+ const resolution = this.resolveHabitDispatch({
2354
+ agent: command.agent,
2355
+ habitName: command.habitName,
2356
+ trigger,
2357
+ source: "habit-poke",
2358
+ ...(command.occurrenceId ? { occurrenceId: command.occurrenceId } : {}),
2359
+ });
2360
+ if (resolution.kind === "skipped") {
2361
+ this.emitHabitDispatchSkipped({
2362
+ agent: command.agent,
2363
+ habitName: command.habitName,
2364
+ trigger,
2365
+ resolution,
2366
+ });
2367
+ return this.skippedHabitDispatchResponse({
2368
+ agent: command.agent,
2369
+ habitName: command.habitName,
2370
+ skipReason: resolution.skipReason,
2371
+ });
2372
+ }
2373
+ this.emitHabitDispatchReady({
2374
+ agent: command.agent,
2375
+ habitName: command.habitName,
2376
+ trigger,
2377
+ resolution,
2378
+ });
2379
+ if (this.nativeHabitRunner && this.nativeHabitMatch?.(command.agent, command.habitName)) {
2380
+ const occurrenceId = resolution.occurrenceId ?? `${trigger}:${command.agent}:${command.habitName}`;
2381
+ const claimKey = `${command.agent}:${command.habitName}`;
2382
+ if (this.nativeHabitClaims.has(claimKey)) {
2383
+ return { ok: true, message: `skipped overlapping native habit occurrence ${occurrenceId}` };
2384
+ }
2385
+ this.nativeHabitClaims.add(claimKey);
2386
+ const startedAt = new Date().toISOString();
2387
+ const runnerId = (0, node_crypto_1.randomUUID)();
2388
+ let nativeResult;
2389
+ try {
2390
+ nativeResult = await this.nativeHabitRunner({
2391
+ agent: command.agent,
2392
+ habitName: command.habitName,
2393
+ trigger,
2394
+ occurrenceId,
2395
+ runnerId,
2396
+ ...(schedulerOrigin ? { schedulerOrigin } : {}),
2397
+ }) ?? { ok: false, error: "native habit runner declined a matched habit" };
2398
+ }
2399
+ catch (error) {
2400
+ nativeResult = { ok: false, error: error instanceof Error ? error.message : String(error) };
2401
+ }
2402
+ const endedAt = new Date().toISOString();
2403
+ let completion;
2404
+ try {
2405
+ completion = (0, habit_session_1.completeHabitRun)({
2406
+ agentRoot: path.join(this.bundlesRoot, `${command.agent}.ouro`),
2407
+ habit: resolution.habit,
2408
+ runId: runnerId,
2409
+ trigger,
2410
+ startedAt,
2411
+ endedAt,
2412
+ operationId: occurrenceId,
2413
+ permissionEnvelope: { schemaVersion: 1, canMessageOutward: true, returnRoutes: [], deniedTools: [], warnings: [] },
2414
+ toolPolicy: { requestedTools: null, grantedTools: [], deniedTools: [], outwardMessagingAllowed: true },
2415
+ ...(nativeResult.ok ? {} : { errors: [nativeResult.error ?? nativeResult.message ?? "native habit failed"] }),
2416
+ });
2417
+ }
2418
+ finally {
2419
+ this.nativeHabitClaims.delete(claimKey);
2420
+ }
2421
+ if (!completion.receiptWritten || !completion.runtimeStateRecorded) {
2422
+ return { ok: false, error: "native habit completed but its durable receipt or cursor could not be recorded", data: nativeResult };
2423
+ }
2424
+ return nativeResult;
2425
+ }
2426
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
2427
+ return this.runNativeRsvpHabit(command, trigger, resolution.occurrenceId);
2428
+ }
2429
+ return this.handlePrivateRuntimeWake((0, habit_private_wake_1.buildHabitPrivateWakeCommand)({
2430
+ agent: command.agent,
2431
+ habitName: command.habitName,
2432
+ trigger,
2433
+ sourceRef: { kind: "daemon-command", id: "habit.poke" },
2434
+ occurrenceId: resolution.occurrenceId,
2435
+ }));
2436
+ }
2437
+ case "habit.probe": {
2438
+ if (!isValidHabitProbeCommand(command)) {
2439
+ return {
2440
+ ok: false,
2441
+ error: "Invalid habit.probe payload: expected non-empty agent/habitName and noSend=true.",
2442
+ };
2443
+ }
2444
+ const trigger = "manual";
2445
+ if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
2446
+ return {
2447
+ ok: false,
2448
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
2449
+ };
2450
+ }
2451
+ const resolution = this.resolveHabitDispatch({
2452
+ agent: command.agent,
2453
+ habitName: command.habitName,
2454
+ trigger,
2455
+ source: "habit-probe",
2456
+ });
2457
+ if (resolution.kind === "skipped") {
2458
+ this.emitHabitDispatchSkipped({
2459
+ agent: command.agent,
2460
+ habitName: command.habitName,
2461
+ trigger,
2462
+ resolution,
2463
+ });
2464
+ return {
2465
+ ok: true,
2466
+ message: `habit probe rejected by lifecycle: status=${resolution.habit.status}`,
2467
+ data: {
2468
+ noSend: true,
2469
+ status: resolution.habit.status,
2470
+ transportInvocationCount: 0,
2471
+ },
2472
+ };
2473
+ }
2474
+ this.emitHabitDispatchReady({
2475
+ agent: command.agent,
2476
+ habitName: command.habitName,
2477
+ trigger,
2478
+ resolution,
2479
+ });
2480
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
2481
+ return this.runNativeRsvpHabit(command, trigger, resolution.occurrenceId, true);
2482
+ }
2483
+ const wake = await this.handlePrivateRuntimeWake((0, habit_private_wake_1.buildHabitPrivateWakeCommand)({
2484
+ agent: command.agent,
2485
+ habitName: command.habitName,
2486
+ trigger,
2487
+ sourceRef: { kind: "daemon-command", id: "habit.probe" },
2488
+ occurrenceId: resolution.occurrenceId,
2489
+ noSend: true,
2490
+ }));
2491
+ if (!wake.ok)
2492
+ return wake;
2493
+ const denied = wake.data
2494
+ ?.decision?.executable === false;
2495
+ const error = denied
2496
+ ? "non-RSVP habit probe was not executed because private-runtime policy denied execution"
2497
+ : "non-RSVP habit probe completion is asynchronous; zero-transport evidence is unverified";
2498
+ return {
2499
+ ok: false,
2500
+ error,
2501
+ data: {
2502
+ ok: false,
2503
+ noSend: true,
2504
+ status: resolution.habit.status,
2505
+ transportInvocationCount: null,
2506
+ error,
2507
+ },
2508
+ };
2509
+ }
2510
+ case "await.poke": {
2511
+ return this.handlePrivateRuntimeWake(this.buildAwaitPrivateWakeCommand(command));
2512
+ }
2513
+ case "mcp.list": {
2514
+ return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
2515
+ const agentName = command.agent ?? "default";
2516
+ const owner = { agentName, agentRoot: (0, identity_1.getAgentRoot)(agentName) };
2517
+ (0, identity_1.setAgentName)(agentName);
2518
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)(owner);
2519
+ if (!mcpManager) {
2520
+ return { ok: true, data: [], message: "no MCP servers configured" };
2521
+ }
2522
+ return { ok: true, data: mcpManager.entries.map(({ server, tools, pluginId }) => ({ server, tools, pluginId })) };
2523
+ });
2524
+ }
2525
+ case "mcp.call": {
2526
+ return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
2527
+ const agentName = command.agent ?? "default";
2528
+ const owner = { agentName, agentRoot: (0, identity_1.getAgentRoot)(agentName) };
2529
+ (0, identity_1.setAgentName)(agentName);
2530
+ const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)(owner);
2531
+ if (!mcpCallManager) {
2532
+ return { ok: false, error: "no MCP servers configured" };
2533
+ }
2534
+ try {
2535
+ const parsedArgs = command.args ? JSON.parse(command.args) : {};
2536
+ const matches = (0, mcp_tools_1.mcpToolsAsDefinitions)(mcpCallManager).filter((definition) => definition.mcpBinding?.server === command.server && definition.mcpBinding.rawName === command.tool);
2537
+ const binding = matches.length === 1 ? matches[0].mcpBinding : undefined;
2538
+ if (!binding)
2539
+ return { ok: false, error: "MCP tool is unavailable or ambiguous" };
2540
+ const result = await mcpCallManager.manager.callTool(binding, parsedArgs, owner);
2541
+ return { ok: true, data: result };
2542
+ }
2543
+ catch (error) {
2544
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
2545
+ }
2546
+ });
505
2547
  }
506
2548
  case "hatch.start":
507
2549
  return {
508
2550
  ok: true,
509
- message: "hatch flow is stubbed in Gate 3 and completed in Gate 6",
2551
+ message: "hatch flow is stubbed; the interactive implementation lands in a later milestone",
510
2552
  };
511
2553
  default:
512
2554
  return {