@ouro.bot/cli 0.1.0-alpha.61 → 0.1.0-alpha.612

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 (418) hide show
  1. package/README.md +127 -23
  2. package/RepairGuide.ouro/agent.json +5 -0
  3. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  4. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  5. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  6. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  7. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  8. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  9. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  12. package/changelog.json +3912 -0
  13. package/dist/arc/attention-types.js +8 -0
  14. package/dist/arc/cares.js +144 -0
  15. package/dist/arc/episodes.js +118 -0
  16. package/dist/arc/intentions.js +134 -0
  17. package/dist/arc/json-store.js +117 -0
  18. package/dist/arc/obligations.js +266 -0
  19. package/dist/arc/packets.js +194 -0
  20. package/dist/arc/presence.js +185 -0
  21. package/dist/arc/task-lifecycle.js +65 -0
  22. package/dist/heart/active-work.js +837 -26
  23. package/dist/heart/agent-entry.js +69 -3
  24. package/dist/heart/attachments/image-normalize.js +194 -0
  25. package/dist/heart/attachments/materialize.js +97 -0
  26. package/dist/heart/attachments/originals.js +88 -0
  27. package/dist/heart/attachments/render.js +29 -0
  28. package/dist/heart/attachments/sources/adapter.js +2 -0
  29. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  30. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  31. package/dist/heart/attachments/sources/index.js +16 -0
  32. package/dist/heart/attachments/store.js +103 -0
  33. package/dist/heart/attachments/types.js +93 -0
  34. package/dist/heart/auth/auth-flow.js +479 -0
  35. package/dist/heart/awaiting/await-alert.js +146 -0
  36. package/dist/heart/awaiting/await-expiry.js +108 -0
  37. package/dist/heart/awaiting/await-loader.js +91 -0
  38. package/dist/heart/awaiting/await-parser.js +141 -0
  39. package/dist/heart/awaiting/await-runtime-state.js +100 -0
  40. package/dist/heart/awaiting/await-scheduler.js +377 -0
  41. package/dist/heart/background-operations.js +281 -0
  42. package/dist/heart/bridges/store.js +14 -2
  43. package/dist/heart/bundle-state.js +168 -0
  44. package/dist/heart/commitments.js +142 -0
  45. package/dist/heart/config-registry.js +322 -0
  46. package/dist/heart/config.js +114 -119
  47. package/dist/heart/core.js +909 -246
  48. package/dist/heart/cross-chat-delivery.js +3 -18
  49. package/dist/heart/daemon/agent-config-check.js +419 -0
  50. package/dist/heart/daemon/agent-discovery.js +102 -3
  51. package/dist/heart/daemon/agent-service.js +522 -0
  52. package/dist/heart/daemon/agentic-repair.js +547 -0
  53. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  54. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  55. package/dist/heart/daemon/cadence.js +70 -0
  56. package/dist/heart/daemon/cli-defaults.js +776 -0
  57. package/dist/heart/daemon/cli-exec.js +7579 -0
  58. package/dist/heart/daemon/cli-help.js +498 -0
  59. package/dist/heart/daemon/cli-parse.js +1599 -0
  60. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  61. package/dist/heart/daemon/cli-render.js +763 -0
  62. package/dist/heart/daemon/cli-types.js +8 -0
  63. package/dist/heart/daemon/connect-bay.js +323 -0
  64. package/dist/heart/daemon/daemon-cli.js +29 -1700
  65. package/dist/heart/daemon/daemon-entry.js +485 -2
  66. package/dist/heart/daemon/daemon-health.js +176 -0
  67. package/dist/heart/daemon/daemon-rollup.js +57 -0
  68. package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
  69. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  70. package/dist/heart/daemon/daemon.js +904 -70
  71. package/dist/heart/daemon/dns-workflow.js +394 -0
  72. package/dist/heart/daemon/doctor-types.js +8 -0
  73. package/dist/heart/daemon/doctor.js +873 -0
  74. package/dist/heart/daemon/health-monitor.js +122 -1
  75. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  76. package/dist/heart/daemon/hooks/bundle-meta.js +115 -1
  77. package/dist/heart/daemon/http-health-probe.js +80 -0
  78. package/dist/heart/daemon/human-command-screens.js +234 -0
  79. package/dist/heart/daemon/human-readiness.js +114 -0
  80. package/dist/heart/daemon/inner-status.js +89 -0
  81. package/dist/heart/daemon/interactive-repair.js +394 -0
  82. package/dist/heart/daemon/launchd.js +37 -8
  83. package/dist/heart/daemon/log-tailer.js +78 -9
  84. package/dist/heart/daemon/logs-prune.js +110 -0
  85. package/dist/heart/daemon/mcp-canary.js +297 -0
  86. package/dist/heart/daemon/os-cron-deps.js +135 -0
  87. package/dist/heart/daemon/os-cron.js +14 -12
  88. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  89. package/dist/heart/daemon/ouro-entry.js +3 -1
  90. package/dist/heart/daemon/process-manager.js +463 -34
  91. package/dist/heart/daemon/provider-discovery.js +137 -0
  92. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  93. package/dist/heart/daemon/pulse.js +475 -0
  94. package/dist/heart/daemon/readiness-repair.js +365 -0
  95. package/dist/heart/daemon/run-hooks.js +2 -0
  96. package/dist/heart/daemon/runtime-logging.js +10 -2
  97. package/dist/heart/daemon/runtime-metadata.js +2 -30
  98. package/dist/heart/daemon/safe-mode.js +161 -0
  99. package/dist/heart/daemon/sense-manager.js +493 -38
  100. package/dist/heart/daemon/session-id-resolver.js +131 -0
  101. package/dist/heart/daemon/skill-management-installer.js +28 -7
  102. package/dist/heart/daemon/socket-client.js +158 -11
  103. package/dist/heart/daemon/stale-bundle-prune.js +96 -0
  104. package/dist/heart/daemon/startup-tui.js +330 -0
  105. package/dist/heart/daemon/task-scheduler.js +3 -25
  106. package/dist/heart/daemon/terminal-ui.js +499 -0
  107. package/dist/heart/daemon/thoughts.js +229 -17
  108. package/dist/heart/daemon/up-progress.js +366 -0
  109. package/dist/heart/daemon/vault-items.js +56 -0
  110. package/dist/heart/delegation.js +1 -1
  111. package/dist/heart/habits/habit-migration.js +189 -0
  112. package/dist/heart/habits/habit-parser.js +140 -0
  113. package/dist/heart/habits/habit-runtime-state.js +100 -0
  114. package/dist/heart/habits/habit-scheduler.js +372 -0
  115. package/dist/heart/{daemon → hatch}/hatch-flow.js +32 -56
  116. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  117. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  118. package/dist/heart/{daemon → hatch}/specialist-tools.js +35 -12
  119. package/dist/heart/identity.js +166 -55
  120. package/dist/heart/kept-notes.js +357 -0
  121. package/dist/heart/kicks.js +1 -1
  122. package/dist/heart/machine-identity.js +161 -0
  123. package/dist/heart/mail-import-discovery.js +353 -0
  124. package/dist/heart/mailbox/mailbox-http-hooks.js +66 -0
  125. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  126. package/dist/heart/mailbox/mailbox-http-routes.js +246 -0
  127. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  128. package/dist/heart/mailbox/mailbox-http-transport.js +116 -0
  129. package/dist/heart/mailbox/mailbox-http.js +99 -0
  130. package/dist/heart/mailbox/mailbox-read.js +31 -0
  131. package/dist/heart/mailbox/mailbox-types.js +27 -0
  132. package/dist/heart/mailbox/mailbox-view.js +197 -0
  133. package/dist/heart/mailbox/readers/agent-machine.js +425 -0
  134. package/dist/heart/mailbox/readers/continuity-readers.js +338 -0
  135. package/dist/heart/mailbox/readers/mail.js +375 -0
  136. package/dist/heart/mailbox/readers/runtime-readers.js +756 -0
  137. package/dist/heart/mailbox/readers/sessions.js +232 -0
  138. package/dist/heart/mailbox/readers/shared.js +111 -0
  139. package/dist/heart/mcp/mcp-server.js +656 -0
  140. package/dist/heart/migrate-config.js +100 -0
  141. package/dist/heart/model-capabilities.js +19 -0
  142. package/dist/heart/platform.js +81 -0
  143. package/dist/heart/provider-attempt.js +134 -0
  144. package/dist/heart/provider-binding-resolver.js +267 -0
  145. package/dist/heart/provider-credentials.js +425 -0
  146. package/dist/heart/provider-failover.js +301 -0
  147. package/dist/heart/provider-models.js +81 -0
  148. package/dist/heart/provider-ping.js +262 -0
  149. package/dist/heart/provider-readiness-cache.js +40 -0
  150. package/dist/heart/provider-visibility.js +188 -0
  151. package/dist/heart/providers/anthropic-token.js +131 -0
  152. package/dist/heart/providers/anthropic.js +139 -52
  153. package/dist/heart/providers/azure.js +23 -11
  154. package/dist/heart/providers/error-classification.js +127 -0
  155. package/dist/heart/providers/github-copilot.js +145 -0
  156. package/dist/heart/providers/minimax-vlm.js +189 -0
  157. package/dist/heart/providers/minimax.js +26 -8
  158. package/dist/heart/providers/openai-codex.js +55 -40
  159. package/dist/heart/runtime-capability-check.js +170 -0
  160. package/dist/heart/runtime-credentials.js +367 -0
  161. package/dist/heart/runtime-cwd.js +87 -0
  162. package/dist/heart/sense-truth.js +13 -4
  163. package/dist/heart/session-activity.js +48 -24
  164. package/dist/heart/session-events.js +1156 -0
  165. package/dist/heart/session-playback-cli-main.js +5 -0
  166. package/dist/heart/session-playback-cli.js +36 -0
  167. package/dist/heart/session-playback.js +231 -0
  168. package/dist/heart/session-stats-cli-main.js +5 -0
  169. package/dist/heart/session-stats.js +182 -0
  170. package/dist/heart/session-transcript.js +133 -0
  171. package/dist/heart/start-of-turn-packet.js +345 -0
  172. package/dist/heart/streaming.js +44 -27
  173. package/dist/heart/sync-classification.js +176 -0
  174. package/dist/heart/sync.js +449 -0
  175. package/dist/heart/target-resolution.js +9 -5
  176. package/dist/heart/tempo.js +93 -0
  177. package/dist/heart/temporal-view.js +41 -0
  178. package/dist/heart/timeouts.js +101 -0
  179. package/dist/heart/tool-activity-callbacks.js +59 -0
  180. package/dist/heart/tool-description.js +143 -0
  181. package/dist/heart/tool-friction.js +55 -0
  182. package/dist/heart/tool-loop.js +200 -0
  183. package/dist/heart/turn-context.js +421 -0
  184. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  185. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  186. package/dist/heart/versioning/ouro-path-installer.js +426 -0
  187. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  188. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  189. package/dist/heart/{daemon → versioning}/update-checker.js +6 -1
  190. package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
  191. package/dist/mailbox-ui/assets/index-9-AxCxuB.js +61 -0
  192. package/dist/mailbox-ui/assets/index-CWzt267f.css +1 -0
  193. package/dist/mailbox-ui/index.html +15 -0
  194. package/dist/mailroom/attention.js +167 -0
  195. package/dist/mailroom/autonomy.js +209 -0
  196. package/dist/mailroom/blob-store.js +712 -0
  197. package/dist/mailroom/body-cache.js +61 -0
  198. package/dist/mailroom/core.js +788 -0
  199. package/dist/mailroom/entry.js +160 -0
  200. package/dist/mailroom/file-store.js +460 -0
  201. package/dist/mailroom/mbox-import.js +393 -0
  202. package/dist/mailroom/migration.js +164 -0
  203. package/dist/mailroom/outbound.js +380 -0
  204. package/dist/mailroom/policy.js +263 -0
  205. package/dist/mailroom/reader.js +233 -0
  206. package/dist/mailroom/search-cache.js +268 -0
  207. package/dist/mailroom/search-relevance.js +319 -0
  208. package/dist/mailroom/smtp-ingress.js +176 -0
  209. package/dist/mailroom/source-state.js +176 -0
  210. package/dist/mailroom/thread.js +109 -0
  211. package/dist/mailroom/travel-extract.js +89 -0
  212. package/dist/mind/bundle-manifest.js +7 -1
  213. package/dist/mind/context.js +250 -101
  214. package/dist/mind/diary-integrity.js +60 -0
  215. package/dist/mind/{memory.js → diary.js} +68 -76
  216. package/dist/mind/embedding-provider.js +60 -0
  217. package/dist/mind/file-state.js +179 -0
  218. package/dist/mind/friends/channel.js +39 -0
  219. package/dist/mind/friends/resolver.js +54 -2
  220. package/dist/mind/friends/store-file.js +48 -4
  221. package/dist/mind/friends/types.js +2 -2
  222. package/dist/mind/journal-index.js +162 -0
  223. package/dist/mind/note-search.js +268 -0
  224. package/dist/mind/obligation-steering.js +221 -0
  225. package/dist/mind/pending.js +6 -1
  226. package/dist/mind/prompt-refresh.js +3 -2
  227. package/dist/mind/prompt.js +1051 -135
  228. package/dist/mind/provenance-trust.js +26 -0
  229. package/dist/mind/scrutiny.js +173 -0
  230. package/dist/nerves/cli-logging.js +7 -1
  231. package/dist/nerves/coverage/audit-rules.js +15 -6
  232. package/dist/nerves/coverage/audit.js +28 -2
  233. package/dist/nerves/coverage/cli.js +1 -1
  234. package/dist/nerves/coverage/contract.js +5 -5
  235. package/dist/nerves/coverage/file-completeness.js +129 -5
  236. package/dist/nerves/event-buffer.js +111 -0
  237. package/dist/nerves/index.js +224 -4
  238. package/dist/nerves/observation.js +20 -0
  239. package/dist/nerves/redact.js +79 -0
  240. package/dist/nerves/review/cli-main.js +5 -0
  241. package/dist/nerves/review/cli.js +156 -0
  242. package/dist/nerves/review/core.js +152 -0
  243. package/dist/nerves/runtime.js +5 -1
  244. package/dist/repertoire/ado-client.js +15 -56
  245. package/dist/repertoire/ado-semantic.js +11 -10
  246. package/dist/repertoire/api-client.js +97 -0
  247. package/dist/repertoire/bitwarden-store.js +997 -0
  248. package/dist/repertoire/bundle-templates.js +72 -0
  249. package/dist/repertoire/bw-installer.js +180 -0
  250. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  251. package/dist/repertoire/coding/context-pack.js +331 -0
  252. package/dist/repertoire/coding/feedback.js +197 -30
  253. package/dist/repertoire/coding/manager.js +163 -10
  254. package/dist/repertoire/coding/spawner.js +55 -9
  255. package/dist/repertoire/coding/tools.js +170 -7
  256. package/dist/repertoire/commerce-errors.js +109 -0
  257. package/dist/repertoire/commerce-self-test.js +156 -0
  258. package/dist/repertoire/credential-access.js +178 -0
  259. package/dist/repertoire/duffel-client.js +185 -0
  260. package/dist/repertoire/github-client.js +14 -55
  261. package/dist/repertoire/graph-client.js +11 -52
  262. package/dist/repertoire/guardrails.js +396 -0
  263. package/dist/repertoire/mcp-client.js +295 -0
  264. package/dist/repertoire/mcp-manager.js +362 -0
  265. package/dist/repertoire/mcp-tools.js +63 -0
  266. package/dist/repertoire/shell-sessions.js +133 -0
  267. package/dist/repertoire/skills.js +18 -4
  268. package/dist/repertoire/stripe-client.js +131 -0
  269. package/dist/repertoire/tasks/board.js +31 -5
  270. package/dist/repertoire/tasks/fix.js +182 -0
  271. package/dist/repertoire/tasks/index.js +16 -4
  272. package/dist/repertoire/tasks/lifecycle.js +2 -2
  273. package/dist/repertoire/tasks/parser.js +3 -2
  274. package/dist/repertoire/tasks/scanner.js +194 -37
  275. package/dist/repertoire/tasks/transitions.js +16 -78
  276. package/dist/repertoire/tool-results.js +29 -0
  277. package/dist/repertoire/tools-attachments.js +317 -0
  278. package/dist/repertoire/tools-awaiting.js +365 -0
  279. package/dist/repertoire/tools-base.js +55 -1082
  280. package/dist/repertoire/tools-bluebubbles.js +1 -0
  281. package/dist/repertoire/tools-bridge.js +141 -0
  282. package/dist/repertoire/tools-bundle.js +984 -0
  283. package/dist/repertoire/tools-config.js +185 -0
  284. package/dist/repertoire/tools-continuity.js +248 -0
  285. package/dist/repertoire/tools-credential.js +381 -0
  286. package/dist/repertoire/tools-files.js +342 -0
  287. package/dist/repertoire/tools-flight.js +224 -0
  288. package/dist/repertoire/tools-flow.js +119 -0
  289. package/dist/repertoire/tools-github.js +1 -7
  290. package/dist/repertoire/tools-mail.js +1916 -0
  291. package/dist/repertoire/tools-notes.js +421 -0
  292. package/dist/repertoire/tools-obligations.js +142 -0
  293. package/dist/repertoire/tools-record.js +463 -0
  294. package/dist/repertoire/tools-runtime.js +148 -0
  295. package/dist/repertoire/tools-session.js +781 -0
  296. package/dist/repertoire/tools-shell.js +120 -0
  297. package/dist/repertoire/tools-stripe.js +180 -0
  298. package/dist/repertoire/tools-surface.js +345 -0
  299. package/dist/repertoire/tools-teams.js +9 -39
  300. package/dist/repertoire/tools-travel.js +125 -0
  301. package/dist/repertoire/tools-trip.js +604 -0
  302. package/dist/repertoire/tools-user-profile.js +144 -0
  303. package/dist/repertoire/tools-vault.js +40 -0
  304. package/dist/repertoire/tools-voice.js +144 -0
  305. package/dist/repertoire/tools.js +115 -103
  306. package/dist/repertoire/travel-api-client.js +360 -0
  307. package/dist/repertoire/user-profile.js +131 -0
  308. package/dist/repertoire/vault-setup.js +246 -0
  309. package/dist/repertoire/vault-unlock.js +594 -0
  310. package/dist/scripts/claude-code-hook.js +41 -0
  311. package/dist/scripts/claude-code-stop-hook.js +47 -0
  312. package/dist/senses/attention-queue.js +116 -0
  313. package/dist/senses/await-turn-message.js +58 -0
  314. package/dist/senses/bluebubbles/active-turns.js +216 -0
  315. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  316. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  317. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +219 -18
  318. package/dist/senses/bluebubbles/entry.js +77 -0
  319. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +20 -3
  320. package/dist/senses/bluebubbles/index.js +2613 -0
  321. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -71
  322. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +33 -12
  323. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +3 -3
  324. package/dist/senses/bluebubbles/processed-log.js +133 -0
  325. package/dist/senses/bluebubbles/replay.js +137 -0
  326. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  327. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  328. package/dist/senses/bluebubbles-meta-guard.js +40 -0
  329. package/dist/senses/cli/bracketed-paste.js +82 -0
  330. package/dist/senses/cli/image-paste.js +287 -0
  331. package/dist/senses/cli/image-ref-navigation.js +75 -0
  332. package/dist/senses/cli/ink-app.js +156 -0
  333. package/dist/senses/cli/inline-diff.js +64 -0
  334. package/dist/senses/cli/input-keys.js +174 -0
  335. package/dist/senses/cli/kill-ring.js +86 -0
  336. package/dist/senses/cli/message-list.js +51 -0
  337. package/dist/senses/cli/ouro-tui.js +607 -0
  338. package/dist/senses/cli/spinner-imperative.js +135 -0
  339. package/dist/senses/cli/spinner.js +101 -0
  340. package/dist/senses/cli/status-line.js +60 -0
  341. package/dist/senses/cli/streaming-markdown.js +526 -0
  342. package/dist/senses/cli/tool-display.js +85 -0
  343. package/dist/senses/cli/tool-render.js +85 -0
  344. package/dist/senses/cli/tui-store.js +240 -0
  345. package/dist/senses/cli/virtual-list.js +35 -0
  346. package/dist/senses/cli-entry.js +60 -8
  347. package/dist/senses/cli-layout.js +100 -0
  348. package/dist/senses/cli.js +516 -204
  349. package/dist/senses/commands.js +66 -3
  350. package/dist/senses/habit-turn-message.js +108 -0
  351. package/dist/senses/inner-dialog-worker.js +185 -21
  352. package/dist/senses/inner-dialog.js +469 -39
  353. package/dist/senses/mail-entry.js +66 -0
  354. package/dist/senses/mail.js +379 -0
  355. package/dist/senses/pipeline.js +654 -181
  356. package/dist/senses/proactive-content-guard.js +51 -0
  357. package/dist/senses/shared-turn.js +392 -0
  358. package/dist/senses/surface-tool.js +70 -0
  359. package/dist/senses/teams-entry.js +60 -8
  360. package/dist/senses/teams.js +387 -98
  361. package/dist/senses/trust-gate.js +100 -5
  362. package/dist/senses/voice/audio-playback.js +237 -0
  363. package/dist/senses/voice/audio-routing.js +119 -0
  364. package/dist/senses/voice/elevenlabs.js +202 -0
  365. package/dist/senses/voice/floor-control.js +431 -0
  366. package/dist/senses/voice/floor-controller.js +115 -0
  367. package/dist/senses/voice/golden-path.js +116 -0
  368. package/dist/senses/voice/index.js +29 -0
  369. package/dist/senses/voice/meeting.js +113 -0
  370. package/dist/senses/voice/outbound.js +190 -0
  371. package/dist/senses/voice/phone.js +33 -0
  372. package/dist/senses/voice/playback.js +139 -0
  373. package/dist/senses/voice/realtime-eval.js +496 -0
  374. package/dist/senses/voice/realtime-trace.js +531 -0
  375. package/dist/senses/voice/transcript.js +70 -0
  376. package/dist/senses/voice/turn.js +191 -0
  377. package/dist/senses/voice/twilio-phone-runtime.js +807 -0
  378. package/dist/senses/voice/twilio-phone.js +5079 -0
  379. package/dist/senses/voice/types.js +2 -0
  380. package/dist/senses/voice/whisper.js +161 -0
  381. package/dist/senses/voice-entry.js +81 -0
  382. package/dist/senses/voice-realtime-eval-command.js +99 -0
  383. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  384. package/dist/senses/voice-twilio-entry.js +87 -0
  385. package/dist/trips/core.js +138 -0
  386. package/dist/trips/store.js +265 -0
  387. package/package.json +41 -7
  388. package/skills/agent-commerce.md +106 -0
  389. package/skills/browser-navigation.md +117 -0
  390. package/skills/commerce-setup-guide.md +116 -0
  391. package/skills/commerce-setup.md +84 -0
  392. package/skills/configure-dev-tools.md +99 -0
  393. package/skills/travel-planning.md +138 -0
  394. package/dist/heart/daemon/auth-flow.js +0 -351
  395. package/dist/heart/daemon/ouro-path-installer.js +0 -178
  396. package/dist/heart/safe-workspace.js +0 -228
  397. package/dist/heart/session-recall.js +0 -116
  398. package/dist/mind/associative-recall.js +0 -209
  399. package/dist/senses/bluebubbles-entry.js +0 -13
  400. package/dist/senses/bluebubbles.js +0 -1177
  401. package/dist/senses/debug-activity.js +0 -148
  402. package/subagents/README.md +0 -7
  403. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  404. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  405. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  406. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  407. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  408. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  409. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  410. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  411. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  412. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  413. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  414. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  415. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  416. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  417. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  418. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -0,0 +1,1156 @@
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.EVENT_CONTENT_MAX_CHARS = void 0;
37
+ exports.truncateLargeEventContent = truncateLargeEventContent;
38
+ exports.capStructuredRecordString = capStructuredRecordString;
39
+ exports.capStructuredRecordStringArray = capStructuredRecordStringArray;
40
+ exports.capStructuredRecordStringLeaves = capStructuredRecordStringLeaves;
41
+ exports.normalizeContinuityState = normalizeContinuityState;
42
+ exports.validateSessionMessages = validateSessionMessages;
43
+ exports.detectDuplicateToolCallIds = detectDuplicateToolCallIds;
44
+ exports.repairSessionMessages = repairSessionMessages;
45
+ exports.migrateToolNames = migrateToolNames;
46
+ exports.sanitizeProviderMessages = sanitizeProviderMessages;
47
+ exports.stampIngressTime = stampIngressTime;
48
+ exports.getIngressTime = getIngressTime;
49
+ exports.projectProviderMessages = projectProviderMessages;
50
+ exports.annotateMessageTimestamps = annotateMessageTimestamps;
51
+ exports.bestEventTimestamp = bestEventTimestamp;
52
+ exports.formatSessionEventTimestamp = formatSessionEventTimestamp;
53
+ exports.extractEventText = extractEventText;
54
+ exports.deriveSessionChronology = deriveSessionChronology;
55
+ exports.describeCurrentSessionTiming = describeCurrentSessionTiming;
56
+ exports.migrateLegacySessionEnvelope = migrateLegacySessionEnvelope;
57
+ exports.parseSessionEnvelope = parseSessionEnvelope;
58
+ exports.loadSessionEnvelopeFile = loadSessionEnvelopeFile;
59
+ exports.buildCanonicalSessionEnvelope = buildCanonicalSessionEnvelope;
60
+ exports.appendEvictedToArchive = appendEvictedToArchive;
61
+ exports.appendSyntheticAssistantEvent = appendSyntheticAssistantEvent;
62
+ const fs = __importStar(require("fs"));
63
+ const runtime_1 = require("../nerves/runtime");
64
+ let archiveDisabledEmitted = false;
65
+ exports.EVENT_CONTENT_MAX_CHARS = 256 * 1024;
66
+ function truncateLargeEventContent(content, maxChars) {
67
+ if (typeof content !== "string") {
68
+ return { content, truncated: false, originalLength: 0 };
69
+ }
70
+ if (content.length <= maxChars) {
71
+ return { content, truncated: false, originalLength: content.length };
72
+ }
73
+ const marker = `[truncated — event content exceeded ${maxChars} chars; original length ${content.length} chars]`;
74
+ const remainingBudget = Math.max(0, maxChars - marker.length);
75
+ const headLength = Math.ceil(remainingBudget * 0.75);
76
+ const tailLength = Math.max(0, remainingBudget - headLength);
77
+ return {
78
+ content: `${content.slice(0, headLength)}${marker}${tailLength > 0 ? content.slice(-tailLength) : ""}`,
79
+ truncated: true,
80
+ originalLength: content.length,
81
+ };
82
+ }
83
+ function capStructuredRecordString(value) {
84
+ return truncateLargeEventContent(value, exports.EVENT_CONTENT_MAX_CHARS).content;
85
+ }
86
+ function capStructuredRecordStringArray(values) {
87
+ return values.map((value) => capStructuredRecordString(value));
88
+ }
89
+ function capStructuredRecordStringLeaves(value) {
90
+ if (typeof value === "string") {
91
+ return capStructuredRecordString(value);
92
+ }
93
+ if (Array.isArray(value)) {
94
+ return value.map((item) => capStructuredRecordStringLeaves(item));
95
+ }
96
+ if (!value || typeof value !== "object") {
97
+ return value;
98
+ }
99
+ const capped = {};
100
+ for (const [key, child] of Object.entries(value)) {
101
+ capped[key] = capStructuredRecordStringLeaves(child);
102
+ }
103
+ return capped;
104
+ }
105
+ function formatElapsed(ms) {
106
+ const minutes = Math.max(0, Math.floor(ms / 60000));
107
+ if (minutes < 60)
108
+ return `${minutes}m ago`;
109
+ const hours = Math.floor(minutes / 60);
110
+ if (hours < 24)
111
+ return `${hours}h ago`;
112
+ const days = Math.floor(hours / 24);
113
+ return `${days}d ago`;
114
+ }
115
+ const LEGACY_WRITTEN_NOTE_PREFIX = "mem" + "ory";
116
+ const TOOL_NAME_MIGRATIONS = {
117
+ final_answer: "settle",
118
+ no_response: "observe",
119
+ go_inward: "ponder",
120
+ descend: "ponder",
121
+ [`${LEGACY_WRITTEN_NOTE_PREFIX}_save`]: "diary_write",
122
+ [`${LEGACY_WRITTEN_NOTE_PREFIX}_search`]: "search_notes",
123
+ };
124
+ function normalizeUsage(usage) {
125
+ if (!usage || typeof usage !== "object")
126
+ return null;
127
+ const record = usage;
128
+ if (typeof record.input_tokens !== "number"
129
+ || typeof record.output_tokens !== "number"
130
+ || typeof record.reasoning_tokens !== "number"
131
+ || typeof record.total_tokens !== "number") {
132
+ return null;
133
+ }
134
+ return {
135
+ input_tokens: record.input_tokens,
136
+ output_tokens: record.output_tokens,
137
+ reasoning_tokens: record.reasoning_tokens,
138
+ total_tokens: record.total_tokens,
139
+ };
140
+ }
141
+ function normalizeContinuityState(state) {
142
+ const record = state && typeof state === "object"
143
+ ? state
144
+ : null;
145
+ return {
146
+ mustResolveBeforeHandoff: record?.mustResolveBeforeHandoff === true,
147
+ lastFriendActivityAt: typeof record?.lastFriendActivityAt === "string" ? record.lastFriendActivityAt : null,
148
+ };
149
+ }
150
+ function normalizeContent(content) {
151
+ if (content == null)
152
+ return null;
153
+ if (typeof content === "string")
154
+ return content;
155
+ if (!Array.isArray(content))
156
+ return null;
157
+ return content
158
+ .filter((part) => part != null && typeof part === "object")
159
+ .map((part) => ({ ...part }));
160
+ }
161
+ const SYNTHETIC_TIMESTAMP_PREFIX_RE = /^(?:(?:\[(?:just now|-\d+[mhd])\])\s*)+/i;
162
+ function stripSyntheticTimestampPrefix(text) {
163
+ return text.replace(SYNTHETIC_TIMESTAMP_PREFIX_RE, "");
164
+ }
165
+ function sanitizeConversationContent(role, content) {
166
+ if (role !== "user" && role !== "assistant")
167
+ return content;
168
+ if (typeof content === "string")
169
+ return stripSyntheticTimestampPrefix(content);
170
+ if (!Array.isArray(content))
171
+ return content;
172
+ return content.map((part) => {
173
+ if (part.type === "text" && typeof part.text === "string") {
174
+ return { ...part, text: stripSyntheticTimestampPrefix(part.text) };
175
+ }
176
+ return part;
177
+ });
178
+ }
179
+ function normalizeToolCalls(rawToolCalls) {
180
+ if (!Array.isArray(rawToolCalls))
181
+ return [];
182
+ return rawToolCalls
183
+ .filter((call) => call != null && typeof call === "object")
184
+ .map((call) => {
185
+ const fn = call.function;
186
+ const originalName = typeof fn?.name === "string" ? fn.name : "unknown";
187
+ const migratedName = TOOL_NAME_MIGRATIONS[originalName] ?? originalName;
188
+ return {
189
+ id: typeof call.id === "string" ? call.id : "",
190
+ type: typeof call.type === "string" ? call.type : "function",
191
+ function: {
192
+ name: migratedName,
193
+ arguments: typeof fn?.arguments === "string" ? fn.arguments : JSON.stringify(fn?.arguments ?? ""),
194
+ },
195
+ };
196
+ });
197
+ }
198
+ function normalizeRole(role) {
199
+ if (role === "developer")
200
+ return "system";
201
+ return role === "system" || role === "user" || role === "assistant" || role === "tool"
202
+ ? role
203
+ : "user";
204
+ }
205
+ function normalizeMessage(message) {
206
+ const record = message;
207
+ const role = normalizeRole(record.role);
208
+ const normalizedContent = sanitizeConversationContent(role, normalizeContent(record.content));
209
+ if (role === "assistant") {
210
+ return {
211
+ role,
212
+ content: normalizedContent,
213
+ name: typeof record.name === "string" ? record.name : null,
214
+ toolCallId: null,
215
+ toolCalls: normalizeToolCalls(record.tool_calls),
216
+ hadToolCallsField: Array.isArray(record.tool_calls),
217
+ };
218
+ }
219
+ if (role === "tool") {
220
+ return {
221
+ role,
222
+ content: typeof record.content === "string" ? record.content : "",
223
+ name: null,
224
+ toolCallId: typeof record.tool_call_id === "string" ? record.tool_call_id : null,
225
+ toolCalls: [],
226
+ hadToolCallsField: false,
227
+ };
228
+ }
229
+ return {
230
+ role,
231
+ content: normalizedContent ?? "",
232
+ name: typeof record.name === "string" ? record.name : null,
233
+ toolCallId: null,
234
+ toolCalls: [],
235
+ hadToolCallsField: false,
236
+ };
237
+ }
238
+ function contentText(content) {
239
+ if (typeof content === "string")
240
+ return content;
241
+ if (!Array.isArray(content))
242
+ return "";
243
+ return content
244
+ .map((part) => (part.type === "text" && typeof part.text === "string"
245
+ ? part.text
246
+ : ""))
247
+ .filter((text) => text.length > 0)
248
+ .join("");
249
+ }
250
+ function toProviderMessage(message) {
251
+ if (message.role === "assistant") {
252
+ const assistant = {
253
+ role: "assistant",
254
+ content: message.content,
255
+ };
256
+ if (message.name)
257
+ assistant.name = message.name;
258
+ if (message.hadToolCallsField || message.toolCalls.length > 0) {
259
+ assistant.tool_calls = message.toolCalls.map((call) => ({
260
+ id: call.id,
261
+ type: call.type,
262
+ function: {
263
+ name: call.function.name,
264
+ arguments: call.function.arguments,
265
+ },
266
+ }));
267
+ }
268
+ return assistant;
269
+ }
270
+ if (message.role === "tool") {
271
+ return {
272
+ role: "tool",
273
+ content: typeof message.content === "string" ? message.content : contentText(message.content),
274
+ tool_call_id: message.toolCallId ?? "",
275
+ };
276
+ }
277
+ if (message.role === "system") {
278
+ return {
279
+ role: "system",
280
+ content: typeof message.content === "string" ? message.content : contentText(message.content),
281
+ ...(message.name ? { name: message.name } : {}),
282
+ };
283
+ }
284
+ return {
285
+ role: "user",
286
+ content: (typeof message.content === "string" || Array.isArray(message.content) ? message.content : ""),
287
+ ...(message.name ? { name: message.name } : {}),
288
+ };
289
+ }
290
+ function messageFingerprint(message) {
291
+ const normalized = normalizeMessage(message);
292
+ return JSON.stringify({
293
+ role: normalized.role,
294
+ content: normalized.content,
295
+ name: normalized.name,
296
+ tool_call_id: normalized.toolCallId,
297
+ tool_calls: normalized.toolCalls,
298
+ });
299
+ }
300
+ function makeEventId(sequence) {
301
+ return `evt-${String(sequence).padStart(6, "0")}`;
302
+ }
303
+ /**
304
+ * Collapse duplicate event ids to a single entry, last-occurrence-wins.
305
+ *
306
+ * Concurrent writers in older versions of postTurnPersist could each load the
307
+ * envelope, compute `events.length + 1` for the next sequence, and both write
308
+ * an event with the same id. The duplicates would persist in the saved JSON
309
+ * and confuse downstream replay (the same outbound message could appear to
310
+ * have been sent twice from the agent's perspective without the agent knowing
311
+ * it sent it). We dedupe defensively on every load so corrupted sessions
312
+ * self-heal on the next save and so any future race produces a consistent
313
+ * view.
314
+ */
315
+ function dedupeEventsByIdLastWins(events) {
316
+ // Index id → last position so we can preserve original order while
317
+ // collapsing duplicates to their final occurrence.
318
+ const lastIndexById = new Map();
319
+ for (let i = 0; i < events.length; i++) {
320
+ lastIndexById.set(events[i].id, i);
321
+ }
322
+ return events.filter((event, index) => lastIndexById.get(event.id) === index);
323
+ }
324
+ /**
325
+ * The next sequence to assign for a freshly-built event. Uses max(existing
326
+ * sequences) + 1 rather than `events.length + 1` so that gaps from earlier
327
+ * pruning, archive replay, or self-heal dedup never produce a colliding id.
328
+ */
329
+ function nextEventSequence(existing) {
330
+ return existing.reduce((max, event) => Math.max(max, event.sequence), 0) + 1;
331
+ }
332
+ function validateSessionMessages(messages) {
333
+ const violations = [];
334
+ let prevNonToolRole = null;
335
+ let prevAssistantHadToolCalls = false;
336
+ let sawToolResultSincePrevAssistant = false;
337
+ for (let i = 0; i < messages.length; i++) {
338
+ const msg = normalizeMessage(messages[i]);
339
+ if (msg.role === "system")
340
+ continue;
341
+ if (msg.role === "tool") {
342
+ sawToolResultSincePrevAssistant = true;
343
+ continue;
344
+ }
345
+ if (msg.role === "assistant" && prevNonToolRole === "assistant") {
346
+ if (!(prevAssistantHadToolCalls && sawToolResultSincePrevAssistant)) {
347
+ violations.push(`back-to-back assistant at index ${i}`);
348
+ }
349
+ }
350
+ prevAssistantHadToolCalls = msg.role === "assistant" && msg.toolCalls.length > 0;
351
+ sawToolResultSincePrevAssistant = false;
352
+ prevNonToolRole = msg.role;
353
+ }
354
+ for (const collision of detectDuplicateToolCallIds(messages)) {
355
+ violations.push(`duplicate tool_call_id '${collision.id}' across assistant messages at indices ${collision.indices.join(", ")} — provider may reject (MiniMax canonicalizes call_function_<hash>_<n> across turns)`);
356
+ }
357
+ return violations;
358
+ }
359
+ /**
360
+ * Detect tool_call_ids that appear in more than one assistant message
361
+ * within the conversation. MiniMax-M2.7 in particular emits canonical
362
+ * ids of the form `call_function_<hash>_<n>` and reuses the same id
363
+ * across turns when the same function is called — which causes provider
364
+ * rejections on replay because tool_call_id is supposed to be unique
365
+ * per request. We don't (yet) rewrite these here; this function exists
366
+ * so the sanitize pipeline can surface the collision through nerves
367
+ * (`mind.session_invariant_violation`) and operators can decide.
368
+ *
369
+ * Same-message duplicates (one assistant calling the same id twice)
370
+ * are not collisions — they're a legitimate parallel call shape and
371
+ * would be handled by the assistant's own emit logic. We only flag
372
+ * cross-message reuse.
373
+ */
374
+ function detectDuplicateToolCallIds(messages) {
375
+ const idsByFirstIndex = new Map();
376
+ for (let i = 0; i < messages.length; i++) {
377
+ const msg = normalizeMessage(messages[i]);
378
+ if (msg.role !== "assistant")
379
+ continue;
380
+ const seenInThisMessage = new Set();
381
+ for (const call of msg.toolCalls) {
382
+ if (!call.id || seenInThisMessage.has(call.id))
383
+ continue;
384
+ seenInThisMessage.add(call.id);
385
+ const indices = idsByFirstIndex.get(call.id) ?? [];
386
+ indices.push(i);
387
+ idsByFirstIndex.set(call.id, indices);
388
+ }
389
+ }
390
+ const collisions = [];
391
+ for (const [id, indices] of idsByFirstIndex) {
392
+ if (indices.length > 1)
393
+ collisions.push({ id, indices });
394
+ }
395
+ return collisions;
396
+ }
397
+ function repairSessionMessages(messages) {
398
+ const normalized = messages.map(normalizeMessage);
399
+ const violations = validateSessionMessages(messages);
400
+ if (violations.length === 0)
401
+ return normalized.map(toProviderMessage);
402
+ const result = [];
403
+ let duplicateAssistantsDropped = 0;
404
+ for (const msg of normalized) {
405
+ if (msg.role === "assistant" && result.length > 0) {
406
+ const prev = result[result.length - 1];
407
+ if (prev.role === "assistant" && prev.toolCalls.length === 0) {
408
+ const prevContent = contentText(prev.content);
409
+ const curContent = contentText(msg.content);
410
+ // Drop the second of two consecutive assistants when the content is
411
+ // byte-identical (after trim) — that's a retry/double-persist artifact,
412
+ // not legitimate continuation. Concatenating them produced visible
413
+ // duplicate text in surfaces. Empty strings still concatenate (could
414
+ // be "" + real content).
415
+ if (prevContent.trim().length > 0 && prevContent.trim() === curContent.trim() && msg.toolCalls.length === 0) {
416
+ duplicateAssistantsDropped += 1;
417
+ continue;
418
+ }
419
+ prev.content = `${prevContent}\n\n${curContent}`;
420
+ continue;
421
+ }
422
+ }
423
+ result.push(msg);
424
+ }
425
+ if (duplicateAssistantsDropped > 0) {
426
+ (0, runtime_1.emitNervesEvent)({
427
+ level: "info",
428
+ event: "mind.session_duplicate_assistant_dropped",
429
+ component: "mind",
430
+ message: "dropped consecutive assistant messages with identical content (retry/double-persist artifact)",
431
+ meta: { count: duplicateAssistantsDropped },
432
+ });
433
+ }
434
+ (0, runtime_1.emitNervesEvent)({
435
+ level: "info",
436
+ event: "mind.session_invariant_repair",
437
+ component: "mind",
438
+ message: "repaired session invariant violations",
439
+ meta: { violations },
440
+ });
441
+ return result.map(toProviderMessage);
442
+ }
443
+ function repairToolCallSequences(messages, inlineReasoningStrippedCallIds = new Set()) {
444
+ const normalized = messages.map(normalizeMessage);
445
+ // Position-aware orphan detection. A tool result is orphaned if there is
446
+ // no preceding assistant message in the array whose tool_calls contain the
447
+ // matching id. (The previous logic checked all assistant messages
448
+ // globally, which kept tool results that appeared BEFORE their matching
449
+ // assistant — invalid order — and triggered MiniMax error 2013 on replay.)
450
+ let removed = 0;
451
+ const seenCallIds = new Set();
452
+ const repaired = normalized.filter((msg) => {
453
+ if (msg.role === "assistant") {
454
+ for (const tc of msg.toolCalls)
455
+ seenCallIds.add(tc.id);
456
+ return true;
457
+ }
458
+ if (msg.role !== "tool")
459
+ return true;
460
+ const keep = msg.toolCallId !== null && seenCallIds.has(msg.toolCallId);
461
+ if (!keep)
462
+ removed++;
463
+ return keep;
464
+ });
465
+ if (removed > 0) {
466
+ (0, runtime_1.emitNervesEvent)({
467
+ level: "info",
468
+ event: "mind.session_orphan_tool_result_repair",
469
+ component: "mind",
470
+ message: "removed orphaned tool results from session history",
471
+ meta: { removed },
472
+ });
473
+ }
474
+ let injected = 0;
475
+ for (let i = 0; i < repaired.length; i++) {
476
+ const msg = repaired[i];
477
+ if (msg.role !== "assistant" || msg.toolCalls.length === 0)
478
+ continue;
479
+ const resultIds = new Set();
480
+ for (let j = i + 1; j < repaired.length; j++) {
481
+ const following = repaired[j];
482
+ if (following.role === "tool" && following.toolCallId !== null) {
483
+ resultIds.add(following.toolCallId);
484
+ continue;
485
+ }
486
+ if (following.role === "assistant" || following.role === "user")
487
+ break;
488
+ }
489
+ const missing = msg.toolCalls.filter((toolCall) => !resultIds.has(toolCall.id));
490
+ if (missing.length === 0)
491
+ continue;
492
+ const syntheticResults = missing.map((toolCall) => ({
493
+ role: "tool",
494
+ content: buildSyntheticToolResultMessage(toolCall.id, inlineReasoningStrippedCallIds),
495
+ name: null,
496
+ toolCallId: toolCall.id,
497
+ toolCalls: [],
498
+ hadToolCallsField: false,
499
+ }));
500
+ let insertAt = i + 1;
501
+ while (insertAt < repaired.length && repaired[insertAt].role === "tool")
502
+ insertAt++;
503
+ repaired.splice(insertAt, 0, ...syntheticResults);
504
+ injected += syntheticResults.length;
505
+ }
506
+ if (injected > 0) {
507
+ (0, runtime_1.emitNervesEvent)({
508
+ level: "info",
509
+ event: "mind.session_orphan_tool_call_repair",
510
+ component: "mind",
511
+ message: "injected synthetic tool results for orphaned tool calls",
512
+ meta: { injected },
513
+ });
514
+ }
515
+ return repaired.map(toProviderMessage);
516
+ }
517
+ function canonicalizeSystemMessageSequence(messages) {
518
+ const normalized = messages.map(normalizeMessage);
519
+ const firstSystemIndex = normalized.findIndex((msg) => msg.role === "system");
520
+ if (firstSystemIndex === -1)
521
+ return normalized.map(toProviderMessage);
522
+ const extraSystemCount = normalized.filter((msg) => msg.role === "system").length - 1;
523
+ if (firstSystemIndex === 0 && extraSystemCount === 0) {
524
+ return normalized.map(toProviderMessage);
525
+ }
526
+ const primarySystem = normalized[firstSystemIndex];
527
+ const nonSystemMessages = normalized.filter((msg) => msg.role !== "system");
528
+ const repaired = [primarySystem, ...nonSystemMessages].map(toProviderMessage);
529
+ (0, runtime_1.emitNervesEvent)({
530
+ level: "info",
531
+ event: "mind.session_system_prompt_repair",
532
+ component: "mind",
533
+ message: "canonicalized session system prompt sequence",
534
+ meta: {
535
+ firstSystemIndex,
536
+ extraSystemCount,
537
+ finalMessageCount: repaired.length,
538
+ },
539
+ });
540
+ return repaired;
541
+ }
542
+ function migrateToolNames(messages) {
543
+ const safeMessages = messages.filter((message) => Boolean(message) && typeof message === "object");
544
+ let migrated = 0;
545
+ for (const message of safeMessages) {
546
+ const record = message;
547
+ if (record.role !== "assistant" || !Array.isArray(record.tool_calls))
548
+ continue;
549
+ for (const toolCall of record.tool_calls) {
550
+ if (!toolCall || typeof toolCall !== "object")
551
+ continue;
552
+ const toolRecord = toolCall;
553
+ if (toolRecord.type !== "function")
554
+ continue;
555
+ const originalName = toolRecord.function?.name;
556
+ if (typeof originalName !== "string")
557
+ continue;
558
+ if (TOOL_NAME_MIGRATIONS[originalName])
559
+ migrated += 1;
560
+ }
561
+ }
562
+ if (migrated > 0) {
563
+ (0, runtime_1.emitNervesEvent)({
564
+ level: "info",
565
+ event: "mind.session_tool_name_migration",
566
+ component: "mind",
567
+ message: "migrated deprecated tool names in session history",
568
+ meta: { migrated },
569
+ });
570
+ }
571
+ return safeMessages.map(normalizeMessage).map(toProviderMessage);
572
+ }
573
+ /**
574
+ * Strip inline `<think>...</think>` blocks from a string. Mirrors the
575
+ * helper at senses/shared-turn.ts (operator-facing) and core.ts
576
+ * (live-turn) — kept inline here because session-events.ts is the load-
577
+ * time repair path and needs its own copy to avoid sense/heart import
578
+ * cycles. If the close tag is missing, drops everything from the open
579
+ * tag onward.
580
+ */
581
+ function stripInlineThinkBlocks(input) {
582
+ let out = input;
583
+ for (;;) {
584
+ const open = out.indexOf("<think>");
585
+ if (open === -1)
586
+ break;
587
+ const close = out.indexOf("</think>", open + "<think>".length);
588
+ if (close === -1) {
589
+ out = out.slice(0, open);
590
+ break;
591
+ }
592
+ out = out.slice(0, open) + out.slice(close + "</think>".length);
593
+ }
594
+ return out.trim();
595
+ }
596
+ /**
597
+ * Strip inline `<think>` content from any assistant message that ALSO has
598
+ * tool_calls. MiniMax-style models persist think-content + tool_calls on
599
+ * the same assistant turn; replaying that combination triggers MiniMax
600
+ * error 2013 ("tool result's tool id not found") and stalls the session.
601
+ *
602
+ * AX requirement: the agent MUST see that this happened. We don't silently
603
+ * paper over their previous turn — we strip for replay correctness AND
604
+ * collect the affected tool_call_ids in `inlineReasoningStrippedCallIds`
605
+ * so the downstream synthetic-tool-result repair can produce an
606
+ * explanatory message addressed to those specific calls. The agent sees:
607
+ * "your previous tool call's result was lost because the assistant message
608
+ * had inline reasoning blocks the provider couldn't replay — here's what
609
+ * happened, retry if needed." Full awareness, no silent corrections.
610
+ *
611
+ * This load-time repair self-heals existing sessions that were saved
612
+ * before the persist-time strip in core.ts landed.
613
+ */
614
+ function repairInlineReasoningOnReplay(messages, inlineReasoningStrippedCallIds) {
615
+ let repaired = 0;
616
+ const result = messages.map((msg) => {
617
+ if (msg.role !== "assistant")
618
+ return msg;
619
+ const a = msg;
620
+ if (!a.tool_calls || a.tool_calls.length === 0)
621
+ return msg;
622
+ if (typeof a.content !== "string")
623
+ return msg;
624
+ if (!a.content.includes("<think>"))
625
+ return msg;
626
+ const stripped = stripInlineThinkBlocks(a.content);
627
+ repaired++;
628
+ for (const tc of a.tool_calls)
629
+ inlineReasoningStrippedCallIds.add(tc.id);
630
+ return { ...a, content: stripped.length > 0 ? stripped : null };
631
+ });
632
+ if (repaired > 0) {
633
+ (0, runtime_1.emitNervesEvent)({
634
+ level: "info",
635
+ event: "mind.session_inline_reasoning_repair",
636
+ component: "mind",
637
+ message: "stripped inline <think> blocks from assistant messages with tool_calls so replay is valid; agent will see explanatory tool-result messages",
638
+ meta: { repaired, affectedCallIds: inlineReasoningStrippedCallIds.size },
639
+ });
640
+ }
641
+ return result;
642
+ }
643
+ /**
644
+ * Compose the synthetic tool-result message the agent sees when their
645
+ * previous turn's tool call has no matching tool result. The default
646
+ * message tells the agent what happened (turn ended early, result lost)
647
+ * and what to do (retry if the work isn't done). When the parent
648
+ * assistant message had inline `<think>` reasoning that the provider
649
+ * rejected, the message is more specific so the agent can adjust.
650
+ *
651
+ * AX rule: every repair must produce a message the agent can read and
652
+ * act on. Silent strips are never OK.
653
+ */
654
+ function buildSyntheticToolResultMessage(toolCallId, inlineReasoningStrippedCallIds) {
655
+ if (inlineReasoningStrippedCallIds.has(toolCallId)) {
656
+ return [
657
+ "error: this tool call's result was lost.",
658
+ "your previous assistant turn included inline `<think>...</think>` reasoning alongside tool_calls,",
659
+ "and the provider (likely MiniMax) rejects that combination on replay (error 2013).",
660
+ "the harness has stripped the inline reasoning from the persisted content so the next replay is valid;",
661
+ "your reasoning trace itself is preserved out-of-band and not lost.",
662
+ "if the underlying work still needs to be done, retry the tool call now —",
663
+ "the call may not have run, or it ran but the result didn't reach you.",
664
+ ].join(" ");
665
+ }
666
+ return [
667
+ "error: this tool call's result was lost — the previous turn ended before the tool finished",
668
+ "(provider rejection, daemon interrupt, or the tool itself errored).",
669
+ "if the work needs to be done, retry the tool call now.",
670
+ ].join(" ");
671
+ }
672
+ function sanitizeProviderMessages(messages) {
673
+ const safeMessages = messages.filter((message) => Boolean(message) && typeof message === "object");
674
+ const normalized = safeMessages.map(normalizeMessage);
675
+ const violations = validateSessionMessages(safeMessages);
676
+ if (violations.length > 0) {
677
+ (0, runtime_1.emitNervesEvent)({
678
+ level: "info",
679
+ event: "mind.session_invariant_violation",
680
+ component: "mind",
681
+ message: "session invariant violated",
682
+ meta: { violations },
683
+ });
684
+ }
685
+ // Track which tool_call_ids belonged to assistant messages whose inline
686
+ // reasoning we just stripped. The synthetic-tool-result repair downstream
687
+ // uses this set to produce an explanatory message for those calls so the
688
+ // agent has full awareness of what happened.
689
+ const inlineReasoningStrippedCallIds = new Set();
690
+ return canonicalizeSystemMessageSequence(migrateToolNames(repairToolCallSequences(repairInlineReasoningOnReplay(repairSessionMessages(normalized.map(toProviderMessage)), inlineReasoningStrippedCallIds), inlineReasoningStrippedCallIds)));
691
+ }
692
+ function stampIngressTime(msg) {
693
+ msg._ingressAt = new Date().toISOString();
694
+ }
695
+ function getIngressTime(msg) {
696
+ const value = msg._ingressAt;
697
+ return typeof value === "string" ? value : null;
698
+ }
699
+ function createEventTime(role, recordedAt, captureKind, ingressAt) {
700
+ if (captureKind === "migration") {
701
+ return {
702
+ authoredAt: null,
703
+ authoredAtSource: "migration",
704
+ observedAt: null,
705
+ observedAtSource: "migration",
706
+ recordedAt,
707
+ recordedAtSource: "migration",
708
+ };
709
+ }
710
+ if (role === "user") {
711
+ return {
712
+ authoredAt: null,
713
+ authoredAtSource: "unknown",
714
+ observedAt: ingressAt ?? recordedAt,
715
+ observedAtSource: "ingest",
716
+ recordedAt,
717
+ recordedAtSource: "save",
718
+ };
719
+ }
720
+ return {
721
+ authoredAt: recordedAt,
722
+ authoredAtSource: "local",
723
+ observedAt: recordedAt,
724
+ observedAtSource: "local",
725
+ recordedAt,
726
+ recordedAtSource: "save",
727
+ };
728
+ }
729
+ function buildEventFromMessage(message, sequence, recordedAt, captureKind, sourceMessageIndex, legacyVersion, ingressAt) {
730
+ const normalized = normalizeMessage(message);
731
+ const role = normalized.role;
732
+ const cappedContent = truncateLargeEventContent(normalized.content, exports.EVENT_CONTENT_MAX_CHARS).content;
733
+ return {
734
+ id: makeEventId(sequence),
735
+ sequence,
736
+ role,
737
+ content: cappedContent,
738
+ name: normalized.name,
739
+ toolCallId: role === "tool" ? normalized.toolCallId : null,
740
+ toolCalls: role === "assistant" ? normalized.toolCalls : [],
741
+ attachments: [],
742
+ time: createEventTime(role, recordedAt, captureKind, ingressAt),
743
+ relations: {
744
+ replyToEventId: null,
745
+ threadRootEventId: null,
746
+ references: [],
747
+ toolCallId: role === "tool" ? normalized.toolCallId : null,
748
+ supersedesEventId: null,
749
+ redactsEventId: null,
750
+ },
751
+ provenance: {
752
+ captureKind,
753
+ legacyVersion,
754
+ sourceMessageIndex,
755
+ },
756
+ };
757
+ }
758
+ function projectProviderMessages(envelope) {
759
+ const eventIds = envelope.projection.eventIds.length > 0
760
+ ? envelope.projection.eventIds
761
+ : envelope.events.map((event) => event.id);
762
+ const byId = new Map(envelope.events.map((event) => [event.id, event]));
763
+ return eventIds
764
+ .map((id) => byId.get(id))
765
+ .filter((event) => Boolean(event))
766
+ .map((event) => toProviderMessage({
767
+ role: event.role,
768
+ content: event.content,
769
+ name: event.name,
770
+ toolCallId: event.toolCallId,
771
+ toolCalls: event.toolCalls,
772
+ hadToolCallsField: event.toolCalls.length > 0,
773
+ }));
774
+ }
775
+ /**
776
+ * Annotate user and assistant messages with a relative time offset tag.
777
+ * System and tool messages are untouched.
778
+ */
779
+ function annotateMessageTimestamps(envelope, messages, nowMs = Date.now()) {
780
+ const eventIds = envelope.projection.eventIds.length > 0
781
+ ? envelope.projection.eventIds
782
+ : envelope.events.map((event) => event.id);
783
+ const byId = new Map(envelope.events.map((event) => [event.id, event]));
784
+ const events = eventIds
785
+ .map((id) => byId.get(id))
786
+ .filter((event) => Boolean(event));
787
+ return messages.map((msg, i) => {
788
+ const event = events[i];
789
+ if (!event)
790
+ return msg;
791
+ if (event.role !== "user" && event.role !== "assistant")
792
+ return msg;
793
+ const ts = bestEventTimestamp(event);
794
+ const elapsed = nowMs - Date.parse(ts);
795
+ if (elapsed < 0)
796
+ return msg;
797
+ const tag = elapsed < 60000 ? "[just now]" : `[-${formatElapsedCompact(elapsed)}]`;
798
+ if (typeof msg.content === "string" && msg.content.length > 0) {
799
+ return { ...msg, content: `${tag} ${msg.content}` };
800
+ }
801
+ return msg;
802
+ });
803
+ }
804
+ /** Compact elapsed format for message annotations: "3m", "2h", "1d". */
805
+ function formatElapsedCompact(ms) {
806
+ const minutes = Math.max(1, Math.floor(ms / 60000));
807
+ if (minutes < 60)
808
+ return `${minutes}m`;
809
+ const hours = Math.floor(minutes / 60);
810
+ if (hours < 24)
811
+ return `${hours}h`;
812
+ const days = Math.floor(hours / 24);
813
+ return `${days}d`;
814
+ }
815
+ function bestEventTimestamp(event) {
816
+ return event.time.authoredAt ?? event.time.observedAt ?? event.time.recordedAt;
817
+ }
818
+ function formatSessionEventTimestamp(event) {
819
+ const iso = bestEventTimestamp(event);
820
+ const date = new Date(iso);
821
+ const year = date.getUTCFullYear();
822
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
823
+ const day = String(date.getUTCDate()).padStart(2, "0");
824
+ const hour = String(date.getUTCHours()).padStart(2, "0");
825
+ const minute = String(date.getUTCMinutes()).padStart(2, "0");
826
+ return `${year}-${month}-${day} ${hour}:${minute}`;
827
+ }
828
+ function extractEventText(event) {
829
+ return contentText(event.content);
830
+ }
831
+ function deriveSessionChronology(events) {
832
+ let lastInboundAt = null;
833
+ let lastOutboundAt = null;
834
+ let lastActivityAt = null;
835
+ let lastAssistantSequence = -1;
836
+ for (const event of events) {
837
+ if (event.role === "system")
838
+ continue;
839
+ const at = bestEventTimestamp(event);
840
+ lastActivityAt = at;
841
+ if (event.role === "user") {
842
+ lastInboundAt = at;
843
+ }
844
+ if (event.role === "assistant") {
845
+ lastOutboundAt = at;
846
+ lastAssistantSequence = event.sequence;
847
+ }
848
+ }
849
+ const unansweredInboundCount = events.filter((event) => event.role === "user" && event.sequence > lastAssistantSequence).length;
850
+ return {
851
+ lastInboundAt,
852
+ lastOutboundAt,
853
+ lastActivityAt,
854
+ unansweredInboundCount,
855
+ };
856
+ }
857
+ function describeCurrentSessionTiming(events, nowMs = Date.now()) {
858
+ const chronology = deriveSessionChronology(events);
859
+ const parts = [];
860
+ if (chronology.lastInboundAt) {
861
+ parts.push(`last inbound ${formatElapsed(nowMs - Date.parse(chronology.lastInboundAt))}`);
862
+ }
863
+ if (chronology.lastOutboundAt) {
864
+ parts.push(`i last replied ${formatElapsed(nowMs - Date.parse(chronology.lastOutboundAt))}`);
865
+ }
866
+ if (chronology.unansweredInboundCount > 0) {
867
+ const count = chronology.unansweredInboundCount;
868
+ parts.push(`${count} unanswered inbound message${count === 1 ? "" : "s"}`);
869
+ }
870
+ return parts.length > 0 ? `current thread: ${parts.join("; ")}` : "";
871
+ }
872
+ function migrateLegacySessionEnvelope(raw, options) {
873
+ if (!raw || typeof raw !== "object")
874
+ return null;
875
+ const legacy = raw;
876
+ const looksLegacy = legacy.version === 1
877
+ || (legacy.version == null && ("messages" in legacy || "lastUsage" in legacy || "state" in legacy));
878
+ if (!looksLegacy)
879
+ return null;
880
+ const messages = Array.isArray(legacy.messages)
881
+ ? sanitizeProviderMessages(legacy.messages)
882
+ : [];
883
+ const recordedAt = options.fileMtimeAt ?? options.recordedAt;
884
+ const events = messages.map((message, index) => buildEventFromMessage(message, index + 1, recordedAt, "migration", index, 1));
885
+ return {
886
+ version: 2,
887
+ events,
888
+ projection: {
889
+ eventIds: events.map((event) => event.id),
890
+ trimmed: false,
891
+ maxTokens: null,
892
+ contextMargin: null,
893
+ inputTokens: null,
894
+ projectedAt: recordedAt,
895
+ },
896
+ lastUsage: normalizeUsage(legacy.lastUsage),
897
+ state: normalizeContinuityState(legacy.state),
898
+ };
899
+ }
900
+ function parseSessionEnvelope(raw, options = {}) {
901
+ const recordedAt = options.recordedAt ?? new Date().toISOString();
902
+ const fileMtimeAt = options.fileMtimeAt ?? null;
903
+ const migrated = migrateLegacySessionEnvelope(raw, { recordedAt, fileMtimeAt });
904
+ if (migrated)
905
+ return migrated;
906
+ if (!raw || typeof raw !== "object")
907
+ return null;
908
+ const record = raw;
909
+ if (record.version !== 2 || !Array.isArray(record.events) || !record.projection || typeof record.projection !== "object") {
910
+ return null;
911
+ }
912
+ const rawEvents = record.events
913
+ .filter((event) => event != null && typeof event === "object")
914
+ .map((event, index) => {
915
+ const role = normalizeRole(event.role);
916
+ const time = event.time;
917
+ const relations = event.relations;
918
+ const provenance = event.provenance;
919
+ const content = sanitizeConversationContent(role, normalizeContent(event.content));
920
+ return {
921
+ id: typeof event.id === "string" ? event.id : makeEventId(index + 1),
922
+ sequence: typeof event.sequence === "number" ? event.sequence : index + 1,
923
+ role,
924
+ content,
925
+ name: typeof event.name === "string" ? event.name : null,
926
+ toolCallId: typeof event.toolCallId === "string" ? event.toolCallId : null,
927
+ toolCalls: normalizeToolCalls(event.toolCalls),
928
+ attachments: Array.isArray(event.attachments) ? event.attachments.filter((item) => typeof item === "string") : [],
929
+ time: {
930
+ authoredAt: typeof time?.authoredAt === "string" ? time.authoredAt : null,
931
+ authoredAtSource: typeof time?.authoredAtSource === "string" ? time.authoredAtSource : "unknown",
932
+ observedAt: typeof time?.observedAt === "string" ? time.observedAt : null,
933
+ observedAtSource: typeof time?.observedAtSource === "string" ? time.observedAtSource : "unknown",
934
+ recordedAt: typeof time?.recordedAt === "string" ? time.recordedAt : recordedAt,
935
+ recordedAtSource: typeof time?.recordedAtSource === "string" ? time.recordedAtSource : "save",
936
+ },
937
+ relations: {
938
+ replyToEventId: typeof relations?.replyToEventId === "string" ? relations.replyToEventId : null,
939
+ threadRootEventId: typeof relations?.threadRootEventId === "string" ? relations.threadRootEventId : null,
940
+ references: Array.isArray(relations?.references) ? relations.references.filter((item) => typeof item === "string") : [],
941
+ toolCallId: typeof relations?.toolCallId === "string" ? relations.toolCallId : null,
942
+ supersedesEventId: typeof relations?.supersedesEventId === "string" ? relations.supersedesEventId : null,
943
+ redactsEventId: typeof relations?.redactsEventId === "string" ? relations.redactsEventId : null,
944
+ },
945
+ provenance: {
946
+ captureKind: typeof provenance?.captureKind === "string" ? provenance.captureKind : "live",
947
+ legacyVersion: typeof provenance?.legacyVersion === "number" ? provenance.legacyVersion : null,
948
+ sourceMessageIndex: typeof provenance?.sourceMessageIndex === "number" ? provenance.sourceMessageIndex : null,
949
+ },
950
+ };
951
+ });
952
+ // Self-heal duplicate event ids that may have been written by concurrent
953
+ // writers in older harness versions. Last-occurrence-wins by id (later
954
+ // entries in the persisted file are the more recent state for that id).
955
+ // We preserve the original document order otherwise, so projection.eventIds
956
+ // still resolves predictably.
957
+ const events = dedupeEventsByIdLastWins(rawEvents);
958
+ const projection = record.projection;
959
+ return {
960
+ version: 2,
961
+ events,
962
+ projection: {
963
+ eventIds: Array.isArray(projection.eventIds) ? projection.eventIds.filter((item) => typeof item === "string") : [],
964
+ trimmed: projection.trimmed === true,
965
+ maxTokens: typeof projection.maxTokens === "number" ? projection.maxTokens : null,
966
+ contextMargin: typeof projection.contextMargin === "number" ? projection.contextMargin : null,
967
+ inputTokens: typeof projection.inputTokens === "number" ? projection.inputTokens : null,
968
+ projectedAt: typeof projection.projectedAt === "string" ? projection.projectedAt : null,
969
+ },
970
+ lastUsage: normalizeUsage(record.lastUsage),
971
+ state: normalizeContinuityState(record.state),
972
+ };
973
+ }
974
+ function loadSessionEnvelopeFile(filePath) {
975
+ try {
976
+ const raw = fs.readFileSync(filePath, "utf-8");
977
+ let mtime;
978
+ try {
979
+ mtime = fs.statSync(filePath).mtime.toISOString();
980
+ }
981
+ catch {
982
+ mtime = new Date().toISOString();
983
+ }
984
+ return parseSessionEnvelope(JSON.parse(raw), {
985
+ recordedAt: mtime,
986
+ fileMtimeAt: mtime,
987
+ });
988
+ }
989
+ catch {
990
+ return null;
991
+ }
992
+ }
993
+ function messageRole(msg) {
994
+ return normalizeRole(msg.role);
995
+ }
996
+ function filterNonSystem(messages) {
997
+ return messages.filter((msg) => messageRole(msg) !== "system");
998
+ }
999
+ /**
1000
+ * Compare two message arrays by their non-system messages only.
1001
+ * Returns the number of matching non-system messages from the start.
1002
+ * System messages (whose content changes every turn due to live world-state)
1003
+ * are excluded so that prefix matching is not defeated by system prompt updates.
1004
+ */
1005
+ function findCommonPrefixLength(a, b) {
1006
+ const aNonSys = filterNonSystem(a);
1007
+ const bNonSys = filterNonSystem(b);
1008
+ const max = Math.min(aNonSys.length, bNonSys.length);
1009
+ for (let i = 0; i < max; i++) {
1010
+ if (messageFingerprint(aNonSys[i]) !== messageFingerprint(bNonSys[i]))
1011
+ return i;
1012
+ }
1013
+ return max;
1014
+ }
1015
+ function selectProjectedEventIds(currentMessages, currentEventIds, trimmedMessages) {
1016
+ if (trimmedMessages.length === 0)
1017
+ return [];
1018
+ const result = [];
1019
+ let needle = 0;
1020
+ let trimmedFingerprint = null;
1021
+ for (let i = 0; i < currentMessages.length && needle < trimmedMessages.length; i++) {
1022
+ const currentMessage = currentMessages[i];
1023
+ const trimmedMessage = trimmedMessages[needle];
1024
+ if (currentMessage !== trimmedMessage) {
1025
+ trimmedFingerprint ??= messageFingerprint(trimmedMessage);
1026
+ if (messageFingerprint(currentMessage) !== trimmedFingerprint)
1027
+ continue;
1028
+ }
1029
+ result.push(currentEventIds[i]);
1030
+ needle++;
1031
+ trimmedFingerprint = null;
1032
+ }
1033
+ return result;
1034
+ }
1035
+ function buildCanonicalSessionEnvelope(options) {
1036
+ const existing = options.existing;
1037
+ // Callers pass pre-sanitized messages + pre-captured ingress times.
1038
+ const currentIngressTimes = options.currentIngressTimes ?? options.currentMessages.map(getIngressTime);
1039
+ const previousMessages = options.previousMessages;
1040
+ const currentMessages = options.currentMessages;
1041
+ const trimmedMessages = options.trimmedMessages;
1042
+ const previousProjectionIds = existing?.projection.eventIds.length
1043
+ ? [...existing.projection.eventIds]
1044
+ : existing?.events.map((event) => event.id) ?? [];
1045
+ // Compare only non-system messages to find the common prefix.
1046
+ // System messages change every turn (live world-state in system prompt)
1047
+ // and must not defeat prefix matching of the actual conversation.
1048
+ const nonSystemPrefix = findCommonPrefixLength(previousMessages, currentMessages);
1049
+ // Build a lookup of non-system previous projection IDs.
1050
+ const prevNonSystemIds = [];
1051
+ for (let i = 0; i < previousMessages.length; i++) {
1052
+ if (messageRole(previousMessages[i]) !== "system") {
1053
+ prevNonSystemIds.push(previousProjectionIds[i]);
1054
+ }
1055
+ }
1056
+ // Walk currentMessages and build currentEventIds + new events.
1057
+ // Non-system messages within the prefix reuse old event IDs.
1058
+ // System messages and post-prefix messages get new events.
1059
+ const events = [...(existing?.events ?? [])];
1060
+ const currentEventIds = [];
1061
+ let nonSystemSeen = 0;
1062
+ for (let i = 0; i < currentMessages.length; i++) {
1063
+ const role = messageRole(currentMessages[i]);
1064
+ const isSystem = role === "system";
1065
+ const inPrefix = !isSystem && nonSystemSeen < nonSystemPrefix;
1066
+ if (inPrefix) {
1067
+ // Reuse existing event ID for this matched non-system message
1068
+ currentEventIds.push(prevNonSystemIds[nonSystemSeen]);
1069
+ nonSystemSeen++;
1070
+ }
1071
+ else if (isSystem && i < previousMessages.length
1072
+ && messageRole(previousMessages[i]) === "system"
1073
+ && messageFingerprint(currentMessages[i]) === messageFingerprint(previousMessages[i])) {
1074
+ // System message at same position with identical content -- reuse event ID
1075
+ currentEventIds.push(previousProjectionIds[i]);
1076
+ }
1077
+ else {
1078
+ if (!isSystem)
1079
+ nonSystemSeen++;
1080
+ // Create a new event. Use nextEventSequence(events) instead of
1081
+ // `events.length + 1` so that any gap (from pruning, archive replay,
1082
+ // or self-heal dedup) cannot collide with an existing id.
1083
+ const event = buildEventFromMessage(currentMessages[i], nextEventSequence(events), options.recordedAt, "live", null, null, currentIngressTimes[i]);
1084
+ events.push(event);
1085
+ currentEventIds.push(event.id);
1086
+ }
1087
+ }
1088
+ const projectionEventIds = selectProjectedEventIds(currentMessages, currentEventIds, trimmedMessages);
1089
+ // Prune events: only keep events whose IDs are in the projection.
1090
+ // Events not in projection are returned as evicted for archiving.
1091
+ const projectionIdSet = new Set(projectionEventIds);
1092
+ const prunedEvents = events.filter((event) => projectionIdSet.has(event.id));
1093
+ const evictedEvents = events.filter((event) => !projectionIdSet.has(event.id));
1094
+ return {
1095
+ envelope: {
1096
+ version: 2,
1097
+ events: prunedEvents,
1098
+ projection: {
1099
+ eventIds: projectionEventIds,
1100
+ trimmed: projectionEventIds.length < currentEventIds.length,
1101
+ maxTokens: options.projectionBasis.maxTokens,
1102
+ contextMargin: options.projectionBasis.contextMargin,
1103
+ inputTokens: options.projectionBasis.inputTokens,
1104
+ projectedAt: options.recordedAt,
1105
+ },
1106
+ lastUsage: normalizeUsage(options.lastUsage),
1107
+ state: normalizeContinuityState(options.state),
1108
+ },
1109
+ evictedEvents,
1110
+ };
1111
+ }
1112
+ function agentFromSessionPath(sessPath) {
1113
+ const match = sessPath.match(/(?:^|[/\\])AgentBundles[/\\]([^/\\]+)\.ouro(?:[/\\]|$)/);
1114
+ return match?.[1] ?? "unknown";
1115
+ }
1116
+ /**
1117
+ * Archive writes are intentionally disabled. The session envelope remains the
1118
+ * bounded working-memory record; evicted events are no longer persisted to an
1119
+ * unbounded sidecar.
1120
+ */
1121
+ function appendEvictedToArchive(sessPath, evictedEvents) {
1122
+ if (evictedEvents.length === 0)
1123
+ return;
1124
+ if (!archiveDisabledEmitted) {
1125
+ archiveDisabledEmitted = true;
1126
+ (0, runtime_1.emitNervesEvent)({
1127
+ component: "heart",
1128
+ event: "heart.session_archive_disabled",
1129
+ message: "session archive append disabled",
1130
+ meta: {
1131
+ type: "session_archive_disabled",
1132
+ agent: agentFromSessionPath(sessPath),
1133
+ sessionPath: sessPath,
1134
+ evictedCount: evictedEvents.length,
1135
+ ts: new Date().toISOString(),
1136
+ },
1137
+ });
1138
+ }
1139
+ }
1140
+ function appendSyntheticAssistantEvent(envelope, content, recordedAt) {
1141
+ // Use nextEventSequence(events) instead of `events.length + 1` so any gap
1142
+ // (from pruning, archive replay, or self-heal dedup) cannot collide with
1143
+ // an existing event id. Same fix pattern as line 1046.
1144
+ const sequence = nextEventSequence(envelope.events);
1145
+ const event = buildEventFromMessage({ role: "assistant", content }, sequence, recordedAt, "synthetic", null, null);
1146
+ return {
1147
+ ...envelope,
1148
+ events: [...envelope.events, event],
1149
+ projection: {
1150
+ ...envelope.projection,
1151
+ eventIds: [...envelope.projection.eventIds, event.id],
1152
+ projectedAt: recordedAt,
1153
+ trimmed: false,
1154
+ },
1155
+ };
1156
+ }