@dudousxd/nestjs-agent-store-drizzle 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema.ts","../src/ensure-schema.ts","../src/drizzle-agent-store.ts","../src/drizzle-governance-queries.ts","../src/drizzle-pricing-store.ts","../src/drizzle-agent-store.module.ts"],"sourcesContent":["import type {\n MessageAttachment,\n MessageRole,\n MessageUsage,\n ToolCallRequest,\n ToolCallStatus,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport type { TablesRelationalConfig } from 'drizzle-orm';\nimport {\n type BaseSQLiteDatabase,\n index,\n integer,\n real,\n sqliteTable,\n text,\n} from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle schema mirroring the MikroORM agent entities (same logical columns/relations):\n * threads, messages, tool calls, token usage, model pricing and run outcomes. Targets the SQLite core so the\n * db-test runs on an in-memory better-sqlite3; timestamps are stored as integer epoch-ms columns\n * (`{ mode: 'timestamp_ms' }`) which Drizzle round-trips to/from JS `Date`, and the model-facing\n * message extras (tool calls/results, follow-ups, usage) live in JSON `text` columns.\n */\n\n/**\n * A conversation thread. `deletedAt` drives soft delete: a deleted thread is hidden from\n * {@link import('./drizzle-agent-store.js').DrizzleAgentStore.getThread}/`listThreads` but its\n * row survives.\n */\nexport const agentThread = sqliteTable(\n 'agent_thread',\n {\n id: text('id').primaryKey(),\n actorRef: text('actor_ref').notNull(),\n tenantRef: text('tenant_ref'),\n title: text('title').notNull(),\n transient: integer('transient', { mode: 'boolean' }).notNull().default(false),\n activeStreamId: text('active_stream_id'),\n /** The agent a new turn on this thread defaults to when the caller names none. */\n defaultAgent: text('default_agent'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n deletedAt: integer('deleted_at', { mode: 'timestamp_ms' }),\n },\n (table) => [index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt)],\n);\n\n/**\n * One stored message in a thread. The model-facing extras (`toolCalls`/`toolResults`/\n * `followUps`/`usage`) are folded into nullable JSON columns so a single row round-trips to a\n * {@link import('@dudousxd/nestjs-agent-core').StoredMessage}. `threadId` cascades on delete.\n */\nexport const agentMessage = sqliteTable(\n 'agent_message',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n role: text('role').$type<MessageRole>().notNull(),\n content: text('content').notNull(),\n toolCalls: text('tool_calls', { mode: 'json' }).$type<ToolCallRequest[]>(),\n toolResults: text('tool_results', { mode: 'json' }).$type<ToolResult[]>(),\n attachments: text('attachments', { mode: 'json' }).$type<MessageAttachment[]>(),\n followUps: text('follow_ups', { mode: 'json' }).$type<string[]>(),\n usage: text('usage', { mode: 'json' }).$type<MessageUsage>(),\n agentName: text('agent_name'),\n runId: text('run_id'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_message_thread_created_idx').on(table.threadId, table.createdAt)],\n);\n\n/**\n * A tool call requested during an assistant turn. The pk is the model-supplied `toolCallId`.\n *\n * `messageId` carries its own index rather than relying on the foreign key: MySQL indexes a foreign\n * key column for you, Postgres does not — and every message-scoped read here filters on it (the\n * thread reader's `IN (…)` over a turn's calls, and `truncateFrom`'s delete).\n */\nexport const agentToolCall = sqliteTable(\n 'agent_tool_call',\n {\n id: text('id').primaryKey(),\n messageId: text('message_id')\n .notNull()\n .references(() => agentMessage.id, { onDelete: 'cascade' }),\n toolName: text('tool_name').notNull(),\n toolType: text('tool_type').$type<ToolKind>().notNull(),\n input: text('input', { mode: 'json' }),\n output: text('output', { mode: 'json' }),\n status: text('status').$type<ToolCallStatus>().notNull(),\n executedByRef: text('executed_by_ref'),\n executionMs: integer('execution_ms'),\n error: text('error'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n executedAt: integer('executed_at', { mode: 'timestamp_ms' }),\n /** The run (turn) this call belongs to, for a trace deep-link; null for a pre-rollout row. */\n runId: text('run_id'),\n },\n (table) => [index('agent_tool_call_message_idx').on(table.messageId)],\n);\n\n/** A token-usage ledger row, summed per actor per day by `quotaToday`. */\nexport const agentTokenUsage = sqliteTable(\n 'agent_token_usage',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: text('actor_ref').notNull(),\n messageId: text('message_id'),\n modelId: text('model_id').notNull(),\n purpose: text('purpose').$type<UsagePurpose>().notNull(),\n inputTokens: integer('input_tokens').notNull(),\n outputTokens: integer('output_tokens').notNull(),\n /** Subset of `inputTokens` written to the prompt cache this turn; null when not reported. */\n cacheWriteTokens: integer('cache_write_tokens'),\n /** Subset of `inputTokens` served from the prompt cache this turn; null when not reported. */\n cacheReadTokens: integer('cache_read_tokens'),\n /** Provider-reported actual USD cost for the turn; null when only tokens were reported. */\n costUsd: real('cost_usd'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt)],\n);\n\n/** Per-model token pricing, versioned by `effectiveFrom`; `isCurrent` flags the live row. */\nexport const agentModelPricing = sqliteTable('agent_model_pricing', {\n id: text('id').primaryKey(),\n modelId: text('model_id').notNull(),\n inputPricePer1m: real('input_price_per_1m').notNull(),\n outputPricePer1m: real('output_price_per_1m').notNull(),\n /** Per-1M price for cache-write input tokens; null → price them at the input rate. */\n cacheWritePricePer1m: real('cache_write_price_per_1m'),\n /** Per-1M price for cache-read input tokens; null → price them at the input rate. */\n cacheReadPricePer1m: real('cache_read_price_per_1m'),\n effectiveFrom: integer('effective_from', { mode: 'timestamp_ms' }).notNull(),\n isCurrent: integer('is_current', { mode: 'boolean' }).notNull(),\n});\n\n/**\n * A run's lifecycle status. Not part of the core SPI (that surfaces `string`) — internal only.\n *\n * `cancelled` is a third TERMINAL, not a flavour of `failed`: someone asked the run to stop and it\n * did. A reliability read that folded it into `failed` would page whoever is on call for model\n * failures every time a user pressed Stop.\n */\nexport type AgentRunStatus = 'running' | 'completed' | 'failed' | 'cancelled';\n\n/**\n * One recorded run (turn) outcome — the durable half of what `aviary:agent:*` diagnostics report\n * ephemerally. Written by {@link import('./drizzle-agent-store.js').DrizzleAgentStore.recordRunStart}/\n * `recordRunEnd`/`bumpRunRetries`, read by\n * {@link import('./drizzle-governance-queries.js').DrizzleGovernanceQueries} for the reliability\n * surfaces (success rate, error breakdown, duration percentiles, trend, recent runs). `threadId`\n * cascades on delete, like `agent_message`/`agent_token_usage`.\n */\nexport const agentRun = sqliteTable(\n 'agent_run',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: text('actor_ref').notNull(),\n agentName: text('agent_name'),\n status: text('status').$type<AgentRunStatus>().notNull(),\n durationMs: integer('duration_ms'),\n errorCode: text('error_code'),\n errorMessage: text('error_message'),\n retries: integer('retries').notNull().default(0),\n startedAt: integer('started_at', { mode: 'timestamp_ms' }).notNull(),\n settledAt: integer('settled_at', { mode: 'timestamp_ms' }),\n /** sha256 hex of the run's resolved (pre-RAG) system prompt; null for a pre-existing run. */\n promptHash: text('prompt_hash'),\n /**\n * The run that delegated this one; null for a turn nobody delegated. The durable runtime's\n * journal holds the same edge, but only there — this column is what lets a reader of run ROWS\n * build the delegation tree and roll a child's cost up to the turn that asked for it, including\n * for a detached child, which outlives its parent's turn and so is paired by nothing in the\n * transcript.\n */\n parentRunId: text('parent_run_id'),\n },\n (table) => [index('agent_run_started_idx').on(table.startedAt)],\n);\n\n/** The six agent tables as one schema object, ready for `drizzle(client, { schema })`. */\nexport const agentSchema = {\n agentThread,\n agentMessage,\n agentToolCall,\n agentTokenUsage,\n agentModelPricing,\n agentRun,\n};\n\n/**\n * The dialect-portable Drizzle SQLite database handle the store operates on. Accepts any SQLite\n * driver (better-sqlite3, libsql, D1, …) in either sync or async result mode; the host app owns\n * the connection and passes the `drizzle(...)` instance in.\n */\nexport type AgentDrizzleDb = BaseSQLiteDatabase<\n 'sync' | 'async',\n unknown,\n Record<string, unknown>,\n TablesRelationalConfig\n>;\n\n/** A persisted thread row as Drizzle selects it. */\nexport type AgentThreadRow = typeof agentThread.$inferSelect;\n/** A persisted message row as Drizzle selects it. */\nexport type AgentMessageRow = typeof agentMessage.$inferSelect;\n/** A persisted run row as Drizzle selects it. */\nexport type AgentRunRow = typeof agentRun.$inferSelect;\n","import { sql } from 'drizzle-orm';\nimport type { AgentDrizzleDb } from './schema.js';\n\n/**\n * Idempotent `CREATE TABLE IF NOT EXISTS` DDL for the six agent tables, mirroring\n * {@link import('./schema.js').agentSchema}. SQLite dialect (the db-test driver); kept here rather\n * than relying on drizzle-kit so the package can stand up its schema with no migration files. Safe\n * to run on boot against a shared database — it never drops or alters existing columns.\n */\nconst statements: string[] = [\n `CREATE TABLE IF NOT EXISTS agent_thread (\n id TEXT PRIMARY KEY NOT NULL,\n actor_ref TEXT NOT NULL,\n tenant_ref TEXT,\n title TEXT NOT NULL,\n transient INTEGER NOT NULL DEFAULT 0,\n active_stream_id TEXT,\n default_agent TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n deleted_at INTEGER\n )`,\n `CREATE INDEX IF NOT EXISTS agent_thread_actor_updated_idx\n ON agent_thread (actor_ref, updated_at)`,\n `CREATE TABLE IF NOT EXISTS agent_message (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n role TEXT NOT NULL,\n content TEXT NOT NULL,\n tool_calls TEXT,\n tool_results TEXT,\n attachments TEXT,\n follow_ups TEXT,\n usage TEXT,\n agent_name TEXT,\n run_id TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS agent_message_thread_created_idx\n ON agent_message (thread_id, created_at)`,\n `CREATE TABLE IF NOT EXISTS agent_tool_call (\n id TEXT PRIMARY KEY NOT NULL,\n message_id TEXT NOT NULL REFERENCES agent_message(id) ON DELETE CASCADE,\n tool_name TEXT NOT NULL,\n tool_type TEXT NOT NULL,\n input TEXT,\n output TEXT,\n status TEXT NOT NULL,\n executed_by_ref TEXT,\n execution_ms INTEGER,\n error TEXT,\n created_at INTEGER NOT NULL,\n executed_at INTEGER,\n run_id TEXT\n )`,\n `CREATE INDEX IF NOT EXISTS agent_tool_call_message_idx\n ON agent_tool_call (message_id)`,\n `CREATE TABLE IF NOT EXISTS agent_token_usage (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n actor_ref TEXT NOT NULL,\n message_id TEXT,\n model_id TEXT NOT NULL,\n purpose TEXT NOT NULL,\n input_tokens INTEGER NOT NULL,\n output_tokens INTEGER NOT NULL,\n cache_write_tokens INTEGER,\n cache_read_tokens INTEGER,\n cost_usd REAL,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS agent_token_usage_actor_created_idx\n ON agent_token_usage (actor_ref, created_at)`,\n `CREATE TABLE IF NOT EXISTS agent_model_pricing (\n id TEXT PRIMARY KEY NOT NULL,\n model_id TEXT NOT NULL,\n input_price_per_1m REAL NOT NULL,\n output_price_per_1m REAL NOT NULL,\n cache_write_price_per_1m REAL,\n cache_read_price_per_1m REAL,\n effective_from INTEGER NOT NULL,\n is_current INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS agent_run (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n actor_ref TEXT NOT NULL,\n agent_name TEXT,\n status TEXT NOT NULL,\n duration_ms INTEGER,\n error_code TEXT,\n error_message TEXT,\n retries INTEGER NOT NULL DEFAULT 0,\n started_at INTEGER NOT NULL,\n settled_at INTEGER,\n prompt_hash TEXT,\n parent_run_id TEXT\n )`,\n `CREATE INDEX IF NOT EXISTS agent_run_started_idx\n ON agent_run (started_at)`,\n];\n\n/**\n * Columns added to a table this package already shipped. `CREATE TABLE IF NOT EXISTS` above is inert\n * against a database that already has the table, so a column introduced later would land on fresh\n * databases only and be missing everywhere the store is actually running. The MikroORM adapter has\n * no such gap — its `ensureAgentSchema` applies `getUpdateSchemaSQL({ safe: true })`, which is\n * add-column-capable — so without this list the two adapters would disagree about what the schema is\n * after an upgrade.\n *\n * Add-column only, never a type change or a drop: `safe` in the same sense as the sibling adapter.\n */\nconst additiveColumns: Array<{ table: string; column: string; ddl: string }> = [\n {\n table: 'agent_message',\n column: 'run_id',\n ddl: 'ALTER TABLE agent_message ADD COLUMN run_id TEXT',\n },\n {\n table: 'agent_message',\n column: 'attachments',\n ddl: 'ALTER TABLE agent_message ADD COLUMN attachments TEXT',\n },\n {\n table: 'agent_thread',\n column: 'default_agent',\n ddl: 'ALTER TABLE agent_thread ADD COLUMN default_agent TEXT',\n },\n {\n table: 'agent_run',\n column: 'parent_run_id',\n ddl: 'ALTER TABLE agent_run ADD COLUMN parent_run_id TEXT',\n },\n];\n\n/**\n * Runs the `CREATE TABLE IF NOT EXISTS` DDL above against the supplied Drizzle SQLite db, then adds\n * any column missing from a table that already existed.\n */\nexport async function ensureAgentSchema(db: AgentDrizzleDb): Promise<void> {\n for (const statement of statements) {\n await db.run(sql.raw(statement));\n }\n for (const { table, column, ddl } of additiveColumns) {\n // Asking the table what it has, rather than running the ALTER and swallowing the failure: a\n // swallowed error cannot tell \"the column is already there\" apart from \"the ALTER is malformed\",\n // and the second one would then go unnoticed until a query hit the missing column.\n const existing = await db.all<{ name: string }>(sql.raw(`PRAGMA table_info(${table})`));\n if (!existing.some((row) => row.name === column)) {\n await db.run(sql.raw(ddl));\n }\n }\n}\n","import type {\n AgentStore,\n AppendMessageInput,\n CreateThreadInput,\n RecordRunStartInput,\n RecordToolCallInput,\n RecordUsageInput,\n StoredMessage,\n ThreadDetail,\n ThreadSummary,\n ThreadTurnPage,\n ThreadTurnQuery,\n ThreadTurnReader,\n ToolResult,\n UpdateThreadInput,\n UpdateToolCallInput,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, sql } from 'drizzle-orm';\nimport {\n type AgentDrizzleDb,\n type AgentMessageRow,\n type AgentRunRow,\n type AgentThreadRow,\n agentMessage,\n agentRun,\n agentThread,\n agentTokenUsage,\n agentToolCall,\n} from './schema.js';\n\n/**\n * Re-exported from the core SPI so a consumer can name this store's window read without importing a\n * second package. ONE definition of the shape, so the adapter and the seam the loop probes for\n * cannot drift apart.\n */\nexport type { ThreadTurnPage, ThreadTurnQuery };\n\n/** The message columns a model turn reads. `usage`, `follow_ups` and `run_id` are nobody's business here. */\nconst TURN_MESSAGE_COLUMNS = {\n id: agentMessage.id,\n role: agentMessage.role,\n content: agentMessage.content,\n agentName: agentMessage.agentName,\n toolCalls: agentMessage.toolCalls,\n toolResults: agentMessage.toolResults,\n attachments: agentMessage.attachments,\n createdAt: agentMessage.createdAt,\n};\n\ntype TurnMessageRow = { [K in keyof typeof TURN_MESSAGE_COLUMNS]: AgentMessageRow[K] };\n\n/**\n * {@link AgentStore} backed by Drizzle ORM — a second adapter alongside the MikroORM one, proving\n * the store SPI is ORM-portable. A POJO receiving a Drizzle SQLite database handle (the host app\n * owns the connection). Behaviour mirrors {@link import('@dudousxd/nestjs-agent-store-mikro-orm')}\n * exactly (fork/truncate/quota/active-stream/soft-delete semantics) so the two are interchangeable.\n */\nexport class DrizzleAgentStore implements AgentStore, ThreadTurnReader {\n constructor(private readonly db: AgentDrizzleDb) {}\n\n async createThread(input: CreateThreadInput): Promise<ThreadSummary> {\n const now = new Date();\n const thread: AgentThreadRow = {\n id: crypto.randomUUID(),\n actorRef: input.actor.id,\n tenantRef: input.actor.tenantRef ?? null,\n title: input.title ?? 'New chat',\n transient: input.transient ?? false,\n activeStreamId: null,\n defaultAgent: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(agentThread).values(thread);\n return this.toSummary(thread);\n }\n\n async getThread(threadId: string): Promise<ThreadDetail | null> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n if (thread === undefined) {\n return null;\n }\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const last = messages[messages.length - 1];\n return {\n ...this.toSummary(thread, last?.content),\n messages: messages.map((message) => this.toStoredMessage(message)),\n ...(thread.activeStreamId != null ? { activeStreamId: thread.activeStreamId } : {}),\n };\n }\n\n /**\n * The window a turn reads off a thread: its newest `messageLimit` messages (oldest first), the\n * title, the default agent, and whether the thread has EVER been answered.\n *\n * {@link getThread} is the wrong read for a turn. It materializes the transcript — every message,\n * every attachment, every tool output the thread ever recorded — and the run then journals what it\n * loaded, so a long thread pays for its whole history on every turn and again on every replay.\n *\n * `hasAssistantMessage` is answered over the WHOLE thread, not the returned page: it answers \"has\n * this conversation been answered before?\", and a thread whose window happens to hold only the\n * user's last questions has still been answered. `null` when the thread is unknown or\n * soft-deleted, same as {@link getThread}.\n */\n async loadThreadForTurn(query: ThreadTurnQuery): Promise<ThreadTurnPage | null> {\n const [thread] = await this.db\n .select({ title: agentThread.title, defaultAgent: agentThread.defaultAgent })\n .from(agentThread)\n .where(and(eq(agentThread.id, query.threadId), isNull(agentThread.deletedAt)));\n if (thread === undefined) {\n return null;\n }\n const messages = await this.loadTurnWindow(query.threadId, query.messageLimit);\n const [answered] = await this.db\n .select({ id: agentMessage.id })\n .from(agentMessage)\n .where(and(eq(agentMessage.threadId, query.threadId), eq(agentMessage.role, 'assistant')))\n .limit(1);\n return {\n title: thread.title,\n defaultAgent: thread.defaultAgent,\n hasAssistantMessage: answered !== undefined,\n messages,\n };\n }\n\n /**\n * The newest `limit` messages of a thread, oldest first, projected to the columns a model turn\n * reads. Read newest-first so the LIMIT is the database's job, then reversed for the prompt.\n */\n private async loadTurnWindow(\n threadId: string,\n limit: number | undefined,\n ): Promise<StoredMessage[]> {\n if (limit !== undefined && limit <= 0) {\n return [];\n }\n const window = this.db\n .select(TURN_MESSAGE_COLUMNS)\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(desc(agentMessage.createdAt), desc(agentMessage.id));\n const rows: TurnMessageRow[] = limit === undefined ? await window : await window.limit(limit);\n return rows.reverse().map((row) => this.toStoredMessage(row));\n }\n\n async listThreads(actorRef: string, limit = 50): Promise<ThreadSummary[]> {\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(\n and(\n eq(agentThread.actorRef, actorRef),\n eq(agentThread.transient, false),\n isNull(agentThread.deletedAt),\n ),\n )\n .orderBy(desc(agentThread.updatedAt))\n .limit(limit);\n const summaries: ThreadSummary[] = [];\n for (const thread of threads) {\n const [last] = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id))\n .orderBy(desc(agentMessage.createdAt), desc(agentMessage.id))\n .limit(1);\n summaries.push(this.toSummary(thread, last?.content));\n }\n return summaries;\n }\n\n async softDeleteThread(threadId: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ deletedAt: new Date() })\n .where(eq(agentThread.id, threadId));\n }\n\n async forkThread(threadId: string, fromMessageId: string): Promise<ThreadSummary> {\n const [source] = await this.db.select().from(agentThread).where(eq(agentThread.id, threadId));\n if (source === undefined) {\n throw new Error(`thread ${threadId} not found`);\n }\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const cutoff = messages.findIndex((message) => message.id === fromMessageId);\n const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;\n const now = new Date();\n const fork: AgentThreadRow = {\n id: crypto.randomUUID(),\n actorRef: source.actorRef,\n tenantRef: source.tenantRef,\n title: source.title,\n transient: false,\n activeStreamId: null,\n defaultAgent: source.defaultAgent,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(agentThread).values(fork);\n if (kept.length > 0) {\n await this.db.insert(agentMessage).values(\n kept.map((message) => ({\n id: crypto.randomUUID(),\n threadId: fork.id,\n role: message.role,\n content: message.content,\n toolCalls: message.toolCalls,\n toolResults: message.toolResults,\n attachments: message.attachments,\n followUps: message.followUps,\n usage: message.usage,\n agentName: message.agentName,\n // The copy is the same message, so it keeps the run that wrote it. A reader asking which\n // turn produced this text gets the truthful answer; the run's own thread is still the\n // original, so a run-scoped read never picks the fork's rows up.\n runId: message.runId,\n createdAt: message.createdAt,\n })),\n );\n }\n return this.toSummary(fork);\n }\n\n async ownerOfThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n return thread?.actorRef ?? null;\n }\n\n async ownerOfToolCall(toolCallId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.id, toolCallId));\n return row?.actorRef ?? null;\n }\n\n async runForToolCall(toolCallId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ runId: agentToolCall.runId, activeStreamId: agentThread.activeStreamId })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.id, toolCallId));\n return row?.runId ?? row?.activeStreamId ?? null;\n }\n\n async ownerOfActiveStream(runId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentThread)\n .where(and(eq(agentThread.activeStreamId, runId), isNull(agentThread.deletedAt)));\n return thread?.actorRef ?? null;\n }\n\n async setTitle(threadId: string, title: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ title, updatedAt: new Date() })\n .where(eq(agentThread.id, threadId));\n }\n\n async promoteThread(threadId: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ transient: false, updatedAt: new Date() })\n .where(and(eq(agentThread.id, threadId), eq(agentThread.transient, true)));\n }\n\n async setActiveStream(threadId: string, runId: string | null): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ activeStreamId: runId })\n .where(eq(agentThread.id, threadId));\n }\n\n /**\n * Patch a thread's `title` and/or `defaultAgent`. Each field is only touched when PRESENT in\n * `patch` — `defaultAgent: null` clears it (falls back to the app default), while an omitted\n * `defaultAgent` leaves whatever is stored untouched. A no-op (including `updatedAt`) when the\n * patch is empty or the thread doesn't exist.\n */\n async updateThread(threadId: string, patch: UpdateThreadInput): Promise<void> {\n const updates: Partial<typeof agentThread.$inferInsert> = {};\n if (patch.title !== undefined) {\n updates.title = patch.title;\n }\n if (patch.defaultAgent !== undefined) {\n updates.defaultAgent = patch.defaultAgent;\n }\n if (Object.keys(updates).length === 0) {\n return;\n }\n updates.updatedAt = new Date();\n await this.db.update(agentThread).set(updates).where(eq(agentThread.id, threadId));\n }\n\n /**\n * The thread's default agent, projected — the caller wants one nullable scalar to decide which\n * agent answers the next turn, and {@link getThread} would materialize the whole transcript to\n * hand it over. `null` when the thread is unknown, soft-deleted, or has no default set.\n */\n async defaultAgentForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ defaultAgent: agentThread.defaultAgent })\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n return thread?.defaultAgent ?? null;\n }\n\n /**\n * Persist the start of a run (turn). Replay-safe: called under a durable localStep.\n *\n * Takes the SPI's own {@link RecordRunStartInput} rather than a hand-copied shape: a field added\n * to the input is otherwise accepted and dropped, silently, by every adapter that re-declares it.\n */\n async recordRunStart(run: RecordRunStartInput): Promise<void> {\n const runRow: AgentRunRow = {\n id: run.runId,\n threadId: run.threadId,\n actorRef: run.actorRef,\n agentName: run.agentName ?? null,\n status: 'running',\n durationMs: null,\n errorCode: null,\n errorMessage: null,\n retries: 0,\n startedAt: new Date(),\n settledAt: null,\n promptHash: run.promptHash ?? null,\n parentRunId: run.parentRunId ?? null,\n };\n await this.db.insert(agentRun).values(runRow);\n }\n\n /** Settle a run's outcome. A no-op when the run is unknown (mirrors `setTitle`/`updateThread`). */\n async recordRunEnd(end: {\n runId: string;\n status: 'completed' | 'failed' | 'cancelled';\n durationMs?: number;\n errorCode?: string;\n errorMessage?: string;\n }): Promise<void> {\n const updates: Partial<typeof agentRun.$inferInsert> = {\n status: end.status,\n settledAt: new Date(),\n };\n if (end.durationMs !== undefined) {\n updates.durationMs = end.durationMs;\n }\n if (end.errorCode !== undefined) {\n updates.errorCode = end.errorCode;\n }\n if (end.errorMessage !== undefined) {\n updates.errorMessage = end.errorMessage;\n }\n await this.db.update(agentRun).set(updates).where(eq(agentRun.id, end.runId));\n }\n\n /** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */\n async bumpRunRetries(runId: string): Promise<void> {\n await this.db\n .update(agentRun)\n .set({ retries: sql`${agentRun.retries} + 1` })\n .where(eq(agentRun.id, runId));\n }\n\n async appendMessage(input: AppendMessageInput): Promise<StoredMessage> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(eq(agentThread.id, input.threadId));\n if (thread === undefined) {\n throw new Error(`thread ${input.threadId} not found`);\n }\n const now = new Date();\n const message: AgentMessageRow = {\n id: crypto.randomUUID(),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n toolCalls: input.toolCalls ?? null,\n toolResults: input.toolResults ?? null,\n attachments: input.attachments ?? null,\n followUps: input.followUps ?? null,\n usage: input.usage ?? null,\n agentName: input.agentName ?? null,\n runId: input.runId ?? null,\n createdAt: now,\n };\n await this.db.insert(agentMessage).values(message);\n await this.db\n .update(agentThread)\n .set({ updatedAt: now })\n .where(eq(agentThread.id, input.threadId));\n return this.toStoredMessage(message);\n }\n\n async setMessageToolResults(messageId: string, results: ToolResult[]): Promise<void> {\n await this.db\n .update(agentMessage)\n .set({ toolResults: results })\n .where(eq(agentMessage.id, messageId));\n }\n\n async truncateFrom(threadId: string, messageId: string): Promise<void> {\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const cutoff = messages.findIndex((message) => message.id === messageId);\n if (cutoff < 0) {\n return;\n }\n const doomedIds = messages.slice(cutoff).map((message) => message.id);\n await this.db.delete(agentToolCall).where(inArray(agentToolCall.messageId, doomedIds));\n await this.db.delete(agentMessage).where(inArray(agentMessage.id, doomedIds));\n }\n\n async recordToolCall(input: RecordToolCallInput): Promise<void> {\n await this.db.insert(agentToolCall).values({\n id: input.toolCallId,\n messageId: input.messageId,\n toolName: input.toolName,\n toolType: input.toolType,\n input: input.input,\n output: null,\n status: input.status,\n executedByRef: null,\n executionMs: null,\n error: null,\n createdAt: new Date(),\n executedAt: null,\n runId: input.runId ?? null,\n });\n }\n\n async updateToolCall(input: UpdateToolCallInput): Promise<void> {\n const updates: Partial<typeof agentToolCall.$inferInsert> = { status: input.status };\n if (input.output !== undefined) {\n updates.output = input.output;\n }\n if (input.error !== undefined) {\n updates.error = input.error;\n }\n if (input.executionMs !== undefined) {\n updates.executionMs = input.executionMs;\n }\n if (input.executedByRef !== undefined) {\n updates.executedByRef = input.executedByRef;\n }\n if (input.status === 'executed' || input.status === 'auto_executed') {\n updates.executedAt = new Date();\n }\n await this.db.update(agentToolCall).set(updates).where(eq(agentToolCall.id, input.toolCallId));\n }\n\n /**\n * Of `mediaIds`, the ones a surviving message in one of this actor's threads still carries.\n *\n * Reads the `attachments` JSON back out and matches in memory rather than pushing the match into\n * SQL: the column holds an array of objects, and every dialect this adapter's sibling targets\n * spells that query differently (`jsonb` containment, `json_table`, `json_each`), while none of\n * them can use an index for it anyway. The scan is bounded by ONE actor's attachment-bearing\n * messages, which is a small set — attachments are rare, and a message without one is excluded\n * by the `is not null` before any JSON is parsed.\n *\n * Soft-deleted threads are deliberately included: their message rows survive, so the bytes they\n * point at are still reachable from stored state and are not garbage.\n */\n async referencedMediaIds(actorRef: string, mediaIds: readonly string[]): Promise<string[]> {\n if (mediaIds.length === 0) {\n return [];\n }\n const rows = await this.db\n .select({ attachments: agentMessage.attachments })\n .from(agentMessage)\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(and(eq(agentThread.actorRef, actorRef), isNotNull(agentMessage.attachments)));\n const wanted = new Set(mediaIds);\n const found = new Set<string>();\n for (const row of rows) {\n for (const attachment of row.attachments ?? []) {\n if (wanted.has(attachment.mediaId)) {\n found.add(attachment.mediaId);\n }\n }\n }\n return [...wanted].filter((mediaId) => found.has(mediaId));\n }\n\n async recordUsage(input: RecordUsageInput): Promise<void> {\n await this.db.insert(agentTokenUsage).values({\n id: crypto.randomUUID(),\n threadId: input.threadId,\n actorRef: input.actorRef,\n messageId: input.messageId ?? null,\n modelId: input.modelId,\n purpose: input.purpose,\n inputTokens: input.usage.inputTokens,\n outputTokens: input.usage.outputTokens,\n cacheWriteTokens: input.usage.cacheWriteTokens ?? null,\n cacheReadTokens: input.usage.cacheReadTokens ?? null,\n costUsd: input.costUsd ?? null,\n createdAt: new Date(),\n });\n }\n\n async quotaToday(\n actorRef: string,\n day: string,\n ): Promise<{ usedTokens: number; costUsd: number }> {\n const start = new Date(`${day}T00:00:00.000Z`);\n const end = new Date(`${day}T23:59:59.999Z`);\n const rows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(\n and(\n eq(agentTokenUsage.actorRef, actorRef),\n gte(agentTokenUsage.createdAt, start),\n lte(agentTokenUsage.createdAt, end),\n ),\n );\n const usedTokens = rows.reduce((sum, row) => sum + row.inputTokens + row.outputTokens, 0);\n const costUsd = rows.reduce((sum, row) => sum + (row.costUsd ?? 0), 0);\n return { usedTokens, costUsd };\n }\n\n private toSummary(thread: AgentThreadRow, lastContent?: string): ThreadSummary {\n return {\n id: thread.id,\n title: thread.title,\n transient: thread.transient,\n createdAt: thread.createdAt.toISOString(),\n updatedAt: thread.updatedAt.toISOString(),\n defaultAgent: thread.defaultAgent,\n ...(lastContent !== undefined ? { lastMessagePreview: lastContent.slice(0, 120) } : {}),\n };\n }\n\n private toStoredMessage(message: TurnMessageRow & Partial<AgentMessageRow>): StoredMessage {\n return {\n id: message.id,\n role: message.role,\n content: message.content,\n createdAt: message.createdAt.toISOString(),\n ...(message.toolCalls != null ? { toolCalls: message.toolCalls } : {}),\n ...(message.toolResults != null ? { toolResults: message.toolResults } : {}),\n ...(message.attachments != null ? { attachments: message.attachments } : {}),\n ...(message.followUps != null ? { followUps: message.followUps } : {}),\n ...(message.usage != null ? { usage: message.usage } : {}),\n ...(message.agentName != null ? { agentName: message.agentName } : {}),\n ...(message.runId != null ? { runId: message.runId } : {}),\n };\n }\n}\n","import type {\n ActorSpendRow,\n AgentGovernanceQueries,\n AgentPricingStore,\n ApprovalWhere,\n GovernancePage,\n GovernancePageQuery,\n GovernanceRange,\n GovernanceRunDetail,\n GovernanceThreadDetail,\n GovernanceThreadDetailQuery,\n GovernanceUsageInput,\n ModelPrice,\n ModelSpendRow,\n PendingApprovalRow,\n RecentRunRow,\n RunAgentBreakdownRow,\n RunErrorBreakdownRow,\n RunMetrics,\n RunToolCallRow,\n RunTrendPoint,\n RunWhere,\n ThreadActivityRow,\n ThreadMessageRow,\n ThreadMeta,\n ThreadSpendRow,\n ThreadWhere,\n ToolCallActivityRow,\n ToolCallStatus,\n ToolCallWhere,\n ToolKind,\n ToolStatRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n bucketByActor,\n bucketByModel,\n bucketByThread,\n bucketUsageTrend,\n dayBoundsUtc,\n rollupThreadUsage,\n truncateDetailContent,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, count, desc, eq, gte, inArray, isNull, like, lte, sql, sum } from 'drizzle-orm';\nimport {\n type AgentDrizzleDb,\n type AgentRunStatus,\n agentMessage,\n agentRun,\n agentThread,\n agentTokenUsage,\n agentToolCall,\n} from './schema.js';\n\n/** No error code recorded on a failed run (the caller didn't classify it). Groups those together. */\nconst UNCLASSIFIED_ERROR_CODE = 'unknown';\n/** Bucket key for a run with no `agentName` (mirrors {@link RunAgentBreakdownRow}'s contract). */\nconst DEFAULT_AGENT_BUCKET = '(default)';\n\n// The paged where-builders below narrow a wire-typed `string` filter value down to the schema\n// column's literal-union `$type<...>()` before it's used in an `eq()` comparison (an unnarrowed\n// `string` isn't assignable to e.g. `agentToolCall.status`'s type). An unrecognized value can never\n// match a row anyway (the column only ever holds these literals), so the paged method short-circuits\n// to an empty page instead of querying with a value that would trivially return nothing.\nconst TOOL_CALL_STATUSES: readonly string[] = [\n 'auto_executed',\n 'pending_approval',\n 'executed',\n 'rejected',\n 'failed',\n];\nfunction isToolCallStatus(value: string): value is ToolCallStatus {\n return TOOL_CALL_STATUSES.includes(value);\n}\n\nconst TOOL_KINDS: readonly string[] = ['read', 'action', 'agent'];\nfunction isToolKind(value: string): value is ToolKind {\n return TOOL_KINDS.includes(value);\n}\n\nconst RUN_STATUSES: readonly string[] = ['running', 'completed', 'failed', 'cancelled'];\nfunction isRunStatus(value: string): value is AgentRunStatus {\n return RUN_STATUSES.includes(value);\n}\n\n/** Inclusive UTC day start, reusing {@link dayBoundsUtc}'s date math so both bounds parse identically. */\nfunction dayStartUtc(day: string): Date {\n return dayBoundsUtc({ fromDay: day, toDay: day }).start;\n}\n\n/** Inclusive UTC day end, reusing {@link dayBoundsUtc}'s date math so both bounds parse identically. */\nfunction dayEndUtc(day: string): Date {\n return dayBoundsUtc({ fromDay: day, toDay: day }).end;\n}\n\n/** An empty page for the given query's page/pageSize — the shape every paged read falls back to. */\nfunction emptyPage<TRow>(query: GovernancePageQuery<unknown>): GovernancePage<TRow> {\n return { rows: [], total: 0, page: query.page, pageSize: query.pageSize };\n}\n\n/** Map a run row onto the SPI row. Shared by `recentRuns`/`runsPage`/`runDetail`/`threadDetail`. */\nfunction toRecentRunRow(run: typeof agentRun.$inferSelect): RecentRunRow {\n return {\n runId: run.id,\n threadId: run.threadId,\n actorRef: run.actorRef,\n agentName: run.agentName ?? null,\n status: run.status,\n durationMs: run.durationMs ?? null,\n errorCode: run.errorCode ?? null,\n errorMessage: run.errorMessage ?? null,\n retries: run.retries,\n startedAt: run.startedAt.toISOString(),\n promptHash: run.promptHash ?? null,\n parentRunId: run.parentRunId ?? null,\n };\n}\n\n/** Map a tool-call row onto the run drill-down's row (execution outcome, not activity-feed shape). */\nfunction toRunToolCallRow(toolCall: typeof agentToolCall.$inferSelect): RunToolCallRow {\n return {\n toolCallId: toolCall.id,\n toolName: toolCall.toolName,\n toolType: toolCall.toolType,\n status: toolCall.status,\n executionMs: toolCall.executionMs ?? null,\n executedByRef: toolCall.executedByRef ?? null,\n error: toolCall.error ?? null,\n createdAt: toolCall.createdAt.toISOString(),\n };\n}\n\n/** Map a Drizzle usage row onto the shared bucketer input (day derived from `createdAt`). */\nfunction toUsageInput(row: typeof agentTokenUsage.$inferSelect): GovernanceUsageInput {\n return {\n modelId: row.modelId,\n actorRef: row.actorRef,\n threadId: row.threadId,\n day: row.createdAt.toISOString().slice(0, 10),\n inputTokens: row.inputTokens,\n outputTokens: row.outputTokens,\n cacheWriteTokens: row.cacheWriteTokens,\n cacheReadTokens: row.cacheReadTokens,\n costUsd: row.costUsd,\n };\n}\n\n/**\n * MySQL-compatible percentile (no `PERCENTILE_CONT`): index into an ascending-sorted array by\n * offset. `null` when there are no settled durations in range. Shared by every reliability query\n * that reports p50/p95 so the SQL and in-memory adapters compute identically.\n */\nfunction percentileMs(sortedDurationsMs: number[], p: number): number | null {\n if (sortedDurationsMs.length === 0) {\n return null;\n }\n const offset = Math.min(sortedDurationsMs.length - 1, Math.floor(p * sortedDurationsMs.length));\n return sortedDurationsMs[offset] ?? null;\n}\n\n/**\n * {@link AgentGovernanceQueries} backed by Drizzle ORM — the read/analytics half of the store SPI,\n * mirroring {@link import('@dudousxd/nestjs-agent-store-mikro-orm')} exactly. Cost is the token\n * ledger priced against the current prices from the injected {@link AgentPricingStore}\n * (`AGENT_PRICING_STORE`), so a host that binds its own pricing store controls the cost every\n * governance surface reports. An unpriced model contributes 0 cost. Aggregation is in-process (like\n * `quotaToday`) so day-bucketing stays dialect-portable.\n */\nexport class DrizzleGovernanceQueries implements AgentGovernanceQueries {\n constructor(\n private readonly db: AgentDrizzleDb,\n private readonly pricingStore: AgentPricingStore,\n ) {}\n\n private async loadPricing(): Promise<Map<string, ModelPrice>> {\n const prices = await this.pricingStore.listCurrentPrices();\n const pricing = new Map<string, ModelPrice>();\n for (const price of prices) {\n pricing.set(price.modelId, {\n inputPricePer1m: price.inputPricePer1m,\n outputPricePer1m: price.outputPricePer1m,\n cacheWritePricePer1m: price.cacheWritePricePer1m ?? null,\n cacheReadPricePer1m: price.cacheReadPricePer1m ?? null,\n });\n }\n return pricing;\n }\n\n private async usageInRange(range: GovernanceRange): Promise<GovernanceUsageInput[]> {\n const { start, end } = dayBoundsUtc(range);\n const rows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(and(gte(agentTokenUsage.createdAt, start), lte(agentTokenUsage.createdAt, end)));\n return rows.map(toUsageInput);\n }\n\n async spendByModel(range: GovernanceRange): Promise<ModelSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByModel(await this.usageInRange(range), pricing);\n }\n\n async spendByActor(range: GovernanceRange): Promise<ActorSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByActor(await this.usageInRange(range), pricing);\n }\n\n /**\n * Top threads by spend within the range, highest cost first, capped at `limit`. Usage rows for a\n * soft-deleted thread (`deletedAt` set) are excluded — the thread no longer surfaces as a\n * governance target even though its ledger rows survive.\n */\n async spendByThread(range: GovernanceRange, limit: number): Promise<ThreadSpendRow[]> {\n const pricing = await this.loadPricing();\n const rows = await this.usageInRange(range);\n const threadIds = [...new Set(rows.map((row) => row.threadId))];\n if (threadIds.length === 0) {\n return [];\n }\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(and(inArray(agentThread.id, threadIds), isNull(agentThread.deletedAt)));\n const threadsById = new Map<string, ThreadMeta>(\n threads.map((thread) => [thread.id, { title: thread.title, actorRef: thread.actorRef }]),\n );\n return bucketByThread(rows, pricing, threadsById, { limit, includeUnknownThreads: false });\n }\n\n async usageTrend(range: GovernanceRange): Promise<UsageTrendPoint[]> {\n const pricing = await this.loadPricing();\n return bucketUsageTrend(await this.usageInRange(range), pricing);\n }\n\n async recentToolCalls(limit: number): Promise<ToolCallActivityRow[]> {\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n toolType: agentToolCall.toolType,\n status: agentToolCall.status,\n threadId: agentMessage.threadId,\n createdAt: agentToolCall.createdAt,\n runId: agentToolCall.runId,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .orderBy(desc(agentToolCall.createdAt), desc(agentToolCall.id))\n .limit(limit);\n return rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n toolType: row.toolType,\n status: row.status,\n threadId: row.threadId,\n createdAt: row.createdAt.toISOString(),\n runId: row.runId,\n }));\n }\n\n /**\n * Message counts and token totals for a whole set of threads in TWO grouped queries, not two per\n * thread — a 200-row page used to cost four hundred round trips. Mirrors the MikroORM adapter's\n * `threadRollups`, which reaches the same numbers without a QueryBuilder.\n */\n private async threadRollups(\n threadIds: string[],\n ): Promise<Map<string, { messageCount: number; totalTokens: number }>> {\n const rollups = new Map<string, { messageCount: number; totalTokens: number }>(\n threadIds.map((threadId) => [threadId, { messageCount: 0, totalTokens: 0 }]),\n );\n if (threadIds.length === 0) {\n return rollups;\n }\n const messageCounts = await this.db\n .select({ threadId: agentMessage.threadId, value: count() })\n .from(agentMessage)\n .where(inArray(agentMessage.threadId, threadIds))\n .groupBy(agentMessage.threadId);\n for (const row of messageCounts) {\n const bucket = rollups.get(row.threadId);\n if (bucket !== undefined) {\n bucket.messageCount = row.value;\n }\n }\n const usageTotals = await this.db\n .select({\n threadId: agentTokenUsage.threadId,\n inputTokens: sum(agentTokenUsage.inputTokens),\n outputTokens: sum(agentTokenUsage.outputTokens),\n })\n .from(agentTokenUsage)\n .where(inArray(agentTokenUsage.threadId, threadIds))\n .groupBy(agentTokenUsage.threadId);\n for (const row of usageTotals) {\n const bucket = rollups.get(row.threadId);\n if (bucket !== undefined) {\n // Drizzle types SUM() as string|null (a dialect can widen it past a JS number).\n bucket.totalTokens = Number(row.inputTokens ?? 0) + Number(row.outputTokens ?? 0);\n }\n }\n return rollups;\n }\n\n /** Decorate an ordered thread list with its batched rollups, preserving the incoming order. */\n private async toThreadActivityRows(\n threads: (typeof agentThread.$inferSelect)[],\n ): Promise<ThreadActivityRow[]> {\n const rollups = await this.threadRollups(threads.map((thread) => thread.id));\n return threads.map((thread) => {\n const rollup = rollups.get(thread.id);\n return {\n threadId: thread.id,\n title: thread.title,\n actorRef: thread.actorRef,\n messageCount: rollup?.messageCount ?? 0,\n totalTokens: rollup?.totalTokens ?? 0,\n lastActivityAt: thread.updatedAt.toISOString(),\n };\n });\n }\n\n async recentThreads(limit: number): Promise<ThreadActivityRow[]> {\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(isNull(agentThread.deletedAt))\n .orderBy(desc(agentThread.updatedAt), desc(agentThread.id))\n .limit(limit);\n return this.toThreadActivityRows(threads);\n }\n\n private async runsInRange(range: GovernanceRange): Promise<(typeof agentRun.$inferSelect)[]> {\n const { start, end } = dayBoundsUtc(range);\n return this.db\n .select()\n .from(agentRun)\n .where(and(gte(agentRun.startedAt, start), lte(agentRun.startedAt, end)));\n }\n\n async runMetrics(range: GovernanceRange): Promise<RunMetrics> {\n const runs = await this.runsInRange(range);\n let completed = 0;\n let failed = 0;\n let retries = 0;\n const settledDurationsMs: number[] = [];\n for (const run of runs) {\n if (run.status === 'completed') {\n completed += 1;\n } else if (run.status === 'failed') {\n failed += 1;\n }\n retries += run.retries;\n if ((run.status === 'completed' || run.status === 'failed') && run.durationMs != null) {\n settledDurationsMs.push(run.durationMs);\n }\n }\n settledDurationsMs.sort((left, right) => left - right);\n return {\n runs: runs.length,\n completed,\n failed,\n successRate: runs.length === 0 ? 0 : completed / runs.length,\n retries,\n durationP50Ms: percentileMs(settledDurationsMs, 0.5),\n durationP95Ms: percentileMs(settledDurationsMs, 0.95),\n };\n }\n\n async runsByAgent(range: GovernanceRange): Promise<RunAgentBreakdownRow[]> {\n const runs = await this.runsInRange(range);\n const byAgent = new Map<string, { runs: number; failed: number; retries: number }>();\n for (const run of runs) {\n const agentName = run.agentName ?? DEFAULT_AGENT_BUCKET;\n const bucket = byAgent.get(agentName) ?? { runs: 0, failed: 0, retries: 0 };\n bucket.runs += 1;\n bucket.failed += run.status === 'failed' ? 1 : 0;\n bucket.retries += run.retries;\n byAgent.set(agentName, bucket);\n }\n const result: RunAgentBreakdownRow[] = [];\n for (const [agentName, bucket] of byAgent) {\n result.push({ agentName, ...bucket });\n }\n result.sort(\n (left, right) => right.runs - left.runs || left.agentName.localeCompare(right.agentName),\n );\n return result;\n }\n\n async runErrors(range: GovernanceRange): Promise<RunErrorBreakdownRow[]> {\n const { start, end } = dayBoundsUtc(range);\n const runs = await this.db\n .select()\n .from(agentRun)\n .where(\n and(\n gte(agentRun.startedAt, start),\n lte(agentRun.startedAt, end),\n eq(agentRun.status, 'failed'),\n ),\n );\n const byError = new Map<string, number>();\n for (const run of runs) {\n const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;\n byError.set(errorCode, (byError.get(errorCode) ?? 0) + 1);\n }\n const result: RunErrorBreakdownRow[] = [];\n for (const [errorCode, errorCount] of byError) {\n result.push({ errorCode, count: errorCount });\n }\n result.sort(\n (left, right) => right.count - left.count || left.errorCode.localeCompare(right.errorCode),\n );\n return result;\n }\n\n async runTrend(range: GovernanceRange): Promise<RunTrendPoint[]> {\n const runs = await this.runsInRange(range);\n const byDay = new Map<string, { runs: number; failed: number }>();\n for (const run of runs) {\n const day = run.startedAt.toISOString().slice(0, 10);\n const bucket = byDay.get(day) ?? { runs: 0, failed: 0 };\n bucket.runs += 1;\n bucket.failed += run.status === 'failed' ? 1 : 0;\n byDay.set(day, bucket);\n }\n const result: RunTrendPoint[] = [];\n for (const [day, bucket] of byDay) {\n result.push({ day, ...bucket });\n }\n result.sort((left, right) => left.day.localeCompare(right.day));\n return result;\n }\n\n async recentRuns(limit: number): Promise<RecentRunRow[]> {\n const runs = await this.db\n .select()\n .from(agentRun)\n .orderBy(desc(agentRun.startedAt), desc(agentRun.id))\n .limit(limit);\n return runs.map(toRecentRunRow);\n }\n\n /**\n * Tool calls sitting `pending_approval`, oldest first (an inbox drains from the back), joined\n * through their message to the owning thread for title/actorRef and to the message itself for\n * `agentName` (null when the message carries none).\n */\n async pendingApprovals(limit: number): Promise<PendingApprovalRow[]> {\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n input: agentToolCall.input,\n threadId: agentThread.id,\n threadTitle: agentThread.title,\n actorRef: agentThread.actorRef,\n agentName: agentMessage.agentName,\n requestedAt: agentToolCall.createdAt,\n runId: agentToolCall.runId,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.status, 'pending_approval'))\n .orderBy(agentToolCall.createdAt, agentToolCall.id)\n .limit(limit);\n return rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n input: row.input,\n threadId: row.threadId,\n threadTitle: row.threadTitle,\n actorRef: row.actorRef,\n agentName: row.agentName ?? null,\n requestedAt: row.requestedAt.toISOString(),\n runId: row.runId,\n }));\n }\n\n /**\n * Per-tool call/failure/rejection/latency rollup over the range, highest call count first.\n * `p50ExecutionMs`/`p95ExecutionMs` are computed over calls that recorded a non-null `executionMs`\n * (regardless of their final status); both `null` when none did. Percentiles are taken in-process\n * off the sorted sample rather than in SQL, matching the MikroORM adapter — MySQL has no\n * `PERCENTILE_CONT` and one portable implementation beats three dialect-specific ones.\n */\n async toolStats(range: GovernanceRange): Promise<ToolStatRow[]> {\n const { start, end } = dayBoundsUtc(range);\n const calls = await this.db\n .select()\n .from(agentToolCall)\n .where(and(gte(agentToolCall.createdAt, start), lte(agentToolCall.createdAt, end)));\n const byTool = new Map<\n string,\n {\n toolName: string;\n toolType: string;\n calls: number;\n failed: number;\n rejected: number;\n executionMs: number[];\n }\n >();\n for (const call of calls) {\n const key = `${call.toolName} ${call.toolType}`;\n const bucket = byTool.get(key) ?? {\n toolName: call.toolName,\n toolType: call.toolType,\n calls: 0,\n failed: 0,\n rejected: 0,\n executionMs: [],\n };\n bucket.calls += 1;\n bucket.failed += call.status === 'failed' ? 1 : 0;\n bucket.rejected += call.status === 'rejected' ? 1 : 0;\n if (call.executionMs != null) {\n bucket.executionMs.push(call.executionMs);\n }\n byTool.set(key, bucket);\n }\n const result: ToolStatRow[] = [];\n for (const bucket of byTool.values()) {\n bucket.executionMs.sort((left, right) => left - right);\n result.push({\n toolName: bucket.toolName,\n toolType: bucket.toolType,\n calls: bucket.calls,\n failed: bucket.failed,\n rejected: bucket.rejected,\n p50ExecutionMs: percentileMs(bucket.executionMs, 0.5),\n p95ExecutionMs: percentileMs(bucket.executionMs, 0.95),\n });\n }\n result.sort(\n (left, right) => right.calls - left.calls || left.toolName.localeCompare(right.toolName),\n );\n return result;\n }\n\n /**\n * Paged, filterable tool-call activity, newest-first (same ordering as {@link recentToolCalls}).\n * `toolType`/`status` values outside the known literals can never match a row — short-circuits to\n * an empty page rather than issuing a query. Joins `agent_message` unconditionally (like\n * `recentToolCalls`) to resolve `threadId` and to support the `threadId` filter.\n */\n async toolCallsPage(\n query: GovernancePageQuery<ToolCallWhere>,\n ): Promise<GovernancePage<ToolCallActivityRow>> {\n const filters = query.where;\n if (filters?.status !== undefined && !isToolCallStatus(filters.status)) {\n return emptyPage(query);\n }\n if (filters?.toolType !== undefined && !isToolKind(filters.toolType)) {\n return emptyPage(query);\n }\n const whereClause = and(\n filters?.toolName !== undefined ? eq(agentToolCall.toolName, filters.toolName) : undefined,\n filters?.toolType !== undefined && isToolKind(filters.toolType)\n ? eq(agentToolCall.toolType, filters.toolType)\n : undefined,\n filters?.status !== undefined && isToolCallStatus(filters.status)\n ? eq(agentToolCall.status, filters.status)\n : undefined,\n filters?.threadId !== undefined ? eq(agentMessage.threadId, filters.threadId) : undefined,\n filters?.fromDay !== undefined\n ? gte(agentToolCall.createdAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(agentToolCall.createdAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .where(whereClause);\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n toolType: agentToolCall.toolType,\n status: agentToolCall.status,\n threadId: agentMessage.threadId,\n createdAt: agentToolCall.createdAt,\n runId: agentToolCall.runId,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .where(whereClause)\n .orderBy(desc(agentToolCall.createdAt), desc(agentToolCall.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize);\n return {\n rows: rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n toolType: row.toolType,\n status: row.status,\n threadId: row.threadId,\n createdAt: row.createdAt.toISOString(),\n runId: row.runId,\n })),\n total: totalRow?.value ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n };\n }\n\n /**\n * Paged, filterable thread activity, newest-first (same ordering as {@link recentThreads}).\n * `title` is a case-insensitive substring match via `lower(...)` on both sides (portable across\n * dialects, regardless of the underlying column collation). Soft-deleted threads are excluded,\n * mirroring `recentThreads`.\n */\n async threadsPage(\n query: GovernancePageQuery<ThreadWhere>,\n ): Promise<GovernancePage<ThreadActivityRow>> {\n const filters = query.where;\n const whereClause = and(\n isNull(agentThread.deletedAt),\n filters?.actorRef !== undefined ? eq(agentThread.actorRef, filters.actorRef) : undefined,\n filters?.title !== undefined\n ? like(sql`lower(${agentThread.title})`, `%${filters.title.toLowerCase()}%`)\n : undefined,\n filters?.fromDay !== undefined\n ? gte(agentThread.updatedAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(agentThread.updatedAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(agentThread)\n .where(whereClause);\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(whereClause)\n .orderBy(desc(agentThread.updatedAt), desc(agentThread.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize);\n const rows = await this.toThreadActivityRows(threads);\n return { rows, total: totalRow?.value ?? 0, page: query.page, pageSize: query.pageSize };\n }\n\n /**\n * Paged, filterable run activity, newest-first (same ordering as {@link recentRuns}). `status`\n * values outside the known literals can never match a row — short-circuits to an empty page.\n */\n async runsPage(query: GovernancePageQuery<RunWhere>): Promise<GovernancePage<RecentRunRow>> {\n const filters = query.where;\n if (filters?.status !== undefined && !isRunStatus(filters.status)) {\n return emptyPage(query);\n }\n const whereClause = and(\n filters?.agentName !== undefined ? eq(agentRun.agentName, filters.agentName) : undefined,\n filters?.status !== undefined && isRunStatus(filters.status)\n ? eq(agentRun.status, filters.status)\n : undefined,\n filters?.errorCode !== undefined ? eq(agentRun.errorCode, filters.errorCode) : undefined,\n filters?.threadId !== undefined ? eq(agentRun.threadId, filters.threadId) : undefined,\n filters?.fromDay !== undefined\n ? gte(agentRun.startedAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined ? lte(agentRun.startedAt, dayEndUtc(filters.toDay)) : undefined,\n );\n const [totalRow] = await this.db.select({ value: count() }).from(agentRun).where(whereClause);\n const runs = await this.db\n .select()\n .from(agentRun)\n .where(whereClause)\n .orderBy(desc(agentRun.startedAt), desc(agentRun.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize);\n return {\n rows: runs.map(toRecentRunRow),\n total: totalRow?.value ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n };\n }\n\n /**\n * Paged, filterable approvals inbox, oldest first — the same ordering as {@link pendingApprovals},\n * now with the `total` that method structurally cannot report. The join to `agent_message` /\n * `agent_thread` is unconditional (it already resolves title/actor/agentName), so the `threadId`/\n * `actorRef`/`agentName` filters cost nothing extra.\n *\n * The order is TOTAL (`created_at asc, id asc`, and `id` is the primary key), so no row can land on\n * two pages or on none for a given snapshot. Ascending order also means a newly requested approval\n * appends past the last page instead of shifting the page an operator is currently reading.\n */\n async approvalsPage(\n query: GovernancePageQuery<ApprovalWhere>,\n ): Promise<GovernancePage<PendingApprovalRow>> {\n const filters = query.where;\n const whereClause = and(\n eq(agentToolCall.status, 'pending_approval'),\n filters?.toolName !== undefined ? eq(agentToolCall.toolName, filters.toolName) : undefined,\n filters?.threadId !== undefined ? eq(agentThread.id, filters.threadId) : undefined,\n filters?.actorRef !== undefined ? eq(agentThread.actorRef, filters.actorRef) : undefined,\n filters?.agentName !== undefined ? eq(agentMessage.agentName, filters.agentName) : undefined,\n filters?.fromDay !== undefined\n ? gte(agentToolCall.createdAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(agentToolCall.createdAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(whereClause);\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n input: agentToolCall.input,\n threadId: agentThread.id,\n threadTitle: agentThread.title,\n actorRef: agentThread.actorRef,\n agentName: agentMessage.agentName,\n requestedAt: agentToolCall.createdAt,\n runId: agentToolCall.runId,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(whereClause)\n .orderBy(asc(agentToolCall.createdAt), asc(agentToolCall.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize);\n return {\n rows: rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n input: row.input,\n threadId: row.threadId,\n threadTitle: row.threadTitle,\n actorRef: row.actorRef,\n agentName: row.agentName ?? null,\n requestedAt: row.requestedAt.toISOString(),\n runId: row.runId,\n })),\n total: totalRow?.value ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n };\n }\n\n /**\n * One run, its owning thread's headline and its tool calls — TWO queries regardless of how many\n * tools the run called. `toolCalls` comes off `agent_tool_call.run_id`, so a run recorded before\n * that column was written reports none.\n */\n async runDetail(runId: string): Promise<GovernanceRunDetail | null> {\n const [row] = await this.db\n .select({ run: agentRun, thread: agentThread })\n .from(agentRun)\n .innerJoin(agentThread, eq(agentRun.threadId, agentThread.id))\n .where(eq(agentRun.id, runId))\n .limit(1);\n if (row === undefined) {\n return null;\n }\n const toolCalls = await this.db\n .select()\n .from(agentToolCall)\n .where(eq(agentToolCall.runId, runId))\n .orderBy(asc(agentToolCall.createdAt), asc(agentToolCall.id));\n return {\n run: toRecentRunRow(row.run),\n thread: {\n threadId: row.thread.id,\n title: row.thread.title,\n actorRef: row.thread.actorRef,\n deleted: row.thread.deletedAt != null,\n },\n toolCalls: toolCalls.map(toRunToolCallRow),\n };\n }\n\n /**\n * One thread with its lifetime usage rollup, its newest runs and its newest messages. A fixed six\n * queries (thread, usage, message count, message page, that page's tool-call counts, runs+count) —\n * the per-message tool-call counts are ONE grouped read over the returned message ids, not one per\n * message. Soft-deleted threads are returned with `deleted: true`; an audit still needs them.\n */\n async threadDetail(query: GovernanceThreadDetailQuery): Promise<GovernanceThreadDetail | null> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(eq(agentThread.id, query.threadId))\n .limit(1);\n if (thread === undefined) {\n return null;\n }\n const pricing = await this.loadPricing();\n const usageRows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(eq(agentTokenUsage.threadId, thread.id));\n const usage = rollupThreadUsage(usageRows.map(toUsageInput), pricing);\n const [messageCountRow] = await this.db\n .select({ value: count() })\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id));\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id))\n .orderBy(desc(agentMessage.createdAt), desc(agentMessage.id))\n .limit(query.messageLimit);\n const toolCallCounts = await this.toolCallCountsByMessage(\n messages.map((message) => message.id),\n );\n const [runTotalRow] = await this.db\n .select({ value: count() })\n .from(agentRun)\n .where(eq(agentRun.threadId, thread.id));\n const runs = await this.db\n .select()\n .from(agentRun)\n .where(eq(agentRun.threadId, thread.id))\n .orderBy(desc(agentRun.startedAt), desc(agentRun.id))\n .limit(query.runLimit);\n return {\n thread: {\n threadId: thread.id,\n title: thread.title,\n actorRef: thread.actorRef,\n messageCount: messageCountRow?.value ?? 0,\n totalTokens: usage.totalTokens,\n lastActivityAt: thread.updatedAt.toISOString(),\n },\n deleted: thread.deletedAt != null,\n usage,\n runs: runs.map(toRecentRunRow),\n runTotal: runTotalRow?.value ?? 0,\n messages: messages.map((message): ThreadMessageRow => {\n const { content, truncated } = truncateDetailContent(message.content);\n return {\n messageId: message.id,\n role: message.role,\n content,\n truncated,\n agentName: message.agentName ?? null,\n toolCallCount: toolCallCounts.get(message.id) ?? 0,\n createdAt: message.createdAt.toISOString(),\n };\n }),\n };\n }\n\n /** Tool-call counts for a set of messages in ONE grouped query — the detail view's no-N+1 guarantee. */\n private async toolCallCountsByMessage(messageIds: string[]): Promise<Map<string, number>> {\n const counts = new Map<string, number>();\n if (messageIds.length === 0) {\n return counts;\n }\n const rows = await this.db\n .select({ messageId: agentToolCall.messageId, value: count() })\n .from(agentToolCall)\n .where(inArray(agentToolCall.messageId, messageIds))\n .groupBy(agentToolCall.messageId);\n for (const row of rows) {\n counts.set(row.messageId, row.value);\n }\n return counts;\n }\n}\n","import type {\n AgentPricingStore,\n CurrentModelPrice,\n ModelPriceInput,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, eq } from 'drizzle-orm';\nimport { type AgentDrizzleDb, agentModelPricing } from './schema.js';\n\n/**\n * {@link AgentPricingStore} backed by Drizzle ORM — the write side of the pricing table\n * {@link import('./drizzle-governance-queries.js').DrizzleGovernanceQueries} joins against. A POJO\n * receiving a Drizzle SQLite database handle (the host app owns the connection), mirroring\n * {@link import('@dudousxd/nestjs-agent-store-mikro-orm')} exactly (atomic supersede semantics).\n */\nexport class DrizzlePricingStore implements AgentPricingStore {\n constructor(private readonly db: AgentDrizzleDb) {}\n\n async upsertModelPrice(input: ModelPriceInput): Promise<void> {\n await this.db\n .update(agentModelPricing)\n .set({ isCurrent: false })\n .where(\n and(eq(agentModelPricing.modelId, input.modelId), eq(agentModelPricing.isCurrent, true)),\n );\n await this.db.insert(agentModelPricing).values({\n id: crypto.randomUUID(),\n modelId: input.modelId,\n inputPricePer1m: input.inputPricePer1m,\n outputPricePer1m: input.outputPricePer1m,\n cacheWritePricePer1m: input.cacheWritePricePer1m ?? null,\n cacheReadPricePer1m: input.cacheReadPricePer1m ?? null,\n effectiveFrom: new Date(),\n isCurrent: true,\n });\n }\n\n async listCurrentPrices(): Promise<CurrentModelPrice[]> {\n const rows = await this.db\n .select()\n .from(agentModelPricing)\n .where(eq(agentModelPricing.isCurrent, true));\n return rows.map((row) => ({\n modelId: row.modelId,\n inputPricePer1m: row.inputPricePer1m,\n outputPricePer1m: row.outputPricePer1m,\n effectiveFrom: row.effectiveFrom.toISOString(),\n ...(row.cacheWritePricePer1m != null\n ? { cacheWritePricePer1m: row.cacheWritePricePer1m }\n : {}),\n ...(row.cacheReadPricePer1m != null ? { cacheReadPricePer1m: row.cacheReadPricePer1m } : {}),\n }));\n }\n}\n","import {\n AGENT_GOVERNANCE_QUERIES,\n AGENT_PRICING_STORE,\n AGENT_STORE,\n type AgentPricingStore,\n} from '@dudousxd/nestjs-agent-core';\nimport { type DynamicModule, Module, type Type } from '@nestjs/common';\nimport { DrizzleAgentStore } from './drizzle-agent-store.js';\nimport { DrizzleGovernanceQueries } from './drizzle-governance-queries.js';\nimport { DrizzlePricingStore } from './drizzle-pricing-store.js';\nimport type { AgentDrizzleDb } from './schema.js';\n\n/** Options for {@link DrizzleAgentStoreModule.forRoot}. The app owns and supplies the db handle. */\nexport interface DrizzleAgentStoreModuleOptions {\n /** A Drizzle SQLite database instance (`drizzle(client, { schema: agentSchema })`). */\n db: AgentDrizzleDb;\n /**\n * Bind {@link AGENT_PRICING_STORE} (which {@link DrizzleGovernanceQueries} prices usage against) to\n * a host-supplied store instead of the default {@link DrizzlePricingStore} — make your OWN pricing\n * table the single source of cost truth without touching `agent_model_pricing`.\n */\n pricingStore?: Type<AgentPricingStore>;\n}\n\n/**\n * Binds {@link DrizzleAgentStore} to the {@link AGENT_STORE} token consumed by\n * `@dudousxd/nestjs-agent`, plus {@link DrizzleGovernanceQueries} to\n * {@link AGENT_GOVERNANCE_QUERIES} (the read-model the dashboard/telescope surfaces consume) and\n * {@link DrizzlePricingStore} to {@link AGENT_PRICING_STORE} (the write side of that pricing table).\n * The host app supplies an already-opened Drizzle db — this module never opens a connection itself.\n *\n * The returned module is global, so {@link AGENT_STORE}, {@link AGENT_GOVERNANCE_QUERIES} and\n * {@link AGENT_PRICING_STORE} are visible app-wide — `AgentModule` resolves the store without an\n * explicit `store` option, and the dashboard/telescope resolve {@link AGENT_GOVERNANCE_QUERIES}\n * without the host re-binding it.\n *\n * ```ts\n * @Module({ imports: [DrizzleAgentStoreModule.forRoot({ db })] })\n * export class AppModule {}\n * ```\n */\n@Module({})\nexport class DrizzleAgentStoreModule {\n static forRoot(options: DrizzleAgentStoreModuleOptions): DynamicModule {\n return {\n module: DrizzleAgentStoreModule,\n global: true,\n providers: [\n { provide: DrizzleAgentStore, useFactory: () => new DrizzleAgentStore(options.db) },\n { provide: AGENT_STORE, useExisting: DrizzleAgentStore },\n {\n provide: DrizzlePricingStore,\n useFactory: () => new DrizzlePricingStore(options.db),\n },\n // AGENT_PRICING_STORE: the host's own store when supplied, else the default Drizzle one.\n // DrizzleGovernanceQueries prices usage against whatever is bound here.\n options.pricingStore\n ? { provide: AGENT_PRICING_STORE, useClass: options.pricingStore }\n : { provide: AGENT_PRICING_STORE, useExisting: DrizzlePricingStore },\n {\n provide: DrizzleGovernanceQueries,\n useFactory: (pricingStore: AgentPricingStore) =>\n new DrizzleGovernanceQueries(options.db, pricingStore),\n inject: [AGENT_PRICING_STORE],\n },\n { provide: AGENT_GOVERNANCE_QUERIES, useExisting: DrizzleGovernanceQueries },\n ],\n exports: [\n DrizzleAgentStore,\n AGENT_STORE,\n DrizzleGovernanceQueries,\n AGENT_GOVERNANCE_QUERIES,\n DrizzlePricingStore,\n AGENT_PRICING_STORE,\n ],\n };\n }\n}\n"],"mappings":";;;;AAWA,SAEEA,OACAC,SACAC,MACAC,aACAC,YACK;AAeA,IAAMC,cAAcF,YACzB,gBACA;EACEG,IAAIF,KAAK,IAAA,EAAMG,WAAU;EACzBC,UAAUJ,KAAK,WAAA,EAAaK,QAAO;EACnCC,WAAWN,KAAK,YAAA;EAChBO,OAAOP,KAAK,OAAA,EAASK,QAAO;EAC5BG,WAAWX,QAAQ,aAAa;IAAEY,MAAM;EAAU,CAAA,EAAGJ,QAAO,EAAGK,QAAQ,KAAA;EACvEC,gBAAgBX,KAAK,kBAAA;;EAErBY,cAAcZ,KAAK,eAAA;EACnBa,WAAWhB,QAAQ,cAAc;IAAEY,MAAM;EAAe,CAAA,EAAGJ,QAAO;EAClES,WAAWjB,QAAQ,cAAc;IAAEY,MAAM;EAAe,CAAA,EAAGJ,QAAO;EAClEU,WA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E,GAAxC;QACd;;;QAGAP,QAAQW,eACJ;UAAEP,SAASQ;UAAqBC,UAAUb,QAAQW;QAAa,IAC/D;UAAEP,SAASQ;UAAqBH,aAAaC;QAAoB;QACrE;UACEN,SAASU;UACTR,YAAY,wBAACK,iBACX,IAAIG,yBAAyBd,QAAQO,IAAII,YAAAA,GAD/B;UAEZI,QAAQ;YAACH;;QACX;QACA;UAAER,SAASY;UAA0BP,aAAaK;QAAyB;;MAE7EG,SAAS;QACPZ;QACAG;QACAM;QACAE;QACAN;QACAE;;IAEJ;EACF;AACF;;;;","names":["index","integer","real","sqliteTable","text","agentThread","id","primaryKey","actorRef","notNull","tenantRef","title","transient","mode","default","activeStreamId","defaultAgent","createdAt","updatedAt","deletedAt","table","on","agentMessage","threadId","references","onDelete","role","$type","content","toolCalls","toolResults","attachments","followUps","usage","agentName","runId","agentToolCall","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentRun","durationMs","errorCode","errorMessage","retries","startedAt","settledAt","promptHash","parentRunId","agentSchema","sql","statements","additiveColumns","table","column","ddl","ensureAgentSchema","db","statement","run","sql","raw","existing","all","some","row","name","and","asc","desc","eq","gte","inArray","isNotNull","isNull","lte","sql","TURN_MESSAGE_COLUMNS","id","agentMessage","role","content","agentName","toolCalls","toolResults","attachments","createdAt","DrizzleAgentStore","db","createThread","input","now","Date","thread","crypto","randomUUID","actorRef","actor","tenantRef","title","transient","activeStreamId","defaultAgent","updatedAt","deletedAt","insert","agentThread","values","toSummary","getThread","threadId","select","from","where","and","eq","isNull","undefined","messages","orderBy","asc","last","length","map","message","toStoredMessage","loadThreadForTurn","query","loadTurnWindow","messageLimit","answered","limit","hasAssistantMessage","window","desc","rows","reverse","row","listThreads","threads","summaries","push","softDeleteThread","update","set","forkThread","fromMessageId","source","Error","cutoff","findIndex","kept","slice","fork","followUps","usage","runId","ownerOfThread","ownerOfToolCall","toolCallId","agentToolCall","innerJoin","messageId","runForToolCall","ownerOfActiveStream","setTitle","promoteThread","setActiveStream","updateThread","patch","updates","Object","keys","defaultAgentForThread","recordRunStart","run","runRow","status","durationMs","errorCode","errorMessage","retries","startedAt","settledAt","promptHash","parentRunId","agentRun","recordRunEnd","end","bumpRunRetries","sql","appendMessage","setMessageToolResults","results","truncateFrom","doomedIds","delete","inArray","recordToolCall","toolName","toolType","output","executedByRef","executionMs","error","executedAt","updateToolCall","referencedMediaIds","mediaIds","isNotNull","wanted","Set","found","attachment","has","mediaId","add","filter","recordUsage","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","quotaToday","day","start","gte","lte","usedTokens","reduce","sum","lastContent","toISOString","lastMessagePreview","bucketByActor","bucketByModel","bucketByThread","bucketUsageTrend","dayBoundsUtc","rollupThreadUsage","truncateDetailContent","and","asc","count","desc","eq","gte","inArray","isNull","like","lte","sql","sum","UNCLASSIFIED_ERROR_CODE","DEFAULT_AGENT_BUCKET","TOOL_CALL_STATUSES","isToolCallStatus","value","includes","TOOL_KINDS","isToolKind","RUN_STATUSES","isRunStatus","dayStartUtc","day","dayBoundsUtc","fromDay","toDay","start","dayEndUtc","end","emptyPage","query","rows","total","page","pageSize","toRecentRunRow","run","runId","id","threadId","actorRef","agentName","status","durationMs","errorCode","errorMessage","retries","startedAt","toISOString","promptHash","parentRunId","toRunToolCallRow","toolCall","toolCallId","toolName","toolType","executionMs","executedByRef","error","createdAt","toUsageInput","row","modelId","slice","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","percentileMs","sortedDurationsMs","p","length","offset","Math","min","floor","DrizzleGovernanceQueries","db","pricingStore","loadPricing","prices","listCurrentPrices","pricing","Map","price","set","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","usageInRange","range","select","from","agentTokenUsage","where","and","gte","lte","map","spendByModel","bucketByModel","spendByActor","bucketByActor","spendByThread","limit","threadIds","Set","threads","agentThread","inArray","isNull","deletedAt","threadsById","thread","title","bucketByThread","includeUnknownThreads","usageTrend","bucketUsageTrend","recentToolCalls","agentToolCall","agentMessage","innerJoin","eq","messageId","orderBy","desc","threadRollups","rollups","messageCount","totalTokens","messageCounts","count","groupBy","bucket","get","undefined","usageTotals","sum","Number","toThreadActivityRows","rollup","lastActivityAt","updatedAt","recentThreads","runsInRange","agentRun","runMetrics","runs","completed","failed","settledDurationsMs","push","sort","left","right","successRate","durationP50Ms","durationP95Ms","runsByAgent","byAgent","result","localeCompare","runErrors","byError","errorCount","runTrend","byDay","recentRuns","pendingApprovals","input","threadTitle","requestedAt","toolStats","calls","byTool","call","key","rejected","values","p50ExecutionMs","p95ExecutionMs","toolCallsPage","filters","whereClause","totalRow","threadsPage","like","sql","toLowerCase","runsPage","approvalsPage","asc","runDetail","toolCalls","deleted","threadDetail","usageRows","usage","rollupThreadUsage","messageCountRow","messages","messageLimit","toolCallCounts","toolCallCountsByMessage","message","runTotalRow","runLimit","runTotal","content","truncated","truncateDetailContent","role","toolCallCount","messageIds","counts","and","eq","DrizzlePricingStore","db","upsertModelPrice","input","update","agentModelPricing","set","isCurrent","where","and","eq","modelId","insert","values","id","crypto","randomUUID","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","Date","listCurrentPrices","rows","select","from","map","row","toISOString","AGENT_GOVERNANCE_QUERIES","AGENT_PRICING_STORE","AGENT_STORE","Module","DrizzleAgentStoreModule","forRoot","options","module","global","providers","provide","DrizzleAgentStore","useFactory","db","AGENT_STORE","useExisting","DrizzlePricingStore","pricingStore","AGENT_PRICING_STORE","useClass","DrizzleGovernanceQueries","inject","AGENT_GOVERNANCE_QUERIES","exports"]}
1
+ {"version":3,"sources":["../src/schema.ts","../src/ensure-schema.ts","../src/drizzle-agent-store.ts","../src/drizzle-governance-queries.ts","../src/drizzle-memory-provider.ts","../src/drizzle-pricing-store.ts","../src/drizzle-rag-ingestion-log.ts","../src/drizzle-agent-store.module.ts"],"sourcesContent":["import type {\n MemoryOrigin,\n MessageAttachment,\n MessageRole,\n MessageUsage,\n ToolCallRequest,\n ToolCallStatus,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport type { TablesRelationalConfig } from 'drizzle-orm';\nimport {\n type BaseSQLiteDatabase,\n index,\n integer,\n real,\n sqliteTable,\n text,\n uniqueIndex,\n} from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle schema mirroring the MikroORM agent entities (same logical columns/relations):\n * threads, messages, tool calls, token usage, model pricing, run outcomes and the RAG ingestion\n * ledger. Targets the SQLite core so the\n * db-test runs on an in-memory better-sqlite3; timestamps are stored as integer epoch-ms columns\n * (`{ mode: 'timestamp_ms' }`) which Drizzle round-trips to/from JS `Date`, and the model-facing\n * message extras (tool calls/results, follow-ups, usage) live in JSON `text` columns.\n */\n\n/**\n * A conversation thread. `deletedAt` drives soft delete: a deleted thread is hidden from\n * {@link import('./drizzle-agent-store.js').DrizzleAgentStore.getThread}/`listThreads` but its\n * row survives.\n */\nexport const agentThread = sqliteTable(\n 'agent_thread',\n {\n id: text('id').primaryKey(),\n actorRef: text('actor_ref').notNull(),\n tenantRef: text('tenant_ref'),\n title: text('title').notNull(),\n transient: integer('transient', { mode: 'boolean' }).notNull().default(false),\n activeStreamId: text('active_stream_id'),\n /** The agent a new turn on this thread defaults to when the caller names none. */\n defaultAgent: text('default_agent'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n deletedAt: integer('deleted_at', { mode: 'timestamp_ms' }),\n },\n (table) => [index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt)],\n);\n\n/**\n * One stored message in a thread. The model-facing extras (`toolCalls`/`toolResults`/\n * `followUps`/`usage`) are folded into nullable JSON columns so a single row round-trips to a\n * {@link import('@dudousxd/nestjs-agent-core').StoredMessage}. `threadId` cascades on delete.\n */\nexport const agentMessage = sqliteTable(\n 'agent_message',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n role: text('role').$type<MessageRole>().notNull(),\n content: text('content').notNull(),\n toolCalls: text('tool_calls', { mode: 'json' }).$type<ToolCallRequest[]>(),\n toolResults: text('tool_results', { mode: 'json' }).$type<ToolResult[]>(),\n attachments: text('attachments', { mode: 'json' }).$type<MessageAttachment[]>(),\n followUps: text('follow_ups', { mode: 'json' }).$type<string[]>(),\n usage: text('usage', { mode: 'json' }).$type<MessageUsage>(),\n agentName: text('agent_name'),\n runId: text('run_id'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_message_thread_created_idx').on(table.threadId, table.createdAt)],\n);\n\n/**\n * A tool call requested during an assistant turn. The pk is the model-supplied `toolCallId`.\n *\n * `messageId` carries its own index rather than relying on the foreign key: MySQL indexes a foreign\n * key column for you, Postgres does not — and every message-scoped read here filters on it (the\n * thread reader's `IN (…)` over a turn's calls, and `truncateFrom`'s delete).\n */\nexport const agentToolCall = sqliteTable(\n 'agent_tool_call',\n {\n id: text('id').primaryKey(),\n messageId: text('message_id')\n .notNull()\n .references(() => agentMessage.id, { onDelete: 'cascade' }),\n toolName: text('tool_name').notNull(),\n toolType: text('tool_type').$type<ToolKind>().notNull(),\n input: text('input', { mode: 'json' }),\n output: text('output', { mode: 'json' }),\n status: text('status').$type<ToolCallStatus>().notNull(),\n executedByRef: text('executed_by_ref'),\n executionMs: integer('execution_ms'),\n error: text('error'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n executedAt: integer('executed_at', { mode: 'timestamp_ms' }),\n /** The run (turn) this call belongs to, for a trace deep-link; null for a pre-rollout row. */\n runId: text('run_id'),\n },\n (table) => [index('agent_tool_call_message_idx').on(table.messageId)],\n);\n\n/** A token-usage ledger row, summed per actor per day by `quotaToday`. */\nexport const agentTokenUsage = sqliteTable(\n 'agent_token_usage',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: text('actor_ref').notNull(),\n messageId: text('message_id'),\n modelId: text('model_id').notNull(),\n purpose: text('purpose').$type<UsagePurpose>().notNull(),\n inputTokens: integer('input_tokens').notNull(),\n outputTokens: integer('output_tokens').notNull(),\n /** Subset of `inputTokens` written to the prompt cache this turn; null when not reported. */\n cacheWriteTokens: integer('cache_write_tokens'),\n /** Subset of `inputTokens` served from the prompt cache this turn; null when not reported. */\n cacheReadTokens: integer('cache_read_tokens'),\n /** Provider-reported actual USD cost for the turn; null when only tokens were reported. */\n costUsd: real('cost_usd'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt)],\n);\n\n/** Per-model token pricing, versioned by `effectiveFrom`; `isCurrent` flags the live row. */\nexport const agentModelPricing = sqliteTable('agent_model_pricing', {\n id: text('id').primaryKey(),\n modelId: text('model_id').notNull(),\n inputPricePer1m: real('input_price_per_1m').notNull(),\n outputPricePer1m: real('output_price_per_1m').notNull(),\n /** Per-1M price for cache-write input tokens; null → price them at the input rate. */\n cacheWritePricePer1m: real('cache_write_price_per_1m'),\n /** Per-1M price for cache-read input tokens; null → price them at the input rate. */\n cacheReadPricePer1m: real('cache_read_price_per_1m'),\n effectiveFrom: integer('effective_from', { mode: 'timestamp_ms' }).notNull(),\n isCurrent: integer('is_current', { mode: 'boolean' }).notNull(),\n});\n\n/**\n * A run's lifecycle status. Not part of the core SPI (that surfaces `string`) — internal only.\n *\n * `cancelled` is a third TERMINAL, not a flavour of `failed`: someone asked the run to stop and it\n * did. A reliability read that folded it into `failed` would page whoever is on call for model\n * failures every time a user pressed Stop.\n */\nexport type AgentRunStatus = 'running' | 'completed' | 'failed' | 'cancelled';\n\n/**\n * One recorded run (turn) outcome — the durable half of what `aviary:agent:*` diagnostics report\n * ephemerally. Written by {@link import('./drizzle-agent-store.js').DrizzleAgentStore.recordRunStart}/\n * `recordRunEnd`/`bumpRunRetries`, read by\n * {@link import('./drizzle-governance-queries.js').DrizzleGovernanceQueries} for the reliability\n * surfaces (success rate, error breakdown, duration percentiles, trend, recent runs). `threadId`\n * cascades on delete, like `agent_message`/`agent_token_usage`.\n */\nexport const agentRun = sqliteTable(\n 'agent_run',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: text('actor_ref').notNull(),\n agentName: text('agent_name'),\n status: text('status').$type<AgentRunStatus>().notNull(),\n durationMs: integer('duration_ms'),\n errorCode: text('error_code'),\n errorMessage: text('error_message'),\n retries: integer('retries').notNull().default(0),\n startedAt: integer('started_at', { mode: 'timestamp_ms' }).notNull(),\n settledAt: integer('settled_at', { mode: 'timestamp_ms' }),\n /** sha256 hex of the run's resolved (pre-RAG) system prompt; null for a pre-existing run. */\n promptHash: text('prompt_hash'),\n /**\n * The run that delegated this one; null for a turn nobody delegated. The durable runtime's\n * journal holds the same edge, but only there — this column is what lets a reader of run ROWS\n * build the delegation tree and roll a child's cost up to the turn that asked for it, including\n * for a detached child, which outlives its parent's turn and so is paired by nothing in the\n * transcript.\n */\n parentRunId: text('parent_run_id'),\n },\n (table) => [index('agent_run_started_idx').on(table.startedAt)],\n);\n\n/**\n * One thing the assistant believes, held at one scope — the row behind a core `MemoryRecord`.\n *\n * `scope` is an OPAQUE token the host mints (`actor:…`, `tenant:…`, whatever axis a deployment scopes\n * by), which is what lets this package own the table at all: there is nothing here for a host to\n * relate its own entities to, so owning the rows takes nothing away from it.\n *\n * The origin is flattened into columns rather than stored as JSON so a host's console can filter and\n * sweep on it. `originThreadId` is deliberately NOT a foreign key — unlike every other table here,\n * which cascades off `agent_thread`: a memory outlives the conversation it came from, and a cascade\n * would delete beliefs when a transcript aged out.\n *\n * One unique index, on (`scope`, `key`) — what `write` upserts against, and what makes a duplicate\n * answer to one question impossible rather than merely unlikely. It doubles as the index every read\n * uses: `list` filters `scope in (…)`, which is that index's leading column, so a second index on\n * `scope` alone would be maintained on every write and read by nothing.\n */\nexport const agentMemory = sqliteTable(\n 'agent_memory',\n {\n id: text('id').primaryKey(),\n /** The opaque scope token. Unique with `key`: one fact per key per scope. */\n scope: text('scope').notNull(),\n /** What the fact is ABOUT. Two scopes sharing a key are one question answered twice. */\n key: text('key').notNull(),\n /** The fact itself, one line, as the model reads it. */\n text: text('text').notNull(),\n originAuthor: text('origin_author').$type<MemoryOrigin['author']>().notNull(),\n /** A pointer that is allowed to dangle — see the table note. */\n originThreadId: text('origin_thread_id'),\n originRunId: text('origin_run_id'),\n originActorRef: text('origin_actor_ref'),\n /** Always-on: carried in every prompt. Set by a host's console, never by a write. */\n pinned: integer('pinned', { mode: 'boolean' }).notNull().default(false),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [uniqueIndex('agent_memory_scope_key_uq').on(table.scope, table.key)],\n);\n/** The terminal states an ingestion attempt can land in. Mirrors `MediaIngestOutcome`. */\nexport type RagIngestionStatus = 'ingested' | 'skipped' | 'failed' | 'removed';\n\n/**\n * The latest ingestion outcome for one RAG document — one row per document id, overwritten on\n * re-ingest by {@link import('./drizzle-rag-ingestion-log.js').DrizzleRagIngestionLog}.\n *\n * This exists because the vector store can only enumerate what it *has*: a document whose extraction\n * produced no text, whose mime type had no extractor, or whose embedding call blew up has zero chunks\n * and is therefore invisible to `VectorStore.listDocuments()`. Without this table, a scanned PDF that\n * silently failed to index is indistinguishable from one that was never uploaded.\n *\n * `collection` / `ownerType` / `ownerId` are opaque strings copied off the diagnostics payload — this\n * package never interprets them, and deliberately has no foreign key to a host's own collection\n * table, which it cannot know about. The index on (`collection`, `updated_at`) is what the\n * per-collection listing reads.\n */\nexport const ragIngestionLog = sqliteTable(\n 'rag_ingestion_log',\n {\n /** The vector-store document id (chunk ids are `${documentId}#<n>`). */\n documentId: text('document_id').primaryKey(),\n status: text('status').$type<RagIngestionStatus>().notNull(),\n collection: text('collection'),\n ownerType: text('owner_type'),\n ownerId: text('owner_id'),\n /** Citation-facing origin — the media record's path. */\n source: text('source'),\n mimeType: text('mime_type'),\n size: integer('size'),\n /** Chunk count on `ingested`; null otherwise. */\n chunks: integer('chunks'),\n /** Skip reason on `skipped` (`unsupported-type` | `too-large` | `empty-text`); null otherwise. */\n reason: text('reason'),\n /** Error message on `failed`; null otherwise. */\n error: text('error'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('rag_ingestion_log_collection_idx').on(table.collection, table.updatedAt)],\n);\n\n/** The tables this store owns, as one schema object, ready for `drizzle(client, { schema })`. */\nexport const agentSchema = {\n agentThread,\n agentMessage,\n agentToolCall,\n agentTokenUsage,\n agentModelPricing,\n agentRun,\n agentMemory,\n ragIngestionLog,\n};\n\n/**\n * The dialect-portable Drizzle SQLite database handle the store operates on. Accepts any SQLite\n * driver (better-sqlite3, libsql, D1, …) in either sync or async result mode; the host app owns\n * the connection and passes the `drizzle(...)` instance in.\n */\nexport type AgentDrizzleDb = BaseSQLiteDatabase<\n 'sync' | 'async',\n unknown,\n Record<string, unknown>,\n TablesRelationalConfig\n>;\n\n/** A persisted thread row as Drizzle selects it. */\nexport type AgentThreadRow = typeof agentThread.$inferSelect;\n/** A persisted message row as Drizzle selects it. */\nexport type AgentMessageRow = typeof agentMessage.$inferSelect;\n/** A persisted run row as Drizzle selects it. */\nexport type AgentRunRow = typeof agentRun.$inferSelect;\n/** A persisted memory row as Drizzle selects it. */\nexport type AgentMemoryRow = typeof agentMemory.$inferSelect;\n/** A persisted RAG ingestion outcome as Drizzle selects it. */\nexport type RagIngestionLogRow = typeof ragIngestionLog.$inferSelect;\n","import { sql } from 'drizzle-orm';\nimport type { AgentDrizzleDb } from './schema.js';\n\n/**\n * Idempotent `CREATE TABLE IF NOT EXISTS` DDL for the tables in\n * {@link import('./schema.js').agentSchema}. SQLite dialect (the db-test driver); kept here rather\n * than relying on drizzle-kit so the package can stand up its schema with no migration files. Safe\n * to run on boot against a shared database — it never drops or alters existing columns.\n */\nconst statements: string[] = [\n `CREATE TABLE IF NOT EXISTS agent_thread (\n id TEXT PRIMARY KEY NOT NULL,\n actor_ref TEXT NOT NULL,\n tenant_ref TEXT,\n title TEXT NOT NULL,\n transient INTEGER NOT NULL DEFAULT 0,\n active_stream_id TEXT,\n default_agent TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n deleted_at INTEGER\n )`,\n `CREATE INDEX IF NOT EXISTS agent_thread_actor_updated_idx\n ON agent_thread (actor_ref, updated_at)`,\n `CREATE TABLE IF NOT EXISTS agent_message (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n role TEXT NOT NULL,\n content TEXT NOT NULL,\n tool_calls TEXT,\n tool_results TEXT,\n attachments TEXT,\n follow_ups TEXT,\n usage TEXT,\n agent_name TEXT,\n run_id TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS agent_message_thread_created_idx\n ON agent_message (thread_id, created_at)`,\n `CREATE TABLE IF NOT EXISTS agent_tool_call (\n id TEXT PRIMARY KEY NOT NULL,\n message_id TEXT NOT NULL REFERENCES agent_message(id) ON DELETE CASCADE,\n tool_name TEXT NOT NULL,\n tool_type TEXT NOT NULL,\n input TEXT,\n output TEXT,\n status TEXT NOT NULL,\n executed_by_ref TEXT,\n execution_ms INTEGER,\n error TEXT,\n created_at INTEGER NOT NULL,\n executed_at INTEGER,\n run_id TEXT\n )`,\n `CREATE INDEX IF NOT EXISTS agent_tool_call_message_idx\n ON agent_tool_call (message_id)`,\n `CREATE TABLE IF NOT EXISTS agent_token_usage (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n actor_ref TEXT NOT NULL,\n message_id TEXT,\n model_id TEXT NOT NULL,\n purpose TEXT NOT NULL,\n input_tokens INTEGER NOT NULL,\n output_tokens INTEGER NOT NULL,\n cache_write_tokens INTEGER,\n cache_read_tokens INTEGER,\n cost_usd REAL,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS agent_token_usage_actor_created_idx\n ON agent_token_usage (actor_ref, created_at)`,\n `CREATE TABLE IF NOT EXISTS agent_model_pricing (\n id TEXT PRIMARY KEY NOT NULL,\n model_id TEXT NOT NULL,\n input_price_per_1m REAL NOT NULL,\n output_price_per_1m REAL NOT NULL,\n cache_write_price_per_1m REAL,\n cache_read_price_per_1m REAL,\n effective_from INTEGER NOT NULL,\n is_current INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS agent_run (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n actor_ref TEXT NOT NULL,\n agent_name TEXT,\n status TEXT NOT NULL,\n duration_ms INTEGER,\n error_code TEXT,\n error_message TEXT,\n retries INTEGER NOT NULL DEFAULT 0,\n started_at INTEGER NOT NULL,\n settled_at INTEGER,\n prompt_hash TEXT,\n parent_run_id TEXT\n )`,\n `CREATE INDEX IF NOT EXISTS agent_run_started_idx\n ON agent_run (started_at)`,\n // `key` and `text` are quoted: both are keywords in at least one engine this DDL is read by, and\n // they are the SPI's own field names, which is worth more here than dodging the quoting.\n `CREATE TABLE IF NOT EXISTS agent_memory (\n id TEXT PRIMARY KEY NOT NULL,\n scope TEXT NOT NULL,\n \"key\" TEXT NOT NULL,\n \"text\" TEXT NOT NULL,\n origin_author TEXT NOT NULL,\n origin_thread_id TEXT,\n origin_run_id TEXT,\n origin_actor_ref TEXT,\n pinned INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )`,\n `CREATE UNIQUE INDEX IF NOT EXISTS agent_memory_scope_key_uq\n ON agent_memory (scope, \"key\")`,\n `CREATE TABLE IF NOT EXISTS rag_ingestion_log (\n document_id TEXT PRIMARY KEY NOT NULL,\n status TEXT NOT NULL,\n collection TEXT,\n owner_type TEXT,\n owner_id TEXT,\n source TEXT,\n mime_type TEXT,\n size INTEGER,\n chunks INTEGER,\n reason TEXT,\n error TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS rag_ingestion_log_collection_idx\n ON rag_ingestion_log (collection, updated_at)`,\n];\n\n/**\n * Columns added to a table this package already shipped. `CREATE TABLE IF NOT EXISTS` above is inert\n * against a database that already has the table, so a column introduced later would land on fresh\n * databases only and be missing everywhere the store is actually running. The MikroORM adapter has\n * no such gap — its `ensureAgentSchema` applies `getUpdateSchemaSQL({ safe: true })`, which is\n * add-column-capable — so without this list the two adapters would disagree about what the schema is\n * after an upgrade.\n *\n * A whole new *table* belongs in {@link statements} and not here: the create guard is only inert\n * against a database that already has the table, so a table nothing has ever created is created in\n * full — every column and index — on a database of any age.\n *\n * Add-column only, never a type change or a drop: `safe` in the same sense as the sibling adapter.\n */\nconst additiveColumns: Array<{ table: string; column: string; ddl: string }> = [\n {\n table: 'agent_message',\n column: 'run_id',\n ddl: 'ALTER TABLE agent_message ADD COLUMN run_id TEXT',\n },\n {\n table: 'agent_message',\n column: 'attachments',\n ddl: 'ALTER TABLE agent_message ADD COLUMN attachments TEXT',\n },\n {\n table: 'agent_thread',\n column: 'default_agent',\n ddl: 'ALTER TABLE agent_thread ADD COLUMN default_agent TEXT',\n },\n {\n table: 'agent_run',\n column: 'parent_run_id',\n ddl: 'ALTER TABLE agent_run ADD COLUMN parent_run_id TEXT',\n },\n];\n\n/**\n * Runs the `CREATE TABLE IF NOT EXISTS` DDL above against the supplied Drizzle SQLite db, then adds\n * any column missing from a table that already existed.\n */\nexport async function ensureAgentSchema(db: AgentDrizzleDb): Promise<void> {\n for (const statement of statements) {\n await db.run(sql.raw(statement));\n }\n for (const { table, column, ddl } of additiveColumns) {\n // Asking the table what it has, rather than running the ALTER and swallowing the failure: a\n // swallowed error cannot tell \"the column is already there\" apart from \"the ALTER is malformed\",\n // and the second one would then go unnoticed until a query hit the missing column.\n const existing = await db.all<{ name: string }>(sql.raw(`PRAGMA table_info(${table})`));\n if (!existing.some((row) => row.name === column)) {\n await db.run(sql.raw(ddl));\n }\n }\n}\n","import type {\n AgentStore,\n AppendMessageInput,\n CreateThreadInput,\n RecordRunStartInput,\n RecordToolCallInput,\n RecordUsageInput,\n StoredMessage,\n ThreadDetail,\n ThreadSummary,\n ThreadTurnPage,\n ThreadTurnQuery,\n ThreadTurnReader,\n ToolResult,\n UpdateThreadInput,\n UpdateToolCallInput,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, sql } from 'drizzle-orm';\nimport {\n type AgentDrizzleDb,\n type AgentMessageRow,\n type AgentRunRow,\n type AgentThreadRow,\n agentMessage,\n agentRun,\n agentThread,\n agentTokenUsage,\n agentToolCall,\n} from './schema.js';\n\n/**\n * Re-exported from the core SPI so a consumer can name this store's window read without importing a\n * second package. ONE definition of the shape, so the adapter and the seam the loop probes for\n * cannot drift apart.\n */\nexport type { ThreadTurnPage, ThreadTurnQuery };\n\n/** The message columns a model turn reads. `usage`, `follow_ups` and `run_id` are nobody's business here. */\nconst TURN_MESSAGE_COLUMNS = {\n id: agentMessage.id,\n role: agentMessage.role,\n content: agentMessage.content,\n agentName: agentMessage.agentName,\n toolCalls: agentMessage.toolCalls,\n toolResults: agentMessage.toolResults,\n attachments: agentMessage.attachments,\n createdAt: agentMessage.createdAt,\n};\n\ntype TurnMessageRow = { [K in keyof typeof TURN_MESSAGE_COLUMNS]: AgentMessageRow[K] };\n\n/**\n * {@link AgentStore} backed by Drizzle ORM — a second adapter alongside the MikroORM one, proving\n * the store SPI is ORM-portable. A POJO receiving a Drizzle SQLite database handle (the host app\n * owns the connection). Behaviour mirrors {@link import('@dudousxd/nestjs-agent-store-mikro-orm')}\n * exactly (fork/truncate/quota/active-stream/soft-delete semantics) so the two are interchangeable.\n */\nexport class DrizzleAgentStore implements AgentStore, ThreadTurnReader {\n constructor(private readonly db: AgentDrizzleDb) {}\n\n async createThread(input: CreateThreadInput): Promise<ThreadSummary> {\n const now = new Date();\n const thread: AgentThreadRow = {\n id: crypto.randomUUID(),\n actorRef: input.actor.id,\n tenantRef: input.actor.tenantRef ?? null,\n title: input.title ?? 'New chat',\n transient: input.transient ?? false,\n activeStreamId: null,\n defaultAgent: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(agentThread).values(thread);\n return this.toSummary(thread);\n }\n\n async getThread(threadId: string): Promise<ThreadDetail | null> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n if (thread === undefined) {\n return null;\n }\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const last = messages[messages.length - 1];\n return {\n ...this.toSummary(thread, last?.content),\n messages: messages.map((message) => this.toStoredMessage(message)),\n ...(thread.activeStreamId != null ? { activeStreamId: thread.activeStreamId } : {}),\n };\n }\n\n /**\n * The window a turn reads off a thread: its newest `messageLimit` messages (oldest first), the\n * title, the default agent, and whether the thread has EVER been answered.\n *\n * {@link getThread} is the wrong read for a turn. It materializes the transcript — every message,\n * every attachment, every tool output the thread ever recorded — and the run then journals what it\n * loaded, so a long thread pays for its whole history on every turn and again on every replay.\n *\n * `hasAssistantMessage` is answered over the WHOLE thread, not the returned page: it answers \"has\n * this conversation been answered before?\", and a thread whose window happens to hold only the\n * user's last questions has still been answered. `null` when the thread is unknown or\n * soft-deleted, same as {@link getThread}.\n */\n async loadThreadForTurn(query: ThreadTurnQuery): Promise<ThreadTurnPage | null> {\n const [thread] = await this.db\n .select({ title: agentThread.title, defaultAgent: agentThread.defaultAgent })\n .from(agentThread)\n .where(and(eq(agentThread.id, query.threadId), isNull(agentThread.deletedAt)));\n if (thread === undefined) {\n return null;\n }\n const messages = await this.loadTurnWindow(query.threadId, query.messageLimit);\n const [answered] = await this.db\n .select({ id: agentMessage.id })\n .from(agentMessage)\n .where(and(eq(agentMessage.threadId, query.threadId), eq(agentMessage.role, 'assistant')))\n .limit(1);\n return {\n title: thread.title,\n defaultAgent: thread.defaultAgent,\n hasAssistantMessage: answered !== undefined,\n messages,\n };\n }\n\n /**\n * The newest `limit` messages of a thread, oldest first, projected to the columns a model turn\n * reads. Read newest-first so the LIMIT is the database's job, then reversed for the prompt.\n */\n private async loadTurnWindow(\n threadId: string,\n limit: number | undefined,\n ): Promise<StoredMessage[]> {\n if (limit !== undefined && limit <= 0) {\n return [];\n }\n const window = this.db\n .select(TURN_MESSAGE_COLUMNS)\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(desc(agentMessage.createdAt), desc(agentMessage.id));\n const rows: TurnMessageRow[] = limit === undefined ? await window : await window.limit(limit);\n return rows.reverse().map((row) => this.toStoredMessage(row));\n }\n\n async listThreads(actorRef: string, limit = 50): Promise<ThreadSummary[]> {\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(\n and(\n eq(agentThread.actorRef, actorRef),\n eq(agentThread.transient, false),\n isNull(agentThread.deletedAt),\n ),\n )\n .orderBy(desc(agentThread.updatedAt))\n .limit(limit);\n const summaries: ThreadSummary[] = [];\n for (const thread of threads) {\n const [last] = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id))\n .orderBy(desc(agentMessage.createdAt), desc(agentMessage.id))\n .limit(1);\n summaries.push(this.toSummary(thread, last?.content));\n }\n return summaries;\n }\n\n async softDeleteThread(threadId: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ deletedAt: new Date() })\n .where(eq(agentThread.id, threadId));\n }\n\n async forkThread(threadId: string, fromMessageId: string): Promise<ThreadSummary> {\n const [source] = await this.db.select().from(agentThread).where(eq(agentThread.id, threadId));\n if (source === undefined) {\n throw new Error(`thread ${threadId} not found`);\n }\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const cutoff = messages.findIndex((message) => message.id === fromMessageId);\n const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;\n const now = new Date();\n const fork: AgentThreadRow = {\n id: crypto.randomUUID(),\n actorRef: source.actorRef,\n tenantRef: source.tenantRef,\n title: source.title,\n transient: false,\n activeStreamId: null,\n defaultAgent: source.defaultAgent,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(agentThread).values(fork);\n if (kept.length > 0) {\n await this.db.insert(agentMessage).values(\n kept.map((message) => ({\n id: crypto.randomUUID(),\n threadId: fork.id,\n role: message.role,\n content: message.content,\n toolCalls: message.toolCalls,\n toolResults: message.toolResults,\n attachments: message.attachments,\n followUps: message.followUps,\n usage: message.usage,\n agentName: message.agentName,\n // The copy is the same message, so it keeps the run that wrote it. A reader asking which\n // turn produced this text gets the truthful answer; the run's own thread is still the\n // original, so a run-scoped read never picks the fork's rows up.\n runId: message.runId,\n createdAt: message.createdAt,\n })),\n );\n }\n return this.toSummary(fork);\n }\n\n async ownerOfThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n return thread?.actorRef ?? null;\n }\n\n async ownerOfToolCall(toolCallId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.id, toolCallId));\n return row?.actorRef ?? null;\n }\n\n async runForToolCall(toolCallId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ runId: agentToolCall.runId, activeStreamId: agentThread.activeStreamId })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.id, toolCallId));\n return row?.runId ?? row?.activeStreamId ?? null;\n }\n\n async ownerOfActiveStream(runId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentThread)\n .where(and(eq(agentThread.activeStreamId, runId), isNull(agentThread.deletedAt)));\n return thread?.actorRef ?? null;\n }\n\n async setTitle(threadId: string, title: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ title, updatedAt: new Date() })\n .where(eq(agentThread.id, threadId));\n }\n\n async promoteThread(threadId: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ transient: false, updatedAt: new Date() })\n .where(and(eq(agentThread.id, threadId), eq(agentThread.transient, true)));\n }\n\n async setActiveStream(threadId: string, runId: string | null): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ activeStreamId: runId })\n .where(eq(agentThread.id, threadId));\n }\n\n /**\n * Patch a thread's `title` and/or `defaultAgent`. Each field is only touched when PRESENT in\n * `patch` — `defaultAgent: null` clears it (falls back to the app default), while an omitted\n * `defaultAgent` leaves whatever is stored untouched. A no-op (including `updatedAt`) when the\n * patch is empty or the thread doesn't exist.\n */\n async updateThread(threadId: string, patch: UpdateThreadInput): Promise<void> {\n const updates: Partial<typeof agentThread.$inferInsert> = {};\n if (patch.title !== undefined) {\n updates.title = patch.title;\n }\n if (patch.defaultAgent !== undefined) {\n updates.defaultAgent = patch.defaultAgent;\n }\n if (Object.keys(updates).length === 0) {\n return;\n }\n updates.updatedAt = new Date();\n await this.db.update(agentThread).set(updates).where(eq(agentThread.id, threadId));\n }\n\n /**\n * The thread's default agent, projected — the caller wants one nullable scalar to decide which\n * agent answers the next turn, and {@link getThread} would materialize the whole transcript to\n * hand it over. `null` when the thread is unknown, soft-deleted, or has no default set.\n */\n async defaultAgentForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ defaultAgent: agentThread.defaultAgent })\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n return thread?.defaultAgent ?? null;\n }\n\n /**\n * Persist the start of a run (turn). Replay-safe: called under a durable localStep.\n *\n * Takes the SPI's own {@link RecordRunStartInput} rather than a hand-copied shape: a field added\n * to the input is otherwise accepted and dropped, silently, by every adapter that re-declares it.\n */\n async recordRunStart(run: RecordRunStartInput): Promise<void> {\n const runRow: AgentRunRow = {\n id: run.runId,\n threadId: run.threadId,\n actorRef: run.actorRef,\n agentName: run.agentName ?? null,\n status: 'running',\n durationMs: null,\n errorCode: null,\n errorMessage: null,\n retries: 0,\n startedAt: new Date(),\n settledAt: null,\n promptHash: run.promptHash ?? null,\n parentRunId: run.parentRunId ?? null,\n };\n await this.db.insert(agentRun).values(runRow);\n }\n\n /** Settle a run's outcome. A no-op when the run is unknown (mirrors `setTitle`/`updateThread`). */\n async recordRunEnd(end: {\n runId: string;\n status: 'completed' | 'failed' | 'cancelled';\n durationMs?: number;\n errorCode?: string;\n errorMessage?: string;\n }): Promise<void> {\n const updates: Partial<typeof agentRun.$inferInsert> = {\n status: end.status,\n settledAt: new Date(),\n };\n if (end.durationMs !== undefined) {\n updates.durationMs = end.durationMs;\n }\n if (end.errorCode !== undefined) {\n updates.errorCode = end.errorCode;\n }\n if (end.errorMessage !== undefined) {\n updates.errorMessage = end.errorMessage;\n }\n await this.db.update(agentRun).set(updates).where(eq(agentRun.id, end.runId));\n }\n\n /** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */\n async bumpRunRetries(runId: string): Promise<void> {\n await this.db\n .update(agentRun)\n .set({ retries: sql`${agentRun.retries} + 1` })\n .where(eq(agentRun.id, runId));\n }\n\n async appendMessage(input: AppendMessageInput): Promise<StoredMessage> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(eq(agentThread.id, input.threadId));\n if (thread === undefined) {\n throw new Error(`thread ${input.threadId} not found`);\n }\n const now = new Date();\n const message: AgentMessageRow = {\n id: crypto.randomUUID(),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n toolCalls: input.toolCalls ?? null,\n toolResults: input.toolResults ?? null,\n attachments: input.attachments ?? null,\n followUps: input.followUps ?? null,\n usage: input.usage ?? null,\n agentName: input.agentName ?? null,\n runId: input.runId ?? null,\n createdAt: now,\n };\n await this.db.insert(agentMessage).values(message);\n await this.db\n .update(agentThread)\n .set({ updatedAt: now })\n .where(eq(agentThread.id, input.threadId));\n return this.toStoredMessage(message);\n }\n\n async setMessageToolResults(messageId: string, results: ToolResult[]): Promise<void> {\n await this.db\n .update(agentMessage)\n .set({ toolResults: results })\n .where(eq(agentMessage.id, messageId));\n }\n\n async truncateFrom(threadId: string, messageId: string): Promise<void> {\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const cutoff = messages.findIndex((message) => message.id === messageId);\n if (cutoff < 0) {\n return;\n }\n const doomedIds = messages.slice(cutoff).map((message) => message.id);\n await this.db.delete(agentToolCall).where(inArray(agentToolCall.messageId, doomedIds));\n await this.db.delete(agentMessage).where(inArray(agentMessage.id, doomedIds));\n }\n\n async recordToolCall(input: RecordToolCallInput): Promise<void> {\n await this.db.insert(agentToolCall).values({\n id: input.toolCallId,\n messageId: input.messageId,\n toolName: input.toolName,\n toolType: input.toolType,\n input: input.input,\n output: null,\n status: input.status,\n executedByRef: null,\n executionMs: null,\n error: null,\n createdAt: new Date(),\n executedAt: null,\n runId: input.runId ?? null,\n });\n }\n\n async updateToolCall(input: UpdateToolCallInput): Promise<void> {\n const updates: Partial<typeof agentToolCall.$inferInsert> = { status: input.status };\n if (input.output !== undefined) {\n updates.output = input.output;\n }\n if (input.error !== undefined) {\n updates.error = input.error;\n }\n if (input.executionMs !== undefined) {\n updates.executionMs = input.executionMs;\n }\n if (input.executedByRef !== undefined) {\n updates.executedByRef = input.executedByRef;\n }\n if (input.status === 'executed' || input.status === 'auto_executed') {\n updates.executedAt = new Date();\n }\n await this.db.update(agentToolCall).set(updates).where(eq(agentToolCall.id, input.toolCallId));\n }\n\n /**\n * Of `mediaIds`, the ones a surviving message in one of this actor's threads still carries.\n *\n * Reads the `attachments` JSON back out and matches in memory rather than pushing the match into\n * SQL: the column holds an array of objects, and every dialect this adapter's sibling targets\n * spells that query differently (`jsonb` containment, `json_table`, `json_each`), while none of\n * them can use an index for it anyway. The scan is bounded by ONE actor's attachment-bearing\n * messages, which is a small set — attachments are rare, and a message without one is excluded\n * by the `is not null` before any JSON is parsed.\n *\n * Soft-deleted threads are deliberately included: their message rows survive, so the bytes they\n * point at are still reachable from stored state and are not garbage.\n */\n async referencedMediaIds(actorRef: string, mediaIds: readonly string[]): Promise<string[]> {\n if (mediaIds.length === 0) {\n return [];\n }\n const rows = await this.db\n .select({ attachments: agentMessage.attachments })\n .from(agentMessage)\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(and(eq(agentThread.actorRef, actorRef), isNotNull(agentMessage.attachments)));\n const wanted = new Set(mediaIds);\n const found = new Set<string>();\n for (const row of rows) {\n for (const attachment of row.attachments ?? []) {\n if (wanted.has(attachment.mediaId)) {\n found.add(attachment.mediaId);\n }\n }\n }\n return [...wanted].filter((mediaId) => found.has(mediaId));\n }\n\n async recordUsage(input: RecordUsageInput): Promise<void> {\n await this.db.insert(agentTokenUsage).values({\n id: crypto.randomUUID(),\n threadId: input.threadId,\n actorRef: input.actorRef,\n messageId: input.messageId ?? null,\n modelId: input.modelId,\n purpose: input.purpose,\n inputTokens: input.usage.inputTokens,\n outputTokens: input.usage.outputTokens,\n cacheWriteTokens: input.usage.cacheWriteTokens ?? null,\n cacheReadTokens: input.usage.cacheReadTokens ?? null,\n costUsd: input.costUsd ?? null,\n createdAt: new Date(),\n });\n }\n\n async quotaToday(\n actorRef: string,\n day: string,\n ): Promise<{ usedTokens: number; costUsd: number }> {\n const start = new Date(`${day}T00:00:00.000Z`);\n const end = new Date(`${day}T23:59:59.999Z`);\n const rows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(\n and(\n eq(agentTokenUsage.actorRef, actorRef),\n gte(agentTokenUsage.createdAt, start),\n lte(agentTokenUsage.createdAt, end),\n ),\n );\n const usedTokens = rows.reduce((sum, row) => sum + row.inputTokens + row.outputTokens, 0);\n const costUsd = rows.reduce((sum, row) => sum + (row.costUsd ?? 0), 0);\n return { usedTokens, costUsd };\n }\n\n private toSummary(thread: AgentThreadRow, lastContent?: string): ThreadSummary {\n return {\n id: thread.id,\n title: thread.title,\n transient: thread.transient,\n createdAt: thread.createdAt.toISOString(),\n updatedAt: thread.updatedAt.toISOString(),\n defaultAgent: thread.defaultAgent,\n ...(lastContent !== undefined ? { lastMessagePreview: lastContent.slice(0, 120) } : {}),\n };\n }\n\n private toStoredMessage(message: TurnMessageRow & Partial<AgentMessageRow>): StoredMessage {\n return {\n id: message.id,\n role: message.role,\n content: message.content,\n createdAt: message.createdAt.toISOString(),\n ...(message.toolCalls != null ? { toolCalls: message.toolCalls } : {}),\n ...(message.toolResults != null ? { toolResults: message.toolResults } : {}),\n ...(message.attachments != null ? { attachments: message.attachments } : {}),\n ...(message.followUps != null ? { followUps: message.followUps } : {}),\n ...(message.usage != null ? { usage: message.usage } : {}),\n ...(message.agentName != null ? { agentName: message.agentName } : {}),\n ...(message.runId != null ? { runId: message.runId } : {}),\n };\n }\n}\n","import type {\n ActorSpendRow,\n AgentGovernanceQueries,\n AgentPricingStore,\n ApprovalWhere,\n GovernancePage,\n GovernancePageQuery,\n GovernanceRange,\n GovernanceRunDetail,\n GovernanceThreadDetail,\n GovernanceThreadDetailQuery,\n GovernanceUsageInput,\n ModelPrice,\n ModelSpendRow,\n PendingApprovalRow,\n RecentRunRow,\n RunAgentBreakdownRow,\n RunErrorBreakdownRow,\n RunMetrics,\n RunToolCallRow,\n RunTrendPoint,\n RunWhere,\n ThreadActivityRow,\n ThreadMessageRow,\n ThreadMeta,\n ThreadSpendRow,\n ThreadWhere,\n ToolCallActivityRow,\n ToolCallStatus,\n ToolCallWhere,\n ToolKind,\n ToolStatRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n bucketByActor,\n bucketByModel,\n bucketByThread,\n bucketUsageTrend,\n dayBoundsUtc,\n rollupThreadUsage,\n truncateDetailContent,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, count, desc, eq, gte, inArray, isNull, like, lte, sql, sum } from 'drizzle-orm';\nimport {\n type AgentDrizzleDb,\n type AgentRunStatus,\n agentMessage,\n agentRun,\n agentThread,\n agentTokenUsage,\n agentToolCall,\n} from './schema.js';\n\n/** No error code recorded on a failed run (the caller didn't classify it). Groups those together. */\nconst UNCLASSIFIED_ERROR_CODE = 'unknown';\n/** Bucket key for a run with no `agentName` (mirrors {@link RunAgentBreakdownRow}'s contract). */\nconst DEFAULT_AGENT_BUCKET = '(default)';\n\n// The paged where-builders below narrow a wire-typed `string` filter value down to the schema\n// column's literal-union `$type<...>()` before it's used in an `eq()` comparison (an unnarrowed\n// `string` isn't assignable to e.g. `agentToolCall.status`'s type). An unrecognized value can never\n// match a row anyway (the column only ever holds these literals), so the paged method short-circuits\n// to an empty page instead of querying with a value that would trivially return nothing.\nconst TOOL_CALL_STATUSES: readonly string[] = [\n 'auto_executed',\n 'pending_approval',\n 'executed',\n 'rejected',\n 'failed',\n];\nfunction isToolCallStatus(value: string): value is ToolCallStatus {\n return TOOL_CALL_STATUSES.includes(value);\n}\n\nconst TOOL_KINDS: readonly string[] = ['read', 'action', 'agent'];\nfunction isToolKind(value: string): value is ToolKind {\n return TOOL_KINDS.includes(value);\n}\n\nconst RUN_STATUSES: readonly string[] = ['running', 'completed', 'failed', 'cancelled'];\nfunction isRunStatus(value: string): value is AgentRunStatus {\n return RUN_STATUSES.includes(value);\n}\n\n/** Inclusive UTC day start, reusing {@link dayBoundsUtc}'s date math so both bounds parse identically. */\nfunction dayStartUtc(day: string): Date {\n return dayBoundsUtc({ fromDay: day, toDay: day }).start;\n}\n\n/** Inclusive UTC day end, reusing {@link dayBoundsUtc}'s date math so both bounds parse identically. */\nfunction dayEndUtc(day: string): Date {\n return dayBoundsUtc({ fromDay: day, toDay: day }).end;\n}\n\n/** An empty page for the given query's page/pageSize — the shape every paged read falls back to. */\nfunction emptyPage<TRow>(query: GovernancePageQuery<unknown>): GovernancePage<TRow> {\n return { rows: [], total: 0, page: query.page, pageSize: query.pageSize };\n}\n\n/** Map a run row onto the SPI row. Shared by `recentRuns`/`runsPage`/`runDetail`/`threadDetail`. */\nfunction toRecentRunRow(run: typeof agentRun.$inferSelect): RecentRunRow {\n return {\n runId: run.id,\n threadId: run.threadId,\n actorRef: run.actorRef,\n agentName: run.agentName ?? null,\n status: run.status,\n durationMs: run.durationMs ?? null,\n errorCode: run.errorCode ?? null,\n errorMessage: run.errorMessage ?? null,\n retries: run.retries,\n startedAt: run.startedAt.toISOString(),\n promptHash: run.promptHash ?? null,\n parentRunId: run.parentRunId ?? null,\n };\n}\n\n/** Map a tool-call row onto the run drill-down's row (execution outcome, not activity-feed shape). */\nfunction toRunToolCallRow(toolCall: typeof agentToolCall.$inferSelect): RunToolCallRow {\n return {\n toolCallId: toolCall.id,\n toolName: toolCall.toolName,\n toolType: toolCall.toolType,\n status: toolCall.status,\n executionMs: toolCall.executionMs ?? null,\n executedByRef: toolCall.executedByRef ?? null,\n error: toolCall.error ?? null,\n createdAt: toolCall.createdAt.toISOString(),\n };\n}\n\n/** Map a Drizzle usage row onto the shared bucketer input (day derived from `createdAt`). */\nfunction toUsageInput(row: typeof agentTokenUsage.$inferSelect): GovernanceUsageInput {\n return {\n modelId: row.modelId,\n actorRef: row.actorRef,\n threadId: row.threadId,\n day: row.createdAt.toISOString().slice(0, 10),\n inputTokens: row.inputTokens,\n outputTokens: row.outputTokens,\n cacheWriteTokens: row.cacheWriteTokens,\n cacheReadTokens: row.cacheReadTokens,\n costUsd: row.costUsd,\n };\n}\n\n/**\n * MySQL-compatible percentile (no `PERCENTILE_CONT`): index into an ascending-sorted array by\n * offset. `null` when there are no settled durations in range. Shared by every reliability query\n * that reports p50/p95 so the SQL and in-memory adapters compute identically.\n */\nfunction percentileMs(sortedDurationsMs: number[], p: number): number | null {\n if (sortedDurationsMs.length === 0) {\n return null;\n }\n const offset = Math.min(sortedDurationsMs.length - 1, Math.floor(p * sortedDurationsMs.length));\n return sortedDurationsMs[offset] ?? null;\n}\n\n/**\n * {@link AgentGovernanceQueries} backed by Drizzle ORM — the read/analytics half of the store SPI,\n * mirroring {@link import('@dudousxd/nestjs-agent-store-mikro-orm')} exactly. Cost is the token\n * ledger priced against the current prices from the injected {@link AgentPricingStore}\n * (`AGENT_PRICING_STORE`), so a host that binds its own pricing store controls the cost every\n * governance surface reports. An unpriced model contributes 0 cost. Aggregation is in-process (like\n * `quotaToday`) so day-bucketing stays dialect-portable.\n */\nexport class DrizzleGovernanceQueries implements AgentGovernanceQueries {\n constructor(\n private readonly db: AgentDrizzleDb,\n private readonly pricingStore: AgentPricingStore,\n ) {}\n\n private async loadPricing(): Promise<Map<string, ModelPrice>> {\n const prices = await this.pricingStore.listCurrentPrices();\n const pricing = new Map<string, ModelPrice>();\n for (const price of prices) {\n pricing.set(price.modelId, {\n inputPricePer1m: price.inputPricePer1m,\n outputPricePer1m: price.outputPricePer1m,\n cacheWritePricePer1m: price.cacheWritePricePer1m ?? null,\n cacheReadPricePer1m: price.cacheReadPricePer1m ?? null,\n });\n }\n return pricing;\n }\n\n private async usageInRange(range: GovernanceRange): Promise<GovernanceUsageInput[]> {\n const { start, end } = dayBoundsUtc(range);\n const rows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(and(gte(agentTokenUsage.createdAt, start), lte(agentTokenUsage.createdAt, end)));\n return rows.map(toUsageInput);\n }\n\n async spendByModel(range: GovernanceRange): Promise<ModelSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByModel(await this.usageInRange(range), pricing);\n }\n\n async spendByActor(range: GovernanceRange): Promise<ActorSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByActor(await this.usageInRange(range), pricing);\n }\n\n /**\n * Top threads by spend within the range, highest cost first, capped at `limit`. Usage rows for a\n * soft-deleted thread (`deletedAt` set) are excluded — the thread no longer surfaces as a\n * governance target even though its ledger rows survive.\n */\n async spendByThread(range: GovernanceRange, limit: number): Promise<ThreadSpendRow[]> {\n const pricing = await this.loadPricing();\n const rows = await this.usageInRange(range);\n const threadIds = [...new Set(rows.map((row) => row.threadId))];\n if (threadIds.length === 0) {\n return [];\n }\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(and(inArray(agentThread.id, threadIds), isNull(agentThread.deletedAt)));\n const threadsById = new Map<string, ThreadMeta>(\n threads.map((thread) => [thread.id, { title: thread.title, actorRef: thread.actorRef }]),\n );\n return bucketByThread(rows, pricing, threadsById, { limit, includeUnknownThreads: false });\n }\n\n async usageTrend(range: GovernanceRange): Promise<UsageTrendPoint[]> {\n const pricing = await this.loadPricing();\n return bucketUsageTrend(await this.usageInRange(range), pricing);\n }\n\n async recentToolCalls(limit: number): Promise<ToolCallActivityRow[]> {\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n toolType: agentToolCall.toolType,\n status: agentToolCall.status,\n threadId: agentMessage.threadId,\n createdAt: agentToolCall.createdAt,\n runId: agentToolCall.runId,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .orderBy(desc(agentToolCall.createdAt), desc(agentToolCall.id))\n .limit(limit);\n return rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n toolType: row.toolType,\n status: row.status,\n threadId: row.threadId,\n createdAt: row.createdAt.toISOString(),\n runId: row.runId,\n }));\n }\n\n /**\n * Message counts and token totals for a whole set of threads in TWO grouped queries, not two per\n * thread — a 200-row page used to cost four hundred round trips. Mirrors the MikroORM adapter's\n * `threadRollups`, which reaches the same numbers without a QueryBuilder.\n */\n private async threadRollups(\n threadIds: string[],\n ): Promise<Map<string, { messageCount: number; totalTokens: number }>> {\n const rollups = new Map<string, { messageCount: number; totalTokens: number }>(\n threadIds.map((threadId) => [threadId, { messageCount: 0, totalTokens: 0 }]),\n );\n if (threadIds.length === 0) {\n return rollups;\n }\n const messageCounts = await this.db\n .select({ threadId: agentMessage.threadId, value: count() })\n .from(agentMessage)\n .where(inArray(agentMessage.threadId, threadIds))\n .groupBy(agentMessage.threadId);\n for (const row of messageCounts) {\n const bucket = rollups.get(row.threadId);\n if (bucket !== undefined) {\n bucket.messageCount = row.value;\n }\n }\n const usageTotals = await this.db\n .select({\n threadId: agentTokenUsage.threadId,\n inputTokens: sum(agentTokenUsage.inputTokens),\n outputTokens: sum(agentTokenUsage.outputTokens),\n })\n .from(agentTokenUsage)\n .where(inArray(agentTokenUsage.threadId, threadIds))\n .groupBy(agentTokenUsage.threadId);\n for (const row of usageTotals) {\n const bucket = rollups.get(row.threadId);\n if (bucket !== undefined) {\n // Drizzle types SUM() as string|null (a dialect can widen it past a JS number).\n bucket.totalTokens = Number(row.inputTokens ?? 0) + Number(row.outputTokens ?? 0);\n }\n }\n return rollups;\n }\n\n /** Decorate an ordered thread list with its batched rollups, preserving the incoming order. */\n private async toThreadActivityRows(\n threads: (typeof agentThread.$inferSelect)[],\n ): Promise<ThreadActivityRow[]> {\n const rollups = await this.threadRollups(threads.map((thread) => thread.id));\n return threads.map((thread) => {\n const rollup = rollups.get(thread.id);\n return {\n threadId: thread.id,\n title: thread.title,\n actorRef: thread.actorRef,\n messageCount: rollup?.messageCount ?? 0,\n totalTokens: rollup?.totalTokens ?? 0,\n lastActivityAt: thread.updatedAt.toISOString(),\n };\n });\n }\n\n async recentThreads(limit: number): Promise<ThreadActivityRow[]> {\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(isNull(agentThread.deletedAt))\n .orderBy(desc(agentThread.updatedAt), desc(agentThread.id))\n .limit(limit);\n return this.toThreadActivityRows(threads);\n }\n\n private async runsInRange(range: GovernanceRange): Promise<(typeof agentRun.$inferSelect)[]> {\n const { start, end } = dayBoundsUtc(range);\n return this.db\n .select()\n .from(agentRun)\n .where(and(gte(agentRun.startedAt, start), lte(agentRun.startedAt, end)));\n }\n\n async runMetrics(range: GovernanceRange): Promise<RunMetrics> {\n const runs = await this.runsInRange(range);\n let completed = 0;\n let failed = 0;\n let retries = 0;\n const settledDurationsMs: number[] = [];\n for (const run of runs) {\n if (run.status === 'completed') {\n completed += 1;\n } else if (run.status === 'failed') {\n failed += 1;\n }\n retries += run.retries;\n if ((run.status === 'completed' || run.status === 'failed') && run.durationMs != null) {\n settledDurationsMs.push(run.durationMs);\n }\n }\n settledDurationsMs.sort((left, right) => left - right);\n return {\n runs: runs.length,\n completed,\n failed,\n successRate: runs.length === 0 ? 0 : completed / runs.length,\n retries,\n durationP50Ms: percentileMs(settledDurationsMs, 0.5),\n durationP95Ms: percentileMs(settledDurationsMs, 0.95),\n };\n }\n\n async runsByAgent(range: GovernanceRange): Promise<RunAgentBreakdownRow[]> {\n const runs = await this.runsInRange(range);\n const byAgent = new Map<string, { runs: number; failed: number; retries: number }>();\n for (const run of runs) {\n const agentName = run.agentName ?? DEFAULT_AGENT_BUCKET;\n const bucket = byAgent.get(agentName) ?? { runs: 0, failed: 0, retries: 0 };\n bucket.runs += 1;\n bucket.failed += run.status === 'failed' ? 1 : 0;\n bucket.retries += run.retries;\n byAgent.set(agentName, bucket);\n }\n const result: RunAgentBreakdownRow[] = [];\n for (const [agentName, bucket] of byAgent) {\n result.push({ agentName, ...bucket });\n }\n result.sort(\n (left, right) => right.runs - left.runs || left.agentName.localeCompare(right.agentName),\n );\n return result;\n }\n\n async runErrors(range: GovernanceRange): Promise<RunErrorBreakdownRow[]> {\n const { start, end } = dayBoundsUtc(range);\n const runs = await this.db\n .select()\n .from(agentRun)\n .where(\n and(\n gte(agentRun.startedAt, start),\n lte(agentRun.startedAt, end),\n eq(agentRun.status, 'failed'),\n ),\n );\n const byError = new Map<string, number>();\n for (const run of runs) {\n const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;\n byError.set(errorCode, (byError.get(errorCode) ?? 0) + 1);\n }\n const result: RunErrorBreakdownRow[] = [];\n for (const [errorCode, errorCount] of byError) {\n result.push({ errorCode, count: errorCount });\n }\n result.sort(\n (left, right) => right.count - left.count || left.errorCode.localeCompare(right.errorCode),\n );\n return result;\n }\n\n async runTrend(range: GovernanceRange): Promise<RunTrendPoint[]> {\n const runs = await this.runsInRange(range);\n const byDay = new Map<string, { runs: number; failed: number }>();\n for (const run of runs) {\n const day = run.startedAt.toISOString().slice(0, 10);\n const bucket = byDay.get(day) ?? { runs: 0, failed: 0 };\n bucket.runs += 1;\n bucket.failed += run.status === 'failed' ? 1 : 0;\n byDay.set(day, bucket);\n }\n const result: RunTrendPoint[] = [];\n for (const [day, bucket] of byDay) {\n result.push({ day, ...bucket });\n }\n result.sort((left, right) => left.day.localeCompare(right.day));\n return result;\n }\n\n async recentRuns(limit: number): Promise<RecentRunRow[]> {\n const runs = await this.db\n .select()\n .from(agentRun)\n .orderBy(desc(agentRun.startedAt), desc(agentRun.id))\n .limit(limit);\n return runs.map(toRecentRunRow);\n }\n\n /**\n * Tool calls sitting `pending_approval`, oldest first (an inbox drains from the back), joined\n * through their message to the owning thread for title/actorRef and to the message itself for\n * `agentName` (null when the message carries none).\n */\n async pendingApprovals(limit: number): Promise<PendingApprovalRow[]> {\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n input: agentToolCall.input,\n threadId: agentThread.id,\n threadTitle: agentThread.title,\n actorRef: agentThread.actorRef,\n agentName: agentMessage.agentName,\n requestedAt: agentToolCall.createdAt,\n runId: agentToolCall.runId,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.status, 'pending_approval'))\n .orderBy(agentToolCall.createdAt, agentToolCall.id)\n .limit(limit);\n return rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n input: row.input,\n threadId: row.threadId,\n threadTitle: row.threadTitle,\n actorRef: row.actorRef,\n agentName: row.agentName ?? null,\n requestedAt: row.requestedAt.toISOString(),\n runId: row.runId,\n }));\n }\n\n /**\n * Per-tool call/failure/rejection/latency rollup over the range, highest call count first.\n * `p50ExecutionMs`/`p95ExecutionMs` are computed over calls that recorded a non-null `executionMs`\n * (regardless of their final status); both `null` when none did. Percentiles are taken in-process\n * off the sorted sample rather than in SQL, matching the MikroORM adapter — MySQL has no\n * `PERCENTILE_CONT` and one portable implementation beats three dialect-specific ones.\n */\n async toolStats(range: GovernanceRange): Promise<ToolStatRow[]> {\n const { start, end } = dayBoundsUtc(range);\n const calls = await this.db\n .select()\n .from(agentToolCall)\n .where(and(gte(agentToolCall.createdAt, start), lte(agentToolCall.createdAt, end)));\n const byTool = new Map<\n string,\n {\n toolName: string;\n toolType: string;\n calls: number;\n failed: number;\n rejected: number;\n executionMs: number[];\n }\n >();\n for (const call of calls) {\n const key = `${call.toolName} ${call.toolType}`;\n const bucket = byTool.get(key) ?? {\n toolName: call.toolName,\n toolType: call.toolType,\n calls: 0,\n failed: 0,\n rejected: 0,\n executionMs: [],\n };\n bucket.calls += 1;\n bucket.failed += call.status === 'failed' ? 1 : 0;\n bucket.rejected += call.status === 'rejected' ? 1 : 0;\n if (call.executionMs != null) {\n bucket.executionMs.push(call.executionMs);\n }\n byTool.set(key, bucket);\n }\n const result: ToolStatRow[] = [];\n for (const bucket of byTool.values()) {\n bucket.executionMs.sort((left, right) => left - right);\n result.push({\n toolName: bucket.toolName,\n toolType: bucket.toolType,\n calls: bucket.calls,\n failed: bucket.failed,\n rejected: bucket.rejected,\n p50ExecutionMs: percentileMs(bucket.executionMs, 0.5),\n p95ExecutionMs: percentileMs(bucket.executionMs, 0.95),\n });\n }\n result.sort(\n (left, right) => right.calls - left.calls || left.toolName.localeCompare(right.toolName),\n );\n return result;\n }\n\n /**\n * Paged, filterable tool-call activity, newest-first (same ordering as {@link recentToolCalls}).\n * `toolType`/`status` values outside the known literals can never match a row — short-circuits to\n * an empty page rather than issuing a query. Joins `agent_message` unconditionally (like\n * `recentToolCalls`) to resolve `threadId` and to support the `threadId` filter.\n */\n async toolCallsPage(\n query: GovernancePageQuery<ToolCallWhere>,\n ): Promise<GovernancePage<ToolCallActivityRow>> {\n const filters = query.where;\n if (filters?.status !== undefined && !isToolCallStatus(filters.status)) {\n return emptyPage(query);\n }\n if (filters?.toolType !== undefined && !isToolKind(filters.toolType)) {\n return emptyPage(query);\n }\n const whereClause = and(\n filters?.toolName !== undefined ? eq(agentToolCall.toolName, filters.toolName) : undefined,\n filters?.toolType !== undefined && isToolKind(filters.toolType)\n ? eq(agentToolCall.toolType, filters.toolType)\n : undefined,\n filters?.status !== undefined && isToolCallStatus(filters.status)\n ? eq(agentToolCall.status, filters.status)\n : undefined,\n filters?.threadId !== undefined ? eq(agentMessage.threadId, filters.threadId) : undefined,\n filters?.fromDay !== undefined\n ? gte(agentToolCall.createdAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(agentToolCall.createdAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .where(whereClause);\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n toolType: agentToolCall.toolType,\n status: agentToolCall.status,\n threadId: agentMessage.threadId,\n createdAt: agentToolCall.createdAt,\n runId: agentToolCall.runId,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .where(whereClause)\n .orderBy(desc(agentToolCall.createdAt), desc(agentToolCall.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize);\n return {\n rows: rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n toolType: row.toolType,\n status: row.status,\n threadId: row.threadId,\n createdAt: row.createdAt.toISOString(),\n runId: row.runId,\n })),\n total: totalRow?.value ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n };\n }\n\n /**\n * Paged, filterable thread activity, newest-first (same ordering as {@link recentThreads}).\n * `title` is a case-insensitive substring match via `lower(...)` on both sides (portable across\n * dialects, regardless of the underlying column collation). Soft-deleted threads are excluded,\n * mirroring `recentThreads`.\n */\n async threadsPage(\n query: GovernancePageQuery<ThreadWhere>,\n ): Promise<GovernancePage<ThreadActivityRow>> {\n const filters = query.where;\n const whereClause = and(\n isNull(agentThread.deletedAt),\n filters?.actorRef !== undefined ? eq(agentThread.actorRef, filters.actorRef) : undefined,\n filters?.title !== undefined\n ? like(sql`lower(${agentThread.title})`, `%${filters.title.toLowerCase()}%`)\n : undefined,\n filters?.fromDay !== undefined\n ? gte(agentThread.updatedAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(agentThread.updatedAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(agentThread)\n .where(whereClause);\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(whereClause)\n .orderBy(desc(agentThread.updatedAt), desc(agentThread.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize);\n const rows = await this.toThreadActivityRows(threads);\n return { rows, total: totalRow?.value ?? 0, page: query.page, pageSize: query.pageSize };\n }\n\n /**\n * Paged, filterable run activity, newest-first (same ordering as {@link recentRuns}). `status`\n * values outside the known literals can never match a row — short-circuits to an empty page.\n */\n async runsPage(query: GovernancePageQuery<RunWhere>): Promise<GovernancePage<RecentRunRow>> {\n const filters = query.where;\n if (filters?.status !== undefined && !isRunStatus(filters.status)) {\n return emptyPage(query);\n }\n const whereClause = and(\n filters?.agentName !== undefined ? eq(agentRun.agentName, filters.agentName) : undefined,\n filters?.status !== undefined && isRunStatus(filters.status)\n ? eq(agentRun.status, filters.status)\n : undefined,\n filters?.errorCode !== undefined ? eq(agentRun.errorCode, filters.errorCode) : undefined,\n filters?.threadId !== undefined ? eq(agentRun.threadId, filters.threadId) : undefined,\n filters?.fromDay !== undefined\n ? gte(agentRun.startedAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined ? lte(agentRun.startedAt, dayEndUtc(filters.toDay)) : undefined,\n );\n const [totalRow] = await this.db.select({ value: count() }).from(agentRun).where(whereClause);\n const runs = await this.db\n .select()\n .from(agentRun)\n .where(whereClause)\n .orderBy(desc(agentRun.startedAt), desc(agentRun.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize);\n return {\n rows: runs.map(toRecentRunRow),\n total: totalRow?.value ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n };\n }\n\n /**\n * Paged, filterable approvals inbox, oldest first — the same ordering as {@link pendingApprovals},\n * now with the `total` that method structurally cannot report. The join to `agent_message` /\n * `agent_thread` is unconditional (it already resolves title/actor/agentName), so the `threadId`/\n * `actorRef`/`agentName` filters cost nothing extra.\n *\n * The order is TOTAL (`created_at asc, id asc`, and `id` is the primary key), so no row can land on\n * two pages or on none for a given snapshot. Ascending order also means a newly requested approval\n * appends past the last page instead of shifting the page an operator is currently reading.\n */\n async approvalsPage(\n query: GovernancePageQuery<ApprovalWhere>,\n ): Promise<GovernancePage<PendingApprovalRow>> {\n const filters = query.where;\n const whereClause = and(\n eq(agentToolCall.status, 'pending_approval'),\n filters?.toolName !== undefined ? eq(agentToolCall.toolName, filters.toolName) : undefined,\n filters?.threadId !== undefined ? eq(agentThread.id, filters.threadId) : undefined,\n filters?.actorRef !== undefined ? eq(agentThread.actorRef, filters.actorRef) : undefined,\n filters?.agentName !== undefined ? eq(agentMessage.agentName, filters.agentName) : undefined,\n filters?.fromDay !== undefined\n ? gte(agentToolCall.createdAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(agentToolCall.createdAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(whereClause);\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n input: agentToolCall.input,\n threadId: agentThread.id,\n threadTitle: agentThread.title,\n actorRef: agentThread.actorRef,\n agentName: agentMessage.agentName,\n requestedAt: agentToolCall.createdAt,\n runId: agentToolCall.runId,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(whereClause)\n .orderBy(asc(agentToolCall.createdAt), asc(agentToolCall.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize);\n return {\n rows: rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n input: row.input,\n threadId: row.threadId,\n threadTitle: row.threadTitle,\n actorRef: row.actorRef,\n agentName: row.agentName ?? null,\n requestedAt: row.requestedAt.toISOString(),\n runId: row.runId,\n })),\n total: totalRow?.value ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n };\n }\n\n /**\n * One run, its owning thread's headline and its tool calls — TWO queries regardless of how many\n * tools the run called. `toolCalls` comes off `agent_tool_call.run_id`, so a run recorded before\n * that column was written reports none.\n */\n async runDetail(runId: string): Promise<GovernanceRunDetail | null> {\n const [row] = await this.db\n .select({ run: agentRun, thread: agentThread })\n .from(agentRun)\n .innerJoin(agentThread, eq(agentRun.threadId, agentThread.id))\n .where(eq(agentRun.id, runId))\n .limit(1);\n if (row === undefined) {\n return null;\n }\n const toolCalls = await this.db\n .select()\n .from(agentToolCall)\n .where(eq(agentToolCall.runId, runId))\n .orderBy(asc(agentToolCall.createdAt), asc(agentToolCall.id));\n return {\n run: toRecentRunRow(row.run),\n thread: {\n threadId: row.thread.id,\n title: row.thread.title,\n actorRef: row.thread.actorRef,\n deleted: row.thread.deletedAt != null,\n },\n toolCalls: toolCalls.map(toRunToolCallRow),\n };\n }\n\n /**\n * One thread with its lifetime usage rollup, its newest runs and its newest messages. A fixed six\n * queries (thread, usage, message count, message page, that page's tool-call counts, runs+count) —\n * the per-message tool-call counts are ONE grouped read over the returned message ids, not one per\n * message. Soft-deleted threads are returned with `deleted: true`; an audit still needs them.\n */\n async threadDetail(query: GovernanceThreadDetailQuery): Promise<GovernanceThreadDetail | null> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(eq(agentThread.id, query.threadId))\n .limit(1);\n if (thread === undefined) {\n return null;\n }\n const pricing = await this.loadPricing();\n const usageRows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(eq(agentTokenUsage.threadId, thread.id));\n const usage = rollupThreadUsage(usageRows.map(toUsageInput), pricing);\n const [messageCountRow] = await this.db\n .select({ value: count() })\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id));\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id))\n .orderBy(desc(agentMessage.createdAt), desc(agentMessage.id))\n .limit(query.messageLimit);\n const toolCallCounts = await this.toolCallCountsByMessage(\n messages.map((message) => message.id),\n );\n const [runTotalRow] = await this.db\n .select({ value: count() })\n .from(agentRun)\n .where(eq(agentRun.threadId, thread.id));\n const runs = await this.db\n .select()\n .from(agentRun)\n .where(eq(agentRun.threadId, thread.id))\n .orderBy(desc(agentRun.startedAt), desc(agentRun.id))\n .limit(query.runLimit);\n return {\n thread: {\n threadId: thread.id,\n title: thread.title,\n actorRef: thread.actorRef,\n messageCount: messageCountRow?.value ?? 0,\n totalTokens: usage.totalTokens,\n lastActivityAt: thread.updatedAt.toISOString(),\n },\n deleted: thread.deletedAt != null,\n usage,\n runs: runs.map(toRecentRunRow),\n runTotal: runTotalRow?.value ?? 0,\n messages: messages.map((message): ThreadMessageRow => {\n const { content, truncated } = truncateDetailContent(message.content);\n return {\n messageId: message.id,\n role: message.role,\n content,\n truncated,\n agentName: message.agentName ?? null,\n toolCallCount: toolCallCounts.get(message.id) ?? 0,\n createdAt: message.createdAt.toISOString(),\n };\n }),\n };\n }\n\n /** Tool-call counts for a set of messages in ONE grouped query — the detail view's no-N+1 guarantee. */\n private async toolCallCountsByMessage(messageIds: string[]): Promise<Map<string, number>> {\n const counts = new Map<string, number>();\n if (messageIds.length === 0) {\n return counts;\n }\n const rows = await this.db\n .select({ messageId: agentToolCall.messageId, value: count() })\n .from(agentToolCall)\n .where(inArray(agentToolCall.messageId, messageIds))\n .groupBy(agentToolCall.messageId);\n for (const row of rows) {\n counts.set(row.messageId, row.value);\n }\n return counts;\n }\n}\n","import {\n type ForgetMemoryInput,\n type ListMemoriesInput,\n type MemoryProvider,\n type MemoryRecord,\n type StoreMemoryInput,\n actorScope,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, eq, inArray } from 'drizzle-orm';\nimport { type AgentDrizzleDb, type AgentMemoryRow, agentMemory } from './schema.js';\n\n/** One row as the library reads it. The origin travels so a person can ask \"says who?\". */\nfunction toRecord(row: AgentMemoryRow): MemoryRecord {\n return {\n id: row.id,\n key: row.key,\n text: row.text,\n scope: row.scope,\n origin: {\n author: row.originAuthor,\n ...(row.originThreadId !== null ? { threadId: row.originThreadId } : {}),\n ...(row.originRunId !== null ? { runId: row.originRunId } : {}),\n ...(row.originActorRef !== null ? { actorRef: row.originActorRef } : {}),\n },\n updatedAt: row.updatedAt.toISOString(),\n pinned: row.pinned,\n };\n}\n\n/**\n * {@link MemoryProvider} backed by Drizzle, over the `agent_memory` table this package's\n * `ensureAgentSchema` creates. The host app owns and supplies the db handle.\n *\n * `search` IS NOT IMPLEMENTED, and that is a decision rather than an omission. It is optional on the\n * SPI, and what it buys is a block filled by relevance once the applicable set outgrows\n * `maxMemories` — which needs an index over the memories themselves, and an index is the half a\n * general-purpose table cannot supply: the shape depends entirely on what a deployment already runs\n * (pgvector, a full-text index, a hybrid service), and picking one here would make this adapter\n * require infrastructure most hosts do not have for a ceiling most of them never reach. Without\n * `search`, `list` reads the applicable scopes whole and the ceiling never bites.\n *\n * The signal that it is worth building is `MemoryDigest.omitted` going non-zero — and\n * `pinnedOmitted` especially, which means a standing policy stopped reaching any prompt. Both are on\n * the `aviary:agent:memory.resolved` diagnostic. A host that gets there implements `search` against\n * its own index and passes it as the provider, or wraps this one.\n */\nexport class DrizzleMemoryProvider implements MemoryProvider {\n constructor(private readonly db: AgentDrizzleDb) {}\n\n /**\n * Every memory visible at `scopes` — asked on EVERY turn, so it is one indexed `scope in (…)`\n * against the leading column of the (`scope`, `key`) unique index.\n *\n * The scope filter is in the QUERY. The library drops out-of-scope records it is handed, but that\n * is a backstop: a memory held for another actor or another tenant is never selected here, so it\n * is unreachable rather than outranked.\n */\n async list({ scopes }: ListMemoriesInput): Promise<MemoryRecord[]> {\n if (scopes.length === 0) {\n return [];\n }\n const rows = await this.db\n .select()\n .from(agentMemory)\n .where(inArray(agentMemory.scope, [...scopes]));\n return rows.map(toRecord);\n }\n\n /**\n * Delete one, and only from the actor's OWN scope.\n *\n * `memoryForgetVerdict` already holds the library's endpoint to that rule; the `where` repeats it\n * because `forget` takes an id and nothing else, so a caller reaching this provider by any other\n * path would otherwise delete a tenant's or the deployment's memory by knowing one id.\n *\n * `false` where nothing matched — which covers \"no such id\" and \"not yours\" identically, so the\n * answer cannot be used to find out which memories exist about other people.\n */\n async forget({ id, ctx }: ForgetMemoryInput): Promise<boolean> {\n const deleted = await this.db\n .delete(agentMemory)\n .where(and(eq(agentMemory.id, id), eq(agentMemory.scope, actorScope(ctx.actor))))\n .returning({ id: agentMemory.id });\n return deleted.length > 0;\n }\n\n /**\n * Upsert on (`scope`, `key`) — one statement, against the unique index, rather than a read\n * followed by a write: two turns concluding the same key at once would otherwise race to a\n * duplicate-key insert and one of them would fail the `remember` tool.\n *\n * The conflict `set` names exactly what a rewrite may change, so `pinned`, `createdAt` and `id`\n * are left alone by construction rather than by an exclusion anyone could forget to extend.\n * Dropping `pinned` would silently unpin a row the next time the agent restated the fact;\n * rewriting `createdAt` would lose when the belief was first formed; reassigning `id` would\n * invalidate the delete handle a person was already shown.\n */\n async write({ key, text, scope, origin, ctx }: StoreMemoryInput): Promise<MemoryRecord> {\n assertAuthorMayWriteScope({ scope, origin, ctx });\n const now = new Date();\n const columns = {\n originAuthor: origin.author,\n originThreadId: origin.threadId ?? null,\n originRunId: origin.runId ?? null,\n originActorRef: origin.actorRef ?? null,\n };\n const [row] = await this.db\n .insert(agentMemory)\n .values({\n id: crypto.randomUUID(),\n scope,\n key,\n text,\n ...columns,\n pinned: false,\n createdAt: now,\n updatedAt: now,\n })\n .onConflictDoUpdate({\n target: [agentMemory.scope, agentMemory.key],\n set: { text, ...columns, updatedAt: now },\n })\n .returning();\n if (row === undefined) {\n throw new Error(\n `DrizzleMemoryProvider: the upsert of \"${key}\" at \"${scope}\" returned no row; the driver does not support RETURNING on conflict.`,\n );\n }\n return toRecord(row);\n }\n\n /**\n * Make one memory always-on, or stop it being one. The operator act the SPI has no method for, on\n * purpose: a pin grants a fact a permanent place in every future prompt, so nothing an agent can\n * reach may set it. Authorize it in your own console — this takes no `ScopeContext` because it is\n * not an actor's act on their own memory.\n *\n * `false` where there is no such id.\n */\n async pin({ id, pinned }: { id: string; pinned: boolean }): Promise<boolean> {\n const updated = await this.db\n .update(agentMemory)\n .set({ pinned, updatedAt: new Date() })\n .where(eq(agentMemory.id, id))\n .returning({ id: agentMemory.id });\n return updated.length > 0;\n }\n}\n\n/**\n * An agent may not choose the scope it writes at — the storage half of the rule `memoryWriteVerdict`\n * states. `StoreMemoryInput` carries a `scope` because a host's own console legitimately publishes at\n * a wider one, and `writeMemory` only ever passes the actor's own; so what an adapter can check from\n * what it is handed is exactly rule three: nothing but a human writes above its own scope.\n *\n * Whether that human may write THERE — membership, elevation — needs facts an adapter is not given\n * (`ScopeContext` carries no resolved scope list and no elevation), and is answered by\n * `memoryWriteVerdict`, which `writeMemory` and a host's console both call. `origin.author` is the\n * axis, and no model-facing path can set it: the `remember` tool has no such parameter and\n * `writeMemory` hardcodes `'agent'`.\n *\n * Restated in each memory adapter with the same wording, so the refusal a host sees does not depend\n * on which store it picked.\n */\nfunction assertAuthorMayWriteScope({\n scope,\n origin,\n ctx,\n}: Pick<StoreMemoryInput, 'scope' | 'origin' | 'ctx'>): void {\n const own = actorScope(ctx.actor);\n if (origin.author !== 'human' && scope !== own) {\n throw new Error(\n `DrizzleMemoryProvider: refusing to write an agent-authored memory at \"${scope}\"; an agent may write only at \"${own}\"`,\n );\n }\n}\n","import type {\n AgentPricingStore,\n CurrentModelPrice,\n ModelPriceInput,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, eq } from 'drizzle-orm';\nimport { type AgentDrizzleDb, agentModelPricing } from './schema.js';\n\n/**\n * {@link AgentPricingStore} backed by Drizzle ORM — the write side of the pricing table\n * {@link import('./drizzle-governance-queries.js').DrizzleGovernanceQueries} joins against. A POJO\n * receiving a Drizzle SQLite database handle (the host app owns the connection), mirroring\n * {@link import('@dudousxd/nestjs-agent-store-mikro-orm')} exactly (atomic supersede semantics).\n */\nexport class DrizzlePricingStore implements AgentPricingStore {\n constructor(private readonly db: AgentDrizzleDb) {}\n\n async upsertModelPrice(input: ModelPriceInput): Promise<void> {\n await this.db\n .update(agentModelPricing)\n .set({ isCurrent: false })\n .where(\n and(eq(agentModelPricing.modelId, input.modelId), eq(agentModelPricing.isCurrent, true)),\n );\n await this.db.insert(agentModelPricing).values({\n id: crypto.randomUUID(),\n modelId: input.modelId,\n inputPricePer1m: input.inputPricePer1m,\n outputPricePer1m: input.outputPricePer1m,\n cacheWritePricePer1m: input.cacheWritePricePer1m ?? null,\n cacheReadPricePer1m: input.cacheReadPricePer1m ?? null,\n effectiveFrom: new Date(),\n isCurrent: true,\n });\n }\n\n async listCurrentPrices(): Promise<CurrentModelPrice[]> {\n const rows = await this.db\n .select()\n .from(agentModelPricing)\n .where(eq(agentModelPricing.isCurrent, true));\n return rows.map((row) => ({\n modelId: row.modelId,\n inputPricePer1m: row.inputPricePer1m,\n outputPricePer1m: row.outputPricePer1m,\n effectiveFrom: row.effectiveFrom.toISOString(),\n ...(row.cacheWritePricePer1m != null\n ? { cacheWritePricePer1m: row.cacheWritePricePer1m }\n : {}),\n ...(row.cacheReadPricePer1m != null ? { cacheReadPricePer1m: row.cacheReadPricePer1m } : {}),\n }));\n }\n}\n","import { subscribe, unsubscribe } from 'node:diagnostics_channel';\nimport { Injectable, Logger, type OnModuleDestroy, type OnModuleInit } from '@nestjs/common';\nimport { type SQL, and, asc, count, desc, eq, gt, lt, or } from 'drizzle-orm';\nimport {\n type AgentDrizzleDb,\n type RagIngestionLogRow,\n type RagIngestionStatus,\n ragIngestionLog,\n} from './schema.js';\n\n/**\n * The `aviary:rag:*` payloads this recorder reads, re-declared here so it couples to the *wire\n * contract* of the diagnostics channel rather than importing `@dudousxd/nestjs-agent-rag-media` —\n * the same convention that package uses for the media channels it consumes. Keep in sync with\n * `rag-media`'s `diagnostics.ts`.\n */\ninterface RagOutcomePayload {\n mediaId?: unknown;\n ownerType?: unknown;\n ownerId?: unknown;\n collection?: unknown;\n source?: unknown;\n mimeType?: unknown;\n size?: unknown;\n chunks?: unknown;\n reason?: unknown;\n error?: unknown;\n}\n\nconst CHANNELS: { name: string; status: RagIngestionStatus }[] = [\n { name: 'aviary:rag:media.ingested', status: 'ingested' },\n { name: 'aviary:rag:media.skipped', status: 'skipped' },\n { name: 'aviary:rag:media.failed', status: 'failed' },\n { name: 'aviary:rag:media.removed', status: 'removed' },\n];\n\n/** Narrow an unknown payload field to a string, treating everything else as absent. */\nfunction str(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n\nfunction num(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\n/**\n * The paging order: newest first, tiebroken on the primary key.\n *\n * `updatedAt` alone is not a total order — a bulk upload stamps every document of the batch with the\n * same second — and a database is free to return tied rows in a different sequence for each\n * LIMIT/OFFSET query. A tie straddling a page boundary then hands a caller sweeping the table a row\n * in *neither* page (or the same row twice), which is how an orphan-sweep leaves an S3 object behind\n * with its log row already gone, and how a reconcile re-embeds documents it already has.\n * `documentId` is the table's primary key, so appending it makes the order total and the pages\n * disjoint.\n *\n * Exported because it is a contract, not an implementation detail: a caller that polls page 1 for a\n * document it just rewrote depends on `updated_at desc`, and a caller that pages depends on the\n * tiebreaker. Spread it into a query of your own (`.orderBy(...RAG_INGESTION_LOG_PAGE_ORDER)`) to\n * read this table the way {@link DrizzleRagIngestionLog} does — and to keep `iterate`'s keyset\n * arithmetic, which is derived from exactly this order, in view.\n */\nexport const RAG_INGESTION_LOG_PAGE_ORDER: SQL[] = [\n desc(ragIngestionLog.updatedAt),\n asc(ragIngestionLog.documentId),\n];\n\n/** Default rows per page for {@link DrizzleRagIngestionLog.list} / `listPage`. */\nconst DEFAULT_PAGE_SIZE = 200;\n\n/** Default rows per round-trip for {@link DrizzleRagIngestionLog.iterate}. */\nconst DEFAULT_BATCH_SIZE = 200;\n\n/** Rows per round-trip, defaulted and clamped: a batch of 0 or NaN would never terminate. */\nfunction batches(batchSize: number | undefined): number {\n const requested = Math.trunc(batchSize ?? DEFAULT_BATCH_SIZE);\n return Number.isFinite(requested) && requested >= 1 ? requested : DEFAULT_BATCH_SIZE;\n}\n\n/**\n * The only two columns a keyset sweep needs to keep going. `listDocumentIds` selects exactly these:\n * the id it returns, plus the `updatedAt` half of the cursor.\n */\nconst CURSOR_COLUMNS = {\n documentId: ragIngestionLog.documentId,\n updatedAt: ragIngestionLog.updatedAt,\n};\n\n/** The coordinates half of a log query: which rows, with nothing said about paging. */\nexport interface RagIngestionLogWhere {\n collection?: string;\n status?: RagIngestionStatus;\n}\n\nexport interface RagIngestionLogQuery extends RagIngestionLogWhere {\n limit?: number;\n offset?: number;\n}\n\n/**\n * Where a sweep left off: the ordering column plus the primary key, i.e. one point in\n * {@link RAG_INGESTION_LOG_PAGE_ORDER}. Not an opaque token — it is two column values, so a caller\n * may persist it across processes and resume from it.\n */\nexport interface RagIngestionLogCursor {\n updatedAt: Date;\n documentId: string;\n}\n\nexport interface RagIngestionLogIterateOptions {\n /**\n * Rows fetched per round-trip. Defaults to 200; anything under 1 or non-finite falls back to\n * that default rather than being honoured — a batch of 0 would fetch nothing and never advance.\n */\n batchSize?: number;\n /** Resume strictly after this point in the order, e.g. a cursor persisted by an earlier sweep. */\n after?: RagIngestionLogCursor;\n}\n\n/**\n * Records the outcome of every RAG ingestion into `rag_ingestion_log`, by subscribing to the\n * `aviary:rag:*` diagnostics channels `@dudousxd/nestjs-agent-rag-media` publishes — the Drizzle\n * counterpart of `MikroOrmRagIngestionLog`, with the same columns, ordering and write semantics, so\n * a console built on one adapter reads the other.\n *\n * It answers the question a vector store structurally cannot: *which documents failed to index, and\n * why*. A skipped or failed document produces no chunks, so it is invisible to\n * `VectorStore.listDocuments()` — the index only knows about successes. Pair the two for a complete\n * picture: the store is the truth about what is retrievable, this table is the truth about what was\n * attempted.\n *\n * Writes are best-effort and never throw: this runs detached from any request, on a diagnostics\n * channel, so a failed write must not take down the ingestion that triggered it. A lost row costs\n * observability, not data — the vector store remains the system of record.\n */\n@Injectable()\nexport class DrizzleRagIngestionLog implements OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(DrizzleRagIngestionLog.name);\n private teardowns: (() => void)[] = [];\n private readonly inFlight = new Set<Promise<void>>();\n\n constructor(private readonly db: AgentDrizzleDb) {}\n\n onModuleInit(): void {\n for (const channel of CHANNELS) {\n const listener = (message: unknown): void => {\n const payload = (message as { payload?: RagOutcomePayload })?.payload;\n if (payload !== undefined) {\n this.track(this.record(channel.status, payload));\n }\n };\n subscribe(channel.name, listener);\n this.teardowns.push(() => unsubscribe(channel.name, listener));\n }\n }\n\n async onModuleDestroy(): Promise<void> {\n for (const teardown of this.teardowns) {\n teardown();\n }\n this.teardowns = [];\n await this.settle();\n }\n\n /** Await every in-flight write — for graceful shutdown and deterministic tests. */\n async settle(): Promise<void> {\n await Promise.allSettled([...this.inFlight]);\n }\n\n /** The latest recorded outcome per document, newest first. */\n async list(query: RagIngestionLogQuery = {}): Promise<RagIngestionLogRow[]> {\n const rows = this.db\n .select()\n .from(ragIngestionLog)\n .where(this.where(query))\n .orderBy(...RAG_INGESTION_LOG_PAGE_ORDER)\n .limit(query.limit ?? DEFAULT_PAGE_SIZE);\n return query.offset === undefined ? rows : rows.offset(query.offset);\n }\n\n /**\n * The same page plus the unpaginated total, so a caller can tell \"these are all of them\" from\n * \"these are the first N\". A list that silently truncates reads as complete when it isn't.\n *\n * Offset paging is only sound over a table nobody is deleting from underneath you: a row removed\n * behind the cursor shifts everything after it back by one, so the next page starts one row late\n * and that row is never seen. Use {@link iterate} for any sweep that deletes.\n */\n async listPage(\n query: RagIngestionLogQuery = {},\n ): Promise<{ rows: RagIngestionLogRow[]; total: number }> {\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(ragIngestionLog)\n .where(this.where(query));\n return { rows: await this.list(query), total: totalRow?.value ?? 0 };\n }\n\n /**\n * Every matching row, newest first, streamed in batches — the sweep-safe way to walk this table.\n *\n * Paging is *keyset*, not offset: each batch asks for the rows that sort strictly after the last\n * row yielded, using `(updatedAt, documentId)` — one point in\n * {@link RAG_INGESTION_LOG_PAGE_ORDER}, which is total because it ends in the primary key. A\n * cursor made of column values does not move when rows leave the table, which is what makes this\n * delete-safe *by construction* rather than by the caller carefully advancing an offset by only\n * the rows it kept.\n *\n * **The guarantee, stated once:** a row is yielded exactly when — at the moment the batch that\n * would contain it is fetched — the row exists, matches `where`, and sorts strictly after the\n * last row already yielded. Everything below is a consequence of that one sentence.\n *\n * What you can rely on:\n * - **Deleting rows while iterating is safe.** Delete any row you like — the one just yielded, the\n * whole batch, rows you have not reached yet — and every row that is still there when the sweep\n * reaches its position is visited exactly once. Nothing is skipped and nothing is repeated,\n * because deleting a row moves no *other* row's `(updatedAt, documentId)`. (Rows you delete\n * *ahead* of the cursor are simply never visited, which is the point of deleting them.)\n * - **Ties are safe.** A bulk upload stamps a whole batch with the same `updatedAt`; the\n * `documentId` tiebreaker keeps consecutive batches disjoint even when every row ties.\n * - **Each row is yielded at most once**, for as long as `updatedAt` only ever moves forward —\n * which is what `record()` does, since it always stamps `now`.\n *\n * What this is **not**: a snapshot, or a repeatable read. The sweep observes the table as it is\n * when each batch is fetched, so:\n * - A row **inserted** mid-sweep by `record()` is stamped `now`. The order is newest-first, so it\n * sorts ahead of a cursor the sweep has already moved past, and is not visited. A sweep\n * therefore never sees documents ingested after it started — the behaviour an orphan sweep\n * wants, since a document that arrived while you were sweeping is not an orphan. (A *direct*\n * insert with a backdated `updatedAt` lands ahead of the cursor and **is** visited; nothing in\n * this class writes one.)\n * - A row **re-ingested** mid-sweep has its `updatedAt` bumped to `now`, moving it ahead of the\n * cursor for the same reason. If the sweep had already passed it, it is not visited twice; if it\n * had not, it is **missed for this pass**. That is the honest limit: against a concurrent\n * writer `iterate` guarantees \"at most once\", not \"at least once\". Sweeps that must not miss a\n * concurrently-rewritten row should be idempotent and run again.\n * - Only a row whose `updatedAt` moves *backwards* — which needs a direct write — can be yielded\n * twice.\n * - `collection` / `status` are re-evaluated per batch, so a row that stops matching mid-sweep\n * stops being visited.\n *\n * There is no `limit`/`offset` here on purpose: `where` says *which* rows, `options` says how the\n * sweep is run. A sweep that stops early stops by `break`ing out of the `for await`.\n */\n iterate(\n where: RagIngestionLogWhere = {},\n options: RagIngestionLogIterateOptions = {},\n ): AsyncGenerator<RagIngestionLogRow, void, undefined> {\n return this.sweep(where, batches(options.batchSize), options.after, (filter, limit) =>\n this.db\n .select()\n .from(ragIngestionLog)\n .where(filter)\n .orderBy(...RAG_INGESTION_LOG_PAGE_ORDER)\n .limit(limit),\n );\n }\n\n /**\n * Just the document ids of the matching rows, in {@link RAG_INGESTION_LOG_PAGE_ORDER}.\n *\n * Returns **all** of them — no 200-row cap, unlike `list` — by sweeping on {@link iterate}'s\n * keyset internally, so it is correct against concurrent deletes for the same reason `iterate`\n * is. What the cap protects against is hydrating an unbounded number of wide rows (`error` is a\n * TEXT column); this selects two columns — the id, plus the `updatedAt` the cursor needs — and\n * keeps only the ids, so the peak footprint is one batch of two-column rows plus a list of\n * strings whose size *is* the answer the caller asked for.\n *\n * For callers that need the id set of a collection and nothing else: an orphan sweep unioning the\n * log against the vector store's own document list.\n */\n async listDocumentIds(\n where: RagIngestionLogWhere = {},\n options: { batchSize?: number } = {},\n ): Promise<string[]> {\n const ids: string[] = [];\n const rows = this.sweep(where, batches(options.batchSize), undefined, (filter, limit) =>\n this.db\n .select(CURSOR_COLUMNS)\n .from(ragIngestionLog)\n .where(filter)\n .orderBy(...RAG_INGESTION_LOG_PAGE_ORDER)\n .limit(limit),\n );\n for await (const row of rows) {\n ids.push(row.documentId);\n }\n return ids;\n }\n\n /** The latest recorded outcome for one document, or null if it was never attempted. */\n async get(documentId: string): Promise<RagIngestionLogRow | null> {\n const [row] = await this.db\n .select()\n .from(ragIngestionLog)\n .where(eq(ragIngestionLog.documentId, documentId));\n return row ?? null;\n }\n\n /** Forget one document's record. Returns whether a row was actually removed. */\n async remove(documentId: string): Promise<boolean> {\n const removed = await this.db\n .delete(ragIngestionLog)\n .where(eq(ragIngestionLog.documentId, documentId))\n .returning({ documentId: ragIngestionLog.documentId });\n return removed.length > 0;\n }\n\n /** Forget every record for a collection — for when the collection itself is deleted. */\n async removeByCollection(collection: string): Promise<number> {\n const removed = await this.db\n .delete(ragIngestionLog)\n .where(eq(ragIngestionLog.collection, collection))\n .returning({ documentId: ragIngestionLog.documentId });\n return removed.length;\n }\n\n /**\n * The keyset sweep both {@link iterate} and {@link listDocumentIds} are made of. `page` decides\n * how wide a row is — whole rows for `iterate`, two columns for `listDocumentIds` — and the\n * `R extends RagIngestionLogCursor` bound says the only thing the sweep needs back: a row it can\n * read the next cursor off.\n *\n * The cursor advances **per yielded row**, not per batch, so a consumer that `break`s mid-batch\n * leaves it on the last row it actually saw. It is two column values read off that row, so a row\n * leaving the table cannot move it — the whole reason this is delete-safe by construction.\n */\n private async *sweep<R extends RagIngestionLogCursor>(\n where: RagIngestionLogWhere,\n batchSize: number,\n after: RagIngestionLogCursor | undefined,\n page: (filter: SQL | undefined, limit: number) => Promise<R[]>,\n ): AsyncGenerator<R, void, undefined> {\n let cursor = after;\n for (;;) {\n const rows = await page(this.keyset(where, cursor), batchSize);\n if (rows.length === 0) {\n return;\n }\n for (const row of rows) {\n yield row;\n cursor = { updatedAt: row.updatedAt, documentId: row.documentId };\n }\n // Deliberately NOT `if (rows.length < batchSize) return`: a short batch means \"nothing after\n // the cursor *right now*\", not \"nothing ever\". One extra empty query per sweep is what makes\n // termination depend on the table rather than on a batch happening to come back full.\n }\n }\n\n private where(query: RagIngestionLogWhere): SQL | undefined {\n return and(\n query.collection !== undefined ? eq(ragIngestionLog.collection, query.collection) : undefined,\n query.status !== undefined ? eq(ragIngestionLog.status, query.status) : undefined,\n );\n }\n\n /**\n * The coordinates filter AND'd with \"strictly after `cursor` in\n * {@link RAG_INGESTION_LOG_PAGE_ORDER}\".\n *\n * The order is `updatedAt desc, documentId asc`, so \"after\" means an older timestamp, or the same\n * timestamp and a larger id. Both halves are needed: the `<` alone would re-yield every row tied\n * with the cursor, and dropping the tie branch would skip them instead.\n */\n private keyset(\n where: RagIngestionLogWhere,\n cursor: RagIngestionLogCursor | undefined,\n ): SQL | undefined {\n const base = this.where(where);\n if (cursor === undefined) {\n return base;\n }\n return and(\n base,\n or(\n lt(ragIngestionLog.updatedAt, cursor.updatedAt),\n and(\n eq(ragIngestionLog.updatedAt, cursor.updatedAt),\n gt(ragIngestionLog.documentId, cursor.documentId),\n ),\n ),\n );\n }\n\n /**\n * Upsert one outcome. Keyed by document id so the row always reflects the *current* state — a\n * retry that succeeds overwrites the failure it replaces, rather than leaving a stale error next\n * to a working document.\n */\n private async record(status: RagIngestionStatus, payload: RagOutcomePayload): Promise<void> {\n const documentId = str(payload.mediaId);\n if (documentId === null) {\n return;\n }\n try {\n const now = new Date();\n // Only the coordinates the payload actually carries go into the conflict `set`, so an update\n // leaves the others untouched — a sparser later event (e.g. `removed`, which knows the owner\n // but not the collection) can't blank out what an earlier `ingested` recorded.\n const collection = str(payload.collection);\n const ownerType = str(payload.ownerType);\n const ownerId = str(payload.ownerId);\n const source = str(payload.source);\n const mimeType = str(payload.mimeType);\n const size = num(payload.size);\n const outcome = {\n status,\n // The three outcome-specific columns are exclusive: null out the ones this status doesn't\n // own on every write, so a successful retry clears the previous attempt's error rather than\n // leaving it next to a working document. Always present → always in the conflict `set`.\n chunks: status === 'ingested' ? num(payload.chunks) : null,\n reason: status === 'skipped' ? str(payload.reason) : null,\n error: status === 'failed' ? str(payload.error) : null,\n updatedAt: now,\n ...(collection !== null ? { collection } : {}),\n ...(ownerType !== null ? { ownerType } : {}),\n ...(ownerId !== null ? { ownerId } : {}),\n ...(source !== null ? { source } : {}),\n ...(mimeType !== null ? { mimeType } : {}),\n ...(size !== null ? { size } : {}),\n };\n // Atomic insert-or-update keyed by the document id (the primary key). Two concurrent events\n // for the same NEW document can't race to a duplicate-key insert the way find-then-insert\n // would. `createdAt` is set on insert but absent from the conflict `set`, so an update never\n // overwrites it.\n await this.db\n .insert(ragIngestionLog)\n .values({ documentId, createdAt: now, ...outcome })\n .onConflictDoUpdate({ target: ragIngestionLog.documentId, set: outcome });\n } catch (error) {\n this.logger.warn(\n `Could not record RAG ingestion outcome for ${documentId}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n\n private track(promise: Promise<void>): void {\n const tracked = promise.finally(() => {\n this.inFlight.delete(tracked);\n });\n this.inFlight.add(tracked);\n }\n}\n","import {\n AGENT_GOVERNANCE_QUERIES,\n AGENT_PRICING_STORE,\n AGENT_STORE,\n type AgentPricingStore,\n} from '@dudousxd/nestjs-agent-core';\nimport { type DynamicModule, Module, type Provider, type Type } from '@nestjs/common';\nimport { DrizzleAgentStore } from './drizzle-agent-store.js';\nimport { DrizzleGovernanceQueries } from './drizzle-governance-queries.js';\nimport { DrizzleMemoryProvider } from './drizzle-memory-provider.js';\nimport { DrizzlePricingStore } from './drizzle-pricing-store.js';\nimport { DrizzleRagIngestionLog } from './drizzle-rag-ingestion-log.js';\nimport type { AgentDrizzleDb } from './schema.js';\n\n/** Options for {@link DrizzleAgentStoreModule.forRoot}. The app owns and supplies the db handle. */\nexport interface DrizzleAgentStoreModuleOptions {\n /** A Drizzle SQLite database instance (`drizzle(client, { schema: agentSchema })`). */\n db: AgentDrizzleDb;\n /**\n * Bind {@link AGENT_PRICING_STORE} (which {@link DrizzleGovernanceQueries} prices usage against) to\n * a host-supplied store instead of the default {@link DrizzlePricingStore} — make your OWN pricing\n * table the single source of cost truth without touching `agent_model_pricing`.\n */\n pricingStore?: Type<AgentPricingStore>;\n /**\n * Record every RAG ingestion outcome into `rag_ingestion_log` by subscribing to the `aviary:rag:*`\n * diagnostics channels (default `true`, matching the MikroORM adapter). This is the only place a\n * *failed* or *skipped* document is visible — one that produced no chunks doesn't exist as far as\n * `VectorStore.listDocuments()` is concerned. Set `false` if you don't ingest media into RAG, or\n * record outcomes yourself.\n *\n * The table has to exist: `ensureAgentSchema` creates it, or write the `CREATE TABLE` into\n * your own migrations. Writes are best-effort, so a missing table costs a warning per ingestion\n * rather than a failed ingestion.\n */\n ragIngestionLog?: boolean;\n}\n\n/**\n * Binds {@link DrizzleAgentStore} to the {@link AGENT_STORE} token consumed by\n * `@dudousxd/nestjs-agent`, plus {@link DrizzleGovernanceQueries} to\n * {@link AGENT_GOVERNANCE_QUERIES} (the read-model the dashboard/telescope surfaces consume) and\n * {@link DrizzlePricingStore} to {@link AGENT_PRICING_STORE} (the write side of that pricing table).\n * The host app supplies an already-opened Drizzle db — this module never opens a connection itself.\n *\n * The returned module is global, so {@link AGENT_STORE}, {@link AGENT_GOVERNANCE_QUERIES} and\n * {@link AGENT_PRICING_STORE} are visible app-wide — `AgentModule` resolves the store without an\n * explicit `store` option, and the dashboard/telescope resolve {@link AGENT_GOVERNANCE_QUERIES}\n * without the host re-binding it.\n *\n * ```ts\n * @Module({ imports: [DrizzleAgentStoreModule.forRoot({ db })] })\n * export class AppModule {}\n * ```\n */\n@Module({})\nexport class DrizzleAgentStoreModule {\n static forRoot(options: DrizzleAgentStoreModuleOptions): DynamicModule {\n const ragProviders: Provider[] =\n options.ragIngestionLog === false\n ? []\n : [\n {\n provide: DrizzleRagIngestionLog,\n useFactory: () => new DrizzleRagIngestionLog(options.db),\n },\n ];\n return {\n module: DrizzleAgentStoreModule,\n global: true,\n providers: [\n ...ragProviders,\n { provide: DrizzleAgentStore, useFactory: () => new DrizzleAgentStore(options.db) },\n { provide: AGENT_STORE, useExisting: DrizzleAgentStore },\n // Exported, never bound to AGENT_MEMORY: that token's PRESENCE is what turns memory on, so\n // binding it here would switch the feature on for every host that installs the store. A\n // host opts in by naming this provider in `AgentModule.forRoot({ memory: { provider } })`.\n { provide: DrizzleMemoryProvider, useFactory: () => new DrizzleMemoryProvider(options.db) },\n {\n provide: DrizzlePricingStore,\n useFactory: () => new DrizzlePricingStore(options.db),\n },\n // AGENT_PRICING_STORE: the host's own store when supplied, else the default Drizzle one.\n // DrizzleGovernanceQueries prices usage against whatever is bound here.\n options.pricingStore\n ? { provide: AGENT_PRICING_STORE, useClass: options.pricingStore }\n : { provide: AGENT_PRICING_STORE, useExisting: DrizzlePricingStore },\n {\n provide: DrizzleGovernanceQueries,\n useFactory: (pricingStore: AgentPricingStore) =>\n new DrizzleGovernanceQueries(options.db, pricingStore),\n inject: [AGENT_PRICING_STORE],\n },\n { provide: AGENT_GOVERNANCE_QUERIES, useExisting: DrizzleGovernanceQueries },\n ],\n exports: [\n ...(options.ragIngestionLog === false ? [] : [DrizzleRagIngestionLog]),\n DrizzleAgentStore,\n AGENT_STORE,\n DrizzleMemoryProvider,\n DrizzleGovernanceQueries,\n AGENT_GOVERNANCE_QUERIES,\n DrizzlePricingStore,\n AGENT_PRICING_STORE,\n ],\n };\n }\n}\n"],"mappings":";;;;AAYA,SAEEA,OACAC,SACAC,MACAC,aACAC,MACAC,mBACK;AAgBA,IAAMC,cAAcH,YACzB,gBACA;EACEI,IAAIH,KAAK,IAAA,EAAMI,WAAU;EACzBC,UAAUL,KAAK,WAAA,EAAaM,QAAO;EACnCC,WAAWP,KAAK,YAAA;EAChBQ,OAAOR,KAAK,OAAA,EAASM,QAAO;EAC5BG,WAAWZ,QAAQ,aAAa;IAAEa,MAAM;EAAU,CAAA,EAAGJ,QAAO,EAAGK,QAAQ,KAAA;EACvEC,gBAAgBZ,KAAK,kBAAA;;EAErBa,cAAcb,KAAK,eAAA;EACnBc,WAAWjB,QAAQ,cAAc;IAAEa,MAAM;EAAe,CAAA,EAAGJ,QAAO;EAClES,WAAWlB,QAAQ,cAAc;IAAEa,MAAM;EAAe,CAAA,EAAGJ,QAAO;EAClEU,WAAWnB,QAAQ,cAAc;IAAEa,MAAM;EAAe,CAAA;AAC1D,GACA,CAACO,UAAU;EAACrB,MAAM,gCAAA,EAAkCsB,GAAGD,MAAMZ,UAAUY,MAAMF,SAAS;CAAE;AAQnF,IAAMI,eAAepB,YAC1B,iBACA;EACEI,IAAIH,KAAK,IAAA,EAAMI,WAAU;EACzBgB,UAAUpB,KAAK,WAAA,EACZM,QAAO,EACPe,WAAW,MAAMnB,YAAYC,IAAI;IAAEmB,UAAU;EAAU,CAAA;EAC1DC,MAAMvB,KAAK,MAAA,EAAQwB,MAAK,EAAgBlB,QAAO;EAC/CmB,SAASzB,KAAK,SAAA,EAAWM,QAAO;EAChCoB,WAAW1B,KAAK,cAAc;IAAEU,MAAM;EAAO,CAAA,EAAGc,MAAK;EACrDG,aAAa3B,KAAK,gBAAgB;I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AAqBC,UAAUjB,QAAQe;QAAa,IAC/D;UAAEZ,SAASa;UAAqBJ,aAAaE;QAAoB;QACrE;UACEX,SAASe;UACTb,YAAY,wBAACU,iBACX,IAAIG,yBAAyBlB,QAAQM,IAAIS,YAAAA,GAD/B;UAEZI,QAAQ;YAACH;;QACX;QACA;UAAEb,SAASiB;UAA0BR,aAAaM;QAAyB;;MAE7EG,SAAS;WACHrB,QAAQE,oBAAoB,QAAQ,CAAA,IAAK;UAACE;;QAC9CM;QACAC;QACAE;QACAK;QACAE;QACAN;QACAE;;IAEJ;EACF;AACF;;;;","names":["index","integer","real","sqliteTable","text","uniqueIndex","agentThread","id","primaryKey","actorRef","notNull","tenantRef","title","transient","mode","default","activeStreamId","defaultAgent","createdAt","updatedAt","deletedAt","table","on","agentMessage","threadId","references","onDelete","role","$type","content","toolCalls","toolResults","attachments","followUps","usage","agentName","runId","agentToolCall","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentRun","durationMs","errorCode","errorMessage","retries","startedAt","settledAt","promptHash","parentRunId","agentMemory","scope","key","originAuthor","originThreadId","originRunId","originActorRef","pinned","ragIngestionLog","documentId","collection","ownerType","ownerId","source","mimeType","size","chunks","reason","agentSchema","sql","statements","additiveColumns","table","column","ddl","ensureAgentSchema","db","statement","run","sql","raw","existing","all","some","row","name","and","asc","desc","eq","gte","inArray","isNotNull","isNull","lte","sql","TURN_MESSAGE_COLUMNS","id","agentMessage","role","content","agentName","toolCalls","toolResults","attachments","createdAt","DrizzleAgentStore","db","createThread","input","now","Date","thread","crypto","randomUUID","actorRef","actor","tenantRef","title","transient","activeStreamId","defaultAgent","updatedAt","deletedAt","insert","agentThread","values","toSummary","getThread","threadId","select","from","where","and","eq","isNull","undefined","messages","orderBy","asc","last","length","map","message","toStoredMessage","loadThreadForTurn","query","loadTurnWindow","messageLimit","answered","limit","hasAssistantMessage","window","desc","rows","reverse","row","listThreads","threads","summaries","push","softDeleteThread","update","set","forkThread","fromMessageId","source","Error","cutoff","findIndex","kept","slice","fork","followUps","usage","runId","ownerOfThread","ownerOfToolCall","toolCallId","agentToolCall","innerJoin","messageId","runForToolCall","ownerOfActiveStream","setTitle","promoteThread","setActiveStream","updateThread","patch","updates","Object","keys","defaultAgentForThread","recordRunStart","run","runRow","status","durationMs","errorCode","errorMessage","retries","startedAt","settledAt","promptHash","parentRunId","agentRun","recordRunEnd","end","bumpRunRetries","sql","appendMessage","setMessageToolResults","results","truncateFrom","doomedIds","delete","inArray","recordToolCall","toolName","toolType","output","executedByRef","executionMs","error","executedAt","updateToolCall","referencedMediaIds","mediaIds","isNotNull","wanted","Set","found","attachment","has","mediaId","add","filter","recordUsage","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","quotaToday","day","start","gte","lte","usedTokens","reduce","sum","lastContent","toISOString","lastMessagePreview","bucketByActor","bucketByModel","bucketByThread","bucketUsageTrend","dayBoundsUtc","rollupThreadUsage","truncateDetailContent","and","asc","count","desc","eq","gte","inArray","isNull","like","lte","sql","sum","UNCLASSIFIED_ERROR_CODE","DEFAULT_AGENT_BUCKET","TOOL_CALL_STATUSES","isToolCallStatus","value","includes","TOOL_KINDS","isToolKind","RUN_STATUSES","isRunStatus","dayStartUtc","day","dayBoundsUtc","fromDay","toDay","start","dayEndUtc","end","emptyPage","query","rows","total","page","pageSize","toRecentRunRow","run","runId","id","threadId","actorRef","agentName","status","durationMs","errorCode","errorMessage","retries","startedAt","toISOString","promptHash","parentRunId","toRunToolCallRow","toolCall","toolCallId","toolName","toolType","executionMs","executedByRef","error","createdAt","toUsageInput","row","modelId","slice","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","percentileMs","sortedDurationsMs","p","length","offset","Math","min","floor","DrizzleGovernanceQueries","db","pricingStore","loadPricing","prices","listCurrentPrices","pricing","Map","price","set","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","usageInRange","range","select","from","agentTokenUsage","where","and","gte","lte","map","spendByModel","bucketByModel","spendByActor","bucketByActor","spendByThread","limit","threadIds","Set","threads","agentThread","inArray","isNull","deletedAt","threadsById","thread","title","bucketByThread","includeUnknownThreads","usageTrend","bucketUsageTrend","recentToolCalls","agentToolCall","agentMessage","innerJoin","eq","messageId","orderBy","desc","threadRollups","rollups","messageCount","totalTokens","messageCounts","count","groupBy","bucket","get","undefined","usageTotals","sum","Number","toThreadActivityRows","rollup","lastActivityAt","updatedAt","recentThreads","runsInRange","agentRun","runMetrics","runs","completed","failed","settledDurationsMs","push","sort","left","right","successRate","durationP50Ms","durationP95Ms","runsByAgent","byAgent","result","localeCompare","runErrors","byError","errorCount","runTrend","byDay","recentRuns","pendingApprovals","input","threadTitle","requestedAt","toolStats","calls","byTool","call","key","rejected","values","p50ExecutionMs","p95ExecutionMs","toolCallsPage","filters","whereClause","totalRow","threadsPage","like","sql","toLowerCase","runsPage","approvalsPage","asc","runDetail","toolCalls","deleted","threadDetail","usageRows","usage","rollupThreadUsage","messageCountRow","messages","messageLimit","toolCallCounts","toolCallCountsByMessage","message","runTotalRow","runLimit","runTotal","content","truncated","truncateDetailContent","role","toolCallCount","messageIds","counts","actorScope","and","eq","inArray","toRecord","row","id","key","text","scope","origin","author","originAuthor","originThreadId","threadId","originRunId","runId","originActorRef","actorRef","updatedAt","toISOString","pinned","DrizzleMemoryProvider","db","list","scopes","length","rows","select","from","agentMemory","where","inArray","map","forget","ctx","deleted","delete","and","eq","actorScope","actor","returning","write","assertAuthorMayWriteScope","now","Date","columns","insert","values","crypto","randomUUID","createdAt","onConflictDoUpdate","target","set","undefined","Error","pin","updated","update","own","and","eq","DrizzlePricingStore","db","upsertModelPrice","input","update","agentModelPricing","set","isCurrent","where","and","eq","modelId","insert","values","id","crypto","randomUUID","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","Date","listCurrentPrices","rows","select","from","map","row","toISOString","subscribe","unsubscribe","Injectable","Logger","and","asc","count","desc","eq","gt","lt","or","CHANNELS","name","status","str","value","length","num","Number","isFinite","RAG_INGESTION_LOG_PAGE_ORDER","desc","ragIngestionLog","updatedAt","asc","documentId","DEFAULT_PAGE_SIZE","DEFAULT_BATCH_SIZE","batches","batchSize","requested","Math","trunc","CURSOR_COLUMNS","DrizzleRagIngestionLog","logger","Logger","teardowns","inFlight","Set","db","onModuleInit","channel","listener","message","payload","undefined","track","record","subscribe","push","unsubscribe","onModuleDestroy","teardown","settle","Promise","allSettled","list","query","rows","select","from","where","orderBy","limit","offset","listPage","totalRow","count","total","iterate","options","sweep","after","filter","listDocumentIds","ids","row","get","eq","remove","removed","delete","returning","removeByCollection","collection","page","cursor","keyset","and","base","or","lt","gt","mediaId","now","Date","ownerType","ownerId","source","mimeType","size","outcome","chunks","reason","error","insert","values","createdAt","onConflictDoUpdate","target","set","warn","Error","String","promise","tracked","finally","add","AGENT_GOVERNANCE_QUERIES","AGENT_PRICING_STORE","AGENT_STORE","Module","DrizzleAgentStoreModule","forRoot","options","ragProviders","ragIngestionLog","provide","DrizzleRagIngestionLog","useFactory","db","module","global","providers","DrizzleAgentStore","AGENT_STORE","useExisting","DrizzleMemoryProvider","DrizzlePricingStore","pricingStore","AGENT_PRICING_STORE","useClass","DrizzleGovernanceQueries","inject","AGENT_GOVERNANCE_QUERIES","exports"]}