@dudousxd/nestjs-agent-store-drizzle 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  // src/index.ts
22
22
  var index_exports = {};
23
23
  __export(index_exports, {
24
+ DrizzleActionProposalStore: () => DrizzleActionProposalStore,
24
25
  DrizzleAgentStore: () => DrizzleAgentStore,
25
26
  DrizzleAgentStoreModule: () => DrizzleAgentStoreModule,
26
27
  DrizzleConfirmTokenStore: () => DrizzleConfirmTokenStore,
@@ -31,6 +32,7 @@ __export(index_exports, {
31
32
  DrizzleStreamFrameTable: () => DrizzleStreamFrameTable,
32
33
  DrizzleTokenStreamSink: () => DrizzleTokenStreamSink,
33
34
  RAG_INGESTION_LOG_PAGE_ORDER: () => RAG_INGESTION_LOG_PAGE_ORDER,
35
+ agentActionProposal: () => agentActionProposal,
34
36
  agentConfirmToken: () => agentConfirmToken,
35
37
  agentDialectOf: () => agentDialectOf,
36
38
  agentMemory: () => agentMemory,
@@ -90,6 +92,7 @@ var agentMessage = (0, import_sqlite_core.sqliteTable)("agent_message", {
90
92
  onDelete: "cascade"
91
93
  }),
92
94
  role: (0, import_sqlite_core.text)("role").$type().notNull(),
95
+ actionProposalOutcome: (0, import_sqlite_core.text)("action_proposal_outcome"),
93
96
  content: (0, import_sqlite_core.text)("content").notNull(),
94
97
  toolCalls: (0, import_sqlite_core.text)("tool_calls", {
95
98
  mode: "json"
@@ -134,6 +137,7 @@ var agentMessage = (0, import_sqlite_core.sqliteTable)("agent_message", {
134
137
  (0, import_sqlite_core.index)("agent_message_thread_created_idx").on(table.threadId, table.createdAt)
135
138
  ]);
136
139
  var agentToolCall = (0, import_sqlite_core.sqliteTable)("agent_tool_call", {
140
+ proposalId: (0, import_sqlite_core.text)("proposal_id"),
137
141
  id: (0, import_sqlite_core.text)("id").primaryKey(),
138
142
  messageId: (0, import_sqlite_core.text)("message_id").notNull().references(() => agentMessage.id, {
139
143
  onDelete: "cascade"
@@ -158,6 +162,10 @@ var agentToolCall = (0, import_sqlite_core.sqliteTable)("agent_tool_call", {
158
162
  }),
159
163
  /** The run (turn) this call belongs to, for a trace deep-link; null for a pre-rollout row. */
160
164
  runId: (0, import_sqlite_core.text)("run_id"),
165
+ /** Resolved per-call wording; null falls back to presentation templates. */
166
+ confirmation: (0, import_sqlite_core.text)("confirmation", {
167
+ mode: "json"
168
+ }).$type(),
161
169
  /** Who had to approve it (`requester` or a role); null for a call no policy put to anyone. */
162
170
  approver: (0, import_sqlite_core.text)("approver"),
163
171
  /** When the approval request lapses; null → never. */
@@ -174,6 +182,9 @@ var agentToolCall = (0, import_sqlite_core.sqliteTable)("agent_tool_call", {
174
182
  (0, import_sqlite_core.index)("agent_tool_call_message_idx").on(table.messageId)
175
183
  ]);
176
184
  var agentQueuedMessage = (0, import_sqlite_core.sqliteTable)("agent_queued_message", {
185
+ uiCapabilities: (0, import_sqlite_core.text)("ui_capabilities", {
186
+ mode: "json"
187
+ }).$type(),
177
188
  id: (0, import_sqlite_core.text)("id").primaryKey(),
178
189
  threadId: (0, import_sqlite_core.text)("thread_id").notNull().references(() => agentThread.id, {
179
190
  onDelete: "cascade"
@@ -351,7 +362,35 @@ var agentStreamFrame = (0, import_sqlite_core.sqliteTable)("agent_stream_frame",
351
362
  ]
352
363
  })
353
364
  ]);
365
+ var agentActionProposal = (0, import_sqlite_core.sqliteTable)("agent_action_proposal", {
366
+ id: (0, import_sqlite_core.text)("id").primaryKey(),
367
+ scopeKey: (0, import_sqlite_core.text)("scope_key").notNull(),
368
+ decision: (0, import_sqlite_core.text)("decision").$type().notNull(),
369
+ logicalSort: (0, import_sqlite_core.text)("logical_sort").notNull(),
370
+ createFingerprint: (0, import_sqlite_core.text)("create_fingerprint").notNull(),
371
+ proposal: (0, import_sqlite_core.text)("proposal", {
372
+ mode: "json"
373
+ }).$type().notNull(),
374
+ version: (0, import_sqlite_core.integer)("version").notNull().default(0),
375
+ executionStatus: (0, import_sqlite_core.text)("execution_status").$type(),
376
+ leaseExpiresAt: (0, import_sqlite_core.integer)("lease_expires_at"),
377
+ deliveryStatus: (0, import_sqlite_core.text)("delivery_status"),
378
+ deliveryLeaseExpiresAt: (0, import_sqlite_core.integer)("delivery_lease_expires_at"),
379
+ replacementGroupKey: (0, import_sqlite_core.text)("replacement_group_key"),
380
+ outcomeIdKey: (0, import_sqlite_core.text)("outcome_id_key"),
381
+ proposalExpiresAt: (0, import_sqlite_core.integer)("proposal_expires_at"),
382
+ discoveryIndexVersion: (0, import_sqlite_core.integer)("discovery_index_version").notNull().default(0),
383
+ createdAt: (0, import_sqlite_core.integer)("created_at").notNull()
384
+ }, (table) => [
385
+ (0, import_sqlite_core.index)("agent_action_proposal_execution_idx").on(table.discoveryIndexVersion, table.executionStatus, table.leaseExpiresAt, table.createdAt),
386
+ (0, import_sqlite_core.index)("agent_action_proposal_expiry_idx").on(table.discoveryIndexVersion, table.decision, table.proposalExpiresAt, table.createdAt),
387
+ (0, import_sqlite_core.index)("agent_action_proposal_replacement_idx").on(table.scopeKey, table.replacementGroupKey, table.decision),
388
+ (0, import_sqlite_core.index)("agent_action_proposal_delivery_idx").on(table.deliveryStatus, table.deliveryLeaseExpiresAt, table.createdAt),
389
+ (0, import_sqlite_core.uniqueIndex)("agent_action_proposal_outcome_idx").on(table.outcomeIdKey),
390
+ (0, import_sqlite_core.index)("agent_action_proposal_scope_idx").on(table.scopeKey, table.createdAt, table.id)
391
+ ]);
354
392
  var agentSchema = {
393
+ agentActionProposal,
355
394
  agentThread,
356
395
  agentMessage,
357
396
  agentQueuedMessage,
@@ -377,6 +416,7 @@ var import_mysql_core2 = require("drizzle-orm/mysql-core");
377
416
  var import_pg_core2 = require("drizzle-orm/pg-core");
378
417
 
379
418
  // src/schema-mysql.ts
419
+ var import_nestjs_agent_core = require("@dudousxd/nestjs-agent-core");
380
420
  var import_mysql_core = require("drizzle-orm/mysql-core");
381
421
  var ts = /* @__PURE__ */ __name((name) => (0, import_mysql_core.datetime)(name, {
382
422
  mode: "date",
@@ -409,6 +449,7 @@ var agentMessage2 = (0, import_mysql_core.mysqlTable)("agent_message", {
409
449
  onDelete: "cascade"
410
450
  }),
411
451
  role: key("role").$type().notNull(),
452
+ actionProposalOutcome: (0, import_mysql_core.longtext)("action_proposal_outcome"),
412
453
  content: (0, import_mysql_core.longtext)("content").notNull(),
413
454
  toolCalls: (0, import_mysql_core.json)("tool_calls").$type(),
414
455
  toolResults: (0, import_mysql_core.json)("tool_results").$type(),
@@ -429,6 +470,7 @@ var agentMessage2 = (0, import_mysql_core.mysqlTable)("agent_message", {
429
470
  (0, import_mysql_core.index)("agent_message_thread_created_idx").on(table.threadId, table.createdAt)
430
471
  ]);
431
472
  var agentToolCall2 = (0, import_mysql_core.mysqlTable)("agent_tool_call", {
473
+ proposalId: key("proposal_id"),
432
474
  id: key("id").primaryKey(),
433
475
  messageId: key("message_id").notNull().references(() => agentMessage2.id, {
434
476
  onDelete: "cascade"
@@ -444,6 +486,7 @@ var agentToolCall2 = (0, import_mysql_core.mysqlTable)("agent_tool_call", {
444
486
  createdAt: ts("created_at").notNull(),
445
487
  executedAt: ts("executed_at"),
446
488
  runId: key("run_id"),
489
+ confirmation: (0, import_mysql_core.json)("confirmation").$type(),
447
490
  approver: key("approver"),
448
491
  expiresAt: ts("expires_at"),
449
492
  remember: (0, import_mysql_core.boolean)("remember"),
@@ -452,6 +495,7 @@ var agentToolCall2 = (0, import_mysql_core.mysqlTable)("agent_tool_call", {
452
495
  (0, import_mysql_core.index)("agent_tool_call_message_idx").on(table.messageId)
453
496
  ]);
454
497
  var agentQueuedMessage2 = (0, import_mysql_core.mysqlTable)("agent_queued_message", {
498
+ uiCapabilities: (0, import_mysql_core.json)("ui_capabilities").$type(),
455
499
  id: key("id").primaryKey(),
456
500
  threadId: key("thread_id").notNull().references(() => agentThread2.id, {
457
501
  onDelete: "cascade"
@@ -581,7 +625,52 @@ var agentStreamFrame2 = (0, import_mysql_core.mysqlTable)("agent_stream_frame",
581
625
  ]
582
626
  })
583
627
  ]);
628
+ var proposalJson = (0, import_mysql_core.customType)({
629
+ dataType: /* @__PURE__ */ __name(() => "longtext", "dataType"),
630
+ toDriver: /* @__PURE__ */ __name((value) => (0, import_nestjs_agent_core.canonicalActionProposalJson)(value), "toDriver"),
631
+ fromDriver: /* @__PURE__ */ __name((value) => JSON.parse(value), "fromDriver")
632
+ });
633
+ var agentActionProposal2 = (0, import_mysql_core.mysqlTable)("agent_action_proposal", {
634
+ id: key("id").primaryKey(),
635
+ scopeKey: key("scope_key").notNull(),
636
+ decision: key("decision").$type().notNull(),
637
+ logicalSort: (0, import_mysql_core.varchar)("logical_sort", {
638
+ length: 1020
639
+ }).notNull(),
640
+ createFingerprint: (0, import_mysql_core.longtext)("create_fingerprint").notNull(),
641
+ proposal: proposalJson("proposal").notNull(),
642
+ version: (0, import_mysql_core.bigint)("version", {
643
+ mode: "number"
644
+ }).notNull().default(0),
645
+ executionStatus: key("execution_status").$type(),
646
+ leaseExpiresAt: (0, import_mysql_core.bigint)("lease_expires_at", {
647
+ mode: "number"
648
+ }),
649
+ deliveryStatus: key("delivery_status"),
650
+ deliveryLeaseExpiresAt: (0, import_mysql_core.bigint)("delivery_lease_expires_at", {
651
+ mode: "number"
652
+ }),
653
+ replacementGroupKey: key("replacement_group_key"),
654
+ outcomeIdKey: key("outcome_id_key"),
655
+ proposalExpiresAt: (0, import_mysql_core.bigint)("proposal_expires_at", {
656
+ mode: "number"
657
+ }),
658
+ discoveryIndexVersion: (0, import_mysql_core.bigint)("discovery_index_version", {
659
+ mode: "number"
660
+ }).notNull().default(0),
661
+ createdAt: (0, import_mysql_core.bigint)("created_at", {
662
+ mode: "number"
663
+ }).notNull()
664
+ }, (table) => [
665
+ (0, import_mysql_core.index)("agent_action_proposal_execution_idx").on(table.discoveryIndexVersion, table.executionStatus, table.leaseExpiresAt, table.createdAt),
666
+ (0, import_mysql_core.index)("agent_action_proposal_expiry_idx").on(table.discoveryIndexVersion, table.decision, table.proposalExpiresAt, table.createdAt),
667
+ (0, import_mysql_core.index)("agent_action_proposal_replacement_idx").on(table.scopeKey, table.replacementGroupKey, table.decision),
668
+ (0, import_mysql_core.index)("agent_action_proposal_delivery_idx").on(table.deliveryStatus, table.deliveryLeaseExpiresAt, table.createdAt),
669
+ (0, import_mysql_core.uniqueIndex)("agent_action_proposal_outcome_idx").on(table.outcomeIdKey),
670
+ (0, import_mysql_core.index)("agent_action_proposal_scope_idx").on(table.scopeKey, table.createdAt, table.id)
671
+ ]);
584
672
  var mysqlAgentSchema = {
673
+ agentActionProposal: agentActionProposal2,
585
674
  agentThread: agentThread2,
586
675
  agentMessage: agentMessage2,
587
676
  agentQueuedMessage: agentQueuedMessage2,
@@ -596,6 +685,7 @@ var mysqlAgentSchema = {
596
685
  };
597
686
 
598
687
  // src/schema-pg.ts
688
+ var import_nestjs_agent_core2 = require("@dudousxd/nestjs-agent-core");
599
689
  var import_pg_core = require("drizzle-orm/pg-core");
600
690
  var ts2 = /* @__PURE__ */ __name((name) => (0, import_pg_core.timestamp)(name, {
601
691
  withTimezone: true,
@@ -626,6 +716,7 @@ var agentMessage3 = (0, import_pg_core.pgTable)("agent_message", {
626
716
  onDelete: "cascade"
627
717
  }),
628
718
  role: (0, import_pg_core.text)("role").$type().notNull(),
719
+ actionProposalOutcome: (0, import_pg_core.text)("action_proposal_outcome"),
629
720
  content: (0, import_pg_core.text)("content").notNull(),
630
721
  toolCalls: (0, import_pg_core.jsonb)("tool_calls").$type(),
631
722
  toolResults: (0, import_pg_core.jsonb)("tool_results").$type(),
@@ -646,6 +737,7 @@ var agentMessage3 = (0, import_pg_core.pgTable)("agent_message", {
646
737
  (0, import_pg_core.index)("agent_message_thread_created_idx").on(table.threadId, table.createdAt)
647
738
  ]);
648
739
  var agentToolCall3 = (0, import_pg_core.pgTable)("agent_tool_call", {
740
+ proposalId: (0, import_pg_core.text)("proposal_id"),
649
741
  id: (0, import_pg_core.text)("id").primaryKey(),
650
742
  messageId: (0, import_pg_core.text)("message_id").notNull().references(() => agentMessage3.id, {
651
743
  onDelete: "cascade"
@@ -661,6 +753,7 @@ var agentToolCall3 = (0, import_pg_core.pgTable)("agent_tool_call", {
661
753
  createdAt: ts2("created_at").notNull(),
662
754
  executedAt: ts2("executed_at"),
663
755
  runId: (0, import_pg_core.text)("run_id"),
756
+ confirmation: (0, import_pg_core.jsonb)("confirmation").$type(),
664
757
  approver: (0, import_pg_core.text)("approver"),
665
758
  expiresAt: ts2("expires_at"),
666
759
  remember: (0, import_pg_core.boolean)("remember"),
@@ -669,6 +762,7 @@ var agentToolCall3 = (0, import_pg_core.pgTable)("agent_tool_call", {
669
762
  (0, import_pg_core.index)("agent_tool_call_message_idx").on(table.messageId)
670
763
  ]);
671
764
  var agentQueuedMessage3 = (0, import_pg_core.pgTable)("agent_queued_message", {
765
+ uiCapabilities: (0, import_pg_core.jsonb)("ui_capabilities").$type(),
672
766
  id: (0, import_pg_core.text)("id").primaryKey(),
673
767
  threadId: (0, import_pg_core.text)("thread_id").notNull().references(() => agentThread3.id, {
674
768
  onDelete: "cascade"
@@ -798,7 +892,50 @@ var agentStreamFrame3 = (0, import_pg_core.pgTable)("agent_stream_frame", {
798
892
  ]
799
893
  })
800
894
  ]);
895
+ var proposalJson2 = (0, import_pg_core.customType)({
896
+ dataType: /* @__PURE__ */ __name(() => "text", "dataType"),
897
+ toDriver: /* @__PURE__ */ __name((value) => (0, import_nestjs_agent_core2.canonicalActionProposalJson)(value), "toDriver"),
898
+ fromDriver: /* @__PURE__ */ __name((value) => JSON.parse(value), "fromDriver")
899
+ });
900
+ var agentActionProposal3 = (0, import_pg_core.pgTable)("agent_action_proposal", {
901
+ id: (0, import_pg_core.text)("id").primaryKey(),
902
+ scopeKey: (0, import_pg_core.text)("scope_key").notNull(),
903
+ decision: (0, import_pg_core.text)("decision").$type().notNull(),
904
+ logicalSort: (0, import_pg_core.text)("logical_sort").notNull(),
905
+ createFingerprint: (0, import_pg_core.text)("create_fingerprint").notNull(),
906
+ proposal: proposalJson2("proposal").notNull(),
907
+ version: (0, import_pg_core.bigint)("version", {
908
+ mode: "number"
909
+ }).notNull().default(0),
910
+ executionStatus: (0, import_pg_core.text)("execution_status").$type(),
911
+ leaseExpiresAt: (0, import_pg_core.bigint)("lease_expires_at", {
912
+ mode: "number"
913
+ }),
914
+ deliveryStatus: (0, import_pg_core.text)("delivery_status"),
915
+ deliveryLeaseExpiresAt: (0, import_pg_core.bigint)("delivery_lease_expires_at", {
916
+ mode: "number"
917
+ }),
918
+ replacementGroupKey: (0, import_pg_core.text)("replacement_group_key"),
919
+ outcomeIdKey: (0, import_pg_core.text)("outcome_id_key"),
920
+ proposalExpiresAt: (0, import_pg_core.bigint)("proposal_expires_at", {
921
+ mode: "number"
922
+ }),
923
+ discoveryIndexVersion: (0, import_pg_core.bigint)("discovery_index_version", {
924
+ mode: "number"
925
+ }).notNull().default(0),
926
+ createdAt: (0, import_pg_core.bigint)("created_at", {
927
+ mode: "number"
928
+ }).notNull()
929
+ }, (table) => [
930
+ (0, import_pg_core.index)("agent_action_proposal_execution_idx").on(table.discoveryIndexVersion, table.executionStatus, table.leaseExpiresAt, table.createdAt),
931
+ (0, import_pg_core.index)("agent_action_proposal_expiry_idx").on(table.discoveryIndexVersion, table.decision, table.proposalExpiresAt, table.createdAt),
932
+ (0, import_pg_core.index)("agent_action_proposal_replacement_idx").on(table.scopeKey, table.replacementGroupKey, table.decision),
933
+ (0, import_pg_core.index)("agent_action_proposal_delivery_idx").on(table.deliveryStatus, table.deliveryLeaseExpiresAt, table.createdAt),
934
+ (0, import_pg_core.uniqueIndex)("agent_action_proposal_outcome_idx").on(table.outcomeIdKey),
935
+ (0, import_pg_core.index)("agent_action_proposal_scope_idx").on(table.scopeKey, table.createdAt, table.id)
936
+ ]);
801
937
  var pgAgentSchema = {
938
+ agentActionProposal: agentActionProposal3,
802
939
  agentThread: agentThread3,
803
940
  agentMessage: agentMessage3,
804
941
  agentQueuedMessage: agentQueuedMessage3,
@@ -1050,8 +1187,514 @@ async function heal(db, dialect) {
1050
1187
  __name(heal, "heal");
1051
1188
 
1052
1189
  // src/drizzle-agent-store.ts
1053
- var import_nestjs_agent_core = require("@dudousxd/nestjs-agent-core");
1190
+ var import_nestjs_agent_core4 = require("@dudousxd/nestjs-agent-core");
1191
+ var import_drizzle_orm4 = require("drizzle-orm");
1192
+
1193
+ // src/drizzle-action-proposal-store.ts
1194
+ var import_node_crypto = require("crypto");
1195
+ var import_nestjs_agent_core3 = require("@dudousxd/nestjs-agent-core");
1054
1196
  var import_drizzle_orm3 = require("drizzle-orm");
1197
+
1198
+ // src/action-proposal-transaction-mode.ts
1199
+ function actionProposalTransactionMode(kind) {
1200
+ if (kind === "BetterSQLite3Database" || kind === "BetterSQLiteTransaction") return "sync";
1201
+ if (kind !== void 0 && [
1202
+ "NodePgDatabase",
1203
+ "NodePgTransaction",
1204
+ "MySql2Database",
1205
+ "MySql2Transaction",
1206
+ "LibSQLDatabase",
1207
+ "LibSQLTransaction"
1208
+ ].includes(kind)) return "async";
1209
+ return "unsupported";
1210
+ }
1211
+ __name(actionProposalTransactionMode, "actionProposalTransactionMode");
1212
+
1213
+ // src/drizzle-action-proposal-store.ts
1214
+ var DrizzleActionProposalStore = class {
1215
+ static {
1216
+ __name(this, "DrizzleActionProposalStore");
1217
+ }
1218
+ db;
1219
+ rawDb;
1220
+ actionProposalAdmissionSupported;
1221
+ synchronousSqlite;
1222
+ dialect;
1223
+ table;
1224
+ clock;
1225
+ constructor(db, options = {}) {
1226
+ this.rawDb = db;
1227
+ const kind = db.constructor[import_drizzle_orm3.entityKind];
1228
+ const transactionMode = actionProposalTransactionMode(kind);
1229
+ this.synchronousSqlite = transactionMode === "sync";
1230
+ this.actionProposalAdmissionSupported = transactionMode !== "unsupported";
1231
+ this.dialect = agentDialectOf(db);
1232
+ this.table = agentTablesFor(this.dialect).agentActionProposal;
1233
+ this.db = asBuilder(db);
1234
+ this.clock = options.clock ?? Date.now;
1235
+ }
1236
+ async createActionProposal(input) {
1237
+ const proposal = (0, import_nestjs_agent_core3.initialActionProposal)(input, this.clock());
1238
+ const row = {
1239
+ id: physicalId(input.id),
1240
+ scopeKey: scopeKey(input),
1241
+ decision: proposal.decision,
1242
+ logicalSort: logicalSort(input.id),
1243
+ createFingerprint: (0, import_nestjs_agent_core3.canonicalActionProposalJson)(input),
1244
+ proposal,
1245
+ ...discoveryMetadata(proposal),
1246
+ version: 0,
1247
+ createdAt: proposal.createdAt
1248
+ };
1249
+ const table = this.table;
1250
+ const insert = this.db.insert(table);
1251
+ const inserted = this.dialect === "mysql" ? mysqlAffectedRows(await insert.ignore().values(row)) : await affectedRows(this.dialect, insert.values(row).onConflictDoNothing(), table.id);
1252
+ const stored = await this.read(input, input.id);
1253
+ if (!stored) return {
1254
+ status: "conflict"
1255
+ };
1256
+ if (inserted === 1) return {
1257
+ status: "created",
1258
+ proposal: stored.proposal
1259
+ };
1260
+ return {
1261
+ status: stored.createFingerprint === row.createFingerprint ? "unchanged" : "conflict",
1262
+ proposal: stored.proposal
1263
+ };
1264
+ }
1265
+ createReplacingActionProposal(input) {
1266
+ if (!input.replacementKey) return this.createActionProposal(input);
1267
+ const proposal = (0, import_nestjs_agent_core3.initialActionProposal)(input, this.clock());
1268
+ return this.transactionSteps((db) => this.replacementSteps(db, input, proposal));
1269
+ }
1270
+ async supersedeActionProposal(scope, id, command) {
1271
+ const replacement = await this.getActionProposal(scope, command.replacementProposalId);
1272
+ if (!replacement) return {
1273
+ status: "not_found"
1274
+ };
1275
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalSupersession)(row, replacement, command, now));
1276
+ }
1277
+ *replacementSteps(db, input, proposal) {
1278
+ const table = this.table;
1279
+ const thread = agentTablesFor(this.dialect).agentThread;
1280
+ if (this.dialect === "sqlite") yield {
1281
+ kind: "write",
1282
+ query: db.update(thread).set({
1283
+ updatedAt: import_drizzle_orm3.sql`${thread.updatedAt}`
1284
+ }).where((0, import_drizzle_orm3.eq)(thread.id, input.threadId))
1285
+ };
1286
+ const threads = yield {
1287
+ kind: "read",
1288
+ query: lockQuery(db.select().from(thread).where((0, import_drizzle_orm3.eq)(thread.id, input.threadId)).limit(1), this.dialect)
1289
+ };
1290
+ const owner = threads[0];
1291
+ if (!owner || owner.id !== input.threadId || owner.deletedAt || owner.actorRef !== input.actorRef || owner.tenantRef !== input.tenantRef) return {
1292
+ status: "conflict"
1293
+ };
1294
+ const existingRows = yield {
1295
+ kind: "read",
1296
+ query: db.select().from(table).where((0, import_drizzle_orm3.eq)(table.id, physicalId(input.id))).limit(1)
1297
+ };
1298
+ const existing = existingRows[0];
1299
+ if (existing) {
1300
+ if (existing.proposal.id !== input.id || !(0, import_nestjs_agent_core3.actionProposalScopeMatches)(existing.proposal, input)) return {
1301
+ status: "conflict"
1302
+ };
1303
+ return {
1304
+ status: existing.createFingerprint === (0, import_nestjs_agent_core3.canonicalActionProposalJson)(input) ? "unchanged" : "conflict",
1305
+ proposal: existing.proposal
1306
+ };
1307
+ }
1308
+ const groupKey = replacementGroupKey(input);
1309
+ if (groupKey === null) throw new Error("Missing explicit replacement identity");
1310
+ const pending = yield {
1311
+ kind: "read",
1312
+ query: lockQuery(db.select().from(table).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.scopeKey, scopeKey(input)), (0, import_drizzle_orm3.eq)(table.replacementGroupKey, groupKey), (0, import_drizzle_orm3.eq)(table.decision, "pending"))), this.dialect)
1313
+ };
1314
+ const row = {
1315
+ id: physicalId(input.id),
1316
+ scopeKey: scopeKey(input),
1317
+ decision: proposal.decision,
1318
+ logicalSort: logicalSort(input.id),
1319
+ createFingerprint: (0, import_nestjs_agent_core3.canonicalActionProposalJson)(input),
1320
+ proposal,
1321
+ ...discoveryMetadata(proposal),
1322
+ version: 0,
1323
+ createdAt: proposal.createdAt
1324
+ };
1325
+ const insert = db.insert(table);
1326
+ const inserted = yield {
1327
+ kind: "read",
1328
+ query: this.dialect === "mysql" ? insert.ignore().values(row) : insert.values(row).onConflictDoNothing().returning({
1329
+ id: table.id
1330
+ })
1331
+ };
1332
+ const count3 = this.dialect === "mysql" ? mysqlAffectedRows(inserted) : inserted.length;
1333
+ if (count3 !== 1) return {
1334
+ status: "conflict"
1335
+ };
1336
+ for (const old of pending) {
1337
+ const result = (0, import_nestjs_agent_core3.transitionActionProposalSupersession)(old.proposal, proposal, {
1338
+ replacementProposalId: proposal.id,
1339
+ actorRef: proposal.actorRef,
1340
+ via: "replacement"
1341
+ }, this.clock());
1342
+ if (!result.proposal || (0, import_nestjs_agent_core3.canonicalActionProposalJson)(result.proposal) === (0, import_nestjs_agent_core3.canonicalActionProposalJson)(old.proposal)) continue;
1343
+ const next = result.proposal;
1344
+ const update = db.update(table).set({
1345
+ proposal: next,
1346
+ decision: next.decision,
1347
+ ...discoveryMetadata(next),
1348
+ version: old.version + 1
1349
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.id, old.id), (0, import_drizzle_orm3.eq)(table.version, old.version)));
1350
+ const updated = yield {
1351
+ kind: "read",
1352
+ query: this.dialect === "mysql" ? update : update.returning({
1353
+ id: table.id
1354
+ })
1355
+ };
1356
+ if ((this.dialect === "mysql" ? mysqlAffectedRows(updated) : updated.length) !== 1) throw new Error("Replacement lost its locked proposal fence");
1357
+ }
1358
+ return {
1359
+ status: "created",
1360
+ proposal
1361
+ };
1362
+ }
1363
+ async getActionProposal(scope, id) {
1364
+ return (await this.read(scope, id))?.proposal ?? null;
1365
+ }
1366
+ async listActionProposals(scope, query = {}) {
1367
+ const limit = (0, import_nestjs_agent_core3.validateActionProposalListQuery)(query);
1368
+ const rows = await this.db.select().from(this.table).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.table.scopeKey, scopeKey(scope)), query.after === void 0 ? void 0 : (0, import_drizzle_orm3.or)((0, import_drizzle_orm3.gt)(this.table.createdAt, query.after.createdAt), (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.table.createdAt, query.after.createdAt), (0, import_drizzle_orm3.gt)(this.table.logicalSort, logicalSort(query.after.id)))), query.decision === void 0 ? void 0 : (0, import_drizzle_orm3.eq)(this.table.decision, query.decision))).orderBy((0, import_drizzle_orm3.asc)(this.table.createdAt), (0, import_drizzle_orm3.asc)(this.table.logicalSort)).limit(limit);
1369
+ return rows.map((row) => row.proposal).filter((proposal) => (0, import_nestjs_agent_core3.actionProposalScopeMatches)(proposal, scope));
1370
+ }
1371
+ decideActionProposal(scope, id, command) {
1372
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalDecision)(row, command, now));
1373
+ }
1374
+ claimActionProposal(scope, id, command) {
1375
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalClaim)(row, command, now, (0, import_node_crypto.randomUUID)()));
1376
+ }
1377
+ extendActionProposalLease(scope, id, command) {
1378
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalLease)(row, command, now));
1379
+ }
1380
+ settleActionProposal(scope, id, command) {
1381
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalSettlement)(row, command, now));
1382
+ }
1383
+ async claimNextActionProposal(command) {
1384
+ const now = this.clock();
1385
+ (0, import_nestjs_agent_core3.validateActionProposalWorkerClaim)(command, now);
1386
+ const table = this.table;
1387
+ const candidates = await this.db.select().from(table).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.discoveryIndexVersion, 1), (0, import_drizzle_orm3.eq)(table.decision, "approved"), (0, import_drizzle_orm3.or)((0, import_drizzle_orm3.eq)(table.executionStatus, "queued"), (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.executionStatus, "executing"), (0, import_drizzle_orm3.lte)(table.leaseExpiresAt, now))))).orderBy((0, import_drizzle_orm3.asc)(table.createdAt), (0, import_drizzle_orm3.asc)(table.logicalSort)).limit(32);
1388
+ for (const candidate of candidates) {
1389
+ const result = await this.claimActionProposal(candidate.proposal, candidate.proposal.id, command);
1390
+ if (result.status === "applied" && result.proposal) return result.proposal;
1391
+ }
1392
+ return null;
1393
+ }
1394
+ async expireActionProposals(command) {
1395
+ const now = this.clock();
1396
+ (0, import_nestjs_agent_core3.validateActionProposalExpiryBatch)(command, now);
1397
+ const table = this.table;
1398
+ const candidates = await this.db.select().from(table).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.discoveryIndexVersion, 1), (0, import_drizzle_orm3.eq)(table.decision, "pending"), (0, import_drizzle_orm3.lte)(table.proposalExpiresAt, now))).orderBy((0, import_drizzle_orm3.asc)(table.createdAt), (0, import_drizzle_orm3.asc)(table.logicalSort)).limit(command.limit);
1399
+ let expired = 0;
1400
+ for (const candidate of candidates) {
1401
+ const result = await this.decideActionProposal(candidate.proposal, candidate.proposal.id, {
1402
+ decision: "expired",
1403
+ actorRef: "system",
1404
+ via: "expiry"
1405
+ });
1406
+ if (result.status === "applied") expired++;
1407
+ }
1408
+ return expired;
1409
+ }
1410
+ async backfillActionProposalDiscoveryIndex(command) {
1411
+ (0, import_nestjs_agent_core3.validateActionProposalDiscoveryIndexBatch)(command);
1412
+ const table = this.table;
1413
+ const candidates = await this.db.select().from(table).where((0, import_drizzle_orm3.eq)(table.discoveryIndexVersion, 0)).orderBy((0, import_drizzle_orm3.asc)(table.createdAt), (0, import_drizzle_orm3.asc)(table.logicalSort)).limit(command.limit);
1414
+ let changed = 0;
1415
+ for (const row of candidates) {
1416
+ changed += await affectedRows(this.dialect, this.db.update(table).set({
1417
+ ...discoveryMetadata(row.proposal),
1418
+ version: row.version + 1
1419
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.id, row.id), (0, import_drizzle_orm3.eq)(table.scopeKey, row.scopeKey), (0, import_drizzle_orm3.eq)(table.version, row.version), (0, import_drizzle_orm3.eq)(table.discoveryIndexVersion, 0))), table.id);
1420
+ }
1421
+ return changed;
1422
+ }
1423
+ async rememberedActionProposalApprovals(scope) {
1424
+ const table = this.table;
1425
+ const rows = await this.db.select().from(table).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.scopeKey, scopeKey(scope)), (0, import_drizzle_orm3.eq)(table.decision, "approved"), (0, import_drizzle_orm3.or)((0, import_drizzle_orm3.eq)(table.executionStatus, "succeeded"), (0, import_drizzle_orm3.eq)(table.executionStatus, "failed"))));
1426
+ return [
1427
+ ...new Set(rows.filter((row) => (0, import_nestjs_agent_core3.actionProposalScopeMatches)(row.proposal, scope) && row.proposal.decisionAudit?.remember === true).map((row) => row.proposal.toolName))
1428
+ ];
1429
+ }
1430
+ async getThreadActionProposalScope(threadId) {
1431
+ const thread = agentTablesFor(this.dialect).agentThread;
1432
+ const [row] = await this.db.select().from(thread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(thread.id, threadId), (0, import_drizzle_orm3.isNull)(thread.deletedAt))).limit(1);
1433
+ return row?.id === threadId ? {
1434
+ actorRef: row.actorRef,
1435
+ tenantRef: row.tenantRef,
1436
+ threadId: row.id
1437
+ } : null;
1438
+ }
1439
+ async claimNextActionProposalOutcome(command) {
1440
+ const now = this.clock();
1441
+ (0, import_nestjs_agent_core3.validateActionProposalWorkerClaim)(command, now);
1442
+ const table = this.table;
1443
+ const candidates = await this.db.select().from(table).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.deliveryStatus, "pending"), (0, import_drizzle_orm3.or)((0, import_drizzle_orm3.isNull)(table.deliveryLeaseExpiresAt), (0, import_drizzle_orm3.lte)(table.deliveryLeaseExpiresAt, now)))).orderBy((0, import_drizzle_orm3.asc)(table.createdAt), (0, import_drizzle_orm3.asc)(table.logicalSort)).limit(32);
1444
+ for (const row of candidates) {
1445
+ const result = await this.mutate(row.proposal, row.proposal.id, (proposal, time) => {
1446
+ const claimed2 = (0, import_nestjs_agent_core3.claimActionProposalOutcome)(proposal, command, time, (0, import_node_crypto.randomUUID)());
1447
+ return claimed2 ? {
1448
+ status: "applied",
1449
+ proposal: claimed2
1450
+ } : {
1451
+ status: "conflict",
1452
+ proposal
1453
+ };
1454
+ });
1455
+ const claimed = result.proposal;
1456
+ if (result.status === "applied" && claimed?.outcome && claimed.outcomeDelivery?.lease) {
1457
+ return {
1458
+ outcome: claimed.outcome,
1459
+ lease: {
1460
+ outcomeId: claimed.outcome.id,
1461
+ token: claimed.outcomeDelivery.lease.token,
1462
+ generation: claimed.outcomeDelivery.generation
1463
+ }
1464
+ };
1465
+ }
1466
+ }
1467
+ return null;
1468
+ }
1469
+ async admitActionProposalOutcome(command) {
1470
+ return this.transactionSteps((db) => this.admissionSteps(db, command));
1471
+ }
1472
+ async transactionSteps(factory) {
1473
+ if (!this.actionProposalAdmissionSupported) throw new Error("Independent actions require a certified transactional Drizzle driver (better-sqlite3, node-postgres, mysql2 or libsql)");
1474
+ if (this.synchronousSqlite) {
1475
+ const database2 = this.rawDb;
1476
+ return database2.transaction((tx) => runSync(factory(asBuilder(tx))), {
1477
+ behavior: "immediate"
1478
+ });
1479
+ }
1480
+ const database = this.rawDb;
1481
+ return database.transaction(async (tx) => runAsync(factory(asBuilder(tx))));
1482
+ }
1483
+ *admissionSteps(db, command) {
1484
+ if (typeof command.outcomeId !== "string" || !command.outcomeId || typeof command.token !== "string" || !command.token || !Number.isSafeInteger(command.generation) || command.generation < 1) throw new TypeError("Invalid outcome fence");
1485
+ const table = this.table;
1486
+ const tables = agentTablesFor(this.dialect);
1487
+ if (this.dialect === "sqlite") yield {
1488
+ kind: "write",
1489
+ query: db.update(table).set({
1490
+ version: import_drizzle_orm3.sql`${table.version}`
1491
+ }).where((0, import_drizzle_orm3.eq)(table.outcomeIdKey, physicalId(command.outcomeId)))
1492
+ };
1493
+ const query = db.select().from(table).where((0, import_drizzle_orm3.eq)(table.outcomeIdKey, physicalId(command.outcomeId))).limit(1);
1494
+ const rows = yield {
1495
+ kind: "read",
1496
+ query: lockQuery(query, this.dialect)
1497
+ };
1498
+ const row = rows[0];
1499
+ if (!row || row.proposal.outcome?.id !== command.outcomeId) return {
1500
+ status: "not_found"
1501
+ };
1502
+ const proposal = row.proposal;
1503
+ const outcome = proposal.outcome;
1504
+ const delivery = proposal.outcomeDelivery;
1505
+ if (!outcome || !delivery) return {
1506
+ status: "not_found"
1507
+ };
1508
+ if (proposal.outcomeDelivery?.status === "admitted") return {
1509
+ status: "unchanged",
1510
+ ...proposal.outcomeDelivery.messageId !== void 0 ? {
1511
+ messageId: proposal.outcomeDelivery.messageId
1512
+ } : {}
1513
+ };
1514
+ if (proposal.outcomeDelivery?.status === "discarded") return {
1515
+ status: "discarded"
1516
+ };
1517
+ if (!(0, import_nestjs_agent_core3.actionProposalOutcomeFenceValid)(proposal, command, this.clock())) return {
1518
+ status: "conflict"
1519
+ };
1520
+ const threadQuery = db.select().from(tables.agentThread).where((0, import_drizzle_orm3.eq)(tables.agentThread.id, proposal.threadId)).limit(1);
1521
+ const threads = yield {
1522
+ kind: "read",
1523
+ query: lockQuery(threadQuery, this.dialect)
1524
+ };
1525
+ const thread = threads[0];
1526
+ const now = this.clock();
1527
+ if (!(0, import_nestjs_agent_core3.actionProposalOutcomeFenceValid)(proposal, command, now)) return {
1528
+ status: "conflict"
1529
+ };
1530
+ if (!thread || thread.id !== proposal.threadId || thread.deletedAt || thread.actorRef !== proposal.actorRef || thread.tenantRef !== proposal.tenantRef) {
1531
+ const discarded = {
1532
+ ...proposal,
1533
+ outcomeDelivery: {
1534
+ ...delivery,
1535
+ status: "discarded",
1536
+ lease: null
1537
+ },
1538
+ updatedAt: now
1539
+ };
1540
+ yield {
1541
+ kind: "write",
1542
+ query: db.update(table).set({
1543
+ proposal: discarded,
1544
+ ...discoveryMetadata(discarded),
1545
+ version: row.version + 1
1546
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.id, row.id), (0, import_drizzle_orm3.eq)(table.version, row.version)))
1547
+ };
1548
+ return {
1549
+ status: "discarded"
1550
+ };
1551
+ }
1552
+ if (thread.activeStreamId !== null) return {
1553
+ status: "busy"
1554
+ };
1555
+ const seqRows = yield {
1556
+ kind: "read",
1557
+ query: db.select({
1558
+ last: (0, import_drizzle_orm3.max)(tables.agentMessage.seq)
1559
+ }).from(tables.agentMessage).where((0, import_drizzle_orm3.eq)(tables.agentMessage.threadId, thread.id))
1560
+ };
1561
+ const messageId = physicalId(command.outcomeId);
1562
+ yield {
1563
+ kind: "write",
1564
+ query: db.insert(tables.agentMessage).values({
1565
+ id: messageId,
1566
+ threadId: thread.id,
1567
+ role: "assistant",
1568
+ content: (0, import_nestjs_agent_core3.actionProposalOutcomeText)(outcome),
1569
+ actionProposalOutcome: (0, import_nestjs_agent_core3.canonicalActionProposalJson)(outcome),
1570
+ ui: null,
1571
+ seq: Number(seqRows[0]?.last ?? 0) + 1,
1572
+ createdAt: new Date(now)
1573
+ })
1574
+ };
1575
+ yield {
1576
+ kind: "write",
1577
+ query: db.update(tables.agentThread).set({
1578
+ updatedAt: new Date(now)
1579
+ }).where((0, import_drizzle_orm3.eq)(tables.agentThread.id, thread.id))
1580
+ };
1581
+ const admitted = {
1582
+ ...proposal,
1583
+ outcomeDelivery: {
1584
+ ...delivery,
1585
+ status: "admitted",
1586
+ lease: null,
1587
+ messageId
1588
+ },
1589
+ updatedAt: now
1590
+ };
1591
+ const update = db.update(table).set({
1592
+ proposal: admitted,
1593
+ ...discoveryMetadata(admitted),
1594
+ version: row.version + 1
1595
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.id, row.id), (0, import_drizzle_orm3.eq)(table.version, row.version)));
1596
+ const changed = yield {
1597
+ kind: "read",
1598
+ query: this.dialect === "mysql" ? update : update.returning({
1599
+ id: table.id
1600
+ })
1601
+ };
1602
+ const count3 = this.dialect === "mysql" ? mysqlAffectedRows(changed) : changed.length;
1603
+ if (count3 !== 1) throw new Error("Outcome admission lost its locked proposal fence");
1604
+ return {
1605
+ status: "applied",
1606
+ messageId
1607
+ };
1608
+ }
1609
+ async read(scope, id) {
1610
+ const [row] = await this.db.select().from(this.table).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.table.id, physicalId(id)), (0, import_drizzle_orm3.eq)(this.table.scopeKey, scopeKey(scope)))).limit(1);
1611
+ return row && row.proposal.id === id && (0, import_nestjs_agent_core3.actionProposalScopeMatches)(row.proposal, scope) ? row : void 0;
1612
+ }
1613
+ async mutate(scope, id, transition) {
1614
+ for (let attempt = 0; attempt < 32; attempt++) {
1615
+ const row2 = await this.read(scope, id);
1616
+ if (!row2) return {
1617
+ status: "not_found"
1618
+ };
1619
+ const result = transition(row2.proposal, this.clock());
1620
+ if (!result.proposal || (0, import_nestjs_agent_core3.canonicalActionProposalJson)(result.proposal) === (0, import_nestjs_agent_core3.canonicalActionProposalJson)(row2.proposal)) return result;
1621
+ const changed = await affectedRows(this.dialect, this.db.update(this.table).set({
1622
+ proposal: result.proposal,
1623
+ decision: result.proposal.decision,
1624
+ ...discoveryMetadata(result.proposal),
1625
+ version: row2.version + 1
1626
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.table.id, physicalId(id)), (0, import_drizzle_orm3.eq)(this.table.scopeKey, scopeKey(scope)), (0, import_drizzle_orm3.eq)(this.table.version, row2.version))), this.table.id);
1627
+ if (changed === 1) return result;
1628
+ }
1629
+ const row = await this.read(scope, id);
1630
+ return row ? {
1631
+ status: "conflict",
1632
+ proposal: row.proposal
1633
+ } : {
1634
+ status: "not_found"
1635
+ };
1636
+ }
1637
+ };
1638
+ function scopeKey(scope) {
1639
+ return (0, import_node_crypto.createHash)("sha256").update((0, import_nestjs_agent_core3.canonicalActionProposalJson)([
1640
+ scope.tenantRef,
1641
+ scope.actorRef,
1642
+ scope.threadId
1643
+ ])).digest("hex");
1644
+ }
1645
+ __name(scopeKey, "scopeKey");
1646
+ function physicalId(id) {
1647
+ return (0, import_node_crypto.createHash)("sha256").update((0, import_nestjs_agent_core3.canonicalActionProposalJson)(id)).digest("hex");
1648
+ }
1649
+ __name(physicalId, "physicalId");
1650
+ function logicalSort(id) {
1651
+ let sort = "";
1652
+ for (let index4 = 0; index4 < id.length; index4++) sort += id.charCodeAt(index4).toString(16).padStart(4, "0");
1653
+ return sort;
1654
+ }
1655
+ __name(logicalSort, "logicalSort");
1656
+ function discoveryMetadata(proposal) {
1657
+ return {
1658
+ replacementGroupKey: replacementGroupKey(proposal),
1659
+ deliveryStatus: proposal.outcomeDelivery?.status ?? null,
1660
+ deliveryLeaseExpiresAt: proposal.outcomeDelivery?.lease?.expiresAt ?? null,
1661
+ outcomeIdKey: proposal.outcome ? physicalId(proposal.outcome.id) : null,
1662
+ executionStatus: proposal.execution?.status ?? null,
1663
+ leaseExpiresAt: proposal.execution?.lease?.expiresAt ?? null,
1664
+ proposalExpiresAt: proposal.expiresAt,
1665
+ discoveryIndexVersion: 1
1666
+ };
1667
+ }
1668
+ __name(discoveryMetadata, "discoveryMetadata");
1669
+ function lockQuery(query, dialect) {
1670
+ return dialect === "sqlite" ? query : query.for("update");
1671
+ }
1672
+ __name(lockQuery, "lockQuery");
1673
+ function runSync(steps) {
1674
+ let next = steps.next();
1675
+ while (!next.done) {
1676
+ const { kind, query } = next.value;
1677
+ const statement = query;
1678
+ next = steps.next(kind === "read" ? statement.all() : statement.run());
1679
+ }
1680
+ return next.value;
1681
+ }
1682
+ __name(runSync, "runSync");
1683
+ async function runAsync(steps) {
1684
+ let next = steps.next();
1685
+ while (!next.done) next = steps.next(await next.value.query);
1686
+ return next.value;
1687
+ }
1688
+ __name(runAsync, "runAsync");
1689
+ function replacementGroupKey(proposal) {
1690
+ return proposal.replacementKey ? physicalId((0, import_nestjs_agent_core3.canonicalActionProposalJson)([
1691
+ proposal.toolName,
1692
+ proposal.replacementKey
1693
+ ])) : null;
1694
+ }
1695
+ __name(replacementGroupKey, "replacementGroupKey");
1696
+
1697
+ // src/drizzle-agent-store.ts
1055
1698
  function turnMessageColumns(message) {
1056
1699
  return {
1057
1700
  id: message.id,
@@ -1072,11 +1715,61 @@ var DrizzleAgentStore = class {
1072
1715
  db;
1073
1716
  dialect;
1074
1717
  t;
1075
- constructor(db) {
1718
+ proposals;
1719
+ constructor(db, options = {}) {
1720
+ this.proposals = new DrizzleActionProposalStore(db, options);
1076
1721
  this.dialect = agentDialectOf(db);
1077
1722
  this.t = agentTablesFor(this.dialect);
1078
1723
  this.db = asBuilder(db);
1079
1724
  }
1725
+ createActionProposal(...args) {
1726
+ return this.proposals.createActionProposal(...args);
1727
+ }
1728
+ getActionProposal(...args) {
1729
+ return this.proposals.getActionProposal(...args);
1730
+ }
1731
+ listActionProposals(...args) {
1732
+ return this.proposals.listActionProposals(...args);
1733
+ }
1734
+ decideActionProposal(...args) {
1735
+ return this.proposals.decideActionProposal(...args);
1736
+ }
1737
+ claimActionProposal(...args) {
1738
+ return this.proposals.claimActionProposal(...args);
1739
+ }
1740
+ extendActionProposalLease(...args) {
1741
+ return this.proposals.extendActionProposalLease(...args);
1742
+ }
1743
+ claimNextActionProposal(...args) {
1744
+ return this.proposals.claimNextActionProposal(...args);
1745
+ }
1746
+ expireActionProposals(...args) {
1747
+ return this.proposals.expireActionProposals(...args);
1748
+ }
1749
+ backfillActionProposalDiscoveryIndex(command) {
1750
+ return this.proposals.backfillActionProposalDiscoveryIndex(command);
1751
+ }
1752
+ settleActionProposal(...args) {
1753
+ return this.proposals.settleActionProposal(...args);
1754
+ }
1755
+ createReplacingActionProposal(...args) {
1756
+ return this.proposals.createReplacingActionProposal(...args);
1757
+ }
1758
+ supersedeActionProposal(...args) {
1759
+ return this.proposals.supersedeActionProposal(...args);
1760
+ }
1761
+ get actionProposalAdmissionSupported() {
1762
+ return this.proposals.actionProposalAdmissionSupported;
1763
+ }
1764
+ getThreadActionProposalScope(threadId) {
1765
+ return this.proposals.getThreadActionProposalScope(threadId);
1766
+ }
1767
+ claimNextActionProposalOutcome(...args) {
1768
+ return this.proposals.claimNextActionProposalOutcome(...args);
1769
+ }
1770
+ admitActionProposalOutcome(...args) {
1771
+ return this.proposals.admitActionProposalOutcome(...args);
1772
+ }
1080
1773
  async createThread(input) {
1081
1774
  const now = /* @__PURE__ */ new Date();
1082
1775
  const thread = {
@@ -1098,11 +1791,11 @@ var DrizzleAgentStore = class {
1098
1791
  return this.toSummary(thread);
1099
1792
  }
1100
1793
  async getThread(threadId) {
1101
- const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
1794
+ const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
1102
1795
  if (thread === void 0) {
1103
1796
  return null;
1104
1797
  }
1105
- const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
1798
+ const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
1106
1799
  const last = messages[messages.length - 1];
1107
1800
  const approvals = await this.approvalsFor(messages.map((message) => message.id));
1108
1801
  return {
@@ -1137,14 +1830,14 @@ var DrizzleAgentStore = class {
1137
1830
  const [thread] = await this.db.select({
1138
1831
  title: this.t.agentThread.title,
1139
1832
  defaultAgent: this.t.agentThread.defaultAgent
1140
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, query.threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
1833
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, query.threadId), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
1141
1834
  if (thread === void 0) {
1142
1835
  return null;
1143
1836
  }
1144
1837
  const messages = await this.loadTurnWindow(query.threadId, query.messageLimit);
1145
1838
  const [answered] = await this.db.select({
1146
1839
  id: this.t.agentMessage.id
1147
- }).from(this.t.agentMessage).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, query.threadId), (0, import_drizzle_orm3.eq)(this.t.agentMessage.role, "assistant"))).limit(1);
1840
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, query.threadId), (0, import_drizzle_orm4.eq)(this.t.agentMessage.role, "assistant"))).limit(1);
1148
1841
  return {
1149
1842
  title: thread.title,
1150
1843
  defaultAgent: thread.defaultAgent,
@@ -1160,15 +1853,15 @@ var DrizzleAgentStore = class {
1160
1853
  if (limit !== void 0 && limit <= 0) {
1161
1854
  return [];
1162
1855
  }
1163
- const window = this.db.select(turnMessageColumns(this.t.agentMessage)).from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrderNewestFirst());
1856
+ const window = this.db.select(turnMessageColumns(this.t.agentMessage)).from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrderNewestFirst());
1164
1857
  const rows = limit === void 0 ? await window : await window.limit(limit);
1165
1858
  return rows.reverse().map((row) => this.toStoredMessage(row));
1166
1859
  }
1167
1860
  async listThreads(actorRef, limit = 50) {
1168
- const threads = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.actorRef, actorRef), (0, import_drizzle_orm3.eq)(this.t.agentThread.transient, false), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt))).orderBy((0, import_drizzle_orm3.desc)(this.t.agentThread.updatedAt)).limit(limit);
1861
+ const threads = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.actorRef, actorRef), (0, import_drizzle_orm4.eq)(this.t.agentThread.transient, false), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt))).orderBy((0, import_drizzle_orm4.desc)(this.t.agentThread.updatedAt)).limit(limit);
1169
1862
  const summaries = [];
1170
1863
  for (const thread of threads) {
1171
- const [last] = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, thread.id)).orderBy(...this.messageOrderNewestFirst()).limit(1);
1864
+ const [last] = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, thread.id)).orderBy(...this.messageOrderNewestFirst()).limit(1);
1172
1865
  summaries.push(this.toSummary(thread, last?.content));
1173
1866
  }
1174
1867
  return summaries;
@@ -1176,14 +1869,14 @@ var DrizzleAgentStore = class {
1176
1869
  async softDeleteThread(threadId) {
1177
1870
  await this.db.update(this.t.agentThread).set({
1178
1871
  deletedAt: /* @__PURE__ */ new Date()
1179
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
1872
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1180
1873
  }
1181
1874
  async forkThread(threadId, fromMessageId) {
1182
- const [source] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
1875
+ const [source] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1183
1876
  if (source === void 0) {
1184
1877
  throw new Error(`thread ${threadId} not found`);
1185
1878
  }
1186
- const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
1879
+ const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
1187
1880
  const cutoff = messages.findIndex((message) => message.id === fromMessageId);
1188
1881
  const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;
1189
1882
  const now = /* @__PURE__ */ new Date();
@@ -1226,6 +1919,7 @@ var DrizzleAgentStore = class {
1226
1919
  reasoning: message.reasoning,
1227
1920
  reasoningMs: message.reasoningMs,
1228
1921
  ui: message.ui,
1922
+ actionProposalOutcome: message.actionProposalOutcome,
1229
1923
  createdAt: message.createdAt
1230
1924
  })));
1231
1925
  }
@@ -1234,20 +1928,20 @@ var DrizzleAgentStore = class {
1234
1928
  async ownerOfThread(threadId) {
1235
1929
  const [thread] = await this.db.select({
1236
1930
  actorRef: this.t.agentThread.actorRef
1237
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
1931
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
1238
1932
  return thread?.actorRef ?? null;
1239
1933
  }
1240
1934
  async ownerOfToolCall(toolCallId) {
1241
1935
  const [row] = await this.db.select({
1242
1936
  actorRef: this.t.agentThread.actorRef
1243
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm3.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
1937
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.id, toolCallId));
1244
1938
  return row?.actorRef ?? null;
1245
1939
  }
1246
1940
  async runForToolCall(toolCallId) {
1247
1941
  const [row] = await this.db.select({
1248
1942
  runId: this.t.agentToolCall.runId,
1249
1943
  activeStreamId: this.t.agentThread.activeStreamId
1250
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm3.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
1944
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.id, toolCallId));
1251
1945
  return row?.runId ?? row?.activeStreamId ?? null;
1252
1946
  }
1253
1947
  /**
@@ -1265,14 +1959,15 @@ var DrizzleAgentStore = class {
1265
1959
  messageId: this.t.agentToolCall.messageId,
1266
1960
  status: this.t.agentToolCall.status,
1267
1961
  approver: this.t.agentToolCall.approver,
1962
+ confirmation: this.t.agentToolCall.confirmation,
1268
1963
  expiresAt: this.t.agentToolCall.expiresAt,
1269
1964
  remember: this.t.agentToolCall.remember,
1270
1965
  executedByRef: this.t.agentToolCall.executedByRef,
1271
1966
  decidedVia: this.t.agentToolCall.decidedVia,
1272
1967
  error: this.t.agentToolCall.error
1273
- }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.inArray)(this.t.agentToolCall.messageId, messageIds), (0, import_drizzle_orm3.isNotNull)(this.t.agentToolCall.approver))).orderBy((0, import_drizzle_orm3.asc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm3.asc)(this.t.agentToolCall.id));
1968
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.inArray)(this.t.agentToolCall.messageId, messageIds), (0, import_drizzle_orm4.isNotNull)(this.t.agentToolCall.approver))).orderBy((0, import_drizzle_orm4.asc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm4.asc)(this.t.agentToolCall.id));
1274
1969
  for (const row of rows) {
1275
- const approval = (0, import_nestjs_agent_core.toolCallApprovalFromRow)({
1970
+ const approval = (0, import_nestjs_agent_core4.toolCallApprovalFromRow)({
1276
1971
  ...row,
1277
1972
  toolCallId: row.id
1278
1973
  });
@@ -1289,13 +1984,20 @@ var DrizzleAgentStore = class {
1289
1984
  async rememberedApprovals(threadId) {
1290
1985
  const rows = await this.db.selectDistinct({
1291
1986
  toolName: this.t.agentToolCall.toolName
1292
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm3.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId), (0, import_drizzle_orm3.eq)(this.t.agentToolCall.remember, true)));
1293
- return rows.map((row) => row.toolName);
1987
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, threadId), (0, import_drizzle_orm4.eq)(this.t.agentToolCall.remember, true)));
1988
+ const scope = await this.getThreadActionProposalScope(threadId);
1989
+ const proposalNames = scope ? await this.proposals.rememberedActionProposalApprovals(scope) : [];
1990
+ return [
1991
+ .../* @__PURE__ */ new Set([
1992
+ ...rows.map((row) => row.toolName),
1993
+ ...proposalNames
1994
+ ])
1995
+ ];
1294
1996
  }
1295
1997
  async toolCallInput(toolCallId) {
1296
1998
  const [row] = await this.db.select({
1297
1999
  input: this.t.agentToolCall.input
1298
- }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
2000
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.id, toolCallId));
1299
2001
  return row?.input ?? null;
1300
2002
  }
1301
2003
  async toolCallApproval(toolCallId) {
@@ -1303,7 +2005,7 @@ var DrizzleAgentStore = class {
1303
2005
  status: this.t.agentToolCall.status,
1304
2006
  approver: this.t.agentToolCall.approver,
1305
2007
  expiresAt: this.t.agentToolCall.expiresAt
1306
- }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
2008
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.id, toolCallId));
1307
2009
  if (row === void 0) {
1308
2010
  return null;
1309
2011
  }
@@ -1316,26 +2018,26 @@ var DrizzleAgentStore = class {
1316
2018
  async ownerOfActiveStream(runId) {
1317
2019
  const [thread] = await this.db.select({
1318
2020
  actorRef: this.t.agentThread.actorRef
1319
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, runId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
2021
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.activeStreamId, runId), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
1320
2022
  return thread?.actorRef ?? null;
1321
2023
  }
1322
2024
  async setTitle(threadId, title) {
1323
2025
  await this.db.update(this.t.agentThread).set({
1324
2026
  title,
1325
2027
  updatedAt: /* @__PURE__ */ new Date()
1326
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2028
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1327
2029
  }
1328
2030
  async promoteThread(threadId) {
1329
2031
  await this.db.update(this.t.agentThread).set({
1330
2032
  transient: false,
1331
2033
  updatedAt: /* @__PURE__ */ new Date()
1332
- }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.eq)(this.t.agentThread.transient, true)));
2034
+ }).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm4.eq)(this.t.agentThread.transient, true)));
1333
2035
  }
1334
2036
  /** Who holds the thread's stream right now, deleted or not. */
1335
2037
  async activeHolder(threadId) {
1336
2038
  const [thread] = await this.db.select({
1337
2039
  activeStreamId: this.t.agentThread.activeStreamId
1338
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2040
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1339
2041
  return thread?.activeStreamId ?? null;
1340
2042
  }
1341
2043
  /**
@@ -1347,18 +2049,18 @@ var DrizzleAgentStore = class {
1347
2049
  messageOrder() {
1348
2050
  const message = this.t.agentMessage;
1349
2051
  return [
1350
- (0, import_drizzle_orm3.asc)(import_drizzle_orm3.sql`coalesce(${message.seq}, 0)`),
1351
- (0, import_drizzle_orm3.asc)(message.createdAt),
1352
- (0, import_drizzle_orm3.asc)(message.id)
2052
+ (0, import_drizzle_orm4.asc)(import_drizzle_orm4.sql`coalesce(${message.seq}, 0)`),
2053
+ (0, import_drizzle_orm4.asc)(message.createdAt),
2054
+ (0, import_drizzle_orm4.asc)(message.id)
1353
2055
  ];
1354
2056
  }
1355
2057
  /** {@link messageOrder}, newest first. */
1356
2058
  messageOrderNewestFirst() {
1357
2059
  const message = this.t.agentMessage;
1358
2060
  return [
1359
- (0, import_drizzle_orm3.desc)(import_drizzle_orm3.sql`coalesce(${message.seq}, 0)`),
1360
- (0, import_drizzle_orm3.desc)(message.createdAt),
1361
- (0, import_drizzle_orm3.desc)(message.id)
2061
+ (0, import_drizzle_orm4.desc)(import_drizzle_orm4.sql`coalesce(${message.seq}, 0)`),
2062
+ (0, import_drizzle_orm4.desc)(message.createdAt),
2063
+ (0, import_drizzle_orm4.desc)(message.id)
1362
2064
  ];
1363
2065
  }
1364
2066
  /**
@@ -1367,15 +2069,15 @@ var DrizzleAgentStore = class {
1367
2069
  */
1368
2070
  async nextMessageSeq(threadId) {
1369
2071
  const [row] = await this.db.select({
1370
- last: (0, import_drizzle_orm3.max)(this.t.agentMessage.seq)
1371
- }).from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId));
2072
+ last: (0, import_drizzle_orm4.max)(this.t.agentMessage.seq)
2073
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, threadId));
1372
2074
  return Number(row?.last ?? 0) + 1;
1373
2075
  }
1374
2076
  /** The run streaming the thread, or `null` — a projection of the one column. */
1375
2077
  async activeRunForThread(threadId) {
1376
2078
  const [thread] = await this.db.select({
1377
2079
  activeStreamId: this.t.agentThread.activeStreamId
1378
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
2080
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
1379
2081
  return thread?.activeStreamId ?? null;
1380
2082
  }
1381
2083
  /**
@@ -1384,15 +2086,15 @@ var DrizzleAgentStore = class {
1384
2086
  */
1385
2087
  async claimActiveStream(threadId, runId, options = {}) {
1386
2088
  const holders = [
1387
- (0, import_drizzle_orm3.isNull)(this.t.agentThread.activeStreamId),
1388
- (0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, runId),
2089
+ (0, import_drizzle_orm4.isNull)(this.t.agentThread.activeStreamId),
2090
+ (0, import_drizzle_orm4.eq)(this.t.agentThread.activeStreamId, runId),
1389
2091
  ...options.replacing !== void 0 ? [
1390
- (0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, options.replacing)
2092
+ (0, import_drizzle_orm4.eq)(this.t.agentThread.activeStreamId, options.replacing)
1391
2093
  ] : []
1392
2094
  ];
1393
2095
  const claimed = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
1394
2096
  activeStreamId: runId
1395
- }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.or)(...holders))), this.t.agentThread.id);
2097
+ }).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm4.or)(...holders))), this.t.agentThread.id);
1396
2098
  if (claimed > 0) {
1397
2099
  return true;
1398
2100
  }
@@ -1401,21 +2103,22 @@ var DrizzleAgentStore = class {
1401
2103
  async releaseActiveStream(threadId, runId) {
1402
2104
  const released = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
1403
2105
  activeStreamId: null
1404
- }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, runId))), this.t.agentThread.id);
2106
+ }).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm4.eq)(this.t.agentThread.activeStreamId, runId))), this.t.agentThread.id);
1405
2107
  return released > 0;
1406
2108
  }
1407
2109
  async enqueueMessage(input) {
1408
2110
  const now = /* @__PURE__ */ new Date();
1409
2111
  const [edge] = await this.db.select({
1410
- first: (0, import_drizzle_orm3.min)(this.t.agentQueuedMessage.position),
1411
- last: (0, import_drizzle_orm3.max)(this.t.agentQueuedMessage.position)
1412
- }).from(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.threadId, input.threadId));
2112
+ first: (0, import_drizzle_orm4.min)(this.t.agentQueuedMessage.position),
2113
+ last: (0, import_drizzle_orm4.max)(this.t.agentQueuedMessage.position)
2114
+ }).from(this.t.agentQueuedMessage).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.threadId, input.threadId));
1413
2115
  const position = input.at === "head" ? (edge?.first ?? 1) - 1 : (edge?.last ?? -1) + 1;
1414
2116
  const row = {
1415
2117
  id: crypto.randomUUID(),
1416
2118
  threadId: input.threadId,
1417
2119
  actor: input.actor,
1418
2120
  content: input.content,
2121
+ uiCapabilities: input.uiCapabilities ?? null,
1419
2122
  attachments: input.attachments !== void 0 && input.attachments.length > 0 ? input.attachments : null,
1420
2123
  agentName: input.agentName ?? null,
1421
2124
  persona: input.persona ?? null,
@@ -1430,11 +2133,11 @@ var DrizzleAgentStore = class {
1430
2133
  return toQueuedMessage(row);
1431
2134
  }
1432
2135
  async listQueue(threadId) {
1433
- const rows = await this.db.select().from(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.threadId, threadId)).orderBy((0, import_drizzle_orm3.asc)(this.t.agentQueuedMessage.position), (0, import_drizzle_orm3.asc)(this.t.agentQueuedMessage.createdAt));
2136
+ const rows = await this.db.select().from(this.t.agentQueuedMessage).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.threadId, threadId)).orderBy((0, import_drizzle_orm4.asc)(this.t.agentQueuedMessage.position), (0, import_drizzle_orm4.asc)(this.t.agentQueuedMessage.createdAt));
1434
2137
  return rows.map(toQueuedMessage);
1435
2138
  }
1436
2139
  async getQueuedMessage(id) {
1437
- const [row] = await this.db.select().from(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, id));
2140
+ const [row] = await this.db.select().from(this.t.agentQueuedMessage).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.id, id));
1438
2141
  return row === void 0 ? null : toQueuedMessage(row);
1439
2142
  }
1440
2143
  async updateQueuedMessage(id, patch) {
@@ -1450,7 +2153,7 @@ var DrizzleAgentStore = class {
1450
2153
  if (patch.interrupt !== void 0) {
1451
2154
  updates.interrupt = patch.interrupt;
1452
2155
  }
1453
- await this.db.update(this.t.agentQueuedMessage).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, id));
2156
+ await this.db.update(this.t.agentQueuedMessage).set(updates).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.id, id));
1454
2157
  return this.getQueuedMessage(id);
1455
2158
  }
1456
2159
  /** Rewrites the thread's positions as 0..n-1 in the new order — a queue is a handful of rows. */
@@ -1465,32 +2168,32 @@ var DrizzleAgentStore = class {
1465
2168
  for (const [position, message] of order.entries()) {
1466
2169
  await this.db.update(this.t.agentQueuedMessage).set({
1467
2170
  position
1468
- }).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, message.id));
2171
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.id, message.id));
1469
2172
  }
1470
2173
  return true;
1471
2174
  }
1472
2175
  async removeQueuedMessage(id) {
1473
- const removed = await affectedRows(this.dialect, this.db.delete(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, id)), this.t.agentQueuedMessage.id);
2176
+ const removed = await affectedRows(this.dialect, this.db.delete(this.t.agentQueuedMessage).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.id, id)), this.t.agentQueuedMessage.id);
1474
2177
  return removed > 0;
1475
2178
  }
1476
2179
  async clearQueue(threadId) {
1477
- return affectedRows(this.dialect, this.db.delete(this.t.agentQueuedMessage).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.threadId, threadId)), this.t.agentQueuedMessage.id);
2180
+ return affectedRows(this.dialect, this.db.delete(this.t.agentQueuedMessage).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.threadId, threadId)), this.t.agentQueuedMessage.id);
1478
2181
  }
1479
2182
  async queuePause(threadId) {
1480
2183
  const [thread] = await this.db.select({
1481
2184
  queuePause: this.t.agentThread.queuePause
1482
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2185
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1483
2186
  return thread?.queuePause ?? null;
1484
2187
  }
1485
2188
  async setQueuePause(threadId, pause) {
1486
2189
  await this.db.update(this.t.agentThread).set({
1487
2190
  queuePause: pause
1488
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2191
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1489
2192
  }
1490
2193
  async setActiveStream(threadId, runId) {
1491
2194
  await this.db.update(this.t.agentThread).set({
1492
2195
  activeStreamId: runId
1493
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2196
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1494
2197
  }
1495
2198
  /**
1496
2199
  * Patch a thread's `title` and/or `defaultAgent`. Each field is only touched when PRESENT in
@@ -1516,7 +2219,7 @@ var DrizzleAgentStore = class {
1516
2219
  return;
1517
2220
  }
1518
2221
  updates.updatedAt = /* @__PURE__ */ new Date();
1519
- await this.db.update(this.t.agentThread).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2222
+ await this.db.update(this.t.agentThread).set(updates).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1520
2223
  }
1521
2224
  /**
1522
2225
  * The thread's default agent, projected — the caller wants one nullable scalar to decide which
@@ -1527,20 +2230,20 @@ var DrizzleAgentStore = class {
1527
2230
  async modelForThread(threadId) {
1528
2231
  const [thread] = await this.db.select({
1529
2232
  model: this.t.agentThread.model
1530
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
2233
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
1531
2234
  return thread?.model ?? null;
1532
2235
  }
1533
2236
  /** The thread's pinned persona, projected like {@link defaultAgentForThread}. */
1534
2237
  async personaForThread(threadId) {
1535
2238
  const [thread] = await this.db.select({
1536
2239
  persona: this.t.agentThread.persona
1537
- }).from(agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
2240
+ }).from(agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
1538
2241
  return thread?.persona ?? null;
1539
2242
  }
1540
2243
  async defaultAgentForThread(threadId) {
1541
2244
  const [thread] = await this.db.select({
1542
2245
  defaultAgent: this.t.agentThread.defaultAgent
1543
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm3.isNull)(this.t.agentThread.deletedAt)));
2246
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
1544
2247
  return thread?.defaultAgent ?? null;
1545
2248
  }
1546
2249
  /**
@@ -1582,16 +2285,16 @@ var DrizzleAgentStore = class {
1582
2285
  if (end.errorMessage !== void 0) {
1583
2286
  updates.errorMessage = end.errorMessage;
1584
2287
  }
1585
- await this.db.update(this.t.agentRun).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentRun.id, end.runId));
2288
+ await this.db.update(this.t.agentRun).set(updates).where((0, import_drizzle_orm4.eq)(this.t.agentRun.id, end.runId));
1586
2289
  }
1587
2290
  /** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */
1588
2291
  async bumpRunRetries(runId) {
1589
2292
  await this.db.update(this.t.agentRun).set({
1590
- retries: import_drizzle_orm3.sql`${this.t.agentRun.retries} + 1`
1591
- }).where((0, import_drizzle_orm3.eq)(this.t.agentRun.id, runId));
2293
+ retries: import_drizzle_orm4.sql`${this.t.agentRun.retries} + 1`
2294
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentRun.id, runId));
1592
2295
  }
1593
2296
  async appendMessage(input) {
1594
- const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, input.threadId));
2297
+ const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, input.threadId));
1595
2298
  if (thread === void 0) {
1596
2299
  throw new Error(`thread ${input.threadId} not found`);
1597
2300
  }
@@ -1601,6 +2304,7 @@ var DrizzleAgentStore = class {
1601
2304
  threadId: input.threadId,
1602
2305
  role: input.role,
1603
2306
  content: input.content,
2307
+ actionProposalOutcome: input.actionProposalOutcome ? (0, import_nestjs_agent_core4.canonicalActionProposalJson)(input.actionProposalOutcome) : null,
1604
2308
  toolCalls: input.toolCalls ?? null,
1605
2309
  toolResults: input.toolResults ?? null,
1606
2310
  attachments: input.attachments ?? null,
@@ -1619,43 +2323,44 @@ var DrizzleAgentStore = class {
1619
2323
  await this.db.insert(this.t.agentMessage).values(message);
1620
2324
  await this.db.update(this.t.agentThread).set({
1621
2325
  updatedAt: now
1622
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, input.threadId));
2326
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, input.threadId));
1623
2327
  return this.toStoredMessage(message);
1624
2328
  }
1625
2329
  async setMessageToolResults(messageId, results) {
1626
2330
  await this.db.update(this.t.agentMessage).set({
1627
2331
  toolResults: results
1628
- }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
2332
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.id, messageId));
1629
2333
  }
1630
2334
  async setMessageUi(messageId, ui) {
1631
2335
  await this.db.update(this.t.agentMessage).set({
1632
2336
  ui: ui.length > 0 ? ui : null
1633
- }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
2337
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.id, messageId));
1634
2338
  }
1635
2339
  async threadOfMessage(messageId) {
1636
2340
  const [row] = await this.db.select({
1637
2341
  threadId: this.t.agentMessage.threadId
1638
- }).from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId)).limit(1);
2342
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.id, messageId)).limit(1);
1639
2343
  return row?.threadId ?? null;
1640
2344
  }
1641
2345
  async setMessageFeedback(messageId, feedback) {
1642
2346
  await this.db.update(this.t.agentMessage).set({
1643
2347
  feedback
1644
- }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
2348
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.id, messageId));
1645
2349
  }
1646
2350
  async truncateFrom(threadId, messageId) {
1647
- const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
2351
+ const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, threadId)).orderBy(...this.messageOrder());
1648
2352
  const cutoff = messages.findIndex((message) => message.id === messageId);
1649
2353
  if (cutoff < 0) {
1650
2354
  return;
1651
2355
  }
1652
2356
  const doomedIds = messages.slice(cutoff).map((message) => message.id);
1653
- await this.db.delete(this.t.agentToolCall).where((0, import_drizzle_orm3.inArray)(this.t.agentToolCall.messageId, doomedIds));
1654
- await this.db.delete(this.t.agentMessage).where((0, import_drizzle_orm3.inArray)(this.t.agentMessage.id, doomedIds));
2357
+ await this.db.delete(this.t.agentToolCall).where((0, import_drizzle_orm4.inArray)(this.t.agentToolCall.messageId, doomedIds));
2358
+ await this.db.delete(this.t.agentMessage).where((0, import_drizzle_orm4.inArray)(this.t.agentMessage.id, doomedIds));
1655
2359
  }
1656
2360
  async recordToolCall(input) {
1657
2361
  await this.db.insert(this.t.agentToolCall).values({
1658
2362
  id: input.toolCallId,
2363
+ proposalId: input.proposalId ?? null,
1659
2364
  messageId: input.messageId,
1660
2365
  toolName: input.toolName,
1661
2366
  toolType: input.toolType,
@@ -1669,6 +2374,7 @@ var DrizzleAgentStore = class {
1669
2374
  executedAt: null,
1670
2375
  runId: input.runId ?? null,
1671
2376
  approver: input.approver ?? null,
2377
+ confirmation: input.confirmation ?? null,
1672
2378
  expiresAt: input.expiresAt !== void 0 ? new Date(input.expiresAt) : null,
1673
2379
  remember: null,
1674
2380
  decidedVia: null
@@ -1699,7 +2405,7 @@ var DrizzleAgentStore = class {
1699
2405
  if (input.status === "executed" || input.status === "auto_executed") {
1700
2406
  updates.executedAt = /* @__PURE__ */ new Date();
1701
2407
  }
1702
- await this.db.update(this.t.agentToolCall).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, input.toolCallId));
2408
+ await this.db.update(this.t.agentToolCall).set(updates).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.id, input.toolCallId));
1703
2409
  }
1704
2410
  async toolCallOutcomes(toolCallIds) {
1705
2411
  if (toolCallIds.length === 0) {
@@ -1710,7 +2416,7 @@ var DrizzleAgentStore = class {
1710
2416
  status: this.t.agentToolCall.status,
1711
2417
  output: this.t.agentToolCall.output,
1712
2418
  error: this.t.agentToolCall.error
1713
- }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.inArray)(this.t.agentToolCall.id, [
2419
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm4.inArray)(this.t.agentToolCall.id, [
1714
2420
  ...toolCallIds
1715
2421
  ]));
1716
2422
  return rows.map((row) => ({
@@ -1725,7 +2431,7 @@ var DrizzleAgentStore = class {
1725
2431
  }));
1726
2432
  }
1727
2433
  async failUnsettledToolCalls(runId, error) {
1728
- const pending = (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentToolCall.runId, runId), (0, import_drizzle_orm3.eq)(this.t.agentToolCall.status, "pending_approval"));
2434
+ const pending = (0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentToolCall.runId, runId), (0, import_drizzle_orm4.eq)(this.t.agentToolCall.status, "pending_approval"));
1729
2435
  const rows = await this.db.select({
1730
2436
  id: this.t.agentToolCall.id
1731
2437
  }).from(this.t.agentToolCall).where(pending);
@@ -1758,10 +2464,10 @@ var DrizzleAgentStore = class {
1758
2464
  }
1759
2465
  const rows = await this.db.select({
1760
2466
  attachments: this.t.agentMessage.attachments
1761
- }).from(this.t.agentMessage).innerJoin(this.t.agentThread, (0, import_drizzle_orm3.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.actorRef, actorRef), (0, import_drizzle_orm3.isNotNull)(this.t.agentMessage.attachments)));
2467
+ }).from(this.t.agentMessage).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.actorRef, actorRef), (0, import_drizzle_orm4.isNotNull)(this.t.agentMessage.attachments)));
1762
2468
  const queued = await this.db.select({
1763
2469
  attachments: this.t.agentQueuedMessage.attachments
1764
- }).from(this.t.agentQueuedMessage).innerJoin(this.t.agentThread, (0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentThread.actorRef, actorRef), (0, import_drizzle_orm3.isNotNull)(this.t.agentQueuedMessage.attachments)));
2470
+ }).from(this.t.agentQueuedMessage).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentThread.actorRef, actorRef), (0, import_drizzle_orm4.isNotNull)(this.t.agentQueuedMessage.attachments)));
1765
2471
  const wanted = new Set(mediaIds);
1766
2472
  const found = /* @__PURE__ */ new Set();
1767
2473
  for (const row of [
@@ -1800,7 +2506,7 @@ var DrizzleAgentStore = class {
1800
2506
  async usageBetween(actorRef, fromDay, toDay) {
1801
2507
  const start = /* @__PURE__ */ new Date(`${fromDay}T00:00:00.000Z`);
1802
2508
  const end = /* @__PURE__ */ new Date(`${toDay}T23:59:59.999Z`);
1803
- const rows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.agentTokenUsage.actorRef, actorRef), (0, import_drizzle_orm3.gte)(this.t.agentTokenUsage.createdAt, start), (0, import_drizzle_orm3.lte)(this.t.agentTokenUsage.createdAt, end)));
2509
+ const rows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentTokenUsage.actorRef, actorRef), (0, import_drizzle_orm4.gte)(this.t.agentTokenUsage.createdAt, start), (0, import_drizzle_orm4.lte)(this.t.agentTokenUsage.createdAt, end)));
1804
2510
  const usedTokens = rows.reduce((sum2, row) => sum2 + row.inputTokens + row.outputTokens, 0);
1805
2511
  const costUsd = rows.reduce((sum2, row) => sum2 + (row.costUsd ?? 0), 0);
1806
2512
  return {
@@ -1826,7 +2532,12 @@ var DrizzleAgentStore = class {
1826
2532
  };
1827
2533
  }
1828
2534
  toStoredMessage(message) {
2535
+ const outcome = message.actionProposalOutcome ? JSON.parse(message.actionProposalOutcome) : void 0;
1829
2536
  return {
2537
+ ...outcome ? {
2538
+ actionProposalOutcome: outcome,
2539
+ ui: outcome.ui
2540
+ } : {},
1830
2541
  id: message.id,
1831
2542
  role: message.role,
1832
2543
  content: message.content,
@@ -1872,6 +2583,9 @@ var DrizzleAgentStore = class {
1872
2583
  };
1873
2584
  function toQueuedMessage(row) {
1874
2585
  return {
2586
+ ...row.uiCapabilities !== null ? {
2587
+ uiCapabilities: row.uiCapabilities
2588
+ } : {},
1875
2589
  id: row.id,
1876
2590
  threadId: row.threadId,
1877
2591
  actor: row.actor,
@@ -1901,8 +2615,8 @@ function toQueuedMessage(row) {
1901
2615
  __name(toQueuedMessage, "toQueuedMessage");
1902
2616
 
1903
2617
  // src/drizzle-governance-queries.ts
1904
- var import_nestjs_agent_core2 = require("@dudousxd/nestjs-agent-core");
1905
- var import_drizzle_orm4 = require("drizzle-orm");
2618
+ var import_nestjs_agent_core5 = require("@dudousxd/nestjs-agent-core");
2619
+ var import_drizzle_orm5 = require("drizzle-orm");
1906
2620
  var UNCLASSIFIED_ERROR_CODE = "unknown";
1907
2621
  var DEFAULT_AGENT_BUCKET = "(default)";
1908
2622
  var TOOL_CALL_STATUSES = [
@@ -1937,14 +2651,14 @@ function isRunStatus(value) {
1937
2651
  }
1938
2652
  __name(isRunStatus, "isRunStatus");
1939
2653
  function dayStartUtc(day) {
1940
- return (0, import_nestjs_agent_core2.dayBoundsUtc)({
2654
+ return (0, import_nestjs_agent_core5.dayBoundsUtc)({
1941
2655
  fromDay: day,
1942
2656
  toDay: day
1943
2657
  }).start;
1944
2658
  }
1945
2659
  __name(dayStartUtc, "dayStartUtc");
1946
2660
  function dayEndUtc(day) {
1947
- return (0, import_nestjs_agent_core2.dayBoundsUtc)({
2661
+ return (0, import_nestjs_agent_core5.dayBoundsUtc)({
1948
2662
  fromDay: day,
1949
2663
  toDay: day
1950
2664
  }).end;
@@ -2039,17 +2753,17 @@ var DrizzleGovernanceQueries = class {
2039
2753
  return pricing;
2040
2754
  }
2041
2755
  async usageInRange(range) {
2042
- const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
2043
- const rows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.gte)(this.t.agentTokenUsage.createdAt, start), (0, import_drizzle_orm4.lte)(this.t.agentTokenUsage.createdAt, end)));
2756
+ const { start, end } = (0, import_nestjs_agent_core5.dayBoundsUtc)(range);
2757
+ const rows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.gte)(this.t.agentTokenUsage.createdAt, start), (0, import_drizzle_orm5.lte)(this.t.agentTokenUsage.createdAt, end)));
2044
2758
  return rows.map(toUsageInput);
2045
2759
  }
2046
2760
  async spendByModel(range) {
2047
2761
  const pricing = await this.loadPricing();
2048
- return (0, import_nestjs_agent_core2.bucketByModel)(await this.usageInRange(range), pricing);
2762
+ return (0, import_nestjs_agent_core5.bucketByModel)(await this.usageInRange(range), pricing);
2049
2763
  }
2050
2764
  async spendByActor(range) {
2051
2765
  const pricing = await this.loadPricing();
2052
- return (0, import_nestjs_agent_core2.bucketByActor)(await this.usageInRange(range), pricing);
2766
+ return (0, import_nestjs_agent_core5.bucketByActor)(await this.usageInRange(range), pricing);
2053
2767
  }
2054
2768
  /**
2055
2769
  * Top threads by spend within the range, highest cost first, capped at `limit`. Usage rows for a
@@ -2065,7 +2779,7 @@ var DrizzleGovernanceQueries = class {
2065
2779
  if (threadIds.length === 0) {
2066
2780
  return [];
2067
2781
  }
2068
- const threads = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.inArray)(this.t.agentThread.id, threadIds), (0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)));
2782
+ const threads = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.inArray)(this.t.agentThread.id, threadIds), (0, import_drizzle_orm5.isNull)(this.t.agentThread.deletedAt)));
2069
2783
  const threadsById = new Map(threads.map((thread) => [
2070
2784
  thread.id,
2071
2785
  {
@@ -2073,14 +2787,14 @@ var DrizzleGovernanceQueries = class {
2073
2787
  actorRef: thread.actorRef
2074
2788
  }
2075
2789
  ]));
2076
- return (0, import_nestjs_agent_core2.bucketByThread)(rows, pricing, threadsById, {
2790
+ return (0, import_nestjs_agent_core5.bucketByThread)(rows, pricing, threadsById, {
2077
2791
  limit,
2078
2792
  includeUnknownThreads: false
2079
2793
  });
2080
2794
  }
2081
2795
  async usageTrend(range) {
2082
2796
  const pricing = await this.loadPricing();
2083
- return (0, import_nestjs_agent_core2.bucketUsageTrend)(await this.usageInRange(range), pricing);
2797
+ return (0, import_nestjs_agent_core5.bucketUsageTrend)(await this.usageInRange(range), pricing);
2084
2798
  }
2085
2799
  async recentToolCalls(limit) {
2086
2800
  const rows = await this.db.select({
@@ -2091,7 +2805,7 @@ var DrizzleGovernanceQueries = class {
2091
2805
  threadId: this.t.agentMessage.threadId,
2092
2806
  createdAt: this.t.agentToolCall.createdAt,
2093
2807
  runId: this.t.agentToolCall.runId
2094
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).orderBy((0, import_drizzle_orm4.desc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm4.desc)(this.t.agentToolCall.id)).limit(limit);
2808
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm5.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).orderBy((0, import_drizzle_orm5.desc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm5.desc)(this.t.agentToolCall.id)).limit(limit);
2095
2809
  return rows.map((row) => ({
2096
2810
  toolCallId: row.toolCallId,
2097
2811
  toolName: row.toolName,
@@ -2120,8 +2834,8 @@ var DrizzleGovernanceQueries = class {
2120
2834
  }
2121
2835
  const messageCounts = await this.db.select({
2122
2836
  threadId: this.t.agentMessage.threadId,
2123
- value: (0, import_drizzle_orm4.count)()
2124
- }).from(this.t.agentMessage).where((0, import_drizzle_orm4.inArray)(this.t.agentMessage.threadId, threadIds)).groupBy(this.t.agentMessage.threadId);
2837
+ value: (0, import_drizzle_orm5.count)()
2838
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm5.inArray)(this.t.agentMessage.threadId, threadIds)).groupBy(this.t.agentMessage.threadId);
2125
2839
  for (const row of messageCounts) {
2126
2840
  const bucket = rollups.get(row.threadId);
2127
2841
  if (bucket !== void 0) {
@@ -2130,9 +2844,9 @@ var DrizzleGovernanceQueries = class {
2130
2844
  }
2131
2845
  const usageTotals = await this.db.select({
2132
2846
  threadId: this.t.agentTokenUsage.threadId,
2133
- inputTokens: (0, import_drizzle_orm4.sum)(this.t.agentTokenUsage.inputTokens),
2134
- outputTokens: (0, import_drizzle_orm4.sum)(this.t.agentTokenUsage.outputTokens)
2135
- }).from(this.t.agentTokenUsage).where((0, import_drizzle_orm4.inArray)(this.t.agentTokenUsage.threadId, threadIds)).groupBy(this.t.agentTokenUsage.threadId);
2847
+ inputTokens: (0, import_drizzle_orm5.sum)(this.t.agentTokenUsage.inputTokens),
2848
+ outputTokens: (0, import_drizzle_orm5.sum)(this.t.agentTokenUsage.outputTokens)
2849
+ }).from(this.t.agentTokenUsage).where((0, import_drizzle_orm5.inArray)(this.t.agentTokenUsage.threadId, threadIds)).groupBy(this.t.agentTokenUsage.threadId);
2136
2850
  for (const row of usageTotals) {
2137
2851
  const bucket = rollups.get(row.threadId);
2138
2852
  if (bucket !== void 0) {
@@ -2157,12 +2871,12 @@ var DrizzleGovernanceQueries = class {
2157
2871
  });
2158
2872
  }
2159
2873
  async recentThreads(limit) {
2160
- const threads = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt)).orderBy((0, import_drizzle_orm4.desc)(this.t.agentThread.updatedAt), (0, import_drizzle_orm4.desc)(this.t.agentThread.id)).limit(limit);
2874
+ const threads = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm5.isNull)(this.t.agentThread.deletedAt)).orderBy((0, import_drizzle_orm5.desc)(this.t.agentThread.updatedAt), (0, import_drizzle_orm5.desc)(this.t.agentThread.id)).limit(limit);
2161
2875
  return this.toThreadActivityRows(threads);
2162
2876
  }
2163
2877
  async runsInRange(range) {
2164
- const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
2165
- return this.db.select().from(this.t.agentRun).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.gte)(this.t.agentRun.startedAt, start), (0, import_drizzle_orm4.lte)(this.t.agentRun.startedAt, end)));
2878
+ const { start, end } = (0, import_nestjs_agent_core5.dayBoundsUtc)(range);
2879
+ return this.db.select().from(this.t.agentRun).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.gte)(this.t.agentRun.startedAt, start), (0, import_drizzle_orm5.lte)(this.t.agentRun.startedAt, end)));
2166
2880
  }
2167
2881
  async runMetrics(range) {
2168
2882
  const runs = await this.runsInRange(range);
@@ -2218,8 +2932,8 @@ var DrizzleGovernanceQueries = class {
2218
2932
  return result;
2219
2933
  }
2220
2934
  async runErrors(range) {
2221
- const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
2222
- const runs = await this.db.select().from(this.t.agentRun).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.gte)(this.t.agentRun.startedAt, start), (0, import_drizzle_orm4.lte)(this.t.agentRun.startedAt, end), (0, import_drizzle_orm4.eq)(this.t.agentRun.status, "failed")));
2935
+ const { start, end } = (0, import_nestjs_agent_core5.dayBoundsUtc)(range);
2936
+ const runs = await this.db.select().from(this.t.agentRun).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.gte)(this.t.agentRun.startedAt, start), (0, import_drizzle_orm5.lte)(this.t.agentRun.startedAt, end), (0, import_drizzle_orm5.eq)(this.t.agentRun.status, "failed")));
2223
2937
  const byError = /* @__PURE__ */ new Map();
2224
2938
  for (const run of runs) {
2225
2939
  const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;
@@ -2259,7 +2973,7 @@ var DrizzleGovernanceQueries = class {
2259
2973
  return result;
2260
2974
  }
2261
2975
  async recentRuns(limit) {
2262
- const runs = await this.db.select().from(this.t.agentRun).orderBy((0, import_drizzle_orm4.desc)(this.t.agentRun.startedAt), (0, import_drizzle_orm4.desc)(this.t.agentRun.id)).limit(limit);
2976
+ const runs = await this.db.select().from(this.t.agentRun).orderBy((0, import_drizzle_orm5.desc)(this.t.agentRun.startedAt), (0, import_drizzle_orm5.desc)(this.t.agentRun.id)).limit(limit);
2263
2977
  return runs.map(toRecentRunRow);
2264
2978
  }
2265
2979
  /**
@@ -2278,7 +2992,7 @@ var DrizzleGovernanceQueries = class {
2278
2992
  agentName: this.t.agentMessage.agentName,
2279
2993
  requestedAt: this.t.agentToolCall.createdAt,
2280
2994
  runId: this.t.agentToolCall.runId
2281
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.status, "pending_approval")).orderBy(this.t.agentToolCall.createdAt, this.t.agentToolCall.id).limit(limit);
2995
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm5.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm5.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm5.eq)(this.t.agentToolCall.status, "pending_approval")).orderBy(this.t.agentToolCall.createdAt, this.t.agentToolCall.id).limit(limit);
2282
2996
  return rows.map((row) => ({
2283
2997
  toolCallId: row.toolCallId,
2284
2998
  toolName: row.toolName,
@@ -2299,8 +3013,8 @@ var DrizzleGovernanceQueries = class {
2299
3013
  * `PERCENTILE_CONT` and one portable implementation beats three dialect-specific ones.
2300
3014
  */
2301
3015
  async toolStats(range) {
2302
- const { start, end } = (0, import_nestjs_agent_core2.dayBoundsUtc)(range);
2303
- const calls = await this.db.select().from(this.t.agentToolCall).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.gte)(this.t.agentToolCall.createdAt, start), (0, import_drizzle_orm4.lte)(this.t.agentToolCall.createdAt, end)));
3016
+ const { start, end } = (0, import_nestjs_agent_core5.dayBoundsUtc)(range);
3017
+ const calls = await this.db.select().from(this.t.agentToolCall).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.gte)(this.t.agentToolCall.createdAt, start), (0, import_drizzle_orm5.lte)(this.t.agentToolCall.createdAt, end)));
2304
3018
  const byTool = /* @__PURE__ */ new Map();
2305
3019
  for (const call of calls) {
2306
3020
  const key2 = `${call.toolName} ${call.toolType}`;
@@ -2350,10 +3064,10 @@ var DrizzleGovernanceQueries = class {
2350
3064
  if (filters?.toolType !== void 0 && !isToolKind(filters.toolType)) {
2351
3065
  return emptyPage(query);
2352
3066
  }
2353
- const whereClause = (0, import_drizzle_orm4.and)(filters?.toolName !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.toolType !== void 0 && isToolKind(filters.toolType) ? (0, import_drizzle_orm4.eq)(this.t.agentToolCall.toolType, filters.toolType) : void 0, filters?.status !== void 0 && isToolCallStatus(filters.status) ? (0, import_drizzle_orm4.eq)(this.t.agentToolCall.status, filters.status) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm4.gte)(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm4.lte)(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
3067
+ const whereClause = (0, import_drizzle_orm5.and)(filters?.toolName !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.toolType !== void 0 && isToolKind(filters.toolType) ? (0, import_drizzle_orm5.eq)(this.t.agentToolCall.toolType, filters.toolType) : void 0, filters?.status !== void 0 && isToolCallStatus(filters.status) ? (0, import_drizzle_orm5.eq)(this.t.agentToolCall.status, filters.status) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentMessage.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm5.gte)(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm5.lte)(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
2354
3068
  const [totalRow] = await this.db.select({
2355
- value: (0, import_drizzle_orm4.count)()
2356
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause);
3069
+ value: (0, import_drizzle_orm5.count)()
3070
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm5.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause);
2357
3071
  const rows = await this.db.select({
2358
3072
  toolCallId: this.t.agentToolCall.id,
2359
3073
  toolName: this.t.agentToolCall.toolName,
@@ -2362,7 +3076,7 @@ var DrizzleGovernanceQueries = class {
2362
3076
  threadId: this.t.agentMessage.threadId,
2363
3077
  createdAt: this.t.agentToolCall.createdAt,
2364
3078
  runId: this.t.agentToolCall.runId
2365
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause).orderBy((0, import_drizzle_orm4.desc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm4.desc)(this.t.agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
3079
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm5.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause).orderBy((0, import_drizzle_orm5.desc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm5.desc)(this.t.agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
2366
3080
  return {
2367
3081
  rows: rows.map((row) => ({
2368
3082
  toolCallId: row.toolCallId,
@@ -2386,11 +3100,11 @@ var DrizzleGovernanceQueries = class {
2386
3100
  */
2387
3101
  async threadsPage(query) {
2388
3102
  const filters = query.where;
2389
- const whereClause = (0, import_drizzle_orm4.and)((0, import_drizzle_orm4.isNull)(this.t.agentThread.deletedAt), filters?.actorRef !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.title !== void 0 ? (0, import_drizzle_orm4.like)(import_drizzle_orm4.sql`lower(${this.t.agentThread.title})`, `%${filters.title.toLowerCase()}%`) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm4.gte)(this.t.agentThread.updatedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm4.lte)(this.t.agentThread.updatedAt, dayEndUtc(filters.toDay)) : void 0);
3103
+ const whereClause = (0, import_drizzle_orm5.and)((0, import_drizzle_orm5.isNull)(this.t.agentThread.deletedAt), filters?.actorRef !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.title !== void 0 ? (0, import_drizzle_orm5.like)(import_drizzle_orm5.sql`lower(${this.t.agentThread.title})`, `%${filters.title.toLowerCase()}%`) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm5.gte)(this.t.agentThread.updatedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm5.lte)(this.t.agentThread.updatedAt, dayEndUtc(filters.toDay)) : void 0);
2390
3104
  const [totalRow] = await this.db.select({
2391
- value: (0, import_drizzle_orm4.count)()
3105
+ value: (0, import_drizzle_orm5.count)()
2392
3106
  }).from(this.t.agentThread).where(whereClause);
2393
- const threads = await this.db.select().from(this.t.agentThread).where(whereClause).orderBy((0, import_drizzle_orm4.desc)(this.t.agentThread.updatedAt), (0, import_drizzle_orm4.desc)(this.t.agentThread.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
3107
+ const threads = await this.db.select().from(this.t.agentThread).where(whereClause).orderBy((0, import_drizzle_orm5.desc)(this.t.agentThread.updatedAt), (0, import_drizzle_orm5.desc)(this.t.agentThread.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
2394
3108
  const rows = await this.toThreadActivityRows(threads);
2395
3109
  return {
2396
3110
  rows,
@@ -2408,11 +3122,11 @@ var DrizzleGovernanceQueries = class {
2408
3122
  if (filters?.status !== void 0 && !isRunStatus(filters.status)) {
2409
3123
  return emptyPage(query);
2410
3124
  }
2411
- const whereClause = (0, import_drizzle_orm4.and)(filters?.agentName !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentRun.agentName, filters.agentName) : void 0, filters?.status !== void 0 && isRunStatus(filters.status) ? (0, import_drizzle_orm4.eq)(this.t.agentRun.status, filters.status) : void 0, filters?.errorCode !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentRun.errorCode, filters.errorCode) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentRun.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm4.gte)(this.t.agentRun.startedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm4.lte)(this.t.agentRun.startedAt, dayEndUtc(filters.toDay)) : void 0);
3125
+ const whereClause = (0, import_drizzle_orm5.and)(filters?.agentName !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentRun.agentName, filters.agentName) : void 0, filters?.status !== void 0 && isRunStatus(filters.status) ? (0, import_drizzle_orm5.eq)(this.t.agentRun.status, filters.status) : void 0, filters?.errorCode !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentRun.errorCode, filters.errorCode) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentRun.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm5.gte)(this.t.agentRun.startedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm5.lte)(this.t.agentRun.startedAt, dayEndUtc(filters.toDay)) : void 0);
2412
3126
  const [totalRow] = await this.db.select({
2413
- value: (0, import_drizzle_orm4.count)()
3127
+ value: (0, import_drizzle_orm5.count)()
2414
3128
  }).from(this.t.agentRun).where(whereClause);
2415
- const runs = await this.db.select().from(this.t.agentRun).where(whereClause).orderBy((0, import_drizzle_orm4.desc)(this.t.agentRun.startedAt), (0, import_drizzle_orm4.desc)(this.t.agentRun.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
3129
+ const runs = await this.db.select().from(this.t.agentRun).where(whereClause).orderBy((0, import_drizzle_orm5.desc)(this.t.agentRun.startedAt), (0, import_drizzle_orm5.desc)(this.t.agentRun.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
2416
3130
  return {
2417
3131
  rows: runs.map(toRecentRunRow),
2418
3132
  total: totalRow?.value ?? 0,
@@ -2432,10 +3146,10 @@ var DrizzleGovernanceQueries = class {
2432
3146
  */
2433
3147
  async approvalsPage(query) {
2434
3148
  const filters = query.where;
2435
- const whereClause = (0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(this.t.agentToolCall.status, "pending_approval"), filters?.toolName !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentThread.id, filters.threadId) : void 0, filters?.actorRef !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.agentName !== void 0 ? (0, import_drizzle_orm4.eq)(this.t.agentMessage.agentName, filters.agentName) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm4.gte)(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm4.lte)(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
3149
+ const whereClause = (0, import_drizzle_orm5.and)((0, import_drizzle_orm5.eq)(this.t.agentToolCall.status, "pending_approval"), filters?.toolName !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.threadId !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentThread.id, filters.threadId) : void 0, filters?.actorRef !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.agentName !== void 0 ? (0, import_drizzle_orm5.eq)(this.t.agentMessage.agentName, filters.agentName) : void 0, filters?.fromDay !== void 0 ? (0, import_drizzle_orm5.gte)(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? (0, import_drizzle_orm5.lte)(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
2436
3150
  const [totalRow] = await this.db.select({
2437
- value: (0, import_drizzle_orm4.count)()
2438
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where(whereClause);
3151
+ value: (0, import_drizzle_orm5.count)()
3152
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm5.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm5.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where(whereClause);
2439
3153
  const rows = await this.db.select({
2440
3154
  toolCallId: this.t.agentToolCall.id,
2441
3155
  toolName: this.t.agentToolCall.toolName,
@@ -2446,7 +3160,7 @@ var DrizzleGovernanceQueries = class {
2446
3160
  agentName: this.t.agentMessage.agentName,
2447
3161
  requestedAt: this.t.agentToolCall.createdAt,
2448
3162
  runId: this.t.agentToolCall.runId
2449
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm4.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where(whereClause).orderBy((0, import_drizzle_orm4.asc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm4.asc)(this.t.agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
3163
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm5.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, (0, import_drizzle_orm5.eq)(this.t.agentMessage.threadId, this.t.agentThread.id)).where(whereClause).orderBy((0, import_drizzle_orm5.asc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm5.asc)(this.t.agentToolCall.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize);
2450
3164
  return {
2451
3165
  rows: rows.map((row) => ({
2452
3166
  toolCallId: row.toolCallId,
@@ -2473,11 +3187,11 @@ var DrizzleGovernanceQueries = class {
2473
3187
  const [row] = await this.db.select({
2474
3188
  run: this.t.agentRun,
2475
3189
  thread: this.t.agentThread
2476
- }).from(this.t.agentRun).innerJoin(this.t.agentThread, (0, import_drizzle_orm4.eq)(this.t.agentRun.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm4.eq)(this.t.agentRun.id, runId)).limit(1);
3190
+ }).from(this.t.agentRun).innerJoin(this.t.agentThread, (0, import_drizzle_orm5.eq)(this.t.agentRun.threadId, this.t.agentThread.id)).where((0, import_drizzle_orm5.eq)(this.t.agentRun.id, runId)).limit(1);
2477
3191
  if (row === void 0) {
2478
3192
  return null;
2479
3193
  }
2480
- const toolCalls = await this.db.select().from(this.t.agentToolCall).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.runId, runId)).orderBy((0, import_drizzle_orm4.asc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm4.asc)(this.t.agentToolCall.id));
3194
+ const toolCalls = await this.db.select().from(this.t.agentToolCall).where((0, import_drizzle_orm5.eq)(this.t.agentToolCall.runId, runId)).orderBy((0, import_drizzle_orm5.asc)(this.t.agentToolCall.createdAt), (0, import_drizzle_orm5.asc)(this.t.agentToolCall.id));
2481
3195
  return {
2482
3196
  run: toRecentRunRow(row.run),
2483
3197
  thread: {
@@ -2496,27 +3210,27 @@ var DrizzleGovernanceQueries = class {
2496
3210
  * message. Soft-deleted threads are returned with `deleted: true`; an audit still needs them.
2497
3211
  */
2498
3212
  async threadDetail(query) {
2499
- const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, query.threadId)).limit(1);
3213
+ const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm5.eq)(this.t.agentThread.id, query.threadId)).limit(1);
2500
3214
  if (thread === void 0) {
2501
3215
  return null;
2502
3216
  }
2503
3217
  const pricing = await this.loadPricing();
2504
- const usageRows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm4.eq)(this.t.agentTokenUsage.threadId, thread.id));
2505
- const usage = (0, import_nestjs_agent_core2.rollupThreadUsage)(usageRows.map(toUsageInput), pricing);
3218
+ const usageRows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm5.eq)(this.t.agentTokenUsage.threadId, thread.id));
3219
+ const usage = (0, import_nestjs_agent_core5.rollupThreadUsage)(usageRows.map(toUsageInput), pricing);
2506
3220
  const [messageCountRow] = await this.db.select({
2507
- value: (0, import_drizzle_orm4.count)()
2508
- }).from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, thread.id));
2509
- const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, thread.id)).orderBy(
3221
+ value: (0, import_drizzle_orm5.count)()
3222
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm5.eq)(this.t.agentMessage.threadId, thread.id));
3223
+ const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm5.eq)(this.t.agentMessage.threadId, thread.id)).orderBy(
2510
3224
  // Append order (see DrizzleAgentStore's message order), newest first.
2511
- (0, import_drizzle_orm4.desc)(import_drizzle_orm4.sql`coalesce(${this.t.agentMessage.seq}, 0)`),
2512
- (0, import_drizzle_orm4.desc)(this.t.agentMessage.createdAt),
2513
- (0, import_drizzle_orm4.desc)(this.t.agentMessage.id)
3225
+ (0, import_drizzle_orm5.desc)(import_drizzle_orm5.sql`coalesce(${this.t.agentMessage.seq}, 0)`),
3226
+ (0, import_drizzle_orm5.desc)(this.t.agentMessage.createdAt),
3227
+ (0, import_drizzle_orm5.desc)(this.t.agentMessage.id)
2514
3228
  ).limit(query.messageLimit);
2515
3229
  const toolCallCounts = await this.toolCallCountsByMessage(messages.map((message) => message.id));
2516
3230
  const [runTotalRow] = await this.db.select({
2517
- value: (0, import_drizzle_orm4.count)()
2518
- }).from(this.t.agentRun).where((0, import_drizzle_orm4.eq)(this.t.agentRun.threadId, thread.id));
2519
- const runs = await this.db.select().from(this.t.agentRun).where((0, import_drizzle_orm4.eq)(this.t.agentRun.threadId, thread.id)).orderBy((0, import_drizzle_orm4.desc)(this.t.agentRun.startedAt), (0, import_drizzle_orm4.desc)(this.t.agentRun.id)).limit(query.runLimit);
3231
+ value: (0, import_drizzle_orm5.count)()
3232
+ }).from(this.t.agentRun).where((0, import_drizzle_orm5.eq)(this.t.agentRun.threadId, thread.id));
3233
+ const runs = await this.db.select().from(this.t.agentRun).where((0, import_drizzle_orm5.eq)(this.t.agentRun.threadId, thread.id)).orderBy((0, import_drizzle_orm5.desc)(this.t.agentRun.startedAt), (0, import_drizzle_orm5.desc)(this.t.agentRun.id)).limit(query.runLimit);
2520
3234
  return {
2521
3235
  thread: {
2522
3236
  threadId: thread.id,
@@ -2531,7 +3245,7 @@ var DrizzleGovernanceQueries = class {
2531
3245
  runs: runs.map(toRecentRunRow),
2532
3246
  runTotal: runTotalRow?.value ?? 0,
2533
3247
  messages: messages.map((message) => {
2534
- const { content, truncated } = (0, import_nestjs_agent_core2.truncateDetailContent)(message.content);
3248
+ const { content, truncated } = (0, import_nestjs_agent_core5.truncateDetailContent)(message.content);
2535
3249
  return {
2536
3250
  messageId: message.id,
2537
3251
  role: message.role,
@@ -2552,8 +3266,8 @@ var DrizzleGovernanceQueries = class {
2552
3266
  }
2553
3267
  const rows = await this.db.select({
2554
3268
  messageId: this.t.agentToolCall.messageId,
2555
- value: (0, import_drizzle_orm4.count)()
2556
- }).from(this.t.agentToolCall).where((0, import_drizzle_orm4.inArray)(this.t.agentToolCall.messageId, messageIds)).groupBy(this.t.agentToolCall.messageId);
3269
+ value: (0, import_drizzle_orm5.count)()
3270
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm5.inArray)(this.t.agentToolCall.messageId, messageIds)).groupBy(this.t.agentToolCall.messageId);
2557
3271
  for (const row of rows) {
2558
3272
  counts.set(row.messageId, row.value);
2559
3273
  }
@@ -2562,8 +3276,8 @@ var DrizzleGovernanceQueries = class {
2562
3276
  };
2563
3277
 
2564
3278
  // src/drizzle-memory-provider.ts
2565
- var import_nestjs_agent_core3 = require("@dudousxd/nestjs-agent-core");
2566
- var import_drizzle_orm5 = require("drizzle-orm");
3279
+ var import_nestjs_agent_core6 = require("@dudousxd/nestjs-agent-core");
3280
+ var import_drizzle_orm6 = require("drizzle-orm");
2567
3281
  function toRecord(row) {
2568
3282
  return {
2569
3283
  id: row.id,
@@ -2611,7 +3325,7 @@ var DrizzleMemoryProvider = class {
2611
3325
  if (scopes.length === 0) {
2612
3326
  return [];
2613
3327
  }
2614
- const rows = await this.db.select().from(this.t.agentMemory).where((0, import_drizzle_orm5.inArray)(this.t.agentMemory.scope, [
3328
+ const rows = await this.db.select().from(this.t.agentMemory).where((0, import_drizzle_orm6.inArray)(this.t.agentMemory.scope, [
2615
3329
  ...scopes
2616
3330
  ]));
2617
3331
  return rows.map(toRecord);
@@ -2627,7 +3341,7 @@ var DrizzleMemoryProvider = class {
2627
3341
  * answer cannot be used to find out which memories exist about other people.
2628
3342
  */
2629
3343
  async forget({ id, ctx }) {
2630
- const deleted = await affectedRows(this.dialect, this.db.delete(this.t.agentMemory).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.eq)(this.t.agentMemory.id, id), (0, import_drizzle_orm5.eq)(this.t.agentMemory.scope, (0, import_nestjs_agent_core3.actorScope)(ctx.actor)))), this.t.agentMemory.id);
3344
+ const deleted = await affectedRows(this.dialect, this.db.delete(this.t.agentMemory).where((0, import_drizzle_orm6.and)((0, import_drizzle_orm6.eq)(this.t.agentMemory.id, id), (0, import_drizzle_orm6.eq)(this.t.agentMemory.scope, (0, import_nestjs_agent_core6.actorScope)(ctx.actor)))), this.t.agentMemory.id);
2631
3345
  return deleted > 0;
2632
3346
  }
2633
3347
  /**
@@ -2676,7 +3390,7 @@ var DrizzleMemoryProvider = class {
2676
3390
  memory.scope,
2677
3391
  memory.key
2678
3392
  ], set);
2679
- [row] = await this.db.select().from(memory).where((0, import_drizzle_orm5.and)((0, import_drizzle_orm5.eq)(memory.scope, scope), (0, import_drizzle_orm5.eq)(memory.key, key2)));
3393
+ [row] = await this.db.select().from(memory).where((0, import_drizzle_orm6.and)((0, import_drizzle_orm6.eq)(memory.scope, scope), (0, import_drizzle_orm6.eq)(memory.key, key2)));
2680
3394
  } else {
2681
3395
  [row] = await insert.onConflictDoUpdate({
2682
3396
  target: [
@@ -2703,12 +3417,12 @@ var DrizzleMemoryProvider = class {
2703
3417
  const updated = await affectedRows(this.dialect, this.db.update(this.t.agentMemory).set({
2704
3418
  pinned,
2705
3419
  updatedAt: /* @__PURE__ */ new Date()
2706
- }).where((0, import_drizzle_orm5.eq)(this.t.agentMemory.id, id)), this.t.agentMemory.id);
3420
+ }).where((0, import_drizzle_orm6.eq)(this.t.agentMemory.id, id)), this.t.agentMemory.id);
2707
3421
  return updated > 0;
2708
3422
  }
2709
3423
  };
2710
3424
  function assertAuthorMayWriteScope({ scope, origin, ctx }) {
2711
- const own = (0, import_nestjs_agent_core3.actorScope)(ctx.actor);
3425
+ const own = (0, import_nestjs_agent_core6.actorScope)(ctx.actor);
2712
3426
  if (origin.author !== "human" && scope !== own) {
2713
3427
  throw new Error(`DrizzleMemoryProvider: refusing to write an agent-authored memory at "${scope}"; an agent may write only at "${own}"`);
2714
3428
  }
@@ -2716,7 +3430,7 @@ function assertAuthorMayWriteScope({ scope, origin, ctx }) {
2716
3430
  __name(assertAuthorMayWriteScope, "assertAuthorMayWriteScope");
2717
3431
 
2718
3432
  // src/drizzle-pricing-store.ts
2719
- var import_drizzle_orm6 = require("drizzle-orm");
3433
+ var import_drizzle_orm7 = require("drizzle-orm");
2720
3434
  var DrizzlePricingStore = class {
2721
3435
  static {
2722
3436
  __name(this, "DrizzlePricingStore");
@@ -2732,7 +3446,7 @@ var DrizzlePricingStore = class {
2732
3446
  async upsertModelPrice(input) {
2733
3447
  await this.db.update(this.t.agentModelPricing).set({
2734
3448
  isCurrent: false
2735
- }).where((0, import_drizzle_orm6.and)((0, import_drizzle_orm6.eq)(this.t.agentModelPricing.modelId, input.modelId), (0, import_drizzle_orm6.eq)(this.t.agentModelPricing.isCurrent, true)));
3449
+ }).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(this.t.agentModelPricing.modelId, input.modelId), (0, import_drizzle_orm7.eq)(this.t.agentModelPricing.isCurrent, true)));
2736
3450
  await this.db.insert(this.t.agentModelPricing).values({
2737
3451
  id: crypto.randomUUID(),
2738
3452
  modelId: input.modelId,
@@ -2745,7 +3459,7 @@ var DrizzlePricingStore = class {
2745
3459
  });
2746
3460
  }
2747
3461
  async listCurrentPrices() {
2748
- const rows = await this.db.select().from(this.t.agentModelPricing).where((0, import_drizzle_orm6.eq)(this.t.agentModelPricing.isCurrent, true));
3462
+ const rows = await this.db.select().from(this.t.agentModelPricing).where((0, import_drizzle_orm7.eq)(this.t.agentModelPricing.isCurrent, true));
2749
3463
  return rows.map((row) => ({
2750
3464
  modelId: row.modelId,
2751
3465
  inputPricePer1m: row.inputPricePer1m,
@@ -2762,8 +3476,8 @@ var DrizzlePricingStore = class {
2762
3476
  };
2763
3477
 
2764
3478
  // src/drizzle-token-stream-sink.ts
2765
- var import_nestjs_agent_core4 = require("@dudousxd/nestjs-agent-core");
2766
- var import_drizzle_orm7 = require("drizzle-orm");
3479
+ var import_nestjs_agent_core7 = require("@dudousxd/nestjs-agent-core");
3480
+ var import_drizzle_orm8 = require("drizzle-orm");
2767
3481
  var DrizzleStreamFrameTable = class {
2768
3482
  static {
2769
3483
  __name(this, "DrizzleStreamFrameTable");
@@ -2777,7 +3491,7 @@ var DrizzleStreamFrameTable = class {
2777
3491
  this.db = asBuilder(db);
2778
3492
  }
2779
3493
  async append(runId, row) {
2780
- await runSql(this.db, this.dialect, import_drizzle_orm7.sql`INSERT INTO agent_stream_frame (run_id, seq, frame, error, created_at)
3494
+ await runSql(this.db, this.dialect, import_drizzle_orm8.sql`INSERT INTO agent_stream_frame (run_id, seq, frame, error, created_at)
2781
3495
  SELECT ${runId}, COALESCE(MAX(seq), 0) + 1, ${row.frame}, ${row.error}, ${row.createdAt}
2782
3496
  FROM agent_stream_frame WHERE run_id = ${runId}`);
2783
3497
  }
@@ -2786,31 +3500,31 @@ var DrizzleStreamFrameTable = class {
2786
3500
  seq: this.t.agentStreamFrame.seq,
2787
3501
  frame: this.t.agentStreamFrame.frame,
2788
3502
  error: this.t.agentStreamFrame.error
2789
- }).from(this.t.agentStreamFrame).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(this.t.agentStreamFrame.runId, runId), (0, import_drizzle_orm7.gt)(this.t.agentStreamFrame.seq, after))).orderBy((0, import_drizzle_orm7.asc)(this.t.agentStreamFrame.seq)).limit(limit);
3503
+ }).from(this.t.agentStreamFrame).where((0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(this.t.agentStreamFrame.runId, runId), (0, import_drizzle_orm8.gt)(this.t.agentStreamFrame.seq, after))).orderBy((0, import_drizzle_orm8.asc)(this.t.agentStreamFrame.seq)).limit(limit);
2790
3504
  }
2791
3505
  async has(runId) {
2792
3506
  const rows = await this.db.select({
2793
3507
  seq: this.t.agentStreamFrame.seq
2794
- }).from(this.t.agentStreamFrame).where((0, import_drizzle_orm7.eq)(this.t.agentStreamFrame.runId, runId)).limit(1);
3508
+ }).from(this.t.agentStreamFrame).where((0, import_drizzle_orm8.eq)(this.t.agentStreamFrame.runId, runId)).limit(1);
2795
3509
  return rows.length > 0;
2796
3510
  }
2797
3511
  async remove(runIds) {
2798
3512
  if (runIds.length === 0) return;
2799
- await this.db.delete(this.t.agentStreamFrame).where((0, import_drizzle_orm7.inArray)(this.t.agentStreamFrame.runId, [
3513
+ await this.db.delete(this.t.agentStreamFrame).where((0, import_drizzle_orm8.inArray)(this.t.agentStreamFrame.runId, [
2800
3514
  ...runIds
2801
3515
  ]));
2802
3516
  }
2803
3517
  async lapsedRuns(cutoff) {
2804
3518
  const rows = await this.db.select({
2805
3519
  runId: this.t.agentStreamFrame.runId
2806
- }).from(this.t.agentStreamFrame).groupBy(this.t.agentStreamFrame.runId).having((0, import_drizzle_orm7.lt)((0, import_drizzle_orm7.max)(this.t.agentStreamFrame.createdAt), cutoff));
3520
+ }).from(this.t.agentStreamFrame).groupBy(this.t.agentStreamFrame.runId).having((0, import_drizzle_orm8.lt)((0, import_drizzle_orm8.max)(this.t.agentStreamFrame.createdAt), cutoff));
2807
3521
  return rows.map((row) => row.runId);
2808
3522
  }
2809
3523
  isUniqueViolation(error) {
2810
3524
  return isUniqueViolation(error);
2811
3525
  }
2812
3526
  };
2813
- var DrizzleTokenStreamSink = class extends import_nestjs_agent_core4.SqlTokenStreamSink {
3527
+ var DrizzleTokenStreamSink = class extends import_nestjs_agent_core7.SqlTokenStreamSink {
2814
3528
  static {
2815
3529
  __name(this, "DrizzleTokenStreamSink");
2816
3530
  }
@@ -2820,7 +3534,7 @@ var DrizzleTokenStreamSink = class extends import_nestjs_agent_core4.SqlTokenStr
2820
3534
  };
2821
3535
 
2822
3536
  // src/drizzle-confirm-token-store.ts
2823
- var import_drizzle_orm8 = require("drizzle-orm");
3537
+ var import_drizzle_orm9 = require("drizzle-orm");
2824
3538
  var DrizzleConfirmTokenStore = class {
2825
3539
  static {
2826
3540
  __name(this, "DrizzleConfirmTokenStore");
@@ -2850,18 +3564,18 @@ var DrizzleConfirmTokenStore = class {
2850
3564
  return inserted === 1;
2851
3565
  }
2852
3566
  async release(hash) {
2853
- await this.db.delete(this.t.agentConfirmToken).where((0, import_drizzle_orm8.eq)(this.t.agentConfirmToken.hash, hash));
3567
+ await this.db.delete(this.t.agentConfirmToken).where((0, import_drizzle_orm9.eq)(this.t.agentConfirmToken.hash, hash));
2854
3568
  }
2855
3569
  async purgeExpired(now = Date.now()) {
2856
3570
  const table = this.t.agentConfirmToken;
2857
- return affectedRows(this.dialect, this.db.delete(table).where((0, import_drizzle_orm8.lt)(table.expiresAt, now)), table.hash);
3571
+ return affectedRows(this.dialect, this.db.delete(table).where((0, import_drizzle_orm9.lt)(table.expiresAt, now)), table.hash);
2858
3572
  }
2859
3573
  };
2860
3574
 
2861
3575
  // src/drizzle-rag-ingestion-log.ts
2862
3576
  var import_node_diagnostics_channel = require("diagnostics_channel");
2863
3577
  var import_common = require("@nestjs/common");
2864
- var import_drizzle_orm9 = require("drizzle-orm");
3578
+ var import_drizzle_orm10 = require("drizzle-orm");
2865
3579
  function _ts_decorate(decorators, target, key2, desc4) {
2866
3580
  var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key2) : desc4, d;
2867
3581
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -2909,8 +3623,8 @@ function num(value) {
2909
3623
  }
2910
3624
  __name(num, "num");
2911
3625
  var RAG_INGESTION_LOG_PAGE_ORDER = [
2912
- (0, import_drizzle_orm9.desc)(ragIngestionLog.updatedAt),
2913
- (0, import_drizzle_orm9.asc)(ragIngestionLog.documentId)
3626
+ (0, import_drizzle_orm10.desc)(ragIngestionLog.updatedAt),
3627
+ (0, import_drizzle_orm10.asc)(ragIngestionLog.documentId)
2914
3628
  ];
2915
3629
  var DEFAULT_PAGE_SIZE = 200;
2916
3630
  var DEFAULT_BATCH_SIZE = 200;
@@ -2981,7 +3695,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2981
3695
  */
2982
3696
  async listPage(query = {}) {
2983
3697
  const [totalRow] = await this.db.select({
2984
- value: (0, import_drizzle_orm9.count)()
3698
+ value: (0, import_drizzle_orm10.count)()
2985
3699
  }).from(this.t.ragIngestionLog).where(this.where(query));
2986
3700
  return {
2987
3701
  rows: await this.list(query),
@@ -3060,17 +3774,17 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
3060
3774
  }
3061
3775
  /** The latest recorded outcome for one document, or null if it was never attempted. */
3062
3776
  async get(documentId) {
3063
- const [row] = await this.db.select().from(this.t.ragIngestionLog).where((0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.documentId, documentId));
3777
+ const [row] = await this.db.select().from(this.t.ragIngestionLog).where((0, import_drizzle_orm10.eq)(this.t.ragIngestionLog.documentId, documentId));
3064
3778
  return row ?? null;
3065
3779
  }
3066
3780
  /** Forget one document's record. Returns whether a row was actually removed. */
3067
3781
  async remove(documentId) {
3068
- const removed = await affectedRows(this.dialect, this.db.delete(this.t.ragIngestionLog).where((0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.documentId, documentId)), this.t.ragIngestionLog.documentId);
3782
+ const removed = await affectedRows(this.dialect, this.db.delete(this.t.ragIngestionLog).where((0, import_drizzle_orm10.eq)(this.t.ragIngestionLog.documentId, documentId)), this.t.ragIngestionLog.documentId);
3069
3783
  return removed > 0;
3070
3784
  }
3071
3785
  /** Forget every record for a collection — for when the collection itself is deleted. */
3072
3786
  async removeByCollection(collection) {
3073
- const removed = await affectedRows(this.dialect, this.db.delete(this.t.ragIngestionLog).where((0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.collection, collection)), this.t.ragIngestionLog.documentId);
3787
+ const removed = await affectedRows(this.dialect, this.db.delete(this.t.ragIngestionLog).where((0, import_drizzle_orm10.eq)(this.t.ragIngestionLog.collection, collection)), this.t.ragIngestionLog.documentId);
3074
3788
  return removed;
3075
3789
  }
3076
3790
  /**
@@ -3100,7 +3814,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
3100
3814
  }
3101
3815
  }
3102
3816
  where(query) {
3103
- return (0, import_drizzle_orm9.and)(query.collection !== void 0 ? (0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.collection, query.collection) : void 0, query.status !== void 0 ? (0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.status, query.status) : void 0);
3817
+ return (0, import_drizzle_orm10.and)(query.collection !== void 0 ? (0, import_drizzle_orm10.eq)(this.t.ragIngestionLog.collection, query.collection) : void 0, query.status !== void 0 ? (0, import_drizzle_orm10.eq)(this.t.ragIngestionLog.status, query.status) : void 0);
3104
3818
  }
3105
3819
  /**
3106
3820
  * The coordinates filter AND'd with "strictly after `cursor` in
@@ -3115,7 +3829,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
3115
3829
  if (cursor === void 0) {
3116
3830
  return base;
3117
3831
  }
3118
- return (0, import_drizzle_orm9.and)(base, (0, import_drizzle_orm9.or)((0, import_drizzle_orm9.lt)(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), (0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), (0, import_drizzle_orm9.gt)(this.t.ragIngestionLog.documentId, cursor.documentId))));
3832
+ return (0, import_drizzle_orm10.and)(base, (0, import_drizzle_orm10.or)((0, import_drizzle_orm10.lt)(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), (0, import_drizzle_orm10.and)((0, import_drizzle_orm10.eq)(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), (0, import_drizzle_orm10.gt)(this.t.ragIngestionLog.documentId, cursor.documentId))));
3119
3833
  }
3120
3834
  /**
3121
3835
  * Upsert one outcome. Keyed by document id so the row always reflects the *current* state — a
@@ -3188,7 +3902,7 @@ DrizzleRagIngestionLog = _ts_decorate([
3188
3902
  ], DrizzleRagIngestionLog);
3189
3903
 
3190
3904
  // src/drizzle-agent-store.module.ts
3191
- var import_nestjs_agent_core5 = require("@dudousxd/nestjs-agent-core");
3905
+ var import_nestjs_agent_core8 = require("@dudousxd/nestjs-agent-core");
3192
3906
  var import_common2 = require("@nestjs/common");
3193
3907
  function _ts_decorate2(decorators, target, key2, desc4) {
3194
3908
  var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key2) : desc4, d;
@@ -3225,7 +3939,7 @@ var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
3225
3939
  useFactory: /* @__PURE__ */ __name(() => new DrizzleAgentStore(options.db), "useFactory")
3226
3940
  },
3227
3941
  {
3228
- provide: import_nestjs_agent_core5.AGENT_STORE,
3942
+ provide: import_nestjs_agent_core8.AGENT_STORE,
3229
3943
  useExisting: DrizzleAgentStore
3230
3944
  },
3231
3945
  // Exported, never bound to AGENT_MEMORY: that token's PRESENCE is what turns memory on, so
@@ -3242,21 +3956,21 @@ var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
3242
3956
  // AGENT_PRICING_STORE: the host's own store when supplied, else the default Drizzle one.
3243
3957
  // DrizzleGovernanceQueries prices usage against whatever is bound here.
3244
3958
  options.pricingStore ? {
3245
- provide: import_nestjs_agent_core5.AGENT_PRICING_STORE,
3959
+ provide: import_nestjs_agent_core8.AGENT_PRICING_STORE,
3246
3960
  useClass: options.pricingStore
3247
3961
  } : {
3248
- provide: import_nestjs_agent_core5.AGENT_PRICING_STORE,
3962
+ provide: import_nestjs_agent_core8.AGENT_PRICING_STORE,
3249
3963
  useExisting: DrizzlePricingStore
3250
3964
  },
3251
3965
  {
3252
3966
  provide: DrizzleGovernanceQueries,
3253
3967
  useFactory: /* @__PURE__ */ __name((pricingStore) => new DrizzleGovernanceQueries(options.db, pricingStore), "useFactory"),
3254
3968
  inject: [
3255
- import_nestjs_agent_core5.AGENT_PRICING_STORE
3969
+ import_nestjs_agent_core8.AGENT_PRICING_STORE
3256
3970
  ]
3257
3971
  },
3258
3972
  {
3259
- provide: import_nestjs_agent_core5.AGENT_GOVERNANCE_QUERIES,
3973
+ provide: import_nestjs_agent_core8.AGENT_GOVERNANCE_QUERIES,
3260
3974
  useExisting: DrizzleGovernanceQueries
3261
3975
  },
3262
3976
  // What makes a `defineConfirmedTool` confirmation single use across replicas.
@@ -3265,7 +3979,7 @@ var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
3265
3979
  useFactory: /* @__PURE__ */ __name(() => new DrizzleConfirmTokenStore(options.db), "useFactory")
3266
3980
  },
3267
3981
  {
3268
- provide: import_nestjs_agent_core5.AGENT_CONFIRM_TOKEN_STORE,
3982
+ provide: import_nestjs_agent_core8.AGENT_CONFIRM_TOKEN_STORE,
3269
3983
  useExisting: DrizzleConfirmTokenStore
3270
3984
  }
3271
3985
  ],
@@ -3274,14 +3988,14 @@ var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
3274
3988
  DrizzleRagIngestionLog
3275
3989
  ],
3276
3990
  DrizzleAgentStore,
3277
- import_nestjs_agent_core5.AGENT_STORE,
3991
+ import_nestjs_agent_core8.AGENT_STORE,
3278
3992
  DrizzleMemoryProvider,
3279
3993
  DrizzleGovernanceQueries,
3280
- import_nestjs_agent_core5.AGENT_GOVERNANCE_QUERIES,
3994
+ import_nestjs_agent_core8.AGENT_GOVERNANCE_QUERIES,
3281
3995
  DrizzlePricingStore,
3282
- import_nestjs_agent_core5.AGENT_PRICING_STORE,
3996
+ import_nestjs_agent_core8.AGENT_PRICING_STORE,
3283
3997
  DrizzleConfirmTokenStore,
3284
- import_nestjs_agent_core5.AGENT_CONFIRM_TOKEN_STORE
3998
+ import_nestjs_agent_core8.AGENT_CONFIRM_TOKEN_STORE
3285
3999
  ]
3286
4000
  };
3287
4001
  }
@@ -3291,6 +4005,7 @@ DrizzleAgentStoreModule = _ts_decorate2([
3291
4005
  ], DrizzleAgentStoreModule);
3292
4006
  // Annotate the CommonJS export names for ESM import in node:
3293
4007
  0 && (module.exports = {
4008
+ DrizzleActionProposalStore,
3294
4009
  DrizzleAgentStore,
3295
4010
  DrizzleAgentStoreModule,
3296
4011
  DrizzleConfirmTokenStore,
@@ -3301,6 +4016,7 @@ DrizzleAgentStoreModule = _ts_decorate2([
3301
4016
  DrizzleStreamFrameTable,
3302
4017
  DrizzleTokenStreamSink,
3303
4018
  RAG_INGESTION_LOG_PAGE_ORDER,
4019
+ agentActionProposal,
3304
4020
  agentConfirmToken,
3305
4021
  agentDialectOf,
3306
4022
  agentMemory,