@ouro.bot/cli 0.1.0-alpha.50 → 0.1.0-alpha.501

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