diff --git a/.forgejo/workflows/deploy.yaml b/.forgejo/workflows/deploy.yaml new file mode 100644 index 0000000..8f73b9d --- /dev/null +++ b/.forgejo/workflows/deploy.yaml @@ -0,0 +1,39 @@ +name: Deploy to Nexus Vector + +on: + push: + branches: + - master + - main + +jobs: + deploy: + runs-on: docker + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Setup SSH + uses: webfactory/ssh-agent@v0.8.0 + with: + ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }} + + - name: Add Host Key + run: | + mkdir -p ~/.ssh + ssh-keyscan -p 2222 -H nexus-vector >> ~/.ssh/known_hosts + ssh-keyscan -p 2222 -H git.runfoo.run >> ~/.ssh/known_hosts + # Fallback for direct IP or alias if runner is local + echo "Host nexus-vector" >> ~/.ssh/config + echo " HostName nexus-vector" >> ~/.ssh/config + echo " Port 2222" >> ~/.ssh/config + echo " User admin" >> ~/.ssh/config + echo " StrictHostKeyChecking no" >> ~/.ssh/config + + - name: Deploy Monorepo via Rsync + run: | + rsync -avz -e "ssh -p 2222" --exclude '.git' --exclude 'node_modules' --exclude 'apps/web/node_modules' --exclude '.next' ./ admin@nexus-vector:/srv/containers/kites/ + + - name: Restart Kites Service + run: | + ssh -p 2222 admin@nexus-vector "cd /srv/containers/kites && docker compose up -d --build kites" diff --git a/.github/prompts/plan.prompt.md b/.github/prompts/plan.prompt.md new file mode 100644 index 0000000..973e2d0 --- /dev/null +++ b/.github/prompts/plan.prompt.md @@ -0,0 +1,8 @@ +You are a Tech Lead. +Your goal is to detail the implementation plan. + +**Instructions:** +1. Read the `spec.md`. +2. Update `plan.md` with file-level details. +3. Consider the stack: Next.js 16 (App Router), Drizzle ORM, Postgres, Tauri (Client). +4. Address deployment implications (Docker, Traefik). diff --git a/.github/prompts/specify.prompt.md b/.github/prompts/specify.prompt.md new file mode 100644 index 0000000..f9a9a5a --- /dev/null +++ b/.github/prompts/specify.prompt.md @@ -0,0 +1,12 @@ +You are a System Architect. +Your goal is to create or update technical specifications in `specs/`. + +**Instructions:** +1. Read `.specify/memory/constitution.md`. +2. Analyze the request. +3. Draft `spec.md` (What/Why), `plan.md` (How/Architecture), and `tasks.md` (Execution). +4. Ensure the spec respects the Hybrid Architecture (Next.js + Tauri). + +**Constraints:** +- Keep it pragmatic. +- Postgres is the source of truth. diff --git a/.github/prompts/tasks.prompt.md b/.github/prompts/tasks.prompt.md new file mode 100644 index 0000000..9565efc --- /dev/null +++ b/.github/prompts/tasks.prompt.md @@ -0,0 +1,8 @@ +You are a Senior Developer. +Your goal is to break down the work into actionable tasks. + +**Instructions:** +1. Read `spec.md` and `plan.md`. +2. Update `tasks.md`. +3. Group tasks by component: [Backend], [Frontend], [Client], [Infra]. +4. Mark dependencies. diff --git a/.specify/memory/constitution.md b/.specify/memory/constitution.md new file mode 100644 index 0000000..5c1ac3b --- /dev/null +++ b/.specify/memory/constitution.md @@ -0,0 +1,7 @@ +# Project Constitution + +1. **Hybrid Architecture:** Kites is a hybrid platform. The "Brain" is a Next.js web application (Nexus/Web), and the "Hand" is a native Desktop Client (Tauri). +2. **Privacy-First:** User data is sensitive. Default to private visibility. API access requires strict authentication (Session or API Key). +3. **Agent-Native:** We build for both humans and AI. The data model (Sessions, Tags, Content) must support structured agent output (e.g., "Run ID", "Agent Name"). +4. **Spec-Driven:** Major changes start with a spec in `specs/`. We document *why* before we code *how*. +5. **Infrastructure:** We deploy to a self-hosted VPS (Nexus Vector) using Docker Compose and Traefik. Database is PostgreSQL. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..80254f6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,63 @@ +FROM node:22-alpine AS base + +# Install dependencies only when needed +FROM base AS deps +WORKDIR /app +COPY package.json package-lock.json* ./ +RUN npm install + +# Rebuild the source code only when needed +FROM base AS builder +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY . . + +# Generate migration SQL files +# RUN npx drizzle-kit generate <-- DISABLED: We are providing generated migrations with custom edits + +# Build Next.js +ENV NEXT_TELEMETRY_DISABLED=1 +RUN npm run build + +# Production image, copy all the files and run next +FROM base AS runner +WORKDIR /app + +ENV NODE_ENV=production +ENV NEXT_TELEMETRY_DISABLED=1 + +RUN addgroup --system --gid 1001 nodejs +RUN adduser --system --uid 1001 nextjs + +# Copy public folder +COPY --from=builder /app/public ./public + +# Set permission for prerender cache +RUN mkdir .next +RUN chown nextjs:nodejs .next + +# Automatically leverage output traces to reduce image size +COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ +COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static + +# Copy migrations and migration script +# Ensure we copy from the source (which now includes them via COPY . . in builder) +COPY --from=builder --chown=nextjs:nodejs /app/drizzle ./drizzle +COPY --from=builder --chown=nextjs:nodejs /app/src/db/migrate.ts ./src/db/migrate.ts + +# Runtime dependencies +RUN npm install -g tsx +RUN npm install drizzle-orm pg dotenv + +# Copy the source so tsx can run migrate.ts +COPY --from=builder --chown=nextjs:nodejs /app/src ./src + +USER nextjs + +EXPOSE 3000 + +ENV PORT=3000 +ENV HOSTNAME="0.0.0.0" + +# Custom entrypoint to run migrations then start app +CMD ["sh", "-c", "npx tsx src/db/migrate.ts && node server.js"] diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100644 index 0000000..e3485a3 --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,92 @@ +# Kites - Agentic Pastebin + +Kites is a clean, agent-native pastebin service designed for LLMs and humans. It features a simple API, structured data model (Sessions, Tags), and a polished UI. + +## Features + +- **Agent-First API**: Simple REST endpoints for creating and retrieving pastes. +- **Sessions**: Group pastes by "run" or logical session. +- **Tags**: Organize pastes with tags. +- **Syntax Highlighting**: Automatic highlighting for various languages. +- **Theming**: Light and Dark mode support. +- **Self-Hostable**: Built with Next.js and SQLite for easy deployment. + +## Tech Stack + +- **Framework**: Next.js 15 (App Router) +- **Database**: SQLite +- **ORM**: Drizzle ORM +- **Styling**: Tailwind CSS v4 +- **Validation**: Zod + +## Getting Started + +### Prerequisites + +- Node.js 18+ +- npm + +### Installation + +1. Clone the repository: + ```bash + git clone https://github.com/fullsizemalt/kites.git + cd kites + ``` + +2. Install dependencies: + ```bash + npm install + ``` + +3. Initialize the database: + ```bash + npx drizzle-kit push + ``` + +4. Run the development server: + ```bash + npm run dev + ``` + + Open [http://localhost:3000](http://localhost:3000) with your browser. + +## API Usage + +### Create a Paste + +```bash +curl -X POST http://localhost:3000/api/v1/pastes \ + -H "Content-Type: application/json" \ + -d '{ + "content": "console.log(\"Hello Kites!\");", + "title": "My First Paste", + "syntax": "javascript", + "tags": ["demo", "js"] + }' +``` + +### Get a Paste (Raw) + +```bash +curl http://localhost:3000/api/v1/pastes/?raw=1 +``` + +### Create a Session + +```bash +curl -X POST http://localhost:3000/api/v1/sessions \ + -H "Content-Type: application/json" \ + -d '{ + "title": "Agent Run 101", + "agentName": "GPT-4" + }' +``` + +## Agent Example + +See `examples/agent_usage.py` for a Python script that demonstrates how an agent can interact with Kites. + +```bash +python3 examples/agent_usage.py +``` diff --git a/apps/web/drizzle.config.ts b/apps/web/drizzle.config.ts new file mode 100644 index 0000000..54feee1 --- /dev/null +++ b/apps/web/drizzle.config.ts @@ -0,0 +1,11 @@ +import type { Config } from 'drizzle-kit'; +import 'dotenv/config'; + +export default { + schema: './src/db/schema.ts', + out: './drizzle', + dialect: 'postgresql', + dbCredentials: { + url: process.env.DATABASE_URL!, + }, +} satisfies Config; \ No newline at end of file diff --git a/apps/web/eslint.config.mjs b/apps/web/eslint.config.mjs new file mode 100644 index 0000000..05e726d --- /dev/null +++ b/apps/web/eslint.config.mjs @@ -0,0 +1,18 @@ +import { defineConfig, globalIgnores } from "eslint/config"; +import nextVitals from "eslint-config-next/core-web-vitals"; +import nextTs from "eslint-config-next/typescript"; + +const eslintConfig = defineConfig([ + ...nextVitals, + ...nextTs, + // Override default ignores of eslint-config-next. + globalIgnores([ + // Default ignores of eslint-config-next: + ".next/**", + "out/**", + "build/**", + "next-env.d.ts", + ]), +]); + +export default eslintConfig; diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts new file mode 100644 index 0000000..de2d453 --- /dev/null +++ b/apps/web/next.config.ts @@ -0,0 +1,7 @@ +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + output: "standalone", +}; + +export default nextConfig; \ No newline at end of file diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..6d4f3cd --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,48 @@ +{ + "name": "web", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "bun --bun next dev", + "build": "bun --bun next build", + "start": "bun --bun next start", + "lint": "bun --bun next lint", + "db:push": "bun --bun drizzle-kit push:pg", + "db:migrate": "bun --bun drizzle-kit migrate", + "db:generate": "bun --bun drizzle-kit generate" + }, + "dependencies": { + "@auth/drizzle-adapter": "^1.11.1", + "@types/react-syntax-highlighter": "^15.5.13", + "pg": "^8.13.1", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "date-fns": "^4.1.0", + "dotenv": "^16.4.5", + "drizzle-orm": "^0.44.7", + "lucide-react": "^0.554.0", + "nanoid": "^5.1.6", + "next": "16.0.3", + "next-auth": "^5.0.0-beta.30", + "next-themes": "^0.4.6", + "@radix-ui/react-select": "^2.1.0", + "@radix-ui/react-popover": "^1.1.0", + "react": "19.2.0", + "react-dom": "19.2.0", + "react-syntax-highlighter": "^16.1.0", + "tailwind-merge": "^3.4.0", + "zod": "^4.1.12" + }, + "devDependencies": { + "@tailwindcss/postcss": "^4", + "@types/pg": "^8.11.0", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "drizzle-kit": "^0.31.7", + "eslint": "^9", + "eslint-config-next": "16.0.3", + "tailwindcss": "^4", + "typescript": "^5" + } +} diff --git a/apps/web/postcss.config.mjs b/apps/web/postcss.config.mjs new file mode 100644 index 0000000..61e3684 --- /dev/null +++ b/apps/web/postcss.config.mjs @@ -0,0 +1,7 @@ +const config = { + plugins: { + "@tailwindcss/postcss": {}, + }, +}; + +export default config; diff --git a/apps/web/public/file.svg b/apps/web/public/file.svg new file mode 100644 index 0000000..004145c --- /dev/null +++ b/apps/web/public/file.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/globe.svg b/apps/web/public/globe.svg new file mode 100644 index 0000000..567f17b --- /dev/null +++ b/apps/web/public/globe.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/next.svg b/apps/web/public/next.svg new file mode 100644 index 0000000..5174b28 --- /dev/null +++ b/apps/web/public/next.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/vercel.svg b/apps/web/public/vercel.svg new file mode 100644 index 0000000..7705396 --- /dev/null +++ b/apps/web/public/vercel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/window.svg b/apps/web/public/window.svg new file mode 100644 index 0000000..b2b2a44 --- /dev/null +++ b/apps/web/public/window.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/sqlite.db b/apps/web/sqlite.db new file mode 100644 index 0000000..68d725c Binary files /dev/null and b/apps/web/sqlite.db differ diff --git a/apps/web/src/app/api/auth/[...nextauth]/route.ts b/apps/web/src/app/api/auth/[...nextauth]/route.ts new file mode 100644 index 0000000..42e2953 --- /dev/null +++ b/apps/web/src/app/api/auth/[...nextauth]/route.ts @@ -0,0 +1,2 @@ +import { handlers } from "@/auth" +export const { GET, POST } = handlers diff --git a/apps/web/src/app/api/v1/pastes/[id]/route.ts b/apps/web/src/app/api/v1/pastes/[id]/route.ts new file mode 100644 index 0000000..0bd783b --- /dev/null +++ b/apps/web/src/app/api/v1/pastes/[id]/route.ts @@ -0,0 +1,69 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { db } from '@/db'; +import { pastes } from '@/db/schema'; +import { eq } from 'drizzle-orm'; +import { z, ZodError } from 'zod'; + +export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + const { searchParams } = new URL(req.url); + const raw = searchParams.get('raw') === '1'; + + const paste = (await db.select().from(pastes).where(eq(pastes.id, id)).limit(1))[0]; + + if (!paste) { + return NextResponse.json({ error: 'Not found' }, { status: 404 }); + } + + if (raw) { + return new NextResponse(paste.content, { + headers: { + 'Content-Type': paste.contentType || 'text/plain', + }, + }); + } + + return NextResponse.json(paste); +} + +const updatePasteSchema = z.object({ + title: z.string().optional(), + content: z.string().optional(), + visibility: z.enum(['public', 'unlisted', 'private']).optional(), + syntax: z.string().optional(), +}); + +export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { + try { + const { id } = await params; + const body = await req.json(); + const validated = updatePasteSchema.parse(body); + + const updated = await db.update(pastes) + .set({ + ...validated, + updatedAt: new Date(), + }) + .where(eq(pastes.id, id)) + .returning(); + + const updatedFirst = updated[0]; + + if (!updatedFirst) { + return NextResponse.json({ error: 'Not found' }, { status: 404 }); + } + + return NextResponse.json(updatedFirst); + } catch (error) { + if (error instanceof ZodError) { + return NextResponse.json({ error: (error as any).errors }, { status: 400 }); + } + return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); + } +} + +export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + await db.delete(pastes).where(eq(pastes.id, id)); + return new NextResponse(null, { status: 204 }); +} diff --git a/apps/web/src/app/api/v1/pastes/route.ts b/apps/web/src/app/api/v1/pastes/route.ts new file mode 100644 index 0000000..6ad2df8 --- /dev/null +++ b/apps/web/src/app/api/v1/pastes/route.ts @@ -0,0 +1,114 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { db } from '@/db'; +import { pastes, tags, pastesToTags } from '@/db/schema'; +import { nanoid } from 'nanoid'; +import { z, ZodError } from 'zod'; +import { eq, desc, like, and } from 'drizzle-orm'; +import { auth } from '@/auth'; + +const createPasteSchema = z.object({ + content: z.string().min(1), + title: z.string().optional(), + tags: z.array(z.string()).optional(), + sessionId: z.string().optional(), + visibility: z.enum(['public', 'unlisted', 'private']).optional().default('public'), + expiresIn: z.number().optional(), // seconds + contentType: z.string().optional(), + syntax: z.string().optional(), +}); + +export async function POST(req: NextRequest) { + try { + const body = await req.json(); + const session = await auth(); + + // API Key Auth for Desktop Client + const apiKey = req.headers.get('x-api-key'); + const isApiAuth = apiKey && apiKey === process.env.KITES_API_KEY; + + if (!session && !isApiAuth) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const validated = createPasteSchema.parse(body); + + const id = nanoid(10); + + // Calculate expiration + let expiresAt = null; + if (validated.expiresIn) { + // Simple expiration logic (seconds) + expiresAt = new Date(Date.now() + validated.expiresIn * 1000); + } + + await db.insert(pastes).values({ + id, + content: validated.content, + title: validated.title, + sessionId: validated.sessionId, + visibility: validated.visibility, + expiresAt, + contentType: validated.contentType, + syntax: validated.syntax, + authorId: session?.user?.id, + }); + + if (validated.tags && validated.tags.length > 0) { + for (const tagName of validated.tags) { + // Simple tag handling: create if not exists, then link + // In a real app, might want to optimize this + let tagId = nanoid(8); + + // Check if tag exists + const existingTag = (await db.select().from(tags).where(eq(tags.name, tagName)).limit(1))[0]; + + if (existingTag) { + tagId = existingTag.id; + } else { + await db.insert(tags).values({ id: tagId, name: tagName }); + } + + await db.insert(pastesToTags).values({ + pasteId: id, + tagId: tagId, + }); + } + } + + const created = (await db.select().from(pastes).where(eq(pastes.id, id)).limit(1))[0]; + + return NextResponse.json(created, { status: 201 }); + } catch (error) { + if (error instanceof ZodError) { + return NextResponse.json({ error: (error as any).errors }, { status: 400 }); + } + console.error(error); + return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); + } +} + +export async function GET(req: NextRequest) { + const { searchParams } = new URL(req.url); + const limit = parseInt(searchParams.get('limit') || '20'); + const offset = parseInt(searchParams.get('offset') || '0'); + const sessionId = searchParams.get('session_id'); + const authorId = searchParams.get('author_id'); + const q = searchParams.get('q'); + + // Basic filtering + let conditions = []; + if (sessionId) conditions.push(eq(pastes.sessionId, sessionId)); + if (authorId) conditions.push(eq(pastes.authorId, authorId)); + if (q) conditions.push(like(pastes.title, `%${q}%`)); // Simple title search + + // TODO: Tag filtering requires join + + const results = await db.select() + .from(pastes) + .where(and(...conditions)) + .orderBy(desc(pastes.createdAt)) + .limit(limit) + .offset(offset); + + return NextResponse.json(results); +} diff --git a/apps/web/src/app/api/v1/sessions/[id]/pastes/route.ts b/apps/web/src/app/api/v1/sessions/[id]/pastes/route.ts new file mode 100644 index 0000000..946cde8 --- /dev/null +++ b/apps/web/src/app/api/v1/sessions/[id]/pastes/route.ts @@ -0,0 +1,15 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { db } from '@/db'; +import { pastes } from '@/db/schema'; +import { eq, desc } from 'drizzle-orm'; + +export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { + const { id: sessionId } = await params; + + const results = await db.select() + .from(pastes) + .where(eq(pastes.sessionId, sessionId)) + .orderBy(desc(pastes.createdAt)); + + return NextResponse.json(results); +} diff --git a/apps/web/src/app/api/v1/sessions/route.ts b/apps/web/src/app/api/v1/sessions/route.ts new file mode 100644 index 0000000..8633ffa --- /dev/null +++ b/apps/web/src/app/api/v1/sessions/route.ts @@ -0,0 +1,46 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { db } from '@/db'; +import { agentSessions } from '@/db/schema'; +import { nanoid } from 'nanoid'; +import { z, ZodError } from 'zod'; +import { eq } from 'drizzle-orm'; +import { auth } from '@/auth'; + +const createSessionSchema = z.object({ + title: z.string().optional(), + agentName: z.string().optional(), +}); + +export async function POST(req: NextRequest) { + try { + const body = await req.json(); + const session = await auth(); + const validated = createSessionSchema.parse(body); + + const id = nanoid(12); + + await db.insert(agentSessions).values({ + id, + title: validated.title, + agentName: validated.agentName, + userId: session?.user?.id, + }); + + const created = (await db.select().from(agentSessions).where(eq(agentSessions.id, id)).limit(1))[0]; // Re-fetch to get default fields if any + + // Since we inserted, we can just return what we have + id if we trust it, but fetching is safer for timestamps + // Actually better-sqlite3 insert doesn't return the row by default unless using returning() which is supported in Drizzle now + // Let's use returning() in the insert above if possible, but I used .values(). + // Drizzle with SQLite supports .returning() + + // Let's refactor to use returning() for cleaner code in next iteration or just re-fetch. + // Re-fetching is fine. + + return NextResponse.json(created || { id, ...validated }, { status: 201 }); + } catch (error) { + if (error instanceof ZodError) { + return NextResponse.json({ error: (error as any).errors }, { status: 400 }); + } + return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); + } +} diff --git a/apps/web/src/app/dashboard/page.tsx b/apps/web/src/app/dashboard/page.tsx new file mode 100644 index 0000000..44ed491 --- /dev/null +++ b/apps/web/src/app/dashboard/page.tsx @@ -0,0 +1,230 @@ +import { auth } from "@/auth"; +import { db } from "@/db"; +import { pastes, tags as tagsTable, pastesToTags, agentSessions } from "@/db/schema"; +import { desc, eq, and, inArray, ilike } from "drizzle-orm"; +import { redirect } from "next/navigation"; +import { formatDistanceToNow } from "date-fns"; +import Link from "next/link"; +import { Code, Cpu, Search, Layers, Tag } from "lucide-react"; +import { Input } from "@/components/ui/input"; +import { Badge } from "@/components/ui/badge"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { Button } from "@/components/ui/button"; + +export const dynamic = 'force-dynamic'; + +export default async function DashboardPage({ searchParams }: { + searchParams: { q?: string; tags?: string; sessionId?: string; syntax?: string } +}) { + const session = await auth(); + if (!session?.user?.id) { + redirect("/api/auth/signin"); + } + + const userId = session.user.id; + const { q, tags, sessionId, syntax } = searchParams; + + // Fetch all tags for filtering UI + const allTags = await db.select().from(tagsTable).orderBy(tagsTable.name); + + // Fetch all sessions for filtering UI + const allSessions = await db.query.agentSessions.findMany({ + where: eq(agentSessions.userId, userId), + orderBy: desc(agentSessions.createdAt), + columns: { id: true, title: true } + }); + + // Build query conditions + const conditions = [eq(pastes.authorId, userId)]; + + if (q) { + conditions.push(ilike(pastes.content, `%${q}%`)); + } + if (sessionId) { + conditions.push(eq(pastes.sessionId, sessionId)); + } + if (syntax) { + conditions.push(eq(pastes.syntax, syntax)); + } + if (tags) { + const selectedTagNames = tags.split(','); + const selectedTags = await db.select({ id: tagsTable.id }).from(tagsTable).where(inArray(tagsTable.name, selectedTagNames)); + const selectedTagIds = selectedTags.map(t => t.id); + + if (selectedTagIds.length > 0) { + const pasteIdsWithTags = await db.select({ pasteId: pastesToTags.pasteId }).from(pastesToTags).where(inArray(pastesToTags.tagId, selectedTagIds)); + const pasteIds = pasteIdsWithTags.map(p => p.pasteId).filter(Boolean) as string[]; + if (pasteIds.length > 0) { + conditions.push(inArray(pastes.id, pasteIds)); + } else { + // If no pastes match the tags, return empty result + conditions.push(eq(pastes.id, 'none')); + } + } + } + + + const userPastes = await db.select() + .from(pastes) + .where(and(...conditions)) + .orderBy(desc(pastes.createdAt)) + .limit(50); // Limit for dashboard view + + const availableSyntaxes = [ + "text", "javascript", "typescript", "python", "json", "markdown", + "html", "css", "bash", "go", "rust" + ]; + + return ( +
+

Your Kites Dashboard

+ + {/* Filter Bar */} +
+ {/* Search Query */} +
+ +
+ + { + if (e.key === 'Enter') { + const newSearchParams = new URLSearchParams(window.location.search); + if (e.currentTarget.value) newSearchParams.set('q', e.currentTarget.value); + else newSearchParams.delete('q'); + window.location.search = newSearchParams.toString(); + } + }} + /> +
+
+ + {/* Tags Filter */} + + + + + +
+ {allTags.map((t) => ( +
+ { + const newSearchParams = new URLSearchParams(window.location.search); + let currentTags = tags ? tags.split(',') : []; + if (e.target.checked) { + currentTags.push(t.name); + } else { + currentTags = currentTags.filter(name => name !== t.name); + } + if (currentTags.length > 0) newSearchParams.set('tags', currentTags.join(',')); + else newSearchParams.delete('tags'); + window.location.search = newSearchParams.toString(); + }} + /> + +
+ ))} +
+
+
+ + {/* Sessions Filter */} + + + {/* Syntax Filter */} + + + {/* Clear Filters Button */} + {(q || tags || sessionId || syntax) && ( + + )} +
+ + {/* Pastes List */} +
+ {userPastes.length === 0 ? ( +
+
👻
+ No pastes found matching your criteria. +
+ ) : ( + userPastes.map((paste) => ( + +
+
+ {paste.syntax ? : } + {paste.syntax || 'Text'} +
+ {formatDistanceToNow(paste.createdAt!, { addSuffix: true })} +
+ +

+ {paste.title || "Untitled Snippet"} +

+ +
+
+ {paste.content} +
+
+
+ + )) + )} +
+
+ ); +} diff --git a/apps/web/src/app/favicon.ico b/apps/web/src/app/favicon.ico new file mode 100644 index 0000000..718d6fe Binary files /dev/null and b/apps/web/src/app/favicon.ico differ diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css new file mode 100644 index 0000000..04aceeb --- /dev/null +++ b/apps/web/src/app/globals.css @@ -0,0 +1,100 @@ +@import "tailwindcss"; + +@layer base { + :root { + --background: 0 0% 100%; + --foreground: 222.2 84% 4.9%; + + --card: 0 0% 100%; + --card-foreground: 222.2 84% 4.9%; + + --popover: 0 0% 100%; + --popover-foreground: 222.2 84% 4.9%; + + --primary: 222.2 47.4% 11.2%; + --primary-foreground: 210 40% 98%; + + --secondary: 210 40% 96.1%; + --secondary-foreground: 222.2 47.4% 11.2%; + + --muted: 210 40% 96.1%; + --muted-foreground: 215.4 16.3% 46.9%; + + --accent: 210 40% 96.1%; + --accent-foreground: 222.2 47.4% 11.2%; + + --destructive: 0 84.2% 60.2%; + --destructive-foreground: 210 40% 98%; + + --border: 214.3 31.8% 91.4%; + --input: 214.3 31.8% 91.4%; + --ring: 222.2 84% 4.9%; + + --radius: 0.5rem; + } + + .dark { + --background: 222.2 84% 4.9%; + --foreground: 210 40% 98%; + + --card: 222.2 84% 4.9%; + --card-foreground: 210 40% 98%; + + --popover: 222.2 84% 4.9%; + --popover-foreground: 210 40% 98%; + + --primary: 210 40% 98%; + --primary-foreground: 222.2 47.4% 11.2%; + + --secondary: 217.2 32.6% 17.5%; + --secondary-foreground: 210 40% 98%; + + --muted: 217.2 32.6% 17.5%; + --muted-foreground: 215 20.2% 65.1%; + + --accent: 217.2 32.6% 17.5%; + --accent-foreground: 210 40% 98%; + + --destructive: 0 62.8% 30.6%; + --destructive-foreground: 210 40% 98%; + + --border: 217.2 32.6% 17.5%; + --input: 217.2 32.6% 17.5%; + --ring: 212.7 26.8% 83.9%; + } +} + +@theme { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-destructive: var(--destructive); + --color-destructive-foreground: var(--destructive-foreground); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); +} + +@layer base { + * { + @apply border-border; + } + + body { + @apply bg-background text-foreground; + } +} \ No newline at end of file diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx new file mode 100644 index 0000000..8bebc91 --- /dev/null +++ b/apps/web/src/app/layout.tsx @@ -0,0 +1,39 @@ +import type { Metadata } from "next"; +import { Inter } from "next/font/google"; +import "./globals.css"; +import { ThemeProvider } from "@/components/theme-provider"; +import { Navbar } from "@/components/navbar"; +import { cn } from "@/lib/utils"; + +const inter = Inter({ subsets: ["latin"] }); + +export const metadata: Metadata = { + title: "Kites - Agentic Pastebin", + description: "A clean, agent-native pastebin service.", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + + +
+ +
+ {children} +
+
+
+ + + ); +} diff --git a/apps/web/src/app/new/page.tsx b/apps/web/src/app/new/page.tsx new file mode 100644 index 0000000..d29e71b --- /dev/null +++ b/apps/web/src/app/new/page.tsx @@ -0,0 +1,49 @@ +import { PasteForm } from "@/components/paste-form"; +import Link from "next/link"; +import { Copy, Terminal, Key } from "lucide-react"; +import { Button } from "@/components/ui/button"; + +export default function NewPastePage() { + return ( +
+

Create New Paste

+

+ Kites helps you manage code snippets, agent outputs, and clipboard history. Create a paste below, or learn how to integrate with your tools. +

+ + {/* Instruction Cards */} +
+
+
+ +
+

For Humans

+

+ Simply paste your content below. Choose a title, syntax, and visibility. Your paste will be available in your personal feed. +

+ +
+
+
+ +
+

For Agents & Clients

+

+ Integrate your LLMs, scripts, or desktop clipboard managers using the Kites API. Generate an API key to securely push data. +

+ +
+
+ + {/* Paste Form */} +

Your Content Here

+ +
+ ); +} \ No newline at end of file diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx new file mode 100644 index 0000000..fe25c83 --- /dev/null +++ b/apps/web/src/app/page.tsx @@ -0,0 +1,147 @@ +import Link from "next/link"; +import { db } from "@/db"; +import { pastes } from "@/db/schema"; +import { desc, eq } from "drizzle-orm"; +import { formatDistanceToNow } from "date-fns"; +import { Button } from "@/components/ui/button"; +import { Terminal, Cpu, Share2, Shield, Code, Sparkles } from "lucide-react"; +import { auth } from "@/auth"; +import { redirect } from "next/navigation"; // Import redirect + +export const dynamic = 'force-dynamic'; + +export default async function Home() { + const session = await auth(); + const userId = session?.user?.id; + + if (userId) { // Redirect if logged in + redirect("/dashboard"); + } + + const recentPastes = await db.select() + .from(pastes) + .orderBy(desc(pastes.createdAt)) + .limit(12); + + return ( +
+ {/* Hero Section */} +
+
+
+
+ + v1.0 Public Beta +
+

+ The Shared Brain for
Humans & AI Agents +

+

+ Stop copy-pasting into the void. Kites is an agent-native clipboard that gives your LLMs a persistent memory and you a unified history. +

+
+ + + + {userId ? ( // Conditional button for logged-in users + + + + ) : ( + + + + )} +
+
+
+ + {/* Abstract "Network" Background */} +
+
+ + {/* Feature Grid */} +
+
+
+
+
+ +
+

Agent-Native API

+

+ Give your agents a POST /pastes endpoint. Let them save context, code blocks, and logs directly to your view. +

+
+
+
+ +
+

Unified History

+

+ Your desktop clipboard, your agent's output, and your mobile saves—all in one structured, searchable timeline. +

+
+
+
+ +
+

Privacy First

+

+ Self-hostable. Private by default. You control the retention policy and visibility of every snippet. +

+
+
+
+
+ + {/* Live Feed (Recent Pastes) */} +
+
+
+
+

{userId ? "My Recent Pastes" : "Live Context Feed"}

+

{userId ? "Your latest snippets and agent interactions." : "Recent items from our community."}

+
+
+ +
+ {recentPastes.length === 0 ? ( +
+
👻
+ No context yet. Create your first paste! +
+ ) : ( + recentPastes.map((paste) => ( + +
+
+ {paste.syntax ? : } + {paste.syntax || 'Text'} +
+ {formatDistanceToNow(paste.createdAt!, { addSuffix: true })} +
+ +

+ {paste.title || "Untitled Snippet"} +

+ +
+
+ {paste.content} +
+
+
+ + )) + )} +
+
+
+
+ ); +} \ No newline at end of file diff --git a/apps/web/src/app/paste/[id]/page.tsx b/apps/web/src/app/paste/[id]/page.tsx new file mode 100644 index 0000000..f8d512c --- /dev/null +++ b/apps/web/src/app/paste/[id]/page.tsx @@ -0,0 +1,76 @@ +import { db } from "@/db"; +import { pastes, tags, pastesToTags } from "@/db/schema"; +import { eq } from "drizzle-orm"; +import { notFound } from "next/navigation"; +import { formatDistanceToNow } from "date-fns"; +import { CodeViewer } from "@/components/code-viewer"; +import Link from "next/link"; +import { Badge } from "@/components/ui/badge"; // We don't have this yet, I'll inline styles or create it + +// Inline simple Badge component for now to avoid creating too many files +function SimpleBadge({ children, className }: { children: React.ReactNode, className?: string }) { + return ( + + {children} + + ); +} + +export default async function PastePage({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + const paste = (await db.select().from(pastes).where(eq(pastes.id, id)).limit(1))[0]; + + if (!paste) { + notFound(); + } + + const pasteTags = await db.select({ + id: tags.id, + name: tags.name, + }) + .from(tags) + .innerJoin(pastesToTags, eq(tags.id, pastesToTags.tagId)) + .where(eq(pastesToTags.pasteId, id)); + + return ( +
+
+
+

{paste.title || "Untitled Paste"}

+
+ {formatDistanceToNow(paste.createdAt!, { addSuffix: true })} + • + {paste.syntax || "text"} + • + {paste.visibility} +
+
+
+ + Raw + + {/* Copy button could go here */} +
+
+ + {pasteTags.length > 0 && ( +
+ {pasteTags.map((tag) => ( + + #{tag.name} + + ))} +
+ )} + +
+ +
+
+ ); +} diff --git a/apps/web/src/app/sessions/[id]/page.tsx b/apps/web/src/app/sessions/[id]/page.tsx new file mode 100644 index 0000000..09fc7a6 --- /dev/null +++ b/apps/web/src/app/sessions/[id]/page.tsx @@ -0,0 +1,64 @@ +import Link from "next/link"; +import { db } from "@/db"; +import { agentSessions, pastes } from "@/db/schema"; +import { eq, desc } from "drizzle-orm"; +import { notFound } from "next/navigation"; +import { formatDistanceToNow } from "date-fns"; + +export default async function SessionPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + const session = (await db.select().from(agentSessions).where(eq(agentSessions.id, id)).limit(1))[0]; + + if (!session) { + notFound(); + } + + const sessionPastes = await db.select() + .from(pastes) + .where(eq(pastes.sessionId, session.id)) + .orderBy(desc(pastes.createdAt)); + + return ( +
+
+

{session.title || "Session " + session.id}

+
+ {formatDistanceToNow(session.createdAt!, { addSuffix: true })} + • + {session.agentName || "Unknown Agent"} +
+
+ +
+ {sessionPastes.length === 0 ? ( +
+ No pastes in this session. +
+ ) : ( + sessionPastes.map((paste) => ( + +
+

+ {paste.title || "Untitled Paste"} +

+ + {paste.syntax || "text"} + +
+
+ {paste.content} +
+
+ {formatDistanceToNow(paste.createdAt!, { addSuffix: true })} +
+ + )) + )} +
+
+ ); +} diff --git a/apps/web/src/app/sessions/page.tsx b/apps/web/src/app/sessions/page.tsx new file mode 100644 index 0000000..94730d3 --- /dev/null +++ b/apps/web/src/app/sessions/page.tsx @@ -0,0 +1,57 @@ +import Link from "next/link"; +import { db } from "@/db"; +import { agentSessions, pastes } from "@/db/schema"; +import { desc, eq, sql } from "drizzle-orm"; +import { formatDistanceToNow } from "date-fns"; + +export const dynamic = 'force-dynamic'; + +export default async function SessionsPage() { + // Fetch sessions with paste count + const allSessions = await db.select({ + id: agentSessions.id, + title: agentSessions.title, + agentName: agentSessions.agentName, + createdAt: agentSessions.createdAt, + pasteCount: sql`count(${pastes.id})`, + }) + .from(agentSessions) + .leftJoin(pastes, eq(agentSessions.id, pastes.sessionId)) + .groupBy(agentSessions.id) + .orderBy(desc(agentSessions.createdAt)); + + return ( +
+

Sessions

+ +
+ {allSessions.length === 0 ? ( +
+ No sessions found. +
+ ) : ( + allSessions.map((session) => ( + +
+

+ {session.title || session.id} +

+ + {session.agentName || "Unknown Agent"} + +
+
+ {formatDistanceToNow(session.createdAt!, { addSuffix: true })} + {session.pasteCount} pastes +
+ + )) + )} +
+
+ ); +} diff --git a/apps/web/src/app/settings/api-keys/page.tsx b/apps/web/src/app/settings/api-keys/page.tsx new file mode 100644 index 0000000..ffc935a --- /dev/null +++ b/apps/web/src/app/settings/api-keys/page.tsx @@ -0,0 +1,37 @@ +import { auth } from "@/auth"; +import { redirect } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { KeyRound, Plus } from "lucide-react"; + +export default async function ApiKeysPage() { + const session = await auth(); + + if (!session?.user) { + redirect("/api/auth/signin"); + } + + return ( +
+
+

API Keys

+ +
+ +
+ +

No API Keys yet.

+

Generate keys to connect your agents and desktop clients.

+
+ + {/* Placeholder for listing existing keys */} + {/*
+
+ sk_live_******************** + +
+
*/} +
+ ); +} diff --git a/apps/web/src/app/tag/[id]/page.tsx b/apps/web/src/app/tag/[id]/page.tsx new file mode 100644 index 0000000..d904613 --- /dev/null +++ b/apps/web/src/app/tag/[id]/page.tsx @@ -0,0 +1,75 @@ +import Link from "next/link"; +import { db } from "@/db"; +import { tags, pastes, pastesToTags } from "@/db/schema"; +import { eq, desc } from "drizzle-orm"; +import { notFound } from "next/navigation"; +import { formatDistanceToNow } from "date-fns"; +import { Badge } from "@/components/ui/badge"; + +export default async function TagPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + const tag = (await db.select().from(tags).where(eq(tags.id, id)).limit(1))[0]; + + if (!tag) { + notFound(); + } + + const taggedPastes = await db.select({ + id: pastes.id, + title: pastes.title, + content: pastes.content, + syntax: pastes.syntax, + createdAt: pastes.createdAt, + visibility: pastes.visibility, + }) + .from(pastes) + .innerJoin(pastesToTags, eq(pastes.id, pastesToTags.pasteId)) + .where(eq(pastesToTags.tagId, tag.id)) + .orderBy(desc(pastes.createdAt)) + .limit(50); + + return ( +
+
+

Tag:

+ #{tag.name} +
+ +
+ {taggedPastes.length === 0 ? ( +
+ No pastes found with this tag. +
+ ) : ( + taggedPastes.map((paste) => ( + +
+

+ {paste.title || "Untitled Paste"} +

+ + {paste.syntax || "text"} + +
+
+ {paste.content} +
+
+ {formatDistanceToNow(paste.createdAt!, { addSuffix: true })} + {paste.visibility !== 'public' && ( + + {paste.visibility} + + )} +
+ + )) + )} +
+
+ ); +} diff --git a/apps/web/src/auth.ts b/apps/web/src/auth.ts new file mode 100644 index 0000000..e863cee --- /dev/null +++ b/apps/web/src/auth.ts @@ -0,0 +1,17 @@ +import NextAuth from "next-auth" +import { DrizzleAdapter } from "@auth/drizzle-adapter" +import { db } from "@/db" +import { accounts, sessions, users, verificationTokens } from "@/db/schema" +import Google from "next-auth/providers/google" +import GitHub from "next-auth/providers/github" +import Apple from "next-auth/providers/apple" + +export const { handlers, auth, signIn, signOut } = NextAuth({ + adapter: DrizzleAdapter(db, { + usersTable: users, + accountsTable: accounts, + sessionsTable: sessions, + verificationTokensTable: verificationTokens, + }), + providers: [Google, GitHub, Apple], +}) diff --git a/apps/web/src/components/auth-components.tsx b/apps/web/src/components/auth-components.tsx new file mode 100644 index 0000000..0281b02 --- /dev/null +++ b/apps/web/src/components/auth-components.tsx @@ -0,0 +1,30 @@ +import { signIn, signOut } from "@/auth" +import { Button } from "./ui/button" + +export function SignIn() { + return ( +
{ + "use server" + await signIn() + }} + > + +
+ ) +} + +export function SignOut() { + return ( +
{ + "use server" + await signOut() + }} + > + +
+ ) +} diff --git a/apps/web/src/components/code-viewer.tsx b/apps/web/src/components/code-viewer.tsx new file mode 100644 index 0000000..91ac17b --- /dev/null +++ b/apps/web/src/components/code-viewer.tsx @@ -0,0 +1,39 @@ +"use client" + +import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; +import { vscDarkPlus, vs } from 'react-syntax-highlighter/dist/esm/styles/prism'; +import { useTheme } from 'next-themes'; +import { useEffect, useState } from 'react'; + +interface CodeViewerProps { + code: string; + language: string; +} + +export function CodeViewer({ code, language }: CodeViewerProps) { + const { theme } = useTheme(); + const [mounted, setMounted] = useState(false); + + useEffect(() => { + setMounted(true); + }, []); + + if (!mounted) { + return ( +
+                {code}
+            
+ ); + } + + return ( + + {code} + + ); +} diff --git a/apps/web/src/components/navbar.tsx b/apps/web/src/components/navbar.tsx new file mode 100644 index 0000000..f6697f2 --- /dev/null +++ b/apps/web/src/components/navbar.tsx @@ -0,0 +1,35 @@ +import Link from "next/link" +import { ThemeToggle } from "./theme-toggle" +import UserButton from "./user-button" + +export function Navbar() { + return ( +
+
+
+ + Kites + + +
+
+ + +
+
+
+ ) +} diff --git a/apps/web/src/components/paste-form.tsx b/apps/web/src/components/paste-form.tsx new file mode 100644 index 0000000..ada27e6 --- /dev/null +++ b/apps/web/src/components/paste-form.tsx @@ -0,0 +1,141 @@ +"use client" + +import { useState } from "react" +import { useRouter } from "next/navigation" + +export function PasteForm() { + const router = useRouter() + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + + async function onSubmit(event: React.FormEvent) { + event.preventDefault() + setLoading(true) + setError(null) + + const formData = new FormData(event.currentTarget) + const data = { + title: formData.get("title"), + content: formData.get("content"), + syntax: formData.get("syntax"), + visibility: formData.get("visibility"), + tags: formData.get("tags")?.toString().split(",").map(t => t.trim()).filter(Boolean), + } + + try { + const res = await fetch("/api/v1/pastes", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(data), + }) + + if (!res.ok) { + const json = await res.json() + throw new Error(JSON.stringify(json.error) || "Failed to create paste") + } + + const created = await res.json() + router.push(`/paste/${created.id}`) + router.refresh() + } catch (err) { + setError(err instanceof Error ? err.message : "Something went wrong") + } finally { + setLoading(false) + } + } + + return ( +
+ {error && ( +
+ {error} +
+ )} + +
+ + +
+ +
+
+ + +
+ +
+ + +
+
+ +
+ + +
+ +
+ +