@ouro.bot/cli 0.1.0-alpha.153 → 0.1.0-alpha.1532

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 (1669) 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 +8964 -41
  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 +59 -0
  492. package/dist/heart/tool-approval.js +382 -0
  493. package/dist/heart/tool-description.js +155 -0
  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 +1190 -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 +553 -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 +4663 -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 +627 -350
  760. package/dist/senses/commands.js +66 -3
  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 +1216 -289
  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 +51 -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 +1270 -378
  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 -1268
  1647. package/dist/senses/contextual-heartbeat.js +0 -106
  1648. package/dist/senses/debug-activity.js +0 -154
  1649. package/dist/senses/inner-dialog-worker.js +0 -154
  1650. package/dist/senses/inner-dialog.js +0 -780
  1651. package/subagents/README.md +0 -7
  1652. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  1653. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  1654. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  1655. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  1656. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  1657. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  1658. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  1659. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  1660. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  1661. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  1662. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  1663. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  1664. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  1665. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  1666. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  1667. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  1668. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
  1669. /package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/store.js +0 -0
@@ -0,0 +1,2789 @@
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.readOrCreateTelegramIdentityKey = void 0;
37
+ exports.createSabQueueProtectiveStateVerifier = createSabQueueProtectiveStateVerifier;
38
+ exports.telegramAcceptanceAuditOwnerDigest = telegramAcceptanceAuditOwnerDigest;
39
+ exports.sanctuaryTelegramTurnReceiptDigest = sanctuaryTelegramTurnReceiptDigest;
40
+ exports.sanctuaryTelegramTurnReceiptMac = sanctuaryTelegramTurnReceiptMac;
41
+ exports.sanctuaryTelegramAuditLifecycleMac = sanctuaryTelegramAuditLifecycleMac;
42
+ exports.sanctuaryTelegramUnauthorizedDropMac = sanctuaryTelegramUnauthorizedDropMac;
43
+ exports.sanctuaryTelegramApprovalEvidenceMac = sanctuaryTelegramApprovalEvidenceMac;
44
+ exports.telegramBotIdFromToken = telegramBotIdFromToken;
45
+ exports.ownerDisplayName = ownerDisplayName;
46
+ exports.opaqueTelegramSubject = opaqueTelegramSubject;
47
+ exports.migrateTelegramFriendIdentity = migrateTelegramFriendIdentity;
48
+ exports.migrateTelegramSessionIdentity = migrateTelegramSessionIdentity;
49
+ exports.parseTelegramSenseCredentials = parseTelegramSenseCredentials;
50
+ exports.createTelegramSenseApp = createTelegramSenseApp;
51
+ exports.loadTelegramSenseCredentials = loadTelegramSenseCredentials;
52
+ exports.createProductionTelegramRelationshipComposition = createProductionTelegramRelationshipComposition;
53
+ exports.startTelegramSenseApp = startTelegramSenseApp;
54
+ exports.sendTelegramExternalEventDecision = sendTelegramExternalEventDecision;
55
+ exports.sendTelegramDelegatedAuditNotice = sendTelegramDelegatedAuditNotice;
56
+ exports.sendTelegramOwnerNotice = sendTelegramOwnerNotice;
57
+ exports.createProactiveRepetitionGuard = createProactiveRepetitionGuard;
58
+ exports.withTelegramTypingIndicator = withTelegramTypingIndicator;
59
+ exports.sendTelegramAwaitFollowUp = sendTelegramAwaitFollowUp;
60
+ const node_crypto_1 = require("node:crypto");
61
+ const node_async_hooks_1 = require("node:async_hooks");
62
+ const node_fs_1 = require("node:fs");
63
+ const path = __importStar(require("node:path"));
64
+ const friends_1 = require("@ouro.bot/friends");
65
+ const delegated_command_1 = require("../a2a/delegated-command");
66
+ const identity_1 = require("../heart/identity");
67
+ const sanctuary_house_1 = require("./sanctuary-house");
68
+ const sanctuary_acceptance_marker_1 = require("../heart/daemon/sanctuary-acceptance-marker");
69
+ const runtime_credentials_1 = require("../heart/runtime-credentials");
70
+ const runtime_1 = require("../nerves/runtime");
71
+ const chat_interaction_1 = require("../heart/chat-interaction");
72
+ const nerves_1 = require("../nerves");
73
+ const sanctuary_interactive_control_1 = require("./sanctuary-interactive-control");
74
+ const telegram_approval_relay_1 = require("./telegram-approval-relay");
75
+ const sanctuary_runtime_1 = require("./sanctuary-runtime");
76
+ const sanctuary_sab_1 = require("./sanctuary-sab");
77
+ const sanctuary_download_credit_presentation_1 = require("./sanctuary-download-credit-presentation");
78
+ const shared_turn_1 = require("./shared-turn");
79
+ const config_1 = require("../heart/config");
80
+ const telegram_identity_key_1 = require("./telegram-identity-key");
81
+ var telegram_identity_key_2 = require("./telegram-identity-key");
82
+ Object.defineProperty(exports, "readOrCreateTelegramIdentityKey", { enumerable: true, get: function () { return telegram_identity_key_2.readOrCreateTelegramIdentityKey; } });
83
+ const telegram_client_1 = require("./telegram-client");
84
+ const inbound_journal_1 = require("./inbound-journal");
85
+ const sanctuary_authority_resident_1 = require("./sanctuary-authority-resident");
86
+ const root_host_approval_runtime_1 = require("./root-host-approval-runtime");
87
+ const tools_sanctuary_host_1 = require("../repertoire/tools-sanctuary-host");
88
+ const sanctuary_runtime_2 = require("./sanctuary-runtime");
89
+ const sanctuary_full_visibility_contract_1 = require("./sanctuary-full-visibility-contract");
90
+ const sanctuary_install_state_contract_1 = require("./sanctuary-install-state-contract");
91
+ const sanctuary_media_catalog_contract_1 = require("./sanctuary-media-catalog-contract");
92
+ const sanctuary_storage_optimization_contract_1 = require("./sanctuary-storage-optimization-contract");
93
+ const sanctuary_grounding_1 = require("./sanctuary-grounding");
94
+ const telegram_approval_runtime_1 = require("./telegram-approval-runtime");
95
+ const telegram_audit_ledger_1 = require("./telegram-audit-ledger");
96
+ const session_events_1 = require("../heart/session-events");
97
+ const telegram_owner_route_1 = require("./telegram-owner-route");
98
+ const telegram_handoff_1 = require("./telegram-handoff");
99
+ const router_1 = require("../heart/external-events/router");
100
+ const session_transaction_1 = require("../mind/session-transaction");
101
+ const approval_files_1 = require("../heart/approval-files");
102
+ const approval_store_1 = require("../heart/approval-store");
103
+ const tools_awaiting_1 = require("../repertoire/tools-awaiting");
104
+ const obligations_1 = require("../arc/obligations");
105
+ const orientation_frame_1 = require("../heart/orientation-frame");
106
+ const telegram_attachments_1 = require("./telegram-attachments");
107
+ const understand_1 = require("../heart/attachments/understand");
108
+ const pending_1 = require("../mind/pending");
109
+ const relationship_authorization_1 = require("../repertoire/relationship-authorization");
110
+ const telegram_admission_1 = require("./telegram-admission");
111
+ const telegram_effect_adapter_1 = require("./telegram-effect-adapter");
112
+ const telegram_chat_actions_1 = require("./telegram-chat-actions");
113
+ const atomic_file_1 = require("../heart/atomic-file");
114
+ const repeat_while_1 = require("./repeat-while");
115
+ const EMPTY_SHARED_TURN_DIAGNOSTIC = "(agent responded but response was empty)";
116
+ function hasUserVisibleTurnResponse(response) {
117
+ const text = response.trim();
118
+ return text.length > 0 && text !== EMPTY_SHARED_TURN_DIAGNOSTIC;
119
+ }
120
+ function responseFallbackAfterDeliveries(result, successfulDeliveryCount) {
121
+ const failedTerminal = result.responseDeliveryFailure?.text ?? (result.responseCausalSessionEventId ? result.deliveryFailures.at(-1)?.text : undefined);
122
+ const response = failedTerminal ?? (successfulDeliveryCount === 0 && result.deliveryFailures.length === 0 ? result.response : "");
123
+ return hasUserVisibleTurnResponse(response) ? response : null;
124
+ }
125
+ function createFullVisibilityProgress() {
126
+ const progress = {};
127
+ return { progress, emptyResponseFallback: () => progress.fallback?.() };
128
+ }
129
+ function createSabQueueProtectiveStateVerifier(options = {}) {
130
+ let client = null;
131
+ return async (action) => {
132
+ client ??= (0, sanctuary_sab_1.createSanctuarySabClient)({ loadApiKey: options.loadApiKey ?? (() => (0, sanctuary_runtime_1.loadSanctuarySabApiKey)("sanctuary")), fetch: options.fetch, now: options.now });
133
+ const snapshot = await client.readQueue();
134
+ const paused = snapshot.paused;
135
+ const digest = (0, node_crypto_1.createHash)("sha256").update(`sabnzbd.queue.paused=${String(paused)}`).digest("hex");
136
+ const verified = action.action === "sabnzbd.pause" && paused && action.verification.verified && action.verification.digest === digest;
137
+ return { verified, reference: `sabnzbd.queue.paused:${digest}:${snapshot.observedAt}` };
138
+ };
139
+ }
140
+ const APPROVAL_EXPIRY_RECONCILE_INTERVAL_MS = 1_000;
141
+ const TELEGRAM_SUBJECT_DOMAIN = "ouroboros.telegram.subject.v1";
142
+ const TELEGRAM_SUBJECT = /^tg_[A-Za-z0-9_-]{43}$/u;
143
+ const TELEGRAM_SUBJECT_INDEX = "identity-subjects.json";
144
+ const TELEGRAM_ACCEPTANCE_AUDIT_EVENTS = new Set([
145
+ "approval.acceptance_continuation_transition",
146
+ "approval.acceptance_transition",
147
+ "senses.sanctuary_health_delivered",
148
+ "senses.sanctuary_read_receipt",
149
+ "senses.telegram_approved_restart_end",
150
+ "senses.telegram_approved_restart_error",
151
+ "senses.telegram_approved_restart_start",
152
+ "senses.telegram_approval_continuation_delivered",
153
+ "senses.telegram_approval_prompt_bound",
154
+ "senses.telegram_turn_end",
155
+ "senses.telegram_turn_error",
156
+ "senses.telegram_turn_start",
157
+ "telegram.approval_prompt_terminalized",
158
+ "telegram.approval_expiry_observed",
159
+ "telegram.approval_stale_callback_settled",
160
+ "telegram.callback_recovery_settled",
161
+ "telegram.callback_settled",
162
+ "telegram.update_dropped",
163
+ ]);
164
+ const telegramAcceptanceAuditOwner = new node_async_hooks_1.AsyncLocalStorage();
165
+ const telegramAcceptanceAuditScenario = new node_async_hooks_1.AsyncLocalStorage();
166
+ const telegramAcceptanceAuditExplicitCommit = new node_async_hooks_1.AsyncLocalStorage();
167
+ /** The opaque reference a household Friend's message is known by in its session and its delivery keys. */
168
+ function telegramHouseholdReference(identityKey, botId, userId, updateId, messageId) {
169
+ return `telegram-inbound:${(0, node_crypto_1.createHmac)("sha256", identityKey).update(`${botId}\0${userId}\0${updateId}\0${messageId}`).digest("hex")}`;
170
+ }
171
+ const telegramInboundTurn = new node_async_hooks_1.AsyncLocalStorage();
172
+ /** Telegram keeps an update it has not been told was handled for at most a day (https://core.telegram.org/bots/api#getting-updates). */
173
+ const TELEGRAM_REDELIVERY_WINDOW_MS = 24 * 60 * 60_000;
174
+ /** Why a message a stopped process left must not run again, or null when it may. */
175
+ function telegramReplayRefusal(entry) {
176
+ if (entry.spoke)
177
+ return "the turn stopped after a reply went out, so it is not run again";
178
+ if (entry.attempts >= inbound_journal_1.MAX_INBOUND_ATTEMPTS)
179
+ return `the turn did not finish in ${entry.attempts} attempts`;
180
+ return null;
181
+ }
182
+ const telegramAcceptanceAudits = new Map();
183
+ const TELEGRAM_TURN_RECEIPT_DOMAINS = {
184
+ "sanctuary-telegram-turn-receipt-v3": "ouroboros.telegram.turn-receipt.v3",
185
+ "sanctuary-telegram-turn-receipt-v4": "ouroboros.telegram.turn-receipt.v4",
186
+ };
187
+ const TELEGRAM_TURN_LEDGER_MAX_BYTES = 4 * 1024 * 1024;
188
+ const TELEGRAM_TURN_LEDGER_MAX_ROWS = 500;
189
+ const TELEGRAM_TURN_LEDGER_MAX_ROW_BYTES = 16 * 1024;
190
+ const telegramTurnLedgerTails = new Map();
191
+ function telegramAcceptanceAuditOwnerDigest(identityKey, agentName, root) {
192
+ return (0, node_crypto_1.createHmac)("sha256", identityKey)
193
+ .update(`ouroboros.telegram.acceptance-audit-owner.v1\0${agentName}\0${root}`, "utf8")
194
+ .digest("hex");
195
+ }
196
+ function acquireTelegramAcceptanceAudit(root, agentName, identityKey, privateValues, scenarioHandleDigest, releaseHook, maxBytes) {
197
+ const existing = telegramAcceptanceAudits.get(root);
198
+ if (existing) {
199
+ if (existing.identityKey !== identityKey)
200
+ throw new Error("Telegram acceptance audit identity changed while active");
201
+ if (existing.scenarioHandleDigest !== scenarioHandleDigest)
202
+ throw new Error("Telegram acceptance audit scenario changed while active");
203
+ existing.ledger.assertHealthy();
204
+ existing.references += 1;
205
+ return { ledger: existing.ledger, ownerDigest: existing.ownerDigest, scenarioHandleDigest: existing.scenarioHandleDigest, release: () => {
206
+ existing.references -= 1;
207
+ if (existing.references === 0) {
208
+ try {
209
+ existing.unregister();
210
+ }
211
+ finally {
212
+ telegramAcceptanceAudits.delete(root);
213
+ }
214
+ releaseHook?.();
215
+ }
216
+ } };
217
+ }
218
+ const ledger = (0, telegram_audit_ledger_1.createTelegramAuditLedger)({ root, identityKey, privateValues, _maxBytes: maxBytes });
219
+ const ownerDigest = telegramAcceptanceAuditOwnerDigest(identityKey, agentName, root);
220
+ let record;
221
+ const unregister = (0, nerves_1.registerGlobalLogSink)((event) => {
222
+ if (!TELEGRAM_ACCEPTANCE_AUDIT_EVENTS.has(event.event))
223
+ return;
224
+ if (telegramAcceptanceAuditExplicitCommit.getStore())
225
+ return;
226
+ const explicitOwner = event.meta.acceptanceAuditOwnerDigest;
227
+ const contextualOwner = telegramAcceptanceAuditOwner.getStore();
228
+ if (explicitOwner !== ownerDigest && contextualOwner !== ownerDigest)
229
+ return;
230
+ const scenario = event.meta.scenarioHandleDigest;
231
+ if (typeof scenario !== "string" || !/^[0-9a-f]{64}$/u.test(scenario) || record.scenarioHandleDigest !== scenario) {
232
+ ledger.poison(new Error("Telegram acceptance audit scenario ownership drift"));
233
+ }
234
+ ledger.append(event);
235
+ });
236
+ record = { agentName, identityKey, ledger, ownerDigest, references: 1, scenarioHandleDigest, unregister };
237
+ telegramAcceptanceAudits.set(root, record);
238
+ return { ledger, ownerDigest, scenarioHandleDigest, release: () => {
239
+ record.references -= 1;
240
+ if (record.references === 0) {
241
+ try {
242
+ record.unregister();
243
+ }
244
+ finally {
245
+ telegramAcceptanceAudits.delete(root);
246
+ }
247
+ releaseHook?.();
248
+ }
249
+ } };
250
+ }
251
+ function sanctuaryTelegramTurnReceiptDigest(identityKey, schemaVersion, purpose, value) {
252
+ return (0, node_crypto_1.createHmac)("sha256", identityKey).update(`${TELEGRAM_TURN_RECEIPT_DOMAINS[schemaVersion]}\0${purpose}\0${value}`, "utf8").digest("hex");
253
+ }
254
+ function canonicalReceiptJson(value) {
255
+ if (Array.isArray(value))
256
+ return `[${value.map(canonicalReceiptJson).join(",")}]`;
257
+ if (value && typeof value === "object") {
258
+ const record = value;
259
+ return `{${Object.keys(record).filter((key) => record[key] !== undefined).sort().map((key) => `${JSON.stringify(key)}:${canonicalReceiptJson(record[key])}`).join(",")}}`;
260
+ }
261
+ const rendered = JSON.stringify(value);
262
+ if (rendered === undefined)
263
+ throw new Error("Telegram receipt contains an unsupported value");
264
+ return rendered;
265
+ }
266
+ function sanctuaryTelegramTurnReceiptMac(identityKey, value) {
267
+ const unsigned = Object.fromEntries(Object.entries(value).filter(([key]) => key !== "receiptMac"));
268
+ return sanctuaryTelegramTurnReceiptDigest(identityKey, "sanctuary-telegram-turn-receipt-v4", "receipt", canonicalReceiptJson(unsigned));
269
+ }
270
+ function sanctuaryTelegramAuditLifecycleMac(identityKey, schemaVersion, event, meta) {
271
+ const unsigned = Object.fromEntries(Object.entries(meta).filter(([key]) => key !== "lifecycleMac"));
272
+ return sanctuaryTelegramTurnReceiptDigest(identityKey, schemaVersion, "audit-lifecycle", canonicalReceiptJson({ event, meta: unsigned }));
273
+ }
274
+ function sanctuaryTelegramUnauthorizedDropMac(identityKey, schemaVersion, value) {
275
+ return sanctuaryTelegramTurnReceiptDigest(identityKey, schemaVersion, "unauthorized-drop", canonicalReceiptJson(value));
276
+ }
277
+ function sanctuaryTelegramApprovalEvidenceMac(identityKey, event, meta) {
278
+ const unsigned = Object.fromEntries(Object.entries(meta).filter(([key]) => key !== "evidenceMac"));
279
+ return sanctuaryTelegramTurnReceiptDigest(identityKey, "sanctuary-telegram-turn-receipt-v3", "approval-evidence", canonicalReceiptJson({ event, meta: unsigned }));
280
+ }
281
+ function sameTelegramLedgerMetadata(left, right) {
282
+ return left.dev === right.dev
283
+ && left.ino === right.ino
284
+ && left.mode === right.mode
285
+ && left.nlink === right.nlink
286
+ && left.uid === right.uid
287
+ && left.gid === right.gid
288
+ && left.size === right.size
289
+ && left.mtimeNs === right.mtimeNs
290
+ && left.ctimeNs === right.ctimeNs;
291
+ }
292
+ function readStableBoundedTelegramLedger(filePath, afterPreReadStat) {
293
+ let handle;
294
+ try {
295
+ handle = (0, node_fs_1.openSync)(filePath, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW);
296
+ }
297
+ catch (error) {
298
+ if (error.code === "ENOENT")
299
+ return null;
300
+ throw error;
301
+ }
302
+ try {
303
+ const before = (0, node_fs_1.fstatSync)(handle, { bigint: true });
304
+ if (!before.isFile())
305
+ throw new Error("Telegram turn receipt ledger must be a regular file");
306
+ if (before.size > BigInt(TELEGRAM_TURN_LEDGER_MAX_BYTES))
307
+ throw new Error("Telegram turn receipt ledger exceeds its bound");
308
+ afterPreReadStat?.(filePath);
309
+ const expectedBytes = Number(before.size);
310
+ const content = Buffer.allocUnsafe(expectedBytes);
311
+ let offset = 0;
312
+ while (offset < expectedBytes) {
313
+ const bytesRead = (0, node_fs_1.readSync)(handle, content, offset, expectedBytes - offset, offset);
314
+ if (bytesRead === 0)
315
+ throw new Error("Telegram turn receipt ledger changed during read");
316
+ offset += bytesRead;
317
+ }
318
+ const overflow = Buffer.allocUnsafe(1);
319
+ const overflowBytes = (0, node_fs_1.readSync)(handle, overflow, 0, 1, expectedBytes);
320
+ const after = (0, node_fs_1.fstatSync)(handle, { bigint: true });
321
+ const pathAfter = (0, node_fs_1.lstatSync)(filePath, { bigint: true });
322
+ if (overflowBytes !== 0 || !sameTelegramLedgerMetadata(before, after)
323
+ || !pathAfter.isFile() || pathAfter.dev !== before.dev || pathAfter.ino !== before.ino) {
324
+ throw new Error("Telegram turn receipt ledger changed during read");
325
+ }
326
+ return content.toString("utf8");
327
+ }
328
+ finally {
329
+ (0, node_fs_1.closeSync)(handle);
330
+ }
331
+ }
332
+ function validateSanctuaryTurnReceipt(value) {
333
+ const grounded = value.schemaVersion === "sanctuary-telegram-turn-receipt-v4";
334
+ const exactKeys = ["completedAt", "deliveries", "deliveryCount", "errorCategory", "providerInvocationCount", "responseDigest", "scenarioHandleDigest", "schemaVersion", "sequenceDigest", "status", "toolInvocationCount", "toolResultDigests", "updateDigest", ...(grounded ? ["receiptMac", "toolGroundings"] : [])].sort();
335
+ const deliveries = value.deliveries;
336
+ if (JSON.stringify(Object.keys(value).sort()) !== JSON.stringify(exactKeys)
337
+ || (!grounded && value.schemaVersion !== "sanctuary-telegram-turn-receipt-v3")
338
+ || typeof value.scenarioHandleDigest !== "string" || !/^[0-9a-f]{64}$/u.test(value.scenarioHandleDigest)
339
+ || (value.status !== "success" && value.status !== "error")
340
+ || (value.status === "success"
341
+ ? value.errorCategory !== null
342
+ : typeof value.errorCategory !== "string" || value.errorCategory.length < 1 || value.errorCategory.length > 128)
343
+ || ![value.updateDigest, value.sequenceDigest, value.responseDigest].every((digest) => typeof digest === "string" && /^[0-9a-f]{64}$/u.test(digest))
344
+ || !Array.isArray(value.toolResultDigests) || value.toolResultDigests.length > 100 || !value.toolResultDigests.every((digest) => typeof digest === "string" && /^[0-9a-f]{64}$/u.test(digest))
345
+ || !Array.isArray(deliveries) || deliveries.length > 100 || !deliveries.every((delivery) => {
346
+ if (!delivery || typeof delivery !== "object" || Array.isArray(delivery))
347
+ return false;
348
+ const record = delivery;
349
+ return JSON.stringify(Object.keys(record).sort()) === JSON.stringify(grounded ? ["chunkDigest", "messageIdDigest", "redactedText", "utf16Units"] : ["chunkDigest", "messageIdDigest"])
350
+ && typeof record.chunkDigest === "string" && /^[0-9a-f]{64}$/u.test(record.chunkDigest)
351
+ && typeof record.messageIdDigest === "string" && /^[0-9a-f]{64}$/u.test(record.messageIdDigest)
352
+ && (!grounded || (typeof record.redactedText === "string" && record.redactedText.length === record.utf16Units && record.utf16Units <= 1_200));
353
+ })
354
+ || (grounded && (!Array.isArray(value.toolGroundings) || value.toolGroundings.length !== 1 || !value.toolGroundings.every((raw) => {
355
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
356
+ return false;
357
+ const record = raw;
358
+ if (JSON.stringify(Object.keys(record).sort()) !== JSON.stringify(["facts", "groundingDigest", "observedAt", "resultDigest", "sourceIdentityDigest", "toolName"]) || (record.toolName !== "unraid_get_system" && record.toolName !== "unraid_get_storage")
359
+ || typeof record.resultDigest !== "string" || !/^[0-9a-f]{64}$/u.test(record.resultDigest) || typeof record.groundingDigest !== "string" || !/^[0-9a-f]{64}$/u.test(record.groundingDigest)
360
+ || typeof record.sourceIdentityDigest !== "string" || !/^[0-9a-f]{64}$/u.test(record.sourceIdentityDigest) || typeof record.observedAt !== "string" || !Number.isFinite(Date.parse(record.observedAt)) || new Date(Date.parse(record.observedAt)).toISOString() !== record.observedAt
361
+ || !record.facts || typeof record.facts !== "object" || Array.isArray(record.facts))
362
+ return false;
363
+ return (0, sanctuary_grounding_1.sanctuaryGroundingDigest)(record.facts) === record.groundingDigest && value.toolResultDigests.includes(record.resultDigest);
364
+ })))
365
+ || (grounded && (typeof value.receiptMac !== "string" || !/^[0-9a-f]{64}$/u.test(value.receiptMac)))
366
+ || ![value.providerInvocationCount, value.toolInvocationCount].every((count) => Number.isSafeInteger(count) && Number(count) >= 0 && Number(count) <= 1_000)
367
+ || !Number.isSafeInteger(value.deliveryCount) || value.deliveryCount !== deliveries.length
368
+ || typeof value.completedAt !== "string" || value.completedAt.length > 30 || !Number.isFinite(Date.parse(value.completedAt)) || new Date(Date.parse(value.completedAt)).toISOString() !== value.completedAt)
369
+ throw new Error("Telegram turn receipt ledger row is invalid");
370
+ }
371
+ async function appendSanctuaryTurnReceipt(agentRoot, receipt, afterPreReadStat) {
372
+ const filePath = path.join(agentRoot, "state", "acceptance", "telegram-turns.ndjson");
373
+ const previous = telegramTurnLedgerTails.get(filePath) ?? Promise.resolve();
374
+ const current = previous.catch(() => undefined).then(() => {
375
+ (0, node_fs_1.mkdirSync)(path.dirname(filePath), { recursive: true, mode: 0o700 });
376
+ let existing = [];
377
+ const raw = readStableBoundedTelegramLedger(filePath, afterPreReadStat);
378
+ if (raw !== null) {
379
+ existing = raw.split("\n").filter(Boolean);
380
+ if (existing.length > TELEGRAM_TURN_LEDGER_MAX_ROWS || existing.some((line) => Buffer.byteLength(line) > TELEGRAM_TURN_LEDGER_MAX_ROW_BYTES))
381
+ throw new Error("Telegram turn receipt ledger is invalid");
382
+ for (const line of existing) {
383
+ validateSanctuaryTurnReceipt(JSON.parse(line));
384
+ }
385
+ }
386
+ validateSanctuaryTurnReceipt(receipt);
387
+ const serialized = JSON.stringify(receipt);
388
+ if (Buffer.byteLength(serialized) > TELEGRAM_TURN_LEDGER_MAX_ROW_BYTES)
389
+ throw new Error("Telegram turn receipt exceeds its bound");
390
+ const lines = [...existing, serialized].slice(-TELEGRAM_TURN_LEDGER_MAX_ROWS);
391
+ let aggregateBytes = lines.reduce((total, line) => total + Buffer.byteLength(line) + 1, 0);
392
+ while (aggregateBytes > TELEGRAM_TURN_LEDGER_MAX_BYTES && lines.length > 1) {
393
+ aggregateBytes -= Buffer.byteLength(lines.shift()) + 1;
394
+ }
395
+ (0, atomic_file_1.writeFileAtomicSync)(filePath, `${lines.join("\n")}\n`);
396
+ });
397
+ telegramTurnLedgerTails.set(filePath, current);
398
+ try {
399
+ await current;
400
+ }
401
+ finally {
402
+ if (telegramTurnLedgerTails.get(filePath) === current)
403
+ telegramTurnLedgerTails.delete(filePath);
404
+ }
405
+ }
406
+ function requiredText(value, label) {
407
+ if (typeof value !== "string" || value.trim().length === 0)
408
+ throw new Error(`Telegram ${label} is missing`);
409
+ return value.trim();
410
+ }
411
+ function canonicalTelegramId(value, label) {
412
+ const text = requiredText(value, label);
413
+ if (!/^[1-9][0-9]*$/u.test(text))
414
+ throw new Error(`Telegram ${label} must be a canonical positive decimal string`);
415
+ return text;
416
+ }
417
+ function telegramBotIdFromToken(token) {
418
+ const match = /^([1-9][0-9]*):/u.exec(token.trim());
419
+ if (!match)
420
+ throw new Error("Telegram bot token does not expose a canonical numeric bot id");
421
+ return match[1];
422
+ }
423
+ function errorCode(error) {
424
+ return error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : undefined;
425
+ }
426
+ /** The admitted owner's display name comes from the household's own house config. */
427
+ function ownerDisplayName(agentName) {
428
+ const { ownerName } = (0, sanctuary_house_1.readSanctuaryHouse)((0, identity_1.getAgentRoot)(agentName));
429
+ return ownerName === sanctuary_house_1.DEFAULT_SANCTUARY_HOUSE.ownerName ? "Owner" : ownerName;
430
+ }
431
+ function opaqueTelegramSubject(identityKey, botToken, authorizedUserId, authorizedChatId) {
432
+ const payload = [
433
+ TELEGRAM_SUBJECT_DOMAIN,
434
+ `bot:${botToken.length}:${botToken}`,
435
+ `user:${authorizedUserId.length}:${authorizedUserId}`,
436
+ `chat:${authorizedChatId.length}:${authorizedChatId}`,
437
+ ].join("\0");
438
+ return `tg_${(0, node_crypto_1.createHmac)("sha256", identityKey).update(payload, "utf8").digest("base64url")}`;
439
+ }
440
+ function readTelegramSubjectIndex(agentRoot, subject) {
441
+ const indexPath = path.join(agentRoot, "state", "senses", "telegram", TELEGRAM_SUBJECT_INDEX);
442
+ let text;
443
+ let handle;
444
+ try {
445
+ handle = (0, node_fs_1.openSync)(indexPath, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW);
446
+ const metadata = (0, node_fs_1.fstatSync)(handle);
447
+ if (!metadata.isFile() || (metadata.mode & 0o777) !== 0o600)
448
+ throw new Error("Telegram identity subject index permissions are invalid");
449
+ text = (0, node_fs_1.readFileSync)(handle, "utf8");
450
+ }
451
+ catch (error) {
452
+ if (errorCode(error) === "ENOENT")
453
+ return [];
454
+ throw error;
455
+ }
456
+ finally {
457
+ if (handle !== undefined)
458
+ (0, node_fs_1.closeSync)(handle);
459
+ }
460
+ const parsed = JSON.parse(text);
461
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
462
+ throw new Error("Telegram identity subject index is invalid");
463
+ const record = parsed;
464
+ if (record.version !== 1 || typeof record.subject !== "string" || !TELEGRAM_SUBJECT.test(record.subject) || !Array.isArray(record.legacySubjects)
465
+ || Object.keys(record).sort().join(",") !== "legacySubjects,subject,version") {
466
+ throw new Error("Telegram identity subject index is invalid");
467
+ }
468
+ const legacySubjects = record.legacySubjects;
469
+ if (!legacySubjects.every((candidate) => typeof candidate === "string" && TELEGRAM_SUBJECT.test(candidate))) {
470
+ throw new Error("Telegram identity subject index is invalid");
471
+ }
472
+ return record.subject === subject ? [] : [record.subject];
473
+ }
474
+ function discoverTelegramFilesystemSubjects(agentRoot) {
475
+ const subjects = new Set();
476
+ const addFriendDirectorySubjects = (root) => {
477
+ let entries;
478
+ try {
479
+ entries = (0, node_fs_1.readdirSync)(root, { withFileTypes: true });
480
+ }
481
+ catch (error) {
482
+ if (errorCode(error) === "ENOENT")
483
+ return;
484
+ throw error;
485
+ }
486
+ for (const entry of entries) {
487
+ if (!entry.isDirectory() || !entry.name.startsWith("telegram-user:"))
488
+ continue;
489
+ const candidate = entry.name.slice("telegram-user:".length);
490
+ if (TELEGRAM_SUBJECT.test(candidate))
491
+ subjects.add(candidate);
492
+ }
493
+ };
494
+ addFriendDirectorySubjects(path.join(agentRoot, "state", "sessions"));
495
+ addFriendDirectorySubjects(path.join(agentRoot, "state", "pending"));
496
+ addFriendDirectorySubjects(path.join(agentRoot, "state", "pending-returns"));
497
+ const friendsRoot = path.join(agentRoot, "friends");
498
+ let friendFiles;
499
+ try {
500
+ friendFiles = (0, node_fs_1.readdirSync)(friendsRoot, { withFileTypes: true });
501
+ }
502
+ catch (error) {
503
+ if (errorCode(error) === "ENOENT")
504
+ return [...subjects];
505
+ throw error;
506
+ }
507
+ for (const entry of friendFiles) {
508
+ if (!entry.isFile() || !entry.name.endsWith(".json"))
509
+ continue;
510
+ const friend = JSON.parse((0, node_fs_1.readFileSync)(path.join(friendsRoot, entry.name), "utf8"));
511
+ if (!friend || typeof friend !== "object" || !Array.isArray(friend.externalIds)) {
512
+ throw new Error("Telegram Friend identity record is invalid");
513
+ }
514
+ for (const external of friend.externalIds) {
515
+ if (!external || typeof external !== "object")
516
+ throw new Error("Telegram Friend external identity is invalid");
517
+ const identity = external;
518
+ if (identity.provider === "telegram-user" && typeof identity.externalId === "string" && TELEGRAM_SUBJECT.test(identity.externalId)) {
519
+ subjects.add(identity.externalId);
520
+ }
521
+ }
522
+ }
523
+ return [...subjects];
524
+ }
525
+ function writeTelegramSubjectIndex(agentRoot, subject, legacySubjects, hooks = {}) {
526
+ const directory = path.join(agentRoot, "state", "senses", "telegram");
527
+ const indexPath = path.join(directory, TELEGRAM_SUBJECT_INDEX);
528
+ const directoryHandle = (0, telegram_identity_key_1.openSecureTelegramDirectory)(directory);
529
+ const temporaryPath = path.join(directory, `.identity-subjects.${(0, node_crypto_1.randomBytes)(12).toString("base64url")}.tmp`);
530
+ let temporaryHandle;
531
+ try {
532
+ temporaryHandle = (0, node_fs_1.openSync)(temporaryPath, node_fs_1.constants.O_CREAT | node_fs_1.constants.O_EXCL | node_fs_1.constants.O_WRONLY | node_fs_1.constants.O_NOFOLLOW, 0o600);
533
+ hooks.afterCreateTemporary?.(temporaryPath);
534
+ const contents = `${JSON.stringify({ version: 1, subject, legacySubjects: [...legacySubjects] }, null, 2)}\n`;
535
+ (0, node_fs_1.writeFileSync)(temporaryHandle, contents);
536
+ (0, node_fs_1.fsyncSync)(temporaryHandle);
537
+ (0, node_fs_1.closeSync)(temporaryHandle);
538
+ temporaryHandle = undefined;
539
+ (0, node_fs_1.renameSync)(temporaryPath, indexPath);
540
+ (0, node_fs_1.fsyncSync)(directoryHandle);
541
+ }
542
+ finally {
543
+ if (temporaryHandle !== undefined)
544
+ (0, node_fs_1.closeSync)(temporaryHandle);
545
+ if ((0, node_fs_1.existsSync)(temporaryPath))
546
+ (0, node_fs_1.unlinkSync)(temporaryPath);
547
+ (0, node_fs_1.closeSync)(directoryHandle);
548
+ }
549
+ }
550
+ async function migrateTelegramFriendIdentity(agentRoot, legacyUserId, subject) {
551
+ const store = new friends_1.FileFriendStore(path.join(agentRoot, "friends"));
552
+ const legacy = await store.findByExternalId("telegram-user", legacyUserId);
553
+ if (!legacy)
554
+ return;
555
+ const current = await store.findByExternalId("telegram-user", subject);
556
+ if (current && current.id !== legacy.id)
557
+ throw new Error("Telegram friend identity migration is ambiguous");
558
+ legacy.externalIds = legacy.externalIds.map((external) => external.provider === "telegram-user" && external.externalId === legacyUserId
559
+ ? { ...external, externalId: subject }
560
+ : external);
561
+ if (legacy.name === `Telegram user ${legacyUserId}`)
562
+ legacy.name = `Telegram user ${subject}`;
563
+ legacy.updatedAt = new Date().toISOString();
564
+ await store.put(legacy.id, legacy);
565
+ }
566
+ function migrateTelegramSessionIdentity(agentRoot, legacyUserId, legacyChatId, subject) {
567
+ const legacyFriendId = `telegram-user:${legacyUserId}`;
568
+ const opaqueFriendId = `telegram-user:${subject}`;
569
+ const migrateDirectory = (root) => {
570
+ const legacy = path.join(root, legacyFriendId);
571
+ const opaque = path.join(root, opaqueFriendId);
572
+ if (!(0, node_fs_1.existsSync)(legacy))
573
+ return (0, node_fs_1.existsSync)(opaque) ? opaque : null;
574
+ if ((0, node_fs_1.existsSync)(opaque))
575
+ throw new Error("Telegram session identity migration is ambiguous");
576
+ (0, node_fs_1.mkdirSync)(root, { recursive: true });
577
+ (0, node_fs_1.renameSync)(legacy, opaque);
578
+ return opaque;
579
+ };
580
+ const sessions = migrateDirectory(path.join(agentRoot, "state", "sessions"));
581
+ if (sessions) {
582
+ const legacySession = path.join(sessions, "telegram", `telegram_${legacyChatId}.json`);
583
+ const opaqueSession = path.join(sessions, "telegram", `telegram_${subject}.json`);
584
+ if ((0, node_fs_1.existsSync)(legacySession)) {
585
+ if ((0, node_fs_1.existsSync)(opaqueSession))
586
+ throw new Error("Telegram session file migration is ambiguous");
587
+ (0, node_fs_1.renameSync)(legacySession, opaqueSession);
588
+ }
589
+ }
590
+ const pending = migrateDirectory(path.join(agentRoot, "state", "pending"));
591
+ if (pending) {
592
+ const legacyPending = path.join(pending, "telegram", `telegram:${legacyChatId}`);
593
+ const opaquePending = path.join(pending, "telegram", `telegram:${subject}`);
594
+ if ((0, node_fs_1.existsSync)(legacyPending)) {
595
+ if ((0, node_fs_1.existsSync)(opaquePending))
596
+ throw new Error("Telegram pending identity migration is ambiguous");
597
+ (0, node_fs_1.renameSync)(legacyPending, opaquePending);
598
+ }
599
+ }
600
+ migrateDirectory(path.join(agentRoot, "state", "pending-returns"));
601
+ }
602
+ function redactTelegramPrivateValues(error, privateValues) {
603
+ let message = error instanceof Error ? error.message : String(error);
604
+ for (const privateValue of privateValues) {
605
+ if (privateValue)
606
+ message = message.split(privateValue).join("[redacted]");
607
+ }
608
+ return message;
609
+ }
610
+ function parseTelegramSenseCredentials(value) {
611
+ return {
612
+ botToken: requiredText(value.telegramBotToken, "bot token"),
613
+ authorizedUserId: canonicalTelegramId(value.telegramAuthorizedUserId, "authorized user id"),
614
+ authorizedChatId: canonicalTelegramId(value.telegramAuthorizedChatId, "authorized chat id"),
615
+ };
616
+ }
617
+ function createTelegramSenseApp(options) {
618
+ const authorityTransport = options.authorityTransport;
619
+ if (authorityTransport && options.agentName !== "sanctuary") {
620
+ throw new Error("Sanctuary Telegram authority transport cannot serve another agent");
621
+ }
622
+ if (authorityTransport && options.credentials.botToken !== undefined) {
623
+ throw new Error("Sanctuary Telegram authority transport forbids a resident bot token");
624
+ }
625
+ const botToken = options.credentials.botToken === undefined
626
+ ? null
627
+ : requiredText(options.credentials.botToken, "bot token");
628
+ if (!botToken && !authorityTransport) {
629
+ throw new Error("Telegram bot token is missing; Sanctuary requires an explicit gateway transport");
630
+ }
631
+ const botId = options.credentials.botId !== undefined
632
+ ? canonicalTelegramId(options.credentials.botId, "bot id")
633
+ : options.admission && botToken ? telegramBotIdFromToken(botToken) : null;
634
+ if (authorityTransport && botId === null) {
635
+ throw new Error("Sanctuary Telegram authority transport requires a pinned bot id");
636
+ }
637
+ const authorizedUserId = canonicalTelegramId(options.credentials.authorizedUserId, "authorized user id");
638
+ const authorizedChatId = canonicalTelegramId(options.credentials.authorizedChatId, "authorized chat id");
639
+ const agentRoot = options._agentRoot ?? (0, identity_1.getAgentRoot)(options.agentName);
640
+ const identityKey = options.identityKey === undefined
641
+ ? (0, telegram_identity_key_1.readOrCreateTelegramIdentityKey)(agentRoot)
642
+ : (0, telegram_identity_key_1.canonicalTelegramIdentityKey)(options.identityKey);
643
+ const subject = opaqueTelegramSubject(identityKey, botId ?? botToken, authorizedUserId, authorizedChatId);
644
+ const transportPrivateValues = [botToken ?? "", authorizedUserId, authorizedChatId];
645
+ const transportError = (error) => redactTelegramPrivateValues(error, transportPrivateValues);
646
+ const api = authorityTransport?.api ?? options.api ?? (0, telegram_client_1.createTelegramBotApi)({ token: botToken });
647
+ const proactiveRepetitionGuard = createProactiveRepetitionGuard();
648
+ const sendTypingIndicator = async (chatId) => { await api.request("sendChatAction", { chat_id: chatId, action: "typing" }); };
649
+ const offsetStore = options.offsetStore ?? new telegram_client_1.FileTelegramOffsetStore(path.join(agentRoot, "state", "senses", "telegram", "offset.json"));
650
+ const inboxStore = options.inboxStore ?? new telegram_client_1.FileTelegramUpdateInboxStore(path.join(agentRoot, "state", "senses", "telegram", "inbox.json"));
651
+ const admissionStore = options.admission
652
+ ? new telegram_admission_1.FileTelegramAdmissionStore(path.join(agentRoot, "state", "senses", "telegram", "admissions"))
653
+ : undefined;
654
+ const runTurn = options.runTurn ?? options._runTurn ?? shared_turn_1.runSenseTurn;
655
+ const collectToolReceipts = options._runWithToolReceiptCollection ?? sanctuary_runtime_2.runWithSanctuaryToolReceiptCollection;
656
+ const useSanctuaryRuntime = options.agentName === "sanctuary" && !options.runTurn;
657
+ const readScenarioHandleDigest = () => (options.acceptanceMarker
658
+ ? options.acceptanceMarker()
659
+ : (0, sanctuary_acceptance_marker_1.readSanctuaryAcceptanceMarker)(options.agentName))?.scenarioHandleDigest;
660
+ let acceptanceAuditLease;
661
+ const retireAcceptanceAudit = () => {
662
+ const lease = acceptanceAuditLease;
663
+ if (!lease)
664
+ return;
665
+ const errors = [];
666
+ try {
667
+ lease.ledger.assertHealthy();
668
+ }
669
+ catch (error) {
670
+ errors.push(error);
671
+ }
672
+ try {
673
+ lease.release();
674
+ }
675
+ catch (error) {
676
+ errors.push(error);
677
+ }
678
+ finally {
679
+ acceptanceAuditLease = undefined;
680
+ }
681
+ if (errors.length === 1)
682
+ throw errors[0];
683
+ if (errors.length > 1)
684
+ throw new AggregateError(errors, "Telegram acceptance audit retirement failed");
685
+ };
686
+ const ensureAcceptanceAudit = () => {
687
+ if (!useSanctuaryRuntime)
688
+ return undefined;
689
+ const scenarioHandleDigest = readScenarioHandleDigest();
690
+ const effectScenarioHandleDigest = telegramAcceptanceAuditScenario.getStore();
691
+ if (effectScenarioHandleDigest !== undefined && (scenarioHandleDigest ?? null) !== effectScenarioHandleDigest) {
692
+ const error = new Error("Telegram acceptance audit scenario ownership drift");
693
+ acceptanceAuditLease?.ledger.poison(error);
694
+ throw error;
695
+ }
696
+ if (scenarioHandleDigest === undefined) {
697
+ if (acceptanceAuditLease) {
698
+ retireAcceptanceAudit();
699
+ }
700
+ return undefined;
701
+ }
702
+ if (!/^[0-9a-f]{64}$/u.test(scenarioHandleDigest))
703
+ throw new Error("Telegram acceptance audit scenario handle is invalid");
704
+ if (!acceptanceAuditLease) {
705
+ acceptanceAuditLease = acquireTelegramAcceptanceAudit(options.acceptanceReceiptRoot ?? agentRoot, options.agentName, identityKey, transportPrivateValues, scenarioHandleDigest, options._acceptanceAuditReleaseHook, options._acceptanceAuditMaxBytes);
706
+ }
707
+ else if (scenarioHandleDigest !== acceptanceAuditLease.scenarioHandleDigest) {
708
+ retireAcceptanceAudit();
709
+ acceptanceAuditLease = acquireTelegramAcceptanceAudit(options.acceptanceReceiptRoot ?? agentRoot, options.agentName, identityKey, transportPrivateValues, scenarioHandleDigest, options._acceptanceAuditReleaseHook, options._acceptanceAuditMaxBytes);
710
+ }
711
+ return acceptanceAuditLease;
712
+ };
713
+ ensureAcceptanceAudit();
714
+ const acceptanceAuditBarrier = () => {
715
+ const lease = ensureAcceptanceAudit();
716
+ if (!lease)
717
+ return;
718
+ lease.ledger.assertHealthy();
719
+ lease.ledger.assertCapacity(8);
720
+ };
721
+ const runWithAcceptanceAuditOwner = async (operation) => {
722
+ const scenarioHandleDigest = readScenarioHandleDigest() ?? null;
723
+ return telegramAcceptanceAuditScenario.run(scenarioHandleDigest, async () => {
724
+ acceptanceAuditBarrier();
725
+ const ownerDigest = acceptanceAuditLease?.ownerDigest ?? "";
726
+ return telegramAcceptanceAuditOwner.run(ownerDigest, async () => {
727
+ try {
728
+ const result = await operation();
729
+ acceptanceAuditBarrier();
730
+ return result;
731
+ }
732
+ catch (error) {
733
+ try {
734
+ acceptanceAuditBarrier();
735
+ }
736
+ catch (auditError) {
737
+ if (error === auditError)
738
+ throw auditError;
739
+ throw new AggregateError([error, auditError], "Telegram effect and acceptance audit verification failed");
740
+ }
741
+ throw error;
742
+ }
743
+ });
744
+ });
745
+ };
746
+ const emitDurableSettlementEvidence = async (event, meta) => {
747
+ if (event === "telegram.callback_settled") {
748
+ await (0, runtime_1.emitNervesEventDurable)({
749
+ component: "senses",
750
+ event: "telegram.callback_settled",
751
+ message: "Telegram approval acceptance evidence durably recorded",
752
+ meta,
753
+ });
754
+ }
755
+ else if (event === "telegram.callback_recovery_settled") {
756
+ await (0, runtime_1.emitNervesEventDurable)({
757
+ component: "senses",
758
+ event: "telegram.callback_recovery_settled",
759
+ message: "Telegram approval acceptance evidence durably recorded",
760
+ meta,
761
+ });
762
+ }
763
+ else {
764
+ throw new Error("Telegram durable acceptance settlement event is unsupported");
765
+ }
766
+ };
767
+ const commitAcceptanceEvidence = useSanctuaryRuntime ? async (event, meta) => {
768
+ acceptanceAuditBarrier();
769
+ const lease = acceptanceAuditLease;
770
+ if (!lease) {
771
+ await emitDurableSettlementEvidence(event, meta);
772
+ return;
773
+ }
774
+ await telegramAcceptanceAuditExplicitCommit.run(true, async () => {
775
+ await emitDurableSettlementEvidence(event, meta);
776
+ });
777
+ acceptanceAuditBarrier();
778
+ lease.ledger.append({
779
+ ts: new Date().toISOString(),
780
+ level: "info",
781
+ event,
782
+ trace_id: (0, node_crypto_1.randomUUID)(),
783
+ component: "senses",
784
+ message: "Telegram approval acceptance evidence durably recorded",
785
+ meta,
786
+ });
787
+ lease.ledger.assertHealthy();
788
+ } : undefined;
789
+ const releaseAcceptanceAudit = (primaryError) => {
790
+ try {
791
+ acceptanceAuditLease?.release();
792
+ }
793
+ catch (releaseError) {
794
+ throw new AggregateError([primaryError, releaseError], "Telegram sense construction and audit release failed");
795
+ }
796
+ throw primaryError;
797
+ };
798
+ let effectJournal;
799
+ let approvalRuntime;
800
+ let rootHostRuntime;
801
+ const approvalCoordinatorFactory = (context) => ({
802
+ propose: (request) => {
803
+ if (request.toolCall.type === "function" && request.toolCall.function.name === "sanctuary_host_execute") {
804
+ if (!rootHostRuntime)
805
+ throw new Error("root host approval coordinator is unavailable");
806
+ return rootHostRuntime.coordinator(context).propose(request);
807
+ }
808
+ return approvalRuntime.coordinator(context).propose(request);
809
+ },
810
+ });
811
+ const getEffectJournal = () => {
812
+ effectJournal ??= new telegram_effect_adapter_1.FileTelegramEffectJournal(path.join(agentRoot, "state", "telegram", "effects"));
813
+ return effectJournal;
814
+ };
815
+ const configuredOwnerFriendId = options.admission?.ownerFriendId ?? `telegram-user:${subject}`;
816
+ const configuredOwnerSessionKey = `telegram:${subject}`;
817
+ const defaultEffectAuthorization = async (input) => {
818
+ const target = input.target;
819
+ if (target.kind === "admission_gate") {
820
+ const pending = admissionStore.read(target.admissionId);
821
+ const authorization = (0, relationship_authorization_1.authorizeRelationshipAccess)({
822
+ profiles: [],
823
+ pendingAdmission: { admissionId: pending.id, botId: pending.botId, userId: pending.userId, chatId: pending.chatId, expiresAt: new Date(pending.expiresAt).toISOString() },
824
+ request: { kind: "admission_gate", admissionId: target.admissionId, botId: target.botId, userId: target.userId, chatId: target.chatId, effect: "fixed_ack", idempotencyKey: input.idempotencyKey, expiresAt: new Date(pending.expiresAt).toISOString() },
825
+ });
826
+ const admissionAuthorization = authorization;
827
+ return { allowed: true, receiptId: admissionAuthorization.receiptId, expiresAt: admissionAuthorization.expiresAt, transport: { chatId: target.chatId } };
828
+ }
829
+ if (input.authorClass === "system_failsafe" && (input.effect.kind !== "text" || input.effect.text !== telegram_effect_adapter_1.FIXED_USENET_SYSTEM_FAILSAFE || !input.idempotencyKey.startsWith("system-failsafe:"))) {
830
+ return { allowed: false, reason: "system failsafe shape is not fixed" };
831
+ }
832
+ if (target.friendId === configuredOwnerFriendId && target.sessionKey === configuredOwnerSessionKey
833
+ && await approvalRuntime?.isPendingTerminalControl?.(input)) {
834
+ return {
835
+ allowed: true, receiptId: `approval-terminal:${(0, node_crypto_1.createHash)("sha256").update(input.idempotencyKey).digest("hex")}`,
836
+ expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(), transport: { chatId: authorizedChatId },
837
+ };
838
+ }
839
+ if (options.authorizeRelationshipEffect) {
840
+ if (target.friendId === configuredOwnerFriendId && target.sessionKey !== configuredOwnerSessionKey)
841
+ return { allowed: false, reason: "owner relationship session binding changed" };
842
+ return options.authorizeRelationshipEffect(input);
843
+ }
844
+ if (target.friendId !== `telegram-user:${subject}` || target.sessionKey !== `telegram:${subject}`) {
845
+ return { allowed: false, reason: "effect target is not the configured owner relationship" };
846
+ }
847
+ return { allowed: true, receiptId: `configured-owner:${subject}`, expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(), transport: { chatId: authorizedChatId } };
848
+ };
849
+ const authorizeEffect = options.authorizeEffect ?? defaultEffectAuthorization;
850
+ let inboundJournal;
851
+ const getInboundJournal = () => {
852
+ inboundJournal ??= (0, inbound_journal_1.openInboundJournal)(agentRoot, "telegram");
853
+ return inboundJournal;
854
+ };
855
+ const inboundJournalFailed = (error) => {
856
+ (0, runtime_1.emitNervesEvent)({
857
+ level: "error",
858
+ component: "senses",
859
+ event: "senses.telegram_inbound_record_failed",
860
+ message: "could not use the Telegram outcome records; turns still run, but a crash during one goes unrecorded",
861
+ meta: { agentName: options.agentName, error: redactTelegramPrivateValues(error, transportPrivateValues) },
862
+ });
863
+ };
864
+ const inboundIdFor = (updateId) => `telegram-update:${(0, node_crypto_1.createHmac)("sha256", identityKey).update(`ouroboros.telegram.inbound-journal.v1\0${subject}\0${updateId}`).digest("hex")}`;
865
+ const settleInbound = (id, outcome, detail) => {
866
+ try {
867
+ getInboundJournal().settle(id, outcome, detail);
868
+ }
869
+ catch (error) {
870
+ inboundJournalFailed(error);
871
+ }
872
+ };
873
+ const householdInboundIdFor = (reference) => `telegram-household:${(0, node_crypto_1.createHash)("sha256").update(reference).digest("hex")}`;
874
+ /**
875
+ * Note, inside a turn, that something is about to go out for its message, before it is sent. When the note
876
+ * cannot be written this throws and nothing is sent, so a replay can never repeat what the person received.
877
+ */
878
+ const noteTurnSpoke = () => {
879
+ const turn = telegramInboundTurn.getStore();
880
+ if (!turn)
881
+ return;
882
+ if (turn.id)
883
+ getInboundJournal().markSpoke(turn.id);
884
+ turn.spoke = true;
885
+ };
886
+ /**
887
+ * Note that something is about to go out for a message. Inside a turn that is the turn's message. Outside one,
888
+ * a delivery key names the message, which covers a reply the outbox sends after a crash.
889
+ */
890
+ const noteInboundSpoke = (idempotencyKey) => {
891
+ if (telegramInboundTurn.getStore()) {
892
+ noteTurnSpoke();
893
+ return;
894
+ }
895
+ const owner = idempotencyKey.startsWith(`turn:${subject}:`) ? idempotencyKey.slice(`turn:${subject}:`.length).split(":")[0] : null;
896
+ const household = /^relationship-turn:(telegram-inbound:[0-9a-f]{64}):/u.exec(idempotencyKey)?.[1];
897
+ if (owner === null && !household)
898
+ return;
899
+ try {
900
+ getInboundJournal().markSpoke(owner !== null ? inboundIdFor(owner) : householdInboundIdFor(household));
901
+ }
902
+ catch (error) {
903
+ inboundJournalFailed(error);
904
+ }
905
+ };
906
+ const authorizeAndNoteSpoke = async (input) => {
907
+ const authorization = await authorizeEffect(input);
908
+ if (input.phase !== "send" || !authorization.allowed)
909
+ return authorization;
910
+ try {
911
+ noteInboundSpoke(input.idempotencyKey);
912
+ }
913
+ catch (error) {
914
+ // The send does not happen, so the outbox must not send it later for a message already recorded failed.
915
+ (0, telegram_effect_adapter_1.abandonTelegramEffect)(getEffectJournal(), input.artifact);
916
+ throw error;
917
+ }
918
+ return authorization;
919
+ };
920
+ let recordAcceptedEffects;
921
+ const configuredOwnerTarget = () => ({ kind: "approved_relationship", friendId: configuredOwnerFriendId, sessionKey: configuredOwnerSessionKey });
922
+ const fallbackText = (text) => `${telegram_owner_route_1.OWNER_ROUTE_FALLBACK_PREFIX}\n\n${text}`;
923
+ const executeOnTelegram = (0, telegram_effect_adapter_1.createTelegramAuthorizedEffectExecutor)({
924
+ store: getEffectJournal,
925
+ api,
926
+ authorize: authorizeAndNoteSpoke,
927
+ barrier: acceptanceAuditBarrier,
928
+ });
929
+ /**
930
+ * An approval card the agent wants from the owner (a tool approval's prompt, a newcomer's admission card) goes to the owner
931
+ * route first, as urgent. The card still goes to Telegram so its buttons work: silently when the primary agent has it,
932
+ * and with the fallback line when it can't be reached. A resend of a card already in the journal is left as it was.
933
+ */
934
+ const executeAuthorizedEffect = async (input) => {
935
+ const route = options.ownerRoute;
936
+ if (!route || input.effect.kind !== "card" || input.target.kind !== "approved_relationship" || input.target.friendId !== configuredOwnerFriendId
937
+ || !/^(?:approval:.+:prompt|owner-card:.+)$/u.test(input.idempotencyKey) || getEffectJournal().readByIdempotencyKey(input.idempotencyKey)) {
938
+ return executeOnTelegram(input);
939
+ }
940
+ const effect = input.effect;
941
+ const choices = effect.buttons.flat().map((button) => button.text).join(", ");
942
+ const item = (0, telegram_owner_route_1.ownerRouteItem)(input.idempotencyKey, `${effect.text}\n\nOptions: ${choices}. The buttons are on the card in the Butler's Telegram chat.`, true);
943
+ const approvalId = /^approval:(.+):prompt$/u.exec(input.idempotencyKey)?.[1];
944
+ let approvalRequest;
945
+ // Building the relay request never stops the card: any error builds none, and the card goes as before.
946
+ try {
947
+ approvalRequest = approvalId === undefined ? undefined : (0, telegram_approval_relay_1.approvalRelayRequestFor)({ agentRoot, routeDid: () => route.peerDid, approvalId, transport: approvalTransport });
948
+ }
949
+ catch (error) {
950
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.telegram_relay_request_failed", message: "sent the approval card without a relay request after building one failed", meta: { error: String(error) } });
951
+ approvalRequest = undefined;
952
+ }
953
+ const outcome = await route(approvalRequest ? { ...item, approvalRequest } : item);
954
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_owner_route_approval", message: "offered an approval card to the owner's primary agent", meta: { agentName: options.agentName, outcome: outcome.status } });
955
+ return executeOnTelegram({
956
+ ...input,
957
+ effect: outcome.status === "delivered" ? { ...effect, silent: true } : { ...effect, text: fallbackText(effect.text) },
958
+ });
959
+ };
960
+ const recordConfiguredOwnerEffect = async (artifact, causalEventId) => {
961
+ await recordAcceptedEffects((0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot), [artifact], undefined, causalEventId ? { [artifact.id]: causalEventId } : undefined);
962
+ };
963
+ const approvalEffects = (0, telegram_effect_adapter_1.createTelegramApprovalEffectPort)({ target: configuredOwnerTarget(), chatId: authorizedChatId, execute: executeAuthorizedEffect, record: recordConfiguredOwnerEffect });
964
+ let toolContext;
965
+ let approvalTransport;
966
+ let interactiveControl;
967
+ let approvalRelayDoor;
968
+ try {
969
+ toolContext = useSanctuaryRuntime ? (options._toolContext ?? (0, sanctuary_runtime_2.createSanctuaryToolContext)(options.agentName)) : undefined;
970
+ if (toolContext && options.telegramContactManager)
971
+ toolContext.telegramContactManager = options.telegramContactManager;
972
+ approvalRuntime = options.approvalRuntime ?? (useSanctuaryRuntime ? (options._createApprovalRuntime ?? telegram_approval_runtime_1.createTelegramApprovalRuntime)({
973
+ agentName: options.agentName,
974
+ api,
975
+ authorizedUserId,
976
+ authorizedChatId,
977
+ subject,
978
+ identityKey,
979
+ toolContext: toolContext ?? {},
980
+ ...(options.resolveRelationshipAuthorization ? {
981
+ resolveOwnerRelationship: (binding) => options.resolveRelationshipAuthorization({
982
+ friendId: binding.friendId, requestId: binding.requestId, sessionEventId: binding.sessionEventId, sessionKey: binding.sessionKey,
983
+ botId: botId, userId: authorizedUserId, chatId: authorizedChatId,
984
+ }),
985
+ } : {}),
986
+ resolveLiveToolContext: async (record) => {
987
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
988
+ if (record.transport !== "telegram" || record.requesterId !== subject
989
+ || record.transportUserId !== subject || record.transportChatId !== subject
990
+ || record.sessionKey !== configuredOwnerSessionKey || path.resolve(record.sessionPath) !== path.resolve(sessionPath)) {
991
+ throw new Error("approval is not bound to the configured owner session");
992
+ }
993
+ const envelope = (0, session_events_1.loadSessionEnvelopeFile)(sessionPath);
994
+ const ingress = envelope && (0, session_events_1.selectEffectiveSessionEvents)(envelope.events).findLast((event) => event.role === "user");
995
+ if (!ingress)
996
+ throw new Error("approval owner ingress is unavailable");
997
+ const relationshipAuthorization = await resolveLiveRelationshipAuthorization({
998
+ friendId: configuredOwnerFriendId, requestId: `approval:${record.approvalId}`, sessionEventId: ingress.id,
999
+ botId: botId, userId: authorizedUserId, chatId: authorizedChatId, sessionKey: configuredOwnerSessionKey,
1000
+ });
1001
+ if (relationshipAuthorization.profileId !== "sanctuary-owner")
1002
+ throw new Error("approval owner profile is unavailable");
1003
+ const friendStore = new friends_1.FileFriendStore(path.join(agentRoot, "friends"));
1004
+ const friend = await friendStore.get(configuredOwnerFriendId);
1005
+ if (!friend)
1006
+ throw new Error("approval owner Friend is unavailable");
1007
+ return {
1008
+ ...toolContext, signin: async () => undefined, agentName: options.agentName, agentRoot,
1009
+ currentSession: { friendId: friend.id, channel: "telegram", key: configuredOwnerSessionKey, sessionPath },
1010
+ currentUserMessage: (0, session_events_1.extractEventText)(ingress),
1011
+ context: { friend, channel: (0, friends_1.getChannelCapabilities)("telegram") }, friendStore, relationshipAuthorization,
1012
+ };
1013
+ },
1014
+ effects: approvalEffects,
1015
+ effectBarrier: acceptanceAuditBarrier,
1016
+ dependencies: {
1017
+ agentRoot,
1018
+ acceptanceMarker: () => {
1019
+ const scenarioHandleDigest = readScenarioHandleDigest();
1020
+ return scenarioHandleDigest ? { scenarioHandleDigest } : null;
1021
+ },
1022
+ commitAcceptanceEvidence,
1023
+ },
1024
+ }) : undefined);
1025
+ approvalTransport = options.approvalTransport ?? approvalRuntime?.transport;
1026
+ const port = authorityTransport?.hostApproval;
1027
+ if (useSanctuaryRuntime && port?.pins.expectedBotId === botId
1028
+ && port.pins.expectedOwnerUserId === authorizedUserId && port.pins.expectedOwnerChatId === authorizedChatId) {
1029
+ // The root host sends the approval card when a proposal is registered, so that counts as a send for the message.
1030
+ const notingPort = {
1031
+ pins: port.pins,
1032
+ refresh: () => port.refresh(),
1033
+ isHealthy: () => port.isHealthy(),
1034
+ acceptsObservation: (metadata) => port.acceptsObservation(metadata),
1035
+ register: async (proposal) => {
1036
+ noteTurnSpoke();
1037
+ return port.register(proposal);
1038
+ },
1039
+ status: (registration) => port.status(registration),
1040
+ execute: (correlation) => port.execute(correlation),
1041
+ callbackForUpdate: (update) => port.callbackForUpdate(update),
1042
+ };
1043
+ rootHostRuntime = (0, root_host_approval_runtime_1.createRootHostApprovalRuntime)({
1044
+ agentRoot, port: notingPort, effectBarrier: acceptanceAuditBarrier, approvalCoordinatorFactory,
1045
+ resolveContext: async (binding) => {
1046
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
1047
+ if (binding.agentRoot !== agentRoot || binding.friendId !== configuredOwnerFriendId
1048
+ || binding.sessionKey !== configuredOwnerSessionKey || binding.sessionPath !== sessionPath) {
1049
+ throw new Error("root host continuation owner session changed");
1050
+ }
1051
+ const relationshipAuthorization = await resolveLiveRelationshipAuthorization({
1052
+ friendId: binding.friendId, requestId: binding.requestId, sessionEventId: binding.sessionEventId,
1053
+ sessionKey: binding.sessionKey, botId: botId, userId: authorizedUserId, chatId: authorizedChatId,
1054
+ });
1055
+ const friendStore = new friends_1.FileFriendStore(path.join(agentRoot, "friends"));
1056
+ const friend = await friendStore.get(binding.friendId);
1057
+ if (!friend)
1058
+ throw new Error("root host owner Friend is unavailable");
1059
+ return {
1060
+ ...toolContext, signin: async () => undefined, agentName: options.agentName, agentRoot,
1061
+ currentSession: { friendId: friend.id, channel: "telegram", key: binding.sessionKey, sessionPath },
1062
+ context: { friend, channel: (0, friends_1.getChannelCapabilities)("telegram") }, friendStore, relationshipAuthorization,
1063
+ rootHost: { port },
1064
+ };
1065
+ },
1066
+ deliver: async (text, approvalId) => {
1067
+ await approvalEffects.sendText({
1068
+ idempotencyKey: `root-host:${approvalId}:continuation:${(0, node_crypto_1.createHash)("sha256").update(text).digest("hex")}`,
1069
+ chatId: authorizedChatId, text, authorClass: "butler",
1070
+ });
1071
+ },
1072
+ });
1073
+ }
1074
+ interactiveControl = useSanctuaryRuntime && approvalTransport
1075
+ ? (options._createInteractiveControl ?? sanctuary_interactive_control_1.createSanctuaryInteractiveControl)({
1076
+ agentRoot,
1077
+ transport: approvalTransport,
1078
+ authorizedUserId,
1079
+ authorizedChatId,
1080
+ runRequest: runWithAcceptanceAuditOwner,
1081
+ })
1082
+ : undefined;
1083
+ // Ari's deny relayed through his primary agent is decided here, beside the taps, under the same lock.
1084
+ approvalRelayDoor = useSanctuaryRuntime && approvalRuntime
1085
+ ? (options._createApprovalRelayDoor ?? telegram_approval_relay_1.createApprovalRelayDoor)({ agentName: options.agentName, agentRoot, runtime: approvalRuntime })
1086
+ : undefined;
1087
+ }
1088
+ catch (error) {
1089
+ releaseAcceptanceAudit(error);
1090
+ }
1091
+ const migrateIdentity = options.migrateIdentity ?? (async () => {
1092
+ const legacySubjects = new Set([
1093
+ ...readTelegramSubjectIndex(agentRoot, subject),
1094
+ ...discoverTelegramFilesystemSubjects(agentRoot),
1095
+ ...(approvalRuntime?.legacySubjects?.() ?? []),
1096
+ ]);
1097
+ legacySubjects.delete(subject);
1098
+ if (legacySubjects.size > 1)
1099
+ throw new Error("Telegram legacy identity subject migration is ambiguous");
1100
+ const migrationSubjects = [...legacySubjects];
1101
+ for (const legacySubject of migrationSubjects) {
1102
+ acceptanceAuditBarrier();
1103
+ migrateTelegramSessionIdentity(agentRoot, legacySubject, legacySubject, subject);
1104
+ acceptanceAuditBarrier();
1105
+ if (!options.admission)
1106
+ await migrateTelegramFriendIdentity(agentRoot, legacySubject, subject);
1107
+ }
1108
+ acceptanceAuditBarrier();
1109
+ migrateTelegramSessionIdentity(agentRoot, authorizedUserId, authorizedChatId, subject);
1110
+ acceptanceAuditBarrier();
1111
+ if (!options.admission)
1112
+ await migrateTelegramFriendIdentity(agentRoot, authorizedUserId, subject);
1113
+ acceptanceAuditBarrier();
1114
+ approvalRuntime?.migrateIdentity?.(migrationSubjects);
1115
+ acceptanceAuditBarrier();
1116
+ writeTelegramSubjectIndex(agentRoot, subject, migrationSubjects, options.subjectIndexHooks);
1117
+ });
1118
+ let approvalReconcileTimer;
1119
+ let approvalReconciliationActive = false;
1120
+ const approvalReconciliationsInFlight = new Set();
1121
+ let nextApprovalReconcileDeadline;
1122
+ let reconcileSystemFailsafes;
1123
+ let stopPromise;
1124
+ let runPromise;
1125
+ const clearApprovalReconcileTimer = () => {
1126
+ if (approvalReconcileTimer)
1127
+ clearTimeout(approvalReconcileTimer);
1128
+ approvalReconcileTimer = undefined;
1129
+ };
1130
+ const scheduleApprovalReconcile = () => {
1131
+ if (!approvalTransport || !approvalReconciliationActive)
1132
+ return;
1133
+ const scheduledAt = nextApprovalReconcileDeadline ?? (Date.now() + APPROVAL_EXPIRY_RECONCILE_INTERVAL_MS);
1134
+ nextApprovalReconcileDeadline = scheduledAt + APPROVAL_EXPIRY_RECONCILE_INTERVAL_MS;
1135
+ const delay = Math.max(0, scheduledAt - Date.now());
1136
+ approvalReconcileTimer = setTimeout(() => {
1137
+ approvalReconcileTimer = undefined;
1138
+ scheduleApprovalReconcile();
1139
+ const reconciliation = runWithAcceptanceAuditOwner(async () => {
1140
+ await approvalTransport.reconcileExpired();
1141
+ await rootHostRuntime?.recover();
1142
+ }).catch((error) => {
1143
+ acceptanceAuditBarrier();
1144
+ (0, runtime_1.emitNervesEvent)({
1145
+ level: "error",
1146
+ component: "senses",
1147
+ event: "senses.telegram_approval_reconcile_error",
1148
+ message: "Telegram approval expiry reconciliation failed",
1149
+ meta: { agentName: options.agentName, subject, error: transportError(error) },
1150
+ });
1151
+ }).finally(() => {
1152
+ approvalReconciliationsInFlight.delete(reconciliation);
1153
+ });
1154
+ approvalReconciliationsInFlight.add(reconciliation);
1155
+ const failsafe = runWithAcceptanceAuditOwner(reconcileSystemFailsafes)
1156
+ .finally(() => { approvalReconciliationsInFlight.delete(failsafe); });
1157
+ approvalReconciliationsInFlight.add(failsafe);
1158
+ }, delay);
1159
+ };
1160
+ const deliverButlerEffect = async (text, idempotencyKey, signal, onMessageDelivered, exactDownloadCreditQuestion = false, replyToMessageId, silent = false) => {
1161
+ const presentedText = (0, sanctuary_download_credit_presentation_1.presentSanctuaryDownloadCreditReply)(options.agentName, exactDownloadCreditQuestion, text);
1162
+ return executeAuthorizedEffect({
1163
+ idempotencyKey,
1164
+ target: configuredOwnerTarget(),
1165
+ authorClass: "butler",
1166
+ effect: { kind: "text", text: presentedText, ...(replyToMessageId ? { replyToMessageId } : {}), ...(silent ? { silent: true } : {}) },
1167
+ ...(signal ? { signal } : {}),
1168
+ ...(onMessageDelivered ? { onMessageDelivered } : {}),
1169
+ });
1170
+ };
1171
+ // House notices wait while Ari's chat is handed to someone else, then go out with the next notice, message or reconcile pass
1172
+ // (see telegram-handoff). Releases run one at a time so two callers never send the same held notice twice, and a notice leaves the
1173
+ // held file before it is sent: from then on the effect journal owns it, exactly like a notice that was never held.
1174
+ const heldNoticesPath = path.join(agentRoot, "state", "telegram", "held-owner-notices.json");
1175
+ const ownerChatIsHandedOff = () => {
1176
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
1177
+ return (0, telegram_handoff_1.ownerChatHandedOff)((0, session_events_1.loadSessionEnvelopeFile)(sessionPath)?.events ?? [], Date.now());
1178
+ };
1179
+ const proactiveLedgerPath = path.join(agentRoot, "state", "telegram", "proactive-sends.json");
1180
+ const countProactiveSend = () => { if (options.proactivePacing)
1181
+ (0, telegram_handoff_1.recordProactiveSend)(proactiveLedgerPath, new Date(), options.proactivePacing); };
1182
+ const releasedHeldKeysPath = path.join(agentRoot, "state", "telegram", "released-held-keys.json");
1183
+ const holdNoticeDuringHandoff = (text, key, critical = (0, telegram_handoff_1.isCriticalNoticeKey)(key)) => {
1184
+ const handedOff = ownerChatIsHandedOff();
1185
+ const pacingReason = !handedOff && options.proactivePacing && !critical ? (0, telegram_handoff_1.proactiveHoldReason)(proactiveLedgerPath, new Date(), options.proactivePacing) : null;
1186
+ if (!handedOff && !pacingReason)
1187
+ return false;
1188
+ const held = (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath);
1189
+ if (!held.some((notice) => notice.key === key))
1190
+ (0, telegram_handoff_1.writeHeldNotices)(heldNoticesPath, [...held, { key, text }]);
1191
+ if (handedOff)
1192
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_notice_held_for_handoff", message: "held a house notice while the owner's chat is handed to someone else", meta: { agentName: options.agentName } });
1193
+ else
1194
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_notice_held_for_pacing", message: "held a house notice for quiet hours or the daily message cap", meta: { agentName: options.agentName, reason: pacingReason } });
1195
+ return true;
1196
+ };
1197
+ // A delegated command's audit notice (see `TelegramSenseApp.sendDelegatedAuditNotice`): sent now, or it throws.
1198
+ const sendDelegatedAuditNotice = async (input) => {
1199
+ const noticeId = requiredText(input.noticeId, "delegated audit notice id");
1200
+ if (!noticeId.startsWith("delegated:") || Buffer.byteLength(noticeId) > 512)
1201
+ throw new Error("Telegram delegated audit notice id is invalid");
1202
+ const key = `owner-notice:${noticeId}`;
1203
+ await runWithAcceptanceAuditOwner(async () => {
1204
+ const text = requiredText(input.text, "delegated audit notice");
1205
+ if (ownerChatIsHandedOff()) {
1206
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.telegram_delegated_notice_refused", message: "refused a delegated command's audit notice while the owner's chat is handed to someone else", meta: { agentName: options.agentName, reason: "handed_off" } });
1207
+ throw new Error("the owner's Telegram chat is handed to someone else, so a delegated command's notice can't be sent");
1208
+ }
1209
+ const pacingReason = options.proactivePacing ? (0, telegram_handoff_1.proactiveHoldReason)(proactiveLedgerPath, new Date(), options.proactivePacing) : null;
1210
+ const silent = options.ownerRoute !== undefined || pacingReason === "quiet_hours";
1211
+ const effect = await deliverButlerEffect(text, key, input.signal, undefined, false, undefined, silent);
1212
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_delegated_notice_sent", message: "sent a delegated command's audit notice to the owner's Telegram chat", meta: { agentName: options.agentName, silent } });
1213
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
1214
+ await recordAcceptedEffects(sessionPath, [effect]);
1215
+ });
1216
+ };
1217
+ // Keys the owner's primary agent accepted, so a retry is already sent (as with the effect journal for Telegram).
1218
+ const routedKeysPath = path.join(agentRoot, "state", "telegram", "routed-owner-notices.json");
1219
+ /**
1220
+ * Offers a self-started message to the owner route. Returns null when it is handled (the peer has it, or it waits in the
1221
+ * held file for the peer), or the text Telegram should send: the message itself with no route, or, for an urgent message
1222
+ * the peer can't take, the message marked as a fallback.
1223
+ */
1224
+ const routeSelfStarted = async (text, key, critical = (0, telegram_handoff_1.isCriticalNoticeKey)(key), signal) => {
1225
+ if (!options.ownerRoute)
1226
+ return text;
1227
+ // Older held notices go first, so the peer hears them in order.
1228
+ await releaseHeldNotices(signal);
1229
+ const item = (0, telegram_owner_route_1.ownerRouteItem)(key, text, critical);
1230
+ const outcome = await options.ownerRoute(item);
1231
+ if (outcome.status === "delivered") {
1232
+ (0, telegram_handoff_1.recordReleasedHeldKeys)(routedKeysPath, [key]);
1233
+ return null;
1234
+ }
1235
+ if (item.urgency === "now") {
1236
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.telegram_owner_route_fallback", message: "the owner's primary agent can't be reached; an urgent message goes to Telegram", meta: { agentName: options.agentName, dedupeKey: item.dedupeKey, detail: outcome.detail } });
1237
+ return fallbackText(text);
1238
+ }
1239
+ const held = (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath);
1240
+ if (!held.some((notice) => notice.key === key))
1241
+ (0, telegram_handoff_1.writeHeldNotices)(heldNoticesPath, [...held, { key, text }]);
1242
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_notice_held_for_owner_route", message: "held a house notice until the owner's primary agent can be reached", meta: { agentName: options.agentName, dedupeKey: item.dedupeKey } });
1243
+ return null;
1244
+ };
1245
+ const ownerRouteWatchPath = path.join(agentRoot, "state", "telegram", "owner-route-watch.json");
1246
+ const readOwnerRouteWatch = () => {
1247
+ try {
1248
+ const parsed = JSON.parse((0, node_fs_1.readFileSync)(ownerRouteWatchPath, "utf8"));
1249
+ return { failures: Number.isSafeInteger(parsed.failures) ? parsed.failures : 0, alertedAt: typeof parsed.alertedAt === "string" ? parsed.alertedAt : null };
1250
+ }
1251
+ catch {
1252
+ return { failures: 0, alertedAt: null };
1253
+ }
1254
+ };
1255
+ const writeOwnerRouteWatch = (state) => {
1256
+ (0, node_fs_1.mkdirSync)(path.dirname(ownerRouteWatchPath), { recursive: true });
1257
+ (0, atomic_file_1.writeFileAtomicSync)(ownerRouteWatchPath, JSON.stringify(state));
1258
+ };
1259
+ const checkOwnerRoute = async () => {
1260
+ const probe = options.ownerRoute?.probe;
1261
+ if (!probe)
1262
+ return;
1263
+ const outcome = await probe();
1264
+ const state = readOwnerRouteWatch();
1265
+ if (outcome.status === "delivered") {
1266
+ if (state.alertedAt) {
1267
+ await executeAuthorizedEffect({ idempotencyKey: `owner-route-watch:back:${state.alertedAt}`, target: configuredOwnerTarget(), authorClass: "butler", effect: { kind: "text", text: telegram_owner_route_1.OWNER_ROUTE_BACK_TEXT, silent: true } });
1268
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_owner_route_back", message: "told the owner, silently, that the primary agent is reachable again", meta: { agentName: options.agentName, downSince: state.alertedAt } });
1269
+ }
1270
+ if (state.failures || state.alertedAt)
1271
+ writeOwnerRouteWatch({ failures: 0, alertedAt: null });
1272
+ return;
1273
+ }
1274
+ const failures = state.failures + 1;
1275
+ if (failures < telegram_owner_route_1.OWNER_ROUTE_WATCH_FAILURES || state.alertedAt) {
1276
+ writeOwnerRouteWatch({ failures, alertedAt: state.alertedAt });
1277
+ return;
1278
+ }
1279
+ const alertedAt = new Date().toISOString();
1280
+ await executeAuthorizedEffect({ idempotencyKey: `owner-route-watch:down:${alertedAt}`, target: configuredOwnerTarget(), authorClass: "butler", effect: { kind: "text", text: telegram_owner_route_1.OWNER_ROUTE_DOWN_TEXT } });
1281
+ writeOwnerRouteWatch({ failures, alertedAt });
1282
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.telegram_owner_route_down", message: "told the owner on Telegram that the primary agent has been unreachable for 15 minutes", meta: { agentName: options.agentName, detail: outcome.detail } });
1283
+ };
1284
+ /** With an owner route, held notices go to the peer one by one; a critical one it can't take goes to Telegram as a fallback. */
1285
+ const releaseHeldNoticesToRoute = async (route, signal) => {
1286
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
1287
+ for (const notice of (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath)) {
1288
+ const critical = (0, telegram_handoff_1.isCriticalNoticeKey)(notice.key);
1289
+ const outcome = await route((0, telegram_owner_route_1.ownerRouteItem)(notice.key, notice.text, critical));
1290
+ if (outcome.status !== "delivered" && !critical)
1291
+ continue;
1292
+ (0, telegram_handoff_1.writeHeldNotices)(heldNoticesPath, (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath).filter((entry) => entry.key !== notice.key));
1293
+ if (outcome.status === "delivered") {
1294
+ (0, telegram_handoff_1.recordReleasedHeldKeys)(routedKeysPath, [notice.key]);
1295
+ continue;
1296
+ }
1297
+ await recordAcceptedEffects(sessionPath, [await deliverButlerEffect(fallbackText(notice.text), notice.key, signal)]);
1298
+ }
1299
+ };
1300
+ let heldNoticeRelease = Promise.resolve();
1301
+ const releaseHeldNotices = async (signal) => {
1302
+ // Nearly always nothing is held: return without queueing, so ordinary turns and the reconcile tick pay nothing.
1303
+ if ((0, telegram_handoff_1.readHeldNotices)(heldNoticesPath).length === 0)
1304
+ return;
1305
+ const release = heldNoticeRelease.then(async () => {
1306
+ if (options.ownerRoute)
1307
+ return releaseHeldNoticesToRoute(options.ownerRoute, signal);
1308
+ const held = (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath);
1309
+ if (ownerChatIsHandedOff())
1310
+ return;
1311
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
1312
+ if (options.proactivePacing) {
1313
+ // Held notices go out as one message, and only when an unprompted message is allowed now (quiet hours and the daily cap).
1314
+ if ((0, telegram_handoff_1.proactiveHoldReason)(proactiveLedgerPath, new Date(), options.proactivePacing))
1315
+ return;
1316
+ /* v8 ignore next -- the caller already saw held notices; only a concurrent release can empty the file before this re-read @preserve */
1317
+ if (held.length === 0)
1318
+ return;
1319
+ const folded = (0, telegram_handoff_1.foldHeldNotices)(held);
1320
+ if (held.length > 1)
1321
+ (0, telegram_handoff_1.recordReleasedHeldKeys)(releasedHeldKeysPath, held.map((notice) => notice.key));
1322
+ (0, telegram_handoff_1.writeHeldNotices)(heldNoticesPath, (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath).filter((entry) => !held.some((notice) => notice.key === entry.key)));
1323
+ await recordAcceptedEffects(sessionPath, [await deliverButlerEffect(folded.text, folded.key, signal)]);
1324
+ countProactiveSend();
1325
+ return;
1326
+ }
1327
+ for (const notice of held) {
1328
+ (0, telegram_handoff_1.writeHeldNotices)(heldNoticesPath, (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath).filter((entry) => entry.key !== notice.key));
1329
+ await recordAcceptedEffects(sessionPath, [await deliverButlerEffect(notice.text, notice.key, signal)]);
1330
+ }
1331
+ });
1332
+ heldNoticeRelease = release.catch(() => undefined);
1333
+ await release;
1334
+ };
1335
+ /** For callers that must not fail because a held notice failed to send; the effect journal keeps the failed send. */
1336
+ const releaseHeldNoticesQuietly = () => releaseHeldNotices().catch((error) => {
1337
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.telegram_held_notice_release_error", message: "a held house notice failed to send; the effect journal has it", meta: { agentName: options.agentName, subject, error: transportError(error) } });
1338
+ });
1339
+ recordAcceptedEffects = async (sessionPath, artifacts, bootstrapInbound, causalEventIds) => {
1340
+ await (0, telegram_effect_adapter_1.recordTelegramEffectsInSession)({ store: getEffectJournal(), sessionPath, artifacts, ...(bootstrapInbound ? { inbound: bootstrapInbound } : {}), ...(causalEventIds ? { causalEventIds } : {}) });
1341
+ for (const artifact of artifacts) {
1342
+ if (artifact.target.kind !== "approved_relationship" || !artifact.target.requestId || artifact.effect.kind !== "text")
1343
+ continue;
1344
+ const recorded = getEffectJournal().read(artifact.id);
1345
+ if (!recorded.parts.every((part) => part.state === "session_recorded"))
1346
+ continue;
1347
+ if (!artifact.obligationReturnId)
1348
+ continue;
1349
+ const obligation = (0, obligations_1.readObligation)(agentRoot, artifact.obligationReturnId);
1350
+ if (obligation?.returnReadyAt && obligation.requestId === artifact.target.requestId
1351
+ && obligation.owedTo?.friendId === artifact.target.friendId && obligation.owedTo.channel === "telegram"
1352
+ && obligation.owedTo.key === artifact.target.sessionKey)
1353
+ (0, obligations_1.fulfillObligation)(agentRoot, obligation.id);
1354
+ }
1355
+ };
1356
+ const deliverAwaitFollowUp = async (request) => {
1357
+ if (!request.requestId)
1358
+ return { status: "blocked", detail: "Telegram follow-up is missing its request binding" };
1359
+ const sessionKey = (0, config_1.canonicalizeTelegramSessionKey)(request.key);
1360
+ try {
1361
+ const obligation = (0, obligations_1.findPendingObligationForRequest)(agentRoot, { requestId: request.requestId, owedTo: { friendId: request.friendId, channel: "telegram", key: sessionKey } });
1362
+ if (obligation && !obligation.returnReadyAt)
1363
+ (0, obligations_1.markObligationReturnReady)(agentRoot, obligation.id, request.deliveryId ?? `telegram-return:${request.requestId}`);
1364
+ const expiry = request.deliveryId?.endsWith(":expired") === true;
1365
+ const artifact = await executeAuthorizedEffect({
1366
+ idempotencyKey: `await-${expiry ? "expiry-" : ""}follow-up:${request.requestId}:${(0, node_crypto_1.createHash)("sha256").update(request.deliveryId ?? request.content).digest("hex")}`,
1367
+ target: { kind: "approved_relationship", friendId: request.friendId, sessionKey, requestId: request.requestId },
1368
+ authorClass: "butler",
1369
+ effect: { kind: "text", text: request.content },
1370
+ ...(obligation ? { obligationReturnId: obligation.id } : {}),
1371
+ });
1372
+ await recordAcceptedEffects((0, shared_turn_1.getSenseSessionPath)(options.agentName, request.friendId, "telegram", sessionKey, agentRoot), [artifact]);
1373
+ return { status: "delivered_now", detail: "sent to the exact request-bound Telegram chat" };
1374
+ }
1375
+ catch (error) {
1376
+ return { status: "blocked", detail: error instanceof Error ? error.message : String(error) };
1377
+ }
1378
+ };
1379
+ (0, tools_awaiting_1.setAwaitToolDeps)({
1380
+ buildDeliveryDeps: () => ({
1381
+ agentName: options.agentName,
1382
+ queuePending: (message) => (0, pending_1.queuePendingMessage)((0, pending_1.getPrivateRuntimePendingDir)(options.agentName), message),
1383
+ deliverers: {
1384
+ telegram: deliverAwaitFollowUp,
1385
+ },
1386
+ }),
1387
+ });
1388
+ const failsafeScanCache = new router_1.ExternalEventScanCache();
1389
+ reconcileSystemFailsafes = async () => {
1390
+ await releaseHeldNoticesQuietly();
1391
+ if (!options.privilegedFailsafe)
1392
+ return;
1393
+ const target = configuredOwnerTarget();
1394
+ try {
1395
+ await (0, telegram_effect_adapter_1.sweepTelegramSystemFailsafes)({
1396
+ eventRoot: options.privilegedFailsafe.eventRoot,
1397
+ target,
1398
+ verifyProtectiveState: options.privilegedFailsafe.verifyProtectiveState,
1399
+ scanCache: failsafeScanCache,
1400
+ execute: executeAuthorizedEffect,
1401
+ recordArtifact: async (artifact) => {
1402
+ await recordAcceptedEffects((0, shared_turn_1.getSenseSessionPath)(options.agentName, target.friendId, "telegram", target.sessionKey, agentRoot), [artifact]);
1403
+ },
1404
+ });
1405
+ }
1406
+ catch (error) {
1407
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.telegram_system_failsafe_error", message: "Telegram system failsafe reconciliation failed", meta: { agentName: options.agentName, subject, error: transportError(error) } });
1408
+ }
1409
+ };
1410
+ async function resolveLiveRelationshipAuthorization(input) {
1411
+ if (!options.resolveRelationshipAuthorization)
1412
+ throw new Error("Telegram relationship authorization resolver is unavailable");
1413
+ const authorization = await options.resolveRelationshipAuthorization(input);
1414
+ if (authorization.subject.friendId !== input.friendId || authorization.subject.admissionState !== "active")
1415
+ throw new Error("Telegram relationship admission is not active");
1416
+ return {
1417
+ requestId: input.requestId,
1418
+ profileId: authorization.profileId,
1419
+ authorizedContextScopes: authorization.authorizedContextScopes,
1420
+ advertisedToolNames: authorization.advertisedToolNames,
1421
+ actor: authorization.actor,
1422
+ resolveCurrent: () => resolveLiveRelationshipAuthorization(input),
1423
+ authorizeTool: async (name, args) => (await options.resolveRelationshipAuthorization(input)).authorizeTool(name, args),
1424
+ };
1425
+ }
1426
+ const prepareRelationshipRunAgentOptions = (input) => {
1427
+ if (!options.resolveRelationshipAuthorization)
1428
+ throw new Error("Telegram relationship authorization resolver is unavailable");
1429
+ const relationshipCoordinates = { ...input, botId: botId };
1430
+ return async ({ runAgentOptions, activeCares = [], careEvidenceNow = Date.now() }) => {
1431
+ const relationshipAuthorization = await resolveLiveRelationshipAuthorization(relationshipCoordinates);
1432
+ const isSanctuaryOwner = options.agentName === "sanctuary" && relationshipAuthorization.profileId === "sanctuary-owner";
1433
+ const isSanctuaryHouseholdConversation = options.agentName === "sanctuary"
1434
+ && (relationshipAuthorization.profileId === "sanctuary-owner" || relationshipAuthorization.profileId === "sanctuary-household");
1435
+ const storageOptimization = isSanctuaryOwner
1436
+ ? (0, sanctuary_storage_optimization_contract_1.sanctuaryStorageOptimizationRequiredToolCalls)(input.userMessage, relationshipAuthorization.advertisedToolNames)
1437
+ : undefined;
1438
+ const staleDockerCare = isSanctuaryOwner
1439
+ ? (0, sanctuary_full_visibility_contract_1.sanctuaryStaleDockerCareRequiredToolCalls)(activeCares, careEvidenceNow, relationshipAuthorization.advertisedToolNames)
1440
+ : undefined;
1441
+ const fullVisibility = isSanctuaryOwner
1442
+ ? (0, sanctuary_full_visibility_contract_1.sanctuaryFullVisibilityRequiredToolCalls)(input.userMessage, relationshipAuthorization.advertisedToolNames, () => staleDockerCare?.currentRiskClaims() ?? [])
1443
+ : undefined;
1444
+ const mediaCatalog = isSanctuaryHouseholdConversation
1445
+ ? (0, sanctuary_media_catalog_contract_1.sanctuaryMediaCatalogRequiredToolCalls)(input.userMessage, relationshipAuthorization.advertisedToolNames)
1446
+ : undefined;
1447
+ const installState = isSanctuaryOwner
1448
+ ? (0, sanctuary_install_state_contract_1.sanctuaryInstallStateRequiredToolCalls)(input.userMessage, relationshipAuthorization.advertisedToolNames)
1449
+ : undefined;
1450
+ const versionQuestion = isSanctuaryOwner
1451
+ ? (0, sanctuary_install_state_contract_1.sanctuaryVersionQuestionRequiredToolCalls)(input.userMessage, relationshipAuthorization.advertisedToolNames)
1452
+ : undefined;
1453
+ if (input.fullVisibilityProgress && fullVisibility)
1454
+ input.fullVisibilityProgress.fallback = fullVisibility.emptyResponseFallback;
1455
+ const contracts = [storageOptimization, fullVisibility, staleDockerCare, mediaCatalog, installState, versionQuestion].filter(Boolean);
1456
+ const ownedNames = contracts.map((contract) => new Set(contract.names));
1457
+ const requiredToolCalls = contracts.length === 0 ? undefined : {
1458
+ names: [...new Set(contracts.flatMap((contract) => [...contract.names]))],
1459
+ get retryMessage() { return contracts.map((contract) => contract.retryMessage).join(" "); },
1460
+ requireSuccessfulResults: true,
1461
+ validateRequiredToolResult: (name, result, args) => contracts.every((contract, index) => {
1462
+ if (!ownedNames[index].has(name))
1463
+ return true;
1464
+ return contract.validateRequiredToolResult?.(name, result, args) ?? true;
1465
+ }),
1466
+ validateToolCallBeforeDispatch: (name, args) => contracts.map((contract) => contract.validateToolCallBeforeDispatch?.(name, args)).find((rejection) => rejection !== undefined),
1467
+ requiredToolCallsAfterResult: (name, args, result) => {
1468
+ const added = new Set();
1469
+ contracts.forEach((contract, index) => {
1470
+ if (!ownedNames[index].has(name) || !contract.requiredToolCallsAfterResult)
1471
+ return;
1472
+ for (const requiredName of contract.requiredToolCallsAfterResult(name, args, result)) {
1473
+ ownedNames[index].add(requiredName);
1474
+ added.add(requiredName);
1475
+ }
1476
+ });
1477
+ return [...added];
1478
+ },
1479
+ validateTerminalAnswer: (answer) => contracts.map((contract) => contract.validateTerminalAnswer?.(answer)).find((rejection) => rejection !== undefined),
1480
+ };
1481
+ const currentToolContext = { ...runAgentOptions.toolContext, relationshipAuthorization };
1482
+ if (isSanctuaryOwner && rootHostRuntime && input.authority && await authorityTransport.hostApproval.refresh()) {
1483
+ currentToolContext.rootHost = { port: authorityTransport.hostApproval, observation: input.authority };
1484
+ try {
1485
+ await (0, tools_sanctuary_host_1.authorizeRootHostContext)(currentToolContext);
1486
+ }
1487
+ catch {
1488
+ delete currentToolContext.rootHost;
1489
+ }
1490
+ }
1491
+ return {
1492
+ ...runAgentOptions,
1493
+ ...(requiredToolCalls ? { requiredToolCalls } : {}),
1494
+ toolContext: currentToolContext,
1495
+ };
1496
+ };
1497
+ };
1498
+ const dispatchResolvedRelationshipTurn = async (input) => {
1499
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, input.friendId, "telegram", input.sessionKey, agentRoot);
1500
+ const effects = [];
1501
+ const chat = (0, telegram_chat_actions_1.createTelegramChatActions)(api, input.chatId, input.messageId, noteTurnSpoke);
1502
+ let ordinal = 0;
1503
+ const deliver = async (text, terminalReturn = false) => {
1504
+ const obligation = terminalReturn ? (0, obligations_1.findPendingObligationForRequest)(agentRoot, {
1505
+ requestId: input.requestId,
1506
+ owedTo: { friendId: input.friendId, channel: "telegram", key: input.sessionKey },
1507
+ }) : undefined;
1508
+ effects.push(await executeAuthorizedEffect({
1509
+ idempotencyKey: `relationship-turn:${input.requestId}:delivery:${ordinal++}`,
1510
+ target: { kind: "approved_relationship", friendId: input.friendId, sessionKey: input.sessionKey, requestId: input.requestId },
1511
+ authorClass: "butler",
1512
+ effect: { kind: "text", text, ...(chat.replyToMessageId() ? { replyToMessageId: chat.replyToMessageId() } : {}) },
1513
+ ...(obligation?.returnReadyAt ? { obligationReturnId: obligation.id } : {}),
1514
+ }));
1515
+ };
1516
+ const orientationFrame = input.orientation?.kind === "newly_admitted"
1517
+ ? {
1518
+ ...(0, orientation_frame_1.buildOrientationFrame)({ channel: "telegram", messages: [{ role: "user", content: input.text }] }),
1519
+ source: {
1520
+ kind: "telegram_newly_admitted",
1521
+ authority: "presentation_only",
1522
+ routingHint: [
1523
+ "This is this person’s first admitted turn. Welcome them warmly and briefly explain what the household Butler can help with before answering their request.",
1524
+ input.orientation.relationship ? `The owner identified this person as their ${input.orientation.relationship}.` : null,
1525
+ input.orientation.attachmentsNeedResend ? "Their original message included attachments that were not downloaded; ask them to resend those attachments now." : null,
1526
+ ].filter(Boolean).join(" "),
1527
+ },
1528
+ }
1529
+ : undefined;
1530
+ const fullVisibility = createFullVisibilityProgress();
1531
+ const result = await runTurn({
1532
+ agentName: options.agentName,
1533
+ channel: "telegram",
1534
+ sessionKey: input.sessionKey,
1535
+ friendId: input.friendId,
1536
+ identity: { provider: "telegram-user", externalId: input.userId, displayName: "Household member", tenantId: botId },
1537
+ userMessage: input.text,
1538
+ ingressRelations: { replyToEventId: null, threadRootEventId: null, references: [input.reference] },
1539
+ precommittedIngress: { eventId: input.eventId, reference: input.reference },
1540
+ ...(orientationFrame ? { orientationFrame } : {}),
1541
+ toolContext: { ...(toolContext ?? {}), chatActions: chat.actions, attachmentIds: input.attachmentIds ?? [] },
1542
+ prepareRunAgentOptions: prepareRelationshipRunAgentOptions({ friendId: input.friendId, requestId: input.requestId,
1543
+ sessionEventId: input.eventId, userId: input.userId, chatId: input.chatId, sessionKey: input.sessionKey, userMessage: input.text, fullVisibilityProgress: fullVisibility.progress }),
1544
+ emptyResponseFallback: fullVisibility.emptyResponseFallback,
1545
+ deliverySink: { onDelivery: (delivery) => deliver(delivery.text, delivery.kind === "settle") },
1546
+ });
1547
+ let responseFallbackArtifactId;
1548
+ const responseFallback = responseFallbackAfterDeliveries(result, effects.length);
1549
+ if (responseFallback) {
1550
+ await deliver(responseFallback, true);
1551
+ responseFallbackArtifactId = effects.at(-1)?.id;
1552
+ }
1553
+ const causalEventIds = Object.fromEntries(effects.flatMap((artifact, index) => {
1554
+ const eventId = result.causalSessionEventIds?.[index]
1555
+ ?? (artifact.id === responseFallbackArtifactId ? result.responseCausalSessionEventId : undefined);
1556
+ return eventId ? [[artifact.id, eventId]] : [];
1557
+ }));
1558
+ await recordAcceptedEffects(sessionPath, effects, undefined, causalEventIds);
1559
+ };
1560
+ const admissionController = options.admission && admissionStore ? (0, telegram_admission_1.createTelegramAdmissionController)({
1561
+ store: admissionStore,
1562
+ owner: { friendId: configuredOwnerFriendId, sessionKey: configuredOwnerSessionKey },
1563
+ sendEffect: async (request) => {
1564
+ const artifact = await executeAuthorizedEffect(request);
1565
+ if (artifact.target.kind === "approved_relationship") {
1566
+ await recordAcceptedEffects((0, shared_turn_1.getSenseSessionPath)(options.agentName, artifact.target.friendId, "telegram", artifact.target.sessionKey, agentRoot), [artifact]);
1567
+ }
1568
+ return artifact.id;
1569
+ },
1570
+ resolveOwnerCard: (messageId) => {
1571
+ const resolved = (0, telegram_effect_adapter_1.resolveTelegramControlArtifact)(getEffectJournal(), { messageId, friendId: configuredOwnerFriendId, sessionKey: configuredOwnerSessionKey });
1572
+ return resolved?.requestId
1573
+ ? { artifactId: resolved.artifactId, admissionId: resolved.requestId }
1574
+ : null;
1575
+ },
1576
+ resolveOwnerCardMessageId: (artifactId) => {
1577
+ const artifact = getEffectJournal().read(artifactId);
1578
+ if (artifact.authorClass !== "control" || artifact.target.kind !== "approved_relationship"
1579
+ || artifact.target.friendId !== configuredOwnerFriendId || artifact.target.sessionKey !== configuredOwnerSessionKey)
1580
+ return null;
1581
+ return artifact.parts.find((part) => part.state === "session_recorded" && part.messageId)?.messageId ?? null;
1582
+ },
1583
+ claimFriend: options.admission.claimFriend,
1584
+ revokeFriend: options.admission.revokeFriend,
1585
+ ...(authorityTransport ? {
1586
+ registerCommunication: (input) => authorityTransport.admitChat({
1587
+ admissionId: input.id,
1588
+ updateId: input.updateId,
1589
+ userId: input.userId,
1590
+ chatId: input.chatId,
1591
+ }),
1592
+ revokeCommunication: (input) => authorityTransport.revokeChat(input),
1593
+ } : {}),
1594
+ commitApprovedIngress: async (input) => {
1595
+ const sessionKey = `telegram:${input.botId}:${input.userId}`;
1596
+ const reference = `telegram-admission:${input.admissionId}`;
1597
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, input.friendId, "telegram", sessionKey, agentRoot);
1598
+ const receipt = await (0, telegram_effect_adapter_1.recordTelegramEffectsInSession)({ store: getEffectJournal(), sessionPath, artifacts: [], inbound: { text: (0, delegated_command_1.shieldDelegatedBanner)(input.text), reference } });
1599
+ return { admissionId: input.admissionId, friendId: input.friendId, sessionKey, eventId: receipt.eventId, reference };
1600
+ },
1601
+ enqueueApprovedWork: async (input) => {
1602
+ if (!inboxStore.captureAdmittedWork)
1603
+ throw new Error("Telegram admitted work inbox is unavailable");
1604
+ inboxStore.captureAdmittedWork(input);
1605
+ },
1606
+ dispatchApprovedWork: async (input) => {
1607
+ if (!inboxStore.admittedWorkState || !inboxStore.claimAdmittedWork || !inboxStore.completeAdmittedWork)
1608
+ return "indeterminate";
1609
+ const state = inboxStore.admittedWorkState(input.admissionId);
1610
+ if (state === "settled")
1611
+ return "settled";
1612
+ if (state !== "pending" || !inboxStore.claimAdmittedWork(input.admissionId))
1613
+ return "indeterminate";
1614
+ try {
1615
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, input.friendId, "telegram", input.sessionKey, agentRoot);
1616
+ const envelope = (0, session_events_1.loadSessionEnvelopeFile)(sessionPath);
1617
+ const event = envelope?.events.find((candidate) => candidate.id === input.eventId
1618
+ && candidate.role === "user" && candidate.relations.references.includes(input.reference));
1619
+ if (!event || typeof event.content !== "string")
1620
+ throw new Error("Telegram admitted work ingress is unavailable");
1621
+ const record = admissionStore.read(input.admissionId);
1622
+ const text = event.content;
1623
+ // The newly admitted Friend's first turn answers their message, not the owner's decision that let it run.
1624
+ await telegramInboundTurn.exit(() => dispatchResolvedRelationshipTurn({ friendId: input.friendId, sessionKey: input.sessionKey, requestId: input.admissionId,
1625
+ eventId: input.eventId, reference: input.reference, text, userId: record.userId, chatId: record.chatId, orientation: input.orientation }));
1626
+ inboxStore.completeAdmittedWork(input.admissionId);
1627
+ return "settled";
1628
+ }
1629
+ catch {
1630
+ return "indeterminate";
1631
+ }
1632
+ },
1633
+ withDecisionLease: (admissionId, work) => (0, session_transaction_1.withSessionTurnLease)(path.join(agentRoot, "state", "senses", "telegram", "admission-decisions", admissionId), async () => work()),
1634
+ ...(options.admission.createDisplayCode ? { createDisplayCode: options.admission.createDisplayCode } : {}),
1635
+ }) : undefined;
1636
+ const recoverEffectOutbox = async () => {
1637
+ if (!effectJournal && !(0, node_fs_1.existsSync)(path.join(agentRoot, "state", "telegram", "effects")))
1638
+ return;
1639
+ await (0, telegram_effect_adapter_1.recoverTelegramEffectOutbox)({
1640
+ store: getEffectJournal(),
1641
+ execute: executeAuthorizedEffect,
1642
+ matches: (artifact) => artifact.target.kind === "approved_relationship",
1643
+ });
1644
+ const accepted = getEffectJournal().list().filter((artifact) => artifact.target.kind === "approved_relationship" && artifact.parts.some((part) => part.state === "accepted"));
1645
+ for (const artifact of accepted) {
1646
+ const target = artifact.target;
1647
+ await recordAcceptedEffects((0, shared_turn_1.getSenseSessionPath)(options.agentName, target.friendId, "telegram", target.sessionKey, agentRoot), [artifact]);
1648
+ }
1649
+ };
1650
+ const hydrateAuthorizedMessage = async (message) => {
1651
+ // The one place inbound Telegram text is assembled for every turn and every stored ingress event: a typed delegated-command banner is marked here, so the stored event and the turn carry identical, shielded text.
1652
+ if (!message.attachments?.length)
1653
+ return { text: (0, delegated_command_1.shieldDelegatedBanner)([message.text, ...(message.attachmentNotices ?? [])].filter(Boolean).join("\n")), attachmentIds: [] };
1654
+ const ingested = await (0, telegram_attachments_1.ingestTelegramAttachments)({
1655
+ agentName: options.agentName,
1656
+ agentRoot,
1657
+ ...(botToken ? { botToken } : {}),
1658
+ api,
1659
+ ...(authorityTransport ? { downloadFile: authorityTransport.downloadFile } : {}),
1660
+ ...(options.attachmentFetch ? { fetch: options.attachmentFetch } : {}),
1661
+ attachments: message.attachments ?? [],
1662
+ });
1663
+ const attachmentIds = ingested.attachments.map((attachment) => attachment.id);
1664
+ const attachmentLines = await (0, understand_1.attachmentTurnLines)(ingested.attachments, { agentName: options.agentName, agentRoot, userText: message.text, timeoutMs: understand_1.ATTACHMENT_WORDS_TIMEOUT_MS });
1665
+ return {
1666
+ text: (0, delegated_command_1.shieldDelegatedBanner)([message.text, ...attachmentLines, ...(message.attachmentNotices ?? []), ...ingested.notices].filter(Boolean).join("\n")),
1667
+ attachmentIds,
1668
+ };
1669
+ };
1670
+ const onMessageBody = async (rawMessage) => {
1671
+ const hydrated = await hydrateAuthorizedMessage(rawMessage);
1672
+ const message = { ...rawMessage, text: hydrated.text };
1673
+ const currentFriendId = configuredOwnerFriendId;
1674
+ const currentSessionKey = configuredOwnerSessionKey;
1675
+ const currentSessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, currentFriendId, "telegram", currentSessionKey, agentRoot);
1676
+ const inboundReference = `telegram-inbound:${(0, node_crypto_1.createHmac)("sha256", identityKey).update(`${message.updateId}\0${message.messageId}`).digest("hex")}`;
1677
+ const acceptanceMarker = options.acceptanceMarker ? options.acceptanceMarker() : (0, sanctuary_acceptance_marker_1.readSanctuaryAcceptanceMarker)(options.agentName);
1678
+ const acceptanceMeta = (0, sanctuary_acceptance_marker_1.sanctuaryAcceptanceEventMeta)(options.agentName);
1679
+ const groundedAcceptance = acceptanceMarker?.label === "unit-16d-whats-up" || acceptanceMarker?.label === "unit-16d-1-space";
1680
+ const acceptanceSchema = groundedAcceptance ? "sanctuary-telegram-turn-receipt-v4" : "sanctuary-telegram-turn-receipt-v3";
1681
+ const auditDigest = (purpose, value) => sanctuaryTelegramTurnReceiptDigest(identityKey, acceptanceSchema, purpose, value);
1682
+ const lifecycleCoordinates = acceptanceMarker ? {
1683
+ scenarioHandleDigest: acceptanceMarker.scenarioHandleDigest,
1684
+ turnDigest: auditDigest("turn", `${message.updateId}\0${message.messageId}`),
1685
+ updateDigest: auditDigest("update", `${message.updateId}\0${message.messageId}`),
1686
+ subject,
1687
+ identityDigest: auditDigest("identity", subject),
1688
+ sessionDigest: auditDigest("session", `telegram:${subject}`),
1689
+ argumentDigest: auditDigest("argument", message.text),
1690
+ } : {};
1691
+ const lifecycleStartedAt = Date.now();
1692
+ const lifecycleMeta = (event, meta, lifecycleAt) => acceptanceMarker
1693
+ ? { ...meta, lifecycleAt, lifecycleMac: sanctuaryTelegramAuditLifecycleMac(identityKey, acceptanceSchema, event, { ...meta, lifecycleAt }) }
1694
+ : meta;
1695
+ (0, runtime_1.emitNervesEvent)({
1696
+ component: "senses",
1697
+ event: "senses.telegram_turn_start",
1698
+ message: "Telegram authorized turn started",
1699
+ meta: lifecycleMeta("senses.telegram_turn_start", { agentName: options.agentName, subject, ...acceptanceMeta, ...lifecycleCoordinates }, lifecycleStartedAt),
1700
+ });
1701
+ acceptanceAuditBarrier();
1702
+ const deliveredMessageIds = [];
1703
+ const deliveredChunks = [];
1704
+ let receiptStatus = "success";
1705
+ let errorCategory = null;
1706
+ const turnMetricsObserver = { providerInvocationCount: 0, toolInvocationCount: 0 };
1707
+ const toolReceiptObserver = { toolResultDigests: [], toolGroundings: [] };
1708
+ const normalizedRequest = message.text.normalize("NFKC").trim().toLocaleLowerCase("en-US");
1709
+ const exactDownloadCreditQuestion = normalizedRequest === "why aren't my shows downloading?";
1710
+ const groundingIntentTool = groundedAcceptance
1711
+ ? /^(?:what['’]?s up|status)\??$/u.test(normalizedRequest) ? "unraid_get_system"
1712
+ : /^how much (?:space|storage) is left\??$/u.test(normalizedRequest) ? "unraid_get_storage"
1713
+ : null
1714
+ : null;
1715
+ const bufferedGroundedDeliveries = [];
1716
+ const turnEffects = [];
1717
+ let deliveryOrdinal = 0;
1718
+ // What these send belongs to other turns and notices, not to this message.
1719
+ await telegramInboundTurn.exit(async () => {
1720
+ await recoverEffectOutbox();
1721
+ await releaseHeldNoticesQuietly();
1722
+ });
1723
+ let ingressRelations = { replyToEventId: null, threadRootEventId: null, references: [inboundReference] };
1724
+ if (message.replyToMessageId && /^[1-9][0-9]*$/u.test(message.replyToMessageId)) {
1725
+ const replyMessageId = Number(message.replyToMessageId);
1726
+ const reply = (0, telegram_effect_adapter_1.resolveTelegramReply)(getEffectJournal(), { messageId: replyMessageId, friendId: currentFriendId, sessionKey: currentSessionKey });
1727
+ const session = reply ? (0, session_events_1.loadSessionEnvelopeFile)(currentSessionPath) : null;
1728
+ if (reply && session?.events.some((event) => event.id === reply.sessionEventId))
1729
+ ingressRelations = {
1730
+ replyToEventId: reply.sessionEventId,
1731
+ threadRootEventId: null,
1732
+ references: [inboundReference, `telegram-artifact:${reply.artifactId}`, ...(reply.requestId ? [`request:${reply.requestId}`] : [])],
1733
+ };
1734
+ }
1735
+ try {
1736
+ acceptanceAuditBarrier();
1737
+ const ingressReceipt = options.resolveRelationshipAuthorization
1738
+ ? await (0, telegram_effect_adapter_1.recordTelegramEffectsInSession)({
1739
+ store: getEffectJournal(),
1740
+ sessionPath: currentSessionPath,
1741
+ artifacts: [],
1742
+ inbound: { text: message.text, reference: inboundReference, attachmentIds: hydrated.attachmentIds, relations: ingressRelations },
1743
+ })
1744
+ : null;
1745
+ const fullVisibility = createFullVisibilityProgress();
1746
+ const chat = (0, telegram_chat_actions_1.createTelegramChatActions)(api, message.chatId, message.messageId, noteTurnSpoke);
1747
+ const collected = await collectToolReceipts(() => runTurn({
1748
+ agentName: options.agentName,
1749
+ channel: "telegram",
1750
+ sessionKey: currentSessionKey,
1751
+ friendId: currentFriendId,
1752
+ identity: {
1753
+ provider: "telegram-user",
1754
+ externalId: options.admission ? message.userId : subject,
1755
+ displayName: options.admission ? ownerDisplayName(options.agentName) : `Telegram user ${subject}`,
1756
+ ...(options.admission ? { tenantId: botId } : {}),
1757
+ },
1758
+ userMessage: message.text,
1759
+ ingressRelations,
1760
+ ...(message.interaction?.kind === "reaction" ? { isReactionSignal: true } : {}),
1761
+ ...(message.replyToText ? { replyingTo: { text: message.replyToText, ...(message.replyToAuthor ? { author: message.replyToAuthor } : {}) } } : {}),
1762
+ ...(ingressReceipt ? { precommittedIngress: ingressReceipt } : {}),
1763
+ turnMetricsObserver,
1764
+ emptyResponseFallback: fullVisibility.emptyResponseFallback,
1765
+ deliverySink: {
1766
+ onDelivery: async (delivery) => {
1767
+ if (groundingIntentTool) {
1768
+ bufferedGroundedDeliveries.push(delivery.kind);
1769
+ }
1770
+ else {
1771
+ turnEffects.push(await deliverButlerEffect(delivery.text, `turn:${subject}:${message.updateId}:delivery:${deliveryOrdinal++}`, undefined, (messageId, chunk) => { deliveredMessageIds.push(messageId); deliveredChunks.push(chunk); }, exactDownloadCreditQuestion, chat.replyToMessageId()));
1772
+ }
1773
+ },
1774
+ },
1775
+ toolContext: { ...(toolContext ?? {}), chatActions: chat.actions, ...(options.resolveRelationshipAuthorization ? { attachmentIds: hydrated.attachmentIds } : {}) },
1776
+ ...(options.resolveRelationshipAuthorization ? {
1777
+ prepareRunAgentOptions: prepareRelationshipRunAgentOptions({
1778
+ friendId: currentFriendId,
1779
+ requestId: inboundReference,
1780
+ sessionEventId: ingressReceipt.eventId,
1781
+ userId: message.userId,
1782
+ chatId: message.chatId,
1783
+ sessionKey: currentSessionKey,
1784
+ userMessage: message.text,
1785
+ authority: message.authority,
1786
+ fullVisibilityProgress: fullVisibility.progress,
1787
+ }),
1788
+ } : {}),
1789
+ ...(approvalRuntime ? { approvalCoordinatorFactory: rootHostRuntime ? approvalCoordinatorFactory : approvalRuntime.coordinator } : {}),
1790
+ }), toolReceiptObserver);
1791
+ const result = collected.result;
1792
+ let responseFallbackArtifactId;
1793
+ turnMetricsObserver.providerInvocationCount = Math.max(turnMetricsObserver.providerInvocationCount, result.providerInvocationCount ?? 0);
1794
+ turnMetricsObserver.toolInvocationCount = Math.max(turnMetricsObserver.toolInvocationCount, result.toolInvocationCount ?? 0);
1795
+ if (groundingIntentTool) {
1796
+ const grounding = toolReceiptObserver.toolGroundings?.length === 1 ? toolReceiptObserver.toolGroundings[0] : undefined;
1797
+ if (!grounding || grounding.toolName !== groundingIntentTool || bufferedGroundedDeliveries.length > 1
1798
+ || (bufferedGroundedDeliveries.length === 1 && bufferedGroundedDeliveries[0] !== "settle"))
1799
+ throw new Error("Canonical Sanctuary query did not produce exactly one matching grounded settle");
1800
+ const canonical = (0, sanctuary_grounding_1.renderSanctuaryGroundedResponse)(grounding.toolName, grounding.facts);
1801
+ turnEffects.push(await deliverButlerEffect(canonical, `turn:${subject}:${message.updateId}:delivery:${deliveryOrdinal++}`, undefined, (messageId, chunk) => { deliveredMessageIds.push(messageId); deliveredChunks.push(chunk); }));
1802
+ }
1803
+ else {
1804
+ const responseFallback = responseFallbackAfterDeliveries(result, turnEffects.length);
1805
+ if (responseFallback) {
1806
+ const artifact = await deliverButlerEffect(responseFallback, `turn:${subject}:${message.updateId}:delivery:${deliveryOrdinal++}`, undefined, (messageId, chunk) => { deliveredMessageIds.push(messageId); deliveredChunks.push(chunk); }, exactDownloadCreditQuestion);
1807
+ turnEffects.push(artifact);
1808
+ responseFallbackArtifactId = artifact.id;
1809
+ }
1810
+ }
1811
+ if (result.sessionPath) {
1812
+ const causalEventIds = Object.fromEntries((groundingIntentTool ? [] : turnEffects).flatMap((artifact, index) => {
1813
+ const eventId = result.causalSessionEventIds?.[index];
1814
+ if (eventId)
1815
+ return [[artifact.id, eventId]];
1816
+ return artifact.id === responseFallbackArtifactId && result.responseCausalSessionEventId
1817
+ ? [[artifact.id, result.responseCausalSessionEventId]]
1818
+ : [];
1819
+ }));
1820
+ await recordAcceptedEffects(result.sessionPath, turnEffects, undefined, causalEventIds);
1821
+ }
1822
+ (0, runtime_1.emitNervesEvent)({
1823
+ component: "senses",
1824
+ event: "senses.telegram_turn_end",
1825
+ message: "Telegram authorized turn completed",
1826
+ meta: lifecycleMeta("senses.telegram_turn_end", { agentName: options.agentName, subject, deliveryCount: turnEffects.length, ...acceptanceMeta, ...lifecycleCoordinates, ...(acceptanceMarker ? { outcome: "success", errorDigest: null } : {}) }, Math.max(Date.now(), lifecycleStartedAt + 1)),
1827
+ });
1828
+ }
1829
+ catch (error) {
1830
+ receiptStatus = "error";
1831
+ errorCategory = (error instanceof Error && error.name.trim() ? error.name : "unknown").slice(0, 128);
1832
+ (0, runtime_1.emitNervesEvent)({
1833
+ level: "error",
1834
+ component: "senses",
1835
+ event: "senses.telegram_turn_error",
1836
+ message: "Telegram authorized turn failed",
1837
+ meta: lifecycleMeta("senses.telegram_turn_error", {
1838
+ agentName: options.agentName,
1839
+ subject,
1840
+ ...acceptanceMeta,
1841
+ ...lifecycleCoordinates,
1842
+ ...(acceptanceMarker ? {
1843
+ outcome: "error",
1844
+ errorDigest: auditDigest("error", redactTelegramPrivateValues(error, [...transportPrivateValues, String(message.updateId), message.messageId])),
1845
+ deliveryCount: deliveredMessageIds.length,
1846
+ } : { error: redactTelegramPrivateValues(error, [...transportPrivateValues, String(message.updateId), message.messageId]) }),
1847
+ }, Math.max(Date.now(), lifecycleStartedAt + 1)),
1848
+ });
1849
+ // Every owner message runs inside its inbound turn.
1850
+ telegramInboundTurn.getStore().failure = `the turn failed (${errorCategory})`;
1851
+ const fallback = "I couldn't complete that turn. The failure was recorded; please try again.";
1852
+ if (deliveredMessageIds.length === 0)
1853
+ turnEffects.push(await deliverButlerEffect(fallback, `turn:${subject}:${message.updateId}:fallback`, undefined, (messageId, chunk) => { deliveredMessageIds.push(messageId); deliveredChunks.push(chunk); }, exactDownloadCreditQuestion));
1854
+ await recordAcceptedEffects(currentSessionPath, turnEffects, { text: message.text, reference: inboundReference, attachmentIds: hydrated.attachmentIds });
1855
+ }
1856
+ finally {
1857
+ if (acceptanceMarker) {
1858
+ acceptanceAuditBarrier();
1859
+ const grounded = groundedAcceptance;
1860
+ const schemaVersion = grounded ? "sanctuary-telegram-turn-receipt-v4" : "sanctuary-telegram-turn-receipt-v3";
1861
+ const hmac = (purpose, value) => sanctuaryTelegramTurnReceiptDigest(identityKey, schemaVersion, purpose, value);
1862
+ const redact = (value) => [...transportPrivateValues, String(message.updateId), message.messageId]
1863
+ .reduce((text, privateValue) => privateValue.length >= 5 ? text.replaceAll(privateValue, "[REDACTED]") : text, value);
1864
+ const deliveries = deliveredMessageIds.map((messageId, index) => {
1865
+ const chunk = deliveredChunks[index];
1866
+ const redactedText = redact(chunk);
1867
+ return { messageIdDigest: hmac("delivery", String(messageId)), chunkDigest: hmac("chunk", grounded ? redactedText : chunk), ...(grounded ? { redactedText, utf16Units: redactedText.length } : {}) };
1868
+ });
1869
+ try {
1870
+ const receipt = {
1871
+ schemaVersion,
1872
+ scenarioHandleDigest: acceptanceMarker.scenarioHandleDigest,
1873
+ status: receiptStatus,
1874
+ errorCategory,
1875
+ updateDigest: hmac("update", `${message.updateId}\0${message.messageId}`),
1876
+ sequenceDigest: hmac("sequence", String(message.updateId)),
1877
+ responseDigest: hmac("response", JSON.stringify(deliveries)),
1878
+ toolResultDigests: toolReceiptObserver.toolResultDigests,
1879
+ ...(grounded ? { toolGroundings: toolReceiptObserver.toolGroundings } : {}),
1880
+ providerInvocationCount: turnMetricsObserver.providerInvocationCount,
1881
+ toolInvocationCount: turnMetricsObserver.toolInvocationCount,
1882
+ deliveryCount: deliveries.length,
1883
+ deliveries,
1884
+ completedAt: new Date().toISOString(),
1885
+ };
1886
+ if (grounded)
1887
+ receipt.receiptMac = sanctuaryTelegramTurnReceiptMac(identityKey, receipt);
1888
+ await appendSanctuaryTurnReceipt(options.acceptanceReceiptRoot ?? agentRoot, receipt, options._afterAcceptanceLedgerPreReadStat);
1889
+ }
1890
+ catch (error) {
1891
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.telegram_acceptance_receipt_error", message: "Telegram acceptance receipt persistence failed", meta: { agentName: options.agentName, scenarioHandleDigest: acceptanceMarker.scenarioHandleDigest, category: error instanceof Error ? error.name : "unknown" } });
1892
+ }
1893
+ }
1894
+ }
1895
+ };
1896
+ // Telegram tells the bot which message was reacted to, not what it said. The journal knows the agent's own messages.
1897
+ const nameReactionTarget = async (message) => {
1898
+ const interaction = message.interaction;
1899
+ if (interaction?.kind !== "reaction")
1900
+ return message;
1901
+ const named = await (0, chat_interaction_1.resolveChatInteractionTarget)(interaction, (id) => {
1902
+ const sent = (0, telegram_effect_adapter_1.resolveTelegramReply)(getEffectJournal(), { messageId: Number(id), friendId: configuredOwnerFriendId, sessionKey: configuredOwnerSessionKey });
1903
+ return sent?.text ? { text: sent.text, fromAgent: true } : null;
1904
+ });
1905
+ return named === interaction ? message : { ...message, interaction: named, text: (0, chat_interaction_1.renderChatInteraction)(named) };
1906
+ };
1907
+ /** Write a message's entry before its turn, or null when it must not run: it has an outcome, or a stopped turn left it unsafe to run again. */
1908
+ const beginInbound = (id) => {
1909
+ let entry;
1910
+ try {
1911
+ entry = getInboundJournal().record(id, { updateClass: "message" });
1912
+ }
1913
+ catch (error) {
1914
+ inboundJournalFailed(error);
1915
+ return { id: null, spoke: false, failure: null };
1916
+ }
1917
+ if (!entry)
1918
+ return null;
1919
+ const refusal = telegramReplayRefusal(entry);
1920
+ if (refusal) {
1921
+ settleInbound(id, "failed", refusal);
1922
+ return null;
1923
+ }
1924
+ getInboundJournal().beginAttempt(id);
1925
+ return { id, spoke: false, failure: null };
1926
+ };
1927
+ /** Run a message's turn and record its one outcome. A turn that throws is recorded as failed and the error goes on. */
1928
+ const runInboundTurn = async (turn, body) => {
1929
+ await telegramInboundTurn.run(turn, async () => {
1930
+ try {
1931
+ await body();
1932
+ }
1933
+ catch (error) {
1934
+ const stopped = `the turn stopped with an error (${error instanceof Error ? error.name : "unknown"})`;
1935
+ if (turn.id)
1936
+ settleInbound(turn.id, "failed", turn.spoke ? `${stopped} after a reply may have gone out` : `${stopped}, and no reply reached them`);
1937
+ throw error;
1938
+ }
1939
+ if (turn.id)
1940
+ settleInbound(turn.id, turn.failure ? "failed" : turn.spoke ? "answered" : "silent", turn.failure ?? undefined);
1941
+ });
1942
+ };
1943
+ /** Record a message a stopped process left as failed, writing its entry first when it has none. */
1944
+ const failInbound = (id, reason) => {
1945
+ try {
1946
+ getInboundJournal().record(id, { updateClass: "message" });
1947
+ }
1948
+ catch (error) {
1949
+ inboundJournalFailed(error);
1950
+ return;
1951
+ }
1952
+ settleInbound(id, "failed", reason);
1953
+ };
1954
+ /**
1955
+ * Telegram redelivered a message a stopped process left. It runs again only when nothing went out for it and it
1956
+ * has tries left; otherwise it is recorded as failed, so no message is left pending. A household Friend's message is
1957
+ * known by its reference. Callbacks and strangers' messages never get an entry and keep their own recovery.
1958
+ */
1959
+ const replayIndeterminate = async (update, reclaim) => {
1960
+ const coordinates = (0, telegram_client_1.telegramUpdateMessageCoordinates)(update);
1961
+ if (!coordinates || coordinates.chatType !== "private")
1962
+ return false;
1963
+ const owner = coordinates.userId === authorizedUserId && coordinates.chatId === authorizedChatId;
1964
+ // Only a new message reaches a household Friend's turn; their edits and reactions are not run.
1965
+ if (!owner && (!update.message || !botId || !options.admission))
1966
+ return false;
1967
+ const reference = owner ? null : telegramHouseholdReference(identityKey, botId, coordinates.userId, update.update_id, coordinates.messageId);
1968
+ const id = reference ? householdInboundIdFor(reference) : inboundIdFor(update.update_id);
1969
+ let entry = null;
1970
+ try {
1971
+ entry = getInboundJournal().get(id);
1972
+ if (!entry && (0, inbound_journal_1.readInboundOutcome)(agentRoot, "telegram", id))
1973
+ return false;
1974
+ if (reference && !await options.admission.resolveApprovedFriend({ botId: botId, userId: coordinates.userId, chatId: coordinates.chatId })) {
1975
+ if (entry)
1976
+ failInbound(id, "they are no longer a household Friend, so it is not run again");
1977
+ return false;
1978
+ }
1979
+ // With no entry the turn never started, or its entry could not be written; a reply it prepared shows which.
1980
+ const preparedKeys = reference ? [`relationship-turn:${reference}:delivery:0`]
1981
+ : [`turn:${subject}:${update.update_id}:delivery:0`, `turn:${subject}:${update.update_id}:fallback`];
1982
+ const refusal = entry ? telegramReplayRefusal(entry)
1983
+ : preparedKeys.some((key) => getEffectJournal().readByIdempotencyKey(key))
1984
+ ? "a reply was prepared before it stopped, but its record could not be written, so it is not run again"
1985
+ : null;
1986
+ if (refusal) {
1987
+ failInbound(id, refusal);
1988
+ return false;
1989
+ }
1990
+ if (!reclaim()) {
1991
+ failInbound(id, "it could not be taken back from the update inbox to run again");
1992
+ return false;
1993
+ }
1994
+ (0, runtime_1.emitNervesEvent)({
1995
+ level: "warn",
1996
+ component: "senses",
1997
+ event: "senses.telegram_inbound_replaying",
1998
+ message: "running a Telegram message again: its turn stopped before anything went out",
1999
+ meta: { agentName: options.agentName, attempts: entry?.attempts ?? 0 },
2000
+ });
2001
+ return true;
2002
+ }
2003
+ catch (error) {
2004
+ // A message with no entry from someone who is not the owner may be a stranger's, which never gets a record.
2005
+ if (entry || owner)
2006
+ failInbound(id, `deciding whether to run it again failed (${error instanceof Error ? error.name : "unknown"})`);
2007
+ else
2008
+ inboundJournalFailed(error);
2009
+ return false;
2010
+ }
2011
+ };
2012
+ /** A message whose update Telegram no longer redelivers can never be answered now, so it is recorded as failed. */
2013
+ const failInboundsPastRedelivery = () => {
2014
+ try {
2015
+ const cutoff = Date.now() - TELEGRAM_REDELIVERY_WINDOW_MS;
2016
+ for (const entry of getInboundJournal().pending()) {
2017
+ if (Date.parse(entry.receivedAt) < cutoff)
2018
+ settleInbound(entry.id, "failed", "Telegram stopped redelivering it after a day, so it was never answered");
2019
+ }
2020
+ }
2021
+ catch (error) {
2022
+ inboundJournalFailed(error);
2023
+ }
2024
+ };
2025
+ const onMessage = (inbound) => runWithAcceptanceAuditOwner(async () => {
2026
+ const message = await nameReactionTarget(inbound);
2027
+ const turn = beginInbound(inboundIdFor(message.updateId));
2028
+ if (!turn)
2029
+ return;
2030
+ await runInboundTurn(turn, () => handleAuthorizedMessage(message));
2031
+ });
2032
+ const handleAuthorizedMessage = async (message) => {
2033
+ const ownerDecision = !message.interaction && !message.attachments?.length && !message.attachmentNotices?.length ? admissionController?.parseOwnerDecision({
2034
+ text: message.text,
2035
+ ...(message.replyToMessageId ? { replyToMessageId: Number(message.replyToMessageId) } : {}),
2036
+ }) : null;
2037
+ if (ownerDecision) {
2038
+ const actor = await options.admission?.resolveOwner({ botId: botId, userId: message.userId, chatId: message.chatId, sessionKey: configuredOwnerSessionKey });
2039
+ if (!actor)
2040
+ throw new Error("Telegram admission owner decision identity is invalid");
2041
+ await admissionController.decide({ ...ownerDecision, actorFriendId: actor.friendId });
2042
+ return;
2043
+ }
2044
+ if ((message.attachments?.length || message.attachmentNotices?.length) && options.admission) {
2045
+ const actor = await options.admission.resolveOwner({ botId: botId, userId: message.userId, chatId: message.chatId, sessionKey: configuredOwnerSessionKey });
2046
+ if (!actor || actor.friendId !== configuredOwnerFriendId)
2047
+ throw new Error("Telegram attachment owner relationship is not active");
2048
+ }
2049
+ // Show the household that the Butler is working rather than silently thinking.
2050
+ // Presence is deliberately separate from delivery: a transport that cannot do
2051
+ // it degrades to silence instead of failing, and message-delivery assertions
2052
+ // stay about messages.
2053
+ await withTelegramTypingIndicator(() => sendTypingIndicator(message.chatId), () => onMessageBody(message));
2054
+ };
2055
+ const onUnknownMessage = admissionController && options.admission ? async (message) => {
2056
+ const approved = await options.admission.resolveApprovedFriend(message);
2057
+ if (!approved) {
2058
+ await admissionController.handleUnknown(message);
2059
+ return;
2060
+ }
2061
+ const reference = telegramHouseholdReference(identityKey, message.botId, message.userId, message.updateId, message.messageId);
2062
+ const turn = beginInbound(householdInboundIdFor(reference));
2063
+ if (!turn)
2064
+ return;
2065
+ await runInboundTurn(turn, async () => {
2066
+ // Existing household Friends need a root-observed communication binding after gateway migration.
2067
+ await authorityTransport?.admitChat({
2068
+ admissionId: (0, node_crypto_1.createHash)("sha256").update(`telegram-communication-v1\0${message.botId}\0${message.userId}\0${message.chatId}`).digest("hex").slice(0, 20),
2069
+ updateId: message.updateId,
2070
+ userId: message.userId,
2071
+ chatId: message.chatId,
2072
+ });
2073
+ const hydrated = await hydrateAuthorizedMessage({
2074
+ updateId: message.updateId,
2075
+ messageId: String(message.messageId),
2076
+ userId: message.userId,
2077
+ chatId: message.chatId,
2078
+ text: message.text,
2079
+ attachments: message.attachments,
2080
+ attachmentNotices: message.attachmentNotices,
2081
+ });
2082
+ const sessionKey = `telegram:${message.botId}:${message.userId}`;
2083
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, approved.friendId, "telegram", sessionKey, agentRoot);
2084
+ const receipt = await (0, telegram_effect_adapter_1.recordTelegramEffectsInSession)({ store: getEffectJournal(), sessionPath, artifacts: [], inbound: { text: hydrated.text, reference, attachmentIds: hydrated.attachmentIds } });
2085
+ await dispatchResolvedRelationshipTurn({ friendId: approved.friendId, sessionKey, requestId: reference, eventId: receipt.eventId,
2086
+ reference, text: hydrated.text, attachmentIds: hydrated.attachmentIds, userId: message.userId, chatId: message.chatId, messageId: String(message.messageId) });
2087
+ });
2088
+ } : undefined;
2089
+ const onUpdate = async (update) => {
2090
+ const callback = update.callback_query;
2091
+ if (callback && rootHostRuntime && await runWithAcceptanceAuditOwner(() => rootHostRuntime.handleUpdate(update)))
2092
+ return true;
2093
+ if (callback?.data?.startsWith("admit:") && admissionController && callback.message) {
2094
+ return runWithAcceptanceAuditOwner(async () => {
2095
+ const actor = await options.admission?.resolveOwner({ botId: botId, userId: String(callback.from.id), chatId: String(callback.message.chat.id), sessionKey: configuredOwnerSessionKey });
2096
+ if (!actor)
2097
+ throw new Error("Telegram admission owner callback identity is invalid");
2098
+ const decision = admissionController.parseCallback(callback.data, callback.message.message_id);
2099
+ await admissionController.decide({ ...decision, actorFriendId: actor.friendId });
2100
+ const ownerTarget = configuredOwnerTarget();
2101
+ const artifact = await executeAuthorizedEffect({
2102
+ idempotencyKey: `admission-callback:${callback.id}`,
2103
+ target: { ...ownerTarget, requestId: decision.admissionId },
2104
+ authorClass: "control",
2105
+ effect: { kind: "callback_ack", callbackQueryId: callback.id },
2106
+ });
2107
+ await recordAcceptedEffects((0, shared_turn_1.getSenseSessionPath)(options.agentName, ownerTarget.friendId, "telegram", ownerTarget.sessionKey, agentRoot), [artifact]);
2108
+ return true;
2109
+ });
2110
+ }
2111
+ if (!callback || !approvalTransport)
2112
+ return false;
2113
+ return runWithAcceptanceAuditOwner(async () => (await approvalTransport.handleUpdate(update)).handled);
2114
+ };
2115
+ let poll;
2116
+ try {
2117
+ poll = (options.createLongPoll ?? telegram_client_1.createTelegramLongPoll)({
2118
+ api,
2119
+ expectedUserId: authorizedUserId,
2120
+ expectedChatId: authorizedChatId,
2121
+ ...(onUnknownMessage ? { botId: botId, onUnknownMessage } : {}),
2122
+ offsetStore,
2123
+ inboxStore,
2124
+ onMessage,
2125
+ onUpdate,
2126
+ replayIndeterminate,
2127
+ ...(authorityTransport ? {
2128
+ settleTransport: authorityTransport.settleTransport,
2129
+ transportMetadata: authorityTransport.metadataForUpdate,
2130
+ } : {}),
2131
+ acceptanceEventMeta: (update, distinctAccount) => {
2132
+ const marker = options.acceptanceMarker ? options.acceptanceMarker() : (0, sanctuary_acceptance_marker_1.readSanctuaryAcceptanceMarker)(options.agentName);
2133
+ if (!marker)
2134
+ return {};
2135
+ const auditOwnerMeta = acceptanceAuditLease ? { acceptanceAuditOwnerDigest: acceptanceAuditLease.ownerDigest } : {};
2136
+ const messageId = update?.message?.message_id ?? update?.callback_query?.message?.message_id;
2137
+ const senderId = update?.message?.from?.id;
2138
+ if (!update || messageId === undefined || senderId === undefined)
2139
+ return { scenarioHandleDigest: marker.scenarioHandleDigest, ...auditOwnerMeta };
2140
+ const schemaVersion = marker.label === "unit-16d-whats-up" || marker.label === "unit-16d-1-space"
2141
+ ? "sanctuary-telegram-turn-receipt-v4" : "sanctuary-telegram-turn-receipt-v3";
2142
+ const digest = (purpose, value) => sanctuaryTelegramTurnReceiptDigest(identityKey, schemaVersion, purpose, value);
2143
+ const senderDistinct = String(senderId) !== authorizedUserId;
2144
+ if (distinctAccount !== senderDistinct)
2145
+ throw new Error("Telegram dropped-update identity classification mismatch");
2146
+ const binding = {
2147
+ scenarioHandleDigest: marker.scenarioHandleDigest,
2148
+ updateDigest: digest("update", `${update.update_id}\0${messageId}`),
2149
+ senderIdentityDigest: digest("sender-identity", String(senderId)),
2150
+ authorizedIdentityDigest: digest("sender-identity", authorizedUserId),
2151
+ senderDistinct,
2152
+ nextOffsetDigest: digest("next-update-id", String(update.update_id + 1)),
2153
+ };
2154
+ return { ...binding, ...auditOwnerMeta, dropMac: sanctuaryTelegramUnauthorizedDropMac(identityKey, schemaVersion, binding) };
2155
+ },
2156
+ onBeforeDispatch: acceptanceAuditBarrier,
2157
+ onDispatchSettled: acceptanceAuditBarrier,
2158
+ });
2159
+ }
2160
+ catch (error) {
2161
+ releaseAcceptanceAudit(error);
2162
+ }
2163
+ const pendingCleanup = new Set([
2164
+ () => poll.stop(),
2165
+ async () => { await runPromise?.catch(() => undefined); },
2166
+ async () => { await Promise.all([...approvalReconciliationsInFlight]); },
2167
+ async () => { await interactiveControl?.stop(); },
2168
+ async () => { await approvalRelayDoor?.stop(); },
2169
+ () => api.stop(),
2170
+ () => approvalRuntime?.close(),
2171
+ () => effectJournal?.close(),
2172
+ () => admissionStore?.close(),
2173
+ () => (0, tools_awaiting_1.resetAwaitToolDeps)(),
2174
+ () => runWithAcceptanceAuditOwner(() => {
2175
+ (0, runtime_1.emitNervesEvent)({
2176
+ component: "senses",
2177
+ event: "senses.telegram_poll_end",
2178
+ message: "Telegram long poll stopped",
2179
+ meta: { agentName: options.agentName, subject },
2180
+ });
2181
+ }),
2182
+ retireAcceptanceAudit,
2183
+ ]);
2184
+ return {
2185
+ checkOwnerRoute,
2186
+ run(signal) {
2187
+ if (runPromise)
2188
+ return runPromise;
2189
+ runPromise = (async () => {
2190
+ await runWithAcceptanceAuditOwner(migrateIdentity);
2191
+ inboxStore.quarantineStrandedAdmittedWork?.();
2192
+ await runWithAcceptanceAuditOwner(async () => { await admissionController?.recover(); });
2193
+ await runWithAcceptanceAuditOwner(recoverEffectOutbox);
2194
+ failInboundsPastRedelivery();
2195
+ await runWithAcceptanceAuditOwner(reconcileSystemFailsafes);
2196
+ try {
2197
+ await runWithAcceptanceAuditOwner(async () => { await toolContext?.sanctuary?.recoverRoutineActions?.(); });
2198
+ }
2199
+ catch (error) {
2200
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.sanctuary_routine_recovery_error", message: "Sanctuary routine action recovery requires inspection", meta: { agentName: options.agentName, subject, category: error instanceof Error ? error.name : "unknown" } });
2201
+ }
2202
+ await runWithAcceptanceAuditOwner(async () => { await approvalRuntime?.recover(); });
2203
+ await runWithAcceptanceAuditOwner(async () => { await rootHostRuntime?.recover(); });
2204
+ await runWithAcceptanceAuditOwner(async () => { await interactiveControl?.start(); });
2205
+ await runWithAcceptanceAuditOwner(async () => { await approvalRelayDoor?.start(); });
2206
+ try {
2207
+ await runWithAcceptanceAuditOwner(async () => { await approvalTransport?.reconcileExpired(); });
2208
+ }
2209
+ catch (error) {
2210
+ acceptanceAuditBarrier();
2211
+ (0, runtime_1.emitNervesEvent)({
2212
+ level: "error",
2213
+ component: "senses",
2214
+ event: "senses.telegram_approval_reconcile_error",
2215
+ message: "Telegram approval expiry reconciliation failed",
2216
+ meta: { agentName: options.agentName, subject, error: transportError(error) },
2217
+ });
2218
+ }
2219
+ (0, runtime_1.emitNervesEvent)({
2220
+ component: "senses",
2221
+ event: "senses.telegram_poll_start",
2222
+ message: "Telegram long poll started",
2223
+ meta: { agentName: options.agentName, subject },
2224
+ });
2225
+ approvalReconciliationActive = true;
2226
+ nextApprovalReconcileDeadline = undefined;
2227
+ scheduleApprovalReconcile();
2228
+ const ownerRouteWatch = options.ownerRoute?.probe
2229
+ ? setInterval(() => {
2230
+ void checkOwnerRoute().catch((error) => (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.telegram_owner_route_watch_error", message: "the check of the owner's primary agent failed", meta: { agentName: options.agentName, error: transportError(error) } }));
2231
+ }, telegram_owner_route_1.OWNER_ROUTE_WATCH_INTERVAL_MS)
2232
+ : undefined;
2233
+ try {
2234
+ await poll.run(signal);
2235
+ }
2236
+ finally {
2237
+ clearInterval(ownerRouteWatch);
2238
+ approvalReconciliationActive = false;
2239
+ nextApprovalReconcileDeadline = undefined;
2240
+ clearApprovalReconcileTimer();
2241
+ await Promise.all([...approvalReconciliationsInFlight]);
2242
+ try {
2243
+ await runWithAcceptanceAuditOwner(async () => { await approvalTransport?.reconcileExpired(); });
2244
+ }
2245
+ catch (error) {
2246
+ acceptanceAuditBarrier();
2247
+ (0, runtime_1.emitNervesEvent)({
2248
+ level: "error",
2249
+ component: "senses",
2250
+ event: "senses.telegram_approval_reconcile_error",
2251
+ message: "Telegram approval expiry reconciliation failed",
2252
+ meta: { agentName: options.agentName, subject, error: transportError(error) },
2253
+ });
2254
+ }
2255
+ await interactiveControl?.stop();
2256
+ await approvalRelayDoor?.stop();
2257
+ }
2258
+ })();
2259
+ return runPromise;
2260
+ },
2261
+ async sendProactive(text, signal) {
2262
+ await runWithAcceptanceAuditOwner(async () => {
2263
+ const proactiveText = requiredText(text, "proactive message");
2264
+ // Unsolicited repetition is the one thing a household agent cannot take
2265
+ // back. External-event decisions are deliberately not guarded here:
2266
+ // dropping one could leave its event undispositioned.
2267
+ if (!proactiveRepetitionGuard.shouldSend(proactiveText)) {
2268
+ (0, runtime_1.emitNervesEvent)({
2269
+ component: "senses",
2270
+ event: "senses.telegram_proactive_repetition_suppressed",
2271
+ message: "suppressed a proactive message repeating a recent one",
2272
+ meta: { agentName: options.agentName, subject },
2273
+ });
2274
+ return;
2275
+ }
2276
+ const key = `proactive:${(0, node_crypto_1.randomUUID)()}`;
2277
+ const telegramText = await routeSelfStarted(proactiveText, key, undefined, signal);
2278
+ if (telegramText === null)
2279
+ return;
2280
+ if (holdNoticeDuringHandoff(telegramText, key))
2281
+ return;
2282
+ await releaseHeldNotices(signal);
2283
+ const effect = await deliverButlerEffect(telegramText, key, signal);
2284
+ countProactiveSend();
2285
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
2286
+ await recordAcceptedEffects(sessionPath, [effect]);
2287
+ });
2288
+ },
2289
+ async sendExternalEventDecision(input) {
2290
+ const identities = [input, ...(input.relatedEvents ?? [])].map((event) => ({
2291
+ source: requiredText(event.source, "external event source"),
2292
+ eventId: requiredText(event.eventId, "external event id"),
2293
+ generation: event.generation,
2294
+ }));
2295
+ if (identities.some(({ source, eventId, generation }) => Buffer.byteLength(source) > 512 || Buffer.byteLength(eventId) > 512
2296
+ || !Number.isSafeInteger(generation) || generation < 1))
2297
+ throw new Error("Telegram external event identity is invalid");
2298
+ const [key, ...relatedKeys] = identities.map(({ source, eventId, generation }) => `external-event:${JSON.stringify([source, eventId, generation])}`);
2299
+ return runWithAcceptanceAuditOwner(async () => {
2300
+ const text = requiredText(input.text, "external event decision");
2301
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
2302
+ const held = (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath);
2303
+ const releasedKeys = (0, telegram_handoff_1.readReleasedHeldKeys)(releasedHeldKeysPath);
2304
+ const routedKeys = (0, telegram_handoff_1.readReleasedHeldKeys)(routedKeysPath);
2305
+ const ownerMessageExists = (candidate) => held.some((notice) => notice.key === candidate)
2306
+ || releasedKeys.includes(candidate)
2307
+ || routedKeys.includes(candidate)
2308
+ || getEffectJournal().readByIdempotencyKey(candidate) !== null;
2309
+ if (ownerMessageExists(key)) {
2310
+ // A retry after the message went out (or was held): finish the original send, never send a reworded second one.
2311
+ const existing = getEffectJournal().readByIdempotencyKey(key);
2312
+ if (existing) {
2313
+ await releaseHeldNotices(input.signal);
2314
+ await recordAcceptedEffects(sessionPath, [await executeAuthorizedEffect({
2315
+ idempotencyKey: key, target: existing.target, authorClass: existing.authorClass, effect: existing.effect,
2316
+ ...(input.signal ? { signal: input.signal } : {}),
2317
+ })]);
2318
+ }
2319
+ return { status: "already_sent", effectKey: key };
2320
+ }
2321
+ const coveredBy = relatedKeys.find(ownerMessageExists);
2322
+ if (coveredBy) {
2323
+ (0, runtime_1.emitNervesEvent)({
2324
+ component: "senses",
2325
+ event: "senses.telegram_external_event_decision_covered",
2326
+ message: "settled an external-event decision under the owner message already sent for its batch",
2327
+ meta: { agentName: options.agentName, effectKey: key, coveredBy },
2328
+ });
2329
+ return { status: "covered", effectKey: coveredBy };
2330
+ }
2331
+ const critical = [key, ...relatedKeys].some(telegram_handoff_1.isCriticalNoticeKey);
2332
+ const telegramText = await routeSelfStarted(text, key, critical, input.signal);
2333
+ if (telegramText === null)
2334
+ return { status: "sent", effectKey: key };
2335
+ if (holdNoticeDuringHandoff(telegramText, key, critical))
2336
+ return { status: "sent", effectKey: key };
2337
+ await releaseHeldNotices(input.signal);
2338
+ const effect = await deliverButlerEffect(telegramText, key, input.signal);
2339
+ countProactiveSend();
2340
+ await recordAcceptedEffects(sessionPath, [effect]);
2341
+ return { status: "sent", effectKey: key };
2342
+ });
2343
+ },
2344
+ async sendAwaitFollowUp(request) {
2345
+ return runWithAcceptanceAuditOwner(() => deliverAwaitFollowUp(request));
2346
+ },
2347
+ async sendOwnerNotice(input) {
2348
+ const noticeId = requiredText(input.noticeId, "owner notice id");
2349
+ if (Buffer.byteLength(noticeId) > 512)
2350
+ throw new Error("Telegram owner notice id is invalid");
2351
+ if (noticeId.startsWith("delegated:"))
2352
+ return sendDelegatedAuditNotice({ ...input, noticeId });
2353
+ await runWithAcceptanceAuditOwner(async () => {
2354
+ const text = requiredText(input.text, "owner notice");
2355
+ const telegramText = await routeSelfStarted(text, `owner-notice:${noticeId}`, undefined, input.signal);
2356
+ if (telegramText === null)
2357
+ return;
2358
+ if (holdNoticeDuringHandoff(telegramText, `owner-notice:${noticeId}`))
2359
+ return;
2360
+ await releaseHeldNotices(input.signal);
2361
+ const effect = await deliverButlerEffect(telegramText, `owner-notice:${noticeId}`, input.signal);
2362
+ countProactiveSend();
2363
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
2364
+ await recordAcceptedEffects(sessionPath, [effect]);
2365
+ });
2366
+ },
2367
+ sendDelegatedAuditNotice,
2368
+ stop() {
2369
+ if (stopPromise)
2370
+ return stopPromise;
2371
+ stopPromise = (async () => {
2372
+ const errors = [];
2373
+ for (const operation of pendingCleanup) {
2374
+ try {
2375
+ await operation();
2376
+ pendingCleanup.delete(operation);
2377
+ }
2378
+ catch (error) {
2379
+ errors.push(error);
2380
+ }
2381
+ }
2382
+ if (errors.length === 1)
2383
+ throw errors[0];
2384
+ if (errors.length > 1)
2385
+ throw new AggregateError(errors, "Telegram sense cleanup failed");
2386
+ })().catch((error) => { stopPromise = undefined; throw error; });
2387
+ return stopPromise;
2388
+ },
2389
+ };
2390
+ }
2391
+ function loadTelegramSenseCredentials(agentName) {
2392
+ const runtime = (0, runtime_credentials_1.readRuntimeCredentialConfig)(agentName);
2393
+ if (!runtime.ok) {
2394
+ throw new Error(`Telegram runtime config is ${runtime.reason}; actor: agent-runnable; run ouro connect telegram --agent ${agentName}`);
2395
+ }
2396
+ return parseTelegramSenseCredentials(runtime.config);
2397
+ }
2398
+ async function createProductionTelegramRelationshipComposition(agentName, credentials, agentRootOverride, authorityTransport) {
2399
+ const agentRoot = agentRootOverride ?? (0, identity_1.getAgentRoot)(agentName);
2400
+ const botId = canonicalTelegramId(credentials.botId ?? telegramBotIdFromToken(credentials.botToken), "bot id");
2401
+ const ownerUserId = canonicalTelegramId(credentials.authorizedUserId, "authorized user id");
2402
+ const ownerChatId = canonicalTelegramId(credentials.authorizedChatId, "authorized chat id");
2403
+ if (ownerUserId !== ownerChatId)
2404
+ throw new Error("Telegram owner relationship requires a private user-bound chat");
2405
+ const ownerSessionKey = `telegram:${opaqueTelegramSubject((0, telegram_identity_key_1.readOrCreateTelegramIdentityKey)(agentRoot), botId, ownerUserId, ownerChatId)}`;
2406
+ const store = new friends_1.FileFriendStore(path.join(agentRoot, "friends"));
2407
+ const sameBotTelegramBindings = (friend) => friend.externalIds.filter((external) => external.provider === "telegram-user" && external.tenantId === botId);
2408
+ const exactTelegramIdentity = (friend, userId) => {
2409
+ const bindings = sameBotTelegramBindings(friend);
2410
+ return bindings.length === 1 && /^[1-9][0-9]*$/u.test(bindings[0].externalId) && bindings[0].externalId === userId;
2411
+ };
2412
+ const canonicalOwner = (friend) => Boolean(friend
2413
+ && exactTelegramIdentity(friend, ownerUserId) && friend.admissionState === "active" && friend.trustLevel === "family"
2414
+ && friend.initiativePolicy === "proactive" && friend.capabilityProfileId === "sanctuary-owner");
2415
+ const canonicalHousehold = (friend, userId) => Boolean(friend
2416
+ && exactTelegramIdentity(friend, userId) && friend.admissionState === "active" && friend.trustLevel === "friend"
2417
+ && friend.initiativePolicy === "request_follow_up_only" && friend.capabilityProfileId === "sanctuary-household");
2418
+ const owner = await store.findByExternalId("telegram-user", ownerUserId, botId);
2419
+ if (!owner || !canonicalOwner(owner)) {
2420
+ throw new Error("Telegram owner Friend must be active with the sanctuary-owner profile and exact bot identity");
2421
+ }
2422
+ const registry = (0, relationship_authorization_1.loadRelationshipCapabilityRegistry)(agentRoot);
2423
+ if (!registry.profiles["sanctuary-owner"] || !registry.profiles["sanctuary-household"]) {
2424
+ throw new Error("Telegram relationship capability registry is missing canonical profiles");
2425
+ }
2426
+ const assertLiveOwner = async (actorFriendId) => {
2427
+ const current = await store.get(owner.id);
2428
+ if (actorFriendId !== owner.id || !canonicalOwner(current))
2429
+ throw new Error("Only the live Telegram owner may manage contacts");
2430
+ };
2431
+ const admissionsRoot = path.join(agentRoot, "state", "senses", "telegram", "admissions");
2432
+ const invalidatePendingApprovals = (sessionPath) => {
2433
+ const stateRoot = path.join(agentRoot, "state", "approvals");
2434
+ const checkpoints = new approval_files_1.FileApprovalCheckpointStore(path.join(stateRoot, "checkpoints.json"));
2435
+ const tokens = new approval_files_1.FileApprovalTokenStore(path.join(stateRoot, "tokens.json"));
2436
+ const approvals = (0, approval_store_1.openApprovalStore)({ databasePath: path.join(stateRoot, "approvals.sqlite") });
2437
+ try {
2438
+ for (const checkpoint of checkpoints.list()) {
2439
+ const approval = approvals.read(checkpoint.approvalId);
2440
+ if (!approval || path.resolve(approval.sessionPath) !== path.resolve(sessionPath))
2441
+ continue;
2442
+ const decisionToken = tokens.get(checkpoint.approvalId);
2443
+ if (approval.state === "preparing")
2444
+ approvals.recoverPreparing({ approvalId: approval.approvalId, state: "abandoned_before_attempt", reason: "requesting relationship was revoked" });
2445
+ else if (approval.state === "awaiting_prompt_binding")
2446
+ approvals.abandonPromptBinding({ approvalId: approval.approvalId, reason: "requesting relationship was revoked" });
2447
+ else if (approval.state === "proposed" && decisionToken)
2448
+ approvals.decide({
2449
+ approvalId: approval.approvalId, decisionToken, decision: "deny", requesterId: approval.requesterId,
2450
+ transport: approval.transport, transportUserId: approval.transportUserId, transportChatId: approval.transportChatId,
2451
+ transportMessageId: approval.transportMessageId, sessionKey: approval.sessionKey, ownerId: `relationship-revocation-${(0, node_crypto_1.randomUUID)()}`,
2452
+ });
2453
+ else if (approval.state === "proposed")
2454
+ throw new Error(`Cannot revoke relationship while approval ${approval.approvalId} is missing its decision token`);
2455
+ else if (approval.state === "claimed" && approval.ownerId)
2456
+ approvals.abandonBeforeAttempt({ approvalId: approval.approvalId, ownerId: approval.ownerId, epoch: approval.epoch, reason: "requesting relationship was revoked" });
2457
+ else if (approval.state === "claimed")
2458
+ throw new Error(`Cannot revoke relationship while approval ${approval.approvalId} is missing its claim owner`);
2459
+ const terminal = approvals.read(checkpoint.approvalId);
2460
+ if (terminal && terminal.state !== "attempted")
2461
+ checkpoints.remove(checkpoint.approvalId);
2462
+ tokens.remove(checkpoint.approvalId);
2463
+ }
2464
+ }
2465
+ finally {
2466
+ approvals.close();
2467
+ }
2468
+ };
2469
+ const telegramContactManager = {
2470
+ list: async ({ actorFriendId }) => {
2471
+ await assertLiveOwner(actorFriendId);
2472
+ const contacts = (await store.listAll()).flatMap((friend) => {
2473
+ if (friend.id === owner.id)
2474
+ return [];
2475
+ const bindings = sameBotTelegramBindings(friend);
2476
+ if (bindings.length !== 1 || !/^[1-9][0-9]*$/u.test(bindings[0].externalId))
2477
+ return [];
2478
+ return [{ friendId: friend.id, name: friend.name, userId: bindings[0].externalId, admissionState: friend.admissionState ?? "unverified", initiativePolicy: friend.initiativePolicy ?? "none" }];
2479
+ }).slice(0, 256);
2480
+ const admissions = new telegram_admission_1.FileTelegramAdmissionStore(admissionsRoot);
2481
+ try {
2482
+ const blocked = admissions.list().filter((record) => record.status === "blocked" && record.botId === botId)
2483
+ .slice(0, 256).map((record) => ({ admissionId: record.id, userId: record.userId, displayCode: record.displayCode, status: "blocked", createdAt: new Date(record.createdAt).toISOString() }));
2484
+ return { contacts, blocked };
2485
+ }
2486
+ finally {
2487
+ admissions.close();
2488
+ }
2489
+ },
2490
+ revoke: async ({ actorFriendId, friendId }) => {
2491
+ await assertLiveOwner(actorFriendId);
2492
+ if (friendId === owner.id)
2493
+ throw new Error("The Telegram owner relationship cannot revoke itself");
2494
+ const current = await store.get(friendId);
2495
+ if (!current)
2496
+ throw new Error("Telegram contact was not found");
2497
+ const bindings = sameBotTelegramBindings(current);
2498
+ if (bindings.length !== 1 || !/^[1-9][0-9]*$/u.test(bindings[0].externalId) || bindings[0].externalId === ownerUserId)
2499
+ throw new Error("Telegram contact identity is not exact");
2500
+ const sessionKey = `telegram:${botId}:${bindings[0].externalId}`;
2501
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(agentName, current.id, "telegram", sessionKey, agentRoot);
2502
+ await (0, session_transaction_1.withSessionTurnLease)(sessionPath, async () => {
2503
+ invalidatePendingApprovals(sessionPath);
2504
+ const live = await store.get(current.id);
2505
+ if (!live || !exactTelegramIdentity(live, bindings[0].externalId))
2506
+ throw new Error("Telegram contact identity changed");
2507
+ await authorityTransport?.revokeChat({ userId: bindings[0].externalId, chatId: bindings[0].externalId });
2508
+ const { capabilityProfileId: _removedProfile, ...withoutProfile } = live;
2509
+ await store.put(live.id, { ...withoutProfile, admissionState: "revoked", initiativePolicy: "none", updatedAt: new Date().toISOString() });
2510
+ (0, tools_awaiting_1.cancelRelationshipFollowUps)(agentRoot, agentName, { friendId: live.id, channel: "telegram", key: sessionKey });
2511
+ });
2512
+ return { revoked: true, friendId };
2513
+ },
2514
+ unblock: async ({ actorFriendId, admissionId }) => {
2515
+ await assertLiveOwner(actorFriendId);
2516
+ const admissions = new telegram_admission_1.FileTelegramAdmissionStore(admissionsRoot);
2517
+ try {
2518
+ const record = admissions.read(admissionId);
2519
+ if (record.botId !== botId || record.userId !== record.chatId)
2520
+ throw new Error("Blocked Telegram contact identity changed");
2521
+ admissions.releaseBlock(admissionId);
2522
+ }
2523
+ finally {
2524
+ admissions.close();
2525
+ }
2526
+ return { unblocked: true, admissionId };
2527
+ },
2528
+ };
2529
+ const resolveEvaluator = async (input) => {
2530
+ const friend = await store.get(input.friendId);
2531
+ const ownerBound = friend?.id === owner.id;
2532
+ const coordinatesValid = ownerBound
2533
+ ? input.botId === botId && input.userId === ownerUserId && input.chatId === ownerChatId && input.sessionKey === ownerSessionKey
2534
+ : input.botId === botId && input.userId === input.chatId && input.sessionKey === `telegram:${botId}:${input.userId}`;
2535
+ if (!friend || !coordinatesValid || (ownerBound ? !canonicalOwner(friend) : !canonicalHousehold(friend, input.userId))) {
2536
+ throw new Error("Telegram relationship identity binding is not active");
2537
+ }
2538
+ return (0, relationship_authorization_1.createRelationshipAuthorizationEvaluator)({
2539
+ friend,
2540
+ registry: (0, relationship_authorization_1.loadRelationshipCapabilityRegistry)(agentRoot),
2541
+ requestId: input.requestId,
2542
+ requestPhase: "inbound",
2543
+ sessionEventId: input.sessionEventId,
2544
+ });
2545
+ };
2546
+ const admission = {
2547
+ ownerFriendId: owner.id,
2548
+ resolveOwner: async ({ botId: candidateBotId, userId, chatId, sessionKey }) => {
2549
+ if (candidateBotId !== botId || userId !== ownerUserId || chatId !== ownerChatId || sessionKey !== ownerSessionKey)
2550
+ return null;
2551
+ const exact = await store.findByExternalId("telegram-user", userId, botId);
2552
+ const current = await store.get(owner.id);
2553
+ return exact?.id === owner.id && canonicalOwner(current)
2554
+ ? { friendId: owner.id }
2555
+ : null;
2556
+ },
2557
+ resolveApprovedFriend: async ({ botId: candidateBotId, userId, chatId }) => {
2558
+ if (candidateBotId !== botId || userId !== chatId)
2559
+ return null;
2560
+ const friend = await store.findByExternalId("telegram-user", userId, botId);
2561
+ return friend && canonicalHousehold(friend, userId) ? { friendId: friend.id } : null;
2562
+ },
2563
+ claimFriend: async (input) => {
2564
+ if (input.botId !== botId || input.userId !== input.chatId)
2565
+ return { kind: "collision", reason: "Telegram identity is not bound to this bot and private chat" };
2566
+ const claimed = await store.claimExternalId({
2567
+ externalId: { provider: "telegram-user", externalId: input.userId, tenantId: botId, linkedAt: new Date().toISOString() },
2568
+ target: { kind: "create", record: { id: (0, node_crypto_1.randomUUID)(), name: "Household member" } },
2569
+ });
2570
+ const current = claimed.record;
2571
+ const now = new Date().toISOString();
2572
+ const connections = input.relationship
2573
+ ? [{ name: owner.name, relationship: input.relationship }, ...(current.connections ?? []).filter((connection) => !(connection.name === owner.name && connection.relationship === input.relationship))]
2574
+ : current.connections;
2575
+ const updated = { ...current,
2576
+ ...(connections ? { connections } : {}),
2577
+ trustLevel: input.defaults.trustLevel, admissionState: input.defaults.admissionState,
2578
+ initiativePolicy: input.defaults.initiativePolicy, capabilityProfileId: input.defaults.capabilityProfileId, updatedAt: now };
2579
+ await store.put(current.id, updated);
2580
+ return { kind: claimed.status === "created" ? "created" : "existing", friendId: current.id };
2581
+ },
2582
+ revokeFriend: async (input) => {
2583
+ if (input.botId !== botId || input.userId !== input.chatId)
2584
+ return { kind: "collision", reason: "Telegram revocation identity is invalid" };
2585
+ const current = await store.findByExternalId("telegram-user", input.userId, botId);
2586
+ if (!current || current.id !== input.friendId || !exactTelegramIdentity(current, input.userId))
2587
+ return { kind: "collision", reason: "Telegram revocation identity changed" };
2588
+ const { capabilityProfileId: _removedProfile, ...withoutProfile } = current;
2589
+ await store.put(current.id, { ...withoutProfile, admissionState: "revoked", initiativePolicy: "none", updatedAt: new Date().toISOString() });
2590
+ (0, tools_awaiting_1.cancelRelationshipFollowUps)(agentRoot, agentName, { friendId: current.id, channel: "telegram", key: `telegram:${botId}:${input.userId}` });
2591
+ return { kind: "revoked" };
2592
+ },
2593
+ };
2594
+ return {
2595
+ telegramContactManager,
2596
+ admission,
2597
+ resolveRelationshipAuthorization: resolveEvaluator,
2598
+ authorizeRelationshipEffect: async (input) => {
2599
+ if (input.target.kind !== "approved_relationship")
2600
+ return { allowed: false, reason: "relationship effect target is required" };
2601
+ const friend = await store.get(input.target.friendId);
2602
+ if (!friend)
2603
+ return { allowed: false, reason: "relationship admission is not active" };
2604
+ const bindings = sameBotTelegramBindings(friend);
2605
+ if (bindings.length !== 1 || !/^[1-9][0-9]*$/u.test(bindings[0].externalId))
2606
+ return { allowed: false, reason: "relationship Telegram identity binding is unavailable" };
2607
+ const chatId = bindings[0].externalId;
2608
+ if (friend.id === owner.id ? !canonicalOwner(friend) : !canonicalHousehold(friend, chatId))
2609
+ return { allowed: false, reason: "relationship admission is not active or canonical" };
2610
+ if (friend.id === owner.id) {
2611
+ if (chatId !== ownerUserId || chatId !== ownerChatId || input.target.sessionKey !== ownerSessionKey)
2612
+ return { allowed: false, reason: "owner Telegram identity or session binding changed" };
2613
+ }
2614
+ else if (input.target.sessionKey !== `telegram:${botId}:${chatId}`)
2615
+ return { allowed: false, reason: "relationship Telegram session binding changed" };
2616
+ const inboundIdempotency = input.target.requestId
2617
+ ? new RegExp(`^relationship-turn:${input.target.requestId.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}:delivery:[0-9]+$`, "u").test(input.idempotencyKey)
2618
+ : false;
2619
+ const durableFollowUp = friend.id !== owner.id && input.target.requestId
2620
+ ? (0, tools_awaiting_1.hasActiveRelationshipFollowUp)(agentRoot, { friendId: friend.id, channel: "telegram", key: input.target.sessionKey, requestId: input.target.requestId, allowElapsed: input.idempotencyKey.startsWith("await-expiry-follow-up:") })
2621
+ : false;
2622
+ if (friend.id !== owner.id && input.target.requestId && !inboundIdempotency && !durableFollowUp)
2623
+ return { allowed: false, reason: "relationship follow-up is not bound to an active request await" };
2624
+ const evaluator = (0, relationship_authorization_1.createRelationshipAuthorizationEvaluator)({
2625
+ friend,
2626
+ registry: (0, relationship_authorization_1.loadRelationshipCapabilityRegistry)(agentRoot),
2627
+ ...(input.target.requestId ? { requestId: input.target.requestId, requestPhase: inboundIdempotency ? "inbound" : "follow_up" } : {}),
2628
+ });
2629
+ const scope = input.target.friendId === owner.id
2630
+ ? (input.target.requestId ? "telegram.owner_event" : "telegram.proactive")
2631
+ : "telegram.request_return";
2632
+ const authorization = evaluator.authorizeEffect(scope);
2633
+ return authorization.allowed
2634
+ ? { allowed: true, receiptId: authorization.receiptId, expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(), transport: { chatId } }
2635
+ : authorization;
2636
+ },
2637
+ };
2638
+ }
2639
+ async function startTelegramSenseApp(agentName, waitForAuthority = false) {
2640
+ let authorityTransport;
2641
+ let credentials;
2642
+ if (agentName === "sanctuary") {
2643
+ const runtime = (0, runtime_credentials_1.readRuntimeCredentialConfig)(agentName);
2644
+ const machine = (0, runtime_credentials_1.readMachineRuntimeCredentialConfig)(agentName);
2645
+ if (!runtime.ok || !machine.ok)
2646
+ throw new Error("Sanctuary Telegram credential inventory is unavailable; migration readback is required");
2647
+ let waiting = false;
2648
+ for (;;) {
2649
+ try {
2650
+ ;
2651
+ ({ credentials, authorityTransport } = (0, sanctuary_authority_resident_1.openSanctuaryResidentAuthority)(runtime.config, machine.config));
2652
+ break;
2653
+ }
2654
+ catch (error) {
2655
+ if (!waitForAuthority || error?.code !== "ENOENT")
2656
+ throw error;
2657
+ if (!waiting) {
2658
+ waiting = true;
2659
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.sanctuary_gateway_waiting", message: "Telegram is unavailable while root gateway pins are not yet published", meta: { agentName } });
2660
+ }
2661
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2662
+ }
2663
+ }
2664
+ }
2665
+ else {
2666
+ const loaded = loadTelegramSenseCredentials(agentName);
2667
+ credentials = { ...loaded, botId: telegramBotIdFromToken(loaded.botToken) };
2668
+ }
2669
+ let app;
2670
+ try {
2671
+ app = createTelegramSenseApp({
2672
+ agentName,
2673
+ credentials,
2674
+ authorityTransport,
2675
+ // The owner is in Los Angeles; a container without TZ would otherwise run quiet hours on UTC.
2676
+ proactivePacing: { timeZone: process.env.TZ || "America/Los_Angeles" },
2677
+ ...(() => { const ownerRoute = (0, telegram_owner_route_1.ownerRouteForAgent)(agentName, (0, identity_1.getAgentRoot)(agentName)); return ownerRoute ? { ownerRoute } : {}; })(),
2678
+ ...(await createProductionTelegramRelationshipComposition(agentName, credentials, undefined, authorityTransport)),
2679
+ ...(agentName === "sanctuary" ? { privilegedFailsafe: {
2680
+ eventRoot: (0, router_1.getExternalEventRoot)(),
2681
+ verifyProtectiveState: createSabQueueProtectiveStateVerifier(),
2682
+ } } : {}),
2683
+ });
2684
+ }
2685
+ catch (error) {
2686
+ authorityTransport?.api.stop();
2687
+ throw error;
2688
+ }
2689
+ (0, runtime_1.emitNervesEvent)({
2690
+ component: "senses",
2691
+ event: "senses.telegram_app_ready",
2692
+ message: "Telegram sense app is ready",
2693
+ meta: { agentName },
2694
+ });
2695
+ return app;
2696
+ }
2697
+ async function sendTelegramExternalEventDecision(agentName, input) {
2698
+ const app = await startTelegramSenseApp(agentName);
2699
+ try {
2700
+ return await app.sendExternalEventDecision(input);
2701
+ }
2702
+ finally {
2703
+ await app.stop();
2704
+ }
2705
+ }
2706
+ /** Sends a delegated command's audit notice; see `sendDelegatedAuditNotice`. Throws when it can't be sent. */
2707
+ async function sendTelegramDelegatedAuditNotice(agentName, input) {
2708
+ const app = await startTelegramSenseApp(agentName);
2709
+ try {
2710
+ await app.sendDelegatedAuditNotice(input);
2711
+ }
2712
+ finally {
2713
+ await app.stop();
2714
+ }
2715
+ }
2716
+ async function sendTelegramOwnerNotice(agentName, input) {
2717
+ const app = await startTelegramSenseApp(agentName);
2718
+ try {
2719
+ await app.sendOwnerNotice(input);
2720
+ }
2721
+ finally {
2722
+ await app.stop();
2723
+ }
2724
+ }
2725
+ /**
2726
+ * Suppresses a proactive message that repeats one sent recently.
2727
+ *
2728
+ * Ari received four probe messages in about two minutes, three of them identical
2729
+ * apart from the clock reading. Only the clock is normalised away — counts and
2730
+ * every other number are the payload, so "3 of 10 episodes" and "7 of 10" stay
2731
+ * distinct and both send.
2732
+ *
2733
+ * This catches verbatim-apart-from-the-clock repetition, not semantic near
2734
+ * duplicates: a message reworded between sends still goes out.
2735
+ */
2736
+ function createProactiveRepetitionGuard(options) {
2737
+ const windowMs = options?.windowMs ?? 900_000;
2738
+ const now = options?.now ?? (() => Date.now());
2739
+ const maxEntries = options?.maxEntries ?? 32;
2740
+ const seen = new Map();
2741
+ const normalize = (text) => text
2742
+ .trim()
2743
+ .replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?/gu, "<timestamp>")
2744
+ .replace(/\b\d{1,2}:\d{2}(?::\d{2})?\b/gu, "<clock>")
2745
+ .replace(/\s+/gu, " ");
2746
+ return {
2747
+ shouldSend(text) {
2748
+ const at = now();
2749
+ for (const [key, sentAt] of [...seen]) {
2750
+ if (at - sentAt >= windowMs)
2751
+ seen.delete(key);
2752
+ }
2753
+ const key = normalize(text);
2754
+ const previous = seen.get(key);
2755
+ if (previous !== undefined && at - previous < windowMs)
2756
+ return false;
2757
+ seen.set(key, at);
2758
+ // A Map keeps insertion order and entries are inserted in send order, so
2759
+ // the earliest key is the oldest; scanning for a minimum would carry a
2760
+ // comparison branch that monotonic time can never take.
2761
+ for (const oldest of seen.keys()) {
2762
+ if (seen.size <= maxEntries)
2763
+ break;
2764
+ seen.delete(oldest);
2765
+ }
2766
+ return true;
2767
+ },
2768
+ };
2769
+ }
2770
+ /**
2771
+ * Telegram clears a typing indicator after roughly five seconds, so a turn that
2772
+ * thinks for longer has to refresh it or the chat goes silent while the Butler is
2773
+ * still working — which is what "leaving me on read" actually looked like.
2774
+ *
2775
+ * Indicator failures are swallowed on purpose: a missing typing bubble must never
2776
+ * take down the reply it was decorating.
2777
+ */
2778
+ async function withTelegramTypingIndicator(send, run, intervalMs = 4_000) {
2779
+ return (0, repeat_while_1.whileRepeating)(send, intervalMs, run);
2780
+ }
2781
+ async function sendTelegramAwaitFollowUp(agentName, request) {
2782
+ const app = await startTelegramSenseApp(agentName);
2783
+ try {
2784
+ return await app.sendAwaitFollowUp(request);
2785
+ }
2786
+ finally {
2787
+ await app.stop();
2788
+ }
2789
+ }