@ouro.bot/cli 0.1.0-alpha.73 → 0.1.0-alpha.730

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