@ouro.bot/cli 0.1.0-alpha.138 → 0.1.0-alpha.1380

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 (1038) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +194 -30
  3. package/RepairGuide.ouro/agent.json +5 -0
  4. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  5. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  6. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  7. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  8. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  9. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  12. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  13. package/assets/bluebubbles-host +264 -0
  14. package/assets/sanctuary-host-launcher.sh +16 -0
  15. package/changelog.json +8090 -34
  16. package/deploy/unraid/Dockerfile +85 -0
  17. package/deploy/unraid/INSTALL.md +64 -0
  18. package/deploy/unraid/README.txt +3032 -0
  19. package/deploy/unraid/audit-container-spec.sh +4 -0
  20. package/deploy/unraid/container-runtime.json +1 -0
  21. package/deploy/unraid/credit-gateway.md +95 -0
  22. package/deploy/unraid/docker-man-template-transaction.mjs +727 -0
  23. package/deploy/unraid/docker-man-template-xml.cjs +105 -0
  24. package/deploy/unraid/github_known_hosts +3 -0
  25. package/deploy/unraid/install.sh +274 -0
  26. package/deploy/unraid/migrate-sanctuary-bundle.mjs +63 -0
  27. package/deploy/unraid/ouro-events/bootstrap-spool.sh +92 -0
  28. package/deploy/unraid/ouro-events/emit-event.mjs +310 -0
  29. package/deploy/unraid/ouro-events/emit-usenet-event.sh +54 -0
  30. package/deploy/unraid/ouro-events/install-usenet-guard.sh +435 -0
  31. package/deploy/unraid/ouro-events/usenet-health.sh +176 -0
  32. package/deploy/unraid/ouro-sync-ssh +98 -0
  33. package/deploy/unraid/ouro-sync.sudoers +3 -0
  34. package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
  35. package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
  36. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  37. package/deploy/unraid/sanctuary-authority-installation.json +36 -0
  38. package/deploy/unraid/sanctuary-authority-service.sh +30 -0
  39. package/deploy/unraid/sanctuary-butler-upgrade.mjs +1523 -0
  40. package/deploy/unraid/sanctuary-deployment-target.mjs +710 -0
  41. package/deploy/unraid/sanctuary-replay-gate.mjs +2680 -0
  42. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  43. package/deploy/unraid/sanctuary-sync-cutover.sh +1039 -0
  44. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2088 -0
  45. package/deploy/unraid/sanctuary-unit16-run.sh +570 -0
  46. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  47. package/deploy/unraid/sanctuary.ouro/agent.json +73 -0
  48. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  49. package/deploy/unraid/sanctuary.ouro/awaiting/house-care-sweep.md +17 -0
  50. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  51. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  52. package/deploy/unraid/sanctuary.ouro/mcp/media-mcp.mjs +2533 -0
  53. package/deploy/unraid/sanctuary.ouro/product/PRODUCT.md +13 -0
  54. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
  55. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
  56. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +7 -0
  57. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +7 -0
  58. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +15 -0
  59. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +3 -0
  60. package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
  61. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +252 -0
  62. package/deploy/unraid/sanctuary.xml +30 -0
  63. package/dist/a2a/card.js +57 -0
  64. package/dist/a2a/client.js +290 -0
  65. package/dist/a2a/config.js +50 -0
  66. package/dist/a2a/delegated-command-grants.js +93 -0
  67. package/dist/a2a/delegated-command.js +197 -0
  68. package/dist/a2a/delegation-stores.js +56 -0
  69. package/dist/a2a/did-resolution.js +205 -0
  70. package/dist/a2a/escalation-grants.js +84 -0
  71. package/dist/a2a/escalation-wiring.js +60 -0
  72. package/dist/a2a/identity.js +258 -0
  73. package/dist/a2a/inbound-share.js +131 -0
  74. package/dist/a2a/mission-result-wire.js +265 -0
  75. package/dist/a2a/onboarding.js +133 -0
  76. package/dist/a2a/operator-trust.js +399 -0
  77. package/dist/a2a/outbox-client.js +59 -0
  78. package/dist/a2a/outbox-store.js +245 -0
  79. package/dist/a2a/outbox-wire.js +106 -0
  80. package/dist/a2a/pin-store.js +167 -0
  81. package/dist/a2a/refusals.js +53 -0
  82. package/dist/a2a/relay-client.js +106 -0
  83. package/dist/a2a/relay-config-vault.js +64 -0
  84. package/dist/a2a/relay-contacts.js +120 -0
  85. package/dist/a2a/relay-inbox.js +360 -0
  86. package/dist/a2a/relay-retirements.js +89 -0
  87. package/dist/a2a/replay-grant-holders.js +33 -0
  88. package/dist/a2a/replay-harness.js +188 -0
  89. package/dist/a2a/resolution-proof.js +53 -0
  90. package/dist/a2a/sealed-chat.js +114 -0
  91. package/dist/a2a/seen-ledger.js +214 -0
  92. package/dist/a2a/server.js +804 -0
  93. package/dist/a2a/task-store.js +69 -0
  94. package/dist/a2a/transport.js +100 -0
  95. package/dist/a2a/trust-commands.js +203 -0
  96. package/dist/a2a/trusted-files.js +185 -0
  97. package/dist/a2a/types.js +3 -0
  98. package/dist/arc/attention-types.js +8 -0
  99. package/dist/arc/cares.js +360 -0
  100. package/dist/arc/episodes.js +118 -0
  101. package/dist/arc/evolution.js +490 -0
  102. package/dist/arc/flight-recorder.js +1030 -0
  103. package/dist/arc/intentions.js +134 -0
  104. package/dist/arc/json-store.js +117 -0
  105. package/dist/arc/obligations.js +386 -0
  106. package/dist/arc/packets.js +336 -0
  107. package/dist/arc/presence.js +185 -0
  108. package/dist/arc/task-lifecycle.js +57 -0
  109. package/dist/commerce/store.js +755 -0
  110. package/dist/commerce/types.js +3 -0
  111. package/dist/eval/assertions/index.js +219 -0
  112. package/dist/eval/domain/case.js +115 -0
  113. package/dist/eval/domain/stats.js +19 -0
  114. package/dist/eval/guest-entry.js +16 -0
  115. package/dist/eval/readback/hedges.js +35 -0
  116. package/dist/eval/sandbox/docker.js +303 -0
  117. package/dist/eval/sandbox/guest.js +41 -0
  118. package/dist/eval/sandbox/projection.js +105 -0
  119. package/dist/eval/sandbox/readback.js +137 -0
  120. package/dist/eval/self-test.js +84 -0
  121. package/dist/eval/transport/provider-proxy.js +261 -0
  122. package/dist/eval/transport/synthetic-sanctuary.js +101 -0
  123. package/dist/eval/transport/telegram-turn.js +209 -0
  124. package/dist/gateway/keys.js +117 -0
  125. package/dist/gateway/server.js +429 -0
  126. package/dist/heart/active-work.js +421 -45
  127. package/dist/heart/agent-entry.js +255 -4
  128. package/dist/heart/approval-files.js +94 -0
  129. package/dist/heart/approval-store.js +957 -0
  130. package/dist/heart/atomic-file.js +115 -0
  131. package/dist/heart/attachments/downloaded-store.js +89 -0
  132. package/dist/heart/attachments/image-normalize.js +201 -0
  133. package/dist/heart/attachments/materialize.js +97 -0
  134. package/dist/heart/attachments/originals.js +102 -0
  135. package/dist/heart/attachments/render.js +29 -0
  136. package/dist/heart/attachments/sources/bluebubbles.js +155 -0
  137. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  138. package/dist/heart/attachments/sources/downloaded.js +76 -0
  139. package/dist/heart/attachments/sources/index.js +19 -0
  140. package/dist/heart/attachments/store.js +132 -0
  141. package/dist/heart/attachments/transcribe-audio.js +172 -0
  142. package/dist/heart/attachments/types.js +93 -0
  143. package/dist/heart/attachments/understand.js +195 -0
  144. package/dist/heart/auth/auth-flow.js +590 -0
  145. package/dist/heart/auth/github-device-login.js +104 -0
  146. package/dist/heart/autonomy-budget.js +478 -0
  147. package/dist/heart/awaiting/a2a-await-delivery.js +109 -0
  148. package/dist/heart/awaiting/await-alert.js +152 -0
  149. package/dist/heart/awaiting/await-expiry.js +143 -0
  150. package/dist/heart/awaiting/await-loader.js +91 -0
  151. package/dist/heart/awaiting/await-parser.js +152 -0
  152. package/dist/heart/awaiting/await-runtime-state.js +130 -0
  153. package/dist/heart/awaiting/await-scheduler.js +403 -0
  154. package/dist/heart/background-operations.js +281 -0
  155. package/dist/heart/bluebubbles-host-account.js +78 -0
  156. package/dist/heart/bridges/manager.js +137 -17
  157. package/dist/heart/bridges/store.js +14 -2
  158. package/dist/heart/bundle-state.js +168 -0
  159. package/dist/heart/chat-interaction.js +38 -0
  160. package/dist/heart/commitments.js +44 -14
  161. package/dist/heart/config-registry.js +340 -0
  162. package/dist/heart/config.js +195 -140
  163. package/dist/heart/context-loss-gauntlet.js +387 -0
  164. package/dist/heart/context-loss-sentinel.js +1200 -0
  165. package/dist/heart/core.js +2580 -639
  166. package/dist/heart/cross-chat-delivery.js +29 -22
  167. package/dist/heart/daemon/agent-config-check.js +494 -0
  168. package/dist/heart/daemon/agent-discovery.js +304 -3
  169. package/dist/heart/daemon/agent-home.js +409 -0
  170. package/dist/heart/daemon/agent-service.js +542 -0
  171. package/dist/heart/daemon/agentic-repair.js +548 -0
  172. package/dist/heart/daemon/await-private-wake.js +59 -0
  173. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  174. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  175. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  176. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  177. package/dist/heart/daemon/boot-sync-probe.js +223 -0
  178. package/dist/heart/daemon/cadence.js +180 -0
  179. package/dist/heart/daemon/cli-arg-redaction.js +26 -0
  180. package/dist/heart/daemon/cli-commands/a2a.js +26 -0
  181. package/dist/heart/daemon/cli-commands/cards.js +68 -0
  182. package/dist/heart/daemon/cli-commands/coding-tools.js +13 -0
  183. package/dist/heart/daemon/cli-commands/desk.js +34 -0
  184. package/dist/heart/daemon/cli-commands/dns.js +13 -0
  185. package/dist/heart/daemon/cli-commands/entry-points.js +164 -0
  186. package/dist/heart/daemon/cli-commands/failure-code.js +11 -0
  187. package/dist/heart/daemon/cli-commands/friends.js +18 -0
  188. package/dist/heart/daemon/cli-commands/habits.js +15 -0
  189. package/dist/heart/daemon/cli-commands/lifecycle.js +39 -0
  190. package/dist/heart/daemon/cli-commands/mail.js +12 -0
  191. package/dist/heart/daemon/cli-commands/mind.js +25 -0
  192. package/dist/heart/daemon/cli-commands/presence.js +28 -0
  193. package/dist/heart/daemon/cli-commands/providers.js +20 -0
  194. package/dist/heart/daemon/cli-commands/rsvp.js +20 -0
  195. package/dist/heart/daemon/cli-commands/shepherd.js +17 -0
  196. package/dist/heart/daemon/cli-commands/vault.js +23 -0
  197. package/dist/heart/daemon/cli-defaults.js +997 -0
  198. package/dist/heart/daemon/cli-desk.js +329 -0
  199. package/dist/heart/daemon/cli-exec.js +9667 -0
  200. package/dist/heart/daemon/cli-gate.js +198 -0
  201. package/dist/heart/daemon/cli-help.js +799 -0
  202. package/dist/heart/daemon/cli-manifest.js +112 -0
  203. package/dist/heart/daemon/cli-parse.js +3598 -0
  204. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  205. package/dist/heart/daemon/cli-render.js +823 -0
  206. package/dist/heart/daemon/cli-types.js +8 -0
  207. package/dist/heart/daemon/compile-cache.js +69 -0
  208. package/dist/heart/daemon/connect-bay.js +323 -0
  209. package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
  210. package/dist/heart/daemon/container-healthcheck.js +123 -0
  211. package/dist/heart/daemon/container-runtime.js +97 -0
  212. package/dist/heart/daemon/container-spec-auditor-main.js +187 -0
  213. package/dist/heart/daemon/container-spec-auditor.js +257 -0
  214. package/dist/heart/daemon/daemon-bootstrap-startup.js +115 -0
  215. package/dist/heart/daemon/daemon-cli.js +29 -2639
  216. package/dist/heart/daemon/daemon-entry.js +1113 -11
  217. package/dist/heart/daemon/daemon-health.js +186 -0
  218. package/dist/heart/daemon/daemon-rollup.js +57 -0
  219. package/dist/heart/daemon/daemon-runtime-sync.js +147 -13
  220. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  221. package/dist/heart/daemon/daemon.js +2070 -125
  222. package/dist/heart/daemon/desk-admin.js +420 -0
  223. package/dist/heart/daemon/dns-workflow.js +394 -0
  224. package/dist/heart/daemon/doctor-types.js +8 -0
  225. package/dist/heart/daemon/doctor.js +1890 -0
  226. package/dist/heart/daemon/freshness.js +345 -0
  227. package/dist/heart/daemon/habit-private-wake.js +61 -0
  228. package/dist/heart/daemon/health-monitor.js +209 -12
  229. package/dist/heart/daemon/home-filesystem.js +93 -0
  230. package/dist/heart/daemon/hook-post-tool-use.js +149 -0
  231. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  232. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  233. package/dist/heart/daemon/http-health-probe.js +80 -0
  234. package/dist/heart/daemon/human-command-screens.js +234 -0
  235. package/dist/heart/daemon/human-readiness.js +114 -0
  236. package/dist/heart/daemon/inner-status.js +78 -0
  237. package/dist/heart/daemon/interactive-repair.js +394 -0
  238. package/dist/heart/daemon/launchd.js +40 -8
  239. package/dist/heart/daemon/linux-service.js +382 -0
  240. package/dist/heart/daemon/log-tailer.js +79 -10
  241. package/dist/heart/daemon/logs-prune.js +132 -0
  242. package/dist/heart/daemon/mcp-canary.js +525 -0
  243. package/dist/heart/daemon/message-router.js +65 -5
  244. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  245. package/dist/heart/daemon/os-cron-deps.js +139 -0
  246. package/dist/heart/daemon/os-cron.js +45 -15
  247. package/dist/heart/daemon/ouro-bot-entry.js +8 -3
  248. package/dist/heart/daemon/ouro-cli-main.js +50 -0
  249. package/dist/heart/daemon/ouro-entry.js +43 -20
  250. package/dist/heart/daemon/plugin-cli.js +432 -0
  251. package/dist/heart/daemon/portable-git-install.js +265 -0
  252. package/dist/heart/daemon/portable-git.js +179 -0
  253. package/dist/heart/daemon/presence-daemon.js +265 -0
  254. package/dist/heart/daemon/presence-roster.js +259 -0
  255. package/dist/heart/daemon/presence.js +462 -0
  256. package/dist/heart/daemon/process-manager.js +763 -61
  257. package/dist/heart/daemon/provider-discovery.js +171 -0
  258. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  259. package/dist/heart/daemon/prunable-bundle.js +144 -0
  260. package/dist/heart/daemon/pulse.js +511 -0
  261. package/dist/heart/daemon/readiness-repair.js +365 -0
  262. package/dist/heart/daemon/run-hooks.js +2 -0
  263. package/dist/heart/daemon/runtime-logging.js +54 -14
  264. package/dist/heart/daemon/runtime-metadata.js +2 -30
  265. package/dist/heart/daemon/runtime-mode.js +13 -2
  266. package/dist/heart/daemon/runtime-replacement-handoff.js +207 -0
  267. package/dist/heart/daemon/safe-mode.js +161 -0
  268. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2659 -0
  269. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1832 -0
  270. package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
  271. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +956 -0
  272. package/dist/heart/daemon/sanctuary-authority-codec.js +86 -0
  273. package/dist/heart/daemon/sanctuary-authority-epoch.js +291 -0
  274. package/dist/heart/daemon/sanctuary-authority-installation.js +161 -0
  275. package/dist/heart/daemon/sanctuary-authority-ledger.js +241 -0
  276. package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +1356 -0
  277. package/dist/heart/daemon/sanctuary-authority-vault-migration.js +79 -0
  278. package/dist/heart/daemon/sanctuary-bundle-migration.js +974 -0
  279. package/dist/heart/daemon/sanctuary-host-authority.js +1008 -0
  280. package/dist/heart/daemon/sanctuary-host-detached-supervisor.js +493 -0
  281. package/dist/heart/daemon/sanctuary-host-executor.js +670 -0
  282. package/dist/heart/daemon/sanctuary-host-linux-kernel.js +334 -0
  283. package/dist/heart/daemon/sanctuary-host-supervisor-entry.js +210 -0
  284. package/dist/heart/daemon/sanctuary-host-supervisor.js +95 -0
  285. package/dist/heart/daemon/sanctuary-package-management.js +113 -0
  286. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
  287. package/dist/heart/daemon/sanctuary-scheduler-origin.js +132 -0
  288. package/dist/heart/daemon/sanctuary-telegram-authority-entry.js +481 -0
  289. package/dist/heart/daemon/sanctuary-telegram-authority-gateway.js +614 -0
  290. package/dist/heart/daemon/sanctuary-telegram-authority-service.js +763 -0
  291. package/dist/heart/daemon/sanctuary-telegram-test-driver-entry.js +97 -0
  292. package/dist/heart/daemon/sanctuary-telegram-test-driver.js +294 -0
  293. package/dist/heart/daemon/sense-manager.js +890 -58
  294. package/dist/heart/daemon/session-id-resolver.js +131 -0
  295. package/dist/heart/daemon/skill-management-installer.js +1 -1
  296. package/dist/heart/daemon/socket-client.js +180 -12
  297. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  298. package/dist/heart/daemon/startup-tui.js +339 -0
  299. package/dist/heart/daemon/supercronic-supervisor.js +282 -0
  300. package/dist/heart/daemon/task-scheduler.js +117 -39
  301. package/dist/heart/daemon/terminal-ui.js +503 -0
  302. package/dist/heart/daemon/thoughts.js +133 -49
  303. package/dist/heart/daemon/up-progress.js +366 -0
  304. package/dist/heart/daemon/vault-items.js +56 -0
  305. package/dist/heart/daemon/vault-outage.js +74 -0
  306. package/dist/heart/delegation.js +0 -3
  307. package/dist/heart/external-events/router.js +1556 -0
  308. package/dist/heart/failure-reports.js +398 -0
  309. package/dist/heart/file-lock.js +109 -0
  310. package/dist/heart/frontend-approval-runtime.js +506 -0
  311. package/dist/heart/frontend-journal.js +215 -0
  312. package/dist/heart/frontend-session-service.js +330 -0
  313. package/dist/heart/frontend-socket-client.js +173 -0
  314. package/dist/heart/frontend-socket.js +434 -0
  315. package/dist/heart/frontend-turn-errors.js +20 -0
  316. package/dist/heart/habits/habit-cancel.js +810 -0
  317. package/dist/heart/habits/habit-lifecycle.js +1324 -0
  318. package/dist/heart/habits/habit-migration.js +194 -0
  319. package/dist/heart/habits/habit-parser.js +278 -0
  320. package/dist/heart/habits/habit-runtime-state.js +93 -0
  321. package/dist/heart/habits/habit-scheduler.js +667 -0
  322. package/dist/heart/habits/habit-session-summary.js +318 -0
  323. package/dist/heart/habits/habit-session.js +636 -0
  324. package/dist/heart/{daemon → hatch}/hatch-flow.js +68 -62
  325. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  326. package/dist/heart/{daemon → hatch}/specialist-prompt.js +10 -6
  327. package/dist/heart/hatch/specialist-tools.js +395 -0
  328. package/dist/heart/identity.js +363 -60
  329. package/dist/heart/kept-notes.js +289 -0
  330. package/dist/heart/machine-identity.js +175 -0
  331. package/dist/heart/mail-import-discovery.js +356 -0
  332. package/dist/heart/mailbox/mailbox-http-hooks.js +99 -0
  333. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  334. package/dist/heart/mailbox/mailbox-http-routes.js +406 -0
  335. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  336. package/dist/heart/mailbox/mailbox-http-transport.js +272 -0
  337. package/dist/heart/mailbox/mailbox-http.js +99 -0
  338. package/dist/heart/mailbox/mailbox-read.js +41 -0
  339. package/dist/heart/mailbox/mailbox-supervision.js +131 -0
  340. package/dist/heart/mailbox/mailbox-types.js +27 -0
  341. package/dist/heart/mailbox/mailbox-view.js +197 -0
  342. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  343. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  344. package/dist/heart/mailbox/readers/mail.js +375 -0
  345. package/dist/heart/mailbox/readers/runtime-readers.js +823 -0
  346. package/dist/heart/mailbox/readers/sessions.js +231 -0
  347. package/dist/heart/mailbox/readers/shared.js +111 -0
  348. package/dist/heart/mcp/mcp-server.js +872 -0
  349. package/dist/heart/migrate-config.js +100 -0
  350. package/dist/heart/model-capabilities.js +98 -16
  351. package/dist/heart/model-limits.js +49 -0
  352. package/dist/heart/optional-packages.js +77 -0
  353. package/dist/heart/orientation-frame.js +393 -0
  354. package/dist/heart/platform.js +81 -0
  355. package/dist/heart/primitives.js +1 -1
  356. package/dist/heart/private-runtime/decision-renderer.js +158 -0
  357. package/dist/heart/private-runtime/index.js +18 -0
  358. package/dist/heart/private-runtime/ledger.js +212 -0
  359. package/dist/heart/private-runtime/policy.js +295 -0
  360. package/dist/heart/private-runtime/types.js +2 -0
  361. package/dist/heart/progress-story.js +1 -1
  362. package/dist/heart/provider-attempt.js +137 -0
  363. package/dist/heart/provider-binding-resolver.js +273 -0
  364. package/dist/heart/provider-credentials.js +449 -0
  365. package/dist/heart/provider-failover.js +260 -37
  366. package/dist/heart/provider-fallback.js +228 -0
  367. package/dist/heart/provider-models.js +96 -0
  368. package/dist/heart/provider-ping-child.js +125 -0
  369. package/dist/heart/provider-ping-entry.js +8 -0
  370. package/dist/heart/provider-ping.js +217 -78
  371. package/dist/heart/provider-readiness-cache.js +119 -0
  372. package/dist/heart/provider-visibility.js +188 -0
  373. package/dist/heart/providers/account-pool.js +717 -0
  374. package/dist/heart/providers/anthropic-token.js +15 -47
  375. package/dist/heart/providers/anthropic.js +259 -80
  376. package/dist/heart/providers/azure.js +19 -31
  377. package/dist/heart/providers/error-classification.js +129 -0
  378. package/dist/heart/providers/github-copilot.js +131 -36
  379. package/dist/heart/providers/minimax-vlm.js +189 -0
  380. package/dist/heart/providers/minimax.js +19 -27
  381. package/dist/heart/providers/openai-codex-token.js +349 -0
  382. package/dist/heart/providers/openai-codex.js +46 -57
  383. package/dist/heart/providers/openai-compatible.js +177 -0
  384. package/dist/heart/quota/fleet-readings.js +222 -0
  385. package/dist/heart/quota/tranche.js +59 -0
  386. package/dist/heart/reach-channel.js +85 -0
  387. package/dist/heart/reply-style.js +52 -0
  388. package/dist/heart/run-ledger.js +247 -0
  389. package/dist/heart/runtime-capability-check.js +170 -0
  390. package/dist/heart/runtime-credentials.js +647 -0
  391. package/dist/heart/runtime-cwd.js +87 -0
  392. package/dist/heart/sense-truth.js +26 -4
  393. package/dist/heart/session-activity.js +89 -23
  394. package/dist/heart/session-events.js +1600 -0
  395. package/dist/heart/session-playback-cli-main.js +10 -0
  396. package/dist/heart/session-playback-cli.js +36 -0
  397. package/dist/heart/session-playback.js +231 -0
  398. package/dist/heart/session-redaction-repair-cli-main.js +34 -0
  399. package/dist/heart/session-redaction-repair.js +552 -0
  400. package/dist/heart/session-stats-cli-main.js +10 -0
  401. package/dist/heart/session-stats.js +183 -0
  402. package/dist/heart/session-transcript.js +133 -0
  403. package/dist/heart/shelf-claims.js +124 -0
  404. package/dist/heart/shepherd/custody-types.js +2 -0
  405. package/dist/heart/shepherd/mandates.js +352 -0
  406. package/dist/heart/shepherd/operation-commands.js +19 -0
  407. package/dist/heart/shepherd/operations.js +139 -0
  408. package/dist/heart/shepherd/supervision.js +114 -0
  409. package/dist/heart/shepherd/types.js +2 -0
  410. package/dist/heart/shepherd-config.js +113 -0
  411. package/dist/heart/source-grounding.js +313 -0
  412. package/dist/heart/sqlite.js +18 -0
  413. package/dist/heart/start-of-turn-packet.js +372 -0
  414. package/dist/heart/steward-policy.js +656 -0
  415. package/dist/heart/streaming.js +620 -192
  416. package/dist/heart/structured-output.js +196 -0
  417. package/dist/heart/sync-classification.js +176 -0
  418. package/dist/heart/sync-health.js +152 -0
  419. package/dist/heart/sync-lock.js +431 -0
  420. package/dist/heart/sync.js +1579 -0
  421. package/dist/heart/target-resolution.js +11 -7
  422. package/dist/heart/tempo.js +93 -0
  423. package/dist/heart/temporal-view.js +41 -0
  424. package/dist/heart/timeouts.js +101 -0
  425. package/dist/heart/tool-activity-callbacks.js +59 -0
  426. package/dist/heart/tool-approval.js +382 -0
  427. package/dist/heart/tool-description.js +155 -0
  428. package/dist/heart/tool-friction.js +55 -0
  429. package/dist/heart/tool-images.js +42 -0
  430. package/dist/heart/tool-loop.js +10 -2
  431. package/dist/heart/tool-output-budget.js +41 -0
  432. package/dist/heart/turn-context.js +503 -0
  433. package/dist/heart/turn-execution-lease.js +78 -0
  434. package/dist/heart/versioning/host-self-update.js +118 -0
  435. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  436. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +3 -2
  437. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  438. package/dist/heart/versioning/ouro-recovery-launcher.js +98 -0
  439. package/dist/heart/versioning/ouro-version-manager.js +432 -0
  440. package/dist/heart/versioning/release-sources.js +185 -0
  441. package/dist/heart/versioning/self-update-defaults.js +424 -0
  442. package/dist/heart/versioning/self-update.js +257 -0
  443. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  444. package/dist/heart/{daemon → versioning}/update-checker.js +12 -35
  445. package/dist/heart/versioning/update-hooks.js +160 -0
  446. package/dist/heart/versioning/update-state.js +134 -0
  447. package/dist/heart/versioning/updater-launchd.js +150 -0
  448. package/dist/heart/versioning/version-intent.js +114 -0
  449. package/dist/heart/work-card.js +380 -0
  450. package/dist/mailbox-ui/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  451. package/dist/mailbox-ui/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  452. package/dist/mailbox-ui/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  453. package/dist/mailbox-ui/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  454. package/dist/mailbox-ui/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  455. package/dist/mailbox-ui/assets/index-CmMXMK-O.js +1 -0
  456. package/dist/mailbox-ui/assets/index-DrBzo6CV.css +1 -0
  457. package/dist/mailbox-ui/assets/vendor-C-KA_woR.js +65 -0
  458. package/dist/mailbox-ui/index.html +18 -0
  459. package/dist/mailroom/attention.js +167 -0
  460. package/dist/mailroom/autonomy.js +209 -0
  461. package/dist/mailroom/azure-sdk.js +27 -0
  462. package/dist/mailroom/blob-store.js +974 -0
  463. package/dist/mailroom/body-cache.js +61 -0
  464. package/dist/mailroom/cache-sync-cli.js +58 -0
  465. package/dist/mailroom/core.js +805 -0
  466. package/dist/mailroom/entry.js +169 -0
  467. package/dist/mailroom/file-store.js +568 -0
  468. package/dist/mailroom/hosted-cache-sync.js +384 -0
  469. package/dist/mailroom/mbox-import.js +393 -0
  470. package/dist/mailroom/migration.js +164 -0
  471. package/dist/mailroom/outbound.js +380 -0
  472. package/dist/mailroom/policy.js +263 -0
  473. package/dist/mailroom/reader.js +291 -0
  474. package/dist/mailroom/search-cache.js +513 -0
  475. package/dist/mailroom/search-relevance.js +319 -0
  476. package/dist/mailroom/smtp-ingress.js +176 -0
  477. package/dist/mailroom/source-state.js +176 -0
  478. package/dist/mailroom/sweep-orphans-cli.js +34 -0
  479. package/dist/mailroom/thread.js +109 -0
  480. package/dist/mailroom/travel-extract.js +89 -0
  481. package/dist/mind/bundle-manifest.js +25 -4
  482. package/dist/mind/context.js +322 -197
  483. package/dist/mind/desk-section.js +342 -0
  484. package/dist/mind/diary-integrity.js +60 -0
  485. package/dist/mind/diary.js +31 -53
  486. package/dist/mind/embedding-provider.js +60 -0
  487. package/dist/mind/file-state.js +179 -0
  488. package/dist/mind/friend-link-codes.js +209 -0
  489. package/dist/mind/friend-merge.js +336 -0
  490. package/dist/mind/house-names.js +43 -0
  491. package/dist/mind/note-search.js +198 -0
  492. package/dist/mind/obligation-steering.js +15 -9
  493. package/dist/mind/outbound-record.js +176 -0
  494. package/dist/mind/pending.js +36 -10
  495. package/dist/mind/prompt-budget.js +511 -0
  496. package/dist/mind/prompt-refresh.js +3 -2
  497. package/dist/mind/prompt.js +978 -342
  498. package/dist/mind/provenance-trust.js +26 -0
  499. package/dist/mind/record-paths.js +312 -0
  500. package/dist/mind/scrutiny.js +121 -0
  501. package/dist/mind/session-transaction.js +642 -0
  502. package/dist/mind/token-estimate.js +17 -0
  503. package/dist/mind/where-am-i.js +147 -0
  504. package/dist/nerves/cli-logging.js +7 -1
  505. package/dist/nerves/coverage/audit-rules.js +15 -6
  506. package/dist/nerves/coverage/audit.js +28 -2
  507. package/dist/nerves/coverage/cli-main.js +6 -1
  508. package/dist/nerves/coverage/cli.js +1 -1
  509. package/dist/nerves/coverage/contract.js +5 -5
  510. package/dist/nerves/coverage/file-completeness.js +161 -5
  511. package/dist/nerves/coverage/run-artifacts.js +55 -35
  512. package/dist/nerves/coverage/source-scanner.js +4 -4
  513. package/dist/nerves/event-buffer.js +111 -0
  514. package/dist/nerves/index.js +293 -9
  515. package/dist/nerves/observation.js +20 -0
  516. package/dist/nerves/redact.js +79 -0
  517. package/dist/nerves/review/cli-main.js +10 -0
  518. package/dist/nerves/review/cli.js +156 -0
  519. package/dist/nerves/review/core.js +159 -0
  520. package/dist/nerves/runtime.js +12 -0
  521. package/dist/repertoire/ado-client.js +15 -56
  522. package/dist/repertoire/ado-semantic.js +108 -40
  523. package/dist/repertoire/api-client.js +97 -0
  524. package/dist/repertoire/auth-required.js +22 -0
  525. package/dist/repertoire/bitwarden-native.js +458 -0
  526. package/dist/repertoire/bitwarden-store.js +1296 -0
  527. package/dist/repertoire/bundle-templates.js +71 -0
  528. package/dist/repertoire/bw-installer.js +268 -0
  529. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  530. package/dist/repertoire/coding/context-pack.js +80 -3
  531. package/dist/repertoire/coding/feedback.js +26 -5
  532. package/dist/repertoire/coding/index.js +15 -3
  533. package/dist/repertoire/coding/manager.js +19 -11
  534. package/dist/repertoire/coding/spawner.js +22 -5
  535. package/dist/repertoire/coding/tools.js +151 -27
  536. package/dist/repertoire/coding/workbench-client.js +272 -0
  537. package/dist/repertoire/coding/workbench-manager.js +346 -0
  538. package/dist/repertoire/commerce-errors.js +109 -0
  539. package/dist/repertoire/commerce-self-test.js +156 -0
  540. package/dist/repertoire/credential-access.js +183 -0
  541. package/dist/repertoire/desk/classifier.js +362 -0
  542. package/dist/repertoire/duffel-client.js +185 -0
  543. package/dist/repertoire/github-client.js +14 -55
  544. package/dist/repertoire/graph-client.js +11 -52
  545. package/dist/repertoire/guardrails.js +1072 -70
  546. package/dist/repertoire/house-sweep.js +471 -0
  547. package/dist/repertoire/in-turn-tools-door.js +54 -0
  548. package/dist/repertoire/mcp-client.js +58 -5
  549. package/dist/repertoire/mcp-manager.js +426 -141
  550. package/dist/repertoire/mcp-tools.js +164 -0
  551. package/dist/repertoire/mcp-write-guard.js +85 -0
  552. package/dist/repertoire/plugin-mcp.js +175 -0
  553. package/dist/repertoire/plugins.js +253 -0
  554. package/dist/repertoire/relationship-authorization.js +322 -0
  555. package/dist/repertoire/sanctuary-container-policy.js +50 -0
  556. package/dist/repertoire/shell-sessions.js +136 -0
  557. package/dist/repertoire/skill-summaries.js +127 -0
  558. package/dist/repertoire/skills.js +48 -4
  559. package/dist/repertoire/stripe-client.js +163 -0
  560. package/dist/repertoire/tool-arguments.js +180 -0
  561. package/dist/repertoire/tool-candidates.js +50 -0
  562. package/dist/repertoire/tool-catalog.js +206 -0
  563. package/dist/repertoire/tool-error-code.js +30 -0
  564. package/dist/repertoire/tool-limits.js +20 -0
  565. package/dist/repertoire/tool-results.js +29 -0
  566. package/dist/repertoire/tools-a2a.js +792 -0
  567. package/dist/repertoire/tools-app-sessions.js +219 -0
  568. package/dist/repertoire/tools-attachments.js +302 -0
  569. package/dist/repertoire/tools-awaiting.js +934 -0
  570. package/dist/repertoire/tools-base.js +85 -1407
  571. package/dist/repertoire/tools-bridge.js +153 -0
  572. package/dist/repertoire/tools-bundle.js +998 -0
  573. package/dist/repertoire/tools-chat.js +185 -0
  574. package/dist/repertoire/tools-commerce.js +272 -0
  575. package/dist/repertoire/tools-config.js +199 -0
  576. package/dist/repertoire/tools-continuity.js +648 -0
  577. package/dist/repertoire/tools-credential.js +410 -0
  578. package/dist/repertoire/tools-escalation.js +98 -0
  579. package/dist/repertoire/tools-evolution.js +560 -0
  580. package/dist/repertoire/tools-files.js +521 -0
  581. package/dist/repertoire/tools-flight.js +313 -0
  582. package/dist/repertoire/tools-flow.js +159 -0
  583. package/dist/repertoire/tools-friend-link.js +65 -0
  584. package/dist/repertoire/tools-github.js +11 -4
  585. package/dist/repertoire/tools-habits.js +111 -0
  586. package/dist/repertoire/tools-house-care.js +190 -0
  587. package/dist/repertoire/tools-mail.js +1928 -0
  588. package/dist/repertoire/tools-notes.js +551 -0
  589. package/dist/repertoire/tools-obligations.js +187 -0
  590. package/dist/repertoire/tools-orientation.js +36 -0
  591. package/dist/repertoire/tools-record.js +497 -0
  592. package/dist/repertoire/tools-rsvp.js +148 -0
  593. package/dist/repertoire/tools-runtime.js +260 -0
  594. package/dist/repertoire/tools-sanctuary-host.js +213 -0
  595. package/dist/repertoire/tools-session.js +1190 -0
  596. package/dist/repertoire/tools-shell.js +275 -0
  597. package/dist/repertoire/tools-shepherd-guidance.js +183 -0
  598. package/dist/repertoire/tools-shepherd.js +369 -0
  599. package/dist/repertoire/tools-steward-policy.js +157 -0
  600. package/dist/repertoire/tools-stripe.js +244 -0
  601. package/dist/repertoire/tools-surface.js +413 -0
  602. package/dist/repertoire/tools-teams.js +67 -17
  603. package/dist/repertoire/tools-telegram-contacts.js +41 -0
  604. package/dist/repertoire/tools-travel.js +142 -0
  605. package/dist/repertoire/tools-trip.js +1041 -0
  606. package/dist/repertoire/tools-unraid.js +627 -0
  607. package/dist/repertoire/tools-user-profile.js +166 -0
  608. package/dist/repertoire/tools-vault.js +46 -0
  609. package/dist/repertoire/tools-voice-local.js +210 -0
  610. package/dist/repertoire/tools-voice.js +153 -0
  611. package/dist/repertoire/tools-web.js +238 -0
  612. package/dist/repertoire/tools.js +572 -274
  613. package/dist/repertoire/travel-api-client.js +463 -0
  614. package/dist/repertoire/unraid-client.js +155 -0
  615. package/dist/repertoire/unraid-restart.js +342 -0
  616. package/dist/repertoire/user-profile.js +131 -0
  617. package/dist/repertoire/vault-setup.js +298 -0
  618. package/dist/repertoire/vault-unlock.js +816 -0
  619. package/dist/rsvp/aisleplanner-client.js +354 -0
  620. package/dist/rsvp/cli.js +936 -0
  621. package/dist/rsvp/config.js +327 -0
  622. package/dist/rsvp/cutover.js +453 -0
  623. package/dist/rsvp/diagnostics.js +232 -0
  624. package/dist/rsvp/diff-renderer.js +176 -0
  625. package/dist/rsvp/habit-policy.js +110 -0
  626. package/dist/rsvp/habit-stage.js +123 -0
  627. package/dist/rsvp/incident-bundle.js +97 -0
  628. package/dist/rsvp/migration.js +204 -0
  629. package/dist/rsvp/native-habit-runner.js +630 -0
  630. package/dist/rsvp/outbound-state.js +628 -0
  631. package/dist/rsvp/query.js +118 -0
  632. package/dist/rsvp/replay.js +233 -0
  633. package/dist/rsvp/snapshot.js +232 -0
  634. package/dist/rsvp/spend-ledger.js +175 -0
  635. package/dist/scripts/claude-code-hook.js +41 -0
  636. package/dist/scripts/claude-code-stop-hook.js +47 -0
  637. package/dist/senses/a2a-entry.js +141 -0
  638. package/dist/senses/acp-server.js +386 -0
  639. package/dist/senses/app-sessions/client.js +128 -0
  640. package/dist/senses/app-sessions/digest-cards.js +187 -0
  641. package/dist/senses/app-sessions/digest-push.js +108 -0
  642. package/dist/senses/app-sessions/digest-sources.js +204 -0
  643. package/dist/senses/app-sessions/digest.js +284 -0
  644. package/dist/senses/app-sessions/run-command.js +51 -0
  645. package/dist/senses/app-sessions/sense.js +252 -0
  646. package/dist/senses/app-sessions/shepherd-cli.js +166 -0
  647. package/dist/senses/app-sessions/shepherd-rows.js +67 -0
  648. package/dist/senses/app-sessions/store.js +149 -0
  649. package/dist/senses/app-sessions/waiting-prompts.js +137 -0
  650. package/dist/senses/app-sessions/waiting-status.js +23 -0
  651. package/dist/senses/app-sessions-entry.js +87 -0
  652. package/dist/senses/attention-queue.js +95 -6
  653. package/dist/senses/await-turn-message.js +65 -0
  654. package/dist/senses/bluebubbles/active-turns.js +241 -0
  655. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  656. package/dist/senses/bluebubbles/attachment-download.js +143 -0
  657. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +384 -48
  658. package/dist/senses/bluebubbles/context-packet.js +207 -0
  659. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  660. package/dist/senses/bluebubbles/entry.js +80 -0
  661. package/dist/senses/bluebubbles/host-account-verifier.js +88 -0
  662. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +21 -3
  663. package/dist/senses/bluebubbles/index.js +4348 -0
  664. package/dist/senses/bluebubbles/latest-turn.js +342 -0
  665. package/dist/senses/bluebubbles/media.js +256 -0
  666. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +147 -30
  667. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +24 -13
  668. package/dist/senses/bluebubbles/outbound-state.js +335 -0
  669. package/dist/senses/bluebubbles/processed-log.js +133 -0
  670. package/dist/senses/bluebubbles/reactions.js +18 -0
  671. package/dist/senses/bluebubbles/replay.js +284 -0
  672. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  673. package/dist/senses/bluebubbles/semantic-receipts.js +2014 -0
  674. package/dist/senses/bluebubbles/send-file.js +20 -0
  675. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  676. package/dist/senses/bluebubbles/webhook-registration.js +257 -0
  677. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  678. package/dist/senses/chat-file.js +75 -0
  679. package/dist/senses/cli/bracketed-paste.js +82 -0
  680. package/dist/senses/cli/image-paste.js +287 -0
  681. package/dist/senses/cli/image-ref-navigation.js +75 -0
  682. package/dist/senses/cli/ink-app.js +156 -0
  683. package/dist/senses/cli/inline-diff.js +64 -0
  684. package/dist/senses/cli/input-keys.js +209 -0
  685. package/dist/senses/cli/kill-ring.js +86 -0
  686. package/dist/senses/cli/message-list.js +51 -0
  687. package/dist/senses/cli/ouro-tui.js +633 -0
  688. package/dist/senses/cli/spinner-imperative.js +135 -0
  689. package/dist/senses/cli/spinner.js +101 -0
  690. package/dist/senses/cli/status-line.js +60 -0
  691. package/dist/senses/cli/streaming-markdown.js +526 -0
  692. package/dist/senses/cli/tool-display.js +85 -0
  693. package/dist/senses/cli/tool-render.js +85 -0
  694. package/dist/senses/cli/tui-store.js +252 -0
  695. package/dist/senses/cli/virtual-list.js +35 -0
  696. package/dist/senses/cli-entry.js +62 -9
  697. package/dist/senses/cli.js +627 -350
  698. package/dist/senses/commands.js +66 -3
  699. package/dist/senses/context-packet-ledger.js +367 -0
  700. package/dist/senses/context-packets.js +154 -0
  701. package/dist/senses/habit-lifecycle-guard.js +24 -0
  702. package/dist/senses/habit-turn-message.js +160 -0
  703. package/dist/senses/ingress-evidence.js +2 -0
  704. package/dist/senses/mail-entry.js +69 -0
  705. package/dist/senses/mail.js +524 -0
  706. package/dist/senses/ordinary-owner-decision.js +97 -0
  707. package/dist/senses/pipeline.js +1141 -282
  708. package/dist/senses/private-runtime-worker.js +857 -0
  709. package/dist/senses/private-runtime.js +1689 -0
  710. package/dist/senses/proactive-content-guard.js +51 -0
  711. package/dist/senses/program-status.js +155 -0
  712. package/dist/senses/repeat-while.js +36 -0
  713. package/dist/senses/root-host-approval-port.js +345 -0
  714. package/dist/senses/root-host-approval-runtime.js +393 -0
  715. package/dist/senses/sanctuary-authority-resident.js +102 -0
  716. package/dist/senses/sanctuary-download-credit-presentation.js +31 -0
  717. package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
  718. package/dist/senses/sanctuary-grounding.js +118 -0
  719. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +21 -0
  720. package/dist/senses/sanctuary-health-acceptance-probe.js +802 -0
  721. package/dist/senses/sanctuary-health-runner.js +106 -0
  722. package/dist/senses/sanctuary-health.js +442 -0
  723. package/dist/senses/sanctuary-house.js +97 -0
  724. package/dist/senses/sanctuary-install-state-contract.js +169 -0
  725. package/dist/senses/sanctuary-interactive-control.js +410 -0
  726. package/dist/senses/sanctuary-media-catalog-contract.js +268 -0
  727. package/dist/senses/sanctuary-media-optimization.js +517 -0
  728. package/dist/senses/sanctuary-runtime.js +392 -0
  729. package/dist/senses/sanctuary-sab.js +85 -0
  730. package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
  731. package/dist/senses/sense-shutdown.js +72 -0
  732. package/dist/senses/shared-turn.js +827 -0
  733. package/dist/senses/shepherd/agent-presentation.js +88 -0
  734. package/dist/senses/shepherd/attention-page.js +166 -0
  735. package/dist/senses/shepherd/attention-sidebar.js +76 -0
  736. package/dist/senses/shepherd/attention.js +295 -0
  737. package/dist/senses/shepherd/checkin-config.js +76 -0
  738. package/dist/senses/shepherd/checkin-store.js +383 -0
  739. package/dist/senses/shepherd/client.js +196 -0
  740. package/dist/senses/shepherd/cmux.js +483 -0
  741. package/dist/senses/shepherd/composer.js +336 -0
  742. package/dist/senses/shepherd/conversation-hold.js +78 -0
  743. package/dist/senses/shepherd/feedback-reply.js +108 -0
  744. package/dist/senses/shepherd/feedback-source.js +20 -0
  745. package/dist/senses/shepherd/feedback-store.js +328 -0
  746. package/dist/senses/shepherd/feedback-submit.js +182 -0
  747. package/dist/senses/shepherd/feedback-worker.js +208 -0
  748. package/dist/senses/shepherd/guidance.js +273 -0
  749. package/dist/senses/shepherd/herdr.js +427 -0
  750. package/dist/senses/shepherd/host.js +14 -0
  751. package/dist/senses/shepherd/human-decision-guard.js +29 -0
  752. package/dist/senses/shepherd/judge-evaluation-command.js +185 -0
  753. package/dist/senses/shepherd/judge-evaluation-entry.js +20 -0
  754. package/dist/senses/shepherd/judge-evaluation.js +144 -0
  755. package/dist/senses/shepherd/judge.js +210 -0
  756. package/dist/senses/shepherd/notice-outbox.js +254 -0
  757. package/dist/senses/shepherd/observation-publisher.js +320 -0
  758. package/dist/senses/shepherd/operations-defaults.js +86 -0
  759. package/dist/senses/shepherd/operations.js +159 -0
  760. package/dist/senses/shepherd/owner-notice.js +496 -0
  761. package/dist/senses/shepherd/prompt-state.js +60 -0
  762. package/dist/senses/shepherd/recovery.js +543 -0
  763. package/dist/senses/shepherd/redact.js +66 -0
  764. package/dist/senses/shepherd/returns.js +79 -0
  765. package/dist/senses/shepherd/sense.js +862 -0
  766. package/dist/senses/shepherd/shepherd-judge-corpus-v1.json +170 -0
  767. package/dist/senses/shepherd/surface.js +125 -0
  768. package/dist/senses/shepherd/target-binding.js +13 -0
  769. package/dist/senses/shepherd/terminal-process.js +147 -0
  770. package/dist/senses/shepherd-entry.js +98 -0
  771. package/dist/senses/surface-tool.js +73 -34
  772. package/dist/senses/teams-attachments.js +68 -0
  773. package/dist/senses/teams-entry.js +80 -9
  774. package/dist/senses/teams-image.js +128 -0
  775. package/dist/senses/teams-off-turn.js +198 -0
  776. package/dist/senses/teams-outbox.js +242 -0
  777. package/dist/senses/teams.js +1167 -369
  778. package/dist/senses/telegram-admission.js +700 -0
  779. package/dist/senses/telegram-approval-runtime.js +793 -0
  780. package/dist/senses/telegram-attachments.js +128 -0
  781. package/dist/senses/telegram-audit-ledger.js +220 -0
  782. package/dist/senses/telegram-authority-transport.js +233 -0
  783. package/dist/senses/telegram-chat-actions.js +54 -0
  784. package/dist/senses/telegram-client.js +1763 -0
  785. package/dist/senses/telegram-effect-adapter.js +877 -0
  786. package/dist/senses/telegram-entry.js +87 -0
  787. package/dist/senses/telegram-handoff.js +150 -0
  788. package/dist/senses/telegram-identity-key.js +143 -0
  789. package/dist/senses/telegram-markdown.js +331 -0
  790. package/dist/senses/telegram-owner-route.js +113 -0
  791. package/dist/senses/telegram.js +2497 -0
  792. package/dist/senses/terminal-handoff.js +44 -0
  793. package/dist/senses/trust-gate.js +104 -9
  794. package/dist/senses/voice/audio-playback.js +237 -0
  795. package/dist/senses/voice/audio-routing.js +119 -0
  796. package/dist/senses/voice/call-auth.js +250 -0
  797. package/dist/senses/voice/elevenlabs.js +202 -0
  798. package/dist/senses/voice/floor-control.js +431 -0
  799. package/dist/senses/voice/floor-controller.js +115 -0
  800. package/dist/senses/voice/golden-path.js +116 -0
  801. package/dist/senses/voice/index.js +29 -0
  802. package/dist/senses/voice/local-audio-control.js +344 -0
  803. package/dist/senses/voice/local-audio-devices.js +516 -0
  804. package/dist/senses/voice/local-audio-disclosure.js +174 -0
  805. package/dist/senses/voice/local-audio-identity.js +103 -0
  806. package/dist/senses/voice/local-audio-join.js +325 -0
  807. package/dist/senses/voice/local-audio-mute.js +199 -0
  808. package/dist/senses/voice/local-audio-notify.js +124 -0
  809. package/dist/senses/voice/local-audio-prompts.js +116 -0
  810. package/dist/senses/voice/local-audio-transport.js +427 -0
  811. package/dist/senses/voice/local-audio.js +281 -0
  812. package/dist/senses/voice/local-media-stream.js +145 -0
  813. package/dist/senses/voice/meeting.js +113 -0
  814. package/dist/senses/voice/outbound.js +190 -0
  815. package/dist/senses/voice/phone.js +33 -0
  816. package/dist/senses/voice/playback.js +139 -0
  817. package/dist/senses/voice/process-guards.js +51 -0
  818. package/dist/senses/voice/realtime-eval.js +496 -0
  819. package/dist/senses/voice/realtime-tool-schema.js +195 -0
  820. package/dist/senses/voice/realtime-trace.js +531 -0
  821. package/dist/senses/voice/transcript.js +70 -0
  822. package/dist/senses/voice/turn.js +191 -0
  823. package/dist/senses/voice/twilio-phone-runtime.js +836 -0
  824. package/dist/senses/voice/twilio-phone.js +5454 -0
  825. package/dist/senses/voice/types.js +2 -0
  826. package/dist/senses/voice/whisper.js +153 -0
  827. package/dist/senses/voice-entry.js +84 -0
  828. package/dist/senses/voice-realtime-eval-command.js +99 -0
  829. package/dist/senses/voice-realtime-eval-entry.js +25 -0
  830. package/dist/senses/voice-twilio-entry.js +88 -0
  831. package/dist/trips/core.js +138 -0
  832. package/dist/trips/store.js +265 -0
  833. package/dist/util/frontmatter.js +69 -0
  834. package/node_modules/@ouro.bot/friends/LICENSE +201 -0
  835. package/node_modules/@ouro.bot/friends/README.md +674 -0
  836. package/node_modules/@ouro.bot/friends/changelog.json +125 -0
  837. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.d.ts +39 -0
  838. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.js +54 -0
  839. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.d.ts +117 -0
  840. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.js +202 -0
  841. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.d.ts +50 -0
  842. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.js +32 -0
  843. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.d.ts +38 -0
  844. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.js +120 -0
  845. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.d.ts +195 -0
  846. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.js +342 -0
  847. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.d.ts +26 -0
  848. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.js +140 -0
  849. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.d.ts +62 -0
  850. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.js +79 -0
  851. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.d.ts +26 -0
  852. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.js +82 -0
  853. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.d.ts +5 -0
  854. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.js +84 -0
  855. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.d.ts +22 -0
  856. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.js +17 -0
  857. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.d.ts +15 -0
  858. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.js +61 -0
  859. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.d.ts +47 -0
  860. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.js +95 -0
  861. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.d.ts +58 -0
  862. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.js +113 -0
  863. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.d.ts +42 -0
  864. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.js +87 -0
  865. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.d.ts +5 -0
  866. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.js +19 -0
  867. package/node_modules/@ouro.bot/friends/dist/account-roster.d.ts +52 -0
  868. package/node_modules/@ouro.bot/friends/dist/account-roster.js +108 -0
  869. package/node_modules/@ouro.bot/friends/dist/agent-peer.d.ts +26 -0
  870. package/node_modules/@ouro.bot/friends/dist/agent-peer.js +138 -0
  871. package/node_modules/@ouro.bot/friends/dist/audit.d.ts +42 -0
  872. package/node_modules/@ouro.bot/friends/dist/audit.js +86 -0
  873. package/node_modules/@ouro.bot/friends/dist/channel.d.ts +11 -0
  874. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/channel.js +80 -3
  875. package/node_modules/@ouro.bot/friends/dist/connect-authority.d.ts +43 -0
  876. package/node_modules/@ouro.bot/friends/dist/connect-authority.js +84 -0
  877. package/node_modules/@ouro.bot/friends/dist/connect.d.ts +56 -0
  878. package/node_modules/@ouro.bot/friends/dist/connect.js +163 -0
  879. package/node_modules/@ouro.bot/friends/dist/consent.d.ts +34 -0
  880. package/node_modules/@ouro.bot/friends/dist/consent.js +65 -0
  881. package/node_modules/@ouro.bot/friends/dist/coordination.d.ts +116 -0
  882. package/node_modules/@ouro.bot/friends/dist/coordination.js +329 -0
  883. package/node_modules/@ouro.bot/friends/dist/delegation-grant.d.ts +21 -0
  884. package/node_modules/@ouro.bot/friends/dist/delegation-grant.js +39 -0
  885. package/node_modules/@ouro.bot/friends/dist/file-bundle.d.ts +17 -0
  886. package/node_modules/@ouro.bot/friends/dist/file-bundle.js +27 -0
  887. package/node_modules/@ouro.bot/friends/dist/friend-lookup.d.ts +9 -0
  888. package/node_modules/@ouro.bot/friends/dist/friend-lookup.js +69 -0
  889. package/node_modules/@ouro.bot/friends/dist/grant-store-file.d.ts +16 -0
  890. package/node_modules/@ouro.bot/friends/dist/grant-store-file.js +136 -0
  891. package/node_modules/@ouro.bot/friends/dist/grant-store.d.ts +7 -0
  892. package/node_modules/@ouro.bot/friends/dist/grant-store.js +8 -0
  893. package/node_modules/@ouro.bot/friends/dist/grants.d.ts +39 -0
  894. package/node_modules/@ouro.bot/friends/dist/grants.js +84 -0
  895. package/node_modules/@ouro.bot/friends/dist/group-context.d.ts +21 -0
  896. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/group-context.js +5 -4
  897. package/node_modules/@ouro.bot/friends/dist/identity.d.ts +17 -0
  898. package/node_modules/@ouro.bot/friends/dist/identity.js +68 -0
  899. package/node_modules/@ouro.bot/friends/dist/index.d.ts +73 -0
  900. package/node_modules/@ouro.bot/friends/dist/index.js +161 -0
  901. package/node_modules/@ouro.bot/friends/dist/link-identity.d.ts +14 -0
  902. package/node_modules/@ouro.bot/friends/dist/link-identity.js +157 -0
  903. package/node_modules/@ouro.bot/friends/dist/mailbox/index.d.ts +105 -0
  904. package/node_modules/@ouro.bot/friends/dist/mailbox/index.js +205 -0
  905. package/node_modules/@ouro.bot/friends/dist/mcp/bin.d.ts +2 -0
  906. package/node_modules/@ouro.bot/friends/dist/mcp/bin.js +16 -0
  907. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.d.ts +40 -0
  908. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.js +549 -0
  909. package/node_modules/@ouro.bot/friends/dist/mcp/index.d.ts +6 -0
  910. package/node_modules/@ouro.bot/friends/dist/mcp/index.js +14 -0
  911. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.d.ts +7 -0
  912. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.js +48 -0
  913. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.d.ts +10 -0
  914. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.js +445 -0
  915. package/node_modules/@ouro.bot/friends/dist/mcp/server.d.ts +30 -0
  916. package/node_modules/@ouro.bot/friends/dist/mcp/server.js +194 -0
  917. package/node_modules/@ouro.bot/friends/dist/message.d.ts +75 -0
  918. package/node_modules/@ouro.bot/friends/dist/message.js +99 -0
  919. package/node_modules/@ouro.bot/friends/dist/mission-result.d.ts +82 -0
  920. package/node_modules/@ouro.bot/friends/dist/mission-result.js +200 -0
  921. package/node_modules/@ouro.bot/friends/dist/mission-share.d.ts +94 -0
  922. package/node_modules/@ouro.bot/friends/dist/mission-share.js +232 -0
  923. package/node_modules/@ouro.bot/friends/dist/mission-store-file.d.ts +18 -0
  924. package/node_modules/@ouro.bot/friends/dist/mission-store-file.js +161 -0
  925. package/node_modules/@ouro.bot/friends/dist/mission-store.d.ts +10 -0
  926. package/node_modules/@ouro.bot/friends/dist/mission-store.js +9 -0
  927. package/node_modules/@ouro.bot/friends/dist/missions.d.ts +31 -0
  928. package/node_modules/@ouro.bot/friends/dist/missions.js +98 -0
  929. package/node_modules/@ouro.bot/friends/dist/notes.d.ts +11 -0
  930. package/node_modules/@ouro.bot/friends/dist/notes.js +90 -0
  931. package/node_modules/@ouro.bot/friends/dist/observability.d.ts +27 -0
  932. package/node_modules/@ouro.bot/friends/dist/observability.js +31 -0
  933. package/node_modules/@ouro.bot/friends/dist/outcomes.d.ts +9 -0
  934. package/node_modules/@ouro.bot/friends/dist/outcomes.js +51 -0
  935. package/node_modules/@ouro.bot/friends/dist/resolver.d.ts +59 -0
  936. package/node_modules/@ouro.bot/friends/dist/resolver.js +276 -0
  937. package/node_modules/@ouro.bot/friends/dist/results.d.ts +10 -0
  938. package/node_modules/@ouro.bot/friends/dist/results.js +2 -0
  939. package/node_modules/@ouro.bot/friends/dist/room.d.ts +22 -0
  940. package/node_modules/@ouro.bot/friends/dist/room.js +40 -0
  941. package/node_modules/@ouro.bot/friends/dist/roster-store-file.d.ts +16 -0
  942. package/node_modules/@ouro.bot/friends/dist/roster-store-file.js +125 -0
  943. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.d.ts +9 -0
  944. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.js +20 -0
  945. package/node_modules/@ouro.bot/friends/dist/roster-store.d.ts +29 -0
  946. package/node_modules/@ouro.bot/friends/dist/roster-store.js +9 -0
  947. package/node_modules/@ouro.bot/friends/dist/roster-verifier.d.ts +23 -0
  948. package/node_modules/@ouro.bot/friends/dist/roster-verifier.js +47 -0
  949. package/node_modules/@ouro.bot/friends/dist/share.d.ts +108 -0
  950. package/node_modules/@ouro.bot/friends/dist/share.js +278 -0
  951. package/node_modules/@ouro.bot/friends/dist/standing.d.ts +83 -0
  952. package/node_modules/@ouro.bot/friends/dist/standing.js +111 -0
  953. package/node_modules/@ouro.bot/friends/dist/store-file.d.ts +82 -0
  954. package/node_modules/@ouro.bot/friends/dist/store-file.js +1074 -0
  955. package/node_modules/@ouro.bot/friends/dist/store.d.ts +43 -0
  956. package/node_modules/@ouro.bot/friends/dist/tokens.d.ts +8 -0
  957. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/tokens.js +2 -2
  958. package/node_modules/@ouro.bot/friends/dist/trust-explanation.d.ts +22 -0
  959. package/node_modules/@ouro.bot/friends/dist/trust-explanation.js +90 -0
  960. package/node_modules/@ouro.bot/friends/dist/trust-mutation.d.ts +16 -0
  961. package/node_modules/@ouro.bot/friends/dist/trust-mutation.js +67 -0
  962. package/node_modules/@ouro.bot/friends/dist/types.d.ts +321 -0
  963. package/node_modules/@ouro.bot/friends/dist/types.js +55 -0
  964. package/node_modules/@ouro.bot/friends/dist/util/cap-string.d.ts +7 -0
  965. package/node_modules/@ouro.bot/friends/dist/util/cap-string.js +35 -0
  966. package/node_modules/@ouro.bot/friends/dist/verifier.d.ts +11 -0
  967. package/node_modules/@ouro.bot/friends/dist/verifier.js +29 -0
  968. package/node_modules/@ouro.bot/friends/dist/whoami.d.ts +7 -0
  969. package/node_modules/@ouro.bot/friends/dist/whoami.js +39 -0
  970. package/node_modules/@ouro.bot/friends/package.json +81 -0
  971. package/node_modules/libsodium/LICENSE +16 -0
  972. package/node_modules/libsodium/README.md +281 -0
  973. package/node_modules/libsodium/dist/modules/libsodium.js +1 -0
  974. package/node_modules/libsodium/dist/modules-esm/libsodium.mjs +1 -0
  975. package/node_modules/libsodium/package.json +54 -0
  976. package/node_modules/libsodium-wrappers/LICENSE +16 -0
  977. package/node_modules/libsodium-wrappers/README.md +281 -0
  978. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.d.ts +2155 -0
  979. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.js +1 -0
  980. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.d.mts +2743 -0
  981. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.mjs +1 -0
  982. package/node_modules/libsodium-wrappers/package.json +74 -0
  983. package/npm-shrinkwrap.json +8789 -0
  984. package/package.json +93 -13
  985. package/skills/agent-commerce.md +116 -0
  986. package/skills/browser-navigation.md +120 -0
  987. package/skills/commerce-setup-guide.md +116 -0
  988. package/skills/commerce-setup.md +87 -0
  989. package/skills/configure-dev-tools.md +99 -0
  990. package/skills/sense-setup.md +56 -0
  991. package/skills/travel-planning.md +141 -0
  992. package/dist/heart/daemon/auth-flow.js +0 -457
  993. package/dist/heart/daemon/ouro-path-installer.js +0 -210
  994. package/dist/heart/daemon/ouro-version-manager.js +0 -171
  995. package/dist/heart/daemon/specialist-tools.js +0 -283
  996. package/dist/heart/daemon/update-hooks.js +0 -138
  997. package/dist/heart/obligations.js +0 -197
  998. package/dist/heart/session-recall.js +0 -216
  999. package/dist/mind/associative-recall.js +0 -287
  1000. package/dist/mind/friends/resolver.js +0 -84
  1001. package/dist/mind/friends/store-file.js +0 -190
  1002. package/dist/mind/friends/trust-explanation.js +0 -74
  1003. package/dist/mind/friends/types.js +0 -29
  1004. package/dist/mind/journal-index.js +0 -161
  1005. package/dist/mind/obligations.js +0 -134
  1006. package/dist/repertoire/tasks/board.js +0 -134
  1007. package/dist/repertoire/tasks/index.js +0 -224
  1008. package/dist/repertoire/tasks/lifecycle.js +0 -80
  1009. package/dist/repertoire/tasks/middleware.js +0 -65
  1010. package/dist/repertoire/tasks/parser.js +0 -173
  1011. package/dist/repertoire/tasks/scanner.js +0 -132
  1012. package/dist/repertoire/tasks/transitions.js +0 -144
  1013. package/dist/repertoire/tools-bluebubbles.js +0 -94
  1014. package/dist/senses/bluebubbles-entry.js +0 -13
  1015. package/dist/senses/bluebubbles-media.js +0 -339
  1016. package/dist/senses/bluebubbles.js +0 -1231
  1017. package/dist/senses/debug-activity.js +0 -154
  1018. package/dist/senses/inner-dialog-worker.js +0 -90
  1019. package/dist/senses/inner-dialog.js +0 -603
  1020. package/subagents/README.md +0 -7
  1021. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  1022. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  1023. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  1024. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  1025. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  1026. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  1027. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  1028. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  1029. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  1030. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  1031. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  1032. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  1033. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  1034. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  1035. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  1036. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  1037. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
  1038. /package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/store.js +0 -0
@@ -0,0 +1,4348 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.BB_IN_FLIGHT_MAX_AGE_MS = exports.BLUEBUBBLES_SEMANTIC_GENERATION_RETENTION_MS = void 0;
37
+ exports.drainBlueBubblesTurns = drainBlueBubblesTurns;
38
+ exports.pruneBlueBubblesSemanticObservationGenerations = pruneBlueBubblesSemanticObservationGenerations;
39
+ exports.auditBlueBubblesObservationOwnership = auditBlueBubblesObservationOwnership;
40
+ exports.tokenizeForDedupe = tokenizeForDedupe;
41
+ exports.jaccardSimilarity = jaccardSimilarity;
42
+ exports.isBlueBubblesMessageInFlight = isBlueBubblesMessageInFlight;
43
+ exports.beginBlueBubblesMessageInFlight = beginBlueBubblesMessageInFlight;
44
+ exports.endBlueBubblesMessageInFlight = endBlueBubblesMessageInFlight;
45
+ exports.__resetBlueBubblesInFlightForTests = __resetBlueBubblesInFlightForTests;
46
+ exports.createBlueBubblesCallbacks = createBlueBubblesCallbacks;
47
+ exports.isAgentSelfHandle = isAgentSelfHandle;
48
+ exports.getDiscoveredOwnHandles = getDiscoveredOwnHandles;
49
+ exports.clearDiscoveredOwnHandles = clearDiscoveredOwnHandles;
50
+ exports.recordDiscoveredOwnHandle = recordDiscoveredOwnHandle;
51
+ exports.seedBlueBubblesStartupSemanticObservations = seedBlueBubblesStartupSemanticObservations;
52
+ exports.handleBlueBubblesEvent = handleBlueBubblesEvent;
53
+ exports.recoverQueuedBlueBubblesMessages = recoverQueuedBlueBubblesMessages;
54
+ exports.catchUpMissedBlueBubblesMessages = catchUpMissedBlueBubblesMessages;
55
+ exports.recoverCapturedBlueBubblesInboundMessages = recoverCapturedBlueBubblesInboundMessages;
56
+ exports.recoverMissedBlueBubblesMessages = recoverMissedBlueBubblesMessages;
57
+ exports.createBlueBubblesWebhookHandler = createBlueBubblesWebhookHandler;
58
+ exports.sendProactiveBlueBubblesMessageToSession = sendProactiveBlueBubblesMessageToSession;
59
+ exports.drainAndSendPendingBlueBubbles = drainAndSendPendingBlueBubbles;
60
+ exports.stopBlueBubblesApp = stopBlueBubblesApp;
61
+ exports.startBlueBubblesApp = startBlueBubblesApp;
62
+ const fs = __importStar(require("node:fs"));
63
+ const http = __importStar(require("node:http"));
64
+ const path = __importStar(require("node:path"));
65
+ const node_crypto_1 = require("node:crypto");
66
+ const core_1 = require("../../heart/core");
67
+ const config_1 = require("../../heart/config");
68
+ const identity_1 = require("../../heart/identity");
69
+ const machine_identity_1 = require("../../heart/machine-identity");
70
+ const runtime_cwd_1 = require("../../heart/runtime-cwd");
71
+ const turn_coordinator_1 = require("../../heart/turn-coordinator");
72
+ const context_1 = require("../../mind/context");
73
+ const friends_1 = require("@ouro.bot/friends");
74
+ const pending_1 = require("../../mind/pending");
75
+ const prompt_1 = require("../../mind/prompt");
76
+ const mcp_manager_1 = require("../../repertoire/mcp-manager");
77
+ const runtime_1 = require("../../nerves/runtime");
78
+ const session_transaction_1 = require("../../mind/session-transaction");
79
+ const outbound_record_1 = require("../../mind/outbound-record");
80
+ const await_alert_1 = require("../../heart/awaiting/await-alert");
81
+ const orientation_frame_1 = require("../../heart/orientation-frame");
82
+ const proactive_content_guard_1 = require("../proactive-content-guard");
83
+ const bluebubbles_meta_guard_1 = require("../bluebubbles-meta-guard");
84
+ const model_1 = require("./model");
85
+ const client_1 = require("./client");
86
+ const reactions_1 = require("./reactions");
87
+ const send_file_1 = require("./send-file");
88
+ const tools_chat_1 = require("../../repertoire/tools-chat");
89
+ const host_account_verifier_1 = require("./host-account-verifier");
90
+ const webhook_registration_1 = require("./webhook-registration");
91
+ const inbound_log_1 = require("./inbound-log");
92
+ const mutation_log_1 = require("./mutation-log");
93
+ const processed_log_1 = require("./processed-log");
94
+ const semantic_receipts_1 = require("./semantic-receipts");
95
+ const runtime_state_1 = require("./runtime-state");
96
+ const session_cleanup_1 = require("./session-cleanup");
97
+ const latest_turn_1 = require("./latest-turn");
98
+ const active_turns_1 = require("./active-turns");
99
+ const trust_gate_1 = require("../trust-gate");
100
+ const pipeline_1 = require("../pipeline");
101
+ const context_packet_ledger_1 = require("../context-packet-ledger");
102
+ const context_packet_1 = require("./context-packet");
103
+ const autonomy_budget_1 = require("../../heart/autonomy-budget");
104
+ const outbound_state_1 = require("./outbound-state");
105
+ const bbFailoverStates = new Map();
106
+ const inFlightBlueBubblesWork = new Set();
107
+ function trackBlueBubblesTurn(work) {
108
+ inFlightBlueBubblesWork.add(work);
109
+ const forget = () => { inFlightBlueBubblesWork.delete(work); };
110
+ void work.then(forget, forget);
111
+ }
112
+ /** Resolves once every queued webhook turn and recovery pass this process started has ended. */
113
+ async function drainBlueBubblesTurns() {
114
+ const work = [...inFlightBlueBubblesWork];
115
+ await Promise.allSettled(work);
116
+ return work.length;
117
+ }
118
+ const activeSemanticHandlingSlots = new Map();
119
+ // Turns that timed out without a reply, per capture, in this process. Each one
120
+ // stays pending for replay until it reaches the delivery attempt cap.
121
+ const unfinishedTurnAttempts = new Map();
122
+ const semanticObservationGenerations = new Map();
123
+ const BLUEBUBBLES_VISIBLE_OUTBOUND_STATUSES = new Set([
124
+ "accepted",
125
+ "enqueued",
126
+ "local-visible",
127
+ "delivered",
128
+ ]);
129
+ // A reply whose final send keeps failing stays pending for recovery this many
130
+ // times, then gets a terminal receipt so one message cannot drain the budget.
131
+ const BLUEBUBBLES_REPLY_DELIVERY_MAX_ATTEMPTS = 3;
132
+ // A timed-out send may still land, so wait before checking the chat and retrying.
133
+ const BLUEBUBBLES_REPLY_RETRY_DELAY_MS = 10 * 60_000;
134
+ exports.BLUEBUBBLES_SEMANTIC_GENERATION_RETENTION_MS = 15 * 60_000;
135
+ /**
136
+ * A retained generation fences older replies in its chat only while its capture
137
+ * still waits for recovery. Once the capture has an outcome (or after the
138
+ * retention window), nothing owns the fence, so release it.
139
+ */
140
+ function pruneBlueBubblesSemanticObservationGenerations(nowMs = Date.now(), pendingKeyHashes) {
141
+ let pruned = 0;
142
+ for (const [keyHash, generation] of semanticObservationGenerations) {
143
+ if (generation.retainedAtMs === null)
144
+ continue;
145
+ const expired = nowMs - generation.retainedAtMs >= exports.BLUEBUBBLES_SEMANTIC_GENERATION_RETENTION_MS;
146
+ const resolved = pendingKeyHashes !== undefined && !pendingKeyHashes.has(keyHash);
147
+ if (!expired && !resolved)
148
+ continue;
149
+ (0, latest_turn_1.clearPending)(generation.reservation);
150
+ semanticObservationGenerations.delete(keyHash);
151
+ pruned += 1;
152
+ }
153
+ return pruned;
154
+ }
155
+ /**
156
+ * Owns the observation reservations one call makes. Every reservation is
157
+ * settled when the scope closes unless a live semantic generation has taken it
158
+ * over, so no code path can leave a fence behind by returning or throwing early.
159
+ */
160
+ class BlueBubblesObservationScope {
161
+ owned = [];
162
+ constructor() {
163
+ openObservationScopes.add(this);
164
+ }
165
+ own(reservation) {
166
+ this.owned.push(reservation);
167
+ return reservation;
168
+ }
169
+ owns(reservation) {
170
+ return this.owned.includes(reservation);
171
+ }
172
+ close() {
173
+ openObservationScopes.delete(this);
174
+ for (const reservation of this.owned.splice(0)) {
175
+ if (!isGenerationReservation(reservation))
176
+ (0, latest_turn_1.clearPending)(reservation);
177
+ }
178
+ }
179
+ }
180
+ const openObservationScopes = new Set();
181
+ /**
182
+ * Runs `work` with a scope that settles its reservations once `work` ends.
183
+ * Returns `work`'s own promise so callers see no extra await.
184
+ */
185
+ function withObservationScope(work) {
186
+ const scope = new BlueBubblesObservationScope();
187
+ const running = work(scope);
188
+ const close = () => scope.close();
189
+ void running.then(close, close);
190
+ return running;
191
+ }
192
+ function isGenerationReservation(reservation) {
193
+ for (const generation of semanticObservationGenerations.values()) {
194
+ if (generation.reservation === reservation)
195
+ return true;
196
+ }
197
+ return false;
198
+ }
199
+ /**
200
+ * Test and diagnostics audit: pending observations that nothing owns. A
201
+ * reservation is owned while its scope is open, or while it is the reservation
202
+ * of a generation that is in flight or whose capture still waits for recovery.
203
+ */
204
+ function auditBlueBubblesObservationOwnership(pendingKeyHashes) {
205
+ const owners = new Map();
206
+ for (const [keyHash, generation] of semanticObservationGenerations) {
207
+ owners.set(generation.reservation, keyHash);
208
+ }
209
+ return (0, latest_turn_1.listPendingObservationsForAudit)().filter((reservation) => {
210
+ if ([...openObservationScopes].some((scope) => scope.owns(reservation)))
211
+ return false;
212
+ const keyHash = owners.get(reservation);
213
+ if (keyHash === undefined)
214
+ return true;
215
+ return !activeSemanticHandlingSlots.has(keyHash) && !pendingKeyHashes.has(keyHash);
216
+ });
217
+ }
218
+ function adoptBlueBubblesSemanticObservation(keyHash, observedReservation, activate) {
219
+ pruneBlueBubblesSemanticObservationGenerations();
220
+ const existing = semanticObservationGenerations.get(keyHash);
221
+ if (!existing) {
222
+ const generation = { reservation: observedReservation, retry: false, retainedAtMs: null };
223
+ semanticObservationGenerations.set(keyHash, generation);
224
+ return generation;
225
+ }
226
+ (0, latest_turn_1.mergeObservationReservations)(existing.reservation, observedReservation);
227
+ if (activate) {
228
+ existing.retainedAtMs = null;
229
+ (0, latest_turn_1.reactivateObservation)(existing.reservation);
230
+ }
231
+ return existing;
232
+ }
233
+ /**
234
+ * A capture seeded at startup already holds its causal place. Fold the recovery pass's fresh reservation into it now, so
235
+ * the lane schedules by the seeded order and a newer recovered turn never waits on an older capture's unfolded duplicate.
236
+ */
237
+ function seededObservationReservation(keyHash, fresh) {
238
+ return semanticObservationGenerations.has(keyHash)
239
+ ? adoptBlueBubblesSemanticObservation(keyHash, fresh, false).reservation
240
+ : fresh;
241
+ }
242
+ function suspendBlueBubblesSemanticObservation(generation) {
243
+ generation.retry = true;
244
+ generation.retainedAtMs = Date.now();
245
+ (0, latest_turn_1.reactivateObservation)(generation.reservation);
246
+ }
247
+ function completeBlueBubblesSemanticObservation(keyHash, generation) {
248
+ (0, latest_turn_1.clearPending)(generation.reservation);
249
+ semanticObservationGenerations.delete(keyHash);
250
+ unfinishedTurnAttempts.delete(keyHash);
251
+ }
252
+ async function acquireBlueBubblesSemanticHandlingSlot(keyHash, generation) {
253
+ const active = activeSemanticHandlingSlots.get(keyHash);
254
+ if (!active) {
255
+ const slot = {
256
+ generation,
257
+ reservation: generation.reservation,
258
+ waiters: [],
259
+ };
260
+ activeSemanticHandlingSlots.set(keyHash, slot);
261
+ return {
262
+ status: "owner",
263
+ slot,
264
+ reservation: generation.reservation,
265
+ allowSameGenerationRetry: generation.retry,
266
+ };
267
+ }
268
+ return await new Promise((resolve) => {
269
+ active.waiters.push(resolve);
270
+ });
271
+ }
272
+ function releaseBlueBubblesSemanticHandlingSlot(keyHash, slot, outcome) {
273
+ if (outcome === "retryable") {
274
+ slot.generation.retry = true;
275
+ const next = slot.waiters.shift();
276
+ if (next) {
277
+ (0, latest_turn_1.reactivateObservation)(slot.reservation);
278
+ next({
279
+ status: "owner",
280
+ slot,
281
+ reservation: slot.reservation,
282
+ allowSameGenerationRetry: true,
283
+ });
284
+ return;
285
+ }
286
+ }
287
+ activeSemanticHandlingSlots.delete(keyHash);
288
+ if (outcome === "terminal") {
289
+ completeBlueBubblesSemanticObservation(keyHash, slot.generation);
290
+ }
291
+ else {
292
+ suspendBlueBubblesSemanticObservation(slot.generation);
293
+ }
294
+ for (const resolve of slot.waiters.splice(0)) {
295
+ resolve({ status: "handled_by_owner" });
296
+ }
297
+ }
298
+ /**
299
+ * In-flight message tracker.
300
+ *
301
+ * Stores the timestamp (ms) when each (sessionKey, messageGuid) was claimed.
302
+ * Stale entries (older than BB_IN_FLIGHT_MAX_AGE_MS) are treated as expired:
303
+ * `isBlueBubblesMessageInFlight` returns false, and `beginBlueBubblesMessageInFlight`
304
+ * is allowed to replace the stale marker.
305
+ *
306
+ * Rationale: `handleBlueBubblesNormalizedEvent` has many exit paths and a leak
307
+ * on any one of them strands the marker forever (until BB sense process restart),
308
+ * which silently halts forward progress on the recovery queue. A real
309
+ * agent lost BlueBubbles inbound for 12+ hours on 2026-05-11 because of
310
+ * exactly this.
311
+ *
312
+ * The TTL bounds the worst case: a leaked marker self-clears after
313
+ * BB_IN_FLIGHT_MAX_AGE_MS, and the next recovery pass can retry. This is
314
+ * defense-in-depth alongside auditing the explicit `endBlueBubblesMessageInFlight`
315
+ * exit-path calls — the audit is still worthwhile, but the TTL guarantees the
316
+ * class of bug can't wedge the queue indefinitely.
317
+ */
318
+ const bbInFlightMessageClaims = new Map();
319
+ /**
320
+ * In-flight markers expire 50% beyond the longest expected turn (recovery turn
321
+ * timeout = 10 min). 15 min gives normal turns full headroom while preventing
322
+ * a leaked marker from blocking forward progress for hours.
323
+ */
324
+ exports.BB_IN_FLIGHT_MAX_AGE_MS = 15 * 60_000;
325
+ // ── Near-duplicate outward-text detection ────────────────────────
326
+ // Used by createBlueBubblesCallbacks to collapse mid-turn rephrasings of the
327
+ // same answer/status into a single delivery. Exposed for direct unit testing
328
+ // of the similarity behavior without spinning up the full callbacks closure.
329
+ const NEAR_DUPLICATE_JACCARD_THRESHOLD = 0.7;
330
+ const NEAR_DUPLICATE_MIN_TOKENS = 5;
331
+ function tokenizeForDedupe(text) {
332
+ const matches = text.toLowerCase().match(/[a-z0-9']+/g);
333
+ if (!matches)
334
+ return new Set();
335
+ return new Set(matches);
336
+ }
337
+ function jaccardSimilarity(a, b) {
338
+ if (a.size === 0 || b.size === 0)
339
+ return 0;
340
+ let intersection = 0;
341
+ for (const token of a) {
342
+ if (b.has(token))
343
+ intersection += 1;
344
+ }
345
+ const union = a.size + b.size - intersection;
346
+ return intersection / union;
347
+ }
348
+ function blueBubblesMessageKey(sessionKey, messageGuid) {
349
+ return `${sessionKey}:${messageGuid.trim()}`;
350
+ }
351
+ function isClaimStale(claimedAtMs, nowMs = Date.now()) {
352
+ return nowMs - claimedAtMs >= exports.BB_IN_FLIGHT_MAX_AGE_MS;
353
+ }
354
+ /** Internal — exported only so unit tests can exercise the TTL semantics. */
355
+ function isBlueBubblesMessageInFlight(sessionKey, messageGuid) {
356
+ if (!messageGuid.trim())
357
+ return false;
358
+ const claimedAtMs = bbInFlightMessageClaims.get(blueBubblesMessageKey(sessionKey, messageGuid));
359
+ if (claimedAtMs === undefined)
360
+ return false;
361
+ return !isClaimStale(claimedAtMs);
362
+ }
363
+ /** Internal — exported only so unit tests can exercise the TTL semantics. */
364
+ function beginBlueBubblesMessageInFlight(sessionKey, messageGuid) {
365
+ if (!messageGuid.trim())
366
+ return true;
367
+ const key = blueBubblesMessageKey(sessionKey, messageGuid);
368
+ const existing = bbInFlightMessageClaims.get(key);
369
+ if (existing !== undefined && !isClaimStale(existing))
370
+ return false;
371
+ if (existing !== undefined && isClaimStale(existing)) {
372
+ (0, runtime_1.emitNervesEvent)({
373
+ level: "warn",
374
+ component: "senses",
375
+ event: "senses.bluebubbles_in_flight_marker_expired",
376
+ message: "in-flight marker expired by TTL; allowing re-claim",
377
+ meta: {
378
+ sessionKey,
379
+ messageGuid,
380
+ claimAgeMs: Date.now() - existing,
381
+ ttlMs: exports.BB_IN_FLIGHT_MAX_AGE_MS,
382
+ },
383
+ });
384
+ }
385
+ bbInFlightMessageClaims.set(key, Date.now());
386
+ return true;
387
+ }
388
+ /** Internal — exported only so unit tests can exercise the TTL semantics. */
389
+ function endBlueBubblesMessageInFlight(sessionKey, messageGuid) {
390
+ bbInFlightMessageClaims.delete(blueBubblesMessageKey(sessionKey, messageGuid));
391
+ }
392
+ /**
393
+ * Test-only: clear all in-flight markers. Production code must use begin/end pairs.
394
+ * Exported so unit tests can reset cross-test state without resetting modules.
395
+ */
396
+ function __resetBlueBubblesInFlightForTests() {
397
+ bbInFlightMessageClaims.clear();
398
+ }
399
+ const defaultDeps = {
400
+ getAgentName: identity_1.getAgentName,
401
+ buildSystem: prompt_1.buildSystem,
402
+ runAgent: core_1.runAgent,
403
+ loadSession: context_1.loadSession,
404
+ saveSession: context_1.saveSession,
405
+ postTurnTrim: context_1.postTurnTrim,
406
+ postTurnPersist: context_1.postTurnPersist,
407
+ sessionPath: config_1.sessionPath,
408
+ accumulateFriendTokens: friends_1.accumulateFriendTokens,
409
+ createClient: () => (0, client_1.createBlueBubblesClient)(),
410
+ recordMutation: mutation_log_1.recordBlueBubblesMutation,
411
+ createFriendStore: () => new friends_1.FileFriendStore(path.join((0, identity_1.getAgentRoot)(), "friends")),
412
+ createFriendResolver: (store, params) => new friends_1.FriendResolver(store, params),
413
+ createServer: http.createServer,
414
+ getOwnHandles: () => [...(0, config_1.getBlueBubblesConfig)().ownHandles, ...discoveredOwnHandles],
415
+ promoteFailoverState: (sessionKey, state) => {
416
+ bbFailoverStates.set(sessionKey, structuredClone(state));
417
+ },
418
+ recordProcessed: processed_log_1.recordProcessedBlueBubblesMessage,
419
+ withSessionTurnLease: session_transaction_1.withSessionTurnLease,
420
+ // Incoming events recheck every time, like sends, so a server that takes over
421
+ // the same URL under another account is refused immediately.
422
+ verifyHostAccount: () => (0, host_account_verifier_1.verifyBlueBubblesServerAccount)({
423
+ agent: (0, identity_1.getAgentName)(),
424
+ hostUsername: (0, identity_1.loadAgentConfig)().senses?.bluebubbles.hostUsername,
425
+ serverUrl: (0, config_1.getBlueBubblesConfig)().serverUrl,
426
+ password: (0, config_1.getBlueBubblesConfig)().password,
427
+ requestTimeoutMs: (0, config_1.getBlueBubblesChannelConfig)().requestTimeoutMs,
428
+ fresh: true,
429
+ }),
430
+ };
431
+ const BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS = 30_000;
432
+ const BLUEBUBBLES_RECOVERY_PASS_DELAY_MS = 1_000;
433
+ const BLUEBUBBLES_RECOVERY_PASS_INTERVAL_MS = 30_000;
434
+ // A turn that is still thinking after this long is treated as hung. It is generous on purpose: a slow reply that
435
+ // arrives is worth far more than a dropped one, and a newer message from the person still supersedes an older turn.
436
+ const BLUEBUBBLES_TURN_TIMEOUT_MS = 10 * 60_000;
437
+ const BLUEBUBBLES_LIVE_TURN_STALLED_MS = 5 * 60_000;
438
+ const BLUEBUBBLES_CALLBACK_CLEANUP_TIMEOUT_MS = 2_000;
439
+ const BLUEBUBBLES_ACTIVITY_OPERATION_TIMEOUT_MS = 20_000;
440
+ const BLUEBUBBLES_CATCHUP_PAGE_SIZE = 50;
441
+ const BLUEBUBBLES_CATCHUP_MAX_PAGES = 20;
442
+ const BLUEBUBBLES_HEALTHY_CATCHUP_OVERLAP_MS = 90_000;
443
+ const BLUEBUBBLES_RECOVERY_CATCHUP_LOOKBACK_MS = 24 * 60 * 60 * 1000;
444
+ const BLUEBUBBLES_FIRST_CATCHUP_LOOKBACK_MS = 10 * 60 * 1000;
445
+ class BlueBubblesRecoveryTurnTimeoutError extends Error {
446
+ constructor(timeoutMs) {
447
+ super(`bluebubbles recovery turn timed out after ${timeoutMs}ms`);
448
+ this.name = "BlueBubblesRecoveryTurnTimeoutError";
449
+ }
450
+ }
451
+ class BlueBubblesActivityTimeoutError extends Error {
452
+ constructor(operation, timeoutMs) {
453
+ super(`bluebubbles ${operation} activity timed out after ${timeoutMs}ms`);
454
+ this.name = "BlueBubblesActivityTimeoutError";
455
+ }
456
+ }
457
+ function withBlueBubblesActivityTimeout(operation, timeoutMs, controller, task) {
458
+ let timer = null;
459
+ controller.signal.throwIfAborted();
460
+ let removeAbortListener;
461
+ const aborted = new Promise((_, reject) => {
462
+ const rejectFromAbort = () => {
463
+ reject(controller.signal.reason);
464
+ };
465
+ controller.signal.addEventListener("abort", rejectFromAbort, { once: true });
466
+ removeAbortListener = () => controller.signal.removeEventListener("abort", rejectFromAbort);
467
+ });
468
+ return Promise.race([
469
+ Promise.resolve().then(() => task(controller.signal)),
470
+ aborted,
471
+ new Promise((_, reject) => {
472
+ timer = setTimeout(() => {
473
+ const error = new BlueBubblesActivityTimeoutError(operation, timeoutMs);
474
+ controller.abort(error);
475
+ reject(error);
476
+ }, timeoutMs);
477
+ /* v8 ignore next -- timer handles expose unref only in some runtimes @preserve */
478
+ if (typeof timer.unref === "function") {
479
+ timer.unref();
480
+ }
481
+ }),
482
+ ]).finally(() => {
483
+ removeAbortListener();
484
+ /* v8 ignore next -- timer is assigned unless a callback task throws synchronously; callback tasks are async @preserve */
485
+ if (timer !== null)
486
+ clearTimeout(timer);
487
+ });
488
+ }
489
+ async function waitForBlueBubblesCallbackCleanup(queue, timeoutMs, meta) {
490
+ let timer = null;
491
+ let timedOut = false;
492
+ await Promise.race([
493
+ queue,
494
+ new Promise((resolve) => {
495
+ timer = setTimeout(() => {
496
+ timedOut = true;
497
+ resolve();
498
+ }, timeoutMs);
499
+ /* v8 ignore next -- timer handles expose unref only in some runtimes @preserve */
500
+ if (typeof timer.unref === "function") {
501
+ timer.unref();
502
+ }
503
+ }),
504
+ ]).finally(() => {
505
+ /* v8 ignore next -- timer is assigned for the cleanup race; null only protects unusual synchronous construction failure @preserve */
506
+ if (timer !== null)
507
+ clearTimeout(timer);
508
+ });
509
+ if (!timedOut)
510
+ return true;
511
+ (0, runtime_1.emitNervesEvent)({
512
+ level: "warn",
513
+ component: "senses",
514
+ event: "senses.bluebubbles_activity_cleanup_timeout",
515
+ message: "bluebubbles callback cleanup timed out; releasing live turn lane",
516
+ meta: { ...meta, timeoutMs },
517
+ });
518
+ return false;
519
+ }
520
+ function resolveFriendParams(event) {
521
+ if (event.chat.isGroup) {
522
+ return {
523
+ provider: "imessage-handle",
524
+ externalId: `group:${event.chat.chatGuid}`,
525
+ displayName: event.chat.displayName ?? "Unknown Group",
526
+ channel: "bluebubbles",
527
+ };
528
+ }
529
+ return {
530
+ provider: "imessage-handle",
531
+ externalId: event.sender.externalId,
532
+ displayName: event.sender.displayName,
533
+ channel: "bluebubbles",
534
+ };
535
+ }
536
+ function resolveGroupExternalId(event) {
537
+ return `group:${event.chat.chatGuid}`;
538
+ }
539
+ /**
540
+ * Check if any participant in a group chat is a known family member.
541
+ * Looks up each participant handle in the friend store.
542
+ */
543
+ async function checkGroupHasFamilyMember(store, event) {
544
+ if (!event.chat.isGroup)
545
+ return false;
546
+ for (const handle of event.chat.participantHandles) {
547
+ const friend = await store.findByExternalId("imessage-handle", handle);
548
+ if (friend?.trustLevel === "family")
549
+ return true;
550
+ }
551
+ return false;
552
+ }
553
+ /**
554
+ * Check if an acquaintance shares any group chat with a family member.
555
+ * Compares group-prefixed externalIds between the acquaintance and all family members.
556
+ */
557
+ async function checkHasExistingGroupWithFamily(store, senderFriend) {
558
+ const trustLevel = senderFriend.trustLevel ?? "friend";
559
+ if (trustLevel !== "acquaintance")
560
+ return false;
561
+ const acquaintanceGroups = new Set((senderFriend.externalIds ?? [])
562
+ .filter((eid) => eid.externalId.startsWith("group:"))
563
+ .map((eid) => eid.externalId));
564
+ if (acquaintanceGroups.size === 0)
565
+ return false;
566
+ const allFriends = await (store.listAll?.() ?? Promise.resolve([]));
567
+ for (const friend of allFriends) {
568
+ if (friend.trustLevel !== "family")
569
+ continue;
570
+ const friendGroups = (friend.externalIds ?? [])
571
+ .filter((eid) => eid.externalId.startsWith("group:"))
572
+ .map((eid) => eid.externalId);
573
+ for (const group of friendGroups) {
574
+ if (acquaintanceGroups.has(group))
575
+ return true;
576
+ }
577
+ }
578
+ return false;
579
+ }
580
+ function extractMessageText(content) {
581
+ if (typeof content === "string")
582
+ return content;
583
+ if (!Array.isArray(content))
584
+ return "";
585
+ return content
586
+ .map((part) => {
587
+ if (part && typeof part === "object" && "type" in part && part.type === "text" && typeof part.text === "string") {
588
+ return part.text;
589
+ }
590
+ return "";
591
+ })
592
+ .filter(Boolean)
593
+ .join("\n");
594
+ }
595
+ function isHistoricalLaneMetadataLine(line) {
596
+ return /^\[(conversation scope|recent active lanes|routing control):?/i.test(line)
597
+ || /^- (top_level|thread:[^:]+):/i.test(line);
598
+ }
599
+ function extractHistoricalLaneSummary(messages) {
600
+ const seen = new Set();
601
+ const summaries = [];
602
+ for (let index = messages.length - 1; index >= 0; index--) {
603
+ const message = messages[index];
604
+ if (message.role !== "user")
605
+ continue;
606
+ const text = extractMessageText(message.content);
607
+ if (!text)
608
+ continue;
609
+ const firstLine = text.split("\n")[0].trim();
610
+ const threadMatch = firstLine.match(/thread id: ([^\]|]+)/i);
611
+ const laneKey = threadMatch
612
+ ? `thread:${threadMatch[1].trim()}`
613
+ : /top[-_]level/i.test(firstLine)
614
+ ? "top_level"
615
+ : null;
616
+ if (!laneKey || seen.has(laneKey))
617
+ continue;
618
+ seen.add(laneKey);
619
+ const snippet = text
620
+ .split("\n")
621
+ .slice(1)
622
+ .map((line) => line.trim())
623
+ .find((line) => line.length > 0 && !isHistoricalLaneMetadataLine(line))
624
+ ?.slice(0, 80) ?? "(no recent text)";
625
+ summaries.push({
626
+ key: laneKey,
627
+ label: laneKey === "top_level" ? "top_level" : laneKey,
628
+ snippet,
629
+ });
630
+ if (summaries.length >= 5)
631
+ break;
632
+ }
633
+ return summaries;
634
+ }
635
+ // Whose words the replied-to message was: the agent's own account, the person replying, or someone else.
636
+ function repliedMessageAuthor(replied, actorExternalId) {
637
+ if (replied.fromMe)
638
+ return "agent";
639
+ return replied.senderAddress && replied.senderAddress === actorExternalId ? "person" : "other";
640
+ }
641
+ function buildBlueBubblesOrientationSource(event, existingMessages, evidence, conversationKind, repliedToText, repliedToAuthor) {
642
+ const repairNotice = event.repairNotice?.trim();
643
+ const actor = evidence.actor;
644
+ const participants = evidence.participants
645
+ .filter((participant) => !(participant.provider === actor.provider
646
+ && participant.externalId === actor.externalId))
647
+ .map((participant) => ({
648
+ role: "group_participant_only",
649
+ provider: participant.provider,
650
+ externalId: participant.externalId,
651
+ displayName: participant.displayName,
652
+ }));
653
+ const presentation = {
654
+ authority: "presentation_only",
655
+ conversationKind,
656
+ event: {
657
+ provider: evidence.provider,
658
+ kind: evidence.kind,
659
+ sourceEventType: evidence.sourceEventType,
660
+ fromMe: evidence.fromMe,
661
+ },
662
+ actor: {
663
+ role: "observed_actor",
664
+ provider: actor.provider,
665
+ externalId: actor.externalId,
666
+ displayName: actor.displayName,
667
+ },
668
+ participants,
669
+ };
670
+ const summaries = extractHistoricalLaneSummary(existingMessages);
671
+ const threadId = event.threadOriginatorGuid?.trim() || undefined;
672
+ const hasThreadRoute = !!threadId || summaries.some((summary) => summary.key.startsWith("thread:"));
673
+ return {
674
+ kind: "bluebubbles",
675
+ ...presentation,
676
+ lane: threadId ? "thread" : "top_level",
677
+ defaultReplyTarget: threadId ? "current_lane" : "top_level",
678
+ ...(threadId ? { threadId } : {}),
679
+ ...(repliedToText ? { replyingToText: repliedToText, ...(repliedToAuthor ? { replyingToAuthor: repliedToAuthor } : {}) } : {}),
680
+ ...(repairNotice ? { repairNotice } : {}),
681
+ ...(summaries.length > 0 ? { recentLanes: summaries } : {}),
682
+ ...(hasThreadRoute
683
+ ? { routingHint: "use set_reply_target to choose current_lane, top_level, or a listed thread before sending BlueBubbles-specific replies." }
684
+ : {}),
685
+ };
686
+ }
687
+ function buildInboundText(event) {
688
+ const baseText = event.textForAgent;
689
+ if (!event.chat.isGroup) {
690
+ return baseText;
691
+ }
692
+ return `${event.sender.displayName}: ${baseText}`;
693
+ }
694
+ function buildInboundContent(event) {
695
+ const text = buildInboundText(event);
696
+ if (!event.inputPartsForAgent || event.inputPartsForAgent.length === 0) {
697
+ return text;
698
+ }
699
+ return [
700
+ { type: "text", text },
701
+ ...event.inputPartsForAgent,
702
+ ];
703
+ }
704
+ function sessionUserMessageIndex(event, existingMessages) {
705
+ const fragment = event.textForAgent.trim();
706
+ if (!fragment)
707
+ return -1;
708
+ return existingMessages.findLastIndex((message) => (message.role === "user" && extractMessageText(message.content).includes(fragment)));
709
+ }
710
+ /**
711
+ * A turn saves the friend's message before the model runs, so the text alone
712
+ * does not prove the message was answered. Only a later assistant reply does;
713
+ * a proactive send recorded in the session afterwards does not count.
714
+ */
715
+ function sessionAlreadyAnsweredMessage(event, existingMessages) {
716
+ const index = sessionUserMessageIndex(event, existingMessages);
717
+ return index >= 0 && existingMessages.slice(index + 1).some((message) => (message.role === "assistant" && !(0, outbound_record_1.isRecordedOutboundText)(extractMessageText(message.content))));
718
+ }
719
+ /** Drop the unanswered copy a dead turn left at the tail, so the replay adds the message once. */
720
+ function withoutUnansweredTail(event, messages) {
721
+ return sessionUserMessageIndex(event, messages) === messages.length - 1
722
+ ? messages.slice(0, -1)
723
+ : messages;
724
+ }
725
+ function getBlueBubblesContinuityIngressTexts(event) {
726
+ const text = event.textForAgent.trim();
727
+ if (text.length > 0)
728
+ return [text];
729
+ const fallbackText = (event.inputPartsForAgent ?? [])
730
+ .map((part) => {
731
+ if (part.type === "text" && typeof part.text === "string") {
732
+ return part.text.trim();
733
+ }
734
+ return "";
735
+ })
736
+ .filter(Boolean)
737
+ .join("\n");
738
+ return fallbackText ? [fallbackText] : [];
739
+ }
740
+ function sha256Hex(input) {
741
+ return (0, node_crypto_1.createHash)("sha256").update(input).digest("hex");
742
+ }
743
+ function blueBubblesAutonomyTarget(event) {
744
+ return {
745
+ messageGuid: event.messageGuid,
746
+ sessionKeyHash: sha256Hex(event.chat.sessionKey),
747
+ chatGuidHash: event.chat.chatGuid ? sha256Hex(event.chat.chatGuid) : undefined,
748
+ chatIdentifierHash: event.chat.chatIdentifier ? sha256Hex(event.chat.chatIdentifier) : undefined,
749
+ };
750
+ }
751
+ function blueBubblesRecoveryStormInput(agentName, event, source) {
752
+ return {
753
+ agent: agentName,
754
+ triggerType: "recovery",
755
+ sourceKind: "sense",
756
+ senseOrHabit: "bluebubbles",
757
+ provider: "bluebubbles-recovery",
758
+ target: blueBubblesAutonomyTarget(event),
759
+ normalizedErrorName: "BlueBubblesRecoveryError",
760
+ normalizedErrorCode: "RECOVERY_FAILED",
761
+ codeLocation: `senses/bluebubbles/${source}`,
762
+ idempotencyBucket: `bluebubbles-recovery:${source}`,
763
+ };
764
+ }
765
+ function shouldUseBlueBubblesRecoveryBudget(source, options) {
766
+ return options.autonomyBudgetTrigger === "recovery"
767
+ || source === "mutation-recovery"
768
+ || source === "upstream-catchup"
769
+ || source === "recovery-bootstrap";
770
+ }
771
+ function shouldCountBlueBubblesRecoveryResultAsSkipped(reason) {
772
+ return reason === "already_processed"
773
+ || reason === "autonomy_budget_blocked"
774
+ || reason === "mutation_state_only"
775
+ || reason === "from_me";
776
+ }
777
+ function recordBlueBubblesRecoveryFailureForBudget(agentName, event, source) {
778
+ try {
779
+ (0, autonomy_budget_1.recordAutonomyFailure)((0, identity_1.getAgentRoot)(agentName), {
780
+ ...blueBubblesRecoveryStormInput(agentName, event, source),
781
+ });
782
+ }
783
+ catch {
784
+ // Autonomy failure accounting must not turn a recovery error into a broader sense outage.
785
+ }
786
+ }
787
+ function insertEphemeralContextMessages(messages, contextMessages, currentUserMessage) {
788
+ if (contextMessages.length === 0)
789
+ return messages;
790
+ const requiredCurrentIndex = currentUserMessage ? messages.indexOf(currentUserMessage) : -1;
791
+ const insertionIndex = requiredCurrentIndex >= 0 ? requiredCurrentIndex : Math.max(0, messages.length - 1);
792
+ return [
793
+ ...messages.slice(0, insertionIndex),
794
+ ...contextMessages,
795
+ ...messages.slice(insertionIndex),
796
+ ];
797
+ }
798
+ function knownProviderMessageTexts(messages) {
799
+ return messages
800
+ .map((message) => extractMessageText(message.content))
801
+ .map((text) => text.trim())
802
+ .filter((text) => text.length > 0);
803
+ }
804
+ async function buildBlueBubblesContextMessages(input) {
805
+ const event = input.event;
806
+ if (!Number.isFinite(event.timestamp))
807
+ return { messages: [], contextPacketIds: [] };
808
+ let result;
809
+ try {
810
+ result = await (0, context_packet_1.buildBlueBubblesContextPacket)({
811
+ agentName: input.agentName,
812
+ client: input.client,
813
+ event,
814
+ knownMessageTexts: knownProviderMessageTexts(input.knownMessages),
815
+ });
816
+ }
817
+ catch (error) {
818
+ (0, runtime_1.emitNervesEvent)({
819
+ level: "warn",
820
+ component: "senses",
821
+ event: "senses.bluebubbles_context_packet_error",
822
+ message: "failed to build live bluebubbles context packet",
823
+ meta: {
824
+ messageGuid: event.messageGuid,
825
+ reason: error instanceof Error ? error.message : String(error),
826
+ },
827
+ });
828
+ return { messages: [], contextPacketIds: [] };
829
+ }
830
+ if (!result)
831
+ return { messages: [], contextPacketIds: [] };
832
+ const { packet, optionalRendered, verifiedPredecessorMessage, historyCount } = result;
833
+ const prepared = {
834
+ messages: optionalRendered
835
+ ? [{ role: "system", content: optionalRendered.text }]
836
+ : [],
837
+ verifiedPredecessorMessage,
838
+ };
839
+ try {
840
+ (0, context_packet_ledger_1.writeSenseContextPacket)(input.agentRoot, packet);
841
+ (0, runtime_1.emitNervesEvent)({
842
+ component: "senses",
843
+ event: "senses.bluebubbles_context_packet_injected",
844
+ message: "injected bluebubbles same-chat context packet",
845
+ meta: {
846
+ packetId: packet.packetId,
847
+ messageGuid: event.messageGuid,
848
+ contextMessages: historyCount,
849
+ },
850
+ });
851
+ return {
852
+ ...prepared,
853
+ contextPacketIds: [packet.packetId],
854
+ };
855
+ }
856
+ catch (error) {
857
+ (0, runtime_1.emitNervesEvent)({
858
+ level: "warn",
859
+ component: "senses",
860
+ event: "senses.bluebubbles_context_packet_error",
861
+ message: "failed to build live bluebubbles context packet",
862
+ meta: {
863
+ messageGuid: event.messageGuid,
864
+ reason: error instanceof Error ? error.message : String(error),
865
+ },
866
+ });
867
+ return { ...prepared, contextPacketIds: [] };
868
+ }
869
+ }
870
+ function createReplyTargetController(event) {
871
+ const defaultTargetLabel = event.threadOriginatorGuid?.trim() ? "current_lane" : "top_level";
872
+ let selection = event.threadOriginatorGuid?.trim()
873
+ ? { target: "current_lane" }
874
+ : { target: "top_level" };
875
+ return {
876
+ getReplyToMessageGuid() {
877
+ if (selection.target === "top_level")
878
+ return undefined;
879
+ if (selection.target === "thread")
880
+ return selection.messageId.trim();
881
+ return event.threadOriginatorGuid?.trim() ? event.messageGuid : undefined;
882
+ },
883
+ setSelection(next) {
884
+ selection = next;
885
+ if (next.target === "top_level") {
886
+ return "bluebubbles reply target override: top_level";
887
+ }
888
+ if (next.target === "thread") {
889
+ return `bluebubbles reply target override: thread:${next.messageId}`;
890
+ }
891
+ return `bluebubbles reply target: using default for this turn (${defaultTargetLabel})`;
892
+ },
893
+ };
894
+ }
895
+ function emitBlueBubblesMarkReadWarning(chat, error) {
896
+ (0, runtime_1.emitNervesEvent)({
897
+ level: "warn",
898
+ component: "senses",
899
+ event: "senses.bluebubbles_mark_read_error",
900
+ message: "failed to mark bluebubbles chat as read",
901
+ meta: {
902
+ chatGuid: chat.chatGuid ?? null,
903
+ reason: error instanceof Error ? error.message : String(error),
904
+ },
905
+ });
906
+ }
907
+ function createBlueBubblesCallbacks(client, chat, replyTarget, isGroupChat, onVisibleActivity, options = {}) {
908
+ let textBuffer = "";
909
+ let typingActive = false;
910
+ let typingCouldBeActive = false;
911
+ let queue = Promise.resolve();
912
+ let outboundClosed = false;
913
+ let nextCleanupToken = 0;
914
+ const activeCleanupTokens = new Set();
915
+ const activeActivityControllers = new Set();
916
+ // Per-turn outward-send dedupe. A single createBlueBubblesCallbacks lifetime
917
+ // serves one inbound turn, so collapsing identical outward bodies inside
918
+ // this closure is scoped tightly: each fresh inbound turn starts with an
919
+ // empty set. Mid-turn settle/proof retry loops historically caused the
920
+ // agent to re-emit the same answer through multiple speak calls and a
921
+ // final flush, surfacing as 4 near-identical iMessages from one ask
922
+ // (2026-05-08 06:18 incident). The guard lets the engine retry harmlessly
923
+ // without duplicating outward delivery to the friend.
924
+ //
925
+ // PR #699 used exact whitespace+case-normalized match. Post-#699 evidence
926
+ // (2026-05-09 05:25 UTC, evt-001814 + evt-001818) showed two answers that
927
+ // start "yep — I looked it up… Assuming you mean AMC's The Audacity…" with
928
+ // substantially the same content but slight rephrasing — the LLM rewrites
929
+ // the same answer on a retry/recovery loop and bypasses an exact-match
930
+ // guard. We now also keep the original token sets so a fuzzy (Jaccard)
931
+ // check catches near-duplicates from the same turn.
932
+ const sentOutwardTextNorms = new Set();
933
+ const sentOutwardTokenSets = [];
934
+ async function canRunOutbound() {
935
+ if (outboundClosed)
936
+ return false;
937
+ if (options.isOutboundCurrent && !options.isOutboundCurrent())
938
+ return false;
939
+ if (options.admitOutbound && !await options.admitOutbound())
940
+ return false;
941
+ if (outboundClosed)
942
+ return false;
943
+ if (options.isOutboundCurrent && !options.isOutboundCurrent())
944
+ return false;
945
+ return true;
946
+ }
947
+ function enqueue(operation, task, enqueueOptions = {}) {
948
+ const cleanupToken = enqueueOptions.cleanupToken;
949
+ const controller = new AbortController();
950
+ activeActivityControllers.add(controller);
951
+ queue = queue
952
+ .then(async () => {
953
+ if (cleanupToken === undefined) {
954
+ if (!await canRunOutbound())
955
+ return;
956
+ }
957
+ else if (!activeCleanupTokens.has(cleanupToken)) {
958
+ return;
959
+ }
960
+ await withBlueBubblesActivityTimeout(operation, BLUEBUBBLES_ACTIVITY_OPERATION_TIMEOUT_MS, controller, task);
961
+ })
962
+ .catch((error) => {
963
+ if (controller.signal.aborted && !(error instanceof BlueBubblesActivityTimeoutError))
964
+ return;
965
+ (0, runtime_1.emitNervesEvent)({
966
+ level: "warn",
967
+ component: "senses",
968
+ event: "senses.bluebubbles_activity_error",
969
+ message: "bluebubbles activity transport failed",
970
+ meta: { operation, reason: error instanceof Error ? error.message : String(error) },
971
+ });
972
+ })
973
+ .finally(() => {
974
+ activeActivityControllers.delete(controller);
975
+ });
976
+ }
977
+ function abortActiveActivity(reason) {
978
+ for (const controller of activeActivityControllers) {
979
+ controller.abort(new Error(reason));
980
+ }
981
+ }
982
+ function enqueueTypingStop() {
983
+ typingActive = false;
984
+ const cleanupToken = ++nextCleanupToken;
985
+ activeCleanupTokens.add(cleanupToken);
986
+ enqueue("typing_stop", async (signal) => {
987
+ try {
988
+ await client.setTyping(chat, false, signal);
989
+ typingCouldBeActive = false;
990
+ }
991
+ finally {
992
+ activeCleanupTokens.delete(cleanupToken);
993
+ }
994
+ }, { cleanupToken });
995
+ }
996
+ function startTypingNow() {
997
+ /* v8 ignore next -- defensive guard: callers already check typingActive @preserve */
998
+ if (typingActive)
999
+ return;
1000
+ /* v8 ignore next -- defensive guard: public callback entrypoints already drop after outbound close @preserve */
1001
+ if (outboundClosed)
1002
+ return;
1003
+ typingActive = true;
1004
+ typingCouldBeActive = true;
1005
+ enqueue("typing_start", async (signal) => {
1006
+ const [markReadResult, typingResult] = await Promise.allSettled([
1007
+ client.markChatRead(chat, signal),
1008
+ client.setTyping(chat, true, signal),
1009
+ ]);
1010
+ if (markReadResult.status === "rejected") {
1011
+ emitBlueBubblesMarkReadWarning(chat, markReadResult.reason);
1012
+ }
1013
+ if (typingResult.status === "rejected") {
1014
+ throw typingResult.reason;
1015
+ }
1016
+ });
1017
+ }
1018
+ function recordVisibleActivity() {
1019
+ onVisibleActivity?.();
1020
+ }
1021
+ function isDuplicateOutwardText(trimmed) {
1022
+ const norm = trimmed.replace(/\s+/g, " ").trim().toLowerCase();
1023
+ if (sentOutwardTextNorms.has(norm))
1024
+ return true;
1025
+ // Fuzzy near-duplicate: when the same answer is rephrased between speak
1026
+ // and settle (or across two speak calls in a recovery loop), the exact
1027
+ // norm differs but token overlap is very high. We compare against every
1028
+ // already-sent body's token set; if any has Jaccard overlap >= the
1029
+ // threshold, treat as a duplicate. We require a minimum token count on
1030
+ // the new body so single-word replies ("yes", "ok") don't get suppressed
1031
+ // against any previous short one with shared tokens.
1032
+ const newTokens = tokenizeForDedupe(trimmed);
1033
+ if (newTokens.size >= NEAR_DUPLICATE_MIN_TOKENS) {
1034
+ for (const prevTokens of sentOutwardTokenSets) {
1035
+ if (prevTokens.size < NEAR_DUPLICATE_MIN_TOKENS)
1036
+ continue;
1037
+ if (jaccardSimilarity(newTokens, prevTokens) >= NEAR_DUPLICATE_JACCARD_THRESHOLD) {
1038
+ return true;
1039
+ }
1040
+ }
1041
+ }
1042
+ sentOutwardTextNorms.add(norm);
1043
+ sentOutwardTokenSets.push(newTokens);
1044
+ return false;
1045
+ }
1046
+ function emitDuplicateOutwardSuppressed(site, messageLength) {
1047
+ (0, runtime_1.emitNervesEvent)({
1048
+ level: "warn",
1049
+ component: "senses",
1050
+ event: "bluebubbles.duplicate_outward_suppressed",
1051
+ message: "suppressed near-identical outward send within single inbound turn",
1052
+ meta: {
1053
+ site,
1054
+ chatGuid: chat.chatGuid ?? null,
1055
+ messageLength,
1056
+ },
1057
+ });
1058
+ }
1059
+ return {
1060
+ settleOutputMode: "retractable_buffer",
1061
+ onModelStart() {
1062
+ if (outboundClosed)
1063
+ return;
1064
+ if (options.enableActivitySignals !== false && !isGroupChat)
1065
+ startTypingNow();
1066
+ (0, runtime_1.emitNervesEvent)({
1067
+ component: "senses",
1068
+ event: "senses.bluebubbles_turn_start",
1069
+ message: "bluebubbles turn started",
1070
+ meta: { chatGuid: chat.chatGuid ?? null },
1071
+ });
1072
+ },
1073
+ onModelStreamStart() {
1074
+ (0, runtime_1.emitNervesEvent)({
1075
+ component: "senses",
1076
+ event: "senses.bluebubbles_stream_start",
1077
+ message: "bluebubbles non-streaming response started",
1078
+ meta: {},
1079
+ });
1080
+ },
1081
+ onTextChunk(text) {
1082
+ if (outboundClosed)
1083
+ return;
1084
+ if (options.enableActivitySignals !== false && isGroupChat && !typingActive)
1085
+ startTypingNow();
1086
+ textBuffer += text;
1087
+ },
1088
+ onReasoningChunk(_text) { },
1089
+ onToolStart(name, _args) {
1090
+ if (outboundClosed)
1091
+ return;
1092
+ // Tool activity is a reply commitment, but iMessage is not a tool-progress
1093
+ // console. Keep the human-facing thread quiet until the agent has real
1094
+ // text, while preserving native read/typing signals and nerves telemetry
1095
+ // for debugging.
1096
+ if (options.enableActivitySignals !== false && !typingActive && name !== "observe" && name !== "speak")
1097
+ startTypingNow();
1098
+ (0, runtime_1.emitNervesEvent)({
1099
+ component: "senses",
1100
+ event: "senses.bluebubbles_tool_start",
1101
+ message: "bluebubbles tool execution started",
1102
+ meta: { name },
1103
+ });
1104
+ },
1105
+ onToolEnd(name, summary, success) {
1106
+ (0, runtime_1.emitNervesEvent)({
1107
+ component: "senses",
1108
+ event: "senses.bluebubbles_tool_end",
1109
+ message: "bluebubbles tool execution completed",
1110
+ meta: { name, success, summary },
1111
+ });
1112
+ },
1113
+ onError(error, severity) {
1114
+ (0, runtime_1.emitNervesEvent)({
1115
+ level: severity === "terminal" ? "error" : "warn",
1116
+ component: "senses",
1117
+ event: "senses.bluebubbles_turn_error",
1118
+ message: "bluebubbles turn callback error",
1119
+ meta: { severity, reason: error.message },
1120
+ });
1121
+ },
1122
+ onClearText() {
1123
+ textBuffer = "";
1124
+ },
1125
+ async flushNow() {
1126
+ if (outboundClosed) {
1127
+ textBuffer = "";
1128
+ return;
1129
+ }
1130
+ // Contract: throws if delivery fails. We deliberately let `client.sendText`
1131
+ // rejections propagate so the engine's speak interception can mark the
1132
+ // tool call as failed and tell the agent the message did not reach the
1133
+ // friend (rather than silently logging and pretending success).
1134
+ const trimmed = textBuffer.trim();
1135
+ if (!trimmed)
1136
+ return;
1137
+ textBuffer = "";
1138
+ if ((0, bluebubbles_meta_guard_1.containsInternalMetaMarkers)(trimmed)) {
1139
+ (0, bluebubbles_meta_guard_1.emitBluebubblesMetaBlocked)({
1140
+ site: "flushNow",
1141
+ message: "bluebubbles speak text blocked: internal meta markers",
1142
+ meta: {
1143
+ chatGuid: chat.chatGuid ?? null,
1144
+ messageLength: trimmed.length,
1145
+ },
1146
+ });
1147
+ return;
1148
+ }
1149
+ if (isDuplicateOutwardText(trimmed)) {
1150
+ emitDuplicateOutwardSuppressed("flushNow", trimmed.length);
1151
+ return;
1152
+ }
1153
+ if (!await canRunOutbound())
1154
+ return;
1155
+ // Count the message as seen once it is handed to the transport: a send
1156
+ // still in flight, or one that timed out, may reach the friend anyway, and
1157
+ // a turn that ends now must not be replayed into repeating it.
1158
+ recordVisibleActivity();
1159
+ await client.sendText({
1160
+ chat,
1161
+ text: trimmed,
1162
+ replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
1163
+ });
1164
+ // Note: do NOT call client.setTyping(chat, false) here — the agent is
1165
+ // still mid-turn, so the typing indicator stays ACTIVE.
1166
+ (0, runtime_1.emitNervesEvent)({
1167
+ component: "senses",
1168
+ event: "bluebubbles.speak_flush",
1169
+ message: "bluebubbles flushed mid-turn speak",
1170
+ meta: { messageLength: trimmed.length },
1171
+ });
1172
+ },
1173
+ async flush(flushOptions = {}) {
1174
+ if (outboundClosed) {
1175
+ textBuffer = "";
1176
+ await waitForBlueBubblesCallbackCleanup(queue, BLUEBUBBLES_CALLBACK_CLEANUP_TIMEOUT_MS, {
1177
+ operation: "flush_after_close",
1178
+ chatGuid: chat.chatGuid ?? null,
1179
+ });
1180
+ return { status: "not_invoked", reason: "closed" };
1181
+ }
1182
+ await queue;
1183
+ const trimmed = textBuffer.trim();
1184
+ if (!trimmed) {
1185
+ if (typingActive) {
1186
+ enqueueTypingStop();
1187
+ await queue;
1188
+ }
1189
+ return { status: "not_invoked", reason: "empty" };
1190
+ }
1191
+ textBuffer = "";
1192
+ /* v8 ignore next 4 -- branch: typing may already be stopped before flush @preserve */
1193
+ if (typingActive) {
1194
+ enqueueTypingStop();
1195
+ await queue;
1196
+ }
1197
+ if ((0, bluebubbles_meta_guard_1.containsInternalMetaMarkers)(trimmed)) {
1198
+ (0, bluebubbles_meta_guard_1.emitBluebubblesMetaBlocked)({
1199
+ site: "flush",
1200
+ message: "bluebubbles outbound text blocked: internal meta markers",
1201
+ meta: {
1202
+ chatGuid: chat.chatGuid ?? null,
1203
+ messageLength: trimmed.length,
1204
+ },
1205
+ });
1206
+ return { status: "not_invoked", reason: "blocked_meta" };
1207
+ }
1208
+ if (isDuplicateOutwardText(trimmed)) {
1209
+ emitDuplicateOutwardSuppressed("flush", trimmed.length);
1210
+ return { status: "not_invoked", reason: "duplicate" };
1211
+ }
1212
+ if (!await canRunOutbound())
1213
+ return { status: "not_invoked", reason: "not_current" };
1214
+ const replyToMessageGuid = replyTarget.getReplyToMessageGuid();
1215
+ const durableOutbound = options.durableOutbound;
1216
+ const durableTempGuid = durableOutbound
1217
+ ? `ouro-inbound-${(0, node_crypto_1.createHash)("sha256")
1218
+ .update(durableOutbound.idempotencyKey)
1219
+ .digest("hex")
1220
+ .slice(0, 32)}`
1221
+ : null;
1222
+ const boundaryState = { durableRecord: null, denialReason: "not_current" };
1223
+ const admitFinalTransport = () => {
1224
+ if (outboundClosed
1225
+ || (options.isOutboundCurrent && !options.isOutboundCurrent())
1226
+ || (options.isOutboundAdmittedNow && !options.isOutboundAdmittedNow())) {
1227
+ boundaryState.denialReason = "not_current";
1228
+ return false;
1229
+ }
1230
+ if (!durableOutbound || boundaryState.durableRecord)
1231
+ return true;
1232
+ const reservation = (0, outbound_state_1.reserveBlueBubblesOutbound)({
1233
+ agentRoot: durableOutbound.agentRoot,
1234
+ idempotencyKey: durableOutbound.idempotencyKey,
1235
+ chat,
1236
+ attachment: durableOutbound.attachment,
1237
+ text: trimmed,
1238
+ tempGuid: durableTempGuid,
1239
+ ...(replyToMessageGuid ? { replyToMessageGuid } : {}),
1240
+ });
1241
+ if (reservation.status !== "reserved") {
1242
+ boundaryState.denialReason = "durable_duplicate";
1243
+ return false;
1244
+ }
1245
+ boundaryState.durableRecord = reservation.record;
1246
+ return true;
1247
+ };
1248
+ const markDurableFailure = (error) => {
1249
+ const durableRecord = boundaryState.durableRecord;
1250
+ if (!durableRecord || !durableOutbound)
1251
+ return;
1252
+ try {
1253
+ (0, outbound_state_1.markBlueBubblesOutboundFailed)({
1254
+ agentRoot: durableOutbound.agentRoot,
1255
+ recordId: durableRecord.recordId,
1256
+ failedAt: new Date().toISOString(),
1257
+ reason: error instanceof Error ? error.message : String(error),
1258
+ });
1259
+ }
1260
+ catch (stateError) {
1261
+ (0, runtime_1.emitNervesEvent)({
1262
+ level: "error",
1263
+ component: "senses",
1264
+ event: "senses.bluebubbles_outbound_state_error",
1265
+ message: "failed to record bluebubbles outbound transport failure",
1266
+ meta: {
1267
+ recordId: durableRecord.recordId,
1268
+ reason: String(stateError),
1269
+ },
1270
+ });
1271
+ }
1272
+ };
1273
+ let response;
1274
+ while (true) {
1275
+ try {
1276
+ flushOptions.signal?.throwIfAborted();
1277
+ response = await client.sendText({
1278
+ chat,
1279
+ text: trimmed,
1280
+ replyToMessageGuid,
1281
+ ...(durableTempGuid ? { tempGuid: durableTempGuid } : {}),
1282
+ ...(flushOptions.signal ? { signal: flushOptions.signal } : {}),
1283
+ beforeTransportInvocation: admitFinalTransport,
1284
+ onTransportInvocation: options.onFinalTransportInvoked,
1285
+ });
1286
+ break;
1287
+ }
1288
+ catch (error) {
1289
+ if (error instanceof client_1.BlueBubblesSendError
1290
+ && error.transportInvoked === false
1291
+ && error.errorCode === "admission_denied") {
1292
+ if (boundaryState.denialReason === "durable_duplicate") {
1293
+ return { status: "not_invoked", reason: "durable_duplicate" };
1294
+ }
1295
+ // A newer observation may be only a temporary fence (duplicate,
1296
+ // audit-only, or otherwise non-promoting). Re-await admission and
1297
+ // retry the same durable reservation if this turn remains current.
1298
+ if (!await canRunOutbound()) {
1299
+ markDurableFailure(error);
1300
+ return { status: "not_invoked", reason: "not_current" };
1301
+ }
1302
+ continue;
1303
+ }
1304
+ markDurableFailure(error);
1305
+ throw error;
1306
+ }
1307
+ }
1308
+ const durableRecord = boundaryState.durableRecord;
1309
+ if (durableRecord && durableOutbound) {
1310
+ try {
1311
+ (0, outbound_state_1.markBlueBubblesOutboundAccepted)({
1312
+ agentRoot: durableOutbound.agentRoot,
1313
+ recordId: durableRecord.recordId,
1314
+ acceptedAt: new Date().toISOString(),
1315
+ ...(response.messageGuid ? { messageGuid: response.messageGuid } : {}),
1316
+ });
1317
+ }
1318
+ catch (stateError) {
1319
+ (0, runtime_1.emitNervesEvent)({
1320
+ level: "error",
1321
+ component: "senses",
1322
+ event: "senses.bluebubbles_outbound_state_error",
1323
+ message: "failed to record accepted bluebubbles outbound transport",
1324
+ meta: {
1325
+ recordId: durableRecord.recordId,
1326
+ reason: String(stateError),
1327
+ },
1328
+ });
1329
+ }
1330
+ }
1331
+ options.onFinalTransportAccepted?.();
1332
+ recordVisibleActivity();
1333
+ return { status: "accepted" };
1334
+ },
1335
+ async finish(options = {}) {
1336
+ const cleanupTimeoutMs = options.timeoutMs ?? BLUEBUBBLES_CALLBACK_CLEANUP_TIMEOUT_MS;
1337
+ const needsTypingStop = typingActive;
1338
+ if (needsTypingStop) {
1339
+ enqueueTypingStop();
1340
+ }
1341
+ const drained = await waitForBlueBubblesCallbackCleanup(queue, cleanupTimeoutMs, {
1342
+ operation: "finish",
1343
+ chatGuid: chat.chatGuid ?? null,
1344
+ });
1345
+ if (!drained) {
1346
+ // The queued start/read request may outlive this turn's bounded lane.
1347
+ // Invalidate its deferred stop, then issue one stop request now while A
1348
+ // still owns the canonical lock so B cannot start typing ahead of it.
1349
+ activeCleanupTokens.clear();
1350
+ abortActiveActivity("bluebubbles activity superseded by bounded cleanup");
1351
+ await waitForBlueBubblesCallbackCleanup(queue, cleanupTimeoutMs, {
1352
+ operation: "finish_after_activity_abort",
1353
+ chatGuid: chat.chatGuid ?? null,
1354
+ });
1355
+ }
1356
+ if (typingCouldBeActive) {
1357
+ const fallbackController = new AbortController();
1358
+ try {
1359
+ await withBlueBubblesActivityTimeout("typing_stop_fallback", cleanupTimeoutMs, fallbackController, (signal) => client.setTyping(chat, false, signal));
1360
+ typingCouldBeActive = false;
1361
+ }
1362
+ catch (error) {
1363
+ (0, runtime_1.emitNervesEvent)({
1364
+ level: "warn",
1365
+ component: "senses",
1366
+ event: "senses.bluebubbles_activity_error",
1367
+ message: "bluebubbles activity transport failed",
1368
+ meta: {
1369
+ operation: "typing_stop_fallback",
1370
+ reason: error instanceof Error ? error.message : String(error),
1371
+ },
1372
+ });
1373
+ }
1374
+ }
1375
+ activeCleanupTokens.clear();
1376
+ },
1377
+ cancelOutbound(reason) {
1378
+ outboundClosed = true;
1379
+ textBuffer = "";
1380
+ abortActiveActivity(`bluebubbles outbound ${reason}`);
1381
+ (0, runtime_1.emitNervesEvent)({
1382
+ level: "warn",
1383
+ component: "senses",
1384
+ event: "senses.bluebubbles_outbound_closed",
1385
+ message: "bluebubbles outbound callbacks closed for timed-out turn",
1386
+ meta: { chatGuid: chat.chatGuid ?? null, reason },
1387
+ });
1388
+ },
1389
+ };
1390
+ }
1391
+ async function readRequestBody(req) {
1392
+ let body = "";
1393
+ for await (const chunk of req) {
1394
+ body += chunk.toString();
1395
+ }
1396
+ return body;
1397
+ }
1398
+ function writeJson(res, statusCode, payload) {
1399
+ res.statusCode = statusCode;
1400
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1401
+ res.end(JSON.stringify(payload));
1402
+ }
1403
+ function writeSemanticCaptureFailure(res) {
1404
+ res.statusCode = 503;
1405
+ res.setHeader("Content-Type", "application/json");
1406
+ res.end('{"ok":false,"error":"semantic_capture_failed"}');
1407
+ }
1408
+ function isWebhookPasswordValid(url, expectedPassword) {
1409
+ const provided = url.searchParams.get("password");
1410
+ return !provided || provided === expectedPassword;
1411
+ }
1412
+ function normalizeHandleForSelfMatch(handle) {
1413
+ const trimmed = handle.trim().toLowerCase();
1414
+ if (!trimmed)
1415
+ return "";
1416
+ // Phone-shaped: strip everything but digits so +1 (415) 555-... matches 14155550000.
1417
+ if (/[+\d]/.test(trimmed) && !trimmed.includes("@")) {
1418
+ const digits = trimmed.replace(/\D/g, "");
1419
+ if (digits.length >= 7)
1420
+ return digits;
1421
+ }
1422
+ return trimmed;
1423
+ }
1424
+ function isAgentSelfHandle(senderExternalId, ownHandles) {
1425
+ if (!senderExternalId || !senderExternalId.trim())
1426
+ return false;
1427
+ const target = normalizeHandleForSelfMatch(senderExternalId);
1428
+ /* v8 ignore start -- target is non-empty by construction since senderExternalId was just verified non-whitespace */
1429
+ if (!target)
1430
+ return false;
1431
+ /* v8 ignore stop */
1432
+ for (const own of ownHandles) {
1433
+ if (normalizeHandleForSelfMatch(own) === target)
1434
+ return true;
1435
+ }
1436
+ return false;
1437
+ }
1438
+ /**
1439
+ * In-memory store of agent iMessage handles auto-discovered from group-chat
1440
+ * `event.fromMe === true` events. Bluebubbles can attribute the peer's handle
1441
+ * as `event.sender.externalId` on 1:1 outbound messages, so discovery is
1442
+ * intentionally limited to the group echo bug that motivated
1443
+ * `bluebubbles.ownHandles` originally.
1444
+ *
1445
+ * Per-process. A daemon restart re-learns from the next outbound. The
1446
+ * accompanying nerves event (`senses.bluebubbles_own_handle_discovered`)
1447
+ * tells the operator what to add to `bluebubbles.ownHandles` for cross-
1448
+ * restart durability.
1449
+ */
1450
+ const discoveredOwnHandles = new Set();
1451
+ function getDiscoveredOwnHandles() {
1452
+ return [...discoveredOwnHandles];
1453
+ }
1454
+ function clearDiscoveredOwnHandles() {
1455
+ discoveredOwnHandles.clear();
1456
+ }
1457
+ function recordDiscoveredOwnHandle(senderExternalId) {
1458
+ if (!senderExternalId || !senderExternalId.trim())
1459
+ return false;
1460
+ const trimmed = senderExternalId.trim();
1461
+ const normalized = normalizeHandleForSelfMatch(trimmed);
1462
+ /* v8 ignore next -- defensive: normalizeHandleForSelfMatch only returns falsy for empty input, already guarded above @preserve */
1463
+ if (!normalized)
1464
+ return false;
1465
+ for (const existing of discoveredOwnHandles) {
1466
+ if (normalizeHandleForSelfMatch(existing) === normalized)
1467
+ return false;
1468
+ }
1469
+ discoveredOwnHandles.add(trimmed);
1470
+ (0, runtime_1.emitNervesEvent)({
1471
+ level: "info",
1472
+ component: "senses",
1473
+ event: "senses.bluebubbles_own_handle_discovered",
1474
+ message: "captured a new agent-owned bluebubbles handle from an isFromMe outbound — add to bluebubbles.ownHandles for cross-restart durability",
1475
+ meta: { handle: trimmed, totalDiscovered: discoveredOwnHandles.size },
1476
+ });
1477
+ return true;
1478
+ }
1479
+ function isSelfFriendRecord(friend, agentName) {
1480
+ if (!friend || friend.kind !== "agent")
1481
+ return false;
1482
+ const normalizedAgent = agentName.trim().toLowerCase();
1483
+ const name = friend.name?.trim().toLowerCase();
1484
+ const bundleName = friend.agentMeta?.bundleName?.trim().toLowerCase();
1485
+ return name === normalizedAgent || bundleName === normalizedAgent;
1486
+ }
1487
+ async function shouldFilterAgentSelfHandle(event, resolvedDeps) {
1488
+ if (!event.chat.isGroup)
1489
+ return false;
1490
+ if (!isAgentSelfHandle(event.sender.externalId, resolvedDeps.getOwnHandles()))
1491
+ return false;
1492
+ const store = resolvedDeps.createFriendStore();
1493
+ const knownFriend = await store
1494
+ .findByExternalId("imessage-handle", event.sender.externalId)
1495
+ .catch(() => null);
1496
+ if (knownFriend && !isSelfFriendRecord(knownFriend, resolvedDeps.getAgentName())) {
1497
+ (0, runtime_1.emitNervesEvent)({
1498
+ level: "warn",
1499
+ component: "senses",
1500
+ event: "senses.bluebubbles_self_handle_bypassed_known_friend",
1501
+ message: "did not filter bluebubbles sender even though it matched ownHandles because it resolves to a known non-self friend",
1502
+ meta: {
1503
+ messageGuid: event.messageGuid,
1504
+ kind: event.kind,
1505
+ senderExternalId: event.sender.externalId,
1506
+ friendId: knownFriend.id,
1507
+ },
1508
+ });
1509
+ return false;
1510
+ }
1511
+ return true;
1512
+ }
1513
+ function createBlueBubblesTurnStage(sessionKey) {
1514
+ return {
1515
+ failoverState: structuredClone(bbFailoverStates.get(sessionKey) ?? { pending: null }),
1516
+ };
1517
+ }
1518
+ function persistAcceptedBlueBubblesProjection(input) {
1519
+ const { stage, deps, event } = input;
1520
+ if (stage.postTurn) {
1521
+ try {
1522
+ deps.postTurnPersist(stage.postTurn.sessionPath, stage.postTurn.prepared, stage.postTurn.usage, stage.postTurn.state);
1523
+ }
1524
+ catch (error) {
1525
+ (0, runtime_1.emitNervesEvent)({
1526
+ level: "error",
1527
+ component: "senses",
1528
+ event: "senses.bluebubbles_accepted_projection_failed",
1529
+ message: "accepted bluebubbles reply could not be projected into canonical session history",
1530
+ meta: {
1531
+ messageGuid: event.messageGuid,
1532
+ sessionKey: event.chat.sessionKey,
1533
+ reason: error instanceof Error ? error.message : String(error),
1534
+ },
1535
+ });
1536
+ }
1537
+ }
1538
+ }
1539
+ function promoteAcceptedBlueBubblesAncillaryState(input) {
1540
+ const { stage, deps, agentName, event, source } = input;
1541
+ try {
1542
+ deps.promoteFailoverState(event.chat.sessionKey, stage.failoverState);
1543
+ }
1544
+ catch (error) {
1545
+ (0, runtime_1.emitNervesEvent)({
1546
+ level: "warn",
1547
+ component: "senses",
1548
+ event: "senses.bluebubbles_failover_state_promotion_failed",
1549
+ message: "accepted bluebubbles reply could not promote staged failover state",
1550
+ meta: {
1551
+ messageGuid: event.messageGuid,
1552
+ sessionKey: event.chat.sessionKey,
1553
+ reason: error instanceof Error ? error.message : String(error),
1554
+ },
1555
+ });
1556
+ }
1557
+ if (stage.tokens) {
1558
+ const emitTokenPromotionFailure = (error) => {
1559
+ (0, runtime_1.emitNervesEvent)({
1560
+ level: "warn",
1561
+ component: "senses",
1562
+ event: "senses.bluebubbles_token_promotion_failed",
1563
+ message: "accepted bluebubbles reply could not promote staged token usage",
1564
+ meta: {
1565
+ messageGuid: event.messageGuid,
1566
+ sessionKey: event.chat.sessionKey,
1567
+ reason: error instanceof Error ? error.message : String(error),
1568
+ },
1569
+ });
1570
+ };
1571
+ try {
1572
+ void deps.accumulateFriendTokens(stage.tokens.store, stage.tokens.friendId, stage.tokens.usage).catch(emitTokenPromotionFailure);
1573
+ }
1574
+ catch (error) {
1575
+ emitTokenPromotionFailure(error);
1576
+ }
1577
+ }
1578
+ try {
1579
+ deps.recordProcessed(agentName, event, source, input.processedOutcome);
1580
+ }
1581
+ catch (error) {
1582
+ (0, runtime_1.emitNervesEvent)({
1583
+ level: "warn",
1584
+ component: "senses",
1585
+ event: "senses.bluebubbles_processed_promotion_failed",
1586
+ message: "accepted bluebubbles reply could not promote processed sidecar state",
1587
+ meta: {
1588
+ messageGuid: event.messageGuid,
1589
+ sessionKey: event.chat.sessionKey,
1590
+ reason: error instanceof Error ? error.message : String(error),
1591
+ },
1592
+ });
1593
+ }
1594
+ }
1595
+ function hasObservedBlueBubblesDirection(event) {
1596
+ return typeof event.fromMe === "boolean";
1597
+ }
1598
+ /**
1599
+ * Waits for permission to send. After a minute it marks the live turn as
1600
+ * stalled, so `ouro status` reports it, and clears the mark once it resumes.
1601
+ */
1602
+ async function awaitBlueBubblesDeliveryAdmission(agentName, turnId, event, capability, signal) {
1603
+ const waitingSince = Date.now();
1604
+ let stalled = false;
1605
+ const stalledTimer = setTimeout(() => {
1606
+ stalled = true;
1607
+ (0, active_turns_1.noteBlueBubblesActiveTurnAdmissionWait)(agentName, turnId, new Date(waitingSince).toISOString());
1608
+ (0, runtime_1.emitNervesEvent)({
1609
+ level: "warn",
1610
+ component: "senses",
1611
+ event: "senses.bluebubbles_delivery_admission_stalled",
1612
+ message: "bluebubbles reply has waited over a minute for permission to send",
1613
+ meta: {
1614
+ messageGuid: event.messageGuid,
1615
+ sessionKey: event.chat.sessionKey,
1616
+ waitedMs: Date.now() - waitingSince,
1617
+ },
1618
+ });
1619
+ }, active_turns_1.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS);
1620
+ /* v8 ignore next -- timer handles expose unref only in some runtimes @preserve */
1621
+ if (typeof stalledTimer.unref === "function") {
1622
+ stalledTimer.unref();
1623
+ }
1624
+ try {
1625
+ return await (0, latest_turn_1.awaitDeliveryAdmission)(capability, signal);
1626
+ }
1627
+ finally {
1628
+ clearTimeout(stalledTimer);
1629
+ if (stalled)
1630
+ (0, active_turns_1.noteBlueBubblesActiveTurnAdmissionWait)(agentName, turnId, null);
1631
+ }
1632
+ }
1633
+ function emitBlueBubblesDeliveryAdmissionTimeout(event, source) {
1634
+ (0, runtime_1.emitNervesEvent)({
1635
+ level: "error",
1636
+ component: "senses",
1637
+ event: "senses.bluebubbles_delivery_admission_timeout",
1638
+ message: "bluebubbles turn gave up waiting for permission to send; the message stays pending for recovery",
1639
+ meta: {
1640
+ messageGuid: event.messageGuid,
1641
+ sessionKey: event.chat.sessionKey,
1642
+ source,
1643
+ },
1644
+ });
1645
+ }
1646
+ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, options) {
1647
+ options.lifecycleSignal?.throwIfAborted();
1648
+ const client = resolvedDeps.createClient();
1649
+ const agentName = resolvedDeps.getAgentName();
1650
+ (0, runtime_cwd_1.recoverRuntimeCwd)();
1651
+ let activeTurnId = null;
1652
+ if (shouldUseBlueBubblesRecoveryBudget(source, options)) {
1653
+ const decision = (0, autonomy_budget_1.reserveAutonomyBudget)((0, identity_1.getAgentRoot)(agentName), {
1654
+ agent: agentName,
1655
+ triggerType: "recovery",
1656
+ sourceKind: "sense",
1657
+ senseOrHabit: "bluebubbles",
1658
+ target: blueBubblesAutonomyTarget(event),
1659
+ idempotencyKey: `bluebubbles-recovery:${source}:${event.messageGuid}`,
1660
+ storm: blueBubblesRecoveryStormInput(agentName, event, source),
1661
+ });
1662
+ if (!decision.allowed) {
1663
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "autonomy_budget_blocked" };
1664
+ }
1665
+ }
1666
+ try {
1667
+ // Reserve the canonical chat lane before any asynchronous adapter setup.
1668
+ // Every admitted inbound is projected in observation order even when a
1669
+ // newer turn supersedes its inference before provider work begins.
1670
+ return await (0, turn_coordinator_1.withSharedTurnLock)("bluebubbles", `${agentName}:${event.chat.sessionKey}`, async () => {
1671
+ options.lifecycleSignal?.throwIfAborted();
1672
+ // Fallback self-detection: BlueBubbles sometimes broadcasts a group-chat
1673
+ // outbound message back through the webhook with `isFromMe` missing/false.
1674
+ // Keep this group-only: stale ownHandles entries must not hide real DMs.
1675
+ if (await shouldFilterAgentSelfHandle(event, resolvedDeps)) {
1676
+ (0, runtime_1.emitNervesEvent)({
1677
+ level: "warn",
1678
+ component: "senses",
1679
+ event: "senses.bluebubbles_self_handle_filtered",
1680
+ message: "filtered bluebubbles event whose sender matched an agent-owned handle (isFromMe was missing/false)",
1681
+ meta: {
1682
+ messageGuid: event.messageGuid,
1683
+ kind: event.kind,
1684
+ senderExternalId: event.sender.externalId,
1685
+ },
1686
+ });
1687
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "from_me" };
1688
+ }
1689
+ options.lifecycleSignal?.throwIfAborted();
1690
+ // ── Adapter setup: friend, session, content, callbacks ────────
1691
+ const store = resolvedDeps.createFriendStore();
1692
+ const resolver = resolvedDeps.createFriendResolver(store, resolveFriendParams(event));
1693
+ const baseContext = await resolver.resolve();
1694
+ options.lifecycleSignal?.throwIfAborted();
1695
+ const context = { ...baseContext, isGroupChat: event.chat.isGroup };
1696
+ const replyTarget = createReplyTargetController(event);
1697
+ const friendId = context.friend.id;
1698
+ const sessPath = resolvedDeps.sessionPath(friendId, "bluebubbles", event.chat.sessionKey);
1699
+ return await resolvedDeps.withSessionTurnLease(sessPath, async (sessionTurnLease) => {
1700
+ // Messages sent into this chat while another turn held it wait outside the session; they go in first, and again when this turn ends.
1701
+ (0, outbound_record_1.drainOutboundRecords)((0, identity_1.getAgentRoot)(), friendId, "bluebubbles", event.chat.sessionKey, sessionTurnLease);
1702
+ try {
1703
+ try {
1704
+ (0, session_cleanup_1.findObsoleteBlueBubblesThreadSessions)(sessPath);
1705
+ }
1706
+ catch (error) {
1707
+ (0, runtime_1.emitNervesEvent)({
1708
+ level: "warn",
1709
+ component: "senses",
1710
+ event: "senses.bluebubbles_thread_lane_cleanup_error",
1711
+ message: "failed to inspect obsolete bluebubbles thread-lane sessions",
1712
+ meta: {
1713
+ sessionPath: sessPath,
1714
+ reason: error instanceof Error ? error.message : String(error),
1715
+ },
1716
+ });
1717
+ }
1718
+ // Pre-load session inside the canonical turn lock so same-chat
1719
+ // deliveries cannot race on stale trunk state.
1720
+ const existing = resolvedDeps.loadSession(sessPath);
1721
+ const replaying = options.semanticRecovery || source !== "webhook";
1722
+ const sessionMessages = existing?.messages && existing.messages.length > 0
1723
+ ? structuredClone(replaying ? withoutUnansweredTail(event, existing.messages) : existing.messages)
1724
+ : [{ role: "system", content: (0, prompt_1.flattenSystemPrompt)(await resolvedDeps.buildSystem("bluebubbles", {}, context)) }];
1725
+ // Record EARLY for audit and crash recovery. This is capture truth, not
1726
+ // a claim that the agent turn completed successfully.
1727
+ const inboundSource = replaying && sessionAlreadyAnsweredMessage(event, existing?.messages ?? sessionMessages)
1728
+ ? "recovery-bootstrap"
1729
+ : source;
1730
+ (0, inbound_log_1.recordBlueBubblesInbound)(agentName, event, inboundSource);
1731
+ if (inboundSource === "recovery-bootstrap") {
1732
+ (0, runtime_1.emitNervesEvent)({
1733
+ component: "senses",
1734
+ event: "senses.bluebubbles_recovery_skip",
1735
+ message: "skipped bluebubbles recovery because the session already contains the message text",
1736
+ meta: {
1737
+ messageGuid: event.messageGuid,
1738
+ sessionKey: event.chat.sessionKey,
1739
+ source,
1740
+ },
1741
+ });
1742
+ (0, processed_log_1.recordProcessedBlueBubblesMessage)(agentName, event, inboundSource, "session-bootstrap");
1743
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "already_processed" };
1744
+ }
1745
+ // The inbound event is canonical truth as soon as its canonical lane is
1746
+ // reserved. Persist it before any supersedable orientation/provider work.
1747
+ const priorMessages = sessionMessages;
1748
+ const userMessage = {
1749
+ role: "user",
1750
+ content: buildInboundContent(event),
1751
+ };
1752
+ resolvedDeps.saveSession(sessPath, [...structuredClone(sessionMessages), structuredClone(userMessage)], existing?.lastUsage, existing?.state);
1753
+ const liveTurnId = (0, active_turns_1.beginBlueBubblesActiveTurn)(agentName, event);
1754
+ activeTurnId = liveTurnId;
1755
+ // Waiting for permission to send is bounded by the turn deadline and shutdown.
1756
+ const admissionDeadline = new AbortController();
1757
+ const admissionDeadlineTimer = setTimeout(() => {
1758
+ admissionDeadline.abort(new Error("delivery_admission_timeout"));
1759
+ }, options.timeoutMs ?? BLUEBUBBLES_TURN_TIMEOUT_MS);
1760
+ let admitted;
1761
+ try {
1762
+ admitted = await awaitBlueBubblesDeliveryAdmission(agentName, liveTurnId, event, options.latestTurnCapability, options.lifecycleSignal
1763
+ ? AbortSignal.any([options.lifecycleSignal, admissionDeadline.signal])
1764
+ : admissionDeadline.signal);
1765
+ }
1766
+ catch (error) {
1767
+ if (options.lifecycleSignal?.aborted)
1768
+ throw error;
1769
+ emitBlueBubblesDeliveryAdmissionTimeout(event, source);
1770
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "delivery_admission_timeout" };
1771
+ }
1772
+ finally {
1773
+ clearTimeout(admissionDeadlineTimer);
1774
+ }
1775
+ if (!admitted || !(0, latest_turn_1.isCurrent)(options.latestTurnCapability)) {
1776
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "superseded" };
1777
+ }
1778
+ options.lifecycleSignal?.throwIfAborted();
1779
+ const mcpOwner = { agentName, agentRoot: (0, identity_1.getAgentRoot)(agentName) };
1780
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)(mcpOwner) ?? undefined;
1781
+ if (event.chat.isGroup) {
1782
+ await (0, friends_1.upsertGroupContextParticipants)({
1783
+ store,
1784
+ participants: event.chat.participantHandles.map((externalId) => ({
1785
+ provider: "imessage-handle",
1786
+ externalId,
1787
+ })),
1788
+ groupExternalId: resolveGroupExternalId(event),
1789
+ });
1790
+ }
1791
+ // Fetch the text of the message being replied to (if this is a threaded reply)
1792
+ const threadGuid = event.threadOriginatorGuid?.trim();
1793
+ let repliedToText = null;
1794
+ let repliedToAuthor;
1795
+ if (threadGuid) {
1796
+ if (client.getRepliedMessage) {
1797
+ const replied = await client.getRepliedMessage(threadGuid).catch(() => null);
1798
+ repliedToText = replied?.text ?? null;
1799
+ repliedToAuthor = replied ? repliedMessageAuthor(replied, options.orientationEvidence.actor.externalId) : undefined;
1800
+ }
1801
+ else {
1802
+ repliedToText = await client.getMessageText(threadGuid).catch(() => null);
1803
+ }
1804
+ (0, runtime_1.emitNervesEvent)({
1805
+ component: "senses",
1806
+ event: "senses.bluebubbles_reply_context",
1807
+ message: repliedToText ? "fetched replied-to message text" : "could not fetch replied-to message text",
1808
+ meta: { threadGuid, hasText: !!repliedToText },
1809
+ });
1810
+ }
1811
+ // Shutdown can land during MCP/group/reply-context awaits above. Recheck
1812
+ // before the remaining synchronous setup installs its lifecycle listener.
1813
+ options.lifecycleSignal?.throwIfAborted();
1814
+ const orientationFrame = (0, orientation_frame_1.buildOrientationFrame)({
1815
+ channel: "bluebubbles",
1816
+ messages: [...priorMessages, userMessage],
1817
+ currentUserMessages: [userMessage],
1818
+ structuredOutputs: existing?.structuredOutputs ?? [],
1819
+ source: buildBlueBubblesOrientationSource(event, priorMessages, options.orientationEvidence, options.orientationConversationKind, repliedToText, repliedToAuthor),
1820
+ });
1821
+ if (!(0, latest_turn_1.isCurrent)(options.latestTurnCapability)) {
1822
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "superseded" };
1823
+ }
1824
+ const turnStage = createBlueBubblesTurnStage(event.chat.sessionKey);
1825
+ let finalTransportInvoked = false;
1826
+ let finalTransportAccepted = false;
1827
+ let spokeBeforeFinalTransport = false;
1828
+ const outboundRuntimeConfig = (0, config_1.getBlueBubblesConfig)();
1829
+ // Aborted on the turn deadline, supersession and shutdown before the final send.
1830
+ const controller = new AbortController();
1831
+ const callbacks = createBlueBubblesCallbacks(client, event.chat, replyTarget, event.chat.isGroup, () => {
1832
+ spokeBeforeFinalTransport = true;
1833
+ (0, active_turns_1.noteBlueBubblesActiveTurnVisibleActivity)(agentName, liveTurnId);
1834
+ }, {
1835
+ admitOutbound: async () => (!options.lifecycleSignal?.aborted
1836
+ && await awaitBlueBubblesDeliveryAdmission(agentName, liveTurnId, event, options.latestTurnCapability, controller.signal)
1837
+ && !options.lifecycleSignal?.aborted),
1838
+ isOutboundCurrent: () => (!options.lifecycleSignal?.aborted
1839
+ && (0, latest_turn_1.isCurrent)(options.latestTurnCapability)),
1840
+ isOutboundAdmittedNow: () => (!options.lifecycleSignal?.aborted
1841
+ && (0, latest_turn_1.isDeliveryAdmittedNow)(options.latestTurnCapability)),
1842
+ onFinalTransportInvoked: () => {
1843
+ finalTransportInvoked = true;
1844
+ },
1845
+ onFinalTransportAccepted: () => {
1846
+ finalTransportAccepted = true;
1847
+ },
1848
+ durableOutbound: {
1849
+ agentRoot: (0, identity_1.getAgentRoot)(),
1850
+ idempotencyKey: blueBubblesInboundReplyIdempotencyKey(options.currentIngressEvidence.captureKeyHash),
1851
+ attachment: {
1852
+ serverUrl: outboundRuntimeConfig.serverUrl,
1853
+ accountId: outboundRuntimeConfig.accountId,
1854
+ },
1855
+ },
1856
+ });
1857
+ const lifecycleSignal = options.lifecycleSignal;
1858
+ let rejectLifecycle;
1859
+ const lifecyclePromise = new Promise((_resolve, reject) => {
1860
+ rejectLifecycle = reject;
1861
+ });
1862
+ let resolveSupersession;
1863
+ const supersessionPromise = new Promise((resolve) => {
1864
+ resolveSupersession = resolve;
1865
+ });
1866
+ const cancelForSupersession = () => {
1867
+ callbacks.cancelOutbound("superseded");
1868
+ if (!finalTransportInvoked) {
1869
+ controller.abort(options.latestTurnCapability.signal.reason);
1870
+ resolveSupersession({
1871
+ handled: true,
1872
+ notifiedAgent: false,
1873
+ kind: event.kind,
1874
+ reason: "superseded",
1875
+ });
1876
+ }
1877
+ };
1878
+ options.latestTurnCapability.signal.addEventListener("abort", cancelForSupersession, { once: true });
1879
+ const cancelForShutdown = () => {
1880
+ callbacks.cancelOutbound("shutdown");
1881
+ if (!finalTransportInvoked) {
1882
+ const reason = lifecycleSignal.reason;
1883
+ controller.abort(reason);
1884
+ // A turn the friend already heard from must not replay in the next
1885
+ // process; end it with a result so it is recorded instead.
1886
+ if (spokeBeforeFinalTransport && resolveTimeout) {
1887
+ options.publishSpokenTurnEnded("shutdown");
1888
+ resolveTimeout({ handled: true, notifiedAgent: false, kind: event.kind, reason: "shutdown", spokeBeforeEnd: true });
1889
+ }
1890
+ else {
1891
+ rejectLifecycle(reason);
1892
+ }
1893
+ }
1894
+ };
1895
+ lifecycleSignal?.addEventListener("abort", cancelForShutdown, { once: true });
1896
+ let timeoutTimer;
1897
+ let timeoutPromise;
1898
+ let resolveTimeout;
1899
+ let recoveryTimedOut = false;
1900
+ let activeRunTurn = null;
1901
+ // BB-specific tool context wrappers
1902
+ const summarize = (0, core_1.createSummarize)("human");
1903
+ const bbCapabilities = (0, friends_1.getChannelCapabilities)("bluebubbles");
1904
+ const pendingDir = (0, pending_1.getPendingDir)(resolvedDeps.getAgentName(), friendId, "bluebubbles", event.chat.sessionKey);
1905
+ // Buffer terminal errors so failover can suppress them.
1906
+ // If failover produces a message, the buffered error is skipped.
1907
+ // If failover doesn't fire, the buffered error is replayed.
1908
+ let bufferedTerminalError = null;
1909
+ /* v8 ignore start -- failover-aware error buffering @preserve */
1910
+ const failoverAwareCallbacks = {
1911
+ ...callbacks,
1912
+ onError(error, severity) {
1913
+ if (severity === "terminal") {
1914
+ bufferedTerminalError = error;
1915
+ return;
1916
+ }
1917
+ callbacks.onError(error, severity);
1918
+ },
1919
+ };
1920
+ /* v8 ignore stop */
1921
+ try {
1922
+ // ── Compute trust gate context for group/acquaintance rules ─────
1923
+ // These store reads can block on filesystem I/O. Race them against the
1924
+ // runtime lifecycle before constructing the shared pipeline so a closed
1925
+ // worker cannot begin new durable or outward work after the read settles.
1926
+ const trustContext = await Promise.race([
1927
+ Promise.all([
1928
+ checkGroupHasFamilyMember(store, event),
1929
+ event.chat.isGroup
1930
+ ? Promise.resolve(false)
1931
+ : checkHasExistingGroupWithFamily(store, context.friend),
1932
+ ]),
1933
+ lifecyclePromise,
1934
+ supersessionPromise.then(() => null),
1935
+ ]);
1936
+ if (trustContext === null) {
1937
+ return {
1938
+ handled: true,
1939
+ notifiedAgent: false,
1940
+ kind: event.kind,
1941
+ reason: "superseded",
1942
+ };
1943
+ }
1944
+ const [groupHasFamilyMember, hasExistingGroupWithFamily] = trustContext;
1945
+ lifecycleSignal?.throwIfAborted();
1946
+ // ── Call shared pipeline ────────────────────────────────────────
1947
+ const timeoutMs = options.timeoutMs ?? BLUEBUBBLES_TURN_TIMEOUT_MS;
1948
+ timeoutPromise = new Promise((resolve) => {
1949
+ resolveTimeout = resolve;
1950
+ });
1951
+ timeoutTimer = setTimeout(() => {
1952
+ const reason = new BlueBubblesRecoveryTurnTimeoutError(timeoutMs);
1953
+ recoveryTimedOut = true;
1954
+ if (!finalTransportInvoked) {
1955
+ if (spokeBeforeFinalTransport)
1956
+ options.publishSpokenTurnEnded("turn_timeout");
1957
+ resolveTimeout?.({
1958
+ handled: true,
1959
+ notifiedAgent: false,
1960
+ kind: event.kind,
1961
+ reason: "turn_timeout",
1962
+ spokeBeforeEnd: spokeBeforeFinalTransport,
1963
+ });
1964
+ }
1965
+ callbacks.cancelOutbound("turn_timeout");
1966
+ (0, latest_turn_1.cancel)(options.latestTurnCapability, "turn_timeout");
1967
+ if (!finalTransportInvoked)
1968
+ controller.abort(reason);
1969
+ (0, runtime_1.emitNervesEvent)({
1970
+ level: "warn",
1971
+ component: "senses",
1972
+ event: "senses.bluebubbles_turn_timeout",
1973
+ message: "bluebubbles turn timed out",
1974
+ meta: {
1975
+ messageGuid: event.messageGuid,
1976
+ sessionKey: event.chat.sessionKey,
1977
+ source,
1978
+ timeoutMs,
1979
+ },
1980
+ });
1981
+ (0, runtime_1.emitNervesEvent)({
1982
+ level: "warn",
1983
+ component: "senses",
1984
+ event: "senses.bluebubbles_timeout_notice_suppressed",
1985
+ message: "bluebubbles timeout notice suppressed from iMessage",
1986
+ meta: {
1987
+ messageGuid: event.messageGuid,
1988
+ sessionKey: event.chat.sessionKey,
1989
+ source,
1990
+ timeoutMs,
1991
+ },
1992
+ });
1993
+ }, timeoutMs);
1994
+ /* v8 ignore next -- timer handles expose unref only in some runtimes @preserve */
1995
+ if (typeof timeoutTimer.unref === "function") {
1996
+ timeoutTimer.unref();
1997
+ }
1998
+ let preparedBlueBubblesContext = {
1999
+ messages: [],
2000
+ contextPacketIds: [],
2001
+ };
2002
+ const turnPromise = (0, pipeline_1.handleInboundTurn)({
2003
+ channel: "bluebubbles",
2004
+ sessionKey: event.chat.sessionKey,
2005
+ capabilities: bbCapabilities,
2006
+ messages: [userMessage],
2007
+ continuityIngressTexts: getBlueBubblesContinuityIngressTexts(event),
2008
+ friendResolver: { resolve: () => Promise.resolve(context) },
2009
+ sessionLoader: {
2010
+ loadOrCreate: () => Promise.resolve({
2011
+ messages: sessionMessages,
2012
+ sessionPath: sessPath,
2013
+ state: existing?.state,
2014
+ events: existing?.events,
2015
+ structuredOutputs: existing?.structuredOutputs,
2016
+ }),
2017
+ },
2018
+ pendingDir,
2019
+ friendStore: store,
2020
+ provider: "imessage-handle",
2021
+ externalId: event.sender.externalId,
2022
+ isGroupChat: event.chat.isGroup,
2023
+ groupHasFamilyMember,
2024
+ hasExistingGroupWithFamily,
2025
+ enforceTrustGate: trust_gate_1.enforceTrustGate,
2026
+ drainPending: pending_1.drainPending,
2027
+ drainDeferredReturns: (deferredFriendId) => (0, pending_1.drainDeferredReturns)(resolvedDeps.getAgentName(), deferredFriendId),
2028
+ prepareRunAgentOptions: async ({ messages = [], currentUserMessages = [], runAgentOptions }) => {
2029
+ preparedBlueBubblesContext = await buildBlueBubblesContextMessages({
2030
+ agentName,
2031
+ agentRoot: (0, identity_1.getAgentRoot)(),
2032
+ client,
2033
+ event,
2034
+ knownMessages: messages,
2035
+ });
2036
+ const currentUserMessage = currentUserMessages.findLast((message) => message.role === "user")
2037
+ ?? messages.findLast((message) => message.role === "user");
2038
+ if (!currentUserMessage)
2039
+ return undefined;
2040
+ Object.freeze(currentUserMessage);
2041
+ const { verifiedPredecessorMessage } = preparedBlueBubblesContext;
2042
+ return {
2043
+ ...(preparedBlueBubblesContext.contextPacketIds.length > 0 ? {
2044
+ contextPacketIds: [
2045
+ ...(runAgentOptions.contextPacketIds ?? []),
2046
+ ...preparedBlueBubblesContext.contextPacketIds,
2047
+ ],
2048
+ } : {}),
2049
+ ...(preparedBlueBubblesContext.messages.length > 0 ? {
2050
+ promptOnlyEvidenceMessages: preparedBlueBubblesContext.messages,
2051
+ } : {}),
2052
+ requiredPromptEvidence: {
2053
+ currentUserMessage,
2054
+ ...(verifiedPredecessorMessage ? { verifiedPredecessorMessage } : {}),
2055
+ },
2056
+ };
2057
+ },
2058
+ runAgent: async (msgs, cb, channel, sig, opts) => {
2059
+ const { codingFeedback: _omittedCodingFeedback, ...safeToolContext } = opts?.toolContext ?? {};
2060
+ const requiredCurrent = opts?.requiredPromptEvidence?.currentUserMessage;
2061
+ const providerMessages = insertEphemeralContextMessages(msgs.map((message) => message === requiredCurrent ? message : structuredClone(message)), [
2062
+ ...preparedBlueBubblesContext.messages,
2063
+ ...(preparedBlueBubblesContext.verifiedPredecessorMessage
2064
+ ? [preparedBlueBubblesContext.verifiedPredecessorMessage]
2065
+ : []),
2066
+ ], requiredCurrent);
2067
+ let generatedMessages = [];
2068
+ const agentResult = await resolvedDeps.runAgent(providerMessages, cb, channel, sig, {
2069
+ ...opts,
2070
+ captureGeneratedMessages: (generated) => {
2071
+ opts?.captureGeneratedMessages?.(generated);
2072
+ generatedMessages = structuredClone(generated);
2073
+ },
2074
+ toolContext: {
2075
+ /* v8 ignore next -- default no-op signin; pipeline provides the real one @preserve */
2076
+ signin: async () => undefined,
2077
+ ...safeToolContext,
2078
+ ...mcpOwner,
2079
+ summarize,
2080
+ chatActions: (0, tools_chat_1.chatActionsForTurn)({
2081
+ setReplyTarget: (selection) => replyTarget.setSelection(selection),
2082
+ react: (emoji, messageId) => (0, reactions_1.reactInBlueBubbles)(client, event.chat, emoji, messageId),
2083
+ sendFile: (filePath, caption) => (0, send_file_1.sendFileInBlueBubbles)(client, event.chat, filePath, caption),
2084
+ }, event.messageGuid),
2085
+ },
2086
+ });
2087
+ if (generatedMessages.length > 0) {
2088
+ msgs.push(...generatedMessages);
2089
+ }
2090
+ return agentResult;
2091
+ },
2092
+ postTurn: (turnMessages, sessionPathArg, usage, hooks, state) => {
2093
+ const prepared = resolvedDeps.postTurnTrim(turnMessages, usage, hooks);
2094
+ turnStage.postTurn = {
2095
+ sessionPath: sessionPathArg,
2096
+ prepared,
2097
+ usage,
2098
+ state,
2099
+ };
2100
+ },
2101
+ accumulateFriendTokens: async (tokenStore, tokenFriendId, usage) => {
2102
+ turnStage.tokens = {
2103
+ store: tokenStore,
2104
+ friendId: tokenFriendId,
2105
+ usage,
2106
+ };
2107
+ },
2108
+ signal: controller.signal,
2109
+ // The deadline, supersession and shutdown handlers record this
2110
+ // turn's outcome, so a turn they cancel need not wait its turn.
2111
+ stopQueueWaitOnAbort: true,
2112
+ runAgentOptions: {
2113
+ mcpManager,
2114
+ orientationFrame,
2115
+ toolContext: {
2116
+ signin: async () => undefined,
2117
+ ...mcpOwner,
2118
+ currentIngressEvidence: options.currentIngressEvidence,
2119
+ },
2120
+ ...(options.isReactionSignal ? { isReactionSignal: true } : {}),
2121
+ },
2122
+ callbacks: failoverAwareCallbacks,
2123
+ sessionTurnLease,
2124
+ failoverState: turnStage.failoverState,
2125
+ });
2126
+ /* v8 ignore start -- detached late-rejection telemetry is asserted in timeout tests, but V8 does not reliably attribute Promise.catch callbacks @preserve */
2127
+ void turnPromise
2128
+ .catch((error) => {
2129
+ if (!recoveryTimedOut)
2130
+ return;
2131
+ (0, runtime_1.emitNervesEvent)({
2132
+ level: "warn",
2133
+ component: "senses",
2134
+ event: "senses.bluebubbles_recovery_error",
2135
+ message: "bluebubbles recovery turn rejected after timeout",
2136
+ meta: {
2137
+ messageGuid: event.messageGuid,
2138
+ sessionKey: event.chat.sessionKey,
2139
+ source,
2140
+ reason: error instanceof Error ? error.message : String(error),
2141
+ },
2142
+ });
2143
+ });
2144
+ /* v8 ignore stop */
2145
+ const runTurn = (async () => {
2146
+ const result = await turnPromise;
2147
+ if (recoveryTimedOut && !finalTransportInvoked) {
2148
+ (0, runtime_1.emitNervesEvent)({
2149
+ level: "warn",
2150
+ component: "senses",
2151
+ event: "senses.bluebubbles_timed_out_turn_suppressed",
2152
+ message: "suppressed late bluebubbles turn result after timeout",
2153
+ meta: {
2154
+ messageGuid: event.messageGuid,
2155
+ sessionKey: event.chat.sessionKey,
2156
+ source,
2157
+ reason: "turn completed after its final-transport boundary closed",
2158
+ },
2159
+ });
2160
+ return {
2161
+ handled: true,
2162
+ notifiedAgent: false,
2163
+ kind: event.kind,
2164
+ reason: "turn_timeout",
2165
+ };
2166
+ }
2167
+ /* v8 ignore start -- failover display + error replay @preserve */
2168
+ if (result.failoverMessage) {
2169
+ callbacks.onClearText?.();
2170
+ callbacks.onTextChunk(result.failoverMessage);
2171
+ bufferedTerminalError = null;
2172
+ }
2173
+ else if (bufferedTerminalError) {
2174
+ callbacks.onError(bufferedTerminalError, "terminal");
2175
+ bufferedTerminalError = null;
2176
+ }
2177
+ /* v8 ignore stop */
2178
+ // ── Handle gate result ────────────────────────────────────────
2179
+ let processedOutcome = "turn-complete";
2180
+ if (!result.gateResult.allowed) {
2181
+ callbacks.onClearText?.();
2182
+ if ("autoReply" in result.gateResult && result.gateResult.autoReply) {
2183
+ callbacks.onTextChunk(result.gateResult.autoReply);
2184
+ }
2185
+ processedOutcome = "trust-gated";
2186
+ }
2187
+ let delivery;
2188
+ try {
2189
+ delivery = await callbacks.flush({ signal: controller.signal });
2190
+ }
2191
+ catch (error) {
2192
+ // Aborted before the transport ran: the deadline, supersession or
2193
+ // shutdown handler already decided this turn's result.
2194
+ if (controller.signal.aborted && !finalTransportInvoked)
2195
+ throw error;
2196
+ (0, runtime_1.emitNervesEvent)({
2197
+ level: "warn",
2198
+ component: "senses",
2199
+ event: "senses.bluebubbles_final_transport_failed",
2200
+ message: "bluebubbles final transport failed after invocation",
2201
+ meta: {
2202
+ messageGuid: event.messageGuid,
2203
+ sessionKey: event.chat.sessionKey,
2204
+ reason: error instanceof Error ? error.message : String(error),
2205
+ },
2206
+ });
2207
+ if (spokeBeforeFinalTransport) {
2208
+ // The friend already saw part of this turn; a retry would repeat it.
2209
+ const failed = (0, outbound_state_1.readBlueBubblesOutboundRecordByIdempotencyKey)((0, identity_1.getAgentRoot)(), blueBubblesInboundReplyIdempotencyKey(options.currentIngressEvidence.captureKeyHash));
2210
+ if (failed) {
2211
+ (0, outbound_state_1.markBlueBubblesOutboundPendingManualVerification)({
2212
+ agentRoot: (0, identity_1.getAgentRoot)(),
2213
+ recordId: failed.recordId,
2214
+ decidedAt: new Date().toISOString(),
2215
+ reason: "mid-turn speech was visible before the final send failed",
2216
+ });
2217
+ }
2218
+ }
2219
+ return {
2220
+ handled: true,
2221
+ notifiedAgent: false,
2222
+ kind: event.kind,
2223
+ reason: "delivery_failed",
2224
+ };
2225
+ }
2226
+ if (delivery.status !== "accepted" || !finalTransportAccepted) {
2227
+ return {
2228
+ handled: true,
2229
+ notifiedAgent: false,
2230
+ kind: event.kind,
2231
+ reason: !(0, latest_turn_1.isCurrent)(options.latestTurnCapability)
2232
+ ? "superseded"
2233
+ : "no_visible_reply",
2234
+ };
2235
+ }
2236
+ // Acceptance is the visibility boundary. Publish the terminal dedupe
2237
+ // receipt first, then project the private generated tail while this
2238
+ // chat's canonical lock remains held. Even if receipt publication
2239
+ // fails, make the best possible canonical projection before surfacing
2240
+ // the retained-claim failure. Ancillary accounting follows both.
2241
+ let receiptFailed = false;
2242
+ let receiptFailure;
2243
+ try {
2244
+ options.publishAcceptedReceipt();
2245
+ }
2246
+ catch (error) {
2247
+ receiptFailed = true;
2248
+ receiptFailure = error;
2249
+ }
2250
+ persistAcceptedBlueBubblesProjection({
2251
+ stage: turnStage,
2252
+ deps: resolvedDeps,
2253
+ event,
2254
+ });
2255
+ if (receiptFailed)
2256
+ throw receiptFailure;
2257
+ promoteAcceptedBlueBubblesAncillaryState({
2258
+ stage: turnStage,
2259
+ deps: resolvedDeps,
2260
+ agentName,
2261
+ event,
2262
+ source,
2263
+ processedOutcome,
2264
+ });
2265
+ (0, runtime_1.emitNervesEvent)({
2266
+ component: "senses",
2267
+ event: "senses.bluebubbles_turn_end",
2268
+ message: "bluebubbles event handled",
2269
+ meta: {
2270
+ messageGuid: event.messageGuid,
2271
+ kind: event.kind,
2272
+ sessionKey: event.chat.sessionKey,
2273
+ },
2274
+ });
2275
+ return {
2276
+ handled: true,
2277
+ notifiedAgent: true,
2278
+ kind: event.kind,
2279
+ };
2280
+ })();
2281
+ activeRunTurn = runTurn;
2282
+ /* v8 ignore start -- detached post-timeout suppression telemetry @preserve */
2283
+ void runTurn.catch((error) => {
2284
+ if (!recoveryTimedOut)
2285
+ return;
2286
+ (0, runtime_1.emitNervesEvent)({
2287
+ level: "warn",
2288
+ component: "senses",
2289
+ event: "senses.bluebubbles_timed_out_turn_suppressed",
2290
+ message: "suppressed late bluebubbles turn result after timeout",
2291
+ meta: {
2292
+ messageGuid: event.messageGuid,
2293
+ sessionKey: event.chat.sessionKey,
2294
+ source,
2295
+ reason: error instanceof Error ? error.message : String(error),
2296
+ },
2297
+ });
2298
+ });
2299
+ /* v8 ignore stop */
2300
+ return await Promise.race([runTurn, timeoutPromise, supersessionPromise, lifecyclePromise]);
2301
+ }
2302
+ finally {
2303
+ // A timed-out/superseded provider may ignore abort briefly. Never release
2304
+ // the cross-process session lease until that work has actually quiesced.
2305
+ if (activeRunTurn)
2306
+ await activeRunTurn.catch(() => undefined);
2307
+ // If a terminal error was buffered and never replayed (e.g., handleInboundTurn threw),
2308
+ // replay it now so the user still sees the error.
2309
+ /* v8 ignore start -- error replay on throw: tested via BB error test @preserve */
2310
+ if (bufferedTerminalError) {
2311
+ callbacks.onError(bufferedTerminalError, "terminal");
2312
+ bufferedTerminalError = null;
2313
+ }
2314
+ /* v8 ignore stop */
2315
+ clearTimeout(timeoutTimer);
2316
+ options.latestTurnCapability.signal.removeEventListener("abort", cancelForSupersession);
2317
+ lifecycleSignal?.removeEventListener("abort", cancelForShutdown);
2318
+ (0, active_turns_1.finishBlueBubblesActiveTurn)(agentName, liveTurnId);
2319
+ activeTurnId = null;
2320
+ await callbacks.finish({ timeoutMs: BLUEBUBBLES_CALLBACK_CLEANUP_TIMEOUT_MS });
2321
+ }
2322
+ }
2323
+ finally {
2324
+ (0, outbound_record_1.drainOutboundRecords)((0, identity_1.getAgentRoot)(), friendId, "bluebubbles", event.chat.sessionKey, sessionTurnLease);
2325
+ }
2326
+ });
2327
+ });
2328
+ }
2329
+ finally {
2330
+ if (activeTurnId)
2331
+ (0, active_turns_1.finishBlueBubblesActiveTurn)(agentName, activeTurnId);
2332
+ }
2333
+ }
2334
+ function recordBlueBubblesAuditSidecar(agentName, event, source, resolvedDeps) {
2335
+ if (event.kind === "message") {
2336
+ if (event.fromMe !== true)
2337
+ (0, inbound_log_1.recordBlueBubblesInbound)(agentName, event, source);
2338
+ return;
2339
+ }
2340
+ try {
2341
+ resolvedDeps.recordMutation(agentName, event);
2342
+ }
2343
+ catch (error) {
2344
+ (0, runtime_1.emitNervesEvent)({
2345
+ level: "error",
2346
+ component: "senses",
2347
+ event: "senses.bluebubbles_mutation_log_error",
2348
+ message: "failed recording bluebubbles mutation sidecar",
2349
+ meta: {
2350
+ messageGuid: event.messageGuid,
2351
+ mutationType: event.mutationType,
2352
+ reason: error instanceof Error ? error.message : String(error),
2353
+ },
2354
+ });
2355
+ }
2356
+ }
2357
+ async function captureBlueBubblesSemanticEvent(normalized, resolvedDeps, source, observationReservation) {
2358
+ const agentName = resolvedDeps.getAgentName();
2359
+ const capturedAt = new Date().toISOString();
2360
+ if (!hasObservedBlueBubblesDirection(normalized)) {
2361
+ (0, runtime_1.emitNervesEvent)({
2362
+ level: "warn",
2363
+ component: "senses",
2364
+ event: "senses.bluebubbles_direction_unobserved",
2365
+ message: "kept bluebubbles event audit-only because message direction was unobserved",
2366
+ meta: {
2367
+ messageGuid: normalized.messageGuid,
2368
+ kind: normalized.kind,
2369
+ source,
2370
+ },
2371
+ });
2372
+ recordBlueBubblesAuditSidecar(agentName, normalized, source, resolvedDeps);
2373
+ return { status: "audit_only", normalized };
2374
+ }
2375
+ const observed = normalized;
2376
+ const cutover = (0, semantic_receipts_1.initializeBlueBubblesSemanticCutover)(agentName);
2377
+ let coordinateGeneration;
2378
+ if (observed.kind === "mutation"
2379
+ && observed.mutationType === "reaction"
2380
+ && observed.reaction
2381
+ && !observed.revision
2382
+ && !Number.isFinite(observed.effectiveTimestamp)
2383
+ && observed.sender.observed === true) {
2384
+ const identity = (0, semantic_receipts_1.buildBlueBubblesSemanticIdentity)({
2385
+ providerNamespace: cutover.providerNamespace,
2386
+ kind: "reaction",
2387
+ eventGuid: observed.messageGuid,
2388
+ targetGuid: observed.targetMessageGuid,
2389
+ actorExternalId: observed.sender.externalId,
2390
+ canonicalValue: observed.reaction.canonicalValue,
2391
+ canonicalAction: observed.reaction.action,
2392
+ coordinateGeneration: 0,
2393
+ });
2394
+ if (identity?.coordinateKey && identity.coordinateHash) {
2395
+ const coordinate = await (0, semantic_receipts_1.allocateBlueBubblesReactionCoordinate)(agentName, {
2396
+ coordinateKey: identity.coordinateKey,
2397
+ coordinateHash: identity.coordinateHash,
2398
+ canonicalAction: observed.reaction.action,
2399
+ });
2400
+ coordinateGeneration = coordinate.generation;
2401
+ }
2402
+ }
2403
+ const capture = (0, semantic_receipts_1.buildBlueBubblesSemanticCapture)({
2404
+ cutover,
2405
+ capturedAt,
2406
+ observationEpoch: observationReservation.observationEpoch,
2407
+ observationOrdinal: observationReservation.ordinal,
2408
+ event: observed,
2409
+ targetAuthorship: null,
2410
+ coordinateGeneration,
2411
+ });
2412
+ if (!capture) {
2413
+ (0, semantic_receipts_1.classifyBlueBubblesRecoveryRecord)(observed, cutover);
2414
+ recordBlueBubblesAuditSidecar(agentName, observed, source, resolvedDeps);
2415
+ return { status: "audit_only", normalized: observed };
2416
+ }
2417
+ const writeResult = (0, semantic_receipts_1.writeBlueBubblesSemanticCapture)(agentName, capture);
2418
+ if (writeResult === "semantic_identity_collision") {
2419
+ throw new Error("semantic_capture_failed");
2420
+ }
2421
+ recordBlueBubblesAuditSidecar(agentName, observed, source, resolvedDeps);
2422
+ return {
2423
+ status: "captured",
2424
+ capture,
2425
+ normalized: observed,
2426
+ writeResult,
2427
+ };
2428
+ }
2429
+ function semanticCaptureChat(capture) {
2430
+ const event = capture.event;
2431
+ const sessionKey = event.sessionKey?.trim();
2432
+ const chatGuid = event.chatGuid?.trim() || undefined;
2433
+ const chatIdentifier = event.chatIdentifier?.trim() || undefined;
2434
+ if (!sessionKey)
2435
+ return null;
2436
+ const fallbackSendTarget = sessionKey.startsWith("chat:")
2437
+ ? { kind: "chat_guid", value: sessionKey.slice("chat:".length).trim() }
2438
+ : sessionKey.startsWith("chat_identifier:")
2439
+ ? { kind: "chat_identifier", value: sessionKey.slice("chat_identifier:".length).trim() }
2440
+ : null;
2441
+ const sendTarget = chatGuid
2442
+ ? { kind: "chat_guid", value: chatGuid }
2443
+ : chatIdentifier
2444
+ ? { kind: "chat_identifier", value: chatIdentifier }
2445
+ : fallbackSendTarget;
2446
+ if (!sendTarget?.value)
2447
+ return null;
2448
+ return {
2449
+ chatGuid,
2450
+ chatIdentifier,
2451
+ isGroup: Boolean(chatGuid?.includes(";+;") || event.participants.length > 1),
2452
+ sessionKey,
2453
+ sendTarget,
2454
+ participantHandles: event.participants.map((participant) => participant.externalId),
2455
+ };
2456
+ }
2457
+ function semanticCaptureRequiresRoutingRepair(capture) {
2458
+ return !capture.event.chatGuid?.trim() && !capture.event.chatIdentifier?.trim();
2459
+ }
2460
+ function hasResolvedBlueBubblesRouting(event) {
2461
+ return Boolean(event.chat.chatGuid?.trim() || event.chat.chatIdentifier?.trim());
2462
+ }
2463
+ function reserveBlueBubblesObservation(event) {
2464
+ return (0, latest_turn_1.reserveObservation)({
2465
+ chatGuid: event.chat.chatGuid,
2466
+ chatIdentifier: event.chat.chatIdentifier,
2467
+ });
2468
+ }
2469
+ function groupBlueBubblesObservationsByLane(candidates) {
2470
+ let groups = [];
2471
+ for (const candidate of candidates) {
2472
+ const keys = new Set((0, latest_turn_1.observationSchedulingKeys)(candidate.observationReservation));
2473
+ const destination = { keys: new Set(keys), candidates: [candidate] };
2474
+ const independentGroups = [];
2475
+ for (const group of groups) {
2476
+ const intersects = (keys.has("unresolved:*")
2477
+ || group.keys.has("unresolved:*")
2478
+ || [...keys].some((key) => group.keys.has(key)));
2479
+ if (!intersects) {
2480
+ independentGroups.push(group);
2481
+ continue;
2482
+ }
2483
+ destination.candidates.push(...group.candidates);
2484
+ for (const key of group.keys)
2485
+ destination.keys.add(key);
2486
+ }
2487
+ groups = [...independentGroups, destination];
2488
+ }
2489
+ return groups.map((group) => group.candidates.sort((left, right) => (right.observationReservation.ordinal - left.observationReservation.ordinal)));
2490
+ }
2491
+ function canonicalizeBlueBubblesEvent(event, capability) {
2492
+ const canonical = capability.canonicalChat;
2493
+ const { chatIdentifier: _observedIdentifier, ...observedChat } = event.chat;
2494
+ return {
2495
+ ...event,
2496
+ chat: {
2497
+ ...observedChat,
2498
+ chatGuid: canonical.chatGuid,
2499
+ ...(canonical.chatIdentifier ? { chatIdentifier: canonical.chatIdentifier } : {}),
2500
+ sessionKey: canonical.sessionKey,
2501
+ sendTarget: { kind: "chat_guid", value: canonical.chatGuid },
2502
+ },
2503
+ };
2504
+ }
2505
+ function isCaptureOnlyBlueBubblesMutation(capture) {
2506
+ return capture.event.kind === "unsend";
2507
+ }
2508
+ /** A reaction or an edit is speech to the agent: it arrives as a message carrying the shared rendering, aimed at the message it changes. */
2509
+ function blueBubblesInteractionAsMessage(event) {
2510
+ return {
2511
+ kind: "message",
2512
+ eventType: event.eventType,
2513
+ messageGuid: event.messageGuid,
2514
+ timestamp: event.timestamp,
2515
+ fromMe: event.fromMe,
2516
+ sender: event.sender,
2517
+ chat: event.chat,
2518
+ text: event.textForAgent,
2519
+ textForAgent: event.textForAgent,
2520
+ attachments: [],
2521
+ hasPayloadData: false,
2522
+ requiresRepair: false,
2523
+ ...(event.targetMessageGuid ? { replyToGuid: event.targetMessageGuid } : {}),
2524
+ };
2525
+ }
2526
+ function isAuditOnlySemanticCapture(capture) {
2527
+ return capture.event.kind === "read" || capture.event.kind === "delivery";
2528
+ }
2529
+ function semanticCaptureToNormalizedEvent(capture) {
2530
+ const event = capture.event;
2531
+ const messageGuid = event.eventGuid?.trim();
2532
+ const chat = semanticCaptureChat(capture);
2533
+ if (!messageGuid || !chat)
2534
+ return null;
2535
+ const sender = {
2536
+ provider: "imessage-handle",
2537
+ externalId: event.actor.externalId,
2538
+ rawId: event.actor.externalId,
2539
+ displayName: event.actor.displayName ?? event.actor.externalId,
2540
+ observed: true,
2541
+ };
2542
+ const timestamp = Date.parse(event.effectiveAt ?? capture.capturedAt);
2543
+ if (event.kind === "message") {
2544
+ const text = event.text ?? "";
2545
+ return {
2546
+ kind: "message",
2547
+ eventType: event.sourceEventType,
2548
+ messageGuid,
2549
+ timestamp,
2550
+ fromMe: event.fromMe,
2551
+ sender,
2552
+ chat,
2553
+ text,
2554
+ textForAgent: text,
2555
+ attachments: [],
2556
+ hasPayloadData: false,
2557
+ requiresRepair: true,
2558
+ };
2559
+ }
2560
+ const shouldNotifyAgent = event.kind === "reaction" || event.kind === "edit" || event.kind === "unsend";
2561
+ const targetMessageGuid = event.targetGuid ?? undefined;
2562
+ const reaction = event.kind === "reaction" && event.canonicalAction && event.canonicalValue
2563
+ ? {
2564
+ ...(0, model_1.describeBlueBubblesReaction)(event.rawTransportValue ?? event.canonicalValue, event.rawTransportValue ?? event.canonicalValue),
2565
+ canonicalValue: event.canonicalValue,
2566
+ action: event.canonicalAction,
2567
+ }
2568
+ : undefined;
2569
+ const textForAgent = reaction
2570
+ ? (0, model_1.renderBlueBubblesReactionText)(reaction, { guid: targetMessageGuid })
2571
+ : event.kind === "edit"
2572
+ ? (0, model_1.renderBlueBubblesEditText)(event.text)
2573
+ : event.kind === "unsend"
2574
+ ? "unsent a message"
2575
+ : event.kind === "read"
2576
+ ? "message marked as read"
2577
+ : "message marked as delivered";
2578
+ return {
2579
+ kind: "mutation",
2580
+ eventType: event.sourceEventType,
2581
+ mutationType: event.kind,
2582
+ messageGuid,
2583
+ targetMessageGuid,
2584
+ timestamp,
2585
+ fromMe: event.fromMe,
2586
+ sender,
2587
+ chat,
2588
+ shouldNotifyAgent,
2589
+ textForAgent,
2590
+ requiresRepair: true,
2591
+ ...(reaction ? { reaction } : {}),
2592
+ ...(event.kind === "edit" && event.text !== null ? { editedText: event.text } : {}),
2593
+ ...(event.revision ? { revision: event.revision } : {}),
2594
+ ...(event.effectiveAt ? { effectiveTimestamp: Date.parse(event.effectiveAt) } : {}),
2595
+ ...(event.kind === "unsend" && event.effectiveAt
2596
+ ? { retractionTimestamp: Date.parse(event.effectiveAt) }
2597
+ : {}),
2598
+ };
2599
+ }
2600
+ function seedBlueBubblesStartupSemanticObservations(deps = {}) {
2601
+ const resolvedDeps = { ...defaultDeps, ...deps };
2602
+ const agentName = resolvedDeps.getAgentName();
2603
+ const cutover = (0, semantic_receipts_1.initializeBlueBubblesSemanticCutover)(agentName);
2604
+ let seeded = 0;
2605
+ for (const capture of (0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName)
2606
+ .sort(semantic_receipts_1.compareBlueBubblesSemanticCaptureOrder)) {
2607
+ const disposition = (0, semantic_receipts_1.classifyBlueBubblesRecoveryRecord)(capture, cutover);
2608
+ if (disposition.disposition === "audit_only")
2609
+ continue;
2610
+ const normalized = semanticCaptureToNormalizedEvent(capture);
2611
+ if (!normalized)
2612
+ continue;
2613
+ const generation = adoptBlueBubblesSemanticObservation(capture.keyHash, reserveBlueBubblesObservation(normalized), false);
2614
+ // Startup seeding runs synchronously before listen. Retain each fence so
2615
+ // persisted pre-restart observations remain causally older than any live
2616
+ // webhook accepted by this process and can reuse the same generation when
2617
+ // the delayed recovery pass begins.
2618
+ suspendBlueBubblesSemanticObservation(generation);
2619
+ seeded += 1;
2620
+ }
2621
+ return seeded;
2622
+ }
2623
+ /** Only an unsend is kept without a turn: it takes words back and adds none for the agent to answer. */
2624
+ function captureOnlyHandledDisposition() {
2625
+ return { outcome: "unsend_capture_only", detailCode: null };
2626
+ }
2627
+ function auditOnlyHandledOutcome(kind) {
2628
+ return kind === "read" ? "read_audit_only" : "delivery_audit_only";
2629
+ }
2630
+ function writeCapturedBlueBubblesHandled(agentName, capture, outcome, detailCode = null) {
2631
+ const handledResult = (0, semantic_receipts_1.writeBlueBubblesSemanticHandled)(agentName, {
2632
+ schemaVersion: 1,
2633
+ canonicalKey: capture.canonicalKey,
2634
+ keyHash: capture.keyHash,
2635
+ handledAt: new Date().toISOString(),
2636
+ outcome,
2637
+ detailCode,
2638
+ });
2639
+ if (handledResult === "semantic_handled_collision") {
2640
+ throw new Error("semantic_handled_collision");
2641
+ }
2642
+ }
2643
+ function blueBubblesInboundReplyIdempotencyKey(captureKeyHash) {
2644
+ return `bluebubbles-inbound-reply:${captureKeyHash}`;
2645
+ }
2646
+ async function blueBubblesFailedReplyIsVisible(deps, chat, record) {
2647
+ const since = Date.parse(record.createdAt);
2648
+ const recent = await deps.createClient().listRecentMessages?.({
2649
+ chatGuid: chat.chatGuid,
2650
+ limit: 25,
2651
+ }) ?? [];
2652
+ return recent.some((message) => (message.kind === "message"
2653
+ && message.fromMe
2654
+ && message.timestamp >= since
2655
+ && message.chat.chatGuid === chat.chatGuid
2656
+ && (0, outbound_state_1.blueBubblesOutboundTextMatches)(record, message.text)));
2657
+ }
2658
+ function blueBubblesRecoveredOutboundOutcome(record) {
2659
+ return BLUEBUBBLES_VISIBLE_OUTBOUND_STATUSES.has(record.status)
2660
+ ? "message_completed"
2661
+ : "message_observed";
2662
+ }
2663
+ async function handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, source, options) {
2664
+ options.lifecycleSignal?.throwIfAborted();
2665
+ const agentName = resolvedDeps.getAgentName();
2666
+ const identity = {
2667
+ canonicalKey: captured.capture.canonicalKey,
2668
+ keyHash: captured.capture.keyHash,
2669
+ };
2670
+ const generation = adoptBlueBubblesSemanticObservation(identity.keyHash, options.observationReservation, true);
2671
+ const semanticHandling = await acquireBlueBubblesSemanticHandlingSlot(identity.keyHash, generation);
2672
+ if (semanticHandling.status === "handled_by_owner") {
2673
+ return {
2674
+ handled: true,
2675
+ notifiedAgent: false,
2676
+ kind: captured.normalized.kind,
2677
+ reason: "already_processed",
2678
+ };
2679
+ }
2680
+ const reservation = semanticHandling.reservation;
2681
+ let claim;
2682
+ try {
2683
+ options.lifecycleSignal?.throwIfAborted();
2684
+ claim = await (0, semantic_receipts_1.acquireBlueBubblesSemanticClaim)(agentName, identity);
2685
+ }
2686
+ catch (error) {
2687
+ releaseBlueBubblesSemanticHandlingSlot(identity.keyHash, semanticHandling.slot, "retryable");
2688
+ throw error;
2689
+ }
2690
+ if (claim.status === "already_handled") {
2691
+ releaseBlueBubblesSemanticHandlingSlot(identity.keyHash, semanticHandling.slot, "terminal");
2692
+ return {
2693
+ handled: true,
2694
+ notifiedAgent: false,
2695
+ kind: captured.normalized.kind,
2696
+ reason: "already_processed",
2697
+ };
2698
+ }
2699
+ if (claim.status === "timeout") {
2700
+ releaseBlueBubblesSemanticHandlingSlot(identity.keyHash, semanticHandling.slot, "retryable");
2701
+ return {
2702
+ handled: false,
2703
+ notifiedAgent: false,
2704
+ kind: captured.normalized.kind,
2705
+ reason: "semantic_claim_timeout",
2706
+ };
2707
+ }
2708
+ let latestTurnCapability = null;
2709
+ let semanticHandlingCompleted = false;
2710
+ let retainSemanticClaim = false;
2711
+ let acceptedReceiptPublished = false;
2712
+ const publishTerminalReceipt = (outcome, detailCode = null) => {
2713
+ try {
2714
+ writeCapturedBlueBubblesHandled(agentName, captured.capture, outcome, detailCode);
2715
+ }
2716
+ catch (error) {
2717
+ // A missing terminal receipt must never reopen this semantic event. Keep
2718
+ // the durable claim live so recovery cannot resurrect a canceled turn or
2719
+ // duplicate a reply whose transport is already externally visible.
2720
+ retainSemanticClaim = true;
2721
+ semanticHandlingCompleted = true;
2722
+ (0, runtime_1.emitNervesEvent)({
2723
+ level: "error",
2724
+ component: "senses",
2725
+ event: "senses.bluebubbles_terminal_receipt_failed",
2726
+ message: "bluebubbles event could not publish its terminal semantic receipt",
2727
+ meta: {
2728
+ messageGuid: captured.normalized.messageGuid,
2729
+ keyHash: captured.capture.keyHash,
2730
+ outcome,
2731
+ reason: error instanceof Error ? error.message : String(error),
2732
+ },
2733
+ });
2734
+ throw error;
2735
+ }
2736
+ };
2737
+ const publishAcceptedReceipt = () => {
2738
+ if (acceptedReceiptPublished)
2739
+ return;
2740
+ publishTerminalReceipt("message_completed");
2741
+ acceptedReceiptPublished = true;
2742
+ };
2743
+ let spokenTurnEndPublished = false;
2744
+ const publishSpokenTurnEnded = (reason) => {
2745
+ if (spokenTurnEndPublished)
2746
+ return;
2747
+ spokenTurnEndPublished = true;
2748
+ semanticHandlingCompleted = true;
2749
+ try {
2750
+ publishTerminalReceipt("message_observed", `${reason}_after_visible_speech`);
2751
+ /* v8 ignore start -- a failed write already kept the claim live and was logged, which also stops a replay @preserve */
2752
+ }
2753
+ catch {
2754
+ // Nothing more to do here.
2755
+ }
2756
+ /* v8 ignore stop */
2757
+ };
2758
+ try {
2759
+ options.lifecycleSignal?.throwIfAborted();
2760
+ if (captured.capture.event.fromMe) {
2761
+ (0, runtime_1.emitNervesEvent)({
2762
+ component: "senses",
2763
+ event: "senses.bluebubbles_from_me_ignored",
2764
+ message: "ignored from-me bluebubbles event",
2765
+ meta: {
2766
+ messageGuid: captured.normalized.messageGuid,
2767
+ kind: captured.normalized.kind,
2768
+ },
2769
+ });
2770
+ if (captured.normalized.chat.isGroup) {
2771
+ recordDiscoveredOwnHandle(captured.normalized.sender.externalId);
2772
+ }
2773
+ const result = {
2774
+ handled: true,
2775
+ notifiedAgent: false,
2776
+ kind: captured.normalized.kind,
2777
+ reason: "from_me",
2778
+ };
2779
+ publishTerminalReceipt("ignored_self");
2780
+ semanticHandlingCompleted = true;
2781
+ return result;
2782
+ }
2783
+ const durableOutbound = (0, outbound_state_1.readBlueBubblesOutboundRecordByIdempotencyKey)((0, identity_1.getAgentRoot)(), blueBubblesInboundReplyIdempotencyKey(captured.capture.keyHash));
2784
+ const retryFailedReply = durableOutbound?.status === "failed"
2785
+ && (durableOutbound.failedAttempts ?? 0) < BLUEBUBBLES_REPLY_DELIVERY_MAX_ATTEMPTS;
2786
+ const completeVisibleFailedReply = () => {
2787
+ // The send that timed out reached the chat after all; do not reply twice.
2788
+ (0, runtime_1.emitNervesEvent)({
2789
+ level: "warn",
2790
+ component: "senses",
2791
+ event: "senses.bluebubbles_inbound_reply_recovery_suppressed",
2792
+ message: "suppressed bluebubbles reply retry because a reply is already in the chat",
2793
+ meta: { messageGuid: captured.normalized.messageGuid, recordId: durableOutbound.recordId },
2794
+ });
2795
+ publishTerminalReceipt("message_completed", "reply_visible_after_failed_send");
2796
+ semanticHandlingCompleted = true;
2797
+ return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "already_processed" };
2798
+ };
2799
+ if (retryFailedReply
2800
+ && Date.now() < Date.parse(durableOutbound.failedAt ?? durableOutbound.updatedAt) + BLUEBUBBLES_REPLY_RETRY_DELAY_MS) {
2801
+ // A send that timed out may still arrive. Close the message as soon as the
2802
+ // reply shows up in the chat; only a retry waits out the delay.
2803
+ const visible = await blueBubblesFailedReplyIsVisible(resolvedDeps, captured.normalized.chat, durableOutbound)
2804
+ .catch(() => false);
2805
+ if (visible)
2806
+ return completeVisibleFailedReply();
2807
+ return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "delivery_failed" };
2808
+ }
2809
+ if (durableOutbound && !retryFailedReply) {
2810
+ const outcome = blueBubblesRecoveredOutboundOutcome(durableOutbound);
2811
+ (0, runtime_1.emitNervesEvent)({
2812
+ level: "warn",
2813
+ component: "senses",
2814
+ event: "senses.bluebubbles_inbound_reply_recovery_suppressed",
2815
+ message: "suppressed bluebubbles inbound reply recovery at its durable send boundary",
2816
+ meta: {
2817
+ messageGuid: captured.normalized.messageGuid,
2818
+ recordId: durableOutbound.recordId,
2819
+ outboundStatus: durableOutbound.status,
2820
+ outcome,
2821
+ },
2822
+ });
2823
+ publishTerminalReceipt(outcome);
2824
+ semanticHandlingCompleted = true;
2825
+ return {
2826
+ handled: true,
2827
+ notifiedAgent: false,
2828
+ kind: captured.normalized.kind,
2829
+ reason: "already_processed",
2830
+ };
2831
+ }
2832
+ let handledOutcome = "message_observed";
2833
+ let result;
2834
+ if (isAuditOnlySemanticCapture(captured.capture)) {
2835
+ handledOutcome = auditOnlyHandledOutcome(captured.capture.event.kind);
2836
+ result = {
2837
+ handled: true,
2838
+ notifiedAgent: false,
2839
+ kind: captured.normalized.kind,
2840
+ reason: "mutation_state_only",
2841
+ };
2842
+ }
2843
+ else {
2844
+ const captureOnlyMutation = isCaptureOnlyBlueBubblesMutation(captured.capture);
2845
+ // A reaction, edit or unsend carries what the turn needs in the webhook itself; only a routed message is re-fetched.
2846
+ const repaired = captured.normalized.kind === "mutation" && captured.normalized.chat.chatGuid?.trim()
2847
+ ? captured.normalized
2848
+ : await resolvedDeps.createClient().repairEvent(captured.normalized);
2849
+ options.lifecycleSignal?.throwIfAborted();
2850
+ if (semanticCaptureRequiresRoutingRepair(captured.capture)
2851
+ && !hasResolvedBlueBubblesRouting(repaired)) {
2852
+ throw new Error("semantic_capture_routing_invalid");
2853
+ }
2854
+ const identityGroundedRepaired = {
2855
+ ...repaired,
2856
+ fromMe: captured.normalized.fromMe,
2857
+ sender: captured.normalized.sender,
2858
+ };
2859
+ const promotion = (0, latest_turn_1.promote)(reservation, {
2860
+ chatGuid: identityGroundedRepaired.chat.chatGuid,
2861
+ chatIdentifier: identityGroundedRepaired.chat.chatIdentifier,
2862
+ }, {
2863
+ allowSameGenerationRetry: semanticHandling.allowSameGenerationRetry,
2864
+ });
2865
+ if (promotion.status !== "promoted") {
2866
+ if (!captureOnlyMutation && promotion.status === "unresolved") {
2867
+ throw new Error("semantic_capture_routing_invalid");
2868
+ }
2869
+ const disposition = captureOnlyMutation
2870
+ ? captureOnlyHandledDisposition()
2871
+ : { outcome: "message_observed", detailCode: null };
2872
+ publishTerminalReceipt(disposition.outcome, disposition.detailCode);
2873
+ semanticHandlingCompleted = true;
2874
+ return {
2875
+ handled: true,
2876
+ notifiedAgent: false,
2877
+ kind: captured.normalized.kind,
2878
+ reason: captureOnlyMutation ? "mutation_state_only" : "superseded",
2879
+ };
2880
+ }
2881
+ latestTurnCapability = promotion.capability;
2882
+ if (captureOnlyMutation) {
2883
+ const disposition = captureOnlyHandledDisposition();
2884
+ publishTerminalReceipt(disposition.outcome, disposition.detailCode);
2885
+ semanticHandlingCompleted = true;
2886
+ return {
2887
+ handled: true,
2888
+ notifiedAgent: false,
2889
+ kind: captured.normalized.kind,
2890
+ reason: "mutation_state_only",
2891
+ };
2892
+ }
2893
+ const interaction = identityGroundedRepaired.kind === "mutation"
2894
+ && (identityGroundedRepaired.mutationType === "reaction" || identityGroundedRepaired.mutationType === "edit")
2895
+ ? identityGroundedRepaired
2896
+ : null;
2897
+ const turnEvent = interaction ? blueBubblesInteractionAsMessage(interaction) : identityGroundedRepaired;
2898
+ if (turnEvent.kind === "mutation") {
2899
+ const outcome = auditOnlyHandledOutcome(turnEvent.mutationType);
2900
+ publishTerminalReceipt(outcome);
2901
+ semanticHandlingCompleted = true;
2902
+ return {
2903
+ handled: true,
2904
+ notifiedAgent: false,
2905
+ kind: captured.normalized.kind,
2906
+ reason: "mutation_state_only",
2907
+ };
2908
+ }
2909
+ const canonicalEvent = canonicalizeBlueBubblesEvent(turnEvent, latestTurnCapability);
2910
+ const capturedOptions = {
2911
+ ...options,
2912
+ latestTurnCapability,
2913
+ currentIngressEvidence: Object.freeze({
2914
+ schemaVersion: 1,
2915
+ provider: "bluebubbles",
2916
+ captureKeyHash: captured.capture.keyHash,
2917
+ }),
2918
+ orientationEvidence: captured.capture.event,
2919
+ orientationConversationKind: canonicalEvent.chat.isGroup ? "group" : "one_to_one",
2920
+ publishAcceptedReceipt,
2921
+ publishSpokenTurnEnded,
2922
+ ...(interaction?.mutationType === "reaction" ? { isReactionSignal: true } : {}),
2923
+ };
2924
+ let failedReplyVisible = false;
2925
+ if (retryFailedReply) {
2926
+ try {
2927
+ failedReplyVisible = await blueBubblesFailedReplyIsVisible(resolvedDeps, canonicalEvent.chat, durableOutbound);
2928
+ }
2929
+ catch (error) {
2930
+ // Without the chat history a retry could reply twice; try again later.
2931
+ (0, runtime_1.emitNervesEvent)({
2932
+ level: "warn",
2933
+ component: "senses",
2934
+ event: "senses.bluebubbles_reply_retry_deferred",
2935
+ message: "deferred a bluebubbles reply retry because recent chat messages could not be read",
2936
+ meta: {
2937
+ messageGuid: captured.normalized.messageGuid,
2938
+ reason: error instanceof Error ? error.message : String(error),
2939
+ },
2940
+ });
2941
+ return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "delivery_failed" };
2942
+ }
2943
+ }
2944
+ if (failedReplyVisible)
2945
+ return completeVisibleFailedReply();
2946
+ result = await handleBlueBubblesNormalizedEvent(canonicalEvent, resolvedDeps, source, capturedOptions);
2947
+ // A budget or storm-breaker block defers the message; it was never seen.
2948
+ // Leave it pending so a later recovery pass retries it once the block lifts.
2949
+ if (result.reason === "autonomy_budget_blocked")
2950
+ return result;
2951
+ if (result.reason === "turn_timeout" || result.reason === "delivery_admission_timeout" || result.reason === "shutdown") {
2952
+ // The turn ended without a reply or a chosen silence. Leave it pending so
2953
+ // recovery replays it, unless the friend already saw part of it or it
2954
+ // keeps failing; then record a visible failure instead.
2955
+ const attempts = (unfinishedTurnAttempts.get(identity.keyHash) ?? 0) + 1;
2956
+ unfinishedTurnAttempts.set(identity.keyHash, attempts);
2957
+ if (!result.spokeBeforeEnd && attempts < BLUEBUBBLES_REPLY_DELIVERY_MAX_ATTEMPTS)
2958
+ return result;
2959
+ (0, runtime_1.emitNervesEvent)({
2960
+ level: "error",
2961
+ component: "senses",
2962
+ event: "senses.bluebubbles_turn_abandoned",
2963
+ message: "gave up replaying a bluebubbles turn that kept ending without a reply",
2964
+ meta: {
2965
+ messageGuid: captured.normalized.messageGuid,
2966
+ reason: result.reason,
2967
+ attempts,
2968
+ spokeBeforeEnd: result.spokeBeforeEnd === true,
2969
+ },
2970
+ });
2971
+ if (result.spokeBeforeEnd) {
2972
+ publishSpokenTurnEnded(result.reason);
2973
+ }
2974
+ else {
2975
+ publishTerminalReceipt("message_observed", `${result.reason}_retries_exhausted`);
2976
+ semanticHandlingCompleted = true;
2977
+ }
2978
+ return result;
2979
+ }
2980
+ if (result.reason === "delivery_failed") {
2981
+ // The reply never reached the chat. Leave the message pending so a later
2982
+ // recovery pass sends it, until the per-message attempt cap is reached.
2983
+ let failed = (0, outbound_state_1.readBlueBubblesOutboundRecordByIdempotencyKey)((0, identity_1.getAgentRoot)(), blueBubblesInboundReplyIdempotencyKey(captured.capture.keyHash));
2984
+ if (failed?.status === "failed") {
2985
+ if (retryFailedReply && failed.failedAttempts === durableOutbound.failedAttempts) {
2986
+ // The retry failed before it reached the transport; count it anyway.
2987
+ failed = (0, outbound_state_1.markBlueBubblesOutboundFailed)({
2988
+ agentRoot: (0, identity_1.getAgentRoot)(),
2989
+ recordId: failed.recordId,
2990
+ failedAt: new Date().toISOString(),
2991
+ reason: "retry failed before the final transport",
2992
+ });
2993
+ }
2994
+ /* v8 ignore next -- a failed record re-read after a send always carries its count @preserve */
2995
+ const failedAttempts = failed.failedAttempts ?? 0;
2996
+ if (failedAttempts < BLUEBUBBLES_REPLY_DELIVERY_MAX_ATTEMPTS)
2997
+ return result;
2998
+ (0, runtime_1.emitNervesEvent)({
2999
+ level: "error",
3000
+ component: "senses",
3001
+ event: "senses.bluebubbles_reply_delivery_abandoned",
3002
+ message: "gave up sending a bluebubbles reply after repeated transport failures",
3003
+ meta: { messageGuid: captured.normalized.messageGuid, failedAttempts },
3004
+ });
3005
+ publishTerminalReceipt("message_observed", "reply_delivery_retries_exhausted");
3006
+ semanticHandlingCompleted = true;
3007
+ return result;
3008
+ }
3009
+ }
3010
+ handledOutcome = result.notifiedAgent ? "message_completed" : "message_observed";
3011
+ }
3012
+ if (result.notifiedAgent) {
3013
+ publishAcceptedReceipt();
3014
+ }
3015
+ else {
3016
+ publishTerminalReceipt(handledOutcome);
3017
+ }
3018
+ semanticHandlingCompleted = true;
3019
+ return result;
3020
+ }
3021
+ finally {
3022
+ if (latestTurnCapability)
3023
+ (0, latest_turn_1.finish)(latestTurnCapability);
3024
+ try {
3025
+ if (!retainSemanticClaim) {
3026
+ (0, semantic_receipts_1.releaseBlueBubblesSemanticClaim)(agentName, claim);
3027
+ }
3028
+ }
3029
+ finally {
3030
+ releaseBlueBubblesSemanticHandlingSlot(identity.keyHash, semanticHandling.slot, retainSemanticClaim
3031
+ ? "retained"
3032
+ : semanticHandlingCompleted ? "terminal" : "retryable");
3033
+ }
3034
+ }
3035
+ }
3036
+ async function handleBlueBubblesEvent(payload, deps = {}) {
3037
+ const resolvedDeps = { ...defaultDeps, ...deps };
3038
+ let normalized;
3039
+ try {
3040
+ normalized = (0, model_1.normalizeBlueBubblesEvent)(payload);
3041
+ }
3042
+ catch (error) {
3043
+ if (error instanceof model_1.BlueBubblesIgnoredEventError) {
3044
+ (0, runtime_1.emitNervesEvent)({
3045
+ component: "senses",
3046
+ event: "senses.bluebubbles_event_skipped",
3047
+ message: "skipped ignorable bluebubbles event",
3048
+ meta: {
3049
+ eventType: error.eventType,
3050
+ },
3051
+ });
3052
+ return {
3053
+ handled: true,
3054
+ notifiedAgent: false,
3055
+ reason: "ignored",
3056
+ };
3057
+ }
3058
+ throw error;
3059
+ }
3060
+ const scope = new BlueBubblesObservationScope();
3061
+ try {
3062
+ const observationReservation = scope.own(reserveBlueBubblesObservation(normalized));
3063
+ const captured = await captureBlueBubblesSemanticEvent(normalized, resolvedDeps, "webhook", observationReservation);
3064
+ if (captured.status === "audit_only") {
3065
+ return { handled: true, notifiedAgent: false, kind: normalized.kind, reason: "ignored" };
3066
+ }
3067
+ return await handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, "webhook", {
3068
+ observationReservation,
3069
+ });
3070
+ }
3071
+ finally {
3072
+ scope.close();
3073
+ }
3074
+ }
3075
+ function parseTimestampMs(value) {
3076
+ if (!value)
3077
+ return null;
3078
+ const parsed = Date.parse(value);
3079
+ return Number.isFinite(parsed) ? parsed : null;
3080
+ }
3081
+ function resolveBlueBubblesCatchUpSince(previousState, nowMs = Date.now()) {
3082
+ if (previousState.upstreamStatus === "error") {
3083
+ return nowMs - BLUEBUBBLES_RECOVERY_CATCHUP_LOOKBACK_MS;
3084
+ }
3085
+ const lastCheckedAt = parseTimestampMs(previousState.lastCheckedAt);
3086
+ if (lastCheckedAt !== null) {
3087
+ return Math.max(0, lastCheckedAt - BLUEBUBBLES_HEALTHY_CATCHUP_OVERLAP_MS);
3088
+ }
3089
+ return nowMs - BLUEBUBBLES_FIRST_CATCHUP_LOOKBACK_MS;
3090
+ }
3091
+ function formatBlueBubblesRuntimeDetail(pending, failed, active) {
3092
+ const queued = pending.pendingRecoveryCount;
3093
+ if (active.admissionStalledTurnCount > 0) {
3094
+ return `iMessage reply stalled; ${active.admissionStalledTurnCount} turn(s) waiting for permission to send for ${Math.round(active.oldestAdmissionWaitAgeMs / 1000)}s`;
3095
+ }
3096
+ if (active.stalledTurnCount > 0) {
3097
+ return `iMessage live turn appears stalled; ${active.stalledTurnCount} active turn(s) older than ${BLUEBUBBLES_LIVE_TURN_STALLED_MS}ms`;
3098
+ }
3099
+ if (active.activeTurnCount > 0)
3100
+ return `upstream reachable; ${active.activeTurnCount} live turn(s) active`;
3101
+ if (queued > 0) {
3102
+ /* v8 ignore next -- every capture this sense writes carries a parseable capturedAt @preserve */
3103
+ return `upstream reachable but iMessage is not caught up; ${queued} message(s) without a reply or recorded outcome, oldest ${Math.round((pending.oldestPendingRecoveryAgeMs ?? 0) / 1000)}s`;
3104
+ }
3105
+ if (failed > 0)
3106
+ return `${failed} message(s) unrecoverable this cycle; upstream ok`;
3107
+ return "upstream reachable";
3108
+ }
3109
+ function blueBubblesPendingRecoverySnapshot(agentName, nowMs = Date.now()) {
3110
+ const pendingEntries = (0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName);
3111
+ const pendingRecordedAt = pendingEntries
3112
+ .map((entry) => entry.capturedAt)
3113
+ .map((value) => ({ value, ms: Date.parse(value) }))
3114
+ .filter((entry) => Number.isFinite(entry.ms))
3115
+ .sort((left, right) => left.ms - right.ms);
3116
+ const oldest = pendingRecordedAt[0];
3117
+ return {
3118
+ pendingRecoveryCount: pendingEntries.length,
3119
+ oldestPendingRecoveryAt: oldest?.value,
3120
+ oldestPendingRecoveryAgeMs: oldest ? Math.max(0, nowMs - oldest.ms) : undefined,
3121
+ };
3122
+ }
3123
+ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3124
+ options.lifecycleSignal?.throwIfAborted();
3125
+ const resolvedDeps = { ...defaultDeps, ...deps };
3126
+ const agentName = resolvedDeps.getAgentName();
3127
+ // Allocate before the first health-probe await. Any live webhook accepted
3128
+ // while that probe is pending must remain causally newer than this pass.
3129
+ const catchUpObservationBatch = options.catchUpObservationBatch ?? (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
3130
+ pruneBlueBubblesSemanticObservationGenerations(Date.now(), new Set((0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName).map((capture) => capture.keyHash)));
3131
+ const client = resolvedDeps.createClient();
3132
+ const checkedAt = new Date().toISOString();
3133
+ const previousState = (0, runtime_state_1.readBlueBubblesRuntimeState)(agentName);
3134
+ try {
3135
+ await client.checkHealth();
3136
+ options.lifecycleSignal?.throwIfAborted();
3137
+ const pendingBeforeCatchup = blueBubblesPendingRecoverySnapshot(agentName);
3138
+ const activeBeforeCatchup = (0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS);
3139
+ (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
3140
+ upstreamStatus: "ok",
3141
+ detail: "upstream reachable; recovery pass running",
3142
+ lastCheckedAt: checkedAt,
3143
+ proofMethod: "bluebubbles.checkHealth",
3144
+ ...pendingBeforeCatchup,
3145
+ ...activeBeforeCatchup,
3146
+ lastRecoveredAt: previousState.lastRecoveredAt,
3147
+ lastRecoveredMessageGuid: previousState.lastRecoveredMessageGuid,
3148
+ });
3149
+ const catchUp = await catchUpMissedBlueBubblesMessages(resolvedDeps, previousState, {
3150
+ processTurns: false,
3151
+ observationBatch: catchUpObservationBatch,
3152
+ lifecycleSignal: options.lifecycleSignal,
3153
+ });
3154
+ options.lifecycleSignal?.throwIfAborted();
3155
+ const failed = catchUp.failed;
3156
+ const pendingAfterCatchup = blueBubblesPendingRecoverySnapshot(agentName);
3157
+ const activeAfterCatchup = (0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS);
3158
+ const queued = pendingAfterCatchup.pendingRecoveryCount;
3159
+ // upstreamStatus reflects whether BlueBubbles itself and the local bridge
3160
+ // can answer webhook traffic. The daemon status layer treats
3161
+ // pendingRecoveryCount as unhealthy for user-facing iMessage reachability,
3162
+ // while this field stays scoped to upstream transport reachability.
3163
+ (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
3164
+ upstreamStatus: "ok",
3165
+ detail: formatBlueBubblesRuntimeDetail(pendingAfterCatchup, failed, activeAfterCatchup),
3166
+ lastCheckedAt: checkedAt,
3167
+ proofMethod: "bluebubbles.checkHealth",
3168
+ ...pendingAfterCatchup,
3169
+ ...activeAfterCatchup,
3170
+ pendingRecoveryCount: queued,
3171
+ failedRecoveryCount: failed,
3172
+ lastRecoveredAt: previousState.lastRecoveredAt,
3173
+ lastRecoveredMessageGuid: previousState.lastRecoveredMessageGuid,
3174
+ });
3175
+ }
3176
+ catch (error) {
3177
+ if (options.lifecycleSignal?.aborted)
3178
+ return;
3179
+ (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
3180
+ upstreamStatus: "error",
3181
+ detail: error instanceof Error ? error.message : String(error),
3182
+ lastCheckedAt: checkedAt,
3183
+ proofMethod: "bluebubbles.checkHealth",
3184
+ ...blueBubblesPendingRecoverySnapshot(agentName),
3185
+ ...(0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS),
3186
+ failedRecoveryCount: 0,
3187
+ });
3188
+ }
3189
+ }
3190
+ async function recoverQueuedBlueBubblesMessages(deps = {}, options = {}) {
3191
+ options.lifecycleSignal?.throwIfAborted();
3192
+ const resolvedDeps = { ...defaultDeps, ...deps };
3193
+ const agentName = resolvedDeps.getAgentName();
3194
+ const previousState = (0, runtime_state_1.readBlueBubblesRuntimeState)(agentName);
3195
+ const initialPending = blueBubblesPendingRecoverySnapshot(agentName).pendingRecoveryCount;
3196
+ if (initialPending === 0) {
3197
+ return { recovered: 0, skipped: 0, failed: 0, pendingRecoveryCount: 0 };
3198
+ }
3199
+ // Recovery re-reads queued messages from the server, so it only runs against
3200
+ // a server confirmed to be under the agent's own host account. Queued work
3201
+ // stays queued (not failed) until it is.
3202
+ try {
3203
+ await resolvedDeps.verifyHostAccount();
3204
+ }
3205
+ catch (error) {
3206
+ (0, runtime_1.emitNervesEvent)({
3207
+ level: "warn",
3208
+ component: "senses",
3209
+ event: "senses.bluebubbles_recovery_host_refused",
3210
+ message: "skipped bluebubbles recovery because the server's host account is not confirmed",
3211
+ meta: { pendingRecoveryCount: initialPending, reason: error instanceof Error ? error.message : String(error) },
3212
+ });
3213
+ return { recovered: 0, skipped: 0, failed: 0, pendingRecoveryCount: initialPending };
3214
+ }
3215
+ const captured = await recoverCapturedBlueBubblesInboundMessages(resolvedDeps, options);
3216
+ options.lifecycleSignal?.throwIfAborted();
3217
+ const recovery = await recoverMissedBlueBubblesMessages(resolvedDeps);
3218
+ options.lifecycleSignal?.throwIfAborted();
3219
+ const pendingSnapshot = blueBubblesPendingRecoverySnapshot(agentName);
3220
+ const pendingRecoveryCount = pendingSnapshot.pendingRecoveryCount;
3221
+ const failed = captured.failed + recovery.failed;
3222
+ const recovered = captured.recovered + recovery.recovered;
3223
+ const skipped = captured.skipped + recovery.skipped;
3224
+ const checkedAt = new Date().toISOString();
3225
+ try {
3226
+ await resolvedDeps.createClient().checkHealth();
3227
+ options.lifecycleSignal?.throwIfAborted();
3228
+ const activeSnapshot = (0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS);
3229
+ (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
3230
+ upstreamStatus: "ok",
3231
+ detail: formatBlueBubblesRuntimeDetail(pendingSnapshot, failed, activeSnapshot),
3232
+ lastCheckedAt: checkedAt,
3233
+ proofMethod: "bluebubbles.checkHealth",
3234
+ ...pendingSnapshot,
3235
+ ...activeSnapshot,
3236
+ failedRecoveryCount: failed,
3237
+ lastRecoveredAt: recovered > 0 ? checkedAt : previousState.lastRecoveredAt,
3238
+ lastRecoveredMessageGuid: previousState.lastRecoveredMessageGuid,
3239
+ });
3240
+ }
3241
+ catch (error) {
3242
+ if (options.lifecycleSignal?.aborted)
3243
+ throw options.lifecycleSignal.reason;
3244
+ (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
3245
+ upstreamStatus: "error",
3246
+ detail: error instanceof Error ? error.message : String(error),
3247
+ lastCheckedAt: checkedAt,
3248
+ proofMethod: "bluebubbles.checkHealth",
3249
+ ...pendingSnapshot,
3250
+ ...(0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS),
3251
+ failedRecoveryCount: failed,
3252
+ lastRecoveredAt: recovered > 0 ? checkedAt : previousState.lastRecoveredAt,
3253
+ lastRecoveredMessageGuid: previousState.lastRecoveredMessageGuid,
3254
+ });
3255
+ }
3256
+ return { recovered, skipped, failed, pendingRecoveryCount };
3257
+ }
3258
+ function catchUpMissedBlueBubblesMessages(deps = {}, previousState, options = {}) {
3259
+ return withObservationScope((scope) => catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousState, options));
3260
+ }
3261
+ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousState, options) {
3262
+ options.lifecycleSignal?.throwIfAborted();
3263
+ const resolvedDeps = { ...defaultDeps, ...deps };
3264
+ const agentName = resolvedDeps.getAgentName();
3265
+ const client = resolvedDeps.createClient();
3266
+ const result = { inspected: 0, recovered: 0, skipped: 0, failed: 0 };
3267
+ const state = previousState ?? (0, runtime_state_1.readBlueBubblesRuntimeState)(agentName);
3268
+ const cutover = (0, semantic_receipts_1.initializeBlueBubblesSemanticCutover)(agentName);
3269
+ const catchUpSince = Math.max(resolveBlueBubblesCatchUpSince(state), Date.parse(cutover.effectiveAt));
3270
+ const processTurns = options.processTurns !== false;
3271
+ let pendingKeyHashes = null;
3272
+ const pendingCaptureKeyHashes = () => {
3273
+ pendingKeyHashes ??= new Set((0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName).map((capture) => capture.keyHash));
3274
+ return pendingKeyHashes;
3275
+ };
3276
+ /* v8 ignore next -- older injected test doubles may omit the catch-up query method */
3277
+ if (!client.listRecentMessages)
3278
+ return result;
3279
+ (0, runtime_1.emitNervesEvent)({
3280
+ component: "senses",
3281
+ event: "senses.bluebubbles_catchup_start",
3282
+ message: "bluebubbles upstream catch-up pass started",
3283
+ meta: {
3284
+ since: new Date(catchUpSince).toISOString(),
3285
+ pageSize: BLUEBUBBLES_CATCHUP_PAGE_SIZE,
3286
+ maxPages: BLUEBUBBLES_CATCHUP_MAX_PAGES,
3287
+ },
3288
+ });
3289
+ const preparedCandidates = [];
3290
+ const seenMessageGuids = new Set();
3291
+ const observationBatch = options.observationBatch ?? (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
3292
+ for (let page = 0; page < BLUEBUBBLES_CATCHUP_MAX_PAGES; page++) {
3293
+ let pageEvents;
3294
+ try {
3295
+ pageEvents = await client.listRecentMessages({
3296
+ limit: BLUEBUBBLES_CATCHUP_PAGE_SIZE,
3297
+ offset: page * BLUEBUBBLES_CATCHUP_PAGE_SIZE,
3298
+ beforeTimestamp: observationBatch.beforeTimestamp,
3299
+ });
3300
+ }
3301
+ catch (error) {
3302
+ if (options.lifecycleSignal?.aborted)
3303
+ throw options.lifecycleSignal.reason;
3304
+ result.failed++;
3305
+ (0, runtime_1.emitNervesEvent)({
3306
+ level: "warn",
3307
+ component: "senses",
3308
+ event: "senses.bluebubbles_catchup_error",
3309
+ message: "bluebubbles upstream catch-up query failed",
3310
+ meta: {
3311
+ offset: page * BLUEBUBBLES_CATCHUP_PAGE_SIZE,
3312
+ reason: error instanceof Error ? error.message : String(error),
3313
+ },
3314
+ });
3315
+ break;
3316
+ }
3317
+ options.lifecycleSignal?.throwIfAborted();
3318
+ const pageMessages = pageEvents
3319
+ .filter((event) => event.kind === "message")
3320
+ .sort((left, right) => right.timestamp - left.timestamp);
3321
+ for (let pageIndex = 0; pageIndex < pageMessages.length; pageIndex++) {
3322
+ const event = pageMessages[pageIndex];
3323
+ if (seenMessageGuids.has(event.messageGuid))
3324
+ continue;
3325
+ seenMessageGuids.add(event.messageGuid);
3326
+ if (event.fromMe
3327
+ || event.timestamp < catchUpSince
3328
+ || (Number.isFinite(event.timestamp) && event.timestamp > observationBatch.beforeTimestamp)) {
3329
+ preparedCandidates.push({ status: "skip", event });
3330
+ continue;
3331
+ }
3332
+ // The bounded ordinal range and upstream snapshot were fixed before the
3333
+ // first query. Each returned page can therefore publish its fences
3334
+ // before the next await, while later ingress stays outside this pass.
3335
+ preparedCandidates.push({
3336
+ status: "ready",
3337
+ event,
3338
+ observationReservation: scope.own((0, latest_turn_1.reserveObservationFromBatch)(observationBatch, page * BLUEBUBBLES_CATCHUP_PAGE_SIZE + pageIndex, {
3339
+ chatGuid: event.chat.chatGuid,
3340
+ chatIdentifier: event.chat.chatIdentifier,
3341
+ })),
3342
+ });
3343
+ }
3344
+ if (pageEvents.length < BLUEBUBBLES_CATCHUP_PAGE_SIZE)
3345
+ break;
3346
+ const oldestMessageTimestamp = pageMessages
3347
+ .reduce((oldest, event) => Math.min(oldest, event.timestamp), Number.POSITIVE_INFINITY);
3348
+ if (oldestMessageTimestamp <= catchUpSince)
3349
+ break;
3350
+ if (page === BLUEBUBBLES_CATCHUP_MAX_PAGES - 1) {
3351
+ result.failed++;
3352
+ (0, runtime_1.emitNervesEvent)({
3353
+ level: "warn",
3354
+ component: "senses",
3355
+ event: "senses.bluebubbles_catchup_error",
3356
+ message: "bluebubbles upstream catch-up reached the bounded page limit",
3357
+ meta: {
3358
+ inspectedPages: BLUEBUBBLES_CATCHUP_MAX_PAGES,
3359
+ reason: "catch-up page limit reached before the outage window cutoff",
3360
+ },
3361
+ });
3362
+ }
3363
+ }
3364
+ for (const prepared of preparedCandidates) {
3365
+ result.inspected++;
3366
+ if (prepared.status === "skip") {
3367
+ result.skipped++;
3368
+ }
3369
+ }
3370
+ const readyCandidates = preparedCandidates.filter((prepared) => prepared.status === "ready");
3371
+ let lastRecoveredOrdinal = -1;
3372
+ await Promise.all(groupBlueBubblesObservationsByLane(readyCandidates).map(async (lane) => {
3373
+ for (const prepared of lane) {
3374
+ const { event, observationReservation } = prepared;
3375
+ try {
3376
+ options.lifecycleSignal?.throwIfAborted();
3377
+ const captured = await captureBlueBubblesSemanticEvent(event, resolvedDeps, "upstream-catchup", observationReservation);
3378
+ if (captured.status === "audit_only") {
3379
+ result.skipped++;
3380
+ continue;
3381
+ }
3382
+ if (!processTurns) {
3383
+ if (captured.writeResult === "semantic_capture_duplicate"
3384
+ && !semanticObservationGenerations.has(captured.capture.keyHash)
3385
+ && !pendingCaptureKeyHashes().has(captured.capture.keyHash)) {
3386
+ // Already has an outcome. Fencing it again would hold every older
3387
+ // reply in this chat behind a message nobody will process.
3388
+ result.skipped++;
3389
+ continue;
3390
+ }
3391
+ const generation = adoptBlueBubblesSemanticObservation(captured.capture.keyHash, observationReservation, false);
3392
+ if (captured.writeResult === "semantic_capture_duplicate") {
3393
+ if (!activeSemanticHandlingSlots.has(captured.capture.keyHash)) {
3394
+ suspendBlueBubblesSemanticObservation(generation);
3395
+ }
3396
+ result.skipped++;
3397
+ }
3398
+ else {
3399
+ // Runtime sync only captures work for the delayed recovery pass,
3400
+ // but its original generation must revoke older work now and be
3401
+ // reused by the queued recovery pass after any intervening turn.
3402
+ const promotion = (0, latest_turn_1.promote)(generation.reservation, {
3403
+ chatGuid: event.chat.chatGuid,
3404
+ chatIdentifier: event.chat.chatIdentifier,
3405
+ });
3406
+ if (promotion.status === "promoted")
3407
+ (0, latest_turn_1.finish)(promotion.capability);
3408
+ suspendBlueBubblesSemanticObservation(generation);
3409
+ result.queued = (result.queued ?? 0) + 1;
3410
+ }
3411
+ continue;
3412
+ }
3413
+ const handled = await handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, "upstream-catchup", {
3414
+ timeoutMs: BLUEBUBBLES_TURN_TIMEOUT_MS,
3415
+ autonomyBudgetTrigger: "recovery",
3416
+ observationReservation,
3417
+ lifecycleSignal: options.lifecycleSignal,
3418
+ });
3419
+ if (handled.reason === "semantic_claim_timeout") {
3420
+ continue;
3421
+ }
3422
+ if (shouldCountBlueBubblesRecoveryResultAsSkipped(handled.reason) || !handled.notifiedAgent) {
3423
+ result.skipped++;
3424
+ }
3425
+ else {
3426
+ result.recovered++;
3427
+ if (observationReservation.ordinal > lastRecoveredOrdinal) {
3428
+ lastRecoveredOrdinal = observationReservation.ordinal;
3429
+ result.lastRecoveredMessageGuid = event.messageGuid;
3430
+ }
3431
+ }
3432
+ }
3433
+ catch (error) {
3434
+ if (options.lifecycleSignal?.aborted)
3435
+ throw options.lifecycleSignal.reason;
3436
+ recordBlueBubblesRecoveryFailureForBudget(agentName, event, "upstream-catchup");
3437
+ result.failed++;
3438
+ (0, runtime_1.emitNervesEvent)({
3439
+ level: "warn",
3440
+ component: "senses",
3441
+ event: "senses.bluebubbles_catchup_error",
3442
+ message: "bluebubbles upstream catch-up message failed",
3443
+ meta: {
3444
+ messageGuid: event.messageGuid,
3445
+ reason: error instanceof Error ? error.message : String(error),
3446
+ },
3447
+ });
3448
+ }
3449
+ }
3450
+ }));
3451
+ if (result.inspected > 0 || result.recovered > 0 || result.skipped > 0 || result.failed > 0) {
3452
+ (0, runtime_1.emitNervesEvent)({
3453
+ component: "senses",
3454
+ event: "senses.bluebubbles_catchup_complete",
3455
+ message: "bluebubbles upstream catch-up pass completed",
3456
+ meta: { ...result },
3457
+ });
3458
+ }
3459
+ return result;
3460
+ }
3461
+ function recoverCapturedBlueBubblesInboundMessages(deps = {}, options = {}) {
3462
+ return withObservationScope((scope) => recoverCapturedBlueBubblesInboundMessagesInScope(scope, deps, options));
3463
+ }
3464
+ async function recoverCapturedBlueBubblesInboundMessagesInScope(scope, deps, options) {
3465
+ options.lifecycleSignal?.throwIfAborted();
3466
+ const resolvedDeps = { ...defaultDeps, ...deps };
3467
+ const agentName = resolvedDeps.getAgentName();
3468
+ const cutover = (0, semantic_receipts_1.initializeBlueBubblesSemanticCutover)(agentName);
3469
+ const result = { recovered: 0, skipped: 0, failed: 0 };
3470
+ const seenKeyHashes = new Set();
3471
+ const candidates = (0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName)
3472
+ .sort(semantic_receipts_1.compareBlueBubblesSemanticCaptureOrder);
3473
+ const preparedCandidates = [];
3474
+ for (const capture of candidates) {
3475
+ options.lifecycleSignal?.throwIfAborted();
3476
+ if (seenKeyHashes.has(capture.keyHash)) {
3477
+ preparedCandidates.push({ status: "skip", capture });
3478
+ continue;
3479
+ }
3480
+ seenKeyHashes.add(capture.keyHash);
3481
+ const disposition = (0, semantic_receipts_1.classifyBlueBubblesRecoveryRecord)(capture, cutover);
3482
+ if (disposition.disposition === "audit_only" && disposition.reason !== "audit_event") {
3483
+ preparedCandidates.push({ status: "skip", capture });
3484
+ continue;
3485
+ }
3486
+ const normalized = semanticCaptureToNormalizedEvent(capture);
3487
+ if (!normalized) {
3488
+ preparedCandidates.push({ status: "invalid", capture });
3489
+ continue;
3490
+ }
3491
+ preparedCandidates.push({
3492
+ status: "ready",
3493
+ capture,
3494
+ normalized,
3495
+ observationReservation: seededObservationReservation(capture.keyHash, scope.own(reserveBlueBubblesObservation(normalized))),
3496
+ });
3497
+ }
3498
+ for (const prepared of preparedCandidates) {
3499
+ const { capture } = prepared;
3500
+ if (prepared.status === "skip") {
3501
+ result.skipped++;
3502
+ continue;
3503
+ }
3504
+ if (prepared.status === "invalid") {
3505
+ result.failed++;
3506
+ (0, runtime_1.emitNervesEvent)({
3507
+ level: "warn",
3508
+ component: "senses",
3509
+ event: "senses.bluebubbles_capture_recovery_error",
3510
+ message: "captured bluebubbles message recovery failed",
3511
+ meta: {
3512
+ messageGuid: capture.event.eventGuid,
3513
+ sessionKey: capture.event.sessionKey,
3514
+ reason: "semantic_capture_routing_invalid",
3515
+ },
3516
+ });
3517
+ }
3518
+ }
3519
+ const readyCandidates = preparedCandidates.filter((prepared) => prepared.status === "ready");
3520
+ await Promise.all(groupBlueBubblesObservationsByLane(readyCandidates).map(async (lane) => {
3521
+ for (const prepared of lane) {
3522
+ const { capture, normalized, observationReservation } = prepared;
3523
+ try {
3524
+ options.lifecycleSignal?.throwIfAborted();
3525
+ const handled = await handleCapturedBlueBubblesSemanticEvent({
3526
+ status: "captured",
3527
+ capture,
3528
+ normalized,
3529
+ writeResult: "semantic_capture_duplicate",
3530
+ }, resolvedDeps, "webhook", {
3531
+ timeoutMs: BLUEBUBBLES_TURN_TIMEOUT_MS,
3532
+ autonomyBudgetTrigger: "recovery",
3533
+ semanticRecovery: true,
3534
+ observationReservation,
3535
+ lifecycleSignal: options.lifecycleSignal,
3536
+ });
3537
+ if (handled.reason === "semantic_claim_timeout") {
3538
+ continue;
3539
+ }
3540
+ if (shouldCountBlueBubblesRecoveryResultAsSkipped(handled.reason) || !handled.notifiedAgent) {
3541
+ result.skipped++;
3542
+ }
3543
+ else {
3544
+ result.recovered++;
3545
+ }
3546
+ }
3547
+ catch (error) {
3548
+ if (options.lifecycleSignal?.aborted)
3549
+ throw options.lifecycleSignal.reason;
3550
+ recordBlueBubblesRecoveryFailureForBudget(agentName, normalized, "webhook");
3551
+ result.failed++;
3552
+ (0, runtime_1.emitNervesEvent)({
3553
+ level: "warn",
3554
+ component: "senses",
3555
+ event: "senses.bluebubbles_capture_recovery_error",
3556
+ message: "captured bluebubbles message recovery failed",
3557
+ meta: {
3558
+ messageGuid: capture.event.eventGuid,
3559
+ sessionKey: capture.event.sessionKey,
3560
+ reason: error instanceof Error ? error.message : String(error),
3561
+ },
3562
+ });
3563
+ }
3564
+ }
3565
+ }));
3566
+ const semanticEventGuids = new Set(candidates
3567
+ .map((capture) => capture.event.eventGuid)
3568
+ .filter((eventGuid) => typeof eventGuid === "string")
3569
+ .map((eventGuid) => eventGuid.trim().toLowerCase()));
3570
+ for (const legacyEntry of (0, inbound_log_1.listRecordedBlueBubblesInbound)(agentName)) {
3571
+ if (semanticEventGuids.has(legacyEntry.messageGuid.trim().toLowerCase()))
3572
+ continue;
3573
+ (0, semantic_receipts_1.classifyBlueBubblesRecoveryRecord)(legacyEntry, cutover);
3574
+ result.skipped++;
3575
+ }
3576
+ return result;
3577
+ }
3578
+ async function recoverMissedBlueBubblesMessages(deps = {}) {
3579
+ const resolvedDeps = { ...defaultDeps, ...deps };
3580
+ const agentName = resolvedDeps.getAgentName();
3581
+ const cutover = (0, semantic_receipts_1.initializeBlueBubblesSemanticCutover)(agentName);
3582
+ const result = { recovered: 0, skipped: 0, pending: 0, failed: 0 };
3583
+ for (const candidate of (0, mutation_log_1.listBlueBubblesRecoveryCandidates)(agentName)) {
3584
+ (0, semantic_receipts_1.classifyBlueBubblesRecoveryRecord)(candidate, cutover);
3585
+ result.skipped++;
3586
+ }
3587
+ if (result.recovered > 0 || result.skipped > 0 || result.pending > 0 || result.failed > 0) {
3588
+ (0, runtime_1.emitNervesEvent)({
3589
+ component: "senses",
3590
+ event: "senses.bluebubbles_recovery_complete",
3591
+ message: "bluebubbles backlog recovery pass completed",
3592
+ meta: { ...result },
3593
+ });
3594
+ }
3595
+ return result;
3596
+ }
3597
+ function createBlueBubblesWebhookHandler(deps = {}, options = {}) {
3598
+ return async (req, res) => {
3599
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
3600
+ if (url.pathname === "/health") {
3601
+ if (req.method === "GET" || req.method === "HEAD") {
3602
+ writeJson(res, 200, { status: "ok", uptime: process.uptime() });
3603
+ return;
3604
+ }
3605
+ writeJson(res, 405, { error: "Method not allowed" });
3606
+ return;
3607
+ }
3608
+ const channelConfig = (0, config_1.getBlueBubblesChannelConfig)();
3609
+ const runtimeConfig = (0, config_1.getBlueBubblesConfig)();
3610
+ if (url.pathname !== channelConfig.webhookPath) {
3611
+ writeJson(res, 404, { error: "Not found" });
3612
+ return;
3613
+ }
3614
+ if (req.method !== "POST") {
3615
+ writeJson(res, 405, { error: "Method not allowed" });
3616
+ return;
3617
+ }
3618
+ if (!isWebhookPasswordValid(url, runtimeConfig.password)) {
3619
+ writeJson(res, 401, { error: "Unauthorized" });
3620
+ return;
3621
+ }
3622
+ // Only take in messages from the agent's own Apple ID: a server running
3623
+ // under another macOS account would hand the agent that person's iMessages.
3624
+ try {
3625
+ await { ...defaultDeps, ...deps }.verifyHostAccount();
3626
+ }
3627
+ catch (error) {
3628
+ writeJson(res, 403, { handled: false, notifiedAgent: false, error: error instanceof Error ? error.message : String(error) });
3629
+ return;
3630
+ }
3631
+ let payload;
3632
+ try {
3633
+ const rawBody = await readRequestBody(req);
3634
+ payload = JSON.parse(rawBody);
3635
+ }
3636
+ catch (error) {
3637
+ (0, runtime_1.emitNervesEvent)({
3638
+ level: "warn",
3639
+ component: "senses",
3640
+ event: "senses.bluebubbles_webhook_bad_json",
3641
+ message: "failed to parse bluebubbles webhook body",
3642
+ meta: {
3643
+ reason: error instanceof Error ? error.message : String(error),
3644
+ },
3645
+ });
3646
+ writeJson(res, 400, { error: "Invalid JSON body" });
3647
+ return;
3648
+ }
3649
+ let normalized;
3650
+ try {
3651
+ normalized = (0, model_1.normalizeBlueBubblesEvent)(payload);
3652
+ }
3653
+ catch (error) {
3654
+ if (error instanceof model_1.BlueBubblesIgnoredEventError) {
3655
+ (0, runtime_1.emitNervesEvent)({
3656
+ component: "senses",
3657
+ event: "senses.bluebubbles_event_skipped",
3658
+ message: "skipped ignorable bluebubbles event",
3659
+ meta: {
3660
+ eventType: error.eventType,
3661
+ },
3662
+ });
3663
+ writeJson(res, 200, {
3664
+ handled: true,
3665
+ notifiedAgent: false,
3666
+ reason: "ignored",
3667
+ });
3668
+ return;
3669
+ }
3670
+ (0, runtime_1.emitNervesEvent)({
3671
+ level: "error",
3672
+ component: "senses",
3673
+ event: "senses.bluebubbles_webhook_error",
3674
+ message: "bluebubbles webhook handling failed",
3675
+ meta: {
3676
+ /* v8 ignore next -- normalizeBlueBubblesEvent throws Error subclasses; String fallback is defensive @preserve */
3677
+ reason: error instanceof Error ? error.message : String(error),
3678
+ },
3679
+ });
3680
+ writeJson(res, 500, {
3681
+ /* v8 ignore next -- normalizeBlueBubblesEvent throws Error subclasses; String fallback is defensive @preserve */
3682
+ error: error instanceof Error ? error.message : String(error),
3683
+ });
3684
+ return;
3685
+ }
3686
+ const resolvedDeps = { ...defaultDeps, ...deps };
3687
+ // The scope outlives this request: it closes when the queued turn ends.
3688
+ const scope = new BlueBubblesObservationScope();
3689
+ const observationReservation = scope.own(reserveBlueBubblesObservation(normalized));
3690
+ let captured;
3691
+ try {
3692
+ captured = await captureBlueBubblesSemanticEvent(normalized, resolvedDeps, "webhook", observationReservation);
3693
+ }
3694
+ catch (error) {
3695
+ scope.close();
3696
+ (0, runtime_1.emitNervesEvent)({
3697
+ level: "error",
3698
+ component: "senses",
3699
+ event: "senses.bluebubbles_webhook_error",
3700
+ message: "bluebubbles semantic capture failed before acknowledgement",
3701
+ meta: {
3702
+ messageGuid: normalized.messageGuid,
3703
+ reason: error instanceof Error ? error.message : String(error),
3704
+ },
3705
+ });
3706
+ writeSemanticCaptureFailure(res);
3707
+ return;
3708
+ }
3709
+ if (captured.status === "audit_only") {
3710
+ scope.close();
3711
+ writeJson(res, 200, {
3712
+ handled: true,
3713
+ notifiedAgent: false,
3714
+ kind: normalized.kind,
3715
+ queued: false,
3716
+ reason: "ignored",
3717
+ });
3718
+ return;
3719
+ }
3720
+ writeJson(res, 200, {
3721
+ handled: true,
3722
+ notifiedAgent: false,
3723
+ kind: normalized.kind,
3724
+ queued: true,
3725
+ reason: "queued",
3726
+ });
3727
+ setTimeout(() => {
3728
+ if (options.lifecycleSignal?.aborted) {
3729
+ scope.close();
3730
+ return;
3731
+ }
3732
+ trackBlueBubblesTurn(handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, "webhook", {
3733
+ observationReservation,
3734
+ lifecycleSignal: options.lifecycleSignal,
3735
+ }).catch((error) => {
3736
+ if (options.lifecycleSignal?.aborted)
3737
+ return;
3738
+ (0, runtime_1.emitNervesEvent)({
3739
+ level: "error",
3740
+ component: "senses",
3741
+ event: "senses.bluebubbles_webhook_async_error",
3742
+ message: "bluebubbles webhook async handling failed after durable capture",
3743
+ meta: {
3744
+ reason: error instanceof Error ? error.message : String(error),
3745
+ },
3746
+ });
3747
+ }).finally(() => scope.close()));
3748
+ }, 0);
3749
+ };
3750
+ }
3751
+ function findImessageHandle(friend) {
3752
+ for (const ext of friend.externalIds) {
3753
+ if (ext.provider === "imessage-handle" && !ext.externalId.startsWith("group:")) {
3754
+ return ext.externalId;
3755
+ }
3756
+ }
3757
+ return undefined;
3758
+ }
3759
+ function normalizeBlueBubblesSessionKey(sessionKey) {
3760
+ const trimmed = sessionKey.trim();
3761
+ if (trimmed.startsWith("chat_identifier_")) {
3762
+ return `chat_identifier:${trimmed.slice("chat_identifier_".length)}`;
3763
+ }
3764
+ if (trimmed.startsWith("chat_")) {
3765
+ return `chat:${trimmed.slice("chat_".length)}`;
3766
+ }
3767
+ return trimmed;
3768
+ }
3769
+ function extractChatIdentifierFromSessionKey(sessionKey) {
3770
+ const normalizedKey = normalizeBlueBubblesSessionKey(sessionKey);
3771
+ if (normalizedKey.startsWith("chat:")) {
3772
+ const chatGuid = normalizedKey.slice("chat:".length).trim();
3773
+ const parts = chatGuid.split(";");
3774
+ return parts.length >= 3 ? parts[2]?.trim() || undefined : undefined;
3775
+ }
3776
+ if (normalizedKey.startsWith("chat_identifier:")) {
3777
+ const identifier = normalizedKey.slice("chat_identifier:".length).trim();
3778
+ return identifier || undefined;
3779
+ }
3780
+ return undefined;
3781
+ }
3782
+ function buildChatRefForSessionKey(friend, sessionKey) {
3783
+ const normalizedKey = normalizeBlueBubblesSessionKey(sessionKey);
3784
+ if (normalizedKey.startsWith("chat:")) {
3785
+ const chatGuid = normalizedKey.slice("chat:".length).trim();
3786
+ if (!chatGuid)
3787
+ return null;
3788
+ return {
3789
+ chatGuid,
3790
+ chatIdentifier: extractChatIdentifierFromSessionKey(sessionKey) ?? findImessageHandle(friend),
3791
+ isGroup: chatGuid.includes(";+;"),
3792
+ sessionKey,
3793
+ sendTarget: { kind: "chat_guid", value: chatGuid },
3794
+ participantHandles: [],
3795
+ };
3796
+ }
3797
+ const chatIdentifier = extractChatIdentifierFromSessionKey(sessionKey) ?? findImessageHandle(friend);
3798
+ if (!chatIdentifier)
3799
+ return null;
3800
+ return {
3801
+ chatIdentifier,
3802
+ isGroup: false,
3803
+ sessionKey,
3804
+ sendTarget: { kind: "chat_identifier", value: chatIdentifier },
3805
+ participantHandles: [],
3806
+ };
3807
+ }
3808
+ /**
3809
+ * The session a proactive send is saved into: the chat key it was sent on, else the friend's existing DM session, else
3810
+ * the DM key an inbound message from their handle would use (`chat:any;-;<handle>`), so their reply loads it.
3811
+ */
3812
+ function proactiveRecordKey(friend, sessionKey, chat, sentChatGuid) {
3813
+ if (normalizeBlueBubblesSessionKey(sessionKey).startsWith("chat:"))
3814
+ return sessionKey;
3815
+ // The DM the server actually sent into is where the friend's reply will be keyed.
3816
+ if (sentChatGuid?.includes(";-;"))
3817
+ return `chat:${sentChatGuid}`;
3818
+ const existing = (0, await_alert_1.resolveAlertKey)((0, identity_1.getAgentRoot)(), friend.id, "bluebubbles");
3819
+ if (existing?.includes(";-;"))
3820
+ return existing;
3821
+ /* v8 ignore start -- a non-chat key is routed by the friend's handle, so a delivered send always had one @preserve */
3822
+ const handle = findImessageHandle(friend) ?? chat.chatIdentifier;
3823
+ return handle ? `chat:any;-;${handle}` : null;
3824
+ /* v8 ignore stop */
3825
+ }
3826
+ /** Saves a delivered message into its chat. Never throws: recording never changes the result of a send that went out. */
3827
+ function recordBlueBubblesProactiveSend(friend, params, chat, sentChatGuid) {
3828
+ try {
3829
+ const key = proactiveRecordKey(friend, params.sessionKey, chat, sentChatGuid);
3830
+ /* v8 ignore next -- a delivered send always had a chat GUID or identifier to send to @preserve */
3831
+ if (!key)
3832
+ return;
3833
+ const origin = params.origin ?? "proactive";
3834
+ (0, outbound_record_1.recordOutboundInSession)({
3835
+ agentRoot: (0, identity_1.getAgentRoot)(), friendId: friend.id, channel: "bluebubbles", key, content: params.text, origin,
3836
+ deliveryId: params.deliveryId ?? `proactive:${(0, node_crypto_1.randomUUID)()}`, originLabel: outbound_record_1.OUTBOUND_ORIGIN_LABELS[origin],
3837
+ });
3838
+ }
3839
+ catch (error) {
3840
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.bluebubbles_proactive_record_error",
3841
+ message: "the BlueBubbles message was sent, but could not be saved into its chat",
3842
+ meta: { friendId: friend.id, error: error instanceof Error ? error.message : String(error) } });
3843
+ }
3844
+ }
3845
+ async function sendProactiveBlueBubblesMessageToSession(params, deps = {}) {
3846
+ if ((0, bluebubbles_meta_guard_1.containsInternalMetaMarkers)(params.text)) {
3847
+ (0, bluebubbles_meta_guard_1.emitBluebubblesMetaBlocked)({
3848
+ site: "proactive",
3849
+ message: "bluebubbles proactive send blocked: internal meta markers",
3850
+ meta: {
3851
+ friendId: params.friendId,
3852
+ sessionKey: params.sessionKey,
3853
+ },
3854
+ });
3855
+ return { delivered: false, reason: "blocked_meta_content" };
3856
+ }
3857
+ const resolvedDeps = { ...defaultDeps, ...deps };
3858
+ const client = resolvedDeps.createClient();
3859
+ const store = resolvedDeps.createFriendStore();
3860
+ let friend;
3861
+ try {
3862
+ friend = await store.get(params.friendId);
3863
+ }
3864
+ catch {
3865
+ friend = null;
3866
+ }
3867
+ // Direct filesystem fallback — store.get() with name resolution wasn't working in production
3868
+ // despite correct compiled code. Bypass the entire store abstraction.
3869
+ /* v8 ignore start -- direct filesystem name resolution @preserve */
3870
+ if (!friend) {
3871
+ try {
3872
+ const friendsDir = path.join((0, identity_1.getAgentRoot)(), "friends");
3873
+ const files = fs.readdirSync(friendsDir).filter((f) => f.endsWith(".json"));
3874
+ for (const file of files) {
3875
+ const raw = JSON.parse(fs.readFileSync(path.join(friendsDir, file), "utf-8"));
3876
+ if (raw.name?.toLowerCase() === params.friendId.toLowerCase()) {
3877
+ friend = raw;
3878
+ (0, runtime_1.emitNervesEvent)({
3879
+ component: "senses",
3880
+ event: "senses.bluebubbles_proactive_name_resolved",
3881
+ message: "resolved friend by name via direct filesystem scan",
3882
+ meta: { friendId: params.friendId, resolvedId: raw.id, name: raw.name },
3883
+ });
3884
+ break;
3885
+ }
3886
+ }
3887
+ }
3888
+ catch (err) {
3889
+ (0, runtime_1.emitNervesEvent)({
3890
+ level: "warn",
3891
+ component: "senses",
3892
+ event: "senses.bluebubbles_proactive_name_resolve_error",
3893
+ message: "direct filesystem name resolution failed",
3894
+ meta: { friendId: params.friendId, error: err instanceof Error ? err.message : String(err) },
3895
+ });
3896
+ }
3897
+ }
3898
+ /* v8 ignore stop */
3899
+ if (!friend) {
3900
+ (0, runtime_1.emitNervesEvent)({
3901
+ level: "warn",
3902
+ component: "senses",
3903
+ event: "senses.bluebubbles_proactive_no_friend",
3904
+ message: "proactive send skipped: friend not found",
3905
+ meta: { friendId: params.friendId, sessionKey: params.sessionKey },
3906
+ });
3907
+ return { delivered: false, reason: "friend_not_found" };
3908
+ }
3909
+ const explicitCrossChatAuthorized = params.intent === "explicit_cross_chat"
3910
+ && friends_1.TRUSTED_LEVELS.has(params.authorizingSession?.trustLevel ?? "stranger");
3911
+ if (!explicitCrossChatAuthorized && !friends_1.TRUSTED_LEVELS.has(friend.trustLevel ?? "stranger")) {
3912
+ (0, runtime_1.emitNervesEvent)({
3913
+ component: "senses",
3914
+ event: "senses.bluebubbles_proactive_trust_skip",
3915
+ message: "proactive send skipped: trust level not allowed",
3916
+ meta: {
3917
+ friendId: params.friendId,
3918
+ sessionKey: params.sessionKey,
3919
+ trustLevel: friend.trustLevel ?? "unknown",
3920
+ intent: params.intent ?? "generic_outreach",
3921
+ authorizingTrustLevel: params.authorizingSession?.trustLevel ?? null,
3922
+ },
3923
+ });
3924
+ return { delivered: false, reason: "trust_skip" };
3925
+ }
3926
+ const chat = buildChatRefForSessionKey(friend, params.sessionKey);
3927
+ if (!chat) {
3928
+ (0, runtime_1.emitNervesEvent)({
3929
+ level: "warn",
3930
+ component: "senses",
3931
+ event: "senses.bluebubbles_proactive_no_handle",
3932
+ message: "proactive send skipped: no iMessage handle found",
3933
+ meta: { friendId: params.friendId, sessionKey: params.sessionKey },
3934
+ });
3935
+ return { delivered: false, reason: "missing_target" };
3936
+ }
3937
+ // Proactive outreach to individuals must go to DMs, never group chats.
3938
+ // Explicit cross-chat responses (bridge completions, delegation returns) ARE allowed to groups
3939
+ // because the request originated from that group.
3940
+ /* v8 ignore start -- group gate: only fires when proactive send targets a group session @preserve */
3941
+ if (chat.isGroup && params.intent !== "explicit_cross_chat") {
3942
+ (0, runtime_1.emitNervesEvent)({
3943
+ level: "warn",
3944
+ component: "senses",
3945
+ event: "senses.bluebubbles_proactive_group_blocked",
3946
+ message: "proactive send blocked: would route to group chat",
3947
+ meta: { friendId: params.friendId, sessionKey: params.sessionKey, chatGuid: chat.chatGuid ?? null, intent: params.intent ?? null },
3948
+ });
3949
+ return { delivered: false, reason: "group_blocked" };
3950
+ }
3951
+ /* v8 ignore stop */
3952
+ const internalContentBlockReason = (0, proactive_content_guard_1.getProactiveInternalContentBlockReason)(params.text);
3953
+ if (internalContentBlockReason) {
3954
+ (0, proactive_content_guard_1.emitProactiveInternalContentBlocked)({
3955
+ friendId: params.friendId,
3956
+ sessionKey: params.sessionKey,
3957
+ reason: internalContentBlockReason,
3958
+ source: "session_send",
3959
+ intent: params.intent ?? "generic_outreach",
3960
+ });
3961
+ return { delivered: false, reason: "internal_content_blocked" };
3962
+ }
3963
+ try {
3964
+ const sent = await client.sendText({ chat, text: params.text });
3965
+ (0, runtime_1.emitNervesEvent)({
3966
+ component: "senses",
3967
+ event: "senses.bluebubbles_proactive_sent",
3968
+ message: "proactive bluebubbles message sent",
3969
+ meta: {
3970
+ friendId: params.friendId,
3971
+ sessionKey: params.sessionKey,
3972
+ chatGuid: chat.chatGuid ?? null,
3973
+ chatIdentifier: chat.chatIdentifier ?? null,
3974
+ },
3975
+ });
3976
+ recordBlueBubblesProactiveSend(friend, params, chat, sent?.chatGuid);
3977
+ return { delivered: true };
3978
+ }
3979
+ catch (error) {
3980
+ if (error instanceof client_1.BlueBubblesSendError && error.errorCode === "chat_unresolved") {
3981
+ (0, runtime_1.emitNervesEvent)({
3982
+ level: "warn",
3983
+ component: "senses",
3984
+ event: "senses.bluebubbles_proactive_no_chat",
3985
+ message: "no BlueBubbles chat matched this friend, so nothing was sent",
3986
+ meta: { friendId: params.friendId, sessionKey: params.sessionKey },
3987
+ });
3988
+ return { delivered: false, reason: "missing_target" };
3989
+ }
3990
+ if (error instanceof host_account_verifier_1.BlueBubblesHostAccountError) {
3991
+ (0, runtime_1.emitNervesEvent)({
3992
+ level: "warn",
3993
+ component: "senses",
3994
+ event: "senses.bluebubbles_proactive_host_account_refused",
3995
+ message: "proactive bluebubbles send refused: the server is signed in to another account",
3996
+ meta: { friendId: params.friendId, sessionKey: params.sessionKey, reason: error.message },
3997
+ });
3998
+ return { delivered: false, reason: "host_account_refused" };
3999
+ }
4000
+ (0, runtime_1.emitNervesEvent)({
4001
+ level: "error",
4002
+ component: "senses",
4003
+ event: "senses.bluebubbles_proactive_send_error",
4004
+ message: "proactive bluebubbles send failed",
4005
+ meta: {
4006
+ friendId: params.friendId,
4007
+ sessionKey: params.sessionKey,
4008
+ reason: error instanceof Error ? error.message : String(error),
4009
+ },
4010
+ });
4011
+ return { delivered: false, reason: "send_error" };
4012
+ }
4013
+ }
4014
+ function scanPendingBlueBubblesFiles(pendingRoot) {
4015
+ const results = [];
4016
+ let friendIds;
4017
+ try {
4018
+ friendIds = fs.readdirSync(pendingRoot);
4019
+ }
4020
+ catch {
4021
+ return results;
4022
+ }
4023
+ for (const friendId of friendIds) {
4024
+ const bbDir = path.join(pendingRoot, friendId, "bluebubbles");
4025
+ let keys;
4026
+ try {
4027
+ keys = fs.readdirSync(bbDir);
4028
+ }
4029
+ catch {
4030
+ continue;
4031
+ }
4032
+ for (const key of keys) {
4033
+ const keyDir = path.join(bbDir, key);
4034
+ let files;
4035
+ try {
4036
+ files = fs.readdirSync(keyDir);
4037
+ }
4038
+ catch {
4039
+ continue;
4040
+ }
4041
+ for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
4042
+ const filePath = path.join(keyDir, file);
4043
+ try {
4044
+ const content = fs.readFileSync(filePath, "utf-8");
4045
+ results.push({ friendId, key, filePath, content });
4046
+ }
4047
+ catch {
4048
+ // skip unreadable files
4049
+ }
4050
+ }
4051
+ }
4052
+ }
4053
+ return results;
4054
+ }
4055
+ async function drainAndSendPendingBlueBubbles(deps = {}, pendingRoot) {
4056
+ const resolvedDeps = { ...defaultDeps, ...deps };
4057
+ const root = pendingRoot ?? path.join((0, identity_1.getAgentRoot)(), "state", "pending");
4058
+ const client = resolvedDeps.createClient();
4059
+ const store = resolvedDeps.createFriendStore();
4060
+ const pendingFiles = scanPendingBlueBubblesFiles(root);
4061
+ const result = { sent: 0, skipped: 0, failed: 0 };
4062
+ for (const { friendId, filePath, content } of pendingFiles) {
4063
+ let parsed;
4064
+ try {
4065
+ parsed = JSON.parse(content);
4066
+ }
4067
+ catch {
4068
+ result.failed++;
4069
+ try {
4070
+ fs.unlinkSync(filePath);
4071
+ }
4072
+ catch { /* ignore */ }
4073
+ continue;
4074
+ }
4075
+ const messageText = typeof parsed.content === "string" ? parsed.content : "";
4076
+ if (!messageText.trim()) {
4077
+ result.skipped++;
4078
+ try {
4079
+ fs.unlinkSync(filePath);
4080
+ }
4081
+ catch { /* ignore */ }
4082
+ continue;
4083
+ }
4084
+ if ((0, bluebubbles_meta_guard_1.containsInternalMetaMarkers)(messageText)) {
4085
+ result.skipped++;
4086
+ try {
4087
+ fs.unlinkSync(filePath);
4088
+ }
4089
+ catch { /* ignore */ }
4090
+ (0, bluebubbles_meta_guard_1.emitBluebubblesMetaBlocked)({
4091
+ site: "drain",
4092
+ message: "bluebubbles drain blocked: internal meta markers",
4093
+ meta: {
4094
+ friendId,
4095
+ filePath,
4096
+ },
4097
+ });
4098
+ continue;
4099
+ }
4100
+ const internalBlockReason = (0, proactive_content_guard_1.getProactiveInternalContentBlockReason)(messageText);
4101
+ if (internalBlockReason) {
4102
+ result.skipped++;
4103
+ try {
4104
+ fs.unlinkSync(filePath);
4105
+ }
4106
+ catch { /* ignore */ }
4107
+ (0, proactive_content_guard_1.emitProactiveInternalContentBlocked)({
4108
+ friendId,
4109
+ reason: internalBlockReason,
4110
+ source: "pending_drain",
4111
+ });
4112
+ continue;
4113
+ }
4114
+ let friend;
4115
+ try {
4116
+ friend = await store.get(friendId);
4117
+ }
4118
+ catch {
4119
+ friend = null;
4120
+ }
4121
+ if (!friend) {
4122
+ result.skipped++;
4123
+ try {
4124
+ fs.unlinkSync(filePath);
4125
+ }
4126
+ catch { /* ignore */ }
4127
+ (0, runtime_1.emitNervesEvent)({
4128
+ level: "warn",
4129
+ component: "senses",
4130
+ event: "senses.bluebubbles_proactive_no_friend",
4131
+ message: "proactive send skipped: friend not found",
4132
+ meta: { friendId },
4133
+ });
4134
+ continue;
4135
+ }
4136
+ if (!friends_1.TRUSTED_LEVELS.has(friend.trustLevel ?? "stranger")) {
4137
+ result.skipped++;
4138
+ try {
4139
+ fs.unlinkSync(filePath);
4140
+ }
4141
+ catch { /* ignore */ }
4142
+ (0, runtime_1.emitNervesEvent)({
4143
+ component: "senses",
4144
+ event: "senses.bluebubbles_proactive_trust_skip",
4145
+ message: "proactive send skipped: trust level not allowed",
4146
+ meta: { friendId, trustLevel: friend.trustLevel ?? "unknown" },
4147
+ });
4148
+ continue;
4149
+ }
4150
+ const handle = findImessageHandle(friend);
4151
+ if (!handle) {
4152
+ result.skipped++;
4153
+ try {
4154
+ fs.unlinkSync(filePath);
4155
+ }
4156
+ catch { /* ignore */ }
4157
+ (0, runtime_1.emitNervesEvent)({
4158
+ level: "warn",
4159
+ component: "senses",
4160
+ event: "senses.bluebubbles_proactive_no_handle",
4161
+ message: "proactive send skipped: no iMessage handle found",
4162
+ meta: { friendId },
4163
+ });
4164
+ continue;
4165
+ }
4166
+ const chat = {
4167
+ chatIdentifier: handle,
4168
+ isGroup: false,
4169
+ sessionKey: friendId,
4170
+ sendTarget: { kind: "chat_identifier", value: handle },
4171
+ participantHandles: [],
4172
+ };
4173
+ try {
4174
+ await client.sendText({ chat, text: messageText });
4175
+ result.sent++;
4176
+ try {
4177
+ fs.unlinkSync(filePath);
4178
+ }
4179
+ catch { /* ignore */ }
4180
+ (0, runtime_1.emitNervesEvent)({
4181
+ component: "senses",
4182
+ event: "senses.bluebubbles_proactive_sent",
4183
+ message: "proactive bluebubbles message sent",
4184
+ meta: { friendId, handle },
4185
+ });
4186
+ }
4187
+ catch (error) {
4188
+ result.failed++;
4189
+ (0, runtime_1.emitNervesEvent)({
4190
+ level: "error",
4191
+ component: "senses",
4192
+ event: "senses.bluebubbles_proactive_send_error",
4193
+ message: "proactive bluebubbles send failed",
4194
+ meta: {
4195
+ friendId,
4196
+ handle,
4197
+ reason: error instanceof Error ? error.message : String(error),
4198
+ },
4199
+ });
4200
+ }
4201
+ }
4202
+ if (result.sent > 0 || result.skipped > 0 || result.failed > 0) {
4203
+ (0, runtime_1.emitNervesEvent)({
4204
+ component: "senses",
4205
+ event: "senses.bluebubbles_proactive_drain_complete",
4206
+ message: "bluebubbles proactive drain complete",
4207
+ meta: { sent: result.sent, skipped: result.skipped, failed: result.failed },
4208
+ });
4209
+ }
4210
+ return result;
4211
+ }
4212
+ const runningBlueBubblesApps = new WeakMap();
4213
+ /**
4214
+ * Stop the sense now. Aborting first ends every in-flight turn (each leaves its
4215
+ * inbound pending for the next process to replay) instead of letting
4216
+ * server.close() wait on them. Resolves with how many turns were still running.
4217
+ */
4218
+ async function stopBlueBubblesApp(server) {
4219
+ runningBlueBubblesApps.get(server)?.();
4220
+ server.close();
4221
+ server.closeAllConnections();
4222
+ return drainBlueBubblesTurns();
4223
+ }
4224
+ function startBlueBubblesApp(deps = {}) {
4225
+ const resolvedDeps = { ...defaultDeps, ...deps };
4226
+ const lifecycleController = new AbortController();
4227
+ (0, semantic_receipts_1.initializeBlueBubblesSemanticCutover)(resolvedDeps.getAgentName());
4228
+ resolvedDeps.createClient();
4229
+ seedBlueBubblesStartupSemanticObservations(resolvedDeps);
4230
+ const startupCatchUpObservationBatch = (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
4231
+ const channelConfig = (0, config_1.getBlueBubblesChannelConfig)();
4232
+ const server = resolvedDeps.createServer(createBlueBubblesWebhookHandler(deps, {
4233
+ lifecycleSignal: lifecycleController.signal,
4234
+ }));
4235
+ let recoveryPassRunning = false;
4236
+ let runtimeSyncRunning = false;
4237
+ let recoveryDelayTimer = null;
4238
+ let webhookReconciler = null;
4239
+ let closed = false;
4240
+ function triggerRecoveryPass() {
4241
+ /* v8 ignore next -- close clears both recovery timers; guard covers an already-queued host callback @preserve */
4242
+ if (closed)
4243
+ return;
4244
+ /* v8 ignore next -- re-entrant timer guard; difficult to force deterministically without timing the turn lock @preserve */
4245
+ if (recoveryPassRunning)
4246
+ return;
4247
+ recoveryPassRunning = true;
4248
+ trackBlueBubblesTurn(recoverQueuedBlueBubblesMessages(resolvedDeps, {
4249
+ lifecycleSignal: lifecycleController.signal,
4250
+ })
4251
+ /* v8 ignore start -- defensive wrapper; expected per-message failures are handled inside recovery helpers @preserve */
4252
+ .catch((error) => {
4253
+ if (closed || lifecycleController.signal.aborted)
4254
+ return;
4255
+ (0, runtime_1.emitNervesEvent)({
4256
+ level: "warn",
4257
+ component: "senses",
4258
+ event: "senses.bluebubbles_recovery_error",
4259
+ message: "bluebubbles queued recovery pass failed",
4260
+ meta: { reason: error instanceof Error ? error.message : String(error) },
4261
+ });
4262
+ })
4263
+ /* v8 ignore stop */
4264
+ .finally(() => {
4265
+ recoveryPassRunning = false;
4266
+ }));
4267
+ }
4268
+ function scheduleRecoveryPass() {
4269
+ if (closed)
4270
+ return;
4271
+ /* v8 ignore next -- duplicate scheduling guard for overlapping health sync completions @preserve */
4272
+ if (recoveryDelayTimer !== null)
4273
+ return;
4274
+ recoveryDelayTimer = setTimeout(() => {
4275
+ recoveryDelayTimer = null;
4276
+ triggerRecoveryPass();
4277
+ }, BLUEBUBBLES_RECOVERY_PASS_DELAY_MS);
4278
+ }
4279
+ function triggerRuntimeSync(catchUpObservationBatch) {
4280
+ if (closed || runtimeSyncRunning)
4281
+ return;
4282
+ runtimeSyncRunning = true;
4283
+ void syncBlueBubblesRuntime(resolvedDeps, {
4284
+ ...(catchUpObservationBatch ? { catchUpObservationBatch } : {}),
4285
+ lifecycleSignal: lifecycleController.signal,
4286
+ })
4287
+ .then(scheduleRecoveryPass)
4288
+ .catch((error) => {
4289
+ if (closed)
4290
+ return;
4291
+ (0, runtime_1.emitNervesEvent)({
4292
+ level: "warn",
4293
+ component: "senses",
4294
+ event: "senses.bluebubbles_recovery_error",
4295
+ message: "bluebubbles runtime sync failed",
4296
+ meta: { reason: error instanceof Error ? error.message : String(error) },
4297
+ });
4298
+ })
4299
+ .finally(() => {
4300
+ runtimeSyncRunning = false;
4301
+ });
4302
+ }
4303
+ const runtimeTimer = setInterval(() => {
4304
+ /* v8 ignore next -- close clears this interval; guard covers an already-queued host callback @preserve */
4305
+ if (closed)
4306
+ return;
4307
+ triggerRuntimeSync();
4308
+ }, BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS);
4309
+ const recoveryTimer = setInterval(triggerRecoveryPass, BLUEBUBBLES_RECOVERY_PASS_INTERVAL_MS);
4310
+ function shutdown() {
4311
+ if (closed)
4312
+ return;
4313
+ closed = true;
4314
+ webhookReconciler?.close();
4315
+ webhookReconciler = null;
4316
+ lifecycleController.abort(new Error("bluebubbles_runtime_shutdown"));
4317
+ clearInterval(runtimeTimer);
4318
+ clearInterval(recoveryTimer);
4319
+ if (recoveryDelayTimer !== null) {
4320
+ clearTimeout(recoveryDelayTimer);
4321
+ recoveryDelayTimer = null;
4322
+ }
4323
+ }
4324
+ server.on?.("close", shutdown);
4325
+ runningBlueBubblesApps.set(server, shutdown);
4326
+ server.listen(channelConfig.port, () => {
4327
+ const blueBubblesConfig = (0, config_1.getBlueBubblesConfig)();
4328
+ webhookReconciler = (0, webhook_registration_1.createBlueBubblesWebhookReconciler)({
4329
+ serverUrl: blueBubblesConfig.serverUrl,
4330
+ password: blueBubblesConfig.password,
4331
+ callbackPort: channelConfig.port,
4332
+ callbackPath: channelConfig.webhookPath,
4333
+ agentName: resolvedDeps.getAgentName(),
4334
+ machineId: (0, machine_identity_1.loadOrCreateMachineIdentity)().machineId,
4335
+ requestTimeoutMs: channelConfig.requestTimeoutMs,
4336
+ listenerReady: true,
4337
+ hostUsername: (0, identity_1.loadAgentConfig)().senses?.bluebubbles.hostUsername,
4338
+ });
4339
+ (0, runtime_1.emitNervesEvent)({
4340
+ component: "channels",
4341
+ event: "channel.app_started",
4342
+ message: "BlueBubbles sense started",
4343
+ meta: { port: channelConfig.port, webhookPath: channelConfig.webhookPath },
4344
+ });
4345
+ });
4346
+ triggerRuntimeSync(startupCatchUpObservationBatch);
4347
+ return server;
4348
+ }