@dudousxd/nestjs-agent-store-drizzle 0.23.0 → 0.24.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 CHANGED
@@ -10,9 +10,9 @@ var __export = (target, all) => {
10
10
  };
11
11
  var __copyProps = (to, from, except, desc4) => {
12
12
  if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc4 = __getOwnPropDesc(from, key)) || desc4.enumerable });
13
+ for (let key2 of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
15
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc4 = __getOwnPropDesc(from, key2)) || desc4.enumerable });
16
16
  }
17
17
  return to;
18
18
  };
@@ -32,17 +32,21 @@ __export(index_exports, {
32
32
  DrizzleTokenStreamSink: () => DrizzleTokenStreamSink,
33
33
  RAG_INGESTION_LOG_PAGE_ORDER: () => RAG_INGESTION_LOG_PAGE_ORDER,
34
34
  agentConfirmToken: () => agentConfirmToken,
35
+ agentDialectOf: () => agentDialectOf,
35
36
  agentMemory: () => agentMemory,
36
37
  agentMessage: () => agentMessage,
37
38
  agentModelPricing: () => agentModelPricing,
38
39
  agentQueuedMessage: () => agentQueuedMessage,
39
40
  agentRun: () => agentRun,
40
41
  agentSchema: () => agentSchema,
42
+ agentSchemaDdl: () => agentSchemaDdl,
41
43
  agentStreamFrame: () => agentStreamFrame,
42
44
  agentThread: () => agentThread,
43
45
  agentTokenUsage: () => agentTokenUsage,
44
46
  agentToolCall: () => agentToolCall,
45
47
  ensureAgentSchema: () => ensureAgentSchema,
48
+ mysqlAgentSchema: () => mysqlAgentSchema,
49
+ pgAgentSchema: () => pgAgentSchema,
46
50
  ragIngestionLog: () => ragIngestionLog
47
51
  });
48
52
  module.exports = __toCommonJS(index_exports);
@@ -117,6 +121,12 @@ var agentMessage = (0, import_sqlite_core.sqliteTable)("agent_message", {
117
121
  feedback: (0, import_sqlite_core.text)("feedback", {
118
122
  mode: "json"
119
123
  }).$type(),
124
+ /**
125
+ * The message's place in its thread, 1-based, assigned on append — what orders a transcript.
126
+ * `created_at` cannot: two messages of one turn routinely share a timestamp, and the uuid that
127
+ * broke the tie is random. `null` on a row from before the column; those sort first.
128
+ */
129
+ seq: (0, import_sqlite_core.integer)("seq"),
120
130
  createdAt: (0, import_sqlite_core.integer)("created_at", {
121
131
  mode: "timestamp_ms"
122
132
  }).notNull()
@@ -351,303 +361,721 @@ var agentSchema = {
351
361
  agentRun,
352
362
  agentMemory,
353
363
  ragIngestionLog,
354
- agentConfirmToken
364
+ agentConfirmToken,
365
+ agentStreamFrame
355
366
  };
356
367
 
357
368
  // src/ensure-schema.ts
369
+ var import_drizzle_orm2 = require("drizzle-orm");
370
+ var import_mysql_core3 = require("drizzle-orm/mysql-core");
371
+ var import_pg_core3 = require("drizzle-orm/pg-core");
372
+ var import_sqlite_core2 = require("drizzle-orm/sqlite-core");
373
+
374
+ // src/dialect.ts
358
375
  var import_drizzle_orm = require("drizzle-orm");
359
- var statements = [
360
- `CREATE TABLE IF NOT EXISTS agent_thread (
361
- id TEXT PRIMARY KEY NOT NULL,
362
- actor_ref TEXT NOT NULL,
363
- tenant_ref TEXT,
364
- title TEXT NOT NULL,
365
- transient INTEGER NOT NULL DEFAULT 0,
366
- active_stream_id TEXT,
367
- default_agent TEXT,
368
- model TEXT,
369
- persona TEXT,
370
- queue_pause TEXT,
371
- created_at INTEGER NOT NULL,
372
- updated_at INTEGER NOT NULL,
373
- deleted_at INTEGER
374
- )`,
375
- `CREATE INDEX IF NOT EXISTS agent_thread_actor_updated_idx
376
- ON agent_thread (actor_ref, updated_at)`,
377
- `CREATE TABLE IF NOT EXISTS agent_message (
378
- id TEXT PRIMARY KEY NOT NULL,
379
- thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,
380
- role TEXT NOT NULL,
381
- content TEXT NOT NULL,
382
- tool_calls TEXT,
383
- tool_results TEXT,
384
- attachments TEXT,
385
- follow_ups TEXT,
386
- usage TEXT,
387
- agent_name TEXT,
388
- persona TEXT,
389
- run_id TEXT,
390
- reasoning TEXT,
391
- reasoning_ms INTEGER,
392
- ui TEXT,
393
- feedback TEXT,
394
- created_at INTEGER NOT NULL
395
- )`,
396
- `CREATE INDEX IF NOT EXISTS agent_message_thread_created_idx
397
- ON agent_message (thread_id, created_at)`,
398
- `CREATE TABLE IF NOT EXISTS agent_queued_message (
399
- id TEXT PRIMARY KEY NOT NULL,
400
- thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,
401
- actor TEXT NOT NULL,
402
- content TEXT NOT NULL,
403
- attachments TEXT,
404
- agent_name TEXT,
405
- persona TEXT,
406
- model TEXT,
407
- page_context TEXT,
408
- interrupt INTEGER NOT NULL DEFAULT 0,
409
- position INTEGER NOT NULL,
410
- created_at INTEGER NOT NULL,
411
- updated_at INTEGER NOT NULL
412
- )`,
413
- `CREATE INDEX IF NOT EXISTS agent_queued_message_thread_position_idx
414
- ON agent_queued_message (thread_id, position)`,
415
- `CREATE TABLE IF NOT EXISTS agent_tool_call (
416
- id TEXT PRIMARY KEY NOT NULL,
417
- message_id TEXT NOT NULL REFERENCES agent_message(id) ON DELETE CASCADE,
418
- tool_name TEXT NOT NULL,
419
- tool_type TEXT NOT NULL,
420
- input TEXT,
421
- output TEXT,
422
- status TEXT NOT NULL,
423
- executed_by_ref TEXT,
424
- execution_ms INTEGER,
425
- error TEXT,
426
- created_at INTEGER NOT NULL,
427
- executed_at INTEGER,
428
- run_id TEXT,
429
- approver TEXT,
430
- expires_at INTEGER,
431
- remember INTEGER,
432
- decided_via TEXT
433
- )`,
434
- `CREATE INDEX IF NOT EXISTS agent_tool_call_message_idx
435
- ON agent_tool_call (message_id)`,
436
- `CREATE TABLE IF NOT EXISTS agent_token_usage (
437
- id TEXT PRIMARY KEY NOT NULL,
438
- thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,
439
- actor_ref TEXT NOT NULL,
440
- message_id TEXT,
441
- model_id TEXT NOT NULL,
442
- purpose TEXT NOT NULL,
443
- input_tokens INTEGER NOT NULL,
444
- output_tokens INTEGER NOT NULL,
445
- cache_write_tokens INTEGER,
446
- cache_read_tokens INTEGER,
447
- cost_usd REAL,
448
- created_at INTEGER NOT NULL
449
- )`,
450
- `CREATE INDEX IF NOT EXISTS agent_token_usage_actor_created_idx
451
- ON agent_token_usage (actor_ref, created_at)`,
452
- `CREATE TABLE IF NOT EXISTS agent_model_pricing (
453
- id TEXT PRIMARY KEY NOT NULL,
454
- model_id TEXT NOT NULL,
455
- input_price_per_1m REAL NOT NULL,
456
- output_price_per_1m REAL NOT NULL,
457
- cache_write_price_per_1m REAL,
458
- cache_read_price_per_1m REAL,
459
- effective_from INTEGER NOT NULL,
460
- is_current INTEGER NOT NULL
461
- )`,
462
- `CREATE TABLE IF NOT EXISTS agent_run (
463
- id TEXT PRIMARY KEY NOT NULL,
464
- thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,
465
- actor_ref TEXT NOT NULL,
466
- agent_name TEXT,
467
- status TEXT NOT NULL,
468
- duration_ms INTEGER,
469
- error_code TEXT,
470
- error_message TEXT,
471
- retries INTEGER NOT NULL DEFAULT 0,
472
- started_at INTEGER NOT NULL,
473
- settled_at INTEGER,
474
- prompt_hash TEXT,
475
- parent_run_id TEXT
476
- )`,
477
- `CREATE INDEX IF NOT EXISTS agent_run_started_idx
478
- ON agent_run (started_at)`,
479
- // `key` and `text` are quoted: both are keywords in at least one engine this DDL is read by, and
480
- // they are the SPI's own field names, which is worth more here than dodging the quoting.
481
- `CREATE TABLE IF NOT EXISTS agent_memory (
482
- id TEXT PRIMARY KEY NOT NULL,
483
- scope TEXT NOT NULL,
484
- "key" TEXT NOT NULL,
485
- "text" TEXT NOT NULL,
486
- origin_author TEXT NOT NULL,
487
- origin_thread_id TEXT,
488
- origin_run_id TEXT,
489
- origin_actor_ref TEXT,
490
- pinned INTEGER NOT NULL DEFAULT 0,
491
- created_at INTEGER NOT NULL,
492
- updated_at INTEGER NOT NULL
493
- )`,
494
- `CREATE UNIQUE INDEX IF NOT EXISTS agent_memory_scope_key_uq
495
- ON agent_memory (scope, "key")`,
496
- `CREATE TABLE IF NOT EXISTS rag_ingestion_log (
497
- document_id TEXT PRIMARY KEY NOT NULL,
498
- status TEXT NOT NULL,
499
- collection TEXT,
500
- owner_type TEXT,
501
- owner_id TEXT,
502
- source TEXT,
503
- mime_type TEXT,
504
- size INTEGER,
505
- chunks INTEGER,
506
- reason TEXT,
507
- error TEXT,
508
- created_at INTEGER NOT NULL,
509
- updated_at INTEGER NOT NULL
510
- )`,
511
- `CREATE INDEX IF NOT EXISTS rag_ingestion_log_collection_idx
512
- ON rag_ingestion_log (collection, updated_at)`,
513
- `CREATE TABLE IF NOT EXISTS agent_stream_frame (
514
- run_id TEXT NOT NULL,
515
- seq INTEGER NOT NULL,
516
- frame TEXT,
517
- error TEXT,
518
- created_at INTEGER NOT NULL,
519
- PRIMARY KEY (run_id, seq)
520
- )`,
521
- `CREATE TABLE IF NOT EXISTS agent_confirm_token (
522
- hash TEXT PRIMARY KEY NOT NULL,
523
- actor_ref TEXT NOT NULL,
524
- tool TEXT NOT NULL,
525
- expires_at INTEGER NOT NULL,
526
- created_at INTEGER NOT NULL
527
- )`,
528
- `CREATE INDEX IF NOT EXISTS agent_confirm_token_expires_idx
529
- ON agent_confirm_token (expires_at)`
530
- ];
531
- var additiveColumns = [
532
- {
533
- table: "agent_message",
534
- column: "run_id",
535
- ddl: "ALTER TABLE agent_message ADD COLUMN run_id TEXT"
536
- },
537
- {
538
- table: "agent_message",
539
- column: "attachments",
540
- ddl: "ALTER TABLE agent_message ADD COLUMN attachments TEXT"
541
- },
542
- {
543
- table: "agent_thread",
544
- column: "default_agent",
545
- ddl: "ALTER TABLE agent_thread ADD COLUMN default_agent TEXT"
546
- },
547
- {
548
- table: "agent_run",
549
- column: "parent_run_id",
550
- ddl: "ALTER TABLE agent_run ADD COLUMN parent_run_id TEXT"
551
- },
552
- {
553
- table: "agent_message",
554
- column: "reasoning",
555
- ddl: "ALTER TABLE agent_message ADD COLUMN reasoning TEXT"
556
- },
557
- {
558
- table: "agent_message",
559
- column: "reasoning_ms",
560
- ddl: "ALTER TABLE agent_message ADD COLUMN reasoning_ms INTEGER"
561
- },
562
- {
563
- table: "agent_message",
564
- column: "ui",
565
- ddl: "ALTER TABLE agent_message ADD COLUMN ui TEXT"
566
- },
567
- {
568
- table: "agent_message",
569
- column: "feedback",
570
- ddl: "ALTER TABLE agent_message ADD COLUMN feedback TEXT"
571
- },
572
- {
573
- table: "agent_thread",
574
- column: "model",
575
- ddl: "ALTER TABLE agent_thread ADD COLUMN model TEXT"
576
- },
577
- {
578
- table: "agent_tool_call",
579
- column: "approver",
580
- ddl: "ALTER TABLE agent_tool_call ADD COLUMN approver TEXT"
581
- },
582
- {
583
- table: "agent_tool_call",
584
- column: "expires_at",
585
- ddl: "ALTER TABLE agent_tool_call ADD COLUMN expires_at INTEGER"
586
- },
587
- {
588
- table: "agent_tool_call",
589
- column: "remember",
590
- ddl: "ALTER TABLE agent_tool_call ADD COLUMN remember INTEGER"
591
- },
592
- {
593
- table: "agent_thread",
594
- column: "queue_pause",
595
- ddl: "ALTER TABLE agent_thread ADD COLUMN queue_pause TEXT"
596
- },
597
- {
598
- table: "agent_tool_call",
599
- column: "decided_via",
600
- ddl: "ALTER TABLE agent_tool_call ADD COLUMN decided_via TEXT"
601
- },
602
- {
603
- table: "agent_thread",
604
- column: "persona",
605
- ddl: "ALTER TABLE agent_thread ADD COLUMN persona TEXT"
606
- },
607
- {
608
- table: "agent_message",
609
- column: "persona",
610
- ddl: "ALTER TABLE agent_message ADD COLUMN persona TEXT"
611
- },
612
- {
613
- table: "agent_queued_message",
614
- column: "persona",
615
- ddl: "ALTER TABLE agent_queued_message ADD COLUMN persona TEXT"
376
+ var import_mysql_core2 = require("drizzle-orm/mysql-core");
377
+ var import_pg_core2 = require("drizzle-orm/pg-core");
378
+
379
+ // src/schema-mysql.ts
380
+ var import_mysql_core = require("drizzle-orm/mysql-core");
381
+ var ts = /* @__PURE__ */ __name((name) => (0, import_mysql_core.datetime)(name, {
382
+ mode: "date",
383
+ fsp: 3
384
+ }), "ts");
385
+ var key = /* @__PURE__ */ __name((name) => (0, import_mysql_core.varchar)(name, {
386
+ length: 255
387
+ }), "key");
388
+ var agentThread2 = (0, import_mysql_core.mysqlTable)("agent_thread", {
389
+ id: key("id").primaryKey(),
390
+ actorRef: key("actor_ref").notNull(),
391
+ tenantRef: key("tenant_ref"),
392
+ title: key("title").notNull(),
393
+ transient: (0, import_mysql_core.boolean)("transient").notNull().default(false),
394
+ activeStreamId: key("active_stream_id"),
395
+ defaultAgent: key("default_agent"),
396
+ model: key("model"),
397
+ /** The persona a send on this thread runs under when it names none; `null` → the agent's default. */
398
+ persona: key("persona"),
399
+ queuePause: (0, import_mysql_core.json)("queue_pause").$type(),
400
+ createdAt: ts("created_at").notNull(),
401
+ updatedAt: ts("updated_at").notNull(),
402
+ deletedAt: ts("deleted_at")
403
+ }, (table) => [
404
+ (0, import_mysql_core.index)("agent_thread_actor_updated_idx").on(table.actorRef, table.updatedAt)
405
+ ]);
406
+ var agentMessage2 = (0, import_mysql_core.mysqlTable)("agent_message", {
407
+ id: key("id").primaryKey(),
408
+ threadId: key("thread_id").notNull().references(() => agentThread2.id, {
409
+ onDelete: "cascade"
410
+ }),
411
+ role: key("role").$type().notNull(),
412
+ content: (0, import_mysql_core.longtext)("content").notNull(),
413
+ toolCalls: (0, import_mysql_core.json)("tool_calls").$type(),
414
+ toolResults: (0, import_mysql_core.json)("tool_results").$type(),
415
+ attachments: (0, import_mysql_core.json)("attachments").$type(),
416
+ followUps: (0, import_mysql_core.json)("follow_ups").$type(),
417
+ usage: (0, import_mysql_core.json)("usage").$type(),
418
+ agentName: key("agent_name"),
419
+ /** The persona the turn that wrote this message ran under; `null` → none. */
420
+ persona: key("persona"),
421
+ runId: key("run_id"),
422
+ reasoning: (0, import_mysql_core.longtext)("reasoning"),
423
+ reasoningMs: (0, import_mysql_core.int)("reasoning_ms"),
424
+ ui: (0, import_mysql_core.json)("ui").$type(),
425
+ feedback: (0, import_mysql_core.json)("feedback").$type(),
426
+ seq: (0, import_mysql_core.int)("seq"),
427
+ createdAt: ts("created_at").notNull()
428
+ }, (table) => [
429
+ (0, import_mysql_core.index)("agent_message_thread_created_idx").on(table.threadId, table.createdAt)
430
+ ]);
431
+ var agentToolCall2 = (0, import_mysql_core.mysqlTable)("agent_tool_call", {
432
+ id: key("id").primaryKey(),
433
+ messageId: key("message_id").notNull().references(() => agentMessage2.id, {
434
+ onDelete: "cascade"
435
+ }),
436
+ toolName: key("tool_name").notNull(),
437
+ toolType: key("tool_type").$type().notNull(),
438
+ input: (0, import_mysql_core.json)("input"),
439
+ output: (0, import_mysql_core.json)("output"),
440
+ status: key("status").$type().notNull(),
441
+ executedByRef: key("executed_by_ref"),
442
+ executionMs: (0, import_mysql_core.int)("execution_ms"),
443
+ error: (0, import_mysql_core.longtext)("error"),
444
+ createdAt: ts("created_at").notNull(),
445
+ executedAt: ts("executed_at"),
446
+ runId: key("run_id"),
447
+ approver: key("approver"),
448
+ expiresAt: ts("expires_at"),
449
+ remember: (0, import_mysql_core.boolean)("remember"),
450
+ decidedVia: key("decided_via")
451
+ }, (table) => [
452
+ (0, import_mysql_core.index)("agent_tool_call_message_idx").on(table.messageId)
453
+ ]);
454
+ var agentQueuedMessage2 = (0, import_mysql_core.mysqlTable)("agent_queued_message", {
455
+ id: key("id").primaryKey(),
456
+ threadId: key("thread_id").notNull().references(() => agentThread2.id, {
457
+ onDelete: "cascade"
458
+ }),
459
+ actor: (0, import_mysql_core.json)("actor").$type().notNull(),
460
+ content: (0, import_mysql_core.longtext)("content").notNull(),
461
+ attachments: (0, import_mysql_core.json)("attachments").$type(),
462
+ agentName: key("agent_name"),
463
+ /** The persona the send resolved — what the message starts under. */
464
+ persona: key("persona"),
465
+ model: key("model"),
466
+ pageContext: (0, import_mysql_core.json)("page_context").$type(),
467
+ interrupt: (0, import_mysql_core.boolean)("interrupt").notNull().default(false),
468
+ position: (0, import_mysql_core.int)("position").notNull(),
469
+ createdAt: ts("created_at").notNull(),
470
+ updatedAt: ts("updated_at").notNull()
471
+ }, (table) => [
472
+ (0, import_mysql_core.index)("agent_queued_message_thread_position_idx").on(table.threadId, table.position)
473
+ ]);
474
+ var agentTokenUsage2 = (0, import_mysql_core.mysqlTable)("agent_token_usage", {
475
+ id: key("id").primaryKey(),
476
+ threadId: key("thread_id").notNull().references(() => agentThread2.id, {
477
+ onDelete: "cascade"
478
+ }),
479
+ actorRef: key("actor_ref").notNull(),
480
+ messageId: key("message_id"),
481
+ modelId: key("model_id").notNull(),
482
+ purpose: key("purpose").$type().notNull(),
483
+ inputTokens: (0, import_mysql_core.int)("input_tokens").notNull(),
484
+ outputTokens: (0, import_mysql_core.int)("output_tokens").notNull(),
485
+ cacheWriteTokens: (0, import_mysql_core.int)("cache_write_tokens"),
486
+ cacheReadTokens: (0, import_mysql_core.int)("cache_read_tokens"),
487
+ costUsd: (0, import_mysql_core.double)("cost_usd"),
488
+ createdAt: ts("created_at").notNull()
489
+ }, (table) => [
490
+ (0, import_mysql_core.index)("agent_token_usage_actor_created_idx").on(table.actorRef, table.createdAt)
491
+ ]);
492
+ var agentModelPricing2 = (0, import_mysql_core.mysqlTable)("agent_model_pricing", {
493
+ id: key("id").primaryKey(),
494
+ modelId: key("model_id").notNull(),
495
+ inputPricePer1m: (0, import_mysql_core.double)("input_price_per_1m").notNull(),
496
+ outputPricePer1m: (0, import_mysql_core.double)("output_price_per_1m").notNull(),
497
+ cacheWritePricePer1m: (0, import_mysql_core.double)("cache_write_price_per_1m"),
498
+ cacheReadPricePer1m: (0, import_mysql_core.double)("cache_read_price_per_1m"),
499
+ effectiveFrom: ts("effective_from").notNull(),
500
+ isCurrent: (0, import_mysql_core.boolean)("is_current").notNull()
501
+ });
502
+ var agentRun2 = (0, import_mysql_core.mysqlTable)("agent_run", {
503
+ id: key("id").primaryKey(),
504
+ threadId: key("thread_id").notNull().references(() => agentThread2.id, {
505
+ onDelete: "cascade"
506
+ }),
507
+ actorRef: key("actor_ref").notNull(),
508
+ agentName: key("agent_name"),
509
+ status: key("status").$type().notNull(),
510
+ durationMs: (0, import_mysql_core.int)("duration_ms"),
511
+ errorCode: key("error_code"),
512
+ errorMessage: (0, import_mysql_core.longtext)("error_message"),
513
+ retries: (0, import_mysql_core.int)("retries").notNull().default(0),
514
+ startedAt: ts("started_at").notNull(),
515
+ settledAt: ts("settled_at"),
516
+ promptHash: key("prompt_hash"),
517
+ parentRunId: key("parent_run_id")
518
+ }, (table) => [
519
+ (0, import_mysql_core.index)("agent_run_started_idx").on(table.startedAt)
520
+ ]);
521
+ var agentMemory2 = (0, import_mysql_core.mysqlTable)("agent_memory", {
522
+ id: key("id").primaryKey(),
523
+ scope: key("scope").notNull(),
524
+ key: key("key").notNull(),
525
+ text: (0, import_mysql_core.longtext)("text").notNull(),
526
+ originAuthor: key("origin_author").$type().notNull(),
527
+ originThreadId: key("origin_thread_id"),
528
+ originRunId: key("origin_run_id"),
529
+ originActorRef: key("origin_actor_ref"),
530
+ pinned: (0, import_mysql_core.boolean)("pinned").notNull().default(false),
531
+ createdAt: ts("created_at").notNull(),
532
+ updatedAt: ts("updated_at").notNull()
533
+ }, (table) => [
534
+ (0, import_mysql_core.uniqueIndex)("agent_memory_scope_key_uq").on(table.scope, table.key)
535
+ ]);
536
+ var ragIngestionLog2 = (0, import_mysql_core.mysqlTable)("rag_ingestion_log", {
537
+ documentId: key("document_id").primaryKey(),
538
+ status: key("status").$type().notNull(),
539
+ collection: key("collection"),
540
+ ownerType: key("owner_type"),
541
+ ownerId: key("owner_id"),
542
+ source: (0, import_mysql_core.longtext)("source"),
543
+ mimeType: key("mime_type"),
544
+ size: (0, import_mysql_core.bigint)("size", {
545
+ mode: "number"
546
+ }),
547
+ chunks: (0, import_mysql_core.int)("chunks"),
548
+ reason: key("reason"),
549
+ error: (0, import_mysql_core.longtext)("error"),
550
+ createdAt: ts("created_at").notNull(),
551
+ updatedAt: ts("updated_at").notNull()
552
+ }, (table) => [
553
+ (0, import_mysql_core.index)("rag_ingestion_log_collection_idx").on(table.collection, table.updatedAt)
554
+ ]);
555
+ var agentConfirmToken2 = (0, import_mysql_core.mysqlTable)("agent_confirm_token", {
556
+ hash: key("hash").primaryKey(),
557
+ actorRef: key("actor_ref").notNull(),
558
+ tool: key("tool").notNull(),
559
+ expiresAt: (0, import_mysql_core.bigint)("expires_at", {
560
+ mode: "number"
561
+ }).notNull(),
562
+ createdAt: (0, import_mysql_core.bigint)("created_at", {
563
+ mode: "number"
564
+ }).notNull()
565
+ }, (table) => [
566
+ (0, import_mysql_core.index)("agent_confirm_token_expires_idx").on(table.expiresAt)
567
+ ]);
568
+ var agentStreamFrame2 = (0, import_mysql_core.mysqlTable)("agent_stream_frame", {
569
+ runId: key("run_id").notNull(),
570
+ seq: (0, import_mysql_core.int)("seq").notNull(),
571
+ frame: (0, import_mysql_core.longtext)("frame"),
572
+ error: (0, import_mysql_core.longtext)("error"),
573
+ createdAt: (0, import_mysql_core.bigint)("created_at", {
574
+ mode: "number"
575
+ }).notNull()
576
+ }, (table) => [
577
+ (0, import_mysql_core.primaryKey)({
578
+ columns: [
579
+ table.runId,
580
+ table.seq
581
+ ]
582
+ })
583
+ ]);
584
+ var mysqlAgentSchema = {
585
+ agentThread: agentThread2,
586
+ agentMessage: agentMessage2,
587
+ agentQueuedMessage: agentQueuedMessage2,
588
+ agentToolCall: agentToolCall2,
589
+ agentTokenUsage: agentTokenUsage2,
590
+ agentModelPricing: agentModelPricing2,
591
+ agentRun: agentRun2,
592
+ agentMemory: agentMemory2,
593
+ ragIngestionLog: ragIngestionLog2,
594
+ agentConfirmToken: agentConfirmToken2,
595
+ agentStreamFrame: agentStreamFrame2
596
+ };
597
+
598
+ // src/schema-pg.ts
599
+ var import_pg_core = require("drizzle-orm/pg-core");
600
+ var ts2 = /* @__PURE__ */ __name((name) => (0, import_pg_core.timestamp)(name, {
601
+ withTimezone: true,
602
+ precision: 3,
603
+ mode: "date"
604
+ }), "ts");
605
+ var agentThread3 = (0, import_pg_core.pgTable)("agent_thread", {
606
+ id: (0, import_pg_core.text)("id").primaryKey(),
607
+ actorRef: (0, import_pg_core.text)("actor_ref").notNull(),
608
+ tenantRef: (0, import_pg_core.text)("tenant_ref"),
609
+ title: (0, import_pg_core.text)("title").notNull(),
610
+ transient: (0, import_pg_core.boolean)("transient").notNull().default(false),
611
+ activeStreamId: (0, import_pg_core.text)("active_stream_id"),
612
+ defaultAgent: (0, import_pg_core.text)("default_agent"),
613
+ model: (0, import_pg_core.text)("model"),
614
+ /** The persona a send on this thread runs under when it names none; `null` → the agent's default. */
615
+ persona: (0, import_pg_core.text)("persona"),
616
+ queuePause: (0, import_pg_core.jsonb)("queue_pause").$type(),
617
+ createdAt: ts2("created_at").notNull(),
618
+ updatedAt: ts2("updated_at").notNull(),
619
+ deletedAt: ts2("deleted_at")
620
+ }, (table) => [
621
+ (0, import_pg_core.index)("agent_thread_actor_updated_idx").on(table.actorRef, table.updatedAt)
622
+ ]);
623
+ var agentMessage3 = (0, import_pg_core.pgTable)("agent_message", {
624
+ id: (0, import_pg_core.text)("id").primaryKey(),
625
+ threadId: (0, import_pg_core.text)("thread_id").notNull().references(() => agentThread3.id, {
626
+ onDelete: "cascade"
627
+ }),
628
+ role: (0, import_pg_core.text)("role").$type().notNull(),
629
+ content: (0, import_pg_core.text)("content").notNull(),
630
+ toolCalls: (0, import_pg_core.jsonb)("tool_calls").$type(),
631
+ toolResults: (0, import_pg_core.jsonb)("tool_results").$type(),
632
+ attachments: (0, import_pg_core.jsonb)("attachments").$type(),
633
+ followUps: (0, import_pg_core.jsonb)("follow_ups").$type(),
634
+ usage: (0, import_pg_core.jsonb)("usage").$type(),
635
+ agentName: (0, import_pg_core.text)("agent_name"),
636
+ /** The persona the turn that wrote this message ran under; `null` → none. */
637
+ persona: (0, import_pg_core.text)("persona"),
638
+ runId: (0, import_pg_core.text)("run_id"),
639
+ reasoning: (0, import_pg_core.text)("reasoning"),
640
+ reasoningMs: (0, import_pg_core.integer)("reasoning_ms"),
641
+ ui: (0, import_pg_core.jsonb)("ui").$type(),
642
+ feedback: (0, import_pg_core.jsonb)("feedback").$type(),
643
+ seq: (0, import_pg_core.integer)("seq"),
644
+ createdAt: ts2("created_at").notNull()
645
+ }, (table) => [
646
+ (0, import_pg_core.index)("agent_message_thread_created_idx").on(table.threadId, table.createdAt)
647
+ ]);
648
+ var agentToolCall3 = (0, import_pg_core.pgTable)("agent_tool_call", {
649
+ id: (0, import_pg_core.text)("id").primaryKey(),
650
+ messageId: (0, import_pg_core.text)("message_id").notNull().references(() => agentMessage3.id, {
651
+ onDelete: "cascade"
652
+ }),
653
+ toolName: (0, import_pg_core.text)("tool_name").notNull(),
654
+ toolType: (0, import_pg_core.text)("tool_type").$type().notNull(),
655
+ input: (0, import_pg_core.jsonb)("input"),
656
+ output: (0, import_pg_core.jsonb)("output"),
657
+ status: (0, import_pg_core.text)("status").$type().notNull(),
658
+ executedByRef: (0, import_pg_core.text)("executed_by_ref"),
659
+ executionMs: (0, import_pg_core.integer)("execution_ms"),
660
+ error: (0, import_pg_core.text)("error"),
661
+ createdAt: ts2("created_at").notNull(),
662
+ executedAt: ts2("executed_at"),
663
+ runId: (0, import_pg_core.text)("run_id"),
664
+ approver: (0, import_pg_core.text)("approver"),
665
+ expiresAt: ts2("expires_at"),
666
+ remember: (0, import_pg_core.boolean)("remember"),
667
+ decidedVia: (0, import_pg_core.text)("decided_via")
668
+ }, (table) => [
669
+ (0, import_pg_core.index)("agent_tool_call_message_idx").on(table.messageId)
670
+ ]);
671
+ var agentQueuedMessage3 = (0, import_pg_core.pgTable)("agent_queued_message", {
672
+ id: (0, import_pg_core.text)("id").primaryKey(),
673
+ threadId: (0, import_pg_core.text)("thread_id").notNull().references(() => agentThread3.id, {
674
+ onDelete: "cascade"
675
+ }),
676
+ actor: (0, import_pg_core.jsonb)("actor").$type().notNull(),
677
+ content: (0, import_pg_core.text)("content").notNull(),
678
+ attachments: (0, import_pg_core.jsonb)("attachments").$type(),
679
+ agentName: (0, import_pg_core.text)("agent_name"),
680
+ /** The persona the send resolved — what the message starts under. */
681
+ persona: (0, import_pg_core.text)("persona"),
682
+ model: (0, import_pg_core.text)("model"),
683
+ pageContext: (0, import_pg_core.jsonb)("page_context").$type(),
684
+ interrupt: (0, import_pg_core.boolean)("interrupt").notNull().default(false),
685
+ position: (0, import_pg_core.integer)("position").notNull(),
686
+ createdAt: ts2("created_at").notNull(),
687
+ updatedAt: ts2("updated_at").notNull()
688
+ }, (table) => [
689
+ (0, import_pg_core.index)("agent_queued_message_thread_position_idx").on(table.threadId, table.position)
690
+ ]);
691
+ var agentTokenUsage3 = (0, import_pg_core.pgTable)("agent_token_usage", {
692
+ id: (0, import_pg_core.text)("id").primaryKey(),
693
+ threadId: (0, import_pg_core.text)("thread_id").notNull().references(() => agentThread3.id, {
694
+ onDelete: "cascade"
695
+ }),
696
+ actorRef: (0, import_pg_core.text)("actor_ref").notNull(),
697
+ messageId: (0, import_pg_core.text)("message_id"),
698
+ modelId: (0, import_pg_core.text)("model_id").notNull(),
699
+ purpose: (0, import_pg_core.text)("purpose").$type().notNull(),
700
+ inputTokens: (0, import_pg_core.integer)("input_tokens").notNull(),
701
+ outputTokens: (0, import_pg_core.integer)("output_tokens").notNull(),
702
+ cacheWriteTokens: (0, import_pg_core.integer)("cache_write_tokens"),
703
+ cacheReadTokens: (0, import_pg_core.integer)("cache_read_tokens"),
704
+ costUsd: (0, import_pg_core.doublePrecision)("cost_usd"),
705
+ createdAt: ts2("created_at").notNull()
706
+ }, (table) => [
707
+ (0, import_pg_core.index)("agent_token_usage_actor_created_idx").on(table.actorRef, table.createdAt)
708
+ ]);
709
+ var agentModelPricing3 = (0, import_pg_core.pgTable)("agent_model_pricing", {
710
+ id: (0, import_pg_core.text)("id").primaryKey(),
711
+ modelId: (0, import_pg_core.text)("model_id").notNull(),
712
+ inputPricePer1m: (0, import_pg_core.doublePrecision)("input_price_per_1m").notNull(),
713
+ outputPricePer1m: (0, import_pg_core.doublePrecision)("output_price_per_1m").notNull(),
714
+ cacheWritePricePer1m: (0, import_pg_core.doublePrecision)("cache_write_price_per_1m"),
715
+ cacheReadPricePer1m: (0, import_pg_core.doublePrecision)("cache_read_price_per_1m"),
716
+ effectiveFrom: ts2("effective_from").notNull(),
717
+ isCurrent: (0, import_pg_core.boolean)("is_current").notNull()
718
+ });
719
+ var agentRun3 = (0, import_pg_core.pgTable)("agent_run", {
720
+ id: (0, import_pg_core.text)("id").primaryKey(),
721
+ threadId: (0, import_pg_core.text)("thread_id").notNull().references(() => agentThread3.id, {
722
+ onDelete: "cascade"
723
+ }),
724
+ actorRef: (0, import_pg_core.text)("actor_ref").notNull(),
725
+ agentName: (0, import_pg_core.text)("agent_name"),
726
+ status: (0, import_pg_core.text)("status").$type().notNull(),
727
+ durationMs: (0, import_pg_core.integer)("duration_ms"),
728
+ errorCode: (0, import_pg_core.text)("error_code"),
729
+ errorMessage: (0, import_pg_core.text)("error_message"),
730
+ retries: (0, import_pg_core.integer)("retries").notNull().default(0),
731
+ startedAt: ts2("started_at").notNull(),
732
+ settledAt: ts2("settled_at"),
733
+ promptHash: (0, import_pg_core.text)("prompt_hash"),
734
+ parentRunId: (0, import_pg_core.text)("parent_run_id")
735
+ }, (table) => [
736
+ (0, import_pg_core.index)("agent_run_started_idx").on(table.startedAt)
737
+ ]);
738
+ var agentMemory3 = (0, import_pg_core.pgTable)("agent_memory", {
739
+ id: (0, import_pg_core.text)("id").primaryKey(),
740
+ scope: (0, import_pg_core.text)("scope").notNull(),
741
+ key: (0, import_pg_core.text)("key").notNull(),
742
+ text: (0, import_pg_core.text)("text").notNull(),
743
+ originAuthor: (0, import_pg_core.text)("origin_author").$type().notNull(),
744
+ originThreadId: (0, import_pg_core.text)("origin_thread_id"),
745
+ originRunId: (0, import_pg_core.text)("origin_run_id"),
746
+ originActorRef: (0, import_pg_core.text)("origin_actor_ref"),
747
+ pinned: (0, import_pg_core.boolean)("pinned").notNull().default(false),
748
+ createdAt: ts2("created_at").notNull(),
749
+ updatedAt: ts2("updated_at").notNull()
750
+ }, (table) => [
751
+ (0, import_pg_core.uniqueIndex)("agent_memory_scope_key_uq").on(table.scope, table.key)
752
+ ]);
753
+ var ragIngestionLog3 = (0, import_pg_core.pgTable)("rag_ingestion_log", {
754
+ documentId: (0, import_pg_core.text)("document_id").primaryKey(),
755
+ status: (0, import_pg_core.text)("status").$type().notNull(),
756
+ collection: (0, import_pg_core.text)("collection"),
757
+ ownerType: (0, import_pg_core.text)("owner_type"),
758
+ ownerId: (0, import_pg_core.text)("owner_id"),
759
+ source: (0, import_pg_core.text)("source"),
760
+ mimeType: (0, import_pg_core.text)("mime_type"),
761
+ size: (0, import_pg_core.bigint)("size", {
762
+ mode: "number"
763
+ }),
764
+ chunks: (0, import_pg_core.integer)("chunks"),
765
+ reason: (0, import_pg_core.text)("reason"),
766
+ error: (0, import_pg_core.text)("error"),
767
+ createdAt: ts2("created_at").notNull(),
768
+ updatedAt: ts2("updated_at").notNull()
769
+ }, (table) => [
770
+ (0, import_pg_core.index)("rag_ingestion_log_collection_idx").on(table.collection, table.updatedAt)
771
+ ]);
772
+ var agentConfirmToken3 = (0, import_pg_core.pgTable)("agent_confirm_token", {
773
+ hash: (0, import_pg_core.text)("hash").primaryKey(),
774
+ actorRef: (0, import_pg_core.text)("actor_ref").notNull(),
775
+ tool: (0, import_pg_core.text)("tool").notNull(),
776
+ expiresAt: (0, import_pg_core.bigint)("expires_at", {
777
+ mode: "number"
778
+ }).notNull(),
779
+ createdAt: (0, import_pg_core.bigint)("created_at", {
780
+ mode: "number"
781
+ }).notNull()
782
+ }, (table) => [
783
+ (0, import_pg_core.index)("agent_confirm_token_expires_idx").on(table.expiresAt)
784
+ ]);
785
+ var agentStreamFrame3 = (0, import_pg_core.pgTable)("agent_stream_frame", {
786
+ runId: (0, import_pg_core.text)("run_id").notNull(),
787
+ seq: (0, import_pg_core.integer)("seq").notNull(),
788
+ frame: (0, import_pg_core.text)("frame"),
789
+ error: (0, import_pg_core.text)("error"),
790
+ createdAt: (0, import_pg_core.bigint)("created_at", {
791
+ mode: "number"
792
+ }).notNull()
793
+ }, (table) => [
794
+ (0, import_pg_core.primaryKey)({
795
+ columns: [
796
+ table.runId,
797
+ table.seq
798
+ ]
799
+ })
800
+ ]);
801
+ var pgAgentSchema = {
802
+ agentThread: agentThread3,
803
+ agentMessage: agentMessage3,
804
+ agentQueuedMessage: agentQueuedMessage3,
805
+ agentToolCall: agentToolCall3,
806
+ agentTokenUsage: agentTokenUsage3,
807
+ agentModelPricing: agentModelPricing3,
808
+ agentRun: agentRun3,
809
+ agentMemory: agentMemory3,
810
+ ragIngestionLog: ragIngestionLog3,
811
+ agentConfirmToken: agentConfirmToken3,
812
+ agentStreamFrame: agentStreamFrame3
813
+ };
814
+
815
+ // src/dialect.ts
816
+ function agentDialectOf(db) {
817
+ if ((0, import_drizzle_orm.is)(db, import_pg_core2.PgDatabase)) return "postgres";
818
+ if ((0, import_drizzle_orm.is)(db, import_mysql_core2.MySqlDatabase)) return "mysql";
819
+ return "sqlite";
820
+ }
821
+ __name(agentDialectOf, "agentDialectOf");
822
+ function agentTablesFor(dialect) {
823
+ if (dialect === "postgres") return pgAgentSchema;
824
+ if (dialect === "mysql") return mysqlAgentSchema;
825
+ return agentSchema;
826
+ }
827
+ __name(agentTablesFor, "agentTablesFor");
828
+ function asBuilder(db) {
829
+ return db;
830
+ }
831
+ __name(asBuilder, "asBuilder");
832
+ async function affectedRows(dialect, statement, column) {
833
+ if (dialect !== "mysql") {
834
+ return (await statement.returning({
835
+ affected: column
836
+ })).length;
837
+ }
838
+ return mysqlAffectedRows(await statement);
839
+ }
840
+ __name(affectedRows, "affectedRows");
841
+ function mysqlAffectedRows(result) {
842
+ const header = Array.isArray(result) ? result[0] : result;
843
+ const counts = header;
844
+ const count3 = counts?.affectedRows ?? counts?.rowsAffected;
845
+ return typeof count3 === "number" ? count3 : 0;
846
+ }
847
+ __name(mysqlAffectedRows, "mysqlAffectedRows");
848
+ async function runSql(db, dialect, statement) {
849
+ if (dialect === "sqlite") {
850
+ await db.run(statement);
851
+ return;
616
852
  }
617
- ];
618
- async function ensureAgentSchema(db) {
619
- for (const statement of statements) {
620
- await db.run(import_drizzle_orm.sql.raw(statement));
853
+ if (dialect === "postgres") {
854
+ await db.execute(statement);
855
+ return;
856
+ }
857
+ await db.execute(statement);
858
+ }
859
+ __name(runSql, "runSql");
860
+ async function querySql(db, dialect, statement) {
861
+ if (dialect === "sqlite") {
862
+ return db.all(statement);
621
863
  }
622
- for (const { table, column, ddl } of additiveColumns) {
623
- const existing = await db.all(import_drizzle_orm.sql.raw(`PRAGMA table_info(${table})`));
624
- if (!existing.some((row) => row.name === column)) {
625
- await db.run(import_drizzle_orm.sql.raw(ddl));
864
+ const result = dialect === "postgres" ? await db.execute(statement) : await db.execute(statement);
865
+ if (dialect === "mysql") {
866
+ return Array.isArray(result) ? result[0] : [];
867
+ }
868
+ return Array.isArray(result) ? result : result.rows ?? [];
869
+ }
870
+ __name(querySql, "querySql");
871
+ function isUniqueViolation(error) {
872
+ for (let current = error; current !== null && typeof current === "object"; ) {
873
+ const { code, errno } = current;
874
+ if (code === "23505" || code === "ER_DUP_ENTRY" || errno === 1062 || code === "ER_LOCK_DEADLOCK" || errno === 1213 || typeof code === "string" && code.startsWith("SQLITE_CONSTRAINT")) {
875
+ return true;
626
876
  }
877
+ current = current.cause;
878
+ }
879
+ return false;
880
+ }
881
+ __name(isUniqueViolation, "isUniqueViolation");
882
+ function upsert(dialect, insert, target, set) {
883
+ if (dialect === "mysql") {
884
+ return insert.onDuplicateKeyUpdate({
885
+ set
886
+ });
887
+ }
888
+ return insert.onConflictDoUpdate({
889
+ target,
890
+ set
891
+ });
892
+ }
893
+ __name(upsert, "upsert");
894
+
895
+ // src/ensure-schema.ts
896
+ async function ensureAgentSchema(db) {
897
+ const dialect = agentDialectOf(db);
898
+ if (dialect === "postgres") {
899
+ await db.transaction(async (tx) => {
900
+ await tx.execute(import_drizzle_orm2.sql.raw(`select pg_advisory_xact_lock(hashtext('${LOCK_NAME}'))`));
901
+ await heal(tx, dialect);
902
+ });
903
+ return;
904
+ }
905
+ if (dialect === "mysql") {
906
+ await db.transaction(async (tx) => {
907
+ await tx.execute(import_drizzle_orm2.sql.raw(`select get_lock('${LOCK_NAME}', 30)`));
908
+ try {
909
+ await heal(tx, dialect);
910
+ } finally {
911
+ await tx.execute(import_drizzle_orm2.sql.raw(`select release_lock('${LOCK_NAME}')`));
912
+ }
913
+ });
914
+ return;
627
915
  }
916
+ await heal(db, dialect);
628
917
  }
629
918
  __name(ensureAgentSchema, "ensureAgentSchema");
919
+ var LOCK_NAME = "nestjs_agent_schema";
920
+ var MYSQL_TABLE_OPTIONS = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin";
921
+ function tableSpec(dialect, table) {
922
+ const config = dialect === "postgres" ? (0, import_pg_core3.getTableConfig)(table) : dialect === "mysql" ? (0, import_mysql_core3.getTableConfig)(table) : (0, import_sqlite_core2.getTableConfig)(table);
923
+ const columns = config.columns;
924
+ const compositeKey = config.primaryKeys[0]?.columns.map((column) => column.name);
925
+ return {
926
+ name: config.name,
927
+ columns,
928
+ primaryKey: compositeKey ?? columns.filter((column) => column.primary).map((c) => c.name),
929
+ foreignKeys: config.foreignKeys.map((foreignKey) => {
930
+ const reference = foreignKey.reference();
931
+ return {
932
+ columns: reference.columns.map((column) => column.name),
933
+ table: (0, import_drizzle_orm2.getTableName)(reference.foreignTable),
934
+ foreignColumns: reference.foreignColumns.map((column) => column.name),
935
+ ...foreignKey.onDelete !== void 0 ? {
936
+ onDelete: foreignKey.onDelete
937
+ } : {}
938
+ };
939
+ }),
940
+ indexes: config.indexes.map((index4) => ({
941
+ name: String(index4.config.name),
942
+ unique: index4.config.unique === true,
943
+ columns: index4.config.columns.map((column) => String(column.name))
944
+ }))
945
+ };
946
+ }
947
+ __name(tableSpec, "tableSpec");
948
+ function quote(dialect, identifier) {
949
+ return dialect === "mysql" ? `\`${identifier}\`` : `"${identifier}"`;
950
+ }
951
+ __name(quote, "quote");
952
+ function literal(dialect, value) {
953
+ if (typeof value === "boolean") {
954
+ return dialect === "sqlite" ? value ? "1" : "0" : value ? "true" : "false";
955
+ }
956
+ if (typeof value === "number") return String(value);
957
+ return `'${String(value).replaceAll("'", "''")}'`;
958
+ }
959
+ __name(literal, "literal");
960
+ function columnDefinition(dialect, column) {
961
+ const parts = [
962
+ quote(dialect, column.name),
963
+ column.getSQLType()
964
+ ];
965
+ if (column.notNull) parts.push("NOT NULL");
966
+ if (column.hasDefault && column.default !== void 0) {
967
+ parts.push(`DEFAULT ${literal(dialect, column.default)}`);
968
+ }
969
+ return parts.join(" ");
970
+ }
971
+ __name(columnDefinition, "columnDefinition");
972
+ function createTableSql(dialect, spec) {
973
+ const q = /* @__PURE__ */ __name((identifier) => quote(dialect, identifier), "q");
974
+ const lines = spec.columns.map((column) => columnDefinition(dialect, column));
975
+ lines.push(`PRIMARY KEY (${spec.primaryKey.map(q).join(", ")})`);
976
+ for (const foreignKey of spec.foreignKeys) {
977
+ lines.push(`FOREIGN KEY (${foreignKey.columns.map(q).join(", ")}) REFERENCES ${q(foreignKey.table)} (${foreignKey.foreignColumns.map(q).join(", ")})${foreignKey.onDelete !== void 0 ? ` ON DELETE ${foreignKey.onDelete.toUpperCase()}` : ""}`);
978
+ }
979
+ const options = dialect === "mysql" ? ` ${MYSQL_TABLE_OPTIONS}` : "";
980
+ return `CREATE TABLE IF NOT EXISTS ${q(spec.name)} (
981
+ ${lines.join(",\n ")}
982
+ )${options}`;
983
+ }
984
+ __name(createTableSql, "createTableSql");
985
+ function agentSchemaDdl(dialect) {
986
+ const statements = [];
987
+ for (const spec of specs(dialect)) {
988
+ statements.push(createTableSql(dialect, spec));
989
+ for (const index4 of spec.indexes) {
990
+ statements.push(createIndexSql(dialect, spec.name, index4));
991
+ }
992
+ }
993
+ return statements;
994
+ }
995
+ __name(agentSchemaDdl, "agentSchemaDdl");
996
+ function createIndexSql(dialect, table, index4) {
997
+ const q = /* @__PURE__ */ __name((identifier) => quote(dialect, identifier), "q");
998
+ const guard = dialect === "mysql" ? "" : "IF NOT EXISTS ";
999
+ return `CREATE ${index4.unique ? "UNIQUE " : ""}INDEX ${guard}${q(index4.name)} ON ${q(table)} (${index4.columns.map(q).join(", ")})`;
1000
+ }
1001
+ __name(createIndexSql, "createIndexSql");
1002
+ function specs(dialect) {
1003
+ const all = Object.values(agentTablesFor(dialect)).map((table) => tableSpec(dialect, table));
1004
+ const ordered = [];
1005
+ const placed = /* @__PURE__ */ new Set();
1006
+ while (ordered.length < all.length) {
1007
+ const ready = all.filter((spec) => !placed.has(spec.name) && spec.foreignKeys.every((key2) => key2.table === spec.name || placed.has(key2.table)));
1008
+ if (ready.length === 0) throw new Error("agent schema: circular foreign keys");
1009
+ for (const spec of ready) {
1010
+ ordered.push(spec);
1011
+ placed.add(spec.name);
1012
+ }
1013
+ }
1014
+ return ordered;
1015
+ }
1016
+ __name(specs, "specs");
1017
+ async function existingColumns(db, dialect, table) {
1018
+ const rows = dialect === "sqlite" ? await querySql(db, dialect, import_drizzle_orm2.sql.raw(`PRAGMA table_info("${table}")`)) : await querySql(db, dialect, import_drizzle_orm2.sql`select column_name as name from information_schema.columns where table_schema = ${import_drizzle_orm2.sql.raw(dialect === "mysql" ? "database()" : "current_schema()")} and table_name = ${table}`);
1019
+ return new Set(rows.map((row) => String(row.name)));
1020
+ }
1021
+ __name(existingColumns, "existingColumns");
1022
+ async function indexExists(db, dialect, table, index4) {
1023
+ let query;
1024
+ if (dialect === "sqlite") {
1025
+ query = import_drizzle_orm2.sql`select name from sqlite_master where type = 'index' and name = ${index4}`;
1026
+ } else if (dialect === "postgres") {
1027
+ query = import_drizzle_orm2.sql`select indexname as name from pg_indexes where schemaname = current_schema() and indexname = ${index4}`;
1028
+ } else {
1029
+ query = import_drizzle_orm2.sql`select index_name as name from information_schema.statistics where table_schema = database() and table_name = ${table} and index_name = ${index4}`;
1030
+ }
1031
+ return (await querySql(db, dialect, query)).length > 0;
1032
+ }
1033
+ __name(indexExists, "indexExists");
1034
+ async function heal(db, dialect) {
1035
+ for (const spec of specs(dialect)) {
1036
+ await runSql(db, dialect, import_drizzle_orm2.sql.raw(createTableSql(dialect, spec)));
1037
+ const present = await existingColumns(db, dialect, spec.name);
1038
+ for (const column of spec.columns) {
1039
+ if (!present.has(column.name)) {
1040
+ await runSql(db, dialect, import_drizzle_orm2.sql.raw(`ALTER TABLE ${quote(dialect, spec.name)} ADD COLUMN ${columnDefinition(dialect, column)}`));
1041
+ }
1042
+ }
1043
+ for (const index4 of spec.indexes) {
1044
+ if (!await indexExists(db, dialect, spec.name, index4.name)) {
1045
+ await runSql(db, dialect, import_drizzle_orm2.sql.raw(createIndexSql(dialect, spec.name, index4)));
1046
+ }
1047
+ }
1048
+ }
1049
+ }
1050
+ __name(heal, "heal");
630
1051
 
631
1052
  // src/drizzle-agent-store.ts
632
1053
  var import_nestjs_agent_core = require("@dudousxd/nestjs-agent-core");
633
- var import_drizzle_orm2 = require("drizzle-orm");
634
- var TURN_MESSAGE_COLUMNS = {
635
- id: agentMessage.id,
636
- role: agentMessage.role,
637
- content: agentMessage.content,
638
- agentName: agentMessage.agentName,
639
- toolCalls: agentMessage.toolCalls,
640
- toolResults: agentMessage.toolResults,
641
- attachments: agentMessage.attachments,
642
- createdAt: agentMessage.createdAt
643
- };
1054
+ var import_drizzle_orm3 = require("drizzle-orm");
1055
+ function turnMessageColumns(message) {
1056
+ return {
1057
+ id: message.id,
1058
+ role: message.role,
1059
+ content: message.content,
1060
+ agentName: message.agentName,
1061
+ toolCalls: message.toolCalls,
1062
+ toolResults: message.toolResults,
1063
+ attachments: message.attachments,
1064
+ createdAt: message.createdAt
1065
+ };
1066
+ }
1067
+ __name(turnMessageColumns, "turnMessageColumns");
644
1068
  var DrizzleAgentStore = class {
645
1069
  static {
646
1070
  __name(this, "DrizzleAgentStore");
647
1071
  }
648
1072
  db;
1073
+ dialect;
1074
+ t;
649
1075
  constructor(db) {
650
- this.db = db;
1076
+ this.dialect = agentDialectOf(db);
1077
+ this.t = agentTablesFor(this.dialect);
1078
+ this.db = asBuilder(db);
651
1079
  }
652
1080
  async createThread(input) {
653
1081
  const now = /* @__PURE__ */ new Date();
@@ -666,15 +1094,15 @@ var DrizzleAgentStore = class {
666
1094
  updatedAt: now,
667
1095
  deletedAt: null
668
1096
  };
669
- await this.db.insert(agentThread).values(thread);
1097
+ await this.db.insert(this.t.agentThread).values(thread);
670
1098
  return this.toSummary(thread);
671
1099
  }
672
1100
  async getThread(threadId) {
673
- const [thread] = await this.db.select().from(agentThread).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.isNull)(agentThread.deletedAt)));
1101
+ const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
674
1102
  if (thread === void 0) {
675
1103
  return null;
676
1104
  }
677
- const messages = await this.db.select().from(agentMessage).where((0, import_drizzle_orm2.eq)(agentMessage.threadId, threadId)).orderBy((0, import_drizzle_orm2.asc)(agentMessage.createdAt), (0, import_drizzle_orm2.asc)(agentMessage.id));
1105
+ const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
678
1106
  const last = messages[messages.length - 1];
679
1107
  const approvals = await this.approvalsFor(messages.map((message) => message.id));
680
1108
  return {
@@ -707,16 +1135,16 @@ var DrizzleAgentStore = class {
707
1135
  */
708
1136
  async loadThreadForTurn(query) {
709
1137
  const [thread] = await this.db.select({
710
- title: agentThread.title,
711
- defaultAgent: agentThread.defaultAgent
712
- }).from(agentThread).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, query.threadId), (0, import_drizzle_orm2.isNull)(agentThread.deletedAt)));
1138
+ title: this.t.agentThread.title,
1139
+ defaultAgent: this.t.agentThread.defaultAgent
1140
+ }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, query.threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
713
1141
  if (thread === void 0) {
714
1142
  return null;
715
1143
  }
716
1144
  const messages = await this.loadTurnWindow(query.threadId, query.messageLimit);
717
1145
  const [answered] = await this.db.select({
718
- id: agentMessage.id
719
- }).from(agentMessage).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentMessage.threadId, query.threadId), (0, import_drizzle_orm2.eq)(agentMessage.role, "assistant"))).limit(1);
1146
+ id: this.t.agentMessage.id
1147
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, query.threadId), (0, import_drizzle_orm3.eq)(this.t.agentMessage.role, "assistant"))).limit(1);
720
1148
  return {
721
1149
  title: thread.title,
722
1150
  defaultAgent: thread.defaultAgent,
@@ -732,30 +1160,30 @@ var DrizzleAgentStore = class {
732
1160
  if (limit !== void 0 && limit <= 0) {
733
1161
  return [];
734
1162
  }
735
- const window = this.db.select(TURN_MESSAGE_COLUMNS).from(agentMessage).where((0, import_drizzle_orm2.eq)(agentMessage.threadId, threadId)).orderBy((0, import_drizzle_orm2.desc)(agentMessage.createdAt), (0, import_drizzle_orm2.desc)(agentMessage.id));
1163
+ const window = this.db.select(turnMessageColumns(this.t.agentMessage)).from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrderNewestFirst());
736
1164
  const rows = limit === void 0 ? await window : await window.limit(limit);
737
1165
  return rows.reverse().map((row) => this.toStoredMessage(row));
738
1166
  }
739
1167
  async listThreads(actorRef, limit = 50) {
740
- const threads = await this.db.select().from(agentThread).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.actorRef, actorRef), (0, import_drizzle_orm2.eq)(agentThread.transient, false), (0, import_drizzle_orm2.isNull)(agentThread.deletedAt))).orderBy((0, import_drizzle_orm2.desc)(agentThread.updatedAt)).limit(limit);
1168
+ const threads = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.actorRef, actorRef), (0, import_drizzle_orm3.eq)(this.t.agentThread.transient, false), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt))).orderBy((0, import_drizzle_orm3.desc)(this.t.agentThread.updatedAt)).limit(limit);
741
1169
  const summaries = [];
742
1170
  for (const thread of threads) {
743
- const [last] = await this.db.select().from(agentMessage).where((0, import_drizzle_orm2.eq)(agentMessage.threadId, thread.id)).orderBy((0, import_drizzle_orm2.desc)(agentMessage.createdAt), (0, import_drizzle_orm2.desc)(agentMessage.id)).limit(1);
1171
+ const [last] = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, thread.id)).orderBy(...this.messageOrderNewestFirst()).limit(1);
744
1172
  summaries.push(this.toSummary(thread, last?.content));
745
1173
  }
746
1174
  return summaries;
747
1175
  }
748
1176
  async softDeleteThread(threadId) {
749
- await this.db.update(agentThread).set({
1177
+ await this.db.update(this.t.agentThread).set({
750
1178
  deletedAt: /* @__PURE__ */ new Date()
751
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1179
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
752
1180
  }
753
1181
  async forkThread(threadId, fromMessageId) {
754
- const [source] = await this.db.select().from(agentThread).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1182
+ const [source] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
755
1183
  if (source === void 0) {
756
1184
  throw new Error(`thread ${threadId} not found`);
757
1185
  }
758
- const messages = await this.db.select().from(agentMessage).where((0, import_drizzle_orm2.eq)(agentMessage.threadId, threadId)).orderBy((0, import_drizzle_orm2.asc)(agentMessage.createdAt), (0, import_drizzle_orm2.asc)(agentMessage.id));
1186
+ const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
759
1187
  const cutoff = messages.findIndex((message) => message.id === fromMessageId);
760
1188
  const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;
761
1189
  const now = /* @__PURE__ */ new Date();
@@ -775,10 +1203,12 @@ var DrizzleAgentStore = class {
775
1203
  updatedAt: now,
776
1204
  deletedAt: null
777
1205
  };
778
- await this.db.insert(agentThread).values(fork);
1206
+ await this.db.insert(this.t.agentThread).values(fork);
779
1207
  if (kept.length > 0) {
780
- await this.db.insert(agentMessage).values(kept.map((message) => ({
1208
+ await this.db.insert(this.t.agentMessage).values(kept.map((message, index4) => ({
781
1209
  id: crypto.randomUUID(),
1210
+ // Numbered afresh in the order just read, so the copy reads back in the original's order.
1211
+ seq: index4 + 1,
782
1212
  threadId: fork.id,
783
1213
  role: message.role,
784
1214
  content: message.content,
@@ -803,21 +1233,21 @@ var DrizzleAgentStore = class {
803
1233
  }
804
1234
  async ownerOfThread(threadId) {
805
1235
  const [thread] = await this.db.select({
806
- actorRef: agentThread.actorRef
807
- }).from(agentThread).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.isNull)(agentThread.deletedAt)));
1236
+ actorRef: this.t.agentThread.actorRef
1237
+ }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
808
1238
  return thread?.actorRef ?? null;
809
1239
  }
810
1240
  async ownerOfToolCall(toolCallId) {
811
1241
  const [row] = await this.db.select({
812
- actorRef: agentThread.actorRef
813
- }).from(agentToolCall).innerJoin(agentMessage, (0, import_drizzle_orm2.eq)(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, (0, import_drizzle_orm2.eq)(agentMessage.threadId, agentThread.id)).where((0, import_drizzle_orm2.eq)(agentToolCall.id, toolCallId));
1242
+ actorRef: this.t.agentThread.actorRef
1243
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm3.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
814
1244
  return row?.actorRef ?? null;
815
1245
  }
816
1246
  async runForToolCall(toolCallId) {
817
1247
  const [row] = await this.db.select({
818
- runId: agentToolCall.runId,
819
- activeStreamId: agentThread.activeStreamId
820
- }).from(agentToolCall).innerJoin(agentMessage, (0, import_drizzle_orm2.eq)(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, (0, import_drizzle_orm2.eq)(agentMessage.threadId, agentThread.id)).where((0, import_drizzle_orm2.eq)(agentToolCall.id, toolCallId));
1248
+ runId: this.t.agentToolCall.runId,
1249
+ activeStreamId: this.t.agentThread.activeStreamId
1250
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm3.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
821
1251
  return row?.runId ?? row?.activeStreamId ?? null;
822
1252
  }
823
1253
  /**
@@ -831,16 +1261,16 @@ var DrizzleAgentStore = class {
831
1261
  return byMessage;
832
1262
  }
833
1263
  const rows = await this.db.select({
834
- id: agentToolCall.id,
835
- messageId: agentToolCall.messageId,
836
- status: agentToolCall.status,
837
- approver: agentToolCall.approver,
838
- expiresAt: agentToolCall.expiresAt,
839
- remember: agentToolCall.remember,
840
- executedByRef: agentToolCall.executedByRef,
841
- decidedVia: agentToolCall.decidedVia,
842
- error: agentToolCall.error
843
- }).from(agentToolCall).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.inArray)(agentToolCall.messageId, messageIds), (0, import_drizzle_orm2.isNotNull)(agentToolCall.approver))).orderBy((0, import_drizzle_orm2.asc)(agentToolCall.createdAt), (0, import_drizzle_orm2.asc)(agentToolCall.id));
1264
+ id: this.t.agentToolCall.id,
1265
+ messageId: this.t.agentToolCall.messageId,
1266
+ status: this.t.agentToolCall.status,
1267
+ approver: this.t.agentToolCall.approver,
1268
+ expiresAt: this.t.agentToolCall.expiresAt,
1269
+ remember: this.t.agentToolCall.remember,
1270
+ executedByRef: this.t.agentToolCall.executedByRef,
1271
+ decidedVia: this.t.agentToolCall.decidedVia,
1272
+ error: this.t.agentToolCall.error
1273
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.inArray)(this.t.agentToolCall.messageId, messageIds), (0, import_drizzle_orm3.isNotNull)(this.t.agentToolCall.approver))).orderBy((0, import_drizzle_orm3.asc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm3.asc)(this.t.agentToolCall.id));
844
1274
  for (const row of rows) {
845
1275
  const approval = (0, import_nestjs_agent_core.toolCallApprovalFromRow)({
846
1276
  ...row,
@@ -858,22 +1288,22 @@ var DrizzleAgentStore = class {
858
1288
  /** Tools whose approval someone asked to remember in this thread. */
859
1289
  async rememberedApprovals(threadId) {
860
1290
  const rows = await this.db.selectDistinct({
861
- toolName: agentToolCall.toolName
862
- }).from(agentToolCall).innerJoin(agentMessage, (0, import_drizzle_orm2.eq)(agentToolCall.messageId, agentMessage.id)).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentMessage.threadId, threadId), (0, import_drizzle_orm2.eq)(agentToolCall.remember, true)));
1291
+ toolName: this.t.agentToolCall.toolName
1292
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm3.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId), (0, import_drizzle_orm3.eq)(this.t.agentToolCall.remember, true)));
863
1293
  return rows.map((row) => row.toolName);
864
1294
  }
865
1295
  async toolCallInput(toolCallId) {
866
1296
  const [row] = await this.db.select({
867
- input: agentToolCall.input
868
- }).from(agentToolCall).where((0, import_drizzle_orm2.eq)(agentToolCall.id, toolCallId));
1297
+ input: this.t.agentToolCall.input
1298
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
869
1299
  return row?.input ?? null;
870
1300
  }
871
1301
  async toolCallApproval(toolCallId) {
872
1302
  const [row] = await this.db.select({
873
- status: agentToolCall.status,
874
- approver: agentToolCall.approver,
875
- expiresAt: agentToolCall.expiresAt
876
- }).from(agentToolCall).where((0, import_drizzle_orm2.eq)(agentToolCall.id, toolCallId));
1303
+ status: this.t.agentToolCall.status,
1304
+ approver: this.t.agentToolCall.approver,
1305
+ expiresAt: this.t.agentToolCall.expiresAt
1306
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
877
1307
  if (row === void 0) {
878
1308
  return null;
879
1309
  }
@@ -885,27 +1315,67 @@ var DrizzleAgentStore = class {
885
1315
  }
886
1316
  async ownerOfActiveStream(runId) {
887
1317
  const [thread] = await this.db.select({
888
- actorRef: agentThread.actorRef
889
- }).from(agentThread).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.activeStreamId, runId), (0, import_drizzle_orm2.isNull)(agentThread.deletedAt)));
1318
+ actorRef: this.t.agentThread.actorRef
1319
+ }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, runId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
890
1320
  return thread?.actorRef ?? null;
891
1321
  }
892
1322
  async setTitle(threadId, title) {
893
- await this.db.update(agentThread).set({
1323
+ await this.db.update(this.t.agentThread).set({
894
1324
  title,
895
1325
  updatedAt: /* @__PURE__ */ new Date()
896
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1326
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
897
1327
  }
898
1328
  async promoteThread(threadId) {
899
- await this.db.update(agentThread).set({
1329
+ await this.db.update(this.t.agentThread).set({
900
1330
  transient: false,
901
1331
  updatedAt: /* @__PURE__ */ new Date()
902
- }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.eq)(agentThread.transient, true)));
1332
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.eq)(this.t.agentThread.transient, true)));
1333
+ }
1334
+ /** Who holds the thread's stream right now, deleted or not. */
1335
+ async activeHolder(threadId) {
1336
+ const [thread] = await this.db.select({
1337
+ activeStreamId: this.t.agentThread.activeStreamId
1338
+ }).from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
1339
+ return thread?.activeStreamId ?? null;
1340
+ }
1341
+ /**
1342
+ * A thread's messages in the order they were appended: by `seq`, which append assigns. A row from
1343
+ * before `seq` existed has none and counts as 0 — first, since every such row is older than every
1344
+ * numbered one — and those order among themselves by `created_at`, then `id`, as they always did.
1345
+ * `coalesce` rather than `nulls first`, which MySQL cannot spell and Postgres defaults the other way.
1346
+ */
1347
+ messageOrder() {
1348
+ const message = this.t.agentMessage;
1349
+ return [
1350
+ (0, import_drizzle_orm3.asc)(import_drizzle_orm3.sql`coalesce(${message.seq}, 0)`),
1351
+ (0, import_drizzle_orm3.asc)(message.createdAt),
1352
+ (0, import_drizzle_orm3.asc)(message.id)
1353
+ ];
1354
+ }
1355
+ /** {@link messageOrder}, newest first. */
1356
+ messageOrderNewestFirst() {
1357
+ const message = this.t.agentMessage;
1358
+ return [
1359
+ (0, import_drizzle_orm3.desc)(import_drizzle_orm3.sql`coalesce(${message.seq}, 0)`),
1360
+ (0, import_drizzle_orm3.desc)(message.createdAt),
1361
+ (0, import_drizzle_orm3.desc)(message.id)
1362
+ ];
1363
+ }
1364
+ /**
1365
+ * The next `seq` in a thread: one past its highest. Two appends racing on ONE thread can draw the
1366
+ * same number — the turn loop never does that, and the tie then falls back to `created_at`, `id`.
1367
+ */
1368
+ async nextMessageSeq(threadId) {
1369
+ const [row] = await this.db.select({
1370
+ last: (0, import_drizzle_orm3.max)(this.t.agentMessage.seq)
1371
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId));
1372
+ return Number(row?.last ?? 0) + 1;
903
1373
  }
904
1374
  /** The run streaming the thread, or `null` — a projection of the one column. */
905
1375
  async activeRunForThread(threadId) {
906
1376
  const [thread] = await this.db.select({
907
- activeStreamId: agentThread.activeStreamId
908
- }).from(agentThread).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.isNull)(agentThread.deletedAt)));
1377
+ activeStreamId: this.t.agentThread.activeStreamId
1378
+ }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
909
1379
  return thread?.activeStreamId ?? null;
910
1380
  }
911
1381
  /**
@@ -914,33 +1384,32 @@ var DrizzleAgentStore = class {
914
1384
  */
915
1385
  async claimActiveStream(threadId, runId, options = {}) {
916
1386
  const holders = [
917
- (0, import_drizzle_orm2.isNull)(agentThread.activeStreamId),
918
- (0, import_drizzle_orm2.eq)(agentThread.activeStreamId, runId),
1387
+ (0, import_drizzle_orm3.isNull)(this.t.agentThread.activeStreamId),
1388
+ (0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, runId),
919
1389
  ...options.replacing !== void 0 ? [
920
- (0, import_drizzle_orm2.eq)(agentThread.activeStreamId, options.replacing)
1390
+ (0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, options.replacing)
921
1391
  ] : []
922
1392
  ];
923
- const claimed = await this.db.update(agentThread).set({
1393
+ const claimed = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
924
1394
  activeStreamId: runId
925
- }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.or)(...holders))).returning({
926
- id: agentThread.id
927
- });
928
- return claimed.length > 0;
1395
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.or)(...holders))), this.t.agentThread.id);
1396
+ if (claimed > 0) {
1397
+ return true;
1398
+ }
1399
+ return await this.activeHolder(threadId) === runId;
929
1400
  }
930
1401
  async releaseActiveStream(threadId, runId) {
931
- const released = await this.db.update(agentThread).set({
1402
+ const released = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
932
1403
  activeStreamId: null
933
- }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.eq)(agentThread.activeStreamId, runId))).returning({
934
- id: agentThread.id
935
- });
936
- return released.length > 0;
1404
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, runId))), this.t.agentThread.id);
1405
+ return released > 0;
937
1406
  }
938
1407
  async enqueueMessage(input) {
939
1408
  const now = /* @__PURE__ */ new Date();
940
1409
  const [edge] = await this.db.select({
941
- first: (0, import_drizzle_orm2.min)(agentQueuedMessage.position),
942
- last: (0, import_drizzle_orm2.max)(agentQueuedMessage.position)
943
- }).from(agentQueuedMessage).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.threadId, input.threadId));
1410
+ first: (0, import_drizzle_orm3.min)(this.t.agentQueuedMessage.position),
1411
+ last: (0, import_drizzle_orm3.max)(this.t.agentQueuedMessage.position)
1412
+ }).from(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.threadId, input.threadId));
944
1413
  const position = input.at === "head" ? (edge?.first ?? 1) - 1 : (edge?.last ?? -1) + 1;
945
1414
  const row = {
946
1415
  id: crypto.randomUUID(),
@@ -957,15 +1426,15 @@ var DrizzleAgentStore = class {
957
1426
  createdAt: now,
958
1427
  updatedAt: now
959
1428
  };
960
- await this.db.insert(agentQueuedMessage).values(row);
1429
+ await this.db.insert(this.t.agentQueuedMessage).values(row);
961
1430
  return toQueuedMessage(row);
962
1431
  }
963
1432
  async listQueue(threadId) {
964
- const rows = await this.db.select().from(agentQueuedMessage).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.threadId, threadId)).orderBy((0, import_drizzle_orm2.asc)(agentQueuedMessage.position), (0, import_drizzle_orm2.asc)(agentQueuedMessage.createdAt));
1433
+ const rows = await this.db.select().from(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.threadId, threadId)).orderBy((0, import_drizzle_orm3.asc)(this.t.agentQueuedMessage.position), (0, import_drizzle_orm3.asc)(this.t.agentQueuedMessage.createdAt));
965
1434
  return rows.map(toQueuedMessage);
966
1435
  }
967
1436
  async getQueuedMessage(id) {
968
- const [row] = await this.db.select().from(agentQueuedMessage).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.id, id));
1437
+ const [row] = await this.db.select().from(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, id));
969
1438
  return row === void 0 ? null : toQueuedMessage(row);
970
1439
  }
971
1440
  async updateQueuedMessage(id, patch) {
@@ -981,52 +1450,47 @@ var DrizzleAgentStore = class {
981
1450
  if (patch.interrupt !== void 0) {
982
1451
  updates.interrupt = patch.interrupt;
983
1452
  }
984
- await this.db.update(agentQueuedMessage).set(updates).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.id, id));
1453
+ await this.db.update(this.t.agentQueuedMessage).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, id));
985
1454
  return this.getQueuedMessage(id);
986
1455
  }
987
1456
  /** Rewrites the thread's positions as 0..n-1 in the new order — a queue is a handful of rows. */
988
- async moveQueuedMessage(id, index2) {
1457
+ async moveQueuedMessage(id, index4) {
989
1458
  const moving = await this.getQueuedMessage(id);
990
1459
  if (moving === null) {
991
1460
  return false;
992
1461
  }
993
1462
  const order = (await this.listQueue(moving.threadId)).filter((message) => message.id !== id);
994
- const target = Math.max(0, Math.min(order.length, Math.trunc(index2)));
1463
+ const target = Math.max(0, Math.min(order.length, Math.trunc(index4)));
995
1464
  order.splice(target, 0, moving);
996
1465
  for (const [position, message] of order.entries()) {
997
- await this.db.update(agentQueuedMessage).set({
1466
+ await this.db.update(this.t.agentQueuedMessage).set({
998
1467
  position
999
- }).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.id, message.id));
1468
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, message.id));
1000
1469
  }
1001
1470
  return true;
1002
1471
  }
1003
1472
  async removeQueuedMessage(id) {
1004
- const removed = await this.db.delete(agentQueuedMessage).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.id, id)).returning({
1005
- id: agentQueuedMessage.id
1006
- });
1007
- return removed.length > 0;
1473
+ const removed = await affectedRows(this.dialect, this.db.delete(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, id)), this.t.agentQueuedMessage.id);
1474
+ return removed > 0;
1008
1475
  }
1009
1476
  async clearQueue(threadId) {
1010
- const removed = await this.db.delete(agentQueuedMessage).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.threadId, threadId)).returning({
1011
- id: agentQueuedMessage.id
1012
- });
1013
- return removed.length;
1477
+ return affectedRows(this.dialect, this.db.delete(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.threadId, threadId)), this.t.agentQueuedMessage.id);
1014
1478
  }
1015
1479
  async queuePause(threadId) {
1016
1480
  const [thread] = await this.db.select({
1017
- queuePause: agentThread.queuePause
1018
- }).from(agentThread).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1481
+ queuePause: this.t.agentThread.queuePause
1482
+ }).from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
1019
1483
  return thread?.queuePause ?? null;
1020
1484
  }
1021
1485
  async setQueuePause(threadId, pause) {
1022
- await this.db.update(agentThread).set({
1486
+ await this.db.update(this.t.agentThread).set({
1023
1487
  queuePause: pause
1024
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1488
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
1025
1489
  }
1026
1490
  async setActiveStream(threadId, runId) {
1027
- await this.db.update(agentThread).set({
1491
+ await this.db.update(this.t.agentThread).set({
1028
1492
  activeStreamId: runId
1029
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1493
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
1030
1494
  }
1031
1495
  /**
1032
1496
  * Patch a thread's `title` and/or `defaultAgent`. Each field is only touched when PRESENT in
@@ -1052,7 +1516,7 @@ var DrizzleAgentStore = class {
1052
1516
  return;
1053
1517
  }
1054
1518
  updates.updatedAt = /* @__PURE__ */ new Date();
1055
- await this.db.update(agentThread).set(updates).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1519
+ await this.db.update(this.t.agentThread).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
1056
1520
  }
1057
1521
  /**
1058
1522
  * The thread's default agent, projected — the caller wants one nullable scalar to decide which
@@ -1062,21 +1526,21 @@ var DrizzleAgentStore = class {
1062
1526
  /** The thread's pinned model, projected like {@link defaultAgentForThread}. */
1063
1527
  async modelForThread(threadId) {
1064
1528
  const [thread] = await this.db.select({
1065
- model: agentThread.model
1066
- }).from(agentThread).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.isNull)(agentThread.deletedAt)));
1529
+ model: this.t.agentThread.model
1530
+ }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
1067
1531
  return thread?.model ?? null;
1068
1532
  }
1069
1533
  /** The thread's pinned persona, projected like {@link defaultAgentForThread}. */
1070
1534
  async personaForThread(threadId) {
1071
1535
  const [thread] = await this.db.select({
1072
- persona: agentThread.persona
1073
- }).from(agentThread).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.isNull)(agentThread.deletedAt)));
1536
+ persona: this.t.agentThread.persona
1537
+ }).from(agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
1074
1538
  return thread?.persona ?? null;
1075
1539
  }
1076
1540
  async defaultAgentForThread(threadId) {
1077
1541
  const [thread] = await this.db.select({
1078
- defaultAgent: agentThread.defaultAgent
1079
- }).from(agentThread).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.isNull)(agentThread.deletedAt)));
1542
+ defaultAgent: this.t.agentThread.defaultAgent
1543
+ }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
1080
1544
  return thread?.defaultAgent ?? null;
1081
1545
  }
1082
1546
  /**
@@ -1101,7 +1565,7 @@ var DrizzleAgentStore = class {
1101
1565
  promptHash: run.promptHash ?? null,
1102
1566
  parentRunId: run.parentRunId ?? null
1103
1567
  };
1104
- await this.db.insert(agentRun).values(runRow);
1568
+ await this.db.insert(this.t.agentRun).values(runRow);
1105
1569
  }
1106
1570
  /** Settle a run's outcome. A no-op when the run is unknown (mirrors `setTitle`/`updateThread`). */
1107
1571
  async recordRunEnd(end) {
@@ -1118,16 +1582,16 @@ var DrizzleAgentStore = class {
1118
1582
  if (end.errorMessage !== void 0) {
1119
1583
  updates.errorMessage = end.errorMessage;
1120
1584
  }
1121
- await this.db.update(agentRun).set(updates).where((0, import_drizzle_orm2.eq)(agentRun.id, end.runId));
1585
+ await this.db.update(this.t.agentRun).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentRun.id, end.runId));
1122
1586
  }
1123
1587
  /** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */
1124
1588
  async bumpRunRetries(runId) {
1125
- await this.db.update(agentRun).set({
1126
- retries: import_drizzle_orm2.sql`${agentRun.retries} + 1`
1127
- }).where((0, import_drizzle_orm2.eq)(agentRun.id, runId));
1589
+ await this.db.update(this.t.agentRun).set({
1590
+ retries: import_drizzle_orm3.sql`${this.t.agentRun.retries} + 1`
1591
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentRun.id, runId));
1128
1592
  }
1129
1593
  async appendMessage(input) {
1130
- const [thread] = await this.db.select().from(agentThread).where((0, import_drizzle_orm2.eq)(agentThread.id, input.threadId));
1594
+ const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, input.threadId));
1131
1595
  if (thread === void 0) {
1132
1596
  throw new Error(`thread ${input.threadId} not found`);
1133
1597
  }
@@ -1149,47 +1613,48 @@ var DrizzleAgentStore = class {
1149
1613
  reasoningMs: input.reasoningMs ?? null,
1150
1614
  ui: input.ui ?? null,
1151
1615
  feedback: null,
1616
+ seq: await this.nextMessageSeq(input.threadId),
1152
1617
  createdAt: now
1153
1618
  };
1154
- await this.db.insert(agentMessage).values(message);
1155
- await this.db.update(agentThread).set({
1619
+ await this.db.insert(this.t.agentMessage).values(message);
1620
+ await this.db.update(this.t.agentThread).set({
1156
1621
  updatedAt: now
1157
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, input.threadId));
1622
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, input.threadId));
1158
1623
  return this.toStoredMessage(message);
1159
1624
  }
1160
1625
  async setMessageToolResults(messageId, results) {
1161
- await this.db.update(agentMessage).set({
1626
+ await this.db.update(this.t.agentMessage).set({
1162
1627
  toolResults: results
1163
- }).where((0, import_drizzle_orm2.eq)(agentMessage.id, messageId));
1628
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
1164
1629
  }
1165
1630
  async setMessageUi(messageId, ui) {
1166
- await this.db.update(agentMessage).set({
1631
+ await this.db.update(this.t.agentMessage).set({
1167
1632
  ui: ui.length > 0 ? ui : null
1168
- }).where((0, import_drizzle_orm2.eq)(agentMessage.id, messageId));
1633
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
1169
1634
  }
1170
1635
  async threadOfMessage(messageId) {
1171
1636
  const [row] = await this.db.select({
1172
- threadId: agentMessage.threadId
1173
- }).from(agentMessage).where((0, import_drizzle_orm2.eq)(agentMessage.id, messageId)).limit(1);
1637
+ threadId: this.t.agentMessage.threadId
1638
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId)).limit(1);
1174
1639
  return row?.threadId ?? null;
1175
1640
  }
1176
1641
  async setMessageFeedback(messageId, feedback) {
1177
- await this.db.update(agentMessage).set({
1642
+ await this.db.update(this.t.agentMessage).set({
1178
1643
  feedback
1179
- }).where((0, import_drizzle_orm2.eq)(agentMessage.id, messageId));
1644
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
1180
1645
  }
1181
1646
  async truncateFrom(threadId, messageId) {
1182
- const messages = await this.db.select().from(agentMessage).where((0, import_drizzle_orm2.eq)(agentMessage.threadId, threadId)).orderBy((0, import_drizzle_orm2.asc)(agentMessage.createdAt), (0, import_drizzle_orm2.asc)(agentMessage.id));
1647
+ const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
1183
1648
  const cutoff = messages.findIndex((message) => message.id === messageId);
1184
1649
  if (cutoff < 0) {
1185
1650
  return;
1186
1651
  }
1187
1652
  const doomedIds = messages.slice(cutoff).map((message) => message.id);
1188
- await this.db.delete(agentToolCall).where((0, import_drizzle_orm2.inArray)(agentToolCall.messageId, doomedIds));
1189
- await this.db.delete(agentMessage).where((0, import_drizzle_orm2.inArray)(agentMessage.id, doomedIds));
1653
+ await this.db.delete(this.t.agentToolCall).where((0, import_drizzle_orm3.inArray)(this.t.agentToolCall.messageId, doomedIds));
1654
+ await this.db.delete(this.t.agentMessage).where((0, import_drizzle_orm3.inArray)(this.t.agentMessage.id, doomedIds));
1190
1655
  }
1191
1656
  async recordToolCall(input) {
1192
- await this.db.insert(agentToolCall).values({
1657
+ await this.db.insert(this.t.agentToolCall).values({
1193
1658
  id: input.toolCallId,
1194
1659
  messageId: input.messageId,
1195
1660
  toolName: input.toolName,
@@ -1234,18 +1699,18 @@ var DrizzleAgentStore = class {
1234
1699
  if (input.status === "executed" || input.status === "auto_executed") {
1235
1700
  updates.executedAt = /* @__PURE__ */ new Date();
1236
1701
  }
1237
- await this.db.update(agentToolCall).set(updates).where((0, import_drizzle_orm2.eq)(agentToolCall.id, input.toolCallId));
1702
+ await this.db.update(this.t.agentToolCall).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, input.toolCallId));
1238
1703
  }
1239
1704
  async toolCallOutcomes(toolCallIds) {
1240
1705
  if (toolCallIds.length === 0) {
1241
1706
  return [];
1242
1707
  }
1243
1708
  const rows = await this.db.select({
1244
- id: agentToolCall.id,
1245
- status: agentToolCall.status,
1246
- output: agentToolCall.output,
1247
- error: agentToolCall.error
1248
- }).from(agentToolCall).where((0, import_drizzle_orm2.inArray)(agentToolCall.id, [
1709
+ id: this.t.agentToolCall.id,
1710
+ status: this.t.agentToolCall.status,
1711
+ output: this.t.agentToolCall.output,
1712
+ error: this.t.agentToolCall.error
1713
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.inArray)(this.t.agentToolCall.id, [
1249
1714
  ...toolCallIds
1250
1715
  ]));
1251
1716
  return rows.map((row) => ({
@@ -1260,14 +1725,14 @@ var DrizzleAgentStore = class {
1260
1725
  }));
1261
1726
  }
1262
1727
  async failUnsettledToolCalls(runId, error) {
1263
- const pending = (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentToolCall.runId, runId), (0, import_drizzle_orm2.eq)(agentToolCall.status, "pending_approval"));
1728
+ const pending = (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentToolCall.runId, runId), (0, import_drizzle_orm3.eq)(this.t.agentToolCall.status, "pending_approval"));
1264
1729
  const rows = await this.db.select({
1265
- id: agentToolCall.id
1266
- }).from(agentToolCall).where(pending);
1730
+ id: this.t.agentToolCall.id
1731
+ }).from(this.t.agentToolCall).where(pending);
1267
1732
  if (rows.length === 0) {
1268
1733
  return 0;
1269
1734
  }
1270
- await this.db.update(agentToolCall).set({
1735
+ await this.db.update(this.t.agentToolCall).set({
1271
1736
  status: "failed",
1272
1737
  error
1273
1738
  }).where(pending);
@@ -1292,11 +1757,11 @@ var DrizzleAgentStore = class {
1292
1757
  return [];
1293
1758
  }
1294
1759
  const rows = await this.db.select({
1295
- attachments: agentMessage.attachments
1296
- }).from(agentMessage).innerJoin(agentThread, (0, import_drizzle_orm2.eq)(agentMessage.threadId, agentThread.id)).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.actorRef, actorRef), (0, import_drizzle_orm2.isNotNull)(agentMessage.attachments)));
1760
+ attachments: this.t.agentMessage.attachments
1761
+ }).from(this.t.agentMessage).innerJoin(this.t.agentThread, (0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.actorRef, actorRef), (0, import_drizzle_orm3.isNotNull)(this.t.agentMessage.attachments)));
1297
1762
  const queued = await this.db.select({
1298
- attachments: agentQueuedMessage.attachments
1299
- }).from(agentQueuedMessage).innerJoin(agentThread, (0, import_drizzle_orm2.eq)(agentQueuedMessage.threadId, agentThread.id)).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.actorRef, actorRef), (0, import_drizzle_orm2.isNotNull)(agentQueuedMessage.attachments)));
1763
+ attachments: this.t.agentQueuedMessage.attachments
1764
+ }).from(this.t.agentQueuedMessage).innerJoin(this.t.agentThread, (0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.actorRef, actorRef), (0, import_drizzle_orm3.isNotNull)(this.t.agentQueuedMessage.attachments)));
1300
1765
  const wanted = new Set(mediaIds);
1301
1766
  const found = /* @__PURE__ */ new Set();
1302
1767
  for (const row of [
@@ -1314,7 +1779,7 @@ var DrizzleAgentStore = class {
1314
1779
  ].filter((mediaId) => found.has(mediaId));
1315
1780
  }
1316
1781
  async recordUsage(input) {
1317
- await this.db.insert(agentTokenUsage).values({
1782
+ await this.db.insert(this.t.agentTokenUsage).values({
1318
1783
  id: crypto.randomUUID(),
1319
1784
  threadId: input.threadId,
1320
1785
  actorRef: input.actorRef,
@@ -1335,7 +1800,7 @@ var DrizzleAgentStore = class {
1335
1800
  async usageBetween(actorRef, fromDay, toDay) {
1336
1801
  const start = /* @__PURE__ */ new Date(`${fromDay}T00:00:00.000Z`);
1337
1802
  const end = /* @__PURE__ */ new Date(`${toDay}T23:59:59.999Z`);
1338
- const rows = await this.db.select().from(agentTokenUsage).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentTokenUsage.actorRef, actorRef), (0, import_drizzle_orm2.gte)(agentTokenUsage.createdAt, start), (0, import_drizzle_orm2.lte)(agentTokenUsage.createdAt, end)));
1803
+ const rows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentTokenUsage.actorRef, actorRef), (0, import_drizzle_orm3.gte)(this.t.agentTokenUsage.createdAt, start), (0, import_drizzle_orm3.lte)(this.t.agentTokenUsage.createdAt, end)));
1339
1804
  const usedTokens = rows.reduce((sum2, row) => sum2 + row.inputTokens + row.outputTokens, 0);
1340
1805
  const costUsd = rows.reduce((sum2, row) => sum2 + (row.costUsd ?? 0), 0);
1341
1806
  return {
@@ -1437,7 +1902,7 @@ __name(toQueuedMessage, "toQueuedMessage");
1437
1902
 
1438
1903
  // src/drizzle-governance-queries.ts
1439
1904
  var import_nestjs_agent_core2 = require("@dudousxd/nestjs-agent-core");
1440
- var import_drizzle_orm3 = require("drizzle-orm");
1905
+ var import_drizzle_orm4 = require("drizzle-orm");
1441
1906
  var UNCLASSIFIED_ERROR_CODE = "unknown";
1442
1907
  var DEFAULT_AGENT_BUCKET = "(default)";
1443
1908
  var TOOL_CALL_STATUSES = [
@@ -1550,11 +2015,15 @@ var DrizzleGovernanceQueries = class {
1550
2015
  static {
1551
2016
  __name(this, "DrizzleGovernanceQueries");
1552
2017
  }
1553
- db;
1554
2018
  pricingStore;
2019
+ db;
2020
+ dialect;
2021
+ t;
1555
2022
  constructor(db, pricingStore) {
1556
- this.db = db;
1557
2023
  this.pricingStore = pricingStore;
2024
+ this.dialect = agentDialectOf(db);
2025
+ this.t = agentTablesFor(this.dialect);
2026
+ this.db = asBuilder(db);
1558
2027
  }
1559
2028
  async loadPricing() {
1560
2029
  const prices = await this.pricingStore.listCurrentPrices();
@@ -1571,7 +2040,7 @@ var DrizzleGovernanceQueries = class {
1571
2040
  }
1572
2041
  async usageInRange(range) {
1573
2042
  const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
1574
- const rows = await this.db.select().from(agentTokenUsage).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.gte)(agentTokenUsage.createdAt, start), (0, import_drizzle_orm3.lte)(agentTokenUsage.createdAt, end)));
2043
+ const rows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.gte)(this.t.agentTokenUsage.createdAt, start), (0, import_drizzle_orm4.lte)(this.t.agentTokenUsage.createdAt, end)));
1575
2044
  return rows.map(toUsageInput);
1576
2045
  }
1577
2046
  async spendByModel(range) {
@@ -1596,7 +2065,7 @@ var DrizzleGovernanceQueries = class {
1596
2065
  if (threadIds.length === 0) {
1597
2066
  return [];
1598
2067
  }
1599
- const threads = await this.db.select().from(agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.inArray)(agentThread.id, threadIds), (0, import_drizzle_orm3.isNull)(agentThread.deletedAt)));
2068
+ const threads = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.inArray)(this.t.agentThread.id, threadIds), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
1600
2069
  const threadsById = new Map(threads.map((thread) => [
1601
2070
  thread.id,
1602
2071
  {
@@ -1615,14 +2084,14 @@ var DrizzleGovernanceQueries = class {
1615
2084
  }
1616
2085
  async recentToolCalls(limit) {
1617
2086
  const rows = await this.db.select({
1618
- toolCallId: agentToolCall.id,
1619
- toolName: agentToolCall.toolName,
1620
- toolType: agentToolCall.toolType,
1621
- status: agentToolCall.status,
1622
- threadId: agentMessage.threadId,
1623
- createdAt: agentToolCall.createdAt,
1624
- runId: agentToolCall.runId
1625
- }).from(agentToolCall).innerJoin(agentMessage, (0, import_drizzle_orm3.eq)(agentToolCall.messageId, agentMessage.id)).orderBy((0, import_drizzle_orm3.desc)(agentToolCall.createdAt), (0, import_drizzle_orm3.desc)(agentToolCall.id)).limit(limit);
2087
+ toolCallId: this.t.agentToolCall.id,
2088
+ toolName: this.t.agentToolCall.toolName,
2089
+ toolType: this.t.agentToolCall.toolType,
2090
+ status: this.t.agentToolCall.status,
2091
+ threadId: this.t.agentMessage.threadId,
2092
+ createdAt: this.t.agentToolCall.createdAt,
2093
+ runId: this.t.agentToolCall.runId
2094
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).orderBy((0, import_drizzle_orm4.desc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm4.desc)(this.t.agentToolCall.id)).limit(limit);
1626
2095
  return rows.map((row) => ({
1627
2096
  toolCallId: row.toolCallId,
1628
2097
  toolName: row.toolName,
@@ -1650,9 +2119,9 @@ var DrizzleGovernanceQueries = class {
1650
2119
  return rollups;
1651
2120
  }
1652
2121
  const messageCounts = await this.db.select({
1653
- threadId: agentMessage.threadId,
1654
- value: (0, import_drizzle_orm3.count)()
1655
- }).from(agentMessage).where((0, import_drizzle_orm3.inArray)(agentMessage.threadId, threadIds)).groupBy(agentMessage.threadId);
2122
+ threadId: this.t.agentMessage.threadId,
2123
+ value: (0, import_drizzle_orm4.count)()
2124
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm4.inArray)(this.t.agentMessage.threadId, threadIds)).groupBy(this.t.agentMessage.threadId);
1656
2125
  for (const row of messageCounts) {
1657
2126
  const bucket = rollups.get(row.threadId);
1658
2127
  if (bucket !== void 0) {
@@ -1660,10 +2129,10 @@ var DrizzleGovernanceQueries = class {
1660
2129
  }
1661
2130
  }
1662
2131
  const usageTotals = await this.db.select({
1663
- threadId: agentTokenUsage.threadId,
1664
- inputTokens: (0, import_drizzle_orm3.sum)(agentTokenUsage.inputTokens),
1665
- outputTokens: (0, import_drizzle_orm3.sum)(agentTokenUsage.outputTokens)
1666
- }).from(agentTokenUsage).where((0, import_drizzle_orm3.inArray)(agentTokenUsage.threadId, threadIds)).groupBy(agentTokenUsage.threadId);
2132
+ threadId: this.t.agentTokenUsage.threadId,
2133
+ inputTokens: (0, import_drizzle_orm4.sum)(this.t.agentTokenUsage.inputTokens),
2134
+ outputTokens: (0, import_drizzle_orm4.sum)(this.t.agentTokenUsage.outputTokens)
2135
+ }).from(this.t.agentTokenUsage).where((0, import_drizzle_orm4.inArray)(this.t.agentTokenUsage.threadId, threadIds)).groupBy(this.t.agentTokenUsage.threadId);
1667
2136
  for (const row of usageTotals) {
1668
2137
  const bucket = rollups.get(row.threadId);
1669
2138
  if (bucket !== void 0) {
@@ -1688,12 +2157,12 @@ var DrizzleGovernanceQueries = class {
1688
2157
  });
1689
2158
  }
1690
2159
  async recentThreads(limit) {
1691
- const threads = await this.db.select().from(agentThread).where((0, import_drizzle_orm3.isNull)(agentThread.deletedAt)).orderBy((0, import_drizzle_orm3.desc)(agentThread.updatedAt), (0, import_drizzle_orm3.desc)(agentThread.id)).limit(limit);
2160
+ const threads = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)).orderBy((0, import_drizzle_orm4.desc)(this.t.agentThread.updatedAt), (0, import_drizzle_orm4.desc)(this.t.agentThread.id)).limit(limit);
1692
2161
  return this.toThreadActivityRows(threads);
1693
2162
  }
1694
2163
  async runsInRange(range) {
1695
2164
  const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
1696
- return this.db.select().from(agentRun).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.gte)(agentRun.startedAt, start), (0, import_drizzle_orm3.lte)(agentRun.startedAt, end)));
2165
+ return this.db.select().from(this.t.agentRun).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.gte)(this.t.agentRun.startedAt, start), (0, import_drizzle_orm4.lte)(this.t.agentRun.startedAt, end)));
1697
2166
  }
1698
2167
  async runMetrics(range) {
1699
2168
  const runs = await this.runsInRange(range);
@@ -1750,7 +2219,7 @@ var DrizzleGovernanceQueries = class {
1750
2219
  }
1751
2220
  async runErrors(range) {
1752
2221
  const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
1753
- const runs = await this.db.select().from(agentRun).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.gte)(agentRun.startedAt, start), (0, import_drizzle_orm3.lte)(agentRun.startedAt, end), (0, import_drizzle_orm3.eq)(agentRun.status, "failed")));
2222
+ const runs = await this.db.select().from(this.t.agentRun).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.gte)(this.t.agentRun.startedAt, start), (0, import_drizzle_orm4.lte)(this.t.agentRun.startedAt, end), (0, import_drizzle_orm4.eq)(this.t.agentRun.status, "failed")));
1754
2223
  const byError = /* @__PURE__ */ new Map();
1755
2224
  for (const run of runs) {
1756
2225
  const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;
@@ -1790,7 +2259,7 @@ var DrizzleGovernanceQueries = class {
1790
2259
  return result;
1791
2260
  }
1792
2261
  async recentRuns(limit) {
1793
- const runs = await this.db.select().from(agentRun).orderBy((0, import_drizzle_orm3.desc)(agentRun.startedAt), (0, import_drizzle_orm3.desc)(agentRun.id)).limit(limit);
2262
+ const runs = await this.db.select().from(this.t.agentRun).orderBy((0, import_drizzle_orm4.desc)(this.t.agentRun.startedAt), (0, import_drizzle_orm4.desc)(this.t.agentRun.id)).limit(limit);
1794
2263
  return runs.map(toRecentRunRow);
1795
2264
  }
1796
2265
  /**
@@ -1800,16 +2269,16 @@ var DrizzleGovernanceQueries = class {
1800
2269
  */
1801
2270
  async pendingApprovals(limit) {
1802
2271
  const rows = await this.db.select({
1803
- toolCallId: agentToolCall.id,
1804
- toolName: agentToolCall.toolName,
1805
- input: agentToolCall.input,
1806
- threadId: agentThread.id,
1807
- threadTitle: agentThread.title,
1808
- actorRef: agentThread.actorRef,
1809
- agentName: agentMessage.agentName,
1810
- requestedAt: agentToolCall.createdAt,
1811
- runId: agentToolCall.runId
1812
- }).from(agentToolCall).innerJoin(agentMessage, (0, import_drizzle_orm3.eq)(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, (0, import_drizzle_orm3.eq)(agentMessage.threadId, agentThread.id)).where((0, import_drizzle_orm3.eq)(agentToolCall.status, "pending_approval")).orderBy(agentToolCall.createdAt, agentToolCall.id).limit(limit);
2272
+ toolCallId: this.t.agentToolCall.id,
2273
+ toolName: this.t.agentToolCall.toolName,
2274
+ input: this.t.agentToolCall.input,
2275
+ threadId: this.t.agentThread.id,
2276
+ threadTitle: this.t.agentThread.title,
2277
+ actorRef: this.t.agentThread.actorRef,
2278
+ agentName: this.t.agentMessage.agentName,
2279
+ requestedAt: this.t.agentToolCall.createdAt,
2280
+ runId: this.t.agentToolCall.runId
2281
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.status, "pending_approval")).orderBy(this.t.agentToolCall.createdAt, this.t.agentToolCall.id).limit(limit);
1813
2282
  return rows.map((row) => ({
1814
2283
  toolCallId: row.toolCallId,
1815
2284
  toolName: row.toolName,
@@ -1831,11 +2300,11 @@ var DrizzleGovernanceQueries = class {
1831
2300
  */
1832
2301
  async toolStats(range) {
1833
2302
  const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
1834
- const calls = await this.db.select().from(agentToolCall).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.gte)(agentToolCall.createdAt, start), (0, import_drizzle_orm3.lte)(agentToolCall.createdAt, end)));
2303
+ const calls = await this.db.select().from(this.t.agentToolCall).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.gte)(this.t.agentToolCall.createdAt, start), (0, import_drizzle_orm4.lte)(this.t.agentToolCall.createdAt, end)));
1835
2304
  const byTool = /* @__PURE__ */ new Map();
1836
2305
  for (const call of calls) {
1837
- const key = `${call.toolName} ${call.toolType}`;
1838
- const bucket = byTool.get(key) ?? {
2306
+ const key2 = `${call.toolName} ${call.toolType}`;
2307
+ const bucket = byTool.get(key2) ?? {
1839
2308
  toolName: call.toolName,
1840
2309
  toolType: call.toolType,
1841
2310
  calls: 0,
@@ -1849,7 +2318,7 @@ var DrizzleGovernanceQueries = class {
1849
2318
  if (call.executionMs != null) {
1850
2319
  bucket.executionMs.push(call.executionMs);
1851
2320
  }
1852
- byTool.set(key, bucket);
2321
+ byTool.set(key2, bucket);
1853
2322
  }
1854
2323
  const result = [];
1855
2324
  for (const bucket of byTool.values()) {
@@ -1881,19 +2350,19 @@ var DrizzleGovernanceQueries = class {
1881
2350
  if (filters?.toolType !== void 0 && !isToolKind(filters.toolType)) {
1882
2351
  return emptyPage(query);
1883
2352
  }
1884
- const whereClause = (0, import_drizzle_orm3.and)(filters?.toolName !== void 0 ? (0, import_drizzle_orm3.eq)(agentToolCall.toolName, filters.toolName) : void 0, filters?.toolType !== void 0 && isToolKind(filters.toolType) ? (0, import_drizzle_orm3.eq)(agentToolCall.toolType, filters.toolType) : void 0, filters?.status !== void 0 && isToolCallStatus(filters.status) ? (0, import_drizzle_orm3.eq)(agentToolCall.status, filters.status) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm3.eq)(agentMessage.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm3.gte)(agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm3.lte)(agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
2353
+ const whereClause = (0, import_drizzle_orm4.and)(filters?.toolName !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.toolType !== void 0 && isToolKind(filters.toolType) ? (0, import_drizzle_orm4.eq)(this.t.agentToolCall.toolType, filters.toolType) : void 0, filters?.status !== void 0 && isToolCallStatus(filters.status) ? (0, import_drizzle_orm4.eq)(this.t.agentToolCall.status, filters.status) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm4.gte)(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm4.lte)(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
1885
2354
  const [totalRow] = await this.db.select({
1886
- value: (0, import_drizzle_orm3.count)()
1887
- }).from(agentToolCall).innerJoin(agentMessage, (0, import_drizzle_orm3.eq)(agentToolCall.messageId, agentMessage.id)).where(whereClause);
2355
+ value: (0, import_drizzle_orm4.count)()
2356
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause);
1888
2357
  const rows = await this.db.select({
1889
- toolCallId: agentToolCall.id,
1890
- toolName: agentToolCall.toolName,
1891
- toolType: agentToolCall.toolType,
1892
- status: agentToolCall.status,
1893
- threadId: agentMessage.threadId,
1894
- createdAt: agentToolCall.createdAt,
1895
- runId: agentToolCall.runId
1896
- }).from(agentToolCall).innerJoin(agentMessage, (0, import_drizzle_orm3.eq)(agentToolCall.messageId, agentMessage.id)).where(whereClause).orderBy((0, import_drizzle_orm3.desc)(agentToolCall.createdAt), (0, import_drizzle_orm3.desc)(agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
2358
+ toolCallId: this.t.agentToolCall.id,
2359
+ toolName: this.t.agentToolCall.toolName,
2360
+ toolType: this.t.agentToolCall.toolType,
2361
+ status: this.t.agentToolCall.status,
2362
+ threadId: this.t.agentMessage.threadId,
2363
+ createdAt: this.t.agentToolCall.createdAt,
2364
+ runId: this.t.agentToolCall.runId
2365
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause).orderBy((0, import_drizzle_orm4.desc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm4.desc)(this.t.agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
1897
2366
  return {
1898
2367
  rows: rows.map((row) => ({
1899
2368
  toolCallId: row.toolCallId,
@@ -1917,11 +2386,11 @@ var DrizzleGovernanceQueries = class {
1917
2386
  */
1918
2387
  async threadsPage(query) {
1919
2388
  const filters = query.where;
1920
- const whereClause = (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.isNull)(agentThread.deletedAt), filters?.actorRef !== void 0 ? (0, import_drizzle_orm3.eq)(agentThread.actorRef, filters.actorRef) : void 0, filters?.title !== void 0 ? (0, import_drizzle_orm3.like)(import_drizzle_orm3.sql`lower(${agentThread.title})`, `%${filters.title.toLowerCase()}%`) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm3.gte)(agentThread.updatedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm3.lte)(agentThread.updatedAt, dayEndUtc(filters.toDay)) : void 0);
2389
+ const whereClause = (0, import_drizzle_orm4.and)((0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt), filters?.actorRef !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.title !== void 0 ? (0, import_drizzle_orm4.like)(import_drizzle_orm4.sql`lower(${this.t.agentThread.title})`, `%${filters.title.toLowerCase()}%`) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm4.gte)(this.t.agentThread.updatedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm4.lte)(this.t.agentThread.updatedAt, dayEndUtc(filters.toDay)) : void 0);
1921
2390
  const [totalRow] = await this.db.select({
1922
- value: (0, import_drizzle_orm3.count)()
1923
- }).from(agentThread).where(whereClause);
1924
- const threads = await this.db.select().from(agentThread).where(whereClause).orderBy((0, import_drizzle_orm3.desc)(agentThread.updatedAt), (0, import_drizzle_orm3.desc)(agentThread.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
2391
+ value: (0, import_drizzle_orm4.count)()
2392
+ }).from(this.t.agentThread).where(whereClause);
2393
+ const threads = await this.db.select().from(this.t.agentThread).where(whereClause).orderBy((0, import_drizzle_orm4.desc)(this.t.agentThread.updatedAt), (0, import_drizzle_orm4.desc)(this.t.agentThread.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
1925
2394
  const rows = await this.toThreadActivityRows(threads);
1926
2395
  return {
1927
2396
  rows,
@@ -1939,11 +2408,11 @@ var DrizzleGovernanceQueries = class {
1939
2408
  if (filters?.status !== void 0 && !isRunStatus(filters.status)) {
1940
2409
  return emptyPage(query);
1941
2410
  }
1942
- const whereClause = (0, import_drizzle_orm3.and)(filters?.agentName !== void 0 ? (0, import_drizzle_orm3.eq)(agentRun.agentName, filters.agentName) : void 0, filters?.status !== void 0 && isRunStatus(filters.status) ? (0, import_drizzle_orm3.eq)(agentRun.status, filters.status) : void 0, filters?.errorCode !== void 0 ? (0, import_drizzle_orm3.eq)(agentRun.errorCode, filters.errorCode) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm3.eq)(agentRun.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm3.gte)(agentRun.startedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm3.lte)(agentRun.startedAt, dayEndUtc(filters.toDay)) : void 0);
2411
+ const whereClause = (0, import_drizzle_orm4.and)(filters?.agentName !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentRun.agentName, filters.agentName) : void 0, filters?.status !== void 0 && isRunStatus(filters.status) ? (0, import_drizzle_orm4.eq)(this.t.agentRun.status, filters.status) : void 0, filters?.errorCode !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentRun.errorCode, filters.errorCode) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentRun.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm4.gte)(this.t.agentRun.startedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm4.lte)(this.t.agentRun.startedAt, dayEndUtc(filters.toDay)) : void 0);
1943
2412
  const [totalRow] = await this.db.select({
1944
- value: (0, import_drizzle_orm3.count)()
1945
- }).from(agentRun).where(whereClause);
1946
- const runs = await this.db.select().from(agentRun).where(whereClause).orderBy((0, import_drizzle_orm3.desc)(agentRun.startedAt), (0, import_drizzle_orm3.desc)(agentRun.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
2413
+ value: (0, import_drizzle_orm4.count)()
2414
+ }).from(this.t.agentRun).where(whereClause);
2415
+ const runs = await this.db.select().from(this.t.agentRun).where(whereClause).orderBy((0, import_drizzle_orm4.desc)(this.t.agentRun.startedAt), (0, import_drizzle_orm4.desc)(this.t.agentRun.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
1947
2416
  return {
1948
2417
  rows: runs.map(toRecentRunRow),
1949
2418
  total: totalRow?.value ?? 0,
@@ -1963,21 +2432,21 @@ var DrizzleGovernanceQueries = class {
1963
2432
  */
1964
2433
  async approvalsPage(query) {
1965
2434
  const filters = query.where;
1966
- const whereClause = (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(agentToolCall.status, "pending_approval"), filters?.toolName !== void 0 ? (0, import_drizzle_orm3.eq)(agentToolCall.toolName, filters.toolName) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm3.eq)(agentThread.id, filters.threadId) : void 0, filters?.actorRef !== void 0 ? (0, import_drizzle_orm3.eq)(agentThread.actorRef, filters.actorRef) : void 0, filters?.agentName !== void 0 ? (0, import_drizzle_orm3.eq)(agentMessage.agentName, filters.agentName) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm3.gte)(agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm3.lte)(agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
2435
+ const whereClause = (0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentToolCall.status, "pending_approval"), filters?.toolName !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentThread.id, filters.threadId) : void 0, filters?.actorRef !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.agentName !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentMessage.agentName, filters.agentName) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm4.gte)(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm4.lte)(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
1967
2436
  const [totalRow] = await this.db.select({
1968
- value: (0, import_drizzle_orm3.count)()
1969
- }).from(agentToolCall).innerJoin(agentMessage, (0, import_drizzle_orm3.eq)(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, (0, import_drizzle_orm3.eq)(agentMessage.threadId, agentThread.id)).where(whereClause);
2437
+ value: (0, import_drizzle_orm4.count)()
2438
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where(whereClause);
1970
2439
  const rows = await this.db.select({
1971
- toolCallId: agentToolCall.id,
1972
- toolName: agentToolCall.toolName,
1973
- input: agentToolCall.input,
1974
- threadId: agentThread.id,
1975
- threadTitle: agentThread.title,
1976
- actorRef: agentThread.actorRef,
1977
- agentName: agentMessage.agentName,
1978
- requestedAt: agentToolCall.createdAt,
1979
- runId: agentToolCall.runId
1980
- }).from(agentToolCall).innerJoin(agentMessage, (0, import_drizzle_orm3.eq)(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, (0, import_drizzle_orm3.eq)(agentMessage.threadId, agentThread.id)).where(whereClause).orderBy((0, import_drizzle_orm3.asc)(agentToolCall.createdAt), (0, import_drizzle_orm3.asc)(agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
2440
+ toolCallId: this.t.agentToolCall.id,
2441
+ toolName: this.t.agentToolCall.toolName,
2442
+ input: this.t.agentToolCall.input,
2443
+ threadId: this.t.agentThread.id,
2444
+ threadTitle: this.t.agentThread.title,
2445
+ actorRef: this.t.agentThread.actorRef,
2446
+ agentName: this.t.agentMessage.agentName,
2447
+ requestedAt: this.t.agentToolCall.createdAt,
2448
+ runId: this.t.agentToolCall.runId
2449
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where(whereClause).orderBy((0, import_drizzle_orm4.asc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm4.asc)(this.t.agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
1981
2450
  return {
1982
2451
  rows: rows.map((row) => ({
1983
2452
  toolCallId: row.toolCallId,
@@ -2002,13 +2471,13 @@ var DrizzleGovernanceQueries = class {
2002
2471
  */
2003
2472
  async runDetail(runId) {
2004
2473
  const [row] = await this.db.select({
2005
- run: agentRun,
2006
- thread: agentThread
2007
- }).from(agentRun).innerJoin(agentThread, (0, import_drizzle_orm3.eq)(agentRun.threadId, agentThread.id)).where((0, import_drizzle_orm3.eq)(agentRun.id, runId)).limit(1);
2474
+ run: this.t.agentRun,
2475
+ thread: this.t.agentThread
2476
+ }).from(this.t.agentRun).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentRun.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm4.eq)(this.t.agentRun.id, runId)).limit(1);
2008
2477
  if (row === void 0) {
2009
2478
  return null;
2010
2479
  }
2011
- const toolCalls = await this.db.select().from(agentToolCall).where((0, import_drizzle_orm3.eq)(agentToolCall.runId, runId)).orderBy((0, import_drizzle_orm3.asc)(agentToolCall.createdAt), (0, import_drizzle_orm3.asc)(agentToolCall.id));
2480
+ const toolCalls = await this.db.select().from(this.t.agentToolCall).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.runId, runId)).orderBy((0, import_drizzle_orm4.asc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm4.asc)(this.t.agentToolCall.id));
2012
2481
  return {
2013
2482
  run: toRecentRunRow(row.run),
2014
2483
  thread: {
@@ -2027,22 +2496,27 @@ var DrizzleGovernanceQueries = class {
2027
2496
  * message. Soft-deleted threads are returned with `deleted: true`; an audit still needs them.
2028
2497
  */
2029
2498
  async threadDetail(query) {
2030
- const [thread] = await this.db.select().from(agentThread).where((0, import_drizzle_orm3.eq)(agentThread.id, query.threadId)).limit(1);
2499
+ const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, query.threadId)).limit(1);
2031
2500
  if (thread === void 0) {
2032
2501
  return null;
2033
2502
  }
2034
2503
  const pricing = await this.loadPricing();
2035
- const usageRows = await this.db.select().from(agentTokenUsage).where((0, import_drizzle_orm3.eq)(agentTokenUsage.threadId, thread.id));
2504
+ const usageRows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm4.eq)(this.t.agentTokenUsage.threadId, thread.id));
2036
2505
  const usage = (0, import_nestjs_agent_core2.rollupThreadUsage)(usageRows.map(toUsageInput), pricing);
2037
2506
  const [messageCountRow] = await this.db.select({
2038
- value: (0, import_drizzle_orm3.count)()
2039
- }).from(agentMessage).where((0, import_drizzle_orm3.eq)(agentMessage.threadId, thread.id));
2040
- const messages = await this.db.select().from(agentMessage).where((0, import_drizzle_orm3.eq)(agentMessage.threadId, thread.id)).orderBy((0, import_drizzle_orm3.desc)(agentMessage.createdAt), (0, import_drizzle_orm3.desc)(agentMessage.id)).limit(query.messageLimit);
2507
+ value: (0, import_drizzle_orm4.count)()
2508
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, thread.id));
2509
+ const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, thread.id)).orderBy(
2510
+ // Append order (see DrizzleAgentStore's message order), newest first.
2511
+ (0, import_drizzle_orm4.desc)(import_drizzle_orm4.sql`coalesce(${this.t.agentMessage.seq}, 0)`),
2512
+ (0, import_drizzle_orm4.desc)(this.t.agentMessage.createdAt),
2513
+ (0, import_drizzle_orm4.desc)(this.t.agentMessage.id)
2514
+ ).limit(query.messageLimit);
2041
2515
  const toolCallCounts = await this.toolCallCountsByMessage(messages.map((message) => message.id));
2042
2516
  const [runTotalRow] = await this.db.select({
2043
- value: (0, import_drizzle_orm3.count)()
2044
- }).from(agentRun).where((0, import_drizzle_orm3.eq)(agentRun.threadId, thread.id));
2045
- const runs = await this.db.select().from(agentRun).where((0, import_drizzle_orm3.eq)(agentRun.threadId, thread.id)).orderBy((0, import_drizzle_orm3.desc)(agentRun.startedAt), (0, import_drizzle_orm3.desc)(agentRun.id)).limit(query.runLimit);
2517
+ value: (0, import_drizzle_orm4.count)()
2518
+ }).from(this.t.agentRun).where((0, import_drizzle_orm4.eq)(this.t.agentRun.threadId, thread.id));
2519
+ const runs = await this.db.select().from(this.t.agentRun).where((0, import_drizzle_orm4.eq)(this.t.agentRun.threadId, thread.id)).orderBy((0, import_drizzle_orm4.desc)(this.t.agentRun.startedAt), (0, import_drizzle_orm4.desc)(this.t.agentRun.id)).limit(query.runLimit);
2046
2520
  return {
2047
2521
  thread: {
2048
2522
  threadId: thread.id,
@@ -2077,9 +2551,9 @@ var DrizzleGovernanceQueries = class {
2077
2551
  return counts;
2078
2552
  }
2079
2553
  const rows = await this.db.select({
2080
- messageId: agentToolCall.messageId,
2081
- value: (0, import_drizzle_orm3.count)()
2082
- }).from(agentToolCall).where((0, import_drizzle_orm3.inArray)(agentToolCall.messageId, messageIds)).groupBy(agentToolCall.messageId);
2554
+ messageId: this.t.agentToolCall.messageId,
2555
+ value: (0, import_drizzle_orm4.count)()
2556
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm4.inArray)(this.t.agentToolCall.messageId, messageIds)).groupBy(this.t.agentToolCall.messageId);
2083
2557
  for (const row of rows) {
2084
2558
  counts.set(row.messageId, row.value);
2085
2559
  }
@@ -2089,7 +2563,7 @@ var DrizzleGovernanceQueries = class {
2089
2563
 
2090
2564
  // src/drizzle-memory-provider.ts
2091
2565
  var import_nestjs_agent_core3 = require("@dudousxd/nestjs-agent-core");
2092
- var import_drizzle_orm4 = require("drizzle-orm");
2566
+ var import_drizzle_orm5 = require("drizzle-orm");
2093
2567
  function toRecord(row) {
2094
2568
  return {
2095
2569
  id: row.id,
@@ -2118,8 +2592,12 @@ var DrizzleMemoryProvider = class {
2118
2592
  __name(this, "DrizzleMemoryProvider");
2119
2593
  }
2120
2594
  db;
2595
+ dialect;
2596
+ t;
2121
2597
  constructor(db) {
2122
- this.db = db;
2598
+ this.dialect = agentDialectOf(db);
2599
+ this.t = agentTablesFor(this.dialect);
2600
+ this.db = asBuilder(db);
2123
2601
  }
2124
2602
  /**
2125
2603
  * Every memory visible at `scopes` — asked on EVERY turn, so it is one indexed `scope in (…)`
@@ -2133,7 +2611,7 @@ var DrizzleMemoryProvider = class {
2133
2611
  if (scopes.length === 0) {
2134
2612
  return [];
2135
2613
  }
2136
- const rows = await this.db.select().from(agentMemory).where((0, import_drizzle_orm4.inArray)(agentMemory.scope, [
2614
+ const rows = await this.db.select().from(this.t.agentMemory).where((0, import_drizzle_orm5.inArray)(this.t.agentMemory.scope, [
2137
2615
  ...scopes
2138
2616
  ]));
2139
2617
  return rows.map(toRecord);
@@ -2149,10 +2627,8 @@ var DrizzleMemoryProvider = class {
2149
2627
  * answer cannot be used to find out which memories exist about other people.
2150
2628
  */
2151
2629
  async forget({ id, ctx }) {
2152
- const deleted = await this.db.delete(agentMemory).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(agentMemory.id, id), (0, import_drizzle_orm4.eq)(agentMemory.scope, (0, import_nestjs_agent_core3.actorScope)(ctx.actor)))).returning({
2153
- id: agentMemory.id
2154
- });
2155
- return deleted.length > 0;
2630
+ const deleted = await affectedRows(this.dialect, this.db.delete(this.t.agentMemory).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.eq)(this.t.agentMemory.id, id), (0, import_drizzle_orm5.eq)(this.t.agentMemory.scope, (0, import_nestjs_agent_core3.actorScope)(ctx.actor)))), this.t.agentMemory.id);
2631
+ return deleted > 0;
2156
2632
  }
2157
2633
  /**
2158
2634
  * Upsert on (`scope`, `key`) — one statement, against the unique index, rather than a read
@@ -2165,7 +2641,7 @@ var DrizzleMemoryProvider = class {
2165
2641
  * rewriting `createdAt` would lose when the belief was first formed; reassigning `id` would
2166
2642
  * invalidate the delete handle a person was already shown.
2167
2643
  */
2168
- async write({ key, text: text2, scope, origin, ctx }) {
2644
+ async write({ key: key2, text: text3, scope, origin, ctx }) {
2169
2645
  assertAuthorMayWriteScope({
2170
2646
  scope,
2171
2647
  origin,
@@ -2178,28 +2654,40 @@ var DrizzleMemoryProvider = class {
2178
2654
  originRunId: origin.runId ?? null,
2179
2655
  originActorRef: origin.actorRef ?? null
2180
2656
  };
2181
- const [row] = await this.db.insert(agentMemory).values({
2657
+ const memory = this.t.agentMemory;
2658
+ const set = {
2659
+ text: text3,
2660
+ ...columns,
2661
+ updatedAt: now
2662
+ };
2663
+ const insert = this.db.insert(memory).values({
2182
2664
  id: crypto.randomUUID(),
2183
2665
  scope,
2184
- key,
2185
- text: text2,
2666
+ key: key2,
2667
+ text: text3,
2186
2668
  ...columns,
2187
2669
  pinned: false,
2188
2670
  createdAt: now,
2189
2671
  updatedAt: now
2190
- }).onConflictDoUpdate({
2191
- target: [
2192
- agentMemory.scope,
2193
- agentMemory.key
2194
- ],
2195
- set: {
2196
- text: text2,
2197
- ...columns,
2198
- updatedAt: now
2199
- }
2200
- }).returning();
2672
+ });
2673
+ let row;
2674
+ if (this.dialect === "mysql") {
2675
+ await upsert(this.dialect, insert, [
2676
+ memory.scope,
2677
+ memory.key
2678
+ ], set);
2679
+ [row] = await this.db.select().from(memory).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.eq)(memory.scope, scope), (0, import_drizzle_orm5.eq)(memory.key, key2)));
2680
+ } else {
2681
+ [row] = await insert.onConflictDoUpdate({
2682
+ target: [
2683
+ memory.scope,
2684
+ memory.key
2685
+ ],
2686
+ set
2687
+ }).returning();
2688
+ }
2201
2689
  if (row === void 0) {
2202
- throw new Error(`DrizzleMemoryProvider: the upsert of "${key}" at "${scope}" returned no row; the driver does not support RETURNING on conflict.`);
2690
+ throw new Error(`DrizzleMemoryProvider: the upsert of "${key2}" at "${scope}" returned no row; the driver does not support RETURNING on conflict.`);
2203
2691
  }
2204
2692
  return toRecord(row);
2205
2693
  }
@@ -2212,13 +2700,11 @@ var DrizzleMemoryProvider = class {
2212
2700
  * `false` where there is no such id.
2213
2701
  */
2214
2702
  async pin({ id, pinned }) {
2215
- const updated = await this.db.update(agentMemory).set({
2703
+ const updated = await affectedRows(this.dialect, this.db.update(this.t.agentMemory).set({
2216
2704
  pinned,
2217
2705
  updatedAt: /* @__PURE__ */ new Date()
2218
- }).where((0, import_drizzle_orm4.eq)(agentMemory.id, id)).returning({
2219
- id: agentMemory.id
2220
- });
2221
- return updated.length > 0;
2706
+ }).where((0, import_drizzle_orm5.eq)(this.t.agentMemory.id, id)), this.t.agentMemory.id);
2707
+ return updated > 0;
2222
2708
  }
2223
2709
  };
2224
2710
  function assertAuthorMayWriteScope({ scope, origin, ctx }) {
@@ -2230,20 +2716,24 @@ function assertAuthorMayWriteScope({ scope, origin, ctx }) {
2230
2716
  __name(assertAuthorMayWriteScope, "assertAuthorMayWriteScope");
2231
2717
 
2232
2718
  // src/drizzle-pricing-store.ts
2233
- var import_drizzle_orm5 = require("drizzle-orm");
2719
+ var import_drizzle_orm6 = require("drizzle-orm");
2234
2720
  var DrizzlePricingStore = class {
2235
2721
  static {
2236
2722
  __name(this, "DrizzlePricingStore");
2237
2723
  }
2238
2724
  db;
2725
+ dialect;
2726
+ t;
2239
2727
  constructor(db) {
2240
- this.db = db;
2728
+ this.dialect = agentDialectOf(db);
2729
+ this.t = agentTablesFor(this.dialect);
2730
+ this.db = asBuilder(db);
2241
2731
  }
2242
2732
  async upsertModelPrice(input) {
2243
- await this.db.update(agentModelPricing).set({
2733
+ await this.db.update(this.t.agentModelPricing).set({
2244
2734
  isCurrent: false
2245
- }).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.eq)(agentModelPricing.modelId, input.modelId), (0, import_drizzle_orm5.eq)(agentModelPricing.isCurrent, true)));
2246
- await this.db.insert(agentModelPricing).values({
2735
+ }).where((0, import_drizzle_orm6.and)((0, import_drizzle_orm6.eq)(this.t.agentModelPricing.modelId, input.modelId), (0, import_drizzle_orm6.eq)(this.t.agentModelPricing.isCurrent, true)));
2736
+ await this.db.insert(this.t.agentModelPricing).values({
2247
2737
  id: crypto.randomUUID(),
2248
2738
  modelId: input.modelId,
2249
2739
  inputPricePer1m: input.inputPricePer1m,
@@ -2255,7 +2745,7 @@ var DrizzlePricingStore = class {
2255
2745
  });
2256
2746
  }
2257
2747
  async listCurrentPrices() {
2258
- const rows = await this.db.select().from(agentModelPricing).where((0, import_drizzle_orm5.eq)(agentModelPricing.isCurrent, true));
2748
+ const rows = await this.db.select().from(this.t.agentModelPricing).where((0, import_drizzle_orm6.eq)(this.t.agentModelPricing.isCurrent, true));
2259
2749
  return rows.map((row) => ({
2260
2750
  modelId: row.modelId,
2261
2751
  inputPricePer1m: row.inputPricePer1m,
@@ -2273,52 +2763,47 @@ var DrizzlePricingStore = class {
2273
2763
 
2274
2764
  // src/drizzle-token-stream-sink.ts
2275
2765
  var import_nestjs_agent_core4 = require("@dudousxd/nestjs-agent-core");
2276
- var import_drizzle_orm6 = require("drizzle-orm");
2277
- function isUniqueViolation(error) {
2278
- for (let current = error; current !== null && typeof current === "object"; ) {
2279
- const code = current.code;
2280
- if (typeof code === "string" && code.startsWith("SQLITE_CONSTRAINT")) return true;
2281
- current = current.cause;
2282
- }
2283
- return false;
2284
- }
2285
- __name(isUniqueViolation, "isUniqueViolation");
2766
+ var import_drizzle_orm7 = require("drizzle-orm");
2286
2767
  var DrizzleStreamFrameTable = class {
2287
2768
  static {
2288
2769
  __name(this, "DrizzleStreamFrameTable");
2289
2770
  }
2290
2771
  db;
2772
+ dialect;
2773
+ t;
2291
2774
  constructor(db) {
2292
- this.db = db;
2775
+ this.dialect = agentDialectOf(db);
2776
+ this.t = agentTablesFor(this.dialect);
2777
+ this.db = asBuilder(db);
2293
2778
  }
2294
2779
  async append(runId, row) {
2295
- await this.db.run(import_drizzle_orm6.sql`INSERT INTO agent_stream_frame (run_id, seq, frame, error, created_at)
2780
+ await runSql(this.db, this.dialect, import_drizzle_orm7.sql`INSERT INTO agent_stream_frame (run_id, seq, frame, error, created_at)
2296
2781
  SELECT ${runId}, COALESCE(MAX(seq), 0) + 1, ${row.frame}, ${row.error}, ${row.createdAt}
2297
2782
  FROM agent_stream_frame WHERE run_id = ${runId}`);
2298
2783
  }
2299
2784
  async read(runId, after, limit) {
2300
2785
  return this.db.select({
2301
- seq: agentStreamFrame.seq,
2302
- frame: agentStreamFrame.frame,
2303
- error: agentStreamFrame.error
2304
- }).from(agentStreamFrame).where((0, import_drizzle_orm6.and)((0, import_drizzle_orm6.eq)(agentStreamFrame.runId, runId), (0, import_drizzle_orm6.gt)(agentStreamFrame.seq, after))).orderBy((0, import_drizzle_orm6.asc)(agentStreamFrame.seq)).limit(limit);
2786
+ seq: this.t.agentStreamFrame.seq,
2787
+ frame: this.t.agentStreamFrame.frame,
2788
+ error: this.t.agentStreamFrame.error
2789
+ }).from(this.t.agentStreamFrame).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(this.t.agentStreamFrame.runId, runId), (0, import_drizzle_orm7.gt)(this.t.agentStreamFrame.seq, after))).orderBy((0, import_drizzle_orm7.asc)(this.t.agentStreamFrame.seq)).limit(limit);
2305
2790
  }
2306
2791
  async has(runId) {
2307
2792
  const rows = await this.db.select({
2308
- seq: agentStreamFrame.seq
2309
- }).from(agentStreamFrame).where((0, import_drizzle_orm6.eq)(agentStreamFrame.runId, runId)).limit(1);
2793
+ seq: this.t.agentStreamFrame.seq
2794
+ }).from(this.t.agentStreamFrame).where((0, import_drizzle_orm7.eq)(this.t.agentStreamFrame.runId, runId)).limit(1);
2310
2795
  return rows.length > 0;
2311
2796
  }
2312
2797
  async remove(runIds) {
2313
2798
  if (runIds.length === 0) return;
2314
- await this.db.delete(agentStreamFrame).where((0, import_drizzle_orm6.inArray)(agentStreamFrame.runId, [
2799
+ await this.db.delete(this.t.agentStreamFrame).where((0, import_drizzle_orm7.inArray)(this.t.agentStreamFrame.runId, [
2315
2800
  ...runIds
2316
2801
  ]));
2317
2802
  }
2318
2803
  async lapsedRuns(cutoff) {
2319
2804
  const rows = await this.db.select({
2320
- runId: agentStreamFrame.runId
2321
- }).from(agentStreamFrame).groupBy(agentStreamFrame.runId).having((0, import_drizzle_orm6.lt)((0, import_drizzle_orm6.max)(agentStreamFrame.createdAt), cutoff));
2805
+ runId: this.t.agentStreamFrame.runId
2806
+ }).from(this.t.agentStreamFrame).groupBy(this.t.agentStreamFrame.runId).having((0, import_drizzle_orm7.lt)((0, import_drizzle_orm7.max)(this.t.agentStreamFrame.createdAt), cutoff));
2322
2807
  return rows.map((row) => row.runId);
2323
2808
  }
2324
2809
  isUniqueViolation(error) {
@@ -2335,54 +2820,60 @@ var DrizzleTokenStreamSink = class extends import_nestjs_agent_core4.SqlTokenStr
2335
2820
  };
2336
2821
 
2337
2822
  // src/drizzle-confirm-token-store.ts
2338
- var import_drizzle_orm7 = require("drizzle-orm");
2823
+ var import_drizzle_orm8 = require("drizzle-orm");
2339
2824
  var DrizzleConfirmTokenStore = class {
2340
2825
  static {
2341
2826
  __name(this, "DrizzleConfirmTokenStore");
2342
2827
  }
2343
2828
  db;
2829
+ dialect;
2830
+ t;
2344
2831
  constructor(db) {
2345
- this.db = db;
2832
+ this.dialect = agentDialectOf(db);
2833
+ this.t = agentTablesFor(this.dialect);
2834
+ this.db = asBuilder(db);
2346
2835
  }
2347
2836
  async claim(input) {
2348
- const inserted = await this.db.insert(agentConfirmToken).values({
2837
+ const row = {
2349
2838
  hash: input.hash,
2350
2839
  actorRef: input.actorRef,
2351
2840
  tool: input.tool,
2352
2841
  expiresAt: input.expiresAt,
2353
2842
  createdAt: Date.now()
2354
- }).onConflictDoNothing().returning({
2355
- hash: agentConfirmToken.hash
2356
- });
2357
- return inserted.length === 1;
2843
+ };
2844
+ const table = this.t.agentConfirmToken;
2845
+ if (this.dialect === "mysql") {
2846
+ const insert = this.db.insert(table);
2847
+ return mysqlAffectedRows(await insert.ignore().values(row)) === 1;
2848
+ }
2849
+ const inserted = await affectedRows(this.dialect, this.db.insert(table).values(row).onConflictDoNothing(), table.hash);
2850
+ return inserted === 1;
2358
2851
  }
2359
2852
  async release(hash) {
2360
- await this.db.delete(agentConfirmToken).where((0, import_drizzle_orm7.eq)(agentConfirmToken.hash, hash));
2853
+ await this.db.delete(this.t.agentConfirmToken).where((0, import_drizzle_orm8.eq)(this.t.agentConfirmToken.hash, hash));
2361
2854
  }
2362
2855
  async purgeExpired(now = Date.now()) {
2363
- const purged = await this.db.delete(agentConfirmToken).where((0, import_drizzle_orm7.lt)(agentConfirmToken.expiresAt, now)).returning({
2364
- hash: agentConfirmToken.hash
2365
- });
2366
- return purged.length;
2856
+ const table = this.t.agentConfirmToken;
2857
+ return affectedRows(this.dialect, this.db.delete(table).where((0, import_drizzle_orm8.lt)(table.expiresAt, now)), table.hash);
2367
2858
  }
2368
2859
  };
2369
2860
 
2370
2861
  // src/drizzle-rag-ingestion-log.ts
2371
2862
  var import_node_diagnostics_channel = require("diagnostics_channel");
2372
2863
  var import_common = require("@nestjs/common");
2373
- var import_drizzle_orm8 = require("drizzle-orm");
2374
- function _ts_decorate(decorators, target, key, desc4) {
2375
- var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
2864
+ var import_drizzle_orm9 = require("drizzle-orm");
2865
+ function _ts_decorate(decorators, target, key2, desc4) {
2866
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key2) : desc4, d;
2376
2867
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2377
- r = Reflect.decorate(decorators, target, key, desc4);
2868
+ r = Reflect.decorate(decorators, target, key2, desc4);
2378
2869
  } else {
2379
2870
  for (var i = decorators.length - 1; i >= 0; i--) {
2380
2871
  if (d = decorators[i]) {
2381
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2872
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key2, r) : d(target, key2)) || r;
2382
2873
  }
2383
2874
  }
2384
2875
  }
2385
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2876
+ return c > 3 && r && Object.defineProperty(target, key2, r), r;
2386
2877
  }
2387
2878
  __name(_ts_decorate, "_ts_decorate");
2388
2879
  function _ts_metadata(metadataKey, metadataValue) {
@@ -2418,8 +2909,8 @@ function num(value) {
2418
2909
  }
2419
2910
  __name(num, "num");
2420
2911
  var RAG_INGESTION_LOG_PAGE_ORDER = [
2421
- (0, import_drizzle_orm8.desc)(ragIngestionLog.updatedAt),
2422
- (0, import_drizzle_orm8.asc)(ragIngestionLog.documentId)
2912
+ (0, import_drizzle_orm9.desc)(ragIngestionLog.updatedAt),
2913
+ (0, import_drizzle_orm9.asc)(ragIngestionLog.documentId)
2423
2914
  ];
2424
2915
  var DEFAULT_PAGE_SIZE = 200;
2425
2916
  var DEFAULT_BATCH_SIZE = 200;
@@ -2428,20 +2919,27 @@ function batches(batchSize) {
2428
2919
  return Number.isFinite(requested) && requested >= 1 ? requested : DEFAULT_BATCH_SIZE;
2429
2920
  }
2430
2921
  __name(batches, "batches");
2431
- var CURSOR_COLUMNS = {
2432
- documentId: ragIngestionLog.documentId,
2433
- updatedAt: ragIngestionLog.updatedAt
2434
- };
2922
+ function cursorColumns(log) {
2923
+ return {
2924
+ documentId: log.documentId,
2925
+ updatedAt: log.updatedAt
2926
+ };
2927
+ }
2928
+ __name(cursorColumns, "cursorColumns");
2435
2929
  var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2436
2930
  static {
2437
2931
  __name(this, "DrizzleRagIngestionLog");
2438
2932
  }
2439
- db;
2440
2933
  logger = new import_common.Logger(_DrizzleRagIngestionLog.name);
2441
2934
  teardowns = [];
2442
2935
  inFlight = /* @__PURE__ */ new Set();
2936
+ db;
2937
+ dialect;
2938
+ t;
2443
2939
  constructor(db) {
2444
- this.db = db;
2940
+ this.dialect = agentDialectOf(db);
2941
+ this.t = agentTablesFor(this.dialect);
2942
+ this.db = asBuilder(db);
2445
2943
  }
2446
2944
  onModuleInit() {
2447
2945
  for (const channel of CHANNELS) {
@@ -2470,7 +2968,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2470
2968
  }
2471
2969
  /** The latest recorded outcome per document, newest first. */
2472
2970
  async list(query = {}) {
2473
- const rows = this.db.select().from(ragIngestionLog).where(this.where(query)).orderBy(...RAG_INGESTION_LOG_PAGE_ORDER).limit(query.limit ?? DEFAULT_PAGE_SIZE);
2971
+ const rows = this.db.select().from(this.t.ragIngestionLog).where(this.where(query)).orderBy(...RAG_INGESTION_LOG_PAGE_ORDER).limit(query.limit ?? DEFAULT_PAGE_SIZE);
2474
2972
  return query.offset === void 0 ? rows : rows.offset(query.offset);
2475
2973
  }
2476
2974
  /**
@@ -2483,8 +2981,8 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2483
2981
  */
2484
2982
  async listPage(query = {}) {
2485
2983
  const [totalRow] = await this.db.select({
2486
- value: (0, import_drizzle_orm8.count)()
2487
- }).from(ragIngestionLog).where(this.where(query));
2984
+ value: (0, import_drizzle_orm9.count)()
2985
+ }).from(this.t.ragIngestionLog).where(this.where(query));
2488
2986
  return {
2489
2987
  rows: await this.list(query),
2490
2988
  total: totalRow?.value ?? 0
@@ -2537,7 +3035,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2537
3035
  * sweep is run. A sweep that stops early stops by `break`ing out of the `for await`.
2538
3036
  */
2539
3037
  iterate(where = {}, options = {}) {
2540
- return this.sweep(where, batches(options.batchSize), options.after, (filter, limit) => this.db.select().from(ragIngestionLog).where(filter).orderBy(...RAG_INGESTION_LOG_PAGE_ORDER).limit(limit));
3038
+ return this.sweep(where, batches(options.batchSize), options.after, (filter, limit) => this.db.select().from(this.t.ragIngestionLog).where(filter).orderBy(...RAG_INGESTION_LOG_PAGE_ORDER).limit(limit));
2541
3039
  }
2542
3040
  /**
2543
3041
  * Just the document ids of the matching rows, in {@link RAG_INGESTION_LOG_PAGE_ORDER}.
@@ -2554,7 +3052,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2554
3052
  */
2555
3053
  async listDocumentIds(where = {}, options = {}) {
2556
3054
  const ids = [];
2557
- const rows = this.sweep(where, batches(options.batchSize), void 0, (filter, limit) => this.db.select(CURSOR_COLUMNS).from(ragIngestionLog).where(filter).orderBy(...RAG_INGESTION_LOG_PAGE_ORDER).limit(limit));
3055
+ const rows = this.sweep(where, batches(options.batchSize), void 0, (filter, limit) => this.db.select(cursorColumns(this.t.ragIngestionLog)).from(this.t.ragIngestionLog).where(filter).orderBy(...RAG_INGESTION_LOG_PAGE_ORDER).limit(limit));
2558
3056
  for await (const row of rows) {
2559
3057
  ids.push(row.documentId);
2560
3058
  }
@@ -2562,22 +3060,18 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2562
3060
  }
2563
3061
  /** The latest recorded outcome for one document, or null if it was never attempted. */
2564
3062
  async get(documentId) {
2565
- const [row] = await this.db.select().from(ragIngestionLog).where((0, import_drizzle_orm8.eq)(ragIngestionLog.documentId, documentId));
3063
+ const [row] = await this.db.select().from(this.t.ragIngestionLog).where((0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.documentId, documentId));
2566
3064
  return row ?? null;
2567
3065
  }
2568
3066
  /** Forget one document's record. Returns whether a row was actually removed. */
2569
3067
  async remove(documentId) {
2570
- const removed = await this.db.delete(ragIngestionLog).where((0, import_drizzle_orm8.eq)(ragIngestionLog.documentId, documentId)).returning({
2571
- documentId: ragIngestionLog.documentId
2572
- });
2573
- return removed.length > 0;
3068
+ const removed = await affectedRows(this.dialect, this.db.delete(this.t.ragIngestionLog).where((0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.documentId, documentId)), this.t.ragIngestionLog.documentId);
3069
+ return removed > 0;
2574
3070
  }
2575
3071
  /** Forget every record for a collection — for when the collection itself is deleted. */
2576
3072
  async removeByCollection(collection) {
2577
- const removed = await this.db.delete(ragIngestionLog).where((0, import_drizzle_orm8.eq)(ragIngestionLog.collection, collection)).returning({
2578
- documentId: ragIngestionLog.documentId
2579
- });
2580
- return removed.length;
3073
+ const removed = await affectedRows(this.dialect, this.db.delete(this.t.ragIngestionLog).where((0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.collection, collection)), this.t.ragIngestionLog.documentId);
3074
+ return removed;
2581
3075
  }
2582
3076
  /**
2583
3077
  * The keyset sweep both {@link iterate} and {@link listDocumentIds} are made of. `page` decides
@@ -2606,7 +3100,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2606
3100
  }
2607
3101
  }
2608
3102
  where(query) {
2609
- return (0, import_drizzle_orm8.and)(query.collection !== void 0 ? (0, import_drizzle_orm8.eq)(ragIngestionLog.collection, query.collection) : void 0, query.status !== void 0 ? (0, import_drizzle_orm8.eq)(ragIngestionLog.status, query.status) : void 0);
3103
+ return (0, import_drizzle_orm9.and)(query.collection !== void 0 ? (0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.collection, query.collection) : void 0, query.status !== void 0 ? (0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.status, query.status) : void 0);
2610
3104
  }
2611
3105
  /**
2612
3106
  * The coordinates filter AND'd with "strictly after `cursor` in
@@ -2621,7 +3115,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2621
3115
  if (cursor === void 0) {
2622
3116
  return base;
2623
3117
  }
2624
- return (0, import_drizzle_orm8.and)(base, (0, import_drizzle_orm8.or)((0, import_drizzle_orm8.lt)(ragIngestionLog.updatedAt, cursor.updatedAt), (0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(ragIngestionLog.updatedAt, cursor.updatedAt), (0, import_drizzle_orm8.gt)(ragIngestionLog.documentId, cursor.documentId))));
3118
+ return (0, import_drizzle_orm9.and)(base, (0, import_drizzle_orm9.or)((0, import_drizzle_orm9.lt)(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), (0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), (0, import_drizzle_orm9.gt)(this.t.ragIngestionLog.documentId, cursor.documentId))));
2625
3119
  }
2626
3120
  /**
2627
3121
  * Upsert one outcome. Keyed by document id so the row always reflects the *current* state — a
@@ -2669,14 +3163,11 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2669
3163
  size
2670
3164
  } : {}
2671
3165
  };
2672
- await this.db.insert(ragIngestionLog).values({
3166
+ await upsert(this.dialect, this.db.insert(this.t.ragIngestionLog).values({
2673
3167
  documentId,
2674
3168
  createdAt: now,
2675
3169
  ...outcome
2676
- }).onConflictDoUpdate({
2677
- target: ragIngestionLog.documentId,
2678
- set: outcome
2679
- });
3170
+ }), this.t.ragIngestionLog.documentId, outcome);
2680
3171
  } catch (error) {
2681
3172
  this.logger.warn(`Could not record RAG ingestion outcome for ${documentId}: ${error instanceof Error ? error.message : String(error)}`);
2682
3173
  }
@@ -2699,18 +3190,18 @@ DrizzleRagIngestionLog = _ts_decorate([
2699
3190
  // src/drizzle-agent-store.module.ts
2700
3191
  var import_nestjs_agent_core5 = require("@dudousxd/nestjs-agent-core");
2701
3192
  var import_common2 = require("@nestjs/common");
2702
- function _ts_decorate2(decorators, target, key, desc4) {
2703
- var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
3193
+ function _ts_decorate2(decorators, target, key2, desc4) {
3194
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key2) : desc4, d;
2704
3195
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2705
- r = Reflect.decorate(decorators, target, key, desc4);
3196
+ r = Reflect.decorate(decorators, target, key2, desc4);
2706
3197
  } else {
2707
3198
  for (var i = decorators.length - 1; i >= 0; i--) {
2708
3199
  if (d = decorators[i]) {
2709
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3200
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key2, r) : d(target, key2)) || r;
2710
3201
  }
2711
3202
  }
2712
3203
  }
2713
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3204
+ return c > 3 && r && Object.defineProperty(target, key2, r), r;
2714
3205
  }
2715
3206
  __name(_ts_decorate2, "_ts_decorate");
2716
3207
  var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
@@ -2811,17 +3302,21 @@ DrizzleAgentStoreModule = _ts_decorate2([
2811
3302
  DrizzleTokenStreamSink,
2812
3303
  RAG_INGESTION_LOG_PAGE_ORDER,
2813
3304
  agentConfirmToken,
3305
+ agentDialectOf,
2814
3306
  agentMemory,
2815
3307
  agentMessage,
2816
3308
  agentModelPricing,
2817
3309
  agentQueuedMessage,
2818
3310
  agentRun,
2819
3311
  agentSchema,
3312
+ agentSchemaDdl,
2820
3313
  agentStreamFrame,
2821
3314
  agentThread,
2822
3315
  agentTokenUsage,
2823
3316
  agentToolCall,
2824
3317
  ensureAgentSchema,
3318
+ mysqlAgentSchema,
3319
+ pgAgentSchema,
2825
3320
  ragIngestionLog
2826
3321
  });
2827
3322
  //# sourceMappingURL=index.cjs.map