refactor(server): move the team runtime into a postponed package (P1.1)
Team mode stays in the repository but is not built or shipped (ADR-0003). - The team server (index.ts, config, db, daemons, plugins, proactive, routes, scheduler, services, ws, drizzle migrations) and its tests move from @waggle/server to packages/team-server (@waggle/team-server, private). It keeps its own copies of the logger and the agent-group executor, so it does not import @waggle/server. @clerk/fastify, bullmq, ioredis, postgres, drizzle-orm, drizzle-kit, cron-parser and @waggle/waggle-dance leave @waggle/server; the launcher drops the same team-only dependencies. - build:packages no longer builds waggle-dance or the worker: nothing in the community edition imports them, and the worker's project reference would otherwise build the team server. The worker now imports from team-server; the team Dockerfile builds both explicitly. - The sidecar no longer starts the team server when DATABASE_URL is set, and loses the team routes (/api/team/*, /api/teams), the WaggleDance routes and bridge (/api/waggle-dance/*), the Team server binding and egress guard, the WebSocket team client, the TeamSync cache and pushes, team audit forwarding, team workspace registration and the team capability-policy lookup in chat. The in-process room signal bus stays: agent groups, fleet runs and external tool runs use it. middleware/audit.ts was dead and is deleted. - @waggle/core loses TeamSync and the teamServer part of WaggleConfig. A teamServer key in config.json is ignored and kept on save, as P0.1 does for the tier keys. Workspaces lose teamServerUrl and teamUserId; teamId and teamRole stay because workspaces from a shared data directory still carry them and the viewer write guards read them. POST /api/workspaces ignores team fields. - The sidecar bundle no longer marks the team packages as external. The agent still references the TeamSync type in orchestrator.ts and pattern-write-back.ts; those files are being rewritten in P1.5 and drop it there. Logs UF-030 and UF-031 (team sync and team policy defects found while removing the code).
This commit is contained in:
42
packages/team-server/src/config.ts
Normal file
42
packages/team-server/src/config.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
export interface ServerConfig {
|
||||
port: number;
|
||||
host: string;
|
||||
databaseUrl: string;
|
||||
redisUrl: string;
|
||||
clerkSecretKey: string;
|
||||
clerkPublishableKey: string;
|
||||
corsOrigin: string[];
|
||||
}
|
||||
|
||||
export function loadConfig(): ServerConfig {
|
||||
return {
|
||||
port: parseInt(process.env.PORT ?? '3100', 10),
|
||||
host: process.env.HOST ?? '0.0.0.0',
|
||||
databaseUrl: (() => {
|
||||
const url = process.env.DATABASE_URL;
|
||||
if (!url) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('DATABASE_URL environment variable is required');
|
||||
}
|
||||
return 'postgres://localhost:5434/waggle';
|
||||
}
|
||||
return url;
|
||||
})(),
|
||||
redisUrl: process.env.REDIS_URL ?? 'redis://localhost:6381',
|
||||
clerkSecretKey: process.env.CLERK_SECRET_KEY ?? '',
|
||||
clerkPublishableKey: process.env.CLERK_PUBLISHABLE_KEY ?? '',
|
||||
corsOrigin: (() => {
|
||||
const origins = process.env.CORS_ORIGIN;
|
||||
if (!origins) {
|
||||
// Fail closed in production: a missing CORS_ORIGIN must not silently
|
||||
// fall back to a localhost dev origin (which both blocks the real prod
|
||||
// frontend AND leaves an unintended localhost origin allowed).
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('CORS_ORIGIN environment variable is required in production');
|
||||
}
|
||||
return ['http://localhost:5173'];
|
||||
}
|
||||
return origins.split(',').map((o) => o.trim()).filter(Boolean);
|
||||
})(),
|
||||
};
|
||||
}
|
||||
126
packages/team-server/src/daemons/hive-mind.ts
Normal file
126
packages/team-server/src/daemons/hive-mind.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { eq, and, desc, gte, sql } from 'drizzle-orm';
|
||||
import { agentJobs, teamResources, tasks, messages, teamMembers } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class HiveMindAgent {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async generateWeeklyDigest(teamId: string): Promise<{ digest: WeeklyDigest; messageId: string }> {
|
||||
const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Aggregate metrics
|
||||
const jobsCompleted = await this.db.select().from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.teamId, teamId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
gte(agentJobs.completedAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const tasksCompleted = await this.db.select().from(tasks)
|
||||
.where(and(
|
||||
eq(tasks.teamId, teamId),
|
||||
eq(tasks.status, 'done'),
|
||||
));
|
||||
|
||||
const resourcesShared = await this.db.select().from(teamResources)
|
||||
.where(and(
|
||||
eq(teamResources.teamId, teamId),
|
||||
gte(teamResources.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const waggleMessages = await this.db.select().from(messages)
|
||||
.where(and(
|
||||
eq(messages.teamId, teamId),
|
||||
gte(messages.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
// Detect duplicate work (similar task titles by different users)
|
||||
const duplicates = this.detectDuplicateWork(tasksCompleted);
|
||||
|
||||
// Find high-rated resources as best practices
|
||||
const bestPractices = await this.db.select().from(teamResources)
|
||||
.where(and(
|
||||
eq(teamResources.teamId, teamId),
|
||||
gte(teamResources.rating, sql`3.0`),
|
||||
))
|
||||
.orderBy(desc(teamResources.rating))
|
||||
.limit(5);
|
||||
|
||||
const digest: WeeklyDigest = {
|
||||
period: { from: oneWeekAgo, to: new Date() },
|
||||
metrics: {
|
||||
jobsCompleted: jobsCompleted.length,
|
||||
tasksCompleted: tasksCompleted.length,
|
||||
resourcesShared: resourcesShared.length,
|
||||
waggleMessages: waggleMessages.length,
|
||||
},
|
||||
duplicateWork: duplicates,
|
||||
bestPractices: bestPractices.map(r => ({ name: r.name, type: r.resourceType, rating: r.rating })),
|
||||
recommendations: this.generateRecommendations(jobsCompleted, duplicates, bestPractices),
|
||||
};
|
||||
|
||||
// Get a team member to attribute the broadcast to
|
||||
const [firstMember] = await this.db.select().from(teamMembers)
|
||||
.where(eq(teamMembers.teamId, teamId))
|
||||
.limit(1);
|
||||
|
||||
const senderId = firstMember?.userId ?? '';
|
||||
|
||||
// Broadcast digest as Waggle Dance message
|
||||
const [msg] = await this.db.insert(messages).values({
|
||||
teamId,
|
||||
senderId,
|
||||
type: 'broadcast',
|
||||
subtype: 'discovery',
|
||||
content: { type: 'weekly_digest', digest },
|
||||
}).returning();
|
||||
|
||||
return { digest, messageId: msg.id };
|
||||
}
|
||||
|
||||
private detectDuplicateWork(tasksList: Array<{ title: string; createdBy: string }>): DuplicateWork[] {
|
||||
// Group by similar titles (case-insensitive first 20 chars)
|
||||
const groups = new Map<string, { titles: string[]; users: Set<string> }>();
|
||||
for (const task of tasksList) {
|
||||
const key = task.title.toLowerCase().substring(0, 20);
|
||||
if (!groups.has(key)) groups.set(key, { titles: [], users: new Set() });
|
||||
groups.get(key)!.titles.push(task.title);
|
||||
groups.get(key)!.users.add(task.createdBy);
|
||||
}
|
||||
return Array.from(groups.values())
|
||||
.filter(g => g.users.size > 1)
|
||||
.map(g => ({ titles: g.titles, users: Array.from(g.users) }));
|
||||
}
|
||||
|
||||
private generateRecommendations(jobs: unknown[], duplicates: DuplicateWork[], bestPractices: unknown[]): string[] {
|
||||
const recommendations: string[] = [];
|
||||
if (duplicates.length > 0) {
|
||||
recommendations.push(`${duplicates.length} potential duplicate work detected. Consider checking the hive before starting tasks.`);
|
||||
}
|
||||
if (bestPractices.length > 0) {
|
||||
recommendations.push(`${bestPractices.length} highly-rated resources available. Share them team-wide.`);
|
||||
}
|
||||
if (jobs.length > 50) {
|
||||
recommendations.push('High job volume this week. Consider automating recurring tasks with cron schedules.');
|
||||
}
|
||||
return recommendations;
|
||||
}
|
||||
}
|
||||
|
||||
interface DuplicateWork {
|
||||
titles: string[];
|
||||
users: string[];
|
||||
}
|
||||
|
||||
interface WeeklyDigest {
|
||||
period: { from: Date; to: Date };
|
||||
metrics: {
|
||||
jobsCompleted: number;
|
||||
tasksCompleted: number;
|
||||
resourcesShared: number;
|
||||
waggleMessages: number;
|
||||
};
|
||||
duplicateWork: DuplicateWork[];
|
||||
bestPractices: Array<{ name: string; type: string; rating: number }>;
|
||||
recommendations: string[];
|
||||
}
|
||||
127
packages/team-server/src/daemons/scout.ts
Normal file
127
packages/team-server/src/daemons/scout.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { eq, and, desc } from 'drizzle-orm';
|
||||
import { scoutFindings, agents, teamMembers, teamResources } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
interface Finding {
|
||||
source: string;
|
||||
category: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
relevanceScore: number;
|
||||
url: string | null;
|
||||
}
|
||||
|
||||
export class ScoutAgent {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async scan(userId: string, teamId: string): Promise<Array<typeof scoutFindings.$inferSelect>> {
|
||||
const findings: Finding[] = [];
|
||||
|
||||
// Source 1: Check team resources for newly shared items
|
||||
findings.push(...await this.checkTeamResources(teamId));
|
||||
|
||||
// Source 2: Mock marketplace check (would check npm/MCP registry in production)
|
||||
findings.push(...await this.checkMarketplace(userId));
|
||||
|
||||
// Score relevance based on user's agent configs and role
|
||||
const scored = await this.scoreRelevance(findings, userId, teamId);
|
||||
|
||||
// Filter out findings with titles already dismissed by this user
|
||||
const existingDismissed = await this.db.select().from(scoutFindings)
|
||||
.where(and(
|
||||
eq(scoutFindings.userId, userId),
|
||||
eq(scoutFindings.status, 'dismissed'),
|
||||
));
|
||||
const dismissedTitles = new Set(existingDismissed.map(f => f.title));
|
||||
const filtered = scored.filter(f => !dismissedTitles.has(f.title));
|
||||
|
||||
// Store findings
|
||||
const stored = [];
|
||||
for (const finding of filtered) {
|
||||
const [entry] = await this.db.insert(scoutFindings).values({
|
||||
userId,
|
||||
teamId,
|
||||
source: finding.source,
|
||||
category: finding.category,
|
||||
title: finding.title,
|
||||
summary: finding.summary,
|
||||
relevanceScore: finding.relevanceScore,
|
||||
url: finding.url,
|
||||
status: 'new',
|
||||
}).returning();
|
||||
stored.push(entry);
|
||||
}
|
||||
|
||||
return stored;
|
||||
}
|
||||
|
||||
private async checkTeamResources(teamId: string): Promise<Finding[]> {
|
||||
const recent = await this.db.select().from(teamResources)
|
||||
.where(eq(teamResources.teamId, teamId))
|
||||
.orderBy(desc(teamResources.createdAt))
|
||||
.limit(5);
|
||||
|
||||
return recent.map(r => ({
|
||||
source: 'team' as const,
|
||||
category: r.resourceType === 'skill' ? 'skill' : 'practice',
|
||||
title: `New team resource: ${r.name}`,
|
||||
summary: r.description ?? `A ${r.resourceType} shared by a team member`,
|
||||
relevanceScore: 0.5,
|
||||
url: null,
|
||||
}));
|
||||
}
|
||||
|
||||
private async checkMarketplace(_userId: string): Promise<Finding[]> {
|
||||
// Mock: In production, would check npm registry for MCP packages, skill marketplace, etc.
|
||||
return [];
|
||||
}
|
||||
|
||||
private async scoreRelevance(findings: Finding[], userId: string, teamId: string): Promise<Finding[]> {
|
||||
// Load user's agent configs for interest matching
|
||||
const userAgents = await this.db.select().from(agents)
|
||||
.where(eq(agents.userId, userId));
|
||||
|
||||
// Load member interests
|
||||
const [membership] = await this.db.select().from(teamMembers)
|
||||
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)));
|
||||
|
||||
const interests = (membership?.interests as string[]) ?? [];
|
||||
const agentTools = userAgents.flatMap(a => (a.tools as string[]) ?? []);
|
||||
|
||||
return findings.map(f => {
|
||||
let score = f.relevanceScore;
|
||||
// Boost if matches user interests
|
||||
if (interests.some(i => f.title.toLowerCase().includes(i.toLowerCase()))) score += 0.3;
|
||||
// Boost if matches agent tool names
|
||||
if (agentTools.some(t => f.title.toLowerCase().includes(t.toLowerCase()))) score += 0.2;
|
||||
return { ...f, relevanceScore: Math.min(score, 1.0) };
|
||||
});
|
||||
}
|
||||
|
||||
async adopt(findingId: string, userId: string) {
|
||||
const [updated] = await this.db.update(scoutFindings)
|
||||
.set({ status: 'adopted' })
|
||||
.where(and(
|
||||
eq(scoutFindings.id, findingId),
|
||||
eq(scoutFindings.userId, userId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async dismiss(findingId: string, userId: string) {
|
||||
const [updated] = await this.db.update(scoutFindings)
|
||||
.set({ status: 'dismissed' })
|
||||
.where(and(
|
||||
eq(scoutFindings.id, findingId),
|
||||
eq(scoutFindings.userId, userId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async listFindings(userId: string) {
|
||||
return this.db.select().from(scoutFindings)
|
||||
.where(eq(scoutFindings.userId, userId));
|
||||
}
|
||||
}
|
||||
94
packages/team-server/src/daemons/subconscious.ts
Normal file
94
packages/team-server/src/daemons/subconscious.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { eq, desc, and, sql } from 'drizzle-orm';
|
||||
import { agentJobs, agentAuditLog } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import { SUBCONSCIOUS_INTERACTION_THRESHOLD } from '@waggle/shared';
|
||||
|
||||
export class SubconsciousAgent {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async shouldReflect(userId: string): Promise<boolean> {
|
||||
// Count completed jobs since last reflection
|
||||
const lastReflection = await this.db.select().from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.userId, userId),
|
||||
eq(agentAuditLog.actionType, 'subconscious_reflection'),
|
||||
))
|
||||
.orderBy(desc(agentAuditLog.createdAt))
|
||||
.limit(1);
|
||||
|
||||
const since = lastReflection[0]?.createdAt ?? new Date(0);
|
||||
const sinceIso = since.toISOString();
|
||||
|
||||
const recentJobs = await this.db.select().from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.userId, userId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
sql`${agentJobs.completedAt} > ${sinceIso}::timestamptz`,
|
||||
));
|
||||
|
||||
return recentJobs.length >= SUBCONSCIOUS_INTERACTION_THRESHOLD;
|
||||
}
|
||||
|
||||
async reflect(userId: string): Promise<{ auditEntry: typeof agentAuditLog.$inferSelect; insights: Insight[] }> {
|
||||
// Get recent completed jobs
|
||||
const recentJobs = await this.db.select().from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.userId, userId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
))
|
||||
.orderBy(desc(agentJobs.completedAt))
|
||||
.limit(20);
|
||||
|
||||
// Analyze patterns
|
||||
const insights = this.analyzePatterns(recentJobs);
|
||||
|
||||
// Log the reflection
|
||||
const [auditEntry] = await this.db.insert(agentAuditLog).values({
|
||||
userId,
|
||||
agentName: 'subconscious',
|
||||
actionType: 'subconscious_reflection',
|
||||
description: `Reflected on ${recentJobs.length} recent jobs. Found ${insights.length} insights.`,
|
||||
afterState: { insights },
|
||||
requiresApproval: insights.some(i => i.type === 'prompt_change'),
|
||||
}).returning();
|
||||
|
||||
return { auditEntry, insights };
|
||||
}
|
||||
|
||||
private analyzePatterns(jobs: Array<typeof agentJobs.$inferSelect>): Insight[] {
|
||||
const insights: Insight[] = [];
|
||||
|
||||
// Pattern: repeated job types
|
||||
const typeCounts = new Map<string, number>();
|
||||
for (const job of jobs) {
|
||||
typeCounts.set(job.jobType, (typeCounts.get(job.jobType) ?? 0) + 1);
|
||||
}
|
||||
for (const [type, count] of typeCounts) {
|
||||
if (count >= 5) {
|
||||
insights.push({
|
||||
type: 'prompt_change',
|
||||
description: `Job type "${type}" executed ${count} times recently`,
|
||||
recommendation: `Consider optimizing the system prompt for ${type} tasks`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Pattern: failed jobs
|
||||
const failedCount = jobs.filter(j => j.status === 'failed').length;
|
||||
if (failedCount >= 3) {
|
||||
insights.push({
|
||||
type: 'tool_issue',
|
||||
description: `${failedCount} jobs failed recently`,
|
||||
recommendation: 'Review tool configurations and consider adding error handling',
|
||||
});
|
||||
}
|
||||
|
||||
return insights;
|
||||
}
|
||||
}
|
||||
|
||||
interface Insight {
|
||||
type: string;
|
||||
description: string;
|
||||
recommendation: string;
|
||||
}
|
||||
16
packages/team-server/src/db/connection.ts
Normal file
16
packages/team-server/src/db/connection.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { drizzle } from 'drizzle-orm/postgres-js';
|
||||
import postgres from 'postgres';
|
||||
import * as schema from './schema.js';
|
||||
|
||||
export function createDb(connectionString: string) {
|
||||
const client = postgres(connectionString);
|
||||
return drizzle(client, { schema });
|
||||
}
|
||||
|
||||
export type Db = ReturnType<typeof createDb>;
|
||||
|
||||
/** The transaction handle drizzle passes to `db.transaction(cb)`. */
|
||||
export type DbTransaction = Parameters<Parameters<Db['transaction']>[0]>[0];
|
||||
|
||||
/** A query executor that is either the root db or an open transaction. */
|
||||
export type DbExecutor = Db | DbTransaction;
|
||||
20
packages/team-server/src/db/migrate.ts
Normal file
20
packages/team-server/src/db/migrate.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { migrate } from 'drizzle-orm/postgres-js/migrator';
|
||||
import { createDb } from './connection.js';
|
||||
import { createLogger } from '../logger.js';
|
||||
|
||||
const log = createLogger('migrate');
|
||||
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
if (!connectionString) throw new Error('DATABASE_URL environment variable is required');
|
||||
|
||||
async function main() {
|
||||
const db = createDb(connectionString!);
|
||||
await migrate(db, { migrationsFolder: './drizzle' });
|
||||
log.info('Migrations complete');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
log.error('Migration failed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
234
packages/team-server/src/db/schema.ts
Normal file
234
packages/team-server/src/db/schema.ts
Normal file
@@ -0,0 +1,234 @@
|
||||
import {
|
||||
pgTable, uuid, text, timestamp, boolean, real, integer, jsonb, primaryKey,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
|
||||
export const users = pgTable('users', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
clerkId: text('clerk_id').unique().notNull(),
|
||||
displayName: text('display_name').notNull(),
|
||||
email: text('email').unique().notNull(),
|
||||
avatarUrl: text('avatar_url'),
|
||||
mindPath: text('mind_path'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teams = pgTable('teams', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
name: text('name').notNull(),
|
||||
slug: text('slug').unique().notNull(),
|
||||
ownerId: uuid('owner_id').references(() => users.id).notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamMembers = pgTable('team_members', {
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
role: text('role').notNull().default('member'),
|
||||
roleDescription: text('role_description'),
|
||||
interests: jsonb('interests').$type<string[]>(),
|
||||
joinedAt: timestamp('joined_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
}, (t) => [primaryKey({ columns: [t.teamId, t.userId] })]);
|
||||
|
||||
export const agents = pgTable('agents', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
teamId: uuid('team_id').references(() => teams.id),
|
||||
name: text('name').notNull(),
|
||||
role: text('role'),
|
||||
systemPrompt: text('system_prompt'),
|
||||
model: text('model').notNull().default('claude-haiku-4-5'),
|
||||
tools: jsonb('tools').$type<string[]>().notNull().default([]),
|
||||
config: jsonb('config').$type<Record<string, unknown>>().notNull().default({}),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const agentGroups = pgTable('agent_groups', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
name: text('name').notNull(),
|
||||
description: text('description'),
|
||||
strategy: text('strategy').notNull().default('parallel'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const agentGroupMembers = pgTable('agent_group_members', {
|
||||
groupId: uuid('group_id').references(() => agentGroups.id).notNull(),
|
||||
agentId: uuid('agent_id').references(() => agents.id).notNull(),
|
||||
roleInGroup: text('role_in_group').notNull().default('worker'),
|
||||
executionOrder: integer('execution_order').notNull().default(0),
|
||||
}, (t) => [primaryKey({ columns: [t.groupId, t.agentId] })]);
|
||||
|
||||
export const tasks = pgTable('tasks', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
title: text('title').notNull(),
|
||||
description: text('description'),
|
||||
status: text('status').notNull().default('open'),
|
||||
priority: text('priority').notNull().default('normal'),
|
||||
createdBy: uuid('created_by').references(() => users.id).notNull(),
|
||||
assignedTo: uuid('assigned_to').references(() => users.id),
|
||||
parentTaskId: uuid('parent_task_id'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const messages = pgTable('messages', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
senderId: uuid('sender_id').references(() => users.id).notNull(),
|
||||
type: text('type').notNull(),
|
||||
subtype: text('subtype').notNull(),
|
||||
content: jsonb('content').$type<Record<string, unknown>>().notNull(),
|
||||
referenceId: uuid('reference_id'),
|
||||
routing: jsonb('routing').$type<Array<{ userId: string; reason: string }>>(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamEntities = pgTable('team_entities', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
entityType: text('entity_type').notNull(),
|
||||
name: text('name').notNull(),
|
||||
properties: jsonb('properties').$type<Record<string, unknown>>().notNull().default({}),
|
||||
sharedBy: uuid('shared_by').references(() => users.id).notNull(),
|
||||
validFrom: timestamp('valid_from', { withTimezone: true }).defaultNow().notNull(),
|
||||
validTo: timestamp('valid_to', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamRelations = pgTable('team_relations', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
sourceId: uuid('source_id').references(() => teamEntities.id).notNull(),
|
||||
targetId: uuid('target_id').references(() => teamEntities.id).notNull(),
|
||||
relationType: text('relation_type').notNull(),
|
||||
confidence: real('confidence').notNull().default(1.0),
|
||||
properties: jsonb('properties').$type<Record<string, unknown>>().notNull().default({}),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamResources = pgTable('team_resources', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
resourceType: text('resource_type').notNull(),
|
||||
name: text('name').notNull(),
|
||||
description: text('description'),
|
||||
config: jsonb('config').$type<Record<string, unknown>>().notNull(),
|
||||
sharedBy: uuid('shared_by').references(() => users.id).notNull(),
|
||||
rating: real('rating').notNull().default(0),
|
||||
useCount: integer('use_count').notNull().default(0),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamCapabilityPolicies = pgTable('team_capability_policies', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
role: text('role').notNull(),
|
||||
allowedSources: jsonb('allowed_sources').$type<string[]>().notNull().default([]),
|
||||
blockedTools: jsonb('blocked_tools').$type<string[]>().notNull().default([]),
|
||||
approvalThreshold: text('approval_threshold').notNull().default('none'),
|
||||
updatedBy: uuid('updated_by').references(() => users.id),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamCapabilityOverrides = pgTable('team_capability_overrides', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
capabilityName: text('capability_name').notNull(),
|
||||
capabilityType: text('capability_type').notNull(),
|
||||
decision: text('decision').notNull(),
|
||||
reason: text('reason').notNull().default(''),
|
||||
decidedBy: uuid('decided_by').references(() => users.id).notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
decidedAt: timestamp('decided_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamCapabilityRequests = pgTable('team_capability_requests', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
requestedBy: uuid('requested_by').references(() => users.id).notNull(),
|
||||
capabilityName: text('capability_name').notNull(),
|
||||
capabilityType: text('capability_type').notNull(),
|
||||
justification: text('justification').notNull(),
|
||||
status: text('status').notNull().default('pending'),
|
||||
decidedBy: uuid('decided_by').references(() => users.id),
|
||||
decisionReason: text('decision_reason'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
decidedAt: timestamp('decided_at', { withTimezone: true }),
|
||||
});
|
||||
|
||||
export const agentJobs = pgTable('agent_jobs', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
jobType: text('job_type').notNull(),
|
||||
status: text('status').notNull().default('queued'),
|
||||
input: jsonb('input').$type<Record<string, unknown>>().notNull(),
|
||||
output: jsonb('output').$type<Record<string, unknown>>(),
|
||||
startedAt: timestamp('started_at', { withTimezone: true }),
|
||||
completedAt: timestamp('completed_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const cronSchedules = pgTable('cron_schedules', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
createdBy: uuid('created_by').references(() => users.id).notNull(),
|
||||
name: text('name').notNull(),
|
||||
cronExpr: text('cron_expr').notNull(),
|
||||
jobType: text('job_type').notNull(),
|
||||
jobConfig: jsonb('job_config').$type<Record<string, unknown>>().notNull().default({}),
|
||||
enabled: boolean('enabled').notNull().default(true),
|
||||
lastRunAt: timestamp('last_run_at', { withTimezone: true }),
|
||||
nextRunAt: timestamp('next_run_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const scoutFindings = pgTable('scout_findings', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id),
|
||||
teamId: uuid('team_id').references(() => teams.id),
|
||||
source: text('source').notNull(),
|
||||
category: text('category').notNull(),
|
||||
title: text('title').notNull(),
|
||||
summary: text('summary'),
|
||||
relevanceScore: real('relevance_score').notNull().default(0),
|
||||
url: text('url'),
|
||||
status: text('status').notNull().default('new'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const proactivePatterns = pgTable('proactive_patterns', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
name: text('name').notNull(),
|
||||
trigger: jsonb('trigger').$type<Record<string, unknown>>().notNull(),
|
||||
suggestionType: text('suggestion_type').notNull(),
|
||||
template: text('template').notNull(),
|
||||
enabled: boolean('enabled').notNull().default(true),
|
||||
});
|
||||
|
||||
export const suggestionsLog = pgTable('suggestions_log', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
patternId: uuid('pattern_id').references(() => proactivePatterns.id).notNull(),
|
||||
context: jsonb('context').$type<Record<string, unknown>>().notNull(),
|
||||
status: text('status').notNull().default('pending'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const agentAuditLog = pgTable('agent_audit_log', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
teamId: uuid('team_id').references(() => teams.id),
|
||||
agentName: text('agent_name').notNull(),
|
||||
actionType: text('action_type').notNull(),
|
||||
description: text('description').notNull(),
|
||||
beforeState: jsonb('before_state').$type<Record<string, unknown>>(),
|
||||
afterState: jsonb('after_state').$type<Record<string, unknown>>(),
|
||||
requiresApproval: boolean('requires_approval').notNull().default(false),
|
||||
approved: boolean('approved'),
|
||||
approvedBy: uuid('approved_by').references(() => users.id),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
98
packages/team-server/src/index.ts
Normal file
98
packages/team-server/src/index.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import Fastify from 'fastify';
|
||||
import { resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import cors from '@fastify/cors';
|
||||
import websocket from '@fastify/websocket';
|
||||
import { loadConfig, type ServerConfig } from './config.js';
|
||||
import { createDb, type Db } from './db/connection.js';
|
||||
import redisPlugin from './plugins/redis.js';
|
||||
import authPlugin from './plugins/auth.js';
|
||||
import { webhookRoutes } from './routes/webhooks.js';
|
||||
import { teamRoutes } from './routes/teams.js';
|
||||
import { agentRoutes } from './routes/agents.js';
|
||||
import { taskRoutes } from './routes/tasks.js';
|
||||
import { messageRoutes } from './routes/messages.js';
|
||||
import { knowledgeRoutes } from './routes/knowledge.js';
|
||||
import { resourceRoutes } from './routes/resources.js';
|
||||
import { jobRoutes } from './routes/jobs.js';
|
||||
import { cronRoutes } from './routes/cron.js';
|
||||
import { suggestionRoutes } from './routes/suggestions.js';
|
||||
import { scoutRoutes } from './routes/scout.js';
|
||||
import { auditRoutes } from './routes/audit.js';
|
||||
import { capabilityGovernanceRoutes } from './routes/capability-governance.js';
|
||||
import { analyticsRoutes } from './routes/analytics.js';
|
||||
import { wsGateway } from './ws/gateway.js';
|
||||
import { JobService } from './services/job-service.js';
|
||||
import { CronRunner } from './scheduler/cron-runner.js';
|
||||
import { createLogger } from './logger.js';
|
||||
|
||||
const log = createLogger('server');
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
config: ServerConfig;
|
||||
db: Db;
|
||||
jobService: JobService;
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildServer(configOverrides?: Partial<ServerConfig>) {
|
||||
const config = { ...loadConfig(), ...configOverrides };
|
||||
|
||||
const server = Fastify({ logger: true });
|
||||
|
||||
server.decorate('config', config);
|
||||
|
||||
const db = createDb(config.databaseUrl);
|
||||
server.decorate('db', db);
|
||||
|
||||
await server.register(cors, { origin: config.corsOrigin });
|
||||
await server.register(websocket);
|
||||
await server.register(redisPlugin);
|
||||
await server.register(authPlugin);
|
||||
await server.register(webhookRoutes);
|
||||
await server.register(teamRoutes);
|
||||
await server.register(agentRoutes);
|
||||
await server.register(taskRoutes);
|
||||
await server.register(messageRoutes);
|
||||
await server.register(knowledgeRoutes);
|
||||
// Job service (must be decorated before job routes)
|
||||
const jobService = new JobService(db, config.redisUrl);
|
||||
server.decorate('jobService', jobService);
|
||||
const cronRunner = new CronRunner(db, jobService, error => {
|
||||
server.log.error({ err: error }, 'Cron scheduler tick failed');
|
||||
});
|
||||
server.addHook('onReady', async () => {
|
||||
cronRunner.start();
|
||||
});
|
||||
server.addHook('onClose', async () => {
|
||||
await cronRunner.stop();
|
||||
await jobService.close();
|
||||
});
|
||||
|
||||
await server.register(resourceRoutes);
|
||||
await server.register(jobRoutes);
|
||||
await server.register(cronRoutes);
|
||||
await server.register(suggestionRoutes);
|
||||
await server.register(scoutRoutes);
|
||||
await server.register(auditRoutes);
|
||||
await server.register(capabilityGovernanceRoutes);
|
||||
await server.register(analyticsRoutes);
|
||||
await server.register(wsGateway);
|
||||
|
||||
// Health check
|
||||
server.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }));
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
// Start server if run directly
|
||||
export function isDirectModule(entryPath: string | undefined, moduleUrl: string): boolean {
|
||||
return entryPath !== undefined && pathToFileURL(resolve(entryPath)).href === moduleUrl;
|
||||
}
|
||||
|
||||
if (isDirectModule(process.argv[1], import.meta.url)) {
|
||||
const server = await buildServer();
|
||||
await server.listen({ port: server.config.port, host: server.config.host });
|
||||
log.info(`Waggle server listening on ${server.config.host}:${server.config.port}`);
|
||||
}
|
||||
47
packages/team-server/src/logger.ts
Normal file
47
packages/team-server/src/logger.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Structured logger for the Waggle team server, a copy of the local
|
||||
* sidecar's logger (packages/server/src/local/logger.ts) so this package
|
||||
* does not depend on @waggle/server.
|
||||
*
|
||||
* Replaces raw console.log/warn/error with tagged, leveled output.
|
||||
* All messages are prefixed with [waggle] and a component tag.
|
||||
* In M2 this writes to stdout; can be extended to file/telemetry later.
|
||||
*/
|
||||
|
||||
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
||||
|
||||
const LEVEL_PREFIX: Record<LogLevel, string> = {
|
||||
debug: '\x1b[90m[debug]\x1b[0m',
|
||||
info: '',
|
||||
warn: '\x1b[33m[warn]\x1b[0m',
|
||||
error: '\x1b[31m[error]\x1b[0m',
|
||||
};
|
||||
|
||||
function formatMessage(tag: string, level: LogLevel, msg: string, data?: unknown): string {
|
||||
const prefix = LEVEL_PREFIX[level];
|
||||
const base = `[waggle:${tag}] ${prefix ? prefix + ' ' : ''}${msg}`;
|
||||
if (data !== undefined) {
|
||||
const detail = typeof data === 'string' ? data : JSON.stringify(data);
|
||||
return `${base} ${detail}`;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
debug(msg: string, data?: unknown): void;
|
||||
info(msg: string, data?: unknown): void;
|
||||
warn(msg: string, data?: unknown): void;
|
||||
error(msg: string, data?: unknown): void;
|
||||
}
|
||||
|
||||
export function createLogger(tag: string): Logger {
|
||||
return {
|
||||
debug(msg, data) { console.debug(formatMessage(tag, 'debug', msg, data)); },
|
||||
info(msg, data) { console.log(formatMessage(tag, 'info', msg, data)); },
|
||||
warn(msg, data) { console.warn(formatMessage(tag, 'warn', msg, data)); },
|
||||
error(msg, data) { console.error(formatMessage(tag, 'error', msg, data)); },
|
||||
};
|
||||
}
|
||||
|
||||
/** Default server logger */
|
||||
export const log = createLogger('server');
|
||||
61
packages/team-server/src/plugins/auth.ts
Normal file
61
packages/team-server/src/plugins/auth.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import fp from 'fastify-plugin';
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { createClerkClient, verifyToken } from '@clerk/fastify';
|
||||
import { UserService } from '../services/user-service.js';
|
||||
|
||||
export type AuthenticateFn = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
userId: string; // our internal user UUID
|
||||
clerkId: string;
|
||||
}
|
||||
interface FastifyInstance {
|
||||
authenticate: AuthenticateFn;
|
||||
_authHandler: { fn: AuthenticateFn };
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(async function authPlugin(fastify: FastifyInstance) {
|
||||
const clerkSecretKey = fastify.config.clerkSecretKey;
|
||||
const clerk = createClerkClient({ secretKey: clerkSecretKey });
|
||||
const userService = new UserService(fastify.db);
|
||||
|
||||
const clerkAuth: AuthenticateFn = async function (request, reply) {
|
||||
const token = request.headers.authorization?.replace('Bearer ', '');
|
||||
if (!token) {
|
||||
return reply.code(401).send({ error: 'Missing authorization token' });
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await verifyToken(token, { secretKey: clerkSecretKey });
|
||||
request.clerkId = payload.sub;
|
||||
|
||||
// Look up internal user, auto-provision if not found
|
||||
let user = await userService.getByClerkId(payload.sub);
|
||||
|
||||
if (!user) {
|
||||
// Auto-create user from Clerk JWT claims (self-healing: works even if webhook was missed)
|
||||
const clerkUser = await clerk.users.getUser(payload.sub);
|
||||
user = await userService.upsertFromClerk({
|
||||
clerkId: payload.sub,
|
||||
displayName: `${clerkUser.firstName ?? ''} ${clerkUser.lastName ?? ''}`.trim() || payload.sub,
|
||||
email: clerkUser.emailAddresses?.[0]?.emailAddress ?? '',
|
||||
avatarUrl: clerkUser.imageUrl ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
request.userId = user.id;
|
||||
} catch {
|
||||
return reply.code(401).send({ error: 'Invalid token' });
|
||||
}
|
||||
};
|
||||
|
||||
// Use an indirection object so tests can swap the auth handler after routes are registered
|
||||
const handler = { fn: clerkAuth };
|
||||
fastify.decorate('_authHandler', handler);
|
||||
|
||||
fastify.decorate('authenticate', async function (request: FastifyRequest, reply: FastifyReply) {
|
||||
return handler.fn(request, reply);
|
||||
});
|
||||
});
|
||||
24
packages/team-server/src/plugins/redis.ts
Normal file
24
packages/team-server/src/plugins/redis.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import fp from 'fastify-plugin';
|
||||
import Redis from 'ioredis';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
redis: Redis;
|
||||
redisSub: Redis;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(async function redisPlugin(fastify: FastifyInstance) {
|
||||
const redisUrl = fastify.config.redisUrl;
|
||||
const redis = new Redis(redisUrl);
|
||||
const redisSub = new Redis(redisUrl);
|
||||
|
||||
fastify.decorate('redis', redis);
|
||||
fastify.decorate('redisSub', redisSub);
|
||||
|
||||
fastify.addHook('onClose', async () => {
|
||||
await redis.quit();
|
||||
await redisSub.quit();
|
||||
});
|
||||
});
|
||||
39
packages/team-server/src/proactive/patterns.ts
Normal file
39
packages/team-server/src/proactive/patterns.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
export interface PatternDef {
|
||||
name: string;
|
||||
triggerCondition: string;
|
||||
suggestionType: string;
|
||||
template: string;
|
||||
}
|
||||
|
||||
export const BUILT_IN_PATTERNS: PatternDef[] = [
|
||||
{
|
||||
name: 'recurring_task',
|
||||
triggerCondition: 'Same task type executed 3+ times',
|
||||
suggestionType: 'cron',
|
||||
template: 'This task runs frequently. Would you like to automate it as a scheduled job?',
|
||||
},
|
||||
{
|
||||
name: 'data_report',
|
||||
triggerCondition: 'Job output contains structured data/metrics',
|
||||
suggestionType: 'dashboard',
|
||||
template: 'This produces data regularly. Want to create a dashboard for it?',
|
||||
},
|
||||
{
|
||||
name: 'relevant_to_others',
|
||||
triggerCondition: 'Job output matches other team member interests',
|
||||
suggestionType: 'share',
|
||||
template: 'This result might be relevant to {targetUser}. Share it?',
|
||||
},
|
||||
{
|
||||
name: 'expensive_model',
|
||||
triggerCondition: 'Job used expensive model for simple task',
|
||||
suggestionType: 'upgrade',
|
||||
template: 'This task could use a cheaper model. Try {cheaperModel} next time?',
|
||||
},
|
||||
{
|
||||
name: 'manual_repetition',
|
||||
triggerCondition: 'User performs same manual steps repeatedly',
|
||||
suggestionType: 'skill',
|
||||
template: 'You keep doing this manually. Want to create a reusable skill for it?',
|
||||
},
|
||||
];
|
||||
182
packages/team-server/src/routes/agents.ts
Normal file
182
packages/team-server/src/routes/agents.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { AgentGroupMemberNotFoundError, AgentService } from '../services/agent-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createAgentSchema, createAgentGroupSchema } from '@waggle/shared';
|
||||
|
||||
export async function agentRoutes(fastify: FastifyInstance) {
|
||||
const agentService = new AgentService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
// POST /api/agents — create sub-agent definition
|
||||
fastify.post('/api/agents', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const parsed = createAgentSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const agent = await agentService.create(request.userId, parsed.data);
|
||||
return reply.code(201).send(agent);
|
||||
});
|
||||
|
||||
// GET /api/agents — list user's agents
|
||||
fastify.get('/api/agents', { preHandler: [fastify.authenticate] }, async (request) => {
|
||||
return agentService.list(request.userId);
|
||||
});
|
||||
|
||||
// PATCH /api/agents/:id — update agent config
|
||||
fastify.patch('/api/agents/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
// Verify ownership by attempting update scoped to userId
|
||||
const existing = await agentService.getById(id);
|
||||
if (!existing) {
|
||||
return reply.code(404).send({ error: 'Agent not found' });
|
||||
}
|
||||
if (existing.userId !== request.userId) {
|
||||
return reply.code(403).send({ error: 'Not authorized to update this agent' });
|
||||
}
|
||||
|
||||
const body = request.body as Record<string, unknown>;
|
||||
const updated = await agentService.update(id, request.userId, body);
|
||||
if (!updated) {
|
||||
return reply.code(400).send({ error: 'No valid fields to update' });
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
|
||||
// DELETE /api/agents/:id — delete agent
|
||||
fastify.delete('/api/agents/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
const existing = await agentService.getById(id);
|
||||
if (!existing) {
|
||||
return reply.code(404).send({ error: 'Agent not found' });
|
||||
}
|
||||
if (existing.userId !== request.userId) {
|
||||
return reply.code(403).send({ error: 'Not authorized to delete this agent' });
|
||||
}
|
||||
|
||||
await agentService.delete(id, request.userId);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// POST /api/agent-groups — create agent group with members
|
||||
fastify.post('/api/agent-groups', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const parsed = createAgentGroupSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
try {
|
||||
const group = await agentService.createGroup(request.userId, parsed.data);
|
||||
return reply.code(201).send(group);
|
||||
} catch (error) {
|
||||
if (error instanceof AgentGroupMemberNotFoundError) {
|
||||
return reply.code(404).send({ error: 'Agent not found' });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/agent-groups — list user's groups
|
||||
fastify.get('/api/agent-groups', { preHandler: [fastify.authenticate] }, async (request) => {
|
||||
return agentService.listGroups(request.userId);
|
||||
});
|
||||
|
||||
// GET /api/agent-groups/:id — get group with members
|
||||
fastify.get('/api/agent-groups/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
const group = await agentService.getGroup(id, request.userId);
|
||||
if (!group) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
return group;
|
||||
});
|
||||
|
||||
// PATCH /api/agent-groups/:id — update group name, description, strategy, or members
|
||||
fastify.patch('/api/agent-groups/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
description?: string;
|
||||
strategy?: string;
|
||||
members?: Array<{ agentId: string; roleInGroup?: string; executionOrder?: number }>;
|
||||
};
|
||||
|
||||
try {
|
||||
const updated = await agentService.updateGroup(id, request.userId, body);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AgentGroupMemberNotFoundError) {
|
||||
return reply.code(404).send({ error: 'Agent not found' });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/agent-groups/:id — delete group and its members
|
||||
fastify.delete('/api/agent-groups/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
const deleted = await agentService.deleteGroup(id, request.userId);
|
||||
if (!deleted) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// POST /api/agent-groups/:id/run — execute group on a task
|
||||
fastify.post('/api/agent-groups/:id/run', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
// Verify group ownership
|
||||
const group = await agentService.getGroup(id, request.userId);
|
||||
if (!group) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
|
||||
const body = request.body as { task?: string; teamId?: string } | undefined;
|
||||
const task = body?.task ?? '';
|
||||
if (!task.trim()) {
|
||||
return reply.code(400).send({ error: 'task is required' });
|
||||
}
|
||||
if (!body?.teamId) {
|
||||
return reply.code(400).send({ error: 'teamId is required to queue a group run' });
|
||||
}
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(body.teamId)) {
|
||||
return reply.code(400).send({ error: 'teamId must be a valid UUID' });
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(body.teamId, request.userId);
|
||||
if (!membership) {
|
||||
return reply.code(404).send({ error: 'Team not found' });
|
||||
}
|
||||
|
||||
// Build workflow template from group definition
|
||||
const { buildWorkflowFromGroup } = await import('../services/agent-group-executor.js');
|
||||
const workflow = buildWorkflowFromGroup({ ...group, description: group.description ?? undefined }, task);
|
||||
|
||||
// Queue the same job type handled by the worker. The former path only
|
||||
// inserted a database row with an unsupported job type, so runs stayed
|
||||
// queued forever and no worker ever executed the workflow.
|
||||
const job = await fastify.jobService.createJob(body.teamId, request.userId, 'group', {
|
||||
groupId: id,
|
||||
taskInput: { task },
|
||||
});
|
||||
|
||||
return reply.code(202).send({
|
||||
jobId: job.id,
|
||||
workflow: {
|
||||
name: workflow.name,
|
||||
steps: workflow.steps.length,
|
||||
strategy: group.strategy,
|
||||
aggregation: workflow.aggregation,
|
||||
},
|
||||
message: `Group "${group.name}" execution started with ${workflow.steps.length} agents using ${group.strategy} strategy.`,
|
||||
});
|
||||
});
|
||||
}
|
||||
44
packages/team-server/src/routes/analytics.ts
Normal file
44
packages/team-server/src/routes/analytics.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { AnalyticsService } from '../services/analytics-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = { member: 1, admin: 2, owner: 3 };
|
||||
|
||||
export async function analyticsRoutes(fastify: FastifyInstance) {
|
||||
const analyticsService = new AnalyticsService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function requireAdmin(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const userLevel = ROLE_HIERARCHY[membership.role] ?? 0;
|
||||
if (userLevel < ROLE_HIERARCHY['admin']) {
|
||||
reply.code(403).send({ error: 'Admin access required' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// GET /api/admin/teams/:slug/analytics — team usage analytics dashboard
|
||||
fastify.get('/api/admin/teams/:slug/analytics', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const analytics = await analyticsService.getAnalytics(team.id);
|
||||
return analytics;
|
||||
});
|
||||
}
|
||||
99
packages/team-server/src/routes/audit.ts
Normal file
99
packages/team-server/src/routes/audit.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { AuditService } from '../services/audit-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = { member: 1, admin: 2, owner: 3 };
|
||||
|
||||
export async function auditRoutes(fastify: FastifyInstance) {
|
||||
const auditService = new AuditService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function requireAdmin(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const userLevel = ROLE_HIERARCHY[membership.role] ?? 0;
|
||||
if (userLevel < ROLE_HIERARCHY['admin']) {
|
||||
reply.code(403).send({ error: 'Admin access required' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// GET /api/admin/teams/:slug/audit -- list audit entries
|
||||
fastify.get('/api/admin/teams/:slug/audit', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { actionType?: string; agentName?: string };
|
||||
const entries = await auditService.list(team.id, {
|
||||
actionType: query.actionType,
|
||||
agentName: query.agentName,
|
||||
});
|
||||
return entries;
|
||||
});
|
||||
|
||||
// GET /api/admin/teams/:slug/audit/pending -- list pending approvals
|
||||
fastify.get('/api/admin/teams/:slug/audit/pending', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
return auditService.getPendingApprovals(team.id);
|
||||
});
|
||||
|
||||
// POST /api/admin/teams/:slug/audit/:id/approve -- approve pending action
|
||||
fastify.post('/api/admin/teams/:slug/audit/:id/approve', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const entry = await auditService.getById(id);
|
||||
if (!entry) {
|
||||
return reply.code(404).send({ error: 'Audit entry not found' });
|
||||
}
|
||||
if (entry.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Audit entry not found' });
|
||||
}
|
||||
|
||||
const updated = await auditService.approve(id, request.userId);
|
||||
return updated;
|
||||
});
|
||||
|
||||
// POST /api/admin/teams/:slug/audit/:id/reject -- reject pending action
|
||||
fastify.post('/api/admin/teams/:slug/audit/:id/reject', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const entry = await auditService.getById(id);
|
||||
if (!entry) {
|
||||
return reply.code(404).send({ error: 'Audit entry not found' });
|
||||
}
|
||||
if (entry.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Audit entry not found' });
|
||||
}
|
||||
|
||||
const updated = await auditService.reject(id, request.userId);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
289
packages/team-server/src/routes/capability-governance.ts
Normal file
289
packages/team-server/src/routes/capability-governance.ts
Normal file
@@ -0,0 +1,289 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { TeamCapabilityGovernance } from '../services/team-capability-governance.js';
|
||||
import { MessageService } from '../services/message-service.js';
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = {
|
||||
member: 1,
|
||||
admin: 2,
|
||||
owner: 3,
|
||||
};
|
||||
|
||||
const VALID_ROLES = ['owner', 'admin', 'member'];
|
||||
const VALID_SOURCES = ['native', 'skill', 'plugin', 'mcp', 'subagent'];
|
||||
const VALID_THRESHOLDS = ['low', 'medium', 'high', 'none'];
|
||||
|
||||
export async function capabilityGovernanceRoutes(fastify: FastifyInstance) {
|
||||
const teamService = new TeamService(fastify.db);
|
||||
const governance = new TeamCapabilityGovernance(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return { team, membership };
|
||||
}
|
||||
|
||||
function requireAdmin(membership: { role: string }, reply: FastifyReply): boolean {
|
||||
const level = ROLE_HIERARCHY[membership.role] ?? 0;
|
||||
if (level < ROLE_HIERARCHY.admin) {
|
||||
reply.code(403).send({ error: 'Admin or owner role required' });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// --- Policies ---
|
||||
|
||||
// GET /api/teams/:slug/capability-policies — list all policies
|
||||
fastify.get('/api/teams/:slug/capability-policies', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
|
||||
const policies = await governance.listPolicies(ctx.team.id);
|
||||
return policies;
|
||||
});
|
||||
|
||||
// PUT /api/teams/:slug/capability-policies/:role — update policy
|
||||
fastify.put('/api/teams/:slug/capability-policies/:role', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, role } = request.params as { slug: string; role: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
if (!requireAdmin(ctx.membership, reply)) return;
|
||||
|
||||
if (!VALID_ROLES.includes(role)) {
|
||||
return reply.code(400).send({ error: `Invalid role. Must be one of: ${VALID_ROLES.join(', ')}` });
|
||||
}
|
||||
|
||||
const body = request.body as {
|
||||
allowedSources?: string[];
|
||||
blockedTools?: string[];
|
||||
approvalThreshold?: string;
|
||||
};
|
||||
|
||||
if (body.allowedSources) {
|
||||
for (const s of body.allowedSources) {
|
||||
if (!VALID_SOURCES.includes(s)) {
|
||||
return reply.code(400).send({ error: `Invalid source: ${s}. Must be one of: ${VALID_SOURCES.join(', ')}` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (body.approvalThreshold && !VALID_THRESHOLDS.includes(body.approvalThreshold)) {
|
||||
return reply.code(400).send({ error: `Invalid threshold. Must be one of: ${VALID_THRESHOLDS.join(', ')}` });
|
||||
}
|
||||
|
||||
const policy = await governance.upsertPolicy(ctx.team.id, role, body, request.userId);
|
||||
return policy;
|
||||
});
|
||||
|
||||
// --- Overrides ---
|
||||
|
||||
// GET /api/teams/:slug/capability-overrides — list all overrides
|
||||
fastify.get('/api/teams/:slug/capability-overrides', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
|
||||
const overrides = await governance.listOverrides(ctx.team.id);
|
||||
return overrides;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/capability-overrides — create override
|
||||
fastify.post('/api/teams/:slug/capability-overrides', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
if (!requireAdmin(ctx.membership, reply)) return;
|
||||
|
||||
const body = request.body as {
|
||||
capabilityName?: string;
|
||||
capabilityType?: string;
|
||||
decision?: string;
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
if (!body.capabilityName || !body.capabilityType || !body.decision) {
|
||||
return reply.code(400).send({ error: 'capabilityName, capabilityType, and decision are required' });
|
||||
}
|
||||
|
||||
if (body.decision !== 'approved' && body.decision !== 'blocked') {
|
||||
return reply.code(400).send({ error: 'decision must be approved or blocked' });
|
||||
}
|
||||
|
||||
try {
|
||||
const override = await governance.createOverride(
|
||||
ctx.team.id,
|
||||
{
|
||||
capabilityName: body.capabilityName,
|
||||
capabilityType: body.capabilityType,
|
||||
decision: body.decision as 'approved' | 'blocked',
|
||||
reason: body.reason,
|
||||
},
|
||||
request.userId,
|
||||
);
|
||||
return reply.code(201).send(override);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '';
|
||||
const code = (err && typeof err === 'object' && 'code' in err) ? (err as { code?: unknown }).code : undefined;
|
||||
if (message.includes('unique') || message.includes('UNIQUE') || code === '23505') {
|
||||
return reply.code(409).send({ error: 'Override already exists for this capability' });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/teams/:slug/capability-overrides/:id — delete override
|
||||
fastify.delete('/api/teams/:slug/capability-overrides/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
if (!requireAdmin(ctx.membership, reply)) return;
|
||||
|
||||
const deleted = await governance.deleteOverride(ctx.team.id, id);
|
||||
if (!deleted) {
|
||||
return reply.code(404).send({ error: 'Override not found' });
|
||||
}
|
||||
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// --- Requests ---
|
||||
|
||||
// POST /api/teams/:slug/capability-requests — submit request
|
||||
fastify.post('/api/teams/:slug/capability-requests', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
|
||||
const body = request.body as {
|
||||
capabilityName?: string;
|
||||
capabilityType?: string;
|
||||
justification?: string;
|
||||
};
|
||||
|
||||
if (!body.capabilityName || !body.capabilityType || !body.justification) {
|
||||
return reply.code(400).send({ error: 'capabilityName, capabilityType, and justification are required' });
|
||||
}
|
||||
|
||||
const result = await governance.submitRequest(ctx.team.id, request.userId, {
|
||||
capabilityName: body.capabilityName,
|
||||
capabilityType: body.capabilityType,
|
||||
justification: body.justification,
|
||||
});
|
||||
|
||||
if (result.duplicate) {
|
||||
return reply.code(409).send({ error: 'A pending request for this capability already exists' });
|
||||
}
|
||||
|
||||
return reply.code(201).send(result.request);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/capability-requests — list requests
|
||||
fastify.get('/api/teams/:slug/capability-requests', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
|
||||
const query = request.query as { status?: string };
|
||||
const allRequests = await governance.listRequests(ctx.team.id, query.status);
|
||||
|
||||
// Non-admin users only see their own requests
|
||||
const level = ROLE_HIERARCHY[ctx.membership.role] ?? 0;
|
||||
if (level < ROLE_HIERARCHY.admin) {
|
||||
return allRequests.filter((r) => r.requestedBy === request.userId);
|
||||
}
|
||||
|
||||
return allRequests;
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/capability-requests/:id — decide request
|
||||
fastify.patch('/api/teams/:slug/capability-requests/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
if (!requireAdmin(ctx.membership, reply)) return;
|
||||
|
||||
const body = request.body as { status?: string; reason?: string };
|
||||
|
||||
if (!body.status || (body.status !== 'approved' && body.status !== 'rejected')) {
|
||||
return reply.code(400).send({ error: 'status must be approved or rejected' });
|
||||
}
|
||||
|
||||
const capRequest = await governance.getRequest(ctx.team.id, id);
|
||||
if (!capRequest) {
|
||||
return reply.code(404).send({ error: 'Request not found' });
|
||||
}
|
||||
|
||||
if (capRequest.status !== 'pending') {
|
||||
return reply.code(400).send({ error: 'Request has already been decided' });
|
||||
}
|
||||
|
||||
const decided = await governance.decideRequest(
|
||||
ctx.team.id,
|
||||
id,
|
||||
request.userId,
|
||||
body.status as 'approved' | 'rejected',
|
||||
body.reason,
|
||||
);
|
||||
|
||||
// On approve: auto-create override
|
||||
if (body.status === 'approved') {
|
||||
try {
|
||||
await governance.createOverride(
|
||||
ctx.team.id,
|
||||
{
|
||||
capabilityName: capRequest.capabilityName,
|
||||
capabilityType: capRequest.capabilityType,
|
||||
decision: 'approved',
|
||||
reason: body.reason,
|
||||
},
|
||||
request.userId,
|
||||
);
|
||||
} catch (_err) {
|
||||
// Override may already exist — ignore conflict
|
||||
}
|
||||
}
|
||||
|
||||
// Send Waggle Dance notification (non-critical)
|
||||
try {
|
||||
const messageService = new MessageService(fastify.db);
|
||||
await messageService.send(ctx.team.id, request.userId, {
|
||||
type: 'response',
|
||||
subtype: 'capability_decision',
|
||||
content: { capabilityName: capRequest.capabilityName, decision: body.status, reason: body.reason ?? '' },
|
||||
routing: [{ userId: capRequest.requestedBy, reason: 'capability_request_decision' }],
|
||||
});
|
||||
} catch (_err) {
|
||||
// Non-critical — don't fail the request
|
||||
}
|
||||
|
||||
return decided;
|
||||
});
|
||||
}
|
||||
84
packages/team-server/src/routes/cron.ts
Normal file
84
packages/team-server/src/routes/cron.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { CronService } from '../services/cron-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createCronSchema } from '@waggle/shared';
|
||||
|
||||
export async function cronRoutes(fastify: FastifyInstance) {
|
||||
const cronService = new CronService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/cron — create a cron schedule
|
||||
fastify.post('/api/teams/:slug/cron', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createCronSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
try {
|
||||
const schedule = await cronService.create(team.id, request.userId, parsed.data);
|
||||
return reply.code(201).send(schedule);
|
||||
} catch (err: unknown) {
|
||||
return reply.code(400).send({ error: 'Invalid cron expression', message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/cron — list schedules for team
|
||||
fastify.get('/api/teams/:slug/cron', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const schedules = await cronService.list(team.id);
|
||||
return schedules;
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/cron/:id — update a cron schedule
|
||||
fastify.patch('/api/teams/:slug/cron/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
cronExpr?: string;
|
||||
enabled?: boolean;
|
||||
jobConfig?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
try {
|
||||
const updated = await cronService.update(team.id, id, body);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Schedule not found' });
|
||||
}
|
||||
return updated;
|
||||
} catch (err: unknown) {
|
||||
return reply.code(400).send({ error: 'Invalid cron expression', message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
});
|
||||
}
|
||||
101
packages/team-server/src/routes/jobs.ts
Normal file
101
packages/team-server/src/routes/jobs.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { queueJobSchema } from '@waggle/shared';
|
||||
import { AgentService } from '../services/agent-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
|
||||
export async function jobRoutes(fastify: FastifyInstance) {
|
||||
const agentService = new AgentService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
// GET /api/jobs?teamSlug=... - list jobs for a team
|
||||
fastify.get('/api/jobs', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { teamSlug, limit } = request.query as { teamSlug?: string; limit?: string };
|
||||
if (!teamSlug) {
|
||||
return reply.code(400).send({ error: 'teamSlug query parameter is required' });
|
||||
}
|
||||
|
||||
const team = await teamService.getBySlug(teamSlug);
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) return reply.code(403).send({ error: 'Not a member of this team' });
|
||||
|
||||
const jobs = await fastify.jobService.listByTeam(team.id, limit ? parseInt(limit, 10) : 50);
|
||||
return jobs;
|
||||
});
|
||||
|
||||
// POST /api/jobs - queue a new job
|
||||
fastify.post('/api/jobs', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const parsed = queueJobSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const teamId = parsed.data.teamId;
|
||||
if (!teamId) {
|
||||
return reply.code(400).send({ error: 'teamId is required' });
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(teamId, request.userId);
|
||||
if (!membership) {
|
||||
return reply.code(404).send({ error: 'Team not found' });
|
||||
}
|
||||
|
||||
if (parsed.data.jobType === 'group') {
|
||||
const groupId = parsed.data.input.groupId;
|
||||
if (typeof groupId !== 'string') {
|
||||
return reply.code(400).send({ error: 'groupId is required for group jobs' });
|
||||
}
|
||||
|
||||
const group = await agentService.getGroup(groupId, request.userId);
|
||||
if (!group) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
}
|
||||
|
||||
const job = await fastify.jobService.createJob(
|
||||
teamId,
|
||||
request.userId,
|
||||
parsed.data.jobType,
|
||||
parsed.data.input,
|
||||
);
|
||||
return reply.code(202).send({ jobId: job.id, status: job.status });
|
||||
});
|
||||
|
||||
// POST /api/jobs/:id/cancel - cancel a running or queued job
|
||||
fastify.post('/api/jobs/:id/cancel', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const job = await fastify.jobService.getJob(id);
|
||||
if (!job) return reply.code(404).send({ error: 'Job not found' });
|
||||
|
||||
const membership = await teamService.getMembership(job.teamId, request.userId);
|
||||
if (!membership) return reply.code(404).send({ error: 'Job not found' });
|
||||
|
||||
if (job.status !== 'queued' && job.status !== 'running') {
|
||||
return reply.code(409).send({ error: `Cannot cancel job with status "${job.status}"` });
|
||||
}
|
||||
|
||||
const updated = await fastify.jobService.cancelJob(id);
|
||||
return { cancelled: true, jobId: updated?.id ?? id };
|
||||
});
|
||||
|
||||
// GET /api/jobs/:id - get job status
|
||||
fastify.get('/api/jobs/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const job = await fastify.jobService.getJob(id);
|
||||
if (!job) return reply.code(404).send({ error: 'Job not found' });
|
||||
|
||||
const membership = await teamService.getMembership(job.teamId, request.userId);
|
||||
if (!membership) return reply.code(404).send({ error: 'Job not found' });
|
||||
|
||||
return job;
|
||||
});
|
||||
}
|
||||
108
packages/team-server/src/routes/knowledge.ts
Normal file
108
packages/team-server/src/routes/knowledge.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { KnowledgeService } from '../services/knowledge-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createEntitySchema, createRelationSchema } from '@waggle/shared';
|
||||
|
||||
export async function knowledgeRoutes(fastify: FastifyInstance) {
|
||||
const knowledgeService = new KnowledgeService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/entities — share entity to team graph
|
||||
fastify.post('/api/teams/:slug/entities', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createEntitySchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const entity = await knowledgeService.createEntity(team.id, request.userId, parsed.data);
|
||||
return reply.code(201).send(entity);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/entities — list/search entities
|
||||
fastify.get('/api/teams/:slug/entities', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { type?: string; search?: string };
|
||||
const filters: { entityType?: string; search?: string } = {};
|
||||
if (query.type) filters.entityType = query.type;
|
||||
if (query.search) filters.search = query.search;
|
||||
|
||||
const entities = await knowledgeService.listEntities(team.id, filters);
|
||||
return entities;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/relations — create relation
|
||||
fastify.post('/api/teams/:slug/relations', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createRelationSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const relation = await knowledgeService.createRelation(team.id, parsed.data);
|
||||
if (!relation) {
|
||||
return reply.code(404).send({ error: 'Entity not found' });
|
||||
}
|
||||
return reply.code(201).send(relation);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/graph — query graph traversal
|
||||
fastify.get('/api/teams/:slug/graph', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { startId?: string; depth?: string; relationTypes?: string };
|
||||
if (!query.startId) {
|
||||
return reply.code(400).send({ error: 'startId query parameter is required' });
|
||||
}
|
||||
|
||||
const depth = query.depth ? parseInt(query.depth, 10) : 2;
|
||||
if (isNaN(depth) || depth < 1 || depth > 10) {
|
||||
return reply.code(400).send({ error: 'depth must be between 1 and 10' });
|
||||
}
|
||||
|
||||
const relationTypes = query.relationTypes
|
||||
? query.relationTypes.split(',').map((s) => s.trim())
|
||||
: undefined;
|
||||
|
||||
const result = await knowledgeService.queryGraph(team.id, query.startId, depth, relationTypes);
|
||||
if (!result) {
|
||||
return reply.code(404).send({ error: 'Entity not found' });
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
96
packages/team-server/src/routes/messages.ts
Normal file
96
packages/team-server/src/routes/messages.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { MessageService } from '../services/message-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { sendMessageSchema } from '@waggle/shared';
|
||||
import { validateMessageTypeCombo } from '@waggle/waggle-dance';
|
||||
import type { MessageType, MessageSubtype } from '@waggle/shared';
|
||||
import { z } from 'zod';
|
||||
|
||||
const hiveCheckSchema = z.object({
|
||||
topic: z.string().min(1).max(500),
|
||||
scope: z.string().max(200).optional(),
|
||||
});
|
||||
|
||||
export async function messageRoutes(fastify: FastifyInstance) {
|
||||
const messageService = new MessageService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/messages — send Waggle Dance message
|
||||
fastify.post('/api/teams/:slug/messages', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = sendMessageSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
// Validate type-subtype combination using waggle-dance protocol
|
||||
if (!validateMessageTypeCombo(parsed.data.type as MessageType, parsed.data.subtype as MessageSubtype)) {
|
||||
return reply.code(400).send({
|
||||
error: `Invalid type-subtype combination: ${parsed.data.type}/${parsed.data.subtype}`,
|
||||
});
|
||||
}
|
||||
|
||||
const message = await messageService.send(
|
||||
team.id,
|
||||
request.userId,
|
||||
parsed.data,
|
||||
fastify.redis,
|
||||
);
|
||||
return reply.code(201).send(message);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/messages — list messages
|
||||
fastify.get('/api/teams/:slug/messages', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { type?: string; subtype?: string };
|
||||
const filters: { type?: string; subtype?: string } = {};
|
||||
if (query.type) filters.type = query.type;
|
||||
if (query.subtype) filters.subtype = query.subtype;
|
||||
|
||||
const messageList = await messageService.list(team.id, filters);
|
||||
return messageList;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/messages/hive-check — check the hive
|
||||
fastify.post('/api/teams/:slug/messages/hive-check', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = hiveCheckSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const result = await messageService.checkHive(team.id, parsed.data);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
78
packages/team-server/src/routes/resources.ts
Normal file
78
packages/team-server/src/routes/resources.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { ResourceService } from '../services/resource-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createResourceSchema } from '@waggle/shared';
|
||||
|
||||
export async function resourceRoutes(fastify: FastifyInstance) {
|
||||
const resourceService = new ResourceService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/resources — share a resource
|
||||
fastify.post('/api/teams/:slug/resources', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createResourceSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const resource = await resourceService.share(team.id, request.userId, parsed.data);
|
||||
return reply.code(201).send(resource);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/resources — list resources
|
||||
fastify.get('/api/teams/:slug/resources', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { type?: string };
|
||||
const resources = await resourceService.list(team.id, query.type);
|
||||
return resources;
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/resources/:id — rate a resource (also increments useCount)
|
||||
fastify.patch('/api/teams/:slug/resources/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const body = request.body as { rating?: number };
|
||||
if (body.rating === undefined || typeof body.rating !== 'number' || body.rating < 0 || body.rating > 5) {
|
||||
return reply.code(400).send({ error: 'rating must be a number between 0 and 5' });
|
||||
}
|
||||
|
||||
// Rate (uses running average) then increment use count
|
||||
const rated = await resourceService.rate(team.id, id, body.rating);
|
||||
if (!rated) {
|
||||
return reply.code(404).send({ error: 'Resource not found' });
|
||||
}
|
||||
|
||||
const updated = await resourceService.incrementUseCount(team.id, id);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
35
packages/team-server/src/routes/scout.ts
Normal file
35
packages/team-server/src/routes/scout.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { ScoutAgent } from '../daemons/scout.js';
|
||||
|
||||
export async function scoutRoutes(fastify: FastifyInstance) {
|
||||
const scout = new ScoutAgent(fastify.db);
|
||||
|
||||
// GET /api/scout/findings — list findings for the authenticated user
|
||||
fastify.get('/api/scout/findings', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request) => {
|
||||
return scout.listFindings(request.userId);
|
||||
});
|
||||
|
||||
// PATCH /api/scout/findings/:id — adopt or dismiss a finding
|
||||
fastify.patch('/api/scout/findings/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = request.body as { status?: string };
|
||||
|
||||
if (!body.status || !['adopted', 'dismissed'].includes(body.status)) {
|
||||
return reply.code(400).send({ error: 'status must be one of: adopted, dismissed' });
|
||||
}
|
||||
|
||||
const action = body.status === 'adopted'
|
||||
? scout.adopt(id, request.userId)
|
||||
: scout.dismiss(id, request.userId);
|
||||
const updated = await action;
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Finding not found' });
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
36
packages/team-server/src/routes/suggestions.ts
Normal file
36
packages/team-server/src/routes/suggestions.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { ProactiveService } from '../services/proactive-service.js';
|
||||
|
||||
export async function suggestionRoutes(fastify: FastifyInstance) {
|
||||
const proactiveService = new ProactiveService(fastify.db);
|
||||
|
||||
// GET /api/suggestions — list pending suggestions for the authenticated user
|
||||
fastify.get('/api/suggestions', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request) => {
|
||||
return proactiveService.listPending(request.userId);
|
||||
});
|
||||
|
||||
// PATCH /api/suggestions/:id — accept, dismiss, or snooze a suggestion
|
||||
fastify.patch('/api/suggestions/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = request.body as { status?: string };
|
||||
|
||||
if (!body.status || !['accepted', 'dismissed', 'snoozed'].includes(body.status)) {
|
||||
return reply.code(400).send({ error: 'status must be one of: accepted, dismissed, snoozed' });
|
||||
}
|
||||
|
||||
const updated = await proactiveService.updateStatus(
|
||||
id,
|
||||
request.userId,
|
||||
body.status as 'accepted' | 'dismissed' | 'snoozed',
|
||||
);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Suggestion not found' });
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
115
packages/team-server/src/routes/tasks.ts
Normal file
115
packages/team-server/src/routes/tasks.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { TaskService } from '../services/task-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createTaskSchema, updateTaskSchema } from '@waggle/shared';
|
||||
|
||||
export async function taskRoutes(fastify: FastifyInstance) {
|
||||
const taskService = new TaskService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/tasks — create task
|
||||
fastify.post('/api/teams/:slug/tasks', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createTaskSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const task = await taskService.create(team.id, request.userId, parsed.data);
|
||||
return reply.code(201).send(task);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/tasks — list tasks
|
||||
fastify.get('/api/teams/:slug/tasks', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { status?: string; assignee?: string; priority?: string };
|
||||
const filters: { status?: string; assignee?: string; priority?: string } = {};
|
||||
if (query.status) filters.status = query.status;
|
||||
if (query.assignee) filters.assignee = query.assignee;
|
||||
if (query.priority) filters.priority = query.priority;
|
||||
|
||||
const taskList = await taskService.list(team.id, filters);
|
||||
return taskList;
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/tasks/:id — get task details
|
||||
fastify.get('/api/teams/:slug/tasks/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const task = await taskService.get(id);
|
||||
if (!task || task.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Task not found' });
|
||||
}
|
||||
|
||||
return task;
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/tasks/:id — update task
|
||||
fastify.patch('/api/teams/:slug/tasks/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = updateTaskSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const existing = await taskService.get(id);
|
||||
if (!existing || existing.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Task not found' });
|
||||
}
|
||||
|
||||
const updated = await taskService.update(id, parsed.data);
|
||||
return updated;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/tasks/:id/claim — claim task
|
||||
fastify.post('/api/teams/:slug/tasks/:id/claim', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const existing = await taskService.get(id);
|
||||
if (!existing || existing.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Task not found' });
|
||||
}
|
||||
|
||||
const claimed = await taskService.claim(id, request.userId);
|
||||
return claimed;
|
||||
});
|
||||
}
|
||||
184
packages/team-server/src/routes/teams.ts
Normal file
184
packages/team-server/src/routes/teams.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { users } from '../db/schema.js';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { createTeamSchema, inviteMemberSchema, updateMemberSchema } from '@waggle/shared';
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = { member: 1, admin: 2, owner: 3 };
|
||||
|
||||
async function requireTeamRole(
|
||||
server: FastifyInstance,
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
slug: string,
|
||||
minRole: 'member' | 'admin' | 'owner',
|
||||
) {
|
||||
const teamService = new TeamService(server.db);
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const userLevel = ROLE_HIERARCHY[membership.role] ?? 0;
|
||||
const requiredLevel = ROLE_HIERARCHY[minRole] ?? 0;
|
||||
if (userLevel < requiredLevel) {
|
||||
reply.code(403).send({ error: 'Insufficient permissions' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return { team, membership };
|
||||
}
|
||||
|
||||
export async function teamRoutes(fastify: FastifyInstance) {
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
// POST /api/teams — create team
|
||||
fastify.post('/api/teams', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const parsed = createTeamSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
// Check slug uniqueness
|
||||
const existing = await teamService.getBySlug(parsed.data.slug);
|
||||
if (existing) {
|
||||
return reply.code(409).send({ error: 'Team slug already exists' });
|
||||
}
|
||||
|
||||
const team = await teamService.create(request.userId, parsed.data);
|
||||
return reply.code(201).send(team);
|
||||
});
|
||||
|
||||
// GET /api/teams — list user's teams
|
||||
fastify.get('/api/teams', { preHandler: [fastify.authenticate] }, async (request) => {
|
||||
return teamService.listForUser(request.userId);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug — get team details with members
|
||||
fastify.get('/api/teams/:slug', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'member');
|
||||
if (!result) return;
|
||||
|
||||
const members = await teamService.getMembers(result.team.id);
|
||||
return { ...result.team, members };
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug — update team (admin+)
|
||||
fastify.patch('/api/teams/:slug', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
|
||||
if (!result) return;
|
||||
|
||||
const body = request.body as { name?: string };
|
||||
if (!body.name || typeof body.name !== 'string' || body.name.length < 1 || body.name.length > 100) {
|
||||
return reply.code(400).send({ error: 'Invalid name' });
|
||||
}
|
||||
|
||||
const updated = await teamService.update(result.team.id, { name: body.name });
|
||||
return updated;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/members — invite member (admin+)
|
||||
fastify.post('/api/teams/:slug/members', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
|
||||
if (!result) return;
|
||||
|
||||
const parsed = inviteMemberSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
// Look up user by email
|
||||
const [targetUser] = await fastify.db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.email, parsed.data.email))
|
||||
.limit(1);
|
||||
|
||||
if (!targetUser) {
|
||||
return reply.code(404).send({ error: 'User not found with that email' });
|
||||
}
|
||||
|
||||
// Check if already a member
|
||||
const existingMembership = await teamService.getMembership(result.team.id, targetUser.id);
|
||||
if (existingMembership) {
|
||||
return reply.code(409).send({ error: 'User is already a member of this team' });
|
||||
}
|
||||
|
||||
const member = await teamService.addMember(result.team.id, targetUser.id, parsed.data.role);
|
||||
return reply.code(201).send(member);
|
||||
});
|
||||
|
||||
// DELETE /api/teams/:slug/members/:userId — remove member (admin+)
|
||||
fastify.delete('/api/teams/:slug/members/:userId', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug, userId } = request.params as { slug: string; userId: string };
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
|
||||
if (!result) return;
|
||||
|
||||
try {
|
||||
const removed = await teamService.removeMember(result.team.id, userId);
|
||||
if (!removed) {
|
||||
return reply.code(404).send({ error: 'Member not found' });
|
||||
}
|
||||
return reply.code(204).send();
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.message === 'Cannot remove the team owner') {
|
||||
return reply.code(403).send({ error: err.message });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/members/:userId — update member
|
||||
fastify.patch('/api/teams/:slug/members/:userId', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug, userId: targetUserId } = request.params as { slug: string; userId: string };
|
||||
|
||||
const parsed = updateMemberSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
// Determine required role: role changes need admin+, self-updates for roleDescription/interests are ok
|
||||
const isSelfUpdate = request.userId === targetUserId;
|
||||
const isRoleChange = parsed.data.role !== undefined;
|
||||
|
||||
if (isRoleChange || !isSelfUpdate) {
|
||||
// Need admin+ for role changes or updating other members
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
|
||||
if (!result) return;
|
||||
|
||||
try {
|
||||
const updated = await teamService.updateMember(result.team.id, targetUserId, parsed.data);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Member not found' });
|
||||
}
|
||||
return updated;
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.message === 'Cannot change the team owner role') {
|
||||
return reply.code(403).send({ error: err.message });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
} else {
|
||||
// Self-update: only roleDescription and interests (no role field)
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'member');
|
||||
if (!result) return;
|
||||
|
||||
const { role: _discard, ...safeData } = parsed.data;
|
||||
const updated = await teamService.updateMember(result.team.id, targetUserId, safeData);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Member not found' });
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
});
|
||||
}
|
||||
57
packages/team-server/src/routes/webhooks.ts
Normal file
57
packages/team-server/src/routes/webhooks.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { verifyWebhook } from '@clerk/fastify/webhooks';
|
||||
import { users } from '../db/schema.js';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
/** Subset of the Clerk user webhook payload `data` object that we consume. */
|
||||
interface ClerkWebhookUserData {
|
||||
id: string;
|
||||
first_name?: string | null;
|
||||
last_name?: string | null;
|
||||
email_addresses?: Array<{ email_address?: string }>;
|
||||
image_url?: string | null;
|
||||
}
|
||||
|
||||
export async function webhookRoutes(fastify: FastifyInstance) {
|
||||
fastify.post('/api/webhooks/clerk', async (request, reply) => {
|
||||
let event: { type: string; data: ClerkWebhookUserData };
|
||||
try {
|
||||
event = await verifyWebhook(request) as typeof event;
|
||||
} catch (error) {
|
||||
fastify.log.warn({ err: error }, 'Clerk webhook verification failed');
|
||||
return reply.code(400).send({ error: 'Invalid webhook signature' });
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'user.created': {
|
||||
const d = event.data;
|
||||
await fastify.db.insert(users).values({
|
||||
clerkId: d.id,
|
||||
displayName: `${d.first_name ?? ''} ${d.last_name ?? ''}`.trim() || d.id,
|
||||
email: d.email_addresses?.[0]?.email_address ?? '',
|
||||
avatarUrl: d.image_url ?? null,
|
||||
}).onConflictDoNothing();
|
||||
break;
|
||||
}
|
||||
case 'user.updated': {
|
||||
const d = event.data;
|
||||
await fastify.db.update(users)
|
||||
.set({
|
||||
displayName: `${d.first_name ?? ''} ${d.last_name ?? ''}`.trim(),
|
||||
email: d.email_addresses?.[0]?.email_address ?? '',
|
||||
avatarUrl: d.image_url ?? null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(users.clerkId, d.id));
|
||||
break;
|
||||
}
|
||||
case 'user.deleted': {
|
||||
const d = event.data;
|
||||
await fastify.db.delete(users).where(eq(users.clerkId, d.id));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return reply.code(200).send({ received: true });
|
||||
});
|
||||
}
|
||||
110
packages/team-server/src/scheduler/cron-runner.ts
Normal file
110
packages/team-server/src/scheduler/cron-runner.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { lte, eq, and } from 'drizzle-orm';
|
||||
import { createHash } from 'node:crypto';
|
||||
import cronParser from 'cron-parser';
|
||||
const { parseExpression } = cronParser;
|
||||
import { cronSchedules } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import type { JobService } from '../services/job-service.js';
|
||||
import { scheduledJobTypeSchema } from '@waggle/shared';
|
||||
|
||||
function occurrenceJobId(scheduleId: string, scheduledFor: Date): string {
|
||||
const bytes = createHash('sha256')
|
||||
.update(scheduleId)
|
||||
.update('\0')
|
||||
.update(scheduledFor.toISOString())
|
||||
.digest()
|
||||
.subarray(0, 16);
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x80;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = bytes.toString('hex');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
|
||||
export class CronRunner {
|
||||
private interval: ReturnType<typeof setInterval> | null = null;
|
||||
private tickInFlight: Promise<number> | null = null;
|
||||
|
||||
constructor(
|
||||
private db: Db,
|
||||
private jobService: JobService,
|
||||
private onError: (error: unknown) => void = () => undefined,
|
||||
) {}
|
||||
|
||||
start(intervalMs = 60_000) {
|
||||
if (this.interval) return;
|
||||
if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
|
||||
throw new Error('Cron interval must be a positive number');
|
||||
}
|
||||
|
||||
const runTick = () => {
|
||||
if (this.tickInFlight) return;
|
||||
const tick = this.tick()
|
||||
.catch(error => {
|
||||
this.onError(error);
|
||||
return 0;
|
||||
})
|
||||
.finally(() => {
|
||||
if (this.tickInFlight === tick) this.tickInFlight = null;
|
||||
});
|
||||
this.tickInFlight = tick;
|
||||
};
|
||||
|
||||
runTick();
|
||||
this.interval = setInterval(runTick, intervalMs);
|
||||
this.interval.unref?.();
|
||||
}
|
||||
|
||||
async stop() {
|
||||
if (this.interval) {
|
||||
clearInterval(this.interval);
|
||||
this.interval = null;
|
||||
}
|
||||
await this.tickInFlight;
|
||||
}
|
||||
|
||||
async tick() {
|
||||
const now = new Date();
|
||||
|
||||
// Find all enabled schedules that are due
|
||||
const due = await this.db.select().from(cronSchedules)
|
||||
.where(and(
|
||||
eq(cronSchedules.enabled, true),
|
||||
lte(cronSchedules.nextRunAt, now),
|
||||
));
|
||||
|
||||
let queuedCount = 0;
|
||||
for (const schedule of due) {
|
||||
const jobType = scheduledJobTypeSchema.safeParse(schedule.jobType);
|
||||
if (!jobType.success || !schedule.nextRunAt) continue;
|
||||
|
||||
try {
|
||||
// Validate legacy rows before queueing so a poison cron expression
|
||||
// cannot create a duplicate job on every scheduler pass.
|
||||
const nextRunAt = parseExpression(schedule.cronExpr).next().toDate();
|
||||
|
||||
await this.jobService.createJob(
|
||||
schedule.teamId,
|
||||
schedule.createdBy,
|
||||
jobType.data,
|
||||
schedule.jobConfig as Record<string, unknown>,
|
||||
occurrenceJobId(schedule.id, schedule.nextRunAt),
|
||||
);
|
||||
|
||||
const [advanced] = await this.db.update(cronSchedules)
|
||||
.set({ lastRunAt: now, nextRunAt })
|
||||
.where(and(
|
||||
eq(cronSchedules.id, schedule.id),
|
||||
eq(cronSchedules.nextRunAt, schedule.nextRunAt),
|
||||
))
|
||||
.returning({ id: cronSchedules.id });
|
||||
if (advanced) queuedCount++;
|
||||
} catch (error) {
|
||||
// One malformed or temporarily failing schedule must not starve the
|
||||
// remaining due work. The lifecycle runner supplies the server logger.
|
||||
this.onError(error);
|
||||
}
|
||||
}
|
||||
|
||||
return queuedCount;
|
||||
}
|
||||
}
|
||||
100
packages/team-server/src/services/agent-group-executor.ts
Normal file
100
packages/team-server/src/services/agent-group-executor.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Agent Group Executor — converts agent group definitions into
|
||||
* SubagentOrchestrator workflow templates and executes them.
|
||||
*
|
||||
* Strategies:
|
||||
* - sequential: Execute members in executionOrder, each waits for previous
|
||||
* - parallel: Execute all members simultaneously
|
||||
* - coordinator: First member coordinates, others are workers
|
||||
*
|
||||
* The local sidecar keeps its own copy in
|
||||
* packages/server/src/services/agent-group-executor.ts.
|
||||
*/
|
||||
|
||||
import type { WorkflowTemplate, WorkflowStep } from '@waggle/agent';
|
||||
|
||||
interface AgentGroupMember {
|
||||
agentId: string;
|
||||
roleInGroup: string;
|
||||
executionOrder: number;
|
||||
// Joined from agents table:
|
||||
name?: string;
|
||||
role?: string;
|
||||
systemPrompt?: string;
|
||||
model?: string;
|
||||
tools?: string[];
|
||||
}
|
||||
|
||||
interface AgentGroupData {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
strategy: string;
|
||||
members: AgentGroupMember[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an agent group with its members into a WorkflowTemplate
|
||||
* that the SubagentOrchestrator can execute.
|
||||
*/
|
||||
export function buildWorkflowFromGroup(group: AgentGroupData, task: string): WorkflowTemplate {
|
||||
const strategy = group.strategy || 'sequential';
|
||||
|
||||
const steps: WorkflowStep[] = [...group.members]
|
||||
.sort((a, b) => (a.executionOrder ?? 0) - (b.executionOrder ?? 0))
|
||||
.map((member, index, arr) => {
|
||||
const personaInstructions = member.systemPrompt?.trim()
|
||||
? `\n\n## Agent Instructions\n${member.systemPrompt.trim()}`
|
||||
: '';
|
||||
const step: WorkflowStep = {
|
||||
name: member.name ?? `agent-${member.agentId}`,
|
||||
role: member.roleInGroup ?? member.role ?? 'worker',
|
||||
task: `${task}${personaInstructions}`,
|
||||
tools: member.tools,
|
||||
maxTurns: 10,
|
||||
model: member.model,
|
||||
};
|
||||
|
||||
switch (strategy) {
|
||||
case 'sequential':
|
||||
// Each step depends on the previous one
|
||||
if (index > 0) {
|
||||
const prevName = arr[index - 1].name ?? `agent-${arr[index - 1].agentId}`;
|
||||
step.dependsOn = [prevName];
|
||||
step.contextFrom = [prevName];
|
||||
}
|
||||
break;
|
||||
|
||||
case 'parallel':
|
||||
// No dependencies — all run simultaneously
|
||||
break;
|
||||
|
||||
case 'coordinator':
|
||||
// First member is coordinator, others depend on coordinator's output
|
||||
if (index === 0) {
|
||||
step.role = 'coordinator';
|
||||
step.task = `You are the coordinator. Break down this task and delegate to your team:\n\n${step.task}`;
|
||||
} else {
|
||||
const coordinatorName = arr[0].name ?? `agent-${arr[0].agentId}`;
|
||||
step.dependsOn = [coordinatorName];
|
||||
step.contextFrom = [coordinatorName];
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return step;
|
||||
});
|
||||
|
||||
// Choose aggregation based on strategy
|
||||
const aggregation: WorkflowTemplate['aggregation'] =
|
||||
strategy === 'coordinator' ? 'synthesize' :
|
||||
strategy === 'parallel' ? 'concatenate' :
|
||||
'last';
|
||||
|
||||
return {
|
||||
name: group.name,
|
||||
description: group.description ?? `Agent group: ${group.name}`,
|
||||
steps,
|
||||
aggregation,
|
||||
};
|
||||
}
|
||||
241
packages/team-server/src/services/agent-service.ts
Normal file
241
packages/team-server/src/services/agent-service.ts
Normal file
@@ -0,0 +1,241 @@
|
||||
import { eq, and, inArray } from 'drizzle-orm';
|
||||
import { agents, agentGroups, agentGroupMembers, agentJobs } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class AgentGroupMemberNotFoundError extends Error {}
|
||||
|
||||
export class AgentService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
private async groupMembersOwned(userId: string, agentIds: string[]): Promise<boolean> {
|
||||
const uniqueAgentIds = [...new Set(agentIds)];
|
||||
if (uniqueAgentIds.length === 0) return true;
|
||||
|
||||
const ownedAgents = await this.db
|
||||
.select({ id: agents.id })
|
||||
.from(agents)
|
||||
.where(and(eq(agents.userId, userId), inArray(agents.id, uniqueAgentIds)));
|
||||
|
||||
return ownedAgents.length === uniqueAgentIds.length;
|
||||
}
|
||||
|
||||
private async assertGroupMembersOwned(userId: string, agentIds: string[]): Promise<void> {
|
||||
if (!(await this.groupMembersOwned(userId, agentIds))) {
|
||||
throw new AgentGroupMemberNotFoundError();
|
||||
}
|
||||
}
|
||||
|
||||
async create(userId: string, data: {
|
||||
name: string;
|
||||
role?: string;
|
||||
systemPrompt?: string;
|
||||
model?: string;
|
||||
tools?: string[];
|
||||
config?: Record<string, unknown>;
|
||||
teamId?: string;
|
||||
}) {
|
||||
const [agent] = await this.db.insert(agents).values({
|
||||
userId,
|
||||
name: data.name,
|
||||
role: data.role,
|
||||
systemPrompt: data.systemPrompt,
|
||||
model: data.model ?? 'claude-haiku-4-5',
|
||||
tools: data.tools ?? [],
|
||||
config: data.config ?? {},
|
||||
teamId: data.teamId,
|
||||
}).returning();
|
||||
return agent;
|
||||
}
|
||||
|
||||
async list(userId: string) {
|
||||
return this.db
|
||||
.select()
|
||||
.from(agents)
|
||||
.where(eq(agents.userId, userId));
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
const [agent] = await this.db
|
||||
.select()
|
||||
.from(agents)
|
||||
.where(eq(agents.id, id))
|
||||
.limit(1);
|
||||
return agent ?? null;
|
||||
}
|
||||
|
||||
async update(id: string, userId: string, data: {
|
||||
name?: string;
|
||||
role?: string;
|
||||
systemPrompt?: string;
|
||||
model?: string;
|
||||
tools?: string[];
|
||||
config?: Record<string, unknown>;
|
||||
}) {
|
||||
const setData: Record<string, unknown> = {};
|
||||
if (data.name !== undefined) setData.name = data.name;
|
||||
if (data.role !== undefined) setData.role = data.role;
|
||||
if (data.systemPrompt !== undefined) setData.systemPrompt = data.systemPrompt;
|
||||
if (data.model !== undefined) setData.model = data.model;
|
||||
if (data.tools !== undefined) setData.tools = data.tools;
|
||||
if (data.config !== undefined) setData.config = data.config;
|
||||
|
||||
if (Object.keys(setData).length === 0) return null;
|
||||
|
||||
const [updated] = await this.db
|
||||
.update(agents)
|
||||
.set(setData)
|
||||
.where(and(eq(agents.id, id), eq(agents.userId, userId)))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async delete(id: string, userId: string) {
|
||||
// First remove agent from any groups
|
||||
await this.db
|
||||
.delete(agentGroupMembers)
|
||||
.where(eq(agentGroupMembers.agentId, id));
|
||||
|
||||
const result = await this.db
|
||||
.delete(agents)
|
||||
.where(and(eq(agents.id, id), eq(agents.userId, userId)))
|
||||
.returning();
|
||||
return result.length > 0;
|
||||
}
|
||||
|
||||
async createGroup(userId: string, data: {
|
||||
name: string;
|
||||
description?: string;
|
||||
strategy: string;
|
||||
members: Array<{ agentId: string; roleInGroup?: string; executionOrder?: number }>;
|
||||
}) {
|
||||
await this.assertGroupMembersOwned(userId, data.members.map((member) => member.agentId));
|
||||
|
||||
return this.db.transaction(async (tx) => {
|
||||
const [group] = await tx.insert(agentGroups).values({
|
||||
userId,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
strategy: data.strategy,
|
||||
}).returning();
|
||||
|
||||
if (data.members.length > 0) {
|
||||
await tx.insert(agentGroupMembers).values(
|
||||
data.members.map((m) => ({
|
||||
groupId: group.id,
|
||||
agentId: m.agentId,
|
||||
roleInGroup: m.roleInGroup ?? 'worker',
|
||||
executionOrder: m.executionOrder ?? 0,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const members = await tx
|
||||
.select()
|
||||
.from(agentGroupMembers)
|
||||
.where(eq(agentGroupMembers.groupId, group.id));
|
||||
|
||||
return { ...group, members };
|
||||
});
|
||||
}
|
||||
|
||||
async listGroups(userId: string) {
|
||||
return this.db
|
||||
.select()
|
||||
.from(agentGroups)
|
||||
.where(eq(agentGroups.userId, userId));
|
||||
}
|
||||
|
||||
async getGroup(groupId: string, userId: string) {
|
||||
const [group] = await this.db
|
||||
.select()
|
||||
.from(agentGroups)
|
||||
.where(and(eq(agentGroups.id, groupId), eq(agentGroups.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (!group) return null;
|
||||
|
||||
const members = await this.db
|
||||
.select()
|
||||
.from(agentGroupMembers)
|
||||
.where(eq(agentGroupMembers.groupId, groupId));
|
||||
|
||||
if (!(await this.groupMembersOwned(userId, members.map((member) => member.agentId)))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { ...group, members };
|
||||
}
|
||||
|
||||
async updateGroup(groupId: string, userId: string, data: {
|
||||
name?: string;
|
||||
description?: string;
|
||||
strategy?: string;
|
||||
members?: Array<{ agentId: string; roleInGroup?: string; executionOrder?: number }>;
|
||||
}) {
|
||||
// Verify ownership
|
||||
const existing = await this.getGroup(groupId, userId);
|
||||
if (!existing) return null;
|
||||
if (data.members) {
|
||||
await this.assertGroupMembersOwned(userId, data.members.map((member) => member.agentId));
|
||||
}
|
||||
|
||||
return this.db.transaction(async (tx) => {
|
||||
// Update group fields if any provided
|
||||
const updates: Record<string, unknown> = {};
|
||||
if (data.name != null) updates.name = data.name;
|
||||
if (data.description != null) updates.description = data.description;
|
||||
if (data.strategy != null) updates.strategy = data.strategy;
|
||||
|
||||
if (Object.keys(updates).length > 0) {
|
||||
updates.updatedAt = new Date();
|
||||
await tx.update(agentGroups).set(updates).where(eq(agentGroups.id, groupId));
|
||||
}
|
||||
|
||||
// Replace members if provided
|
||||
if (data.members) {
|
||||
await tx.delete(agentGroupMembers).where(eq(agentGroupMembers.groupId, groupId));
|
||||
if (data.members.length > 0) {
|
||||
await tx.insert(agentGroupMembers).values(
|
||||
data.members.map(m => ({
|
||||
groupId,
|
||||
agentId: m.agentId,
|
||||
roleInGroup: m.roleInGroup ?? 'worker',
|
||||
executionOrder: m.executionOrder ?? 0,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Return updated group with members
|
||||
const [group] = await tx.select().from(agentGroups).where(eq(agentGroups.id, groupId));
|
||||
const members = await tx.select().from(agentGroupMembers).where(eq(agentGroupMembers.groupId, groupId));
|
||||
return { ...group, members };
|
||||
});
|
||||
}
|
||||
|
||||
async deleteGroup(groupId: string, userId: string): Promise<boolean> {
|
||||
const existing = await this.getGroup(groupId, userId);
|
||||
if (!existing) return false;
|
||||
|
||||
await this.db.transaction(async (tx) => {
|
||||
await tx.delete(agentGroupMembers).where(eq(agentGroupMembers.groupId, groupId));
|
||||
await tx.delete(agentGroups).where(eq(agentGroups.id, groupId));
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
async createJob(userId: string, data: {
|
||||
teamId: string;
|
||||
jobType: string;
|
||||
input: Record<string, unknown>;
|
||||
}) {
|
||||
const [job] = await this.db.insert(agentJobs).values({
|
||||
userId,
|
||||
teamId: data.teamId,
|
||||
jobType: data.jobType,
|
||||
status: 'queued',
|
||||
input: data.input,
|
||||
}).returning();
|
||||
return job;
|
||||
}
|
||||
}
|
||||
291
packages/team-server/src/services/analytics-service.ts
Normal file
291
packages/team-server/src/services/analytics-service.ts
Normal file
@@ -0,0 +1,291 @@
|
||||
import { eq, and, sql, count, desc, gte, lt } from 'drizzle-orm';
|
||||
import {
|
||||
teamMembers, users, tasks, agentAuditLog, agentJobs,
|
||||
teamCapabilityRequests, messages,
|
||||
} from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export interface AnalyticsResponse {
|
||||
activeUsers: { daily: number; weekly: number; monthly: number };
|
||||
tokenUsage: {
|
||||
total: number;
|
||||
byUser: Array<{ userId: string; name: string; tokens: number; cost: number }>;
|
||||
};
|
||||
topTools: Array<{ name: string; invocations: number }>;
|
||||
topCommands: Array<{ name: string; count: number }>;
|
||||
capabilityGaps: Array<{ tool: string; requestCount: number; suggestion: string }>;
|
||||
performanceTrends: {
|
||||
correctionRate: number;
|
||||
correctionTrend: number;
|
||||
avgResponseTime: number;
|
||||
};
|
||||
}
|
||||
|
||||
export class AnalyticsService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async getAnalytics(teamId: string): Promise<AnalyticsResponse> {
|
||||
const [activeUsers, tokenUsage, topTools, topCommands, capabilityGaps, performanceTrends] =
|
||||
await Promise.all([
|
||||
this.getActiveUsers(teamId),
|
||||
this.getTokenUsage(teamId),
|
||||
this.getTopTools(teamId),
|
||||
this.getTopCommands(teamId),
|
||||
this.getCapabilityGaps(teamId),
|
||||
this.getPerformanceTrends(teamId),
|
||||
]);
|
||||
|
||||
return {
|
||||
activeUsers,
|
||||
tokenUsage,
|
||||
topTools,
|
||||
topCommands,
|
||||
capabilityGaps,
|
||||
performanceTrends,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Count active users based on audit log activity within time windows.
|
||||
* Falls back to member count if no activity found.
|
||||
*/
|
||||
private async getActiveUsers(teamId: string) {
|
||||
const now = new Date();
|
||||
const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
const oneMonthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const [dailyResult] = await this.db
|
||||
.select({ count: sql<number>`count(distinct ${agentAuditLog.userId})` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneDayAgo),
|
||||
));
|
||||
|
||||
const [weeklyResult] = await this.db
|
||||
.select({ count: sql<number>`count(distinct ${agentAuditLog.userId})` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const [monthlyResult] = await this.db
|
||||
.select({ count: sql<number>`count(distinct ${agentAuditLog.userId})` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneMonthAgo),
|
||||
));
|
||||
|
||||
return {
|
||||
daily: Number(dailyResult?.count ?? 0),
|
||||
weekly: Number(weeklyResult?.count ?? 0),
|
||||
monthly: Number(monthlyResult?.count ?? 0),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute token usage from completed jobs.
|
||||
* Since we don't have a dedicated token tracking table, we estimate from
|
||||
* job outputs that may contain token counts, or fall back to job counts as proxy.
|
||||
*/
|
||||
private async getTokenUsage(teamId: string) {
|
||||
// Get all members for this team
|
||||
const members = await this.db
|
||||
.select({
|
||||
userId: teamMembers.userId,
|
||||
displayName: users.displayName,
|
||||
})
|
||||
.from(teamMembers)
|
||||
.innerJoin(users, eq(teamMembers.userId, users.id))
|
||||
.where(eq(teamMembers.teamId, teamId));
|
||||
|
||||
// Count completed jobs per user as a proxy for usage
|
||||
const jobCounts = await this.db
|
||||
.select({
|
||||
userId: agentJobs.userId,
|
||||
jobCount: sql<number>`count(*)`,
|
||||
})
|
||||
.from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.teamId, teamId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
))
|
||||
.groupBy(agentJobs.userId);
|
||||
|
||||
const jobCountMap = new Map(jobCounts.map((j) => [j.userId, Number(j.jobCount)]));
|
||||
|
||||
// Estimate tokens: ~1000 tokens per completed job (rough proxy)
|
||||
const TOKENS_PER_JOB = 1000;
|
||||
const COST_PER_1K_TOKENS = 0.005;
|
||||
|
||||
const byUser = members.map((m) => {
|
||||
const jobs = jobCountMap.get(m.userId) ?? 0;
|
||||
const tokens = jobs * TOKENS_PER_JOB;
|
||||
return {
|
||||
userId: m.userId,
|
||||
name: m.displayName,
|
||||
tokens,
|
||||
cost: Math.round((tokens / 1000) * COST_PER_1K_TOKENS * 100) / 100,
|
||||
};
|
||||
});
|
||||
|
||||
const total = byUser.reduce((sum, u) => sum + u.tokens, 0);
|
||||
|
||||
return { total, byUser };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get top tools from audit log action types (tool invocations are logged as actions).
|
||||
*/
|
||||
private async getTopTools(teamId: string) {
|
||||
const results = await this.db
|
||||
.select({
|
||||
name: agentAuditLog.actionType,
|
||||
invocations: sql<number>`count(*)`,
|
||||
})
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
))
|
||||
.groupBy(agentAuditLog.actionType)
|
||||
.orderBy(desc(sql`count(*)`))
|
||||
.limit(10);
|
||||
|
||||
return results.map((r) => ({
|
||||
name: r.name,
|
||||
invocations: Number(r.invocations),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get top commands from audit log entries where actionType starts with 'command:'.
|
||||
* Falls back to all action types containing 'command' or starting with '/'.
|
||||
*/
|
||||
private async getTopCommands(teamId: string) {
|
||||
const results = await this.db
|
||||
.select({
|
||||
name: agentAuditLog.actionType,
|
||||
count: sql<number>`count(*)`,
|
||||
})
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
sql`${agentAuditLog.actionType} LIKE 'command:%'`,
|
||||
))
|
||||
.groupBy(agentAuditLog.actionType)
|
||||
.orderBy(desc(sql`count(*)`))
|
||||
.limit(10);
|
||||
|
||||
return results.map((r) => {
|
||||
const stripped = r.name.replace(/^command:/, '');
|
||||
return {
|
||||
name: stripped.startsWith('/') ? stripped : `/${stripped}`,
|
||||
count: Number(r.count),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Identify capability gaps from denied/pending capability requests.
|
||||
*/
|
||||
private async getCapabilityGaps(teamId: string) {
|
||||
const results = await this.db
|
||||
.select({
|
||||
tool: teamCapabilityRequests.capabilityName,
|
||||
requestCount: sql<number>`count(*)`,
|
||||
})
|
||||
.from(teamCapabilityRequests)
|
||||
.where(and(
|
||||
eq(teamCapabilityRequests.teamId, teamId),
|
||||
sql`${teamCapabilityRequests.status} IN ('pending', 'rejected')`,
|
||||
))
|
||||
.groupBy(teamCapabilityRequests.capabilityName)
|
||||
.orderBy(desc(sql`count(*)`))
|
||||
.limit(10);
|
||||
|
||||
return results.map((r) => ({
|
||||
tool: r.tool,
|
||||
requestCount: Number(r.requestCount),
|
||||
suggestion: `Install ${r.tool} connector or add to allowed tools`,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute performance trends from audit log.
|
||||
* - correctionRate: fraction of actions that were corrections/rejections
|
||||
* - correctionTrend: difference between this week and last week correction rates
|
||||
* - avgResponseTime: average time between job creation and completion (seconds)
|
||||
*/
|
||||
private async getPerformanceTrends(teamId: string) {
|
||||
const now = new Date();
|
||||
const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
const twoWeeksAgo = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// This week's correction rate
|
||||
const [thisWeekTotal] = await this.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const [thisWeekRejected] = await this.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneWeekAgo),
|
||||
eq(agentAuditLog.approved, false),
|
||||
));
|
||||
|
||||
// Last week's correction rate
|
||||
const [lastWeekTotal] = await this.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, twoWeeksAgo),
|
||||
lt(agentAuditLog.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const [lastWeekRejected] = await this.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, twoWeeksAgo),
|
||||
lt(agentAuditLog.createdAt, oneWeekAgo),
|
||||
eq(agentAuditLog.approved, false),
|
||||
));
|
||||
|
||||
const thisWeekRate = Number(thisWeekTotal?.count) > 0
|
||||
? Number(thisWeekRejected?.count ?? 0) / Number(thisWeekTotal.count)
|
||||
: 0;
|
||||
|
||||
const lastWeekRate = Number(lastWeekTotal?.count) > 0
|
||||
? Number(lastWeekRejected?.count ?? 0) / Number(lastWeekTotal.count)
|
||||
: 0;
|
||||
|
||||
// Average response time from completed jobs
|
||||
const [avgTime] = await this.db
|
||||
.select({
|
||||
avgSeconds: sql<number>`coalesce(avg(extract(epoch from (${agentJobs.completedAt} - ${agentJobs.createdAt}))), 0)`,
|
||||
})
|
||||
.from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.teamId, teamId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
sql`${agentJobs.completedAt} IS NOT NULL`,
|
||||
));
|
||||
|
||||
return {
|
||||
correctionRate: Math.round(thisWeekRate * 100) / 100,
|
||||
correctionTrend: Math.round((thisWeekRate - lastWeekRate) * 100) / 100,
|
||||
avgResponseTime: Math.round(Number(avgTime?.avgSeconds ?? 0) * 10) / 10,
|
||||
};
|
||||
}
|
||||
}
|
||||
74
packages/team-server/src/services/audit-service.ts
Normal file
74
packages/team-server/src/services/audit-service.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { eq, and, desc, isNull } from 'drizzle-orm';
|
||||
import { agentAuditLog } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class AuditService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async log(entry: {
|
||||
userId: string;
|
||||
teamId?: string;
|
||||
agentName: string;
|
||||
actionType: string;
|
||||
description: string;
|
||||
beforeState?: Record<string, unknown>;
|
||||
afterState?: Record<string, unknown>;
|
||||
requiresApproval?: boolean;
|
||||
}) {
|
||||
const [created] = await this.db.insert(agentAuditLog).values({
|
||||
userId: entry.userId,
|
||||
teamId: entry.teamId ?? null,
|
||||
agentName: entry.agentName,
|
||||
actionType: entry.actionType,
|
||||
description: entry.description,
|
||||
beforeState: entry.beforeState ?? null,
|
||||
afterState: entry.afterState ?? null,
|
||||
requiresApproval: entry.requiresApproval ?? false,
|
||||
}).returning();
|
||||
return created;
|
||||
}
|
||||
|
||||
async list(teamId: string, filters?: { actionType?: string; agentName?: string }) {
|
||||
const conditions = [eq(agentAuditLog.teamId, teamId)];
|
||||
if (filters?.actionType) conditions.push(eq(agentAuditLog.actionType, filters.actionType));
|
||||
if (filters?.agentName) conditions.push(eq(agentAuditLog.agentName, filters.agentName));
|
||||
|
||||
return this.db.select().from(agentAuditLog)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(agentAuditLog.createdAt))
|
||||
.limit(100);
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
const [entry] = await this.db.select().from(agentAuditLog)
|
||||
.where(eq(agentAuditLog.id, id))
|
||||
.limit(1);
|
||||
return entry ?? null;
|
||||
}
|
||||
|
||||
async approve(entryId: string, approvedBy: string) {
|
||||
const [updated] = await this.db.update(agentAuditLog)
|
||||
.set({ approved: true, approvedBy })
|
||||
.where(eq(agentAuditLog.id, entryId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async reject(entryId: string, approvedBy: string) {
|
||||
const [updated] = await this.db.update(agentAuditLog)
|
||||
.set({ approved: false, approvedBy })
|
||||
.where(eq(agentAuditLog.id, entryId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async getPendingApprovals(teamId: string) {
|
||||
return this.db.select().from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
eq(agentAuditLog.requiresApproval, true),
|
||||
isNull(agentAuditLog.approved),
|
||||
))
|
||||
.orderBy(desc(agentAuditLog.createdAt));
|
||||
}
|
||||
}
|
||||
90
packages/team-server/src/services/cron-service.ts
Normal file
90
packages/team-server/src/services/cron-service.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import cronParser from 'cron-parser';
|
||||
const { parseExpression } = cronParser;
|
||||
import { cronSchedules } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import { scheduledJobTypeSchema } from '@waggle/shared';
|
||||
|
||||
export function getNextRunAt(cronExpr: string): Date {
|
||||
const interval = parseExpression(cronExpr);
|
||||
return interval.next().toDate();
|
||||
}
|
||||
|
||||
export class CronService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async create(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: { name: string; cronExpr: string; jobType: string; jobConfig?: Record<string, unknown> },
|
||||
) {
|
||||
// Validate cron expression by parsing it
|
||||
const nextRunAt = getNextRunAt(data.cronExpr);
|
||||
const jobType = scheduledJobTypeSchema.safeParse(data.jobType);
|
||||
if (!jobType.success) {
|
||||
throw new Error(`Unsupported scheduled job type: ${data.jobType}`);
|
||||
}
|
||||
|
||||
const [schedule] = await this.db.insert(cronSchedules).values({
|
||||
teamId,
|
||||
createdBy: userId,
|
||||
name: data.name,
|
||||
cronExpr: data.cronExpr,
|
||||
jobType: jobType.data,
|
||||
jobConfig: data.jobConfig ?? {},
|
||||
enabled: true,
|
||||
nextRunAt,
|
||||
}).returning();
|
||||
|
||||
return schedule;
|
||||
}
|
||||
|
||||
async list(teamId: string) {
|
||||
return this.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.teamId, teamId));
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
const [schedule] = await this.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.id, id));
|
||||
return schedule ?? null;
|
||||
}
|
||||
|
||||
async update(teamId: string, id: string, data: { name?: string; cronExpr?: string; enabled?: boolean; jobConfig?: Record<string, unknown> }) {
|
||||
const updates: Record<string, unknown> = {};
|
||||
|
||||
if (data.name !== undefined) updates.name = data.name;
|
||||
if (data.enabled !== undefined) updates.enabled = data.enabled;
|
||||
if (data.jobConfig !== undefined) updates.jobConfig = data.jobConfig;
|
||||
|
||||
if (data.cronExpr !== undefined) {
|
||||
updates.cronExpr = data.cronExpr;
|
||||
updates.nextRunAt = getNextRunAt(data.cronExpr);
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) return null;
|
||||
|
||||
const [updated] = await this.db.update(cronSchedules)
|
||||
.set(updates)
|
||||
.where(and(
|
||||
eq(cronSchedules.id, id),
|
||||
eq(cronSchedules.teamId, teamId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async markRun(id: string) {
|
||||
const schedule = await this.getById(id);
|
||||
if (!schedule) return null;
|
||||
|
||||
const now = new Date();
|
||||
const nextRunAt = getNextRunAt(schedule.cronExpr);
|
||||
|
||||
const [updated] = await this.db.update(cronSchedules)
|
||||
.set({ lastRunAt: now, nextRunAt })
|
||||
.where(eq(cronSchedules.id, id))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
}
|
||||
103
packages/team-server/src/services/job-service.ts
Normal file
103
packages/team-server/src/services/job-service.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { Queue } from 'bullmq';
|
||||
import { eq, desc } from 'drizzle-orm';
|
||||
import { agentJobs } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class JobService {
|
||||
private queue: Queue;
|
||||
|
||||
constructor(private db: Db, redisUrl: string, queueName = 'waggle-jobs') {
|
||||
const url = new URL(redisUrl);
|
||||
this.queue = new Queue(queueName, {
|
||||
connection: {
|
||||
host: url.hostname,
|
||||
port: parseInt(url.port || '6379'),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async createJob(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
jobType: string,
|
||||
input: Record<string, unknown>,
|
||||
jobId?: string,
|
||||
) {
|
||||
const [created] = await this.db.insert(agentJobs).values({
|
||||
...(jobId ? { id: jobId } : {}),
|
||||
teamId,
|
||||
userId,
|
||||
jobType,
|
||||
status: 'queued',
|
||||
input,
|
||||
}).onConflictDoNothing({ target: agentJobs.id }).returning();
|
||||
|
||||
const job = created ?? (jobId ? await this.getJob(jobId) : null);
|
||||
if (!job) throw new Error('Failed to create job');
|
||||
if (job.teamId !== teamId || job.userId !== userId || job.jobType !== jobType) {
|
||||
throw new Error('Job idempotency key collision');
|
||||
}
|
||||
|
||||
await this.queue.add(job.jobType, {
|
||||
jobId: job.id,
|
||||
teamId: job.teamId,
|
||||
userId: job.userId,
|
||||
jobType: job.jobType,
|
||||
input: job.input,
|
||||
}, { jobId: job.id });
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
async getJob(jobId: string) {
|
||||
const [job] = await this.db.select().from(agentJobs).where(eq(agentJobs.id, jobId));
|
||||
return job ?? null;
|
||||
}
|
||||
|
||||
async listByTeam(teamId: string, limit = 50) {
|
||||
return this.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId))
|
||||
.orderBy(desc(agentJobs.createdAt))
|
||||
.limit(Math.min(limit, 100));
|
||||
}
|
||||
|
||||
async updateJobStatus(jobId: string, status: string, output?: Record<string, unknown>) {
|
||||
const updates: Record<string, unknown> = { status };
|
||||
if (status === 'running') updates.startedAt = new Date();
|
||||
if (status === 'completed' || status === 'failed') {
|
||||
updates.completedAt = new Date();
|
||||
if (output) updates.output = output;
|
||||
}
|
||||
const [updated] = await this.db.update(agentJobs)
|
||||
.set(updates)
|
||||
.where(eq(agentJobs.id, jobId))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
|
||||
async cancelJob(jobId: string) {
|
||||
// Update DB status
|
||||
const updated = await this.updateJobStatus(jobId, 'cancelled');
|
||||
|
||||
// Try to remove from BullMQ queue
|
||||
try {
|
||||
const bullJob = await this.queue.getJob(jobId);
|
||||
if (bullJob) {
|
||||
const state = await bullJob.getState();
|
||||
if (state === 'waiting' || state === 'delayed') {
|
||||
await bullJob.remove();
|
||||
} else if (state === 'active') {
|
||||
await bullJob.moveToFailed(new Error('Cancelled by user'), 'cancelled', true);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Queue removal failed — DB status is still updated
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
async close() {
|
||||
await this.queue.close();
|
||||
}
|
||||
}
|
||||
168
packages/team-server/src/services/knowledge-service.ts
Normal file
168
packages/team-server/src/services/knowledge-service.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { eq, and, or, ilike, inArray } from 'drizzle-orm';
|
||||
import { teamEntities, teamRelations } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export interface EntityFilters {
|
||||
entityType?: string;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
export class KnowledgeService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async createEntity(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: {
|
||||
entityType: string;
|
||||
name: string;
|
||||
properties?: Record<string, unknown>;
|
||||
validFrom?: string;
|
||||
validTo?: string;
|
||||
},
|
||||
) {
|
||||
const values: typeof teamEntities.$inferInsert = {
|
||||
teamId,
|
||||
entityType: data.entityType,
|
||||
name: data.name,
|
||||
properties: data.properties ?? {},
|
||||
sharedBy: userId,
|
||||
};
|
||||
if (data.validFrom) values.validFrom = new Date(data.validFrom);
|
||||
if (data.validTo) values.validTo = new Date(data.validTo);
|
||||
|
||||
const [entity] = await this.db.insert(teamEntities).values(values).returning();
|
||||
return entity;
|
||||
}
|
||||
|
||||
async listEntities(teamId: string, filters?: EntityFilters) {
|
||||
const conditions = [eq(teamEntities.teamId, teamId)];
|
||||
|
||||
if (filters?.entityType) {
|
||||
conditions.push(eq(teamEntities.entityType, filters.entityType));
|
||||
}
|
||||
if (filters?.search) {
|
||||
conditions.push(ilike(teamEntities.name, `%${filters.search}%`));
|
||||
}
|
||||
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamEntities)
|
||||
.where(and(...conditions));
|
||||
}
|
||||
|
||||
async getEntity(entityId: string) {
|
||||
const [entity] = await this.db
|
||||
.select()
|
||||
.from(teamEntities)
|
||||
.where(eq(teamEntities.id, entityId))
|
||||
.limit(1);
|
||||
return entity ?? null;
|
||||
}
|
||||
|
||||
async createRelation(
|
||||
teamId: string,
|
||||
data: {
|
||||
sourceId: string;
|
||||
targetId: string;
|
||||
relationType: string;
|
||||
confidence?: number;
|
||||
properties?: Record<string, unknown>;
|
||||
},
|
||||
) {
|
||||
const endpointIds = [...new Set([data.sourceId, data.targetId])];
|
||||
const ownedEndpoints = await this.db
|
||||
.select({ id: teamEntities.id })
|
||||
.from(teamEntities)
|
||||
.where(and(
|
||||
eq(teamEntities.teamId, teamId),
|
||||
inArray(teamEntities.id, endpointIds),
|
||||
));
|
||||
if (ownedEndpoints.length !== endpointIds.length) return null;
|
||||
|
||||
const [relation] = await this.db.insert(teamRelations).values({
|
||||
teamId,
|
||||
sourceId: data.sourceId,
|
||||
targetId: data.targetId,
|
||||
relationType: data.relationType,
|
||||
confidence: data.confidence ?? 1.0,
|
||||
properties: data.properties ?? {},
|
||||
}).returning();
|
||||
return relation;
|
||||
}
|
||||
|
||||
async queryGraph(
|
||||
teamId: string,
|
||||
startEntityId: string,
|
||||
depth: number = 2,
|
||||
relationTypes?: string[],
|
||||
) {
|
||||
const [startEntity] = await this.db
|
||||
.select()
|
||||
.from(teamEntities)
|
||||
.where(and(
|
||||
eq(teamEntities.id, startEntityId),
|
||||
eq(teamEntities.teamId, teamId),
|
||||
))
|
||||
.limit(1);
|
||||
if (!startEntity) return null;
|
||||
|
||||
const visited = new Set<string>([startEntityId]);
|
||||
const resultEntities: Array<typeof teamEntities.$inferSelect> = [startEntity];
|
||||
const resultRelations: Array<typeof teamRelations.$inferSelect> = [];
|
||||
|
||||
let frontier = [startEntityId];
|
||||
|
||||
for (let d = 0; d < depth && frontier.length > 0; d++) {
|
||||
// Find relations connected to frontier entities
|
||||
const rels = await this.db
|
||||
.select()
|
||||
.from(teamRelations)
|
||||
.where(
|
||||
and(
|
||||
eq(teamRelations.teamId, teamId),
|
||||
or(
|
||||
inArray(teamRelations.sourceId, frontier),
|
||||
inArray(teamRelations.targetId, frontier),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Apply relationTypes filter if provided
|
||||
const filteredRels = relationTypes
|
||||
? rels.filter((r) => relationTypes.includes(r.relationType))
|
||||
: rels;
|
||||
|
||||
const nextFrontier: string[] = [];
|
||||
for (const rel of filteredRels) {
|
||||
resultRelations.push(rel);
|
||||
for (const id of [rel.sourceId, rel.targetId]) {
|
||||
if (!visited.has(id)) {
|
||||
visited.add(id);
|
||||
nextFrontier.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (nextFrontier.length > 0) {
|
||||
const entities = await this.db
|
||||
.select()
|
||||
.from(teamEntities)
|
||||
.where(
|
||||
and(
|
||||
eq(teamEntities.teamId, teamId),
|
||||
inArray(teamEntities.id, nextFrontier),
|
||||
),
|
||||
);
|
||||
resultEntities.push(...entities);
|
||||
}
|
||||
|
||||
frontier = nextFrontier;
|
||||
}
|
||||
|
||||
return {
|
||||
entities: resultEntities,
|
||||
relations: resultRelations,
|
||||
};
|
||||
}
|
||||
}
|
||||
119
packages/team-server/src/services/message-service.ts
Normal file
119
packages/team-server/src/services/message-service.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { eq, and, desc, sql } from 'drizzle-orm';
|
||||
import { messages, teamEntities, tasks } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import type { HiveQuery, HiveQueryResult } from '@waggle/waggle-dance';
|
||||
import type Redis from 'ioredis';
|
||||
|
||||
export interface MessageFilters {
|
||||
type?: string;
|
||||
subtype?: string;
|
||||
}
|
||||
|
||||
export class MessageService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async send(
|
||||
teamId: string,
|
||||
senderId: string,
|
||||
data: {
|
||||
type: string;
|
||||
subtype: string;
|
||||
content: Record<string, unknown>;
|
||||
referenceId?: string;
|
||||
routing?: Array<{ userId: string; reason: string }>;
|
||||
},
|
||||
redis?: Redis,
|
||||
) {
|
||||
const [message] = await this.db.insert(messages).values({
|
||||
teamId,
|
||||
senderId,
|
||||
type: data.type,
|
||||
subtype: data.subtype,
|
||||
content: data.content,
|
||||
referenceId: data.referenceId ?? null,
|
||||
routing: data.routing ?? null,
|
||||
}).returning();
|
||||
|
||||
// Publish to Redis for real-time delivery
|
||||
if (redis) {
|
||||
await redis.publish(`team:${teamId}:waggle`, JSON.stringify(message));
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
async list(teamId: string, filters?: MessageFilters) {
|
||||
const conditions = [eq(messages.teamId, teamId)];
|
||||
|
||||
if (filters?.type) {
|
||||
conditions.push(eq(messages.type, filters.type));
|
||||
}
|
||||
if (filters?.subtype) {
|
||||
conditions.push(eq(messages.subtype, filters.subtype));
|
||||
}
|
||||
|
||||
return this.db
|
||||
.select()
|
||||
.from(messages)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(messages.createdAt));
|
||||
}
|
||||
|
||||
async checkHive(teamId: string, query: HiveQuery): Promise<HiveQueryResult> {
|
||||
const searchTerm = `%${query.topic}%`;
|
||||
|
||||
// Search team_entities by name or entityType matching the topic
|
||||
const entities = await this.db
|
||||
.select({
|
||||
id: teamEntities.id,
|
||||
name: teamEntities.name,
|
||||
entityType: teamEntities.entityType,
|
||||
properties: teamEntities.properties,
|
||||
})
|
||||
.from(teamEntities)
|
||||
.where(
|
||||
and(
|
||||
eq(teamEntities.teamId, teamId),
|
||||
sql`(${teamEntities.name} ILIKE ${searchTerm} OR ${teamEntities.entityType} ILIKE ${searchTerm})`,
|
||||
),
|
||||
)
|
||||
.limit(10);
|
||||
|
||||
// Search tasks by title or description matching the topic
|
||||
const relatedTasks = await this.db
|
||||
.select({
|
||||
id: tasks.id,
|
||||
title: tasks.title,
|
||||
status: tasks.status,
|
||||
createdBy: tasks.createdBy,
|
||||
})
|
||||
.from(tasks)
|
||||
.where(
|
||||
and(
|
||||
eq(tasks.teamId, teamId),
|
||||
sql`(${tasks.title} ILIKE ${searchTerm} OR ${tasks.description} ILIKE ${searchTerm})`,
|
||||
),
|
||||
)
|
||||
.limit(10);
|
||||
|
||||
// Search recent broadcast messages
|
||||
const relatedMessages = await this.db
|
||||
.select({
|
||||
id: messages.id,
|
||||
type: messages.type,
|
||||
subtype: messages.subtype,
|
||||
content: messages.content,
|
||||
})
|
||||
.from(messages)
|
||||
.where(
|
||||
and(
|
||||
eq(messages.teamId, teamId),
|
||||
eq(messages.type, 'broadcast'),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(messages.createdAt))
|
||||
.limit(10);
|
||||
|
||||
return { entities, relatedTasks, relatedMessages };
|
||||
}
|
||||
}
|
||||
102
packages/team-server/src/services/proactive-service.ts
Normal file
102
packages/team-server/src/services/proactive-service.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { eq, and, desc } from 'drizzle-orm';
|
||||
import { proactivePatterns, suggestionsLog } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import { MAX_SUGGESTIONS_PER_INTERACTION } from '@waggle/shared';
|
||||
import { BUILT_IN_PATTERNS } from '../proactive/patterns.js';
|
||||
|
||||
export class ProactiveService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async ensurePatternsSeeded() {
|
||||
const existing = await this.db.select().from(proactivePatterns);
|
||||
if (existing.length === 0) {
|
||||
for (const p of BUILT_IN_PATTERNS) {
|
||||
await this.db.insert(proactivePatterns).values({
|
||||
name: p.name,
|
||||
trigger: { condition: p.triggerCondition },
|
||||
suggestionType: p.suggestionType,
|
||||
template: p.template,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async evaluate(userId: string, jobContext: Record<string, unknown>) {
|
||||
// Check if user already has max pending suggestions
|
||||
const pending = await this.db.select().from(suggestionsLog)
|
||||
.where(and(
|
||||
eq(suggestionsLog.userId, userId),
|
||||
eq(suggestionsLog.status, 'pending'),
|
||||
));
|
||||
|
||||
if (pending.length >= MAX_SUGGESTIONS_PER_INTERACTION) return null;
|
||||
|
||||
// Get active patterns
|
||||
const patterns = await this.db.select().from(proactivePatterns)
|
||||
.where(eq(proactivePatterns.enabled, true));
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const shouldTrigger = this.matchPattern(pattern, jobContext);
|
||||
if (!shouldTrigger) continue;
|
||||
|
||||
// Check if already dismissed for this pattern
|
||||
const dismissed = await this.db.select().from(suggestionsLog)
|
||||
.where(and(
|
||||
eq(suggestionsLog.userId, userId),
|
||||
eq(suggestionsLog.patternId, pattern.id),
|
||||
eq(suggestionsLog.status, 'dismissed'),
|
||||
));
|
||||
|
||||
if (dismissed.length > 0) continue;
|
||||
|
||||
// Create suggestion
|
||||
const [suggestion] = await this.db.insert(suggestionsLog).values({
|
||||
userId,
|
||||
patternId: pattern.id,
|
||||
context: jobContext,
|
||||
status: 'pending',
|
||||
}).returning();
|
||||
|
||||
return { ...suggestion, pattern };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private matchPattern(
|
||||
pattern: { suggestionType: string },
|
||||
context: Record<string, unknown>,
|
||||
): boolean {
|
||||
const triggerType = pattern.suggestionType;
|
||||
if (triggerType === 'cron' && context.repeatCount && (context.repeatCount as number) >= 3) return true;
|
||||
if (triggerType === 'dashboard' && context.hasData) return true;
|
||||
if (triggerType === 'share' && context.relevantUsers) return true;
|
||||
if (triggerType === 'upgrade' && context.expensiveModel) return true;
|
||||
if (triggerType === 'skill' && context.manualSteps) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
async listPending(userId: string) {
|
||||
return this.db.select().from(suggestionsLog)
|
||||
.where(and(
|
||||
eq(suggestionsLog.userId, userId),
|
||||
eq(suggestionsLog.status, 'pending'),
|
||||
))
|
||||
.orderBy(desc(suggestionsLog.createdAt));
|
||||
}
|
||||
|
||||
async updateStatus(
|
||||
suggestionId: string,
|
||||
userId: string,
|
||||
status: 'accepted' | 'dismissed' | 'snoozed',
|
||||
) {
|
||||
const [updated] = await this.db.update(suggestionsLog)
|
||||
.set({ status })
|
||||
.where(and(
|
||||
eq(suggestionsLog.id, suggestionId),
|
||||
eq(suggestionsLog.userId, userId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
}
|
||||
89
packages/team-server/src/services/resource-service.ts
Normal file
89
packages/team-server/src/services/resource-service.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { teamResources } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class ResourceService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async share(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: {
|
||||
resourceType: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
config: Record<string, unknown>;
|
||||
},
|
||||
) {
|
||||
const [resource] = await this.db.insert(teamResources).values({
|
||||
teamId,
|
||||
resourceType: data.resourceType,
|
||||
name: data.name,
|
||||
description: data.description ?? null,
|
||||
config: data.config,
|
||||
sharedBy: userId,
|
||||
rating: 0,
|
||||
useCount: 0,
|
||||
}).returning();
|
||||
return resource;
|
||||
}
|
||||
|
||||
async list(teamId: string, resourceType?: string) {
|
||||
const conditions = [eq(teamResources.teamId, teamId)];
|
||||
|
||||
if (resourceType) {
|
||||
conditions.push(eq(teamResources.resourceType, resourceType));
|
||||
}
|
||||
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamResources)
|
||||
.where(and(...conditions));
|
||||
}
|
||||
|
||||
async rate(teamId: string, resourceId: string, rating: number) {
|
||||
const [resource] = await this.db
|
||||
.select()
|
||||
.from(teamResources)
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.limit(1);
|
||||
if (!resource) return null;
|
||||
|
||||
const newRating = resource.useCount > 0
|
||||
? (resource.rating * resource.useCount + rating) / (resource.useCount + 1)
|
||||
: rating;
|
||||
|
||||
const [updated] = await this.db.update(teamResources)
|
||||
.set({ rating: newRating })
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
|
||||
async incrementUseCount(teamId: string, resourceId: string) {
|
||||
const [resource] = await this.db
|
||||
.select()
|
||||
.from(teamResources)
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.limit(1);
|
||||
if (!resource) return null;
|
||||
|
||||
const [updated] = await this.db.update(teamResources)
|
||||
.set({ useCount: resource.useCount + 1 })
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
91
packages/team-server/src/services/task-service.ts
Normal file
91
packages/team-server/src/services/task-service.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { tasks } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export interface TaskFilters {
|
||||
status?: string;
|
||||
assignee?: string;
|
||||
priority?: string;
|
||||
}
|
||||
|
||||
export class TaskService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async create(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: { title: string; description?: string; priority?: string; parentTaskId?: string },
|
||||
) {
|
||||
const [task] = await this.db.insert(tasks).values({
|
||||
teamId,
|
||||
title: data.title,
|
||||
description: data.description,
|
||||
priority: data.priority ?? 'normal',
|
||||
createdBy: userId,
|
||||
parentTaskId: data.parentTaskId,
|
||||
}).returning();
|
||||
return task;
|
||||
}
|
||||
|
||||
async list(teamId: string, filters?: TaskFilters) {
|
||||
const conditions = [eq(tasks.teamId, teamId)];
|
||||
|
||||
if (filters?.status) {
|
||||
conditions.push(eq(tasks.status, filters.status));
|
||||
}
|
||||
if (filters?.assignee) {
|
||||
conditions.push(eq(tasks.assignedTo, filters.assignee));
|
||||
}
|
||||
if (filters?.priority) {
|
||||
conditions.push(eq(tasks.priority, filters.priority));
|
||||
}
|
||||
|
||||
return this.db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(...conditions));
|
||||
}
|
||||
|
||||
async get(taskId: string) {
|
||||
const [task] = await this.db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(eq(tasks.id, taskId))
|
||||
.limit(1);
|
||||
return task ?? null;
|
||||
}
|
||||
|
||||
async update(
|
||||
taskId: string,
|
||||
data: {
|
||||
title?: string;
|
||||
description?: string;
|
||||
status?: string;
|
||||
priority?: string;
|
||||
assignedTo?: string | null;
|
||||
},
|
||||
) {
|
||||
const setData: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (data.title !== undefined) setData.title = data.title;
|
||||
if (data.description !== undefined) setData.description = data.description;
|
||||
if (data.status !== undefined) setData.status = data.status;
|
||||
if (data.priority !== undefined) setData.priority = data.priority;
|
||||
if (data.assignedTo !== undefined) setData.assignedTo = data.assignedTo;
|
||||
|
||||
const [updated] = await this.db
|
||||
.update(tasks)
|
||||
.set(setData)
|
||||
.where(eq(tasks.id, taskId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async claim(taskId: string, userId: string) {
|
||||
const [updated] = await this.db
|
||||
.update(tasks)
|
||||
.set({ assignedTo: userId, status: 'claimed', updatedAt: new Date() })
|
||||
.where(eq(tasks.id, taskId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
}
|
||||
379
packages/team-server/src/services/team-capability-governance.ts
Normal file
379
packages/team-server/src/services/team-capability-governance.ts
Normal file
@@ -0,0 +1,379 @@
|
||||
import { eq, and, desc } from 'drizzle-orm';
|
||||
import { RISK_LEVELS, riskRank, type RiskLevel } from '@waggle/shared';
|
||||
import {
|
||||
teamCapabilityPolicies,
|
||||
teamCapabilityOverrides,
|
||||
teamCapabilityRequests,
|
||||
} from '../db/schema.js';
|
||||
import type { DbExecutor } from '../db/connection.js';
|
||||
|
||||
export interface EffectivePermissions {
|
||||
role: string;
|
||||
allowedSources: string[];
|
||||
blockedTools: string[];
|
||||
approvalThreshold: string;
|
||||
overrides: Map<string, 'approved' | 'blocked'>;
|
||||
}
|
||||
|
||||
export type PermissionResult =
|
||||
| 'allowed'
|
||||
| 'blocked'
|
||||
| 'needs_approval'
|
||||
| 'source_not_allowed';
|
||||
|
||||
/**
|
||||
* Rank a governance risk string on the canonical scale (P7/D15 A2b). The
|
||||
* governance domain adds a 'none' tier (below 'low') that the canonical set
|
||||
* doesn't have. Anything else falls back to canonical riskRank, so 'critical'
|
||||
* (rank 3) correctly outranks 'low' (0) — the previous local map omitted
|
||||
* 'critical', so `?? 0` sorted a critical risk BELOW low (a silent RBAC defect).
|
||||
*/
|
||||
function governanceRiskRank(level: string): number {
|
||||
if (level === 'none') return -1;
|
||||
return (RISK_LEVELS as readonly string[]).includes(level)
|
||||
? riskRank(level as RiskLevel)
|
||||
: -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given risk level exceeds the threshold.
|
||||
* Threshold 'none' means nothing triggers approval.
|
||||
*/
|
||||
export function riskExceedsThreshold(risk: string, threshold: string): boolean {
|
||||
if (threshold === 'none') return false;
|
||||
return governanceRiskRank(risk) > governanceRiskRank(threshold);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve permission for a single capability against effective permissions.
|
||||
*
|
||||
* Resolution order:
|
||||
* 1. Check overrides — if override exists, return its decision immediately
|
||||
* 2. Check role policy (source allowed? tool blocked?)
|
||||
* 3. If policy allows but risk exceeds threshold → needs_approval
|
||||
* 4. Otherwise → allowed
|
||||
*/
|
||||
export function resolvePermission(
|
||||
perms: EffectivePermissions,
|
||||
capabilityName: string,
|
||||
capabilityType: string,
|
||||
risk: string = 'low',
|
||||
): PermissionResult {
|
||||
// 1. Override wins
|
||||
const override = perms.overrides.get(capabilityName);
|
||||
if (override === 'approved') return 'allowed';
|
||||
if (override === 'blocked') return 'blocked';
|
||||
|
||||
// 2. Blocked tool check
|
||||
if (perms.blockedTools.includes(capabilityName)) return 'blocked';
|
||||
|
||||
// 3. Source allowed check
|
||||
if (!perms.allowedSources.includes(capabilityType)) return 'source_not_allowed';
|
||||
|
||||
// 4. Risk threshold check
|
||||
if (riskExceedsThreshold(risk, perms.approvalThreshold)) return 'needs_approval';
|
||||
|
||||
return 'allowed';
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter a list of capabilities by permissions, returning only those allowed or needing approval.
|
||||
*/
|
||||
export function filterByPermissions(
|
||||
perms: EffectivePermissions,
|
||||
capabilities: Array<{ name: string; type: string; risk?: string }>,
|
||||
): Array<{ name: string; type: string; risk?: string; result: PermissionResult }> {
|
||||
return capabilities.map((cap) => ({
|
||||
...cap,
|
||||
result: resolvePermission(perms, cap.name, cap.type, cap.risk ?? 'low'),
|
||||
}));
|
||||
}
|
||||
|
||||
export interface DefaultPolicy {
|
||||
role: string;
|
||||
allowedSources: string[];
|
||||
blockedTools: string[];
|
||||
approvalThreshold: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the 3 default role policies for a new team.
|
||||
*/
|
||||
export function getDefaultPolicies(): DefaultPolicy[] {
|
||||
return [
|
||||
{
|
||||
role: 'owner',
|
||||
allowedSources: ['native', 'skill', 'plugin', 'mcp'],
|
||||
blockedTools: [],
|
||||
approvalThreshold: 'none',
|
||||
},
|
||||
{
|
||||
role: 'admin',
|
||||
allowedSources: ['native', 'skill', 'plugin', 'mcp'],
|
||||
blockedTools: [],
|
||||
approvalThreshold: 'none',
|
||||
},
|
||||
{
|
||||
role: 'member',
|
||||
allowedSources: ['native', 'skill'],
|
||||
blockedTools: ['bash', 'delete_skill'],
|
||||
approvalThreshold: 'medium',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export class TeamCapabilityGovernance {
|
||||
constructor(private db: DbExecutor) {}
|
||||
|
||||
/**
|
||||
* Get effective permissions for a role in a team, including overrides.
|
||||
*/
|
||||
async getEffectivePermissions(teamId: string, role: string): Promise<EffectivePermissions> {
|
||||
// Get role policy
|
||||
const [policy] = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityPolicies)
|
||||
.where(and(
|
||||
eq(teamCapabilityPolicies.teamId, teamId),
|
||||
eq(teamCapabilityPolicies.role, role),
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
// Get overrides for this team
|
||||
const overrideRows = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityOverrides)
|
||||
.where(eq(teamCapabilityOverrides.teamId, teamId));
|
||||
|
||||
const overrides = new Map<string, 'approved' | 'blocked'>();
|
||||
for (const row of overrideRows) {
|
||||
overrides.set(row.capabilityName, row.decision as 'approved' | 'blocked');
|
||||
}
|
||||
|
||||
if (!policy) {
|
||||
// Fallback: no policy found, restrictive defaults
|
||||
return {
|
||||
role,
|
||||
allowedSources: [],
|
||||
blockedTools: [],
|
||||
approvalThreshold: 'none',
|
||||
overrides,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
role,
|
||||
allowedSources: policy.allowedSources as string[],
|
||||
blockedTools: policy.blockedTools as string[],
|
||||
approvalThreshold: policy.approvalThreshold,
|
||||
overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async listPolicies(teamId: string) {
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamCapabilityPolicies)
|
||||
.where(eq(teamCapabilityPolicies.teamId, teamId));
|
||||
}
|
||||
|
||||
async upsertPolicy(
|
||||
teamId: string,
|
||||
role: string,
|
||||
data: {
|
||||
allowedSources?: string[];
|
||||
blockedTools?: string[];
|
||||
approvalThreshold?: string;
|
||||
},
|
||||
updatedBy: string,
|
||||
) {
|
||||
const [existing] = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityPolicies)
|
||||
.where(and(
|
||||
eq(teamCapabilityPolicies.teamId, teamId),
|
||||
eq(teamCapabilityPolicies.role, role),
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (existing) {
|
||||
const [updated] = await this.db
|
||||
.update(teamCapabilityPolicies)
|
||||
.set({
|
||||
...(data.allowedSources !== undefined && { allowedSources: data.allowedSources }),
|
||||
...(data.blockedTools !== undefined && { blockedTools: data.blockedTools }),
|
||||
...(data.approvalThreshold !== undefined && { approvalThreshold: data.approvalThreshold }),
|
||||
updatedBy,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(teamCapabilityPolicies.id, existing.id))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
|
||||
const defaults = getDefaultPolicies().find((p) => p.role === role);
|
||||
const [created] = await this.db
|
||||
.insert(teamCapabilityPolicies)
|
||||
.values({
|
||||
teamId,
|
||||
role,
|
||||
allowedSources: data.allowedSources ?? defaults?.allowedSources ?? [],
|
||||
blockedTools: data.blockedTools ?? defaults?.blockedTools ?? [],
|
||||
approvalThreshold: data.approvalThreshold ?? defaults?.approvalThreshold ?? 'none',
|
||||
updatedBy,
|
||||
})
|
||||
.returning();
|
||||
return created;
|
||||
}
|
||||
|
||||
async seedDefaultPolicies(teamId: string, seedBy: string) {
|
||||
const defaults = getDefaultPolicies();
|
||||
const results = [];
|
||||
for (const policy of defaults) {
|
||||
const [row] = await this.db
|
||||
.insert(teamCapabilityPolicies)
|
||||
.values({
|
||||
teamId,
|
||||
role: policy.role,
|
||||
allowedSources: policy.allowedSources,
|
||||
blockedTools: policy.blockedTools,
|
||||
approvalThreshold: policy.approvalThreshold,
|
||||
updatedBy: seedBy,
|
||||
})
|
||||
.returning();
|
||||
results.push(row);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// --- Overrides ---
|
||||
|
||||
async listOverrides(teamId: string) {
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamCapabilityOverrides)
|
||||
.where(eq(teamCapabilityOverrides.teamId, teamId))
|
||||
.orderBy(desc(teamCapabilityOverrides.createdAt));
|
||||
}
|
||||
|
||||
async createOverride(
|
||||
teamId: string,
|
||||
data: {
|
||||
capabilityName: string;
|
||||
capabilityType: string;
|
||||
decision: 'approved' | 'blocked';
|
||||
reason?: string;
|
||||
},
|
||||
decidedBy: string,
|
||||
) {
|
||||
const [row] = await this.db
|
||||
.insert(teamCapabilityOverrides)
|
||||
.values({
|
||||
teamId,
|
||||
capabilityName: data.capabilityName,
|
||||
capabilityType: data.capabilityType,
|
||||
decision: data.decision,
|
||||
reason: data.reason ?? '',
|
||||
decidedBy,
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
async deleteOverride(teamId: string, overrideId: string) {
|
||||
const [deleted] = await this.db
|
||||
.delete(teamCapabilityOverrides)
|
||||
.where(and(
|
||||
eq(teamCapabilityOverrides.teamId, teamId),
|
||||
eq(teamCapabilityOverrides.id, overrideId),
|
||||
))
|
||||
.returning();
|
||||
return deleted ?? null;
|
||||
}
|
||||
|
||||
// --- Requests ---
|
||||
|
||||
async listRequests(teamId: string, status?: string) {
|
||||
const conditions = [eq(teamCapabilityRequests.teamId, teamId)];
|
||||
if (status) {
|
||||
conditions.push(eq(teamCapabilityRequests.status, status));
|
||||
}
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamCapabilityRequests)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(teamCapabilityRequests.createdAt));
|
||||
}
|
||||
|
||||
async submitRequest(
|
||||
teamId: string,
|
||||
requestedBy: string,
|
||||
data: {
|
||||
capabilityName: string;
|
||||
capabilityType: string;
|
||||
justification: string;
|
||||
},
|
||||
): Promise<{ duplicate: true } | { duplicate: false; request: typeof teamCapabilityRequests.$inferSelect }> {
|
||||
// Duplicate check: pending request for same capability by same user
|
||||
const [existing] = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityRequests)
|
||||
.where(and(
|
||||
eq(teamCapabilityRequests.teamId, teamId),
|
||||
eq(teamCapabilityRequests.requestedBy, requestedBy),
|
||||
eq(teamCapabilityRequests.capabilityName, data.capabilityName),
|
||||
eq(teamCapabilityRequests.status, 'pending'),
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (existing) return { duplicate: true };
|
||||
|
||||
const [request] = await this.db
|
||||
.insert(teamCapabilityRequests)
|
||||
.values({
|
||||
teamId,
|
||||
requestedBy,
|
||||
capabilityName: data.capabilityName,
|
||||
capabilityType: data.capabilityType,
|
||||
justification: data.justification,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return { duplicate: false, request };
|
||||
}
|
||||
|
||||
async getRequest(teamId: string, requestId: string) {
|
||||
const [row] = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityRequests)
|
||||
.where(and(
|
||||
eq(teamCapabilityRequests.teamId, teamId),
|
||||
eq(teamCapabilityRequests.id, requestId),
|
||||
))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
async decideRequest(
|
||||
teamId: string,
|
||||
requestId: string,
|
||||
decidedBy: string,
|
||||
decision: 'approved' | 'rejected',
|
||||
reason?: string,
|
||||
) {
|
||||
const [updated] = await this.db
|
||||
.update(teamCapabilityRequests)
|
||||
.set({
|
||||
status: decision,
|
||||
decidedBy,
|
||||
decisionReason: reason ?? null,
|
||||
decidedAt: new Date(),
|
||||
})
|
||||
.where(and(
|
||||
eq(teamCapabilityRequests.teamId, teamId),
|
||||
eq(teamCapabilityRequests.id, requestId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
}
|
||||
139
packages/team-server/src/services/team-service.ts
Normal file
139
packages/team-server/src/services/team-service.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import { eq, and, sql } from 'drizzle-orm';
|
||||
import { teams, teamMembers, users } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import { TeamCapabilityGovernance } from './team-capability-governance.js';
|
||||
|
||||
export class TeamService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async create(ownerId: string, data: { name: string; slug: string }) {
|
||||
return this.db.transaction(async (tx) => {
|
||||
const [team] = await tx.insert(teams).values({
|
||||
name: data.name,
|
||||
slug: data.slug,
|
||||
ownerId,
|
||||
}).returning();
|
||||
|
||||
await tx.insert(teamMembers).values({
|
||||
teamId: team.id,
|
||||
userId: ownerId,
|
||||
role: 'owner',
|
||||
});
|
||||
|
||||
// Seed default capability policies
|
||||
const governance = new TeamCapabilityGovernance(tx);
|
||||
await governance.seedDefaultPolicies(team.id, ownerId);
|
||||
|
||||
return team;
|
||||
});
|
||||
}
|
||||
|
||||
async getBySlug(slug: string) {
|
||||
const [team] = await this.db.select().from(teams).where(eq(teams.slug, slug)).limit(1);
|
||||
return team ?? null;
|
||||
}
|
||||
|
||||
async listForUser(userId: string) {
|
||||
const rows = await this.db
|
||||
.select({
|
||||
id: teams.id,
|
||||
name: teams.name,
|
||||
slug: teams.slug,
|
||||
ownerId: teams.ownerId,
|
||||
createdAt: teams.createdAt,
|
||||
role: teamMembers.role,
|
||||
})
|
||||
.from(teamMembers)
|
||||
.innerJoin(teams, eq(teamMembers.teamId, teams.id))
|
||||
.where(eq(teamMembers.userId, userId));
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
async update(teamId: string, data: { name: string }) {
|
||||
const [updated] = await this.db
|
||||
.update(teams)
|
||||
.set({ name: data.name })
|
||||
.where(eq(teams.id, teamId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async addMember(teamId: string, userId: string, role: 'admin' | 'member') {
|
||||
const [member] = await this.db.insert(teamMembers).values({
|
||||
teamId,
|
||||
userId,
|
||||
role,
|
||||
}).returning();
|
||||
return member;
|
||||
}
|
||||
|
||||
async removeMember(teamId: string, userId: string) {
|
||||
// Prevent removing the owner
|
||||
const membership = await this.getMembership(teamId, userId);
|
||||
if (!membership) return false;
|
||||
if (membership.role === 'owner') {
|
||||
throw new Error('Cannot remove the team owner');
|
||||
}
|
||||
|
||||
await this.db
|
||||
.delete(teamMembers)
|
||||
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)));
|
||||
return true;
|
||||
}
|
||||
|
||||
async updateMember(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: { role?: 'admin' | 'member'; roleDescription?: string; interests?: string[] },
|
||||
) {
|
||||
if (data.role !== undefined) {
|
||||
const membership = await this.getMembership(teamId, userId);
|
||||
if (!membership) return null;
|
||||
if (membership.role === 'owner') {
|
||||
throw new Error('Cannot change the team owner role');
|
||||
}
|
||||
}
|
||||
|
||||
const setData: Record<string, unknown> = {};
|
||||
if (data.role !== undefined) setData.role = data.role;
|
||||
if (data.roleDescription !== undefined) setData.roleDescription = data.roleDescription;
|
||||
if (data.interests !== undefined) setData.interests = data.interests;
|
||||
|
||||
if (Object.keys(setData).length === 0) return null;
|
||||
|
||||
const [updated] = await this.db
|
||||
.update(teamMembers)
|
||||
.set(setData)
|
||||
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async getMembership(teamId: string, userId: string) {
|
||||
const [membership] = await this.db
|
||||
.select()
|
||||
.from(teamMembers)
|
||||
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)))
|
||||
.limit(1);
|
||||
return membership ?? null;
|
||||
}
|
||||
|
||||
async getMembers(teamId: string) {
|
||||
const rows = await this.db
|
||||
.select({
|
||||
userId: teamMembers.userId,
|
||||
role: teamMembers.role,
|
||||
roleDescription: teamMembers.roleDescription,
|
||||
interests: teamMembers.interests,
|
||||
joinedAt: teamMembers.joinedAt,
|
||||
displayName: users.displayName,
|
||||
email: users.email,
|
||||
avatarUrl: users.avatarUrl,
|
||||
})
|
||||
.from(teamMembers)
|
||||
.innerJoin(users, eq(teamMembers.userId, users.id))
|
||||
.where(eq(teamMembers.teamId, teamId));
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
59
packages/team-server/src/services/user-service.ts
Normal file
59
packages/team-server/src/services/user-service.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { users } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export interface ClerkUserData {
|
||||
clerkId: string;
|
||||
displayName: string;
|
||||
email: string;
|
||||
avatarUrl?: string | null;
|
||||
}
|
||||
|
||||
export class UserService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async getByClerkId(clerkId: string) {
|
||||
const [user] = await this.db.select().from(users).where(eq(users.clerkId, clerkId)).limit(1);
|
||||
return user ?? null;
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
const [user] = await this.db.select().from(users).where(eq(users.id, id)).limit(1);
|
||||
return user ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or update a user from Clerk JWT claims.
|
||||
* Used by auth plugin for auto-provisioning on first auth,
|
||||
* and by webhook for ongoing sync.
|
||||
*/
|
||||
async upsertFromClerk(data: ClerkUserData) {
|
||||
const existing = await this.getByClerkId(data.clerkId);
|
||||
|
||||
if (existing) {
|
||||
// Update display name / email / avatar if changed
|
||||
await this.db.update(users)
|
||||
.set({
|
||||
displayName: data.displayName,
|
||||
email: data.email,
|
||||
avatarUrl: data.avatarUrl ?? null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(users.clerkId, data.clerkId));
|
||||
// Return fresh copy
|
||||
return (await this.getByClerkId(data.clerkId))!;
|
||||
}
|
||||
|
||||
// Insert new user
|
||||
const [created] = await this.db.insert(users)
|
||||
.values({
|
||||
clerkId: data.clerkId,
|
||||
displayName: data.displayName,
|
||||
email: data.email,
|
||||
avatarUrl: data.avatarUrl ?? null,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return created;
|
||||
}
|
||||
}
|
||||
46
packages/team-server/src/ws/connection-manager.ts
Normal file
46
packages/team-server/src/ws/connection-manager.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import type { WebSocket } from 'ws';
|
||||
import type { WsServerEvent } from '@waggle/shared';
|
||||
|
||||
export class ConnectionManager {
|
||||
private connections = new Map<string, Map<string, WebSocket>>(); // teamId -> userId -> ws
|
||||
|
||||
add(teamId: string, userId: string, ws: WebSocket): void {
|
||||
if (!this.connections.has(teamId)) {
|
||||
this.connections.set(teamId, new Map());
|
||||
}
|
||||
this.connections.get(teamId)!.set(userId, ws);
|
||||
}
|
||||
|
||||
remove(teamId: string, userId: string): void {
|
||||
this.connections.get(teamId)?.delete(userId);
|
||||
if (this.connections.get(teamId)?.size === 0) {
|
||||
this.connections.delete(teamId);
|
||||
}
|
||||
}
|
||||
|
||||
broadcast(teamId: string, event: WsServerEvent, excludeUserId?: string): void {
|
||||
const team = this.connections.get(teamId);
|
||||
if (!team) return;
|
||||
const data = JSON.stringify(event);
|
||||
for (const [userId, ws] of team) {
|
||||
if (userId !== excludeUserId && ws.readyState === ws.OPEN) {
|
||||
ws.send(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sendTo(teamId: string, userId: string, event: WsServerEvent): void {
|
||||
const ws = this.connections.get(teamId)?.get(userId);
|
||||
if (ws && ws.readyState === ws.OPEN) {
|
||||
ws.send(JSON.stringify(event));
|
||||
}
|
||||
}
|
||||
|
||||
getConnectedUsers(teamId: string): string[] {
|
||||
return Array.from(this.connections.get(teamId)?.keys() ?? []);
|
||||
}
|
||||
|
||||
getTeamCount(): number {
|
||||
return this.connections.size;
|
||||
}
|
||||
}
|
||||
264
packages/team-server/src/ws/gateway.ts
Normal file
264
packages/team-server/src/ws/gateway.ts
Normal file
@@ -0,0 +1,264 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { WsClientEvent, WsServerEvent } from '@waggle/shared';
|
||||
import { createClerkClient, verifyToken } from '@clerk/fastify';
|
||||
import { ConnectionManager } from './connection-manager.js';
|
||||
import { teams, messages, users } from '../db/schema.js';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
|
||||
export const connectionManager = new ConnectionManager();
|
||||
|
||||
/**
|
||||
* Validate that a string looks like a JWT (3 dot-separated base64url segments).
|
||||
* This is a structural check, not a cryptographic verification.
|
||||
*/
|
||||
function isJwtStructure(token: string): boolean {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return false;
|
||||
// Each segment should be non-empty and valid base64url
|
||||
const base64urlRegex = /^[A-Za-z0-9_-]+$/;
|
||||
return parts.every((part) => part.length > 0 && base64urlRegex.test(part));
|
||||
}
|
||||
|
||||
// Overridable verifier for testing — allows tests to swap in a mock
|
||||
export type WsTokenVerifier = (token: string) => Promise<{ sub: string }>;
|
||||
let _wsTokenVerifier: WsTokenVerifier | null = null;
|
||||
|
||||
/** Override the WS token verifier (for testing only) */
|
||||
export function setWsTokenVerifier(verifier: WsTokenVerifier | null): void {
|
||||
_wsTokenVerifier = verifier;
|
||||
}
|
||||
|
||||
export async function wsGateway(fastify: FastifyInstance) {
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
// Create Clerk client for JWT verification if secret key is available
|
||||
const clerkSecretKey = fastify.config.clerkSecretKey;
|
||||
const clerk = clerkSecretKey
|
||||
? createClerkClient({ secretKey: clerkSecretKey })
|
||||
: null;
|
||||
|
||||
// Hard fail in production if no JWT verification path is configured. Without
|
||||
// either a Clerk client or a test override, the gateway would have no way to
|
||||
// cryptographically verify incoming tokens — the previous fallback (unsigned
|
||||
// JWT decode) is forgeable. NODE_ENV !== 'production' (dev / desktop /
|
||||
// testing) is allowed to start without the key, but connections without a
|
||||
// verifier are rejected at request time below.
|
||||
if (!clerk && !_wsTokenVerifier && process.env.NODE_ENV === 'production') {
|
||||
throw new Error(
|
||||
'[ws-gateway] CLERK_SECRET_KEY required in production. WebSocket gateway ' +
|
||||
'refuses to start without cryptographic JWT verification configured. ' +
|
||||
'Set CLERK_SECRET_KEY in environment or settings.json.',
|
||||
);
|
||||
}
|
||||
if (!clerk && !_wsTokenVerifier) {
|
||||
fastify.log.warn(
|
||||
'[ws-gateway] CLERK_SECRET_KEY absent; WebSocket connections will be rejected. ' +
|
||||
'This is dev/desktop mode — set CLERK_SECRET_KEY for cloud/SaaS deployments.',
|
||||
);
|
||||
}
|
||||
|
||||
fastify.get('/ws', { websocket: true }, (socket, request) => {
|
||||
let userId: string | null = null;
|
||||
let teamId: string | null = null;
|
||||
|
||||
socket.on('message', async (raw: Buffer | string) => {
|
||||
try {
|
||||
const event = JSON.parse(raw.toString()) as WsClientEvent;
|
||||
|
||||
switch (event.type) {
|
||||
case 'authenticate': {
|
||||
const token = event.token;
|
||||
|
||||
// Reject tokens that are not JWTs (plain userIds, random strings)
|
||||
if (!isJwtStructure(token)) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
message: 'Invalid token: must be a valid JWT',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let sub: string;
|
||||
|
||||
if (_wsTokenVerifier) {
|
||||
// Test override path
|
||||
const result = await _wsTokenVerifier(token);
|
||||
sub = result.sub;
|
||||
} else if (clerk) {
|
||||
// Production path: full Clerk JWT verification. `clerk` is only
|
||||
// non-null when clerkSecretKey is set, so the secretKey below is
|
||||
// always present here.
|
||||
const payload = await verifyToken(token, { secretKey: clerkSecretKey });
|
||||
sub = payload.sub;
|
||||
} else {
|
||||
// No verifier available — reject. The startup check above ensures
|
||||
// production cannot reach this branch. Dev/desktop without a key
|
||||
// hits this and is rejected at connection time (no silent decode).
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
message: 'Authentication unavailable: server has no JWT verifier configured',
|
||||
}),
|
||||
);
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Look up internal user by Clerk ID
|
||||
const [user] = await fastify.db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.clerkId, sub));
|
||||
|
||||
if (!user) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
message: 'User not found',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (teamId && userId) {
|
||||
connectionManager.remove(teamId, userId);
|
||||
}
|
||||
teamId = null;
|
||||
userId = user.id;
|
||||
socket.send(JSON.stringify({ type: 'authenticated', userId }));
|
||||
} catch {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
message: 'Token verification failed',
|
||||
}),
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'join_team': {
|
||||
if (!userId) {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Not authenticated' }));
|
||||
return;
|
||||
}
|
||||
|
||||
const [team] = await fastify.db
|
||||
.select()
|
||||
.from(teams)
|
||||
.where(eq(teams.slug, event.teamSlug));
|
||||
|
||||
if (!team) {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Team not found' }));
|
||||
return;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, userId);
|
||||
if (!membership) {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Team not found' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Leave previous team if any
|
||||
if (teamId && userId) {
|
||||
connectionManager.remove(teamId, userId);
|
||||
}
|
||||
|
||||
teamId = team.id;
|
||||
connectionManager.add(teamId, userId, socket);
|
||||
|
||||
// Subscribe to Redis channel for this team
|
||||
const channel = `team:${teamId}:waggle`;
|
||||
try {
|
||||
const existingChannels = await fastify.redisSub.call('PUBSUB', 'CHANNELS', channel) as string[];
|
||||
// Only subscribe if not already subscribed (redisSub is shared)
|
||||
if (!existingChannels || !existingChannels.includes(channel)) {
|
||||
await fastify.redisSub.subscribe(channel);
|
||||
}
|
||||
} catch {
|
||||
// Redis subscribe failure is non-fatal — real-time updates won't work
|
||||
// but join should still succeed
|
||||
}
|
||||
|
||||
socket.send(JSON.stringify({ type: 'joined_team', teamSlug: event.teamSlug }));
|
||||
break;
|
||||
}
|
||||
|
||||
case 'send_message': {
|
||||
if (!userId || !teamId) {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Not in a team' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Persist message
|
||||
const [msg] = await fastify.db
|
||||
.insert(messages)
|
||||
.values({
|
||||
teamId,
|
||||
senderId: userId,
|
||||
type: event.messageType,
|
||||
subtype: event.subtype,
|
||||
content: event.content,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Publish to Redis for cross-process delivery
|
||||
await fastify.redis.publish(
|
||||
`team:${teamId}:waggle`,
|
||||
JSON.stringify(msg),
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Invalid message' }));
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
if (teamId && userId) {
|
||||
connectionManager.remove(teamId, userId);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Forward Redis pub/sub messages to WebSocket clients
|
||||
fastify.redisSub.on('message', (channel: string, data: string) => {
|
||||
const match = channel.match(/^team:(.+):waggle$/);
|
||||
if (!match) return;
|
||||
const tId = match[1];
|
||||
try {
|
||||
const event: WsServerEvent = { type: 'waggle_message', message: JSON.parse(data) };
|
||||
connectionManager.broadcast(tId, event);
|
||||
} catch {
|
||||
// Ignore malformed messages from Redis
|
||||
}
|
||||
});
|
||||
|
||||
// Subscribe to job progress channels via pattern matching
|
||||
await fastify.redisSub.psubscribe('job:*:progress');
|
||||
|
||||
// Forward job progress events to WebSocket clients
|
||||
fastify.redisSub.on('pmessage', (_pattern: string, channel: string, data: string) => {
|
||||
const jobMatch = channel.match(/^job:(.+):progress$/);
|
||||
if (!jobMatch) return;
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
const event: WsServerEvent = {
|
||||
type: 'job_progress',
|
||||
jobId: jobMatch[1],
|
||||
progress: parsed,
|
||||
};
|
||||
// Route to the team that owns this job
|
||||
if (parsed.teamId) {
|
||||
connectionManager.broadcast(parsed.teamId, event);
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed messages from Redis
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user