nox-mem 3.0.0
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 +21 -0
- package/README.md +179 -0
- package/dist/api/answer.d.ts +116 -0
- package/dist/api/answer.js +274 -0
- package/dist/api/answer.validate-patch.d.ts +72 -0
- package/dist/api/answer.validate-patch.js +52 -0
- package/dist/api/brief-diversity.d.ts +64 -0
- package/dist/api/brief-diversity.js +91 -0
- package/dist/api/brief.d.ts +114 -0
- package/dist/api/brief.js +524 -0
- package/dist/api/conflict.d.ts +33 -0
- package/dist/api/conflict.js +143 -0
- package/dist/api/cors.d.ts +73 -0
- package/dist/api/cors.js +124 -0
- package/dist/api/events-stream-limited.d.ts +133 -0
- package/dist/api/events-stream-limited.js +217 -0
- package/dist/api/events-stream.d.ts +53 -0
- package/dist/api/events-stream.js +125 -0
- package/dist/api/export.d.ts +42 -0
- package/dist/api/export.js +85 -0
- package/dist/api/health-confidence-adapter.d.ts +29 -0
- package/dist/api/health-confidence-adapter.js +73 -0
- package/dist/api/health-confidence.d.ts +36 -0
- package/dist/api/health-confidence.js +141 -0
- package/dist/api/hooks.d.ts +50 -0
- package/dist/api/hooks.js +115 -0
- package/dist/api/import.d.ts +38 -0
- package/dist/api/import.js +87 -0
- package/dist/api/ingest-event.d.ts +65 -0
- package/dist/api/ingest-event.js +153 -0
- package/dist/api/mark.d.ts +42 -0
- package/dist/api/mark.js +127 -0
- package/dist/api/server-deps-a2.d.ts +55 -0
- package/dist/api/server-deps-a2.js +138 -0
- package/dist/api/server-deps-l2-l3.d.ts +68 -0
- package/dist/api/server-deps-l2-l3.js +123 -0
- package/dist/api/server-deps-p1.d.ts +84 -0
- package/dist/api/server-deps-p1.js +156 -0
- package/dist/api/server-deps-p2.d.ts +32 -0
- package/dist/api/server-deps-p2.js +84 -0
- package/dist/api/server-deps-p5.d.ts +66 -0
- package/dist/api/server-deps-p5.js +139 -0
- package/dist/api/viewer-static.d.ts +30 -0
- package/dist/api/viewer-static.js +102 -0
- package/dist/api/wire-up.d.ts +54 -0
- package/dist/api/wire-up.js +521 -0
- package/dist/api-impact.d.ts +30 -0
- package/dist/api-impact.js +196 -0
- package/dist/api-server.d.ts +2 -0
- package/dist/api-server.js +614 -0
- package/dist/backfill-fts-anchor.d.ts +15 -0
- package/dist/backfill-fts-anchor.js +97 -0
- package/dist/backfill-source-type.d.ts +20 -0
- package/dist/backfill-source-type.js +182 -0
- package/dist/churn.d.ts +31 -0
- package/dist/churn.js +98 -0
- package/dist/cli/answer.d.ts +66 -0
- package/dist/cli/answer.js +287 -0
- package/dist/cli/conflict.d.ts +38 -0
- package/dist/cli/conflict.js +282 -0
- package/dist/cli/export.d.ts +51 -0
- package/dist/cli/export.js +280 -0
- package/dist/cli/hooks.d.ts +54 -0
- package/dist/cli/hooks.js +133 -0
- package/dist/cli/import.d.ts +52 -0
- package/dist/cli/import.js +274 -0
- package/dist/cli/mark.d.ts +33 -0
- package/dist/cli/mark.js +130 -0
- package/dist/cli/ocr-batch.d.ts +12 -0
- package/dist/cli/ocr-batch.js +411 -0
- package/dist/cli/snapshot-main.d.ts +30 -0
- package/dist/cli/snapshot-main.js +47 -0
- package/dist/cli/viewer.d.ts +35 -0
- package/dist/cli/viewer.js +71 -0
- package/dist/cli-telemetry.d.ts +36 -0
- package/dist/cli-telemetry.js +150 -0
- package/dist/compact.d.ts +7 -0
- package/dist/compact.js +147 -0
- package/dist/consolidate.d.ts +18 -0
- package/dist/consolidate.js +475 -0
- package/dist/consolidation.d.ts +32 -0
- package/dist/consolidation.js +212 -0
- package/dist/cross-agent-v2.d.ts +45 -0
- package/dist/cross-agent-v2.js +271 -0
- package/dist/cross-search.d.ts +11 -0
- package/dist/cross-search.js +119 -0
- package/dist/crystallize.d.ts +43 -0
- package/dist/crystallize.js +111 -0
- package/dist/db.d.ts +11 -0
- package/dist/db.js +388 -0
- package/dist/dedup.d.ts +1 -0
- package/dist/dedup.js +106 -0
- package/dist/detect-changes.d.ts +29 -0
- package/dist/detect-changes.js +236 -0
- package/dist/digest.d.ts +1 -0
- package/dist/digest.js +205 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +71 -0
- package/dist/embed.d.ts +45 -0
- package/dist/embed.js +257 -0
- package/dist/evals.d.ts +176 -0
- package/dist/evals.js +351 -0
- package/dist/generate-user-profile.d.ts +18 -0
- package/dist/generate-user-profile.js +163 -0
- package/dist/graphify-ingest.d.ts +18 -0
- package/dist/graphify-ingest.js +158 -0
- package/dist/impact.d.ts +39 -0
- package/dist/impact.js +143 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +689 -0
- package/dist/ingest-entity.d.ts +44 -0
- package/dist/ingest-entity.js +197 -0
- package/dist/ingest.d.ts +13 -0
- package/dist/ingest.js +210 -0
- package/dist/kg-llm.d.ts +39 -0
- package/dist/kg-llm.js +295 -0
- package/dist/knowledge-graph.d.ts +72 -0
- package/dist/knowledge-graph.js +507 -0
- package/dist/lib/answer/config.d.ts +41 -0
- package/dist/lib/answer/config.js +70 -0
- package/dist/lib/answer/index.d.ts +47 -0
- package/dist/lib/answer/index.js +221 -0
- package/dist/lib/answer/prompt.d.ts +37 -0
- package/dist/lib/answer/prompt.js +88 -0
- package/dist/lib/answer/provider.d.ts +47 -0
- package/dist/lib/answer/provider.js +101 -0
- package/dist/lib/answer/retrieval.d.ts +36 -0
- package/dist/lib/answer/retrieval.js +92 -0
- package/dist/lib/answer/telemetry.d.ts +99 -0
- package/dist/lib/answer/telemetry.js +154 -0
- package/dist/lib/answer/types.d.ts +108 -0
- package/dist/lib/answer/types.js +1 -0
- package/dist/lib/api/error-leak-fix.d.ts +54 -0
- package/dist/lib/api/error-leak-fix.js +55 -0
- package/dist/lib/api/safe-error-message.d.ts +70 -0
- package/dist/lib/api/safe-error-message.js +122 -0
- package/dist/lib/archive/common-passwords.d.ts +37 -0
- package/dist/lib/archive/common-passwords.js +753 -0
- package/dist/lib/archive/encryption.d.ts +81 -0
- package/dist/lib/archive/encryption.js +236 -0
- package/dist/lib/archive/enforce-strength.d.ts +54 -0
- package/dist/lib/archive/enforce-strength.js +70 -0
- package/dist/lib/archive/entropy.d.ts +34 -0
- package/dist/lib/archive/entropy.js +180 -0
- package/dist/lib/archive/export-locking.d.ts +102 -0
- package/dist/lib/archive/export-locking.js +202 -0
- package/dist/lib/archive/format.d.ts +20 -0
- package/dist/lib/archive/format.js +174 -0
- package/dist/lib/archive/index.d.ts +23 -0
- package/dist/lib/archive/index.js +17 -0
- package/dist/lib/archive/manifest.d.ts +53 -0
- package/dist/lib/archive/manifest.js +183 -0
- package/dist/lib/archive/migration.d.ts +36 -0
- package/dist/lib/archive/migration.js +100 -0
- package/dist/lib/archive/migrations/v18_to_v19.d.ts +16 -0
- package/dist/lib/archive/migrations/v18_to_v19.js +18 -0
- package/dist/lib/archive/orchestrator.d.ts +166 -0
- package/dist/lib/archive/orchestrator.js +428 -0
- package/dist/lib/archive/serializers/chunks.d.ts +30 -0
- package/dist/lib/archive/serializers/chunks.js +113 -0
- package/dist/lib/archive/serializers/embeddings.d.ts +36 -0
- package/dist/lib/archive/serializers/embeddings.js +115 -0
- package/dist/lib/archive/serializers/kg.d.ts +28 -0
- package/dist/lib/archive/serializers/kg.js +184 -0
- package/dist/lib/archive/serializers/ops_audit.d.ts +21 -0
- package/dist/lib/archive/serializers/ops_audit.js +97 -0
- package/dist/lib/archive/server-deps.d.ts +131 -0
- package/dist/lib/archive/server-deps.js +232 -0
- package/dist/lib/archive/strength.d.ts +50 -0
- package/dist/lib/archive/strength.js +77 -0
- package/dist/lib/archive/types.d.ts +159 -0
- package/dist/lib/archive/types.js +45 -0
- package/dist/lib/archive/unpack-streaming.d.ts +70 -0
- package/dist/lib/archive/unpack-streaming.js +255 -0
- package/dist/lib/auth/localhost-guard.d.ts +106 -0
- package/dist/lib/auth/localhost-guard.js +164 -0
- package/dist/lib/confidence/config.d.ts +37 -0
- package/dist/lib/confidence/config.js +107 -0
- package/dist/lib/confidence/db-shim-singleton.d.ts +20 -0
- package/dist/lib/confidence/db-shim-singleton.js +41 -0
- package/dist/lib/confidence/db-shim.d.ts +47 -0
- package/dist/lib/confidence/db-shim.js +141 -0
- package/dist/lib/confidence/mark.d.ts +58 -0
- package/dist/lib/confidence/mark.js +168 -0
- package/dist/lib/confidence/ranking.d.ts +69 -0
- package/dist/lib/confidence/ranking.js +101 -0
- package/dist/lib/confidence/search-filter.d.ts +44 -0
- package/dist/lib/confidence/search-filter.js +103 -0
- package/dist/lib/confidence/types.d.ts +146 -0
- package/dist/lib/confidence/types.js +20 -0
- package/dist/lib/confidence/write-hooks.d.ts +50 -0
- package/dist/lib/confidence/write-hooks.js +159 -0
- package/dist/lib/conflict/audit-fk-check.d.ts +72 -0
- package/dist/lib/conflict/audit-fk-check.js +131 -0
- package/dist/lib/conflict/audit-writer.d.ts +39 -0
- package/dist/lib/conflict/audit-writer.js +133 -0
- package/dist/lib/conflict/db-singleton.d.ts +28 -0
- package/dist/lib/conflict/db-singleton.js +61 -0
- package/dist/lib/conflict/db.d.ts +27 -0
- package/dist/lib/conflict/db.js +20 -0
- package/dist/lib/conflict/detector-direct.d.ts +21 -0
- package/dist/lib/conflict/detector-direct.js +105 -0
- package/dist/lib/conflict/evidence.d.ts +24 -0
- package/dist/lib/conflict/evidence.js +76 -0
- package/dist/lib/conflict/index.d.ts +14 -0
- package/dist/lib/conflict/index.js +12 -0
- package/dist/lib/conflict/scheduler.d.ts +78 -0
- package/dist/lib/conflict/scheduler.js +111 -0
- package/dist/lib/conflict/shadow.d.ts +75 -0
- package/dist/lib/conflict/shadow.js +161 -0
- package/dist/lib/conflict/types.d.ts +133 -0
- package/dist/lib/conflict/types.js +19 -0
- package/dist/lib/cost-cap.d.ts +94 -0
- package/dist/lib/cost-cap.js +129 -0
- package/dist/lib/deps/deps-registry.d.ts +111 -0
- package/dist/lib/deps/deps-registry.js +209 -0
- package/dist/lib/error-sanitizer/middleware.d.ts +43 -0
- package/dist/lib/error-sanitizer/middleware.js +100 -0
- package/dist/lib/error-sanitizer/sanitize.d.ts +78 -0
- package/dist/lib/error-sanitizer/sanitize.js +202 -0
- package/dist/lib/eval-batch.d.ts +34 -0
- package/dist/lib/eval-batch.js +103 -0
- package/dist/lib/eval-metrics.d.ts +36 -0
- package/dist/lib/eval-metrics.js +95 -0
- package/dist/lib/eval.d.ts +106 -0
- package/dist/lib/eval.js +343 -0
- package/dist/lib/events/bus.d.ts +135 -0
- package/dist/lib/events/bus.js +95 -0
- package/dist/lib/fts-anchor.d.ts +1 -0
- package/dist/lib/fts-anchor.js +131 -0
- package/dist/lib/hooks/classifier.d.ts +47 -0
- package/dist/lib/hooks/classifier.js +129 -0
- package/dist/lib/hooks/config.d.ts +49 -0
- package/dist/lib/hooks/config.js +106 -0
- package/dist/lib/hooks/decorators.d.ts +35 -0
- package/dist/lib/hooks/decorators.js +59 -0
- package/dist/lib/hooks/pipeline.d.ts +76 -0
- package/dist/lib/hooks/pipeline.js +213 -0
- package/dist/lib/hooks/privacy-filter-adapter.d.ts +55 -0
- package/dist/lib/hooks/privacy-filter-adapter.js +84 -0
- package/dist/lib/hooks/rate-limit-constant-time.d.ts +57 -0
- package/dist/lib/hooks/rate-limit-constant-time.js +69 -0
- package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +71 -0
- package/dist/lib/hooks/rate-limit-dryrun-fix.js +110 -0
- package/dist/lib/hooks/rate-limit.d.ts +54 -0
- package/dist/lib/hooks/rate-limit.js +122 -0
- package/dist/lib/hooks/server-deps.d.ts +61 -0
- package/dist/lib/hooks/server-deps.js +92 -0
- package/dist/lib/hooks/source-allowlist.d.ts +26 -0
- package/dist/lib/hooks/source-allowlist.js +53 -0
- package/dist/lib/hooks/types.d.ts +129 -0
- package/dist/lib/hooks/types.js +24 -0
- package/dist/lib/hooks/worker.d.ts +56 -0
- package/dist/lib/hooks/worker.js +150 -0
- package/dist/lib/ingest-router.d.ts +25 -0
- package/dist/lib/ingest-router.js +103 -0
- package/dist/lib/ocr-detector.d.ts +61 -0
- package/dist/lib/ocr-detector.js +138 -0
- package/dist/lib/ocr-engine-stub.d.ts +48 -0
- package/dist/lib/ocr-engine-stub.js +190 -0
- package/dist/lib/ocr-engines/google-doc-ai.d.ts +36 -0
- package/dist/lib/ocr-engines/google-doc-ai.js +164 -0
- package/dist/lib/ocr-jobs.d.ts +67 -0
- package/dist/lib/ocr-jobs.js +129 -0
- package/dist/lib/op-audit-extension/ran-at-guard.d.ts +86 -0
- package/dist/lib/op-audit-extension/ran-at-guard.js +110 -0
- package/dist/lib/op-audit.d.ts +71 -0
- package/dist/lib/op-audit.js +777 -0
- package/dist/lib/privacy-br/detector.d.ts +42 -0
- package/dist/lib/privacy-br/detector.js +130 -0
- package/dist/lib/privacy-br/index.d.ts +20 -0
- package/dist/lib/privacy-br/index.js +20 -0
- package/dist/lib/privacy-br/integration.d.ts +71 -0
- package/dist/lib/privacy-br/integration.js +74 -0
- package/dist/lib/privacy-br/patterns.d.ts +117 -0
- package/dist/lib/privacy-br/patterns.js +434 -0
- package/dist/lib/privacy-br/redact.d.ts +42 -0
- package/dist/lib/privacy-br/redact.js +103 -0
- package/dist/lib/privacy-br/types.d.ts +55 -0
- package/dist/lib/privacy-br/types.js +25 -0
- package/dist/lib/regex-extract/extractor.d.ts +30 -0
- package/dist/lib/regex-extract/extractor.js +91 -0
- package/dist/lib/regex-extract/frontmatter.d.ts +44 -0
- package/dist/lib/regex-extract/frontmatter.js +169 -0
- package/dist/lib/regex-extract/index.d.ts +14 -0
- package/dist/lib/regex-extract/index.js +14 -0
- package/dist/lib/regex-extract/ingest-router-l4.d.ts +76 -0
- package/dist/lib/regex-extract/ingest-router-l4.js +102 -0
- package/dist/lib/regex-extract/patterns.d.ts +61 -0
- package/dist/lib/regex-extract/patterns.js +91 -0
- package/dist/lib/regex-extract/production-wire.d.ts +128 -0
- package/dist/lib/regex-extract/production-wire.js +202 -0
- package/dist/lib/regex-extract/reconcile.d.ts +162 -0
- package/dist/lib/regex-extract/reconcile.js +210 -0
- package/dist/lib/regex-extract/strip-code.d.ts +24 -0
- package/dist/lib/regex-extract/strip-code.js +52 -0
- package/dist/lib/regex-extract/types.d.ts +48 -0
- package/dist/lib/regex-extract/types.js +25 -0
- package/dist/lib/reranker.d.ts +80 -0
- package/dist/lib/reranker.js +324 -0
- package/dist/lib/shadow-tracker.d.ts +191 -0
- package/dist/lib/shadow-tracker.js +384 -0
- package/dist/lib/spo-injection.d.ts +52 -0
- package/dist/lib/spo-injection.js +166 -0
- package/dist/lib/telemetry-collector.d.ts +158 -0
- package/dist/lib/telemetry-collector.js +249 -0
- package/dist/lib/temporal-detector.d.ts +27 -0
- package/dist/lib/temporal-detector.js +81 -0
- package/dist/lib/viewer/auth.d.ts +37 -0
- package/dist/lib/viewer/auth.js +70 -0
- package/dist/lib/viewer/backpressure.d.ts +59 -0
- package/dist/lib/viewer/backpressure.js +100 -0
- package/dist/lib/viewer/broadcast-singleton.d.ts +34 -0
- package/dist/lib/viewer/broadcast-singleton.js +49 -0
- package/dist/lib/viewer/broadcast.d.ts +66 -0
- package/dist/lib/viewer/broadcast.js +96 -0
- package/dist/lib/viewer/event-types.d.ts +132 -0
- package/dist/lib/viewer/event-types.js +74 -0
- package/dist/lib/viewer/instrumentation.d.ts +106 -0
- package/dist/lib/viewer/instrumentation.js +224 -0
- package/dist/lib/viewer/migration.d.ts +23 -0
- package/dist/lib/viewer/migration.js +56 -0
- package/dist/lib/viewer/redaction.d.ts +44 -0
- package/dist/lib/viewer/redaction.js +139 -0
- package/dist/lib/viewer/session.d.ts +51 -0
- package/dist/lib/viewer/session.js +87 -0
- package/dist/mcp/tools/answer.d.ts +94 -0
- package/dist/mcp/tools/answer.js +213 -0
- package/dist/mcp/tools/archive.d.ts +152 -0
- package/dist/mcp/tools/archive.js +170 -0
- package/dist/mcp/tools/conflict.d.ts +44 -0
- package/dist/mcp/tools/conflict.js +130 -0
- package/dist/mcp/tools/hooks.d.ts +29 -0
- package/dist/mcp/tools/hooks.js +78 -0
- package/dist/mcp/tools/mark.d.ts +38 -0
- package/dist/mcp/tools/mark.js +82 -0
- package/dist/mcp/tools/viewer.d.ts +58 -0
- package/dist/mcp/tools/viewer.js +64 -0
- package/dist/mcp-server.d.ts +2 -0
- package/dist/mcp-server.js +395 -0
- package/dist/metrics.d.ts +3 -0
- package/dist/metrics.js +59 -0
- package/dist/noise-filter.d.ts +18 -0
- package/dist/noise-filter.js +142 -0
- package/dist/notion-sync.d.ts +7 -0
- package/dist/notion-sync.js +97 -0
- package/dist/observability/adapters/a3-adapter.d.ts +63 -0
- package/dist/observability/adapters/a3-adapter.js +83 -0
- package/dist/observability/adapters/p1-adapter.d.ts +49 -0
- package/dist/observability/adapters/p1-adapter.js +63 -0
- package/dist/observability/adapters/p5-adapter.d.ts +36 -0
- package/dist/observability/adapters/p5-adapter.js +71 -0
- package/dist/observability/cardinality.d.ts +61 -0
- package/dist/observability/cardinality.js +300 -0
- package/dist/observability/collectors/db-stats.collector.d.ts +9 -0
- package/dist/observability/collectors/db-stats.collector.js +88 -0
- package/dist/observability/collectors/eventbus.collector.d.ts +6 -0
- package/dist/observability/collectors/eventbus.collector.js +50 -0
- package/dist/observability/collectors/process.collector.d.ts +7 -0
- package/dist/observability/collectors/process.collector.js +93 -0
- package/dist/observability/collectors/provider-telemetry.collector.d.ts +11 -0
- package/dist/observability/collectors/provider-telemetry.collector.js +112 -0
- package/dist/observability/collectors/search-telemetry.collector.d.ts +12 -0
- package/dist/observability/collectors/search-telemetry.collector.js +76 -0
- package/dist/observability/exporter.d.ts +30 -0
- package/dist/observability/exporter.js +182 -0
- package/dist/observability/index.d.ts +22 -0
- package/dist/observability/index.js +21 -0
- package/dist/observability/metrics.d.ts +53 -0
- package/dist/observability/metrics.js +213 -0
- package/dist/observability/privacy-guard.d.ts +32 -0
- package/dist/observability/privacy-guard.js +116 -0
- package/dist/observability/record.d.ts +83 -0
- package/dist/observability/record.js +217 -0
- package/dist/observability/registry.d.ts +60 -0
- package/dist/observability/registry.js +93 -0
- package/dist/observability/types.d.ts +115 -0
- package/dist/observability/types.js +235 -0
- package/dist/observability.d.ts +131 -0
- package/dist/observability.js +234 -0
- package/dist/plugins/nox-hooks/index.d.ts +61 -0
- package/dist/plugins/nox-hooks/index.js +99 -0
- package/dist/primer.d.ts +1 -0
- package/dist/primer.js +100 -0
- package/dist/privacy/filter.d.ts +27 -0
- package/dist/privacy/filter.js +74 -0
- package/dist/privacy/patterns.d.ts +29 -0
- package/dist/privacy/patterns.js +178 -0
- package/dist/privacy/tag-parser.d.ts +24 -0
- package/dist/privacy/tag-parser.js +29 -0
- package/dist/project-context-gen.d.ts +10 -0
- package/dist/project-context-gen.js +106 -0
- package/dist/providers/embedding/gemini.d.ts +73 -0
- package/dist/providers/embedding/gemini.js +118 -0
- package/dist/providers/embedding/openai.d.ts +76 -0
- package/dist/providers/embedding/openai.js +123 -0
- package/dist/providers/embedding/types.d.ts +39 -0
- package/dist/providers/embedding/types.js +1 -0
- package/dist/providers/embedding/voyage.d.ts +36 -0
- package/dist/providers/embedding/voyage.js +29 -0
- package/dist/providers/index.d.ts +116 -0
- package/dist/providers/index.js +158 -0
- package/dist/providers/llm/anthropic.d.ts +29 -0
- package/dist/providers/llm/anthropic.js +28 -0
- package/dist/providers/llm/chain.d.ts +99 -0
- package/dist/providers/llm/chain.js +213 -0
- package/dist/providers/llm/gemini.d.ts +48 -0
- package/dist/providers/llm/gemini.js +96 -0
- package/dist/providers/llm/openai.d.ts +64 -0
- package/dist/providers/llm/openai.js +109 -0
- package/dist/providers/llm/types.d.ts +47 -0
- package/dist/providers/llm/types.js +1 -0
- package/dist/providers/telemetry.d.ts +87 -0
- package/dist/providers/telemetry.js +156 -0
- package/dist/providers/types.d.ts +42 -0
- package/dist/providers/types.js +59 -0
- package/dist/query-entity-count.d.ts +54 -0
- package/dist/query-entity-count.js +171 -0
- package/dist/reflect.d.ts +26 -0
- package/dist/reflect.js +290 -0
- package/dist/reindex-errors.d.ts +7 -0
- package/dist/reindex-errors.js +21 -0
- package/dist/reindex.d.ts +16 -0
- package/dist/reindex.js +293 -0
- package/dist/retention.d.ts +40 -0
- package/dist/retention.js +86 -0
- package/dist/salience.d.ts +85 -0
- package/dist/salience.js +245 -0
- package/dist/scripts/migrate-v17-ops-audit.d.ts +17 -0
- package/dist/scripts/migrate-v17-ops-audit.js +70 -0
- package/dist/search-dedup.d.ts +44 -0
- package/dist/search-dedup.js +137 -0
- package/dist/search-expansion.d.ts +20 -0
- package/dist/search-expansion.js +99 -0
- package/dist/search.d.ts +62 -0
- package/dist/search.js +582 -0
- package/dist/seh-detector.d.ts +31 -0
- package/dist/seh-detector.js +201 -0
- package/dist/self-improve.d.ts +1 -0
- package/dist/self-improve.js +189 -0
- package/dist/session-distill.d.ts +29 -0
- package/dist/session-distill.js +325 -0
- package/dist/session-update.d.ts +1 -0
- package/dist/session-update.js +54 -0
- package/dist/shared-memory.d.ts +24 -0
- package/dist/shared-memory.js +104 -0
- package/dist/stats.d.ts +1 -0
- package/dist/stats.js +44 -0
- package/dist/temporal-retrieval.d.ts +132 -0
- package/dist/temporal-retrieval.js +495 -0
- package/dist/tier-manager.d.ts +69 -0
- package/dist/tier-manager.js +225 -0
- package/dist/vectorize.d.ts +16 -0
- package/dist/vectorize.js +91 -0
- package/dist/watch.d.ts +8 -0
- package/dist/watch.js +124 -0
- package/package.json +74 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// ─── Error type ──────────────────────────────────────────────────────────────
|
|
2
|
+
/** Thrown when the daily spend cap is exceeded. MUST NOT contain prompt content. */
|
|
3
|
+
export class CostCapExceededError extends Error {
|
|
4
|
+
capUsd;
|
|
5
|
+
spentUsd;
|
|
6
|
+
resetAtUtc; // ISO date string
|
|
7
|
+
constructor(capUsd, spentUsd, resetAtUtc) {
|
|
8
|
+
// CRITICAL: no prompt content here — only numbers.
|
|
9
|
+
super(`CostCapExceededError: daily spend cap of $${capUsd.toFixed(4)} USD exceeded ` +
|
|
10
|
+
`(accumulated: $${spentUsd.toFixed(4)} USD). ` +
|
|
11
|
+
`Cap resets at ${resetAtUtc} UTC. ` +
|
|
12
|
+
`Set NOX_PROVIDER_DAILY_USD_CAP_BYPASS=1 to override (logged to ops_audit).`);
|
|
13
|
+
this.name = "CostCapExceededError";
|
|
14
|
+
this.capUsd = capUsd;
|
|
15
|
+
this.spentUsd = spentUsd;
|
|
16
|
+
this.resetAtUtc = resetAtUtc;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
// ─── Price table ─────────────────────────────────────────────────────────────
|
|
20
|
+
/**
|
|
21
|
+
* Price table: USD per 1M tokens (input).
|
|
22
|
+
* Sources: public pricing pages as of 2026-05.
|
|
23
|
+
* These are used for real-time cost estimation — reconcile vs invoice monthly.
|
|
24
|
+
*/
|
|
25
|
+
export const PRICE_TABLE_USD_PER_1M_INPUT = {
|
|
26
|
+
"gemini-2.5-flash-lite": 0.10,
|
|
27
|
+
"gemini-2.5-flash": 0.30,
|
|
28
|
+
"gemini-2.5-pro": 1.25,
|
|
29
|
+
"gpt-4o-mini": 0.15,
|
|
30
|
+
"gpt-4o": 2.50,
|
|
31
|
+
"claude-3-5-haiku": 0.80,
|
|
32
|
+
"claude-3-5-sonnet": 3.00,
|
|
33
|
+
};
|
|
34
|
+
export const PRICE_TABLE_USD_PER_1M_OUTPUT = {
|
|
35
|
+
"gemini-2.5-flash-lite": 0.40,
|
|
36
|
+
"gemini-2.5-flash": 2.50,
|
|
37
|
+
"gemini-2.5-pro": 10.00,
|
|
38
|
+
"gpt-4o-mini": 0.60,
|
|
39
|
+
"gpt-4o": 10.00,
|
|
40
|
+
"claude-3-5-haiku": 4.00,
|
|
41
|
+
"claude-3-5-sonnet": 15.00,
|
|
42
|
+
};
|
|
43
|
+
/** Estimate cost in USD from token counts + model name. Returns 0 if model unknown. */
|
|
44
|
+
export function estimateCostUsd(model, tokensIn, tokensOut) {
|
|
45
|
+
const inPrice = PRICE_TABLE_USD_PER_1M_INPUT[model] ?? 0;
|
|
46
|
+
const outPrice = PRICE_TABLE_USD_PER_1M_OUTPUT[model] ?? 0;
|
|
47
|
+
return (tokensIn / 1_000_000) * inPrice + (tokensOut / 1_000_000) * outPrice;
|
|
48
|
+
}
|
|
49
|
+
/** In-memory fallback accumulator (single-day rolling window). */
|
|
50
|
+
let inMemorySpentUsd = 0;
|
|
51
|
+
let inMemoryWindowStart = startOfDayUtcMs();
|
|
52
|
+
function startOfDayUtcMs() {
|
|
53
|
+
const now = new Date();
|
|
54
|
+
return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
|
|
55
|
+
}
|
|
56
|
+
/** Reset the in-memory accumulator (test utility). */
|
|
57
|
+
export function resetInMemoryAccumulator() {
|
|
58
|
+
inMemorySpentUsd = 0;
|
|
59
|
+
inMemoryWindowStart = startOfDayUtcMs();
|
|
60
|
+
}
|
|
61
|
+
function defaultAccumulatedCostFn() {
|
|
62
|
+
// Rotate window at midnight UTC.
|
|
63
|
+
const dayStart = startOfDayUtcMs();
|
|
64
|
+
if (dayStart > inMemoryWindowStart) {
|
|
65
|
+
inMemorySpentUsd = 0;
|
|
66
|
+
inMemoryWindowStart = dayStart;
|
|
67
|
+
}
|
|
68
|
+
return Promise.resolve(inMemorySpentUsd);
|
|
69
|
+
}
|
|
70
|
+
function defaultOnCost(costUsd) {
|
|
71
|
+
// Rotate window first.
|
|
72
|
+
const dayStart = startOfDayUtcMs();
|
|
73
|
+
if (dayStart > inMemoryWindowStart) {
|
|
74
|
+
inMemorySpentUsd = 0;
|
|
75
|
+
inMemoryWindowStart = dayStart;
|
|
76
|
+
}
|
|
77
|
+
inMemorySpentUsd += costUsd;
|
|
78
|
+
}
|
|
79
|
+
export class CostCappedProvider {
|
|
80
|
+
name;
|
|
81
|
+
model;
|
|
82
|
+
contextWindow;
|
|
83
|
+
provider;
|
|
84
|
+
capUsd;
|
|
85
|
+
accumulatedCostFn;
|
|
86
|
+
bypassFn;
|
|
87
|
+
onBypass;
|
|
88
|
+
onCost;
|
|
89
|
+
constructor(opts) {
|
|
90
|
+
this.provider = opts.provider;
|
|
91
|
+
this.name = opts.provider.name;
|
|
92
|
+
this.model = opts.provider.model;
|
|
93
|
+
this.contextWindow = opts.provider.contextWindow;
|
|
94
|
+
const env = opts.env ?? process.env;
|
|
95
|
+
const capFromEnv = parseFloat(env.NOX_PROVIDER_DAILY_USD_CAP ?? "50.00");
|
|
96
|
+
this.capUsd = opts.capUsd ?? (isFinite(capFromEnv) ? capFromEnv : 50.00);
|
|
97
|
+
this.accumulatedCostFn = opts.accumulatedCostFn ?? defaultAccumulatedCostFn;
|
|
98
|
+
this.bypassFn =
|
|
99
|
+
opts.bypassFn ?? (() => (opts.env ?? process.env).NOX_PROVIDER_DAILY_USD_CAP_BYPASS === "1");
|
|
100
|
+
this.onBypass = opts.onBypass;
|
|
101
|
+
this.onCost = opts.onCost ?? defaultOnCost;
|
|
102
|
+
}
|
|
103
|
+
async complete(opts) {
|
|
104
|
+
const spent = await this.accumulatedCostFn();
|
|
105
|
+
const bypass = this.bypassFn();
|
|
106
|
+
if (spent >= this.capUsd) {
|
|
107
|
+
if (!bypass) {
|
|
108
|
+
const resetAt = new Date(startOfDayUtcMs() + 86_400_000).toISOString().slice(0, 10);
|
|
109
|
+
throw new CostCapExceededError(this.capUsd, spent, resetAt);
|
|
110
|
+
}
|
|
111
|
+
// Bypass active → audit log + proceed.
|
|
112
|
+
this.onBypass?.({
|
|
113
|
+
ts: Date.now(),
|
|
114
|
+
capUsd: this.capUsd,
|
|
115
|
+
spentUsd: spent,
|
|
116
|
+
model: this.model,
|
|
117
|
+
providerId: this.name,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
const result = await this.provider.complete(opts);
|
|
121
|
+
// Track cost after successful call.
|
|
122
|
+
const costUsd = estimateCostUsd(this.model, result.tokensIn, result.tokensOut);
|
|
123
|
+
this.onCost(costUsd, this.model, this.name);
|
|
124
|
+
return result;
|
|
125
|
+
}
|
|
126
|
+
async healthCheck() {
|
|
127
|
+
return this.provider.healthCheck();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/lib/deps/deps-registry.ts — Central singleton resolver for wire-up adapters.
|
|
3
|
+
*
|
|
4
|
+
* Wave O (close-the-503-gap) needs five adapter modules (P1/A2/P5/L2-L3/P2)
|
|
5
|
+
* to share three runtime dependencies:
|
|
6
|
+
*
|
|
7
|
+
* 1. Better-sqlite3 Database handle (nox-mem.db)
|
|
8
|
+
* 2. Gemini provider (already used elsewhere in the codebase)
|
|
9
|
+
* 3. Event bus / broadcaster singleton for SSE
|
|
10
|
+
*
|
|
11
|
+
* Goals (regra de ouro #2 — "Single DB connection"):
|
|
12
|
+
*
|
|
13
|
+
* - One Database instance per process. All adapters acquire via `getDb()`.
|
|
14
|
+
* - Lazy initialization. Importing this module does not open the file.
|
|
15
|
+
* - Test-friendly. `resetDepsRegistryForTests()` flushes all singletons so
|
|
16
|
+
* `node --test` runs do not bleed state between cases.
|
|
17
|
+
* - Soft-fail. If better-sqlite3 isn't installed in the staged sandbox, the
|
|
18
|
+
* resolver returns `null` instead of throwing — the wire-up router maps
|
|
19
|
+
* null → 503 not_implemented (same pattern as before).
|
|
20
|
+
*
|
|
21
|
+
* Production wiring path:
|
|
22
|
+
* `/root/.openclaw/workspace/tools/nox-mem/dist/lib/deps/deps-registry.js`
|
|
23
|
+
* resolves NOX_DB_PATH from env (default
|
|
24
|
+
* `${OPENCLAW_WORKSPACE}/data/nox-mem.db`), opens better-sqlite3 with
|
|
25
|
+
* `readonly:false`, sets `journal_mode=WAL`. Same lifecycle the existing
|
|
26
|
+
* `nox-mem` CLI uses (see entity_file_format memory note).
|
|
27
|
+
*
|
|
28
|
+
* Why a registry instead of per-pillar singletons:
|
|
29
|
+
* - Avoids duplicate DB handles (one per pillar = N WAL writers, race).
|
|
30
|
+
* - Centralizes env reads so misconfig fails fast at first acquisition.
|
|
31
|
+
* - Lets tests swap the DB factory once (`__setDbFactoryForTests`) and have
|
|
32
|
+
* all five adapters honor the override.
|
|
33
|
+
*/
|
|
34
|
+
/**
|
|
35
|
+
* Structural Database type. Matches the better-sqlite3 surface used across
|
|
36
|
+
* staged dirs (`DBHandle` in L2, `Db` in L3, the orchestrator types in A2).
|
|
37
|
+
* Keeping the shim here avoids a hard `better-sqlite3` dep on the test path.
|
|
38
|
+
*/
|
|
39
|
+
export interface DbHandle {
|
|
40
|
+
prepare(sql: string): {
|
|
41
|
+
run(...params: unknown[]): {
|
|
42
|
+
changes: number;
|
|
43
|
+
lastInsertRowid: number | bigint;
|
|
44
|
+
};
|
|
45
|
+
get<T = unknown>(...params: unknown[]): T | undefined;
|
|
46
|
+
all<T = unknown>(...params: unknown[]): T[];
|
|
47
|
+
iterate?<T = unknown>(...params: unknown[]): Iterable<T>;
|
|
48
|
+
};
|
|
49
|
+
exec(sql: string): void;
|
|
50
|
+
transaction?<T extends (...args: any[]) => any>(fn: T): T;
|
|
51
|
+
pragma?(sql: string, opts?: {
|
|
52
|
+
simple?: boolean;
|
|
53
|
+
}): unknown;
|
|
54
|
+
close?(): void;
|
|
55
|
+
}
|
|
56
|
+
export interface GeminiProvider {
|
|
57
|
+
/** Identifier — e.g. "gemini-2.5-flash-lite". */
|
|
58
|
+
model: string;
|
|
59
|
+
/** Generate text completion. Returns {text, tokensIn, tokensOut, model}. */
|
|
60
|
+
complete(opts: {
|
|
61
|
+
system?: string;
|
|
62
|
+
user: string;
|
|
63
|
+
maxTokens?: number;
|
|
64
|
+
temperature?: number;
|
|
65
|
+
}): Promise<{
|
|
66
|
+
text: string;
|
|
67
|
+
tokensIn: number;
|
|
68
|
+
tokensOut: number;
|
|
69
|
+
model: string;
|
|
70
|
+
}>;
|
|
71
|
+
}
|
|
72
|
+
export interface EventBus {
|
|
73
|
+
/**
|
|
74
|
+
* Subscribe to event envelopes. Returns an unsubscribe function.
|
|
75
|
+
* The provider is opaque here; viewer-static + events-stream use it via
|
|
76
|
+
* the staged-P5 `Broadcaster` directly.
|
|
77
|
+
*/
|
|
78
|
+
publish(ev: unknown): unknown;
|
|
79
|
+
addClient(id: string, notify: () => void, lastEventId?: number): unknown;
|
|
80
|
+
removeClient(id: string): void;
|
|
81
|
+
ringSnapshot(): readonly unknown[];
|
|
82
|
+
clientCount(): number;
|
|
83
|
+
}
|
|
84
|
+
type DbFactory = () => DbHandle | null;
|
|
85
|
+
type ProviderFactory = () => GeminiProvider | null;
|
|
86
|
+
type EventBusFactory = () => EventBus | null;
|
|
87
|
+
/** Resolve nox-mem.db path from env, falling back to the canonical VPS path. */
|
|
88
|
+
export declare function resolveDbPath(): string;
|
|
89
|
+
/**
|
|
90
|
+
* Acquire (and cache) the process-wide DB handle.
|
|
91
|
+
* Returns null when better-sqlite3 is unavailable (staged-dir-only mode).
|
|
92
|
+
*/
|
|
93
|
+
export declare function getDb(): Promise<DbHandle | null>;
|
|
94
|
+
/**
|
|
95
|
+
* Acquire the cached Gemini provider, or null when GEMINI_API_KEY is unset.
|
|
96
|
+
*/
|
|
97
|
+
export declare function getProvider(): Promise<GeminiProvider | null>;
|
|
98
|
+
/**
|
|
99
|
+
* Acquire the cached EventBus (Broadcaster instance).
|
|
100
|
+
*/
|
|
101
|
+
export declare function getEventBus(): Promise<EventBus | null>;
|
|
102
|
+
/**
|
|
103
|
+
* Replace the DB factory. Pass `null` to clear (re-enable default factory).
|
|
104
|
+
* Internal — wire-up adapter tests use this to inject fakes.
|
|
105
|
+
*/
|
|
106
|
+
export declare function __setDbFactoryForTests(fn: DbFactory | null): void;
|
|
107
|
+
export declare function __setProviderFactoryForTests(fn: ProviderFactory | null): void;
|
|
108
|
+
export declare function __setEventBusFactoryForTests(fn: EventBusFactory | null): void;
|
|
109
|
+
/** Drop every singleton + clear factories. Use in `beforeEach` of test suites. */
|
|
110
|
+
export declare function resetDepsRegistryForTests(): void;
|
|
111
|
+
export {};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/lib/deps/deps-registry.ts — Central singleton resolver for wire-up adapters.
|
|
3
|
+
*
|
|
4
|
+
* Wave O (close-the-503-gap) needs five adapter modules (P1/A2/P5/L2-L3/P2)
|
|
5
|
+
* to share three runtime dependencies:
|
|
6
|
+
*
|
|
7
|
+
* 1. Better-sqlite3 Database handle (nox-mem.db)
|
|
8
|
+
* 2. Gemini provider (already used elsewhere in the codebase)
|
|
9
|
+
* 3. Event bus / broadcaster singleton for SSE
|
|
10
|
+
*
|
|
11
|
+
* Goals (regra de ouro #2 — "Single DB connection"):
|
|
12
|
+
*
|
|
13
|
+
* - One Database instance per process. All adapters acquire via `getDb()`.
|
|
14
|
+
* - Lazy initialization. Importing this module does not open the file.
|
|
15
|
+
* - Test-friendly. `resetDepsRegistryForTests()` flushes all singletons so
|
|
16
|
+
* `node --test` runs do not bleed state between cases.
|
|
17
|
+
* - Soft-fail. If better-sqlite3 isn't installed in the staged sandbox, the
|
|
18
|
+
* resolver returns `null` instead of throwing — the wire-up router maps
|
|
19
|
+
* null → 503 not_implemented (same pattern as before).
|
|
20
|
+
*
|
|
21
|
+
* Production wiring path:
|
|
22
|
+
* `/root/.openclaw/workspace/tools/nox-mem/dist/lib/deps/deps-registry.js`
|
|
23
|
+
* resolves NOX_DB_PATH from env (default
|
|
24
|
+
* `${OPENCLAW_WORKSPACE}/data/nox-mem.db`), opens better-sqlite3 with
|
|
25
|
+
* `readonly:false`, sets `journal_mode=WAL`. Same lifecycle the existing
|
|
26
|
+
* `nox-mem` CLI uses (see entity_file_format memory note).
|
|
27
|
+
*
|
|
28
|
+
* Why a registry instead of per-pillar singletons:
|
|
29
|
+
* - Avoids duplicate DB handles (one per pillar = N WAL writers, race).
|
|
30
|
+
* - Centralizes env reads so misconfig fails fast at first acquisition.
|
|
31
|
+
* - Lets tests swap the DB factory once (`__setDbFactoryForTests`) and have
|
|
32
|
+
* all five adapters honor the override.
|
|
33
|
+
*/
|
|
34
|
+
import { resolve as pathResolve } from "node:path";
|
|
35
|
+
let _db;
|
|
36
|
+
let _provider;
|
|
37
|
+
let _bus;
|
|
38
|
+
let _dbFactory = null;
|
|
39
|
+
let _providerFactory = null;
|
|
40
|
+
let _eventBusFactory = null;
|
|
41
|
+
/** Resolve nox-mem.db path from env, falling back to the canonical VPS path. */
|
|
42
|
+
export function resolveDbPath() {
|
|
43
|
+
// Test-override channel (avoids touching prod paths during `node --test`).
|
|
44
|
+
if (process.env["NOX_DB_PATH"])
|
|
45
|
+
return process.env["NOX_DB_PATH"];
|
|
46
|
+
const workspace = process.env["OPENCLAW_WORKSPACE"];
|
|
47
|
+
if (workspace)
|
|
48
|
+
return pathResolve(workspace, "data/nox-mem.db");
|
|
49
|
+
// Final fallback (VPS canonical layout).
|
|
50
|
+
return "/root/.openclaw/workspace/tools/nox-mem/data/nox-mem.db";
|
|
51
|
+
}
|
|
52
|
+
/** Default DB factory — tries better-sqlite3, soft-fails when missing. */
|
|
53
|
+
async function defaultDbFactory() {
|
|
54
|
+
try {
|
|
55
|
+
// Dynamic import keeps the staged dir installable without runtime deps.
|
|
56
|
+
// String indirection — `better-sqlite3` is a peer dep on prod, not part
|
|
57
|
+
// of the staged-wire-up-adapters devDependencies.
|
|
58
|
+
const BSQLITE_SPEC = "better-sqlite3";
|
|
59
|
+
const mod = await import(BSQLITE_SPEC);
|
|
60
|
+
const Database = mod.default ?? mod;
|
|
61
|
+
const path = resolveDbPath();
|
|
62
|
+
const handle = new Database(path);
|
|
63
|
+
if (typeof handle.pragma === "function") {
|
|
64
|
+
try {
|
|
65
|
+
handle.pragma("journal_mode = WAL");
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// pragma failures are non-fatal — some test DBs reject WAL.
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return handle;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Default Gemini provider — sources GEMINI_API_KEY + GEMINI_MODEL.
|
|
79
|
+
* When the key is missing OR `@google/generative-ai` isn't installed,
|
|
80
|
+
* returns `null` so adapters fall through to the 503 path.
|
|
81
|
+
*/
|
|
82
|
+
async function defaultProviderFactory() {
|
|
83
|
+
const key = process.env["GEMINI_API_KEY"];
|
|
84
|
+
if (!key)
|
|
85
|
+
return null;
|
|
86
|
+
const modelName = process.env["GEMINI_MODEL"] ?? "gemini-2.5-flash-lite";
|
|
87
|
+
try {
|
|
88
|
+
// String indirection — `@google/generative-ai` is a runtime dep on prod.
|
|
89
|
+
const GEMINI_SPEC = "@google/generative-ai";
|
|
90
|
+
const mod = await import(GEMINI_SPEC);
|
|
91
|
+
const ctor = mod.GoogleGenerativeAI ?? mod.default?.GoogleGenerativeAI;
|
|
92
|
+
if (!ctor)
|
|
93
|
+
return null;
|
|
94
|
+
const client = new ctor(key);
|
|
95
|
+
return {
|
|
96
|
+
model: modelName,
|
|
97
|
+
async complete(opts) {
|
|
98
|
+
const model = client.getGenerativeModel({ model: modelName });
|
|
99
|
+
const prompt = opts.system
|
|
100
|
+
? `${opts.system}\n\n${opts.user}`
|
|
101
|
+
: opts.user;
|
|
102
|
+
const result = await model.generateContent({
|
|
103
|
+
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
|
104
|
+
generationConfig: {
|
|
105
|
+
maxOutputTokens: opts.maxTokens ?? 2048,
|
|
106
|
+
temperature: opts.temperature ?? 0.2,
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
const text = result?.response?.text?.() ?? "";
|
|
110
|
+
const usage = result?.response?.usageMetadata ?? {};
|
|
111
|
+
return {
|
|
112
|
+
text,
|
|
113
|
+
tokensIn: usage.promptTokenCount ?? 0,
|
|
114
|
+
tokensOut: usage.candidatesTokenCount ?? 0,
|
|
115
|
+
model: modelName,
|
|
116
|
+
};
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Default event bus factory — wraps staged-P5 Broadcaster when present.
|
|
126
|
+
* Returns null when the viewer module isn't deployed (503-fallback path).
|
|
127
|
+
*/
|
|
128
|
+
async function defaultEventBusFactory() {
|
|
129
|
+
try {
|
|
130
|
+
// String indirection — `../viewer/broadcast.js` is co-located only
|
|
131
|
+
// after staged-P5 is rsynced.
|
|
132
|
+
const BROADCAST_SPEC = "../viewer/broadcast.js";
|
|
133
|
+
const mod = await import(BROADCAST_SPEC);
|
|
134
|
+
const Broadcaster = mod.Broadcaster;
|
|
135
|
+
if (!Broadcaster)
|
|
136
|
+
return null;
|
|
137
|
+
return new Broadcaster();
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// ─── Public API ──────────────────────────────────────────────────────────────
|
|
144
|
+
/**
|
|
145
|
+
* Acquire (and cache) the process-wide DB handle.
|
|
146
|
+
* Returns null when better-sqlite3 is unavailable (staged-dir-only mode).
|
|
147
|
+
*/
|
|
148
|
+
export async function getDb() {
|
|
149
|
+
if (_db !== undefined)
|
|
150
|
+
return _db;
|
|
151
|
+
if (_dbFactory) {
|
|
152
|
+
_db = _dbFactory();
|
|
153
|
+
return _db ?? null;
|
|
154
|
+
}
|
|
155
|
+
_db = await defaultDbFactory();
|
|
156
|
+
return _db ?? null;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Acquire the cached Gemini provider, or null when GEMINI_API_KEY is unset.
|
|
160
|
+
*/
|
|
161
|
+
export async function getProvider() {
|
|
162
|
+
if (_provider !== undefined)
|
|
163
|
+
return _provider;
|
|
164
|
+
if (_providerFactory) {
|
|
165
|
+
_provider = _providerFactory();
|
|
166
|
+
return _provider ?? null;
|
|
167
|
+
}
|
|
168
|
+
_provider = await defaultProviderFactory();
|
|
169
|
+
return _provider ?? null;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Acquire the cached EventBus (Broadcaster instance).
|
|
173
|
+
*/
|
|
174
|
+
export async function getEventBus() {
|
|
175
|
+
if (_bus !== undefined)
|
|
176
|
+
return _bus;
|
|
177
|
+
if (_eventBusFactory) {
|
|
178
|
+
_bus = _eventBusFactory();
|
|
179
|
+
return _bus ?? null;
|
|
180
|
+
}
|
|
181
|
+
_bus = await defaultEventBusFactory();
|
|
182
|
+
return _bus ?? null;
|
|
183
|
+
}
|
|
184
|
+
// ─── Test seams ──────────────────────────────────────────────────────────────
|
|
185
|
+
/**
|
|
186
|
+
* Replace the DB factory. Pass `null` to clear (re-enable default factory).
|
|
187
|
+
* Internal — wire-up adapter tests use this to inject fakes.
|
|
188
|
+
*/
|
|
189
|
+
export function __setDbFactoryForTests(fn) {
|
|
190
|
+
_dbFactory = fn;
|
|
191
|
+
_db = undefined;
|
|
192
|
+
}
|
|
193
|
+
export function __setProviderFactoryForTests(fn) {
|
|
194
|
+
_providerFactory = fn;
|
|
195
|
+
_provider = undefined;
|
|
196
|
+
}
|
|
197
|
+
export function __setEventBusFactoryForTests(fn) {
|
|
198
|
+
_eventBusFactory = fn;
|
|
199
|
+
_bus = undefined;
|
|
200
|
+
}
|
|
201
|
+
/** Drop every singleton + clear factories. Use in `beforeEach` of test suites. */
|
|
202
|
+
export function resetDepsRegistryForTests() {
|
|
203
|
+
_db = undefined;
|
|
204
|
+
_provider = undefined;
|
|
205
|
+
_bus = undefined;
|
|
206
|
+
_dbFactory = null;
|
|
207
|
+
_providerFactory = null;
|
|
208
|
+
_eventBusFactory = null;
|
|
209
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* G5 T2 — Middleware factories.
|
|
3
|
+
*
|
|
4
|
+
* Two flavours:
|
|
5
|
+
* - `expressErrorMiddleware(opts)` — drop-in `(err, req, res, next)` for
|
|
6
|
+
* Express / Fastify-adapter routes.
|
|
7
|
+
* - `sanitizerWrap(handler, opts)` — framework-agnostic. Wraps an async
|
|
8
|
+
* handler `(input) => Promise<{ status, headers, body }>` so any thrown
|
|
9
|
+
* error is converted into a sanitized response shape consistent with
|
|
10
|
+
* P1/A2/L2/L3/P2/P5.
|
|
11
|
+
*
|
|
12
|
+
* Both seed requestId via `X-Request-ID` header (case-insensitive) when
|
|
13
|
+
* present, else generate a fresh UUID.
|
|
14
|
+
*/
|
|
15
|
+
import { SanitizeOptions } from "./sanitize.js";
|
|
16
|
+
type ExpressLike = {
|
|
17
|
+
status: (n: number) => ExpressLike;
|
|
18
|
+
setHeader: (name: string, value: string) => void;
|
|
19
|
+
json: (body: unknown) => void;
|
|
20
|
+
};
|
|
21
|
+
type ExpressReqLike = {
|
|
22
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
23
|
+
};
|
|
24
|
+
type NextFn = (err?: unknown) => void;
|
|
25
|
+
export interface ExpressMiddlewareOptions extends Omit<SanitizeOptions, "requestId"> {
|
|
26
|
+
/** Header name from which to pull existing request IDs. Default `x-request-id`. */
|
|
27
|
+
requestIdHeader?: string;
|
|
28
|
+
}
|
|
29
|
+
export declare function expressErrorMiddleware(opts?: ExpressMiddlewareOptions): (err: unknown, req: ExpressReqLike, res: ExpressLike, _next: NextFn) => void;
|
|
30
|
+
export interface HandlerInput {
|
|
31
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
32
|
+
[k: string]: unknown;
|
|
33
|
+
}
|
|
34
|
+
export interface HandlerOutput {
|
|
35
|
+
status: number;
|
|
36
|
+
headers?: Record<string, string>;
|
|
37
|
+
body: unknown;
|
|
38
|
+
}
|
|
39
|
+
export declare function sanitizerWrap<I extends HandlerInput>(handler: (input: I) => Promise<HandlerOutput>, opts?: ExpressMiddlewareOptions): (input: I) => Promise<HandlerOutput>;
|
|
40
|
+
export declare function errorToResponse(err: unknown, opts?: Omit<SanitizeOptions, "requestId"> & {
|
|
41
|
+
requestId?: string;
|
|
42
|
+
}): HandlerOutput;
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* G5 T2 — Middleware factories.
|
|
3
|
+
*
|
|
4
|
+
* Two flavours:
|
|
5
|
+
* - `expressErrorMiddleware(opts)` — drop-in `(err, req, res, next)` for
|
|
6
|
+
* Express / Fastify-adapter routes.
|
|
7
|
+
* - `sanitizerWrap(handler, opts)` — framework-agnostic. Wraps an async
|
|
8
|
+
* handler `(input) => Promise<{ status, headers, body }>` so any thrown
|
|
9
|
+
* error is converted into a sanitized response shape consistent with
|
|
10
|
+
* P1/A2/L2/L3/P2/P5.
|
|
11
|
+
*
|
|
12
|
+
* Both seed requestId via `X-Request-ID` header (case-insensitive) when
|
|
13
|
+
* present, else generate a fresh UUID.
|
|
14
|
+
*/
|
|
15
|
+
import { sanitizeErrorForHttp, } from "./sanitize.js";
|
|
16
|
+
export function expressErrorMiddleware(opts = {}) {
|
|
17
|
+
const headerName = (opts.requestIdHeader ?? "x-request-id").toLowerCase();
|
|
18
|
+
return function (err, req, res, _next) {
|
|
19
|
+
const requestId = pickHeader(req.headers, headerName);
|
|
20
|
+
const { status, body } = sanitizeErrorForHttp(err, {
|
|
21
|
+
exposeStack: opts.exposeStack,
|
|
22
|
+
nodeEnv: opts.nodeEnv,
|
|
23
|
+
log: opts.log,
|
|
24
|
+
requestId,
|
|
25
|
+
});
|
|
26
|
+
res.status(status);
|
|
27
|
+
res.setHeader("Content-Type", "application/json");
|
|
28
|
+
res.setHeader("X-Request-ID", body.requestId);
|
|
29
|
+
res.json(body);
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function pickHeader(headers, lowerName) {
|
|
33
|
+
if (!headers)
|
|
34
|
+
return undefined;
|
|
35
|
+
for (const k of Object.keys(headers)) {
|
|
36
|
+
if (k.toLowerCase() === lowerName) {
|
|
37
|
+
const v = headers[k];
|
|
38
|
+
if (Array.isArray(v))
|
|
39
|
+
return v[0];
|
|
40
|
+
return v;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
export function sanitizerWrap(handler, opts = {}) {
|
|
46
|
+
const headerName = (opts.requestIdHeader ?? "x-request-id").toLowerCase();
|
|
47
|
+
return async (input) => {
|
|
48
|
+
const requestId = pickHeader(input.headers, headerName);
|
|
49
|
+
try {
|
|
50
|
+
const out = await handler(input);
|
|
51
|
+
// Always propagate X-Request-ID on success too, so clients can correlate.
|
|
52
|
+
const finalHeaders = {
|
|
53
|
+
...(out.headers ?? {}),
|
|
54
|
+
"X-Request-ID": requestId ?? "",
|
|
55
|
+
};
|
|
56
|
+
if (finalHeaders["X-Request-ID"].length === 0) {
|
|
57
|
+
// Generate one on success path too so logs always have a key.
|
|
58
|
+
finalHeaders["X-Request-ID"] = sanitizeErrorForHttp(new Error("noop"), {
|
|
59
|
+
requestId: undefined,
|
|
60
|
+
}).body.requestId;
|
|
61
|
+
// Note: we don't actually throw here — generator above is the cheap
|
|
62
|
+
// randomUUID fallback path; the noop error result is discarded.
|
|
63
|
+
}
|
|
64
|
+
return { ...out, headers: finalHeaders };
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
const sanitized = sanitizeErrorForHttp(err, {
|
|
68
|
+
exposeStack: opts.exposeStack,
|
|
69
|
+
nodeEnv: opts.nodeEnv,
|
|
70
|
+
log: opts.log,
|
|
71
|
+
requestId,
|
|
72
|
+
});
|
|
73
|
+
return {
|
|
74
|
+
status: sanitized.status,
|
|
75
|
+
headers: {
|
|
76
|
+
"Content-Type": "application/json",
|
|
77
|
+
"X-Request-ID": sanitized.body.requestId,
|
|
78
|
+
},
|
|
79
|
+
body: sanitized.body,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
// ─── Light-touch helper for already-implemented catch-blocks ────────────
|
|
85
|
+
//
|
|
86
|
+
// Most existing handlers have a per-error `try { ... } catch (err) { return
|
|
87
|
+
// jsonResponse(500, ...) }` pattern. Migration step 1 is to swap that for
|
|
88
|
+
// `return errorToResponse(err, opts)` — minimal blast radius, zero behaviour
|
|
89
|
+
// change on the happy path.
|
|
90
|
+
export function errorToResponse(err, opts = {}) {
|
|
91
|
+
const { status, body } = sanitizeErrorForHttp(err, opts);
|
|
92
|
+
return {
|
|
93
|
+
status,
|
|
94
|
+
headers: {
|
|
95
|
+
"Content-Type": "application/json",
|
|
96
|
+
"X-Request-ID": body.requestId,
|
|
97
|
+
},
|
|
98
|
+
body,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* G5 T1 — Central error sanitizer for HTTP responses.
|
|
3
|
+
*
|
|
4
|
+
* Threat-model ref: docs/security/THREAT-MODEL.md §6.2 T-A3-1 + Appendix Gap G5.
|
|
5
|
+
*
|
|
6
|
+
* Problem: Wave B HTTP handlers (P1 answer, A2 export, L3 mark, P5 viewer
|
|
7
|
+
* SSE, L2 conflict, P2 hooks) each implement their own catch-block. Several
|
|
8
|
+
* leak `error.stack` or internal paths (`/Users/lab/...`, `/root/...`) via
|
|
9
|
+
* `JSON.stringify(err)` or `err.message` containing fs paths.
|
|
10
|
+
*
|
|
11
|
+
* Solution: one function. All handlers pipe their errors through
|
|
12
|
+
* `sanitizeErrorForHttp()` to produce a fixed shape:
|
|
13
|
+
*
|
|
14
|
+
* { error: string, code: string, requestId: string, details?: unknown }
|
|
15
|
+
*
|
|
16
|
+
* Always emits requestId so users can quote one to support. Never emits stack
|
|
17
|
+
* (unless `exposeStack: true` AND NODE_ENV=development AND the dev flag is
|
|
18
|
+
* explicitly opted into via the caller).
|
|
19
|
+
*
|
|
20
|
+
* Status-code policy: maps a small allowlist of known error classes. Unknown
|
|
21
|
+
* → 500 + generic message. The status code is the only signal the client
|
|
22
|
+
* needs to differentiate "your input was bad" from "we crashed".
|
|
23
|
+
*
|
|
24
|
+
* Code values are CAPITAL_SNAKE per HTTP-convention; matches both the error's
|
|
25
|
+
* `.name` and a stable string per error class.
|
|
26
|
+
*/
|
|
27
|
+
export interface SanitizedErrorBody {
|
|
28
|
+
/** User-safe message (≤200 chars). NO paths, NO env, NO stack. */
|
|
29
|
+
error: string;
|
|
30
|
+
/** Stable code: error class name OR known status code label. */
|
|
31
|
+
code: string;
|
|
32
|
+
/** Request correlation ID — present even when caller didn't supply one. */
|
|
33
|
+
requestId: string;
|
|
34
|
+
/**
|
|
35
|
+
* Optional safe details. Caller MUST pre-vet — sanitizer will pass through
|
|
36
|
+
* unchanged but drops the field entirely if it contains a stack trace or
|
|
37
|
+
* a recognised internal-path pattern.
|
|
38
|
+
*/
|
|
39
|
+
details?: unknown;
|
|
40
|
+
/**
|
|
41
|
+
* Stack trace — present ONLY when `exposeStack: true` AND `NODE_ENV !== 'production'`.
|
|
42
|
+
* Always omitted in production builds. Tested.
|
|
43
|
+
*/
|
|
44
|
+
stack?: string;
|
|
45
|
+
}
|
|
46
|
+
export interface SanitizeOptions {
|
|
47
|
+
/**
|
|
48
|
+
* Request correlation ID. If empty/missing, generated via crypto.randomUUID().
|
|
49
|
+
* MUST be propagated by the caller (middleware seam).
|
|
50
|
+
*/
|
|
51
|
+
requestId?: string;
|
|
52
|
+
/**
|
|
53
|
+
* Expose stack in the response body. Default `false`.
|
|
54
|
+
* GATED additionally on `nodeEnv !== 'production'` — production never leaks.
|
|
55
|
+
*/
|
|
56
|
+
exposeStack?: boolean;
|
|
57
|
+
/**
|
|
58
|
+
* NODE_ENV override (defaults to process.env.NODE_ENV).
|
|
59
|
+
* Tests pass this explicitly to validate the prod-guard branch.
|
|
60
|
+
*/
|
|
61
|
+
nodeEnv?: string;
|
|
62
|
+
/** Optional log sink for the redacted line (caller-injectable). */
|
|
63
|
+
log?: (line: string) => void;
|
|
64
|
+
}
|
|
65
|
+
export interface SanitizedResult {
|
|
66
|
+
status: number;
|
|
67
|
+
body: SanitizedErrorBody;
|
|
68
|
+
}
|
|
69
|
+
declare const ERROR_STATUS_MAP: ReadonlyMap<string, {
|
|
70
|
+
status: number;
|
|
71
|
+
code: string;
|
|
72
|
+
safeMsg?: string;
|
|
73
|
+
}>;
|
|
74
|
+
export declare function sanitizeErrorForHttp(err: unknown, opts?: SanitizeOptions): SanitizedResult;
|
|
75
|
+
/** Convenience: generate a fresh requestId (callable from middleware). */
|
|
76
|
+
export declare function newRequestId(): string;
|
|
77
|
+
/** Re-export so callers can `import { sanitizeErrorForHttp, ... }`. */
|
|
78
|
+
export { ERROR_STATUS_MAP };
|