diff --git a/docs/plans/2026-03-12-claude-code-sessions-design.md b/docs/plans/2026-03-12-claude-code-sessions-design.md new file mode 100644 index 0000000..f48ff1b --- /dev/null +++ b/docs/plans/2026-03-12-claude-code-sessions-design.md @@ -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; + 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 diff --git a/docs/plans/2026-03-12-claude-code-sessions-implementation.md b/docs/plans/2026-03-12-claude-code-sessions-implementation.md new file mode 100644 index 0000000..09f6e63 --- /dev/null +++ b/docs/plans/2026-03-12-claude-code-sessions-implementation.md @@ -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; + 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([]); + 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 ( +
+
+

Claude Code Sessions

+

View your Claude Code session history

+
+ + + + Sessions + + + {loading ? ( +

Loading...

+ ) : sessions.length === 0 ? ( +

No sessions found.

+ ) : ( + + + + Session + First Request + Last Activity + Requests + Model + + + + + {sessions.map((sess) => ( + + {sess._id} + {new Date(sess.firstRequest).toLocaleString()} + {new Date(sess.lastRequest).toLocaleString()} + + {sess.requestCount} + + {sess.model} + + + + + + + ))} + +
+ )} +
+
+
+ ); +} +``` + +**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; + output?: unknown; + status: string; + }>; +} + +const toolIcons: Record> = { + 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 = { + 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 { + 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([]); + const [loading, setLoading] = useState(true); + const [expandedRequest, setExpandedRequest] = useState(null); + const [expandedTool, setExpandedTool] = useState(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 ( +
+
+ + + +
+

Session Details

+

{params.sessionId}

+
+
+ +
+ {loading ? ( +

Loading...

+ ) : logs.length === 0 ? ( +

No requests in this session.

+ ) : ( + logs.map((log) => { + const toolCalls = getToolCalls(log); + const isExpanded = expandedRequest === log.id; + + return ( + + +
+
+ +
+ {new Date(log.timestamp).toLocaleString()} +

{log.originalModel}

+
+
+ {toolCalls.length > 0 && ( + {toolCalls.length} tool calls + )} +
+
+ {isExpanded && ( + + {/* User messages */} +
+

Messages

+
+ {log.requestBody.messages?.slice(-3).map((msg, i) => ( +
+ {msg.role}:{" "} + {typeof msg.content === "string" + ? msg.content.slice(0, 200) + : "..."} +
+ ))} +
+
+ + {/* Tool calls */} + {toolCalls.length > 0 && ( +
+

Tool Calls

+
+ {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 ( +
+
setExpandedTool(isToolExpanded ? null : tc.id)} + > + + {tc.function.name} + - {summary} + {isToolExpanded ? ( + + ) : ( + + )} +
+ {isToolExpanded && ( +
+
+                                      {JSON.stringify(JSON.parse(tc.function.arguments || "{}"), null, 2)}
+                                    
+
+ )} +
+ ); + })} +
+
+ )} +
+ )} +
+ ); + }) + )} +
+
+ ); +} +``` + +**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!** diff --git a/scripts/claude-code-setup.sh b/scripts/claude-code-setup.sh new file mode 100755 index 0000000..0882079 --- /dev/null +++ b/scripts/claude-code-setup.sh @@ -0,0 +1,128 @@ +#!/bin/bash +# +# Claude Code Setup Script +# Usage: ./scripts/claude-code-setup.sh +# +# 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 " + 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." diff --git a/src/app/v1/health/route.ts b/src/app/v1/health/route.ts new file mode 100644 index 0000000..263681a --- /dev/null +++ b/src/app/v1/health/route.ts @@ -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, + }, + }); +} diff --git a/src/app/v1/messages/route.ts b/src/app/v1/messages/route.ts new file mode 100644 index 0000000..1293a09 --- /dev/null +++ b/src/app/v1/messages/route.ts @@ -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 { + return handleAnthropicMessages(request); +} + +export async function GET(): Promise { + return new Response(JSON.stringify({ + anthropic_version: "2023-06-01", + messages: [] + }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); +} diff --git a/src/app/v1/status/route.ts b/src/app/v1/status/route.ts new file mode 100644 index 0000000..eb6ca66 --- /dev/null +++ b/src/app/v1/status/route.ts @@ -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" }); +}