@ouro.bot/cli 0.1.0-alpha.154 → 0.1.0-alpha.1540

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