@dudousxd/nestjs-agent-store-drizzle 0.36.2 → 0.37.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.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _dudousxd_nestjs_agent_core from '@dudousxd/nestjs-agent-core';
2
- import { MessageRole, ToolCallRequest, ToolResult, MessageAttachment, MessageUsage, AgentUiComponent, MessageFeedback, AgentHostContext, Actor, PageContext, RunStepTiming, QueuePause, ActionProposal, GenuiValidity, GenuiErrorCategory, CostSource, ToolKind, ToolCallStatus, ToolConfirmation, UsagePurpose, AgentStore, ThreadTurnReader, ThreadSettingsReader, ChatQueueStore, ActionProposalStore, ActionProposalWorkerStore, ActionProposalDiscoveryIndexStore, ActionProposalOutcomeStore, ActionProposalStoreOptions, ActionProposalSupersessionStore, CreateThreadInput, ThreadSummary, ThreadDetail, ThreadTurnQuery, ThreadTurnPage, ForkThreadOptions, ToolCallApprovalState, EnqueueMessageInput, QueuedMessage, QueuedMessagePatch, UpdateThreadInput, ThreadSettings, RecordRunStartInput, RecordRunEndInput, AppendMessageInput, StoredMessage, RecordToolCallInput, UpdateToolCallInput, ToolCallOutcome, RecordUsageInput, RecordGenuiCallInput, UsageTotals, CreateActionProposal, CreateActionProposalResult, ActionProposalScope, ActionProposalMutationResult, ListActionProposals, ActionProposalDecisionCommand, ClaimActionProposal, ExtendActionProposalLease, SettleActionProposal, ActionProposalOutcomeLease, AgentGovernanceQueries, AgentPricingStore, GovernanceRange, ModelSpendRow, FeatureSpendRow, TimestampRange, UsageBreakdownFilter, UsageBreakdownRow, ActorSpendRow, ThreadSpendRow, UsageTrendPoint, ToolCallActivityRow, ThreadActivityRow, RunMetrics, RunAgentBreakdownRow, RunErrorBreakdownRow, RunTrendPoint, RecentRunRow, PendingApprovalRow, ToolStatRow, GovernancePageQuery, ToolCallWhere, GovernancePage, ThreadWhere, RunWhere, ApprovalWhere, GovernanceRunDetail, GovernanceThreadDetailQuery, GovernanceThreadDetail, GenuiStats, MemoryProvider, ListMemoriesInput, MemoryRecord, ForgetMemoryInput, StoreMemoryInput, ModelPriceInput, CurrentModelPrice, StreamFrameTable, StreamFrameRow, SqlTokenStreamSink, SqlTokenStreamSinkOptions, ConfirmTokenStore, ConfirmTokenClaim, ChannelStore, PoppyStore, PoppyConversationRecord, PoppyConversationPatch, PoppyEventBody, StoredPoppyEvent, PoppyMessageReceipt, PoppyMessageClaim, PoppyConnectionStore, PoppyConnectionRecord, PoppyPendingConnect } from '@dudousxd/nestjs-agent-core';
2
+ import { MessageRole, ToolCallRequest, ToolResult, MessageAttachment, MessageUsage, AgentUiComponent, MessageFeedback, AgentHostContext, Actor, PageContext, RunStepTiming, QueuePause, ActionProposal, GenuiValidity, GenuiErrorCategory, CostSource, ToolKind, ToolCallStatus, ToolConfirmation, UsagePurpose, AgentStore, ThreadTurnReader, ThreadSettingsReader, ChatQueueStore, ActionProposalStore, ActionProposalWorkerStore, ActionProposalDiscoveryIndexStore, ActionProposalOutcomeStore, ActionProposalStoreOptions, ActionProposalSupersessionStore, CreateThreadInput, ThreadSummary, ThreadDetail, ThreadTurnQuery, ThreadTurnPage, TenantRowFilter, ForkThreadOptions, ToolCallApprovalState, TenantTarget, EnqueueMessageInput, QueuedMessage, QueuedMessagePatch, UpdateThreadInput, ThreadSettings, RecordRunStartInput, RecordRunEndInput, AppendMessageInput, StoredMessage, RecordToolCallInput, UpdateToolCallInput, ToolCallOutcome, RecordUsageInput, RecordGenuiCallInput, UsageTotals, CreateActionProposal, CreateActionProposalResult, ActionProposalScope, ActionProposalMutationResult, ListActionProposals, ActionProposalDecisionCommand, ClaimActionProposal, ExtendActionProposalLease, SettleActionProposal, ActionProposalOutcomeLease, AgentGovernanceQueries, AgentPricingStore, GovernanceRange, ModelSpendRow, FeatureSpendRow, TimestampRange, UsageBreakdownFilter, UsageBreakdownRow, ActorSpendRow, ThreadSpendRow, UsageTrendPoint, ToolCallActivityRow, ThreadActivityRow, RunMetrics, RunAgentBreakdownRow, RunErrorBreakdownRow, RunTrendPoint, RecentRunRow, PendingApprovalRow, ToolStatRow, GovernancePageQuery, ToolCallWhere, GovernancePage, ThreadWhere, RunWhere, ApprovalWhere, GovernanceRunDetail, GovernanceThreadDetailQuery, GovernanceThreadDetail, GenuiStats, MemoryProvider, ListMemoriesInput, MemoryRecord, ForgetMemoryInput, StoreMemoryInput, ModelPriceInput, CurrentModelPrice, StreamFrameTable, StreamFrameRow, SqlTokenStreamSink, SqlTokenStreamSinkOptions, ConfirmTokenStore, ConfirmTokenClaim, ChannelStore, PoppyStore, PoppyConversationRecord, PoppyConversationPatch, PoppyEventBody, StoredPoppyEvent, PoppyMessageReceipt, PoppyMessageClaim, PoppyConnectionStore, PoppyConnectionRecord, PoppyPendingConnect } from '@dudousxd/nestjs-agent-core';
3
3
  export { ThreadTurnPage, ThreadTurnQuery } from '@dudousxd/nestjs-agent-core';
4
4
  import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
5
5
  import { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
@@ -9771,6 +9771,8 @@ declare class DrizzleAgentStore implements AgentStore, ThreadTurnReader, ThreadS
9771
9771
  */
9772
9772
  private loadTurnWindow;
9773
9773
  listThreads(actorRef: string, limit?: number): Promise<ThreadSummary[]>;
9774
+ listThreadsForTenant(actorRef: string, filter: TenantRowFilter, limit?: number): Promise<ThreadSummary[]>;
9775
+ private listThreadsWhere;
9774
9776
  /**
9775
9777
  * The content of each thread's newest message ({@link messageOrderNewestFirst}), in a fixed two
9776
9778
  * reads for any number of threads: each thread's highest `seq`, then the rows holding it. Only a
@@ -9792,6 +9794,9 @@ declare class DrizzleAgentStore implements AgentStore, ThreadTurnReader, ThreadS
9792
9794
  rememberedApprovals(threadId: string): Promise<string[]>;
9793
9795
  toolCallInput(toolCallId: string): Promise<unknown>;
9794
9796
  toolCallApproval(toolCallId: string): Promise<ToolCallApprovalState | null>;
9797
+ tenantOf(target: TenantTarget): Promise<{
9798
+ tenantRef: string | null;
9799
+ } | null>;
9795
9800
  ownerOfActiveStream(runId: string): Promise<string | null>;
9796
9801
  setTitle(threadId: string, title: string): Promise<void>;
9797
9802
  promoteThread(threadId: string): Promise<void>;
@@ -9903,6 +9908,15 @@ declare class DrizzleAgentStore implements AgentStore, ThreadTurnReader, ThreadS
9903
9908
  fromDay: string;
9904
9909
  toDay: string;
9905
9910
  }[]): Promise<UsageTotals[]>;
9911
+ /**
9912
+ * {@link usageWindows} over the tenant's rows (every actor's, or `actorRef`'s only), served by the
9913
+ * `(tenant_ref, created_at)` index.
9914
+ */
9915
+ usageWindowsForTenant(tenantRef: string, ranges: readonly {
9916
+ fromDay: string;
9917
+ toDay: string;
9918
+ }[], actorRef?: string): Promise<UsageTotals[]>;
9919
+ private sumUsageWindows;
9906
9920
  private toSummary;
9907
9921
  private toStoredMessage;
9908
9922
  }
@@ -9978,11 +9992,26 @@ declare class DrizzleActionProposalStore implements ActionProposalStore, ActionP
9978
9992
  * `quotaToday`) so day-bucketing stays dialect-portable.
9979
9993
  */
9980
9994
  declare class DrizzleGovernanceQueries implements AgentGovernanceQueries {
9995
+ private readonly source;
9981
9996
  private readonly pricingStore;
9997
+ private readonly tenant?;
9982
9998
  private readonly db;
9983
9999
  private readonly dialect;
9984
10000
  private readonly t;
9985
- constructor(db: AgentDrizzleDb, pricingStore: AgentPricingStore);
10001
+ /**
10002
+ * `tenant`: the rows these queries may see (see {@link forTenant}); absent → every row. Threads by
10003
+ * their `tenant_ref`; runs, messages, tool calls and generative-UI calls by their thread's; usage
10004
+ * by its own `tenant_ref`.
10005
+ */
10006
+ constructor(source: AgentDrizzleDb, pricingStore: AgentPricingStore, tenant?: TenantRowFilter | undefined);
10007
+ /** These queries narrowed to the rows `filter` may see — the console's tenant scope. */
10008
+ forTenant(filter: TenantRowFilter): DrizzleGovernanceQueries;
10009
+ /** The matching rule on a `tenant_ref` column; `undefined` (no condition) without a scope. */
10010
+ private tenantOn;
10011
+ /** Rows keyed by a thread id whose thread the scope may see; `undefined` without a scope. */
10012
+ private threadIn;
10013
+ /** Tool calls (by `message_id`) on a thread the scope may see; `undefined` without a scope. */
10014
+ private toolCallIn;
9986
10015
  private loadPricing;
9987
10016
  /**
9988
10017
  * The usage rows in range, with only what the bucketers read: `requests` always (a recorded row
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _dudousxd_nestjs_agent_core from '@dudousxd/nestjs-agent-core';
2
- import { MessageRole, ToolCallRequest, ToolResult, MessageAttachment, MessageUsage, AgentUiComponent, MessageFeedback, AgentHostContext, Actor, PageContext, RunStepTiming, QueuePause, ActionProposal, GenuiValidity, GenuiErrorCategory, CostSource, ToolKind, ToolCallStatus, ToolConfirmation, UsagePurpose, AgentStore, ThreadTurnReader, ThreadSettingsReader, ChatQueueStore, ActionProposalStore, ActionProposalWorkerStore, ActionProposalDiscoveryIndexStore, ActionProposalOutcomeStore, ActionProposalStoreOptions, ActionProposalSupersessionStore, CreateThreadInput, ThreadSummary, ThreadDetail, ThreadTurnQuery, ThreadTurnPage, ForkThreadOptions, ToolCallApprovalState, EnqueueMessageInput, QueuedMessage, QueuedMessagePatch, UpdateThreadInput, ThreadSettings, RecordRunStartInput, RecordRunEndInput, AppendMessageInput, StoredMessage, RecordToolCallInput, UpdateToolCallInput, ToolCallOutcome, RecordUsageInput, RecordGenuiCallInput, UsageTotals, CreateActionProposal, CreateActionProposalResult, ActionProposalScope, ActionProposalMutationResult, ListActionProposals, ActionProposalDecisionCommand, ClaimActionProposal, ExtendActionProposalLease, SettleActionProposal, ActionProposalOutcomeLease, AgentGovernanceQueries, AgentPricingStore, GovernanceRange, ModelSpendRow, FeatureSpendRow, TimestampRange, UsageBreakdownFilter, UsageBreakdownRow, ActorSpendRow, ThreadSpendRow, UsageTrendPoint, ToolCallActivityRow, ThreadActivityRow, RunMetrics, RunAgentBreakdownRow, RunErrorBreakdownRow, RunTrendPoint, RecentRunRow, PendingApprovalRow, ToolStatRow, GovernancePageQuery, ToolCallWhere, GovernancePage, ThreadWhere, RunWhere, ApprovalWhere, GovernanceRunDetail, GovernanceThreadDetailQuery, GovernanceThreadDetail, GenuiStats, MemoryProvider, ListMemoriesInput, MemoryRecord, ForgetMemoryInput, StoreMemoryInput, ModelPriceInput, CurrentModelPrice, StreamFrameTable, StreamFrameRow, SqlTokenStreamSink, SqlTokenStreamSinkOptions, ConfirmTokenStore, ConfirmTokenClaim, ChannelStore, PoppyStore, PoppyConversationRecord, PoppyConversationPatch, PoppyEventBody, StoredPoppyEvent, PoppyMessageReceipt, PoppyMessageClaim, PoppyConnectionStore, PoppyConnectionRecord, PoppyPendingConnect } from '@dudousxd/nestjs-agent-core';
2
+ import { MessageRole, ToolCallRequest, ToolResult, MessageAttachment, MessageUsage, AgentUiComponent, MessageFeedback, AgentHostContext, Actor, PageContext, RunStepTiming, QueuePause, ActionProposal, GenuiValidity, GenuiErrorCategory, CostSource, ToolKind, ToolCallStatus, ToolConfirmation, UsagePurpose, AgentStore, ThreadTurnReader, ThreadSettingsReader, ChatQueueStore, ActionProposalStore, ActionProposalWorkerStore, ActionProposalDiscoveryIndexStore, ActionProposalOutcomeStore, ActionProposalStoreOptions, ActionProposalSupersessionStore, CreateThreadInput, ThreadSummary, ThreadDetail, ThreadTurnQuery, ThreadTurnPage, TenantRowFilter, ForkThreadOptions, ToolCallApprovalState, TenantTarget, EnqueueMessageInput, QueuedMessage, QueuedMessagePatch, UpdateThreadInput, ThreadSettings, RecordRunStartInput, RecordRunEndInput, AppendMessageInput, StoredMessage, RecordToolCallInput, UpdateToolCallInput, ToolCallOutcome, RecordUsageInput, RecordGenuiCallInput, UsageTotals, CreateActionProposal, CreateActionProposalResult, ActionProposalScope, ActionProposalMutationResult, ListActionProposals, ActionProposalDecisionCommand, ClaimActionProposal, ExtendActionProposalLease, SettleActionProposal, ActionProposalOutcomeLease, AgentGovernanceQueries, AgentPricingStore, GovernanceRange, ModelSpendRow, FeatureSpendRow, TimestampRange, UsageBreakdownFilter, UsageBreakdownRow, ActorSpendRow, ThreadSpendRow, UsageTrendPoint, ToolCallActivityRow, ThreadActivityRow, RunMetrics, RunAgentBreakdownRow, RunErrorBreakdownRow, RunTrendPoint, RecentRunRow, PendingApprovalRow, ToolStatRow, GovernancePageQuery, ToolCallWhere, GovernancePage, ThreadWhere, RunWhere, ApprovalWhere, GovernanceRunDetail, GovernanceThreadDetailQuery, GovernanceThreadDetail, GenuiStats, MemoryProvider, ListMemoriesInput, MemoryRecord, ForgetMemoryInput, StoreMemoryInput, ModelPriceInput, CurrentModelPrice, StreamFrameTable, StreamFrameRow, SqlTokenStreamSink, SqlTokenStreamSinkOptions, ConfirmTokenStore, ConfirmTokenClaim, ChannelStore, PoppyStore, PoppyConversationRecord, PoppyConversationPatch, PoppyEventBody, StoredPoppyEvent, PoppyMessageReceipt, PoppyMessageClaim, PoppyConnectionStore, PoppyConnectionRecord, PoppyPendingConnect } from '@dudousxd/nestjs-agent-core';
3
3
  export { ThreadTurnPage, ThreadTurnQuery } from '@dudousxd/nestjs-agent-core';
4
4
  import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
5
5
  import { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
@@ -9771,6 +9771,8 @@ declare class DrizzleAgentStore implements AgentStore, ThreadTurnReader, ThreadS
9771
9771
  */
9772
9772
  private loadTurnWindow;
9773
9773
  listThreads(actorRef: string, limit?: number): Promise<ThreadSummary[]>;
9774
+ listThreadsForTenant(actorRef: string, filter: TenantRowFilter, limit?: number): Promise<ThreadSummary[]>;
9775
+ private listThreadsWhere;
9774
9776
  /**
9775
9777
  * The content of each thread's newest message ({@link messageOrderNewestFirst}), in a fixed two
9776
9778
  * reads for any number of threads: each thread's highest `seq`, then the rows holding it. Only a
@@ -9792,6 +9794,9 @@ declare class DrizzleAgentStore implements AgentStore, ThreadTurnReader, ThreadS
9792
9794
  rememberedApprovals(threadId: string): Promise<string[]>;
9793
9795
  toolCallInput(toolCallId: string): Promise<unknown>;
9794
9796
  toolCallApproval(toolCallId: string): Promise<ToolCallApprovalState | null>;
9797
+ tenantOf(target: TenantTarget): Promise<{
9798
+ tenantRef: string | null;
9799
+ } | null>;
9795
9800
  ownerOfActiveStream(runId: string): Promise<string | null>;
9796
9801
  setTitle(threadId: string, title: string): Promise<void>;
9797
9802
  promoteThread(threadId: string): Promise<void>;
@@ -9903,6 +9908,15 @@ declare class DrizzleAgentStore implements AgentStore, ThreadTurnReader, ThreadS
9903
9908
  fromDay: string;
9904
9909
  toDay: string;
9905
9910
  }[]): Promise<UsageTotals[]>;
9911
+ /**
9912
+ * {@link usageWindows} over the tenant's rows (every actor's, or `actorRef`'s only), served by the
9913
+ * `(tenant_ref, created_at)` index.
9914
+ */
9915
+ usageWindowsForTenant(tenantRef: string, ranges: readonly {
9916
+ fromDay: string;
9917
+ toDay: string;
9918
+ }[], actorRef?: string): Promise<UsageTotals[]>;
9919
+ private sumUsageWindows;
9906
9920
  private toSummary;
9907
9921
  private toStoredMessage;
9908
9922
  }
@@ -9978,11 +9992,26 @@ declare class DrizzleActionProposalStore implements ActionProposalStore, ActionP
9978
9992
  * `quotaToday`) so day-bucketing stays dialect-portable.
9979
9993
  */
9980
9994
  declare class DrizzleGovernanceQueries implements AgentGovernanceQueries {
9995
+ private readonly source;
9981
9996
  private readonly pricingStore;
9997
+ private readonly tenant?;
9982
9998
  private readonly db;
9983
9999
  private readonly dialect;
9984
10000
  private readonly t;
9985
- constructor(db: AgentDrizzleDb, pricingStore: AgentPricingStore);
10001
+ /**
10002
+ * `tenant`: the rows these queries may see (see {@link forTenant}); absent → every row. Threads by
10003
+ * their `tenant_ref`; runs, messages, tool calls and generative-UI calls by their thread's; usage
10004
+ * by its own `tenant_ref`.
10005
+ */
10006
+ constructor(source: AgentDrizzleDb, pricingStore: AgentPricingStore, tenant?: TenantRowFilter | undefined);
10007
+ /** These queries narrowed to the rows `filter` may see — the console's tenant scope. */
10008
+ forTenant(filter: TenantRowFilter): DrizzleGovernanceQueries;
10009
+ /** The matching rule on a `tenant_ref` column; `undefined` (no condition) without a scope. */
10010
+ private tenantOn;
10011
+ /** Rows keyed by a thread id whose thread the scope may see; `undefined` without a scope. */
10012
+ private threadIn;
10013
+ /** Tool calls (by `message_id`) on a thread the scope may see; `undefined` without a scope. */
10014
+ private toolCallIn;
9986
10015
  private loadPricing;
9987
10016
  /**
9988
10017
  * The usage rows in range, with only what the bucketers read: `requests` always (a recorded row
package/dist/index.js CHANGED
@@ -220,7 +220,9 @@ var agentTokenUsage = sqliteTable("agent_token_usage", {
220
220
  index("agent_token_usage_actor_created_idx").on(table.actorRef, table.createdAt),
221
221
  index("agent_token_usage_created_idx").on(table.createdAt),
222
222
  index("agent_token_usage_thread_idx").on(table.threadId),
223
- index("agent_token_usage_feature_created_idx").on(table.feature, table.createdAt)
223
+ index("agent_token_usage_feature_created_idx").on(table.feature, table.createdAt),
224
+ // `quota.per: 'tenant' | 'actor-in-tenant'` sums a tenant's window.
225
+ index("agent_token_usage_tenant_created_idx").on(table.tenantRef, table.createdAt)
224
226
  ]);
225
227
  var agentGenuiCall = sqliteTable("agent_genui_call", {
226
228
  id: text("id").primaryKey(),
@@ -693,7 +695,9 @@ var agentTokenUsage2 = mysqlTable("agent_token_usage", {
693
695
  index2("agent_token_usage_actor_created_idx").on(table.actorRef, table.createdAt),
694
696
  index2("agent_token_usage_created_idx").on(table.createdAt),
695
697
  index2("agent_token_usage_thread_idx").on(table.threadId),
696
- index2("agent_token_usage_feature_created_idx").on(table.feature, table.createdAt)
698
+ index2("agent_token_usage_feature_created_idx").on(table.feature, table.createdAt),
699
+ // `quota.per: 'tenant' | 'actor-in-tenant'` sums a tenant's window.
700
+ index2("agent_token_usage_tenant_created_idx").on(table.tenantRef, table.createdAt)
697
701
  ]);
698
702
  var agentGenuiCall2 = mysqlTable("agent_genui_call", {
699
703
  id: key("id").primaryKey(),
@@ -1180,7 +1184,9 @@ var agentTokenUsage3 = pgTable("agent_token_usage", {
1180
1184
  index3("agent_token_usage_actor_created_idx").on(table.actorRef, table.createdAt),
1181
1185
  index3("agent_token_usage_created_idx").on(table.createdAt),
1182
1186
  index3("agent_token_usage_thread_idx").on(table.threadId),
1183
- index3("agent_token_usage_feature_created_idx").on(table.feature, table.createdAt)
1187
+ index3("agent_token_usage_feature_created_idx").on(table.feature, table.createdAt),
1188
+ // `quota.per: 'tenant' | 'actor-in-tenant'` sums a tenant's window.
1189
+ index3("agent_token_usage_tenant_created_idx").on(table.tenantRef, table.createdAt)
1184
1190
  ]);
1185
1191
  var agentGenuiCall3 = pgTable("agent_genui_call", {
1186
1192
  id: text2("id").primaryKey(),
@@ -2524,7 +2530,15 @@ var DrizzleAgentStore = class {
2524
2530
  return rows.reverse().map((row) => this.toStoredMessage(row));
2525
2531
  }
2526
2532
  async listThreads(actorRef, limit = 50) {
2527
- const threads = await this.db.select().from(this.t.agentThread).where(and2(eq2(this.t.agentThread.actorRef, actorRef), eq2(this.t.agentThread.transient, false), isNull2(this.t.agentThread.deletedAt))).orderBy(desc(this.t.agentThread.updatedAt)).limit(limit);
2533
+ return this.listThreadsWhere(actorRef, void 0, limit);
2534
+ }
2535
+ async listThreadsForTenant(actorRef, filter, limit = 50) {
2536
+ const column = this.t.agentThread.tenantRef;
2537
+ const visible = filter.tenant === void 0 ? isNull2(column) : filter.nulls ? or2(eq2(column, filter.tenant), isNull2(column)) : eq2(column, filter.tenant);
2538
+ return this.listThreadsWhere(actorRef, visible, limit);
2539
+ }
2540
+ async listThreadsWhere(actorRef, tenant, limit) {
2541
+ const threads = await this.db.select().from(this.t.agentThread).where(and2(eq2(this.t.agentThread.actorRef, actorRef), eq2(this.t.agentThread.transient, false), isNull2(this.t.agentThread.deletedAt), tenant)).orderBy(desc(this.t.agentThread.updatedAt)).limit(limit);
2528
2542
  const previews = await this.lastMessageContents(threads.map((thread) => thread.id));
2529
2543
  return threads.map((thread) => this.toSummary(thread, previews.get(thread.id)));
2530
2544
  }
@@ -2718,6 +2732,23 @@ var DrizzleAgentStore = class {
2718
2732
  expiresAt: row.expiresAt?.toISOString() ?? null
2719
2733
  };
2720
2734
  }
2735
+ async tenantOf(target) {
2736
+ const thread = this.t.agentThread;
2737
+ if ("toolCallId" in target) {
2738
+ const [row2] = await this.db.select({
2739
+ tenantRef: thread.tenantRef
2740
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq2(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(thread, eq2(this.t.agentMessage.threadId, thread.id)).where(eq2(this.t.agentToolCall.id, target.toolCallId));
2741
+ return row2 === void 0 ? null : {
2742
+ tenantRef: row2.tenantRef ?? null
2743
+ };
2744
+ }
2745
+ const [row] = await this.db.select({
2746
+ tenantRef: thread.tenantRef
2747
+ }).from(thread).where(and2("threadId" in target ? eq2(thread.id, target.threadId) : eq2(thread.activeStreamId, target.runId), isNull2(thread.deletedAt)));
2748
+ return row === void 0 ? null : {
2749
+ tenantRef: row.tenantRef ?? null
2750
+ };
2751
+ }
2721
2752
  async ownerOfActiveStream(runId) {
2722
2753
  const [thread] = await this.db.select({
2723
2754
  actorRef: this.t.agentThread.actorRef
@@ -3313,6 +3344,17 @@ var DrizzleAgentStore = class {
3313
3344
  * it, and no usage row crosses the wire.
3314
3345
  */
3315
3346
  async usageWindows(actorRef, ranges) {
3347
+ return this.sumUsageWindows(eq2(this.t.agentTokenUsage.actorRef, actorRef), ranges);
3348
+ }
3349
+ /**
3350
+ * {@link usageWindows} over the tenant's rows (every actor's, or `actorRef`'s only), served by the
3351
+ * `(tenant_ref, created_at)` index.
3352
+ */
3353
+ async usageWindowsForTenant(tenantRef, ranges, actorRef) {
3354
+ const usage = this.t.agentTokenUsage;
3355
+ return this.sumUsageWindows(and2(eq2(usage.tenantRef, tenantRef), actorRef !== void 0 ? eq2(usage.actorRef, actorRef) : void 0), ranges);
3356
+ }
3357
+ async sumUsageWindows(owner, ranges) {
3316
3358
  if (ranges.length === 0) {
3317
3359
  return [];
3318
3360
  }
@@ -3330,7 +3372,7 @@ var DrizzleAgentStore = class {
3330
3372
  });
3331
3373
  const from = new Date(Math.min(...bounds.map(({ start }) => start.getTime())));
3332
3374
  const to = new Date(Math.max(...bounds.map(({ end }) => end.getTime())));
3333
- const [row] = await this.db.select(columns).from(usage).where(and2(eq2(usage.actorRef, actorRef), within(from, to), eq2(usage.countsTowardsQuota, true)));
3375
+ const [row] = await this.db.select(columns).from(usage).where(and2(owner, within(from, to), eq2(usage.countsTowardsQuota, true)));
3334
3376
  return bounds.map((_, index4) => ({
3335
3377
  usedTokens: Number(row?.[`tokens${index4}`] ?? 0),
3336
3378
  costUsd: Number(row?.[`cost${index4}`] ?? 0),
@@ -3442,7 +3484,7 @@ __name(toQueuedMessage, "toQueuedMessage");
3442
3484
 
3443
3485
  // src/drizzle-governance-queries.ts
3444
3486
  import { bucketByActor, bucketByFeature, bucketByModel, bucketByThread, bucketUsageBreakdown, bucketUsageTrend, dayBoundsUtc, rollupThreadUsage, summarizeGenuiCalls, truncateDetailContent, usageRangeBounds } from "@dudousxd/nestjs-agent-core";
3445
- import { and as and3, asc as asc3, count, desc as desc2, eq as eq3, gte as gte2, inArray as inArray2, isNull as isNull3, like, lt, lte as lte3, sql as sql4, sum } from "drizzle-orm";
3487
+ import { and as and3, asc as asc3, count, desc as desc2, eq as eq3, gte as gte2, inArray as inArray2, isNull as isNull3, like, lt, lte as lte3, or as or3, sql as sql4, sum } from "drizzle-orm";
3446
3488
  var UNCLASSIFIED_ERROR_CODE = "unknown";
3447
3489
  var DEFAULT_AGENT_BUCKET = "(default)";
3448
3490
  var TOOL_CALL_STATUSES = [
@@ -3624,19 +3666,55 @@ function percentileMs(sortedDurationsMs, p) {
3624
3666
  return sortedDurationsMs[offset] ?? null;
3625
3667
  }
3626
3668
  __name(percentileMs, "percentileMs");
3627
- var DrizzleGovernanceQueries = class {
3669
+ var DrizzleGovernanceQueries = class _DrizzleGovernanceQueries {
3628
3670
  static {
3629
3671
  __name(this, "DrizzleGovernanceQueries");
3630
3672
  }
3673
+ source;
3631
3674
  pricingStore;
3675
+ tenant;
3632
3676
  db;
3633
3677
  dialect;
3634
3678
  t;
3635
- constructor(db, pricingStore) {
3679
+ /**
3680
+ * `tenant`: the rows these queries may see (see {@link forTenant}); absent → every row. Threads by
3681
+ * their `tenant_ref`; runs, messages, tool calls and generative-UI calls by their thread's; usage
3682
+ * by its own `tenant_ref`.
3683
+ */
3684
+ constructor(source, pricingStore, tenant) {
3685
+ this.source = source;
3636
3686
  this.pricingStore = pricingStore;
3637
- this.dialect = agentDialectOf(db);
3687
+ this.tenant = tenant;
3688
+ this.dialect = agentDialectOf(source);
3638
3689
  this.t = agentTablesFor(this.dialect);
3639
- this.db = asBuilder(db);
3690
+ this.db = asBuilder(source);
3691
+ }
3692
+ /** These queries narrowed to the rows `filter` may see — the console's tenant scope. */
3693
+ forTenant(filter) {
3694
+ return new _DrizzleGovernanceQueries(this.source, this.pricingStore, filter);
3695
+ }
3696
+ /** The matching rule on a `tenant_ref` column; `undefined` (no condition) without a scope. */
3697
+ tenantOn(column) {
3698
+ const filter = this.tenant;
3699
+ if (filter === void 0) return void 0;
3700
+ if (filter.tenant === void 0) return isNull3(column);
3701
+ return filter.nulls ? or3(eq3(column, filter.tenant), isNull3(column)) : eq3(column, filter.tenant);
3702
+ }
3703
+ /** Rows keyed by a thread id whose thread the scope may see; `undefined` without a scope. */
3704
+ threadIn(threadId) {
3705
+ const visible = this.tenantOn(this.t.agentThread.tenantRef);
3706
+ if (visible === void 0) return void 0;
3707
+ return inArray2(threadId, this.db.select({
3708
+ id: this.t.agentThread.id
3709
+ }).from(this.t.agentThread).where(visible));
3710
+ }
3711
+ /** Tool calls (by `message_id`) on a thread the scope may see; `undefined` without a scope. */
3712
+ toolCallIn(messageId) {
3713
+ const visible = this.threadIn(this.t.agentMessage.threadId);
3714
+ if (visible === void 0) return void 0;
3715
+ return inArray2(messageId, this.db.select({
3716
+ id: this.t.agentMessage.id
3717
+ }).from(this.t.agentMessage).where(visible));
3640
3718
  }
3641
3719
  async loadPricing() {
3642
3720
  const prices = await this.pricingStore.listCurrentPrices();
@@ -3677,7 +3755,7 @@ var DrizzleGovernanceQueries = class {
3677
3755
  audioSeconds: usage.audioSeconds,
3678
3756
  characters: usage.characters
3679
3757
  } : {}
3680
- }).from(usage).where(and3(gte2(this.t.agentTokenUsage.createdAt, start), lt(this.t.agentTokenUsage.createdAt, end)));
3758
+ }).from(usage).where(and3(gte2(this.t.agentTokenUsage.createdAt, start), lt(this.t.agentTokenUsage.createdAt, end), this.tenantOn(usage.tenantRef)));
3681
3759
  return rows.map(toUsageInput);
3682
3760
  }
3683
3761
  async spendByModel(range) {
@@ -3742,7 +3820,7 @@ var DrizzleGovernanceQueries = class {
3742
3820
  threadId: this.t.agentMessage.threadId,
3743
3821
  createdAt: this.t.agentToolCall.createdAt,
3744
3822
  runId: this.t.agentToolCall.runId
3745
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq3(this.t.agentToolCall.messageId, this.t.agentMessage.id)).orderBy(desc2(this.t.agentToolCall.createdAt), desc2(this.t.agentToolCall.id)).limit(limit);
3823
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq3(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(this.threadIn(this.t.agentMessage.threadId)).orderBy(desc2(this.t.agentToolCall.createdAt), desc2(this.t.agentToolCall.id)).limit(limit);
3746
3824
  return rows.map((row) => ({
3747
3825
  toolCallId: row.toolCallId,
3748
3826
  toolName: row.toolName,
@@ -3809,7 +3887,7 @@ var DrizzleGovernanceQueries = class {
3809
3887
  });
3810
3888
  }
3811
3889
  async recentThreads(limit) {
3812
- const threads = await this.db.select().from(this.t.agentThread).where(isNull3(this.t.agentThread.deletedAt)).orderBy(desc2(this.t.agentThread.updatedAt), desc2(this.t.agentThread.id)).limit(limit);
3890
+ const threads = await this.db.select().from(this.t.agentThread).where(and3(isNull3(this.t.agentThread.deletedAt), this.tenantOn(this.t.agentThread.tenantRef))).orderBy(desc2(this.t.agentThread.updatedAt), desc2(this.t.agentThread.id)).limit(limit);
3813
3891
  return this.toThreadActivityRows(threads);
3814
3892
  }
3815
3893
  /** The range's runs, with only the columns the rollups read. */
@@ -3824,7 +3902,7 @@ var DrizzleGovernanceQueries = class {
3824
3902
  ttftMs: run.ttftMs,
3825
3903
  parentRunId: run.parentRunId,
3826
3904
  startedAt: run.startedAt
3827
- }).from(run).where(and3(gte2(run.startedAt, start), lte3(run.startedAt, end)));
3905
+ }).from(run).where(and3(gte2(run.startedAt, start), lte3(run.startedAt, end), this.threadIn(run.threadId)));
3828
3906
  }
3829
3907
  async runMetrics(range) {
3830
3908
  const runs = await this.runsInRange(range);
@@ -3890,7 +3968,7 @@ var DrizzleGovernanceQueries = class {
3890
3968
  const { start, end } = dayBoundsUtc(range);
3891
3969
  const runs = await this.db.select({
3892
3970
  errorCode: this.t.agentRun.errorCode
3893
- }).from(this.t.agentRun).where(and3(gte2(this.t.agentRun.startedAt, start), lte3(this.t.agentRun.startedAt, end), eq3(this.t.agentRun.status, "failed")));
3971
+ }).from(this.t.agentRun).where(and3(gte2(this.t.agentRun.startedAt, start), lte3(this.t.agentRun.startedAt, end), eq3(this.t.agentRun.status, "failed"), this.threadIn(this.t.agentRun.threadId)));
3894
3972
  const byError = /* @__PURE__ */ new Map();
3895
3973
  for (const run of runs) {
3896
3974
  const errorCode = run.errorCode ?? UNCLASSIFIED_ERROR_CODE;
@@ -3930,7 +4008,7 @@ var DrizzleGovernanceQueries = class {
3930
4008
  return result;
3931
4009
  }
3932
4010
  async recentRuns(limit) {
3933
- const runs = await this.db.select().from(this.t.agentRun).orderBy(desc2(this.t.agentRun.startedAt), desc2(this.t.agentRun.id)).limit(limit);
4011
+ const runs = await this.db.select().from(this.t.agentRun).where(this.threadIn(this.t.agentRun.threadId)).orderBy(desc2(this.t.agentRun.startedAt), desc2(this.t.agentRun.id)).limit(limit);
3934
4012
  return runs.map(toRecentRunRow);
3935
4013
  }
3936
4014
  /**
@@ -3949,7 +4027,7 @@ var DrizzleGovernanceQueries = class {
3949
4027
  agentName: this.t.agentMessage.agentName,
3950
4028
  requestedAt: this.t.agentToolCall.createdAt,
3951
4029
  runId: this.t.agentToolCall.runId
3952
- }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq3(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, eq3(this.t.agentMessage.threadId, this.t.agentThread.id)).where(eq3(this.t.agentToolCall.status, "pending_approval")).orderBy(this.t.agentToolCall.createdAt, this.t.agentToolCall.id).limit(limit);
4030
+ }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq3(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, eq3(this.t.agentMessage.threadId, this.t.agentThread.id)).where(and3(eq3(this.t.agentToolCall.status, "pending_approval"), this.tenantOn(this.t.agentThread.tenantRef))).orderBy(this.t.agentToolCall.createdAt, this.t.agentToolCall.id).limit(limit);
3953
4031
  return rows.map((row) => ({
3954
4032
  toolCallId: row.toolCallId,
3955
4033
  toolName: row.toolName,
@@ -3976,7 +4054,7 @@ var DrizzleGovernanceQueries = class {
3976
4054
  toolType: this.t.agentToolCall.toolType,
3977
4055
  status: this.t.agentToolCall.status,
3978
4056
  executionMs: this.t.agentToolCall.executionMs
3979
- }).from(this.t.agentToolCall).where(and3(gte2(this.t.agentToolCall.createdAt, start), lte3(this.t.agentToolCall.createdAt, end)));
4057
+ }).from(this.t.agentToolCall).where(and3(gte2(this.t.agentToolCall.createdAt, start), lte3(this.t.agentToolCall.createdAt, end), this.toolCallIn(this.t.agentToolCall.messageId)));
3980
4058
  const byTool = /* @__PURE__ */ new Map();
3981
4059
  for (const call of calls) {
3982
4060
  const key2 = `${call.toolName} ${call.toolType}`;
@@ -4026,7 +4104,7 @@ var DrizzleGovernanceQueries = class {
4026
4104
  if (filters?.toolType !== void 0 && !isToolKind(filters.toolType)) {
4027
4105
  return emptyPage(query);
4028
4106
  }
4029
- const whereClause = and3(filters?.toolName !== void 0 ? eq3(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.toolType !== void 0 && isToolKind(filters.toolType) ? eq3(this.t.agentToolCall.toolType, filters.toolType) : void 0, filters?.status !== void 0 && isToolCallStatus(filters.status) ? eq3(this.t.agentToolCall.status, filters.status) : void 0, filters?.threadId !== void 0 ? eq3(this.t.agentMessage.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte3(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
4107
+ const whereClause = and3(filters?.toolName !== void 0 ? eq3(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.toolType !== void 0 && isToolKind(filters.toolType) ? eq3(this.t.agentToolCall.toolType, filters.toolType) : void 0, filters?.status !== void 0 && isToolCallStatus(filters.status) ? eq3(this.t.agentToolCall.status, filters.status) : void 0, filters?.threadId !== void 0 ? eq3(this.t.agentMessage.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte3(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0, this.threadIn(this.t.agentMessage.threadId));
4030
4108
  const [totalRow] = await this.db.select({
4031
4109
  value: count()
4032
4110
  }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq3(this.t.agentToolCall.messageId, this.t.agentMessage.id)).where(whereClause);
@@ -4062,7 +4140,7 @@ var DrizzleGovernanceQueries = class {
4062
4140
  */
4063
4141
  async threadsPage(query) {
4064
4142
  const filters = query.where;
4065
- const whereClause = and3(isNull3(this.t.agentThread.deletedAt), filters?.actorRef !== void 0 ? eq3(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.title !== void 0 ? like(sql4`lower(${this.t.agentThread.title})`, `%${filters.title.toLowerCase()}%`) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentThread.updatedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte3(this.t.agentThread.updatedAt, dayEndUtc(filters.toDay)) : void 0);
4143
+ const whereClause = and3(isNull3(this.t.agentThread.deletedAt), filters?.actorRef !== void 0 ? eq3(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.title !== void 0 ? like(sql4`lower(${this.t.agentThread.title})`, `%${filters.title.toLowerCase()}%`) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentThread.updatedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte3(this.t.agentThread.updatedAt, dayEndUtc(filters.toDay)) : void 0, this.tenantOn(this.t.agentThread.tenantRef));
4066
4144
  const [totalRow] = await this.db.select({
4067
4145
  value: count()
4068
4146
  }).from(this.t.agentThread).where(whereClause);
@@ -4084,7 +4162,7 @@ var DrizzleGovernanceQueries = class {
4084
4162
  if (filters?.status !== void 0 && !isRunStatus(filters.status)) {
4085
4163
  return emptyPage(query);
4086
4164
  }
4087
- const whereClause = and3(filters?.agentName !== void 0 ? eq3(this.t.agentRun.agentName, filters.agentName) : void 0, filters?.status !== void 0 && isRunStatus(filters.status) ? eq3(this.t.agentRun.status, filters.status) : void 0, filters?.errorCode !== void 0 ? eq3(this.t.agentRun.errorCode, filters.errorCode) : void 0, filters?.threadId !== void 0 ? eq3(this.t.agentRun.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentRun.startedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte3(this.t.agentRun.startedAt, dayEndUtc(filters.toDay)) : void 0);
4165
+ const whereClause = and3(filters?.agentName !== void 0 ? eq3(this.t.agentRun.agentName, filters.agentName) : void 0, filters?.status !== void 0 && isRunStatus(filters.status) ? eq3(this.t.agentRun.status, filters.status) : void 0, filters?.errorCode !== void 0 ? eq3(this.t.agentRun.errorCode, filters.errorCode) : void 0, filters?.threadId !== void 0 ? eq3(this.t.agentRun.threadId, filters.threadId) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentRun.startedAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte3(this.t.agentRun.startedAt, dayEndUtc(filters.toDay)) : void 0, this.threadIn(this.t.agentRun.threadId));
4088
4166
  const [totalRow] = await this.db.select({
4089
4167
  value: count()
4090
4168
  }).from(this.t.agentRun).where(whereClause);
@@ -4108,7 +4186,7 @@ var DrizzleGovernanceQueries = class {
4108
4186
  */
4109
4187
  async approvalsPage(query) {
4110
4188
  const filters = query.where;
4111
- const whereClause = and3(eq3(this.t.agentToolCall.status, "pending_approval"), filters?.toolName !== void 0 ? eq3(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.threadId !== void 0 ? eq3(this.t.agentThread.id, filters.threadId) : void 0, filters?.actorRef !== void 0 ? eq3(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.agentName !== void 0 ? eq3(this.t.agentMessage.agentName, filters.agentName) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte3(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0);
4189
+ const whereClause = and3(eq3(this.t.agentToolCall.status, "pending_approval"), filters?.toolName !== void 0 ? eq3(this.t.agentToolCall.toolName, filters.toolName) : void 0, filters?.threadId !== void 0 ? eq3(this.t.agentThread.id, filters.threadId) : void 0, filters?.actorRef !== void 0 ? eq3(this.t.agentThread.actorRef, filters.actorRef) : void 0, filters?.agentName !== void 0 ? eq3(this.t.agentMessage.agentName, filters.agentName) : void 0, filters?.fromDay !== void 0 ? gte2(this.t.agentToolCall.createdAt, dayStartUtc(filters.fromDay)) : void 0, filters?.toDay !== void 0 ? lte3(this.t.agentToolCall.createdAt, dayEndUtc(filters.toDay)) : void 0, this.tenantOn(this.t.agentThread.tenantRef));
4112
4190
  const [totalRow] = await this.db.select({
4113
4191
  value: count()
4114
4192
  }).from(this.t.agentToolCall).innerJoin(this.t.agentMessage, eq3(this.t.agentToolCall.messageId, this.t.agentMessage.id)).innerJoin(this.t.agentThread, eq3(this.t.agentMessage.threadId, this.t.agentThread.id)).where(whereClause);
@@ -4149,7 +4227,7 @@ var DrizzleGovernanceQueries = class {
4149
4227
  const [row] = await this.db.select({
4150
4228
  run: this.t.agentRun,
4151
4229
  thread: this.t.agentThread
4152
- }).from(this.t.agentRun).innerJoin(this.t.agentThread, eq3(this.t.agentRun.threadId, this.t.agentThread.id)).where(eq3(this.t.agentRun.id, runId)).limit(1);
4230
+ }).from(this.t.agentRun).innerJoin(this.t.agentThread, eq3(this.t.agentRun.threadId, this.t.agentThread.id)).where(and3(eq3(this.t.agentRun.id, runId), this.tenantOn(this.t.agentThread.tenantRef))).limit(1);
4153
4231
  if (row === void 0) {
4154
4232
  return null;
4155
4233
  }
@@ -4173,7 +4251,7 @@ var DrizzleGovernanceQueries = class {
4173
4251
  * message. Soft-deleted threads are returned with `deleted: true`; an audit still needs them.
4174
4252
  */
4175
4253
  async threadDetail(query) {
4176
- const [thread] = await this.db.select().from(this.t.agentThread).where(eq3(this.t.agentThread.id, query.threadId)).limit(1);
4254
+ const [thread] = await this.db.select().from(this.t.agentThread).where(and3(eq3(this.t.agentThread.id, query.threadId), this.tenantOn(this.t.agentThread.tenantRef))).limit(1);
4177
4255
  if (thread === void 0) {
4178
4256
  return null;
4179
4257
  }
@@ -4225,7 +4303,7 @@ var DrizzleGovernanceQueries = class {
4225
4303
  async genuiStats(range) {
4226
4304
  const { start, end } = dayBoundsUtc(range);
4227
4305
  const table = this.t.agentGenuiCall;
4228
- const rows = await this.db.select().from(table).where(and3(gte2(table.createdAt, start.getTime()), lte3(table.createdAt, end.getTime())));
4306
+ const rows = await this.db.select().from(table).where(and3(gte2(table.createdAt, start.getTime()), lte3(table.createdAt, end.getTime()), this.threadIn(table.threadId)));
4229
4307
  return summarizeGenuiCalls(rows.map(toGenuiCallRow));
4230
4308
  }
4231
4309
  /** Tool-call counts for a set of messages in ONE grouped query — the detail view's no-N+1 guarantee. */
@@ -4616,7 +4694,7 @@ var DrizzleChannelStore = class {
4616
4694
 
4617
4695
  // src/drizzle-poppy-store.ts
4618
4696
  import { newEventId } from "@dudousxd/nestjs-agent-core";
4619
- import { and as and8, desc as desc3, eq as eq9, gt as gt4, isNull as isNull4, lt as lt4, lte as lte5, or as or3 } from "drizzle-orm";
4697
+ import { and as and8, desc as desc3, eq as eq9, gt as gt4, isNull as isNull4, lt as lt4, lte as lte5, or as or4 } from "drizzle-orm";
4620
4698
  var MAX_APPEND_ATTEMPTS = 50;
4621
4699
  var sleep = /* @__PURE__ */ __name((ms) => new Promise((resolve) => setTimeout(resolve, ms)), "sleep");
4622
4700
  var nullable = /* @__PURE__ */ __name((value) => value == null ? null : String(value), "nullable");
@@ -4846,7 +4924,7 @@ var DrizzlePoppyStore = class {
4846
4924
  const taken = await affectedRows(this.dialect, this.db.update(table).set({
4847
4925
  readerHolder: holder,
4848
4926
  readerUntil: now + ttlMs
4849
- }).where(and8(eq9(table.id, conversationId), or3(isNull4(table.readerHolder), eq9(table.readerHolder, holder), lte5(table.readerUntil, now)))), table.id);
4927
+ }).where(and8(eq9(table.id, conversationId), or4(isNull4(table.readerHolder), eq9(table.readerHolder, holder), lte5(table.readerUntil, now)))), table.id);
4850
4928
  if (taken === 1) return true;
4851
4929
  if (this.dialect !== "mysql") return false;
4852
4930
  const [row] = await this.db.select({
@@ -4995,7 +5073,7 @@ __name(toConnection, "toConnection");
4995
5073
  // src/drizzle-rag-ingestion-log.ts
4996
5074
  import { subscribe, unsubscribe } from "diagnostics_channel";
4997
5075
  import { Injectable, Logger } from "@nestjs/common";
4998
- import { and as and10, asc as asc6, count as count2, desc as desc4, eq as eq11, gt as gt5, lt as lt5, or as or4 } from "drizzle-orm";
5076
+ import { and as and10, asc as asc6, count as count2, desc as desc4, eq as eq11, gt as gt5, lt as lt5, or as or5 } from "drizzle-orm";
4999
5077
  function _ts_decorate(decorators, target, key2, desc5) {
5000
5078
  var c = arguments.length, r = c < 3 ? target : desc5 === null ? desc5 = Object.getOwnPropertyDescriptor(target, key2) : desc5, d;
5001
5079
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -5249,7 +5327,7 @@ var DrizzleRagIngestionLog = class _DrizzleRagIngestionLog {
5249
5327
  if (cursor === void 0) {
5250
5328
  return base;
5251
5329
  }
5252
- return and10(base, or4(lt5(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), and10(eq11(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), gt5(this.t.ragIngestionLog.documentId, cursor.documentId))));
5330
+ return and10(base, or5(lt5(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), and10(eq11(this.t.ragIngestionLog.updatedAt, cursor.updatedAt), gt5(this.t.ragIngestionLog.documentId, cursor.documentId))));
5253
5331
  }
5254
5332
  /**
5255
5333
  * Upsert one outcome. Keyed by document id so the row always reflects the *current* state — a