@ouro.bot/cli 0.1.0-alpha.66 → 0.1.0-alpha.660

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