nova-personal-agent-server 0.4.1 → 1.0.2
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/LICENSE +674 -201
- package/README.md +10 -0
- package/bin/nova-space-host.mjs +4 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
- package/node_modules/@nova-personal-agent/relay/package.json +1 -0
- package/package.json +11 -4
- package/runtime/dist/src/cascaded-text-provider.js +8 -3
- package/runtime/dist/src/composition/assembly.js +133 -35
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
- package/runtime/dist/src/composition/production-composition.js +57 -21
- package/runtime/dist/src/composition/realtime-assembly.js +160 -52
- package/runtime/dist/src/composition/soul-context.js +22 -0
- package/runtime/dist/src/config/capability-registry.js +48 -3
- package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
- package/runtime/dist/src/config/config.js +541 -128
- package/runtime/dist/src/config/credential-rotation.js +26 -0
- package/runtime/dist/src/config/data-root.js +764 -0
- package/runtime/dist/src/config/diagnostics.js +3 -1
- package/runtime/dist/src/config/environment-contract.js +190 -188
- package/runtime/dist/src/config/model-routes.js +140 -0
- package/runtime/dist/src/config/voice-credentials.js +55 -0
- package/runtime/dist/src/connectors/composio/index.js +9 -0
- package/runtime/dist/src/connectors/feishu/index.js +258 -44
- package/runtime/dist/src/connectors/macos/mail.js +7 -3
- package/runtime/dist/src/connectors/macos/reader.js +3 -1
- package/runtime/dist/src/conversation-voice-provider.js +5 -2
- package/runtime/dist/src/core/causal-runtime.js +38 -3
- package/runtime/dist/src/core/context-view.js +7 -0
- package/runtime/dist/src/core/guards.js +32 -0
- package/runtime/dist/src/core/runtime.js +3 -0
- package/runtime/dist/src/core/schedule-tools.js +2 -2
- package/runtime/dist/src/core/source-processing-instructions.js +2 -2
- package/runtime/dist/src/core/source-processing-tools.js +3 -1
- package/runtime/dist/src/core/tool-schema.js +42 -7
- package/runtime/dist/src/desktop/desktop-camera.js +3 -5
- package/runtime/dist/src/desktop/desktop-control.js +41 -8
- package/runtime/dist/src/desktop/desktop-session.js +90 -19
- package/runtime/dist/src/desktop/desktop-wire.js +5 -7
- package/runtime/dist/src/desktop/startup-error.js +18 -16
- package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
- package/runtime/dist/src/desktop-entry.js +6 -2
- package/runtime/dist/src/desktop.js +5 -1
- package/runtime/dist/src/device/attempt.js +65 -0
- package/runtime/dist/src/device/authority.js +159 -0
- package/runtime/dist/src/device/gateway.js +87 -0
- package/runtime/dist/src/device/ledger.js +91 -0
- package/runtime/dist/src/device/ownership.js +92 -0
- package/runtime/dist/src/device/port.js +2 -0
- package/runtime/dist/src/device/schedule-ownership.js +103 -0
- package/runtime/dist/src/executors/acp/transport.js +2 -0
- package/runtime/dist/src/executors/browser.js +4 -3
- package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
- package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
- package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
- package/runtime/dist/src/executors/codex/common.js +1 -1
- package/runtime/dist/src/executors/codex/contract.js +12 -16
- package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
- package/runtime/dist/src/executors/codex/factory.js +54 -32
- package/runtime/dist/src/executors/codex/host-config.js +69 -20
- package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
- package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
- package/runtime/dist/src/executors/codex/process-owner.js +4 -6
- package/runtime/dist/src/executors/codex/production-host.js +33 -34
- package/runtime/dist/src/executors/codex/protocol.js +9 -14
- package/runtime/dist/src/executors/codex/session-title.js +6 -8
- package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
- package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
- package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
- package/runtime/dist/src/executors/coding/intake.js +12 -7
- package/runtime/dist/src/executors/computer-backend.js +18 -10
- package/runtime/dist/src/executors/computer-config.js +32 -0
- package/runtime/dist/src/executors/computer-device.js +68 -16
- package/runtime/dist/src/executors/computer-worker.js +18 -6
- package/runtime/dist/src/executors/computer.js +29 -56
- package/runtime/dist/src/executors/device-lock.js +14 -5
- package/runtime/dist/src/executors/gui-execution.js +2 -0
- package/runtime/dist/src/executors/index.js +0 -1
- package/runtime/dist/src/executors/mobile.js +9 -8
- package/runtime/dist/src/executors/native-process.js +4 -0
- package/runtime/dist/src/executors/search.js +3 -5
- package/runtime/dist/src/executors/task-resources.js +21 -0
- package/runtime/dist/src/executors/watcher.js +2 -4
- package/runtime/dist/src/experience/host.js +179 -0
- package/runtime/dist/src/index.js +2 -0
- package/runtime/dist/src/knowledge/assembly.js +3 -4
- package/runtime/dist/src/knowledge/embeddings.js +50 -34
- package/runtime/dist/src/knowledge/service.js +1 -0
- package/runtime/dist/src/knowledge/store-client.js +1 -6
- package/runtime/dist/src/knowledge/store-worker.js +1 -3
- package/runtime/dist/src/mem0/resource.js +25 -0
- package/runtime/dist/src/mem0/store-worker.js +234 -21
- package/runtime/dist/src/memory/consumer.js +31 -0
- package/runtime/dist/src/memory/engine-worker.js +210 -0
- package/runtime/dist/src/memory/entry.js +8 -1
- package/runtime/dist/src/memory/explicit-memory.js +20 -0
- package/runtime/dist/src/memory/factory.js +30 -15
- package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
- package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
- package/runtime/dist/src/memory/prerecall-port.js +27 -0
- package/runtime/dist/src/memory/prerecall.js +1 -1
- package/runtime/dist/src/memory/production-engine.js +151 -0
- package/runtime/dist/src/memory/provenance.js +1 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
- package/runtime/dist/src/memory/retrieval.js +107 -22
- package/runtime/dist/src/memory/sensitivity.js +6 -2
- package/runtime/dist/src/memory/source-retrieval.js +11 -0
- package/runtime/dist/src/memory/tool-capabilities.js +46 -0
- package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
- package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
- package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
- package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
- package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
- package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
- package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
- package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
- package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
- package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
- package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
- package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
- package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
- package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
- package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
- package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
- package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
- package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
- package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
- package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
- package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
- package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
- package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
- package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
- package/runtime/dist/src/memory-ledger/store-client.js +235 -37
- package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
- package/runtime/dist/src/memory-ledger/store.js +91 -1
- package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
- package/runtime/dist/src/memory-substrate/diary.js +27 -0
- package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
- package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
- package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
- package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
- package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
- package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
- package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
- package/runtime/dist/src/memory-substrate/migration.js +2 -0
- package/runtime/dist/src/memory-substrate/purge.js +12 -2
- package/runtime/dist/src/memory-substrate/resource.js +514 -129
- package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
- package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
- package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
- package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
- package/runtime/dist/src/memory-substrate/source-state.js +8 -0
- package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
- package/runtime/dist/src/memory-substrate/store.js +125 -23
- package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
- package/runtime/dist/src/model/goal-writer.js +80 -0
- package/runtime/dist/src/model/jev-client.js +24 -13
- package/runtime/dist/src/model/model-adapters.js +2 -3
- package/runtime/dist/src/model/model-catalog.js +80 -0
- package/runtime/dist/src/model/model-gateway.js +47 -18
- package/runtime/dist/src/model/model-purpose.js +3 -4
- package/runtime/dist/src/model/personal-writer.js +536 -44
- package/runtime/dist/src/model/proactivity.js +50 -6
- package/runtime/dist/src/model/responses-model-gateway.js +59 -0
- package/runtime/dist/src/model/task-verifier.js +3 -3
- package/runtime/dist/src/model/timeline-anchors.js +77 -0
- package/runtime/dist/src/model/timeline-perspective.js +13 -0
- package/runtime/dist/src/model/timeline-selection.js +182 -0
- package/runtime/dist/src/model/understanding-writer.js +27 -0
- package/runtime/dist/src/model/vision-capability.js +3 -1
- package/runtime/dist/src/model/workbench-writer.js +96 -0
- package/runtime/dist/src/news/feeds.js +6 -10
- package/runtime/dist/src/news/interests.js +23 -0
- package/runtime/dist/src/news/service.js +87 -31
- package/runtime/dist/src/news/sources.json +116 -0
- package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
- package/runtime/dist/src/notifications/content.js +41 -0
- package/runtime/dist/src/notifications/contracts.js +4 -2
- package/runtime/dist/src/notifications/feed.js +6 -2
- package/runtime/dist/src/notifications/service.js +27 -14
- package/runtime/dist/src/notifications/store.js +3 -1
- package/runtime/dist/src/personal-agent/app-context.js +39 -4
- package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
- package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
- package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
- package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
- package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
- package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
- package/runtime/dist/src/personal-agent/contracts.js +24 -4
- package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
- package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
- package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
- package/runtime/dist/src/personal-agent/conversations.js +71 -15
- package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
- package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
- package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
- package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2379 -223
- package/runtime/dist/src/personal-agent/identity-context.js +33 -0
- package/runtime/dist/src/personal-agent/life.js +129 -11
- package/runtime/dist/src/personal-agent/local-shell.js +181 -0
- package/runtime/dist/src/personal-agent/local-tools.js +234 -0
- package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
- package/runtime/dist/src/personal-agent/project-digests.js +7 -3
- package/runtime/dist/src/personal-agent/project-history.js +36 -0
- package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
- package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
- package/runtime/dist/src/personal-agent/sources.js +9 -1
- package/runtime/dist/src/personal-agent/store.js +124 -14
- package/runtime/dist/src/personal-agent/task-loop.js +3 -0
- package/runtime/dist/src/personal-agent/tasks.js +16 -4
- package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
- package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
- package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
- package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
- package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
- package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
- package/runtime/dist/src/personal-agent/understanding.js +7 -22
- package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
- package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
- package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
- package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
- package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
- package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
- package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
- package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
- package/runtime/dist/src/projects/project-native-resource.js +10 -8
- package/runtime/dist/src/projects/project-store.js +36 -4
- package/runtime/dist/src/realtime/bridge.js +77 -8
- package/runtime/dist/src/realtime/capabilities.js +19 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
- package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
- package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
- package/runtime/dist/src/realtime/evidence.js +1 -1
- package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
- package/runtime/dist/src/realtime/gemini.js +14 -3
- package/runtime/dist/src/realtime/host-delivery.js +37 -4
- package/runtime/dist/src/realtime/protocol.js +18 -3
- package/runtime/dist/src/realtime/provider-projection.js +4 -1
- package/runtime/dist/src/realtime/provider-session.js +73 -16
- package/runtime/dist/src/realtime/qwen-transport.js +35 -4
- package/runtime/dist/src/realtime/qwen.js +144 -9
- package/runtime/dist/src/realtime/service-state.js +0 -1
- package/runtime/dist/src/realtime/service.js +93 -7
- package/runtime/dist/src/realtime/session.js +39 -32
- package/runtime/dist/src/realtime/sglang-native.js +214 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
- package/runtime/dist/src/realtime/telemetry.js +6 -3
- package/runtime/dist/src/realtime/tool-continuations.js +84 -7
- package/runtime/dist/src/realtime/transport.js +17 -0
- package/runtime/dist/src/realtime/usage.js +33 -17
- package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
- package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
- package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
- package/runtime/dist/src/server/aoq-chat-server.js +1 -1
- package/runtime/dist/src/server/client-server.js +21 -0
- package/runtime/dist/src/server-entry.js +3 -0
- package/runtime/dist/src/space-host/admin-socket.js +115 -0
- package/runtime/dist/src/space-host/audio-owner.js +44 -0
- package/runtime/dist/src/space-host/cli.js +195 -0
- package/runtime/dist/src/space-host/config.js +247 -0
- package/runtime/dist/src/space-host/context-input.js +12 -0
- package/runtime/dist/src/space-host/contracts.js +10 -0
- package/runtime/dist/src/space-host/host-admin.js +114 -0
- package/runtime/dist/src/space-host/key-delivery.js +28 -0
- package/runtime/dist/src/space-host/mobile-tools.js +9 -0
- package/runtime/dist/src/space-host/model-settings.js +213 -0
- package/runtime/dist/src/space-host/projection.js +37 -0
- package/runtime/dist/src/space-host/push.js +137 -0
- package/runtime/dist/src/space-host/relay-transport.js +55 -0
- package/runtime/dist/src/space-host/service.js +841 -0
- package/runtime/dist/src/space-host/voice-crypto.js +240 -0
- package/runtime/dist/src/space-host/voice.js +600 -0
- package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
- package/runtime/dist/src/storage/private-database.js +7 -10
- package/runtime/dist/src/text/unicode-normalize.js +5 -1
- package/runtime/dist/src/understanding/candidates.js +8 -10
- package/runtime/dist/src/understanding/fixture.js +1 -1
- package/runtime/dist/src/understanding/pipeline.js +4 -4
- package/runtime/dist/src/usage/context.js +23 -0
- package/runtime/dist/src/usage/index.js +4 -0
- package/runtime/dist/src/usage/ledger-worker.js +90 -0
- package/runtime/dist/src/usage/ledger.js +74 -0
- package/runtime/dist/src/usage/model-call.js +63 -0
- package/runtime/dist/src/usage/pricing.js +68 -0
- package/runtime/dist/src/usage/summary.js +69 -0
- package/runtime/dist/src/voicemem/store-client.js +104 -21
- package/runtime/dist/src/voicemem/store-worker.js +5 -8
- package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
- package/src/command.mjs +8 -1
- package/runtime/dist/src/executors/autoglm.js +0 -376
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { beginModelUsage } from '../usage/model-call.js';
|
|
1
2
|
import { SensitiveContentPolicy, SensitivePathPolicy } from '../memory/sensitivity.js';
|
|
3
|
+
import { rotatedCredential } from '../config/credential-rotation.js';
|
|
2
4
|
const MAX_BATCH = 10;
|
|
3
5
|
const MAX_INPUTS = 1_000;
|
|
4
6
|
const MAX_INPUT_CODE_POINTS = 32_768;
|
|
@@ -19,6 +21,7 @@ export class EmbeddingProviderFailure extends Error {
|
|
|
19
21
|
export class DashScopeEmbeddingProvider {
|
|
20
22
|
id;
|
|
21
23
|
dims;
|
|
24
|
+
#onUsage;
|
|
22
25
|
#apiKey;
|
|
23
26
|
#model;
|
|
24
27
|
#endpoint;
|
|
@@ -42,6 +45,7 @@ export class DashScopeEmbeddingProvider {
|
|
|
42
45
|
|| base.password !== '' || base.search !== '' || base.hash !== '') {
|
|
43
46
|
throw new EmbeddingProviderFailure('configuration');
|
|
44
47
|
}
|
|
48
|
+
this.#onUsage = options.onUsage;
|
|
45
49
|
this.#apiKey = options.apiKey;
|
|
46
50
|
this.#model = model;
|
|
47
51
|
this.dims = dims;
|
|
@@ -73,47 +77,59 @@ export class DashScopeEmbeddingProvider {
|
|
|
73
77
|
}
|
|
74
78
|
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
|
75
79
|
const combined = signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
|
|
76
|
-
|
|
80
|
+
const finishUsage = beginModelUsage(this.#onUsage, this.#endpoint, this.#model, 'embedding');
|
|
81
|
+
let rawUsage;
|
|
82
|
+
let succeeded = false;
|
|
77
83
|
try {
|
|
78
|
-
response
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
if (signal?.aborted === true)
|
|
88
|
-
signal.throwIfAborted();
|
|
89
|
-
throw new EmbeddingProviderFailure(timeout.aborted ? 'timeout' : 'transport');
|
|
90
|
-
}
|
|
91
|
-
try {
|
|
92
|
-
if (response.status >= 300 && response.status < 400) {
|
|
93
|
-
void response.body?.cancel();
|
|
94
|
-
throw new EmbeddingProviderFailure('redirect');
|
|
84
|
+
let response;
|
|
85
|
+
try {
|
|
86
|
+
response = await this.#fetch(this.#endpoint, {
|
|
87
|
+
method: 'POST',
|
|
88
|
+
headers: { Authorization: `Bearer ${rotatedCredential(this.#apiKey)}`, 'Content-Type': 'application/json' },
|
|
89
|
+
body,
|
|
90
|
+
redirect: 'manual',
|
|
91
|
+
signal: combined,
|
|
92
|
+
});
|
|
95
93
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
94
|
+
catch {
|
|
95
|
+
if (signal?.aborted === true)
|
|
96
|
+
signal.throwIfAborted();
|
|
97
|
+
throw new EmbeddingProviderFailure(timeout.aborted ? 'timeout' : 'transport');
|
|
100
98
|
}
|
|
101
|
-
const bytes = await readBounded(response);
|
|
102
|
-
let parsed;
|
|
103
99
|
try {
|
|
104
|
-
|
|
100
|
+
if (response.status >= 300 && response.status < 400) {
|
|
101
|
+
void response.body?.cancel();
|
|
102
|
+
throw new EmbeddingProviderFailure('redirect');
|
|
103
|
+
}
|
|
104
|
+
if (!response.ok) {
|
|
105
|
+
void response.body?.cancel();
|
|
106
|
+
throw new EmbeddingProviderFailure(response.status === 401 || response.status === 403
|
|
107
|
+
? 'authentication' : response.status === 429 ? 'rate_limited' : 'provider_error');
|
|
108
|
+
}
|
|
109
|
+
const bytes = await readBounded(response);
|
|
110
|
+
let parsed;
|
|
111
|
+
try {
|
|
112
|
+
parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
throw new EmbeddingProviderFailure('malformed_response');
|
|
116
|
+
}
|
|
117
|
+
if (plainObject(parsed))
|
|
118
|
+
rawUsage = parsed.usage;
|
|
119
|
+
const vectors = parseVectors(parsed, texts.length, this.dims, this.#model);
|
|
120
|
+
succeeded = true;
|
|
121
|
+
return vectors;
|
|
105
122
|
}
|
|
106
|
-
catch {
|
|
107
|
-
|
|
123
|
+
catch (cause) {
|
|
124
|
+
if (signal?.aborted === true)
|
|
125
|
+
signal.throwIfAborted();
|
|
126
|
+
if (cause instanceof EmbeddingProviderFailure)
|
|
127
|
+
throw cause;
|
|
128
|
+
throw new EmbeddingProviderFailure(timeout.aborted ? 'timeout' : 'transport');
|
|
108
129
|
}
|
|
109
|
-
return parseVectors(parsed, texts.length, this.dims, this.#model);
|
|
110
130
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
signal.throwIfAborted();
|
|
114
|
-
if (cause instanceof EmbeddingProviderFailure)
|
|
115
|
-
throw cause;
|
|
116
|
-
throw new EmbeddingProviderFailure(timeout.aborted ? 'timeout' : 'transport');
|
|
131
|
+
finally {
|
|
132
|
+
finishUsage(rawUsage, signal?.aborted ? 'cancelled' : succeeded ? 'success' : 'error');
|
|
117
133
|
}
|
|
118
134
|
}
|
|
119
135
|
}
|
|
@@ -65,6 +65,7 @@ export class KnowledgeService {
|
|
|
65
65
|
for (const active of this.#syncing.values())
|
|
66
66
|
active.abort.abort();
|
|
67
67
|
await Promise.allSettled([...this.#syncing.values()].map(active => active.done));
|
|
68
|
+
await this.#binding?.catch(() => { });
|
|
68
69
|
await this.#store.close();
|
|
69
70
|
}
|
|
70
71
|
purgeEvidence(ids) { return this.#store.purgeEvidence(ids); }
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Worker } from 'node:worker_threads';
|
|
2
|
+
import { hasOnlyKeys, isRecord } from '../core/guards.js';
|
|
2
3
|
export class KnowledgeStoreClientError extends Error {
|
|
3
4
|
code;
|
|
4
5
|
constructor(code) {
|
|
@@ -176,10 +177,4 @@ function isStoreCode(value) {
|
|
|
176
177
|
function positiveInteger(value) {
|
|
177
178
|
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
|
178
179
|
}
|
|
179
|
-
function isRecord(value) {
|
|
180
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
181
|
-
}
|
|
182
|
-
function hasOnlyKeys(value, allowed) {
|
|
183
|
-
return Object.keys(value).every(key => allowed.includes(key));
|
|
184
|
-
}
|
|
185
180
|
//# sourceMappingURL=store-client.js.map
|
|
@@ -4,6 +4,7 @@ import { isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
|
4
4
|
import { DatabaseSync } from 'node:sqlite';
|
|
5
5
|
import { SensitiveContentPolicy, SensitivePathPolicy } from '../memory/sensitivity.js';
|
|
6
6
|
import { preparePrivateDatabasePath, PrivateDatabaseError } from '../storage/private-database.js';
|
|
7
|
+
import { isRecord } from '../core/guards.js';
|
|
7
8
|
const MAX_SOURCE_BYTES = 10 * 1024 * 1024;
|
|
8
9
|
const MAX_CHUNKS = 20_000;
|
|
9
10
|
const DEFAULT_MAX_SOURCES = 100;
|
|
@@ -836,8 +837,5 @@ function safeOutputUrl(value) {
|
|
|
836
837
|
function redactPathSpans(value) {
|
|
837
838
|
return value.replace(/(?:\\\\[^\s<>"'`()\[\]{},;!?]+|[A-Za-z]:[\\/][^\s<>"'`()\[\]{},;!?]+|\/(?!\/)[^\s<>"'`()\[\]{},;!?]+)/gu, '[path]');
|
|
838
839
|
}
|
|
839
|
-
function isRecord(value) {
|
|
840
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
841
|
-
}
|
|
842
840
|
function invalid() { throw new StoreError('STORE_INVALID_INPUT'); }
|
|
843
841
|
//# sourceMappingURL=store-worker.js.map
|
|
@@ -23,6 +23,31 @@ export function createMem0PersonalMemory(options) {
|
|
|
23
23
|
},
|
|
24
24
|
});
|
|
25
25
|
return {
|
|
26
|
+
maxRecallLimit: store.maxRecallLimit,
|
|
27
|
+
recallEngine: 'mem0',
|
|
28
|
+
requiresConversationConsumer: true,
|
|
29
|
+
capabilities: () => ({ list: true, get: true, correct: true, forgetEntry: true, forgetSource: true }),
|
|
30
|
+
get: id => store.get(id),
|
|
31
|
+
getMany: ids => store.getMem0Many(ids),
|
|
32
|
+
list: options => store.list(options),
|
|
33
|
+
correct: (...args) => store.correct(...args),
|
|
34
|
+
forgetEntry: (...args) => store.forgetEntry(...args),
|
|
35
|
+
readEvidence: id => store.readMem0Evidence(id),
|
|
36
|
+
canReadConversationEvidence: (id, consumer) => store.canReadMem0ConversationEvidence(id, consumer),
|
|
37
|
+
forgetSource: ref => store.forgetSource(ref),
|
|
38
|
+
forgetSources: async (refs) => {
|
|
39
|
+
let failed = false;
|
|
40
|
+
for (const ref of refs) {
|
|
41
|
+
try {
|
|
42
|
+
await store.forgetSource(ref);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
failed = true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (failed)
|
|
49
|
+
throw new PersonalMemoryError('error');
|
|
50
|
+
},
|
|
26
51
|
open: () => store.open(),
|
|
27
52
|
inspect: query => store.inspectStore(query),
|
|
28
53
|
close: () => store.close(),
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { MemoryListOptionsSchema, MemorySourceRefSchema } from '../memory/entry.js';
|
|
1
3
|
import { memoryInspectionQuerySchema } from '../memory/personal-memory-inspection.js';
|
|
2
4
|
import { existsSync } from 'node:fs';
|
|
3
5
|
import { isAbsolute, join, resolve } from 'node:path';
|
|
@@ -30,7 +32,7 @@ port.on('message', (value) => {
|
|
|
30
32
|
port.postMessage({ kind: 'protocol_error' });
|
|
31
33
|
return;
|
|
32
34
|
}
|
|
33
|
-
if (
|
|
35
|
+
if (['recall', 'get', 'getMany', 'list', 'readEvidence', 'canReadConversationEvidence', 'inspect'].includes(request.operation)) {
|
|
34
36
|
void handle(request);
|
|
35
37
|
return;
|
|
36
38
|
}
|
|
@@ -40,12 +42,13 @@ async function handle(request) {
|
|
|
40
42
|
try {
|
|
41
43
|
const result = await execute(request);
|
|
42
44
|
port.postMessage({ kind: 'response', request_id: request.request_id, ok: true, result });
|
|
43
|
-
if (request.operation === 'open' || request.operation === 'remember' ||
|
|
45
|
+
if (request.operation === 'open' || request.operation === 'remember' || ['forget', 'forgetSource', 'forgetEntry'].includes(request.operation))
|
|
44
46
|
scheduleDrain();
|
|
45
47
|
}
|
|
46
48
|
catch (error) {
|
|
47
49
|
const code = error instanceof StoreError || error instanceof PrivateDatabaseError ? error.code
|
|
48
|
-
: request.operation === 'recall' ? 'STORE_RECALL_FAILED'
|
|
50
|
+
: request.operation === 'recall' ? 'STORE_RECALL_FAILED'
|
|
51
|
+
: ['get', 'getMany', 'list', 'readEvidence', 'canReadConversationEvidence', 'inspect'].includes(request.operation) ? 'STORE_READ_FAILED' : 'STORE_WRITE_FAILED';
|
|
49
52
|
port.postMessage({ kind: 'response', request_id: request.request_id, ok: false, error_code: code });
|
|
50
53
|
}
|
|
51
54
|
if (request.operation === 'close')
|
|
@@ -69,14 +72,40 @@ async function execute(request) {
|
|
|
69
72
|
return inspect(request);
|
|
70
73
|
if (request.operation === 'remember')
|
|
71
74
|
return remember(request);
|
|
72
|
-
if (request.operation === '
|
|
73
|
-
|
|
75
|
+
if (request.operation === 'get')
|
|
76
|
+
return get(request.id);
|
|
77
|
+
if (request.operation === 'getMany') {
|
|
78
|
+
if (!Array.isArray(request.ids) || request.ids.length > 100 || !request.ids.every(id => text(id, 256)))
|
|
74
79
|
throw new StoreError('STORE_INVALID_INPUT');
|
|
80
|
+
const entries = await Promise.all(request.ids.map(id => get(id)));
|
|
81
|
+
return entries.map(entry => entry?.evidence_refs?.every(id => source(id)?.state === 'learned') ? entry : null);
|
|
82
|
+
}
|
|
83
|
+
if (request.operation === 'list')
|
|
84
|
+
return list(request);
|
|
85
|
+
if (request.operation === 'correct' || request.operation === 'forgetEntry')
|
|
86
|
+
return mutateEntry(request);
|
|
87
|
+
if (request.operation === 'readEvidence')
|
|
88
|
+
return readEvidence(request.id);
|
|
89
|
+
if (request.operation === 'canReadConversationEvidence') {
|
|
90
|
+
if (!text(request.id, 256) || !text(request.consumer, 256))
|
|
91
|
+
return false;
|
|
92
|
+
const row = source(request.id);
|
|
93
|
+
return !!row && row.state !== 'forgotten' && !!data.conversationProviders?.includes(request.consumer)
|
|
94
|
+
&& JSON.parse(row.conversation_providers).includes(request.consumer);
|
|
95
|
+
}
|
|
96
|
+
if (request.operation === 'forget' || request.operation === 'forgetSource') {
|
|
97
|
+
const sourceId = request.operation === 'forgetSource' ? request.ref : request.sourceId;
|
|
98
|
+
if (!text(sourceId, 256))
|
|
99
|
+
throw new StoreError('STORE_INVALID_INPUT');
|
|
100
|
+
// The durable intent is written first: a crash before the tombstone leaves a harmless flag,
|
|
101
|
+
// while a crash after it must never lose the physical-cleanup obligation.
|
|
102
|
+
markCompactionPending();
|
|
75
103
|
// Tombstone unknown ids too, so delayed admission cannot resurrect an explicitly deleted source.
|
|
76
104
|
ledger.prepare(`INSERT INTO sources (id,payload,state,recorded_at,cleaned) VALUES (?, '', 'forgotten', ?, 0)
|
|
77
|
-
ON CONFLICT(id) DO UPDATE SET payload='', state='forgotten', cleaned=0`).run(
|
|
78
|
-
|
|
79
|
-
|
|
105
|
+
ON CONFLICT(id) DO UPDATE SET payload='', state='forgotten', cleaned=0`).run(sourceId, new Date().toISOString());
|
|
106
|
+
ledger.prepare('DELETE FROM item_edits WHERE source_id=?').run(sourceId);
|
|
107
|
+
failed.delete(sourceId);
|
|
108
|
+
return request.operation === 'forgetSource' ? null : { state: 'forgotten', source_id: sourceId };
|
|
80
109
|
}
|
|
81
110
|
return recall(request);
|
|
82
111
|
}
|
|
@@ -98,12 +127,48 @@ async function inspect(request) {
|
|
|
98
127
|
if (ledger.prepare('SELECT state FROM sources WHERE id=?').get(row.id)?.state === 'forgotten')
|
|
99
128
|
continue;
|
|
100
129
|
const payload = JSON.parse(row.payload);
|
|
101
|
-
const facts = found.results.filter(item => item.metadata?.nova_source_id === row.id).map(item => item.
|
|
130
|
+
const facts = found.results.filter(item => item.metadata?.nova_source_id === row.id).map(item => project(item)).filter((entry) => entry !== null).map(entry => entry.content);
|
|
102
131
|
entries.push({ sourceId: row.id, state: row.state, recordedAt: row.recorded_at,
|
|
103
132
|
original: payload.text.slice(0, 1500), memories: facts.slice(0, 4).map(text => text.slice(0, 500)),
|
|
104
133
|
truncated: payload.text.length > 1500 || facts.length > 4 || facts.some(text => text.length > 500) });
|
|
105
134
|
}
|
|
106
|
-
return { engine: 'mem0', entries, next: rows.length > 10 ? rows[9].cursor : null };
|
|
135
|
+
return { engine: 'mem0', entries: entries.filter(entry => source(entry.sourceId)?.state !== 'forgotten'), next: rows.length > 10 ? rows[9].cursor : null };
|
|
136
|
+
}
|
|
137
|
+
const COMPACTION_KEY = 'compaction_pending';
|
|
138
|
+
function pendingCompaction() {
|
|
139
|
+
return ledger?.prepare('SELECT value FROM meta WHERE key=?').get(COMPACTION_KEY)?.value === '1';
|
|
140
|
+
}
|
|
141
|
+
function markCompactionPending() {
|
|
142
|
+
ledger?.prepare('INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value')
|
|
143
|
+
.run(COMPACTION_KEY, '1');
|
|
144
|
+
}
|
|
145
|
+
function clearCompactionPending() {
|
|
146
|
+
ledger?.prepare('DELETE FROM meta WHERE key=?').run(COMPACTION_KEY);
|
|
147
|
+
}
|
|
148
|
+
/** A deleted row's bytes stay in free pages and the WAL until every database is rebuilt. */
|
|
149
|
+
function compactStore() {
|
|
150
|
+
if (!ledger)
|
|
151
|
+
return;
|
|
152
|
+
ledger.exec('PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON');
|
|
153
|
+
ledger.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get();
|
|
154
|
+
ledger.exec('VACUUM');
|
|
155
|
+
ledger.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get();
|
|
156
|
+
for (const name of ['vectors.db', 'vectors_entities.db']) {
|
|
157
|
+
const path = join(data.path, name);
|
|
158
|
+
if (!existsSync(path))
|
|
159
|
+
continue;
|
|
160
|
+
const database = new DatabaseSync(path);
|
|
161
|
+
try {
|
|
162
|
+
database.exec('PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON');
|
|
163
|
+
database.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get();
|
|
164
|
+
database.exec('VACUUM');
|
|
165
|
+
database.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get();
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
database.close();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
clearCompactionPending();
|
|
107
172
|
}
|
|
108
173
|
function open() {
|
|
109
174
|
if (ledger || closed)
|
|
@@ -119,8 +184,22 @@ function open() {
|
|
|
119
184
|
ledger = new DatabaseSync(join(data.path, 'ledger.db'));
|
|
120
185
|
ledger.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
|
|
121
186
|
CREATE TABLE IF NOT EXISTS owner (user_id TEXT PRIMARY KEY);
|
|
187
|
+
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
122
188
|
CREATE TABLE IF NOT EXISTS sources (id TEXT PRIMARY KEY, payload TEXT NOT NULL,
|
|
123
|
-
state TEXT NOT NULL CHECK(state IN ('pending','learned','forgotten')), recorded_at TEXT NOT NULL, cleaned INTEGER NOT NULL DEFAULT 0)
|
|
189
|
+
state TEXT NOT NULL CHECK(state IN ('pending','learned','forgotten')), recorded_at TEXT NOT NULL, cleaned INTEGER NOT NULL DEFAULT 0);
|
|
190
|
+
CREATE TABLE IF NOT EXISTS item_edits (id TEXT PRIMARY KEY, source_id TEXT NOT NULL, content TEXT NOT NULL,
|
|
191
|
+
version TEXT NOT NULL, status TEXT NOT NULL, user_source TEXT, cleaned INTEGER NOT NULL DEFAULT 0);`);
|
|
192
|
+
ledger.exec('BEGIN IMMEDIATE');
|
|
193
|
+
try {
|
|
194
|
+
if (!ledger.prepare('PRAGMA table_info(sources)').all().some(row => row.name === 'conversation_providers')) {
|
|
195
|
+
ledger.exec("ALTER TABLE sources ADD COLUMN conversation_providers TEXT NOT NULL DEFAULT '[]'");
|
|
196
|
+
}
|
|
197
|
+
ledger.exec('COMMIT');
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
ledger.exec('ROLLBACK');
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
124
203
|
learningLock = new DatabaseSync(join(data.path, 'learning-lock.db'));
|
|
125
204
|
learningLock.exec('PRAGMA busy_timeout=0');
|
|
126
205
|
const owner = ledger.prepare('SELECT user_id FROM owner').get();
|
|
@@ -129,11 +208,13 @@ function open() {
|
|
|
129
208
|
ledger.prepare('INSERT OR IGNORE INTO owner (user_id) VALUES (?)').run(data.userId);
|
|
130
209
|
secureSidecar(join(data.path, 'ledger.db'), '-wal');
|
|
131
210
|
secureSidecar(join(data.path, 'ledger.db'), '-shm');
|
|
211
|
+
// Compaction runs from the drain (after derived vectors are deleted), never on the open path:
|
|
212
|
+
// a synchronous VACUUM here can exceed the client's request deadline and leave it unopened.
|
|
132
213
|
sdk = new Memory({
|
|
133
214
|
disableHistory: true,
|
|
134
215
|
embedder: { provider: 'openai', config: { baseURL: data.embedding.baseUrl, apiKey: data.embedding.apiKey,
|
|
135
216
|
model: data.embedding.model, ...(data.embedding.dimensions === undefined ? {} : { embeddingDims: data.embedding.dimensions }) } },
|
|
136
|
-
llm: { provider: 'openai', config: { baseURL: data.embedding.baseUrl, apiKey: data.embedding.apiKey,
|
|
217
|
+
llm: { provider: 'openai', config: { baseURL: (data.extraction ?? data.embedding).baseUrl, apiKey: (data.extraction ?? data.embedding).apiKey,
|
|
137
218
|
model: data.extractionModel ?? 'unused', timeout: 30_000 } },
|
|
138
219
|
vectorStore: { provider: 'memory', config: { dbPath: join(data.path, 'vectors.db'), collectionName: 'nova_personal',
|
|
139
220
|
...(data.embedding.dimensions === undefined ? {} : { dimension: data.embedding.dimensions }) } },
|
|
@@ -167,12 +248,14 @@ function remember(request) {
|
|
|
167
248
|
if (previous) {
|
|
168
249
|
if (previous.payload !== payload)
|
|
169
250
|
throw new StoreError('STORE_INVALID_INPUT');
|
|
251
|
+
ledger.prepare("UPDATE sources SET conversation_providers=? WHERE id=? AND state!='forgotten' AND json_array_length(conversation_providers)=0")
|
|
252
|
+
.run(JSON.stringify(data.conversationProviders ?? []), request.sourceId);
|
|
170
253
|
return { state: previous.state, source_id: request.sourceId };
|
|
171
254
|
}
|
|
172
255
|
if (!data.extractionModel)
|
|
173
256
|
throw new StoreError('STORE_WRITE_FAILED');
|
|
174
|
-
ledger.prepare("INSERT OR IGNORE INTO sources (id,payload,state,recorded_at) VALUES (?,?,'pending'
|
|
175
|
-
.run(request.sourceId, payload, new Date().toISOString());
|
|
257
|
+
ledger.prepare("INSERT OR IGNORE INTO sources (id,payload,state,recorded_at,conversation_providers) VALUES (?,?,'pending',?,?)")
|
|
258
|
+
.run(request.sourceId, payload, new Date().toISOString(), JSON.stringify(data.conversationProviders ?? []));
|
|
176
259
|
const admitted = source(request.sourceId);
|
|
177
260
|
if (admitted.state !== 'forgotten' && admitted.payload !== payload)
|
|
178
261
|
throw new StoreError('STORE_INVALID_INPUT');
|
|
@@ -202,13 +285,106 @@ async function recall(request) {
|
|
|
202
285
|
if (!text(item.id, 256) || !text(item.memory, Number.MAX_SAFE_INTEGER) || !Number.isFinite(item.score))
|
|
203
286
|
throw new StoreError('STORE_RECALL_FAILED');
|
|
204
287
|
const payload = JSON.parse(row.payload);
|
|
205
|
-
|
|
288
|
+
const entry = project(item);
|
|
289
|
+
if (!entry)
|
|
290
|
+
continue;
|
|
291
|
+
hits.push({ memoryId: item.id, kind: 'fact', text: entry.content, subject: data.userId,
|
|
206
292
|
attribute: '', emotion: '', occurredAt: payload.occurredAt, recordedAt: row.recorded_at,
|
|
207
293
|
score: Math.max(-1, Math.min(1, item.score)), evidenceIds: [id] });
|
|
208
294
|
}
|
|
209
295
|
}
|
|
210
296
|
return { source: 'personal', state: hits.length ? 'ok' : 'empty', scope: request.scope, hits, rightBrainHits: [], degraded: ledger.prepare("SELECT 1 FROM sources WHERE state='pending' LIMIT 1").get() !== undefined };
|
|
211
297
|
}
|
|
298
|
+
function project(item, rows) {
|
|
299
|
+
const sourceId = item.metadata?.nova_source_id;
|
|
300
|
+
if (!text(sourceId, 256) || !text(item.id, 256) || !text(item.memory, Number.MAX_SAFE_INTEGER) || item.attributedTo === 'assistant')
|
|
301
|
+
return null;
|
|
302
|
+
const row = rows ? rows.sources.get(sourceId) : source(sourceId);
|
|
303
|
+
if (row?.state !== 'learned')
|
|
304
|
+
return null;
|
|
305
|
+
const edit = rows ? rows.edits.get(item.id) : ledger.prepare('SELECT * FROM item_edits WHERE id=?').get(item.id);
|
|
306
|
+
if (edit?.status === 'forgotten')
|
|
307
|
+
return null;
|
|
308
|
+
const content = edit?.content ?? truncate(item.memory, 500);
|
|
309
|
+
// SDK timestamps are durable per item; older SDK rows fall back to canonical-content hashes.
|
|
310
|
+
const version = edit?.version ?? createHash('sha256').update(item.updatedAt ? JSON.stringify([item.updatedAt, content]) : content).digest('hex');
|
|
311
|
+
const original = { type: 'conversation', ref: sourceId, observed_at: row.recorded_at };
|
|
312
|
+
return { id: item.id, version, content, memory_scope: 'user', kind: 'fact', origin: 'inferred', source_refs: edit?.user_source ? [original, MemorySourceRefSchema.parse(JSON.parse(edit.user_source))] : [original],
|
|
313
|
+
evidence_refs: [sourceId], observed_at: row.recorded_at, recorded_at: row.recorded_at, topic: '', status: 'active', corrected_to: null, confidence_note: null };
|
|
314
|
+
}
|
|
315
|
+
async function get(id) {
|
|
316
|
+
if (!text(id, 256))
|
|
317
|
+
throw new StoreError('STORE_INVALID_INPUT');
|
|
318
|
+
const opened = sdk;
|
|
319
|
+
const item = await opened.get(id);
|
|
320
|
+
if (closed || sdk !== opened || !ledger)
|
|
321
|
+
throw new StoreError('STORE_CLOSED');
|
|
322
|
+
return item?.id === id ? project(item) : null;
|
|
323
|
+
}
|
|
324
|
+
async function list(request) {
|
|
325
|
+
const parsed = MemoryListOptionsSchema.safeParse({ ...(request.cursor === undefined ? {} : { cursor: request.cursor }), ...(request.limit === undefined ? {} : { limit: request.limit }), ...(request.include_expired === undefined ? {} : { include_expired: request.include_expired }) });
|
|
326
|
+
if (!parsed.success || parsed.data.include_expired === true)
|
|
327
|
+
throw new StoreError('STORE_INVALID_INPUT');
|
|
328
|
+
const opened = sdk, limit = parsed.data.limit ?? 100;
|
|
329
|
+
const found = await opened.getAll({ filters: { user_id: data.userId }, topK: Number.MAX_SAFE_INTEGER });
|
|
330
|
+
if (closed || sdk !== opened || !ledger)
|
|
331
|
+
throw new StoreError('STORE_CLOSED');
|
|
332
|
+
// The SDK has no cursor: each request scans O(n) items once, without cross-request caching.
|
|
333
|
+
// Batch local overrides/sources; only hydrate the selected page after cursor filtering and sorting.
|
|
334
|
+
const rows = {
|
|
335
|
+
sources: new Map(ledger.prepare('SELECT * FROM sources').all().map(row => [row.id, row])),
|
|
336
|
+
edits: new Map(ledger.prepare('SELECT * FROM item_edits').all().map(row => [row.id, row])),
|
|
337
|
+
};
|
|
338
|
+
const candidates = found.results.filter(item => {
|
|
339
|
+
const id = item.metadata?.nova_source_id;
|
|
340
|
+
return text(item.id, 256) && text(id, 256) && text(item.memory, Number.MAX_SAFE_INTEGER) && item.attributedTo !== 'assistant'
|
|
341
|
+
&& rows.sources.get(id)?.state === 'learned' && rows.edits.get(item.id)?.status !== 'forgotten'
|
|
342
|
+
&& (parsed.data.cursor === undefined || item.id > parsed.data.cursor);
|
|
343
|
+
}).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
344
|
+
const entries = candidates.slice(0, limit).map(item => project(item, rows));
|
|
345
|
+
return { entries, cursor: candidates.length > limit ? entries[limit - 1].id : null };
|
|
346
|
+
}
|
|
347
|
+
function readEvidence(id) {
|
|
348
|
+
if (!text(id, 256))
|
|
349
|
+
throw new StoreError('STORE_INVALID_INPUT');
|
|
350
|
+
const row = source(id);
|
|
351
|
+
if (!row || row.state === 'forgotten')
|
|
352
|
+
return null;
|
|
353
|
+
const payload = JSON.parse(row.payload);
|
|
354
|
+
return { evidence_id: id, locator: id, text: payload.text, source_kind: 'conversation', observed_at: row.recorded_at, trust: 'untrusted_external' };
|
|
355
|
+
}
|
|
356
|
+
async function mutateEntry(request) {
|
|
357
|
+
if (!text(request.id, 256) || request.expectedVersion === null || (typeof request.expectedVersion !== 'string' && typeof request.expectedVersion !== 'number'))
|
|
358
|
+
throw new StoreError('STORE_INVALID_INPUT');
|
|
359
|
+
const correcting = request.operation === 'correct';
|
|
360
|
+
const userSource = correcting ? MemorySourceRefSchema.safeParse(request.userSource) : undefined;
|
|
361
|
+
if (correcting && (!text(request.content, 500) || !userSource?.success))
|
|
362
|
+
throw new StoreError('STORE_INVALID_INPUT');
|
|
363
|
+
const opened = sdk, item = await opened.get(request.id);
|
|
364
|
+
if (closed || sdk !== opened || !ledger)
|
|
365
|
+
throw new StoreError('STORE_CLOSED');
|
|
366
|
+
ledger.exec('BEGIN IMMEDIATE');
|
|
367
|
+
try {
|
|
368
|
+
const previous = item ? project(item) : null;
|
|
369
|
+
if (!previous)
|
|
370
|
+
throw new StoreError('STORE_NOT_FOUND');
|
|
371
|
+
if (previous.version !== request.expectedVersion)
|
|
372
|
+
throw new StoreError('STORE_STALE_REVISION');
|
|
373
|
+
const version = randomUUID(), status = correcting ? 'active' : 'forgotten';
|
|
374
|
+
ledger.prepare(`INSERT INTO item_edits(id,source_id,content,version,status,user_source,cleaned) VALUES (?,?,?,?,?,?,0)
|
|
375
|
+
ON CONFLICT(id) DO UPDATE SET content=excluded.content,version=excluded.version,status=excluded.status,user_source=excluded.user_source,cleaned=0`)
|
|
376
|
+
.run(request.id, previous.evidence_refs[0], correcting ? String(request.content) : '', version, status, userSource?.success ? JSON.stringify(userSource.data) : null);
|
|
377
|
+
if (!correcting)
|
|
378
|
+
markCompactionPending();
|
|
379
|
+
const entry = correcting ? project(item) : { ...previous, content: '', version, status: 'forgotten' };
|
|
380
|
+
ledger.exec('COMMIT');
|
|
381
|
+
return correcting ? { previous, entry } : entry;
|
|
382
|
+
}
|
|
383
|
+
catch (error) {
|
|
384
|
+
ledger.exec('ROLLBACK');
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
212
388
|
function source(id) {
|
|
213
389
|
return ledger?.prepare('SELECT * FROM sources WHERE id=?').get(id);
|
|
214
390
|
}
|
|
@@ -233,11 +409,27 @@ function scheduleDrain() {
|
|
|
233
409
|
for (;;) {
|
|
234
410
|
if (closed || sdk !== opened || !ledger)
|
|
235
411
|
return;
|
|
412
|
+
const deleted = ledger.prepare("SELECT id FROM item_edits WHERE status='forgotten' AND cleaned=0").all();
|
|
413
|
+
for (const row of deleted) {
|
|
414
|
+
try {
|
|
415
|
+
await deleteIfPresent(opened, String(row.id));
|
|
416
|
+
if (closed || sdk !== opened || !ledger)
|
|
417
|
+
return;
|
|
418
|
+
ledger.prepare('UPDATE item_edits SET cleaned=1 WHERE id=?').run(row.id);
|
|
419
|
+
}
|
|
420
|
+
catch { /* durable per-item tombstone retries on the next drain */ }
|
|
421
|
+
}
|
|
236
422
|
const next = ledger.prepare("SELECT * FROM sources WHERE state='pending' OR (state='forgotten' AND cleaned=0) ORDER BY rowid").all()
|
|
237
423
|
.find(row => !failed.has(row.id) && (row.state === 'forgotten' || data.extractionModel !== undefined));
|
|
238
424
|
if (!next)
|
|
239
425
|
return;
|
|
240
426
|
try {
|
|
427
|
+
// A user edit freezes extraction for this source: SDK re-add assigns new ids and would
|
|
428
|
+
// otherwise resurrect corrected/forgotten facts. Source erasure still cleans every item.
|
|
429
|
+
if (next.state === 'pending' && ledger.prepare('SELECT 1 FROM item_edits WHERE source_id=? LIMIT 1').get(next.id)) {
|
|
430
|
+
ledger.prepare("UPDATE sources SET state='learned' WHERE id=? AND state='pending'").run(next.id);
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
241
433
|
// Clean crash-interrupted ADDs before re-extraction; source metadata scopes every public deletion.
|
|
242
434
|
await deleteDerived(opened, next.id);
|
|
243
435
|
if (closed || sdk !== opened)
|
|
@@ -263,7 +455,7 @@ function scheduleDrain() {
|
|
|
263
455
|
const results = await opened.getAll({ filters: { user_id: data.userId, nova_source_id: { eq: next.id } }, topK: Number.MAX_SAFE_INTEGER });
|
|
264
456
|
for (const item of results.results)
|
|
265
457
|
if (item.attributedTo === 'assistant')
|
|
266
|
-
await opened
|
|
458
|
+
await deleteIfPresent(opened, item.id);
|
|
267
459
|
// ponytail: SDK empty results cannot distinguish no facts from swallowed failures; retry on reopen.
|
|
268
460
|
const persisted = new Set(results.results.filter(item => item.attributedTo !== 'assistant').map(item => item.id));
|
|
269
461
|
if (!added.results.length || !persisted.size || added.results.some(item => !persisted.has(item.id)))
|
|
@@ -280,8 +472,26 @@ function scheduleDrain() {
|
|
|
280
472
|
})().catch(() => undefined).finally(() => {
|
|
281
473
|
learningLock?.exec('ROLLBACK');
|
|
282
474
|
draining = false;
|
|
475
|
+
// Compact only after every forgotten source finished deleting its derived vectors.
|
|
476
|
+
if (pendingCompaction() && !ledger?.prepare("SELECT 1 FROM sources WHERE state='forgotten' AND cleaned=0 LIMIT 1").get() && !ledger?.prepare("SELECT 1 FROM item_edits WHERE status='forgotten' AND cleaned=0 LIMIT 1").get()) {
|
|
477
|
+
try {
|
|
478
|
+
compactStore();
|
|
479
|
+
}
|
|
480
|
+
catch { /* keep the durable intent for the next attempt */ }
|
|
481
|
+
}
|
|
283
482
|
});
|
|
284
483
|
}
|
|
484
|
+
async function deleteIfPresent(opened, id) {
|
|
485
|
+
try {
|
|
486
|
+
await opened.delete(id);
|
|
487
|
+
}
|
|
488
|
+
catch (error) {
|
|
489
|
+
// SDK delete throws after an interrupted cleanup already removed the vector. Verify absence
|
|
490
|
+
// instead of matching SDK diagnostics; read failures must keep the cleanup obligation pending.
|
|
491
|
+
if (await opened.get(id) !== null)
|
|
492
|
+
throw error;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
285
495
|
async function deleteDerived(opened, id) {
|
|
286
496
|
for (;;) {
|
|
287
497
|
if (closed || sdk !== opened)
|
|
@@ -294,26 +504,29 @@ async function deleteDerived(opened, id) {
|
|
|
294
504
|
return;
|
|
295
505
|
if (item.metadata?.nova_source_id !== id)
|
|
296
506
|
throw new StoreError('STORE_WRITE_FAILED');
|
|
297
|
-
await opened
|
|
507
|
+
await deleteIfPresent(opened, item.id);
|
|
298
508
|
}
|
|
299
509
|
}
|
|
300
510
|
}
|
|
301
511
|
function parseData(value) {
|
|
302
|
-
if (!record(value) || !keys(value, ['path', 'userId', 'embedding', 'extractionModel'])
|
|
512
|
+
if (!record(value) || !keys(value, ['path', 'userId', 'embedding', 'extractionModel', 'extraction', 'conversationProviders'])
|
|
513
|
+
|| (value.conversationProviders !== undefined && (!Array.isArray(value.conversationProviders) || value.conversationProviders.length > 100 || !value.conversationProviders.every(v => text(v, 256))))
|
|
303
514
|
|| !text(value.path, 4096) || !isAbsolute(value.path) || resolve(value.path) !== value.path
|
|
304
515
|
|| !text(value.userId, 256) || value.userId === '*' || /\s/u.test(value.userId)
|
|
305
516
|
|| !record(value.embedding) || !keys(value.embedding, ['baseUrl', 'apiKey', 'model', 'dimensions'])
|
|
306
517
|
|| !text(value.embedding.baseUrl, 2048) || !text(value.embedding.apiKey, 4096) || !text(value.embedding.model, 256)
|
|
307
518
|
|| (value.embedding.dimensions !== undefined && (!positive(value.embedding.dimensions) || value.embedding.dimensions > 4096))
|
|
519
|
+
|| (value.extraction !== undefined && (!record(value.extraction) || !keys(value.extraction, ['baseUrl', 'apiKey']) || !text(value.extraction.baseUrl, 2048) || !boundedText(value.extraction.apiKey, 4096)))
|
|
308
520
|
|| (value.extractionModel !== undefined && !text(value.extractionModel, 256)))
|
|
309
521
|
throw new Error('invalid mem0 Worker data');
|
|
310
522
|
return value;
|
|
311
523
|
}
|
|
312
524
|
function parseRequest(value) {
|
|
313
|
-
if (!record(value) || value.kind !== 'request' || !positive(value.request_id) || !['open', 'recall', 'remember', 'forget', 'inspect', 'close'].includes(String(value.operation)))
|
|
525
|
+
if (!record(value) || value.kind !== 'request' || !positive(value.request_id) || !['open', 'recall', 'remember', 'forget', 'inspect', 'get', 'getMany', 'list', 'correct', 'forgetEntry', 'forgetSource', 'readEvidence', 'canReadConversationEvidence', 'close'].includes(String(value.operation)))
|
|
314
526
|
return undefined;
|
|
315
|
-
const
|
|
316
|
-
|
|
527
|
+
const entryFields = { get: ['id'], getMany: ['ids'], list: ['cursor', 'limit', 'include_expired'], correct: ['id', 'expectedVersion', 'content', 'userSource'], forgetEntry: ['id', 'expectedVersion'], forgetSource: ['ref'], readEvidence: ['id'], canReadConversationEvidence: ['id', 'consumer'] };
|
|
528
|
+
const fields = entryFields[String(value.operation)] ?? (value.operation === 'remember' ? ['sourceId', 'sessionId', 'sequence', 'text', 'occurredAt', 'previousAssistantReply']
|
|
529
|
+
: value.operation === 'inspect' ? ['query', 'before'] : value.operation === 'recall' ? ['query', 'scope', 'limit'] : value.operation === 'forget' ? ['sourceId'] : []);
|
|
317
530
|
return keys(value, ['kind', 'request_id', 'operation', ...fields]) ? value : undefined;
|
|
318
531
|
}
|
|
319
532
|
function record(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createHash as embeddingHash } from 'node:crypto';
|
|
2
|
+
import { requireIntegratedRealtime, resolveSelectedModelConnection, resolveModelRoute } from '../config/config.js';
|
|
3
|
+
import { requireSelectedCascadedLlmConfig } from '../config/cascaded-realtime-config.js';
|
|
4
|
+
export function configuredMemoryConsumer(settings, mode) {
|
|
5
|
+
return configuredMemoryRecipient(settings, mode)?.consumer;
|
|
6
|
+
}
|
|
7
|
+
export function configuredMemoryRecipient(settings, mode) {
|
|
8
|
+
try {
|
|
9
|
+
const selected = mode === 'text' || settings.pipeline_mode === 'cascaded' ? requireSelectedCascadedLlmConfig(settings) : undefined;
|
|
10
|
+
const voice = selected === undefined ? requireIntegratedRealtime(settings) : undefined;
|
|
11
|
+
const endpoint = selected?.config.baseUrl ?? voice.url, model = selected?.config.model ?? voice.model;
|
|
12
|
+
return { consumer: embeddingHash('sha256').update(JSON.stringify({ provider: selected?.provider ?? settings.integrated_provider, endpoint, model })).digest('hex'), provider: endpoint + '|' + model };
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function configuredTaskVerifierConsumer(settings) {
|
|
19
|
+
return configuredDiscoveryConsumer(settings);
|
|
20
|
+
}
|
|
21
|
+
export function configuredDiscoveryConsumer(settings) {
|
|
22
|
+
const route = resolveModelRoute(settings, 'support'), connection = route ?? resolveSelectedModelConnection(settings);
|
|
23
|
+
if (!connection)
|
|
24
|
+
return undefined;
|
|
25
|
+
return embeddingHash('sha256').update(JSON.stringify({ provider: connection.provider, endpoint: connection.baseUrl, model: route?.model ?? settings.support_model })).digest('hex');
|
|
26
|
+
}
|
|
27
|
+
export function configuredMemoryConsumers(settings) {
|
|
28
|
+
const discovery = configuredDiscoveryConsumer(settings);
|
|
29
|
+
return [...new Set([...['text', 'voice'].map(mode => configuredMemoryConsumer(settings, mode)).filter((value) => value !== undefined), ...(discovery ? [discovery] : [])])];
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=consumer.js.map
|