@ouro.bot/cli 0.1.0-alpha.10 → 0.1.0-alpha.1000

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