Nyk commited on
Commit
05adc4a
·
2 Parent(s): 2afed80c556431

Merge remote-tracking branch 'origin/main' into feat/medium-priority-v1.1

Browse files

# Conflicts:
# src/app/api/agents/route.ts
# src/app/api/alerts/route.ts
# src/app/api/auth/login/route.ts
# src/app/api/spawn/route.ts
# src/app/api/tasks/[id]/route.ts
# src/app/api/tasks/route.ts
# src/app/api/webhooks/route.ts
# src/lib/validation.ts

.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ node_modules
2
+ .git
3
+ .data
4
+ .next
5
+ .env
6
+ *.md
7
+ .github
8
+ ops
9
+ scripts
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:20-slim AS base
2
+ RUN corepack enable && corepack prepare pnpm@latest --activate
3
+ WORKDIR /app
4
+
5
+ FROM base AS deps
6
+ COPY package.json pnpm-lock.yaml ./
7
+ RUN pnpm install --frozen-lockfile
8
+
9
+ FROM base AS build
10
+ COPY --from=deps /app/node_modules ./node_modules
11
+ COPY . .
12
+ RUN pnpm build
13
+
14
+ FROM node:20-slim AS runtime
15
+ WORKDIR /app
16
+ ENV NODE_ENV=production
17
+ RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
18
+ COPY --from=build /app/.next/standalone ./
19
+ COPY --from=build /app/.next/static ./.next/static
20
+ COPY --from=build /app/public ./public
21
+ USER nextjs
22
+ EXPOSE 3000
23
+ CMD ["node", "server.js"]
docker-compose.yml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ mission-control:
3
+ build: .
4
+ ports:
5
+ - "3000:3000"
6
+ env_file: .env
7
+ volumes:
8
+ - mc-data:/app/.data
9
+ restart: unless-stopped
10
+
11
+ volumes:
12
+ mc-data:
next.config.js CHANGED
@@ -1,5 +1,6 @@
1
  /** @type {import('next').NextConfig} */
2
  const nextConfig = {
 
3
  turbopack: {},
4
 
5
  // Security headers
 
1
  /** @type {import('next').NextConfig} */
2
  const nextConfig = {
3
+ output: 'standalone',
4
  turbopack: {},
5
 
6
  // Security headers
src/app/api/agents/route.ts CHANGED
@@ -5,6 +5,7 @@ import { getTemplate, buildAgentConfig } from '@/lib/agent-templates';
5
  import { writeAgentToConfig } from '@/lib/agent-sync';
6
  import { logAuditEvent } from '@/lib/db';
7
  import { getUserFromRequest, requireRole } from '@/lib/auth';
 
8
  import { logger } from '@/lib/logger';
9
  import { validateBody, createAgentSchema } from '@/lib/validation';
10
 
@@ -109,6 +110,9 @@ export async function POST(request: NextRequest) {
109
  const auth = requireRole(request, 'operator');
110
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
111
 
 
 
 
112
  try {
113
  const db = getDatabase();
114
  const validated = await validateBody(request, createAgentSchema);
@@ -134,11 +138,11 @@ export async function POST(request: NextRequest) {
134
  const tpl = getTemplate(template);
135
  if (tpl) {
136
  const builtConfig = buildAgentConfig(tpl, (gateway_config || {}) as any);
137
- finalConfig = { ...builtConfig, ...config };
138
  if (!finalRole) finalRole = tpl.config.identity?.theme || tpl.type;
139
  }
140
  } else if (gateway_config) {
141
- finalConfig = { ...config, ...gateway_config };
142
  }
143
 
144
  if (!name || !finalRole) {
@@ -247,10 +251,13 @@ export async function PUT(request: NextRequest) {
247
  const auth = requireRole(request, 'operator');
248
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
249
 
 
 
 
250
  try {
251
  const db = getDatabase();
252
  const body = await request.json();
253
-
254
  // Handle single agent update or bulk updates
255
  if (body.name) {
256
  // Single agent update
 
5
  import { writeAgentToConfig } from '@/lib/agent-sync';
6
  import { logAuditEvent } from '@/lib/db';
7
  import { getUserFromRequest, requireRole } from '@/lib/auth';
8
+ import { mutationLimiter } from '@/lib/rate-limit';
9
  import { logger } from '@/lib/logger';
10
  import { validateBody, createAgentSchema } from '@/lib/validation';
11
 
 
110
  const auth = requireRole(request, 'operator');
111
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
112
 
113
+ const rateCheck = mutationLimiter(request);
114
+ if (rateCheck) return rateCheck;
115
+
116
  try {
117
  const db = getDatabase();
118
  const validated = await validateBody(request, createAgentSchema);
 
138
  const tpl = getTemplate(template);
139
  if (tpl) {
140
  const builtConfig = buildAgentConfig(tpl, (gateway_config || {}) as any);
141
+ finalConfig = { ...builtConfig, ...finalConfig };
142
  if (!finalRole) finalRole = tpl.config.identity?.theme || tpl.type;
143
  }
144
  } else if (gateway_config) {
145
+ finalConfig = { ...finalConfig, ...(gateway_config as Record<string, any>) };
146
  }
147
 
148
  if (!name || !finalRole) {
 
251
  const auth = requireRole(request, 'operator');
252
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
253
 
254
+ const rateCheck = mutationLimiter(request);
255
+ if (rateCheck) return rateCheck;
256
+
257
  try {
258
  const db = getDatabase();
259
  const body = await request.json();
260
+
261
  // Handle single agent update or bulk updates
262
  if (body.name) {
263
  // Single agent update
src/app/api/alerts/route.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase } from '@/lib/db'
 
4
  import { createAlertSchema } from '@/lib/validation'
5
 
6
  interface AlertRule {
@@ -45,6 +46,9 @@ export async function POST(request: NextRequest) {
45
  const auth = requireRole(request, 'operator')
46
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
47
 
 
 
 
48
  const db = getDatabase()
49
  const body = await request.json()
50
 
@@ -103,6 +107,9 @@ export async function PUT(request: NextRequest) {
103
  const auth = requireRole(request, 'operator')
104
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
105
 
 
 
 
106
  const db = getDatabase()
107
  const body = await request.json()
108
  const { id, ...updates } = body
@@ -141,6 +148,9 @@ export async function DELETE(request: NextRequest) {
141
  const auth = requireRole(request, 'admin')
142
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
143
 
 
 
 
144
  const db = getDatabase()
145
  const body = await request.json()
146
  const { id } = body
 
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase } from '@/lib/db'
4
+ import { mutationLimiter } from '@/lib/rate-limit'
5
  import { createAlertSchema } from '@/lib/validation'
6
 
7
  interface AlertRule {
 
46
  const auth = requireRole(request, 'operator')
47
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
48
 
49
+ const rateCheck = mutationLimiter(request)
50
+ if (rateCheck) return rateCheck
51
+
52
  const db = getDatabase()
53
  const body = await request.json()
54
 
 
107
  const auth = requireRole(request, 'operator')
108
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
109
 
110
+ const rateCheck = mutationLimiter(request)
111
+ if (rateCheck) return rateCheck
112
+
113
  const db = getDatabase()
114
  const body = await request.json()
115
  const { id, ...updates } = body
 
148
  const auth = requireRole(request, 'admin')
149
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
150
 
151
+ const rateCheck = mutationLimiter(request)
152
+ if (rateCheck) return rateCheck
153
+
154
  const db = getDatabase()
155
  const body = await request.json()
156
  const { id } = body
src/app/api/auth/login/route.ts CHANGED
@@ -2,28 +2,13 @@ import { NextResponse } from 'next/server'
2
  import { authenticateUser, createSession } from '@/lib/auth'
3
  import { logAuditEvent } from '@/lib/db'
4
  import { getMcSessionCookieOptions } from '@/lib/session-cookie'
 
5
  import { logger } from '@/lib/logger'
6
 
7
- // Rate limiting: 5 attempts per minute per IP
8
- const loginAttempts = new Map<string, { count: number; resetAt: number }>()
9
-
10
- function checkRateLimit(ip: string): boolean {
11
- const now = Date.now()
12
- const entry = loginAttempts.get(ip)
13
- if (!entry || now > entry.resetAt) {
14
- loginAttempts.set(ip, { count: 1, resetAt: now + 60_000 })
15
- return true
16
- }
17
- entry.count++
18
- return entry.count <= 5
19
- }
20
-
21
  export async function POST(request: Request) {
22
  try {
23
- const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown'
24
- if (!checkRateLimit(ip)) {
25
- return NextResponse.json({ error: 'Too many login attempts. Try again in a minute.' }, { status: 429 })
26
- }
27
 
28
  const { username, password } = await request.json()
29
 
 
2
  import { authenticateUser, createSession } from '@/lib/auth'
3
  import { logAuditEvent } from '@/lib/db'
4
  import { getMcSessionCookieOptions } from '@/lib/session-cookie'
5
+ import { loginLimiter } from '@/lib/rate-limit'
6
  import { logger } from '@/lib/logger'
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  export async function POST(request: Request) {
9
  try {
10
+ const rateCheck = loginLimiter(request)
11
+ if (rateCheck) return rateCheck
 
 
12
 
13
  const { username, password } = await request.json()
14
 
src/app/api/export/route.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
 
4
 
5
  /**
6
  * GET /api/export?type=audit|tasks|activities|pipelines&format=csv|json&since=UNIX&until=UNIX
@@ -10,6 +11,9 @@ export async function GET(request: NextRequest) {
10
  const auth = requireRole(request, 'admin')
11
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
12
 
 
 
 
13
  const { searchParams } = new URL(request.url)
14
  const type = searchParams.get('type')
15
  const format = searchParams.get('format') || 'csv'
 
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
4
+ import { heavyLimiter } from '@/lib/rate-limit'
5
 
6
  /**
7
  * GET /api/export?type=audit|tasks|activities|pipelines&format=csv|json&since=UNIX&until=UNIX
 
11
  const auth = requireRole(request, 'admin')
12
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
13
 
14
+ const rateCheck = heavyLimiter(request)
15
+ if (rateCheck) return rateCheck
16
+
17
  const { searchParams } = new URL(request.url)
18
  const type = searchParams.get('type')
19
  const format = searchParams.get('format') || 'csv'
src/app/api/notifications/route.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { NextRequest, NextResponse } from 'next/server';
2
  import { getDatabase, Notification } from '@/lib/db';
3
  import { requireRole } from '@/lib/auth';
 
4
 
5
  /**
6
  * GET /api/notifications - Get notifications for a specific recipient
@@ -138,6 +139,9 @@ export async function PUT(request: NextRequest) {
138
  const auth = requireRole(request, 'operator');
139
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
140
 
 
 
 
141
  try {
142
  const db = getDatabase();
143
  const body = await request.json();
@@ -193,6 +197,9 @@ export async function DELETE(request: NextRequest) {
193
  const auth = requireRole(request, 'admin');
194
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
195
 
 
 
 
196
  try {
197
  const db = getDatabase();
198
  const body = await request.json();
@@ -244,6 +251,9 @@ export async function POST(request: NextRequest) {
244
  const auth = requireRole(request, 'operator');
245
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
246
 
 
 
 
247
  try {
248
  const db = getDatabase();
249
  const body = await request.json();
 
1
  import { NextRequest, NextResponse } from 'next/server';
2
  import { getDatabase, Notification } from '@/lib/db';
3
  import { requireRole } from '@/lib/auth';
4
+ import { mutationLimiter } from '@/lib/rate-limit';
5
 
6
  /**
7
  * GET /api/notifications - Get notifications for a specific recipient
 
139
  const auth = requireRole(request, 'operator');
140
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
141
 
142
+ const rateCheck = mutationLimiter(request);
143
+ if (rateCheck) return rateCheck;
144
+
145
  try {
146
  const db = getDatabase();
147
  const body = await request.json();
 
197
  const auth = requireRole(request, 'admin');
198
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
199
 
200
+ const rateCheck = mutationLimiter(request);
201
+ if (rateCheck) return rateCheck;
202
+
203
  try {
204
  const db = getDatabase();
205
  const body = await request.json();
 
251
  const auth = requireRole(request, 'operator');
252
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
253
 
254
+ const rateCheck = mutationLimiter(request);
255
+ if (rateCheck) return rateCheck;
256
+
257
  try {
258
  const db = getDatabase();
259
  const body = await request.json();
src/app/api/sessions/[id]/control/route.ts ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { requireRole } from '@/lib/auth'
3
+ import { runClawdbot } from '@/lib/command'
4
+ import { db_helpers } from '@/lib/db'
5
+
6
+ export async function POST(
7
+ request: NextRequest,
8
+ { params }: { params: Promise<{ id: string }> }
9
+ ) {
10
+ const auth = requireRole(request, 'operator')
11
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
12
+
13
+ try {
14
+ const { id } = await params
15
+ const { action } = await request.json()
16
+
17
+ if (!['monitor', 'pause', 'terminate'].includes(action)) {
18
+ return NextResponse.json(
19
+ { error: 'Invalid action. Must be: monitor, pause, terminate' },
20
+ { status: 400 }
21
+ )
22
+ }
23
+
24
+ let result
25
+ if (action === 'terminate') {
26
+ result = await runClawdbot(
27
+ ['-c', `sessions_kill("${id}")`],
28
+ { timeoutMs: 10000 }
29
+ )
30
+ } else {
31
+ const message = action === 'monitor'
32
+ ? JSON.stringify({ type: 'control', action: 'monitor' })
33
+ : JSON.stringify({ type: 'control', action: 'pause' })
34
+ result = await runClawdbot(
35
+ ['-c', `sessions_send("${id}", ${JSON.stringify(message)})`],
36
+ { timeoutMs: 10000 }
37
+ )
38
+ }
39
+
40
+ db_helpers.logActivity(
41
+ 'session_control',
42
+ 'session',
43
+ 0,
44
+ auth.user.username,
45
+ `Session ${action}: ${id}`,
46
+ { session_key: id, action }
47
+ )
48
+
49
+ return NextResponse.json({
50
+ success: true,
51
+ action,
52
+ session: id,
53
+ stdout: result.stdout.trim(),
54
+ })
55
+ } catch (error: any) {
56
+ return NextResponse.json(
57
+ { error: error.message || 'Session control failed' },
58
+ { status: 500 }
59
+ )
60
+ }
61
+ }
src/app/api/settings/route.ts CHANGED
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
 
5
 
6
  interface SettingRow {
7
  key: string
@@ -101,6 +102,9 @@ export async function PUT(request: NextRequest) {
101
  const auth = requireRole(request, 'admin')
102
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
103
 
 
 
 
104
  const body = await request.json().catch(() => null)
105
  if (!body?.settings || typeof body.settings !== 'object') {
106
  return NextResponse.json({ error: 'settings object required' }, { status: 400 })
@@ -157,6 +161,9 @@ export async function DELETE(request: NextRequest) {
157
  const auth = requireRole(request, 'admin')
158
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
159
 
 
 
 
160
  let body: any
161
  try { body = await request.json() } catch { return NextResponse.json({ error: 'Request body required' }, { status: 400 }) }
162
  const key = body.key
 
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
5
+ import { mutationLimiter } from '@/lib/rate-limit'
6
 
7
  interface SettingRow {
8
  key: string
 
102
  const auth = requireRole(request, 'admin')
103
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
104
 
105
+ const rateCheck = mutationLimiter(request)
106
+ if (rateCheck) return rateCheck
107
+
108
  const body = await request.json().catch(() => null)
109
  if (!body?.settings || typeof body.settings !== 'object') {
110
  return NextResponse.json({ error: 'settings object required' }, { status: 400 })
 
161
  const auth = requireRole(request, 'admin')
162
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
163
 
164
+ const rateCheck = mutationLimiter(request)
165
+ if (rateCheck) return rateCheck
166
+
167
  let body: any
168
  try { body = await request.json() } catch { return NextResponse.json({ error: 'Request body required' }, { status: 400 }) }
169
  const key = body.key
src/app/api/spawn/route.ts CHANGED
@@ -4,12 +4,16 @@ import { requireRole } from '@/lib/auth'
4
  import { config } from '@/lib/config'
5
  import { readdir, readFile, stat } from 'fs/promises'
6
  import { join } from 'path'
 
7
  import { logger } from '@/lib/logger'
8
 
9
  export async function POST(request: NextRequest) {
10
  const auth = requireRole(request, 'operator')
11
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
12
 
 
 
 
13
  try {
14
  const { task, model, label, timeoutSeconds } = await request.json()
15
 
 
4
  import { config } from '@/lib/config'
5
  import { readdir, readFile, stat } from 'fs/promises'
6
  import { join } from 'path'
7
+ import { heavyLimiter } from '@/lib/rate-limit'
8
  import { logger } from '@/lib/logger'
9
 
10
  export async function POST(request: NextRequest) {
11
  const auth = requireRole(request, 'operator')
12
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
13
 
14
+ const rateCheck = heavyLimiter(request)
15
+ if (rateCheck) return rateCheck
16
+
17
  try {
18
  const { task, model, label, timeoutSeconds } = await request.json()
19
 
src/app/api/status/route.ts CHANGED
@@ -6,6 +6,7 @@ import { config } from '@/lib/config'
6
  import { getDatabase } from '@/lib/db'
7
  import { getAllGatewaySessions, getAgentLiveStatuses } from '@/lib/sessions'
8
  import { requireRole } from '@/lib/auth'
 
9
 
10
  export async function GET(request: NextRequest) {
11
  const auth = requireRole(request, 'viewer')
@@ -340,17 +341,8 @@ async function getGatewayStatus() {
340
 
341
  async function getAvailableModels() {
342
  // This would typically query the gateway or config files
343
- // For now, return the models from AGENTS.md
344
- const models = [
345
- { alias: 'haiku', name: 'anthropic/claude-3-5-haiku-latest', provider: 'anthropic', description: 'Ultra-cheap, simple tasks', costPer1k: 0.25 },
346
- { alias: 'sonnet', name: 'anthropic/claude-sonnet-4-20250514', provider: 'anthropic', description: 'Standard workhorse', costPer1k: 3.0 },
347
- { alias: 'opus', name: 'anthropic/claude-opus-4-5', provider: 'anthropic', description: 'Premium quality', costPer1k: 15.0 },
348
- { alias: 'deepseek', name: 'ollama/deepseek-r1:14b', provider: 'ollama', description: 'Local reasoning (free)', costPer1k: 0.0 },
349
- { alias: 'groq-fast', name: 'groq/llama-3.1-8b-instant', provider: 'groq', description: '840 tok/s, ultra fast', costPer1k: 0.05 },
350
- { alias: 'groq', name: 'groq/llama-3.3-70b-versatile', provider: 'groq', description: 'Fast + quality balance', costPer1k: 0.59 },
351
- { alias: 'kimi', name: 'moonshot/kimi-k2.5', provider: 'moonshot', description: 'Alternative provider', costPer1k: 1.0 },
352
- { alias: 'minimax', name: 'minimax/minimax-m2.1', provider: 'minimax', description: 'Cost-effective (1/10th price), strong coding', costPer1k: 0.3 },
353
- ]
354
 
355
  try {
356
  // Check which Ollama models are available locally
 
6
  import { getDatabase } from '@/lib/db'
7
  import { getAllGatewaySessions, getAgentLiveStatuses } from '@/lib/sessions'
8
  import { requireRole } from '@/lib/auth'
9
+ import { MODEL_CATALOG } from '@/lib/models'
10
 
11
  export async function GET(request: NextRequest) {
12
  const auth = requireRole(request, 'viewer')
 
341
 
342
  async function getAvailableModels() {
343
  // This would typically query the gateway or config files
344
+ // Model catalog is the single source of truth
345
+ const models = [...MODEL_CATALOG]
 
 
 
 
 
 
 
 
 
346
 
347
  try {
348
  // Check which Ollama models are available locally
src/app/api/tasks/[id]/route.ts CHANGED
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
2
  import { getDatabase, Task, db_helpers } from '@/lib/db';
3
  import { eventBus } from '@/lib/event-bus';
4
  import { getUserFromRequest, requireRole } from '@/lib/auth';
 
5
  import { logger } from '@/lib/logger';
6
  import { validateBody, updateTaskSchema } from '@/lib/validation';
7
 
@@ -65,6 +66,9 @@ export async function PUT(
65
  const auth = requireRole(request, 'operator');
66
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
67
 
 
 
 
68
  try {
69
  const db = getDatabase();
70
  const resolvedParams = await params;
@@ -259,6 +263,9 @@ export async function DELETE(
259
  const auth = requireRole(request, 'operator');
260
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
261
 
 
 
 
262
  try {
263
  const db = getDatabase();
264
  const resolvedParams = await params;
 
2
  import { getDatabase, Task, db_helpers } from '@/lib/db';
3
  import { eventBus } from '@/lib/event-bus';
4
  import { getUserFromRequest, requireRole } from '@/lib/auth';
5
+ import { mutationLimiter } from '@/lib/rate-limit';
6
  import { logger } from '@/lib/logger';
7
  import { validateBody, updateTaskSchema } from '@/lib/validation';
8
 
 
66
  const auth = requireRole(request, 'operator');
67
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
68
 
69
+ const rateCheck = mutationLimiter(request);
70
+ if (rateCheck) return rateCheck;
71
+
72
  try {
73
  const db = getDatabase();
74
  const resolvedParams = await params;
 
263
  const auth = requireRole(request, 'operator');
264
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
265
 
266
+ const rateCheck = mutationLimiter(request);
267
+ if (rateCheck) return rateCheck;
268
+
269
  try {
270
  const db = getDatabase();
271
  const resolvedParams = await params;
src/app/api/tasks/route.ts CHANGED
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
2
  import { getDatabase, Task, db_helpers } from '@/lib/db';
3
  import { eventBus } from '@/lib/event-bus';
4
  import { requireRole } from '@/lib/auth';
 
5
  import { logger } from '@/lib/logger';
6
  import { validateBody, createTaskSchema } from '@/lib/validation';
7
 
@@ -97,6 +98,9 @@ export async function POST(request: NextRequest) {
97
  const auth = requireRole(request, 'operator');
98
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
99
 
 
 
 
100
  try {
101
  const db = getDatabase();
102
  const validated = await validateBody(request, createTaskSchema);
@@ -199,6 +203,9 @@ export async function PUT(request: NextRequest) {
199
  const auth = requireRole(request, 'operator');
200
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
201
 
 
 
 
202
  try {
203
  const db = getDatabase();
204
  const { tasks } = await request.json();
 
2
  import { getDatabase, Task, db_helpers } from '@/lib/db';
3
  import { eventBus } from '@/lib/event-bus';
4
  import { requireRole } from '@/lib/auth';
5
+ import { mutationLimiter } from '@/lib/rate-limit';
6
  import { logger } from '@/lib/logger';
7
  import { validateBody, createTaskSchema } from '@/lib/validation';
8
 
 
98
  const auth = requireRole(request, 'operator');
99
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
100
 
101
+ const rateCheck = mutationLimiter(request);
102
+ if (rateCheck) return rateCheck;
103
+
104
  try {
105
  const db = getDatabase();
106
  const validated = await validateBody(request, createTaskSchema);
 
203
  const auth = requireRole(request, 'operator');
204
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
205
 
206
+ const rateCheck = mutationLimiter(request);
207
+ if (rateCheck) return rateCheck;
208
+
209
  try {
210
  const db = getDatabase();
211
  const { tasks } = await request.json();
src/app/api/webhooks/route.ts CHANGED
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
2
  import { getDatabase } from '@/lib/db'
3
  import { requireRole } from '@/lib/auth'
4
  import { randomBytes, createHmac } from 'crypto'
 
5
  import { logger } from '@/lib/logger'
6
  import { validateBody, createWebhookSchema } from '@/lib/validation'
7
 
@@ -45,6 +46,9 @@ export async function POST(request: NextRequest) {
45
  const auth = requireRole(request, 'admin')
46
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
47
 
 
 
 
48
  try {
49
  const db = getDatabase()
50
  const validated = await validateBody(request, createWebhookSchema)
@@ -82,6 +86,9 @@ export async function PUT(request: NextRequest) {
82
  const auth = requireRole(request, 'admin')
83
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
84
 
 
 
 
85
  try {
86
  const db = getDatabase()
87
  const body = await request.json()
@@ -137,6 +144,9 @@ export async function DELETE(request: NextRequest) {
137
  const auth = requireRole(request, 'admin')
138
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
139
 
 
 
 
140
  try {
141
  const db = getDatabase()
142
  let body: any
 
2
  import { getDatabase } from '@/lib/db'
3
  import { requireRole } from '@/lib/auth'
4
  import { randomBytes, createHmac } from 'crypto'
5
+ import { mutationLimiter } from '@/lib/rate-limit'
6
  import { logger } from '@/lib/logger'
7
  import { validateBody, createWebhookSchema } from '@/lib/validation'
8
 
 
46
  const auth = requireRole(request, 'admin')
47
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
48
 
49
+ const rateCheck = mutationLimiter(request)
50
+ if (rateCheck) return rateCheck
51
+
52
  try {
53
  const db = getDatabase()
54
  const validated = await validateBody(request, createWebhookSchema)
 
86
  const auth = requireRole(request, 'admin')
87
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
88
 
89
+ const rateCheck = mutationLimiter(request)
90
+ if (rateCheck) return rateCheck
91
+
92
  try {
93
  const db = getDatabase()
94
  const body = await request.json()
 
144
  const auth = requireRole(request, 'admin')
145
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
146
 
147
+ const rateCheck = mutationLimiter(request)
148
+ if (rateCheck) return rateCheck
149
+
150
  try {
151
  const db = getDatabase()
152
  let body: any
src/components/panels/session-details-panel.tsx CHANGED
@@ -26,6 +26,7 @@ export function SessionDetailsPanel() {
26
 
27
  useSmartPoll(loadSessions, 60000, { pauseWhenConnected: true })
28
 
 
29
  const [sessionFilter, setSessionFilter] = useState<'all' | 'active' | 'idle'>('all')
30
  const [sortBy, setSortBy] = useState<'age' | 'tokens' | 'model'>('age')
31
  const [expandedSession, setExpandedSession] = useState<string | null>(null)
@@ -323,36 +324,80 @@ export function SessionDetailsPanel() {
323
  {/* Actions */}
324
  <div className="flex space-x-2">
325
  <button
326
- className="px-3 py-1 text-xs bg-blue-500/20 text-blue-400 border border-blue-500/30 rounded hover:bg-blue-500/30 transition-colors"
327
- onClick={(e) => {
 
328
  e.stopPropagation()
329
- // TODO: Implement session monitoring
330
- console.log('Monitor session:', session.id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  }}
332
  >
333
- Monitor
334
  </button>
335
  <button
336
- className="px-3 py-1 text-xs bg-yellow-500/20 text-yellow-400 border border-yellow-500/30 rounded hover:bg-yellow-500/30 transition-colors"
337
- onClick={(e) => {
 
338
  e.stopPropagation()
339
- // TODO: Implement session pause
340
- console.log('Pause session:', session.id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  }}
342
  >
343
- Pause
344
  </button>
345
  <button
346
- className="px-3 py-1 text-xs bg-red-500/20 text-red-400 border border-red-500/30 rounded hover:bg-red-500/30 transition-colors"
347
- onClick={(e) => {
 
348
  e.stopPropagation()
349
- if (confirm('Are you sure you want to terminate this session?')) {
350
- // TODO: Implement session termination
351
- console.log('Terminate session:', session.id)
 
 
 
 
 
 
 
 
 
 
 
 
 
352
  }
353
  }}
354
  >
355
- Terminate
356
  </button>
357
  </div>
358
  </div>
 
26
 
27
  useSmartPoll(loadSessions, 60000, { pauseWhenConnected: true })
28
 
29
+ const [controllingSession, setControllingSession] = useState<string | null>(null)
30
  const [sessionFilter, setSessionFilter] = useState<'all' | 'active' | 'idle'>('all')
31
  const [sortBy, setSortBy] = useState<'age' | 'tokens' | 'model'>('age')
32
  const [expandedSession, setExpandedSession] = useState<string | null>(null)
 
324
  {/* Actions */}
325
  <div className="flex space-x-2">
326
  <button
327
+ className="px-3 py-1 text-xs bg-blue-500/20 text-blue-400 border border-blue-500/30 rounded hover:bg-blue-500/30 transition-colors disabled:opacity-50"
328
+ disabled={controllingSession !== null}
329
+ onClick={async (e) => {
330
  e.stopPropagation()
331
+ setControllingSession(`monitor-${session.id}`)
332
+ try {
333
+ const res = await fetch(`/api/sessions/${session.id}/control`, {
334
+ method: 'POST',
335
+ headers: { 'Content-Type': 'application/json' },
336
+ body: JSON.stringify({ action: 'monitor' }),
337
+ })
338
+ if (!res.ok) {
339
+ const data = await res.json()
340
+ alert(data.error || 'Failed to monitor session')
341
+ }
342
+ } catch {
343
+ alert('Failed to monitor session')
344
+ } finally {
345
+ setControllingSession(null)
346
+ }
347
  }}
348
  >
349
+ {controllingSession === `monitor-${session.id}` ? 'Working...' : 'Monitor'}
350
  </button>
351
  <button
352
+ className="px-3 py-1 text-xs bg-yellow-500/20 text-yellow-400 border border-yellow-500/30 rounded hover:bg-yellow-500/30 transition-colors disabled:opacity-50"
353
+ disabled={controllingSession !== null}
354
+ onClick={async (e) => {
355
  e.stopPropagation()
356
+ setControllingSession(`pause-${session.id}`)
357
+ try {
358
+ const res = await fetch(`/api/sessions/${session.id}/control`, {
359
+ method: 'POST',
360
+ headers: { 'Content-Type': 'application/json' },
361
+ body: JSON.stringify({ action: 'pause' }),
362
+ })
363
+ if (!res.ok) {
364
+ const data = await res.json()
365
+ alert(data.error || 'Failed to pause session')
366
+ }
367
+ } catch {
368
+ alert('Failed to pause session')
369
+ } finally {
370
+ setControllingSession(null)
371
+ }
372
  }}
373
  >
374
+ {controllingSession === `pause-${session.id}` ? 'Working...' : 'Pause'}
375
  </button>
376
  <button
377
+ className="px-3 py-1 text-xs bg-red-500/20 text-red-400 border border-red-500/30 rounded hover:bg-red-500/30 transition-colors disabled:opacity-50"
378
+ disabled={controllingSession !== null}
379
+ onClick={async (e) => {
380
  e.stopPropagation()
381
+ if (!window.confirm('Are you sure you want to terminate this session?')) return
382
+ setControllingSession(`terminate-${session.id}`)
383
+ try {
384
+ const res = await fetch(`/api/sessions/${session.id}/control`, {
385
+ method: 'POST',
386
+ headers: { 'Content-Type': 'application/json' },
387
+ body: JSON.stringify({ action: 'terminate' }),
388
+ })
389
+ if (!res.ok) {
390
+ const data = await res.json()
391
+ alert(data.error || 'Failed to terminate session')
392
+ }
393
+ } catch {
394
+ alert('Failed to terminate session')
395
+ } finally {
396
+ setControllingSession(null)
397
  }
398
  }}
399
  >
400
+ {controllingSession === `terminate-${session.id}` ? 'Working...' : 'Terminate'}
401
  </button>
402
  </div>
403
  </div>
src/lib/models.ts ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface ModelConfig {
2
+ alias: string
3
+ name: string
4
+ provider: string
5
+ description: string
6
+ costPer1k: number
7
+ }
8
+
9
+ export const MODEL_CATALOG: ModelConfig[] = [
10
+ { alias: 'haiku', name: 'anthropic/claude-3-5-haiku-latest', provider: 'anthropic', description: 'Ultra-cheap, simple tasks', costPer1k: 0.25 },
11
+ { alias: 'sonnet', name: 'anthropic/claude-sonnet-4-20250514', provider: 'anthropic', description: 'Standard workhorse', costPer1k: 3.0 },
12
+ { alias: 'opus', name: 'anthropic/claude-opus-4-5', provider: 'anthropic', description: 'Premium quality', costPer1k: 15.0 },
13
+ { alias: 'deepseek', name: 'ollama/deepseek-r1:14b', provider: 'ollama', description: 'Local reasoning (free)', costPer1k: 0.0 },
14
+ { alias: 'groq-fast', name: 'groq/llama-3.1-8b-instant', provider: 'groq', description: '840 tok/s, ultra fast', costPer1k: 0.05 },
15
+ { alias: 'groq', name: 'groq/llama-3.3-70b-versatile', provider: 'groq', description: 'Fast + quality balance', costPer1k: 0.59 },
16
+ { alias: 'kimi', name: 'moonshot/kimi-k2.5', provider: 'moonshot', description: 'Alternative provider', costPer1k: 1.0 },
17
+ { alias: 'minimax', name: 'minimax/minimax-m2.1', provider: 'minimax', description: 'Cost-effective (1/10th price), strong coding', costPer1k: 0.3 },
18
+ ]
19
+
20
+ export function getModelByAlias(alias: string): ModelConfig | undefined {
21
+ return MODEL_CATALOG.find(m => m.alias === alias)
22
+ }
23
+
24
+ export function getModelByName(name: string): ModelConfig | undefined {
25
+ return MODEL_CATALOG.find(m => m.name === name)
26
+ }
27
+
28
+ export function getAllModels(): ModelConfig[] {
29
+ return [...MODEL_CATALOG]
30
+ }
src/lib/rate-limit.ts ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextResponse } from 'next/server'
2
+
3
+ interface RateLimitEntry {
4
+ count: number
5
+ resetAt: number
6
+ }
7
+
8
+ interface RateLimiterOptions {
9
+ windowMs: number
10
+ maxRequests: number
11
+ message?: string
12
+ }
13
+
14
+ export function createRateLimiter(options: RateLimiterOptions) {
15
+ const store = new Map<string, RateLimitEntry>()
16
+
17
+ // Periodic cleanup every 60s
18
+ const cleanupInterval = setInterval(() => {
19
+ const now = Date.now()
20
+ for (const [key, entry] of store) {
21
+ if (now > entry.resetAt) store.delete(key)
22
+ }
23
+ }, 60_000)
24
+ // Don't prevent process exit
25
+ if (cleanupInterval.unref) cleanupInterval.unref()
26
+
27
+ return function checkRateLimit(request: Request): NextResponse | null {
28
+ const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown'
29
+ const now = Date.now()
30
+ const entry = store.get(ip)
31
+
32
+ if (!entry || now > entry.resetAt) {
33
+ store.set(ip, { count: 1, resetAt: now + options.windowMs })
34
+ return null
35
+ }
36
+
37
+ entry.count++
38
+ if (entry.count > options.maxRequests) {
39
+ return NextResponse.json(
40
+ { error: options.message || 'Too many requests. Please try again later.' },
41
+ { status: 429 }
42
+ )
43
+ }
44
+
45
+ return null
46
+ }
47
+ }
48
+
49
+ export const loginLimiter = createRateLimiter({
50
+ windowMs: 60_000,
51
+ maxRequests: 5,
52
+ message: 'Too many login attempts. Try again in a minute.',
53
+ })
54
+
55
+ export const mutationLimiter = createRateLimiter({
56
+ windowMs: 60_000,
57
+ maxRequests: 60,
58
+ })
59
+
60
+ export const heavyLimiter = createRateLimiter({
61
+ windowMs: 60_000,
62
+ maxRequests: 10,
63
+ message: 'Too many requests for this resource. Please try again later.',
64
+ })
src/lib/validation.ts CHANGED
@@ -36,8 +36,8 @@ export const createTaskSchema = z.object({
36
  due_date: z.number().optional(),
37
  estimated_hours: z.number().min(0).optional(),
38
  actual_hours: z.number().min(0).optional(),
39
- tags: z.array(z.string()).default([]),
40
- metadata: z.record(z.string(), z.unknown()).default({}),
41
  })
42
 
43
  export const updateTaskSchema = createTaskSchema.partial()
@@ -48,7 +48,7 @@ export const createAgentSchema = z.object({
48
  session_key: z.string().max(200).optional(),
49
  soul_content: z.string().max(50000).optional(),
50
  status: z.enum(['online', 'offline', 'busy', 'idle', 'error']).default('offline'),
51
- config: z.record(z.string(), z.unknown()).default({}),
52
  template: z.string().max(100).optional(),
53
  gateway_config: z.record(z.string(), z.unknown()).optional(),
54
  write_to_gateway: z.boolean().optional(),
 
36
  due_date: z.number().optional(),
37
  estimated_hours: z.number().min(0).optional(),
38
  actual_hours: z.number().min(0).optional(),
39
+ tags: z.array(z.string()).default([] as string[]),
40
+ metadata: z.record(z.string(), z.unknown()).default({} as Record<string, unknown>),
41
  })
42
 
43
  export const updateTaskSchema = createTaskSchema.partial()
 
48
  session_key: z.string().max(200).optional(),
49
  soul_content: z.string().max(50000).optional(),
50
  status: z.enum(['online', 'offline', 'busy', 'idle', 'error']).default('offline'),
51
+ config: z.record(z.string(), z.unknown()).default({} as Record<string, unknown>),
52
  template: z.string().max(100).optional(),
53
  gateway_config: z.record(z.string(), z.unknown()).optional(),
54
  write_to_gateway: z.boolean().optional(),
src/store/index.ts CHANGED
@@ -2,6 +2,7 @@
2
 
3
  import { create } from 'zustand'
4
  import { subscribeWithSelector } from 'zustand/middleware'
 
5
 
6
  // Enhanced types for Mission Control
7
  export interface Session {
@@ -523,16 +524,7 @@ export const useMissionControl = create<MissionControlStore>()(
523
  },
524
 
525
  // Model Configuration
526
- availableModels: [
527
- { alias: 'haiku', name: 'anthropic/claude-3-5-haiku-latest', provider: 'anthropic', description: 'Ultra-cheap, simple tasks', costPer1k: 0.25 },
528
- { alias: 'sonnet', name: 'anthropic/claude-sonnet-4-20250514', provider: 'anthropic', description: 'Standard workhorse', costPer1k: 3.0 },
529
- { alias: 'opus', name: 'anthropic/claude-opus-4-5', provider: 'anthropic', description: 'Premium quality', costPer1k: 15.0 },
530
- { alias: 'deepseek', name: 'ollama/deepseek-r1:14b', provider: 'ollama', description: 'Local reasoning (free)', costPer1k: 0.0 },
531
- { alias: 'groq-fast', name: 'groq/llama-3.1-8b-instant', provider: 'groq', description: '840 tok/s, ultra fast', costPer1k: 0.05 },
532
- { alias: 'groq', name: 'groq/llama-3.3-70b-versatile', provider: 'groq', description: 'Fast + quality balance', costPer1k: 0.59 },
533
- { alias: 'kimi', name: 'moonshot/kimi-k2.5', provider: 'moonshot', description: 'Alternative provider', costPer1k: 1.0 },
534
- { alias: 'minimax', name: 'minimax/minimax-m2.1', provider: 'minimax', description: 'Cost-effective (1/10th price), strong coding', costPer1k: 0.3 },
535
- ],
536
  setAvailableModels: (models) => set({ availableModels: models }),
537
 
538
  // Auth
 
2
 
3
  import { create } from 'zustand'
4
  import { subscribeWithSelector } from 'zustand/middleware'
5
+ import { MODEL_CATALOG } from '@/lib/models'
6
 
7
  // Enhanced types for Mission Control
8
  export interface Session {
 
524
  },
525
 
526
  // Model Configuration
527
+ availableModels: [...MODEL_CATALOG],
 
 
 
 
 
 
 
 
 
528
  setAvailableModels: (models) => set({ availableModels: models }),
529
 
530
  // Auth