feat: add v1 health, messages, and status endpoints

- Add /v1/health endpoint for service health checks
- Add /v1/messages endpoint for Anthropic Messages API
- Add /v1/status endpoint for service status
- Add planning docs for Claude Code sessions feature
This commit is contained in:
Zebratic committed 2026-03-12 05:20:46 +01:00
1 parent 8fc78cc6c2
commit c6b8a8a320
6 files changed
+793

No files matched your search

@@ -0,0 +1,76 @@
# Claude Code Sessions View - Design
## Overview
Add a new "Sessions" page to the dashboard that shows Claude Code sessions, displaying all previous sessions with their prompts and expandable tool call details.
## Data Storage
Extend the existing `debug_logs` collection with:
- `sessionId` - extracted from `x-anthropic-billing-header` (the `cch` value)
- `toolCalls` - array of tool call data
## UI/UX Design
### Route
`/dashboard/sessions`
### Navigation
Add "Sessions" nav item to dashboard sidebar (between Logs and Settings)
### Sessions List Page
Table showing all sessions:
- Session ID (truncated)
- First request time
- Last activity time
- Number of requests
- Model used
### Session Detail View
Click session to see:
- All requests in chronological order
- Each request shows:
- Timestamp
- Model
- User message preview (first 100 chars)
- Collapsed tool calls section (shows count badge)
- Click to expand tool calls:
- Tool name icon (color-coded by type)
- Tool type (Read, Edit, Write, WebFetch, etc.)
- Summary: file path for file ops, URL for web, etc.
- Expandable: full input/output JSON
### Color Coding for Tools
| Tool Type | Color | Examples |
|-----------|-------|----------|
| File Read | Blue | Read, Glob, Grep |
| File Write | Green | Edit, Write, WriteCreateFile, NotebookEdit |
| Web Fetch | Purple | WebFetch, WebSearch |
| Command | Orange | Bash, node |
| Info | Gray | TaskGet, TaskList, TodoWrite |
## Data Model
```typescript
interface ToolCall {
id: string;
name: string;
input: Record<string, unknown>;
output?: unknown;
status: "pending" | "success" | "error";
startedAt: Date;
completedAt?: Date;
}
interface DebugLogEntry {
// ... existing fields
sessionId?: string;
toolCalls?: ToolCall[];
}
```
## API Endpoints
1. `GET /api/dashboard/sessions` - List sessions grouped by sessionId
2. `GET /api/dashboard/sessions/[sessionId]` - Get session details with requests
@@ -0,0 +1,531 @@
# Claude Code Sessions Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Add a new "Sessions" page to the dashboard that shows Claude Code sessions with their prompts and expandable tool call details.
**Architecture:** Extend the existing debug_logs collection with sessionId and toolCalls fields. Create new API endpoints for session listing and details. Add UI pages for viewing sessions.
**Tech Stack:** Next.js App Router, MongoDB, Tailwind CSS, shadcn/ui components
---
### Task 1: Update Debug Log to Capture Session ID and Tool Calls
**Files:**
- Modify: `src/server/services/debug-logger.ts`
- Modify: `src/server/services/anthropic-messages-handler.ts`
- Modify: `src/server/services/request-handler.ts`
**Step 1: Update DebugLogEntry interface to add sessionId and toolCalls fields**
```typescript
// In src/server/services/debug-logger.ts, add to DebugLogEntry:
export interface ToolCall {
id: string;
name: string;
input: Record<string, unknown>;
output?: unknown;
status: "pending" | "success" | "error";
startedAt: Date;
completedAt?: Date;
}
export interface DebugLogEntry {
// ... existing fields
sessionId?: string;
toolCalls?: ToolCall[];
}
```
**Step 2: Extract session ID from x-anthropic-billing-header in debug-logger.ts**
Add a function to extract session ID:
```typescript
export function extractSessionId(request: Request): string | undefined {
const billingHeader = request.headers.get("x-anthropic-billing-header");
if (!billingHeader) return undefined;
// Parse cch=value from header like "cc_version=2.1.70...;cc_entrypoint=cli;cch=1167f;"
const match = billingHeader.match(/cch=([^;]+)/);
return match ? match[1] : undefined;
}
```
**Step 3: Pass sessionId when calling logDebugEntry in anthropic-messages-handler.ts**
In the debug logging section, add:
```typescript
const sessionId = extractSessionId(request);
```
And include in logDebugEntry call:
```typescript
logDebugEntry({
// ... existing fields
sessionId,
toolCalls: [], // Will be populated from response
// ...
})
```
**Step 4: Extract tool calls from response in anthropic-messages-handler.ts**
When the response contains tool_calls, extract them:
```typescript
// After getting result from provider
const toolCalls: ToolCall[] = [];
if (result.choices[0]?.message.tool_calls) {
for (const tc of result.choices[0].message.tool_calls) {
toolCalls.push({
id: tc.id,
name: tc.function.name,
input: JSON.parse(tc.function.arguments),
status: "success",
startedAt: new Date(),
completedAt: new Date(),
});
}
}
```
**Step 5: Commit**
---
### Task 2: Create API Endpoints for Sessions
**Files:**
- Create: `src/app/api/dashboard/sessions/route.ts`
- Create: `src/app/api/dashboard/sessions/[sessionId]/route.ts`
**Step 1: Create GET endpoint for listing sessions**
```typescript
// src/app/api/dashboard/sessions/route.ts
import { getSession } from "@/lib/auth";
import { getMongoDb } from "@/lib/mongo";
import { NextResponse } from "next/server";
export async function GET() {
const session = await getSession();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const db = getMongoDb();
// Group by sessionId and get session summaries
const sessions = await db.collection("debug_logs").aggregate([
{ $match: { userId: session.user.id, sessionId: { $exists: true, $ne: null } } },
{ $sort: { timestamp: -1 } },
{
$group: {
_id: "$sessionId",
firstRequest: { $first: "$timestamp" },
lastRequest: { $last: "$timestamp" },
requestCount: { $sum: 1 },
model: { $first: "$originalModel" },
}
},
{ $sort: { lastRequest: -1 } },
{ $limit: 50 }
]).toArray();
return NextResponse.json({ data: sessions });
}
```
**Step 2: Create GET endpoint for session details**
```typescript
// src/app/api/dashboard/sessions/[sessionId]/route.ts
import { getSession } from "@/lib/auth";
import { getMongoDb } from "@/lib/mongo";
import { NextResponse } from "next/server";
export async function GET(request: Request, { params }: { params: { sessionId: string } }) {
const session = await getSession();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const db = getMongoDb();
const sessionId = params.sessionId;
const logs = await db.collection("debug_logs")
.find({ userId: session.user.id, sessionId })
.sort({ timestamp: 1 })
.toArray();
return NextResponse.json({ data: logs });
}
```
**Step 3: Commit**
---
### Task 3: Add Sessions Page to Dashboard
**Files:**
- Create: `src/app/dashboard/sessions/page.tsx`
- Create: `src/app/dashboard/sessions/[sessionId]/page.tsx`
**Step 1: Create sessions list page**
```typescript
// src/app/dashboard/sessions/page.tsx
"use client";
import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ChevronRight } from "lucide-react";
import Link from "next/link";
interface Session {
_id: string;
firstRequest: string;
lastRequest: string;
requestCount: number;
model: string;
}
export default function SessionsPage() {
const [sessions, setSessions] = useState<Session[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("/api/dashboard/sessions")
.then((res) => res.json())
.then((data) => {
setSessions(data.data || []);
setLoading(false);
})
.catch(() => setLoading(false));
}, []);
return (
<div className="space-y-6">
<div>
<h1 className="text-xl font-bold sm:text-2xl">Claude Code Sessions</h1>
<p className="text-sm text-muted-foreground">View your Claude Code session history</p>
</div>
<Card>
<CardHeader>
<CardTitle>Sessions</CardTitle>
</CardHeader>
<CardContent>
{loading ? (
<p className="text-sm text-muted-foreground">Loading...</p>
) : sessions.length === 0 ? (
<p className="text-sm text-muted-foreground">No sessions found.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Session</TableHead>
<TableHead>First Request</TableHead>
<TableHead>Last Activity</TableHead>
<TableHead>Requests</TableHead>
<TableHead>Model</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{sessions.map((sess) => (
<TableRow key={sess._id}>
<TableCell className="font-mono text-xs">{sess._id}</TableCell>
<TableCell className="text-sm">{new Date(sess.firstRequest).toLocaleString()}</TableCell>
<TableCell className="text-sm">{new Date(sess.lastRequest).toLocaleString()}</TableCell>
<TableCell>
<Badge variant="secondary">{sess.requestCount}</Badge>
</TableCell>
<TableCell className="text-sm">{sess.model}</TableCell>
<TableCell>
<Link href={`/dashboard/sessions/${sess._id}`}>
<Button size="sm" variant="ghost">
<ChevronRight className="h-4 w-4" />
</Button>
</Link>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
);
}
```
**Step 2: Create session detail page with expandable tool calls**
```typescript
// src/app/dashboard/sessions/[sessionId]/page.tsx
"use client";
import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ChevronDown, ChevronRight, FileText, Edit, Globe, Terminal, Info } from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
interface DebugLog {
id: string;
timestamp: string;
originalModel: string;
requestBody: {
messages?: Array<{ role: string; content: string }>;
tools?: Array<{ function: { name: string; description: string } }>;
};
providerResponse?: {
body: {
choices?: Array<{
message?: {
content?: string;
tool_calls?: Array<{
id: string;
function: { name: string; arguments: string };
}>;
};
}>;
};
};
toolCalls?: Array<{
id: string;
name: string;
input: Record<string, unknown>;
output?: unknown;
status: string;
}>;
}
const toolIcons: Record<string, React.ComponentType<{ className?: string }>> = {
Read: FileText,
Glob: FileText,
Grep: FileText,
Edit: Edit,
Write: Edit,
WriteCreateFile: Edit,
WebFetch: Globe,
WebSearch: Globe,
Bash: Terminal,
node: Terminal,
default: Info,
};
const toolColors: Record<string, string> = {
Read: "text-blue-500",
Glob: "text-blue-500",
Grep: "text-blue-500",
Edit: "text-green-500",
Write: "text-green-500",
WriteCreateFile: "text-green-500",
WebFetch: "text-purple-500",
WebSearch: "text-purple-500",
Bash: "text-orange-500",
node: "text-orange-500",
};
function getToolSummary(name: string, input: Record<string, unknown>): string {
if (name === "Read" || name === "Glob" || name === "Grep") {
return input.file_path?.toString() || input.path?.toString() || "Unknown file";
}
if (name === "Write" || name === "WriteCreateFile" || name === "Edit") {
return input.file_path?.toString() || "Unknown file";
}
if (name === "WebFetch" || name === "WebSearch") {
return input.url?.toString() || input.query?.toString() || "Unknown";
}
if (name === "Bash" || name === "node") {
return input.command?.toString() || "Unknown command";
}
return "View details";
}
export default function SessionDetailPage() {
const params = useParams();
const [logs, setLogs] = useState<DebugLog[]>([]);
const [loading, setLoading] = useState(true);
const [expandedRequest, setExpandedRequest] = useState<string | null>(null);
const [expandedTool, setExpandedTool] = useState<string | null>(null);
useEffect(() => {
fetch(`/api/dashboard/sessions/${params.sessionId}`)
.then((res) => res.json())
.then((data) => {
setLogs(data.data || []);
setLoading(false);
})
.catch(() => setLoading(false));
}, [params.sessionId]);
// Extract tool calls from provider response
const getToolCalls = (log: DebugLog) => {
const response = log.providerResponse?.body as any;
return response?.choices?.[0]?.message?.tool_calls || [];
};
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<Link href="/dashboard/sessions">
<Button variant="ghost" size="sm">Back</Button>
</Link>
<div>
<h1 className="text-xl font-bold sm:text-2xl">Session Details</h1>
<p className="text-sm text-muted-foreground font-mono">{params.sessionId}</p>
</div>
</div>
<div className="space-y-4">
{loading ? (
<p className="text-sm text-muted-foreground">Loading...</p>
) : logs.length === 0 ? (
<p className="text-sm text-muted-foreground">No requests in this session.</p>
) : (
logs.map((log) => {
const toolCalls = getToolCalls(log);
const isExpanded = expandedRequest === log.id;
return (
<Card key={log.id}>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Button
variant="ghost"
size="sm"
onClick={() => setExpandedRequest(isExpanded ? null : log.id)}
>
{isExpanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</Button>
<div>
<CardTitle className="text-base">{new Date(log.timestamp).toLocaleString()}</CardTitle>
<p className="text-sm text-muted-foreground">{log.originalModel}</p>
</div>
</div>
{toolCalls.length > 0 && (
<Badge variant="secondary">{toolCalls.length} tool calls</Badge>
)}
</div>
</CardHeader>
{isExpanded && (
<CardContent className="space-y-4">
{/* User messages */}
<div>
<h4 className="text-sm font-medium mb-2">Messages</h4>
<div className="space-y-2">
{log.requestBody.messages?.slice(-3).map((msg, i) => (
<div key={i} className={`p-2 rounded text-sm ${
msg.role === "user" ? "bg-muted" : "bg-muted/50"
}`}>
<span className="font-medium">{msg.role}:</span>{" "}
{typeof msg.content === "string"
? msg.content.slice(0, 200)
: "..."}
</div>
))}
</div>
</div>
{/* Tool calls */}
{toolCalls.length > 0 && (
<div>
<h4 className="text-sm font-medium mb-2">Tool Calls</h4>
<div className="space-y-2">
{toolCalls.map((tc) => {
const Icon = toolIcons[tc.function.name] || toolIcons.default;
const colorClass = toolColors[tc.function.name] || "text-gray-500";
const summary = getToolSummary(tc.function.name, JSON.parse(tc.function.arguments || "{}"));
const isToolExpanded = expandedTool === tc.id;
return (
<div key={tc.id} className="border rounded-md">
<div
className="flex items-center gap-2 p-2 cursor-pointer hover:bg-muted"
onClick={() => setExpandedTool(isToolExpanded ? null : tc.id)}
>
<Icon className={`h-4 w-4 ${colorClass}`} />
<span className="font-medium text-sm">{tc.function.name}</span>
<span className="text-sm text-muted-foreground">- {summary}</span>
{isToolExpanded ? (
<ChevronDown className="h-3 w-3 ml-auto" />
) : (
<ChevronRight className="h-3 w-3 ml-auto" />
)}
</div>
{isToolExpanded && (
<div className="p-2 border-t bg-muted/30">
<pre className="text-xs overflow-x-auto">
{JSON.stringify(JSON.parse(tc.function.arguments || "{}"), null, 2)}
</pre>
</div>
)}
</div>
);
})}
</div>
</div>
)}
</CardContent>
)}
</Card>
);
})
)}
</div>
</div>
);
}
```
**Step 3: Commit**
---
### Task 4: Add Sessions to Sidebar Navigation
**Files:**
- Modify: `src/components/layout/sidebar.tsx`
**Step 1: Add Sessions nav item**
In the dashboardNav array, add:
```typescript
{ label: "Sessions", href: "/dashboard/sessions", icon: MessageSquareCode },
```
Import the icon:
```typescript
import { ..., MessageSquareCode } from "lucide-react";
```
**Step 2: Commit**
---
### Task 5: Build and Test
**Step 1: Run build**
```bash
npm run build
```
**Step 2: Fix any TypeScript errors**
**Step 3: Commit**
---
**Plan complete!**
+128
View File
@@ -0,0 +1,128 @@
#!/bin/bash
#
# Claude Code Setup Script
# Usage: ./scripts/claude-code-setup.sh <PROXY_URL> <TOKEN>
#
# This script configures Claude Code to use your LLM proxy instead of Anthropic API.
#
# Arguments:
# PROXY_URL: The base URL of your LLM proxy (e.g., https://your-proxy.com)
# TOKEN: Your API key from the proxy
#
# Example:
# ./scripts/claude-code-setup.sh https://api.yourdomain.com sk-your-api-key
#
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Function to print colored output
print_status() {
echo -e "${GREEN}[✓]${NC} $1"
}
print_error() {
echo -e "${RED}[✗]${NC} $1"
}
print_info() {
echo -e "${YELLOW}[i]${NC} $1"
}
# Check arguments
if [ $# -ne 2 ]; then
echo "Usage: $0 <PROXY_URL> <TOKEN>"
echo ""
echo "Arguments:"
echo " PROXY_URL The base URL of your LLM proxy (e.g., https://your-proxy.com)"
echo " TOKEN Your API key from the proxy"
echo ""
echo "Example:"
echo " $0 https://api.yourdomain.com sk-your-api-key"
exit 1
fi
PROXY_URL="$1"
TOKEN="$2"
print_info "Testing /status endpoint..."
STATUS_CODE=$(curl -s -o /dev/null -w "%{http_code}" "${PROXY_URL}/status")
if [ "$STATUS_CODE" = "200" ]; then
print_status "Service is up (status endpoint returned 200)"
else
print_error "Service check failed (status endpoint returned $STATUS_CODE)"
exit 1
fi
print_info "Testing /health endpoint with token..."
HEALTH_CODE=$(curl -s -o /dev/null -w "%{http_code}" -H "x-api-key: ${TOKEN}" "${PROXY_URL}/health")
if [ "$HEALTH_CODE" = "200" ]; then
print_status "Token is valid (health endpoint returned 200)"
else
print_error "Token validation failed (health endpoint returned $HEALTH_CODE)"
exit 1
fi
print_info "Testing chat completions through proxy..."
CHAT_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
-X POST "${PROXY_URL}/v1/chat/completions" \
-H "Authorization: Bearer ${TOKEN}" \
-H "Content-Type: application/json" \
-d '{"model":"claude-3-5-sonnet-20241022","messages":[{"role":"user","content":"Hello"}],"max_tokens":10}')
if [ "$CHAT_CODE" = "200" ]; then
print_status "Chat completions working (returned 200)"
else
print_error "Chat completions test failed (returned $CHAT_CODE)"
exit 1
fi
print_info "Creating Claude Code settings..."
# Create settings directory if it doesn't exist
SETTINGS_DIR="$HOME/.claude"
mkdir -p "$SETTINGS_DIR"
# Create settings.json with proxy configuration
SETTINGS_FILE="$SETTINGS_DIR/settings.json"
# Create backup if file exists
if [ -f "$SETTINGS_FILE" ]; then
BACKUP_FILE="$SETTINGS_FILE.backup.$(date +%Y%m%d_%H%M%S)"
cp "$SETTINGS_FILE" "$BACKUP_FILE"
print_info "Backed up existing settings to $BACKUP_FILE"
fi
# Write new settings
cat > "$SETTINGS_FILE" << EOF
{
"ANTHROPIC_BASE_URL": "${PROXY_URL}/v1",
"ANTHROPIC_AUTH_TOKEN": "${TOKEN}",
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "true",
"API_TIMEOUT_MS": "300000",
"MODEL_PREferences": {
"haiku": "claude-3-haiku-20240307",
"sonnet": "claude-3-5-sonnet-20241022",
"opus": "claude-3-opus-20240229"
}
}
EOF
print_status "Settings written to $SETTINGS_FILE"
print_info ""
print_info "Claude Code is now configured to use your proxy!"
print_info ""
print_info "Configuration:"
print_info " Proxy URL: ${PROXY_URL}"
print_info " Models:"
print_info " - Haiku: claude-3-haiku-20240307"
print_info " - Sonnet: claude-3-5-sonnet-20241022"
print_info " - Opus: claude-3-opus-20240229"
print_info ""
print_info "You can now use Claude Code with your proxy. If Claude Code was running,"
print_info "you may need to restart it for the changes to take effect."
+33
View File
@@ -0,0 +1,33 @@
import { NextResponse } from "next/server";
import { authenticateApiKey } from "@/server/services/api-key-auth";
// GET /v1/health - Token validation endpoint for Claude Code
// Validates API key via x-api-key header
export async function GET(request: Request) {
const apiKey = request.headers.get("x-api-key");
if (!apiKey) {
return NextResponse.json(
{ error: { message: "Missing x-api-key header", type: "invalid_request_error" } },
{ status: 401 }
);
}
// Use Bearer token format for authentication check
const auth = await authenticateApiKey(`Bearer ${apiKey}`);
if (!auth) {
return NextResponse.json(
{ error: { message: "Invalid API key", type: "invalid_request_error" } },
{ status: 401 }
);
}
return NextResponse.json({
status: "ok",
user: {
id: auth.user.id,
email: auth.user.email,
},
});
}
+18
View File
@@ -0,0 +1,18 @@
import { handleAnthropicMessages } from "@/server/services/anthropic-messages-handler";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request): Promise<Response> {
return handleAnthropicMessages(request);
}
export async function GET(): Promise<Response> {
return new Response(JSON.stringify({
anthropic_version: "2023-06-01",
messages: []
}), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
+7
View File
@@ -0,0 +1,7 @@
import { NextResponse } from "next/server";
// GET /v1/status - Health check endpoint for Claude Code
// Returns 200 if service is up
export async function GET() {
return NextResponse.json({ status: "ok" });
}