@happyvertical/smrt-core 0.55.22 → 0.55.23

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.
@@ -5,6 +5,13 @@
5
5
  SvelteKit and outside the ORM. Any caller with a database handle and a
6
6
  JSON-serializable work result can use it.
7
7
 
8
+ Claim creation and completion bind UTC ISO timestamp strings (#3942). The
9
+ DuckDB raw-query path does not normalize JavaScript `Date` parameters; binding
10
+ one in the claim insert fails before the work callback runs. Keep these scalar
11
+ bindings portable without changing claim identity or transaction boundaries.
12
+ The shared run-once suite executes on SQLite and DuckDB; the PostgreSQL suite
13
+ additionally covers replay and concurrent submissions across connections.
14
+
8
15
  ## Why this exists, and why it is not the token alone
9
16
 
10
17
  Every consumer with a form, a retried request, or a double-tapped button
@@ -525,6 +525,16 @@ rather than collapsing them, so there is no silent-collision hazard there.
525
525
 
526
526
  ### The `_smrt_` prefix does not mean "system table" (#2376)
527
527
 
528
+ `SmrtClass` coalesces concurrent system-table initialization through completion
529
+ of bootstrap, deferred compatibility, and vector setup (#3944). In-flight work
530
+ is shared only by the same database handle. Distinct handles at the same URL
531
+ retain database-level coordination: a caller-owned transaction may finish its
532
+ initialization statements before its tables become visible to another handle.
533
+ All same-handle waiters observe failure; the pending entry is removed so a fresh
534
+ instance can retry. Existing completed-success cache identities are unchanged.
535
+ Provision system tables on a base connection before caller-owned transactions;
536
+ constructor initialization still preserves PostgreSQL's transaction lock lifetime.
537
+
528
538
  `bootstrapSystemTables()` owns nine hand-written tables; ~25 more `_smrt_*`
529
539
  tables belong to `@smrt()` models and are created by `db:migrate` (feature
530
540
  flags, prompt overrides, subscription plans, report schedules, field policies,
package/dist/class.d.ts CHANGED
@@ -153,6 +153,7 @@ export declare class SmrtClass {
153
153
  */
154
154
  private static _systemTablesInitialized;
155
155
  private static _systemTablesInitializedByUrl;
156
+ private static _systemTablesInitializing;
156
157
  /**
157
158
  * Creates a new SmrtClass instance
158
159
  *
@@ -1 +1 @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H,IAAI,EAAE,sBASL;IAED;;;;;;;;OAQG;IACG,YAAY,CAAC,CAAC,EAClB,EAAE,EAAE,iBAAiB,EACrB,SAAS,EAAE,CAAC,KAAK,EAAE,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,GACrC,OAAO,CAAC,CAAC,CAAC;IAkBb;;OAEG;IACH,IAAI,EAAE,aAEL;IAED;;OAEG;IACH,kBAAkB,IAAI,eAAe,GAAG,SAAS;IAIjD;;OAEG;IACH,YAAY,IAAI,IAAI;IAIpB;;OAEG;IACG,WAAW,CACf,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAwD/B;;OAEG;IACG,gBAAgB,CACpB,OAAO,GAAE,qBAA0B,GAClC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAyExC;;;;OAIG;IACH,IAAI,SAAS,IAAI,SAAS,GAAG,SAAS,CAErC;IAED;;;;;;;;;;;;;;OAcG;IACH,OAAO,IAAI,IAAI;IAef,OAAO,CAAC,kBAAkB;IAsB1B,OAAO,CAAC,yBAAyB;YAkBnB,qBAAqB;IAwCnC,OAAO,CAAC,qBAAqB;CAoD9B"}
package/dist/class.js CHANGED
@@ -199,6 +199,7 @@ var SmrtClass = class SmrtClass {
199
199
  */
200
200
  static _systemTablesInitialized = /* @__PURE__ */ new WeakSet();
201
201
  static _systemTablesInitializedByUrl = /* @__PURE__ */ new Set();
202
+ static _systemTablesInitializing = /* @__PURE__ */ new WeakMap();
202
203
  /**
203
204
  * Creates a new SmrtClass instance
204
205
  *
@@ -511,15 +512,26 @@ var SmrtClass = class SmrtClass {
511
512
  if (useInstanceTracking) {
512
513
  if (SmrtClass._systemTablesInitialized.has(this._db)) return;
513
514
  } else if (SmrtClass._systemTablesInitializedByUrl.has(dbUrl)) return;
515
+ const db = this._db;
516
+ const pending = SmrtClass._systemTablesInitializing.get(db);
517
+ if (pending) return pending;
518
+ const initialization = (async () => {
519
+ try {
520
+ await ensureSystemTables(db, this._dbEngineHint);
521
+ await this.settleDeferredSystemTableCompatibility(db);
522
+ await this.ensureNativeVectorStorage();
523
+ if (useInstanceTracking) SmrtClass._systemTablesInitialized.add(db);
524
+ else SmrtClass._systemTablesInitializedByUrl.add(dbUrl);
525
+ } catch (error) {
526
+ const dbInfo = db.constructor?.name || "unknown database";
527
+ throw new Error(`Failed to create system tables for ${dbInfo}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
528
+ }
529
+ })();
530
+ SmrtClass._systemTablesInitializing.set(db, initialization);
514
531
  try {
515
- await ensureSystemTables(this._db, this._dbEngineHint);
516
- await this.settleDeferredSystemTableCompatibility(this._db);
517
- await this.ensureNativeVectorStorage();
518
- if (useInstanceTracking) SmrtClass._systemTablesInitialized.add(this._db);
519
- else SmrtClass._systemTablesInitializedByUrl.add(dbUrl);
520
- } catch (error) {
521
- const dbInfo = this._db.constructor?.name || "unknown database";
522
- throw new Error(`Failed to create system tables for ${dbInfo}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
532
+ await initialization;
533
+ } finally {
534
+ SmrtClass._systemTablesInitializing.delete(db);
523
535
  }
524
536
  }
525
537
  /**
package/dist/class.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"class.js","names":[],"sources":["../src/class.ts"],"sourcesContent":["import type { AIClient, AIClientOptions } from '@happyvertical/ai';\nimport type {\n FilesystemAdapter,\n FilesystemAdapterOptions,\n} from '@happyvertical/files';\nimport { createLogger, type LoggerConfig } from '@happyvertical/logger';\nimport {\n type AIExplicitConfig,\n getAIConfigBlock,\n mergeAIConfigObjects,\n tryResolveAIProviderConfig,\n withAIAliases,\n} from '@happyvertical/smrt-config';\nimport type {\n AiTokenUsage,\n AiUsageHandler,\n AiUsageListOptions,\n AiUsageSnapshot,\n AiUsageStats,\n AiUsageSummaryOptions,\n SignalAdapter,\n SmrtAiUsageEvent,\n SmrtAiUsageRecord,\n} from '@happyvertical/smrt-types';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n AiUsageCollector,\n AiUsagePersistenceHandler,\n} from './adapters/ai-usage.js';\nimport { estimateAiUsageCost } from './adapters/cost-rates.js';\nimport { registerChangeFeedWriter } from './change-feed.js';\nimport {\n getSmrtModuleConfig,\n type SmrtGlobalConfig,\n} from './config/global-config.js';\nimport type {\n AIConfig,\n AiUsageConfig,\n GlobalSignalConfig,\n MetricsConfig,\n PubSubConfig,\n} from './config.js';\nimport { config } from './config.js';\nimport type { DatabaseConfig } from './database.js';\nimport {\n type DecisionClient,\n type DecisionConfig,\n type DecisionOptions,\n type DecisionRequest,\n type DecisionResult,\n executeDecision,\n} from './decisions.js';\nimport { createFilesystemAdapter } from './filesystem-loader.js';\nimport { getDatabase, importAI } from './host.js';\nimport { noteNativeDuckDbHandle } from './native-duckdb.js';\nimport { applyPostgresRuntimeTimeouts } from './postgres-timeouts.js';\nimport { detectEngine } from './schema/ddl/index.js';\nimport { SignalBus } from './signals/bus.js';\nimport { ensureSystemTables as ensureFrameworkSystemTables } from './system/bootstrap.js';\nimport {\n ensureDeferredSystemTableCompatibility,\n tableExists,\n} from './system/compatibility.js';\nimport { SMRT_SCHEMA_VERSION } from './system/schema.js';\nimport { toSafeInteger } from './utils/safe-integer.js';\n\n/**\n * `_smrt_migrations.version` suffix marking that the deferred (manifest-created)\n * system tables have been through their compatibility pass (issue #2376).\n */\nconst DEFERRED_COMPATIBILITY_VERSION_SUFFIX = '+deferred-compat';\n\nconst logger = createLogger({ level: 'info' });\n\ntype DatabaseWithConfig = DatabaseInterface & {\n config?: {\n type?: string;\n url?: string;\n };\n type?: string;\n};\n\ninterface ResolvedAiUsageConfig {\n enabled: boolean;\n persist: boolean;\n estimateCosts: boolean;\n costRates?: Record<string, { input: number; output: number }>;\n handlers: AiUsageHandler[];\n}\n\ntype AiUsageFilterOptions = Pick<\n AiUsageListOptions,\n | 'since'\n | 'until'\n | 'provider'\n | 'model'\n | 'operation'\n | 'className'\n | 'tenantId'\n>;\n\ninterface AiUsageWhereClause {\n conditions: string[];\n params: unknown[];\n nextParamIndex: number;\n}\n\nfunction firstString(...candidates: unknown[]): string | undefined {\n return candidates.find((candidate): candidate is string => {\n return typeof candidate === 'string';\n });\n}\n\nfunction firstNumber(...candidates: unknown[]): number | undefined {\n return candidates.find((candidate): candidate is number => {\n return typeof candidate === 'number';\n });\n}\n\nfunction getDatabaseUrl(db: DatabaseInterface): string {\n const dbWithConfig = db as DatabaseWithConfig;\n return db.url || dbWithConfig.config?.url || '';\n}\n\nfunction getDatabaseTypeHint(\n config: DatabaseConfig | undefined,\n): string | undefined {\n if (!config || typeof config === 'string') {\n return undefined;\n }\n\n const configWithType = config as DatabaseWithConfig & {\n client?: unknown;\n };\n\n if (typeof configWithType.type === 'string') {\n return configWithType.type;\n }\n\n if (typeof configWithType.config?.type === 'string') {\n return configWithType.config.type;\n }\n\n if ('query' in configWithType && typeof configWithType.query === 'function') {\n return undefined;\n }\n\n if ('client' in configWithType && configWithType.client) {\n return 'postgres';\n }\n\n return undefined;\n}\n\nfunction normalizeIncomingAiUsageTokens(\n value: unknown,\n): AiTokenUsage | undefined {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n\n const usage = value as Record<string, unknown>;\n const promptTokens =\n typeof usage.promptTokens === 'number'\n ? usage.promptTokens\n : typeof usage.inputTokens === 'number'\n ? usage.inputTokens\n : undefined;\n const completionTokens =\n typeof usage.completionTokens === 'number'\n ? usage.completionTokens\n : typeof usage.outputTokens === 'number'\n ? usage.outputTokens\n : undefined;\n const totalTokens =\n typeof usage.totalTokens === 'number'\n ? usage.totalTokens\n : promptTokens !== undefined || completionTokens !== undefined\n ? (promptTokens ?? 0) + (completionTokens ?? 0)\n : undefined;\n\n if (\n promptTokens === undefined &&\n completionTokens === undefined &&\n totalTokens === undefined\n ) {\n return undefined;\n }\n\n return {\n promptTokens,\n completionTokens,\n totalTokens,\n };\n}\n\nfunction hydratePersistedAiUsageTokens(row: {\n prompt_tokens?: unknown;\n completion_tokens?: unknown;\n total_tokens?: unknown;\n}): AiTokenUsage | undefined {\n const promptTokens =\n row.prompt_tokens === null || row.prompt_tokens === undefined\n ? undefined\n : toSafeInteger(row.prompt_tokens, 'AI usage prompt tokens');\n const completionTokens =\n row.completion_tokens === null || row.completion_tokens === undefined\n ? undefined\n : toSafeInteger(row.completion_tokens, 'AI usage completion tokens');\n const totalTokens =\n row.total_tokens === null || row.total_tokens === undefined\n ? undefined\n : toSafeInteger(row.total_tokens, 'AI usage total tokens');\n\n if (\n promptTokens === undefined &&\n completionTokens === undefined &&\n totalTokens === undefined\n ) {\n return undefined;\n }\n\n return {\n promptTokens,\n completionTokens,\n totalTokens,\n };\n}\n\nfunction normalizeAiUsageTags(\n value: unknown,\n): Record<string, string> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return undefined;\n }\n\n const tags: Record<string, string> = {};\n for (const [key, tagValue] of Object.entries(value)) {\n if (tagValue === undefined || tagValue === null) continue;\n tags[key] = String(tagValue);\n }\n\n return Object.keys(tags).length > 0 ? tags : undefined;\n}\n\nfunction parseAiUsageTags(value: unknown): Record<string, string> | undefined {\n if (typeof value !== 'string') {\n return undefined;\n }\n\n try {\n return normalizeAiUsageTags(JSON.parse(value));\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeAiUsageTimestamp(value: unknown): Date {\n if (value instanceof Date) {\n return value;\n }\n\n if (typeof value === 'string' || typeof value === 'number') {\n const date = new Date(value);\n if (!Number.isNaN(date.getTime())) {\n return date;\n }\n }\n\n return new Date();\n}\n\nfunction getQueryRows(\n result: Awaited<ReturnType<DatabaseInterface['query']>>,\n): Record<string, unknown>[] {\n return Array.isArray(result)\n ? (result as Record<string, unknown>[])\n : ((result as { rows?: Record<string, unknown>[] }).rows ?? []);\n}\n\nfunction buildAiUsageWhereClause(\n options: AiUsageFilterOptions,\n): AiUsageWhereClause {\n const conditions: string[] = [];\n const params: unknown[] = [];\n let nextParamIndex = 1;\n\n if (options.since) {\n conditions.push(`created_at >= $${nextParamIndex++}`);\n params.push(options.since.toISOString());\n }\n\n if (options.until) {\n conditions.push(`created_at <= $${nextParamIndex++}`);\n params.push(options.until.toISOString());\n }\n\n if (options.provider) {\n conditions.push(`provider = $${nextParamIndex++}`);\n params.push(options.provider);\n }\n\n if (options.model) {\n conditions.push(`model = $${nextParamIndex++}`);\n params.push(options.model);\n }\n\n if (options.operation) {\n conditions.push(`operation = $${nextParamIndex++}`);\n params.push(options.operation);\n }\n\n if (options.className) {\n conditions.push(`class_name = $${nextParamIndex++}`);\n params.push(options.className);\n }\n\n if (options.tenantId === null) {\n conditions.push(`tenant_id IS NULL`);\n } else if (options.tenantId) {\n conditions.push(`tenant_id = $${nextParamIndex++}`);\n params.push(options.tenantId);\n }\n\n return {\n conditions,\n params,\n nextParamIndex,\n };\n}\n\n/**\n * Configuration options for the SmrtClass\n */\nexport interface SmrtClassOptions {\n /**\n * Optional custom class name override\n */\n _className?: string;\n\n /**\n * Database configuration - unified approach matching @happyvertical/sql\n *\n * Supports three formats:\n * - String shortcut: 'products.db' (auto-detects database type)\n * - Config object: { type: 'sqlite', url: 'products.db' }\n * - DatabaseInterface instance: await getDatabase(...)\n *\n * @see DatabaseConfig for type definition\n */\n db?: DatabaseConfig;\n\n /**\n * Alias for db option - for backward compatibility with documentation\n *\n * @deprecated Use 'db' instead. This alias exists for backward compatibility.\n */\n persistence?: DatabaseConfig;\n\n /**\n * Filesystem adapter configuration options\n */\n fs?: FilesystemAdapterOptions;\n\n /**\n * AI client configuration options or instance\n */\n ai?: AIClientOptions | AIClient;\n\n /**\n * Optional typed-decision provider or already-built decision-capable client.\n * It is independent from `ai`, which remains the generation client.\n */\n decisions?: DecisionConfig | DecisionClient;\n\n /**\n * AI usage tracking configuration (overrides global defaults)\n */\n usage?: AiUsageConfig;\n\n /**\n * Logging configuration (overrides global default)\n */\n logging?: LoggerConfig;\n\n /**\n * Metrics configuration (overrides global default)\n */\n metrics?: MetricsConfig;\n\n /**\n * Pub/Sub configuration (overrides global default)\n */\n pubsub?: PubSubConfig;\n\n /**\n * Sanitization configuration (overrides global default)\n */\n sanitization?: import('./config.js').GlobalSignalConfig['sanitization'];\n\n /**\n * Custom signal configuration (overrides global default)\n */\n signals?: {\n /** Shared signal bus instance */\n bus?: SignalBus;\n /** Additional custom adapters */\n adapters?: SignalAdapter[];\n };\n\n /**\n * Internal flag to reuse an already initialized DatabaseInterface instance.\n *\n * Skips database resolution and system-table setup during lightweight hydration.\n * @internal\n */\n _reuseInitializedDb?: boolean;\n\n /**\n * Internal flag to defer runtime-only services such as signals and AI setup.\n *\n * Lightweight hydration paths set this so plain query reads avoid per-row\n * runtime bootstrap costs.\n * @internal\n */\n _deferRuntimeInitialization?: boolean;\n}\n\n/**\n * Foundation class providing core functionality for the SMRT framework\n *\n * SmrtClass provides unified access to database, filesystem, and AI client\n * interfaces. It serves as the foundation for all other classes in the\n * SMRT framework.\n */\nexport class SmrtClass {\n /**\n * AI client instance for interacting with AI models\n */\n protected _ai!: AIClient;\n\n /** Optional, independently initialized typed-decision client. */\n protected _decisionClient?: DecisionClient;\n\n private _decisionClientInitPromise?: Promise<DecisionClient | undefined>;\n\n /**\n * Filesystem adapter for file operations\n */\n protected _fs!: FilesystemAdapter;\n\n /**\n * Database interface for data persistence\n */\n protected _db!: DatabaseInterface;\n private _dbEngineHint?: string;\n\n /**\n * Class name used for identification\n */\n protected _className!: string;\n\n /**\n * Signal bus for method execution tracking\n */\n protected _signalBus?: SignalBus;\n\n /**\n * Adapters registered by this instance (for cleanup)\n */\n private _registeredAdapters: SignalAdapter[] = [];\n\n /**\n * In-memory AI usage collector for quick inspection.\n */\n private _aiUsageCollector?: AiUsageCollector;\n\n /**\n * Registered AI usage handlers for this instance.\n */\n private _aiUsageHandlers: AiUsageHandler[] = [];\n\n /**\n * Tracks whether optional runtime services (signals, AI, fs) are ready.\n */\n private _runtimeServicesInitialized = false;\n\n /**\n * Shared in-flight runtime initialization promise for single-flight setup.\n */\n private _runtimeServicesInitPromise?: Promise<void>;\n\n /**\n * Configuration options provided to the class\n */\n public options: SmrtClassOptions;\n\n /**\n * Track which databases have had system tables initialized\n * - WeakSet for :memory: databases (URL not unique, track by instance)\n * - Set<string> for all others (URL is unique identifier)\n */\n private static _systemTablesInitialized = new WeakSet<DatabaseInterface>();\n private static _systemTablesInitializedByUrl = new Set<string>();\n\n /**\n * Creates a new SmrtClass instance\n *\n * @param options - Configuration options for database, filesystem, and AI clients\n */\n constructor(options: SmrtClassOptions = {}) {\n this.options = options;\n this._className = this.constructor.name;\n }\n\n /**\n * Determines whether this class requires a database to function\n *\n * Override this method in subclasses that require database access\n * to enable early validation during initialization.\n *\n * @returns True if database is required, false otherwise\n * @example\n * ```typescript\n * class MyDataModel extends SmrtClass {\n * protected requiresDatabase(): boolean {\n * return true; // This class needs database access\n * }\n * }\n * ```\n */\n protected requiresDatabase(): boolean {\n return false; // Base class doesn't require database by default\n }\n\n /**\n * Initializes database, filesystem, and AI client connections\n *\n * This method sets up all required services based on the provided options.\n * It should be called before using any of the service interfaces.\n *\n * @returns Promise that resolves to this instance for chaining\n * @throws {Error} If database is required but not provided in options\n */\n protected async initialize(): Promise<this> {\n await this.initializeCoreResources();\n\n if (!this.options._deferRuntimeInitialization) {\n await this.initializeRuntimeServices();\n }\n\n return this;\n }\n\n /**\n * Initialize core resources required for ORM behavior.\n *\n * This setup is shared by both full runtime initialization and lightweight\n * query hydration. Hydrated objects reuse an existing DB connection and skip\n * repeated system-table checks.\n */\n protected async initializeCoreResources(): Promise<void> {\n // Framework init hook for the change feed (#1758): make sure the writer\n // interceptor observes every save/delete before any instance can write.\n // Idempotent and cheap when already registered.\n registerChangeFeedWriter();\n\n // Map persistence to db for backward compatibility\n if (this.options.persistence && !this.options.db) {\n this.options.db = this.options.persistence;\n }\n\n // Validate database configuration if required\n if (this.requiresDatabase() && !this.options.db) {\n throw new Error(\n `${this._className} requires a database configuration. ` +\n `Please provide 'db' in options: { db: { url: '...' } } or { db: 'database.db' }`,\n );\n }\n\n if (this.options.db) {\n this._dbEngineHint = getDatabaseTypeHint(this.options.db);\n\n if (\n this.options._reuseInitializedDb &&\n typeof this.options.db === 'object' &&\n 'query' in this.options.db\n ) {\n this._db = this.options.db as DatabaseInterface;\n this.options.db = this._db;\n noteNativeDuckDbHandle(this._db, this._dbEngineHint);\n } else {\n // Handle four db config formats (in implementation order):\n // 1. String URL: 'products.db' (shortcut)\n // 2. DatabaseInterface instance: already initialized db (has 'query' method)\n // 3. Config with client: { type: 'postgres', client: pgPool } (SvelteKit pattern)\n // 4. Config object: { type: 'sqlite', url: 'products.db' }\n if (typeof this.options.db === 'string') {\n // Format 1: String shortcut - let getDatabase auto-detect type from URL\n // Preserve connection sharing for file-backed databases while leaving\n // true in-memory databases isolated per instance.\n const isMemoryDb = this.options.db === ':memory:';\n // PostgreSQL URLs pick up the runtime timeout bounds, and the dbid is\n // derived from the bounded URL so the same rewrite at every call site\n // still resolves to one shared pool (#2377).\n const bounded = applyPostgresRuntimeTimeouts({\n url: this.options.db,\n });\n this._db = await getDatabase({\n ...bounded,\n ...(isMemoryDb ? {} : { dbid: `smrt:${bounded.url}` }),\n } as unknown as Parameters<typeof getDatabase>[0]);\n } else if ('query' in this.options.db) {\n // Format 2: Already a DatabaseInterface instance - return as-is\n this._db = this.options.db as DatabaseInterface;\n } else if ('client' in this.options.db && this.options.db.client) {\n // Format 3: Config with pre-created client (e.g., from SvelteKit's $env-based connection)\n // Pass the client to getDatabase which will use it instead of creating a new connection\n const dbConfig = this.options.db as {\n type?: string;\n client: unknown;\n url?: string;\n };\n // `client` is a runtime-only property the postgres adapter reads\n // but the public `getDatabase` option union does not model, so the\n // literal is routed through the function's own parameter type.\n this._db = await getDatabase({\n type: dbConfig.type || 'postgres',\n client: dbConfig.client,\n url: dbConfig.url,\n } as unknown as Parameters<typeof getDatabase>[0]);\n } else {\n // Format 4: Config object - pass to getDatabase (handles all types uniformly)\n // Preserve connection sharing for file-backed databases while leaving\n // true in-memory databases isolated per instance.\n const dbConfig = this.options.db as { url?: string; type?: string };\n const dbUrl = dbConfig.url || 'memory';\n const isMemoryDb = dbUrl === ':memory:' || dbUrl === 'memory';\n // Keep the config's own key set: an object with no `url` must stay\n // that way so the adapter applies its own default (#2377).\n const bounded = applyPostgresRuntimeTimeouts({ ...this.options.db });\n // The loose config-object variant of `DatabaseConfig` carries an\n // index signature that the closed `getDatabase` option union does\n // not accept structurally, so route through its parameter type.\n this._db = await getDatabase({\n ...bounded,\n ...(isMemoryDb ? {} : { dbid: `smrt:${bounded.url ?? dbUrl}` }),\n } as unknown as Parameters<typeof getDatabase>[0]);\n }\n\n /**\n * INTENTIONAL MUTATION: After resolving the database config,\n * we replace options.db with the actual DatabaseInterface instance.\n * This enables child objects to share the same connection via:\n *\n * const child = new ChildObject({ db: parent.options.db });\n *\n * Without this, passing this.options to getCollection() would use the config object\n * which causes a NEW db instance to be created, losing data isolation.\n *\n * See issue #567 for context on why this pattern is necessary.\n */\n this.options.db = this._db;\n // Identify a native DuckDB root now, so transaction handles later\n // bound to this object resolve to the same engine (#3737).\n noteNativeDuckDbHandle(this._db, this._dbEngineHint);\n\n await this.ensureSystemTables();\n }\n }\n }\n\n /**\n * Initialize optional runtime services that are not required for plain ORM reads.\n */\n protected async initializeRuntimeServices(): Promise<void> {\n if (this._runtimeServicesInitialized) {\n return;\n }\n\n if (!this._runtimeServicesInitPromise) {\n this._runtimeServicesInitPromise = (async () => {\n if (this.options.fs && !this._fs) {\n // Acquired through the boundary in filesystem-loader.ts so the\n // @happyvertical/files SDK (S3/googleapis) never enters\n // provider-neutral consumer bundles (#1977/#1979).\n this._fs = await createFilesystemAdapter(this.options.fs);\n }\n\n // Initialize AI client with environment variable support\n // Priority: instance options > env vars > global config > defaults\n const globalConfig = config.toJSON();\n const usageConfig = this.mergeAiUsageConfig(globalConfig);\n this.initializeAiUsageHandlers(usageConfig);\n\n // The smrt.config.ts `ai` block (resolved through smrt-config's shared\n // resolver) is the lowest-priority declared source, above SMRT_AI_*.\n // Only a block that names a provider counts: a partial block (model,\n // baseUrl or apiKeyEnv alone) behaves exactly like an absent block.\n const declaredBlock = getAIConfigBlock();\n const aiConfigBlock = declaredBlock?.provider ? declaredBlock : null;\n if (\n !this._ai &&\n (this.options.ai ||\n globalConfig.ai ||\n aiConfigBlock ||\n process.env.SMRT_AI_PROVIDER)\n ) {\n // Check if options.ai is already a client-like object with embed method\n // This allows passing mock AI clients for testing\n const aiOption = this.options.ai as\n | Record<string, unknown>\n | undefined;\n if (\n aiOption &&\n typeof aiOption === 'object' &&\n typeof aiOption.embed === 'function' &&\n !aiOption.provider\n ) {\n this._ai = aiOption as unknown as AIClient;\n } else {\n // Passthrough tuning fields (timeout, maxRetries, ...) still come\n // from `SMRT_AI_*` via loadEnvConfig. Provider/key/model selection\n // goes through the shared smrt-config resolver below (#3372).\n const { loadEnvConfig } = await import('@happyvertical/utils');\n\n // Start with global defaults\n const baseConfig = globalConfig.ai || {};\n\n // Merge with instance options (takes priority over global)\n // Provider ownership holds across these two layers too: the shared\n // canonicalising merge folds provider/type and model/defaultModel,\n // and drops the global layer's provider, key, base URL and model\n // when the instance options name a different provider.\n const userConfig = mergeAIConfigObjects(\n baseConfig,\n this.options.ai,\n );\n\n // Load environment variables and merge (user options take priority).\n // `AIConfig` carries an index signature, so provider-specific keys\n // (`type`, `onUsage`, `defaultModel`, …) read back as `unknown`.\n const aiConfig = loadEnvConfig<AIConfig>(userConfig, {\n packageName: 'ai',\n prefix: 'SMRT',\n schema: {\n provider: 'string',\n model: 'string',\n apiKey: 'string',\n timeout: 'number',\n maxRetries: 'number',\n temperature: 'number',\n maxTokens: 'number',\n },\n });\n\n // Provider, key, base URL and model always come from the shared\n // resolver's bound result (options.ai > core global config >\n // smrt.config `ai` block > SMRT_AI_*), so a credential is only ever\n // sent to the provider its own source named; env-loaded values are\n // replaced, not merged. Tuning fields keep their current source.\n // Without a block the provider's own key variable is not consulted\n // (no behaviour change for apps that never declared one).\n const resolvedAi = tryResolveAIProviderConfig({\n explicit: userConfig as AIExplicitConfig,\n config: aiConfigBlock,\n prefixes: ['SMRT_AI'],\n autoDetect: false,\n requireProvider: false,\n providerKeyEnvFallback: Boolean(aiConfigBlock),\n });\n // Replace (never merge) the identity/credential fields with the\n // resolver's bound result, then set both client-facing aliases so\n // no stale `type` / `defaultModel` reaches getAI().\n const bound: Record<string, unknown> = {\n provider: resolvedAi?.provider,\n apiKey: resolvedAi?.apiKey,\n baseUrl: resolvedAi?.baseUrl,\n model: resolvedAi?.model,\n };\n for (const key of [\n 'provider',\n 'type',\n 'apiKey',\n 'baseUrl',\n 'model',\n 'defaultModel',\n ]) {\n delete (aiConfig as Record<string, unknown>)[key];\n }\n for (const [key, value] of Object.entries(bound)) {\n if (value) (aiConfig as Record<string, unknown>)[key] = value;\n }\n Object.assign(\n aiConfig,\n withAIAliases(aiConfig as Record<string, unknown>),\n );\n\n const existingOnUsage =\n aiConfig.onUsage ??\n (userConfig as Record<string, unknown>).onUsage ??\n undefined;\n aiConfig.onUsage = async (event: unknown) => {\n if (typeof existingOnUsage === 'function') {\n await (existingOnUsage as (usageEvent: unknown) => unknown)(\n event,\n );\n }\n await this.handleAiUsageCallback(event, aiConfig, usageConfig);\n };\n\n // Only initialize if we have a provider configured\n if (aiConfig.provider || aiConfig.type || aiConfig.apiKey) {\n // Use the getAI() factory (loaded lazily to keep the\n // `@happyvertical/ai` module graph off smrt-core's cold-start\n // import path — see issue #2894) to support all AI providers\n // (OpenAI, Anthropic, Gemini, etc.). getAI() returns\n // AIInterface, which we narrow to AIClient for backward\n // compatibility. The index-signature `AIConfig` is routed\n // through getAI's own parameter type rather than the closed\n // union.\n const { getAI } = await importAI();\n this._ai = (await getAI(\n aiConfig as unknown as Parameters<typeof getAI>[0],\n )) as unknown as AIClient;\n }\n }\n }\n\n await this.initializeSignals();\n this._runtimeServicesInitialized = true;\n })();\n }\n\n try {\n await this._runtimeServicesInitPromise;\n } finally {\n this._runtimeServicesInitPromise = undefined;\n }\n }\n\n /**\n * Ensure deferred runtime services are ready before using them.\n */\n protected async ensureRuntimeServicesInitialized(): Promise<void> {\n if (!this._runtimeServicesInitialized) {\n await this.initializeRuntimeServices();\n }\n }\n\n /**\n * Resolve the AI client, initializing deferred runtime services on demand.\n */\n protected async getAiClient(): Promise<AIClient> {\n await this.ensureRuntimeServicesInitialized();\n\n if (!this._ai) {\n throw new Error(\n `${this._className} does not have an AI client configured. ` +\n `Provide 'ai' in options or configure a global SMRT AI provider.`,\n );\n }\n\n return this._ai;\n }\n\n /**\n * Resolve the AI client if one is configured, otherwise return undefined.\n */\n protected async getOptionalAiClient(): Promise<AIClient | undefined> {\n await this.ensureRuntimeServicesInitialized();\n return this._ai;\n }\n\n /**\n * Resolve the optional typed-decision client without changing the generation\n * client used by `is()`, `do()`, or `describe()`. The SDK import stays inside\n * this opt-in path so ordinary SMRT applications neither load nor configure\n * the decision provider.\n */\n protected async getDecisionClient(): Promise<DecisionClient | undefined> {\n await this.ensureRuntimeServicesInitialized();\n\n if (this._decisionClient) return this._decisionClient;\n if (this._decisionClientInitPromise) {\n return this._decisionClientInitPromise;\n }\n\n this._decisionClientInitPromise = (async () => {\n const instanceDecision = this.options.decisions;\n if (\n instanceDecision &&\n typeof instanceDecision === 'object' &&\n typeof (instanceDecision as DecisionClient).decide === 'function'\n ) {\n this._decisionClient = instanceDecision as DecisionClient;\n return this._decisionClient;\n }\n\n const configuredDecision = this.getDecisionConfig();\n if (!configuredDecision) return undefined;\n if (configuredDecision.type !== 'typesafe') {\n throw new Error(\"Decision configuration requires type: 'typesafe'.\");\n }\n\n // `getAI()` is deliberately dynamically imported, matching the existing\n // generation setup. The #1284 SDK adds `decide` as an optional interface\n // capability, so third-party/older clients remain source-compatible.\n const { getAI } = await importAI();\n this._decisionClient = (await getAI(\n configuredDecision as Parameters<typeof getAI>[0],\n )) as unknown as DecisionClient;\n return this._decisionClient;\n })();\n\n try {\n return await this._decisionClientInitPromise;\n } finally {\n this._decisionClientInitPromise = undefined;\n }\n }\n\n /**\n * Attempt one typed decision batch against caller-curated state.\n *\n * `undefined` is the explicit legacy-route signal: no decision client was\n * configured. Configured capability, provider, and response errors always\n * propagate. Object methods with registered tools must retain their\n * generation route and therefore do not call this helper.\n */\n protected async attemptDecision(\n request: DecisionRequest,\n options?: DecisionOptions,\n ): Promise<DecisionResult | undefined> {\n const decision = await this.getDecisionClient();\n if (!decision) return undefined;\n\n const result = await executeDecision(decision, request, options);\n await this.recordAiUsageEvent(\n {\n provider: result.provenance.provider,\n model: result.provenance.model,\n operation: 'decision',\n usage: result.usage,\n tags: { operation: 'decision' },\n },\n result.provenance,\n );\n return result;\n }\n\n /** Resolve project, global, and instance decision options in that order. */\n protected getDecisionConfig(): DecisionConfig | undefined {\n const instanceDecision = this.options.decisions;\n const instanceConfig =\n instanceDecision &&\n typeof instanceDecision === 'object' &&\n typeof (instanceDecision as DecisionClient).decide !== 'function'\n ? (instanceDecision as Partial<DecisionConfig>)\n : undefined;\n const projectDecision = getSmrtModuleConfig<SmrtGlobalConfig>('smrt', {})\n .decisions as Partial<DecisionConfig> | undefined;\n const globalDecision = config.toJSON().decisions as\n | Partial<DecisionConfig>\n | undefined;\n const resolved = {\n ...projectDecision,\n ...globalDecision,\n ...instanceConfig,\n } as Partial<DecisionConfig>;\n return Object.keys(resolved).length === 0\n ? undefined\n : (resolved as DecisionConfig);\n }\n\n /**\n * Records an SDK operation through SMRT's established usage handlers. The\n * event carries provider/model/tokens only; prompts, object data, and secrets\n * never enter usage persistence or callbacks.\n */\n protected async recordAiUsageEvent(\n event: unknown,\n providerConfig: Record<string, unknown>,\n ): Promise<void> {\n await this.ensureRuntimeServicesInitialized();\n await this.handleAiUsageCallback(\n event,\n providerConfig,\n this.mergeAiUsageConfig(config.toJSON()),\n );\n }\n\n private async isSystemSchemaVersionApplied(\n db: DatabaseInterface,\n version: string,\n ): Promise<boolean> {\n const engine = detectEngine(getDatabaseUrl(db), this._dbEngineHint);\n\n if (\n engine === 'postgres' &&\n !(await tableExists(db, '_smrt_migrations', this._dbEngineHint))\n ) {\n return false;\n }\n\n try {\n const versionParam = engine === 'postgres' ? '$1' : '?';\n const rows = await db.query(\n `SELECT 1 FROM _smrt_migrations WHERE version = ${versionParam} LIMIT 1`,\n version,\n );\n return getQueryRows(rows).length > 0;\n } catch (error) {\n if (engine === 'postgres') {\n throw error;\n }\n\n return false;\n }\n }\n\n /**\n * Ensure SMRT system tables exist in the database\n *\n * System tables use the _smrt_ prefix and store framework metadata:\n * - _smrt_contexts: Context memory storage for remembered patterns\n * - _smrt_migrations: Schema version tracking\n * - _smrt_schema_migrations / _smrt_backfills: Migration and backfill ledgers\n * - _smrt_embeddings: Embedding vectors for semantic search\n * - _smrt_dispatch / _smrt_dispatch_subscriptions: Inter-agent dispatch queue\n * - _smrt_ai_usage: AI usage telemetry\n * - _smrt_changes: Append-only change feed\n *\n * Note that the _smrt_ prefix alone does NOT mean \"system table\" — ~25\n * `@smrt()` domain tables (feature flags, prompt overrides, subscription\n * plans, …) carry it too and are created by `db:migrate`, not here. The\n * framework's own list is `SYSTEM_TABLE_NAMES` in\n * `schema/system-table-shapes.ts`, derived from this DDL.\n *\n * This method is idempotent and safe to call multiple times.\n * Tables are only created once per database connection.\n */\n private async ensureSystemTables(): Promise<void> {\n if (!this._db) return;\n\n const dbUrl = getDatabaseUrl(this._db);\n\n // Some databases share URLs but are different instances:\n // - :memory: databases (SQLite/DuckDB in-memory)\n // - JSON databases (may have undefined or shared URLs)\n // - Any database with undefined URL\n // Use WeakSet for instance tracking, Set<string> for URL tracking\n const dbConstructorName = this._db.constructor?.name || '';\n const isMemoryDb = dbUrl === ':memory:';\n const isJsonDb = dbConstructorName.toLowerCase().includes('json');\n const hasUndefinedUrl = !dbUrl;\n const useInstanceTracking = isMemoryDb || isJsonDb || hasUndefinedUrl;\n\n if (useInstanceTracking) {\n // Check WeakSet for databases that may share URLs (track by instance)\n if (SmrtClass._systemTablesInitialized.has(this._db)) {\n return;\n }\n } else {\n // Check Set<string> for URL-based databases (track by URL)\n if (SmrtClass._systemTablesInitializedByUrl.has(dbUrl)) {\n return;\n }\n }\n\n try {\n await ensureFrameworkSystemTables(this._db, this._dbEngineHint);\n await this.settleDeferredSystemTableCompatibility(this._db);\n await this.ensureNativeVectorStorage();\n\n // Mark as initialized using appropriate tracking mechanism\n if (useInstanceTracking) {\n SmrtClass._systemTablesInitialized.add(this._db);\n } else {\n SmrtClass._systemTablesInitializedByUrl.add(dbUrl);\n }\n } catch (error) {\n // DO NOT SWALLOW ERRORS - fail loudly so we know what's wrong\n const dbInfo = this._db.constructor?.name || 'unknown database';\n throw new Error(\n `Failed to create system tables for ${dbInfo}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n }\n\n /**\n * Run the compatibility pass for the system tables `db:migrate` creates, then\n * stamp its own marker in `_smrt_migrations` (issue #2376).\n *\n * Deliberately runs OUTSIDE the bootstrap lock/transaction, and deliberately\n * cannot fail startup:\n *\n * - `_smrt_jobs` / `_smrt_job_events` are created by `db:migrate` from the\n * jobs manifest, which on a fresh install runs AFTER the framework's first\n * bootstrap. Gating this pass on {@link SMRT_SCHEMA_VERSION} would mean the\n * version gets stamped while the tables are still absent and the pass never\n * runs on that database again. It therefore carries its own marker, which\n * is written only once every deferred table exists and has been upgraded.\n * - Its statements are ALTER TABLE / CREATE INDEX against tables the\n * framework does not own. Inside the PostgreSQL bootstrap transaction one\n * failure (a permissions problem, say) would abort the transaction and roll\n * back system-table creation with it. Outside, a failure is a logged\n * warning and the next process start retries — the pass is idempotent and\n * already tolerates concurrent creators.\n *\n * Until the tables exist this costs two catalog probes per process per\n * database; afterwards the marker short-circuits it.\n */\n private async settleDeferredSystemTableCompatibility(\n db: DatabaseInterface,\n ): Promise<void> {\n const marker = `${SMRT_SCHEMA_VERSION}${DEFERRED_COMPATIBILITY_VERSION_SUFFIX}`;\n\n try {\n if (await this.isSystemSchemaVersionApplied(db, marker)) {\n return;\n }\n\n const { settled } = await ensureDeferredSystemTableCompatibility(\n db,\n this._dbEngineHint,\n );\n if (!settled) {\n return;\n }\n\n const id = crypto.randomUUID();\n const description = 'Deferred SMRT system table compatibility';\n await db.execute`\n INSERT INTO _smrt_migrations (id, version, description)\n VALUES (${id}, ${marker}, ${description})\n ON CONFLICT(version) DO NOTHING\n `;\n } catch (error) {\n logger.warn(\n `[smrt] Deferred system table compatibility did not complete; retrying on the next start: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n\n private async ensureNativeVectorStorage(): Promise<void> {\n if (!this._db) {\n return;\n }\n\n try {\n const { ObjectRegistry } = await import('./registry.js');\n const embeddingConfig = ObjectRegistry.getProjectEmbeddingConfig();\n if (embeddingConfig?.storage === 'native') {\n const { EmbeddingStorage } = await import('./embeddings/storage.js');\n const vector = this._db.vector;\n if (vector) {\n const dimensions = embeddingConfig.dimensions || 768;\n await EmbeddingStorage.ensureVectorStorage(\n this._db,\n dimensions,\n vector,\n );\n } else {\n logger.warn(\n '[smrt] Embedding storage set to \"native\" but database has no vector capability. Falling back to JSON storage.',\n );\n }\n }\n } catch (error) {\n // Don't fail system table initialization for vector setup errors\n logger.warn(\n `[smrt] Failed to initialize vector storage: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /**\n * Access system tables through standard database interface\n * System tables use _smrt_ prefix to avoid conflicts with user tables\n */\n protected get systemDb(): DatabaseInterface {\n return this._db;\n }\n\n /**\n * Return the database engine hint captured from the caller's configuration.\n * Adapters may not expose their original type after construction (notably\n * in-memory DuckDB/JSON connections), so query helpers can combine this\n * hint with their public connection capabilities.\n */\n protected getDatabaseEngineHint(): string | undefined {\n return this._dbEngineHint;\n }\n\n /**\n * Initialize signal bus and adapters\n *\n * Merges global configuration with instance-specific overrides.\n * Registers built-in and custom adapters based on configuration.\n */\n private async initializeSignals(): Promise<void> {\n const globalConfig = config.toJSON();\n const effectiveConfig = this.mergeSignalConfig(globalConfig);\n\n // If a shared bus is provided, always use it (don't create new adapters)\n if (this.options.signals?.bus) {\n this._signalBus = this.options.signals.bus;\n return;\n }\n\n // Otherwise, check if we should initialize signals based on config\n if (!this.shouldInitializeSignals(effectiveConfig)) {\n return;\n }\n\n this._signalBus = new SignalBus({\n sanitization: effectiveConfig.sanitization,\n });\n await this.registerAdapters(effectiveConfig);\n }\n\n /**\n * Merge global and instance signal configuration\n *\n * Instance configuration takes priority over global defaults.\n *\n * @param globalConfig - Global configuration from smrt.configure()\n * @returns Merged configuration\n */\n private mergeSignalConfig(\n globalConfig: GlobalSignalConfig,\n ): GlobalSignalConfig {\n return {\n logging: this.options.logging ?? globalConfig.logging,\n metrics: this.options.metrics ?? globalConfig.metrics,\n pubsub: this.options.pubsub ?? globalConfig.pubsub,\n usage: this.mergeAiUsageConfig(globalConfig),\n sanitization: this.options.sanitization ?? globalConfig.sanitization,\n signals: {\n bus: this.options.signals?.bus ?? globalConfig.signals?.bus,\n adapters: [\n ...(globalConfig.signals?.adapters ?? []),\n ...(this.options.signals?.adapters ?? []),\n ],\n },\n };\n }\n\n /**\n * Check if signals should be initialized\n *\n * Signals are initialized if any adapter is configured.\n *\n * @param config - Effective signal configuration\n * @returns True if signals should be initialized\n */\n private shouldInitializeSignals(config: GlobalSignalConfig): boolean {\n return !!(\n config.logging !== false ||\n config.metrics?.enabled ||\n config.pubsub?.enabled ||\n config.signals?.adapters?.length\n );\n }\n\n /**\n * Register signal adapters based on configuration\n *\n * @param config - Effective signal configuration\n */\n private async registerAdapters(config: GlobalSignalConfig): Promise<void> {\n if (!this._signalBus) return;\n\n // Logging adapter (default: enabled with console)\n if (config.logging !== false) {\n const { createLogger, LoggerAdapter } = await import(\n '@happyvertical/logger'\n );\n const logger = createLogger(config.logging ?? true);\n const adapter = new LoggerAdapter(logger);\n this._signalBus.register(adapter);\n this._registeredAdapters.push(adapter);\n }\n\n // Metrics adapter (default: disabled)\n if (config.metrics?.enabled) {\n const { MetricsAdapter } = await import('./adapters/metrics.js');\n const adapter = new MetricsAdapter();\n this._signalBus.register(adapter);\n this._registeredAdapters.push(adapter);\n }\n\n // Pub/Sub adapter (default: disabled)\n if (config.pubsub?.enabled) {\n const { PubSubAdapter } = await import('./adapters/pubsub.js');\n const adapter = new PubSubAdapter();\n this._signalBus.register(adapter);\n this._registeredAdapters.push(adapter);\n }\n\n // Custom adapters\n if (config.signals?.adapters) {\n for (const adapter of config.signals.adapters) {\n this._signalBus.register(adapter);\n this._registeredAdapters.push(adapter);\n }\n }\n }\n\n /**\n * Gets the filesystem adapter instance\n */\n get fs() {\n return this._fs;\n }\n\n /**\n * Gets the database interface instance\n */\n get db() {\n // Throw helpful error if database is accessed before initialization\n if (!this._db) {\n throw new Error(\n `Database accessed before initialization. ` +\n `Please call await instance.initialize() before accessing the database.`,\n );\n }\n return this._db;\n }\n\n /**\n * Temporarily bind this initialized instance to another database interface.\n *\n * This is intended for transaction-scoped work where a caller must ensure\n * that every nested SMRT read and write uses the transaction database passed\n * to its callback. The original database is restored whether the callback\n * succeeds or throws. Do not use the same instance concurrently while it is\n * temporarily bound.\n */\n async withDatabase<T>(\n db: DatabaseInterface,\n operation: (bound: this) => Promise<T>,\n ): Promise<T> {\n // Read through the public getter so an uninitialized instance fails with\n // the normal, actionable SmrtClass error before any state is mutated.\n const previousDb = this.db;\n const previousOptionDb = this.options.db;\n // `db` is usually a transaction handle of `previousDb`, which carries no\n // adapter markers; identify the root before swapping it out (#3737).\n noteNativeDuckDbHandle(previousDb, this._dbEngineHint);\n this._db = db;\n this.options.db = db;\n try {\n return await operation(this);\n } finally {\n this._db = previousDb;\n this.options.db = previousOptionDb;\n }\n }\n\n /**\n * Gets the AI client instance\n */\n get ai() {\n return this._ai;\n }\n\n /**\n * Get the in-memory AI usage snapshot for this instance.\n */\n getAiUsageSnapshot(): AiUsageSnapshot | undefined {\n return this._aiUsageCollector?.getSnapshot();\n }\n\n /**\n * Reset the in-memory AI usage collector.\n */\n resetAiUsage(): void {\n this._aiUsageCollector?.reset();\n }\n\n /**\n * List persisted AI usage records.\n */\n async listAiUsage(\n options: AiUsageListOptions = {},\n ): Promise<SmrtAiUsageRecord[]> {\n if (!this._db) {\n throw new Error(\n `AI usage requires a database configuration. ` +\n `Please call initialize() with a db option before querying usage.`,\n );\n }\n\n const { conditions, params } = buildAiUsageWhereClause(options);\n let paramIndex = params.length + 1;\n\n let sql = 'SELECT * FROM _smrt_ai_usage';\n if (conditions.length > 0) {\n sql += ` WHERE ${conditions.join(' AND ')}`;\n }\n\n sql += ` ORDER BY ${\n options.orderBy === 'timestamp ASC' ? 'created_at ASC' : 'created_at DESC'\n }`;\n\n if (options.limit !== undefined) {\n sql += ` LIMIT $${paramIndex++}`;\n params.push(options.limit);\n }\n\n if (options.offset !== undefined) {\n sql += ` OFFSET $${paramIndex++}`;\n params.push(options.offset);\n }\n\n const rows = getQueryRows(await this._db.query(sql, ...params));\n\n return rows.map((row) => ({\n id: String(row.id),\n provider: String(row.provider),\n model: String(row.model),\n operation: String(row.operation),\n usage: hydratePersistedAiUsageTokens(row),\n estimatedCost:\n row.estimated_cost === null || row.estimated_cost === undefined\n ? undefined\n : Number(row.estimated_cost),\n duration: toSafeInteger(row.duration ?? 0, 'AI usage duration'),\n className:\n row.class_name === null || row.class_name === undefined\n ? undefined\n : String(row.class_name),\n tenantId:\n row.tenant_id === undefined\n ? undefined\n : (row.tenant_id as string | null),\n tags: parseAiUsageTags(row.tags),\n timestamp: normalizeAiUsageTimestamp(row.created_at),\n }));\n }\n\n /**\n * Summarize persisted AI usage records by a grouping dimension.\n */\n async summarizeAiUsage(\n options: AiUsageSummaryOptions = {},\n ): Promise<Record<string, AiUsageStats>> {\n if (!this._db) {\n throw new Error(\n `AI usage requires a database configuration. ` +\n `Please call initialize() with a db option before querying usage.`,\n );\n }\n\n const groupBy = options.groupBy ?? 'model';\n const bucketExpression =\n groupBy === 'provider'\n ? `provider`\n : groupBy === 'model'\n ? `provider || ':' || model`\n : groupBy === 'class'\n ? `COALESCE(class_name, 'unknown')`\n : groupBy === 'tenant'\n ? `COALESCE(tenant_id, 'global')`\n : groupBy === 'operation'\n ? `operation`\n : `substr(CAST(created_at AS TEXT), 1, 10)`;\n\n const { conditions, params } = buildAiUsageWhereClause(options);\n\n let sql = `\n SELECT ${bucketExpression} AS bucket,\n COUNT(*) AS call_count,\n COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens,\n COALESCE(SUM(completion_tokens), 0) AS completion_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(duration), 0) AS total_duration,\n COALESCE(SUM(estimated_cost), 0) AS estimated_cost,\n MAX(created_at) AS last_used\n FROM _smrt_ai_usage\n `;\n\n if (conditions.length > 0) {\n sql += ` WHERE ${conditions.join(' AND ')}`;\n }\n\n sql += ' GROUP BY bucket ORDER BY bucket ASC';\n\n const rows = getQueryRows(await this._db.query(sql, ...params));\n const summary: Record<string, AiUsageStats> = {};\n\n for (const row of rows) {\n const bucket = String(row.bucket);\n summary[bucket] = {\n callCount: toSafeInteger(row.call_count ?? 0, 'AI usage call count'),\n promptTokens: toSafeInteger(\n row.prompt_tokens ?? 0,\n 'AI usage prompt-token total',\n ),\n completionTokens: toSafeInteger(\n row.completion_tokens ?? 0,\n 'AI usage completion-token total',\n ),\n totalTokens: toSafeInteger(\n row.total_tokens ?? 0,\n 'AI usage token total',\n ),\n totalDuration: toSafeInteger(\n row.total_duration ?? 0,\n 'AI usage duration total',\n ),\n estimatedCost: Number(row.estimated_cost ?? 0),\n lastUsed: row.last_used ? new Date(String(row.last_used)).getTime() : 0,\n };\n }\n\n return summary;\n }\n\n /**\n * Gets the signal bus instance\n *\n * @returns Signal bus if signals are enabled, undefined otherwise\n */\n get signalBus(): SignalBus | undefined {\n return this._signalBus;\n }\n\n /**\n * Cleanup method to prevent memory leaks\n *\n * Unregisters all adapters from the signal bus that were registered\n * by this instance. Call this when the SmrtClass instance is no longer\n * needed to prevent memory leaks.\n *\n * @example\n * ```typescript\n * const product = new Product({ name: 'Widget' });\n * await product.initialize();\n * // ... use product ...\n * product.destroy(); // Clean up when done\n * ```\n */\n destroy(): void {\n // Only unregister adapters if we own the bus (not shared)\n if (this._signalBus && !this.options.signals?.bus) {\n for (const adapter of this._registeredAdapters) {\n this._signalBus.unregister(adapter);\n }\n this._registeredAdapters = [];\n }\n\n // TODO: If SmrtClass grows a broader async teardown lifecycle, move\n // AI usage handler cleanup there alongside other connection-bound state.\n this._aiUsageCollector = undefined;\n this._aiUsageHandlers = [];\n }\n\n private mergeAiUsageConfig(\n globalConfig: GlobalSignalConfig,\n ): ResolvedAiUsageConfig {\n const globalUsage = globalConfig.usage ?? {};\n const instanceUsage = this.options.usage ?? {};\n\n return {\n enabled: instanceUsage.enabled ?? globalUsage.enabled ?? true,\n persist: instanceUsage.persist ?? globalUsage.persist ?? true,\n estimateCosts:\n instanceUsage.estimateCosts ?? globalUsage.estimateCosts ?? true,\n costRates: {\n ...(globalUsage.costRates ?? {}),\n ...(instanceUsage.costRates ?? {}),\n },\n handlers: [\n ...(globalUsage.handlers ?? []),\n ...(instanceUsage.handlers ?? []),\n ],\n };\n }\n\n private initializeAiUsageHandlers(config: ResolvedAiUsageConfig): void {\n this._aiUsageCollector = undefined;\n this._aiUsageHandlers = [];\n\n if (!config.enabled) {\n return;\n }\n\n this._aiUsageCollector = new AiUsageCollector();\n this._aiUsageHandlers.push(this._aiUsageCollector);\n\n if (config.persist && this._db) {\n this._aiUsageHandlers.push(new AiUsagePersistenceHandler(this._db));\n }\n\n this._aiUsageHandlers.push(...config.handlers);\n }\n\n private async handleAiUsageCallback(\n event: unknown,\n aiConfig: Record<string, unknown>,\n usageConfig: ResolvedAiUsageConfig,\n ): Promise<void> {\n if (!usageConfig.enabled || this._aiUsageHandlers.length === 0) {\n return;\n }\n\n const normalizedEvent = this.normalizeAiUsageEvent(event, aiConfig);\n if (!normalizedEvent) {\n return;\n }\n\n if (usageConfig.estimateCosts) {\n normalizedEvent.estimatedCost = estimateAiUsageCost(\n normalizedEvent.provider,\n normalizedEvent.model,\n normalizedEvent.usage,\n usageConfig.costRates,\n );\n }\n\n const results = await Promise.allSettled(\n this._aiUsageHandlers.map((handler) => handler.handle(normalizedEvent)),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logger.warn(\n `[smrt] AI usage handler failed for ${normalizedEvent.provider}:${normalizedEvent.model}: ${\n result.reason instanceof Error\n ? result.reason.message\n : String(result.reason)\n }`,\n );\n }\n }\n }\n\n private normalizeAiUsageEvent(\n event: unknown,\n aiConfig: Record<string, unknown>,\n ): SmrtAiUsageEvent | undefined {\n const raw = (event ?? {}) as Record<string, unknown>;\n const provider = firstString(\n raw.provider,\n raw.type,\n aiConfig.provider,\n aiConfig.type,\n );\n const model = firstString(\n raw.model,\n raw.defaultModel,\n aiConfig.model,\n aiConfig.defaultModel,\n );\n const operation =\n firstString(raw.operation, raw.kind, raw.method) ?? 'unknown';\n const usage =\n normalizeIncomingAiUsageTokens(raw.usage) ??\n normalizeIncomingAiUsageTokens(raw.tokenUsage) ??\n normalizeIncomingAiUsageTokens({\n promptTokens: raw.promptTokens,\n completionTokens: raw.completionTokens,\n totalTokens: raw.totalTokens,\n });\n\n if (!provider || !model) {\n return undefined;\n }\n\n const duration =\n firstNumber(raw.duration, raw.durationMs, raw.latency) ?? 0;\n const tenantId =\n 'tenantId' in this &&\n (this as { tenantId?: string | null }).tenantId !== undefined\n ? ((this as { tenantId?: string | null }).tenantId ?? null)\n : undefined;\n\n return {\n provider,\n model,\n operation,\n usage,\n duration,\n timestamp: normalizeAiUsageTimestamp(raw.timestamp),\n tags: normalizeAiUsageTags(raw.tags),\n className: this._className,\n tenantId,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAM,wCAAwC;AAE9C,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;AAmC7C,SAAS,YAAY,GAAG,YAA2C;CACjE,OAAO,WAAW,MAAM,cAAmC;EACzD,OAAO,OAAO,cAAc;CAC9B,CAAC;AACH;AAEA,SAAS,YAAY,GAAG,YAA2C;C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A;GACA;GACA,WAAW,0BAA0B,IAAI,SAAS;GAClD,MAAM,qBAAqB,IAAI,IAAI;GACnC,WAAW,KAAK;GAChB;EACF;CACF;AACF"}
1
+ {"version":3,"file":"class.js","names":[],"sources":["../src/class.ts"],"sourcesContent":["import type { AIClient, AIClientOptions } from '@happyvertical/ai';\nimport type {\n FilesystemAdapter,\n FilesystemAdapterOptions,\n} from '@happyvertical/files';\nimport { createLogger, type LoggerConfig } from '@happyvertical/logger';\nimport {\n type AIExplicitConfig,\n getAIConfigBlock,\n mergeAIConfigObjects,\n tryResolveAIProviderConfig,\n withAIAliases,\n} from '@happyvertical/smrt-config';\nimport type {\n AiTokenUsage,\n AiUsageHandler,\n AiUsageListOptions,\n AiUsageSnapshot,\n AiUsageStats,\n AiUsageSummaryOptions,\n SignalAdapter,\n SmrtAiUsageEvent,\n SmrtAiUsageRecord,\n} from '@happyvertical/smrt-types';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n AiUsageCollector,\n AiUsagePersistenceHandler,\n} from './adapters/ai-usage.js';\nimport { estimateAiUsageCost } from './adapters/cost-rates.js';\nimport { registerChangeFeedWriter } from './change-feed.js';\nimport {\n getSmrtModuleConfig,\n type SmrtGlobalConfig,\n} from './config/global-config.js';\nimport type {\n AIConfig,\n AiUsageConfig,\n GlobalSignalConfig,\n MetricsConfig,\n PubSubConfig,\n} from './config.js';\nimport { config } from './config.js';\nimport type { DatabaseConfig } from './database.js';\nimport {\n type DecisionClient,\n type DecisionConfig,\n type DecisionOptions,\n type DecisionRequest,\n type DecisionResult,\n executeDecision,\n} from './decisions.js';\nimport { createFilesystemAdapter } from './filesystem-loader.js';\nimport { getDatabase, importAI } from './host.js';\nimport { noteNativeDuckDbHandle } from './native-duckdb.js';\nimport { applyPostgresRuntimeTimeouts } from './postgres-timeouts.js';\nimport { detectEngine } from './schema/ddl/index.js';\nimport { SignalBus } from './signals/bus.js';\nimport { ensureSystemTables as ensureFrameworkSystemTables } from './system/bootstrap.js';\nimport {\n ensureDeferredSystemTableCompatibility,\n tableExists,\n} from './system/compatibility.js';\nimport { SMRT_SCHEMA_VERSION } from './system/schema.js';\nimport { toSafeInteger } from './utils/safe-integer.js';\n\n/**\n * `_smrt_migrations.version` suffix marking that the deferred (manifest-created)\n * system tables have been through their compatibility pass (issue #2376).\n */\nconst DEFERRED_COMPATIBILITY_VERSION_SUFFIX = '+deferred-compat';\n\nconst logger = createLogger({ level: 'info' });\n\ntype DatabaseWithConfig = DatabaseInterface & {\n config?: {\n type?: string;\n url?: string;\n };\n type?: string;\n};\n\ninterface ResolvedAiUsageConfig {\n enabled: boolean;\n persist: boolean;\n estimateCosts: boolean;\n costRates?: Record<string, { input: number; output: number }>;\n handlers: AiUsageHandler[];\n}\n\ntype AiUsageFilterOptions = Pick<\n AiUsageListOptions,\n | 'since'\n | 'until'\n | 'provider'\n | 'model'\n | 'operation'\n | 'className'\n | 'tenantId'\n>;\n\ninterface AiUsageWhereClause {\n conditions: string[];\n params: unknown[];\n nextParamIndex: number;\n}\n\nfunction firstString(...candidates: unknown[]): string | undefined {\n return candidates.find((candidate): candidate is string => {\n return typeof candidate === 'string';\n });\n}\n\nfunction firstNumber(...candidates: unknown[]): number | undefined {\n return candidates.find((candidate): candidate is number => {\n return typeof candidate === 'number';\n });\n}\n\nfunction getDatabaseUrl(db: DatabaseInterface): string {\n const dbWithConfig = db as DatabaseWithConfig;\n return db.url || dbWithConfig.config?.url || '';\n}\n\nfunction getDatabaseTypeHint(\n config: DatabaseConfig | undefined,\n): string | undefined {\n if (!config || typeof config === 'string') {\n return undefined;\n }\n\n const configWithType = config as DatabaseWithConfig & {\n client?: unknown;\n };\n\n if (typeof configWithType.type === 'string') {\n return configWithType.type;\n }\n\n if (typeof configWithType.config?.type === 'string') {\n return configWithType.config.type;\n }\n\n if ('query' in configWithType && typeof configWithType.query === 'function') {\n return undefined;\n }\n\n if ('client' in configWithType && configWithType.client) {\n return 'postgres';\n }\n\n return undefined;\n}\n\nfunction normalizeIncomingAiUsageTokens(\n value: unknown,\n): AiTokenUsage | undefined {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n\n const usage = value as Record<string, unknown>;\n const promptTokens =\n typeof usage.promptTokens === 'number'\n ? usage.promptTokens\n : typeof usage.inputTokens === 'number'\n ? usage.inputTokens\n : undefined;\n const completionTokens =\n typeof usage.completionTokens === 'number'\n ? usage.completionTokens\n : typeof usage.outputTokens === 'number'\n ? usage.outputTokens\n : undefined;\n const totalTokens =\n typeof usage.totalTokens === 'number'\n ? usage.totalTokens\n : promptTokens !== undefined || completionTokens !== undefined\n ? (promptTokens ?? 0) + (completionTokens ?? 0)\n : undefined;\n\n if (\n promptTokens === undefined &&\n completionTokens === undefined &&\n totalTokens === undefined\n ) {\n return undefined;\n }\n\n return {\n promptTokens,\n completionTokens,\n totalTokens,\n };\n}\n\nfunction hydratePersistedAiUsageTokens(row: {\n prompt_tokens?: unknown;\n completion_tokens?: unknown;\n total_tokens?: unknown;\n}): AiTokenUsage | undefined {\n const promptTokens =\n row.prompt_tokens === null || row.prompt_tokens === undefined\n ? undefined\n : toSafeInteger(row.prompt_tokens, 'AI usage prompt tokens');\n const completionTokens =\n row.completion_tokens === null || row.completion_tokens === undefined\n ? undefined\n : toSafeInteger(row.completion_tokens, 'AI usage completion tokens');\n const totalTokens =\n row.total_tokens === null || row.total_tokens === undefined\n ? undefined\n : toSafeInteger(row.total_tokens, 'AI usage total tokens');\n\n if (\n promptTokens === undefined &&\n completionTokens === undefined &&\n totalTokens === undefined\n ) {\n return undefined;\n }\n\n return {\n promptTokens,\n completionTokens,\n totalTokens,\n };\n}\n\nfunction normalizeAiUsageTags(\n value: unknown,\n): Record<string, string> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return undefined;\n }\n\n const tags: Record<string, string> = {};\n for (const [key, tagValue] of Object.entries(value)) {\n if (tagValue === undefined || tagValue === null) continue;\n tags[key] = String(tagValue);\n }\n\n return Object.keys(tags).length > 0 ? tags : undefined;\n}\n\nfunction parseAiUsageTags(value: unknown): Record<string, string> | undefined {\n if (typeof value !== 'string') {\n return undefined;\n }\n\n try {\n return normalizeAiUsageTags(JSON.parse(value));\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeAiUsageTimestamp(value: unknown): Date {\n if (value instanceof Date) {\n return value;\n }\n\n if (typeof value === 'string' || typeof value === 'number') {\n const date = new Date(value);\n if (!Number.isNaN(date.getTime())) {\n return date;\n }\n }\n\n return new Date();\n}\n\nfunction getQueryRows(\n result: Awaited<ReturnType<DatabaseInterface['query']>>,\n): Record<string, unknown>[] {\n return Array.isArray(result)\n ? (result as Record<string, unknown>[])\n : ((result as { rows?: Record<string, unknown>[] }).rows ?? []);\n}\n\nfunction buildAiUsageWhereClause(\n options: AiUsageFilterOptions,\n): AiUsageWhereClause {\n const conditions: string[] = [];\n const params: unknown[] = [];\n let nextParamIndex = 1;\n\n if (options.since) {\n conditions.push(`created_at >= $${nextParamIndex++}`);\n params.push(options.since.toISOString());\n }\n\n if (options.until) {\n conditions.push(`created_at <= $${nextParamIndex++}`);\n params.push(options.until.toISOString());\n }\n\n if (options.provider) {\n conditions.push(`provider = $${nextParamIndex++}`);\n params.push(options.provider);\n }\n\n if (options.model) {\n conditions.push(`model = $${nextParamIndex++}`);\n params.push(options.model);\n }\n\n if (options.operation) {\n conditions.push(`operation = $${nextParamIndex++}`);\n params.push(options.operation);\n }\n\n if (options.className) {\n conditions.push(`class_name = $${nextParamIndex++}`);\n params.push(options.className);\n }\n\n if (options.tenantId === null) {\n conditions.push(`tenant_id IS NULL`);\n } else if (options.tenantId) {\n conditions.push(`tenant_id = $${nextParamIndex++}`);\n params.push(options.tenantId);\n }\n\n return {\n conditions,\n params,\n nextParamIndex,\n };\n}\n\n/**\n * Configuration options for the SmrtClass\n */\nexport interface SmrtClassOptions {\n /**\n * Optional custom class name override\n */\n _className?: string;\n\n /**\n * Database configuration - unified approach matching @happyvertical/sql\n *\n * Supports three formats:\n * - String shortcut: 'products.db' (auto-detects database type)\n * - Config object: { type: 'sqlite', url: 'products.db' }\n * - DatabaseInterface instance: await getDatabase(...)\n *\n * @see DatabaseConfig for type definition\n */\n db?: DatabaseConfig;\n\n /**\n * Alias for db option - for backward compatibility with documentation\n *\n * @deprecated Use 'db' instead. This alias exists for backward compatibility.\n */\n persistence?: DatabaseConfig;\n\n /**\n * Filesystem adapter configuration options\n */\n fs?: FilesystemAdapterOptions;\n\n /**\n * AI client configuration options or instance\n */\n ai?: AIClientOptions | AIClient;\n\n /**\n * Optional typed-decision provider or already-built decision-capable client.\n * It is independent from `ai`, which remains the generation client.\n */\n decisions?: DecisionConfig | DecisionClient;\n\n /**\n * AI usage tracking configuration (overrides global defaults)\n */\n usage?: AiUsageConfig;\n\n /**\n * Logging configuration (overrides global default)\n */\n logging?: LoggerConfig;\n\n /**\n * Metrics configuration (overrides global default)\n */\n metrics?: MetricsConfig;\n\n /**\n * Pub/Sub configuration (overrides global default)\n */\n pubsub?: PubSubConfig;\n\n /**\n * Sanitization configuration (overrides global default)\n */\n sanitization?: import('./config.js').GlobalSignalConfig['sanitization'];\n\n /**\n * Custom signal configuration (overrides global default)\n */\n signals?: {\n /** Shared signal bus instance */\n bus?: SignalBus;\n /** Additional custom adapters */\n adapters?: SignalAdapter[];\n };\n\n /**\n * Internal flag to reuse an already initialized DatabaseInterface instance.\n *\n * Skips database resolution and system-table setup during lightweight hydration.\n * @internal\n */\n _reuseInitializedDb?: boolean;\n\n /**\n * Internal flag to defer runtime-only services such as signals and AI setup.\n *\n * Lightweight hydration paths set this so plain query reads avoid per-row\n * runtime bootstrap costs.\n * @internal\n */\n _deferRuntimeInitialization?: boolean;\n}\n\n/**\n * Foundation class providing core functionality for the SMRT framework\n *\n * SmrtClass provides unified access to database, filesystem, and AI client\n * interfaces. It serves as the foundation for all other classes in the\n * SMRT framework.\n */\nexport class SmrtClass {\n /**\n * AI client instance for interacting with AI models\n */\n protected _ai!: AIClient;\n\n /** Optional, independently initialized typed-decision client. */\n protected _decisionClient?: DecisionClient;\n\n private _decisionClientInitPromise?: Promise<DecisionClient | undefined>;\n\n /**\n * Filesystem adapter for file operations\n */\n protected _fs!: FilesystemAdapter;\n\n /**\n * Database interface for data persistence\n */\n protected _db!: DatabaseInterface;\n private _dbEngineHint?: string;\n\n /**\n * Class name used for identification\n */\n protected _className!: string;\n\n /**\n * Signal bus for method execution tracking\n */\n protected _signalBus?: SignalBus;\n\n /**\n * Adapters registered by this instance (for cleanup)\n */\n private _registeredAdapters: SignalAdapter[] = [];\n\n /**\n * In-memory AI usage collector for quick inspection.\n */\n private _aiUsageCollector?: AiUsageCollector;\n\n /**\n * Registered AI usage handlers for this instance.\n */\n private _aiUsageHandlers: AiUsageHandler[] = [];\n\n /**\n * Tracks whether optional runtime services (signals, AI, fs) are ready.\n */\n private _runtimeServicesInitialized = false;\n\n /**\n * Shared in-flight runtime initialization promise for single-flight setup.\n */\n private _runtimeServicesInitPromise?: Promise<void>;\n\n /**\n * Configuration options provided to the class\n */\n public options: SmrtClassOptions;\n\n /**\n * Track which databases have had system tables initialized\n * - WeakSet for :memory: databases (URL not unique, track by instance)\n * - Set<string> for all others (URL is unique identifier)\n */\n private static _systemTablesInitialized = new WeakSet<DatabaseInterface>();\n private static _systemTablesInitializedByUrl = new Set<string>();\n private static _systemTablesInitializing = new WeakMap<\n DatabaseInterface,\n Promise<void>\n >();\n\n /**\n * Creates a new SmrtClass instance\n *\n * @param options - Configuration options for database, filesystem, and AI clients\n */\n constructor(options: SmrtClassOptions = {}) {\n this.options = options;\n this._className = this.constructor.name;\n }\n\n /**\n * Determines whether this class requires a database to function\n *\n * Override this method in subclasses that require database access\n * to enable early validation during initialization.\n *\n * @returns True if database is required, false otherwise\n * @example\n * ```typescript\n * class MyDataModel extends SmrtClass {\n * protected requiresDatabase(): boolean {\n * return true; // This class needs database access\n * }\n * }\n * ```\n */\n protected requiresDatabase(): boolean {\n return false; // Base class doesn't require database by default\n }\n\n /**\n * Initializes database, filesystem, and AI client connections\n *\n * This method sets up all required services based on the provided options.\n * It should be called before using any of the service interfaces.\n *\n * @returns Promise that resolves to this instance for chaining\n * @throws {Error} If database is required but not provided in options\n */\n protected async initialize(): Promise<this> {\n await this.initializeCoreResources();\n\n if (!this.options._deferRuntimeInitialization) {\n await this.initializeRuntimeServices();\n }\n\n return this;\n }\n\n /**\n * Initialize core resources required for ORM behavior.\n *\n * This setup is shared by both full runtime initialization and lightweight\n * query hydration. Hydrated objects reuse an existing DB connection and skip\n * repeated system-table checks.\n */\n protected async initializeCoreResources(): Promise<void> {\n // Framework init hook for the change feed (#1758): make sure the writer\n // interceptor observes every save/delete before any instance can write.\n // Idempotent and cheap when already registered.\n registerChangeFeedWriter();\n\n // Map persistence to db for backward compatibility\n if (this.options.persistence && !this.options.db) {\n this.options.db = this.options.persistence;\n }\n\n // Validate database configuration if required\n if (this.requiresDatabase() && !this.options.db) {\n throw new Error(\n `${this._className} requires a database configuration. ` +\n `Please provide 'db' in options: { db: { url: '...' } } or { db: 'database.db' }`,\n );\n }\n\n if (this.options.db) {\n this._dbEngineHint = getDatabaseTypeHint(this.options.db);\n\n if (\n this.options._reuseInitializedDb &&\n typeof this.options.db === 'object' &&\n 'query' in this.options.db\n ) {\n this._db = this.options.db as DatabaseInterface;\n this.options.db = this._db;\n noteNativeDuckDbHandle(this._db, this._dbEngineHint);\n } else {\n // Handle four db config formats (in implementation order):\n // 1. String URL: 'products.db' (shortcut)\n // 2. DatabaseInterface instance: already initialized db (has 'query' method)\n // 3. Config with client: { type: 'postgres', client: pgPool } (SvelteKit pattern)\n // 4. Config object: { type: 'sqlite', url: 'products.db' }\n if (typeof this.options.db === 'string') {\n // Format 1: String shortcut - let getDatabase auto-detect type from URL\n // Preserve connection sharing for file-backed databases while leaving\n // true in-memory databases isolated per instance.\n const isMemoryDb = this.options.db === ':memory:';\n // PostgreSQL URLs pick up the runtime timeout bounds, and the dbid is\n // derived from the bounded URL so the same rewrite at every call site\n // still resolves to one shared pool (#2377).\n const bounded = applyPostgresRuntimeTimeouts({\n url: this.options.db,\n });\n this._db = await getDatabase({\n ...bounded,\n ...(isMemoryDb ? {} : { dbid: `smrt:${bounded.url}` }),\n } as unknown as Parameters<typeof getDatabase>[0]);\n } else if ('query' in this.options.db) {\n // Format 2: Already a DatabaseInterface instance - return as-is\n this._db = this.options.db as DatabaseInterface;\n } else if ('client' in this.options.db && this.options.db.client) {\n // Format 3: Config with pre-created client (e.g., from SvelteKit's $env-based connection)\n // Pass the client to getDatabase which will use it instead of creating a new connection\n const dbConfig = this.options.db as {\n type?: string;\n client: unknown;\n url?: string;\n };\n // `client` is a runtime-only property the postgres adapter reads\n // but the public `getDatabase` option union does not model, so the\n // literal is routed through the function's own parameter type.\n this._db = await getDatabase({\n type: dbConfig.type || 'postgres',\n client: dbConfig.client,\n url: dbConfig.url,\n } as unknown as Parameters<typeof getDatabase>[0]);\n } else {\n // Format 4: Config object - pass to getDatabase (handles all types uniformly)\n // Preserve connection sharing for file-backed databases while leaving\n // true in-memory databases isolated per instance.\n const dbConfig = this.options.db as { url?: string; type?: string };\n const dbUrl = dbConfig.url || 'memory';\n const isMemoryDb = dbUrl === ':memory:' || dbUrl === 'memory';\n // Keep the config's own key set: an object with no `url` must stay\n // that way so the adapter applies its own default (#2377).\n const bounded = applyPostgresRuntimeTimeouts({ ...this.options.db });\n // The loose config-object variant of `DatabaseConfig` carries an\n // index signature that the closed `getDatabase` option union does\n // not accept structurally, so route through its parameter type.\n this._db = await getDatabase({\n ...bounded,\n ...(isMemoryDb ? {} : { dbid: `smrt:${bounded.url ?? dbUrl}` }),\n } as unknown as Parameters<typeof getDatabase>[0]);\n }\n\n /**\n * INTENTIONAL MUTATION: After resolving the database config,\n * we replace options.db with the actual DatabaseInterface instance.\n * This enables child objects to share the same connection via:\n *\n * const child = new ChildObject({ db: parent.options.db });\n *\n * Without this, passing this.options to getCollection() would use the config object\n * which causes a NEW db instance to be created, losing data isolation.\n *\n * See issue #567 for context on why this pattern is necessary.\n */\n this.options.db = this._db;\n // Identify a native DuckDB root now, so transaction handles later\n // bound to this object resolve to the same engine (#3737).\n noteNativeDuckDbHandle(this._db, this._dbEngineHint);\n\n await this.ensureSystemTables();\n }\n }\n }\n\n /**\n * Initialize optional runtime services that are not required for plain ORM reads.\n */\n protected async initializeRuntimeServices(): Promise<void> {\n if (this._runtimeServicesInitialized) {\n return;\n }\n\n if (!this._runtimeServicesInitPromise) {\n this._runtimeServicesInitPromise = (async () => {\n if (this.options.fs && !this._fs) {\n // Acquired through the boundary in filesystem-loader.ts so the\n // @happyvertical/files SDK (S3/googleapis) never enters\n // provider-neutral consumer bundles (#1977/#1979).\n this._fs = await createFilesystemAdapter(this.options.fs);\n }\n\n // Initialize AI client with environment variable support\n // Priority: instance options > env vars > global config > defaults\n const globalConfig = config.toJSON();\n const usageConfig = this.mergeAiUsageConfig(globalConfig);\n this.initializeAiUsageHandlers(usageConfig);\n\n // The smrt.config.ts `ai` block (resolved through smrt-config's shared\n // resolver) is the lowest-priority declared source, above SMRT_AI_*.\n // Only a block that names a provider counts: a partial block (model,\n // baseUrl or apiKeyEnv alone) behaves exactly like an absent block.\n const declaredBlock = getAIConfigBlock();\n const aiConfigBlock = declaredBlock?.provider ? declaredBlock : null;\n if (\n !this._ai &&\n (this.options.ai ||\n globalConfig.ai ||\n aiConfigBlock ||\n process.env.SMRT_AI_PROVIDER)\n ) {\n // Check if options.ai is already a client-like object with embed method\n // This allows passing mock AI clients for testing\n const aiOption = this.options.ai as\n | Record<string, unknown>\n | undefined;\n if (\n aiOption &&\n typeof aiOption === 'object' &&\n typeof aiOption.embed === 'function' &&\n !aiOption.provider\n ) {\n this._ai = aiOption as unknown as AIClient;\n } else {\n // Passthrough tuning fields (timeout, maxRetries, ...) still come\n // from `SMRT_AI_*` via loadEnvConfig. Provider/key/model selection\n // goes through the shared smrt-config resolver below (#3372).\n const { loadEnvConfig } = await import('@happyvertical/utils');\n\n // Start with global defaults\n const baseConfig = globalConfig.ai || {};\n\n // Merge with instance options (takes priority over global)\n // Provider ownership holds across these two layers too: the shared\n // canonicalising merge folds provider/type and model/defaultModel,\n // and drops the global layer's provider, key, base URL and model\n // when the instance options name a different provider.\n const userConfig = mergeAIConfigObjects(\n baseConfig,\n this.options.ai,\n );\n\n // Load environment variables and merge (user options take priority).\n // `AIConfig` carries an index signature, so provider-specific keys\n // (`type`, `onUsage`, `defaultModel`, …) read back as `unknown`.\n const aiConfig = loadEnvConfig<AIConfig>(userConfig, {\n packageName: 'ai',\n prefix: 'SMRT',\n schema: {\n provider: 'string',\n model: 'string',\n apiKey: 'string',\n timeout: 'number',\n maxRetries: 'number',\n temperature: 'number',\n maxTokens: 'number',\n },\n });\n\n // Provider, key, base URL and model always come from the shared\n // resolver's bound result (options.ai > core global config >\n // smrt.config `ai` block > SMRT_AI_*), so a credential is only ever\n // sent to the provider its own source named; env-loaded values are\n // replaced, not merged. Tuning fields keep their current source.\n // Without a block the provider's own key variable is not consulted\n // (no behaviour change for apps that never declared one).\n const resolvedAi = tryResolveAIProviderConfig({\n explicit: userConfig as AIExplicitConfig,\n config: aiConfigBlock,\n prefixes: ['SMRT_AI'],\n autoDetect: false,\n requireProvider: false,\n providerKeyEnvFallback: Boolean(aiConfigBlock),\n });\n // Replace (never merge) the identity/credential fields with the\n // resolver's bound result, then set both client-facing aliases so\n // no stale `type` / `defaultModel` reaches getAI().\n const bound: Record<string, unknown> = {\n provider: resolvedAi?.provider,\n apiKey: resolvedAi?.apiKey,\n baseUrl: resolvedAi?.baseUrl,\n model: resolvedAi?.model,\n };\n for (const key of [\n 'provider',\n 'type',\n 'apiKey',\n 'baseUrl',\n 'model',\n 'defaultModel',\n ]) {\n delete (aiConfig as Record<string, unknown>)[key];\n }\n for (const [key, value] of Object.entries(bound)) {\n if (value) (aiConfig as Record<string, unknown>)[key] = value;\n }\n Object.assign(\n aiConfig,\n withAIAliases(aiConfig as Record<string, unknown>),\n );\n\n const existingOnUsage =\n aiConfig.onUsage ??\n (userConfig as Record<string, unknown>).onUsage ??\n undefined;\n aiConfig.onUsage = async (event: unknown) => {\n if (typeof existingOnUsage === 'function') {\n await (existingOnUsage as (usageEvent: unknown) => unknown)(\n event,\n );\n }\n await this.handleAiUsageCallback(event, aiConfig, usageConfig);\n };\n\n // Only initialize if we have a provider configured\n if (aiConfig.provider || aiConfig.type || aiConfig.apiKey) {\n // Use the getAI() factory (loaded lazily to keep the\n // `@happyvertical/ai` module graph off smrt-core's cold-start\n // import path — see issue #2894) to support all AI providers\n // (OpenAI, Anthropic, Gemini, etc.). getAI() returns\n // AIInterface, which we narrow to AIClient for backward\n // compatibility. The index-signature `AIConfig` is routed\n // through getAI's own parameter type rather than the closed\n // union.\n const { getAI } = await importAI();\n this._ai = (await getAI(\n aiConfig as unknown as Parameters<typeof getAI>[0],\n )) as unknown as AIClient;\n }\n }\n }\n\n await this.initializeSignals();\n this._runtimeServicesInitialized = true;\n })();\n }\n\n try {\n await this._runtimeServicesInitPromise;\n } finally {\n this._runtimeServicesInitPromise = undefined;\n }\n }\n\n /**\n * Ensure deferred runtime services are ready before using them.\n */\n protected async ensureRuntimeServicesInitialized(): Promise<void> {\n if (!this._runtimeServicesInitialized) {\n await this.initializeRuntimeServices();\n }\n }\n\n /**\n * Resolve the AI client, initializing deferred runtime services on demand.\n */\n protected async getAiClient(): Promise<AIClient> {\n await this.ensureRuntimeServicesInitialized();\n\n if (!this._ai) {\n throw new Error(\n `${this._className} does not have an AI client configured. ` +\n `Provide 'ai' in options or configure a global SMRT AI provider.`,\n );\n }\n\n return this._ai;\n }\n\n /**\n * Resolve the AI client if one is configured, otherwise return undefined.\n */\n protected async getOptionalAiClient(): Promise<AIClient | undefined> {\n await this.ensureRuntimeServicesInitialized();\n return this._ai;\n }\n\n /**\n * Resolve the optional typed-decision client without changing the generation\n * client used by `is()`, `do()`, or `describe()`. The SDK import stays inside\n * this opt-in path so ordinary SMRT applications neither load nor configure\n * the decision provider.\n */\n protected async getDecisionClient(): Promise<DecisionClient | undefined> {\n await this.ensureRuntimeServicesInitialized();\n\n if (this._decisionClient) return this._decisionClient;\n if (this._decisionClientInitPromise) {\n return this._decisionClientInitPromise;\n }\n\n this._decisionClientInitPromise = (async () => {\n const instanceDecision = this.options.decisions;\n if (\n instanceDecision &&\n typeof instanceDecision === 'object' &&\n typeof (instanceDecision as DecisionClient).decide === 'function'\n ) {\n this._decisionClient = instanceDecision as DecisionClient;\n return this._decisionClient;\n }\n\n const configuredDecision = this.getDecisionConfig();\n if (!configuredDecision) return undefined;\n if (configuredDecision.type !== 'typesafe') {\n throw new Error(\"Decision configuration requires type: 'typesafe'.\");\n }\n\n // `getAI()` is deliberately dynamically imported, matching the existing\n // generation setup. The #1284 SDK adds `decide` as an optional interface\n // capability, so third-party/older clients remain source-compatible.\n const { getAI } = await importAI();\n this._decisionClient = (await getAI(\n configuredDecision as Parameters<typeof getAI>[0],\n )) as unknown as DecisionClient;\n return this._decisionClient;\n })();\n\n try {\n return await this._decisionClientInitPromise;\n } finally {\n this._decisionClientInitPromise = undefined;\n }\n }\n\n /**\n * Attempt one typed decision batch against caller-curated state.\n *\n * `undefined` is the explicit legacy-route signal: no decision client was\n * configured. Configured capability, provider, and response errors always\n * propagate. Object methods with registered tools must retain their\n * generation route and therefore do not call this helper.\n */\n protected async attemptDecision(\n request: DecisionRequest,\n options?: DecisionOptions,\n ): Promise<DecisionResult | undefined> {\n const decision = await this.getDecisionClient();\n if (!decision) return undefined;\n\n const result = await executeDecision(decision, request, options);\n await this.recordAiUsageEvent(\n {\n provider: result.provenance.provider,\n model: result.provenance.model,\n operation: 'decision',\n usage: result.usage,\n tags: { operation: 'decision' },\n },\n result.provenance,\n );\n return result;\n }\n\n /** Resolve project, global, and instance decision options in that order. */\n protected getDecisionConfig(): DecisionConfig | undefined {\n const instanceDecision = this.options.decisions;\n const instanceConfig =\n instanceDecision &&\n typeof instanceDecision === 'object' &&\n typeof (instanceDecision as DecisionClient).decide !== 'function'\n ? (instanceDecision as Partial<DecisionConfig>)\n : undefined;\n const projectDecision = getSmrtModuleConfig<SmrtGlobalConfig>('smrt', {})\n .decisions as Partial<DecisionConfig> | undefined;\n const globalDecision = config.toJSON().decisions as\n | Partial<DecisionConfig>\n | undefined;\n const resolved = {\n ...projectDecision,\n ...globalDecision,\n ...instanceConfig,\n } as Partial<DecisionConfig>;\n return Object.keys(resolved).length === 0\n ? undefined\n : (resolved as DecisionConfig);\n }\n\n /**\n * Records an SDK operation through SMRT's established usage handlers. The\n * event carries provider/model/tokens only; prompts, object data, and secrets\n * never enter usage persistence or callbacks.\n */\n protected async recordAiUsageEvent(\n event: unknown,\n providerConfig: Record<string, unknown>,\n ): Promise<void> {\n await this.ensureRuntimeServicesInitialized();\n await this.handleAiUsageCallback(\n event,\n providerConfig,\n this.mergeAiUsageConfig(config.toJSON()),\n );\n }\n\n private async isSystemSchemaVersionApplied(\n db: DatabaseInterface,\n version: string,\n ): Promise<boolean> {\n const engine = detectEngine(getDatabaseUrl(db), this._dbEngineHint);\n\n if (\n engine === 'postgres' &&\n !(await tableExists(db, '_smrt_migrations', this._dbEngineHint))\n ) {\n return false;\n }\n\n try {\n const versionParam = engine === 'postgres' ? '$1' : '?';\n const rows = await db.query(\n `SELECT 1 FROM _smrt_migrations WHERE version = ${versionParam} LIMIT 1`,\n version,\n );\n return getQueryRows(rows).length > 0;\n } catch (error) {\n if (engine === 'postgres') {\n throw error;\n }\n\n return false;\n }\n }\n\n /**\n * Ensure SMRT system tables exist in the database\n *\n * System tables use the _smrt_ prefix and store framework metadata:\n * - _smrt_contexts: Context memory storage for remembered patterns\n * - _smrt_migrations: Schema version tracking\n * - _smrt_schema_migrations / _smrt_backfills: Migration and backfill ledgers\n * - _smrt_embeddings: Embedding vectors for semantic search\n * - _smrt_dispatch / _smrt_dispatch_subscriptions: Inter-agent dispatch queue\n * - _smrt_ai_usage: AI usage telemetry\n * - _smrt_changes: Append-only change feed\n *\n * Note that the _smrt_ prefix alone does NOT mean \"system table\" — ~25\n * `@smrt()` domain tables (feature flags, prompt overrides, subscription\n * plans, …) carry it too and are created by `db:migrate`, not here. The\n * framework's own list is `SYSTEM_TABLE_NAMES` in\n * `schema/system-table-shapes.ts`, derived from this DDL.\n *\n * This method is idempotent and safe to call multiple times.\n * Tables are only created once per database connection.\n */\n private async ensureSystemTables(): Promise<void> {\n if (!this._db) return;\n\n const dbUrl = getDatabaseUrl(this._db);\n\n // Some databases share URLs but are different instances:\n // - :memory: databases (SQLite/DuckDB in-memory)\n // - JSON databases (may have undefined or shared URLs)\n // - Any database with undefined URL\n // Use WeakSet for instance tracking, Set<string> for URL tracking\n const dbConstructorName = this._db.constructor?.name || '';\n const isMemoryDb = dbUrl === ':memory:';\n const isJsonDb = dbConstructorName.toLowerCase().includes('json');\n const hasUndefinedUrl = !dbUrl;\n const useInstanceTracking = isMemoryDb || isJsonDb || hasUndefinedUrl;\n\n if (useInstanceTracking) {\n // Check WeakSet for databases that may share URLs (track by instance)\n if (SmrtClass._systemTablesInitialized.has(this._db)) {\n return;\n }\n } else {\n // Check Set<string> for URL-based databases (track by URL)\n if (SmrtClass._systemTablesInitializedByUrl.has(dbUrl)) {\n return;\n }\n }\n\n const db = this._db;\n const pending = SmrtClass._systemTablesInitializing.get(db);\n if (pending) return pending;\n\n // Share only an actual handle: another handle at the same URL may need\n // to wait for this caller's outer transaction to commit, not just for its\n // initialization statements. Database locks coordinate those handles.\n const initialization = (async () => {\n try {\n await ensureFrameworkSystemTables(db, this._dbEngineHint);\n await this.settleDeferredSystemTableCompatibility(db);\n await this.ensureNativeVectorStorage();\n\n if (useInstanceTracking) {\n SmrtClass._systemTablesInitialized.add(db);\n } else {\n SmrtClass._systemTablesInitializedByUrl.add(dbUrl);\n }\n } catch (error) {\n const dbInfo = db.constructor?.name || 'unknown database';\n throw new Error(\n `Failed to create system tables for ${dbInfo}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n })();\n SmrtClass._systemTablesInitializing.set(db, initialization);\n try {\n await initialization;\n } finally {\n SmrtClass._systemTablesInitializing.delete(db);\n }\n }\n\n /**\n * Run the compatibility pass for the system tables `db:migrate` creates, then\n * stamp its own marker in `_smrt_migrations` (issue #2376).\n *\n * Deliberately runs OUTSIDE the bootstrap lock/transaction, and deliberately\n * cannot fail startup:\n *\n * - `_smrt_jobs` / `_smrt_job_events` are created by `db:migrate` from the\n * jobs manifest, which on a fresh install runs AFTER the framework's first\n * bootstrap. Gating this pass on {@link SMRT_SCHEMA_VERSION} would mean the\n * version gets stamped while the tables are still absent and the pass never\n * runs on that database again. It therefore carries its own marker, which\n * is written only once every deferred table exists and has been upgraded.\n * - Its statements are ALTER TABLE / CREATE INDEX against tables the\n * framework does not own. Inside the PostgreSQL bootstrap transaction one\n * failure (a permissions problem, say) would abort the transaction and roll\n * back system-table creation with it. Outside, a failure is a logged\n * warning and the next process start retries — the pass is idempotent and\n * already tolerates concurrent creators.\n *\n * Until the tables exist this costs two catalog probes per process per\n * database; afterwards the marker short-circuits it.\n */\n private async settleDeferredSystemTableCompatibility(\n db: DatabaseInterface,\n ): Promise<void> {\n const marker = `${SMRT_SCHEMA_VERSION}${DEFERRED_COMPATIBILITY_VERSION_SUFFIX}`;\n\n try {\n if (await this.isSystemSchemaVersionApplied(db, marker)) {\n return;\n }\n\n const { settled } = await ensureDeferredSystemTableCompatibility(\n db,\n this._dbEngineHint,\n );\n if (!settled) {\n return;\n }\n\n const id = crypto.randomUUID();\n const description = 'Deferred SMRT system table compatibility';\n await db.execute`\n INSERT INTO _smrt_migrations (id, version, description)\n VALUES (${id}, ${marker}, ${description})\n ON CONFLICT(version) DO NOTHING\n `;\n } catch (error) {\n logger.warn(\n `[smrt] Deferred system table compatibility did not complete; retrying on the next start: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n\n private async ensureNativeVectorStorage(): Promise<void> {\n if (!this._db) {\n return;\n }\n\n try {\n const { ObjectRegistry } = await import('./registry.js');\n const embeddingConfig = ObjectRegistry.getProjectEmbeddingConfig();\n if (embeddingConfig?.storage === 'native') {\n const { EmbeddingStorage } = await import('./embeddings/storage.js');\n const vector = this._db.vector;\n if (vector) {\n const dimensions = embeddingConfig.dimensions || 768;\n await EmbeddingStorage.ensureVectorStorage(\n this._db,\n dimensions,\n vector,\n );\n } else {\n logger.warn(\n '[smrt] Embedding storage set to \"native\" but database has no vector capability. Falling back to JSON storage.',\n );\n }\n }\n } catch (error) {\n // Don't fail system table initialization for vector setup errors\n logger.warn(\n `[smrt] Failed to initialize vector storage: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /**\n * Access system tables through standard database interface\n * System tables use _smrt_ prefix to avoid conflicts with user tables\n */\n protected get systemDb(): DatabaseInterface {\n return this._db;\n }\n\n /**\n * Return the database engine hint captured from the caller's configuration.\n * Adapters may not expose their original type after construction (notably\n * in-memory DuckDB/JSON connections), so query helpers can combine this\n * hint with their public connection capabilities.\n */\n protected getDatabaseEngineHint(): string | undefined {\n return this._dbEngineHint;\n }\n\n /**\n * Initialize signal bus and adapters\n *\n * Merges global configuration with instance-specific overrides.\n * Registers built-in and custom adapters based on configuration.\n */\n private async initializeSignals(): Promise<void> {\n const globalConfig = config.toJSON();\n const effectiveConfig = this.mergeSignalConfig(globalConfig);\n\n // If a shared bus is provided, always use it (don't create new adapters)\n if (this.options.signals?.bus) {\n this._signalBus = this.options.signals.bus;\n return;\n }\n\n // Otherwise, check if we should initialize signals based on config\n if (!this.shouldInitializeSignals(effectiveConfig)) {\n return;\n }\n\n this._signalBus = new SignalBus({\n sanitization: effectiveConfig.sanitization,\n });\n await this.registerAdapters(effectiveConfig);\n }\n\n /**\n * Merge global and instance signal configuration\n *\n * Instance configuration takes priority over global defaults.\n *\n * @param globalConfig - Global configuration from smrt.configure()\n * @returns Merged configuration\n */\n private mergeSignalConfig(\n globalConfig: GlobalSignalConfig,\n ): GlobalSignalConfig {\n return {\n logging: this.options.logging ?? globalConfig.logging,\n metrics: this.options.metrics ?? globalConfig.metrics,\n pubsub: this.options.pubsub ?? globalConfig.pubsub,\n usage: this.mergeAiUsageConfig(globalConfig),\n sanitization: this.options.sanitization ?? globalConfig.sanitization,\n signals: {\n bus: this.options.signals?.bus ?? globalConfig.signals?.bus,\n adapters: [\n ...(globalConfig.signals?.adapters ?? []),\n ...(this.options.signals?.adapters ?? []),\n ],\n },\n };\n }\n\n /**\n * Check if signals should be initialized\n *\n * Signals are initialized if any adapter is configured.\n *\n * @param config - Effective signal configuration\n * @returns True if signals should be initialized\n */\n private shouldInitializeSignals(config: GlobalSignalConfig): boolean {\n return !!(\n config.logging !== false ||\n config.metrics?.enabled ||\n config.pubsub?.enabled ||\n config.signals?.adapters?.length\n );\n }\n\n /**\n * Register signal adapters based on configuration\n *\n * @param config - Effective signal configuration\n */\n private async registerAdapters(config: GlobalSignalConfig): Promise<void> {\n if (!this._signalBus) return;\n\n // Logging adapter (default: enabled with console)\n if (config.logging !== false) {\n const { createLogger, LoggerAdapter } = await import(\n '@happyvertical/logger'\n );\n const logger = createLogger(config.logging ?? true);\n const adapter = new LoggerAdapter(logger);\n this._signalBus.register(adapter);\n this._registeredAdapters.push(adapter);\n }\n\n // Metrics adapter (default: disabled)\n if (config.metrics?.enabled) {\n const { MetricsAdapter } = await import('./adapters/metrics.js');\n const adapter = new MetricsAdapter();\n this._signalBus.register(adapter);\n this._registeredAdapters.push(adapter);\n }\n\n // Pub/Sub adapter (default: disabled)\n if (config.pubsub?.enabled) {\n const { PubSubAdapter } = await import('./adapters/pubsub.js');\n const adapter = new PubSubAdapter();\n this._signalBus.register(adapter);\n this._registeredAdapters.push(adapter);\n }\n\n // Custom adapters\n if (config.signals?.adapters) {\n for (const adapter of config.signals.adapters) {\n this._signalBus.register(adapter);\n this._registeredAdapters.push(adapter);\n }\n }\n }\n\n /**\n * Gets the filesystem adapter instance\n */\n get fs() {\n return this._fs;\n }\n\n /**\n * Gets the database interface instance\n */\n get db() {\n // Throw helpful error if database is accessed before initialization\n if (!this._db) {\n throw new Error(\n `Database accessed before initialization. ` +\n `Please call await instance.initialize() before accessing the database.`,\n );\n }\n return this._db;\n }\n\n /**\n * Temporarily bind this initialized instance to another database interface.\n *\n * This is intended for transaction-scoped work where a caller must ensure\n * that every nested SMRT read and write uses the transaction database passed\n * to its callback. The original database is restored whether the callback\n * succeeds or throws. Do not use the same instance concurrently while it is\n * temporarily bound.\n */\n async withDatabase<T>(\n db: DatabaseInterface,\n operation: (bound: this) => Promise<T>,\n ): Promise<T> {\n // Read through the public getter so an uninitialized instance fails with\n // the normal, actionable SmrtClass error before any state is mutated.\n const previousDb = this.db;\n const previousOptionDb = this.options.db;\n // `db` is usually a transaction handle of `previousDb`, which carries no\n // adapter markers; identify the root before swapping it out (#3737).\n noteNativeDuckDbHandle(previousDb, this._dbEngineHint);\n this._db = db;\n this.options.db = db;\n try {\n return await operation(this);\n } finally {\n this._db = previousDb;\n this.options.db = previousOptionDb;\n }\n }\n\n /**\n * Gets the AI client instance\n */\n get ai() {\n return this._ai;\n }\n\n /**\n * Get the in-memory AI usage snapshot for this instance.\n */\n getAiUsageSnapshot(): AiUsageSnapshot | undefined {\n return this._aiUsageCollector?.getSnapshot();\n }\n\n /**\n * Reset the in-memory AI usage collector.\n */\n resetAiUsage(): void {\n this._aiUsageCollector?.reset();\n }\n\n /**\n * List persisted AI usage records.\n */\n async listAiUsage(\n options: AiUsageListOptions = {},\n ): Promise<SmrtAiUsageRecord[]> {\n if (!this._db) {\n throw new Error(\n `AI usage requires a database configuration. ` +\n `Please call initialize() with a db option before querying usage.`,\n );\n }\n\n const { conditions, params } = buildAiUsageWhereClause(options);\n let paramIndex = params.length + 1;\n\n let sql = 'SELECT * FROM _smrt_ai_usage';\n if (conditions.length > 0) {\n sql += ` WHERE ${conditions.join(' AND ')}`;\n }\n\n sql += ` ORDER BY ${\n options.orderBy === 'timestamp ASC' ? 'created_at ASC' : 'created_at DESC'\n }`;\n\n if (options.limit !== undefined) {\n sql += ` LIMIT $${paramIndex++}`;\n params.push(options.limit);\n }\n\n if (options.offset !== undefined) {\n sql += ` OFFSET $${paramIndex++}`;\n params.push(options.offset);\n }\n\n const rows = getQueryRows(await this._db.query(sql, ...params));\n\n return rows.map((row) => ({\n id: String(row.id),\n provider: String(row.provider),\n model: String(row.model),\n operation: String(row.operation),\n usage: hydratePersistedAiUsageTokens(row),\n estimatedCost:\n row.estimated_cost === null || row.estimated_cost === undefined\n ? undefined\n : Number(row.estimated_cost),\n duration: toSafeInteger(row.duration ?? 0, 'AI usage duration'),\n className:\n row.class_name === null || row.class_name === undefined\n ? undefined\n : String(row.class_name),\n tenantId:\n row.tenant_id === undefined\n ? undefined\n : (row.tenant_id as string | null),\n tags: parseAiUsageTags(row.tags),\n timestamp: normalizeAiUsageTimestamp(row.created_at),\n }));\n }\n\n /**\n * Summarize persisted AI usage records by a grouping dimension.\n */\n async summarizeAiUsage(\n options: AiUsageSummaryOptions = {},\n ): Promise<Record<string, AiUsageStats>> {\n if (!this._db) {\n throw new Error(\n `AI usage requires a database configuration. ` +\n `Please call initialize() with a db option before querying usage.`,\n );\n }\n\n const groupBy = options.groupBy ?? 'model';\n const bucketExpression =\n groupBy === 'provider'\n ? `provider`\n : groupBy === 'model'\n ? `provider || ':' || model`\n : groupBy === 'class'\n ? `COALESCE(class_name, 'unknown')`\n : groupBy === 'tenant'\n ? `COALESCE(tenant_id, 'global')`\n : groupBy === 'operation'\n ? `operation`\n : `substr(CAST(created_at AS TEXT), 1, 10)`;\n\n const { conditions, params } = buildAiUsageWhereClause(options);\n\n let sql = `\n SELECT ${bucketExpression} AS bucket,\n COUNT(*) AS call_count,\n COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens,\n COALESCE(SUM(completion_tokens), 0) AS completion_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(duration), 0) AS total_duration,\n COALESCE(SUM(estimated_cost), 0) AS estimated_cost,\n MAX(created_at) AS last_used\n FROM _smrt_ai_usage\n `;\n\n if (conditions.length > 0) {\n sql += ` WHERE ${conditions.join(' AND ')}`;\n }\n\n sql += ' GROUP BY bucket ORDER BY bucket ASC';\n\n const rows = getQueryRows(await this._db.query(sql, ...params));\n const summary: Record<string, AiUsageStats> = {};\n\n for (const row of rows) {\n const bucket = String(row.bucket);\n summary[bucket] = {\n callCount: toSafeInteger(row.call_count ?? 0, 'AI usage call count'),\n promptTokens: toSafeInteger(\n row.prompt_tokens ?? 0,\n 'AI usage prompt-token total',\n ),\n completionTokens: toSafeInteger(\n row.completion_tokens ?? 0,\n 'AI usage completion-token total',\n ),\n totalTokens: toSafeInteger(\n row.total_tokens ?? 0,\n 'AI usage token total',\n ),\n totalDuration: toSafeInteger(\n row.total_duration ?? 0,\n 'AI usage duration total',\n ),\n estimatedCost: Number(row.estimated_cost ?? 0),\n lastUsed: row.last_used ? new Date(String(row.last_used)).getTime() : 0,\n };\n }\n\n return summary;\n }\n\n /**\n * Gets the signal bus instance\n *\n * @returns Signal bus if signals are enabled, undefined otherwise\n */\n get signalBus(): SignalBus | undefined {\n return this._signalBus;\n }\n\n /**\n * Cleanup method to prevent memory leaks\n *\n * Unregisters all adapters from the signal bus that were registered\n * by this instance. Call this when the SmrtClass instance is no longer\n * needed to prevent memory leaks.\n *\n * @example\n * ```typescript\n * const product = new Product({ name: 'Widget' });\n * await product.initialize();\n * // ... use product ...\n * product.destroy(); // Clean up when done\n * ```\n */\n destroy(): void {\n // Only unregister adapters if we own the bus (not shared)\n if (this._signalBus && !this.options.signals?.bus) {\n for (const adapter of this._registeredAdapters) {\n this._signalBus.unregister(adapter);\n }\n this._registeredAdapters = [];\n }\n\n // TODO: If SmrtClass grows a broader async teardown lifecycle, move\n // AI usage handler cleanup there alongside other connection-bound state.\n this._aiUsageCollector = undefined;\n this._aiUsageHandlers = [];\n }\n\n private mergeAiUsageConfig(\n globalConfig: GlobalSignalConfig,\n ): ResolvedAiUsageConfig {\n const globalUsage = globalConfig.usage ?? {};\n const instanceUsage = this.options.usage ?? {};\n\n return {\n enabled: instanceUsage.enabled ?? globalUsage.enabled ?? true,\n persist: instanceUsage.persist ?? globalUsage.persist ?? true,\n estimateCosts:\n instanceUsage.estimateCosts ?? globalUsage.estimateCosts ?? true,\n costRates: {\n ...(globalUsage.costRates ?? {}),\n ...(instanceUsage.costRates ?? {}),\n },\n handlers: [\n ...(globalUsage.handlers ?? []),\n ...(instanceUsage.handlers ?? []),\n ],\n };\n }\n\n private initializeAiUsageHandlers(config: ResolvedAiUsageConfig): void {\n this._aiUsageCollector = undefined;\n this._aiUsageHandlers = [];\n\n if (!config.enabled) {\n return;\n }\n\n this._aiUsageCollector = new AiUsageCollector();\n this._aiUsageHandlers.push(this._aiUsageCollector);\n\n if (config.persist && this._db) {\n this._aiUsageHandlers.push(new AiUsagePersistenceHandler(this._db));\n }\n\n this._aiUsageHandlers.push(...config.handlers);\n }\n\n private async handleAiUsageCallback(\n event: unknown,\n aiConfig: Record<string, unknown>,\n usageConfig: ResolvedAiUsageConfig,\n ): Promise<void> {\n if (!usageConfig.enabled || this._aiUsageHandlers.length === 0) {\n return;\n }\n\n const normalizedEvent = this.normalizeAiUsageEvent(event, aiConfig);\n if (!normalizedEvent) {\n return;\n }\n\n if (usageConfig.estimateCosts) {\n normalizedEvent.estimatedCost = estimateAiUsageCost(\n normalizedEvent.provider,\n normalizedEvent.model,\n normalizedEvent.usage,\n usageConfig.costRates,\n );\n }\n\n const results = await Promise.allSettled(\n this._aiUsageHandlers.map((handler) => handler.handle(normalizedEvent)),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logger.warn(\n `[smrt] AI usage handler failed for ${normalizedEvent.provider}:${normalizedEvent.model}: ${\n result.reason instanceof Error\n ? result.reason.message\n : String(result.reason)\n }`,\n );\n }\n }\n }\n\n private normalizeAiUsageEvent(\n event: unknown,\n aiConfig: Record<string, unknown>,\n ): SmrtAiUsageEvent | undefined {\n const raw = (event ?? {}) as Record<string, unknown>;\n const provider = firstString(\n raw.provider,\n raw.type,\n aiConfig.provider,\n aiConfig.type,\n );\n const model = firstString(\n raw.model,\n raw.defaultModel,\n aiConfig.model,\n aiConfig.defaultModel,\n );\n const operation =\n firstString(raw.operation, raw.kind, raw.method) ?? 'unknown';\n const usage =\n normalizeIncomingAiUsageTokens(raw.usage) ??\n normalizeIncomingAiUsageTokens(raw.tokenUsage) ??\n normalizeIncomingAiUsageTokens({\n promptTokens: raw.promptTokens,\n completionTokens: raw.completionTokens,\n totalTokens: raw.totalTokens,\n });\n\n if (!provider || !model) {\n return undefined;\n }\n\n const duration =\n firstNumber(raw.duration, raw.durationMs, raw.latency) ?? 0;\n const tenantId =\n 'tenantId' in this &&\n (this as { tenantId?: string | null }).tenantId !== undefined\n ? ((this as { tenantId?: string | null }).tenantId ?? null)\n : undefined;\n\n return {\n provider,\n model,\n operation,\n usage,\n duration,\n timestamp: normalizeAiUsageTimestamp(raw.timestamp),\n tags: normalizeAiUsageTags(raw.tags),\n className: this._className,\n tenantId,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAM,wCAAwC;AAE9C,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;AAmC7C,SAAS,YAAY,GAAG,YAA2C;CACjE,OAAO,WAAW,MAAM,cAAmC;EACzD,OAAO,OAAO,cAAc;CAC9B,CAAC;AACH;AAEA,SAAS,YAAY,GAAG,YAA2C;CACjE,OAAO,WAAW,MAAM,cAAmC;EACzD,OAAO,OAAO,cAAc;CAC9B,CAAC;AACH;AAEA,SAAS,eAAe,IAA+B;CACrD,MAAM,eAAe;CACrB,OAAO,GAAG,OAAO,aAAa,QAAQ,OAAO;AAC/C;AAEA,SAAS,oBACP,QACoB;CACpB,IAAI,CAAC,UAAU,OAAO,WAAW,UAC/B;CAGF,MAAM,iBAAiB;CAIvB,IAAI,OAAO,eAAe,SAAS,UACjC,OAAO,eAAe;CAGxB,IAAI,OAAO,eAAe,QAAQ,SAAS,UACzC,OAAO,eAAe,OAAO;CAG/B,IAAI,WAAW,kBAAkB,OAAO,eAAe,UAAU,YAC/D;CAGF,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p": 0,
5
5
  "packageName": "@happyvertical/smrt-core",
6
- "packageVersion": "0.55.22",
6
+ "packageVersion": "0.55.23",
7
7
  "objects": {
8
8
  "@happyvertical/smrt-core:SmrtClass": {
9
9
  "name": "smrtclass",