@agentlensai/server 0.11.0 → 0.13.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/dist/cloud/auth/rbac.d.ts +1 -1
- package/dist/cloud/auth/rbac.d.ts.map +1 -1
- package/dist/cloud/auth/rbac.js +2 -2
- package/dist/cloud/auth/rbac.js.map +1 -1
- package/dist/cloud/billing/stripe-client.d.ts.map +1 -1
- package/dist/cloud/billing/stripe-client.js +6 -1
- package/dist/cloud/billing/stripe-client.js.map +1 -1
- package/dist/cloud/ingestion/gateway.d.ts.map +1 -1
- package/dist/cloud/ingestion/gateway.js +0 -1
- package/dist/cloud/ingestion/gateway.js.map +1 -1
- package/dist/cloud/middleware/validate-org-access.d.ts +14 -0
- package/dist/cloud/middleware/validate-org-access.d.ts.map +1 -0
- package/dist/cloud/middleware/validate-org-access.js +38 -0
- package/dist/cloud/middleware/validate-org-access.js.map +1 -0
- package/dist/cloud/routes/index.d.ts +13 -0
- package/dist/cloud/routes/index.d.ts.map +1 -0
- package/dist/cloud/routes/index.js +98 -0
- package/dist/cloud/routes/index.js.map +1 -0
- package/dist/config.d.ts +33 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +71 -1
- package/dist/config.js.map +1 -1
- package/dist/db/api-key-lookup.d.ts +25 -0
- package/dist/db/api-key-lookup.d.ts.map +1 -0
- package/dist/db/api-key-lookup.js +38 -0
- package/dist/db/api-key-lookup.js.map +1 -0
- package/dist/db/connection.postgres.d.ts +44 -0
- package/dist/db/connection.postgres.d.ts.map +1 -0
- package/dist/db/connection.postgres.js +79 -0
- package/dist/db/connection.postgres.js.map +1 -0
- package/dist/db/cost-budget-store.d.ts +30 -0
- package/dist/db/cost-budget-store.d.ts.map +1 -0
- package/dist/db/cost-budget-store.js +201 -0
- package/dist/db/cost-budget-store.js.map +1 -0
- package/dist/db/drizzle/0000_initial.sql +336 -0
- package/dist/db/drizzle/0001_indexes.sql +20 -0
- package/dist/db/drizzle/0002_pgvector.sql +19 -0
- package/dist/db/drizzle/drizzle/0000_initial.sql +336 -0
- package/dist/db/drizzle/drizzle/0001_indexes.sql +20 -0
- package/dist/db/drizzle/drizzle/0002_pgvector.sql +19 -0
- package/dist/db/drizzle/drizzle/meta/0000_snapshot.json +2593 -0
- package/dist/db/drizzle/drizzle/meta/_journal.json +27 -0
- package/dist/db/drizzle/meta/0000_snapshot.json +2593 -0
- package/dist/db/drizzle/meta/_journal.json +27 -0
- package/dist/db/embedding-store.d.ts +2 -1
- package/dist/db/embedding-store.d.ts.map +1 -1
- package/dist/db/embedding-store.interface.d.ts +19 -0
- package/dist/db/embedding-store.interface.d.ts.map +1 -0
- package/dist/db/embedding-store.interface.js +7 -0
- package/dist/db/embedding-store.interface.js.map +1 -0
- package/dist/db/embedding-store.js +3 -1
- package/dist/db/embedding-store.js.map +1 -1
- package/dist/db/eval-store.d.ts +88 -0
- package/dist/db/eval-store.d.ts.map +1 -0
- package/dist/db/eval-store.js +408 -0
- package/dist/db/eval-store.js.map +1 -0
- package/dist/db/guardrail-store.d.ts +9 -0
- package/dist/db/guardrail-store.d.ts.map +1 -1
- package/dist/db/guardrail-store.js +57 -3
- package/dist/db/guardrail-store.js.map +1 -1
- package/dist/db/index.d.ts +7 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +4 -12
- package/dist/db/index.js.map +1 -1
- package/dist/db/migrate.d.ts +5 -22
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +7 -637
- package/dist/db/migrate.js.map +1 -1
- package/dist/db/migrate.postgres.d.ts +16 -0
- package/dist/db/migrate.postgres.d.ts.map +1 -0
- package/dist/db/migrate.postgres.js +23 -0
- package/dist/db/migrate.postgres.js.map +1 -0
- package/dist/db/migrate.sqlite.d.ts +26 -0
- package/dist/db/migrate.sqlite.d.ts.map +1 -0
- package/dist/db/migrate.sqlite.js +920 -0
- package/dist/db/migrate.sqlite.js.map +1 -0
- package/dist/db/postgres-embedding-store.d.ts +23 -0
- package/dist/db/postgres-embedding-store.d.ts.map +1 -0
- package/dist/db/postgres-embedding-store.js +218 -0
- package/dist/db/postgres-embedding-store.js.map +1 -0
- package/dist/db/postgres-store.d.ts +80 -0
- package/dist/db/postgres-store.d.ts.map +1 -0
- package/dist/db/postgres-store.js +910 -0
- package/dist/db/postgres-store.js.map +1 -0
- package/dist/db/prompt-store.d.ts +57 -0
- package/dist/db/prompt-store.d.ts.map +1 -0
- package/dist/db/prompt-store.js +300 -0
- package/dist/db/prompt-store.js.map +1 -0
- package/dist/db/repositories/agent-repository.d.ts +21 -0
- package/dist/db/repositories/agent-repository.d.ts.map +1 -0
- package/dist/db/repositories/agent-repository.js +142 -0
- package/dist/db/repositories/agent-repository.js.map +1 -0
- package/dist/db/repositories/alert-repository.d.ts +27 -0
- package/dist/db/repositories/alert-repository.d.ts.map +1 -0
- package/dist/db/repositories/alert-repository.js +164 -0
- package/dist/db/repositories/alert-repository.js.map +1 -0
- package/dist/db/repositories/analytics-repository.d.ts +24 -0
- package/dist/db/repositories/analytics-repository.d.ts.map +1 -0
- package/dist/db/repositories/analytics-repository.js +147 -0
- package/dist/db/repositories/analytics-repository.js.map +1 -0
- package/dist/db/repositories/event-repository.d.ts +81 -0
- package/dist/db/repositories/event-repository.d.ts.map +1 -0
- package/dist/db/repositories/event-repository.js +331 -0
- package/dist/db/repositories/event-repository.js.map +1 -0
- package/dist/db/repositories/notification-channel-repository.d.ts +28 -0
- package/dist/db/repositories/notification-channel-repository.d.ts.map +1 -0
- package/dist/db/repositories/notification-channel-repository.js +151 -0
- package/dist/db/repositories/notification-channel-repository.js.map +1 -0
- package/dist/db/repositories/session-repository.d.ts +26 -0
- package/dist/db/repositories/session-repository.d.ts.map +1 -0
- package/dist/db/repositories/session-repository.js +240 -0
- package/dist/db/repositories/session-repository.js.map +1 -0
- package/dist/db/schema.postgres.d.ts +4681 -0
- package/dist/db/schema.postgres.d.ts.map +1 -0
- package/dist/db/schema.postgres.js +458 -0
- package/dist/db/schema.postgres.js.map +1 -0
- package/dist/db/schema.sqlite.d.ts +2221 -671
- package/dist/db/schema.sqlite.d.ts.map +1 -1
- package/dist/db/schema.sqlite.js +137 -2
- package/dist/db/schema.sqlite.js.map +1 -1
- package/dist/db/services/retention-service.d.ts +13 -0
- package/dist/db/services/retention-service.d.ts.map +1 -0
- package/dist/db/services/retention-service.js +48 -0
- package/dist/db/services/retention-service.js.map +1 -0
- package/dist/db/shared/query-helpers.d.ts +32 -0
- package/dist/db/shared/query-helpers.d.ts.map +1 -0
- package/dist/db/shared/query-helpers.js +180 -0
- package/dist/db/shared/query-helpers.js.map +1 -0
- package/dist/db/sqlite-store.d.ts +48 -55
- package/dist/db/sqlite-store.d.ts.map +1 -1
- package/dist/db/sqlite-store.js +78 -945
- package/dist/db/sqlite-store.js.map +1 -1
- package/dist/db/tenant-scoped-store.d.ts +18 -1
- package/dist/db/tenant-scoped-store.d.ts.map +1 -1
- package/dist/db/tenant-scoped-store.js +6 -0
- package/dist/db/tenant-scoped-store.js.map +1 -1
- package/dist/index.d.ts +28 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +432 -97
- package/dist/index.js.map +1 -1
- package/dist/lib/alert-engine.d.ts +10 -0
- package/dist/lib/alert-engine.d.ts.map +1 -1
- package/dist/lib/alert-engine.js +73 -20
- package/dist/lib/alert-engine.js.map +1 -1
- package/dist/lib/audit-verify.d.ts +40 -0
- package/dist/lib/audit-verify.d.ts.map +1 -0
- package/dist/lib/audit-verify.js +128 -0
- package/dist/lib/audit-verify.js.map +1 -0
- package/dist/lib/audit.d.ts +37 -0
- package/dist/lib/audit.d.ts.map +1 -0
- package/dist/lib/audit.js +59 -0
- package/dist/lib/audit.js.map +1 -0
- package/dist/lib/budget-engine.d.ts +26 -0
- package/dist/lib/budget-engine.d.ts.map +1 -0
- package/dist/lib/budget-engine.js +201 -0
- package/dist/lib/budget-engine.js.map +1 -0
- package/dist/lib/compliance-export.d.ts +41 -0
- package/dist/lib/compliance-export.d.ts.map +1 -0
- package/dist/lib/compliance-export.js +124 -0
- package/dist/lib/compliance-export.js.map +1 -0
- package/dist/lib/compliance-report.d.ts +87 -0
- package/dist/lib/compliance-report.d.ts.map +1 -0
- package/dist/lib/compliance-report.js +148 -0
- package/dist/lib/compliance-report.js.map +1 -0
- package/dist/lib/context/retrieval.d.ts +5 -3
- package/dist/lib/context/retrieval.d.ts.map +1 -1
- package/dist/lib/context/retrieval.js +5 -2
- package/dist/lib/context/retrieval.js.map +1 -1
- package/dist/lib/cost-anomaly-detector.d.ts +23 -0
- package/dist/lib/cost-anomaly-detector.d.ts.map +1 -0
- package/dist/lib/cost-anomaly-detector.js +108 -0
- package/dist/lib/cost-anomaly-detector.js.map +1 -0
- package/dist/lib/db-resilience.d.ts +15 -0
- package/dist/lib/db-resilience.d.ts.map +1 -0
- package/dist/lib/db-resilience.js +49 -0
- package/dist/lib/db-resilience.js.map +1 -0
- package/dist/lib/diagnostics/cache.d.ts +29 -0
- package/dist/lib/diagnostics/cache.d.ts.map +1 -0
- package/dist/lib/diagnostics/cache.js +88 -0
- package/dist/lib/diagnostics/cache.js.map +1 -0
- package/dist/lib/diagnostics/context-builder.d.ts +41 -0
- package/dist/lib/diagnostics/context-builder.d.ts.map +1 -0
- package/dist/lib/diagnostics/context-builder.js +135 -0
- package/dist/lib/diagnostics/context-builder.js.map +1 -0
- package/dist/lib/diagnostics/index.d.ts +34 -0
- package/dist/lib/diagnostics/index.d.ts.map +1 -0
- package/dist/lib/diagnostics/index.js +223 -0
- package/dist/lib/diagnostics/index.js.map +1 -0
- package/dist/lib/diagnostics/llm-client.d.ts +24 -0
- package/dist/lib/diagnostics/llm-client.d.ts.map +1 -0
- package/dist/lib/diagnostics/llm-client.js +42 -0
- package/dist/lib/diagnostics/llm-client.js.map +1 -0
- package/dist/lib/diagnostics/prompt-templates.d.ts +18 -0
- package/dist/lib/diagnostics/prompt-templates.d.ts.map +1 -0
- package/dist/lib/diagnostics/prompt-templates.js +144 -0
- package/dist/lib/diagnostics/prompt-templates.js.map +1 -0
- package/dist/lib/diagnostics/providers/anthropic.d.ts +8 -0
- package/dist/lib/diagnostics/providers/anthropic.d.ts.map +1 -0
- package/dist/lib/diagnostics/providers/anthropic.js +79 -0
- package/dist/lib/diagnostics/providers/anthropic.js.map +1 -0
- package/dist/lib/diagnostics/providers/openai.d.ts +8 -0
- package/dist/lib/diagnostics/providers/openai.d.ts.map +1 -0
- package/dist/lib/diagnostics/providers/openai.js +70 -0
- package/dist/lib/diagnostics/providers/openai.js.map +1 -0
- package/dist/lib/diagnostics/providers/types.d.ts +23 -0
- package/dist/lib/diagnostics/providers/types.d.ts.map +1 -0
- package/dist/lib/diagnostics/providers/types.js +5 -0
- package/dist/lib/diagnostics/providers/types.js.map +1 -0
- package/dist/lib/diagnostics/response-parser.d.ts +60 -0
- package/dist/lib/diagnostics/response-parser.d.ts.map +1 -0
- package/dist/lib/diagnostics/response-parser.js +55 -0
- package/dist/lib/diagnostics/response-parser.js.map +1 -0
- package/dist/lib/diagnostics/types.d.ts +60 -0
- package/dist/lib/diagnostics/types.d.ts.map +1 -0
- package/dist/lib/diagnostics/types.js +7 -0
- package/dist/lib/diagnostics/types.js.map +1 -0
- package/dist/lib/embeddings/index.d.ts +6 -3
- package/dist/lib/embeddings/index.d.ts.map +1 -1
- package/dist/lib/embeddings/index.js +7 -15
- package/dist/lib/embeddings/index.js.map +1 -1
- package/dist/lib/embeddings/worker.d.ts +2 -2
- package/dist/lib/embeddings/worker.d.ts.map +1 -1
- package/dist/lib/embeddings/worker.js +3 -1
- package/dist/lib/embeddings/worker.js.map +1 -1
- package/dist/lib/error-sanitizer.d.ts +28 -0
- package/dist/lib/error-sanitizer.d.ts.map +1 -0
- package/dist/lib/error-sanitizer.js +106 -0
- package/dist/lib/error-sanitizer.js.map +1 -0
- package/dist/lib/eval/index.d.ts +15 -0
- package/dist/lib/eval/index.d.ts.map +1 -0
- package/dist/lib/eval/index.js +24 -0
- package/dist/lib/eval/index.js.map +1 -0
- package/dist/lib/eval/runner.d.ts +28 -0
- package/dist/lib/eval/runner.d.ts.map +1 -0
- package/dist/lib/eval/runner.js +260 -0
- package/dist/lib/eval/runner.js.map +1 -0
- package/dist/lib/eval/scorers/contains.d.ts +10 -0
- package/dist/lib/eval/scorers/contains.d.ts.map +1 -0
- package/dist/lib/eval/scorers/contains.js +33 -0
- package/dist/lib/eval/scorers/contains.js.map +1 -0
- package/dist/lib/eval/scorers/exact-match.d.ts +10 -0
- package/dist/lib/eval/scorers/exact-match.d.ts.map +1 -0
- package/dist/lib/eval/scorers/exact-match.js +33 -0
- package/dist/lib/eval/scorers/exact-match.js.map +1 -0
- package/dist/lib/eval/scorers/index.d.ts +20 -0
- package/dist/lib/eval/scorers/index.d.ts.map +1 -0
- package/dist/lib/eval/scorers/index.js +19 -0
- package/dist/lib/eval/scorers/index.js.map +1 -0
- package/dist/lib/eval/scorers/llm-judge.d.ts +22 -0
- package/dist/lib/eval/scorers/llm-judge.d.ts.map +1 -0
- package/dist/lib/eval/scorers/llm-judge.js +79 -0
- package/dist/lib/eval/scorers/llm-judge.js.map +1 -0
- package/dist/lib/eval/scorers/regex.d.ts +10 -0
- package/dist/lib/eval/scorers/regex.d.ts.map +1 -0
- package/dist/lib/eval/scorers/regex.js +36 -0
- package/dist/lib/eval/scorers/regex.js.map +1 -0
- package/dist/lib/guardrails/actions.d.ts +6 -0
- package/dist/lib/guardrails/actions.d.ts.map +1 -1
- package/dist/lib/guardrails/actions.js +82 -0
- package/dist/lib/guardrails/actions.js.map +1 -1
- package/dist/lib/guardrails/conditions.d.ts +47 -0
- package/dist/lib/guardrails/conditions.d.ts.map +1 -1
- package/dist/lib/guardrails/conditions.js +55 -10
- package/dist/lib/guardrails/conditions.js.map +1 -1
- package/dist/lib/guardrails/content-engine.d.ts +19 -0
- package/dist/lib/guardrails/content-engine.d.ts.map +1 -0
- package/dist/lib/guardrails/content-engine.js +154 -0
- package/dist/lib/guardrails/content-engine.js.map +1 -0
- package/dist/lib/guardrails/engine.d.ts +33 -0
- package/dist/lib/guardrails/engine.d.ts.map +1 -1
- package/dist/lib/guardrails/engine.js +37 -2
- package/dist/lib/guardrails/engine.js.map +1 -1
- package/dist/lib/guardrails/scanners/base-scanner.d.ts +23 -0
- package/dist/lib/guardrails/scanners/base-scanner.d.ts.map +1 -0
- package/dist/lib/guardrails/scanners/base-scanner.js +7 -0
- package/dist/lib/guardrails/scanners/base-scanner.js.map +1 -0
- package/dist/lib/guardrails/scanners/patterns/pii-patterns.d.ts +13 -0
- package/dist/lib/guardrails/scanners/patterns/pii-patterns.d.ts.map +1 -0
- package/dist/lib/guardrails/scanners/patterns/pii-patterns.js +49 -0
- package/dist/lib/guardrails/scanners/patterns/pii-patterns.js.map +1 -0
- package/dist/lib/guardrails/scanners/patterns/secret-patterns.d.ts +6 -0
- package/dist/lib/guardrails/scanners/patterns/secret-patterns.d.ts.map +1 -0
- package/dist/lib/guardrails/scanners/patterns/secret-patterns.js +69 -0
- package/dist/lib/guardrails/scanners/patterns/secret-patterns.js.map +1 -0
- package/dist/lib/guardrails/scanners/pii-scanner.d.ts +10 -0
- package/dist/lib/guardrails/scanners/pii-scanner.d.ts.map +1 -0
- package/dist/lib/guardrails/scanners/pii-scanner.js +57 -0
- package/dist/lib/guardrails/scanners/pii-scanner.js.map +1 -0
- package/dist/lib/guardrails/scanners/scanner-registry.d.ts +14 -0
- package/dist/lib/guardrails/scanners/scanner-registry.d.ts.map +1 -0
- package/dist/lib/guardrails/scanners/scanner-registry.js +51 -0
- package/dist/lib/guardrails/scanners/scanner-registry.js.map +1 -0
- package/dist/lib/guardrails/scanners/secrets-scanner.d.ts +9 -0
- package/dist/lib/guardrails/scanners/secrets-scanner.d.ts.map +1 -0
- package/dist/lib/guardrails/scanners/secrets-scanner.js +47 -0
- package/dist/lib/guardrails/scanners/secrets-scanner.js.map +1 -0
- package/dist/lib/logger.d.ts +8 -0
- package/dist/lib/logger.d.ts.map +1 -0
- package/dist/lib/logger.js +31 -0
- package/dist/lib/logger.js.map +1 -0
- package/dist/lib/lore-client.d.ts +128 -0
- package/dist/lib/lore-client.d.ts.map +1 -0
- package/dist/lib/lore-client.js +188 -0
- package/dist/lib/lore-client.js.map +1 -0
- package/dist/lib/mesh-client.d.ts +31 -0
- package/dist/lib/mesh-client.d.ts.map +1 -0
- package/dist/lib/mesh-client.js +72 -0
- package/dist/lib/mesh-client.js.map +1 -0
- package/dist/lib/notifications/grouping-buffer.d.ts +25 -0
- package/dist/lib/notifications/grouping-buffer.d.ts.map +1 -0
- package/dist/lib/notifications/grouping-buffer.js +73 -0
- package/dist/lib/notifications/grouping-buffer.js.map +1 -0
- package/dist/lib/notifications/provider.d.ts +10 -0
- package/dist/lib/notifications/provider.d.ts.map +1 -0
- package/dist/lib/notifications/provider.js +5 -0
- package/dist/lib/notifications/provider.js.map +1 -0
- package/dist/lib/notifications/providers/email.d.ts +14 -0
- package/dist/lib/notifications/providers/email.d.ts.map +1 -0
- package/dist/lib/notifications/providers/email.js +88 -0
- package/dist/lib/notifications/providers/email.js.map +1 -0
- package/dist/lib/notifications/providers/pagerduty.d.ts +16 -0
- package/dist/lib/notifications/providers/pagerduty.d.ts.map +1 -0
- package/dist/lib/notifications/providers/pagerduty.js +94 -0
- package/dist/lib/notifications/providers/pagerduty.js.map +1 -0
- package/dist/lib/notifications/providers/slack.d.ts +14 -0
- package/dist/lib/notifications/providers/slack.d.ts.map +1 -0
- package/dist/lib/notifications/providers/slack.js +106 -0
- package/dist/lib/notifications/providers/slack.js.map +1 -0
- package/dist/lib/notifications/providers/webhook.d.ts +16 -0
- package/dist/lib/notifications/providers/webhook.d.ts.map +1 -0
- package/dist/lib/notifications/providers/webhook.js +78 -0
- package/dist/lib/notifications/providers/webhook.js.map +1 -0
- package/dist/lib/notifications/router.d.ts +30 -0
- package/dist/lib/notifications/router.d.ts.map +1 -0
- package/dist/lib/notifications/router.js +137 -0
- package/dist/lib/notifications/router.js.map +1 -0
- package/dist/lib/notifications/ssrf.d.ts +13 -0
- package/dist/lib/notifications/ssrf.d.ts.map +1 -0
- package/dist/lib/notifications/ssrf.js +37 -0
- package/dist/lib/notifications/ssrf.js.map +1 -0
- package/dist/lib/optimization/analyzers/model-downgrade.d.ts +15 -0
- package/dist/lib/optimization/analyzers/model-downgrade.d.ts.map +1 -0
- package/dist/lib/optimization/analyzers/model-downgrade.js +58 -0
- package/dist/lib/optimization/analyzers/model-downgrade.js.map +1 -0
- package/dist/lib/optimization/analyzers/prompt-optimization.d.ts +17 -0
- package/dist/lib/optimization/analyzers/prompt-optimization.d.ts.map +1 -0
- package/dist/lib/optimization/analyzers/prompt-optimization.js +160 -0
- package/dist/lib/optimization/analyzers/prompt-optimization.js.map +1 -0
- package/dist/lib/optimization/analyzers/types.d.ts +23 -0
- package/dist/lib/optimization/analyzers/types.d.ts.map +1 -0
- package/dist/lib/optimization/analyzers/types.js +5 -0
- package/dist/lib/optimization/analyzers/types.js.map +1 -0
- package/dist/lib/optimization/classifier.d.ts +4 -3
- package/dist/lib/optimization/classifier.d.ts.map +1 -1
- package/dist/lib/optimization/classifier.js +15 -9
- package/dist/lib/optimization/classifier.js.map +1 -1
- package/dist/lib/optimization/cost-optimizer.d.ts +21 -0
- package/dist/lib/optimization/cost-optimizer.d.ts.map +1 -0
- package/dist/lib/optimization/cost-optimizer.js +114 -0
- package/dist/lib/optimization/cost-optimizer.js.map +1 -0
- package/dist/lib/optimization/engine.d.ts.map +1 -1
- package/dist/lib/optimization/engine.js +45 -6
- package/dist/lib/optimization/engine.js.map +1 -1
- package/dist/lib/optimization/forecast.d.ts +39 -0
- package/dist/lib/optimization/forecast.d.ts.map +1 -0
- package/dist/lib/optimization/forecast.js +128 -0
- package/dist/lib/optimization/forecast.js.map +1 -0
- package/dist/lib/secrets.d.ts +30 -0
- package/dist/lib/secrets.d.ts.map +1 -0
- package/dist/lib/secrets.js +103 -0
- package/dist/lib/secrets.js.map +1 -0
- package/dist/lib/threshold-monitor.d.ts +53 -0
- package/dist/lib/threshold-monitor.d.ts.map +1 -0
- package/dist/lib/threshold-monitor.js +112 -0
- package/dist/lib/threshold-monitor.js.map +1 -0
- package/dist/middleware/audit.d.ts +16 -0
- package/dist/middleware/audit.d.ts.map +1 -0
- package/dist/middleware/audit.js +16 -0
- package/dist/middleware/audit.js.map +1 -0
- package/dist/middleware/auth-errors.d.ts +67 -0
- package/dist/middleware/auth-errors.d.ts.map +1 -0
- package/dist/middleware/auth-errors.js +84 -0
- package/dist/middleware/auth-errors.js.map +1 -0
- package/dist/middleware/auth.d.ts +5 -2
- package/dist/middleware/auth.d.ts.map +1 -1
- package/dist/middleware/auth.js +44 -17
- package/dist/middleware/auth.js.map +1 -1
- package/dist/middleware/body-limit.d.ts +9 -0
- package/dist/middleware/body-limit.d.ts.map +1 -0
- package/dist/middleware/body-limit.js +15 -0
- package/dist/middleware/body-limit.js.map +1 -0
- package/dist/middleware/cors-config.d.ts +30 -0
- package/dist/middleware/cors-config.d.ts.map +1 -0
- package/dist/middleware/cors-config.js +55 -0
- package/dist/middleware/cors-config.js.map +1 -0
- package/dist/middleware/rate-limit.d.ts +9 -0
- package/dist/middleware/rate-limit.d.ts.map +1 -0
- package/dist/middleware/rate-limit.js +56 -0
- package/dist/middleware/rate-limit.js.map +1 -0
- package/dist/middleware/rbac.d.ts +30 -0
- package/dist/middleware/rbac.d.ts.map +1 -0
- package/dist/middleware/rbac.js +87 -0
- package/dist/middleware/rbac.js.map +1 -0
- package/dist/middleware/security-headers.d.ts +12 -0
- package/dist/middleware/security-headers.d.ts.map +1 -0
- package/dist/middleware/security-headers.js +57 -0
- package/dist/middleware/security-headers.js.map +1 -0
- package/dist/middleware/unified-auth.d.ts +49 -0
- package/dist/middleware/unified-auth.d.ts.map +1 -0
- package/dist/middleware/unified-auth.js +246 -0
- package/dist/middleware/unified-auth.js.map +1 -0
- package/dist/middleware/validation.d.ts +31 -0
- package/dist/middleware/validation.d.ts.map +1 -0
- package/dist/middleware/validation.js +45 -0
- package/dist/middleware/validation.js.map +1 -0
- package/dist/routes/alerts.d.ts.map +1 -1
- package/dist/routes/alerts.js +4 -3
- package/dist/routes/alerts.js.map +1 -1
- package/dist/routes/analytics.d.ts +2 -1
- package/dist/routes/analytics.d.ts.map +1 -1
- package/dist/routes/analytics.js +175 -95
- package/dist/routes/analytics.js.map +1 -1
- package/dist/routes/api-keys.d.ts +5 -0
- package/dist/routes/api-keys.d.ts.map +1 -1
- package/dist/routes/api-keys.js +89 -8
- package/dist/routes/api-keys.js.map +1 -1
- package/dist/routes/audit-verify.d.ts +12 -0
- package/dist/routes/audit-verify.d.ts.map +1 -0
- package/dist/routes/audit-verify.js +73 -0
- package/dist/routes/audit-verify.js.map +1 -0
- package/dist/routes/audit.d.ts +4 -6
- package/dist/routes/audit.d.ts.map +1 -1
- package/dist/routes/audit.js +54 -157
- package/dist/routes/audit.js.map +1 -1
- package/dist/routes/auth.d.ts +21 -0
- package/dist/routes/auth.d.ts.map +1 -0
- package/dist/routes/auth.js +235 -0
- package/dist/routes/auth.js.map +1 -0
- package/dist/routes/benchmarks.d.ts.map +1 -1
- package/dist/routes/benchmarks.js +63 -11
- package/dist/routes/benchmarks.js.map +1 -1
- package/dist/routes/capabilities-top.d.ts.map +1 -1
- package/dist/routes/capabilities-top.js +1 -4
- package/dist/routes/capabilities-top.js.map +1 -1
- package/dist/routes/capabilities.d.ts.map +1 -1
- package/dist/routes/capabilities.js +1 -7
- package/dist/routes/capabilities.js.map +1 -1
- package/dist/routes/compliance.d.ts +17 -0
- package/dist/routes/compliance.d.ts.map +1 -0
- package/dist/routes/compliance.js +151 -0
- package/dist/routes/compliance.js.map +1 -0
- package/dist/routes/config.d.ts +1 -13
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/context.d.ts.map +1 -1
- package/dist/routes/context.js +6 -5
- package/dist/routes/context.js.map +1 -1
- package/dist/routes/cost-budgets.d.ts +20 -0
- package/dist/routes/cost-budgets.d.ts.map +1 -0
- package/dist/routes/cost-budgets.js +194 -0
- package/dist/routes/cost-budgets.js.map +1 -0
- package/dist/routes/delegation.d.ts.map +1 -1
- package/dist/routes/delegation.js +67 -41
- package/dist/routes/delegation.js.map +1 -1
- package/dist/routes/delegations-top.d.ts.map +1 -1
- package/dist/routes/delegations-top.js +1 -3
- package/dist/routes/delegations-top.js.map +1 -1
- package/dist/routes/diagnose.d.ts +16 -0
- package/dist/routes/diagnose.d.ts.map +1 -0
- package/dist/routes/diagnose.js +82 -0
- package/dist/routes/diagnose.js.map +1 -0
- package/dist/routes/discovery.d.ts.map +1 -1
- package/dist/routes/discovery.js +50 -38
- package/dist/routes/discovery.js.map +1 -1
- package/dist/routes/eval.d.ts +24 -0
- package/dist/routes/eval.d.ts.map +1 -0
- package/dist/routes/eval.js +281 -0
- package/dist/routes/eval.js.map +1 -0
- package/dist/routes/events.d.ts.map +1 -1
- package/dist/routes/events.js +11 -6
- package/dist/routes/events.js.map +1 -1
- package/dist/routes/guardrails.d.ts +2 -1
- package/dist/routes/guardrails.d.ts.map +1 -1
- package/dist/routes/guardrails.js +85 -14
- package/dist/routes/guardrails.js.map +1 -1
- package/dist/routes/health.d.ts +14 -11
- package/dist/routes/health.d.ts.map +1 -1
- package/dist/routes/health.js +181 -61
- package/dist/routes/health.js.map +1 -1
- package/dist/routes/lore-proxy.d.ts +13 -0
- package/dist/routes/lore-proxy.d.ts.map +1 -0
- package/dist/routes/lore-proxy.js +229 -0
- package/dist/routes/lore-proxy.js.map +1 -0
- package/dist/routes/mesh-proxy.d.ts +7 -0
- package/dist/routes/mesh-proxy.d.ts.map +1 -0
- package/dist/routes/mesh-proxy.js +94 -0
- package/dist/routes/mesh-proxy.js.map +1 -0
- package/dist/routes/notifications.d.ts +19 -0
- package/dist/routes/notifications.d.ts.map +1 -0
- package/dist/routes/notifications.js +129 -0
- package/dist/routes/notifications.js.map +1 -0
- package/dist/routes/optimize.d.ts.map +1 -1
- package/dist/routes/optimize.js +44 -0
- package/dist/routes/optimize.js.map +1 -1
- package/dist/routes/otlp.d.ts +17 -0
- package/dist/routes/otlp.d.ts.map +1 -0
- package/dist/routes/otlp.js +544 -0
- package/dist/routes/otlp.js.map +1 -0
- package/dist/routes/prompts.d.ts +21 -0
- package/dist/routes/prompts.d.ts.map +1 -0
- package/dist/routes/prompts.js +173 -0
- package/dist/routes/prompts.js.map +1 -0
- package/dist/routes/recall.d.ts.map +1 -1
- package/dist/routes/recall.js +6 -4
- package/dist/routes/recall.js.map +1 -1
- package/dist/routes/replay.d.ts.map +1 -1
- package/dist/routes/replay.js +2 -1
- package/dist/routes/replay.js.map +1 -1
- package/dist/routes/server-info.d.ts +9 -0
- package/dist/routes/server-info.d.ts.map +1 -0
- package/dist/routes/server-info.js +18 -0
- package/dist/routes/server-info.js.map +1 -0
- package/dist/routes/sessions.d.ts +7 -7
- package/dist/routes/sessions.d.ts.map +1 -1
- package/dist/routes/sessions.js +112 -35
- package/dist/routes/sessions.js.map +1 -1
- package/dist/routes/stats.d.ts.map +1 -1
- package/dist/routes/stats.js +40 -0
- package/dist/routes/stats.js.map +1 -1
- package/dist/routes/stream.d.ts +2 -2
- package/dist/routes/stream.d.ts.map +1 -1
- package/dist/routes/stream.js +7 -11
- package/dist/routes/stream.js.map +1 -1
- package/dist/routes/tenant-helper.d.ts +15 -10
- package/dist/routes/tenant-helper.d.ts.map +1 -1
- package/dist/routes/tenant-helper.js +36 -22
- package/dist/routes/tenant-helper.js.map +1 -1
- package/dist/routes/trust.d.ts.map +1 -1
- package/dist/routes/trust.js +1 -3
- package/dist/routes/trust.js.map +1 -1
- package/dist/schemas/api-keys.d.ts +11 -0
- package/dist/schemas/api-keys.d.ts.map +1 -0
- package/dist/schemas/api-keys.js +10 -0
- package/dist/schemas/api-keys.js.map +1 -0
- package/dist/schemas/common.d.ts +34 -0
- package/dist/schemas/common.d.ts.map +1 -0
- package/dist/schemas/common.js +43 -0
- package/dist/schemas/common.js.map +1 -0
- package/dist/schemas/delegation.d.ts +23 -0
- package/dist/schemas/delegation.d.ts.map +1 -0
- package/dist/schemas/delegation.js +22 -0
- package/dist/schemas/delegation.js.map +1 -0
- package/dist/schemas/discovery.d.ts +17 -0
- package/dist/schemas/discovery.d.ts.map +1 -0
- package/dist/schemas/discovery.js +15 -0
- package/dist/schemas/discovery.js.map +1 -0
- package/dist/schemas/health.d.ts +75 -0
- package/dist/schemas/health.d.ts.map +1 -0
- package/dist/schemas/health.js +55 -0
- package/dist/schemas/health.js.map +1 -0
- package/dist/schemas/index.d.ts +6 -0
- package/dist/schemas/index.d.ts.map +1 -0
- package/dist/schemas/index.js +6 -0
- package/dist/schemas/index.js.map +1 -0
- package/dist/schemas/sessions.d.ts +67 -0
- package/dist/schemas/sessions.d.ts.map +1 -0
- package/dist/schemas/sessions.js +58 -0
- package/dist/schemas/sessions.js.map +1 -0
- package/dist/services/delegation-service.d.ts +1 -4
- package/dist/services/delegation-service.d.ts.map +1 -1
- package/dist/services/delegation-service.js +5 -31
- package/dist/services/delegation-service.js.map +1 -1
- package/package.json +29 -19
- package/dist/db/lesson-store.d.ts +0 -57
- package/dist/db/lesson-store.d.ts.map +0 -1
- package/dist/db/lesson-store.js +0 -217
- package/dist/db/lesson-store.js.map +0 -1
- package/dist/lib/embeddings/local.d.ts +0 -15
- package/dist/lib/embeddings/local.d.ts.map +0 -1
- package/dist/lib/embeddings/local.js +0 -65
- package/dist/lib/embeddings/local.js.map +0 -1
- package/dist/lib/redaction/human-review-layer.d.ts +0 -37
- package/dist/lib/redaction/human-review-layer.d.ts.map +0 -1
- package/dist/lib/redaction/human-review-layer.js +0 -62
- package/dist/lib/redaction/human-review-layer.js.map +0 -1
- package/dist/lib/redaction/index.d.ts +0 -12
- package/dist/lib/redaction/index.d.ts.map +0 -1
- package/dist/lib/redaction/index.js +0 -12
- package/dist/lib/redaction/index.js.map +0 -1
- package/dist/lib/redaction/pii-detection-layer.d.ts +0 -30
- package/dist/lib/redaction/pii-detection-layer.d.ts.map +0 -1
- package/dist/lib/redaction/pii-detection-layer.js +0 -183
- package/dist/lib/redaction/pii-detection-layer.js.map +0 -1
- package/dist/lib/redaction/pipeline.d.ts +0 -26
- package/dist/lib/redaction/pipeline.d.ts.map +0 -1
- package/dist/lib/redaction/pipeline.js +0 -91
- package/dist/lib/redaction/pipeline.js.map +0 -1
- package/dist/lib/redaction/secret-detection-layer.d.ts +0 -10
- package/dist/lib/redaction/secret-detection-layer.d.ts.map +0 -1
- package/dist/lib/redaction/secret-detection-layer.js +0 -79
- package/dist/lib/redaction/secret-detection-layer.js.map +0 -1
- package/dist/lib/redaction/secret-patterns.d.ts +0 -29
- package/dist/lib/redaction/secret-patterns.d.ts.map +0 -1
- package/dist/lib/redaction/secret-patterns.js +0 -133
- package/dist/lib/redaction/secret-patterns.js.map +0 -1
- package/dist/lib/redaction/semantic-denylist-layer.d.ts +0 -10
- package/dist/lib/redaction/semantic-denylist-layer.d.ts.map +0 -1
- package/dist/lib/redaction/semantic-denylist-layer.js +0 -64
- package/dist/lib/redaction/semantic-denylist-layer.js.map +0 -1
- package/dist/lib/redaction/tenant-deidentification-layer.d.ts +0 -10
- package/dist/lib/redaction/tenant-deidentification-layer.d.ts.map +0 -1
- package/dist/lib/redaction/tenant-deidentification-layer.js +0 -64
- package/dist/lib/redaction/tenant-deidentification-layer.js.map +0 -1
- package/dist/lib/redaction/url-path-scrubbing-layer.d.ts +0 -14
- package/dist/lib/redaction/url-path-scrubbing-layer.d.ts.map +0 -1
- package/dist/lib/redaction/url-path-scrubbing-layer.js +0 -156
- package/dist/lib/redaction/url-path-scrubbing-layer.js.map +0 -1
- package/dist/routes/community.d.ts +0 -24
- package/dist/routes/community.d.ts.map +0 -1
- package/dist/routes/community.js +0 -272
- package/dist/routes/community.js.map +0 -1
- package/dist/routes/lessons.d.ts +0 -19
- package/dist/routes/lessons.d.ts.map +0 -1
- package/dist/routes/lessons.js +0 -164
- package/dist/routes/lessons.js.map +0 -1
- package/dist/routes/redaction-test.d.ts +0 -14
- package/dist/routes/redaction-test.d.ts.map +0 -1
- package/dist/routes/redaction-test.js +0 -33
- package/dist/routes/redaction-test.js.map +0 -1
- package/dist/services/community-service.d.ts +0 -283
- package/dist/services/community-service.d.ts.map +0 -1
- package/dist/services/community-service.js +0 -816
- package/dist/services/community-service.js.map +0 -1
|
@@ -0,0 +1,910 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL implementation of IEventStore.
|
|
3
|
+
*
|
|
4
|
+
* Uses Drizzle ORM with postgres.js driver and the Postgres schema
|
|
5
|
+
* (jsonb columns, native PG functions).
|
|
6
|
+
*/
|
|
7
|
+
import { eq, and, gte, lte, desc, asc, sql, inArray, count as drizzleCount } from 'drizzle-orm';
|
|
8
|
+
import { computeEventHash } from '@agentlensai/core';
|
|
9
|
+
import { events, sessions, agents, alertRules, alertHistory, } from './schema.postgres.js';
|
|
10
|
+
import { HashChainError, NotFoundError } from './errors.js';
|
|
11
|
+
import { createLogger } from '../lib/logger.js';
|
|
12
|
+
import { withRetry } from '../lib/db-resilience.js';
|
|
13
|
+
const log = createLogger('PostgresEventStore');
|
|
14
|
+
// ─── Helpers ────────────────────────────────────────────────
|
|
15
|
+
function safeJsonParse(raw, fallback) {
|
|
16
|
+
if (raw === null || raw === undefined)
|
|
17
|
+
return fallback;
|
|
18
|
+
if (typeof raw === 'object')
|
|
19
|
+
return raw;
|
|
20
|
+
if (typeof raw === 'string') {
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse(raw);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return fallback;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return fallback;
|
|
29
|
+
}
|
|
30
|
+
/** Build event WHERE conditions for Postgres schema. */
|
|
31
|
+
function buildEventConditions(query) {
|
|
32
|
+
const conditions = [];
|
|
33
|
+
if (query.tenantId)
|
|
34
|
+
conditions.push(eq(events.tenantId, query.tenantId));
|
|
35
|
+
if (query.sessionId)
|
|
36
|
+
conditions.push(eq(events.sessionId, query.sessionId));
|
|
37
|
+
if (query.agentId)
|
|
38
|
+
conditions.push(eq(events.agentId, query.agentId));
|
|
39
|
+
if (query.eventType) {
|
|
40
|
+
if (Array.isArray(query.eventType)) {
|
|
41
|
+
conditions.push(inArray(events.eventType, query.eventType));
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
conditions.push(eq(events.eventType, query.eventType));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (query.severity) {
|
|
48
|
+
if (Array.isArray(query.severity)) {
|
|
49
|
+
conditions.push(inArray(events.severity, query.severity));
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
conditions.push(eq(events.severity, query.severity));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (query.from)
|
|
56
|
+
conditions.push(gte(events.timestamp, query.from));
|
|
57
|
+
if (query.to)
|
|
58
|
+
conditions.push(lte(events.timestamp, query.to));
|
|
59
|
+
if (query.search) {
|
|
60
|
+
const searchTerm = query.search.slice(0, 500);
|
|
61
|
+
const escaped = searchTerm
|
|
62
|
+
.replace(/\\/g, '\\\\')
|
|
63
|
+
.replace(/%/g, '\\%')
|
|
64
|
+
.replace(/_/g, '\\_');
|
|
65
|
+
// Cast jsonb payload to text for LIKE search
|
|
66
|
+
conditions.push(sql `${events.payload}::text LIKE ${'%' + escaped + '%'} ESCAPE '\\'`);
|
|
67
|
+
}
|
|
68
|
+
return conditions;
|
|
69
|
+
}
|
|
70
|
+
/** Build session WHERE conditions for Postgres schema. */
|
|
71
|
+
function buildSessionConditions(query) {
|
|
72
|
+
const conditions = [];
|
|
73
|
+
if (query.tenantId)
|
|
74
|
+
conditions.push(eq(sessions.tenantId, query.tenantId));
|
|
75
|
+
if (query.agentId)
|
|
76
|
+
conditions.push(eq(sessions.agentId, query.agentId));
|
|
77
|
+
if (query.status) {
|
|
78
|
+
if (Array.isArray(query.status)) {
|
|
79
|
+
if (query.status.length === 1)
|
|
80
|
+
conditions.push(eq(sessions.status, query.status[0]));
|
|
81
|
+
else if (query.status.length > 1)
|
|
82
|
+
conditions.push(inArray(sessions.status, query.status));
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
conditions.push(eq(sessions.status, query.status));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (query.from)
|
|
89
|
+
conditions.push(gte(sessions.startedAt, query.from));
|
|
90
|
+
if (query.to)
|
|
91
|
+
conditions.push(lte(sessions.startedAt, query.to));
|
|
92
|
+
if (query.tags && query.tags.length > 0) {
|
|
93
|
+
// Use jsonb ?| operator for tag matching (OR semantics)
|
|
94
|
+
conditions.push(sql `${sessions.tags} ?| array[${sql.join(query.tags.map(t => sql `${t}`), sql `, `)}]`);
|
|
95
|
+
}
|
|
96
|
+
return conditions;
|
|
97
|
+
}
|
|
98
|
+
/** Map PG event row → AgentLensEvent (jsonb columns are already objects). */
|
|
99
|
+
function mapEventRow(row) {
|
|
100
|
+
return {
|
|
101
|
+
id: row.id,
|
|
102
|
+
timestamp: row.timestamp,
|
|
103
|
+
sessionId: row.sessionId,
|
|
104
|
+
agentId: row.agentId,
|
|
105
|
+
eventType: row.eventType,
|
|
106
|
+
severity: row.severity,
|
|
107
|
+
payload: safeJsonParse(row.payload, {}),
|
|
108
|
+
metadata: safeJsonParse(row.metadata, {}),
|
|
109
|
+
prevHash: row.prevHash,
|
|
110
|
+
hash: row.hash,
|
|
111
|
+
tenantId: row.tenantId,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function mapSessionRow(row) {
|
|
115
|
+
return {
|
|
116
|
+
id: row.id,
|
|
117
|
+
agentId: row.agentId,
|
|
118
|
+
agentName: row.agentName ?? undefined,
|
|
119
|
+
startedAt: row.startedAt,
|
|
120
|
+
endedAt: row.endedAt ?? undefined,
|
|
121
|
+
status: row.status,
|
|
122
|
+
eventCount: row.eventCount,
|
|
123
|
+
toolCallCount: row.toolCallCount,
|
|
124
|
+
errorCount: row.errorCount,
|
|
125
|
+
totalCostUsd: row.totalCostUsd,
|
|
126
|
+
llmCallCount: row.llmCallCount,
|
|
127
|
+
totalInputTokens: row.totalInputTokens,
|
|
128
|
+
totalOutputTokens: row.totalOutputTokens,
|
|
129
|
+
tags: safeJsonParse(row.tags, []),
|
|
130
|
+
tenantId: row.tenantId,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function mapAgentRow(row) {
|
|
134
|
+
return {
|
|
135
|
+
id: row.id,
|
|
136
|
+
name: row.name,
|
|
137
|
+
description: row.description ?? undefined,
|
|
138
|
+
firstSeenAt: row.firstSeenAt,
|
|
139
|
+
lastSeenAt: row.lastSeenAt,
|
|
140
|
+
sessionCount: row.sessionCount,
|
|
141
|
+
tenantId: row.tenantId,
|
|
142
|
+
modelOverride: row.modelOverride ?? undefined,
|
|
143
|
+
pausedAt: row.pausedAt ?? undefined,
|
|
144
|
+
pauseReason: row.pauseReason ?? undefined,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function mapAlertRuleRow(row) {
|
|
148
|
+
return {
|
|
149
|
+
id: row.id,
|
|
150
|
+
name: row.name,
|
|
151
|
+
enabled: row.enabled,
|
|
152
|
+
condition: row.condition,
|
|
153
|
+
threshold: row.threshold,
|
|
154
|
+
windowMinutes: row.windowMinutes,
|
|
155
|
+
scope: safeJsonParse(row.scope, {}),
|
|
156
|
+
notifyChannels: safeJsonParse(row.notifyChannels, []),
|
|
157
|
+
createdAt: row.createdAt,
|
|
158
|
+
updatedAt: row.updatedAt,
|
|
159
|
+
tenantId: row.tenantId,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function warnIfNoTenant(method, tenantId) {
|
|
163
|
+
if (tenantId === undefined) {
|
|
164
|
+
log.warn(`${method}() called without tenantId — query is unscoped. ` +
|
|
165
|
+
`Ensure tenant isolation is applied upstream (via TenantScopedStore).`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// ─── PostgresEventStore ─────────────────────────────────────
|
|
169
|
+
export class PostgresEventStore {
|
|
170
|
+
db;
|
|
171
|
+
constructor(db) {
|
|
172
|
+
this.db = db;
|
|
173
|
+
}
|
|
174
|
+
// ─── Events ────────────────────────────────────────────────
|
|
175
|
+
async insertEvents(eventList) {
|
|
176
|
+
if (eventList.length === 0)
|
|
177
|
+
return;
|
|
178
|
+
await withRetry(() => this.db.transaction(async (tx) => {
|
|
179
|
+
const firstEvent = eventList[0];
|
|
180
|
+
const tenantId = firstEvent.tenantId ?? 'default';
|
|
181
|
+
// Check if first event already exists
|
|
182
|
+
const [existingFirst] = await tx
|
|
183
|
+
.select({ id: events.id })
|
|
184
|
+
.from(events)
|
|
185
|
+
.where(eq(events.id, firstEvent.id))
|
|
186
|
+
.limit(1);
|
|
187
|
+
if (!existingFirst) {
|
|
188
|
+
// Verify chain continuity
|
|
189
|
+
const [lastStoredEvent] = await tx
|
|
190
|
+
.select({ hash: events.hash })
|
|
191
|
+
.from(events)
|
|
192
|
+
.where(and(eq(events.sessionId, firstEvent.sessionId), eq(events.tenantId, tenantId)))
|
|
193
|
+
.orderBy(desc(events.timestamp), desc(events.id))
|
|
194
|
+
.limit(1);
|
|
195
|
+
const lastStoredHash = lastStoredEvent?.hash ?? null;
|
|
196
|
+
if (firstEvent.prevHash !== lastStoredHash) {
|
|
197
|
+
throw new HashChainError(`Chain continuity broken: event ${firstEvent.id} has prevHash=${firstEvent.prevHash} but last stored hash is ${lastStoredHash}`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
// Verify hashes within batch
|
|
201
|
+
for (let i = 0; i < eventList.length; i++) {
|
|
202
|
+
const event = eventList[i];
|
|
203
|
+
if (i > 0) {
|
|
204
|
+
const prevEvent = eventList[i - 1];
|
|
205
|
+
if (event.prevHash !== prevEvent.hash) {
|
|
206
|
+
throw new HashChainError(`Chain continuity broken within batch: event ${event.id} has prevHash=${event.prevHash} but previous event hash is ${prevEvent.hash}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const recomputedHash = computeEventHash({
|
|
210
|
+
id: event.id,
|
|
211
|
+
timestamp: event.timestamp,
|
|
212
|
+
sessionId: event.sessionId,
|
|
213
|
+
agentId: event.agentId,
|
|
214
|
+
eventType: event.eventType,
|
|
215
|
+
severity: event.severity,
|
|
216
|
+
payload: event.payload,
|
|
217
|
+
metadata: event.metadata,
|
|
218
|
+
prevHash: event.prevHash,
|
|
219
|
+
});
|
|
220
|
+
if (event.hash !== recomputedHash) {
|
|
221
|
+
throw new HashChainError(`Hash mismatch for event ${event.id}: supplied=${event.hash}, computed=${recomputedHash}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// Insert events and update sessions/agents
|
|
225
|
+
for (const event of eventList) {
|
|
226
|
+
const evTenantId = event.tenantId ?? 'default';
|
|
227
|
+
await tx
|
|
228
|
+
.insert(events)
|
|
229
|
+
.values({
|
|
230
|
+
id: event.id,
|
|
231
|
+
timestamp: event.timestamp,
|
|
232
|
+
sessionId: event.sessionId,
|
|
233
|
+
agentId: event.agentId,
|
|
234
|
+
eventType: event.eventType,
|
|
235
|
+
severity: event.severity,
|
|
236
|
+
payload: event.payload,
|
|
237
|
+
metadata: event.metadata,
|
|
238
|
+
prevHash: event.prevHash,
|
|
239
|
+
hash: event.hash,
|
|
240
|
+
tenantId: evTenantId,
|
|
241
|
+
})
|
|
242
|
+
.onConflictDoNothing({ target: events.id });
|
|
243
|
+
// Handle session update
|
|
244
|
+
await this.handleSessionUpdate(tx, event, evTenantId);
|
|
245
|
+
// Handle agent upsert
|
|
246
|
+
await this.handleAgentUpsert(tx, event, evTenantId);
|
|
247
|
+
}
|
|
248
|
+
}));
|
|
249
|
+
}
|
|
250
|
+
async handleSessionUpdate(tx, event, tenantId) {
|
|
251
|
+
if (event.eventType === 'session_started') {
|
|
252
|
+
const payload = event.payload;
|
|
253
|
+
const tags = payload.tags ?? [];
|
|
254
|
+
const agentName = payload.agentName ?? undefined;
|
|
255
|
+
await tx
|
|
256
|
+
.insert(sessions)
|
|
257
|
+
.values({
|
|
258
|
+
id: event.sessionId,
|
|
259
|
+
agentId: event.agentId,
|
|
260
|
+
agentName: agentName,
|
|
261
|
+
startedAt: event.timestamp,
|
|
262
|
+
status: 'active',
|
|
263
|
+
eventCount: 1,
|
|
264
|
+
toolCallCount: 0,
|
|
265
|
+
errorCount: 0,
|
|
266
|
+
totalCostUsd: 0,
|
|
267
|
+
tags: tags,
|
|
268
|
+
tenantId,
|
|
269
|
+
})
|
|
270
|
+
.onConflictDoUpdate({
|
|
271
|
+
target: [sessions.id, sessions.tenantId],
|
|
272
|
+
set: {
|
|
273
|
+
agentName: agentName ?? sql `coalesce(${sessions.agentName}, NULL)`,
|
|
274
|
+
status: 'active',
|
|
275
|
+
eventCount: sql `${sessions.eventCount} + 1`,
|
|
276
|
+
tags: tags.length > 0 ? tags : sql `${sessions.tags}`,
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
// Ensure session exists
|
|
282
|
+
await tx
|
|
283
|
+
.insert(sessions)
|
|
284
|
+
.values({
|
|
285
|
+
id: event.sessionId,
|
|
286
|
+
agentId: event.agentId,
|
|
287
|
+
startedAt: event.timestamp,
|
|
288
|
+
status: 'active',
|
|
289
|
+
eventCount: 0,
|
|
290
|
+
toolCallCount: 0,
|
|
291
|
+
errorCount: 0,
|
|
292
|
+
totalCostUsd: 0,
|
|
293
|
+
tags: [],
|
|
294
|
+
tenantId,
|
|
295
|
+
})
|
|
296
|
+
.onConflictDoNothing({ target: [sessions.id, sessions.tenantId] });
|
|
297
|
+
const isToolCall = event.eventType === 'tool_call';
|
|
298
|
+
const isError = event.severity === 'error' || event.severity === 'critical' || event.eventType === 'tool_error';
|
|
299
|
+
const isCost = event.eventType === 'cost_tracked';
|
|
300
|
+
const isLlmResponse = event.eventType === 'llm_response';
|
|
301
|
+
const costPayload = event.payload;
|
|
302
|
+
const costUsd = isCost ? (Number(costPayload.costUsd) || 0) : 0;
|
|
303
|
+
const llmCostUsd = isLlmResponse ? (Number(costPayload.costUsd) || 0) : 0;
|
|
304
|
+
const llmUsage = isLlmResponse ? costPayload.usage : undefined;
|
|
305
|
+
const llmInputTokens = llmUsage ? (Number(llmUsage.inputTokens) || 0) : 0;
|
|
306
|
+
const llmOutputTokens = llmUsage ? (Number(llmUsage.outputTokens) || 0) : 0;
|
|
307
|
+
if (event.eventType === 'session_ended') {
|
|
308
|
+
const payload = event.payload;
|
|
309
|
+
const reason = payload.reason;
|
|
310
|
+
const status = reason === 'error' ? 'error' : 'completed';
|
|
311
|
+
await tx
|
|
312
|
+
.update(sessions)
|
|
313
|
+
.set({
|
|
314
|
+
endedAt: event.timestamp,
|
|
315
|
+
status,
|
|
316
|
+
eventCount: sql `${sessions.eventCount} + 1`,
|
|
317
|
+
errorCount: isError ? sql `${sessions.errorCount} + 1` : sessions.errorCount,
|
|
318
|
+
})
|
|
319
|
+
.where(and(eq(sessions.id, event.sessionId), eq(sessions.tenantId, tenantId)));
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
await tx
|
|
323
|
+
.update(sessions)
|
|
324
|
+
.set({
|
|
325
|
+
eventCount: sql `${sessions.eventCount} + 1`,
|
|
326
|
+
toolCallCount: isToolCall ? sql `${sessions.toolCallCount} + 1` : sessions.toolCallCount,
|
|
327
|
+
errorCount: isError ? sql `${sessions.errorCount} + 1` : sessions.errorCount,
|
|
328
|
+
totalCostUsd: isCost
|
|
329
|
+
? sql `${sessions.totalCostUsd} + ${costUsd}`
|
|
330
|
+
: isLlmResponse
|
|
331
|
+
? sql `${sessions.totalCostUsd} + ${llmCostUsd}`
|
|
332
|
+
: sessions.totalCostUsd,
|
|
333
|
+
llmCallCount: isLlmResponse ? sql `${sessions.llmCallCount} + 1` : sessions.llmCallCount,
|
|
334
|
+
totalInputTokens: isLlmResponse ? sql `${sessions.totalInputTokens} + ${llmInputTokens}` : sessions.totalInputTokens,
|
|
335
|
+
totalOutputTokens: isLlmResponse ? sql `${sessions.totalOutputTokens} + ${llmOutputTokens}` : sessions.totalOutputTokens,
|
|
336
|
+
})
|
|
337
|
+
.where(and(eq(sessions.id, event.sessionId), eq(sessions.tenantId, tenantId)));
|
|
338
|
+
}
|
|
339
|
+
async handleAgentUpsert(tx, event, tenantId) {
|
|
340
|
+
const payload = event.payload;
|
|
341
|
+
const agentName = payload.agentName ?? event.agentId;
|
|
342
|
+
await tx
|
|
343
|
+
.insert(agents)
|
|
344
|
+
.values({
|
|
345
|
+
id: event.agentId,
|
|
346
|
+
name: agentName,
|
|
347
|
+
firstSeenAt: event.timestamp,
|
|
348
|
+
lastSeenAt: event.timestamp,
|
|
349
|
+
sessionCount: event.eventType === 'session_started' ? 1 : 0,
|
|
350
|
+
tenantId,
|
|
351
|
+
})
|
|
352
|
+
.onConflictDoUpdate({
|
|
353
|
+
target: [agents.id, agents.tenantId],
|
|
354
|
+
set: {
|
|
355
|
+
lastSeenAt: event.timestamp,
|
|
356
|
+
sessionCount: event.eventType === 'session_started'
|
|
357
|
+
? sql `${agents.sessionCount} + 1`
|
|
358
|
+
: agents.sessionCount,
|
|
359
|
+
},
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
async queryEvents(query) {
|
|
363
|
+
const limit = Math.min(query.limit ?? 50, 500);
|
|
364
|
+
const offset = query.offset ?? 0;
|
|
365
|
+
const orderDir = query.order === 'asc' ? asc : desc;
|
|
366
|
+
const conditions = buildEventConditions(query);
|
|
367
|
+
const rows = await this.db
|
|
368
|
+
.select()
|
|
369
|
+
.from(events)
|
|
370
|
+
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
|
371
|
+
.orderBy(orderDir(events.timestamp))
|
|
372
|
+
.limit(limit)
|
|
373
|
+
.offset(offset);
|
|
374
|
+
const total = await this.countEvents(query);
|
|
375
|
+
return {
|
|
376
|
+
events: rows.map(mapEventRow),
|
|
377
|
+
total,
|
|
378
|
+
hasMore: offset + rows.length < total,
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
async getEvent(id, tenantId) {
|
|
382
|
+
warnIfNoTenant('getEvent', tenantId);
|
|
383
|
+
const conditions = [eq(events.id, id)];
|
|
384
|
+
if (tenantId)
|
|
385
|
+
conditions.push(eq(events.tenantId, tenantId));
|
|
386
|
+
const [row] = await this.db
|
|
387
|
+
.select()
|
|
388
|
+
.from(events)
|
|
389
|
+
.where(and(...conditions))
|
|
390
|
+
.limit(1);
|
|
391
|
+
return row ? mapEventRow(row) : null;
|
|
392
|
+
}
|
|
393
|
+
async getSessionTimeline(sessionId, tenantId) {
|
|
394
|
+
const conditions = [eq(events.sessionId, sessionId)];
|
|
395
|
+
if (tenantId)
|
|
396
|
+
conditions.push(eq(events.tenantId, tenantId));
|
|
397
|
+
const rows = await this.db
|
|
398
|
+
.select()
|
|
399
|
+
.from(events)
|
|
400
|
+
.where(and(...conditions))
|
|
401
|
+
.orderBy(asc(events.timestamp));
|
|
402
|
+
return rows.map(mapEventRow);
|
|
403
|
+
}
|
|
404
|
+
async getLastEventHash(sessionId, tenantId) {
|
|
405
|
+
const conditions = [eq(events.sessionId, sessionId)];
|
|
406
|
+
if (tenantId)
|
|
407
|
+
conditions.push(eq(events.tenantId, tenantId));
|
|
408
|
+
const [row] = await this.db
|
|
409
|
+
.select({ hash: events.hash })
|
|
410
|
+
.from(events)
|
|
411
|
+
.where(and(...conditions))
|
|
412
|
+
.orderBy(desc(events.timestamp), desc(events.id))
|
|
413
|
+
.limit(1);
|
|
414
|
+
return row?.hash ?? null;
|
|
415
|
+
}
|
|
416
|
+
async countEvents(query) {
|
|
417
|
+
const conditions = buildEventConditions(query);
|
|
418
|
+
const [result] = await this.db
|
|
419
|
+
.select({ count: drizzleCount() })
|
|
420
|
+
.from(events)
|
|
421
|
+
.where(conditions.length > 0 ? and(...conditions) : undefined);
|
|
422
|
+
return result?.count ?? 0;
|
|
423
|
+
}
|
|
424
|
+
async countEventsBatch(query) {
|
|
425
|
+
const conditions = [];
|
|
426
|
+
if (query.tenantId)
|
|
427
|
+
conditions.push(eq(events.tenantId, query.tenantId));
|
|
428
|
+
conditions.push(eq(events.agentId, query.agentId));
|
|
429
|
+
conditions.push(gte(events.timestamp, query.from));
|
|
430
|
+
conditions.push(lte(events.timestamp, query.to));
|
|
431
|
+
// Use PG FILTER clause for efficiency
|
|
432
|
+
const [result] = await this.db
|
|
433
|
+
.select({
|
|
434
|
+
total: drizzleCount(),
|
|
435
|
+
error: sql `count(*) FILTER (WHERE ${events.severity} = 'error')`,
|
|
436
|
+
critical: sql `count(*) FILTER (WHERE ${events.severity} = 'critical')`,
|
|
437
|
+
toolError: sql `count(*) FILTER (WHERE ${events.eventType} = 'tool_error')`,
|
|
438
|
+
})
|
|
439
|
+
.from(events)
|
|
440
|
+
.where(and(...conditions));
|
|
441
|
+
return {
|
|
442
|
+
total: result?.total ?? 0,
|
|
443
|
+
error: Number(result?.error ?? 0),
|
|
444
|
+
critical: Number(result?.critical ?? 0),
|
|
445
|
+
toolError: Number(result?.toolError ?? 0),
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
// ─── Sessions ──────────────────────────────────────────────
|
|
449
|
+
async upsertSession(session) {
|
|
450
|
+
await withRetry(async () => {
|
|
451
|
+
const tenantId = session.tenantId ?? 'default';
|
|
452
|
+
const [existing] = await this.db
|
|
453
|
+
.select()
|
|
454
|
+
.from(sessions)
|
|
455
|
+
.where(and(eq(sessions.id, session.id), eq(sessions.tenantId, tenantId)))
|
|
456
|
+
.limit(1);
|
|
457
|
+
if (existing) {
|
|
458
|
+
const updates = {};
|
|
459
|
+
if (session.agentId !== undefined)
|
|
460
|
+
updates.agentId = session.agentId;
|
|
461
|
+
if (session.agentName !== undefined)
|
|
462
|
+
updates.agentName = session.agentName;
|
|
463
|
+
if (session.startedAt !== undefined)
|
|
464
|
+
updates.startedAt = session.startedAt;
|
|
465
|
+
if (session.endedAt !== undefined)
|
|
466
|
+
updates.endedAt = session.endedAt;
|
|
467
|
+
if (session.status !== undefined)
|
|
468
|
+
updates.status = session.status;
|
|
469
|
+
if (session.eventCount !== undefined)
|
|
470
|
+
updates.eventCount = session.eventCount;
|
|
471
|
+
if (session.toolCallCount !== undefined)
|
|
472
|
+
updates.toolCallCount = session.toolCallCount;
|
|
473
|
+
if (session.errorCount !== undefined)
|
|
474
|
+
updates.errorCount = session.errorCount;
|
|
475
|
+
if (session.totalCostUsd !== undefined)
|
|
476
|
+
updates.totalCostUsd = session.totalCostUsd;
|
|
477
|
+
if (session.llmCallCount !== undefined)
|
|
478
|
+
updates.llmCallCount = session.llmCallCount;
|
|
479
|
+
if (session.totalInputTokens !== undefined)
|
|
480
|
+
updates.totalInputTokens = session.totalInputTokens;
|
|
481
|
+
if (session.totalOutputTokens !== undefined)
|
|
482
|
+
updates.totalOutputTokens = session.totalOutputTokens;
|
|
483
|
+
if (session.tags !== undefined)
|
|
484
|
+
updates.tags = session.tags;
|
|
485
|
+
if (Object.keys(updates).length > 0) {
|
|
486
|
+
await this.db
|
|
487
|
+
.update(sessions)
|
|
488
|
+
.set(updates)
|
|
489
|
+
.where(and(eq(sessions.id, session.id), eq(sessions.tenantId, tenantId)));
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
else {
|
|
493
|
+
await this.db.insert(sessions).values({
|
|
494
|
+
id: session.id,
|
|
495
|
+
agentId: session.agentId ?? '',
|
|
496
|
+
startedAt: session.startedAt ?? new Date().toISOString(),
|
|
497
|
+
status: session.status ?? 'active',
|
|
498
|
+
agentName: session.agentName,
|
|
499
|
+
endedAt: session.endedAt,
|
|
500
|
+
eventCount: session.eventCount ?? 0,
|
|
501
|
+
toolCallCount: session.toolCallCount ?? 0,
|
|
502
|
+
errorCount: session.errorCount ?? 0,
|
|
503
|
+
totalCostUsd: session.totalCostUsd ?? 0,
|
|
504
|
+
llmCallCount: session.llmCallCount ?? 0,
|
|
505
|
+
totalInputTokens: session.totalInputTokens ?? 0,
|
|
506
|
+
totalOutputTokens: session.totalOutputTokens ?? 0,
|
|
507
|
+
tags: session.tags ?? [],
|
|
508
|
+
tenantId,
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
async querySessions(query) {
|
|
514
|
+
warnIfNoTenant('querySessions', query.tenantId);
|
|
515
|
+
const limit = Math.min(query.limit ?? 50, 500);
|
|
516
|
+
const offset = query.offset ?? 0;
|
|
517
|
+
const conditions = buildSessionConditions(query);
|
|
518
|
+
const rows = await this.db
|
|
519
|
+
.select()
|
|
520
|
+
.from(sessions)
|
|
521
|
+
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
|
522
|
+
.orderBy(desc(sessions.startedAt))
|
|
523
|
+
.limit(limit)
|
|
524
|
+
.offset(offset);
|
|
525
|
+
const [totalResult] = await this.db
|
|
526
|
+
.select({ count: drizzleCount() })
|
|
527
|
+
.from(sessions)
|
|
528
|
+
.where(conditions.length > 0 ? and(...conditions) : undefined);
|
|
529
|
+
return {
|
|
530
|
+
sessions: rows.map(mapSessionRow),
|
|
531
|
+
total: totalResult?.count ?? 0,
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
async getSession(id, tenantId) {
|
|
535
|
+
const conditions = [eq(sessions.id, id)];
|
|
536
|
+
if (tenantId)
|
|
537
|
+
conditions.push(eq(sessions.tenantId, tenantId));
|
|
538
|
+
const [row] = await this.db
|
|
539
|
+
.select()
|
|
540
|
+
.from(sessions)
|
|
541
|
+
.where(and(...conditions))
|
|
542
|
+
.limit(1);
|
|
543
|
+
return row ? mapSessionRow(row) : null;
|
|
544
|
+
}
|
|
545
|
+
async sumSessionCost(query) {
|
|
546
|
+
const conditions = [];
|
|
547
|
+
if (query.tenantId)
|
|
548
|
+
conditions.push(eq(sessions.tenantId, query.tenantId));
|
|
549
|
+
conditions.push(eq(sessions.agentId, query.agentId));
|
|
550
|
+
conditions.push(gte(sessions.startedAt, query.from));
|
|
551
|
+
const [result] = await this.db
|
|
552
|
+
.select({ total: sql `COALESCE(SUM(${sessions.totalCostUsd}), 0)` })
|
|
553
|
+
.from(sessions)
|
|
554
|
+
.where(and(...conditions));
|
|
555
|
+
return result?.total ?? 0;
|
|
556
|
+
}
|
|
557
|
+
// ─── Agents ────────────────────────────────────────────────
|
|
558
|
+
async upsertAgent(agent) {
|
|
559
|
+
const tenantId = agent.tenantId ?? 'default';
|
|
560
|
+
const [existing] = await this.db
|
|
561
|
+
.select()
|
|
562
|
+
.from(agents)
|
|
563
|
+
.where(and(eq(agents.id, agent.id), eq(agents.tenantId, tenantId)))
|
|
564
|
+
.limit(1);
|
|
565
|
+
if (existing) {
|
|
566
|
+
const updates = {};
|
|
567
|
+
if (agent.name !== undefined)
|
|
568
|
+
updates.name = agent.name;
|
|
569
|
+
if (agent.description !== undefined)
|
|
570
|
+
updates.description = agent.description;
|
|
571
|
+
if (agent.lastSeenAt !== undefined)
|
|
572
|
+
updates.lastSeenAt = agent.lastSeenAt;
|
|
573
|
+
if (agent.sessionCount !== undefined)
|
|
574
|
+
updates.sessionCount = agent.sessionCount;
|
|
575
|
+
if (Object.keys(updates).length > 0) {
|
|
576
|
+
await this.db
|
|
577
|
+
.update(agents)
|
|
578
|
+
.set(updates)
|
|
579
|
+
.where(and(eq(agents.id, agent.id), eq(agents.tenantId, tenantId)));
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
else {
|
|
583
|
+
const now = new Date().toISOString();
|
|
584
|
+
await this.db.insert(agents).values({
|
|
585
|
+
id: agent.id,
|
|
586
|
+
name: agent.name ?? agent.id,
|
|
587
|
+
description: agent.description,
|
|
588
|
+
firstSeenAt: agent.firstSeenAt ?? now,
|
|
589
|
+
lastSeenAt: agent.lastSeenAt ?? now,
|
|
590
|
+
sessionCount: agent.sessionCount ?? 0,
|
|
591
|
+
tenantId,
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
async pauseAgent(tenantId, agentId, reason) {
|
|
596
|
+
const result = await this.db
|
|
597
|
+
.update(agents)
|
|
598
|
+
.set({ pausedAt: new Date().toISOString(), pauseReason: reason })
|
|
599
|
+
.where(and(eq(agents.id, agentId), eq(agents.tenantId, tenantId)));
|
|
600
|
+
return result.rowCount > 0;
|
|
601
|
+
}
|
|
602
|
+
async unpauseAgent(tenantId, agentId, clearModelOverride) {
|
|
603
|
+
const updates = { pausedAt: null, pauseReason: null };
|
|
604
|
+
if (clearModelOverride)
|
|
605
|
+
updates.modelOverride = null;
|
|
606
|
+
const result = await this.db
|
|
607
|
+
.update(agents)
|
|
608
|
+
.set(updates)
|
|
609
|
+
.where(and(eq(agents.id, agentId), eq(agents.tenantId, tenantId)));
|
|
610
|
+
return result.rowCount > 0;
|
|
611
|
+
}
|
|
612
|
+
async setModelOverride(tenantId, agentId, model) {
|
|
613
|
+
const result = await this.db
|
|
614
|
+
.update(agents)
|
|
615
|
+
.set({ modelOverride: model })
|
|
616
|
+
.where(and(eq(agents.id, agentId), eq(agents.tenantId, tenantId)));
|
|
617
|
+
return result.rowCount > 0;
|
|
618
|
+
}
|
|
619
|
+
async listAgents(tenantId) {
|
|
620
|
+
warnIfNoTenant('listAgents', tenantId);
|
|
621
|
+
const conditions = tenantId ? [eq(agents.tenantId, tenantId)] : [];
|
|
622
|
+
const rows = await this.db
|
|
623
|
+
.select()
|
|
624
|
+
.from(agents)
|
|
625
|
+
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
|
626
|
+
.orderBy(desc(agents.lastSeenAt));
|
|
627
|
+
return rows.map(mapAgentRow);
|
|
628
|
+
}
|
|
629
|
+
async getAgent(id, tenantId) {
|
|
630
|
+
const conditions = [eq(agents.id, id)];
|
|
631
|
+
if (tenantId)
|
|
632
|
+
conditions.push(eq(agents.tenantId, tenantId));
|
|
633
|
+
const [row] = await this.db
|
|
634
|
+
.select()
|
|
635
|
+
.from(agents)
|
|
636
|
+
.where(and(...conditions))
|
|
637
|
+
.limit(1);
|
|
638
|
+
return row ? mapAgentRow(row) : null;
|
|
639
|
+
}
|
|
640
|
+
// ─── Alerts ────────────────────────────────────────────────
|
|
641
|
+
async createAlertRule(rule) {
|
|
642
|
+
await this.db.insert(alertRules).values({
|
|
643
|
+
id: rule.id,
|
|
644
|
+
name: rule.name,
|
|
645
|
+
enabled: rule.enabled,
|
|
646
|
+
condition: rule.condition,
|
|
647
|
+
threshold: rule.threshold,
|
|
648
|
+
windowMinutes: rule.windowMinutes,
|
|
649
|
+
scope: rule.scope,
|
|
650
|
+
notifyChannels: rule.notifyChannels,
|
|
651
|
+
createdAt: rule.createdAt,
|
|
652
|
+
updatedAt: rule.updatedAt,
|
|
653
|
+
tenantId: rule.tenantId ?? 'default',
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
async updateAlertRule(id, updates, tenantId) {
|
|
657
|
+
const setValues = {};
|
|
658
|
+
if (updates.name !== undefined)
|
|
659
|
+
setValues.name = updates.name;
|
|
660
|
+
if (updates.enabled !== undefined)
|
|
661
|
+
setValues.enabled = updates.enabled;
|
|
662
|
+
if (updates.condition !== undefined)
|
|
663
|
+
setValues.condition = updates.condition;
|
|
664
|
+
if (updates.threshold !== undefined)
|
|
665
|
+
setValues.threshold = updates.threshold;
|
|
666
|
+
if (updates.windowMinutes !== undefined)
|
|
667
|
+
setValues.windowMinutes = updates.windowMinutes;
|
|
668
|
+
if (updates.scope !== undefined)
|
|
669
|
+
setValues.scope = updates.scope;
|
|
670
|
+
if (updates.notifyChannels !== undefined)
|
|
671
|
+
setValues.notifyChannels = updates.notifyChannels;
|
|
672
|
+
if (updates.updatedAt !== undefined)
|
|
673
|
+
setValues.updatedAt = updates.updatedAt;
|
|
674
|
+
const whereConditions = [eq(alertRules.id, id)];
|
|
675
|
+
if (tenantId)
|
|
676
|
+
whereConditions.push(eq(alertRules.tenantId, tenantId));
|
|
677
|
+
if (Object.keys(setValues).length === 0) {
|
|
678
|
+
const [existing] = await this.db
|
|
679
|
+
.select({ id: alertRules.id })
|
|
680
|
+
.from(alertRules)
|
|
681
|
+
.where(and(...whereConditions))
|
|
682
|
+
.limit(1);
|
|
683
|
+
if (!existing)
|
|
684
|
+
throw new NotFoundError(`Alert rule not found: ${id}`);
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
const result = await this.db
|
|
688
|
+
.update(alertRules)
|
|
689
|
+
.set(setValues)
|
|
690
|
+
.where(and(...whereConditions));
|
|
691
|
+
if (result.rowCount === 0) {
|
|
692
|
+
throw new NotFoundError(`Alert rule not found: ${id}`);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
async deleteAlertRule(id, tenantId) {
|
|
696
|
+
const whereConditions = [eq(alertRules.id, id)];
|
|
697
|
+
if (tenantId)
|
|
698
|
+
whereConditions.push(eq(alertRules.tenantId, tenantId));
|
|
699
|
+
const result = await this.db.delete(alertRules).where(and(...whereConditions));
|
|
700
|
+
if (result.rowCount === 0) {
|
|
701
|
+
throw new NotFoundError(`Alert rule not found: ${id}`);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
async listAlertRules(tenantId) {
|
|
705
|
+
warnIfNoTenant('listAlertRules', tenantId);
|
|
706
|
+
const conditions = tenantId ? [eq(alertRules.tenantId, tenantId)] : [];
|
|
707
|
+
const rows = await this.db
|
|
708
|
+
.select()
|
|
709
|
+
.from(alertRules)
|
|
710
|
+
.where(conditions.length > 0 ? and(...conditions) : undefined);
|
|
711
|
+
return rows.map(mapAlertRuleRow);
|
|
712
|
+
}
|
|
713
|
+
async getAlertRule(id, tenantId) {
|
|
714
|
+
const conditions = [eq(alertRules.id, id)];
|
|
715
|
+
if (tenantId)
|
|
716
|
+
conditions.push(eq(alertRules.tenantId, tenantId));
|
|
717
|
+
const [row] = await this.db
|
|
718
|
+
.select()
|
|
719
|
+
.from(alertRules)
|
|
720
|
+
.where(and(...conditions))
|
|
721
|
+
.limit(1);
|
|
722
|
+
return row ? mapAlertRuleRow(row) : null;
|
|
723
|
+
}
|
|
724
|
+
async insertAlertHistory(entry) {
|
|
725
|
+
await this.db.insert(alertHistory).values({
|
|
726
|
+
id: entry.id,
|
|
727
|
+
ruleId: entry.ruleId,
|
|
728
|
+
triggeredAt: entry.triggeredAt,
|
|
729
|
+
resolvedAt: entry.resolvedAt ?? null,
|
|
730
|
+
currentValue: entry.currentValue,
|
|
731
|
+
threshold: entry.threshold,
|
|
732
|
+
message: entry.message,
|
|
733
|
+
tenantId: entry.tenantId ?? 'default',
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
async listAlertHistory(opts) {
|
|
737
|
+
const limit = Math.min(opts?.limit ?? 50, 500);
|
|
738
|
+
const offset = opts?.offset ?? 0;
|
|
739
|
+
const conditions = [];
|
|
740
|
+
if (opts?.ruleId)
|
|
741
|
+
conditions.push(eq(alertHistory.ruleId, opts.ruleId));
|
|
742
|
+
if (opts?.tenantId)
|
|
743
|
+
conditions.push(eq(alertHistory.tenantId, opts.tenantId));
|
|
744
|
+
const rows = await this.db
|
|
745
|
+
.select()
|
|
746
|
+
.from(alertHistory)
|
|
747
|
+
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
|
748
|
+
.orderBy(desc(alertHistory.triggeredAt))
|
|
749
|
+
.limit(limit)
|
|
750
|
+
.offset(offset);
|
|
751
|
+
const [totalResult] = await this.db
|
|
752
|
+
.select({ count: drizzleCount() })
|
|
753
|
+
.from(alertHistory)
|
|
754
|
+
.where(conditions.length > 0 ? and(...conditions) : undefined);
|
|
755
|
+
return {
|
|
756
|
+
entries: rows.map((row) => ({
|
|
757
|
+
id: row.id,
|
|
758
|
+
ruleId: row.ruleId,
|
|
759
|
+
triggeredAt: row.triggeredAt,
|
|
760
|
+
resolvedAt: row.resolvedAt ?? undefined,
|
|
761
|
+
currentValue: row.currentValue,
|
|
762
|
+
threshold: row.threshold,
|
|
763
|
+
message: row.message,
|
|
764
|
+
tenantId: row.tenantId,
|
|
765
|
+
})),
|
|
766
|
+
total: totalResult?.count ?? 0,
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
// ─── Analytics & Stats ─────────────────────────────────────
|
|
770
|
+
async getAnalytics(params) {
|
|
771
|
+
warnIfNoTenant('getAnalytics', params.tenantId);
|
|
772
|
+
// PG: use to_char + date_trunc instead of strftime
|
|
773
|
+
const truncUnit = params.granularity === 'hour' ? 'hour' : params.granularity === 'day' ? 'day' : 'week';
|
|
774
|
+
const formatStr = params.granularity === 'week'
|
|
775
|
+
? 'IYYY-IW' // ISO year-week
|
|
776
|
+
: params.granularity === 'day'
|
|
777
|
+
? 'YYYY-MM-DD"T"00:00:00"Z"'
|
|
778
|
+
: 'YYYY-MM-DD"T"HH24:00:00"Z"';
|
|
779
|
+
const bucketResult = await this.db.execute(sql `
|
|
780
|
+
SELECT
|
|
781
|
+
to_char(date_trunc(${truncUnit}, timestamp::timestamp), ${formatStr}) as bucket,
|
|
782
|
+
COUNT(*)::int as "eventCount",
|
|
783
|
+
count(*) FILTER (WHERE event_type = 'tool_call')::int as "toolCallCount",
|
|
784
|
+
count(*) FILTER (WHERE severity IN ('error', 'critical') OR event_type = 'tool_error')::int as "errorCount",
|
|
785
|
+
COUNT(DISTINCT session_id)::int as "uniqueSessions",
|
|
786
|
+
COALESCE(AVG((payload->>'durationMs')::double precision) FILTER (WHERE event_type = 'tool_response'), 0)::double precision as "avgLatencyMs",
|
|
787
|
+
COALESCE(SUM((payload->>'costUsd')::double precision) FILTER (WHERE event_type = 'cost_tracked'), 0)::double precision as "totalCostUsd"
|
|
788
|
+
FROM events
|
|
789
|
+
WHERE timestamp >= ${params.from}
|
|
790
|
+
AND timestamp <= ${params.to}
|
|
791
|
+
${params.agentId ? sql `AND agent_id = ${params.agentId}` : sql ``}
|
|
792
|
+
${params.tenantId ? sql `AND tenant_id = ${params.tenantId}` : sql ``}
|
|
793
|
+
GROUP BY bucket
|
|
794
|
+
ORDER BY bucket ASC
|
|
795
|
+
`);
|
|
796
|
+
const bucketRows = [...bucketResult];
|
|
797
|
+
const totalsResult = await this.db.execute(sql `
|
|
798
|
+
SELECT
|
|
799
|
+
COUNT(*)::int as "eventCount",
|
|
800
|
+
count(*) FILTER (WHERE event_type = 'tool_call')::int as "toolCallCount",
|
|
801
|
+
count(*) FILTER (WHERE severity IN ('error', 'critical') OR event_type = 'tool_error')::int as "errorCount",
|
|
802
|
+
COUNT(DISTINCT session_id)::int as "uniqueSessions",
|
|
803
|
+
COUNT(DISTINCT agent_id)::int as "uniqueAgents",
|
|
804
|
+
COALESCE(AVG((payload->>'durationMs')::double precision) FILTER (WHERE event_type = 'tool_response'), 0)::double precision as "avgLatencyMs",
|
|
805
|
+
COALESCE(SUM((payload->>'costUsd')::double precision) FILTER (WHERE event_type = 'cost_tracked'), 0)::double precision as "totalCostUsd"
|
|
806
|
+
FROM events
|
|
807
|
+
WHERE timestamp >= ${params.from}
|
|
808
|
+
AND timestamp <= ${params.to}
|
|
809
|
+
${params.agentId ? sql `AND agent_id = ${params.agentId}` : sql ``}
|
|
810
|
+
${params.tenantId ? sql `AND tenant_id = ${params.tenantId}` : sql ``}
|
|
811
|
+
`);
|
|
812
|
+
const totalsRow = totalsResult[0];
|
|
813
|
+
return {
|
|
814
|
+
buckets: bucketRows.map((row) => ({
|
|
815
|
+
timestamp: row.bucket,
|
|
816
|
+
eventCount: Number(row.eventCount),
|
|
817
|
+
toolCallCount: Number(row.toolCallCount),
|
|
818
|
+
errorCount: Number(row.errorCount),
|
|
819
|
+
avgLatencyMs: Number(row.avgLatencyMs),
|
|
820
|
+
totalCostUsd: Number(row.totalCostUsd),
|
|
821
|
+
uniqueSessions: Number(row.uniqueSessions),
|
|
822
|
+
})),
|
|
823
|
+
totals: {
|
|
824
|
+
eventCount: Number(totalsRow?.eventCount ?? 0),
|
|
825
|
+
toolCallCount: Number(totalsRow?.toolCallCount ?? 0),
|
|
826
|
+
errorCount: Number(totalsRow?.errorCount ?? 0),
|
|
827
|
+
avgLatencyMs: Number(totalsRow?.avgLatencyMs ?? 0),
|
|
828
|
+
totalCostUsd: Number(totalsRow?.totalCostUsd ?? 0),
|
|
829
|
+
uniqueSessions: Number(totalsRow?.uniqueSessions ?? 0),
|
|
830
|
+
uniqueAgents: Number(totalsRow?.uniqueAgents ?? 0),
|
|
831
|
+
},
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
async getStats(tenantId) {
|
|
835
|
+
const eventConditions = tenantId ? [eq(events.tenantId, tenantId)] : [];
|
|
836
|
+
const sessionConditions = tenantId ? [eq(sessions.tenantId, tenantId)] : [];
|
|
837
|
+
const agentConditions = tenantId ? [eq(agents.tenantId, tenantId)] : [];
|
|
838
|
+
const [eventResult] = await this.db
|
|
839
|
+
.select({ count: drizzleCount() })
|
|
840
|
+
.from(events)
|
|
841
|
+
.where(eventConditions.length > 0 ? and(...eventConditions) : undefined);
|
|
842
|
+
const [sessionResult] = await this.db
|
|
843
|
+
.select({ count: drizzleCount() })
|
|
844
|
+
.from(sessions)
|
|
845
|
+
.where(sessionConditions.length > 0 ? and(...sessionConditions) : undefined);
|
|
846
|
+
const [agentResult] = await this.db
|
|
847
|
+
.select({ count: drizzleCount() })
|
|
848
|
+
.from(agents)
|
|
849
|
+
.where(agentConditions.length > 0 ? and(...agentConditions) : undefined);
|
|
850
|
+
const [oldest] = await this.db
|
|
851
|
+
.select({ timestamp: events.timestamp })
|
|
852
|
+
.from(events)
|
|
853
|
+
.where(eventConditions.length > 0 ? and(...eventConditions) : undefined)
|
|
854
|
+
.orderBy(asc(events.timestamp))
|
|
855
|
+
.limit(1);
|
|
856
|
+
const [newest] = await this.db
|
|
857
|
+
.select({ timestamp: events.timestamp })
|
|
858
|
+
.from(events)
|
|
859
|
+
.where(eventConditions.length > 0 ? and(...eventConditions) : undefined)
|
|
860
|
+
.orderBy(desc(events.timestamp))
|
|
861
|
+
.limit(1);
|
|
862
|
+
// Use pg_database_size for storage estimate
|
|
863
|
+
const sizeQueryResult = await this.db.execute(sql `SELECT pg_database_size(current_database()) as size`);
|
|
864
|
+
const sizeResult = sizeQueryResult[0];
|
|
865
|
+
return {
|
|
866
|
+
totalEvents: eventResult?.count ?? 0,
|
|
867
|
+
totalSessions: sessionResult?.count ?? 0,
|
|
868
|
+
totalAgents: agentResult?.count ?? 0,
|
|
869
|
+
oldestEvent: oldest?.timestamp,
|
|
870
|
+
newestEvent: newest?.timestamp,
|
|
871
|
+
storageSizeBytes: Number(sizeResult?.size ?? 0),
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
// ─── Maintenance ───────────────────────────────────────────
|
|
875
|
+
async applyRetention(olderThan, tenantId) {
|
|
876
|
+
const countConditions = [lte(events.timestamp, olderThan)];
|
|
877
|
+
if (tenantId)
|
|
878
|
+
countConditions.push(eq(events.tenantId, tenantId));
|
|
879
|
+
const [countResult] = await this.db
|
|
880
|
+
.select({ count: drizzleCount() })
|
|
881
|
+
.from(events)
|
|
882
|
+
.where(and(...countConditions));
|
|
883
|
+
const deletedCount = countResult?.count ?? 0;
|
|
884
|
+
if (deletedCount === 0)
|
|
885
|
+
return { deletedCount: 0 };
|
|
886
|
+
await this.db.transaction(async (tx) => {
|
|
887
|
+
if (tenantId) {
|
|
888
|
+
await tx
|
|
889
|
+
.delete(events)
|
|
890
|
+
.where(and(lte(events.timestamp, olderThan), eq(events.tenantId, tenantId)));
|
|
891
|
+
await tx.execute(sql `
|
|
892
|
+
DELETE FROM sessions
|
|
893
|
+
WHERE tenant_id = ${tenantId}
|
|
894
|
+
AND id NOT IN (
|
|
895
|
+
SELECT DISTINCT session_id FROM events WHERE tenant_id = ${tenantId}
|
|
896
|
+
)
|
|
897
|
+
`);
|
|
898
|
+
}
|
|
899
|
+
else {
|
|
900
|
+
await tx.delete(events).where(lte(events.timestamp, olderThan));
|
|
901
|
+
await tx.execute(sql `
|
|
902
|
+
DELETE FROM sessions
|
|
903
|
+
WHERE id NOT IN (SELECT DISTINCT session_id FROM events)
|
|
904
|
+
`);
|
|
905
|
+
}
|
|
906
|
+
});
|
|
907
|
+
return { deletedCount };
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
//# sourceMappingURL=postgres-store.js.map
|