@dudousxd/nestjs-agent-core 0.10.0 → 0.11.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
@@ -1044,6 +1044,13 @@ interface ToolStatRow {
1044
1044
  calls: number;
1045
1045
  failed: number;
1046
1046
  rejected: number;
1047
+ /**
1048
+ * p50 (median) of executionMs across calls that recorded one; null when none carry it. Reported
1049
+ * alongside p95 rather than a mean: tool latency is long-tailed (a retry or a slow upstream drags
1050
+ * an average somewhere no single call ever was), so the pair "typical / tail" is what an operator
1051
+ * can actually act on.
1052
+ */
1053
+ p50ExecutionMs: number | null;
1047
1054
  /** p95 of executionMs across executed calls; null when none carry it. */
1048
1055
  p95ExecutionMs: number | null;
1049
1056
  }
@@ -1095,6 +1102,115 @@ interface RunWhere {
1095
1102
  fromDay?: string;
1096
1103
  toDay?: string;
1097
1104
  }
1105
+ /** Filters for {@link AgentGovernanceQueries.approvalsPage}. */
1106
+ interface ApprovalWhere {
1107
+ toolName?: string;
1108
+ threadId?: string;
1109
+ /** The requesting thread's owner. */
1110
+ actorRef?: string;
1111
+ agentName?: string;
1112
+ /** Inclusive UTC day bounds on when the approval was requested, `YYYY-MM-DD`. */
1113
+ fromDay?: string;
1114
+ toDay?: string;
1115
+ }
1116
+ /** One tool call inside a {@link GovernanceRunDetail}, with the execution outcome a list row can't afford to carry. */
1117
+ interface RunToolCallRow {
1118
+ toolCallId: string;
1119
+ toolName: string;
1120
+ toolType: string;
1121
+ status: string;
1122
+ /** Wall time of the execution; null for a call that never executed (rejected/still pending). */
1123
+ executionMs: number | null;
1124
+ /** Who executed/decided it, when the store recorded an attribution. */
1125
+ executedByRef: string | null;
1126
+ /** The failure text for a `failed` call; null otherwise. */
1127
+ error: string | null;
1128
+ /** ISO timestamp. */
1129
+ createdAt: string;
1130
+ }
1131
+ /** The owning thread's headline, carried on a drill-down so it can be named without a second read. */
1132
+ interface DetailThreadRef {
1133
+ threadId: string;
1134
+ title: string;
1135
+ actorRef: string;
1136
+ /** True when the thread is soft-deleted — its history is still readable, the thread is not. */
1137
+ deleted: boolean;
1138
+ }
1139
+ /**
1140
+ * Everything a run drill-down renders: the run row itself, its owning thread's headline, and the
1141
+ * tool calls attributed to it.
1142
+ *
1143
+ * `toolCalls` is empty for a run recorded before tool calls carried a `runId` (the column is
1144
+ * nullable and pre-rollout rows have none) — indistinguishable, from here, from a run that called
1145
+ * no tools. There is deliberately no cost figure: the token ledger has no run column, so per-run
1146
+ * spend is not attributable without a store migration.
1147
+ */
1148
+ interface GovernanceRunDetail {
1149
+ run: RecentRunRow;
1150
+ thread: DetailThreadRef;
1151
+ /** The run's tool calls, oldest first — the order they were requested in. */
1152
+ toolCalls: RunToolCallRow[];
1153
+ }
1154
+ /** One message inside a {@link GovernanceThreadDetail}. `content` is capped server-side. */
1155
+ interface ThreadMessageRow {
1156
+ messageId: string;
1157
+ role: string;
1158
+ /** Message text, cut to {@link THREAD_DETAIL_CONTENT_CHARS}; see `truncated`. */
1159
+ content: string;
1160
+ /** True when `content` was cut — the console shows an explicit "…" rather than implying the tail. */
1161
+ truncated: boolean;
1162
+ agentName: string | null;
1163
+ /** How many tool calls this message requested. */
1164
+ toolCallCount: number;
1165
+ /** ISO timestamp. */
1166
+ createdAt: string;
1167
+ }
1168
+ /** Token/cost rollup across a thread's whole ledger (not range-scoped — a thread's lifetime). */
1169
+ interface ThreadUsageRollup {
1170
+ /** Ledger rows, i.e. billed turns. */
1171
+ requests: number;
1172
+ inputTokens: number;
1173
+ outputTokens: number;
1174
+ totalTokens: number;
1175
+ costUsd: number;
1176
+ }
1177
+ /** Everything a thread drill-down renders, in one call. */
1178
+ interface GovernanceThreadDetail {
1179
+ /** The thread's own activity row (`messageCount` is the thread total, not the page below). */
1180
+ thread: ThreadActivityRow;
1181
+ /** True when the thread is soft-deleted. */
1182
+ deleted: boolean;
1183
+ usage: ThreadUsageRollup;
1184
+ /** The thread's runs, newest first, capped at the query's `runLimit`. */
1185
+ runs: RecentRunRow[];
1186
+ /** Runs on this thread in total — `runs.length < runTotal` means the cap bit. */
1187
+ runTotal: number;
1188
+ /** The thread's messages, newest first, capped at the query's `messageLimit`. */
1189
+ messages: ThreadMessageRow[];
1190
+ }
1191
+ /** Row caps for {@link AgentGovernanceQueries.threadDetail}, already clamped by the caller. */
1192
+ interface GovernanceThreadDetailQuery {
1193
+ threadId: string;
1194
+ /** Max messages returned, newest first. */
1195
+ messageLimit: number;
1196
+ /** Max runs returned, newest first. */
1197
+ runLimit: number;
1198
+ }
1199
+ /**
1200
+ * Per-message content cap for {@link ThreadMessageRow.content}. A drill-down is a triage view, not a
1201
+ * transcript reader: capping here keeps one response bounded regardless of how long an assistant
1202
+ * turn ran. Shared by every adapter so the cut is identical wherever the console is served from.
1203
+ */
1204
+ declare const THREAD_DETAIL_CONTENT_CHARS = 2000;
1205
+ /**
1206
+ * Cut a message body to {@link THREAD_DETAIL_CONTENT_CHARS}, reporting whether it was cut. Lives
1207
+ * next to the cap so every adapter truncates at the same boundary — a console comparing two stores
1208
+ * must not see two different "…".
1209
+ */
1210
+ declare function truncateDetailContent(content: string): {
1211
+ content: string;
1212
+ truncated: boolean;
1213
+ };
1098
1214
  /**
1099
1215
  * The governance read-model. Cost is `inputTokens/1e6 * inputPricePer1m + outputTokens/1e6 *
1100
1216
  * outputPricePer1m` against the current pricing row per model; an unpriced model contributes 0 cost
@@ -1113,8 +1229,19 @@ interface AgentGovernanceQueries {
1113
1229
  runErrors(range: GovernanceRange): Promise<RunErrorBreakdownRow[]>;
1114
1230
  runTrend(range: GovernanceRange): Promise<RunTrendPoint[]>;
1115
1231
  recentRuns(limit: number): Promise<RecentRunRow[]>;
1116
- /** Tool calls sitting `pending_approval`, oldest first — an inbox drains from the back. Capped at `limit`. */
1232
+ /**
1233
+ * Tool calls sitting `pending_approval`, oldest first — an inbox drains from the back. Capped at
1234
+ * `limit`, with NO total: a caller that needs to know whether the cap hid anything wants
1235
+ * {@link approvalsPage} instead.
1236
+ */
1117
1237
  pendingApprovals(limit: number): Promise<PendingApprovalRow[]>;
1238
+ /**
1239
+ * Paged, filterable approvals inbox, oldest first (same ordering as `pendingApprovals`). Unlike
1240
+ * that method this reports `total`, so a console can page a backlog and say how much of it is
1241
+ * off-screen — the one failure this surface cannot afford is a pending approval nobody sees.
1242
+ * An adapter without the backing data returns an empty page (`total: 0`) rather than throwing.
1243
+ */
1244
+ approvalsPage(query: GovernancePageQuery<ApprovalWhere>): Promise<GovernancePage<PendingApprovalRow>>;
1118
1245
  /** Per-tool call/failure/rejection/latency rollup over the range, highest call count first. */
1119
1246
  toolStats(range: GovernanceRange): Promise<ToolStatRow[]>;
1120
1247
  /**
@@ -1132,6 +1259,21 @@ interface AgentGovernanceQueries {
1132
1259
  * by a store without run recording (no `recordRunStart`) returns an empty page (`total: 0`).
1133
1260
  */
1134
1261
  runsPage(query: GovernancePageQuery<RunWhere>): Promise<GovernancePage<RecentRunRow>>;
1262
+ /**
1263
+ * One run with its owning thread and its tool calls — the drill-down behind a row in the runs
1264
+ * table. `null` when no run has that id. ONE call, not one per tool call: a failed run is the
1265
+ * thing an operator opens first and it should not cost a query per step.
1266
+ *
1267
+ * An adapter backed by a store without run recording returns `null` for every id.
1268
+ */
1269
+ runDetail(runId: string): Promise<GovernanceRunDetail | null>;
1270
+ /**
1271
+ * One thread with its lifetime usage rollup, its recent runs and its recent messages — the
1272
+ * drill-down behind a row in the threads table. `null` when no thread has that id; a soft-deleted
1273
+ * thread IS returned (with `deleted: true`), because "what did the thread we just deleted do" is
1274
+ * exactly the question an audit asks.
1275
+ */
1276
+ threadDetail(query: GovernanceThreadDetailQuery): Promise<GovernanceThreadDetail | null>;
1135
1277
  }
1136
1278
 
1137
1279
  /**
@@ -1248,6 +1390,12 @@ declare function bucketByThread(rows: GovernanceUsageInput[], prices: ReadonlyMa
1248
1390
  limit: number;
1249
1391
  includeUnknownThreads: boolean;
1250
1392
  }): ThreadSpendRow[];
1393
+ /**
1394
+ * Sum an already-scoped set of usage rows into one rollup — the thread drill-down's headline. Same
1395
+ * `rowCost` as every bucketer above (provider-reported cost wins, else the cache-aware estimate), so
1396
+ * a thread's detail cost and its row in the by-thread ranking can never disagree.
1397
+ */
1398
+ declare function rollupThreadUsage(rows: GovernanceUsageInput[], prices: ReadonlyMap<string, ModelPrice>): ThreadUsageRollup;
1251
1399
  /** Aggregate usage rows into a daily token/cost trend, ascending by day. */
1252
1400
  declare function bucketUsageTrend(rows: GovernanceUsageInput[], prices: ReadonlyMap<string, ModelPrice>): UsageTrendPoint[];
1253
1401
  /** Turn an inclusive `YYYY-MM-DD` day range into the UTC datetime bounds used to filter usage rows. */
@@ -1597,4 +1745,4 @@ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
1597
1745
  */
1598
1746
  declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
1599
1747
 
1600
- export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MODEL, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, type AiToolCtx, type AppendMessageInput, type AttachmentStagingStore, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, type Decision, DefaultRolesPolicy, type EmbeddingProvider, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceUsageInput, type InvokeWithTransientRetryOptions, type LlmStepEnvelope, type MessageAttachment, type MessageRole, type MessageUsage, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type PageContext, type Passage, type PendingApprovalRow, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RerankOptions, type Reranker, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, type RunErrorBreakdownRow, type RunMetrics, type RunTrendPoint, type RunWhere, type SinkWriter, type StageAttachmentInput, type StoredMessage, type StreamError, type ThreadActivityRow, type ThreadDetail, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolCallWhere, type ToolDefinition, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type ToolTransientRetryNumbers, type ToolTransientRetryOptions, type ToolTransientRetrySetting, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, agentDiagnosticKey, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, dayBoundsUtc, encodeStreamEvent, estimateCost, filterToolsByAllowList, filterToolsByRole, invokeWithTransientRetry, isTransientToolError, publishAgentDelegated, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentToolCall, publishAgentToolRetry, resolveToolTransientRetryNumbers, runAgentLoop, seedModelPrices, traceLlmTurn, traceToolExecution, withToolTimeout };
1748
+ export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MODEL, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, type AiToolCtx, type AppendMessageInput, type ApprovalWhere, type AttachmentStagingStore, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, type Decision, DefaultRolesPolicy, type DetailThreadRef, type EmbeddingProvider, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, type InvokeWithTransientRetryOptions, type LlmStepEnvelope, type MessageAttachment, type MessageRole, type MessageUsage, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type PageContext, type Passage, type PendingApprovalRow, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RerankOptions, type Reranker, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, type SinkWriter, type StageAttachmentInput, type StoredMessage, type StreamError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, type ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolCallWhere, type ToolDefinition, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type ToolTransientRetryNumbers, type ToolTransientRetryOptions, type ToolTransientRetrySetting, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, agentDiagnosticKey, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, dayBoundsUtc, encodeStreamEvent, estimateCost, filterToolsByAllowList, filterToolsByRole, invokeWithTransientRetry, isTransientToolError, publishAgentDelegated, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentToolCall, publishAgentToolRetry, resolveToolTransientRetryNumbers, rollupThreadUsage, runAgentLoop, seedModelPrices, traceLlmTurn, traceToolExecution, truncateDetailContent, withToolTimeout };
package/dist/index.d.ts CHANGED
@@ -1044,6 +1044,13 @@ interface ToolStatRow {
1044
1044
  calls: number;
1045
1045
  failed: number;
1046
1046
  rejected: number;
1047
+ /**
1048
+ * p50 (median) of executionMs across calls that recorded one; null when none carry it. Reported
1049
+ * alongside p95 rather than a mean: tool latency is long-tailed (a retry or a slow upstream drags
1050
+ * an average somewhere no single call ever was), so the pair "typical / tail" is what an operator
1051
+ * can actually act on.
1052
+ */
1053
+ p50ExecutionMs: number | null;
1047
1054
  /** p95 of executionMs across executed calls; null when none carry it. */
1048
1055
  p95ExecutionMs: number | null;
1049
1056
  }
@@ -1095,6 +1102,115 @@ interface RunWhere {
1095
1102
  fromDay?: string;
1096
1103
  toDay?: string;
1097
1104
  }
1105
+ /** Filters for {@link AgentGovernanceQueries.approvalsPage}. */
1106
+ interface ApprovalWhere {
1107
+ toolName?: string;
1108
+ threadId?: string;
1109
+ /** The requesting thread's owner. */
1110
+ actorRef?: string;
1111
+ agentName?: string;
1112
+ /** Inclusive UTC day bounds on when the approval was requested, `YYYY-MM-DD`. */
1113
+ fromDay?: string;
1114
+ toDay?: string;
1115
+ }
1116
+ /** One tool call inside a {@link GovernanceRunDetail}, with the execution outcome a list row can't afford to carry. */
1117
+ interface RunToolCallRow {
1118
+ toolCallId: string;
1119
+ toolName: string;
1120
+ toolType: string;
1121
+ status: string;
1122
+ /** Wall time of the execution; null for a call that never executed (rejected/still pending). */
1123
+ executionMs: number | null;
1124
+ /** Who executed/decided it, when the store recorded an attribution. */
1125
+ executedByRef: string | null;
1126
+ /** The failure text for a `failed` call; null otherwise. */
1127
+ error: string | null;
1128
+ /** ISO timestamp. */
1129
+ createdAt: string;
1130
+ }
1131
+ /** The owning thread's headline, carried on a drill-down so it can be named without a second read. */
1132
+ interface DetailThreadRef {
1133
+ threadId: string;
1134
+ title: string;
1135
+ actorRef: string;
1136
+ /** True when the thread is soft-deleted — its history is still readable, the thread is not. */
1137
+ deleted: boolean;
1138
+ }
1139
+ /**
1140
+ * Everything a run drill-down renders: the run row itself, its owning thread's headline, and the
1141
+ * tool calls attributed to it.
1142
+ *
1143
+ * `toolCalls` is empty for a run recorded before tool calls carried a `runId` (the column is
1144
+ * nullable and pre-rollout rows have none) — indistinguishable, from here, from a run that called
1145
+ * no tools. There is deliberately no cost figure: the token ledger has no run column, so per-run
1146
+ * spend is not attributable without a store migration.
1147
+ */
1148
+ interface GovernanceRunDetail {
1149
+ run: RecentRunRow;
1150
+ thread: DetailThreadRef;
1151
+ /** The run's tool calls, oldest first — the order they were requested in. */
1152
+ toolCalls: RunToolCallRow[];
1153
+ }
1154
+ /** One message inside a {@link GovernanceThreadDetail}. `content` is capped server-side. */
1155
+ interface ThreadMessageRow {
1156
+ messageId: string;
1157
+ role: string;
1158
+ /** Message text, cut to {@link THREAD_DETAIL_CONTENT_CHARS}; see `truncated`. */
1159
+ content: string;
1160
+ /** True when `content` was cut — the console shows an explicit "…" rather than implying the tail. */
1161
+ truncated: boolean;
1162
+ agentName: string | null;
1163
+ /** How many tool calls this message requested. */
1164
+ toolCallCount: number;
1165
+ /** ISO timestamp. */
1166
+ createdAt: string;
1167
+ }
1168
+ /** Token/cost rollup across a thread's whole ledger (not range-scoped — a thread's lifetime). */
1169
+ interface ThreadUsageRollup {
1170
+ /** Ledger rows, i.e. billed turns. */
1171
+ requests: number;
1172
+ inputTokens: number;
1173
+ outputTokens: number;
1174
+ totalTokens: number;
1175
+ costUsd: number;
1176
+ }
1177
+ /** Everything a thread drill-down renders, in one call. */
1178
+ interface GovernanceThreadDetail {
1179
+ /** The thread's own activity row (`messageCount` is the thread total, not the page below). */
1180
+ thread: ThreadActivityRow;
1181
+ /** True when the thread is soft-deleted. */
1182
+ deleted: boolean;
1183
+ usage: ThreadUsageRollup;
1184
+ /** The thread's runs, newest first, capped at the query's `runLimit`. */
1185
+ runs: RecentRunRow[];
1186
+ /** Runs on this thread in total — `runs.length < runTotal` means the cap bit. */
1187
+ runTotal: number;
1188
+ /** The thread's messages, newest first, capped at the query's `messageLimit`. */
1189
+ messages: ThreadMessageRow[];
1190
+ }
1191
+ /** Row caps for {@link AgentGovernanceQueries.threadDetail}, already clamped by the caller. */
1192
+ interface GovernanceThreadDetailQuery {
1193
+ threadId: string;
1194
+ /** Max messages returned, newest first. */
1195
+ messageLimit: number;
1196
+ /** Max runs returned, newest first. */
1197
+ runLimit: number;
1198
+ }
1199
+ /**
1200
+ * Per-message content cap for {@link ThreadMessageRow.content}. A drill-down is a triage view, not a
1201
+ * transcript reader: capping here keeps one response bounded regardless of how long an assistant
1202
+ * turn ran. Shared by every adapter so the cut is identical wherever the console is served from.
1203
+ */
1204
+ declare const THREAD_DETAIL_CONTENT_CHARS = 2000;
1205
+ /**
1206
+ * Cut a message body to {@link THREAD_DETAIL_CONTENT_CHARS}, reporting whether it was cut. Lives
1207
+ * next to the cap so every adapter truncates at the same boundary — a console comparing two stores
1208
+ * must not see two different "…".
1209
+ */
1210
+ declare function truncateDetailContent(content: string): {
1211
+ content: string;
1212
+ truncated: boolean;
1213
+ };
1098
1214
  /**
1099
1215
  * The governance read-model. Cost is `inputTokens/1e6 * inputPricePer1m + outputTokens/1e6 *
1100
1216
  * outputPricePer1m` against the current pricing row per model; an unpriced model contributes 0 cost
@@ -1113,8 +1229,19 @@ interface AgentGovernanceQueries {
1113
1229
  runErrors(range: GovernanceRange): Promise<RunErrorBreakdownRow[]>;
1114
1230
  runTrend(range: GovernanceRange): Promise<RunTrendPoint[]>;
1115
1231
  recentRuns(limit: number): Promise<RecentRunRow[]>;
1116
- /** Tool calls sitting `pending_approval`, oldest first — an inbox drains from the back. Capped at `limit`. */
1232
+ /**
1233
+ * Tool calls sitting `pending_approval`, oldest first — an inbox drains from the back. Capped at
1234
+ * `limit`, with NO total: a caller that needs to know whether the cap hid anything wants
1235
+ * {@link approvalsPage} instead.
1236
+ */
1117
1237
  pendingApprovals(limit: number): Promise<PendingApprovalRow[]>;
1238
+ /**
1239
+ * Paged, filterable approvals inbox, oldest first (same ordering as `pendingApprovals`). Unlike
1240
+ * that method this reports `total`, so a console can page a backlog and say how much of it is
1241
+ * off-screen — the one failure this surface cannot afford is a pending approval nobody sees.
1242
+ * An adapter without the backing data returns an empty page (`total: 0`) rather than throwing.
1243
+ */
1244
+ approvalsPage(query: GovernancePageQuery<ApprovalWhere>): Promise<GovernancePage<PendingApprovalRow>>;
1118
1245
  /** Per-tool call/failure/rejection/latency rollup over the range, highest call count first. */
1119
1246
  toolStats(range: GovernanceRange): Promise<ToolStatRow[]>;
1120
1247
  /**
@@ -1132,6 +1259,21 @@ interface AgentGovernanceQueries {
1132
1259
  * by a store without run recording (no `recordRunStart`) returns an empty page (`total: 0`).
1133
1260
  */
1134
1261
  runsPage(query: GovernancePageQuery<RunWhere>): Promise<GovernancePage<RecentRunRow>>;
1262
+ /**
1263
+ * One run with its owning thread and its tool calls — the drill-down behind a row in the runs
1264
+ * table. `null` when no run has that id. ONE call, not one per tool call: a failed run is the
1265
+ * thing an operator opens first and it should not cost a query per step.
1266
+ *
1267
+ * An adapter backed by a store without run recording returns `null` for every id.
1268
+ */
1269
+ runDetail(runId: string): Promise<GovernanceRunDetail | null>;
1270
+ /**
1271
+ * One thread with its lifetime usage rollup, its recent runs and its recent messages — the
1272
+ * drill-down behind a row in the threads table. `null` when no thread has that id; a soft-deleted
1273
+ * thread IS returned (with `deleted: true`), because "what did the thread we just deleted do" is
1274
+ * exactly the question an audit asks.
1275
+ */
1276
+ threadDetail(query: GovernanceThreadDetailQuery): Promise<GovernanceThreadDetail | null>;
1135
1277
  }
1136
1278
 
1137
1279
  /**
@@ -1248,6 +1390,12 @@ declare function bucketByThread(rows: GovernanceUsageInput[], prices: ReadonlyMa
1248
1390
  limit: number;
1249
1391
  includeUnknownThreads: boolean;
1250
1392
  }): ThreadSpendRow[];
1393
+ /**
1394
+ * Sum an already-scoped set of usage rows into one rollup — the thread drill-down's headline. Same
1395
+ * `rowCost` as every bucketer above (provider-reported cost wins, else the cache-aware estimate), so
1396
+ * a thread's detail cost and its row in the by-thread ranking can never disagree.
1397
+ */
1398
+ declare function rollupThreadUsage(rows: GovernanceUsageInput[], prices: ReadonlyMap<string, ModelPrice>): ThreadUsageRollup;
1251
1399
  /** Aggregate usage rows into a daily token/cost trend, ascending by day. */
1252
1400
  declare function bucketUsageTrend(rows: GovernanceUsageInput[], prices: ReadonlyMap<string, ModelPrice>): UsageTrendPoint[];
1253
1401
  /** Turn an inclusive `YYYY-MM-DD` day range into the UTC datetime bounds used to filter usage rows. */
@@ -1597,4 +1745,4 @@ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
1597
1745
  */
1598
1746
  declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
1599
1747
 
1600
- export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MODEL, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, type AiToolCtx, type AppendMessageInput, type AttachmentStagingStore, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, type Decision, DefaultRolesPolicy, type EmbeddingProvider, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceUsageInput, type InvokeWithTransientRetryOptions, type LlmStepEnvelope, type MessageAttachment, type MessageRole, type MessageUsage, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type PageContext, type Passage, type PendingApprovalRow, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RerankOptions, type Reranker, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, type RunErrorBreakdownRow, type RunMetrics, type RunTrendPoint, type RunWhere, type SinkWriter, type StageAttachmentInput, type StoredMessage, type StreamError, type ThreadActivityRow, type ThreadDetail, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolCallWhere, type ToolDefinition, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type ToolTransientRetryNumbers, type ToolTransientRetryOptions, type ToolTransientRetrySetting, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, agentDiagnosticKey, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, dayBoundsUtc, encodeStreamEvent, estimateCost, filterToolsByAllowList, filterToolsByRole, invokeWithTransientRetry, isTransientToolError, publishAgentDelegated, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentToolCall, publishAgentToolRetry, resolveToolTransientRetryNumbers, runAgentLoop, seedModelPrices, traceLlmTurn, traceToolExecution, withToolTimeout };
1748
+ export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MODEL, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, type AiToolCtx, type AppendMessageInput, type ApprovalWhere, type AttachmentStagingStore, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, type Decision, DefaultRolesPolicy, type DetailThreadRef, type EmbeddingProvider, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, type InvokeWithTransientRetryOptions, type LlmStepEnvelope, type MessageAttachment, type MessageRole, type MessageUsage, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type PageContext, type Passage, type PendingApprovalRow, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RerankOptions, type Reranker, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, type SinkWriter, type StageAttachmentInput, type StoredMessage, type StreamError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, type ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolCallWhere, type ToolDefinition, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type ToolTransientRetryNumbers, type ToolTransientRetryOptions, type ToolTransientRetrySetting, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, agentDiagnosticKey, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, dayBoundsUtc, encodeStreamEvent, estimateCost, filterToolsByAllowList, filterToolsByRole, invokeWithTransientRetry, isTransientToolError, publishAgentDelegated, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentToolCall, publishAgentToolRetry, resolveToolTransientRetryNumbers, rollupThreadUsage, runAgentLoop, seedModelPrices, traceLlmTurn, traceToolExecution, truncateDetailContent, withToolTimeout };
package/dist/index.js CHANGED
@@ -52,6 +52,22 @@ async function seedModelPrices(store, prices) {
52
52
  }
53
53
  __name(seedModelPrices, "seedModelPrices");
54
54
 
55
+ // src/spi/governance-queries.ts
56
+ var THREAD_DETAIL_CONTENT_CHARS = 2e3;
57
+ function truncateDetailContent(content) {
58
+ if (content.length <= THREAD_DETAIL_CONTENT_CHARS) {
59
+ return {
60
+ content,
61
+ truncated: false
62
+ };
63
+ }
64
+ return {
65
+ content: content.slice(0, THREAD_DETAIL_CONTENT_CHARS),
66
+ truncated: true
67
+ };
68
+ }
69
+ __name(truncateDetailContent, "truncateDetailContent");
70
+
55
71
  // src/governance/compute.ts
56
72
  function estimateCost(usage, price) {
57
73
  if (price === void 0) {
@@ -157,6 +173,24 @@ function bucketByThread(rows, prices, threads, options) {
157
173
  return result.slice(0, options.limit);
158
174
  }
159
175
  __name(bucketByThread, "bucketByThread");
176
+ function rollupThreadUsage(rows, prices) {
177
+ const rollup = {
178
+ requests: 0,
179
+ inputTokens: 0,
180
+ outputTokens: 0,
181
+ totalTokens: 0,
182
+ costUsd: 0
183
+ };
184
+ for (const row of rows) {
185
+ rollup.requests += 1;
186
+ rollup.inputTokens += row.inputTokens;
187
+ rollup.outputTokens += row.outputTokens;
188
+ rollup.totalTokens += row.inputTokens + row.outputTokens;
189
+ rollup.costUsd += rowCost(row, prices);
190
+ }
191
+ return rollup;
192
+ }
193
+ __name(rollupThreadUsage, "rollupThreadUsage");
160
194
  function bucketUsageTrend(rows, prices) {
161
195
  const byDay = /* @__PURE__ */ new Map();
162
196
  for (const row of rows) {
@@ -1178,6 +1212,7 @@ export {
1178
1212
  DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS,
1179
1213
  DefaultRolesPolicy,
1180
1214
  QuotaExceededError,
1215
+ THREAD_DETAIL_CONTENT_CHARS,
1181
1216
  ToolForbiddenError,
1182
1217
  ToolInputInvalidError,
1183
1218
  ToolNotFoundError,
@@ -1204,10 +1239,12 @@ export {
1204
1239
  publishAgentToolCall,
1205
1240
  publishAgentToolRetry,
1206
1241
  resolveToolTransientRetryNumbers,
1242
+ rollupThreadUsage,
1207
1243
  runAgentLoop,
1208
1244
  seedModelPrices,
1209
1245
  traceLlmTurn,
1210
1246
  traceToolExecution,
1247
+ truncateDetailContent,
1211
1248
  withToolTimeout
1212
1249
  };
1213
1250
  //# sourceMappingURL=index.js.map