@tonyclaw/agent-inspector 2.0.23 → 2.0.25

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 (41) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/assets/{CompareDrawer-DnYQtd8R.js → CompareDrawer-DVNvS0GQ.js} +1 -1
  3. package/.output/public/assets/ProxyViewerContainer-By3XtQhZ.js +115 -0
  4. package/.output/public/assets/{ReplayDialog-B-3V95xT.js → ReplayDialog-Cw6bN-NR.js} +1 -1
  5. package/.output/public/assets/{RequestAnatomy-CT8hLGLa.js → RequestAnatomy-DnIsirBE.js} +1 -1
  6. package/.output/public/assets/{ResponseView-DK3CYom0.js → ResponseView-ygsUs7FU.js} +1 -1
  7. package/.output/public/assets/{StreamingChunkSequence-D3jJutjp.js → StreamingChunkSequence-DMUn8qXi.js} +1 -1
  8. package/.output/public/assets/_sessionId-DoqvnFx7.js +1 -0
  9. package/.output/public/assets/index-B0YcFeL-.js +1 -0
  10. package/.output/public/assets/index-DsiKfWCp.css +1 -0
  11. package/.output/public/assets/{main-hF_572U6.js → main-kBQ49n13.js} +2 -2
  12. package/.output/server/{_sessionId-BqhNE2M8.mjs → _sessionId-CYKaI68v.mjs} +2 -2
  13. package/.output/server/_ssr/{CompareDrawer-C4LQW4S1.mjs → CompareDrawer-CHk4p41X.mjs} +2 -2
  14. package/.output/server/_ssr/{ProxyViewerContainer-BKInvawk.mjs → ProxyViewerContainer-Co9ENCKV.mjs} +276 -47
  15. package/.output/server/_ssr/{ReplayDialog-C3ZiRihL.mjs → ReplayDialog-BRs3fk8H.mjs} +3 -3
  16. package/.output/server/_ssr/{RequestAnatomy-DlVAPIQZ.mjs → RequestAnatomy-Cb68EeZz.mjs} +2 -2
  17. package/.output/server/_ssr/{ResponseView-nMS0rkxu.mjs → ResponseView-DGdbfEjs.mjs} +2 -2
  18. package/.output/server/_ssr/{StreamingChunkSequence-PDWqrNiO.mjs → StreamingChunkSequence-DptYgirK.mjs} +2 -2
  19. package/.output/server/_ssr/{index-Cd1zD-lo.mjs → index-Ef5mCuww.mjs} +2 -2
  20. package/.output/server/_ssr/index.mjs +2 -2
  21. package/.output/server/_ssr/{router-R9gm7_sh.mjs → router-Cvv7SJnd.mjs} +192 -15
  22. package/.output/server/{_tanstack-start-manifest_v-BnLVH_EX.mjs → _tanstack-start-manifest_v-DQoXxIFQ.mjs} +1 -1
  23. package/.output/server/index.mjs +56 -56
  24. package/package.json +1 -1
  25. package/src/components/ProxyViewer.tsx +11 -1
  26. package/src/components/ProxyViewerContainer.tsx +21 -15
  27. package/src/components/providers/ProviderForm.tsx +176 -16
  28. package/src/lib/export-logs.ts +54 -11
  29. package/src/lib/providerTestPrompt.ts +4 -4
  30. package/src/lib/utils.ts +46 -0
  31. package/src/mcp/toolHandlers.ts +58 -8
  32. package/src/proxy/logFinalizer.ts +79 -1
  33. package/src/proxy/logIndex.ts +6 -1
  34. package/src/proxy/schemas.ts +3 -0
  35. package/src/proxy/store.ts +79 -2
  36. package/src/routes/api/logs.stream.ts +5 -2
  37. package/src/routes/api/logs.ts +4 -1
  38. package/.output/public/assets/ProxyViewerContainer-BTYGkg36.js +0 -115
  39. package/.output/public/assets/_sessionId-DpdfAzbo.js +0 -1
  40. package/.output/public/assets/index-780zTVwp.css +0 -1
  41. package/.output/public/assets/index-BpJNbm9G.js +0 -1
@@ -64,6 +64,7 @@ function filterLogs(
64
64
  const DEBOUNCE_MS = 50;
65
65
  const HASH_SCROLL_ATTEMPTS = 12;
66
66
  const HASH_HIGHLIGHT_MS = 1800;
67
+ const MAX_CLIENT_LOGS = 500;
67
68
 
68
69
  function buildLogsStreamUrl(sessionId: string | undefined): string {
69
70
  if (sessionId === undefined) return "/api/logs/stream";
@@ -71,6 +72,20 @@ function buildLogsStreamUrl(sessionId: string | undefined): string {
71
72
  return `/api/logs/stream?${params.toString()}`;
72
73
  }
73
74
 
75
+ function buildLogIndex(logs: readonly CapturedLog[]): Map<number, number> {
76
+ const idx = new Map<number, number>();
77
+ for (let i = 0; i < logs.length; i++) {
78
+ const log = logs[i];
79
+ if (log !== undefined) idx.set(log.id, i);
80
+ }
81
+ return idx;
82
+ }
83
+
84
+ function trimClientLogs(logs: CapturedLog[]): CapturedLog[] {
85
+ if (logs.length <= MAX_CLIENT_LOGS) return logs;
86
+ return logs.slice(logs.length - MAX_CLIENT_LOGS);
87
+ }
88
+
74
89
  export function ProxyViewerContainer({
75
90
  initialSessionId,
76
91
  }: {
@@ -132,6 +147,8 @@ export function ProxyViewerContainer({
132
147
  next = [...next, log];
133
148
  }
134
149
  }
150
+ next = trimClientLogs(next);
151
+ logIndexRef.current = buildLogIndex(next);
135
152
  return next;
136
153
  });
137
154
  }, []);
@@ -173,14 +190,9 @@ export function ProxyViewerContainer({
173
190
  }
174
191
  pendingUpdatesRef.current = [];
175
192
 
176
- // Build fresh index
177
- const idx = new Map<number, number>();
178
- for (let i = 0; i < update.logs.length; i++) {
179
- const log = update.logs[i];
180
- if (log !== undefined) idx.set(log.id, i);
181
- }
182
- logIndexRef.current = idx;
183
- setAllLogs(update.logs);
193
+ const nextLogs = trimClientLogs(update.logs);
194
+ logIndexRef.current = buildLogIndex(nextLogs);
195
+ setAllLogs(nextLogs);
184
196
  setError(null);
185
197
  } else if (update.type === "update") {
186
198
  scheduleUpdate(update.log);
@@ -317,13 +329,7 @@ export function ProxyViewerContainer({
317
329
  const idSet = new Set(ids);
318
330
  setAllLogs((prev) => {
319
331
  const remaining = prev.filter((l) => !idSet.has(l.id));
320
- // Rebuild index
321
- const idx = new Map<number, number>();
322
- for (let i = 0; i < remaining.length; i++) {
323
- const log = remaining[i];
324
- if (log !== undefined) idx.set(log.id, i);
325
- }
326
- logIndexRef.current = idx;
332
+ logIndexRef.current = buildLogIndex(remaining);
327
333
  return remaining;
328
334
  });
329
335
  setError(null);
@@ -1,9 +1,11 @@
1
1
  import { type JSX, useState, useEffect, useRef } from "react";
2
2
  import { Button } from "../ui/button";
3
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
3
4
  import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from "../ui/tooltip";
4
5
  import { Eye, EyeOff, Copy, Check, ChevronDown } from "lucide-react";
5
6
  import type { ProviderConfig, ProviderModelMetadata } from "../../lib/providerContract";
6
7
  import { maskApiKey } from "../../lib/mask";
8
+ import { formatContextWindowInput, parseContextWindowTokensInput } from "../../lib/utils";
7
9
 
8
10
  const ZHIPU_PROVIDER_KEYWORDS = ["zhipu", "zhipuai", "bigmodel", "z.ai", "zai", "glm"];
9
11
  const ZHIPU_CODING_PROVIDER_KEYWORDS = [
@@ -129,11 +131,29 @@ type ProviderFormProps = {
129
131
 
130
132
  type ModelMetadataDraft = {
131
133
  contextWindow: string;
134
+ contextWindowMode: ContextWindowMode;
132
135
  outputLimit: string;
133
136
  };
134
137
 
138
+ type ContextWindowMode = "unset" | "preset" | "custom";
139
+
140
+ type ContextWindowUnit = "K" | "M" | "tokens";
141
+
142
+ const CONTEXT_WINDOW_UNSET = "__unset__";
143
+ const CONTEXT_WINDOW_CUSTOM = "__custom__";
144
+
145
+ const CONTEXT_WINDOW_PRESETS = [
146
+ { value: "32K", label: "Small" },
147
+ { value: "64K", label: "Standard" },
148
+ { value: "128K", label: "Medium" },
149
+ { value: "200K", label: "Long" },
150
+ { value: "256K", label: "Extended" },
151
+ { value: "512K", label: "Large" },
152
+ { value: "1M", label: "Max" },
153
+ ];
154
+
135
155
  function emptyMetadataDraft(): ModelMetadataDraft {
136
- return { contextWindow: "", outputLimit: "" };
156
+ return { contextWindow: "", contextWindowMode: "unset", outputLimit: "" };
137
157
  }
138
158
 
139
159
  function normalizeModelName(value: string): string {
@@ -152,14 +172,74 @@ function findModelMetadata(
152
172
  );
153
173
  }
154
174
 
175
+ function findContextWindowPreset(value: string): string | null {
176
+ const tokens = parseContextWindowTokensInput(value);
177
+ if (tokens === null) return null;
178
+ for (const preset of CONTEXT_WINDOW_PRESETS) {
179
+ if (parseContextWindowTokensInput(preset.value) === tokens) return preset.value;
180
+ }
181
+ return null;
182
+ }
183
+
184
+ function contextWindowModeForValue(value: string): ContextWindowMode {
185
+ if (value.trim() === "") return "unset";
186
+ return findContextWindowPreset(value) !== null ? "preset" : "custom";
187
+ }
188
+
189
+ function selectedContextWindowPresetValue(draft: ModelMetadataDraft): string {
190
+ switch (draft.contextWindowMode) {
191
+ case "unset":
192
+ return CONTEXT_WINDOW_UNSET;
193
+ case "custom":
194
+ return CONTEXT_WINDOW_CUSTOM;
195
+ case "preset":
196
+ return findContextWindowPreset(draft.contextWindow) ?? CONTEXT_WINDOW_CUSTOM;
197
+ }
198
+ }
199
+
200
+ function splitContextWindowEditorValue(value: string): { amount: string; unit: ContextWindowUnit } {
201
+ const trimmed = value.trim().replaceAll(",", "");
202
+ if (trimmed === "") return { amount: "", unit: "K" };
203
+ const match = /^(\d+(?:\.\d+)?)\s*([kKmM])?$/.exec(trimmed);
204
+ if (match === null) return { amount: trimmed, unit: "K" };
205
+ const amount = match[1];
206
+ if (amount === undefined) return { amount: trimmed, unit: "K" };
207
+ const unit = match[2];
208
+ if (unit === undefined || unit === "") return { amount, unit: "tokens" };
209
+ switch (unit.toLowerCase()) {
210
+ case "k":
211
+ return { amount, unit: "K" };
212
+ case "m":
213
+ return { amount, unit: "M" };
214
+ default:
215
+ return { amount: trimmed, unit: "K" };
216
+ }
217
+ }
218
+
219
+ function joinContextWindowEditorValue(amount: string, unit: ContextWindowUnit): string {
220
+ const trimmed = amount.trim();
221
+ if (trimmed === "") return "";
222
+ switch (unit) {
223
+ case "K":
224
+ return `${trimmed}K`;
225
+ case "M":
226
+ return `${trimmed}M`;
227
+ case "tokens":
228
+ return trimmed;
229
+ }
230
+ }
231
+
155
232
  function createMetadataDrafts(
156
233
  provider: ProviderConfig | undefined,
157
234
  models: readonly string[],
158
235
  ): ModelMetadataDraft[] {
159
236
  return models.map((model) => {
160
237
  const metadata = findModelMetadata(provider, model);
238
+ const contextWindow =
239
+ metadata?.contextWindow !== undefined ? formatContextWindowInput(metadata.contextWindow) : "";
161
240
  return {
162
- contextWindow: metadata?.contextWindow?.toString() ?? "",
241
+ contextWindow,
242
+ contextWindowMode: contextWindowModeForValue(contextWindow),
163
243
  outputLimit: metadata?.outputLimit?.toString() ?? "",
164
244
  };
165
245
  });
@@ -315,11 +395,11 @@ export function ProviderForm({ provider, onSubmit, onCancel }: ProviderFormProps
315
395
  newErrors.modelMetadataUrl = "Invalid URL format";
316
396
  }
317
397
  modelMetadataDrafts.forEach((draft, index) => {
318
- const contextWindow = readPositiveIntegerInput(draft.contextWindow);
398
+ const contextWindow = parseContextWindowTokensInput(draft.contextWindow);
319
399
  const outputLimit = readPositiveIntegerInput(draft.outputLimit);
320
400
  if (draft.contextWindow.trim() !== "" && contextWindow === null) {
321
401
  newErrors[`modelMetadata.${index}.contextWindow`] =
322
- "Context window must be a positive integer";
402
+ "Context window must be a positive number, optionally using K or M";
323
403
  }
324
404
  if (draft.outputLimit.trim() !== "" && outputLimit === null) {
325
405
  newErrors[`modelMetadata.${index}.outputLimit`] = "Output limit must be a positive integer";
@@ -361,6 +441,51 @@ export function ProviderForm({ provider, onSubmit, onCancel }: ProviderFormProps
361
441
  });
362
442
  }
363
443
 
444
+ function updateContextWindowPreset(index: number, value: string): void {
445
+ switch (value) {
446
+ case CONTEXT_WINDOW_UNSET:
447
+ updateMetadataDraft(index, { contextWindow: "", contextWindowMode: "unset" });
448
+ return;
449
+ case CONTEXT_WINDOW_CUSTOM: {
450
+ const current = modelMetadataDrafts[index] ?? emptyMetadataDraft();
451
+ updateMetadataDraft(index, {
452
+ contextWindow: current.contextWindow,
453
+ contextWindowMode: "custom",
454
+ });
455
+ return;
456
+ }
457
+ default:
458
+ updateMetadataDraft(index, { contextWindow: value, contextWindowMode: "preset" });
459
+ return;
460
+ }
461
+ }
462
+
463
+ function updateContextWindowAmount(index: number, amount: string): void {
464
+ const current = modelMetadataDrafts[index] ?? emptyMetadataDraft();
465
+ const editorValue = splitContextWindowEditorValue(current.contextWindow);
466
+ updateMetadataDraft(index, {
467
+ contextWindow: joinContextWindowEditorValue(amount, editorValue.unit),
468
+ contextWindowMode: "custom",
469
+ });
470
+ }
471
+
472
+ function updateContextWindowUnit(index: number, unit: string): void {
473
+ const current = modelMetadataDrafts[index] ?? emptyMetadataDraft();
474
+ const editorValue = splitContextWindowEditorValue(current.contextWindow);
475
+ switch (unit) {
476
+ case "K":
477
+ case "M":
478
+ case "tokens":
479
+ updateMetadataDraft(index, {
480
+ contextWindow: joinContextWindowEditorValue(editorValue.amount, unit),
481
+ contextWindowMode: "custom",
482
+ });
483
+ return;
484
+ default:
485
+ return;
486
+ }
487
+ }
488
+
364
489
  function removeModel(index: number): void {
365
490
  setModels((prev) => prev.filter((_, idx) => idx !== index));
366
491
  setModelMetadataDrafts((prev) => prev.filter((_, idx) => idx !== index));
@@ -379,7 +504,7 @@ export function ProviderForm({ provider, onSubmit, onCancel }: ProviderFormProps
379
504
  const trimmedModel = model.trim();
380
505
  if (trimmedModel === "") return;
381
506
  const draft = modelMetadataDrafts[index] ?? emptyMetadataDraft();
382
- const contextWindow = readPositiveIntegerInput(draft.contextWindow);
507
+ const contextWindow = parseContextWindowTokensInput(draft.contextWindow);
383
508
  const outputLimit = readPositiveIntegerInput(draft.outputLimit);
384
509
  if (contextWindow === null && outputLimit === null) return;
385
510
 
@@ -548,6 +673,8 @@ export function ProviderForm({ provider, onSubmit, onCancel }: ProviderFormProps
548
673
  const draft = modelMetadataDrafts[i] ?? emptyMetadataDraft();
549
674
  const contextWindowError = errors[`modelMetadata.${i}.contextWindow`];
550
675
  const outputLimitError = errors[`modelMetadata.${i}.outputLimit`];
676
+ const contextWindowPresetValue = selectedContextWindowPresetValue(draft);
677
+ const contextWindowEditorValue = splitContextWindowEditorValue(draft.contextWindow);
551
678
  return (
552
679
  <div
553
680
  key={i}
@@ -624,21 +751,54 @@ export function ProviderForm({ provider, onSubmit, onCancel }: ProviderFormProps
624
751
  </div>
625
752
 
626
753
  <div className="grid gap-2 sm:grid-cols-2">
627
- <label className="space-y-1 text-xs text-muted-foreground">
754
+ <div className="space-y-1 text-xs text-muted-foreground">
628
755
  <span>Context Window</span>
629
- <input
630
- type="number"
631
- min={1}
632
- step={1000}
633
- value={draft.contextWindow}
634
- onChange={(e) => updateMetadataDraft(i, { contextWindow: e.target.value })}
635
- placeholder="e.g. 1048576"
636
- className="w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-xs text-foreground ring-offset-background placeholder:text-muted-foreground focus-visible:border-ring focus-visible:outline-ring focus-visible:ring-[3px]"
637
- />
756
+ <Select
757
+ value={contextWindowPresetValue}
758
+ onValueChange={(value) => updateContextWindowPreset(i, value)}
759
+ >
760
+ <SelectTrigger size="sm" className="w-full bg-background font-mono text-xs">
761
+ <SelectValue />
762
+ </SelectTrigger>
763
+ <SelectContent className="max-h-64">
764
+ <SelectItem value={CONTEXT_WINDOW_UNSET}>Not set</SelectItem>
765
+ {CONTEXT_WINDOW_PRESETS.map((preset) => (
766
+ <SelectItem key={preset.value} value={preset.value}>
767
+ {preset.label} · {preset.value}
768
+ </SelectItem>
769
+ ))}
770
+ <SelectItem value={CONTEXT_WINDOW_CUSTOM}>Custom</SelectItem>
771
+ </SelectContent>
772
+ </Select>
773
+ {draft.contextWindowMode === "custom" && (
774
+ <div className="grid grid-cols-[minmax(0,1fr)_5.75rem] gap-1.5">
775
+ <input
776
+ type="text"
777
+ inputMode="decimal"
778
+ value={contextWindowEditorValue.amount}
779
+ onChange={(e) => updateContextWindowAmount(i, e.target.value)}
780
+ placeholder="128"
781
+ className="w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-xs text-foreground ring-offset-background placeholder:text-muted-foreground focus-visible:border-ring focus-visible:outline-ring focus-visible:ring-[3px]"
782
+ />
783
+ <Select
784
+ value={contextWindowEditorValue.unit}
785
+ onValueChange={(value) => updateContextWindowUnit(i, value)}
786
+ >
787
+ <SelectTrigger size="sm" className="w-full bg-background font-mono text-xs">
788
+ <SelectValue />
789
+ </SelectTrigger>
790
+ <SelectContent>
791
+ <SelectItem value="K">K</SelectItem>
792
+ <SelectItem value="M">M</SelectItem>
793
+ <SelectItem value="tokens">tokens</SelectItem>
794
+ </SelectContent>
795
+ </Select>
796
+ </div>
797
+ )}
638
798
  {contextWindowError !== undefined && (
639
799
  <span className="block text-destructive">{contextWindowError}</span>
640
800
  )}
641
- </label>
801
+ </div>
642
802
  <label className="space-y-1 text-xs text-muted-foreground">
643
803
  <span>Output Limit</span>
644
804
  <input
@@ -2,6 +2,12 @@ import JSZip from "jszip";
2
2
  import type { CapturedLog } from "../proxy/schemas";
3
3
 
4
4
  export type ExportMode = "redacted" | "raw";
5
+ export type ExportLogsResult =
6
+ | { ok: true }
7
+ | {
8
+ ok: false;
9
+ message: string;
10
+ };
5
11
 
6
12
  const REDACTED = "[REDACTED]";
7
13
  const SECRET_KEY_PATTERN =
@@ -13,6 +19,39 @@ const SECRET_TEXT_PATTERNS: readonly RegExp[] = [
13
19
  /\bghp_[A-Za-z0-9_]{12,}\b/g,
14
20
  /\bglpat-[A-Za-z0-9_-]{12,}\b/g,
15
21
  ];
22
+ const MAX_EXPORT_LOGS = 200;
23
+ const MAX_EXPORT_TEXT_CHARS = 25_000_000;
24
+ const MAX_STREAMING_CHUNK_EXPORTS = 50;
25
+
26
+ function formatApproxSize(chars: number): string {
27
+ if (chars < 1024) return `${chars} chars`;
28
+ if (chars < 1024 * 1024) return `${Math.ceil(chars / 1024)} KB`;
29
+ return `${Math.ceil(chars / (1024 * 1024))} MB`;
30
+ }
31
+
32
+ function estimateExportTextChars(logs: readonly CapturedLog[]): number {
33
+ let total = 0;
34
+ for (const log of logs) {
35
+ total += log.rawRequestBody?.length ?? 0;
36
+ total += log.responseText?.length ?? 0;
37
+ }
38
+ return total;
39
+ }
40
+
41
+ function exportLimitMessage(logs: readonly CapturedLog[]): string | null {
42
+ if (logs.length > MAX_EXPORT_LOGS) {
43
+ return `Export is limited to ${MAX_EXPORT_LOGS} logs at once. Narrow the filter and try again.`;
44
+ }
45
+
46
+ const estimatedChars = estimateExportTextChars(logs);
47
+ if (estimatedChars > MAX_EXPORT_TEXT_CHARS) {
48
+ return `Export is too large (${formatApproxSize(
49
+ estimatedChars,
50
+ )} of text). Narrow the filter and try again.`;
51
+ }
52
+
53
+ return null;
54
+ }
16
55
 
17
56
  async function fetchStreamingChunks(logId: number): Promise<string | null> {
18
57
  try {
@@ -64,9 +103,13 @@ function exportText(text: string, mode: ExportMode): string {
64
103
  export async function exportLogsAsZip(
65
104
  logs: CapturedLog[],
66
105
  mode: ExportMode = "redacted",
67
- ): Promise<void> {
106
+ ): Promise<ExportLogsResult> {
107
+ const limitMessage = exportLimitMessage(logs);
108
+ if (limitMessage !== null) return { ok: false, message: limitMessage };
109
+
68
110
  const zip = new JSZip();
69
111
  const suffix = mode === "redacted" ? "redacted" : "raw";
112
+ const streamingLogs = logs.filter((log) => log.streaming).slice(0, MAX_STREAMING_CHUNK_EXPORTS);
70
113
  zip.file(
71
114
  "manifest.json",
72
115
  JSON.stringify(
@@ -76,6 +119,8 @@ export async function exportLogsAsZip(
76
119
  redacted: mode === "redacted",
77
120
  logCount: logs.length,
78
121
  logIds: logs.map((log) => log.id),
122
+ streamingChunkExportLimit: MAX_STREAMING_CHUNK_EXPORTS,
123
+ streamingChunkLogIds: streamingLogs.map((log) => log.id),
79
124
  },
80
125
  null,
81
126
  2,
@@ -92,16 +137,13 @@ export async function exportLogsAsZip(
92
137
  }
93
138
  }
94
139
 
95
- // Fetch SSE chunks in parallel for streaming logs
96
- const streamingLogs = logs.filter((log) => log.streaming);
97
- await Promise.allSettled(
98
- streamingLogs.map(async (log) => {
99
- const chunks = await fetchStreamingChunks(log.id);
100
- if (chunks !== null) {
101
- zip.file(`#${log.id}.SSE.Response.json`, exportText(chunks, mode));
102
- }
103
- }),
104
- );
140
+ // Fetch SSE chunks sequentially so exports do not spike browser memory.
141
+ for (const log of streamingLogs) {
142
+ const chunks = await fetchStreamingChunks(log.id);
143
+ if (chunks !== null) {
144
+ zip.file(`#${log.id}.SSE.Response.json`, exportText(chunks, mode));
145
+ }
146
+ }
105
147
 
106
148
  // Generate and download ZIP
107
149
  const blob = await zip.generateAsync({ type: "blob" });
@@ -115,4 +157,5 @@ export async function exportLogsAsZip(
115
157
  document.body.removeChild(anchor);
116
158
 
117
159
  URL.revokeObjectURL(url);
160
+ return { ok: true };
118
161
  }
@@ -9,7 +9,7 @@ export type ProviderTestRequestBody = {
9
9
  model: string;
10
10
  messages: ProviderTestMessage[];
11
11
  max_tokens: number;
12
- stream?: true;
12
+ stream: boolean;
13
13
  };
14
14
 
15
15
  const MEMORY_PROBE_FACTS = [
@@ -32,9 +32,9 @@ function modeInstruction(mode: ProviderTestMode): string {
32
32
  function maxTokensForMode(mode: ProviderTestMode): number {
33
33
  switch (mode) {
34
34
  case "non-streaming":
35
- return 1024;
35
+ return 256;
36
36
  case "streaming":
37
- return 384;
37
+ return 256;
38
38
  }
39
39
  }
40
40
 
@@ -71,7 +71,7 @@ export function buildProviderTestRequestBody(
71
71
  };
72
72
  switch (mode) {
73
73
  case "non-streaming":
74
- return base;
74
+ return { ...base, stream: false };
75
75
  case "streaming":
76
76
  return { ...base, stream: true };
77
77
  }
package/src/lib/utils.ts CHANGED
@@ -17,6 +17,52 @@ export function formatContextWindowTokens(count: number): string {
17
17
  return (count / 1024).toFixed(1).replace(/\.0$/, "") + "K";
18
18
  }
19
19
 
20
+ function formatExactContextUnit(count: number, multiplier: number, unit: "K" | "M"): string | null {
21
+ const tenths = count * 10;
22
+ if (!Number.isSafeInteger(tenths) || tenths % multiplier !== 0) return null;
23
+ return (tenths / multiplier / 10).toFixed(1).replace(/\.0$/, "") + unit;
24
+ }
25
+
26
+ export function formatContextWindowInput(count: number): string {
27
+ if (!Number.isSafeInteger(count) || count <= 0) return count.toString();
28
+ if (count >= 1024 * 1024) {
29
+ const megaValue = formatExactContextUnit(count, 1024 * 1024, "M");
30
+ if (megaValue !== null) return megaValue;
31
+ }
32
+ const kiloValue = formatExactContextUnit(count, 1024, "K");
33
+ if (kiloValue !== null) return kiloValue;
34
+ return count.toString();
35
+ }
36
+
37
+ function contextWindowUnitMultiplier(unit: string | undefined): number | null {
38
+ if (unit === undefined || unit === "") return 1;
39
+ switch (unit.toLowerCase()) {
40
+ case "k":
41
+ return 1024;
42
+ case "m":
43
+ return 1024 * 1024;
44
+ default:
45
+ return null;
46
+ }
47
+ }
48
+
49
+ export function parseContextWindowTokensInput(value: string): number | null {
50
+ const trimmed = value.trim().replaceAll(",", "");
51
+ if (trimmed === "") return null;
52
+ const match = /^(\d+(?:\.\d+)?)\s*([kKmM])?$/.exec(trimmed);
53
+ if (match === null) return null;
54
+ const amountText = match[1];
55
+ if (amountText === undefined) return null;
56
+ const amount = Number(amountText);
57
+ const unit = match[2];
58
+ const multiplier = contextWindowUnitMultiplier(unit);
59
+ if (!Number.isFinite(amount) || amount <= 0 || multiplier === null) return null;
60
+ if ((unit === undefined || unit === "") && !Number.isInteger(amount)) return null;
61
+ const tokens = Math.round(amount * multiplier);
62
+ if (!Number.isSafeInteger(tokens) || tokens <= 0) return null;
63
+ return tokens;
64
+ }
65
+
20
66
  export type StatusCategory = "success" | "client_error" | "server_error" | "pending";
21
67
 
22
68
  export function getStatusCategory(status: number | null): StatusCategory {
@@ -13,12 +13,13 @@
13
13
  * `isError: true` results from inside the impl.
14
14
  */
15
15
 
16
+ import { Buffer } from "node:buffer";
16
17
  import { z } from "zod";
17
18
  import { LoopbackTimeoutError, type CallApiOptions } from "./loopback";
18
19
  import { extractLastUserMessagePreview, extractResponsePreview } from "./previewExtractor";
19
20
  import { CapturedLogSchema, type CapturedLog } from "../proxy/schemas";
20
21
 
21
- /** Minimal callApi contract same shape as the real `callApi` in loopback.ts. */
22
+ /** Minimal callApi contract: same shape as the real `callApi` in loopback.ts. */
22
23
  export type CallApiFn = (path: string, options?: CallApiOptions) => Promise<Response>;
23
24
 
24
25
  export type ToolResult = {
@@ -26,7 +27,7 @@ export type ToolResult = {
26
27
  isError?: true;
27
28
  };
28
29
 
29
- // Loose shape returned by `GET /api/logs` `logs: CapturedLog[]` and a few
30
+ // Loose shape returned by `GET /api/logs`: `logs: CapturedLog[]` and a few
30
31
  // pagination fields. The CapturedLog items are fully validated downstream.
31
32
  const LogsListResponseSchema = z.object({
32
33
  logs: z.array(CapturedLogSchema).optional(),
@@ -37,6 +38,7 @@ const LogsListResponseSchema = z.object({
37
38
 
38
39
  const PAGINATION_DEFAULTS = { offset: 0, limit: 3 };
39
40
  export const LIMIT_HARD_CAP = 5;
41
+ const LOG_DETAIL_TEXT_LIMIT = 200_000;
40
42
 
41
43
  export function clampLimit(input: number | undefined): number {
42
44
  if (input === undefined) return PAGINATION_DEFAULTS.limit;
@@ -52,10 +54,55 @@ function toolError(message: string): ToolResult {
52
54
  return { content: [{ type: "text", text: message }], isError: true };
53
55
  }
54
56
 
57
+ function textByteLength(value: string | null): number | null {
58
+ if (value === null) return null;
59
+ return Buffer.byteLength(value, "utf8");
60
+ }
61
+
62
+ function hasBodyText(value: string | null, byteLength: number | null | undefined): boolean {
63
+ if (value !== null && value.length > 0) return true;
64
+ return byteLength !== undefined && byteLength !== null && byteLength > 0;
65
+ }
66
+
67
+ function truncateToolText(value: string | null): {
68
+ value: string | null;
69
+ byteLength: number | null;
70
+ truncated: boolean;
71
+ } {
72
+ if (value === null) return { value: null, byteLength: null, truncated: false };
73
+ const byteLength = textByteLength(value);
74
+ if (value.length <= LOG_DETAIL_TEXT_LIMIT) {
75
+ return { value, byteLength, truncated: false };
76
+ }
77
+ const suffix = `\n[truncated by agent-inspector MCP: original ${byteLength ?? 0} bytes]`;
78
+ return {
79
+ value: `${value.slice(0, LOG_DETAIL_TEXT_LIMIT)}${suffix}`,
80
+ byteLength,
81
+ truncated: true,
82
+ };
83
+ }
84
+
85
+ function buildBoundedLogDetail(log: CapturedLog): Record<string, unknown> {
86
+ const { streamingChunks: _chunks, rawRequestBody, responseText, ...rest } = log;
87
+ const boundedRequest = truncateToolText(rawRequestBody);
88
+ const boundedResponse = truncateToolText(responseText);
89
+ return {
90
+ ...rest,
91
+ rawRequestBody: boundedRequest.value,
92
+ responseText: boundedResponse.value,
93
+ rawRequestBodyBytes: boundedRequest.byteLength,
94
+ responseTextBytes: boundedResponse.byteLength,
95
+ rawRequestBodyTruncated: boundedRequest.truncated,
96
+ responseTextTruncated: boundedResponse.truncated,
97
+ };
98
+ }
99
+
55
100
  export function buildLogSummary(log: CapturedLog) {
56
101
  const hasError =
57
102
  (log.error !== null && log.error !== undefined && log.error.length > 0) ||
58
103
  (log.responseStatus !== null && log.responseStatus !== undefined && log.responseStatus >= 400);
104
+ const rawRequestBodyBytes = log.rawRequestBodyBytes ?? textByteLength(log.rawRequestBody);
105
+ const responseTextBytes = log.responseTextBytes ?? textByteLength(log.responseText);
59
106
  return {
60
107
  id: log.id,
61
108
  timestamp: log.timestamp,
@@ -81,7 +128,9 @@ export function buildLogSummary(log: CapturedLog) {
81
128
  hasChunks:
82
129
  (log.streamingChunks !== undefined && log.streamingChunks !== null) ||
83
130
  (log.streamingChunksPath !== null && log.streamingChunksPath !== undefined),
84
- hasRawRequestBody: log.rawRequestBody !== null && log.rawRequestBody !== undefined,
131
+ hasRawRequestBody: hasBodyText(log.rawRequestBody, rawRequestBodyBytes),
132
+ rawRequestBodyBytes,
133
+ responseTextBytes,
85
134
  };
86
135
  }
87
136
 
@@ -99,7 +148,11 @@ export type ListLogsArgs = {
99
148
  export async function listLogsImpl(callApi: CallApiFn, args: ListLogsArgs): Promise<ToolResult> {
100
149
  const offset = args.offset ?? PAGINATION_DEFAULTS.offset;
101
150
  const limit = clampLimit(args.limit);
102
- const params = new URLSearchParams({ offset: String(offset), limit: String(limit) });
151
+ const params = new URLSearchParams({
152
+ offset: String(offset),
153
+ limit: String(limit),
154
+ compact: "1",
155
+ });
103
156
  if (args.sessionId !== undefined && args.sessionId.length > 0) {
104
157
  params.set("sessionId", args.sessionId);
105
158
  }
@@ -123,10 +176,7 @@ export async function getLogImpl(callApi: CallApiFn, id: number): Promise<ToolRe
123
176
  if (!parsed.success) {
124
177
  return toolError(`GET /api/logs/${id} returned an unparseable CapturedLog`);
125
178
  }
126
- // Strip streamingChunks per design D6 — the agent asks for chunks
127
- // explicitly via inspector_get_log_chunks.
128
- const { streamingChunks: _chunks, ...rest } = parsed.data;
129
- return textJson(rest);
179
+ return textJson(buildBoundedLogDetail(parsed.data));
130
180
  }
131
181
 
132
182
  export async function getLogChunksImpl(callApi: CallApiFn, id: number): Promise<ToolResult> {