Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

Add full-stack codebase chat interface with agentic tool use and streaming

RaghavChamadiya3435385197ca
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 57f5bba68..e1dadd1ec 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -34,10 +34,11 @@ For per-package detail (installation, full API reference, all CLI flags, file ma
9. [Decision Intelligence](#9-decision-intelligence)
10. [MCP Server](#10-mcp-server)
11. [REST API and Web UI](#11-rest-api-and-web-ui)
-12. [Data Flow Diagrams](#12-data-flow-diagrams)
-13. [Key Design Decisions](#13-key-design-decisions)
-14. [Adding a New Language](#14-adding-a-new-language)
-15. [Adding a New LLM Provider](#15-adding-a-new-llm-provider)
+12. [Codebase Chat](#12-codebase-chat)
+13. [Data Flow Diagrams](#13-data-flow-diagrams)
+14. [Key Design Decisions](#14-key-design-decisions)
+15. [Adding a New Language](#15-adding-a-new-language)
+16. [Adding a New LLM Provider](#16-adding-a-new-llm-provider)
---
@@ -1033,7 +1034,37 @@ file, tokens used, estimated cost, estimated time remaining).
---
-## 12. Data Flow Diagrams
+## 12. Codebase Chat
+
+WikiCode includes an interactive chat interface that lets users ask questions about
+their codebase and receive answers grounded in the wiki, dependency graph, git
+history, and architectural decisions. The chat agent uses whichever LLM provider
+the user has configured and has access to all 8 MCP tools.
+
+See [`docs/CHAT.md`](CHAT.md) for the full technical reference covering the
+backend agentic loop, SSE streaming protocol, provider abstraction extensions,
+database schema, frontend component architecture, and artifact rendering system.
+
+**Key design points:**
+
+- **Provider-agnostic** — the chat agent goes through the same provider abstraction
+ as documentation generation. A `ChatProvider` protocol extends `BaseProvider` with
+ `stream_chat()` for streaming + tool use without breaking existing callers.
+- **Tool reuse** — the 8 MCP tools are called directly as Python functions (no
+ subprocess round-trip). Tool schemas are defined once in `chat_tools.py` and
+ fed to both the LLM and the executor.
+- **SSE streaming** — `POST /api/repos/{repo_id}/chat/messages` runs the agentic
+ loop and streams back Server-Sent Events (`text_delta`, `tool_start`,
+ `tool_result`, `done`, `error`).
+- **Conversation persistence** — chat history is stored in `conversations` and
+ `chat_messages` tables, allowing replay and continuation across page refreshes.
+- **Artifact panel** — tool results with rich content (wiki pages, Mermaid diagrams,
+ search results, risk reports) open in a slide-in artifact panel that reuses
+ existing frontend components.
+
+---
+
+## 13. Data Flow Diagrams
### Init flow
@@ -1183,7 +1214,7 @@ instead of reading 40 files
---
-## 13. Key Design Decisions
+## 14. Key Design Decisions
### Three-layer folder exclusion, not one monolithic list
@@ -1311,7 +1342,7 @@ and the vector store embed (LanceDB or pgvector) can overlap with the next file'
---
-## 14. Adding a New Language
+## 15. Adding a New Language
1. **Write `packages/core/queries/<language>.scm`**
@@ -1353,7 +1384,7 @@ and the vector store embed (LanceDB or pgvector) can overlap with the next file'
---
-## 15. Adding a New LLM Provider
+## 16. Adding a New LLM Provider
1. **Create `packages/core/providers/<name>.py`**
diff --git a/docs/CHAT.md b/docs/CHAT.md
new file mode 100644
index 000000000..c18f0df31
--- /dev/null
+++ b/docs/CHAT.md
@@ -0,0 +1,373 @@
+# Codebase Chat — Technical Reference
+
+The codebase chat feature lets users have an interactive conversation with their
+codebase. The agent uses whichever LLM provider the user has configured, has
+access to all 8 MCP tools, and streams responses back to the browser in real time
+showing tool calls as they happen and rendering results in an artifact panel.
+
+---
+
+## Table of Contents
+
+1. [Architecture Overview](#1-architecture-overview)
+2. [Database Schema](#2-database-schema)
+3. [ChatProvider Protocol](#3-chatprovider-protocol)
+4. [Tool Registry](#4-tool-registry)
+5. [Provider Configuration](#5-provider-configuration)
+6. [SSE Streaming Protocol](#6-sse-streaming-protocol)
+7. [Agentic Loop](#7-agentic-loop)
+8. [REST API Endpoints](#8-rest-api-endpoints)
+9. [Frontend Architecture](#9-frontend-architecture)
+10. [Provider-Specific Notes](#10-provider-specific-notes)
+
+---
+
+## 1. Architecture Overview
+
+```
+User types question
+ |
+ v
+POST /api/repos/{repo_id}/chat/messages
+ |
+ v
++------ Chat Router (SSE stream) ------+
+| |
+| 1. Create/load conversation |
+| 2. Save user message to DB |
+| 3. Build LLM message history |
+| 4. Call provider.stream_chat() <----+---- tool_executor callback
+| | |
+| v |
+| 5. Stream text_delta events -------> SSE to browser
+| 6. On tool_start: |
+| - Execute tool (or provider |
+| executes internally) |
+| - Emit tool_result event -------> SSE to browser
+| 7. If tool calls found: |
+| - Append to history, loop to 4 |
+| 8. If no tool calls: |
+| - Save assistant message to DB |
+| - Emit done event |
++---------------------------------------+
+```
+
+The agentic loop is in the chat router for most providers (OpenAI, Anthropic,
+Ollama, LiteLLM). For Gemini, the loop runs inside `stream_chat()` using native
+Content objects to preserve thought signatures. The router passes a
+`tool_executor` callback that Gemini calls internally.
+
+---
+
+## 2. Database Schema
+
+Two tables added in migration `0005_chat_conversations.py`:
+
+### `conversations`
+
+| Column | Type | Notes |
+|--------|------|-------|
+| `id` | `String(32)` PK | UUID hex |
+| `repository_id` | `String(32)` FK | CASCADE delete |
+| `title` | `Text` | Auto-generated from first 6 words |
+| `created_at` | `DateTime(tz)` | |
+| `updated_at` | `DateTime(tz)` | Auto-updated on new messages |
+
+**Index:** `ix_conversations_repo_updated` on `(repository_id, updated_at)`
+
+### `chat_messages`
+
+| Column | Type | Notes |
+|--------|------|-------|
+| `id` | `String(32)` PK | UUID hex |
+| `conversation_id` | `String(32)` FK | CASCADE delete |
+| `role` | `String(32)` | `user` or `assistant` |
+| `content_json` | `Text` | JSON blob (see below) |
+| `created_at` | `DateTime(tz)` | |
+
+**Index:** `ix_chat_messages_conv_created` on `(conversation_id, created_at)`
+
+### Message content format
+
+**User messages:**
+```json
+{"text": "What does the auth module do?"}
+```
+
+**Assistant messages:**
+```json
+{
+ "text": "The auth module handles...",
+ "tool_calls": [
+ {
+ "id": "call_abc123",
+ "name": "get_context",
+ "arguments": {"targets": ["src/auth"]},
+ "result": { ... }
+ }
+ ]
+}
+```
+
+---
+
+## 3. ChatProvider Protocol
+
+Defined in `packages/core/src/wikicode/core/providers/base.py`.
+
+The existing `BaseProvider.generate()` is untouched. A new `ChatProvider`
+protocol class (using `typing.Protocol` + `@runtime_checkable`) adds streaming
+chat with tool use as an opt-in capability.
+
+```python
+@runtime_checkable
+class ChatProvider(Protocol):
+ def stream_chat(
+ self,
+ messages: list[dict], # OpenAI-format message list
+ tools: list[dict], # OpenAI-format tool definitions
+ system_prompt: str,
+ max_tokens: int = 8192,
+ temperature: float = 0.7,
+ request_id: str | None = None,
+ tool_executor: Any | None = None, # async callable(name, args) -> dict
+ ) -> AsyncIterator[ChatStreamEvent]: ...
+```
+
+**Supporting dataclasses:**
+
+- `ChatToolCall(id, name, arguments)` — a tool call the LLM wants to make
+- `ChatStreamEvent(type, text?, tool_call?, tool_result_data?, stop_reason?, input_tokens, output_tokens)` — a single event in the stream
+
+**Event types:**
+
+| `type` | Populated fields | Meaning |
+|--------|-----------------|---------|
+| `text_delta` | `text` | Incremental text token(s) |
+| `tool_start` | `tool_call` | LLM wants to call a tool |
+| `tool_result` | `tool_call`, `tool_result_data` | Tool executed (by provider internally) |
+| `usage` | `input_tokens`, `output_tokens` | Token usage update |
+| `stop` | `stop_reason` | Generation ended (`end_turn`, `tool_use`, `max_tokens`) |
+
+**Implementations:** Anthropic, OpenAI, Gemini, Ollama, LiteLLM. All accept the
+`tool_executor` parameter; only Gemini uses it (for thought signature handling).
+
+---
+
+## 4. Tool Registry
+
+Defined in `packages/server/src/wikicode/server/chat_tools.py`.
+
+Single source of truth for tool schemas and execution. Imports the 8 MCP tool
+functions directly from `wikicode.server.mcp_server`.
+
+```python
+TOOL_REGISTRY: dict[str, ToolDef] # name -> ToolDef(name, description, parameters, function, artifact_type)
+```
+
+**Key functions:**
+
+| Function | Purpose |
+|----------|---------|
+| `get_tool_schemas_for_llm()` | Returns OpenAI-format tool definitions for the LLM |
+| `execute_tool(name, args)` | Runs a tool and ensures JSON-serializable output |
+| `get_artifact_type(name)` | Maps tool name to frontend artifact type |
+| `init_tool_state(...)` | Bridges FastAPI app state to MCP module globals |
+
+**Tool to artifact type mapping:**
+
+| Tool | Artifact Type |
+|------|--------------|
+| `get_overview` | `overview` |
+| `get_context` | `wiki_page` |
+| `get_risk` | `risk_report` |
+| `get_why` | `decisions` |
+| `search_codebase` | `search_results` |
+| `get_dependency_path` | `graph` |
+| `get_dead_code` | `dead_code` |
+| `get_architecture_diagram` | `diagram` |
+
+---
+
+## 5. Provider Configuration
+
+Defined in `packages/server/src/wikicode/server/provider_config.py`.
+
+API keys and active provider/model selection are stored in a server-side
+`provider_config.json` file. Environment variables take precedence over stored
+keys.
+
+**Resolution order for API keys:**
+1. Environment variable (e.g. `GEMINI_API_KEY`, `ANTHROPIC_API_KEY`)
+2. Stored key in `provider_config.json`
+
+**Active provider resolution:**
+1. Explicitly set via `PATCH /api/providers/active`
+2. Auto-detect from first configured provider
+
+**Provider catalog:** Gemini, Anthropic, OpenAI, Ollama (local, no key), LiteLLM.
+
+---
+
+## 6. SSE Streaming Protocol
+
+The chat endpoint returns `Content-Type: text/event-stream`. Each event is:
+
+```
+event: data
+data: {"type": "...", ...}
+
+```
+
+**Event shapes:**
+
+```jsonc
+// Incremental text from the LLM
+{"type": "text_delta", "text": "The auth module..."}
+
+// LLM wants to call a tool
+{"type": "tool_start", "tool_id": "call_123", "tool_name": "get_context", "input": {"targets": ["src/auth"]}}
+
+// Tool execution completed
+{"type": "tool_result", "tool_id": "call_123", "tool_name": "get_context", "summary": "Context for 1 target(s)", "artifact": {"type": "wiki_page", "data": {...}}}
+
+// Stream complete
+{"type": "done", "conversation_id": "abc123", "message_id": "def456"}
+
+// Error
+{"type": "error", "message": "Provider error: ..."}
+```
+
+**Headers:** `Cache-Control: no-cache`, `X-Accel-Buffering: no`, `Connection: keep-alive`
+
+**Retry:** `retry: 3000` sent at stream start.
+
+---
+
+## 7. Agentic Loop
+
+The loop runs up to 10 iterations per request.
+
+```
+for each iteration:
+ 1. Call provider.stream_chat(messages, tools, system_prompt, tool_executor)
+ 2. Collect text_delta events -> stream to client
+ 3. Collect tool_start events -> stream to client
+ 4. Collect tool_result events (from internal execution) -> stream to client
+ 5. If there are pending tool calls (not internally executed):
+ a. Execute each tool
+ b. Emit tool_result to client
+ c. Append assistant + tool results to message history
+ d. Continue loop
+ 6. If no tool calls: break
+```
+
+After the loop, the assistant message (text + all tool calls with results) is
+saved to the database and a `done` event is emitted.
+
+---
+
+## 8. REST API Endpoints
+
+### Chat
+
+| Method | Path | Description |
+|--------|------|-------------|
+| `POST` | `/api/repos/{repo_id}/chat/messages` | SSE stream — send a message and get a streaming response |
+| `GET` | `/api/repos/{repo_id}/chat/conversations` | List conversations for a repo |
+| `GET` | `/api/repos/{repo_id}/chat/conversations/{id}` | Get conversation with all messages |
+| `DELETE` | `/api/repos/{repo_id}/chat/conversations/{id}` | Delete a conversation |
+
+**POST body:**
+```json
+{
+ "message": "What does the auth module do?",
+ "conversation_id": null,
+ "provider": null,
+ "model": null
+}
+```
+
+`conversation_id` — omit or `null` to start a new conversation.
+`provider` / `model` — optional per-request overrides.
+
+### Providers
+
+| Method | Path | Description |
+|--------|------|-------------|
+| `GET` | `/api/providers` | List all providers with status and active selection |
+| `PATCH` | `/api/providers/active` | Set active provider and model |
+| `POST` | `/api/providers/{id}/key` | Store an API key |
+| `DELETE` | `/api/providers/{id}/key` | Remove an API key |
+
+---
+
+## 9. Frontend Architecture
+
+### API Layer (`src/lib/api/`)
+
+- `chat.ts` — `listConversations`, `getConversation`, `deleteConversation`, `postChatMessage` (returns raw Response for SSE reading)
+- `providers.ts` — `getProviders`, `setActiveProvider`, `addProviderKey`, `removeProviderKey`
+
+### Hooks (`src/lib/hooks/`)
+
+- `useChat(repoId)` — full chat state machine. Uses `fetch` + `ReadableStream` (not `EventSource`, which is GET-only). Manages messages, streaming state, conversation ID, error handling, and abort control. Exposes `sendMessage`, `loadConversation`, `reset`.
+- `useProviders()` — SWR wrapper for provider management. Exposes `providers`, `activeProvider`, `activeModel`, `activate`, `saveKey`, `removeKey`.
+
+### Components (`src/components/chat/`)
+
+| Component | Purpose |
+|-----------|---------|
+| `ChatInterface` | Main container — empty state (greeting + suggestions + model selector) and active state (message list + input) |
+| `ChatMessage` | Renders user bubble or assistant message (tool blocks + markdown) |
+| `ChatMarkdown` | Client-side markdown renderer using `react-markdown` + `remark-gfm` with design token styling |
+| `ToolCallBlock` | Inline tool call visualization — running (spinner), done collapsed (checkmark + summary), done expanded (input/output JSON) |
+| `ArtifactPanel` | Right slide-in panel with tabs for multiple artifacts. Renders by type: markdown, Mermaid diagrams, search results, raw JSON |
+| `ModelSelector` | Compact popover for switching provider/model and adding API keys inline |
+| `ConversationHistory` | Dropdown listing past conversations with delete and new-conversation actions |
+
+### Page Structure
+
+The repo landing page (`/repos/[id]`) is the chat interface:
+- Compact header (repo name + commit badge + branch badge)
+- `ChatInterface` filling remaining viewport height
+- Sidebar nav item updated from "Overview" to "Chat"
+
+All other repo sub-pages (graph, wiki, coverage, etc.) are unchanged.
+
+---
+
+## 10. Provider-Specific Notes
+
+### Anthropic
+
+Uses `client.messages.stream()` with native Anthropic message format. Converts
+OpenAI-format messages to Anthropic format (tool results as `user` role with
+`tool_result` content blocks, tool calls as `tool_use` content blocks). The
+agentic loop runs in the chat router.
+
+### OpenAI
+
+Uses `client.chat.completions.create(stream=True)`. Native OpenAI format —
+minimal conversion needed. Tool call fragments are accumulated across stream
+chunks and emitted as complete `tool_start` events. The agentic loop runs in
+the chat router.
+
+### Gemini
+
+Uses `client.models.generate_content()` (non-streaming, in a thread pool).
+**Runs the agentic loop internally** via the `tool_executor` callback to
+preserve `thought_signature` on function call parts. Gemini's API requires
+these signatures when replaying function calls in conversation history; the
+OpenAI-format round-trip through the router would lose them. Native `Content`
+objects are used throughout the internal loop.
+
+### Ollama
+
+Uses the OpenAI-compatible endpoint (`localhost:11434/v1`) via `AsyncOpenAI`.
+Same streaming pattern as OpenAI. The agentic loop runs in the chat router.
+
+### LiteLLM
+
+Uses `litellm.acompletion(stream=True)`. OpenAI-compatible streaming. The
+agentic loop runs in the chat router.
diff --git a/package-lock.json b/package-lock.json
index 598cdf102..e6a5af1b4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -6546,6 +6546,16 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/html-url-attributes": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/html-void-elements": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz",
@@ -7650,6 +7660,16 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/markdown-table": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",
+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/marked": {
"version": "16.4.2",
"resolved": "https://registry.npmjs.org/marked/-/marked-16.4.2.tgz",
@@ -7672,6 +7692,48 @@
"node": ">= 0.4"
}
},
+ "node_modules/mdast-util-find-and-replace": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",
+ "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "escape-string-regexp": "^5.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",
+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/mdast-util-find-and-replace/node_modules/unist-util-visit-parents": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",
+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/mdast-util-from-markdown": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz",
@@ -7696,6 +7758,107 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/mdast-util-gfm": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",
+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-gfm-autolink-literal": "^2.0.0",
+ "mdast-util-gfm-footnote": "^2.0.0",
+ "mdast-util-gfm-strikethrough": "^2.0.0",
+ "mdast-util-gfm-table": "^2.0.0",
+ "mdast-util-gfm-task-list-item": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-autolink-literal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",
+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "ccount": "^2.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-find-and-replace": "^3.0.0",
+ "micromark-util-character": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.1.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-strikethrough": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz",
+ "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-table": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",
+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "markdown-table": "^3.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-task-list-item": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",
+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/mdast-util-mdx": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/mdast-util-mdx/-/mdast-util-mdx-3.0.0.tgz",
@@ -7950,6 +8113,127 @@
"micromark-util-types": "^2.0.0"
}
},
+ "node_modules/micromark-extension-gfm": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",
+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-extension-gfm-autolink-literal": "^2.0.0",
+ "micromark-extension-gfm-footnote": "^2.0.0",
+ "micromark-extension-gfm-strikethrough": "^2.0.0",
+ "micromark-extension-gfm-table": "^2.0.0",
+ "micromark-extension-gfm-tagfilter": "^2.0.0",
+ "micromark-extension-gfm-task-list-item": "^2.0.0",
+ "micromark-util-combine-extensions": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-autolink-literal": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",
+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-core-commonmark": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-strikethrough": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",
+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-table": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz",
+ "integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-tagfilter": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",
+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-task-list-item": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",
+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/micromark-extension-mdx-expression": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/micromark-extension-mdx-expression/-/micromark-extension-mdx-expression-3.0.1.tgz",
@@ -9240,6 +9524,33 @@
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
+ "node_modules/react-markdown": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
+ "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "hast-util-to-jsx-runtime": "^2.0.0",
+ "html-url-attributes": "^3.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-rehype": "^11.0.0",
+ "unified": "^11.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ },
+ "peerDependencies": {
+ "@types/react": ">=18",
+ "react": ">=18"
+ }
+ },
"node_modules/react-remove-scroll": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",
@@ -9529,6 +9840,24 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/remark-gfm": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",
+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-gfm": "^3.0.0",
+ "micromark-extension-gfm": "^3.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-stringify": "^11.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/remark-mdx": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/remark-mdx/-/remark-mdx-3.1.1.tgz",
@@ -9576,6 +9905,21 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/remark-stringify": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz",
+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/resolve": {
"version": "1.22.11",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",
@@ -11124,7 +11468,9 @@
"nuqs": "^2.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
+ "react-markdown": "^10.1.0",
"recharts": "^2.13.0",
+ "remark-gfm": "^4.0.1",
"shiki": "^1.22.0",
"sonner": "^2.0.7",
"swr": "^2.2.5",
diff --git a/packages/core/alembic/versions/0005_chat_conversations.py b/packages/core/alembic/versions/0005_chat_conversations.py
new file mode 100644
index 000000000..e36c7f3fc
--- /dev/null
+++ b/packages/core/alembic/versions/0005_chat_conversations.py
@@ -0,0 +1,79 @@
+"""Add conversations and chat_messages tables for codebase chat feature.
+
+Revision ID: 0005
+Revises: 0004
+Create Date: 2026-03-25
+"""
+
+from __future__ import annotations
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0005"
+down_revision: Union[str, None] = "0004"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "conversations",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("title", sa.Text, nullable=False, server_default="New conversation"),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ nullable=False,
+ server_default=sa.func.now(),
+ ),
+ sa.Column(
+ "updated_at",
+ sa.DateTime(timezone=True),
+ nullable=False,
+ server_default=sa.func.now(),
+ ),
+ )
+ op.create_index(
+ "ix_conversations_repo_updated",
+ "conversations",
+ ["repository_id", "updated_at"],
+ )
+
+ op.create_table(
+ "chat_messages",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column(
+ "conversation_id",
+ sa.String(32),
+ sa.ForeignKey("conversations.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("role", sa.String(32), nullable=False),
+ sa.Column("content_json", sa.Text, nullable=False, server_default="{}"),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ nullable=False,
+ server_default=sa.func.now(),
+ ),
+ )
+ op.create_index(
+ "ix_chat_messages_conv_created",
+ "chat_messages",
+ ["conversation_id", "created_at"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("chat_messages")
+ op.drop_table("conversations")
diff --git a/packages/core/src/wikicode/core/persistence/__init__.py b/packages/core/src/wikicode/core/persistence/__init__.py
index ac01411cd..4688dea3d 100644
--- a/packages/core/src/wikicode/core/persistence/__init__.py
+++ b/packages/core/src/wikicode/core/persistence/__init__.py
@@ -19,8 +19,13 @@ from .crud import (
batch_upsert_graph_nodes,
batch_upsert_symbols,
bulk_upsert_decisions,
+ count_chat_messages,
+ create_chat_message,
+ create_conversation,
+ delete_conversation,
delete_decision,
get_all_git_metadata,
+ get_conversation,
get_dead_code_findings,
get_dead_code_summary,
get_decision,
@@ -34,12 +39,16 @@ from .crud import (
get_repository_by_path,
get_stale_decisions,
get_stale_pages,
+ list_chat_messages,
+ list_conversations,
list_decisions,
list_pages,
mark_webhook_processed,
recompute_decision_staleness,
save_dead_code_findings,
store_webhook_event,
+ touch_conversation,
+ update_conversation_title,
update_dead_code_status,
update_decision_status,
update_job_status,
@@ -64,6 +73,8 @@ from .database import (
from .embedder import Embedder, MockEmbedder
from .models import (
Base,
+ ChatMessage,
+ Conversation,
DeadCodeFinding,
DecisionRecord,
GenerationJob,
@@ -96,6 +107,8 @@ __all__ = [
"get_session",
# models
"Base",
+ "ChatMessage",
+ "Conversation",
"Repository",
"GenerationJob",
"Page",
@@ -146,6 +159,16 @@ __all__ = [
"recompute_decision_staleness",
"get_stale_decisions",
"get_decision_health_summary",
+ # chat crud
+ "create_conversation",
+ "get_conversation",
+ "list_conversations",
+ "update_conversation_title",
+ "delete_conversation",
+ "touch_conversation",
+ "create_chat_message",
+ "list_chat_messages",
+ "count_chat_messages",
# embedder
"Embedder",
"MockEmbedder",
diff --git a/packages/core/src/wikicode/core/persistence/crud.py b/packages/core/src/wikicode/core/persistence/crud.py
index 65e5674a3..3b805b818 100644
--- a/packages/core/src/wikicode/core/persistence/crud.py
+++ b/packages/core/src/wikicode/core/persistence/crud.py
@@ -21,6 +21,8 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from .models import (
+ ChatMessage,
+ Conversation,
DeadCodeFinding,
DecisionRecord,
GenerationJob,
@@ -1172,3 +1174,114 @@ async def get_decision_health_summary(
"proposed_awaiting_review": proposed_decisions,
"ungoverned_hotspots": ungoverned,
}
+
+
+# ---------------------------------------------------------------------------
+# Conversation CRUD
+# ---------------------------------------------------------------------------
+
+
+async def create_conversation(
+ session: AsyncSession,
+ *,
+ repository_id: str,
+ title: str = "New conversation",
+) -> Conversation:
+ conv = Conversation(repository_id=repository_id, title=title)
+ session.add(conv)
+ await session.flush()
+ return conv
+
+
+async def get_conversation(
+ session: AsyncSession, conversation_id: str
+) -> Conversation | None:
+ return await session.get(Conversation, conversation_id)
+
+
+async def list_conversations(
+ session: AsyncSession, repository_id: str, *, limit: int = 50
+) -> list[Conversation]:
+ result = await session.execute(
+ select(Conversation)
+ .where(Conversation.repository_id == repository_id)
+ .order_by(Conversation.updated_at.desc())
+ .limit(limit)
+ )
+ return list(result.scalars().all())
+
+
+async def update_conversation_title(
+ session: AsyncSession, conversation_id: str, title: str
+) -> Conversation | None:
+ conv = await session.get(Conversation, conversation_id)
+ if conv:
+ conv.title = title
+ conv.updated_at = _now_utc()
+ await session.flush()
+ return conv
+
+
+async def delete_conversation(session: AsyncSession, conversation_id: str) -> bool:
+ conv = await session.get(Conversation, conversation_id)
+ if conv is None:
+ return False
+ await session.delete(conv)
+ await session.flush()
+ return True
+
+
+async def touch_conversation(
+ session: AsyncSession, conversation_id: str
+) -> None:
+ """Update the updated_at timestamp of a conversation."""
+ conv = await session.get(Conversation, conversation_id)
+ if conv:
+ conv.updated_at = _now_utc()
+ await session.flush()
+
+
+# ---------------------------------------------------------------------------
+# ChatMessage CRUD
+# ---------------------------------------------------------------------------
+
+
+async def create_chat_message(
+ session: AsyncSession,
+ *,
+ conversation_id: str,
+ role: str,
+ content: dict,
+) -> ChatMessage:
+ msg = ChatMessage(
+ conversation_id=conversation_id,
+ role=role,
+ content_json=json.dumps(content),
+ )
+ session.add(msg)
+ await session.flush()
+ return msg
+
+
+async def list_chat_messages(
+ session: AsyncSession, conversation_id: str
+) -> list[ChatMessage]:
+ result = await session.execute(
+ select(ChatMessage)
+ .where(ChatMessage.conversation_id == conversation_id)
+ .order_by(ChatMessage.created_at.asc())
+ )
+ return list(result.scalars().all())
+
+
+async def count_chat_messages(
+ session: AsyncSession, conversation_id: str
+) -> int:
+ from sqlalchemy import func
+
+ result = await session.execute(
+ select(func.count())
+ .select_from(ChatMessage)
+ .where(ChatMessage.conversation_id == conversation_id)
+ )
+ return result.scalar() or 0
diff --git a/packages/core/src/wikicode/core/persistence/models.py b/packages/core/src/wikicode/core/persistence/models.py
index 52fb8af11..7e64016a8 100644
--- a/packages/core/src/wikicode/core/persistence/models.py
+++ b/packages/core/src/wikicode/core/persistence/models.py
@@ -367,6 +367,40 @@ class DecisionRecord(Base):
)
+class Conversation(Base):
+ """A chat conversation for a repository."""
+
+ __tablename__ = "conversations"
+
+ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
+ )
+ title: Mapped[str] = mapped_column(Text, nullable=False, default="New conversation")
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc
+ )
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc
+ )
+
+
+class ChatMessage(Base):
+ """A single message in a chat conversation."""
+
+ __tablename__ = "chat_messages"
+
+ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)
+ conversation_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("conversations.id", ondelete="CASCADE"), nullable=False
+ )
+ role: Mapped[str] = mapped_column(String(32), nullable=False) # user | assistant
+ content_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc
+ )
+
+
class DeadCodeFinding(Base):
"""Dead code finding: unreachable files, unused exports, zombie packages."""
diff --git a/packages/core/src/wikicode/core/providers/__init__.py b/packages/core/src/wikicode/core/providers/__init__.py
index 18046333e..cd4fae453 100644
--- a/packages/core/src/wikicode/core/providers/__init__.py
+++ b/packages/core/src/wikicode/core/providers/__init__.py
@@ -11,6 +11,9 @@ to instantiate a provider by name — this is the preferred entry point.
from wikicode.core.providers.base import (
BaseProvider,
+ ChatProvider,
+ ChatStreamEvent,
+ ChatToolCall,
GeneratedResponse,
ProviderError,
RateLimitError,
@@ -19,6 +22,9 @@ from wikicode.core.providers.registry import get_provider, list_providers, regis
__all__ = [
"BaseProvider",
+ "ChatProvider",
+ "ChatStreamEvent",
+ "ChatToolCall",
"GeneratedResponse",
"ProviderError",
"RateLimitError",
diff --git a/packages/core/src/wikicode/core/providers/anthropic.py b/packages/core/src/wikicode/core/providers/anthropic.py
index 694e94d52..7954af965 100644
--- a/packages/core/src/wikicode/core/providers/anthropic.py
+++ b/packages/core/src/wikicode/core/providers/anthropic.py
@@ -27,10 +27,14 @@ from tenacity import (
from wikicode.core.providers.base import (
BaseProvider,
+ ChatStreamEvent,
+ ChatToolCall,
GeneratedResponse,
ProviderError,
RateLimitError,
)
+
+from typing import Any, AsyncIterator
from wikicode.core.rate_limiter import RateLimiter
log = structlog.get_logger(__name__)
@@ -153,3 +157,150 @@ class AnthropicProvider(BaseProvider):
request_id=request_id,
)
return result
+
+ # --- ChatProvider protocol implementation ---
+
+ async def stream_chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]],
+ system_prompt: str,
+ max_tokens: int = 8192,
+ temperature: float = 0.7,
+ request_id: str | None = None,
+ tool_executor: Any | None = None,
+ ) -> AsyncIterator[ChatStreamEvent]:
+ import json as _json
+
+ # Convert OpenAI-format tools to Anthropic format
+ anthropic_tools = []
+ for t in tools:
+ fn = t.get("function", t)
+ anthropic_tools.append({
+ "name": fn["name"],
+ "description": fn.get("description", ""),
+ "input_schema": fn.get("parameters", {}),
+ })
+
+ # Convert OpenAI-format messages to Anthropic format
+ anthropic_messages = _to_anthropic_messages(messages)
+
+ kwargs: dict[str, Any] = {
+ "model": self._model,
+ "max_tokens": max_tokens,
+ "temperature": temperature,
+ "system": system_prompt,
+ "messages": anthropic_messages,
+ }
+ if anthropic_tools:
+ kwargs["tools"] = anthropic_tools
+
+ try:
+ async with self._client.messages.stream(**kwargs) as stream:
+ current_tool_id: str | None = None
+ current_tool_name: str | None = None
+ current_tool_input_json = ""
+
+ async for event in stream:
+ if event.type == "content_block_start":
+ block = event.content_block
+ if hasattr(block, "type") and block.type == "tool_use":
+ current_tool_id = block.id
+ current_tool_name = block.name
+ current_tool_input_json = ""
+ elif event.type == "content_block_delta":
+ delta = event.delta
+ if hasattr(delta, "type"):
+ if delta.type == "text_delta":
+ yield ChatStreamEvent(type="text_delta", text=delta.text)
+ elif delta.type == "input_json_delta":
+ current_tool_input_json += delta.partial_json
+ elif event.type == "content_block_stop":
+ if current_tool_name:
+ try:
+ args = _json.loads(current_tool_input_json) if current_tool_input_json else {}
+ except Exception:
+ args = {}
+ yield ChatStreamEvent(
+ type="tool_start",
+ tool_call=ChatToolCall(
+ id=current_tool_id or "",
+ name=current_tool_name,
+ arguments=args,
+ ),
+ )
+ current_tool_id = None
+ current_tool_name = None
+ current_tool_input_json = ""
+ elif event.type == "message_delta":
+ stop = getattr(event.delta, "stop_reason", None)
+ usage = getattr(event, "usage", None)
+ if usage:
+ yield ChatStreamEvent(
+ type="usage",
+ input_tokens=getattr(usage, "input_tokens", 0) or 0,
+ output_tokens=getattr(usage, "output_tokens", 0) or 0,
+ )
+ if stop:
+ yield ChatStreamEvent(type="stop", stop_reason=stop)
+ elif event.type == "message_stop":
+ pass # Final cleanup; stop already yielded via message_delta
+ except _AnthropicRateLimitError as exc:
+ raise RateLimitError("anthropic", str(exc), status_code=429) from exc
+ except _AnthropicAPIStatusError as exc:
+ raise ProviderError("anthropic", str(exc), status_code=exc.status_code) from exc
+
+
+def _to_anthropic_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Convert OpenAI-format messages to Anthropic format.
+
+ Key differences:
+ - Anthropic has no 'system' role in messages (handled via top-level param)
+ - Tool results go as 'user' messages with tool_result content blocks
+ - assistant tool_calls become content blocks with type=tool_use
+ """
+ result: list[dict[str, Any]] = []
+ for msg in messages:
+ role = msg.get("role", "")
+ if role == "system":
+ continue # Handled via system= parameter
+
+ if role == "tool":
+ # OpenAI tool result → Anthropic user message with tool_result block
+ result.append({
+ "role": "user",
+ "content": [{
+ "type": "tool_result",
+ "tool_use_id": msg.get("tool_call_id", ""),
+ "content": msg.get("content", ""),
+ }],
+ })
+ elif role == "assistant":
+ content_blocks: list[dict[str, Any]] = []
+ # Text content
+ text = msg.get("content")
+ if text:
+ content_blocks.append({"type": "text", "text": text})
+ # Tool calls
+ for tc in msg.get("tool_calls", []):
+ fn = tc.get("function", {})
+ import json as _json
+ args = fn.get("arguments", "{}")
+ if isinstance(args, str):
+ try:
+ args = _json.loads(args)
+ except Exception:
+ args = {}
+ content_blocks.append({
+ "type": "tool_use",
+ "id": tc.get("id", ""),
+ "name": fn.get("name", ""),
+ "input": args,
+ })
+ if content_blocks:
+ result.append({"role": "assistant", "content": content_blocks})
+ else:
+ # User message
+ result.append({"role": "user", "content": msg.get("content", "")})
+
+ return result
diff --git a/packages/core/src/wikicode/core/providers/base.py b/packages/core/src/wikicode/core/providers/base.py
index ea059ce6c..c4d931c30 100644
--- a/packages/core/src/wikicode/core/providers/base.py
+++ b/packages/core/src/wikicode/core/providers/base.py
@@ -15,7 +15,7 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
-from typing import Any
+from typing import Any, AsyncIterator, Protocol, runtime_checkable
@dataclass
@@ -138,3 +138,90 @@ class RateLimitError(ProviderError):
but RateLimitError signals that backing off longer won't help —
the operator needs to review rate limits or reduce concurrency.
"""
+
+
+# ---------------------------------------------------------------------------
+# Chat streaming types and protocol (opt-in for providers that support it)
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class ChatToolCall:
+ """A tool call requested by the LLM during a chat turn."""
+
+ id: str
+ name: str
+ arguments: dict[str, Any]
+
+
+@dataclass
+class ChatStreamEvent:
+ """A single event yielded by stream_chat().
+
+ The ``type`` field determines which other fields are populated:
+ - ``text_delta``: incremental text token(s) in ``text``
+ - ``tool_start``: a completed tool call block in ``tool_call``
+ - ``tool_result``: tool execution result (from internal loops) in ``tool_call`` + ``tool_result_data``
+ - ``usage``: token counts in ``input_tokens`` / ``output_tokens``
+ - ``stop``: end of generation (may follow tool_start if stop_reason is tool_use)
+ """
+
+ type: str # text_delta | tool_start | tool_result | usage | stop
+ text: str | None = None
+ tool_call: ChatToolCall | None = None
+ tool_result_data: dict[str, Any] | None = None # populated for tool_result events
+ stop_reason: str | None = None # end_turn | tool_use | max_tokens
+ input_tokens: int = 0
+ output_tokens: int = 0
+
+
+ToolExecutor = Any # Callable[[str, dict], Awaitable[dict]] — but kept as Any to avoid import cycles
+
+
+@runtime_checkable
+class ChatProvider(Protocol):
+ """Optional protocol for providers that support streaming chat with tool use.
+
+ Providers opt in by implementing stream_chat(). The existing BaseProvider
+ and its generate() method remain completely untouched.
+
+ Messages use OpenAI-format dicts. Each provider's stream_chat()
+ converts to its native format internally.
+ """
+
+ @property
+ def provider_name(self) -> str: ...
+
+ @property
+ def model_name(self) -> str: ...
+
+ def stream_chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]],
+ system_prompt: str,
+ max_tokens: int = 8192,
+ temperature: float = 0.7,
+ request_id: str | None = None,
+ tool_executor: ToolExecutor | None = None,
+ ) -> AsyncIterator[ChatStreamEvent]:
+ """Stream a multi-turn chat response with tool use support.
+
+ Args:
+ messages: OpenAI-format message list (role + content + tool_calls).
+ tools: OpenAI-format tool definitions for function calling.
+ system_prompt: System instructions for the agent.
+ max_tokens: Max completion tokens.
+ temperature: Sampling temperature.
+ request_id: Optional trace ID.
+ tool_executor: Optional async callable(name, args) -> dict. If provided,
+ providers that need internal tool-call looping (e.g. Gemini
+ for thought_signature preservation) will execute tools
+ internally and yield tool_start/tool_result events. Providers
+ that don't need it (OpenAI, Anthropic) ignore this parameter
+ and let the caller handle the loop.
+
+ Yields:
+ ChatStreamEvent objects as tokens and tool calls arrive.
+ """
+ ...
diff --git a/packages/core/src/wikicode/core/providers/gemini.py b/packages/core/src/wikicode/core/providers/gemini.py
index ae8da8966..be98f5b0f 100644
--- a/packages/core/src/wikicode/core/providers/gemini.py
+++ b/packages/core/src/wikicode/core/providers/gemini.py
@@ -24,10 +24,14 @@ from tenacity import (
from wikicode.core.providers.base import (
BaseProvider,
+ ChatStreamEvent,
+ ChatToolCall,
GeneratedResponse,
ProviderError,
RateLimitError,
)
+
+from typing import Any, AsyncIterator
from wikicode.core.rate_limiter import RateLimiter
log = structlog.get_logger(__name__)
@@ -174,3 +178,206 @@ class GeminiProvider(BaseProvider):
request_id=request_id,
)
return result
+
+ # --- ChatProvider protocol implementation ---
+
+ async def stream_chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]],
+ system_prompt: str,
+ max_tokens: int = 8192,
+ temperature: float = 0.7,
+ request_id: str | None = None,
+ tool_executor: Any | None = None,
+ ) -> AsyncIterator[ChatStreamEvent]:
+ """Stream chat using Gemini's native generate_content.
+
+ Gemini requires thought_signature to be preserved on function_call
+ parts when sending them back. To handle this, we use non-streaming
+ generate_content and run the full agentic loop internally using
+ native Content objects (which preserve thought signatures). The
+ tool_executor callback is required for Gemini — if not provided
+ and the model requests tool calls, a stop event with tool_use is
+ yielded and the caller must handle it (though this will fail on
+ the next round-trip due to missing thought signatures).
+ """
+ import json as _json
+
+ model_name = self._model
+ api_key = self._api_key
+
+ def _call_sync(contents, config):
+ """Single Gemini generate_content call in thread."""
+ from google import genai # type: ignore[import-untyped]
+
+ client = genai.Client(api_key=api_key)
+ try:
+ response = client.models.generate_content(
+ model=model_name,
+ contents=contents,
+ config=config,
+ )
+ except Exception as exc:
+ exc_str = str(exc)
+ status_code = getattr(exc, "status_code", None) or getattr(exc, "code", None)
+ if status_code == 429 or "429" in exc_str or "quota" in exc_str.lower():
+ raise RateLimitError("gemini", exc_str, status_code=429) from exc
+ raise ProviderError("gemini", f"{type(exc).__name__}: {exc_str}") from exc
+ return response
+
+ from google.genai import types as genai_types # type: ignore[import-untyped]
+
+ # Convert OpenAI tools to Gemini FunctionDeclarations
+ gemini_tools = None
+ if tools:
+ declarations = []
+ for t in tools:
+ fn = t.get("function", t)
+ params = fn.get("parameters", {})
+ declarations.append(genai_types.FunctionDeclaration(
+ name=fn["name"],
+ description=fn.get("description", ""),
+ parameters=params if params else None,
+ ))
+ gemini_tools = [genai_types.Tool(function_declarations=declarations)]
+
+ config = genai_types.GenerateContentConfig(
+ system_instruction=system_prompt,
+ temperature=temperature,
+ tools=gemini_tools,
+ )
+
+ # Convert initial OpenAI messages to Gemini native Content objects
+ contents = _to_gemini_contents(messages)
+
+ max_loops = 10
+ for _ in range(max_loops):
+ # Call Gemini
+ try:
+ response = await asyncio.to_thread(_call_sync, contents, config)
+ except (RateLimitError, ProviderError):
+ raise
+ except Exception as exc:
+ raise ProviderError("gemini", f"{type(exc).__name__}: {exc}") from exc
+
+ if not response.candidates:
+ yield ChatStreamEvent(type="stop", stop_reason="end_turn")
+ return
+
+ # The model's response content — preserved as-is for the next turn
+ model_content = response.candidates[0].content
+
+ # Extract events from response parts
+ function_calls_found: list[tuple[str, str, dict]] = []
+ for part in model_content.parts:
+ if hasattr(part, "text") and part.text:
+ yield ChatStreamEvent(type="text_delta", text=part.text)
+ elif hasattr(part, "function_call") and part.function_call:
+ fc = part.function_call
+ args = dict(fc.args) if fc.args else {}
+ tc_id = f"gemini-{fc.name}-{id(part)}"
+ function_calls_found.append((tc_id, fc.name, args))
+ yield ChatStreamEvent(
+ type="tool_start",
+ tool_call=ChatToolCall(
+ id=tc_id,
+ name=fc.name,
+ arguments=args,
+ ),
+ )
+
+ if not function_calls_found:
+ yield ChatStreamEvent(type="stop", stop_reason="end_turn")
+ return
+
+ # If no tool_executor, yield stop and let the caller handle
+ # (will break on next round-trip due to thought_signature, but
+ # this is a fallback)
+ if tool_executor is None:
+ yield ChatStreamEvent(type="stop", stop_reason="tool_use")
+ return
+
+ # Execute tools and build function_response parts
+ # Append the model's response (with thought signatures) to contents
+ contents.append(model_content)
+
+ response_parts = []
+ for tc_id, name, args in function_calls_found:
+ result = await tool_executor(name, args)
+ yield ChatStreamEvent(
+ type="tool_result",
+ tool_call=ChatToolCall(id=tc_id, name=name, arguments=args),
+ tool_result_data=result,
+ )
+ response_parts.append(
+ genai_types.Part.from_function_response(
+ name=name,
+ response=result,
+ )
+ )
+
+ # Append tool results as a user turn
+ contents.append(genai_types.Content(role="user", parts=response_parts))
+ # Loop back to get the model's text response
+
+ # Max loops reached
+ yield ChatStreamEvent(type="stop", stop_reason="end_turn")
+
+
+def _to_gemini_contents(messages: list[dict[str, Any]]) -> list:
+ """Convert OpenAI-format messages to Gemini Content objects.
+
+ Only used for the initial history conversion. Subsequent tool-call
+ round-trips use native Gemini Content objects (preserving thought
+ signatures).
+ """
+ from google.genai import types as genai_types # type: ignore[import-untyped]
+ import json as _json
+
+ contents = []
+ for msg in messages:
+ role = msg.get("role", "")
+ if role == "system":
+ continue # Handled via system_instruction
+
+ gemini_role = "model" if role == "assistant" else "user"
+ parts = []
+
+ if role == "tool":
+ # Tool result → function_response part
+ content_str = msg.get("content", "{}")
+ try:
+ response_data = _json.loads(content_str) if isinstance(content_str, str) else content_str
+ except Exception:
+ response_data = {"result": content_str}
+ parts.append(genai_types.Part.from_function_response(
+ name=msg.get("name", "unknown"),
+ response=response_data,
+ ))
+ gemini_role = "user"
+ elif role == "assistant":
+ text = msg.get("content")
+ if text:
+ parts.append(genai_types.Part.from_text(text=text))
+ for tc in msg.get("tool_calls", []):
+ fn = tc.get("function", {})
+ args_str = fn.get("arguments", "{}")
+ if isinstance(args_str, str):
+ try:
+ args = _json.loads(args_str)
+ except Exception:
+ args = {}
+ else:
+ args = args_str
+ parts.append(genai_types.Part.from_function_call(
+ name=fn.get("name", ""),
+ args=args,
+ ))
+ else:
+ parts.append(genai_types.Part.from_text(text=msg.get("content", "")))
+
+ if parts:
+ contents.append(genai_types.Content(role=gemini_role, parts=parts))
+
+ return contents
diff --git a/packages/core/src/wikicode/core/providers/litellm.py b/packages/core/src/wikicode/core/providers/litellm.py
index 90313b2d2..9db2439f4 100644
--- a/packages/core/src/wikicode/core/providers/litellm.py
+++ b/packages/core/src/wikicode/core/providers/litellm.py
@@ -30,10 +30,14 @@ from tenacity import (
from wikicode.core.providers.base import (
BaseProvider,
+ ChatStreamEvent,
+ ChatToolCall,
GeneratedResponse,
ProviderError,
RateLimitError,
)
+
+from typing import Any, AsyncIterator
from wikicode.core.rate_limiter import RateLimiter
log = structlog.get_logger(__name__)
@@ -159,3 +163,91 @@ class LiteLLMProvider(BaseProvider):
request_id=request_id,
)
return result
+
+ # --- ChatProvider protocol implementation ---
+
+ async def stream_chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]],
+ system_prompt: str,
+ max_tokens: int = 8192,
+ temperature: float = 0.7,
+ request_id: str | None = None,
+ tool_executor: Any | None = None,
+ ) -> AsyncIterator[ChatStreamEvent]:
+ import json as _json
+ import litellm # type: ignore[import-untyped]
+
+ litellm.set_verbose = False
+ litellm.suppress_debug_info = True
+
+ full_messages = [{"role": "system", "content": system_prompt}, *messages]
+ call_kwargs: dict[str, Any] = {
+ "model": self._model,
+ "messages": full_messages,
+ "temperature": temperature,
+ "max_tokens": max_tokens,
+ "stream": True,
+ }
+ if tools:
+ call_kwargs["tools"] = tools
+ if self._api_key:
+ call_kwargs["api_key"] = self._api_key
+ if self._api_base:
+ call_kwargs["api_base"] = self._api_base
+
+ try:
+ stream = await litellm.acompletion(**call_kwargs)
+ except litellm.RateLimitError as exc:
+ raise RateLimitError("litellm", str(exc), status_code=429) from exc
+ except litellm.APIError as exc:
+ raise ProviderError("litellm", str(exc)) from exc
+
+ tool_calls_acc: dict[int, dict[str, Any]] = {}
+
+ try:
+ async for chunk in stream:
+ choice = chunk.choices[0] if chunk.choices else None
+ if not choice:
+ continue
+
+ delta = choice.delta
+ finish = choice.finish_reason
+
+ if delta and getattr(delta, "content", None):
+ yield ChatStreamEvent(type="text_delta", text=delta.content)
+
+ if delta and getattr(delta, "tool_calls", None):
+ for tc_delta in delta.tool_calls:
+ idx = tc_delta.index
+ if idx not in tool_calls_acc:
+ tool_calls_acc[idx] = {"id": getattr(tc_delta, "id", "") or "", "name": "", "arguments": ""}
+ acc = tool_calls_acc[idx]
+ if getattr(tc_delta, "id", None):
+ acc["id"] = tc_delta.id
+ fn = getattr(tc_delta, "function", None)
+ if fn:
+ if getattr(fn, "name", None):
+ acc["name"] = fn.name
+ if getattr(fn, "arguments", None):
+ acc["arguments"] += fn.arguments
+
+ if finish:
+ for idx in sorted(tool_calls_acc.keys()):
+ acc = tool_calls_acc[idx]
+ try:
+ args = _json.loads(acc["arguments"]) if acc["arguments"] else {}
+ except Exception:
+ args = {}
+ yield ChatStreamEvent(
+ type="tool_start",
+ tool_call=ChatToolCall(id=acc["id"], name=acc["name"], arguments=args),
+ )
+ tool_calls_acc.clear()
+ stop_reason = "tool_use" if finish == "tool_calls" else "end_turn"
+ yield ChatStreamEvent(type="stop", stop_reason=stop_reason)
+ except litellm.RateLimitError as exc:
+ raise RateLimitError("litellm", str(exc), status_code=429) from exc
+ except Exception as exc:
+ raise ProviderError("litellm", f"{type(exc).__name__}: {exc}") from exc
diff --git a/packages/core/src/wikicode/core/providers/ollama.py b/packages/core/src/wikicode/core/providers/ollama.py
index e3ee821a9..c3167f4a6 100644
--- a/packages/core/src/wikicode/core/providers/ollama.py
+++ b/packages/core/src/wikicode/core/providers/ollama.py
@@ -33,9 +33,13 @@ from tenacity import (
from wikicode.core.providers.base import (
BaseProvider,
+ ChatStreamEvent,
+ ChatToolCall,
GeneratedResponse,
ProviderError,
)
+
+from typing import Any, AsyncIterator
from wikicode.core.rate_limiter import RateLimiter
log = structlog.get_logger(__name__)
@@ -158,3 +162,79 @@ class OllamaProvider(BaseProvider):
request_id=request_id,
)
return result
+
+ # --- ChatProvider protocol implementation ---
+
+ async def stream_chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]],
+ system_prompt: str,
+ max_tokens: int = 8192,
+ temperature: float = 0.7,
+ request_id: str | None = None,
+ tool_executor: Any | None = None,
+ ) -> AsyncIterator[ChatStreamEvent]:
+ """Stream chat via Ollama's OpenAI-compatible endpoint."""
+ import json as _json
+
+ full_messages = [{"role": "system", "content": system_prompt}, *messages]
+ kwargs: dict[str, Any] = {
+ "model": self._model,
+ "max_tokens": max_tokens,
+ "temperature": temperature,
+ "messages": full_messages,
+ "stream": True,
+ }
+ if tools:
+ kwargs["tools"] = tools
+
+ try:
+ stream = await self._client.chat.completions.create(**kwargs)
+ except _OpenAIAPIStatusError as exc:
+ raise ProviderError("ollama", str(exc), status_code=exc.status_code) from exc
+
+ tool_calls_acc: dict[int, dict[str, Any]] = {}
+
+ try:
+ async for chunk in stream:
+ choice = chunk.choices[0] if chunk.choices else None
+ if not choice:
+ continue
+
+ delta = choice.delta
+ finish = choice.finish_reason
+
+ if delta and delta.content:
+ yield ChatStreamEvent(type="text_delta", text=delta.content)
+
+ if delta and delta.tool_calls:
+ for tc_delta in delta.tool_calls:
+ idx = tc_delta.index
+ if idx not in tool_calls_acc:
+ tool_calls_acc[idx] = {"id": tc_delta.id or "", "name": "", "arguments": ""}
+ acc = tool_calls_acc[idx]
+ if tc_delta.id:
+ acc["id"] = tc_delta.id
+ if tc_delta.function:
+ if tc_delta.function.name:
+ acc["name"] = tc_delta.function.name
+ if tc_delta.function.arguments:
+ acc["arguments"] += tc_delta.function.arguments
+
+ if finish:
+ for idx in sorted(tool_calls_acc.keys()):
+ acc = tool_calls_acc[idx]
+ try:
+ args = _json.loads(acc["arguments"]) if acc["arguments"] else {}
+ except Exception:
+ args = {}
+ yield ChatStreamEvent(
+ type="tool_start",
+ tool_call=ChatToolCall(id=acc["id"], name=acc["name"], arguments=args),
+ )
+ tool_calls_acc.clear()
+ stop_reason = "tool_use" if finish == "tool_calls" else "end_turn"
+ yield ChatStreamEvent(type="stop", stop_reason=stop_reason)
+ except _OpenAIAPIStatusError as exc:
+ raise ProviderError("ollama", str(exc), status_code=exc.status_code) from exc
diff --git a/packages/core/src/wikicode/core/providers/openai.py b/packages/core/src/wikicode/core/providers/openai.py
index cbbaf035b..9f718cf9b 100644
--- a/packages/core/src/wikicode/core/providers/openai.py
+++ b/packages/core/src/wikicode/core/providers/openai.py
@@ -26,10 +26,14 @@ from tenacity import (
from wikicode.core.providers.base import (
BaseProvider,
+ ChatStreamEvent,
+ ChatToolCall,
GeneratedResponse,
ProviderError,
RateLimitError,
)
+
+from typing import Any, AsyncIterator
from wikicode.core.rate_limiter import RateLimiter
log = structlog.get_logger(__name__)
@@ -150,3 +154,101 @@ class OpenAIProvider(BaseProvider):
request_id=request_id,
)
return result
+
+ # --- ChatProvider protocol implementation ---
+
+ async def stream_chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]],
+ system_prompt: str,
+ max_tokens: int = 8192,
+ temperature: float = 0.7,
+ request_id: str | None = None,
+ tool_executor: Any | None = None,
+ ) -> AsyncIterator[ChatStreamEvent]:
+ import json as _json
+
+ full_messages = [{"role": "system", "content": system_prompt}, *messages]
+ kwargs: dict[str, Any] = {
+ "model": self._model,
+ "max_tokens": max_tokens,
+ "temperature": temperature,
+ "messages": full_messages,
+ "stream": True,
+ }
+ if tools:
+ kwargs["tools"] = tools
+
+ try:
+ stream = await self._client.chat.completions.create(**kwargs)
+ except _OpenAIRateLimitError as exc:
+ raise RateLimitError("openai", str(exc), status_code=429) from exc
+ except _OpenAIAPIStatusError as exc:
+ raise ProviderError("openai", str(exc), status_code=exc.status_code) from exc
+
+ # Track in-progress tool calls (OpenAI streams them incrementally)
+ tool_calls_acc: dict[int, dict[str, Any]] = {}
+
+ try:
+ async for chunk in stream:
+ choice = chunk.choices[0] if chunk.choices else None
+ if not choice:
+ if chunk.usage:
+ yield ChatStreamEvent(
+ type="usage",
+ input_tokens=chunk.usage.prompt_tokens or 0,
+ output_tokens=chunk.usage.completion_tokens or 0,
+ )
+ continue
+
+ delta = choice.delta
+ finish = choice.finish_reason
+
+ # Text content
+ if delta and delta.content:
+ yield ChatStreamEvent(type="text_delta", text=delta.content)
+
+ # Tool call fragments
+ if delta and delta.tool_calls:
+ for tc_delta in delta.tool_calls:
+ idx = tc_delta.index
+ if idx not in tool_calls_acc:
+ tool_calls_acc[idx] = {
+ "id": tc_delta.id or "",
+ "name": "",
+ "arguments": "",
+ }
+ acc = tool_calls_acc[idx]
+ if tc_delta.id:
+ acc["id"] = tc_delta.id
+ if tc_delta.function:
+ if tc_delta.function.name:
+ acc["name"] = tc_delta.function.name
+ if tc_delta.function.arguments:
+ acc["arguments"] += tc_delta.function.arguments
+
+ if finish:
+ # Emit accumulated tool calls
+ for idx in sorted(tool_calls_acc.keys()):
+ acc = tool_calls_acc[idx]
+ try:
+ args = _json.loads(acc["arguments"]) if acc["arguments"] else {}
+ except Exception:
+ args = {}
+ yield ChatStreamEvent(
+ type="tool_start",
+ tool_call=ChatToolCall(
+ id=acc["id"],
+ name=acc["name"],
+ arguments=args,
+ ),
+ )
+ tool_calls_acc.clear()
+
+ stop_reason = "tool_use" if finish == "tool_calls" else "end_turn"
+ yield ChatStreamEvent(type="stop", stop_reason=stop_reason)
+ except _OpenAIRateLimitError as exc:
+ raise RateLimitError("openai", str(exc), status_code=429) from exc
+ except _OpenAIAPIStatusError as exc:
+ raise ProviderError("openai", str(exc), status_code=exc.status_code) from exc
diff --git a/packages/server/src/wikicode/server/app.py b/packages/server/src/wikicode/server/app.py
index 7db7464b8..c78c09ce3 100644
--- a/packages/server/src/wikicode/server/app.py
+++ b/packages/server/src/wikicode/server/app.py
@@ -26,6 +26,7 @@ from wikicode.core.persistence.search import FullTextSearch
from wikicode.core.persistence.vector_store import InMemoryVectorStore
from wikicode.server import __version__
from wikicode.server.routers import (
+ chat,
dead_code,
decisions,
git,
@@ -33,6 +34,7 @@ from wikicode.server.routers import (
health,
jobs,
pages,
+ providers,
repos,
search,
symbols,
@@ -98,6 +100,15 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
app.state.vector_store = vector_store
app.state.scheduler = scheduler
+ # Initialize chat tool state (bridges FastAPI state to MCP tool globals)
+ from wikicode.server.chat_tools import init_tool_state
+
+ init_tool_state(
+ session_factory=session_factory,
+ fts=fts,
+ vector_store=vector_store,
+ )
+
logger.info("wikicode_server_started", extra={"version": __version__})
yield
@@ -147,5 +158,7 @@ def create_app() -> FastAPI:
app.include_router(git.router)
app.include_router(dead_code.router)
app.include_router(decisions.router)
+ app.include_router(chat.router)
+ app.include_router(providers.router)
return app
diff --git a/packages/server/src/wikicode/server/chat_tools.py b/packages/server/src/wikicode/server/chat_tools.py
new file mode 100644
index 000000000..77d103bcc
--- /dev/null
+++ b/packages/server/src/wikicode/server/chat_tools.py
@@ -0,0 +1,280 @@
+"""Chat tool registry — single source of truth for tool schemas and execution.
+
+Imports the 8 MCP tool functions directly and exposes them as a callable registry
+for the agentic chat loop. Also provides OpenAI-format tool definitions for the LLM.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from dataclasses import dataclass
+from typing import Any, Callable, Awaitable
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class ToolDef:
+ """A tool definition with schema and callable."""
+
+ name: str
+ description: str
+ parameters: dict[str, Any] # JSON Schema
+ function: Callable[..., Awaitable[dict[str, Any]]]
+ artifact_type: str # For the frontend artifact panel
+
+
+# ---------------------------------------------------------------------------
+# Tool schemas (matching FastMCP's auto-generated schemas from function sigs)
+# ---------------------------------------------------------------------------
+
+_TOOL_SCHEMAS: list[dict[str, Any]] = [
+ {
+ "name": "get_overview",
+ "description": "Get a high-level overview of the repository: architecture, key modules, entry points.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "repo": {"type": "string", "description": "Repository path, name, or ID. Omit if only one repo."},
+ },
+ "required": [],
+ },
+ "artifact_type": "overview",
+ },
+ {
+ "name": "get_context",
+ "description": "Get documentation, ownership, freshness, and decisions for one or more files, modules, or symbols.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "targets": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "File paths, module paths, or symbol names to look up.",
+ },
+ "include": {
+ "type": "array",
+ "items": {"type": "string", "enum": ["docs", "ownership", "last_change", "decisions", "freshness"]},
+ "description": "Subset of fields to include. Default: all.",
+ },
+ "repo": {"type": "string", "description": "Repository identifier."},
+ },
+ "required": ["targets"],
+ },
+ "artifact_type": "wiki_page",
+ },
+ {
+ "name": "get_risk",
+ "description": "Assess modification risk for files: hotspot score, dependents, co-change partners, ownership.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "targets": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "File paths to assess risk for.",
+ },
+ "repo": {"type": "string", "description": "Repository identifier."},
+ },
+ "required": ["targets"],
+ },
+ "artifact_type": "risk_report",
+ },
+ {
+ "name": "get_why",
+ "description": "Query architectural decisions: health dashboard (no query), path-based lookup, or natural language search.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Natural language question, file/module path, or omit for health dashboard."},
+ "repo": {"type": "string", "description": "Repository identifier."},
+ },
+ "required": [],
+ },
+ "artifact_type": "decisions",
+ },
+ {
+ "name": "search_codebase",
+ "description": "Semantic and full-text search across all wiki documentation pages.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Natural language search query."},
+ "limit": {"type": "integer", "description": "Max results (default 5).", "default": 5},
+ "page_type": {"type": "string", "description": "Filter by page type (e.g., file_page, module_page)."},
+ "repo": {"type": "string", "description": "Repository identifier."},
+ },
+ "required": ["query"],
+ },
+ "artifact_type": "search_results",
+ },
+ {
+ "name": "get_dependency_path",
+ "description": "Find the shortest dependency path between two files or modules in the codebase graph.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "source": {"type": "string", "description": "Source file or module path."},
+ "target": {"type": "string", "description": "Target file or module path."},
+ "repo": {"type": "string", "description": "Repository identifier."},
+ },
+ "required": ["source", "target"],
+ },
+ "artifact_type": "graph",
+ },
+ {
+ "name": "get_dead_code",
+ "description": "List dead code findings: unreachable files, unused exports, zombie packages.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "repo": {"type": "string", "description": "Repository identifier."},
+ "kind": {"type": "string", "description": "Filter: unreachable_file, unused_export, unused_internal, zombie_package."},
+ "min_confidence": {"type": "number", "description": "Minimum confidence threshold (default 0.5).", "default": 0.5},
+ "safe_only": {"type": "boolean", "description": "Only return safe-to-delete findings.", "default": False},
+ "limit": {"type": "integer", "description": "Max findings (default 20).", "default": 20},
+ },
+ "required": [],
+ },
+ "artifact_type": "dead_code",
+ },
+ {
+ "name": "get_architecture_diagram",
+ "description": "Generate a Mermaid architecture diagram for the repo, a module, or a file.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "scope": {"type": "string", "description": "Scope: repo, module, or file.", "default": "repo"},
+ "path": {"type": "string", "description": "Required for module/file scope."},
+ "diagram_type": {"type": "string", "description": "Diagram type: auto, flowchart, class, sequence.", "default": "auto"},
+ "repo": {"type": "string", "description": "Repository identifier."},
+ },
+ "required": [],
+ },
+ "artifact_type": "diagram",
+ },
+]
+
+
+def _build_registry() -> dict[str, ToolDef]:
+ """Build the tool registry by importing MCP tool functions."""
+ from wikicode.server.mcp_server import (
+ get_overview,
+ get_context,
+ get_risk,
+ get_why,
+ search_codebase,
+ get_dependency_path,
+ get_dead_code,
+ get_architecture_diagram,
+ )
+
+ func_map: dict[str, Callable] = {
+ "get_overview": get_overview,
+ "get_context": get_context,
+ "get_risk": get_risk,
+ "get_why": get_why,
+ "search_codebase": search_codebase,
+ "get_dependency_path": get_dependency_path,
+ "get_dead_code": get_dead_code,
+ "get_architecture_diagram": get_architecture_diagram,
+ }
+
+ registry: dict[str, ToolDef] = {}
+ for schema in _TOOL_SCHEMAS:
+ name = schema["name"]
+ registry[name] = ToolDef(
+ name=name,
+ description=schema["description"],
+ parameters=schema["parameters"],
+ function=func_map[name],
+ artifact_type=schema["artifact_type"],
+ )
+ return registry
+
+
+# Lazy singleton
+_registry: dict[str, ToolDef] | None = None
+
+
+def get_tool_registry() -> dict[str, ToolDef]:
+ """Get the tool registry (lazy-initialized)."""
+ global _registry
+ if _registry is None:
+ _registry = _build_registry()
+ return _registry
+
+
+def get_tool_schemas_for_llm() -> list[dict[str, Any]]:
+ """Return OpenAI-format tool definitions for the LLM."""
+ return [
+ {
+ "type": "function",
+ "function": {
+ "name": schema["name"],
+ "description": schema["description"],
+ "parameters": schema["parameters"],
+ },
+ }
+ for schema in _TOOL_SCHEMAS
+ ]
+
+
+def _make_json_serializable(obj: Any) -> Any:
+ """Recursively ensure an object is JSON-serializable."""
+ if obj is None or isinstance(obj, (bool, int, float, str)):
+ return obj
+ if isinstance(obj, dict):
+ return {str(k): _make_json_serializable(v) for k, v in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [_make_json_serializable(item) for item in obj]
+ if hasattr(obj, "__dict__"):
+ return _make_json_serializable(vars(obj))
+ return str(obj)
+
+
+async def execute_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
+ """Execute a tool by name and return JSON-serializable result."""
+ registry = get_tool_registry()
+ tool_def = registry.get(name)
+ if not tool_def:
+ return {"error": f"Unknown tool: {name}"}
+
+ try:
+ result = await tool_def.function(**arguments)
+ return _make_json_serializable(result)
+ except Exception as exc:
+ logger.exception("Tool execution failed: %s", name)
+ return {"error": f"{type(exc).__name__}: {exc}"}
+
+
+def get_artifact_type(tool_name: str) -> str:
+ """Get the artifact type for a tool's results."""
+ registry = get_tool_registry()
+ tool_def = registry.get(tool_name)
+ return tool_def.artifact_type if tool_def else "unknown"
+
+
+def init_tool_state(
+ session_factory: Any,
+ fts: Any,
+ vector_store: Any,
+ decision_store: Any | None = None,
+ repo_path: str | None = None,
+) -> None:
+ """Bridge FastAPI app state to the MCP server module globals.
+
+ Must be called during app lifespan startup so that direct tool calls
+ from the chat router use the same DB session factory and stores.
+ """
+ import wikicode.server.mcp_server as mcp_mod
+
+ mcp_mod._session_factory = session_factory
+ mcp_mod._fts = fts
+ mcp_mod._vector_store = vector_store
+ if decision_store is not None:
+ mcp_mod._decision_store = decision_store
+ if repo_path is not None:
+ mcp_mod._repo_path = repo_path
+ logger.info("Chat tool state initialized")
diff --git a/packages/server/src/wikicode/server/provider_config.py b/packages/server/src/wikicode/server/provider_config.py
new file mode 100644
index 000000000..38ecc7b46
--- /dev/null
+++ b/packages/server/src/wikicode/server/provider_config.py
@@ -0,0 +1,199 @@
+"""Provider configuration management — API keys, active provider, model selection.
+
+Stores configuration in a server-side JSON file. Environment variables take
+precedence over stored keys for each provider.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Provider catalog (hardcoded — add new providers here)
+# ---------------------------------------------------------------------------
+
+PROVIDER_CATALOG: list[dict[str, Any]] = [
+ {
+ "id": "gemini",
+ "name": "Google Gemini",
+ "default_model": "gemini-3.1-flash-lite-preview",
+ "models": ["gemini-3.1-flash-lite-preview", "gemini-3-flash-preview", "gemini-1.5-pro", "gemini-1.5-flash"],
+ "env_keys": ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
+ "requires_key": True,
+ },
+ {
+ "id": "anthropic",
+ "name": "Anthropic",
+ "default_model": "claude-sonnet-4-6",
+ "models": ["claude-sonnet-4-6", "claude-haiku-4-5"],
+ "env_keys": ["ANTHROPIC_API_KEY"],
+ "requires_key": True,
+ },
+ {
+ "id": "openai",
+ "name": "OpenAI",
+ "default_model": "gpt-4o",
+ "models": ["gpt-4o", "gpt-4o-mini"],
+ "env_keys": ["OPENAI_API_KEY"],
+ "requires_key": True,
+ },
+ {
+ "id": "ollama",
+ "name": "Ollama (Local)",
+ "default_model": "llama3.2",
+ "models": ["llama3.2", "codellama", "deepseek-coder-v2", "qwen2.5-coder"],
+ "env_keys": [],
+ "requires_key": False,
+ },
+ {
+ "id": "litellm",
+ "name": "LiteLLM",
+ "default_model": "groq/llama-3.1-70b-versatile",
+ "models": ["groq/llama-3.1-70b-versatile"],
+ "env_keys": [],
+ "requires_key": True,
+ },
+]
+
+_CATALOG_BY_ID = {p["id"]: p for p in PROVIDER_CATALOG}
+
+
+# ---------------------------------------------------------------------------
+# Config file I/O
+# ---------------------------------------------------------------------------
+
+def _config_path() -> Path:
+ config_dir = os.environ.get("WIKICODE_CONFIG_DIR", "")
+ if config_dir:
+ return Path(config_dir) / "provider_config.json"
+ return Path("provider_config.json")
+
+
+def _load_config() -> dict[str, Any]:
+ path = _config_path()
+ if path.exists():
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ logger.warning("Failed to read provider config, using defaults")
+ return {}
+
+
+def _save_config(config: dict[str, Any]) -> None:
+ path = _config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(config, indent=2), encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+def _get_key_for_provider(provider_id: str) -> str | None:
+ """Get API key: env var takes precedence, then stored config."""
+ catalog = _CATALOG_BY_ID.get(provider_id)
+ if not catalog:
+ return None
+
+ # Check env vars first
+ for env_key in catalog.get("env_keys", []):
+ val = os.environ.get(env_key)
+ if val:
+ return val
+
+ # Check stored config
+ config = _load_config()
+ keys = config.get("keys", {})
+ return keys.get(provider_id)
+
+
+def list_provider_status() -> dict[str, Any]:
+ """Return the full provider status including active selection."""
+ config = _load_config()
+ active_id = config.get("active_provider")
+ active_model = config.get("active_model")
+
+ # Auto-detect active if not set
+ if not active_id:
+ for p in PROVIDER_CATALOG:
+ if _get_key_for_provider(p["id"]) or not p["requires_key"]:
+ active_id = p["id"]
+ active_model = p["default_model"]
+ break
+
+ providers = []
+ for p in PROVIDER_CATALOG:
+ has_key = bool(_get_key_for_provider(p["id"]))
+ configured = has_key or not p["requires_key"]
+ providers.append({
+ "id": p["id"],
+ "name": p["name"],
+ "models": p["models"],
+ "default_model": p["default_model"],
+ "configured": configured,
+ })
+
+ return {
+ "active": {
+ "provider": active_id,
+ "model": active_model or (_CATALOG_BY_ID.get(active_id, {}).get("default_model") if active_id else None),
+ },
+ "providers": providers,
+ }
+
+
+def get_active_provider() -> tuple[str | None, str | None]:
+ """Return (provider_id, model) for the currently active provider."""
+ status = list_provider_status()
+ active = status["active"]
+ return active["provider"], active["model"]
+
+
+def set_active_provider(provider_id: str, model: str | None = None) -> None:
+ """Set the active provider and model. Persists to config file."""
+ if provider_id not in _CATALOG_BY_ID:
+ raise ValueError(f"Unknown provider: {provider_id}")
+ config = _load_config()
+ config["active_provider"] = provider_id
+ config["active_model"] = model or _CATALOG_BY_ID[provider_id]["default_model"]
+ _save_config(config)
+
+
+def set_api_key(provider_id: str, key: str | None) -> None:
+ """Store or remove an API key for a provider."""
+ if provider_id not in _CATALOG_BY_ID:
+ raise ValueError(f"Unknown provider: {provider_id}")
+ config = _load_config()
+ keys = config.setdefault("keys", {})
+ if key:
+ keys[provider_id] = key
+ else:
+ keys.pop(provider_id, None)
+ _save_config(config)
+
+
+def get_chat_provider_instance():
+ """Create a provider instance for chat using the active config.
+
+ Returns a provider that implements both BaseProvider and ChatProvider.
+ """
+ from wikicode.core.providers.registry import get_provider
+
+ provider_id, model = get_active_provider()
+ if not provider_id:
+ raise ValueError("No active provider configured. Set an API key first.")
+
+ api_key = _get_key_for_provider(provider_id)
+ catalog = _CATALOG_BY_ID[provider_id]
+
+ kwargs: dict[str, Any] = {"model": model or catalog["default_model"]}
+ if api_key:
+ kwargs["api_key"] = api_key
+
+ return get_provider(provider_id, with_rate_limiter=False, **kwargs)
diff --git a/packages/server/src/wikicode/server/routers/chat.py b/packages/server/src/wikicode/server/routers/chat.py
new file mode 100644
index 000000000..68c7e4a77
--- /dev/null
+++ b/packages/server/src/wikicode/server/routers/chat.py
@@ -0,0 +1,474 @@
+"""Chat router — SSE streaming agentic loop and conversation management."""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException, Request
+from starlette.responses import StreamingResponse
+
+from wikicode.core.persistence.database import get_session
+from wikicode.core.persistence import crud
+from wikicode.core.providers.base import ChatProvider, ChatStreamEvent, ProviderError
+from wikicode.server.chat_tools import (
+ execute_tool,
+ get_artifact_type,
+ get_tool_schemas_for_llm,
+ init_tool_state,
+)
+from wikicode.server.deps import get_db_session, verify_api_key
+from wikicode.server.provider_config import get_chat_provider_instance, set_active_provider
+from wikicode.server.schemas import (
+ ChatMessageResponse,
+ ChatRequest,
+ ConversationResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(
+ tags=["chat"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+_MAX_AGENTIC_LOOPS = 10
+
+_SYSTEM_PROMPT_TEMPLATE = """You are a codebase intelligence assistant for the repository "{repo_name}" located at {repo_path}.
+
+You have access to 8 specialized tools for querying the codebase wiki, dependency graph, git history, and architectural decisions. Use them proactively — do NOT answer from memory when a tool gives more accurate answers.
+
+Guidelines:
+- Call get_overview first if the user asks about the codebase generally and no prior context exists
+- Pass all relevant targets to get_context and get_risk in a single call — never call the same tool twice for different targets when they can be batched
+- Call get_why for any "why was this built this way" question
+- Call search_codebase for broad questions about where something is implemented
+- Cite specific file paths, function names, and line numbers from tool results — be concrete, not general
+- Format responses in markdown. File paths in backticks. Code in fenced blocks.
+- When tool results contain documentation, synthesize and explain rather than dumping raw content
+- If a tool returns an error, explain what happened and suggest alternatives"""
+
+
+def _build_system_prompt(repo_name: str, repo_path: str) -> str:
+ return _SYSTEM_PROMPT_TEMPLATE.format(repo_name=repo_name, repo_path=repo_path)
+
+
+async def _get_repo_info(factory: Any, repo_id: str) -> tuple[str, str]:
+ """Get repo name and path from DB."""
+ async with get_session(factory) as session:
+ repo = await crud.get_repository(session, repo_id)
+ if not repo:
+ raise HTTPException(404, f"Repository {repo_id} not found")
+ return repo.name, repo.local_path
+
+
+# ---------------------------------------------------------------------------
+# SSE Chat Endpoint
+# ---------------------------------------------------------------------------
+
+
[email protected]("/api/repos/{repo_id}/chat/messages")
+async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
+ """Stream an agentic chat response via SSE."""
+ factory = request.app.state.session_factory
+
+ # Resolve repo
+ repo_name, repo_path = await _get_repo_info(factory, repo_id)
+
+ # Resolve provider (optional per-request override)
+ if body.provider:
+ try:
+ set_active_provider(body.provider, body.model)
+ except ValueError as exc:
+ raise HTTPException(400, str(exc)) from exc
+
+ try:
+ provider = get_chat_provider_instance()
+ except Exception as exc:
+ raise HTTPException(422, f"No chat provider available: {exc}") from exc
+
+ if not isinstance(provider, ChatProvider):
+ raise HTTPException(
+ 422,
+ f"Provider '{provider.provider_name}' does not support streaming chat. "
+ "Configure a provider that supports tool use (Anthropic, OpenAI, Gemini).",
+ )
+
+ async def event_stream():
+ conv_id = body.conversation_id
+ msg_id = ""
+
+ try:
+ # Emit retry interval
+ yield "retry: 3000\n\n"
+
+ # Create or load conversation
+ async with get_session(factory) as session:
+ if conv_id:
+ conv = await crud.get_conversation(session, conv_id)
+ if not conv or conv.repository_id != repo_id:
+ yield _sse_event("error", {"message": "Conversation not found"})
+ return
+ else:
+ title = " ".join(body.message.split()[:6])
+ conv = await crud.create_conversation(
+ session, repository_id=repo_id, title=title
+ )
+ conv_id = conv.id
+
+ # Save user message
+ await crud.create_chat_message(
+ session,
+ conversation_id=conv_id,
+ role="user",
+ content={"text": body.message},
+ )
+
+ # Build message history from DB
+ async with get_session(factory) as session:
+ db_messages = await crud.list_chat_messages(session, conv_id)
+ llm_messages = _db_messages_to_llm_format(db_messages)
+
+ system_prompt = _build_system_prompt(repo_name, repo_path)
+ tool_schemas = get_tool_schemas_for_llm()
+
+ # Tool executor callback — used by providers that run the
+ # agentic loop internally (e.g. Gemini for thought_signature).
+ async def _tool_executor(name: str, args: dict) -> dict:
+ return await execute_tool(name, args)
+
+ # Agentic loop
+ assistant_text_parts: list[str] = []
+ tool_calls_made: list[dict[str, Any]] = []
+
+ for loop_idx in range(_MAX_AGENTIC_LOOPS):
+ stop_reason = None
+ pending_tool_calls: list[dict[str, Any]] = []
+
+ try:
+ async for event in provider.stream_chat(
+ messages=llm_messages,
+ tools=tool_schemas,
+ system_prompt=system_prompt,
+ max_tokens=8192,
+ temperature=0.7,
+ tool_executor=_tool_executor,
+ ):
+ if await request.is_disconnected():
+ return
+
+ if event.type == "text_delta" and event.text:
+ assistant_text_parts.append(event.text)
+ yield _sse_event("data", {
+ "type": "text_delta",
+ "text": event.text,
+ })
+
+ elif event.type == "tool_start" and event.tool_call:
+ tc = event.tool_call
+ pending_tool_calls.append({
+ "id": tc.id,
+ "name": tc.name,
+ "arguments": tc.arguments,
+ })
+ yield _sse_event("data", {
+ "type": "tool_start",
+ "tool_id": tc.id,
+ "tool_name": tc.name,
+ "input": tc.arguments,
+ })
+
+ elif event.type == "tool_result" and event.tool_call:
+ # Provider executed the tool internally (e.g. Gemini).
+ # Emit the result to the frontend.
+ tc = event.tool_call
+ result = event.tool_result_data or {}
+ artifact_type = get_artifact_type(tc.name)
+ summary = _build_tool_summary(tc.name, result)
+
+ yield _sse_event("data", {
+ "type": "tool_result",
+ "tool_id": tc.id,
+ "tool_name": tc.name,
+ "summary": summary,
+ "artifact": {
+ "type": artifact_type,
+ "data": result,
+ },
+ })
+
+ tool_calls_made.append({
+ "id": tc.id,
+ "name": tc.name,
+ "arguments": tc.arguments,
+ "result": result,
+ })
+
+ # Remove from pending since provider already executed it
+ pending_tool_calls = [
+ p for p in pending_tool_calls if p["id"] != tc.id
+ ]
+
+ elif event.type == "stop":
+ stop_reason = event.stop_reason
+
+ except ProviderError as exc:
+ yield _sse_event("data", {
+ "type": "error",
+ "message": str(exc),
+ })
+ return
+
+ # Execute tool calls that weren't handled internally by the provider
+ if pending_tool_calls:
+ # Add assistant message with tool calls to history
+ assistant_text = "".join(assistant_text_parts)
+ assistant_msg: dict[str, Any] = {"role": "assistant"}
+ if assistant_text:
+ assistant_msg["content"] = assistant_text
+ assistant_msg["tool_calls"] = [
+ {
+ "id": tc["id"],
+ "type": "function",
+ "function": {
+ "name": tc["name"],
+ "arguments": json.dumps(tc["arguments"]),
+ },
+ }
+ for tc in pending_tool_calls
+ ]
+ llm_messages.append(assistant_msg)
+ assistant_text_parts.clear()
+
+ # Execute each tool and add results
+ for tc in pending_tool_calls:
+ result = await execute_tool(tc["name"], tc["arguments"])
+ artifact_type = get_artifact_type(tc["name"])
+
+ # Build summary from result
+ summary = _build_tool_summary(tc["name"], result)
+
+ yield _sse_event("data", {
+ "type": "tool_result",
+ "tool_id": tc["id"],
+ "tool_name": tc["name"],
+ "summary": summary,
+ "artifact": {
+ "type": artifact_type,
+ "data": result,
+ },
+ })
+
+ tool_calls_made.append({
+ "id": tc["id"],
+ "name": tc["name"],
+ "arguments": tc["arguments"],
+ "result": result,
+ })
+
+ # Add tool result to LLM history
+ llm_messages.append({
+ "role": "tool",
+ "tool_call_id": tc["id"],
+ "name": tc["name"],
+ "content": json.dumps(result),
+ })
+
+ # Always loop back so the LLM can generate a text
+ # response based on the tool results.
+ continue
+
+ # No pending tool calls — end of generation
+ break
+
+ # Save assistant message to DB
+ final_text = "".join(assistant_text_parts)
+ async with get_session(factory) as session:
+ msg = await crud.create_chat_message(
+ session,
+ conversation_id=conv_id,
+ role="assistant",
+ content={
+ "text": final_text,
+ "tool_calls": tool_calls_made,
+ },
+ )
+ msg_id = msg.id
+ await crud.touch_conversation(session, conv_id)
+
+ yield _sse_event("data", {
+ "type": "done",
+ "conversation_id": conv_id,
+ "message_id": msg_id,
+ })
+
+ except Exception as exc:
+ logger.exception("Chat stream error")
+ yield _sse_event("data", {
+ "type": "error",
+ "message": f"Internal error: {type(exc).__name__}: {exc}",
+ })
+
+ return StreamingResponse(
+ event_stream(),
+ media_type="text/event-stream",
+ headers={
+ "Cache-Control": "no-cache",
+ "X-Accel-Buffering": "no",
+ "Connection": "keep-alive",
+ },
+ )
+
+
+# ---------------------------------------------------------------------------
+# Conversation history endpoints
+# ---------------------------------------------------------------------------
+
+
[email protected]("/api/repos/{repo_id}/chat/conversations")
+async def list_conversations(
+ repo_id: str,
+ session=Depends(get_db_session),
+):
+ convs = await crud.list_conversations(session, repo_id)
+ result = []
+ for c in convs:
+ count = await crud.count_chat_messages(session, c.id)
+ result.append(ConversationResponse.from_orm(c, message_count=count))
+ return result
+
+
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}")
+async def get_conversation(
+ repo_id: str,
+ conversation_id: str,
+ session=Depends(get_db_session),
+):
+ conv = await crud.get_conversation(session, conversation_id)
+ if not conv or conv.repository_id != repo_id:
+ raise HTTPException(404, "Conversation not found")
+
+ messages = await crud.list_chat_messages(session, conversation_id)
+ return {
+ "conversation": ConversationResponse.from_orm(conv, message_count=len(messages)),
+ "messages": [ChatMessageResponse.from_orm(m) for m in messages],
+ }
+
+
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}")
+async def delete_conversation(
+ repo_id: str,
+ conversation_id: str,
+ session=Depends(get_db_session),
+):
+ conv = await crud.get_conversation(session, conversation_id)
+ if not conv or conv.repository_id != repo_id:
+ raise HTTPException(404, "Conversation not found")
+ await crud.delete_conversation(session, conversation_id)
+ return {"ok": True}
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _sse_event(event: str, data: dict[str, Any]) -> str:
+ """Format a single SSE event."""
+ return f"event: {event}\ndata: {json.dumps(data)}\n\n"
+
+
+def _db_messages_to_llm_format(db_messages: list) -> list[dict[str, Any]]:
+ """Convert DB chat messages to OpenAI-format message list."""
+ llm_messages: list[dict[str, Any]] = []
+
+ for msg in db_messages:
+ content = json.loads(msg.content_json) if isinstance(msg.content_json, str) else msg.content_json
+
+ if msg.role == "user":
+ llm_messages.append({
+ "role": "user",
+ "content": content.get("text", ""),
+ })
+ elif msg.role == "assistant":
+ text = content.get("text", "")
+ tool_calls = content.get("tool_calls", [])
+
+ if tool_calls:
+ # Reconstruct the assistant + tool result messages
+ assistant_msg: dict[str, Any] = {"role": "assistant"}
+ if text:
+ assistant_msg["content"] = text
+ assistant_msg["tool_calls"] = [
+ {
+ "id": tc["id"],
+ "type": "function",
+ "function": {
+ "name": tc["name"],
+ "arguments": json.dumps(tc.get("arguments", {})),
+ },
+ }
+ for tc in tool_calls
+ ]
+ llm_messages.append(assistant_msg)
+
+ # Add tool results
+ for tc in tool_calls:
+ llm_messages.append({
+ "role": "tool",
+ "tool_call_id": tc["id"],
+ "name": tc["name"],
+ "content": json.dumps(tc.get("result", {})),
+ })
+ else:
+ llm_messages.append({
+ "role": "assistant",
+ "content": text,
+ })
+
+ return llm_messages
+
+
+def _build_tool_summary(tool_name: str, result: dict[str, Any]) -> str:
+ """Build a short summary string from a tool result."""
+ if "error" in result:
+ return f"Error: {result['error']}"
+
+ if tool_name == "get_overview":
+ title = result.get("title", "")
+ modules = len(result.get("key_modules", []))
+ return f"Overview: {title} ({modules} key modules)"
+
+ if tool_name == "get_context":
+ targets = result.get("targets", {})
+ return f"Context for {len(targets)} target(s)"
+
+ if tool_name == "get_risk":
+ targets = result.get("targets", {})
+ return f"Risk assessment for {len(targets)} file(s)"
+
+ if tool_name == "get_why":
+ mode = result.get("mode", "")
+ if mode == "health":
+ counts = result.get("counts", {})
+ return f"Decision health: {counts.get('active', 0)} active, {counts.get('stale', 0)} stale"
+ decisions = result.get("decisions", [])
+ return f"Found {len(decisions)} decision(s)"
+
+ if tool_name == "search_codebase":
+ results = result.get("results", [])
+ return f"Found {len(results)} result(s)"
+
+ if tool_name == "get_dependency_path":
+ dist = result.get("distance", -1)
+ return f"Path found (distance: {dist})" if dist >= 0 else "No path found"
+
+ if tool_name == "get_dead_code":
+ summary = result.get("summary", {})
+ return f"{summary.get('total_findings', 0)} findings, {summary.get('deletable_lines', 0)} deletable lines"
+
+ if tool_name == "get_architecture_diagram":
+ return f"Generated {result.get('diagram_type', 'diagram')}"
+
+ return "Completed"
diff --git a/packages/server/src/wikicode/server/routers/providers.py b/packages/server/src/wikicode/server/routers/providers.py
new file mode 100644
index 000000000..f0455f49c
--- /dev/null
+++ b/packages/server/src/wikicode/server/routers/providers.py
@@ -0,0 +1,53 @@
+"""Provider management endpoints — list, activate, manage API keys."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, HTTPException
+
+from wikicode.server.deps import verify_api_key
+from wikicode.server.provider_config import (
+ list_provider_status,
+ set_active_provider,
+ set_api_key,
+)
+from wikicode.server.schemas import SetActiveProviderRequest, SetApiKeyRequest
+
+router = APIRouter(
+ prefix="/api/providers",
+ tags=["providers"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+async def get_providers():
+ """List all providers with their status and active selection."""
+ return list_provider_status()
+
+
+async def set_active(body: SetActiveProviderRequest):
+ """Set the active provider and model."""
+ try:
+ set_active_provider(body.provider, body.model)
+ except ValueError as exc:
+ raise HTTPException(400, str(exc)) from exc
+ return list_provider_status()
+
+
[email protected]("/{provider_id}/key", status_code=204)
+async def add_provider_key(provider_id: str, body: SetApiKeyRequest):
+ """Store an API key for a provider."""
+ try:
+ set_api_key(provider_id, body.api_key)
+ except ValueError as exc:
+ raise HTTPException(400, str(exc)) from exc
+
+
[email protected]("/{provider_id}/key", status_code=204)
+async def remove_provider_key(provider_id: str):
+ """Remove a provider's API key."""
+ try:
+ set_api_key(provider_id, None)
+ except ValueError as exc:
+ raise HTTPException(400, str(exc)) from exc
diff --git a/packages/server/src/wikicode/server/schemas.py b/packages/server/src/wikicode/server/schemas.py
index 6d981d012..1e823ccbd 100644
--- a/packages/server/src/wikicode/server/schemas.py
+++ b/packages/server/src/wikicode/server/schemas.py
@@ -592,3 +592,72 @@ class DecisionCreate(BaseModel):
class DecisionStatusUpdate(BaseModel):
status: str
superseded_by: str | None = None
+
+
+# ---------------------------------------------------------------------------
+# Chat
+# ---------------------------------------------------------------------------
+
+
+class ChatRequest(BaseModel):
+ message: str
+ conversation_id: str | None = None
+ provider: str | None = None
+ model: str | None = None
+
+
+class ConversationResponse(BaseModel):
+ id: str
+ repository_id: str
+ title: str
+ message_count: int = 0
+ created_at: datetime
+ updated_at: datetime
+
+ @classmethod
+ def from_orm(cls, obj: object, message_count: int = 0) -> ConversationResponse:
+ return cls(
+ id=obj.id, # type: ignore[attr-defined]
+ repository_id=obj.repository_id, # type: ignore[attr-defined]
+ title=obj.title, # type: ignore[attr-defined]
+ message_count=message_count,
+ created_at=obj.created_at, # type: ignore[attr-defined]
+ updated_at=obj.updated_at, # type: ignore[attr-defined]
+ )
+
+
+class ChatMessageResponse(BaseModel):
+ id: str
+ conversation_id: str
+ role: str
+ content: dict
+ created_at: datetime
+
+ @classmethod
+ def from_orm(cls, obj: object) -> ChatMessageResponse:
+ content_str = obj.content_json # type: ignore[attr-defined]
+ try:
+ content = json.loads(content_str) if isinstance(content_str, str) else content_str
+ except Exception:
+ content = {"text": content_str}
+ return cls(
+ id=obj.id, # type: ignore[attr-defined]
+ conversation_id=obj.conversation_id, # type: ignore[attr-defined]
+ role=obj.role, # type: ignore[attr-defined]
+ content=content,
+ created_at=obj.created_at, # type: ignore[attr-defined]
+ )
+
+
+# ---------------------------------------------------------------------------
+# Providers
+# ---------------------------------------------------------------------------
+
+
+class SetActiveProviderRequest(BaseModel):
+ provider: str
+ model: str | None = None
+
+
+class SetApiKeyRequest(BaseModel):
+ api_key: str
diff --git a/packages/web/package.json b/packages/web/package.json
index dfff04897..c7255f777 100644
--- a/packages/web/package.json
+++ b/packages/web/package.json
@@ -43,7 +43,9 @@
"nuqs": "^2.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
+ "react-markdown": "^10.1.0",
"recharts": "^2.13.0",
+ "remark-gfm": "^4.0.1",
"shiki": "^1.22.0",
"sonner": "^2.0.7",
"swr": "^2.2.5",
diff --git a/packages/web/src/app/repos/[id]/page.tsx b/packages/web/src/app/repos/[id]/page.tsx
index b69761286..bcf118d52 100644
--- a/packages/web/src/app/repos/[id]/page.tsx
+++ b/packages/web/src/app/repos/[id]/page.tsx
@@ -1,28 +1,9 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
-import Link from "next/link";
-import {
- FileText,
- Clock,
- Hash,
- Code2,
- AlertTriangle,
- Network,
- BookOpen,
- Flame,
- Target,
- TrendingDown,
-} from "lucide-react";
-import { getRepo, getRepoStats } from "@/lib/api/repos";
-import { listPages } from "@/lib/api/pages";
-import { listDeadCode } from "@/lib/api/dead-code";
-import { getHotspots } from "@/lib/api/git";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Hash } from "lucide-react";
+import { getRepo } from "@/lib/api/repos";
import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
-import { StatCard } from "@/components/shared/stat-card";
-import { OperationsPanel } from "@/components/repos/operations-panel";
-import { formatNumber } from "@/lib/utils/format";
+import { ChatInterface } from "@/components/chat/chat-interface";
interface Props {
params: Promise<{ id: string }>;
@@ -32,13 +13,13 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { id } = await params;
try {
const repo = await getRepo(id);
- return { title: repo.name };
+ return { title: `${repo.name} — Chat` };
} catch {
return { title: "Repository" };
}
}
-export default async function RepoOverviewPage({ params }: Props) {
+export default async function RepoChatPage({ params }: Props) {
const { id } = await params;
let repo;
@@ -48,226 +29,34 @@ export default async function RepoOverviewPage({ params }: Props) {
notFound();
}
- const [statsResult, lowConfPagesResult, deadExportsResult, hotspotsResult] =
- await Promise.allSettled([
- getRepoStats(id),
- listPages(id, { sort_by: "confidence", order: "asc", limit: 5 }),
- listDeadCode(id, { kind: "unused_export", limit: 5 }),
- getHotspots(id, 5),
- ]);
-
- const stats = statsResult.status === "fulfilled" ? statsResult.value : null;
- const lowConfPages = lowConfPagesResult.status === "fulfilled" ? lowConfPagesResult.value : [];
- const deadExports = deadExportsResult.status === "fulfilled" ? deadExportsResult.value : [];
- const hotspots = hotspotsResult.status === "fulfilled" ? hotspotsResult.value : [];
-
return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1200px]">
- {/* Header */}
- <div className="flex items-start justify-between">
- <div>
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)]">
+ <div className="flex flex-col h-full">
+ {/* Compact header */}
+ <div className="px-4 pt-3 pb-2 flex items-center justify-between shrink-0 border-b border-[var(--color-border-default)]">
+ <div className="min-w-0">
+ <h1 className="text-sm font-semibold text-[var(--color-text-primary)] truncate">
{repo.name}
</h1>
- <p className="text-xs font-mono text-[var(--color-text-tertiary)] mt-0.5">
+ <p className="text-[10px] font-mono text-[var(--color-text-tertiary)] truncate">
{repo.local_path}
</p>
</div>
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-1.5 shrink-0 ml-3">
{repo.head_commit && (
- <Badge variant="outline">
- <Hash className="h-3 w-3" />
+ <Badge variant="outline" className="text-[10px] h-5">
+ <Hash className="h-2.5 w-2.5" />
{repo.head_commit.slice(0, 7)}
</Badge>
)}
- <Badge variant="outline">{repo.default_branch}</Badge>
- </div>
- </div>
-
- {/* Stats strip */}
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
- <StatCard
- label="Files"
- value={stats ? formatNumber(stats.file_count) : "—"}
- icon={<FileText className="h-4 w-4" />}
- />
- <StatCard
- label="Symbols"
- value={stats ? formatNumber(stats.symbol_count) : "—"}
- icon={<Code2 className="h-4 w-4" />}
- />
- <StatCard
- label="Entry Points"
- value={stats ? formatNumber(stats.entry_point_count) : "—"}
- icon={<Target className="h-4 w-4" />}
- />
- <StatCard
- label="Doc Coverage"
- value={stats ? `${stats.doc_coverage_pct.toFixed(0)}%` : "—"}
- icon={<BookOpen className="h-4 w-4" />}
- />
- <StatCard
- label="Freshness"
- value={stats ? `${stats.freshness_score.toFixed(0)}%` : "—"}
- icon={<Clock className="h-4 w-4" />}
- />
- <StatCard
- label="Dead Exports"
- value={stats ? formatNumber(stats.dead_export_count) : "—"}
- icon={<TrendingDown className="h-4 w-4" />}
- />
- </div>
-
- {/* Operations panel */}
- <OperationsPanel repoId={id} repoName={repo.name} />
-
- {/* Two-column content */}
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
- {/* Left: Needs Attention */}
- <div className="space-y-4">
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium flex items-center gap-2">
- <AlertTriangle className="h-4 w-4 text-amber-400" />
- Needs Attention
- </CardTitle>
- </CardHeader>
- <CardContent className="space-y-4">
- {/* Low confidence pages */}
- <div>
- <p className="text-xs text-[var(--color-text-tertiary)] mb-2 uppercase tracking-wider font-medium">
- Low-confidence docs
- </p>
- {lowConfPages.length === 0 ? (
- <p className="text-xs text-[var(--color-text-secondary)]">All pages look good.</p>
- ) : (
- <div className="space-y-1">
- {lowConfPages.map((page) => (
- <Link
- key={page.id}
- href={`/repos/${id}/wiki/${encodeURIComponent(page.target_path)}`}
- className="flex items-center justify-between py-1 px-2 rounded hover:bg-[var(--color-bg-elevated)] group transition-colors"
- >
- <span className="font-mono text-xs text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)] truncate">
- {page.target_path}
- </span>
- <span
- className="ml-2 shrink-0 text-xs tabular-nums font-medium"
- style={{
- color: page.confidence < 0.5 ? "#ef4444" : "#f59e0b",
- }}
- >
- {(page.confidence * 100).toFixed(0)}%
- </span>
- </Link>
- ))}
- </div>
- )}
- </div>
-
- {/* Dead exports */}
- <div>
- <p className="text-xs text-[var(--color-text-tertiary)] mb-2 uppercase tracking-wider font-medium">
- Unused exports
- </p>
- {deadExports.length === 0 ? (
- <p className="text-xs text-[var(--color-text-secondary)]">No unused exports found.</p>
- ) : (
- <div className="space-y-1">
- {deadExports.map((finding) => (
- <Link
- key={finding.id}
- href={`/repos/${id}/dead-code`}
- className="flex items-center justify-between py-1 px-2 rounded hover:bg-[var(--color-bg-elevated)] group transition-colors"
- >
- <div className="flex-1 min-w-0">
- <span className="font-mono text-xs text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)] truncate block">
- {finding.file_path}
- </span>
- {finding.symbol_name && (
- <span className="font-mono text-xs text-[var(--color-text-tertiary)]">
- {finding.symbol_name}
- </span>
- )}
- </div>
- <span className="ml-2 shrink-0 text-xs tabular-nums text-[var(--color-text-tertiary)]">
- {(finding.confidence * 100).toFixed(0)}%
- </span>
- </Link>
- ))}
- </div>
- )}
- </div>
- </CardContent>
- </Card>
- </div>
-
- {/* Right: Most Active */}
- <div>
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium flex items-center gap-2">
- <Flame className="h-4 w-4 text-orange-400" />
- Most Active (30d)
- </CardTitle>
- </CardHeader>
- <CardContent>
- {hotspots.length === 0 ? (
- <p className="text-xs text-[var(--color-text-secondary)]">
- No git activity data yet.
- </p>
- ) : (
- <div className="space-y-1">
- {hotspots.map((hs) => (
- <div
- key={hs.file_path}
- className="flex items-center justify-between py-1 px-2 rounded"
- >
- <div className="flex-1 min-w-0">
- <span className="font-mono text-xs text-[var(--color-text-secondary)] truncate block">
- {hs.file_path}
- </span>
- {hs.primary_owner && (
- <span className="text-xs text-[var(--color-text-tertiary)]">
- {hs.primary_owner}
- </span>
- )}
- </div>
- <div className="ml-2 shrink-0 text-right">
- <span className="text-xs tabular-nums font-medium text-[var(--color-text-primary)]">
- {hs.commit_count_90d}
- </span>
- <span className="text-xs text-[var(--color-text-tertiary)] ml-1">commits</span>
- </div>
- </div>
- ))}
- </div>
- )}
- </CardContent>
- </Card>
+ <Badge variant="outline" className="text-[10px] h-5">
+ {repo.default_branch}
+ </Badge>
</div>
</div>
- {/* CTA buttons */}
- <div className="flex flex-wrap gap-3">
- <Button asChild>
- <Link href={`/repos/${id}/graph`}>
- <Network className="h-4 w-4 mr-2" />
- Explore Graph →
- </Link>
- </Button>
- <Button variant="secondary" asChild>
- <Link href={`/repos/${id}/dead-code`}>
- <TrendingDown className="h-4 w-4 mr-2" />
- View Dead Code →
- </Link>
- </Button>
- <Button variant="secondary" asChild>
- <Link href={`/repos/${id}/wiki`}>
- <BookOpen className="h-4 w-4 mr-2" />
- Browse Docs →
- </Link>
- </Button>
+ {/* Chat interface fills remaining height */}
+ <div className="flex-1 min-h-0">
+ <ChatInterface repoId={id} repoName={repo.name} />
</div>
</div>
);
diff --git a/packages/web/src/components/chat/artifact-panel.tsx b/packages/web/src/components/chat/artifact-panel.tsx
new file mode 100644
index 000000000..0cbd66e38
--- /dev/null
+++ b/packages/web/src/components/chat/artifact-panel.tsx
@@ -0,0 +1,222 @@
+"use client";
+
+import { useState } from "react";
+import { X } from "lucide-react";
+import { cn } from "@/lib/utils/cn";
+import { ChatMarkdown } from "./chat-markdown";
+
+export interface Artifact {
+ type: string;
+ title: string;
+ data: Record<string, unknown>;
+}
+
+interface ArtifactPanelProps {
+ artifacts: Artifact[];
+ open: boolean;
+ onClose: () => void;
+}
+
+export function ArtifactPanel({ artifacts, open, onClose }: ArtifactPanelProps) {
+ const [activeIdx, setActiveIdx] = useState(0);
+
+ if (!open || artifacts.length === 0) return null;
+
+ const active = artifacts[Math.min(activeIdx, artifacts.length - 1)];
+
+ return (
+ <>
+ {/* Mobile: full-screen overlay */}
+ <div className="fixed inset-0 z-[var(--z-modal)] bg-black/50 lg:hidden" onClick={onClose} />
+
+ <div
+ className={cn(
+ "fixed right-0 top-0 z-[var(--z-modal)] h-full bg-[var(--color-bg-surface)] border-l border-[var(--color-border-default)] flex flex-col",
+ "w-full sm:w-[480px] lg:w-[420px]",
+ "transition-transform duration-300",
+ open ? "translate-x-0" : "translate-x-full",
+ )}
+ >
+ {/* Header */}
+ <div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border-default)] shrink-0">
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ Artifacts
+ </span>
+ <button
+ onClick={onClose}
+ className="p-1 rounded hover:bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] transition-colors"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </div>
+
+ {/* Tabs */}
+ {artifacts.length > 1 && (
+ <div className="flex gap-0 border-b border-[var(--color-border-default)] shrink-0 overflow-x-auto px-2">
+ {artifacts.map((art, idx) => (
+ <button
+ key={idx}
+ onClick={() => setActiveIdx(idx)}
+ className={cn(
+ "px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors",
+ idx === activeIdx
+ ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
+ : "border-transparent text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",
+ )}
+ >
+ {art.title || art.type}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {/* Content */}
+ <div className="flex-1 overflow-y-auto p-4">
+ <ArtifactRenderer artifact={active} />
+ </div>
+ </div>
+ </>
+ );
+}
+
+function ArtifactRenderer({ artifact }: { artifact: Artifact }) {
+ const { type, data } = artifact;
+
+ switch (type) {
+ case "overview":
+ case "wiki_page": {
+ const content =
+ (data as Record<string, unknown>).content_md as string ??
+ (data as Record<string, unknown>).content as string ??
+ "";
+ // For get_context with targets
+ const targets = data.targets as Record<string, Record<string, unknown>> | undefined;
+ if (targets) {
+ return (
+ <div className="space-y-4">
+ {Object.entries(targets).map(([target, info]) => {
+ const docs = (info as Record<string, unknown>).docs as Record<string, unknown> | undefined;
+ const md = docs?.content_md as string ?? "";
+ return (
+ <div key={target}>
+ <h3 className="text-xs font-mono text-[var(--color-accent-primary)] mb-2">
+ {target}
+ </h3>
+ {md ? <ChatMarkdown content={md} /> : (
+ <pre className="text-xs font-mono text-[var(--color-text-secondary)] overflow-auto max-h-96">
+ {JSON.stringify(info, null, 2)}
+ </pre>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+ }
+ return content ? <ChatMarkdown content={content} /> : <RawJson data={data} />;
+ }
+
+ case "diagram": {
+ const mermaid = (data.mermaid_syntax as string) ?? "";
+ if (mermaid) {
+ return <MermaidBlock chart={mermaid} />;
+ }
+ return <RawJson data={data} />;
+ }
+
+ case "search_results": {
+ const results = (data.results as Array<Record<string, unknown>>) ?? [];
+ return (
+ <div className="space-y-2">
+ {results.map((r, i) => (
+ <div
+ key={i}
+ className="rounded-lg border border-[var(--color-border-default)] p-3"
+ >
+ <div className="text-xs font-medium text-[var(--color-text-primary)]">
+ {r.title as string}
+ </div>
+ <div className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5">
+ {r.page_type as string} · score: {((r.relevance_score as number) ?? 0).toFixed(2)}
+ </div>
+ {r.snippet && (
+ <p className="text-xs text-[var(--color-text-secondary)] mt-1 line-clamp-3">
+ {r.snippet as string}
+ </p>
+ )}
+ </div>
+ ))}
+ {results.length === 0 && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ No results found.
+ </p>
+ )}
+ </div>
+ );
+ }
+
+ case "risk_report":
+ case "decisions":
+ case "dead_code":
+ case "graph":
+ default:
+ return <RawJson data={data} />;
+ }
+}
+
+function RawJson({ data }: { data: Record<string, unknown> }) {
+ return (
+ <pre className="text-[10px] font-mono text-[var(--color-text-secondary)] overflow-auto max-h-[70vh] whitespace-pre-wrap break-words">
+ {JSON.stringify(data, null, 2)}
+ </pre>
+ );
+}
+
+function MermaidBlock({ chart }: { chart: string }) {
+ // Use dynamic import via useEffect for Mermaid (same pattern as wiki)
+ const [svg, setSvg] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ // Lazy load mermaid
+ import("mermaid").then((mermaid) => {
+ const mermaidInstance = mermaid.default;
+ mermaidInstance.initialize({
+ startOnLoad: false,
+ theme: "dark",
+ themeVariables: {
+ background: "var(--color-bg-surface)",
+ primaryColor: "#5B9CF6",
+ primaryTextColor: "#e2e8f0",
+ lineColor: "#334155",
+ },
+ });
+ const id = `mermaid-artifact-${Math.random().toString(36).slice(2)}`;
+ mermaidInstance
+ .render(id, chart)
+ .then(({ svg: renderedSvg }) => setSvg(renderedSvg))
+ .catch((err: Error) => setError(err.message));
+ });
+
+ if (error) {
+ return (
+ <div className="rounded border border-red-500/30 bg-red-500/10 p-3 text-xs text-red-400">
+ Diagram error: {error}
+ </div>
+ );
+ }
+
+ if (svg) {
+ return (
+ <div
+ className="flex justify-center overflow-x-auto rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4"
+ dangerouslySetInnerHTML={{ __html: svg }}
+ />
+ );
+ }
+
+ return (
+ <div className="flex justify-center p-4">
+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-[var(--color-accent-primary)] border-t-transparent" />
+ </div>
+ );
+}
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
new file mode 100644
index 000000000..7e68d94c3
--- /dev/null
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -0,0 +1,255 @@
+"use client";
+
+import { useRef, useEffect, useState, useCallback } from "react";
+import { Send, StopCircle, PanelRight, MessageSquare } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { useChat } from "@/lib/hooks/use-chat";
+import { ChatMessage } from "./chat-message";
+import { ModelSelector } from "./model-selector";
+import { ConversationHistory } from "./conversation-history";
+import { ArtifactPanel, type Artifact } from "./artifact-panel";
+import { cn } from "@/lib/utils/cn";
+
+interface ChatInterfaceProps {
+ repoId: string;
+ repoName?: string;
+}
+
+const DEFAULT_SUGGESTIONS = [
+ "Give me an overview of this codebase",
+ "What are the highest-risk files to modify?",
+ "Show me the architecture diagram",
+ "What dead code can be safely removed?",
+ "What architectural decisions have been made?",
+ "Search for authentication-related code",
+];
+
+export function ChatInterface({ repoId, repoName }: ChatInterfaceProps) {
+ const {
+ messages,
+ conversationId,
+ isStreaming,
+ error,
+ sendMessage,
+ loadConversation,
+ reset,
+ } = useChat(repoId);
+
+ const [input, setInput] = useState("");
+ const [artifactPanelOpen, setArtifactPanelOpen] = useState(false);
+ const [artifacts, setArtifacts] = useState<Artifact[]>([]);
+ const bottomRef = useRef<HTMLDivElement>(null);
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+
+ const isEmpty = messages.length === 0;
+
+ // Auto-scroll to bottom
+ useEffect(() => {
+ bottomRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, [messages]);
+
+ // Auto-resize textarea
+ useEffect(() => {
+ const ta = textareaRef.current;
+ if (ta) {
+ ta.style.height = "auto";
+ ta.style.height = `${Math.min(ta.scrollHeight, 144)}px`;
+ }
+ }, [input]);
+
+ const handleViewArtifact = useCallback(
+ (artifact: { type: string; data: Record<string, unknown> }) => {
+ const title = (artifact.data.title as string) ?? artifact.type;
+ const newArt: Artifact = { type: artifact.type, title, data: artifact.data };
+
+ setArtifacts((prev) => {
+ const existing = prev.findIndex(
+ (a) => a.type === newArt.type && a.title === newArt.title,
+ );
+ if (existing >= 0) return prev;
+ return [...prev, newArt];
+ });
+ setArtifactPanelOpen(true);
+ },
+ [],
+ );
+
+ async function handleSubmit() {
+ const text = input.trim();
+ if (!text || isStreaming) return;
+ setInput("");
+ if (textareaRef.current) {
+ textareaRef.current.style.height = "auto";
+ }
+ await sendMessage(text);
+ }
+
+ function handleSuggestion(text: string) {
+ setInput(text);
+ textareaRef.current?.focus();
+ }
+
+ // Count artifacts from all messages
+ const totalArtifactCount = messages.reduce(
+ (count, m) =>
+ count + m.toolCalls.filter((tc) => tc.artifact).length,
+ 0,
+ );
+
+ return (
+ <div className="flex h-full flex-col min-h-0">
+ {/* Header bar (when active conversation) */}
+ {!isEmpty && (
+ <div className="flex items-center justify-between px-4 py-2 border-b border-[var(--color-border-default)] shrink-0 bg-[var(--color-bg-surface)]/95 backdrop-blur-sm">
+ <div className="flex items-center gap-2">
+ <ConversationHistory
+ repoId={repoId}
+ activeConversationId={conversationId}
+ onSelect={loadConversation}
+ onNew={reset}
+ />
+ </div>
+ <div className="flex items-center gap-2">
+ {totalArtifactCount > 0 && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 text-xs gap-1"
+ onClick={() => setArtifactPanelOpen(true)}
+ >
+ <PanelRight className="h-3.5 w-3.5" />
+ {totalArtifactCount}
+ </Button>
+ )}
+ <ModelSelector />
+ </div>
+ </div>
+ )}
+
+ {/* Message list or empty state */}
+ <div className="flex-1 min-h-0 relative">
+ {isEmpty ? (
+ <div className="flex flex-col items-center justify-center h-full gap-8 px-4">
+ <div className="text-center space-y-2">
+ <div className="flex items-center justify-center mb-4">
+ <div className="rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] p-3">
+ <MessageSquare className="h-6 w-6 text-[var(--color-accent-primary)]" />
+ </div>
+ </div>
+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">
+ Ask anything about {repoName ?? "this codebase"}
+ </h2>
+ <p className="text-sm text-[var(--color-text-secondary)] max-w-md">
+ Explore architecture, assess risk, search code, trace
+ dependencies, and understand decisions.
+ </p>
+ </div>
+
+ {/* Suggestion chips */}
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-w-lg w-full">
+ {DEFAULT_SUGGESTIONS.map((s) => (
+ <button
+ key={s}
+ className="text-left text-xs text-[var(--color-text-secondary)] rounded-lg border border-[var(--color-border-default)] px-3 py-2.5 hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)] transition-colors"
+ onClick={() => handleSuggestion(s)}
+ >
+ {s}
+ </button>
+ ))}
+ </div>
+
+ {/* Model selector for empty state */}
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ Using:
+ </span>
+ <ModelSelector />
+ <ConversationHistory
+ repoId={repoId}
+ activeConversationId={null}
+ onSelect={loadConversation}
+ onNew={reset}
+ />
+ </div>
+ </div>
+ ) : (
+ <ScrollArea className="h-full">
+ <div className="px-4 py-4 space-y-4 max-w-3xl mx-auto">
+ {messages.map((m) => (
+ <ChatMessage
+ key={m.id}
+ message={m}
+ onViewArtifact={handleViewArtifact}
+ />
+ ))}
+ {error && (
+ <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-xs text-red-400">
+ {error}
+ </div>
+ )}
+ <div ref={bottomRef} />
+ </div>
+ </ScrollArea>
+ )}
+ </div>
+
+ {/* Input area */}
+ <div
+ className={cn(
+ "shrink-0 px-4 py-3",
+ !isEmpty && "border-t border-[var(--color-border-default)]",
+ )}
+ >
+ <div className="max-w-3xl mx-auto">
+ <div
+ className={cn(
+ "flex items-end gap-2 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2",
+ isEmpty && "shadow-lg shadow-black/20",
+ )}
+ >
+ <textarea
+ ref={textareaRef}
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ handleSubmit();
+ }
+ }}
+ placeholder="Ask anything about this codebase..."
+ rows={1}
+ className="flex-1 resize-none bg-transparent text-sm text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none leading-6 max-h-36 overflow-y-auto"
+ style={{ scrollbarWidth: "none" }}
+ />
+ <Button
+ size="icon"
+ className="h-7 w-7 shrink-0"
+ onClick={isStreaming ? reset : handleSubmit}
+ disabled={!input.trim() && !isStreaming}
+ >
+ {isStreaming ? (
+ <StopCircle className="h-3.5 w-3.5" />
+ ) : (
+ <Send className="h-3.5 w-3.5" />
+ )}
+ </Button>
+ </div>
+ {isEmpty && (
+ <p className="text-center text-[10px] text-[var(--color-text-tertiary)] mt-2">
+ Shift+Enter for newline · Enter to send
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Artifact panel */}
+ <ArtifactPanel
+ artifacts={artifacts}
+ open={artifactPanelOpen}
+ onClose={() => setArtifactPanelOpen(false)}
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/components/chat/chat-markdown.tsx b/packages/web/src/components/chat/chat-markdown.tsx
new file mode 100644
index 000000000..db04d7d5b
--- /dev/null
+++ b/packages/web/src/components/chat/chat-markdown.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import type { Components } from "react-markdown";
+
+const components: Components = {
+ h1: ({ children }) => (
+ <h1 className="text-base font-semibold text-[var(--color-text-primary)] mt-4 mb-2">
+ {children}
+ </h1>
+ ),
+ h2: ({ children }) => (
+ <h2 className="text-sm font-semibold text-[var(--color-text-primary)] mt-3 mb-1.5">
+ {children}
+ </h2>
+ ),
+ h3: ({ children }) => (
+ <h3 className="text-sm font-medium text-[var(--color-text-primary)] mt-2 mb-1">
+ {children}
+ </h3>
+ ),
+ p: ({ children }) => (
+ <p className="text-sm text-[var(--color-text-secondary)] leading-relaxed mb-2">
+ {children}
+ </p>
+ ),
+ ul: ({ children }) => (
+ <ul className="list-disc ml-4 text-sm text-[var(--color-text-secondary)] space-y-0.5 mb-2">
+ {children}
+ </ul>
+ ),
+ ol: ({ children }) => (
+ <ol className="list-decimal ml-4 text-sm text-[var(--color-text-secondary)] space-y-0.5 mb-2">
+ {children}
+ </ol>
+ ),
+ li: ({ children }) => <li className="leading-relaxed">{children}</li>,
+ code: ({ className, children, ...props }) => {
+ const isBlock = className?.includes("language-");
+ if (isBlock) {
+ return (
+ <pre className="my-2 rounded-md bg-[var(--color-bg-inset)] border border-[var(--color-border-default)] p-3 overflow-x-auto">
+ <code
+ className="text-xs font-mono text-[var(--color-text-primary)]"
+ {...props}
+ >
+ {children}
+ </code>
+ </pre>
+ );
+ }
+ return (
+ <code
+ className="rounded px-1.5 py-0.5 bg-[var(--color-bg-elevated)] text-[var(--color-accent-primary)] text-xs font-mono"
+ {...props}
+ >
+ {children}
+ </code>
+ );
+ },
+ pre: ({ children }) => <>{children}</>,
+ blockquote: ({ children }) => (
+ <blockquote className="border-l-2 border-[var(--color-accent-primary)] pl-3 my-2 text-sm text-[var(--color-text-secondary)] italic">
+ {children}
+ </blockquote>
+ ),
+ a: ({ href, children }) => (
+ <a
+ href={href}
+ className="text-[var(--color-accent-primary)] hover:underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {children}
+ </a>
+ ),
+ table: ({ children }) => (
+ <div className="overflow-x-auto my-2">
+ <table className="text-xs w-full border-collapse">{children}</table>
+ </div>
+ ),
+ th: ({ children }) => (
+ <th className="text-left px-2 py-1 border-b border-[var(--color-border-default)] text-[var(--color-text-tertiary)] font-medium uppercase tracking-wider text-[10px]">
+ {children}
+ </th>
+ ),
+ td: ({ children }) => (
+ <td className="px-2 py-1 border-b border-[var(--color-border-default)] text-[var(--color-text-secondary)]">
+ {children}
+ </td>
+ ),
+ strong: ({ children }) => (
+ <strong className="font-medium text-[var(--color-text-primary)]">
+ {children}
+ </strong>
+ ),
+ hr: () => <hr className="my-3 border-[var(--color-border-default)]" />,
+};
+
+interface ChatMarkdownProps {
+ content: string;
+}
+
+export function ChatMarkdown({ content }: ChatMarkdownProps) {
+ return (
+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
+ {content}
+ </ReactMarkdown>
+ );
+}
diff --git a/packages/web/src/components/chat/chat-message.tsx b/packages/web/src/components/chat/chat-message.tsx
new file mode 100644
index 000000000..3a8859474
--- /dev/null
+++ b/packages/web/src/components/chat/chat-message.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import { Bot, User } from "lucide-react";
+import { cn } from "@/lib/utils/cn";
+import { ToolCallBlock } from "./tool-call-block";
+import { ChatMarkdown } from "./chat-markdown";
+import type { ChatMessage as ChatMessageType } from "@/lib/hooks/use-chat";
+
+interface ChatMessageProps {
+ message: ChatMessageType;
+ onViewArtifact?: (artifact: { type: string; data: Record<string, unknown> }) => void;
+}
+
+export function ChatMessage({ message, onViewArtifact }: ChatMessageProps) {
+ const isUser = message.role === "user";
+
+ return (
+ <div className={cn("flex gap-3", isUser && "flex-row-reverse")}>
+ {/* Avatar */}
+ <div
+ className={cn(
+ "flex h-7 w-7 shrink-0 items-center justify-center rounded-full mt-0.5",
+ isUser
+ ? "bg-[var(--color-accent-primary)]"
+ : "bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)]",
+ )}
+ >
+ {isUser ? (
+ <User className="h-3.5 w-3.5 text-white" />
+ ) : (
+ <Bot className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ )}
+ </div>
+
+ {/* Content */}
+ <div
+ className={cn(
+ "flex-1 min-w-0",
+ isUser && "flex flex-col items-end",
+ )}
+ >
+ {/* User message */}
+ {isUser && (
+ <div className="rounded-2xl rounded-tr-sm bg-[var(--color-accent-primary)] px-3.5 py-2 text-sm text-white max-w-[85%]">
+ {message.text}
+ </div>
+ )}
+
+ {/* Assistant message */}
+ {!isUser && (
+ <div className="max-w-full space-y-1">
+ {/* Tool calls */}
+ {message.toolCalls.length > 0 && (
+ <div className="space-y-1">
+ {message.toolCalls.map((tc) => (
+ <ToolCallBlock
+ key={tc.id}
+ toolCall={tc}
+ onViewArtifact={
+ tc.artifact && onViewArtifact
+ ? () => onViewArtifact(tc.artifact!)
+ : undefined
+ }
+ />
+ ))}
+ </div>
+ )}
+
+ {/* Text content */}
+ {message.text && (
+ <div className="prose-chat">
+ <ChatMarkdown content={message.text} />
+ </div>
+ )}
+
+ {/* Streaming cursor */}
+ {message.isStreaming &&
+ !message.text &&
+ message.toolCalls.length === 0 && (
+ <div className="flex items-center gap-1.5 py-2">
+ <div className="h-1.5 w-1.5 rounded-full bg-[var(--color-accent-primary)] animate-pulse" />
+ <div
+ className="h-1.5 w-1.5 rounded-full bg-[var(--color-accent-primary)] animate-pulse"
+ style={{ animationDelay: "0.15s" }}
+ />
+ <div
+ className="h-1.5 w-1.5 rounded-full bg-[var(--color-accent-primary)] animate-pulse"
+ style={{ animationDelay: "0.3s" }}
+ />
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/chat/conversation-history.tsx b/packages/web/src/components/chat/conversation-history.tsx
new file mode 100644
index 000000000..12944595d
--- /dev/null
+++ b/packages/web/src/components/chat/conversation-history.tsx
@@ -0,0 +1,131 @@
+"use client";
+
+import { useState } from "react";
+import useSWR from "swr";
+import { History, Plus, Trash2 } from "lucide-react";
+import { cn } from "@/lib/utils/cn";
+import { listConversations, deleteConversation } from "@/lib/api/chat";
+import type { ConversationResponse } from "@/lib/api/types";
+
+interface ConversationHistoryProps {
+ repoId: string;
+ activeConversationId: string | null;
+ onSelect: (id: string) => void;
+ onNew: () => void;
+}
+
+function formatRelativeTime(dateStr: string): string {
+ const diff = Date.now() - new Date(dateStr).getTime();
+ const mins = Math.floor(diff / 60000);
+ if (mins < 1) return "just now";
+ if (mins < 60) return `${mins}m ago`;
+ const hours = Math.floor(mins / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ if (days < 7) return `${days}d ago`;
+ return new Date(dateStr).toLocaleDateString();
+}
+
+export function ConversationHistory({
+ repoId,
+ activeConversationId,
+ onSelect,
+ onNew,
+}: ConversationHistoryProps) {
+ const [open, setOpen] = useState(false);
+ const { data: conversations, mutate } = useSWR<ConversationResponse[]>(
+ open ? `chat-convs:${repoId}` : null,
+ () => listConversations(repoId),
+ { revalidateOnFocus: false },
+ );
+
+ async function handleDelete(convId: string) {
+ await deleteConversation(repoId, convId);
+ await mutate();
+ }
+
+ return (
+ <div className="relative">
+ <button
+ onClick={() => setOpen(!open)}
+ className={cn(
+ "flex items-center gap-1 rounded-md px-2 py-1 text-xs",
+ "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",
+ "hover:bg-[var(--color-bg-elevated)] transition-colors",
+ )}
+ >
+ <History className="h-3.5 w-3.5" />
+ History
+ </button>
+
+ {open && (
+ <>
+ <div
+ className="fixed inset-0 z-[var(--z-dropdown)]"
+ onClick={() => setOpen(false)}
+ />
+ <div className="absolute left-0 top-full mt-1 z-[calc(var(--z-dropdown)+1)] w-72 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-lg overflow-hidden">
+ {/* New conversation */}
+ <button
+ onClick={() => {
+ onNew();
+ setOpen(false);
+ }}
+ className="flex w-full items-center gap-2 px-3 py-2 text-xs text-[var(--color-accent-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors border-b border-[var(--color-border-default)]"
+ >
+ <Plus className="h-3.5 w-3.5" />
+ New conversation
+ </button>
+
+ {/* Conversation list */}
+ <div className="max-h-64 overflow-y-auto">
+ {!conversations && (
+ <div className="px-3 py-4 text-xs text-[var(--color-text-tertiary)] text-center">
+ Loading...
+ </div>
+ )}
+ {conversations?.length === 0 && (
+ <div className="px-3 py-4 text-xs text-[var(--color-text-tertiary)] text-center">
+ No conversations yet
+ </div>
+ )}
+ {conversations?.map((conv) => (
+ <div
+ key={conv.id}
+ className={cn(
+ "flex items-center gap-2 px-3 py-2 hover:bg-[var(--color-bg-elevated)] transition-colors group cursor-pointer",
+ conv.id === activeConversationId &&
+ "bg-[var(--color-accent-muted)]",
+ )}
+ onClick={() => {
+ onSelect(conv.id);
+ setOpen(false);
+ }}
+ >
+ <div className="flex-1 min-w-0">
+ <div className="text-xs text-[var(--color-text-primary)] truncate">
+ {conv.title}
+ </div>
+ <div className="text-[10px] text-[var(--color-text-tertiary)]">
+ {formatRelativeTime(conv.updated_at)} ·{" "}
+ {conv.message_count} msgs
+ </div>
+ </div>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handleDelete(conv.id);
+ }}
+ className="opacity-0 group-hover:opacity-100 p-1 text-[var(--color-text-tertiary)] hover:text-red-400 transition-all"
+ >
+ <Trash2 className="h-3 w-3" />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/components/chat/model-selector.tsx b/packages/web/src/components/chat/model-selector.tsx
new file mode 100644
index 000000000..4001b313b
--- /dev/null
+++ b/packages/web/src/components/chat/model-selector.tsx
@@ -0,0 +1,193 @@
+"use client";
+
+import { useState } from "react";
+import { ChevronDown, Check, Key, X } from "lucide-react";
+import { useProviders } from "@/lib/hooks/use-providers";
+import { cn } from "@/lib/utils/cn";
+
+export function ModelSelector() {
+ const {
+ providers,
+ activeProvider,
+ activeModel,
+ isLoading,
+ activate,
+ saveKey,
+ } = useProviders();
+
+ const [open, setOpen] = useState(false);
+ const [addingKeyFor, setAddingKeyFor] = useState<string | null>(null);
+ const [keyInput, setKeyInput] = useState("");
+ const [saving, setSaving] = useState(false);
+
+ const activeP = providers.find((p) => p.id === activeProvider);
+ const label = activeP
+ ? `${activeP.name} · ${activeModel ?? activeP.default_model}`
+ : "Select model";
+
+ async function handleSelect(providerId: string, model: string) {
+ await activate(providerId, model);
+ setOpen(false);
+ }
+
+ async function handleSaveKey(providerId: string) {
+ if (!keyInput.trim()) return;
+ setSaving(true);
+ try {
+ await saveKey(providerId, keyInput.trim());
+ setAddingKeyFor(null);
+ setKeyInput("");
+ } catch {
+ // error handled by SWR
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <div className="relative">
+ <button
+ onClick={() => setOpen(!open)}
+ className={cn(
+ "flex items-center gap-1.5 rounded-md px-2 py-1 text-xs",
+ "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",
+ "hover:bg-[var(--color-bg-elevated)] transition-colors",
+ "border border-[var(--color-border-default)]",
+ )}
+ >
+ <span className="truncate max-w-[200px]">{isLoading ? "..." : label}</span>
+ <ChevronDown className="h-3 w-3 shrink-0" />
+ </button>
+
+ {open && (
+ <>
+ {/* Backdrop */}
+ <div
+ className="fixed inset-0 z-[var(--z-dropdown)]"
+ onClick={() => {
+ setOpen(false);
+ setAddingKeyFor(null);
+ }}
+ />
+
+ {/* Popover */}
+ <div className="absolute right-0 top-full mt-1 z-[calc(var(--z-dropdown)+1)] w-72 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-lg overflow-hidden">
+ <div className="p-2 space-y-1 max-h-80 overflow-y-auto">
+ {providers.map((provider) => {
+ const isConfigured = provider.configured;
+ return (
+ <div key={provider.id}>
+ {/* Provider header */}
+ <div className="flex items-center justify-between px-2 py-1">
+ <span
+ className={cn(
+ "text-xs font-medium",
+ isConfigured
+ ? "text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-tertiary)]",
+ )}
+ >
+ {provider.name}
+ </span>
+ {!isConfigured && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ setAddingKeyFor(
+ addingKeyFor === provider.id
+ ? null
+ : provider.id,
+ );
+ setKeyInput("");
+ }}
+ className="text-[10px] text-[var(--color-accent-primary)] hover:underline flex items-center gap-0.5"
+ >
+ <Key className="h-3 w-3" />
+ Add key
+ </button>
+ )}
+ </div>
+
+ {/* Add key form */}
+ {addingKeyFor === provider.id && (
+ <div className="px-2 pb-1.5 flex gap-1">
+ <input
+ type="password"
+ value={keyInput}
+ onChange={(e) => setKeyInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter")
+ handleSaveKey(provider.id);
+ }}
+ placeholder="API key..."
+ className="flex-1 rounded border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1 text-xs text-[var(--color-text-primary)] outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)]"
+ autoFocus
+ />
+ <button
+ onClick={() => handleSaveKey(provider.id)}
+ disabled={saving || !keyInput.trim()}
+ className="rounded bg-[var(--color-accent-primary)] px-2 py-1 text-xs text-white disabled:opacity-50"
+ >
+ {saving ? "..." : "Save"}
+ </button>
+ <button
+ onClick={() => {
+ setAddingKeyFor(null);
+ setKeyInput("");
+ }}
+ className="p-1 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </div>
+ )}
+
+ {/* Models */}
+ {isConfigured &&
+ provider.models.map((model) => {
+ const isActive =
+ activeProvider === provider.id &&
+ activeModel === model;
+ return (
+ <button
+ key={model}
+ onClick={() =>
+ handleSelect(provider.id, model)
+ }
+ className={cn(
+ "flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-xs transition-colors",
+ isActive
+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",
+ )}
+ >
+ <span className="flex-1 text-left font-mono truncate">
+ {model}
+ </span>
+ {isActive && (
+ <Check className="h-3 w-3 shrink-0" />
+ )}
+ </button>
+ );
+ })}
+
+ {/* Unconfigured models (greyed) */}
+ {!isConfigured &&
+ provider.models.map((model) => (
+ <div
+ key={model}
+ className="px-3 py-1.5 text-xs font-mono text-[var(--color-text-tertiary)] opacity-50"
+ >
+ {model}
+ </div>
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/components/chat/tool-call-block.tsx b/packages/web/src/components/chat/tool-call-block.tsx
new file mode 100644
index 000000000..181ddbe00
--- /dev/null
+++ b/packages/web/src/components/chat/tool-call-block.tsx
@@ -0,0 +1,95 @@
+"use client";
+
+import { useState } from "react";
+import { ChevronDown, ChevronRight, Loader2, CheckCircle2, ExternalLink } from "lucide-react";
+import { cn } from "@/lib/utils/cn";
+import type { ChatToolCall } from "@/lib/hooks/use-chat";
+
+const TOOL_LABELS: Record<string, string> = {
+ get_overview: "Getting codebase overview",
+ get_context: "Looking up context",
+ get_risk: "Assessing risk",
+ get_why: "Querying decisions",
+ search_codebase: "Searching codebase",
+ get_dependency_path: "Tracing dependency path",
+ get_dead_code: "Checking dead code",
+ get_architecture_diagram: "Generating architecture diagram",
+};
+
+interface ToolCallBlockProps {
+ toolCall: ChatToolCall;
+ onViewArtifact?: () => void;
+}
+
+export function ToolCallBlock({ toolCall, onViewArtifact }: ToolCallBlockProps) {
+ const [expanded, setExpanded] = useState(false);
+ const label = TOOL_LABELS[toolCall.name] ?? toolCall.name;
+ const isRunning = toolCall.status === "running";
+
+ return (
+ <div className="my-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-xs overflow-hidden">
+ <button
+ className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-[var(--color-bg-overlay)] transition-colors"
+ onClick={() => !isRunning && setExpanded((e) => !e)}
+ >
+ {isRunning ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin text-[var(--color-accent-primary)] shrink-0" />
+ ) : (
+ <CheckCircle2 className="h-3.5 w-3.5 text-green-400 shrink-0" />
+ )}
+ <span className="font-medium text-[var(--color-text-secondary)]">
+ {label}
+ </span>
+ {toolCall.summary && !isRunning && (
+ <span className="text-[var(--color-text-tertiary)] truncate ml-1">
+ — {toolCall.summary}
+ </span>
+ )}
+ <span className="ml-auto flex items-center gap-1">
+ {toolCall.artifact && onViewArtifact && !isRunning && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onViewArtifact();
+ }}
+ className="text-[var(--color-accent-primary)] hover:underline flex items-center gap-0.5"
+ >
+ View <ExternalLink className="h-3 w-3" />
+ </button>
+ )}
+ {!isRunning && (
+ expanded ? (
+ <ChevronDown className="h-3 w-3 text-[var(--color-text-tertiary)]" />
+ ) : (
+ <ChevronRight className="h-3 w-3 text-[var(--color-text-tertiary)]" />
+ )
+ )}
+ </span>
+ </button>
+
+ {expanded && (
+ <div className="border-t border-[var(--color-border-default)] px-3 py-2 space-y-2">
+ <div>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium">
+ Input
+ </span>
+ <pre className="mt-1 text-[10px] font-mono text-[var(--color-text-secondary)] overflow-x-auto max-h-32 overflow-y-auto">
+ {JSON.stringify(toolCall.arguments, null, 2)}
+ </pre>
+ </div>
+ {toolCall.result && (
+ <div>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium">
+ Result
+ </span>
+ <pre className="mt-1 text-[10px] font-mono text-[var(--color-text-secondary)] overflow-x-auto max-h-48 overflow-y-auto">
+ {JSON.stringify(toolCall.result, null, 2).slice(0, 2000)}
+ {JSON.stringify(toolCall.result).length > 2000 ? "\n..." : ""}
+ </pre>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index b0273514e..78998cf63 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -8,6 +8,7 @@ import {
BookOpen,
GitBranch,
Lightbulb,
+ MessageSquare,
Search,
Code2,
BarChart3,
@@ -40,7 +41,7 @@ const GLOBAL_NAV: NavItem[] = [
function repoNavItems(repoId: string): NavItem[] {
return [
- { label: "Overview", href: `/repos/${repoId}`, icon: BookOpen },
+ { label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare },
{ label: "Search", href: `/repos/${repoId}/search`, icon: Search },
{ label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },
{ label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },
diff --git a/packages/web/src/lib/api/chat.ts b/packages/web/src/lib/api/chat.ts
new file mode 100644
index 000000000..2eb9def7e
--- /dev/null
+++ b/packages/web/src/lib/api/chat.ts
@@ -0,0 +1,73 @@
+/**
+ * Chat API module — conversation management and SSE message streaming.
+ */
+
+import { apiGet, apiDelete, BASE_URL, buildHeaders } from "./client";
+import type { ConversationResponse, ChatMessageResponse } from "./types";
+
+export async function listConversations(
+ repoId: string,
+): Promise<ConversationResponse[]> {
+ return apiGet<ConversationResponse[]>(
+ `/api/repos/${repoId}/chat/conversations`,
+ );
+}
+
+export async function getConversation(
+ repoId: string,
+ conversationId: string,
+): Promise<{
+ conversation: ConversationResponse;
+ messages: ChatMessageResponse[];
+}> {
+ return apiGet(`/api/repos/${repoId}/chat/conversations/${conversationId}`);
+}
+
+export async function deleteConversation(
+ repoId: string,
+ conversationId: string,
+): Promise<void> {
+ await apiDelete(`/api/repos/${repoId}/chat/conversations/${conversationId}`);
+}
+
+/**
+ * POST a chat message and return the raw Response for SSE streaming.
+ * The caller reads response.body as a ReadableStream.
+ */
+export async function postChatMessage(
+ repoId: string,
+ opts: {
+ message: string;
+ conversationId?: string;
+ provider?: string;
+ model?: string;
+ },
+): Promise<Response> {
+ const url = `${BASE_URL}/api/repos/${repoId}/chat/messages`;
+ const headers = buildHeaders();
+ headers.set("Accept", "text/event-stream");
+
+ const res = await fetch(url, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ message: opts.message,
+ conversation_id: opts.conversationId ?? null,
+ provider: opts.provider ?? null,
+ model: opts.model ?? null,
+ }),
+ });
+
+ if (!res.ok) {
+ let detail = res.statusText;
+ try {
+ const json = (await res.json()) as { detail?: string };
+ detail = json.detail ?? detail;
+ } catch {
+ // not JSON
+ }
+ throw new Error(`Chat error ${res.status}: ${detail}`);
+ }
+
+ return res;
+}
diff --git a/packages/web/src/lib/api/client.ts b/packages/web/src/lib/api/client.ts
new file mode 100644
index 000000000..798ca74ce
--- /dev/null
+++ b/packages/web/src/lib/api/client.ts
@@ -0,0 +1,124 @@
+/**
+ * Base fetch wrapper for the WikiCode REST API.
+ *
+ * Reads the API base URL from NEXT_PUBLIC_WIKICODE_API_URL (default: empty string,
+ * meaning requests go to the same origin — the Next.js rewrite proxies them).
+ *
+ * API key is read from NEXT_PUBLIC_WIKICODE_API_KEY. For production use, the key
+ * should be stored in an httpOnly cookie set by the settings page.
+ */
+
+import type { ApiError } from "./types";
+
+const BASE_URL = process.env.NEXT_PUBLIC_WIKICODE_API_URL ?? "";
+
+function getApiKey(): string | null {
+ // In browser: check localStorage (set by settings page)
+ if (typeof window !== "undefined") {
+ return localStorage.getItem("wikicode_api_key") ?? null;
+ }
+ // In server components: use env var
+ return process.env.WIKICODE_API_KEY ?? process.env.NEXT_PUBLIC_WIKICODE_API_KEY ?? null;
+}
+
+function buildHeaders(extra?: Record<string, string>): Headers {
+ const headers = new Headers({
+ "Content-Type": "application/json",
+ ...extra,
+ });
+ const key = getApiKey();
+ if (key) {
+ headers.set("Authorization", `Bearer ${key}`);
+ }
+ return headers;
+}
+
+class ApiClientError extends Error {
+ constructor(
+ public readonly status: number,
+ public readonly detail: string,
+ ) {
+ super(`API error ${status}: ${detail}`);
+ this.name = "ApiClientError";
+ }
+}
+
+async function handleResponse<T>(res: Response): Promise<T> {
+ if (!res.ok) {
+ let detail = res.statusText;
+ try {
+ const json = (await res.json()) as ApiError;
+ detail = json.detail ?? detail;
+ } catch {
+ // response body is not JSON
+ }
+ throw new ApiClientError(res.status, detail);
+ }
+ return res.json() as Promise<T>;
+}
+
+export async function apiGet<T>(
+ path: string,
+ params?: Record<string, string | number | boolean | undefined>,
+ fetchOptions?: RequestInit,
+): Promise<T> {
+ const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");
+ if (params) {
+ for (const [k, v] of Object.entries(params)) {
+ if (v !== undefined && v !== null) {
+ url.searchParams.set(k, String(v));
+ }
+ }
+ }
+ const res = await fetch(url.toString(), {
+ method: "GET",
+ headers: buildHeaders(),
+ ...fetchOptions,
+ });
+ return handleResponse<T>(res);
+}
+
+export async function apiPost<T>(
+ path: string,
+ body?: unknown,
+ fetchOptions?: RequestInit,
+): Promise<T> {
+ const url = `${BASE_URL}${path}`;
+ const res = await fetch(url, {
+ method: "POST",
+ headers: buildHeaders(),
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ ...fetchOptions,
+ });
+ return handleResponse<T>(res);
+}
+
+export async function apiPatch<T>(
+ path: string,
+ body?: unknown,
+ fetchOptions?: RequestInit,
+): Promise<T> {
+ const url = `${BASE_URL}${path}`;
+ const res = await fetch(url, {
+ method: "PATCH",
+ headers: buildHeaders(),
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ ...fetchOptions,
+ });
+ return handleResponse<T>(res);
+}
+
+export async function apiDelete<T>(
+ path: string,
+ fetchOptions?: RequestInit,
+): Promise<T> {
+ const url = `${BASE_URL}${path}`;
+ const res = await fetch(url, {
+ method: "DELETE",
+ headers: buildHeaders(),
+ ...fetchOptions,
+ });
+ return handleResponse<T>(res);
+}
+
+export { ApiClientError, BASE_URL, buildHeaders };
diff --git a/packages/web/src/lib/api/providers.ts b/packages/web/src/lib/api/providers.ts
new file mode 100644
index 000000000..d1e8989bd
--- /dev/null
+++ b/packages/web/src/lib/api/providers.ts
@@ -0,0 +1,31 @@
+/**
+ * Provider management API module.
+ */
+
+import { apiGet, apiPatch, apiPost, apiDelete } from "./client";
+import type { ProvidersResponse } from "./types";
+
+export async function getProviders(): Promise<ProvidersResponse> {
+ return apiGet<ProvidersResponse>("/api/providers");
+}
+
+export async function setActiveProvider(
+ provider: string,
+ model?: string,
+): Promise<ProvidersResponse> {
+ return apiPatch<ProvidersResponse>("/api/providers/active", {
+ provider,
+ model: model ?? null,
+ });
+}
+
+export async function addProviderKey(
+ providerId: string,
+ apiKey: string,
+): Promise<void> {
+ await apiPost(`/api/providers/${providerId}/key`, { api_key: apiKey });
+}
+
+export async function removeProviderKey(providerId: string): Promise<void> {
+ await apiDelete(`/api/providers/${providerId}/key`);
+}
diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.ts
new file mode 100644
index 000000000..ba5c6c5ce
--- /dev/null
+++ b/packages/web/src/lib/api/types.ts
@@ -0,0 +1,508 @@
+/**
+ * TypeScript types mirroring the backend Pydantic schemas.
+ * Source of truth: packages/server/src/wikicode/server/schemas.py
+ */
+
+// ---------------------------------------------------------------------------
+// Repository
+// ---------------------------------------------------------------------------
+
+export interface RepoCreate {
+ name: string;
+ local_path: string;
+ url?: string;
+ default_branch?: string;
+ settings?: Record<string, unknown>;
+}
+
+export interface RepoUpdate {
+ name?: string;
+ url?: string;
+ default_branch?: string;
+ settings?: {
+ exclude_patterns?: string[];
+ [key: string]: unknown;
+ };
+}
+
+export interface RepoResponse {
+ id: string;
+ name: string;
+ url: string;
+ local_path: string;
+ default_branch: string;
+ head_commit: string | null;
+ settings: Record<string, unknown>;
+ created_at: string;
+ updated_at: string;
+}
+
+// ---------------------------------------------------------------------------
+// Pages
+// ---------------------------------------------------------------------------
+
+export interface PageResponse {
+ id: string;
+ repository_id: string;
+ page_type: string;
+ title: string;
+ content: string;
+ target_path: string;
+ source_hash: string;
+ model_name: string;
+ provider_name: string;
+ input_tokens: number;
+ output_tokens: number;
+ cached_tokens: number;
+ generation_level: number;
+ version: number;
+ confidence: number;
+ freshness_status: string;
+ metadata: Record<string, unknown>;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface PageVersionResponse {
+ id: string;
+ page_id: string;
+ version: number;
+ page_type: string;
+ title: string;
+ content: string;
+ source_hash: string;
+ model_name: string;
+ provider_name: string;
+ input_tokens: number;
+ output_tokens: number;
+ confidence: number;
+ archived_at: string;
+}
+
+export interface PageListResponse {
+ pages: PageResponse[];
+ total: number;
+}
+
+// ---------------------------------------------------------------------------
+// Jobs
+// ---------------------------------------------------------------------------
+
+export interface JobResponse {
+ id: string;
+ repository_id: string;
+ status: "pending" | "running" | "completed" | "failed" | "paused";
+ provider_name: string;
+ model_name: string;
+ total_pages: number;
+ completed_pages: number;
+ failed_pages: number;
+ current_level: number;
+ error_message: string | null;
+ config: Record<string, unknown>;
+ created_at: string;
+ updated_at: string;
+ started_at: string | null;
+ finished_at: string | null;
+}
+
+export interface JobProgressEvent {
+ event: "progress" | "done" | "error";
+ job_id: string;
+ completed_pages: number;
+ total_pages: number;
+ current_page?: string;
+ current_level?: number;
+ tokens_input?: number;
+ tokens_output?: number;
+ estimated_cost?: number;
+ error?: string;
+}
+
+// ---------------------------------------------------------------------------
+// Search
+// ---------------------------------------------------------------------------
+
+export interface SearchRequest {
+ query: string;
+ search_type?: "semantic" | "fulltext";
+ limit?: number;
+}
+
+export interface SearchResultResponse {
+ page_id: string;
+ title: string;
+ page_type: string;
+ target_path: string;
+ score: number;
+ snippet: string;
+ search_type: string;
+}
+
+// ---------------------------------------------------------------------------
+// Symbols
+// ---------------------------------------------------------------------------
+
+export interface SymbolResponse {
+ id: string;
+ repository_id: string;
+ file_path: string;
+ symbol_id: string;
+ name: string;
+ qualified_name: string;
+ kind: string;
+ signature: string;
+ start_line: number;
+ end_line: number;
+ docstring: string | null;
+ visibility: string;
+ is_async: boolean;
+ complexity_estimate: number;
+ language: string;
+ parent_name: string | null;
+}
+
+// ---------------------------------------------------------------------------
+// Graph
+// ---------------------------------------------------------------------------
+
+export interface GraphNodeResponse {
+ node_id: string;
+ node_type: string;
+ language: string;
+ symbol_count: number;
+ pagerank: number;
+ betweenness: number;
+ community_id: number;
+ is_test: boolean;
+ is_entry_point: boolean;
+}
+
+export interface GraphEdgeResponse {
+ source: string;
+ target: string;
+ imported_names: string[];
+}
+
+export interface GraphExportResponse {
+ nodes: GraphNodeResponse[];
+ links: GraphEdgeResponse[];
+}
+
+export interface GraphPathResponse {
+ path: Array<{ node: string; relationship: string; edge_type: string }>;
+ distance: number;
+ explanation: string;
+}
+
+export interface ModuleNodeResponse {
+ module_id: string;
+ file_count: number;
+ symbol_count: number;
+ avg_pagerank: number;
+ doc_coverage_pct: number;
+}
+
+export interface ModuleEdgeResponse {
+ source: string;
+ target: string;
+ edge_count: number;
+}
+
+export interface ModuleGraphResponse {
+ nodes: ModuleNodeResponse[];
+ edges: ModuleEdgeResponse[];
+}
+
+export interface EgoGraphResponse {
+ nodes: GraphNodeResponse[];
+ links: GraphEdgeResponse[];
+ center_node_id: string;
+ center_git_meta: GitMetadataResponse | null;
+ inbound_count: number;
+ outbound_count: number;
+}
+
+export interface NodeSearchResult {
+ node_id: string;
+ language: string;
+ symbol_count: number;
+}
+
+export interface DeadCodeGraphNodeResponse {
+ node_id: string;
+ node_type: string;
+ language: string;
+ symbol_count: number;
+ pagerank: number;
+ betweenness: number;
+ community_id: number;
+ is_test: boolean;
+ is_entry_point: boolean;
+ confidence_group: string;
+}
+
+export interface DeadCodeGraphResponse {
+ nodes: DeadCodeGraphNodeResponse[];
+ links: GraphEdgeResponse[];
+}
+
+export interface HotFilesNodeResponse {
+ node_id: string;
+ node_type: string;
+ language: string;
+ symbol_count: number;
+ pagerank: number;
+ betweenness: number;
+ community_id: number;
+ is_test: boolean;
+ is_entry_point: boolean;
+ commit_count: number;
+}
+
+export interface HotFilesGraphResponse {
+ nodes: HotFilesNodeResponse[];
+ links: GraphEdgeResponse[];
+}
+
+export interface RepoStatsResponse {
+ file_count: number;
+ symbol_count: number;
+ entry_point_count: number;
+ doc_coverage_pct: number;
+ freshness_score: number;
+ dead_export_count: number;
+}
+
+// ---------------------------------------------------------------------------
+// Git Intelligence
+// ---------------------------------------------------------------------------
+
+export interface GitMetadataResponse {
+ file_path: string;
+ commit_count_total: number;
+ commit_count_90d: number;
+ commit_count_30d: number;
+ first_commit_at: string | null;
+ last_commit_at: string | null;
+ primary_owner_name: string | null;
+ primary_owner_email: string | null;
+ primary_owner_commit_pct: number | null;
+ top_authors: Array<{ name: string; email: string; commit_count: number; pct: number }>;
+ significant_commits: Array<{ sha: string; date: string; message: string; author: string }>;
+ co_change_partners: Array<{ file_path: string; co_change_count: number }>;
+ is_hotspot: boolean;
+ is_stable: boolean;
+ churn_percentile: number;
+ age_days: number;
+}
+
+export interface HotspotResponse {
+ file_path: string;
+ commit_count_90d: number;
+ churn_percentile: number;
+ primary_owner: string | null;
+ is_hotspot: boolean;
+}
+
+export interface OwnershipEntry {
+ module_path: string;
+ primary_owner: string | null;
+ owner_pct: number | null;
+ file_count: number;
+ is_silo: boolean;
+}
+
+export interface GitSummaryResponse {
+ total_files: number;
+ hotspot_count: number;
+ stable_count: number;
+ average_churn_percentile: number;
+ top_owners: Array<{ name: string; email: string; file_count: number; pct: number }>;
+}
+
+// ---------------------------------------------------------------------------
+// Dead Code
+// ---------------------------------------------------------------------------
+
+export interface DeadCodeFindingResponse {
+ id: string;
+ kind: string;
+ file_path: string;
+ symbol_name: string | null;
+ symbol_kind: string | null;
+ confidence: number;
+ reason: string;
+ lines: number;
+ safe_to_delete: boolean;
+ primary_owner: string | null;
+ status: string;
+ note: string | null;
+}
+
+export interface DeadCodePatchRequest {
+ status: string;
+ note?: string;
+}
+
+export interface DeadCodeSummaryResponse {
+ total_findings: number;
+ confidence_summary: Record<string, number>;
+ deletable_lines: number;
+ total_lines: number;
+ by_kind: Record<string, number>;
+}
+
+// ---------------------------------------------------------------------------
+// Decisions
+// ---------------------------------------------------------------------------
+
+export interface DecisionRecordResponse {
+ id: string;
+ repository_id: string;
+ title: string;
+ status: "proposed" | "active" | "deprecated" | "superseded";
+ context: string;
+ decision: string;
+ rationale: string;
+ alternatives: string[];
+ consequences: string[];
+ affected_files: string[];
+ affected_modules: string[];
+ tags: string[];
+ source: "git_archaeology" | "inline_marker" | "readme_mining" | "cli";
+ evidence_commits: string[];
+ evidence_file: string | null;
+ evidence_line: number | null;
+ confidence: number;
+ staleness_score: number;
+ superseded_by: string | null;
+ last_code_change: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface DecisionCreate {
+ title: string;
+ context?: string;
+ decision?: string;
+ rationale?: string;
+ alternatives?: string[];
+ consequences?: string[];
+ affected_files?: string[];
+ affected_modules?: string[];
+ tags?: string[];
+}
+
+export interface DecisionStatusUpdate {
+ status: string;
+ superseded_by?: string;
+}
+
+export interface DecisionHealthResponse {
+ summary: {
+ active: number;
+ proposed: number;
+ deprecated: number;
+ superseded: number;
+ stale: number;
+ };
+ stale_decisions: DecisionRecordResponse[];
+ proposed_awaiting_review: DecisionRecordResponse[];
+ ungoverned_hotspots: string[];
+}
+
+// ---------------------------------------------------------------------------
+// Health
+// ---------------------------------------------------------------------------
+
+export interface HealthResponse {
+ status: string;
+ db: string;
+ version: string;
+}
+
+// ---------------------------------------------------------------------------
+// Webhooks
+// ---------------------------------------------------------------------------
+
+export interface WebhookResponse {
+ event_id: string;
+ status: string;
+}
+
+// ---------------------------------------------------------------------------
+// Chat
+// ---------------------------------------------------------------------------
+
+export interface ConversationResponse {
+ id: string;
+ repository_id: string;
+ title: string;
+ message_count: number;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ChatMessageResponse {
+ id: string;
+ conversation_id: string;
+ role: "user" | "assistant";
+ content: {
+ text?: string;
+ tool_calls?: Array<{
+ id: string;
+ name: string;
+ arguments?: Record<string, unknown>;
+ result?: Record<string, unknown>;
+ }>;
+ };
+ created_at: string;
+}
+
+export type ChatSSEEvent =
+ | { type: "text_delta"; text: string }
+ | {
+ type: "tool_start";
+ tool_id: string;
+ tool_name: string;
+ input: Record<string, unknown>;
+ }
+ | {
+ type: "tool_result";
+ tool_id: string;
+ tool_name: string;
+ summary: string;
+ artifact: { type: string; data: Record<string, unknown> };
+ }
+ | { type: "done"; conversation_id: string; message_id: string }
+ | { type: "error"; message: string };
+
+// ---------------------------------------------------------------------------
+// Providers
+// ---------------------------------------------------------------------------
+
+export interface ProviderInfo {
+ id: string;
+ name: string;
+ models: string[];
+ default_model: string;
+ configured: boolean;
+}
+
+export interface ProvidersResponse {
+ active: {
+ provider: string | null;
+ model: string | null;
+ };
+ providers: ProviderInfo[];
+}
+
+// ---------------------------------------------------------------------------
+// API error
+// ---------------------------------------------------------------------------
+
+export interface ApiError {
+ detail: string;
+ status: number;
+}
diff --git a/packages/web/src/lib/hooks/use-chat.ts b/packages/web/src/lib/hooks/use-chat.ts
new file mode 100644
index 000000000..c8c58660e
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-chat.ts
@@ -0,0 +1,244 @@
+"use client";
+
+import { useCallback, useRef, useState } from "react";
+import { postChatMessage, getConversation } from "@/lib/api/chat";
+import type { ChatSSEEvent } from "@/lib/api/types";
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export interface ChatToolCall {
+ id: string;
+ name: string;
+ arguments: Record<string, unknown>;
+ result?: Record<string, unknown>;
+ summary?: string;
+ artifact?: { type: string; data: Record<string, unknown> };
+ status: "running" | "done" | "error";
+}
+
+export interface ChatMessage {
+ id: string;
+ serverId?: string;
+ role: "user" | "assistant";
+ text: string;
+ toolCalls: ChatToolCall[];
+ isStreaming: boolean;
+}
+
+export interface UseChatState {
+ messages: ChatMessage[];
+ conversationId: string | null;
+ isStreaming: boolean;
+ error: string | null;
+}
+
+// ---------------------------------------------------------------------------
+// Hook
+// ---------------------------------------------------------------------------
+
+export function useChat(repoId: string) {
+ const [state, setState] = useState<UseChatState>({
+ messages: [],
+ conversationId: null,
+ isStreaming: false,
+ error: null,
+ });
+
+ const abortRef = useRef<AbortController | null>(null);
+
+ const sendMessage = useCallback(
+ async (text: string, opts?: { provider?: string; model?: string }) => {
+ abortRef.current?.abort();
+ const abort = new AbortController();
+ abortRef.current = abort;
+
+ const userMsgId = `user-${Date.now()}`;
+ const asstMsgId = `asst-${Date.now()}`;
+
+ setState((prev) => ({
+ ...prev,
+ isStreaming: true,
+ error: null,
+ messages: [
+ ...prev.messages,
+ {
+ id: userMsgId,
+ role: "user",
+ text,
+ toolCalls: [],
+ isStreaming: false,
+ },
+ {
+ id: asstMsgId,
+ role: "assistant",
+ text: "",
+ toolCalls: [],
+ isStreaming: true,
+ },
+ ],
+ }));
+
+ try {
+ const res = await postChatMessage(repoId, {
+ message: text,
+ conversationId: state.conversationId ?? undefined,
+ provider: opts?.provider,
+ model: opts?.model,
+ });
+
+ if (!res.body) throw new Error("No response body");
+
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done || abort.signal.aborted) break;
+
+ buffer += decoder.decode(value, { stream: true });
+
+ // Parse SSE lines
+ const lines = buffer.split("\n");
+ buffer = lines.pop() ?? "";
+
+ for (const line of lines) {
+ if (line.startsWith("data: ")) {
+ const data = line.slice(6);
+ try {
+ const parsed = JSON.parse(data) as ChatSSEEvent;
+ handleEvent(parsed, asstMsgId);
+ } catch {
+ // malformed line
+ }
+ }
+ }
+ }
+ } catch (err: unknown) {
+ if (!abort.signal.aborted) {
+ setState((prev) => ({
+ ...prev,
+ isStreaming: false,
+ error: err instanceof Error ? err.message : String(err),
+ messages: prev.messages.map((m) =>
+ m.id === asstMsgId ? { ...m, isStreaming: false } : m,
+ ),
+ }));
+ }
+ }
+
+ function handleEvent(ev: ChatSSEEvent, asstId: string) {
+ setState((prev) => {
+ const messages = prev.messages.map((m) => {
+ if (m.id !== asstId) return m;
+
+ switch (ev.type) {
+ case "text_delta":
+ return { ...m, text: m.text + ev.text };
+
+ case "tool_start":
+ return {
+ ...m,
+ toolCalls: [
+ ...m.toolCalls,
+ {
+ id: ev.tool_id,
+ name: ev.tool_name,
+ arguments: ev.input,
+ status: "running" as const,
+ },
+ ],
+ };
+
+ case "tool_result":
+ return {
+ ...m,
+ toolCalls: m.toolCalls.map((tc) =>
+ tc.id === ev.tool_id
+ ? {
+ ...tc,
+ result: ev.artifact.data,
+ summary: ev.summary,
+ artifact: ev.artifact,
+ status: "done" as const,
+ }
+ : tc,
+ ),
+ };
+
+ case "done":
+ return { ...m, isStreaming: false, serverId: ev.message_id };
+
+ case "error":
+ return { ...m, isStreaming: false };
+
+ default:
+ return m;
+ }
+ });
+
+ return {
+ ...prev,
+ isStreaming:
+ ev.type !== "done" && ev.type !== "error"
+ ? prev.isStreaming
+ : false,
+ conversationId:
+ ev.type === "done" ? ev.conversation_id : prev.conversationId,
+ error: ev.type === "error" ? ev.message : prev.error,
+ messages,
+ };
+ });
+ }
+ },
+ [repoId, state.conversationId],
+ );
+
+ const loadConversation = useCallback(
+ async (conversationId: string) => {
+ try {
+ const data = await getConversation(repoId, conversationId);
+ const msgs: ChatMessage[] = data.messages.map((m) => ({
+ id: m.id,
+ serverId: m.id,
+ role: m.role,
+ text: m.content.text ?? "",
+ toolCalls: (m.content.tool_calls ?? []).map((tc) => ({
+ id: tc.id,
+ name: tc.name,
+ arguments: tc.arguments ?? {},
+ result: tc.result,
+ status: "done" as const,
+ })),
+ isStreaming: false,
+ }));
+ setState({
+ messages: msgs,
+ conversationId,
+ isStreaming: false,
+ error: null,
+ });
+ } catch (err) {
+ setState((prev) => ({
+ ...prev,
+ error: err instanceof Error ? err.message : String(err),
+ }));
+ }
+ },
+ [repoId],
+ );
+
+ const reset = useCallback(() => {
+ abortRef.current?.abort();
+ setState({
+ messages: [],
+ conversationId: null,
+ isStreaming: false,
+ error: null,
+ });
+ }, []);
+
+ return { ...state, sendMessage, loadConversation, reset };
+}
diff --git a/packages/web/src/lib/hooks/use-providers.ts b/packages/web/src/lib/hooks/use-providers.ts
new file mode 100644
index 000000000..d5d12c714
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-providers.ts
@@ -0,0 +1,46 @@
+"use client";
+
+import useSWR from "swr";
+import {
+ getProviders,
+ setActiveProvider,
+ addProviderKey,
+ removeProviderKey,
+} from "@/lib/api/providers";
+import type { ProvidersResponse } from "@/lib/api/types";
+
+export function useProviders() {
+ const { data, mutate, isLoading } = useSWR<ProvidersResponse>(
+ "/api/providers",
+ getProviders,
+ { revalidateOnFocus: false },
+ );
+
+ const activeProvider = data?.active.provider ?? null;
+ const activeModel = data?.active.model ?? null;
+
+ async function activate(providerId: string, model?: string) {
+ await setActiveProvider(providerId, model);
+ await mutate();
+ }
+
+ async function saveKey(providerId: string, key: string) {
+ await addProviderKey(providerId, key);
+ await mutate();
+ }
+
+ async function removeKey(providerId: string) {
+ await removeProviderKey(providerId);
+ await mutate();
+ }
+
+ return {
+ providers: data?.providers ?? [],
+ activeProvider,
+ activeModel,
+ isLoading,
+ activate,
+ saveKey,
+ removeKey,
+ };
+}
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index f69d654f5..ea497995c 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -302,5 +302,7 @@ def test_base_includes_all_models():
"git_metadata",
"dead_code_findings",
"decision_records",
+ "conversations",
+ "chat_messages",
}
assert expected == table_names