@dudousxd/nestjs-agent-store-drizzle 0.23.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -9
- package/dist/index.cjs +1100 -605
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4802 -17
- package/dist/index.d.ts +4802 -17
- package/dist/index.js +1076 -585
- package/dist/index.js.map +1 -1
- package/package.json +5 -2
package/dist/index.js
CHANGED
|
@@ -71,6 +71,12 @@ var agentMessage = sqliteTable("agent_message", {
|
|
|
71
71
|
feedback: text("feedback", {
|
|
72
72
|
mode: "json"
|
|
73
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"),
|
|
74
80
|
createdAt: integer("created_at", {
|
|
75
81
|
mode: "timestamp_ms"
|
|
76
82
|
}).notNull()
|
|
@@ -305,303 +311,721 @@ var agentSchema = {
|
|
|
305
311
|
agentRun,
|
|
306
312
|
agentMemory,
|
|
307
313
|
ragIngestionLog,
|
|
308
|
-
agentConfirmToken
|
|
314
|
+
agentConfirmToken,
|
|
315
|
+
agentStreamFrame
|
|
309
316
|
};
|
|
310
317
|
|
|
311
318
|
// src/ensure-schema.ts
|
|
312
|
-
import { sql } from "drizzle-orm";
|
|
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
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
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;
|
|
570
802
|
}
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
803
|
+
if (dialect === "postgres") {
|
|
804
|
+
await db.execute(statement);
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
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] : [];
|
|
575
817
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
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;
|
|
580
826
|
}
|
|
827
|
+
current = current.cause;
|
|
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;
|
|
581
865
|
}
|
|
866
|
+
await heal(db, dialect);
|
|
582
867
|
}
|
|
583
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");
|
|
584
1001
|
|
|
585
1002
|
// src/drizzle-agent-store.ts
|
|
586
1003
|
import { toolCallApprovalFromRow } from "@dudousxd/nestjs-agent-core";
|
|
587
1004
|
import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, max, min, or, sql as sql2 } from "drizzle-orm";
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
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");
|
|
598
1018
|
var DrizzleAgentStore = class {
|
|
599
1019
|
static {
|
|
600
1020
|
__name(this, "DrizzleAgentStore");
|
|
601
1021
|
}
|
|
602
1022
|
db;
|
|
1023
|
+
dialect;
|
|
1024
|
+
t;
|
|
603
1025
|
constructor(db) {
|
|
604
|
-
this.
|
|
1026
|
+
this.dialect = agentDialectOf(db);
|
|
1027
|
+
this.t = agentTablesFor(this.dialect);
|
|
1028
|
+
this.db = asBuilder(db);
|
|
605
1029
|
}
|
|
606
1030
|
async createThread(input) {
|
|
607
1031
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -620,15 +1044,15 @@ var DrizzleAgentStore = class {
|
|
|
620
1044
|
updatedAt: now,
|
|
621
1045
|
deletedAt: null
|
|
622
1046
|
};
|
|
623
|
-
await this.db.insert(agentThread).values(thread);
|
|
1047
|
+
await this.db.insert(this.t.agentThread).values(thread);
|
|
624
1048
|
return this.toSummary(thread);
|
|
625
1049
|
}
|
|
626
1050
|
async getThread(threadId) {
|
|
627
|
-
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)));
|
|
628
1052
|
if (thread === void 0) {
|
|
629
1053
|
return null;
|
|
630
1054
|
}
|
|
631
|
-
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());
|
|
632
1056
|
const last = messages[messages.length - 1];
|
|
633
1057
|
const approvals = await this.approvalsFor(messages.map((message) => message.id));
|
|
634
1058
|
return {
|
|
@@ -661,16 +1085,16 @@ var DrizzleAgentStore = class {
|
|
|
661
1085
|
*/
|
|
662
1086
|
async loadThreadForTurn(query) {
|
|
663
1087
|
const [thread] = await this.db.select({
|
|
664
|
-
title: agentThread.title,
|
|
665
|
-
defaultAgent: agentThread.defaultAgent
|
|
666
|
-
}).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)));
|
|
667
1091
|
if (thread === void 0) {
|
|
668
1092
|
return null;
|
|
669
1093
|
}
|
|
670
1094
|
const messages = await this.loadTurnWindow(query.threadId, query.messageLimit);
|
|
671
1095
|
const [answered] = await this.db.select({
|
|
672
|
-
id: agentMessage.id
|
|
673
|
-
}).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);
|
|
674
1098
|
return {
|
|
675
1099
|
title: thread.title,
|
|
676
1100
|
defaultAgent: thread.defaultAgent,
|
|
@@ -686,30 +1110,30 @@ var DrizzleAgentStore = class {
|
|
|
686
1110
|
if (limit !== void 0 && limit <= 0) {
|
|
687
1111
|
return [];
|
|
688
1112
|
}
|
|
689
|
-
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());
|
|
690
1114
|
const rows = limit === void 0 ? await window : await window.limit(limit);
|
|
691
1115
|
return rows.reverse().map((row) => this.toStoredMessage(row));
|
|
692
1116
|
}
|
|
693
1117
|
async listThreads(actorRef, limit = 50) {
|
|
694
|
-
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);
|
|
695
1119
|
const summaries = [];
|
|
696
1120
|
for (const thread of threads) {
|
|
697
|
-
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);
|
|
698
1122
|
summaries.push(this.toSummary(thread, last?.content));
|
|
699
1123
|
}
|
|
700
1124
|
return summaries;
|
|
701
1125
|
}
|
|
702
1126
|
async softDeleteThread(threadId) {
|
|
703
|
-
await this.db.update(agentThread).set({
|
|
1127
|
+
await this.db.update(this.t.agentThread).set({
|
|
704
1128
|
deletedAt: /* @__PURE__ */ new Date()
|
|
705
|
-
}).where(eq(agentThread.id, threadId));
|
|
1129
|
+
}).where(eq(this.t.agentThread.id, threadId));
|
|
706
1130
|
}
|
|
707
1131
|
async forkThread(threadId, fromMessageId) {
|
|
708
|
-
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));
|
|
709
1133
|
if (source === void 0) {
|
|
710
1134
|
throw new Error(`thread ${threadId} not found`);
|
|
711
1135
|
}
|
|
712
|
-
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());
|
|
713
1137
|
const cutoff = messages.findIndex((message) => message.id === fromMessageId);
|
|
714
1138
|
const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;
|
|
715
1139
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -729,10 +1153,12 @@ var DrizzleAgentStore = class {
|
|
|
729
1153
|
updatedAt: now,
|
|
730
1154
|
deletedAt: null
|
|
731
1155
|
};
|
|
732
|
-
await this.db.insert(agentThread).values(fork);
|
|
1156
|
+
await this.db.insert(this.t.agentThread).values(fork);
|
|
733
1157
|
if (kept.length > 0) {
|
|
734
|
-
await this.db.insert(agentMessage).values(kept.map((message) => ({
|
|
1158
|
+
await this.db.insert(this.t.agentMessage).values(kept.map((message, index4) => ({
|
|
735
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,
|
|
736
1162
|
threadId: fork.id,
|
|
737
1163
|
role: message.role,
|
|
738
1164
|
content: message.content,
|
|
@@ -757,21 +1183,21 @@ var DrizzleAgentStore = class {
|
|
|
757
1183
|
}
|
|
758
1184
|
async ownerOfThread(threadId) {
|
|
759
1185
|
const [thread] = await this.db.select({
|
|
760
|
-
actorRef: agentThread.actorRef
|
|
761
|
-
}).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)));
|
|
762
1188
|
return thread?.actorRef ?? null;
|
|
763
1189
|
}
|
|
764
1190
|
async ownerOfToolCall(toolCallId) {
|
|
765
1191
|
const [row] = await this.db.select({
|
|
766
|
-
actorRef: agentThread.actorRef
|
|
767
|
-
}).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));
|
|
768
1194
|
return row?.actorRef ?? null;
|
|
769
1195
|
}
|
|
770
1196
|
async runForToolCall(toolCallId) {
|
|
771
1197
|
const [row] = await this.db.select({
|
|
772
|
-
runId: agentToolCall.runId,
|
|
773
|
-
activeStreamId: agentThread.activeStreamId
|
|
774
|
-
}).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));
|
|
775
1201
|
return row?.runId ?? row?.activeStreamId ?? null;
|
|
776
1202
|
}
|
|
777
1203
|
/**
|
|
@@ -785,16 +1211,16 @@ var DrizzleAgentStore = class {
|
|
|
785
1211
|
return byMessage;
|
|
786
1212
|
}
|
|
787
1213
|
const rows = await this.db.select({
|
|
788
|
-
id: agentToolCall.id,
|
|
789
|
-
messageId: agentToolCall.messageId,
|
|
790
|
-
status: agentToolCall.status,
|
|
791
|
-
approver: agentToolCall.approver,
|
|
792
|
-
expiresAt: agentToolCall.expiresAt,
|
|
793
|
-
remember: agentToolCall.remember,
|
|
794
|
-
executedByRef: agentToolCall.executedByRef,
|
|
795
|
-
decidedVia: agentToolCall.decidedVia,
|
|
796
|
-
error: agentToolCall.error
|
|
797
|
-
}).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));
|
|
798
1224
|
for (const row of rows) {
|
|
799
1225
|
const approval = toolCallApprovalFromRow({
|
|
800
1226
|
...row,
|
|
@@ -812,22 +1238,22 @@ var DrizzleAgentStore = class {
|
|
|
812
1238
|
/** Tools whose approval someone asked to remember in this thread. */
|
|
813
1239
|
async rememberedApprovals(threadId) {
|
|
814
1240
|
const rows = await this.db.selectDistinct({
|
|
815
|
-
toolName: agentToolCall.toolName
|
|
816
|
-
}).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)));
|
|
817
1243
|
return rows.map((row) => row.toolName);
|
|
818
1244
|
}
|
|
819
1245
|
async toolCallInput(toolCallId) {
|
|
820
1246
|
const [row] = await this.db.select({
|
|
821
|
-
input: agentToolCall.input
|
|
822
|
-
}).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));
|
|
823
1249
|
return row?.input ?? null;
|
|
824
1250
|
}
|
|
825
1251
|
async toolCallApproval(toolCallId) {
|
|
826
1252
|
const [row] = await this.db.select({
|
|
827
|
-
status: agentToolCall.status,
|
|
828
|
-
approver: agentToolCall.approver,
|
|
829
|
-
expiresAt: agentToolCall.expiresAt
|
|
830
|
-
}).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));
|
|
831
1257
|
if (row === void 0) {
|
|
832
1258
|
return null;
|
|
833
1259
|
}
|
|
@@ -839,27 +1265,67 @@ var DrizzleAgentStore = class {
|
|
|
839
1265
|
}
|
|
840
1266
|
async ownerOfActiveStream(runId) {
|
|
841
1267
|
const [thread] = await this.db.select({
|
|
842
|
-
actorRef: agentThread.actorRef
|
|
843
|
-
}).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)));
|
|
844
1270
|
return thread?.actorRef ?? null;
|
|
845
1271
|
}
|
|
846
1272
|
async setTitle(threadId, title) {
|
|
847
|
-
await this.db.update(agentThread).set({
|
|
1273
|
+
await this.db.update(this.t.agentThread).set({
|
|
848
1274
|
title,
|
|
849
1275
|
updatedAt: /* @__PURE__ */ new Date()
|
|
850
|
-
}).where(eq(agentThread.id, threadId));
|
|
1276
|
+
}).where(eq(this.t.agentThread.id, threadId));
|
|
851
1277
|
}
|
|
852
1278
|
async promoteThread(threadId) {
|
|
853
|
-
await this.db.update(agentThread).set({
|
|
1279
|
+
await this.db.update(this.t.agentThread).set({
|
|
854
1280
|
transient: false,
|
|
855
1281
|
updatedAt: /* @__PURE__ */ new Date()
|
|
856
|
-
}).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;
|
|
857
1323
|
}
|
|
858
1324
|
/** The run streaming the thread, or `null` — a projection of the one column. */
|
|
859
1325
|
async activeRunForThread(threadId) {
|
|
860
1326
|
const [thread] = await this.db.select({
|
|
861
|
-
activeStreamId: agentThread.activeStreamId
|
|
862
|
-
}).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)));
|
|
863
1329
|
return thread?.activeStreamId ?? null;
|
|
864
1330
|
}
|
|
865
1331
|
/**
|
|
@@ -868,33 +1334,32 @@ var DrizzleAgentStore = class {
|
|
|
868
1334
|
*/
|
|
869
1335
|
async claimActiveStream(threadId, runId, options = {}) {
|
|
870
1336
|
const holders = [
|
|
871
|
-
isNull(agentThread.activeStreamId),
|
|
872
|
-
eq(agentThread.activeStreamId, runId),
|
|
1337
|
+
isNull(this.t.agentThread.activeStreamId),
|
|
1338
|
+
eq(this.t.agentThread.activeStreamId, runId),
|
|
873
1339
|
...options.replacing !== void 0 ? [
|
|
874
|
-
eq(agentThread.activeStreamId, options.replacing)
|
|
1340
|
+
eq(this.t.agentThread.activeStreamId, options.replacing)
|
|
875
1341
|
] : []
|
|
876
1342
|
];
|
|
877
|
-
const claimed = await this.db.update(agentThread).set({
|
|
1343
|
+
const claimed = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
|
|
878
1344
|
activeStreamId: runId
|
|
879
|
-
}).where(and(eq(agentThread.id, threadId), or(...holders))).
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
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;
|
|
883
1350
|
}
|
|
884
1351
|
async releaseActiveStream(threadId, runId) {
|
|
885
|
-
const released = await this.db.update(agentThread).set({
|
|
1352
|
+
const released = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
|
|
886
1353
|
activeStreamId: null
|
|
887
|
-
}).where(and(eq(agentThread.id, threadId), eq(agentThread.activeStreamId, runId))).
|
|
888
|
-
|
|
889
|
-
});
|
|
890
|
-
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;
|
|
891
1356
|
}
|
|
892
1357
|
async enqueueMessage(input) {
|
|
893
1358
|
const now = /* @__PURE__ */ new Date();
|
|
894
1359
|
const [edge] = await this.db.select({
|
|
895
|
-
first: min(agentQueuedMessage.position),
|
|
896
|
-
last: max(agentQueuedMessage.position)
|
|
897
|
-
}).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));
|
|
898
1363
|
const position = input.at === "head" ? (edge?.first ?? 1) - 1 : (edge?.last ?? -1) + 1;
|
|
899
1364
|
const row = {
|
|
900
1365
|
id: crypto.randomUUID(),
|
|
@@ -911,15 +1376,15 @@ var DrizzleAgentStore = class {
|
|
|
911
1376
|
createdAt: now,
|
|
912
1377
|
updatedAt: now
|
|
913
1378
|
};
|
|
914
|
-
await this.db.insert(agentQueuedMessage).values(row);
|
|
1379
|
+
await this.db.insert(this.t.agentQueuedMessage).values(row);
|
|
915
1380
|
return toQueuedMessage(row);
|
|
916
1381
|
}
|
|
917
1382
|
async listQueue(threadId) {
|
|
918
|
-
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));
|
|
919
1384
|
return rows.map(toQueuedMessage);
|
|
920
1385
|
}
|
|
921
1386
|
async getQueuedMessage(id) {
|
|
922
|
-
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));
|
|
923
1388
|
return row === void 0 ? null : toQueuedMessage(row);
|
|
924
1389
|
}
|
|
925
1390
|
async updateQueuedMessage(id, patch) {
|
|
@@ -935,52 +1400,47 @@ var DrizzleAgentStore = class {
|
|
|
935
1400
|
if (patch.interrupt !== void 0) {
|
|
936
1401
|
updates.interrupt = patch.interrupt;
|
|
937
1402
|
}
|
|
938
|
-
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));
|
|
939
1404
|
return this.getQueuedMessage(id);
|
|
940
1405
|
}
|
|
941
1406
|
/** Rewrites the thread's positions as 0..n-1 in the new order — a queue is a handful of rows. */
|
|
942
|
-
async moveQueuedMessage(id,
|
|
1407
|
+
async moveQueuedMessage(id, index4) {
|
|
943
1408
|
const moving = await this.getQueuedMessage(id);
|
|
944
1409
|
if (moving === null) {
|
|
945
1410
|
return false;
|
|
946
1411
|
}
|
|
947
1412
|
const order = (await this.listQueue(moving.threadId)).filter((message) => message.id !== id);
|
|
948
|
-
const target = Math.max(0, Math.min(order.length, Math.trunc(
|
|
1413
|
+
const target = Math.max(0, Math.min(order.length, Math.trunc(index4)));
|
|
949
1414
|
order.splice(target, 0, moving);
|
|
950
1415
|
for (const [position, message] of order.entries()) {
|
|
951
|
-
await this.db.update(agentQueuedMessage).set({
|
|
1416
|
+
await this.db.update(this.t.agentQueuedMessage).set({
|
|
952
1417
|
position
|
|
953
|
-
}).where(eq(agentQueuedMessage.id, message.id));
|
|
1418
|
+
}).where(eq(this.t.agentQueuedMessage.id, message.id));
|
|
954
1419
|
}
|
|
955
1420
|
return true;
|
|
956
1421
|
}
|
|
957
1422
|
async removeQueuedMessage(id) {
|
|
958
|
-
const removed = await this.db.delete(agentQueuedMessage).where(eq(agentQueuedMessage.id, id)).
|
|
959
|
-
|
|
960
|
-
});
|
|
961
|
-
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;
|
|
962
1425
|
}
|
|
963
1426
|
async clearQueue(threadId) {
|
|
964
|
-
|
|
965
|
-
id: agentQueuedMessage.id
|
|
966
|
-
});
|
|
967
|
-
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);
|
|
968
1428
|
}
|
|
969
1429
|
async queuePause(threadId) {
|
|
970
1430
|
const [thread] = await this.db.select({
|
|
971
|
-
queuePause: agentThread.queuePause
|
|
972
|
-
}).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));
|
|
973
1433
|
return thread?.queuePause ?? null;
|
|
974
1434
|
}
|
|
975
1435
|
async setQueuePause(threadId, pause) {
|
|
976
|
-
await this.db.update(agentThread).set({
|
|
1436
|
+
await this.db.update(this.t.agentThread).set({
|
|
977
1437
|
queuePause: pause
|
|
978
|
-
}).where(eq(agentThread.id, threadId));
|
|
1438
|
+
}).where(eq(this.t.agentThread.id, threadId));
|
|
979
1439
|
}
|
|
980
1440
|
async setActiveStream(threadId, runId) {
|
|
981
|
-
await this.db.update(agentThread).set({
|
|
1441
|
+
await this.db.update(this.t.agentThread).set({
|
|
982
1442
|
activeStreamId: runId
|
|
983
|
-
}).where(eq(agentThread.id, threadId));
|
|
1443
|
+
}).where(eq(this.t.agentThread.id, threadId));
|
|
984
1444
|
}
|
|
985
1445
|
/**
|
|
986
1446
|
* Patch a thread's `title` and/or `defaultAgent`. Each field is only touched when PRESENT in
|
|
@@ -1006,7 +1466,7 @@ var DrizzleAgentStore = class {
|
|
|
1006
1466
|
return;
|
|
1007
1467
|
}
|
|
1008
1468
|
updates.updatedAt = /* @__PURE__ */ new Date();
|
|
1009
|
-
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));
|
|
1010
1470
|
}
|
|
1011
1471
|
/**
|
|
1012
1472
|
* The thread's default agent, projected — the caller wants one nullable scalar to decide which
|
|
@@ -1016,21 +1476,21 @@ var DrizzleAgentStore = class {
|
|
|
1016
1476
|
/** The thread's pinned model, projected like {@link defaultAgentForThread}. */
|
|
1017
1477
|
async modelForThread(threadId) {
|
|
1018
1478
|
const [thread] = await this.db.select({
|
|
1019
|
-
model: agentThread.model
|
|
1020
|
-
}).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)));
|
|
1021
1481
|
return thread?.model ?? null;
|
|
1022
1482
|
}
|
|
1023
1483
|
/** The thread's pinned persona, projected like {@link defaultAgentForThread}. */
|
|
1024
1484
|
async personaForThread(threadId) {
|
|
1025
1485
|
const [thread] = await this.db.select({
|
|
1026
|
-
persona: agentThread.persona
|
|
1027
|
-
}).from(agentThread).where(and(eq(agentThread.id, threadId), isNull(agentThread.deletedAt)));
|
|
1486
|
+
persona: this.t.agentThread.persona
|
|
1487
|
+
}).from(agentThread).where(and(eq(this.t.agentThread.id, threadId), isNull(this.t.agentThread.deletedAt)));
|
|
1028
1488
|
return thread?.persona ?? null;
|
|
1029
1489
|
}
|
|
1030
1490
|
async defaultAgentForThread(threadId) {
|
|
1031
1491
|
const [thread] = await this.db.select({
|
|
1032
|
-
defaultAgent: agentThread.defaultAgent
|
|
1033
|
-
}).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)));
|
|
1034
1494
|
return thread?.defaultAgent ?? null;
|
|
1035
1495
|
}
|
|
1036
1496
|
/**
|
|
@@ -1055,7 +1515,7 @@ var DrizzleAgentStore = class {
|
|
|
1055
1515
|
promptHash: run.promptHash ?? null,
|
|
1056
1516
|
parentRunId: run.parentRunId ?? null
|
|
1057
1517
|
};
|
|
1058
|
-
await this.db.insert(agentRun).values(runRow);
|
|
1518
|
+
await this.db.insert(this.t.agentRun).values(runRow);
|
|
1059
1519
|
}
|
|
1060
1520
|
/** Settle a run's outcome. A no-op when the run is unknown (mirrors `setTitle`/`updateThread`). */
|
|
1061
1521
|
async recordRunEnd(end) {
|
|
@@ -1072,16 +1532,16 @@ var DrizzleAgentStore = class {
|
|
|
1072
1532
|
if (end.errorMessage !== void 0) {
|
|
1073
1533
|
updates.errorMessage = end.errorMessage;
|
|
1074
1534
|
}
|
|
1075
|
-
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));
|
|
1076
1536
|
}
|
|
1077
1537
|
/** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */
|
|
1078
1538
|
async bumpRunRetries(runId) {
|
|
1079
|
-
await this.db.update(agentRun).set({
|
|
1080
|
-
retries: sql2`${agentRun.retries} + 1`
|
|
1081
|
-
}).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));
|
|
1082
1542
|
}
|
|
1083
1543
|
async appendMessage(input) {
|
|
1084
|
-
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));
|
|
1085
1545
|
if (thread === void 0) {
|
|
1086
1546
|
throw new Error(`thread ${input.threadId} not found`);
|
|
1087
1547
|
}
|
|
@@ -1103,47 +1563,48 @@ var DrizzleAgentStore = class {
|
|
|
1103
1563
|
reasoningMs: input.reasoningMs ?? null,
|
|
1104
1564
|
ui: input.ui ?? null,
|
|
1105
1565
|
feedback: null,
|
|
1566
|
+
seq: await this.nextMessageSeq(input.threadId),
|
|
1106
1567
|
createdAt: now
|
|
1107
1568
|
};
|
|
1108
|
-
await this.db.insert(agentMessage).values(message);
|
|
1109
|
-
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({
|
|
1110
1571
|
updatedAt: now
|
|
1111
|
-
}).where(eq(agentThread.id, input.threadId));
|
|
1572
|
+
}).where(eq(this.t.agentThread.id, input.threadId));
|
|
1112
1573
|
return this.toStoredMessage(message);
|
|
1113
1574
|
}
|
|
1114
1575
|
async setMessageToolResults(messageId, results) {
|
|
1115
|
-
await this.db.update(agentMessage).set({
|
|
1576
|
+
await this.db.update(this.t.agentMessage).set({
|
|
1116
1577
|
toolResults: results
|
|
1117
|
-
}).where(eq(agentMessage.id, messageId));
|
|
1578
|
+
}).where(eq(this.t.agentMessage.id, messageId));
|
|
1118
1579
|
}
|
|
1119
1580
|
async setMessageUi(messageId, ui) {
|
|
1120
|
-
await this.db.update(agentMessage).set({
|
|
1581
|
+
await this.db.update(this.t.agentMessage).set({
|
|
1121
1582
|
ui: ui.length > 0 ? ui : null
|
|
1122
|
-
}).where(eq(agentMessage.id, messageId));
|
|
1583
|
+
}).where(eq(this.t.agentMessage.id, messageId));
|
|
1123
1584
|
}
|
|
1124
1585
|
async threadOfMessage(messageId) {
|
|
1125
1586
|
const [row] = await this.db.select({
|
|
1126
|
-
threadId: agentMessage.threadId
|
|
1127
|
-
}).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);
|
|
1128
1589
|
return row?.threadId ?? null;
|
|
1129
1590
|
}
|
|
1130
1591
|
async setMessageFeedback(messageId, feedback) {
|
|
1131
|
-
await this.db.update(agentMessage).set({
|
|
1592
|
+
await this.db.update(this.t.agentMessage).set({
|
|
1132
1593
|
feedback
|
|
1133
|
-
}).where(eq(agentMessage.id, messageId));
|
|
1594
|
+
}).where(eq(this.t.agentMessage.id, messageId));
|
|
1134
1595
|
}
|
|
1135
1596
|
async truncateFrom(threadId, messageId) {
|
|
1136
|
-
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());
|
|
1137
1598
|
const cutoff = messages.findIndex((message) => message.id === messageId);
|
|
1138
1599
|
if (cutoff < 0) {
|
|
1139
1600
|
return;
|
|
1140
1601
|
}
|
|
1141
1602
|
const doomedIds = messages.slice(cutoff).map((message) => message.id);
|
|
1142
|
-
await this.db.delete(agentToolCall).where(inArray(agentToolCall.messageId, doomedIds));
|
|
1143
|
-
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));
|
|
1144
1605
|
}
|
|
1145
1606
|
async recordToolCall(input) {
|
|
1146
|
-
await this.db.insert(agentToolCall).values({
|
|
1607
|
+
await this.db.insert(this.t.agentToolCall).values({
|
|
1147
1608
|
id: input.toolCallId,
|
|
1148
1609
|
messageId: input.messageId,
|
|
1149
1610
|
toolName: input.toolName,
|
|
@@ -1188,18 +1649,18 @@ var DrizzleAgentStore = class {
|
|
|
1188
1649
|
if (input.status === "executed" || input.status === "auto_executed") {
|
|
1189
1650
|
updates.executedAt = /* @__PURE__ */ new Date();
|
|
1190
1651
|
}
|
|
1191
|
-
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));
|
|
1192
1653
|
}
|
|
1193
1654
|
async toolCallOutcomes(toolCallIds) {
|
|
1194
1655
|
if (toolCallIds.length === 0) {
|
|
1195
1656
|
return [];
|
|
1196
1657
|
}
|
|
1197
1658
|
const rows = await this.db.select({
|
|
1198
|
-
id: agentToolCall.id,
|
|
1199
|
-
status: agentToolCall.status,
|
|
1200
|
-
output: agentToolCall.output,
|
|
1201
|
-
error: agentToolCall.error
|
|
1202
|
-
}).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, [
|
|
1203
1664
|
...toolCallIds
|
|
1204
1665
|
]));
|
|
1205
1666
|
return rows.map((row) => ({
|
|
@@ -1214,14 +1675,14 @@ var DrizzleAgentStore = class {
|
|
|
1214
1675
|
}));
|
|
1215
1676
|
}
|
|
1216
1677
|
async failUnsettledToolCalls(runId, error) {
|
|
1217
|
-
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"));
|
|
1218
1679
|
const rows = await this.db.select({
|
|
1219
|
-
id: agentToolCall.id
|
|
1220
|
-
}).from(agentToolCall).where(pending);
|
|
1680
|
+
id: this.t.agentToolCall.id
|
|
1681
|
+
}).from(this.t.agentToolCall).where(pending);
|
|
1221
1682
|
if (rows.length === 0) {
|
|
1222
1683
|
return 0;
|
|
1223
1684
|
}
|
|
1224
|
-
await this.db.update(agentToolCall).set({
|
|
1685
|
+
await this.db.update(this.t.agentToolCall).set({
|
|
1225
1686
|
status: "failed",
|
|
1226
1687
|
error
|
|
1227
1688
|
}).where(pending);
|
|
@@ -1246,11 +1707,11 @@ var DrizzleAgentStore = class {
|
|
|
1246
1707
|
return [];
|
|
1247
1708
|
}
|
|
1248
1709
|
const rows = await this.db.select({
|
|
1249
|
-
attachments: agentMessage.attachments
|
|
1250
|
-
}).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)));
|
|
1251
1712
|
const queued = await this.db.select({
|
|
1252
|
-
attachments: agentQueuedMessage.attachments
|
|
1253
|
-
}).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)));
|
|
1254
1715
|
const wanted = new Set(mediaIds);
|
|
1255
1716
|
const found = /* @__PURE__ */ new Set();
|
|
1256
1717
|
for (const row of [
|
|
@@ -1268,7 +1729,7 @@ var DrizzleAgentStore = class {
|
|
|
1268
1729
|
].filter((mediaId) => found.has(mediaId));
|
|
1269
1730
|
}
|
|
1270
1731
|
async recordUsage(input) {
|
|
1271
|
-
await this.db.insert(agentTokenUsage).values({
|
|
1732
|
+
await this.db.insert(this.t.agentTokenUsage).values({
|
|
1272
1733
|
id: crypto.randomUUID(),
|
|
1273
1734
|
threadId: input.threadId,
|
|
1274
1735
|
actorRef: input.actorRef,
|
|
@@ -1289,7 +1750,7 @@ var DrizzleAgentStore = class {
|
|
|
1289
1750
|
async usageBetween(actorRef, fromDay, toDay) {
|
|
1290
1751
|
const start = /* @__PURE__ */ new Date(`${fromDay}T00:00:00.000Z`);
|
|
1291
1752
|
const end = /* @__PURE__ */ new Date(`${toDay}T23:59:59.999Z`);
|
|
1292
|
-
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)));
|
|
1293
1754
|
const usedTokens = rows.reduce((sum2, row) => sum2 + row.inputTokens + row.outputTokens, 0);
|
|
1294
1755
|
const costUsd = rows.reduce((sum2, row) => sum2 + (row.costUsd ?? 0), 0);
|
|
1295
1756
|
return {
|
|
@@ -1504,11 +1965,15 @@ var DrizzleGovernanceQueries = class {
|
|
|
1504
1965
|
static {
|
|
1505
1966
|
__name(this, "DrizzleGovernanceQueries");
|
|
1506
1967
|
}
|
|
1507
|
-
db;
|
|
1508
1968
|
pricingStore;
|
|
1969
|
+
db;
|
|
1970
|
+
dialect;
|
|
1971
|
+
t;
|
|
1509
1972
|
constructor(db, pricingStore) {
|
|
1510
|
-
this.db = db;
|
|
1511
1973
|
this.pricingStore = pricingStore;
|
|
1974
|
+
this.dialect = agentDialectOf(db);
|
|
1975
|
+
this.t = agentTablesFor(this.dialect);
|
|
1976
|
+
this.db = asBuilder(db);
|
|
1512
1977
|
}
|
|
1513
1978
|
async loadPricing() {
|
|
1514
1979
|
const prices = await this.pricingStore.listCurrentPrices();
|
|
@@ -1525,7 +1990,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1525
1990
|
}
|
|
1526
1991
|
async usageInRange(range) {
|
|
1527
1992
|
const { start, end } = dayBoundsUtc(range);
|
|
1528
|
-
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)));
|
|
1529
1994
|
return rows.map(toUsageInput);
|
|
1530
1995
|
}
|
|
1531
1996
|
async spendByModel(range) {
|
|
@@ -1550,7 +2015,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1550
2015
|
if (threadIds.length === 0) {
|
|
1551
2016
|
return [];
|
|
1552
2017
|
}
|
|
1553
|
-
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)));
|
|
1554
2019
|
const threadsById = new Map(threads.map((thread) => [
|
|
1555
2020
|
thread.id,
|
|
1556
2021
|
{
|
|
@@ -1569,14 +2034,14 @@ var DrizzleGovernanceQueries = class {
|
|
|
1569
2034
|
}
|
|
1570
2035
|
async recentToolCalls(limit) {
|
|
1571
2036
|
const rows = await this.db.select({
|
|
1572
|
-
toolCallId: agentToolCall.id,
|
|
1573
|
-
toolName: agentToolCall.toolName,
|
|
1574
|
-
toolType: agentToolCall.toolType,
|
|
1575
|
-
status: agentToolCall.status,
|
|
1576
|
-
threadId: agentMessage.threadId,
|
|
1577
|
-
createdAt: agentToolCall.createdAt,
|
|
1578
|
-
runId: agentToolCall.runId
|
|
1579
|
-
}).from(agentToolCall).innerJoin(agentMessage, 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);
|
|
1580
2045
|
return rows.map((row) => ({
|
|
1581
2046
|
toolCallId: row.toolCallId,
|
|
1582
2047
|
toolName: row.toolName,
|
|
@@ -1604,9 +2069,9 @@ var DrizzleGovernanceQueries = class {
|
|
|
1604
2069
|
return rollups;
|
|
1605
2070
|
}
|
|
1606
2071
|
const messageCounts = await this.db.select({
|
|
1607
|
-
threadId: agentMessage.threadId,
|
|
2072
|
+
threadId: this.t.agentMessage.threadId,
|
|
1608
2073
|
value: count()
|
|
1609
|
-
}).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);
|
|
1610
2075
|
for (const row of messageCounts) {
|
|
1611
2076
|
const bucket = rollups.get(row.threadId);
|
|
1612
2077
|
if (bucket !== void 0) {
|
|
@@ -1614,10 +2079,10 @@ var DrizzleGovernanceQueries = class {
|
|
|
1614
2079
|
}
|
|
1615
2080
|
}
|
|
1616
2081
|
const usageTotals = await this.db.select({
|
|
1617
|
-
threadId: agentTokenUsage.threadId,
|
|
1618
|
-
inputTokens: sum(agentTokenUsage.inputTokens),
|
|
1619
|
-
outputTokens: sum(agentTokenUsage.outputTokens)
|
|
1620
|
-
}).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);
|
|
1621
2086
|
for (const row of usageTotals) {
|
|
1622
2087
|
const bucket = rollups.get(row.threadId);
|
|
1623
2088
|
if (bucket !== void 0) {
|
|
@@ -1642,12 +2107,12 @@ var DrizzleGovernanceQueries = class {
|
|
|
1642
2107
|
});
|
|
1643
2108
|
}
|
|
1644
2109
|
async recentThreads(limit) {
|
|
1645
|
-
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);
|
|
1646
2111
|
return this.toThreadActivityRows(threads);
|
|
1647
2112
|
}
|
|
1648
2113
|
async runsInRange(range) {
|
|
1649
2114
|
const { start, end } = dayBoundsUtc(range);
|
|
1650
|
-
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)));
|
|
1651
2116
|
}
|
|
1652
2117
|
async runMetrics(range) {
|
|
1653
2118
|
const runs = await this.runsInRange(range);
|
|
@@ -1704,7 +2169,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1704
2169
|
}
|
|
1705
2170
|
async runErrors(range) {
|
|
1706
2171
|
const { start, end } = dayBoundsUtc(range);
|
|
1707
|
-
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")));
|
|
1708
2173
|
const byError = /* @__PURE__ */ new Map();
|
|
1709
2174
|
for (const run of runs) {
|
|
1710
2175
|
const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;
|
|
@@ -1744,7 +2209,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1744
2209
|
return result;
|
|
1745
2210
|
}
|
|
1746
2211
|
async recentRuns(limit) {
|
|
1747
|
-
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);
|
|
1748
2213
|
return runs.map(toRecentRunRow);
|
|
1749
2214
|
}
|
|
1750
2215
|
/**
|
|
@@ -1754,16 +2219,16 @@ var DrizzleGovernanceQueries = class {
|
|
|
1754
2219
|
*/
|
|
1755
2220
|
async pendingApprovals(limit) {
|
|
1756
2221
|
const rows = await this.db.select({
|
|
1757
|
-
toolCallId: agentToolCall.id,
|
|
1758
|
-
toolName: agentToolCall.toolName,
|
|
1759
|
-
input: agentToolCall.input,
|
|
1760
|
-
threadId: agentThread.id,
|
|
1761
|
-
threadTitle: agentThread.title,
|
|
1762
|
-
actorRef: agentThread.actorRef,
|
|
1763
|
-
agentName: agentMessage.agentName,
|
|
1764
|
-
requestedAt: agentToolCall.createdAt,
|
|
1765
|
-
runId: agentToolCall.runId
|
|
1766
|
-
}).from(agentToolCall).innerJoin(agentMessage, 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);
|
|
1767
2232
|
return rows.map((row) => ({
|
|
1768
2233
|
toolCallId: row.toolCallId,
|
|
1769
2234
|
toolName: row.toolName,
|
|
@@ -1785,11 +2250,11 @@ var DrizzleGovernanceQueries = class {
|
|
|
1785
2250
|
*/
|
|
1786
2251
|
async toolStats(range) {
|
|
1787
2252
|
const { start, end } = dayBoundsUtc(range);
|
|
1788
|
-
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)));
|
|
1789
2254
|
const byTool = /* @__PURE__ */ new Map();
|
|
1790
2255
|
for (const call of calls) {
|
|
1791
|
-
const
|
|
1792
|
-
const bucket = byTool.get(
|
|
2256
|
+
const key2 = `${call.toolName} ${call.toolType}`;
|
|
2257
|
+
const bucket = byTool.get(key2) ?? {
|
|
1793
2258
|
toolName: call.toolName,
|
|
1794
2259
|
toolType: call.toolType,
|
|
1795
2260
|
calls: 0,
|
|
@@ -1803,7 +2268,7 @@ var DrizzleGovernanceQueries = class {
|
|
|
1803
2268
|
if (call.executionMs != null) {
|
|
1804
2269
|
bucket.executionMs.push(call.executionMs);
|
|
1805
2270
|
}
|
|
1806
|
-
byTool.set(
|
|
2271
|
+
byTool.set(key2, bucket);
|
|
1807
2272
|
}
|
|
1808
2273
|
const result = [];
|
|
1809
2274
|
for (const bucket of byTool.values()) {
|
|
@@ -1835,19 +2300,19 @@ var DrizzleGovernanceQueries = class {
|
|
|
1835
2300
|
if (filters?.toolType !== void 0 && !isToolKind(filters.toolType)) {
|
|
1836
2301
|
return emptyPage(query);
|
|
1837
2302
|
}
|
|
1838
|
-
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);
|
|
1839
2304
|
const [totalRow] = await this.db.select({
|
|
1840
2305
|
value: count()
|
|
1841
|
-
}).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);
|
|
1842
2307
|
const rows = await this.db.select({
|
|
1843
|
-
toolCallId: agentToolCall.id,
|
|
1844
|
-
toolName: agentToolCall.toolName,
|
|
1845
|
-
toolType: agentToolCall.toolType,
|
|
1846
|
-
status: agentToolCall.status,
|
|
1847
|
-
threadId: agentMessage.threadId,
|
|
1848
|
-
createdAt: agentToolCall.createdAt,
|
|
1849
|
-
runId: agentToolCall.runId
|
|
1850
|
-
}).from(agentToolCall).innerJoin(agentMessage, 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);
|
|
1851
2316
|
return {
|
|
1852
2317
|
rows: rows.map((row) => ({
|
|
1853
2318
|
toolCallId: row.toolCallId,
|
|
@@ -1871,11 +2336,11 @@ var DrizzleGovernanceQueries = class {
|
|
|
1871
2336
|
*/
|
|
1872
2337
|
async threadsPage(query) {
|
|
1873
2338
|
const filters = query.where;
|
|
1874
|
-
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);
|
|
1875
2340
|
const [totalRow] = await this.db.select({
|
|
1876
2341
|
value: count()
|
|
1877
|
-
}).from(agentThread).where(whereClause);
|
|
1878
|
-
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);
|
|
1879
2344
|
const rows = await this.toThreadActivityRows(threads);
|
|
1880
2345
|
return {
|
|
1881
2346
|
rows,
|
|
@@ -1893,11 +2358,11 @@ var DrizzleGovernanceQueries = class {
|
|
|
1893
2358
|
if (filters?.status !== void 0 && !isRunStatus(filters.status)) {
|
|
1894
2359
|
return emptyPage(query);
|
|
1895
2360
|
}
|
|
1896
|
-
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);
|
|
1897
2362
|
const [totalRow] = await this.db.select({
|
|
1898
2363
|
value: count()
|
|
1899
|
-
}).from(agentRun).where(whereClause);
|
|
1900
|
-
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);
|
|
1901
2366
|
return {
|
|
1902
2367
|
rows: runs.map(toRecentRunRow),
|
|
1903
2368
|
total: totalRow?.value ?? 0,
|
|
@@ -1917,21 +2382,21 @@ var DrizzleGovernanceQueries = class {
|
|
|
1917
2382
|
*/
|
|
1918
2383
|
async approvalsPage(query) {
|
|
1919
2384
|
const filters = query.where;
|
|
1920
|
-
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);
|
|
1921
2386
|
const [totalRow] = await this.db.select({
|
|
1922
2387
|
value: count()
|
|
1923
|
-
}).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);
|
|
1924
2389
|
const rows = await this.db.select({
|
|
1925
|
-
toolCallId: agentToolCall.id,
|
|
1926
|
-
toolName: agentToolCall.toolName,
|
|
1927
|
-
input: agentToolCall.input,
|
|
1928
|
-
threadId: agentThread.id,
|
|
1929
|
-
threadTitle: agentThread.title,
|
|
1930
|
-
actorRef: agentThread.actorRef,
|
|
1931
|
-
agentName: agentMessage.agentName,
|
|
1932
|
-
requestedAt: agentToolCall.createdAt,
|
|
1933
|
-
runId: agentToolCall.runId
|
|
1934
|
-
}).from(agentToolCall).innerJoin(agentMessage, 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);
|
|
1935
2400
|
return {
|
|
1936
2401
|
rows: rows.map((row) => ({
|
|
1937
2402
|
toolCallId: row.toolCallId,
|
|
@@ -1956,13 +2421,13 @@ var DrizzleGovernanceQueries = class {
|
|
|
1956
2421
|
*/
|
|
1957
2422
|
async runDetail(runId) {
|
|
1958
2423
|
const [row] = await this.db.select({
|
|
1959
|
-
run: agentRun,
|
|
1960
|
-
thread: agentThread
|
|
1961
|
-
}).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);
|
|
1962
2427
|
if (row === void 0) {
|
|
1963
2428
|
return null;
|
|
1964
2429
|
}
|
|
1965
|
-
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));
|
|
1966
2431
|
return {
|
|
1967
2432
|
run: toRecentRunRow(row.run),
|
|
1968
2433
|
thread: {
|
|
@@ -1981,22 +2446,27 @@ var DrizzleGovernanceQueries = class {
|
|
|
1981
2446
|
* message. Soft-deleted threads are returned with `deleted: true`; an audit still needs them.
|
|
1982
2447
|
*/
|
|
1983
2448
|
async threadDetail(query) {
|
|
1984
|
-
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);
|
|
1985
2450
|
if (thread === void 0) {
|
|
1986
2451
|
return null;
|
|
1987
2452
|
}
|
|
1988
2453
|
const pricing = await this.loadPricing();
|
|
1989
|
-
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));
|
|
1990
2455
|
const usage = rollupThreadUsage(usageRows.map(toUsageInput), pricing);
|
|
1991
2456
|
const [messageCountRow] = await this.db.select({
|
|
1992
2457
|
value: count()
|
|
1993
|
-
}).from(agentMessage).where(eq2(agentMessage.threadId, thread.id));
|
|
1994
|
-
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);
|
|
1995
2465
|
const toolCallCounts = await this.toolCallCountsByMessage(messages.map((message) => message.id));
|
|
1996
2466
|
const [runTotalRow] = await this.db.select({
|
|
1997
2467
|
value: count()
|
|
1998
|
-
}).from(agentRun).where(eq2(agentRun.threadId, thread.id));
|
|
1999
|
-
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);
|
|
2000
2470
|
return {
|
|
2001
2471
|
thread: {
|
|
2002
2472
|
threadId: thread.id,
|
|
@@ -2031,9 +2501,9 @@ var DrizzleGovernanceQueries = class {
|
|
|
2031
2501
|
return counts;
|
|
2032
2502
|
}
|
|
2033
2503
|
const rows = await this.db.select({
|
|
2034
|
-
messageId: agentToolCall.messageId,
|
|
2504
|
+
messageId: this.t.agentToolCall.messageId,
|
|
2035
2505
|
value: count()
|
|
2036
|
-
}).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);
|
|
2037
2507
|
for (const row of rows) {
|
|
2038
2508
|
counts.set(row.messageId, row.value);
|
|
2039
2509
|
}
|
|
@@ -2072,8 +2542,12 @@ var DrizzleMemoryProvider = class {
|
|
|
2072
2542
|
__name(this, "DrizzleMemoryProvider");
|
|
2073
2543
|
}
|
|
2074
2544
|
db;
|
|
2545
|
+
dialect;
|
|
2546
|
+
t;
|
|
2075
2547
|
constructor(db) {
|
|
2076
|
-
this.
|
|
2548
|
+
this.dialect = agentDialectOf(db);
|
|
2549
|
+
this.t = agentTablesFor(this.dialect);
|
|
2550
|
+
this.db = asBuilder(db);
|
|
2077
2551
|
}
|
|
2078
2552
|
/**
|
|
2079
2553
|
* Every memory visible at `scopes` — asked on EVERY turn, so it is one indexed `scope in (…)`
|
|
@@ -2087,7 +2561,7 @@ var DrizzleMemoryProvider = class {
|
|
|
2087
2561
|
if (scopes.length === 0) {
|
|
2088
2562
|
return [];
|
|
2089
2563
|
}
|
|
2090
|
-
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, [
|
|
2091
2565
|
...scopes
|
|
2092
2566
|
]));
|
|
2093
2567
|
return rows.map(toRecord);
|
|
@@ -2103,10 +2577,8 @@ var DrizzleMemoryProvider = class {
|
|
|
2103
2577
|
* answer cannot be used to find out which memories exist about other people.
|
|
2104
2578
|
*/
|
|
2105
2579
|
async forget({ id, ctx }) {
|
|
2106
|
-
const deleted = await this.db.delete(agentMemory).where(and3(eq3(agentMemory.id, id), eq3(agentMemory.scope, actorScope(ctx.actor)))).
|
|
2107
|
-
|
|
2108
|
-
});
|
|
2109
|
-
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;
|
|
2110
2582
|
}
|
|
2111
2583
|
/**
|
|
2112
2584
|
* Upsert on (`scope`, `key`) — one statement, against the unique index, rather than a read
|
|
@@ -2119,7 +2591,7 @@ var DrizzleMemoryProvider = class {
|
|
|
2119
2591
|
* rewriting `createdAt` would lose when the belief was first formed; reassigning `id` would
|
|
2120
2592
|
* invalidate the delete handle a person was already shown.
|
|
2121
2593
|
*/
|
|
2122
|
-
async write({ key, text:
|
|
2594
|
+
async write({ key: key2, text: text3, scope, origin, ctx }) {
|
|
2123
2595
|
assertAuthorMayWriteScope({
|
|
2124
2596
|
scope,
|
|
2125
2597
|
origin,
|
|
@@ -2132,28 +2604,40 @@ var DrizzleMemoryProvider = class {
|
|
|
2132
2604
|
originRunId: origin.runId ?? null,
|
|
2133
2605
|
originActorRef: origin.actorRef ?? null
|
|
2134
2606
|
};
|
|
2135
|
-
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({
|
|
2136
2614
|
id: crypto.randomUUID(),
|
|
2137
2615
|
scope,
|
|
2138
|
-
key,
|
|
2139
|
-
text:
|
|
2616
|
+
key: key2,
|
|
2617
|
+
text: text3,
|
|
2140
2618
|
...columns,
|
|
2141
2619
|
pinned: false,
|
|
2142
2620
|
createdAt: now,
|
|
2143
2621
|
updatedAt: now
|
|
2144
|
-
})
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
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
|
+
}
|
|
2155
2639
|
if (row === void 0) {
|
|
2156
|
-
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.`);
|
|
2157
2641
|
}
|
|
2158
2642
|
return toRecord(row);
|
|
2159
2643
|
}
|
|
@@ -2166,13 +2650,11 @@ var DrizzleMemoryProvider = class {
|
|
|
2166
2650
|
* `false` where there is no such id.
|
|
2167
2651
|
*/
|
|
2168
2652
|
async pin({ id, pinned }) {
|
|
2169
|
-
const updated = await this.db.update(agentMemory).set({
|
|
2653
|
+
const updated = await affectedRows(this.dialect, this.db.update(this.t.agentMemory).set({
|
|
2170
2654
|
pinned,
|
|
2171
2655
|
updatedAt: /* @__PURE__ */ new Date()
|
|
2172
|
-
}).where(eq3(agentMemory.id, id)).
|
|
2173
|
-
|
|
2174
|
-
});
|
|
2175
|
-
return updated.length > 0;
|
|
2656
|
+
}).where(eq3(this.t.agentMemory.id, id)), this.t.agentMemory.id);
|
|
2657
|
+
return updated > 0;
|
|
2176
2658
|
}
|
|
2177
2659
|
};
|
|
2178
2660
|
function assertAuthorMayWriteScope({ scope, origin, ctx }) {
|
|
@@ -2190,14 +2672,18 @@ var DrizzlePricingStore = class {
|
|
|
2190
2672
|
__name(this, "DrizzlePricingStore");
|
|
2191
2673
|
}
|
|
2192
2674
|
db;
|
|
2675
|
+
dialect;
|
|
2676
|
+
t;
|
|
2193
2677
|
constructor(db) {
|
|
2194
|
-
this.
|
|
2678
|
+
this.dialect = agentDialectOf(db);
|
|
2679
|
+
this.t = agentTablesFor(this.dialect);
|
|
2680
|
+
this.db = asBuilder(db);
|
|
2195
2681
|
}
|
|
2196
2682
|
async upsertModelPrice(input) {
|
|
2197
|
-
await this.db.update(agentModelPricing).set({
|
|
2683
|
+
await this.db.update(this.t.agentModelPricing).set({
|
|
2198
2684
|
isCurrent: false
|
|
2199
|
-
}).where(and4(eq4(agentModelPricing.modelId, input.modelId), eq4(agentModelPricing.isCurrent, true)));
|
|
2200
|
-
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({
|
|
2201
2687
|
id: crypto.randomUUID(),
|
|
2202
2688
|
modelId: input.modelId,
|
|
2203
2689
|
inputPricePer1m: input.inputPricePer1m,
|
|
@@ -2209,7 +2695,7 @@ var DrizzlePricingStore = class {
|
|
|
2209
2695
|
});
|
|
2210
2696
|
}
|
|
2211
2697
|
async listCurrentPrices() {
|
|
2212
|
-
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));
|
|
2213
2699
|
return rows.map((row) => ({
|
|
2214
2700
|
modelId: row.modelId,
|
|
2215
2701
|
inputPricePer1m: row.inputPricePer1m,
|
|
@@ -2228,51 +2714,46 @@ var DrizzlePricingStore = class {
|
|
|
2228
2714
|
// src/drizzle-token-stream-sink.ts
|
|
2229
2715
|
import { SqlTokenStreamSink } from "@dudousxd/nestjs-agent-core";
|
|
2230
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";
|
|
2231
|
-
function isUniqueViolation(error) {
|
|
2232
|
-
for (let current = error; current !== null && typeof current === "object"; ) {
|
|
2233
|
-
const code = current.code;
|
|
2234
|
-
if (typeof code === "string" && code.startsWith("SQLITE_CONSTRAINT")) return true;
|
|
2235
|
-
current = current.cause;
|
|
2236
|
-
}
|
|
2237
|
-
return false;
|
|
2238
|
-
}
|
|
2239
|
-
__name(isUniqueViolation, "isUniqueViolation");
|
|
2240
2717
|
var DrizzleStreamFrameTable = class {
|
|
2241
2718
|
static {
|
|
2242
2719
|
__name(this, "DrizzleStreamFrameTable");
|
|
2243
2720
|
}
|
|
2244
2721
|
db;
|
|
2722
|
+
dialect;
|
|
2723
|
+
t;
|
|
2245
2724
|
constructor(db) {
|
|
2246
|
-
this.
|
|
2725
|
+
this.dialect = agentDialectOf(db);
|
|
2726
|
+
this.t = agentTablesFor(this.dialect);
|
|
2727
|
+
this.db = asBuilder(db);
|
|
2247
2728
|
}
|
|
2248
2729
|
async append(runId, row) {
|
|
2249
|
-
await this.db.
|
|
2730
|
+
await runSql(this.db, this.dialect, sql4`INSERT INTO agent_stream_frame (run_id, seq, frame, error, created_at)
|
|
2250
2731
|
SELECT ${runId}, COALESCE(MAX(seq), 0) + 1, ${row.frame}, ${row.error}, ${row.createdAt}
|
|
2251
2732
|
FROM agent_stream_frame WHERE run_id = ${runId}`);
|
|
2252
2733
|
}
|
|
2253
2734
|
async read(runId, after, limit) {
|
|
2254
2735
|
return this.db.select({
|
|
2255
|
-
seq: agentStreamFrame.seq,
|
|
2256
|
-
frame: agentStreamFrame.frame,
|
|
2257
|
-
error: agentStreamFrame.error
|
|
2258
|
-
}).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);
|
|
2259
2740
|
}
|
|
2260
2741
|
async has(runId) {
|
|
2261
2742
|
const rows = await this.db.select({
|
|
2262
|
-
seq: agentStreamFrame.seq
|
|
2263
|
-
}).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);
|
|
2264
2745
|
return rows.length > 0;
|
|
2265
2746
|
}
|
|
2266
2747
|
async remove(runIds) {
|
|
2267
2748
|
if (runIds.length === 0) return;
|
|
2268
|
-
await this.db.delete(agentStreamFrame).where(inArray4(agentStreamFrame.runId, [
|
|
2749
|
+
await this.db.delete(this.t.agentStreamFrame).where(inArray4(this.t.agentStreamFrame.runId, [
|
|
2269
2750
|
...runIds
|
|
2270
2751
|
]));
|
|
2271
2752
|
}
|
|
2272
2753
|
async lapsedRuns(cutoff) {
|
|
2273
2754
|
const rows = await this.db.select({
|
|
2274
|
-
runId: agentStreamFrame.runId
|
|
2275
|
-
}).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));
|
|
2276
2757
|
return rows.map((row) => row.runId);
|
|
2277
2758
|
}
|
|
2278
2759
|
isUniqueViolation(error) {
|
|
@@ -2295,29 +2776,35 @@ var DrizzleConfirmTokenStore = class {
|
|
|
2295
2776
|
__name(this, "DrizzleConfirmTokenStore");
|
|
2296
2777
|
}
|
|
2297
2778
|
db;
|
|
2779
|
+
dialect;
|
|
2780
|
+
t;
|
|
2298
2781
|
constructor(db) {
|
|
2299
|
-
this.
|
|
2782
|
+
this.dialect = agentDialectOf(db);
|
|
2783
|
+
this.t = agentTablesFor(this.dialect);
|
|
2784
|
+
this.db = asBuilder(db);
|
|
2300
2785
|
}
|
|
2301
2786
|
async claim(input) {
|
|
2302
|
-
const
|
|
2787
|
+
const row = {
|
|
2303
2788
|
hash: input.hash,
|
|
2304
2789
|
actorRef: input.actorRef,
|
|
2305
2790
|
tool: input.tool,
|
|
2306
2791
|
expiresAt: input.expiresAt,
|
|
2307
2792
|
createdAt: Date.now()
|
|
2308
|
-
}
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
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;
|
|
2312
2801
|
}
|
|
2313
2802
|
async release(hash) {
|
|
2314
|
-
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));
|
|
2315
2804
|
}
|
|
2316
2805
|
async purgeExpired(now = Date.now()) {
|
|
2317
|
-
const
|
|
2318
|
-
|
|
2319
|
-
});
|
|
2320
|
-
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);
|
|
2321
2808
|
}
|
|
2322
2809
|
};
|
|
2323
2810
|
|
|
@@ -2325,18 +2812,18 @@ var DrizzleConfirmTokenStore = class {
|
|
|
2325
2812
|
import { subscribe, unsubscribe } from "diagnostics_channel";
|
|
2326
2813
|
import { Injectable, Logger } from "@nestjs/common";
|
|
2327
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";
|
|
2328
|
-
function _ts_decorate(decorators, target,
|
|
2329
|
-
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;
|
|
2330
2817
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
|
|
2331
|
-
r = Reflect.decorate(decorators, target,
|
|
2818
|
+
r = Reflect.decorate(decorators, target, key2, desc4);
|
|
2332
2819
|
} else {
|
|
2333
2820
|
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
2334
2821
|
if (d = decorators[i]) {
|
|
2335
|
-
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;
|
|
2336
2823
|
}
|
|
2337
2824
|
}
|
|
2338
2825
|
}
|
|
2339
|
-
return c > 3 && r && Object.defineProperty(target,
|
|
2826
|
+
return c > 3 && r && Object.defineProperty(target, key2, r), r;
|
|
2340
2827
|
}
|
|
2341
2828
|
__name(_ts_decorate, "_ts_decorate");
|
|
2342
2829
|
function _ts_metadata(metadataKey, metadataValue) {
|
|
@@ -2382,20 +2869,27 @@ function batches(batchSize) {
|
|
|
2382
2869
|
return Number.isFinite(requested) && requested >= 1 ? requested : DEFAULT_BATCH_SIZE;
|
|
2383
2870
|
}
|
|
2384
2871
|
__name(batches, "batches");
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2872
|
+
function cursorColumns(log) {
|
|
2873
|
+
return {
|
|
2874
|
+
documentId: log.documentId,
|
|
2875
|
+
updatedAt: log.updatedAt
|
|
2876
|
+
};
|
|
2877
|
+
}
|
|
2878
|
+
__name(cursorColumns, "cursorColumns");
|
|
2389
2879
|
var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
2390
2880
|
static {
|
|
2391
2881
|
__name(this, "DrizzleRagIngestionLog");
|
|
2392
2882
|
}
|
|
2393
|
-
db;
|
|
2394
2883
|
logger = new Logger(_DrizzleRagIngestionLog.name);
|
|
2395
2884
|
teardowns = [];
|
|
2396
2885
|
inFlight = /* @__PURE__ */ new Set();
|
|
2886
|
+
db;
|
|
2887
|
+
dialect;
|
|
2888
|
+
t;
|
|
2397
2889
|
constructor(db) {
|
|
2398
|
-
this.
|
|
2890
|
+
this.dialect = agentDialectOf(db);
|
|
2891
|
+
this.t = agentTablesFor(this.dialect);
|
|
2892
|
+
this.db = asBuilder(db);
|
|
2399
2893
|
}
|
|
2400
2894
|
onModuleInit() {
|
|
2401
2895
|
for (const channel of CHANNELS) {
|
|
@@ -2424,7 +2918,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2424
2918
|
}
|
|
2425
2919
|
/** The latest recorded outcome per document, newest first. */
|
|
2426
2920
|
async list(query = {}) {
|
|
2427
|
-
const rows = this.db.select().from(ragIngestionLog).where(this.where(query)).orderBy(...RAG_INGESTION_LOG_PAGE_ORDER).limit(query.limit ?? DEFAULT_PAGE_SIZE);
|
|
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);
|
|
2428
2922
|
return query.offset === void 0 ? rows : rows.offset(query.offset);
|
|
2429
2923
|
}
|
|
2430
2924
|
/**
|
|
@@ -2438,7 +2932,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2438
2932
|
async listPage(query = {}) {
|
|
2439
2933
|
const [totalRow] = await this.db.select({
|
|
2440
2934
|
value: count2()
|
|
2441
|
-
}).from(ragIngestionLog).where(this.where(query));
|
|
2935
|
+
}).from(this.t.ragIngestionLog).where(this.where(query));
|
|
2442
2936
|
return {
|
|
2443
2937
|
rows: await this.list(query),
|
|
2444
2938
|
total: totalRow?.value ?? 0
|
|
@@ -2491,7 +2985,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2491
2985
|
* sweep is run. A sweep that stops early stops by `break`ing out of the `for await`.
|
|
2492
2986
|
*/
|
|
2493
2987
|
iterate(where = {}, options = {}) {
|
|
2494
|
-
return this.sweep(where, batches(options.batchSize), options.after, (filter, limit) => this.db.select().from(ragIngestionLog).where(filter).orderBy(...RAG_INGESTION_LOG_PAGE_ORDER).limit(limit));
|
|
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));
|
|
2495
2989
|
}
|
|
2496
2990
|
/**
|
|
2497
2991
|
* Just the document ids of the matching rows, in {@link RAG_INGESTION_LOG_PAGE_ORDER}.
|
|
@@ -2508,7 +3002,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2508
3002
|
*/
|
|
2509
3003
|
async listDocumentIds(where = {}, options = {}) {
|
|
2510
3004
|
const ids = [];
|
|
2511
|
-
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));
|
|
2512
3006
|
for await (const row of rows) {
|
|
2513
3007
|
ids.push(row.documentId);
|
|
2514
3008
|
}
|
|
@@ -2516,22 +3010,18 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2516
3010
|
}
|
|
2517
3011
|
/** The latest recorded outcome for one document, or null if it was never attempted. */
|
|
2518
3012
|
async get(documentId) {
|
|
2519
|
-
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));
|
|
2520
3014
|
return row ?? null;
|
|
2521
3015
|
}
|
|
2522
3016
|
/** Forget one document's record. Returns whether a row was actually removed. */
|
|
2523
3017
|
async remove(documentId) {
|
|
2524
|
-
const removed = await this.db.delete(ragIngestionLog).where(eq7(ragIngestionLog.documentId, documentId)).
|
|
2525
|
-
|
|
2526
|
-
});
|
|
2527
|
-
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;
|
|
2528
3020
|
}
|
|
2529
3021
|
/** Forget every record for a collection — for when the collection itself is deleted. */
|
|
2530
3022
|
async removeByCollection(collection) {
|
|
2531
|
-
const removed = await this.db.delete(ragIngestionLog).where(eq7(ragIngestionLog.collection, collection)).
|
|
2532
|
-
|
|
2533
|
-
});
|
|
2534
|
-
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;
|
|
2535
3025
|
}
|
|
2536
3026
|
/**
|
|
2537
3027
|
* The keyset sweep both {@link iterate} and {@link listDocumentIds} are made of. `page` decides
|
|
@@ -2560,7 +3050,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2560
3050
|
}
|
|
2561
3051
|
}
|
|
2562
3052
|
where(query) {
|
|
2563
|
-
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);
|
|
2564
3054
|
}
|
|
2565
3055
|
/**
|
|
2566
3056
|
* The coordinates filter AND'd with "strictly after `cursor` in
|
|
@@ -2575,7 +3065,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2575
3065
|
if (cursor === void 0) {
|
|
2576
3066
|
return base;
|
|
2577
3067
|
}
|
|
2578
|
-
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))));
|
|
2579
3069
|
}
|
|
2580
3070
|
/**
|
|
2581
3071
|
* Upsert one outcome. Keyed by document id so the row always reflects the *current* state — a
|
|
@@ -2623,14 +3113,11 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
|
|
|
2623
3113
|
size
|
|
2624
3114
|
} : {}
|
|
2625
3115
|
};
|
|
2626
|
-
await this.db.insert(ragIngestionLog).values({
|
|
3116
|
+
await upsert(this.dialect, this.db.insert(this.t.ragIngestionLog).values({
|
|
2627
3117
|
documentId,
|
|
2628
3118
|
createdAt: now,
|
|
2629
3119
|
...outcome
|
|
2630
|
-
}).
|
|
2631
|
-
target: ragIngestionLog.documentId,
|
|
2632
|
-
set: outcome
|
|
2633
|
-
});
|
|
3120
|
+
}), this.t.ragIngestionLog.documentId, outcome);
|
|
2634
3121
|
} catch (error) {
|
|
2635
3122
|
this.logger.warn(`Could not record RAG ingestion outcome for ${documentId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2636
3123
|
}
|
|
@@ -2653,18 +3140,18 @@ DrizzleRagIngestionLog = _ts_decorate([
|
|
|
2653
3140
|
// src/drizzle-agent-store.module.ts
|
|
2654
3141
|
import { AGENT_CONFIRM_TOKEN_STORE, AGENT_GOVERNANCE_QUERIES, AGENT_PRICING_STORE, AGENT_STORE } from "@dudousxd/nestjs-agent-core";
|
|
2655
3142
|
import { Module } from "@nestjs/common";
|
|
2656
|
-
function _ts_decorate2(decorators, target,
|
|
2657
|
-
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;
|
|
2658
3145
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
|
|
2659
|
-
r = Reflect.decorate(decorators, target,
|
|
3146
|
+
r = Reflect.decorate(decorators, target, key2, desc4);
|
|
2660
3147
|
} else {
|
|
2661
3148
|
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
2662
3149
|
if (d = decorators[i]) {
|
|
2663
|
-
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;
|
|
2664
3151
|
}
|
|
2665
3152
|
}
|
|
2666
3153
|
}
|
|
2667
|
-
return c > 3 && r && Object.defineProperty(target,
|
|
3154
|
+
return c > 3 && r && Object.defineProperty(target, key2, r), r;
|
|
2668
3155
|
}
|
|
2669
3156
|
__name(_ts_decorate2, "_ts_decorate");
|
|
2670
3157
|
var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
|
|
@@ -2764,17 +3251,21 @@ export {
|
|
|
2764
3251
|
DrizzleTokenStreamSink,
|
|
2765
3252
|
RAG_INGESTION_LOG_PAGE_ORDER,
|
|
2766
3253
|
agentConfirmToken,
|
|
3254
|
+
agentDialectOf,
|
|
2767
3255
|
agentMemory,
|
|
2768
3256
|
agentMessage,
|
|
2769
3257
|
agentModelPricing,
|
|
2770
3258
|
agentQueuedMessage,
|
|
2771
3259
|
agentRun,
|
|
2772
3260
|
agentSchema,
|
|
3261
|
+
agentSchemaDdl,
|
|
2773
3262
|
agentStreamFrame,
|
|
2774
3263
|
agentThread,
|
|
2775
3264
|
agentTokenUsage,
|
|
2776
3265
|
agentToolCall,
|
|
2777
3266
|
ensureAgentSchema,
|
|
3267
|
+
mysqlAgentSchema,
|
|
3268
|
+
pgAgentSchema,
|
|
2778
3269
|
ragIngestionLog
|
|
2779
3270
|
};
|
|
2780
3271
|
//# sourceMappingURL=index.js.map
|