@tonyclaw/llm-inspector 1.12.0 → 1.14.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/.output/nitro.json +1 -1
- package/.output/public/assets/index-B5q3Llgm.css +1 -0
- package/.output/public/assets/index-C6tbslcs.js +105 -0
- package/.output/public/assets/{main-BYCM7aJx.js → main-C1k6vRnH.js} +3 -3
- package/.output/server/_libs/cfworker__json-schema.mjs +1 -0
- package/.output/server/_libs/lucide-react.mjs +64 -58
- package/.output/server/_libs/modelcontextprotocol__server.mjs +9738 -0
- package/.output/server/_libs/zod.mjs +79 -16
- package/.output/server/_ssr/{index-DhChP_jV.mjs → index-AxruZp16.mjs} +1201 -165
- package/.output/server/_ssr/index.mjs +2 -2
- package/.output/server/_ssr/{router-PZjNwOcw.mjs → router-DtleGqN8.mjs} +650 -29
- package/.output/server/_tanstack-start-manifest_v-B1WAHWIa.mjs +4 -0
- package/.output/server/index.mjs +24 -24
- package/README.md +98 -0
- package/package.json +3 -1
- package/src/components/ProxyViewer.tsx +126 -2
- package/src/components/proxy-viewer/CompareDrawer.tsx +880 -0
- package/src/components/proxy-viewer/ConversationGroup.tsx +8 -0
- package/src/components/proxy-viewer/LogEntry.tsx +14 -1
- package/src/components/proxy-viewer/LogEntryHeader.tsx +28 -0
- package/src/components/proxy-viewer/formats/openai/ResponseView.tsx +74 -4
- package/src/components/proxy-viewer/requestDiff.ts +277 -0
- package/src/lib/serverPort.ts +41 -0
- package/src/mcp/loopback.ts +76 -0
- package/src/mcp/previewExtractor.ts +166 -0
- package/src/mcp/server.ts +320 -0
- package/src/mcp/toolHandlers.ts +259 -0
- package/src/proxy/formats/openai/schemas.ts +19 -0
- package/src/proxy/handler.ts +23 -2
- package/src/proxy/openaiOrphanToolStrip.ts +148 -0
- package/src/proxy/schemas.ts +1 -0
- package/src/routes/api/mcp.ts +25 -0
- package/.output/public/assets/index-DVgdkDgq.js +0 -105
- package/.output/public/assets/index-DZx2yk8v.css +0 -1
- package/.output/server/_tanstack-start-manifest_v-l1kWkG0h.mjs +0 -4
|
@@ -21,6 +21,10 @@ export type ConversationGroupProps = {
|
|
|
21
21
|
* across the whole viewer. Each `LogEntry` looks up its own entry.
|
|
22
22
|
*/
|
|
23
23
|
cacheTrends?: Map<number, CacheTrendEntry>;
|
|
24
|
+
/** Set of log ids currently marked for comparison. Forwarded to each `LogEntry`. */
|
|
25
|
+
selectedSet: Set<number>;
|
|
26
|
+
/** Toggle a log in/out of the comparison selection. */
|
|
27
|
+
onToggleSelect: (logId: number) => void;
|
|
24
28
|
};
|
|
25
29
|
|
|
26
30
|
function computeStats(logs: CapturedLog[]): {
|
|
@@ -41,6 +45,8 @@ export const ConversationGroup = memo(function ({
|
|
|
41
45
|
viewMode = "simple",
|
|
42
46
|
strip,
|
|
43
47
|
cacheTrends,
|
|
48
|
+
selectedSet,
|
|
49
|
+
onToggleSelect,
|
|
44
50
|
}: ConversationGroupProps): JSX.Element {
|
|
45
51
|
const [expanded, setExpanded] = useState(false);
|
|
46
52
|
|
|
@@ -81,6 +87,8 @@ export const ConversationGroup = memo(function ({
|
|
|
81
87
|
suppressApiFormatBadge={!mixed}
|
|
82
88
|
strip={strip}
|
|
83
89
|
cacheTrend={cacheTrends?.get(log.id) ?? null}
|
|
90
|
+
isSelected={selectedSet.has(log.id)}
|
|
91
|
+
onToggleSelect={onToggleSelect}
|
|
84
92
|
/>
|
|
85
93
|
))}
|
|
86
94
|
</div>
|
|
@@ -31,6 +31,10 @@ export type LogEntryProps = {
|
|
|
31
31
|
* `null` (or absent) means the header should render with no arrows.
|
|
32
32
|
*/
|
|
33
33
|
cacheTrend?: CacheTrendEntry | null;
|
|
34
|
+
/** Whether this log is currently marked for comparison. */
|
|
35
|
+
isSelected?: boolean;
|
|
36
|
+
/** Toggle this log in/out of the comparison selection. */
|
|
37
|
+
onToggleSelect?: (logId: number) => void;
|
|
34
38
|
};
|
|
35
39
|
|
|
36
40
|
/**
|
|
@@ -138,6 +142,8 @@ export const LogEntry = memo(function ({
|
|
|
138
142
|
suppressApiFormatBadge = false,
|
|
139
143
|
strip,
|
|
140
144
|
cacheTrend = null,
|
|
145
|
+
isSelected = false,
|
|
146
|
+
onToggleSelect,
|
|
141
147
|
}: LogEntryProps): JSX.Element {
|
|
142
148
|
const [expanded, setExpanded] = useState<boolean>(false);
|
|
143
149
|
const [requestCopied, setRequestCopied] = useState<boolean>(false);
|
|
@@ -193,7 +199,12 @@ export const LogEntry = memo(function ({
|
|
|
193
199
|
|
|
194
200
|
return (
|
|
195
201
|
<>
|
|
196
|
-
<div
|
|
202
|
+
<div
|
|
203
|
+
className={cn(
|
|
204
|
+
"border border-border rounded-lg mb-3 overflow-hidden",
|
|
205
|
+
isSelected && "border-l-2 border-l-amber-400",
|
|
206
|
+
)}
|
|
207
|
+
>
|
|
197
208
|
<LogEntryHeader
|
|
198
209
|
log={log}
|
|
199
210
|
parsedRequest={parsedRequest}
|
|
@@ -201,6 +212,8 @@ export const LogEntry = memo(function ({
|
|
|
201
212
|
onToggle={() => setExpanded(!expanded)}
|
|
202
213
|
suppressApiFormatBadge={suppressApiFormatBadge}
|
|
203
214
|
cacheTrend={cacheTrend}
|
|
215
|
+
isSelected={isSelected}
|
|
216
|
+
onToggleSelect={onToggleSelect}
|
|
204
217
|
/>
|
|
205
218
|
|
|
206
219
|
{expanded && (
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ArrowDown,
|
|
3
3
|
ArrowUp,
|
|
4
|
+
Check,
|
|
4
5
|
ChevronDown,
|
|
5
6
|
ChevronRight,
|
|
6
7
|
Clock,
|
|
@@ -66,6 +67,10 @@ export type LogEntryHeaderProps = {
|
|
|
66
67
|
* the corresponding cache span renders as it did before — no arrow.
|
|
67
68
|
*/
|
|
68
69
|
cacheTrend?: { creation: CacheTrend | null; read: CacheTrend | null } | null;
|
|
70
|
+
/** Whether this log is currently marked for comparison. */
|
|
71
|
+
isSelected?: boolean;
|
|
72
|
+
/** Toggle this log in/out of the comparison selection. */
|
|
73
|
+
onToggleSelect?: (logId: number) => void;
|
|
69
74
|
};
|
|
70
75
|
|
|
71
76
|
export const LogEntryHeader = memo(function ({
|
|
@@ -75,6 +80,8 @@ export const LogEntryHeader = memo(function ({
|
|
|
75
80
|
onToggle,
|
|
76
81
|
suppressApiFormatBadge = false,
|
|
77
82
|
cacheTrend = null,
|
|
83
|
+
isSelected = false,
|
|
84
|
+
onToggleSelect,
|
|
78
85
|
}: LogEntryHeaderProps): JSX.Element {
|
|
79
86
|
const statusCategory = getStatusCategory(log.responseStatus);
|
|
80
87
|
|
|
@@ -104,6 +111,27 @@ export const LogEntryHeader = memo(function ({
|
|
|
104
111
|
}
|
|
105
112
|
}}
|
|
106
113
|
>
|
|
114
|
+
{/* Selection checkbox (for log-request comparison) */}
|
|
115
|
+
{onToggleSelect !== undefined && (
|
|
116
|
+
<button
|
|
117
|
+
type="button"
|
|
118
|
+
onClick={(e) => {
|
|
119
|
+
e.stopPropagation();
|
|
120
|
+
onToggleSelect(log.id);
|
|
121
|
+
}}
|
|
122
|
+
aria-label={isSelected ? "Deselect for comparison" : "Select for comparison"}
|
|
123
|
+
aria-pressed={isSelected}
|
|
124
|
+
className={cn(
|
|
125
|
+
"shrink-0 size-4 rounded-sm border flex items-center justify-center transition-colors cursor-pointer",
|
|
126
|
+
isSelected
|
|
127
|
+
? "bg-amber-400 border-amber-400 text-amber-950"
|
|
128
|
+
: "border-muted-foreground/40 hover:border-amber-400 hover:bg-amber-400/10",
|
|
129
|
+
)}
|
|
130
|
+
>
|
|
131
|
+
{isSelected && <Check className="size-3" strokeWidth={3} />}
|
|
132
|
+
</button>
|
|
133
|
+
)}
|
|
134
|
+
|
|
107
135
|
{/* Request ID */}
|
|
108
136
|
<span className="text-blue-400/80 font-mono text-xs font-semibold tabular-nums shrink-0">
|
|
109
137
|
#{log.id}
|
|
@@ -1,18 +1,83 @@
|
|
|
1
|
-
import { StopCircle, Zap } from "lucide-react";
|
|
2
|
-
import type
|
|
1
|
+
import { StopCircle, Terminal, Zap } from "lucide-react";
|
|
2
|
+
import { useState, type JSX } from "react";
|
|
3
3
|
import ReactMarkdown from "react-markdown";
|
|
4
|
-
import type { OpenAIResponse } from "../../../../proxy/schemas";
|
|
4
|
+
import type { OpenAIResponse, OpenAIToolCall } from "../../../../proxy/schemas";
|
|
5
5
|
import { formatTokens } from "../../../../lib/utils";
|
|
6
6
|
import { Badge } from "../../../ui/badge";
|
|
7
|
+
import { JsonViewer, safeJsonValue } from "../../../ui/json-viewer";
|
|
8
|
+
import { ScrollArea } from "../../../ui/scroll-area";
|
|
7
9
|
import { Separator } from "../../../ui/separator";
|
|
10
|
+
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "../../../ui/collapsible";
|
|
11
|
+
import { ChevronDown, ChevronRight } from "lucide-react";
|
|
8
12
|
import { extractThinkingFromContent, ThinkingBlock } from "../anthropic/ContentBlocks";
|
|
9
13
|
|
|
10
14
|
// Re-export for use in other components
|
|
11
15
|
export { extractThinkingFromContent } from "../anthropic/ContentBlocks";
|
|
12
16
|
|
|
17
|
+
/** Best-effort JSON parse of an OpenAI `function.arguments` string. Returns
|
|
18
|
+
* the parsed object, or `null` on parse failure so the renderer can fall
|
|
19
|
+
* back to showing the raw string. */
|
|
20
|
+
function parseToolArguments(raw: string | undefined): unknown {
|
|
21
|
+
if (raw === undefined || raw === "") return {};
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(raw);
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One collapsible tool_use row, mirroring the Anthropic ToolUseBlock visual
|
|
30
|
+
* treatment (Terminal icon, blue accent, name as a Badge, JSON input in a
|
|
31
|
+
* scrollable JsonViewer). */
|
|
32
|
+
function OpenAIToolCallBlock({ call }: { call: OpenAIToolCall }): JSX.Element {
|
|
33
|
+
const [open, setOpen] = useState(false);
|
|
34
|
+
const name = call.function.name ?? "(unnamed tool)";
|
|
35
|
+
const parsed = parseToolArguments(call.function.arguments);
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
<Collapsible open={open} onOpenChange={setOpen}>
|
|
39
|
+
<div className="border-l-2 border-blue-500/40 my-1">
|
|
40
|
+
<CollapsibleTrigger className="flex items-center gap-1.5 px-3 py-1 w-full text-left cursor-pointer hover:bg-blue-500/5 transition-colors rounded-r-sm group">
|
|
41
|
+
<Terminal className="size-3.5 text-blue-400 shrink-0" />
|
|
42
|
+
<Badge variant="outline" className="text-[10px] font-mono px-1.5 py-0 h-4">
|
|
43
|
+
{name}
|
|
44
|
+
</Badge>
|
|
45
|
+
{call.id !== undefined && call.id !== "" && (
|
|
46
|
+
<span className="text-[10px] font-mono text-muted-foreground/60 truncate">
|
|
47
|
+
{call.id}
|
|
48
|
+
</span>
|
|
49
|
+
)}
|
|
50
|
+
<span className="flex-1" />
|
|
51
|
+
{open ? (
|
|
52
|
+
<ChevronDown className="size-3 text-muted-foreground" />
|
|
53
|
+
) : (
|
|
54
|
+
<ChevronRight className="size-3 text-muted-foreground" />
|
|
55
|
+
)}
|
|
56
|
+
</CollapsibleTrigger>
|
|
57
|
+
<CollapsibleContent>
|
|
58
|
+
<div className="px-3 pb-2">
|
|
59
|
+
<ScrollArea className="max-h-[60vh]">
|
|
60
|
+
{parsed === null ? (
|
|
61
|
+
// JSON.parse failed — show the raw string so the user can
|
|
62
|
+
// still see what the model tried to call.
|
|
63
|
+
<pre className="font-mono text-xs whitespace-pre-wrap break-words text-rose-300/90">
|
|
64
|
+
{call.function.arguments}
|
|
65
|
+
</pre>
|
|
66
|
+
) : (
|
|
67
|
+
<JsonViewer data={safeJsonValue(parsed)} defaultExpandDepth={2} />
|
|
68
|
+
)}
|
|
69
|
+
</ScrollArea>
|
|
70
|
+
</div>
|
|
71
|
+
</CollapsibleContent>
|
|
72
|
+
</div>
|
|
73
|
+
</Collapsible>
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
13
77
|
export function OpenAIResponseView({ response }: { response: OpenAIResponse }): JSX.Element {
|
|
14
78
|
const choice = response.choices[0];
|
|
15
79
|
const message = choice?.message;
|
|
80
|
+
const toolCalls = message?.tool_calls ?? [];
|
|
16
81
|
|
|
17
82
|
return (
|
|
18
83
|
<div className="space-y-3">
|
|
@@ -70,6 +135,10 @@ export function OpenAIResponseView({ response }: { response: OpenAIResponse }):
|
|
|
70
135
|
</div>
|
|
71
136
|
);
|
|
72
137
|
})()}
|
|
138
|
+
{toolCalls.map((call, i) => (
|
|
139
|
+
// biome-ignore lint/suspicious/noArrayIndexKey: tool_calls is the positionally stable list from the response
|
|
140
|
+
<OpenAIToolCallBlock key={call.id ?? `tc-${i}`} call={call} />
|
|
141
|
+
))}
|
|
73
142
|
{message?.function_call !== null && message?.function_call !== undefined && (
|
|
74
143
|
<div className="border border-blue-500/30 rounded-md p-3 bg-blue-500/5">
|
|
75
144
|
<div className="text-xs text-blue-400 font-mono mb-1">function_call</div>
|
|
@@ -85,7 +154,8 @@ export function OpenAIResponseView({ response }: { response: OpenAIResponse }):
|
|
|
85
154
|
(message?.reasoning_content === null ||
|
|
86
155
|
message?.reasoning_content === undefined ||
|
|
87
156
|
message.reasoning_content.length === 0) &&
|
|
88
|
-
(message?.function_call === null || message?.function_call === undefined) &&
|
|
157
|
+
(message?.function_call === null || message?.function_call === undefined) &&
|
|
158
|
+
toolCalls.length === 0 && (
|
|
89
159
|
<p className="text-xs text-muted-foreground italic">Empty response content</p>
|
|
90
160
|
)}
|
|
91
161
|
</div>
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Path-aligned JSON-tree diff helpers for the "compare two log requests" feature.
|
|
3
|
+
*
|
|
4
|
+
* Given two captured log Request payloads, we:
|
|
5
|
+
* 1. Normalize each payload (deep-clone, sort object keys, keep array order)
|
|
6
|
+
* so that non-semantic differences (key order, string whitespace) do not
|
|
7
|
+
* generate false positives.
|
|
8
|
+
* 2. Walk the two trees in lockstep, emitting a list of path-anchored
|
|
9
|
+
* `DiffOp`s. Equal subtrees collapse into a single op at the subtree
|
|
10
|
+
* root, so the renderer can choose to expand or hide them.
|
|
11
|
+
* 3. Emit ops in path-sorted order (depth-first, sibling order = object-key
|
|
12
|
+
* ascending then array-index ascending) so the renderer can lay them
|
|
13
|
+
* out linearly.
|
|
14
|
+
*
|
|
15
|
+
* No runtime dependencies. Mirrors the `cacheTrend.ts` pure-helper pattern.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export type JsonPrimitive = string | number | boolean | null;
|
|
19
|
+
export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
|
20
|
+
|
|
21
|
+
export type JsonNode =
|
|
22
|
+
| { kind: "object"; value: Record<string, JsonNode> }
|
|
23
|
+
| { kind: "array"; value: JsonNode[] }
|
|
24
|
+
| { kind: "primitive"; value: JsonPrimitive };
|
|
25
|
+
|
|
26
|
+
export type DiffOp =
|
|
27
|
+
| { kind: "equal"; path: string; value: JsonNode }
|
|
28
|
+
| { kind: "added"; path: string; value: JsonNode }
|
|
29
|
+
| { kind: "removed"; path: string; value: JsonNode }
|
|
30
|
+
| {
|
|
31
|
+
kind: "changed";
|
|
32
|
+
path: string;
|
|
33
|
+
left: JsonNode;
|
|
34
|
+
right: JsonNode;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** A single segment of a JSON path: an object key or an array index. */
|
|
38
|
+
export type PathSegment = string | number;
|
|
39
|
+
|
|
40
|
+
const ROOT_PATH = "";
|
|
41
|
+
|
|
42
|
+
/** Render a path segment list as a human-readable string.
|
|
43
|
+
*
|
|
44
|
+
* - Root (empty list) → `""` (no label; the renderer hides the gutter)
|
|
45
|
+
* - Object key → `.foo`
|
|
46
|
+
* - Array index → `[3]`
|
|
47
|
+
* - Top-level object key → `messages` (no leading dot)
|
|
48
|
+
*
|
|
49
|
+
* Examples:
|
|
50
|
+
* [] → ""
|
|
51
|
+
* ["messages"] → "messages"
|
|
52
|
+
* ["messages", 3] → "messages[3]"
|
|
53
|
+
* ["messages", 3, "content"] → "messages[3].content"
|
|
54
|
+
* ["messages", 3, "content", 0] → "messages[3].content[0]"
|
|
55
|
+
*/
|
|
56
|
+
export function formatPath(segments: PathSegment[]): string {
|
|
57
|
+
if (segments.length === 0) return ROOT_PATH;
|
|
58
|
+
let out = "";
|
|
59
|
+
for (let i = 0; i < segments.length; i++) {
|
|
60
|
+
const seg = segments[i];
|
|
61
|
+
if (seg === undefined) continue;
|
|
62
|
+
if (typeof seg === "number") {
|
|
63
|
+
out += `[${seg}]`;
|
|
64
|
+
} else if (i === 0) {
|
|
65
|
+
out += seg;
|
|
66
|
+
} else {
|
|
67
|
+
out += `.${seg}`;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
74
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Normalize a captured Request body for comparison.
|
|
79
|
+
*
|
|
80
|
+
* Captured Request bodies are sometimes already-parsed objects and sometimes
|
|
81
|
+
* JSON-encoded strings (depending on which capture path produced the log).
|
|
82
|
+
* We:
|
|
83
|
+
* 1. Try `JSON.parse` if the input is a string.
|
|
84
|
+
* 2. Deep-walk the value, building a fresh `JsonNode` tree.
|
|
85
|
+
* 3. Sort object keys lexicographically (key order is not semantically
|
|
86
|
+
* meaningful for most LLM SDKs but varies between SDK versions, so we
|
|
87
|
+
* canonicalize it).
|
|
88
|
+
* 4. Keep array order (semantically meaningful: `messages[]` order is
|
|
89
|
+
* conversation order; reordering it would silently destroy the diff).
|
|
90
|
+
* 5. Leave primitives alone (no whitespace trim — those can be meaningful
|
|
91
|
+
* in user-message text).
|
|
92
|
+
*
|
|
93
|
+
* Idempotent at the data level: re-normalizing the same shape (in any key
|
|
94
|
+
* order) yields the same tree.
|
|
95
|
+
*/
|
|
96
|
+
export function normalizeRequest(raw: unknown): JsonNode {
|
|
97
|
+
if (typeof raw === "string") {
|
|
98
|
+
try {
|
|
99
|
+
return toNode(JSON.parse(raw));
|
|
100
|
+
} catch {
|
|
101
|
+
// Unparseable string: wrap as a primitive string node so the diff can
|
|
102
|
+
// still operate on it (changed vs. another string, or added/removed
|
|
103
|
+
// vs. an object).
|
|
104
|
+
return { kind: "primitive", value: raw };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return toNode(raw);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function toNode(value: unknown): JsonNode {
|
|
111
|
+
if (value === null) return { kind: "primitive", value: null };
|
|
112
|
+
if (typeof value === "string") return { kind: "primitive", value };
|
|
113
|
+
if (typeof value === "number") return { kind: "primitive", value };
|
|
114
|
+
if (typeof value === "boolean") return { kind: "primitive", value };
|
|
115
|
+
if (Array.isArray(value)) {
|
|
116
|
+
return { kind: "array", value: value.map((v) => toNode(v)) };
|
|
117
|
+
}
|
|
118
|
+
if (isPlainObject(value)) {
|
|
119
|
+
const out: Record<string, JsonNode> = {};
|
|
120
|
+
for (const k of Object.keys(value).sort()) {
|
|
121
|
+
out[k] = toNode(value[k]);
|
|
122
|
+
}
|
|
123
|
+
return { kind: "object", value: out };
|
|
124
|
+
}
|
|
125
|
+
// Functions, symbols, bigints, undefined — treat as null in the diff model.
|
|
126
|
+
return { kind: "primitive", value: null };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Compute the path-aligned diff of two normalized trees.
|
|
131
|
+
*
|
|
132
|
+
* Emits `DiffOp[]` in path-sorted order. For each path:
|
|
133
|
+
* - if both trees have the same value, emit a single `equal` op at the
|
|
134
|
+
* deepest common ancestor (so equal subtrees collapse into one op);
|
|
135
|
+
* - if only the right has it, emit `added`;
|
|
136
|
+
* - if only the left has it, emit `removed`;
|
|
137
|
+
* - if both have it but it differs, emit `changed` (and recurse into
|
|
138
|
+
* objects/arrays so the user sees *which* field changed).
|
|
139
|
+
*
|
|
140
|
+
* Pure: does not mutate `left` or `right`.
|
|
141
|
+
*/
|
|
142
|
+
export function diffTrees(left: JsonNode, right: JsonNode): DiffOp[] {
|
|
143
|
+
const ops: DiffOp[] = [];
|
|
144
|
+
walk([], left, right, ops);
|
|
145
|
+
return ops;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function walk(segments: PathSegment[], left: JsonNode, right: JsonNode, out: DiffOp[]): void {
|
|
149
|
+
const path = formatPath(segments);
|
|
150
|
+
|
|
151
|
+
if (nodeEqual(left, right)) {
|
|
152
|
+
out.push({ kind: "equal", path, value: left });
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Type mismatch or primitive change.
|
|
157
|
+
if (left.kind !== right.kind) {
|
|
158
|
+
out.push({ kind: "changed", path, left, right });
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (left.kind === "primitive" && right.kind === "primitive") {
|
|
163
|
+
out.push({ kind: "changed", path, left, right });
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (left.kind === "object" && right.kind === "object") {
|
|
168
|
+
const leftKeys = Object.keys(left.value);
|
|
169
|
+
const rightKeys = Object.keys(right.value);
|
|
170
|
+
const rightKeySet = new Set(rightKeys);
|
|
171
|
+
|
|
172
|
+
for (const k of leftKeys) {
|
|
173
|
+
const lChild = left.value[k];
|
|
174
|
+
if (lChild === undefined) continue;
|
|
175
|
+
if (!rightKeySet.has(k)) {
|
|
176
|
+
out.push({
|
|
177
|
+
kind: "removed",
|
|
178
|
+
path: formatPath([...segments, k]),
|
|
179
|
+
value: lChild,
|
|
180
|
+
});
|
|
181
|
+
} else {
|
|
182
|
+
const rChild = right.value[k];
|
|
183
|
+
if (rChild === undefined) continue;
|
|
184
|
+
walk([...segments, k], lChild, rChild, out);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
for (const k of rightKeys) {
|
|
188
|
+
if (leftKeys.includes(k)) continue;
|
|
189
|
+
const rChild = right.value[k];
|
|
190
|
+
if (rChild === undefined) continue;
|
|
191
|
+
out.push({
|
|
192
|
+
kind: "added",
|
|
193
|
+
path: formatPath([...segments, k]),
|
|
194
|
+
value: rChild,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (left.kind === "array" && right.kind === "array") {
|
|
201
|
+
const minLen = Math.min(left.value.length, right.value.length);
|
|
202
|
+
for (let i = 0; i < minLen; i++) {
|
|
203
|
+
const lChild = left.value[i];
|
|
204
|
+
const rChild = right.value[i];
|
|
205
|
+
if (lChild === undefined || rChild === undefined) continue;
|
|
206
|
+
walk([...segments, i], lChild, rChild, out);
|
|
207
|
+
}
|
|
208
|
+
for (let i = minLen; i < right.value.length; i++) {
|
|
209
|
+
const rChild = right.value[i];
|
|
210
|
+
if (rChild === undefined) continue;
|
|
211
|
+
out.push({
|
|
212
|
+
kind: "added",
|
|
213
|
+
path: formatPath([...segments, i]),
|
|
214
|
+
value: rChild,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
for (let i = minLen; i < left.value.length; i++) {
|
|
218
|
+
const lChild = left.value[i];
|
|
219
|
+
if (lChild === undefined) continue;
|
|
220
|
+
out.push({
|
|
221
|
+
kind: "removed",
|
|
222
|
+
path: formatPath([...segments, i]),
|
|
223
|
+
value: lChild,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function nodeEqual(a: JsonNode, b: JsonNode): boolean {
|
|
230
|
+
if (a.kind !== b.kind) return false;
|
|
231
|
+
if (a.kind === "primitive" && b.kind === "primitive") {
|
|
232
|
+
return a.value === b.value;
|
|
233
|
+
}
|
|
234
|
+
if (a.kind === "array" && b.kind === "array") {
|
|
235
|
+
if (a.value.length !== b.value.length) return false;
|
|
236
|
+
for (let i = 0; i < a.value.length; i++) {
|
|
237
|
+
const ai = a.value[i];
|
|
238
|
+
const bi = b.value[i];
|
|
239
|
+
if (ai === undefined || bi === undefined) return false;
|
|
240
|
+
if (!nodeEqual(ai, bi)) return false;
|
|
241
|
+
}
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
if (a.kind === "object" && b.kind === "object") {
|
|
245
|
+
const aKeys = Object.keys(a.value);
|
|
246
|
+
const bKeys = Object.keys(b.value);
|
|
247
|
+
if (aKeys.length !== bKeys.length) return false;
|
|
248
|
+
for (const k of aKeys) {
|
|
249
|
+
const av = a.value[k];
|
|
250
|
+
const bv = b.value[k];
|
|
251
|
+
if (av === undefined || bv === undefined) return false;
|
|
252
|
+
if (!nodeEqual(av, bv)) return false;
|
|
253
|
+
}
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Render a JsonNode to a compact human-readable preview. Used by the
|
|
260
|
+
* diff view's gutter or change rows where we want a one-line summary
|
|
261
|
+
* without pretty-printing the whole subtree. */
|
|
262
|
+
export function previewNode(node: JsonNode, maxLen = 80): string {
|
|
263
|
+
let s: string;
|
|
264
|
+
switch (node.kind) {
|
|
265
|
+
case "primitive":
|
|
266
|
+
s = node.value === null ? "null" : JSON.stringify(node.value);
|
|
267
|
+
break;
|
|
268
|
+
case "array":
|
|
269
|
+
s = `[… ${node.value.length} items]`;
|
|
270
|
+
break;
|
|
271
|
+
case "object":
|
|
272
|
+
s = `{… ${Object.keys(node.value).length} keys}`;
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
if (s.length > maxLen) s = `${s.slice(0, maxLen - 1)}…`;
|
|
276
|
+
return s;
|
|
277
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/* eslint-disable functional/no-throw-statements */
|
|
2
|
+
/**
|
|
3
|
+
* Tracks the HTTP port the inspector server is bound to, so internal
|
|
4
|
+
* components (currently the MCP server's loopback fetch) can build
|
|
5
|
+
* `http://127.0.0.1:<port>/...` URLs without env-var coupling.
|
|
6
|
+
*
|
|
7
|
+
* Initialization order:
|
|
8
|
+
* 1. `setCurrentPort(port)` — explicit override (used by tests, or any
|
|
9
|
+
* code that has direct knowledge of the bound port).
|
|
10
|
+
* 2. `process.env.PORT` — fallback. The CLI (`src/cli.ts`) sets this
|
|
11
|
+
* before spawning the server process, so in normal operation this
|
|
12
|
+
* branch is taken and no explicit `setCurrentPort` call is needed.
|
|
13
|
+
*
|
|
14
|
+
* `getCurrentPort()` throws if neither source is available.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
let overridePort: number | null = null;
|
|
18
|
+
|
|
19
|
+
export function setCurrentPort(port: number): void {
|
|
20
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
21
|
+
throw new Error(`setCurrentPort: invalid port ${port}`);
|
|
22
|
+
}
|
|
23
|
+
overridePort = port;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function getCurrentPort(): number {
|
|
27
|
+
if (overridePort !== null) return overridePort;
|
|
28
|
+
const envPort = process.env["PORT"];
|
|
29
|
+
if (envPort !== undefined && envPort !== "") {
|
|
30
|
+
const n = Number(envPort);
|
|
31
|
+
if (Number.isInteger(n) && n > 0 && n <= 65535) return n;
|
|
32
|
+
}
|
|
33
|
+
throw new Error(
|
|
34
|
+
"Inspector server port not initialized: PORT env var is unset and setCurrentPort() has not been called",
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Reset for tests. */
|
|
39
|
+
export function _resetForTests(): void {
|
|
40
|
+
overridePort = null;
|
|
41
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/* eslint-disable functional/no-throw-statements */
|
|
2
|
+
/**
|
|
3
|
+
* HTTP loopback helper for MCP tool handlers.
|
|
4
|
+
*
|
|
5
|
+
* Why HTTP loopback (not direct function calls): see
|
|
6
|
+
* `openspec/changes/add-mcp-server/design.md` decision D2. All MCP tools
|
|
7
|
+
* delegate to existing `/api/*` endpoints so any future cross-cutting
|
|
8
|
+
* middleware (auth, rate-limit, audit, metrics) added to `/api` is
|
|
9
|
+
* automatically inherited by MCP without duplicate plumbing.
|
|
10
|
+
*
|
|
11
|
+
* NOTE: TanStack Start / Nitro may expose an in-process route invocation
|
|
12
|
+
* API (e.g. Nitro's `$fetch` helper) that would let us skip the real HTTP
|
|
13
|
+
* round-trip while preserving the routing contract. As of this writing
|
|
14
|
+
* that investigation is open (tasks.md 2.3). If/when adopted, the public
|
|
15
|
+
* surface of this module — `callApi(path, init?)` returning a `Response`
|
|
16
|
+
* — should stay identical so callers don't change.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { getCurrentPort } from "../lib/serverPort";
|
|
20
|
+
|
|
21
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
22
|
+
|
|
23
|
+
export type CallApiOptions = RequestInit & {
|
|
24
|
+
/** Override default 30s timeout. */
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export class LoopbackTimeoutError extends Error {
|
|
29
|
+
constructor(
|
|
30
|
+
public readonly path: string,
|
|
31
|
+
public readonly timeoutMs: number,
|
|
32
|
+
) {
|
|
33
|
+
super(`Loopback call to ${path} timed out after ${timeoutMs}ms`);
|
|
34
|
+
this.name = "LoopbackTimeoutError";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Make an HTTP request to one of the inspector's own /api/* endpoints
|
|
40
|
+
* via 127.0.0.1 loopback. The returned Response is a standard Web
|
|
41
|
+
* Response; callers decide whether to call .json(), .text(), .arrayBuffer().
|
|
42
|
+
*
|
|
43
|
+
* `path` MUST start with `/` (e.g. `/api/logs`).
|
|
44
|
+
*/
|
|
45
|
+
export async function callApi(path: string, options: CallApiOptions = {}): Promise<Response> {
|
|
46
|
+
if (!path.startsWith("/")) {
|
|
47
|
+
throw new Error(`callApi: path must start with '/', got: ${path}`);
|
|
48
|
+
}
|
|
49
|
+
const port = getCurrentPort();
|
|
50
|
+
const url = `http://127.0.0.1:${port}${path}`;
|
|
51
|
+
|
|
52
|
+
const { timeoutMs = DEFAULT_TIMEOUT_MS, signal: userSignal, ...rest } = options;
|
|
53
|
+
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);
|
|
56
|
+
|
|
57
|
+
// If caller passed their own signal, chain it.
|
|
58
|
+
if (userSignal !== undefined && userSignal !== null) {
|
|
59
|
+
if (userSignal.aborted) {
|
|
60
|
+
controller.abort();
|
|
61
|
+
} else {
|
|
62
|
+
userSignal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
try {
|
|
67
|
+
return await fetch(url, { ...rest, signal: controller.signal });
|
|
68
|
+
} catch (err) {
|
|
69
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
70
|
+
throw new LoopbackTimeoutError(path, timeoutMs);
|
|
71
|
+
}
|
|
72
|
+
throw err;
|
|
73
|
+
} finally {
|
|
74
|
+
clearTimeout(timeoutHandle);
|
|
75
|
+
}
|
|
76
|
+
}
|