moving
This commit is contained in:
@@ -1,10 +1,30 @@
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
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;
|
||||
@@ -88,6 +108,8 @@ export class AgentService {
|
||||
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,
|
||||
@@ -137,6 +159,10 @@ export class AgentService {
|
||||
.from(agentGroupMembers)
|
||||
.where(eq(agentGroupMembers.groupId, groupId));
|
||||
|
||||
if (!(await this.groupMembersOwned(userId, members.map((member) => member.agentId)))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { ...group, members };
|
||||
}
|
||||
|
||||
@@ -149,6 +175,9 @@ export class AgentService {
|
||||
// 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
|
||||
|
||||
@@ -3,6 +3,7 @@ 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);
|
||||
@@ -19,13 +20,17 @@ export class CronService {
|
||||
) {
|
||||
// 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: data.jobType,
|
||||
jobType: jobType.data,
|
||||
jobConfig: data.jobConfig ?? {},
|
||||
enabled: true,
|
||||
nextRunAt,
|
||||
@@ -45,7 +50,7 @@ export class CronService {
|
||||
return schedule ?? null;
|
||||
}
|
||||
|
||||
async update(id: string, data: { name?: string; cronExpr?: string; enabled?: boolean; jobConfig?: Record<string, unknown> }) {
|
||||
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;
|
||||
@@ -61,7 +66,10 @@ export class CronService {
|
||||
|
||||
const [updated] = await this.db.update(cronSchedules)
|
||||
.set(updates)
|
||||
.where(eq(cronSchedules.id, id))
|
||||
.where(and(
|
||||
eq(cronSchedules.id, id),
|
||||
eq(cronSchedules.teamId, teamId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
@@ -16,21 +16,34 @@ export class JobService {
|
||||
});
|
||||
}
|
||||
|
||||
async createJob(teamId: string, userId: string, jobType: string, input: Record<string, unknown>) {
|
||||
const [job] = await this.db.insert(agentJobs).values({
|
||||
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,
|
||||
}).returning();
|
||||
}).onConflictDoNothing({ target: agentJobs.id }).returning();
|
||||
|
||||
await this.queue.add(jobType, {
|
||||
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,
|
||||
userId,
|
||||
jobType,
|
||||
input,
|
||||
teamId: job.teamId,
|
||||
userId: job.userId,
|
||||
jobType: job.jobType,
|
||||
input: job.input,
|
||||
}, { jobId: job.id });
|
||||
|
||||
return job;
|
||||
|
||||
@@ -70,6 +70,16 @@ export class KnowledgeService {
|
||||
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,
|
||||
@@ -87,8 +97,18 @@ export class KnowledgeService {
|
||||
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> = [];
|
||||
const resultEntities: Array<typeof teamEntities.$inferSelect> = [startEntity];
|
||||
const resultRelations: Array<typeof teamRelations.$inferSelect> = [];
|
||||
|
||||
let frontier = [startEntityId];
|
||||
@@ -140,14 +160,8 @@ export class KnowledgeService {
|
||||
frontier = nextFrontier;
|
||||
}
|
||||
|
||||
// Fetch the start entity
|
||||
const [startEntity] = await this.db
|
||||
.select()
|
||||
.from(teamEntities)
|
||||
.where(eq(teamEntities.id, startEntityId));
|
||||
|
||||
return {
|
||||
entities: [startEntity, ...resultEntities].filter(Boolean),
|
||||
entities: resultEntities,
|
||||
relations: resultRelations,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -85,10 +85,17 @@ export class ProactiveService {
|
||||
.orderBy(desc(suggestionsLog.createdAt));
|
||||
}
|
||||
|
||||
async updateStatus(suggestionId: string, status: 'accepted' | 'dismissed' | 'snoozed') {
|
||||
async updateStatus(
|
||||
suggestionId: string,
|
||||
userId: string,
|
||||
status: 'accepted' | 'dismissed' | 'snoozed',
|
||||
) {
|
||||
const [updated] = await this.db.update(suggestionsLog)
|
||||
.set({ status })
|
||||
.where(eq(suggestionsLog.id, suggestionId))
|
||||
.where(and(
|
||||
eq(suggestionsLog.id, suggestionId),
|
||||
eq(suggestionsLog.userId, userId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
@@ -41,11 +41,14 @@ export class ResourceService {
|
||||
.where(and(...conditions));
|
||||
}
|
||||
|
||||
async rate(resourceId: string, rating: number) {
|
||||
async rate(teamId: string, resourceId: string, rating: number) {
|
||||
const [resource] = await this.db
|
||||
.select()
|
||||
.from(teamResources)
|
||||
.where(eq(teamResources.id, resourceId))
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.limit(1);
|
||||
if (!resource) return null;
|
||||
|
||||
@@ -55,22 +58,31 @@ export class ResourceService {
|
||||
|
||||
const [updated] = await this.db.update(teamResources)
|
||||
.set({ rating: newRating })
|
||||
.where(eq(teamResources.id, resourceId))
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
|
||||
async incrementUseCount(resourceId: string) {
|
||||
async incrementUseCount(teamId: string, resourceId: string) {
|
||||
const [resource] = await this.db
|
||||
.select()
|
||||
.from(teamResources)
|
||||
.where(eq(teamResources.id, resourceId))
|
||||
.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(eq(teamResources.id, resourceId))
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
|
||||
@@ -280,10 +280,13 @@ export class TeamCapabilityGovernance {
|
||||
return row;
|
||||
}
|
||||
|
||||
async deleteOverride(overrideId: string) {
|
||||
async deleteOverride(teamId: string, overrideId: string) {
|
||||
const [deleted] = await this.db
|
||||
.delete(teamCapabilityOverrides)
|
||||
.where(eq(teamCapabilityOverrides.id, overrideId))
|
||||
.where(and(
|
||||
eq(teamCapabilityOverrides.teamId, teamId),
|
||||
eq(teamCapabilityOverrides.id, overrideId),
|
||||
))
|
||||
.returning();
|
||||
return deleted ?? null;
|
||||
}
|
||||
@@ -339,16 +342,20 @@ export class TeamCapabilityGovernance {
|
||||
return { duplicate: false, request };
|
||||
}
|
||||
|
||||
async getRequest(requestId: string) {
|
||||
async getRequest(teamId: string, requestId: string) {
|
||||
const [row] = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityRequests)
|
||||
.where(eq(teamCapabilityRequests.id, requestId))
|
||||
.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',
|
||||
@@ -362,7 +369,10 @@ export class TeamCapabilityGovernance {
|
||||
decisionReason: reason ?? null,
|
||||
decidedAt: new Date(),
|
||||
})
|
||||
.where(eq(teamCapabilityRequests.id, requestId))
|
||||
.where(and(
|
||||
eq(teamCapabilityRequests.teamId, teamId),
|
||||
eq(teamCapabilityRequests.id, requestId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
@@ -87,6 +87,14 @@ export class TeamService {
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user