antigravity-chat-proxy 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +362 -0
  2. package/app/api/v1/artifacts/[convId]/[filename]/route.ts +75 -0
  3. package/app/api/v1/artifacts/[convId]/route.ts +47 -0
  4. package/app/api/v1/artifacts/active/[filename]/route.ts +50 -0
  5. package/app/api/v1/artifacts/active/route.ts +89 -0
  6. package/app/api/v1/artifacts/route.ts +43 -0
  7. package/app/api/v1/chat/action/route.ts +30 -0
  8. package/app/api/v1/chat/approve/route.ts +21 -0
  9. package/app/api/v1/chat/history/route.ts +23 -0
  10. package/app/api/v1/chat/mode/route.ts +59 -0
  11. package/app/api/v1/chat/new/route.ts +21 -0
  12. package/app/api/v1/chat/reject/route.ts +21 -0
  13. package/app/api/v1/chat/route.ts +105 -0
  14. package/app/api/v1/chat/state/route.ts +23 -0
  15. package/app/api/v1/chat/stream/route.ts +258 -0
  16. package/app/api/v1/conversations/active/route.ts +117 -0
  17. package/app/api/v1/conversations/route.ts +189 -0
  18. package/app/api/v1/conversations/select/route.ts +114 -0
  19. package/app/api/v1/debug/dom/route.ts +30 -0
  20. package/app/api/v1/debug/scrape/route.ts +56 -0
  21. package/app/api/v1/health/route.ts +13 -0
  22. package/app/api/v1/windows/cdp-start/route.ts +32 -0
  23. package/app/api/v1/windows/cdp-status/route.ts +32 -0
  24. package/app/api/v1/windows/close/route.ts +67 -0
  25. package/app/api/v1/windows/open/route.ts +49 -0
  26. package/app/api/v1/windows/recent/route.ts +25 -0
  27. package/app/api/v1/windows/route.ts +27 -0
  28. package/app/api/v1/windows/select/route.ts +35 -0
  29. package/app/debug/page.tsx +228 -0
  30. package/app/favicon.ico +0 -0
  31. package/app/globals.css +1234 -0
  32. package/app/layout.tsx +42 -0
  33. package/app/page.tsx +10 -0
  34. package/bin/cli.js +601 -0
  35. package/components/agent-message.tsx +63 -0
  36. package/components/artifact-panel.tsx +133 -0
  37. package/components/chat-container.tsx +82 -0
  38. package/components/chat-input.tsx +92 -0
  39. package/components/conversation-selector.tsx +97 -0
  40. package/components/header.tsx +302 -0
  41. package/components/hitl-dialog.tsx +23 -0
  42. package/components/message-list.tsx +41 -0
  43. package/components/thinking-block.tsx +14 -0
  44. package/components/tool-call-card.tsx +75 -0
  45. package/components/typing-indicator.tsx +11 -0
  46. package/components/user-message.tsx +13 -0
  47. package/components/welcome-screen.tsx +38 -0
  48. package/hooks/use-artifacts.ts +85 -0
  49. package/hooks/use-chat.ts +278 -0
  50. package/hooks/use-conversations.ts +190 -0
  51. package/lib/actions/hitl.ts +113 -0
  52. package/lib/actions/new-chat.ts +116 -0
  53. package/lib/actions/send-message.ts +31 -0
  54. package/lib/actions/switch-conversation.ts +92 -0
  55. package/lib/cdp/connection.ts +95 -0
  56. package/lib/cdp/process-manager.ts +327 -0
  57. package/lib/cdp/recent-projects.ts +137 -0
  58. package/lib/cdp/selectors.ts +11 -0
  59. package/lib/context.ts +38 -0
  60. package/lib/init.ts +48 -0
  61. package/lib/logger.ts +32 -0
  62. package/lib/scraper/agent-mode.ts +122 -0
  63. package/lib/scraper/agent-state.ts +756 -0
  64. package/lib/scraper/chat-history.ts +138 -0
  65. package/lib/scraper/ide-conversations.ts +124 -0
  66. package/lib/sse/diff-states.ts +141 -0
  67. package/lib/types.ts +146 -0
  68. package/lib/utils.ts +7 -0
  69. package/next.config.ts +7 -0
  70. package/package.json +50 -0
  71. package/public/file.svg +1 -0
  72. package/public/globe.svg +1 -0
  73. package/public/next.svg +1 -0
  74. package/public/vercel.svg +1 -0
  75. package/public/window.svg +1 -0
  76. package/tsconfig.json +34 -0
package/README.md ADDED
@@ -0,0 +1,362 @@
1
+ <div align="center">
2
+
3
+ # 🌐 Antigravity Chat Proxy
4
+
5
+ **Chat with the Antigravity AI Agent from any browser**
6
+
7
+ A Next.js proxy that bridges your browser to the [Antigravity IDE](https://github.com/anthropics/antigravity) via Chrome DevTools Protocol (CDP), providing a real-time chat interface with full access to the agent's capabilities — file operations, terminal commands, search, MCP tools, and more.
8
+
9
+ [![Next.js](https://img.shields.io/badge/Next.js-16-black?logo=next.js)](https://nextjs.org)
10
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-3178C6?logo=typescript)](https://typescriptlang.org)
11
+ [![License](https://img.shields.io/badge/License-MIT-green)](LICENSE)
12
+
13
+ </div>
14
+
15
+ ---
16
+
17
+ ## 📋 Table of Contents
18
+
19
+ - [Overview](#overview)
20
+ - [Architecture](#architecture)
21
+ - [Features](#features)
22
+ - [Getting Started](#getting-started)
23
+ - [API Reference](#api-reference)
24
+ - [Project Structure](#project-structure)
25
+ - [How It Works](#how-it-works)
26
+ - [Configuration](#configuration)
27
+ - [Development](#development)
28
+
29
+ ---
30
+
31
+ ## Overview
32
+
33
+ Antigravity Chat Proxy acts as a bridge between your web browser and the Antigravity IDE (a VS Code fork with an embedded AI agent). It connects to the IDE via **Chrome DevTools Protocol (CDP)** using Puppeteer, scrapes the agent's UI state in real-time, and exposes it through a clean **REST + SSE API** consumed by a React frontend.
34
+
35
+ This enables you to:
36
+ - Chat with the Antigravity agent from **any device** on your network
37
+ - See real-time tool calls, thinking blocks, and responses via **Server-Sent Events**
38
+ - Approve or reject **Human-in-the-Loop (HITL)** actions remotely
39
+ - Browse conversation artifacts and switch between IDE windows
40
+ - Access the full agent experience outside the IDE's native panel
41
+
42
+ ---
43
+
44
+ ## Architecture
45
+
46
+ ```
47
+ ┌─────────────────┐ ┌──────────────────────┐ ┌─────────────────┐
48
+ │ │ │ │ │ │
49
+ │ Browser UI │◄─SSE──│ Next.js Proxy │◄─CDP──│ Antigravity │
50
+ │ (React) │──REST─│ (API Routes) │──────│ IDE (Electron) │
51
+ │ │ │ │ │ │
52
+ └─────────────────┘ └──────────────────────┘ └─────────────────┘
53
+ Port 3000 lib/ services Port 9223
54
+ ```
55
+
56
+ ### Data Flow
57
+
58
+ 1. **User sends a message** → React UI → `POST /api/v1/chat/stream`
59
+ 2. **Proxy types into IDE** → CDP → Puppeteer → Antigravity chat input → `Enter`
60
+ 3. **Proxy polls agent state** → DOM scraping every 500ms → multi-signal running detection
61
+ 4. **State diffs emitted as SSE** → thinking blocks, tool calls, HITL events, responses
62
+ 5. **Frontend renders in real-time** → tool call cards, approve/reject buttons, streaming response HTML
63
+
64
+ ---
65
+
66
+ ## Features
67
+
68
+ ### 🔄 Real-Time SSE Streaming
69
+ State diffing engine compares agent snapshots every 500ms and emits granular typed events:
70
+ - `thinking` — "Thought for 5s" blocks
71
+ - `tool_call` — command execution, file edits, search, MCP tools
72
+ - `hitl` — approval required / approval resolved
73
+ - `response` — streaming HTML response content
74
+ - `notification` — agent notifications
75
+ - `file_change` — file diff indicators
76
+ - `status` — running state transitions
77
+ - `error` — agent error detection
78
+ - `done` — completion with final response
79
+
80
+ ### 🛡️ Multi-Signal Completion Detection
81
+ Avoids premature stream termination using 4 independent signals:
82
+ 1. **Spinner visibility** — CSS animation detection
83
+ 2. **Stop button presence** — aria-label / text matching
84
+ 3. **Pending tool calls** — cancel button without exit code
85
+ 4. **Step group activity** — progress indicators, status text matching
86
+
87
+ ### 🔧 Human-in-the-Loop (HITL)
88
+ Remote approve/reject for destructive operations:
89
+ - One-click approve (`/api/v1/chat/approve`) or reject (`/api/v1/chat/reject`)
90
+ - Per-tool action buttons via `/api/v1/chat/action` with `toolId` + `buttonText`
91
+ - Permission dialog detection for MCP tools and file access
92
+
93
+ ### 📁 Artifact Browser
94
+ Browse and read agent-generated artifacts:
95
+ - List conversations from `~/.gemini/antigravity/brain/`
96
+ - List files per conversation
97
+ - Serve artifact content with proper MIME types
98
+
99
+ ### 🪟 Multi-Window Support
100
+ Connect to any Antigravity workbench window:
101
+ - Auto-discover all `workbench.html` pages via CDP
102
+ - Switch between windows at runtime
103
+ - Environment variable for default window (`PROXY_PAGE`)
104
+
105
+ ### 🎨 Glassmorphism Dark Theme
106
+ Premium UI with:
107
+ - Dark mode with glass-morphism effects and backdrop blur
108
+ - Animated gradient accents (indigo → purple → pink)
109
+ - Tool call cards with status-based coloring and pulse animations
110
+ - Typing indicator, thinking blocks, and HITL dialogs with micro-animations
111
+ - Inter + JetBrains Mono typography via `next/font`
112
+
113
+ ---
114
+
115
+ ## Getting Started
116
+
117
+ ### Prerequisites
118
+
119
+ - **Node.js** ≥ 18
120
+ - **Antigravity IDE** running with remote debugging enabled:
121
+ ```bash
122
+ antigravity --remote-debugging-port=9223
123
+ ```
124
+
125
+ ### Installation
126
+
127
+ ```bash
128
+ git clone <repo-url>
129
+ cd antigravity-chat-proxy-next
130
+ npm install
131
+ ```
132
+
133
+ ### Running
134
+
135
+ ```bash
136
+ # Development (with hot reload)
137
+ npm run dev
138
+
139
+ # Production
140
+ npm run build
141
+ npm start
142
+ ```
143
+
144
+ Open **http://localhost:3000** in your browser.
145
+
146
+ ---
147
+
148
+ ## API Reference
149
+
150
+ All endpoints are versioned under `/api/v1/`.
151
+
152
+ ### Health & Status
153
+
154
+ | Method | Endpoint | Description |
155
+ |--------|----------|-------------|
156
+ | `GET` | `/api/v1/health` | Connection status |
157
+
158
+ ### Chat
159
+
160
+ | Method | Endpoint | Description |
161
+ |--------|----------|-------------|
162
+ | `POST` | `/api/v1/chat` | Send message (blocking — waits for full response) |
163
+ | `POST` | `/api/v1/chat/stream` | Send message (SSE streaming — real-time events) |
164
+ | `GET` | `/api/v1/chat/state` | Current agent panel state snapshot |
165
+ | `GET` | `/api/v1/chat/history` | Full conversation history (scrolls to de-virtualize) |
166
+ | `POST` | `/api/v1/chat/new` | Start a new chat session in the IDE |
167
+ | `POST` | `/api/v1/chat/approve` | Click the approve/run HITL button |
168
+ | `POST` | `/api/v1/chat/reject` | Click the reject/cancel HITL button |
169
+ | `POST` | `/api/v1/chat/action` | Click any footer button by `toolId` + `buttonText` |
170
+
171
+ ### Conversations
172
+
173
+ | Method | Endpoint | Description |
174
+ |--------|----------|-------------|
175
+ | `GET` | `/api/v1/conversations` | List all conversations with metadata |
176
+ | `POST` | `/api/v1/conversations/select` | Set active conversation (switches in IDE) |
177
+ | `GET` | `/api/v1/conversations/active` | Get current active conversation |
178
+
179
+ ### Artifacts
180
+
181
+ | Method | Endpoint | Description |
182
+ |--------|----------|-------------|
183
+ | `GET` | `/api/v1/artifacts` | List all artifact directories |
184
+ | `GET` | `/api/v1/artifacts/:convId` | List files in a conversation |
185
+ | `GET` | `/api/v1/artifacts/:convId/:filename` | Serve a specific artifact file |
186
+
187
+ ### Windows
188
+
189
+ | Method | Endpoint | Description |
190
+ |--------|----------|-------------|
191
+ | `GET` | `/api/v1/windows` | List available Antigravity workbench windows |
192
+ | `POST` | `/api/v1/windows/select` | Switch to a different window |
193
+
194
+ ### Debug
195
+
196
+ | Method | Endpoint | Description |
197
+ |--------|----------|-------------|
198
+ | `GET` | `/api/v1/debug/dom` | Raw HTML dump of the agent panel |
199
+
200
+ ### SSE Event Types
201
+
202
+ When using `/api/v1/chat/stream`, the response is a stream of `data: {JSON}\n\n` lines:
203
+
204
+ ```jsonc
205
+ // Thinking block
206
+ data: {"type":"thinking","time":"Thought for 5s"}
207
+
208
+ // Tool call (new or updated)
209
+ data: {"type":"tool_call","index":0,"id":"0","status":"Running command","type":"command","command":"ls -la","isNew":true}
210
+
211
+ // HITL approval required
212
+ data: {"type":"hitl","action":"approval_required","tool":{...}}
213
+
214
+ // Streaming response (HTML)
215
+ data: {"type":"response","content":"<p>Here are the files...</p>","index":0,"partial":true}
216
+
217
+ // Completion
218
+ data: {"type":"done","finalResponse":"<p>Done!</p>","isHTML":true}
219
+ ```
220
+
221
+ ---
222
+
223
+ ## Project Structure
224
+
225
+ ```
226
+ antigravity-chat-proxy-next/
227
+
228
+ ├── app/ # Next.js App Router
229
+ │ ├── layout.tsx # Root layout (fonts, metadata, global CSS)
230
+ │ ├── page.tsx # Main chat page
231
+ │ ├── globals.css # Consolidated design system (200+ lines)
232
+ │ └── api/v1/ # 18 versioned API routes
233
+ │ ├── health/route.ts
234
+ │ ├── chat/
235
+ │ │ ├── route.ts # POST → blocking chat
236
+ │ │ ├── stream/route.ts # POST → SSE streaming (core endpoint)
237
+ │ │ ├── state/route.ts # GET → agent state snapshot
238
+ │ │ ├── history/route.ts # GET → conversation history
239
+ │ │ ├── new/route.ts # POST → start new chat
240
+ │ │ ├── approve/route.ts # POST → HITL approve
241
+ │ │ ├── reject/route.ts # POST → HITL reject
242
+ │ │ └── action/route.ts # POST → click any button
243
+ │ ├── conversations/ # 3 routes (list, select, active)
244
+ │ ├── artifacts/ # 3 routes (list, files, serve)
245
+ │ ├── windows/ # 2 routes (list, select)
246
+ │ └── debug/dom/route.ts # DOM dump
247
+
248
+ ├── components/ # React UI Components
249
+ │ ├── header.tsx # Logo, status, window selector, new chat
250
+ │ ├── welcome-screen.tsx # Landing screen with quick prompts
251
+ │ ├── message-list.tsx # Scrollable message container
252
+ │ ├── user-message.tsx # User chat bubble
253
+ │ ├── agent-message.tsx # Agent response with steps
254
+ │ ├── tool-call-card.tsx # Tool call visualization
255
+ │ ├── thinking-block.tsx # "Thought for Xs" indicator
256
+ │ ├── hitl-dialog.tsx # Approve/reject dialog
257
+ │ ├── typing-indicator.tsx # Bouncing dots animation
258
+ │ └── chat-input.tsx # Auto-resizing textarea + send btn
259
+
260
+ ├── hooks/
261
+ │ └── use-chat.ts # Central hook: SSE, state, health, HITL
262
+
263
+ ├── lib/ # Server-side services (Node.js only)
264
+ │ ├── types.ts # Shared TypeScript types
265
+ │ ├── context.ts # Singleton shared state (replaces ctx)
266
+ │ ├── init.ts # Lazy CDP initialization
267
+ │ ├── utils.ts # sleep() utility
268
+ │ ├── cdp/
269
+ │ │ ├── connection.ts # Puppeteer CDP connect/discover/select
270
+ │ │ └── selectors.ts # DOM selector constants
271
+ │ ├── scraper/
272
+ │ │ ├── agent-state.ts # Full agent panel scraper (500+ lines)
273
+ │ │ └── chat-history.ts # Conversation history with scroll de-virtualization
274
+ │ ├── actions/
275
+ │ │ ├── send-message.ts # Type + Enter via CDP
276
+ │ │ ├── hitl.ts # Approve/reject/action button clicks
277
+ │ │ ├── new-chat.ts # Multi-strategy new chat button detection
278
+ │ │ └── switch-conversation.ts # Switch active conversation in IDE
279
+ │ └── sse/
280
+ │ └── diff-states.ts # State diffing engine for SSE events
281
+
282
+ ├── next.config.ts
283
+ ├── tsconfig.json
284
+ └── package.json
285
+ ```
286
+
287
+ ---
288
+
289
+ ## How It Works
290
+
291
+ ### CDP Connection
292
+ The proxy connects to Antigravity's Electron app via `puppeteer-core` using the Chrome DevTools Protocol. The IDE must be launched with `--remote-debugging-port=9223`. The connection is established lazily on the first API request and the Puppeteer `Page` instance is reused across all subsequent requests via a module-level singleton.
293
+
294
+ ### DOM Scraping
295
+ The scraper (`lib/scraper/agent-state.ts`) runs inside `page.evaluate()` — a function injected into the IDE's renderer process. It walks the agent side panel DOM to extract:
296
+
297
+ - **Running state** using 4 independent signals (spinner, stop button, pending tools, step indicators)
298
+ - **Thinking blocks** — buttons starting with "Thought for"
299
+ - **Tool calls** — border containers with status headers, commands, terminal output, exit codes
300
+ - **Inline file tools** — file edit/read/search rows with additions/deletions
301
+ - **MCP tools** — tool name, arguments, output
302
+ - **Permission dialogs** — allow/deny button groups
303
+ - **Response blocks** — `.leading-relaxed.select-text` elements (HTML preserved)
304
+ - **Notifications** — `.notify-user-container` blocks
305
+ - **Errors** — text pattern matching for agent termination
306
+ - **File changes** — SVG icon-based diff indicators
307
+
308
+ ### SSE State Diffing
309
+ The diff engine (`lib/sse/diff-states.ts`) compares consecutive agent state snapshots and emits only the changes as typed events. This ensures clients receive granular, efficient updates rather than full state dumps.
310
+
311
+ ### Virtualization Handling
312
+ The IDE uses DOM virtualization for long conversations. The scraper handles this by:
313
+ - **Chat history**: Scrolling from top to bottom in increments to force all content to render
314
+ - **Tool calls**: Assigning persistent `data-proxy-tool-id` attributes and tracking tools in a session-scoped `Map` that survives DOM recycling
315
+ - **Responses**: Accumulating responses in a session array that only grows, never shrinks
316
+
317
+ ---
318
+
319
+ ## Configuration
320
+
321
+ | Variable | Default | Description |
322
+ |----------|---------|-------------|
323
+ | `CDP_PORT` | `9223` | Remote debugging port of the Antigravity IDE |
324
+ | `PROXY_PAGE` | `0` | Index of the workbench window to connect to |
325
+ | `PORT` | `3000` | Next.js server port |
326
+
327
+ ---
328
+
329
+ ## Development
330
+
331
+ ```bash
332
+ # Start dev server with hot reload
333
+ npm run dev
334
+
335
+ # Type check
336
+ npx tsc --noEmit
337
+
338
+ # Production build
339
+ npm run build
340
+
341
+ # Start production server
342
+ npm start
343
+ ```
344
+
345
+ ### Key Design Decisions
346
+
347
+ | Decision | Rationale |
348
+ |----------|-----------|
349
+ | **Module singleton** for shared state | Next.js API routes share the Node.js process — a module-level object persists across requests without global state hacks |
350
+ | **Lazy CDP init** | Connection is established on first API call, not at import time — avoids crashes when IDE isn't running |
351
+ | **API versioning** (`/api/v1/`) | Future-proofs the API for breaking changes without disrupting existing consumers |
352
+ | **`legacy.js` dropped** | The 5 blocking helper functions were superseded by the SSE streaming path — the blocking `/api/v1/chat` endpoint uses the scraper directly instead |
353
+ | **HTML response preservation** | `innerHTML` extraction preserves rich formatting (code blocks, lists, links) from the agent's output |
354
+ | **Multi-signal completion** | Using a single signal (e.g., spinner) is unreliable — combining 4 signals prevents premature stream termination |
355
+
356
+ ---
357
+
358
+ <div align="center">
359
+
360
+ **Built with [Next.js](https://nextjs.org) · [Puppeteer](https://pptr.dev) · [TypeScript](https://typescriptlang.org)**
361
+
362
+ </div>
@@ -0,0 +1,75 @@
1
+ import { NextResponse, NextRequest } from 'next/server';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import os from 'os';
5
+
6
+ export const dynamic = 'force-dynamic';
7
+
8
+ const BRAIN_DIR = path.join(os.homedir(), '.gemini', 'antigravity', 'brain');
9
+
10
+ const MIME_TYPES: Record<string, string> = {
11
+ '.md': 'text/markdown; charset=utf-8',
12
+ '.txt': 'text/plain; charset=utf-8',
13
+ '.json': 'application/json; charset=utf-8',
14
+ '.html': 'text/html; charset=utf-8',
15
+ '.css': 'text/css; charset=utf-8',
16
+ '.js': 'text/javascript; charset=utf-8',
17
+ '.ts': 'text/typescript; charset=utf-8',
18
+ '.yaml': 'text/yaml; charset=utf-8',
19
+ '.yml': 'text/yaml; charset=utf-8',
20
+ '.png': 'image/png',
21
+ '.jpg': 'image/jpeg',
22
+ '.jpeg': 'image/jpeg',
23
+ '.gif': 'image/gif',
24
+ '.svg': 'image/svg+xml',
25
+ '.webp': 'image/webp',
26
+ };
27
+
28
+ /**
29
+ * GET /api/v1/artifacts/[convId]/[filename] — serve a specific artifact file.
30
+ */
31
+ export async function GET(
32
+ _request: NextRequest,
33
+ { params }: { params: Promise<{ convId: string; filename: string }> }
34
+ ) {
35
+ const { convId, filename } = await params;
36
+ const sanitizedConv = convId.replace(/[^a-zA-Z0-9\-_]/g, '');
37
+ const sanitizedFile = filename.replace(/[^a-zA-Z0-9\-_.]/g, '');
38
+ const filePath = path.join(BRAIN_DIR, sanitizedConv, sanitizedFile);
39
+
40
+ // Security: ensure file is within BRAIN_DIR
41
+ const resolved = path.resolve(filePath);
42
+ if (!resolved.startsWith(BRAIN_DIR)) {
43
+ return NextResponse.json(
44
+ { error: 'Access denied' },
45
+ { status: 403 }
46
+ );
47
+ }
48
+
49
+ if (!fs.existsSync(filePath)) {
50
+ return NextResponse.json(
51
+ { error: 'File not found' },
52
+ { status: 404 }
53
+ );
54
+ }
55
+
56
+ try {
57
+ const ext = path.extname(sanitizedFile).toLowerCase();
58
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
59
+ const isText = contentType.startsWith('text/') || contentType.includes('json');
60
+
61
+ if (isText) {
62
+ const content = fs.readFileSync(filePath, 'utf-8');
63
+ return new Response(content, {
64
+ headers: { 'Content-Type': contentType },
65
+ });
66
+ } else {
67
+ const buffer = fs.readFileSync(filePath);
68
+ return new Response(buffer, {
69
+ headers: { 'Content-Type': contentType },
70
+ });
71
+ }
72
+ } catch (err: any) {
73
+ return NextResponse.json({ error: err.message }, { status: 500 });
74
+ }
75
+ }
@@ -0,0 +1,47 @@
1
+ import { NextResponse, NextRequest } from 'next/server';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import os from 'os';
5
+
6
+ export const dynamic = 'force-dynamic';
7
+
8
+ const BRAIN_DIR = path.join(os.homedir(), '.gemini', 'antigravity', 'brain');
9
+
10
+ /**
11
+ * GET /api/v1/artifacts/[convId] — list files in a conversation directory.
12
+ */
13
+ export async function GET(
14
+ _request: NextRequest,
15
+ { params }: { params: Promise<{ convId: string }> }
16
+ ) {
17
+ const { convId } = await params;
18
+ const sanitized = convId.replace(/[^a-zA-Z0-9\-_]/g, '');
19
+ const convDir = path.join(BRAIN_DIR, sanitized);
20
+
21
+ if (!fs.existsSync(convDir)) {
22
+ return NextResponse.json(
23
+ { error: 'Conversation not found' },
24
+ { status: 404 }
25
+ );
26
+ }
27
+
28
+ try {
29
+ const files = fs
30
+ .readdirSync(convDir)
31
+ .filter(
32
+ (f) =>
33
+ !f.startsWith('.') && fs.statSync(path.join(convDir, f)).isFile()
34
+ )
35
+ .map((f) => {
36
+ const stat = fs.statSync(path.join(convDir, f));
37
+ return {
38
+ name: f,
39
+ size: stat.size,
40
+ mtime: stat.mtime.toISOString(),
41
+ };
42
+ });
43
+ return NextResponse.json({ convId: sanitized, files });
44
+ } catch (err: any) {
45
+ return NextResponse.json({ error: err.message }, { status: 500 });
46
+ }
47
+ }
@@ -0,0 +1,50 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import ctx from '@/lib/context';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import os from 'os';
6
+
7
+ export const dynamic = 'force-dynamic';
8
+
9
+ const BRAIN_DIR = path.join(os.homedir(), '.gemini', 'antigravity', 'brain');
10
+
11
+ /**
12
+ * GET /api/v1/artifacts/active/[filename] — serve a file from the active conversation.
13
+ */
14
+ export async function GET(
15
+ _request: NextRequest,
16
+ { params }: { params: Promise<{ filename: string }> }
17
+ ) {
18
+ const { filename } = await params;
19
+
20
+ if (!ctx.activeConversationId) {
21
+ return NextResponse.json({ error: 'No active conversation' }, { status: 404 });
22
+ }
23
+
24
+ const filePath = path.join(BRAIN_DIR, ctx.activeConversationId, filename);
25
+ const resolved = path.resolve(filePath);
26
+ const expected = path.resolve(path.join(BRAIN_DIR, ctx.activeConversationId));
27
+ if (!resolved.startsWith(expected)) {
28
+ return NextResponse.json({ error: 'Invalid path' }, { status: 403 });
29
+ }
30
+
31
+ if (!fs.existsSync(resolved)) {
32
+ return NextResponse.json({ error: 'File not found' }, { status: 404 });
33
+ }
34
+
35
+ const content = fs.readFileSync(resolved, 'utf-8');
36
+ const ext = path.extname(filename).toLowerCase();
37
+ const mimeTypes: Record<string, string> = {
38
+ '.md': 'text/markdown',
39
+ '.json': 'application/json',
40
+ '.ts': 'text/typescript',
41
+ '.tsx': 'text/typescript',
42
+ '.css': 'text/css',
43
+ '.txt': 'text/plain',
44
+ };
45
+ const contentType = mimeTypes[ext] || 'text/plain';
46
+
47
+ return new NextResponse(content, {
48
+ headers: { 'Content-Type': contentType },
49
+ });
50
+ }
@@ -0,0 +1,89 @@
1
+ import { NextResponse } from 'next/server';
2
+ import ctx from '@/lib/context';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import os from 'os';
6
+
7
+ export const dynamic = 'force-dynamic';
8
+
9
+ const BRAIN_DIR = path.join(os.homedir(), '.gemini', 'antigravity', 'brain');
10
+
11
+ /**
12
+ * Auto-detect the most recently modified conversation directory.
13
+ * Ensures the artifact panel works even before a conversation is explicitly selected.
14
+ */
15
+ function autoDetectActiveConversation(): string | null {
16
+ try {
17
+ if (!fs.existsSync(BRAIN_DIR)) return null;
18
+ const entries = fs.readdirSync(BRAIN_DIR, { withFileTypes: true });
19
+ let latest: { id: string; mtime: number } | null = null;
20
+
21
+ for (const entry of entries) {
22
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
23
+ const dirPath = path.join(BRAIN_DIR, entry.name);
24
+ const stat = fs.statSync(dirPath);
25
+ if (!latest || stat.mtimeMs > latest.mtime) {
26
+ latest = { id: entry.name, mtime: stat.mtimeMs };
27
+ }
28
+ }
29
+ return latest?.id ?? null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * GET /api/v1/artifacts/active — list files in the active conversation directory.
37
+ * Auto-detects active conversation on first load if none is set.
38
+ */
39
+ export async function GET() {
40
+ try {
41
+ // Auto-detect on first load if no conversation has been selected yet
42
+ if (!ctx.activeConversationId && !ctx.activeTitle) {
43
+ ctx.activeConversationId = autoDetectActiveConversation();
44
+ }
45
+
46
+ if (!ctx.activeConversationId) {
47
+ return NextResponse.json({ files: [] }); // Graceful empty state
48
+ }
49
+
50
+ const convDir = path.join(BRAIN_DIR, ctx.activeConversationId);
51
+ if (!fs.existsSync(convDir)) {
52
+ return NextResponse.json({ files: [] });
53
+ }
54
+
55
+ const files: any[] = [];
56
+ const entries = fs.readdirSync(convDir, { recursive: true, withFileTypes: true });
57
+
58
+ for (const d of entries) {
59
+ if (!d.isFile() || !d.name.endsWith('.md')) continue;
60
+
61
+ // Node 20+ uses parentPath, older Node might use path. Fallback to convDir just in case
62
+ // @ts-ignore
63
+ const parentDir = d.parentPath || d.path || convDir;
64
+ const fullPath = path.join(parentDir, d.name);
65
+ const relPath = path.relative(convDir, fullPath).replace(/\\/g, '/');
66
+
67
+ // Skip hidden folders like .system_generated
68
+ if (relPath.split('/').some(p => p.startsWith('.'))) continue;
69
+
70
+ try {
71
+ const stats = fs.statSync(fullPath);
72
+ files.push({
73
+ name: relPath, // Return the relative path, e.g. "browser/scratchpad.md"
74
+ size: stats.size,
75
+ mtime: stats.mtime.toISOString(),
76
+ });
77
+ } catch {
78
+ continue;
79
+ }
80
+ }
81
+
82
+ // Sort newest first
83
+ files.sort((a: any, b: any) => new Date(b.mtime).getTime() - new Date(a.mtime).getTime());
84
+
85
+ return NextResponse.json({ files });
86
+ } catch (err: any) {
87
+ return NextResponse.json({ error: err.message }, { status: 500 });
88
+ }
89
+ }
@@ -0,0 +1,43 @@
1
+ import { NextResponse } from 'next/server';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import os from 'os';
5
+
6
+ export const dynamic = 'force-dynamic';
7
+
8
+ const BRAIN_DIR = path.join(os.homedir(), '.gemini', 'antigravity', 'brain');
9
+
10
+ /**
11
+ * GET /api/v1/artifacts — list all conversation directories with artifact files.
12
+ */
13
+ export async function GET() {
14
+ try {
15
+ if (!fs.existsSync(BRAIN_DIR)) {
16
+ return NextResponse.json({ artifacts: [] });
17
+ }
18
+
19
+ const dirs = fs
20
+ .readdirSync(BRAIN_DIR, { withFileTypes: true })
21
+ .filter((d) => d.isDirectory() && !d.name.startsWith('.'))
22
+ .map((d) => {
23
+ const dirPath = path.join(BRAIN_DIR, d.name);
24
+ try {
25
+ const files = fs
26
+ .readdirSync(dirPath)
27
+ .filter(
28
+ (f) =>
29
+ !f.startsWith('.') &&
30
+ fs.statSync(path.join(dirPath, f)).isFile()
31
+ );
32
+ return { id: d.name, fileCount: files.length };
33
+ } catch {
34
+ return { id: d.name, fileCount: 0 };
35
+ }
36
+ })
37
+ .filter((d) => d.fileCount > 0);
38
+
39
+ return NextResponse.json({ artifacts: dirs });
40
+ } catch (err: any) {
41
+ return NextResponse.json({ error: err.message }, { status: 500 });
42
+ }
43
+ }