@ouro.bot/cli 0.1.0-alpha.48 → 0.1.0-alpha.481
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 +132 -19
- package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -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 +3069 -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 +857 -0
- 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 +426 -0
- package/dist/heart/background-operations.js +234 -0
- package/dist/heart/bridges/manager.js +358 -0
- package/dist/heart/bridges/state-machine.js +135 -0
- package/dist/heart/bridges/store.js +123 -0
- package/dist/heart/bundle-state.js +168 -0
- package/dist/heart/commitments.js +111 -0
- package/dist/heart/config-registry.js +304 -0
- package/dist/heart/config.js +110 -128
- package/dist/heart/core.js +745 -227
- package/dist/heart/cross-chat-delivery.js +131 -0
- package/dist/heart/daemon/agent-config-check.js +490 -0
- package/dist/heart/daemon/agent-discovery.js +79 -3
- package/dist/heart/daemon/agent-service.js +360 -0
- package/dist/heart/daemon/agentic-repair.js +216 -0
- package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
- package/dist/heart/daemon/cadence.js +70 -0
- package/dist/heart/daemon/cli-defaults.js +640 -0
- package/dist/heart/daemon/cli-exec.js +6933 -0
- package/dist/heart/daemon/cli-help.js +487 -0
- package/dist/heart/daemon/cli-parse.js +1527 -0
- package/dist/heart/daemon/cli-render-doctor.js +57 -0
- package/dist/heart/daemon/cli-render.js +561 -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 -1616
- package/dist/heart/daemon/daemon-entry.js +345 -3
- package/dist/heart/daemon/daemon-health.js +141 -0
- package/dist/heart/daemon/daemon-runtime-sync.js +190 -12
- package/dist/heart/daemon/daemon-tombstone.js +236 -0
- package/dist/heart/daemon/daemon.js +677 -58
- package/dist/heart/daemon/dns-workflow.js +394 -0
- package/dist/heart/daemon/doctor-types.js +8 -0
- package/dist/heart/daemon/doctor.js +486 -0
- package/dist/heart/daemon/health-monitor.js +92 -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 +25 -5
- package/dist/heart/daemon/log-tailer.js +82 -12
- package/dist/heart/daemon/logs-prune.js +110 -0
- package/dist/heart/daemon/message-router.js +2 -2
- package/dist/heart/daemon/os-cron-deps.js +134 -0
- 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 +214 -0
- 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 +73 -0
- package/dist/heart/daemon/runtime-mode.js +67 -0
- package/dist/heart/daemon/safe-mode.js +161 -0
- package/dist/heart/daemon/sense-manager.js +178 -37
- 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 +109 -4
- package/dist/heart/daemon/stale-bundle-prune.js +96 -0
- package/dist/heart/daemon/startup-tui.js +264 -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 +149 -10
- package/dist/heart/daemon/up-progress.js +366 -0
- package/dist/heart/daemon/vault-items.js +56 -0
- package/dist/heart/delegation.js +62 -0
- 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 +52 -117
- package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
- 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 +201 -66
- 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/mcp/mcp-server.js +653 -0
- package/dist/heart/migrate-config.js +100 -0
- package/dist/heart/model-capabilities.js +59 -0
- package/dist/heart/outlook/outlook-http-hooks.js +66 -0
- package/dist/heart/outlook/outlook-http-response.js +7 -0
- package/dist/heart/outlook/outlook-http-routes.js +244 -0
- package/dist/heart/outlook/outlook-http-static.js +99 -0
- package/dist/heart/outlook/outlook-http-transport.js +116 -0
- package/dist/heart/outlook/outlook-http.js +99 -0
- package/dist/heart/outlook/outlook-read.js +31 -0
- package/dist/heart/outlook/outlook-types.js +27 -0
- package/dist/heart/outlook/outlook-view.js +195 -0
- package/dist/heart/outlook/readers/agent-machine.js +359 -0
- package/dist/heart/outlook/readers/continuity-readers.js +332 -0
- package/dist/heart/outlook/readers/mail.js +362 -0
- package/dist/heart/outlook/readers/runtime-readers.js +644 -0
- package/dist/heart/outlook/readers/sessions.js +232 -0
- package/dist/heart/outlook/readers/shared.js +111 -0
- package/dist/heart/platform.js +81 -0
- package/dist/heart/progress-story.js +42 -0
- package/dist/heart/provider-attempt.js +134 -0
- package/dist/heart/provider-binding-resolver.js +255 -0
- package/dist/heart/provider-credentials.js +424 -0
- package/dist/heart/provider-failover.js +266 -0
- package/dist/heart/provider-models.js +81 -0
- package/dist/heart/provider-ping.js +262 -0
- package/dist/heart/provider-state.js +216 -0
- package/dist/heart/provider-visibility.js +188 -0
- package/dist/heart/providers/anthropic-token.js +131 -0
- package/dist/heart/providers/anthropic.js +193 -55
- package/dist/heart/providers/azure.js +103 -12
- package/dist/heart/providers/error-classification.js +63 -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 +29 -7
- package/dist/heart/providers/openai-codex.js +62 -38
- package/dist/heart/runtime-capability-check.js +170 -0
- package/dist/heart/runtime-credentials.js +260 -0
- package/dist/heart/sense-truth.js +11 -4
- package/dist/heart/session-activity.js +190 -0
- package/dist/heart/session-events.js +855 -0
- package/dist/heart/session-transcript.js +167 -0
- package/dist/heart/start-of-turn-packet.js +345 -0
- package/dist/heart/streaming.js +36 -27
- package/dist/heart/sync.js +332 -0
- package/dist/heart/target-resolution.js +127 -0
- package/dist/heart/tempo.js +93 -0
- package/dist/heart/temporal-view.js +41 -0
- package/dist/heart/tool-activity-callbacks.js +36 -0
- package/dist/heart/tool-description.js +135 -0
- package/dist/heart/tool-friction.js +55 -0
- package/dist/heart/tool-loop.js +200 -0
- package/dist/heart/turn-context.js +361 -0
- package/dist/heart/turn-coordinator.js +24 -1
- package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +1 -1
- package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
- package/dist/heart/versioning/ouro-path-installer.js +425 -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 +5 -1
- package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
- package/dist/mailroom/attention.js +167 -0
- package/dist/mailroom/autonomy.js +209 -0
- package/dist/mailroom/blob-store.js +573 -0
- package/dist/mailroom/core.js +658 -0
- package/dist/mailroom/entry.js +160 -0
- package/dist/mailroom/file-store.js +400 -0
- package/dist/mailroom/mbox-import.js +341 -0
- package/dist/mailroom/outbound.js +380 -0
- package/dist/mailroom/policy.js +263 -0
- package/dist/mailroom/reader.js +197 -0
- package/dist/mailroom/smtp-ingress.js +176 -0
- package/dist/mailroom/source-state.js +176 -0
- package/dist/mailroom/travel-extract.js +89 -0
- package/dist/mind/bundle-manifest.js +7 -1
- package/dist/mind/context.js +132 -93
- package/dist/mind/diary-integrity.js +60 -0
- package/dist/mind/{memory.js → diary.js} +74 -93
- package/dist/mind/embedding-provider.js +60 -0
- package/dist/mind/file-state.js +179 -0
- package/dist/mind/friends/channel.js +30 -0
- package/dist/mind/friends/group-context.js +144 -0
- package/dist/mind/friends/resolver.js +38 -1
- package/dist/mind/friends/store-file.js +39 -3
- package/dist/mind/friends/trust-explanation.js +74 -0
- 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 +66 -7
- package/dist/mind/prompt-refresh.js +3 -2
- package/dist/mind/prompt.js +978 -169
- 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 +84 -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/runtime.js +5 -1
- package/dist/outlook-ui/assets/index-BPr5vNuM.css +1 -0
- package/dist/outlook-ui/assets/index-CPfhbn13.js +61 -0
- package/dist/outlook-ui/index.html +15 -0
- 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 +774 -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 +111 -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 +255 -0
- package/dist/repertoire/mcp-manager.js +305 -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 +43 -5
- package/dist/repertoire/tasks/fix.js +182 -0
- package/dist/repertoire/tasks/index.js +37 -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 +44 -740
- package/dist/repertoire/tools-bluebubbles.js +1 -0
- package/dist/repertoire/tools-bridge.js +141 -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 +105 -0
- package/dist/repertoire/tools-github.js +1 -7
- package/dist/repertoire/tools-mail.js +896 -0
- package/dist/repertoire/tools-notes.js +376 -0
- package/dist/repertoire/tools-session.js +746 -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-user-profile.js +144 -0
- package/dist/repertoire/tools-vault.js +40 -0
- package/dist/repertoire/tools.js +144 -113
- 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 +561 -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/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 +73 -0
- package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +7 -3
- package/dist/senses/{bluebubbles.js → bluebubbles/index.js} +705 -116
- 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/replay.js +129 -0
- package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +2 -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 +605 -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 +83 -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 +516 -211
- package/dist/senses/commands.js +66 -3
- package/dist/senses/habit-turn-message.js +108 -0
- package/dist/senses/inner-dialog-worker.js +97 -17
- package/dist/senses/inner-dialog.js +404 -14
- package/dist/senses/mail-entry.js +66 -0
- package/dist/senses/mail.js +232 -0
- package/dist/senses/pipeline.js +533 -72
- package/dist/senses/proactive-content-guard.js +51 -0
- package/dist/senses/shared-turn.js +205 -0
- package/dist/senses/surface-tool.js +68 -0
- package/dist/senses/teams-entry.js +60 -8
- package/dist/senses/teams.js +413 -163
- package/dist/senses/trust-gate.js +5 -5
- package/package.json +37 -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/ouro-path-installer.js +0 -178
- package/dist/heart/daemon/subagent-installer.js +0 -166
- package/dist/mind/associative-recall.js +0 -209
- package/dist/senses/bluebubbles-entry.js +0 -13
- package/dist/senses/debug-activity.js +0 -127
- 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,855 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.normalizeContinuityState = normalizeContinuityState;
|
|
37
|
+
exports.validateSessionMessages = validateSessionMessages;
|
|
38
|
+
exports.repairSessionMessages = repairSessionMessages;
|
|
39
|
+
exports.migrateToolNames = migrateToolNames;
|
|
40
|
+
exports.sanitizeProviderMessages = sanitizeProviderMessages;
|
|
41
|
+
exports.stampIngressTime = stampIngressTime;
|
|
42
|
+
exports.getIngressTime = getIngressTime;
|
|
43
|
+
exports.projectProviderMessages = projectProviderMessages;
|
|
44
|
+
exports.annotateMessageTimestamps = annotateMessageTimestamps;
|
|
45
|
+
exports.bestEventTimestamp = bestEventTimestamp;
|
|
46
|
+
exports.formatSessionEventTimestamp = formatSessionEventTimestamp;
|
|
47
|
+
exports.extractEventText = extractEventText;
|
|
48
|
+
exports.deriveSessionChronology = deriveSessionChronology;
|
|
49
|
+
exports.describeCurrentSessionTiming = describeCurrentSessionTiming;
|
|
50
|
+
exports.migrateLegacySessionEnvelope = migrateLegacySessionEnvelope;
|
|
51
|
+
exports.parseSessionEnvelope = parseSessionEnvelope;
|
|
52
|
+
exports.loadSessionEnvelopeFile = loadSessionEnvelopeFile;
|
|
53
|
+
exports.buildCanonicalSessionEnvelope = buildCanonicalSessionEnvelope;
|
|
54
|
+
exports.loadFullEventHistory = loadFullEventHistory;
|
|
55
|
+
exports.appendEvictedToArchive = appendEvictedToArchive;
|
|
56
|
+
exports.appendSyntheticAssistantEvent = appendSyntheticAssistantEvent;
|
|
57
|
+
const fs = __importStar(require("fs"));
|
|
58
|
+
const runtime_1 = require("../nerves/runtime");
|
|
59
|
+
function formatElapsed(ms) {
|
|
60
|
+
const minutes = Math.max(0, Math.floor(ms / 60000));
|
|
61
|
+
if (minutes < 60)
|
|
62
|
+
return `${minutes}m ago`;
|
|
63
|
+
const hours = Math.floor(minutes / 60);
|
|
64
|
+
if (hours < 24)
|
|
65
|
+
return `${hours}h ago`;
|
|
66
|
+
const days = Math.floor(hours / 24);
|
|
67
|
+
return `${days}d ago`;
|
|
68
|
+
}
|
|
69
|
+
const LEGACY_WRITTEN_NOTE_PREFIX = "mem" + "ory";
|
|
70
|
+
const TOOL_NAME_MIGRATIONS = {
|
|
71
|
+
final_answer: "settle",
|
|
72
|
+
no_response: "observe",
|
|
73
|
+
go_inward: "ponder",
|
|
74
|
+
descend: "ponder",
|
|
75
|
+
[`${LEGACY_WRITTEN_NOTE_PREFIX}_save`]: "diary_write",
|
|
76
|
+
[`${LEGACY_WRITTEN_NOTE_PREFIX}_search`]: "search_notes",
|
|
77
|
+
};
|
|
78
|
+
function normalizeUsage(usage) {
|
|
79
|
+
if (!usage || typeof usage !== "object")
|
|
80
|
+
return null;
|
|
81
|
+
const record = usage;
|
|
82
|
+
if (typeof record.input_tokens !== "number"
|
|
83
|
+
|| typeof record.output_tokens !== "number"
|
|
84
|
+
|| typeof record.reasoning_tokens !== "number"
|
|
85
|
+
|| typeof record.total_tokens !== "number") {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
input_tokens: record.input_tokens,
|
|
90
|
+
output_tokens: record.output_tokens,
|
|
91
|
+
reasoning_tokens: record.reasoning_tokens,
|
|
92
|
+
total_tokens: record.total_tokens,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function normalizeContinuityState(state) {
|
|
96
|
+
const record = state && typeof state === "object"
|
|
97
|
+
? state
|
|
98
|
+
: null;
|
|
99
|
+
return {
|
|
100
|
+
mustResolveBeforeHandoff: record?.mustResolveBeforeHandoff === true,
|
|
101
|
+
lastFriendActivityAt: typeof record?.lastFriendActivityAt === "string" ? record.lastFriendActivityAt : null,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function normalizeContent(content) {
|
|
105
|
+
if (content == null)
|
|
106
|
+
return null;
|
|
107
|
+
if (typeof content === "string")
|
|
108
|
+
return content;
|
|
109
|
+
if (!Array.isArray(content))
|
|
110
|
+
return null;
|
|
111
|
+
return content
|
|
112
|
+
.filter((part) => part != null && typeof part === "object")
|
|
113
|
+
.map((part) => ({ ...part }));
|
|
114
|
+
}
|
|
115
|
+
function normalizeToolCalls(rawToolCalls) {
|
|
116
|
+
if (!Array.isArray(rawToolCalls))
|
|
117
|
+
return [];
|
|
118
|
+
return rawToolCalls
|
|
119
|
+
.filter((call) => call != null && typeof call === "object")
|
|
120
|
+
.map((call) => {
|
|
121
|
+
const fn = call.function;
|
|
122
|
+
const originalName = typeof fn?.name === "string" ? fn.name : "unknown";
|
|
123
|
+
const migratedName = TOOL_NAME_MIGRATIONS[originalName] ?? originalName;
|
|
124
|
+
return {
|
|
125
|
+
id: typeof call.id === "string" ? call.id : "",
|
|
126
|
+
type: typeof call.type === "string" ? call.type : "function",
|
|
127
|
+
function: {
|
|
128
|
+
name: migratedName,
|
|
129
|
+
arguments: typeof fn?.arguments === "string" ? fn.arguments : JSON.stringify(fn?.arguments ?? ""),
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
function normalizeRole(role) {
|
|
135
|
+
if (role === "developer")
|
|
136
|
+
return "system";
|
|
137
|
+
return role === "system" || role === "user" || role === "assistant" || role === "tool"
|
|
138
|
+
? role
|
|
139
|
+
: "user";
|
|
140
|
+
}
|
|
141
|
+
function normalizeMessage(message) {
|
|
142
|
+
const record = message;
|
|
143
|
+
const role = normalizeRole(record.role);
|
|
144
|
+
if (role === "assistant") {
|
|
145
|
+
return {
|
|
146
|
+
role,
|
|
147
|
+
content: normalizeContent(record.content),
|
|
148
|
+
name: typeof record.name === "string" ? record.name : null,
|
|
149
|
+
toolCallId: null,
|
|
150
|
+
toolCalls: normalizeToolCalls(record.tool_calls),
|
|
151
|
+
hadToolCallsField: Array.isArray(record.tool_calls),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
if (role === "tool") {
|
|
155
|
+
return {
|
|
156
|
+
role,
|
|
157
|
+
content: typeof record.content === "string" ? record.content : "",
|
|
158
|
+
name: null,
|
|
159
|
+
toolCallId: typeof record.tool_call_id === "string" ? record.tool_call_id : null,
|
|
160
|
+
toolCalls: [],
|
|
161
|
+
hadToolCallsField: false,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
role,
|
|
166
|
+
content: normalizeContent(record.content) ?? "",
|
|
167
|
+
name: typeof record.name === "string" ? record.name : null,
|
|
168
|
+
toolCallId: null,
|
|
169
|
+
toolCalls: [],
|
|
170
|
+
hadToolCallsField: false,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
function contentText(content) {
|
|
174
|
+
if (typeof content === "string")
|
|
175
|
+
return content;
|
|
176
|
+
if (!Array.isArray(content))
|
|
177
|
+
return "";
|
|
178
|
+
return content
|
|
179
|
+
.map((part) => (part.type === "text" && typeof part.text === "string"
|
|
180
|
+
? part.text
|
|
181
|
+
: ""))
|
|
182
|
+
.filter((text) => text.length > 0)
|
|
183
|
+
.join("");
|
|
184
|
+
}
|
|
185
|
+
function toProviderMessage(message) {
|
|
186
|
+
if (message.role === "assistant") {
|
|
187
|
+
const assistant = {
|
|
188
|
+
role: "assistant",
|
|
189
|
+
content: message.content,
|
|
190
|
+
};
|
|
191
|
+
if (message.name)
|
|
192
|
+
assistant.name = message.name;
|
|
193
|
+
if (message.hadToolCallsField || message.toolCalls.length > 0) {
|
|
194
|
+
assistant.tool_calls = message.toolCalls.map((call) => ({
|
|
195
|
+
id: call.id,
|
|
196
|
+
type: call.type,
|
|
197
|
+
function: {
|
|
198
|
+
name: call.function.name,
|
|
199
|
+
arguments: call.function.arguments,
|
|
200
|
+
},
|
|
201
|
+
}));
|
|
202
|
+
}
|
|
203
|
+
return assistant;
|
|
204
|
+
}
|
|
205
|
+
if (message.role === "tool") {
|
|
206
|
+
return {
|
|
207
|
+
role: "tool",
|
|
208
|
+
content: typeof message.content === "string" ? message.content : contentText(message.content),
|
|
209
|
+
tool_call_id: message.toolCallId ?? "",
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
if (message.role === "system") {
|
|
213
|
+
return {
|
|
214
|
+
role: "system",
|
|
215
|
+
content: typeof message.content === "string" ? message.content : contentText(message.content),
|
|
216
|
+
...(message.name ? { name: message.name } : {}),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
role: "user",
|
|
221
|
+
content: (typeof message.content === "string" || Array.isArray(message.content) ? message.content : ""),
|
|
222
|
+
...(message.name ? { name: message.name } : {}),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function messageFingerprint(message) {
|
|
226
|
+
const normalized = normalizeMessage(message);
|
|
227
|
+
return JSON.stringify({
|
|
228
|
+
role: normalized.role,
|
|
229
|
+
content: normalized.content,
|
|
230
|
+
name: normalized.name,
|
|
231
|
+
tool_call_id: normalized.toolCallId,
|
|
232
|
+
tool_calls: normalized.toolCalls,
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
function makeEventId(sequence) {
|
|
236
|
+
return `evt-${String(sequence).padStart(6, "0")}`;
|
|
237
|
+
}
|
|
238
|
+
function validateSessionMessages(messages) {
|
|
239
|
+
const violations = [];
|
|
240
|
+
let prevNonToolRole = null;
|
|
241
|
+
let prevAssistantHadToolCalls = false;
|
|
242
|
+
let sawToolResultSincePrevAssistant = false;
|
|
243
|
+
for (let i = 0; i < messages.length; i++) {
|
|
244
|
+
const msg = normalizeMessage(messages[i]);
|
|
245
|
+
if (msg.role === "system")
|
|
246
|
+
continue;
|
|
247
|
+
if (msg.role === "tool") {
|
|
248
|
+
sawToolResultSincePrevAssistant = true;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
if (msg.role === "assistant" && prevNonToolRole === "assistant") {
|
|
252
|
+
if (!(prevAssistantHadToolCalls && sawToolResultSincePrevAssistant)) {
|
|
253
|
+
violations.push(`back-to-back assistant at index ${i}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
prevAssistantHadToolCalls = msg.role === "assistant" && msg.toolCalls.length > 0;
|
|
257
|
+
sawToolResultSincePrevAssistant = false;
|
|
258
|
+
prevNonToolRole = msg.role;
|
|
259
|
+
}
|
|
260
|
+
return violations;
|
|
261
|
+
}
|
|
262
|
+
function repairSessionMessages(messages) {
|
|
263
|
+
const normalized = messages.map(normalizeMessage);
|
|
264
|
+
const violations = validateSessionMessages(messages);
|
|
265
|
+
if (violations.length === 0)
|
|
266
|
+
return normalized.map(toProviderMessage);
|
|
267
|
+
const result = [];
|
|
268
|
+
for (const msg of normalized) {
|
|
269
|
+
if (msg.role === "assistant" && result.length > 0) {
|
|
270
|
+
const prev = result[result.length - 1];
|
|
271
|
+
if (prev.role === "assistant" && prev.toolCalls.length === 0) {
|
|
272
|
+
const prevContent = contentText(prev.content);
|
|
273
|
+
const curContent = contentText(msg.content);
|
|
274
|
+
prev.content = `${prevContent}\n\n${curContent}`;
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
result.push(msg);
|
|
279
|
+
}
|
|
280
|
+
(0, runtime_1.emitNervesEvent)({
|
|
281
|
+
level: "info",
|
|
282
|
+
event: "mind.session_invariant_repair",
|
|
283
|
+
component: "mind",
|
|
284
|
+
message: "repaired session invariant violations",
|
|
285
|
+
meta: { violations },
|
|
286
|
+
});
|
|
287
|
+
return result.map(toProviderMessage);
|
|
288
|
+
}
|
|
289
|
+
function stripOrphanedToolResults(messages) {
|
|
290
|
+
const normalized = messages.map(normalizeMessage);
|
|
291
|
+
const validCallIds = new Set();
|
|
292
|
+
for (const msg of normalized) {
|
|
293
|
+
if (msg.role !== "assistant")
|
|
294
|
+
continue;
|
|
295
|
+
for (const toolCall of msg.toolCalls)
|
|
296
|
+
validCallIds.add(toolCall.id);
|
|
297
|
+
}
|
|
298
|
+
let removed = 0;
|
|
299
|
+
const repaired = normalized.filter((msg) => {
|
|
300
|
+
if (msg.role !== "tool")
|
|
301
|
+
return true;
|
|
302
|
+
const keep = msg.toolCallId !== null && validCallIds.has(msg.toolCallId);
|
|
303
|
+
if (!keep)
|
|
304
|
+
removed++;
|
|
305
|
+
return keep;
|
|
306
|
+
});
|
|
307
|
+
if (removed > 0) {
|
|
308
|
+
(0, runtime_1.emitNervesEvent)({
|
|
309
|
+
level: "info",
|
|
310
|
+
event: "mind.session_orphan_tool_result_repair",
|
|
311
|
+
component: "mind",
|
|
312
|
+
message: "removed orphaned tool results from session history",
|
|
313
|
+
meta: { removed },
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
return repaired.map(toProviderMessage);
|
|
317
|
+
}
|
|
318
|
+
function migrateToolNames(messages) {
|
|
319
|
+
const safeMessages = messages.filter((message) => Boolean(message) && typeof message === "object");
|
|
320
|
+
let migrated = 0;
|
|
321
|
+
for (const message of safeMessages) {
|
|
322
|
+
const record = message;
|
|
323
|
+
if (record.role !== "assistant" || !Array.isArray(record.tool_calls))
|
|
324
|
+
continue;
|
|
325
|
+
for (const toolCall of record.tool_calls) {
|
|
326
|
+
if (!toolCall || typeof toolCall !== "object")
|
|
327
|
+
continue;
|
|
328
|
+
const toolRecord = toolCall;
|
|
329
|
+
if (toolRecord.type !== "function")
|
|
330
|
+
continue;
|
|
331
|
+
const originalName = toolRecord.function?.name;
|
|
332
|
+
if (typeof originalName !== "string")
|
|
333
|
+
continue;
|
|
334
|
+
if (TOOL_NAME_MIGRATIONS[originalName])
|
|
335
|
+
migrated += 1;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (migrated > 0) {
|
|
339
|
+
(0, runtime_1.emitNervesEvent)({
|
|
340
|
+
level: "info",
|
|
341
|
+
event: "mind.session_tool_name_migration",
|
|
342
|
+
component: "mind",
|
|
343
|
+
message: "migrated deprecated tool names in session history",
|
|
344
|
+
meta: { migrated },
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
return safeMessages.map(normalizeMessage).map(toProviderMessage);
|
|
348
|
+
}
|
|
349
|
+
function sanitizeProviderMessages(messages) {
|
|
350
|
+
const safeMessages = messages.filter((message) => Boolean(message) && typeof message === "object");
|
|
351
|
+
const normalized = safeMessages.map(normalizeMessage);
|
|
352
|
+
const violations = validateSessionMessages(safeMessages);
|
|
353
|
+
if (violations.length > 0) {
|
|
354
|
+
(0, runtime_1.emitNervesEvent)({
|
|
355
|
+
level: "info",
|
|
356
|
+
event: "mind.session_invariant_violation",
|
|
357
|
+
component: "mind",
|
|
358
|
+
message: "session invariant violated",
|
|
359
|
+
meta: { violations },
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
return migrateToolNames(stripOrphanedToolResults(repairSessionMessages(normalized.map(toProviderMessage))));
|
|
363
|
+
}
|
|
364
|
+
function stampIngressTime(msg) {
|
|
365
|
+
msg._ingressAt = new Date().toISOString();
|
|
366
|
+
}
|
|
367
|
+
function getIngressTime(msg) {
|
|
368
|
+
const value = msg._ingressAt;
|
|
369
|
+
return typeof value === "string" ? value : null;
|
|
370
|
+
}
|
|
371
|
+
function createEventTime(role, recordedAt, captureKind, ingressAt) {
|
|
372
|
+
if (captureKind === "migration") {
|
|
373
|
+
return {
|
|
374
|
+
authoredAt: null,
|
|
375
|
+
authoredAtSource: "migration",
|
|
376
|
+
observedAt: null,
|
|
377
|
+
observedAtSource: "migration",
|
|
378
|
+
recordedAt,
|
|
379
|
+
recordedAtSource: "migration",
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
if (role === "user") {
|
|
383
|
+
return {
|
|
384
|
+
authoredAt: null,
|
|
385
|
+
authoredAtSource: "unknown",
|
|
386
|
+
observedAt: ingressAt ?? recordedAt,
|
|
387
|
+
observedAtSource: "ingest",
|
|
388
|
+
recordedAt,
|
|
389
|
+
recordedAtSource: "save",
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
return {
|
|
393
|
+
authoredAt: recordedAt,
|
|
394
|
+
authoredAtSource: "local",
|
|
395
|
+
observedAt: recordedAt,
|
|
396
|
+
observedAtSource: "local",
|
|
397
|
+
recordedAt,
|
|
398
|
+
recordedAtSource: "save",
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
function buildEventFromMessage(message, sequence, recordedAt, captureKind, sourceMessageIndex, legacyVersion, ingressAt) {
|
|
402
|
+
const normalized = normalizeMessage(message);
|
|
403
|
+
const role = normalized.role;
|
|
404
|
+
return {
|
|
405
|
+
id: makeEventId(sequence),
|
|
406
|
+
sequence,
|
|
407
|
+
role,
|
|
408
|
+
content: normalized.content,
|
|
409
|
+
name: normalized.name,
|
|
410
|
+
toolCallId: role === "tool" ? normalized.toolCallId : null,
|
|
411
|
+
toolCalls: role === "assistant" ? normalized.toolCalls : [],
|
|
412
|
+
attachments: [],
|
|
413
|
+
time: createEventTime(role, recordedAt, captureKind, ingressAt),
|
|
414
|
+
relations: {
|
|
415
|
+
replyToEventId: null,
|
|
416
|
+
threadRootEventId: null,
|
|
417
|
+
references: [],
|
|
418
|
+
toolCallId: role === "tool" ? normalized.toolCallId : null,
|
|
419
|
+
supersedesEventId: null,
|
|
420
|
+
redactsEventId: null,
|
|
421
|
+
},
|
|
422
|
+
provenance: {
|
|
423
|
+
captureKind,
|
|
424
|
+
legacyVersion,
|
|
425
|
+
sourceMessageIndex,
|
|
426
|
+
},
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
function projectProviderMessages(envelope) {
|
|
430
|
+
const eventIds = envelope.projection.eventIds.length > 0
|
|
431
|
+
? envelope.projection.eventIds
|
|
432
|
+
: envelope.events.map((event) => event.id);
|
|
433
|
+
const byId = new Map(envelope.events.map((event) => [event.id, event]));
|
|
434
|
+
return eventIds
|
|
435
|
+
.map((id) => byId.get(id))
|
|
436
|
+
.filter((event) => Boolean(event))
|
|
437
|
+
.map((event) => toProviderMessage({
|
|
438
|
+
role: event.role,
|
|
439
|
+
content: event.content,
|
|
440
|
+
name: event.name,
|
|
441
|
+
toolCallId: event.toolCallId,
|
|
442
|
+
toolCalls: event.toolCalls,
|
|
443
|
+
hadToolCallsField: event.toolCalls.length > 0,
|
|
444
|
+
}));
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Annotate user and assistant messages with a relative time offset tag.
|
|
448
|
+
* System and tool messages are untouched.
|
|
449
|
+
*/
|
|
450
|
+
function annotateMessageTimestamps(envelope, messages, nowMs = Date.now()) {
|
|
451
|
+
const eventIds = envelope.projection.eventIds.length > 0
|
|
452
|
+
? envelope.projection.eventIds
|
|
453
|
+
: envelope.events.map((event) => event.id);
|
|
454
|
+
const byId = new Map(envelope.events.map((event) => [event.id, event]));
|
|
455
|
+
const events = eventIds
|
|
456
|
+
.map((id) => byId.get(id))
|
|
457
|
+
.filter((event) => Boolean(event));
|
|
458
|
+
return messages.map((msg, i) => {
|
|
459
|
+
const event = events[i];
|
|
460
|
+
if (!event)
|
|
461
|
+
return msg;
|
|
462
|
+
if (event.role !== "user" && event.role !== "assistant")
|
|
463
|
+
return msg;
|
|
464
|
+
const ts = bestEventTimestamp(event);
|
|
465
|
+
const elapsed = nowMs - Date.parse(ts);
|
|
466
|
+
if (elapsed < 0)
|
|
467
|
+
return msg;
|
|
468
|
+
const tag = elapsed < 60000 ? "[just now]" : `[-${formatElapsedCompact(elapsed)}]`;
|
|
469
|
+
if (typeof msg.content === "string" && msg.content.length > 0) {
|
|
470
|
+
return { ...msg, content: `${tag} ${msg.content}` };
|
|
471
|
+
}
|
|
472
|
+
return msg;
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
/** Compact elapsed format for message annotations: "3m", "2h", "1d". */
|
|
476
|
+
function formatElapsedCompact(ms) {
|
|
477
|
+
const minutes = Math.max(1, Math.floor(ms / 60000));
|
|
478
|
+
if (minutes < 60)
|
|
479
|
+
return `${minutes}m`;
|
|
480
|
+
const hours = Math.floor(minutes / 60);
|
|
481
|
+
if (hours < 24)
|
|
482
|
+
return `${hours}h`;
|
|
483
|
+
const days = Math.floor(hours / 24);
|
|
484
|
+
return `${days}d`;
|
|
485
|
+
}
|
|
486
|
+
function bestEventTimestamp(event) {
|
|
487
|
+
return event.time.authoredAt ?? event.time.observedAt ?? event.time.recordedAt;
|
|
488
|
+
}
|
|
489
|
+
function formatSessionEventTimestamp(event) {
|
|
490
|
+
const iso = bestEventTimestamp(event);
|
|
491
|
+
const date = new Date(iso);
|
|
492
|
+
const year = date.getUTCFullYear();
|
|
493
|
+
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
|
|
494
|
+
const day = String(date.getUTCDate()).padStart(2, "0");
|
|
495
|
+
const hour = String(date.getUTCHours()).padStart(2, "0");
|
|
496
|
+
const minute = String(date.getUTCMinutes()).padStart(2, "0");
|
|
497
|
+
return `${year}-${month}-${day} ${hour}:${minute}`;
|
|
498
|
+
}
|
|
499
|
+
function extractEventText(event) {
|
|
500
|
+
return contentText(event.content);
|
|
501
|
+
}
|
|
502
|
+
function deriveSessionChronology(events) {
|
|
503
|
+
let lastInboundAt = null;
|
|
504
|
+
let lastOutboundAt = null;
|
|
505
|
+
let lastActivityAt = null;
|
|
506
|
+
let lastAssistantSequence = -1;
|
|
507
|
+
for (const event of events) {
|
|
508
|
+
if (event.role === "system")
|
|
509
|
+
continue;
|
|
510
|
+
const at = bestEventTimestamp(event);
|
|
511
|
+
lastActivityAt = at;
|
|
512
|
+
if (event.role === "user") {
|
|
513
|
+
lastInboundAt = at;
|
|
514
|
+
}
|
|
515
|
+
if (event.role === "assistant") {
|
|
516
|
+
lastOutboundAt = at;
|
|
517
|
+
lastAssistantSequence = event.sequence;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const unansweredInboundCount = events.filter((event) => event.role === "user" && event.sequence > lastAssistantSequence).length;
|
|
521
|
+
return {
|
|
522
|
+
lastInboundAt,
|
|
523
|
+
lastOutboundAt,
|
|
524
|
+
lastActivityAt,
|
|
525
|
+
unansweredInboundCount,
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
function describeCurrentSessionTiming(events, nowMs = Date.now()) {
|
|
529
|
+
const chronology = deriveSessionChronology(events);
|
|
530
|
+
const parts = [];
|
|
531
|
+
if (chronology.lastInboundAt) {
|
|
532
|
+
parts.push(`last inbound ${formatElapsed(nowMs - Date.parse(chronology.lastInboundAt))}`);
|
|
533
|
+
}
|
|
534
|
+
if (chronology.lastOutboundAt) {
|
|
535
|
+
parts.push(`i last replied ${formatElapsed(nowMs - Date.parse(chronology.lastOutboundAt))}`);
|
|
536
|
+
}
|
|
537
|
+
if (chronology.unansweredInboundCount > 0) {
|
|
538
|
+
const count = chronology.unansweredInboundCount;
|
|
539
|
+
parts.push(`${count} unanswered inbound message${count === 1 ? "" : "s"}`);
|
|
540
|
+
}
|
|
541
|
+
return parts.length > 0 ? `current thread: ${parts.join("; ")}` : "";
|
|
542
|
+
}
|
|
543
|
+
function migrateLegacySessionEnvelope(raw, options) {
|
|
544
|
+
if (!raw || typeof raw !== "object")
|
|
545
|
+
return null;
|
|
546
|
+
const legacy = raw;
|
|
547
|
+
const looksLegacy = legacy.version === 1
|
|
548
|
+
|| (legacy.version == null && ("messages" in legacy || "lastUsage" in legacy || "state" in legacy));
|
|
549
|
+
if (!looksLegacy)
|
|
550
|
+
return null;
|
|
551
|
+
const messages = Array.isArray(legacy.messages)
|
|
552
|
+
? sanitizeProviderMessages(legacy.messages)
|
|
553
|
+
: [];
|
|
554
|
+
const recordedAt = options.fileMtimeAt ?? options.recordedAt;
|
|
555
|
+
const events = messages.map((message, index) => buildEventFromMessage(message, index + 1, recordedAt, "migration", index, 1));
|
|
556
|
+
return {
|
|
557
|
+
version: 2,
|
|
558
|
+
events,
|
|
559
|
+
projection: {
|
|
560
|
+
eventIds: events.map((event) => event.id),
|
|
561
|
+
trimmed: false,
|
|
562
|
+
maxTokens: null,
|
|
563
|
+
contextMargin: null,
|
|
564
|
+
inputTokens: null,
|
|
565
|
+
projectedAt: recordedAt,
|
|
566
|
+
},
|
|
567
|
+
lastUsage: normalizeUsage(legacy.lastUsage),
|
|
568
|
+
state: normalizeContinuityState(legacy.state),
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
function parseSessionEnvelope(raw, options = {}) {
|
|
572
|
+
const recordedAt = options.recordedAt ?? new Date().toISOString();
|
|
573
|
+
const fileMtimeAt = options.fileMtimeAt ?? null;
|
|
574
|
+
const migrated = migrateLegacySessionEnvelope(raw, { recordedAt, fileMtimeAt });
|
|
575
|
+
if (migrated)
|
|
576
|
+
return migrated;
|
|
577
|
+
if (!raw || typeof raw !== "object")
|
|
578
|
+
return null;
|
|
579
|
+
const record = raw;
|
|
580
|
+
if (record.version !== 2 || !Array.isArray(record.events) || !record.projection || typeof record.projection !== "object") {
|
|
581
|
+
return null;
|
|
582
|
+
}
|
|
583
|
+
const events = record.events
|
|
584
|
+
.filter((event) => event != null && typeof event === "object")
|
|
585
|
+
.map((event, index) => {
|
|
586
|
+
const role = normalizeRole(event.role);
|
|
587
|
+
const time = event.time;
|
|
588
|
+
const relations = event.relations;
|
|
589
|
+
const provenance = event.provenance;
|
|
590
|
+
return {
|
|
591
|
+
id: typeof event.id === "string" ? event.id : makeEventId(index + 1),
|
|
592
|
+
sequence: typeof event.sequence === "number" ? event.sequence : index + 1,
|
|
593
|
+
role,
|
|
594
|
+
content: normalizeContent(event.content),
|
|
595
|
+
name: typeof event.name === "string" ? event.name : null,
|
|
596
|
+
toolCallId: typeof event.toolCallId === "string" ? event.toolCallId : null,
|
|
597
|
+
toolCalls: normalizeToolCalls(event.toolCalls),
|
|
598
|
+
attachments: Array.isArray(event.attachments) ? event.attachments.filter((item) => typeof item === "string") : [],
|
|
599
|
+
time: {
|
|
600
|
+
authoredAt: typeof time?.authoredAt === "string" ? time.authoredAt : null,
|
|
601
|
+
authoredAtSource: typeof time?.authoredAtSource === "string" ? time.authoredAtSource : "unknown",
|
|
602
|
+
observedAt: typeof time?.observedAt === "string" ? time.observedAt : null,
|
|
603
|
+
observedAtSource: typeof time?.observedAtSource === "string" ? time.observedAtSource : "unknown",
|
|
604
|
+
recordedAt: typeof time?.recordedAt === "string" ? time.recordedAt : recordedAt,
|
|
605
|
+
recordedAtSource: typeof time?.recordedAtSource === "string" ? time.recordedAtSource : "save",
|
|
606
|
+
},
|
|
607
|
+
relations: {
|
|
608
|
+
replyToEventId: typeof relations?.replyToEventId === "string" ? relations.replyToEventId : null,
|
|
609
|
+
threadRootEventId: typeof relations?.threadRootEventId === "string" ? relations.threadRootEventId : null,
|
|
610
|
+
references: Array.isArray(relations?.references) ? relations.references.filter((item) => typeof item === "string") : [],
|
|
611
|
+
toolCallId: typeof relations?.toolCallId === "string" ? relations.toolCallId : null,
|
|
612
|
+
supersedesEventId: typeof relations?.supersedesEventId === "string" ? relations.supersedesEventId : null,
|
|
613
|
+
redactsEventId: typeof relations?.redactsEventId === "string" ? relations.redactsEventId : null,
|
|
614
|
+
},
|
|
615
|
+
provenance: {
|
|
616
|
+
captureKind: typeof provenance?.captureKind === "string" ? provenance.captureKind : "live",
|
|
617
|
+
legacyVersion: typeof provenance?.legacyVersion === "number" ? provenance.legacyVersion : null,
|
|
618
|
+
sourceMessageIndex: typeof provenance?.sourceMessageIndex === "number" ? provenance.sourceMessageIndex : null,
|
|
619
|
+
},
|
|
620
|
+
};
|
|
621
|
+
});
|
|
622
|
+
const projection = record.projection;
|
|
623
|
+
return {
|
|
624
|
+
version: 2,
|
|
625
|
+
events,
|
|
626
|
+
projection: {
|
|
627
|
+
eventIds: Array.isArray(projection.eventIds) ? projection.eventIds.filter((item) => typeof item === "string") : [],
|
|
628
|
+
trimmed: projection.trimmed === true,
|
|
629
|
+
maxTokens: typeof projection.maxTokens === "number" ? projection.maxTokens : null,
|
|
630
|
+
contextMargin: typeof projection.contextMargin === "number" ? projection.contextMargin : null,
|
|
631
|
+
inputTokens: typeof projection.inputTokens === "number" ? projection.inputTokens : null,
|
|
632
|
+
projectedAt: typeof projection.projectedAt === "string" ? projection.projectedAt : null,
|
|
633
|
+
},
|
|
634
|
+
lastUsage: normalizeUsage(record.lastUsage),
|
|
635
|
+
state: normalizeContinuityState(record.state),
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
function loadSessionEnvelopeFile(filePath) {
|
|
639
|
+
try {
|
|
640
|
+
const raw = fs.readFileSync(filePath, "utf-8");
|
|
641
|
+
let mtime;
|
|
642
|
+
try {
|
|
643
|
+
mtime = fs.statSync(filePath).mtime.toISOString();
|
|
644
|
+
}
|
|
645
|
+
catch {
|
|
646
|
+
mtime = new Date().toISOString();
|
|
647
|
+
}
|
|
648
|
+
return parseSessionEnvelope(JSON.parse(raw), {
|
|
649
|
+
recordedAt: mtime,
|
|
650
|
+
fileMtimeAt: mtime,
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
catch {
|
|
654
|
+
return null;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
function messageRole(msg) {
|
|
658
|
+
return normalizeRole(msg.role);
|
|
659
|
+
}
|
|
660
|
+
function filterNonSystem(messages) {
|
|
661
|
+
return messages.filter((msg) => messageRole(msg) !== "system");
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Compare two message arrays by their non-system messages only.
|
|
665
|
+
* Returns the number of matching non-system messages from the start.
|
|
666
|
+
* System messages (whose content changes every turn due to live world-state)
|
|
667
|
+
* are excluded so that prefix matching is not defeated by system prompt updates.
|
|
668
|
+
*/
|
|
669
|
+
function findCommonPrefixLength(a, b) {
|
|
670
|
+
const aNonSys = filterNonSystem(a);
|
|
671
|
+
const bNonSys = filterNonSystem(b);
|
|
672
|
+
const max = Math.min(aNonSys.length, bNonSys.length);
|
|
673
|
+
for (let i = 0; i < max; i++) {
|
|
674
|
+
if (messageFingerprint(aNonSys[i]) !== messageFingerprint(bNonSys[i]))
|
|
675
|
+
return i;
|
|
676
|
+
}
|
|
677
|
+
return max;
|
|
678
|
+
}
|
|
679
|
+
function selectProjectedEventIds(currentMessages, currentEventIds, trimmedMessages) {
|
|
680
|
+
if (trimmedMessages.length === 0)
|
|
681
|
+
return [];
|
|
682
|
+
const trimmedFingerprints = trimmedMessages.map(messageFingerprint);
|
|
683
|
+
const result = [];
|
|
684
|
+
let needle = 0;
|
|
685
|
+
for (let i = 0; i < currentMessages.length && needle < trimmedFingerprints.length; i++) {
|
|
686
|
+
if (messageFingerprint(currentMessages[i]) !== trimmedFingerprints[needle])
|
|
687
|
+
continue;
|
|
688
|
+
result.push(currentEventIds[i]);
|
|
689
|
+
needle++;
|
|
690
|
+
}
|
|
691
|
+
return result;
|
|
692
|
+
}
|
|
693
|
+
function buildCanonicalSessionEnvelope(options) {
|
|
694
|
+
const existing = options.existing;
|
|
695
|
+
// Callers pass pre-sanitized messages + pre-captured ingress times.
|
|
696
|
+
const currentIngressTimes = options.currentIngressTimes ?? options.currentMessages.map(getIngressTime);
|
|
697
|
+
const previousMessages = options.previousMessages;
|
|
698
|
+
const currentMessages = options.currentMessages;
|
|
699
|
+
const trimmedMessages = options.trimmedMessages;
|
|
700
|
+
const previousProjectionIds = existing?.projection.eventIds.length
|
|
701
|
+
? [...existing.projection.eventIds]
|
|
702
|
+
: existing?.events.map((event) => event.id) ?? [];
|
|
703
|
+
// Compare only non-system messages to find the common prefix.
|
|
704
|
+
// System messages change every turn (live world-state in system prompt)
|
|
705
|
+
// and must not defeat prefix matching of the actual conversation.
|
|
706
|
+
const nonSystemPrefix = findCommonPrefixLength(previousMessages, currentMessages);
|
|
707
|
+
// Build a lookup of non-system previous projection IDs.
|
|
708
|
+
const prevNonSystemIds = [];
|
|
709
|
+
for (let i = 0; i < previousMessages.length; i++) {
|
|
710
|
+
if (messageRole(previousMessages[i]) !== "system") {
|
|
711
|
+
prevNonSystemIds.push(previousProjectionIds[i]);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
// Walk currentMessages and build currentEventIds + new events.
|
|
715
|
+
// Non-system messages within the prefix reuse old event IDs.
|
|
716
|
+
// System messages and post-prefix messages get new events.
|
|
717
|
+
const events = [...(existing?.events ?? [])];
|
|
718
|
+
const currentEventIds = [];
|
|
719
|
+
let nonSystemSeen = 0;
|
|
720
|
+
for (let i = 0; i < currentMessages.length; i++) {
|
|
721
|
+
const role = messageRole(currentMessages[i]);
|
|
722
|
+
const isSystem = role === "system";
|
|
723
|
+
const inPrefix = !isSystem && nonSystemSeen < nonSystemPrefix;
|
|
724
|
+
if (inPrefix) {
|
|
725
|
+
// Reuse existing event ID for this matched non-system message
|
|
726
|
+
currentEventIds.push(prevNonSystemIds[nonSystemSeen]);
|
|
727
|
+
nonSystemSeen++;
|
|
728
|
+
}
|
|
729
|
+
else if (isSystem && i < previousMessages.length
|
|
730
|
+
&& messageRole(previousMessages[i]) === "system"
|
|
731
|
+
&& messageFingerprint(currentMessages[i]) === messageFingerprint(previousMessages[i])) {
|
|
732
|
+
// System message at same position with identical content -- reuse event ID
|
|
733
|
+
currentEventIds.push(previousProjectionIds[i]);
|
|
734
|
+
}
|
|
735
|
+
else {
|
|
736
|
+
if (!isSystem)
|
|
737
|
+
nonSystemSeen++;
|
|
738
|
+
// Create a new event
|
|
739
|
+
const event = buildEventFromMessage(currentMessages[i], events.length + 1, options.recordedAt, "live", null, null, currentIngressTimes[i]);
|
|
740
|
+
events.push(event);
|
|
741
|
+
currentEventIds.push(event.id);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
const projectionEventIds = selectProjectedEventIds(currentMessages, currentEventIds, trimmedMessages);
|
|
745
|
+
// Prune events: only keep events whose IDs are in the projection.
|
|
746
|
+
// Events not in projection are returned as evicted for archiving.
|
|
747
|
+
const projectionIdSet = new Set(projectionEventIds);
|
|
748
|
+
const prunedEvents = events.filter((event) => projectionIdSet.has(event.id));
|
|
749
|
+
const evictedEvents = events.filter((event) => !projectionIdSet.has(event.id));
|
|
750
|
+
return {
|
|
751
|
+
envelope: {
|
|
752
|
+
version: 2,
|
|
753
|
+
events: prunedEvents,
|
|
754
|
+
projection: {
|
|
755
|
+
eventIds: projectionEventIds,
|
|
756
|
+
trimmed: projectionEventIds.length < currentEventIds.length,
|
|
757
|
+
maxTokens: options.projectionBasis.maxTokens,
|
|
758
|
+
contextMargin: options.projectionBasis.contextMargin,
|
|
759
|
+
inputTokens: options.projectionBasis.inputTokens,
|
|
760
|
+
projectedAt: options.recordedAt,
|
|
761
|
+
},
|
|
762
|
+
lastUsage: normalizeUsage(options.lastUsage),
|
|
763
|
+
state: normalizeContinuityState(options.state),
|
|
764
|
+
},
|
|
765
|
+
evictedEvents,
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Load full event history from both the pruned envelope and the NDJSON archive.
|
|
770
|
+
* Returns all events deduplicated by id and sorted by sequence.
|
|
771
|
+
* Corrupted archive lines are silently skipped.
|
|
772
|
+
*/
|
|
773
|
+
function loadFullEventHistory(sessPath) {
|
|
774
|
+
const envelope = loadSessionEnvelopeFile(sessPath);
|
|
775
|
+
if (!envelope)
|
|
776
|
+
return [];
|
|
777
|
+
const envelopeEvents = envelope.events;
|
|
778
|
+
const archivePath = sessPath.replace(/\.json$/, ".archive.ndjson");
|
|
779
|
+
let archiveEvents = [];
|
|
780
|
+
try {
|
|
781
|
+
const raw = fs.readFileSync(archivePath, "utf-8");
|
|
782
|
+
const lines = raw.split("\n");
|
|
783
|
+
for (const line of lines) {
|
|
784
|
+
const trimmed = line.trim();
|
|
785
|
+
if (trimmed.length === 0)
|
|
786
|
+
continue;
|
|
787
|
+
try {
|
|
788
|
+
const event = JSON.parse(trimmed);
|
|
789
|
+
if (event && typeof event.id === "string" && typeof event.sequence === "number") {
|
|
790
|
+
archiveEvents.push(event);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
catch {
|
|
794
|
+
// Skip corrupted lines
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
catch {
|
|
799
|
+
// Archive file doesn't exist or can't be read -- that's fine
|
|
800
|
+
}
|
|
801
|
+
// Merge, deduplicate by id, sort by sequence
|
|
802
|
+
const seen = new Set();
|
|
803
|
+
const merged = [];
|
|
804
|
+
for (const event of [...archiveEvents, ...envelopeEvents]) {
|
|
805
|
+
if (seen.has(event.id))
|
|
806
|
+
continue;
|
|
807
|
+
seen.add(event.id);
|
|
808
|
+
merged.push(event);
|
|
809
|
+
}
|
|
810
|
+
merged.sort((a, b) => a.sequence - b.sequence);
|
|
811
|
+
return merged;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Append evicted events to an NDJSON archive file.
|
|
815
|
+
* The archive path is derived from the session path by replacing .json with .archive.ndjson.
|
|
816
|
+
* Each event is written as a single JSON line. The file is appended to, not overwritten.
|
|
817
|
+
* Failures are logged and swallowed -- archive write must never crash the persist path.
|
|
818
|
+
*/
|
|
819
|
+
function appendEvictedToArchive(sessPath, evictedEvents) {
|
|
820
|
+
if (evictedEvents.length === 0)
|
|
821
|
+
return;
|
|
822
|
+
const archivePath = sessPath.replace(/\.json$/, ".archive.ndjson");
|
|
823
|
+
try {
|
|
824
|
+
const ndjson = evictedEvents.map((event) => JSON.stringify(event)).join("\n") + "\n";
|
|
825
|
+
fs.appendFileSync(archivePath, ndjson);
|
|
826
|
+
}
|
|
827
|
+
catch (err) {
|
|
828
|
+
(0, runtime_1.emitNervesEvent)({
|
|
829
|
+
level: "warn",
|
|
830
|
+
component: "heart",
|
|
831
|
+
event: "heart.archive_write_error",
|
|
832
|
+
message: "failed to write evicted events to archive",
|
|
833
|
+
meta: {
|
|
834
|
+
archivePath,
|
|
835
|
+
eventCount: evictedEvents.length,
|
|
836
|
+
/* v8 ignore next -- defensive: Node fs always throws Error instances @preserve */
|
|
837
|
+
error: err instanceof Error ? err.message : String(err),
|
|
838
|
+
},
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
function appendSyntheticAssistantEvent(envelope, content, recordedAt) {
|
|
843
|
+
const sequence = envelope.events.length + 1;
|
|
844
|
+
const event = buildEventFromMessage({ role: "assistant", content }, sequence, recordedAt, "synthetic", null, null);
|
|
845
|
+
return {
|
|
846
|
+
...envelope,
|
|
847
|
+
events: [...envelope.events, event],
|
|
848
|
+
projection: {
|
|
849
|
+
...envelope.projection,
|
|
850
|
+
eventIds: [...envelope.projection.eventIds, event.id],
|
|
851
|
+
projectedAt: recordedAt,
|
|
852
|
+
trimmed: false,
|
|
853
|
+
},
|
|
854
|
+
};
|
|
855
|
+
}
|