@ouro.bot/cli 0.1.0-alpha.71 → 0.1.0-alpha.710

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 (505) hide show
  1. package/README.md +133 -23
  2. package/RepairGuide.ouro/agent.json +5 -0
  3. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  4. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  5. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  6. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  7. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  8. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  9. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  12. package/changelog.json +4510 -14
  13. package/dist/a2a/card.js +57 -0
  14. package/dist/a2a/client.js +180 -0
  15. package/dist/a2a/config.js +50 -0
  16. package/dist/a2a/delegation-stores.js +56 -0
  17. package/dist/a2a/did-resolution.js +93 -0
  18. package/dist/a2a/identity.js +170 -0
  19. package/dist/a2a/inbound-share.js +107 -0
  20. package/dist/a2a/mission-result-wire.js +196 -0
  21. package/dist/a2a/onboarding.js +115 -0
  22. package/dist/a2a/pin-store.js +132 -0
  23. package/dist/a2a/seen-ledger.js +120 -0
  24. package/dist/a2a/server.js +604 -0
  25. package/dist/a2a/task-store.js +69 -0
  26. package/dist/a2a/transport.js +45 -0
  27. package/dist/a2a/types.js +3 -0
  28. package/dist/arc/attention-types.js +8 -0
  29. package/dist/arc/cares.js +144 -0
  30. package/dist/arc/episodes.js +118 -0
  31. package/dist/arc/evolution.js +490 -0
  32. package/dist/arc/flight-recorder.js +928 -0
  33. package/dist/arc/intentions.js +134 -0
  34. package/dist/arc/json-store.js +117 -0
  35. package/dist/arc/obligations.js +348 -0
  36. package/dist/arc/packets.js +336 -0
  37. package/dist/arc/presence.js +185 -0
  38. package/dist/arc/task-lifecycle.js +57 -0
  39. package/dist/commerce/store.js +755 -0
  40. package/dist/commerce/types.js +3 -0
  41. package/dist/heart/active-work.js +867 -43
  42. package/dist/heart/agent-entry.js +190 -3
  43. package/dist/heart/attachments/image-normalize.js +194 -0
  44. package/dist/heart/attachments/materialize.js +97 -0
  45. package/dist/heart/attachments/originals.js +88 -0
  46. package/dist/heart/attachments/render.js +29 -0
  47. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  48. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  49. package/dist/heart/attachments/sources/index.js +16 -0
  50. package/dist/heart/attachments/store.js +103 -0
  51. package/dist/heart/attachments/types.js +93 -0
  52. package/dist/heart/auth/auth-flow.js +479 -0
  53. package/dist/heart/autonomy-budget.js +434 -0
  54. package/dist/heart/awaiting/await-alert.js +146 -0
  55. package/dist/heart/awaiting/await-expiry.js +108 -0
  56. package/dist/heart/awaiting/await-loader.js +91 -0
  57. package/dist/heart/awaiting/await-parser.js +141 -0
  58. package/dist/heart/awaiting/await-runtime-state.js +100 -0
  59. package/dist/heart/awaiting/await-scheduler.js +378 -0
  60. package/dist/heart/background-operations.js +281 -0
  61. package/dist/heart/bridges/manager.js +137 -17
  62. package/dist/heart/bridges/store.js +14 -2
  63. package/dist/heart/bundle-state.js +168 -0
  64. package/dist/heart/commitments.js +135 -0
  65. package/dist/heart/config-registry.js +331 -0
  66. package/dist/heart/config.js +119 -127
  67. package/dist/heart/context-loss-gauntlet.js +354 -0
  68. package/dist/heart/context-loss-sentinel.js +1155 -0
  69. package/dist/heart/core.js +1306 -278
  70. package/dist/heart/cross-chat-delivery.js +8 -22
  71. package/dist/heart/daemon/agent-config-check.js +451 -0
  72. package/dist/heart/daemon/agent-discovery.js +185 -3
  73. package/dist/heart/daemon/agent-service.js +523 -0
  74. package/dist/heart/daemon/agentic-repair.js +547 -0
  75. package/dist/heart/daemon/await-private-wake.js +59 -0
  76. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  77. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  78. package/dist/heart/daemon/cadence.js +180 -0
  79. package/dist/heart/daemon/cli-defaults.js +825 -0
  80. package/dist/heart/daemon/cli-desk.js +322 -0
  81. package/dist/heart/daemon/cli-exec.js +8194 -0
  82. package/dist/heart/daemon/cli-help.js +678 -0
  83. package/dist/heart/daemon/cli-parse.js +2476 -0
  84. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  85. package/dist/heart/daemon/cli-render.js +770 -0
  86. package/dist/heart/daemon/cli-types.js +8 -0
  87. package/dist/heart/daemon/connect-bay.js +323 -0
  88. package/dist/heart/daemon/daemon-cli.js +29 -1943
  89. package/dist/heart/daemon/daemon-entry.js +842 -10
  90. package/dist/heart/daemon/daemon-health.js +176 -0
  91. package/dist/heart/daemon/daemon-rollup.js +57 -0
  92. package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
  93. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  94. package/dist/heart/daemon/daemon.js +1289 -84
  95. package/dist/heart/daemon/dns-workflow.js +394 -0
  96. package/dist/heart/daemon/doctor-types.js +8 -0
  97. package/dist/heart/daemon/doctor.js +1126 -0
  98. package/dist/heart/daemon/habit-private-wake.js +56 -0
  99. package/dist/heart/daemon/health-monitor.js +142 -11
  100. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  101. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  102. package/dist/heart/daemon/http-health-probe.js +80 -0
  103. package/dist/heart/daemon/human-command-screens.js +234 -0
  104. package/dist/heart/daemon/human-readiness.js +114 -0
  105. package/dist/heart/daemon/inner-status.js +78 -0
  106. package/dist/heart/daemon/interactive-repair.js +394 -0
  107. package/dist/heart/daemon/launchd.js +37 -8
  108. package/dist/heart/daemon/log-tailer.js +79 -10
  109. package/dist/heart/daemon/logs-prune.js +110 -0
  110. package/dist/heart/daemon/mcp-canary.js +297 -0
  111. package/dist/heart/daemon/message-router.js +45 -5
  112. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  113. package/dist/heart/daemon/os-cron-deps.js +135 -0
  114. package/dist/heart/daemon/os-cron.js +22 -14
  115. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  116. package/dist/heart/daemon/ouro-entry.js +3 -1
  117. package/dist/heart/daemon/plugin-cli.js +432 -0
  118. package/dist/heart/daemon/process-manager.js +519 -40
  119. package/dist/heart/daemon/provider-discovery.js +137 -0
  120. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  121. package/dist/heart/daemon/pulse.js +511 -0
  122. package/dist/heart/daemon/readiness-repair.js +365 -0
  123. package/dist/heart/daemon/run-hooks.js +2 -0
  124. package/dist/heart/daemon/runtime-logging.js +41 -14
  125. package/dist/heart/daemon/runtime-metadata.js +2 -30
  126. package/dist/heart/daemon/safe-mode.js +161 -0
  127. package/dist/heart/daemon/sense-manager.js +670 -48
  128. package/dist/heart/daemon/session-id-resolver.js +131 -0
  129. package/dist/heart/daemon/skill-management-installer.js +1 -1
  130. package/dist/heart/daemon/socket-client.js +171 -12
  131. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  132. package/dist/heart/daemon/startup-tui.js +338 -0
  133. package/dist/heart/daemon/task-scheduler.js +117 -39
  134. package/dist/heart/daemon/terminal-ui.js +499 -0
  135. package/dist/heart/daemon/thoughts.js +255 -43
  136. package/dist/heart/daemon/up-progress.js +366 -0
  137. package/dist/heart/daemon/vault-items.js +56 -0
  138. package/dist/heart/delegation.js +1 -4
  139. package/dist/heart/external-events/router.js +121 -0
  140. package/dist/heart/habits/habit-migration.js +189 -0
  141. package/dist/heart/habits/habit-parser.js +214 -0
  142. package/dist/heart/habits/habit-runtime-state.js +114 -0
  143. package/dist/heart/habits/habit-scheduler.js +431 -0
  144. package/dist/heart/habits/habit-session-summary.js +318 -0
  145. package/dist/heart/habits/habit-session.js +617 -0
  146. package/dist/heart/{daemon → hatch}/hatch-flow.js +51 -60
  147. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  148. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  149. package/dist/heart/{daemon → hatch}/specialist-tools.js +53 -18
  150. package/dist/heart/identity.js +174 -59
  151. package/dist/heart/kept-notes.js +289 -0
  152. package/dist/heart/kicks.js +1 -1
  153. package/dist/heart/machine-identity.js +161 -0
  154. package/dist/heart/mail-import-discovery.js +353 -0
  155. package/dist/heart/mailbox/mailbox-http-hooks.js +96 -0
  156. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  157. package/dist/heart/mailbox/mailbox-http-routes.js +375 -0
  158. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  159. package/dist/heart/mailbox/mailbox-http-transport.js +116 -0
  160. package/dist/heart/mailbox/mailbox-http.js +99 -0
  161. package/dist/heart/mailbox/mailbox-read.js +37 -0
  162. package/dist/heart/mailbox/mailbox-types.js +27 -0
  163. package/dist/heart/mailbox/mailbox-view.js +197 -0
  164. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  165. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  166. package/dist/heart/mailbox/readers/mail.js +375 -0
  167. package/dist/heart/mailbox/readers/runtime-readers.js +815 -0
  168. package/dist/heart/mailbox/readers/sessions.js +232 -0
  169. package/dist/heart/mailbox/readers/shared.js +111 -0
  170. package/dist/heart/mcp/mcp-server.js +696 -0
  171. package/dist/heart/migrate-config.js +100 -0
  172. package/dist/heart/model-capabilities.js +11 -0
  173. package/dist/heart/orientation-frame.js +217 -0
  174. package/dist/heart/platform.js +81 -0
  175. package/dist/heart/primitives.js +1 -1
  176. package/dist/heart/private-runtime/decision-renderer.js +156 -0
  177. package/dist/heart/private-runtime/index.js +18 -0
  178. package/dist/heart/private-runtime/ledger.js +218 -0
  179. package/dist/heart/private-runtime/policy.js +214 -0
  180. package/dist/heart/private-runtime/types.js +2 -0
  181. package/dist/heart/progress-story.js +1 -1
  182. package/dist/heart/provider-attempt.js +134 -0
  183. package/dist/heart/provider-binding-resolver.js +273 -0
  184. package/dist/heart/provider-credentials.js +441 -0
  185. package/dist/heart/provider-failover.js +311 -0
  186. package/dist/heart/provider-models.js +81 -0
  187. package/dist/heart/provider-ping.js +262 -0
  188. package/dist/heart/provider-readiness-cache.js +119 -0
  189. package/dist/heart/provider-visibility.js +188 -0
  190. package/dist/heart/providers/anthropic-token.js +131 -0
  191. package/dist/heart/providers/anthropic.js +139 -52
  192. package/dist/heart/providers/azure.js +23 -11
  193. package/dist/heart/providers/error-classification.js +127 -0
  194. package/dist/heart/providers/github-copilot.js +34 -38
  195. package/dist/heart/providers/minimax-vlm.js +189 -0
  196. package/dist/heart/providers/minimax.js +26 -8
  197. package/dist/heart/providers/openai-codex-token.js +349 -0
  198. package/dist/heart/providers/openai-codex.js +55 -40
  199. package/dist/heart/run-ledger.js +247 -0
  200. package/dist/heart/runtime-capability-check.js +170 -0
  201. package/dist/heart/runtime-credentials.js +398 -0
  202. package/dist/heart/runtime-cwd.js +87 -0
  203. package/dist/heart/sense-truth.js +20 -4
  204. package/dist/heart/session-activity.js +90 -24
  205. package/dist/heart/session-events.js +1133 -0
  206. package/dist/heart/session-playback-cli-main.js +5 -0
  207. package/dist/heart/session-playback-cli.js +36 -0
  208. package/dist/heart/session-playback.js +231 -0
  209. package/dist/heart/session-stats-cli-main.js +5 -0
  210. package/dist/heart/session-stats.js +182 -0
  211. package/dist/heart/session-transcript.js +133 -0
  212. package/dist/heart/start-of-turn-packet.js +365 -0
  213. package/dist/heart/streaming.js +44 -27
  214. package/dist/heart/structured-output.js +196 -0
  215. package/dist/heart/sync-classification.js +176 -0
  216. package/dist/heart/sync.js +449 -0
  217. package/dist/heart/target-resolution.js +11 -7
  218. package/dist/heart/tempo.js +93 -0
  219. package/dist/heart/temporal-view.js +41 -0
  220. package/dist/heart/timeouts.js +101 -0
  221. package/dist/heart/tool-activity-callbacks.js +59 -0
  222. package/dist/heart/tool-description.js +155 -0
  223. package/dist/heart/tool-friction.js +55 -0
  224. package/dist/heart/tool-loop.js +200 -0
  225. package/dist/heart/turn-context.js +472 -0
  226. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  227. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  228. package/dist/heart/versioning/ouro-path-installer.js +426 -0
  229. package/dist/heart/versioning/ouro-version-manager.js +409 -0
  230. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  231. package/dist/heart/{daemon → versioning}/update-checker.js +6 -1
  232. package/dist/heart/versioning/update-hooks.js +154 -0
  233. package/dist/heart/work-card.js +380 -0
  234. package/dist/mailbox-ui/assets/index-Du_9G9WO.css +1 -0
  235. package/dist/mailbox-ui/assets/index-J8zDwHmE.js +1 -0
  236. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
  237. package/dist/mailbox-ui/index.html +16 -0
  238. package/dist/mailroom/attention.js +167 -0
  239. package/dist/mailroom/autonomy.js +209 -0
  240. package/dist/mailroom/blob-store.js +715 -0
  241. package/dist/mailroom/body-cache.js +61 -0
  242. package/dist/mailroom/core.js +788 -0
  243. package/dist/mailroom/entry.js +160 -0
  244. package/dist/mailroom/file-store.js +568 -0
  245. package/dist/mailroom/mbox-import.js +393 -0
  246. package/dist/mailroom/migration.js +164 -0
  247. package/dist/mailroom/outbound.js +380 -0
  248. package/dist/mailroom/policy.js +263 -0
  249. package/dist/mailroom/reader.js +233 -0
  250. package/dist/mailroom/search-cache.js +334 -0
  251. package/dist/mailroom/search-relevance.js +319 -0
  252. package/dist/mailroom/smtp-ingress.js +176 -0
  253. package/dist/mailroom/source-state.js +176 -0
  254. package/dist/mailroom/thread.js +109 -0
  255. package/dist/mailroom/travel-extract.js +89 -0
  256. package/dist/mind/bundle-manifest.js +24 -2
  257. package/dist/mind/context.js +250 -101
  258. package/dist/mind/desk-section.js +362 -0
  259. package/dist/mind/diary-integrity.js +60 -0
  260. package/dist/mind/{memory.js → diary.js} +68 -77
  261. package/dist/mind/embedding-provider.js +60 -0
  262. package/dist/mind/file-state.js +179 -0
  263. package/dist/mind/{associative-recall.js → note-search.js} +47 -58
  264. package/dist/mind/obligation-steering.js +221 -0
  265. package/dist/mind/pending.js +13 -8
  266. package/dist/mind/prompt-budget.js +380 -0
  267. package/dist/mind/prompt-refresh.js +3 -2
  268. package/dist/mind/prompt.js +1028 -169
  269. package/dist/mind/provenance-trust.js +26 -0
  270. package/dist/mind/record-paths.js +312 -0
  271. package/dist/mind/scrutiny.js +173 -0
  272. package/dist/nerves/cli-logging.js +7 -1
  273. package/dist/nerves/coverage/audit-rules.js +15 -6
  274. package/dist/nerves/coverage/audit.js +28 -2
  275. package/dist/nerves/coverage/cli.js +1 -1
  276. package/dist/nerves/coverage/contract.js +5 -5
  277. package/dist/nerves/coverage/file-completeness.js +139 -5
  278. package/dist/nerves/event-buffer.js +111 -0
  279. package/dist/nerves/index.js +234 -4
  280. package/dist/nerves/observation.js +20 -0
  281. package/dist/nerves/redact.js +79 -0
  282. package/dist/nerves/review/cli-main.js +5 -0
  283. package/dist/nerves/review/cli.js +156 -0
  284. package/dist/nerves/review/core.js +152 -0
  285. package/dist/nerves/runtime.js +5 -1
  286. package/dist/repertoire/ado-client.js +15 -56
  287. package/dist/repertoire/ado-semantic.js +16 -10
  288. package/dist/repertoire/api-client.js +97 -0
  289. package/dist/repertoire/bitwarden-store.js +1021 -0
  290. package/dist/repertoire/bundle-templates.js +71 -0
  291. package/dist/repertoire/bw-installer.js +180 -0
  292. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  293. package/dist/repertoire/coding/context-pack.js +331 -0
  294. package/dist/repertoire/coding/feedback.js +218 -30
  295. package/dist/repertoire/coding/index.js +15 -3
  296. package/dist/repertoire/coding/manager.js +166 -10
  297. package/dist/repertoire/coding/spawner.js +58 -11
  298. package/dist/repertoire/coding/tools.js +242 -14
  299. package/dist/repertoire/coding/workbench-client.js +272 -0
  300. package/dist/repertoire/coding/workbench-manager.js +346 -0
  301. package/dist/repertoire/commerce-errors.js +109 -0
  302. package/dist/repertoire/commerce-self-test.js +156 -0
  303. package/dist/repertoire/credential-access.js +178 -0
  304. package/dist/repertoire/desk/classifier.js +362 -0
  305. package/dist/repertoire/duffel-client.js +185 -0
  306. package/dist/repertoire/github-client.js +14 -55
  307. package/dist/repertoire/graph-client.js +11 -52
  308. package/dist/repertoire/guardrails.js +156 -27
  309. package/dist/repertoire/mcp-client.js +44 -3
  310. package/dist/repertoire/mcp-manager.js +259 -20
  311. package/dist/repertoire/mcp-tools.js +83 -0
  312. package/dist/repertoire/plugin-mcp.js +175 -0
  313. package/dist/repertoire/plugins.js +253 -0
  314. package/dist/repertoire/shell-sessions.js +133 -0
  315. package/dist/repertoire/skills.js +48 -4
  316. package/dist/repertoire/stripe-client.js +131 -0
  317. package/dist/repertoire/tool-results.js +29 -0
  318. package/dist/repertoire/tools-a2a.js +699 -0
  319. package/dist/repertoire/tools-attachments.js +317 -0
  320. package/dist/repertoire/tools-awaiting.js +372 -0
  321. package/dist/repertoire/tools-base.js +65 -1095
  322. package/dist/repertoire/tools-bluebubbles.js +2 -0
  323. package/dist/repertoire/tools-bridge.js +144 -0
  324. package/dist/repertoire/tools-bundle.js +993 -0
  325. package/dist/repertoire/tools-commerce.js +253 -0
  326. package/dist/repertoire/tools-config.js +186 -0
  327. package/dist/repertoire/tools-continuity.js +252 -0
  328. package/dist/repertoire/tools-credential.js +383 -0
  329. package/dist/repertoire/tools-evolution.js +527 -0
  330. package/dist/repertoire/tools-files.js +344 -0
  331. package/dist/repertoire/tools-flight.js +290 -0
  332. package/dist/repertoire/tools-flow.js +119 -0
  333. package/dist/repertoire/tools-github.js +3 -8
  334. package/dist/repertoire/tools-mail.js +1975 -0
  335. package/dist/repertoire/tools-notes.js +459 -0
  336. package/dist/repertoire/tools-obligations.js +182 -0
  337. package/dist/repertoire/tools-orientation.js +31 -0
  338. package/dist/repertoire/tools-record.js +482 -0
  339. package/dist/repertoire/tools-rsvp.js +139 -0
  340. package/dist/repertoire/tools-runtime.js +150 -0
  341. package/dist/repertoire/tools-session.js +881 -0
  342. package/dist/repertoire/tools-shell.js +120 -0
  343. package/dist/repertoire/tools-stripe.js +224 -0
  344. package/dist/repertoire/tools-surface.js +355 -0
  345. package/dist/repertoire/tools-teams.js +12 -39
  346. package/dist/repertoire/tools-travel.js +125 -0
  347. package/dist/repertoire/tools-trip.js +982 -0
  348. package/dist/repertoire/tools-user-profile.js +146 -0
  349. package/dist/repertoire/tools-vault.js +40 -0
  350. package/dist/repertoire/tools-voice.js +145 -0
  351. package/dist/repertoire/tools.js +250 -80
  352. package/dist/repertoire/travel-api-client.js +360 -0
  353. package/dist/repertoire/user-profile.js +131 -0
  354. package/dist/repertoire/vault-setup.js +246 -0
  355. package/dist/repertoire/vault-unlock.js +594 -0
  356. package/dist/rsvp/aisleplanner-client.js +354 -0
  357. package/dist/rsvp/cli.js +758 -0
  358. package/dist/rsvp/config.js +327 -0
  359. package/dist/rsvp/cutover.js +433 -0
  360. package/dist/rsvp/diagnostics.js +222 -0
  361. package/dist/rsvp/diff-renderer.js +161 -0
  362. package/dist/rsvp/habit-policy.js +85 -0
  363. package/dist/rsvp/habit-stage.js +98 -0
  364. package/dist/rsvp/incident-bundle.js +97 -0
  365. package/dist/rsvp/migration.js +204 -0
  366. package/dist/rsvp/native-habit-runner.js +321 -0
  367. package/dist/rsvp/outbound-state.js +268 -0
  368. package/dist/rsvp/query.js +118 -0
  369. package/dist/rsvp/replay.js +233 -0
  370. package/dist/rsvp/snapshot.js +232 -0
  371. package/dist/rsvp/spend-ledger.js +175 -0
  372. package/dist/scripts/claude-code-hook.js +41 -0
  373. package/dist/scripts/claude-code-stop-hook.js +47 -0
  374. package/dist/senses/a2a-entry.js +115 -0
  375. package/dist/senses/attention-queue.js +186 -0
  376. package/dist/senses/await-turn-message.js +58 -0
  377. package/dist/senses/bluebubbles/active-turns.js +216 -0
  378. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  379. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  380. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +226 -19
  381. package/dist/senses/bluebubbles/context-packet.js +101 -0
  382. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  383. package/dist/senses/bluebubbles/entry.js +77 -0
  384. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +20 -3
  385. package/dist/senses/bluebubbles/index.js +2881 -0
  386. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -71
  387. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +33 -12
  388. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +3 -3
  389. package/dist/senses/bluebubbles/outbound-state.js +304 -0
  390. package/dist/senses/bluebubbles/processed-log.js +133 -0
  391. package/dist/senses/bluebubbles/replay.js +284 -0
  392. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  393. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  394. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  395. package/dist/senses/cli/bracketed-paste.js +82 -0
  396. package/dist/senses/cli/image-paste.js +287 -0
  397. package/dist/senses/cli/image-ref-navigation.js +75 -0
  398. package/dist/senses/cli/ink-app.js +156 -0
  399. package/dist/senses/cli/inline-diff.js +64 -0
  400. package/dist/senses/cli/input-keys.js +174 -0
  401. package/dist/senses/cli/kill-ring.js +86 -0
  402. package/dist/senses/cli/message-list.js +51 -0
  403. package/dist/senses/cli/ouro-tui.js +607 -0
  404. package/dist/senses/cli/spinner-imperative.js +135 -0
  405. package/dist/senses/cli/spinner.js +101 -0
  406. package/dist/senses/cli/status-line.js +60 -0
  407. package/dist/senses/cli/streaming-markdown.js +526 -0
  408. package/dist/senses/cli/tool-display.js +85 -0
  409. package/dist/senses/cli/tool-render.js +85 -0
  410. package/dist/senses/cli/tui-store.js +240 -0
  411. package/dist/senses/cli/virtual-list.js +35 -0
  412. package/dist/senses/cli-entry.js +60 -8
  413. package/dist/senses/cli-layout.js +100 -0
  414. package/dist/senses/cli.js +521 -214
  415. package/dist/senses/commands.js +66 -3
  416. package/dist/senses/context-packet-ledger.js +245 -0
  417. package/dist/senses/context-packets.js +154 -0
  418. package/dist/senses/habit-turn-message.js +160 -0
  419. package/dist/senses/mail-entry.js +66 -0
  420. package/dist/senses/mail.js +395 -0
  421. package/dist/senses/pipeline.js +952 -178
  422. package/dist/senses/private-runtime-worker.js +739 -0
  423. package/dist/senses/private-runtime.js +1157 -0
  424. package/dist/senses/proactive-content-guard.js +51 -0
  425. package/dist/senses/shared-turn.js +416 -0
  426. package/dist/senses/surface-tool.js +109 -0
  427. package/dist/senses/teams-entry.js +60 -8
  428. package/dist/senses/teams.js +397 -112
  429. package/dist/senses/trust-gate.js +104 -9
  430. package/dist/senses/voice/audio-playback.js +237 -0
  431. package/dist/senses/voice/audio-routing.js +119 -0
  432. package/dist/senses/voice/elevenlabs.js +202 -0
  433. package/dist/senses/voice/floor-control.js +431 -0
  434. package/dist/senses/voice/floor-controller.js +115 -0
  435. package/dist/senses/voice/golden-path.js +116 -0
  436. package/dist/senses/voice/index.js +29 -0
  437. package/dist/senses/voice/meeting.js +113 -0
  438. package/dist/senses/voice/outbound.js +190 -0
  439. package/dist/senses/voice/phone.js +33 -0
  440. package/dist/senses/voice/playback.js +139 -0
  441. package/dist/senses/voice/realtime-eval.js +496 -0
  442. package/dist/senses/voice/realtime-trace.js +531 -0
  443. package/dist/senses/voice/transcript.js +70 -0
  444. package/dist/senses/voice/turn.js +191 -0
  445. package/dist/senses/voice/twilio-phone-runtime.js +807 -0
  446. package/dist/senses/voice/twilio-phone.js +5081 -0
  447. package/dist/senses/voice/types.js +2 -0
  448. package/dist/senses/voice/whisper.js +161 -0
  449. package/dist/senses/voice-entry.js +81 -0
  450. package/dist/senses/voice-realtime-eval-command.js +99 -0
  451. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  452. package/dist/senses/voice-twilio-entry.js +87 -0
  453. package/dist/trips/core.js +138 -0
  454. package/dist/trips/store.js +265 -0
  455. package/dist/util/frontmatter.js +69 -0
  456. package/package.json +57 -12
  457. package/skills/agent-commerce.md +113 -0
  458. package/skills/browser-navigation.md +117 -0
  459. package/skills/commerce-setup-guide.md +116 -0
  460. package/skills/commerce-setup.md +84 -0
  461. package/skills/configure-dev-tools.md +99 -0
  462. package/skills/travel-planning.md +138 -0
  463. package/dist/heart/daemon/auth-flow.js +0 -409
  464. package/dist/heart/daemon/ouro-path-installer.js +0 -178
  465. package/dist/heart/daemon/update-hooks.js +0 -138
  466. package/dist/heart/safe-workspace.js +0 -228
  467. package/dist/heart/session-recall.js +0 -116
  468. package/dist/mind/friends/channel.js +0 -84
  469. package/dist/mind/friends/group-context.js +0 -144
  470. package/dist/mind/friends/resolver.js +0 -84
  471. package/dist/mind/friends/store-file.js +0 -190
  472. package/dist/mind/friends/store.js +0 -4
  473. package/dist/mind/friends/tokens.js +0 -26
  474. package/dist/mind/friends/trust-explanation.js +0 -74
  475. package/dist/mind/friends/types.js +0 -29
  476. package/dist/repertoire/tasks/board.js +0 -134
  477. package/dist/repertoire/tasks/index.js +0 -224
  478. package/dist/repertoire/tasks/lifecycle.js +0 -80
  479. package/dist/repertoire/tasks/middleware.js +0 -65
  480. package/dist/repertoire/tasks/parser.js +0 -173
  481. package/dist/repertoire/tasks/scanner.js +0 -132
  482. package/dist/repertoire/tasks/transitions.js +0 -144
  483. package/dist/senses/bluebubbles-entry.js +0 -13
  484. package/dist/senses/bluebubbles.js +0 -1180
  485. package/dist/senses/debug-activity.js +0 -148
  486. package/dist/senses/inner-dialog-worker.js +0 -90
  487. package/dist/senses/inner-dialog.js +0 -480
  488. package/subagents/README.md +0 -7
  489. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  490. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  491. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  492. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  493. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  494. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  495. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  496. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  497. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  498. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  499. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  500. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  501. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  502. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  503. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  504. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  505. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -34,43 +34,424 @@ 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.killOrphanProcesses = killOrphanProcesses;
43
+ exports.writePidfile = writePidfile;
44
+ exports.handleAgentSenseTurn = handleAgentSenseTurn;
45
+ exports.handleAgentAskTurn = handleAgentAskTurn;
37
46
  const fs = __importStar(require("fs"));
38
47
  const net = __importStar(require("net"));
48
+ const os = __importStar(require("os"));
39
49
  const path = __importStar(require("path"));
40
50
  const identity_1 = require("../identity");
51
+ const agent_discovery_1 = require("./agent-discovery");
41
52
  const runtime_1 = require("../../nerves/runtime");
42
53
  const runtime_metadata_1 = require("./runtime-metadata");
43
54
  const runtime_mode_1 = require("./runtime-mode");
44
- const update_hooks_1 = require("./update-hooks");
55
+ const update_hooks_1 = require("../versioning/update-hooks");
45
56
  const bundle_meta_1 = require("./hooks/bundle-meta");
57
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
46
58
  const bundle_manifest_1 = require("../../mind/bundle-manifest");
47
- const update_checker_1 = require("./update-checker");
48
- const staged_restart_1 = require("./staged-restart");
59
+ const update_checker_1 = require("../versioning/update-checker");
49
60
  const child_process_1 = require("child_process");
50
61
  const pending_1 = require("../../mind/pending");
51
- const channel_1 = require("../../mind/friends/channel");
62
+ const agent_service_1 = require("./agent-service");
63
+ const friends_1 = require("@ouro.bot/friends");
52
64
  const mcp_manager_1 = require("../../repertoire/mcp-manager");
65
+ const mailbox_http_1 = require("../mailbox/mailbox-http");
66
+ const mailbox_types_1 = require("../mailbox/mailbox-types");
67
+ const mailbox_read_1 = require("../mailbox/mailbox-read");
68
+ const mailbox_view_1 = require("../mailbox/mailbox-view");
69
+ const provider_visibility_1 = require("../provider-visibility");
70
+ const private_runtime_1 = require("../private-runtime");
71
+ const socket_client_1 = require("./socket-client");
72
+ const flight_recorder_1 = require("../../arc/flight-recorder");
73
+ const await_private_wake_1 = require("./await-private-wake");
74
+ const habit_private_wake_1 = require("./habit-private-wake");
75
+ const habit_parser_1 = require("../habits/habit-parser");
76
+ const habit_runtime_state_1 = require("../habits/habit-runtime-state");
77
+ const router_1 = require("../external-events/router");
78
+ const habit_policy_1 = require("../../rsvp/habit-policy");
79
+ const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
80
+ /**
81
+ * Defense-in-depth: detect if we're running under vitest. The pidfile lives
82
+ * at a hardcoded path under the user's real ~/.ouro-cli/ — there's no DI
83
+ * seam to redirect it. So when a test creates a real OuroDaemon and calls
84
+ * start(), the daemon's killOrphanProcesses() reads the REAL pidfile,
85
+ * ps-verifies the PIDs, and SIGTERMs the production daemon. We saw this
86
+ * cause an outage on 2026-04-08 (alpha.265 daemon killed 93s after startup
87
+ * by a vitest test that called daemon.start()).
88
+ *
89
+ * Both killOrphanProcesses() and writePidfile() short-circuit under vitest
90
+ * to make the production pidfile sacred. Tests that need to verify these
91
+ * functions' behavior should use the extracted pure helpers
92
+ * (parseOrphanPidsFromPs, filterPidfilePidsToActualOrphans).
93
+ */
94
+ function isVitestProcess() {
95
+ /* v8 ignore next -- defensive: process and process.argv always exist in node @preserve */
96
+ if (typeof process === "undefined" || !Array.isArray(process.argv))
97
+ return false;
98
+ return process.argv.some((arg) => typeof arg === "string" && arg.includes("vitest"));
99
+ }
100
+ function messageFromHabitPokeError(error) {
101
+ if (error instanceof Error)
102
+ return error.message;
103
+ /* v8 ignore next -- defensive fallback for hostile/non-Error throws from filesystem or parsers @preserve */
104
+ return String(error);
105
+ }
106
+ /**
107
+ * Scan `ps -eo pid,ppid,command` output for daemon-owned entry points whose
108
+ * parent has died (PPID reparented to init/PID 1). Returns the list of PIDs
109
+ * that are safe to SIGTERM — true orphans, not children of live sibling
110
+ * daemons running from worktrees, test suites, or other users of the harness.
111
+ *
112
+ * Exported so unit tests can exercise the filter without shelling out.
113
+ */
114
+ function parseOrphanPidsFromPs(psOutput, selfPid) {
115
+ const orphans = [];
116
+ for (const line of psOutput.split("\n")) {
117
+ // Explicitly exclude MCP server processes — they share a harness entry
118
+ // point but are not daemon children and must never be killed.
119
+ if (line.includes("mcp-serve") || line.includes("mcp serve"))
120
+ continue;
121
+ // Match only daemon-owned JS entry points.
122
+ if (!line.includes("agent-entry.js")
123
+ && !line.includes("daemon-entry.js")
124
+ && !line.includes("bluebubbles/entry.js")
125
+ && !line.includes("mail-entry.js")
126
+ && !line.includes("teams-entry.js")
127
+ && !line.includes("a2a-entry.js"))
128
+ continue;
129
+ // Parse `<pid> <ppid> <command...>`. ps pads these with leading spaces.
130
+ // Regex guarantees both groups are \d+ so parseInt can't produce NaN.
131
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s/);
132
+ if (!match)
133
+ continue;
134
+ const pid = parseInt(match[1], 10);
135
+ const ppid = parseInt(match[2], 10);
136
+ if (pid === selfPid)
137
+ continue;
138
+ // CRITICAL: only kill processes whose parent is init (PID 1). A live
139
+ // PPID means the process belongs to another daemon instance (parallel
140
+ // test run, sibling worktree, another user of /tmp/ouroboros-daemon.sock).
141
+ // Killing those will crash unrelated harnesses — we saw this in B6
142
+ // when a vitest worker's daemon killed a production agent's children.
143
+ if (ppid !== 1)
144
+ continue;
145
+ orphans.push(pid);
146
+ }
147
+ return orphans;
148
+ }
149
+ /**
150
+ * Given a list of PIDs from the pidfile, return only those that are actual
151
+ * orphans (PPID reparented to init/PID 1). Protects against a polluted
152
+ * pidfile killing a PID that the OS has reassigned to an unrelated process.
153
+ *
154
+ * Implementation: shells out to `ps -p <csv> -o pid,ppid` for a batch lookup.
155
+ * Returns the empty list if ps fails — safer to skip cleanup than to
156
+ * wildcard-kill on a bad read.
157
+ *
158
+ * Exported for direct unit coverage.
159
+ */
160
+ function filterPidfilePidsToActualOrphans(candidatePids, psRunner = runPsCheck) {
161
+ if (candidatePids.length === 0)
162
+ return [];
163
+ const psOutput = psRunner(candidatePids);
164
+ if (psOutput === null)
165
+ return [];
166
+ const survivingOrphans = [];
167
+ // `ps -p x,y,z -o pid,ppid` emits a header line then one row per found PID.
168
+ // PIDs not found (already exited) are silently omitted — which is the
169
+ // correct behavior for us: we only want to kill live orphans.
170
+ for (const line of psOutput.split("\n")) {
171
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
172
+ if (!match)
173
+ continue;
174
+ const pid = parseInt(match[1], 10);
175
+ const ppid = parseInt(match[2], 10);
176
+ if (ppid !== 1)
177
+ continue;
178
+ if (!candidatePids.includes(pid))
179
+ continue;
180
+ survivingOrphans.push(pid);
181
+ }
182
+ return survivingOrphans;
183
+ }
184
+ function mergeUniqueOrphanPids(...sources) {
185
+ const merged = [];
186
+ const seen = new Set();
187
+ for (const source of sources) {
188
+ for (const pid of source) {
189
+ if (seen.has(pid))
190
+ continue;
191
+ seen.add(pid);
192
+ merged.push(pid);
193
+ }
194
+ }
195
+ return merged;
196
+ }
197
+ const ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS = 5_000;
198
+ const ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS = 50;
199
+ /* v8 ignore start -- process liveness probe; pure wait behavior covered via injected deps @preserve */
200
+ function defaultIsPidAlive(pid) {
201
+ try {
202
+ process.kill(pid, 0);
203
+ return true;
204
+ }
205
+ catch (error) {
206
+ return error.code === "EPERM";
207
+ }
208
+ }
209
+ /* v8 ignore stop */
210
+ /* v8 ignore start -- real timer wiring; wait behavior covered via injected sleep @preserve */
211
+ async function defaultSettleSleep(ms) {
212
+ await new Promise((resolve) => setTimeout(resolve, ms));
213
+ }
214
+ /* v8 ignore stop */
215
+ async function waitForOrphanProcessesToSettle(pids, deps = {}) {
216
+ if (pids.length === 0)
217
+ return [];
218
+ const isPidAlive = deps.isPidAlive ?? defaultIsPidAlive;
219
+ const now = deps.now ?? Date.now;
220
+ const sleep = deps.sleep ?? defaultSettleSleep;
221
+ const timeoutMs = deps.timeoutMs ?? ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS;
222
+ const pollIntervalMs = deps.pollIntervalMs ?? ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS;
223
+ const deadline = now() + timeoutMs;
224
+ let survivors = pids.filter(isPidAlive);
225
+ while (survivors.length > 0 && now() < deadline) {
226
+ await sleep(pollIntervalMs);
227
+ survivors = pids.filter(isPidAlive);
228
+ }
229
+ return survivors;
230
+ }
231
+ /* v8 ignore start -- shells out to ps; covered by filterPidfilePidsToActualOrphans unit tests via injected runner @preserve */
232
+ function runPsCheck(pids) {
233
+ try {
234
+ const csv = pids.join(",");
235
+ return (0, child_process_1.execSync)(`ps -p ${csv} -o pid=,ppid=`, { encoding: "utf-8", timeout: 5000 });
236
+ }
237
+ catch {
238
+ // ps returns non-zero when none of the requested PIDs exist. Treat as
239
+ // "no survivors" rather than an error.
240
+ return "";
241
+ }
242
+ }
243
+ /* v8 ignore stop */
244
+ /**
245
+ * Kill all ouro processes from the previous daemon instance using the pidfile.
246
+ * On startup, reads PIDs from ~/.ouro-cli/daemon.pids, kills them all, then
247
+ * deletes the file. The new daemon writes its own PIDs after spawning.
248
+ *
249
+ * Safety: pidfile contents are verified before being killed — each PID must
250
+ * be an actual orphan (PPID reparented to init/PID 1) via
251
+ * `filterPidfilePidsToActualOrphans`. Otherwise a polluted pidfile (written
252
+ * by a test, or a crashed daemon whose PIDs have since been reused by the
253
+ * OS) could SIGTERM unrelated processes.
254
+ *
255
+ * Falls back to ps-based scanning scoped to true orphans (PPID=1) if the
256
+ * pidfile doesn't exist (first run, previous daemon crashed before writing,
257
+ * manual cleanup). The scope is narrow on purpose — see parseOrphanPidsFromPs.
258
+ */
259
+ /* v8 ignore start -- process lifecycle: uses kill/ps, tested via deployment @preserve */
260
+ function isProductionDaemonSocketPath(socketPath) {
261
+ return socketPath === socket_client_1.DEFAULT_DAEMON_SOCKET_PATH;
262
+ }
263
+ function killOrphanProcesses(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
264
+ if (!isProductionDaemonSocketPath(socketPath)) {
265
+ (0, runtime_1.emitNervesEvent)({
266
+ level: "warn",
267
+ component: "daemon",
268
+ event: "daemon.orphan_cleanup_nonproduction_blocked",
269
+ message: "blocked orphan cleanup for non-production daemon socket",
270
+ meta: { socketPath, pidfilePath: PIDFILE_PATH },
271
+ });
272
+ return [];
273
+ }
274
+ if (isVitestProcess()) {
275
+ (0, runtime_1.emitNervesEvent)({
276
+ level: "warn",
277
+ component: "daemon",
278
+ event: "daemon.orphan_cleanup_test_blocked",
279
+ message: "blocked killOrphanProcesses from touching real pidfile under vitest",
280
+ meta: { pidfilePath: PIDFILE_PATH },
281
+ });
282
+ return [];
283
+ }
284
+ try {
285
+ let pidfileOrphans = [];
286
+ let scanOrphans = [];
287
+ // Primary: read pidfile from previous daemon
288
+ try {
289
+ const raw = fs.readFileSync(PIDFILE_PATH, "utf-8");
290
+ const candidates = raw.split("\n")
291
+ .map((s) => parseInt(s.trim(), 10))
292
+ .filter((n) => !isNaN(n) && n !== process.pid);
293
+ // Verify each candidate is an actual live orphan before killing. See
294
+ // docstring above for why this matters.
295
+ pidfileOrphans = filterPidfilePidsToActualOrphans(candidates);
296
+ fs.unlinkSync(PIDFILE_PATH);
297
+ }
298
+ catch {
299
+ // No pidfile — the ps scan below still covers true orphans.
300
+ }
301
+ // Always supplement the pidfile with the scoped ps scan. A stale or
302
+ // partial pidfile can otherwise kill one old daemon while leaving a
303
+ // sibling PPID=1 daemon alive without a socket.
304
+ try {
305
+ const result = (0, child_process_1.execSync)("ps -eo pid,ppid,command", { encoding: "utf-8", timeout: 5000 });
306
+ scanOrphans = parseOrphanPidsFromPs(result, process.pid);
307
+ }
308
+ catch { /* ps failed — best effort */ }
309
+ const pidsToKill = mergeUniqueOrphanPids(pidfileOrphans, scanOrphans);
310
+ if (pidsToKill.length > 0) {
311
+ for (const pid of pidsToKill) {
312
+ try {
313
+ process.kill(pid, "SIGTERM");
314
+ }
315
+ catch { /* already exited */ }
316
+ }
317
+ (0, runtime_1.emitNervesEvent)({
318
+ component: "daemon",
319
+ event: "daemon.orphan_cleanup",
320
+ message: `killed ${pidsToKill.length} orphaned ouro processes`,
321
+ meta: { pids: pidsToKill },
322
+ });
323
+ }
324
+ return pidsToKill;
325
+ }
326
+ catch (error) {
327
+ (0, runtime_1.emitNervesEvent)({
328
+ level: "warn",
329
+ component: "daemon",
330
+ event: "daemon.orphan_cleanup_error",
331
+ message: "failed to clean up orphaned ouro processes",
332
+ meta: { error: error instanceof Error ? error.message : String(error) },
333
+ });
334
+ return [];
335
+ }
336
+ }
337
+ /**
338
+ * Write all managed PIDs (daemon + children) to the pidfile.
339
+ * Called after all agents and senses are spawned.
340
+ */
341
+ function writePidfile(extraPids = [], socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
342
+ if (!isProductionDaemonSocketPath(socketPath)) {
343
+ (0, runtime_1.emitNervesEvent)({
344
+ level: "warn",
345
+ component: "daemon",
346
+ event: "daemon.write_pidfile_nonproduction_blocked",
347
+ message: "blocked production pidfile write for non-production daemon socket",
348
+ meta: { socketPath, pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
349
+ });
350
+ return;
351
+ }
352
+ if (isVitestProcess()) {
353
+ (0, runtime_1.emitNervesEvent)({
354
+ level: "warn",
355
+ component: "daemon",
356
+ event: "daemon.write_pidfile_test_blocked",
357
+ message: "blocked writePidfile from clobbering real pidfile under vitest",
358
+ meta: { pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
359
+ });
360
+ return;
361
+ }
362
+ try {
363
+ const pids = [process.pid, ...extraPids].filter(Boolean);
364
+ fs.mkdirSync(path.dirname(PIDFILE_PATH), { recursive: true });
365
+ fs.writeFileSync(PIDFILE_PATH, pids.join("\n") + "\n", "utf-8");
366
+ }
367
+ catch { /* best effort */ }
368
+ }
369
+ function readSocketIdentity(socketPath) {
370
+ try {
371
+ const stats = fs.lstatSync(socketPath);
372
+ return {
373
+ dev: stats.dev,
374
+ ino: stats.ino,
375
+ ctimeMs: stats.ctimeMs,
376
+ };
377
+ }
378
+ catch {
379
+ return null;
380
+ }
381
+ }
382
+ function sameSocketIdentity(left, right) {
383
+ if (!left || !right)
384
+ return false;
385
+ return left.dev === right.dev && left.ino === right.ino && left.ctimeMs === right.ctimeMs;
386
+ }
53
387
  function buildWorkerRows(snapshots) {
54
388
  return snapshots.map((snapshot) => ({
55
389
  agent: snapshot.name,
56
390
  worker: snapshot.channel,
391
+ autoStart: snapshot.autoStart ?? true,
57
392
  status: snapshot.status,
58
393
  pid: snapshot.pid,
59
394
  restartCount: snapshot.restartCount,
60
395
  startedAt: snapshot.startedAt,
396
+ lastExitCode: snapshot.lastExitCode ?? null,
397
+ lastSignal: snapshot.lastSignal ?? null,
398
+ errorReason: snapshot.errorReason ?? null,
399
+ fixHint: snapshot.fixHint ?? null,
61
400
  }));
62
401
  }
402
+ function unhealthySenseRows(senses) {
403
+ return senses.filter((row) => {
404
+ if (!row.enabled)
405
+ return false;
406
+ if (row.status === "disabled" || row.status === "not_attached")
407
+ return false;
408
+ if (row.status === "interactive" || row.status === "running")
409
+ return false;
410
+ return true;
411
+ });
412
+ }
413
+ function isParkedWorker(row) {
414
+ return row.autoStart === false && row.status === "stopped";
415
+ }
416
+ function unhealthyWorkerRows(workers) {
417
+ return workers.filter((row) => !isParkedWorker(row) && row.status !== "running");
418
+ }
419
+ function unhealthyHealthChecks(healthChecks) {
420
+ return healthChecks.filter((row) => row.status !== "ok");
421
+ }
422
+ function overviewHealth(workers, senses, healthChecks = []) {
423
+ if (unhealthyWorkerRows(workers).length > 0)
424
+ return "warn";
425
+ if (unhealthySenseRows(senses).length > 0)
426
+ return "warn";
427
+ if (unhealthyHealthChecks(healthChecks).length > 0)
428
+ return "warn";
429
+ return "ok";
430
+ }
63
431
  function formatStatusSummary(payload) {
64
- if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0) {
432
+ if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0 && (payload.healthChecks ?? []).length === 0) {
65
433
  return "no managed agents";
66
434
  }
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}`),
435
+ const degraded = [
436
+ ...unhealthyWorkerRows(payload.workers)
437
+ .map((row) => `worker:${row.agent}/${row.worker}:${row.status}`),
438
+ ...unhealthySenseRows(payload.senses)
439
+ .map((row) => `sense:${row.agent}/${row.sense}:${row.status}`),
440
+ ...(payload.healthChecks ?? [])
441
+ .filter((row) => row.status !== "ok")
442
+ .map((row) => `health-check:${row.name}:${row.status}`),
72
443
  ];
73
- const detail = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
444
+ const detail = degraded.length > 0 ? `\tdegraded=${degraded.join(",")}` : "";
445
+ if (!detail) {
446
+ const rows = [
447
+ ...payload.workers.map((row) => `${row.agent}/${row.worker}:${row.status}`),
448
+ ...payload.senses
449
+ .filter((row) => row.enabled)
450
+ .map((row) => `${row.agent}/${row.sense}:${row.status}`),
451
+ ];
452
+ const items = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
453
+ return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${items}`;
454
+ }
74
455
  return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${detail}`;
75
456
  }
76
457
  function parseIncomingCommand(raw) {
@@ -90,6 +471,85 @@ function parseIncomingCommand(raw) {
90
471
  }
91
472
  return parsed;
92
473
  }
474
+ function isValidSenseReviveCommand(command) {
475
+ return typeof command.agent === "string"
476
+ && typeof command.sense === "string"
477
+ && typeof command.reason === "string";
478
+ }
479
+ function isValidTaskPokeCommand(command) {
480
+ return typeof command.agent === "string"
481
+ && command.agent.trim().length > 0
482
+ && typeof command.taskId === "string"
483
+ && command.taskId.trim().length > 0;
484
+ }
485
+ function isValidHabitPokeCommand(command) {
486
+ return typeof command.agent === "string"
487
+ && command.agent.trim().length > 0
488
+ && typeof command.habitName === "string"
489
+ && command.habitName.trim().length > 0;
490
+ }
491
+ function taskIdFromTaskPokePrivateWakeCommand(command) {
492
+ if (command.kind !== "private.wake" || command.triggerSource !== "task-poke")
493
+ return null;
494
+ const taskRef = command.originRefs?.find((ref) => ref.kind === "task" && typeof ref.id === "string");
495
+ if (!taskRef || typeof taskRef.id !== "string")
496
+ return null;
497
+ const trimmed = taskRef.id.trim();
498
+ return trimmed.length > 0 ? trimmed : null;
499
+ }
500
+ /**
501
+ * Handle agent.senseTurn command: runs a full agent turn via the daemon process.
502
+ * Dynamic import lazy-loads shared-turn. Hot-reload works because ouro dev
503
+ * restarts the daemon process (fresh module cache).
504
+ */
505
+ async function handleAgentSenseTurn(command, runtime) {
506
+ try {
507
+ const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
508
+ setAgentName(command.agent);
509
+ const { runSenseTurn } = await Promise.resolve().then(() => __importStar(require("../../senses/shared-turn")));
510
+ const result = await runSenseTurn({
511
+ agentName: command.agent,
512
+ channel: command.channel,
513
+ sessionKey: command.sessionKey,
514
+ friendId: command.friendId,
515
+ userMessage: command.message,
516
+ ...(runtime?.socketPath ? { toolContext: { daemonSocketPath: runtime.socketPath } } : {}),
517
+ // Per-turn, per-agent runtime MCP injection (e.g. Workbench's ouro_workbench).
518
+ // Scoped to THIS turn only — never stored as module state, so a concurrent
519
+ // turn for a different agent cannot inherit these servers.
520
+ ...(command.runtimeMcp ? { runtimeMcpServers: command.runtimeMcp } : {}),
521
+ });
522
+ return {
523
+ ok: true,
524
+ message: result.response,
525
+ data: { ponderDeferred: result.ponderDeferred },
526
+ };
527
+ }
528
+ catch (error) {
529
+ /* v8 ignore next -- branch: String(error) fallback only for non-Error throws @preserve */
530
+ const errorMessage = error instanceof Error ? error.message : String(error);
531
+ return { ok: false, error: `sense turn failed: ${errorMessage}` };
532
+ }
533
+ }
534
+ async function handleAgentAskTurn(command, runtime) {
535
+ /* v8 ignore start -- ask command parameter defaults are legacy MCP compatibility; send_message shares the primary path @preserve */
536
+ const question = typeof command.question === "string" ? command.question : "";
537
+ if (!question.trim())
538
+ return { ok: false, error: "Missing required parameter: question" };
539
+ const channel = typeof command.channel === "string" && command.channel.trim() ? command.channel.trim() : "mcp";
540
+ const sessionKey = typeof command.sessionKey === "string" && command.sessionKey.trim()
541
+ ? command.sessionKey.trim()
542
+ : `agent-ask:${command.friendId}`;
543
+ /* v8 ignore stop */
544
+ return handleAgentSenseTurn({
545
+ kind: "agent.senseTurn",
546
+ agent: command.agent,
547
+ friendId: command.friendId,
548
+ channel,
549
+ sessionKey,
550
+ message: question,
551
+ }, runtime);
552
+ }
93
553
  class OuroDaemon {
94
554
  socketPath;
95
555
  processManager;
@@ -98,7 +558,16 @@ class OuroDaemon {
98
558
  router;
99
559
  senseManager;
100
560
  bundlesRoot;
561
+ mode;
101
562
  server = null;
563
+ mailboxServer = null;
564
+ socketIdentity = null;
565
+ senseAutostartTimer = null;
566
+ mailboxServerFactory;
567
+ privateRuntimePolicyDeps;
568
+ onStopCommandComplete;
569
+ externalEventRoot;
570
+ rsvpHabitRunner;
102
571
  constructor(options) {
103
572
  this.socketPath = options.socketPath;
104
573
  this.processManager = options.processManager;
@@ -107,6 +576,102 @@ class OuroDaemon {
107
576
  this.router = options.router;
108
577
  this.senseManager = options.senseManager ?? null;
109
578
  this.bundlesRoot = options.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
579
+ this.mode = options.mode ?? "production";
580
+ this.mailboxServerFactory = options.mailboxServerFactory ?? this.createDefaultMailboxServer.bind(this);
581
+ this.privateRuntimePolicyDeps = options.privateRuntimePolicyDeps ?? {};
582
+ this.onStopCommandComplete = options.onStopCommandComplete ?? null;
583
+ this.externalEventRoot = options.externalEventRoot ?? null;
584
+ this.rsvpHabitRunner = options.rsvpHabitRunner;
585
+ }
586
+ /* 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 */
587
+ createDefaultMailboxServer() {
588
+ return (0, mailbox_http_1.startMailboxHttpServer)({
589
+ host: "127.0.0.1",
590
+ port: mailbox_types_1.MAILBOX_DEFAULT_PORT,
591
+ bundlesRoot: this.bundlesRoot,
592
+ readMachineState: () => (0, mailbox_read_1.readMailboxMachineState)({ bundlesRoot: this.bundlesRoot }),
593
+ readMachineView: ({ machine }) => {
594
+ const overview = this.buildStatusPayload().overview;
595
+ return (0, mailbox_view_1.buildMailboxMachineView)({
596
+ machine,
597
+ daemon: {
598
+ status: overview.daemon,
599
+ health: overview.health,
600
+ mode: overview.mode,
601
+ socketPath: overview.socketPath,
602
+ mailboxUrl: overview.mailboxUrl,
603
+ entryPath: overview.entryPath,
604
+ workerCount: overview.workerCount,
605
+ senseCount: overview.senseCount,
606
+ },
607
+ });
608
+ },
609
+ readAgentState: (agentName) => (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot }),
610
+ readAgentView: (agentName) => {
611
+ const agent = (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot });
612
+ return (0, mailbox_view_1.buildMailboxAgentView)({
613
+ agent,
614
+ viewer: { kind: "human" },
615
+ });
616
+ },
617
+ });
618
+ }
619
+ /* v8 ignore stop */
620
+ buildStatusPayload() {
621
+ const snapshots = this.processManager.listAgentSnapshots();
622
+ const workers = buildWorkerRows(snapshots);
623
+ const senses = this.senseManager?.listSenseRows() ?? [];
624
+ const healthChecks = this.overlaySchedulerHealth(this.healthMonitor.getLastResults?.() ?? []);
625
+ const repoRoot = (0, identity_1.getRepoRoot)();
626
+ const sync = (0, agent_discovery_1.listBundleSyncRows)({ bundlesRoot: this.bundlesRoot });
627
+ const agents = (0, agent_discovery_1.listAllBundleAgents)({ bundlesRoot: this.bundlesRoot });
628
+ const providerAgents = (0, agent_discovery_1.listEnabledBundleAgents)({ bundlesRoot: this.bundlesRoot });
629
+ const providers = providerAgents.flatMap((agentName) => (0, provider_visibility_1.providerVisibilityStatusRows)((0, provider_visibility_1.buildAgentProviderVisibility)({
630
+ agentName,
631
+ agentRoot: path.join(this.bundlesRoot, `${agentName}.ouro`),
632
+ })));
633
+ const mailboxUrl = this.mailboxServer?.origin ?? "http://127.0.0.1:0";
634
+ return {
635
+ overview: {
636
+ daemon: "running",
637
+ health: overviewHealth(workers, senses, healthChecks),
638
+ socketPath: this.socketPath,
639
+ mailboxUrl,
640
+ outlookUrl: mailboxUrl,
641
+ ...(0, runtime_metadata_1.getRuntimeMetadata)(),
642
+ workerCount: workers.length,
643
+ senseCount: senses.length,
644
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
645
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
646
+ },
647
+ workers,
648
+ senses,
649
+ ...(healthChecks.length > 0 ? { healthChecks } : {}),
650
+ sync,
651
+ agents,
652
+ ...(providers.length > 0 ? { providers } : {}),
653
+ };
654
+ }
655
+ overlaySchedulerHealth(healthChecks) {
656
+ const degradedJobs = this.scheduler.listDegradedJobs?.() ?? [];
657
+ if (degradedJobs.length === 0)
658
+ return healthChecks;
659
+ const cronHealth = {
660
+ name: "cron-health",
661
+ status: "warn",
662
+ message: `cron jobs degraded; timer fallback active: ${degradedJobs
663
+ .map((job) => `${job.id} (${job.reason})`)
664
+ .join(", ")}`,
665
+ };
666
+ const next = healthChecks.map((check) => ({ ...check }));
667
+ const existingIndex = next.findIndex((check) => check.name === "cron-health");
668
+ if (existingIndex === -1) {
669
+ next.push(cronHealth);
670
+ }
671
+ else {
672
+ next[existingIndex] = cronHealth;
673
+ }
674
+ return next;
110
675
  }
111
676
  async start() {
112
677
  if (this.server)
@@ -117,65 +682,182 @@ class OuroDaemon {
117
682
  message: "starting daemon server",
118
683
  meta: { socketPath: this.socketPath },
119
684
  });
685
+ try {
686
+ await this.startInner();
687
+ }
688
+ catch (err) {
689
+ // Emit a paired terminating event (`_error`) so the nerves audit's
690
+ // start_end_pairing rule is satisfied when startup throws mid-sequence
691
+ // and `stop()` (which emits `server_end`) is never called.
692
+ (0, runtime_1.emitNervesEvent)({
693
+ level: "error",
694
+ component: "daemon",
695
+ event: "daemon.server_error",
696
+ message: "daemon start failed",
697
+ meta: {
698
+ error: err instanceof Error ? err.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(err),
699
+ },
700
+ });
701
+ throw err;
702
+ }
703
+ }
704
+ async startInner() {
120
705
  // Register update hooks and apply pending updates before starting agents
121
706
  (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
707
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
122
708
  const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
123
709
  await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
124
710
  // 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
- }
711
+ // Skip in dev mode — dev builds should not auto-update from npm
712
+ if (this.mode === "dev") {
713
+ (0, runtime_1.emitNervesEvent)({
714
+ component: "daemon",
715
+ event: "daemon.update_checker_skip",
716
+ message: "skipping update checker in dev mode",
717
+ meta: { reason: "dev mode" },
718
+ });
719
+ }
720
+ else {
721
+ (0, update_checker_1.startUpdateChecker)({
722
+ currentVersion,
723
+ deps: {
724
+ distTag: update_checker_1.CLI_UPDATE_DIST_TAG,
725
+ /* v8 ignore start -- integration: real HTTP fetch @preserve */
726
+ fetchRegistryJson: async () => {
727
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
728
+ return res.json();
150
729
  },
151
- gracefulShutdown: () => daemon.stop(),
152
- nodePath: process.execPath,
153
- bundlesRoot,
154
- });
155
- },
156
- /* v8 ignore stop */
157
- });
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();
730
+ /* v8 ignore stop */
731
+ },
732
+ });
733
+ }
734
+ // MCP connections are lazily initialized per-agent during senseTurn
735
+ // (daemon manages multiple agents; agent identity must be set before loading MCP config)
736
+ /* v8 ignore start -- orphan cleanup + pidfile: calls process management functions @preserve */
737
+ const killedOrphanPids = killOrphanProcesses(this.socketPath);
738
+ await waitForOrphanProcessesToSettle(killedOrphanPids);
739
+ /* v8 ignore stop */
740
+ await this.openCommandSocket();
741
+ this.triggerAutoStartAgents();
742
+ this.triggerAutoStartSensesWhenAgentsSettled();
743
+ // Write all managed PIDs to disk so the next daemon can clean up
744
+ /* v8 ignore start -- pidfile write: collects PIDs from process managers @preserve */
745
+ const agentPids = this.processManager.listAgentSnapshots().map((s) => s.pid).filter((p) => p !== null);
746
+ const sensePids = this.senseManager?.listManagedPids?.() ?? [];
747
+ writePidfile([...agentPids, ...sensePids], this.socketPath);
748
+ /* v8 ignore stop */
163
749
  this.scheduler.start?.();
164
750
  await this.scheduler.reconcile?.();
165
751
  await this.drainPendingBundleMessages();
166
752
  await this.drainPendingSenseMessages();
753
+ // startInner is only reachable when this.server is null (guarded in
754
+ // start()), and stop() nulls out this.mailboxServer alongside this.server,
755
+ // so mailboxServer is guaranteed unset here — no need for a guard.
756
+ try {
757
+ this.mailboxServer = await this.mailboxServerFactory();
758
+ }
759
+ catch (error) {
760
+ (0, runtime_1.emitNervesEvent)({
761
+ level: "warn",
762
+ component: "daemon",
763
+ event: "daemon.mailbox_start_failed",
764
+ message: `Mailbox server failed to start: ${String(error)}`,
765
+ meta: { port: mailbox_types_1.MAILBOX_DEFAULT_PORT },
766
+ });
767
+ }
768
+ }
769
+ triggerAutoStartAgents() {
770
+ if (this.processManager.triggerAutoStartAgents) {
771
+ this.processManager.triggerAutoStartAgents();
772
+ return;
773
+ }
774
+ void this.processManager.startAutoStartAgents().catch((error) => {
775
+ (0, runtime_1.emitNervesEvent)({
776
+ level: "error",
777
+ component: "daemon",
778
+ event: "daemon.agent_autostart_error",
779
+ message: "agent autostart failed after daemon socket opened",
780
+ meta: { error: error instanceof Error ? error.message : String(error) },
781
+ });
782
+ });
783
+ }
784
+ triggerAutoStartSenses() {
785
+ /* v8 ignore next -- defensive: callers already check senseManager before delegating here @preserve */
786
+ if (!this.senseManager)
787
+ return;
788
+ if (this.senseManager.triggerAutoStartSenses) {
789
+ this.senseManager.triggerAutoStartSenses();
790
+ return;
791
+ }
792
+ void this.senseManager.startAutoStartSenses().catch((error) => {
793
+ (0, runtime_1.emitNervesEvent)({
794
+ level: "error",
795
+ component: "daemon",
796
+ event: "daemon.sense_autostart_error",
797
+ message: "sense autostart failed after daemon socket opened",
798
+ meta: { error: error instanceof Error ? error.message : String(error) },
799
+ });
800
+ });
801
+ }
802
+ triggerAutoStartSensesWhenAgentsSettled() {
803
+ if (!this.senseManager)
804
+ return;
805
+ const waitingOnAgents = this.processManager.listAgentSnapshots()
806
+ .some((snapshot) => snapshot.status === "starting");
807
+ if (!waitingOnAgents) {
808
+ this.triggerAutoStartSenses();
809
+ return;
810
+ }
811
+ this.senseAutostartTimer = setTimeout(() => {
812
+ this.senseAutostartTimer = null;
813
+ this.triggerAutoStartSensesWhenAgentsSettled();
814
+ }, 250);
815
+ }
816
+ async openCommandSocket() {
167
817
  if (fs.existsSync(this.socketPath)) {
168
818
  fs.unlinkSync(this.socketPath);
169
819
  }
170
- this.server = net.createServer((connection) => {
820
+ // allowHalfOpen: true lets the server keep its writable side open after
821
+ // the client sends FIN. Without this, when a client calls `client.end()`
822
+ // after writing a command, node closes the server's writable side
823
+ // automatically — so a long-running response (like an agent.senseTurn
824
+ // LLM turn that takes 5+ seconds) never reaches the client. The
825
+ // socket-client fix in #303/#334 also removed client.end() on the
826
+ // sending side, but this option is defense in depth: even if a future
827
+ // caller half-closes, the server still writes its response correctly.
828
+ this.server = net.createServer({ allowHalfOpen: true }, (connection) => {
171
829
  let raw = "";
172
830
  let responded = false;
831
+ /* v8 ignore start — connection error handler requires real socket error @preserve */
832
+ connection.on("error", (err) => {
833
+ (0, runtime_1.emitNervesEvent)({
834
+ level: "warn",
835
+ component: "daemon",
836
+ event: "daemon.connection_error",
837
+ message: "socket connection error",
838
+ meta: { error: err.message, code: err.code ?? null },
839
+ });
840
+ });
841
+ /* v8 ignore stop */
173
842
  const flushResponse = async () => {
174
843
  if (responded)
175
844
  return;
176
845
  responded = true;
177
846
  const response = await this.handleRawPayload(raw);
178
- connection.end(response);
847
+ try {
848
+ connection.end(response);
849
+ /* v8 ignore start — EPIPE catch requires real socket disconnect @preserve */
850
+ }
851
+ catch (err) {
852
+ (0, runtime_1.emitNervesEvent)({
853
+ level: "warn",
854
+ component: "daemon",
855
+ event: "daemon.connection_end_error",
856
+ message: "failed to send response to client (EPIPE)",
857
+ meta: { error: err instanceof Error ? err.message : String(err) },
858
+ });
859
+ }
860
+ /* v8 ignore stop */
179
861
  };
180
862
  connection.on("data", (chunk) => {
181
863
  raw += chunk.toString("utf-8");
@@ -188,7 +870,23 @@ class OuroDaemon {
188
870
  const server = this.server;
189
871
  await new Promise((resolve, reject) => {
190
872
  server.once("error", reject);
191
- server.listen(this.socketPath, () => resolve());
873
+ server.listen(this.socketPath, () => {
874
+ // Replace the one-time error listener with a persistent one after successful listen
875
+ server.removeAllListeners("error");
876
+ this.socketIdentity = readSocketIdentity(this.socketPath);
877
+ /* v8 ignore start — server error after listen requires real socket race condition @preserve */
878
+ server.on("error", (err) => {
879
+ (0, runtime_1.emitNervesEvent)({
880
+ level: "error",
881
+ component: "daemon",
882
+ event: "daemon.server_error",
883
+ message: "daemon server error after listen",
884
+ meta: { error: err.message, code: err.code ?? null },
885
+ });
886
+ });
887
+ /* v8 ignore stop */
888
+ resolve();
889
+ });
192
890
  });
193
891
  }
194
892
  async drainPendingBundleMessages() {
@@ -240,7 +938,7 @@ class OuroDaemon {
240
938
  }
241
939
  }
242
940
  /** Drains per-sense pending dirs for always-on senses across all agents. */
243
- static ALWAYS_ON_SENSES = new Set((0, channel_1.getAlwaysOnSenseNames)());
941
+ static ALWAYS_ON_SENSES = new Set((0, friends_1.getAlwaysOnSenseNames)());
244
942
  async drainPendingSenseMessages() {
245
943
  if (!fs.existsSync(this.bundlesRoot))
246
944
  return;
@@ -327,26 +1025,87 @@ class OuroDaemon {
327
1025
  }
328
1026
  }
329
1027
  async stop() {
1028
+ // Must be named `_end` (not `_stop`) to satisfy the nerves audit's
1029
+ // start/end pairing rule — see src/nerves/coverage/audit-rules.ts.
1030
+ // This is the counterpart to `daemon.server_start` emitted at line 480.
330
1031
  (0, runtime_1.emitNervesEvent)({
331
1032
  component: "daemon",
332
- event: "daemon.server_stop",
1033
+ event: "daemon.server_end",
333
1034
  message: "stopping daemon server",
334
1035
  meta: { socketPath: this.socketPath },
335
1036
  });
336
1037
  (0, update_checker_1.stopUpdateChecker)();
337
1038
  (0, mcp_manager_1.shutdownSharedMcpManager)();
338
1039
  this.scheduler.stop?.();
1040
+ this.healthMonitor.stopPeriodicChecks?.();
1041
+ if (this.senseAutostartTimer) {
1042
+ clearTimeout(this.senseAutostartTimer);
1043
+ this.senseAutostartTimer = null;
1044
+ }
339
1045
  await this.processManager.stopAll();
340
1046
  await this.senseManager?.stopAll();
341
1047
  if (this.server) {
342
- await new Promise((resolve) => {
343
- this.server?.close(() => resolve());
344
- });
1048
+ // DO NOT `await` server.close() here. server.close() resolves only
1049
+ // after every open connection has closed. When stop() is invoked
1050
+ // from the daemon.stop command handler, the calling client's
1051
+ // connection is STILL open — its flushResponse() is currently
1052
+ // awaiting THIS function. Awaiting close() creates a deadlock:
1053
+ //
1054
+ // client → flushResponse → handleRawPayload → daemon.stop case
1055
+ // → stop() → await server.close() (waits for client's connection)
1056
+ // → client's connection waits for flushResponse to call
1057
+ // connection.end() → DEADLOCK
1058
+ //
1059
+ // Both processes sit in kevent forever. Verified live on
1060
+ // 2026-04-08: alpha.268 daemon hung at `daemon.server_end` log
1061
+ // line for 5+ minutes after a client sent daemon.stop, while the
1062
+ // client (alpha.270 ouro up) hung waiting for the response.
1063
+ //
1064
+ // This regressed when #303/#334/#339 stopped half-closing the
1065
+ // client socket and switched the server to allowHalfOpen: true.
1066
+ // Previously, the client called .end() after writing its command,
1067
+ // which (with allowHalfOpen: false) caused node to auto-tear-down
1068
+ // the server's writable side — incidentally unblocking
1069
+ // server.close() before the response was sent. The half-close
1070
+ // breakage masked this deadlock; the fix exposed it.
1071
+ //
1072
+ // Solution: fire close() and let it complete asynchronously. Once
1073
+ // stop() returns, the daemon.stop case returns its response,
1074
+ // flushResponse() calls connection.end(response), the connection
1075
+ // closes, and server.close()'s pending callback fires. The event
1076
+ // loop drains and the daemon exits cleanly.
1077
+ this.server.close();
345
1078
  this.server = null;
346
1079
  }
347
- if (fs.existsSync(this.socketPath)) {
1080
+ if (this.mailboxServer) {
1081
+ await this.mailboxServer.stop();
1082
+ this.mailboxServer = null;
1083
+ }
1084
+ const socketPathExists = fs.existsSync(this.socketPath);
1085
+ const currentSocketIdentity = socketPathExists ? readSocketIdentity(this.socketPath) : null;
1086
+ if (sameSocketIdentity(this.socketIdentity, currentSocketIdentity)) {
348
1087
  fs.unlinkSync(this.socketPath);
349
1088
  }
1089
+ else if (socketPathExists) {
1090
+ const expectedSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...this.socketIdentity };
1091
+ const actualSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...currentSocketIdentity };
1092
+ (0, runtime_1.emitNervesEvent)({
1093
+ level: "warn",
1094
+ component: "daemon",
1095
+ event: "daemon.socket_cleanup_skipped",
1096
+ message: "skipped daemon socket cleanup because the socket path no longer belongs to this daemon",
1097
+ meta: {
1098
+ socketPath: this.socketPath,
1099
+ expectedDev: expectedSocketIdentity.dev,
1100
+ expectedIno: expectedSocketIdentity.ino,
1101
+ expectedCtimeMs: expectedSocketIdentity.ctimeMs,
1102
+ actualDev: actualSocketIdentity.dev,
1103
+ actualIno: actualSocketIdentity.ino,
1104
+ actualCtimeMs: actualSocketIdentity.ctimeMs,
1105
+ },
1106
+ });
1107
+ }
1108
+ this.socketIdentity = null;
350
1109
  }
351
1110
  async handleRawPayload(raw) {
352
1111
  try {
@@ -368,32 +1127,256 @@ class OuroDaemon {
368
1127
  message: "handling daemon command",
369
1128
  meta: { kind: command.kind },
370
1129
  });
1130
+ try {
1131
+ return await this.handleCommandInner(command);
1132
+ /* v8 ignore start — command error catch tested in daemon-command-error.test; instanceof branches defensive @preserve */
1133
+ }
1134
+ catch (error) {
1135
+ (0, runtime_1.emitNervesEvent)({
1136
+ level: "error",
1137
+ component: "daemon",
1138
+ event: "daemon.command_error",
1139
+ message: "unexpected error handling daemon command",
1140
+ meta: {
1141
+ kind: command.kind,
1142
+ error: error instanceof Error ? error.message : String(error),
1143
+ stack: error instanceof Error ? error.stack ?? null : null,
1144
+ },
1145
+ });
1146
+ throw error;
1147
+ }
1148
+ /* v8 ignore stop */
1149
+ }
1150
+ hasManagedPrivateRuntime(agent) {
1151
+ return this.processManager.listAgentSnapshots().some((snapshot) => snapshot.name === agent && snapshot.channel === "private-runtime");
1152
+ }
1153
+ buildPrivateRuntimeWakeRequest(command) {
1154
+ if (command.kind === "inner.wake") {
1155
+ return {
1156
+ agent: command.agent,
1157
+ origin: "daemon.private.wake",
1158
+ reason: "legacy inner.wake compatibility alias",
1159
+ providerLane: "inner",
1160
+ triggerSource: "legacy",
1161
+ budgetClass: "interactive",
1162
+ originRefs: [{ kind: "daemon-command", id: "inner.wake" }],
1163
+ };
1164
+ }
1165
+ return {
1166
+ agent: command.agent,
1167
+ origin: "daemon.private.wake",
1168
+ reason: command.reason ?? "manual private-runtime wake",
1169
+ providerLane: "inner",
1170
+ triggerSource: command.triggerSource ?? "manual",
1171
+ budgetClass: command.budgetClass ?? "interactive",
1172
+ ...(command.idempotencyKey ? { idempotencyKey: command.idempotencyKey } : {}),
1173
+ originRefs: command.originRefs ?? [{ kind: "daemon-command", id: "private.wake" }],
1174
+ };
1175
+ }
1176
+ buildAwaitPrivateWakeCommand(command) {
1177
+ return (0, await_private_wake_1.buildAwaitPrivateWakeCommand)({
1178
+ agent: command.agent,
1179
+ awaitName: command.awaitName,
1180
+ triggerSource: "await-poke",
1181
+ });
1182
+ }
1183
+ buildTaskPokePrivateWakeCommand(command, receiptId) {
1184
+ return {
1185
+ kind: "private.wake",
1186
+ agent: command.agent,
1187
+ reason: `task poke ${command.taskId}`,
1188
+ triggerSource: "task-poke",
1189
+ budgetClass: "scheduled",
1190
+ idempotencyKey: `task-poke:${command.agent}:${command.taskId}:${receiptId}`,
1191
+ originRefs: [
1192
+ { kind: "task", id: command.taskId },
1193
+ { kind: "queue-receipt", id: receiptId },
1194
+ { kind: "daemon-command", id: "task.poke" },
1195
+ ],
1196
+ };
1197
+ }
1198
+ buildExternalEventPrivateWakeCommand(command, receiptId) {
1199
+ return {
1200
+ kind: "private.wake",
1201
+ agent: command.agent,
1202
+ reason: `external event ${command.source}/${command.eventType}`,
1203
+ triggerSource: "external-event",
1204
+ budgetClass: "interactive",
1205
+ idempotencyKey: `external-event:${command.agent}:${command.source}:${command.eventId}`,
1206
+ originRefs: [
1207
+ { kind: "external-event", id: command.eventId, source: command.source, eventType: command.eventType },
1208
+ { kind: "queue-receipt", id: receiptId },
1209
+ { kind: "daemon-command", id: "external.event.submit" },
1210
+ ],
1211
+ };
1212
+ }
1213
+ resolveHabitPokeOccurrenceId(command, trigger) {
1214
+ const agentRoot = path.join(this.bundlesRoot, `${command.agent}.ouro`);
1215
+ const habitPath = path.join(agentRoot, "habits", `${command.habitName}.md`);
1216
+ let parsedHabit = null;
1217
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
1218
+ if (!fs.existsSync(habitPath))
1219
+ return { skipReason: "RSVP habit file not found" };
1220
+ try {
1221
+ parsedHabit = (0, habit_runtime_state_1.applyHabitRuntimeState)(agentRoot, (0, habit_parser_1.parseHabitFile)(fs.readFileSync(habitPath, "utf-8"), habitPath));
1222
+ }
1223
+ catch (error) {
1224
+ return { skipReason: `RSVP habit metadata invalid: ${messageFromHabitPokeError(error)}` };
1225
+ }
1226
+ if (!parsedHabit.rsvp)
1227
+ return { skipReason: "RSVP habit metadata is required before private runtime wake" };
1228
+ }
1229
+ if (trigger === "poke" || trigger === "manual")
1230
+ return undefined;
1231
+ if (typeof command.occurrenceId === "string" && command.occurrenceId.trim().length > 0)
1232
+ return command.occurrenceId.trim();
1233
+ if (!fs.existsSync(habitPath))
1234
+ return { skipReason: "habit file not found" };
1235
+ const habit = parsedHabit ?? (0, habit_runtime_state_1.applyHabitRuntimeState)(agentRoot, (0, habit_parser_1.parseHabitFile)(fs.readFileSync(habitPath, "utf-8"), habitPath));
1236
+ if (habit.cadence === null)
1237
+ return { skipReason: "habit has no cadence" };
1238
+ const cadence = habit.cadence;
1239
+ if (habit.lastRun === null)
1240
+ return `${trigger}:first-run:${cadence}`;
1241
+ return `${trigger}:last-run:${habit.lastRun}:cadence:${cadence}`;
1242
+ }
1243
+ async runNativeRsvpHabit(command, trigger, occurrenceId) {
1244
+ const runner = this.rsvpHabitRunner ?? (async (input) => {
1245
+ const { runNativeRsvpHabit } = await Promise.resolve().then(() => __importStar(require("../../rsvp/native-habit-runner")));
1246
+ return runNativeRsvpHabit(input);
1247
+ });
1248
+ const result = await runner({
1249
+ agent: command.agent,
1250
+ bundlesRoot: this.bundlesRoot,
1251
+ habitName: command.habitName,
1252
+ trigger,
1253
+ ...(occurrenceId ? { occurrenceId } : {}),
1254
+ });
1255
+ return {
1256
+ ok: result.ok,
1257
+ message: result.message,
1258
+ data: result,
1259
+ };
1260
+ }
1261
+ buildPrivateRuntimeWorkerWakeMessage(command, decision) {
1262
+ const awaitName = (0, await_private_wake_1.awaitNameFromPrivateWakeCommand)(command);
1263
+ if (awaitName) {
1264
+ return {
1265
+ type: "await",
1266
+ awaitName,
1267
+ privateTurnDecision: decision,
1268
+ };
1269
+ }
1270
+ const taskId = taskIdFromTaskPokePrivateWakeCommand(command);
1271
+ if (taskId) {
1272
+ return {
1273
+ type: "poke",
1274
+ taskId,
1275
+ privateTurnDecision: decision,
1276
+ };
1277
+ }
1278
+ const habitMessage = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
1279
+ if (habitMessage) {
1280
+ return {
1281
+ type: "habit",
1282
+ habitName: habitMessage.habitName,
1283
+ trigger: habitMessage.trigger,
1284
+ privateTurnDecision: decision,
1285
+ };
1286
+ }
1287
+ return { type: "message", privateTurnDecision: decision };
1288
+ }
1289
+ queueExternalEventForPrivateRuntime(record) {
1290
+ 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);
1291
+ const originKey = `${record.source}:${record.eventId}`;
1292
+ const parsedReceivedAt = Date.parse(record.receivedAt);
1293
+ (0, pending_1.queuePendingMessage)(pendingDir, {
1294
+ from: "ouro-external-event",
1295
+ friendId: "ouro-external-event",
1296
+ channel: "external-event",
1297
+ key: originKey,
1298
+ content: (0, router_1.buildExternalEventMessage)(record),
1299
+ timestamp: Number.isFinite(parsedReceivedAt) ? parsedReceivedAt : Date.now(),
1300
+ delegatedFrom: {
1301
+ friendId: "ouro-external-event",
1302
+ channel: "external-event",
1303
+ key: originKey,
1304
+ },
1305
+ obligationStatus: "pending",
1306
+ mode: "relay",
1307
+ });
1308
+ (0, runtime_1.emitNervesEvent)({
1309
+ component: "daemon",
1310
+ event: "daemon.external_event_private_runtime_queued",
1311
+ message: "queued external event for private-runtime attention",
1312
+ meta: {
1313
+ agent: record.agent,
1314
+ source: record.source,
1315
+ eventType: record.eventType,
1316
+ eventId: record.eventId,
1317
+ pendingDir,
1318
+ },
1319
+ });
1320
+ }
1321
+ async handlePrivateRuntimeWake(command, beforeDispatch) {
1322
+ if (!this.hasManagedPrivateRuntime(command.agent)) {
1323
+ return {
1324
+ ok: false,
1325
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
1326
+ };
1327
+ }
1328
+ const decision = await (0, private_runtime_1.requestPrivateTurnDecision)(this.buildPrivateRuntimeWakeRequest(command), {
1329
+ bundlesRoot: this.bundlesRoot,
1330
+ ...this.privateRuntimePolicyDeps,
1331
+ });
1332
+ if (!decision.executable) {
1333
+ return {
1334
+ ok: true,
1335
+ message: `private-runtime wake denied for ${command.agent}: ${decision.deniedReason}`,
1336
+ data: { decision },
1337
+ };
1338
+ }
1339
+ await beforeDispatch?.(decision);
1340
+ await this.processManager.startAgent(command.agent);
1341
+ this.processManager.sendToAgent?.(command.agent, this.buildPrivateRuntimeWorkerWakeMessage(command, decision));
1342
+ return {
1343
+ ok: true,
1344
+ message: `woke private runtime for ${command.agent}`,
1345
+ data: { decision },
1346
+ };
1347
+ }
1348
+ async handleCommandInner(command) {
371
1349
  switch (command.kind) {
372
1350
  case "daemon.start":
373
1351
  await this.start();
374
1352
  return { ok: true, message: "daemon started" };
375
1353
  case "daemon.stop":
376
1354
  await this.stop();
1355
+ this.onStopCommandComplete?.();
377
1356
  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),
1357
+ case "daemon.restart": {
1358
+ // Restart is "stop + let launchctl respawn." Under launchctl's KeepAlive
1359
+ // policy the process is auto-restarted on exit, so daemon.restart and
1360
+ // daemon.stop differ only in intent + audit trail. In dev (no launchctl),
1361
+ // the process simply exits — same observable behavior as daemon.stop.
1362
+ (0, runtime_1.emitNervesEvent)({
1363
+ component: "daemon",
1364
+ event: "daemon.restart_requested",
1365
+ message: "daemon restart requested",
1366
+ meta: {
1367
+ reason: command.reason ?? null,
1368
+ requestedBy: command.requestedBy ?? null,
393
1369
  },
394
- workers,
395
- senses,
1370
+ });
1371
+ await this.stop();
1372
+ this.onStopCommandComplete?.();
1373
+ return {
1374
+ ok: true,
1375
+ message: "daemon restarting — launchctl will respawn",
396
1376
  };
1377
+ }
1378
+ case "daemon.status": {
1379
+ const data = this.buildStatusPayload();
397
1380
  return {
398
1381
  ok: true,
399
1382
  summary: formatStatusSummary(data),
@@ -412,15 +1395,112 @@ class OuroDaemon {
412
1395
  message: "log streaming available via ouro logs",
413
1396
  data: { logDir: "~/AgentBundles/<agent>.ouro/state/daemon/logs" },
414
1397
  };
1398
+ case "daemon.sense_revive": {
1399
+ if (!isValidSenseReviveCommand(command)) {
1400
+ return {
1401
+ ok: false,
1402
+ error: "Invalid daemon.sense_revive payload: expected string fields 'agent', 'sense', and 'reason'.",
1403
+ };
1404
+ }
1405
+ const revivedSenseRow = await this.senseManager?.reviveSense?.(command.agent, command.sense);
1406
+ if (revivedSenseRow) {
1407
+ return {
1408
+ ok: true,
1409
+ message: `revived ${command.agent}/${command.sense}`,
1410
+ data: revivedSenseRow,
1411
+ };
1412
+ }
1413
+ const managedSenseSnapshots = this.processManager.listAgentSnapshots()
1414
+ .filter((snapshot) => snapshot.name.startsWith(`${command.agent}:`));
1415
+ if (managedSenseSnapshots.length === 0) {
1416
+ return {
1417
+ ok: false,
1418
+ error: `No managed agent '${command.agent}' is registered with daemon-managed senses.`,
1419
+ };
1420
+ }
1421
+ const exactTargetName = `${command.agent}:${command.sense}`;
1422
+ const target = managedSenseSnapshots.find((snapshot) => snapshot.name === exactTargetName)
1423
+ ?? managedSenseSnapshots.find((snapshot) => snapshot.channel === command.sense);
1424
+ if (!target) {
1425
+ return {
1426
+ ok: false,
1427
+ error: `No managed sense '${command.sense}' is registered for agent '${command.agent}'.`,
1428
+ };
1429
+ }
1430
+ this.processManager.resetAgentFailureState(target.name);
1431
+ await this.processManager.startAgent(target.name);
1432
+ const freshSnapshot = this.processManager.listAgentSnapshots()
1433
+ .find((snapshot) => snapshot.name === target.name) ?? target;
1434
+ return {
1435
+ ok: true,
1436
+ message: `revived ${command.agent}/${command.sense}`,
1437
+ data: freshSnapshot,
1438
+ };
1439
+ }
415
1440
  case "agent.start":
416
1441
  await this.processManager.startAgent(command.agent);
417
1442
  return { ok: true, message: `started ${command.agent}` };
418
1443
  case "agent.stop":
419
1444
  await this.processManager.stopAgent?.(command.agent);
420
1445
  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}` };
1446
+ case "agent.restart": {
1447
+ if (!this.processManager.restartAgent) {
1448
+ return { ok: false, error: "Managed agent restart is not available." };
1449
+ }
1450
+ const managedSnapshot = this.processManager.listAgentSnapshots()
1451
+ .find((snapshot) => snapshot.name === command.agent);
1452
+ if (!managedSnapshot) {
1453
+ return { ok: false, error: `Unknown managed agent '${command.agent}'.` };
1454
+ }
1455
+ if (managedSnapshot.autoStart === false && managedSnapshot.status === "stopped") {
1456
+ return { ok: true, message: `restart skipped for parked non-autostart agent '${command.agent}'` };
1457
+ }
1458
+ const restartWork = command.skipConfigCheck === true
1459
+ ? this.processManager.restartAgent(command.agent, { skipConfigCheck: true })
1460
+ : this.processManager.restartAgent(command.agent);
1461
+ void restartWork.catch((error) => {
1462
+ (0, runtime_1.emitNervesEvent)({
1463
+ level: "error",
1464
+ component: "daemon",
1465
+ event: "daemon.agent_restart_request_error",
1466
+ message: "managed agent restart failed after request acknowledgement",
1467
+ meta: {
1468
+ agent: command.agent,
1469
+ error: error instanceof Error ? error.message : String(error),
1470
+ },
1471
+ });
1472
+ });
1473
+ return { ok: true, message: `restart requested for ${command.agent}` };
1474
+ }
1475
+ case "agent.ask":
1476
+ return handleAgentAskTurn(command, { socketPath: this.socketPath });
1477
+ case "agent.status":
1478
+ return (0, agent_service_1.handleAgentStatus)(command);
1479
+ case "agent.catchup":
1480
+ return (0, agent_service_1.handleAgentCatchup)(command);
1481
+ case "agent.delegate":
1482
+ return (0, agent_service_1.handleAgentDelegate)(command);
1483
+ case "agent.getContext":
1484
+ return (0, agent_service_1.handleAgentGetContext)(command);
1485
+ case "agent.searchFacts":
1486
+ return (0, agent_service_1.handleAgentSearchFacts)(command);
1487
+ case "agent.getTask":
1488
+ return (0, agent_service_1.handleAgentGetTask)(command);
1489
+ case "agent.checkScope":
1490
+ return (0, agent_service_1.handleAgentCheckScope)(command);
1491
+ case "agent.requestDecision":
1492
+ return (0, agent_service_1.handleAgentRequestDecision)(command);
1493
+ case "agent.checkGuidance":
1494
+ return (0, agent_service_1.handleAgentCheckGuidance)(command);
1495
+ case "agent.reportProgress":
1496
+ return (0, agent_service_1.handleAgentReportProgress)(command);
1497
+ case "agent.reportBlocker":
1498
+ return (0, agent_service_1.handleAgentReportBlocker)(command);
1499
+ case "agent.reportComplete":
1500
+ return (0, agent_service_1.handleAgentReportComplete)(command);
1501
+ case "agent.senseTurn":
1502
+ return handleAgentSenseTurn(command, { socketPath: this.socketPath });
1503
+ /* v8 ignore stop */
424
1504
  case "cron.list": {
425
1505
  const jobs = this.scheduler.listJobs();
426
1506
  const summary = jobs.length === 0
@@ -429,10 +1509,28 @@ class OuroDaemon {
429
1509
  return { ok: true, summary, data: jobs };
430
1510
  }
431
1511
  case "cron.trigger": {
1512
+ const habitResult = await this.scheduler.triggerHabitJob?.(command.jobId);
1513
+ if (habitResult?.ok) {
1514
+ return { ok: true, message: habitResult.message };
1515
+ }
432
1516
  const result = await this.scheduler.triggerJob(command.jobId);
433
1517
  return { ok: result.ok, message: result.message };
434
1518
  }
435
1519
  case "message.send": {
1520
+ // Pure queue-only delivery. We DO NOT wake the recipient — that was
1521
+ // the 2026-05-11 $50 bleed. The Claude Code post-tool-use hook
1522
+ // (cli-exec.ts) intentionally sends only message.send for tool-use
1523
+ // events to avoid waking the agent on every tool call. The hook's
1524
+ // intent was completely defeated by this handler calling
1525
+ // `sendToAgent({type: "message"})`, which woke the private runtime
1526
+ // worker on EVERY message.send anyway. ~30 message.send/min × the
1527
+ // 3-turn instinct-loop cap = ~90 turns/min sustained for hours.
1528
+ //
1529
+ // Callers that want immediate processing must send `private.wake`
1530
+ // explicitly after message.send. The CLI `ouro msg` does so
1531
+ // (lifecycle-boundary delivery should wake); the hook does so
1532
+ // only on session-start / stop, not per tool-use; the API does
1533
+ // not (notifications go to the queue).
436
1534
  const receipt = await this.router.send({
437
1535
  from: command.from,
438
1536
  to: command.to,
@@ -441,7 +1539,6 @@ class OuroDaemon {
441
1539
  sessionId: command.sessionId,
442
1540
  taskRef: command.taskRef,
443
1541
  });
444
- this.processManager.sendToAgent?.(command.to, { type: "message" });
445
1542
  return { ok: true, message: `queued message ${receipt.id}`, data: receipt };
446
1543
  }
447
1544
  case "message.poll": {
@@ -452,13 +1549,75 @@ class OuroDaemon {
452
1549
  data: messages,
453
1550
  };
454
1551
  }
455
- case "inner.wake":
456
- await this.processManager.startAgent(command.agent);
457
- this.processManager.sendToAgent?.(command.agent, { type: "message" });
1552
+ case "external.event.submit": {
1553
+ const record = (0, router_1.recordExternalEvent)({
1554
+ agent: command.agent,
1555
+ source: command.source,
1556
+ eventType: command.eventType,
1557
+ eventId: command.eventId,
1558
+ summary: command.summary,
1559
+ evidence: command.evidence,
1560
+ payloadPath: command.payloadPath,
1561
+ priority: command.priority,
1562
+ }, {
1563
+ ...(this.externalEventRoot ? { root: this.externalEventRoot } : {}),
1564
+ });
1565
+ const receipt = await this.router.send({
1566
+ from: "ouro-external-event",
1567
+ to: command.agent,
1568
+ content: (0, router_1.buildExternalEventMessage)(record),
1569
+ priority: record.priority,
1570
+ sessionId: command.sessionId,
1571
+ taskRef: command.taskRef ?? `${record.source}:${record.eventId}`,
1572
+ });
1573
+ let wake = null;
1574
+ if (command.wake !== false) {
1575
+ wake = await this.handlePrivateRuntimeWake(this.buildExternalEventPrivateWakeCommand(command, receipt.id), () => this.queueExternalEventForPrivateRuntime(record));
1576
+ }
1577
+ return {
1578
+ ok: true,
1579
+ message: command.wake === false
1580
+ ? `queued external event ${record.source}/${record.eventId} as ${receipt.id}`
1581
+ : `queued external event ${record.source}/${record.eventId} as ${receipt.id}; ${wake?.message ?? "wake skipped"}`,
1582
+ data: { event: record, receipt, wake },
1583
+ };
1584
+ }
1585
+ case "private.decisions": {
1586
+ const requestedLimit = Number.isInteger(command.limit) && command.limit && command.limit > 0 ? command.limit : 20;
1587
+ const limit = Math.min(requestedLimit, 1000);
1588
+ const ledgerPath = (0, private_runtime_1.privateTurnLedgerPath)(command.agent, { bundlesRoot: this.bundlesRoot });
1589
+ const ledgerExists = fs.existsSync(ledgerPath);
1590
+ let decisions;
1591
+ try {
1592
+ decisions = ledgerExists ? (0, private_runtime_1.readPrivateTurnLedger)(ledgerPath) : [];
1593
+ }
1594
+ catch {
1595
+ return {
1596
+ ok: false,
1597
+ error: `private-runtime decision ledger is malformed: ${ledgerPath}; repair or remove malformed JSONL rows before reading decisions`,
1598
+ };
1599
+ }
1600
+ const guidance = ledgerExists
1601
+ ? undefined
1602
+ : `No private-runtime decision ledger exists for ${command.agent}; run an explicit private-runtime trigger or check ${path.dirname(ledgerPath)}.`;
1603
+ const payload = (0, private_runtime_1.buildPrivateDecisionReadPayload)({
1604
+ agent: command.agent,
1605
+ ledgerPath,
1606
+ decisions,
1607
+ limit,
1608
+ ...(guidance ? { guidance } : {}),
1609
+ });
458
1610
  return {
459
1611
  ok: true,
460
- message: `woke inner dialog for ${command.agent}`,
1612
+ summary: (0, private_runtime_1.privateDecisionCountSummary)(payload.decisions.length),
1613
+ ...(guidance ? { message: guidance } : {}),
1614
+ data: payload,
461
1615
  };
1616
+ }
1617
+ case "inner.wake":
1618
+ return this.handlePrivateRuntimeWake(command);
1619
+ case "private.wake":
1620
+ return this.handlePrivateRuntimeWake(command);
462
1621
  case "chat.connect":
463
1622
  await this.processManager.startAgent(command.agent);
464
1623
  return {
@@ -466,6 +1625,12 @@ class OuroDaemon {
466
1625
  message: `connected to ${command.agent}`,
467
1626
  };
468
1627
  case "task.poke": {
1628
+ if (!isValidTaskPokeCommand(command)) {
1629
+ return {
1630
+ ok: false,
1631
+ error: "Invalid task.poke payload: expected non-empty string fields 'agent' and 'taskId'.",
1632
+ };
1633
+ }
469
1634
  const receipt = await this.router.send({
470
1635
  from: "ouro-poke",
471
1636
  to: command.agent,
@@ -474,14 +1639,53 @@ class OuroDaemon {
474
1639
  taskRef: command.taskId,
475
1640
  });
476
1641
  await this.scheduler.recordTaskRun?.(command.agent, command.taskId);
477
- this.processManager.sendToAgent?.(command.agent, { type: "poke", taskId: command.taskId });
1642
+ await this.handlePrivateRuntimeWake(this.buildTaskPokePrivateWakeCommand(command, receipt.id));
478
1643
  return {
479
1644
  ok: true,
480
1645
  message: `queued poke ${receipt.id}`,
481
1646
  data: receipt,
482
1647
  };
483
1648
  }
1649
+ case "habit.poke": {
1650
+ if (!isValidHabitPokeCommand(command)) {
1651
+ return {
1652
+ ok: false,
1653
+ error: "Invalid habit.poke payload: expected non-empty string fields 'agent' and 'habitName'.",
1654
+ };
1655
+ }
1656
+ const trigger = command.trigger ?? "poke";
1657
+ if (!(0, flight_recorder_1.isHabitRunTrigger)(trigger)) {
1658
+ return { ok: false, error: `invalid habit trigger: ${String(trigger)}` };
1659
+ }
1660
+ if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
1661
+ return {
1662
+ ok: false,
1663
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
1664
+ };
1665
+ }
1666
+ const occurrenceId = this.resolveHabitPokeOccurrenceId(command, trigger);
1667
+ if (typeof occurrenceId === "object") {
1668
+ return {
1669
+ ok: true,
1670
+ message: `skipped scheduled habit ${command.habitName} for ${command.agent}: ${occurrenceId.skipReason}`,
1671
+ };
1672
+ }
1673
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
1674
+ return this.runNativeRsvpHabit(command, trigger, occurrenceId);
1675
+ }
1676
+ return this.handlePrivateRuntimeWake((0, habit_private_wake_1.buildHabitPrivateWakeCommand)({
1677
+ agent: command.agent,
1678
+ habitName: command.habitName,
1679
+ trigger,
1680
+ sourceRef: { kind: "daemon-command", id: "habit.poke" },
1681
+ occurrenceId,
1682
+ }));
1683
+ }
1684
+ case "await.poke": {
1685
+ return this.handlePrivateRuntimeWake(this.buildAwaitPrivateWakeCommand(command));
1686
+ }
484
1687
  case "mcp.list": {
1688
+ (0, identity_1.setAgentName)(command.agent ?? "default");
485
1689
  const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)();
486
1690
  if (!mcpManager) {
487
1691
  return { ok: true, data: [], message: "no MCP servers configured" };
@@ -489,6 +1693,7 @@ class OuroDaemon {
489
1693
  return { ok: true, data: mcpManager.listAllTools() };
490
1694
  }
491
1695
  case "mcp.call": {
1696
+ (0, identity_1.setAgentName)(command.agent ?? "default");
492
1697
  const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)();
493
1698
  if (!mcpCallManager) {
494
1699
  return { ok: false, error: "no MCP servers configured" };
@@ -506,7 +1711,7 @@ class OuroDaemon {
506
1711
  case "hatch.start":
507
1712
  return {
508
1713
  ok: true,
509
- message: "hatch flow is stubbed in Gate 3 and completed in Gate 6",
1714
+ message: "hatch flow is stubbed; the interactive implementation lands in a later milestone",
510
1715
  };
511
1716
  default:
512
1717
  return {