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