@dudousxd/nestjs-agent-store-drizzle 0.22.1 → 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);
@@ -62,6 +66,8 @@ var agentThread = (0, import_sqlite_core.sqliteTable)("agent_thread", {
62
66
  defaultAgent: (0, import_sqlite_core.text)("default_agent"),
63
67
  /** The model every turn on this thread runs on unless the send names one; `null` → default. */
64
68
  model: (0, import_sqlite_core.text)("model"),
69
+ /** The persona a send on this thread runs under when it names none; `null` → the agent's default. */
70
+ persona: (0, import_sqlite_core.text)("persona"),
65
71
  /** Why the thread's message queue stopped draining; `null` → it drains. */
66
72
  queuePause: (0, import_sqlite_core.text)("queue_pause", {
67
73
  mode: "json"
@@ -101,6 +107,8 @@ var agentMessage = (0, import_sqlite_core.sqliteTable)("agent_message", {
101
107
  mode: "json"
102
108
  }).$type(),
103
109
  agentName: (0, import_sqlite_core.text)("agent_name"),
110
+ /** The persona the turn that wrote this message ran under; `null` → none. */
111
+ persona: (0, import_sqlite_core.text)("persona"),
104
112
  runId: (0, import_sqlite_core.text)("run_id"),
105
113
  /** The step's streamed thinking; `null` when the model produced none. */
106
114
  reasoning: (0, import_sqlite_core.text)("reasoning"),
@@ -113,6 +121,12 @@ var agentMessage = (0, import_sqlite_core.sqliteTable)("agent_message", {
113
121
  feedback: (0, import_sqlite_core.text)("feedback", {
114
122
  mode: "json"
115
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"),
116
130
  createdAt: (0, import_sqlite_core.integer)("created_at", {
117
131
  mode: "timestamp_ms"
118
132
  }).notNull()
@@ -173,6 +187,8 @@ var agentQueuedMessage = (0, import_sqlite_core.sqliteTable)("agent_queued_messa
173
187
  mode: "json"
174
188
  }).$type(),
175
189
  agentName: (0, import_sqlite_core.text)("agent_name"),
190
+ /** The persona the send resolved — what the message starts under. */
191
+ persona: (0, import_sqlite_core.text)("persona"),
176
192
  model: (0, import_sqlite_core.text)("model"),
177
193
  pageContext: (0, import_sqlite_core.text)("page_context", {
178
194
  mode: "json"
@@ -345,285 +361,721 @@ var agentSchema = {
345
361
  agentRun,
346
362
  agentMemory,
347
363
  ragIngestionLog,
348
- agentConfirmToken
364
+ agentConfirmToken,
365
+ agentStreamFrame
349
366
  };
350
367
 
351
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
352
375
  var import_drizzle_orm = require("drizzle-orm");
353
- var statements = [
354
- `CREATE TABLE IF NOT EXISTS agent_thread (
355
- id TEXT PRIMARY KEY NOT NULL,
356
- actor_ref TEXT NOT NULL,
357
- tenant_ref TEXT,
358
- title TEXT NOT NULL,
359
- transient INTEGER NOT NULL DEFAULT 0,
360
- active_stream_id TEXT,
361
- default_agent TEXT,
362
- model TEXT,
363
- queue_pause TEXT,
364
- created_at INTEGER NOT NULL,
365
- updated_at INTEGER NOT NULL,
366
- deleted_at INTEGER
367
- )`,
368
- `CREATE INDEX IF NOT EXISTS agent_thread_actor_updated_idx
369
- ON agent_thread (actor_ref, updated_at)`,
370
- `CREATE TABLE IF NOT EXISTS agent_message (
371
- id TEXT PRIMARY KEY NOT NULL,
372
- thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,
373
- role TEXT NOT NULL,
374
- content TEXT NOT NULL,
375
- tool_calls TEXT,
376
- tool_results TEXT,
377
- attachments TEXT,
378
- follow_ups TEXT,
379
- usage TEXT,
380
- agent_name TEXT,
381
- run_id TEXT,
382
- reasoning TEXT,
383
- reasoning_ms INTEGER,
384
- ui TEXT,
385
- feedback TEXT,
386
- created_at INTEGER NOT NULL
387
- )`,
388
- `CREATE INDEX IF NOT EXISTS agent_message_thread_created_idx
389
- ON agent_message (thread_id, created_at)`,
390
- `CREATE TABLE IF NOT EXISTS agent_queued_message (
391
- id TEXT PRIMARY KEY NOT NULL,
392
- thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,
393
- actor TEXT NOT NULL,
394
- content TEXT NOT NULL,
395
- attachments TEXT,
396
- agent_name TEXT,
397
- model TEXT,
398
- page_context TEXT,
399
- interrupt INTEGER NOT NULL DEFAULT 0,
400
- position INTEGER NOT NULL,
401
- created_at INTEGER NOT NULL,
402
- updated_at INTEGER NOT NULL
403
- )`,
404
- `CREATE INDEX IF NOT EXISTS agent_queued_message_thread_position_idx
405
- ON agent_queued_message (thread_id, position)`,
406
- `CREATE TABLE IF NOT EXISTS agent_tool_call (
407
- id TEXT PRIMARY KEY NOT NULL,
408
- message_id TEXT NOT NULL REFERENCES agent_message(id) ON DELETE CASCADE,
409
- tool_name TEXT NOT NULL,
410
- tool_type TEXT NOT NULL,
411
- input TEXT,
412
- output TEXT,
413
- status TEXT NOT NULL,
414
- executed_by_ref TEXT,
415
- execution_ms INTEGER,
416
- error TEXT,
417
- created_at INTEGER NOT NULL,
418
- executed_at INTEGER,
419
- run_id TEXT,
420
- approver TEXT,
421
- expires_at INTEGER,
422
- remember INTEGER,
423
- decided_via TEXT
424
- )`,
425
- `CREATE INDEX IF NOT EXISTS agent_tool_call_message_idx
426
- ON agent_tool_call (message_id)`,
427
- `CREATE TABLE IF NOT EXISTS agent_token_usage (
428
- id TEXT PRIMARY KEY NOT NULL,
429
- thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,
430
- actor_ref TEXT NOT NULL,
431
- message_id TEXT,
432
- model_id TEXT NOT NULL,
433
- purpose TEXT NOT NULL,
434
- input_tokens INTEGER NOT NULL,
435
- output_tokens INTEGER NOT NULL,
436
- cache_write_tokens INTEGER,
437
- cache_read_tokens INTEGER,
438
- cost_usd REAL,
439
- created_at INTEGER NOT NULL
440
- )`,
441
- `CREATE INDEX IF NOT EXISTS agent_token_usage_actor_created_idx
442
- ON agent_token_usage (actor_ref, created_at)`,
443
- `CREATE TABLE IF NOT EXISTS agent_model_pricing (
444
- id TEXT PRIMARY KEY NOT NULL,
445
- model_id TEXT NOT NULL,
446
- input_price_per_1m REAL NOT NULL,
447
- output_price_per_1m REAL NOT NULL,
448
- cache_write_price_per_1m REAL,
449
- cache_read_price_per_1m REAL,
450
- effective_from INTEGER NOT NULL,
451
- is_current INTEGER NOT NULL
452
- )`,
453
- `CREATE TABLE IF NOT EXISTS agent_run (
454
- id TEXT PRIMARY KEY NOT NULL,
455
- thread_id TEXT NOT NULL REFERENCES agent_thread(id) ON DELETE CASCADE,
456
- actor_ref TEXT NOT NULL,
457
- agent_name TEXT,
458
- status TEXT NOT NULL,
459
- duration_ms INTEGER,
460
- error_code TEXT,
461
- error_message TEXT,
462
- retries INTEGER NOT NULL DEFAULT 0,
463
- started_at INTEGER NOT NULL,
464
- settled_at INTEGER,
465
- prompt_hash TEXT,
466
- parent_run_id TEXT
467
- )`,
468
- `CREATE INDEX IF NOT EXISTS agent_run_started_idx
469
- ON agent_run (started_at)`,
470
- // `key` and `text` are quoted: both are keywords in at least one engine this DDL is read by, and
471
- // they are the SPI's own field names, which is worth more here than dodging the quoting.
472
- `CREATE TABLE IF NOT EXISTS agent_memory (
473
- id TEXT PRIMARY KEY NOT NULL,
474
- scope TEXT NOT NULL,
475
- "key" TEXT NOT NULL,
476
- "text" TEXT NOT NULL,
477
- origin_author TEXT NOT NULL,
478
- origin_thread_id TEXT,
479
- origin_run_id TEXT,
480
- origin_actor_ref TEXT,
481
- pinned INTEGER NOT NULL DEFAULT 0,
482
- created_at INTEGER NOT NULL,
483
- updated_at INTEGER NOT NULL
484
- )`,
485
- `CREATE UNIQUE INDEX IF NOT EXISTS agent_memory_scope_key_uq
486
- ON agent_memory (scope, "key")`,
487
- `CREATE TABLE IF NOT EXISTS rag_ingestion_log (
488
- document_id TEXT PRIMARY KEY NOT NULL,
489
- status TEXT NOT NULL,
490
- collection TEXT,
491
- owner_type TEXT,
492
- owner_id TEXT,
493
- source TEXT,
494
- mime_type TEXT,
495
- size INTEGER,
496
- chunks INTEGER,
497
- reason TEXT,
498
- error TEXT,
499
- created_at INTEGER NOT NULL,
500
- updated_at INTEGER NOT NULL
501
- )`,
502
- `CREATE INDEX IF NOT EXISTS rag_ingestion_log_collection_idx
503
- ON rag_ingestion_log (collection, updated_at)`,
504
- `CREATE TABLE IF NOT EXISTS agent_stream_frame (
505
- run_id TEXT NOT NULL,
506
- seq INTEGER NOT NULL,
507
- frame TEXT,
508
- error TEXT,
509
- created_at INTEGER NOT NULL,
510
- PRIMARY KEY (run_id, seq)
511
- )`,
512
- `CREATE TABLE IF NOT EXISTS agent_confirm_token (
513
- hash TEXT PRIMARY KEY NOT NULL,
514
- actor_ref TEXT NOT NULL,
515
- tool TEXT NOT NULL,
516
- expires_at INTEGER NOT NULL,
517
- created_at INTEGER NOT NULL
518
- )`,
519
- `CREATE INDEX IF NOT EXISTS agent_confirm_token_expires_idx
520
- ON agent_confirm_token (expires_at)`
521
- ];
522
- var additiveColumns = [
523
- {
524
- table: "agent_message",
525
- column: "run_id",
526
- ddl: "ALTER TABLE agent_message ADD COLUMN run_id TEXT"
527
- },
528
- {
529
- table: "agent_message",
530
- column: "attachments",
531
- ddl: "ALTER TABLE agent_message ADD COLUMN attachments TEXT"
532
- },
533
- {
534
- table: "agent_thread",
535
- column: "default_agent",
536
- ddl: "ALTER TABLE agent_thread ADD COLUMN default_agent TEXT"
537
- },
538
- {
539
- table: "agent_run",
540
- column: "parent_run_id",
541
- ddl: "ALTER TABLE agent_run ADD COLUMN parent_run_id TEXT"
542
- },
543
- {
544
- table: "agent_message",
545
- column: "reasoning",
546
- ddl: "ALTER TABLE agent_message ADD COLUMN reasoning TEXT"
547
- },
548
- {
549
- table: "agent_message",
550
- column: "reasoning_ms",
551
- ddl: "ALTER TABLE agent_message ADD COLUMN reasoning_ms INTEGER"
552
- },
553
- {
554
- table: "agent_message",
555
- column: "ui",
556
- ddl: "ALTER TABLE agent_message ADD COLUMN ui TEXT"
557
- },
558
- {
559
- table: "agent_message",
560
- column: "feedback",
561
- ddl: "ALTER TABLE agent_message ADD COLUMN feedback TEXT"
562
- },
563
- {
564
- table: "agent_thread",
565
- column: "model",
566
- ddl: "ALTER TABLE agent_thread ADD COLUMN model TEXT"
567
- },
568
- {
569
- table: "agent_tool_call",
570
- column: "approver",
571
- ddl: "ALTER TABLE agent_tool_call ADD COLUMN approver TEXT"
572
- },
573
- {
574
- table: "agent_tool_call",
575
- column: "expires_at",
576
- ddl: "ALTER TABLE agent_tool_call ADD COLUMN expires_at INTEGER"
577
- },
578
- {
579
- table: "agent_tool_call",
580
- column: "remember",
581
- ddl: "ALTER TABLE agent_tool_call ADD COLUMN remember INTEGER"
582
- },
583
- {
584
- table: "agent_thread",
585
- column: "queue_pause",
586
- ddl: "ALTER TABLE agent_thread ADD COLUMN queue_pause TEXT"
587
- },
588
- {
589
- table: "agent_tool_call",
590
- column: "decided_via",
591
- ddl: "ALTER TABLE agent_tool_call ADD COLUMN decided_via 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;
592
852
  }
593
- ];
594
- async function ensureAgentSchema(db) {
595
- for (const statement of statements) {
596
- 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);
597
863
  }
598
- for (const { table, column, ddl } of additiveColumns) {
599
- const existing = await db.all(import_drizzle_orm.sql.raw(`PRAGMA table_info(${table})`));
600
- if (!existing.some((row) => row.name === column)) {
601
- 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;
602
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
+ });
603
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;
915
+ }
916
+ await heal(db, dialect);
604
917
  }
605
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");
606
1051
 
607
1052
  // src/drizzle-agent-store.ts
608
1053
  var import_nestjs_agent_core = require("@dudousxd/nestjs-agent-core");
609
- var import_drizzle_orm2 = require("drizzle-orm");
610
- var TURN_MESSAGE_COLUMNS = {
611
- id: agentMessage.id,
612
- role: agentMessage.role,
613
- content: agentMessage.content,
614
- agentName: agentMessage.agentName,
615
- toolCalls: agentMessage.toolCalls,
616
- toolResults: agentMessage.toolResults,
617
- attachments: agentMessage.attachments,
618
- createdAt: agentMessage.createdAt
619
- };
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");
620
1068
  var DrizzleAgentStore = class {
621
1069
  static {
622
1070
  __name(this, "DrizzleAgentStore");
623
1071
  }
624
1072
  db;
1073
+ dialect;
1074
+ t;
625
1075
  constructor(db) {
626
- this.db = db;
1076
+ this.dialect = agentDialectOf(db);
1077
+ this.t = agentTablesFor(this.dialect);
1078
+ this.db = asBuilder(db);
627
1079
  }
628
1080
  async createThread(input) {
629
1081
  const now = /* @__PURE__ */ new Date();
@@ -636,20 +1088,21 @@ var DrizzleAgentStore = class {
636
1088
  activeStreamId: null,
637
1089
  defaultAgent: null,
638
1090
  model: null,
1091
+ persona: input.persona ?? null,
639
1092
  queuePause: null,
640
1093
  createdAt: now,
641
1094
  updatedAt: now,
642
1095
  deletedAt: null
643
1096
  };
644
- await this.db.insert(agentThread).values(thread);
1097
+ await this.db.insert(this.t.agentThread).values(thread);
645
1098
  return this.toSummary(thread);
646
1099
  }
647
1100
  async getThread(threadId) {
648
- 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)));
649
1102
  if (thread === void 0) {
650
1103
  return null;
651
1104
  }
652
- 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());
653
1106
  const last = messages[messages.length - 1];
654
1107
  const approvals = await this.approvalsFor(messages.map((message) => message.id));
655
1108
  return {
@@ -682,16 +1135,16 @@ var DrizzleAgentStore = class {
682
1135
  */
683
1136
  async loadThreadForTurn(query) {
684
1137
  const [thread] = await this.db.select({
685
- title: agentThread.title,
686
- defaultAgent: agentThread.defaultAgent
687
- }).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)));
688
1141
  if (thread === void 0) {
689
1142
  return null;
690
1143
  }
691
1144
  const messages = await this.loadTurnWindow(query.threadId, query.messageLimit);
692
1145
  const [answered] = await this.db.select({
693
- id: agentMessage.id
694
- }).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);
695
1148
  return {
696
1149
  title: thread.title,
697
1150
  defaultAgent: thread.defaultAgent,
@@ -707,30 +1160,30 @@ var DrizzleAgentStore = class {
707
1160
  if (limit !== void 0 && limit <= 0) {
708
1161
  return [];
709
1162
  }
710
- 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());
711
1164
  const rows = limit === void 0 ? await window : await window.limit(limit);
712
1165
  return rows.reverse().map((row) => this.toStoredMessage(row));
713
1166
  }
714
1167
  async listThreads(actorRef, limit = 50) {
715
- 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);
716
1169
  const summaries = [];
717
1170
  for (const thread of threads) {
718
- 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);
719
1172
  summaries.push(this.toSummary(thread, last?.content));
720
1173
  }
721
1174
  return summaries;
722
1175
  }
723
1176
  async softDeleteThread(threadId) {
724
- await this.db.update(agentThread).set({
1177
+ await this.db.update(this.t.agentThread).set({
725
1178
  deletedAt: /* @__PURE__ */ new Date()
726
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1179
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
727
1180
  }
728
1181
  async forkThread(threadId, fromMessageId) {
729
- 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));
730
1183
  if (source === void 0) {
731
1184
  throw new Error(`thread ${threadId} not found`);
732
1185
  }
733
- 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());
734
1187
  const cutoff = messages.findIndex((message) => message.id === fromMessageId);
735
1188
  const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;
736
1189
  const now = /* @__PURE__ */ new Date();
@@ -743,16 +1196,19 @@ var DrizzleAgentStore = class {
743
1196
  activeStreamId: null,
744
1197
  defaultAgent: source.defaultAgent,
745
1198
  model: source.model,
1199
+ persona: source.persona,
746
1200
  // A fork is a new conversation: nothing is waiting on it, and nothing is paused.
747
1201
  queuePause: null,
748
1202
  createdAt: now,
749
1203
  updatedAt: now,
750
1204
  deletedAt: null
751
1205
  };
752
- await this.db.insert(agentThread).values(fork);
1206
+ await this.db.insert(this.t.agentThread).values(fork);
753
1207
  if (kept.length > 0) {
754
- await this.db.insert(agentMessage).values(kept.map((message) => ({
1208
+ await this.db.insert(this.t.agentMessage).values(kept.map((message, index4) => ({
755
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,
756
1212
  threadId: fork.id,
757
1213
  role: message.role,
758
1214
  content: message.content,
@@ -762,6 +1218,7 @@ var DrizzleAgentStore = class {
762
1218
  followUps: message.followUps,
763
1219
  usage: message.usage,
764
1220
  agentName: message.agentName,
1221
+ persona: message.persona,
765
1222
  // The copy is the same message, so it keeps the run that wrote it. A reader asking which
766
1223
  // turn produced this text gets the truthful answer; the run's own thread is still the
767
1224
  // original, so a run-scoped read never picks the fork's rows up.
@@ -776,21 +1233,21 @@ var DrizzleAgentStore = class {
776
1233
  }
777
1234
  async ownerOfThread(threadId) {
778
1235
  const [thread] = await this.db.select({
779
- actorRef: agentThread.actorRef
780
- }).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)));
781
1238
  return thread?.actorRef ?? null;
782
1239
  }
783
1240
  async ownerOfToolCall(toolCallId) {
784
1241
  const [row] = await this.db.select({
785
- actorRef: agentThread.actorRef
786
- }).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));
787
1244
  return row?.actorRef ?? null;
788
1245
  }
789
1246
  async runForToolCall(toolCallId) {
790
1247
  const [row] = await this.db.select({
791
- runId: agentToolCall.runId,
792
- activeStreamId: agentThread.activeStreamId
793
- }).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));
794
1251
  return row?.runId ?? row?.activeStreamId ?? null;
795
1252
  }
796
1253
  /**
@@ -804,16 +1261,16 @@ var DrizzleAgentStore = class {
804
1261
  return byMessage;
805
1262
  }
806
1263
  const rows = await this.db.select({
807
- id: agentToolCall.id,
808
- messageId: agentToolCall.messageId,
809
- status: agentToolCall.status,
810
- approver: agentToolCall.approver,
811
- expiresAt: agentToolCall.expiresAt,
812
- remember: agentToolCall.remember,
813
- executedByRef: agentToolCall.executedByRef,
814
- decidedVia: agentToolCall.decidedVia,
815
- error: agentToolCall.error
816
- }).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));
817
1274
  for (const row of rows) {
818
1275
  const approval = (0, import_nestjs_agent_core.toolCallApprovalFromRow)({
819
1276
  ...row,
@@ -831,22 +1288,22 @@ var DrizzleAgentStore = class {
831
1288
  /** Tools whose approval someone asked to remember in this thread. */
832
1289
  async rememberedApprovals(threadId) {
833
1290
  const rows = await this.db.selectDistinct({
834
- toolName: agentToolCall.toolName
835
- }).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)));
836
1293
  return rows.map((row) => row.toolName);
837
1294
  }
838
1295
  async toolCallInput(toolCallId) {
839
1296
  const [row] = await this.db.select({
840
- input: agentToolCall.input
841
- }).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));
842
1299
  return row?.input ?? null;
843
1300
  }
844
1301
  async toolCallApproval(toolCallId) {
845
1302
  const [row] = await this.db.select({
846
- status: agentToolCall.status,
847
- approver: agentToolCall.approver,
848
- expiresAt: agentToolCall.expiresAt
849
- }).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));
850
1307
  if (row === void 0) {
851
1308
  return null;
852
1309
  }
@@ -858,27 +1315,67 @@ var DrizzleAgentStore = class {
858
1315
  }
859
1316
  async ownerOfActiveStream(runId) {
860
1317
  const [thread] = await this.db.select({
861
- actorRef: agentThread.actorRef
862
- }).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)));
863
1320
  return thread?.actorRef ?? null;
864
1321
  }
865
1322
  async setTitle(threadId, title) {
866
- await this.db.update(agentThread).set({
1323
+ await this.db.update(this.t.agentThread).set({
867
1324
  title,
868
1325
  updatedAt: /* @__PURE__ */ new Date()
869
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1326
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
870
1327
  }
871
1328
  async promoteThread(threadId) {
872
- await this.db.update(agentThread).set({
1329
+ await this.db.update(this.t.agentThread).set({
873
1330
  transient: false,
874
1331
  updatedAt: /* @__PURE__ */ new Date()
875
- }).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;
876
1373
  }
877
1374
  /** The run streaming the thread, or `null` — a projection of the one column. */
878
1375
  async activeRunForThread(threadId) {
879
1376
  const [thread] = await this.db.select({
880
- activeStreamId: agentThread.activeStreamId
881
- }).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)));
882
1379
  return thread?.activeStreamId ?? null;
883
1380
  }
884
1381
  /**
@@ -887,33 +1384,32 @@ var DrizzleAgentStore = class {
887
1384
  */
888
1385
  async claimActiveStream(threadId, runId, options = {}) {
889
1386
  const holders = [
890
- (0, import_drizzle_orm2.isNull)(agentThread.activeStreamId),
891
- (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),
892
1389
  ...options.replacing !== void 0 ? [
893
- (0, import_drizzle_orm2.eq)(agentThread.activeStreamId, options.replacing)
1390
+ (0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, options.replacing)
894
1391
  ] : []
895
1392
  ];
896
- const claimed = await this.db.update(agentThread).set({
1393
+ const claimed = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
897
1394
  activeStreamId: runId
898
- }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.or)(...holders))).returning({
899
- id: agentThread.id
900
- });
901
- 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;
902
1400
  }
903
1401
  async releaseActiveStream(threadId, runId) {
904
- const released = await this.db.update(agentThread).set({
1402
+ const released = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
905
1403
  activeStreamId: null
906
- }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(agentThread.id, threadId), (0, import_drizzle_orm2.eq)(agentThread.activeStreamId, runId))).returning({
907
- id: agentThread.id
908
- });
909
- 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;
910
1406
  }
911
1407
  async enqueueMessage(input) {
912
1408
  const now = /* @__PURE__ */ new Date();
913
1409
  const [edge] = await this.db.select({
914
- first: (0, import_drizzle_orm2.min)(agentQueuedMessage.position),
915
- last: (0, import_drizzle_orm2.max)(agentQueuedMessage.position)
916
- }).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));
917
1413
  const position = input.at === "head" ? (edge?.first ?? 1) - 1 : (edge?.last ?? -1) + 1;
918
1414
  const row = {
919
1415
  id: crypto.randomUUID(),
@@ -922,6 +1418,7 @@ var DrizzleAgentStore = class {
922
1418
  content: input.content,
923
1419
  attachments: input.attachments !== void 0 && input.attachments.length > 0 ? input.attachments : null,
924
1420
  agentName: input.agentName ?? null,
1421
+ persona: input.persona ?? null,
925
1422
  model: input.model ?? null,
926
1423
  pageContext: input.pageContext ?? null,
927
1424
  interrupt: input.interrupt === true,
@@ -929,15 +1426,15 @@ var DrizzleAgentStore = class {
929
1426
  createdAt: now,
930
1427
  updatedAt: now
931
1428
  };
932
- await this.db.insert(agentQueuedMessage).values(row);
1429
+ await this.db.insert(this.t.agentQueuedMessage).values(row);
933
1430
  return toQueuedMessage(row);
934
1431
  }
935
1432
  async listQueue(threadId) {
936
- 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));
937
1434
  return rows.map(toQueuedMessage);
938
1435
  }
939
1436
  async getQueuedMessage(id) {
940
- 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));
941
1438
  return row === void 0 ? null : toQueuedMessage(row);
942
1439
  }
943
1440
  async updateQueuedMessage(id, patch) {
@@ -953,52 +1450,47 @@ var DrizzleAgentStore = class {
953
1450
  if (patch.interrupt !== void 0) {
954
1451
  updates.interrupt = patch.interrupt;
955
1452
  }
956
- 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));
957
1454
  return this.getQueuedMessage(id);
958
1455
  }
959
1456
  /** Rewrites the thread's positions as 0..n-1 in the new order — a queue is a handful of rows. */
960
- async moveQueuedMessage(id, index2) {
1457
+ async moveQueuedMessage(id, index4) {
961
1458
  const moving = await this.getQueuedMessage(id);
962
1459
  if (moving === null) {
963
1460
  return false;
964
1461
  }
965
1462
  const order = (await this.listQueue(moving.threadId)).filter((message) => message.id !== id);
966
- 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)));
967
1464
  order.splice(target, 0, moving);
968
1465
  for (const [position, message] of order.entries()) {
969
- await this.db.update(agentQueuedMessage).set({
1466
+ await this.db.update(this.t.agentQueuedMessage).set({
970
1467
  position
971
- }).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.id, message.id));
1468
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, message.id));
972
1469
  }
973
1470
  return true;
974
1471
  }
975
1472
  async removeQueuedMessage(id) {
976
- const removed = await this.db.delete(agentQueuedMessage).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.id, id)).returning({
977
- id: agentQueuedMessage.id
978
- });
979
- 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;
980
1475
  }
981
1476
  async clearQueue(threadId) {
982
- const removed = await this.db.delete(agentQueuedMessage).where((0, import_drizzle_orm2.eq)(agentQueuedMessage.threadId, threadId)).returning({
983
- id: agentQueuedMessage.id
984
- });
985
- 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);
986
1478
  }
987
1479
  async queuePause(threadId) {
988
1480
  const [thread] = await this.db.select({
989
- queuePause: agentThread.queuePause
990
- }).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));
991
1483
  return thread?.queuePause ?? null;
992
1484
  }
993
1485
  async setQueuePause(threadId, pause) {
994
- await this.db.update(agentThread).set({
1486
+ await this.db.update(this.t.agentThread).set({
995
1487
  queuePause: pause
996
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1488
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
997
1489
  }
998
1490
  async setActiveStream(threadId, runId) {
999
- await this.db.update(agentThread).set({
1491
+ await this.db.update(this.t.agentThread).set({
1000
1492
  activeStreamId: runId
1001
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, threadId));
1493
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
1002
1494
  }
1003
1495
  /**
1004
1496
  * Patch a thread's `title` and/or `defaultAgent`. Each field is only touched when PRESENT in
@@ -1017,11 +1509,14 @@ var DrizzleAgentStore = class {
1017
1509
  if (patch.model !== void 0) {
1018
1510
  updates.model = patch.model;
1019
1511
  }
1512
+ if (patch.persona !== void 0) {
1513
+ updates.persona = patch.persona;
1514
+ }
1020
1515
  if (Object.keys(updates).length === 0) {
1021
1516
  return;
1022
1517
  }
1023
1518
  updates.updatedAt = /* @__PURE__ */ new Date();
1024
- 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));
1025
1520
  }
1026
1521
  /**
1027
1522
  * The thread's default agent, projected — the caller wants one nullable scalar to decide which
@@ -1031,14 +1526,21 @@ var DrizzleAgentStore = class {
1031
1526
  /** The thread's pinned model, projected like {@link defaultAgentForThread}. */
1032
1527
  async modelForThread(threadId) {
1033
1528
  const [thread] = await this.db.select({
1034
- model: agentThread.model
1035
- }).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)));
1036
1531
  return thread?.model ?? null;
1037
1532
  }
1533
+ /** The thread's pinned persona, projected like {@link defaultAgentForThread}. */
1534
+ async personaForThread(threadId) {
1535
+ const [thread] = await this.db.select({
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)));
1538
+ return thread?.persona ?? null;
1539
+ }
1038
1540
  async defaultAgentForThread(threadId) {
1039
1541
  const [thread] = await this.db.select({
1040
- defaultAgent: agentThread.defaultAgent
1041
- }).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)));
1042
1544
  return thread?.defaultAgent ?? null;
1043
1545
  }
1044
1546
  /**
@@ -1063,7 +1565,7 @@ var DrizzleAgentStore = class {
1063
1565
  promptHash: run.promptHash ?? null,
1064
1566
  parentRunId: run.parentRunId ?? null
1065
1567
  };
1066
- await this.db.insert(agentRun).values(runRow);
1568
+ await this.db.insert(this.t.agentRun).values(runRow);
1067
1569
  }
1068
1570
  /** Settle a run's outcome. A no-op when the run is unknown (mirrors `setTitle`/`updateThread`). */
1069
1571
  async recordRunEnd(end) {
@@ -1080,16 +1582,16 @@ var DrizzleAgentStore = class {
1080
1582
  if (end.errorMessage !== void 0) {
1081
1583
  updates.errorMessage = end.errorMessage;
1082
1584
  }
1083
- 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));
1084
1586
  }
1085
1587
  /** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */
1086
1588
  async bumpRunRetries(runId) {
1087
- await this.db.update(agentRun).set({
1088
- retries: import_drizzle_orm2.sql`${agentRun.retries} + 1`
1089
- }).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));
1090
1592
  }
1091
1593
  async appendMessage(input) {
1092
- 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));
1093
1595
  if (thread === void 0) {
1094
1596
  throw new Error(`thread ${input.threadId} not found`);
1095
1597
  }
@@ -1105,52 +1607,54 @@ var DrizzleAgentStore = class {
1105
1607
  followUps: input.followUps ?? null,
1106
1608
  usage: input.usage ?? null,
1107
1609
  agentName: input.agentName ?? null,
1610
+ persona: input.persona ?? null,
1108
1611
  runId: input.runId ?? null,
1109
1612
  reasoning: input.reasoning ?? null,
1110
1613
  reasoningMs: input.reasoningMs ?? null,
1111
1614
  ui: input.ui ?? null,
1112
1615
  feedback: null,
1616
+ seq: await this.nextMessageSeq(input.threadId),
1113
1617
  createdAt: now
1114
1618
  };
1115
- await this.db.insert(agentMessage).values(message);
1116
- 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({
1117
1621
  updatedAt: now
1118
- }).where((0, import_drizzle_orm2.eq)(agentThread.id, input.threadId));
1622
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, input.threadId));
1119
1623
  return this.toStoredMessage(message);
1120
1624
  }
1121
1625
  async setMessageToolResults(messageId, results) {
1122
- await this.db.update(agentMessage).set({
1626
+ await this.db.update(this.t.agentMessage).set({
1123
1627
  toolResults: results
1124
- }).where((0, import_drizzle_orm2.eq)(agentMessage.id, messageId));
1628
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
1125
1629
  }
1126
1630
  async setMessageUi(messageId, ui) {
1127
- await this.db.update(agentMessage).set({
1631
+ await this.db.update(this.t.agentMessage).set({
1128
1632
  ui: ui.length > 0 ? ui : null
1129
- }).where((0, import_drizzle_orm2.eq)(agentMessage.id, messageId));
1633
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
1130
1634
  }
1131
1635
  async threadOfMessage(messageId) {
1132
1636
  const [row] = await this.db.select({
1133
- threadId: agentMessage.threadId
1134
- }).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);
1135
1639
  return row?.threadId ?? null;
1136
1640
  }
1137
1641
  async setMessageFeedback(messageId, feedback) {
1138
- await this.db.update(agentMessage).set({
1642
+ await this.db.update(this.t.agentMessage).set({
1139
1643
  feedback
1140
- }).where((0, import_drizzle_orm2.eq)(agentMessage.id, messageId));
1644
+ }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
1141
1645
  }
1142
1646
  async truncateFrom(threadId, messageId) {
1143
- 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());
1144
1648
  const cutoff = messages.findIndex((message) => message.id === messageId);
1145
1649
  if (cutoff < 0) {
1146
1650
  return;
1147
1651
  }
1148
1652
  const doomedIds = messages.slice(cutoff).map((message) => message.id);
1149
- await this.db.delete(agentToolCall).where((0, import_drizzle_orm2.inArray)(agentToolCall.messageId, doomedIds));
1150
- 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));
1151
1655
  }
1152
1656
  async recordToolCall(input) {
1153
- await this.db.insert(agentToolCall).values({
1657
+ await this.db.insert(this.t.agentToolCall).values({
1154
1658
  id: input.toolCallId,
1155
1659
  messageId: input.messageId,
1156
1660
  toolName: input.toolName,
@@ -1195,18 +1699,18 @@ var DrizzleAgentStore = class {
1195
1699
  if (input.status === "executed" || input.status === "auto_executed") {
1196
1700
  updates.executedAt = /* @__PURE__ */ new Date();
1197
1701
  }
1198
- 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));
1199
1703
  }
1200
1704
  async toolCallOutcomes(toolCallIds) {
1201
1705
  if (toolCallIds.length === 0) {
1202
1706
  return [];
1203
1707
  }
1204
1708
  const rows = await this.db.select({
1205
- id: agentToolCall.id,
1206
- status: agentToolCall.status,
1207
- output: agentToolCall.output,
1208
- error: agentToolCall.error
1209
- }).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, [
1210
1714
  ...toolCallIds
1211
1715
  ]));
1212
1716
  return rows.map((row) => ({
@@ -1221,14 +1725,14 @@ var DrizzleAgentStore = class {
1221
1725
  }));
1222
1726
  }
1223
1727
  async failUnsettledToolCalls(runId, error) {
1224
- 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"));
1225
1729
  const rows = await this.db.select({
1226
- id: agentToolCall.id
1227
- }).from(agentToolCall).where(pending);
1730
+ id: this.t.agentToolCall.id
1731
+ }).from(this.t.agentToolCall).where(pending);
1228
1732
  if (rows.length === 0) {
1229
1733
  return 0;
1230
1734
  }
1231
- await this.db.update(agentToolCall).set({
1735
+ await this.db.update(this.t.agentToolCall).set({
1232
1736
  status: "failed",
1233
1737
  error
1234
1738
  }).where(pending);
@@ -1253,11 +1757,11 @@ var DrizzleAgentStore = class {
1253
1757
  return [];
1254
1758
  }
1255
1759
  const rows = await this.db.select({
1256
- attachments: agentMessage.attachments
1257
- }).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)));
1258
1762
  const queued = await this.db.select({
1259
- attachments: agentQueuedMessage.attachments
1260
- }).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)));
1261
1765
  const wanted = new Set(mediaIds);
1262
1766
  const found = /* @__PURE__ */ new Set();
1263
1767
  for (const row of [
@@ -1275,7 +1779,7 @@ var DrizzleAgentStore = class {
1275
1779
  ].filter((mediaId) => found.has(mediaId));
1276
1780
  }
1277
1781
  async recordUsage(input) {
1278
- await this.db.insert(agentTokenUsage).values({
1782
+ await this.db.insert(this.t.agentTokenUsage).values({
1279
1783
  id: crypto.randomUUID(),
1280
1784
  threadId: input.threadId,
1281
1785
  actorRef: input.actorRef,
@@ -1296,7 +1800,7 @@ var DrizzleAgentStore = class {
1296
1800
  async usageBetween(actorRef, fromDay, toDay) {
1297
1801
  const start = /* @__PURE__ */ new Date(`${fromDay}T00:00:00.000Z`);
1298
1802
  const end = /* @__PURE__ */ new Date(`${toDay}T23:59:59.999Z`);
1299
- 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)));
1300
1804
  const usedTokens = rows.reduce((sum2, row) => sum2 + row.inputTokens + row.outputTokens, 0);
1301
1805
  const costUsd = rows.reduce((sum2, row) => sum2 + (row.costUsd ?? 0), 0);
1302
1806
  return {
@@ -1315,6 +1819,7 @@ var DrizzleAgentStore = class {
1315
1819
  ...thread.model != null ? {
1316
1820
  model: thread.model
1317
1821
  } : {},
1822
+ persona: thread.persona ?? null,
1318
1823
  ...lastContent !== void 0 ? {
1319
1824
  lastMessagePreview: lastContent.slice(0, 120)
1320
1825
  } : {}
@@ -1344,6 +1849,9 @@ var DrizzleAgentStore = class {
1344
1849
  ...message.agentName != null ? {
1345
1850
  agentName: message.agentName
1346
1851
  } : {},
1852
+ ...message.persona != null ? {
1853
+ persona: message.persona
1854
+ } : {},
1347
1855
  ...message.runId != null ? {
1348
1856
  runId: message.runId
1349
1857
  } : {},
@@ -1374,6 +1882,9 @@ function toQueuedMessage(row) {
1374
1882
  ...row.agentName !== null ? {
1375
1883
  agentName: row.agentName
1376
1884
  } : {},
1885
+ ...row.persona !== null ? {
1886
+ persona: row.persona
1887
+ } : {},
1377
1888
  ...row.model !== null ? {
1378
1889
  model: row.model
1379
1890
  } : {},
@@ -1391,7 +1902,7 @@ __name(toQueuedMessage, "toQueuedMessage");
1391
1902
 
1392
1903
  // src/drizzle-governance-queries.ts
1393
1904
  var import_nestjs_agent_core2 = require("@dudousxd/nestjs-agent-core");
1394
- var import_drizzle_orm3 = require("drizzle-orm");
1905
+ var import_drizzle_orm4 = require("drizzle-orm");
1395
1906
  var UNCLASSIFIED_ERROR_CODE = "unknown";
1396
1907
  var DEFAULT_AGENT_BUCKET = "(default)";
1397
1908
  var TOOL_CALL_STATUSES = [
@@ -1504,11 +2015,15 @@ var DrizzleGovernanceQueries = class {
1504
2015
  static {
1505
2016
  __name(this, "DrizzleGovernanceQueries");
1506
2017
  }
1507
- db;
1508
2018
  pricingStore;
2019
+ db;
2020
+ dialect;
2021
+ t;
1509
2022
  constructor(db, pricingStore) {
1510
- this.db = db;
1511
2023
  this.pricingStore = pricingStore;
2024
+ this.dialect = agentDialectOf(db);
2025
+ this.t = agentTablesFor(this.dialect);
2026
+ this.db = asBuilder(db);
1512
2027
  }
1513
2028
  async loadPricing() {
1514
2029
  const prices = await this.pricingStore.listCurrentPrices();
@@ -1525,7 +2040,7 @@ var DrizzleGovernanceQueries = class {
1525
2040
  }
1526
2041
  async usageInRange(range) {
1527
2042
  const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
1528
- 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)));
1529
2044
  return rows.map(toUsageInput);
1530
2045
  }
1531
2046
  async spendByModel(range) {
@@ -1550,7 +2065,7 @@ var DrizzleGovernanceQueries = class {
1550
2065
  if (threadIds.length === 0) {
1551
2066
  return [];
1552
2067
  }
1553
- 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)));
1554
2069
  const threadsById = new Map(threads.map((thread) => [
1555
2070
  thread.id,
1556
2071
  {
@@ -1569,14 +2084,14 @@ var DrizzleGovernanceQueries = class {
1569
2084
  }
1570
2085
  async recentToolCalls(limit) {
1571
2086
  const rows = await this.db.select({
1572
- toolCallId: agentToolCall.id,
1573
- toolName: agentToolCall.toolName,
1574
- toolType: agentToolCall.toolType,
1575
- status: agentToolCall.status,
1576
- threadId: agentMessage.threadId,
1577
- createdAt: agentToolCall.createdAt,
1578
- runId: agentToolCall.runId
1579
- }).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);
1580
2095
  return rows.map((row) => ({
1581
2096
  toolCallId: row.toolCallId,
1582
2097
  toolName: row.toolName,
@@ -1604,9 +2119,9 @@ var DrizzleGovernanceQueries = class {
1604
2119
  return rollups;
1605
2120
  }
1606
2121
  const messageCounts = await this.db.select({
1607
- threadId: agentMessage.threadId,
1608
- value: (0, import_drizzle_orm3.count)()
1609
- }).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);
1610
2125
  for (const row of messageCounts) {
1611
2126
  const bucket = rollups.get(row.threadId);
1612
2127
  if (bucket !== void 0) {
@@ -1614,10 +2129,10 @@ var DrizzleGovernanceQueries = class {
1614
2129
  }
1615
2130
  }
1616
2131
  const usageTotals = await this.db.select({
1617
- threadId: agentTokenUsage.threadId,
1618
- inputTokens: (0, import_drizzle_orm3.sum)(agentTokenUsage.inputTokens),
1619
- outputTokens: (0, import_drizzle_orm3.sum)(agentTokenUsage.outputTokens)
1620
- }).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);
1621
2136
  for (const row of usageTotals) {
1622
2137
  const bucket = rollups.get(row.threadId);
1623
2138
  if (bucket !== void 0) {
@@ -1642,12 +2157,12 @@ var DrizzleGovernanceQueries = class {
1642
2157
  });
1643
2158
  }
1644
2159
  async recentThreads(limit) {
1645
- 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);
1646
2161
  return this.toThreadActivityRows(threads);
1647
2162
  }
1648
2163
  async runsInRange(range) {
1649
2164
  const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
1650
- 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)));
1651
2166
  }
1652
2167
  async runMetrics(range) {
1653
2168
  const runs = await this.runsInRange(range);
@@ -1704,7 +2219,7 @@ var DrizzleGovernanceQueries = class {
1704
2219
  }
1705
2220
  async runErrors(range) {
1706
2221
  const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
1707
- 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")));
1708
2223
  const byError = /* @__PURE__ */ new Map();
1709
2224
  for (const run of runs) {
1710
2225
  const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;
@@ -1744,7 +2259,7 @@ var DrizzleGovernanceQueries = class {
1744
2259
  return result;
1745
2260
  }
1746
2261
  async recentRuns(limit) {
1747
- 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);
1748
2263
  return runs.map(toRecentRunRow);
1749
2264
  }
1750
2265
  /**
@@ -1754,16 +2269,16 @@ var DrizzleGovernanceQueries = class {
1754
2269
  */
1755
2270
  async pendingApprovals(limit) {
1756
2271
  const rows = await this.db.select({
1757
- toolCallId: agentToolCall.id,
1758
- toolName: agentToolCall.toolName,
1759
- input: agentToolCall.input,
1760
- threadId: agentThread.id,
1761
- threadTitle: agentThread.title,
1762
- actorRef: agentThread.actorRef,
1763
- agentName: agentMessage.agentName,
1764
- requestedAt: agentToolCall.createdAt,
1765
- runId: agentToolCall.runId
1766
- }).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);
1767
2282
  return rows.map((row) => ({
1768
2283
  toolCallId: row.toolCallId,
1769
2284
  toolName: row.toolName,
@@ -1785,11 +2300,11 @@ var DrizzleGovernanceQueries = class {
1785
2300
  */
1786
2301
  async toolStats(range) {
1787
2302
  const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
1788
- 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)));
1789
2304
  const byTool = /* @__PURE__ */ new Map();
1790
2305
  for (const call of calls) {
1791
- const key = `${call.toolName} ${call.toolType}`;
1792
- const bucket = byTool.get(key) ?? {
2306
+ const key2 = `${call.toolName} ${call.toolType}`;
2307
+ const bucket = byTool.get(key2) ?? {
1793
2308
  toolName: call.toolName,
1794
2309
  toolType: call.toolType,
1795
2310
  calls: 0,
@@ -1803,7 +2318,7 @@ var DrizzleGovernanceQueries = class {
1803
2318
  if (call.executionMs != null) {
1804
2319
  bucket.executionMs.push(call.executionMs);
1805
2320
  }
1806
- byTool.set(key, bucket);
2321
+ byTool.set(key2, bucket);
1807
2322
  }
1808
2323
  const result = [];
1809
2324
  for (const bucket of byTool.values()) {
@@ -1835,19 +2350,19 @@ var DrizzleGovernanceQueries = class {
1835
2350
  if (filters?.toolType !== void 0 && !isToolKind(filters.toolType)) {
1836
2351
  return emptyPage(query);
1837
2352
  }
1838
- 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);
1839
2354
  const [totalRow] = await this.db.select({
1840
- value: (0, import_drizzle_orm3.count)()
1841
- }).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);
1842
2357
  const rows = await this.db.select({
1843
- toolCallId: agentToolCall.id,
1844
- toolName: agentToolCall.toolName,
1845
- toolType: agentToolCall.toolType,
1846
- status: agentToolCall.status,
1847
- threadId: agentMessage.threadId,
1848
- createdAt: agentToolCall.createdAt,
1849
- runId: agentToolCall.runId
1850
- }).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);
1851
2366
  return {
1852
2367
  rows: rows.map((row) => ({
1853
2368
  toolCallId: row.toolCallId,
@@ -1871,11 +2386,11 @@ var DrizzleGovernanceQueries = class {
1871
2386
  */
1872
2387
  async threadsPage(query) {
1873
2388
  const filters = query.where;
1874
- 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);
1875
2390
  const [totalRow] = await this.db.select({
1876
- value: (0, import_drizzle_orm3.count)()
1877
- }).from(agentThread).where(whereClause);
1878
- 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);
1879
2394
  const rows = await this.toThreadActivityRows(threads);
1880
2395
  return {
1881
2396
  rows,
@@ -1893,11 +2408,11 @@ var DrizzleGovernanceQueries = class {
1893
2408
  if (filters?.status !== void 0 && !isRunStatus(filters.status)) {
1894
2409
  return emptyPage(query);
1895
2410
  }
1896
- 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);
1897
2412
  const [totalRow] = await this.db.select({
1898
- value: (0, import_drizzle_orm3.count)()
1899
- }).from(agentRun).where(whereClause);
1900
- 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);
1901
2416
  return {
1902
2417
  rows: runs.map(toRecentRunRow),
1903
2418
  total: totalRow?.value ?? 0,
@@ -1917,21 +2432,21 @@ var DrizzleGovernanceQueries = class {
1917
2432
  */
1918
2433
  async approvalsPage(query) {
1919
2434
  const filters = query.where;
1920
- 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);
1921
2436
  const [totalRow] = await this.db.select({
1922
- value: (0, import_drizzle_orm3.count)()
1923
- }).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);
1924
2439
  const rows = await this.db.select({
1925
- toolCallId: agentToolCall.id,
1926
- toolName: agentToolCall.toolName,
1927
- input: agentToolCall.input,
1928
- threadId: agentThread.id,
1929
- threadTitle: agentThread.title,
1930
- actorRef: agentThread.actorRef,
1931
- agentName: agentMessage.agentName,
1932
- requestedAt: agentToolCall.createdAt,
1933
- runId: agentToolCall.runId
1934
- }).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);
1935
2450
  return {
1936
2451
  rows: rows.map((row) => ({
1937
2452
  toolCallId: row.toolCallId,
@@ -1956,13 +2471,13 @@ var DrizzleGovernanceQueries = class {
1956
2471
  */
1957
2472
  async runDetail(runId) {
1958
2473
  const [row] = await this.db.select({
1959
- run: agentRun,
1960
- thread: agentThread
1961
- }).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);
1962
2477
  if (row === void 0) {
1963
2478
  return null;
1964
2479
  }
1965
- 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));
1966
2481
  return {
1967
2482
  run: toRecentRunRow(row.run),
1968
2483
  thread: {
@@ -1981,22 +2496,27 @@ var DrizzleGovernanceQueries = class {
1981
2496
  * message. Soft-deleted threads are returned with `deleted: true`; an audit still needs them.
1982
2497
  */
1983
2498
  async threadDetail(query) {
1984
- 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);
1985
2500
  if (thread === void 0) {
1986
2501
  return null;
1987
2502
  }
1988
2503
  const pricing = await this.loadPricing();
1989
- 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));
1990
2505
  const usage = (0, import_nestjs_agent_core2.rollupThreadUsage)(usageRows.map(toUsageInput), pricing);
1991
2506
  const [messageCountRow] = await this.db.select({
1992
- value: (0, import_drizzle_orm3.count)()
1993
- }).from(agentMessage).where((0, import_drizzle_orm3.eq)(agentMessage.threadId, thread.id));
1994
- 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);
1995
2515
  const toolCallCounts = await this.toolCallCountsByMessage(messages.map((message) => message.id));
1996
2516
  const [runTotalRow] = await this.db.select({
1997
- value: (0, import_drizzle_orm3.count)()
1998
- }).from(agentRun).where((0, import_drizzle_orm3.eq)(agentRun.threadId, thread.id));
1999
- 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);
2000
2520
  return {
2001
2521
  thread: {
2002
2522
  threadId: thread.id,
@@ -2031,9 +2551,9 @@ var DrizzleGovernanceQueries = class {
2031
2551
  return counts;
2032
2552
  }
2033
2553
  const rows = await this.db.select({
2034
- messageId: agentToolCall.messageId,
2035
- value: (0, import_drizzle_orm3.count)()
2036
- }).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);
2037
2557
  for (const row of rows) {
2038
2558
  counts.set(row.messageId, row.value);
2039
2559
  }
@@ -2043,7 +2563,7 @@ var DrizzleGovernanceQueries = class {
2043
2563
 
2044
2564
  // src/drizzle-memory-provider.ts
2045
2565
  var import_nestjs_agent_core3 = require("@dudousxd/nestjs-agent-core");
2046
- var import_drizzle_orm4 = require("drizzle-orm");
2566
+ var import_drizzle_orm5 = require("drizzle-orm");
2047
2567
  function toRecord(row) {
2048
2568
  return {
2049
2569
  id: row.id,
@@ -2072,8 +2592,12 @@ var DrizzleMemoryProvider = class {
2072
2592
  __name(this, "DrizzleMemoryProvider");
2073
2593
  }
2074
2594
  db;
2595
+ dialect;
2596
+ t;
2075
2597
  constructor(db) {
2076
- this.db = db;
2598
+ this.dialect = agentDialectOf(db);
2599
+ this.t = agentTablesFor(this.dialect);
2600
+ this.db = asBuilder(db);
2077
2601
  }
2078
2602
  /**
2079
2603
  * Every memory visible at `scopes` — asked on EVERY turn, so it is one indexed `scope in (…)`
@@ -2087,7 +2611,7 @@ var DrizzleMemoryProvider = class {
2087
2611
  if (scopes.length === 0) {
2088
2612
  return [];
2089
2613
  }
2090
- 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, [
2091
2615
  ...scopes
2092
2616
  ]));
2093
2617
  return rows.map(toRecord);
@@ -2103,10 +2627,8 @@ var DrizzleMemoryProvider = class {
2103
2627
  * answer cannot be used to find out which memories exist about other people.
2104
2628
  */
2105
2629
  async forget({ id, ctx }) {
2106
- 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({
2107
- id: agentMemory.id
2108
- });
2109
- 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;
2110
2632
  }
2111
2633
  /**
2112
2634
  * Upsert on (`scope`, `key`) — one statement, against the unique index, rather than a read
@@ -2119,7 +2641,7 @@ var DrizzleMemoryProvider = class {
2119
2641
  * rewriting `createdAt` would lose when the belief was first formed; reassigning `id` would
2120
2642
  * invalidate the delete handle a person was already shown.
2121
2643
  */
2122
- async write({ key, text: text2, scope, origin, ctx }) {
2644
+ async write({ key: key2, text: text3, scope, origin, ctx }) {
2123
2645
  assertAuthorMayWriteScope({
2124
2646
  scope,
2125
2647
  origin,
@@ -2132,28 +2654,40 @@ var DrizzleMemoryProvider = class {
2132
2654
  originRunId: origin.runId ?? null,
2133
2655
  originActorRef: origin.actorRef ?? null
2134
2656
  };
2135
- 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({
2136
2664
  id: crypto.randomUUID(),
2137
2665
  scope,
2138
- key,
2139
- text: text2,
2666
+ key: key2,
2667
+ text: text3,
2140
2668
  ...columns,
2141
2669
  pinned: false,
2142
2670
  createdAt: now,
2143
2671
  updatedAt: now
2144
- }).onConflictDoUpdate({
2145
- target: [
2146
- agentMemory.scope,
2147
- agentMemory.key
2148
- ],
2149
- set: {
2150
- text: text2,
2151
- ...columns,
2152
- updatedAt: now
2153
- }
2154
- }).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
+ }
2155
2689
  if (row === void 0) {
2156
- 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.`);
2157
2691
  }
2158
2692
  return toRecord(row);
2159
2693
  }
@@ -2166,13 +2700,11 @@ var DrizzleMemoryProvider = class {
2166
2700
  * `false` where there is no such id.
2167
2701
  */
2168
2702
  async pin({ id, pinned }) {
2169
- const updated = await this.db.update(agentMemory).set({
2703
+ const updated = await affectedRows(this.dialect, this.db.update(this.t.agentMemory).set({
2170
2704
  pinned,
2171
2705
  updatedAt: /* @__PURE__ */ new Date()
2172
- }).where((0, import_drizzle_orm4.eq)(agentMemory.id, id)).returning({
2173
- id: agentMemory.id
2174
- });
2175
- return updated.length > 0;
2706
+ }).where((0, import_drizzle_orm5.eq)(this.t.agentMemory.id, id)), this.t.agentMemory.id);
2707
+ return updated > 0;
2176
2708
  }
2177
2709
  };
2178
2710
  function assertAuthorMayWriteScope({ scope, origin, ctx }) {
@@ -2184,20 +2716,24 @@ function assertAuthorMayWriteScope({ scope, origin, ctx }) {
2184
2716
  __name(assertAuthorMayWriteScope, "assertAuthorMayWriteScope");
2185
2717
 
2186
2718
  // src/drizzle-pricing-store.ts
2187
- var import_drizzle_orm5 = require("drizzle-orm");
2719
+ var import_drizzle_orm6 = require("drizzle-orm");
2188
2720
  var DrizzlePricingStore = class {
2189
2721
  static {
2190
2722
  __name(this, "DrizzlePricingStore");
2191
2723
  }
2192
2724
  db;
2725
+ dialect;
2726
+ t;
2193
2727
  constructor(db) {
2194
- this.db = db;
2728
+ this.dialect = agentDialectOf(db);
2729
+ this.t = agentTablesFor(this.dialect);
2730
+ this.db = asBuilder(db);
2195
2731
  }
2196
2732
  async upsertModelPrice(input) {
2197
- await this.db.update(agentModelPricing).set({
2733
+ await this.db.update(this.t.agentModelPricing).set({
2198
2734
  isCurrent: false
2199
- }).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.eq)(agentModelPricing.modelId, input.modelId), (0, import_drizzle_orm5.eq)(agentModelPricing.isCurrent, true)));
2200
- 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({
2201
2737
  id: crypto.randomUUID(),
2202
2738
  modelId: input.modelId,
2203
2739
  inputPricePer1m: input.inputPricePer1m,
@@ -2209,7 +2745,7 @@ var DrizzlePricingStore = class {
2209
2745
  });
2210
2746
  }
2211
2747
  async listCurrentPrices() {
2212
- 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));
2213
2749
  return rows.map((row) => ({
2214
2750
  modelId: row.modelId,
2215
2751
  inputPricePer1m: row.inputPricePer1m,
@@ -2227,52 +2763,47 @@ var DrizzlePricingStore = class {
2227
2763
 
2228
2764
  // src/drizzle-token-stream-sink.ts
2229
2765
  var import_nestjs_agent_core4 = require("@dudousxd/nestjs-agent-core");
2230
- var import_drizzle_orm6 = require("drizzle-orm");
2231
- function isUniqueViolation(error) {
2232
- for (let current = error; current !== null && typeof current === "object"; ) {
2233
- const code = current.code;
2234
- if (typeof code === "string" && code.startsWith("SQLITE_CONSTRAINT")) return true;
2235
- current = current.cause;
2236
- }
2237
- return false;
2238
- }
2239
- __name(isUniqueViolation, "isUniqueViolation");
2766
+ var import_drizzle_orm7 = require("drizzle-orm");
2240
2767
  var DrizzleStreamFrameTable = class {
2241
2768
  static {
2242
2769
  __name(this, "DrizzleStreamFrameTable");
2243
2770
  }
2244
2771
  db;
2772
+ dialect;
2773
+ t;
2245
2774
  constructor(db) {
2246
- this.db = db;
2775
+ this.dialect = agentDialectOf(db);
2776
+ this.t = agentTablesFor(this.dialect);
2777
+ this.db = asBuilder(db);
2247
2778
  }
2248
2779
  async append(runId, row) {
2249
- 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)
2250
2781
  SELECT ${runId}, COALESCE(MAX(seq), 0) + 1, ${row.frame}, ${row.error}, ${row.createdAt}
2251
2782
  FROM agent_stream_frame WHERE run_id = ${runId}`);
2252
2783
  }
2253
2784
  async read(runId, after, limit) {
2254
2785
  return this.db.select({
2255
- seq: agentStreamFrame.seq,
2256
- frame: agentStreamFrame.frame,
2257
- error: agentStreamFrame.error
2258
- }).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);
2259
2790
  }
2260
2791
  async has(runId) {
2261
2792
  const rows = await this.db.select({
2262
- seq: agentStreamFrame.seq
2263
- }).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);
2264
2795
  return rows.length > 0;
2265
2796
  }
2266
2797
  async remove(runIds) {
2267
2798
  if (runIds.length === 0) return;
2268
- 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, [
2269
2800
  ...runIds
2270
2801
  ]));
2271
2802
  }
2272
2803
  async lapsedRuns(cutoff) {
2273
2804
  const rows = await this.db.select({
2274
- runId: agentStreamFrame.runId
2275
- }).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));
2276
2807
  return rows.map((row) => row.runId);
2277
2808
  }
2278
2809
  isUniqueViolation(error) {
@@ -2289,54 +2820,60 @@ var DrizzleTokenStreamSink = class extends import_nestjs_agent_core4.SqlTokenStr
2289
2820
  };
2290
2821
 
2291
2822
  // src/drizzle-confirm-token-store.ts
2292
- var import_drizzle_orm7 = require("drizzle-orm");
2823
+ var import_drizzle_orm8 = require("drizzle-orm");
2293
2824
  var DrizzleConfirmTokenStore = class {
2294
2825
  static {
2295
2826
  __name(this, "DrizzleConfirmTokenStore");
2296
2827
  }
2297
2828
  db;
2829
+ dialect;
2830
+ t;
2298
2831
  constructor(db) {
2299
- this.db = db;
2832
+ this.dialect = agentDialectOf(db);
2833
+ this.t = agentTablesFor(this.dialect);
2834
+ this.db = asBuilder(db);
2300
2835
  }
2301
2836
  async claim(input) {
2302
- const inserted = await this.db.insert(agentConfirmToken).values({
2837
+ const row = {
2303
2838
  hash: input.hash,
2304
2839
  actorRef: input.actorRef,
2305
2840
  tool: input.tool,
2306
2841
  expiresAt: input.expiresAt,
2307
2842
  createdAt: Date.now()
2308
- }).onConflictDoNothing().returning({
2309
- hash: agentConfirmToken.hash
2310
- });
2311
- 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;
2312
2851
  }
2313
2852
  async release(hash) {
2314
- 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));
2315
2854
  }
2316
2855
  async purgeExpired(now = Date.now()) {
2317
- const purged = await this.db.delete(agentConfirmToken).where((0, import_drizzle_orm7.lt)(agentConfirmToken.expiresAt, now)).returning({
2318
- hash: agentConfirmToken.hash
2319
- });
2320
- 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);
2321
2858
  }
2322
2859
  };
2323
2860
 
2324
2861
  // src/drizzle-rag-ingestion-log.ts
2325
2862
  var import_node_diagnostics_channel = require("diagnostics_channel");
2326
2863
  var import_common = require("@nestjs/common");
2327
- var import_drizzle_orm8 = require("drizzle-orm");
2328
- function _ts_decorate(decorators, target, key, desc4) {
2329
- 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;
2330
2867
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2331
- r = Reflect.decorate(decorators, target, key, desc4);
2868
+ r = Reflect.decorate(decorators, target, key2, desc4);
2332
2869
  } else {
2333
2870
  for (var i = decorators.length - 1; i >= 0; i--) {
2334
2871
  if (d = decorators[i]) {
2335
- 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;
2336
2873
  }
2337
2874
  }
2338
2875
  }
2339
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2876
+ return c > 3 && r && Object.defineProperty(target, key2, r), r;
2340
2877
  }
2341
2878
  __name(_ts_decorate, "_ts_decorate");
2342
2879
  function _ts_metadata(metadataKey, metadataValue) {
@@ -2372,8 +2909,8 @@ function num(value) {
2372
2909
  }
2373
2910
  __name(num, "num");
2374
2911
  var RAG_INGESTION_LOG_PAGE_ORDER = [
2375
- (0, import_drizzle_orm8.desc)(ragIngestionLog.updatedAt),
2376
- (0, import_drizzle_orm8.asc)(ragIngestionLog.documentId)
2912
+ (0, import_drizzle_orm9.desc)(ragIngestionLog.updatedAt),
2913
+ (0, import_drizzle_orm9.asc)(ragIngestionLog.documentId)
2377
2914
  ];
2378
2915
  var DEFAULT_PAGE_SIZE = 200;
2379
2916
  var DEFAULT_BATCH_SIZE = 200;
@@ -2382,20 +2919,27 @@ function batches(batchSize) {
2382
2919
  return Number.isFinite(requested) && requested >= 1 ? requested : DEFAULT_BATCH_SIZE;
2383
2920
  }
2384
2921
  __name(batches, "batches");
2385
- var CURSOR_COLUMNS = {
2386
- documentId: ragIngestionLog.documentId,
2387
- updatedAt: ragIngestionLog.updatedAt
2388
- };
2922
+ function cursorColumns(log) {
2923
+ return {
2924
+ documentId: log.documentId,
2925
+ updatedAt: log.updatedAt
2926
+ };
2927
+ }
2928
+ __name(cursorColumns, "cursorColumns");
2389
2929
  var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2390
2930
  static {
2391
2931
  __name(this, "DrizzleRagIngestionLog");
2392
2932
  }
2393
- db;
2394
2933
  logger = new import_common.Logger(_DrizzleRagIngestionLog.name);
2395
2934
  teardowns = [];
2396
2935
  inFlight = /* @__PURE__ */ new Set();
2936
+ db;
2937
+ dialect;
2938
+ t;
2397
2939
  constructor(db) {
2398
- this.db = db;
2940
+ this.dialect = agentDialectOf(db);
2941
+ this.t = agentTablesFor(this.dialect);
2942
+ this.db = asBuilder(db);
2399
2943
  }
2400
2944
  onModuleInit() {
2401
2945
  for (const channel of CHANNELS) {
@@ -2424,7 +2968,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2424
2968
  }
2425
2969
  /** The latest recorded outcome per document, newest first. */
2426
2970
  async list(query = {}) {
2427
- 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);
2428
2972
  return query.offset === void 0 ? rows : rows.offset(query.offset);
2429
2973
  }
2430
2974
  /**
@@ -2437,8 +2981,8 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2437
2981
  */
2438
2982
  async listPage(query = {}) {
2439
2983
  const [totalRow] = await this.db.select({
2440
- value: (0, import_drizzle_orm8.count)()
2441
- }).from(ragIngestionLog).where(this.where(query));
2984
+ value: (0, import_drizzle_orm9.count)()
2985
+ }).from(this.t.ragIngestionLog).where(this.where(query));
2442
2986
  return {
2443
2987
  rows: await this.list(query),
2444
2988
  total: totalRow?.value ?? 0
@@ -2491,7 +3035,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2491
3035
  * sweep is run. A sweep that stops early stops by `break`ing out of the `for await`.
2492
3036
  */
2493
3037
  iterate(where = {}, options = {}) {
2494
- 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));
2495
3039
  }
2496
3040
  /**
2497
3041
  * Just the document ids of the matching rows, in {@link RAG_INGESTION_LOG_PAGE_ORDER}.
@@ -2508,7 +3052,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2508
3052
  */
2509
3053
  async listDocumentIds(where = {}, options = {}) {
2510
3054
  const ids = [];
2511
- 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));
2512
3056
  for await (const row of rows) {
2513
3057
  ids.push(row.documentId);
2514
3058
  }
@@ -2516,22 +3060,18 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2516
3060
  }
2517
3061
  /** The latest recorded outcome for one document, or null if it was never attempted. */
2518
3062
  async get(documentId) {
2519
- 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));
2520
3064
  return row ?? null;
2521
3065
  }
2522
3066
  /** Forget one document's record. Returns whether a row was actually removed. */
2523
3067
  async remove(documentId) {
2524
- const removed = await this.db.delete(ragIngestionLog).where((0, import_drizzle_orm8.eq)(ragIngestionLog.documentId, documentId)).returning({
2525
- documentId: ragIngestionLog.documentId
2526
- });
2527
- 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;
2528
3070
  }
2529
3071
  /** Forget every record for a collection — for when the collection itself is deleted. */
2530
3072
  async removeByCollection(collection) {
2531
- const removed = await this.db.delete(ragIngestionLog).where((0, import_drizzle_orm8.eq)(ragIngestionLog.collection, collection)).returning({
2532
- documentId: ragIngestionLog.documentId
2533
- });
2534
- 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;
2535
3075
  }
2536
3076
  /**
2537
3077
  * The keyset sweep both {@link iterate} and {@link listDocumentIds} are made of. `page` decides
@@ -2560,7 +3100,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2560
3100
  }
2561
3101
  }
2562
3102
  where(query) {
2563
- 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);
2564
3104
  }
2565
3105
  /**
2566
3106
  * The coordinates filter AND'd with "strictly after `cursor` in
@@ -2575,7 +3115,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2575
3115
  if (cursor === void 0) {
2576
3116
  return base;
2577
3117
  }
2578
- 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))));
2579
3119
  }
2580
3120
  /**
2581
3121
  * Upsert one outcome. Keyed by document id so the row always reflects the *current* state — a
@@ -2623,14 +3163,11 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2623
3163
  size
2624
3164
  } : {}
2625
3165
  };
2626
- await this.db.insert(ragIngestionLog).values({
3166
+ await upsert(this.dialect, this.db.insert(this.t.ragIngestionLog).values({
2627
3167
  documentId,
2628
3168
  createdAt: now,
2629
3169
  ...outcome
2630
- }).onConflictDoUpdate({
2631
- target: ragIngestionLog.documentId,
2632
- set: outcome
2633
- });
3170
+ }), this.t.ragIngestionLog.documentId, outcome);
2634
3171
  } catch (error) {
2635
3172
  this.logger.warn(`Could not record RAG ingestion outcome for ${documentId}: ${error instanceof Error ? error.message : String(error)}`);
2636
3173
  }
@@ -2653,18 +3190,18 @@ DrizzleRagIngestionLog = _ts_decorate([
2653
3190
  // src/drizzle-agent-store.module.ts
2654
3191
  var import_nestjs_agent_core5 = require("@dudousxd/nestjs-agent-core");
2655
3192
  var import_common2 = require("@nestjs/common");
2656
- function _ts_decorate2(decorators, target, key, desc4) {
2657
- 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;
2658
3195
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2659
- r = Reflect.decorate(decorators, target, key, desc4);
3196
+ r = Reflect.decorate(decorators, target, key2, desc4);
2660
3197
  } else {
2661
3198
  for (var i = decorators.length - 1; i >= 0; i--) {
2662
3199
  if (d = decorators[i]) {
2663
- 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;
2664
3201
  }
2665
3202
  }
2666
3203
  }
2667
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3204
+ return c > 3 && r && Object.defineProperty(target, key2, r), r;
2668
3205
  }
2669
3206
  __name(_ts_decorate2, "_ts_decorate");
2670
3207
  var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
@@ -2765,17 +3302,21 @@ DrizzleAgentStoreModule = _ts_decorate2([
2765
3302
  DrizzleTokenStreamSink,
2766
3303
  RAG_INGESTION_LOG_PAGE_ORDER,
2767
3304
  agentConfirmToken,
3305
+ agentDialectOf,
2768
3306
  agentMemory,
2769
3307
  agentMessage,
2770
3308
  agentModelPricing,
2771
3309
  agentQueuedMessage,
2772
3310
  agentRun,
2773
3311
  agentSchema,
3312
+ agentSchemaDdl,
2774
3313
  agentStreamFrame,
2775
3314
  agentThread,
2776
3315
  agentTokenUsage,
2777
3316
  agentToolCall,
2778
3317
  ensureAgentSchema,
3318
+ mysqlAgentSchema,
3319
+ pgAgentSchema,
2779
3320
  ragIngestionLog
2780
3321
  });
2781
3322
  //# sourceMappingURL=index.cjs.map