@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/README.md +48 -9
- package/dist/index.cjs +1126 -585
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4918 -17
- package/dist/index.d.ts +4918 -17
- package/dist/index.js +1102 -565
- package/dist/index.js.map +1 -1
- package/package.json +7 -4
package/dist/index.js
CHANGED
|
@@ -16,6 +16,8 @@ var agentThread = sqliteTable("agent_thread", {
|
|
|
16
16
|
defaultAgent: text("default_agent"),
|
|
17
17
|
/** The model every turn on this thread runs on unless the send names one; `null` → default. */
|
|
18
18
|
model: text("model"),
|
|
19
|
+
/** The persona a send on this thread runs under when it names none; `null` → the agent's default. */
|
|
20
|
+
persona: text("persona"),
|
|
19
21
|
/** Why the thread's message queue stopped draining; `null` → it drains. */
|
|
20
22
|
queuePause: text("queue_pause", {
|
|
21
23
|
mode: "json"
|
|
@@ -55,6 +57,8 @@ var agentMessage = sqliteTable("agent_message", {
|
|
|
55
57
|
mode: "json"
|
|
56
58
|
}).$type(),
|
|
57
59
|
agentName: text("agent_name"),
|
|
60
|
+
/** The persona the turn that wrote this message ran under; `null` → none. */
|
|
61
|
+
persona: text("persona"),
|
|
58
62
|
runId: text("run_id"),
|
|
59
63
|
/** The step's streamed thinking; `null` when the model produced none. */
|
|
60
64
|
reasoning: text("reasoning"),
|
|
@@ -67,6 +71,12 @@ var agentMessage = sqliteTable("agent_message", {
|
|
|
67
71
|
feedback: text("feedback", {
|
|
68
72
|
mode: "json"
|
|
69
73
|
}).$type(),
|
|
74
|
+
/**
|
|
75
|
+
* The message's place in its thread, 1-based, assigned on append — what orders a transcript.
|
|
76
|
+
* `created_at` cannot: two messages of one turn routinely share a timestamp, and the uuid that
|
|
77
|
+
* broke the tie is random. `null` on a row from before the column; those sort first.
|
|
78
|
+
*/
|
|
79
|
+
seq: integer("seq"),
|
|
70
80
|
createdAt: integer("created_at", {
|
|
71
81
|
mode: "timestamp_ms"
|
|
72
82
|
}).notNull()
|
|
@@ -127,6 +137,8 @@ var agentQueuedMessage = sqliteTable("agent_queued_message", {
|
|
|
127
137
|
mode: "json"
|
|
128
138
|
}).$type(),
|
|
129
139
|
agentName: text("agent_name"),
|
|
140
|
+
/** The persona the send resolved — what the message starts under. */
|
|
141
|
+
persona: text("persona"),
|
|
130
142
|
model: text("model"),
|
|
131
143
|
pageContext: text("page_context", {
|
|
132
144
|
mode: "json"
|
|
@@ -299,285 +311,721 @@ var agentSchema = {
|
|
|
299
311
|
agentRun,
|
|
300
312
|
agentMemory,
|
|
301
313
|
ragIngestionLog,
|
|
302
|
-
agentConfirmToken
|
|
314
|
+
agentConfirmToken,
|
|
315
|
+
agentStreamFrame
|
|
303
316
|
};
|
|
304
317
|
|
|
305
318
|
// src/ensure-schema.ts
|
|
306
|
-
import { sql } from "drizzle-orm";
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
)
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
)
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
)
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
)
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
)
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
)
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
319
|
+
import { getTableName, sql } from "drizzle-orm";
|
|
320
|
+
import { getTableConfig as mysqlTableConfig } from "drizzle-orm/mysql-core";
|
|
321
|
+
import { getTableConfig as pgTableConfig } from "drizzle-orm/pg-core";
|
|
322
|
+
import { getTableConfig as sqliteTableConfig } from "drizzle-orm/sqlite-core";
|
|
323
|
+
|
|
324
|
+
// src/dialect.ts
|
|
325
|
+
import { is } from "drizzle-orm";
|
|
326
|
+
import { MySqlDatabase } from "drizzle-orm/mysql-core";
|
|
327
|
+
import { PgDatabase } from "drizzle-orm/pg-core";
|
|
328
|
+
|
|
329
|
+
// src/schema-mysql.ts
|
|
330
|
+
import { bigint, boolean, datetime, double, index as index2, int, json, longtext, mysqlTable, primaryKey as primaryKey2, uniqueIndex as uniqueIndex2, varchar } from "drizzle-orm/mysql-core";
|
|
331
|
+
var ts = /* @__PURE__ */ __name((name) => datetime(name, {
|
|
332
|
+
mode: "date",
|
|
333
|
+
fsp: 3
|
|
334
|
+
}), "ts");
|
|
335
|
+
var key = /* @__PURE__ */ __name((name) => varchar(name, {
|
|
336
|
+
length: 255
|
|
337
|
+
}), "key");
|
|
338
|
+
var agentThread2 = mysqlTable("agent_thread", {
|
|
339
|
+
id: key("id").primaryKey(),
|
|
340
|
+
actorRef: key("actor_ref").notNull(),
|
|
341
|
+
tenantRef: key("tenant_ref"),
|
|
342
|
+
title: key("title").notNull(),
|
|
343
|
+
transient: boolean("transient").notNull().default(false),
|
|
344
|
+
activeStreamId: key("active_stream_id"),
|
|
345
|
+
defaultAgent: key("default_agent"),
|
|
346
|
+
model: key("model"),
|
|
347
|
+
/** The persona a send on this thread runs under when it names none; `null` → the agent's default. */
|
|
348
|
+
persona: key("persona"),
|
|
349
|
+
queuePause: json("queue_pause").$type(),
|
|
350
|
+
createdAt: ts("created_at").notNull(),
|
|
351
|
+
updatedAt: ts("updated_at").notNull(),
|
|
352
|
+
deletedAt: ts("deleted_at")
|
|
353
|
+
}, (table) => [
|
|
354
|
+
index2("agent_thread_actor_updated_idx").on(table.actorRef, table.updatedAt)
|
|
355
|
+
]);
|
|
356
|
+
var agentMessage2 = mysqlTable("agent_message", {
|
|
357
|
+
id: key("id").primaryKey(),
|
|
358
|
+
threadId: key("thread_id").notNull().references(() => agentThread2.id, {
|
|
359
|
+
onDelete: "cascade"
|
|
360
|
+
}),
|
|
361
|
+
role: key("role").$type().notNull(),
|
|
362
|
+
content: longtext("content").notNull(),
|
|
363
|
+
toolCalls: json("tool_calls").$type(),
|
|
364
|
+
toolResults: json("tool_results").$type(),
|
|
365
|
+
attachments: json("attachments").$type(),
|
|
366
|
+
followUps: json("follow_ups").$type(),
|
|
367
|
+
usage: json("usage").$type(),
|
|
368
|
+
agentName: key("agent_name"),
|
|
369
|
+
/** The persona the turn that wrote this message ran under; `null` → none. */
|
|
370
|
+
persona: key("persona"),
|
|
371
|
+
runId: key("run_id"),
|
|
372
|
+
reasoning: longtext("reasoning"),
|
|
373
|
+
reasoningMs: int("reasoning_ms"),
|
|
374
|
+
ui: json("ui").$type(),
|
|
375
|
+
feedback: json("feedback").$type(),
|
|
376
|
+
seq: int("seq"),
|
|
377
|
+
createdAt: ts("created_at").notNull()
|
|
378
|
+
}, (table) => [
|
|
379
|
+
index2("agent_message_thread_created_idx").on(table.threadId, table.createdAt)
|
|
380
|
+
]);
|
|
381
|
+
var agentToolCall2 = mysqlTable("agent_tool_call", {
|
|
382
|
+
id: key("id").primaryKey(),
|
|
383
|
+
messageId: key("message_id").notNull().references(() => agentMessage2.id, {
|
|
384
|
+
onDelete: "cascade"
|
|
385
|
+
}),
|
|
386
|
+
toolName: key("tool_name").notNull(),
|
|
387
|
+
toolType: key("tool_type").$type().notNull(),
|
|
388
|
+
input: json("input"),
|
|
389
|
+
output: json("output"),
|
|
390
|
+
status: key("status").$type().notNull(),
|
|
391
|
+
executedByRef: key("executed_by_ref"),
|
|
392
|
+
executionMs: int("execution_ms"),
|
|
393
|
+
error: longtext("error"),
|
|
394
|
+
createdAt: ts("created_at").notNull(),
|
|
395
|
+
executedAt: ts("executed_at"),
|
|
396
|
+
runId: key("run_id"),
|
|
397
|
+
approver: key("approver"),
|
|
398
|
+
expiresAt: ts("expires_at"),
|
|
399
|
+
remember: boolean("remember"),
|
|
400
|
+
decidedVia: key("decided_via")
|
|
401
|
+
}, (table) => [
|
|
402
|
+
index2("agent_tool_call_message_idx").on(table.messageId)
|
|
403
|
+
]);
|
|
404
|
+
var agentQueuedMessage2 = mysqlTable("agent_queued_message", {
|
|
405
|
+
id: key("id").primaryKey(),
|
|
406
|
+
threadId: key("thread_id").notNull().references(() => agentThread2.id, {
|
|
407
|
+
onDelete: "cascade"
|
|
408
|
+
}),
|
|
409
|
+
actor: json("actor").$type().notNull(),
|
|
410
|
+
content: longtext("content").notNull(),
|
|
411
|
+
attachments: json("attachments").$type(),
|
|
412
|
+
agentName: key("agent_name"),
|
|
413
|
+
/** The persona the send resolved — what the message starts under. */
|
|
414
|
+
persona: key("persona"),
|
|
415
|
+
model: key("model"),
|
|
416
|
+
pageContext: json("page_context").$type(),
|
|
417
|
+
interrupt: boolean("interrupt").notNull().default(false),
|
|
418
|
+
position: int("position").notNull(),
|
|
419
|
+
createdAt: ts("created_at").notNull(),
|
|
420
|
+
updatedAt: ts("updated_at").notNull()
|
|
421
|
+
}, (table) => [
|
|
422
|
+
index2("agent_queued_message_thread_position_idx").on(table.threadId, table.position)
|
|
423
|
+
]);
|
|
424
|
+
var agentTokenUsage2 = mysqlTable("agent_token_usage", {
|
|
425
|
+
id: key("id").primaryKey(),
|
|
426
|
+
threadId: key("thread_id").notNull().references(() => agentThread2.id, {
|
|
427
|
+
onDelete: "cascade"
|
|
428
|
+
}),
|
|
429
|
+
actorRef: key("actor_ref").notNull(),
|
|
430
|
+
messageId: key("message_id"),
|
|
431
|
+
modelId: key("model_id").notNull(),
|
|
432
|
+
purpose: key("purpose").$type().notNull(),
|
|
433
|
+
inputTokens: int("input_tokens").notNull(),
|
|
434
|
+
outputTokens: int("output_tokens").notNull(),
|
|
435
|
+
cacheWriteTokens: int("cache_write_tokens"),
|
|
436
|
+
cacheReadTokens: int("cache_read_tokens"),
|
|
437
|
+
costUsd: double("cost_usd"),
|
|
438
|
+
createdAt: ts("created_at").notNull()
|
|
439
|
+
}, (table) => [
|
|
440
|
+
index2("agent_token_usage_actor_created_idx").on(table.actorRef, table.createdAt)
|
|
441
|
+
]);
|
|
442
|
+
var agentModelPricing2 = mysqlTable("agent_model_pricing", {
|
|
443
|
+
id: key("id").primaryKey(),
|
|
444
|
+
modelId: key("model_id").notNull(),
|
|
445
|
+
inputPricePer1m: double("input_price_per_1m").notNull(),
|
|
446
|
+
outputPricePer1m: double("output_price_per_1m").notNull(),
|
|
447
|
+
cacheWritePricePer1m: double("cache_write_price_per_1m"),
|
|
448
|
+
cacheReadPricePer1m: double("cache_read_price_per_1m"),
|
|
449
|
+
effectiveFrom: ts("effective_from").notNull(),
|
|
450
|
+
isCurrent: boolean("is_current").notNull()
|
|
451
|
+
});
|
|
452
|
+
var agentRun2 = mysqlTable("agent_run", {
|
|
453
|
+
id: key("id").primaryKey(),
|
|
454
|
+
threadId: key("thread_id").notNull().references(() => agentThread2.id, {
|
|
455
|
+
onDelete: "cascade"
|
|
456
|
+
}),
|
|
457
|
+
actorRef: key("actor_ref").notNull(),
|
|
458
|
+
agentName: key("agent_name"),
|
|
459
|
+
status: key("status").$type().notNull(),
|
|
460
|
+
durationMs: int("duration_ms"),
|
|
461
|
+
errorCode: key("error_code"),
|
|
462
|
+
errorMessage: longtext("error_message"),
|
|
463
|
+
retries: int("retries").notNull().default(0),
|
|
464
|
+
startedAt: ts("started_at").notNull(),
|
|
465
|
+
settledAt: ts("settled_at"),
|
|
466
|
+
promptHash: key("prompt_hash"),
|
|
467
|
+
parentRunId: key("parent_run_id")
|
|
468
|
+
}, (table) => [
|
|
469
|
+
index2("agent_run_started_idx").on(table.startedAt)
|
|
470
|
+
]);
|
|
471
|
+
var agentMemory2 = mysqlTable("agent_memory", {
|
|
472
|
+
id: key("id").primaryKey(),
|
|
473
|
+
scope: key("scope").notNull(),
|
|
474
|
+
key: key("key").notNull(),
|
|
475
|
+
text: longtext("text").notNull(),
|
|
476
|
+
originAuthor: key("origin_author").$type().notNull(),
|
|
477
|
+
originThreadId: key("origin_thread_id"),
|
|
478
|
+
originRunId: key("origin_run_id"),
|
|
479
|
+
originActorRef: key("origin_actor_ref"),
|
|
480
|
+
pinned: boolean("pinned").notNull().default(false),
|
|
481
|
+
createdAt: ts("created_at").notNull(),
|
|
482
|
+
updatedAt: ts("updated_at").notNull()
|
|
483
|
+
}, (table) => [
|
|
484
|
+
uniqueIndex2("agent_memory_scope_key_uq").on(table.scope, table.key)
|
|
485
|
+
]);
|
|
486
|
+
var ragIngestionLog2 = mysqlTable("rag_ingestion_log", {
|
|
487
|
+
documentId: key("document_id").primaryKey(),
|
|
488
|
+
status: key("status").$type().notNull(),
|
|
489
|
+
collection: key("collection"),
|
|
490
|
+
ownerType: key("owner_type"),
|
|
491
|
+
ownerId: key("owner_id"),
|
|
492
|
+
source: longtext("source"),
|
|
493
|
+
mimeType: key("mime_type"),
|
|
494
|
+
size: bigint("size", {
|
|
495
|
+
mode: "number"
|
|
496
|
+
}),
|
|
497
|
+
chunks: int("chunks"),
|
|
498
|
+
reason: key("reason"),
|
|
499
|
+
error: longtext("error"),
|
|
500
|
+
createdAt: ts("created_at").notNull(),
|
|
501
|
+
updatedAt: ts("updated_at").notNull()
|
|
502
|
+
}, (table) => [
|
|
503
|
+
index2("rag_ingestion_log_collection_idx").on(table.collection, table.updatedAt)
|
|
504
|
+
]);
|
|
505
|
+
var agentConfirmToken2 = mysqlTable("agent_confirm_token", {
|
|
506
|
+
hash: key("hash").primaryKey(),
|
|
507
|
+
actorRef: key("actor_ref").notNull(),
|
|
508
|
+
tool: key("tool").notNull(),
|
|
509
|
+
expiresAt: bigint("expires_at", {
|
|
510
|
+
mode: "number"
|
|
511
|
+
}).notNull(),
|
|
512
|
+
createdAt: bigint("created_at", {
|
|
513
|
+
mode: "number"
|
|
514
|
+
}).notNull()
|
|
515
|
+
}, (table) => [
|
|
516
|
+
index2("agent_confirm_token_expires_idx").on(table.expiresAt)
|
|
517
|
+
]);
|
|
518
|
+
var agentStreamFrame2 = mysqlTable("agent_stream_frame", {
|
|
519
|
+
runId: key("run_id").notNull(),
|
|
520
|
+
seq: int("seq").notNull(),
|
|
521
|
+
frame: longtext("frame"),
|
|
522
|
+
error: longtext("error"),
|
|
523
|
+
createdAt: bigint("created_at", {
|
|
524
|
+
mode: "number"
|
|
525
|
+
}).notNull()
|
|
526
|
+
}, (table) => [
|
|
527
|
+
primaryKey2({
|
|
528
|
+
columns: [
|
|
529
|
+
table.runId,
|
|
530
|
+
table.seq
|
|
531
|
+
]
|
|
532
|
+
})
|
|
533
|
+
]);
|
|
534
|
+
var mysqlAgentSchema = {
|
|
535
|
+
agentThread: agentThread2,
|
|
536
|
+
agentMessage: agentMessage2,
|
|
537
|
+
agentQueuedMessage: agentQueuedMessage2,
|
|
538
|
+
agentToolCall: agentToolCall2,
|
|
539
|
+
agentTokenUsage: agentTokenUsage2,
|
|
540
|
+
agentModelPricing: agentModelPricing2,
|
|
541
|
+
agentRun: agentRun2,
|
|
542
|
+
agentMemory: agentMemory2,
|
|
543
|
+
ragIngestionLog: ragIngestionLog2,
|
|
544
|
+
agentConfirmToken: agentConfirmToken2,
|
|
545
|
+
agentStreamFrame: agentStreamFrame2
|
|
546
|
+
};
|
|
547
|
+
|
|
548
|
+
// src/schema-pg.ts
|
|
549
|
+
import { bigint as bigint2, boolean as boolean2, doublePrecision, index as index3, integer as integer2, jsonb, pgTable, primaryKey as primaryKey3, text as text2, timestamp, uniqueIndex as uniqueIndex3 } from "drizzle-orm/pg-core";
|
|
550
|
+
var ts2 = /* @__PURE__ */ __name((name) => timestamp(name, {
|
|
551
|
+
withTimezone: true,
|
|
552
|
+
precision: 3,
|
|
553
|
+
mode: "date"
|
|
554
|
+
}), "ts");
|
|
555
|
+
var agentThread3 = pgTable("agent_thread", {
|
|
556
|
+
id: text2("id").primaryKey(),
|
|
557
|
+
actorRef: text2("actor_ref").notNull(),
|
|
558
|
+
tenantRef: text2("tenant_ref"),
|
|
559
|
+
title: text2("title").notNull(),
|
|
560
|
+
transient: boolean2("transient").notNull().default(false),
|
|
561
|
+
activeStreamId: text2("active_stream_id"),
|
|
562
|
+
defaultAgent: text2("default_agent"),
|
|
563
|
+
model: text2("model"),
|
|
564
|
+
/** The persona a send on this thread runs under when it names none; `null` → the agent's default. */
|
|
565
|
+
persona: text2("persona"),
|
|
566
|
+
queuePause: jsonb("queue_pause").$type(),
|
|
567
|
+
createdAt: ts2("created_at").notNull(),
|
|
568
|
+
updatedAt: ts2("updated_at").notNull(),
|
|
569
|
+
deletedAt: ts2("deleted_at")
|
|
570
|
+
}, (table) => [
|
|
571
|
+
index3("agent_thread_actor_updated_idx").on(table.actorRef, table.updatedAt)
|
|
572
|
+
]);
|
|
573
|
+
var agentMessage3 = pgTable("agent_message", {
|
|
574
|
+
id: text2("id").primaryKey(),
|
|
575
|
+
threadId: text2("thread_id").notNull().references(() => agentThread3.id, {
|
|
576
|
+
onDelete: "cascade"
|
|
577
|
+
}),
|
|
578
|
+
role: text2("role").$type().notNull(),
|
|
579
|
+
content: text2("content").notNull(),
|
|
580
|
+
toolCalls: jsonb("tool_calls").$type(),
|
|
581
|
+
toolResults: jsonb("tool_results").$type(),
|
|
582
|
+
attachments: jsonb("attachments").$type(),
|
|
583
|
+
followUps: jsonb("follow_ups").$type(),
|
|
584
|
+
usage: jsonb("usage").$type(),
|
|
585
|
+
agentName: text2("agent_name"),
|
|
586
|
+
/** The persona the turn that wrote this message ran under; `null` → none. */
|
|
587
|
+
persona: text2("persona"),
|
|
588
|
+
runId: text2("run_id"),
|
|
589
|
+
reasoning: text2("reasoning"),
|
|
590
|
+
reasoningMs: integer2("reasoning_ms"),
|
|
591
|
+
ui: jsonb("ui").$type(),
|
|
592
|
+
feedback: jsonb("feedback").$type(),
|
|
593
|
+
seq: integer2("seq"),
|
|
594
|
+
createdAt: ts2("created_at").notNull()
|
|
595
|
+
}, (table) => [
|
|
596
|
+
index3("agent_message_thread_created_idx").on(table.threadId, table.createdAt)
|
|
597
|
+
]);
|
|
598
|
+
var agentToolCall3 = pgTable("agent_tool_call", {
|
|
599
|
+
id: text2("id").primaryKey(),
|
|
600
|
+
messageId: text2("message_id").notNull().references(() => agentMessage3.id, {
|
|
601
|
+
onDelete: "cascade"
|
|
602
|
+
}),
|
|
603
|
+
toolName: text2("tool_name").notNull(),
|
|
604
|
+
toolType: text2("tool_type").$type().notNull(),
|
|
605
|
+
input: jsonb("input"),
|
|
606
|
+
output: jsonb("output"),
|
|
607
|
+
status: text2("status").$type().notNull(),
|
|
608
|
+
executedByRef: text2("executed_by_ref"),
|
|
609
|
+
executionMs: integer2("execution_ms"),
|
|
610
|
+
error: text2("error"),
|
|
611
|
+
createdAt: ts2("created_at").notNull(),
|
|
612
|
+
executedAt: ts2("executed_at"),
|
|
613
|
+
runId: text2("run_id"),
|
|
614
|
+
approver: text2("approver"),
|
|
615
|
+
expiresAt: ts2("expires_at"),
|
|
616
|
+
remember: boolean2("remember"),
|
|
617
|
+
decidedVia: text2("decided_via")
|
|
618
|
+
}, (table) => [
|
|
619
|
+
index3("agent_tool_call_message_idx").on(table.messageId)
|
|
620
|
+
]);
|
|
621
|
+
var agentQueuedMessage3 = pgTable("agent_queued_message", {
|
|
622
|
+
id: text2("id").primaryKey(),
|
|
623
|
+
threadId: text2("thread_id").notNull().references(() => agentThread3.id, {
|
|
624
|
+
onDelete: "cascade"
|
|
625
|
+
}),
|
|
626
|
+
actor: jsonb("actor").$type().notNull(),
|
|
627
|
+
content: text2("content").notNull(),
|
|
628
|
+
attachments: jsonb("attachments").$type(),
|
|
629
|
+
agentName: text2("agent_name"),
|
|
630
|
+
/** The persona the send resolved — what the message starts under. */
|
|
631
|
+
persona: text2("persona"),
|
|
632
|
+
model: text2("model"),
|
|
633
|
+
pageContext: jsonb("page_context").$type(),
|
|
634
|
+
interrupt: boolean2("interrupt").notNull().default(false),
|
|
635
|
+
position: integer2("position").notNull(),
|
|
636
|
+
createdAt: ts2("created_at").notNull(),
|
|
637
|
+
updatedAt: ts2("updated_at").notNull()
|
|
638
|
+
}, (table) => [
|
|
639
|
+
index3("agent_queued_message_thread_position_idx").on(table.threadId, table.position)
|
|
640
|
+
]);
|
|
641
|
+
var agentTokenUsage3 = pgTable("agent_token_usage", {
|
|
642
|
+
id: text2("id").primaryKey(),
|
|
643
|
+
threadId: text2("thread_id").notNull().references(() => agentThread3.id, {
|
|
644
|
+
onDelete: "cascade"
|
|
645
|
+
}),
|
|
646
|
+
actorRef: text2("actor_ref").notNull(),
|
|
647
|
+
messageId: text2("message_id"),
|
|
648
|
+
modelId: text2("model_id").notNull(),
|
|
649
|
+
purpose: text2("purpose").$type().notNull(),
|
|
650
|
+
inputTokens: integer2("input_tokens").notNull(),
|
|
651
|
+
outputTokens: integer2("output_tokens").notNull(),
|
|
652
|
+
cacheWriteTokens: integer2("cache_write_tokens"),
|
|
653
|
+
cacheReadTokens: integer2("cache_read_tokens"),
|
|
654
|
+
costUsd: doublePrecision("cost_usd"),
|
|
655
|
+
createdAt: ts2("created_at").notNull()
|
|
656
|
+
}, (table) => [
|
|
657
|
+
index3("agent_token_usage_actor_created_idx").on(table.actorRef, table.createdAt)
|
|
658
|
+
]);
|
|
659
|
+
var agentModelPricing3 = pgTable("agent_model_pricing", {
|
|
660
|
+
id: text2("id").primaryKey(),
|
|
661
|
+
modelId: text2("model_id").notNull(),
|
|
662
|
+
inputPricePer1m: doublePrecision("input_price_per_1m").notNull(),
|
|
663
|
+
outputPricePer1m: doublePrecision("output_price_per_1m").notNull(),
|
|
664
|
+
cacheWritePricePer1m: doublePrecision("cache_write_price_per_1m"),
|
|
665
|
+
cacheReadPricePer1m: doublePrecision("cache_read_price_per_1m"),
|
|
666
|
+
effectiveFrom: ts2("effective_from").notNull(),
|
|
667
|
+
isCurrent: boolean2("is_current").notNull()
|
|
668
|
+
});
|
|
669
|
+
var agentRun3 = pgTable("agent_run", {
|
|
670
|
+
id: text2("id").primaryKey(),
|
|
671
|
+
threadId: text2("thread_id").notNull().references(() => agentThread3.id, {
|
|
672
|
+
onDelete: "cascade"
|
|
673
|
+
}),
|
|
674
|
+
actorRef: text2("actor_ref").notNull(),
|
|
675
|
+
agentName: text2("agent_name"),
|
|
676
|
+
status: text2("status").$type().notNull(),
|
|
677
|
+
durationMs: integer2("duration_ms"),
|
|
678
|
+
errorCode: text2("error_code"),
|
|
679
|
+
errorMessage: text2("error_message"),
|
|
680
|
+
retries: integer2("retries").notNull().default(0),
|
|
681
|
+
startedAt: ts2("started_at").notNull(),
|
|
682
|
+
settledAt: ts2("settled_at"),
|
|
683
|
+
promptHash: text2("prompt_hash"),
|
|
684
|
+
parentRunId: text2("parent_run_id")
|
|
685
|
+
}, (table) => [
|
|
686
|
+
index3("agent_run_started_idx").on(table.startedAt)
|
|
687
|
+
]);
|
|
688
|
+
var agentMemory3 = pgTable("agent_memory", {
|
|
689
|
+
id: text2("id").primaryKey(),
|
|
690
|
+
scope: text2("scope").notNull(),
|
|
691
|
+
key: text2("key").notNull(),
|
|
692
|
+
text: text2("text").notNull(),
|
|
693
|
+
originAuthor: text2("origin_author").$type().notNull(),
|
|
694
|
+
originThreadId: text2("origin_thread_id"),
|
|
695
|
+
originRunId: text2("origin_run_id"),
|
|
696
|
+
originActorRef: text2("origin_actor_ref"),
|
|
697
|
+
pinned: boolean2("pinned").notNull().default(false),
|
|
698
|
+
createdAt: ts2("created_at").notNull(),
|
|
699
|
+
updatedAt: ts2("updated_at").notNull()
|
|
700
|
+
}, (table) => [
|
|
701
|
+
uniqueIndex3("agent_memory_scope_key_uq").on(table.scope, table.key)
|
|
702
|
+
]);
|
|
703
|
+
var ragIngestionLog3 = pgTable("rag_ingestion_log", {
|
|
704
|
+
documentId: text2("document_id").primaryKey(),
|
|
705
|
+
status: text2("status").$type().notNull(),
|
|
706
|
+
collection: text2("collection"),
|
|
707
|
+
ownerType: text2("owner_type"),
|
|
708
|
+
ownerId: text2("owner_id"),
|
|
709
|
+
source: text2("source"),
|
|
710
|
+
mimeType: text2("mime_type"),
|
|
711
|
+
size: bigint2("size", {
|
|
712
|
+
mode: "number"
|
|
713
|
+
}),
|
|
714
|
+
chunks: integer2("chunks"),
|
|
715
|
+
reason: text2("reason"),
|
|
716
|
+
error: text2("error"),
|
|
717
|
+
createdAt: ts2("created_at").notNull(),
|
|
718
|
+
updatedAt: ts2("updated_at").notNull()
|
|
719
|
+
}, (table) => [
|
|
720
|
+
index3("rag_ingestion_log_collection_idx").on(table.collection, table.updatedAt)
|
|
721
|
+
]);
|
|
722
|
+
var agentConfirmToken3 = pgTable("agent_confirm_token", {
|
|
723
|
+
hash: text2("hash").primaryKey(),
|
|
724
|
+
actorRef: text2("actor_ref").notNull(),
|
|
725
|
+
tool: text2("tool").notNull(),
|
|
726
|
+
expiresAt: bigint2("expires_at", {
|
|
727
|
+
mode: "number"
|
|
728
|
+
}).notNull(),
|
|
729
|
+
createdAt: bigint2("created_at", {
|
|
730
|
+
mode: "number"
|
|
731
|
+
}).notNull()
|
|
732
|
+
}, (table) => [
|
|
733
|
+
index3("agent_confirm_token_expires_idx").on(table.expiresAt)
|
|
734
|
+
]);
|
|
735
|
+
var agentStreamFrame3 = pgTable("agent_stream_frame", {
|
|
736
|
+
runId: text2("run_id").notNull(),
|
|
737
|
+
seq: integer2("seq").notNull(),
|
|
738
|
+
frame: text2("frame"),
|
|
739
|
+
error: text2("error"),
|
|
740
|
+
createdAt: bigint2("created_at", {
|
|
741
|
+
mode: "number"
|
|
742
|
+
}).notNull()
|
|
743
|
+
}, (table) => [
|
|
744
|
+
primaryKey3({
|
|
745
|
+
columns: [
|
|
746
|
+
table.runId,
|
|
747
|
+
table.seq
|
|
748
|
+
]
|
|
749
|
+
})
|
|
750
|
+
]);
|
|
751
|
+
var pgAgentSchema = {
|
|
752
|
+
agentThread: agentThread3,
|
|
753
|
+
agentMessage: agentMessage3,
|
|
754
|
+
agentQueuedMessage: agentQueuedMessage3,
|
|
755
|
+
agentToolCall: agentToolCall3,
|
|
756
|
+
agentTokenUsage: agentTokenUsage3,
|
|
757
|
+
agentModelPricing: agentModelPricing3,
|
|
758
|
+
agentRun: agentRun3,
|
|
759
|
+
agentMemory: agentMemory3,
|
|
760
|
+
ragIngestionLog: ragIngestionLog3,
|
|
761
|
+
agentConfirmToken: agentConfirmToken3,
|
|
762
|
+
agentStreamFrame: agentStreamFrame3
|
|
763
|
+
};
|
|
764
|
+
|
|
765
|
+
// src/dialect.ts
|
|
766
|
+
function agentDialectOf(db) {
|
|
767
|
+
if (is(db, PgDatabase)) return "postgres";
|
|
768
|
+
if (is(db, MySqlDatabase)) return "mysql";
|
|
769
|
+
return "sqlite";
|
|
770
|
+
}
|
|
771
|
+
__name(agentDialectOf, "agentDialectOf");
|
|
772
|
+
function agentTablesFor(dialect) {
|
|
773
|
+
if (dialect === "postgres") return pgAgentSchema;
|
|
774
|
+
if (dialect === "mysql") return mysqlAgentSchema;
|
|
775
|
+
return agentSchema;
|
|
776
|
+
}
|
|
777
|
+
__name(agentTablesFor, "agentTablesFor");
|
|
778
|
+
function asBuilder(db) {
|
|
779
|
+
return db;
|
|
780
|
+
}
|
|
781
|
+
__name(asBuilder, "asBuilder");
|
|
782
|
+
async function affectedRows(dialect, statement, column) {
|
|
783
|
+
if (dialect !== "mysql") {
|
|
784
|
+
return (await statement.returning({
|
|
785
|
+
affected: column
|
|
786
|
+
})).length;
|
|
787
|
+
}
|
|
788
|
+
return mysqlAffectedRows(await statement);
|
|
789
|
+
}
|
|
790
|
+
__name(affectedRows, "affectedRows");
|
|
791
|
+
function mysqlAffectedRows(result) {
|
|
792
|
+
const header = Array.isArray(result) ? result[0] : result;
|
|
793
|
+
const counts = header;
|
|
794
|
+
const count3 = counts?.affectedRows ?? counts?.rowsAffected;
|
|
795
|
+
return typeof count3 === "number" ? count3 : 0;
|
|
796
|
+
}
|
|
797
|
+
__name(mysqlAffectedRows, "mysqlAffectedRows");
|
|
798
|
+
async function runSql(db, dialect, statement) {
|
|
799
|
+
if (dialect === "sqlite") {
|
|
800
|
+
await db.run(statement);
|
|
801
|
+
return;
|
|
546
802
|
}
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
await db.run(sql.raw(statement));
|
|
803
|
+
if (dialect === "postgres") {
|
|
804
|
+
await db.execute(statement);
|
|
805
|
+
return;
|
|
551
806
|
}
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
807
|
+
await db.execute(statement);
|
|
808
|
+
}
|
|
809
|
+
__name(runSql, "runSql");
|
|
810
|
+
async function querySql(db, dialect, statement) {
|
|
811
|
+
if (dialect === "sqlite") {
|
|
812
|
+
return db.all(statement);
|
|
813
|
+
}
|
|
814
|
+
const result = dialect === "postgres" ? await db.execute(statement) : await db.execute(statement);
|
|
815
|
+
if (dialect === "mysql") {
|
|
816
|
+
return Array.isArray(result) ? result[0] : [];
|
|
817
|
+
}
|
|
818
|
+
return Array.isArray(result) ? result : result.rows ?? [];
|
|
819
|
+
}
|
|
820
|
+
__name(querySql, "querySql");
|
|
821
|
+
function isUniqueViolation(error) {
|
|
822
|
+
for (let current = error; current !== null && typeof current === "object"; ) {
|
|
823
|
+
const { code, errno } = current;
|
|
824
|
+
if (code === "23505" || code === "ER_DUP_ENTRY" || errno === 1062 || code === "ER_LOCK_DEADLOCK" || errno === 1213 || typeof code === "string" && code.startsWith("SQLITE_CONSTRAINT")) {
|
|
825
|
+
return true;
|
|
556
826
|
}
|
|
827
|
+
current = current.cause;
|
|
557
828
|
}
|
|
829
|
+
return false;
|
|
830
|
+
}
|
|
831
|
+
__name(isUniqueViolation, "isUniqueViolation");
|
|
832
|
+
function upsert(dialect, insert, target, set) {
|
|
833
|
+
if (dialect === "mysql") {
|
|
834
|
+
return insert.onDuplicateKeyUpdate({
|
|
835
|
+
set
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
return insert.onConflictDoUpdate({
|
|
839
|
+
target,
|
|
840
|
+
set
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
__name(upsert, "upsert");
|
|
844
|
+
|
|
845
|
+
// src/ensure-schema.ts
|
|
846
|
+
async function ensureAgentSchema(db) {
|
|
847
|
+
const dialect = agentDialectOf(db);
|
|
848
|
+
if (dialect === "postgres") {
|
|
849
|
+
await db.transaction(async (tx) => {
|
|
850
|
+
await tx.execute(sql.raw(`select pg_advisory_xact_lock(hashtext('${LOCK_NAME}'))`));
|
|
851
|
+
await heal(tx, dialect);
|
|
852
|
+
});
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
if (dialect === "mysql") {
|
|
856
|
+
await db.transaction(async (tx) => {
|
|
857
|
+
await tx.execute(sql.raw(`select get_lock('${LOCK_NAME}', 30)`));
|
|
858
|
+
try {
|
|
859
|
+
await heal(tx, dialect);
|
|
860
|
+
} finally {
|
|
861
|
+
await tx.execute(sql.raw(`select release_lock('${LOCK_NAME}')`));
|
|
862
|
+
}
|
|
863
|
+
});
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
await heal(db, dialect);
|
|
558
867
|
}
|
|
559
868
|
__name(ensureAgentSchema, "ensureAgentSchema");
|
|
869
|
+
var LOCK_NAME = "nestjs_agent_schema";
|
|
870
|
+
var MYSQL_TABLE_OPTIONS = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin";
|
|
871
|
+
function tableSpec(dialect, table) {
|
|
872
|
+
const config = dialect === "postgres" ? pgTableConfig(table) : dialect === "mysql" ? mysqlTableConfig(table) : sqliteTableConfig(table);
|
|
873
|
+
const columns = config.columns;
|
|
874
|
+
const compositeKey = config.primaryKeys[0]?.columns.map((column) => column.name);
|
|
875
|
+
return {
|
|
876
|
+
name: config.name,
|
|
877
|
+
columns,
|
|
878
|
+
primaryKey: compositeKey ?? columns.filter((column) => column.primary).map((c) => c.name),
|
|
879
|
+
foreignKeys: config.foreignKeys.map((foreignKey) => {
|
|
880
|
+
const reference = foreignKey.reference();
|
|
881
|
+
return {
|
|
882
|
+
columns: reference.columns.map((column) => column.name),
|
|
883
|
+
table: getTableName(reference.foreignTable),
|
|
884
|
+
foreignColumns: reference.foreignColumns.map((column) => column.name),
|
|
885
|
+
...foreignKey.onDelete !== void 0 ? {
|
|
886
|
+
onDelete: foreignKey.onDelete
|
|
887
|
+
} : {}
|
|
888
|
+
};
|
|
889
|
+
}),
|
|
890
|
+
indexes: config.indexes.map((index4) => ({
|
|
891
|
+
name: String(index4.config.name),
|
|
892
|
+
unique: index4.config.unique === true,
|
|
893
|
+
columns: index4.config.columns.map((column) => String(column.name))
|
|
894
|
+
}))
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
__name(tableSpec, "tableSpec");
|
|
898
|
+
function quote(dialect, identifier) {
|
|
899
|
+
return dialect === "mysql" ? `\`${identifier}\`` : `"${identifier}"`;
|
|
900
|
+
}
|
|
901
|
+
__name(quote, "quote");
|
|
902
|
+
function literal(dialect, value) {
|
|
903
|
+
if (typeof value === "boolean") {
|
|
904
|
+
return dialect === "sqlite" ? value ? "1" : "0" : value ? "true" : "false";
|
|
905
|
+
}
|
|
906
|
+
if (typeof value === "number") return String(value);
|
|
907
|
+
return `'${String(value).replaceAll("'", "''")}'`;
|
|
908
|
+
}
|
|
909
|
+
__name(literal, "literal");
|
|
910
|
+
function columnDefinition(dialect, column) {
|
|
911
|
+
const parts = [
|
|
912
|
+
quote(dialect, column.name),
|
|
913
|
+
column.getSQLType()
|
|
914
|
+
];
|
|
915
|
+
if (column.notNull) parts.push("NOT NULL");
|
|
916
|
+
if (column.hasDefault && column.default !== void 0) {
|
|
917
|
+
parts.push(`DEFAULT ${literal(dialect, column.default)}`);
|
|
918
|
+
}
|
|
919
|
+
return parts.join(" ");
|
|
920
|
+
}
|
|
921
|
+
__name(columnDefinition, "columnDefinition");
|
|
922
|
+
function createTableSql(dialect, spec) {
|
|
923
|
+
const q = /* @__PURE__ */ __name((identifier) => quote(dialect, identifier), "q");
|
|
924
|
+
const lines = spec.columns.map((column) => columnDefinition(dialect, column));
|
|
925
|
+
lines.push(`PRIMARY KEY (${spec.primaryKey.map(q).join(", ")})`);
|
|
926
|
+
for (const foreignKey of spec.foreignKeys) {
|
|
927
|
+
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()}` : ""}`);
|
|
928
|
+
}
|
|
929
|
+
const options = dialect === "mysql" ? ` ${MYSQL_TABLE_OPTIONS}` : "";
|
|
930
|
+
return `CREATE TABLE IF NOT EXISTS ${q(spec.name)} (
|
|
931
|
+
${lines.join(",\n ")}
|
|
932
|
+
)${options}`;
|
|
933
|
+
}
|
|
934
|
+
__name(createTableSql, "createTableSql");
|
|
935
|
+
function agentSchemaDdl(dialect) {
|
|
936
|
+
const statements = [];
|
|
937
|
+
for (const spec of specs(dialect)) {
|
|
938
|
+
statements.push(createTableSql(dialect, spec));
|
|
939
|
+
for (const index4 of spec.indexes) {
|
|
940
|
+
statements.push(createIndexSql(dialect, spec.name, index4));
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
return statements;
|
|
944
|
+
}
|
|
945
|
+
__name(agentSchemaDdl, "agentSchemaDdl");
|
|
946
|
+
function createIndexSql(dialect, table, index4) {
|
|
947
|
+
const q = /* @__PURE__ */ __name((identifier) => quote(dialect, identifier), "q");
|
|
948
|
+
const guard = dialect === "mysql" ? "" : "IF NOT EXISTS ";
|
|
949
|
+
return `CREATE ${index4.unique ? "UNIQUE " : ""}INDEX ${guard}${q(index4.name)} ON ${q(table)} (${index4.columns.map(q).join(", ")})`;
|
|
950
|
+
}
|
|
951
|
+
__name(createIndexSql, "createIndexSql");
|
|
952
|
+
function specs(dialect) {
|
|
953
|
+
const all = Object.values(agentTablesFor(dialect)).map((table) => tableSpec(dialect, table));
|
|
954
|
+
const ordered = [];
|
|
955
|
+
const placed = /* @__PURE__ */ new Set();
|
|
956
|
+
while (ordered.length < all.length) {
|
|
957
|
+
const ready = all.filter((spec) => !placed.has(spec.name) && spec.foreignKeys.every((key2) => key2.table === spec.name || placed.has(key2.table)));
|
|
958
|
+
if (ready.length === 0) throw new Error("agent schema: circular foreign keys");
|
|
959
|
+
for (const spec of ready) {
|
|
960
|
+
ordered.push(spec);
|
|
961
|
+
placed.add(spec.name);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
return ordered;
|
|
965
|
+
}
|
|
966
|
+
__name(specs, "specs");
|
|
967
|
+
async function existingColumns(db, dialect, table) {
|
|
968
|
+
const rows = dialect === "sqlite" ? await querySql(db, dialect, sql.raw(`PRAGMA table_info("${table}")`)) : await querySql(db, dialect, sql`select column_name as name from information_schema.columns where table_schema = ${sql.raw(dialect === "mysql" ? "database()" : "current_schema()")} and table_name = ${table}`);
|
|
969
|
+
return new Set(rows.map((row) => String(row.name)));
|
|
970
|
+
}
|
|
971
|
+
__name(existingColumns, "existingColumns");
|
|
972
|
+
async function indexExists(db, dialect, table, index4) {
|
|
973
|
+
let query;
|
|
974
|
+
if (dialect === "sqlite") {
|
|
975
|
+
query = sql`select name from sqlite_master where type = 'index' and name = ${index4}`;
|
|
976
|
+
} else if (dialect === "postgres") {
|
|
977
|
+
query = sql`select indexname as name from pg_indexes where schemaname = current_schema() and indexname = ${index4}`;
|
|
978
|
+
} else {
|
|
979
|
+
query = sql`select index_name as name from information_schema.statistics where table_schema = database() and table_name = ${table} and index_name = ${index4}`;
|
|
980
|
+
}
|
|
981
|
+
return (await querySql(db, dialect, query)).length > 0;
|
|
982
|
+
}
|
|
983
|
+
__name(indexExists, "indexExists");
|
|
984
|
+
async function heal(db, dialect) {
|
|
985
|
+
for (const spec of specs(dialect)) {
|
|
986
|
+
await runSql(db, dialect, sql.raw(createTableSql(dialect, spec)));
|
|
987
|
+
const present = await existingColumns(db, dialect, spec.name);
|
|
988
|
+
for (const column of spec.columns) {
|
|
989
|
+
if (!present.has(column.name)) {
|
|
990
|
+
await runSql(db, dialect, sql.raw(`ALTER TABLE ${quote(dialect, spec.name)} ADD COLUMN ${columnDefinition(dialect, column)}`));
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
for (const index4 of spec.indexes) {
|
|
994
|
+
if (!await indexExists(db, dialect, spec.name, index4.name)) {
|
|
995
|
+
await runSql(db, dialect, sql.raw(createIndexSql(dialect, spec.name, index4)));
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
__name(heal, "heal");
|
|
560
1001
|
|
|
561
1002
|
// src/drizzle-agent-store.ts
|
|
562
1003
|
import { toolCallApprovalFromRow } from "@dudousxd/nestjs-agent-core";
|
|
563
1004
|
import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, max, min, or, sql as sql2 } from "drizzle-orm";
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
1005
|
+
function turnMessageColumns(message) {
|
|
1006
|
+
return {
|
|
1007
|
+
id: message.id,
|
|
1008
|
+
role: message.role,
|
|
1009
|
+
content: message.content,
|
|
1010
|
+
agentName: message.agentName,
|
|
1011
|
+
toolCalls: message.toolCalls,
|
|
1012
|
+
toolResults: message.toolResults,
|
|
1013
|
+
attachments: message.attachments,
|
|
1014
|
+
createdAt: message.createdAt
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
__name(turnMessageColumns, "turnMessageColumns");
|
|
574
1018
|
var DrizzleAgentStore = class {
|
|
575
1019
|
static {
|
|
576
1020
|
__name(this, "DrizzleAgentStore");
|
|
577
1021
|
}
|
|
578
1022
|
db;
|
|
1023
|
+
dialect;
|
|
1024
|
+
t;
|
|
579
1025
|
constructor(db) {
|
|
580
|
-
this.
|
|
1026
|
+
this.dialect = agentDialectOf(db);
|
|
1027
|
+
this.t = agentTablesFor(this.dialect);
|
|
1028
|
+
this.db = asBuilder(db);
|
|
581
1029
|
}
|
|
582
1030
|
async createThread(input) {
|
|
583
1031
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -590,20 +1038,21 @@ var DrizzleAgentStore = class {
|
|
|
590
1038
|
activeStreamId: null,
|
|
591
1039
|
defaultAgent: null,
|
|
592
1040
|
model: null,
|
|
1041
|
+
persona: input.persona ?? null,
|
|
593
1042
|
queuePause: null,
|
|
594
1043
|
createdAt: now,
|
|
595
1044
|
updatedAt: now,
|
|
596
1045
|
deletedAt: null
|
|
597
1046
|
};
|
|
598
|
-
await this.db.insert(agentThread).values(thread);
|
|
1047
|
+
await this.db.insert(this.t.agentThread).values(thread);
|
|
599
1048
|
return this.toSummary(thread);
|
|
600
1049
|
}
|
|
601
1050
|
async getThread(threadId) {
|
|
602
|
-
const [thread] = await this.db.select().from(agentThread).where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));
|
|
1051
|
+
const [thread] = await this.db.select().from(this.t.agentThread).where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));
|
|
603
1052
|
if (thread === void 0) {
|
|
604
1053
|
return null;
|
|
605
1054
|
}
|
|
606
|
-
const messages = await this.db.select().from(agentMessage).where(eq(agentMessage.threadId, threadId)).orderBy(
|
|
1055
|
+
const messages = await this.db.select().from(this.t.agentMessage).where(eq(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
|
|
607
1056
|
const last = messages[messages.length - 1];
|
|
608
1057
|
const approvals = await this.approvalsFor(messages.map((message) => message.id));
|
|
609
1058
|
return {
|
|
@@ -636,16 +1085,16 @@ var DrizzleAgentStore = class {
|
|
|
636
1085
|
*/
|
|
637
1086
|
async loadThreadForTurn(query) {
|
|
638
1087
|
const [thread] = await this.db.select({
|
|
639
|
-
title: agentThread.title,
|
|
640
|
-
defaultAgent: agentThread.defaultAgent
|
|
641
|
-
}).from(agentThread).where(and(eq(agentThread.id, query.threadId), isNull(agentThread.deletedAt)));
|
|
1088
|
+
title: this.t.agentThread.title,
|
|
1089
|
+
defaultAgent: this.t.agentThread.defaultAgent
|
|
1090
|
+
}).from(this.t.agentThread).where(and(eq(this.t.agentThread.id, query.threadId), isNull(this.t.agentThread.deletedAt)));
|
|
642
1091
|
if (thread === void 0) {
|
|
643
1092
|
return null;
|
|
644
1093
|
}
|
|
645
1094
|
const messages = await this.loadTurnWindow(query.threadId, query.messageLimit);
|
|
646
1095
|
const [answered] = await this.db.select({
|
|
647
|
-
id: agentMessage.id
|
|
648
|
-
}).from(agentMessage).where(and(eq(agentMessage.threadId, query.threadId), eq(agentMessage.role, "assistant"))).limit(1);
|
|
1096
|
+
id: this.t.agentMessage.id
|
|
1097
|
+
}).from(this.t.agentMessage).where(and(eq(this.t.agentMessage.threadId, query.threadId), eq(this.t.agentMessage.role, "assistant"))).limit(1);
|
|
649
1098
|
return {
|
|
650
1099
|
title: thread.title,
|
|
651
1100
|
defaultAgent: thread.defaultAgent,
|
|
@@ -661,30 +1110,30 @@ var DrizzleAgentStore = class {
|
|
|
661
1110
|
if (limit !== void 0 && limit <= 0) {
|
|
662
1111
|
return [];
|
|
663
1112
|
}
|
|
664
|
-
const window = this.db.select(
|
|
1113
|
+
const window = this.db.select(turnMessageColumns(this.t.agentMessage)).from(this.t.agentMessage).where(eq(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrderNewestFirst());
|
|
665
1114
|
const rows = limit === void 0 ? await window : await window.limit(limit);
|
|
666
1115
|
return rows.reverse().map((row) => this.toStoredMessage(row));
|
|
667
1116
|
}
|
|
668
1117
|
async listThreads(actorRef, limit = 50) {
|
|
669
|
-
const threads = await this.db.select().from(agentThread).where(and(eq(agentThread.actorRef, actorRef), eq(agentThread.transient, false), isNull(agentThread.deletedAt))).orderBy(desc(agentThread.updatedAt)).limit(limit);
|
|
1118
|
+
const threads = await this.db.select().from(this.t.agentThread).where(and(eq(this.t.agentThread.actorRef, actorRef), eq(this.t.agentThread.transient, false), isNull(this.t.agentThread.deletedAt))).orderBy(desc(this.t.agentThread.updatedAt)).limit(limit);
|
|
670
1119
|
const summaries = [];
|
|
671
1120
|
for (const thread of threads) {
|
|
672
|
-
const [last] = await this.db.select().from(agentMessage).where(eq(agentMessage.threadId, thread.id)).orderBy(
|
|
1121
|
+
const [last] = await this.db.select().from(this.t.agentMessage).where(eq(this.t.agentMessage.threadId, thread.id)).orderBy(...this.messageOrderNewestFirst()).limit(1);
|
|
673
1122
|
summaries.push(this.toSummary(thread, last?.content));
|
|
674
1123
|
}
|
|
675
1124
|
return summaries;
|
|
676
1125
|
}
|
|
677
1126
|
async softDeleteThread(threadId) {
|
|
678
|
-
await this.db.update(agentThread).set({
|
|
1127
|
+
await this.db.update(this.t.agentThread).set({
|
|
679
1128
|
deletedAt: /* @__PURE__ */ new Date()
|
|
680
|
-
}).where(eq(agentThread.id, threadId));
|
|
1129
|
+
}).where(eq(this.t.agentThread.id, threadId));
|
|
681
1130
|
}
|
|
682
1131
|
async forkThread(threadId, fromMessageId) {
|
|
683
|
-
const [source] = await this.db.select().from(agentThread).where(eq(agentThread.id, threadId));
|
|
1132
|
+
const [source] = await this.db.select().from(this.t.agentThread).where(eq(this.t.agentThread.id, threadId));
|
|
684
1133
|
if (source === void 0) {
|
|
685
1134
|
throw new Error(`thread ${threadId} not found`);
|
|
686
1135
|
}
|
|
687
|
-
const messages = await this.db.select().from(agentMessage).where(eq(agentMessage.threadId, threadId)).orderBy(
|
|
1136
|
+
const messages = await this.db.select().from(this.t.agentMessage).where(eq(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
|
|
688
1137
|
const cutoff = messages.findIndex((message) => message.id === fromMessageId);
|
|
689
1138
|
const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;
|
|
690
1139
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -697,16 +1146,19 @@ var DrizzleAgentStore = class {
|
|
|
697
1146
|
activeStreamId: null,
|
|
698
1147
|
defaultAgent: source.defaultAgent,
|
|
699
1148
|
model: source.model,
|
|
1149
|
+
persona: source.persona,
|
|
700
1150
|
// A fork is a new conversation: nothing is waiting on it, and nothing is paused.
|
|
701
1151
|
queuePause: null,
|
|
702
1152
|
createdAt: now,
|
|
703
1153
|
updatedAt: now,
|
|
704
1154
|
deletedAt: null
|
|
705
1155
|
};
|
|
706
|
-
await this.db.insert(agentThread).values(fork);
|
|
1156
|
+
await this.db.insert(this.t.agentThread).values(fork);
|
|
707
1157
|
if (kept.length > 0) {
|
|
708
|
-
await this.db.insert(agentMessage).values(kept.map((message) => ({
|
|
1158
|
+
await this.db.insert(this.t.agentMessage).values(kept.map((message, index4) => ({
|
|
709
1159
|
id: crypto.randomUUID(),
|
|
1160
|
+
// Numbered afresh in the order just read, so the copy reads back in the original's order.
|
|
1161
|
+
seq: index4 + 1,
|
|
710
1162
|
threadId: fork.id,
|
|
711
1163
|
role: message.role,
|
|
712
1164
|
content: message.content,
|
|
@@ -716,6 +1168,7 @@ var DrizzleAgentStore = class {
|
|
|
716
1168
|
followUps: message.followUps,
|
|
717
1169
|
usage: message.usage,
|
|
718
1170
|
agentName: message.agentName,
|
|
1171
|
+
persona: message.persona,
|
|
719
1172
|
// The copy is the same message, so it keeps the run that wrote it. A reader asking which
|
|
720
1173
|
// turn produced this text gets the truthful answer; the run's own thread is still the
|
|
721
1174
|
// original, so a run-scoped read never picks the fork's rows up.
|
|
@@ -730,21 +1183,21 @@ var DrizzleAgentStore = class {
|
|
|
730
1183
|
}
|
|
731
1184
|
async ownerOfThread(threadId) {
|
|
732
1185
|
const [thread] = await this.db.select({
|
|
733
|
-
actorRef: agentThread.actorRef
|
|
734
|
-
}).from(agentThread).where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));
|
|
1186
|
+
actorRef: this.t.agentThread.actorRef
|
|
1187
|
+
}).from(this.t.agentThread).where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));
|
|
735
1188
|
return thread?.actorRef ?? null;
|
|
736
1189
|
}
|
|
737
1190
|
async ownerOfToolCall(toolCallId) {
|
|
738
1191
|
const [row] = await this.db.select({
|
|
739
|
-
actorRef: agentThread.actorRef
|
|
740
|
-
}).from(agentToolCall).innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id)).where(eq(agentToolCall.id, toolCallId));
|
|
1192
|
+
actorRef: this.t.agentThread.actorRef
|
|
1193
|
+
}).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id)).where(eq(this.t.agentToolCall.id, toolCallId));
|
|
741
1194
|
return row?.actorRef ?? null;
|
|
742
1195
|
}
|
|
743
1196
|
async runForToolCall(toolCallId) {
|
|
744
1197
|
const [row] = await this.db.select({
|
|
745
|
-
runId: agentToolCall.runId,
|
|
746
|
-
activeStreamId: agentThread.activeStreamId
|
|
747
|
-
}).from(agentToolCall).innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id)).where(eq(agentToolCall.id, toolCallId));
|
|
1198
|
+
runId: this.t.agentToolCall.runId,
|
|
1199
|
+
activeStreamId: this.t.agentThread.activeStreamId
|
|
1200
|
+
}).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id)).where(eq(this.t.agentToolCall.id, toolCallId));
|
|
748
1201
|
return row?.runId ?? row?.activeStreamId ?? null;
|
|
749
1202
|
}
|
|
750
1203
|
/**
|
|
@@ -758,16 +1211,16 @@ var DrizzleAgentStore = class {
|
|
|
758
1211
|
return byMessage;
|
|
759
1212
|
}
|
|
760
1213
|
const rows = await this.db.select({
|
|
761
|
-
id: agentToolCall.id,
|
|
762
|
-
messageId: agentToolCall.messageId,
|
|
763
|
-
status: agentToolCall.status,
|
|
764
|
-
approver: agentToolCall.approver,
|
|
765
|
-
expiresAt: agentToolCall.expiresAt,
|
|
766
|
-
remember: agentToolCall.remember,
|
|
767
|
-
executedByRef: agentToolCall.executedByRef,
|
|
768
|
-
decidedVia: agentToolCall.decidedVia,
|
|
769
|
-
error: agentToolCall.error
|
|
770
|
-
}).from(agentToolCall).where(and(inArray(agentToolCall.messageId, messageIds), isNotNull(agentToolCall.approver))).orderBy(asc(agentToolCall.createdAt), asc(agentToolCall.id));
|
|
1214
|
+
id: this.t.agentToolCall.id,
|
|
1215
|
+
messageId: this.t.agentToolCall.messageId,
|
|
1216
|
+
status: this.t.agentToolCall.status,
|
|
1217
|
+
approver: this.t.agentToolCall.approver,
|
|
1218
|
+
expiresAt: this.t.agentToolCall.expiresAt,
|
|
1219
|
+
remember: this.t.agentToolCall.remember,
|
|
1220
|
+
executedByRef: this.t.agentToolCall.executedByRef,
|
|
1221
|
+
decidedVia: this.t.agentToolCall.decidedVia,
|
|
1222
|
+
error: this.t.agentToolCall.error
|
|
1223
|
+
}).from(this.t.agentToolCall).where(and(inArray(this.t.agentToolCall.messageId, messageIds), isNotNull(this.t.agentToolCall.approver))).orderBy(asc(this.t.agentToolCall.createdAt), asc(this.t.agentToolCall.id));
|
|
771
1224
|
for (const row of rows) {
|
|
772
1225
|
const approval = toolCallApprovalFromRow({
|
|
773
1226
|
...row,
|
|
@@ -785,22 +1238,22 @@ var DrizzleAgentStore = class {
|
|
|
785
1238
|
/** Tools whose approval someone asked to remember in this thread. */
|
|
786
1239
|
async rememberedApprovals(threadId) {
|
|
787
1240
|
const rows = await this.db.selectDistinct({
|
|
788
|
-
toolName: agentToolCall.toolName
|
|
789
|
-
}).from(agentToolCall).innerJoin(agentMessage, eq(agentToolCall.messageId, agentMessage.id)).where(and(eq(agentMessage.threadId, threadId), eq(agentToolCall.remember, true)));
|
|
1241
|
+
toolName: this.t.agentToolCall.toolName
|
|
1242
|
+
}).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(and(eq(this.t.agentMessage.threadId, threadId), eq(this.t.agentToolCall.remember, true)));
|
|
790
1243
|
return rows.map((row) => row.toolName);
|
|
791
1244
|
}
|
|
792
1245
|
async toolCallInput(toolCallId) {
|
|
793
1246
|
const [row] = await this.db.select({
|
|
794
|
-
input: agentToolCall.input
|
|
795
|
-
}).from(agentToolCall).where(eq(agentToolCall.id, toolCallId));
|
|
1247
|
+
input: this.t.agentToolCall.input
|
|
1248
|
+
}).from(this.t.agentToolCall).where(eq(this.t.agentToolCall.id, toolCallId));
|
|
796
1249
|
return row?.input ?? null;
|
|
797
1250
|
}
|
|
798
1251
|
async toolCallApproval(toolCallId) {
|
|
799
1252
|
const [row] = await this.db.select({
|
|
800
|
-
status: agentToolCall.status,
|
|
801
|
-
approver: agentToolCall.approver,
|
|
802
|
-
expiresAt: agentToolCall.expiresAt
|
|
803
|
-
}).from(agentToolCall).where(eq(agentToolCall.id, toolCallId));
|
|
1253
|
+
status: this.t.agentToolCall.status,
|
|
1254
|
+
approver: this.t.agentToolCall.approver,
|
|
1255
|
+
expiresAt: this.t.agentToolCall.expiresAt
|
|
1256
|
+
}).from(this.t.agentToolCall).where(eq(this.t.agentToolCall.id, toolCallId));
|
|
804
1257
|
if (row === void 0) {
|
|
805
1258
|
return null;
|
|
806
1259
|
}
|
|
@@ -812,27 +1265,67 @@ var DrizzleAgentStore = class {
|
|
|
812
1265
|
}
|
|
813
1266
|
async ownerOfActiveStream(runId) {
|
|
814
1267
|
const [thread] = await this.db.select({
|
|
815
|
-
actorRef: agentThread.actorRef
|
|
816
|
-
}).from(agentThread).where(and(eq(agentThread.activeStreamId, runId), isNull(agentThread.deletedAt)));
|
|
1268
|
+
actorRef: this.t.agentThread.actorRef
|
|
1269
|
+
}).from(this.t.agentThread).where(and(eq(this.t.agentThread.activeStreamId, runId), isNull(this.t.agentThread.deletedAt)));
|
|
817
1270
|
return thread?.actorRef ?? null;
|
|
818
1271
|
}
|
|
819
1272
|
async setTitle(threadId, title) {
|
|
820
|
-
await this.db.update(agentThread).set({
|
|
1273
|
+
await this.db.update(this.t.agentThread).set({
|
|
821
1274
|
title,
|
|
822
1275
|
updatedAt: /* @__PURE__ */ new Date()
|
|
823
|
-
}).where(eq(agentThread.id, threadId));
|
|
1276
|
+
}).where(eq(this.t.agentThread.id, threadId));
|
|
824
1277
|
}
|
|
825
1278
|
async promoteThread(threadId) {
|
|
826
|
-
await this.db.update(agentThread).set({
|
|
1279
|
+
await this.db.update(this.t.agentThread).set({
|
|
827
1280
|
transient: false,
|
|
828
1281
|
updatedAt: /* @__PURE__ */ new Date()
|
|
829
|
-
}).where(and(eq(agentThread.id, threadId), eq(agentThread.transient, true)));
|
|
1282
|
+
}).where(and(eq(this.t.agentThread.id, threadId), eq(this.t.agentThread.transient, true)));
|
|
1283
|
+
}
|
|
1284
|
+
/** Who holds the thread's stream right now, deleted or not. */
|
|
1285
|
+
async activeHolder(threadId) {
|
|
1286
|
+
const [thread] = await this.db.select({
|
|
1287
|
+
activeStreamId: this.t.agentThread.activeStreamId
|
|
1288
|
+
}).from(this.t.agentThread).where(eq(this.t.agentThread.id, threadId));
|
|
1289
|
+
return thread?.activeStreamId ?? null;
|
|
1290
|
+
}
|
|
1291
|
+
/**
|
|
1292
|
+
* A thread's messages in the order they were appended: by `seq`, which append assigns. A row from
|
|
1293
|
+
* before `seq` existed has none and counts as 0 — first, since every such row is older than every
|
|
1294
|
+
* numbered one — and those order among themselves by `created_at`, then `id`, as they always did.
|
|
1295
|
+
* `coalesce` rather than `nulls first`, which MySQL cannot spell and Postgres defaults the other way.
|
|
1296
|
+
*/
|
|
1297
|
+
messageOrder() {
|
|
1298
|
+
const message = this.t.agentMessage;
|
|
1299
|
+
return [
|
|
1300
|
+
asc(sql2`coalesce(${message.seq}, 0)`),
|
|
1301
|
+
asc(message.createdAt),
|
|
1302
|
+
asc(message.id)
|
|
1303
|
+
];
|
|
1304
|
+
}
|
|
1305
|
+
/** {@link messageOrder}, newest first. */
|
|
1306
|
+
messageOrderNewestFirst() {
|
|
1307
|
+
const message = this.t.agentMessage;
|
|
1308
|
+
return [
|
|
1309
|
+
desc(sql2`coalesce(${message.seq}, 0)`),
|
|
1310
|
+
desc(message.createdAt),
|
|
1311
|
+
desc(message.id)
|
|
1312
|
+
];
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* The next `seq` in a thread: one past its highest. Two appends racing on ONE thread can draw the
|
|
1316
|
+
* same number — the turn loop never does that, and the tie then falls back to `created_at`, `id`.
|
|
1317
|
+
*/
|
|
1318
|
+
async nextMessageSeq(threadId) {
|
|
1319
|
+
const [row] = await this.db.select({
|
|
1320
|
+
last: max(this.t.agentMessage.seq)
|
|
1321
|
+
}).from(this.t.agentMessage).where(eq(this.t.agentMessage.threadId, threadId));
|
|
1322
|
+
return Number(row?.last ?? 0) + 1;
|
|
830
1323
|
}
|
|
831
1324
|
/** The run streaming the thread, or `null` — a projection of the one column. */
|
|
832
1325
|
async activeRunForThread(threadId) {
|
|
833
1326
|
const [thread] = await this.db.select({
|
|
834
|
-
activeStreamId: agentThread.activeStreamId
|
|
835
|
-
}).from(agentThread).where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));
|
|
1327
|
+
activeStreamId: this.t.agentThread.activeStreamId
|
|
1328
|
+
}).from(this.t.agentThread).where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));
|
|
836
1329
|
return thread?.activeStreamId ?? null;
|
|
837
1330
|
}
|
|
838
1331
|
/**
|
|
@@ -841,33 +1334,32 @@ var DrizzleAgentStore = class {
|
|
|
841
1334
|
*/
|
|
842
1335
|
async claimActiveStream(threadId, runId, options = {}) {
|
|
843
1336
|
const holders = [
|
|
844
|
-
isNull(agentThread.activeStreamId),
|
|
845
|
-
eq(agentThread.activeStreamId, runId),
|
|
1337
|
+
isNull(this.t.agentThread.activeStreamId),
|
|
1338
|
+
eq(this.t.agentThread.activeStreamId, runId),
|
|
846
1339
|
...options.replacing !== void 0 ? [
|
|
847
|
-
eq(agentThread.activeStreamId, options.replacing)
|
|
1340
|
+
eq(this.t.agentThread.activeStreamId, options.replacing)
|
|
848
1341
|
] : []
|
|
849
1342
|
];
|
|
850
|
-
const claimed = await this.db.update(agentThread).set({
|
|
1343
|
+
const claimed = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
|
|
851
1344
|
activeStreamId: runId
|
|
852
|
-
}).where(and(eq(agentThread.id, threadId), or(...holders))).
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
1345
|
+
}).where(and(eq(this.t.agentThread.id, threadId), or(...holders))), this.t.agentThread.id);
|
|
1346
|
+
if (claimed > 0) {
|
|
1347
|
+
return true;
|
|
1348
|
+
}
|
|
1349
|
+
return await this.activeHolder(threadId) === runId;
|
|
856
1350
|
}
|
|
857
1351
|
async releaseActiveStream(threadId, runId) {
|
|
858
|
-
const released = await this.db.update(agentThread).set({
|
|
1352
|
+
const released = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
|
|
859
1353
|
activeStreamId: null
|
|
860
|
-
}).where(and(eq(agentThread.id, threadId), eq(agentThread.activeStreamId, runId))).
|
|
861
|
-
|
|
862
|
-
});
|
|
863
|
-
return released.length > 0;
|
|
1354
|
+
}).where(and(eq(this.t.agentThread.id, threadId), eq(this.t.agentThread.activeStreamId, runId))), this.t.agentThread.id);
|
|
1355
|
+
return released > 0;
|
|
864
1356
|
}
|
|
865
1357
|
async enqueueMessage(input) {
|
|
866
1358
|
const now = /* @__PURE__ */ new Date();
|
|
867
1359
|
const [edge] = await this.db.select({
|
|
868
|
-
first: min(agentQueuedMessage.position),
|
|
869
|
-
last: max(agentQueuedMessage.position)
|
|
870
|
-
}).from(agentQueuedMessage).where(eq(agentQueuedMessage.threadId, input.threadId));
|
|
1360
|
+
first: min(this.t.agentQueuedMessage.position),
|
|
1361
|
+
last: max(this.t.agentQueuedMessage.position)
|
|
1362
|
+
}).from(this.t.agentQueuedMessage).where(eq(this.t.agentQueuedMessage.threadId, input.threadId));
|
|
871
1363
|
const position = input.at === "head" ? (edge?.first ?? 1) - 1 : (edge?.last ?? -1) + 1;
|
|
872
1364
|
const row = {
|
|
873
1365
|
id: crypto.randomUUID(),
|
|
@@ -876,6 +1368,7 @@ var DrizzleAgentStore = class {
|
|
|
876
1368
|
content: input.content,
|
|
877
1369
|
attachments: input.attachments !== void 0 && input.attachments.length > 0 ? input.attachments : null,
|
|
878
1370
|
agentName: input.agentName ?? null,
|
|
1371
|
+
persona: input.persona ?? null,
|
|
879
1372
|
model: input.model ?? null,
|
|
880
1373
|
pageContext: input.pageContext ?? null,
|
|
881
1374
|
interrupt: input.interrupt === true,
|
|
@@ -883,15 +1376,15 @@ var DrizzleAgentStore = class {
|
|
|
883
1376
|
createdAt: now,
|
|
884
1377
|
updatedAt: now
|
|
885
1378
|
};
|
|
886
|
-
await this.db.insert(agentQueuedMessage).values(row);
|
|
1379
|
+
await this.db.insert(this.t.agentQueuedMessage).values(row);
|
|
887
1380
|
return toQueuedMessage(row);
|
|
888
1381
|
}
|
|
889
1382
|
async listQueue(threadId) {
|
|
890
|
-
const rows = await this.db.select().from(agentQueuedMessage).where(eq(agentQueuedMessage.threadId, threadId)).orderBy(asc(agentQueuedMessage.position), asc(agentQueuedMessage.createdAt));
|
|
1383
|
+
const rows = await this.db.select().from(this.t.agentQueuedMessage).where(eq(this.t.agentQueuedMessage.threadId, threadId)).orderBy(asc(this.t.agentQueuedMessage.position), asc(this.t.agentQueuedMessage.createdAt));
|
|
891
1384
|
return rows.map(toQueuedMessage);
|
|
892
1385
|
}
|
|
893
1386
|
async getQueuedMessage(id) {
|
|
894
|
-
const [row] = await this.db.select().from(agentQueuedMessage).where(eq(agentQueuedMessage.id, id));
|
|
1387
|
+
const [row] = await this.db.select().from(this.t.agentQueuedMessage).where(eq(this.t.agentQueuedMessage.id, id));
|
|
895
1388
|
return row === void 0 ? null : toQueuedMessage(row);
|
|
896
1389
|
}
|
|
897
1390
|
async updateQueuedMessage(id, patch) {
|
|
@@ -907,52 +1400,47 @@ var DrizzleAgentStore = class {
|
|
|
907
1400
|
if (patch.interrupt !== void 0) {
|
|
908
1401
|
updates.interrupt = patch.interrupt;
|
|
909
1402
|
}
|
|
910
|
-
await this.db.update(agentQueuedMessage).set(updates).where(eq(agentQueuedMessage.id, id));
|
|
1403
|
+
await this.db.update(this.t.agentQueuedMessage).set(updates).where(eq(this.t.agentQueuedMessage.id, id));
|
|
911
1404
|
return this.getQueuedMessage(id);
|
|
912
1405
|
}
|
|
913
1406
|
/** Rewrites the thread's positions as 0..n-1 in the new order — a queue is a handful of rows. */
|
|
914
|
-
async moveQueuedMessage(id,
|
|
1407
|
+
async moveQueuedMessage(id, index4) {
|
|
915
1408
|
const moving = await this.getQueuedMessage(id);
|
|
916
1409
|
if (moving === null) {
|
|
917
1410
|
return false;
|
|
918
1411
|
}
|
|
919
1412
|
const order = (await this.listQueue(moving.threadId)).filter((message) => message.id !== id);
|
|
920
|
-
const target = Math.max(0, Math.min(order.length, Math.trunc(
|
|
1413
|
+
const target = Math.max(0, Math.min(order.length, Math.trunc(index4)));
|
|
921
1414
|
order.splice(target, 0, moving);
|
|
922
1415
|
for (const [position, message] of order.entries()) {
|
|
923
|
-
await this.db.update(agentQueuedMessage).set({
|
|
1416
|
+
await this.db.update(this.t.agentQueuedMessage).set({
|
|
924
1417
|
position
|
|
925
|
-
}).where(eq(agentQueuedMessage.id, message.id));
|
|
1418
|
+
}).where(eq(this.t.agentQueuedMessage.id, message.id));
|
|
926
1419
|
}
|
|
927
1420
|
return true;
|
|
928
1421
|
}
|
|
929
1422
|
async removeQueuedMessage(id) {
|
|
930
|
-
const removed = await this.db.delete(agentQueuedMessage).where(eq(agentQueuedMessage.id, id)).
|
|
931
|
-
|
|
932
|
-
});
|
|
933
|
-
return removed.length > 0;
|
|
1423
|
+
const removed = await affectedRows(this.dialect, this.db.delete(this.t.agentQueuedMessage).where(eq(this.t.agentQueuedMessage.id, id)), this.t.agentQueuedMessage.id);
|
|
1424
|
+
return removed > 0;
|
|
934
1425
|
}
|
|
935
1426
|
async clearQueue(threadId) {
|
|
936
|
-
|
|
937
|
-
id: agentQueuedMessage.id
|
|
938
|
-
});
|
|
939
|
-
return removed.length;
|
|
1427
|
+
return affectedRows(this.dialect, this.db.delete(this.t.agentQueuedMessage).where(eq(this.t.agentQueuedMessage.threadId, threadId)), this.t.agentQueuedMessage.id);
|
|
940
1428
|
}
|
|
941
1429
|
async queuePause(threadId) {
|
|
942
1430
|
const [thread] = await this.db.select({
|
|
943
|
-
queuePause: agentThread.queuePause
|
|
944
|
-
}).from(agentThread).where(eq(agentThread.id, threadId));
|
|
1431
|
+
queuePause: this.t.agentThread.queuePause
|
|
1432
|
+
}).from(this.t.agentThread).where(eq(this.t.agentThread.id, threadId));
|
|
945
1433
|
return thread?.queuePause ?? null;
|
|
946
1434
|
}
|
|
947
1435
|
async setQueuePause(threadId, pause) {
|
|
948
|
-
await this.db.update(agentThread).set({
|
|
1436
|
+
await this.db.update(this.t.agentThread).set({
|
|
949
1437
|
queuePause: pause
|
|
950
|
-
}).where(eq(agentThread.id, threadId));
|
|
1438
|
+
}).where(eq(this.t.agentThread.id, threadId));
|
|
951
1439
|
}
|
|
952
1440
|
async setActiveStream(threadId, runId) {
|
|
953
|
-
await this.db.update(agentThread).set({
|
|
1441
|
+
await this.db.update(this.t.agentThread).set({
|
|
954
1442
|
activeStreamId: runId
|
|
955
|
-
}).where(eq(agentThread.id, threadId));
|
|
1443
|
+
}).where(eq(this.t.agentThread.id, threadId));
|
|
956
1444
|
}
|
|
957
1445
|
/**
|
|
958
1446
|
* Patch a thread's `title` and/or `defaultAgent`. Each field is only touched when PRESENT in
|
|
@@ -971,11 +1459,14 @@ var DrizzleAgentStore = class {
|
|
|
971
1459
|
if (patch.model !== void 0) {
|
|
972
1460
|
updates.model = patch.model;
|
|
973
1461
|
}
|
|
1462
|
+
if (patch.persona !== void 0) {
|
|
1463
|
+
updates.persona = patch.persona;
|
|
1464
|
+
}
|
|
974
1465
|
if (Object.keys(updates).length === 0) {
|
|
975
1466
|
return;
|
|
976
1467
|
}
|
|
977
1468
|
updates.updatedAt = /* @__PURE__ */ new Date();
|
|
978
|
-
await this.db.update(agentThread).set(updates).where(eq(agentThread.id, threadId));
|
|
1469
|
+
await this.db.update(this.t.agentThread).set(updates).where(eq(this.t.agentThread.id, threadId));
|
|
979
1470
|
}
|
|
980
1471
|
/**
|
|
981
1472
|
* The thread's default agent, projected — the caller wants one nullable scalar to decide which
|
|
@@ -985,14 +1476,21 @@ var DrizzleAgentStore = class {
|
|
|
985
1476
|
/** The thread's pinned model, projected like {@link defaultAgentForThread}. */
|
|
986
1477
|
async modelForThread(threadId) {
|
|
987
1478
|
const [thread] = await this.db.select({
|
|
988
|
-
model: agentThread.model
|
|
989
|
-
}).from(agentThread).where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));
|
|
1479
|
+
model: this.t.agentThread.model
|
|
1480
|
+
}).from(this.t.agentThread).where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));
|
|
990
1481
|
return thread?.model ?? null;
|
|
991
1482
|
}
|
|
1483
|
+
/** The thread's pinned persona, projected like {@link defaultAgentForThread}. */
|
|
1484
|
+
async personaForThread(threadId) {
|
|
1485
|
+
const [thread] = await this.db.select({
|
|
1486
|
+
persona: this.t.agentThread.persona
|
|
1487
|
+
}).from(agentThread).where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));
|
|
1488
|
+
return thread?.persona ?? null;
|
|
1489
|
+
}
|
|
992
1490
|
async defaultAgentForThread(threadId) {
|
|
993
1491
|
const [thread] = await this.db.select({
|
|
994
|
-
defaultAgent: agentThread.defaultAgent
|
|
995
|
-
}).from(agentThread).where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));
|
|
1492
|
+
defaultAgent: this.t.agentThread.defaultAgent
|
|
1493
|
+
}).from(this.t.agentThread).where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));
|
|
996
1494
|
return thread?.defaultAgent ?? null;
|
|
997
1495
|
}
|
|
998
1496
|
/**
|
|
@@ -1017,7 +1515,7 @@ var DrizzleAgentStore = class {
|
|
|
1017
1515
|
promptHash: run.promptHash ?? null,
|
|
1018
1516
|
parentRunId: run.parentRunId ?? null
|
|
1019
1517
|
};
|
|
1020
|
-
await this.db.insert(agentRun).values(runRow);
|
|
1518
|
+
await this.db.insert(this.t.agentRun).values(runRow);
|
|
1021
1519
|
}
|
|
1022
1520
|
/** Settle a run's outcome. A no-op when the run is unknown (mirrors `setTitle`/`updateThread`). */
|
|
1023
1521
|
async recordRunEnd(end) {
|
|
@@ -1034,16 +1532,16 @@ var DrizzleAgentStore = class {
|
|
|
1034
1532
|
if (end.errorMessage !== void 0) {
|
|
1035
1533
|
updates.errorMessage = end.errorMessage;
|
|
1036
1534
|
}
|
|
1037
|
-
await this.db.update(agentRun).set(updates).where(eq(agentRun.id, end.runId));
|
|
1535
|
+
await this.db.update(this.t.agentRun).set(updates).where(eq(this.t.agentRun.id, end.runId));
|
|
1038
1536
|
}
|
|
1039
1537
|
/** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */
|
|
1040
1538
|
async bumpRunRetries(runId) {
|
|
1041
|
-
await this.db.update(agentRun).set({
|
|
1042
|
-
retries: sql2`${agentRun.retries} + 1`
|
|
1043
|
-
}).where(eq(agentRun.id, runId));
|
|
1539
|
+
await this.db.update(this.t.agentRun).set({
|
|
1540
|
+
retries: sql2`${this.t.agentRun.retries} + 1`
|
|
1541
|
+
}).where(eq(this.t.agentRun.id, runId));
|
|
1044
1542
|
}
|
|
1045
1543
|
async appendMessage(input) {
|
|
1046
|
-
const [thread] = await this.db.select().from(agentThread).where(eq(agentThread.id, input.threadId));
|
|
1544
|
+
const [thread] = await this.db.select().from(this.t.agentThread).where(eq(this.t.agentThread.id, input.threadId));
|
|
1047
1545
|
if (thread === void 0) {
|
|
1048
1546
|
throw new Error(`thread ${input.threadId} not found`);
|
|
1049
1547
|
}
|
|
@@ -1059,52 +1557,54 @@ var DrizzleAgentStore = class {
|
|
|
1059
1557
|
followUps: input.followUps ?? null,
|
|
1060
1558
|
usage: input.usage ?? null,
|
|
1061
1559
|
agentName: input.agentName ?? null,
|
|
1560
|
+
persona: input.persona ?? null,
|
|
1062
1561
|
runId: input.runId ?? null,
|
|
1063
1562
|
reasoning: input.reasoning ?? null,
|
|
1064
1563
|
reasoningMs: input.reasoningMs ?? null,
|
|
1065
1564
|
ui: input.ui ?? null,
|
|
1066
1565
|
feedback: null,
|
|
1566
|
+
seq: await this.nextMessageSeq(input.threadId),
|
|
1067
1567
|
createdAt: now
|
|
1068
1568
|
};
|
|
1069
|
-
await this.db.insert(agentMessage).values(message);
|
|
1070
|
-
await this.db.update(agentThread).set({
|
|
1569
|
+
await this.db.insert(this.t.agentMessage).values(message);
|
|
1570
|
+
await this.db.update(this.t.agentThread).set({
|
|
1071
1571
|
updatedAt: now
|
|
1072
|
-
}).where(eq(agentThread.id, input.threadId));
|
|
1572
|
+
}).where(eq(this.t.agentThread.id, input.threadId));
|
|
1073
1573
|
return this.toStoredMessage(message);
|
|
1074
1574
|
}
|
|
1075
1575
|
async setMessageToolResults(messageId, results) {
|
|
1076
|
-
await this.db.update(agentMessage).set({
|
|
1576
|
+
await this.db.update(this.t.agentMessage).set({
|
|
1077
1577
|
toolResults: results
|
|
1078
|
-
}).where(eq(agentMessage.id, messageId));
|
|
1578
|
+
}).where(eq(this.t.agentMessage.id, messageId));
|
|
1079
1579
|
}
|
|
1080
1580
|
async setMessageUi(messageId, ui) {
|
|
1081
|
-
await this.db.update(agentMessage).set({
|
|
1581
|
+
await this.db.update(this.t.agentMessage).set({
|
|
1082
1582
|
ui: ui.length > 0 ? ui : null
|
|
1083
|
-
}).where(eq(agentMessage.id, messageId));
|
|
1583
|
+
}).where(eq(this.t.agentMessage.id, messageId));
|
|
1084
1584
|
}
|
|
1085
1585
|
async threadOfMessage(messageId) {
|
|
1086
1586
|
const [row] = await this.db.select({
|
|
1087
|
-
threadId: agentMessage.threadId
|
|
1088
|
-
}).from(agentMessage).where(eq(agentMessage.id, messageId)).limit(1);
|
|
1587
|
+
threadId: this.t.agentMessage.threadId
|
|
1588
|
+
}).from(this.t.agentMessage).where(eq(this.t.agentMessage.id, messageId)).limit(1);
|
|
1089
1589
|
return row?.threadId ?? null;
|
|
1090
1590
|
}
|
|
1091
1591
|
async setMessageFeedback(messageId, feedback) {
|
|
1092
|
-
await this.db.update(agentMessage).set({
|
|
1592
|
+
await this.db.update(this.t.agentMessage).set({
|
|
1093
1593
|
feedback
|
|
1094
|
-
}).where(eq(agentMessage.id, messageId));
|
|
1594
|
+
}).where(eq(this.t.agentMessage.id, messageId));
|
|
1095
1595
|
}
|
|
1096
1596
|
async truncateFrom(threadId, messageId) {
|
|
1097
|
-
const messages = await this.db.select().from(agentMessage).where(eq(agentMessage.threadId, threadId)).orderBy(
|
|
1597
|
+
const messages = await this.db.select().from(this.t.agentMessage).where(eq(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
|
|
1098
1598
|
const cutoff = messages.findIndex((message) => message.id === messageId);
|
|
1099
1599
|
if (cutoff < 0) {
|
|
1100
1600
|
return;
|
|
1101
1601
|
}
|
|
1102
1602
|
const doomedIds = messages.slice(cutoff).map((message) => message.id);
|
|
1103
|
-
await this.db.delete(agentToolCall).where(inArray(agentToolCall.messageId, doomedIds));
|
|
1104
|
-
await this.db.delete(agentMessage).where(inArray(agentMessage.id, doomedIds));
|
|
1603
|
+
await this.db.delete(this.t.agentToolCall).where(inArray(this.t.agentToolCall.messageId, doomedIds));
|
|
1604
|
+
await this.db.delete(this.t.agentMessage).where(inArray(this.t.agentMessage.id, doomedIds));
|
|
1105
1605
|
}
|
|
1106
1606
|
async recordToolCall(input) {
|
|
1107
|
-
await this.db.insert(agentToolCall).values({
|
|
1607
|
+
await this.db.insert(this.t.agentToolCall).values({
|
|
1108
1608
|
id: input.toolCallId,
|
|
1109
1609
|
messageId: input.messageId,
|
|
1110
1610
|
toolName: input.toolName,
|
|
@@ -1149,18 +1649,18 @@ var DrizzleAgentStore = class {
|
|
|
1149
1649
|
if (input.status === "executed" || input.status === "auto_executed") {
|
|
1150
1650
|
updates.executedAt = /* @__PURE__ */ new Date();
|
|
1151
1651
|
}
|
|
1152
|
-
await this.db.update(agentToolCall).set(updates).where(eq(agentToolCall.id, input.toolCallId));
|
|
1652
|
+
await this.db.update(this.t.agentToolCall).set(updates).where(eq(this.t.agentToolCall.id, input.toolCallId));
|
|
1153
1653
|
}
|
|
1154
1654
|
async toolCallOutcomes(toolCallIds) {
|
|
1155
1655
|
if (toolCallIds.length === 0) {
|
|
1156
1656
|
return [];
|
|
1157
1657
|
}
|
|
1158
1658
|
const rows = await this.db.select({
|
|
1159
|
-
id: agentToolCall.id,
|
|
1160
|
-
status: agentToolCall.status,
|
|
1161
|
-
output: agentToolCall.output,
|
|
1162
|
-
error: agentToolCall.error
|
|
1163
|
-
}).from(agentToolCall).where(inArray(agentToolCall.id, [
|
|
1659
|
+
id: this.t.agentToolCall.id,
|
|
1660
|
+
status: this.t.agentToolCall.status,
|
|
1661
|
+
output: this.t.agentToolCall.output,
|
|
1662
|
+
error: this.t.agentToolCall.error
|
|
1663
|
+
}).from(this.t.agentToolCall).where(inArray(this.t.agentToolCall.id, [
|
|
1164
1664
|
...toolCallIds
|
|
1165
1665
|
]));
|
|
1166
1666
|
return rows.map((row) => ({
|
|
@@ -1175,14 +1675,14 @@ var DrizzleAgentStore = class {
|
|
|
1175
1675
|
}));
|
|
1176
1676
|
}
|
|
1177
1677
|
async failUnsettledToolCalls(runId, error) {
|
|
1178
|
-
const pending = and(eq(agentToolCall.runId, runId), eq(agentToolCall.status, "pending_approval"));
|
|
1678
|
+
const pending = and(eq(this.t.agentToolCall.runId, runId), eq(this.t.agentToolCall.status, "pending_approval"));
|
|
1179
1679
|
const rows = await this.db.select({
|
|
1180
|
-
id: agentToolCall.id
|
|
1181
|
-
}).from(agentToolCall).where(pending);
|
|
1680
|
+
id: this.t.agentToolCall.id
|
|
1681
|
+
}).from(this.t.agentToolCall).where(pending);
|
|
1182
1682
|
if (rows.length === 0) {
|
|
1183
1683
|
return 0;
|
|
1184
1684
|
}
|
|
1185
|
-
await this.db.update(agentToolCall).set({
|
|
1685
|
+
await this.db.update(this.t.agentToolCall).set({
|
|
1186
1686
|
status: "failed",
|
|
1187
1687
|
error
|
|
1188
1688
|
}).where(pending);
|
|
@@ -1207,11 +1707,11 @@ var DrizzleAgentStore = class {
|
|
|
1207
1707
|
return [];
|
|
1208
1708
|
}
|
|
1209
1709
|
const rows = await this.db.select({
|
|
1210
|
-
attachments: agentMessage.attachments
|
|
1211
|
-
}).from(agentMessage).innerJoin(agentThread, eq(agentMessage.threadId, agentThread.id)).where(and(eq(agentThread.actorRef, actorRef), isNotNull(agentMessage.attachments)));
|
|
1710
|
+
attachments: this.t.agentMessage.attachments
|
|
1711
|
+
}).from(this.t.agentMessage).innerJoin(this.t.agentThread, eq(this.t.agentMessage.threadId, this.t.agentThread.id)).where(and(eq(this.t.agentThread.actorRef, actorRef), isNotNull(this.t.agentMessage.attachments)));
|
|
1212
1712
|
const queued = await this.db.select({
|
|
1213
|
-
attachments: agentQueuedMessage.attachments
|
|
1214
|
-
}).from(agentQueuedMessage).innerJoin(agentThread, eq(agentQueuedMessage.threadId, agentThread.id)).where(and(eq(agentThread.actorRef, actorRef), isNotNull(agentQueuedMessage.attachments)));
|
|
1713
|
+
attachments: this.t.agentQueuedMessage.attachments
|
|
1714
|
+
}).from(this.t.agentQueuedMessage).innerJoin(this.t.agentThread, eq(this.t.agentQueuedMessage.threadId, this.t.agentThread.id)).where(and(eq(this.t.agentThread.actorRef, actorRef), isNotNull(this.t.agentQueuedMessage.attachments)));
|
|
1215
1715
|
const wanted = new Set(mediaIds);
|
|
1216
1716
|
const found = /* @__PURE__ */ new Set();
|
|
1217
1717
|
for (const row of [
|
|
@@ -1229,7 +1729,7 @@ var DrizzleAgentStore = class {
|
|
|
1229
1729
|
].filter((mediaId) => found.has(mediaId));
|
|
1230
1730
|
}
|
|
1231
1731
|
async recordUsage(input) {
|
|
1232
|
-
await this.db.insert(agentTokenUsage).values({
|
|
1732
|
+
await this.db.insert(this.t.agentTokenUsage).values({
|
|
1233
1733
|
id: crypto.randomUUID(),
|
|
1234
1734
|
threadId: input.threadId,
|
|
1235
1735
|
actorRef: input.actorRef,
|
|
@@ -1250,7 +1750,7 @@ var DrizzleAgentStore = class {
|
|
|
1250
1750
|
async usageBetween(actorRef, fromDay, toDay) {
|
|
1251
1751
|
const start = /* @__PURE__ */ new Date(`${fromDay}T00:00:00.000Z`);
|
|
1252
1752
|
const end = /* @__PURE__ */ new Date(`${toDay}T23:59:59.999Z`);
|
|
1253
|
-
const rows = await this.db.select().from(agentTokenUsage).where(and(eq(agentTokenUsage.actorRef, actorRef), gte(agentTokenUsage.createdAt, start), lte(agentTokenUsage.createdAt, end)));
|
|
1753
|
+
const rows = await this.db.select().from(this.t.agentTokenUsage).where(and(eq(this.t.agentTokenUsage.actorRef, actorRef), gte(this.t.agentTokenUsage.createdAt, start), lte(this.t.agentTokenUsage.createdAt, end)));
|
|
1254
1754
|
const usedTokens = rows.reduce((sum2, row) => sum2 + row.inputTokens + row.outputTokens, 0);
|
|
1255
1755
|
const costUsd = rows.reduce((sum2, row) => sum2 + (row.costUsd ?? 0), 0);
|
|
1256
1756
|
return {
|
|
@@ -1269,6 +1769,7 @@ var DrizzleAgentStore = class {
|
|
|
1269
1769
|
...thread.model != null ? {
|
|
1270
1770
|
model: thread.model
|
|
1271
1771
|
} : {},
|
|
1772
|
+
persona: thread.persona ?? null,
|
|
1272
1773
|
...lastContent !== void 0 ? {
|
|
1273
1774
|
lastMessagePreview: lastContent.slice(0, 120)
|
|
1274
1775
|
} : {}
|
|
@@ -1298,6 +1799,9 @@ var DrizzleAgentStore = class {
|
|
|
1298
1799
|
...message.agentName != null ? {
|
|
1299
1800
|
agentName: message.agentName
|
|
1300
1801
|
} : {},
|
|
1802
|
+
...message.persona != null ? {
|
|
1803
|
+
persona: message.persona
|
|
1804
|
+
} : {},
|
|
1301
1805
|
...message.runId != null ? {
|
|
1302
1806
|
runId: message.runId
|
|
1303
1807
|
} : {},
|
|
@@ -1328,6 +1832,9 @@ function toQueuedMessage(row) {
|
|
|
1328
1832
|
...row.agentName !== null ? {
|
|
1329
1833
|
agentName: row.agentName
|
|
1330
1834
|
} : {},
|
|
1835
|
+
...row.persona !== null ? {
|
|
1836
|
+
persona: row.persona
|
|
1837
|
+
} : {},
|
|
1331
1838
|
...row.model !== null ? {
|
|
1332
1839
|
model: row.model
|
|
1333
1840
|
} : {},
|
|
@@ -1458,11 +1965,15 @@ var DrizzleGovernanceQueries = class {
|
|
|
1458
1965
|
static {
|
|
1459
1966
|
__name(this, "DrizzleGovernanceQueries");
|
|
1460
1967
|
}
|
|
1461
|
-
db;
|
|
1462
1968
|
pricingStore;
|
|
1969
|
+
db;
|
|
1970
|
+
dialect;
|
|
1971
|
+
t;
|
|
1463
1972
|
constructor(db, pricingStore) {
|
|
1464
|
-
this.db = db;
|
|
1465
1973
|
this.pricingStore = pricingStore;
|
|
1974
|
+
this.dialect = agentDialectOf(db);
|
|
1975
|
+
this.t = agentTablesFor(this.dialect);
|
|
1976
|
+
this.db = asBuilder(db);
|
|
1466
1977
|
}
|
|
1467
1978
|
async loadPricing() {
|
|
1468
1979
|
const prices = await this.pricingStore.listCurrentPrices();
|
|
@@ -1479,7 +1990,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1479
1990
|
}
|
|
1480
1991
|
async usageInRange(range) {
|
|
1481
1992
|
const { start, end } = dayBoundsUtc(range);
|
|
1482
|
-
const rows = await this.db.select().from(agentTokenUsage).where(and2(gte2(agentTokenUsage.createdAt, start), lte2(agentTokenUsage.createdAt, end)));
|
|
1993
|
+
const rows = await this.db.select().from(this.t.agentTokenUsage).where(and2(gte2(this.t.agentTokenUsage.createdAt, start), lte2(this.t.agentTokenUsage.createdAt, end)));
|
|
1483
1994
|
return rows.map(toUsageInput);
|
|
1484
1995
|
}
|
|
1485
1996
|
async spendByModel(range) {
|
|
@@ -1504,7 +2015,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1504
2015
|
if (threadIds.length === 0) {
|
|
1505
2016
|
return [];
|
|
1506
2017
|
}
|
|
1507
|
-
const threads = await this.db.select().from(agentThread).where(and2(inArray2(agentThread.id, threadIds), isNull2(agentThread.deletedAt)));
|
|
2018
|
+
const threads = await this.db.select().from(this.t.agentThread).where(and2(inArray2(this.t.agentThread.id, threadIds), isNull2(this.t.agentThread.deletedAt)));
|
|
1508
2019
|
const threadsById = new Map(threads.map((thread) => [
|
|
1509
2020
|
thread.id,
|
|
1510
2021
|
{
|
|
@@ -1523,14 +2034,14 @@ var DrizzleGovernanceQueries = class {
|
|
|
1523
2034
|
}
|
|
1524
2035
|
async recentToolCalls(limit) {
|
|
1525
2036
|
const rows = await this.db.select({
|
|
1526
|
-
toolCallId: agentToolCall.id,
|
|
1527
|
-
toolName: agentToolCall.toolName,
|
|
1528
|
-
toolType: agentToolCall.toolType,
|
|
1529
|
-
status: agentToolCall.status,
|
|
1530
|
-
threadId: agentMessage.threadId,
|
|
1531
|
-
createdAt: agentToolCall.createdAt,
|
|
1532
|
-
runId: agentToolCall.runId
|
|
1533
|
-
}).from(agentToolCall).innerJoin(agentMessage, eq2(agentToolCall.messageId, agentMessage.id)).orderBy(desc2(agentToolCall.createdAt), desc2(agentToolCall.id)).limit(limit);
|
|
2037
|
+
toolCallId: this.t.agentToolCall.id,
|
|
2038
|
+
toolName: this.t.agentToolCall.toolName,
|
|
2039
|
+
toolType: this.t.agentToolCall.toolType,
|
|
2040
|
+
status: this.t.agentToolCall.status,
|
|
2041
|
+
threadId: this.t.agentMessage.threadId,
|
|
2042
|
+
createdAt: this.t.agentToolCall.createdAt,
|
|
2043
|
+
runId: this.t.agentToolCall.runId
|
|
2044
|
+
}).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq2(this.t.agentToolCall.messageId, this.t.agentMessage.id)).orderBy(desc2(this.t.agentToolCall.createdAt), desc2(this.t.agentToolCall.id)).limit(limit);
|
|
1534
2045
|
return rows.map((row) => ({
|
|
1535
2046
|
toolCallId: row.toolCallId,
|
|
1536
2047
|
toolName: row.toolName,
|
|
@@ -1558,9 +2069,9 @@ var DrizzleGovernanceQueries = class {
|
|
|
1558
2069
|
return rollups;
|
|
1559
2070
|
}
|
|
1560
2071
|
const messageCounts = await this.db.select({
|
|
1561
|
-
threadId: agentMessage.threadId,
|
|
2072
|
+
threadId: this.t.agentMessage.threadId,
|
|
1562
2073
|
value: count()
|
|
1563
|
-
}).from(agentMessage).where(inArray2(agentMessage.threadId, threadIds)).groupBy(agentMessage.threadId);
|
|
2074
|
+
}).from(this.t.agentMessage).where(inArray2(this.t.agentMessage.threadId, threadIds)).groupBy(this.t.agentMessage.threadId);
|
|
1564
2075
|
for (const row of messageCounts) {
|
|
1565
2076
|
const bucket = rollups.get(row.threadId);
|
|
1566
2077
|
if (bucket !== void 0) {
|
|
@@ -1568,10 +2079,10 @@ var DrizzleGovernanceQueries = class {
|
|
|
1568
2079
|
}
|
|
1569
2080
|
}
|
|
1570
2081
|
const usageTotals = await this.db.select({
|
|
1571
|
-
threadId: agentTokenUsage.threadId,
|
|
1572
|
-
inputTokens: sum(agentTokenUsage.inputTokens),
|
|
1573
|
-
outputTokens: sum(agentTokenUsage.outputTokens)
|
|
1574
|
-
}).from(agentTokenUsage).where(inArray2(agentTokenUsage.threadId, threadIds)).groupBy(agentTokenUsage.threadId);
|
|
2082
|
+
threadId: this.t.agentTokenUsage.threadId,
|
|
2083
|
+
inputTokens: sum(this.t.agentTokenUsage.inputTokens),
|
|
2084
|
+
outputTokens: sum(this.t.agentTokenUsage.outputTokens)
|
|
2085
|
+
}).from(this.t.agentTokenUsage).where(inArray2(this.t.agentTokenUsage.threadId, threadIds)).groupBy(this.t.agentTokenUsage.threadId);
|
|
1575
2086
|
for (const row of usageTotals) {
|
|
1576
2087
|
const bucket = rollups.get(row.threadId);
|
|
1577
2088
|
if (bucket !== void 0) {
|
|
@@ -1596,12 +2107,12 @@ var DrizzleGovernanceQueries = class {
|
|
|
1596
2107
|
});
|
|
1597
2108
|
}
|
|
1598
2109
|
async recentThreads(limit) {
|
|
1599
|
-
const threads = await this.db.select().from(agentThread).where(isNull2(agentThread.deletedAt)).orderBy(desc2(agentThread.updatedAt), desc2(agentThread.id)).limit(limit);
|
|
2110
|
+
const threads = await this.db.select().from(this.t.agentThread).where(isNull2(this.t.agentThread.deletedAt)).orderBy(desc2(this.t.agentThread.updatedAt), desc2(this.t.agentThread.id)).limit(limit);
|
|
1600
2111
|
return this.toThreadActivityRows(threads);
|
|
1601
2112
|
}
|
|
1602
2113
|
async runsInRange(range) {
|
|
1603
2114
|
const { start, end } = dayBoundsUtc(range);
|
|
1604
|
-
return this.db.select().from(agentRun).where(and2(gte2(agentRun.startedAt, start), lte2(agentRun.startedAt, end)));
|
|
2115
|
+
return this.db.select().from(this.t.agentRun).where(and2(gte2(this.t.agentRun.startedAt, start), lte2(this.t.agentRun.startedAt, end)));
|
|
1605
2116
|
}
|
|
1606
2117
|
async runMetrics(range) {
|
|
1607
2118
|
const runs = await this.runsInRange(range);
|
|
@@ -1658,7 +2169,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1658
2169
|
}
|
|
1659
2170
|
async runErrors(range) {
|
|
1660
2171
|
const { start, end } = dayBoundsUtc(range);
|
|
1661
|
-
const runs = await this.db.select().from(agentRun).where(and2(gte2(agentRun.startedAt, start), lte2(agentRun.startedAt, end), eq2(agentRun.status, "failed")));
|
|
2172
|
+
const runs = await this.db.select().from(this.t.agentRun).where(and2(gte2(this.t.agentRun.startedAt, start), lte2(this.t.agentRun.startedAt, end), eq2(this.t.agentRun.status, "failed")));
|
|
1662
2173
|
const byError = /* @__PURE__ */ new Map();
|
|
1663
2174
|
for (const run of runs) {
|
|
1664
2175
|
const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;
|
|
@@ -1698,7 +2209,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1698
2209
|
return result;
|
|
1699
2210
|
}
|
|
1700
2211
|
async recentRuns(limit) {
|
|
1701
|
-
const runs = await this.db.select().from(agentRun).orderBy(desc2(agentRun.startedAt), desc2(agentRun.id)).limit(limit);
|
|
2212
|
+
const runs = await this.db.select().from(this.t.agentRun).orderBy(desc2(this.t.agentRun.startedAt), desc2(this.t.agentRun.id)).limit(limit);
|
|
1702
2213
|
return runs.map(toRecentRunRow);
|
|
1703
2214
|
}
|
|
1704
2215
|
/**
|
|
@@ -1708,16 +2219,16 @@ var DrizzleGovernanceQueries = class {
|
|
|
1708
2219
|
*/
|
|
1709
2220
|
async pendingApprovals(limit) {
|
|
1710
2221
|
const rows = await this.db.select({
|
|
1711
|
-
toolCallId: agentToolCall.id,
|
|
1712
|
-
toolName: agentToolCall.toolName,
|
|
1713
|
-
input: agentToolCall.input,
|
|
1714
|
-
threadId: agentThread.id,
|
|
1715
|
-
threadTitle: agentThread.title,
|
|
1716
|
-
actorRef: agentThread.actorRef,
|
|
1717
|
-
agentName: agentMessage.agentName,
|
|
1718
|
-
requestedAt: agentToolCall.createdAt,
|
|
1719
|
-
runId: agentToolCall.runId
|
|
1720
|
-
}).from(agentToolCall).innerJoin(agentMessage, eq2(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, eq2(agentMessage.threadId, agentThread.id)).where(eq2(agentToolCall.status, "pending_approval")).orderBy(agentToolCall.createdAt, agentToolCall.id).limit(limit);
|
|
2222
|
+
toolCallId: this.t.agentToolCall.id,
|
|
2223
|
+
toolName: this.t.agentToolCall.toolName,
|
|
2224
|
+
input: this.t.agentToolCall.input,
|
|
2225
|
+
threadId: this.t.agentThread.id,
|
|
2226
|
+
threadTitle: this.t.agentThread.title,
|
|
2227
|
+
actorRef: this.t.agentThread.actorRef,
|
|
2228
|
+
agentName: this.t.agentMessage.agentName,
|
|
2229
|
+
requestedAt: this.t.agentToolCall.createdAt,
|
|
2230
|
+
runId: this.t.agentToolCall.runId
|
|
2231
|
+
}).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq2(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, eq2(this.t.agentMessage.threadId, this.t.agentThread.id)).where(eq2(this.t.agentToolCall.status, "pending_approval")).orderBy(this.t.agentToolCall.createdAt, this.t.agentToolCall.id).limit(limit);
|
|
1721
2232
|
return rows.map((row) => ({
|
|
1722
2233
|
toolCallId: row.toolCallId,
|
|
1723
2234
|
toolName: row.toolName,
|
|
@@ -1739,11 +2250,11 @@ var DrizzleGovernanceQueries = class {
|
|
|
1739
2250
|
*/
|
|
1740
2251
|
async toolStats(range) {
|
|
1741
2252
|
const { start, end } = dayBoundsUtc(range);
|
|
1742
|
-
const calls = await this.db.select().from(agentToolCall).where(and2(gte2(agentToolCall.createdAt, start), lte2(agentToolCall.createdAt, end)));
|
|
2253
|
+
const calls = await this.db.select().from(this.t.agentToolCall).where(and2(gte2(this.t.agentToolCall.createdAt, start), lte2(this.t.agentToolCall.createdAt, end)));
|
|
1743
2254
|
const byTool = /* @__PURE__ */ new Map();
|
|
1744
2255
|
for (const call of calls) {
|
|
1745
|
-
const
|
|
1746
|
-
const bucket = byTool.get(
|
|
2256
|
+
const key2 = `${call.toolName} ${call.toolType}`;
|
|
2257
|
+
const bucket = byTool.get(key2) ?? {
|
|
1747
2258
|
toolName: call.toolName,
|
|
1748
2259
|
toolType: call.toolType,
|
|
1749
2260
|
calls: 0,
|
|
@@ -1757,7 +2268,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1757
2268
|
if (call.executionMs != null) {
|
|
1758
2269
|
bucket.executionMs.push(call.executionMs);
|
|
1759
2270
|
}
|
|
1760
|
-
byTool.set(
|
|
2271
|
+
byTool.set(key2, bucket);
|
|
1761
2272
|
}
|
|
1762
2273
|
const result = [];
|
|
1763
2274
|
for (const bucket of byTool.values()) {
|
|
@@ -1789,19 +2300,19 @@ var DrizzleGovernanceQueries = class {
|
|
|
1789
2300
|
if (filters?.toolType !== void 0 && !isToolKind(filters.toolType)) {
|
|
1790
2301
|
return emptyPage(query);
|
|
1791
2302
|
}
|
|
1792
|
-
const whereClause = and2(filters?.toolName !== void 0 ? eq2(agentToolCall.toolName, filters.toolName) : void 0, filters?.toolType !== void 0 && isToolKind(filters.toolType) ? eq2(agentToolCall.toolType, filters.toolType) : void 0, filters?.status !== void 0 && isToolCallStatus(filters.status) ? eq2(agentToolCall.status, filters.status) : void 0, filters?.threadId !== void 0 ? eq2(agentMessage.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? gte2(agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte2(agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
|
|
2303
|
+
const whereClause = and2(filters?.toolName !== void 0 ? eq2(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.toolType !== void 0 && isToolKind(filters.toolType) ? eq2(this.t.agentToolCall.toolType, filters.toolType) : void 0, filters?.status !== void 0 && isToolCallStatus(filters.status) ? eq2(this.t.agentToolCall.status, filters.status) : void 0, filters?.threadId !== void 0 ? eq2(this.t.agentMessage.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte2(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
|
|
1793
2304
|
const [totalRow] = await this.db.select({
|
|
1794
2305
|
value: count()
|
|
1795
|
-
}).from(agentToolCall).innerJoin(agentMessage, eq2(agentToolCall.messageId, agentMessage.id)).where(whereClause);
|
|
2306
|
+
}).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq2(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause);
|
|
1796
2307
|
const rows = await this.db.select({
|
|
1797
|
-
toolCallId: agentToolCall.id,
|
|
1798
|
-
toolName: agentToolCall.toolName,
|
|
1799
|
-
toolType: agentToolCall.toolType,
|
|
1800
|
-
status: agentToolCall.status,
|
|
1801
|
-
threadId: agentMessage.threadId,
|
|
1802
|
-
createdAt: agentToolCall.createdAt,
|
|
1803
|
-
runId: agentToolCall.runId
|
|
1804
|
-
}).from(agentToolCall).innerJoin(agentMessage, eq2(agentToolCall.messageId, agentMessage.id)).where(whereClause).orderBy(desc2(agentToolCall.createdAt), desc2(agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
|
|
2308
|
+
toolCallId: this.t.agentToolCall.id,
|
|
2309
|
+
toolName: this.t.agentToolCall.toolName,
|
|
2310
|
+
toolType: this.t.agentToolCall.toolType,
|
|
2311
|
+
status: this.t.agentToolCall.status,
|
|
2312
|
+
threadId: this.t.agentMessage.threadId,
|
|
2313
|
+
createdAt: this.t.agentToolCall.createdAt,
|
|
2314
|
+
runId: this.t.agentToolCall.runId
|
|
2315
|
+
}).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq2(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause).orderBy(desc2(this.t.agentToolCall.createdAt), desc2(this.t.agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
|
|
1805
2316
|
return {
|
|
1806
2317
|
rows: rows.map((row) => ({
|
|
1807
2318
|
toolCallId: row.toolCallId,
|
|
@@ -1825,11 +2336,11 @@ var DrizzleGovernanceQueries = class {
|
|
|
1825
2336
|
*/
|
|
1826
2337
|
async threadsPage(query) {
|
|
1827
2338
|
const filters = query.where;
|
|
1828
|
-
const whereClause = and2(isNull2(agentThread.deletedAt), filters?.actorRef !== void 0 ? eq2(agentThread.actorRef, filters.actorRef) : void 0, filters?.title !== void 0 ? like(sql3`lower(${agentThread.title})`, `%${filters.title.toLowerCase()}%`) : void 0, filters?.fromDay !== void 0 ? gte2(agentThread.updatedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte2(agentThread.updatedAt, dayEndUtc(filters.toDay)) : void 0);
|
|
2339
|
+
const whereClause = and2(isNull2(this.t.agentThread.deletedAt), filters?.actorRef !== void 0 ? eq2(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.title !== void 0 ? like(sql3`lower(${this.t.agentThread.title})`, `%${filters.title.toLowerCase()}%`) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentThread.updatedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte2(this.t.agentThread.updatedAt, dayEndUtc(filters.toDay)) : void 0);
|
|
1829
2340
|
const [totalRow] = await this.db.select({
|
|
1830
2341
|
value: count()
|
|
1831
|
-
}).from(agentThread).where(whereClause);
|
|
1832
|
-
const threads = await this.db.select().from(agentThread).where(whereClause).orderBy(desc2(agentThread.updatedAt), desc2(agentThread.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
|
|
2342
|
+
}).from(this.t.agentThread).where(whereClause);
|
|
2343
|
+
const threads = await this.db.select().from(this.t.agentThread).where(whereClause).orderBy(desc2(this.t.agentThread.updatedAt), desc2(this.t.agentThread.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
|
|
1833
2344
|
const rows = await this.toThreadActivityRows(threads);
|
|
1834
2345
|
return {
|
|
1835
2346
|
rows,
|
|
@@ -1847,11 +2358,11 @@ var DrizzleGovernanceQueries = class {
|
|
|
1847
2358
|
if (filters?.status !== void 0 && !isRunStatus(filters.status)) {
|
|
1848
2359
|
return emptyPage(query);
|
|
1849
2360
|
}
|
|
1850
|
-
const whereClause = and2(filters?.agentName !== void 0 ? eq2(agentRun.agentName, filters.agentName) : void 0, filters?.status !== void 0 && isRunStatus(filters.status) ? eq2(agentRun.status, filters.status) : void 0, filters?.errorCode !== void 0 ? eq2(agentRun.errorCode, filters.errorCode) : void 0, filters?.threadId !== void 0 ? eq2(agentRun.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? gte2(agentRun.startedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte2(agentRun.startedAt, dayEndUtc(filters.toDay)) : void 0);
|
|
2361
|
+
const whereClause = and2(filters?.agentName !== void 0 ? eq2(this.t.agentRun.agentName, filters.agentName) : void 0, filters?.status !== void 0 && isRunStatus(filters.status) ? eq2(this.t.agentRun.status, filters.status) : void 0, filters?.errorCode !== void 0 ? eq2(this.t.agentRun.errorCode, filters.errorCode) : void 0, filters?.threadId !== void 0 ? eq2(this.t.agentRun.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentRun.startedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte2(this.t.agentRun.startedAt, dayEndUtc(filters.toDay)) : void 0);
|
|
1851
2362
|
const [totalRow] = await this.db.select({
|
|
1852
2363
|
value: count()
|
|
1853
|
-
}).from(agentRun).where(whereClause);
|
|
1854
|
-
const runs = await this.db.select().from(agentRun).where(whereClause).orderBy(desc2(agentRun.startedAt), desc2(agentRun.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
|
|
2364
|
+
}).from(this.t.agentRun).where(whereClause);
|
|
2365
|
+
const runs = await this.db.select().from(this.t.agentRun).where(whereClause).orderBy(desc2(this.t.agentRun.startedAt), desc2(this.t.agentRun.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
|
|
1855
2366
|
return {
|
|
1856
2367
|
rows: runs.map(toRecentRunRow),
|
|
1857
2368
|
total: totalRow?.value ?? 0,
|
|
@@ -1871,21 +2382,21 @@ var DrizzleGovernanceQueries = class {
|
|
|
1871
2382
|
*/
|
|
1872
2383
|
async approvalsPage(query) {
|
|
1873
2384
|
const filters = query.where;
|
|
1874
|
-
const whereClause = and2(eq2(agentToolCall.status, "pending_approval"), filters?.toolName !== void 0 ? eq2(agentToolCall.toolName, filters.toolName) : void 0, filters?.threadId !== void 0 ? eq2(agentThread.id, filters.threadId) : void 0, filters?.actorRef !== void 0 ? eq2(agentThread.actorRef, filters.actorRef) : void 0, filters?.agentName !== void 0 ? eq2(agentMessage.agentName, filters.agentName) : void 0, filters?.fromDay !== void 0 ? gte2(agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte2(agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
|
|
2385
|
+
const whereClause = and2(eq2(this.t.agentToolCall.status, "pending_approval"), filters?.toolName !== void 0 ? eq2(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.threadId !== void 0 ? eq2(this.t.agentThread.id, filters.threadId) : void 0, filters?.actorRef !== void 0 ? eq2(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.agentName !== void 0 ? eq2(this.t.agentMessage.agentName, filters.agentName) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte2(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
|
|
1875
2386
|
const [totalRow] = await this.db.select({
|
|
1876
2387
|
value: count()
|
|
1877
|
-
}).from(agentToolCall).innerJoin(agentMessage, eq2(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, eq2(agentMessage.threadId, agentThread.id)).where(whereClause);
|
|
2388
|
+
}).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq2(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, eq2(this.t.agentMessage.threadId, this.t.agentThread.id)).where(whereClause);
|
|
1878
2389
|
const rows = await this.db.select({
|
|
1879
|
-
toolCallId: agentToolCall.id,
|
|
1880
|
-
toolName: agentToolCall.toolName,
|
|
1881
|
-
input: agentToolCall.input,
|
|
1882
|
-
threadId: agentThread.id,
|
|
1883
|
-
threadTitle: agentThread.title,
|
|
1884
|
-
actorRef: agentThread.actorRef,
|
|
1885
|
-
agentName: agentMessage.agentName,
|
|
1886
|
-
requestedAt: agentToolCall.createdAt,
|
|
1887
|
-
runId: agentToolCall.runId
|
|
1888
|
-
}).from(agentToolCall).innerJoin(agentMessage, eq2(agentToolCall.messageId, agentMessage.id)).innerJoin(agentThread, eq2(agentMessage.threadId, agentThread.id)).where(whereClause).orderBy(asc2(agentToolCall.createdAt), asc2(agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
|
|
2390
|
+
toolCallId: this.t.agentToolCall.id,
|
|
2391
|
+
toolName: this.t.agentToolCall.toolName,
|
|
2392
|
+
input: this.t.agentToolCall.input,
|
|
2393
|
+
threadId: this.t.agentThread.id,
|
|
2394
|
+
threadTitle: this.t.agentThread.title,
|
|
2395
|
+
actorRef: this.t.agentThread.actorRef,
|
|
2396
|
+
agentName: this.t.agentMessage.agentName,
|
|
2397
|
+
requestedAt: this.t.agentToolCall.createdAt,
|
|
2398
|
+
runId: this.t.agentToolCall.runId
|
|
2399
|
+
}).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq2(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, eq2(this.t.agentMessage.threadId, this.t.agentThread.id)).where(whereClause).orderBy(asc2(this.t.agentToolCall.createdAt), asc2(this.t.agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
|
|
1889
2400
|
return {
|
|
1890
2401
|
rows: rows.map((row) => ({
|
|
1891
2402
|
toolCallId: row.toolCallId,
|
|
@@ -1910,13 +2421,13 @@ var DrizzleGovernanceQueries = class {
|
|
|
1910
2421
|
*/
|
|
1911
2422
|
async runDetail(runId) {
|
|
1912
2423
|
const [row] = await this.db.select({
|
|
1913
|
-
run: agentRun,
|
|
1914
|
-
thread: agentThread
|
|
1915
|
-
}).from(agentRun).innerJoin(agentThread, eq2(agentRun.threadId, agentThread.id)).where(eq2(agentRun.id, runId)).limit(1);
|
|
2424
|
+
run: this.t.agentRun,
|
|
2425
|
+
thread: this.t.agentThread
|
|
2426
|
+
}).from(this.t.agentRun).innerJoin(this.t.agentThread, eq2(this.t.agentRun.threadId, this.t.agentThread.id)).where(eq2(this.t.agentRun.id, runId)).limit(1);
|
|
1916
2427
|
if (row === void 0) {
|
|
1917
2428
|
return null;
|
|
1918
2429
|
}
|
|
1919
|
-
const toolCalls = await this.db.select().from(agentToolCall).where(eq2(agentToolCall.runId, runId)).orderBy(asc2(agentToolCall.createdAt), asc2(agentToolCall.id));
|
|
2430
|
+
const toolCalls = await this.db.select().from(this.t.agentToolCall).where(eq2(this.t.agentToolCall.runId, runId)).orderBy(asc2(this.t.agentToolCall.createdAt), asc2(this.t.agentToolCall.id));
|
|
1920
2431
|
return {
|
|
1921
2432
|
run: toRecentRunRow(row.run),
|
|
1922
2433
|
thread: {
|
|
@@ -1935,22 +2446,27 @@ var DrizzleGovernanceQueries = class {
|
|
|
1935
2446
|
* message. Soft-deleted threads are returned with `deleted: true`; an audit still needs them.
|
|
1936
2447
|
*/
|
|
1937
2448
|
async threadDetail(query) {
|
|
1938
|
-
const [thread] = await this.db.select().from(agentThread).where(eq2(agentThread.id, query.threadId)).limit(1);
|
|
2449
|
+
const [thread] = await this.db.select().from(this.t.agentThread).where(eq2(this.t.agentThread.id, query.threadId)).limit(1);
|
|
1939
2450
|
if (thread === void 0) {
|
|
1940
2451
|
return null;
|
|
1941
2452
|
}
|
|
1942
2453
|
const pricing = await this.loadPricing();
|
|
1943
|
-
const usageRows = await this.db.select().from(agentTokenUsage).where(eq2(agentTokenUsage.threadId, thread.id));
|
|
2454
|
+
const usageRows = await this.db.select().from(this.t.agentTokenUsage).where(eq2(this.t.agentTokenUsage.threadId, thread.id));
|
|
1944
2455
|
const usage = rollupThreadUsage(usageRows.map(toUsageInput), pricing);
|
|
1945
2456
|
const [messageCountRow] = await this.db.select({
|
|
1946
2457
|
value: count()
|
|
1947
|
-
}).from(agentMessage).where(eq2(agentMessage.threadId, thread.id));
|
|
1948
|
-
const messages = await this.db.select().from(agentMessage).where(eq2(agentMessage.threadId, thread.id)).orderBy(
|
|
2458
|
+
}).from(this.t.agentMessage).where(eq2(this.t.agentMessage.threadId, thread.id));
|
|
2459
|
+
const messages = await this.db.select().from(this.t.agentMessage).where(eq2(this.t.agentMessage.threadId, thread.id)).orderBy(
|
|
2460
|
+
// Append order (see DrizzleAgentStore's message order), newest first.
|
|
2461
|
+
desc2(sql3`coalesce(${this.t.agentMessage.seq}, 0)`),
|
|
2462
|
+
desc2(this.t.agentMessage.createdAt),
|
|
2463
|
+
desc2(this.t.agentMessage.id)
|
|
2464
|
+
).limit(query.messageLimit);
|
|
1949
2465
|
const toolCallCounts = await this.toolCallCountsByMessage(messages.map((message) => message.id));
|
|
1950
2466
|
const [runTotalRow] = await this.db.select({
|
|
1951
2467
|
value: count()
|
|
1952
|
-
}).from(agentRun).where(eq2(agentRun.threadId, thread.id));
|
|
1953
|
-
const runs = await this.db.select().from(agentRun).where(eq2(agentRun.threadId, thread.id)).orderBy(desc2(agentRun.startedAt), desc2(agentRun.id)).limit(query.runLimit);
|
|
2468
|
+
}).from(this.t.agentRun).where(eq2(this.t.agentRun.threadId, thread.id));
|
|
2469
|
+
const runs = await this.db.select().from(this.t.agentRun).where(eq2(this.t.agentRun.threadId, thread.id)).orderBy(desc2(this.t.agentRun.startedAt), desc2(this.t.agentRun.id)).limit(query.runLimit);
|
|
1954
2470
|
return {
|
|
1955
2471
|
thread: {
|
|
1956
2472
|
threadId: thread.id,
|
|
@@ -1985,9 +2501,9 @@ var DrizzleGovernanceQueries = class {
|
|
|
1985
2501
|
return counts;
|
|
1986
2502
|
}
|
|
1987
2503
|
const rows = await this.db.select({
|
|
1988
|
-
messageId: agentToolCall.messageId,
|
|
2504
|
+
messageId: this.t.agentToolCall.messageId,
|
|
1989
2505
|
value: count()
|
|
1990
|
-
}).from(agentToolCall).where(inArray2(agentToolCall.messageId, messageIds)).groupBy(agentToolCall.messageId);
|
|
2506
|
+
}).from(this.t.agentToolCall).where(inArray2(this.t.agentToolCall.messageId, messageIds)).groupBy(this.t.agentToolCall.messageId);
|
|
1991
2507
|
for (const row of rows) {
|
|
1992
2508
|
counts.set(row.messageId, row.value);
|
|
1993
2509
|
}
|
|
@@ -2026,8 +2542,12 @@ var DrizzleMemoryProvider = class {
|
|
|
2026
2542
|
__name(this, "DrizzleMemoryProvider");
|
|
2027
2543
|
}
|
|
2028
2544
|
db;
|
|
2545
|
+
dialect;
|
|
2546
|
+
t;
|
|
2029
2547
|
constructor(db) {
|
|
2030
|
-
this.
|
|
2548
|
+
this.dialect = agentDialectOf(db);
|
|
2549
|
+
this.t = agentTablesFor(this.dialect);
|
|
2550
|
+
this.db = asBuilder(db);
|
|
2031
2551
|
}
|
|
2032
2552
|
/**
|
|
2033
2553
|
* Every memory visible at `scopes` — asked on EVERY turn, so it is one indexed `scope in (…)`
|
|
@@ -2041,7 +2561,7 @@ var DrizzleMemoryProvider = class {
|
|
|
2041
2561
|
if (scopes.length === 0) {
|
|
2042
2562
|
return [];
|
|
2043
2563
|
}
|
|
2044
|
-
const rows = await this.db.select().from(agentMemory).where(inArray3(agentMemory.scope, [
|
|
2564
|
+
const rows = await this.db.select().from(this.t.agentMemory).where(inArray3(this.t.agentMemory.scope, [
|
|
2045
2565
|
...scopes
|
|
2046
2566
|
]));
|
|
2047
2567
|
return rows.map(toRecord);
|
|
@@ -2057,10 +2577,8 @@ var DrizzleMemoryProvider = class {
|
|
|
2057
2577
|
* answer cannot be used to find out which memories exist about other people.
|
|
2058
2578
|
*/
|
|
2059
2579
|
async forget({ id, ctx }) {
|
|
2060
|
-
const deleted = await this.db.delete(agentMemory).where(and3(eq3(agentMemory.id, id), eq3(agentMemory.scope, actorScope(ctx.actor)))).
|
|
2061
|
-
|
|
2062
|
-
});
|
|
2063
|
-
return deleted.length > 0;
|
|
2580
|
+
const deleted = await affectedRows(this.dialect, this.db.delete(this.t.agentMemory).where(and3(eq3(this.t.agentMemory.id, id), eq3(this.t.agentMemory.scope, actorScope(ctx.actor)))), this.t.agentMemory.id);
|
|
2581
|
+
return deleted > 0;
|
|
2064
2582
|
}
|
|
2065
2583
|
/**
|
|
2066
2584
|
* Upsert on (`scope`, `key`) — one statement, against the unique index, rather than a read
|
|
@@ -2073,7 +2591,7 @@ var DrizzleMemoryProvider = class {
|
|
|
2073
2591
|
* rewriting `createdAt` would lose when the belief was first formed; reassigning `id` would
|
|
2074
2592
|
* invalidate the delete handle a person was already shown.
|
|
2075
2593
|
*/
|
|
2076
|
-
async write({ key, text:
|
|
2594
|
+
async write({ key: key2, text: text3, scope, origin, ctx }) {
|
|
2077
2595
|
assertAuthorMayWriteScope({
|
|
2078
2596
|
scope,
|
|
2079
2597
|
origin,
|
|
@@ -2086,28 +2604,40 @@ var DrizzleMemoryProvider = class {
|
|
|
2086
2604
|
originRunId: origin.runId ?? null,
|
|
2087
2605
|
originActorRef: origin.actorRef ?? null
|
|
2088
2606
|
};
|
|
2089
|
-
const
|
|
2607
|
+
const memory = this.t.agentMemory;
|
|
2608
|
+
const set = {
|
|
2609
|
+
text: text3,
|
|
2610
|
+
...columns,
|
|
2611
|
+
updatedAt: now
|
|
2612
|
+
};
|
|
2613
|
+
const insert = this.db.insert(memory).values({
|
|
2090
2614
|
id: crypto.randomUUID(),
|
|
2091
2615
|
scope,
|
|
2092
|
-
key,
|
|
2093
|
-
text:
|
|
2616
|
+
key: key2,
|
|
2617
|
+
text: text3,
|
|
2094
2618
|
...columns,
|
|
2095
2619
|
pinned: false,
|
|
2096
2620
|
createdAt: now,
|
|
2097
2621
|
updatedAt: now
|
|
2098
|
-
})
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2622
|
+
});
|
|
2623
|
+
let row;
|
|
2624
|
+
if (this.dialect === "mysql") {
|
|
2625
|
+
await upsert(this.dialect, insert, [
|
|
2626
|
+
memory.scope,
|
|
2627
|
+
memory.key
|
|
2628
|
+
], set);
|
|
2629
|
+
[row] = await this.db.select().from(memory).where(and3(eq3(memory.scope, scope), eq3(memory.key, key2)));
|
|
2630
|
+
} else {
|
|
2631
|
+
[row] = await insert.onConflictDoUpdate({
|
|
2632
|
+
target: [
|
|
2633
|
+
memory.scope,
|
|
2634
|
+
memory.key
|
|
2635
|
+
],
|
|
2636
|
+
set
|
|
2637
|
+
}).returning();
|
|
2638
|
+
}
|
|
2109
2639
|
if (row === void 0) {
|
|
2110
|
-
throw new Error(`DrizzleMemoryProvider: the upsert of "${
|
|
2640
|
+
throw new Error(`DrizzleMemoryProvider: the upsert of "${key2}" at "${scope}" returned no row; the driver does not support RETURNING on conflict.`);
|
|
2111
2641
|
}
|
|
2112
2642
|
return toRecord(row);
|
|
2113
2643
|
}
|
|
@@ -2120,13 +2650,11 @@ var DrizzleMemoryProvider = class {
|
|
|
2120
2650
|
* `false` where there is no such id.
|
|
2121
2651
|
*/
|
|
2122
2652
|
async pin({ id, pinned }) {
|
|
2123
|
-
const updated = await this.db.update(agentMemory).set({
|
|
2653
|
+
const updated = await affectedRows(this.dialect, this.db.update(this.t.agentMemory).set({
|
|
2124
2654
|
pinned,
|
|
2125
2655
|
updatedAt: /* @__PURE__ */ new Date()
|
|
2126
|
-
}).where(eq3(agentMemory.id, id)).
|
|
2127
|
-
|
|
2128
|
-
});
|
|
2129
|
-
return updated.length > 0;
|
|
2656
|
+
}).where(eq3(this.t.agentMemory.id, id)), this.t.agentMemory.id);
|
|
2657
|
+
return updated > 0;
|
|
2130
2658
|
}
|
|
2131
2659
|
};
|
|
2132
2660
|
function assertAuthorMayWriteScope({ scope, origin, ctx }) {
|
|
@@ -2144,14 +2672,18 @@ var DrizzlePricingStore = class {
|
|
|
2144
2672
|
__name(this, "DrizzlePricingStore");
|
|
2145
2673
|
}
|
|
2146
2674
|
db;
|
|
2675
|
+
dialect;
|
|
2676
|
+
t;
|
|
2147
2677
|
constructor(db) {
|
|
2148
|
-
this.
|
|
2678
|
+
this.dialect = agentDialectOf(db);
|
|
2679
|
+
this.t = agentTablesFor(this.dialect);
|
|
2680
|
+
this.db = asBuilder(db);
|
|
2149
2681
|
}
|
|
2150
2682
|
async upsertModelPrice(input) {
|
|
2151
|
-
await this.db.update(agentModelPricing).set({
|
|
2683
|
+
await this.db.update(this.t.agentModelPricing).set({
|
|
2152
2684
|
isCurrent: false
|
|
2153
|
-
}).where(and4(eq4(agentModelPricing.modelId, input.modelId), eq4(agentModelPricing.isCurrent, true)));
|
|
2154
|
-
await this.db.insert(agentModelPricing).values({
|
|
2685
|
+
}).where(and4(eq4(this.t.agentModelPricing.modelId, input.modelId), eq4(this.t.agentModelPricing.isCurrent, true)));
|
|
2686
|
+
await this.db.insert(this.t.agentModelPricing).values({
|
|
2155
2687
|
id: crypto.randomUUID(),
|
|
2156
2688
|
modelId: input.modelId,
|
|
2157
2689
|
inputPricePer1m: input.inputPricePer1m,
|
|
@@ -2163,7 +2695,7 @@ var DrizzlePricingStore = class {
|
|
|
2163
2695
|
});
|
|
2164
2696
|
}
|
|
2165
2697
|
async listCurrentPrices() {
|
|
2166
|
-
const rows = await this.db.select().from(agentModelPricing).where(eq4(agentModelPricing.isCurrent, true));
|
|
2698
|
+
const rows = await this.db.select().from(this.t.agentModelPricing).where(eq4(this.t.agentModelPricing.isCurrent, true));
|
|
2167
2699
|
return rows.map((row) => ({
|
|
2168
2700
|
modelId: row.modelId,
|
|
2169
2701
|
inputPricePer1m: row.inputPricePer1m,
|
|
@@ -2182,51 +2714,46 @@ var DrizzlePricingStore = class {
|
|
|
2182
2714
|
// src/drizzle-token-stream-sink.ts
|
|
2183
2715
|
import { SqlTokenStreamSink } from "@dudousxd/nestjs-agent-core";
|
|
2184
2716
|
import { and as and5, asc as asc3, eq as eq5, gt, inArray as inArray4, lt, max as max2, sql as sql4 } from "drizzle-orm";
|
|
2185
|
-
function isUniqueViolation(error) {
|
|
2186
|
-
for (let current = error; current !== null && typeof current === "object"; ) {
|
|
2187
|
-
const code = current.code;
|
|
2188
|
-
if (typeof code === "string" && code.startsWith("SQLITE_CONSTRAINT")) return true;
|
|
2189
|
-
current = current.cause;
|
|
2190
|
-
}
|
|
2191
|
-
return false;
|
|
2192
|
-
}
|
|
2193
|
-
__name(isUniqueViolation, "isUniqueViolation");
|
|
2194
2717
|
var DrizzleStreamFrameTable = class {
|
|
2195
2718
|
static {
|
|
2196
2719
|
__name(this, "DrizzleStreamFrameTable");
|
|
2197
2720
|
}
|
|
2198
2721
|
db;
|
|
2722
|
+
dialect;
|
|
2723
|
+
t;
|
|
2199
2724
|
constructor(db) {
|
|
2200
|
-
this.
|
|
2725
|
+
this.dialect = agentDialectOf(db);
|
|
2726
|
+
this.t = agentTablesFor(this.dialect);
|
|
2727
|
+
this.db = asBuilder(db);
|
|
2201
2728
|
}
|
|
2202
2729
|
async append(runId, row) {
|
|
2203
|
-
await this.db.
|
|
2730
|
+
await runSql(this.db, this.dialect, sql4`INSERT INTO agent_stream_frame (run_id, seq, frame, error, created_at)
|
|
2204
2731
|
SELECT ${runId}, COALESCE(MAX(seq), 0) + 1, ${row.frame}, ${row.error}, ${row.createdAt}
|
|
2205
2732
|
FROM agent_stream_frame WHERE run_id = ${runId}`);
|
|
2206
2733
|
}
|
|
2207
2734
|
async read(runId, after, limit) {
|
|
2208
2735
|
return this.db.select({
|
|
2209
|
-
seq: agentStreamFrame.seq,
|
|
2210
|
-
frame: agentStreamFrame.frame,
|
|
2211
|
-
error: agentStreamFrame.error
|
|
2212
|
-
}).from(agentStreamFrame).where(and5(eq5(agentStreamFrame.runId, runId), gt(agentStreamFrame.seq, after))).orderBy(asc3(agentStreamFrame.seq)).limit(limit);
|
|
2736
|
+
seq: this.t.agentStreamFrame.seq,
|
|
2737
|
+
frame: this.t.agentStreamFrame.frame,
|
|
2738
|
+
error: this.t.agentStreamFrame.error
|
|
2739
|
+
}).from(this.t.agentStreamFrame).where(and5(eq5(this.t.agentStreamFrame.runId, runId), gt(this.t.agentStreamFrame.seq, after))).orderBy(asc3(this.t.agentStreamFrame.seq)).limit(limit);
|
|
2213
2740
|
}
|
|
2214
2741
|
async has(runId) {
|
|
2215
2742
|
const rows = await this.db.select({
|
|
2216
|
-
seq: agentStreamFrame.seq
|
|
2217
|
-
}).from(agentStreamFrame).where(eq5(agentStreamFrame.runId, runId)).limit(1);
|
|
2743
|
+
seq: this.t.agentStreamFrame.seq
|
|
2744
|
+
}).from(this.t.agentStreamFrame).where(eq5(this.t.agentStreamFrame.runId, runId)).limit(1);
|
|
2218
2745
|
return rows.length > 0;
|
|
2219
2746
|
}
|
|
2220
2747
|
async remove(runIds) {
|
|
2221
2748
|
if (runIds.length === 0) return;
|
|
2222
|
-
await this.db.delete(agentStreamFrame).where(inArray4(agentStreamFrame.runId, [
|
|
2749
|
+
await this.db.delete(this.t.agentStreamFrame).where(inArray4(this.t.agentStreamFrame.runId, [
|
|
2223
2750
|
...runIds
|
|
2224
2751
|
]));
|
|
2225
2752
|
}
|
|
2226
2753
|
async lapsedRuns(cutoff) {
|
|
2227
2754
|
const rows = await this.db.select({
|
|
2228
|
-
runId: agentStreamFrame.runId
|
|
2229
|
-
}).from(agentStreamFrame).groupBy(agentStreamFrame.runId).having(lt(max2(agentStreamFrame.createdAt), cutoff));
|
|
2755
|
+
runId: this.t.agentStreamFrame.runId
|
|
2756
|
+
}).from(this.t.agentStreamFrame).groupBy(this.t.agentStreamFrame.runId).having(lt(max2(this.t.agentStreamFrame.createdAt), cutoff));
|
|
2230
2757
|
return rows.map((row) => row.runId);
|
|
2231
2758
|
}
|
|
2232
2759
|
isUniqueViolation(error) {
|
|
@@ -2249,29 +2776,35 @@ var DrizzleConfirmTokenStore = class {
|
|
|
2249
2776
|
__name(this, "DrizzleConfirmTokenStore");
|
|
2250
2777
|
}
|
|
2251
2778
|
db;
|
|
2779
|
+
dialect;
|
|
2780
|
+
t;
|
|
2252
2781
|
constructor(db) {
|
|
2253
|
-
this.
|
|
2782
|
+
this.dialect = agentDialectOf(db);
|
|
2783
|
+
this.t = agentTablesFor(this.dialect);
|
|
2784
|
+
this.db = asBuilder(db);
|
|
2254
2785
|
}
|
|
2255
2786
|
async claim(input) {
|
|
2256
|
-
const
|
|
2787
|
+
const row = {
|
|
2257
2788
|
hash: input.hash,
|
|
2258
2789
|
actorRef: input.actorRef,
|
|
2259
2790
|
tool: input.tool,
|
|
2260
2791
|
expiresAt: input.expiresAt,
|
|
2261
2792
|
createdAt: Date.now()
|
|
2262
|
-
}
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2793
|
+
};
|
|
2794
|
+
const table = this.t.agentConfirmToken;
|
|
2795
|
+
if (this.dialect === "mysql") {
|
|
2796
|
+
const insert = this.db.insert(table);
|
|
2797
|
+
return mysqlAffectedRows(await insert.ignore().values(row)) === 1;
|
|
2798
|
+
}
|
|
2799
|
+
const inserted = await affectedRows(this.dialect, this.db.insert(table).values(row).onConflictDoNothing(), table.hash);
|
|
2800
|
+
return inserted === 1;
|
|
2266
2801
|
}
|
|
2267
2802
|
async release(hash) {
|
|
2268
|
-
await this.db.delete(agentConfirmToken).where(eq6(agentConfirmToken.hash, hash));
|
|
2803
|
+
await this.db.delete(this.t.agentConfirmToken).where(eq6(this.t.agentConfirmToken.hash, hash));
|
|
2269
2804
|
}
|
|
2270
2805
|
async purgeExpired(now = Date.now()) {
|
|
2271
|
-
const
|
|
2272
|
-
|
|
2273
|
-
});
|
|
2274
|
-
return purged.length;
|
|
2806
|
+
const table = this.t.agentConfirmToken;
|
|
2807
|
+
return affectedRows(this.dialect, this.db.delete(table).where(lt2(table.expiresAt, now)), table.hash);
|
|
2275
2808
|
}
|
|
2276
2809
|
};
|
|
2277
2810
|
|
|
@@ -2279,18 +2812,18 @@ var DrizzleConfirmTokenStore = class {
|
|
|
2279
2812
|
import { subscribe, unsubscribe } from "diagnostics_channel";
|
|
2280
2813
|
import { Injectable, Logger } from "@nestjs/common";
|
|
2281
2814
|
import { and as and6, asc as asc4, count as count2, desc as desc3, eq as eq7, gt as gt2, lt as lt3, or as or2 } from "drizzle-orm";
|
|
2282
|
-
function _ts_decorate(decorators, target,
|
|
2283
|
-
var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target,
|
|
2815
|
+
function _ts_decorate(decorators, target, key2, desc4) {
|
|
2816
|
+
var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key2) : desc4, d;
|
|
2284
2817
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
|
|
2285
|
-
r = Reflect.decorate(decorators, target,
|
|
2818
|
+
r = Reflect.decorate(decorators, target, key2, desc4);
|
|
2286
2819
|
} else {
|
|
2287
2820
|
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
2288
2821
|
if (d = decorators[i]) {
|
|
2289
|
-
r = (c < 3 ? d(r) : c > 3 ? d(target,
|
|
2822
|
+
r = (c < 3 ? d(r) : c > 3 ? d(target, key2, r) : d(target, key2)) || r;
|
|
2290
2823
|
}
|
|
2291
2824
|
}
|
|
2292
2825
|
}
|
|
2293
|
-
return c > 3 && r && Object.defineProperty(target,
|
|
2826
|
+
return c > 3 && r && Object.defineProperty(target, key2, r), r;
|
|
2294
2827
|
}
|
|
2295
2828
|
__name(_ts_decorate, "_ts_decorate");
|
|
2296
2829
|
function _ts_metadata(metadataKey, metadataValue) {
|
|
@@ -2336,20 +2869,27 @@ function batches(batchSize) {
|
|
|
2336
2869
|
return Number.isFinite(requested) && requested >= 1 ? requested : DEFAULT_BATCH_SIZE;
|
|
2337
2870
|
}
|
|
2338
2871
|
__name(batches, "batches");
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2872
|
+
function cursorColumns(log) {
|
|
2873
|
+
return {
|
|
2874
|
+
documentId: log.documentId,
|
|
2875
|
+
updatedAt: log.updatedAt
|
|
2876
|
+
};
|
|
2877
|
+
}
|
|
2878
|
+
__name(cursorColumns, "cursorColumns");
|
|
2343
2879
|
var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
2344
2880
|
static {
|
|
2345
2881
|
__name(this, "DrizzleRagIngestionLog");
|
|
2346
2882
|
}
|
|
2347
|
-
db;
|
|
2348
2883
|
logger = new Logger(_DrizzleRagIngestionLog.name);
|
|
2349
2884
|
teardowns = [];
|
|
2350
2885
|
inFlight = /* @__PURE__ */ new Set();
|
|
2886
|
+
db;
|
|
2887
|
+
dialect;
|
|
2888
|
+
t;
|
|
2351
2889
|
constructor(db) {
|
|
2352
|
-
this.
|
|
2890
|
+
this.dialect = agentDialectOf(db);
|
|
2891
|
+
this.t = agentTablesFor(this.dialect);
|
|
2892
|
+
this.db = asBuilder(db);
|
|
2353
2893
|
}
|
|
2354
2894
|
onModuleInit() {
|
|
2355
2895
|
for (const channel of CHANNELS) {
|
|
@@ -2378,7 +2918,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2378
2918
|
}
|
|
2379
2919
|
/** The latest recorded outcome per document, newest first. */
|
|
2380
2920
|
async list(query = {}) {
|
|
2381
|
-
const rows = this.db.select().from(ragIngestionLog).where(this.where(query)).orderBy(...RAG_INGESTION_LOG_PAGE_ORDER).limit(query.limit ?? DEFAULT_PAGE_SIZE);
|
|
2921
|
+
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);
|
|
2382
2922
|
return query.offset === void 0 ? rows : rows.offset(query.offset);
|
|
2383
2923
|
}
|
|
2384
2924
|
/**
|
|
@@ -2392,7 +2932,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2392
2932
|
async listPage(query = {}) {
|
|
2393
2933
|
const [totalRow] = await this.db.select({
|
|
2394
2934
|
value: count2()
|
|
2395
|
-
}).from(ragIngestionLog).where(this.where(query));
|
|
2935
|
+
}).from(this.t.ragIngestionLog).where(this.where(query));
|
|
2396
2936
|
return {
|
|
2397
2937
|
rows: await this.list(query),
|
|
2398
2938
|
total: totalRow?.value ?? 0
|
|
@@ -2445,7 +2985,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2445
2985
|
* sweep is run. A sweep that stops early stops by `break`ing out of the `for await`.
|
|
2446
2986
|
*/
|
|
2447
2987
|
iterate(where = {}, options = {}) {
|
|
2448
|
-
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));
|
|
2988
|
+
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));
|
|
2449
2989
|
}
|
|
2450
2990
|
/**
|
|
2451
2991
|
* Just the document ids of the matching rows, in {@link RAG_INGESTION_LOG_PAGE_ORDER}.
|
|
@@ -2462,7 +3002,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2462
3002
|
*/
|
|
2463
3003
|
async listDocumentIds(where = {}, options = {}) {
|
|
2464
3004
|
const ids = [];
|
|
2465
|
-
const rows = this.sweep(where, batches(options.batchSize), void 0, (filter, limit) => this.db.select(
|
|
3005
|
+
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));
|
|
2466
3006
|
for await (const row of rows) {
|
|
2467
3007
|
ids.push(row.documentId);
|
|
2468
3008
|
}
|
|
@@ -2470,22 +3010,18 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2470
3010
|
}
|
|
2471
3011
|
/** The latest recorded outcome for one document, or null if it was never attempted. */
|
|
2472
3012
|
async get(documentId) {
|
|
2473
|
-
const [row] = await this.db.select().from(ragIngestionLog).where(eq7(ragIngestionLog.documentId, documentId));
|
|
3013
|
+
const [row] = await this.db.select().from(this.t.ragIngestionLog).where(eq7(this.t.ragIngestionLog.documentId, documentId));
|
|
2474
3014
|
return row ?? null;
|
|
2475
3015
|
}
|
|
2476
3016
|
/** Forget one document's record. Returns whether a row was actually removed. */
|
|
2477
3017
|
async remove(documentId) {
|
|
2478
|
-
const removed = await this.db.delete(ragIngestionLog).where(eq7(ragIngestionLog.documentId, documentId)).
|
|
2479
|
-
|
|
2480
|
-
});
|
|
2481
|
-
return removed.length > 0;
|
|
3018
|
+
const removed = await affectedRows(this.dialect, this.db.delete(this.t.ragIngestionLog).where(eq7(this.t.ragIngestionLog.documentId, documentId)), this.t.ragIngestionLog.documentId);
|
|
3019
|
+
return removed > 0;
|
|
2482
3020
|
}
|
|
2483
3021
|
/** Forget every record for a collection — for when the collection itself is deleted. */
|
|
2484
3022
|
async removeByCollection(collection) {
|
|
2485
|
-
const removed = await this.db.delete(ragIngestionLog).where(eq7(ragIngestionLog.collection, collection)).
|
|
2486
|
-
|
|
2487
|
-
});
|
|
2488
|
-
return removed.length;
|
|
3023
|
+
const removed = await affectedRows(this.dialect, this.db.delete(this.t.ragIngestionLog).where(eq7(this.t.ragIngestionLog.collection, collection)), this.t.ragIngestionLog.documentId);
|
|
3024
|
+
return removed;
|
|
2489
3025
|
}
|
|
2490
3026
|
/**
|
|
2491
3027
|
* The keyset sweep both {@link iterate} and {@link listDocumentIds} are made of. `page` decides
|
|
@@ -2514,7 +3050,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2514
3050
|
}
|
|
2515
3051
|
}
|
|
2516
3052
|
where(query) {
|
|
2517
|
-
return and6(query.collection !== void 0 ? eq7(ragIngestionLog.collection, query.collection) : void 0, query.status !== void 0 ? eq7(ragIngestionLog.status, query.status) : void 0);
|
|
3053
|
+
return and6(query.collection !== void 0 ? eq7(this.t.ragIngestionLog.collection, query.collection) : void 0, query.status !== void 0 ? eq7(this.t.ragIngestionLog.status, query.status) : void 0);
|
|
2518
3054
|
}
|
|
2519
3055
|
/**
|
|
2520
3056
|
* The coordinates filter AND'd with "strictly after `cursor` in
|
|
@@ -2529,7 +3065,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2529
3065
|
if (cursor === void 0) {
|
|
2530
3066
|
return base;
|
|
2531
3067
|
}
|
|
2532
|
-
return and6(base, or2(lt3(ragIngestionLog.updatedAt, cursor.updatedAt), and6(eq7(ragIngestionLog.updatedAt, cursor.updatedAt), gt2(ragIngestionLog.documentId, cursor.documentId))));
|
|
3068
|
+
return and6(base, or2(lt3(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), and6(eq7(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), gt2(this.t.ragIngestionLog.documentId, cursor.documentId))));
|
|
2533
3069
|
}
|
|
2534
3070
|
/**
|
|
2535
3071
|
* Upsert one outcome. Keyed by document id so the row always reflects the *current* state — a
|
|
@@ -2577,14 +3113,11 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2577
3113
|
size
|
|
2578
3114
|
} : {}
|
|
2579
3115
|
};
|
|
2580
|
-
await this.db.insert(ragIngestionLog).values({
|
|
3116
|
+
await upsert(this.dialect, this.db.insert(this.t.ragIngestionLog).values({
|
|
2581
3117
|
documentId,
|
|
2582
3118
|
createdAt: now,
|
|
2583
3119
|
...outcome
|
|
2584
|
-
}).
|
|
2585
|
-
target: ragIngestionLog.documentId,
|
|
2586
|
-
set: outcome
|
|
2587
|
-
});
|
|
3120
|
+
}), this.t.ragIngestionLog.documentId, outcome);
|
|
2588
3121
|
} catch (error) {
|
|
2589
3122
|
this.logger.warn(`Could not record RAG ingestion outcome for ${documentId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2590
3123
|
}
|
|
@@ -2607,18 +3140,18 @@ DrizzleRagIngestionLog = _ts_decorate([
|
|
|
2607
3140
|
// src/drizzle-agent-store.module.ts
|
|
2608
3141
|
import { AGENT_CONFIRM_TOKEN_STORE, AGENT_GOVERNANCE_QUERIES, AGENT_PRICING_STORE, AGENT_STORE } from "@dudousxd/nestjs-agent-core";
|
|
2609
3142
|
import { Module } from "@nestjs/common";
|
|
2610
|
-
function _ts_decorate2(decorators, target,
|
|
2611
|
-
var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target,
|
|
3143
|
+
function _ts_decorate2(decorators, target, key2, desc4) {
|
|
3144
|
+
var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key2) : desc4, d;
|
|
2612
3145
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
|
|
2613
|
-
r = Reflect.decorate(decorators, target,
|
|
3146
|
+
r = Reflect.decorate(decorators, target, key2, desc4);
|
|
2614
3147
|
} else {
|
|
2615
3148
|
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
2616
3149
|
if (d = decorators[i]) {
|
|
2617
|
-
r = (c < 3 ? d(r) : c > 3 ? d(target,
|
|
3150
|
+
r = (c < 3 ? d(r) : c > 3 ? d(target, key2, r) : d(target, key2)) || r;
|
|
2618
3151
|
}
|
|
2619
3152
|
}
|
|
2620
3153
|
}
|
|
2621
|
-
return c > 3 && r && Object.defineProperty(target,
|
|
3154
|
+
return c > 3 && r && Object.defineProperty(target, key2, r), r;
|
|
2622
3155
|
}
|
|
2623
3156
|
__name(_ts_decorate2, "_ts_decorate");
|
|
2624
3157
|
var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
|
|
@@ -2718,17 +3251,21 @@ export {
|
|
|
2718
3251
|
DrizzleTokenStreamSink,
|
|
2719
3252
|
RAG_INGESTION_LOG_PAGE_ORDER,
|
|
2720
3253
|
agentConfirmToken,
|
|
3254
|
+
agentDialectOf,
|
|
2721
3255
|
agentMemory,
|
|
2722
3256
|
agentMessage,
|
|
2723
3257
|
agentModelPricing,
|
|
2724
3258
|
agentQueuedMessage,
|
|
2725
3259
|
agentRun,
|
|
2726
3260
|
agentSchema,
|
|
3261
|
+
agentSchemaDdl,
|
|
2727
3262
|
agentStreamFrame,
|
|
2728
3263
|
agentThread,
|
|
2729
3264
|
agentTokenUsage,
|
|
2730
3265
|
agentToolCall,
|
|
2731
3266
|
ensureAgentSchema,
|
|
3267
|
+
mysqlAgentSchema,
|
|
3268
|
+
pgAgentSchema,
|
|
2732
3269
|
ragIngestionLog
|
|
2733
3270
|
};
|
|
2734
3271
|
//# sourceMappingURL=index.js.map
|