@tonyclaw/agent-inspector 3.0.30 → 3.0.32

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.
Files changed (44) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/assets/{CompareDrawer-B6cXJohL.js → CompareDrawer-CONqySRK.js} +1 -1
  3. package/.output/public/assets/{InspectorPet-mAzeGmEE.js → InspectorPet-B6oMiG2V.js} +1 -1
  4. package/.output/public/assets/ProxyViewerContainer-Ce_WtVu2.js +126 -0
  5. package/.output/public/assets/{ReplayDialog-DodiTL6E.js → ReplayDialog-BauSX4Hj.js} +1 -1
  6. package/.output/public/assets/{RequestAnatomy-B3IauToI.js → RequestAnatomy-gyMOB2oK.js} +1 -1
  7. package/.output/public/assets/ResponseView-CUQvY1eb.js +2 -0
  8. package/.output/public/assets/{StreamingChunkSequence-vLDOVQM_.js → StreamingChunkSequence-CE6R5CKU.js} +1 -1
  9. package/.output/public/assets/{_sessionId-BFH4TOaI.js → _sessionId-BW1YYf5W.js} +1 -1
  10. package/.output/public/assets/{_sessionId-Cj_HIFZx.js → _sessionId-DRRig28i.js} +1 -1
  11. package/.output/public/assets/{index-DkDdKvLl.js → index-BTor51ZC.js} +3 -3
  12. package/.output/public/assets/{index-Ch7uqnCT.js → index-BzL-q9eN.js} +1 -1
  13. package/.output/public/assets/{index-Bmj2lcWE.js → index-CbFGlzA-.js} +1 -1
  14. package/.output/public/assets/index-D17dU-mX.css +1 -0
  15. package/.output/public/assets/{index-ZlhqCrSg.js → index-iN9QtGKF.js} +1 -1
  16. package/.output/public/assets/{json-viewer-BdrnVQu-.js → json-viewer-cR8mD7Tl.js} +1 -1
  17. package/.output/public/assets/{jszip.min-CS_nt_o1.js → jszip.min-aHTREmPV.js} +1 -1
  18. package/.output/server/_libs/lucide-react.mjs +55 -55
  19. package/.output/server/{_sessionId-C5S3pGZd.mjs → _sessionId-CuTfM9Wy.mjs} +2 -2
  20. package/.output/server/{_sessionId-g6D69lKq.mjs → _sessionId-RGCARWul.mjs} +1 -1
  21. package/.output/server/_ssr/{CompareDrawer-CqUmGHal.mjs → CompareDrawer-mUnxKFwp.mjs} +3 -3
  22. package/.output/server/_ssr/{InspectorPet-DI0UJd01.mjs → InspectorPet-J0mv5NOp.mjs} +1 -1
  23. package/.output/server/_ssr/{ProxyViewerContainer-CvsUmbJ3.mjs → ProxyViewerContainer-C7Wx7SjJ.mjs} +457 -47
  24. package/.output/server/_ssr/{ReplayDialog-DS48dpFG.mjs → ReplayDialog-C_zNrriu.mjs} +4 -4
  25. package/.output/server/_ssr/{RequestAnatomy-DxYVQU1C.mjs → RequestAnatomy-lvR2Uz9j.mjs} +3 -3
  26. package/.output/server/_ssr/{ResponseView-BLXW73eq.mjs → ResponseView-CRcqekgn.mjs} +3 -14
  27. package/.output/server/_ssr/{StreamingChunkSequence-DD0iFuy0.mjs → StreamingChunkSequence-CJLR-ZYV.mjs} +3 -3
  28. package/.output/server/_ssr/{index-RHVJnU2p.mjs → index-BhL5Yn1J.mjs} +1 -1
  29. package/.output/server/_ssr/{index-B10LIaK0.mjs → index-urTy0DU2.mjs} +2 -2
  30. package/.output/server/_ssr/index.mjs +2 -2
  31. package/.output/server/_ssr/{json-viewer-LDu2XBaK.mjs → json-viewer-BcooIEu5.mjs} +3 -3
  32. package/.output/server/_ssr/{router-GKvrwifJ.mjs → router-D-PJYphE.mjs} +5382 -4524
  33. package/.output/server/{_tanstack-start-manifest_v-Df2n4mbT.mjs → _tanstack-start-manifest_v-DhxDbp_1.mjs} +1 -1
  34. package/.output/server/index.mjs +92 -92
  35. package/package.json +1 -1
  36. package/src/components/pi-agent/PiAgentPanel.tsx +229 -34
  37. package/src/components/pi-agent/piAgentChatLogic.ts +287 -0
  38. package/src/components/ui/transient-toast.tsx +6 -5
  39. package/src/lib/piAgentContract.ts +80 -0
  40. package/src/services/piAgent.ts +131 -102
  41. package/src/services/piAgentRetrieval.ts +1180 -0
  42. package/.output/public/assets/ProxyViewerContainer-CkFWv_Nm.js +0 -126
  43. package/.output/public/assets/ResponseView-Hn-5ordK.js +0 -3
  44. package/.output/public/assets/index-CgJj-HBC.css +0 -1
@@ -0,0 +1,1180 @@
1
+ import type { CapturedLog } from "../contracts";
2
+ import { listCandidates } from "../knowledge/candidateStore";
3
+ import type { KnowledgeCandidate } from "../knowledge/types";
4
+ import type { Alert } from "../lib/alertContract";
5
+ import type { InspectorGroup } from "../lib/groupContract";
6
+ import type { ProviderConfig } from "../lib/providerContract";
7
+ import type { InspectorRun } from "../lib/runContract";
8
+ import { listAlerts } from "../proxy/alerts";
9
+ import { listGroups } from "../proxy/groupStore";
10
+ import { getProviders } from "../proxy/providers";
11
+ import { listRuns } from "../proxy/runStore";
12
+ import {
13
+ getLogById,
14
+ listLogsPage,
15
+ type ListLogsPageOptions,
16
+ type ListLogsPageResult,
17
+ } from "../proxy/store";
18
+
19
+ export type PiAgentEvidenceSource = "log" | "knowledge" | "alert" | "run" | "group" | "provider";
20
+
21
+ export type PiAgentCountEntry = {
22
+ value: string;
23
+ count: number;
24
+ };
25
+
26
+ export type PiAgentRetrievalSummary = {
27
+ matchedLogs: number;
28
+ knowledgeMatched: number;
29
+ failures: number;
30
+ pending: number;
31
+ sessions: number;
32
+ models: PiAgentCountEntry[];
33
+ providers: PiAgentCountEntry[];
34
+ latency: {
35
+ count: number;
36
+ minMs: number | null;
37
+ maxMs: number | null;
38
+ averageMs: number | null;
39
+ };
40
+ tokens: {
41
+ input: number;
42
+ output: number;
43
+ total: number;
44
+ };
45
+ sourceCounts: Record<PiAgentEvidenceSource, number>;
46
+ };
47
+
48
+ export type PiAgentQueryStats = {
49
+ scannedLogs: number;
50
+ hydratedLogs: number;
51
+ matchedLogs: number;
52
+ scannedKnowledge: number;
53
+ matchedKnowledge: number;
54
+ returnedEvidence: number;
55
+ truncated: boolean;
56
+ durationMs: number;
57
+ };
58
+
59
+ export type PiAgentEvidence = {
60
+ source: PiAgentEvidenceSource;
61
+ id: string;
62
+ logId?: number;
63
+ knowledgeId?: string;
64
+ logIds?: number[];
65
+ timestamp?: string;
66
+ sessionId?: string;
67
+ model?: string;
68
+ providerName?: string;
69
+ path?: string;
70
+ status?: number | string | null;
71
+ elapsedMs?: number;
72
+ inputTokens?: number;
73
+ outputTokens?: number;
74
+ score: number;
75
+ matchedFields: string[];
76
+ excerpt: string;
77
+ entityType?: string;
78
+ title?: string;
79
+ knowledgeType?: string;
80
+ tags?: string[];
81
+ };
82
+
83
+ export type PiAgentRetrievalResult = {
84
+ summary: PiAgentRetrievalSummary;
85
+ queryStats: PiAgentQueryStats;
86
+ evidence: PiAgentEvidence[];
87
+ };
88
+
89
+ export type PiAgentRetrievalLimits = {
90
+ scanPageSize: number;
91
+ maxScannedLogs: number;
92
+ maxHydratedLogs: number;
93
+ maxEvidence: number;
94
+ maxExcerptChars: number;
95
+ maxKnowledgeCandidates: number;
96
+ maxAuxiliaryRecords: number;
97
+ };
98
+
99
+ export type PiAgentRetrievalInput = {
100
+ question: string;
101
+ sessionId?: string;
102
+ recentUserQuestion?: string;
103
+ limits?: Partial<PiAgentRetrievalLimits>;
104
+ };
105
+
106
+ export type PiAgentRetrievalDependencies = {
107
+ listLogPage: (options: ListLogsPageOptions) => Promise<ListLogsPageResult>;
108
+ getLog: (id: number) => Promise<CapturedLog | null>;
109
+ listKnowledgeCandidates: () => KnowledgeCandidate[];
110
+ listInspectorAlerts: () => Promise<Alert[]>;
111
+ listInspectorRuns: () => InspectorRun[];
112
+ listInspectorGroups: () => InspectorGroup[];
113
+ listInspectorProviders: () => ProviderConfig[];
114
+ };
115
+
116
+ type QueryIntents = {
117
+ failure: boolean;
118
+ pending: boolean;
119
+ performance: boolean;
120
+ tokens: boolean;
121
+ tools: boolean;
122
+ sessions: boolean;
123
+ overview: boolean;
124
+ };
125
+
126
+ type QueryPlan = {
127
+ phrase: string;
128
+ terms: string[];
129
+ intents: QueryIntents;
130
+ };
131
+
132
+ type SearchField = {
133
+ name: string;
134
+ text: string;
135
+ weight: number;
136
+ };
137
+
138
+ type ScoreResult = {
139
+ score: number;
140
+ matchedFields: string[];
141
+ };
142
+
143
+ type RankedLog = ScoreResult & {
144
+ log: CapturedLog;
145
+ };
146
+
147
+ type ScanResult = {
148
+ logs: CapturedLog[];
149
+ total: number;
150
+ truncated: boolean;
151
+ };
152
+
153
+ type SourceCandidate = {
154
+ evidence: PiAgentEvidence;
155
+ sortTimestamp: string;
156
+ };
157
+
158
+ const DEFAULT_LIMITS: PiAgentRetrievalLimits = {
159
+ scanPageSize: 250,
160
+ maxScannedLogs: 20_000,
161
+ maxHydratedLogs: 48,
162
+ maxEvidence: 16,
163
+ maxExcerptChars: 720,
164
+ maxKnowledgeCandidates: 5_000,
165
+ maxAuxiliaryRecords: 1_000,
166
+ };
167
+
168
+ const MAX_LIMITS: PiAgentRetrievalLimits = {
169
+ scanPageSize: 1_000,
170
+ maxScannedLogs: 100_000,
171
+ maxHydratedLogs: 100,
172
+ maxEvidence: 30,
173
+ maxExcerptChars: 1_200,
174
+ maxKnowledgeCandidates: 20_000,
175
+ maxAuxiliaryRecords: 5_000,
176
+ };
177
+
178
+ const ENGLISH_STOP_WORDS = new Set([
179
+ "a",
180
+ "an",
181
+ "and",
182
+ "are",
183
+ "be",
184
+ "did",
185
+ "do",
186
+ "does",
187
+ "for",
188
+ "from",
189
+ "how",
190
+ "i",
191
+ "in",
192
+ "is",
193
+ "it",
194
+ "me",
195
+ "of",
196
+ "on",
197
+ "or",
198
+ "the",
199
+ "this",
200
+ "to",
201
+ "was",
202
+ "were",
203
+ "what",
204
+ "when",
205
+ "where",
206
+ "which",
207
+ "who",
208
+ "why",
209
+ "with",
210
+ ]);
211
+
212
+ const REFERENTIAL_MARKERS = [
213
+ "which one",
214
+ "that one",
215
+ "the former",
216
+ "the latter",
217
+ "it",
218
+ "哪个",
219
+ "那个",
220
+ "其中",
221
+ "它",
222
+ "这个",
223
+ "上述",
224
+ ];
225
+
226
+ const INTENT_ALIASES = {
227
+ failure: [
228
+ "error",
229
+ "fail",
230
+ "failed",
231
+ "failure",
232
+ "exception",
233
+ "timeout",
234
+ "错误",
235
+ "失败",
236
+ "异常",
237
+ "超时",
238
+ "报错",
239
+ ],
240
+ pending: [
241
+ "pending",
242
+ "hang",
243
+ "hung",
244
+ "stuck",
245
+ "unfinished",
246
+ "未完成",
247
+ "没结束",
248
+ "卡住",
249
+ "挂起",
250
+ "无响应",
251
+ ],
252
+ performance: [
253
+ "slow",
254
+ "slowest",
255
+ "latency",
256
+ "performance",
257
+ "duration",
258
+ "耗时",
259
+ "延迟",
260
+ "性能",
261
+ "最慢",
262
+ "响应时间",
263
+ ],
264
+ tokens: ["token", "tokens", "cost", "usage", "消耗", "用量", "费用"],
265
+ tools: ["tool", "tools", "function call", "工具", "调用了什么"],
266
+ sessions: ["session", "sessions", "conversation", "会话", "对话"],
267
+ overview: [
268
+ "overview",
269
+ "summary",
270
+ "overall",
271
+ "aggregate",
272
+ "statistics",
273
+ "概览",
274
+ "汇总",
275
+ "总体",
276
+ "整体",
277
+ "统计",
278
+ "情况",
279
+ ],
280
+ } satisfies Record<keyof QueryIntents, readonly string[]>;
281
+
282
+ const SENSITIVE_KEY_PATTERN =
283
+ /^(?:raw[-_]?headers?|headers?|authorization|proxy[-_]?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|password|passwd|secret|cookie|set[-_]?cookie)$/i;
284
+
285
+ async function defaultListAlerts(): Promise<Alert[]> {
286
+ const result = await listAlerts({ limit: 200, scanLimit: 2_000 });
287
+ return result.alerts;
288
+ }
289
+
290
+ const DEFAULT_DEPENDENCIES: PiAgentRetrievalDependencies = {
291
+ listLogPage: listLogsPage,
292
+ getLog: getLogById,
293
+ listKnowledgeCandidates: listCandidates,
294
+ listInspectorAlerts: defaultListAlerts,
295
+ listInspectorRuns: listRuns,
296
+ listInspectorGroups: listGroups,
297
+ listInspectorProviders: getProviders,
298
+ };
299
+
300
+ function clampLimit(value: number | undefined, fallback: number, maximum: number): number {
301
+ if (value === undefined || !Number.isInteger(value) || value < 1) return fallback;
302
+ return Math.min(value, maximum);
303
+ }
304
+
305
+ function resolveLimits(input: Partial<PiAgentRetrievalLimits> | undefined): PiAgentRetrievalLimits {
306
+ return {
307
+ scanPageSize: clampLimit(
308
+ input?.scanPageSize,
309
+ DEFAULT_LIMITS.scanPageSize,
310
+ MAX_LIMITS.scanPageSize,
311
+ ),
312
+ maxScannedLogs: clampLimit(
313
+ input?.maxScannedLogs,
314
+ DEFAULT_LIMITS.maxScannedLogs,
315
+ MAX_LIMITS.maxScannedLogs,
316
+ ),
317
+ maxHydratedLogs: clampLimit(
318
+ input?.maxHydratedLogs,
319
+ DEFAULT_LIMITS.maxHydratedLogs,
320
+ MAX_LIMITS.maxHydratedLogs,
321
+ ),
322
+ maxEvidence: clampLimit(input?.maxEvidence, DEFAULT_LIMITS.maxEvidence, MAX_LIMITS.maxEvidence),
323
+ maxExcerptChars: clampLimit(
324
+ input?.maxExcerptChars,
325
+ DEFAULT_LIMITS.maxExcerptChars,
326
+ MAX_LIMITS.maxExcerptChars,
327
+ ),
328
+ maxKnowledgeCandidates: clampLimit(
329
+ input?.maxKnowledgeCandidates,
330
+ DEFAULT_LIMITS.maxKnowledgeCandidates,
331
+ MAX_LIMITS.maxKnowledgeCandidates,
332
+ ),
333
+ maxAuxiliaryRecords: clampLimit(
334
+ input?.maxAuxiliaryRecords,
335
+ DEFAULT_LIMITS.maxAuxiliaryRecords,
336
+ MAX_LIMITS.maxAuxiliaryRecords,
337
+ ),
338
+ };
339
+ }
340
+
341
+ function replaceControlCharacters(value: string): string {
342
+ let output = "";
343
+ for (const character of value) {
344
+ const code = character.charCodeAt(0);
345
+ output += code <= 31 || (code >= 127 && code <= 159) ? " " : character;
346
+ }
347
+ return output;
348
+ }
349
+
350
+ function normalizeSearchText(value: string): string {
351
+ return replaceControlCharacters(value)
352
+ .normalize("NFKC")
353
+ .toLocaleLowerCase()
354
+ .replace(/\s+/g, " ")
355
+ .trim();
356
+ }
357
+
358
+ function hasCjk(value: string): boolean {
359
+ return /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(value);
360
+ }
361
+
362
+ function appendCjkTerms(segment: string, output: Set<string>): void {
363
+ const characters = [...segment];
364
+ if (characters.length > 1) output.add(segment);
365
+ for (const size of [2, 3]) {
366
+ for (let index = 0; index + size <= characters.length; index += 1) {
367
+ output.add(characters.slice(index, index + size).join(""));
368
+ if (output.size >= 64) return;
369
+ }
370
+ }
371
+ }
372
+
373
+ function extractTerms(value: string): string[] {
374
+ const output = new Set<string>();
375
+ for (const match of value.matchAll(/[\p{L}\p{N}][\p{L}\p{N}_.:/-]*/gu)) {
376
+ const token = match[0];
377
+ if (token.length < 2 || hasCjk(token) || ENGLISH_STOP_WORDS.has(token)) continue;
378
+ output.add(token);
379
+ if (output.size >= 64) return [...output];
380
+ }
381
+ for (const match of value.matchAll(
382
+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu,
383
+ )) {
384
+ appendCjkTerms(match[0], output);
385
+ if (output.size >= 64) break;
386
+ }
387
+ return [...output];
388
+ }
389
+
390
+ function hasAlias(value: string, aliases: readonly string[]): boolean {
391
+ return aliases.some((alias) => value.includes(alias));
392
+ }
393
+
394
+ function isReferential(value: string): boolean {
395
+ return REFERENTIAL_MARKERS.some((marker) => value.includes(marker));
396
+ }
397
+
398
+ function buildQueryPlan(input: PiAgentRetrievalInput): QueryPlan {
399
+ const current = normalizeSearchText(input.question.slice(0, 4_000));
400
+ const previous = normalizeSearchText(input.recentUserQuestion?.slice(0, 2_000) ?? "");
401
+ const retrievalText =
402
+ isReferential(current) && previous !== "" ? `${current} ${previous}` : current;
403
+ const terms = extractTerms(retrievalText);
404
+ return {
405
+ phrase: current.length >= 2 && current.length <= 240 ? current : "",
406
+ terms,
407
+ intents: {
408
+ failure: hasAlias(retrievalText, INTENT_ALIASES.failure),
409
+ pending: hasAlias(retrievalText, INTENT_ALIASES.pending),
410
+ performance: hasAlias(retrievalText, INTENT_ALIASES.performance),
411
+ tokens: hasAlias(retrievalText, INTENT_ALIASES.tokens),
412
+ tools: hasAlias(retrievalText, INTENT_ALIASES.tools),
413
+ sessions: hasAlias(retrievalText, INTENT_ALIASES.sessions),
414
+ overview: current === "" || hasAlias(retrievalText, INTENT_ALIASES.overview),
415
+ },
416
+ };
417
+ }
418
+
419
+ function scoreFields(query: QueryPlan, fields: readonly SearchField[]): ScoreResult {
420
+ let score = 0;
421
+ const matchedFields = new Set<string>();
422
+ for (const field of fields) {
423
+ const normalized = normalizeSearchText(field.text);
424
+ if (normalized === "") continue;
425
+ let matched = false;
426
+ if (query.phrase !== "" && normalized.includes(query.phrase)) {
427
+ score += field.weight * 3;
428
+ matched = true;
429
+ }
430
+ let termMatches = 0;
431
+ for (const term of query.terms) {
432
+ if (normalized.includes(term)) termMatches += 1;
433
+ if (termMatches >= 4) break;
434
+ }
435
+ if (termMatches > 0) {
436
+ score += field.weight * termMatches;
437
+ matched = true;
438
+ }
439
+ if (matched) matchedFields.add(field.name);
440
+ }
441
+ return { score, matchedFields: [...matchedFields] };
442
+ }
443
+
444
+ function addScore(result: ScoreResult, score: number, field: string): void {
445
+ result.score += score;
446
+ if (!result.matchedFields.includes(field)) result.matchedFields.push(field);
447
+ }
448
+
449
+ function isFailedLog(log: CapturedLog): boolean {
450
+ const hasError = log.error !== undefined && log.error !== null && log.error.trim() !== "";
451
+ return (log.responseStatus !== null && log.responseStatus >= 400) || hasError;
452
+ }
453
+
454
+ function scoreLogMetadata(log: CapturedLog, query: QueryPlan): ScoreResult {
455
+ const result = scoreFields(query, [
456
+ { name: "sessionId", text: log.sessionId ?? "", weight: 14 },
457
+ { name: "model", text: log.model ?? "", weight: 12 },
458
+ { name: "providerName", text: log.providerName ?? "", weight: 11 },
459
+ { name: "path", text: log.path, weight: 9 },
460
+ { name: "error", text: log.error ?? "", weight: 13 },
461
+ { name: "warnings", text: log.warnings?.join(" ") ?? "", weight: 10 },
462
+ { name: "responseStatus", text: log.responseStatus?.toString() ?? "pending", weight: 8 },
463
+ { name: "apiFormat", text: log.apiFormat, weight: 5 },
464
+ { name: "project", text: log.clientProjectFolder ?? "", weight: 4 },
465
+ ]);
466
+
467
+ if (query.intents.failure && isFailedLog(log)) addScore(result, 24, "failure");
468
+ if (query.intents.failure && (log.warnings?.length ?? 0) > 0) {
469
+ addScore(result, 12, "warnings");
470
+ }
471
+ if (query.intents.pending && log.responseStatus === null) addScore(result, 28, "pending");
472
+ if (query.intents.performance && log.elapsedMs !== null) {
473
+ addScore(result, 4 + Math.min(18, Math.log2(Math.max(1, log.elapsedMs))), "elapsedMs");
474
+ }
475
+ if (query.intents.tokens && (log.inputTokens !== null || log.outputTokens !== null)) {
476
+ addScore(result, 8, "tokens");
477
+ }
478
+ if (query.intents.tools) addScore(result, 1, "toolTraceCandidate");
479
+ if (query.intents.sessions && log.sessionId !== null) addScore(result, 3, "sessionId");
480
+ if (query.intents.overview) addScore(result, 1, "overviewScope");
481
+ return result;
482
+ }
483
+
484
+ function scoreHydratedLog(log: CapturedLog, query: QueryPlan): ScoreResult {
485
+ const metadata = scoreLogMetadata(log, query);
486
+ const bodies = scoreFields(query, [
487
+ { name: "requestBody", text: log.rawRequestBody ?? "", weight: 9 },
488
+ { name: "responseBody", text: log.responseText ?? "", weight: 8 },
489
+ ]);
490
+ for (const field of bodies.matchedFields) {
491
+ if (!metadata.matchedFields.includes(field)) metadata.matchedFields.push(field);
492
+ }
493
+ metadata.score += bodies.score;
494
+ return metadata;
495
+ }
496
+
497
+ function compareRankedLogs(left: RankedLog, right: RankedLog): number {
498
+ return (
499
+ right.score - left.score ||
500
+ right.log.timestamp.localeCompare(left.log.timestamp) ||
501
+ right.log.id - left.log.id
502
+ );
503
+ }
504
+
505
+ async function scanLogs(
506
+ input: PiAgentRetrievalInput,
507
+ limits: PiAgentRetrievalLimits,
508
+ dependencies: PiAgentRetrievalDependencies,
509
+ ): Promise<ScanResult> {
510
+ const logsById = new Map<number, CapturedLog>();
511
+ let offset = 0;
512
+ let knownTotal = 0;
513
+ let truncated = false;
514
+ while (offset < limits.maxScannedLogs) {
515
+ const limit = Math.min(limits.scanPageSize, limits.maxScannedLogs - offset);
516
+ let page: ListLogsPageResult;
517
+ try {
518
+ page = await dependencies.listLogPage({
519
+ sessionId: input.sessionId,
520
+ offset,
521
+ limit,
522
+ includeBodies: false,
523
+ });
524
+ } catch {
525
+ truncated = true;
526
+ break;
527
+ }
528
+ knownTotal = page.total;
529
+ for (const log of page.logs) logsById.set(log.id, log);
530
+ offset += page.logs.length;
531
+ if (page.logs.length === 0 || offset >= page.total) break;
532
+ }
533
+ if (knownTotal > logsById.size) truncated = true;
534
+ return {
535
+ logs: [...logsById.values()],
536
+ total: Math.max(knownTotal, logsById.size),
537
+ truncated,
538
+ };
539
+ }
540
+
541
+ async function readLogSafely(
542
+ id: number,
543
+ dependencies: PiAgentRetrievalDependencies,
544
+ ): Promise<CapturedLog | null> {
545
+ try {
546
+ return await dependencies.getLog(id);
547
+ } catch {
548
+ return null;
549
+ }
550
+ }
551
+
552
+ async function hydrateRankedLogs(
553
+ ranked: readonly RankedLog[],
554
+ query: QueryPlan,
555
+ limits: PiAgentRetrievalLimits,
556
+ dependencies: PiAgentRetrievalDependencies,
557
+ ): Promise<{ ranked: RankedLog[]; hydrated: number }> {
558
+ const hydrationPool = ranked.slice(0, limits.maxHydratedLogs);
559
+ const hydratedById = new Map<number, RankedLog>();
560
+ let hydrated = 0;
561
+ for (let offset = 0; offset < hydrationPool.length; offset += 8) {
562
+ const batch = hydrationPool.slice(offset, offset + 8);
563
+ const logs = await Promise.all(
564
+ batch.map(async (candidate) => readLogSafely(candidate.log.id, dependencies)),
565
+ );
566
+ for (const log of logs) {
567
+ if (log === null) continue;
568
+ hydrated += 1;
569
+ hydratedById.set(log.id, { log, ...scoreHydratedLog(log, query) });
570
+ }
571
+ }
572
+ return {
573
+ ranked: ranked
574
+ .map((candidate) => hydratedById.get(candidate.log.id) ?? candidate)
575
+ .sort(compareRankedLogs),
576
+ hydrated,
577
+ };
578
+ }
579
+
580
+ function sanitizeUnknown(value: unknown, depth = 0): unknown {
581
+ if (depth > 6) return "[bounded]";
582
+ if (value === null || typeof value === "boolean" || typeof value === "number") return value;
583
+ if (typeof value === "string") return sanitizeText(value);
584
+ if (Array.isArray(value))
585
+ return value.slice(0, 40).map((item) => sanitizeUnknown(item, depth + 1));
586
+ if (typeof value !== "object") return String(value);
587
+
588
+ const output: Record<string, unknown> = {};
589
+ for (const [key, child] of Object.entries(value).slice(0, 60)) {
590
+ if (SENSITIVE_KEY_PATTERN.test(key)) continue;
591
+ output[key] = sanitizeUnknown(child, depth + 1);
592
+ }
593
+ return output;
594
+ }
595
+
596
+ function sanitizeText(value: string): string {
597
+ return replaceControlCharacters(value)
598
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "[REDACTED]")
599
+ .replace(/\bsk-[A-Za-z0-9_-]{6,}/gi, "[REDACTED]")
600
+ .replace(
601
+ /\b(?:raw[-_]?headers?|headers?|authorization|proxy[-_]?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|password|passwd|secret|cookie|set[-_]?cookie)\b\s*[=:]\s*(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi,
602
+ "[REDACTED]",
603
+ )
604
+ .replace(
605
+ /\b(?:rawheaders|headers|authorization|proxy-authorization|x-api-key|apikey|api_key|access_token|refresh_token)\b/gi,
606
+ "[sensitive-field]",
607
+ )
608
+ .replace(/\s+/g, " ")
609
+ .trim();
610
+ }
611
+
612
+ export function sanitizePiAgentEvidenceText(value: string): string {
613
+ try {
614
+ const parsed: unknown = JSON.parse(value);
615
+ return sanitizeText(JSON.stringify(sanitizeUnknown(parsed)));
616
+ } catch {
617
+ return sanitizeText(value);
618
+ }
619
+ }
620
+
621
+ function excerptAroundTerms(value: string, query: QueryPlan, maxLength: number): string {
622
+ const sanitized = sanitizePiAgentEvidenceText(value);
623
+ if (sanitized.length <= maxLength) return sanitized;
624
+ const normalized = normalizeSearchText(sanitized);
625
+ const anchors = query.phrase === "" ? query.terms : [query.phrase, ...query.terms];
626
+ let matchIndex = -1;
627
+ for (const anchor of anchors) {
628
+ matchIndex = normalized.indexOf(anchor);
629
+ if (matchIndex >= 0) break;
630
+ }
631
+ const start = matchIndex < 0 ? 0 : Math.max(0, matchIndex - Math.floor(maxLength / 3));
632
+ const end = Math.min(sanitized.length, start + maxLength);
633
+ return `${start > 0 ? "…" : ""}${sanitized.slice(start, end)}${end < sanitized.length ? "…" : ""}`;
634
+ }
635
+
636
+ function firstMatchingBody(log: CapturedLog, matchedFields: readonly string[]): string | null {
637
+ if (matchedFields.includes("requestBody") && log.rawRequestBody !== null) {
638
+ return log.rawRequestBody;
639
+ }
640
+ if (matchedFields.includes("responseBody") && log.responseText !== null) {
641
+ return log.responseText;
642
+ }
643
+ if (log.error !== undefined && log.error !== null && log.error.trim() !== "") return log.error;
644
+ if (log.warnings !== undefined && log.warnings.length > 0) return log.warnings.join(" | ");
645
+ return null;
646
+ }
647
+
648
+ function logExcerpt(
649
+ log: CapturedLog,
650
+ candidate: RankedLog,
651
+ query: QueryPlan,
652
+ maxLength: number,
653
+ ): string {
654
+ const body = firstMatchingBody(log, candidate.matchedFields);
655
+ if (body !== null) return excerptAroundTerms(body, query, maxLength);
656
+ const metadata = [
657
+ `Log ${String(log.id)}`,
658
+ `session ${log.sessionId ?? "unknown"}`,
659
+ `model ${log.model ?? "unknown"}`,
660
+ `provider ${log.providerName ?? "unknown"}`,
661
+ `path ${log.path}`,
662
+ `status ${log.responseStatus?.toString() ?? "pending"}`,
663
+ `elapsed ${log.elapsedMs?.toString() ?? "unknown"} ms`,
664
+ ].join(" · ");
665
+ return excerptAroundTerms(metadata, query, maxLength);
666
+ }
667
+
668
+ function logEvidence(
669
+ candidate: RankedLog,
670
+ query: QueryPlan,
671
+ maxExcerptChars: number,
672
+ ): PiAgentEvidence {
673
+ const log = candidate.log;
674
+ return {
675
+ source: "log",
676
+ id: String(log.id),
677
+ logId: log.id,
678
+ timestamp: log.timestamp,
679
+ sessionId: log.sessionId ?? undefined,
680
+ model: log.model ?? undefined,
681
+ providerName: log.providerName ?? undefined,
682
+ path: log.path,
683
+ status: log.responseStatus,
684
+ elapsedMs: log.elapsedMs ?? undefined,
685
+ inputTokens: log.inputTokens ?? undefined,
686
+ outputTokens: log.outputTokens ?? undefined,
687
+ score: Math.round(candidate.score * 100) / 100,
688
+ matchedFields: candidate.matchedFields,
689
+ excerpt: logExcerpt(log, candidate, query, maxExcerptChars),
690
+ entityType: "log",
691
+ title: `Log #${String(log.id)}`,
692
+ };
693
+ }
694
+
695
+ function safeMetadataText(value: Record<string, unknown>): string {
696
+ return sanitizeText(JSON.stringify(sanitizeUnknown(value)));
697
+ }
698
+
699
+ function scoreKnowledge(candidate: KnowledgeCandidate, query: QueryPlan): ScoreResult {
700
+ const result = scoreFields(query, [
701
+ { name: "knowledgeId", text: candidate.id, weight: 10 },
702
+ { name: "title", text: candidate.title, weight: 12 },
703
+ { name: "content", text: candidate.content, weight: 9 },
704
+ { name: "tags", text: candidate.tags.join(" "), weight: 8 },
705
+ { name: "knowledgeType", text: candidate.type, weight: 6 },
706
+ { name: "knowledgeStatus", text: candidate.status, weight: 5 },
707
+ { name: "sessionId", text: candidate.sessionId, weight: 10 },
708
+ { name: "logIds", text: candidate.logIds.join(" "), weight: 4 },
709
+ ]);
710
+ if (query.intents.failure && candidate.status === "failed") {
711
+ addScore(result, 12, "knowledgeStatus");
712
+ }
713
+ if (query.intents.overview) addScore(result, 1, "overviewScope");
714
+ return result;
715
+ }
716
+
717
+ function knowledgeEvidence(
718
+ candidate: KnowledgeCandidate,
719
+ score: ScoreResult,
720
+ query: QueryPlan,
721
+ maxExcerptChars: number,
722
+ ): PiAgentEvidence {
723
+ return {
724
+ source: "knowledge",
725
+ id: candidate.id,
726
+ knowledgeId: candidate.id,
727
+ logIds: candidate.logIds,
728
+ timestamp: candidate.updatedAt,
729
+ sessionId: candidate.sessionId,
730
+ status: candidate.status,
731
+ score: Math.round(score.score * 100) / 100,
732
+ matchedFields: score.matchedFields,
733
+ excerpt: excerptAroundTerms(
734
+ `${candidate.title}. ${candidate.content}. Tags: ${candidate.tags.join(", ")}`,
735
+ query,
736
+ maxExcerptChars,
737
+ ),
738
+ entityType: "knowledge-candidate",
739
+ title: sanitizeText(candidate.title),
740
+ knowledgeType: candidate.type,
741
+ tags: candidate.tags
742
+ .map(sanitizeText)
743
+ .filter((tag) => tag !== "")
744
+ .slice(0, 20),
745
+ };
746
+ }
747
+
748
+ function scoreAlert(alert: Alert, query: QueryPlan): ScoreResult {
749
+ const result = scoreFields(query, [
750
+ { name: "alertId", text: alert.id, weight: 9 },
751
+ { name: "title", text: alert.title, weight: 11 },
752
+ { name: "message", text: alert.message, weight: 10 },
753
+ { name: "category", text: alert.category, weight: 8 },
754
+ { name: "severity", text: alert.severity, weight: 7 },
755
+ { name: "sessionId", text: alert.sessionIds.join(" "), weight: 9 },
756
+ { name: "providerName", text: alert.provider ?? "", weight: 8 },
757
+ { name: "model", text: alert.model ?? "", weight: 8 },
758
+ { name: "metadata", text: safeMetadataText(alert.metadata), weight: 3 },
759
+ ]);
760
+ if (query.intents.failure) addScore(result, alert.severity === "critical" ? 18 : 10, "alert");
761
+ if (query.intents.performance && alert.category === "slow-response") {
762
+ addScore(result, 16, "category");
763
+ }
764
+ if (query.intents.overview) addScore(result, 1, "overviewScope");
765
+ return result;
766
+ }
767
+
768
+ function alertEvidence(
769
+ alert: Alert,
770
+ score: ScoreResult,
771
+ query: QueryPlan,
772
+ maxExcerptChars: number,
773
+ ): PiAgentEvidence {
774
+ return {
775
+ source: "alert",
776
+ id: alert.id,
777
+ logIds: alert.logIds,
778
+ timestamp: alert.lastSeenAt,
779
+ sessionId: alert.sessionIds[0],
780
+ model: alert.model ?? undefined,
781
+ providerName: alert.provider ?? undefined,
782
+ status: alert.status,
783
+ score: Math.round(score.score * 100) / 100,
784
+ matchedFields: score.matchedFields,
785
+ excerpt: excerptAroundTerms(`${alert.title}. ${alert.message}`, query, maxExcerptChars),
786
+ entityType: alert.category,
787
+ title: sanitizeText(alert.title),
788
+ };
789
+ }
790
+
791
+ function scoreRun(run: InspectorRun, query: QueryPlan): ScoreResult {
792
+ const result = scoreFields(query, [
793
+ { name: "runId", text: run.id, weight: 10 },
794
+ { name: "sessionId", text: run.sessionId, weight: 11 },
795
+ { name: "title", text: run.title, weight: 10 },
796
+ { name: "task", text: run.task ?? "", weight: 9 },
797
+ { name: "project", text: run.project ?? "", weight: 7 },
798
+ { name: "agent", text: run.agent ?? "", weight: 7 },
799
+ { name: "status", text: run.status, weight: 7 },
800
+ { name: "tags", text: run.tags.join(" "), weight: 7 },
801
+ { name: "metadata", text: safeMetadataText(run.metadata), weight: 3 },
802
+ ]);
803
+ if (query.intents.failure && run.status === "failed") addScore(result, 18, "status");
804
+ if (query.intents.pending && (run.status === "created" || run.status === "running")) {
805
+ addScore(result, 14, "status");
806
+ }
807
+ if (query.intents.overview) addScore(result, 1, "overviewScope");
808
+ return result;
809
+ }
810
+
811
+ function runEvidence(
812
+ run: InspectorRun,
813
+ score: ScoreResult,
814
+ query: QueryPlan,
815
+ maxExcerptChars: number,
816
+ ): PiAgentEvidence {
817
+ return {
818
+ source: "run",
819
+ id: run.id,
820
+ timestamp: run.updatedAt,
821
+ sessionId: run.sessionId,
822
+ status: run.status,
823
+ score: Math.round(score.score * 100) / 100,
824
+ matchedFields: score.matchedFields,
825
+ excerpt: excerptAroundTerms(
826
+ `${run.title}. ${run.task ?? ""} Project: ${run.project ?? "unknown"}. Agent: ${run.agent ?? "unknown"}`,
827
+ query,
828
+ maxExcerptChars,
829
+ ),
830
+ entityType: "run",
831
+ title: sanitizeText(run.title),
832
+ tags: run.tags
833
+ .map(sanitizeText)
834
+ .filter((tag) => tag !== "")
835
+ .slice(0, 20),
836
+ };
837
+ }
838
+
839
+ function groupSessions(group: InspectorGroup): string[] {
840
+ return [...new Set(group.members.map((member) => member.sessionId))];
841
+ }
842
+
843
+ function scoreGroup(group: InspectorGroup, query: QueryPlan): ScoreResult {
844
+ const result = scoreFields(query, [
845
+ { name: "groupId", text: group.id, weight: 10 },
846
+ { name: "title", text: group.title, weight: 10 },
847
+ { name: "task", text: group.task ?? "", weight: 9 },
848
+ { name: "project", text: group.project ?? "", weight: 7 },
849
+ { name: "status", text: group.status, weight: 7 },
850
+ { name: "tags", text: group.tags.join(" "), weight: 7 },
851
+ { name: "sessionId", text: groupSessions(group).join(" "), weight: 9 },
852
+ { name: "metadata", text: safeMetadataText(group.metadata), weight: 3 },
853
+ ]);
854
+ if (query.intents.failure && group.status === "failed") addScore(result, 18, "status");
855
+ if (query.intents.pending && (group.status === "created" || group.status === "running")) {
856
+ addScore(result, 14, "status");
857
+ }
858
+ if (query.intents.overview) addScore(result, 1, "overviewScope");
859
+ return result;
860
+ }
861
+
862
+ function groupEvidence(
863
+ group: InspectorGroup,
864
+ score: ScoreResult,
865
+ query: QueryPlan,
866
+ maxExcerptChars: number,
867
+ ): PiAgentEvidence {
868
+ return {
869
+ source: "group",
870
+ id: group.id,
871
+ timestamp: group.updatedAt,
872
+ sessionId: groupSessions(group)[0],
873
+ status: group.status,
874
+ score: Math.round(score.score * 100) / 100,
875
+ matchedFields: score.matchedFields,
876
+ excerpt: excerptAroundTerms(
877
+ `${group.title}. ${group.task ?? ""} Project: ${group.project ?? "unknown"}. Members: ${String(group.members.length)}`,
878
+ query,
879
+ maxExcerptChars,
880
+ ),
881
+ entityType: "group",
882
+ title: sanitizeText(group.title),
883
+ tags: group.tags
884
+ .map(sanitizeText)
885
+ .filter((tag) => tag !== "")
886
+ .slice(0, 20),
887
+ };
888
+ }
889
+
890
+ function scoreProvider(provider: ProviderConfig, query: QueryPlan): ScoreResult {
891
+ const result = scoreFields(query, [
892
+ { name: "providerId", text: provider.id, weight: 10 },
893
+ { name: "providerName", text: provider.name, weight: 12 },
894
+ { name: "model", text: provider.models.join(" "), weight: 10 },
895
+ { name: "providerSource", text: provider.source ?? "", weight: 5 },
896
+ { name: "apiFormat", text: provider.format ?? "", weight: 5 },
897
+ ]);
898
+ if (query.intents.overview) addScore(result, 1, "overviewScope");
899
+ return result;
900
+ }
901
+
902
+ function providerEvidence(
903
+ provider: ProviderConfig,
904
+ score: ScoreResult,
905
+ query: QueryPlan,
906
+ maxExcerptChars: number,
907
+ ): PiAgentEvidence {
908
+ return {
909
+ source: "provider",
910
+ id: provider.id,
911
+ timestamp: provider.updatedAt,
912
+ providerName: provider.name,
913
+ status: "configured",
914
+ score: Math.round(score.score * 100) / 100,
915
+ matchedFields: score.matchedFields,
916
+ excerpt: excerptAroundTerms(
917
+ `Provider ${provider.name}. Models: ${provider.models.join(", ") || "none"}. Source: ${provider.source ?? "unknown"}. Format: ${provider.format ?? "mixed"}.`,
918
+ query,
919
+ maxExcerptChars,
920
+ ),
921
+ entityType: "provider",
922
+ title: sanitizeText(provider.name),
923
+ };
924
+ }
925
+
926
+ function readSyncStore<T>(reader: () => T[]): T[] {
927
+ try {
928
+ return reader();
929
+ } catch {
930
+ return [];
931
+ }
932
+ }
933
+
934
+ async function readAlertsStore(reader: () => Promise<Alert[]>): Promise<Alert[]> {
935
+ try {
936
+ return await reader();
937
+ } catch {
938
+ return [];
939
+ }
940
+ }
941
+
942
+ function sessionMatches(
943
+ candidateSessionIds: readonly string[],
944
+ sessionId: string | undefined,
945
+ ): boolean {
946
+ return sessionId === undefined || candidateSessionIds.includes(sessionId);
947
+ }
948
+
949
+ function collectKnowledgeCandidates(
950
+ candidates: readonly KnowledgeCandidate[],
951
+ input: PiAgentRetrievalInput,
952
+ query: QueryPlan,
953
+ limits: PiAgentRetrievalLimits,
954
+ ): SourceCandidate[] {
955
+ const output: SourceCandidate[] = [];
956
+ for (const candidate of candidates.slice(0, limits.maxKnowledgeCandidates)) {
957
+ if (!sessionMatches([candidate.sessionId], input.sessionId)) continue;
958
+ const score = scoreKnowledge(candidate, query);
959
+ if (score.score <= 0) continue;
960
+ output.push({
961
+ evidence: knowledgeEvidence(candidate, score, query, limits.maxExcerptChars),
962
+ sortTimestamp: candidate.updatedAt,
963
+ });
964
+ }
965
+ return output;
966
+ }
967
+
968
+ function collectAlertCandidates(
969
+ alerts: readonly Alert[],
970
+ input: PiAgentRetrievalInput,
971
+ query: QueryPlan,
972
+ limits: PiAgentRetrievalLimits,
973
+ ): SourceCandidate[] {
974
+ const output: SourceCandidate[] = [];
975
+ for (const alert of alerts.slice(0, limits.maxAuxiliaryRecords)) {
976
+ if (!sessionMatches(alert.sessionIds, input.sessionId)) continue;
977
+ const score = scoreAlert(alert, query);
978
+ if (score.score <= 0) continue;
979
+ output.push({
980
+ evidence: alertEvidence(alert, score, query, limits.maxExcerptChars),
981
+ sortTimestamp: alert.lastSeenAt,
982
+ });
983
+ }
984
+ return output;
985
+ }
986
+
987
+ function collectRunCandidates(
988
+ runs: readonly InspectorRun[],
989
+ input: PiAgentRetrievalInput,
990
+ query: QueryPlan,
991
+ limits: PiAgentRetrievalLimits,
992
+ ): SourceCandidate[] {
993
+ const output: SourceCandidate[] = [];
994
+ for (const run of runs.slice(0, limits.maxAuxiliaryRecords)) {
995
+ if (!sessionMatches([run.sessionId], input.sessionId)) continue;
996
+ const score = scoreRun(run, query);
997
+ if (score.score <= 0) continue;
998
+ output.push({
999
+ evidence: runEvidence(run, score, query, limits.maxExcerptChars),
1000
+ sortTimestamp: run.updatedAt,
1001
+ });
1002
+ }
1003
+ return output;
1004
+ }
1005
+
1006
+ function collectGroupCandidates(
1007
+ groups: readonly InspectorGroup[],
1008
+ input: PiAgentRetrievalInput,
1009
+ query: QueryPlan,
1010
+ limits: PiAgentRetrievalLimits,
1011
+ ): SourceCandidate[] {
1012
+ const output: SourceCandidate[] = [];
1013
+ for (const group of groups.slice(0, limits.maxAuxiliaryRecords)) {
1014
+ const sessions = groupSessions(group);
1015
+ if (!sessionMatches(sessions, input.sessionId)) continue;
1016
+ const score = scoreGroup(group, query);
1017
+ if (score.score <= 0) continue;
1018
+ output.push({
1019
+ evidence: groupEvidence(group, score, query, limits.maxExcerptChars),
1020
+ sortTimestamp: group.updatedAt,
1021
+ });
1022
+ }
1023
+ return output;
1024
+ }
1025
+
1026
+ function collectProviderCandidates(
1027
+ providers: readonly ProviderConfig[],
1028
+ input: PiAgentRetrievalInput,
1029
+ query: QueryPlan,
1030
+ limits: PiAgentRetrievalLimits,
1031
+ ): SourceCandidate[] {
1032
+ if (input.sessionId !== undefined) return [];
1033
+ const output: SourceCandidate[] = [];
1034
+ for (const provider of providers.slice(0, limits.maxAuxiliaryRecords)) {
1035
+ const score = scoreProvider(provider, query);
1036
+ if (score.score <= 0) continue;
1037
+ output.push({
1038
+ evidence: providerEvidence(provider, score, query, limits.maxExcerptChars),
1039
+ sortTimestamp: provider.updatedAt,
1040
+ });
1041
+ }
1042
+ return output;
1043
+ }
1044
+
1045
+ function countValues(values: readonly (string | null | undefined)[]): PiAgentCountEntry[] {
1046
+ const counts = new Map<string, number>();
1047
+ for (const value of values) {
1048
+ if (value === null || value === undefined || value.trim() === "") continue;
1049
+ counts.set(value, (counts.get(value) ?? 0) + 1);
1050
+ }
1051
+ return [...counts.entries()]
1052
+ .map(([value, count]) => ({ value, count }))
1053
+ .sort((left, right) => right.count - left.count || left.value.localeCompare(right.value));
1054
+ }
1055
+
1056
+ function sourceCounts(
1057
+ candidates: readonly SourceCandidate[],
1058
+ ): Record<PiAgentEvidenceSource, number> {
1059
+ const counts: Record<PiAgentEvidenceSource, number> = {
1060
+ log: 0,
1061
+ knowledge: 0,
1062
+ alert: 0,
1063
+ run: 0,
1064
+ group: 0,
1065
+ provider: 0,
1066
+ };
1067
+ for (const candidate of candidates) {
1068
+ counts[candidate.evidence.source] += 1;
1069
+ }
1070
+ return counts;
1071
+ }
1072
+
1073
+ function summarize(
1074
+ logs: readonly RankedLog[],
1075
+ candidates: readonly SourceCandidate[],
1076
+ ): PiAgentRetrievalSummary {
1077
+ const matchedLogs = logs
1078
+ .filter((candidate) => candidate.score > 0)
1079
+ .map((candidate) => candidate.log);
1080
+ const latencies = matchedLogs
1081
+ .map((log) => log.elapsedMs)
1082
+ .filter((value): value is number => value !== null && Number.isFinite(value));
1083
+ const latencyTotal = latencies.reduce((sum, value) => sum + value, 0);
1084
+ const input = matchedLogs.reduce((sum, log) => sum + (log.inputTokens ?? 0), 0);
1085
+ const output = matchedLogs.reduce((sum, log) => sum + (log.outputTokens ?? 0), 0);
1086
+ const counts = sourceCounts(candidates);
1087
+ return {
1088
+ matchedLogs: matchedLogs.length,
1089
+ knowledgeMatched: counts.knowledge,
1090
+ failures: matchedLogs.filter(isFailedLog).length,
1091
+ pending: matchedLogs.filter((log) => log.responseStatus === null).length,
1092
+ sessions: new Set(
1093
+ matchedLogs
1094
+ .map((log) => log.sessionId)
1095
+ .filter((sessionId): sessionId is string => sessionId !== null),
1096
+ ).size,
1097
+ models: countValues(matchedLogs.map((log) => log.model)),
1098
+ providers: countValues(matchedLogs.map((log) => log.providerName)),
1099
+ latency: {
1100
+ count: latencies.length,
1101
+ minMs: latencies.length > 0 ? Math.min(...latencies) : null,
1102
+ maxMs: latencies.length > 0 ? Math.max(...latencies) : null,
1103
+ averageMs:
1104
+ latencies.length > 0 ? Math.round((latencyTotal / latencies.length) * 100) / 100 : null,
1105
+ },
1106
+ tokens: { input, output, total: input + output },
1107
+ sourceCounts: counts,
1108
+ };
1109
+ }
1110
+
1111
+ function compareSourceCandidates(left: SourceCandidate, right: SourceCandidate): number {
1112
+ return (
1113
+ right.evidence.score - left.evidence.score ||
1114
+ right.sortTimestamp.localeCompare(left.sortTimestamp) ||
1115
+ left.evidence.id.localeCompare(right.evidence.id)
1116
+ );
1117
+ }
1118
+
1119
+ export async function retrievePiAgentEvidence(
1120
+ input: PiAgentRetrievalInput,
1121
+ dependencies: PiAgentRetrievalDependencies = DEFAULT_DEPENDENCIES,
1122
+ ): Promise<PiAgentRetrievalResult> {
1123
+ const startedAt = Date.now();
1124
+ const limits = resolveLimits(input.limits);
1125
+ const query = buildQueryPlan(input);
1126
+ const [scan, alerts] = await Promise.all([
1127
+ scanLogs(input, limits, dependencies),
1128
+ readAlertsStore(dependencies.listInspectorAlerts),
1129
+ ]);
1130
+ const knowledge = readSyncStore(dependencies.listKnowledgeCandidates);
1131
+ const runs = readSyncStore(dependencies.listInspectorRuns);
1132
+ const groups = readSyncStore(dependencies.listInspectorGroups);
1133
+ const providers = readSyncStore(dependencies.listInspectorProviders);
1134
+
1135
+ const metadataRanked = scan.logs
1136
+ .map((log): RankedLog => ({ log, ...scoreLogMetadata(log, query) }))
1137
+ .sort(compareRankedLogs);
1138
+ const hydrated = await hydrateRankedLogs(metadataRanked, query, limits, dependencies);
1139
+ const matchedLogs = hydrated.ranked.filter((candidate) => candidate.score > 0);
1140
+ const logCandidates: SourceCandidate[] = matchedLogs.map((candidate) => ({
1141
+ evidence: logEvidence(candidate, query, limits.maxExcerptChars),
1142
+ sortTimestamp: candidate.log.timestamp,
1143
+ }));
1144
+ const auxiliaryCandidates = [
1145
+ ...collectKnowledgeCandidates(knowledge, input, query, limits),
1146
+ ...collectAlertCandidates(alerts, input, query, limits),
1147
+ ...collectRunCandidates(runs, input, query, limits),
1148
+ ...collectGroupCandidates(groups, input, query, limits),
1149
+ ...collectProviderCandidates(providers, input, query, limits),
1150
+ ];
1151
+ const allCandidates = [...logCandidates, ...auxiliaryCandidates].sort(compareSourceCandidates);
1152
+ const evidence = allCandidates
1153
+ .slice(0, limits.maxEvidence)
1154
+ .map((candidate) => candidate.evidence);
1155
+ const matchedKnowledge = auxiliaryCandidates.filter(
1156
+ (candidate) => candidate.evidence.source === "knowledge",
1157
+ ).length;
1158
+ const boundedSource =
1159
+ knowledge.length > limits.maxKnowledgeCandidates ||
1160
+ alerts.length > limits.maxAuxiliaryRecords ||
1161
+ runs.length > limits.maxAuxiliaryRecords ||
1162
+ groups.length > limits.maxAuxiliaryRecords ||
1163
+ providers.length > limits.maxAuxiliaryRecords;
1164
+ const truncated = scan.truncated || boundedSource || allCandidates.length > limits.maxEvidence;
1165
+
1166
+ return {
1167
+ summary: summarize(hydrated.ranked, allCandidates),
1168
+ queryStats: {
1169
+ scannedLogs: scan.logs.length,
1170
+ hydratedLogs: hydrated.hydrated,
1171
+ matchedLogs: matchedLogs.length,
1172
+ scannedKnowledge: Math.min(knowledge.length, limits.maxKnowledgeCandidates),
1173
+ matchedKnowledge,
1174
+ returnedEvidence: evidence.length,
1175
+ truncated,
1176
+ durationMs: Math.max(0, Date.now() - startedAt),
1177
+ },
1178
+ evidence,
1179
+ };
1180
+ }