@dudousxd/nestjs-agent-store-drizzle 0.36.2 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/schema.ts","../src/ensure-schema.ts","../src/dialect.ts","../src/schema-mysql.ts","../src/schema-pg.ts","../src/drizzle-agent-store.ts","../src/drizzle-action-proposal-store.ts","../src/action-proposal-transaction-mode.ts","../src/drizzle-governance-queries.ts","../src/drizzle-memory-provider.ts","../src/drizzle-pricing-store.ts","../src/drizzle-token-stream-sink.ts","../src/drizzle-confirm-token-store.ts","../src/drizzle-channel-store.ts","../src/drizzle-poppy-store.ts","../src/drizzle-poppy-connection-store.ts","../src/drizzle-rag-ingestion-log.ts","../src/drizzle-agent-store.module.ts"],"sourcesContent":["export * from './schema.js';\nexport * from './ensure-schema.js';\nexport * from './drizzle-agent-store.js';\nexport * from './drizzle-action-proposal-store.js';\nexport * from './drizzle-governance-queries.js';\nexport * from './drizzle-memory-provider.js';\nexport * from './drizzle-pricing-store.js';\nexport * from './drizzle-token-stream-sink.js';\nexport * from './drizzle-confirm-token-store.js';\nexport * from './drizzle-channel-store.js';\nexport * from './drizzle-poppy-store.js';\nexport * from './drizzle-poppy-connection-store.js';\nexport * from './drizzle-rag-ingestion-log.js';\nexport * from './drizzle-agent-store.module.js';\nexport { pgAgentSchema } from './schema-pg.js';\nexport { mysqlAgentSchema } from './schema-mysql.js';\nexport {\n type AgentDialect,\n type AgentMySqlDb,\n type AgentPgDb,\n type AgentSqliteDb,\n agentDialectOf,\n} from './dialect.js';\n","import type {\n ActionProposal,\n Actor,\n AgentUiComponent,\n MemoryOrigin,\n MessageAttachment,\n MessageFeedback,\n MessageRole,\n MessageUsage,\n PageContext,\n QueuePause,\n ToolCallRequest,\n ToolCallStatus,\n ToolConfirmation,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport type {\n AgentHostContext,\n CostSource,\n GenuiErrorCategory,\n GenuiToolMarker,\n GenuiValidity,\n RecordGenuiCallInput,\n RunStepTiming,\n} from '@dudousxd/nestjs-agent-core';\nimport type { UiCapabilities } from '@dudousxd/nestjs-agent-core/genui';\nimport {\n index,\n integer,\n primaryKey,\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 /** The model every turn on this thread runs on unless the send names one; `null` → default. */\n model: text('model'),\n /** The persona a send on this thread runs under when it names none; `null` → the agent's default. */\n persona: text('persona'),\n /** Why the thread's message queue stopped draining; `null` → it drains. */\n queuePause: text('queue_pause', { mode: 'json' }).$type<QueuePause>(),\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) => [\n index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt),\n // `ownerOfActiveStream` reads by run id on every stream attach and reconnect.\n index('agent_thread_active_stream_idx').on(table.activeStreamId),\n ],\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 actionProposalOutcome: text('action_proposal_outcome'),\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 /** The persona the turn that wrote this message ran under; `null` → none. */\n persona: text('persona'),\n runId: text('run_id'),\n /** The step's streamed thinking; `null` when the model produced none. */\n reasoning: text('reasoning'),\n reasoningMs: integer('reasoning_ms'),\n /** Components pushed during the step (`ui` stream frames), replayed on reload. */\n ui: text('ui', { mode: 'json' }).$type<AgentUiComponent[]>(),\n /** The thread owner's thumbs-up/down (+ comment); `null` when unrated. Not copied on fork. */\n feedback: text('feedback', { mode: 'json' }).$type<MessageFeedback>(),\n /**\n * The message's place in its thread, 1-based, assigned on append — what orders a transcript.\n * `created_at` cannot: two messages of one turn routinely share a timestamp, and the uuid that\n * broke the tie is random. `null` on a row from before the column; those sort first.\n */\n seq: integer('seq'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [\n index('agent_message_thread_created_idx').on(table.threadId, table.createdAt),\n // Transcript reads order a thread's messages by `seq`.\n index('agent_message_thread_seq_idx').on(table.threadId, table.seq),\n ],\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 proposalId: text('proposal_id'),\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 /** Resolved per-call wording; null falls back to presentation templates. */\n confirmation: text('confirmation', { mode: 'json' }).$type<ToolConfirmation>(),\n /** Who had to approve it (`requester` or a role); null for a call no policy put to anyone. */\n approver: text('approver'),\n /** When the approval request lapses; null → never. */\n expiresAt: integer('expires_at', { mode: 'timestamp_ms' }),\n /** The approval covers later calls of this tool in this thread. */\n remember: integer('remember', { mode: 'boolean' }),\n /** The surface the decision came through (`web`, `slack`, `remembered`, …). */\n decidedVia: text('decided_via'),\n },\n (table) => [\n index('agent_tool_call_message_idx').on(table.messageId),\n // The approvals inbox: `pending_approval`, oldest first.\n index('agent_tool_call_status_created_idx').on(table.status, table.createdAt),\n index('agent_tool_call_run_idx').on(table.runId),\n index('agent_tool_call_created_idx').on(table.createdAt),\n ],\n);\n\n/**\n * A message sent while a turn was running on its thread, waiting to run after it — see the core\n * `ChatQueueStore`. Not part of the transcript: the turn it starts appends it as its user message,\n * and the row is deleted as it starts. `position` orders a thread's queue (head first); it is\n * rewritten on a move, and only ever compared within one thread. `threadId` cascades on delete.\n */\nexport const agentQueuedMessage = sqliteTable(\n 'agent_queued_message',\n {\n uiCapabilities: text('ui_capabilities', { mode: 'json' }).$type<UiCapabilities>(),\n hostContext: text('host_context', { mode: 'json' }).$type<AgentHostContext>(),\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n /** Who queued it — the turn it starts runs as this actor. */\n actor: text('actor', { mode: 'json' }).$type<Actor>().notNull(),\n content: text('content').notNull(),\n attachments: text('attachments', { mode: 'json' }).$type<MessageAttachment[]>(),\n agentName: text('agent_name'),\n /** The persona the send resolved — what the message starts under. */\n persona: text('persona'),\n model: text('model'),\n pageContext: text('page_context', { mode: 'json' }).$type<PageContext>(),\n interrupt: integer('interrupt', { mode: 'boolean' }).notNull().default(false),\n position: integer('position').notNull(),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_queued_message_thread_position_idx').on(table.threadId, table.position)],\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 // NULL for usage recorded outside any conversation (`AgentService.recordUsage`).\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 /** The turn's USD cost: provider-reported, or estimated from the price row (see `costSource`); null when unpriced. */\n costUsd: real('cost_usd'),\n /** Where `cost_usd` came from: `'provider'` (reported) or `'estimate'` (tokens × the price row); null on rows from before it existed (reported). */\n costSource: text('cost_source').$type<CostSource>(),\n /** The run the row belongs to. */\n runId: text('run_id'),\n /** What the spend was for: `agent:<name>` for an agent turn, the app's own otherwise; null → `agent`. */\n feature: text('feature'),\n provider: text('provider'),\n tenantRef: text('tenant_ref'),\n /** Units a row bills by when they are not tokens. */\n audioSeconds: real('audio_seconds'),\n characters: integer('characters'),\n requests: integer('requests'),\n /** The caller's own JSON, never read by the library. */\n metadata: text('metadata', { mode: 'json' }).$type<Record<string, unknown>>(),\n /** `false` keeps the row out of the agent's quota windows (`recordUsage({ countsTowardsQuota: false })`). */\n countsTowardsQuota: integer('counts_towards_quota', { mode: 'boolean' })\n .notNull()\n .default(true),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [\n index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt),\n index('agent_token_usage_created_idx').on(table.createdAt),\n index('agent_token_usage_thread_idx').on(table.threadId),\n index('agent_token_usage_feature_created_idx').on(table.feature, table.createdAt),\n ],\n);\n\n/**\n * Generative-UI telemetry (`AgentStore.recordGenuiCalls`): one row per UI tool call, keyed by the\n * tool call's id, so a replayed record replaces rather than duplicates. Metadata only — `payload`\n * (the call's arguments) is filled solely when the tool samples payloads. `created_at` is epoch-ms.\n */\nexport const agentGenuiCall = sqliteTable(\n 'agent_genui_call',\n {\n id: text('id').primaryKey(),\n runId: text('run_id').notNull(),\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 step: integer('step').notNull(),\n toolName: text('tool_name').notNull(),\n channel: text('channel').notNull(),\n mode: text('mode').$type<GenuiToolMarker['mode']>().notNull(),\n modelId: text('model_id').notNull(),\n attempt: integer('attempt').notNull(),\n outcome: text('outcome').$type<RecordGenuiCallInput['outcome']>().notNull(),\n validity: text('validity').$type<GenuiValidity>().notNull(),\n errorCategory: text('error_category').$type<GenuiErrorCategory>(),\n errorMessage: text('error_message'),\n inputTokens: integer('input_tokens').notNull(),\n outputTokens: integer('output_tokens').notNull(),\n costUsd: real('cost_usd'),\n costSource: text('cost_source').$type<CostSource>(),\n firstFrameMs: integer('first_frame_ms'),\n completeFrameMs: integer('complete_frame_ms'),\n payloadBytes: integer('payload_bytes').notNull(),\n payload: text('payload'),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [\n index('agent_genui_call_created_idx').on(table.createdAt),\n index('agent_genui_call_run_idx').on(table.runId),\n ],\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 /** Turn start to the first `text` frame; null for a run that streamed none or did not complete. */\n ttftMs: integer('ttft_ms'),\n /** The run's known spend (the sum of its model calls with a known cost); null when none had one. */\n costUsd: real('cost_usd'),\n /** The model the run's last model call resolved to. */\n modelId: text('model_id'),\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 /** Enqueue → body start (ms); null when not read. */\n queueMs: integer('queue_ms'),\n /** Where the completed run's time went: model and tool totals, counts, and the per-step list. */\n modelMs: integer('model_ms'),\n toolsMs: integer('tools_ms'),\n modelCalls: integer('model_calls'),\n toolCalls: integer('tool_calls'),\n timings: text('timings', { mode: 'json' }).$type<RunStepTiming[]>(),\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/**\n * Text channels' short-lived state (`@dudousxd/nestjs-agent-channels`), one row per key: the provider\n * message ids already answered, a question waiting for the person's answer, an outcome already\n * relayed. The primary key is the lock a claim takes; `expires_at` is epoch-ms, and past it the row\n * is free again and dead weight for `DrizzleChannelStore.purgeExpired`. Keys longer than 255\n * characters are stored by their SHA-256.\n */\nexport const agentChannelState = sqliteTable(\n 'agent_channel_state',\n {\n key: text('key').primaryKey(),\n value: text('value'),\n expiresAt: integer('expires_at').notNull(),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [index('agent_channel_state_expires_idx').on(table.expiresAt)],\n);\n\n/**\n * Spent confirm tokens (`defineConfirmedTool`), one row per token, keyed by its SHA-256 — the\n * primary key is the lock that makes a confirmation single use across replicas. Only the hash, the\n * actor and the tool are kept, never an argument. `expires_at` is epoch-ms; past it the row is dead\n * weight for `DrizzleConfirmTokenStore.purgeExpired`.\n */\nexport const agentConfirmToken = sqliteTable(\n 'agent_confirm_token',\n {\n hash: text('hash').primaryKey(),\n actorRef: text('actor_ref').notNull(),\n tool: text('tool').notNull(),\n expiresAt: integer('expires_at').notNull(),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [index('agent_confirm_token_expires_idx').on(table.expiresAt)],\n);\n\n/**\n * One row per frame of a run's live stream (`DrizzleTokenStreamSink`), numbered per run from 1 with\n * no gaps. `frame` is one NDJSON line; `null` marks the end, with `error` set when the run failed.\n * `created_at` (epoch-ms) is what the TTL counts from — a run's LAST row.\n */\nexport const agentStreamFrame = sqliteTable(\n 'agent_stream_frame',\n {\n runId: text('run_id').notNull(),\n seq: integer('seq').notNull(),\n frame: text('frame'),\n error: text('error'),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [primaryKey({ columns: [table.runId, table.seq] })],\n);\n\n/** Independent action proposals; decision and execution work commit in one fenced row. */\nexport const agentActionProposal = sqliteTable(\n 'agent_action_proposal',\n {\n id: text('id').primaryKey(),\n scopeKey: text('scope_key').notNull(),\n decision: text('decision').$type<ActionProposal['decision']>().notNull(),\n logicalSort: text('logical_sort').notNull(),\n createFingerprint: text('create_fingerprint').notNull(),\n proposal: text('proposal', { mode: 'json' }).$type<ActionProposal>().notNull(),\n version: integer('version').notNull().default(0),\n executionStatus:\n text('execution_status').$type<NonNullable<ActionProposal['execution']>['status']>(),\n leaseExpiresAt: integer('lease_expires_at'),\n deliveryStatus: text('delivery_status'),\n deliveryLeaseExpiresAt: integer('delivery_lease_expires_at'),\n replacementGroupKey: text('replacement_group_key'),\n outcomeIdKey: text('outcome_id_key'),\n proposalExpiresAt: integer('proposal_expires_at'),\n discoveryIndexVersion: integer('discovery_index_version').notNull().default(0),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [\n index('agent_action_proposal_execution_idx').on(\n table.discoveryIndexVersion,\n table.executionStatus,\n table.leaseExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_expiry_idx').on(\n table.discoveryIndexVersion,\n table.decision,\n table.proposalExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_replacement_idx').on(\n table.scopeKey,\n table.replacementGroupKey,\n table.decision,\n ),\n index('agent_action_proposal_delivery_idx').on(\n table.deliveryStatus,\n table.deliveryLeaseExpiresAt,\n table.createdAt,\n ),\n uniqueIndex('agent_action_proposal_outcome_idx').on(table.outcomeIdKey),\n index('agent_action_proposal_scope_idx').on(table.scopeKey, table.createdAt, table.id),\n ],\n);\n\n/**\n * Personal Agent Protocol (Poppy) conversations (`DrizzlePoppyStore`): who it is with, its status,\n * the User's context and the identity its turns run as (JSON text), and the reader lease\n * (`reader_holder` until `reader_until`, epoch-ms) that lets one replica at a time write a reply.\n * `pruned_seq`: events at or below it were pruned.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConversation = sqliteTable('agent_poppy_conversation', {\n id: text('id').primaryKey(),\n clientId: text('client_id').notNull(),\n userId: text('user_id').notNull(),\n accountRef: text('account_ref'),\n agentName: text('agent_name').notNull(),\n threadId: text('thread_id'),\n parentId: text('parent_id'),\n openDirectId: text('open_direct_id'),\n status: text('status').notNull(),\n responder: text('responder').notNull(),\n context: text('context'),\n activeRunId: text('active_run_id'),\n turnSeq: integer('turn_seq').notNull(),\n grantInfo: text('grant_info'),\n readerHolder: text('reader_holder'),\n readerUntil: integer('reader_until'),\n prunedSeq: integer('pruned_seq').notNull(),\n createdAt: integer('created_at').notNull(),\n updatedAt: integer('updated_at').notNull(),\n});\n\n/**\n * A Poppy conversation's events, append-only, numbered per conversation. The primary key is the\n * position, so two appends racing for one cannot both win; `event_key` (unique per conversation)\n * is what keeps a re-read turn from writing its reply twice. `event` is the event as JSON text.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyEvent = sqliteTable(\n 'agent_poppy_event',\n {\n conversationId: text('conversation_id').notNull(),\n seq: integer('seq').notNull(),\n id: text('id').notNull(),\n type: text('type').notNull(),\n event: text('event').notNull(),\n eventKey: text('event_key'),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.conversationId, table.seq] }),\n uniqueIndex('agent_poppy_event_key_idx').on(table.conversationId, table.eventKey),\n index('agent_poppy_event_id_idx').on(table.conversationId, table.id),\n ],\n);\n\n/**\n * Accepted Poppy messages, one row per (owner, message id) — the primary key is the idempotency lock\n * that makes two deliveries of one message one (§7.3); `response` is what the first got, as JSON.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyMessage = sqliteTable(\n 'agent_poppy_message',\n {\n owner: text('owner').notNull(),\n messageId: text('message_id').notNull(),\n fingerprint: text('fingerprint').notNull(),\n conversationId: text('conversation_id').notNull(),\n response: text('response').notNull(),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.messageId] })],\n);\n\n/**\n * This app's Poppy connections (`DrizzlePoppyConnectionStore`): one per (owner, Company issuer),\n * holding the client state SEALED by the caller — never a token in the clear.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnection = sqliteTable(\n 'agent_poppy_connection',\n {\n owner: text('owner').notNull(),\n issuer: text('issuer').notNull(),\n domain: text('domain').notNull(),\n organization: text('organization').notNull(),\n scope: text('scope').notNull(),\n status: text('status').notNull(),\n state: text('state').notNull(),\n createdAt: integer('created_at').notNull(),\n updatedAt: integer('updated_at').notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.issuer] })],\n);\n\n/**\n * Poppy sign-ins in flight, started by the `connect` tool and completed on the connect page. `actor`\n * is JSON text; `flow` the sealed per-method state.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnect = sqliteTable('agent_poppy_connect', {\n id: text('id').primaryKey(),\n owner: text('owner').notNull(),\n domain: text('domain').notNull(),\n issuer: text('issuer').notNull(),\n organization: text('organization').notNull(),\n scope: text('scope').notNull(),\n actor: text('actor'),\n threadId: text('thread_id'),\n runId: text('run_id'),\n toolCallId: text('tool_call_id'),\n flow: text('flow'),\n status: text('status').notNull(),\n expiresAt: integer('expires_at').notNull(),\n createdAt: integer('created_at').notNull(),\n});\n\n/** The tables this store owns, as one schema object, ready for `drizzle(client, { schema })`. */\nexport const agentSchema = {\n agentActionProposal,\n agentThread,\n agentMessage,\n agentQueuedMessage,\n agentToolCall,\n agentTokenUsage,\n agentGenuiCall,\n agentModelPricing,\n agentRun,\n agentMemory,\n ragIngestionLog,\n agentConfirmToken,\n agentChannelState,\n agentStreamFrame,\n agentPoppyConversation,\n agentPoppyEvent,\n agentPoppyMessage,\n agentPoppyConnection,\n agentPoppyConnect,\n};\n\n/**\n * The database handle the stores take — SQLite, Postgres or MySQL. Defined in `./dialect.js`;\n * re-exported here, where it has always been importable from.\n */\nexport type { AgentDrizzleDb } from './dialect.js';\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 queued message row as Drizzle selects it. */\nexport type AgentQueuedMessageRow = typeof agentQueuedMessage.$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 { type Column, type SQL, getTableName, sql } from 'drizzle-orm';\nimport { getTableConfig as mysqlTableConfig } from 'drizzle-orm/mysql-core';\nimport { getTableConfig as pgTableConfig } from 'drizzle-orm/pg-core';\nimport { getTableConfig as sqliteTableConfig } from 'drizzle-orm/sqlite-core';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentMySqlDb,\n type AgentPgDb,\n agentDialectOf,\n agentTablesFor,\n querySql,\n runSql,\n} from './dialect.js';\n\n/**\n * Creates the agent tables a database lacks, adds the columns and indexes an existing one lacks, and\n * relaxes a column the schema made nullable since (`agent_token_usage.thread_id`: usage recorded\n * outside a conversation) — never drops anything — safe to run on every boot against a shared\n * database. Postgres drops the `NOT NULL` in place, MySQL `MODIFY`s the column, and SQLite, which can\n * do neither, rebuilds that one table (created under a scratch name, rows copied, renamed) inside a\n * savepoint; only a table no other table references is rebuilt, and its indexes come back below. SQLite,\n * Postgres and MySQL alike, with no drizzle-kit and no migration files.\n *\n * The DDL is rendered from the dialect's Drizzle schema ({@link import('./schema.js').agentSchema},\n * {@link import('./schema-pg.js').pgAgentSchema}, {@link import('./schema-mysql.js').mysqlAgentSchema})\n * rather than written out by hand, so the tables this creates are the tables the stores query, column\n * for column, and a column added to a schema later reaches every database that is already running\n * without a list of `ALTER`s to keep in step. A column added later must therefore be nullable or\n * carry a default — an existing table cannot take a `NOT NULL` column without one.\n *\n * On Postgres and MySQL it runs under a cross-replica lock (`pg_advisory_xact_lock`, `get_lock`),\n * held on one connection for the whole run: several replicas booting an empty database at once would\n * otherwise race their `CREATE TABLE IF NOT EXISTS` — which Postgres does not make race-safe — and\n * all but one fail. On Postgres the whole heal is also one transaction, so it lands entirely or not\n * at all.\n */\nexport async function ensureAgentSchema(db: AgentDrizzleDb): Promise<void> {\n const dialect = agentDialectOf(db);\n if (dialect === 'postgres') {\n await (db as AgentPgDb).transaction(async (tx) => {\n await tx.execute(sql.raw(`select pg_advisory_xact_lock(hashtext('${LOCK_NAME}'))`));\n await heal(tx as unknown as AgentDrizzleDb, dialect);\n });\n return;\n }\n if (dialect === 'mysql') {\n await (db as AgentMySqlDb).transaction(async (tx) => {\n // A session lock: taken and released on the transaction's one connection. MySQL's DDL commits\n // implicitly, so this is a pinned connection rather than an atomic heal.\n await tx.execute(sql.raw(`select get_lock('${LOCK_NAME}', 30)`));\n try {\n await heal(tx as unknown as AgentDrizzleDb, dialect);\n } finally {\n await tx.execute(sql.raw(`select release_lock('${LOCK_NAME}')`));\n }\n });\n return;\n }\n await heal(db, dialect);\n}\n\nconst LOCK_NAME = 'nestjs_agent_schema';\n\n/** Table options MySQL needs spelled out: InnoDB for the foreign keys, a case-sensitive collation. */\nconst MYSQL_TABLE_OPTIONS = 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin';\n\ninterface IndexSpec {\n name: string;\n unique: boolean;\n columns: string[];\n}\n\ninterface TableSpec {\n name: string;\n columns: Column[];\n primaryKey: string[];\n foreignKeys: { columns: string[]; table: string; foreignColumns: string[]; onDelete?: string }[];\n indexes: IndexSpec[];\n}\n\n/** One agent table, read off its Drizzle definition in `dialect`. */\nfunction tableSpec(dialect: AgentDialect, table: unknown): TableSpec {\n const config =\n dialect === 'postgres'\n ? pgTableConfig(table as Parameters<typeof pgTableConfig>[0])\n : dialect === 'mysql'\n ? mysqlTableConfig(table as Parameters<typeof mysqlTableConfig>[0])\n : sqliteTableConfig(table as Parameters<typeof sqliteTableConfig>[0]);\n const columns = config.columns as unknown as Column[];\n const compositeKey = config.primaryKeys[0]?.columns.map((column) => column.name);\n return {\n name: config.name,\n columns,\n primaryKey: compositeKey ?? columns.filter((column) => column.primary).map((c) => c.name),\n foreignKeys: config.foreignKeys.map((foreignKey) => {\n const reference = foreignKey.reference();\n return {\n columns: reference.columns.map((column) => column.name),\n table: getTableName(reference.foreignTable),\n foreignColumns: reference.foreignColumns.map((column) => column.name),\n ...(foreignKey.onDelete !== undefined ? { onDelete: foreignKey.onDelete } : {}),\n };\n }),\n indexes: config.indexes.map((index) => ({\n name: String(index.config.name),\n unique: index.config.unique === true,\n columns: (index.config.columns as { name?: string }[]).map((column) => String(column.name)),\n })),\n };\n}\n\nfunction quote(dialect: AgentDialect, identifier: string): string {\n return dialect === 'mysql' ? `\\`${identifier}\\`` : `\"${identifier}\"`;\n}\n\nfunction literal(dialect: AgentDialect, value: unknown): string {\n if (typeof value === 'boolean') {\n return dialect === 'sqlite' ? (value ? '1' : '0') : value ? 'true' : 'false';\n }\n if (typeof value === 'number') return String(value);\n return `'${String(value).replaceAll(\"'\", \"''\")}'`;\n}\n\n/** `name TYPE [NOT NULL] [DEFAULT …]` — no key or reference, which the table states separately. */\nfunction columnDefinition(dialect: AgentDialect, column: Column): string {\n const parts = [quote(dialect, column.name), column.getSQLType()];\n if (column.notNull) parts.push('NOT NULL');\n if (column.hasDefault && column.default !== undefined) {\n parts.push(`DEFAULT ${literal(dialect, column.default)}`);\n }\n return parts.join(' ');\n}\n\nfunction createTableSql(dialect: AgentDialect, spec: TableSpec): string {\n const q = (identifier: string) => quote(dialect, identifier);\n const lines = spec.columns.map((column) => columnDefinition(dialect, column));\n lines.push(`PRIMARY KEY (${spec.primaryKey.map(q).join(', ')})`);\n for (const foreignKey of spec.foreignKeys) {\n lines.push(\n `FOREIGN KEY (${foreignKey.columns.map(q).join(', ')}) REFERENCES ${q(foreignKey.table)} (${foreignKey.foreignColumns.map(q).join(', ')})${foreignKey.onDelete !== undefined ? ` ON DELETE ${foreignKey.onDelete.toUpperCase()}` : ''}`,\n );\n }\n const options = dialect === 'mysql' ? ` ${MYSQL_TABLE_OPTIONS}` : '';\n return `CREATE TABLE IF NOT EXISTS ${q(spec.name)} (\\n ${lines.join(',\\n ')}\\n)${options}`;\n}\n\n/** The DDL that creates the agent tables in `dialect`, in dependency order. Indexes included. */\nexport function agentSchemaDdl(dialect: AgentDialect): string[] {\n const statements: string[] = [];\n for (const spec of specs(dialect)) {\n statements.push(createTableSql(dialect, spec));\n for (const index of spec.indexes) {\n statements.push(createIndexSql(dialect, spec.name, index));\n }\n }\n return statements;\n}\n\nfunction createIndexSql(dialect: AgentDialect, table: string, index: IndexSpec): string {\n const q = (identifier: string) => quote(dialect, identifier);\n // MySQL has no `IF NOT EXISTS` on an index; `heal` asks first there.\n const guard = dialect === 'mysql' ? '' : 'IF NOT EXISTS ';\n return `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${guard}${q(index.name)} ON ${q(table)} (${index.columns.map(q).join(', ')})`;\n}\n\n/** Every agent table in `dialect`, parents before the children that reference them. */\nfunction specs(dialect: AgentDialect): TableSpec[] {\n const all = Object.values(agentTablesFor(dialect)).map((table) => tableSpec(dialect, table));\n const ordered: TableSpec[] = [];\n const placed = new Set<string>();\n while (ordered.length < all.length) {\n const ready = all.filter(\n (spec) =>\n !placed.has(spec.name) &&\n spec.foreignKeys.every((key) => key.table === spec.name || placed.has(key.table)),\n );\n if (ready.length === 0) throw new Error('agent schema: circular foreign keys');\n for (const spec of ready) {\n ordered.push(spec);\n placed.add(spec.name);\n }\n }\n return ordered;\n}\n\nasync function existingColumns(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n table: string,\n): Promise<Set<string>> {\n return new Set((await columnNullability(db, dialect, table)).keys());\n}\n\n/** Each column the table has, and whether the database lets it hold NULL. */\nasync function columnNullability(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n table: string,\n): Promise<Map<string, boolean>> {\n if (dialect === 'sqlite') {\n const rows = await querySql<{ name: string; notnull: number }>(\n db,\n dialect,\n sql.raw(`PRAGMA table_info(\"${table}\")`),\n );\n return new Map(rows.map((row) => [String(row.name), Number(row.notnull) === 0]));\n }\n const rows = await querySql<{ name: string; nullable: string }>(\n db,\n dialect,\n sql`select column_name as name, is_nullable as nullable from information_schema.columns where table_schema = ${sql.raw(dialect === 'mysql' ? 'database()' : 'current_schema()')} and table_name = ${table}`,\n );\n return new Map(\n rows.map((row) => [\n String(row.name ?? (row as { NAME?: string }).NAME),\n String(row.nullable ?? (row as { NULLABLE?: string }).NULLABLE).toUpperCase() === 'YES',\n ]),\n );\n}\n\n/**\n * Let `column` hold NULL. In place on Postgres and MySQL; on SQLite the table is rebuilt in its\n * current shape under a scratch name, its rows copied, and renamed over the old one, inside a\n * savepoint — refused for a table another agent table references, whose foreign keys a rebuild\n * would break.\n */\nasync function relaxNotNull(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n spec: TableSpec,\n column: Column,\n all: readonly TableSpec[],\n): Promise<void> {\n const q = (identifier: string) => quote(dialect, identifier);\n if (dialect === 'postgres') {\n await runSql(\n db,\n dialect,\n sql.raw(`ALTER TABLE ${q(spec.name)} ALTER COLUMN ${q(column.name)} DROP NOT NULL`),\n );\n return;\n }\n if (dialect === 'mysql') {\n await runSql(\n db,\n dialect,\n sql.raw(`ALTER TABLE ${q(spec.name)} MODIFY ${columnDefinition(dialect, column)}`),\n );\n return;\n }\n if (\n all.some((other) => other.foreignKeys.some((key) => key.table === spec.name && other !== spec))\n ) {\n throw new Error(\n `agent schema: cannot make ${spec.name}.${column.name} nullable on SQLite — other tables reference ${spec.name}`,\n );\n }\n const scratch = `${spec.name}__rebuild`;\n const present = [...(await columnNullability(db, dialect, spec.name)).keys()];\n const list = present.map(q).join(', ');\n await runSql(db, dialect, sql.raw('SAVEPOINT agent_schema_rebuild'));\n try {\n await runSql(db, dialect, sql.raw(`DROP TABLE IF EXISTS ${q(scratch)}`));\n await runSql(db, dialect, sql.raw(createTableSql(dialect, { ...spec, name: scratch })));\n await runSql(\n db,\n dialect,\n sql.raw(`INSERT INTO ${q(scratch)} (${list}) SELECT ${list} FROM ${q(spec.name)}`),\n );\n await runSql(db, dialect, sql.raw(`DROP TABLE ${q(spec.name)}`));\n await runSql(db, dialect, sql.raw(`ALTER TABLE ${q(scratch)} RENAME TO ${q(spec.name)}`));\n await runSql(db, dialect, sql.raw('RELEASE SAVEPOINT agent_schema_rebuild'));\n } catch (error) {\n await runSql(db, dialect, sql.raw('ROLLBACK TO SAVEPOINT agent_schema_rebuild')).catch(\n () => undefined,\n );\n await runSql(db, dialect, sql.raw('RELEASE SAVEPOINT agent_schema_rebuild')).catch(\n () => undefined,\n );\n throw error;\n }\n}\n\nasync function indexExists(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n table: string,\n index: string,\n): Promise<boolean> {\n let query: SQL;\n if (dialect === 'sqlite') {\n query = sql`select name from sqlite_master where type = 'index' and name = ${index}`;\n } else if (dialect === 'postgres') {\n query = sql`select indexname as name from pg_indexes where schemaname = current_schema() and indexname = ${index}`;\n } else {\n query = sql`select index_name as name from information_schema.statistics where table_schema = database() and table_name = ${table} and index_name = ${index}`;\n }\n return (await querySql(db, dialect, query)).length > 0;\n}\n\nasync function heal(db: AgentDrizzleDb, dialect: AgentDialect): Promise<void> {\n const all = specs(dialect);\n for (const spec of all) {\n await runSql(db, dialect, sql.raw(createTableSql(dialect, spec)));\n // `CREATE TABLE IF NOT EXISTS` is inert against a table that is already there, so a column the\n // schema gained since is added here. Asked, not attempted-and-swallowed: a swallowed error cannot\n // tell \"already there\" from \"the ALTER is malformed\".\n const present = await existingColumns(db, dialect, spec.name);\n for (const column of spec.columns) {\n if (!present.has(column.name)) {\n await runSql(\n db,\n dialect,\n sql.raw(\n `ALTER TABLE ${quote(dialect, spec.name)} ADD COLUMN ${columnDefinition(dialect, column)}`,\n ),\n );\n }\n }\n // A column the schema made nullable since it was created. Primary-key columns are left alone:\n // drizzle reports them nullable on some dialects, and none of them ever relaxes.\n const nullable = await columnNullability(db, dialect, spec.name);\n for (const column of spec.columns) {\n if (column.notNull || spec.primaryKey.includes(column.name)) continue;\n if (nullable.get(column.name) === false) {\n await relaxNotNull(db, dialect, spec, column, all);\n }\n }\n for (const index of spec.indexes) {\n if (!(await indexExists(db, dialect, spec.name, index.name))) {\n await runSql(db, dialect, sql.raw(createIndexSql(dialect, spec.name, index)));\n }\n }\n }\n}\n","import { type SQL, type TablesRelationalConfig, is } from 'drizzle-orm';\nimport {\n MySqlDatabase,\n type MySqlQueryResultHKT,\n type PreparedQueryHKTBase,\n} from 'drizzle-orm/mysql-core';\nimport { PgDatabase, type PgQueryResultHKT } from 'drizzle-orm/pg-core';\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';\nimport { mysqlAgentSchema } from './schema-mysql.js';\nimport { pgAgentSchema } from './schema-pg.js';\nimport { agentSchema } from './schema.js';\n\n/** The SQL dialects the stores in this package run on. */\nexport type AgentDialect = 'sqlite' | 'postgres' | 'mysql';\n\n/** A Drizzle SQLite database, any driver (better-sqlite3, libsql, D1, …), sync or async. */\nexport type AgentSqliteDb = BaseSQLiteDatabase<\n 'sync' | 'async',\n unknown,\n Record<string, unknown>,\n TablesRelationalConfig\n>;\n/** A Drizzle Postgres database, any driver (node-postgres, postgres.js, Neon, PGlite, …). */\nexport type AgentPgDb = PgDatabase<\n PgQueryResultHKT,\n Record<string, unknown>,\n TablesRelationalConfig\n>;\n/** A Drizzle MySQL database (mysql2, PlanetScale, …). */\nexport type AgentMySqlDb = MySqlDatabase<\n MySqlQueryResultHKT,\n PreparedQueryHKTBase,\n Record<string, unknown>,\n TablesRelationalConfig\n>;\n\n/**\n * The database handle every store here takes: a Drizzle database on SQLite, Postgres or MySQL. The\n * host owns the connection and passes the `drizzle(...)` instance in; the store tells the dialect\n * from the handle itself, and finds its tables in that dialect's schema\n * ({@link import('./schema.js').agentSchema}, {@link pgAgentSchema}, {@link mysqlAgentSchema}).\n */\nexport type AgentDrizzleDb = AgentSqliteDb | AgentPgDb | AgentMySqlDb;\n\n/** Which dialect a Drizzle handle speaks. */\nexport function agentDialectOf(db: AgentDrizzleDb): AgentDialect {\n if (is(db, PgDatabase)) return 'postgres';\n if (is(db, MySqlDatabase)) return 'mysql';\n return 'sqlite';\n}\n\n/** The SQLite tables, which every dialect's table set mirrors key for key and column for column. */\nexport type AgentTables = typeof agentSchema;\n\n/**\n * The agent tables in `dialect`, typed as the SQLite set.\n *\n * The three schemas declare the same property names over the same column names, and a Drizzle query\n * builder runs whatever table it is handed: the column objects carry their own driver mapping (a\n * `Date` becomes epoch-ms on SQLite, ISO on Postgres, `datetime` text on MySQL). So the stores are\n * written once, against the SQLite types, and run on the table set of the handle's dialect. The few\n * places the dialects really differ — `RETURNING`, upserts, raw statements — go through the helpers\n * below instead.\n */\nexport function agentTablesFor(dialect: AgentDialect): AgentTables {\n if (dialect === 'postgres') return pgAgentSchema as unknown as AgentTables;\n if (dialect === 'mysql') return mysqlAgentSchema as unknown as AgentTables;\n return agentSchema;\n}\n\n/**\n * The handle as the SQLite query-builder type the stores are written against. A view for the type\n * checker only — see {@link agentTablesFor}; nothing SQLite-only (`run`/`all`/`get`, `returning` on\n * MySQL) may be called through it outside the helpers here.\n */\nexport function asBuilder(db: AgentDrizzleDb): AgentSqliteDb {\n return db as AgentSqliteDb;\n}\n\n/** A write statement that can be awaited and, outside MySQL, asked to `RETURNING` a column. */\ninterface Returnable {\n returning(fields: Record<string, unknown>): PromiseLike<unknown[]>;\n}\n\n/**\n * How many rows an UPDATE/DELETE/INSERT touched. `RETURNING` on SQLite and Postgres — the one answer\n * every driver of those gives alike — and the result header's `affectedRows` on MySQL, which has no\n * `RETURNING`.\n *\n * MySQL counts MATCHED rows for an update only while the connection has `FOUND_ROWS` (mysql2's\n * default); without it, an update that writes the value already there reports 0. A caller for whom\n * that difference matters re-reads the row rather than trusting a 0.\n */\nexport async function affectedRows(\n dialect: AgentDialect,\n statement: Returnable & PromiseLike<unknown>,\n column: unknown,\n): Promise<number> {\n if (dialect !== 'mysql') {\n return (await statement.returning({ affected: column })).length;\n }\n return mysqlAffectedRows(await statement);\n}\n\n/** `affectedRows` off a MySQL driver's result (mysql2's `[ResultSetHeader, fields]`, or a header). */\nexport function mysqlAffectedRows(result: unknown): number {\n const header = Array.isArray(result) ? result[0] : result;\n const counts = header as { affectedRows?: unknown; rowsAffected?: unknown } | null | undefined;\n // mysql2 says `affectedRows`; PlanetScale's serverless driver says `rowsAffected`.\n const count = counts?.affectedRows ?? counts?.rowsAffected;\n return typeof count === 'number' ? count : 0;\n}\n\n/** Run a raw statement, discarding its result. */\nexport async function runSql(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n statement: SQL,\n): Promise<void> {\n if (dialect === 'sqlite') {\n await (db as AgentSqliteDb).run(statement);\n return;\n }\n if (dialect === 'postgres') {\n await (db as AgentPgDb).execute(statement);\n return;\n }\n await (db as AgentMySqlDb).execute(statement);\n}\n\n/** Run a raw query and return its rows, whatever shape the driver hands them back in. */\nexport async function querySql<T>(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n statement: SQL,\n): Promise<T[]> {\n if (dialect === 'sqlite') {\n return (db as AgentSqliteDb).all<T>(statement);\n }\n const result: unknown =\n dialect === 'postgres'\n ? await (db as AgentPgDb).execute(statement)\n : await (db as AgentMySqlDb).execute(statement);\n if (dialect === 'mysql') {\n // mysql2: [rows, fields]\n return (Array.isArray(result) ? result[0] : []) as T[];\n }\n // node-postgres: { rows }; postgres.js and friends: the rows themselves\n return (Array.isArray(result) ? result : ((result as { rows?: T[] }).rows ?? [])) as T[];\n}\n\n/**\n * Did this write lose a race it can simply retry? A duplicate on a primary-key or unique index —\n * Postgres `23505`, MySQL `ER_DUP_ENTRY` (1062), SQLite's constraint codes — or, on MySQL, being the\n * deadlock victim (`ER_LOCK_DEADLOCK`, 1213): two `INSERT … SELECT MAX(seq) + 1` into one run take\n * gap locks on the same range, and InnoDB settles that by rolling one of them back rather than by a\n * duplicate key. Walks the `cause` chain, since Drizzle wraps the driver's error.\n */\nexport function isUniqueViolation(error: unknown): boolean {\n for (let current = error; current !== null && typeof current === 'object'; ) {\n const { code, errno } = current as { code?: unknown; errno?: unknown };\n if (\n code === '23505' ||\n code === 'ER_DUP_ENTRY' ||\n errno === 1062 ||\n code === 'ER_LOCK_DEADLOCK' ||\n errno === 1213 ||\n (typeof code === 'string' && code.startsWith('SQLITE_CONSTRAINT'))\n ) {\n return true;\n }\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\n/** An insert builder, as far as an upsert needs one. */\ninterface Upsertable {\n onConflictDoUpdate(config: {\n target: unknown;\n set: Record<string, unknown>;\n }): PromiseLike<unknown>;\n}\n\n/**\n * Insert, or update `set` on the row already holding `target`'s key: `ON CONFLICT … DO UPDATE` on\n * SQLite and Postgres, `ON DUPLICATE KEY UPDATE` on MySQL — which keys off EVERY unique index of the\n * table rather than a named target, so `target` must be the table's only key the row can collide on.\n */\nexport function upsert(\n dialect: AgentDialect,\n insert: Upsertable,\n target: unknown,\n set: Record<string, unknown>,\n): PromiseLike<unknown> {\n if (dialect === 'mysql') {\n return (\n insert as unknown as {\n onDuplicateKeyUpdate(config: { set: Record<string, unknown> }): PromiseLike<unknown>;\n }\n ).onDuplicateKeyUpdate({ set });\n }\n return insert.onConflictDoUpdate({ target, set });\n}\n","import { canonicalActionProposalJson } from '@dudousxd/nestjs-agent-core';\nimport type {\n ActionProposal,\n Actor,\n AgentUiComponent,\n MemoryOrigin,\n MessageAttachment,\n MessageFeedback,\n MessageRole,\n MessageUsage,\n PageContext,\n QueuePause,\n ToolCallRequest,\n ToolCallStatus,\n ToolConfirmation,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport type {\n AgentHostContext,\n CostSource,\n GenuiErrorCategory,\n GenuiToolMarker,\n GenuiValidity,\n RecordGenuiCallInput,\n RunStepTiming,\n} from '@dudousxd/nestjs-agent-core';\nimport type { UiCapabilities } from '@dudousxd/nestjs-agent-core/genui';\nimport {\n bigint,\n boolean,\n customType,\n datetime,\n double,\n index,\n int,\n json,\n longtext,\n mysqlTable,\n primaryKey,\n uniqueIndex,\n varchar,\n} from 'drizzle-orm/mysql-core';\nimport type { AgentRunStatus, RagIngestionStatus } from './schema.js';\n\n/**\n * The agent tables for MySQL (8.0+) — the same tables, columns and JS property names as the SQLite\n * {@link import('./schema.js').agentSchema}, in MySQL types: `json` for the JSON columns,\n * `datetime(3)` for the timestamps (UTC, read back as `Date` — MySQL's bare `datetime` is whole\n * seconds), `longtext` for anything a model or a stack trace can make long (`text` stops at 64 KB),\n * `varchar(255)` for keys and short labels (an index needs a bounded column), `bigint` for the\n * epoch-ms counters, `double` for prices and costs. `ensureAgentSchema` creates the tables\n * `utf8mb4_bin`, so ids and actor refs compare case-sensitively, as on Postgres and SQLite. Pass it to\n * `drizzle(pool, { schema: mysqlAgentSchema, mode: 'default' })`.\n */\nconst ts = (name: string) => datetime(name, { mode: 'date', fsp: 3 });\n/** A key or short label: bounded, so it can be indexed. */\nconst key = (name: string) => varchar(name, { length: 255 });\n\nexport const agentThread = mysqlTable(\n 'agent_thread',\n {\n id: key('id').primaryKey(),\n actorRef: key('actor_ref').notNull(),\n tenantRef: key('tenant_ref'),\n title: key('title').notNull(),\n transient: boolean('transient').notNull().default(false),\n activeStreamId: key('active_stream_id'),\n defaultAgent: key('default_agent'),\n model: key('model'),\n /** The persona a send on this thread runs under when it names none; `null` → the agent's default. */\n persona: key('persona'),\n queuePause: json('queue_pause').$type<QueuePause>(),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n deletedAt: ts('deleted_at'),\n },\n (table) => [\n index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt),\n // `ownerOfActiveStream` reads by run id on every stream attach and reconnect.\n index('agent_thread_active_stream_idx').on(table.activeStreamId),\n ],\n);\n\nexport const agentMessage = mysqlTable(\n 'agent_message',\n {\n id: key('id').primaryKey(),\n threadId: key('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n role: key('role').$type<MessageRole>().notNull(),\n actionProposalOutcome: longtext('action_proposal_outcome'),\n content: longtext('content').notNull(),\n toolCalls: json('tool_calls').$type<ToolCallRequest[]>(),\n toolResults: json('tool_results').$type<ToolResult[]>(),\n attachments: json('attachments').$type<MessageAttachment[]>(),\n followUps: json('follow_ups').$type<string[]>(),\n usage: json('usage').$type<MessageUsage>(),\n agentName: key('agent_name'),\n /** The persona the turn that wrote this message ran under; `null` → none. */\n persona: key('persona'),\n runId: key('run_id'),\n reasoning: longtext('reasoning'),\n reasoningMs: int('reasoning_ms'),\n ui: json('ui').$type<AgentUiComponent[]>(),\n feedback: json('feedback').$type<MessageFeedback>(),\n seq: int('seq'),\n createdAt: ts('created_at').notNull(),\n },\n (table) => [\n index('agent_message_thread_created_idx').on(table.threadId, table.createdAt),\n // Transcript reads order a thread's messages by `seq`.\n index('agent_message_thread_seq_idx').on(table.threadId, table.seq),\n ],\n);\n\nexport const agentToolCall = mysqlTable(\n 'agent_tool_call',\n {\n proposalId: key('proposal_id'),\n id: key('id').primaryKey(),\n messageId: key('message_id')\n .notNull()\n .references(() => agentMessage.id, { onDelete: 'cascade' }),\n toolName: key('tool_name').notNull(),\n toolType: key('tool_type').$type<ToolKind>().notNull(),\n input: json('input'),\n output: json('output'),\n status: key('status').$type<ToolCallStatus>().notNull(),\n executedByRef: key('executed_by_ref'),\n executionMs: int('execution_ms'),\n error: longtext('error'),\n createdAt: ts('created_at').notNull(),\n executedAt: ts('executed_at'),\n runId: key('run_id'),\n confirmation: json('confirmation').$type<ToolConfirmation>(),\n approver: key('approver'),\n expiresAt: ts('expires_at'),\n remember: boolean('remember'),\n decidedVia: key('decided_via'),\n },\n (table) => [\n index('agent_tool_call_message_idx').on(table.messageId),\n // The approvals inbox: `pending_approval`, oldest first.\n index('agent_tool_call_status_created_idx').on(table.status, table.createdAt),\n index('agent_tool_call_run_idx').on(table.runId),\n index('agent_tool_call_created_idx').on(table.createdAt),\n ],\n);\n\nexport const agentQueuedMessage = mysqlTable(\n 'agent_queued_message',\n {\n uiCapabilities: json('ui_capabilities').$type<UiCapabilities>(),\n hostContext: json('host_context').$type<AgentHostContext>(),\n id: key('id').primaryKey(),\n threadId: key('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actor: json('actor').$type<Actor>().notNull(),\n content: longtext('content').notNull(),\n attachments: json('attachments').$type<MessageAttachment[]>(),\n agentName: key('agent_name'),\n /** The persona the send resolved — what the message starts under. */\n persona: key('persona'),\n model: key('model'),\n pageContext: json('page_context').$type<PageContext>(),\n interrupt: boolean('interrupt').notNull().default(false),\n position: int('position').notNull(),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [index('agent_queued_message_thread_position_idx').on(table.threadId, table.position)],\n);\n\nexport const agentTokenUsage = mysqlTable(\n 'agent_token_usage',\n {\n id: key('id').primaryKey(),\n threadId: key('thread_id')\n // NULL for usage recorded outside any conversation (`AgentService.recordUsage`).\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: key('actor_ref').notNull(),\n messageId: key('message_id'),\n modelId: key('model_id').notNull(),\n purpose: key('purpose').$type<UsagePurpose>().notNull(),\n inputTokens: int('input_tokens').notNull(),\n outputTokens: int('output_tokens').notNull(),\n cacheWriteTokens: int('cache_write_tokens'),\n cacheReadTokens: int('cache_read_tokens'),\n costUsd: double('cost_usd'),\n /** Where `cost_usd` came from: `'provider'` (reported) or `'estimate'` (tokens × the price row); null on rows from before it existed (reported). */\n costSource: key('cost_source').$type<CostSource>(),\n /** The run the row belongs to. */\n runId: key('run_id'),\n /** What the spend was for: `agent:<name>` for an agent turn, the app's own otherwise; null → `agent`. */\n feature: key('feature'),\n provider: key('provider'),\n tenantRef: key('tenant_ref'),\n /** Units a row bills by when they are not tokens. */\n audioSeconds: double('audio_seconds'),\n characters: bigint('characters', { mode: 'number' }),\n requests: int('requests'),\n /** The caller's own JSON, never read by the library. */\n metadata: json('metadata').$type<Record<string, unknown>>(),\n /** `false` keeps the row out of the agent's quota windows (`recordUsage({ countsTowardsQuota: false })`). */\n countsTowardsQuota: boolean('counts_towards_quota').notNull().default(true),\n createdAt: ts('created_at').notNull(),\n },\n (table) => [\n index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt),\n index('agent_token_usage_created_idx').on(table.createdAt),\n index('agent_token_usage_thread_idx').on(table.threadId),\n index('agent_token_usage_feature_created_idx').on(table.feature, table.createdAt),\n ],\n);\n\n/**\n * Generative-UI telemetry (`AgentStore.recordGenuiCalls`): one row per UI tool call, keyed by the\n * tool call's id, so a replayed record replaces rather than duplicates. Metadata only — `payload`\n * (the call's arguments) is filled solely when the tool samples payloads. `created_at` is epoch-ms.\n */\nexport const agentGenuiCall = mysqlTable(\n 'agent_genui_call',\n {\n id: key('id').primaryKey(),\n runId: key('run_id').notNull(),\n threadId: key('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: key('actor_ref').notNull(),\n agentName: key('agent_name'),\n step: int('step').notNull(),\n toolName: key('tool_name').notNull(),\n channel: key('channel').notNull(),\n mode: key('mode').$type<GenuiToolMarker['mode']>().notNull(),\n modelId: key('model_id').notNull(),\n attempt: int('attempt').notNull(),\n outcome: key('outcome').$type<RecordGenuiCallInput['outcome']>().notNull(),\n validity: key('validity').$type<GenuiValidity>().notNull(),\n errorCategory: key('error_category').$type<GenuiErrorCategory>(),\n errorMessage: longtext('error_message'),\n inputTokens: int('input_tokens').notNull(),\n outputTokens: int('output_tokens').notNull(),\n costUsd: double('cost_usd'),\n costSource: varchar('cost_source', { length: 16 }).$type<CostSource>(),\n firstFrameMs: bigint('first_frame_ms', { mode: 'number' }),\n completeFrameMs: bigint('complete_frame_ms', { mode: 'number' }),\n payloadBytes: int('payload_bytes').notNull(),\n payload: longtext('payload'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n index('agent_genui_call_created_idx').on(table.createdAt),\n index('agent_genui_call_run_idx').on(table.runId),\n ],\n);\n\nexport const agentModelPricing = mysqlTable('agent_model_pricing', {\n id: key('id').primaryKey(),\n modelId: key('model_id').notNull(),\n inputPricePer1m: double('input_price_per_1m').notNull(),\n outputPricePer1m: double('output_price_per_1m').notNull(),\n cacheWritePricePer1m: double('cache_write_price_per_1m'),\n cacheReadPricePer1m: double('cache_read_price_per_1m'),\n effectiveFrom: ts('effective_from').notNull(),\n isCurrent: boolean('is_current').notNull(),\n});\n\nexport const agentRun = mysqlTable(\n 'agent_run',\n {\n id: key('id').primaryKey(),\n threadId: key('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: key('actor_ref').notNull(),\n agentName: key('agent_name'),\n status: key('status').$type<AgentRunStatus>().notNull(),\n durationMs: int('duration_ms'),\n /** Turn start to the first `text` frame; null for a run that streamed none or did not complete. */\n ttftMs: int('ttft_ms'),\n /** The run's known spend (the sum of its model calls with a known cost); null when none had one. */\n costUsd: double('cost_usd'),\n /** The model the run's last model call resolved to. */\n modelId: key('model_id'),\n errorCode: key('error_code'),\n errorMessage: longtext('error_message'),\n retries: int('retries').notNull().default(0),\n startedAt: ts('started_at').notNull(),\n settledAt: ts('settled_at'),\n promptHash: key('prompt_hash'),\n parentRunId: key('parent_run_id'),\n /** Enqueue → body start (ms); null when not read. */\n queueMs: int('queue_ms'),\n /** Where the completed run's time went: model and tool totals, counts, and the per-step list. */\n modelMs: int('model_ms'),\n toolsMs: int('tools_ms'),\n modelCalls: int('model_calls'),\n toolCalls: int('tool_calls'),\n timings: json('timings').$type<RunStepTiming[]>(),\n },\n (table) => [index('agent_run_started_idx').on(table.startedAt)],\n);\n\nexport const agentMemory = mysqlTable(\n 'agent_memory',\n {\n id: key('id').primaryKey(),\n scope: key('scope').notNull(),\n key: key('key').notNull(),\n text: longtext('text').notNull(),\n originAuthor: key('origin_author').$type<MemoryOrigin['author']>().notNull(),\n originThreadId: key('origin_thread_id'),\n originRunId: key('origin_run_id'),\n originActorRef: key('origin_actor_ref'),\n pinned: boolean('pinned').notNull().default(false),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [uniqueIndex('agent_memory_scope_key_uq').on(table.scope, table.key)],\n);\n\nexport const ragIngestionLog = mysqlTable(\n 'rag_ingestion_log',\n {\n documentId: key('document_id').primaryKey(),\n status: key('status').$type<RagIngestionStatus>().notNull(),\n collection: key('collection'),\n ownerType: key('owner_type'),\n ownerId: key('owner_id'),\n source: longtext('source'),\n mimeType: key('mime_type'),\n size: bigint('size', { mode: 'number' }),\n chunks: int('chunks'),\n reason: key('reason'),\n error: longtext('error'),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [index('rag_ingestion_log_collection_idx').on(table.collection, table.updatedAt)],\n);\n\n/**\n * Text channels' short-lived state (`@dudousxd/nestjs-agent-channels`), one row per key: the provider\n * message ids already answered, a question waiting for the person's answer, an outcome already\n * relayed. The primary key is the lock a claim takes; `expires_at` is epoch-ms, and past it the row\n * is free again and dead weight for `DrizzleChannelStore.purgeExpired`. Keys longer than 255\n * characters are stored by their SHA-256.\n */\nexport const agentChannelState = mysqlTable(\n 'agent_channel_state',\n {\n key: key('key').primaryKey(),\n value: longtext('value'),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [index('agent_channel_state_expires_idx').on(table.expiresAt)],\n);\n\nexport const agentConfirmToken = mysqlTable(\n 'agent_confirm_token',\n {\n hash: key('hash').primaryKey(),\n actorRef: key('actor_ref').notNull(),\n tool: key('tool').notNull(),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [index('agent_confirm_token_expires_idx').on(table.expiresAt)],\n);\n\nexport const agentStreamFrame = mysqlTable(\n 'agent_stream_frame',\n {\n runId: key('run_id').notNull(),\n seq: int('seq').notNull(),\n frame: longtext('frame'),\n error: longtext('error'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.runId, table.seq] })],\n);\n\n/** JSON text preserves valid JSON strings that a native JSON column cannot represent. */\nconst proposalJson = customType<{ data: ActionProposal; driverData: string }>({\n dataType: () => 'longtext',\n toDriver: (value) => canonicalActionProposalJson(value),\n fromDriver: (value) => JSON.parse(value) as ActionProposal,\n});\n\n/** Independent action proposals; decision and execution work commit in one fenced row. */\nexport const agentActionProposal = mysqlTable(\n 'agent_action_proposal',\n {\n id: key('id').primaryKey(),\n scopeKey: key('scope_key').notNull(),\n decision: key('decision').$type<ActionProposal['decision']>().notNull(),\n logicalSort: varchar('logical_sort', { length: 1020 }).notNull(),\n createFingerprint: longtext('create_fingerprint').notNull(),\n proposal: proposalJson('proposal').notNull(),\n version: bigint('version', { mode: 'number' }).notNull().default(0),\n executionStatus:\n key('execution_status').$type<NonNullable<ActionProposal['execution']>['status']>(),\n leaseExpiresAt: bigint('lease_expires_at', { mode: 'number' }),\n deliveryStatus: key('delivery_status'),\n deliveryLeaseExpiresAt: bigint('delivery_lease_expires_at', { mode: 'number' }),\n replacementGroupKey: key('replacement_group_key'),\n outcomeIdKey: key('outcome_id_key'),\n proposalExpiresAt: bigint('proposal_expires_at', { mode: 'number' }),\n discoveryIndexVersion: bigint('discovery_index_version', { mode: 'number' })\n .notNull()\n .default(0),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n index('agent_action_proposal_execution_idx').on(\n table.discoveryIndexVersion,\n table.executionStatus,\n table.leaseExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_expiry_idx').on(\n table.discoveryIndexVersion,\n table.decision,\n table.proposalExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_replacement_idx').on(\n table.scopeKey,\n table.replacementGroupKey,\n table.decision,\n ),\n index('agent_action_proposal_delivery_idx').on(\n table.deliveryStatus,\n table.deliveryLeaseExpiresAt,\n table.createdAt,\n ),\n uniqueIndex('agent_action_proposal_outcome_idx').on(table.outcomeIdKey),\n index('agent_action_proposal_scope_idx').on(table.scopeKey, table.createdAt, table.id),\n ],\n);\n\n/**\n * Personal Agent Protocol (Poppy) conversations (`DrizzlePoppyStore`): who it is with, its status,\n * the User's context and the identity its turns run as (JSON text), and the reader lease\n * (`reader_holder` until `reader_until`, epoch-ms) that lets one replica at a time write a reply.\n * `pruned_seq`: events at or below it were pruned.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConversation = mysqlTable('agent_poppy_conversation', {\n id: key('id').primaryKey(),\n clientId: varchar('client_id', { length: 2048 }).notNull(),\n userId: key('user_id').notNull(),\n accountRef: key('account_ref'),\n agentName: key('agent_name').notNull(),\n threadId: key('thread_id'),\n parentId: key('parent_id'),\n openDirectId: key('open_direct_id'),\n status: key('status').notNull(),\n responder: key('responder').notNull(),\n context: longtext('context'),\n activeRunId: key('active_run_id'),\n turnSeq: bigint('turn_seq', { mode: 'number' }).notNull(),\n grantInfo: longtext('grant_info'),\n readerHolder: key('reader_holder'),\n readerUntil: bigint('reader_until', { mode: 'number' }),\n prunedSeq: bigint('pruned_seq', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),\n});\n\n/**\n * A Poppy conversation's events, append-only, numbered per conversation. The primary key is the\n * position, so two appends racing for one cannot both win; `event_key` (unique per conversation)\n * is what keeps a re-read turn from writing its reply twice. `event` is the event as JSON text.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyEvent = mysqlTable(\n 'agent_poppy_event',\n {\n conversationId: key('conversation_id').notNull(),\n seq: bigint('seq', { mode: 'number' }).notNull(),\n id: key('id').notNull(),\n type: key('type').notNull(),\n event: longtext('event').notNull(),\n eventKey: key('event_key'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.conversationId, table.seq] }),\n uniqueIndex('agent_poppy_event_key_idx').on(table.conversationId, table.eventKey),\n index('agent_poppy_event_id_idx').on(table.conversationId, table.id),\n ],\n);\n\n/**\n * Accepted Poppy messages, one row per (owner, message id) — the primary key is the idempotency lock\n * that makes two deliveries of one message one (§7.3); `response` is what the first got, as JSON.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyMessage = mysqlTable(\n 'agent_poppy_message',\n {\n owner: key('owner').notNull(),\n messageId: key('message_id').notNull(),\n fingerprint: key('fingerprint').notNull(),\n conversationId: key('conversation_id').notNull(),\n response: longtext('response').notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.messageId] })],\n);\n\n/**\n * This app's Poppy connections (`DrizzlePoppyConnectionStore`): one per (owner, Company issuer),\n * holding the client state SEALED by the caller — never a token in the clear.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnection = mysqlTable(\n 'agent_poppy_connection',\n {\n owner: key('owner').notNull(),\n issuer: varchar('issuer', { length: 512 }).notNull(),\n domain: key('domain').notNull(),\n organization: key('organization').notNull(),\n scope: longtext('scope').notNull(),\n status: key('status').notNull(),\n state: longtext('state').notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.issuer] })],\n);\n\n/**\n * Poppy sign-ins in flight, started by the `connect` tool and completed on the connect page. `actor`\n * is JSON text; `flow` the sealed per-method state.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnect = mysqlTable('agent_poppy_connect', {\n id: key('id').primaryKey(),\n owner: key('owner').notNull(),\n domain: key('domain').notNull(),\n issuer: varchar('issuer', { length: 512 }).notNull(),\n organization: key('organization').notNull(),\n scope: longtext('scope').notNull(),\n actor: longtext('actor'),\n threadId: key('thread_id'),\n runId: key('run_id'),\n toolCallId: key('tool_call_id'),\n flow: longtext('flow'),\n status: key('status').notNull(),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n});\n\n/** Every agent table, for `drizzle(pool, { schema: mysqlAgentSchema, mode: 'default' })` on MySQL. */\nexport const mysqlAgentSchema = {\n agentActionProposal,\n agentThread,\n agentMessage,\n agentQueuedMessage,\n agentToolCall,\n agentTokenUsage,\n agentGenuiCall,\n agentModelPricing,\n agentRun,\n agentMemory,\n ragIngestionLog,\n agentConfirmToken,\n agentChannelState,\n agentStreamFrame,\n agentPoppyConversation,\n agentPoppyEvent,\n agentPoppyMessage,\n agentPoppyConnection,\n agentPoppyConnect,\n};\n","import { canonicalActionProposalJson } from '@dudousxd/nestjs-agent-core';\nimport type {\n ActionProposal,\n Actor,\n AgentUiComponent,\n MemoryOrigin,\n MessageAttachment,\n MessageFeedback,\n MessageRole,\n MessageUsage,\n PageContext,\n QueuePause,\n ToolCallRequest,\n ToolCallStatus,\n ToolConfirmation,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport type {\n AgentHostContext,\n CostSource,\n GenuiErrorCategory,\n GenuiToolMarker,\n GenuiValidity,\n RecordGenuiCallInput,\n RunStepTiming,\n} from '@dudousxd/nestjs-agent-core';\nimport type { UiCapabilities } from '@dudousxd/nestjs-agent-core/genui';\nimport {\n bigint,\n boolean,\n customType,\n doublePrecision,\n index,\n integer,\n jsonb,\n pgTable,\n primaryKey,\n text,\n timestamp,\n uniqueIndex,\n varchar,\n} from 'drizzle-orm/pg-core';\nimport type { AgentRunStatus, RagIngestionStatus } from './schema.js';\n\n/**\n * The agent tables for Postgres — the same tables, columns and JS property names as the SQLite\n * {@link import('./schema.js').agentSchema}, in Postgres types: `jsonb` for the JSON columns,\n * `timestamptz(3)` for the timestamps (read back as `Date`), `bigint` for the epoch-ms counters,\n * `double precision` for prices and costs. Pass it to `drizzle(pool, { schema: pgAgentSchema })`;\n * every store in this package finds these tables from the handle, whichever schema it was built with.\n */\nconst ts = (name: string) => timestamp(name, { withTimezone: true, precision: 3, mode: 'date' });\n\nexport const agentThread = pgTable(\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: boolean('transient').notNull().default(false),\n activeStreamId: text('active_stream_id'),\n defaultAgent: text('default_agent'),\n model: text('model'),\n /** The persona a send on this thread runs under when it names none; `null` → the agent's default. */\n persona: text('persona'),\n queuePause: jsonb('queue_pause').$type<QueuePause>(),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n deletedAt: ts('deleted_at'),\n },\n (table) => [\n index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt),\n // `ownerOfActiveStream` reads by run id on every stream attach and reconnect.\n index('agent_thread_active_stream_idx').on(table.activeStreamId),\n ],\n);\n\nexport const agentMessage = pgTable(\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 actionProposalOutcome: text('action_proposal_outcome'),\n content: text('content').notNull(),\n toolCalls: jsonb('tool_calls').$type<ToolCallRequest[]>(),\n toolResults: jsonb('tool_results').$type<ToolResult[]>(),\n attachments: jsonb('attachments').$type<MessageAttachment[]>(),\n followUps: jsonb('follow_ups').$type<string[]>(),\n usage: jsonb('usage').$type<MessageUsage>(),\n agentName: text('agent_name'),\n /** The persona the turn that wrote this message ran under; `null` → none. */\n persona: text('persona'),\n runId: text('run_id'),\n reasoning: text('reasoning'),\n reasoningMs: integer('reasoning_ms'),\n ui: jsonb('ui').$type<AgentUiComponent[]>(),\n feedback: jsonb('feedback').$type<MessageFeedback>(),\n seq: integer('seq'),\n createdAt: ts('created_at').notNull(),\n },\n (table) => [\n index('agent_message_thread_created_idx').on(table.threadId, table.createdAt),\n // Transcript reads order a thread's messages by `seq`.\n index('agent_message_thread_seq_idx').on(table.threadId, table.seq),\n ],\n);\n\nexport const agentToolCall = pgTable(\n 'agent_tool_call',\n {\n proposalId: text('proposal_id'),\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: jsonb('input'),\n output: jsonb('output'),\n status: text('status').$type<ToolCallStatus>().notNull(),\n executedByRef: text('executed_by_ref'),\n executionMs: integer('execution_ms'),\n error: text('error'),\n createdAt: ts('created_at').notNull(),\n executedAt: ts('executed_at'),\n runId: text('run_id'),\n confirmation: jsonb('confirmation').$type<ToolConfirmation>(),\n approver: text('approver'),\n expiresAt: ts('expires_at'),\n remember: boolean('remember'),\n decidedVia: text('decided_via'),\n },\n (table) => [\n index('agent_tool_call_message_idx').on(table.messageId),\n // The approvals inbox: `pending_approval`, oldest first.\n index('agent_tool_call_status_created_idx').on(table.status, table.createdAt),\n index('agent_tool_call_run_idx').on(table.runId),\n index('agent_tool_call_created_idx').on(table.createdAt),\n ],\n);\n\nexport const agentQueuedMessage = pgTable(\n 'agent_queued_message',\n {\n uiCapabilities: jsonb('ui_capabilities').$type<UiCapabilities>(),\n hostContext: jsonb('host_context').$type<AgentHostContext>(),\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actor: jsonb('actor').$type<Actor>().notNull(),\n content: text('content').notNull(),\n attachments: jsonb('attachments').$type<MessageAttachment[]>(),\n agentName: text('agent_name'),\n /** The persona the send resolved — what the message starts under. */\n persona: text('persona'),\n model: text('model'),\n pageContext: jsonb('page_context').$type<PageContext>(),\n interrupt: boolean('interrupt').notNull().default(false),\n position: integer('position').notNull(),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [index('agent_queued_message_thread_position_idx').on(table.threadId, table.position)],\n);\n\nexport const agentTokenUsage = pgTable(\n 'agent_token_usage',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n // NULL for usage recorded outside any conversation (`AgentService.recordUsage`).\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 cacheWriteTokens: integer('cache_write_tokens'),\n cacheReadTokens: integer('cache_read_tokens'),\n costUsd: doublePrecision('cost_usd'),\n /** Where `cost_usd` came from: `'provider'` (reported) or `'estimate'` (tokens × the price row); null on rows from before it existed (reported). */\n costSource: text('cost_source').$type<CostSource>(),\n /** The run the row belongs to. */\n runId: text('run_id'),\n /** What the spend was for: `agent:<name>` for an agent turn, the app's own otherwise; null → `agent`. */\n feature: text('feature'),\n provider: text('provider'),\n tenantRef: text('tenant_ref'),\n /** Units a row bills by when they are not tokens. */\n audioSeconds: doublePrecision('audio_seconds'),\n characters: bigint('characters', { mode: 'number' }),\n requests: integer('requests'),\n /** The caller's own JSON, never read by the library. */\n metadata: jsonb('metadata').$type<Record<string, unknown>>(),\n /** `false` keeps the row out of the agent's quota windows (`recordUsage({ countsTowardsQuota: false })`). */\n countsTowardsQuota: boolean('counts_towards_quota').notNull().default(true),\n createdAt: ts('created_at').notNull(),\n },\n (table) => [\n index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt),\n index('agent_token_usage_created_idx').on(table.createdAt),\n index('agent_token_usage_thread_idx').on(table.threadId),\n index('agent_token_usage_feature_created_idx').on(table.feature, table.createdAt),\n ],\n);\n\n/**\n * Generative-UI telemetry (`AgentStore.recordGenuiCalls`): one row per UI tool call, keyed by the\n * tool call's id, so a replayed record replaces rather than duplicates. Metadata only — `payload`\n * (the call's arguments) is filled solely when the tool samples payloads. `created_at` is epoch-ms.\n */\nexport const agentGenuiCall = pgTable(\n 'agent_genui_call',\n {\n id: text('id').primaryKey(),\n runId: text('run_id').notNull(),\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 step: integer('step').notNull(),\n toolName: text('tool_name').notNull(),\n channel: text('channel').notNull(),\n mode: text('mode').$type<GenuiToolMarker['mode']>().notNull(),\n modelId: text('model_id').notNull(),\n attempt: integer('attempt').notNull(),\n outcome: text('outcome').$type<RecordGenuiCallInput['outcome']>().notNull(),\n validity: text('validity').$type<GenuiValidity>().notNull(),\n errorCategory: text('error_category').$type<GenuiErrorCategory>(),\n errorMessage: text('error_message'),\n inputTokens: integer('input_tokens').notNull(),\n outputTokens: integer('output_tokens').notNull(),\n costUsd: doublePrecision('cost_usd'),\n costSource: varchar('cost_source', { length: 16 }).$type<CostSource>(),\n firstFrameMs: bigint('first_frame_ms', { mode: 'number' }),\n completeFrameMs: bigint('complete_frame_ms', { mode: 'number' }),\n payloadBytes: integer('payload_bytes').notNull(),\n payload: text('payload'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n index('agent_genui_call_created_idx').on(table.createdAt),\n index('agent_genui_call_run_idx').on(table.runId),\n ],\n);\n\nexport const agentModelPricing = pgTable('agent_model_pricing', {\n id: text('id').primaryKey(),\n modelId: text('model_id').notNull(),\n inputPricePer1m: doublePrecision('input_price_per_1m').notNull(),\n outputPricePer1m: doublePrecision('output_price_per_1m').notNull(),\n cacheWritePricePer1m: doublePrecision('cache_write_price_per_1m'),\n cacheReadPricePer1m: doublePrecision('cache_read_price_per_1m'),\n effectiveFrom: ts('effective_from').notNull(),\n isCurrent: boolean('is_current').notNull(),\n});\n\nexport const agentRun = pgTable(\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 /** Turn start to the first `text` frame; null for a run that streamed none or did not complete. */\n ttftMs: integer('ttft_ms'),\n /** The run's known spend (the sum of its model calls with a known cost); null when none had one. */\n costUsd: doublePrecision('cost_usd'),\n /** The model the run's last model call resolved to. */\n modelId: text('model_id'),\n errorCode: text('error_code'),\n errorMessage: text('error_message'),\n retries: integer('retries').notNull().default(0),\n startedAt: ts('started_at').notNull(),\n settledAt: ts('settled_at'),\n promptHash: text('prompt_hash'),\n parentRunId: text('parent_run_id'),\n /** Enqueue → body start (ms); null when not read. */\n queueMs: integer('queue_ms'),\n /** Where the completed run's time went: model and tool totals, counts, and the per-step list. */\n modelMs: integer('model_ms'),\n toolsMs: integer('tools_ms'),\n modelCalls: integer('model_calls'),\n toolCalls: integer('tool_calls'),\n timings: jsonb('timings').$type<RunStepTiming[]>(),\n },\n (table) => [index('agent_run_started_idx').on(table.startedAt)],\n);\n\nexport const agentMemory = pgTable(\n 'agent_memory',\n {\n id: text('id').primaryKey(),\n scope: text('scope').notNull(),\n key: text('key').notNull(),\n text: text('text').notNull(),\n originAuthor: text('origin_author').$type<MemoryOrigin['author']>().notNull(),\n originThreadId: text('origin_thread_id'),\n originRunId: text('origin_run_id'),\n originActorRef: text('origin_actor_ref'),\n pinned: boolean('pinned').notNull().default(false),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [uniqueIndex('agent_memory_scope_key_uq').on(table.scope, table.key)],\n);\n\nexport const ragIngestionLog = pgTable(\n 'rag_ingestion_log',\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 source: text('source'),\n mimeType: text('mime_type'),\n size: bigint('size', { mode: 'number' }),\n chunks: integer('chunks'),\n reason: text('reason'),\n error: text('error'),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [index('rag_ingestion_log_collection_idx').on(table.collection, table.updatedAt)],\n);\n\n/**\n * Text channels' short-lived state (`@dudousxd/nestjs-agent-channels`), one row per key: the provider\n * message ids already answered, a question waiting for the person's answer, an outcome already\n * relayed. The primary key is the lock a claim takes; `expires_at` is epoch-ms, and past it the row\n * is free again and dead weight for `DrizzleChannelStore.purgeExpired`. Keys longer than 255\n * characters are stored by their SHA-256.\n */\nexport const agentChannelState = pgTable(\n 'agent_channel_state',\n {\n key: text('key').primaryKey(),\n value: text('value'),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [index('agent_channel_state_expires_idx').on(table.expiresAt)],\n);\n\nexport const agentConfirmToken = pgTable(\n 'agent_confirm_token',\n {\n hash: text('hash').primaryKey(),\n actorRef: text('actor_ref').notNull(),\n tool: text('tool').notNull(),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [index('agent_confirm_token_expires_idx').on(table.expiresAt)],\n);\n\nexport const agentStreamFrame = pgTable(\n 'agent_stream_frame',\n {\n runId: text('run_id').notNull(),\n seq: integer('seq').notNull(),\n frame: text('frame'),\n error: text('error'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.runId, table.seq] })],\n);\n\n/** JSON text preserves valid JSON strings that a native JSON column cannot represent. */\nconst proposalJson = customType<{ data: ActionProposal; driverData: string }>({\n dataType: () => 'text',\n toDriver: (value) => canonicalActionProposalJson(value),\n fromDriver: (value) => JSON.parse(value) as ActionProposal,\n});\n\n/** Independent action proposals; decision and execution work commit in one fenced row. */\nexport const agentActionProposal = pgTable(\n 'agent_action_proposal',\n {\n id: text('id').primaryKey(),\n scopeKey: text('scope_key').notNull(),\n decision: text('decision').$type<ActionProposal['decision']>().notNull(),\n logicalSort: text('logical_sort').notNull(),\n createFingerprint: text('create_fingerprint').notNull(),\n proposal: proposalJson('proposal').notNull(),\n version: bigint('version', { mode: 'number' }).notNull().default(0),\n executionStatus:\n text('execution_status').$type<NonNullable<ActionProposal['execution']>['status']>(),\n leaseExpiresAt: bigint('lease_expires_at', { mode: 'number' }),\n deliveryStatus: text('delivery_status'),\n deliveryLeaseExpiresAt: bigint('delivery_lease_expires_at', { mode: 'number' }),\n replacementGroupKey: text('replacement_group_key'),\n outcomeIdKey: text('outcome_id_key'),\n proposalExpiresAt: bigint('proposal_expires_at', { mode: 'number' }),\n discoveryIndexVersion: bigint('discovery_index_version', { mode: 'number' })\n .notNull()\n .default(0),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n index('agent_action_proposal_execution_idx').on(\n table.discoveryIndexVersion,\n table.executionStatus,\n table.leaseExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_expiry_idx').on(\n table.discoveryIndexVersion,\n table.decision,\n table.proposalExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_replacement_idx').on(\n table.scopeKey,\n table.replacementGroupKey,\n table.decision,\n ),\n index('agent_action_proposal_delivery_idx').on(\n table.deliveryStatus,\n table.deliveryLeaseExpiresAt,\n table.createdAt,\n ),\n uniqueIndex('agent_action_proposal_outcome_idx').on(table.outcomeIdKey),\n index('agent_action_proposal_scope_idx').on(table.scopeKey, table.createdAt, table.id),\n ],\n);\n\n/**\n * Personal Agent Protocol (Poppy) conversations (`DrizzlePoppyStore`): who it is with, its status,\n * the User's context and the identity its turns run as (JSON text), and the reader lease\n * (`reader_holder` until `reader_until`, epoch-ms) that lets one replica at a time write a reply.\n * `pruned_seq`: events at or below it were pruned.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConversation = pgTable('agent_poppy_conversation', {\n id: text('id').primaryKey(),\n clientId: text('client_id').notNull(),\n userId: text('user_id').notNull(),\n accountRef: text('account_ref'),\n agentName: text('agent_name').notNull(),\n threadId: text('thread_id'),\n parentId: text('parent_id'),\n openDirectId: text('open_direct_id'),\n status: text('status').notNull(),\n responder: text('responder').notNull(),\n context: text('context'),\n activeRunId: text('active_run_id'),\n turnSeq: bigint('turn_seq', { mode: 'number' }).notNull(),\n grantInfo: text('grant_info'),\n readerHolder: text('reader_holder'),\n readerUntil: bigint('reader_until', { mode: 'number' }),\n prunedSeq: bigint('pruned_seq', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),\n});\n\n/**\n * A Poppy conversation's events, append-only, numbered per conversation. The primary key is the\n * position, so two appends racing for one cannot both win; `event_key` (unique per conversation)\n * is what keeps a re-read turn from writing its reply twice. `event` is the event as JSON text.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyEvent = pgTable(\n 'agent_poppy_event',\n {\n conversationId: text('conversation_id').notNull(),\n seq: bigint('seq', { mode: 'number' }).notNull(),\n id: text('id').notNull(),\n type: text('type').notNull(),\n event: text('event').notNull(),\n eventKey: text('event_key'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.conversationId, table.seq] }),\n uniqueIndex('agent_poppy_event_key_idx').on(table.conversationId, table.eventKey),\n index('agent_poppy_event_id_idx').on(table.conversationId, table.id),\n ],\n);\n\n/**\n * Accepted Poppy messages, one row per (owner, message id) — the primary key is the idempotency lock\n * that makes two deliveries of one message one (§7.3); `response` is what the first got, as JSON.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyMessage = pgTable(\n 'agent_poppy_message',\n {\n owner: text('owner').notNull(),\n messageId: text('message_id').notNull(),\n fingerprint: text('fingerprint').notNull(),\n conversationId: text('conversation_id').notNull(),\n response: text('response').notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.messageId] })],\n);\n\n/**\n * This app's Poppy connections (`DrizzlePoppyConnectionStore`): one per (owner, Company issuer),\n * holding the client state SEALED by the caller — never a token in the clear.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnection = pgTable(\n 'agent_poppy_connection',\n {\n owner: text('owner').notNull(),\n issuer: text('issuer').notNull(),\n domain: text('domain').notNull(),\n organization: text('organization').notNull(),\n scope: text('scope').notNull(),\n status: text('status').notNull(),\n state: text('state').notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.issuer] })],\n);\n\n/**\n * Poppy sign-ins in flight, started by the `connect` tool and completed on the connect page. `actor`\n * is JSON text; `flow` the sealed per-method state.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnect = pgTable('agent_poppy_connect', {\n id: text('id').primaryKey(),\n owner: text('owner').notNull(),\n domain: text('domain').notNull(),\n issuer: text('issuer').notNull(),\n organization: text('organization').notNull(),\n scope: text('scope').notNull(),\n actor: text('actor'),\n threadId: text('thread_id'),\n runId: text('run_id'),\n toolCallId: text('tool_call_id'),\n flow: text('flow'),\n status: text('status').notNull(),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n});\n\n/** Every agent table, for `drizzle(pool, { schema: pgAgentSchema })` on Postgres. */\nexport const pgAgentSchema = {\n agentActionProposal,\n agentThread,\n agentMessage,\n agentQueuedMessage,\n agentToolCall,\n agentTokenUsage,\n agentGenuiCall,\n agentModelPricing,\n agentRun,\n agentMemory,\n ragIngestionLog,\n agentConfirmToken,\n agentChannelState,\n agentStreamFrame,\n agentPoppyConversation,\n agentPoppyEvent,\n agentPoppyMessage,\n agentPoppyConnection,\n agentPoppyConnect,\n};\n","import {\n type ActionProposalDiscoveryIndexStore,\n type ActionProposalOutcomeStore,\n type ActionProposalStore,\n type ActionProposalStoreOptions,\n type ActionProposalSupersessionStore,\n type ActionProposalWorkerStore,\n type AgentStore,\n type AgentUiComponent,\n type AppendMessageInput,\n type ChatQueueStore,\n type CreateThreadInput,\n type EnqueueMessageInput,\n type ForkThreadOptions,\n type MessageFeedback,\n type QueuePause,\n type QueuedMessage,\n type QueuedMessagePatch,\n type RecordGenuiCallInput,\n type RecordRunEndInput,\n type RecordRunStartInput,\n type RecordToolCallInput,\n type RecordUsageInput,\n type StoredMessage,\n type ThreadDetail,\n type ThreadSettings,\n type ThreadSettingsReader,\n type ThreadSummary,\n type ThreadTurnPage,\n type ThreadTurnQuery,\n type ThreadTurnReader,\n type ToolCallApproval,\n type ToolCallApprovalState,\n type ToolCallOutcome,\n type ToolResult,\n type UpdateThreadInput,\n type UpdateToolCallInput,\n type UsageTotals,\n canonicalActionProposalJson,\n sumUsage,\n toolCallApprovalFromRow,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n type SQL,\n and,\n asc,\n desc,\n eq,\n gte,\n inArray,\n isNotNull,\n isNull,\n lte,\n max,\n min,\n or,\n sql,\n} from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n upsert,\n} from './dialect.js';\nimport { DrizzleActionProposalStore } from './drizzle-action-proposal-store.js';\nimport {\n type AgentMessageRow,\n type AgentQueuedMessageRow,\n type AgentRunRow,\n type AgentThreadRow,\n agentMessage,\n agentQueuedMessage,\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. */\nfunction turnMessageColumns(message: AgentTables['agentMessage']) {\n return {\n id: message.id,\n role: message.role,\n content: message.content,\n agentName: message.agentName,\n toolCalls: message.toolCalls,\n toolResults: message.toolResults,\n attachments: message.attachments,\n createdAt: message.createdAt,\n };\n}\n\ntype TurnMessageRow = { [K in keyof ReturnType<typeof turnMessageColumns>]: 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 database handle — SQLite, Postgres or\n * MySQL (the host app 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\n implements\n AgentStore,\n ThreadTurnReader,\n ThreadSettingsReader,\n ChatQueueStore,\n ActionProposalStore,\n ActionProposalWorkerStore,\n ActionProposalDiscoveryIndexStore,\n ActionProposalOutcomeStore\n{\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n private readonly proposals: DrizzleActionProposalStore;\n\n constructor(db: AgentDrizzleDb, options: ActionProposalStoreOptions = {}) {\n this.proposals = new DrizzleActionProposalStore(db, options);\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n createActionProposal(\n ...args: Parameters<ActionProposalStore['createActionProposal']>\n ): ReturnType<ActionProposalStore['createActionProposal']> {\n return this.proposals.createActionProposal(...args);\n }\n\n getActionProposal(\n ...args: Parameters<ActionProposalStore['getActionProposal']>\n ): ReturnType<ActionProposalStore['getActionProposal']> {\n return this.proposals.getActionProposal(...args);\n }\n\n listActionProposals(\n ...args: Parameters<ActionProposalStore['listActionProposals']>\n ): ReturnType<ActionProposalStore['listActionProposals']> {\n return this.proposals.listActionProposals(...args);\n }\n\n decideActionProposal(\n ...args: Parameters<ActionProposalStore['decideActionProposal']>\n ): ReturnType<ActionProposalStore['decideActionProposal']> {\n return this.proposals.decideActionProposal(...args);\n }\n\n claimActionProposal(\n ...args: Parameters<ActionProposalStore['claimActionProposal']>\n ): ReturnType<ActionProposalStore['claimActionProposal']> {\n return this.proposals.claimActionProposal(...args);\n }\n\n extendActionProposalLease(\n ...args: Parameters<ActionProposalStore['extendActionProposalLease']>\n ): ReturnType<ActionProposalStore['extendActionProposalLease']> {\n return this.proposals.extendActionProposalLease(...args);\n }\n\n claimNextActionProposal(\n ...args: Parameters<ActionProposalWorkerStore['claimNextActionProposal']>\n ): ReturnType<ActionProposalWorkerStore['claimNextActionProposal']> {\n return this.proposals.claimNextActionProposal(...args);\n }\n\n expireActionProposals(\n ...args: Parameters<ActionProposalWorkerStore['expireActionProposals']>\n ): ReturnType<ActionProposalWorkerStore['expireActionProposals']> {\n return this.proposals.expireActionProposals(...args);\n }\n\n backfillActionProposalDiscoveryIndex(command: { limit: number }): Promise<number> {\n return this.proposals.backfillActionProposalDiscoveryIndex(command);\n }\n\n settleActionProposal(\n ...args: Parameters<ActionProposalStore['settleActionProposal']>\n ): ReturnType<ActionProposalStore['settleActionProposal']> {\n return this.proposals.settleActionProposal(...args);\n }\n\n createReplacingActionProposal(\n ...args: Parameters<ActionProposalSupersessionStore['createReplacingActionProposal']>\n ) {\n return this.proposals.createReplacingActionProposal(...args);\n }\n supersedeActionProposal(\n ...args: Parameters<ActionProposalSupersessionStore['supersedeActionProposal']>\n ) {\n return this.proposals.supersedeActionProposal(...args);\n }\n\n get actionProposalAdmissionSupported(): boolean {\n return this.proposals.actionProposalAdmissionSupported;\n }\n getThreadActionProposalScope(threadId: string) {\n return this.proposals.getThreadActionProposalScope(threadId);\n }\n claimNextActionProposalOutcome(\n ...args: Parameters<ActionProposalOutcomeStore['claimNextActionProposalOutcome']>\n ) {\n return this.proposals.claimNextActionProposalOutcome(...args);\n }\n admitActionProposalOutcome(\n ...args: Parameters<ActionProposalOutcomeStore['admitActionProposalOutcome']>\n ) {\n return this.proposals.admitActionProposalOutcome(...args);\n }\n\n async createThread(input: CreateThreadInput): Promise<ThreadSummary> {\n const now = new Date();\n const thread: AgentThreadRow = {\n id: input.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 model: null,\n persona: input.persona ?? null,\n queuePause: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(this.t.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(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));\n if (thread === undefined) {\n return null;\n }\n const messages = await this.db\n .select()\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId))\n .orderBy(...this.messageOrder());\n const last = messages[messages.length - 1];\n const approvals = await this.approvalsFor(messages.map((message) => message.id));\n return {\n ...this.toSummary(thread, last?.content),\n messages: messages.map((message) => {\n const stored = this.toStoredMessage(message);\n const onMessage = approvals.get(message.id);\n return onMessage !== undefined ? { ...stored, approvals: onMessage } : stored;\n }),\n ...(thread.activeStreamId != null ? { activeRunId: 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: this.t.agentThread.title, defaultAgent: this.t.agentThread.defaultAgent })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, query.threadId), isNull(this.t.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: this.t.agentMessage.id })\n .from(this.t.agentMessage)\n .where(\n and(\n eq(this.t.agentMessage.threadId, query.threadId),\n eq(this.t.agentMessage.role, 'assistant'),\n ),\n )\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(turnMessageColumns(this.t.agentMessage))\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId))\n .orderBy(...this.messageOrderNewestFirst());\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(this.t.agentThread)\n .where(\n and(\n eq(this.t.agentThread.actorRef, actorRef),\n eq(this.t.agentThread.transient, false),\n isNull(this.t.agentThread.deletedAt),\n ),\n )\n .orderBy(desc(this.t.agentThread.updatedAt))\n .limit(limit);\n const previews = await this.lastMessageContents(threads.map((thread) => thread.id));\n return threads.map((thread) => this.toSummary(thread, previews.get(thread.id)));\n }\n\n /**\n * The content of each thread's newest message ({@link messageOrderNewestFirst}), in a fixed two\n * reads for any number of threads: each thread's highest `seq`, then the rows holding it. Only a\n * thread whose every message predates `seq` is read on its own, by `created_at`.\n */\n private async lastMessageContents(threadIds: readonly string[]): Promise<Map<string, string>> {\n const contents = new Map<string, string>();\n if (threadIds.length === 0) {\n return contents;\n }\n const message = this.t.agentMessage;\n const highest = await this.db\n .select({ threadId: message.threadId, seq: max(message.seq) })\n .from(message)\n .where(inArray(message.threadId, [...threadIds]))\n .groupBy(message.threadId);\n const numbered = highest.filter((row) => row.seq !== null);\n if (numbered.length > 0) {\n const rows = await this.db\n .select({ threadId: message.threadId, content: message.content })\n .from(message)\n .where(\n or(\n ...numbered.map((row) =>\n and(eq(message.threadId, row.threadId), eq(message.seq, Number(row.seq))),\n ),\n ),\n )\n .orderBy(...this.messageOrderNewestFirst());\n for (const row of rows) {\n if (!contents.has(row.threadId)) {\n contents.set(row.threadId, row.content);\n }\n }\n }\n for (const row of highest) {\n if (row.seq === null) {\n const [last] = await this.db\n .select({ content: message.content })\n .from(message)\n .where(eq(message.threadId, row.threadId))\n .orderBy(...this.messageOrderNewestFirst())\n .limit(1);\n if (last !== undefined) {\n contents.set(row.threadId, last.content);\n }\n }\n }\n return contents;\n }\n\n async softDeleteThread(threadId: string): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ deletedAt: new Date() })\n .where(eq(this.t.agentThread.id, threadId));\n }\n\n async forkThread(\n threadId: string,\n fromMessageId: string,\n options: ForkThreadOptions = {},\n ): Promise<ThreadSummary> {\n const [source] = await this.db\n .select()\n .from(this.t.agentThread)\n .where(eq(this.t.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(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId))\n .orderBy(...this.messageOrder());\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: options.actorRef ?? source.actorRef,\n tenantRef: options.tenantRef !== undefined ? options.tenantRef : source.tenantRef,\n title: source.title,\n transient: false,\n activeStreamId: null,\n defaultAgent: source.defaultAgent,\n model: source.model,\n persona: source.persona,\n // A fork is a new conversation: nothing is waiting on it, and nothing is paused.\n queuePause: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(this.t.agentThread).values(fork);\n if (kept.length > 0) {\n await this.db.insert(this.t.agentMessage).values(\n kept.map((message, index) => ({\n id: crypto.randomUUID(),\n // Numbered afresh in the order just read, so the copy reads back in the original's order.\n seq: index + 1,\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 persona: message.persona,\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 reasoning: message.reasoning,\n reasoningMs: message.reasoningMs,\n ui: message.ui,\n actionProposalOutcome: message.actionProposalOutcome,\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: this.t.agentThread.actorRef })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.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: this.t.agentThread.actorRef })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(eq(this.t.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({\n runId: this.t.agentToolCall.runId,\n activeStreamId: this.t.agentThread.activeStreamId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(eq(this.t.agentToolCall.id, toolCallId));\n return row?.runId ?? row?.activeStreamId ?? null;\n }\n\n /**\n * The approval record of every call on `messageIds` that a policy put to a person, grouped by\n * message. One query over the calls that carry an approver — a thread whose calls never asked\n * anyone reads nothing back.\n */\n private async approvalsFor(messageIds: string[]): Promise<Map<string, ToolCallApproval[]>> {\n const byMessage = new Map<string, ToolCallApproval[]>();\n if (messageIds.length === 0) {\n return byMessage;\n }\n const rows = await this.db\n .select({\n id: this.t.agentToolCall.id,\n messageId: this.t.agentToolCall.messageId,\n status: this.t.agentToolCall.status,\n approver: this.t.agentToolCall.approver,\n confirmation: this.t.agentToolCall.confirmation,\n expiresAt: this.t.agentToolCall.expiresAt,\n remember: this.t.agentToolCall.remember,\n executedByRef: this.t.agentToolCall.executedByRef,\n decidedVia: this.t.agentToolCall.decidedVia,\n error: this.t.agentToolCall.error,\n })\n .from(this.t.agentToolCall)\n .where(\n and(\n inArray(this.t.agentToolCall.messageId, messageIds),\n isNotNull(this.t.agentToolCall.approver),\n ),\n )\n .orderBy(asc(this.t.agentToolCall.createdAt), asc(this.t.agentToolCall.id));\n for (const row of rows) {\n const approval = toolCallApprovalFromRow({ ...row, toolCallId: row.id });\n if (approval === null) {\n continue;\n }\n const list = byMessage.get(row.messageId) ?? [];\n list.push(approval);\n byMessage.set(row.messageId, list);\n }\n return byMessage;\n }\n\n /** Tools whose approval someone asked to remember in this thread. */\n async rememberedApprovals(threadId: string): Promise<string[]> {\n const rows = await this.db\n .selectDistinct({ toolName: this.t.agentToolCall.toolName })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .where(\n and(eq(this.t.agentMessage.threadId, threadId), eq(this.t.agentToolCall.remember, true)),\n );\n const scope = await this.getThreadActionProposalScope(threadId);\n const proposalNames = scope\n ? await this.proposals.rememberedActionProposalApprovals(scope)\n : [];\n return [...new Set([...rows.map((row) => row.toolName), ...proposalNames])];\n }\n\n async toolCallInput(toolCallId: string): Promise<unknown> {\n const [row] = await this.db\n .select({ input: this.t.agentToolCall.input })\n .from(this.t.agentToolCall)\n .where(eq(this.t.agentToolCall.id, toolCallId));\n return row?.input ?? null;\n }\n\n async toolCallApproval(toolCallId: string): Promise<ToolCallApprovalState | null> {\n const [row] = await this.db\n .select({\n status: this.t.agentToolCall.status,\n approver: this.t.agentToolCall.approver,\n expiresAt: this.t.agentToolCall.expiresAt,\n })\n .from(this.t.agentToolCall)\n .where(eq(this.t.agentToolCall.id, toolCallId));\n if (row === undefined) {\n return null;\n }\n return {\n status: row.status,\n approver: row.approver,\n expiresAt: row.expiresAt?.toISOString() ?? null,\n };\n }\n\n async ownerOfActiveStream(runId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: this.t.agentThread.actorRef })\n .from(this.t.agentThread)\n .where(\n and(eq(this.t.agentThread.activeStreamId, runId), isNull(this.t.agentThread.deletedAt)),\n );\n return thread?.actorRef ?? null;\n }\n\n async setTitle(threadId: string, title: string): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ title, updatedAt: new Date() })\n .where(eq(this.t.agentThread.id, threadId));\n }\n\n async promoteThread(threadId: string): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ transient: false, updatedAt: new Date() })\n .where(and(eq(this.t.agentThread.id, threadId), eq(this.t.agentThread.transient, true)));\n }\n\n /** Who holds the thread's stream right now, deleted or not. */\n private async activeHolder(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ activeStreamId: this.t.agentThread.activeStreamId })\n .from(this.t.agentThread)\n .where(eq(this.t.agentThread.id, threadId));\n return thread?.activeStreamId ?? null;\n }\n\n /**\n * A thread's messages in the order they were appended: by `seq`, which append assigns. A row from\n * before `seq` existed has none and counts as 0 — first, since every such row is older than every\n * numbered one — and those order among themselves by `created_at`, then `id`, as they always did.\n * `coalesce` rather than `nulls first`, which MySQL cannot spell and Postgres defaults the other way.\n */\n private messageOrder(): SQL[] {\n const message = this.t.agentMessage;\n return [asc(sql`coalesce(${message.seq}, 0)`), asc(message.createdAt), asc(message.id)];\n }\n\n /** {@link messageOrder}, newest first. */\n private messageOrderNewestFirst(): SQL[] {\n const message = this.t.agentMessage;\n return [desc(sql`coalesce(${message.seq}, 0)`), desc(message.createdAt), desc(message.id)];\n }\n\n /**\n * The next `seq` in a thread: one past its highest. Two appends racing on ONE thread can draw the\n * same number — the turn loop never does that, and the tie then falls back to `created_at`, `id`.\n */\n private async nextMessageSeq(threadId: string): Promise<number> {\n const [row] = await this.db\n .select({ last: max(this.t.agentMessage.seq) })\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId));\n return Number(row?.last ?? 0) + 1;\n }\n\n /** The run streaming the thread, or `null` — a projection of the one column. */\n async activeRunForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ activeStreamId: this.t.agentThread.activeStreamId })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));\n return thread?.activeStreamId ?? null;\n }\n\n /**\n * One conditional UPDATE, so of two racing claims exactly one changes the row: set the holder to\n * `runId` only when there is none, it is already `runId`, or it is `replacing`.\n */\n async claimActiveStream(\n threadId: string,\n runId: string,\n options: { replacing?: string } = {},\n ): Promise<boolean> {\n const holders = [\n isNull(this.t.agentThread.activeStreamId),\n eq(this.t.agentThread.activeStreamId, runId),\n ...(options.replacing !== undefined\n ? [eq(this.t.agentThread.activeStreamId, options.replacing)]\n : []),\n ];\n const claimed = await affectedRows(\n this.dialect,\n this.db\n .update(this.t.agentThread)\n .set({ activeStreamId: runId })\n .where(and(eq(this.t.agentThread.id, threadId), or(...holders))),\n this.t.agentThread.id,\n );\n if (claimed > 0) {\n return true;\n }\n // Zero can still be a win: a MySQL connection without FOUND_ROWS reports CHANGED rows, and\n // re-claiming a thread this run already holds changes nothing. The row says who holds it now.\n return (await this.activeHolder(threadId)) === runId;\n }\n\n async releaseActiveStream(threadId: string, runId: string): Promise<boolean> {\n const released = await affectedRows(\n this.dialect,\n this.db\n .update(this.t.agentThread)\n .set({ activeStreamId: null })\n .where(\n and(eq(this.t.agentThread.id, threadId), eq(this.t.agentThread.activeStreamId, runId)),\n ),\n this.t.agentThread.id,\n );\n return released > 0;\n }\n\n async enqueueMessage(input: EnqueueMessageInput): Promise<QueuedMessage> {\n const now = new Date();\n const [edge] = await this.db\n .select({\n first: min(this.t.agentQueuedMessage.position),\n last: max(this.t.agentQueuedMessage.position),\n })\n .from(this.t.agentQueuedMessage)\n .where(eq(this.t.agentQueuedMessage.threadId, input.threadId));\n const position = input.at === 'head' ? (edge?.first ?? 1) - 1 : (edge?.last ?? -1) + 1;\n const row: AgentQueuedMessageRow = {\n id: crypto.randomUUID(),\n threadId: input.threadId,\n actor: input.actor,\n content: input.content,\n uiCapabilities: input.uiCapabilities ?? null,\n hostContext: input.hostContext ?? null,\n attachments:\n input.attachments !== undefined && input.attachments.length > 0 ? input.attachments : null,\n agentName: input.agentName ?? null,\n persona: input.persona ?? null,\n model: input.model ?? null,\n pageContext: input.pageContext ?? null,\n interrupt: input.interrupt === true,\n position,\n createdAt: now,\n updatedAt: now,\n };\n await this.db.insert(this.t.agentQueuedMessage).values(row);\n return toQueuedMessage(row);\n }\n\n async listQueue(threadId: string): Promise<QueuedMessage[]> {\n const rows = await this.db\n .select()\n .from(this.t.agentQueuedMessage)\n .where(eq(this.t.agentQueuedMessage.threadId, threadId))\n .orderBy(asc(this.t.agentQueuedMessage.position), asc(this.t.agentQueuedMessage.createdAt));\n return rows.map(toQueuedMessage);\n }\n\n async getQueuedMessage(id: string): Promise<QueuedMessage | null> {\n const [row] = await this.db\n .select()\n .from(this.t.agentQueuedMessage)\n .where(eq(this.t.agentQueuedMessage.id, id));\n return row === undefined ? null : toQueuedMessage(row);\n }\n\n async updateQueuedMessage(id: string, patch: QueuedMessagePatch): Promise<QueuedMessage | null> {\n const updates: Partial<AgentQueuedMessageRow> = { updatedAt: new Date() };\n if (patch.content !== undefined) {\n updates.content = patch.content;\n }\n if (patch.attachments !== undefined) {\n updates.attachments =\n patch.attachments === null || patch.attachments.length === 0 ? null : patch.attachments;\n }\n if (patch.interrupt !== undefined) {\n updates.interrupt = patch.interrupt;\n }\n await this.db\n .update(this.t.agentQueuedMessage)\n .set(updates)\n .where(eq(this.t.agentQueuedMessage.id, id));\n return this.getQueuedMessage(id);\n }\n\n /** Rewrites the thread's positions as 0..n-1 in the new order — a queue is a handful of rows. */\n async moveQueuedMessage(id: string, index: number): Promise<boolean> {\n const moving = await this.getQueuedMessage(id);\n if (moving === null) {\n return false;\n }\n const order = (await this.listQueue(moving.threadId)).filter((message) => message.id !== id);\n const target = Math.max(0, Math.min(order.length, Math.trunc(index)));\n order.splice(target, 0, moving);\n for (const [position, message] of order.entries()) {\n await this.db\n .update(this.t.agentQueuedMessage)\n .set({ position })\n .where(eq(this.t.agentQueuedMessage.id, message.id));\n }\n return true;\n }\n\n async removeQueuedMessage(id: string): Promise<boolean> {\n const removed = await affectedRows(\n this.dialect,\n this.db.delete(this.t.agentQueuedMessage).where(eq(this.t.agentQueuedMessage.id, id)),\n this.t.agentQueuedMessage.id,\n );\n return removed > 0;\n }\n\n async clearQueue(threadId: string): Promise<number> {\n return affectedRows(\n this.dialect,\n this.db\n .delete(this.t.agentQueuedMessage)\n .where(eq(this.t.agentQueuedMessage.threadId, threadId)),\n this.t.agentQueuedMessage.id,\n );\n }\n\n async queuePause(threadId: string): Promise<QueuePause | null> {\n const [thread] = await this.db\n .select({ queuePause: this.t.agentThread.queuePause })\n .from(this.t.agentThread)\n .where(eq(this.t.agentThread.id, threadId));\n return thread?.queuePause ?? null;\n }\n\n async setQueuePause(threadId: string, pause: QueuePause | null): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ queuePause: pause })\n .where(eq(this.t.agentThread.id, threadId));\n }\n\n async setActiveStream(threadId: string, runId: string | null): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ activeStreamId: runId })\n .where(eq(this.t.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 (patch.model !== undefined) {\n updates.model = patch.model;\n }\n if (patch.persona !== undefined) {\n updates.persona = patch.persona;\n }\n if (Object.keys(updates).length === 0) {\n return;\n }\n updates.updatedAt = new Date();\n await this.db\n .update(this.t.agentThread)\n .set(updates)\n .where(eq(this.t.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 /** The thread's pinned model, projected like {@link defaultAgentForThread}. */\n async modelForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ model: this.t.agentThread.model })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));\n return thread?.model ?? null;\n }\n\n /** The thread's pinned persona, projected like {@link defaultAgentForThread}. */\n async personaForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ persona: this.t.agentThread.persona })\n .from(agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));\n return thread?.persona ?? null;\n }\n\n async threadSettings(threadId: string): Promise<ThreadSettings | null> {\n const thread = this.t.agentThread;\n const [row] = await this.db\n .select({\n actorRef: thread.actorRef,\n defaultAgent: thread.defaultAgent,\n persona: thread.persona,\n model: thread.model,\n })\n .from(thread)\n .where(and(eq(thread.id, threadId), isNull(thread.deletedAt)));\n if (row === undefined) {\n return null;\n }\n return {\n actorRef: row.actorRef,\n defaultAgent: row.defaultAgent ?? null,\n persona: row.persona ?? null,\n model: row.model ?? null,\n };\n }\n\n async defaultAgentForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ defaultAgent: this.t.agentThread.defaultAgent })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.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 ttftMs: null,\n costUsd: null,\n modelId: 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 queueMs: run.queueMs !== undefined ? Math.max(0, Math.round(run.queueMs)) : null,\n modelMs: null,\n toolsMs: null,\n modelCalls: null,\n toolCalls: null,\n timings: null,\n };\n await this.db.insert(this.t.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: RecordRunEndInput): 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.ttftMs !== undefined) {\n updates.ttftMs = end.ttftMs;\n }\n if (end.costUsd !== undefined) {\n updates.costUsd = end.costUsd;\n }\n if (end.modelId !== undefined) {\n updates.modelId = end.modelId;\n }\n if (end.errorCode !== undefined) {\n updates.errorCode = end.errorCode;\n }\n if (end.errorMessage !== undefined) {\n updates.errorMessage = end.errorMessage;\n }\n if (end.timings !== undefined) {\n updates.modelMs = Math.round(end.timings.modelMs);\n updates.toolsMs = Math.round(end.timings.toolsMs);\n updates.modelCalls = end.timings.modelCalls;\n updates.toolCalls = end.timings.toolCalls;\n updates.timings = end.timings.steps;\n }\n await this.db.update(this.t.agentRun).set(updates).where(eq(this.t.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(this.t.agentRun)\n .set({ retries: sql`${this.t.agentRun.retries} + 1` })\n .where(eq(this.t.agentRun.id, runId));\n }\n\n async appendMessage(input: AppendMessageInput): Promise<StoredMessage> {\n const [thread] = await this.db\n .select()\n .from(this.t.agentThread)\n .where(eq(this.t.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 actionProposalOutcome: input.actionProposalOutcome\n ? canonicalActionProposalJson(input.actionProposalOutcome)\n : null,\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 persona: input.persona ?? null,\n runId: input.runId ?? null,\n reasoning: input.reasoning ?? null,\n reasoningMs: input.reasoningMs ?? null,\n ui: input.ui ?? null,\n feedback: null,\n seq: await this.nextMessageSeq(input.threadId),\n createdAt: now,\n };\n await this.db.insert(this.t.agentMessage).values(message);\n await this.db\n .update(this.t.agentThread)\n .set({ updatedAt: now })\n .where(eq(this.t.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(this.t.agentMessage)\n .set({ toolResults: results })\n .where(eq(this.t.agentMessage.id, messageId));\n }\n\n async setMessageUi(messageId: string, ui: AgentUiComponent[]): Promise<void> {\n await this.db\n .update(this.t.agentMessage)\n .set({ ui: ui.length > 0 ? ui : null })\n .where(eq(this.t.agentMessage.id, messageId));\n }\n\n async threadOfMessage(messageId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ threadId: this.t.agentMessage.threadId })\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.id, messageId))\n .limit(1);\n return row?.threadId ?? null;\n }\n\n async setMessageFeedback(messageId: string, feedback: MessageFeedback | null): Promise<void> {\n await this.db\n .update(this.t.agentMessage)\n .set({ feedback })\n .where(eq(this.t.agentMessage.id, messageId));\n }\n\n async truncateFrom(threadId: string, messageId: string): Promise<void> {\n const messages = await this.db\n .select()\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId))\n .orderBy(...this.messageOrder());\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\n .delete(this.t.agentToolCall)\n .where(inArray(this.t.agentToolCall.messageId, doomedIds));\n await this.db.delete(this.t.agentMessage).where(inArray(this.t.agentMessage.id, doomedIds));\n }\n\n async recordToolCall(input: RecordToolCallInput): Promise<void> {\n await this.db.insert(this.t.agentToolCall).values({\n id: input.toolCallId,\n proposalId: input.proposalId ?? null,\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 approver: input.approver ?? null,\n confirmation: input.confirmation ?? null,\n expiresAt: input.expiresAt !== undefined ? new Date(input.expiresAt) : null,\n remember: null,\n decidedVia: 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.remember !== undefined) {\n updates.remember = input.remember;\n }\n if (input.decidedVia !== undefined) {\n updates.decidedVia = input.decidedVia;\n }\n if (input.status === 'executed' || input.status === 'auto_executed') {\n updates.executedAt = new Date();\n }\n await this.db\n .update(this.t.agentToolCall)\n .set(updates)\n .where(eq(this.t.agentToolCall.id, input.toolCallId));\n }\n\n async toolCallOutcomes(toolCallIds: readonly string[]): Promise<ToolCallOutcome[]> {\n if (toolCallIds.length === 0) {\n return [];\n }\n const rows = await this.db\n .select({\n id: this.t.agentToolCall.id,\n status: this.t.agentToolCall.status,\n output: this.t.agentToolCall.output,\n error: this.t.agentToolCall.error,\n })\n .from(this.t.agentToolCall)\n .where(inArray(this.t.agentToolCall.id, [...toolCallIds]));\n return rows.map((row) => ({\n id: row.id,\n status: row.status,\n ...(row.output !== undefined && row.output !== null ? { output: row.output } : {}),\n ...(typeof row.error === 'string' ? { error: row.error } : {}),\n }));\n }\n\n async failUnsettledToolCalls(runId: string, error: string): Promise<number> {\n const pending = and(\n eq(this.t.agentToolCall.runId, runId),\n eq(this.t.agentToolCall.status, 'pending_approval'),\n );\n // Counted first: an UPDATE's affected-row count is spelled differently by every driver this\n // adapter runs on. The number is informational; the write is what matters.\n const rows = await this.db\n .select({ id: this.t.agentToolCall.id })\n .from(this.t.agentToolCall)\n .where(pending);\n if (rows.length === 0) {\n return 0;\n }\n await this.db.update(this.t.agentToolCall).set({ status: 'failed', error }).where(pending);\n return rows.length;\n }\n\n /**\n * Of `mediaIds`, the ones a surviving message — or a message waiting in the queue — in one of\n * 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: this.t.agentMessage.attachments })\n .from(this.t.agentMessage)\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(\n and(eq(this.t.agentThread.actorRef, actorRef), isNotNull(this.t.agentMessage.attachments)),\n );\n // A message waiting in a thread's queue has been sent and not yet run: what it carries is in use.\n const queued = await this.db\n .select({ attachments: this.t.agentQueuedMessage.attachments })\n .from(this.t.agentQueuedMessage)\n .innerJoin(this.t.agentThread, eq(this.t.agentQueuedMessage.threadId, this.t.agentThread.id))\n .where(\n and(\n eq(this.t.agentThread.actorRef, actorRef),\n isNotNull(this.t.agentQueuedMessage.attachments),\n ),\n );\n const wanted = new Set(mediaIds);\n const found = new Set<string>();\n for (const row of [...rows, ...queued]) {\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(this.t.agentTokenUsage).values({\n id: crypto.randomUUID(),\n threadId: input.threadId ?? null,\n actorRef: input.actorRef,\n messageId: input.messageId ?? null,\n runId: input.runId ?? null,\n feature: input.feature ?? null,\n provider: input.provider ?? null,\n tenantRef: input.tenantRef ?? null,\n audioSeconds: input.audioSeconds ?? null,\n characters: input.characters ?? null,\n requests: input.requests ?? null,\n metadata: input.metadata ?? null,\n countsTowardsQuota: input.countsTowardsQuota !== false,\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 costSource: input.costUsd !== undefined ? (input.costSource ?? 'provider') : null,\n createdAt: new Date(),\n });\n }\n\n /**\n * Generative-UI telemetry: one `agent_genui_call` row per UI tool call, upserted by its tool call\n * id — a replayed record replaces the row (keeping the first `created_at`) rather than adding one.\n */\n async recordGenuiCalls(rows: readonly RecordGenuiCallInput[]): Promise<void> {\n const table = this.t.agentGenuiCall;\n for (const row of rows) {\n const columns = {\n runId: row.runId,\n threadId: row.threadId,\n actorRef: row.actorRef,\n agentName: row.agentName ?? null,\n step: row.step,\n toolName: row.toolName,\n channel: row.channel,\n mode: row.mode,\n modelId: row.modelId,\n attempt: row.attempt,\n outcome: row.outcome,\n validity: row.validity,\n errorCategory: row.errorCategory ?? null,\n errorMessage: row.errorMessage ?? null,\n inputTokens: row.inputTokens,\n outputTokens: row.outputTokens,\n costUsd: row.costUsd ?? null,\n costSource: row.costSource ?? null,\n firstFrameMs: row.firstFrameMs ?? null,\n completeFrameMs: row.completeFrameMs ?? null,\n payloadBytes: row.payloadBytes,\n payload: row.payload ?? null,\n };\n await upsert(\n this.dialect,\n this.db.insert(table).values({ id: row.toolCallId, ...columns, createdAt: Date.now() }),\n table.id,\n columns,\n );\n }\n }\n\n async quotaToday(actorRef: string, day: string): Promise<UsageTotals> {\n return this.usageBetween(actorRef, day, day);\n }\n\n async usageBetween(actorRef: string, fromDay: string, toDay: string): Promise<UsageTotals> {\n const [totals] = await this.usageWindows(actorRef, [{ fromDay, toDay }]);\n return totals ?? sumUsage([]);\n }\n\n /**\n * Every range summed by the database in one statement, each as a conditional aggregate over the\n * rows of the smallest span covering them all — the actor's `(actor_ref, created_at)` index serves\n * it, and no usage row crosses the wire.\n */\n async usageWindows(\n actorRef: string,\n ranges: readonly { fromDay: string; toDay: string }[],\n ): Promise<UsageTotals[]> {\n if (ranges.length === 0) {\n return [];\n }\n const usage = this.t.agentTokenUsage;\n const bounds = ranges.map(({ fromDay, toDay }) => ({\n start: new Date(`${fromDay}T00:00:00.000Z`),\n end: new Date(`${toDay}T23:59:59.999Z`),\n }));\n const within = (start: Date, end: Date) =>\n and(gte(usage.createdAt, start), lte(usage.createdAt, end));\n const columns: Record<string, SQL> = {};\n bounds.forEach(({ start, end }, index) => {\n columns[`tokens${index}`] =\n sql`sum(case when ${within(start, end)} then ${usage.inputTokens} + ${usage.outputTokens} else 0 end)`;\n columns[`cost${index}`] =\n sql`sum(case when ${within(start, end)} then ${usage.costUsd} else 0 end)`;\n columns[`estimated${index}`] =\n sql`sum(case when ${within(start, end)} and ${usage.costSource} = 'estimate' then ${usage.costUsd} else 0 end)`;\n });\n const from = new Date(Math.min(...bounds.map(({ start }) => start.getTime())));\n const to = new Date(Math.max(...bounds.map(({ end }) => end.getTime())));\n const [row] = (await this.db\n .select(columns)\n .from(usage)\n // The rows a quota window counts: a filter on the rows the (actor_ref, created_at) index\n // already narrows to one actor's window.\n .where(\n and(eq(usage.actorRef, actorRef), within(from, to), eq(usage.countsTowardsQuota, true)),\n )) as Record<string, unknown>[];\n return bounds.map((_, index) => ({\n usedTokens: Number(row?.[`tokens${index}`] ?? 0),\n costUsd: Number(row?.[`cost${index}`] ?? 0),\n estimatedCostUsd: Number(row?.[`estimated${index}`] ?? 0),\n }));\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 ...(thread.model != null ? { model: thread.model } : {}),\n persona: thread.persona ?? null,\n ...(lastContent !== undefined ? { lastMessagePreview: lastContent.slice(0, 120) } : {}),\n };\n }\n\n private toStoredMessage(message: TurnMessageRow & Partial<AgentMessageRow>): StoredMessage {\n const outcome = message.actionProposalOutcome\n ? (JSON.parse(message.actionProposalOutcome) as NonNullable<\n StoredMessage['actionProposalOutcome']\n >)\n : undefined;\n return {\n ...(outcome ? { actionProposalOutcome: outcome, ui: outcome.ui } : {}),\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.persona != null ? { persona: message.persona } : {}),\n ...(message.runId != null ? { runId: message.runId } : {}),\n ...(message.reasoning != null ? { reasoning: message.reasoning } : {}),\n ...(message.reasoningMs != null ? { reasoningMs: message.reasoningMs } : {}),\n ...(message.ui != null ? { ui: message.ui } : {}),\n ...(message.feedback != null ? { feedback: message.feedback } : {}),\n };\n }\n}\n\nfunction toQueuedMessage(row: AgentQueuedMessageRow): QueuedMessage {\n return {\n ...(row.uiCapabilities !== null ? { uiCapabilities: row.uiCapabilities } : {}),\n ...(row.hostContext != null ? { hostContext: row.hostContext } : {}),\n id: row.id,\n threadId: row.threadId,\n actor: row.actor,\n content: row.content,\n ...(row.attachments !== null && row.attachments.length > 0\n ? { attachments: row.attachments }\n : {}),\n ...(row.agentName !== null ? { agentName: row.agentName } : {}),\n ...(row.persona !== null ? { persona: row.persona } : {}),\n ...(row.model !== null ? { model: row.model } : {}),\n ...(row.pageContext !== null ? { pageContext: row.pageContext } : {}),\n ...(row.interrupt ? { interrupt: true } : {}),\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n };\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport {\n type ActionProposal,\n type ActionProposalDecisionCommand,\n type ActionProposalDiscoveryIndexStore,\n type ActionProposalMutationResult,\n type ActionProposalOutcomeLease,\n type ActionProposalOutcomeStore,\n type ActionProposalScope,\n type ActionProposalStore,\n type ActionProposalStoreOptions,\n type ActionProposalSupersessionStore,\n type ActionProposalWorkerStore,\n type ClaimActionProposal,\n type CreateActionProposal,\n type CreateActionProposalResult,\n type ExtendActionProposalLease,\n type ListActionProposals,\n type SettleActionProposal,\n actionProposalOutcomeFenceValid,\n actionProposalOutcomeText,\n actionProposalScopeMatches,\n canonicalActionProposalJson,\n claimActionProposalOutcome,\n initialActionProposal,\n toolCallUpdateForTransition,\n transitionActionProposalClaim,\n transitionActionProposalDecision,\n transitionActionProposalLease,\n transitionActionProposalSettlement,\n transitionActionProposalSupersession,\n validateActionProposalDiscoveryIndexBatch,\n validateActionProposalExpiryBatch,\n validateActionProposalListQuery,\n validateActionProposalWorkerClaim,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, entityKind, eq, gt, isNull, lte, max, or, sql } from 'drizzle-orm';\nimport { actionProposalTransactionMode } from './action-proposal-transaction-mode.js';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n mysqlAffectedRows,\n} from './dialect.js';\n\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\ntype ProposalRow = AgentTables['agentActionProposal']['$inferSelect'];\n\n/**\n * Independent persisted proposals. Each decision and its durable execution work live in one row;\n * a version predicate fences every read/modify/write across connections and store instances.\n */\nexport class DrizzleActionProposalStore\n implements\n ActionProposalStore,\n ActionProposalWorkerStore,\n ActionProposalDiscoveryIndexStore,\n ActionProposalSupersessionStore\n{\n private readonly db: AgentSqliteDb;\n private readonly rawDb: AgentDrizzleDb;\n readonly actionProposalAdmissionSupported: boolean;\n private readonly synchronousSqlite: boolean;\n private readonly dialect: AgentDialect;\n private readonly table: AgentTables['agentActionProposal'];\n private readonly clock: () => number;\n\n constructor(db: AgentDrizzleDb, options: ActionProposalStoreOptions = {}) {\n this.rawDb = db;\n const kind = (db.constructor as unknown as Record<symbol, string>)[entityKind];\n const transactionMode = actionProposalTransactionMode(kind);\n this.synchronousSqlite = transactionMode === 'sync';\n this.actionProposalAdmissionSupported = transactionMode !== 'unsupported';\n this.dialect = agentDialectOf(db);\n this.table = agentTablesFor(this.dialect).agentActionProposal;\n this.db = asBuilder(db);\n this.clock = options.clock ?? Date.now;\n }\n\n async createActionProposal(input: CreateActionProposal): Promise<CreateActionProposalResult> {\n const proposal = initialActionProposal(input, this.clock());\n const row = {\n id: physicalId(input.id),\n scopeKey: scopeKey(input),\n decision: proposal.decision,\n logicalSort: logicalSort(input.id),\n createFingerprint: canonicalActionProposalJson(input),\n proposal,\n ...discoveryMetadata(proposal),\n version: 0,\n createdAt: proposal.createdAt,\n };\n const table = this.table;\n const insert = this.db.insert(table);\n const inserted =\n this.dialect === 'mysql'\n ? mysqlAffectedRows(\n await (insert as unknown as MySqlInsertIgnore<typeof row>).ignore().values(row),\n )\n : await affectedRows(this.dialect, insert.values(row).onConflictDoNothing(), table.id);\n const stored = await this.read(input, input.id);\n if (!stored) return { status: 'conflict' };\n if (inserted === 1) return { status: 'created', proposal: stored.proposal };\n return {\n status: stored.createFingerprint === row.createFingerprint ? 'unchanged' : 'conflict',\n proposal: stored.proposal,\n };\n }\n\n createReplacingActionProposal(input: CreateActionProposal): Promise<CreateActionProposalResult> {\n if (!input.replacementKey) return this.createActionProposal(input);\n const proposal = initialActionProposal(input, this.clock());\n return this.transactionSteps((db) => this.replacementSteps(db, input, proposal));\n }\n\n async supersedeActionProposal(\n scope: ActionProposalScope,\n id: string,\n command: { replacementProposalId: string; actorRef: string; via: string },\n ): Promise<ActionProposalMutationResult> {\n const replacement = await this.getActionProposal(scope, command.replacementProposalId);\n if (!replacement) return { status: 'not_found' };\n return this.mutate(scope, id, (row, now) =>\n transitionActionProposalSupersession(row, replacement, command, now),\n );\n }\n\n private *replacementSteps(\n db: AgentSqliteDb,\n input: CreateActionProposal,\n proposal: ActionProposal,\n ): Generator<AdmissionQuery, CreateActionProposalResult, unknown> {\n const table = this.table;\n const thread = agentTablesFor(this.dialect).agentThread;\n // The shared conversation admission row serializes new replacements within this scope.\n if (this.dialect === 'sqlite')\n yield {\n kind: 'write',\n query: db\n .update(thread)\n .set({ updatedAt: sql`${thread.updatedAt}` })\n .where(eq(thread.id, input.threadId)),\n };\n const threads = (yield {\n kind: 'read',\n query: lockQuery(\n db.select().from(thread).where(eq(thread.id, input.threadId)).limit(1),\n this.dialect,\n ),\n }) as Array<AgentTables['agentThread']['$inferSelect']>;\n const owner = threads[0];\n if (\n !owner ||\n owner.id !== input.threadId ||\n owner.deletedAt ||\n owner.actorRef !== input.actorRef ||\n owner.tenantRef !== input.tenantRef\n )\n return { status: 'conflict' };\n const existingRows = (yield {\n kind: 'read',\n query: db\n .select()\n .from(table)\n .where(eq(table.id, physicalId(input.id)))\n .limit(1),\n }) as ProposalRow[];\n const existing = existingRows[0];\n if (existing) {\n if (\n existing.proposal.id !== input.id ||\n !actionProposalScopeMatches(existing.proposal, input)\n )\n return { status: 'conflict' };\n return {\n status:\n existing.createFingerprint === canonicalActionProposalJson(input)\n ? 'unchanged'\n : 'conflict',\n proposal: existing.proposal,\n };\n }\n const groupKey = replacementGroupKey(input);\n if (groupKey === null) throw new Error('Missing explicit replacement identity');\n const pending = (yield {\n kind: 'read',\n query: lockQuery(\n db\n .select()\n .from(table)\n .where(\n and(\n eq(table.scopeKey, scopeKey(input)),\n eq(table.replacementGroupKey, groupKey),\n eq(table.decision, 'pending'),\n ),\n ),\n this.dialect,\n ),\n }) as ProposalRow[];\n const row = {\n id: physicalId(input.id),\n scopeKey: scopeKey(input),\n decision: proposal.decision,\n logicalSort: logicalSort(input.id),\n createFingerprint: canonicalActionProposalJson(input),\n proposal,\n ...discoveryMetadata(proposal),\n version: 0,\n createdAt: proposal.createdAt,\n };\n const insert = db.insert(table);\n const inserted = yield {\n kind: 'read',\n query:\n this.dialect === 'mysql'\n ? (insert as unknown as MySqlInsertIgnore<typeof row>).ignore().values(row)\n : insert.values(row).onConflictDoNothing().returning({ id: table.id }),\n };\n const count =\n this.dialect === 'mysql' ? mysqlAffectedRows(inserted) : (inserted as unknown[]).length;\n if (count !== 1) return { status: 'conflict' };\n for (const old of pending) {\n const result = transitionActionProposalSupersession(\n old.proposal,\n proposal,\n { replacementProposalId: proposal.id, actorRef: proposal.actorRef, via: 'replacement' },\n this.clock(),\n );\n if (\n !result.proposal ||\n canonicalActionProposalJson(result.proposal) === canonicalActionProposalJson(old.proposal)\n )\n continue;\n const next = result.proposal;\n const update = db\n .update(table)\n .set({\n proposal: next,\n decision: next.decision,\n ...discoveryMetadata(next),\n version: old.version + 1,\n })\n .where(and(eq(table.id, old.id), eq(table.version, old.version)));\n const updated = yield {\n kind: 'read',\n query: this.dialect === 'mysql' ? update : update.returning({ id: table.id }),\n };\n if (\n (this.dialect === 'mysql' ? mysqlAffectedRows(updated) : (updated as unknown[]).length) !==\n 1\n )\n throw new Error('Replacement lost its locked proposal fence');\n const settled = this.toolCallSettlement(db, old.proposal, next);\n if (settled) yield { kind: 'write', query: settled };\n }\n return { status: 'created', proposal };\n }\n\n async getActionProposal(scope: ActionProposalScope, id: string): Promise<ActionProposal | null> {\n return (await this.read(scope, id))?.proposal ?? null;\n }\n\n async listActionProposals(\n scope: ActionProposalScope,\n query: ListActionProposals = {},\n ): Promise<ActionProposal[]> {\n const limit = validateActionProposalListQuery(query);\n const rows = await this.db\n .select()\n .from(this.table)\n .where(\n and(\n eq(this.table.scopeKey, scopeKey(scope)),\n query.after === undefined\n ? undefined\n : or(\n gt(this.table.createdAt, query.after.createdAt),\n and(\n eq(this.table.createdAt, query.after.createdAt),\n gt(this.table.logicalSort, logicalSort(query.after.id)),\n ),\n ),\n query.decision === undefined ? undefined : eq(this.table.decision, query.decision),\n ),\n )\n .orderBy(asc(this.table.createdAt), asc(this.table.logicalSort))\n .limit(limit);\n return rows\n .map((row) => row.proposal)\n .filter((proposal) => actionProposalScopeMatches(proposal, scope));\n }\n\n decideActionProposal(\n scope: ActionProposalScope,\n id: string,\n command: ActionProposalDecisionCommand,\n ): Promise<ActionProposalMutationResult> {\n return this.mutate(scope, id, (row, now) =>\n transitionActionProposalDecision(row, command, now),\n );\n }\n\n claimActionProposal(\n scope: ActionProposalScope,\n id: string,\n command: ClaimActionProposal,\n ): Promise<ActionProposalMutationResult> {\n return this.mutate(scope, id, (row, now) =>\n transitionActionProposalClaim(row, command, now, randomUUID()),\n );\n }\n\n extendActionProposalLease(\n scope: ActionProposalScope,\n id: string,\n command: ExtendActionProposalLease,\n ): Promise<ActionProposalMutationResult> {\n return this.mutate(scope, id, (row, now) => transitionActionProposalLease(row, command, now));\n }\n\n settleActionProposal(\n scope: ActionProposalScope,\n id: string,\n command: SettleActionProposal,\n ): Promise<ActionProposalMutationResult> {\n return this.mutate(scope, id, (row, now) =>\n transitionActionProposalSettlement(row, command, now),\n );\n }\n\n async claimNextActionProposal(command: ClaimActionProposal): Promise<ActionProposal | null> {\n const now = this.clock();\n validateActionProposalWorkerClaim(command, now);\n const table = this.table;\n const candidates = await this.db\n .select()\n .from(table)\n .where(\n and(\n eq(table.discoveryIndexVersion, 1),\n eq(table.decision, 'approved'),\n or(\n eq(table.executionStatus, 'queued'),\n and(eq(table.executionStatus, 'executing'), lte(table.leaseExpiresAt, now)),\n ),\n ),\n )\n .orderBy(asc(table.createdAt), asc(table.logicalSort))\n .limit(32);\n for (const candidate of candidates) {\n const result = await this.claimActionProposal(\n candidate.proposal,\n candidate.proposal.id,\n command,\n );\n if (result.status === 'applied' && result.proposal) return result.proposal;\n }\n return null;\n }\n\n async expireActionProposals(command: { limit: number }): Promise<number> {\n const now = this.clock();\n validateActionProposalExpiryBatch(command, now);\n const table = this.table;\n const candidates = await this.db\n .select()\n .from(table)\n .where(\n and(\n eq(table.discoveryIndexVersion, 1),\n eq(table.decision, 'pending'),\n lte(table.proposalExpiresAt, now),\n ),\n )\n .orderBy(asc(table.createdAt), asc(table.logicalSort))\n .limit(command.limit);\n let expired = 0;\n for (const candidate of candidates) {\n const result = await this.decideActionProposal(candidate.proposal, candidate.proposal.id, {\n decision: 'expired',\n actorRef: 'system',\n via: 'expiry',\n });\n if (result.status === 'applied') expired++;\n }\n return expired;\n }\n\n async backfillActionProposalDiscoveryIndex(command: { limit: number }): Promise<number> {\n validateActionProposalDiscoveryIndexBatch(command);\n const table = this.table;\n const candidates = await this.db\n .select()\n .from(table)\n .where(eq(table.discoveryIndexVersion, 0))\n .orderBy(asc(table.createdAt), asc(table.logicalSort))\n .limit(command.limit);\n let changed = 0;\n for (const row of candidates) {\n changed += await affectedRows(\n this.dialect,\n this.db\n .update(table)\n .set({\n ...discoveryMetadata(row.proposal),\n version: row.version + 1,\n })\n .where(\n and(\n eq(table.id, row.id),\n eq(table.scopeKey, row.scopeKey),\n eq(table.version, row.version),\n eq(table.discoveryIndexVersion, 0),\n ),\n ),\n table.id,\n );\n }\n return changed;\n }\n\n async rememberedActionProposalApprovals(scope: ActionProposalScope): Promise<string[]> {\n const table = this.table;\n const rows = await this.db\n .select()\n .from(table)\n .where(\n and(\n eq(table.scopeKey, scopeKey(scope)),\n eq(table.decision, 'approved'),\n or(eq(table.executionStatus, 'succeeded'), eq(table.executionStatus, 'failed')),\n ),\n );\n return [\n ...new Set(\n rows\n .filter(\n (row) =>\n actionProposalScopeMatches(row.proposal, scope) &&\n row.proposal.decisionAudit?.remember === true,\n )\n .map((row) => row.proposal.toolName),\n ),\n ];\n }\n\n async getThreadActionProposalScope(threadId: string) {\n const thread = agentTablesFor(this.dialect).agentThread;\n const [row] = await this.db\n .select()\n .from(thread)\n .where(and(eq(thread.id, threadId), isNull(thread.deletedAt)))\n .limit(1);\n return row?.id === threadId\n ? { actorRef: row.actorRef, tenantRef: row.tenantRef, threadId: row.id }\n : null;\n }\n\n async claimNextActionProposalOutcome(command: ClaimActionProposal) {\n const now = this.clock();\n validateActionProposalWorkerClaim(command, now);\n const table = this.table;\n const candidates = await this.db\n .select()\n .from(table)\n .where(\n and(\n eq(table.deliveryStatus, 'pending'),\n or(isNull(table.deliveryLeaseExpiresAt), lte(table.deliveryLeaseExpiresAt, now)),\n ),\n )\n .orderBy(asc(table.createdAt), asc(table.logicalSort))\n .limit(32);\n for (const row of candidates) {\n const result = await this.mutate(row.proposal, row.proposal.id, (proposal, time) => {\n const claimed = claimActionProposalOutcome(proposal, command, time, randomUUID());\n return claimed\n ? { status: 'applied', proposal: claimed }\n : { status: 'conflict', proposal };\n });\n const claimed = result.proposal;\n if (result.status === 'applied' && claimed?.outcome && claimed.outcomeDelivery?.lease) {\n return {\n outcome: claimed.outcome,\n lease: {\n outcomeId: claimed.outcome.id,\n token: claimed.outcomeDelivery.lease.token,\n generation: claimed.outcomeDelivery.generation,\n },\n };\n }\n }\n return null;\n }\n\n async admitActionProposalOutcome(\n command: ActionProposalOutcomeLease,\n ): ReturnType<ActionProposalOutcomeStore['admitActionProposalOutcome']> {\n return this.transactionSteps((db) => this.admissionSteps(db, command));\n }\n\n private async transactionSteps<T>(\n factory: (db: AgentSqliteDb) => Generator<AdmissionQuery, T, unknown>,\n ): Promise<T> {\n if (!this.actionProposalAdmissionSupported)\n throw new Error(\n 'Independent actions require a certified transactional Drizzle driver (better-sqlite3, node-postgres, mysql2 or libsql)',\n );\n if (this.synchronousSqlite) {\n const database = this.rawDb as unknown as {\n transaction<R>(callback: (tx: AgentDrizzleDb) => R, config?: { behavior: 'immediate' }): R;\n };\n return database.transaction((tx) => runSync(factory(asBuilder(tx))), {\n behavior: 'immediate',\n });\n }\n const database = this.rawDb as unknown as {\n transaction<R>(callback: (tx: AgentDrizzleDb) => Promise<R>): Promise<R>;\n };\n return database.transaction(async (tx) => runAsync(factory(asBuilder(tx))));\n }\n\n private *admissionSteps(\n db: AgentSqliteDb,\n command: ActionProposalOutcomeLease,\n ): Generator<\n AdmissionQuery,\n Awaited<ReturnType<ActionProposalOutcomeStore['admitActionProposalOutcome']>>,\n unknown\n > {\n if (\n typeof command.outcomeId !== 'string' ||\n !command.outcomeId ||\n typeof command.token !== 'string' ||\n !command.token ||\n !Number.isSafeInteger(command.generation) ||\n command.generation < 1\n )\n throw new TypeError('Invalid outcome fence');\n const table = this.table;\n const tables = agentTablesFor(this.dialect);\n // Write first on asynchronous SQLite too; serialize before reading the proposal or thread.\n if (this.dialect === 'sqlite')\n yield {\n kind: 'write',\n query: db\n .update(table)\n .set({ version: sql`${table.version}` })\n .where(eq(table.outcomeIdKey, physicalId(command.outcomeId))),\n };\n const query = db\n .select()\n .from(table)\n .where(eq(table.outcomeIdKey, physicalId(command.outcomeId)))\n .limit(1);\n const rows = (yield { kind: 'read', query: lockQuery(query, this.dialect) }) as ProposalRow[];\n const row = rows[0];\n if (!row || row.proposal.outcome?.id !== command.outcomeId) return { status: 'not_found' };\n const proposal = row.proposal;\n const outcome = proposal.outcome;\n const delivery = proposal.outcomeDelivery;\n if (!outcome || !delivery) return { status: 'not_found' };\n if (proposal.outcomeDelivery?.status === 'admitted')\n return {\n status: 'unchanged',\n ...(proposal.outcomeDelivery.messageId !== undefined\n ? { messageId: proposal.outcomeDelivery.messageId }\n : {}),\n };\n if (proposal.outcomeDelivery?.status === 'discarded') return { status: 'discarded' };\n if (!actionProposalOutcomeFenceValid(proposal, command, this.clock()))\n return { status: 'conflict' };\n const threadQuery = db\n .select()\n .from(tables.agentThread)\n .where(eq(tables.agentThread.id, proposal.threadId))\n .limit(1);\n const threads = (yield { kind: 'read', query: lockQuery(threadQuery, this.dialect) }) as Array<\n AgentTables['agentThread']['$inferSelect']\n >;\n const thread = threads[0];\n // Locks may have waited beyond the lease; never use the earlier timestamp to admit.\n const now = this.clock();\n if (!actionProposalOutcomeFenceValid(proposal, command, now)) return { status: 'conflict' };\n if (\n !thread ||\n thread.id !== proposal.threadId ||\n thread.deletedAt ||\n thread.actorRef !== proposal.actorRef ||\n thread.tenantRef !== proposal.tenantRef\n ) {\n const discarded: ActionProposal = {\n ...proposal,\n outcomeDelivery: { ...delivery, status: 'discarded', lease: null },\n updatedAt: now,\n };\n yield {\n kind: 'write',\n query: db\n .update(table)\n .set({ proposal: discarded, ...discoveryMetadata(discarded), version: row.version + 1 })\n .where(and(eq(table.id, row.id), eq(table.version, row.version))),\n };\n return { status: 'discarded' };\n }\n if (thread.activeStreamId !== null) return { status: 'busy' };\n const seqRows = (yield {\n kind: 'read',\n query: db\n .select({ last: max(tables.agentMessage.seq) })\n .from(tables.agentMessage)\n .where(eq(tables.agentMessage.threadId, thread.id)),\n }) as Array<{ last: number | null }>;\n const messageId = physicalId(command.outcomeId);\n yield {\n kind: 'write',\n query: db.insert(tables.agentMessage).values({\n id: messageId,\n threadId: thread.id,\n role: 'assistant',\n content: actionProposalOutcomeText(outcome),\n actionProposalOutcome: canonicalActionProposalJson(outcome),\n ui: null,\n seq: Number(seqRows[0]?.last ?? 0) + 1,\n createdAt: new Date(now),\n }),\n };\n yield {\n kind: 'write',\n query: db\n .update(tables.agentThread)\n .set({ updatedAt: new Date(now) })\n .where(eq(tables.agentThread.id, thread.id)),\n };\n const admitted: ActionProposal = {\n ...proposal,\n outcomeDelivery: { ...delivery, status: 'admitted', lease: null, messageId },\n updatedAt: now,\n };\n const update = db\n .update(table)\n .set({ proposal: admitted, ...discoveryMetadata(admitted), version: row.version + 1 })\n .where(and(eq(table.id, row.id), eq(table.version, row.version)));\n const changed = yield {\n kind: 'read',\n query: this.dialect === 'mysql' ? update : update.returning({ id: table.id }),\n };\n const count =\n this.dialect === 'mysql' ? mysqlAffectedRows(changed) : (changed as unknown[]).length;\n if (count !== 1) throw new Error('Outcome admission lost its locked proposal fence');\n return { status: 'applied', messageId };\n }\n\n /**\n * The update that settles the proposal's `proposed` tool-call record after a transition from\n * `previous` to `next` (see `toolCallUpdateForTransition`), or `undefined` when its status stays —\n * so the dashboard and run detail show `executed` / `failed` / `rejected` / `expired` instead of\n * `proposed` forever.\n */\n private toolCallSettlement(db: AgentSqliteDb, previous: ActionProposal, next: ActionProposal) {\n const update = toolCallUpdateForTransition(previous, next);\n if (update === null) return undefined;\n const toolCall = agentTablesFor(this.dialect).agentToolCall;\n return db\n .update(toolCall)\n .set({\n status: update.status,\n ...(update.output !== undefined ? { output: update.output } : {}),\n ...(update.error !== undefined ? { error: update.error } : {}),\n ...(update.executedByRef !== undefined ? { executedByRef: update.executedByRef } : {}),\n ...(update.decidedVia !== undefined ? { decidedVia: update.decidedVia } : {}),\n ...(update.remember !== undefined ? { remember: update.remember } : {}),\n ...(update.status === 'executed' ? { executedAt: new Date(this.clock()) } : {}),\n })\n .where(and(eq(toolCall.id, update.toolCallId), eq(toolCall.proposalId, next.id)));\n }\n\n private async read(scope: ActionProposalScope, id: string): Promise<ProposalRow | undefined> {\n const [row] = await this.db\n .select()\n .from(this.table)\n .where(and(eq(this.table.id, physicalId(id)), eq(this.table.scopeKey, scopeKey(scope))))\n .limit(1);\n return row && row.proposal.id === id && actionProposalScopeMatches(row.proposal, scope)\n ? row\n : undefined;\n }\n\n private async mutate(\n scope: ActionProposalScope,\n id: string,\n transition: (proposal: ActionProposal, now: number) => ActionProposalMutationResult,\n ): Promise<ActionProposalMutationResult> {\n // A caller repeatable-read transaction may retain its original snapshot after losing CAS.\n // Bound retries so that transaction returns a conflict instead of spinning indefinitely.\n for (let attempt = 0; attempt < 32; attempt++) {\n const row = await this.read(scope, id);\n if (!row) return { status: 'not_found' };\n // Recompute the trusted clock after every lost CAS, so a delayed retry cannot approve or\n // settle a proposal using the time observed before another writer advanced it.\n const result = transition(row.proposal, this.clock());\n if (\n !result.proposal ||\n canonicalActionProposalJson(result.proposal) === canonicalActionProposalJson(row.proposal)\n )\n return result;\n const changed = await affectedRows(\n this.dialect,\n this.db\n .update(this.table)\n .set({\n proposal: result.proposal,\n decision: result.proposal.decision,\n ...discoveryMetadata(result.proposal),\n version: row.version + 1,\n })\n .where(\n and(\n eq(this.table.id, physicalId(id)),\n eq(this.table.scopeKey, scopeKey(scope)),\n eq(this.table.version, row.version),\n ),\n ),\n this.table.id,\n );\n // Return this operation's winning fence, never a peer's later recovery token.\n if (changed === 1) {\n await this.toolCallSettlement(this.db, row.proposal, result.proposal);\n return result;\n }\n }\n const row = await this.read(scope, id);\n return row ? { status: 'conflict', proposal: row.proposal } : { status: 'not_found' };\n }\n}\n\nfunction scopeKey(scope: ActionProposalScope): string {\n return createHash('sha256')\n .update(canonicalActionProposalJson([scope.tenantRef, scope.actorRef, scope.threadId]))\n .digest('hex');\n}\n\nfunction physicalId(id: string): string {\n return createHash('sha256').update(canonicalActionProposalJson(id)).digest('hex');\n}\n\n/** Hex UTF16 code units preserve the core's JavaScript lexical ID order in every SQL dialect. */\nfunction logicalSort(id: string): string {\n let sort = '';\n for (let index = 0; index < id.length; index++)\n sort += id.charCodeAt(index).toString(16).padStart(4, '0');\n return sort;\n}\n\nfunction discoveryMetadata(proposal: ActionProposal) {\n return {\n replacementGroupKey: replacementGroupKey(proposal),\n deliveryStatus: proposal.outcomeDelivery?.status ?? null,\n deliveryLeaseExpiresAt: proposal.outcomeDelivery?.lease?.expiresAt ?? null,\n outcomeIdKey: proposal.outcome ? physicalId(proposal.outcome.id) : null,\n executionStatus: proposal.execution?.status ?? null,\n leaseExpiresAt: proposal.execution?.lease?.expiresAt ?? null,\n proposalExpiresAt: proposal.expiresAt,\n discoveryIndexVersion: 1,\n };\n}\n\ninterface AdmissionQuery {\n kind: 'read' | 'write';\n query: PromiseLike<unknown>;\n}\nfunction lockQuery(query: PromiseLike<unknown>, dialect: AgentDialect): PromiseLike<unknown> {\n return dialect === 'sqlite'\n ? query\n : (query as unknown as { for(mode: 'update'): PromiseLike<unknown> }).for('update');\n}\nfunction runSync<T>(steps: Generator<AdmissionQuery, T, unknown>): T {\n let next = steps.next();\n while (!next.done) {\n const { kind, query } = next.value;\n const statement = query as unknown as { all(): unknown; run(): unknown };\n next = steps.next(kind === 'read' ? statement.all() : statement.run());\n }\n return next.value;\n}\nasync function runAsync<T>(steps: Generator<AdmissionQuery, T, unknown>): Promise<T> {\n let next = steps.next();\n while (!next.done) next = steps.next(await next.value.query);\n return next.value;\n}\n\nfunction replacementGroupKey(\n proposal: Pick<CreateActionProposal, 'toolName' | 'replacementKey'>,\n): string | null {\n return proposal.replacementKey\n ? physicalId(canonicalActionProposalJson([proposal.toolName, proposal.replacementKey]))\n : null;\n}\n","/** Explicitly certified drivers; unknown/synchronous drivers must never receive an async callback. */\nexport function actionProposalTransactionMode(\n kind: string | undefined,\n): 'sync' | 'async' | 'unsupported' {\n if (kind === 'BetterSQLite3Database' || kind === 'BetterSQLiteTransaction') return 'sync';\n if (\n kind !== undefined &&\n [\n 'NodePgDatabase',\n 'NodePgTransaction',\n 'PostgresJsDatabase',\n 'PostgresJsTransaction',\n 'MySql2Database',\n 'MySql2Transaction',\n 'LibSQLDatabase',\n 'LibSQLTransaction',\n ].includes(kind)\n )\n return 'async';\n return 'unsupported';\n}\n","import type {\n ActorSpendRow,\n AgentGovernanceQueries,\n AgentPricingStore,\n ApprovalWhere,\n FeatureSpendRow,\n GenuiCallRow,\n GenuiStats,\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 RunTimings,\n RunToolCallRow,\n RunTrendPoint,\n RunWhere,\n ThreadActivityRow,\n ThreadMessageRow,\n ThreadMeta,\n ThreadSpendRow,\n ThreadWhere,\n TimestampRange,\n ToolCallActivityRow,\n ToolCallStatus,\n ToolCallWhere,\n ToolKind,\n ToolStatRow,\n UsageBreakdownFilter,\n UsageBreakdownRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n bucketByActor,\n bucketByFeature,\n bucketByModel,\n bucketByThread,\n bucketUsageBreakdown,\n bucketUsageTrend,\n dayBoundsUtc,\n rollupThreadUsage,\n summarizeGenuiCalls,\n truncateDetailContent,\n usageRangeBounds,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n and,\n asc,\n count,\n desc,\n eq,\n gte,\n inArray,\n isNull,\n like,\n lt,\n lte,\n sql,\n sum,\n} from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n} from './dialect.js';\nimport {\n type AgentRunStatus,\n agentGenuiCall,\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 'proposed',\n 'auto_executed',\n 'pending_approval',\n 'executed',\n 'rejected',\n 'failed',\n 'expired',\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 an `agent_genui_call` row onto the core row: a NULL column is an absent field. */\nfunction toGenuiCallRow(row: typeof agentGenuiCall.$inferSelect): GenuiCallRow {\n return {\n toolCallId: row.id,\n runId: row.runId,\n threadId: row.threadId,\n actorRef: row.actorRef,\n ...(row.agentName !== null ? { agentName: row.agentName } : {}),\n step: Number(row.step),\n toolName: row.toolName,\n channel: row.channel,\n mode: row.mode,\n modelId: row.modelId,\n attempt: Number(row.attempt),\n outcome: row.outcome,\n validity: row.validity,\n ...(row.errorCategory !== null ? { errorCategory: row.errorCategory } : {}),\n ...(row.errorMessage !== null ? { errorMessage: row.errorMessage } : {}),\n inputTokens: Number(row.inputTokens),\n outputTokens: Number(row.outputTokens),\n ...(row.costUsd !== null ? { costUsd: Number(row.costUsd) } : {}),\n ...(row.costSource !== null ? { costSource: row.costSource } : {}),\n ...(row.firstFrameMs !== null ? { firstFrameMs: Number(row.firstFrameMs) } : {}),\n ...(row.completeFrameMs !== null ? { completeFrameMs: Number(row.completeFrameMs) } : {}),\n payloadBytes: Number(row.payloadBytes),\n ...(row.payload !== null ? { payload: row.payload } : {}),\n createdAt: new Date(Number(row.createdAt)),\n };\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 ttftMs: run.ttftMs ?? null,\n // MySQL's DOUBLE and Postgres' double precision come back as numbers; a driver that hands a\n // decimal back as a string is normalized here so the SPI row is always a number.\n costUsd: run.costUsd == null ? null : Number(run.costUsd),\n modelId: run.modelId ?? 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 queueMs: run.queueMs ?? null,\n modelMs: run.modelMs ?? null,\n toolsMs: run.toolsMs ?? null,\n modelCalls: run.modelCalls ?? null,\n toolCalls: run.toolCalls ?? null,\n };\n}\n\n/** A run row's persisted {@link RunTimings}, or `null` when it has none. */\nfunction toRunTimings(run: typeof agentRun.$inferSelect): RunTimings | null {\n if (!Array.isArray(run.timings)) return null;\n return {\n modelMs: run.modelMs ?? 0,\n toolsMs: run.toolsMs ?? 0,\n modelCalls: run.modelCalls ?? 0,\n toolCalls: run.toolCalls ?? 0,\n steps: run.timings,\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(\n row: Pick<\n typeof agentTokenUsage.$inferSelect,\n | 'modelId'\n | 'actorRef'\n | 'threadId'\n | 'createdAt'\n | 'inputTokens'\n | 'outputTokens'\n | 'cacheWriteTokens'\n | 'cacheReadTokens'\n | 'costUsd'\n > &\n Partial<\n Pick<\n typeof agentTokenUsage.$inferSelect,\n 'feature' | 'purpose' | 'costSource' | 'audioSeconds' | 'characters' | 'requests'\n >\n >,\n): GovernanceUsageInput {\n return {\n feature: row.feature ?? null,\n purpose: row.purpose ?? null,\n costSource: row.costSource ?? null,\n audioSeconds: row.audioSeconds == null ? null : Number(row.audioSeconds),\n characters: row.characters == null ? null : Number(row.characters),\n requests: row.requests ?? null,\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 private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(\n db: AgentDrizzleDb,\n private readonly pricingStore: AgentPricingStore,\n ) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\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 /**\n * The usage rows in range, with only what the bucketers read: `requests` always (a recorded row\n * counts as its own requests in every rollup), and the feature/unit columns only for the\n * per-feature reads that group by them.\n */\n private async usageInRange(\n range: GovernanceRange | TimestampRange,\n withFeature = false,\n ): Promise<GovernanceUsageInput[]> {\n const { start, end } = usageRangeBounds(range);\n const usage = this.t.agentTokenUsage;\n // Only what the bucketers read.\n const rows = await this.db\n .select({\n modelId: usage.modelId,\n actorRef: usage.actorRef,\n threadId: usage.threadId,\n createdAt: usage.createdAt,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cacheWriteTokens: usage.cacheWriteTokens,\n cacheReadTokens: usage.cacheReadTokens,\n costUsd: usage.costUsd,\n requests: usage.requests,\n ...(withFeature\n ? {\n feature: usage.feature,\n purpose: usage.purpose,\n costSource: usage.costSource,\n audioSeconds: usage.audioSeconds,\n characters: usage.characters,\n }\n : {}),\n })\n .from(usage)\n .where(\n and(\n gte(this.t.agentTokenUsage.createdAt, start),\n lt(this.t.agentTokenUsage.createdAt, end),\n ),\n );\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 spendByFeature(range: GovernanceRange): Promise<FeatureSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByFeature(await this.usageInRange(range, true), pricing);\n }\n\n async usageBreakdown(\n range: GovernanceRange | TimestampRange,\n filter?: UsageBreakdownFilter,\n ): Promise<UsageBreakdownRow[]> {\n const pricing = await this.loadPricing();\n return bucketUsageBreakdown(await this.usageInRange(range, true), pricing, filter);\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 = [\n ...new Set(rows.flatMap((row) => (row.threadId === null ? [] : [row.threadId]))),\n ];\n if (threadIds.length === 0) {\n return [];\n }\n const threads = await this.db\n .select({\n id: this.t.agentThread.id,\n title: this.t.agentThread.title,\n actorRef: this.t.agentThread.actorRef,\n })\n .from(this.t.agentThread)\n .where(and(inArray(this.t.agentThread.id, threadIds), isNull(this.t.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: this.t.agentToolCall.id,\n toolName: this.t.agentToolCall.toolName,\n toolType: this.t.agentToolCall.toolType,\n status: this.t.agentToolCall.status,\n threadId: this.t.agentMessage.threadId,\n createdAt: this.t.agentToolCall.createdAt,\n runId: this.t.agentToolCall.runId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .orderBy(desc(this.t.agentToolCall.createdAt), desc(this.t.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: this.t.agentMessage.threadId, value: count() })\n .from(this.t.agentMessage)\n .where(inArray(this.t.agentMessage.threadId, threadIds))\n .groupBy(this.t.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: this.t.agentTokenUsage.threadId,\n inputTokens: sum(this.t.agentTokenUsage.inputTokens),\n outputTokens: sum(this.t.agentTokenUsage.outputTokens),\n })\n .from(this.t.agentTokenUsage)\n .where(inArray(this.t.agentTokenUsage.threadId, threadIds))\n .groupBy(this.t.agentTokenUsage.threadId);\n for (const row of usageTotals) {\n if (row.threadId === null) continue;\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(this.t.agentThread)\n .where(isNull(this.t.agentThread.deletedAt))\n .orderBy(desc(this.t.agentThread.updatedAt), desc(this.t.agentThread.id))\n .limit(limit);\n return this.toThreadActivityRows(threads);\n }\n\n /** The range's runs, with only the columns the rollups read. */\n private async runsInRange(range: GovernanceRange) {\n const { start, end } = dayBoundsUtc(range);\n const run = this.t.agentRun;\n return this.db\n .select({\n agentName: run.agentName,\n status: run.status,\n retries: run.retries,\n durationMs: run.durationMs,\n ttftMs: run.ttftMs,\n parentRunId: run.parentRunId,\n startedAt: run.startedAt,\n })\n .from(run)\n .where(and(gte(run.startedAt, start), lte(run.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 const ttftsMs: 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 // A person waited for the first token of a completed TOP-LEVEL turn only: a delegated child\n // streams into its parent's turn.\n if (run.status === 'completed' && run.parentRunId == null && run.ttftMs != null) {\n ttftsMs.push(run.ttftMs);\n }\n }\n settledDurationsMs.sort((left, right) => left - right);\n ttftsMs.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 ttftP50Ms: percentileMs(ttftsMs, 0.5),\n ttftP95Ms: percentileMs(ttftsMs, 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({ errorCode: this.t.agentRun.errorCode })\n .from(this.t.agentRun)\n .where(\n and(\n gte(this.t.agentRun.startedAt, start),\n lte(this.t.agentRun.startedAt, end),\n eq(this.t.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(this.t.agentRun)\n .orderBy(desc(this.t.agentRun.startedAt), desc(this.t.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: this.t.agentToolCall.id,\n toolName: this.t.agentToolCall.toolName,\n input: this.t.agentToolCall.input,\n threadId: this.t.agentThread.id,\n threadTitle: this.t.agentThread.title,\n actorRef: this.t.agentThread.actorRef,\n agentName: this.t.agentMessage.agentName,\n requestedAt: this.t.agentToolCall.createdAt,\n runId: this.t.agentToolCall.runId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(eq(this.t.agentToolCall.status, 'pending_approval'))\n .orderBy(this.t.agentToolCall.createdAt, this.t.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 toolName: this.t.agentToolCall.toolName,\n toolType: this.t.agentToolCall.toolType,\n status: this.t.agentToolCall.status,\n executionMs: this.t.agentToolCall.executionMs,\n })\n .from(this.t.agentToolCall)\n .where(\n and(gte(this.t.agentToolCall.createdAt, start), lte(this.t.agentToolCall.createdAt, end)),\n );\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\n ? eq(this.t.agentToolCall.toolName, filters.toolName)\n : undefined,\n filters?.toolType !== undefined && isToolKind(filters.toolType)\n ? eq(this.t.agentToolCall.toolType, filters.toolType)\n : undefined,\n filters?.status !== undefined && isToolCallStatus(filters.status)\n ? eq(this.t.agentToolCall.status, filters.status)\n : undefined,\n filters?.threadId !== undefined\n ? eq(this.t.agentMessage.threadId, filters.threadId)\n : undefined,\n filters?.fromDay !== undefined\n ? gte(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .where(whereClause);\n const rows = await this.db\n .select({\n toolCallId: this.t.agentToolCall.id,\n toolName: this.t.agentToolCall.toolName,\n toolType: this.t.agentToolCall.toolType,\n status: this.t.agentToolCall.status,\n threadId: this.t.agentMessage.threadId,\n createdAt: this.t.agentToolCall.createdAt,\n runId: this.t.agentToolCall.runId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .where(whereClause)\n .orderBy(desc(this.t.agentToolCall.createdAt), desc(this.t.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(this.t.agentThread.deletedAt),\n filters?.actorRef !== undefined\n ? eq(this.t.agentThread.actorRef, filters.actorRef)\n : undefined,\n filters?.title !== undefined\n ? like(sql`lower(${this.t.agentThread.title})`, `%${filters.title.toLowerCase()}%`)\n : undefined,\n filters?.fromDay !== undefined\n ? gte(this.t.agentThread.updatedAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(this.t.agentThread.updatedAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentThread)\n .where(whereClause);\n const threads = await this.db\n .select()\n .from(this.t.agentThread)\n .where(whereClause)\n .orderBy(desc(this.t.agentThread.updatedAt), desc(this.t.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\n ? eq(this.t.agentRun.agentName, filters.agentName)\n : undefined,\n filters?.status !== undefined && isRunStatus(filters.status)\n ? eq(this.t.agentRun.status, filters.status)\n : undefined,\n filters?.errorCode !== undefined\n ? eq(this.t.agentRun.errorCode, filters.errorCode)\n : undefined,\n filters?.threadId !== undefined ? eq(this.t.agentRun.threadId, filters.threadId) : undefined,\n filters?.fromDay !== undefined\n ? gte(this.t.agentRun.startedAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(this.t.agentRun.startedAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentRun)\n .where(whereClause);\n const runs = await this.db\n .select()\n .from(this.t.agentRun)\n .where(whereClause)\n .orderBy(desc(this.t.agentRun.startedAt), desc(this.t.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(this.t.agentToolCall.status, 'pending_approval'),\n filters?.toolName !== undefined\n ? eq(this.t.agentToolCall.toolName, filters.toolName)\n : undefined,\n filters?.threadId !== undefined ? eq(this.t.agentThread.id, filters.threadId) : undefined,\n filters?.actorRef !== undefined\n ? eq(this.t.agentThread.actorRef, filters.actorRef)\n : undefined,\n filters?.agentName !== undefined\n ? eq(this.t.agentMessage.agentName, filters.agentName)\n : undefined,\n filters?.fromDay !== undefined\n ? gte(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay))\n : undefined,\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(whereClause);\n const rows = await this.db\n .select({\n toolCallId: this.t.agentToolCall.id,\n toolName: this.t.agentToolCall.toolName,\n input: this.t.agentToolCall.input,\n threadId: this.t.agentThread.id,\n threadTitle: this.t.agentThread.title,\n actorRef: this.t.agentThread.actorRef,\n agentName: this.t.agentMessage.agentName,\n requestedAt: this.t.agentToolCall.createdAt,\n runId: this.t.agentToolCall.runId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(whereClause)\n .orderBy(asc(this.t.agentToolCall.createdAt), asc(this.t.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: this.t.agentRun, thread: this.t.agentThread })\n .from(this.t.agentRun)\n .innerJoin(this.t.agentThread, eq(this.t.agentRun.threadId, this.t.agentThread.id))\n .where(eq(this.t.agentRun.id, runId))\n .limit(1);\n if (row === undefined) {\n return null;\n }\n const toolCalls = await this.db\n .select()\n .from(this.t.agentToolCall)\n .where(eq(this.t.agentToolCall.runId, runId))\n .orderBy(asc(this.t.agentToolCall.createdAt), asc(this.t.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 timings: toRunTimings(row.run),\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(this.t.agentThread)\n .where(eq(this.t.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(this.t.agentTokenUsage)\n .where(eq(this.t.agentTokenUsage.threadId, thread.id));\n const usage = rollupThreadUsage(usageRows.map(toUsageInput), pricing);\n const [messageCountRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, thread.id));\n const messages = await this.db\n .select()\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, thread.id))\n .orderBy(\n // Append order (see DrizzleAgentStore's message order), newest first.\n desc(sql`coalesce(${this.t.agentMessage.seq}, 0)`),\n desc(this.t.agentMessage.createdAt),\n desc(this.t.agentMessage.id),\n )\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(this.t.agentRun)\n .where(eq(this.t.agentRun.threadId, thread.id));\n const runs = await this.db\n .select()\n .from(this.t.agentRun)\n .where(eq(this.t.agentRun.threadId, thread.id))\n .orderBy(desc(this.t.agentRun.startedAt), desc(this.t.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 /** Generative-UI stats over the `agent_genui_call` rows created in the (UTC, inclusive) day range. */\n async genuiStats(range: GovernanceRange): Promise<GenuiStats> {\n const { start, end } = dayBoundsUtc(range);\n const table = this.t.agentGenuiCall;\n const rows = await this.db\n .select()\n .from(table)\n .where(and(gte(table.createdAt, start.getTime()), lte(table.createdAt, end.getTime())));\n return summarizeGenuiCalls(rows.map(toGenuiCallRow));\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: this.t.agentToolCall.messageId, value: count() })\n .from(this.t.agentToolCall)\n .where(inArray(this.t.agentToolCall.messageId, messageIds))\n .groupBy(this.t.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 {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n upsert,\n} from './dialect.js';\nimport { 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 private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\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(this.t.agentMemory)\n .where(inArray(this.t.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 affectedRows(\n this.dialect,\n this.db\n .delete(this.t.agentMemory)\n .where(\n and(eq(this.t.agentMemory.id, id), eq(this.t.agentMemory.scope, actorScope(ctx.actor))),\n ),\n this.t.agentMemory.id,\n );\n return deleted > 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 memory = this.t.agentMemory;\n const set = { text, ...columns, updatedAt: now };\n const insert = this.db.insert(memory).values({\n id: crypto.randomUUID(),\n scope,\n key,\n text,\n ...columns,\n pinned: false,\n createdAt: now,\n updatedAt: now,\n });\n let row: AgentMemoryRow | undefined;\n if (this.dialect === 'mysql') {\n // No `RETURNING` on MySQL: upsert, then read the row back by the key it was upserted on.\n await upsert(this.dialect, insert, [memory.scope, memory.key], set);\n [row] = await this.db\n .select()\n .from(memory)\n .where(and(eq(memory.scope, scope), eq(memory.key, key)));\n } else {\n [row] = await insert\n .onConflictDoUpdate({ target: [memory.scope, memory.key], set })\n .returning();\n }\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 affectedRows(\n this.dialect,\n this.db\n .update(this.t.agentMemory)\n .set({ pinned, updatedAt: new Date() })\n .where(eq(this.t.agentMemory.id, id)),\n this.t.agentMemory.id,\n );\n return updated > 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 {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n} from './dialect.js';\nimport { 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 private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async upsertModelPrice(input: ModelPriceInput): Promise<void> {\n await this.db\n .update(this.t.agentModelPricing)\n .set({ isCurrent: false })\n .where(\n and(\n eq(this.t.agentModelPricing.modelId, input.modelId),\n eq(this.t.agentModelPricing.isCurrent, true),\n ),\n );\n await this.db.insert(this.t.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(this.t.agentModelPricing)\n .where(eq(this.t.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 SqlTokenStreamSink,\n type SqlTokenStreamSinkOptions,\n type StreamFrameRow,\n type StreamFrameTable,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, eq, gt, inArray, lt, max, sql } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n isUniqueViolation,\n runSql,\n} from './dialect.js';\nimport { agentStreamFrame } from './schema.js';\n\n/** {@link StreamFrameTable} over `agent_stream_frame`, through a Drizzle handle on any dialect. */\nexport class DrizzleStreamFrameTable implements StreamFrameTable {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async append(\n runId: string,\n row: { frame: string | null; error: string | null; createdAt: number },\n ): Promise<void> {\n // The next number and the insert are one statement: the (run_id, seq) key settles a race.\n // MySQL takes an INSERT … SELECT from the table it inserts into (it materialises the read).\n await runSql(\n this.db,\n this.dialect,\n sql`INSERT INTO agent_stream_frame (run_id, seq, frame, error, created_at)\n SELECT ${runId}, COALESCE(MAX(seq), 0) + 1, ${row.frame}, ${row.error}, ${row.createdAt}\n FROM agent_stream_frame WHERE run_id = ${runId}`,\n );\n }\n\n async read(runId: string, after: number, limit: number): Promise<StreamFrameRow[]> {\n return this.db\n .select({\n seq: this.t.agentStreamFrame.seq,\n frame: this.t.agentStreamFrame.frame,\n error: this.t.agentStreamFrame.error,\n })\n .from(this.t.agentStreamFrame)\n .where(and(eq(this.t.agentStreamFrame.runId, runId), gt(this.t.agentStreamFrame.seq, after)))\n .orderBy(asc(this.t.agentStreamFrame.seq))\n .limit(limit);\n }\n\n async has(runId: string): Promise<boolean> {\n const rows = await this.db\n .select({ seq: this.t.agentStreamFrame.seq })\n .from(this.t.agentStreamFrame)\n .where(eq(this.t.agentStreamFrame.runId, runId))\n .limit(1);\n return rows.length > 0;\n }\n\n async remove(runIds: readonly string[]): Promise<void> {\n if (runIds.length === 0) return;\n await this.db\n .delete(this.t.agentStreamFrame)\n .where(inArray(this.t.agentStreamFrame.runId, [...runIds]));\n }\n\n async lapsedRuns(cutoff: number): Promise<string[]> {\n const rows = await this.db\n .select({ runId: this.t.agentStreamFrame.runId })\n .from(this.t.agentStreamFrame)\n .groupBy(this.t.agentStreamFrame.runId)\n .having(lt(max(this.t.agentStreamFrame.createdAt), cutoff));\n return rows.map((row) => row.runId);\n }\n\n isUniqueViolation(error: unknown): boolean {\n return isUniqueViolation(error);\n }\n}\n\n/**\n * A multi-replica `TokenStreamSink` over the app's Drizzle database — several replicas, no Redis.\n * Polled, with streamed text coalesced into one row per `flushMs`; see `SqlTokenStreamSink` for the\n * trade-offs. The `agent_stream_frame` table comes from `ensureAgentSchema` (or your migration).\n *\n * ```ts\n * AgentModule.forRoot({ model, sink: new DrizzleTokenStreamSink(db) });\n * ```\n */\nexport class DrizzleTokenStreamSink extends SqlTokenStreamSink {\n constructor(db: AgentDrizzleDb, options: SqlTokenStreamSinkOptions = {}) {\n super(new DrizzleStreamFrameTable(db), options);\n }\n}\n","import type { ConfirmTokenClaim, ConfirmTokenStore } from '@dudousxd/nestjs-agent-core';\nimport { eq, lt } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n mysqlAffectedRows,\n} from './dialect.js';\n\n/** The slice of Drizzle's MySQL insert builder used here, which the SQLite view does not have. */\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\n/**\n * A production `ConfirmTokenStore` (`defineConfirmedTool`) over the `agent_confirm_token` table —\n * what makes a confirmed write single use across replicas.\n *\n * `claim` is one insert that skips a duplicate hash — `ON CONFLICT DO NOTHING` on SQLite and\n * Postgres, `INSERT IGNORE` on MySQL — so the primary key is the lock: of two concurrent\n * confirmations one inserts and the other touches no row. A statement that does not FAIL on the\n * duplicate, rather than an insert whose violation is caught, so it never aborts a surrounding\n * transaction. Only the token's SHA-256, the actor and the tool name are stored; call\n * {@link purgeExpired} from a scheduled job to drop the dead rows. The table comes from\n * `ensureAgentSchema` (or your own migration).\n */\nexport class DrizzleConfirmTokenStore implements ConfirmTokenStore {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async claim(input: ConfirmTokenClaim): Promise<boolean> {\n const row = {\n hash: input.hash,\n actorRef: input.actorRef,\n tool: input.tool,\n expiresAt: input.expiresAt,\n createdAt: Date.now(),\n };\n const table = this.t.agentConfirmToken;\n if (this.dialect === 'mysql') {\n // MySQL's insert builder: `INSERT IGNORE`, and the header's affectedRows is 0 on a duplicate.\n const insert = this.db.insert(table) as unknown as MySqlInsertIgnore<typeof row>;\n return mysqlAffectedRows(await insert.ignore().values(row)) === 1;\n }\n const inserted = await affectedRows(\n this.dialect,\n this.db.insert(table).values(row).onConflictDoNothing(),\n table.hash,\n );\n return inserted === 1;\n }\n\n async release(hash: string): Promise<void> {\n await this.db.delete(this.t.agentConfirmToken).where(eq(this.t.agentConfirmToken.hash, hash));\n }\n\n async purgeExpired(now: number = Date.now()): Promise<number> {\n const table = this.t.agentConfirmToken;\n return affectedRows(\n this.dialect,\n this.db.delete(table).where(lt(table.expiresAt, now)),\n table.hash,\n );\n }\n}\n","import { createHash } from 'node:crypto';\nimport type { ChannelStore } from '@dudousxd/nestjs-agent-core';\nimport { and, eq, gt, lte } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n mysqlAffectedRows,\n upsert,\n} from './dialect.js';\n\n/** The slice of Drizzle's MySQL insert builder used here, which the SQLite view does not have. */\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\n/** Keys longer than the column are stored by their hash. */\nconst channelStateKey = (key: string): string =>\n key.length <= 255 ? key : `sha256:${createHash('sha256').update(key).digest('hex')}`;\n\nexport interface DrizzleChannelStoreOptions {\n /** How often a claim also deletes expired rows. Default 10 minutes; `0` → never (purge yourself). */\n purgeEveryMs?: number;\n}\n\n/**\n * A `ChannelStore` (text channels, `@dudousxd/nestjs-agent-channels`) over the `agent_channel_state`\n * table — shared by every replica, no Redis needed.\n *\n * A claim deletes the key's row when it expired, then inserts it skipping a duplicate key —\n * `ON CONFLICT DO NOTHING` on SQLite and Postgres, `INSERT IGNORE` on MySQL — so the primary key is\n * the lock: of two concurrent claims one inserts and the other touches no row. Expired rows are\n * deleted as claims arrive (`purgeEveryMs`), or by {@link purgeExpired} from a job. The table comes\n * from `ensureAgentSchema` (or your own migration).\n */\nexport class DrizzleChannelStore implements ChannelStore {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n private readonly purgeEveryMs: number;\n private lastPurge = 0;\n\n constructor(db: AgentDrizzleDb, options: DrizzleChannelStoreOptions = {}) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n this.purgeEveryMs = options.purgeEveryMs ?? 10 * 60 * 1000;\n }\n\n async claim(key: string, ttlMs: number): Promise<boolean> {\n const table = this.t.agentChannelState;\n const now = Date.now();\n if (this.purgeEveryMs > 0 && now - this.lastPurge >= this.purgeEveryMs) {\n this.lastPurge = now;\n await this.purgeExpired(now);\n }\n const id = channelStateKey(key);\n // An expired claim is free again.\n await this.db.delete(table).where(and(eq(table.key, id), lte(table.expiresAt, now)));\n const row = { key: id, value: null, expiresAt: now + ttlMs, createdAt: now };\n if (this.dialect === 'mysql') {\n // MySQL's insert builder: `INSERT IGNORE`, and the header's affectedRows is 0 on a duplicate.\n const insert = this.db.insert(table) as unknown as MySqlInsertIgnore<typeof row>;\n return mysqlAffectedRows(await insert.ignore().values(row)) === 1;\n }\n const inserted = await affectedRows(\n this.dialect,\n this.db.insert(table).values(row).onConflictDoNothing(),\n table.key,\n );\n return inserted === 1;\n }\n\n async get(key: string): Promise<string | null> {\n const table = this.t.agentChannelState;\n const rows = await this.db\n .select({ value: table.value })\n .from(table)\n .where(and(eq(table.key, channelStateKey(key)), gt(table.expiresAt, Date.now())));\n const value = rows[0]?.value;\n return typeof value === 'string' ? value : null;\n }\n\n async set(key: string, value: string, ttlMs: number): Promise<void> {\n const table = this.t.agentChannelState;\n const now = Date.now();\n await upsert(\n this.dialect,\n this.db\n .insert(table)\n .values({ key: channelStateKey(key), value, expiresAt: now + ttlMs, createdAt: now }),\n table.key,\n { value, expiresAt: now + ttlMs },\n );\n }\n\n async delete(key: string): Promise<void> {\n const table = this.t.agentChannelState;\n await this.db.delete(table).where(eq(table.key, channelStateKey(key)));\n }\n\n async purgeExpired(now: number = Date.now()): Promise<number> {\n const table = this.t.agentChannelState;\n return affectedRows(\n this.dialect,\n this.db.delete(table).where(lte(table.expiresAt, now)),\n table.key,\n );\n }\n}\n","import {\n type PoppyContext,\n type PoppyConversationPatch,\n type PoppyConversationRecord,\n type PoppyEvent,\n type PoppyEventBody,\n type PoppyGrant,\n type PoppyMessageClaim,\n type PoppyMessageReceipt,\n type PoppyResponder,\n type PoppyStatus,\n type PoppyStore,\n type StoredPoppyEvent,\n newEventId,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, desc, eq, gt, isNull, lt, lte, or } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n isUniqueViolation,\n mysqlAffectedRows,\n} from './dialect.js';\n\n/** The slice of Drizzle's MySQL insert builder used here, which the SQLite view does not have. */\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\n/** How many times an append re-numbers itself after losing its position to another append. */\nconst MAX_APPEND_ATTEMPTS = 50;\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst nullable = (value: unknown): string | null => (value == null ? null : String(value));\n\nfunction toInt(value: unknown): number {\n if (typeof value === 'number') return value;\n if (typeof value === 'bigint') return Number(value);\n if (typeof value === 'string') return Number.parseInt(value, 10) || 0;\n return 0;\n}\n\nconst PATCH_COLUMNS = {\n accountRef: 'accountRef',\n threadId: 'threadId',\n openDirectId: 'openDirectId',\n status: 'status',\n responder: 'responder',\n context: 'context',\n activeRunId: 'activeRunId',\n turnSeq: 'turnSeq',\n grant: 'grantInfo',\n prunedSeq: 'prunedSeq',\n} as const satisfies Record<keyof PoppyConversationPatch, string>;\n\n/**\n * A `PoppyStore` (Personal Agent Protocol conversations, `@dudousxd/nestjs-agent-poppy`) over the\n * `agent_poppy_conversation`, `agent_poppy_event` and `agent_poppy_message` tables — shared by every\n * replica. The tables come from `ensureAgentSchema` (or your own migration).\n *\n * Every race is settled by a key rather than a lock: an event's primary key is its position, so of\n * two appends numbered alike one inserts and the other re-numbers itself after it; `(conversation,\n * event_key)` is unique, so a keyed append happens once; a message's `(owner, message_id)` is the\n * idempotency lock. Those inserts skip a duplicate (`ON CONFLICT DO NOTHING`, `INSERT IGNORE` on\n * MySQL) rather than fail on it, so they never abort a surrounding Postgres transaction. The reader\n * lease is one conditional `UPDATE` of the conversation row.\n *\n * @experimental Tracks Personal Agent Protocol Draft 0.1 (https://personalagentprotocol.org/docs/spec).\n */\nexport class DrizzlePoppyStore implements PoppyStore {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async createConversation(record: PoppyConversationRecord): Promise<void> {\n await this.db.insert(this.t.agentPoppyConversation).values({\n id: record.id,\n clientId: record.clientId,\n userId: record.userId,\n accountRef: record.accountRef,\n agentName: record.agentName,\n threadId: record.threadId,\n parentId: record.parentId,\n openDirectId: record.openDirectId,\n status: record.status,\n responder: record.responder,\n context: JSON.stringify(record.context),\n activeRunId: record.activeRunId,\n turnSeq: record.turnSeq,\n grantInfo: record.grant === null ? null : JSON.stringify(record.grant),\n readerHolder: null,\n readerUntil: null,\n prunedSeq: record.prunedSeq,\n createdAt: record.createdAt,\n updatedAt: record.updatedAt,\n });\n }\n\n async getConversation(id: string): Promise<PoppyConversationRecord | null> {\n const table = this.t.agentPoppyConversation;\n const [row] = await this.db.select().from(table).where(eq(table.id, id)).limit(1);\n if (!row) return null;\n return {\n id: row.id,\n clientId: row.clientId,\n userId: row.userId,\n accountRef: nullable(row.accountRef),\n agentName: row.agentName,\n threadId: nullable(row.threadId),\n parentId: nullable(row.parentId),\n openDirectId: nullable(row.openDirectId),\n status: row.status as PoppyStatus,\n responder: row.responder as PoppyResponder,\n context: row.context == null ? {} : (JSON.parse(row.context) as PoppyContext),\n activeRunId: nullable(row.activeRunId),\n turnSeq: toInt(row.turnSeq),\n grant: row.grantInfo == null ? null : (JSON.parse(row.grantInfo) as PoppyGrant),\n prunedSeq: toInt(row.prunedSeq),\n createdAt: toInt(row.createdAt),\n updatedAt: toInt(row.updatedAt),\n };\n }\n\n async updateConversation(id: string, patch: PoppyConversationPatch): Promise<void> {\n const table = this.t.agentPoppyConversation;\n const set: Record<string, unknown> = { updatedAt: Date.now() };\n for (const [key, column] of Object.entries(PATCH_COLUMNS)) {\n const value = patch[key as keyof PoppyConversationPatch];\n if (value === undefined) continue;\n set[column] =\n key === 'context' || (key === 'grant' && value !== null) ? JSON.stringify(value) : value;\n }\n await this.db\n .update(table)\n .set(set as typeof table.$inferInsert)\n .where(eq(table.id, id));\n }\n\n async appendEvent(\n conversationId: string,\n body: PoppyEventBody,\n options: { key?: string } = {},\n ): Promise<{ event: StoredPoppyEvent; created: boolean }> {\n const table = this.t.agentPoppyEvent;\n for (let attempt = 1; ; attempt++) {\n if (options.key !== undefined) {\n const [existing] = await this.db\n .select({ seq: table.seq, event: table.event })\n .from(table)\n .where(and(eq(table.conversationId, conversationId), eq(table.eventKey, options.key)))\n .limit(1);\n if (existing) {\n return {\n event: { seq: toInt(existing.seq), event: JSON.parse(existing.event) as PoppyEvent },\n created: false,\n };\n }\n }\n const seq = (await this.lastSeq(conversationId)) + 1;\n const now = Date.now();\n const stored: StoredPoppyEvent = {\n seq,\n event: { id: newEventId(seq), created_at: new Date(now).toISOString(), ...body },\n };\n let inserted = false;\n try {\n inserted = await this.insertIgnore(table, {\n conversationId,\n seq,\n id: stored.event.id,\n type: body.type,\n event: JSON.stringify(stored.event),\n eventKey: options.key ?? null,\n createdAt: now,\n });\n } catch (error) {\n // MySQL may settle two inserts into one gap with a deadlock rather than a skipped duplicate.\n if (!isUniqueViolation(error)) throw error;\n }\n if (inserted) return { event: stored, created: true };\n // Another append took this position (or this key) first: look again, numbered after it.\n if (attempt >= MAX_APPEND_ATTEMPTS) {\n throw new Error(`poppy: could not append to ${conversationId} after ${attempt} attempts`);\n }\n await sleep(Math.random() * Math.min(attempt, 10) * 2);\n }\n }\n\n /** The last position taken: the last event's, or — every event pruned — the pruned floor. */\n private async lastSeq(conversationId: string): Promise<number> {\n const table = this.t.agentPoppyEvent;\n const [last] = await this.db\n .select({ seq: table.seq })\n .from(table)\n .where(eq(table.conversationId, conversationId))\n .orderBy(desc(table.seq))\n .limit(1);\n if (last) return toInt(last.seq);\n const conversations = this.t.agentPoppyConversation;\n const [conversation] = await this.db\n .select({ prunedSeq: conversations.prunedSeq })\n .from(conversations)\n .where(eq(conversations.id, conversationId))\n .limit(1);\n return toInt(conversation?.prunedSeq);\n }\n\n async listEvents(\n conversationId: string,\n afterSeq: number,\n limit: number,\n ): Promise<StoredPoppyEvent[]> {\n const table = this.t.agentPoppyEvent;\n const rows = await this.db\n .select({ seq: table.seq, event: table.event })\n .from(table)\n .where(and(eq(table.conversationId, conversationId), gt(table.seq, afterSeq)))\n .orderBy(table.seq)\n .limit(limit);\n return rows.map((row) => ({ seq: toInt(row.seq), event: JSON.parse(row.event) as PoppyEvent }));\n }\n\n async findEventSeq(conversationId: string, eventId: string): Promise<number | null> {\n const table = this.t.agentPoppyEvent;\n const [row] = await this.db\n .select({ seq: table.seq })\n .from(table)\n .where(and(eq(table.conversationId, conversationId), eq(table.id, eventId)))\n .limit(1);\n return row ? toInt(row.seq) : null;\n }\n\n async pruneEvents(conversationId: string, before: number): Promise<void> {\n const table = this.t.agentPoppyEvent;\n const [last] = await this.db\n .select({ seq: table.seq })\n .from(table)\n .where(eq(table.conversationId, conversationId))\n .orderBy(desc(table.seq))\n .limit(1);\n if (!last) return;\n // The newest event old enough to go, short of the last: it and everything before it go.\n const [dropped] = await this.db\n .select({ seq: table.seq })\n .from(table)\n .where(\n and(\n eq(table.conversationId, conversationId),\n lt(table.createdAt, before),\n lt(table.seq, toInt(last.seq)),\n ),\n )\n .orderBy(desc(table.seq))\n .limit(1);\n if (!dropped) return;\n const upTo = toInt(dropped.seq);\n // The floor moves first, so a reader never takes the gap for events not yet written.\n const conversations = this.t.agentPoppyConversation;\n await this.db\n .update(conversations)\n .set({ prunedSeq: upTo })\n .where(and(eq(conversations.id, conversationId), lt(conversations.prunedSeq, upTo)));\n await this.db\n .delete(table)\n .where(and(eq(table.conversationId, conversationId), lte(table.seq, upTo)));\n }\n\n async claimMessage(\n owner: string,\n messageId: string,\n receipt: PoppyMessageReceipt,\n ): Promise<PoppyMessageClaim> {\n const table = this.t.agentPoppyMessage;\n for (let attempt = 1; ; attempt++) {\n const inserted = await this.insertIgnore(table, {\n owner,\n messageId,\n fingerprint: receipt.fingerprint,\n conversationId: receipt.conversationId,\n response: JSON.stringify(receipt.response),\n createdAt: Date.now(),\n });\n if (inserted) return { status: 'claimed' };\n const [row] = await this.db\n .select()\n .from(table)\n .where(and(eq(table.owner, owner), eq(table.messageId, messageId)))\n .limit(1);\n if (row) {\n return {\n status: 'existing',\n fingerprint: row.fingerprint,\n conversationId: row.conversationId,\n response: JSON.parse(row.response) as PoppyMessageReceipt['response'],\n };\n }\n // Released between the two statements: claim afresh.\n if (attempt >= 5) throw new Error(`poppy: could not claim message ${messageId}`);\n }\n }\n\n async releaseMessage(owner: string, messageId: string): Promise<void> {\n const table = this.t.agentPoppyMessage;\n await this.db.delete(table).where(and(eq(table.owner, owner), eq(table.messageId, messageId)));\n }\n\n async leaseReader(conversationId: string, holder: string, ttlMs: number): Promise<boolean> {\n const table = this.t.agentPoppyConversation;\n const now = Date.now();\n // One conditional update: free, already ours, or expired. Of two takers the row lock serializes\n // them, and the second's condition no longer holds.\n const taken = await affectedRows(\n this.dialect,\n this.db\n .update(table)\n .set({ readerHolder: holder, readerUntil: now + ttlMs })\n .where(\n and(\n eq(table.id, conversationId),\n or(\n isNull(table.readerHolder),\n eq(table.readerHolder, holder),\n lte(table.readerUntil, now),\n ),\n ),\n ),\n table.id,\n );\n if (taken === 1) return true;\n if (this.dialect !== 'mysql') return false;\n // MySQL may count only CHANGED rows (no FOUND_ROWS): a renewal in the same millisecond reads 0.\n const [row] = await this.db\n .select({ holder: table.readerHolder })\n .from(table)\n .where(eq(table.id, conversationId))\n .limit(1);\n return row?.holder === holder;\n }\n\n async releaseReader(conversationId: string, holder: string): Promise<void> {\n const table = this.t.agentPoppyConversation;\n await this.db\n .update(table)\n .set({ readerHolder: null, readerUntil: null })\n .where(and(eq(table.id, conversationId), eq(table.readerHolder, holder)));\n }\n\n /** Insert `row`, skipping it on any duplicate key. `true` when it went in. */\n private async insertIgnore<Row extends Record<string, unknown>>(\n table: AgentTables['agentPoppyEvent'] | AgentTables['agentPoppyMessage'],\n row: Row,\n ): Promise<boolean> {\n if (this.dialect === 'mysql') {\n const insert = this.db.insert(table) as unknown as MySqlInsertIgnore<Row>;\n return mysqlAffectedRows(await insert.ignore().values(row)) === 1;\n }\n const statement = this.db\n .insert(table)\n .values(row as never)\n .onConflictDoNothing();\n return (await affectedRows(this.dialect, statement, table.createdAt)) === 1;\n }\n}\n","import type {\n PoppyConnectionRecord,\n PoppyConnectionStore,\n PoppyPendingConnect,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, eq } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n upsert,\n} from './dialect.js';\n\n/** The slice of Drizzle's MySQL insert builder used here, which the SQLite view does not have. */\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\nconst nullable = (value: unknown): string | null => (value == null ? null : String(value));\nconst toInt = (value: unknown): number => (typeof value === 'number' ? value : Number(value ?? 0));\n\n/**\n * A `PoppyConnectionStore` (`AgentPoppyConnectionsModule`: this app's agent acting at other Poppy\n * companies) over the `agent_poppy_connection` and `agent_poppy_connect` tables. A connection is\n * keyed by (owner, issuer) and upserted on it; a pending connect is inserted once, skipping a\n * duplicate id. The client state arrives sealed: no token is ever stored in the clear. On MySQL an\n * issuer is at most 512 characters (the composite key's index limit). The tables come from\n * `ensureAgentSchema` (or your own migration).\n *\n * @experimental Tracks Personal Agent Protocol Draft 0.1 (https://personalagentprotocol.org/docs/spec).\n */\nexport class DrizzlePoppyConnectionStore implements PoppyConnectionStore {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async listConnections(owner: string): Promise<PoppyConnectionRecord[]> {\n const table = this.t.agentPoppyConnection;\n const rows = await this.db\n .select()\n .from(table)\n .where(eq(table.owner, owner))\n .orderBy(asc(table.domain), asc(table.issuer));\n return rows.map(toConnection);\n }\n\n async getConnection(owner: string, issuer: string): Promise<PoppyConnectionRecord | null> {\n const table = this.t.agentPoppyConnection;\n const [row] = await this.db\n .select()\n .from(table)\n .where(and(eq(table.owner, owner), eq(table.issuer, issuer)))\n .limit(1);\n return row ? toConnection(row) : null;\n }\n\n async saveConnection(record: PoppyConnectionRecord): Promise<void> {\n const table = this.t.agentPoppyConnection;\n const columns = {\n domain: record.domain,\n organization: record.organization,\n scope: record.scope,\n status: record.status,\n state: record.state,\n updatedAt: record.updatedAt,\n };\n await upsert(\n this.dialect,\n this.db.insert(table).values({\n owner: record.owner,\n issuer: record.issuer,\n createdAt: record.createdAt,\n ...columns,\n }),\n [table.owner, table.issuer],\n columns,\n );\n }\n\n async deleteConnection(owner: string, issuer: string): Promise<void> {\n const table = this.t.agentPoppyConnection;\n await this.db.delete(table).where(and(eq(table.owner, owner), eq(table.issuer, issuer)));\n }\n\n async createPending(record: PoppyPendingConnect): Promise<void> {\n const table = this.t.agentPoppyConnect;\n const row = {\n id: record.id,\n owner: record.owner,\n domain: record.domain,\n issuer: record.issuer,\n organization: record.organization,\n scope: record.scope,\n actor: record.actor === null ? null : JSON.stringify(record.actor),\n threadId: record.threadId,\n runId: record.runId,\n toolCallId: record.toolCallId,\n flow: record.flow,\n status: record.status,\n expiresAt: record.expiresAt,\n createdAt: record.createdAt,\n };\n // Created once: a second create of the same id is a no-op.\n if (this.dialect === 'mysql') {\n const insert = this.db.insert(table) as unknown as MySqlInsertIgnore<typeof row>;\n await insert.ignore().values(row);\n return;\n }\n await this.db.insert(table).values(row).onConflictDoNothing();\n }\n\n async getPending(id: string): Promise<PoppyPendingConnect | null> {\n const table = this.t.agentPoppyConnect;\n const [row] = await this.db.select().from(table).where(eq(table.id, id)).limit(1);\n if (!row) return null;\n return {\n id: row.id,\n owner: row.owner,\n domain: row.domain,\n issuer: row.issuer,\n organization: row.organization,\n scope: row.scope ?? '',\n actor: row.actor == null ? null : (JSON.parse(row.actor) as PoppyPendingConnect['actor']),\n threadId: nullable(row.threadId),\n runId: nullable(row.runId),\n toolCallId: nullable(row.toolCallId),\n flow: nullable(row.flow),\n status: row.status as PoppyPendingConnect['status'],\n expiresAt: toInt(row.expiresAt),\n createdAt: toInt(row.createdAt),\n };\n }\n\n async updatePending(\n id: string,\n patch: Partial<Pick<PoppyPendingConnect, 'flow' | 'status'>>,\n ): Promise<void> {\n const set: { flow?: string | null; status?: string } = {};\n if (patch.flow !== undefined) set.flow = patch.flow;\n if (patch.status !== undefined) set.status = patch.status;\n if (Object.keys(set).length === 0) return;\n const table = this.t.agentPoppyConnect;\n await this.db.update(table).set(set).where(eq(table.id, id));\n }\n}\n\nfunction toConnection(\n row: AgentTables['agentPoppyConnection']['$inferSelect'],\n): PoppyConnectionRecord {\n return {\n owner: row.owner,\n issuer: row.issuer,\n domain: row.domain,\n organization: row.organization,\n scope: row.scope ?? '',\n status: row.status as PoppyConnectionRecord['status'],\n state: row.state,\n createdAt: toInt(row.createdAt),\n updatedAt: toInt(row.updatedAt),\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 AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n upsert,\n} from './dialect.js';\nimport { type RagIngestionLogRow, type RagIngestionStatus, ragIngestionLog } 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 */\n// Built on the SQLite table, and right on every dialect: an ORDER BY renders only the column's name.\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 */\nfunction cursorColumns(log: AgentTables['ragIngestionLog']) {\n return { documentId: log.documentId, updatedAt: log.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 private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\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(this.t.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(this.t.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(this.t.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(cursorColumns(this.t.ragIngestionLog))\n .from(this.t.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(this.t.ragIngestionLog)\n .where(eq(this.t.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 affectedRows(\n this.dialect,\n this.db\n .delete(this.t.ragIngestionLog)\n .where(eq(this.t.ragIngestionLog.documentId, documentId)),\n this.t.ragIngestionLog.documentId,\n );\n return removed > 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 affectedRows(\n this.dialect,\n this.db\n .delete(this.t.ragIngestionLog)\n .where(eq(this.t.ragIngestionLog.collection, collection)),\n this.t.ragIngestionLog.documentId,\n );\n return removed;\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\n ? eq(this.t.ragIngestionLog.collection, query.collection)\n : undefined,\n query.status !== undefined ? eq(this.t.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(this.t.ragIngestionLog.updatedAt, cursor.updatedAt),\n and(\n eq(this.t.ragIngestionLog.updatedAt, cursor.updatedAt),\n gt(this.t.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 upsert(\n this.dialect,\n this.db.insert(this.t.ragIngestionLog).values({ documentId, createdAt: now, ...outcome }),\n this.t.ragIngestionLog.documentId,\n outcome,\n );\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_CHANNEL_STORE,\n AGENT_CONFIRM_TOKEN_STORE,\n AGENT_GOVERNANCE_QUERIES,\n AGENT_POPPY_CONNECTION_STORE,\n AGENT_POPPY_STORE,\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 { DrizzleChannelStore } from './drizzle-channel-store.js';\nimport { DrizzleConfirmTokenStore } from './drizzle-confirm-token-store.js';\nimport { DrizzleGovernanceQueries } from './drizzle-governance-queries.js';\nimport { DrizzleMemoryProvider } from './drizzle-memory-provider.js';\nimport { DrizzlePoppyConnectionStore } from './drizzle-poppy-connection-store.js';\nimport { DrizzlePoppyStore } from './drizzle-poppy-store.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 /**\n * A Drizzle database on SQLite, Postgres or MySQL — `drizzle(client, { schema: agentSchema })`,\n * `pgAgentSchema` or `mysqlAgentSchema`. The stores read the dialect off the handle.\n */\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 * {@link DrizzleConfirmTokenStore} to {@link AGENT_CONFIRM_TOKEN_STORE} (confirmed writes), and\n * {@link DrizzleChannelStore} to {@link AGENT_CHANNEL_STORE} (text channels' state), and\n * {@link DrizzlePoppyStore} / {@link DrizzlePoppyConnectionStore} to {@link AGENT_POPPY_STORE} /\n * {@link AGENT_POPPY_CONNECTION_STORE} (Personal Agent Protocol conversations and connections).\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 // What makes a `defineConfirmedTool` confirmation single use across replicas.\n {\n provide: DrizzleConfirmTokenStore,\n useFactory: () => new DrizzleConfirmTokenStore(options.db),\n },\n { provide: AGENT_CONFIRM_TOKEN_STORE, useExisting: DrizzleConfirmTokenStore },\n // Text channels' state (`@dudousxd/nestjs-agent-channels`), shared by every replica.\n { provide: DrizzleChannelStore, useFactory: () => new DrizzleChannelStore(options.db) },\n { provide: AGENT_CHANNEL_STORE, useExisting: DrizzleChannelStore },\n // Personal Agent Protocol (Poppy) conversations and connections, shared by every replica.\n { provide: DrizzlePoppyStore, useFactory: () => new DrizzlePoppyStore(options.db) },\n { provide: AGENT_POPPY_STORE, useExisting: DrizzlePoppyStore },\n {\n provide: DrizzlePoppyConnectionStore,\n useFactory: () => new DrizzlePoppyConnectionStore(options.db),\n },\n { provide: AGENT_POPPY_CONNECTION_STORE, useExisting: DrizzlePoppyConnectionStore },\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 DrizzleConfirmTokenStore,\n AGENT_CONFIRM_TOKEN_STORE,\n DrizzleChannelStore,\n AGENT_CHANNEL_STORE,\n DrizzlePoppyStore,\n AGENT_POPPY_STORE,\n DrizzlePoppyConnectionStore,\n AGENT_POPPY_CONNECTION_STORE,\n ],\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC4BA,yBAQO;AAgBA,IAAMA,kBAAcC,gCACzB,gBACA;EACEC,QAAIC,yBAAK,IAAA,EAAMC,WAAU;EACzBC,cAAUF,yBAAK,WAAA,EAAaG,QAAO;EACnCC,eAAWJ,yBAAK,YAAA;EAChBK,WAAOL,yBAAK,OAAA,EAASG,QAAO;EAC5BG,eAAWC,4BAAQ,aAAa;IAAEC,MAAM;EAAU,CAAA,EAAGL,QAAO,EAAGM,QAAQ,KAAA;EACvEC,oBAAgBV,yBAAK,kBAAA;;EAErBW,kBAAcX,yBAAK,eAAA;;EAEnBY,WAAOZ,yBAAK,OAAA;;EAEZa,aAASb,yBAAK,SAAA;;EAEdc,gBAAYd,yBAAK,eAAe;IAAEQ,MAAM;EAAO,CAAA,EAAGO,MAAK;EACvDC,eAAWT,4BAAQ,cAAc;IAAEC,MAAM;EAAe,CAAA,EAAGL,QAAO;EAClEc,eAAWV,4BAAQ,cAAc;IAAEC,MAAM;EAAe,CAAA,EAAGL,QAAO;EAClEe,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UAAaC,aAAaF;QAAkB;;;;QAIvD;UAAEP,SAASU;UAAuBR,YAAY,6BAAM,IAAIQ,sBAAsBb,QAAQM,EAAE,GAA1C;QAA4C;QAC1F;UACEH,SAASW;UACTT,YAAY,6BAAM,IAAIS,oBAAoBd,QAAQM,EAAE,GAAxC;QACd;;;QAGAN,QAAQe,eACJ;UAAEZ,SAASa;UAAqBC,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;;QAE3E;UACEf,SAASkB;UACThB,YAAY,6BAAM,IAAIgB,yBAAyBrB,QAAQM,EAAE,GAA7C;QACd;QACA;UAAEH,SAASmB;UAA2BV,aAAaS;QAAyB;;QAE5E;UAAElB,SAASoB;UAAqBlB,YAAY,6BAAM,IAAIkB,oBAAoBvB,QAAQM,EAAE,GAAxC;QAA0C;QACtF;UAAEH,SAASqB;UAAqBZ,aAAaW;QAAoB;;QAEjE;UAAEpB,SAASsB;UAAmBpB,YAAY,6BAAM,IAAIoB,kBAAkBzB,QAAQM,EAAE,GAAtC;QAAwC;QAClF;UAAEH,SAASuB;UAAmBd,aAAaa;QAAkB;QAC7D;UACEtB,SAASwB;UACTtB,YAAY,6BAAM,IAAIsB,4BAA4B3B,QAAQM,EAAE,GAAhD;QACd;QACA;UAAEH,SAASyB;UAA8BhB,aAAae;QAA4B;;MAEpFE,SAAS;WACH7B,QAAQE,oBAAoB,QAAQ,CAAA,IAAK;UAACE;;QAC9CM;QACAC;QACAE;QACAK;QACAE;QACAN;QACAE;QACAK;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;;IAEJ;EACF;AACF;;;;","names":["agentThread","sqliteTable","id","text","primaryKey","actorRef","notNull","tenantRef","title","transient","integer","mode","default","activeStreamId","defaultAgent","model","persona","queuePause","$type","createdAt","updatedAt","deletedAt","table","index","on","agentMessage","threadId","references","onDelete","role","actionProposalOutcome","content","toolCalls","toolResults","attachments","followUps","usage","agentName","runId","reasoning","reasoningMs","ui","feedback","seq","agentToolCall","proposalId","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","confirmation","approver","expiresAt","remember","decidedVia","agentQueuedMessage","uiCapabilities","hostContext","actor","pageContext","interrupt","position","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","real","costSource","feature","provider","audioSeconds","characters","requests","metadata","countsTowardsQuota","agentGenuiCall","step","channel","attempt","outcome","validity","errorCategory","errorMessage","firstFrameMs","completeFrameMs","payloadBytes","payload","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentRun","durationMs","ttftMs","errorCode","retries","startedAt","settledAt","promptHash","parentRunId","queueMs","modelMs","toolsMs","modelCalls","timings","agentMemory","scope","key","originAuthor","originThreadId","originRunId","originActorRef","pinned","uniqueIndex","ragIngestionLog","documentId","collection","ownerType","ownerId","source","mimeType","size","chunks","reason","agentChannelState","value","agentConfirmToken","hash","tool","agentStreamFrame","frame","columns","agentActionProposal","scopeKey","decision","logicalSort","createFingerprint","proposal","version","executionStatus","leaseExpiresAt","deliveryStatus","deliveryLeaseExpiresAt","replacementGroupKey","outcomeIdKey","proposalExpiresAt","discoveryIndexVersion","agentPoppyConversation","clientId","userId","accountRef","parentId","openDirectId","responder","context","activeRunId","turnSeq","grantInfo","readerHolder","readerUntil","prunedSeq","agentPoppyEvent","conversationId","type","event","eventKey","agentPoppyMessage","owner","fingerprint","response","agentPoppyConnection","issuer","domain","organization","state","agentPoppyConnect","toolCallId","flow","agentSchema","import_drizzle_orm","import_mysql_core","import_pg_core","import_sqlite_core","import_mysql_core","import_pg_core","ts","name","datetime","mode","fsp","key","varchar","length","agentThread","mysqlTable","id","primaryKey","actorRef","notNull","tenantRef","title","transient","boolean","default","activeStreamId","defaultAgent","model","persona","queuePause","json","$type","createdAt","updatedAt","deletedAt","table","index","on","agentMessage","threadId","references","onDelete","role","actionProposalOutcome","longtext","content","toolCalls","toolResults","attachments","followUps","usage","agentName","runId","reasoning","reasoningMs","int","ui","feedback","seq","agentToolCall","proposalId","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","confirmation","approver","expiresAt","remember","decidedVia","agentQueuedMessage","uiCapabilities","hostContext","actor","pageContext","interrupt","position","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","double","costSource","feature","provider","audioSeconds","characters","bigint","requests","metadata","countsTowardsQuota","agentGenuiCall","step","channel","attempt","outcome","validity","errorCategory","errorMessage","firstFrameMs","completeFrameMs","payloadBytes","payload","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentRun","durationMs","ttftMs","errorCode","retries","startedAt","settledAt","promptHash","parentRunId","queueMs","modelMs","toolsMs","modelCalls","timings","agentMemory","scope","text","originAuthor","originThreadId","originRunId","originActorRef","pinned","uniqueIndex","ragIngestionLog","documentId","collection","ownerType","ownerId","source","mimeType","size","chunks","reason","agentChannelState","value","agentConfirmToken","hash","tool","agentStreamFrame","frame","columns","proposalJson","customType","dataType","toDriver","canonicalActionProposalJson","fromDriver","JSON","parse","agentActionProposal","scopeKey","decision","logicalSort","createFingerprint","proposal","version","executionStatus","leaseExpiresAt","deliveryStatus","deliveryLeaseExpiresAt","replacementGroupKey","outcomeIdKey","proposalExpiresAt","discoveryIndexVersion","agentPoppyConversation","clientId","userId","accountRef","parentId","openDirectId","responder","context","activeRunId","turnSeq","grantInfo","readerHolder","readerUntil","prunedSeq","agentPoppyEvent","conversationId","type","event","eventKey","agentPoppyMessage","owner","fingerprint","response","agentPoppyConnection","issuer","domain","organization","state","agentPoppyConnect","toolCallId","flow","mysqlAgentSchema","import_nestjs_agent_core","ts","name","timestamp","withTimezone","precision","mode","agentThread","pgTable","id","text","primaryKey","actorRef","notNull","tenantRef","title","transient","boolean","default","activeStreamId","defaultAgent","model","persona","queuePause","jsonb","$type","createdAt","updatedAt","deletedAt","table","index","on","agentMessage","threadId","references","onDelete","role","actionProposalOutcome","content","toolCalls","toolResults","attachments","followUps","usage","agentName","runId","reasoning","reasoningMs","integer","ui","feedback","seq","agentToolCall","proposalId","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","confirmation","approver","expiresAt","remember","decidedVia","agentQueuedMessage","uiCapabilities","hostContext","actor","pageContext","interrupt","position","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","doublePrecision","costSource","feature","provider","audioSeconds","characters","bigint","requests","metadata","countsTowardsQuota","agentGenuiCall","step","channel","attempt","outcome","validity","errorCategory","errorMessage","varchar","length","firstFrameMs","completeFrameMs","payloadBytes","payload","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentRun","durationMs","ttftMs","errorCode","retries","startedAt","settledAt","promptHash","parentRunId","queueMs","modelMs","toolsMs","modelCalls","timings","agentMemory","scope","key","originAuthor","originThreadId","originRunId","originActorRef","pinned","uniqueIndex","ragIngestionLog","documentId","collection","ownerType","ownerId","source","mimeType","size","chunks","reason","agentChannelState","value","agentConfirmToken","hash","tool","agentStreamFrame","frame","columns","proposalJson","customType","dataType","toDriver","canonicalActionProposalJson","fromDriver","JSON","parse","agentActionProposal","scopeKey","decision","logicalSort","createFingerprint","proposal","version","executionStatus","leaseExpiresAt","deliveryStatus","deliveryLeaseExpiresAt","replacementGroupKey","outcomeIdKey","proposalExpiresAt","discoveryIndexVersion","agentPoppyConversation","clientId","userId","accountRef","parentId","openDirectId","responder","context","activeRunId","turnSeq","grantInfo","readerHolder","readerUntil","prunedSeq","agentPoppyEvent","conversationId","type","event","eventKey","agentPoppyMessage","owner","fingerprint","response","agentPoppyConnection","issuer","domain","organization","state","agentPoppyConnect","toolCallId","flow","pgAgentSchema","agentDialectOf","db","is","PgDatabase","MySqlDatabase","agentTablesFor","dialect","pgAgentSchema","mysqlAgentSchema","agentSchema","asBuilder","affectedRows","statement","column","returning","affected","length","mysqlAffectedRows","result","header","Array","isArray","counts","count","rowsAffected","runSql","run","execute","querySql","all","rows","isUniqueViolation","error","current","code","errno","startsWith","cause","upsert","insert","target","set","onDuplicateKeyUpdate","onConflictDoUpdate","ensureAgentSchema","db","dialect","agentDialectOf","transaction","tx","execute","sql","raw","LOCK_NAME","heal","MYSQL_TABLE_OPTIONS","tableSpec","table","config","pgTableConfig","mysqlTableConfig","sqliteTableConfig","columns","compositeKey","primaryKeys","map","column","name","primaryKey","filter","primary","c","foreignKeys","foreignKey","reference","getTableName","foreignTable","foreignColumns","onDelete","undefined","indexes","index","String","unique","quote","identifier","literal","value","replaceAll","columnDefinition","parts","getSQLType","notNull","push","hasDefault","default","join","createTableSql","spec","q","lines","toUpperCase","options","agentSchemaDdl","statements","specs","createIndexSql","guard","all","Object","values","agentTablesFor","ordered","placed","Set","length","ready","has","every","key","Error","add","existingColumns","columnNullability","keys","rows","querySql","Map","row","Number","notnull","NAME","nullable","NULLABLE","relaxNotNull","runSql","some","other","scratch","present","list","error","catch","indexExists","query","includes","get","import_nestjs_agent_core","import_drizzle_orm","import_nestjs_agent_core","import_drizzle_orm","actionProposalTransactionMode","kind","undefined","includes","DrizzleActionProposalStore","db","rawDb","actionProposalAdmissionSupported","synchronousSqlite","dialect","table","clock","options","kind","entityKind","transactionMode","actionProposalTransactionMode","agentDialectOf","agentTablesFor","agentActionProposal","asBuilder","Date","now","createActionProposal","input","proposal","initialActionProposal","row","id","physicalId","scopeKey","decision","logicalSort","createFingerprint","canonicalActionProposalJson","discoveryMetadata","version","createdAt","insert","inserted","mysqlAffectedRows","ignore","values","affectedRows","onConflictDoNothing","stored","read","status","createReplacingActionProposal","replacementKey","transactionSteps","replacementSteps","supersedeActionProposal","scope","command","replacement","getActionProposal","replacementProposalId","mutate","transitionActionProposalSupersession","thread","agentThread","query","update","set","updatedAt","sql","where","eq","threadId","threads","lockQuery","select","from","limit","owner","deletedAt","actorRef","tenantRef","existingRows","existing","actionProposalScopeMatches","groupKey","replacementGroupKey","Error","pending","and","returning","count","length","old","result","via","next","updated","settled","toolCallSettlement","listActionProposals","validateActionProposalListQuery","rows","after","undefined","or","gt","orderBy","asc","map","filter","decideActionProposal","transitionActionProposalDecision","claimActionProposal","transitionActionProposalClaim","randomUUID","extendActionProposalLease","transitionActionProposalLease","settleActionProposal","transitionActionProposalSettlement","claimNextActionProposal","validateActionProposalWorkerClaim","candidates","discoveryIndexVersion","executionStatus","lte","leaseExpiresAt","candidate","expireActionProposals","validateActionProposalExpiryBatch","proposalExpiresAt","expired","backfillActionProposalDiscoveryIndex","validateActionProposalDiscoveryIndexBatch","changed","rememberedActionProposalApprovals","Set","decisionAudit","remember","toolName","getThreadActionProposalScope","isNull","claimNextActionProposalOutcome","deliveryStatus","deliveryLeaseExpiresAt","time","claimed","claimActionProposalOutcome","outcome","outcomeDelivery","lease","outcomeId","token","generation","admitActionProposalOutcome","admissionSteps","factory","database","transaction","tx","runSync","behavior","runAsync","Number","isSafeInteger","TypeError","tables","outcomeIdKey","delivery","messageId","actionProposalOutcomeFenceValid","threadQuery","discarded","activeStreamId","seqRows","last","max","agentMessage","seq","role","content","actionProposalOutcomeText","actionProposalOutcome","ui","admitted","previous","toolCallUpdateForTransition","toolCall","agentToolCall","output","error","executedByRef","decidedVia","executedAt","toolCallId","proposalId","transition","attempt","createHash","digest","sort","index","charCodeAt","toString","padStart","expiresAt","execution","for","steps","done","value","statement","all","run","turnMessageColumns","message","id","role","content","agentName","toolCalls","toolResults","attachments","createdAt","DrizzleAgentStore","db","dialect","t","proposals","options","DrizzleActionProposalStore","agentDialectOf","agentTablesFor","asBuilder","createActionProposal","args","getActionProposal","listActionProposals","decideActionProposal","claimActionProposal","extendActionProposalLease","claimNextActionProposal","expireActionProposals","backfillActionProposalDiscoveryIndex","command","settleActionProposal","createReplacingActionProposal","supersedeActionProposal","actionProposalAdmissionSupported","getThreadActionProposalScope","threadId","claimNextActionProposalOutcome","admitActionProposalOutcome","createThread","input","now","Date","thread","crypto","randomUUID","actorRef","actor","tenantRef","title","transient","activeStreamId","defaultAgent","model","persona","queuePause","updatedAt","deletedAt","insert","agentThread","values","toSummary","getThread","select","from","where","and","eq","isNull","undefined","messages","agentMessage","orderBy","messageOrder","last","length","approvals","approvalsFor","map","stored","toStoredMessage","onMessage","get","activeRunId","loadThreadForTurn","query","loadTurnWindow","messageLimit","answered","limit","hasAssistantMessage","window","messageOrderNewestFirst","rows","reverse","row","listThreads","threads","desc","previews","lastMessageContents","threadIds","contents","Map","highest","seq","max","inArray","groupBy","numbered","filter","or","Number","has","set","softDeleteThread","update","forkThread","fromMessageId","source","Error","cutoff","findIndex","kept","slice","fork","index","followUps","usage","runId","reasoning","reasoningMs","ui","actionProposalOutcome","ownerOfThread","ownerOfToolCall","toolCallId","agentToolCall","innerJoin","messageId","runForToolCall","messageIds","byMessage","status","approver","confirmation","expiresAt","remember","executedByRef","decidedVia","error","isNotNull","asc","approval","toolCallApprovalFromRow","list","push","rememberedApprovals","selectDistinct","toolName","scope","proposalNames","rememberedActionProposalApprovals","Set","toolCallInput","toolCallApproval","toISOString","ownerOfActiveStream","setTitle","promoteThread","activeHolder","sql","nextMessageSeq","activeRunForThread","claimActiveStream","holders","replacing","claimed","affectedRows","releaseActiveStream","released","enqueueMessage","edge","first","min","agentQueuedMessage","position","at","uiCapabilities","hostContext","pageContext","interrupt","toQueuedMessage","listQueue","getQueuedMessage","updateQueuedMessage","patch","updates","moveQueuedMessage","moving","order","target","Math","trunc","splice","entries","removeQueuedMessage","removed","delete","clearQueue","setQueuePause","pause","setActiveStream","updateThread","Object","keys","modelForThread","personaForThread","threadSettings","defaultAgentForThread","recordRunStart","run","runRow","durationMs","ttftMs","costUsd","modelId","errorCode","errorMessage","retries","startedAt","settledAt","promptHash","parentRunId","queueMs","round","modelMs","toolsMs","modelCalls","timings","agentRun","recordRunEnd","end","steps","bumpRunRetries","appendMessage","canonicalActionProposalJson","feedback","setMessageToolResults","results","setMessageUi","threadOfMessage","setMessageFeedback","truncateFrom","doomedIds","recordToolCall","proposalId","toolType","output","executionMs","executedAt","updateToolCall","toolCallOutcomes","toolCallIds","failUnsettledToolCalls","pending","referencedMediaIds","mediaIds","queued","wanted","found","attachment","mediaId","add","recordUsage","agentTokenUsage","feature","provider","audioSeconds","characters","requests","metadata","countsTowardsQuota","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costSource","recordGenuiCalls","table","agentGenuiCall","columns","step","channel","mode","attempt","outcome","validity","errorCategory","firstFrameMs","completeFrameMs","payloadBytes","payload","upsert","quotaToday","day","usageBetween","fromDay","toDay","totals","usageWindows","sumUsage","ranges","bounds","start","within","gte","lte","forEach","getTime","to","_","usedTokens","estimatedCostUsd","lastContent","lastMessagePreview","JSON","parse","import_nestjs_agent_core","import_drizzle_orm","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","toGenuiCallRow","row","toolCallId","id","runId","threadId","actorRef","agentName","step","Number","toolName","channel","mode","modelId","attempt","outcome","validity","errorCategory","errorMessage","inputTokens","outputTokens","costUsd","costSource","firstFrameMs","completeFrameMs","payloadBytes","payload","createdAt","Date","toRecentRunRow","run","status","durationMs","ttftMs","errorCode","retries","startedAt","toISOString","promptHash","parentRunId","queueMs","modelMs","toolsMs","modelCalls","toolCalls","toRunTimings","Array","isArray","timings","steps","toRunToolCallRow","toolCall","toolType","executionMs","executedByRef","error","toUsageInput","feature","purpose","audioSeconds","characters","requests","slice","cacheWriteTokens","cacheReadTokens","percentileMs","sortedDurationsMs","p","length","offset","Math","min","floor","DrizzleGovernanceQueries","db","dialect","t","pricingStore","agentDialectOf","agentTablesFor","asBuilder","loadPricing","prices","listCurrentPrices","pricing","Map","price","set","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","usageInRange","range","withFeature","usageRangeBounds","usage","agentTokenUsage","select","from","where","and","gte","lt","map","spendByModel","bucketByModel","spendByFeature","bucketByFeature","usageBreakdown","filter","bucketUsageBreakdown","spendByActor","bucketByActor","spendByThread","limit","threadIds","Set","flatMap","threads","agentThread","title","inArray","isNull","deletedAt","threadsById","thread","bucketByThread","includeUnknownThreads","usageTrend","bucketUsageTrend","recentToolCalls","agentToolCall","agentMessage","innerJoin","eq","messageId","orderBy","desc","threadRollups","rollups","messageCount","totalTokens","messageCounts","count","groupBy","bucket","get","undefined","usageTotals","sum","toThreadActivityRows","rollup","lastActivityAt","updatedAt","recentThreads","runsInRange","agentRun","lte","runMetrics","runs","completed","failed","settledDurationsMs","ttftsMs","push","sort","left","right","successRate","durationP50Ms","durationP95Ms","ttftP50Ms","ttftP95Ms","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","deleted","threadDetail","usageRows","rollupThreadUsage","messageCountRow","messages","seq","messageLimit","toolCallCounts","toolCallCountsByMessage","message","runTotalRow","runLimit","runTotal","content","truncated","truncateDetailContent","role","toolCallCount","genuiStats","table","agentGenuiCall","getTime","summarizeGenuiCalls","messageIds","counts","import_nestjs_agent_core","import_drizzle_orm","toRecord","row","id","key","text","scope","origin","author","originAuthor","originThreadId","threadId","originRunId","runId","originActorRef","actorRef","updatedAt","toISOString","pinned","DrizzleMemoryProvider","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","list","scopes","length","rows","select","from","agentMemory","where","inArray","map","forget","ctx","deleted","affectedRows","delete","and","eq","actorScope","actor","write","assertAuthorMayWriteScope","now","Date","columns","memory","set","insert","values","crypto","randomUUID","createdAt","upsert","onConflictDoUpdate","target","returning","undefined","Error","pin","updated","update","own","import_drizzle_orm","DrizzlePricingStore","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","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","import_nestjs_agent_core","import_drizzle_orm","DrizzleStreamFrameTable","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","append","runId","row","runSql","sql","frame","error","createdAt","read","after","limit","select","seq","agentStreamFrame","from","where","and","eq","gt","orderBy","asc","has","rows","length","remove","runIds","delete","inArray","lapsedRuns","cutoff","groupBy","having","lt","max","map","isUniqueViolation","DrizzleTokenStreamSink","SqlTokenStreamSink","options","import_drizzle_orm","DrizzleConfirmTokenStore","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","claim","input","row","hash","actorRef","tool","expiresAt","createdAt","Date","now","table","agentConfirmToken","insert","mysqlAffectedRows","ignore","values","inserted","affectedRows","onConflictDoNothing","release","delete","where","eq","purgeExpired","lt","import_node_crypto","import_drizzle_orm","channelStateKey","key","length","createHash","update","digest","DrizzleChannelStore","db","dialect","t","purgeEveryMs","lastPurge","options","agentDialectOf","agentTablesFor","asBuilder","claim","ttlMs","table","agentChannelState","now","Date","purgeExpired","id","delete","where","and","eq","lte","expiresAt","row","value","createdAt","insert","mysqlAffectedRows","ignore","values","inserted","affectedRows","onConflictDoNothing","get","rows","select","from","gt","set","upsert","import_nestjs_agent_core","import_drizzle_orm","MAX_APPEND_ATTEMPTS","sleep","ms","Promise","resolve","setTimeout","nullable","value","String","toInt","Number","parseInt","PATCH_COLUMNS","accountRef","threadId","openDirectId","status","responder","context","activeRunId","turnSeq","grant","prunedSeq","DrizzlePoppyStore","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","createConversation","record","insert","agentPoppyConversation","values","id","clientId","userId","agentName","parentId","JSON","stringify","grantInfo","readerHolder","readerUntil","createdAt","updatedAt","getConversation","table","row","select","from","where","eq","limit","parse","updateConversation","patch","set","Date","now","key","column","Object","entries","undefined","update","appendEvent","conversationId","body","options","agentPoppyEvent","attempt","existing","seq","event","and","eventKey","created","lastSeq","stored","newEventId","created_at","toISOString","inserted","insertIgnore","type","error","isUniqueViolation","Error","Math","random","min","last","orderBy","desc","conversations","conversation","listEvents","afterSeq","rows","gt","map","findEventSeq","eventId","pruneEvents","before","dropped","lt","upTo","delete","lte","claimMessage","owner","messageId","receipt","agentPoppyMessage","fingerprint","response","releaseMessage","leaseReader","holder","ttlMs","taken","affectedRows","or","isNull","releaseReader","mysqlAffectedRows","ignore","statement","onConflictDoNothing","import_drizzle_orm","nullable","value","String","toInt","Number","DrizzlePoppyConnectionStore","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","listConnections","owner","table","agentPoppyConnection","rows","select","from","where","eq","orderBy","asc","domain","issuer","map","toConnection","getConnection","row","and","limit","saveConnection","record","columns","organization","scope","status","state","updatedAt","upsert","insert","values","createdAt","deleteConnection","delete","createPending","agentPoppyConnect","id","actor","JSON","stringify","threadId","runId","toolCallId","flow","expiresAt","ignore","onConflictDoNothing","getPending","parse","updatePending","patch","set","undefined","Object","keys","length","update","import_drizzle_orm","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","cursorColumns","log","DrizzleRagIngestionLog","logger","Logger","teardowns","inFlight","Set","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","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","affectedRows","delete","removeByCollection","collection","page","cursor","keyset","and","base","or","lt","gt","mediaId","now","Date","ownerType","ownerId","source","mimeType","size","outcome","chunks","reason","error","upsert","insert","values","createdAt","warn","Error","String","promise","tracked","finally","add","import_nestjs_agent_core","import_common","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","DrizzleConfirmTokenStore","AGENT_CONFIRM_TOKEN_STORE","DrizzleChannelStore","AGENT_CHANNEL_STORE","DrizzlePoppyStore","AGENT_POPPY_STORE","DrizzlePoppyConnectionStore","AGENT_POPPY_CONNECTION_STORE","exports"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/schema.ts","../src/ensure-schema.ts","../src/dialect.ts","../src/schema-mysql.ts","../src/schema-pg.ts","../src/drizzle-agent-store.ts","../src/drizzle-action-proposal-store.ts","../src/action-proposal-transaction-mode.ts","../src/drizzle-governance-queries.ts","../src/drizzle-memory-provider.ts","../src/drizzle-pricing-store.ts","../src/drizzle-token-stream-sink.ts","../src/drizzle-confirm-token-store.ts","../src/drizzle-channel-store.ts","../src/drizzle-poppy-store.ts","../src/drizzle-poppy-connection-store.ts","../src/drizzle-rag-ingestion-log.ts","../src/drizzle-agent-store.module.ts"],"sourcesContent":["export * from './schema.js';\nexport * from './ensure-schema.js';\nexport * from './drizzle-agent-store.js';\nexport * from './drizzle-action-proposal-store.js';\nexport * from './drizzle-governance-queries.js';\nexport * from './drizzle-memory-provider.js';\nexport * from './drizzle-pricing-store.js';\nexport * from './drizzle-token-stream-sink.js';\nexport * from './drizzle-confirm-token-store.js';\nexport * from './drizzle-channel-store.js';\nexport * from './drizzle-poppy-store.js';\nexport * from './drizzle-poppy-connection-store.js';\nexport * from './drizzle-rag-ingestion-log.js';\nexport * from './drizzle-agent-store.module.js';\nexport { pgAgentSchema } from './schema-pg.js';\nexport { mysqlAgentSchema } from './schema-mysql.js';\nexport {\n type AgentDialect,\n type AgentMySqlDb,\n type AgentPgDb,\n type AgentSqliteDb,\n agentDialectOf,\n} from './dialect.js';\n","import type {\n ActionProposal,\n Actor,\n AgentUiComponent,\n MemoryOrigin,\n MessageAttachment,\n MessageFeedback,\n MessageRole,\n MessageUsage,\n PageContext,\n QueuePause,\n ToolCallRequest,\n ToolCallStatus,\n ToolConfirmation,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport type {\n AgentHostContext,\n CostSource,\n GenuiErrorCategory,\n GenuiToolMarker,\n GenuiValidity,\n RecordGenuiCallInput,\n RunStepTiming,\n} from '@dudousxd/nestjs-agent-core';\nimport type { UiCapabilities } from '@dudousxd/nestjs-agent-core/genui';\nimport {\n index,\n integer,\n primaryKey,\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 /** The model every turn on this thread runs on unless the send names one; `null` → default. */\n model: text('model'),\n /** The persona a send on this thread runs under when it names none; `null` → the agent's default. */\n persona: text('persona'),\n /** Why the thread's message queue stopped draining; `null` → it drains. */\n queuePause: text('queue_pause', { mode: 'json' }).$type<QueuePause>(),\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) => [\n index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt),\n // `ownerOfActiveStream` reads by run id on every stream attach and reconnect.\n index('agent_thread_active_stream_idx').on(table.activeStreamId),\n ],\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 actionProposalOutcome: text('action_proposal_outcome'),\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 /** The persona the turn that wrote this message ran under; `null` → none. */\n persona: text('persona'),\n runId: text('run_id'),\n /** The step's streamed thinking; `null` when the model produced none. */\n reasoning: text('reasoning'),\n reasoningMs: integer('reasoning_ms'),\n /** Components pushed during the step (`ui` stream frames), replayed on reload. */\n ui: text('ui', { mode: 'json' }).$type<AgentUiComponent[]>(),\n /** The thread owner's thumbs-up/down (+ comment); `null` when unrated. Not copied on fork. */\n feedback: text('feedback', { mode: 'json' }).$type<MessageFeedback>(),\n /**\n * The message's place in its thread, 1-based, assigned on append — what orders a transcript.\n * `created_at` cannot: two messages of one turn routinely share a timestamp, and the uuid that\n * broke the tie is random. `null` on a row from before the column; those sort first.\n */\n seq: integer('seq'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [\n index('agent_message_thread_created_idx').on(table.threadId, table.createdAt),\n // Transcript reads order a thread's messages by `seq`.\n index('agent_message_thread_seq_idx').on(table.threadId, table.seq),\n ],\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 proposalId: text('proposal_id'),\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 /** Resolved per-call wording; null falls back to presentation templates. */\n confirmation: text('confirmation', { mode: 'json' }).$type<ToolConfirmation>(),\n /** Who had to approve it (`requester` or a role); null for a call no policy put to anyone. */\n approver: text('approver'),\n /** When the approval request lapses; null → never. */\n expiresAt: integer('expires_at', { mode: 'timestamp_ms' }),\n /** The approval covers later calls of this tool in this thread. */\n remember: integer('remember', { mode: 'boolean' }),\n /** The surface the decision came through (`web`, `slack`, `remembered`, …). */\n decidedVia: text('decided_via'),\n },\n (table) => [\n index('agent_tool_call_message_idx').on(table.messageId),\n // The approvals inbox: `pending_approval`, oldest first.\n index('agent_tool_call_status_created_idx').on(table.status, table.createdAt),\n index('agent_tool_call_run_idx').on(table.runId),\n index('agent_tool_call_created_idx').on(table.createdAt),\n ],\n);\n\n/**\n * A message sent while a turn was running on its thread, waiting to run after it — see the core\n * `ChatQueueStore`. Not part of the transcript: the turn it starts appends it as its user message,\n * and the row is deleted as it starts. `position` orders a thread's queue (head first); it is\n * rewritten on a move, and only ever compared within one thread. `threadId` cascades on delete.\n */\nexport const agentQueuedMessage = sqliteTable(\n 'agent_queued_message',\n {\n uiCapabilities: text('ui_capabilities', { mode: 'json' }).$type<UiCapabilities>(),\n hostContext: text('host_context', { mode: 'json' }).$type<AgentHostContext>(),\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n /** Who queued it — the turn it starts runs as this actor. */\n actor: text('actor', { mode: 'json' }).$type<Actor>().notNull(),\n content: text('content').notNull(),\n attachments: text('attachments', { mode: 'json' }).$type<MessageAttachment[]>(),\n agentName: text('agent_name'),\n /** The persona the send resolved — what the message starts under. */\n persona: text('persona'),\n model: text('model'),\n pageContext: text('page_context', { mode: 'json' }).$type<PageContext>(),\n interrupt: integer('interrupt', { mode: 'boolean' }).notNull().default(false),\n position: integer('position').notNull(),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_queued_message_thread_position_idx').on(table.threadId, table.position)],\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 // NULL for usage recorded outside any conversation (`AgentService.recordUsage`).\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 /** The turn's USD cost: provider-reported, or estimated from the price row (see `costSource`); null when unpriced. */\n costUsd: real('cost_usd'),\n /** Where `cost_usd` came from: `'provider'` (reported) or `'estimate'` (tokens × the price row); null on rows from before it existed (reported). */\n costSource: text('cost_source').$type<CostSource>(),\n /** The run the row belongs to. */\n runId: text('run_id'),\n /** What the spend was for: `agent:<name>` for an agent turn, the app's own otherwise; null → `agent`. */\n feature: text('feature'),\n provider: text('provider'),\n tenantRef: text('tenant_ref'),\n /** Units a row bills by when they are not tokens. */\n audioSeconds: real('audio_seconds'),\n characters: integer('characters'),\n requests: integer('requests'),\n /** The caller's own JSON, never read by the library. */\n metadata: text('metadata', { mode: 'json' }).$type<Record<string, unknown>>(),\n /** `false` keeps the row out of the agent's quota windows (`recordUsage({ countsTowardsQuota: false })`). */\n countsTowardsQuota: integer('counts_towards_quota', { mode: 'boolean' })\n .notNull()\n .default(true),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [\n index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt),\n index('agent_token_usage_created_idx').on(table.createdAt),\n index('agent_token_usage_thread_idx').on(table.threadId),\n index('agent_token_usage_feature_created_idx').on(table.feature, table.createdAt),\n // `quota.per: 'tenant' | 'actor-in-tenant'` sums a tenant's window.\n index('agent_token_usage_tenant_created_idx').on(table.tenantRef, table.createdAt),\n ],\n);\n\n/**\n * Generative-UI telemetry (`AgentStore.recordGenuiCalls`): one row per UI tool call, keyed by the\n * tool call's id, so a replayed record replaces rather than duplicates. Metadata only — `payload`\n * (the call's arguments) is filled solely when the tool samples payloads. `created_at` is epoch-ms.\n */\nexport const agentGenuiCall = sqliteTable(\n 'agent_genui_call',\n {\n id: text('id').primaryKey(),\n runId: text('run_id').notNull(),\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 step: integer('step').notNull(),\n toolName: text('tool_name').notNull(),\n channel: text('channel').notNull(),\n mode: text('mode').$type<GenuiToolMarker['mode']>().notNull(),\n modelId: text('model_id').notNull(),\n attempt: integer('attempt').notNull(),\n outcome: text('outcome').$type<RecordGenuiCallInput['outcome']>().notNull(),\n validity: text('validity').$type<GenuiValidity>().notNull(),\n errorCategory: text('error_category').$type<GenuiErrorCategory>(),\n errorMessage: text('error_message'),\n inputTokens: integer('input_tokens').notNull(),\n outputTokens: integer('output_tokens').notNull(),\n costUsd: real('cost_usd'),\n costSource: text('cost_source').$type<CostSource>(),\n firstFrameMs: integer('first_frame_ms'),\n completeFrameMs: integer('complete_frame_ms'),\n payloadBytes: integer('payload_bytes').notNull(),\n payload: text('payload'),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [\n index('agent_genui_call_created_idx').on(table.createdAt),\n index('agent_genui_call_run_idx').on(table.runId),\n ],\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 /** Turn start to the first `text` frame; null for a run that streamed none or did not complete. */\n ttftMs: integer('ttft_ms'),\n /** The run's known spend (the sum of its model calls with a known cost); null when none had one. */\n costUsd: real('cost_usd'),\n /** The model the run's last model call resolved to. */\n modelId: text('model_id'),\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 /** Enqueue → body start (ms); null when not read. */\n queueMs: integer('queue_ms'),\n /** Where the completed run's time went: model and tool totals, counts, and the per-step list. */\n modelMs: integer('model_ms'),\n toolsMs: integer('tools_ms'),\n modelCalls: integer('model_calls'),\n toolCalls: integer('tool_calls'),\n timings: text('timings', { mode: 'json' }).$type<RunStepTiming[]>(),\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/**\n * Text channels' short-lived state (`@dudousxd/nestjs-agent-channels`), one row per key: the provider\n * message ids already answered, a question waiting for the person's answer, an outcome already\n * relayed. The primary key is the lock a claim takes; `expires_at` is epoch-ms, and past it the row\n * is free again and dead weight for `DrizzleChannelStore.purgeExpired`. Keys longer than 255\n * characters are stored by their SHA-256.\n */\nexport const agentChannelState = sqliteTable(\n 'agent_channel_state',\n {\n key: text('key').primaryKey(),\n value: text('value'),\n expiresAt: integer('expires_at').notNull(),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [index('agent_channel_state_expires_idx').on(table.expiresAt)],\n);\n\n/**\n * Spent confirm tokens (`defineConfirmedTool`), one row per token, keyed by its SHA-256 — the\n * primary key is the lock that makes a confirmation single use across replicas. Only the hash, the\n * actor and the tool are kept, never an argument. `expires_at` is epoch-ms; past it the row is dead\n * weight for `DrizzleConfirmTokenStore.purgeExpired`.\n */\nexport const agentConfirmToken = sqliteTable(\n 'agent_confirm_token',\n {\n hash: text('hash').primaryKey(),\n actorRef: text('actor_ref').notNull(),\n tool: text('tool').notNull(),\n expiresAt: integer('expires_at').notNull(),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [index('agent_confirm_token_expires_idx').on(table.expiresAt)],\n);\n\n/**\n * One row per frame of a run's live stream (`DrizzleTokenStreamSink`), numbered per run from 1 with\n * no gaps. `frame` is one NDJSON line; `null` marks the end, with `error` set when the run failed.\n * `created_at` (epoch-ms) is what the TTL counts from — a run's LAST row.\n */\nexport const agentStreamFrame = sqliteTable(\n 'agent_stream_frame',\n {\n runId: text('run_id').notNull(),\n seq: integer('seq').notNull(),\n frame: text('frame'),\n error: text('error'),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [primaryKey({ columns: [table.runId, table.seq] })],\n);\n\n/** Independent action proposals; decision and execution work commit in one fenced row. */\nexport const agentActionProposal = sqliteTable(\n 'agent_action_proposal',\n {\n id: text('id').primaryKey(),\n scopeKey: text('scope_key').notNull(),\n decision: text('decision').$type<ActionProposal['decision']>().notNull(),\n logicalSort: text('logical_sort').notNull(),\n createFingerprint: text('create_fingerprint').notNull(),\n proposal: text('proposal', { mode: 'json' }).$type<ActionProposal>().notNull(),\n version: integer('version').notNull().default(0),\n executionStatus:\n text('execution_status').$type<NonNullable<ActionProposal['execution']>['status']>(),\n leaseExpiresAt: integer('lease_expires_at'),\n deliveryStatus: text('delivery_status'),\n deliveryLeaseExpiresAt: integer('delivery_lease_expires_at'),\n replacementGroupKey: text('replacement_group_key'),\n outcomeIdKey: text('outcome_id_key'),\n proposalExpiresAt: integer('proposal_expires_at'),\n discoveryIndexVersion: integer('discovery_index_version').notNull().default(0),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [\n index('agent_action_proposal_execution_idx').on(\n table.discoveryIndexVersion,\n table.executionStatus,\n table.leaseExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_expiry_idx').on(\n table.discoveryIndexVersion,\n table.decision,\n table.proposalExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_replacement_idx').on(\n table.scopeKey,\n table.replacementGroupKey,\n table.decision,\n ),\n index('agent_action_proposal_delivery_idx').on(\n table.deliveryStatus,\n table.deliveryLeaseExpiresAt,\n table.createdAt,\n ),\n uniqueIndex('agent_action_proposal_outcome_idx').on(table.outcomeIdKey),\n index('agent_action_proposal_scope_idx').on(table.scopeKey, table.createdAt, table.id),\n ],\n);\n\n/**\n * Personal Agent Protocol (Poppy) conversations (`DrizzlePoppyStore`): who it is with, its status,\n * the User's context and the identity its turns run as (JSON text), and the reader lease\n * (`reader_holder` until `reader_until`, epoch-ms) that lets one replica at a time write a reply.\n * `pruned_seq`: events at or below it were pruned.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConversation = sqliteTable('agent_poppy_conversation', {\n id: text('id').primaryKey(),\n clientId: text('client_id').notNull(),\n userId: text('user_id').notNull(),\n accountRef: text('account_ref'),\n agentName: text('agent_name').notNull(),\n threadId: text('thread_id'),\n parentId: text('parent_id'),\n openDirectId: text('open_direct_id'),\n status: text('status').notNull(),\n responder: text('responder').notNull(),\n context: text('context'),\n activeRunId: text('active_run_id'),\n turnSeq: integer('turn_seq').notNull(),\n grantInfo: text('grant_info'),\n readerHolder: text('reader_holder'),\n readerUntil: integer('reader_until'),\n prunedSeq: integer('pruned_seq').notNull(),\n createdAt: integer('created_at').notNull(),\n updatedAt: integer('updated_at').notNull(),\n});\n\n/**\n * A Poppy conversation's events, append-only, numbered per conversation. The primary key is the\n * position, so two appends racing for one cannot both win; `event_key` (unique per conversation)\n * is what keeps a re-read turn from writing its reply twice. `event` is the event as JSON text.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyEvent = sqliteTable(\n 'agent_poppy_event',\n {\n conversationId: text('conversation_id').notNull(),\n seq: integer('seq').notNull(),\n id: text('id').notNull(),\n type: text('type').notNull(),\n event: text('event').notNull(),\n eventKey: text('event_key'),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.conversationId, table.seq] }),\n uniqueIndex('agent_poppy_event_key_idx').on(table.conversationId, table.eventKey),\n index('agent_poppy_event_id_idx').on(table.conversationId, table.id),\n ],\n);\n\n/**\n * Accepted Poppy messages, one row per (owner, message id) — the primary key is the idempotency lock\n * that makes two deliveries of one message one (§7.3); `response` is what the first got, as JSON.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyMessage = sqliteTable(\n 'agent_poppy_message',\n {\n owner: text('owner').notNull(),\n messageId: text('message_id').notNull(),\n fingerprint: text('fingerprint').notNull(),\n conversationId: text('conversation_id').notNull(),\n response: text('response').notNull(),\n createdAt: integer('created_at').notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.messageId] })],\n);\n\n/**\n * This app's Poppy connections (`DrizzlePoppyConnectionStore`): one per (owner, Company issuer),\n * holding the client state SEALED by the caller — never a token in the clear.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnection = sqliteTable(\n 'agent_poppy_connection',\n {\n owner: text('owner').notNull(),\n issuer: text('issuer').notNull(),\n domain: text('domain').notNull(),\n organization: text('organization').notNull(),\n scope: text('scope').notNull(),\n status: text('status').notNull(),\n state: text('state').notNull(),\n createdAt: integer('created_at').notNull(),\n updatedAt: integer('updated_at').notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.issuer] })],\n);\n\n/**\n * Poppy sign-ins in flight, started by the `connect` tool and completed on the connect page. `actor`\n * is JSON text; `flow` the sealed per-method state.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnect = sqliteTable('agent_poppy_connect', {\n id: text('id').primaryKey(),\n owner: text('owner').notNull(),\n domain: text('domain').notNull(),\n issuer: text('issuer').notNull(),\n organization: text('organization').notNull(),\n scope: text('scope').notNull(),\n actor: text('actor'),\n threadId: text('thread_id'),\n runId: text('run_id'),\n toolCallId: text('tool_call_id'),\n flow: text('flow'),\n status: text('status').notNull(),\n expiresAt: integer('expires_at').notNull(),\n createdAt: integer('created_at').notNull(),\n});\n\n/** The tables this store owns, as one schema object, ready for `drizzle(client, { schema })`. */\nexport const agentSchema = {\n agentActionProposal,\n agentThread,\n agentMessage,\n agentQueuedMessage,\n agentToolCall,\n agentTokenUsage,\n agentGenuiCall,\n agentModelPricing,\n agentRun,\n agentMemory,\n ragIngestionLog,\n agentConfirmToken,\n agentChannelState,\n agentStreamFrame,\n agentPoppyConversation,\n agentPoppyEvent,\n agentPoppyMessage,\n agentPoppyConnection,\n agentPoppyConnect,\n};\n\n/**\n * The database handle the stores take — SQLite, Postgres or MySQL. Defined in `./dialect.js`;\n * re-exported here, where it has always been importable from.\n */\nexport type { AgentDrizzleDb } from './dialect.js';\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 queued message row as Drizzle selects it. */\nexport type AgentQueuedMessageRow = typeof agentQueuedMessage.$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 { type Column, type SQL, getTableName, sql } from 'drizzle-orm';\nimport { getTableConfig as mysqlTableConfig } from 'drizzle-orm/mysql-core';\nimport { getTableConfig as pgTableConfig } from 'drizzle-orm/pg-core';\nimport { getTableConfig as sqliteTableConfig } from 'drizzle-orm/sqlite-core';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentMySqlDb,\n type AgentPgDb,\n agentDialectOf,\n agentTablesFor,\n querySql,\n runSql,\n} from './dialect.js';\n\n/**\n * Creates the agent tables a database lacks, adds the columns and indexes an existing one lacks, and\n * relaxes a column the schema made nullable since (`agent_token_usage.thread_id`: usage recorded\n * outside a conversation) — never drops anything — safe to run on every boot against a shared\n * database. Postgres drops the `NOT NULL` in place, MySQL `MODIFY`s the column, and SQLite, which can\n * do neither, rebuilds that one table (created under a scratch name, rows copied, renamed) inside a\n * savepoint; only a table no other table references is rebuilt, and its indexes come back below. SQLite,\n * Postgres and MySQL alike, with no drizzle-kit and no migration files.\n *\n * The DDL is rendered from the dialect's Drizzle schema ({@link import('./schema.js').agentSchema},\n * {@link import('./schema-pg.js').pgAgentSchema}, {@link import('./schema-mysql.js').mysqlAgentSchema})\n * rather than written out by hand, so the tables this creates are the tables the stores query, column\n * for column, and a column added to a schema later reaches every database that is already running\n * without a list of `ALTER`s to keep in step. A column added later must therefore be nullable or\n * carry a default — an existing table cannot take a `NOT NULL` column without one.\n *\n * On Postgres and MySQL it runs under a cross-replica lock (`pg_advisory_xact_lock`, `get_lock`),\n * held on one connection for the whole run: several replicas booting an empty database at once would\n * otherwise race their `CREATE TABLE IF NOT EXISTS` — which Postgres does not make race-safe — and\n * all but one fail. On Postgres the whole heal is also one transaction, so it lands entirely or not\n * at all.\n */\nexport async function ensureAgentSchema(db: AgentDrizzleDb): Promise<void> {\n const dialect = agentDialectOf(db);\n if (dialect === 'postgres') {\n await (db as AgentPgDb).transaction(async (tx) => {\n await tx.execute(sql.raw(`select pg_advisory_xact_lock(hashtext('${LOCK_NAME}'))`));\n await heal(tx as unknown as AgentDrizzleDb, dialect);\n });\n return;\n }\n if (dialect === 'mysql') {\n await (db as AgentMySqlDb).transaction(async (tx) => {\n // A session lock: taken and released on the transaction's one connection. MySQL's DDL commits\n // implicitly, so this is a pinned connection rather than an atomic heal.\n await tx.execute(sql.raw(`select get_lock('${LOCK_NAME}', 30)`));\n try {\n await heal(tx as unknown as AgentDrizzleDb, dialect);\n } finally {\n await tx.execute(sql.raw(`select release_lock('${LOCK_NAME}')`));\n }\n });\n return;\n }\n await heal(db, dialect);\n}\n\nconst LOCK_NAME = 'nestjs_agent_schema';\n\n/** Table options MySQL needs spelled out: InnoDB for the foreign keys, a case-sensitive collation. */\nconst MYSQL_TABLE_OPTIONS = 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin';\n\ninterface IndexSpec {\n name: string;\n unique: boolean;\n columns: string[];\n}\n\ninterface TableSpec {\n name: string;\n columns: Column[];\n primaryKey: string[];\n foreignKeys: { columns: string[]; table: string; foreignColumns: string[]; onDelete?: string }[];\n indexes: IndexSpec[];\n}\n\n/** One agent table, read off its Drizzle definition in `dialect`. */\nfunction tableSpec(dialect: AgentDialect, table: unknown): TableSpec {\n const config =\n dialect === 'postgres'\n ? pgTableConfig(table as Parameters<typeof pgTableConfig>[0])\n : dialect === 'mysql'\n ? mysqlTableConfig(table as Parameters<typeof mysqlTableConfig>[0])\n : sqliteTableConfig(table as Parameters<typeof sqliteTableConfig>[0]);\n const columns = config.columns as unknown as Column[];\n const compositeKey = config.primaryKeys[0]?.columns.map((column) => column.name);\n return {\n name: config.name,\n columns,\n primaryKey: compositeKey ?? columns.filter((column) => column.primary).map((c) => c.name),\n foreignKeys: config.foreignKeys.map((foreignKey) => {\n const reference = foreignKey.reference();\n return {\n columns: reference.columns.map((column) => column.name),\n table: getTableName(reference.foreignTable),\n foreignColumns: reference.foreignColumns.map((column) => column.name),\n ...(foreignKey.onDelete !== undefined ? { onDelete: foreignKey.onDelete } : {}),\n };\n }),\n indexes: config.indexes.map((index) => ({\n name: String(index.config.name),\n unique: index.config.unique === true,\n columns: (index.config.columns as { name?: string }[]).map((column) => String(column.name)),\n })),\n };\n}\n\nfunction quote(dialect: AgentDialect, identifier: string): string {\n return dialect === 'mysql' ? `\\`${identifier}\\`` : `\"${identifier}\"`;\n}\n\nfunction literal(dialect: AgentDialect, value: unknown): string {\n if (typeof value === 'boolean') {\n return dialect === 'sqlite' ? (value ? '1' : '0') : value ? 'true' : 'false';\n }\n if (typeof value === 'number') return String(value);\n return `'${String(value).replaceAll(\"'\", \"''\")}'`;\n}\n\n/** `name TYPE [NOT NULL] [DEFAULT …]` — no key or reference, which the table states separately. */\nfunction columnDefinition(dialect: AgentDialect, column: Column): string {\n const parts = [quote(dialect, column.name), column.getSQLType()];\n if (column.notNull) parts.push('NOT NULL');\n if (column.hasDefault && column.default !== undefined) {\n parts.push(`DEFAULT ${literal(dialect, column.default)}`);\n }\n return parts.join(' ');\n}\n\nfunction createTableSql(dialect: AgentDialect, spec: TableSpec): string {\n const q = (identifier: string) => quote(dialect, identifier);\n const lines = spec.columns.map((column) => columnDefinition(dialect, column));\n lines.push(`PRIMARY KEY (${spec.primaryKey.map(q).join(', ')})`);\n for (const foreignKey of spec.foreignKeys) {\n lines.push(\n `FOREIGN KEY (${foreignKey.columns.map(q).join(', ')}) REFERENCES ${q(foreignKey.table)} (${foreignKey.foreignColumns.map(q).join(', ')})${foreignKey.onDelete !== undefined ? ` ON DELETE ${foreignKey.onDelete.toUpperCase()}` : ''}`,\n );\n }\n const options = dialect === 'mysql' ? ` ${MYSQL_TABLE_OPTIONS}` : '';\n return `CREATE TABLE IF NOT EXISTS ${q(spec.name)} (\\n ${lines.join(',\\n ')}\\n)${options}`;\n}\n\n/** The DDL that creates the agent tables in `dialect`, in dependency order. Indexes included. */\nexport function agentSchemaDdl(dialect: AgentDialect): string[] {\n const statements: string[] = [];\n for (const spec of specs(dialect)) {\n statements.push(createTableSql(dialect, spec));\n for (const index of spec.indexes) {\n statements.push(createIndexSql(dialect, spec.name, index));\n }\n }\n return statements;\n}\n\nfunction createIndexSql(dialect: AgentDialect, table: string, index: IndexSpec): string {\n const q = (identifier: string) => quote(dialect, identifier);\n // MySQL has no `IF NOT EXISTS` on an index; `heal` asks first there.\n const guard = dialect === 'mysql' ? '' : 'IF NOT EXISTS ';\n return `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${guard}${q(index.name)} ON ${q(table)} (${index.columns.map(q).join(', ')})`;\n}\n\n/** Every agent table in `dialect`, parents before the children that reference them. */\nfunction specs(dialect: AgentDialect): TableSpec[] {\n const all = Object.values(agentTablesFor(dialect)).map((table) => tableSpec(dialect, table));\n const ordered: TableSpec[] = [];\n const placed = new Set<string>();\n while (ordered.length < all.length) {\n const ready = all.filter(\n (spec) =>\n !placed.has(spec.name) &&\n spec.foreignKeys.every((key) => key.table === spec.name || placed.has(key.table)),\n );\n if (ready.length === 0) throw new Error('agent schema: circular foreign keys');\n for (const spec of ready) {\n ordered.push(spec);\n placed.add(spec.name);\n }\n }\n return ordered;\n}\n\nasync function existingColumns(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n table: string,\n): Promise<Set<string>> {\n return new Set((await columnNullability(db, dialect, table)).keys());\n}\n\n/** Each column the table has, and whether the database lets it hold NULL. */\nasync function columnNullability(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n table: string,\n): Promise<Map<string, boolean>> {\n if (dialect === 'sqlite') {\n const rows = await querySql<{ name: string; notnull: number }>(\n db,\n dialect,\n sql.raw(`PRAGMA table_info(\"${table}\")`),\n );\n return new Map(rows.map((row) => [String(row.name), Number(row.notnull) === 0]));\n }\n const rows = await querySql<{ name: string; nullable: string }>(\n db,\n dialect,\n sql`select column_name as name, is_nullable as nullable from information_schema.columns where table_schema = ${sql.raw(dialect === 'mysql' ? 'database()' : 'current_schema()')} and table_name = ${table}`,\n );\n return new Map(\n rows.map((row) => [\n String(row.name ?? (row as { NAME?: string }).NAME),\n String(row.nullable ?? (row as { NULLABLE?: string }).NULLABLE).toUpperCase() === 'YES',\n ]),\n );\n}\n\n/**\n * Let `column` hold NULL. In place on Postgres and MySQL; on SQLite the table is rebuilt in its\n * current shape under a scratch name, its rows copied, and renamed over the old one, inside a\n * savepoint — refused for a table another agent table references, whose foreign keys a rebuild\n * would break.\n */\nasync function relaxNotNull(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n spec: TableSpec,\n column: Column,\n all: readonly TableSpec[],\n): Promise<void> {\n const q = (identifier: string) => quote(dialect, identifier);\n if (dialect === 'postgres') {\n await runSql(\n db,\n dialect,\n sql.raw(`ALTER TABLE ${q(spec.name)} ALTER COLUMN ${q(column.name)} DROP NOT NULL`),\n );\n return;\n }\n if (dialect === 'mysql') {\n await runSql(\n db,\n dialect,\n sql.raw(`ALTER TABLE ${q(spec.name)} MODIFY ${columnDefinition(dialect, column)}`),\n );\n return;\n }\n if (\n all.some((other) => other.foreignKeys.some((key) => key.table === spec.name && other !== spec))\n ) {\n throw new Error(\n `agent schema: cannot make ${spec.name}.${column.name} nullable on SQLite — other tables reference ${spec.name}`,\n );\n }\n const scratch = `${spec.name}__rebuild`;\n const present = [...(await columnNullability(db, dialect, spec.name)).keys()];\n const list = present.map(q).join(', ');\n await runSql(db, dialect, sql.raw('SAVEPOINT agent_schema_rebuild'));\n try {\n await runSql(db, dialect, sql.raw(`DROP TABLE IF EXISTS ${q(scratch)}`));\n await runSql(db, dialect, sql.raw(createTableSql(dialect, { ...spec, name: scratch })));\n await runSql(\n db,\n dialect,\n sql.raw(`INSERT INTO ${q(scratch)} (${list}) SELECT ${list} FROM ${q(spec.name)}`),\n );\n await runSql(db, dialect, sql.raw(`DROP TABLE ${q(spec.name)}`));\n await runSql(db, dialect, sql.raw(`ALTER TABLE ${q(scratch)} RENAME TO ${q(spec.name)}`));\n await runSql(db, dialect, sql.raw('RELEASE SAVEPOINT agent_schema_rebuild'));\n } catch (error) {\n await runSql(db, dialect, sql.raw('ROLLBACK TO SAVEPOINT agent_schema_rebuild')).catch(\n () => undefined,\n );\n await runSql(db, dialect, sql.raw('RELEASE SAVEPOINT agent_schema_rebuild')).catch(\n () => undefined,\n );\n throw error;\n }\n}\n\nasync function indexExists(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n table: string,\n index: string,\n): Promise<boolean> {\n let query: SQL;\n if (dialect === 'sqlite') {\n query = sql`select name from sqlite_master where type = 'index' and name = ${index}`;\n } else if (dialect === 'postgres') {\n query = sql`select indexname as name from pg_indexes where schemaname = current_schema() and indexname = ${index}`;\n } else {\n query = sql`select index_name as name from information_schema.statistics where table_schema = database() and table_name = ${table} and index_name = ${index}`;\n }\n return (await querySql(db, dialect, query)).length > 0;\n}\n\nasync function heal(db: AgentDrizzleDb, dialect: AgentDialect): Promise<void> {\n const all = specs(dialect);\n for (const spec of all) {\n await runSql(db, dialect, sql.raw(createTableSql(dialect, spec)));\n // `CREATE TABLE IF NOT EXISTS` is inert against a table that is already there, so a column the\n // schema gained since is added here. Asked, not attempted-and-swallowed: a swallowed error cannot\n // tell \"already there\" from \"the ALTER is malformed\".\n const present = await existingColumns(db, dialect, spec.name);\n for (const column of spec.columns) {\n if (!present.has(column.name)) {\n await runSql(\n db,\n dialect,\n sql.raw(\n `ALTER TABLE ${quote(dialect, spec.name)} ADD COLUMN ${columnDefinition(dialect, column)}`,\n ),\n );\n }\n }\n // A column the schema made nullable since it was created. Primary-key columns are left alone:\n // drizzle reports them nullable on some dialects, and none of them ever relaxes.\n const nullable = await columnNullability(db, dialect, spec.name);\n for (const column of spec.columns) {\n if (column.notNull || spec.primaryKey.includes(column.name)) continue;\n if (nullable.get(column.name) === false) {\n await relaxNotNull(db, dialect, spec, column, all);\n }\n }\n for (const index of spec.indexes) {\n if (!(await indexExists(db, dialect, spec.name, index.name))) {\n await runSql(db, dialect, sql.raw(createIndexSql(dialect, spec.name, index)));\n }\n }\n }\n}\n","import { type SQL, type TablesRelationalConfig, is } from 'drizzle-orm';\nimport {\n MySqlDatabase,\n type MySqlQueryResultHKT,\n type PreparedQueryHKTBase,\n} from 'drizzle-orm/mysql-core';\nimport { PgDatabase, type PgQueryResultHKT } from 'drizzle-orm/pg-core';\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';\nimport { mysqlAgentSchema } from './schema-mysql.js';\nimport { pgAgentSchema } from './schema-pg.js';\nimport { agentSchema } from './schema.js';\n\n/** The SQL dialects the stores in this package run on. */\nexport type AgentDialect = 'sqlite' | 'postgres' | 'mysql';\n\n/** A Drizzle SQLite database, any driver (better-sqlite3, libsql, D1, …), sync or async. */\nexport type AgentSqliteDb = BaseSQLiteDatabase<\n 'sync' | 'async',\n unknown,\n Record<string, unknown>,\n TablesRelationalConfig\n>;\n/** A Drizzle Postgres database, any driver (node-postgres, postgres.js, Neon, PGlite, …). */\nexport type AgentPgDb = PgDatabase<\n PgQueryResultHKT,\n Record<string, unknown>,\n TablesRelationalConfig\n>;\n/** A Drizzle MySQL database (mysql2, PlanetScale, …). */\nexport type AgentMySqlDb = MySqlDatabase<\n MySqlQueryResultHKT,\n PreparedQueryHKTBase,\n Record<string, unknown>,\n TablesRelationalConfig\n>;\n\n/**\n * The database handle every store here takes: a Drizzle database on SQLite, Postgres or MySQL. The\n * host owns the connection and passes the `drizzle(...)` instance in; the store tells the dialect\n * from the handle itself, and finds its tables in that dialect's schema\n * ({@link import('./schema.js').agentSchema}, {@link pgAgentSchema}, {@link mysqlAgentSchema}).\n */\nexport type AgentDrizzleDb = AgentSqliteDb | AgentPgDb | AgentMySqlDb;\n\n/** Which dialect a Drizzle handle speaks. */\nexport function agentDialectOf(db: AgentDrizzleDb): AgentDialect {\n if (is(db, PgDatabase)) return 'postgres';\n if (is(db, MySqlDatabase)) return 'mysql';\n return 'sqlite';\n}\n\n/** The SQLite tables, which every dialect's table set mirrors key for key and column for column. */\nexport type AgentTables = typeof agentSchema;\n\n/**\n * The agent tables in `dialect`, typed as the SQLite set.\n *\n * The three schemas declare the same property names over the same column names, and a Drizzle query\n * builder runs whatever table it is handed: the column objects carry their own driver mapping (a\n * `Date` becomes epoch-ms on SQLite, ISO on Postgres, `datetime` text on MySQL). So the stores are\n * written once, against the SQLite types, and run on the table set of the handle's dialect. The few\n * places the dialects really differ — `RETURNING`, upserts, raw statements — go through the helpers\n * below instead.\n */\nexport function agentTablesFor(dialect: AgentDialect): AgentTables {\n if (dialect === 'postgres') return pgAgentSchema as unknown as AgentTables;\n if (dialect === 'mysql') return mysqlAgentSchema as unknown as AgentTables;\n return agentSchema;\n}\n\n/**\n * The handle as the SQLite query-builder type the stores are written against. A view for the type\n * checker only — see {@link agentTablesFor}; nothing SQLite-only (`run`/`all`/`get`, `returning` on\n * MySQL) may be called through it outside the helpers here.\n */\nexport function asBuilder(db: AgentDrizzleDb): AgentSqliteDb {\n return db as AgentSqliteDb;\n}\n\n/** A write statement that can be awaited and, outside MySQL, asked to `RETURNING` a column. */\ninterface Returnable {\n returning(fields: Record<string, unknown>): PromiseLike<unknown[]>;\n}\n\n/**\n * How many rows an UPDATE/DELETE/INSERT touched. `RETURNING` on SQLite and Postgres — the one answer\n * every driver of those gives alike — and the result header's `affectedRows` on MySQL, which has no\n * `RETURNING`.\n *\n * MySQL counts MATCHED rows for an update only while the connection has `FOUND_ROWS` (mysql2's\n * default); without it, an update that writes the value already there reports 0. A caller for whom\n * that difference matters re-reads the row rather than trusting a 0.\n */\nexport async function affectedRows(\n dialect: AgentDialect,\n statement: Returnable & PromiseLike<unknown>,\n column: unknown,\n): Promise<number> {\n if (dialect !== 'mysql') {\n return (await statement.returning({ affected: column })).length;\n }\n return mysqlAffectedRows(await statement);\n}\n\n/** `affectedRows` off a MySQL driver's result (mysql2's `[ResultSetHeader, fields]`, or a header). */\nexport function mysqlAffectedRows(result: unknown): number {\n const header = Array.isArray(result) ? result[0] : result;\n const counts = header as { affectedRows?: unknown; rowsAffected?: unknown } | null | undefined;\n // mysql2 says `affectedRows`; PlanetScale's serverless driver says `rowsAffected`.\n const count = counts?.affectedRows ?? counts?.rowsAffected;\n return typeof count === 'number' ? count : 0;\n}\n\n/** Run a raw statement, discarding its result. */\nexport async function runSql(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n statement: SQL,\n): Promise<void> {\n if (dialect === 'sqlite') {\n await (db as AgentSqliteDb).run(statement);\n return;\n }\n if (dialect === 'postgres') {\n await (db as AgentPgDb).execute(statement);\n return;\n }\n await (db as AgentMySqlDb).execute(statement);\n}\n\n/** Run a raw query and return its rows, whatever shape the driver hands them back in. */\nexport async function querySql<T>(\n db: AgentDrizzleDb,\n dialect: AgentDialect,\n statement: SQL,\n): Promise<T[]> {\n if (dialect === 'sqlite') {\n return (db as AgentSqliteDb).all<T>(statement);\n }\n const result: unknown =\n dialect === 'postgres'\n ? await (db as AgentPgDb).execute(statement)\n : await (db as AgentMySqlDb).execute(statement);\n if (dialect === 'mysql') {\n // mysql2: [rows, fields]\n return (Array.isArray(result) ? result[0] : []) as T[];\n }\n // node-postgres: { rows }; postgres.js and friends: the rows themselves\n return (Array.isArray(result) ? result : ((result as { rows?: T[] }).rows ?? [])) as T[];\n}\n\n/**\n * Did this write lose a race it can simply retry? A duplicate on a primary-key or unique index —\n * Postgres `23505`, MySQL `ER_DUP_ENTRY` (1062), SQLite's constraint codes — or, on MySQL, being the\n * deadlock victim (`ER_LOCK_DEADLOCK`, 1213): two `INSERT … SELECT MAX(seq) + 1` into one run take\n * gap locks on the same range, and InnoDB settles that by rolling one of them back rather than by a\n * duplicate key. Walks the `cause` chain, since Drizzle wraps the driver's error.\n */\nexport function isUniqueViolation(error: unknown): boolean {\n for (let current = error; current !== null && typeof current === 'object'; ) {\n const { code, errno } = current as { code?: unknown; errno?: unknown };\n if (\n code === '23505' ||\n code === 'ER_DUP_ENTRY' ||\n errno === 1062 ||\n code === 'ER_LOCK_DEADLOCK' ||\n errno === 1213 ||\n (typeof code === 'string' && code.startsWith('SQLITE_CONSTRAINT'))\n ) {\n return true;\n }\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\n/** An insert builder, as far as an upsert needs one. */\ninterface Upsertable {\n onConflictDoUpdate(config: {\n target: unknown;\n set: Record<string, unknown>;\n }): PromiseLike<unknown>;\n}\n\n/**\n * Insert, or update `set` on the row already holding `target`'s key: `ON CONFLICT … DO UPDATE` on\n * SQLite and Postgres, `ON DUPLICATE KEY UPDATE` on MySQL — which keys off EVERY unique index of the\n * table rather than a named target, so `target` must be the table's only key the row can collide on.\n */\nexport function upsert(\n dialect: AgentDialect,\n insert: Upsertable,\n target: unknown,\n set: Record<string, unknown>,\n): PromiseLike<unknown> {\n if (dialect === 'mysql') {\n return (\n insert as unknown as {\n onDuplicateKeyUpdate(config: { set: Record<string, unknown> }): PromiseLike<unknown>;\n }\n ).onDuplicateKeyUpdate({ set });\n }\n return insert.onConflictDoUpdate({ target, set });\n}\n","import { canonicalActionProposalJson } from '@dudousxd/nestjs-agent-core';\nimport type {\n ActionProposal,\n Actor,\n AgentUiComponent,\n MemoryOrigin,\n MessageAttachment,\n MessageFeedback,\n MessageRole,\n MessageUsage,\n PageContext,\n QueuePause,\n ToolCallRequest,\n ToolCallStatus,\n ToolConfirmation,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport type {\n AgentHostContext,\n CostSource,\n GenuiErrorCategory,\n GenuiToolMarker,\n GenuiValidity,\n RecordGenuiCallInput,\n RunStepTiming,\n} from '@dudousxd/nestjs-agent-core';\nimport type { UiCapabilities } from '@dudousxd/nestjs-agent-core/genui';\nimport {\n bigint,\n boolean,\n customType,\n datetime,\n double,\n index,\n int,\n json,\n longtext,\n mysqlTable,\n primaryKey,\n uniqueIndex,\n varchar,\n} from 'drizzle-orm/mysql-core';\nimport type { AgentRunStatus, RagIngestionStatus } from './schema.js';\n\n/**\n * The agent tables for MySQL (8.0+) — the same tables, columns and JS property names as the SQLite\n * {@link import('./schema.js').agentSchema}, in MySQL types: `json` for the JSON columns,\n * `datetime(3)` for the timestamps (UTC, read back as `Date` — MySQL's bare `datetime` is whole\n * seconds), `longtext` for anything a model or a stack trace can make long (`text` stops at 64 KB),\n * `varchar(255)` for keys and short labels (an index needs a bounded column), `bigint` for the\n * epoch-ms counters, `double` for prices and costs. `ensureAgentSchema` creates the tables\n * `utf8mb4_bin`, so ids and actor refs compare case-sensitively, as on Postgres and SQLite. Pass it to\n * `drizzle(pool, { schema: mysqlAgentSchema, mode: 'default' })`.\n */\nconst ts = (name: string) => datetime(name, { mode: 'date', fsp: 3 });\n/** A key or short label: bounded, so it can be indexed. */\nconst key = (name: string) => varchar(name, { length: 255 });\n\nexport const agentThread = mysqlTable(\n 'agent_thread',\n {\n id: key('id').primaryKey(),\n actorRef: key('actor_ref').notNull(),\n tenantRef: key('tenant_ref'),\n title: key('title').notNull(),\n transient: boolean('transient').notNull().default(false),\n activeStreamId: key('active_stream_id'),\n defaultAgent: key('default_agent'),\n model: key('model'),\n /** The persona a send on this thread runs under when it names none; `null` → the agent's default. */\n persona: key('persona'),\n queuePause: json('queue_pause').$type<QueuePause>(),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n deletedAt: ts('deleted_at'),\n },\n (table) => [\n index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt),\n // `ownerOfActiveStream` reads by run id on every stream attach and reconnect.\n index('agent_thread_active_stream_idx').on(table.activeStreamId),\n ],\n);\n\nexport const agentMessage = mysqlTable(\n 'agent_message',\n {\n id: key('id').primaryKey(),\n threadId: key('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n role: key('role').$type<MessageRole>().notNull(),\n actionProposalOutcome: longtext('action_proposal_outcome'),\n content: longtext('content').notNull(),\n toolCalls: json('tool_calls').$type<ToolCallRequest[]>(),\n toolResults: json('tool_results').$type<ToolResult[]>(),\n attachments: json('attachments').$type<MessageAttachment[]>(),\n followUps: json('follow_ups').$type<string[]>(),\n usage: json('usage').$type<MessageUsage>(),\n agentName: key('agent_name'),\n /** The persona the turn that wrote this message ran under; `null` → none. */\n persona: key('persona'),\n runId: key('run_id'),\n reasoning: longtext('reasoning'),\n reasoningMs: int('reasoning_ms'),\n ui: json('ui').$type<AgentUiComponent[]>(),\n feedback: json('feedback').$type<MessageFeedback>(),\n seq: int('seq'),\n createdAt: ts('created_at').notNull(),\n },\n (table) => [\n index('agent_message_thread_created_idx').on(table.threadId, table.createdAt),\n // Transcript reads order a thread's messages by `seq`.\n index('agent_message_thread_seq_idx').on(table.threadId, table.seq),\n ],\n);\n\nexport const agentToolCall = mysqlTable(\n 'agent_tool_call',\n {\n proposalId: key('proposal_id'),\n id: key('id').primaryKey(),\n messageId: key('message_id')\n .notNull()\n .references(() => agentMessage.id, { onDelete: 'cascade' }),\n toolName: key('tool_name').notNull(),\n toolType: key('tool_type').$type<ToolKind>().notNull(),\n input: json('input'),\n output: json('output'),\n status: key('status').$type<ToolCallStatus>().notNull(),\n executedByRef: key('executed_by_ref'),\n executionMs: int('execution_ms'),\n error: longtext('error'),\n createdAt: ts('created_at').notNull(),\n executedAt: ts('executed_at'),\n runId: key('run_id'),\n confirmation: json('confirmation').$type<ToolConfirmation>(),\n approver: key('approver'),\n expiresAt: ts('expires_at'),\n remember: boolean('remember'),\n decidedVia: key('decided_via'),\n },\n (table) => [\n index('agent_tool_call_message_idx').on(table.messageId),\n // The approvals inbox: `pending_approval`, oldest first.\n index('agent_tool_call_status_created_idx').on(table.status, table.createdAt),\n index('agent_tool_call_run_idx').on(table.runId),\n index('agent_tool_call_created_idx').on(table.createdAt),\n ],\n);\n\nexport const agentQueuedMessage = mysqlTable(\n 'agent_queued_message',\n {\n uiCapabilities: json('ui_capabilities').$type<UiCapabilities>(),\n hostContext: json('host_context').$type<AgentHostContext>(),\n id: key('id').primaryKey(),\n threadId: key('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actor: json('actor').$type<Actor>().notNull(),\n content: longtext('content').notNull(),\n attachments: json('attachments').$type<MessageAttachment[]>(),\n agentName: key('agent_name'),\n /** The persona the send resolved — what the message starts under. */\n persona: key('persona'),\n model: key('model'),\n pageContext: json('page_context').$type<PageContext>(),\n interrupt: boolean('interrupt').notNull().default(false),\n position: int('position').notNull(),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [index('agent_queued_message_thread_position_idx').on(table.threadId, table.position)],\n);\n\nexport const agentTokenUsage = mysqlTable(\n 'agent_token_usage',\n {\n id: key('id').primaryKey(),\n threadId: key('thread_id')\n // NULL for usage recorded outside any conversation (`AgentService.recordUsage`).\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: key('actor_ref').notNull(),\n messageId: key('message_id'),\n modelId: key('model_id').notNull(),\n purpose: key('purpose').$type<UsagePurpose>().notNull(),\n inputTokens: int('input_tokens').notNull(),\n outputTokens: int('output_tokens').notNull(),\n cacheWriteTokens: int('cache_write_tokens'),\n cacheReadTokens: int('cache_read_tokens'),\n costUsd: double('cost_usd'),\n /** Where `cost_usd` came from: `'provider'` (reported) or `'estimate'` (tokens × the price row); null on rows from before it existed (reported). */\n costSource: key('cost_source').$type<CostSource>(),\n /** The run the row belongs to. */\n runId: key('run_id'),\n /** What the spend was for: `agent:<name>` for an agent turn, the app's own otherwise; null → `agent`. */\n feature: key('feature'),\n provider: key('provider'),\n tenantRef: key('tenant_ref'),\n /** Units a row bills by when they are not tokens. */\n audioSeconds: double('audio_seconds'),\n characters: bigint('characters', { mode: 'number' }),\n requests: int('requests'),\n /** The caller's own JSON, never read by the library. */\n metadata: json('metadata').$type<Record<string, unknown>>(),\n /** `false` keeps the row out of the agent's quota windows (`recordUsage({ countsTowardsQuota: false })`). */\n countsTowardsQuota: boolean('counts_towards_quota').notNull().default(true),\n createdAt: ts('created_at').notNull(),\n },\n (table) => [\n index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt),\n index('agent_token_usage_created_idx').on(table.createdAt),\n index('agent_token_usage_thread_idx').on(table.threadId),\n index('agent_token_usage_feature_created_idx').on(table.feature, table.createdAt),\n // `quota.per: 'tenant' | 'actor-in-tenant'` sums a tenant's window.\n index('agent_token_usage_tenant_created_idx').on(table.tenantRef, table.createdAt),\n ],\n);\n\n/**\n * Generative-UI telemetry (`AgentStore.recordGenuiCalls`): one row per UI tool call, keyed by the\n * tool call's id, so a replayed record replaces rather than duplicates. Metadata only — `payload`\n * (the call's arguments) is filled solely when the tool samples payloads. `created_at` is epoch-ms.\n */\nexport const agentGenuiCall = mysqlTable(\n 'agent_genui_call',\n {\n id: key('id').primaryKey(),\n runId: key('run_id').notNull(),\n threadId: key('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: key('actor_ref').notNull(),\n agentName: key('agent_name'),\n step: int('step').notNull(),\n toolName: key('tool_name').notNull(),\n channel: key('channel').notNull(),\n mode: key('mode').$type<GenuiToolMarker['mode']>().notNull(),\n modelId: key('model_id').notNull(),\n attempt: int('attempt').notNull(),\n outcome: key('outcome').$type<RecordGenuiCallInput['outcome']>().notNull(),\n validity: key('validity').$type<GenuiValidity>().notNull(),\n errorCategory: key('error_category').$type<GenuiErrorCategory>(),\n errorMessage: longtext('error_message'),\n inputTokens: int('input_tokens').notNull(),\n outputTokens: int('output_tokens').notNull(),\n costUsd: double('cost_usd'),\n costSource: varchar('cost_source', { length: 16 }).$type<CostSource>(),\n firstFrameMs: bigint('first_frame_ms', { mode: 'number' }),\n completeFrameMs: bigint('complete_frame_ms', { mode: 'number' }),\n payloadBytes: int('payload_bytes').notNull(),\n payload: longtext('payload'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n index('agent_genui_call_created_idx').on(table.createdAt),\n index('agent_genui_call_run_idx').on(table.runId),\n ],\n);\n\nexport const agentModelPricing = mysqlTable('agent_model_pricing', {\n id: key('id').primaryKey(),\n modelId: key('model_id').notNull(),\n inputPricePer1m: double('input_price_per_1m').notNull(),\n outputPricePer1m: double('output_price_per_1m').notNull(),\n cacheWritePricePer1m: double('cache_write_price_per_1m'),\n cacheReadPricePer1m: double('cache_read_price_per_1m'),\n effectiveFrom: ts('effective_from').notNull(),\n isCurrent: boolean('is_current').notNull(),\n});\n\nexport const agentRun = mysqlTable(\n 'agent_run',\n {\n id: key('id').primaryKey(),\n threadId: key('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: key('actor_ref').notNull(),\n agentName: key('agent_name'),\n status: key('status').$type<AgentRunStatus>().notNull(),\n durationMs: int('duration_ms'),\n /** Turn start to the first `text` frame; null for a run that streamed none or did not complete. */\n ttftMs: int('ttft_ms'),\n /** The run's known spend (the sum of its model calls with a known cost); null when none had one. */\n costUsd: double('cost_usd'),\n /** The model the run's last model call resolved to. */\n modelId: key('model_id'),\n errorCode: key('error_code'),\n errorMessage: longtext('error_message'),\n retries: int('retries').notNull().default(0),\n startedAt: ts('started_at').notNull(),\n settledAt: ts('settled_at'),\n promptHash: key('prompt_hash'),\n parentRunId: key('parent_run_id'),\n /** Enqueue → body start (ms); null when not read. */\n queueMs: int('queue_ms'),\n /** Where the completed run's time went: model and tool totals, counts, and the per-step list. */\n modelMs: int('model_ms'),\n toolsMs: int('tools_ms'),\n modelCalls: int('model_calls'),\n toolCalls: int('tool_calls'),\n timings: json('timings').$type<RunStepTiming[]>(),\n },\n (table) => [index('agent_run_started_idx').on(table.startedAt)],\n);\n\nexport const agentMemory = mysqlTable(\n 'agent_memory',\n {\n id: key('id').primaryKey(),\n scope: key('scope').notNull(),\n key: key('key').notNull(),\n text: longtext('text').notNull(),\n originAuthor: key('origin_author').$type<MemoryOrigin['author']>().notNull(),\n originThreadId: key('origin_thread_id'),\n originRunId: key('origin_run_id'),\n originActorRef: key('origin_actor_ref'),\n pinned: boolean('pinned').notNull().default(false),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [uniqueIndex('agent_memory_scope_key_uq').on(table.scope, table.key)],\n);\n\nexport const ragIngestionLog = mysqlTable(\n 'rag_ingestion_log',\n {\n documentId: key('document_id').primaryKey(),\n status: key('status').$type<RagIngestionStatus>().notNull(),\n collection: key('collection'),\n ownerType: key('owner_type'),\n ownerId: key('owner_id'),\n source: longtext('source'),\n mimeType: key('mime_type'),\n size: bigint('size', { mode: 'number' }),\n chunks: int('chunks'),\n reason: key('reason'),\n error: longtext('error'),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [index('rag_ingestion_log_collection_idx').on(table.collection, table.updatedAt)],\n);\n\n/**\n * Text channels' short-lived state (`@dudousxd/nestjs-agent-channels`), one row per key: the provider\n * message ids already answered, a question waiting for the person's answer, an outcome already\n * relayed. The primary key is the lock a claim takes; `expires_at` is epoch-ms, and past it the row\n * is free again and dead weight for `DrizzleChannelStore.purgeExpired`. Keys longer than 255\n * characters are stored by their SHA-256.\n */\nexport const agentChannelState = mysqlTable(\n 'agent_channel_state',\n {\n key: key('key').primaryKey(),\n value: longtext('value'),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [index('agent_channel_state_expires_idx').on(table.expiresAt)],\n);\n\nexport const agentConfirmToken = mysqlTable(\n 'agent_confirm_token',\n {\n hash: key('hash').primaryKey(),\n actorRef: key('actor_ref').notNull(),\n tool: key('tool').notNull(),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [index('agent_confirm_token_expires_idx').on(table.expiresAt)],\n);\n\nexport const agentStreamFrame = mysqlTable(\n 'agent_stream_frame',\n {\n runId: key('run_id').notNull(),\n seq: int('seq').notNull(),\n frame: longtext('frame'),\n error: longtext('error'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.runId, table.seq] })],\n);\n\n/** JSON text preserves valid JSON strings that a native JSON column cannot represent. */\nconst proposalJson = customType<{ data: ActionProposal; driverData: string }>({\n dataType: () => 'longtext',\n toDriver: (value) => canonicalActionProposalJson(value),\n fromDriver: (value) => JSON.parse(value) as ActionProposal,\n});\n\n/** Independent action proposals; decision and execution work commit in one fenced row. */\nexport const agentActionProposal = mysqlTable(\n 'agent_action_proposal',\n {\n id: key('id').primaryKey(),\n scopeKey: key('scope_key').notNull(),\n decision: key('decision').$type<ActionProposal['decision']>().notNull(),\n logicalSort: varchar('logical_sort', { length: 1020 }).notNull(),\n createFingerprint: longtext('create_fingerprint').notNull(),\n proposal: proposalJson('proposal').notNull(),\n version: bigint('version', { mode: 'number' }).notNull().default(0),\n executionStatus:\n key('execution_status').$type<NonNullable<ActionProposal['execution']>['status']>(),\n leaseExpiresAt: bigint('lease_expires_at', { mode: 'number' }),\n deliveryStatus: key('delivery_status'),\n deliveryLeaseExpiresAt: bigint('delivery_lease_expires_at', { mode: 'number' }),\n replacementGroupKey: key('replacement_group_key'),\n outcomeIdKey: key('outcome_id_key'),\n proposalExpiresAt: bigint('proposal_expires_at', { mode: 'number' }),\n discoveryIndexVersion: bigint('discovery_index_version', { mode: 'number' })\n .notNull()\n .default(0),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n index('agent_action_proposal_execution_idx').on(\n table.discoveryIndexVersion,\n table.executionStatus,\n table.leaseExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_expiry_idx').on(\n table.discoveryIndexVersion,\n table.decision,\n table.proposalExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_replacement_idx').on(\n table.scopeKey,\n table.replacementGroupKey,\n table.decision,\n ),\n index('agent_action_proposal_delivery_idx').on(\n table.deliveryStatus,\n table.deliveryLeaseExpiresAt,\n table.createdAt,\n ),\n uniqueIndex('agent_action_proposal_outcome_idx').on(table.outcomeIdKey),\n index('agent_action_proposal_scope_idx').on(table.scopeKey, table.createdAt, table.id),\n ],\n);\n\n/**\n * Personal Agent Protocol (Poppy) conversations (`DrizzlePoppyStore`): who it is with, its status,\n * the User's context and the identity its turns run as (JSON text), and the reader lease\n * (`reader_holder` until `reader_until`, epoch-ms) that lets one replica at a time write a reply.\n * `pruned_seq`: events at or below it were pruned.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConversation = mysqlTable('agent_poppy_conversation', {\n id: key('id').primaryKey(),\n clientId: varchar('client_id', { length: 2048 }).notNull(),\n userId: key('user_id').notNull(),\n accountRef: key('account_ref'),\n agentName: key('agent_name').notNull(),\n threadId: key('thread_id'),\n parentId: key('parent_id'),\n openDirectId: key('open_direct_id'),\n status: key('status').notNull(),\n responder: key('responder').notNull(),\n context: longtext('context'),\n activeRunId: key('active_run_id'),\n turnSeq: bigint('turn_seq', { mode: 'number' }).notNull(),\n grantInfo: longtext('grant_info'),\n readerHolder: key('reader_holder'),\n readerUntil: bigint('reader_until', { mode: 'number' }),\n prunedSeq: bigint('pruned_seq', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),\n});\n\n/**\n * A Poppy conversation's events, append-only, numbered per conversation. The primary key is the\n * position, so two appends racing for one cannot both win; `event_key` (unique per conversation)\n * is what keeps a re-read turn from writing its reply twice. `event` is the event as JSON text.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyEvent = mysqlTable(\n 'agent_poppy_event',\n {\n conversationId: key('conversation_id').notNull(),\n seq: bigint('seq', { mode: 'number' }).notNull(),\n id: key('id').notNull(),\n type: key('type').notNull(),\n event: longtext('event').notNull(),\n eventKey: key('event_key'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.conversationId, table.seq] }),\n uniqueIndex('agent_poppy_event_key_idx').on(table.conversationId, table.eventKey),\n index('agent_poppy_event_id_idx').on(table.conversationId, table.id),\n ],\n);\n\n/**\n * Accepted Poppy messages, one row per (owner, message id) — the primary key is the idempotency lock\n * that makes two deliveries of one message one (§7.3); `response` is what the first got, as JSON.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyMessage = mysqlTable(\n 'agent_poppy_message',\n {\n owner: key('owner').notNull(),\n messageId: key('message_id').notNull(),\n fingerprint: key('fingerprint').notNull(),\n conversationId: key('conversation_id').notNull(),\n response: longtext('response').notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.messageId] })],\n);\n\n/**\n * This app's Poppy connections (`DrizzlePoppyConnectionStore`): one per (owner, Company issuer),\n * holding the client state SEALED by the caller — never a token in the clear.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnection = mysqlTable(\n 'agent_poppy_connection',\n {\n owner: key('owner').notNull(),\n issuer: varchar('issuer', { length: 512 }).notNull(),\n domain: key('domain').notNull(),\n organization: key('organization').notNull(),\n scope: longtext('scope').notNull(),\n status: key('status').notNull(),\n state: longtext('state').notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.issuer] })],\n);\n\n/**\n * Poppy sign-ins in flight, started by the `connect` tool and completed on the connect page. `actor`\n * is JSON text; `flow` the sealed per-method state.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnect = mysqlTable('agent_poppy_connect', {\n id: key('id').primaryKey(),\n owner: key('owner').notNull(),\n domain: key('domain').notNull(),\n issuer: varchar('issuer', { length: 512 }).notNull(),\n organization: key('organization').notNull(),\n scope: longtext('scope').notNull(),\n actor: longtext('actor'),\n threadId: key('thread_id'),\n runId: key('run_id'),\n toolCallId: key('tool_call_id'),\n flow: longtext('flow'),\n status: key('status').notNull(),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n});\n\n/** Every agent table, for `drizzle(pool, { schema: mysqlAgentSchema, mode: 'default' })` on MySQL. */\nexport const mysqlAgentSchema = {\n agentActionProposal,\n agentThread,\n agentMessage,\n agentQueuedMessage,\n agentToolCall,\n agentTokenUsage,\n agentGenuiCall,\n agentModelPricing,\n agentRun,\n agentMemory,\n ragIngestionLog,\n agentConfirmToken,\n agentChannelState,\n agentStreamFrame,\n agentPoppyConversation,\n agentPoppyEvent,\n agentPoppyMessage,\n agentPoppyConnection,\n agentPoppyConnect,\n};\n","import { canonicalActionProposalJson } from '@dudousxd/nestjs-agent-core';\nimport type {\n ActionProposal,\n Actor,\n AgentUiComponent,\n MemoryOrigin,\n MessageAttachment,\n MessageFeedback,\n MessageRole,\n MessageUsage,\n PageContext,\n QueuePause,\n ToolCallRequest,\n ToolCallStatus,\n ToolConfirmation,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport type {\n AgentHostContext,\n CostSource,\n GenuiErrorCategory,\n GenuiToolMarker,\n GenuiValidity,\n RecordGenuiCallInput,\n RunStepTiming,\n} from '@dudousxd/nestjs-agent-core';\nimport type { UiCapabilities } from '@dudousxd/nestjs-agent-core/genui';\nimport {\n bigint,\n boolean,\n customType,\n doublePrecision,\n index,\n integer,\n jsonb,\n pgTable,\n primaryKey,\n text,\n timestamp,\n uniqueIndex,\n varchar,\n} from 'drizzle-orm/pg-core';\nimport type { AgentRunStatus, RagIngestionStatus } from './schema.js';\n\n/**\n * The agent tables for Postgres — the same tables, columns and JS property names as the SQLite\n * {@link import('./schema.js').agentSchema}, in Postgres types: `jsonb` for the JSON columns,\n * `timestamptz(3)` for the timestamps (read back as `Date`), `bigint` for the epoch-ms counters,\n * `double precision` for prices and costs. Pass it to `drizzle(pool, { schema: pgAgentSchema })`;\n * every store in this package finds these tables from the handle, whichever schema it was built with.\n */\nconst ts = (name: string) => timestamp(name, { withTimezone: true, precision: 3, mode: 'date' });\n\nexport const agentThread = pgTable(\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: boolean('transient').notNull().default(false),\n activeStreamId: text('active_stream_id'),\n defaultAgent: text('default_agent'),\n model: text('model'),\n /** The persona a send on this thread runs under when it names none; `null` → the agent's default. */\n persona: text('persona'),\n queuePause: jsonb('queue_pause').$type<QueuePause>(),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n deletedAt: ts('deleted_at'),\n },\n (table) => [\n index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt),\n // `ownerOfActiveStream` reads by run id on every stream attach and reconnect.\n index('agent_thread_active_stream_idx').on(table.activeStreamId),\n ],\n);\n\nexport const agentMessage = pgTable(\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 actionProposalOutcome: text('action_proposal_outcome'),\n content: text('content').notNull(),\n toolCalls: jsonb('tool_calls').$type<ToolCallRequest[]>(),\n toolResults: jsonb('tool_results').$type<ToolResult[]>(),\n attachments: jsonb('attachments').$type<MessageAttachment[]>(),\n followUps: jsonb('follow_ups').$type<string[]>(),\n usage: jsonb('usage').$type<MessageUsage>(),\n agentName: text('agent_name'),\n /** The persona the turn that wrote this message ran under; `null` → none. */\n persona: text('persona'),\n runId: text('run_id'),\n reasoning: text('reasoning'),\n reasoningMs: integer('reasoning_ms'),\n ui: jsonb('ui').$type<AgentUiComponent[]>(),\n feedback: jsonb('feedback').$type<MessageFeedback>(),\n seq: integer('seq'),\n createdAt: ts('created_at').notNull(),\n },\n (table) => [\n index('agent_message_thread_created_idx').on(table.threadId, table.createdAt),\n // Transcript reads order a thread's messages by `seq`.\n index('agent_message_thread_seq_idx').on(table.threadId, table.seq),\n ],\n);\n\nexport const agentToolCall = pgTable(\n 'agent_tool_call',\n {\n proposalId: text('proposal_id'),\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: jsonb('input'),\n output: jsonb('output'),\n status: text('status').$type<ToolCallStatus>().notNull(),\n executedByRef: text('executed_by_ref'),\n executionMs: integer('execution_ms'),\n error: text('error'),\n createdAt: ts('created_at').notNull(),\n executedAt: ts('executed_at'),\n runId: text('run_id'),\n confirmation: jsonb('confirmation').$type<ToolConfirmation>(),\n approver: text('approver'),\n expiresAt: ts('expires_at'),\n remember: boolean('remember'),\n decidedVia: text('decided_via'),\n },\n (table) => [\n index('agent_tool_call_message_idx').on(table.messageId),\n // The approvals inbox: `pending_approval`, oldest first.\n index('agent_tool_call_status_created_idx').on(table.status, table.createdAt),\n index('agent_tool_call_run_idx').on(table.runId),\n index('agent_tool_call_created_idx').on(table.createdAt),\n ],\n);\n\nexport const agentQueuedMessage = pgTable(\n 'agent_queued_message',\n {\n uiCapabilities: jsonb('ui_capabilities').$type<UiCapabilities>(),\n hostContext: jsonb('host_context').$type<AgentHostContext>(),\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actor: jsonb('actor').$type<Actor>().notNull(),\n content: text('content').notNull(),\n attachments: jsonb('attachments').$type<MessageAttachment[]>(),\n agentName: text('agent_name'),\n /** The persona the send resolved — what the message starts under. */\n persona: text('persona'),\n model: text('model'),\n pageContext: jsonb('page_context').$type<PageContext>(),\n interrupt: boolean('interrupt').notNull().default(false),\n position: integer('position').notNull(),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [index('agent_queued_message_thread_position_idx').on(table.threadId, table.position)],\n);\n\nexport const agentTokenUsage = pgTable(\n 'agent_token_usage',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n // NULL for usage recorded outside any conversation (`AgentService.recordUsage`).\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 cacheWriteTokens: integer('cache_write_tokens'),\n cacheReadTokens: integer('cache_read_tokens'),\n costUsd: doublePrecision('cost_usd'),\n /** Where `cost_usd` came from: `'provider'` (reported) or `'estimate'` (tokens × the price row); null on rows from before it existed (reported). */\n costSource: text('cost_source').$type<CostSource>(),\n /** The run the row belongs to. */\n runId: text('run_id'),\n /** What the spend was for: `agent:<name>` for an agent turn, the app's own otherwise; null → `agent`. */\n feature: text('feature'),\n provider: text('provider'),\n tenantRef: text('tenant_ref'),\n /** Units a row bills by when they are not tokens. */\n audioSeconds: doublePrecision('audio_seconds'),\n characters: bigint('characters', { mode: 'number' }),\n requests: integer('requests'),\n /** The caller's own JSON, never read by the library. */\n metadata: jsonb('metadata').$type<Record<string, unknown>>(),\n /** `false` keeps the row out of the agent's quota windows (`recordUsage({ countsTowardsQuota: false })`). */\n countsTowardsQuota: boolean('counts_towards_quota').notNull().default(true),\n createdAt: ts('created_at').notNull(),\n },\n (table) => [\n index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt),\n index('agent_token_usage_created_idx').on(table.createdAt),\n index('agent_token_usage_thread_idx').on(table.threadId),\n index('agent_token_usage_feature_created_idx').on(table.feature, table.createdAt),\n // `quota.per: 'tenant' | 'actor-in-tenant'` sums a tenant's window.\n index('agent_token_usage_tenant_created_idx').on(table.tenantRef, table.createdAt),\n ],\n);\n\n/**\n * Generative-UI telemetry (`AgentStore.recordGenuiCalls`): one row per UI tool call, keyed by the\n * tool call's id, so a replayed record replaces rather than duplicates. Metadata only — `payload`\n * (the call's arguments) is filled solely when the tool samples payloads. `created_at` is epoch-ms.\n */\nexport const agentGenuiCall = pgTable(\n 'agent_genui_call',\n {\n id: text('id').primaryKey(),\n runId: text('run_id').notNull(),\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 step: integer('step').notNull(),\n toolName: text('tool_name').notNull(),\n channel: text('channel').notNull(),\n mode: text('mode').$type<GenuiToolMarker['mode']>().notNull(),\n modelId: text('model_id').notNull(),\n attempt: integer('attempt').notNull(),\n outcome: text('outcome').$type<RecordGenuiCallInput['outcome']>().notNull(),\n validity: text('validity').$type<GenuiValidity>().notNull(),\n errorCategory: text('error_category').$type<GenuiErrorCategory>(),\n errorMessage: text('error_message'),\n inputTokens: integer('input_tokens').notNull(),\n outputTokens: integer('output_tokens').notNull(),\n costUsd: doublePrecision('cost_usd'),\n costSource: varchar('cost_source', { length: 16 }).$type<CostSource>(),\n firstFrameMs: bigint('first_frame_ms', { mode: 'number' }),\n completeFrameMs: bigint('complete_frame_ms', { mode: 'number' }),\n payloadBytes: integer('payload_bytes').notNull(),\n payload: text('payload'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n index('agent_genui_call_created_idx').on(table.createdAt),\n index('agent_genui_call_run_idx').on(table.runId),\n ],\n);\n\nexport const agentModelPricing = pgTable('agent_model_pricing', {\n id: text('id').primaryKey(),\n modelId: text('model_id').notNull(),\n inputPricePer1m: doublePrecision('input_price_per_1m').notNull(),\n outputPricePer1m: doublePrecision('output_price_per_1m').notNull(),\n cacheWritePricePer1m: doublePrecision('cache_write_price_per_1m'),\n cacheReadPricePer1m: doublePrecision('cache_read_price_per_1m'),\n effectiveFrom: ts('effective_from').notNull(),\n isCurrent: boolean('is_current').notNull(),\n});\n\nexport const agentRun = pgTable(\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 /** Turn start to the first `text` frame; null for a run that streamed none or did not complete. */\n ttftMs: integer('ttft_ms'),\n /** The run's known spend (the sum of its model calls with a known cost); null when none had one. */\n costUsd: doublePrecision('cost_usd'),\n /** The model the run's last model call resolved to. */\n modelId: text('model_id'),\n errorCode: text('error_code'),\n errorMessage: text('error_message'),\n retries: integer('retries').notNull().default(0),\n startedAt: ts('started_at').notNull(),\n settledAt: ts('settled_at'),\n promptHash: text('prompt_hash'),\n parentRunId: text('parent_run_id'),\n /** Enqueue → body start (ms); null when not read. */\n queueMs: integer('queue_ms'),\n /** Where the completed run's time went: model and tool totals, counts, and the per-step list. */\n modelMs: integer('model_ms'),\n toolsMs: integer('tools_ms'),\n modelCalls: integer('model_calls'),\n toolCalls: integer('tool_calls'),\n timings: jsonb('timings').$type<RunStepTiming[]>(),\n },\n (table) => [index('agent_run_started_idx').on(table.startedAt)],\n);\n\nexport const agentMemory = pgTable(\n 'agent_memory',\n {\n id: text('id').primaryKey(),\n scope: text('scope').notNull(),\n key: text('key').notNull(),\n text: text('text').notNull(),\n originAuthor: text('origin_author').$type<MemoryOrigin['author']>().notNull(),\n originThreadId: text('origin_thread_id'),\n originRunId: text('origin_run_id'),\n originActorRef: text('origin_actor_ref'),\n pinned: boolean('pinned').notNull().default(false),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [uniqueIndex('agent_memory_scope_key_uq').on(table.scope, table.key)],\n);\n\nexport const ragIngestionLog = pgTable(\n 'rag_ingestion_log',\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 source: text('source'),\n mimeType: text('mime_type'),\n size: bigint('size', { mode: 'number' }),\n chunks: integer('chunks'),\n reason: text('reason'),\n error: text('error'),\n createdAt: ts('created_at').notNull(),\n updatedAt: ts('updated_at').notNull(),\n },\n (table) => [index('rag_ingestion_log_collection_idx').on(table.collection, table.updatedAt)],\n);\n\n/**\n * Text channels' short-lived state (`@dudousxd/nestjs-agent-channels`), one row per key: the provider\n * message ids already answered, a question waiting for the person's answer, an outcome already\n * relayed. The primary key is the lock a claim takes; `expires_at` is epoch-ms, and past it the row\n * is free again and dead weight for `DrizzleChannelStore.purgeExpired`. Keys longer than 255\n * characters are stored by their SHA-256.\n */\nexport const agentChannelState = pgTable(\n 'agent_channel_state',\n {\n key: text('key').primaryKey(),\n value: text('value'),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [index('agent_channel_state_expires_idx').on(table.expiresAt)],\n);\n\nexport const agentConfirmToken = pgTable(\n 'agent_confirm_token',\n {\n hash: text('hash').primaryKey(),\n actorRef: text('actor_ref').notNull(),\n tool: text('tool').notNull(),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [index('agent_confirm_token_expires_idx').on(table.expiresAt)],\n);\n\nexport const agentStreamFrame = pgTable(\n 'agent_stream_frame',\n {\n runId: text('run_id').notNull(),\n seq: integer('seq').notNull(),\n frame: text('frame'),\n error: text('error'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.runId, table.seq] })],\n);\n\n/** JSON text preserves valid JSON strings that a native JSON column cannot represent. */\nconst proposalJson = customType<{ data: ActionProposal; driverData: string }>({\n dataType: () => 'text',\n toDriver: (value) => canonicalActionProposalJson(value),\n fromDriver: (value) => JSON.parse(value) as ActionProposal,\n});\n\n/** Independent action proposals; decision and execution work commit in one fenced row. */\nexport const agentActionProposal = pgTable(\n 'agent_action_proposal',\n {\n id: text('id').primaryKey(),\n scopeKey: text('scope_key').notNull(),\n decision: text('decision').$type<ActionProposal['decision']>().notNull(),\n logicalSort: text('logical_sort').notNull(),\n createFingerprint: text('create_fingerprint').notNull(),\n proposal: proposalJson('proposal').notNull(),\n version: bigint('version', { mode: 'number' }).notNull().default(0),\n executionStatus:\n text('execution_status').$type<NonNullable<ActionProposal['execution']>['status']>(),\n leaseExpiresAt: bigint('lease_expires_at', { mode: 'number' }),\n deliveryStatus: text('delivery_status'),\n deliveryLeaseExpiresAt: bigint('delivery_lease_expires_at', { mode: 'number' }),\n replacementGroupKey: text('replacement_group_key'),\n outcomeIdKey: text('outcome_id_key'),\n proposalExpiresAt: bigint('proposal_expires_at', { mode: 'number' }),\n discoveryIndexVersion: bigint('discovery_index_version', { mode: 'number' })\n .notNull()\n .default(0),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n index('agent_action_proposal_execution_idx').on(\n table.discoveryIndexVersion,\n table.executionStatus,\n table.leaseExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_expiry_idx').on(\n table.discoveryIndexVersion,\n table.decision,\n table.proposalExpiresAt,\n table.createdAt,\n ),\n index('agent_action_proposal_replacement_idx').on(\n table.scopeKey,\n table.replacementGroupKey,\n table.decision,\n ),\n index('agent_action_proposal_delivery_idx').on(\n table.deliveryStatus,\n table.deliveryLeaseExpiresAt,\n table.createdAt,\n ),\n uniqueIndex('agent_action_proposal_outcome_idx').on(table.outcomeIdKey),\n index('agent_action_proposal_scope_idx').on(table.scopeKey, table.createdAt, table.id),\n ],\n);\n\n/**\n * Personal Agent Protocol (Poppy) conversations (`DrizzlePoppyStore`): who it is with, its status,\n * the User's context and the identity its turns run as (JSON text), and the reader lease\n * (`reader_holder` until `reader_until`, epoch-ms) that lets one replica at a time write a reply.\n * `pruned_seq`: events at or below it were pruned.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConversation = pgTable('agent_poppy_conversation', {\n id: text('id').primaryKey(),\n clientId: text('client_id').notNull(),\n userId: text('user_id').notNull(),\n accountRef: text('account_ref'),\n agentName: text('agent_name').notNull(),\n threadId: text('thread_id'),\n parentId: text('parent_id'),\n openDirectId: text('open_direct_id'),\n status: text('status').notNull(),\n responder: text('responder').notNull(),\n context: text('context'),\n activeRunId: text('active_run_id'),\n turnSeq: bigint('turn_seq', { mode: 'number' }).notNull(),\n grantInfo: text('grant_info'),\n readerHolder: text('reader_holder'),\n readerUntil: bigint('reader_until', { mode: 'number' }),\n prunedSeq: bigint('pruned_seq', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),\n});\n\n/**\n * A Poppy conversation's events, append-only, numbered per conversation. The primary key is the\n * position, so two appends racing for one cannot both win; `event_key` (unique per conversation)\n * is what keeps a re-read turn from writing its reply twice. `event` is the event as JSON text.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyEvent = pgTable(\n 'agent_poppy_event',\n {\n conversationId: text('conversation_id').notNull(),\n seq: bigint('seq', { mode: 'number' }).notNull(),\n id: text('id').notNull(),\n type: text('type').notNull(),\n event: text('event').notNull(),\n eventKey: text('event_key'),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.conversationId, table.seq] }),\n uniqueIndex('agent_poppy_event_key_idx').on(table.conversationId, table.eventKey),\n index('agent_poppy_event_id_idx').on(table.conversationId, table.id),\n ],\n);\n\n/**\n * Accepted Poppy messages, one row per (owner, message id) — the primary key is the idempotency lock\n * that makes two deliveries of one message one (§7.3); `response` is what the first got, as JSON.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyMessage = pgTable(\n 'agent_poppy_message',\n {\n owner: text('owner').notNull(),\n messageId: text('message_id').notNull(),\n fingerprint: text('fingerprint').notNull(),\n conversationId: text('conversation_id').notNull(),\n response: text('response').notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.messageId] })],\n);\n\n/**\n * This app's Poppy connections (`DrizzlePoppyConnectionStore`): one per (owner, Company issuer),\n * holding the client state SEALED by the caller — never a token in the clear.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnection = pgTable(\n 'agent_poppy_connection',\n {\n owner: text('owner').notNull(),\n issuer: text('issuer').notNull(),\n domain: text('domain').notNull(),\n organization: text('organization').notNull(),\n scope: text('scope').notNull(),\n status: text('status').notNull(),\n state: text('state').notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.owner, table.issuer] })],\n);\n\n/**\n * Poppy sign-ins in flight, started by the `connect` tool and completed on the connect page. `actor`\n * is JSON text; `flow` the sealed per-method state.\n *\n * @experimental Personal Agent Protocol Draft 0.1.\n */\nexport const agentPoppyConnect = pgTable('agent_poppy_connect', {\n id: text('id').primaryKey(),\n owner: text('owner').notNull(),\n domain: text('domain').notNull(),\n issuer: text('issuer').notNull(),\n organization: text('organization').notNull(),\n scope: text('scope').notNull(),\n actor: text('actor'),\n threadId: text('thread_id'),\n runId: text('run_id'),\n toolCallId: text('tool_call_id'),\n flow: text('flow'),\n status: text('status').notNull(),\n expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),\n createdAt: bigint('created_at', { mode: 'number' }).notNull(),\n});\n\n/** Every agent table, for `drizzle(pool, { schema: pgAgentSchema })` on Postgres. */\nexport const pgAgentSchema = {\n agentActionProposal,\n agentThread,\n agentMessage,\n agentQueuedMessage,\n agentToolCall,\n agentTokenUsage,\n agentGenuiCall,\n agentModelPricing,\n agentRun,\n agentMemory,\n ragIngestionLog,\n agentConfirmToken,\n agentChannelState,\n agentStreamFrame,\n agentPoppyConversation,\n agentPoppyEvent,\n agentPoppyMessage,\n agentPoppyConnection,\n agentPoppyConnect,\n};\n","import {\n type ActionProposalDiscoveryIndexStore,\n type ActionProposalOutcomeStore,\n type ActionProposalStore,\n type ActionProposalStoreOptions,\n type ActionProposalSupersessionStore,\n type ActionProposalWorkerStore,\n type AgentStore,\n type AgentUiComponent,\n type AppendMessageInput,\n type ChatQueueStore,\n type CreateThreadInput,\n type EnqueueMessageInput,\n type ForkThreadOptions,\n type MessageFeedback,\n type QueuePause,\n type QueuedMessage,\n type QueuedMessagePatch,\n type RecordGenuiCallInput,\n type RecordRunEndInput,\n type RecordRunStartInput,\n type RecordToolCallInput,\n type RecordUsageInput,\n type StoredMessage,\n type TenantRowFilter,\n type TenantTarget,\n type ThreadDetail,\n type ThreadSettings,\n type ThreadSettingsReader,\n type ThreadSummary,\n type ThreadTurnPage,\n type ThreadTurnQuery,\n type ThreadTurnReader,\n type ToolCallApproval,\n type ToolCallApprovalState,\n type ToolCallOutcome,\n type ToolResult,\n type UpdateThreadInput,\n type UpdateToolCallInput,\n type UsageTotals,\n canonicalActionProposalJson,\n sumUsage,\n toolCallApprovalFromRow,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n type SQL,\n and,\n asc,\n desc,\n eq,\n gte,\n inArray,\n isNotNull,\n isNull,\n lte,\n max,\n min,\n or,\n sql,\n} from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n upsert,\n} from './dialect.js';\nimport { DrizzleActionProposalStore } from './drizzle-action-proposal-store.js';\nimport {\n type AgentMessageRow,\n type AgentQueuedMessageRow,\n type AgentRunRow,\n type AgentThreadRow,\n agentMessage,\n agentQueuedMessage,\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. */\nfunction turnMessageColumns(message: AgentTables['agentMessage']) {\n return {\n id: message.id,\n role: message.role,\n content: message.content,\n agentName: message.agentName,\n toolCalls: message.toolCalls,\n toolResults: message.toolResults,\n attachments: message.attachments,\n createdAt: message.createdAt,\n };\n}\n\ntype TurnMessageRow = { [K in keyof ReturnType<typeof turnMessageColumns>]: 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 database handle — SQLite, Postgres or\n * MySQL (the host app 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\n implements\n AgentStore,\n ThreadTurnReader,\n ThreadSettingsReader,\n ChatQueueStore,\n ActionProposalStore,\n ActionProposalWorkerStore,\n ActionProposalDiscoveryIndexStore,\n ActionProposalOutcomeStore\n{\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n private readonly proposals: DrizzleActionProposalStore;\n\n constructor(db: AgentDrizzleDb, options: ActionProposalStoreOptions = {}) {\n this.proposals = new DrizzleActionProposalStore(db, options);\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n createActionProposal(\n ...args: Parameters<ActionProposalStore['createActionProposal']>\n ): ReturnType<ActionProposalStore['createActionProposal']> {\n return this.proposals.createActionProposal(...args);\n }\n\n getActionProposal(\n ...args: Parameters<ActionProposalStore['getActionProposal']>\n ): ReturnType<ActionProposalStore['getActionProposal']> {\n return this.proposals.getActionProposal(...args);\n }\n\n listActionProposals(\n ...args: Parameters<ActionProposalStore['listActionProposals']>\n ): ReturnType<ActionProposalStore['listActionProposals']> {\n return this.proposals.listActionProposals(...args);\n }\n\n decideActionProposal(\n ...args: Parameters<ActionProposalStore['decideActionProposal']>\n ): ReturnType<ActionProposalStore['decideActionProposal']> {\n return this.proposals.decideActionProposal(...args);\n }\n\n claimActionProposal(\n ...args: Parameters<ActionProposalStore['claimActionProposal']>\n ): ReturnType<ActionProposalStore['claimActionProposal']> {\n return this.proposals.claimActionProposal(...args);\n }\n\n extendActionProposalLease(\n ...args: Parameters<ActionProposalStore['extendActionProposalLease']>\n ): ReturnType<ActionProposalStore['extendActionProposalLease']> {\n return this.proposals.extendActionProposalLease(...args);\n }\n\n claimNextActionProposal(\n ...args: Parameters<ActionProposalWorkerStore['claimNextActionProposal']>\n ): ReturnType<ActionProposalWorkerStore['claimNextActionProposal']> {\n return this.proposals.claimNextActionProposal(...args);\n }\n\n expireActionProposals(\n ...args: Parameters<ActionProposalWorkerStore['expireActionProposals']>\n ): ReturnType<ActionProposalWorkerStore['expireActionProposals']> {\n return this.proposals.expireActionProposals(...args);\n }\n\n backfillActionProposalDiscoveryIndex(command: { limit: number }): Promise<number> {\n return this.proposals.backfillActionProposalDiscoveryIndex(command);\n }\n\n settleActionProposal(\n ...args: Parameters<ActionProposalStore['settleActionProposal']>\n ): ReturnType<ActionProposalStore['settleActionProposal']> {\n return this.proposals.settleActionProposal(...args);\n }\n\n createReplacingActionProposal(\n ...args: Parameters<ActionProposalSupersessionStore['createReplacingActionProposal']>\n ) {\n return this.proposals.createReplacingActionProposal(...args);\n }\n supersedeActionProposal(\n ...args: Parameters<ActionProposalSupersessionStore['supersedeActionProposal']>\n ) {\n return this.proposals.supersedeActionProposal(...args);\n }\n\n get actionProposalAdmissionSupported(): boolean {\n return this.proposals.actionProposalAdmissionSupported;\n }\n getThreadActionProposalScope(threadId: string) {\n return this.proposals.getThreadActionProposalScope(threadId);\n }\n claimNextActionProposalOutcome(\n ...args: Parameters<ActionProposalOutcomeStore['claimNextActionProposalOutcome']>\n ) {\n return this.proposals.claimNextActionProposalOutcome(...args);\n }\n admitActionProposalOutcome(\n ...args: Parameters<ActionProposalOutcomeStore['admitActionProposalOutcome']>\n ) {\n return this.proposals.admitActionProposalOutcome(...args);\n }\n\n async createThread(input: CreateThreadInput): Promise<ThreadSummary> {\n const now = new Date();\n const thread: AgentThreadRow = {\n id: input.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 model: null,\n persona: input.persona ?? null,\n queuePause: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(this.t.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(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));\n if (thread === undefined) {\n return null;\n }\n const messages = await this.db\n .select()\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId))\n .orderBy(...this.messageOrder());\n const last = messages[messages.length - 1];\n const approvals = await this.approvalsFor(messages.map((message) => message.id));\n return {\n ...this.toSummary(thread, last?.content),\n messages: messages.map((message) => {\n const stored = this.toStoredMessage(message);\n const onMessage = approvals.get(message.id);\n return onMessage !== undefined ? { ...stored, approvals: onMessage } : stored;\n }),\n ...(thread.activeStreamId != null ? { activeRunId: 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: this.t.agentThread.title, defaultAgent: this.t.agentThread.defaultAgent })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, query.threadId), isNull(this.t.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: this.t.agentMessage.id })\n .from(this.t.agentMessage)\n .where(\n and(\n eq(this.t.agentMessage.threadId, query.threadId),\n eq(this.t.agentMessage.role, 'assistant'),\n ),\n )\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(turnMessageColumns(this.t.agentMessage))\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId))\n .orderBy(...this.messageOrderNewestFirst());\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 return this.listThreadsWhere(actorRef, undefined, limit);\n }\n\n async listThreadsForTenant(\n actorRef: string,\n filter: TenantRowFilter,\n limit = 50,\n ): Promise<ThreadSummary[]> {\n const column = this.t.agentThread.tenantRef;\n const visible =\n filter.tenant === undefined\n ? isNull(column)\n : filter.nulls\n ? or(eq(column, filter.tenant), isNull(column))\n : eq(column, filter.tenant);\n return this.listThreadsWhere(actorRef, visible, limit);\n }\n\n private async listThreadsWhere(\n actorRef: string,\n tenant: SQL | undefined,\n limit: number,\n ): Promise<ThreadSummary[]> {\n const threads = await this.db\n .select()\n .from(this.t.agentThread)\n .where(\n and(\n eq(this.t.agentThread.actorRef, actorRef),\n eq(this.t.agentThread.transient, false),\n isNull(this.t.agentThread.deletedAt),\n tenant,\n ),\n )\n .orderBy(desc(this.t.agentThread.updatedAt))\n .limit(limit);\n const previews = await this.lastMessageContents(threads.map((thread) => thread.id));\n return threads.map((thread) => this.toSummary(thread, previews.get(thread.id)));\n }\n\n /**\n * The content of each thread's newest message ({@link messageOrderNewestFirst}), in a fixed two\n * reads for any number of threads: each thread's highest `seq`, then the rows holding it. Only a\n * thread whose every message predates `seq` is read on its own, by `created_at`.\n */\n private async lastMessageContents(threadIds: readonly string[]): Promise<Map<string, string>> {\n const contents = new Map<string, string>();\n if (threadIds.length === 0) {\n return contents;\n }\n const message = this.t.agentMessage;\n const highest = await this.db\n .select({ threadId: message.threadId, seq: max(message.seq) })\n .from(message)\n .where(inArray(message.threadId, [...threadIds]))\n .groupBy(message.threadId);\n const numbered = highest.filter((row) => row.seq !== null);\n if (numbered.length > 0) {\n const rows = await this.db\n .select({ threadId: message.threadId, content: message.content })\n .from(message)\n .where(\n or(\n ...numbered.map((row) =>\n and(eq(message.threadId, row.threadId), eq(message.seq, Number(row.seq))),\n ),\n ),\n )\n .orderBy(...this.messageOrderNewestFirst());\n for (const row of rows) {\n if (!contents.has(row.threadId)) {\n contents.set(row.threadId, row.content);\n }\n }\n }\n for (const row of highest) {\n if (row.seq === null) {\n const [last] = await this.db\n .select({ content: message.content })\n .from(message)\n .where(eq(message.threadId, row.threadId))\n .orderBy(...this.messageOrderNewestFirst())\n .limit(1);\n if (last !== undefined) {\n contents.set(row.threadId, last.content);\n }\n }\n }\n return contents;\n }\n\n async softDeleteThread(threadId: string): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ deletedAt: new Date() })\n .where(eq(this.t.agentThread.id, threadId));\n }\n\n async forkThread(\n threadId: string,\n fromMessageId: string,\n options: ForkThreadOptions = {},\n ): Promise<ThreadSummary> {\n const [source] = await this.db\n .select()\n .from(this.t.agentThread)\n .where(eq(this.t.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(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId))\n .orderBy(...this.messageOrder());\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: options.actorRef ?? source.actorRef,\n tenantRef: options.tenantRef !== undefined ? options.tenantRef : source.tenantRef,\n title: source.title,\n transient: false,\n activeStreamId: null,\n defaultAgent: source.defaultAgent,\n model: source.model,\n persona: source.persona,\n // A fork is a new conversation: nothing is waiting on it, and nothing is paused.\n queuePause: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(this.t.agentThread).values(fork);\n if (kept.length > 0) {\n await this.db.insert(this.t.agentMessage).values(\n kept.map((message, index) => ({\n id: crypto.randomUUID(),\n // Numbered afresh in the order just read, so the copy reads back in the original's order.\n seq: index + 1,\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 persona: message.persona,\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 reasoning: message.reasoning,\n reasoningMs: message.reasoningMs,\n ui: message.ui,\n actionProposalOutcome: message.actionProposalOutcome,\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: this.t.agentThread.actorRef })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.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: this.t.agentThread.actorRef })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(eq(this.t.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({\n runId: this.t.agentToolCall.runId,\n activeStreamId: this.t.agentThread.activeStreamId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(eq(this.t.agentToolCall.id, toolCallId));\n return row?.runId ?? row?.activeStreamId ?? null;\n }\n\n /**\n * The approval record of every call on `messageIds` that a policy put to a person, grouped by\n * message. One query over the calls that carry an approver — a thread whose calls never asked\n * anyone reads nothing back.\n */\n private async approvalsFor(messageIds: string[]): Promise<Map<string, ToolCallApproval[]>> {\n const byMessage = new Map<string, ToolCallApproval[]>();\n if (messageIds.length === 0) {\n return byMessage;\n }\n const rows = await this.db\n .select({\n id: this.t.agentToolCall.id,\n messageId: this.t.agentToolCall.messageId,\n status: this.t.agentToolCall.status,\n approver: this.t.agentToolCall.approver,\n confirmation: this.t.agentToolCall.confirmation,\n expiresAt: this.t.agentToolCall.expiresAt,\n remember: this.t.agentToolCall.remember,\n executedByRef: this.t.agentToolCall.executedByRef,\n decidedVia: this.t.agentToolCall.decidedVia,\n error: this.t.agentToolCall.error,\n })\n .from(this.t.agentToolCall)\n .where(\n and(\n inArray(this.t.agentToolCall.messageId, messageIds),\n isNotNull(this.t.agentToolCall.approver),\n ),\n )\n .orderBy(asc(this.t.agentToolCall.createdAt), asc(this.t.agentToolCall.id));\n for (const row of rows) {\n const approval = toolCallApprovalFromRow({ ...row, toolCallId: row.id });\n if (approval === null) {\n continue;\n }\n const list = byMessage.get(row.messageId) ?? [];\n list.push(approval);\n byMessage.set(row.messageId, list);\n }\n return byMessage;\n }\n\n /** Tools whose approval someone asked to remember in this thread. */\n async rememberedApprovals(threadId: string): Promise<string[]> {\n const rows = await this.db\n .selectDistinct({ toolName: this.t.agentToolCall.toolName })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .where(\n and(eq(this.t.agentMessage.threadId, threadId), eq(this.t.agentToolCall.remember, true)),\n );\n const scope = await this.getThreadActionProposalScope(threadId);\n const proposalNames = scope\n ? await this.proposals.rememberedActionProposalApprovals(scope)\n : [];\n return [...new Set([...rows.map((row) => row.toolName), ...proposalNames])];\n }\n\n async toolCallInput(toolCallId: string): Promise<unknown> {\n const [row] = await this.db\n .select({ input: this.t.agentToolCall.input })\n .from(this.t.agentToolCall)\n .where(eq(this.t.agentToolCall.id, toolCallId));\n return row?.input ?? null;\n }\n\n async toolCallApproval(toolCallId: string): Promise<ToolCallApprovalState | null> {\n const [row] = await this.db\n .select({\n status: this.t.agentToolCall.status,\n approver: this.t.agentToolCall.approver,\n expiresAt: this.t.agentToolCall.expiresAt,\n })\n .from(this.t.agentToolCall)\n .where(eq(this.t.agentToolCall.id, toolCallId));\n if (row === undefined) {\n return null;\n }\n return {\n status: row.status,\n approver: row.approver,\n expiresAt: row.expiresAt?.toISOString() ?? null,\n };\n }\n\n async tenantOf(target: TenantTarget): Promise<{ tenantRef: string | null } | null> {\n const thread = this.t.agentThread;\n if ('toolCallId' in target) {\n const [row] = await this.db\n .select({ tenantRef: thread.tenantRef })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(thread, eq(this.t.agentMessage.threadId, thread.id))\n .where(eq(this.t.agentToolCall.id, target.toolCallId));\n return row === undefined ? null : { tenantRef: row.tenantRef ?? null };\n }\n const [row] = await this.db\n .select({ tenantRef: thread.tenantRef })\n .from(thread)\n .where(\n and(\n 'threadId' in target\n ? eq(thread.id, target.threadId)\n : eq(thread.activeStreamId, target.runId),\n isNull(thread.deletedAt),\n ),\n );\n return row === undefined ? null : { tenantRef: row.tenantRef ?? null };\n }\n\n async ownerOfActiveStream(runId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: this.t.agentThread.actorRef })\n .from(this.t.agentThread)\n .where(\n and(eq(this.t.agentThread.activeStreamId, runId), isNull(this.t.agentThread.deletedAt)),\n );\n return thread?.actorRef ?? null;\n }\n\n async setTitle(threadId: string, title: string): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ title, updatedAt: new Date() })\n .where(eq(this.t.agentThread.id, threadId));\n }\n\n async promoteThread(threadId: string): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ transient: false, updatedAt: new Date() })\n .where(and(eq(this.t.agentThread.id, threadId), eq(this.t.agentThread.transient, true)));\n }\n\n /** Who holds the thread's stream right now, deleted or not. */\n private async activeHolder(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ activeStreamId: this.t.agentThread.activeStreamId })\n .from(this.t.agentThread)\n .where(eq(this.t.agentThread.id, threadId));\n return thread?.activeStreamId ?? null;\n }\n\n /**\n * A thread's messages in the order they were appended: by `seq`, which append assigns. A row from\n * before `seq` existed has none and counts as 0 — first, since every such row is older than every\n * numbered one — and those order among themselves by `created_at`, then `id`, as they always did.\n * `coalesce` rather than `nulls first`, which MySQL cannot spell and Postgres defaults the other way.\n */\n private messageOrder(): SQL[] {\n const message = this.t.agentMessage;\n return [asc(sql`coalesce(${message.seq}, 0)`), asc(message.createdAt), asc(message.id)];\n }\n\n /** {@link messageOrder}, newest first. */\n private messageOrderNewestFirst(): SQL[] {\n const message = this.t.agentMessage;\n return [desc(sql`coalesce(${message.seq}, 0)`), desc(message.createdAt), desc(message.id)];\n }\n\n /**\n * The next `seq` in a thread: one past its highest. Two appends racing on ONE thread can draw the\n * same number — the turn loop never does that, and the tie then falls back to `created_at`, `id`.\n */\n private async nextMessageSeq(threadId: string): Promise<number> {\n const [row] = await this.db\n .select({ last: max(this.t.agentMessage.seq) })\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId));\n return Number(row?.last ?? 0) + 1;\n }\n\n /** The run streaming the thread, or `null` — a projection of the one column. */\n async activeRunForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ activeStreamId: this.t.agentThread.activeStreamId })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));\n return thread?.activeStreamId ?? null;\n }\n\n /**\n * One conditional UPDATE, so of two racing claims exactly one changes the row: set the holder to\n * `runId` only when there is none, it is already `runId`, or it is `replacing`.\n */\n async claimActiveStream(\n threadId: string,\n runId: string,\n options: { replacing?: string } = {},\n ): Promise<boolean> {\n const holders = [\n isNull(this.t.agentThread.activeStreamId),\n eq(this.t.agentThread.activeStreamId, runId),\n ...(options.replacing !== undefined\n ? [eq(this.t.agentThread.activeStreamId, options.replacing)]\n : []),\n ];\n const claimed = await affectedRows(\n this.dialect,\n this.db\n .update(this.t.agentThread)\n .set({ activeStreamId: runId })\n .where(and(eq(this.t.agentThread.id, threadId), or(...holders))),\n this.t.agentThread.id,\n );\n if (claimed > 0) {\n return true;\n }\n // Zero can still be a win: a MySQL connection without FOUND_ROWS reports CHANGED rows, and\n // re-claiming a thread this run already holds changes nothing. The row says who holds it now.\n return (await this.activeHolder(threadId)) === runId;\n }\n\n async releaseActiveStream(threadId: string, runId: string): Promise<boolean> {\n const released = await affectedRows(\n this.dialect,\n this.db\n .update(this.t.agentThread)\n .set({ activeStreamId: null })\n .where(\n and(eq(this.t.agentThread.id, threadId), eq(this.t.agentThread.activeStreamId, runId)),\n ),\n this.t.agentThread.id,\n );\n return released > 0;\n }\n\n async enqueueMessage(input: EnqueueMessageInput): Promise<QueuedMessage> {\n const now = new Date();\n const [edge] = await this.db\n .select({\n first: min(this.t.agentQueuedMessage.position),\n last: max(this.t.agentQueuedMessage.position),\n })\n .from(this.t.agentQueuedMessage)\n .where(eq(this.t.agentQueuedMessage.threadId, input.threadId));\n const position = input.at === 'head' ? (edge?.first ?? 1) - 1 : (edge?.last ?? -1) + 1;\n const row: AgentQueuedMessageRow = {\n id: crypto.randomUUID(),\n threadId: input.threadId,\n actor: input.actor,\n content: input.content,\n uiCapabilities: input.uiCapabilities ?? null,\n hostContext: input.hostContext ?? null,\n attachments:\n input.attachments !== undefined && input.attachments.length > 0 ? input.attachments : null,\n agentName: input.agentName ?? null,\n persona: input.persona ?? null,\n model: input.model ?? null,\n pageContext: input.pageContext ?? null,\n interrupt: input.interrupt === true,\n position,\n createdAt: now,\n updatedAt: now,\n };\n await this.db.insert(this.t.agentQueuedMessage).values(row);\n return toQueuedMessage(row);\n }\n\n async listQueue(threadId: string): Promise<QueuedMessage[]> {\n const rows = await this.db\n .select()\n .from(this.t.agentQueuedMessage)\n .where(eq(this.t.agentQueuedMessage.threadId, threadId))\n .orderBy(asc(this.t.agentQueuedMessage.position), asc(this.t.agentQueuedMessage.createdAt));\n return rows.map(toQueuedMessage);\n }\n\n async getQueuedMessage(id: string): Promise<QueuedMessage | null> {\n const [row] = await this.db\n .select()\n .from(this.t.agentQueuedMessage)\n .where(eq(this.t.agentQueuedMessage.id, id));\n return row === undefined ? null : toQueuedMessage(row);\n }\n\n async updateQueuedMessage(id: string, patch: QueuedMessagePatch): Promise<QueuedMessage | null> {\n const updates: Partial<AgentQueuedMessageRow> = { updatedAt: new Date() };\n if (patch.content !== undefined) {\n updates.content = patch.content;\n }\n if (patch.attachments !== undefined) {\n updates.attachments =\n patch.attachments === null || patch.attachments.length === 0 ? null : patch.attachments;\n }\n if (patch.interrupt !== undefined) {\n updates.interrupt = patch.interrupt;\n }\n await this.db\n .update(this.t.agentQueuedMessage)\n .set(updates)\n .where(eq(this.t.agentQueuedMessage.id, id));\n return this.getQueuedMessage(id);\n }\n\n /** Rewrites the thread's positions as 0..n-1 in the new order — a queue is a handful of rows. */\n async moveQueuedMessage(id: string, index: number): Promise<boolean> {\n const moving = await this.getQueuedMessage(id);\n if (moving === null) {\n return false;\n }\n const order = (await this.listQueue(moving.threadId)).filter((message) => message.id !== id);\n const target = Math.max(0, Math.min(order.length, Math.trunc(index)));\n order.splice(target, 0, moving);\n for (const [position, message] of order.entries()) {\n await this.db\n .update(this.t.agentQueuedMessage)\n .set({ position })\n .where(eq(this.t.agentQueuedMessage.id, message.id));\n }\n return true;\n }\n\n async removeQueuedMessage(id: string): Promise<boolean> {\n const removed = await affectedRows(\n this.dialect,\n this.db.delete(this.t.agentQueuedMessage).where(eq(this.t.agentQueuedMessage.id, id)),\n this.t.agentQueuedMessage.id,\n );\n return removed > 0;\n }\n\n async clearQueue(threadId: string): Promise<number> {\n return affectedRows(\n this.dialect,\n this.db\n .delete(this.t.agentQueuedMessage)\n .where(eq(this.t.agentQueuedMessage.threadId, threadId)),\n this.t.agentQueuedMessage.id,\n );\n }\n\n async queuePause(threadId: string): Promise<QueuePause | null> {\n const [thread] = await this.db\n .select({ queuePause: this.t.agentThread.queuePause })\n .from(this.t.agentThread)\n .where(eq(this.t.agentThread.id, threadId));\n return thread?.queuePause ?? null;\n }\n\n async setQueuePause(threadId: string, pause: QueuePause | null): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ queuePause: pause })\n .where(eq(this.t.agentThread.id, threadId));\n }\n\n async setActiveStream(threadId: string, runId: string | null): Promise<void> {\n await this.db\n .update(this.t.agentThread)\n .set({ activeStreamId: runId })\n .where(eq(this.t.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 (patch.model !== undefined) {\n updates.model = patch.model;\n }\n if (patch.persona !== undefined) {\n updates.persona = patch.persona;\n }\n if (Object.keys(updates).length === 0) {\n return;\n }\n updates.updatedAt = new Date();\n await this.db\n .update(this.t.agentThread)\n .set(updates)\n .where(eq(this.t.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 /** The thread's pinned model, projected like {@link defaultAgentForThread}. */\n async modelForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ model: this.t.agentThread.model })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));\n return thread?.model ?? null;\n }\n\n /** The thread's pinned persona, projected like {@link defaultAgentForThread}. */\n async personaForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ persona: this.t.agentThread.persona })\n .from(agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));\n return thread?.persona ?? null;\n }\n\n async threadSettings(threadId: string): Promise<ThreadSettings | null> {\n const thread = this.t.agentThread;\n const [row] = await this.db\n .select({\n actorRef: thread.actorRef,\n defaultAgent: thread.defaultAgent,\n persona: thread.persona,\n model: thread.model,\n })\n .from(thread)\n .where(and(eq(thread.id, threadId), isNull(thread.deletedAt)));\n if (row === undefined) {\n return null;\n }\n return {\n actorRef: row.actorRef,\n defaultAgent: row.defaultAgent ?? null,\n persona: row.persona ?? null,\n model: row.model ?? null,\n };\n }\n\n async defaultAgentForThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ defaultAgent: this.t.agentThread.defaultAgent })\n .from(this.t.agentThread)\n .where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.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 ttftMs: null,\n costUsd: null,\n modelId: 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 queueMs: run.queueMs !== undefined ? Math.max(0, Math.round(run.queueMs)) : null,\n modelMs: null,\n toolsMs: null,\n modelCalls: null,\n toolCalls: null,\n timings: null,\n };\n await this.db.insert(this.t.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: RecordRunEndInput): 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.ttftMs !== undefined) {\n updates.ttftMs = end.ttftMs;\n }\n if (end.costUsd !== undefined) {\n updates.costUsd = end.costUsd;\n }\n if (end.modelId !== undefined) {\n updates.modelId = end.modelId;\n }\n if (end.errorCode !== undefined) {\n updates.errorCode = end.errorCode;\n }\n if (end.errorMessage !== undefined) {\n updates.errorMessage = end.errorMessage;\n }\n if (end.timings !== undefined) {\n updates.modelMs = Math.round(end.timings.modelMs);\n updates.toolsMs = Math.round(end.timings.toolsMs);\n updates.modelCalls = end.timings.modelCalls;\n updates.toolCalls = end.timings.toolCalls;\n updates.timings = end.timings.steps;\n }\n await this.db.update(this.t.agentRun).set(updates).where(eq(this.t.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(this.t.agentRun)\n .set({ retries: sql`${this.t.agentRun.retries} + 1` })\n .where(eq(this.t.agentRun.id, runId));\n }\n\n async appendMessage(input: AppendMessageInput): Promise<StoredMessage> {\n const [thread] = await this.db\n .select()\n .from(this.t.agentThread)\n .where(eq(this.t.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 actionProposalOutcome: input.actionProposalOutcome\n ? canonicalActionProposalJson(input.actionProposalOutcome)\n : null,\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 persona: input.persona ?? null,\n runId: input.runId ?? null,\n reasoning: input.reasoning ?? null,\n reasoningMs: input.reasoningMs ?? null,\n ui: input.ui ?? null,\n feedback: null,\n seq: await this.nextMessageSeq(input.threadId),\n createdAt: now,\n };\n await this.db.insert(this.t.agentMessage).values(message);\n await this.db\n .update(this.t.agentThread)\n .set({ updatedAt: now })\n .where(eq(this.t.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(this.t.agentMessage)\n .set({ toolResults: results })\n .where(eq(this.t.agentMessage.id, messageId));\n }\n\n async setMessageUi(messageId: string, ui: AgentUiComponent[]): Promise<void> {\n await this.db\n .update(this.t.agentMessage)\n .set({ ui: ui.length > 0 ? ui : null })\n .where(eq(this.t.agentMessage.id, messageId));\n }\n\n async threadOfMessage(messageId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ threadId: this.t.agentMessage.threadId })\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.id, messageId))\n .limit(1);\n return row?.threadId ?? null;\n }\n\n async setMessageFeedback(messageId: string, feedback: MessageFeedback | null): Promise<void> {\n await this.db\n .update(this.t.agentMessage)\n .set({ feedback })\n .where(eq(this.t.agentMessage.id, messageId));\n }\n\n async truncateFrom(threadId: string, messageId: string): Promise<void> {\n const messages = await this.db\n .select()\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, threadId))\n .orderBy(...this.messageOrder());\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\n .delete(this.t.agentToolCall)\n .where(inArray(this.t.agentToolCall.messageId, doomedIds));\n await this.db.delete(this.t.agentMessage).where(inArray(this.t.agentMessage.id, doomedIds));\n }\n\n async recordToolCall(input: RecordToolCallInput): Promise<void> {\n await this.db.insert(this.t.agentToolCall).values({\n id: input.toolCallId,\n proposalId: input.proposalId ?? null,\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 approver: input.approver ?? null,\n confirmation: input.confirmation ?? null,\n expiresAt: input.expiresAt !== undefined ? new Date(input.expiresAt) : null,\n remember: null,\n decidedVia: 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.remember !== undefined) {\n updates.remember = input.remember;\n }\n if (input.decidedVia !== undefined) {\n updates.decidedVia = input.decidedVia;\n }\n if (input.status === 'executed' || input.status === 'auto_executed') {\n updates.executedAt = new Date();\n }\n await this.db\n .update(this.t.agentToolCall)\n .set(updates)\n .where(eq(this.t.agentToolCall.id, input.toolCallId));\n }\n\n async toolCallOutcomes(toolCallIds: readonly string[]): Promise<ToolCallOutcome[]> {\n if (toolCallIds.length === 0) {\n return [];\n }\n const rows = await this.db\n .select({\n id: this.t.agentToolCall.id,\n status: this.t.agentToolCall.status,\n output: this.t.agentToolCall.output,\n error: this.t.agentToolCall.error,\n })\n .from(this.t.agentToolCall)\n .where(inArray(this.t.agentToolCall.id, [...toolCallIds]));\n return rows.map((row) => ({\n id: row.id,\n status: row.status,\n ...(row.output !== undefined && row.output !== null ? { output: row.output } : {}),\n ...(typeof row.error === 'string' ? { error: row.error } : {}),\n }));\n }\n\n async failUnsettledToolCalls(runId: string, error: string): Promise<number> {\n const pending = and(\n eq(this.t.agentToolCall.runId, runId),\n eq(this.t.agentToolCall.status, 'pending_approval'),\n );\n // Counted first: an UPDATE's affected-row count is spelled differently by every driver this\n // adapter runs on. The number is informational; the write is what matters.\n const rows = await this.db\n .select({ id: this.t.agentToolCall.id })\n .from(this.t.agentToolCall)\n .where(pending);\n if (rows.length === 0) {\n return 0;\n }\n await this.db.update(this.t.agentToolCall).set({ status: 'failed', error }).where(pending);\n return rows.length;\n }\n\n /**\n * Of `mediaIds`, the ones a surviving message — or a message waiting in the queue — in one of\n * 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: this.t.agentMessage.attachments })\n .from(this.t.agentMessage)\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(\n and(eq(this.t.agentThread.actorRef, actorRef), isNotNull(this.t.agentMessage.attachments)),\n );\n // A message waiting in a thread's queue has been sent and not yet run: what it carries is in use.\n const queued = await this.db\n .select({ attachments: this.t.agentQueuedMessage.attachments })\n .from(this.t.agentQueuedMessage)\n .innerJoin(this.t.agentThread, eq(this.t.agentQueuedMessage.threadId, this.t.agentThread.id))\n .where(\n and(\n eq(this.t.agentThread.actorRef, actorRef),\n isNotNull(this.t.agentQueuedMessage.attachments),\n ),\n );\n const wanted = new Set(mediaIds);\n const found = new Set<string>();\n for (const row of [...rows, ...queued]) {\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(this.t.agentTokenUsage).values({\n id: crypto.randomUUID(),\n threadId: input.threadId ?? null,\n actorRef: input.actorRef,\n messageId: input.messageId ?? null,\n runId: input.runId ?? null,\n feature: input.feature ?? null,\n provider: input.provider ?? null,\n tenantRef: input.tenantRef ?? null,\n audioSeconds: input.audioSeconds ?? null,\n characters: input.characters ?? null,\n requests: input.requests ?? null,\n metadata: input.metadata ?? null,\n countsTowardsQuota: input.countsTowardsQuota !== false,\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 costSource: input.costUsd !== undefined ? (input.costSource ?? 'provider') : null,\n createdAt: new Date(),\n });\n }\n\n /**\n * Generative-UI telemetry: one `agent_genui_call` row per UI tool call, upserted by its tool call\n * id — a replayed record replaces the row (keeping the first `created_at`) rather than adding one.\n */\n async recordGenuiCalls(rows: readonly RecordGenuiCallInput[]): Promise<void> {\n const table = this.t.agentGenuiCall;\n for (const row of rows) {\n const columns = {\n runId: row.runId,\n threadId: row.threadId,\n actorRef: row.actorRef,\n agentName: row.agentName ?? null,\n step: row.step,\n toolName: row.toolName,\n channel: row.channel,\n mode: row.mode,\n modelId: row.modelId,\n attempt: row.attempt,\n outcome: row.outcome,\n validity: row.validity,\n errorCategory: row.errorCategory ?? null,\n errorMessage: row.errorMessage ?? null,\n inputTokens: row.inputTokens,\n outputTokens: row.outputTokens,\n costUsd: row.costUsd ?? null,\n costSource: row.costSource ?? null,\n firstFrameMs: row.firstFrameMs ?? null,\n completeFrameMs: row.completeFrameMs ?? null,\n payloadBytes: row.payloadBytes,\n payload: row.payload ?? null,\n };\n await upsert(\n this.dialect,\n this.db.insert(table).values({ id: row.toolCallId, ...columns, createdAt: Date.now() }),\n table.id,\n columns,\n );\n }\n }\n\n async quotaToday(actorRef: string, day: string): Promise<UsageTotals> {\n return this.usageBetween(actorRef, day, day);\n }\n\n async usageBetween(actorRef: string, fromDay: string, toDay: string): Promise<UsageTotals> {\n const [totals] = await this.usageWindows(actorRef, [{ fromDay, toDay }]);\n return totals ?? sumUsage([]);\n }\n\n /**\n * Every range summed by the database in one statement, each as a conditional aggregate over the\n * rows of the smallest span covering them all — the actor's `(actor_ref, created_at)` index serves\n * it, and no usage row crosses the wire.\n */\n async usageWindows(\n actorRef: string,\n ranges: readonly { fromDay: string; toDay: string }[],\n ): Promise<UsageTotals[]> {\n return this.sumUsageWindows(eq(this.t.agentTokenUsage.actorRef, actorRef), ranges);\n }\n\n /**\n * {@link usageWindows} over the tenant's rows (every actor's, or `actorRef`'s only), served by the\n * `(tenant_ref, created_at)` index.\n */\n async usageWindowsForTenant(\n tenantRef: string,\n ranges: readonly { fromDay: string; toDay: string }[],\n actorRef?: string,\n ): Promise<UsageTotals[]> {\n const usage = this.t.agentTokenUsage;\n return this.sumUsageWindows(\n and(\n eq(usage.tenantRef, tenantRef),\n actorRef !== undefined ? eq(usage.actorRef, actorRef) : undefined,\n ) as SQL,\n ranges,\n );\n }\n\n private async sumUsageWindows(\n owner: SQL,\n ranges: readonly { fromDay: string; toDay: string }[],\n ): Promise<UsageTotals[]> {\n if (ranges.length === 0) {\n return [];\n }\n const usage = this.t.agentTokenUsage;\n const bounds = ranges.map(({ fromDay, toDay }) => ({\n start: new Date(`${fromDay}T00:00:00.000Z`),\n end: new Date(`${toDay}T23:59:59.999Z`),\n }));\n const within = (start: Date, end: Date) =>\n and(gte(usage.createdAt, start), lte(usage.createdAt, end));\n const columns: Record<string, SQL> = {};\n bounds.forEach(({ start, end }, index) => {\n columns[`tokens${index}`] =\n sql`sum(case when ${within(start, end)} then ${usage.inputTokens} + ${usage.outputTokens} else 0 end)`;\n columns[`cost${index}`] =\n sql`sum(case when ${within(start, end)} then ${usage.costUsd} else 0 end)`;\n columns[`estimated${index}`] =\n sql`sum(case when ${within(start, end)} and ${usage.costSource} = 'estimate' then ${usage.costUsd} else 0 end)`;\n });\n const from = new Date(Math.min(...bounds.map(({ start }) => start.getTime())));\n const to = new Date(Math.max(...bounds.map(({ end }) => end.getTime())));\n const [row] = (await this.db\n .select(columns)\n .from(usage)\n // The rows a quota window counts: a filter on the rows the (actor_ref, created_at) or\n // (tenant_ref, created_at) index already narrows to one owner's window.\n .where(and(owner, within(from, to), eq(usage.countsTowardsQuota, true)))) as Record<\n string,\n unknown\n >[];\n return bounds.map((_, index) => ({\n usedTokens: Number(row?.[`tokens${index}`] ?? 0),\n costUsd: Number(row?.[`cost${index}`] ?? 0),\n estimatedCostUsd: Number(row?.[`estimated${index}`] ?? 0),\n }));\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 ...(thread.model != null ? { model: thread.model } : {}),\n persona: thread.persona ?? null,\n ...(lastContent !== undefined ? { lastMessagePreview: lastContent.slice(0, 120) } : {}),\n };\n }\n\n private toStoredMessage(message: TurnMessageRow & Partial<AgentMessageRow>): StoredMessage {\n const outcome = message.actionProposalOutcome\n ? (JSON.parse(message.actionProposalOutcome) as NonNullable<\n StoredMessage['actionProposalOutcome']\n >)\n : undefined;\n return {\n ...(outcome ? { actionProposalOutcome: outcome, ui: outcome.ui } : {}),\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.persona != null ? { persona: message.persona } : {}),\n ...(message.runId != null ? { runId: message.runId } : {}),\n ...(message.reasoning != null ? { reasoning: message.reasoning } : {}),\n ...(message.reasoningMs != null ? { reasoningMs: message.reasoningMs } : {}),\n ...(message.ui != null ? { ui: message.ui } : {}),\n ...(message.feedback != null ? { feedback: message.feedback } : {}),\n };\n }\n}\n\nfunction toQueuedMessage(row: AgentQueuedMessageRow): QueuedMessage {\n return {\n ...(row.uiCapabilities !== null ? { uiCapabilities: row.uiCapabilities } : {}),\n ...(row.hostContext != null ? { hostContext: row.hostContext } : {}),\n id: row.id,\n threadId: row.threadId,\n actor: row.actor,\n content: row.content,\n ...(row.attachments !== null && row.attachments.length > 0\n ? { attachments: row.attachments }\n : {}),\n ...(row.agentName !== null ? { agentName: row.agentName } : {}),\n ...(row.persona !== null ? { persona: row.persona } : {}),\n ...(row.model !== null ? { model: row.model } : {}),\n ...(row.pageContext !== null ? { pageContext: row.pageContext } : {}),\n ...(row.interrupt ? { interrupt: true } : {}),\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n };\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport {\n type ActionProposal,\n type ActionProposalDecisionCommand,\n type ActionProposalDiscoveryIndexStore,\n type ActionProposalMutationResult,\n type ActionProposalOutcomeLease,\n type ActionProposalOutcomeStore,\n type ActionProposalScope,\n type ActionProposalStore,\n type ActionProposalStoreOptions,\n type ActionProposalSupersessionStore,\n type ActionProposalWorkerStore,\n type ClaimActionProposal,\n type CreateActionProposal,\n type CreateActionProposalResult,\n type ExtendActionProposalLease,\n type ListActionProposals,\n type SettleActionProposal,\n actionProposalOutcomeFenceValid,\n actionProposalOutcomeText,\n actionProposalScopeMatches,\n canonicalActionProposalJson,\n claimActionProposalOutcome,\n initialActionProposal,\n toolCallUpdateForTransition,\n transitionActionProposalClaim,\n transitionActionProposalDecision,\n transitionActionProposalLease,\n transitionActionProposalSettlement,\n transitionActionProposalSupersession,\n validateActionProposalDiscoveryIndexBatch,\n validateActionProposalExpiryBatch,\n validateActionProposalListQuery,\n validateActionProposalWorkerClaim,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, entityKind, eq, gt, isNull, lte, max, or, sql } from 'drizzle-orm';\nimport { actionProposalTransactionMode } from './action-proposal-transaction-mode.js';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n mysqlAffectedRows,\n} from './dialect.js';\n\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\ntype ProposalRow = AgentTables['agentActionProposal']['$inferSelect'];\n\n/**\n * Independent persisted proposals. Each decision and its durable execution work live in one row;\n * a version predicate fences every read/modify/write across connections and store instances.\n */\nexport class DrizzleActionProposalStore\n implements\n ActionProposalStore,\n ActionProposalWorkerStore,\n ActionProposalDiscoveryIndexStore,\n ActionProposalSupersessionStore\n{\n private readonly db: AgentSqliteDb;\n private readonly rawDb: AgentDrizzleDb;\n readonly actionProposalAdmissionSupported: boolean;\n private readonly synchronousSqlite: boolean;\n private readonly dialect: AgentDialect;\n private readonly table: AgentTables['agentActionProposal'];\n private readonly clock: () => number;\n\n constructor(db: AgentDrizzleDb, options: ActionProposalStoreOptions = {}) {\n this.rawDb = db;\n const kind = (db.constructor as unknown as Record<symbol, string>)[entityKind];\n const transactionMode = actionProposalTransactionMode(kind);\n this.synchronousSqlite = transactionMode === 'sync';\n this.actionProposalAdmissionSupported = transactionMode !== 'unsupported';\n this.dialect = agentDialectOf(db);\n this.table = agentTablesFor(this.dialect).agentActionProposal;\n this.db = asBuilder(db);\n this.clock = options.clock ?? Date.now;\n }\n\n async createActionProposal(input: CreateActionProposal): Promise<CreateActionProposalResult> {\n const proposal = initialActionProposal(input, this.clock());\n const row = {\n id: physicalId(input.id),\n scopeKey: scopeKey(input),\n decision: proposal.decision,\n logicalSort: logicalSort(input.id),\n createFingerprint: canonicalActionProposalJson(input),\n proposal,\n ...discoveryMetadata(proposal),\n version: 0,\n createdAt: proposal.createdAt,\n };\n const table = this.table;\n const insert = this.db.insert(table);\n const inserted =\n this.dialect === 'mysql'\n ? mysqlAffectedRows(\n await (insert as unknown as MySqlInsertIgnore<typeof row>).ignore().values(row),\n )\n : await affectedRows(this.dialect, insert.values(row).onConflictDoNothing(), table.id);\n const stored = await this.read(input, input.id);\n if (!stored) return { status: 'conflict' };\n if (inserted === 1) return { status: 'created', proposal: stored.proposal };\n return {\n status: stored.createFingerprint === row.createFingerprint ? 'unchanged' : 'conflict',\n proposal: stored.proposal,\n };\n }\n\n createReplacingActionProposal(input: CreateActionProposal): Promise<CreateActionProposalResult> {\n if (!input.replacementKey) return this.createActionProposal(input);\n const proposal = initialActionProposal(input, this.clock());\n return this.transactionSteps((db) => this.replacementSteps(db, input, proposal));\n }\n\n async supersedeActionProposal(\n scope: ActionProposalScope,\n id: string,\n command: { replacementProposalId: string; actorRef: string; via: string },\n ): Promise<ActionProposalMutationResult> {\n const replacement = await this.getActionProposal(scope, command.replacementProposalId);\n if (!replacement) return { status: 'not_found' };\n return this.mutate(scope, id, (row, now) =>\n transitionActionProposalSupersession(row, replacement, command, now),\n );\n }\n\n private *replacementSteps(\n db: AgentSqliteDb,\n input: CreateActionProposal,\n proposal: ActionProposal,\n ): Generator<AdmissionQuery, CreateActionProposalResult, unknown> {\n const table = this.table;\n const thread = agentTablesFor(this.dialect).agentThread;\n // The shared conversation admission row serializes new replacements within this scope.\n if (this.dialect === 'sqlite')\n yield {\n kind: 'write',\n query: db\n .update(thread)\n .set({ updatedAt: sql`${thread.updatedAt}` })\n .where(eq(thread.id, input.threadId)),\n };\n const threads = (yield {\n kind: 'read',\n query: lockQuery(\n db.select().from(thread).where(eq(thread.id, input.threadId)).limit(1),\n this.dialect,\n ),\n }) as Array<AgentTables['agentThread']['$inferSelect']>;\n const owner = threads[0];\n if (\n !owner ||\n owner.id !== input.threadId ||\n owner.deletedAt ||\n owner.actorRef !== input.actorRef ||\n owner.tenantRef !== input.tenantRef\n )\n return { status: 'conflict' };\n const existingRows = (yield {\n kind: 'read',\n query: db\n .select()\n .from(table)\n .where(eq(table.id, physicalId(input.id)))\n .limit(1),\n }) as ProposalRow[];\n const existing = existingRows[0];\n if (existing) {\n if (\n existing.proposal.id !== input.id ||\n !actionProposalScopeMatches(existing.proposal, input)\n )\n return { status: 'conflict' };\n return {\n status:\n existing.createFingerprint === canonicalActionProposalJson(input)\n ? 'unchanged'\n : 'conflict',\n proposal: existing.proposal,\n };\n }\n const groupKey = replacementGroupKey(input);\n if (groupKey === null) throw new Error('Missing explicit replacement identity');\n const pending = (yield {\n kind: 'read',\n query: lockQuery(\n db\n .select()\n .from(table)\n .where(\n and(\n eq(table.scopeKey, scopeKey(input)),\n eq(table.replacementGroupKey, groupKey),\n eq(table.decision, 'pending'),\n ),\n ),\n this.dialect,\n ),\n }) as ProposalRow[];\n const row = {\n id: physicalId(input.id),\n scopeKey: scopeKey(input),\n decision: proposal.decision,\n logicalSort: logicalSort(input.id),\n createFingerprint: canonicalActionProposalJson(input),\n proposal,\n ...discoveryMetadata(proposal),\n version: 0,\n createdAt: proposal.createdAt,\n };\n const insert = db.insert(table);\n const inserted = yield {\n kind: 'read',\n query:\n this.dialect === 'mysql'\n ? (insert as unknown as MySqlInsertIgnore<typeof row>).ignore().values(row)\n : insert.values(row).onConflictDoNothing().returning({ id: table.id }),\n };\n const count =\n this.dialect === 'mysql' ? mysqlAffectedRows(inserted) : (inserted as unknown[]).length;\n if (count !== 1) return { status: 'conflict' };\n for (const old of pending) {\n const result = transitionActionProposalSupersession(\n old.proposal,\n proposal,\n { replacementProposalId: proposal.id, actorRef: proposal.actorRef, via: 'replacement' },\n this.clock(),\n );\n if (\n !result.proposal ||\n canonicalActionProposalJson(result.proposal) === canonicalActionProposalJson(old.proposal)\n )\n continue;\n const next = result.proposal;\n const update = db\n .update(table)\n .set({\n proposal: next,\n decision: next.decision,\n ...discoveryMetadata(next),\n version: old.version + 1,\n })\n .where(and(eq(table.id, old.id), eq(table.version, old.version)));\n const updated = yield {\n kind: 'read',\n query: this.dialect === 'mysql' ? update : update.returning({ id: table.id }),\n };\n if (\n (this.dialect === 'mysql' ? mysqlAffectedRows(updated) : (updated as unknown[]).length) !==\n 1\n )\n throw new Error('Replacement lost its locked proposal fence');\n const settled = this.toolCallSettlement(db, old.proposal, next);\n if (settled) yield { kind: 'write', query: settled };\n }\n return { status: 'created', proposal };\n }\n\n async getActionProposal(scope: ActionProposalScope, id: string): Promise<ActionProposal | null> {\n return (await this.read(scope, id))?.proposal ?? null;\n }\n\n async listActionProposals(\n scope: ActionProposalScope,\n query: ListActionProposals = {},\n ): Promise<ActionProposal[]> {\n const limit = validateActionProposalListQuery(query);\n const rows = await this.db\n .select()\n .from(this.table)\n .where(\n and(\n eq(this.table.scopeKey, scopeKey(scope)),\n query.after === undefined\n ? undefined\n : or(\n gt(this.table.createdAt, query.after.createdAt),\n and(\n eq(this.table.createdAt, query.after.createdAt),\n gt(this.table.logicalSort, logicalSort(query.after.id)),\n ),\n ),\n query.decision === undefined ? undefined : eq(this.table.decision, query.decision),\n ),\n )\n .orderBy(asc(this.table.createdAt), asc(this.table.logicalSort))\n .limit(limit);\n return rows\n .map((row) => row.proposal)\n .filter((proposal) => actionProposalScopeMatches(proposal, scope));\n }\n\n decideActionProposal(\n scope: ActionProposalScope,\n id: string,\n command: ActionProposalDecisionCommand,\n ): Promise<ActionProposalMutationResult> {\n return this.mutate(scope, id, (row, now) =>\n transitionActionProposalDecision(row, command, now),\n );\n }\n\n claimActionProposal(\n scope: ActionProposalScope,\n id: string,\n command: ClaimActionProposal,\n ): Promise<ActionProposalMutationResult> {\n return this.mutate(scope, id, (row, now) =>\n transitionActionProposalClaim(row, command, now, randomUUID()),\n );\n }\n\n extendActionProposalLease(\n scope: ActionProposalScope,\n id: string,\n command: ExtendActionProposalLease,\n ): Promise<ActionProposalMutationResult> {\n return this.mutate(scope, id, (row, now) => transitionActionProposalLease(row, command, now));\n }\n\n settleActionProposal(\n scope: ActionProposalScope,\n id: string,\n command: SettleActionProposal,\n ): Promise<ActionProposalMutationResult> {\n return this.mutate(scope, id, (row, now) =>\n transitionActionProposalSettlement(row, command, now),\n );\n }\n\n async claimNextActionProposal(command: ClaimActionProposal): Promise<ActionProposal | null> {\n const now = this.clock();\n validateActionProposalWorkerClaim(command, now);\n const table = this.table;\n const candidates = await this.db\n .select()\n .from(table)\n .where(\n and(\n eq(table.discoveryIndexVersion, 1),\n eq(table.decision, 'approved'),\n or(\n eq(table.executionStatus, 'queued'),\n and(eq(table.executionStatus, 'executing'), lte(table.leaseExpiresAt, now)),\n ),\n ),\n )\n .orderBy(asc(table.createdAt), asc(table.logicalSort))\n .limit(32);\n for (const candidate of candidates) {\n const result = await this.claimActionProposal(\n candidate.proposal,\n candidate.proposal.id,\n command,\n );\n if (result.status === 'applied' && result.proposal) return result.proposal;\n }\n return null;\n }\n\n async expireActionProposals(command: { limit: number }): Promise<number> {\n const now = this.clock();\n validateActionProposalExpiryBatch(command, now);\n const table = this.table;\n const candidates = await this.db\n .select()\n .from(table)\n .where(\n and(\n eq(table.discoveryIndexVersion, 1),\n eq(table.decision, 'pending'),\n lte(table.proposalExpiresAt, now),\n ),\n )\n .orderBy(asc(table.createdAt), asc(table.logicalSort))\n .limit(command.limit);\n let expired = 0;\n for (const candidate of candidates) {\n const result = await this.decideActionProposal(candidate.proposal, candidate.proposal.id, {\n decision: 'expired',\n actorRef: 'system',\n via: 'expiry',\n });\n if (result.status === 'applied') expired++;\n }\n return expired;\n }\n\n async backfillActionProposalDiscoveryIndex(command: { limit: number }): Promise<number> {\n validateActionProposalDiscoveryIndexBatch(command);\n const table = this.table;\n const candidates = await this.db\n .select()\n .from(table)\n .where(eq(table.discoveryIndexVersion, 0))\n .orderBy(asc(table.createdAt), asc(table.logicalSort))\n .limit(command.limit);\n let changed = 0;\n for (const row of candidates) {\n changed += await affectedRows(\n this.dialect,\n this.db\n .update(table)\n .set({\n ...discoveryMetadata(row.proposal),\n version: row.version + 1,\n })\n .where(\n and(\n eq(table.id, row.id),\n eq(table.scopeKey, row.scopeKey),\n eq(table.version, row.version),\n eq(table.discoveryIndexVersion, 0),\n ),\n ),\n table.id,\n );\n }\n return changed;\n }\n\n async rememberedActionProposalApprovals(scope: ActionProposalScope): Promise<string[]> {\n const table = this.table;\n const rows = await this.db\n .select()\n .from(table)\n .where(\n and(\n eq(table.scopeKey, scopeKey(scope)),\n eq(table.decision, 'approved'),\n or(eq(table.executionStatus, 'succeeded'), eq(table.executionStatus, 'failed')),\n ),\n );\n return [\n ...new Set(\n rows\n .filter(\n (row) =>\n actionProposalScopeMatches(row.proposal, scope) &&\n row.proposal.decisionAudit?.remember === true,\n )\n .map((row) => row.proposal.toolName),\n ),\n ];\n }\n\n async getThreadActionProposalScope(threadId: string) {\n const thread = agentTablesFor(this.dialect).agentThread;\n const [row] = await this.db\n .select()\n .from(thread)\n .where(and(eq(thread.id, threadId), isNull(thread.deletedAt)))\n .limit(1);\n return row?.id === threadId\n ? { actorRef: row.actorRef, tenantRef: row.tenantRef, threadId: row.id }\n : null;\n }\n\n async claimNextActionProposalOutcome(command: ClaimActionProposal) {\n const now = this.clock();\n validateActionProposalWorkerClaim(command, now);\n const table = this.table;\n const candidates = await this.db\n .select()\n .from(table)\n .where(\n and(\n eq(table.deliveryStatus, 'pending'),\n or(isNull(table.deliveryLeaseExpiresAt), lte(table.deliveryLeaseExpiresAt, now)),\n ),\n )\n .orderBy(asc(table.createdAt), asc(table.logicalSort))\n .limit(32);\n for (const row of candidates) {\n const result = await this.mutate(row.proposal, row.proposal.id, (proposal, time) => {\n const claimed = claimActionProposalOutcome(proposal, command, time, randomUUID());\n return claimed\n ? { status: 'applied', proposal: claimed }\n : { status: 'conflict', proposal };\n });\n const claimed = result.proposal;\n if (result.status === 'applied' && claimed?.outcome && claimed.outcomeDelivery?.lease) {\n return {\n outcome: claimed.outcome,\n lease: {\n outcomeId: claimed.outcome.id,\n token: claimed.outcomeDelivery.lease.token,\n generation: claimed.outcomeDelivery.generation,\n },\n };\n }\n }\n return null;\n }\n\n async admitActionProposalOutcome(\n command: ActionProposalOutcomeLease,\n ): ReturnType<ActionProposalOutcomeStore['admitActionProposalOutcome']> {\n return this.transactionSteps((db) => this.admissionSteps(db, command));\n }\n\n private async transactionSteps<T>(\n factory: (db: AgentSqliteDb) => Generator<AdmissionQuery, T, unknown>,\n ): Promise<T> {\n if (!this.actionProposalAdmissionSupported)\n throw new Error(\n 'Independent actions require a certified transactional Drizzle driver (better-sqlite3, node-postgres, mysql2 or libsql)',\n );\n if (this.synchronousSqlite) {\n const database = this.rawDb as unknown as {\n transaction<R>(callback: (tx: AgentDrizzleDb) => R, config?: { behavior: 'immediate' }): R;\n };\n return database.transaction((tx) => runSync(factory(asBuilder(tx))), {\n behavior: 'immediate',\n });\n }\n const database = this.rawDb as unknown as {\n transaction<R>(callback: (tx: AgentDrizzleDb) => Promise<R>): Promise<R>;\n };\n return database.transaction(async (tx) => runAsync(factory(asBuilder(tx))));\n }\n\n private *admissionSteps(\n db: AgentSqliteDb,\n command: ActionProposalOutcomeLease,\n ): Generator<\n AdmissionQuery,\n Awaited<ReturnType<ActionProposalOutcomeStore['admitActionProposalOutcome']>>,\n unknown\n > {\n if (\n typeof command.outcomeId !== 'string' ||\n !command.outcomeId ||\n typeof command.token !== 'string' ||\n !command.token ||\n !Number.isSafeInteger(command.generation) ||\n command.generation < 1\n )\n throw new TypeError('Invalid outcome fence');\n const table = this.table;\n const tables = agentTablesFor(this.dialect);\n // Write first on asynchronous SQLite too; serialize before reading the proposal or thread.\n if (this.dialect === 'sqlite')\n yield {\n kind: 'write',\n query: db\n .update(table)\n .set({ version: sql`${table.version}` })\n .where(eq(table.outcomeIdKey, physicalId(command.outcomeId))),\n };\n const query = db\n .select()\n .from(table)\n .where(eq(table.outcomeIdKey, physicalId(command.outcomeId)))\n .limit(1);\n const rows = (yield { kind: 'read', query: lockQuery(query, this.dialect) }) as ProposalRow[];\n const row = rows[0];\n if (!row || row.proposal.outcome?.id !== command.outcomeId) return { status: 'not_found' };\n const proposal = row.proposal;\n const outcome = proposal.outcome;\n const delivery = proposal.outcomeDelivery;\n if (!outcome || !delivery) return { status: 'not_found' };\n if (proposal.outcomeDelivery?.status === 'admitted')\n return {\n status: 'unchanged',\n ...(proposal.outcomeDelivery.messageId !== undefined\n ? { messageId: proposal.outcomeDelivery.messageId }\n : {}),\n };\n if (proposal.outcomeDelivery?.status === 'discarded') return { status: 'discarded' };\n if (!actionProposalOutcomeFenceValid(proposal, command, this.clock()))\n return { status: 'conflict' };\n const threadQuery = db\n .select()\n .from(tables.agentThread)\n .where(eq(tables.agentThread.id, proposal.threadId))\n .limit(1);\n const threads = (yield { kind: 'read', query: lockQuery(threadQuery, this.dialect) }) as Array<\n AgentTables['agentThread']['$inferSelect']\n >;\n const thread = threads[0];\n // Locks may have waited beyond the lease; never use the earlier timestamp to admit.\n const now = this.clock();\n if (!actionProposalOutcomeFenceValid(proposal, command, now)) return { status: 'conflict' };\n if (\n !thread ||\n thread.id !== proposal.threadId ||\n thread.deletedAt ||\n thread.actorRef !== proposal.actorRef ||\n thread.tenantRef !== proposal.tenantRef\n ) {\n const discarded: ActionProposal = {\n ...proposal,\n outcomeDelivery: { ...delivery, status: 'discarded', lease: null },\n updatedAt: now,\n };\n yield {\n kind: 'write',\n query: db\n .update(table)\n .set({ proposal: discarded, ...discoveryMetadata(discarded), version: row.version + 1 })\n .where(and(eq(table.id, row.id), eq(table.version, row.version))),\n };\n return { status: 'discarded' };\n }\n if (thread.activeStreamId !== null) return { status: 'busy' };\n const seqRows = (yield {\n kind: 'read',\n query: db\n .select({ last: max(tables.agentMessage.seq) })\n .from(tables.agentMessage)\n .where(eq(tables.agentMessage.threadId, thread.id)),\n }) as Array<{ last: number | null }>;\n const messageId = physicalId(command.outcomeId);\n yield {\n kind: 'write',\n query: db.insert(tables.agentMessage).values({\n id: messageId,\n threadId: thread.id,\n role: 'assistant',\n content: actionProposalOutcomeText(outcome),\n actionProposalOutcome: canonicalActionProposalJson(outcome),\n ui: null,\n seq: Number(seqRows[0]?.last ?? 0) + 1,\n createdAt: new Date(now),\n }),\n };\n yield {\n kind: 'write',\n query: db\n .update(tables.agentThread)\n .set({ updatedAt: new Date(now) })\n .where(eq(tables.agentThread.id, thread.id)),\n };\n const admitted: ActionProposal = {\n ...proposal,\n outcomeDelivery: { ...delivery, status: 'admitted', lease: null, messageId },\n updatedAt: now,\n };\n const update = db\n .update(table)\n .set({ proposal: admitted, ...discoveryMetadata(admitted), version: row.version + 1 })\n .where(and(eq(table.id, row.id), eq(table.version, row.version)));\n const changed = yield {\n kind: 'read',\n query: this.dialect === 'mysql' ? update : update.returning({ id: table.id }),\n };\n const count =\n this.dialect === 'mysql' ? mysqlAffectedRows(changed) : (changed as unknown[]).length;\n if (count !== 1) throw new Error('Outcome admission lost its locked proposal fence');\n return { status: 'applied', messageId };\n }\n\n /**\n * The update that settles the proposal's `proposed` tool-call record after a transition from\n * `previous` to `next` (see `toolCallUpdateForTransition`), or `undefined` when its status stays —\n * so the dashboard and run detail show `executed` / `failed` / `rejected` / `expired` instead of\n * `proposed` forever.\n */\n private toolCallSettlement(db: AgentSqliteDb, previous: ActionProposal, next: ActionProposal) {\n const update = toolCallUpdateForTransition(previous, next);\n if (update === null) return undefined;\n const toolCall = agentTablesFor(this.dialect).agentToolCall;\n return db\n .update(toolCall)\n .set({\n status: update.status,\n ...(update.output !== undefined ? { output: update.output } : {}),\n ...(update.error !== undefined ? { error: update.error } : {}),\n ...(update.executedByRef !== undefined ? { executedByRef: update.executedByRef } : {}),\n ...(update.decidedVia !== undefined ? { decidedVia: update.decidedVia } : {}),\n ...(update.remember !== undefined ? { remember: update.remember } : {}),\n ...(update.status === 'executed' ? { executedAt: new Date(this.clock()) } : {}),\n })\n .where(and(eq(toolCall.id, update.toolCallId), eq(toolCall.proposalId, next.id)));\n }\n\n private async read(scope: ActionProposalScope, id: string): Promise<ProposalRow | undefined> {\n const [row] = await this.db\n .select()\n .from(this.table)\n .where(and(eq(this.table.id, physicalId(id)), eq(this.table.scopeKey, scopeKey(scope))))\n .limit(1);\n return row && row.proposal.id === id && actionProposalScopeMatches(row.proposal, scope)\n ? row\n : undefined;\n }\n\n private async mutate(\n scope: ActionProposalScope,\n id: string,\n transition: (proposal: ActionProposal, now: number) => ActionProposalMutationResult,\n ): Promise<ActionProposalMutationResult> {\n // A caller repeatable-read transaction may retain its original snapshot after losing CAS.\n // Bound retries so that transaction returns a conflict instead of spinning indefinitely.\n for (let attempt = 0; attempt < 32; attempt++) {\n const row = await this.read(scope, id);\n if (!row) return { status: 'not_found' };\n // Recompute the trusted clock after every lost CAS, so a delayed retry cannot approve or\n // settle a proposal using the time observed before another writer advanced it.\n const result = transition(row.proposal, this.clock());\n if (\n !result.proposal ||\n canonicalActionProposalJson(result.proposal) === canonicalActionProposalJson(row.proposal)\n )\n return result;\n const changed = await affectedRows(\n this.dialect,\n this.db\n .update(this.table)\n .set({\n proposal: result.proposal,\n decision: result.proposal.decision,\n ...discoveryMetadata(result.proposal),\n version: row.version + 1,\n })\n .where(\n and(\n eq(this.table.id, physicalId(id)),\n eq(this.table.scopeKey, scopeKey(scope)),\n eq(this.table.version, row.version),\n ),\n ),\n this.table.id,\n );\n // Return this operation's winning fence, never a peer's later recovery token.\n if (changed === 1) {\n await this.toolCallSettlement(this.db, row.proposal, result.proposal);\n return result;\n }\n }\n const row = await this.read(scope, id);\n return row ? { status: 'conflict', proposal: row.proposal } : { status: 'not_found' };\n }\n}\n\nfunction scopeKey(scope: ActionProposalScope): string {\n return createHash('sha256')\n .update(canonicalActionProposalJson([scope.tenantRef, scope.actorRef, scope.threadId]))\n .digest('hex');\n}\n\nfunction physicalId(id: string): string {\n return createHash('sha256').update(canonicalActionProposalJson(id)).digest('hex');\n}\n\n/** Hex UTF16 code units preserve the core's JavaScript lexical ID order in every SQL dialect. */\nfunction logicalSort(id: string): string {\n let sort = '';\n for (let index = 0; index < id.length; index++)\n sort += id.charCodeAt(index).toString(16).padStart(4, '0');\n return sort;\n}\n\nfunction discoveryMetadata(proposal: ActionProposal) {\n return {\n replacementGroupKey: replacementGroupKey(proposal),\n deliveryStatus: proposal.outcomeDelivery?.status ?? null,\n deliveryLeaseExpiresAt: proposal.outcomeDelivery?.lease?.expiresAt ?? null,\n outcomeIdKey: proposal.outcome ? physicalId(proposal.outcome.id) : null,\n executionStatus: proposal.execution?.status ?? null,\n leaseExpiresAt: proposal.execution?.lease?.expiresAt ?? null,\n proposalExpiresAt: proposal.expiresAt,\n discoveryIndexVersion: 1,\n };\n}\n\ninterface AdmissionQuery {\n kind: 'read' | 'write';\n query: PromiseLike<unknown>;\n}\nfunction lockQuery(query: PromiseLike<unknown>, dialect: AgentDialect): PromiseLike<unknown> {\n return dialect === 'sqlite'\n ? query\n : (query as unknown as { for(mode: 'update'): PromiseLike<unknown> }).for('update');\n}\nfunction runSync<T>(steps: Generator<AdmissionQuery, T, unknown>): T {\n let next = steps.next();\n while (!next.done) {\n const { kind, query } = next.value;\n const statement = query as unknown as { all(): unknown; run(): unknown };\n next = steps.next(kind === 'read' ? statement.all() : statement.run());\n }\n return next.value;\n}\nasync function runAsync<T>(steps: Generator<AdmissionQuery, T, unknown>): Promise<T> {\n let next = steps.next();\n while (!next.done) next = steps.next(await next.value.query);\n return next.value;\n}\n\nfunction replacementGroupKey(\n proposal: Pick<CreateActionProposal, 'toolName' | 'replacementKey'>,\n): string | null {\n return proposal.replacementKey\n ? physicalId(canonicalActionProposalJson([proposal.toolName, proposal.replacementKey]))\n : null;\n}\n","/** Explicitly certified drivers; unknown/synchronous drivers must never receive an async callback. */\nexport function actionProposalTransactionMode(\n kind: string | undefined,\n): 'sync' | 'async' | 'unsupported' {\n if (kind === 'BetterSQLite3Database' || kind === 'BetterSQLiteTransaction') return 'sync';\n if (\n kind !== undefined &&\n [\n 'NodePgDatabase',\n 'NodePgTransaction',\n 'PostgresJsDatabase',\n 'PostgresJsTransaction',\n 'MySql2Database',\n 'MySql2Transaction',\n 'LibSQLDatabase',\n 'LibSQLTransaction',\n ].includes(kind)\n )\n return 'async';\n return 'unsupported';\n}\n","import type {\n ActorSpendRow,\n AgentGovernanceQueries,\n AgentPricingStore,\n ApprovalWhere,\n FeatureSpendRow,\n GenuiCallRow,\n GenuiStats,\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 RunTimings,\n RunToolCallRow,\n RunTrendPoint,\n RunWhere,\n TenantRowFilter,\n ThreadActivityRow,\n ThreadMessageRow,\n ThreadMeta,\n ThreadSpendRow,\n ThreadWhere,\n TimestampRange,\n ToolCallActivityRow,\n ToolCallStatus,\n ToolCallWhere,\n ToolKind,\n ToolStatRow,\n UsageBreakdownFilter,\n UsageBreakdownRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n bucketByActor,\n bucketByFeature,\n bucketByModel,\n bucketByThread,\n bucketUsageBreakdown,\n bucketUsageTrend,\n dayBoundsUtc,\n rollupThreadUsage,\n summarizeGenuiCalls,\n truncateDetailContent,\n usageRangeBounds,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n type Column,\n type SQL,\n and,\n asc,\n count,\n desc,\n eq,\n gte,\n inArray,\n isNull,\n like,\n lt,\n lte,\n or,\n sql,\n sum,\n} from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n} from './dialect.js';\nimport {\n type AgentRunStatus,\n agentGenuiCall,\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 'proposed',\n 'auto_executed',\n 'pending_approval',\n 'executed',\n 'rejected',\n 'failed',\n 'expired',\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 an `agent_genui_call` row onto the core row: a NULL column is an absent field. */\nfunction toGenuiCallRow(row: typeof agentGenuiCall.$inferSelect): GenuiCallRow {\n return {\n toolCallId: row.id,\n runId: row.runId,\n threadId: row.threadId,\n actorRef: row.actorRef,\n ...(row.agentName !== null ? { agentName: row.agentName } : {}),\n step: Number(row.step),\n toolName: row.toolName,\n channel: row.channel,\n mode: row.mode,\n modelId: row.modelId,\n attempt: Number(row.attempt),\n outcome: row.outcome,\n validity: row.validity,\n ...(row.errorCategory !== null ? { errorCategory: row.errorCategory } : {}),\n ...(row.errorMessage !== null ? { errorMessage: row.errorMessage } : {}),\n inputTokens: Number(row.inputTokens),\n outputTokens: Number(row.outputTokens),\n ...(row.costUsd !== null ? { costUsd: Number(row.costUsd) } : {}),\n ...(row.costSource !== null ? { costSource: row.costSource } : {}),\n ...(row.firstFrameMs !== null ? { firstFrameMs: Number(row.firstFrameMs) } : {}),\n ...(row.completeFrameMs !== null ? { completeFrameMs: Number(row.completeFrameMs) } : {}),\n payloadBytes: Number(row.payloadBytes),\n ...(row.payload !== null ? { payload: row.payload } : {}),\n createdAt: new Date(Number(row.createdAt)),\n };\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 ttftMs: run.ttftMs ?? null,\n // MySQL's DOUBLE and Postgres' double precision come back as numbers; a driver that hands a\n // decimal back as a string is normalized here so the SPI row is always a number.\n costUsd: run.costUsd == null ? null : Number(run.costUsd),\n modelId: run.modelId ?? 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 queueMs: run.queueMs ?? null,\n modelMs: run.modelMs ?? null,\n toolsMs: run.toolsMs ?? null,\n modelCalls: run.modelCalls ?? null,\n toolCalls: run.toolCalls ?? null,\n };\n}\n\n/** A run row's persisted {@link RunTimings}, or `null` when it has none. */\nfunction toRunTimings(run: typeof agentRun.$inferSelect): RunTimings | null {\n if (!Array.isArray(run.timings)) return null;\n return {\n modelMs: run.modelMs ?? 0,\n toolsMs: run.toolsMs ?? 0,\n modelCalls: run.modelCalls ?? 0,\n toolCalls: run.toolCalls ?? 0,\n steps: run.timings,\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(\n row: Pick<\n typeof agentTokenUsage.$inferSelect,\n | 'modelId'\n | 'actorRef'\n | 'threadId'\n | 'createdAt'\n | 'inputTokens'\n | 'outputTokens'\n | 'cacheWriteTokens'\n | 'cacheReadTokens'\n | 'costUsd'\n > &\n Partial<\n Pick<\n typeof agentTokenUsage.$inferSelect,\n 'feature' | 'purpose' | 'costSource' | 'audioSeconds' | 'characters' | 'requests'\n >\n >,\n): GovernanceUsageInput {\n return {\n feature: row.feature ?? null,\n purpose: row.purpose ?? null,\n costSource: row.costSource ?? null,\n audioSeconds: row.audioSeconds == null ? null : Number(row.audioSeconds),\n characters: row.characters == null ? null : Number(row.characters),\n requests: row.requests ?? null,\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 private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n /**\n * `tenant`: the rows these queries may see (see {@link forTenant}); absent → every row. Threads by\n * their `tenant_ref`; runs, messages, tool calls and generative-UI calls by their thread's; usage\n * by its own `tenant_ref`.\n */\n constructor(\n private readonly source: AgentDrizzleDb,\n private readonly pricingStore: AgentPricingStore,\n private readonly tenant?: TenantRowFilter,\n ) {\n this.dialect = agentDialectOf(source);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(source);\n }\n\n /** These queries narrowed to the rows `filter` may see — the console's tenant scope. */\n forTenant(filter: TenantRowFilter): DrizzleGovernanceQueries {\n return new DrizzleGovernanceQueries(this.source, this.pricingStore, filter);\n }\n\n /** The matching rule on a `tenant_ref` column; `undefined` (no condition) without a scope. */\n private tenantOn(column: Column): SQL | undefined {\n const filter = this.tenant;\n if (filter === undefined) return undefined;\n if (filter.tenant === undefined) return isNull(column);\n return filter.nulls ? or(eq(column, filter.tenant), isNull(column)) : eq(column, filter.tenant);\n }\n\n /** Rows keyed by a thread id whose thread the scope may see; `undefined` without a scope. */\n private threadIn(threadId: Column): SQL | undefined {\n const visible = this.tenantOn(this.t.agentThread.tenantRef);\n if (visible === undefined) return undefined;\n return inArray(\n threadId,\n this.db.select({ id: this.t.agentThread.id }).from(this.t.agentThread).where(visible),\n );\n }\n\n /** Tool calls (by `message_id`) on a thread the scope may see; `undefined` without a scope. */\n private toolCallIn(messageId: Column): SQL | undefined {\n const visible = this.threadIn(this.t.agentMessage.threadId);\n if (visible === undefined) return undefined;\n return inArray(\n messageId,\n this.db.select({ id: this.t.agentMessage.id }).from(this.t.agentMessage).where(visible),\n );\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 /**\n * The usage rows in range, with only what the bucketers read: `requests` always (a recorded row\n * counts as its own requests in every rollup), and the feature/unit columns only for the\n * per-feature reads that group by them.\n */\n private async usageInRange(\n range: GovernanceRange | TimestampRange,\n withFeature = false,\n ): Promise<GovernanceUsageInput[]> {\n const { start, end } = usageRangeBounds(range);\n const usage = this.t.agentTokenUsage;\n // Only what the bucketers read.\n const rows = await this.db\n .select({\n modelId: usage.modelId,\n actorRef: usage.actorRef,\n threadId: usage.threadId,\n createdAt: usage.createdAt,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cacheWriteTokens: usage.cacheWriteTokens,\n cacheReadTokens: usage.cacheReadTokens,\n costUsd: usage.costUsd,\n requests: usage.requests,\n ...(withFeature\n ? {\n feature: usage.feature,\n purpose: usage.purpose,\n costSource: usage.costSource,\n audioSeconds: usage.audioSeconds,\n characters: usage.characters,\n }\n : {}),\n })\n .from(usage)\n .where(\n and(\n gte(this.t.agentTokenUsage.createdAt, start),\n lt(this.t.agentTokenUsage.createdAt, end),\n this.tenantOn(usage.tenantRef),\n ),\n );\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 spendByFeature(range: GovernanceRange): Promise<FeatureSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByFeature(await this.usageInRange(range, true), pricing);\n }\n\n async usageBreakdown(\n range: GovernanceRange | TimestampRange,\n filter?: UsageBreakdownFilter,\n ): Promise<UsageBreakdownRow[]> {\n const pricing = await this.loadPricing();\n return bucketUsageBreakdown(await this.usageInRange(range, true), pricing, filter);\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 = [\n ...new Set(rows.flatMap((row) => (row.threadId === null ? [] : [row.threadId]))),\n ];\n if (threadIds.length === 0) {\n return [];\n }\n const threads = await this.db\n .select({\n id: this.t.agentThread.id,\n title: this.t.agentThread.title,\n actorRef: this.t.agentThread.actorRef,\n })\n .from(this.t.agentThread)\n .where(and(inArray(this.t.agentThread.id, threadIds), isNull(this.t.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: this.t.agentToolCall.id,\n toolName: this.t.agentToolCall.toolName,\n toolType: this.t.agentToolCall.toolType,\n status: this.t.agentToolCall.status,\n threadId: this.t.agentMessage.threadId,\n createdAt: this.t.agentToolCall.createdAt,\n runId: this.t.agentToolCall.runId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .where(this.threadIn(this.t.agentMessage.threadId))\n .orderBy(desc(this.t.agentToolCall.createdAt), desc(this.t.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: this.t.agentMessage.threadId, value: count() })\n .from(this.t.agentMessage)\n .where(inArray(this.t.agentMessage.threadId, threadIds))\n .groupBy(this.t.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: this.t.agentTokenUsage.threadId,\n inputTokens: sum(this.t.agentTokenUsage.inputTokens),\n outputTokens: sum(this.t.agentTokenUsage.outputTokens),\n })\n .from(this.t.agentTokenUsage)\n .where(inArray(this.t.agentTokenUsage.threadId, threadIds))\n .groupBy(this.t.agentTokenUsage.threadId);\n for (const row of usageTotals) {\n if (row.threadId === null) continue;\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(this.t.agentThread)\n .where(and(isNull(this.t.agentThread.deletedAt), this.tenantOn(this.t.agentThread.tenantRef)))\n .orderBy(desc(this.t.agentThread.updatedAt), desc(this.t.agentThread.id))\n .limit(limit);\n return this.toThreadActivityRows(threads);\n }\n\n /** The range's runs, with only the columns the rollups read. */\n private async runsInRange(range: GovernanceRange) {\n const { start, end } = dayBoundsUtc(range);\n const run = this.t.agentRun;\n return this.db\n .select({\n agentName: run.agentName,\n status: run.status,\n retries: run.retries,\n durationMs: run.durationMs,\n ttftMs: run.ttftMs,\n parentRunId: run.parentRunId,\n startedAt: run.startedAt,\n })\n .from(run)\n .where(and(gte(run.startedAt, start), lte(run.startedAt, end), this.threadIn(run.threadId)));\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 const ttftsMs: 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 // A person waited for the first token of a completed TOP-LEVEL turn only: a delegated child\n // streams into its parent's turn.\n if (run.status === 'completed' && run.parentRunId == null && run.ttftMs != null) {\n ttftsMs.push(run.ttftMs);\n }\n }\n settledDurationsMs.sort((left, right) => left - right);\n ttftsMs.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 ttftP50Ms: percentileMs(ttftsMs, 0.5),\n ttftP95Ms: percentileMs(ttftsMs, 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({ errorCode: this.t.agentRun.errorCode })\n .from(this.t.agentRun)\n .where(\n and(\n gte(this.t.agentRun.startedAt, start),\n lte(this.t.agentRun.startedAt, end),\n eq(this.t.agentRun.status, 'failed'),\n this.threadIn(this.t.agentRun.threadId),\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(this.t.agentRun)\n .where(this.threadIn(this.t.agentRun.threadId))\n .orderBy(desc(this.t.agentRun.startedAt), desc(this.t.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: this.t.agentToolCall.id,\n toolName: this.t.agentToolCall.toolName,\n input: this.t.agentToolCall.input,\n threadId: this.t.agentThread.id,\n threadTitle: this.t.agentThread.title,\n actorRef: this.t.agentThread.actorRef,\n agentName: this.t.agentMessage.agentName,\n requestedAt: this.t.agentToolCall.createdAt,\n runId: this.t.agentToolCall.runId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(\n and(\n eq(this.t.agentToolCall.status, 'pending_approval'),\n this.tenantOn(this.t.agentThread.tenantRef),\n ),\n )\n .orderBy(this.t.agentToolCall.createdAt, this.t.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 toolName: this.t.agentToolCall.toolName,\n toolType: this.t.agentToolCall.toolType,\n status: this.t.agentToolCall.status,\n executionMs: this.t.agentToolCall.executionMs,\n })\n .from(this.t.agentToolCall)\n .where(\n and(\n gte(this.t.agentToolCall.createdAt, start),\n lte(this.t.agentToolCall.createdAt, end),\n this.toolCallIn(this.t.agentToolCall.messageId),\n ),\n );\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\n ? eq(this.t.agentToolCall.toolName, filters.toolName)\n : undefined,\n filters?.toolType !== undefined && isToolKind(filters.toolType)\n ? eq(this.t.agentToolCall.toolType, filters.toolType)\n : undefined,\n filters?.status !== undefined && isToolCallStatus(filters.status)\n ? eq(this.t.agentToolCall.status, filters.status)\n : undefined,\n filters?.threadId !== undefined\n ? eq(this.t.agentMessage.threadId, filters.threadId)\n : undefined,\n filters?.fromDay !== undefined\n ? gte(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay))\n : undefined,\n this.threadIn(this.t.agentMessage.threadId),\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .where(whereClause);\n const rows = await this.db\n .select({\n toolCallId: this.t.agentToolCall.id,\n toolName: this.t.agentToolCall.toolName,\n toolType: this.t.agentToolCall.toolType,\n status: this.t.agentToolCall.status,\n threadId: this.t.agentMessage.threadId,\n createdAt: this.t.agentToolCall.createdAt,\n runId: this.t.agentToolCall.runId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .where(whereClause)\n .orderBy(desc(this.t.agentToolCall.createdAt), desc(this.t.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(this.t.agentThread.deletedAt),\n filters?.actorRef !== undefined\n ? eq(this.t.agentThread.actorRef, filters.actorRef)\n : undefined,\n filters?.title !== undefined\n ? like(sql`lower(${this.t.agentThread.title})`, `%${filters.title.toLowerCase()}%`)\n : undefined,\n filters?.fromDay !== undefined\n ? gte(this.t.agentThread.updatedAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(this.t.agentThread.updatedAt, dayEndUtc(filters.toDay))\n : undefined,\n this.tenantOn(this.t.agentThread.tenantRef),\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentThread)\n .where(whereClause);\n const threads = await this.db\n .select()\n .from(this.t.agentThread)\n .where(whereClause)\n .orderBy(desc(this.t.agentThread.updatedAt), desc(this.t.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\n ? eq(this.t.agentRun.agentName, filters.agentName)\n : undefined,\n filters?.status !== undefined && isRunStatus(filters.status)\n ? eq(this.t.agentRun.status, filters.status)\n : undefined,\n filters?.errorCode !== undefined\n ? eq(this.t.agentRun.errorCode, filters.errorCode)\n : undefined,\n filters?.threadId !== undefined ? eq(this.t.agentRun.threadId, filters.threadId) : undefined,\n filters?.fromDay !== undefined\n ? gte(this.t.agentRun.startedAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(this.t.agentRun.startedAt, dayEndUtc(filters.toDay))\n : undefined,\n this.threadIn(this.t.agentRun.threadId),\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentRun)\n .where(whereClause);\n const runs = await this.db\n .select()\n .from(this.t.agentRun)\n .where(whereClause)\n .orderBy(desc(this.t.agentRun.startedAt), desc(this.t.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(this.t.agentToolCall.status, 'pending_approval'),\n filters?.toolName !== undefined\n ? eq(this.t.agentToolCall.toolName, filters.toolName)\n : undefined,\n filters?.threadId !== undefined ? eq(this.t.agentThread.id, filters.threadId) : undefined,\n filters?.actorRef !== undefined\n ? eq(this.t.agentThread.actorRef, filters.actorRef)\n : undefined,\n filters?.agentName !== undefined\n ? eq(this.t.agentMessage.agentName, filters.agentName)\n : undefined,\n filters?.fromDay !== undefined\n ? gte(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay))\n : undefined,\n filters?.toDay !== undefined\n ? lte(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay))\n : undefined,\n this.tenantOn(this.t.agentThread.tenantRef),\n );\n const [totalRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(whereClause);\n const rows = await this.db\n .select({\n toolCallId: this.t.agentToolCall.id,\n toolName: this.t.agentToolCall.toolName,\n input: this.t.agentToolCall.input,\n threadId: this.t.agentThread.id,\n threadTitle: this.t.agentThread.title,\n actorRef: this.t.agentThread.actorRef,\n agentName: this.t.agentMessage.agentName,\n requestedAt: this.t.agentToolCall.createdAt,\n runId: this.t.agentToolCall.runId,\n })\n .from(this.t.agentToolCall)\n .innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id))\n .innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id))\n .where(whereClause)\n .orderBy(asc(this.t.agentToolCall.createdAt), asc(this.t.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: this.t.agentRun, thread: this.t.agentThread })\n .from(this.t.agentRun)\n .innerJoin(this.t.agentThread, eq(this.t.agentRun.threadId, this.t.agentThread.id))\n .where(and(eq(this.t.agentRun.id, runId), this.tenantOn(this.t.agentThread.tenantRef)))\n .limit(1);\n if (row === undefined) {\n return null;\n }\n const toolCalls = await this.db\n .select()\n .from(this.t.agentToolCall)\n .where(eq(this.t.agentToolCall.runId, runId))\n .orderBy(asc(this.t.agentToolCall.createdAt), asc(this.t.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 timings: toRunTimings(row.run),\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(this.t.agentThread)\n .where(\n and(eq(this.t.agentThread.id, query.threadId), this.tenantOn(this.t.agentThread.tenantRef)),\n )\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(this.t.agentTokenUsage)\n .where(eq(this.t.agentTokenUsage.threadId, thread.id));\n const usage = rollupThreadUsage(usageRows.map(toUsageInput), pricing);\n const [messageCountRow] = await this.db\n .select({ value: count() })\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, thread.id));\n const messages = await this.db\n .select()\n .from(this.t.agentMessage)\n .where(eq(this.t.agentMessage.threadId, thread.id))\n .orderBy(\n // Append order (see DrizzleAgentStore's message order), newest first.\n desc(sql`coalesce(${this.t.agentMessage.seq}, 0)`),\n desc(this.t.agentMessage.createdAt),\n desc(this.t.agentMessage.id),\n )\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(this.t.agentRun)\n .where(eq(this.t.agentRun.threadId, thread.id));\n const runs = await this.db\n .select()\n .from(this.t.agentRun)\n .where(eq(this.t.agentRun.threadId, thread.id))\n .orderBy(desc(this.t.agentRun.startedAt), desc(this.t.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 /** Generative-UI stats over the `agent_genui_call` rows created in the (UTC, inclusive) day range. */\n async genuiStats(range: GovernanceRange): Promise<GenuiStats> {\n const { start, end } = dayBoundsUtc(range);\n const table = this.t.agentGenuiCall;\n const rows = await this.db\n .select()\n .from(table)\n .where(\n and(\n gte(table.createdAt, start.getTime()),\n lte(table.createdAt, end.getTime()),\n this.threadIn(table.threadId),\n ),\n );\n return summarizeGenuiCalls(rows.map(toGenuiCallRow));\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: this.t.agentToolCall.messageId, value: count() })\n .from(this.t.agentToolCall)\n .where(inArray(this.t.agentToolCall.messageId, messageIds))\n .groupBy(this.t.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 {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n upsert,\n} from './dialect.js';\nimport { 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 private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\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(this.t.agentMemory)\n .where(inArray(this.t.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 affectedRows(\n this.dialect,\n this.db\n .delete(this.t.agentMemory)\n .where(\n and(eq(this.t.agentMemory.id, id), eq(this.t.agentMemory.scope, actorScope(ctx.actor))),\n ),\n this.t.agentMemory.id,\n );\n return deleted > 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 memory = this.t.agentMemory;\n const set = { text, ...columns, updatedAt: now };\n const insert = this.db.insert(memory).values({\n id: crypto.randomUUID(),\n scope,\n key,\n text,\n ...columns,\n pinned: false,\n createdAt: now,\n updatedAt: now,\n });\n let row: AgentMemoryRow | undefined;\n if (this.dialect === 'mysql') {\n // No `RETURNING` on MySQL: upsert, then read the row back by the key it was upserted on.\n await upsert(this.dialect, insert, [memory.scope, memory.key], set);\n [row] = await this.db\n .select()\n .from(memory)\n .where(and(eq(memory.scope, scope), eq(memory.key, key)));\n } else {\n [row] = await insert\n .onConflictDoUpdate({ target: [memory.scope, memory.key], set })\n .returning();\n }\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 affectedRows(\n this.dialect,\n this.db\n .update(this.t.agentMemory)\n .set({ pinned, updatedAt: new Date() })\n .where(eq(this.t.agentMemory.id, id)),\n this.t.agentMemory.id,\n );\n return updated > 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 {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n} from './dialect.js';\nimport { 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 private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async upsertModelPrice(input: ModelPriceInput): Promise<void> {\n await this.db\n .update(this.t.agentModelPricing)\n .set({ isCurrent: false })\n .where(\n and(\n eq(this.t.agentModelPricing.modelId, input.modelId),\n eq(this.t.agentModelPricing.isCurrent, true),\n ),\n );\n await this.db.insert(this.t.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(this.t.agentModelPricing)\n .where(eq(this.t.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 SqlTokenStreamSink,\n type SqlTokenStreamSinkOptions,\n type StreamFrameRow,\n type StreamFrameTable,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, eq, gt, inArray, lt, max, sql } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n isUniqueViolation,\n runSql,\n} from './dialect.js';\nimport { agentStreamFrame } from './schema.js';\n\n/** {@link StreamFrameTable} over `agent_stream_frame`, through a Drizzle handle on any dialect. */\nexport class DrizzleStreamFrameTable implements StreamFrameTable {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async append(\n runId: string,\n row: { frame: string | null; error: string | null; createdAt: number },\n ): Promise<void> {\n // The next number and the insert are one statement: the (run_id, seq) key settles a race.\n // MySQL takes an INSERT … SELECT from the table it inserts into (it materialises the read).\n await runSql(\n this.db,\n this.dialect,\n sql`INSERT INTO agent_stream_frame (run_id, seq, frame, error, created_at)\n SELECT ${runId}, COALESCE(MAX(seq), 0) + 1, ${row.frame}, ${row.error}, ${row.createdAt}\n FROM agent_stream_frame WHERE run_id = ${runId}`,\n );\n }\n\n async read(runId: string, after: number, limit: number): Promise<StreamFrameRow[]> {\n return this.db\n .select({\n seq: this.t.agentStreamFrame.seq,\n frame: this.t.agentStreamFrame.frame,\n error: this.t.agentStreamFrame.error,\n })\n .from(this.t.agentStreamFrame)\n .where(and(eq(this.t.agentStreamFrame.runId, runId), gt(this.t.agentStreamFrame.seq, after)))\n .orderBy(asc(this.t.agentStreamFrame.seq))\n .limit(limit);\n }\n\n async has(runId: string): Promise<boolean> {\n const rows = await this.db\n .select({ seq: this.t.agentStreamFrame.seq })\n .from(this.t.agentStreamFrame)\n .where(eq(this.t.agentStreamFrame.runId, runId))\n .limit(1);\n return rows.length > 0;\n }\n\n async remove(runIds: readonly string[]): Promise<void> {\n if (runIds.length === 0) return;\n await this.db\n .delete(this.t.agentStreamFrame)\n .where(inArray(this.t.agentStreamFrame.runId, [...runIds]));\n }\n\n async lapsedRuns(cutoff: number): Promise<string[]> {\n const rows = await this.db\n .select({ runId: this.t.agentStreamFrame.runId })\n .from(this.t.agentStreamFrame)\n .groupBy(this.t.agentStreamFrame.runId)\n .having(lt(max(this.t.agentStreamFrame.createdAt), cutoff));\n return rows.map((row) => row.runId);\n }\n\n isUniqueViolation(error: unknown): boolean {\n return isUniqueViolation(error);\n }\n}\n\n/**\n * A multi-replica `TokenStreamSink` over the app's Drizzle database — several replicas, no Redis.\n * Polled, with streamed text coalesced into one row per `flushMs`; see `SqlTokenStreamSink` for the\n * trade-offs. The `agent_stream_frame` table comes from `ensureAgentSchema` (or your migration).\n *\n * ```ts\n * AgentModule.forRoot({ model, sink: new DrizzleTokenStreamSink(db) });\n * ```\n */\nexport class DrizzleTokenStreamSink extends SqlTokenStreamSink {\n constructor(db: AgentDrizzleDb, options: SqlTokenStreamSinkOptions = {}) {\n super(new DrizzleStreamFrameTable(db), options);\n }\n}\n","import type { ConfirmTokenClaim, ConfirmTokenStore } from '@dudousxd/nestjs-agent-core';\nimport { eq, lt } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n mysqlAffectedRows,\n} from './dialect.js';\n\n/** The slice of Drizzle's MySQL insert builder used here, which the SQLite view does not have. */\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\n/**\n * A production `ConfirmTokenStore` (`defineConfirmedTool`) over the `agent_confirm_token` table —\n * what makes a confirmed write single use across replicas.\n *\n * `claim` is one insert that skips a duplicate hash — `ON CONFLICT DO NOTHING` on SQLite and\n * Postgres, `INSERT IGNORE` on MySQL — so the primary key is the lock: of two concurrent\n * confirmations one inserts and the other touches no row. A statement that does not FAIL on the\n * duplicate, rather than an insert whose violation is caught, so it never aborts a surrounding\n * transaction. Only the token's SHA-256, the actor and the tool name are stored; call\n * {@link purgeExpired} from a scheduled job to drop the dead rows. The table comes from\n * `ensureAgentSchema` (or your own migration).\n */\nexport class DrizzleConfirmTokenStore implements ConfirmTokenStore {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async claim(input: ConfirmTokenClaim): Promise<boolean> {\n const row = {\n hash: input.hash,\n actorRef: input.actorRef,\n tool: input.tool,\n expiresAt: input.expiresAt,\n createdAt: Date.now(),\n };\n const table = this.t.agentConfirmToken;\n if (this.dialect === 'mysql') {\n // MySQL's insert builder: `INSERT IGNORE`, and the header's affectedRows is 0 on a duplicate.\n const insert = this.db.insert(table) as unknown as MySqlInsertIgnore<typeof row>;\n return mysqlAffectedRows(await insert.ignore().values(row)) === 1;\n }\n const inserted = await affectedRows(\n this.dialect,\n this.db.insert(table).values(row).onConflictDoNothing(),\n table.hash,\n );\n return inserted === 1;\n }\n\n async release(hash: string): Promise<void> {\n await this.db.delete(this.t.agentConfirmToken).where(eq(this.t.agentConfirmToken.hash, hash));\n }\n\n async purgeExpired(now: number = Date.now()): Promise<number> {\n const table = this.t.agentConfirmToken;\n return affectedRows(\n this.dialect,\n this.db.delete(table).where(lt(table.expiresAt, now)),\n table.hash,\n );\n }\n}\n","import { createHash } from 'node:crypto';\nimport type { ChannelStore } from '@dudousxd/nestjs-agent-core';\nimport { and, eq, gt, lte } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n mysqlAffectedRows,\n upsert,\n} from './dialect.js';\n\n/** The slice of Drizzle's MySQL insert builder used here, which the SQLite view does not have. */\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\n/** Keys longer than the column are stored by their hash. */\nconst channelStateKey = (key: string): string =>\n key.length <= 255 ? key : `sha256:${createHash('sha256').update(key).digest('hex')}`;\n\nexport interface DrizzleChannelStoreOptions {\n /** How often a claim also deletes expired rows. Default 10 minutes; `0` → never (purge yourself). */\n purgeEveryMs?: number;\n}\n\n/**\n * A `ChannelStore` (text channels, `@dudousxd/nestjs-agent-channels`) over the `agent_channel_state`\n * table — shared by every replica, no Redis needed.\n *\n * A claim deletes the key's row when it expired, then inserts it skipping a duplicate key —\n * `ON CONFLICT DO NOTHING` on SQLite and Postgres, `INSERT IGNORE` on MySQL — so the primary key is\n * the lock: of two concurrent claims one inserts and the other touches no row. Expired rows are\n * deleted as claims arrive (`purgeEveryMs`), or by {@link purgeExpired} from a job. The table comes\n * from `ensureAgentSchema` (or your own migration).\n */\nexport class DrizzleChannelStore implements ChannelStore {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n private readonly purgeEveryMs: number;\n private lastPurge = 0;\n\n constructor(db: AgentDrizzleDb, options: DrizzleChannelStoreOptions = {}) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n this.purgeEveryMs = options.purgeEveryMs ?? 10 * 60 * 1000;\n }\n\n async claim(key: string, ttlMs: number): Promise<boolean> {\n const table = this.t.agentChannelState;\n const now = Date.now();\n if (this.purgeEveryMs > 0 && now - this.lastPurge >= this.purgeEveryMs) {\n this.lastPurge = now;\n await this.purgeExpired(now);\n }\n const id = channelStateKey(key);\n // An expired claim is free again.\n await this.db.delete(table).where(and(eq(table.key, id), lte(table.expiresAt, now)));\n const row = { key: id, value: null, expiresAt: now + ttlMs, createdAt: now };\n if (this.dialect === 'mysql') {\n // MySQL's insert builder: `INSERT IGNORE`, and the header's affectedRows is 0 on a duplicate.\n const insert = this.db.insert(table) as unknown as MySqlInsertIgnore<typeof row>;\n return mysqlAffectedRows(await insert.ignore().values(row)) === 1;\n }\n const inserted = await affectedRows(\n this.dialect,\n this.db.insert(table).values(row).onConflictDoNothing(),\n table.key,\n );\n return inserted === 1;\n }\n\n async get(key: string): Promise<string | null> {\n const table = this.t.agentChannelState;\n const rows = await this.db\n .select({ value: table.value })\n .from(table)\n .where(and(eq(table.key, channelStateKey(key)), gt(table.expiresAt, Date.now())));\n const value = rows[0]?.value;\n return typeof value === 'string' ? value : null;\n }\n\n async set(key: string, value: string, ttlMs: number): Promise<void> {\n const table = this.t.agentChannelState;\n const now = Date.now();\n await upsert(\n this.dialect,\n this.db\n .insert(table)\n .values({ key: channelStateKey(key), value, expiresAt: now + ttlMs, createdAt: now }),\n table.key,\n { value, expiresAt: now + ttlMs },\n );\n }\n\n async delete(key: string): Promise<void> {\n const table = this.t.agentChannelState;\n await this.db.delete(table).where(eq(table.key, channelStateKey(key)));\n }\n\n async purgeExpired(now: number = Date.now()): Promise<number> {\n const table = this.t.agentChannelState;\n return affectedRows(\n this.dialect,\n this.db.delete(table).where(lte(table.expiresAt, now)),\n table.key,\n );\n }\n}\n","import {\n type PoppyContext,\n type PoppyConversationPatch,\n type PoppyConversationRecord,\n type PoppyEvent,\n type PoppyEventBody,\n type PoppyGrant,\n type PoppyMessageClaim,\n type PoppyMessageReceipt,\n type PoppyResponder,\n type PoppyStatus,\n type PoppyStore,\n type StoredPoppyEvent,\n newEventId,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, desc, eq, gt, isNull, lt, lte, or } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n isUniqueViolation,\n mysqlAffectedRows,\n} from './dialect.js';\n\n/** The slice of Drizzle's MySQL insert builder used here, which the SQLite view does not have. */\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\n/** How many times an append re-numbers itself after losing its position to another append. */\nconst MAX_APPEND_ATTEMPTS = 50;\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst nullable = (value: unknown): string | null => (value == null ? null : String(value));\n\nfunction toInt(value: unknown): number {\n if (typeof value === 'number') return value;\n if (typeof value === 'bigint') return Number(value);\n if (typeof value === 'string') return Number.parseInt(value, 10) || 0;\n return 0;\n}\n\nconst PATCH_COLUMNS = {\n accountRef: 'accountRef',\n threadId: 'threadId',\n openDirectId: 'openDirectId',\n status: 'status',\n responder: 'responder',\n context: 'context',\n activeRunId: 'activeRunId',\n turnSeq: 'turnSeq',\n grant: 'grantInfo',\n prunedSeq: 'prunedSeq',\n} as const satisfies Record<keyof PoppyConversationPatch, string>;\n\n/**\n * A `PoppyStore` (Personal Agent Protocol conversations, `@dudousxd/nestjs-agent-poppy`) over the\n * `agent_poppy_conversation`, `agent_poppy_event` and `agent_poppy_message` tables — shared by every\n * replica. The tables come from `ensureAgentSchema` (or your own migration).\n *\n * Every race is settled by a key rather than a lock: an event's primary key is its position, so of\n * two appends numbered alike one inserts and the other re-numbers itself after it; `(conversation,\n * event_key)` is unique, so a keyed append happens once; a message's `(owner, message_id)` is the\n * idempotency lock. Those inserts skip a duplicate (`ON CONFLICT DO NOTHING`, `INSERT IGNORE` on\n * MySQL) rather than fail on it, so they never abort a surrounding Postgres transaction. The reader\n * lease is one conditional `UPDATE` of the conversation row.\n *\n * @experimental Tracks Personal Agent Protocol Draft 0.1 (https://personalagentprotocol.org/docs/spec).\n */\nexport class DrizzlePoppyStore implements PoppyStore {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async createConversation(record: PoppyConversationRecord): Promise<void> {\n await this.db.insert(this.t.agentPoppyConversation).values({\n id: record.id,\n clientId: record.clientId,\n userId: record.userId,\n accountRef: record.accountRef,\n agentName: record.agentName,\n threadId: record.threadId,\n parentId: record.parentId,\n openDirectId: record.openDirectId,\n status: record.status,\n responder: record.responder,\n context: JSON.stringify(record.context),\n activeRunId: record.activeRunId,\n turnSeq: record.turnSeq,\n grantInfo: record.grant === null ? null : JSON.stringify(record.grant),\n readerHolder: null,\n readerUntil: null,\n prunedSeq: record.prunedSeq,\n createdAt: record.createdAt,\n updatedAt: record.updatedAt,\n });\n }\n\n async getConversation(id: string): Promise<PoppyConversationRecord | null> {\n const table = this.t.agentPoppyConversation;\n const [row] = await this.db.select().from(table).where(eq(table.id, id)).limit(1);\n if (!row) return null;\n return {\n id: row.id,\n clientId: row.clientId,\n userId: row.userId,\n accountRef: nullable(row.accountRef),\n agentName: row.agentName,\n threadId: nullable(row.threadId),\n parentId: nullable(row.parentId),\n openDirectId: nullable(row.openDirectId),\n status: row.status as PoppyStatus,\n responder: row.responder as PoppyResponder,\n context: row.context == null ? {} : (JSON.parse(row.context) as PoppyContext),\n activeRunId: nullable(row.activeRunId),\n turnSeq: toInt(row.turnSeq),\n grant: row.grantInfo == null ? null : (JSON.parse(row.grantInfo) as PoppyGrant),\n prunedSeq: toInt(row.prunedSeq),\n createdAt: toInt(row.createdAt),\n updatedAt: toInt(row.updatedAt),\n };\n }\n\n async updateConversation(id: string, patch: PoppyConversationPatch): Promise<void> {\n const table = this.t.agentPoppyConversation;\n const set: Record<string, unknown> = { updatedAt: Date.now() };\n for (const [key, column] of Object.entries(PATCH_COLUMNS)) {\n const value = patch[key as keyof PoppyConversationPatch];\n if (value === undefined) continue;\n set[column] =\n key === 'context' || (key === 'grant' && value !== null) ? JSON.stringify(value) : value;\n }\n await this.db\n .update(table)\n .set(set as typeof table.$inferInsert)\n .where(eq(table.id, id));\n }\n\n async appendEvent(\n conversationId: string,\n body: PoppyEventBody,\n options: { key?: string } = {},\n ): Promise<{ event: StoredPoppyEvent; created: boolean }> {\n const table = this.t.agentPoppyEvent;\n for (let attempt = 1; ; attempt++) {\n if (options.key !== undefined) {\n const [existing] = await this.db\n .select({ seq: table.seq, event: table.event })\n .from(table)\n .where(and(eq(table.conversationId, conversationId), eq(table.eventKey, options.key)))\n .limit(1);\n if (existing) {\n return {\n event: { seq: toInt(existing.seq), event: JSON.parse(existing.event) as PoppyEvent },\n created: false,\n };\n }\n }\n const seq = (await this.lastSeq(conversationId)) + 1;\n const now = Date.now();\n const stored: StoredPoppyEvent = {\n seq,\n event: { id: newEventId(seq), created_at: new Date(now).toISOString(), ...body },\n };\n let inserted = false;\n try {\n inserted = await this.insertIgnore(table, {\n conversationId,\n seq,\n id: stored.event.id,\n type: body.type,\n event: JSON.stringify(stored.event),\n eventKey: options.key ?? null,\n createdAt: now,\n });\n } catch (error) {\n // MySQL may settle two inserts into one gap with a deadlock rather than a skipped duplicate.\n if (!isUniqueViolation(error)) throw error;\n }\n if (inserted) return { event: stored, created: true };\n // Another append took this position (or this key) first: look again, numbered after it.\n if (attempt >= MAX_APPEND_ATTEMPTS) {\n throw new Error(`poppy: could not append to ${conversationId} after ${attempt} attempts`);\n }\n await sleep(Math.random() * Math.min(attempt, 10) * 2);\n }\n }\n\n /** The last position taken: the last event's, or — every event pruned — the pruned floor. */\n private async lastSeq(conversationId: string): Promise<number> {\n const table = this.t.agentPoppyEvent;\n const [last] = await this.db\n .select({ seq: table.seq })\n .from(table)\n .where(eq(table.conversationId, conversationId))\n .orderBy(desc(table.seq))\n .limit(1);\n if (last) return toInt(last.seq);\n const conversations = this.t.agentPoppyConversation;\n const [conversation] = await this.db\n .select({ prunedSeq: conversations.prunedSeq })\n .from(conversations)\n .where(eq(conversations.id, conversationId))\n .limit(1);\n return toInt(conversation?.prunedSeq);\n }\n\n async listEvents(\n conversationId: string,\n afterSeq: number,\n limit: number,\n ): Promise<StoredPoppyEvent[]> {\n const table = this.t.agentPoppyEvent;\n const rows = await this.db\n .select({ seq: table.seq, event: table.event })\n .from(table)\n .where(and(eq(table.conversationId, conversationId), gt(table.seq, afterSeq)))\n .orderBy(table.seq)\n .limit(limit);\n return rows.map((row) => ({ seq: toInt(row.seq), event: JSON.parse(row.event) as PoppyEvent }));\n }\n\n async findEventSeq(conversationId: string, eventId: string): Promise<number | null> {\n const table = this.t.agentPoppyEvent;\n const [row] = await this.db\n .select({ seq: table.seq })\n .from(table)\n .where(and(eq(table.conversationId, conversationId), eq(table.id, eventId)))\n .limit(1);\n return row ? toInt(row.seq) : null;\n }\n\n async pruneEvents(conversationId: string, before: number): Promise<void> {\n const table = this.t.agentPoppyEvent;\n const [last] = await this.db\n .select({ seq: table.seq })\n .from(table)\n .where(eq(table.conversationId, conversationId))\n .orderBy(desc(table.seq))\n .limit(1);\n if (!last) return;\n // The newest event old enough to go, short of the last: it and everything before it go.\n const [dropped] = await this.db\n .select({ seq: table.seq })\n .from(table)\n .where(\n and(\n eq(table.conversationId, conversationId),\n lt(table.createdAt, before),\n lt(table.seq, toInt(last.seq)),\n ),\n )\n .orderBy(desc(table.seq))\n .limit(1);\n if (!dropped) return;\n const upTo = toInt(dropped.seq);\n // The floor moves first, so a reader never takes the gap for events not yet written.\n const conversations = this.t.agentPoppyConversation;\n await this.db\n .update(conversations)\n .set({ prunedSeq: upTo })\n .where(and(eq(conversations.id, conversationId), lt(conversations.prunedSeq, upTo)));\n await this.db\n .delete(table)\n .where(and(eq(table.conversationId, conversationId), lte(table.seq, upTo)));\n }\n\n async claimMessage(\n owner: string,\n messageId: string,\n receipt: PoppyMessageReceipt,\n ): Promise<PoppyMessageClaim> {\n const table = this.t.agentPoppyMessage;\n for (let attempt = 1; ; attempt++) {\n const inserted = await this.insertIgnore(table, {\n owner,\n messageId,\n fingerprint: receipt.fingerprint,\n conversationId: receipt.conversationId,\n response: JSON.stringify(receipt.response),\n createdAt: Date.now(),\n });\n if (inserted) return { status: 'claimed' };\n const [row] = await this.db\n .select()\n .from(table)\n .where(and(eq(table.owner, owner), eq(table.messageId, messageId)))\n .limit(1);\n if (row) {\n return {\n status: 'existing',\n fingerprint: row.fingerprint,\n conversationId: row.conversationId,\n response: JSON.parse(row.response) as PoppyMessageReceipt['response'],\n };\n }\n // Released between the two statements: claim afresh.\n if (attempt >= 5) throw new Error(`poppy: could not claim message ${messageId}`);\n }\n }\n\n async releaseMessage(owner: string, messageId: string): Promise<void> {\n const table = this.t.agentPoppyMessage;\n await this.db.delete(table).where(and(eq(table.owner, owner), eq(table.messageId, messageId)));\n }\n\n async leaseReader(conversationId: string, holder: string, ttlMs: number): Promise<boolean> {\n const table = this.t.agentPoppyConversation;\n const now = Date.now();\n // One conditional update: free, already ours, or expired. Of two takers the row lock serializes\n // them, and the second's condition no longer holds.\n const taken = await affectedRows(\n this.dialect,\n this.db\n .update(table)\n .set({ readerHolder: holder, readerUntil: now + ttlMs })\n .where(\n and(\n eq(table.id, conversationId),\n or(\n isNull(table.readerHolder),\n eq(table.readerHolder, holder),\n lte(table.readerUntil, now),\n ),\n ),\n ),\n table.id,\n );\n if (taken === 1) return true;\n if (this.dialect !== 'mysql') return false;\n // MySQL may count only CHANGED rows (no FOUND_ROWS): a renewal in the same millisecond reads 0.\n const [row] = await this.db\n .select({ holder: table.readerHolder })\n .from(table)\n .where(eq(table.id, conversationId))\n .limit(1);\n return row?.holder === holder;\n }\n\n async releaseReader(conversationId: string, holder: string): Promise<void> {\n const table = this.t.agentPoppyConversation;\n await this.db\n .update(table)\n .set({ readerHolder: null, readerUntil: null })\n .where(and(eq(table.id, conversationId), eq(table.readerHolder, holder)));\n }\n\n /** Insert `row`, skipping it on any duplicate key. `true` when it went in. */\n private async insertIgnore<Row extends Record<string, unknown>>(\n table: AgentTables['agentPoppyEvent'] | AgentTables['agentPoppyMessage'],\n row: Row,\n ): Promise<boolean> {\n if (this.dialect === 'mysql') {\n const insert = this.db.insert(table) as unknown as MySqlInsertIgnore<Row>;\n return mysqlAffectedRows(await insert.ignore().values(row)) === 1;\n }\n const statement = this.db\n .insert(table)\n .values(row as never)\n .onConflictDoNothing();\n return (await affectedRows(this.dialect, statement, table.createdAt)) === 1;\n }\n}\n","import type {\n PoppyConnectionRecord,\n PoppyConnectionStore,\n PoppyPendingConnect,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, eq } from 'drizzle-orm';\nimport {\n type AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n upsert,\n} from './dialect.js';\n\n/** The slice of Drizzle's MySQL insert builder used here, which the SQLite view does not have. */\ninterface MySqlInsertIgnore<Row> {\n ignore(): { values(value: Row): PromiseLike<unknown> };\n}\n\nconst nullable = (value: unknown): string | null => (value == null ? null : String(value));\nconst toInt = (value: unknown): number => (typeof value === 'number' ? value : Number(value ?? 0));\n\n/**\n * A `PoppyConnectionStore` (`AgentPoppyConnectionsModule`: this app's agent acting at other Poppy\n * companies) over the `agent_poppy_connection` and `agent_poppy_connect` tables. A connection is\n * keyed by (owner, issuer) and upserted on it; a pending connect is inserted once, skipping a\n * duplicate id. The client state arrives sealed: no token is ever stored in the clear. On MySQL an\n * issuer is at most 512 characters (the composite key's index limit). The tables come from\n * `ensureAgentSchema` (or your own migration).\n *\n * @experimental Tracks Personal Agent Protocol Draft 0.1 (https://personalagentprotocol.org/docs/spec).\n */\nexport class DrizzlePoppyConnectionStore implements PoppyConnectionStore {\n private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\n\n async listConnections(owner: string): Promise<PoppyConnectionRecord[]> {\n const table = this.t.agentPoppyConnection;\n const rows = await this.db\n .select()\n .from(table)\n .where(eq(table.owner, owner))\n .orderBy(asc(table.domain), asc(table.issuer));\n return rows.map(toConnection);\n }\n\n async getConnection(owner: string, issuer: string): Promise<PoppyConnectionRecord | null> {\n const table = this.t.agentPoppyConnection;\n const [row] = await this.db\n .select()\n .from(table)\n .where(and(eq(table.owner, owner), eq(table.issuer, issuer)))\n .limit(1);\n return row ? toConnection(row) : null;\n }\n\n async saveConnection(record: PoppyConnectionRecord): Promise<void> {\n const table = this.t.agentPoppyConnection;\n const columns = {\n domain: record.domain,\n organization: record.organization,\n scope: record.scope,\n status: record.status,\n state: record.state,\n updatedAt: record.updatedAt,\n };\n await upsert(\n this.dialect,\n this.db.insert(table).values({\n owner: record.owner,\n issuer: record.issuer,\n createdAt: record.createdAt,\n ...columns,\n }),\n [table.owner, table.issuer],\n columns,\n );\n }\n\n async deleteConnection(owner: string, issuer: string): Promise<void> {\n const table = this.t.agentPoppyConnection;\n await this.db.delete(table).where(and(eq(table.owner, owner), eq(table.issuer, issuer)));\n }\n\n async createPending(record: PoppyPendingConnect): Promise<void> {\n const table = this.t.agentPoppyConnect;\n const row = {\n id: record.id,\n owner: record.owner,\n domain: record.domain,\n issuer: record.issuer,\n organization: record.organization,\n scope: record.scope,\n actor: record.actor === null ? null : JSON.stringify(record.actor),\n threadId: record.threadId,\n runId: record.runId,\n toolCallId: record.toolCallId,\n flow: record.flow,\n status: record.status,\n expiresAt: record.expiresAt,\n createdAt: record.createdAt,\n };\n // Created once: a second create of the same id is a no-op.\n if (this.dialect === 'mysql') {\n const insert = this.db.insert(table) as unknown as MySqlInsertIgnore<typeof row>;\n await insert.ignore().values(row);\n return;\n }\n await this.db.insert(table).values(row).onConflictDoNothing();\n }\n\n async getPending(id: string): Promise<PoppyPendingConnect | null> {\n const table = this.t.agentPoppyConnect;\n const [row] = await this.db.select().from(table).where(eq(table.id, id)).limit(1);\n if (!row) return null;\n return {\n id: row.id,\n owner: row.owner,\n domain: row.domain,\n issuer: row.issuer,\n organization: row.organization,\n scope: row.scope ?? '',\n actor: row.actor == null ? null : (JSON.parse(row.actor) as PoppyPendingConnect['actor']),\n threadId: nullable(row.threadId),\n runId: nullable(row.runId),\n toolCallId: nullable(row.toolCallId),\n flow: nullable(row.flow),\n status: row.status as PoppyPendingConnect['status'],\n expiresAt: toInt(row.expiresAt),\n createdAt: toInt(row.createdAt),\n };\n }\n\n async updatePending(\n id: string,\n patch: Partial<Pick<PoppyPendingConnect, 'flow' | 'status'>>,\n ): Promise<void> {\n const set: { flow?: string | null; status?: string } = {};\n if (patch.flow !== undefined) set.flow = patch.flow;\n if (patch.status !== undefined) set.status = patch.status;\n if (Object.keys(set).length === 0) return;\n const table = this.t.agentPoppyConnect;\n await this.db.update(table).set(set).where(eq(table.id, id));\n }\n}\n\nfunction toConnection(\n row: AgentTables['agentPoppyConnection']['$inferSelect'],\n): PoppyConnectionRecord {\n return {\n owner: row.owner,\n issuer: row.issuer,\n domain: row.domain,\n organization: row.organization,\n scope: row.scope ?? '',\n status: row.status as PoppyConnectionRecord['status'],\n state: row.state,\n createdAt: toInt(row.createdAt),\n updatedAt: toInt(row.updatedAt),\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 AgentDialect,\n type AgentDrizzleDb,\n type AgentSqliteDb,\n type AgentTables,\n affectedRows,\n agentDialectOf,\n agentTablesFor,\n asBuilder,\n upsert,\n} from './dialect.js';\nimport { type RagIngestionLogRow, type RagIngestionStatus, ragIngestionLog } 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 */\n// Built on the SQLite table, and right on every dialect: an ORDER BY renders only the column's name.\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 */\nfunction cursorColumns(log: AgentTables['ragIngestionLog']) {\n return { documentId: log.documentId, updatedAt: log.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 private readonly db: AgentSqliteDb;\n private readonly dialect: AgentDialect;\n private readonly t: AgentTables;\n\n constructor(db: AgentDrizzleDb) {\n this.dialect = agentDialectOf(db);\n this.t = agentTablesFor(this.dialect);\n this.db = asBuilder(db);\n }\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(this.t.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(this.t.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(this.t.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(cursorColumns(this.t.ragIngestionLog))\n .from(this.t.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(this.t.ragIngestionLog)\n .where(eq(this.t.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 affectedRows(\n this.dialect,\n this.db\n .delete(this.t.ragIngestionLog)\n .where(eq(this.t.ragIngestionLog.documentId, documentId)),\n this.t.ragIngestionLog.documentId,\n );\n return removed > 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 affectedRows(\n this.dialect,\n this.db\n .delete(this.t.ragIngestionLog)\n .where(eq(this.t.ragIngestionLog.collection, collection)),\n this.t.ragIngestionLog.documentId,\n );\n return removed;\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\n ? eq(this.t.ragIngestionLog.collection, query.collection)\n : undefined,\n query.status !== undefined ? eq(this.t.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(this.t.ragIngestionLog.updatedAt, cursor.updatedAt),\n and(\n eq(this.t.ragIngestionLog.updatedAt, cursor.updatedAt),\n gt(this.t.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 upsert(\n this.dialect,\n this.db.insert(this.t.ragIngestionLog).values({ documentId, createdAt: now, ...outcome }),\n this.t.ragIngestionLog.documentId,\n outcome,\n );\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_CHANNEL_STORE,\n AGENT_CONFIRM_TOKEN_STORE,\n AGENT_GOVERNANCE_QUERIES,\n AGENT_POPPY_CONNECTION_STORE,\n AGENT_POPPY_STORE,\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 { DrizzleChannelStore } from './drizzle-channel-store.js';\nimport { DrizzleConfirmTokenStore } from './drizzle-confirm-token-store.js';\nimport { DrizzleGovernanceQueries } from './drizzle-governance-queries.js';\nimport { DrizzleMemoryProvider } from './drizzle-memory-provider.js';\nimport { DrizzlePoppyConnectionStore } from './drizzle-poppy-connection-store.js';\nimport { DrizzlePoppyStore } from './drizzle-poppy-store.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 /**\n * A Drizzle database on SQLite, Postgres or MySQL — `drizzle(client, { schema: agentSchema })`,\n * `pgAgentSchema` or `mysqlAgentSchema`. The stores read the dialect off the handle.\n */\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 * {@link DrizzleConfirmTokenStore} to {@link AGENT_CONFIRM_TOKEN_STORE} (confirmed writes), and\n * {@link DrizzleChannelStore} to {@link AGENT_CHANNEL_STORE} (text channels' state), and\n * {@link DrizzlePoppyStore} / {@link DrizzlePoppyConnectionStore} to {@link AGENT_POPPY_STORE} /\n * {@link AGENT_POPPY_CONNECTION_STORE} (Personal Agent Protocol conversations and connections).\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 // What makes a `defineConfirmedTool` confirmation single use across replicas.\n {\n provide: DrizzleConfirmTokenStore,\n useFactory: () => new DrizzleConfirmTokenStore(options.db),\n },\n { provide: AGENT_CONFIRM_TOKEN_STORE, useExisting: DrizzleConfirmTokenStore },\n // Text channels' state (`@dudousxd/nestjs-agent-channels`), shared by every replica.\n { provide: DrizzleChannelStore, useFactory: () => new DrizzleChannelStore(options.db) },\n { provide: AGENT_CHANNEL_STORE, useExisting: DrizzleChannelStore },\n // Personal Agent Protocol (Poppy) conversations and connections, shared by every replica.\n { provide: DrizzlePoppyStore, useFactory: () => new DrizzlePoppyStore(options.db) },\n { provide: AGENT_POPPY_STORE, useExisting: DrizzlePoppyStore },\n {\n provide: DrizzlePoppyConnectionStore,\n useFactory: () => new DrizzlePoppyConnectionStore(options.db),\n },\n { provide: AGENT_POPPY_CONNECTION_STORE, useExisting: DrizzlePoppyConnectionStore },\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 DrizzleConfirmTokenStore,\n AGENT_CONFIRM_TOKEN_STORE,\n DrizzleChannelStore,\n AGENT_CHANNEL_STORE,\n DrizzlePoppyStore,\n AGENT_POPPY_STORE,\n DrizzlePoppyConnectionStore,\n AGENT_POPPY_CONNECTION_STORE,\n ],\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC4BA,yBAQO;AAgBA,IAAMA,kBAAcC,gCACzB,gBACA;EACEC,QAAIC,yBAAK,IAAA,EAAMC,WAAU;EACzBC,cAAUF,yBAAK,WAAA,EAAaG,QAAO;EACnCC,eAAWJ,yBAAK,YAAA;EAChBK,WAAOL,yBAAK,OAAA,EAASG,QAAO;EAC5BG,eAAWC,4BAAQ,aAAa;IAAEC,MAAM;EAAU,CAAA,EAAGL,QAAO,EAAGM,QAAQ,KAAA;EACvEC,oBAAgBV,yBAAK,kBAAA;;EAErBW,kBAAcX,yBAAK,eAAA;;EAEnBY,WAAOZ,yBAAK,OAAA;;EAEZa,aAASb,yBAAK,SAAA;;EAEdc,gBAAYd,yBAAK,eAAe;IAAEQ,MAAM;EAAO,CAAA,EAAGO,MAAK;EACvDC,eAAWT,4BAAQ,cAAc;IAAEC,MAAM;EAAe,CAAA,EAAGL,QAAO;EAClEc,eAAWV,4BAAQ,cAAc;IAAEC,MAAM;EAAe,CAAA,EAAGL,QAAO;EAClEe,eAAWX,4BAAQ,cAAc;IAAEC,MAAM;EAAe,CAAA;AAC1D,GACA,CAACW,UAAU;MACTC,0BAAM,gCAAA,EAAkCC,GAAGF,MAAMjB,UAAUiB,MAAMF,SAAS;;MAE1EG,0BAAM,gCAAA,EAAkCC,GAAGF,MAAMT,cAAc;CA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;;;QAIvD;UAAEP,SAASU;UAAuBR,YAAY,6BAAM,IAAIQ,sBAAsBb,QAAQM,EAAE,GAA1C;QAA4C;QAC1F;UACEH,SAASW;UACTT,YAAY,6BAAM,IAAIS,oBAAoBd,QAAQM,EAAE,GAAxC;QACd;;;QAGAN,QAAQe,eACJ;UAAEZ,SAASa;UAAqBC,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;;QAE3E;UACEf,SAASkB;UACThB,YAAY,6BAAM,IAAIgB,yBAAyBrB,QAAQM,EAAE,GAA7C;QACd;QACA;UAAEH,SAASmB;UAA2BV,aAAaS;QAAyB;;QAE5E;UAAElB,SAASoB;UAAqBlB,YAAY,6BAAM,IAAIkB,oBAAoBvB,QAAQM,EAAE,GAAxC;QAA0C;QACtF;UAAEH,SAASqB;UAAqBZ,aAAaW;QAAoB;;QAEjE;UAAEpB,SAASsB;UAAmBpB,YAAY,6BAAM,IAAIoB,kBAAkBzB,QAAQM,EAAE,GAAtC;QAAwC;QAClF;UAAEH,SAASuB;UAAmBd,aAAaa;QAAkB;QAC7D;UACEtB,SAASwB;UACTtB,YAAY,6BAAM,IAAIsB,4BAA4B3B,QAAQM,EAAE,GAAhD;QACd;QACA;UAAEH,SAASyB;UAA8BhB,aAAae;QAA4B;;MAEpFE,SAAS;WACH7B,QAAQE,oBAAoB,QAAQ,CAAA,IAAK;UAACE;;QAC9CM;QACAC;QACAE;QACAK;QACAE;QACAN;QACAE;QACAK;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;;IAEJ;EACF;AACF;;;;","names":["agentThread","sqliteTable","id","text","primaryKey","actorRef","notNull","tenantRef","title","transient","integer","mode","default","activeStreamId","defaultAgent","model","persona","queuePause","$type","createdAt","updatedAt","deletedAt","table","index","on","agentMessage","threadId","references","onDelete","role","actionProposalOutcome","content","toolCalls","toolResults","attachments","followUps","usage","agentName","runId","reasoning","reasoningMs","ui","feedback","seq","agentToolCall","proposalId","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","confirmation","approver","expiresAt","remember","decidedVia","agentQueuedMessage","uiCapabilities","hostContext","actor","pageContext","interrupt","position","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","real","costSource","feature","provider","audioSeconds","characters","requests","metadata","countsTowardsQuota","agentGenuiCall","step","channel","attempt","outcome","validity","errorCategory","errorMessage","firstFrameMs","completeFrameMs","payloadBytes","payload","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentRun","durationMs","ttftMs","errorCode","retries","startedAt","settledAt","promptHash","parentRunId","queueMs","modelMs","toolsMs","modelCalls","timings","agentMemory","scope","key","originAuthor","originThreadId","originRunId","originActorRef","pinned","uniqueIndex","ragIngestionLog","documentId","collection","ownerType","ownerId","source","mimeType","size","chunks","reason","agentChannelState","value","agentConfirmToken","hash","tool","agentStreamFrame","frame","columns","agentActionProposal","scopeKey","decision","logicalSort","createFingerprint","proposal","version","executionStatus","leaseExpiresAt","deliveryStatus","deliveryLeaseExpiresAt","replacementGroupKey","outcomeIdKey","proposalExpiresAt","discoveryIndexVersion","agentPoppyConversation","clientId","userId","accountRef","parentId","openDirectId","responder","context","activeRunId","turnSeq","grantInfo","readerHolder","readerUntil","prunedSeq","agentPoppyEvent","conversationId","type","event","eventKey","agentPoppyMessage","owner","fingerprint","response","agentPoppyConnection","issuer","domain","organization","state","agentPoppyConnect","toolCallId","flow","agentSchema","import_drizzle_orm","import_mysql_core","import_pg_core","import_sqlite_core","import_mysql_core","import_pg_core","ts","name","datetime","mode","fsp","key","varchar","length","agentThread","mysqlTable","id","primaryKey","actorRef","notNull","tenantRef","title","transient","boolean","default","activeStreamId","defaultAgent","model","persona","queuePause","json","$type","createdAt","updatedAt","deletedAt","table","index","on","agentMessage","threadId","references","onDelete","role","actionProposalOutcome","longtext","content","toolCalls","toolResults","attachments","followUps","usage","agentName","runId","reasoning","reasoningMs","int","ui","feedback","seq","agentToolCall","proposalId","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","confirmation","approver","expiresAt","remember","decidedVia","agentQueuedMessage","uiCapabilities","hostContext","actor","pageContext","interrupt","position","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","double","costSource","feature","provider","audioSeconds","characters","bigint","requests","metadata","countsTowardsQuota","agentGenuiCall","step","channel","attempt","outcome","validity","errorCategory","errorMessage","firstFrameMs","completeFrameMs","payloadBytes","payload","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentRun","durationMs","ttftMs","errorCode","retries","startedAt","settledAt","promptHash","parentRunId","queueMs","modelMs","toolsMs","modelCalls","timings","agentMemory","scope","text","originAuthor","originThreadId","originRunId","originActorRef","pinned","uniqueIndex","ragIngestionLog","documentId","collection","ownerType","ownerId","source","mimeType","size","chunks","reason","agentChannelState","value","agentConfirmToken","hash","tool","agentStreamFrame","frame","columns","proposalJson","customType","dataType","toDriver","canonicalActionProposalJson","fromDriver","JSON","parse","agentActionProposal","scopeKey","decision","logicalSort","createFingerprint","proposal","version","executionStatus","leaseExpiresAt","deliveryStatus","deliveryLeaseExpiresAt","replacementGroupKey","outcomeIdKey","proposalExpiresAt","discoveryIndexVersion","agentPoppyConversation","clientId","userId","accountRef","parentId","openDirectId","responder","context","activeRunId","turnSeq","grantInfo","readerHolder","readerUntil","prunedSeq","agentPoppyEvent","conversationId","type","event","eventKey","agentPoppyMessage","owner","fingerprint","response","agentPoppyConnection","issuer","domain","organization","state","agentPoppyConnect","toolCallId","flow","mysqlAgentSchema","import_nestjs_agent_core","ts","name","timestamp","withTimezone","precision","mode","agentThread","pgTable","id","text","primaryKey","actorRef","notNull","tenantRef","title","transient","boolean","default","activeStreamId","defaultAgent","model","persona","queuePause","jsonb","$type","createdAt","updatedAt","deletedAt","table","index","on","agentMessage","threadId","references","onDelete","role","actionProposalOutcome","content","toolCalls","toolResults","attachments","followUps","usage","agentName","runId","reasoning","reasoningMs","integer","ui","feedback","seq","agentToolCall","proposalId","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","confirmation","approver","expiresAt","remember","decidedVia","agentQueuedMessage","uiCapabilities","hostContext","actor","pageContext","interrupt","position","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","doublePrecision","costSource","feature","provider","audioSeconds","characters","bigint","requests","metadata","countsTowardsQuota","agentGenuiCall","step","channel","attempt","outcome","validity","errorCategory","errorMessage","varchar","length","firstFrameMs","completeFrameMs","payloadBytes","payload","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentRun","durationMs","ttftMs","errorCode","retries","startedAt","settledAt","promptHash","parentRunId","queueMs","modelMs","toolsMs","modelCalls","timings","agentMemory","scope","key","originAuthor","originThreadId","originRunId","originActorRef","pinned","uniqueIndex","ragIngestionLog","documentId","collection","ownerType","ownerId","source","mimeType","size","chunks","reason","agentChannelState","value","agentConfirmToken","hash","tool","agentStreamFrame","frame","columns","proposalJson","customType","dataType","toDriver","canonicalActionProposalJson","fromDriver","JSON","parse","agentActionProposal","scopeKey","decision","logicalSort","createFingerprint","proposal","version","executionStatus","leaseExpiresAt","deliveryStatus","deliveryLeaseExpiresAt","replacementGroupKey","outcomeIdKey","proposalExpiresAt","discoveryIndexVersion","agentPoppyConversation","clientId","userId","accountRef","parentId","openDirectId","responder","context","activeRunId","turnSeq","grantInfo","readerHolder","readerUntil","prunedSeq","agentPoppyEvent","conversationId","type","event","eventKey","agentPoppyMessage","owner","fingerprint","response","agentPoppyConnection","issuer","domain","organization","state","agentPoppyConnect","toolCallId","flow","pgAgentSchema","agentDialectOf","db","is","PgDatabase","MySqlDatabase","agentTablesFor","dialect","pgAgentSchema","mysqlAgentSchema","agentSchema","asBuilder","affectedRows","statement","column","returning","affected","length","mysqlAffectedRows","result","header","Array","isArray","counts","count","rowsAffected","runSql","run","execute","querySql","all","rows","isUniqueViolation","error","current","code","errno","startsWith","cause","upsert","insert","target","set","onDuplicateKeyUpdate","onConflictDoUpdate","ensureAgentSchema","db","dialect","agentDialectOf","transaction","tx","execute","sql","raw","LOCK_NAME","heal","MYSQL_TABLE_OPTIONS","tableSpec","table","config","pgTableConfig","mysqlTableConfig","sqliteTableConfig","columns","compositeKey","primaryKeys","map","column","name","primaryKey","filter","primary","c","foreignKeys","foreignKey","reference","getTableName","foreignTable","foreignColumns","onDelete","undefined","indexes","index","String","unique","quote","identifier","literal","value","replaceAll","columnDefinition","parts","getSQLType","notNull","push","hasDefault","default","join","createTableSql","spec","q","lines","toUpperCase","options","agentSchemaDdl","statements","specs","createIndexSql","guard","all","Object","values","agentTablesFor","ordered","placed","Set","length","ready","has","every","key","Error","add","existingColumns","columnNullability","keys","rows","querySql","Map","row","Number","notnull","NAME","nullable","NULLABLE","relaxNotNull","runSql","some","other","scratch","present","list","error","catch","indexExists","query","includes","get","import_nestjs_agent_core","import_drizzle_orm","import_nestjs_agent_core","import_drizzle_orm","actionProposalTransactionMode","kind","undefined","includes","DrizzleActionProposalStore","db","rawDb","actionProposalAdmissionSupported","synchronousSqlite","dialect","table","clock","options","kind","entityKind","transactionMode","actionProposalTransactionMode","agentDialectOf","agentTablesFor","agentActionProposal","asBuilder","Date","now","createActionProposal","input","proposal","initialActionProposal","row","id","physicalId","scopeKey","decision","logicalSort","createFingerprint","canonicalActionProposalJson","discoveryMetadata","version","createdAt","insert","inserted","mysqlAffectedRows","ignore","values","affectedRows","onConflictDoNothing","stored","read","status","createReplacingActionProposal","replacementKey","transactionSteps","replacementSteps","supersedeActionProposal","scope","command","replacement","getActionProposal","replacementProposalId","mutate","transitionActionProposalSupersession","thread","agentThread","query","update","set","updatedAt","sql","where","eq","threadId","threads","lockQuery","select","from","limit","owner","deletedAt","actorRef","tenantRef","existingRows","existing","actionProposalScopeMatches","groupKey","replacementGroupKey","Error","pending","and","returning","count","length","old","result","via","next","updated","settled","toolCallSettlement","listActionProposals","validateActionProposalListQuery","rows","after","undefined","or","gt","orderBy","asc","map","filter","decideActionProposal","transitionActionProposalDecision","claimActionProposal","transitionActionProposalClaim","randomUUID","extendActionProposalLease","transitionActionProposalLease","settleActionProposal","transitionActionProposalSettlement","claimNextActionProposal","validateActionProposalWorkerClaim","candidates","discoveryIndexVersion","executionStatus","lte","leaseExpiresAt","candidate","expireActionProposals","validateActionProposalExpiryBatch","proposalExpiresAt","expired","backfillActionProposalDiscoveryIndex","validateActionProposalDiscoveryIndexBatch","changed","rememberedActionProposalApprovals","Set","decisionAudit","remember","toolName","getThreadActionProposalScope","isNull","claimNextActionProposalOutcome","deliveryStatus","deliveryLeaseExpiresAt","time","claimed","claimActionProposalOutcome","outcome","outcomeDelivery","lease","outcomeId","token","generation","admitActionProposalOutcome","admissionSteps","factory","database","transaction","tx","runSync","behavior","runAsync","Number","isSafeInteger","TypeError","tables","outcomeIdKey","delivery","messageId","actionProposalOutcomeFenceValid","threadQuery","discarded","activeStreamId","seqRows","last","max","agentMessage","seq","role","content","actionProposalOutcomeText","actionProposalOutcome","ui","admitted","previous","toolCallUpdateForTransition","toolCall","agentToolCall","output","error","executedByRef","decidedVia","executedAt","toolCallId","proposalId","transition","attempt","createHash","digest","sort","index","charCodeAt","toString","padStart","expiresAt","execution","for","steps","done","value","statement","all","run","turnMessageColumns","message","id","role","content","agentName","toolCalls","toolResults","attachments","createdAt","DrizzleAgentStore","db","dialect","t","proposals","options","DrizzleActionProposalStore","agentDialectOf","agentTablesFor","asBuilder","createActionProposal","args","getActionProposal","listActionProposals","decideActionProposal","claimActionProposal","extendActionProposalLease","claimNextActionProposal","expireActionProposals","backfillActionProposalDiscoveryIndex","command","settleActionProposal","createReplacingActionProposal","supersedeActionProposal","actionProposalAdmissionSupported","getThreadActionProposalScope","threadId","claimNextActionProposalOutcome","admitActionProposalOutcome","createThread","input","now","Date","thread","crypto","randomUUID","actorRef","actor","tenantRef","title","transient","activeStreamId","defaultAgent","model","persona","queuePause","updatedAt","deletedAt","insert","agentThread","values","toSummary","getThread","select","from","where","and","eq","isNull","undefined","messages","agentMessage","orderBy","messageOrder","last","length","approvals","approvalsFor","map","stored","toStoredMessage","onMessage","get","activeRunId","loadThreadForTurn","query","loadTurnWindow","messageLimit","answered","limit","hasAssistantMessage","window","messageOrderNewestFirst","rows","reverse","row","listThreads","listThreadsWhere","listThreadsForTenant","filter","column","visible","tenant","nulls","or","threads","desc","previews","lastMessageContents","threadIds","contents","Map","highest","seq","max","inArray","groupBy","numbered","Number","has","set","softDeleteThread","update","forkThread","fromMessageId","source","Error","cutoff","findIndex","kept","slice","fork","index","followUps","usage","runId","reasoning","reasoningMs","ui","actionProposalOutcome","ownerOfThread","ownerOfToolCall","toolCallId","agentToolCall","innerJoin","messageId","runForToolCall","messageIds","byMessage","status","approver","confirmation","expiresAt","remember","executedByRef","decidedVia","error","isNotNull","asc","approval","toolCallApprovalFromRow","list","push","rememberedApprovals","selectDistinct","toolName","scope","proposalNames","rememberedActionProposalApprovals","Set","toolCallInput","toolCallApproval","toISOString","tenantOf","target","ownerOfActiveStream","setTitle","promoteThread","activeHolder","sql","nextMessageSeq","activeRunForThread","claimActiveStream","holders","replacing","claimed","affectedRows","releaseActiveStream","released","enqueueMessage","edge","first","min","agentQueuedMessage","position","at","uiCapabilities","hostContext","pageContext","interrupt","toQueuedMessage","listQueue","getQueuedMessage","updateQueuedMessage","patch","updates","moveQueuedMessage","moving","order","Math","trunc","splice","entries","removeQueuedMessage","removed","delete","clearQueue","setQueuePause","pause","setActiveStream","updateThread","Object","keys","modelForThread","personaForThread","threadSettings","defaultAgentForThread","recordRunStart","run","runRow","durationMs","ttftMs","costUsd","modelId","errorCode","errorMessage","retries","startedAt","settledAt","promptHash","parentRunId","queueMs","round","modelMs","toolsMs","modelCalls","timings","agentRun","recordRunEnd","end","steps","bumpRunRetries","appendMessage","canonicalActionProposalJson","feedback","setMessageToolResults","results","setMessageUi","threadOfMessage","setMessageFeedback","truncateFrom","doomedIds","recordToolCall","proposalId","toolType","output","executionMs","executedAt","updateToolCall","toolCallOutcomes","toolCallIds","failUnsettledToolCalls","pending","referencedMediaIds","mediaIds","queued","wanted","found","attachment","mediaId","add","recordUsage","agentTokenUsage","feature","provider","audioSeconds","characters","requests","metadata","countsTowardsQuota","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costSource","recordGenuiCalls","table","agentGenuiCall","columns","step","channel","mode","attempt","outcome","validity","errorCategory","firstFrameMs","completeFrameMs","payloadBytes","payload","upsert","quotaToday","day","usageBetween","fromDay","toDay","totals","usageWindows","sumUsage","ranges","sumUsageWindows","usageWindowsForTenant","owner","bounds","start","within","gte","lte","forEach","getTime","to","_","usedTokens","estimatedCostUsd","lastContent","lastMessagePreview","JSON","parse","import_nestjs_agent_core","import_drizzle_orm","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","toGenuiCallRow","row","toolCallId","id","runId","threadId","actorRef","agentName","step","Number","toolName","channel","mode","modelId","attempt","outcome","validity","errorCategory","errorMessage","inputTokens","outputTokens","costUsd","costSource","firstFrameMs","completeFrameMs","payloadBytes","payload","createdAt","Date","toRecentRunRow","run","status","durationMs","ttftMs","errorCode","retries","startedAt","toISOString","promptHash","parentRunId","queueMs","modelMs","toolsMs","modelCalls","toolCalls","toRunTimings","Array","isArray","timings","steps","toRunToolCallRow","toolCall","toolType","executionMs","executedByRef","error","toUsageInput","feature","purpose","audioSeconds","characters","requests","slice","cacheWriteTokens","cacheReadTokens","percentileMs","sortedDurationsMs","p","length","offset","Math","min","floor","DrizzleGovernanceQueries","db","dialect","t","source","pricingStore","tenant","agentDialectOf","agentTablesFor","asBuilder","forTenant","filter","tenantOn","column","undefined","isNull","nulls","or","eq","threadIn","visible","agentThread","tenantRef","inArray","select","from","where","toolCallIn","messageId","agentMessage","loadPricing","prices","listCurrentPrices","pricing","Map","price","set","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","usageInRange","range","withFeature","usageRangeBounds","usage","agentTokenUsage","and","gte","lt","map","spendByModel","bucketByModel","spendByFeature","bucketByFeature","usageBreakdown","bucketUsageBreakdown","spendByActor","bucketByActor","spendByThread","limit","threadIds","Set","flatMap","threads","title","deletedAt","threadsById","thread","bucketByThread","includeUnknownThreads","usageTrend","bucketUsageTrend","recentToolCalls","agentToolCall","innerJoin","orderBy","desc","threadRollups","rollups","messageCount","totalTokens","messageCounts","count","groupBy","bucket","get","usageTotals","sum","toThreadActivityRows","rollup","lastActivityAt","updatedAt","recentThreads","runsInRange","agentRun","lte","runMetrics","runs","completed","failed","settledDurationsMs","ttftsMs","push","sort","left","right","successRate","durationP50Ms","durationP95Ms","ttftP50Ms","ttftP95Ms","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","deleted","threadDetail","usageRows","rollupThreadUsage","messageCountRow","messages","seq","messageLimit","toolCallCounts","toolCallCountsByMessage","message","runTotalRow","runLimit","runTotal","content","truncated","truncateDetailContent","role","toolCallCount","genuiStats","table","agentGenuiCall","getTime","summarizeGenuiCalls","messageIds","counts","import_nestjs_agent_core","import_drizzle_orm","toRecord","row","id","key","text","scope","origin","author","originAuthor","originThreadId","threadId","originRunId","runId","originActorRef","actorRef","updatedAt","toISOString","pinned","DrizzleMemoryProvider","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","list","scopes","length","rows","select","from","agentMemory","where","inArray","map","forget","ctx","deleted","affectedRows","delete","and","eq","actorScope","actor","write","assertAuthorMayWriteScope","now","Date","columns","memory","set","insert","values","crypto","randomUUID","createdAt","upsert","onConflictDoUpdate","target","returning","undefined","Error","pin","updated","update","own","import_drizzle_orm","DrizzlePricingStore","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","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","import_nestjs_agent_core","import_drizzle_orm","DrizzleStreamFrameTable","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","append","runId","row","runSql","sql","frame","error","createdAt","read","after","limit","select","seq","agentStreamFrame","from","where","and","eq","gt","orderBy","asc","has","rows","length","remove","runIds","delete","inArray","lapsedRuns","cutoff","groupBy","having","lt","max","map","isUniqueViolation","DrizzleTokenStreamSink","SqlTokenStreamSink","options","import_drizzle_orm","DrizzleConfirmTokenStore","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","claim","input","row","hash","actorRef","tool","expiresAt","createdAt","Date","now","table","agentConfirmToken","insert","mysqlAffectedRows","ignore","values","inserted","affectedRows","onConflictDoNothing","release","delete","where","eq","purgeExpired","lt","import_node_crypto","import_drizzle_orm","channelStateKey","key","length","createHash","update","digest","DrizzleChannelStore","db","dialect","t","purgeEveryMs","lastPurge","options","agentDialectOf","agentTablesFor","asBuilder","claim","ttlMs","table","agentChannelState","now","Date","purgeExpired","id","delete","where","and","eq","lte","expiresAt","row","value","createdAt","insert","mysqlAffectedRows","ignore","values","inserted","affectedRows","onConflictDoNothing","get","rows","select","from","gt","set","upsert","import_nestjs_agent_core","import_drizzle_orm","MAX_APPEND_ATTEMPTS","sleep","ms","Promise","resolve","setTimeout","nullable","value","String","toInt","Number","parseInt","PATCH_COLUMNS","accountRef","threadId","openDirectId","status","responder","context","activeRunId","turnSeq","grant","prunedSeq","DrizzlePoppyStore","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","createConversation","record","insert","agentPoppyConversation","values","id","clientId","userId","agentName","parentId","JSON","stringify","grantInfo","readerHolder","readerUntil","createdAt","updatedAt","getConversation","table","row","select","from","where","eq","limit","parse","updateConversation","patch","set","Date","now","key","column","Object","entries","undefined","update","appendEvent","conversationId","body","options","agentPoppyEvent","attempt","existing","seq","event","and","eventKey","created","lastSeq","stored","newEventId","created_at","toISOString","inserted","insertIgnore","type","error","isUniqueViolation","Error","Math","random","min","last","orderBy","desc","conversations","conversation","listEvents","afterSeq","rows","gt","map","findEventSeq","eventId","pruneEvents","before","dropped","lt","upTo","delete","lte","claimMessage","owner","messageId","receipt","agentPoppyMessage","fingerprint","response","releaseMessage","leaseReader","holder","ttlMs","taken","affectedRows","or","isNull","releaseReader","mysqlAffectedRows","ignore","statement","onConflictDoNothing","import_drizzle_orm","nullable","value","String","toInt","Number","DrizzlePoppyConnectionStore","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","listConnections","owner","table","agentPoppyConnection","rows","select","from","where","eq","orderBy","asc","domain","issuer","map","toConnection","getConnection","row","and","limit","saveConnection","record","columns","organization","scope","status","state","updatedAt","upsert","insert","values","createdAt","deleteConnection","delete","createPending","agentPoppyConnect","id","actor","JSON","stringify","threadId","runId","toolCallId","flow","expiresAt","ignore","onConflictDoNothing","getPending","parse","updatePending","patch","set","undefined","Object","keys","length","update","import_drizzle_orm","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","cursorColumns","log","DrizzleRagIngestionLog","logger","Logger","teardowns","inFlight","Set","db","dialect","t","agentDialectOf","agentTablesFor","asBuilder","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","affectedRows","delete","removeByCollection","collection","page","cursor","keyset","and","base","or","lt","gt","mediaId","now","Date","ownerType","ownerId","source","mimeType","size","outcome","chunks","reason","error","upsert","insert","values","createdAt","warn","Error","String","promise","tracked","finally","add","import_nestjs_agent_core","import_common","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","DrizzleConfirmTokenStore","AGENT_CONFIRM_TOKEN_STORE","DrizzleChannelStore","AGENT_CHANNEL_STORE","DrizzlePoppyStore","AGENT_POPPY_STORE","DrizzlePoppyConnectionStore","AGENT_POPPY_CONNECTION_STORE","exports"]}