@dudousxd/nestjs-agent-store-drizzle 0.24.0 → 0.26.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,516 @@ 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
+ "PostgresJsDatabase",
1205
+ "PostgresJsTransaction",
1206
+ "MySql2Database",
1207
+ "MySql2Transaction",
1208
+ "LibSQLDatabase",
1209
+ "LibSQLTransaction"
1210
+ ].includes(kind)) return "async";
1211
+ return "unsupported";
1212
+ }
1213
+ __name(actionProposalTransactionMode, "actionProposalTransactionMode");
1214
+
1215
+ // src/drizzle-action-proposal-store.ts
1216
+ var DrizzleActionProposalStore = class {
1217
+ static {
1218
+ __name(this, "DrizzleActionProposalStore");
1219
+ }
1220
+ db;
1221
+ rawDb;
1222
+ actionProposalAdmissionSupported;
1223
+ synchronousSqlite;
1224
+ dialect;
1225
+ table;
1226
+ clock;
1227
+ constructor(db, options = {}) {
1228
+ this.rawDb = db;
1229
+ const kind = db.constructor[import_drizzle_orm3.entityKind];
1230
+ const transactionMode = actionProposalTransactionMode(kind);
1231
+ this.synchronousSqlite = transactionMode === "sync";
1232
+ this.actionProposalAdmissionSupported = transactionMode !== "unsupported";
1233
+ this.dialect = agentDialectOf(db);
1234
+ this.table = agentTablesFor(this.dialect).agentActionProposal;
1235
+ this.db = asBuilder(db);
1236
+ this.clock = options.clock ?? Date.now;
1237
+ }
1238
+ async createActionProposal(input) {
1239
+ const proposal = (0, import_nestjs_agent_core3.initialActionProposal)(input, this.clock());
1240
+ const row = {
1241
+ id: physicalId(input.id),
1242
+ scopeKey: scopeKey(input),
1243
+ decision: proposal.decision,
1244
+ logicalSort: logicalSort(input.id),
1245
+ createFingerprint: (0, import_nestjs_agent_core3.canonicalActionProposalJson)(input),
1246
+ proposal,
1247
+ ...discoveryMetadata(proposal),
1248
+ version: 0,
1249
+ createdAt: proposal.createdAt
1250
+ };
1251
+ const table = this.table;
1252
+ const insert = this.db.insert(table);
1253
+ const inserted = this.dialect === "mysql" ? mysqlAffectedRows(await insert.ignore().values(row)) : await affectedRows(this.dialect, insert.values(row).onConflictDoNothing(), table.id);
1254
+ const stored = await this.read(input, input.id);
1255
+ if (!stored) return {
1256
+ status: "conflict"
1257
+ };
1258
+ if (inserted === 1) return {
1259
+ status: "created",
1260
+ proposal: stored.proposal
1261
+ };
1262
+ return {
1263
+ status: stored.createFingerprint === row.createFingerprint ? "unchanged" : "conflict",
1264
+ proposal: stored.proposal
1265
+ };
1266
+ }
1267
+ createReplacingActionProposal(input) {
1268
+ if (!input.replacementKey) return this.createActionProposal(input);
1269
+ const proposal = (0, import_nestjs_agent_core3.initialActionProposal)(input, this.clock());
1270
+ return this.transactionSteps((db) => this.replacementSteps(db, input, proposal));
1271
+ }
1272
+ async supersedeActionProposal(scope, id, command) {
1273
+ const replacement = await this.getActionProposal(scope, command.replacementProposalId);
1274
+ if (!replacement) return {
1275
+ status: "not_found"
1276
+ };
1277
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalSupersession)(row, replacement, command, now));
1278
+ }
1279
+ *replacementSteps(db, input, proposal) {
1280
+ const table = this.table;
1281
+ const thread = agentTablesFor(this.dialect).agentThread;
1282
+ if (this.dialect === "sqlite") yield {
1283
+ kind: "write",
1284
+ query: db.update(thread).set({
1285
+ updatedAt: import_drizzle_orm3.sql`${thread.updatedAt}`
1286
+ }).where((0, import_drizzle_orm3.eq)(thread.id, input.threadId))
1287
+ };
1288
+ const threads = yield {
1289
+ kind: "read",
1290
+ query: lockQuery(db.select().from(thread).where((0, import_drizzle_orm3.eq)(thread.id, input.threadId)).limit(1), this.dialect)
1291
+ };
1292
+ const owner = threads[0];
1293
+ if (!owner || owner.id !== input.threadId || owner.deletedAt || owner.actorRef !== input.actorRef || owner.tenantRef !== input.tenantRef) return {
1294
+ status: "conflict"
1295
+ };
1296
+ const existingRows = yield {
1297
+ kind: "read",
1298
+ query: db.select().from(table).where((0, import_drizzle_orm3.eq)(table.id, physicalId(input.id))).limit(1)
1299
+ };
1300
+ const existing = existingRows[0];
1301
+ if (existing) {
1302
+ if (existing.proposal.id !== input.id || !(0, import_nestjs_agent_core3.actionProposalScopeMatches)(existing.proposal, input)) return {
1303
+ status: "conflict"
1304
+ };
1305
+ return {
1306
+ status: existing.createFingerprint === (0, import_nestjs_agent_core3.canonicalActionProposalJson)(input) ? "unchanged" : "conflict",
1307
+ proposal: existing.proposal
1308
+ };
1309
+ }
1310
+ const groupKey = replacementGroupKey(input);
1311
+ if (groupKey === null) throw new Error("Missing explicit replacement identity");
1312
+ const pending = yield {
1313
+ kind: "read",
1314
+ 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)
1315
+ };
1316
+ const row = {
1317
+ id: physicalId(input.id),
1318
+ scopeKey: scopeKey(input),
1319
+ decision: proposal.decision,
1320
+ logicalSort: logicalSort(input.id),
1321
+ createFingerprint: (0, import_nestjs_agent_core3.canonicalActionProposalJson)(input),
1322
+ proposal,
1323
+ ...discoveryMetadata(proposal),
1324
+ version: 0,
1325
+ createdAt: proposal.createdAt
1326
+ };
1327
+ const insert = db.insert(table);
1328
+ const inserted = yield {
1329
+ kind: "read",
1330
+ query: this.dialect === "mysql" ? insert.ignore().values(row) : insert.values(row).onConflictDoNothing().returning({
1331
+ id: table.id
1332
+ })
1333
+ };
1334
+ const count3 = this.dialect === "mysql" ? mysqlAffectedRows(inserted) : inserted.length;
1335
+ if (count3 !== 1) return {
1336
+ status: "conflict"
1337
+ };
1338
+ for (const old of pending) {
1339
+ const result = (0, import_nestjs_agent_core3.transitionActionProposalSupersession)(old.proposal, proposal, {
1340
+ replacementProposalId: proposal.id,
1341
+ actorRef: proposal.actorRef,
1342
+ via: "replacement"
1343
+ }, this.clock());
1344
+ if (!result.proposal || (0, import_nestjs_agent_core3.canonicalActionProposalJson)(result.proposal) === (0, import_nestjs_agent_core3.canonicalActionProposalJson)(old.proposal)) continue;
1345
+ const next = result.proposal;
1346
+ const update = db.update(table).set({
1347
+ proposal: next,
1348
+ decision: next.decision,
1349
+ ...discoveryMetadata(next),
1350
+ version: old.version + 1
1351
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.id, old.id), (0, import_drizzle_orm3.eq)(table.version, old.version)));
1352
+ const updated = yield {
1353
+ kind: "read",
1354
+ query: this.dialect === "mysql" ? update : update.returning({
1355
+ id: table.id
1356
+ })
1357
+ };
1358
+ if ((this.dialect === "mysql" ? mysqlAffectedRows(updated) : updated.length) !== 1) throw new Error("Replacement lost its locked proposal fence");
1359
+ }
1360
+ return {
1361
+ status: "created",
1362
+ proposal
1363
+ };
1364
+ }
1365
+ async getActionProposal(scope, id) {
1366
+ return (await this.read(scope, id))?.proposal ?? null;
1367
+ }
1368
+ async listActionProposals(scope, query = {}) {
1369
+ const limit = (0, import_nestjs_agent_core3.validateActionProposalListQuery)(query);
1370
+ 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);
1371
+ return rows.map((row) => row.proposal).filter((proposal) => (0, import_nestjs_agent_core3.actionProposalScopeMatches)(proposal, scope));
1372
+ }
1373
+ decideActionProposal(scope, id, command) {
1374
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalDecision)(row, command, now));
1375
+ }
1376
+ claimActionProposal(scope, id, command) {
1377
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalClaim)(row, command, now, (0, import_node_crypto.randomUUID)()));
1378
+ }
1379
+ extendActionProposalLease(scope, id, command) {
1380
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalLease)(row, command, now));
1381
+ }
1382
+ settleActionProposal(scope, id, command) {
1383
+ return this.mutate(scope, id, (row, now) => (0, import_nestjs_agent_core3.transitionActionProposalSettlement)(row, command, now));
1384
+ }
1385
+ async claimNextActionProposal(command) {
1386
+ const now = this.clock();
1387
+ (0, import_nestjs_agent_core3.validateActionProposalWorkerClaim)(command, now);
1388
+ const table = this.table;
1389
+ 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);
1390
+ for (const candidate of candidates) {
1391
+ const result = await this.claimActionProposal(candidate.proposal, candidate.proposal.id, command);
1392
+ if (result.status === "applied" && result.proposal) return result.proposal;
1393
+ }
1394
+ return null;
1395
+ }
1396
+ async expireActionProposals(command) {
1397
+ const now = this.clock();
1398
+ (0, import_nestjs_agent_core3.validateActionProposalExpiryBatch)(command, now);
1399
+ const table = this.table;
1400
+ 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);
1401
+ let expired = 0;
1402
+ for (const candidate of candidates) {
1403
+ const result = await this.decideActionProposal(candidate.proposal, candidate.proposal.id, {
1404
+ decision: "expired",
1405
+ actorRef: "system",
1406
+ via: "expiry"
1407
+ });
1408
+ if (result.status === "applied") expired++;
1409
+ }
1410
+ return expired;
1411
+ }
1412
+ async backfillActionProposalDiscoveryIndex(command) {
1413
+ (0, import_nestjs_agent_core3.validateActionProposalDiscoveryIndexBatch)(command);
1414
+ const table = this.table;
1415
+ 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);
1416
+ let changed = 0;
1417
+ for (const row of candidates) {
1418
+ changed += await affectedRows(this.dialect, this.db.update(table).set({
1419
+ ...discoveryMetadata(row.proposal),
1420
+ version: row.version + 1
1421
+ }).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);
1422
+ }
1423
+ return changed;
1424
+ }
1425
+ async rememberedActionProposalApprovals(scope) {
1426
+ const table = this.table;
1427
+ 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"))));
1428
+ return [
1429
+ ...new Set(rows.filter((row) => (0, import_nestjs_agent_core3.actionProposalScopeMatches)(row.proposal, scope) && row.proposal.decisionAudit?.remember === true).map((row) => row.proposal.toolName))
1430
+ ];
1431
+ }
1432
+ async getThreadActionProposalScope(threadId) {
1433
+ const thread = agentTablesFor(this.dialect).agentThread;
1434
+ 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);
1435
+ return row?.id === threadId ? {
1436
+ actorRef: row.actorRef,
1437
+ tenantRef: row.tenantRef,
1438
+ threadId: row.id
1439
+ } : null;
1440
+ }
1441
+ async claimNextActionProposalOutcome(command) {
1442
+ const now = this.clock();
1443
+ (0, import_nestjs_agent_core3.validateActionProposalWorkerClaim)(command, now);
1444
+ const table = this.table;
1445
+ 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);
1446
+ for (const row of candidates) {
1447
+ const result = await this.mutate(row.proposal, row.proposal.id, (proposal, time) => {
1448
+ const claimed2 = (0, import_nestjs_agent_core3.claimActionProposalOutcome)(proposal, command, time, (0, import_node_crypto.randomUUID)());
1449
+ return claimed2 ? {
1450
+ status: "applied",
1451
+ proposal: claimed2
1452
+ } : {
1453
+ status: "conflict",
1454
+ proposal
1455
+ };
1456
+ });
1457
+ const claimed = result.proposal;
1458
+ if (result.status === "applied" && claimed?.outcome && claimed.outcomeDelivery?.lease) {
1459
+ return {
1460
+ outcome: claimed.outcome,
1461
+ lease: {
1462
+ outcomeId: claimed.outcome.id,
1463
+ token: claimed.outcomeDelivery.lease.token,
1464
+ generation: claimed.outcomeDelivery.generation
1465
+ }
1466
+ };
1467
+ }
1468
+ }
1469
+ return null;
1470
+ }
1471
+ async admitActionProposalOutcome(command) {
1472
+ return this.transactionSteps((db) => this.admissionSteps(db, command));
1473
+ }
1474
+ async transactionSteps(factory) {
1475
+ if (!this.actionProposalAdmissionSupported) throw new Error("Independent actions require a certified transactional Drizzle driver (better-sqlite3, node-postgres, mysql2 or libsql)");
1476
+ if (this.synchronousSqlite) {
1477
+ const database2 = this.rawDb;
1478
+ return database2.transaction((tx) => runSync(factory(asBuilder(tx))), {
1479
+ behavior: "immediate"
1480
+ });
1481
+ }
1482
+ const database = this.rawDb;
1483
+ return database.transaction(async (tx) => runAsync(factory(asBuilder(tx))));
1484
+ }
1485
+ *admissionSteps(db, command) {
1486
+ 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");
1487
+ const table = this.table;
1488
+ const tables = agentTablesFor(this.dialect);
1489
+ if (this.dialect === "sqlite") yield {
1490
+ kind: "write",
1491
+ query: db.update(table).set({
1492
+ version: import_drizzle_orm3.sql`${table.version}`
1493
+ }).where((0, import_drizzle_orm3.eq)(table.outcomeIdKey, physicalId(command.outcomeId)))
1494
+ };
1495
+ const query = db.select().from(table).where((0, import_drizzle_orm3.eq)(table.outcomeIdKey, physicalId(command.outcomeId))).limit(1);
1496
+ const rows = yield {
1497
+ kind: "read",
1498
+ query: lockQuery(query, this.dialect)
1499
+ };
1500
+ const row = rows[0];
1501
+ if (!row || row.proposal.outcome?.id !== command.outcomeId) return {
1502
+ status: "not_found"
1503
+ };
1504
+ const proposal = row.proposal;
1505
+ const outcome = proposal.outcome;
1506
+ const delivery = proposal.outcomeDelivery;
1507
+ if (!outcome || !delivery) return {
1508
+ status: "not_found"
1509
+ };
1510
+ if (proposal.outcomeDelivery?.status === "admitted") return {
1511
+ status: "unchanged",
1512
+ ...proposal.outcomeDelivery.messageId !== void 0 ? {
1513
+ messageId: proposal.outcomeDelivery.messageId
1514
+ } : {}
1515
+ };
1516
+ if (proposal.outcomeDelivery?.status === "discarded") return {
1517
+ status: "discarded"
1518
+ };
1519
+ if (!(0, import_nestjs_agent_core3.actionProposalOutcomeFenceValid)(proposal, command, this.clock())) return {
1520
+ status: "conflict"
1521
+ };
1522
+ const threadQuery = db.select().from(tables.agentThread).where((0, import_drizzle_orm3.eq)(tables.agentThread.id, proposal.threadId)).limit(1);
1523
+ const threads = yield {
1524
+ kind: "read",
1525
+ query: lockQuery(threadQuery, this.dialect)
1526
+ };
1527
+ const thread = threads[0];
1528
+ const now = this.clock();
1529
+ if (!(0, import_nestjs_agent_core3.actionProposalOutcomeFenceValid)(proposal, command, now)) return {
1530
+ status: "conflict"
1531
+ };
1532
+ if (!thread || thread.id !== proposal.threadId || thread.deletedAt || thread.actorRef !== proposal.actorRef || thread.tenantRef !== proposal.tenantRef) {
1533
+ const discarded = {
1534
+ ...proposal,
1535
+ outcomeDelivery: {
1536
+ ...delivery,
1537
+ status: "discarded",
1538
+ lease: null
1539
+ },
1540
+ updatedAt: now
1541
+ };
1542
+ yield {
1543
+ kind: "write",
1544
+ query: db.update(table).set({
1545
+ proposal: discarded,
1546
+ ...discoveryMetadata(discarded),
1547
+ version: row.version + 1
1548
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.id, row.id), (0, import_drizzle_orm3.eq)(table.version, row.version)))
1549
+ };
1550
+ return {
1551
+ status: "discarded"
1552
+ };
1553
+ }
1554
+ if (thread.activeStreamId !== null) return {
1555
+ status: "busy"
1556
+ };
1557
+ const seqRows = yield {
1558
+ kind: "read",
1559
+ query: db.select({
1560
+ last: (0, import_drizzle_orm3.max)(tables.agentMessage.seq)
1561
+ }).from(tables.agentMessage).where((0, import_drizzle_orm3.eq)(tables.agentMessage.threadId, thread.id))
1562
+ };
1563
+ const messageId = physicalId(command.outcomeId);
1564
+ yield {
1565
+ kind: "write",
1566
+ query: db.insert(tables.agentMessage).values({
1567
+ id: messageId,
1568
+ threadId: thread.id,
1569
+ role: "assistant",
1570
+ content: (0, import_nestjs_agent_core3.actionProposalOutcomeText)(outcome),
1571
+ actionProposalOutcome: (0, import_nestjs_agent_core3.canonicalActionProposalJson)(outcome),
1572
+ ui: null,
1573
+ seq: Number(seqRows[0]?.last ?? 0) + 1,
1574
+ createdAt: new Date(now)
1575
+ })
1576
+ };
1577
+ yield {
1578
+ kind: "write",
1579
+ query: db.update(tables.agentThread).set({
1580
+ updatedAt: new Date(now)
1581
+ }).where((0, import_drizzle_orm3.eq)(tables.agentThread.id, thread.id))
1582
+ };
1583
+ const admitted = {
1584
+ ...proposal,
1585
+ outcomeDelivery: {
1586
+ ...delivery,
1587
+ status: "admitted",
1588
+ lease: null,
1589
+ messageId
1590
+ },
1591
+ updatedAt: now
1592
+ };
1593
+ const update = db.update(table).set({
1594
+ proposal: admitted,
1595
+ ...discoveryMetadata(admitted),
1596
+ version: row.version + 1
1597
+ }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(table.id, row.id), (0, import_drizzle_orm3.eq)(table.version, row.version)));
1598
+ const changed = yield {
1599
+ kind: "read",
1600
+ query: this.dialect === "mysql" ? update : update.returning({
1601
+ id: table.id
1602
+ })
1603
+ };
1604
+ const count3 = this.dialect === "mysql" ? mysqlAffectedRows(changed) : changed.length;
1605
+ if (count3 !== 1) throw new Error("Outcome admission lost its locked proposal fence");
1606
+ return {
1607
+ status: "applied",
1608
+ messageId
1609
+ };
1610
+ }
1611
+ async read(scope, id) {
1612
+ 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);
1613
+ return row && row.proposal.id === id && (0, import_nestjs_agent_core3.actionProposalScopeMatches)(row.proposal, scope) ? row : void 0;
1614
+ }
1615
+ async mutate(scope, id, transition) {
1616
+ for (let attempt = 0; attempt < 32; attempt++) {
1617
+ const row2 = await this.read(scope, id);
1618
+ if (!row2) return {
1619
+ status: "not_found"
1620
+ };
1621
+ const result = transition(row2.proposal, this.clock());
1622
+ if (!result.proposal || (0, import_nestjs_agent_core3.canonicalActionProposalJson)(result.proposal) === (0, import_nestjs_agent_core3.canonicalActionProposalJson)(row2.proposal)) return result;
1623
+ const changed = await affectedRows(this.dialect, this.db.update(this.table).set({
1624
+ proposal: result.proposal,
1625
+ decision: result.proposal.decision,
1626
+ ...discoveryMetadata(result.proposal),
1627
+ version: row2.version + 1
1628
+ }).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);
1629
+ if (changed === 1) return result;
1630
+ }
1631
+ const row = await this.read(scope, id);
1632
+ return row ? {
1633
+ status: "conflict",
1634
+ proposal: row.proposal
1635
+ } : {
1636
+ status: "not_found"
1637
+ };
1638
+ }
1639
+ };
1640
+ function scopeKey(scope) {
1641
+ return (0, import_node_crypto.createHash)("sha256").update((0, import_nestjs_agent_core3.canonicalActionProposalJson)([
1642
+ scope.tenantRef,
1643
+ scope.actorRef,
1644
+ scope.threadId
1645
+ ])).digest("hex");
1646
+ }
1647
+ __name(scopeKey, "scopeKey");
1648
+ function physicalId(id) {
1649
+ return (0, import_node_crypto.createHash)("sha256").update((0, import_nestjs_agent_core3.canonicalActionProposalJson)(id)).digest("hex");
1650
+ }
1651
+ __name(physicalId, "physicalId");
1652
+ function logicalSort(id) {
1653
+ let sort = "";
1654
+ for (let index4 = 0; index4 < id.length; index4++) sort += id.charCodeAt(index4).toString(16).padStart(4, "0");
1655
+ return sort;
1656
+ }
1657
+ __name(logicalSort, "logicalSort");
1658
+ function discoveryMetadata(proposal) {
1659
+ return {
1660
+ replacementGroupKey: replacementGroupKey(proposal),
1661
+ deliveryStatus: proposal.outcomeDelivery?.status ?? null,
1662
+ deliveryLeaseExpiresAt: proposal.outcomeDelivery?.lease?.expiresAt ?? null,
1663
+ outcomeIdKey: proposal.outcome ? physicalId(proposal.outcome.id) : null,
1664
+ executionStatus: proposal.execution?.status ?? null,
1665
+ leaseExpiresAt: proposal.execution?.lease?.expiresAt ?? null,
1666
+ proposalExpiresAt: proposal.expiresAt,
1667
+ discoveryIndexVersion: 1
1668
+ };
1669
+ }
1670
+ __name(discoveryMetadata, "discoveryMetadata");
1671
+ function lockQuery(query, dialect) {
1672
+ return dialect === "sqlite" ? query : query.for("update");
1673
+ }
1674
+ __name(lockQuery, "lockQuery");
1675
+ function runSync(steps) {
1676
+ let next = steps.next();
1677
+ while (!next.done) {
1678
+ const { kind, query } = next.value;
1679
+ const statement = query;
1680
+ next = steps.next(kind === "read" ? statement.all() : statement.run());
1681
+ }
1682
+ return next.value;
1683
+ }
1684
+ __name(runSync, "runSync");
1685
+ async function runAsync(steps) {
1686
+ let next = steps.next();
1687
+ while (!next.done) next = steps.next(await next.value.query);
1688
+ return next.value;
1689
+ }
1690
+ __name(runAsync, "runAsync");
1691
+ function replacementGroupKey(proposal) {
1692
+ return proposal.replacementKey ? physicalId((0, import_nestjs_agent_core3.canonicalActionProposalJson)([
1693
+ proposal.toolName,
1694
+ proposal.replacementKey
1695
+ ])) : null;
1696
+ }
1697
+ __name(replacementGroupKey, "replacementGroupKey");
1698
+
1699
+ // src/drizzle-agent-store.ts
1055
1700
  function turnMessageColumns(message) {
1056
1701
  return {
1057
1702
  id: message.id,
@@ -1072,11 +1717,61 @@ var DrizzleAgentStore = class {
1072
1717
  db;
1073
1718
  dialect;
1074
1719
  t;
1075
- constructor(db) {
1720
+ proposals;
1721
+ constructor(db, options = {}) {
1722
+ this.proposals = new DrizzleActionProposalStore(db, options);
1076
1723
  this.dialect = agentDialectOf(db);
1077
1724
  this.t = agentTablesFor(this.dialect);
1078
1725
  this.db = asBuilder(db);
1079
1726
  }
1727
+ createActionProposal(...args) {
1728
+ return this.proposals.createActionProposal(...args);
1729
+ }
1730
+ getActionProposal(...args) {
1731
+ return this.proposals.getActionProposal(...args);
1732
+ }
1733
+ listActionProposals(...args) {
1734
+ return this.proposals.listActionProposals(...args);
1735
+ }
1736
+ decideActionProposal(...args) {
1737
+ return this.proposals.decideActionProposal(...args);
1738
+ }
1739
+ claimActionProposal(...args) {
1740
+ return this.proposals.claimActionProposal(...args);
1741
+ }
1742
+ extendActionProposalLease(...args) {
1743
+ return this.proposals.extendActionProposalLease(...args);
1744
+ }
1745
+ claimNextActionProposal(...args) {
1746
+ return this.proposals.claimNextActionProposal(...args);
1747
+ }
1748
+ expireActionProposals(...args) {
1749
+ return this.proposals.expireActionProposals(...args);
1750
+ }
1751
+ backfillActionProposalDiscoveryIndex(command) {
1752
+ return this.proposals.backfillActionProposalDiscoveryIndex(command);
1753
+ }
1754
+ settleActionProposal(...args) {
1755
+ return this.proposals.settleActionProposal(...args);
1756
+ }
1757
+ createReplacingActionProposal(...args) {
1758
+ return this.proposals.createReplacingActionProposal(...args);
1759
+ }
1760
+ supersedeActionProposal(...args) {
1761
+ return this.proposals.supersedeActionProposal(...args);
1762
+ }
1763
+ get actionProposalAdmissionSupported() {
1764
+ return this.proposals.actionProposalAdmissionSupported;
1765
+ }
1766
+ getThreadActionProposalScope(threadId) {
1767
+ return this.proposals.getThreadActionProposalScope(threadId);
1768
+ }
1769
+ claimNextActionProposalOutcome(...args) {
1770
+ return this.proposals.claimNextActionProposalOutcome(...args);
1771
+ }
1772
+ admitActionProposalOutcome(...args) {
1773
+ return this.proposals.admitActionProposalOutcome(...args);
1774
+ }
1080
1775
  async createThread(input) {
1081
1776
  const now = /* @__PURE__ */ new Date();
1082
1777
  const thread = {
@@ -1098,11 +1793,11 @@ var DrizzleAgentStore = class {
1098
1793
  return this.toSummary(thread);
1099
1794
  }
1100
1795
  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)));
1796
+ 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
1797
  if (thread === void 0) {
1103
1798
  return null;
1104
1799
  }
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());
1800
+ 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
1801
  const last = messages[messages.length - 1];
1107
1802
  const approvals = await this.approvalsFor(messages.map((message) => message.id));
1108
1803
  return {
@@ -1137,14 +1832,14 @@ var DrizzleAgentStore = class {
1137
1832
  const [thread] = await this.db.select({
1138
1833
  title: this.t.agentThread.title,
1139
1834
  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)));
1835
+ }).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
1836
  if (thread === void 0) {
1142
1837
  return null;
1143
1838
  }
1144
1839
  const messages = await this.loadTurnWindow(query.threadId, query.messageLimit);
1145
1840
  const [answered] = await this.db.select({
1146
1841
  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);
1842
+ }).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
1843
  return {
1149
1844
  title: thread.title,
1150
1845
  defaultAgent: thread.defaultAgent,
@@ -1160,15 +1855,15 @@ var DrizzleAgentStore = class {
1160
1855
  if (limit !== void 0 && limit <= 0) {
1161
1856
  return [];
1162
1857
  }
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());
1858
+ 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
1859
  const rows = limit === void 0 ? await window : await window.limit(limit);
1165
1860
  return rows.reverse().map((row) => this.toStoredMessage(row));
1166
1861
  }
1167
1862
  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);
1863
+ 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
1864
  const summaries = [];
1170
1865
  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);
1866
+ 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
1867
  summaries.push(this.toSummary(thread, last?.content));
1173
1868
  }
1174
1869
  return summaries;
@@ -1176,14 +1871,14 @@ var DrizzleAgentStore = class {
1176
1871
  async softDeleteThread(threadId) {
1177
1872
  await this.db.update(this.t.agentThread).set({
1178
1873
  deletedAt: /* @__PURE__ */ new Date()
1179
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
1874
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1180
1875
  }
1181
1876
  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));
1877
+ const [source] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1183
1878
  if (source === void 0) {
1184
1879
  throw new Error(`thread ${threadId} not found`);
1185
1880
  }
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());
1881
+ 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
1882
  const cutoff = messages.findIndex((message) => message.id === fromMessageId);
1188
1883
  const kept = cutoff >= 0 ? messages.slice(0, cutoff + 1) : messages;
1189
1884
  const now = /* @__PURE__ */ new Date();
@@ -1226,6 +1921,7 @@ var DrizzleAgentStore = class {
1226
1921
  reasoning: message.reasoning,
1227
1922
  reasoningMs: message.reasoningMs,
1228
1923
  ui: message.ui,
1924
+ actionProposalOutcome: message.actionProposalOutcome,
1229
1925
  createdAt: message.createdAt
1230
1926
  })));
1231
1927
  }
@@ -1234,20 +1930,20 @@ var DrizzleAgentStore = class {
1234
1930
  async ownerOfThread(threadId) {
1235
1931
  const [thread] = await this.db.select({
1236
1932
  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)));
1933
+ }).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
1934
  return thread?.actorRef ?? null;
1239
1935
  }
1240
1936
  async ownerOfToolCall(toolCallId) {
1241
1937
  const [row] = await this.db.select({
1242
1938
  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));
1939
+ }).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
1940
  return row?.actorRef ?? null;
1245
1941
  }
1246
1942
  async runForToolCall(toolCallId) {
1247
1943
  const [row] = await this.db.select({
1248
1944
  runId: this.t.agentToolCall.runId,
1249
1945
  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));
1946
+ }).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
1947
  return row?.runId ?? row?.activeStreamId ?? null;
1252
1948
  }
1253
1949
  /**
@@ -1265,14 +1961,15 @@ var DrizzleAgentStore = class {
1265
1961
  messageId: this.t.agentToolCall.messageId,
1266
1962
  status: this.t.agentToolCall.status,
1267
1963
  approver: this.t.agentToolCall.approver,
1964
+ confirmation: this.t.agentToolCall.confirmation,
1268
1965
  expiresAt: this.t.agentToolCall.expiresAt,
1269
1966
  remember: this.t.agentToolCall.remember,
1270
1967
  executedByRef: this.t.agentToolCall.executedByRef,
1271
1968
  decidedVia: this.t.agentToolCall.decidedVia,
1272
1969
  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));
1970
+ }).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
1971
  for (const row of rows) {
1275
- const approval = (0, import_nestjs_agent_core.toolCallApprovalFromRow)({
1972
+ const approval = (0, import_nestjs_agent_core4.toolCallApprovalFromRow)({
1276
1973
  ...row,
1277
1974
  toolCallId: row.id
1278
1975
  });
@@ -1289,13 +1986,20 @@ var DrizzleAgentStore = class {
1289
1986
  async rememberedApprovals(threadId) {
1290
1987
  const rows = await this.db.selectDistinct({
1291
1988
  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);
1989
+ }).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)));
1990
+ const scope = await this.getThreadActionProposalScope(threadId);
1991
+ const proposalNames = scope ? await this.proposals.rememberedActionProposalApprovals(scope) : [];
1992
+ return [
1993
+ .../* @__PURE__ */ new Set([
1994
+ ...rows.map((row) => row.toolName),
1995
+ ...proposalNames
1996
+ ])
1997
+ ];
1294
1998
  }
1295
1999
  async toolCallInput(toolCallId) {
1296
2000
  const [row] = await this.db.select({
1297
2001
  input: this.t.agentToolCall.input
1298
- }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
2002
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.id, toolCallId));
1299
2003
  return row?.input ?? null;
1300
2004
  }
1301
2005
  async toolCallApproval(toolCallId) {
@@ -1303,7 +2007,7 @@ var DrizzleAgentStore = class {
1303
2007
  status: this.t.agentToolCall.status,
1304
2008
  approver: this.t.agentToolCall.approver,
1305
2009
  expiresAt: this.t.agentToolCall.expiresAt
1306
- }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, toolCallId));
2010
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.id, toolCallId));
1307
2011
  if (row === void 0) {
1308
2012
  return null;
1309
2013
  }
@@ -1316,26 +2020,26 @@ var DrizzleAgentStore = class {
1316
2020
  async ownerOfActiveStream(runId) {
1317
2021
  const [thread] = await this.db.select({
1318
2022
  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)));
2023
+ }).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
2024
  return thread?.actorRef ?? null;
1321
2025
  }
1322
2026
  async setTitle(threadId, title) {
1323
2027
  await this.db.update(this.t.agentThread).set({
1324
2028
  title,
1325
2029
  updatedAt: /* @__PURE__ */ new Date()
1326
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2030
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1327
2031
  }
1328
2032
  async promoteThread(threadId) {
1329
2033
  await this.db.update(this.t.agentThread).set({
1330
2034
  transient: false,
1331
2035
  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)));
2036
+ }).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
2037
  }
1334
2038
  /** Who holds the thread's stream right now, deleted or not. */
1335
2039
  async activeHolder(threadId) {
1336
2040
  const [thread] = await this.db.select({
1337
2041
  activeStreamId: this.t.agentThread.activeStreamId
1338
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2042
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1339
2043
  return thread?.activeStreamId ?? null;
1340
2044
  }
1341
2045
  /**
@@ -1347,18 +2051,18 @@ var DrizzleAgentStore = class {
1347
2051
  messageOrder() {
1348
2052
  const message = this.t.agentMessage;
1349
2053
  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)
2054
+ (0, import_drizzle_orm4.asc)(import_drizzle_orm4.sql`coalesce(${message.seq}, 0)`),
2055
+ (0, import_drizzle_orm4.asc)(message.createdAt),
2056
+ (0, import_drizzle_orm4.asc)(message.id)
1353
2057
  ];
1354
2058
  }
1355
2059
  /** {@link messageOrder}, newest first. */
1356
2060
  messageOrderNewestFirst() {
1357
2061
  const message = this.t.agentMessage;
1358
2062
  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)
2063
+ (0, import_drizzle_orm4.desc)(import_drizzle_orm4.sql`coalesce(${message.seq}, 0)`),
2064
+ (0, import_drizzle_orm4.desc)(message.createdAt),
2065
+ (0, import_drizzle_orm4.desc)(message.id)
1362
2066
  ];
1363
2067
  }
1364
2068
  /**
@@ -1367,15 +2071,15 @@ var DrizzleAgentStore = class {
1367
2071
  */
1368
2072
  async nextMessageSeq(threadId) {
1369
2073
  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));
2074
+ last: (0, import_drizzle_orm4.max)(this.t.agentMessage.seq)
2075
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.threadId, threadId));
1372
2076
  return Number(row?.last ?? 0) + 1;
1373
2077
  }
1374
2078
  /** The run streaming the thread, or `null` — a projection of the one column. */
1375
2079
  async activeRunForThread(threadId) {
1376
2080
  const [thread] = await this.db.select({
1377
2081
  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)));
2082
+ }).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
2083
  return thread?.activeStreamId ?? null;
1380
2084
  }
1381
2085
  /**
@@ -1384,15 +2088,15 @@ var DrizzleAgentStore = class {
1384
2088
  */
1385
2089
  async claimActiveStream(threadId, runId, options = {}) {
1386
2090
  const holders = [
1387
- (0, import_drizzle_orm3.isNull)(this.t.agentThread.activeStreamId),
1388
- (0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, runId),
2091
+ (0, import_drizzle_orm4.isNull)(this.t.agentThread.activeStreamId),
2092
+ (0, import_drizzle_orm4.eq)(this.t.agentThread.activeStreamId, runId),
1389
2093
  ...options.replacing !== void 0 ? [
1390
- (0, import_drizzle_orm3.eq)(this.t.agentThread.activeStreamId, options.replacing)
2094
+ (0, import_drizzle_orm4.eq)(this.t.agentThread.activeStreamId, options.replacing)
1391
2095
  ] : []
1392
2096
  ];
1393
2097
  const claimed = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
1394
2098
  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);
2099
+ }).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
2100
  if (claimed > 0) {
1397
2101
  return true;
1398
2102
  }
@@ -1401,21 +2105,22 @@ var DrizzleAgentStore = class {
1401
2105
  async releaseActiveStream(threadId, runId) {
1402
2106
  const released = await affectedRows(this.dialect, this.db.update(this.t.agentThread).set({
1403
2107
  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);
2108
+ }).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
2109
  return released > 0;
1406
2110
  }
1407
2111
  async enqueueMessage(input) {
1408
2112
  const now = /* @__PURE__ */ new Date();
1409
2113
  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));
2114
+ first: (0, import_drizzle_orm4.min)(this.t.agentQueuedMessage.position),
2115
+ last: (0, import_drizzle_orm4.max)(this.t.agentQueuedMessage.position)
2116
+ }).from(this.t.agentQueuedMessage).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.threadId, input.threadId));
1413
2117
  const position = input.at === "head" ? (edge?.first ?? 1) - 1 : (edge?.last ?? -1) + 1;
1414
2118
  const row = {
1415
2119
  id: crypto.randomUUID(),
1416
2120
  threadId: input.threadId,
1417
2121
  actor: input.actor,
1418
2122
  content: input.content,
2123
+ uiCapabilities: input.uiCapabilities ?? null,
1419
2124
  attachments: input.attachments !== void 0 && input.attachments.length > 0 ? input.attachments : null,
1420
2125
  agentName: input.agentName ?? null,
1421
2126
  persona: input.persona ?? null,
@@ -1430,11 +2135,11 @@ var DrizzleAgentStore = class {
1430
2135
  return toQueuedMessage(row);
1431
2136
  }
1432
2137
  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));
2138
+ 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
2139
  return rows.map(toQueuedMessage);
1435
2140
  }
1436
2141
  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));
2142
+ const [row] = await this.db.select().from(this.t.agentQueuedMessage).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.id, id));
1438
2143
  return row === void 0 ? null : toQueuedMessage(row);
1439
2144
  }
1440
2145
  async updateQueuedMessage(id, patch) {
@@ -1450,7 +2155,7 @@ var DrizzleAgentStore = class {
1450
2155
  if (patch.interrupt !== void 0) {
1451
2156
  updates.interrupt = patch.interrupt;
1452
2157
  }
1453
- await this.db.update(this.t.agentQueuedMessage).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, id));
2158
+ await this.db.update(this.t.agentQueuedMessage).set(updates).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.id, id));
1454
2159
  return this.getQueuedMessage(id);
1455
2160
  }
1456
2161
  /** Rewrites the thread's positions as 0..n-1 in the new order — a queue is a handful of rows. */
@@ -1465,32 +2170,32 @@ var DrizzleAgentStore = class {
1465
2170
  for (const [position, message] of order.entries()) {
1466
2171
  await this.db.update(this.t.agentQueuedMessage).set({
1467
2172
  position
1468
- }).where((0, import_drizzle_orm3.eq)(this.t.agentQueuedMessage.id, message.id));
2173
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentQueuedMessage.id, message.id));
1469
2174
  }
1470
2175
  return true;
1471
2176
  }
1472
2177
  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);
2178
+ 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
2179
  return removed > 0;
1475
2180
  }
1476
2181
  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);
2182
+ 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
2183
  }
1479
2184
  async queuePause(threadId) {
1480
2185
  const [thread] = await this.db.select({
1481
2186
  queuePause: this.t.agentThread.queuePause
1482
- }).from(this.t.agentThread).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2187
+ }).from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1483
2188
  return thread?.queuePause ?? null;
1484
2189
  }
1485
2190
  async setQueuePause(threadId, pause) {
1486
2191
  await this.db.update(this.t.agentThread).set({
1487
2192
  queuePause: pause
1488
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2193
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1489
2194
  }
1490
2195
  async setActiveStream(threadId, runId) {
1491
2196
  await this.db.update(this.t.agentThread).set({
1492
2197
  activeStreamId: runId
1493
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, threadId));
2198
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1494
2199
  }
1495
2200
  /**
1496
2201
  * Patch a thread's `title` and/or `defaultAgent`. Each field is only touched when PRESENT in
@@ -1516,7 +2221,7 @@ var DrizzleAgentStore = class {
1516
2221
  return;
1517
2222
  }
1518
2223
  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));
2224
+ await this.db.update(this.t.agentThread).set(updates).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, threadId));
1520
2225
  }
1521
2226
  /**
1522
2227
  * The thread's default agent, projected — the caller wants one nullable scalar to decide which
@@ -1527,20 +2232,20 @@ var DrizzleAgentStore = class {
1527
2232
  async modelForThread(threadId) {
1528
2233
  const [thread] = await this.db.select({
1529
2234
  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)));
2235
+ }).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
2236
  return thread?.model ?? null;
1532
2237
  }
1533
2238
  /** The thread's pinned persona, projected like {@link defaultAgentForThread}. */
1534
2239
  async personaForThread(threadId) {
1535
2240
  const [thread] = await this.db.select({
1536
2241
  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)));
2242
+ }).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
2243
  return thread?.persona ?? null;
1539
2244
  }
1540
2245
  async defaultAgentForThread(threadId) {
1541
2246
  const [thread] = await this.db.select({
1542
2247
  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)));
2248
+ }).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
2249
  return thread?.defaultAgent ?? null;
1545
2250
  }
1546
2251
  /**
@@ -1582,16 +2287,16 @@ var DrizzleAgentStore = class {
1582
2287
  if (end.errorMessage !== void 0) {
1583
2288
  updates.errorMessage = end.errorMessage;
1584
2289
  }
1585
- await this.db.update(this.t.agentRun).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentRun.id, end.runId));
2290
+ await this.db.update(this.t.agentRun).set(updates).where((0, import_drizzle_orm4.eq)(this.t.agentRun.id, end.runId));
1586
2291
  }
1587
2292
  /** Bump the run's llm-step retry counter. Atomic `retries = retries + 1`, no read-modify-write. */
1588
2293
  async bumpRunRetries(runId) {
1589
2294
  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));
2295
+ retries: import_drizzle_orm4.sql`${this.t.agentRun.retries} + 1`
2296
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentRun.id, runId));
1592
2297
  }
1593
2298
  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));
2299
+ const [thread] = await this.db.select().from(this.t.agentThread).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, input.threadId));
1595
2300
  if (thread === void 0) {
1596
2301
  throw new Error(`thread ${input.threadId} not found`);
1597
2302
  }
@@ -1601,6 +2306,7 @@ var DrizzleAgentStore = class {
1601
2306
  threadId: input.threadId,
1602
2307
  role: input.role,
1603
2308
  content: input.content,
2309
+ actionProposalOutcome: input.actionProposalOutcome ? (0, import_nestjs_agent_core4.canonicalActionProposalJson)(input.actionProposalOutcome) : null,
1604
2310
  toolCalls: input.toolCalls ?? null,
1605
2311
  toolResults: input.toolResults ?? null,
1606
2312
  attachments: input.attachments ?? null,
@@ -1619,43 +2325,44 @@ var DrizzleAgentStore = class {
1619
2325
  await this.db.insert(this.t.agentMessage).values(message);
1620
2326
  await this.db.update(this.t.agentThread).set({
1621
2327
  updatedAt: now
1622
- }).where((0, import_drizzle_orm3.eq)(this.t.agentThread.id, input.threadId));
2328
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentThread.id, input.threadId));
1623
2329
  return this.toStoredMessage(message);
1624
2330
  }
1625
2331
  async setMessageToolResults(messageId, results) {
1626
2332
  await this.db.update(this.t.agentMessage).set({
1627
2333
  toolResults: results
1628
- }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
2334
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.id, messageId));
1629
2335
  }
1630
2336
  async setMessageUi(messageId, ui) {
1631
2337
  await this.db.update(this.t.agentMessage).set({
1632
2338
  ui: ui.length > 0 ? ui : null
1633
- }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
2339
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.id, messageId));
1634
2340
  }
1635
2341
  async threadOfMessage(messageId) {
1636
2342
  const [row] = await this.db.select({
1637
2343
  threadId: this.t.agentMessage.threadId
1638
- }).from(this.t.agentMessage).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId)).limit(1);
2344
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.id, messageId)).limit(1);
1639
2345
  return row?.threadId ?? null;
1640
2346
  }
1641
2347
  async setMessageFeedback(messageId, feedback) {
1642
2348
  await this.db.update(this.t.agentMessage).set({
1643
2349
  feedback
1644
- }).where((0, import_drizzle_orm3.eq)(this.t.agentMessage.id, messageId));
2350
+ }).where((0, import_drizzle_orm4.eq)(this.t.agentMessage.id, messageId));
1645
2351
  }
1646
2352
  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());
2353
+ 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
2354
  const cutoff = messages.findIndex((message) => message.id === messageId);
1649
2355
  if (cutoff < 0) {
1650
2356
  return;
1651
2357
  }
1652
2358
  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));
2359
+ await this.db.delete(this.t.agentToolCall).where((0, import_drizzle_orm4.inArray)(this.t.agentToolCall.messageId, doomedIds));
2360
+ await this.db.delete(this.t.agentMessage).where((0, import_drizzle_orm4.inArray)(this.t.agentMessage.id, doomedIds));
1655
2361
  }
1656
2362
  async recordToolCall(input) {
1657
2363
  await this.db.insert(this.t.agentToolCall).values({
1658
2364
  id: input.toolCallId,
2365
+ proposalId: input.proposalId ?? null,
1659
2366
  messageId: input.messageId,
1660
2367
  toolName: input.toolName,
1661
2368
  toolType: input.toolType,
@@ -1669,6 +2376,7 @@ var DrizzleAgentStore = class {
1669
2376
  executedAt: null,
1670
2377
  runId: input.runId ?? null,
1671
2378
  approver: input.approver ?? null,
2379
+ confirmation: input.confirmation ?? null,
1672
2380
  expiresAt: input.expiresAt !== void 0 ? new Date(input.expiresAt) : null,
1673
2381
  remember: null,
1674
2382
  decidedVia: null
@@ -1699,7 +2407,7 @@ var DrizzleAgentStore = class {
1699
2407
  if (input.status === "executed" || input.status === "auto_executed") {
1700
2408
  updates.executedAt = /* @__PURE__ */ new Date();
1701
2409
  }
1702
- await this.db.update(this.t.agentToolCall).set(updates).where((0, import_drizzle_orm3.eq)(this.t.agentToolCall.id, input.toolCallId));
2410
+ await this.db.update(this.t.agentToolCall).set(updates).where((0, import_drizzle_orm4.eq)(this.t.agentToolCall.id, input.toolCallId));
1703
2411
  }
1704
2412
  async toolCallOutcomes(toolCallIds) {
1705
2413
  if (toolCallIds.length === 0) {
@@ -1710,7 +2418,7 @@ var DrizzleAgentStore = class {
1710
2418
  status: this.t.agentToolCall.status,
1711
2419
  output: this.t.agentToolCall.output,
1712
2420
  error: this.t.agentToolCall.error
1713
- }).from(this.t.agentToolCall).where((0, import_drizzle_orm3.inArray)(this.t.agentToolCall.id, [
2421
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm4.inArray)(this.t.agentToolCall.id, [
1714
2422
  ...toolCallIds
1715
2423
  ]));
1716
2424
  return rows.map((row) => ({
@@ -1725,7 +2433,7 @@ var DrizzleAgentStore = class {
1725
2433
  }));
1726
2434
  }
1727
2435
  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"));
2436
+ 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
2437
  const rows = await this.db.select({
1730
2438
  id: this.t.agentToolCall.id
1731
2439
  }).from(this.t.agentToolCall).where(pending);
@@ -1758,10 +2466,10 @@ var DrizzleAgentStore = class {
1758
2466
  }
1759
2467
  const rows = await this.db.select({
1760
2468
  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)));
2469
+ }).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
2470
  const queued = await this.db.select({
1763
2471
  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)));
2472
+ }).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
2473
  const wanted = new Set(mediaIds);
1766
2474
  const found = /* @__PURE__ */ new Set();
1767
2475
  for (const row of [
@@ -1800,7 +2508,7 @@ var DrizzleAgentStore = class {
1800
2508
  async usageBetween(actorRef, fromDay, toDay) {
1801
2509
  const start = /* @__PURE__ */ new Date(`${fromDay}T00:00:00.000Z`);
1802
2510
  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)));
2511
+ 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
2512
  const usedTokens = rows.reduce((sum2, row) => sum2 + row.inputTokens + row.outputTokens, 0);
1805
2513
  const costUsd = rows.reduce((sum2, row) => sum2 + (row.costUsd ?? 0), 0);
1806
2514
  return {
@@ -1826,7 +2534,12 @@ var DrizzleAgentStore = class {
1826
2534
  };
1827
2535
  }
1828
2536
  toStoredMessage(message) {
2537
+ const outcome = message.actionProposalOutcome ? JSON.parse(message.actionProposalOutcome) : void 0;
1829
2538
  return {
2539
+ ...outcome ? {
2540
+ actionProposalOutcome: outcome,
2541
+ ui: outcome.ui
2542
+ } : {},
1830
2543
  id: message.id,
1831
2544
  role: message.role,
1832
2545
  content: message.content,
@@ -1872,6 +2585,9 @@ var DrizzleAgentStore = class {
1872
2585
  };
1873
2586
  function toQueuedMessage(row) {
1874
2587
  return {
2588
+ ...row.uiCapabilities !== null ? {
2589
+ uiCapabilities: row.uiCapabilities
2590
+ } : {},
1875
2591
  id: row.id,
1876
2592
  threadId: row.threadId,
1877
2593
  actor: row.actor,
@@ -1901,8 +2617,8 @@ function toQueuedMessage(row) {
1901
2617
  __name(toQueuedMessage, "toQueuedMessage");
1902
2618
 
1903
2619
  // src/drizzle-governance-queries.ts
1904
- var import_nestjs_agent_core2 = require("@dudousxd/nestjs-agent-core");
1905
- var import_drizzle_orm4 = require("drizzle-orm");
2620
+ var import_nestjs_agent_core5 = require("@dudousxd/nestjs-agent-core");
2621
+ var import_drizzle_orm5 = require("drizzle-orm");
1906
2622
  var UNCLASSIFIED_ERROR_CODE = "unknown";
1907
2623
  var DEFAULT_AGENT_BUCKET = "(default)";
1908
2624
  var TOOL_CALL_STATUSES = [
@@ -1937,14 +2653,14 @@ function isRunStatus(value) {
1937
2653
  }
1938
2654
  __name(isRunStatus, "isRunStatus");
1939
2655
  function dayStartUtc(day) {
1940
- return (0, import_nestjs_agent_core2.dayBoundsUtc)({
2656
+ return (0, import_nestjs_agent_core5.dayBoundsUtc)({
1941
2657
  fromDay: day,
1942
2658
  toDay: day
1943
2659
  }).start;
1944
2660
  }
1945
2661
  __name(dayStartUtc, "dayStartUtc");
1946
2662
  function dayEndUtc(day) {
1947
- return (0, import_nestjs_agent_core2.dayBoundsUtc)({
2663
+ return (0, import_nestjs_agent_core5.dayBoundsUtc)({
1948
2664
  fromDay: day,
1949
2665
  toDay: day
1950
2666
  }).end;
@@ -2039,17 +2755,17 @@ var DrizzleGovernanceQueries = class {
2039
2755
  return pricing;
2040
2756
  }
2041
2757
  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)));
2758
+ const { start, end } = (0, import_nestjs_agent_core5.dayBoundsUtc)(range);
2759
+ 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
2760
  return rows.map(toUsageInput);
2045
2761
  }
2046
2762
  async spendByModel(range) {
2047
2763
  const pricing = await this.loadPricing();
2048
- return (0, import_nestjs_agent_core2.bucketByModel)(await this.usageInRange(range), pricing);
2764
+ return (0, import_nestjs_agent_core5.bucketByModel)(await this.usageInRange(range), pricing);
2049
2765
  }
2050
2766
  async spendByActor(range) {
2051
2767
  const pricing = await this.loadPricing();
2052
- return (0, import_nestjs_agent_core2.bucketByActor)(await this.usageInRange(range), pricing);
2768
+ return (0, import_nestjs_agent_core5.bucketByActor)(await this.usageInRange(range), pricing);
2053
2769
  }
2054
2770
  /**
2055
2771
  * Top threads by spend within the range, highest cost first, capped at `limit`. Usage rows for a
@@ -2065,7 +2781,7 @@ var DrizzleGovernanceQueries = class {
2065
2781
  if (threadIds.length === 0) {
2066
2782
  return [];
2067
2783
  }
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)));
2784
+ 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
2785
  const threadsById = new Map(threads.map((thread) => [
2070
2786
  thread.id,
2071
2787
  {
@@ -2073,14 +2789,14 @@ var DrizzleGovernanceQueries = class {
2073
2789
  actorRef: thread.actorRef
2074
2790
  }
2075
2791
  ]));
2076
- return (0, import_nestjs_agent_core2.bucketByThread)(rows, pricing, threadsById, {
2792
+ return (0, import_nestjs_agent_core5.bucketByThread)(rows, pricing, threadsById, {
2077
2793
  limit,
2078
2794
  includeUnknownThreads: false
2079
2795
  });
2080
2796
  }
2081
2797
  async usageTrend(range) {
2082
2798
  const pricing = await this.loadPricing();
2083
- return (0, import_nestjs_agent_core2.bucketUsageTrend)(await this.usageInRange(range), pricing);
2799
+ return (0, import_nestjs_agent_core5.bucketUsageTrend)(await this.usageInRange(range), pricing);
2084
2800
  }
2085
2801
  async recentToolCalls(limit) {
2086
2802
  const rows = await this.db.select({
@@ -2091,7 +2807,7 @@ var DrizzleGovernanceQueries = class {
2091
2807
  threadId: this.t.agentMessage.threadId,
2092
2808
  createdAt: this.t.agentToolCall.createdAt,
2093
2809
  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);
2810
+ }).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
2811
  return rows.map((row) => ({
2096
2812
  toolCallId: row.toolCallId,
2097
2813
  toolName: row.toolName,
@@ -2120,8 +2836,8 @@ var DrizzleGovernanceQueries = class {
2120
2836
  }
2121
2837
  const messageCounts = await this.db.select({
2122
2838
  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);
2839
+ value: (0, import_drizzle_orm5.count)()
2840
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm5.inArray)(this.t.agentMessage.threadId, threadIds)).groupBy(this.t.agentMessage.threadId);
2125
2841
  for (const row of messageCounts) {
2126
2842
  const bucket = rollups.get(row.threadId);
2127
2843
  if (bucket !== void 0) {
@@ -2130,9 +2846,9 @@ var DrizzleGovernanceQueries = class {
2130
2846
  }
2131
2847
  const usageTotals = await this.db.select({
2132
2848
  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);
2849
+ inputTokens: (0, import_drizzle_orm5.sum)(this.t.agentTokenUsage.inputTokens),
2850
+ outputTokens: (0, import_drizzle_orm5.sum)(this.t.agentTokenUsage.outputTokens)
2851
+ }).from(this.t.agentTokenUsage).where((0, import_drizzle_orm5.inArray)(this.t.agentTokenUsage.threadId, threadIds)).groupBy(this.t.agentTokenUsage.threadId);
2136
2852
  for (const row of usageTotals) {
2137
2853
  const bucket = rollups.get(row.threadId);
2138
2854
  if (bucket !== void 0) {
@@ -2157,12 +2873,12 @@ var DrizzleGovernanceQueries = class {
2157
2873
  });
2158
2874
  }
2159
2875
  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);
2876
+ 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
2877
  return this.toThreadActivityRows(threads);
2162
2878
  }
2163
2879
  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)));
2880
+ const { start, end } = (0, import_nestjs_agent_core5.dayBoundsUtc)(range);
2881
+ 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
2882
  }
2167
2883
  async runMetrics(range) {
2168
2884
  const runs = await this.runsInRange(range);
@@ -2218,8 +2934,8 @@ var DrizzleGovernanceQueries = class {
2218
2934
  return result;
2219
2935
  }
2220
2936
  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")));
2937
+ const { start, end } = (0, import_nestjs_agent_core5.dayBoundsUtc)(range);
2938
+ 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
2939
  const byError = /* @__PURE__ */ new Map();
2224
2940
  for (const run of runs) {
2225
2941
  const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;
@@ -2259,7 +2975,7 @@ var DrizzleGovernanceQueries = class {
2259
2975
  return result;
2260
2976
  }
2261
2977
  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);
2978
+ 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
2979
  return runs.map(toRecentRunRow);
2264
2980
  }
2265
2981
  /**
@@ -2278,7 +2994,7 @@ var DrizzleGovernanceQueries = class {
2278
2994
  agentName: this.t.agentMessage.agentName,
2279
2995
  requestedAt: this.t.agentToolCall.createdAt,
2280
2996
  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);
2997
+ }).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
2998
  return rows.map((row) => ({
2283
2999
  toolCallId: row.toolCallId,
2284
3000
  toolName: row.toolName,
@@ -2299,8 +3015,8 @@ var DrizzleGovernanceQueries = class {
2299
3015
  * `PERCENTILE_CONT` and one portable implementation beats three dialect-specific ones.
2300
3016
  */
2301
3017
  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)));
3018
+ const { start, end } = (0, import_nestjs_agent_core5.dayBoundsUtc)(range);
3019
+ 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
3020
  const byTool = /* @__PURE__ */ new Map();
2305
3021
  for (const call of calls) {
2306
3022
  const key2 = `${call.toolName} ${call.toolType}`;
@@ -2350,10 +3066,10 @@ var DrizzleGovernanceQueries = class {
2350
3066
  if (filters?.toolType !== void 0 && !isToolKind(filters.toolType)) {
2351
3067
  return emptyPage(query);
2352
3068
  }
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);
3069
+ 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
3070
  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);
3071
+ value: (0, import_drizzle_orm5.count)()
3072
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, (0, import_drizzle_orm5.eq)(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause);
2357
3073
  const rows = await this.db.select({
2358
3074
  toolCallId: this.t.agentToolCall.id,
2359
3075
  toolName: this.t.agentToolCall.toolName,
@@ -2362,7 +3078,7 @@ var DrizzleGovernanceQueries = class {
2362
3078
  threadId: this.t.agentMessage.threadId,
2363
3079
  createdAt: this.t.agentToolCall.createdAt,
2364
3080
  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);
3081
+ }).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
3082
  return {
2367
3083
  rows: rows.map((row) => ({
2368
3084
  toolCallId: row.toolCallId,
@@ -2386,11 +3102,11 @@ var DrizzleGovernanceQueries = class {
2386
3102
  */
2387
3103
  async threadsPage(query) {
2388
3104
  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);
3105
+ 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
3106
  const [totalRow] = await this.db.select({
2391
- value: (0, import_drizzle_orm4.count)()
3107
+ value: (0, import_drizzle_orm5.count)()
2392
3108
  }).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);
3109
+ 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
3110
  const rows = await this.toThreadActivityRows(threads);
2395
3111
  return {
2396
3112
  rows,
@@ -2408,11 +3124,11 @@ var DrizzleGovernanceQueries = class {
2408
3124
  if (filters?.status !== void 0 && !isRunStatus(filters.status)) {
2409
3125
  return emptyPage(query);
2410
3126
  }
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);
3127
+ 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
3128
  const [totalRow] = await this.db.select({
2413
- value: (0, import_drizzle_orm4.count)()
3129
+ value: (0, import_drizzle_orm5.count)()
2414
3130
  }).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);
3131
+ 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
3132
  return {
2417
3133
  rows: runs.map(toRecentRunRow),
2418
3134
  total: totalRow?.value ?? 0,
@@ -2432,10 +3148,10 @@ var DrizzleGovernanceQueries = class {
2432
3148
  */
2433
3149
  async approvalsPage(query) {
2434
3150
  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);
3151
+ 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
3152
  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);
3153
+ value: (0, import_drizzle_orm5.count)()
3154
+ }).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
3155
  const rows = await this.db.select({
2440
3156
  toolCallId: this.t.agentToolCall.id,
2441
3157
  toolName: this.t.agentToolCall.toolName,
@@ -2446,7 +3162,7 @@ var DrizzleGovernanceQueries = class {
2446
3162
  agentName: this.t.agentMessage.agentName,
2447
3163
  requestedAt: this.t.agentToolCall.createdAt,
2448
3164
  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);
3165
+ }).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
3166
  return {
2451
3167
  rows: rows.map((row) => ({
2452
3168
  toolCallId: row.toolCallId,
@@ -2473,11 +3189,11 @@ var DrizzleGovernanceQueries = class {
2473
3189
  const [row] = await this.db.select({
2474
3190
  run: this.t.agentRun,
2475
3191
  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);
3192
+ }).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
3193
  if (row === void 0) {
2478
3194
  return null;
2479
3195
  }
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));
3196
+ 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
3197
  return {
2482
3198
  run: toRecentRunRow(row.run),
2483
3199
  thread: {
@@ -2496,27 +3212,27 @@ var DrizzleGovernanceQueries = class {
2496
3212
  * message. Soft-deleted threads are returned with `deleted: true`; an audit still needs them.
2497
3213
  */
2498
3214
  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);
3215
+ 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
3216
  if (thread === void 0) {
2501
3217
  return null;
2502
3218
  }
2503
3219
  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);
3220
+ const usageRows = await this.db.select().from(this.t.agentTokenUsage).where((0, import_drizzle_orm5.eq)(this.t.agentTokenUsage.threadId, thread.id));
3221
+ const usage = (0, import_nestjs_agent_core5.rollupThreadUsage)(usageRows.map(toUsageInput), pricing);
2506
3222
  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(
3223
+ value: (0, import_drizzle_orm5.count)()
3224
+ }).from(this.t.agentMessage).where((0, import_drizzle_orm5.eq)(this.t.agentMessage.threadId, thread.id));
3225
+ const messages = await this.db.select().from(this.t.agentMessage).where((0, import_drizzle_orm5.eq)(this.t.agentMessage.threadId, thread.id)).orderBy(
2510
3226
  // 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)
3227
+ (0, import_drizzle_orm5.desc)(import_drizzle_orm5.sql`coalesce(${this.t.agentMessage.seq}, 0)`),
3228
+ (0, import_drizzle_orm5.desc)(this.t.agentMessage.createdAt),
3229
+ (0, import_drizzle_orm5.desc)(this.t.agentMessage.id)
2514
3230
  ).limit(query.messageLimit);
2515
3231
  const toolCallCounts = await this.toolCallCountsByMessage(messages.map((message) => message.id));
2516
3232
  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);
3233
+ value: (0, import_drizzle_orm5.count)()
3234
+ }).from(this.t.agentRun).where((0, import_drizzle_orm5.eq)(this.t.agentRun.threadId, thread.id));
3235
+ 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
3236
  return {
2521
3237
  thread: {
2522
3238
  threadId: thread.id,
@@ -2531,7 +3247,7 @@ var DrizzleGovernanceQueries = class {
2531
3247
  runs: runs.map(toRecentRunRow),
2532
3248
  runTotal: runTotalRow?.value ?? 0,
2533
3249
  messages: messages.map((message) => {
2534
- const { content, truncated } = (0, import_nestjs_agent_core2.truncateDetailContent)(message.content);
3250
+ const { content, truncated } = (0, import_nestjs_agent_core5.truncateDetailContent)(message.content);
2535
3251
  return {
2536
3252
  messageId: message.id,
2537
3253
  role: message.role,
@@ -2552,8 +3268,8 @@ var DrizzleGovernanceQueries = class {
2552
3268
  }
2553
3269
  const rows = await this.db.select({
2554
3270
  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);
3271
+ value: (0, import_drizzle_orm5.count)()
3272
+ }).from(this.t.agentToolCall).where((0, import_drizzle_orm5.inArray)(this.t.agentToolCall.messageId, messageIds)).groupBy(this.t.agentToolCall.messageId);
2557
3273
  for (const row of rows) {
2558
3274
  counts.set(row.messageId, row.value);
2559
3275
  }
@@ -2562,8 +3278,8 @@ var DrizzleGovernanceQueries = class {
2562
3278
  };
2563
3279
 
2564
3280
  // src/drizzle-memory-provider.ts
2565
- var import_nestjs_agent_core3 = require("@dudousxd/nestjs-agent-core");
2566
- var import_drizzle_orm5 = require("drizzle-orm");
3281
+ var import_nestjs_agent_core6 = require("@dudousxd/nestjs-agent-core");
3282
+ var import_drizzle_orm6 = require("drizzle-orm");
2567
3283
  function toRecord(row) {
2568
3284
  return {
2569
3285
  id: row.id,
@@ -2611,7 +3327,7 @@ var DrizzleMemoryProvider = class {
2611
3327
  if (scopes.length === 0) {
2612
3328
  return [];
2613
3329
  }
2614
- const rows = await this.db.select().from(this.t.agentMemory).where((0, import_drizzle_orm5.inArray)(this.t.agentMemory.scope, [
3330
+ const rows = await this.db.select().from(this.t.agentMemory).where((0, import_drizzle_orm6.inArray)(this.t.agentMemory.scope, [
2615
3331
  ...scopes
2616
3332
  ]));
2617
3333
  return rows.map(toRecord);
@@ -2627,7 +3343,7 @@ var DrizzleMemoryProvider = class {
2627
3343
  * answer cannot be used to find out which memories exist about other people.
2628
3344
  */
2629
3345
  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);
3346
+ 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
3347
  return deleted > 0;
2632
3348
  }
2633
3349
  /**
@@ -2676,7 +3392,7 @@ var DrizzleMemoryProvider = class {
2676
3392
  memory.scope,
2677
3393
  memory.key
2678
3394
  ], 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)));
3395
+ [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
3396
  } else {
2681
3397
  [row] = await insert.onConflictDoUpdate({
2682
3398
  target: [
@@ -2703,12 +3419,12 @@ var DrizzleMemoryProvider = class {
2703
3419
  const updated = await affectedRows(this.dialect, this.db.update(this.t.agentMemory).set({
2704
3420
  pinned,
2705
3421
  updatedAt: /* @__PURE__ */ new Date()
2706
- }).where((0, import_drizzle_orm5.eq)(this.t.agentMemory.id, id)), this.t.agentMemory.id);
3422
+ }).where((0, import_drizzle_orm6.eq)(this.t.agentMemory.id, id)), this.t.agentMemory.id);
2707
3423
  return updated > 0;
2708
3424
  }
2709
3425
  };
2710
3426
  function assertAuthorMayWriteScope({ scope, origin, ctx }) {
2711
- const own = (0, import_nestjs_agent_core3.actorScope)(ctx.actor);
3427
+ const own = (0, import_nestjs_agent_core6.actorScope)(ctx.actor);
2712
3428
  if (origin.author !== "human" && scope !== own) {
2713
3429
  throw new Error(`DrizzleMemoryProvider: refusing to write an agent-authored memory at "${scope}"; an agent may write only at "${own}"`);
2714
3430
  }
@@ -2716,7 +3432,7 @@ function assertAuthorMayWriteScope({ scope, origin, ctx }) {
2716
3432
  __name(assertAuthorMayWriteScope, "assertAuthorMayWriteScope");
2717
3433
 
2718
3434
  // src/drizzle-pricing-store.ts
2719
- var import_drizzle_orm6 = require("drizzle-orm");
3435
+ var import_drizzle_orm7 = require("drizzle-orm");
2720
3436
  var DrizzlePricingStore = class {
2721
3437
  static {
2722
3438
  __name(this, "DrizzlePricingStore");
@@ -2732,7 +3448,7 @@ var DrizzlePricingStore = class {
2732
3448
  async upsertModelPrice(input) {
2733
3449
  await this.db.update(this.t.agentModelPricing).set({
2734
3450
  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)));
3451
+ }).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
3452
  await this.db.insert(this.t.agentModelPricing).values({
2737
3453
  id: crypto.randomUUID(),
2738
3454
  modelId: input.modelId,
@@ -2745,7 +3461,7 @@ var DrizzlePricingStore = class {
2745
3461
  });
2746
3462
  }
2747
3463
  async listCurrentPrices() {
2748
- const rows = await this.db.select().from(this.t.agentModelPricing).where((0, import_drizzle_orm6.eq)(this.t.agentModelPricing.isCurrent, true));
3464
+ const rows = await this.db.select().from(this.t.agentModelPricing).where((0, import_drizzle_orm7.eq)(this.t.agentModelPricing.isCurrent, true));
2749
3465
  return rows.map((row) => ({
2750
3466
  modelId: row.modelId,
2751
3467
  inputPricePer1m: row.inputPricePer1m,
@@ -2762,8 +3478,8 @@ var DrizzlePricingStore = class {
2762
3478
  };
2763
3479
 
2764
3480
  // 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");
3481
+ var import_nestjs_agent_core7 = require("@dudousxd/nestjs-agent-core");
3482
+ var import_drizzle_orm8 = require("drizzle-orm");
2767
3483
  var DrizzleStreamFrameTable = class {
2768
3484
  static {
2769
3485
  __name(this, "DrizzleStreamFrameTable");
@@ -2777,7 +3493,7 @@ var DrizzleStreamFrameTable = class {
2777
3493
  this.db = asBuilder(db);
2778
3494
  }
2779
3495
  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)
3496
+ await runSql(this.db, this.dialect, import_drizzle_orm8.sql`INSERT INTO agent_stream_frame (run_id, seq, frame, error, created_at)
2781
3497
  SELECT ${runId}, COALESCE(MAX(seq), 0) + 1, ${row.frame}, ${row.error}, ${row.createdAt}
2782
3498
  FROM agent_stream_frame WHERE run_id = ${runId}`);
2783
3499
  }
@@ -2786,31 +3502,31 @@ var DrizzleStreamFrameTable = class {
2786
3502
  seq: this.t.agentStreamFrame.seq,
2787
3503
  frame: this.t.agentStreamFrame.frame,
2788
3504
  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);
3505
+ }).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
3506
  }
2791
3507
  async has(runId) {
2792
3508
  const rows = await this.db.select({
2793
3509
  seq: this.t.agentStreamFrame.seq
2794
- }).from(this.t.agentStreamFrame).where((0, import_drizzle_orm7.eq)(this.t.agentStreamFrame.runId, runId)).limit(1);
3510
+ }).from(this.t.agentStreamFrame).where((0, import_drizzle_orm8.eq)(this.t.agentStreamFrame.runId, runId)).limit(1);
2795
3511
  return rows.length > 0;
2796
3512
  }
2797
3513
  async remove(runIds) {
2798
3514
  if (runIds.length === 0) return;
2799
- await this.db.delete(this.t.agentStreamFrame).where((0, import_drizzle_orm7.inArray)(this.t.agentStreamFrame.runId, [
3515
+ await this.db.delete(this.t.agentStreamFrame).where((0, import_drizzle_orm8.inArray)(this.t.agentStreamFrame.runId, [
2800
3516
  ...runIds
2801
3517
  ]));
2802
3518
  }
2803
3519
  async lapsedRuns(cutoff) {
2804
3520
  const rows = await this.db.select({
2805
3521
  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));
3522
+ }).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
3523
  return rows.map((row) => row.runId);
2808
3524
  }
2809
3525
  isUniqueViolation(error) {
2810
3526
  return isUniqueViolation(error);
2811
3527
  }
2812
3528
  };
2813
- var DrizzleTokenStreamSink = class extends import_nestjs_agent_core4.SqlTokenStreamSink {
3529
+ var DrizzleTokenStreamSink = class extends import_nestjs_agent_core7.SqlTokenStreamSink {
2814
3530
  static {
2815
3531
  __name(this, "DrizzleTokenStreamSink");
2816
3532
  }
@@ -2820,7 +3536,7 @@ var DrizzleTokenStreamSink = class extends import_nestjs_agent_core4.SqlTokenStr
2820
3536
  };
2821
3537
 
2822
3538
  // src/drizzle-confirm-token-store.ts
2823
- var import_drizzle_orm8 = require("drizzle-orm");
3539
+ var import_drizzle_orm9 = require("drizzle-orm");
2824
3540
  var DrizzleConfirmTokenStore = class {
2825
3541
  static {
2826
3542
  __name(this, "DrizzleConfirmTokenStore");
@@ -2850,18 +3566,18 @@ var DrizzleConfirmTokenStore = class {
2850
3566
  return inserted === 1;
2851
3567
  }
2852
3568
  async release(hash) {
2853
- await this.db.delete(this.t.agentConfirmToken).where((0, import_drizzle_orm8.eq)(this.t.agentConfirmToken.hash, hash));
3569
+ await this.db.delete(this.t.agentConfirmToken).where((0, import_drizzle_orm9.eq)(this.t.agentConfirmToken.hash, hash));
2854
3570
  }
2855
3571
  async purgeExpired(now = Date.now()) {
2856
3572
  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);
3573
+ return affectedRows(this.dialect, this.db.delete(table).where((0, import_drizzle_orm9.lt)(table.expiresAt, now)), table.hash);
2858
3574
  }
2859
3575
  };
2860
3576
 
2861
3577
  // src/drizzle-rag-ingestion-log.ts
2862
3578
  var import_node_diagnostics_channel = require("diagnostics_channel");
2863
3579
  var import_common = require("@nestjs/common");
2864
- var import_drizzle_orm9 = require("drizzle-orm");
3580
+ var import_drizzle_orm10 = require("drizzle-orm");
2865
3581
  function _ts_decorate(decorators, target, key2, desc4) {
2866
3582
  var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key2) : desc4, d;
2867
3583
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -2909,8 +3625,8 @@ function num(value) {
2909
3625
  }
2910
3626
  __name(num, "num");
2911
3627
  var RAG_INGESTION_LOG_PAGE_ORDER = [
2912
- (0, import_drizzle_orm9.desc)(ragIngestionLog.updatedAt),
2913
- (0, import_drizzle_orm9.asc)(ragIngestionLog.documentId)
3628
+ (0, import_drizzle_orm10.desc)(ragIngestionLog.updatedAt),
3629
+ (0, import_drizzle_orm10.asc)(ragIngestionLog.documentId)
2914
3630
  ];
2915
3631
  var DEFAULT_PAGE_SIZE = 200;
2916
3632
  var DEFAULT_BATCH_SIZE = 200;
@@ -2981,7 +3697,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
2981
3697
  */
2982
3698
  async listPage(query = {}) {
2983
3699
  const [totalRow] = await this.db.select({
2984
- value: (0, import_drizzle_orm9.count)()
3700
+ value: (0, import_drizzle_orm10.count)()
2985
3701
  }).from(this.t.ragIngestionLog).where(this.where(query));
2986
3702
  return {
2987
3703
  rows: await this.list(query),
@@ -3060,17 +3776,17 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
3060
3776
  }
3061
3777
  /** The latest recorded outcome for one document, or null if it was never attempted. */
3062
3778
  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));
3779
+ const [row] = await this.db.select().from(this.t.ragIngestionLog).where((0, import_drizzle_orm10.eq)(this.t.ragIngestionLog.documentId, documentId));
3064
3780
  return row ?? null;
3065
3781
  }
3066
3782
  /** Forget one document's record. Returns whether a row was actually removed. */
3067
3783
  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);
3784
+ 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
3785
  return removed > 0;
3070
3786
  }
3071
3787
  /** Forget every record for a collection — for when the collection itself is deleted. */
3072
3788
  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);
3789
+ 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
3790
  return removed;
3075
3791
  }
3076
3792
  /**
@@ -3100,7 +3816,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
3100
3816
  }
3101
3817
  }
3102
3818
  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);
3819
+ 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
3820
  }
3105
3821
  /**
3106
3822
  * The coordinates filter AND'd with "strictly after `cursor` in
@@ -3115,7 +3831,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
3115
3831
  if (cursor === void 0) {
3116
3832
  return base;
3117
3833
  }
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))));
3834
+ 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
3835
  }
3120
3836
  /**
3121
3837
  * Upsert one outcome. Keyed by document id so the row always reflects the *current* state — a
@@ -3188,7 +3904,7 @@ DrizzleRagIngestionLog = _ts_decorate([
3188
3904
  ], DrizzleRagIngestionLog);
3189
3905
 
3190
3906
  // src/drizzle-agent-store.module.ts
3191
- var import_nestjs_agent_core5 = require("@dudousxd/nestjs-agent-core");
3907
+ var import_nestjs_agent_core8 = require("@dudousxd/nestjs-agent-core");
3192
3908
  var import_common2 = require("@nestjs/common");
3193
3909
  function _ts_decorate2(decorators, target, key2, desc4) {
3194
3910
  var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key2) : desc4, d;
@@ -3225,7 +3941,7 @@ var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
3225
3941
  useFactory: /* @__PURE__ */ __name(() => new DrizzleAgentStore(options.db), "useFactory")
3226
3942
  },
3227
3943
  {
3228
- provide: import_nestjs_agent_core5.AGENT_STORE,
3944
+ provide: import_nestjs_agent_core8.AGENT_STORE,
3229
3945
  useExisting: DrizzleAgentStore
3230
3946
  },
3231
3947
  // Exported, never bound to AGENT_MEMORY: that token's PRESENCE is what turns memory on, so
@@ -3242,21 +3958,21 @@ var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
3242
3958
  // AGENT_PRICING_STORE: the host's own store when supplied, else the default Drizzle one.
3243
3959
  // DrizzleGovernanceQueries prices usage against whatever is bound here.
3244
3960
  options.pricingStore ? {
3245
- provide: import_nestjs_agent_core5.AGENT_PRICING_STORE,
3961
+ provide: import_nestjs_agent_core8.AGENT_PRICING_STORE,
3246
3962
  useClass: options.pricingStore
3247
3963
  } : {
3248
- provide: import_nestjs_agent_core5.AGENT_PRICING_STORE,
3964
+ provide: import_nestjs_agent_core8.AGENT_PRICING_STORE,
3249
3965
  useExisting: DrizzlePricingStore
3250
3966
  },
3251
3967
  {
3252
3968
  provide: DrizzleGovernanceQueries,
3253
3969
  useFactory: /* @__PURE__ */ __name((pricingStore) => new DrizzleGovernanceQueries(options.db, pricingStore), "useFactory"),
3254
3970
  inject: [
3255
- import_nestjs_agent_core5.AGENT_PRICING_STORE
3971
+ import_nestjs_agent_core8.AGENT_PRICING_STORE
3256
3972
  ]
3257
3973
  },
3258
3974
  {
3259
- provide: import_nestjs_agent_core5.AGENT_GOVERNANCE_QUERIES,
3975
+ provide: import_nestjs_agent_core8.AGENT_GOVERNANCE_QUERIES,
3260
3976
  useExisting: DrizzleGovernanceQueries
3261
3977
  },
3262
3978
  // What makes a `defineConfirmedTool` confirmation single use across replicas.
@@ -3265,7 +3981,7 @@ var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
3265
3981
  useFactory: /* @__PURE__ */ __name(() => new DrizzleConfirmTokenStore(options.db), "useFactory")
3266
3982
  },
3267
3983
  {
3268
- provide: import_nestjs_agent_core5.AGENT_CONFIRM_TOKEN_STORE,
3984
+ provide: import_nestjs_agent_core8.AGENT_CONFIRM_TOKEN_STORE,
3269
3985
  useExisting: DrizzleConfirmTokenStore
3270
3986
  }
3271
3987
  ],
@@ -3274,14 +3990,14 @@ var DrizzleAgentStoreModule = class _DrizzleAgentStoreModule {
3274
3990
  DrizzleRagIngestionLog
3275
3991
  ],
3276
3992
  DrizzleAgentStore,
3277
- import_nestjs_agent_core5.AGENT_STORE,
3993
+ import_nestjs_agent_core8.AGENT_STORE,
3278
3994
  DrizzleMemoryProvider,
3279
3995
  DrizzleGovernanceQueries,
3280
- import_nestjs_agent_core5.AGENT_GOVERNANCE_QUERIES,
3996
+ import_nestjs_agent_core8.AGENT_GOVERNANCE_QUERIES,
3281
3997
  DrizzlePricingStore,
3282
- import_nestjs_agent_core5.AGENT_PRICING_STORE,
3998
+ import_nestjs_agent_core8.AGENT_PRICING_STORE,
3283
3999
  DrizzleConfirmTokenStore,
3284
- import_nestjs_agent_core5.AGENT_CONFIRM_TOKEN_STORE
4000
+ import_nestjs_agent_core8.AGENT_CONFIRM_TOKEN_STORE
3285
4001
  ]
3286
4002
  };
3287
4003
  }
@@ -3291,6 +4007,7 @@ DrizzleAgentStoreModule = _ts_decorate2([
3291
4007
  ], DrizzleAgentStoreModule);
3292
4008
  // Annotate the CommonJS export names for ESM import in node:
3293
4009
  0 && (module.exports = {
4010
+ DrizzleActionProposalStore,
3294
4011
  DrizzleAgentStore,
3295
4012
  DrizzleAgentStoreModule,
3296
4013
  DrizzleConfirmTokenStore,
@@ -3301,6 +4018,7 @@ DrizzleAgentStoreModule = _ts_decorate2([
3301
4018
  DrizzleStreamFrameTable,
3302
4019
  DrizzleTokenStreamSink,
3303
4020
  RAG_INGESTION_LOG_PAGE_ORDER,
4021
+ agentActionProposal,
3304
4022
  agentConfirmToken,
3305
4023
  agentDialectOf,
3306
4024
  agentMemory,