@dudousxd/nestjs-agent-store-drizzle 0.3.4 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +204 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +457 -4
- package/dist/index.d.ts +457 -4
- package/dist/index.js +204 -3
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -113,12 +113,34 @@ var agentModelPricing = sqliteTable("agent_model_pricing", {
|
|
|
113
113
|
mode: "boolean"
|
|
114
114
|
}).notNull()
|
|
115
115
|
});
|
|
116
|
+
var agentRun = sqliteTable("agent_run", {
|
|
117
|
+
id: text("id").primaryKey(),
|
|
118
|
+
threadId: text("thread_id").notNull().references(() => agentThread.id, {
|
|
119
|
+
onDelete: "cascade"
|
|
120
|
+
}),
|
|
121
|
+
actorRef: text("actor_ref").notNull(),
|
|
122
|
+
agentName: text("agent_name"),
|
|
123
|
+
status: text("status").$type().notNull(),
|
|
124
|
+
durationMs: integer("duration_ms"),
|
|
125
|
+
errorCode: text("error_code"),
|
|
126
|
+
errorMessage: text("error_message"),
|
|
127
|
+
retries: integer("retries").notNull().default(0),
|
|
128
|
+
startedAt: integer("started_at", {
|
|
129
|
+
mode: "timestamp_ms"
|
|
130
|
+
}).notNull(),
|
|
131
|
+
settledAt: integer("settled_at", {
|
|
132
|
+
mode: "timestamp_ms"
|
|
133
|
+
})
|
|
134
|
+
}, (table) => [
|
|
135
|
+
index("agent_run_started_idx").on(table.startedAt)
|
|
136
|
+
]);
|
|
116
137
|
var agentSchema = {
|
|
117
138
|
agentThread,
|
|
118
139
|
agentMessage,
|
|
119
140
|
agentToolCall,
|
|
120
141
|
agentTokenUsage,
|
|
121
|
-
agentModelPricing
|
|
142
|
+
agentModelPricing,
|
|
143
|
+
agentRun
|
|
122
144
|
};
|
|
123
145
|
|
|
124
146
|
// src/ensure-schema.ts
|
|
@@ -190,7 +212,22 @@ var statements = [
|
|
|
190
212
|
cache_read_price_per_1m REAL,
|
|
191
213
|
effective_from INTEGER NOT NULL,
|
|
192
214
|
is_current INTEGER NOT NULL
|
|
193
|
-
)
|
|
215
|
+
)`,
|
|
216
|
+
`CREATE TABLE IF NOT EXISTS agent_run (
|
|
217
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
218
|
+
thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,
|
|
219
|
+
actor_ref TEXT NOT NULL,
|
|
220
|
+
agent_name TEXT,
|
|
221
|
+
status TEXT NOT NULL,
|
|
222
|
+
duration_ms INTEGER,
|
|
223
|
+
error_code TEXT,
|
|
224
|
+
error_message TEXT,
|
|
225
|
+
retries INTEGER NOT NULL DEFAULT 0,
|
|
226
|
+
started_at INTEGER NOT NULL,
|
|
227
|
+
settled_at INTEGER
|
|
228
|
+
)`,
|
|
229
|
+
`CREATE INDEX IF NOT EXISTS agent_run_started_idx
|
|
230
|
+
ON agent_run (started_at)`
|
|
194
231
|
];
|
|
195
232
|
async function ensureAgentSchema(db) {
|
|
196
233
|
for (const statement of statements) {
|
|
@@ -200,7 +237,7 @@ async function ensureAgentSchema(db) {
|
|
|
200
237
|
__name(ensureAgentSchema, "ensureAgentSchema");
|
|
201
238
|
|
|
202
239
|
// src/drizzle-agent-store.ts
|
|
203
|
-
import { and, asc, desc, eq, gte, inArray, isNull, lte } from "drizzle-orm";
|
|
240
|
+
import { and, asc, desc, eq, gte, inArray, isNull, lte, sql as sql2 } from "drizzle-orm";
|
|
204
241
|
var DrizzleAgentStore = class {
|
|
205
242
|
static {
|
|
206
243
|
__name(this, "DrizzleAgentStore");
|
|
@@ -332,6 +369,46 @@ var DrizzleAgentStore = class {
|
|
|
332
369
|
activeStreamId: runId
|
|
333
370
|
}).where(eq(agentThread.id, threadId));
|
|
334
371
|
}
|
|
372
|
+
/** Persist the start of a run (turn). Replay-safe: called under a durable localStep. */
|
|
373
|
+
async recordRunStart(run) {
|
|
374
|
+
const runRow = {
|
|
375
|
+
id: run.runId,
|
|
376
|
+
threadId: run.threadId,
|
|
377
|
+
actorRef: run.actorRef,
|
|
378
|
+
agentName: run.agentName ?? null,
|
|
379
|
+
status: "running",
|
|
380
|
+
durationMs: null,
|
|
381
|
+
errorCode: null,
|
|
382
|
+
errorMessage: null,
|
|
383
|
+
retries: 0,
|
|
384
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
385
|
+
settledAt: null
|
|
386
|
+
};
|
|
387
|
+
await this.db.insert(agentRun).values(runRow);
|
|
388
|
+
}
|
|
389
|
+
/** Settle a run's outcome. A no-op when the run is unknown (mirrors `setTitle`/`updateThread`). */
|
|
390
|
+
async recordRunEnd(end) {
|
|
391
|
+
const updates = {
|
|
392
|
+
status: end.status,
|
|
393
|
+
settledAt: /* @__PURE__ */ new Date()
|
|
394
|
+
};
|
|
395
|
+
if (end.durationMs !== void 0) {
|
|
396
|
+
updates.durationMs = end.durationMs;
|
|
397
|
+
}
|
|
398
|
+
if (end.errorCode !== void 0) {
|
|
399
|
+
updates.errorCode = end.errorCode;
|
|
400
|
+
}
|
|
401
|
+
if (end.errorMessage !== void 0) {
|
|
402
|
+
updates.errorMessage = end.errorMessage;
|
|
403
|
+
}
|
|
404
|
+
await this.db.update(agentRun).set(updates).where(eq(agentRun.id, end.runId));
|
|
405
|
+
}
|
|
406
|
+
/** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */
|
|
407
|
+
async bumpRunRetries(runId) {
|
|
408
|
+
await this.db.update(agentRun).set({
|
|
409
|
+
retries: sql2`${agentRun.retries} + 1`
|
|
410
|
+
}).where(eq(agentRun.id, runId));
|
|
411
|
+
}
|
|
335
412
|
async appendMessage(input) {
|
|
336
413
|
const [thread] = await this.db.select().from(agentThread).where(eq(agentThread.id, input.threadId));
|
|
337
414
|
if (thread === void 0) {
|
|
@@ -470,6 +547,8 @@ var DrizzleAgentStore = class {
|
|
|
470
547
|
// src/drizzle-governance-queries.ts
|
|
471
548
|
import { bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, dayBoundsUtc } from "@dudousxd/nestjs-agent-core";
|
|
472
549
|
import { and as and2, count, desc as desc2, eq as eq2, gte as gte2, inArray as inArray2, isNull as isNull2, lte as lte2 } from "drizzle-orm";
|
|
550
|
+
var UNCLASSIFIED_ERROR_CODE = "unknown";
|
|
551
|
+
var DEFAULT_AGENT_BUCKET = "(default)";
|
|
473
552
|
function toUsageInput(row) {
|
|
474
553
|
return {
|
|
475
554
|
modelId: row.modelId,
|
|
@@ -484,6 +563,14 @@ function toUsageInput(row) {
|
|
|
484
563
|
};
|
|
485
564
|
}
|
|
486
565
|
__name(toUsageInput, "toUsageInput");
|
|
566
|
+
function percentileMs(sortedDurationsMs, p) {
|
|
567
|
+
if (sortedDurationsMs.length === 0) {
|
|
568
|
+
return null;
|
|
569
|
+
}
|
|
570
|
+
const offset = Math.min(sortedDurationsMs.length - 1, Math.floor(p * sortedDurationsMs.length));
|
|
571
|
+
return sortedDurationsMs[offset] ?? null;
|
|
572
|
+
}
|
|
573
|
+
__name(percentileMs, "percentileMs");
|
|
487
574
|
var DrizzleGovernanceQueries = class {
|
|
488
575
|
static {
|
|
489
576
|
__name(this, "DrizzleGovernanceQueries");
|
|
@@ -589,6 +676,119 @@ var DrizzleGovernanceQueries = class {
|
|
|
589
676
|
}
|
|
590
677
|
return result;
|
|
591
678
|
}
|
|
679
|
+
async runsInRange(range) {
|
|
680
|
+
const { start, end } = dayBoundsUtc(range);
|
|
681
|
+
return this.db.select().from(agentRun).where(and2(gte2(agentRun.startedAt, start), lte2(agentRun.startedAt, end)));
|
|
682
|
+
}
|
|
683
|
+
async runMetrics(range) {
|
|
684
|
+
const runs = await this.runsInRange(range);
|
|
685
|
+
let completed = 0;
|
|
686
|
+
let failed = 0;
|
|
687
|
+
let retries = 0;
|
|
688
|
+
const settledDurationsMs = [];
|
|
689
|
+
for (const run of runs) {
|
|
690
|
+
if (run.status === "completed") {
|
|
691
|
+
completed += 1;
|
|
692
|
+
} else if (run.status === "failed") {
|
|
693
|
+
failed += 1;
|
|
694
|
+
}
|
|
695
|
+
retries += run.retries;
|
|
696
|
+
if ((run.status === "completed" || run.status === "failed") && run.durationMs != null) {
|
|
697
|
+
settledDurationsMs.push(run.durationMs);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
settledDurationsMs.sort((left, right) => left - right);
|
|
701
|
+
return {
|
|
702
|
+
runs: runs.length,
|
|
703
|
+
completed,
|
|
704
|
+
failed,
|
|
705
|
+
successRate: runs.length === 0 ? 0 : completed / runs.length,
|
|
706
|
+
retries,
|
|
707
|
+
durationP50Ms: percentileMs(settledDurationsMs, 0.5),
|
|
708
|
+
durationP95Ms: percentileMs(settledDurationsMs, 0.95)
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
async runsByAgent(range) {
|
|
712
|
+
const runs = await this.runsInRange(range);
|
|
713
|
+
const byAgent = /* @__PURE__ */ new Map();
|
|
714
|
+
for (const run of runs) {
|
|
715
|
+
const agentName = run.agentName ?? DEFAULT_AGENT_BUCKET;
|
|
716
|
+
const bucket = byAgent.get(agentName) ?? {
|
|
717
|
+
runs: 0,
|
|
718
|
+
failed: 0,
|
|
719
|
+
retries: 0
|
|
720
|
+
};
|
|
721
|
+
bucket.runs += 1;
|
|
722
|
+
bucket.failed += run.status === "failed" ? 1 : 0;
|
|
723
|
+
bucket.retries += run.retries;
|
|
724
|
+
byAgent.set(agentName, bucket);
|
|
725
|
+
}
|
|
726
|
+
const result = [];
|
|
727
|
+
for (const [agentName, bucket] of byAgent) {
|
|
728
|
+
result.push({
|
|
729
|
+
agentName,
|
|
730
|
+
...bucket
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
result.sort((left, right) => right.runs - left.runs || left.agentName.localeCompare(right.agentName));
|
|
734
|
+
return result;
|
|
735
|
+
}
|
|
736
|
+
async runErrors(range) {
|
|
737
|
+
const { start, end } = dayBoundsUtc(range);
|
|
738
|
+
const runs = await this.db.select().from(agentRun).where(and2(gte2(agentRun.startedAt, start), lte2(agentRun.startedAt, end), eq2(agentRun.status, "failed")));
|
|
739
|
+
const byError = /* @__PURE__ */ new Map();
|
|
740
|
+
for (const run of runs) {
|
|
741
|
+
const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;
|
|
742
|
+
byError.set(errorCode, (byError.get(errorCode) ?? 0) + 1);
|
|
743
|
+
}
|
|
744
|
+
const result = [];
|
|
745
|
+
for (const [errorCode, errorCount] of byError) {
|
|
746
|
+
result.push({
|
|
747
|
+
errorCode,
|
|
748
|
+
count: errorCount
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
result.sort((left, right) => right.count - left.count || left.errorCode.localeCompare(right.errorCode));
|
|
752
|
+
return result;
|
|
753
|
+
}
|
|
754
|
+
async runTrend(range) {
|
|
755
|
+
const runs = await this.runsInRange(range);
|
|
756
|
+
const byDay = /* @__PURE__ */ new Map();
|
|
757
|
+
for (const run of runs) {
|
|
758
|
+
const day = run.startedAt.toISOString().slice(0, 10);
|
|
759
|
+
const bucket = byDay.get(day) ?? {
|
|
760
|
+
runs: 0,
|
|
761
|
+
failed: 0
|
|
762
|
+
};
|
|
763
|
+
bucket.runs += 1;
|
|
764
|
+
bucket.failed += run.status === "failed" ? 1 : 0;
|
|
765
|
+
byDay.set(day, bucket);
|
|
766
|
+
}
|
|
767
|
+
const result = [];
|
|
768
|
+
for (const [day, bucket] of byDay) {
|
|
769
|
+
result.push({
|
|
770
|
+
day,
|
|
771
|
+
...bucket
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
result.sort((left, right) => left.day.localeCompare(right.day));
|
|
775
|
+
return result;
|
|
776
|
+
}
|
|
777
|
+
async recentRuns(limit) {
|
|
778
|
+
const runs = await this.db.select().from(agentRun).orderBy(desc2(agentRun.startedAt), desc2(agentRun.id)).limit(limit);
|
|
779
|
+
return runs.map((run) => ({
|
|
780
|
+
runId: run.id,
|
|
781
|
+
threadId: run.threadId,
|
|
782
|
+
actorRef: run.actorRef,
|
|
783
|
+
agentName: run.agentName ?? null,
|
|
784
|
+
status: run.status,
|
|
785
|
+
durationMs: run.durationMs ?? null,
|
|
786
|
+
errorCode: run.errorCode ?? null,
|
|
787
|
+
errorMessage: run.errorMessage ?? null,
|
|
788
|
+
retries: run.retries,
|
|
789
|
+
startedAt: run.startedAt.toISOString()
|
|
790
|
+
}));
|
|
791
|
+
}
|
|
592
792
|
};
|
|
593
793
|
|
|
594
794
|
// src/drizzle-pricing-store.ts
|
|
@@ -706,6 +906,7 @@ export {
|
|
|
706
906
|
DrizzlePricingStore,
|
|
707
907
|
agentMessage,
|
|
708
908
|
agentModelPricing,
|
|
909
|
+
agentRun,
|
|
709
910
|
agentSchema,
|
|
710
911
|
agentThread,
|
|
711
912
|
agentTokenUsage,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema.ts","../src/ensure-schema.ts","../src/drizzle-agent-store.ts","../src/drizzle-governance-queries.ts","../src/drizzle-pricing-store.ts","../src/drizzle-agent-store.module.ts"],"sourcesContent":["import type {\n MessageRole,\n MessageUsage,\n ToolCallRequest,\n ToolCallStatus,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n type BaseSQLiteDatabase,\n index,\n integer,\n real,\n sqliteTable,\n text,\n} from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle schema mirroring the MikroORM agent entities (same logical columns/relations):\n * threads, messages, tool calls, token usage and model pricing. 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 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n deletedAt: integer('deleted_at', { mode: 'timestamp_ms' }),\n },\n (table) => [index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt)],\n);\n\n/**\n * One stored message in a thread. The model-facing extras (`toolCalls`/`toolResults`/\n * `followUps`/`usage`) are folded into nullable JSON columns so a single row round-trips to a\n * {@link import('@dudousxd/nestjs-agent-core').StoredMessage}. `threadId` cascades on delete.\n */\nexport const agentMessage = sqliteTable(\n 'agent_message',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n role: text('role').$type<MessageRole>().notNull(),\n content: text('content').notNull(),\n toolCalls: text('tool_calls', { mode: 'json' }).$type<ToolCallRequest[]>(),\n toolResults: text('tool_results', { mode: 'json' }).$type<ToolResult[]>(),\n followUps: text('follow_ups', { mode: 'json' }).$type<string[]>(),\n usage: text('usage', { mode: 'json' }).$type<MessageUsage>(),\n agentName: text('agent_name'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_message_thread_created_idx').on(table.threadId, table.createdAt)],\n);\n\n/** A tool call requested during an assistant turn. The pk is the model-supplied `toolCallId`. */\nexport const agentToolCall = sqliteTable('agent_tool_call', {\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});\n\n/** A token-usage ledger row, summed per actor per day by `quotaToday`. */\nexport const agentTokenUsage = sqliteTable(\n 'agent_token_usage',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: text('actor_ref').notNull(),\n messageId: text('message_id'),\n modelId: text('model_id').notNull(),\n purpose: text('purpose').$type<UsagePurpose>().notNull(),\n inputTokens: integer('input_tokens').notNull(),\n outputTokens: integer('output_tokens').notNull(),\n /** Subset of `inputTokens` written to the prompt cache this turn; null when not reported. */\n cacheWriteTokens: integer('cache_write_tokens'),\n /** Subset of `inputTokens` served from the prompt cache this turn; null when not reported. */\n cacheReadTokens: integer('cache_read_tokens'),\n /** Provider-reported actual USD cost for the turn; null when only tokens were reported. */\n costUsd: real('cost_usd'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt)],\n);\n\n/** Per-model token pricing, versioned by `effectiveFrom`; `isCurrent` flags the live row. */\nexport const agentModelPricing = sqliteTable('agent_model_pricing', {\n id: text('id').primaryKey(),\n modelId: text('model_id').notNull(),\n inputPricePer1m: real('input_price_per_1m').notNull(),\n outputPricePer1m: real('output_price_per_1m').notNull(),\n /** Per-1M price for cache-write input tokens; null → price them at the input rate. */\n cacheWritePricePer1m: real('cache_write_price_per_1m'),\n /** Per-1M price for cache-read input tokens; null → price them at the input rate. */\n cacheReadPricePer1m: real('cache_read_price_per_1m'),\n effectiveFrom: integer('effective_from', { mode: 'timestamp_ms' }).notNull(),\n isCurrent: integer('is_current', { mode: 'boolean' }).notNull(),\n});\n\n/** The five agent tables as one schema object, ready for `drizzle(client, { schema })`. */\nexport const agentSchema = {\n agentThread,\n agentMessage,\n agentToolCall,\n agentTokenUsage,\n agentModelPricing,\n};\n\n/**\n * The dialect-portable Drizzle SQLite database handle the store operates on. Accepts any SQLite\n * driver (better-sqlite3, libsql, D1, …) in either sync or async result mode; the host app owns\n * the connection and passes the `drizzle(...)` instance in.\n */\nexport type AgentDrizzleDb = BaseSQLiteDatabase<'sync' | 'async', unknown>;\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","import { sql } from 'drizzle-orm';\nimport type { AgentDrizzleDb } from './schema.js';\n\n/**\n * Idempotent `CREATE TABLE IF NOT EXISTS` DDL for the five agent tables, mirroring\n * {@link import('./schema.js').agentSchema}. SQLite dialect (the db-test driver); kept here rather\n * than relying on drizzle-kit so the package can stand up its schema with no migration files. Safe\n * to run on boot against a shared database — it never drops or alters existing columns.\n */\nconst statements: string[] = [\n `CREATE TABLE IF NOT EXISTS agent_thread (\n id TEXT PRIMARY KEY NOT NULL,\n actor_ref TEXT NOT NULL,\n tenant_ref TEXT,\n title TEXT NOT NULL,\n transient INTEGER NOT NULL DEFAULT 0,\n active_stream_id TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n deleted_at INTEGER\n )`,\n `CREATE INDEX IF NOT EXISTS agent_thread_actor_updated_idx\n ON agent_thread (actor_ref, updated_at)`,\n `CREATE TABLE IF NOT EXISTS agent_message (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n role TEXT NOT NULL,\n content TEXT NOT NULL,\n tool_calls TEXT,\n tool_results TEXT,\n follow_ups TEXT,\n usage TEXT,\n agent_name TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS agent_message_thread_created_idx\n ON agent_message (thread_id, created_at)`,\n `CREATE TABLE IF NOT EXISTS agent_tool_call (\n id TEXT PRIMARY KEY NOT NULL,\n message_id TEXT NOT NULL REFERENCES agent_message(id) ON DELETE CASCADE,\n tool_name TEXT NOT NULL,\n tool_type TEXT NOT NULL,\n input TEXT,\n output TEXT,\n status TEXT NOT NULL,\n executed_by_ref TEXT,\n execution_ms INTEGER,\n error TEXT,\n created_at INTEGER NOT NULL,\n executed_at INTEGER\n )`,\n `CREATE TABLE IF NOT EXISTS agent_token_usage (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n actor_ref TEXT NOT NULL,\n message_id TEXT,\n model_id TEXT NOT NULL,\n purpose TEXT NOT NULL,\n input_tokens INTEGER NOT NULL,\n output_tokens INTEGER NOT NULL,\n cache_write_tokens INTEGER,\n cache_read_tokens INTEGER,\n cost_usd REAL,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS agent_token_usage_actor_created_idx\n ON agent_token_usage (actor_ref, created_at)`,\n `CREATE TABLE IF NOT EXISTS agent_model_pricing (\n id TEXT PRIMARY KEY NOT NULL,\n model_id TEXT NOT NULL,\n input_price_per_1m REAL NOT NULL,\n output_price_per_1m REAL NOT NULL,\n cache_write_price_per_1m REAL,\n cache_read_price_per_1m REAL,\n effective_from INTEGER NOT NULL,\n is_current INTEGER NOT NULL\n )`,\n];\n\n/** Runs the `CREATE TABLE IF NOT EXISTS` DDL above against the supplied Drizzle SQLite db. */\nexport async function ensureAgentSchema(db: AgentDrizzleDb): Promise<void> {\n for (const statement of statements) {\n await db.run(sql.raw(statement));\n }\n}\n","import type {\n AgentStore,\n AppendMessageInput,\n CreateThreadInput,\n RecordToolCallInput,\n RecordUsageInput,\n StoredMessage,\n ThreadDetail,\n ThreadSummary,\n UpdateToolCallInput,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, desc, eq, gte, inArray, isNull, lte } from 'drizzle-orm';\nimport {\n type AgentDrizzleDb,\n type AgentMessageRow,\n type AgentThreadRow,\n agentMessage,\n agentThread,\n agentTokenUsage,\n agentToolCall,\n} from './schema.js';\n\n/**\n * {@link AgentStore} backed by Drizzle ORM — a second adapter alongside the MikroORM one, proving\n * the store SPI is ORM-portable. A POJO receiving a Drizzle SQLite database handle (the host app\n * owns the connection). Behaviour mirrors {@link import('@dudousxd/nestjs-agent-store-mikro-orm')}\n * exactly (fork/truncate/quota/active-stream/soft-delete semantics) so the two are interchangeable.\n */\nexport class DrizzleAgentStore implements AgentStore {\n constructor(private readonly db: AgentDrizzleDb) {}\n\n async createThread(input: CreateThreadInput): Promise<ThreadSummary> {\n const now = new Date();\n const thread: AgentThreadRow = {\n id: crypto.randomUUID(),\n actorRef: input.actor.id,\n tenantRef: input.actor.tenantRef ?? null,\n title: input.title ?? 'New chat',\n transient: input.transient ?? false,\n activeStreamId: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(agentThread).values(thread);\n return this.toSummary(thread);\n }\n\n async getThread(threadId: string): Promise<ThreadDetail | null> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n if (thread === undefined) {\n return null;\n }\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const last = messages[messages.length - 1];\n return {\n ...this.toSummary(thread, last?.content),\n messages: messages.map((message) => this.toStoredMessage(message)),\n ...(thread.activeStreamId != null ? { activeStreamId: thread.activeStreamId } : {}),\n };\n }\n\n async listThreads(actorRef: string, limit = 50): Promise<ThreadSummary[]> {\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(\n and(\n eq(agentThread.actorRef, actorRef),\n eq(agentThread.transient, false),\n isNull(agentThread.deletedAt),\n ),\n )\n .orderBy(desc(agentThread.updatedAt))\n .limit(limit);\n const summaries: ThreadSummary[] = [];\n for (const thread of threads) {\n const [last] = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id))\n .orderBy(desc(agentMessage.createdAt), desc(agentMessage.id))\n .limit(1);\n summaries.push(this.toSummary(thread, last?.content));\n }\n return summaries;\n }\n\n async softDeleteThread(threadId: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ deletedAt: new Date() })\n .where(eq(agentThread.id, threadId));\n }\n\n async forkThread(threadId: string, fromMessageId: string): Promise<ThreadSummary> {\n const [source] = await this.db.select().from(agentThread).where(eq(agentThread.id, threadId));\n if (source === undefined) {\n throw new Error(`thread ${threadId} not found`);\n }\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const cutoff = messages.findIndex((message) => message.id === fromMessageId);\n const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;\n const now = new Date();\n const fork: AgentThreadRow = {\n id: crypto.randomUUID(),\n actorRef: source.actorRef,\n tenantRef: source.tenantRef,\n title: source.title,\n transient: false,\n activeStreamId: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(agentThread).values(fork);\n if (kept.length > 0) {\n await this.db.insert(agentMessage).values(\n kept.map((message) => ({\n id: crypto.randomUUID(),\n threadId: fork.id,\n role: message.role,\n content: message.content,\n toolCalls: message.toolCalls,\n toolResults: message.toolResults,\n followUps: message.followUps,\n usage: message.usage,\n agentName: message.agentName,\n createdAt: message.createdAt,\n })),\n );\n }\n return this.toSummary(fork);\n }\n\n async ownerOfThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n return thread?.actorRef ?? null;\n }\n\n async ownerOfToolCall(toolCallId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.id, toolCallId));\n return row?.actorRef ?? null;\n }\n\n async runForToolCall(toolCallId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ activeStreamId: agentThread.activeStreamId })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.id, toolCallId));\n return row?.activeStreamId ?? null;\n }\n\n async ownerOfActiveStream(runId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentThread)\n .where(and(eq(agentThread.activeStreamId, runId), isNull(agentThread.deletedAt)));\n return thread?.actorRef ?? null;\n }\n\n async setTitle(threadId: string, title: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ title, updatedAt: new Date() })\n .where(eq(agentThread.id, threadId));\n }\n\n async promoteThread(threadId: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ transient: false, updatedAt: new Date() })\n .where(and(eq(agentThread.id, threadId), eq(agentThread.transient, true)));\n }\n\n async setActiveStream(threadId: string, runId: string | null): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ activeStreamId: runId })\n .where(eq(agentThread.id, threadId));\n }\n\n async appendMessage(input: AppendMessageInput): Promise<StoredMessage> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(eq(agentThread.id, input.threadId));\n if (thread === undefined) {\n throw new Error(`thread ${input.threadId} not found`);\n }\n const now = new Date();\n const message: AgentMessageRow = {\n id: crypto.randomUUID(),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n toolCalls: input.toolCalls ?? null,\n toolResults: input.toolResults ?? null,\n followUps: input.followUps ?? null,\n usage: input.usage ?? null,\n agentName: input.agentName ?? null,\n createdAt: now,\n };\n await this.db.insert(agentMessage).values(message);\n await this.db\n .update(agentThread)\n .set({ updatedAt: now })\n .where(eq(agentThread.id, input.threadId));\n return this.toStoredMessage(message);\n }\n\n async truncateFrom(threadId: string, messageId: string): Promise<void> {\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const cutoff = messages.findIndex((message) => message.id === messageId);\n if (cutoff < 0) {\n return;\n }\n const doomedIds = messages.slice(cutoff).map((message) => message.id);\n await this.db.delete(agentToolCall).where(inArray(agentToolCall.messageId, doomedIds));\n await this.db.delete(agentMessage).where(inArray(agentMessage.id, doomedIds));\n }\n\n async recordToolCall(input: RecordToolCallInput): Promise<void> {\n await this.db.insert(agentToolCall).values({\n id: input.toolCallId,\n messageId: input.messageId,\n toolName: input.toolName,\n toolType: input.toolType,\n input: input.input,\n output: null,\n status: input.status,\n executedByRef: null,\n executionMs: null,\n error: null,\n createdAt: new Date(),\n executedAt: null,\n });\n }\n\n async updateToolCall(input: UpdateToolCallInput): Promise<void> {\n const updates: Partial<typeof agentToolCall.$inferInsert> = { status: input.status };\n if (input.output !== undefined) {\n updates.output = input.output;\n }\n if (input.error !== undefined) {\n updates.error = input.error;\n }\n if (input.executionMs !== undefined) {\n updates.executionMs = input.executionMs;\n }\n if (input.executedByRef !== undefined) {\n updates.executedByRef = input.executedByRef;\n }\n if (input.status === 'executed' || input.status === 'auto_executed') {\n updates.executedAt = new Date();\n }\n await this.db.update(agentToolCall).set(updates).where(eq(agentToolCall.id, input.toolCallId));\n }\n\n async recordUsage(input: RecordUsageInput): Promise<void> {\n await this.db.insert(agentTokenUsage).values({\n id: crypto.randomUUID(),\n threadId: input.threadId,\n actorRef: input.actorRef,\n messageId: input.messageId ?? null,\n modelId: input.modelId,\n purpose: input.purpose,\n inputTokens: input.usage.inputTokens,\n outputTokens: input.usage.outputTokens,\n cacheWriteTokens: input.usage.cacheWriteTokens ?? null,\n cacheReadTokens: input.usage.cacheReadTokens ?? null,\n costUsd: input.costUsd ?? null,\n createdAt: new Date(),\n });\n }\n\n async quotaToday(\n actorRef: string,\n day: string,\n ): Promise<{ usedTokens: number; costUsd: number }> {\n const start = new Date(`${day}T00:00:00.000Z`);\n const end = new Date(`${day}T23:59:59.999Z`);\n const rows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(\n and(\n eq(agentTokenUsage.actorRef, actorRef),\n gte(agentTokenUsage.createdAt, start),\n lte(agentTokenUsage.createdAt, end),\n ),\n );\n const usedTokens = rows.reduce((sum, row) => sum + row.inputTokens + row.outputTokens, 0);\n const costUsd = rows.reduce((sum, row) => sum + (row.costUsd ?? 0), 0);\n return { usedTokens, costUsd };\n }\n\n private toSummary(thread: AgentThreadRow, lastContent?: string): ThreadSummary {\n return {\n id: thread.id,\n title: thread.title,\n transient: thread.transient,\n createdAt: thread.createdAt.toISOString(),\n updatedAt: thread.updatedAt.toISOString(),\n ...(lastContent !== undefined ? { lastMessagePreview: lastContent.slice(0, 120) } : {}),\n };\n }\n\n private toStoredMessage(message: AgentMessageRow): StoredMessage {\n return {\n id: message.id,\n role: message.role,\n content: message.content,\n createdAt: message.createdAt.toISOString(),\n ...(message.toolCalls != null ? { toolCalls: message.toolCalls } : {}),\n ...(message.toolResults != null ? { toolResults: message.toolResults } : {}),\n ...(message.followUps != null ? { followUps: message.followUps } : {}),\n ...(message.usage != null ? { usage: message.usage } : {}),\n ...(message.agentName != null ? { agentName: message.agentName } : {}),\n };\n }\n}\n","import type {\n ActorSpendRow,\n AgentGovernanceQueries,\n AgentPricingStore,\n GovernanceRange,\n GovernanceUsageInput,\n ModelPrice,\n ModelSpendRow,\n ThreadActivityRow,\n ThreadMeta,\n ThreadSpendRow,\n ToolCallActivityRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n bucketByActor,\n bucketByModel,\n bucketByThread,\n bucketUsageTrend,\n dayBoundsUtc,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, count, desc, eq, gte, inArray, isNull, lte } from 'drizzle-orm';\nimport {\n type AgentDrizzleDb,\n agentMessage,\n agentThread,\n agentTokenUsage,\n agentToolCall,\n} from './schema.js';\n\n/** Map a Drizzle usage row onto the shared bucketer input (day derived from `createdAt`). */\nfunction toUsageInput(row: typeof agentTokenUsage.$inferSelect): GovernanceUsageInput {\n return {\n modelId: row.modelId,\n actorRef: row.actorRef,\n threadId: row.threadId,\n day: row.createdAt.toISOString().slice(0, 10),\n inputTokens: row.inputTokens,\n outputTokens: row.outputTokens,\n cacheWriteTokens: row.cacheWriteTokens,\n cacheReadTokens: row.cacheReadTokens,\n costUsd: row.costUsd,\n };\n}\n\n/**\n * {@link AgentGovernanceQueries} backed by Drizzle ORM — the read/analytics half of the store SPI,\n * mirroring {@link import('@dudousxd/nestjs-agent-store-mikro-orm')} exactly. Cost is the token\n * ledger priced against the current prices from the injected {@link AgentPricingStore}\n * (`AGENT_PRICING_STORE`), so a host that binds its own pricing store controls the cost every\n * governance surface reports. An unpriced model contributes 0 cost. Aggregation is in-process (like\n * `quotaToday`) so day-bucketing stays dialect-portable.\n */\nexport class DrizzleGovernanceQueries implements AgentGovernanceQueries {\n constructor(\n private readonly db: AgentDrizzleDb,\n private readonly pricingStore: AgentPricingStore,\n ) {}\n\n private async loadPricing(): Promise<Map<string, ModelPrice>> {\n const prices = await this.pricingStore.listCurrentPrices();\n const pricing = new Map<string, ModelPrice>();\n for (const price of prices) {\n pricing.set(price.modelId, {\n inputPricePer1m: price.inputPricePer1m,\n outputPricePer1m: price.outputPricePer1m,\n cacheWritePricePer1m: price.cacheWritePricePer1m ?? null,\n cacheReadPricePer1m: price.cacheReadPricePer1m ?? null,\n });\n }\n return pricing;\n }\n\n private async usageInRange(range: GovernanceRange): Promise<GovernanceUsageInput[]> {\n const { start, end } = dayBoundsUtc(range);\n const rows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(and(gte(agentTokenUsage.createdAt, start), lte(agentTokenUsage.createdAt, end)));\n return rows.map(toUsageInput);\n }\n\n async spendByModel(range: GovernanceRange): Promise<ModelSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByModel(await this.usageInRange(range), pricing);\n }\n\n async spendByActor(range: GovernanceRange): Promise<ActorSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByActor(await this.usageInRange(range), pricing);\n }\n\n /**\n * Top threads by spend within the range, highest cost first, capped at `limit`. Usage rows for a\n * soft-deleted thread (`deletedAt` set) are excluded — the thread no longer surfaces as a\n * governance target even though its ledger rows survive.\n */\n async spendByThread(range: GovernanceRange, limit: number): Promise<ThreadSpendRow[]> {\n const pricing = await this.loadPricing();\n const rows = await this.usageInRange(range);\n const threadIds = [...new Set(rows.map((row) => row.threadId))];\n if (threadIds.length === 0) {\n return [];\n }\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(and(inArray(agentThread.id, threadIds), isNull(agentThread.deletedAt)));\n const threadsById = new Map<string, ThreadMeta>(\n threads.map((thread) => [thread.id, { title: thread.title, actorRef: thread.actorRef }]),\n );\n return bucketByThread(rows, pricing, threadsById, { limit, includeUnknownThreads: false });\n }\n\n async usageTrend(range: GovernanceRange): Promise<UsageTrendPoint[]> {\n const pricing = await this.loadPricing();\n return bucketUsageTrend(await this.usageInRange(range), pricing);\n }\n\n async recentToolCalls(limit: number): Promise<ToolCallActivityRow[]> {\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n toolType: agentToolCall.toolType,\n status: agentToolCall.status,\n threadId: agentMessage.threadId,\n createdAt: agentToolCall.createdAt,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .orderBy(desc(agentToolCall.createdAt), desc(agentToolCall.id))\n .limit(limit);\n return rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n toolType: row.toolType,\n status: row.status,\n threadId: row.threadId,\n createdAt: row.createdAt.toISOString(),\n }));\n }\n\n async recentThreads(limit: number): Promise<ThreadActivityRow[]> {\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(isNull(agentThread.deletedAt))\n .orderBy(desc(agentThread.updatedAt), desc(agentThread.id))\n .limit(limit);\n const result: ThreadActivityRow[] = [];\n for (const thread of threads) {\n const [messageCountRow] = await this.db\n .select({ value: count() })\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id));\n const usageRows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(eq(agentTokenUsage.threadId, thread.id));\n const totalTokens = usageRows.reduce(\n (sum, row) => sum + row.inputTokens + row.outputTokens,\n 0,\n );\n result.push({\n threadId: thread.id,\n title: thread.title,\n actorRef: thread.actorRef,\n messageCount: messageCountRow?.value ?? 0,\n totalTokens,\n lastActivityAt: thread.updatedAt.toISOString(),\n });\n }\n return result;\n }\n}\n","import type {\n AgentPricingStore,\n CurrentModelPrice,\n ModelPriceInput,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, eq } from 'drizzle-orm';\nimport { type AgentDrizzleDb, agentModelPricing } from './schema.js';\n\n/**\n * {@link AgentPricingStore} backed by Drizzle ORM — the write side of the pricing table\n * {@link import('./drizzle-governance-queries.js').DrizzleGovernanceQueries} joins against. A POJO\n * receiving a Drizzle SQLite database handle (the host app owns the connection), mirroring\n * {@link import('@dudousxd/nestjs-agent-store-mikro-orm')} exactly (atomic supersede semantics).\n */\nexport class DrizzlePricingStore implements AgentPricingStore {\n constructor(private readonly db: AgentDrizzleDb) {}\n\n async upsertModelPrice(input: ModelPriceInput): Promise<void> {\n await this.db\n .update(agentModelPricing)\n .set({ isCurrent: false })\n .where(\n and(eq(agentModelPricing.modelId, input.modelId), eq(agentModelPricing.isCurrent, true)),\n );\n await this.db.insert(agentModelPricing).values({\n id: crypto.randomUUID(),\n modelId: input.modelId,\n inputPricePer1m: input.inputPricePer1m,\n outputPricePer1m: input.outputPricePer1m,\n cacheWritePricePer1m: input.cacheWritePricePer1m ?? null,\n cacheReadPricePer1m: input.cacheReadPricePer1m ?? null,\n effectiveFrom: new Date(),\n isCurrent: true,\n });\n }\n\n async listCurrentPrices(): Promise<CurrentModelPrice[]> {\n const rows = await this.db\n .select()\n .from(agentModelPricing)\n .where(eq(agentModelPricing.isCurrent, true));\n return rows.map((row) => ({\n modelId: row.modelId,\n inputPricePer1m: row.inputPricePer1m,\n outputPricePer1m: row.outputPricePer1m,\n effectiveFrom: row.effectiveFrom.toISOString(),\n ...(row.cacheWritePricePer1m != null\n ? { cacheWritePricePer1m: row.cacheWritePricePer1m }\n : {}),\n ...(row.cacheReadPricePer1m != null ? { cacheReadPricePer1m: row.cacheReadPricePer1m } : {}),\n }));\n }\n}\n","import {\n AGENT_GOVERNANCE_QUERIES,\n AGENT_PRICING_STORE,\n AGENT_STORE,\n type AgentPricingStore,\n} from '@dudousxd/nestjs-agent-core';\nimport { type DynamicModule, Module, type Type } from '@nestjs/common';\nimport { DrizzleAgentStore } from './drizzle-agent-store.js';\nimport { DrizzleGovernanceQueries } from './drizzle-governance-queries.js';\nimport { DrizzlePricingStore } from './drizzle-pricing-store.js';\nimport type { AgentDrizzleDb } from './schema.js';\n\n/** Options for {@link DrizzleAgentStoreModule.forRoot}. The app owns and supplies the db handle. */\nexport interface DrizzleAgentStoreModuleOptions {\n /** A Drizzle SQLite database instance (`drizzle(client, { schema: agentSchema })`). */\n db: AgentDrizzleDb;\n /**\n * Bind {@link AGENT_PRICING_STORE} (which {@link DrizzleGovernanceQueries} prices usage against) to\n * a host-supplied store instead of the default {@link DrizzlePricingStore} — make your OWN pricing\n * table the single source of cost truth without touching `agent_model_pricing`.\n */\n pricingStore?: Type<AgentPricingStore>;\n}\n\n/**\n * Binds {@link DrizzleAgentStore} to the {@link AGENT_STORE} token consumed by\n * `@dudousxd/nestjs-agent`, plus {@link DrizzleGovernanceQueries} to\n * {@link AGENT_GOVERNANCE_QUERIES} (the read-model the dashboard/telescope surfaces consume) and\n * {@link DrizzlePricingStore} to {@link AGENT_PRICING_STORE} (the write side of that pricing table).\n * The host app supplies an already-opened Drizzle db — this module never opens a connection itself.\n *\n * The returned module is global, so {@link AGENT_STORE}, {@link AGENT_GOVERNANCE_QUERIES} and\n * {@link AGENT_PRICING_STORE} are visible app-wide — `AgentModule` resolves the store without an\n * explicit `store` option, and the dashboard/telescope resolve {@link AGENT_GOVERNANCE_QUERIES}\n * without the host re-binding it.\n *\n * ```ts\n * @Module({ imports: [DrizzleAgentStoreModule.forRoot({ db })] })\n * export class AppModule {}\n * ```\n */\n@Module({})\nexport class DrizzleAgentStoreModule {\n static forRoot(options: DrizzleAgentStoreModuleOptions): DynamicModule {\n return {\n module: DrizzleAgentStoreModule,\n global: true,\n providers: [\n { provide: DrizzleAgentStore, useFactory: () => new DrizzleAgentStore(options.db) },\n { provide: AGENT_STORE, useExisting: DrizzleAgentStore },\n {\n provide: DrizzlePricingStore,\n useFactory: () => new DrizzlePricingStore(options.db),\n },\n // AGENT_PRICING_STORE: the host's own store when supplied, else the default Drizzle one.\n // DrizzleGovernanceQueries prices usage against whatever is bound here.\n options.pricingStore\n ? { provide: AGENT_PRICING_STORE, useClass: options.pricingStore }\n : { provide: AGENT_PRICING_STORE, useExisting: DrizzlePricingStore },\n {\n provide: DrizzleGovernanceQueries,\n useFactory: (pricingStore: AgentPricingStore) =>\n new DrizzleGovernanceQueries(options.db, pricingStore),\n inject: [AGENT_PRICING_STORE],\n },\n { provide: AGENT_GOVERNANCE_QUERIES, useExisting: DrizzleGovernanceQueries },\n ],\n exports: [\n DrizzleAgentStore,\n AGENT_STORE,\n DrizzleGovernanceQueries,\n AGENT_GOVERNANCE_QUERIES,\n DrizzlePricingStore,\n AGENT_PRICING_STORE,\n ],\n };\n }\n}\n"],"mappings":";;;;AASA,SAEEA,OACAC,SACAC,MACAC,aACAC,YACK;AAeA,IAAMC,cAAcF,YACzB,gBACA;EACEG,IAAIF,KAAK,IAAA,EAAMG,WAAU;EACzBC,UAAUJ,KAAK,WAAA,EAAaK,QAAO;EACnCC,WAAWN,KAAK,YAAA;EAChBO,OAAOP,KAAK,OAAA,EAASK,QAAO;EAC5BG,WAAWX,QAAQ,aAAa;IAAEY,MAAM;EAAU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,iBACX,IAAIG,yBAAyBd,QAAQO,IAAII,YAAAA,GAD/B;UAEZI,QAAQ;YAACH;;QACX;QACA;UAAER,SAASY;UAA0BP,aAAaK;QAAyB;;MAE7EG,SAAS;QACPZ;QACAG;QACAM;QACAE;QACAN;QACAE;;IAEJ;EACF;AACF;;;;","names":["index","integer","real","sqliteTable","text","agentThread","id","primaryKey","actorRef","notNull","tenantRef","title","transient","mode","default","activeStreamId","createdAt","updatedAt","deletedAt","table","on","agentMessage","threadId","references","onDelete","role","$type","content","toolCalls","toolResults","followUps","usage","agentName","agentToolCall","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentSchema","sql","statements","ensureAgentSchema","db","statement","run","sql","raw","and","asc","desc","eq","gte","inArray","isNull","lte","DrizzleAgentStore","db","createThread","input","now","Date","thread","id","crypto","randomUUID","actorRef","actor","tenantRef","title","transient","activeStreamId","createdAt","updatedAt","deletedAt","insert","agentThread","values","toSummary","getThread","threadId","select","from","where","and","eq","isNull","undefined","messages","agentMessage","orderBy","asc","last","length","content","map","message","toStoredMessage","listThreads","limit","threads","desc","summaries","push","softDeleteThread","update","set","forkThread","fromMessageId","source","Error","cutoff","findIndex","kept","slice","fork","role","toolCalls","toolResults","followUps","usage","agentName","ownerOfThread","ownerOfToolCall","toolCallId","row","agentToolCall","innerJoin","messageId","runForToolCall","ownerOfActiveStream","runId","setTitle","promoteThread","setActiveStream","appendMessage","truncateFrom","doomedIds","delete","inArray","recordToolCall","toolName","toolType","output","status","executedByRef","executionMs","error","executedAt","updateToolCall","updates","recordUsage","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","quotaToday","day","start","end","rows","gte","lte","usedTokens","reduce","sum","lastContent","toISOString","lastMessagePreview","bucketByActor","bucketByModel","bucketByThread","bucketUsageTrend","dayBoundsUtc","and","count","desc","eq","gte","inArray","isNull","lte","toUsageInput","row","modelId","actorRef","threadId","day","createdAt","toISOString","slice","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","DrizzleGovernanceQueries","db","pricingStore","loadPricing","prices","listCurrentPrices","pricing","Map","price","set","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","usageInRange","range","start","end","dayBoundsUtc","rows","select","from","agentTokenUsage","where","and","gte","lte","map","spendByModel","bucketByModel","spendByActor","bucketByActor","spendByThread","limit","threadIds","Set","length","threads","agentThread","inArray","id","isNull","deletedAt","threadsById","thread","title","bucketByThread","includeUnknownThreads","usageTrend","bucketUsageTrend","recentToolCalls","toolCallId","agentToolCall","toolName","toolType","status","agentMessage","innerJoin","eq","messageId","orderBy","desc","recentThreads","updatedAt","result","messageCountRow","value","count","usageRows","totalTokens","reduce","sum","push","messageCount","lastActivityAt","and","eq","DrizzlePricingStore","db","upsertModelPrice","input","update","agentModelPricing","set","isCurrent","where","and","eq","modelId","insert","values","id","crypto","randomUUID","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","Date","listCurrentPrices","rows","select","from","map","row","toISOString","AGENT_GOVERNANCE_QUERIES","AGENT_PRICING_STORE","AGENT_STORE","Module","DrizzleAgentStoreModule","forRoot","options","module","global","providers","provide","DrizzleAgentStore","useFactory","db","AGENT_STORE","useExisting","DrizzlePricingStore","pricingStore","AGENT_PRICING_STORE","useClass","DrizzleGovernanceQueries","inject","AGENT_GOVERNANCE_QUERIES","exports"]}
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts","../src/ensure-schema.ts","../src/drizzle-agent-store.ts","../src/drizzle-governance-queries.ts","../src/drizzle-pricing-store.ts","../src/drizzle-agent-store.module.ts"],"sourcesContent":["import type {\n MessageRole,\n MessageUsage,\n ToolCallRequest,\n ToolCallStatus,\n ToolKind,\n ToolResult,\n UsagePurpose,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n type BaseSQLiteDatabase,\n index,\n integer,\n real,\n sqliteTable,\n text,\n} from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle schema mirroring the MikroORM agent entities (same logical columns/relations):\n * threads, messages, tool calls, token usage, model pricing and run outcomes. Targets the SQLite core so the\n * db-test runs on an in-memory better-sqlite3; timestamps are stored as integer epoch-ms columns\n * (`{ mode: 'timestamp_ms' }`) which Drizzle round-trips to/from JS `Date`, and the model-facing\n * message extras (tool calls/results, follow-ups, usage) live in JSON `text` columns.\n */\n\n/**\n * A conversation thread. `deletedAt` drives soft delete: a deleted thread is hidden from\n * {@link import('./drizzle-agent-store.js').DrizzleAgentStore.getThread}/`listThreads` but its\n * row survives.\n */\nexport const agentThread = sqliteTable(\n 'agent_thread',\n {\n id: text('id').primaryKey(),\n actorRef: text('actor_ref').notNull(),\n tenantRef: text('tenant_ref'),\n title: text('title').notNull(),\n transient: integer('transient', { mode: 'boolean' }).notNull().default(false),\n activeStreamId: text('active_stream_id'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n deletedAt: integer('deleted_at', { mode: 'timestamp_ms' }),\n },\n (table) => [index('agent_thread_actor_updated_idx').on(table.actorRef, table.updatedAt)],\n);\n\n/**\n * One stored message in a thread. The model-facing extras (`toolCalls`/`toolResults`/\n * `followUps`/`usage`) are folded into nullable JSON columns so a single row round-trips to a\n * {@link import('@dudousxd/nestjs-agent-core').StoredMessage}. `threadId` cascades on delete.\n */\nexport const agentMessage = sqliteTable(\n 'agent_message',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n role: text('role').$type<MessageRole>().notNull(),\n content: text('content').notNull(),\n toolCalls: text('tool_calls', { mode: 'json' }).$type<ToolCallRequest[]>(),\n toolResults: text('tool_results', { mode: 'json' }).$type<ToolResult[]>(),\n followUps: text('follow_ups', { mode: 'json' }).$type<string[]>(),\n usage: text('usage', { mode: 'json' }).$type<MessageUsage>(),\n agentName: text('agent_name'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_message_thread_created_idx').on(table.threadId, table.createdAt)],\n);\n\n/** A tool call requested during an assistant turn. The pk is the model-supplied `toolCallId`. */\nexport const agentToolCall = sqliteTable('agent_tool_call', {\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});\n\n/** A token-usage ledger row, summed per actor per day by `quotaToday`. */\nexport const agentTokenUsage = sqliteTable(\n 'agent_token_usage',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: text('actor_ref').notNull(),\n messageId: text('message_id'),\n modelId: text('model_id').notNull(),\n purpose: text('purpose').$type<UsagePurpose>().notNull(),\n inputTokens: integer('input_tokens').notNull(),\n outputTokens: integer('output_tokens').notNull(),\n /** Subset of `inputTokens` written to the prompt cache this turn; null when not reported. */\n cacheWriteTokens: integer('cache_write_tokens'),\n /** Subset of `inputTokens` served from the prompt cache this turn; null when not reported. */\n cacheReadTokens: integer('cache_read_tokens'),\n /** Provider-reported actual USD cost for the turn; null when only tokens were reported. */\n costUsd: real('cost_usd'),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => [index('agent_token_usage_actor_created_idx').on(table.actorRef, table.createdAt)],\n);\n\n/** Per-model token pricing, versioned by `effectiveFrom`; `isCurrent` flags the live row. */\nexport const agentModelPricing = sqliteTable('agent_model_pricing', {\n id: text('id').primaryKey(),\n modelId: text('model_id').notNull(),\n inputPricePer1m: real('input_price_per_1m').notNull(),\n outputPricePer1m: real('output_price_per_1m').notNull(),\n /** Per-1M price for cache-write input tokens; null → price them at the input rate. */\n cacheWritePricePer1m: real('cache_write_price_per_1m'),\n /** Per-1M price for cache-read input tokens; null → price them at the input rate. */\n cacheReadPricePer1m: real('cache_read_price_per_1m'),\n effectiveFrom: integer('effective_from', { mode: 'timestamp_ms' }).notNull(),\n isCurrent: integer('is_current', { mode: 'boolean' }).notNull(),\n});\n\n/** A run's lifecycle status. Not part of the core SPI (that surfaces `string`) — internal only. */\nexport type AgentRunStatus = 'running' | 'completed' | 'failed';\n\n/**\n * One recorded run (turn) outcome — the durable half of what `aviary:agent:*` diagnostics report\n * ephemerally. Written by {@link import('./drizzle-agent-store.js').DrizzleAgentStore.recordRunStart}/\n * `recordRunEnd`/`bumpRunRetries`, read by\n * {@link import('./drizzle-governance-queries.js').DrizzleGovernanceQueries} for the reliability\n * surfaces (success rate, error breakdown, duration percentiles, trend, recent runs). `threadId`\n * cascades on delete, like `agent_message`/`agent_token_usage`.\n */\nexport const agentRun = sqliteTable(\n 'agent_run',\n {\n id: text('id').primaryKey(),\n threadId: text('thread_id')\n .notNull()\n .references(() => agentThread.id, { onDelete: 'cascade' }),\n actorRef: text('actor_ref').notNull(),\n agentName: text('agent_name'),\n status: text('status').$type<AgentRunStatus>().notNull(),\n durationMs: integer('duration_ms'),\n errorCode: text('error_code'),\n errorMessage: text('error_message'),\n retries: integer('retries').notNull().default(0),\n startedAt: integer('started_at', { mode: 'timestamp_ms' }).notNull(),\n settledAt: integer('settled_at', { mode: 'timestamp_ms' }),\n },\n (table) => [index('agent_run_started_idx').on(table.startedAt)],\n);\n\n/** The six agent tables as one schema object, ready for `drizzle(client, { schema })`. */\nexport const agentSchema = {\n agentThread,\n agentMessage,\n agentToolCall,\n agentTokenUsage,\n agentModelPricing,\n agentRun,\n};\n\n/**\n * The dialect-portable Drizzle SQLite database handle the store operates on. Accepts any SQLite\n * driver (better-sqlite3, libsql, D1, …) in either sync or async result mode; the host app owns\n * the connection and passes the `drizzle(...)` instance in.\n */\nexport type AgentDrizzleDb = BaseSQLiteDatabase<'sync' | 'async', unknown>;\n\n/** A persisted thread row as Drizzle selects it. */\nexport type AgentThreadRow = typeof agentThread.$inferSelect;\n/** A persisted message row as Drizzle selects it. */\nexport type AgentMessageRow = typeof agentMessage.$inferSelect;\n/** A persisted run row as Drizzle selects it. */\nexport type AgentRunRow = typeof agentRun.$inferSelect;\n","import { sql } from 'drizzle-orm';\nimport type { AgentDrizzleDb } from './schema.js';\n\n/**\n * Idempotent `CREATE TABLE IF NOT EXISTS` DDL for the six agent tables, mirroring\n * {@link import('./schema.js').agentSchema}. SQLite dialect (the db-test driver); kept here rather\n * than relying on drizzle-kit so the package can stand up its schema with no migration files. Safe\n * to run on boot against a shared database — it never drops or alters existing columns.\n */\nconst statements: string[] = [\n `CREATE TABLE IF NOT EXISTS agent_thread (\n id TEXT PRIMARY KEY NOT NULL,\n actor_ref TEXT NOT NULL,\n tenant_ref TEXT,\n title TEXT NOT NULL,\n transient INTEGER NOT NULL DEFAULT 0,\n active_stream_id TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n deleted_at INTEGER\n )`,\n `CREATE INDEX IF NOT EXISTS agent_thread_actor_updated_idx\n ON agent_thread (actor_ref, updated_at)`,\n `CREATE TABLE IF NOT EXISTS agent_message (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n role TEXT NOT NULL,\n content TEXT NOT NULL,\n tool_calls TEXT,\n tool_results TEXT,\n follow_ups TEXT,\n usage TEXT,\n agent_name TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS agent_message_thread_created_idx\n ON agent_message (thread_id, created_at)`,\n `CREATE TABLE IF NOT EXISTS agent_tool_call (\n id TEXT PRIMARY KEY NOT NULL,\n message_id TEXT NOT NULL REFERENCES agent_message(id) ON DELETE CASCADE,\n tool_name TEXT NOT NULL,\n tool_type TEXT NOT NULL,\n input TEXT,\n output TEXT,\n status TEXT NOT NULL,\n executed_by_ref TEXT,\n execution_ms INTEGER,\n error TEXT,\n created_at INTEGER NOT NULL,\n executed_at INTEGER\n )`,\n `CREATE TABLE IF NOT EXISTS agent_token_usage (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n actor_ref TEXT NOT NULL,\n message_id TEXT,\n model_id TEXT NOT NULL,\n purpose TEXT NOT NULL,\n input_tokens INTEGER NOT NULL,\n output_tokens INTEGER NOT NULL,\n cache_write_tokens INTEGER,\n cache_read_tokens INTEGER,\n cost_usd REAL,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS agent_token_usage_actor_created_idx\n ON agent_token_usage (actor_ref, created_at)`,\n `CREATE TABLE IF NOT EXISTS agent_model_pricing (\n id TEXT PRIMARY KEY NOT NULL,\n model_id TEXT NOT NULL,\n input_price_per_1m REAL NOT NULL,\n output_price_per_1m REAL NOT NULL,\n cache_write_price_per_1m REAL,\n cache_read_price_per_1m REAL,\n effective_from INTEGER NOT NULL,\n is_current INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS agent_run (\n id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,\n actor_ref TEXT NOT NULL,\n agent_name TEXT,\n status TEXT NOT NULL,\n duration_ms INTEGER,\n error_code TEXT,\n error_message TEXT,\n retries INTEGER NOT NULL DEFAULT 0,\n started_at INTEGER NOT NULL,\n settled_at INTEGER\n )`,\n `CREATE INDEX IF NOT EXISTS agent_run_started_idx\n ON agent_run (started_at)`,\n];\n\n/** Runs the `CREATE TABLE IF NOT EXISTS` DDL above against the supplied Drizzle SQLite db. */\nexport async function ensureAgentSchema(db: AgentDrizzleDb): Promise<void> {\n for (const statement of statements) {\n await db.run(sql.raw(statement));\n }\n}\n","import type {\n AgentStore,\n AppendMessageInput,\n CreateThreadInput,\n RecordToolCallInput,\n RecordUsageInput,\n StoredMessage,\n ThreadDetail,\n ThreadSummary,\n UpdateToolCallInput,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, asc, desc, eq, gte, inArray, isNull, lte, sql } from 'drizzle-orm';\nimport {\n type AgentDrizzleDb,\n type AgentMessageRow,\n type AgentRunRow,\n type AgentThreadRow,\n agentMessage,\n agentRun,\n agentThread,\n agentTokenUsage,\n agentToolCall,\n} from './schema.js';\n\n/**\n * {@link AgentStore} backed by Drizzle ORM — a second adapter alongside the MikroORM one, proving\n * the store SPI is ORM-portable. A POJO receiving a Drizzle SQLite database handle (the host app\n * owns the connection). Behaviour mirrors {@link import('@dudousxd/nestjs-agent-store-mikro-orm')}\n * exactly (fork/truncate/quota/active-stream/soft-delete semantics) so the two are interchangeable.\n */\nexport class DrizzleAgentStore implements AgentStore {\n constructor(private readonly db: AgentDrizzleDb) {}\n\n async createThread(input: CreateThreadInput): Promise<ThreadSummary> {\n const now = new Date();\n const thread: AgentThreadRow = {\n id: crypto.randomUUID(),\n actorRef: input.actor.id,\n tenantRef: input.actor.tenantRef ?? null,\n title: input.title ?? 'New chat',\n transient: input.transient ?? false,\n activeStreamId: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(agentThread).values(thread);\n return this.toSummary(thread);\n }\n\n async getThread(threadId: string): Promise<ThreadDetail | null> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n if (thread === undefined) {\n return null;\n }\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const last = messages[messages.length - 1];\n return {\n ...this.toSummary(thread, last?.content),\n messages: messages.map((message) => this.toStoredMessage(message)),\n ...(thread.activeStreamId != null ? { activeStreamId: thread.activeStreamId } : {}),\n };\n }\n\n async listThreads(actorRef: string, limit = 50): Promise<ThreadSummary[]> {\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(\n and(\n eq(agentThread.actorRef, actorRef),\n eq(agentThread.transient, false),\n isNull(agentThread.deletedAt),\n ),\n )\n .orderBy(desc(agentThread.updatedAt))\n .limit(limit);\n const summaries: ThreadSummary[] = [];\n for (const thread of threads) {\n const [last] = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id))\n .orderBy(desc(agentMessage.createdAt), desc(agentMessage.id))\n .limit(1);\n summaries.push(this.toSummary(thread, last?.content));\n }\n return summaries;\n }\n\n async softDeleteThread(threadId: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ deletedAt: new Date() })\n .where(eq(agentThread.id, threadId));\n }\n\n async forkThread(threadId: string, fromMessageId: string): Promise<ThreadSummary> {\n const [source] = await this.db.select().from(agentThread).where(eq(agentThread.id, threadId));\n if (source === undefined) {\n throw new Error(`thread ${threadId} not found`);\n }\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const cutoff = messages.findIndex((message) => message.id === fromMessageId);\n const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;\n const now = new Date();\n const fork: AgentThreadRow = {\n id: crypto.randomUUID(),\n actorRef: source.actorRef,\n tenantRef: source.tenantRef,\n title: source.title,\n transient: false,\n activeStreamId: null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n };\n await this.db.insert(agentThread).values(fork);\n if (kept.length > 0) {\n await this.db.insert(agentMessage).values(\n kept.map((message) => ({\n id: crypto.randomUUID(),\n threadId: fork.id,\n role: message.role,\n content: message.content,\n toolCalls: message.toolCalls,\n toolResults: message.toolResults,\n followUps: message.followUps,\n usage: message.usage,\n agentName: message.agentName,\n createdAt: message.createdAt,\n })),\n );\n }\n return this.toSummary(fork);\n }\n\n async ownerOfThread(threadId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentThread)\n .where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));\n return thread?.actorRef ?? null;\n }\n\n async ownerOfToolCall(toolCallId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.id, toolCallId));\n return row?.actorRef ?? null;\n }\n\n async runForToolCall(toolCallId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ activeStreamId: agentThread.activeStreamId })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id))\n .where(eq(agentToolCall.id, toolCallId));\n return row?.activeStreamId ?? null;\n }\n\n async ownerOfActiveStream(runId: string): Promise<string | null> {\n const [thread] = await this.db\n .select({ actorRef: agentThread.actorRef })\n .from(agentThread)\n .where(and(eq(agentThread.activeStreamId, runId), isNull(agentThread.deletedAt)));\n return thread?.actorRef ?? null;\n }\n\n async setTitle(threadId: string, title: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ title, updatedAt: new Date() })\n .where(eq(agentThread.id, threadId));\n }\n\n async promoteThread(threadId: string): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ transient: false, updatedAt: new Date() })\n .where(and(eq(agentThread.id, threadId), eq(agentThread.transient, true)));\n }\n\n async setActiveStream(threadId: string, runId: string | null): Promise<void> {\n await this.db\n .update(agentThread)\n .set({ activeStreamId: runId })\n .where(eq(agentThread.id, threadId));\n }\n\n /** Persist the start of a run (turn). Replay-safe: called under a durable localStep. */\n async recordRunStart(run: {\n runId: string;\n threadId: string;\n actorRef: string;\n agentName?: string;\n }): Promise<void> {\n const runRow: AgentRunRow = {\n id: run.runId,\n threadId: run.threadId,\n actorRef: run.actorRef,\n agentName: run.agentName ?? null,\n status: 'running',\n durationMs: null,\n errorCode: null,\n errorMessage: null,\n retries: 0,\n startedAt: new Date(),\n settledAt: null,\n };\n await this.db.insert(agentRun).values(runRow);\n }\n\n /** Settle a run's outcome. A no-op when the run is unknown (mirrors `setTitle`/`updateThread`). */\n async recordRunEnd(end: {\n runId: string;\n status: 'completed' | 'failed';\n durationMs?: number;\n errorCode?: string;\n errorMessage?: string;\n }): Promise<void> {\n const updates: Partial<typeof agentRun.$inferInsert> = {\n status: end.status,\n settledAt: new Date(),\n };\n if (end.durationMs !== undefined) {\n updates.durationMs = end.durationMs;\n }\n if (end.errorCode !== undefined) {\n updates.errorCode = end.errorCode;\n }\n if (end.errorMessage !== undefined) {\n updates.errorMessage = end.errorMessage;\n }\n await this.db.update(agentRun).set(updates).where(eq(agentRun.id, end.runId));\n }\n\n /** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */\n async bumpRunRetries(runId: string): Promise<void> {\n await this.db\n .update(agentRun)\n .set({ retries: sql`${agentRun.retries} + 1` })\n .where(eq(agentRun.id, runId));\n }\n\n async appendMessage(input: AppendMessageInput): Promise<StoredMessage> {\n const [thread] = await this.db\n .select()\n .from(agentThread)\n .where(eq(agentThread.id, input.threadId));\n if (thread === undefined) {\n throw new Error(`thread ${input.threadId} not found`);\n }\n const now = new Date();\n const message: AgentMessageRow = {\n id: crypto.randomUUID(),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n toolCalls: input.toolCalls ?? null,\n toolResults: input.toolResults ?? null,\n followUps: input.followUps ?? null,\n usage: input.usage ?? null,\n agentName: input.agentName ?? null,\n createdAt: now,\n };\n await this.db.insert(agentMessage).values(message);\n await this.db\n .update(agentThread)\n .set({ updatedAt: now })\n .where(eq(agentThread.id, input.threadId));\n return this.toStoredMessage(message);\n }\n\n async truncateFrom(threadId: string, messageId: string): Promise<void> {\n const messages = await this.db\n .select()\n .from(agentMessage)\n .where(eq(agentMessage.threadId, threadId))\n .orderBy(asc(agentMessage.createdAt), asc(agentMessage.id));\n const cutoff = messages.findIndex((message) => message.id === messageId);\n if (cutoff < 0) {\n return;\n }\n const doomedIds = messages.slice(cutoff).map((message) => message.id);\n await this.db.delete(agentToolCall).where(inArray(agentToolCall.messageId, doomedIds));\n await this.db.delete(agentMessage).where(inArray(agentMessage.id, doomedIds));\n }\n\n async recordToolCall(input: RecordToolCallInput): Promise<void> {\n await this.db.insert(agentToolCall).values({\n id: input.toolCallId,\n messageId: input.messageId,\n toolName: input.toolName,\n toolType: input.toolType,\n input: input.input,\n output: null,\n status: input.status,\n executedByRef: null,\n executionMs: null,\n error: null,\n createdAt: new Date(),\n executedAt: null,\n });\n }\n\n async updateToolCall(input: UpdateToolCallInput): Promise<void> {\n const updates: Partial<typeof agentToolCall.$inferInsert> = { status: input.status };\n if (input.output !== undefined) {\n updates.output = input.output;\n }\n if (input.error !== undefined) {\n updates.error = input.error;\n }\n if (input.executionMs !== undefined) {\n updates.executionMs = input.executionMs;\n }\n if (input.executedByRef !== undefined) {\n updates.executedByRef = input.executedByRef;\n }\n if (input.status === 'executed' || input.status === 'auto_executed') {\n updates.executedAt = new Date();\n }\n await this.db.update(agentToolCall).set(updates).where(eq(agentToolCall.id, input.toolCallId));\n }\n\n async recordUsage(input: RecordUsageInput): Promise<void> {\n await this.db.insert(agentTokenUsage).values({\n id: crypto.randomUUID(),\n threadId: input.threadId,\n actorRef: input.actorRef,\n messageId: input.messageId ?? null,\n modelId: input.modelId,\n purpose: input.purpose,\n inputTokens: input.usage.inputTokens,\n outputTokens: input.usage.outputTokens,\n cacheWriteTokens: input.usage.cacheWriteTokens ?? null,\n cacheReadTokens: input.usage.cacheReadTokens ?? null,\n costUsd: input.costUsd ?? null,\n createdAt: new Date(),\n });\n }\n\n async quotaToday(\n actorRef: string,\n day: string,\n ): Promise<{ usedTokens: number; costUsd: number }> {\n const start = new Date(`${day}T00:00:00.000Z`);\n const end = new Date(`${day}T23:59:59.999Z`);\n const rows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(\n and(\n eq(agentTokenUsage.actorRef, actorRef),\n gte(agentTokenUsage.createdAt, start),\n lte(agentTokenUsage.createdAt, end),\n ),\n );\n const usedTokens = rows.reduce((sum, row) => sum + row.inputTokens + row.outputTokens, 0);\n const costUsd = rows.reduce((sum, row) => sum + (row.costUsd ?? 0), 0);\n return { usedTokens, costUsd };\n }\n\n private toSummary(thread: AgentThreadRow, lastContent?: string): ThreadSummary {\n return {\n id: thread.id,\n title: thread.title,\n transient: thread.transient,\n createdAt: thread.createdAt.toISOString(),\n updatedAt: thread.updatedAt.toISOString(),\n ...(lastContent !== undefined ? { lastMessagePreview: lastContent.slice(0, 120) } : {}),\n };\n }\n\n private toStoredMessage(message: AgentMessageRow): StoredMessage {\n return {\n id: message.id,\n role: message.role,\n content: message.content,\n createdAt: message.createdAt.toISOString(),\n ...(message.toolCalls != null ? { toolCalls: message.toolCalls } : {}),\n ...(message.toolResults != null ? { toolResults: message.toolResults } : {}),\n ...(message.followUps != null ? { followUps: message.followUps } : {}),\n ...(message.usage != null ? { usage: message.usage } : {}),\n ...(message.agentName != null ? { agentName: message.agentName } : {}),\n };\n }\n}\n","import type {\n ActorSpendRow,\n AgentGovernanceQueries,\n AgentPricingStore,\n GovernanceRange,\n GovernanceUsageInput,\n ModelPrice,\n ModelSpendRow,\n RecentRunRow,\n RunAgentBreakdownRow,\n RunErrorBreakdownRow,\n RunMetrics,\n RunTrendPoint,\n ThreadActivityRow,\n ThreadMeta,\n ThreadSpendRow,\n ToolCallActivityRow,\n UsageTrendPoint,\n} from '@dudousxd/nestjs-agent-core';\nimport {\n bucketByActor,\n bucketByModel,\n bucketByThread,\n bucketUsageTrend,\n dayBoundsUtc,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, count, desc, eq, gte, inArray, isNull, lte } from 'drizzle-orm';\nimport {\n type AgentDrizzleDb,\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/** Map a Drizzle usage row onto the shared bucketer input (day derived from `createdAt`). */\nfunction toUsageInput(row: typeof agentTokenUsage.$inferSelect): GovernanceUsageInput {\n return {\n modelId: row.modelId,\n actorRef: row.actorRef,\n threadId: row.threadId,\n day: row.createdAt.toISOString().slice(0, 10),\n inputTokens: row.inputTokens,\n outputTokens: row.outputTokens,\n cacheWriteTokens: row.cacheWriteTokens,\n cacheReadTokens: row.cacheReadTokens,\n costUsd: row.costUsd,\n };\n}\n\n/**\n * MySQL-compatible percentile (no `PERCENTILE_CONT`): index into an ascending-sorted array by\n * offset. `null` when there are no settled durations in range. Shared by every reliability query\n * that reports p50/p95 so the SQL and in-memory adapters compute identically.\n */\nfunction percentileMs(sortedDurationsMs: number[], p: number): number | null {\n if (sortedDurationsMs.length === 0) {\n return null;\n }\n const offset = Math.min(sortedDurationsMs.length - 1, Math.floor(p * sortedDurationsMs.length));\n return sortedDurationsMs[offset] ?? null;\n}\n\n/**\n * {@link AgentGovernanceQueries} backed by Drizzle ORM — the read/analytics half of the store SPI,\n * mirroring {@link import('@dudousxd/nestjs-agent-store-mikro-orm')} exactly. Cost is the token\n * ledger priced against the current prices from the injected {@link AgentPricingStore}\n * (`AGENT_PRICING_STORE`), so a host that binds its own pricing store controls the cost every\n * governance surface reports. An unpriced model contributes 0 cost. Aggregation is in-process (like\n * `quotaToday`) so day-bucketing stays dialect-portable.\n */\nexport class DrizzleGovernanceQueries implements AgentGovernanceQueries {\n constructor(\n private readonly db: AgentDrizzleDb,\n private readonly pricingStore: AgentPricingStore,\n ) {}\n\n private async loadPricing(): Promise<Map<string, ModelPrice>> {\n const prices = await this.pricingStore.listCurrentPrices();\n const pricing = new Map<string, ModelPrice>();\n for (const price of prices) {\n pricing.set(price.modelId, {\n inputPricePer1m: price.inputPricePer1m,\n outputPricePer1m: price.outputPricePer1m,\n cacheWritePricePer1m: price.cacheWritePricePer1m ?? null,\n cacheReadPricePer1m: price.cacheReadPricePer1m ?? null,\n });\n }\n return pricing;\n }\n\n private async usageInRange(range: GovernanceRange): Promise<GovernanceUsageInput[]> {\n const { start, end } = dayBoundsUtc(range);\n const rows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(and(gte(agentTokenUsage.createdAt, start), lte(agentTokenUsage.createdAt, end)));\n return rows.map(toUsageInput);\n }\n\n async spendByModel(range: GovernanceRange): Promise<ModelSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByModel(await this.usageInRange(range), pricing);\n }\n\n async spendByActor(range: GovernanceRange): Promise<ActorSpendRow[]> {\n const pricing = await this.loadPricing();\n return bucketByActor(await this.usageInRange(range), pricing);\n }\n\n /**\n * Top threads by spend within the range, highest cost first, capped at `limit`. Usage rows for a\n * soft-deleted thread (`deletedAt` set) are excluded — the thread no longer surfaces as a\n * governance target even though its ledger rows survive.\n */\n async spendByThread(range: GovernanceRange, limit: number): Promise<ThreadSpendRow[]> {\n const pricing = await this.loadPricing();\n const rows = await this.usageInRange(range);\n const threadIds = [...new Set(rows.map((row) => row.threadId))];\n if (threadIds.length === 0) {\n return [];\n }\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(and(inArray(agentThread.id, threadIds), isNull(agentThread.deletedAt)));\n const threadsById = new Map<string, ThreadMeta>(\n threads.map((thread) => [thread.id, { title: thread.title, actorRef: thread.actorRef }]),\n );\n return bucketByThread(rows, pricing, threadsById, { limit, includeUnknownThreads: false });\n }\n\n async usageTrend(range: GovernanceRange): Promise<UsageTrendPoint[]> {\n const pricing = await this.loadPricing();\n return bucketUsageTrend(await this.usageInRange(range), pricing);\n }\n\n async recentToolCalls(limit: number): Promise<ToolCallActivityRow[]> {\n const rows = await this.db\n .select({\n toolCallId: agentToolCall.id,\n toolName: agentToolCall.toolName,\n toolType: agentToolCall.toolType,\n status: agentToolCall.status,\n threadId: agentMessage.threadId,\n createdAt: agentToolCall.createdAt,\n })\n .from(agentToolCall)\n .innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id))\n .orderBy(desc(agentToolCall.createdAt), desc(agentToolCall.id))\n .limit(limit);\n return rows.map((row) => ({\n toolCallId: row.toolCallId,\n toolName: row.toolName,\n toolType: row.toolType,\n status: row.status,\n threadId: row.threadId,\n createdAt: row.createdAt.toISOString(),\n }));\n }\n\n async recentThreads(limit: number): Promise<ThreadActivityRow[]> {\n const threads = await this.db\n .select()\n .from(agentThread)\n .where(isNull(agentThread.deletedAt))\n .orderBy(desc(agentThread.updatedAt), desc(agentThread.id))\n .limit(limit);\n const result: ThreadActivityRow[] = [];\n for (const thread of threads) {\n const [messageCountRow] = await this.db\n .select({ value: count() })\n .from(agentMessage)\n .where(eq(agentMessage.threadId, thread.id));\n const usageRows = await this.db\n .select()\n .from(agentTokenUsage)\n .where(eq(agentTokenUsage.threadId, thread.id));\n const totalTokens = usageRows.reduce(\n (sum, row) => sum + row.inputTokens + row.outputTokens,\n 0,\n );\n result.push({\n threadId: thread.id,\n title: thread.title,\n actorRef: thread.actorRef,\n messageCount: messageCountRow?.value ?? 0,\n totalTokens,\n lastActivityAt: thread.updatedAt.toISOString(),\n });\n }\n return result;\n }\n\n private async runsInRange(range: GovernanceRange): Promise<(typeof agentRun.$inferSelect)[]> {\n const { start, end } = dayBoundsUtc(range);\n return this.db\n .select()\n .from(agentRun)\n .where(and(gte(agentRun.startedAt, start), lte(agentRun.startedAt, end)));\n }\n\n async runMetrics(range: GovernanceRange): Promise<RunMetrics> {\n const runs = await this.runsInRange(range);\n let completed = 0;\n let failed = 0;\n let retries = 0;\n const settledDurationsMs: number[] = [];\n for (const run of runs) {\n if (run.status === 'completed') {\n completed += 1;\n } else if (run.status === 'failed') {\n failed += 1;\n }\n retries += run.retries;\n if ((run.status === 'completed' || run.status === 'failed') && run.durationMs != null) {\n settledDurationsMs.push(run.durationMs);\n }\n }\n settledDurationsMs.sort((left, right) => left - right);\n return {\n runs: runs.length,\n completed,\n failed,\n successRate: runs.length === 0 ? 0 : completed / runs.length,\n retries,\n durationP50Ms: percentileMs(settledDurationsMs, 0.5),\n durationP95Ms: percentileMs(settledDurationsMs, 0.95),\n };\n }\n\n async runsByAgent(range: GovernanceRange): Promise<RunAgentBreakdownRow[]> {\n const runs = await this.runsInRange(range);\n const byAgent = new Map<string, { runs: number; failed: number; retries: number }>();\n for (const run of runs) {\n const agentName = run.agentName ?? DEFAULT_AGENT_BUCKET;\n const bucket = byAgent.get(agentName) ?? { runs: 0, failed: 0, retries: 0 };\n bucket.runs += 1;\n bucket.failed += run.status === 'failed' ? 1 : 0;\n bucket.retries += run.retries;\n byAgent.set(agentName, bucket);\n }\n const result: RunAgentBreakdownRow[] = [];\n for (const [agentName, bucket] of byAgent) {\n result.push({ agentName, ...bucket });\n }\n result.sort(\n (left, right) => right.runs - left.runs || left.agentName.localeCompare(right.agentName),\n );\n return result;\n }\n\n async runErrors(range: GovernanceRange): Promise<RunErrorBreakdownRow[]> {\n const { start, end } = dayBoundsUtc(range);\n const runs = await this.db\n .select()\n .from(agentRun)\n .where(\n and(\n gte(agentRun.startedAt, start),\n lte(agentRun.startedAt, end),\n eq(agentRun.status, 'failed'),\n ),\n );\n const byError = new Map<string, number>();\n for (const run of runs) {\n const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;\n byError.set(errorCode, (byError.get(errorCode) ?? 0) + 1);\n }\n const result: RunErrorBreakdownRow[] = [];\n for (const [errorCode, errorCount] of byError) {\n result.push({ errorCode, count: errorCount });\n }\n result.sort(\n (left, right) => right.count - left.count || left.errorCode.localeCompare(right.errorCode),\n );\n return result;\n }\n\n async runTrend(range: GovernanceRange): Promise<RunTrendPoint[]> {\n const runs = await this.runsInRange(range);\n const byDay = new Map<string, { runs: number; failed: number }>();\n for (const run of runs) {\n const day = run.startedAt.toISOString().slice(0, 10);\n const bucket = byDay.get(day) ?? { runs: 0, failed: 0 };\n bucket.runs += 1;\n bucket.failed += run.status === 'failed' ? 1 : 0;\n byDay.set(day, bucket);\n }\n const result: RunTrendPoint[] = [];\n for (const [day, bucket] of byDay) {\n result.push({ day, ...bucket });\n }\n result.sort((left, right) => left.day.localeCompare(right.day));\n return result;\n }\n\n async recentRuns(limit: number): Promise<RecentRunRow[]> {\n const runs = await this.db\n .select()\n .from(agentRun)\n .orderBy(desc(agentRun.startedAt), desc(agentRun.id))\n .limit(limit);\n return runs.map((run) => ({\n runId: run.id,\n threadId: run.threadId,\n actorRef: run.actorRef,\n agentName: run.agentName ?? null,\n status: run.status,\n durationMs: run.durationMs ?? null,\n errorCode: run.errorCode ?? null,\n errorMessage: run.errorMessage ?? null,\n retries: run.retries,\n startedAt: run.startedAt.toISOString(),\n }));\n }\n}\n","import type {\n AgentPricingStore,\n CurrentModelPrice,\n ModelPriceInput,\n} from '@dudousxd/nestjs-agent-core';\nimport { and, eq } from 'drizzle-orm';\nimport { type AgentDrizzleDb, agentModelPricing } from './schema.js';\n\n/**\n * {@link AgentPricingStore} backed by Drizzle ORM — the write side of the pricing table\n * {@link import('./drizzle-governance-queries.js').DrizzleGovernanceQueries} joins against. A POJO\n * receiving a Drizzle SQLite database handle (the host app owns the connection), mirroring\n * {@link import('@dudousxd/nestjs-agent-store-mikro-orm')} exactly (atomic supersede semantics).\n */\nexport class DrizzlePricingStore implements AgentPricingStore {\n constructor(private readonly db: AgentDrizzleDb) {}\n\n async upsertModelPrice(input: ModelPriceInput): Promise<void> {\n await this.db\n .update(agentModelPricing)\n .set({ isCurrent: false })\n .where(\n and(eq(agentModelPricing.modelId, input.modelId), eq(agentModelPricing.isCurrent, true)),\n );\n await this.db.insert(agentModelPricing).values({\n id: crypto.randomUUID(),\n modelId: input.modelId,\n inputPricePer1m: input.inputPricePer1m,\n outputPricePer1m: input.outputPricePer1m,\n cacheWritePricePer1m: input.cacheWritePricePer1m ?? null,\n cacheReadPricePer1m: input.cacheReadPricePer1m ?? null,\n effectiveFrom: new Date(),\n isCurrent: true,\n });\n }\n\n async listCurrentPrices(): Promise<CurrentModelPrice[]> {\n const rows = await this.db\n .select()\n .from(agentModelPricing)\n .where(eq(agentModelPricing.isCurrent, true));\n return rows.map((row) => ({\n modelId: row.modelId,\n inputPricePer1m: row.inputPricePer1m,\n outputPricePer1m: row.outputPricePer1m,\n effectiveFrom: row.effectiveFrom.toISOString(),\n ...(row.cacheWritePricePer1m != null\n ? { cacheWritePricePer1m: row.cacheWritePricePer1m }\n : {}),\n ...(row.cacheReadPricePer1m != null ? { cacheReadPricePer1m: row.cacheReadPricePer1m } : {}),\n }));\n }\n}\n","import {\n AGENT_GOVERNANCE_QUERIES,\n AGENT_PRICING_STORE,\n AGENT_STORE,\n type AgentPricingStore,\n} from '@dudousxd/nestjs-agent-core';\nimport { type DynamicModule, Module, type Type } from '@nestjs/common';\nimport { DrizzleAgentStore } from './drizzle-agent-store.js';\nimport { DrizzleGovernanceQueries } from './drizzle-governance-queries.js';\nimport { DrizzlePricingStore } from './drizzle-pricing-store.js';\nimport type { AgentDrizzleDb } from './schema.js';\n\n/** Options for {@link DrizzleAgentStoreModule.forRoot}. The app owns and supplies the db handle. */\nexport interface DrizzleAgentStoreModuleOptions {\n /** A Drizzle SQLite database instance (`drizzle(client, { schema: agentSchema })`). */\n db: AgentDrizzleDb;\n /**\n * Bind {@link AGENT_PRICING_STORE} (which {@link DrizzleGovernanceQueries} prices usage against) to\n * a host-supplied store instead of the default {@link DrizzlePricingStore} — make your OWN pricing\n * table the single source of cost truth without touching `agent_model_pricing`.\n */\n pricingStore?: Type<AgentPricingStore>;\n}\n\n/**\n * Binds {@link DrizzleAgentStore} to the {@link AGENT_STORE} token consumed by\n * `@dudousxd/nestjs-agent`, plus {@link DrizzleGovernanceQueries} to\n * {@link AGENT_GOVERNANCE_QUERIES} (the read-model the dashboard/telescope surfaces consume) and\n * {@link DrizzlePricingStore} to {@link AGENT_PRICING_STORE} (the write side of that pricing table).\n * The host app supplies an already-opened Drizzle db — this module never opens a connection itself.\n *\n * The returned module is global, so {@link AGENT_STORE}, {@link AGENT_GOVERNANCE_QUERIES} and\n * {@link AGENT_PRICING_STORE} are visible app-wide — `AgentModule` resolves the store without an\n * explicit `store` option, and the dashboard/telescope resolve {@link AGENT_GOVERNANCE_QUERIES}\n * without the host re-binding it.\n *\n * ```ts\n * @Module({ imports: [DrizzleAgentStoreModule.forRoot({ db })] })\n * export class AppModule {}\n * ```\n */\n@Module({})\nexport class DrizzleAgentStoreModule {\n static forRoot(options: DrizzleAgentStoreModuleOptions): DynamicModule {\n return {\n module: DrizzleAgentStoreModule,\n global: true,\n providers: [\n { provide: DrizzleAgentStore, useFactory: () => new DrizzleAgentStore(options.db) },\n { provide: AGENT_STORE, useExisting: DrizzleAgentStore },\n {\n provide: DrizzlePricingStore,\n useFactory: () => new DrizzlePricingStore(options.db),\n },\n // AGENT_PRICING_STORE: the host's own store when supplied, else the default Drizzle one.\n // DrizzleGovernanceQueries prices usage against whatever is bound here.\n options.pricingStore\n ? { provide: AGENT_PRICING_STORE, useClass: options.pricingStore }\n : { provide: AGENT_PRICING_STORE, useExisting: DrizzlePricingStore },\n {\n provide: DrizzleGovernanceQueries,\n useFactory: (pricingStore: AgentPricingStore) =>\n new DrizzleGovernanceQueries(options.db, pricingStore),\n inject: [AGENT_PRICING_STORE],\n },\n { provide: AGENT_GOVERNANCE_QUERIES, useExisting: DrizzleGovernanceQueries },\n ],\n exports: [\n DrizzleAgentStore,\n AGENT_STORE,\n DrizzleGovernanceQueries,\n AGENT_GOVERNANCE_QUERIES,\n DrizzlePricingStore,\n AGENT_PRICING_STORE,\n ],\n };\n }\n}\n"],"mappings":";;;;AASA,SAE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kBAAkBE,WAAW,IAAA,CAAA;AACzC,WAAOiB,KAAKG,IAAI,CAACC,SAAS;MACxBjB,SAASiB,IAAIjB;MACbM,iBAAiBW,IAAIX;MACrBC,kBAAkBU,IAAIV;MACtBG,eAAeO,IAAIP,cAAcQ,YAAW;MAC5C,GAAID,IAAIT,wBAAwB,OAC5B;QAAEA,sBAAsBS,IAAIT;MAAqB,IACjD,CAAC;MACL,GAAIS,IAAIR,uBAAuB,OAAO;QAAEA,qBAAqBQ,IAAIR;MAAoB,IAAI,CAAC;IAC5F,EAAA;EACF;AACF;;;ACpDA,SACEU,0BACAC,qBACAC,mBAEK;AACP,SAA6BC,cAAyB;;;;;;;;AAoC/C,IAAMC,0BAAN,MAAMA,yBAAAA;SAAAA;;;EACX,OAAOC,QAAQC,SAAwD;AACrE,WAAO;MACLC,QAAQH;MACRI,QAAQ;MACRC,WAAW;QACT;UAAEC,SAASC;UAAmBC,YAAY,6BAAM,IAAID,kBAAkBL,QAAQO,EAAE,GAAtC;QAAwC;QAClF;UAAEH,SAASI;UAAaC,aAAaJ;QAAkB;QACvD;UACED,SAASM;UACTJ,YAAY,6BAAM,IAAII,oBAAoBV,QAAQO,EAAE,GAAxC;QACd;;;QAGAP,QAAQW,eACJ;UAAEP,SAASQ;UAAqBC,UAAUb,QAAQW;QAAa,IAC/D;UAAEP,SAASQ;UAAqBH,aAAaC;QAAoB;QACrE;UACEN,SAASU;UACTR,YAAY,wBAACK,iBACX,IAAIG,yBAAyBd,QAAQO,IAAII,YAAAA,GAD/B;UAEZI,QAAQ;YAACH;;QACX;QACA;UAAER,SAASY;UAA0BP,aAAaK;QAAyB;;MAE7EG,SAAS;QACPZ;QACAG;QACAM;QACAE;QACAN;QACAE;;IAEJ;EACF;AACF;;;;","names":["index","integer","real","sqliteTable","text","agentThread","id","primaryKey","actorRef","notNull","tenantRef","title","transient","mode","default","activeStreamId","createdAt","updatedAt","deletedAt","table","on","agentMessage","threadId","references","onDelete","role","$type","content","toolCalls","toolResults","followUps","usage","agentName","agentToolCall","messageId","toolName","toolType","input","output","status","executedByRef","executionMs","error","executedAt","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","agentModelPricing","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","isCurrent","agentRun","durationMs","errorCode","errorMessage","retries","startedAt","settledAt","agentSchema","sql","statements","ensureAgentSchema","db","statement","run","sql","raw","and","asc","desc","eq","gte","inArray","isNull","lte","sql","DrizzleAgentStore","db","createThread","input","now","Date","thread","id","crypto","randomUUID","actorRef","actor","tenantRef","title","transient","activeStreamId","createdAt","updatedAt","deletedAt","insert","agentThread","values","toSummary","getThread","threadId","select","from","where","and","eq","isNull","undefined","messages","agentMessage","orderBy","asc","last","length","content","map","message","toStoredMessage","listThreads","limit","threads","desc","summaries","push","softDeleteThread","update","set","forkThread","fromMessageId","source","Error","cutoff","findIndex","kept","slice","fork","role","toolCalls","toolResults","followUps","usage","agentName","ownerOfThread","ownerOfToolCall","toolCallId","row","agentToolCall","innerJoin","messageId","runForToolCall","ownerOfActiveStream","runId","setTitle","promoteThread","setActiveStream","recordRunStart","run","runRow","status","durationMs","errorCode","errorMessage","retries","startedAt","settledAt","agentRun","recordRunEnd","end","updates","bumpRunRetries","sql","appendMessage","truncateFrom","doomedIds","delete","inArray","recordToolCall","toolName","toolType","output","executedByRef","executionMs","error","executedAt","updateToolCall","recordUsage","agentTokenUsage","modelId","purpose","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","quotaToday","day","start","rows","gte","lte","usedTokens","reduce","sum","lastContent","toISOString","lastMessagePreview","bucketByActor","bucketByModel","bucketByThread","bucketUsageTrend","dayBoundsUtc","and","count","desc","eq","gte","inArray","isNull","lte","UNCLASSIFIED_ERROR_CODE","DEFAULT_AGENT_BUCKET","toUsageInput","row","modelId","actorRef","threadId","day","createdAt","toISOString","slice","inputTokens","outputTokens","cacheWriteTokens","cacheReadTokens","costUsd","percentileMs","sortedDurationsMs","p","length","offset","Math","min","floor","DrizzleGovernanceQueries","db","pricingStore","loadPricing","prices","listCurrentPrices","pricing","Map","price","set","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","usageInRange","range","start","end","dayBoundsUtc","rows","select","from","agentTokenUsage","where","and","gte","lte","map","spendByModel","bucketByModel","spendByActor","bucketByActor","spendByThread","limit","threadIds","Set","threads","agentThread","inArray","id","isNull","deletedAt","threadsById","thread","title","bucketByThread","includeUnknownThreads","usageTrend","bucketUsageTrend","recentToolCalls","toolCallId","agentToolCall","toolName","toolType","status","agentMessage","innerJoin","eq","messageId","orderBy","desc","recentThreads","updatedAt","result","messageCountRow","value","count","usageRows","totalTokens","reduce","sum","push","messageCount","lastActivityAt","runsInRange","agentRun","startedAt","runMetrics","runs","completed","failed","retries","settledDurationsMs","run","durationMs","sort","left","right","successRate","durationP50Ms","durationP95Ms","runsByAgent","byAgent","agentName","bucket","get","localeCompare","runErrors","byError","errorCode","errorCount","runTrend","byDay","recentRuns","runId","errorMessage","and","eq","DrizzlePricingStore","db","upsertModelPrice","input","update","agentModelPricing","set","isCurrent","where","and","eq","modelId","insert","values","id","crypto","randomUUID","inputPricePer1m","outputPricePer1m","cacheWritePricePer1m","cacheReadPricePer1m","effectiveFrom","Date","listCurrentPrices","rows","select","from","map","row","toISOString","AGENT_GOVERNANCE_QUERIES","AGENT_PRICING_STORE","AGENT_STORE","Module","DrizzleAgentStoreModule","forRoot","options","module","global","providers","provide","DrizzleAgentStore","useFactory","db","AGENT_STORE","useExisting","DrizzlePricingStore","pricingStore","AGENT_PRICING_STORE","useClass","DrizzleGovernanceQueries","inject","AGENT_GOVERNANCE_QUERIES","exports"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dudousxd/nestjs-agent-store-drizzle",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/DavideCarvalho/nestjs-agent.git",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"dist"
|
|
30
30
|
],
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@dudousxd/nestjs-agent-core": "0.
|
|
32
|
+
"@dudousxd/nestjs-agent-core": "0.5.0"
|
|
33
33
|
},
|
|
34
34
|
"peerDependencies": {
|
|
35
35
|
"@nestjs/common": "^10.0.0 || ^11.0.0",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"tsup": "8.3.5",
|
|
44
44
|
"typescript": "5.9.3",
|
|
45
45
|
"vitest": "2.1.9",
|
|
46
|
-
"@dudousxd/nestjs-agent-core": "0.
|
|
46
|
+
"@dudousxd/nestjs-agent-core": "0.5.0"
|
|
47
47
|
},
|
|
48
48
|
"scripts": {
|
|
49
49
|
"build": "tsup",
|