@happyvertical/smrt-core 0.30.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/AGENTS.md +124 -0
- package/CLAUDE.md +1 -0
- package/LICENSE +7 -0
- package/README.md +265 -0
- package/bin/smrt-prebuild.js +26 -0
- package/dist/__tests__/fixtures/advisor-test-classes.d.ts +28 -0
- package/dist/__tests__/fixtures/advisor-test-classes.d.ts.map +1 -0
- package/dist/__tests__/fixtures/collection-coverage-fixtures.d.ts +12 -0
- package/dist/__tests__/fixtures/collection-coverage-fixtures.d.ts.map +1 -0
- package/dist/__tests__/fixtures/inheritance-resolver-fixtures.d.ts +28 -0
- package/dist/__tests__/fixtures/inheritance-resolver-fixtures.d.ts.map +1 -0
- package/dist/__tests__/fixtures/inheritance-test-classes.d.ts +43 -0
- package/dist/__tests__/fixtures/inheritance-test-classes.d.ts.map +1 -0
- package/dist/__tests__/fixtures/mcp-integration-test-classes.d.ts +18 -0
- package/dist/__tests__/fixtures/mcp-integration-test-classes.d.ts.map +1 -0
- package/dist/__tests__/fixtures/object-ai-memory-fixtures.d.ts +15 -0
- package/dist/__tests__/fixtures/object-ai-memory-fixtures.d.ts.map +1 -0
- package/dist/__tests__/fixtures/object-spec-test-classes.d.ts +13 -0
- package/dist/__tests__/fixtures/object-spec-test-classes.d.ts.map +1 -0
- package/dist/__tests__/fixtures/registry-test-classes.d.ts +23 -0
- package/dist/__tests__/fixtures/registry-test-classes.d.ts.map +1 -0
- package/dist/adapters/ai-usage.d.ts +23 -0
- package/dist/adapters/ai-usage.d.ts.map +1 -0
- package/dist/adapters/ai-usage.js +105 -0
- package/dist/adapters/ai-usage.js.map +1 -0
- package/dist/adapters/cost-rates.d.ts +20 -0
- package/dist/adapters/cost-rates.d.ts.map +1 -0
- package/dist/adapters/cost-rates.js +40 -0
- package/dist/adapters/cost-rates.js.map +1 -0
- package/dist/adapters/index.d.ts +19 -0
- package/dist/adapters/index.d.ts.map +1 -0
- package/dist/adapters/metrics.d.ts +111 -0
- package/dist/adapters/metrics.d.ts.map +1 -0
- package/dist/adapters/metrics.js +169 -0
- package/dist/adapters/metrics.js.map +1 -0
- package/dist/adapters/pubsub.d.ts +124 -0
- package/dist/adapters/pubsub.d.ts.map +1 -0
- package/dist/adapters/pubsub.js +121 -0
- package/dist/adapters/pubsub.js.map +1 -0
- package/dist/browser.d.ts +32 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +68 -0
- package/dist/browser.js.map +1 -0
- package/dist/child-accessors.d.ts +27 -0
- package/dist/child-accessors.d.ts.map +1 -0
- package/dist/child-accessors.js +35 -0
- package/dist/child-accessors.js.map +1 -0
- package/dist/class.d.ts +313 -0
- package/dist/class.d.ts.map +1 -0
- package/dist/class.js +896 -0
- package/dist/class.js.map +1 -0
- package/dist/collection-cache.d.ts +110 -0
- package/dist/collection-cache.d.ts.map +1 -0
- package/dist/collection-cache.js +187 -0
- package/dist/collection-cache.js.map +1 -0
- package/dist/collection.d.ts +894 -0
- package/dist/collection.d.ts.map +1 -0
- package/dist/collection.js +1987 -0
- package/dist/collection.js.map +1 -0
- package/dist/config/global-config.d.ts +3 -0
- package/dist/config/global-config.d.ts.map +1 -0
- package/dist/config/global-config.js +19 -0
- package/dist/config/global-config.js.map +1 -0
- package/dist/config.d.ts +145 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +57 -0
- package/dist/config.js.map +1 -0
- package/dist/consumer-plugin/index.d.ts +22 -0
- package/dist/consumer-plugin/index.d.ts.map +1 -0
- package/dist/consumer-plugin/index.js +452 -0
- package/dist/consumer-plugin/index.js.map +1 -0
- package/dist/consumer-plugin.d.ts +8 -0
- package/dist/consumer-plugin.d.ts.map +1 -0
- package/dist/consumer-plugin.js +5 -0
- package/dist/consumer-plugin.js.map +1 -0
- package/dist/database.d.ts +95 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +32 -0
- package/dist/database.js.map +1 -0
- package/dist/decorators/compatibility.d.ts +14 -0
- package/dist/decorators/compatibility.d.ts.map +1 -0
- package/dist/decorators/compatibility.js +111 -0
- package/dist/decorators/compatibility.js.map +1 -0
- package/dist/decorators/index.d.ts +381 -0
- package/dist/decorators/index.d.ts.map +1 -0
- package/dist/decorators/index.js +104 -0
- package/dist/decorators/index.js.map +1 -0
- package/dist/dispatch/bus.d.ts +306 -0
- package/dist/dispatch/bus.d.ts.map +1 -0
- package/dist/dispatch/bus.js +583 -0
- package/dist/dispatch/bus.js.map +1 -0
- package/dist/dispatch/collections/DispatchSubscriptions.d.ts +79 -0
- package/dist/dispatch/collections/DispatchSubscriptions.d.ts.map +1 -0
- package/dist/dispatch/collections/DispatchSubscriptions.js +243 -0
- package/dist/dispatch/collections/DispatchSubscriptions.js.map +1 -0
- package/dist/dispatch/collections/Dispatches.d.ts +98 -0
- package/dist/dispatch/collections/Dispatches.d.ts.map +1 -0
- package/dist/dispatch/collections/Dispatches.js +358 -0
- package/dist/dispatch/collections/Dispatches.js.map +1 -0
- package/dist/dispatch/index.d.ts +47 -0
- package/dist/dispatch/index.d.ts.map +1 -0
- package/dist/dispatch/models/Dispatch.d.ts +101 -0
- package/dist/dispatch/models/Dispatch.d.ts.map +1 -0
- package/dist/dispatch/models/Dispatch.js +162 -0
- package/dist/dispatch/models/Dispatch.js.map +1 -0
- package/dist/dispatch/models/DispatchSubscription.d.ts +83 -0
- package/dist/dispatch/models/DispatchSubscription.d.ts.map +1 -0
- package/dist/dispatch/models/DispatchSubscription.js +112 -0
- package/dist/dispatch/models/DispatchSubscription.js.map +1 -0
- package/dist/dispatch/tenant-resolver.d.ts +98 -0
- package/dist/dispatch/tenant-resolver.d.ts.map +1 -0
- package/dist/dispatch/tenant-resolver.js +32 -0
- package/dist/dispatch/tenant-resolver.js.map +1 -0
- package/dist/dispatch/types.d.ts +149 -0
- package/dist/dispatch/types.d.ts.map +1 -0
- package/dist/embeddings/hash.d.ts +33 -0
- package/dist/embeddings/hash.d.ts.map +1 -0
- package/dist/embeddings/hash.js +37 -0
- package/dist/embeddings/hash.js.map +1 -0
- package/dist/embeddings/index.d.ts +36 -0
- package/dist/embeddings/index.d.ts.map +1 -0
- package/dist/embeddings/provider.d.ts +75 -0
- package/dist/embeddings/provider.d.ts.map +1 -0
- package/dist/embeddings/provider.js +170 -0
- package/dist/embeddings/provider.js.map +1 -0
- package/dist/embeddings/similarity.d.ts +47 -0
- package/dist/embeddings/similarity.d.ts.map +1 -0
- package/dist/embeddings/similarity.js +64 -0
- package/dist/embeddings/similarity.js.map +1 -0
- package/dist/embeddings/storage.d.ts +125 -0
- package/dist/embeddings/storage.d.ts.map +1 -0
- package/dist/embeddings/storage.js +283 -0
- package/dist/embeddings/storage.js.map +1 -0
- package/dist/embeddings/types.d.ts +250 -0
- package/dist/embeddings/types.d.ts.map +1 -0
- package/dist/errors.d.ts +363 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +669 -0
- package/dist/errors.js.map +1 -0
- package/dist/generators/cli.d.ts +162 -0
- package/dist/generators/cli.d.ts.map +1 -0
- package/dist/generators/cli.js +462 -0
- package/dist/generators/cli.js.map +1 -0
- package/dist/generators/index.d.ts +13 -0
- package/dist/generators/index.d.ts.map +1 -0
- package/dist/generators/mcp-runtime-template.d.ts +60 -0
- package/dist/generators/mcp-runtime-template.d.ts.map +1 -0
- package/dist/generators/mcp-runtime-template.js +509 -0
- package/dist/generators/mcp-runtime-template.js.map +1 -0
- package/dist/generators/mcp.d.ts +231 -0
- package/dist/generators/mcp.d.ts.map +1 -0
- package/dist/generators/mcp.js +1220 -0
- package/dist/generators/mcp.js.map +1 -0
- package/dist/generators/rest.d.ts +171 -0
- package/dist/generators/rest.d.ts.map +1 -0
- package/dist/generators/rest.js +591 -0
- package/dist/generators/rest.js.map +1 -0
- package/dist/generators/swagger.d.ts +21 -0
- package/dist/generators/swagger.d.ts.map +1 -0
- package/dist/generators/swagger.js +307 -0
- package/dist/generators/swagger.js.map +1 -0
- package/dist/generators/tenant-gate.d.ts +74 -0
- package/dist/generators/tenant-gate.d.ts.map +1 -0
- package/dist/generators/tenant-gate.js +15 -0
- package/dist/generators/tenant-gate.js.map +1 -0
- package/dist/generators.d.ts +8 -0
- package/dist/generators.d.ts.map +1 -0
- package/dist/generators.js +19 -0
- package/dist/generators.js.map +1 -0
- package/dist/hierarchical.d.ts +103 -0
- package/dist/hierarchical.d.ts.map +1 -0
- package/dist/hierarchical.js +184 -0
- package/dist/hierarchical.js.map +1 -0
- package/dist/index.d.ts +57 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +202 -0
- package/dist/index.js.map +1 -0
- package/dist/interceptors.d.ts +251 -0
- package/dist/interceptors.d.ts.map +1 -0
- package/dist/interceptors.js +259 -0
- package/dist/interceptors.js.map +1 -0
- package/dist/junction.d.ts +99 -0
- package/dist/junction.d.ts.map +1 -0
- package/dist/junction.js +136 -0
- package/dist/junction.js.map +1 -0
- package/dist/knowledge.d.ts +11 -0
- package/dist/knowledge.d.ts.map +1 -0
- package/dist/knowledge.js +310 -0
- package/dist/knowledge.js.map +1 -0
- package/dist/lazy-config.d.ts +160 -0
- package/dist/lazy-config.d.ts.map +1 -0
- package/dist/lazy-config.js +146 -0
- package/dist/lazy-config.js.map +1 -0
- package/dist/manifest/discover-base-classes.d.ts +78 -0
- package/dist/manifest/discover-base-classes.d.ts.map +1 -0
- package/dist/manifest/discover-base-classes.js +85 -0
- package/dist/manifest/discover-base-classes.js.map +1 -0
- package/dist/manifest/discover-smrt-packages.d.ts +48 -0
- package/dist/manifest/discover-smrt-packages.d.ts.map +1 -0
- package/dist/manifest/discover-smrt-packages.js +361 -0
- package/dist/manifest/discover-smrt-packages.js.map +1 -0
- package/dist/manifest/generator.d.ts +93 -0
- package/dist/manifest/generator.d.ts.map +1 -0
- package/dist/manifest/generator.js +380 -0
- package/dist/manifest/generator.js.map +1 -0
- package/dist/manifest/index.d.ts +16 -0
- package/dist/manifest/index.d.ts.map +1 -0
- package/dist/manifest/index.js +51 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/manifest/manager.d.ts +51 -0
- package/dist/manifest/manager.d.ts.map +1 -0
- package/dist/manifest/manager.js +89 -0
- package/dist/manifest/manager.js.map +1 -0
- package/dist/manifest/manifest-loader.d.ts +187 -0
- package/dist/manifest/manifest-loader.d.ts.map +1 -0
- package/dist/manifest/manifest-loader.js +847 -0
- package/dist/manifest/manifest-loader.js.map +1 -0
- package/dist/manifest/sources/composite.d.ts +22 -0
- package/dist/manifest/sources/composite.d.ts.map +1 -0
- package/dist/manifest/sources/composite.js +60 -0
- package/dist/manifest/sources/composite.js.map +1 -0
- package/dist/manifest/sources/embedded.d.ts +7 -0
- package/dist/manifest/sources/embedded.d.ts.map +1 -0
- package/dist/manifest/sources/embedded.js +30 -0
- package/dist/manifest/sources/embedded.js.map +1 -0
- package/dist/manifest/sources/explicit-paths.d.ts +17 -0
- package/dist/manifest/sources/explicit-paths.d.ts.map +1 -0
- package/dist/manifest/sources/explicit-paths.js +35 -0
- package/dist/manifest/sources/explicit-paths.js.map +1 -0
- package/dist/manifest/sources/fallback.d.ts +25 -0
- package/dist/manifest/sources/fallback.d.ts.map +1 -0
- package/dist/manifest/sources/fallback.js +63 -0
- package/dist/manifest/sources/fallback.js.map +1 -0
- package/dist/manifest/sources/index.d.ts +17 -0
- package/dist/manifest/sources/index.d.ts.map +1 -0
- package/dist/manifest/sources/local-test.d.ts +7 -0
- package/dist/manifest/sources/local-test.d.ts.map +1 -0
- package/dist/manifest/sources/local-test.js +21 -0
- package/dist/manifest/sources/local-test.js.map +1 -0
- package/dist/manifest/sources/static.d.ts +7 -0
- package/dist/manifest/sources/static.d.ts.map +1 -0
- package/dist/manifest/sources/static.js +19 -0
- package/dist/manifest/sources/static.js.map +1 -0
- package/dist/manifest/sources/test.d.ts +7 -0
- package/dist/manifest/sources/test.d.ts.map +1 -0
- package/dist/manifest/sources/test.js +21 -0
- package/dist/manifest/sources/test.js.map +1 -0
- package/dist/manifest/sources/types.d.ts +79 -0
- package/dist/manifest/sources/types.d.ts.map +1 -0
- package/dist/manifest/sources/types.js +61 -0
- package/dist/manifest/sources/types.js.map +1 -0
- package/dist/manifest/static-manifest.d.ts +4 -0
- package/dist/manifest/static-manifest.d.ts.map +1 -0
- package/dist/manifest/static-manifest.js +1535 -0
- package/dist/manifest/static-manifest.js.map +1 -0
- package/dist/manifest/store.d.ts +111 -0
- package/dist/manifest/store.d.ts.map +1 -0
- package/dist/manifest/store.js +431 -0
- package/dist/manifest/store.js.map +1 -0
- package/dist/manifest/test-manifest-loader.d.ts +3 -0
- package/dist/manifest/test-manifest-loader.d.ts.map +1 -0
- package/dist/manifest/test-manifest-stub.d.ts +4 -0
- package/dist/manifest/test-manifest-stub.d.ts.map +1 -0
- package/dist/manifest/test-manifest-stub.js +80013 -0
- package/dist/manifest/test-manifest-stub.js.map +1 -0
- package/dist/manifest.d.ts +8 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/manifest.js +20 -0
- package/dist/manifest.js.map +1 -0
- package/dist/manifest.json +1489 -0
- package/dist/mcp-advisor/index.d.ts +499 -0
- package/dist/mcp-advisor/index.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/add-ai-methods.d.ts +6 -0
- package/dist/mcp-advisor/tools/add-ai-methods.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/configure-decorators.d.ts +6 -0
- package/dist/mcp-advisor/tools/configure-decorators.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/generate-collection.d.ts +6 -0
- package/dist/mcp-advisor/tools/generate-collection.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/generate-field-definitions.d.ts +6 -0
- package/dist/mcp-advisor/tools/generate-field-definitions.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/generate-smrt-class.d.ts +6 -0
- package/dist/mcp-advisor/tools/generate-smrt-class.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/get-object-config.d.ts +6 -0
- package/dist/mcp-advisor/tools/get-object-config.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/get-object-schema.d.ts +10 -0
- package/dist/mcp-advisor/tools/get-object-schema.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/list-registered-objects.d.ts +9 -0
- package/dist/mcp-advisor/tools/list-registered-objects.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/preview-api-endpoints.d.ts +9 -0
- package/dist/mcp-advisor/tools/preview-api-endpoints.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/preview-mcp-tools.d.ts +9 -0
- package/dist/mcp-advisor/tools/preview-mcp-tools.d.ts.map +1 -0
- package/dist/mcp-advisor/tools/validate-smrt-object.d.ts +6 -0
- package/dist/mcp-advisor/tools/validate-smrt-object.d.ts.map +1 -0
- package/dist/mcp-advisor/types.d.ts +209 -0
- package/dist/mcp-advisor/types.d.ts.map +1 -0
- package/dist/migrations/backfill-tracker.d.ts +84 -0
- package/dist/migrations/backfill-tracker.d.ts.map +1 -0
- package/dist/migrations/backfill-tracker.js +118 -0
- package/dist/migrations/backfill-tracker.js.map +1 -0
- package/dist/migrations/checksum.d.ts +43 -0
- package/dist/migrations/checksum.d.ts.map +1 -0
- package/dist/migrations/checksum.js +32 -0
- package/dist/migrations/checksum.js.map +1 -0
- package/dist/migrations/differ.d.ts +186 -0
- package/dist/migrations/differ.d.ts.map +1 -0
- package/dist/migrations/differ.js +601 -0
- package/dist/migrations/differ.js.map +1 -0
- package/dist/migrations/generator.d.ts +133 -0
- package/dist/migrations/generator.d.ts.map +1 -0
- package/dist/migrations/generator.js +328 -0
- package/dist/migrations/generator.js.map +1 -0
- package/dist/migrations/index.d.ts +20 -0
- package/dist/migrations/index.d.ts.map +1 -0
- package/dist/migrations/orchestrate.d.ts +148 -0
- package/dist/migrations/orchestrate.d.ts.map +1 -0
- package/dist/migrations/orchestrate.js +118 -0
- package/dist/migrations/orchestrate.js.map +1 -0
- package/dist/migrations/tracker.d.ts +134 -0
- package/dist/migrations/tracker.d.ts.map +1 -0
- package/dist/migrations/tracker.js +624 -0
- package/dist/migrations/tracker.js.map +1 -0
- package/dist/migrations/types.d.ts +221 -0
- package/dist/migrations/types.d.ts.map +1 -0
- package/dist/migrations.d.ts +7 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +26 -0
- package/dist/migrations.js.map +1 -0
- package/dist/node_modules/.pnpm/balanced-match@4.0.4/node_modules/balanced-match/dist/esm/index.js +56 -0
- package/dist/node_modules/.pnpm/balanced-match@4.0.4/node_modules/balanced-match/dist/esm/index.js.map +1 -0
- package/dist/node_modules/.pnpm/brace-expansion@5.0.5/node_modules/brace-expansion/dist/esm/index.js +163 -0
- package/dist/node_modules/.pnpm/brace-expansion@5.0.5/node_modules/brace-expansion/dist/esm/index.js.map +1 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/assert-valid-pattern.js +13 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map +1 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/ast.js +654 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/ast.js.map +1 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/brace-expressions.js +111 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/brace-expressions.js.map +1 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/escape.js +10 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/escape.js.map +1 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/index.js +824 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/index.js.map +1 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/unescape.js +10 -0
- package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/unescape.js.map +1 -0
- package/dist/object.d.ts +1202 -0
- package/dist/object.d.ts.map +1 -0
- package/dist/object.js +2731 -0
- package/dist/object.js.map +1 -0
- package/dist/polymorphic-association.d.ts +69 -0
- package/dist/polymorphic-association.d.ts.map +1 -0
- package/dist/polymorphic-association.js +96 -0
- package/dist/polymorphic-association.js.map +1 -0
- package/dist/prebuild/cli.d.ts +7 -0
- package/dist/prebuild/cli.d.ts.map +1 -0
- package/dist/prebuild/cli.js +29 -0
- package/dist/prebuild/cli.js.map +1 -0
- package/dist/prebuild/index.d.ts +22 -0
- package/dist/prebuild/index.d.ts.map +1 -0
- package/dist/prebuild/index.js +239 -0
- package/dist/prebuild/index.js.map +1 -0
- package/dist/prebuild.d.ts +8 -0
- package/dist/prebuild.d.ts.map +1 -0
- package/dist/prebuild.js +6 -0
- package/dist/prebuild.js.map +1 -0
- package/dist/registry/cache-config.d.ts +13 -0
- package/dist/registry/cache-config.d.ts.map +1 -0
- package/dist/registry/cache-config.js +17 -0
- package/dist/registry/cache-config.js.map +1 -0
- package/dist/registry/class-registration.d.ts +31 -0
- package/dist/registry/class-registration.d.ts.map +1 -0
- package/dist/registry/class-registration.js +1074 -0
- package/dist/registry/class-registration.js.map +1 -0
- package/dist/registry/collection-resolution.d.ts +45 -0
- package/dist/registry/collection-resolution.d.ts.map +1 -0
- package/dist/registry/collection-resolution.js +121 -0
- package/dist/registry/collection-resolution.js.map +1 -0
- package/dist/registry/collision-policy.d.ts +179 -0
- package/dist/registry/collision-policy.d.ts.map +1 -0
- package/dist/registry/collision-policy.js +153 -0
- package/dist/registry/collision-policy.js.map +1 -0
- package/dist/registry/diagnostics.d.ts +58 -0
- package/dist/registry/diagnostics.d.ts.map +1 -0
- package/dist/registry/diagnostics.js +54 -0
- package/dist/registry/diagnostics.js.map +1 -0
- package/dist/registry/embedding-manager.d.ts +23 -0
- package/dist/registry/embedding-manager.d.ts.map +1 -0
- package/dist/registry/embedding-manager.js +62 -0
- package/dist/registry/embedding-manager.js.map +1 -0
- package/dist/registry/index.d.ts +13 -0
- package/dist/registry/index.d.ts.map +1 -0
- package/dist/registry/inheritance-resolver.d.ts +13 -0
- package/dist/registry/inheritance-resolver.d.ts.map +1 -0
- package/dist/registry/inheritance-resolver.js +244 -0
- package/dist/registry/inheritance-resolver.js.map +1 -0
- package/dist/registry/manifest-field-merge.d.ts +4 -0
- package/dist/registry/manifest-field-merge.d.ts.map +1 -0
- package/dist/registry/manifest-field-merge.js +82 -0
- package/dist/registry/manifest-field-merge.js.map +1 -0
- package/dist/registry/name-resolver.d.ts +102 -0
- package/dist/registry/name-resolver.d.ts.map +1 -0
- package/dist/registry/name-resolver.js +241 -0
- package/dist/registry/name-resolver.js.map +1 -0
- package/dist/registry/relationship-graph.d.ts +16 -0
- package/dist/registry/relationship-graph.d.ts.map +1 -0
- package/dist/registry/relationship-graph.js +79 -0
- package/dist/registry/relationship-graph.js.map +1 -0
- package/dist/registry/schema-builder.d.ts +113 -0
- package/dist/registry/schema-builder.d.ts.map +1 -0
- package/dist/registry/schema-builder.js +474 -0
- package/dist/registry/schema-builder.js.map +1 -0
- package/dist/registry/shared-state.d.ts +62 -0
- package/dist/registry/shared-state.d.ts.map +1 -0
- package/dist/registry/shared-state.js +135 -0
- package/dist/registry/shared-state.js.map +1 -0
- package/dist/registry/types.d.ts +667 -0
- package/dist/registry/types.d.ts.map +1 -0
- package/dist/registry/validator.d.ts +13 -0
- package/dist/registry/validator.d.ts.map +1 -0
- package/dist/registry/validator.js +138 -0
- package/dist/registry/validator.js.map +1 -0
- package/dist/registry.d.ts +1358 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +2301 -0
- package/dist/registry.js.map +1 -0
- package/dist/runtime/client.d.ts +34 -0
- package/dist/runtime/client.d.ts.map +1 -0
- package/dist/runtime/client.js +104 -0
- package/dist/runtime/client.js.map +1 -0
- package/dist/runtime/index.d.ts +10 -0
- package/dist/runtime/index.d.ts.map +1 -0
- package/dist/runtime/mcp.d.ts +47 -0
- package/dist/runtime/mcp.d.ts.map +1 -0
- package/dist/runtime/mcp.js +72 -0
- package/dist/runtime/mcp.js.map +1 -0
- package/dist/runtime/server.d.ts +92 -0
- package/dist/runtime/server.d.ts.map +1 -0
- package/dist/runtime/server.js +390 -0
- package/dist/runtime/server.js.map +1 -0
- package/dist/runtime/types.d.ts +58 -0
- package/dist/runtime/types.d.ts.map +1 -0
- package/dist/runtime.d.ts +8 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +10 -0
- package/dist/runtime.js.map +1 -0
- package/dist/scanner/import-scanner.d.ts +7 -0
- package/dist/scanner/import-scanner.d.ts.map +1 -0
- package/dist/scanner/index.d.ts +12 -0
- package/dist/scanner/index.d.ts.map +1 -0
- package/dist/scanner/manifest-generator.d.ts +304 -0
- package/dist/scanner/manifest-generator.d.ts.map +1 -0
- package/dist/scanner/manifest-generator.js +1707 -0
- package/dist/scanner/manifest-generator.js.map +1 -0
- package/dist/scanner/test-file-patterns.d.ts +18 -0
- package/dist/scanner/test-file-patterns.d.ts.map +1 -0
- package/dist/scanner/test-file-patterns.js +16 -0
- package/dist/scanner/test-file-patterns.js.map +1 -0
- package/dist/scanner/types.d.ts +313 -0
- package/dist/scanner/types.d.ts.map +1 -0
- package/dist/scanner/types.js +2 -0
- package/dist/scanner/types.js.map +1 -0
- package/dist/scanner.d.ts +6 -0
- package/dist/scanner.d.ts.map +1 -0
- package/dist/scanner.js +6 -0
- package/dist/scanner.js.map +1 -0
- package/dist/schema/code-generator.d.ts +53 -0
- package/dist/schema/code-generator.d.ts.map +1 -0
- package/dist/schema/ddl/base-strategy.d.ts +80 -0
- package/dist/schema/ddl/base-strategy.d.ts.map +1 -0
- package/dist/schema/ddl/base-strategy.js +240 -0
- package/dist/schema/ddl/base-strategy.js.map +1 -0
- package/dist/schema/ddl/duckdb-strategy.d.ts +33 -0
- package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -0
- package/dist/schema/ddl/duckdb-strategy.js +74 -0
- package/dist/schema/ddl/duckdb-strategy.js.map +1 -0
- package/dist/schema/ddl/index.d.ts +53 -0
- package/dist/schema/ddl/index.d.ts.map +1 -0
- package/dist/schema/ddl/index.js +80 -0
- package/dist/schema/ddl/index.js.map +1 -0
- package/dist/schema/ddl/json-duckdb-strategy.d.ts +8 -0
- package/dist/schema/ddl/json-duckdb-strategy.d.ts.map +1 -0
- package/dist/schema/ddl/json-duckdb-strategy.js +14 -0
- package/dist/schema/ddl/json-duckdb-strategy.js.map +1 -0
- package/dist/schema/ddl/postgres-strategy.d.ts +29 -0
- package/dist/schema/ddl/postgres-strategy.d.ts.map +1 -0
- package/dist/schema/ddl/postgres-strategy.js +102 -0
- package/dist/schema/ddl/postgres-strategy.js.map +1 -0
- package/dist/schema/ddl/sqlite-strategy.d.ts +38 -0
- package/dist/schema/ddl/sqlite-strategy.d.ts.map +1 -0
- package/dist/schema/ddl/sqlite-strategy.js +74 -0
- package/dist/schema/ddl/sqlite-strategy.js.map +1 -0
- package/dist/schema/ddl/types.d.ts +114 -0
- package/dist/schema/ddl/types.d.ts.map +1 -0
- package/dist/schema/generator.d.ts +176 -0
- package/dist/schema/generator.d.ts.map +1 -0
- package/dist/schema/generator.js +1076 -0
- package/dist/schema/generator.js.map +1 -0
- package/dist/schema/index-utils.d.ts +19 -0
- package/dist/schema/index-utils.d.ts.map +1 -0
- package/dist/schema/index-utils.js +32 -0
- package/dist/schema/index-utils.js.map +1 -0
- package/dist/schema/index.d.ts +13 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/override-system.d.ts +43 -0
- package/dist/schema/override-system.d.ts.map +1 -0
- package/dist/schema/schema-aggregator.d.ts +112 -0
- package/dist/schema/schema-aggregator.d.ts.map +1 -0
- package/dist/schema/schema-manager.d.ts +95 -0
- package/dist/schema/schema-manager.d.ts.map +1 -0
- package/dist/schema/schema-manager.js +283 -0
- package/dist/schema/schema-manager.js.map +1 -0
- package/dist/schema/sql-identifiers.d.ts +107 -0
- package/dist/schema/sql-identifiers.d.ts.map +1 -0
- package/dist/schema/sql-identifiers.js +190 -0
- package/dist/schema/sql-identifiers.js.map +1 -0
- package/dist/schema/table-verifier.d.ts +10 -0
- package/dist/schema/table-verifier.d.ts.map +1 -0
- package/dist/schema/table-verifier.js +37 -0
- package/dist/schema/table-verifier.js.map +1 -0
- package/dist/schema/types.d.ts +241 -0
- package/dist/schema/types.d.ts.map +1 -0
- package/dist/schema/utils.d.ts +32 -0
- package/dist/schema/utils.d.ts.map +1 -0
- package/dist/schema/utils.js +134 -0
- package/dist/schema/utils.js.map +1 -0
- package/dist/scripts/create-wrappers.js +89 -0
- package/dist/scripts/generate-manifest.js +155 -0
- package/dist/scripts/generate-test-manifest.js +77 -0
- package/dist/scripts/migrate-datetime-to-timestamp.ts +310 -0
- package/dist/scripts/prepack.js +49 -0
- package/dist/signals/bus.d.ts +64 -0
- package/dist/signals/bus.d.ts.map +1 -0
- package/dist/signals/bus.js +102 -0
- package/dist/signals/bus.js.map +1 -0
- package/dist/signals/index.d.ts +11 -0
- package/dist/signals/index.d.ts.map +1 -0
- package/dist/signals/sanitizer.d.ts +54 -0
- package/dist/signals/sanitizer.d.ts.map +1 -0
- package/dist/signals/sanitizer.js +111 -0
- package/dist/signals/sanitizer.js.map +1 -0
- package/dist/smrt-knowledge.json +335 -0
- package/dist/system/compatibility.d.ts +8 -0
- package/dist/system/compatibility.d.ts.map +1 -0
- package/dist/system/compatibility.js +409 -0
- package/dist/system/compatibility.js.map +1 -0
- package/dist/system/index.d.ts +9 -0
- package/dist/system/index.d.ts.map +1 -0
- package/dist/system/schema.d.ts +69 -0
- package/dist/system/schema.d.ts.map +1 -0
- package/dist/system/schema.js +271 -0
- package/dist/system/schema.js.map +1 -0
- package/dist/system/types.d.ts +135 -0
- package/dist/system/types.d.ts.map +1 -0
- package/dist/system-fields.d.ts +44 -0
- package/dist/system-fields.d.ts.map +1 -0
- package/dist/system-fields.js +55 -0
- package/dist/system-fields.js.map +1 -0
- package/dist/table-cache.d.ts +28 -0
- package/dist/table-cache.d.ts.map +1 -0
- package/dist/table-cache.js +21 -0
- package/dist/table-cache.js.map +1 -0
- package/dist/test-utils.d.ts +140 -0
- package/dist/test-utils.d.ts.map +1 -0
- package/dist/testing/database.d.ts +73 -0
- package/dist/testing/database.d.ts.map +1 -0
- package/dist/testing/database.js +204 -0
- package/dist/testing/database.js.map +1 -0
- package/dist/testing/index.d.ts +21 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing.d.ts +6 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +5 -0
- package/dist/testing.js.map +1 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/tool-executor.d.ts +101 -0
- package/dist/tools/tool-executor.d.ts.map +1 -0
- package/dist/tools/tool-executor.js +142 -0
- package/dist/tools/tool-executor.js.map +1 -0
- package/dist/tools/tool-generator.d.ts +54 -0
- package/dist/tools/tool-generator.d.ts.map +1 -0
- package/dist/tools/tool-generator.js +121 -0
- package/dist/tools/tool-generator.js.map +1 -0
- package/dist/utils/chunk.d.ts +32 -0
- package/dist/utils/chunk.d.ts.map +1 -0
- package/dist/utils/chunk.js +14 -0
- package/dist/utils/chunk.js.map +1 -0
- package/dist/utils/import-workspace-module.d.ts +8 -0
- package/dist/utils/import-workspace-module.d.ts.map +1 -0
- package/dist/utils/import-workspace-module.js +81 -0
- package/dist/utils/import-workspace-module.js.map +1 -0
- package/dist/utils/json.d.ts +102 -0
- package/dist/utils/json.d.ts.map +1 -0
- package/dist/utils/json.js +43 -0
- package/dist/utils/json.js.map +1 -0
- package/dist/utils/lru-cache.d.ts +69 -0
- package/dist/utils/lru-cache.d.ts.map +1 -0
- package/dist/utils/lru-cache.js +100 -0
- package/dist/utils/lru-cache.js.map +1 -0
- package/dist/utils/naming.d.ts +16 -0
- package/dist/utils/naming.d.ts.map +1 -0
- package/dist/utils/naming.js +23 -0
- package/dist/utils/naming.js.map +1 -0
- package/dist/utils/qualified-names.d.ts +122 -0
- package/dist/utils/qualified-names.d.ts.map +1 -0
- package/dist/utils/qualified-names.js +82 -0
- package/dist/utils/qualified-names.js.map +1 -0
- package/dist/utils/scanner-module.d.ts +37 -0
- package/dist/utils/scanner-module.d.ts.map +1 -0
- package/dist/utils.d.ts +177 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +185 -0
- package/dist/utils.js.map +1 -0
- package/dist/vite-plugin/import-build-aware.d.ts +68 -0
- package/dist/vite-plugin/import-build-aware.d.ts.map +1 -0
- package/dist/vite-plugin/import-build-aware.js +72 -0
- package/dist/vite-plugin/import-build-aware.js.map +1 -0
- package/dist/vite-plugin/index.d.ts +59 -0
- package/dist/vite-plugin/index.d.ts.map +1 -0
- package/dist/vite-plugin/index.js +1400 -0
- package/dist/vite-plugin/index.js.map +1 -0
- package/dist/vite-plugin/sveltekit-generator.d.ts +66 -0
- package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -0
- package/dist/vite-plugin/sveltekit-generator.js +1375 -0
- package/dist/vite-plugin/sveltekit-generator.js.map +1 -0
- package/dist/vite-plugin/templates/default-ui.ts +432 -0
- package/dist/vite-plugin/templates/default.html +206 -0
- package/dist/vite-plugin.d.ts +8 -0
- package/dist/vite-plugin.d.ts.map +1 -0
- package/dist/vite-plugin.js +11 -0
- package/dist/vite-plugin.js.map +1 -0
- package/package.json +208 -0
package/dist/class.js
ADDED
|
@@ -0,0 +1,896 @@
|
|
|
1
|
+
import { getAI } from "@happyvertical/ai";
|
|
2
|
+
import { FilesystemAdapter } from "@happyvertical/files";
|
|
3
|
+
import { createLogger } from "@happyvertical/logger";
|
|
4
|
+
import { getDatabase } from "@happyvertical/sql";
|
|
5
|
+
import { AiUsageCollector, AiUsagePersistenceHandler } from "./adapters/ai-usage.js";
|
|
6
|
+
import { estimateAiUsageCost } from "./adapters/cost-rates.js";
|
|
7
|
+
import { config } from "./config.js";
|
|
8
|
+
import { detectEngine } from "./schema/ddl/index.js";
|
|
9
|
+
import { SignalBus } from "./signals/bus.js";
|
|
10
|
+
import { tableExists, ensureLegacySystemTableCompatibility } from "./system/compatibility.js";
|
|
11
|
+
import { SMRT_SCHEMA_VERSION, ALL_SYSTEM_TABLES } from "./system/schema.js";
|
|
12
|
+
const SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL = "SELECT pg_advisory_xact_lock(hashtext('smrt'), hashtext('system-tables'))";
|
|
13
|
+
const logger = createLogger({ level: "info" });
|
|
14
|
+
function firstString(...candidates) {
|
|
15
|
+
return candidates.find((candidate) => {
|
|
16
|
+
return typeof candidate === "string";
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
function firstNumber(...candidates) {
|
|
20
|
+
return candidates.find((candidate) => {
|
|
21
|
+
return typeof candidate === "number";
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function getDatabaseUrl(db) {
|
|
25
|
+
const dbWithConfig = db;
|
|
26
|
+
return db.url || dbWithConfig.config?.url || "";
|
|
27
|
+
}
|
|
28
|
+
function getDatabaseTypeHint(config2) {
|
|
29
|
+
if (!config2 || typeof config2 === "string") {
|
|
30
|
+
return void 0;
|
|
31
|
+
}
|
|
32
|
+
const configWithType = config2;
|
|
33
|
+
if (typeof configWithType.type === "string") {
|
|
34
|
+
return configWithType.type;
|
|
35
|
+
}
|
|
36
|
+
if (typeof configWithType.config?.type === "string") {
|
|
37
|
+
return configWithType.config.type;
|
|
38
|
+
}
|
|
39
|
+
if ("query" in configWithType && typeof configWithType.query === "function") {
|
|
40
|
+
return void 0;
|
|
41
|
+
}
|
|
42
|
+
if ("client" in configWithType && configWithType.client) {
|
|
43
|
+
return "postgres";
|
|
44
|
+
}
|
|
45
|
+
return void 0;
|
|
46
|
+
}
|
|
47
|
+
function normalizeIncomingAiUsageTokens(value) {
|
|
48
|
+
if (!value || typeof value !== "object") {
|
|
49
|
+
return void 0;
|
|
50
|
+
}
|
|
51
|
+
const usage = value;
|
|
52
|
+
const promptTokens = typeof usage.promptTokens === "number" ? usage.promptTokens : typeof usage.inputTokens === "number" ? usage.inputTokens : void 0;
|
|
53
|
+
const completionTokens = typeof usage.completionTokens === "number" ? usage.completionTokens : typeof usage.outputTokens === "number" ? usage.outputTokens : void 0;
|
|
54
|
+
const totalTokens = typeof usage.totalTokens === "number" ? usage.totalTokens : promptTokens !== void 0 || completionTokens !== void 0 ? (promptTokens ?? 0) + (completionTokens ?? 0) : void 0;
|
|
55
|
+
if (promptTokens === void 0 && completionTokens === void 0 && totalTokens === void 0) {
|
|
56
|
+
return void 0;
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
promptTokens,
|
|
60
|
+
completionTokens,
|
|
61
|
+
totalTokens
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function hydratePersistedAiUsageTokens(row) {
|
|
65
|
+
const promptTokens = typeof row.prompt_tokens === "number" ? row.prompt_tokens : row.prompt_tokens === null || row.prompt_tokens === void 0 ? void 0 : Number(row.prompt_tokens);
|
|
66
|
+
const completionTokens = typeof row.completion_tokens === "number" ? row.completion_tokens : row.completion_tokens === null || row.completion_tokens === void 0 ? void 0 : Number(row.completion_tokens);
|
|
67
|
+
const totalTokens = typeof row.total_tokens === "number" ? row.total_tokens : row.total_tokens === null || row.total_tokens === void 0 ? void 0 : Number(row.total_tokens);
|
|
68
|
+
if (promptTokens === void 0 && completionTokens === void 0 && totalTokens === void 0) {
|
|
69
|
+
return void 0;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
promptTokens,
|
|
73
|
+
completionTokens,
|
|
74
|
+
totalTokens
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function normalizeAiUsageTags(value) {
|
|
78
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
79
|
+
return void 0;
|
|
80
|
+
}
|
|
81
|
+
const tags = {};
|
|
82
|
+
for (const [key, tagValue] of Object.entries(value)) {
|
|
83
|
+
if (tagValue === void 0 || tagValue === null) continue;
|
|
84
|
+
tags[key] = String(tagValue);
|
|
85
|
+
}
|
|
86
|
+
return Object.keys(tags).length > 0 ? tags : void 0;
|
|
87
|
+
}
|
|
88
|
+
function parseAiUsageTags(value) {
|
|
89
|
+
if (typeof value !== "string") {
|
|
90
|
+
return void 0;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
return normalizeAiUsageTags(JSON.parse(value));
|
|
94
|
+
} catch {
|
|
95
|
+
return void 0;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function normalizeAiUsageTimestamp(value) {
|
|
99
|
+
if (value instanceof Date) {
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
103
|
+
const date = new Date(value);
|
|
104
|
+
if (!Number.isNaN(date.getTime())) {
|
|
105
|
+
return date;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return /* @__PURE__ */ new Date();
|
|
109
|
+
}
|
|
110
|
+
function getQueryRows(result) {
|
|
111
|
+
return Array.isArray(result) ? result : result.rows ?? [];
|
|
112
|
+
}
|
|
113
|
+
function buildAiUsageWhereClause(options) {
|
|
114
|
+
const conditions = [];
|
|
115
|
+
const params = [];
|
|
116
|
+
let nextParamIndex = 1;
|
|
117
|
+
if (options.since) {
|
|
118
|
+
conditions.push(`created_at >= $${nextParamIndex++}`);
|
|
119
|
+
params.push(options.since.toISOString());
|
|
120
|
+
}
|
|
121
|
+
if (options.until) {
|
|
122
|
+
conditions.push(`created_at <= $${nextParamIndex++}`);
|
|
123
|
+
params.push(options.until.toISOString());
|
|
124
|
+
}
|
|
125
|
+
if (options.provider) {
|
|
126
|
+
conditions.push(`provider = $${nextParamIndex++}`);
|
|
127
|
+
params.push(options.provider);
|
|
128
|
+
}
|
|
129
|
+
if (options.model) {
|
|
130
|
+
conditions.push(`model = $${nextParamIndex++}`);
|
|
131
|
+
params.push(options.model);
|
|
132
|
+
}
|
|
133
|
+
if (options.operation) {
|
|
134
|
+
conditions.push(`operation = $${nextParamIndex++}`);
|
|
135
|
+
params.push(options.operation);
|
|
136
|
+
}
|
|
137
|
+
if (options.className) {
|
|
138
|
+
conditions.push(`class_name = $${nextParamIndex++}`);
|
|
139
|
+
params.push(options.className);
|
|
140
|
+
}
|
|
141
|
+
if (options.tenantId === null) {
|
|
142
|
+
conditions.push(`tenant_id IS NULL`);
|
|
143
|
+
} else if (options.tenantId) {
|
|
144
|
+
conditions.push(`tenant_id = $${nextParamIndex++}`);
|
|
145
|
+
params.push(options.tenantId);
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
conditions,
|
|
149
|
+
params,
|
|
150
|
+
nextParamIndex
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
class SmrtClass {
|
|
154
|
+
/**
|
|
155
|
+
* AI client instance for interacting with AI models
|
|
156
|
+
*/
|
|
157
|
+
_ai;
|
|
158
|
+
/**
|
|
159
|
+
* Filesystem adapter for file operations
|
|
160
|
+
*/
|
|
161
|
+
_fs;
|
|
162
|
+
/**
|
|
163
|
+
* Database interface for data persistence
|
|
164
|
+
*/
|
|
165
|
+
_db;
|
|
166
|
+
_dbEngineHint;
|
|
167
|
+
/**
|
|
168
|
+
* Class name used for identification
|
|
169
|
+
*/
|
|
170
|
+
_className;
|
|
171
|
+
/**
|
|
172
|
+
* Signal bus for method execution tracking
|
|
173
|
+
*/
|
|
174
|
+
_signalBus;
|
|
175
|
+
/**
|
|
176
|
+
* Adapters registered by this instance (for cleanup)
|
|
177
|
+
*/
|
|
178
|
+
_registeredAdapters = [];
|
|
179
|
+
/**
|
|
180
|
+
* In-memory AI usage collector for quick inspection.
|
|
181
|
+
*/
|
|
182
|
+
_aiUsageCollector;
|
|
183
|
+
/**
|
|
184
|
+
* Registered AI usage handlers for this instance.
|
|
185
|
+
*/
|
|
186
|
+
_aiUsageHandlers = [];
|
|
187
|
+
/**
|
|
188
|
+
* Tracks whether optional runtime services (signals, AI, fs) are ready.
|
|
189
|
+
*/
|
|
190
|
+
_runtimeServicesInitialized = false;
|
|
191
|
+
/**
|
|
192
|
+
* Shared in-flight runtime initialization promise for single-flight setup.
|
|
193
|
+
*/
|
|
194
|
+
_runtimeServicesInitPromise;
|
|
195
|
+
/**
|
|
196
|
+
* Configuration options provided to the class
|
|
197
|
+
*/
|
|
198
|
+
options;
|
|
199
|
+
/**
|
|
200
|
+
* Track which databases have had system tables initialized
|
|
201
|
+
* - WeakSet for :memory: databases (URL not unique, track by instance)
|
|
202
|
+
* - Set<string> for all others (URL is unique identifier)
|
|
203
|
+
*/
|
|
204
|
+
static _systemTablesInitialized = /* @__PURE__ */ new WeakSet();
|
|
205
|
+
static _systemTablesInitializedByUrl = /* @__PURE__ */ new Set();
|
|
206
|
+
/**
|
|
207
|
+
* Creates a new SmrtClass instance
|
|
208
|
+
*
|
|
209
|
+
* @param options - Configuration options for database, filesystem, and AI clients
|
|
210
|
+
*/
|
|
211
|
+
constructor(options = {}) {
|
|
212
|
+
this.options = options;
|
|
213
|
+
this._className = this.constructor.name;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Determines whether this class requires a database to function
|
|
217
|
+
*
|
|
218
|
+
* Override this method in subclasses that require database access
|
|
219
|
+
* to enable early validation during initialization.
|
|
220
|
+
*
|
|
221
|
+
* @returns True if database is required, false otherwise
|
|
222
|
+
* @example
|
|
223
|
+
* ```typescript
|
|
224
|
+
* class MyDataModel extends SmrtClass {
|
|
225
|
+
* protected requiresDatabase(): boolean {
|
|
226
|
+
* return true; // This class needs database access
|
|
227
|
+
* }
|
|
228
|
+
* }
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
requiresDatabase() {
|
|
232
|
+
return false;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Initializes database, filesystem, and AI client connections
|
|
236
|
+
*
|
|
237
|
+
* This method sets up all required services based on the provided options.
|
|
238
|
+
* It should be called before using any of the service interfaces.
|
|
239
|
+
*
|
|
240
|
+
* @returns Promise that resolves to this instance for chaining
|
|
241
|
+
* @throws {Error} If database is required but not provided in options
|
|
242
|
+
*/
|
|
243
|
+
async initialize() {
|
|
244
|
+
await this.initializeCoreResources();
|
|
245
|
+
if (!this.options._deferRuntimeInitialization) {
|
|
246
|
+
await this.initializeRuntimeServices();
|
|
247
|
+
}
|
|
248
|
+
return this;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Initialize core resources required for ORM behavior.
|
|
252
|
+
*
|
|
253
|
+
* This setup is shared by both full runtime initialization and lightweight
|
|
254
|
+
* query hydration. Hydrated objects reuse an existing DB connection and skip
|
|
255
|
+
* repeated system-table checks.
|
|
256
|
+
*/
|
|
257
|
+
async initializeCoreResources() {
|
|
258
|
+
if (this.options.persistence && !this.options.db) {
|
|
259
|
+
this.options.db = this.options.persistence;
|
|
260
|
+
}
|
|
261
|
+
if (this.requiresDatabase() && !this.options.db) {
|
|
262
|
+
throw new Error(
|
|
263
|
+
`${this._className} requires a database configuration. Please provide 'db' in options: { db: { url: '...' } } or { db: 'database.db' }`
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
if (this.options.db) {
|
|
267
|
+
this._dbEngineHint = getDatabaseTypeHint(this.options.db);
|
|
268
|
+
if (this.options._reuseInitializedDb && typeof this.options.db === "object" && "query" in this.options.db) {
|
|
269
|
+
this._db = this.options.db;
|
|
270
|
+
this.options.db = this._db;
|
|
271
|
+
} else {
|
|
272
|
+
if (typeof this.options.db === "string") {
|
|
273
|
+
const isMemoryDb = this.options.db === ":memory:";
|
|
274
|
+
this._db = await getDatabase({
|
|
275
|
+
url: this.options.db,
|
|
276
|
+
...isMemoryDb ? {} : { dbid: `smrt:${this.options.db}` }
|
|
277
|
+
});
|
|
278
|
+
} else if ("query" in this.options.db) {
|
|
279
|
+
this._db = this.options.db;
|
|
280
|
+
} else if ("client" in this.options.db && this.options.db.client) {
|
|
281
|
+
const dbConfig = this.options.db;
|
|
282
|
+
this._db = await getDatabase({
|
|
283
|
+
type: dbConfig.type || "postgres",
|
|
284
|
+
client: dbConfig.client,
|
|
285
|
+
url: dbConfig.url
|
|
286
|
+
});
|
|
287
|
+
} else {
|
|
288
|
+
const dbConfig = this.options.db;
|
|
289
|
+
const dbUrl = dbConfig.url || "memory";
|
|
290
|
+
const isMemoryDb = dbUrl === ":memory:" || dbUrl === "memory";
|
|
291
|
+
this._db = await getDatabase({
|
|
292
|
+
...this.options.db,
|
|
293
|
+
...isMemoryDb ? {} : { dbid: `smrt:${dbUrl}` }
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
this.options.db = this._db;
|
|
297
|
+
await this.ensureSystemTables();
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Initialize optional runtime services that are not required for plain ORM reads.
|
|
303
|
+
*/
|
|
304
|
+
async initializeRuntimeServices() {
|
|
305
|
+
if (this._runtimeServicesInitialized) {
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
if (!this._runtimeServicesInitPromise) {
|
|
309
|
+
this._runtimeServicesInitPromise = (async () => {
|
|
310
|
+
if (this.options.fs && !this._fs) {
|
|
311
|
+
this._fs = await FilesystemAdapter.create(this.options.fs);
|
|
312
|
+
}
|
|
313
|
+
const globalConfig = config.toJSON();
|
|
314
|
+
const usageConfig = this.mergeAiUsageConfig(globalConfig);
|
|
315
|
+
this.initializeAiUsageHandlers(usageConfig);
|
|
316
|
+
if (!this._ai && (this.options.ai || globalConfig.ai || process.env.SMRT_AI_PROVIDER)) {
|
|
317
|
+
const aiOption = this.options.ai;
|
|
318
|
+
if (aiOption && typeof aiOption === "object" && typeof aiOption.embed === "function" && !aiOption.provider) {
|
|
319
|
+
this._ai = aiOption;
|
|
320
|
+
} else {
|
|
321
|
+
const { loadEnvConfig } = await import("@happyvertical/utils");
|
|
322
|
+
const baseConfig = globalConfig.ai || {};
|
|
323
|
+
const userConfig = { ...baseConfig, ...this.options.ai };
|
|
324
|
+
const aiConfig = loadEnvConfig(userConfig, {
|
|
325
|
+
packageName: "ai",
|
|
326
|
+
prefix: "SMRT",
|
|
327
|
+
schema: {
|
|
328
|
+
provider: "string",
|
|
329
|
+
model: "string",
|
|
330
|
+
apiKey: "string",
|
|
331
|
+
timeout: "number",
|
|
332
|
+
maxRetries: "number",
|
|
333
|
+
temperature: "number",
|
|
334
|
+
maxTokens: "number"
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
const existingOnUsage = aiConfig.onUsage ?? userConfig.onUsage ?? void 0;
|
|
338
|
+
aiConfig.onUsage = async (event) => {
|
|
339
|
+
if (typeof existingOnUsage === "function") {
|
|
340
|
+
await existingOnUsage(
|
|
341
|
+
event
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
await this.handleAiUsageCallback(event, aiConfig, usageConfig);
|
|
345
|
+
};
|
|
346
|
+
if (aiConfig.provider || aiConfig.type || aiConfig.apiKey) {
|
|
347
|
+
this._ai = await getAI(aiConfig);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
await this.initializeSignals();
|
|
352
|
+
this._runtimeServicesInitialized = true;
|
|
353
|
+
})();
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
await this._runtimeServicesInitPromise;
|
|
357
|
+
} finally {
|
|
358
|
+
this._runtimeServicesInitPromise = void 0;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Ensure deferred runtime services are ready before using them.
|
|
363
|
+
*/
|
|
364
|
+
async ensureRuntimeServicesInitialized() {
|
|
365
|
+
if (!this._runtimeServicesInitialized) {
|
|
366
|
+
await this.initializeRuntimeServices();
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Resolve the AI client, initializing deferred runtime services on demand.
|
|
371
|
+
*/
|
|
372
|
+
async getAiClient() {
|
|
373
|
+
await this.ensureRuntimeServicesInitialized();
|
|
374
|
+
if (!this._ai) {
|
|
375
|
+
throw new Error(
|
|
376
|
+
`${this._className} does not have an AI client configured. Provide 'ai' in options or configure a global SMRT AI provider.`
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
return this._ai;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Resolve the AI client if one is configured, otherwise return undefined.
|
|
383
|
+
*/
|
|
384
|
+
async getOptionalAiClient() {
|
|
385
|
+
await this.ensureRuntimeServicesInitialized();
|
|
386
|
+
return this._ai;
|
|
387
|
+
}
|
|
388
|
+
async isSystemSchemaVersionApplied(db, version) {
|
|
389
|
+
const engine = detectEngine(getDatabaseUrl(db), this._dbEngineHint);
|
|
390
|
+
if (engine === "postgres" && !await tableExists(db, "_smrt_migrations", this._dbEngineHint)) {
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
try {
|
|
394
|
+
const versionParam = engine === "postgres" ? "$1" : "?";
|
|
395
|
+
const rows = await db.query(
|
|
396
|
+
`SELECT 1 FROM _smrt_migrations WHERE version = ${versionParam} LIMIT 1`,
|
|
397
|
+
version
|
|
398
|
+
);
|
|
399
|
+
return getQueryRows(rows).length > 0;
|
|
400
|
+
} catch (error) {
|
|
401
|
+
if (engine === "postgres") {
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
return false;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Ensure SMRT system tables exist in the database
|
|
409
|
+
*
|
|
410
|
+
* System tables use _smrt_ prefix and store framework metadata:
|
|
411
|
+
* - _smrt_contexts: Context memory storage for remembered patterns
|
|
412
|
+
* - _smrt_migrations: Schema version tracking
|
|
413
|
+
* - _smrt_registry: Object registry persistence
|
|
414
|
+
* - _smrt_signals: Signal history/audit log
|
|
415
|
+
*
|
|
416
|
+
* This method is idempotent and safe to call multiple times.
|
|
417
|
+
* Tables are only created once per database connection.
|
|
418
|
+
*/
|
|
419
|
+
async ensureSystemTables() {
|
|
420
|
+
if (!this._db) return;
|
|
421
|
+
const dbUrl = getDatabaseUrl(this._db);
|
|
422
|
+
const dbConstructorName = this._db.constructor?.name || "";
|
|
423
|
+
const isMemoryDb = dbUrl === ":memory:";
|
|
424
|
+
const isJsonDb = dbConstructorName.toLowerCase().includes("json");
|
|
425
|
+
const hasUndefinedUrl = !dbUrl;
|
|
426
|
+
const useInstanceTracking = isMemoryDb || isJsonDb || hasUndefinedUrl;
|
|
427
|
+
if (useInstanceTracking) {
|
|
428
|
+
if (SmrtClass._systemTablesInitialized.has(this._db)) {
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
} else {
|
|
432
|
+
if (SmrtClass._systemTablesInitializedByUrl.has(dbUrl)) {
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
try {
|
|
437
|
+
await this.withSystemTableBootstrapLock(
|
|
438
|
+
(db) => this.bootstrapSystemTables(db)
|
|
439
|
+
);
|
|
440
|
+
await this.ensureNativeVectorStorage();
|
|
441
|
+
if (useInstanceTracking) {
|
|
442
|
+
SmrtClass._systemTablesInitialized.add(this._db);
|
|
443
|
+
} else {
|
|
444
|
+
SmrtClass._systemTablesInitializedByUrl.add(dbUrl);
|
|
445
|
+
}
|
|
446
|
+
} catch (error) {
|
|
447
|
+
const dbInfo = this._db.constructor?.name || "unknown database";
|
|
448
|
+
throw new Error(
|
|
449
|
+
`Failed to create system tables for ${dbInfo}: ${error instanceof Error ? error.message : String(error)}`,
|
|
450
|
+
{ cause: error }
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
async withSystemTableBootstrapLock(callback) {
|
|
455
|
+
if (!this._db) {
|
|
456
|
+
throw new Error("Database is not initialized");
|
|
457
|
+
}
|
|
458
|
+
const beginTransaction = this._db.beginTransaction;
|
|
459
|
+
const transaction = this._db.transaction;
|
|
460
|
+
const shouldUsePostgresLock = detectEngine(getDatabaseUrl(this._db), this._dbEngineHint) === "postgres";
|
|
461
|
+
if (!shouldUsePostgresLock) {
|
|
462
|
+
return callback(this._db);
|
|
463
|
+
}
|
|
464
|
+
if (typeof beginTransaction === "function") {
|
|
465
|
+
const tx = await beginTransaction.call(this._db);
|
|
466
|
+
if (!tx) {
|
|
467
|
+
throw new Error("Database transaction could not be started");
|
|
468
|
+
}
|
|
469
|
+
try {
|
|
470
|
+
await tx.query(SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL);
|
|
471
|
+
const result = await callback(tx);
|
|
472
|
+
await tx.commit();
|
|
473
|
+
return result;
|
|
474
|
+
} catch (error) {
|
|
475
|
+
await this.rollbackSystemTableBootstrap(tx);
|
|
476
|
+
throw error;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (typeof transaction === "function") {
|
|
480
|
+
const runInTransaction = transaction.bind(this._db);
|
|
481
|
+
return runInTransaction(async (tx) => {
|
|
482
|
+
await tx.query(SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL);
|
|
483
|
+
return callback(tx);
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
throw new Error(
|
|
487
|
+
"Postgres system table bootstrap requires a transaction-capable database adapter"
|
|
488
|
+
);
|
|
489
|
+
}
|
|
490
|
+
async rollbackSystemTableBootstrap(tx) {
|
|
491
|
+
try {
|
|
492
|
+
if (typeof tx.isActive !== "function" || tx.isActive()) {
|
|
493
|
+
await tx.rollback();
|
|
494
|
+
}
|
|
495
|
+
} catch (rollbackError) {
|
|
496
|
+
logger.warn(
|
|
497
|
+
`[smrt] Failed to rollback system table bootstrap transaction: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
async bootstrapSystemTables(db) {
|
|
502
|
+
const version = SMRT_SCHEMA_VERSION;
|
|
503
|
+
if (await this.isSystemSchemaVersionApplied(db, version)) {
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
await ensureLegacySystemTableCompatibility(db, this._dbEngineHint);
|
|
507
|
+
const allStatements = [];
|
|
508
|
+
for (const multiStatementSQL of ALL_SYSTEM_TABLES) {
|
|
509
|
+
const statements = multiStatementSQL.split(";").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
510
|
+
allStatements.push(...statements);
|
|
511
|
+
}
|
|
512
|
+
for (const statement of allStatements) {
|
|
513
|
+
await db.query(statement);
|
|
514
|
+
}
|
|
515
|
+
const id = crypto.randomUUID();
|
|
516
|
+
const description = "Initial SMRT system tables";
|
|
517
|
+
await db.execute`
|
|
518
|
+
INSERT INTO _smrt_migrations (id, version, description)
|
|
519
|
+
VALUES (${id}, ${version}, ${description})
|
|
520
|
+
ON CONFLICT(version) DO NOTHING
|
|
521
|
+
`;
|
|
522
|
+
}
|
|
523
|
+
async ensureNativeVectorStorage() {
|
|
524
|
+
if (!this._db) {
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
try {
|
|
528
|
+
const { ObjectRegistry } = await import("./registry.js");
|
|
529
|
+
const embeddingConfig = ObjectRegistry.getProjectEmbeddingConfig();
|
|
530
|
+
if (embeddingConfig?.storage === "native") {
|
|
531
|
+
const { EmbeddingStorage } = await import("./embeddings/storage.js");
|
|
532
|
+
const vector = this._db.vector;
|
|
533
|
+
if (vector) {
|
|
534
|
+
const dimensions = embeddingConfig.dimensions || 768;
|
|
535
|
+
await EmbeddingStorage.ensureVectorStorage(
|
|
536
|
+
this._db,
|
|
537
|
+
dimensions,
|
|
538
|
+
vector
|
|
539
|
+
);
|
|
540
|
+
} else {
|
|
541
|
+
logger.warn(
|
|
542
|
+
'[smrt] Embedding storage set to "native" but database has no vector capability. Falling back to JSON storage.'
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
} catch (error) {
|
|
547
|
+
logger.warn(
|
|
548
|
+
`[smrt] Failed to initialize vector storage: ${error instanceof Error ? error.message : String(error)}`
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Access system tables through standard database interface
|
|
554
|
+
* System tables use _smrt_ prefix to avoid conflicts with user tables
|
|
555
|
+
*/
|
|
556
|
+
get systemDb() {
|
|
557
|
+
return this._db;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Initialize signal bus and adapters
|
|
561
|
+
*
|
|
562
|
+
* Merges global configuration with instance-specific overrides.
|
|
563
|
+
* Registers built-in and custom adapters based on configuration.
|
|
564
|
+
*/
|
|
565
|
+
async initializeSignals() {
|
|
566
|
+
const globalConfig = config.toJSON();
|
|
567
|
+
const effectiveConfig = this.mergeSignalConfig(globalConfig);
|
|
568
|
+
if (this.options.signals?.bus) {
|
|
569
|
+
this._signalBus = this.options.signals.bus;
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
if (!this.shouldInitializeSignals(effectiveConfig)) {
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
this._signalBus = new SignalBus({
|
|
576
|
+
sanitization: effectiveConfig.sanitization
|
|
577
|
+
});
|
|
578
|
+
await this.registerAdapters(effectiveConfig);
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Merge global and instance signal configuration
|
|
582
|
+
*
|
|
583
|
+
* Instance configuration takes priority over global defaults.
|
|
584
|
+
*
|
|
585
|
+
* @param globalConfig - Global configuration from smrt.configure()
|
|
586
|
+
* @returns Merged configuration
|
|
587
|
+
*/
|
|
588
|
+
mergeSignalConfig(globalConfig) {
|
|
589
|
+
return {
|
|
590
|
+
logging: this.options.logging ?? globalConfig.logging,
|
|
591
|
+
metrics: this.options.metrics ?? globalConfig.metrics,
|
|
592
|
+
pubsub: this.options.pubsub ?? globalConfig.pubsub,
|
|
593
|
+
usage: this.mergeAiUsageConfig(globalConfig),
|
|
594
|
+
sanitization: this.options.sanitization ?? globalConfig.sanitization,
|
|
595
|
+
signals: {
|
|
596
|
+
bus: this.options.signals?.bus ?? globalConfig.signals?.bus,
|
|
597
|
+
adapters: [
|
|
598
|
+
...globalConfig.signals?.adapters ?? [],
|
|
599
|
+
...this.options.signals?.adapters ?? []
|
|
600
|
+
]
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Check if signals should be initialized
|
|
606
|
+
*
|
|
607
|
+
* Signals are initialized if any adapter is configured.
|
|
608
|
+
*
|
|
609
|
+
* @param config - Effective signal configuration
|
|
610
|
+
* @returns True if signals should be initialized
|
|
611
|
+
*/
|
|
612
|
+
shouldInitializeSignals(config2) {
|
|
613
|
+
return !!(config2.logging !== false || config2.metrics?.enabled || config2.pubsub?.enabled || config2.signals?.adapters?.length);
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Register signal adapters based on configuration
|
|
617
|
+
*
|
|
618
|
+
* @param config - Effective signal configuration
|
|
619
|
+
*/
|
|
620
|
+
async registerAdapters(config2) {
|
|
621
|
+
if (!this._signalBus) return;
|
|
622
|
+
if (config2.logging !== false) {
|
|
623
|
+
const { createLogger: createLogger2, LoggerAdapter } = await import("@happyvertical/logger");
|
|
624
|
+
const logger2 = createLogger2(config2.logging ?? true);
|
|
625
|
+
const adapter = new LoggerAdapter(logger2);
|
|
626
|
+
this._signalBus.register(adapter);
|
|
627
|
+
this._registeredAdapters.push(adapter);
|
|
628
|
+
}
|
|
629
|
+
if (config2.metrics?.enabled) {
|
|
630
|
+
const { MetricsAdapter } = await import("./adapters/metrics.js");
|
|
631
|
+
const adapter = new MetricsAdapter();
|
|
632
|
+
this._signalBus.register(adapter);
|
|
633
|
+
this._registeredAdapters.push(adapter);
|
|
634
|
+
}
|
|
635
|
+
if (config2.pubsub?.enabled) {
|
|
636
|
+
const { PubSubAdapter } = await import("./adapters/pubsub.js");
|
|
637
|
+
const adapter = new PubSubAdapter();
|
|
638
|
+
this._signalBus.register(adapter);
|
|
639
|
+
this._registeredAdapters.push(adapter);
|
|
640
|
+
}
|
|
641
|
+
if (config2.signals?.adapters) {
|
|
642
|
+
for (const adapter of config2.signals.adapters) {
|
|
643
|
+
this._signalBus.register(adapter);
|
|
644
|
+
this._registeredAdapters.push(adapter);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Gets the filesystem adapter instance
|
|
650
|
+
*/
|
|
651
|
+
get fs() {
|
|
652
|
+
return this._fs;
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Gets the database interface instance
|
|
656
|
+
*/
|
|
657
|
+
get db() {
|
|
658
|
+
if (!this._db) {
|
|
659
|
+
throw new Error(
|
|
660
|
+
`Database accessed before initialization. Please call await instance.initialize() before accessing the database.`
|
|
661
|
+
);
|
|
662
|
+
}
|
|
663
|
+
return this._db;
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* Gets the AI client instance
|
|
667
|
+
*/
|
|
668
|
+
get ai() {
|
|
669
|
+
return this._ai;
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Get the in-memory AI usage snapshot for this instance.
|
|
673
|
+
*/
|
|
674
|
+
getAiUsageSnapshot() {
|
|
675
|
+
return this._aiUsageCollector?.getSnapshot();
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* Reset the in-memory AI usage collector.
|
|
679
|
+
*/
|
|
680
|
+
resetAiUsage() {
|
|
681
|
+
this._aiUsageCollector?.reset();
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* List persisted AI usage records.
|
|
685
|
+
*/
|
|
686
|
+
async listAiUsage(options = {}) {
|
|
687
|
+
if (!this._db) {
|
|
688
|
+
throw new Error(
|
|
689
|
+
`AI usage requires a database configuration. Please call initialize() with a db option before querying usage.`
|
|
690
|
+
);
|
|
691
|
+
}
|
|
692
|
+
const { conditions, params } = buildAiUsageWhereClause(options);
|
|
693
|
+
let paramIndex = params.length + 1;
|
|
694
|
+
let sql = "SELECT * FROM _smrt_ai_usage";
|
|
695
|
+
if (conditions.length > 0) {
|
|
696
|
+
sql += ` WHERE ${conditions.join(" AND ")}`;
|
|
697
|
+
}
|
|
698
|
+
sql += ` ORDER BY ${options.orderBy === "timestamp ASC" ? "created_at ASC" : "created_at DESC"}`;
|
|
699
|
+
if (options.limit !== void 0) {
|
|
700
|
+
sql += ` LIMIT $${paramIndex++}`;
|
|
701
|
+
params.push(options.limit);
|
|
702
|
+
}
|
|
703
|
+
if (options.offset !== void 0) {
|
|
704
|
+
sql += ` OFFSET $${paramIndex++}`;
|
|
705
|
+
params.push(options.offset);
|
|
706
|
+
}
|
|
707
|
+
const rows = getQueryRows(await this._db.query(sql, ...params));
|
|
708
|
+
return rows.map((row) => ({
|
|
709
|
+
id: String(row.id),
|
|
710
|
+
provider: String(row.provider),
|
|
711
|
+
model: String(row.model),
|
|
712
|
+
operation: String(row.operation),
|
|
713
|
+
usage: hydratePersistedAiUsageTokens(row),
|
|
714
|
+
estimatedCost: row.estimated_cost === null || row.estimated_cost === void 0 ? void 0 : Number(row.estimated_cost),
|
|
715
|
+
duration: Number(row.duration ?? 0),
|
|
716
|
+
className: row.class_name === null || row.class_name === void 0 ? void 0 : String(row.class_name),
|
|
717
|
+
tenantId: row.tenant_id === void 0 ? void 0 : row.tenant_id,
|
|
718
|
+
tags: parseAiUsageTags(row.tags),
|
|
719
|
+
timestamp: normalizeAiUsageTimestamp(row.created_at)
|
|
720
|
+
}));
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Summarize persisted AI usage records by a grouping dimension.
|
|
724
|
+
*/
|
|
725
|
+
async summarizeAiUsage(options = {}) {
|
|
726
|
+
if (!this._db) {
|
|
727
|
+
throw new Error(
|
|
728
|
+
`AI usage requires a database configuration. Please call initialize() with a db option before querying usage.`
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
const groupBy = options.groupBy ?? "model";
|
|
732
|
+
const bucketExpression = groupBy === "provider" ? `provider` : groupBy === "model" ? `provider || ':' || model` : groupBy === "class" ? `COALESCE(class_name, 'unknown')` : groupBy === "tenant" ? `COALESCE(tenant_id, 'global')` : groupBy === "operation" ? `operation` : `substr(CAST(created_at AS TEXT), 1, 10)`;
|
|
733
|
+
const { conditions, params } = buildAiUsageWhereClause(options);
|
|
734
|
+
let sql = `
|
|
735
|
+
SELECT ${bucketExpression} AS bucket,
|
|
736
|
+
COUNT(*) AS call_count,
|
|
737
|
+
COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens,
|
|
738
|
+
COALESCE(SUM(completion_tokens), 0) AS completion_tokens,
|
|
739
|
+
COALESCE(SUM(total_tokens), 0) AS total_tokens,
|
|
740
|
+
COALESCE(SUM(duration), 0) AS total_duration,
|
|
741
|
+
COALESCE(SUM(estimated_cost), 0) AS estimated_cost,
|
|
742
|
+
MAX(created_at) AS last_used
|
|
743
|
+
FROM _smrt_ai_usage
|
|
744
|
+
`;
|
|
745
|
+
if (conditions.length > 0) {
|
|
746
|
+
sql += ` WHERE ${conditions.join(" AND ")}`;
|
|
747
|
+
}
|
|
748
|
+
sql += " GROUP BY bucket ORDER BY bucket ASC";
|
|
749
|
+
const rows = getQueryRows(await this._db.query(sql, ...params));
|
|
750
|
+
const summary = {};
|
|
751
|
+
for (const row of rows) {
|
|
752
|
+
const bucket = String(row.bucket);
|
|
753
|
+
summary[bucket] = {
|
|
754
|
+
callCount: Number(row.call_count ?? 0),
|
|
755
|
+
promptTokens: Number(row.prompt_tokens ?? 0),
|
|
756
|
+
completionTokens: Number(row.completion_tokens ?? 0),
|
|
757
|
+
totalTokens: Number(row.total_tokens ?? 0),
|
|
758
|
+
totalDuration: Number(row.total_duration ?? 0),
|
|
759
|
+
estimatedCost: Number(row.estimated_cost ?? 0),
|
|
760
|
+
lastUsed: row.last_used ? new Date(String(row.last_used)).getTime() : 0
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
return summary;
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* Gets the signal bus instance
|
|
767
|
+
*
|
|
768
|
+
* @returns Signal bus if signals are enabled, undefined otherwise
|
|
769
|
+
*/
|
|
770
|
+
get signalBus() {
|
|
771
|
+
return this._signalBus;
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Cleanup method to prevent memory leaks
|
|
775
|
+
*
|
|
776
|
+
* Unregisters all adapters from the signal bus that were registered
|
|
777
|
+
* by this instance. Call this when the SmrtClass instance is no longer
|
|
778
|
+
* needed to prevent memory leaks.
|
|
779
|
+
*
|
|
780
|
+
* @example
|
|
781
|
+
* ```typescript
|
|
782
|
+
* const product = new Product({ name: 'Widget' });
|
|
783
|
+
* await product.initialize();
|
|
784
|
+
* // ... use product ...
|
|
785
|
+
* product.destroy(); // Clean up when done
|
|
786
|
+
* ```
|
|
787
|
+
*/
|
|
788
|
+
destroy() {
|
|
789
|
+
if (this._signalBus && !this.options.signals?.bus) {
|
|
790
|
+
for (const adapter of this._registeredAdapters) {
|
|
791
|
+
this._signalBus.unregister(adapter);
|
|
792
|
+
}
|
|
793
|
+
this._registeredAdapters = [];
|
|
794
|
+
}
|
|
795
|
+
this._aiUsageCollector = void 0;
|
|
796
|
+
this._aiUsageHandlers = [];
|
|
797
|
+
}
|
|
798
|
+
mergeAiUsageConfig(globalConfig) {
|
|
799
|
+
const globalUsage = globalConfig.usage ?? {};
|
|
800
|
+
const instanceUsage = this.options.usage ?? {};
|
|
801
|
+
return {
|
|
802
|
+
enabled: instanceUsage.enabled ?? globalUsage.enabled ?? true,
|
|
803
|
+
persist: instanceUsage.persist ?? globalUsage.persist ?? true,
|
|
804
|
+
estimateCosts: instanceUsage.estimateCosts ?? globalUsage.estimateCosts ?? true,
|
|
805
|
+
costRates: {
|
|
806
|
+
...globalUsage.costRates ?? {},
|
|
807
|
+
...instanceUsage.costRates ?? {}
|
|
808
|
+
},
|
|
809
|
+
handlers: [
|
|
810
|
+
...globalUsage.handlers ?? [],
|
|
811
|
+
...instanceUsage.handlers ?? []
|
|
812
|
+
]
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
initializeAiUsageHandlers(config2) {
|
|
816
|
+
this._aiUsageCollector = void 0;
|
|
817
|
+
this._aiUsageHandlers = [];
|
|
818
|
+
if (!config2.enabled) {
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
this._aiUsageCollector = new AiUsageCollector();
|
|
822
|
+
this._aiUsageHandlers.push(this._aiUsageCollector);
|
|
823
|
+
if (config2.persist && this._db) {
|
|
824
|
+
this._aiUsageHandlers.push(new AiUsagePersistenceHandler(this._db));
|
|
825
|
+
}
|
|
826
|
+
this._aiUsageHandlers.push(...config2.handlers);
|
|
827
|
+
}
|
|
828
|
+
async handleAiUsageCallback(event, aiConfig, usageConfig) {
|
|
829
|
+
if (!usageConfig.enabled || this._aiUsageHandlers.length === 0) {
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
const normalizedEvent = this.normalizeAiUsageEvent(event, aiConfig);
|
|
833
|
+
if (!normalizedEvent) {
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
if (usageConfig.estimateCosts) {
|
|
837
|
+
normalizedEvent.estimatedCost = estimateAiUsageCost(
|
|
838
|
+
normalizedEvent.provider,
|
|
839
|
+
normalizedEvent.model,
|
|
840
|
+
normalizedEvent.usage,
|
|
841
|
+
usageConfig.costRates
|
|
842
|
+
);
|
|
843
|
+
}
|
|
844
|
+
const results = await Promise.allSettled(
|
|
845
|
+
this._aiUsageHandlers.map((handler) => handler.handle(normalizedEvent))
|
|
846
|
+
);
|
|
847
|
+
for (const result of results) {
|
|
848
|
+
if (result.status === "rejected") {
|
|
849
|
+
logger.warn(
|
|
850
|
+
`[smrt] AI usage handler failed for ${normalizedEvent.provider}:${normalizedEvent.model}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
normalizeAiUsageEvent(event, aiConfig) {
|
|
856
|
+
const raw = event ?? {};
|
|
857
|
+
const provider = firstString(
|
|
858
|
+
raw.provider,
|
|
859
|
+
raw.type,
|
|
860
|
+
aiConfig.provider,
|
|
861
|
+
aiConfig.type
|
|
862
|
+
);
|
|
863
|
+
const model = firstString(
|
|
864
|
+
raw.model,
|
|
865
|
+
raw.defaultModel,
|
|
866
|
+
aiConfig.model,
|
|
867
|
+
aiConfig.defaultModel
|
|
868
|
+
);
|
|
869
|
+
const operation = firstString(raw.operation, raw.kind, raw.method) ?? "unknown";
|
|
870
|
+
const usage = normalizeIncomingAiUsageTokens(raw.usage) ?? normalizeIncomingAiUsageTokens(raw.tokenUsage) ?? normalizeIncomingAiUsageTokens({
|
|
871
|
+
promptTokens: raw.promptTokens,
|
|
872
|
+
completionTokens: raw.completionTokens,
|
|
873
|
+
totalTokens: raw.totalTokens
|
|
874
|
+
});
|
|
875
|
+
if (!provider || !model) {
|
|
876
|
+
return void 0;
|
|
877
|
+
}
|
|
878
|
+
const duration = firstNumber(raw.duration, raw.durationMs, raw.latency) ?? 0;
|
|
879
|
+
const tenantId = "tenantId" in this && this.tenantId !== void 0 ? this.tenantId ?? null : void 0;
|
|
880
|
+
return {
|
|
881
|
+
provider,
|
|
882
|
+
model,
|
|
883
|
+
operation,
|
|
884
|
+
usage,
|
|
885
|
+
duration,
|
|
886
|
+
timestamp: normalizeAiUsageTimestamp(raw.timestamp),
|
|
887
|
+
tags: normalizeAiUsageTags(raw.tags),
|
|
888
|
+
className: this._className,
|
|
889
|
+
tenantId
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
export {
|
|
894
|
+
SmrtClass
|
|
895
|
+
};
|
|
896
|
+
//# sourceMappingURL=class.js.map
|