@ouro.bot/cli 0.1.0-alpha.100 → 0.1.0-alpha.1001

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