Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

feat(db): CMP-1 persist durable custom agents (#67)

grim4e79f837dba6
diff --git a/apps/api/package.json b/apps/api/package.json
index 065a9e5c..9128b2a1 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -16,8 +16,8 @@
"postinstall": "node scripts/chmod-trpc-binary.mjs",
"start": "bun src/main.ts",
"start:prod": "bun dist/main.js",
- "test": "CRM_TELEMETRY_DISABLED=1 bun test",
- "test:watch": "bun test --watch",
+ "test": "CRM_TELEMETRY_DISABLED=1 bun test --preload ./test/setup.ts",
+ "test:watch": "CRM_TELEMETRY_DISABLED=1 bun test --watch --preload ./test/setup.ts",
"trpc:generate": "nestjs-trpc generate -e src/app.module.ts -r \"**/*.router.ts\" -o src/generated",
"clean": "rm -rf .turbo dist node_modules src/generated"
},
diff --git a/apps/api/src/agent/agent-access.service.ts b/apps/api/src/agent/agent-access.service.ts
new file mode 100644
index 00000000..a9dccf24
--- /dev/null
+++ b/apps/api/src/agent/agent-access.service.ts
@@ -0,0 +1,99 @@
+import {
+ isWorkspaceAdmin,
+ isWorkspaceRole,
+ WORKSPACE_ID,
+ type WorkspaceRole,
+} from "@crm/auth";
+import type { Db, Prisma } from "@crm/db";
+import {
+ ForbiddenException,
+ Injectable,
+ NotFoundException,
+} from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import { canReadAgent, isPrivateAgentDraft } from "./agent-visibility";
+
+@Injectable()
+export class AgentAccessService {
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ async assertMember(userId: string): Promise<WorkspaceRole> {
+ const member = await this.db.member.findUnique({
+ where: {
+ organizationId_userId: { organizationId: WORKSPACE_ID, userId },
+ },
+ select: { role: true },
+ });
+
+ if (!member) {
+ throw new ForbiddenException("You are not a member of this workspace.");
+ }
+
+ return isWorkspaceRole(member.role) ? member.role : "member";
+ }
+
+ async assertCanManageInTransaction(
+ tx: Prisma.TransactionClient,
+ agentId: string,
+ userId: string,
+ ) {
+ const [member] = await tx.$queryRaw<Array<{ role: string }>>`
+ SELECT role
+ FROM "member"
+ WHERE "organizationId" = ${WORKSPACE_ID}
+ AND "userId" = ${userId}
+ FOR SHARE
+ `;
+
+ if (!member) {
+ throw new ForbiddenException("You are not a member of this workspace.");
+ }
+
+ const role = isWorkspaceRole(member.role) ? member.role : "member";
+ const agent = await tx.agentDefinition.findFirst({
+ where: { id: agentId, status: { not: "DELETED" } },
+ select: {
+ id: true,
+ createdById: true,
+ status: true,
+ name: true,
+ description: true,
+ },
+ });
+
+ if (!agent) {
+ throw new NotFoundException(`No agent with id ${agentId}.`);
+ }
+
+ if (isPrivateAgentDraft(agent.status) && agent.createdById !== userId) {
+ throw new NotFoundException(`No agent with id ${agentId}.`);
+ }
+
+ if (agent.createdById !== userId && !isWorkspaceAdmin(role)) {
+ throw new ForbiddenException(
+ "Only the creator or a workspace admin can change this agent.",
+ );
+ }
+
+ return agent;
+ }
+
+ async assertCanRead(agentId: string, userId: string) {
+ await this.assertMember(userId);
+ const agent = await this.db.agentDefinition.findFirst({
+ where: { id: agentId, status: { not: "DELETED" } },
+ select: {
+ id: true,
+ createdById: true,
+ status: true,
+ currentVersionId: true,
+ },
+ });
+
+ if (!agent || !canReadAgent(agent.status, agent.createdById, userId)) {
+ throw new NotFoundException(`No agent with id ${agentId}.`);
+ }
+
+ return agent;
+ }
+}
diff --git a/apps/api/src/agent/agent-definitions.service.ts b/apps/api/src/agent/agent-definitions.service.ts
new file mode 100644
index 00000000..6ab1a048
--- /dev/null
+++ b/apps/api/src/agent/agent-definitions.service.ts
@@ -0,0 +1,486 @@
+import type { Db, Prisma } from "@crm/db";
+import type { AgentDefinitionStatus } from "@crm/db/enums";
+import {
+ BadRequestException,
+ Injectable,
+ NotFoundException,
+} from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import { AgentAccessService } from "./agent-access.service";
+import { TEAM_AGENT_STATUSES } from "./agent-visibility";
+import type { AgentDeployInput, AgentUpdateInput } from "./agents.contracts";
+
+@Injectable()
+export class AgentDefinitionsService {
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly access: AgentAccessService,
+ ) {}
+
+ async list(userId: string) {
+ await this.access.assertMember(userId);
+
+ const rows = await this.db.agentDefinition.findMany({
+ where: { status: { in: [...TEAM_AGENT_STATUSES] } },
+ orderBy: { updatedAt: "desc" },
+ select: {
+ id: true,
+ name: true,
+ description: true,
+ status: true,
+ createdAt: true,
+ updatedAt: true,
+ createdBy: { select: { id: true, name: true, image: true } },
+ currentVersion: {
+ select: { id: true, number: true, deployedAt: true },
+ },
+ triggers: {
+ where: { enabled: true },
+ orderBy: { nextRunAt: "asc" },
+ take: 1,
+ select: { id: true, type: true, name: true, nextRunAt: true },
+ },
+ _count: { select: { runs: true } },
+ },
+ });
+
+ return rows.map((row) => ({
+ ...row,
+ createdAt: row.createdAt.toISOString(),
+ updatedAt: row.updatedAt.toISOString(),
+ currentVersion: row.currentVersion
+ ? {
+ ...row.currentVersion,
+ deployedAt: row.currentVersion.deployedAt?.toISOString() ?? null,
+ }
+ : null,
+ triggers: row.triggers.map((trigger) => ({
+ ...trigger,
+ nextRunAt: trigger.nextRunAt?.toISOString() ?? null,
+ })),
+ runCount: row._count.runs,
+ }));
+ }
+
+ async byId(id: string, userId: string) {
+ await this.access.assertCanRead(id, userId);
+
+ const row = await this.db.agentDefinition.findFirst({
+ where: { id, status: { not: "DELETED" } },
+ select: {
+ id: true,
+ name: true,
+ description: true,
+ status: true,
+ createdById: true,
+ createdAt: true,
+ updatedAt: true,
+ createdBy: { select: { id: true, name: true, image: true } },
+ currentVersion: {
+ select: {
+ id: true,
+ number: true,
+ status: true,
+ manifest: true,
+ modelId: true,
+ sandboxPolicy: true,
+ approvedAt: true,
+ deployedAt: true,
+ },
+ },
+ triggers: {
+ orderBy: { createdAt: "asc" },
+ select: {
+ id: true,
+ type: true,
+ name: true,
+ config: true,
+ enabled: true,
+ nextRunAt: true,
+ lastRunAt: true,
+ },
+ },
+ _count: { select: { runs: true } },
+ },
+ });
+
+ if (!row) throw new NotFoundException(`No agent with id ${id}.`);
+
+ return {
+ ...row,
+ canManage: row.createdById === userId || (await this.canAdmin(userId)),
+ createdAt: row.createdAt.toISOString(),
+ updatedAt: row.updatedAt.toISOString(),
+ currentVersion: row.currentVersion
+ ? {
+ ...row.currentVersion,
+ approvedAt: row.currentVersion.approvedAt?.toISOString() ?? null,
+ deployedAt: row.currentVersion.deployedAt?.toISOString() ?? null,
+ }
+ : null,
+ triggers: row.triggers.map((trigger) => ({
+ ...trigger,
+ nextRunAt: trigger.nextRunAt?.toISOString() ?? null,
+ lastRunAt: trigger.lastRunAt?.toISOString() ?? null,
+ })),
+ runCount: row._count.runs,
+ };
+ }
+
+ async update(input: AgentUpdateInput, userId: string) {
+ const description = input.description?.trim() || null;
+
+ const updated = await this.db.$transaction(async (tx) => {
+ await this.access.assertCanManageInTransaction(tx, input.id, userId);
+ const agent = await this.lockAgent(tx, input.id);
+ const row = await tx.agentDefinition.update({
+ where: { id: input.id },
+ data: { name: input.name, description },
+ select: { id: true, name: true, description: true, status: true },
+ });
+
+ await tx.agentAuditEvent.create({
+ data: {
+ agentId: input.id,
+ actorUserId: userId,
+ actorType: "USER",
+ actorId: userId,
+ type: "agent.updated",
+ summary: "Changed agent details",
+ before: { name: agent.name, description: agent.description },
+ after: { name: input.name, description },
+ },
+ });
+
+ return row;
+ });
+
+ return updated;
+ }
+
+ async deploy(input: AgentDeployInput, userId: string) {
+ return this.db.$transaction(async (tx) => {
+ await this.access.assertCanManageInTransaction(tx, input.id, userId);
+ const agent = await this.lockAgent(tx, input.id);
+ const existing = await tx.agentAuditEvent.findFirst({
+ where: {
+ agentId: input.id,
+ type: "agent.deployed",
+ requestId: input.clientRequestId,
+ },
+ select: { versionId: true },
+ });
+
+ if (existing) {
+ if (existing.versionId !== input.versionId) {
+ throw new BadRequestException(
+ "That deployment request has already been used.",
+ );
+ }
+
+ return { id: input.id, versionId: input.versionId, status: "LIVE" };
+ }
+
+ const version = await tx.agentVersion.findFirst({
+ where: { id: input.versionId, agentId: input.id },
+ select: { id: true, number: true, status: true, manifest: true },
+ });
+
+ if (!version) {
+ throw new NotFoundException(`No version with id ${input.versionId}.`);
+ }
+
+ if (version.status !== "READY" && version.status !== "DEPLOYED") {
+ throw new BadRequestException(
+ "Only a validated agent version can be deployed.",
+ );
+ }
+ const metadata = versionMetadata(version.manifest);
+
+ const now = new Date();
+ await tx.agentVersion.updateMany({
+ where: {
+ agentId: input.id,
+ status: "DEPLOYED",
+ id: { not: input.versionId },
+ },
+ data: { status: "READY" },
+ });
+
+ await tx.agentVersion.update({
+ where: { id: input.versionId },
+ data: {
+ status: "DEPLOYED",
+ approvedAt: now,
+ deployedAt: now,
+ },
+ });
+
+ await tx.agentDefinition.update({
+ where: { id: input.id },
+ data: {
+ currentVersionId: input.versionId,
+ status: "LIVE",
+ archivedAt: null,
+ ...metadata,
+ },
+ });
+
+ await tx.agentTrigger.updateMany({
+ where: { agentId: input.id },
+ data: { enabled: false },
+ });
+
+ await tx.agentTrigger.updateMany({
+ where: { agentId: input.id, versionId: input.versionId },
+ data: { enabled: true },
+ });
+
+ await tx.agentAuditEvent.create({
+ data: {
+ agentId: input.id,
+ versionId: input.versionId,
+ actorUserId: userId,
+ actorType: "USER",
+ actorId: userId,
+ type: "agent.deployed",
+ summary: `Made version ${version.number} live for the team`,
+ before: { status: agent.status },
+ after: { status: "LIVE", version: version.number, ...metadata },
+ requestId: input.clientRequestId,
+ },
+ });
+
+ return { id: input.id, versionId: input.versionId, status: "LIVE" };
+ });
+ }
+
+ async pause(id: string, userId: string) {
+ return this.changeStatus(
+ id,
+ userId,
+ ["LIVE"],
+ "PAUSED",
+ "agent.paused",
+ "Paused agent",
+ "Only a live agent can be paused.",
+ );
+ }
+
+ async resume(id: string, userId: string) {
+ return this.changeStatus(
+ id,
+ userId,
+ ["PAUSED"],
+ "LIVE",
+ "agent.resumed",
+ "Resumed agent",
+ "Only a paused agent can be resumed.",
+ );
+ }
+
+ async archive(id: string, userId: string) {
+ return this.changeStatus(
+ id,
+ userId,
+ ["LIVE", "PAUSED"],
+ "ARCHIVED",
+ "agent.archived",
+ "Archived agent",
+ "Only a live or paused agent can be archived.",
+ { archivedAt: new Date() },
+ );
+ }
+
+ async restore(id: string, userId: string) {
+ return this.changeStatus(
+ id,
+ userId,
+ ["ARCHIVED"],
+ "PAUSED",
+ "agent.restored",
+ "Restored agent",
+ "Only an archived agent can be restored.",
+ { archivedAt: null },
+ );
+ }
+
+ async remove(id: string, userId: string) {
+ const now = new Date();
+
+ return this.db.$transaction(async (tx) => {
+ await this.access.assertCanManageInTransaction(tx, id, userId);
+ const [current] = await tx.$queryRaw<
+ Array<{ id: string; status: string }>
+ >`
+ SELECT id, status
+ FROM "agentDefinition"
+ WHERE id = ${id}
+ FOR UPDATE
+ `;
+
+ if (!current || current.status === "DELETED") {
+ throw new NotFoundException(`No agent with id ${id}.`);
+ }
+
+ const disabledTriggers = await tx.agentTrigger.updateMany({
+ where: { agentId: id, enabled: true },
+ data: { enabled: false, nextRunAt: null },
+ });
+
+ const cancellableRuns = await tx.$queryRaw<Array<{ id: string }>>`
+ SELECT id
+ FROM "agentRun"
+ WHERE "agentId" = ${id}
+ AND (
+ status IN ('QUEUED', 'WAITING_FOR_APPROVAL')
+ OR (status = 'RUNNING' AND "sessionId" IS NULL)
+ )
+ ORDER BY id
+ FOR UPDATE
+ `;
+
+ for (const run of cancellableRuns) {
+ const cancelled = await tx.agentRun.update({
+ where: { id: run.id },
+ data: {
+ status: "CANCELLED",
+ finishedAt: now,
+ errorCode: "AGENT_DELETED",
+ errorMessage: "The agent was deleted before this run completed.",
+ nextEventSequence: { increment: 1 },
+ },
+ select: { nextEventSequence: true },
+ });
+
+ await tx.agentRunEvent.create({
+ data: {
+ runId: run.id,
+ sequence: cancelled.nextEventSequence,
+ type: "run.cancelled",
+ data: { reason: "agent.deleted" },
+ emittedAt: now,
+ },
+ });
+ }
+
+ const agent = await tx.agentDefinition.update({
+ where: { id },
+ data: { status: "DELETED", deletedAt: now },
+ select: { id: true, name: true, status: true, updatedAt: true },
+ });
+
+ await tx.agentAuditEvent.create({
+ data: {
+ agentId: id,
+ actorUserId: userId,
+ actorType: "USER",
+ actorId: userId,
+ type: "agent.deleted",
+ summary: "Deleted agent",
+ before: { status: current.status },
+ after: {
+ status: "DELETED",
+ disabledTriggers: disabledTriggers.count,
+ cancelledRuns: cancellableRuns.length,
+ },
+ },
+ });
+
+ return {
+ ...agent,
+ updatedAt: agent.updatedAt.toISOString(),
+ disabledTriggers: disabledTriggers.count,
+ cancelledRuns: cancellableRuns.length,
+ };
+ });
+ }
+
+ private async changeStatus(
+ id: string,
+ userId: string,
+ allowedFrom: readonly AgentDefinitionStatus[],
+ status: "LIVE" | "PAUSED" | "ARCHIVED",
+ type: string,
+ summary: string,
+ invalidStatusMessage: string,
+ extra: Prisma.AgentDefinitionUpdateInput = {},
+ ) {
+ return this.db.$transaction(async (tx) => {
+ await this.access.assertCanManageInTransaction(tx, id, userId);
+ const before = await this.lockAgent(tx, id);
+ if (!allowedFrom.includes(before.status)) {
+ throw new BadRequestException(invalidStatusMessage);
+ }
+
+ const agent = await tx.agentDefinition.update({
+ where: { id },
+ data: { status, ...extra },
+ select: { id: true, name: true, status: true, updatedAt: true },
+ });
+
+ await tx.agentAuditEvent.create({
+ data: {
+ agentId: id,
+ actorUserId: userId,
+ actorType: "USER",
+ actorId: userId,
+ type,
+ summary,
+ before: { status: before.status },
+ after: { status },
+ },
+ });
+
+ return { ...agent, updatedAt: agent.updatedAt.toISOString() };
+ });
+ }
+
+ private async lockAgent(tx: Prisma.TransactionClient, id: string) {
+ const [agent] = await tx.$queryRaw<
+ Array<{
+ id: string;
+ status: AgentDefinitionStatus;
+ name: string;
+ description: string | null;
+ }>
+ >`
+ SELECT id, status, name, description
+ FROM "agentDefinition"
+ WHERE id = ${id}
+ FOR UPDATE
+ `;
+
+ if (!agent || agent.status === "DELETED") {
+ throw new NotFoundException(`No agent with id ${id}.`);
+ }
+
+ return agent;
+ }
+
+ private async canAdmin(userId: string): Promise<boolean> {
+ const role = await this.access.assertMember(userId);
+ return role === "owner" || role === "admin";
+ }
+}
+
+function versionMetadata(manifest: unknown): {
+ name?: string;
+ description?: string | null;
+} {
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) {
+ return {};
+ }
+
+ const record = manifest as Record<string, unknown>;
+ const name = typeof record.name === "string" ? record.name.trim() : "";
+ const description =
+ typeof record.description === "string"
+ ? record.description.trim() || null
+ : undefined;
+
+ return {
+ ...(name ? { name } : {}),
+ ...(description !== undefined ? { description } : {}),
+ };
+}
diff --git a/apps/api/src/agent/agent-runs.service.ts b/apps/api/src/agent/agent-runs.service.ts
new file mode 100644
index 00000000..7585c801
--- /dev/null
+++ b/apps/api/src/agent/agent-runs.service.ts
@@ -0,0 +1,217 @@
+import { randomUUID } from "node:crypto";
+import type { Db } from "@crm/db";
+import { lockIdempotencyKey } from "@crm/db/idempotency";
+import {
+ BadRequestException,
+ Injectable,
+ NotFoundException,
+} from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import { AgentAccessService } from "./agent-access.service";
+import { AgentTriggerService } from "./agent-trigger.service";
+import type { AgentRunNowInput } from "./agents.contracts";
+
+@Injectable()
+export class AgentRunsService {
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly access: AgentAccessService,
+ private readonly trigger: AgentTriggerService,
+ ) {}
+
+ async list(agentId: string, limit: number, userId: string) {
+ await this.readableAgent(agentId, userId);
+
+ const rows = await this.db.agentRun.findMany({
+ where: { agentId },
+ orderBy: { createdAt: "desc" },
+ take: limit,
+ select: {
+ id: true,
+ status: true,
+ triggerType: true,
+ summary: true,
+ modelId: true,
+ inputTokens: true,
+ outputTokens: true,
+ costUsd: true,
+ errorCode: true,
+ errorMessage: true,
+ createdAt: true,
+ startedAt: true,
+ finishedAt: true,
+ initiatedBy: { select: { id: true, name: true, image: true } },
+ version: { select: { id: true, number: true } },
+ events: {
+ orderBy: { sequence: "asc" },
+ select: {
+ id: true,
+ sequence: true,
+ type: true,
+ data: true,
+ emittedAt: true,
+ },
+ },
+ actions: {
+ orderBy: { plannedAt: "asc" },
+ select: {
+ id: true,
+ type: true,
+ provider: true,
+ targetType: true,
+ targetId: true,
+ targetLabel: true,
+ summary: true,
+ status: true,
+ externalId: true,
+ attemptCount: true,
+ errorCode: true,
+ errorMessage: true,
+ plannedAt: true,
+ startedAt: true,
+ completedAt: true,
+ },
+ },
+ },
+ });
+
+ return rows.map((run) => ({
+ ...run,
+ costUsd: run.costUsd?.toString() ?? null,
+ createdAt: run.createdAt.toISOString(),
+ startedAt: run.startedAt?.toISOString() ?? null,
+ finishedAt: run.finishedAt?.toISOString() ?? null,
+ events: run.events.map((event) => ({
+ ...event,
+ emittedAt: event.emittedAt.toISOString(),
+ })),
+ actions: run.actions.map((action) => ({
+ ...action,
+ plannedAt: action.plannedAt.toISOString(),
+ startedAt: action.startedAt?.toISOString() ?? null,
+ completedAt: action.completedAt?.toISOString() ?? null,
+ })),
+ }));
+ }
+
+ async activity(agentId: string, limit: number, userId: string) {
+ await this.readableAgent(agentId, userId);
+
+ const rows = await this.db.agentAuditEvent.findMany({
+ where: { agentId },
+ orderBy: { emittedAt: "desc" },
+ take: limit,
+ select: {
+ id: true,
+ type: true,
+ summary: true,
+ before: true,
+ after: true,
+ requestId: true,
+ emittedAt: true,
+ actorType: true,
+ actorId: true,
+ actorUser: { select: { id: true, name: true, image: true } },
+ version: { select: { id: true, number: true } },
+ },
+ });
+
+ return rows.map((event) => ({
+ ...event,
+ emittedAt: event.emittedAt.toISOString(),
+ }));
+ }
+
+ async runNow(input: AgentRunNowInput, userId: string) {
+ await this.access.assertMember(userId);
+ const existing = await this.db.agentRun.findUnique({
+ where: { idempotencyKey: input.clientRequestId },
+ select: { id: true, agentId: true },
+ });
+
+ if (existing) {
+ this.assertReplayMatches(existing.agentId, input.id);
+ this.trigger.deployedAgentRunQueued();
+ return { id: existing.id };
+ }
+
+ const run = await this.db.$transaction(async (tx) => {
+ await lockIdempotencyKey(tx, input.clientRequestId);
+ const replay = await tx.agentRun.findUnique({
+ where: { idempotencyKey: input.clientRequestId },
+ select: { id: true, agentId: true },
+ });
+ if (replay) {
+ this.assertReplayMatches(replay.agentId, input.id);
+ return { id: replay.id };
+ }
+
+ const [agent] = await tx.$queryRaw<
+ Array<{
+ id: string;
+ status: string;
+ currentVersionId: string | null;
+ }>
+ >`
+ SELECT id, status, "currentVersionId"
+ FROM "agentDefinition"
+ WHERE id = ${input.id}
+ FOR UPDATE
+ `;
+
+ if (!agent || agent.status === "DELETED") {
+ throw new NotFoundException(`No agent with id ${input.id}.`);
+ }
+
+ if (agent.status !== "LIVE" || !agent.currentVersionId) {
+ throw new BadRequestException("This agent is not live yet.");
+ }
+
+ const created = await tx.agentRun.create({
+ data: {
+ agentId: input.id,
+ versionId: agent.currentVersionId,
+ initiatedById: userId,
+ triggerType: "MANUAL",
+ idempotencyKey: input.clientRequestId,
+ correlationId: randomUUID(),
+ events: {
+ create: { sequence: 0, type: "run.queued", data: {} },
+ },
+ },
+ select: { id: true },
+ });
+
+ await tx.agentAuditEvent.create({
+ data: {
+ agentId: input.id,
+ versionId: agent.currentVersionId,
+ actorUserId: userId,
+ actorType: "USER",
+ actorId: userId,
+ type: "run.requested",
+ summary: "Requested a manual run",
+ requestId: input.clientRequestId,
+ },
+ });
+
+ return created;
+ });
+
+ this.trigger.deployedAgentRunQueued();
+ return run;
+ }
+
+ private async readableAgent(agentId: string, userId: string) {
+ return this.access.assertCanRead(agentId, userId);
+ }
+
+ private assertReplayMatches(
+ existingAgentId: string,
+ requestedAgentId: string,
+ ) {
+ if (existingAgentId !== requestedAgentId) {
+ throw new BadRequestException("That run request has already been used.");
+ }
+ }
+}
diff --git a/apps/api/src/agent/agent-trigger.service.ts b/apps/api/src/agent/agent-trigger.service.ts
index 626edb15..5046a49c 100644
--- a/apps/api/src/agent/agent-trigger.service.ts
+++ b/apps/api/src/agent/agent-trigger.service.ts
@@ -130,6 +130,14 @@ export class AgentTriggerService {
});
}
+ builderConversationQueued(): void {
+ this.pokeRoute("/internal/crm/builder-dispatch");
+ }
+
+ deployedAgentRunQueued(): void {
+ this.pokeRoute("/internal/crm/agent-dispatch");
+ }
+
async backfill(input: {
kind: string;
reason: string;
@@ -243,6 +251,10 @@ export class AgentTriggerService {
}
private poke(): void {
+ this.pokeRoute("/internal/crm/dispatch");
+ }
+
+ private pokeRoute(path: string): void {
const agent = bridge();
if (!agent) return;
@@ -254,11 +266,17 @@ export class AgentTriggerService {
};
try {
- void fetch(agent.url("/internal/crm/dispatch"), {
+ void fetch(agent.url(path), {
method: "POST",
headers: { authorization: `Bearer ${agent.secret}` },
signal: AbortSignal.timeout(POKE_TIMEOUT_MS),
- }).catch(missed);
+ })
+ .then((response) => {
+ if (!response.ok) {
+ throw new Error(`Agent poke returned ${response.status}.`);
+ }
+ })
+ .catch(missed);
} catch (error) {
missed(error);
}
diff --git a/apps/api/src/agent/agent-visibility.ts b/apps/api/src/agent/agent-visibility.ts
new file mode 100644
index 00000000..c74082c5
--- /dev/null
+++ b/apps/api/src/agent/agent-visibility.ts
@@ -0,0 +1,15 @@
+import type { AgentDefinitionStatus } from "@crm/db/enums";
+
+export const TEAM_AGENT_STATUSES = ["LIVE", "PAUSED", "ARCHIVED"] as const;
+
+export function isPrivateAgentDraft(status: AgentDefinitionStatus): boolean {
+ return status === "DRAFT" || status === "DEPLOYING";
+}
+
+export function canReadAgent(
+ status: AgentDefinitionStatus,
+ createdById: string,
+ userId: string,
+): boolean {
+ return !isPrivateAgentDraft(status) || createdById === userId;
+}
diff --git a/apps/api/src/agent/agent.module.ts b/apps/api/src/agent/agent.module.ts
index d88c9d59..2cdae2c2 100644
--- a/apps/api/src/agent/agent.module.ts
+++ b/apps/api/src/agent/agent.module.ts
@@ -1,10 +1,24 @@
import { Module } from "@nestjs/common";
+import { TrpcModule } from "../trpc/trpc.module";
+import { AgentAccessService } from "./agent-access.service";
+import { AgentDefinitionsService } from "./agent-definitions.service";
import { AgentQueueService } from "./agent-queue.service";
+import { AgentRunsService } from "./agent-runs.service";
import { AgentTriggerService } from "./agent-trigger.service";
+import { AgentsRouter } from "./agents.router";
import { ResearchKeyService } from "./research-key.service";
@Module({
- providers: [AgentTriggerService, AgentQueueService, ResearchKeyService],
+ imports: [TrpcModule],
+ providers: [
+ AgentAccessService,
+ AgentDefinitionsService,
+ AgentQueueService,
+ AgentRunsService,
+ AgentTriggerService,
+ AgentsRouter,
+ ResearchKeyService,
+ ],
exports: [AgentTriggerService, AgentQueueService, ResearchKeyService],
})
export class AgentModule {}
diff --git a/apps/api/src/agent/agents.contracts.ts b/apps/api/src/agent/agents.contracts.ts
new file mode 100644
index 00000000..967e3046
--- /dev/null
+++ b/apps/api/src/agent/agents.contracts.ts
@@ -0,0 +1,27 @@
+import { z } from "zod";
+
+export const agentIdInput = z.object({ id: z.string().min(1) });
+
+export const agentHistoryInput = agentIdInput.extend({
+ limit: z.number().int().min(1).max(100).default(50),
+});
+
+export const agentUpdateInput = agentIdInput.extend({
+ name: z.string().trim().min(1).max(120),
+ description: z.string().trim().max(500).nullable(),
+});
+
+export type AgentUpdateInput = z.infer<typeof agentUpdateInput>;
+
+export const agentRunNowInput = agentIdInput.extend({
+ clientRequestId: z.uuid(),
+});
+
+export type AgentRunNowInput = z.infer<typeof agentRunNowInput>;
+
+export const agentDeployInput = agentIdInput.extend({
+ versionId: z.string().min(1),
+ clientRequestId: z.uuid(),
+});
+
+export type AgentDeployInput = z.infer<typeof agentDeployInput>;
diff --git a/apps/api/src/agent/agents.router.ts b/apps/api/src/agent/agents.router.ts
new file mode 100644
index 00000000..0dec15a8
--- /dev/null
+++ b/apps/api/src/agent/agents.router.ts
@@ -0,0 +1,107 @@
+import { Inject } from "@nestjs/common";
+import {
+ Ctx,
+ Input,
+ Mutation,
+ Query,
+ Router,
+ UseMiddlewares,
+} from "nestjs-trpc";
+import type { z } from "zod";
+import type { AuthedTrpcContext } from "../trpc/context.types";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import { AgentDefinitionsService } from "./agent-definitions.service";
+import { AgentRunsService } from "./agent-runs.service";
+import {
+ agentDeployInput,
+ agentHistoryInput,
+ agentIdInput,
+ agentRunNowInput,
+ agentUpdateInput,
+} from "./agents.contracts";
+
+@Router({ alias: "agents" })
+@UseMiddlewares(AuthMiddleware)
+export class AgentsRouter {
+ constructor(
+ @Inject(AgentDefinitionsService)
+ private readonly agents: AgentDefinitionsService,
+ @Inject(AgentRunsService)
+ private readonly runs: AgentRunsService,
+ ) {}
+
+ @Query()
+ async list(@Ctx() ctx: AuthedTrpcContext) {
+ return this.agents.list(ctx.user.id);
+ }
+
+ @Query({ input: agentIdInput })
+ async byId(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.agents.byId(id, ctx.user.id);
+ }
+
+ @Query({ input: agentHistoryInput })
+ async history(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof agentHistoryInput>,
+ ) {
+ return this.runs.list(input.id, input.limit, ctx.user.id);
+ }
+
+ @Query({ input: agentHistoryInput })
+ async activity(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof agentHistoryInput>,
+ ) {
+ return this.runs.activity(input.id, input.limit, ctx.user.id);
+ }
+
+ @Mutation({ input: agentUpdateInput })
+ async update(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof agentUpdateInput>,
+ ) {
+ return this.agents.update(input, ctx.user.id);
+ }
+
+ @Mutation({ input: agentDeployInput })
+ async deploy(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof agentDeployInput>,
+ ) {
+ return this.agents.deploy(input, ctx.user.id);
+ }
+
+ @Mutation({ input: agentIdInput })
+ async pause(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.agents.pause(id, ctx.user.id);
+ }
+
+ @Mutation({ input: agentIdInput })
+ async resume(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.agents.resume(id, ctx.user.id);
+ }
+
+ @Mutation({ input: agentIdInput })
+ async archive(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.agents.archive(id, ctx.user.id);
+ }
+
+ @Mutation({ input: agentIdInput })
+ async restore(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.agents.restore(id, ctx.user.id);
+ }
+
+ @Mutation({ input: agentIdInput })
+ async remove(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.agents.remove(id, ctx.user.id);
+ }
+
+ @Mutation({ input: agentRunNowInput })
+ async runNow(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof agentRunNowInput>,
+ ) {
+ return this.runs.runNow(input, ctx.user.id);
+ }
+}
diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts
index 0426549b..723ff44f 100644
--- a/apps/api/src/app.module.ts
+++ b/apps/api/src/app.module.ts
@@ -3,6 +3,7 @@ import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";
import { ActivitiesModule } from "./activities/activities.module";
+import { AgentModule } from "./agent/agent.module";
import { AuthModule } from "./auth/auth.module";
import { BackfillModule } from "./backfill/backfill.module";
import { AppCacheModule } from "./cache/cache.module";
@@ -54,6 +55,7 @@ import { WorkspaceModule } from "./workspace/workspace.module";
DealsModule,
FieldsModule,
ActivitiesModule,
+ AgentModule,
DashboardModule,
SearchModule,
MailboxModule,
diff --git a/apps/api/src/conversations/conversation-attachments.controller.ts b/apps/api/src/conversations/conversation-attachments.controller.ts
new file mode 100644
index 00000000..1da698f7
--- /dev/null
+++ b/apps/api/src/conversations/conversation-attachments.controller.ts
@@ -0,0 +1,56 @@
+import type { auth } from "@crm/auth";
+import {
+ Controller,
+ Get,
+ Param,
+ Query,
+ Res,
+ StreamableFile,
+} from "@nestjs/common";
+import { Session, type UserSession } from "@thallesp/nestjs-better-auth";
+import type { Response } from "express";
+import { ConversationsService } from "./conversations.service";
+
+type CrmSession = UserSession<typeof auth>;
+
+@Controller("api/conversations/attachments")
+export class ConversationAttachmentsController {
+ constructor(private readonly conversations: ConversationsService) {}
+
+ @Get(":id")
+ async read(
+ @Param("id") id: string,
+ @Query("share") shareToken: string | undefined,
+ @Session() session: CrmSession,
+ @Res({ passthrough: true }) response: Response,
+ ) {
+ const attachment = await this.conversations.attachment(
+ id,
+ session.user.id,
+ shareToken,
+ );
+ const content = Buffer.from(attachment.content);
+ const disposition = attachment.previewable ? "inline" : "attachment";
+ const mediaType = attachment.previewable
+ ? attachment.mediaType
+ : "application/octet-stream";
+
+ response.setHeader("Cache-Control", "private, no-store");
+ response.setHeader("Content-Length", content.byteLength.toString());
+ response.setHeader("Content-Type", mediaType);
+ response.setHeader(
+ "Content-Disposition",
+ `${disposition}; filename*=UTF-8''${encodeHeaderValue(attachment.name)}`,
+ );
+ response.setHeader("X-Content-Type-Options", "nosniff");
+
+ return new StreamableFile(content);
+ }
+}
+
+function encodeHeaderValue(value: string): string {
+ return encodeURIComponent(value).replace(
+ /[!'()*]/g,
+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
+ );
+}
diff --git a/apps/api/src/conversations/conversation-attachments.ts b/apps/api/src/conversations/conversation-attachments.ts
new file mode 100644
index 00000000..4dc8d4fa
--- /dev/null
+++ b/apps/api/src/conversations/conversation-attachments.ts
@@ -0,0 +1,45 @@
+import type { Prisma } from "@crm/db";
+
+export type StoredBuilderAttachment = {
+ id: string;
+ name: string;
+ mediaType: string;
+ size: number;
+};
+
+export function builderMessageWithAttachments(
+ value: Prisma.JsonValue,
+ attachments: StoredBuilderAttachment[],
+ shareToken?: string,
+): Prisma.JsonObject {
+ const message = recordOf(value);
+ return {
+ ...message,
+ attachments: attachments.map((attachment) => ({
+ id: attachment.id,
+ name: attachment.name,
+ type: attachment.mediaType,
+ size: attachment.size,
+ previewUrl: isPreviewableImage(attachment.mediaType)
+ ? attachmentUrl(attachment.id, shareToken)
+ : null,
+ })),
+ } as Prisma.JsonObject;
+}
+
+export function isPreviewableImage(mediaType: string): boolean {
+ return ["image/gif", "image/jpeg", "image/png", "image/webp"].includes(
+ mediaType.toLowerCase(),
+ );
+}
+
+function attachmentUrl(id: string, shareToken?: string): string {
+ const path = `/api/conversations/attachments/${encodeURIComponent(id)}`;
+ return shareToken ? `${path}?share=${encodeURIComponent(shareToken)}` : path;
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
diff --git a/apps/api/src/conversations/conversation-share-token.ts b/apps/api/src/conversations/conversation-share-token.ts
new file mode 100644
index 00000000..025564e8
--- /dev/null
+++ b/apps/api/src/conversations/conversation-share-token.ts
@@ -0,0 +1,5 @@
+import { createHash } from "node:crypto";
+
+export function conversationShareTokenHash(token: string): string {
+ return createHash("sha256").update(token).digest("hex");
+}
diff --git a/apps/api/src/conversations/conversation-sharing.service.ts b/apps/api/src/conversations/conversation-sharing.service.ts
new file mode 100644
index 00000000..f63c75d2
--- /dev/null
+++ b/apps/api/src/conversations/conversation-sharing.service.ts
@@ -0,0 +1,234 @@
+import { randomBytes } from "node:crypto";
+import { WORKSPACE_ID } from "@crm/auth";
+import type { Db, Prisma } from "@crm/db";
+import {
+ ForbiddenException,
+ Injectable,
+ NotFoundException,
+} from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import { builderMessageWithAttachments } from "./conversation-attachments";
+import { conversationShareTokenHash } from "./conversation-share-token";
+
+@Injectable()
+export class ConversationSharingService {
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ async status(conversationId: string, userId: string) {
+ await this.ownedBuilder(conversationId, userId);
+
+ const share = await this.db.agentConversationShare.findFirst({
+ where: {
+ conversationId,
+ revokedAt: null,
+ OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
+ },
+ select: { createdAt: true, expiresAt: true },
+ });
+
+ return {
+ enabled: share !== null,
+ createdAt: share?.createdAt.toISOString() ?? null,
+ expiresAt: share?.expiresAt?.toISOString() ?? null,
+ };
+ }
+
+ async create(conversationId: string, userId: string) {
+ const token = randomBytes(32).toString("base64url");
+ const tokenHash = conversationShareTokenHash(token);
+
+ const created = await this.db.$transaction(async (tx) => {
+ if (!(await this.lockOwnedBuilder(tx, conversationId, userId))) {
+ return false;
+ }
+
+ await tx.agentConversationShare.updateMany({
+ where: { conversationId, revokedAt: null },
+ data: { revokedAt: new Date() },
+ });
+
+ await tx.agentConversationShare.create({
+ data: { conversationId, createdById: userId, tokenHash },
+ });
+
+ return true;
+ });
+ if (!created) this.missingBuilder(conversationId);
+
+ return { token };
+ }
+
+ async revoke(conversationId: string, userId: string) {
+ const revoked = await this.db.$transaction(async (tx) => {
+ if (!(await this.lockOwnedBuilder(tx, conversationId, userId))) {
+ return false;
+ }
+
+ await tx.agentConversationShare.updateMany({
+ where: { conversationId, revokedAt: null },
+ data: { revokedAt: new Date() },
+ });
+
+ return true;
+ });
+ if (!revoked) this.missingBuilder(conversationId);
+
+ return { id: conversationId };
+ }
+
+ async resolve(token: string, userId: string) {
+ await this.assertWorkspaceMember(userId);
+
+ const share = await this.db.agentConversationShare.findFirst({
+ where: {
+ tokenHash: conversationShareTokenHash(token),
+ revokedAt: null,
+ OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
+ conversation: { kind: "BUILDER" },
+ },
+ select: {
+ conversation: {
+ select: {
+ id: true,
+ title: true,
+ sessionId: true,
+ lastMessageAt: true,
+ user: { select: { name: true } },
+ agent: { select: { id: true, name: true, status: true } },
+ builderArtifacts: {
+ orderBy: [{ createdAt: "desc" }, { revision: "desc" }],
+ take: 100,
+ select: {
+ id: true,
+ versionId: true,
+ path: true,
+ language: true,
+ content: true,
+ previousContent: true,
+ revision: true,
+ status: true,
+ createdAt: true,
+ },
+ },
+ submissions: {
+ orderBy: { createdAt: "asc" },
+ select: {
+ id: true,
+ commandType: true,
+ message: true,
+ status: true,
+ errorMessage: true,
+ createdAt: true,
+ attachments: {
+ orderBy: { position: "asc" },
+ select: {
+ id: true,
+ name: true,
+ mediaType: true,
+ size: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!share) {
+ throw new NotFoundException("That shared conversation is unavailable.");
+ }
+
+ const { conversation } = share;
+ const events = conversation.sessionId
+ ? await this.db.agentEvent.findMany({
+ where: { sessionId: conversation.sessionId },
+ orderBy: [{ emittedAt: "desc" }, { id: "desc" }],
+ take: 5000,
+ select: { id: true, type: true, data: true, emittedAt: true },
+ })
+ : [];
+
+ return {
+ id: conversation.id,
+ title: conversation.title,
+ ownerName: conversation.user.name,
+ lastMessageAt: conversation.lastMessageAt.toISOString(),
+ agent: conversation.agent,
+ builderArtifacts: conversation.builderArtifacts.map((artifact) => ({
+ ...artifact,
+ createdAt: artifact.createdAt.toISOString(),
+ })),
+ submissions: conversation.submissions.map(
+ ({ attachments, ...submission }) => ({
+ ...submission,
+ message: builderMessageWithAttachments(
+ submission.message,
+ attachments,
+ token,
+ ),
+ createdAt: submission.createdAt.toISOString(),
+ }),
+ ),
+ events: events.reverse().map((event) => ({
+ type: event.type,
+ data: event.data,
+ meta: { id: event.id, at: event.emittedAt.toISOString() },
+ })),
+ };
+ }
+
+ private async ownedBuilder(conversationId: string, userId: string) {
+ const conversation = await this.db.agentConversation.findFirst({
+ where: { id: conversationId, userId, kind: "BUILDER" },
+ select: { id: true },
+ });
+
+ if (!conversation) {
+ this.missingBuilder(conversationId);
+ }
+
+ return conversation;
+ }
+
+ private async lockOwnedBuilder(
+ tx: Prisma.TransactionClient,
+ conversationId: string,
+ userId: string,
+ ): Promise<boolean> {
+ const rows = await tx.$queryRaw<Array<{ id: string }>>`
+ SELECT id
+ FROM "agentConversation"
+ WHERE id = ${conversationId}
+ FOR UPDATE
+ `;
+ if (rows.length === 0) return false;
+
+ return (
+ (await tx.agentConversation.count({
+ where: { id: conversationId, userId, kind: "BUILDER" },
+ })) === 1
+ );
+ }
+
+ private missingBuilder(conversationId: string): never {
+ throw new NotFoundException(
+ `No builder conversation with id ${conversationId}.`,
+ );
+ }
+
+ private async assertWorkspaceMember(userId: string): Promise<void> {
+ const member = await this.db.member.findUnique({
+ where: {
+ organizationId_userId: { organizationId: WORKSPACE_ID, userId },
+ },
+ select: { id: true },
+ });
+
+ if (!member) {
+ throw new ForbiddenException(
+ "This conversation belongs to another team.",
+ );
+ }
+ }
+}
diff --git a/apps/api/src/conversations/conversations.contracts.ts b/apps/api/src/conversations/conversations.contracts.ts
index 5b99ae34..1e8e9ad0 100644
--- a/apps/api/src/conversations/conversations.contracts.ts
+++ b/apps/api/src/conversations/conversations.contracts.ts
@@ -1,23 +1,36 @@
import { z } from "zod";
-export const conversationListInput = z.object({
- contactId: z.string().optional(),
- companyId: z.string().optional(),
- dealId: z.string().optional(),
-});
+const recordShape = {
+ contactId: z.string().trim().min(1).optional(),
+ companyId: z.string().trim().min(1).optional(),
+ dealId: z.string().trim().min(1).optional(),
+};
+
+const hasExactlyOneRecord = (input: {
+ contactId?: string;
+ companyId?: string;
+ dealId?: string;
+}) =>
+ [input.contactId, input.companyId, input.dealId].filter(Boolean).length === 1;
+
+const recordMessage = "Choose exactly one contact, company or deal.";
+
+export const conversationListInput = z
+ .object(recordShape)
+ .refine(hasExactlyOneRecord, { message: recordMessage });
export type ConversationListInput = z.infer<typeof conversationListInput>;
-export const conversationSaveInput = z.object({
- contactId: z.string().optional(),
- companyId: z.string().optional(),
- dealId: z.string().optional(),
- sessionId: z.string(),
- continuationToken: z.string().nullish(),
- streamIndex: z.number().int().min(0).optional(),
- title: z.string().optional(),
- messageCount: z.number().int().min(0).optional(),
-});
+export const conversationSaveInput = z
+ .object({
+ ...recordShape,
+ sessionId: z.string().trim().min(1),
+ continuationToken: z.string().nullish(),
+ streamIndex: z.number().int().min(0).optional(),
+ title: z.string().trim().max(120).optional(),
+ messageCount: z.number().int().min(0).optional(),
+ })
+ .refine(hasExactlyOneRecord, { message: recordMessage });
export type ConversationSaveInput = z.infer<typeof conversationSaveInput>;
@@ -29,3 +42,103 @@ export const conversationEventsInput = z.object({
});
export type ConversationEventsInput = z.infer<typeof conversationEventsInput>;
+
+export const builderResource = z.object({
+ kind: z.enum(["integration", "company", "contact", "deal"]),
+ id: z.string().trim().min(1).max(160),
+ label: z.string().trim().min(1).max(120),
+ detail: z.string().trim().max(160).nullable().optional(),
+ imageUrl: z.url().nullable().optional(),
+});
+
+export const builderAttachment = z
+ .object({
+ name: z.string().trim().min(1).max(180),
+ type: z.string().trim().min(1).max(120),
+ size: z.number().int().min(1).max(2_000_000),
+ contentBase64: z
+ .string()
+ .min(1)
+ .max(2_800_000)
+ .regex(
+ /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/,
+ "Attachment content must be valid base64.",
+ ),
+ })
+ .refine(
+ (attachment) =>
+ decodedBase64Size(attachment.contentBase64) === attachment.size,
+ { message: "Attachment size does not match its content.", path: ["size"] },
+ );
+
+const builderStoredAttachment = z.object({
+ id: z.string().trim().min(1),
+ name: z.string().trim().min(1).max(180),
+ type: z.string().trim().min(1).max(120),
+ size: z.number().int().min(1).max(2_000_000),
+ previewUrl: z.string().nullable().optional(),
+});
+
+const builderPromptShape = {
+ clientRequestId: z.uuid(),
+ commandType: z.enum(["CHAT", "CREATE_AGENT"]).default("CHAT"),
+ message: z.string().trim().min(1).max(20_000),
+ resources: z.array(builderResource).max(20).default([]),
+};
+
+export const builderConversationCreateInput = z.object({
+ ...builderPromptShape,
+ attachments: z.array(builderAttachment).max(5).default([]),
+});
+
+export type BuilderConversationCreateInput = z.infer<
+ typeof builderConversationCreateInput
+>;
+
+export const builderConversationSubmitInput = z.object({
+ ...builderPromptShape,
+ id: z.string().min(1),
+ attachments: z
+ .array(z.union([builderAttachment, builderStoredAttachment]))
+ .max(5)
+ .default([]),
+});
+
+export type BuilderConversationSubmitInput = z.infer<
+ typeof builderConversationSubmitInput
+>;
+
+export const builderQuestionResponseInput = z
+ .object({
+ id: z.string().min(1),
+ clientRequestId: z.uuid(),
+ requestId: z.string().trim().min(1).max(240),
+ optionId: z.string().trim().min(1).max(160).optional(),
+ text: z.string().trim().min(1).max(20_000).optional(),
+ })
+ .refine((input) => Boolean(input.optionId) !== Boolean(input.text), {
+ message: "Choose one option or enter a written answer.",
+ });
+
+export type BuilderQuestionResponseInput = z.infer<
+ typeof builderQuestionResponseInput
+>;
+
+export const sharedConversationInput = z.object({
+ token: z.string().trim().min(32).max(256),
+});
+
+export const builderResourceSearchInput = z.object({
+ q: z.string().trim().max(120).default(""),
+});
+
+export const builderResponseRatingInput = z.object({
+ id: z.string().min(1),
+ messageId: z.string().trim().min(1).max(240),
+ rating: z.enum(["UP", "DOWN"]).nullable(),
+});
+
+function decodedBase64Size(value: string): number {
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
+ return (value.length / 4) * 3 - padding;
+}
diff --git a/apps/api/src/conversations/conversations.module.ts b/apps/api/src/conversations/conversations.module.ts
index 54df59fb..7aaba500 100644
--- a/apps/api/src/conversations/conversations.module.ts
+++ b/apps/api/src/conversations/conversations.module.ts
@@ -1,11 +1,19 @@
import { Module } from "@nestjs/common";
+import { AgentModule } from "../agent/agent.module";
import { TrpcModule } from "../trpc/trpc.module";
+import { ConversationAttachmentsController } from "./conversation-attachments.controller";
+import { ConversationSharingService } from "./conversation-sharing.service";
import { ConversationsRouter } from "./conversations.router";
import { ConversationsService } from "./conversations.service";
@Module({
- imports: [TrpcModule],
- providers: [ConversationsService, ConversationsRouter],
+ imports: [TrpcModule, AgentModule],
+ controllers: [ConversationAttachmentsController],
+ providers: [
+ ConversationsService,
+ ConversationSharingService,
+ ConversationsRouter,
+ ],
exports: [ConversationsService],
})
export class ConversationsModule {}
diff --git a/apps/api/src/conversations/conversations.router.ts b/apps/api/src/conversations/conversations.router.ts
index ac66ba8b..e65987ee 100644
--- a/apps/api/src/conversations/conversations.router.ts
+++ b/apps/api/src/conversations/conversations.router.ts
@@ -10,11 +10,18 @@ import {
import type { z } from "zod";
import type { AuthedTrpcContext } from "../trpc/context.types";
import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import { ConversationSharingService } from "./conversation-sharing.service";
import {
+ builderConversationCreateInput,
+ builderConversationSubmitInput,
+ builderQuestionResponseInput,
+ builderResourceSearchInput,
+ builderResponseRatingInput,
conversationEventsInput,
conversationIdInput,
conversationListInput,
conversationSaveInput,
+ sharedConversationInput,
} from "./conversations.contracts";
import { ConversationsService } from "./conversations.service";
@@ -24,6 +31,8 @@ export class ConversationsRouter {
constructor(
@Inject(ConversationsService)
private readonly conversations: ConversationsService,
+ @Inject(ConversationSharingService)
+ private readonly sharing: ConversationSharingService,
) {}
@Query({ input: conversationListInput })
@@ -34,6 +43,21 @@ export class ConversationsRouter {
return this.conversations.list(input, ctx.user.id);
}
+ @Query()
+ async builderList(@Ctx() ctx: AuthedTrpcContext) {
+ return this.conversations.listBuilder(ctx.user.id);
+ }
+
+ @Query({ input: builderResourceSearchInput })
+ async builderResources(@Ctx() ctx: AuthedTrpcContext, @Input("q") q: string) {
+ return this.conversations.builderResources(q, ctx.user.id);
+ }
+
+ @Query({ input: conversationIdInput })
+ async builderById(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.conversations.builderById(id, ctx.user.id);
+ }
+
@Query({ input: conversationEventsInput })
async events(
@Ctx() ctx: AuthedTrpcContext,
@@ -50,6 +74,63 @@ export class ConversationsRouter {
return this.conversations.save(input, ctx.user.id);
}
+ @Mutation({ input: builderConversationCreateInput })
+ async createBuilder(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof builderConversationCreateInput>,
+ ) {
+ return this.conversations.createBuilder(input, ctx.user.id);
+ }
+
+ @Mutation({ input: builderConversationSubmitInput })
+ async submitBuilder(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof builderConversationSubmitInput>,
+ ) {
+ return this.conversations.submitBuilder(input, ctx.user.id);
+ }
+
+ @Mutation({ input: builderQuestionResponseInput })
+ async answerBuilderQuestion(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof builderQuestionResponseInput>,
+ ) {
+ return this.conversations.answerBuilderQuestion(input, ctx.user.id);
+ }
+
+ @Mutation({ input: builderResponseRatingInput })
+ async rateBuilderResponse(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof builderResponseRatingInput>,
+ ) {
+ return this.conversations.rateBuilderResponse(input, ctx.user.id);
+ }
+
+ @Mutation({ input: conversationIdInput })
+ async markRead(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.conversations.markRead(id, ctx.user.id);
+ }
+
+ @Query({ input: conversationIdInput })
+ async shareStatus(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.sharing.status(id, ctx.user.id);
+ }
+
+ @Mutation({ input: conversationIdInput })
+ async createShare(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.sharing.create(id, ctx.user.id);
+ }
+
+ @Mutation({ input: conversationIdInput })
+ async revokeShare(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.sharing.revoke(id, ctx.user.id);
+ }
+
+ @Query({ input: sharedConversationInput })
+ async shared(@Ctx() ctx: AuthedTrpcContext, @Input("token") token: string) {
+ return this.sharing.resolve(token, ctx.user.id);
+ }
+
@Mutation({ input: conversationIdInput })
async remove(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
return this.conversations.remove(id, ctx.user.id);
diff --git a/apps/api/src/conversations/conversations.service.ts b/apps/api/src/conversations/conversations.service.ts
index c28b7786..55a2665d 100644
--- a/apps/api/src/conversations/conversations.service.ts
+++ b/apps/api/src/conversations/conversations.service.ts
@@ -1,15 +1,23 @@
-import type { Db } from "@crm/db";
-import { CACHE_MANAGER } from "@nestjs/cache-manager";
+import { WORKSPACE_ID } from "@crm/auth";
+import { type Db, type Prisma, Prisma as PrismaNamespace } from "@crm/db";
import {
BadRequestException,
- Inject,
Injectable,
Logger,
NotFoundException,
+ Optional,
} from "@nestjs/common";
-import type { Cache } from "cache-manager";
+import { AgentTriggerService } from "../agent/agent-trigger.service";
import { InjectDatabase } from "../database/database.constants";
+import {
+ builderMessageWithAttachments,
+ isPreviewableImage,
+} from "./conversation-attachments";
+import { conversationShareTokenHash } from "./conversation-share-token";
import type {
+ BuilderConversationCreateInput,
+ BuilderConversationSubmitInput,
+ BuilderQuestionResponseInput,
ConversationEventsInput,
ConversationListInput,
ConversationSaveInput,
@@ -25,10 +33,30 @@ export interface ConversationSummary {
lastMessageAt: string;
}
-const LIST_TTL_MS = 10 * 60_000;
+export interface BuilderConversationSummary {
+ id: string;
+ sessionId: string | null;
+ continuationToken: string | null;
+ streamIndex: number;
+ title: string | null;
+ messageCount: number;
+ lastMessageAt: string;
+ lastAssistantAt: string | null;
+ unread: boolean;
+ state: "working" | "unread" | "deployed" | "idle";
+ agent: {
+ id: string;
+ name: string;
+ status: string;
+ } | null;
+}
-const listKey = (userId: string, recordId: string) =>
- `agent:conversations:${userId}:${recordId}`;
+type ExistingBuilderRequest = {
+ id: string;
+ conversationId: string;
+ submittedById: string;
+ conversation: { id: string; userId: string; kind: string };
+};
@Injectable()
export class ConversationsService {
@@ -36,7 +64,7 @@ export class ConversationsService {
constructor(
@InjectDatabase() private readonly db: Db,
- @Inject(CACHE_MANAGER) private readonly cache: Cache,
+ @Optional() private readonly agent?: AgentTriggerService,
) {}
async list(
@@ -44,12 +72,7 @@ export class ConversationsService {
userId: string,
): Promise<ConversationSummary[]> {
const recordId = this.recordId(input);
- const key = listKey(userId, recordId);
-
- const cached = await this.cache.get<ConversationSummary[]>(key);
- if (cached) return cached;
-
- this.logger.debug({ message: "Conversation list cache miss", recordId });
+ this.logger.debug({ message: "Conversation list read", recordId });
const rows = await this.db.agentConversation.findMany({
where: {
@@ -71,73 +94,795 @@ export class ConversationsService {
},
});
- const summaries = rows.map((row) => ({
+ const summaries = rows.flatMap((row) =>
+ row.sessionId
+ ? [
+ {
+ ...row,
+ sessionId: row.sessionId,
+ lastMessageAt: row.lastMessageAt.toISOString(),
+ },
+ ]
+ : [],
+ );
+
+ return summaries;
+ }
+
+ async listBuilder(userId: string): Promise<BuilderConversationSummary[]> {
+ await this.assertWorkspaceMember(userId);
+ const rows = await this.db.agentConversation.findMany({
+ where: { userId, kind: "BUILDER" },
+ orderBy: { lastMessageAt: "desc" },
+ take: 50,
+ select: {
+ id: true,
+ sessionId: true,
+ continuationToken: true,
+ streamIndex: true,
+ title: true,
+ messageCount: true,
+ lastMessageAt: true,
+ lastAssistantAt: true,
+ lastReadAt: true,
+ agent: { select: { id: true, name: true, status: true } },
+ _count: {
+ select: {
+ submissions: { where: { commandType: "CREATE_AGENT" } },
+ },
+ },
+ submissions: {
+ where: { status: { in: ["PENDING", "SENDING"] } },
+ select: { id: true },
+ take: 1,
+ },
+ },
+ });
+
+ return rows.map((row) => {
+ const unread = Boolean(
+ row.lastAssistantAt &&
+ (!row.lastReadAt || row.lastAssistantAt > row.lastReadAt),
+ );
+ const working =
+ row.submissions.length > 0 ||
+ Boolean(row.sessionId && !row.continuationToken);
+
+ return {
+ id: row.id,
+ sessionId: row.sessionId,
+ continuationToken: row.continuationToken,
+ streamIndex: row.streamIndex,
+ title: row.title,
+ messageCount: row.messageCount,
+ lastMessageAt: row.lastMessageAt.toISOString(),
+ lastAssistantAt: row.lastAssistantAt?.toISOString() ?? null,
+ unread,
+ state:
+ row._count.submissions > 0 && row.agent?.status === "LIVE"
+ ? "deployed"
+ : working
+ ? "working"
+ : unread
+ ? "unread"
+ : "idle",
+ agent: row.agent,
+ };
+ });
+ }
+
+ async builderResources(q: string, userId: string) {
+ await this.assertWorkspaceMember(userId);
+
+ const search = q.trim();
+ const contains = search
+ ? { contains: search, mode: "insensitive" as const }
+ : undefined;
+
+ const [companies, contacts, deals] = await Promise.all([
+ this.db.company.findMany({
+ where: contains ? { name: contains } : undefined,
+ orderBy: { lastActivityAt: { sort: "desc", nulls: "last" } },
+ take: 6,
+ select: { id: true, name: true, domain: true, logoUrl: true },
+ }),
+ this.db.contact.findMany({
+ where: contains
+ ? {
+ OR: [
+ { firstName: contains },
+ { lastName: contains },
+ { email: contains },
+ ],
+ }
+ : undefined,
+ orderBy: { lastActivityAt: { sort: "desc", nulls: "last" } },
+ take: 6,
+ select: {
+ id: true,
+ firstName: true,
+ lastName: true,
+ email: true,
+ imageUrl: true,
+ company: { select: { name: true } },
+ },
+ }),
+ this.db.deal.findMany({
+ where: contains ? { name: contains } : undefined,
+ orderBy: { lastActivityAt: { sort: "desc", nulls: "last" } },
+ take: 6,
+ select: {
+ id: true,
+ name: true,
+ company: { select: { name: true, logoUrl: true } },
+ },
+ }),
+ ]);
+
+ return [
+ ...companies.map((company) => ({
+ kind: "company" as const,
+ id: company.id,
+ label: company.name,
+ detail: company.domain,
+ imageUrl: company.logoUrl,
+ })),
+ ...contacts.map((contact) => ({
+ kind: "contact" as const,
+ id: contact.id,
+ label: [contact.firstName, contact.lastName].filter(Boolean).join(" "),
+ detail: contact.company?.name ?? contact.email,
+ imageUrl: contact.imageUrl,
+ })),
+ ...deals.map((deal) => ({
+ kind: "deal" as const,
+ id: deal.id,
+ label: deal.name,
+ detail: deal.company.name,
+ imageUrl: deal.company.logoUrl,
+ })),
+ ];
+ }
+
+ async builderById(id: string, userId: string) {
+ await this.assertWorkspaceMember(userId);
+ const row = await this.db.agentConversation.findFirst({
+ where: { id, userId, kind: "BUILDER" },
+ select: {
+ id: true,
+ sessionId: true,
+ continuationToken: true,
+ streamIndex: true,
+ title: true,
+ messageCount: true,
+ lastMessageAt: true,
+ lastAssistantAt: true,
+ lastReadAt: true,
+ agent: {
+ select: {
+ id: true,
+ name: true,
+ description: true,
+ status: true,
+ createdBy: { select: { id: true, name: true } },
+ currentVersion: {
+ select: {
+ id: true,
+ number: true,
+ status: true,
+ manifest: true,
+ modelId: true,
+ sandboxPolicy: true,
+ deployedAt: true,
+ },
+ },
+ triggers: {
+ orderBy: { createdAt: "asc" },
+ select: {
+ id: true,
+ type: true,
+ name: true,
+ config: true,
+ enabled: true,
+ nextRunAt: true,
+ },
+ },
+ },
+ },
+ createdVersions: {
+ orderBy: { number: "desc" },
+ take: 1,
+ select: {
+ id: true,
+ number: true,
+ status: true,
+ instructions: true,
+ manifest: true,
+ modelId: true,
+ sandboxPolicy: true,
+ validation: true,
+ createdAt: true,
+ },
+ },
+ builderArtifacts: {
+ orderBy: [{ createdAt: "desc" }, { revision: "desc" }],
+ take: 100,
+ select: {
+ id: true,
+ versionId: true,
+ path: true,
+ language: true,
+ content: true,
+ previousContent: true,
+ revision: true,
+ status: true,
+ createdAt: true,
+ },
+ },
+ feedback: {
+ where: { userId },
+ select: { messageId: true, rating: true },
+ },
+ submissions: {
+ orderBy: { createdAt: "asc" },
+ select: {
+ id: true,
+ clientRequestId: true,
+ commandType: true,
+ message: true,
+ status: true,
+ errorCode: true,
+ errorMessage: true,
+ createdAt: true,
+ sentAt: true,
+ acceptedAt: true,
+ attachments: {
+ orderBy: { position: "asc" },
+ select: {
+ id: true,
+ name: true,
+ mediaType: true,
+ size: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!row) {
+ throw new NotFoundException(`No builder conversation with id ${id}.`);
+ }
+
+ return {
...row,
lastMessageAt: row.lastMessageAt.toISOString(),
- }));
+ lastAssistantAt: row.lastAssistantAt?.toISOString() ?? null,
+ lastReadAt: row.lastReadAt?.toISOString() ?? null,
+ agent: row.agent
+ ? {
+ ...row.agent,
+ currentVersion: row.agent.currentVersion
+ ? {
+ ...row.agent.currentVersion,
+ deployedAt:
+ row.agent.currentVersion.deployedAt?.toISOString() ?? null,
+ }
+ : null,
+ triggers: row.agent.triggers.map((trigger) => ({
+ ...trigger,
+ nextRunAt: trigger.nextRunAt?.toISOString() ?? null,
+ })),
+ }
+ : null,
+ createdVersions: row.createdVersions.map((version) => ({
+ ...version,
+ createdAt: version.createdAt.toISOString(),
+ })),
+ builderArtifacts: row.builderArtifacts.map((artifact) => ({
+ ...artifact,
+ createdAt: artifact.createdAt.toISOString(),
+ })),
+ submissions: row.submissions.map(({ attachments, ...submission }) => ({
+ ...submission,
+ message: builderMessageWithAttachments(submission.message, attachments),
+ createdAt: submission.createdAt.toISOString(),
+ sentAt: submission.sentAt?.toISOString() ?? null,
+ acceptedAt: submission.acceptedAt?.toISOString() ?? null,
+ })),
+ };
+ }
+
+ async createBuilder(
+ input: BuilderConversationCreateInput,
+ userId: string,
+ ): Promise<{ id: string }> {
+ await this.assertWorkspaceMember(userId);
+ const existing = await this.requestByClientId(input.clientRequestId);
+
+ if (existing) {
+ return this.replayBuilderCreation(existing, userId);
+ }
- await this.cache.set(key, summaries, LIST_TTL_MS);
+ const now = new Date();
+ try {
+ const conversation = await this.db.agentConversation.create({
+ data: {
+ kind: "BUILDER",
+ userId,
+ title: null,
+ lastReadAt: now,
+ lastMessageAt: now,
+ submissions: {
+ create: {
+ submittedById: userId,
+ clientRequestId: input.clientRequestId,
+ commandType: input.commandType,
+ message: this.builderMessage(input),
+ attachments: {
+ create: this.attachmentWrites(input.attachments),
+ },
+ },
+ },
+ },
+ select: { id: true },
+ });
- return summaries;
+ this.agent?.builderConversationQueued();
+ return conversation;
+ } catch (error) {
+ if (!isUniqueConstraint(error)) throw error;
+ const winner = await this.requestByClientId(input.clientRequestId);
+ if (!winner) throw error;
+ return this.replayBuilderCreation(winner, userId);
+ }
}
- async save(
- input: ConversationSaveInput,
+ async submitBuilder(
+ input: BuilderConversationSubmitInput,
userId: string,
): Promise<{ id: string }> {
- const recordId = this.recordId(input);
+ await this.assertWorkspaceMember(userId);
+ const existing = await this.requestByClientId(input.clientRequestId);
- const conversation = await this.db.agentConversation.upsert({
- where: { sessionId: input.sessionId },
- create: {
- sessionId: input.sessionId,
- continuationToken: input.continuationToken ?? null,
- streamIndex: input.streamIndex ?? 0,
- title: input.title?.slice(0, 120) ?? null,
- messageCount: input.messageCount ?? 0,
+ if (existing) {
+ return this.replayBuilderSubmission(existing, input.id, userId);
+ }
+
+ const conversation = await this.db.agentConversation.findFirst({
+ where: { id: input.id, userId, kind: "BUILDER" },
+ select: { id: true },
+ });
+
+ if (!conversation) {
+ throw new NotFoundException(
+ `No builder conversation with id ${input.id}.`,
+ );
+ }
+
+ try {
+ const attachmentWrites = await this.submissionAttachmentWrites(
+ input,
userId,
- contactId: input.contactId ?? null,
- companyId: input.companyId ?? null,
- dealId: input.dealId ?? null,
- },
- update: {
- continuationToken: input.continuationToken ?? null,
- streamIndex: input.streamIndex ?? 0,
- messageCount: input.messageCount ?? 0,
- lastMessageAt: new Date(),
+ );
+ const submission = await this.db.$transaction(async (tx) => {
+ const created = await tx.agentConversationSubmission.create({
+ data: {
+ conversationId: input.id,
+ submittedById: userId,
+ clientRequestId: input.clientRequestId,
+ commandType: input.commandType,
+ message: this.builderMessage(input),
+ attachments: {
+ create: attachmentWrites,
+ },
+ },
+ select: { id: true },
+ });
+
+ await tx.agentConversation.update({
+ where: { id: input.id },
+ data: { lastMessageAt: new Date(), lastReadAt: new Date() },
+ });
+
+ return created;
+ });
+
+ this.agent?.builderConversationQueued();
+ return submission;
+ } catch (error) {
+ if (!isUniqueConstraint(error)) throw error;
+ const winner = await this.requestByClientId(input.clientRequestId);
+ if (!winner) throw error;
+ return this.replayBuilderSubmission(winner, input.id, userId);
+ }
+ }
+
+ async answerBuilderQuestion(
+ input: BuilderQuestionResponseInput,
+ userId: string,
+ ): Promise<{ id: string }> {
+ await this.assertWorkspaceMember(userId);
+ const existing = await this.requestByClientId(input.clientRequestId);
+
+ if (existing) {
+ return this.replayBuilderSubmission(existing, input.id, userId);
+ }
+
+ const conversation = await this.db.agentConversation.findFirst({
+ where: { id: input.id, userId, kind: "BUILDER" },
+ select: { id: true, sessionId: true, continuationToken: true },
+ });
+
+ if (!conversation) {
+ throw new NotFoundException(
+ `No builder conversation with id ${input.id}.`,
+ );
+ }
+
+ if (!conversation.sessionId || !conversation.continuationToken) {
+ throw new BadRequestException(
+ "The agent is no longer waiting for that answer.",
+ );
+ }
+
+ const boundary = await this.db.agentEvent.findFirst({
+ where: {
+ sessionId: conversation.sessionId,
+ type: {
+ in: [
+ "input.requested",
+ "message.received",
+ "turn.cancelled",
+ "session.completed",
+ "session.failed",
+ ],
+ },
},
- select: { id: true, userId: true },
+ orderBy: [{ emittedAt: "desc" }, { id: "desc" }],
+ select: { type: true, data: true },
});
- if (conversation.userId !== userId) {
+ if (boundary?.type !== "input.requested") {
+ throw new BadRequestException(
+ "The agent is no longer waiting for that answer.",
+ );
+ }
+
+ const requests = arrayOf(recordOf(boundary.data).requests).map(recordOf);
+ const question = requests.find(
+ (request) =>
+ request.kind === "question" && request.requestId === input.requestId,
+ );
+
+ if (!question) {
+ throw new BadRequestException(
+ "That follow-up question is no longer active.",
+ );
+ }
+
+ const options = arrayOf(question.options).map(recordOf);
+ const selected = input.optionId
+ ? options.find((option) => option.id === input.optionId)
+ : null;
+
+ if (input.optionId && !selected) {
throw new BadRequestException(
- "That conversation belongs to someone else.",
+ "That answer is not available for this question.",
);
}
- await this.cache.del(listKey(userId, recordId));
+ const acceptsText =
+ question.allowFreeform === true ||
+ question.display === "text" ||
+ options.length === 0;
+ if (input.text && !acceptsText) {
+ throw new BadRequestException(
+ "Choose one of the available answers for this question.",
+ );
+ }
+
+ const answer = input.optionId ?? input.text;
+ if (!answer) {
+ throw new BadRequestException("Choose an answer before submitting.");
+ }
+
+ const displayText =
+ typeof selected?.label === "string" ? selected.label : answer;
+ try {
+ const submission = await this.db.$transaction(async (tx) => {
+ const created = await tx.agentConversationSubmission.create({
+ data: {
+ conversationId: input.id,
+ submittedById: userId,
+ clientRequestId: input.clientRequestId,
+ inputRequestId: input.requestId,
+ commandType: "CHAT",
+ message: {
+ text: displayText,
+ resources: [],
+ attachments: [],
+ inputResponse: { requestId: input.requestId, answer },
+ },
+ },
+ select: { id: true },
+ });
+
+ await tx.agentConversation.update({
+ where: { id: input.id },
+ data: { lastMessageAt: new Date(), lastReadAt: new Date() },
+ });
+
+ return created;
+ });
+
+ this.agent?.builderConversationQueued();
+ return submission;
+ } catch (error) {
+ if (!isUniqueConstraint(error)) throw error;
- return { id: conversation.id };
+ const winner = await this.requestByClientId(input.clientRequestId);
+ if (winner) {
+ return this.replayBuilderSubmission(winner, input.id, userId);
+ }
+
+ const answered = await this.db.agentConversationSubmission.findFirst({
+ where: {
+ conversationId: input.id,
+ inputRequestId: input.requestId,
+ },
+ select: { id: true },
+ });
+ if (answered) {
+ throw new BadRequestException(
+ "That follow-up question has already been answered.",
+ );
+ }
+
+ throw error;
+ }
+ }
+
+ async markRead(id: string, userId: string): Promise<{ id: string }> {
+ await this.assertWorkspaceMember(userId);
+ const updated = await this.db.agentConversation.updateMany({
+ where: { id, userId, kind: "BUILDER" },
+ data: { lastReadAt: new Date() },
+ });
+
+ if (updated.count === 0) {
+ throw new NotFoundException(`No builder conversation with id ${id}.`);
+ }
+
+ return { id };
+ }
+
+ async attachment(
+ id: string,
+ userId: string,
+ shareToken?: string,
+ ): Promise<{
+ name: string;
+ mediaType: string;
+ content: Uint8Array;
+ previewable: boolean;
+ }> {
+ await this.assertWorkspaceMember(userId);
+ const share = shareToken?.trim();
+ const row = await this.db.agentConversationAttachment.findFirst({
+ where: {
+ id,
+ submission: {
+ conversation: {
+ kind: "BUILDER",
+ OR: [
+ { userId },
+ ...(share
+ ? [
+ {
+ shares: {
+ some: {
+ tokenHash: conversationShareTokenHash(share),
+ revokedAt: null,
+ OR: [
+ { expiresAt: null },
+ { expiresAt: { gt: new Date() } },
+ ],
+ },
+ },
+ },
+ ]
+ : []),
+ ],
+ },
+ },
+ },
+ select: { name: true, mediaType: true, content: true },
+ });
+
+ if (!row) {
+ throw new NotFoundException("That attachment is unavailable.");
+ }
+
+ return {
+ ...row,
+ previewable: isPreviewableImage(row.mediaType),
+ };
+ }
+
+ async rateBuilderResponse(
+ input: { id: string; messageId: string; rating: "UP" | "DOWN" | null },
+ userId: string,
+ ) {
+ await this.assertWorkspaceMember(userId);
+ const conversation = await this.db.agentConversation.findFirst({
+ where: { id: input.id, userId, kind: "BUILDER" },
+ select: { id: true },
+ });
+
+ if (!conversation) {
+ throw new NotFoundException(
+ `No builder conversation with id ${input.id}.`,
+ );
+ }
+
+ const key = {
+ conversationId_userId_messageId: {
+ conversationId: input.id,
+ userId,
+ messageId: input.messageId,
+ },
+ };
+
+ if (!input.rating) {
+ await this.db.agentConversationFeedback.deleteMany({
+ where: key.conversationId_userId_messageId,
+ });
+ return { id: input.messageId, rating: null };
+ }
+
+ await this.db.agentConversationFeedback.upsert({
+ where: key,
+ create: {
+ conversationId: input.id,
+ userId,
+ messageId: input.messageId,
+ rating: input.rating,
+ },
+ update: { rating: input.rating },
+ });
+
+ return { id: input.messageId, rating: input.rating };
+ }
+
+ async save(
+ input: ConversationSaveInput,
+ userId: string,
+ ): Promise<{ id: string }> {
+ const recordId = this.recordId(input);
+ const updateExisting = async (existing: {
+ id: string;
+ kind: string;
+ userId: string;
+ contactId: string | null;
+ companyId: string | null;
+ dealId: string | null;
+ }) => {
+ if (existing.userId !== userId || existing.kind !== "RECORD") {
+ throw new NotFoundException(
+ `No record conversation with session ${input.sessionId}.`,
+ );
+ }
+
+ const existingRecordId =
+ existing.contactId ?? existing.companyId ?? existing.dealId;
+ if (existingRecordId !== recordId) {
+ throw new BadRequestException(
+ "A conversation cannot be moved to another CRM record.",
+ );
+ }
+
+ const updated = await this.db.agentConversation.updateMany({
+ where: {
+ id: existing.id,
+ kind: "RECORD",
+ userId,
+ contactId: input.contactId ?? null,
+ companyId: input.companyId ?? null,
+ dealId: input.dealId ?? null,
+ },
+ data: {
+ continuationToken: input.continuationToken ?? null,
+ streamIndex: input.streamIndex ?? 0,
+ messageCount: input.messageCount ?? 0,
+ lastMessageAt: new Date(),
+ },
+ });
+
+ if (updated.count !== 1) {
+ throw new NotFoundException(
+ `No record conversation with session ${input.sessionId}.`,
+ );
+ }
+
+ return { id: existing.id };
+ };
+
+ const existing = await this.db.agentConversation.findUnique({
+ where: { sessionId: input.sessionId },
+ select: {
+ id: true,
+ kind: true,
+ userId: true,
+ contactId: true,
+ companyId: true,
+ dealId: true,
+ },
+ });
+ let conversation: { id: string };
+
+ if (existing) {
+ conversation = await updateExisting(existing);
+ } else {
+ try {
+ conversation = await this.db.agentConversation.create({
+ data: {
+ sessionId: input.sessionId,
+ continuationToken: input.continuationToken ?? null,
+ streamIndex: input.streamIndex ?? 0,
+ title: input.title?.slice(0, 120) ?? null,
+ messageCount: input.messageCount ?? 0,
+ userId,
+ contactId: input.contactId ?? null,
+ companyId: input.companyId ?? null,
+ dealId: input.dealId ?? null,
+ },
+ select: { id: true },
+ });
+ } catch (error) {
+ if (!isUniqueConstraint(error)) throw error;
+ const winner = await this.db.agentConversation.findUnique({
+ where: { sessionId: input.sessionId },
+ select: {
+ id: true,
+ kind: true,
+ userId: true,
+ contactId: true,
+ companyId: true,
+ dealId: true,
+ },
+ });
+ if (!winner) throw error;
+ conversation = await updateExisting(winner);
+ }
+ }
+
+ return conversation;
}
async events(input: ConversationEventsInput, userId: string) {
const conversation = await this.db.agentConversation.findUnique({
where: { id: input.id },
- select: { sessionId: true, userId: true },
+ select: { kind: true, sessionId: true, userId: true },
});
if (!conversation || conversation.userId !== userId) {
throw new NotFoundException(`No conversation with id ${input.id}.`);
}
+ if (conversation.kind === "BUILDER") {
+ await this.assertWorkspaceMember(userId);
+ }
+
+ if (!conversation.sessionId) return [];
const events = await this.db.agentEvent.findMany({
where: { sessionId: conversation.sessionId },
- orderBy: { emittedAt: "asc" },
+ orderBy: [{ emittedAt: "desc" }, { id: "desc" }],
take: input.limit,
select: { id: true, type: true, data: true, emittedAt: true },
});
- return events.map((event) => ({
+ return events.reverse().map((event) => ({
type: event.type,
data: event.data,
meta: { id: event.id, at: event.emittedAt.toISOString() },
@@ -149,10 +894,8 @@ export class ConversationsService {
where: { id },
select: {
id: true,
+ kind: true,
userId: true,
- contactId: true,
- companyId: true,
- dealId: true,
sessionId: true,
},
});
@@ -160,23 +903,22 @@ export class ConversationsService {
if (!conversation || conversation.userId !== userId) {
throw new NotFoundException(`No conversation with id ${id}.`);
}
+ if (conversation.kind === "BUILDER") {
+ await this.assertWorkspaceMember(userId);
+ }
- await this.db.$transaction([
- this.db.agentEvent.deleteMany({
- where: { sessionId: conversation.sessionId },
- }),
- this.db.agentConversation.delete({ where: { id } }),
- ]);
+ await this.db.$transaction(async (tx) => {
+ await tx.agentBuilderArtifact.deleteMany({
+ where: { conversationId: id, versionId: null },
+ });
+ if (conversation.sessionId) {
+ await tx.agentEvent.deleteMany({
+ where: { sessionId: conversation.sessionId },
+ });
+ }
- await this.cache.del(
- listKey(
- userId,
- conversation.contactId ??
- conversation.companyId ??
- conversation.dealId ??
- "",
- ),
- );
+ await tx.agentConversation.delete({ where: { id } });
+ });
this.logger.log({ message: "Conversation removed", conversationId: id });
@@ -188,14 +930,180 @@ export class ConversationsService {
companyId?: string;
dealId?: string;
}): string {
- const recordId = input.contactId ?? input.companyId ?? input.dealId;
+ const recordIds = [input.contactId, input.companyId, input.dealId].filter(
+ (recordId): recordId is string => Boolean(recordId),
+ );
+ const [recordId] = recordIds;
- if (!recordId) {
+ if (!recordId || recordIds.length !== 1) {
throw new BadRequestException(
- "A conversation belongs to a contact, a company or a deal.",
+ "Choose exactly one contact, company or deal.",
);
}
return recordId;
}
+
+ private builderMessage(input: {
+ message: string;
+ resources: BuilderConversationCreateInput["resources"];
+ attachments:
+ | BuilderConversationCreateInput["attachments"]
+ | BuilderConversationSubmitInput["attachments"];
+ }): Prisma.InputJsonValue {
+ return {
+ text: input.message,
+ resources: input.resources,
+ attachments: input.attachments.map(({ name, type, size }) => ({
+ name,
+ type,
+ size,
+ })),
+ };
+ }
+
+ private attachmentWrites(
+ attachments: BuilderConversationCreateInput["attachments"],
+ ) {
+ return attachments.map((attachment, position) => ({
+ name: attachment.name,
+ mediaType: attachment.type,
+ size: attachment.size,
+ content: Buffer.from(attachment.contentBase64, "base64"),
+ position,
+ }));
+ }
+
+ private async submissionAttachmentWrites(
+ input: BuilderConversationSubmitInput,
+ userId: string,
+ ) {
+ const referencedIds = input.attachments.flatMap((attachment) =>
+ "contentBase64" in attachment ? [] : [attachment.id],
+ );
+ const referenced =
+ referencedIds.length > 0
+ ? await this.db.agentConversationAttachment.findMany({
+ where: {
+ id: { in: referencedIds },
+ submission: {
+ conversation: { id: input.id, userId, kind: "BUILDER" },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ mediaType: true,
+ size: true,
+ content: true,
+ },
+ })
+ : [];
+ const referencedById = new Map(referenced.map((row) => [row.id, row]));
+
+ if (referencedIds.some((id) => !referencedById.has(id))) {
+ throw new BadRequestException(
+ "One or more attachments are no longer available.",
+ );
+ }
+
+ return input.attachments.map((attachment, position) => {
+ if ("contentBase64" in attachment) {
+ return {
+ name: attachment.name,
+ mediaType: attachment.type,
+ size: attachment.size,
+ content: Buffer.from(attachment.contentBase64, "base64"),
+ position,
+ };
+ }
+
+ const stored = referencedById.get(attachment.id);
+ if (!stored) {
+ throw new BadRequestException(
+ "One or more attachments are no longer available.",
+ );
+ }
+ return {
+ name: stored.name,
+ mediaType: stored.mediaType,
+ size: stored.size,
+ content: stored.content,
+ position,
+ };
+ });
+ }
+
+ private async assertWorkspaceMember(userId: string): Promise<void> {
+ const member = await this.db.member.findUnique({
+ where: {
+ organizationId_userId: { organizationId: WORKSPACE_ID, userId },
+ },
+ select: { id: true },
+ });
+
+ if (!member) {
+ throw new NotFoundException("No workspace membership was found.");
+ }
+ }
+
+ private requestByClientId(
+ clientRequestId: string,
+ ): Promise<ExistingBuilderRequest | null> {
+ return this.db.agentConversationSubmission.findUnique({
+ where: { clientRequestId },
+ select: {
+ id: true,
+ conversationId: true,
+ submittedById: true,
+ conversation: { select: { id: true, userId: true, kind: true } },
+ },
+ });
+ }
+
+ private replayBuilderCreation(
+ existing: ExistingBuilderRequest,
+ userId: string,
+ ): { id: string } {
+ if (
+ existing.conversation.userId !== userId ||
+ existing.conversation.kind !== "BUILDER"
+ ) {
+ throw new BadRequestException("That request has already been used.");
+ }
+
+ return { id: existing.conversation.id };
+ }
+
+ private replayBuilderSubmission(
+ existing: ExistingBuilderRequest,
+ conversationId: string,
+ userId: string,
+ ): { id: string } {
+ if (
+ existing.conversationId !== conversationId ||
+ existing.submittedById !== userId
+ ) {
+ throw new BadRequestException("That request has already been used.");
+ }
+
+ return { id: existing.id };
+ }
+}
+
+function isUniqueConstraint(error: unknown): boolean {
+ return (
+ error instanceof PrismaNamespace.PrismaClientKnownRequestError &&
+ error.code === "P2002"
+ );
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+function arrayOf(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
}
diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.ts
index 6b3b7271..695f1d6b 100644
--- a/apps/api/src/generated/server.ts
+++ b/apps/api/src/generated/server.ts
@@ -14,9 +14,10 @@ import { z } from "zod";
const t = initTRPC.create();
const publicProcedure = t.procedure;
import { timelineInput, timelineCountsInput, myTasksInput, activityCreateInput, completeInput } from "../activities/activities.contracts";
+import { agentIdInput, agentHistoryInput, agentUpdateInput, agentDeployInput, agentRunNowInput } from "../agent/agents.contracts";
import { companyListInput, companyIdInput, companyOptionsInput, companyCreateInput, companyUpdateArgs, companyBulkOwnerInput, companyBulkInput, setPrimaryContactInput } from "../companies/companies.contracts";
import { contactListInput, contactIdInput, contactCreateInput, contactUpdateArgs, contactBulkOwnerInput, contactBulkCompanyInput, contactBulkInput, factDecisionInput } from "../contacts/contacts.contracts";
-import { conversationListInput, conversationEventsInput, conversationSaveInput, conversationIdInput } from "../conversations/conversations.contracts";
+import { conversationListInput, builderResourceSearchInput, conversationIdInput, conversationEventsInput, conversationSaveInput, builderConversationCreateInput, builderConversationSubmitInput, builderQuestionResponseInput, builderResponseRatingInput, sharedConversationInput } from "../conversations/conversations.contracts";
import { setReportingCurrencyInput, setManualRateInput, removeManualRateInput } from "../currency/currency.contracts";
import { dashboardSummaryInput } from "../dashboard/dashboard.contracts";
import { dealListInput, dealIdInput, dealCreateInput, dealUpdateArgs, setStageInput, dealContactsInput, dealAttachContactInput, dealDetachContactInput, dealContactRoleInput, dealBulkOwnerInput, dealBulkStageInput, dealBulkInput } from "../deals/deals.contracts";
@@ -27,6 +28,7 @@ import { setAgentModelInput, setResearchKeyInput } from "../settings/settings.co
import { ssoProviderListInput, registerSsoProviderInput, deleteSsoProviderInput } from "../sso/sso.contracts";
import { memberListInput, updateWorkspaceInput, setMemberRoleInput } from "../workspace/workspace.contracts";
import type { ActivitiesRouter } from "../activities/activities.router";
+import type { AgentsRouter } from "../agent/agents.router";
import type { CompaniesRouter } from "../companies/companies.router";
import type { ContactsRouter } from "../contacts/contacts.router";
import type { ConversationsRouter } from "../conversations/conversations.router";
@@ -60,6 +62,43 @@ const appRouter = t.router({
.input(completeInput)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ActivitiesRouter["complete"]>>)
}),
+ agents: t.router({
+ list: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["list"]>>),
+ byId: publicProcedure
+ .input(agentIdInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["byId"]>>),
+ history: publicProcedure
+ .input(agentHistoryInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["history"]>>),
+ activity: publicProcedure
+ .input(agentHistoryInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["activity"]>>),
+ update: publicProcedure
+ .input(agentUpdateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["update"]>>),
+ deploy: publicProcedure
+ .input(agentDeployInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["deploy"]>>),
+ pause: publicProcedure
+ .input(agentIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["pause"]>>),
+ resume: publicProcedure
+ .input(agentIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["resume"]>>),
+ archive: publicProcedure
+ .input(agentIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["archive"]>>),
+ restore: publicProcedure
+ .input(agentIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["restore"]>>),
+ remove: publicProcedure
+ .input(agentIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["remove"]>>),
+ runNow: publicProcedure
+ .input(agentRunNowInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<AgentsRouter["runNow"]>>)
+ }),
companies: t.router({
list: publicProcedure
.input(companyListInput)
@@ -137,12 +176,47 @@ const appRouter = t.router({
list: publicProcedure
.input(conversationListInput)
.query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["list"]>>),
+ builderList: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["builderList"]>>),
+ builderResources: publicProcedure
+ .input(builderResourceSearchInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["builderResources"]>>),
+ builderById: publicProcedure
+ .input(conversationIdInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["builderById"]>>),
events: publicProcedure
.input(conversationEventsInput)
.query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["events"]>>),
save: publicProcedure
.input(conversationSaveInput)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["save"]>>),
+ createBuilder: publicProcedure
+ .input(builderConversationCreateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["createBuilder"]>>),
+ submitBuilder: publicProcedure
+ .input(builderConversationSubmitInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["submitBuilder"]>>),
+ answerBuilderQuestion: publicProcedure
+ .input(builderQuestionResponseInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["answerBuilderQuestion"]>>),
+ rateBuilderResponse: publicProcedure
+ .input(builderResponseRatingInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["rateBuilderResponse"]>>),
+ markRead: publicProcedure
+ .input(conversationIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["markRead"]>>),
+ shareStatus: publicProcedure
+ .input(conversationIdInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["shareStatus"]>>),
+ createShare: publicProcedure
+ .input(conversationIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["createShare"]>>),
+ revokeShare: publicProcedure
+ .input(conversationIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["revokeShare"]>>),
+ shared: publicProcedure
+ .input(sharedConversationInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["shared"]>>),
remove: publicProcedure
.input(conversationIdInput)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ConversationsRouter["remove"]>>)
diff --git a/apps/api/src/workspace/workspace.contracts.ts b/apps/api/src/workspace/workspace.contracts.ts
index a79a53da..55d57784 100644
--- a/apps/api/src/workspace/workspace.contracts.ts
+++ b/apps/api/src/workspace/workspace.contracts.ts
@@ -1,4 +1,5 @@
import { WORKSPACE_ROLES } from "@crm/auth";
+import { MAX_SLUG } from "@crm/db/workspace";
import { z } from "zod";
import { listInput } from "../trpc/list-input";
@@ -11,6 +12,13 @@ export type MemberListInput = z.infer<typeof memberListInput>;
export const updateWorkspaceInput = z.object({
name: z.string().trim().min(1).max(120),
website: z.string().trim().min(1).max(255),
+ slug: z
+ .string()
+ .trim()
+ .min(1)
+ .max(MAX_SLUG)
+ .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
+ .optional(),
});
export const setMemberRoleInput = z.object({
diff --git a/apps/api/src/workspace/workspace.service.ts b/apps/api/src/workspace/workspace.service.ts
index bce1d687..505a0a10 100644
--- a/apps/api/src/workspace/workspace.service.ts
+++ b/apps/api/src/workspace/workspace.service.ts
@@ -144,7 +144,7 @@ export class WorkspaceService {
where: { id: WORKSPACE_ID },
data: {
name: input.name,
- slug: workspaceSlug(input.name),
+ slug: workspaceSlug(input.slug ?? input.name),
website,
metadata: markOnboarded(before?.metadata ?? null, new Date()),
},
diff --git a/apps/api/test/agent-delete.spec.ts b/apps/api/test/agent-delete.spec.ts
new file mode 100644
index 00000000..ed897915
--- /dev/null
+++ b/apps/api/test/agent-delete.spec.ts
@@ -0,0 +1,264 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { DEFAULT_WORKSPACE_NAME, WORKSPACE_ID } from "@crm/auth";
+import { db } from "@crm/db";
+import { workspaceSlug } from "@crm/db/workspace";
+import { AgentAccessService } from "../src/agent/agent-access.service";
+import { AgentDefinitionsService } from "../src/agent/agent-definitions.service";
+
+const suffix = crypto.randomUUID();
+const userId = `agent-delete-user-${suffix}`;
+const memberId = `agent-delete-member-${suffix}`;
+const idempotencyPrefix = `agent-delete-${suffix}`;
+
+const access = new AgentAccessService(db);
+const agents = new AgentDefinitionsService(db, access);
+
+let agentId: string;
+let versionId: string;
+let triggerId: string;
+let queuedRunId: string;
+let waitingRunId: string;
+let runningRunId: string;
+let deliveryRunId: string;
+
+async function clean() {
+ if (agentId) {
+ await db.agentRunEvent.deleteMany({ where: { run: { agentId } } });
+ await db.agentAction.deleteMany({ where: { agentId } });
+ await db.agentAuditEvent.deleteMany({ where: { agentId } });
+ await db.agentRun.deleteMany({ where: { agentId } });
+ await db.agentTrigger.deleteMany({ where: { agentId } });
+ await db.agentDefinition.updateMany({
+ where: { id: agentId },
+ data: { currentVersionId: null },
+ });
+ await db.agentVersion.deleteMany({ where: { agentId } });
+ await db.agentDefinition.deleteMany({ where: { id: agentId } });
+ }
+
+ await db.member.deleteMany({ where: { id: memberId } });
+ await db.user.deleteMany({ where: { id: userId } });
+}
+
+beforeAll(async () => {
+ await db.organization.upsert({
+ where: { id: WORKSPACE_ID },
+ update: {},
+ create: {
+ id: WORKSPACE_ID,
+ name: DEFAULT_WORKSPACE_NAME,
+ slug: workspaceSlug(DEFAULT_WORKSPACE_NAME),
+ createdAt: new Date(),
+ },
+ });
+ await db.user.create({
+ data: {
+ id: userId,
+ name: "Agent Delete Test",
+ email: `${userId}@example.test`,
+ },
+ });
+ await db.member.create({
+ data: {
+ id: memberId,
+ organizationId: WORKSPACE_ID,
+ userId,
+ role: "member",
+ createdAt: new Date(),
+ },
+ });
+
+ const agent = await db.agentDefinition.create({
+ data: {
+ name: "Delete me",
+ status: "PAUSED",
+ createdById: userId,
+ },
+ select: { id: true },
+ });
+ agentId = agent.id;
+
+ const version = await db.agentVersion.create({
+ data: {
+ agentId,
+ number: 1,
+ status: "DEPLOYED",
+ instructions: "Test deletion behavior.",
+ manifest: {},
+ modelId: "test/model",
+ sandboxPolicy: {},
+ createdById: userId,
+ approvedAt: new Date(),
+ deployedAt: new Date(),
+ },
+ select: { id: true },
+ });
+ versionId = version.id;
+ await db.agentDefinition.update({
+ where: { id: agentId },
+ data: { currentVersionId: versionId },
+ });
+
+ const trigger = await db.agentTrigger.create({
+ data: {
+ agentId,
+ versionId,
+ type: "SCHEDULE",
+ name: "Every hour",
+ config: { intervalMinutes: 60 },
+ createdById: userId,
+ enabled: true,
+ nextRunAt: new Date(Date.now() + 60 * 60 * 1000),
+ },
+ select: { id: true },
+ });
+ triggerId = trigger.id;
+
+ const [queued, waiting, running, delivery] = await Promise.all([
+ db.agentRun.create({
+ data: {
+ agentId,
+ versionId,
+ triggerId,
+ triggerType: "SCHEDULE",
+ status: "QUEUED",
+ idempotencyKey: `${idempotencyPrefix}-queued`,
+ correlationId: `${idempotencyPrefix}-queued`,
+ },
+ select: { id: true },
+ }),
+ db.agentRun.create({
+ data: {
+ agentId,
+ versionId,
+ triggerType: "MANUAL",
+ status: "WAITING_FOR_APPROVAL",
+ idempotencyKey: `${idempotencyPrefix}-waiting`,
+ correlationId: `${idempotencyPrefix}-waiting`,
+ },
+ select: { id: true },
+ }),
+ db.agentRun.create({
+ data: {
+ agentId,
+ versionId,
+ triggerType: "MANUAL",
+ status: "RUNNING",
+ idempotencyKey: `${idempotencyPrefix}-running`,
+ correlationId: `${idempotencyPrefix}-running`,
+ startedAt: new Date(),
+ sessionId: `${idempotencyPrefix}-active-session`,
+ },
+ select: { id: true },
+ }),
+ db.agentRun.create({
+ data: {
+ agentId,
+ versionId,
+ triggerType: "MANUAL",
+ status: "RUNNING",
+ idempotencyKey: `${idempotencyPrefix}-delivery`,
+ correlationId: `${idempotencyPrefix}-delivery`,
+ startedAt: new Date(),
+ },
+ select: { id: true },
+ }),
+ ]);
+ queuedRunId = queued.id;
+ waitingRunId = waiting.id;
+ runningRunId = running.id;
+ deliveryRunId = delivery.id;
+});
+
+afterAll(async () => {
+ await clean();
+});
+
+describe("deleting an agent", () => {
+ it("stops future work while preserving its audit history", async () => {
+ const removed = await agents.remove(agentId, userId);
+
+ expect(removed.status).toBe("DELETED");
+ expect(removed.disabledTriggers).toBe(1);
+ expect(removed.cancelledRuns).toBe(3);
+
+ const [definition, trigger, runs, runEvents, auditEvent, listed] =
+ await Promise.all([
+ db.agentDefinition.findUnique({ where: { id: agentId } }),
+ db.agentTrigger.findUnique({ where: { id: triggerId } }),
+ db.agentRun.findMany({
+ where: {
+ id: {
+ in: [queuedRunId, waitingRunId, runningRunId, deliveryRunId],
+ },
+ },
+ select: {
+ id: true,
+ status: true,
+ errorCode: true,
+ finishedAt: true,
+ },
+ }),
+ db.agentRunEvent.findMany({
+ where: {
+ runId: { in: [queuedRunId, waitingRunId, deliveryRunId] },
+ },
+ select: { runId: true, type: true, data: true },
+ }),
+ db.agentAuditEvent.findFirst({
+ where: { agentId, type: "agent.deleted" },
+ }),
+ agents.list(userId),
+ ]);
+
+ expect(definition?.deletedAt).not.toBeNull();
+ expect(trigger).toMatchObject({ enabled: false, nextRunAt: null });
+ expect(
+ runs.filter((run) =>
+ [queuedRunId, waitingRunId, deliveryRunId].includes(run.id),
+ ),
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ status: "CANCELLED",
+ errorCode: "AGENT_DELETED",
+ finishedAt: expect.any(Date),
+ }),
+ expect.objectContaining({
+ status: "CANCELLED",
+ errorCode: "AGENT_DELETED",
+ finishedAt: expect.any(Date),
+ }),
+ expect.objectContaining({
+ status: "CANCELLED",
+ errorCode: "AGENT_DELETED",
+ finishedAt: expect.any(Date),
+ }),
+ ]),
+ );
+ expect(runs.find((run) => run.id === runningRunId)?.status).toBe("RUNNING");
+ expect(runEvents).toHaveLength(3);
+ expect(runEvents).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: "run.cancelled",
+ data: { reason: "agent.deleted" },
+ }),
+ ]),
+ );
+ expect(auditEvent?.after).toEqual({
+ status: "DELETED",
+ disabledTriggers: 1,
+ cancelledRuns: 3,
+ });
+ expect(listed.some((agent) => agent.id === agentId)).toBe(false);
+
+ let lookupError: unknown;
+ try {
+ await agents.byId(agentId, userId);
+ } catch (error) {
+ lookupError = error;
+ }
+ expect((lookupError as Error).message).toBe(`No agent with id ${agentId}.`);
+ });
+});
diff --git a/apps/api/test/agent-lifecycle.spec.ts b/apps/api/test/agent-lifecycle.spec.ts
new file mode 100644
index 00000000..97e6627e
--- /dev/null
+++ b/apps/api/test/agent-lifecycle.spec.ts
@@ -0,0 +1,426 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { DEFAULT_WORKSPACE_NAME, WORKSPACE_ID } from "@crm/auth";
+import { db } from "@crm/db";
+import { workspaceSlug } from "@crm/db/workspace";
+import { AgentAccessService } from "../src/agent/agent-access.service";
+import { AgentDefinitionsService } from "../src/agent/agent-definitions.service";
+
+const suffix = crypto.randomUUID();
+const userId = `agent-lifecycle-user-${suffix}`;
+const teammateId = `agent-lifecycle-teammate-${suffix}`;
+const memberId = `agent-lifecycle-member-${suffix}`;
+const teammateMemberId = `agent-lifecycle-teammate-member-${suffix}`;
+const access = new AgentAccessService(db);
+const agents = new AgentDefinitionsService(db, access);
+
+beforeAll(async () => {
+ await db.organization.upsert({
+ where: { id: WORKSPACE_ID },
+ update: {},
+ create: {
+ id: WORKSPACE_ID,
+ name: DEFAULT_WORKSPACE_NAME,
+ slug: workspaceSlug(DEFAULT_WORKSPACE_NAME),
+ createdAt: new Date(),
+ },
+ });
+ await db.user.createMany({
+ data: [
+ {
+ id: userId,
+ name: "Agent Lifecycle Test",
+ email: `${userId}@example.test`,
+ },
+ {
+ id: teammateId,
+ name: "Agent Lifecycle Teammate",
+ email: `${teammateId}@example.test`,
+ },
+ ],
+ });
+ await db.member.createMany({
+ data: [
+ {
+ id: memberId,
+ organizationId: WORKSPACE_ID,
+ userId,
+ role: "member",
+ createdAt: new Date(),
+ },
+ {
+ id: teammateMemberId,
+ organizationId: WORKSPACE_ID,
+ userId: teammateId,
+ role: "member",
+ createdAt: new Date(),
+ },
+ ],
+ });
+});
+
+afterAll(async () => {
+ const agentIds = (
+ await db.agentDefinition.findMany({
+ where: { createdById: userId },
+ select: { id: true },
+ })
+ ).map((agent) => agent.id);
+ if (agentIds.length > 0) {
+ await db.agentRunEvent.deleteMany({
+ where: { run: { agentId: { in: agentIds } } },
+ });
+ await db.agentAction.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentAuditEvent.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentRun.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentTrigger.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentBuilderArtifact.deleteMany({
+ where: { version: { agentId: { in: agentIds } } },
+ });
+ await db.agentDefinition.updateMany({
+ where: { id: { in: agentIds } },
+ data: { currentVersionId: null },
+ });
+ await db.agentVersion.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentDefinition.deleteMany({
+ where: { id: { in: agentIds } },
+ });
+ }
+ await db.member.deleteMany({
+ where: { id: { in: [memberId, teammateMemberId] } },
+ });
+ await db.user.deleteMany({ where: { id: { in: [userId, teammateId] } } });
+});
+
+async function createAgent(versionCount = 1, status = "DRAFT" as const) {
+ const agent = await db.agentDefinition.create({
+ data: {
+ name: `Lifecycle agent ${crypto.randomUUID()}`,
+ status,
+ createdById: userId,
+ },
+ select: { id: true },
+ });
+ const versions = [];
+ for (let number = 1; number <= versionCount; number += 1) {
+ versions.push(
+ await db.agentVersion.create({
+ data: {
+ agentId: agent.id,
+ number,
+ status: "READY",
+ instructions: `Version ${number}`,
+ manifest: {},
+ modelId: "test/model",
+ sandboxPolicy: {},
+ createdById: userId,
+ },
+ select: { id: true, number: true },
+ }),
+ );
+ }
+ return { agentId: agent.id, versions };
+}
+
+describe("agent lifecycle", () => {
+ it("returns stable private and team contracts while auditing metadata edits", async () => {
+ const { agentId, versions } = await createAgent();
+ const versionId = versions[0]?.id;
+ if (!versionId) throw new Error("Missing version");
+
+ const updated = await agents.update(
+ {
+ id: agentId,
+ name: "Renewal monitor",
+ description: " ",
+ },
+ userId,
+ );
+ expect(updated).toMatchObject({
+ id: agentId,
+ name: "Renewal monitor",
+ description: null,
+ status: "DRAFT",
+ });
+ expect((await agents.byId(agentId, userId)).canManage).toBe(true);
+ expect(
+ (await agents.list(userId)).some((agent) => agent.id === agentId),
+ ).toBe(false);
+ let privateDraftError: unknown;
+ try {
+ await agents.byId(agentId, teammateId);
+ } catch (error) {
+ privateDraftError = error;
+ }
+ expect((privateDraftError as Error).message).toBe(
+ `No agent with id ${agentId}.`,
+ );
+
+ await agents.deploy(
+ { id: agentId, versionId, clientRequestId: crypto.randomUUID() },
+ userId,
+ );
+ const nextRunAt = new Date("2026-08-06T12:00:00.000Z");
+ const lastRunAt = new Date("2026-08-05T12:00:00.000Z");
+ await db.agentTrigger.create({
+ data: {
+ agentId,
+ versionId,
+ type: "SCHEDULE",
+ name: "Every morning",
+ config: { intervalMinutes: 1440 },
+ createdById: userId,
+ enabled: true,
+ nextRunAt,
+ lastRunAt,
+ },
+ });
+
+ const detail = await agents.byId(agentId, teammateId);
+ const listed = await agents.list(teammateId);
+ const audit = await db.agentAuditEvent.findFirstOrThrow({
+ where: { agentId, type: "agent.updated" },
+ });
+ const listItem = listed.find((agent) => agent.id === agentId);
+ expect(detail).toMatchObject({
+ id: agentId,
+ canManage: false,
+ status: "LIVE",
+ currentVersion: {
+ id: versionId,
+ approvedAt: expect.any(String),
+ deployedAt: expect.any(String),
+ },
+ triggers: [
+ {
+ name: "Every morning",
+ nextRunAt: nextRunAt.toISOString(),
+ lastRunAt: lastRunAt.toISOString(),
+ },
+ ],
+ });
+ expect(detail.createdAt).toBe(new Date(detail.createdAt).toISOString());
+ expect(detail.updatedAt).toBe(new Date(detail.updatedAt).toISOString());
+ expect(listItem).toMatchObject({
+ id: agentId,
+ status: "LIVE",
+ currentVersion: { id: versionId, deployedAt: expect.any(String) },
+ triggers: [{ nextRunAt: nextRunAt.toISOString() }],
+ runCount: 0,
+ });
+ expect(audit.before).toEqual({
+ name: expect.stringContaining("Lifecycle agent"),
+ description: null,
+ });
+ expect(audit.after).toEqual({
+ name: "Renewal monitor",
+ description: null,
+ });
+ });
+
+ it("promotes versioned draft metadata only when that version is deployed", async () => {
+ const { agentId, versions } = await createAgent();
+ const versionId = versions[0]?.id;
+ if (!versionId) throw new Error("Missing version");
+
+ await db.agentVersion.update({
+ where: { id: versionId },
+ data: {
+ manifest: {
+ name: "Pipeline health monitor",
+ description: "Summarize pipeline health for the team.",
+ },
+ },
+ });
+ const before = await db.agentDefinition.findUniqueOrThrow({
+ where: { id: agentId },
+ select: { name: true, description: true, status: true },
+ });
+ expect(before).toMatchObject({
+ name: expect.stringContaining("Lifecycle agent"),
+ description: null,
+ status: "DRAFT",
+ });
+
+ await agents.deploy(
+ { id: agentId, versionId, clientRequestId: crypto.randomUUID() },
+ userId,
+ );
+
+ const after = await db.agentDefinition.findUniqueOrThrow({
+ where: { id: agentId },
+ select: {
+ name: true,
+ description: true,
+ status: true,
+ currentVersionId: true,
+ },
+ });
+ expect(after).toEqual({
+ name: "Pipeline health monitor",
+ description: "Summarize pipeline health for the team.",
+ status: "LIVE",
+ currentVersionId: versionId,
+ });
+ });
+
+ it("keeps a draft private when pause or archive is requested", async () => {
+ const { agentId } = await createAgent();
+
+ const errors: Error[] = [];
+ for (const transition of [agents.pause, agents.archive]) {
+ try {
+ await transition.call(agents, agentId, userId);
+ } catch (error) {
+ errors.push(error as Error);
+ }
+ }
+ expect(errors.map((error) => error.message)).toEqual([
+ "Only a live agent can be paused.",
+ "Only a live or paused agent can be archived.",
+ ]);
+
+ const [definition, teamAgents] = await Promise.all([
+ db.agentDefinition.findUnique({ where: { id: agentId } }),
+ agents.list(userId),
+ ]);
+ expect(definition?.status).toBe("DRAFT");
+ expect(teamAgents.some((agent) => agent.id === agentId)).toBe(false);
+ });
+
+ it("moves only through valid deployed lifecycle states", async () => {
+ const { agentId, versions } = await createAgent(2);
+ const firstVersionId = versions[0]?.id;
+ const secondVersionId = versions[1]?.id;
+ if (!firstVersionId || !secondVersionId)
+ throw new Error("Missing versions");
+
+ await agents.deploy(
+ {
+ id: agentId,
+ versionId: firstVersionId,
+ clientRequestId: crypto.randomUUID(),
+ },
+ userId,
+ );
+ await agents.pause(agentId, userId);
+ await agents.resume(agentId, userId);
+ await agents.archive(agentId, userId);
+ await agents.restore(agentId, userId);
+ await agents.deploy(
+ {
+ id: agentId,
+ versionId: secondVersionId,
+ clientRequestId: crypto.randomUUID(),
+ },
+ userId,
+ );
+
+ const [definition, deployedVersions] = await Promise.all([
+ db.agentDefinition.findUnique({ where: { id: agentId } }),
+ db.agentVersion.findMany({
+ where: { agentId, status: "DEPLOYED" },
+ select: { id: true },
+ }),
+ ]);
+ expect(definition).toMatchObject({
+ status: "LIVE",
+ currentVersionId: secondVersionId,
+ archivedAt: null,
+ });
+ expect(deployedVersions).toEqual([{ id: secondVersionId }]);
+ });
+
+ it("serializes deployments and preserves request idempotency", async () => {
+ const { agentId, versions } = await createAgent(2);
+ const firstVersionId = versions[0]?.id;
+ const secondVersionId = versions[1]?.id;
+ if (!firstVersionId || !secondVersionId)
+ throw new Error("Missing versions");
+ const clientRequestId = crypto.randomUUID();
+
+ const collision = await Promise.allSettled([
+ agents.deploy(
+ { id: agentId, versionId: firstVersionId, clientRequestId },
+ userId,
+ ),
+ agents.deploy(
+ { id: agentId, versionId: secondVersionId, clientRequestId },
+ userId,
+ ),
+ ]);
+ expect(
+ collision.filter((result) => result.status === "fulfilled"),
+ ).toHaveLength(1);
+ expect(
+ collision.filter((result) => result.status === "rejected"),
+ ).toHaveLength(1);
+
+ const definition = await db.agentDefinition.findUniqueOrThrow({
+ where: { id: agentId },
+ select: { currentVersionId: true },
+ });
+ const currentVersionId = definition.currentVersionId;
+ if (!currentVersionId) throw new Error("Missing current version");
+ const retries = await Promise.all(
+ Array.from({ length: 4 }, () =>
+ agents.deploy(
+ {
+ id: agentId,
+ versionId: currentVersionId,
+ clientRequestId,
+ },
+ userId,
+ ),
+ ),
+ );
+ expect(new Set(retries.map((retry) => retry.versionId))).toEqual(
+ new Set([currentVersionId]),
+ );
+ expect(
+ await db.agentAuditEvent.count({
+ where: { agentId, type: "agent.deployed", requestId: clientRequestId },
+ }),
+ ).toBe(1);
+ expect(
+ await db.agentVersion.count({
+ where: { agentId, status: "DEPLOYED" },
+ }),
+ ).toBe(1);
+ });
+
+ it("cannot resurrect an agent when deletion races a transition", async () => {
+ const { agentId, versions } = await createAgent();
+ const versionId = versions[0]?.id;
+ if (!versionId) throw new Error("Missing version");
+ await agents.deploy(
+ {
+ id: agentId,
+ versionId,
+ clientRequestId: crypto.randomUUID(),
+ },
+ userId,
+ );
+
+ await Promise.allSettled([
+ agents.pause(agentId, userId),
+ agents.remove(agentId, userId),
+ ]);
+
+ expect(
+ await db.agentDefinition.findUnique({
+ where: { id: agentId },
+ select: { status: true },
+ }),
+ ).toEqual({ status: "DELETED" });
+ });
+});
diff --git a/apps/api/test/agent-runs.spec.ts b/apps/api/test/agent-runs.spec.ts
new file mode 100644
index 00000000..92ee4c96
--- /dev/null
+++ b/apps/api/test/agent-runs.spec.ts
@@ -0,0 +1,303 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { DEFAULT_WORKSPACE_NAME, WORKSPACE_ID } from "@crm/auth";
+import { db } from "@crm/db";
+import { workspaceSlug } from "@crm/db/workspace";
+import { AgentAccessService } from "../src/agent/agent-access.service";
+import { AgentRunsService } from "../src/agent/agent-runs.service";
+import type { AgentTriggerService } from "../src/agent/agent-trigger.service";
+
+const suffix = crypto.randomUUID();
+const userId = `agent-run-user-${suffix}`;
+const outsiderId = `agent-run-outsider-${suffix}`;
+const memberId = `agent-run-member-${suffix}`;
+let agentId = "";
+let versionId = "";
+let pokeCount = 0;
+const trigger = {
+ deployedAgentRunQueued() {
+ pokeCount += 1;
+ },
+} as AgentTriggerService;
+const service = new AgentRunsService(db, new AgentAccessService(db), trigger);
+
+beforeAll(async () => {
+ await db.organization.upsert({
+ where: { id: WORKSPACE_ID },
+ update: {},
+ create: {
+ id: WORKSPACE_ID,
+ name: DEFAULT_WORKSPACE_NAME,
+ slug: workspaceSlug(DEFAULT_WORKSPACE_NAME),
+ createdAt: new Date(),
+ },
+ });
+ await db.user.createMany({
+ data: [
+ {
+ id: userId,
+ name: "Agent Run Test",
+ email: `${userId}@example.test`,
+ },
+ {
+ id: outsiderId,
+ name: "Agent Run Outsider",
+ email: `${outsiderId}@example.test`,
+ },
+ ],
+ });
+ await db.member.create({
+ data: {
+ id: memberId,
+ organizationId: WORKSPACE_ID,
+ userId,
+ role: "member",
+ createdAt: new Date(),
+ },
+ });
+ const agent = await db.agentDefinition.create({
+ data: { name: "Run safely", status: "LIVE", createdById: userId },
+ select: { id: true },
+ });
+ agentId = agent.id;
+ const version = await db.agentVersion.create({
+ data: {
+ agentId,
+ number: 1,
+ status: "DEPLOYED",
+ instructions: "Run once.",
+ manifest: {},
+ modelId: "test/model",
+ sandboxPolicy: {},
+ createdById: userId,
+ },
+ select: { id: true },
+ });
+ versionId = version.id;
+ await db.agentDefinition.update({
+ where: { id: agentId },
+ data: { currentVersionId: versionId },
+ });
+});
+
+afterAll(async () => {
+ const agentIds = (
+ await db.agentDefinition.findMany({
+ where: { createdById: userId },
+ select: { id: true },
+ })
+ ).map((agent) => agent.id);
+ if (agentIds.length > 0) {
+ await db.agentRunEvent.deleteMany({
+ where: { run: { agentId: { in: agentIds } } },
+ });
+ await db.agentAction.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentAuditEvent.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentRun.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentDefinition.updateMany({
+ where: { id: { in: agentIds } },
+ data: { currentVersionId: null },
+ });
+ await db.agentVersion.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentDefinition.deleteMany({
+ where: { id: { in: agentIds } },
+ });
+ }
+ await db.member.deleteMany({ where: { id: memberId } });
+ await db.user.deleteMany({ where: { id: { in: [userId, outsiderId] } } });
+});
+
+describe("manual agent runs", () => {
+ it("returns ordered, transport-safe run and activity history", async () => {
+ const clientRequestId = crypto.randomUUID();
+ const { id: runId } = await service.runNow(
+ { id: agentId, clientRequestId },
+ userId,
+ );
+ const startedAt = new Date("2026-08-05T12:00:00.000Z");
+ const completedAt = new Date("2026-08-05T12:00:02.000Z");
+ await db.agentRun.update({
+ where: { id: runId },
+ data: {
+ status: "SUCCEEDED",
+ summary: "Prepared the account brief",
+ modelId: "test/model",
+ inputTokens: 120,
+ outputTokens: 80,
+ costUsd: "0.012345",
+ startedAt,
+ finishedAt: completedAt,
+ },
+ });
+ await db.agentRunEvent.create({
+ data: {
+ runId,
+ sequence: 1,
+ type: "run.completed",
+ data: { summary: "Prepared the account brief" },
+ emittedAt: completedAt,
+ },
+ });
+ await db.agentAction.create({
+ data: {
+ agentId,
+ runId,
+ type: "timeline.note.created",
+ provider: "crm",
+ targetType: "company",
+ targetId: "company-1",
+ targetLabel: "Acme",
+ summary: "Added a meeting brief",
+ status: "SUCCEEDED",
+ idempotencyKey: `action-${clientRequestId}`,
+ plannedAt: startedAt,
+ startedAt,
+ completedAt,
+ },
+ });
+
+ const [runs, activity] = await Promise.all([
+ service.list(agentId, 1, userId),
+ service.activity(agentId, 1, userId),
+ ]);
+ expect(runs).toHaveLength(1);
+ expect(runs[0]).toMatchObject({
+ id: runId,
+ status: "SUCCEEDED",
+ costUsd: "0.012345",
+ startedAt: startedAt.toISOString(),
+ finishedAt: completedAt.toISOString(),
+ events: [
+ { sequence: 0, type: "run.queued", emittedAt: expect.any(String) },
+ {
+ sequence: 1,
+ type: "run.completed",
+ emittedAt: completedAt.toISOString(),
+ },
+ ],
+ actions: [
+ {
+ type: "timeline.note.created",
+ plannedAt: startedAt.toISOString(),
+ startedAt: startedAt.toISOString(),
+ completedAt: completedAt.toISOString(),
+ },
+ ],
+ });
+ expect(runs[0]?.createdAt).toBe(
+ new Date(runs[0]?.createdAt ?? "").toISOString(),
+ );
+ expect(activity).toHaveLength(1);
+ expect(activity[0]).toMatchObject({
+ type: "run.requested",
+ requestId: clientRequestId,
+ emittedAt: expect.any(String),
+ actorUser: { id: userId },
+ version: { id: versionId, number: 1 },
+ });
+ });
+
+ it("rejects a manual run while an agent is not live", async () => {
+ const beforePokeCount = pokeCount;
+ const draft = await db.agentDefinition.create({
+ data: {
+ name: "Draft run guard",
+ status: "DRAFT",
+ createdById: userId,
+ },
+ select: { id: true },
+ });
+
+ let runError: unknown;
+ try {
+ await service.runNow(
+ { id: draft.id, clientRequestId: crypto.randomUUID() },
+ userId,
+ );
+ } catch (error) {
+ runError = error;
+ }
+ expect((runError as Error).message).toBe("This agent is not live yet.");
+ expect(pokeCount).toBe(beforePokeCount);
+ });
+
+ it("deduplicates concurrent requests and keeps the run and audit atomic", async () => {
+ const beforePokeCount = pokeCount;
+ const clientRequestId = crypto.randomUUID();
+ const results = await Promise.all(
+ Array.from({ length: 4 }, () =>
+ service.runNow({ id: agentId, clientRequestId }, userId),
+ ),
+ );
+
+ expect(new Set(results.map((result) => result.id)).size).toBe(1);
+ expect(
+ await db.agentRun.count({ where: { idempotencyKey: clientRequestId } }),
+ ).toBe(1);
+ expect(
+ await db.agentAuditEvent.count({
+ where: { agentId, type: "run.requested", requestId: clientRequestId },
+ }),
+ ).toBe(1);
+ expect(pokeCount).toBe(beforePokeCount + 4);
+ });
+
+ it("checks workspace membership before replaying an existing request", async () => {
+ const clientRequestId = crypto.randomUUID();
+ await service.runNow({ id: agentId, clientRequestId }, userId);
+
+ let error: Error | null = null;
+ try {
+ await service.runNow({ id: agentId, clientRequestId }, outsiderId);
+ } catch (caught) {
+ error = caught as Error;
+ }
+ expect(error?.message).toBe("You are not a member of this workspace.");
+ });
+
+ it("allows only one agent to claim a globally reused request id", async () => {
+ const otherAgent = await db.agentDefinition.create({
+ data: { name: "Other live agent", status: "LIVE", createdById: userId },
+ select: { id: true },
+ });
+ const otherVersion = await db.agentVersion.create({
+ data: {
+ agentId: otherAgent.id,
+ number: 1,
+ status: "DEPLOYED",
+ instructions: "Run once.",
+ manifest: {},
+ modelId: "test/model",
+ sandboxPolicy: {},
+ createdById: userId,
+ },
+ select: { id: true },
+ });
+ await db.agentDefinition.update({
+ where: { id: otherAgent.id },
+ data: { currentVersionId: otherVersion.id },
+ });
+ const clientRequestId = crypto.randomUUID();
+
+ const attempts = await Promise.allSettled([
+ service.runNow({ id: agentId, clientRequestId }, userId),
+ service.runNow({ id: otherAgent.id, clientRequestId }, userId),
+ ]);
+ expect(
+ attempts.filter((attempt) => attempt.status === "fulfilled"),
+ ).toHaveLength(1);
+ expect(
+ attempts.filter((attempt) => attempt.status === "rejected"),
+ ).toHaveLength(1);
+ expect(
+ await db.agentRun.count({ where: { idempotencyKey: clientRequestId } }),
+ ).toBe(1);
+ });
+});
diff --git a/apps/api/test/agent-visibility.spec.ts b/apps/api/test/agent-visibility.spec.ts
new file mode 100644
index 00000000..8c012f78
--- /dev/null
+++ b/apps/api/test/agent-visibility.spec.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "bun:test";
+import {
+ canReadAgent,
+ isPrivateAgentDraft,
+ TEAM_AGENT_STATUSES,
+} from "../src/agent/agent-visibility";
+
+describe("agent visibility", () => {
+ it("keeps drafts private to their creator", () => {
+ expect(canReadAgent("DRAFT", "creator", "creator")).toBe(true);
+ expect(canReadAgent("DRAFT", "creator", "teammate")).toBe(false);
+ expect(canReadAgent("DEPLOYING", "creator", "teammate")).toBe(false);
+ });
+
+ it("makes deployed lifecycle states visible to the team", () => {
+ for (const status of TEAM_AGENT_STATUSES) {
+ expect(canReadAgent(status, "creator", "teammate")).toBe(true);
+ }
+ });
+
+ it("treats deployment as the ownership boundary", () => {
+ expect(isPrivateAgentDraft("DRAFT")).toBe(true);
+ expect(isPrivateAgentDraft("DEPLOYING")).toBe(true);
+ expect(isPrivateAgentDraft("LIVE")).toBe(false);
+ });
+});
diff --git a/apps/api/test/conversation-sharing.spec.ts b/apps/api/test/conversation-sharing.spec.ts
new file mode 100644
index 00000000..c1443504
--- /dev/null
+++ b/apps/api/test/conversation-sharing.spec.ts
@@ -0,0 +1,226 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { DEFAULT_WORKSPACE_NAME, WORKSPACE_ID } from "@crm/auth";
+import { db } from "@crm/db";
+import { workspaceSlug } from "@crm/db/workspace";
+import { ConversationSharingService } from "../src/conversations/conversation-sharing.service";
+import { ConversationsService } from "../src/conversations/conversations.service";
+
+const suffix = crypto.randomUUID();
+const userId = `share-user-${suffix}`;
+const outsiderId = `share-outsider-${suffix}`;
+const viewerId = `share-viewer-${suffix}`;
+const memberId = `share-member-${suffix}`;
+const viewerMemberId = `share-viewer-member-${suffix}`;
+const sessionId = `share-session-${suffix}`;
+let conversationId = "";
+let attachmentId = "";
+const service = new ConversationSharingService(db);
+const conversations = new ConversationsService(db);
+
+beforeAll(async () => {
+ await db.organization.upsert({
+ where: { id: WORKSPACE_ID },
+ update: {},
+ create: {
+ id: WORKSPACE_ID,
+ name: DEFAULT_WORKSPACE_NAME,
+ slug: workspaceSlug(DEFAULT_WORKSPACE_NAME),
+ createdAt: new Date(),
+ },
+ });
+ await db.user.createMany({
+ data: [
+ { id: userId, name: "Share Owner", email: `${userId}@example.test` },
+ {
+ id: outsiderId,
+ name: "Share Outsider",
+ email: `${outsiderId}@example.test`,
+ },
+ {
+ id: viewerId,
+ name: "Share Viewer",
+ email: `${viewerId}@example.test`,
+ },
+ ],
+ });
+ await db.member.createMany({
+ data: [
+ {
+ id: memberId,
+ organizationId: WORKSPACE_ID,
+ userId,
+ role: "member",
+ createdAt: new Date(),
+ },
+ {
+ id: viewerMemberId,
+ organizationId: WORKSPACE_ID,
+ userId: viewerId,
+ role: "member",
+ createdAt: new Date(),
+ },
+ ],
+ });
+ const conversation = await db.agentConversation.create({
+ data: {
+ kind: "BUILDER",
+ userId,
+ title: "Share safely",
+ sessionId,
+ },
+ select: { id: true },
+ });
+ conversationId = conversation.id;
+ const submission = await db.agentConversationSubmission.create({
+ data: {
+ conversationId,
+ submittedById: userId,
+ clientRequestId: crypto.randomUUID(),
+ message: {
+ text: "Review the image",
+ resources: [],
+ attachments: [{ name: "shared.png", type: "image/png", size: 4 }],
+ },
+ attachments: {
+ create: {
+ name: "shared.png",
+ mediaType: "image/png",
+ size: 4,
+ content: Buffer.from([1, 2, 3, 4]),
+ position: 0,
+ },
+ },
+ },
+ select: { attachments: { select: { id: true } } },
+ });
+ attachmentId = submission.attachments[0]?.id ?? "";
+});
+
+afterAll(async () => {
+ await db.agentEvent.deleteMany({ where: { sessionId } });
+ await db.agentConversation.deleteMany({ where: { id: conversationId } });
+ await db.member.deleteMany({
+ where: { id: { in: [memberId, viewerMemberId] } },
+ });
+ await db.user.deleteMany({
+ where: { id: { in: [userId, outsiderId, viewerId] } },
+ });
+});
+
+describe("conversation sharing", () => {
+ it("keeps a builder chat private until its owner creates a link", async () => {
+ let unavailable: unknown;
+ try {
+ await service.resolve("x".repeat(43), userId);
+ } catch (error) {
+ unavailable = error;
+ }
+ expect(unavailable).toBeDefined();
+
+ const { token } = await service.create(conversationId, userId);
+ expect(await service.resolve(token, userId)).toMatchObject({
+ id: conversationId,
+ title: "Share safely",
+ ownerName: "Share Owner",
+ });
+ });
+
+ it("allows only the owner to create or revoke a chat link", async () => {
+ for (const operation of [
+ () => service.create(conversationId, outsiderId),
+ () => service.revoke(conversationId, outsiderId),
+ ]) {
+ let denied: unknown;
+ try {
+ await operation();
+ } catch (error) {
+ denied = error;
+ }
+ expect(denied).toBeDefined();
+ }
+ });
+
+ it("keeps exactly one active link across concurrent replacements", async () => {
+ const results = await Promise.all(
+ Array.from({ length: 4 }, () => service.create(conversationId, userId)),
+ );
+ const activeShares = await db.agentConversationShare.findMany({
+ where: { conversationId, revokedAt: null },
+ select: { tokenHash: true },
+ });
+
+ expect(activeShares).toHaveLength(1);
+ const resolutions = await Promise.allSettled(
+ results.map(({ token }) => service.resolve(token, userId)),
+ );
+ expect(
+ resolutions.filter((result) => result.status === "fulfilled"),
+ ).toHaveLength(1);
+ });
+
+ it("requires workspace membership to open a valid shared link", async () => {
+ const { token } = await service.create(conversationId, userId);
+ let denied: unknown;
+ try {
+ await service.resolve(token, outsiderId);
+ } catch (error) {
+ denied = error;
+ }
+
+ expect(denied).toBeDefined();
+ });
+
+ it("authorizes attachment bytes with the active share token only", async () => {
+ const { token } = await service.create(conversationId, userId);
+ const shared = await service.resolve(token, viewerId);
+ const message = recordOf(shared.submissions[0]?.message);
+ const attachment = recordOf(arrayOf(message.attachments)[0]);
+ expect(attachment.previewUrl).toBe(
+ `/api/conversations/attachments/${attachmentId}?share=${encodeURIComponent(token)}`,
+ );
+ expect(
+ Buffer.from(
+ (await conversations.attachment(attachmentId, viewerId, token)).content,
+ ),
+ ).toEqual(Buffer.from([1, 2, 3, 4]));
+
+ await service.revoke(conversationId, userId);
+ let revokedError: unknown;
+ try {
+ await conversations.attachment(attachmentId, viewerId, token);
+ } catch (error) {
+ revokedError = error;
+ }
+ expect((revokedError as Error).message).toBe(
+ "That attachment is unavailable.",
+ );
+ });
+
+ it("revokes the active link", async () => {
+ const { token } = await service.create(conversationId, userId);
+ await service.revoke(conversationId, userId);
+
+ expect(
+ await db.agentConversationShare.count({
+ where: { conversationId, revokedAt: null },
+ }),
+ ).toBe(0);
+ let unavailable: unknown;
+ try {
+ await service.resolve(token, userId);
+ } catch (error) {
+ unavailable = error;
+ }
+ expect(unavailable).toBeDefined();
+ });
+});
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+function arrayOf(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
diff --git a/apps/api/test/conversations.spec.ts b/apps/api/test/conversations.spec.ts
index 8bc5bbb5..9cffe206 100644
--- a/apps/api/test/conversations.spec.ts
+++ b/apps/api/test/conversations.spec.ts
@@ -1,51 +1,79 @@
import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { DEFAULT_WORKSPACE_NAME, WORKSPACE_ID } from "@crm/auth";
import { db } from "@crm/db";
+import { workspaceSlug } from "@crm/db/workspace";
+import {
+ builderConversationCreateInput,
+ conversationListInput,
+ conversationSaveInput,
+} from "../src/conversations/conversations.contracts";
import { ConversationsService } from "../src/conversations/conversations.service";
const suffix = process.env.TEST_RUN_ID ?? "conversations-spec";
const email = `conversation.subject.${suffix}@example.test`;
const userId = `user-${suffix}`;
-
-function memoryCache() {
- const store = new Map<string, unknown>();
- return {
- store,
- get: async <T>(key: string) => store.get(key) as T | undefined,
- set: async (key: string, value: unknown) => {
- store.set(key, value);
- },
- del: async (key: string) => {
- store.delete(key);
- },
- };
-}
+const memberId = `conversation-member-${suffix}`;
let contactId: string;
let service: ConversationsService;
-let cache: ReturnType<typeof memoryCache>;
beforeAll(async () => {
+ await db.agentEvent.deleteMany({
+ where: {
+ OR: [
+ { sessionId: { startsWith: `builder-question-${suffix}` } },
+ { sessionId: { startsWith: `ses_${suffix}` } },
+ ],
+ },
+ });
+ await db.agentConversation.deleteMany({ where: { userId } });
+ await db.member.deleteMany({ where: { id: memberId } });
await db.user.deleteMany({ where: { id: userId } });
await db.contact.deleteMany({ where: { email } });
+ await db.organization.upsert({
+ where: { id: WORKSPACE_ID },
+ update: {},
+ create: {
+ id: WORKSPACE_ID,
+ name: DEFAULT_WORKSPACE_NAME,
+ slug: workspaceSlug(DEFAULT_WORKSPACE_NAME),
+ createdAt: new Date(),
+ },
+ });
await db.user.create({
data: { id: userId, name: "Test Rep", email: `${userId}@example.test` },
});
+ await db.member.create({
+ data: {
+ id: memberId,
+ organizationId: WORKSPACE_ID,
+ userId,
+ role: "member",
+ createdAt: new Date(),
+ },
+ });
const contact = await db.contact.create({
data: { firstName: "Conversation", lastName: "Subject", email },
select: { id: true },
});
contactId = contact.id;
- cache = memoryCache();
- service = new ConversationsService(
- db,
- cache as unknown as ConstructorParameters<typeof ConversationsService>[1],
- );
+ service = new ConversationsService(db);
});
afterAll(async () => {
+ await db.agentEvent.deleteMany({
+ where: {
+ OR: [
+ { sessionId: { startsWith: `builder-question-${suffix}` } },
+ { sessionId: { startsWith: `ses_${suffix}` } },
+ ],
+ },
+ });
await db.contact.deleteMany({ where: { email } });
+ await db.agentConversation.deleteMany({ where: { userId } });
+ await db.member.deleteMany({ where: { id: memberId } });
await db.user.deleteMany({ where: { id: userId } });
});
@@ -100,17 +128,15 @@ describe("ConversationsService", () => {
});
});
- it("serves the list from cache, and drops it when something changes", async () => {
- await service.list({ contactId }, userId);
- expect(cache.store.size).toBe(1);
-
+ it("reflects newly saved conversations immediately", async () => {
+ const before = await service.list({ contactId }, userId);
await service.save(
{ contactId, sessionId: `ses_${suffix}_2`, messageCount: 1 },
userId,
);
- expect(cache.store.size).toBe(0);
-
- expect(await service.list({ contactId }, userId)).toHaveLength(2);
+ expect(await service.list({ contactId }, userId)).toHaveLength(
+ before.length + 1,
+ );
});
it("newest first, so reopening lands on the last thing you asked", async () => {
@@ -123,40 +149,640 @@ describe("ConversationsService", () => {
});
it("refuses a conversation that belongs to a record of neither kind", async () => {
- expect(
+ await expect(
service.save({ sessionId: `ses_${suffix}_3` }, userId),
).rejects.toThrow();
});
+ it("requires exactly one CRM record in list and save inputs", () => {
+ expect(conversationListInput.safeParse({}).success).toBe(false);
+ expect(
+ conversationListInput.safeParse({ contactId, companyId: "company-1" })
+ .success,
+ ).toBe(false);
+ expect(
+ conversationSaveInput.safeParse({
+ contactId,
+ dealId: "deal-1",
+ sessionId: "session-1",
+ }).success,
+ ).toBe(false);
+ });
+
+ it("does not mutate a conversation owned by another rep", async () => {
+ const sessionId = `ses_${suffix}_ownership`;
+ await service.save(
+ {
+ contactId,
+ sessionId,
+ continuationToken: "owner-token",
+ streamIndex: 3,
+ },
+ userId,
+ );
+
+ let ownershipError: unknown;
+ try {
+ await service.save(
+ {
+ contactId,
+ sessionId,
+ continuationToken: "attacker-token",
+ streamIndex: 99,
+ },
+ "somebody-else",
+ );
+ } catch (error) {
+ ownershipError = error;
+ }
+ expect(ownershipError).toBeDefined();
+
+ expect(
+ await db.agentConversation.findUnique({
+ where: { sessionId },
+ select: { continuationToken: true, streamIndex: true },
+ }),
+ ).toEqual({ continuationToken: "owner-token", streamIndex: 3 });
+ });
+
+ it("does not move an existing session to another CRM record", async () => {
+ const sessionId = `ses_${suffix}_record`;
+ await service.save({ contactId, sessionId }, userId);
+
+ let recordError: unknown;
+ try {
+ await service.save({ companyId: "another-record", sessionId }, userId);
+ } catch (error) {
+ recordError = error;
+ }
+ expect(recordError).toBeInstanceOf(Error);
+ expect((recordError as Error).message).toContain("cannot be moved");
+ });
+
+ it("deduplicates concurrent saves of the same record session", async () => {
+ const sessionId = `ses_${suffix}_concurrent`;
+ const results = await Promise.all(
+ Array.from({ length: 4 }, () =>
+ service.save({ contactId, sessionId, streamIndex: 7 }, userId),
+ ),
+ );
+
+ expect(new Set(results.map((result) => result.id)).size).toBe(1);
+ expect(await db.agentConversation.count({ where: { sessionId } })).toBe(1);
+ });
+
+ it("does not treat a builder session as a record conversation", async () => {
+ const builder = await service.createBuilder(
+ {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CHAT",
+ message: "Summarize this customer",
+ resources: [],
+ attachments: [],
+ },
+ userId,
+ );
+ const sessionId = `ses_${suffix}_builder`;
+ await db.agentConversation.update({
+ where: { id: builder.id },
+ data: { sessionId },
+ });
+
+ let saveError: unknown;
+ try {
+ await service.save({ contactId, sessionId }, userId);
+ } catch (error) {
+ saveError = error;
+ }
+ expect(saveError).toBeDefined();
+ expect(
+ await db.agentConversation.findUnique({
+ where: { id: builder.id },
+ select: { kind: true, contactId: true },
+ }),
+ ).toEqual({ kind: "BUILDER", contactId: null });
+ });
+
+ it("returns the newest event window in chronological order", async () => {
+ const sessionId = `ses_${suffix}_events`;
+ const saved = await service.save({ contactId, sessionId }, userId);
+ const emittedAt = new Date("2026-08-05T12:00:00.000Z");
+ await db.agentEvent.createMany({
+ data: [0, 1, 2, 3].map((position) => ({
+ id: `evt_${suffix}_window_${position}`,
+ sessionId,
+ contactId,
+ type: `event.${position}`,
+ data: {},
+ emittedAt: new Date(emittedAt.getTime() + position),
+ })),
+ });
+
+ expect(
+ (await service.events({ id: saved.id, limit: 2 }, userId)).map(
+ (event) => event.type,
+ ),
+ ).toEqual(["event.2", "event.3"]);
+ });
+
it("forgets a conversation and the events behind it", async () => {
- const [conversation] = await service.list({ contactId }, userId);
- if (!conversation) throw new Error("expected a conversation");
+ const sessionId = `ses_${suffix}_delete`;
+ const conversation = await service.save({ contactId, sessionId }, userId);
await db.agentEvent.create({
data: {
id: `evt_${suffix}`,
- sessionId: conversation.sessionId,
+ sessionId,
contactId,
type: "turn.completed",
data: {},
emittedAt: new Date(),
},
});
+ await db.agentBuilderArtifact.create({
+ data: {
+ conversationId: conversation.id,
+ path: "agent/instructions.md",
+ language: "markdown",
+ content: "Temporary draft",
+ revision: 1,
+ },
+ });
await service.remove(conversation.id, userId);
- expect(await service.list({ contactId }, userId)).toHaveLength(1);
+ expect(
+ await db.agentConversation.findUnique({ where: { id: conversation.id } }),
+ ).toBeNull();
expect(
await db.agentEvent.count({
- where: { sessionId: conversation.sessionId },
+ where: { sessionId },
+ }),
+ ).toBe(0);
+ expect(
+ await db.agentBuilderArtifact.count({
+ where: { conversationId: conversation.id },
}),
).toBe(0);
});
it("will not let one rep delete another's conversation", async () => {
- const [conversation] = await service.list({ contactId }, userId);
- if (!conversation) throw new Error("expected a conversation");
+ const conversation = await service.save(
+ { contactId, sessionId: `ses_${suffix}_protected` },
+ userId,
+ );
- expect(service.remove(conversation.id, "somebody-else")).rejects.toThrow();
+ let removeError: unknown;
+ try {
+ await service.remove(conversation.id, "somebody-else");
+ } catch (error) {
+ removeError = error;
+ }
+ expect(removeError).toBeDefined();
+ expect(
+ await db.agentConversation.findUnique({ where: { id: conversation.id } }),
+ ).not.toBeNull();
+ });
+
+ it("persists the command type that controls agent creation", async () => {
+ const chat = await service.createBuilder(
+ {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CHAT",
+ message: "Tell me about this customer",
+ resources: [],
+ attachments: [],
+ },
+ userId,
+ );
+ const creation = await service.createBuilder(
+ {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CREATE_AGENT",
+ message: "/Create agent Flag stalled deals",
+ resources: [],
+ attachments: [],
+ },
+ userId,
+ );
+
+ expect(
+ (await service.builderById(chat.id, userId)).submissions[0],
+ ).toMatchObject({ commandType: "CHAT" });
+ expect(
+ (await service.builderById(creation.id, userId)).submissions[0],
+ ).toMatchObject({ commandType: "CREATE_AGENT" });
+ expect((await service.builderById(chat.id, userId)).title).toBeNull();
+ expect((await service.builderById(creation.id, userId)).title).toBeNull();
+ });
+
+ it("persists attachment bytes once and returns lightweight transcript metadata", async () => {
+ const imageBytes = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+ const textBytes = Buffer.from("account notes");
+ const input = {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CHAT" as const,
+ message: "Review these files",
+ resources: [],
+ attachments: [
+ {
+ name: "account.png",
+ type: "image/png",
+ size: imageBytes.byteLength,
+ contentBase64: imageBytes.toString("base64"),
+ },
+ {
+ name: "notes.txt",
+ type: "text/plain",
+ size: textBytes.byteLength,
+ contentBase64: textBytes.toString("base64"),
+ },
+ ],
+ };
+ const conversation = await service.createBuilder(input, userId);
+ const detail = await service.builderById(conversation.id, userId);
+ const submission = detail.submissions.find(
+ (row) => row.clientRequestId === input.clientRequestId,
+ );
+ const message = recordOf(submission?.message);
+ const attachments = arrayOf(message.attachments).map(recordOf);
+
+ expect(JSON.stringify(message)).not.toContain("contentBase64");
+ expect(attachments).toEqual([
+ expect.objectContaining({
+ name: "account.png",
+ type: "image/png",
+ size: imageBytes.byteLength,
+ previewUrl: expect.stringContaining("/api/conversations/attachments/"),
+ }),
+ expect.objectContaining({
+ name: "notes.txt",
+ type: "text/plain",
+ size: textBytes.byteLength,
+ previewUrl: null,
+ }),
+ ]);
+ const imageId = attachments[0]?.id;
+ if (typeof imageId !== "string") throw new Error("Missing attachment id");
+ const image = await service.attachment(imageId, userId);
+ expect(Buffer.from(image.content)).toEqual(imageBytes);
+ expect(image).toMatchObject({
+ name: "account.png",
+ mediaType: "image/png",
+ previewable: true,
+ });
+ });
+
+ it("rejects attachment metadata that does not match its bytes", () => {
+ expect(
+ builderConversationCreateInput.safeParse({
+ clientRequestId: crypto.randomUUID(),
+ message: "Review this file",
+ attachments: [
+ {
+ name: "notes.txt",
+ type: "text/plain",
+ size: 99,
+ contentBase64: Buffer.from("notes").toString("base64"),
+ },
+ ],
+ }).success,
+ ).toBe(false);
+ });
+
+ it("reuses persisted attachment bytes when retrying a failed agent turn", async () => {
+ const bytes = Buffer.from("retry-safe attachment");
+ const conversation = await service.createBuilder(
+ {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CHAT",
+ message: "Read this attachment",
+ resources: [],
+ attachments: [
+ {
+ name: "retry.txt",
+ type: "text/plain",
+ size: bytes.byteLength,
+ contentBase64: bytes.toString("base64"),
+ },
+ ],
+ },
+ userId,
+ );
+ const original = await service.builderById(conversation.id, userId);
+ const originalMessage = recordOf(original.submissions[0]?.message);
+ const originalAttachment = recordOf(
+ arrayOf(originalMessage.attachments)[0],
+ );
+
+ await service.submitBuilder(
+ {
+ id: conversation.id,
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CHAT",
+ message: "Try reading it again",
+ resources: [],
+ attachments: [
+ {
+ id: String(originalAttachment.id),
+ name: String(originalAttachment.name),
+ type: String(originalAttachment.type),
+ size: Number(originalAttachment.size),
+ previewUrl: null,
+ },
+ ],
+ },
+ userId,
+ );
+
+ const detail = await service.builderById(conversation.id, userId);
+ const retryMessage = recordOf(detail.submissions.at(-1)?.message);
+ const retryAttachment = recordOf(arrayOf(retryMessage.attachments)[0]);
+ expect(retryAttachment.id).not.toBe(originalAttachment.id);
+ const stored = await service.attachment(String(retryAttachment.id), userId);
+ expect(Buffer.from(stored.content)).toEqual(bytes);
+ });
+
+ it("does not copy an attachment from another private conversation", async () => {
+ const bytes = Buffer.from("private attachment");
+ const source = await service.createBuilder(
+ {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CHAT",
+ message: "Private source",
+ resources: [],
+ attachments: [
+ {
+ name: "private.txt",
+ type: "text/plain",
+ size: bytes.byteLength,
+ contentBase64: bytes.toString("base64"),
+ },
+ ],
+ },
+ userId,
+ );
+ const target = await service.createBuilder(
+ {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CHAT",
+ message: "Different private chat",
+ resources: [],
+ attachments: [],
+ },
+ userId,
+ );
+ const sourceDetail = await service.builderById(source.id, userId);
+ const sourceMessage = recordOf(sourceDetail.submissions[0]?.message);
+ const attachment = recordOf(arrayOf(sourceMessage.attachments)[0]);
+
+ let submitError: unknown;
+ try {
+ await service.submitBuilder(
+ {
+ id: target.id,
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CHAT",
+ message: "Copy data across chats",
+ resources: [],
+ attachments: [
+ {
+ id: String(attachment.id),
+ name: String(attachment.name),
+ type: String(attachment.type),
+ size: Number(attachment.size),
+ previewUrl: null,
+ },
+ ],
+ },
+ userId,
+ );
+ } catch (error) {
+ submitError = error;
+ }
+ expect(submitError).toBeInstanceOf(Error);
+ expect((submitError as Error).message).toContain("no longer available");
+ });
+
+ it("deduplicates concurrent builder creation retries", async () => {
+ const clientRequestId = crypto.randomUUID();
+ const results = await Promise.all(
+ Array.from({ length: 4 }, () =>
+ service.createBuilder(
+ {
+ clientRequestId,
+ commandType: "CHAT",
+ message: "Prepare a renewal brief",
+ resources: [],
+ attachments: [],
+ },
+ userId,
+ ),
+ ),
+ );
+
+ expect(new Set(results.map((result) => result.id)).size).toBe(1);
+ expect(
+ await db.agentConversationSubmission.count({
+ where: { clientRequestId },
+ }),
+ ).toBe(1);
+ });
+
+ it("deduplicates concurrent builder message retries", async () => {
+ const conversation = await service.createBuilder(
+ {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CHAT",
+ message: "Review the account history",
+ resources: [],
+ attachments: [],
+ },
+ userId,
+ );
+ const clientRequestId = crypto.randomUUID();
+ const results = await Promise.all(
+ Array.from({ length: 4 }, () =>
+ service.submitBuilder(
+ {
+ id: conversation.id,
+ clientRequestId,
+ commandType: "CHAT",
+ message: "Summarize the open risks",
+ resources: [],
+ attachments: [],
+ },
+ userId,
+ ),
+ ),
+ );
+
+ expect(new Set(results.map((result) => result.id)).size).toBe(1);
+ expect(
+ await db.agentConversationSubmission.count({
+ where: { clientRequestId },
+ }),
+ ).toBe(1);
+ });
+
+ it("queues a pending builder answer for the CRM-owned Eve channel", async () => {
+ const conversation = await service.createBuilder(
+ {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CREATE_AGENT",
+ message: "/Create agent Flag overdue invoices",
+ resources: [],
+ attachments: [],
+ },
+ userId,
+ );
+ const sessionId = `builder-question-${suffix}-1`;
+ await db.agentConversation.update({
+ where: { id: conversation.id },
+ data: {
+ sessionId,
+ continuationToken: `crm:builder:${conversation.id}`,
+ },
+ });
+ await db.agentEvent.create({
+ data: {
+ id: `evt_${suffix}_question`,
+ sessionId,
+ type: "input.requested",
+ data: {
+ requests: [
+ {
+ kind: "question",
+ requestId: "question-1",
+ prompt: "Where should this go?",
+ display: "select",
+ options: [{ id: "crm-task", label: "Create a CRM task" }],
+ },
+ ],
+ },
+ emittedAt: new Date(),
+ },
+ });
+
+ const response = await service.answerBuilderQuestion(
+ {
+ id: conversation.id,
+ clientRequestId: crypto.randomUUID(),
+ requestId: "question-1",
+ optionId: "crm-task",
+ },
+ userId,
+ );
+ const submission = await db.agentConversationSubmission.findUnique({
+ where: { id: response.id },
+ select: {
+ commandType: true,
+ inputRequestId: true,
+ message: true,
+ status: true,
+ },
+ });
+
+ expect(submission).toMatchObject({
+ commandType: "CHAT",
+ inputRequestId: "question-1",
+ status: "PENDING",
+ message: {
+ text: "Create a CRM task",
+ inputResponse: {
+ requestId: "question-1",
+ answer: "crm-task",
+ },
+ },
+ });
+ });
+
+ it("accepts only one concurrent answer to a follow-up request", async () => {
+ const conversation = await service.createBuilder(
+ {
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CREATE_AGENT",
+ message: "/Create agent Prepare meeting briefs",
+ resources: [],
+ attachments: [],
+ },
+ userId,
+ );
+ const sessionId = `builder-question-${suffix}-2`;
+ await db.agentConversation.update({
+ where: { id: conversation.id },
+ data: {
+ sessionId,
+ continuationToken: `crm:builder:${conversation.id}`,
+ },
+ });
+ await db.agentEvent.create({
+ data: {
+ id: `evt_${suffix}_concurrent_question`,
+ sessionId,
+ type: "input.requested",
+ data: {
+ requests: [
+ {
+ kind: "question",
+ requestId: "question-concurrent",
+ prompt: "Which output?",
+ display: "select",
+ options: [
+ { id: "note", label: "Create a note" },
+ { id: "task", label: "Create a task" },
+ ],
+ },
+ ],
+ },
+ emittedAt: new Date(),
+ },
+ });
+
+ const results = await Promise.allSettled([
+ service.answerBuilderQuestion(
+ {
+ id: conversation.id,
+ clientRequestId: crypto.randomUUID(),
+ requestId: "question-concurrent",
+ optionId: "note",
+ },
+ userId,
+ ),
+ service.answerBuilderQuestion(
+ {
+ id: conversation.id,
+ clientRequestId: crypto.randomUUID(),
+ requestId: "question-concurrent",
+ optionId: "task",
+ },
+ userId,
+ ),
+ ]);
+
+ expect(
+ results.filter((result) => result.status === "fulfilled"),
+ ).toHaveLength(1);
+ expect(
+ results.filter((result) => result.status === "rejected"),
+ ).toHaveLength(1);
+ expect(
+ await db.agentConversationSubmission.count({
+ where: {
+ conversationId: conversation.id,
+ inputRequestId: "question-concurrent",
+ },
+ }),
+ ).toBe(1);
});
});
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+function arrayOf(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
diff --git a/apps/api/test/setup.ts b/apps/api/test/setup.ts
new file mode 100644
index 00000000..f8ec45ff
--- /dev/null
+++ b/apps/api/test/setup.ts
@@ -0,0 +1,7 @@
+import { afterAll } from "bun:test";
+
+afterAll(async () => {
+ if (!process.env.DATABASE_URL) return;
+ const { db } = await import("@crm/db");
+ await db.$disconnect();
+});
diff --git a/apps/api/turbo.json b/apps/api/turbo.json
index 8a3d1922..04699fe5 100644
--- a/apps/api/turbo.json
+++ b/apps/api/turbo.json
@@ -15,6 +15,7 @@
"outputs": ["src/generated/**"]
},
"dev": {
+ "dependsOn": ["$TURBO_EXTENDS$"],
"cache": false,
"persistent": true,
"passThroughEnv": [
diff --git a/docs/telemetry.md b/docs/telemetry.md
index aa303241..bb3aa7e2 100644
--- a/docs/telemetry.md
+++ b/docs/telemetry.md
@@ -120,7 +120,7 @@ Each is only whether the key is set. `cap_context_dev` is whether an `AppSetting
| `recheck_interval_days` | Their intervals, in day bands |
| `agent_conversations` | How many `AgentConversation` rows exist |
-Tool names are matched against the twenty-four tools in `apps/agent/agent/tools/` and eve's own
+Tool names are matched against the authored tools in `apps/agent/agent/tools/` and eve's own
builtins. Anything else is counted as `other`. Task kinds are matched against `TASK_KINDS`.
Tool counts are read from the `agentEvent` rows the audit hook already writes — the event `type`
diff --git a/packages/auth/src/auth.ts b/packages/auth/src/auth.ts
index 1e23d22e..8dcd1a3d 100644
--- a/packages/auth/src/auth.ts
+++ b/packages/auth/src/auth.ts
@@ -54,6 +54,7 @@ if (env.microsoft) {
export const auth = betterAuth({
appName: "CRM",
+ baseURL: env.apiUrl,
database: prismaAdapter(db, {
provider: "postgresql",
diff --git a/packages/auth/src/env.ts b/packages/auth/src/env.ts
index 552c6810..87ba1763 100644
--- a/packages/auth/src/env.ts
+++ b/packages/auth/src/env.ts
@@ -53,7 +53,8 @@ const appUrls = (optional("APP_URL") ?? DEFAULT_APP_URL)
const appUrl = appUrls[0] ?? DEFAULT_APP_URL;
export const env = {
- appUrl: apiUrl,
+ apiUrl,
+ appUrl,
google: googleCredentials(),
microsoft: microsoftCredentials(),
cookieDomain: optional("AUTH_COOKIE_DOMAIN"),
diff --git a/packages/auth/test/signed-in.spec.ts b/packages/auth/test/signed-in.spec.ts
index 7c3f84fb..bc9f53f3 100644
--- a/packages/auth/test/signed-in.spec.ts
+++ b/packages/auth/test/signed-in.spec.ts
@@ -30,4 +30,19 @@ describe("the signed-in registry", () => {
await expect(notifySignedIn(USER)).resolves.toBeUndefined();
expect(after).toEqual(["still ran"]);
});
+
+ it("waits for handlers in registration order", async () => {
+ const order: string[] = [];
+ onSignedIn(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ order.push("first");
+ });
+ onSignedIn(() => {
+ order.push("second");
+ });
+
+ await notifySignedIn(USER);
+
+ expect(order).toEqual(["first", "second"]);
+ });
});
diff --git a/packages/db/README.md b/packages/db/README.md
index ce9e0123..e4be5ff7 100644
--- a/packages/db/README.md
+++ b/packages/db/README.md
@@ -36,6 +36,7 @@ CLI works without any app running.
| Script | Purpose |
| ------------- | -------------------------------------------------------- |
| `build` | `prisma generate` — cached by Turborepo, runs via `^build` |
+| `dev:prepare` | Apply pending local migrations, reject drift, and generate Prisma Client |
| `db:generate` | Regenerate Prisma Client |
| `db:migrate` | Create and apply a migration (development) |
| `db:deploy` | Apply pending migrations (CI / production) |
@@ -47,6 +48,11 @@ CLI works without any app running.
Each is also exposed at the repo root (`bun run db:migrate`) and routed through
`turbo run`.
+The root `bun run dev` command runs `dev:prepare` before any service starts and
+reruns it when the schema or migrations change. Services that hold a Prisma
+client restart only after preparation finishes, so they cannot retain an older
+generated model map.
+
## Notes
- **Prisma 7 + driver adapter.** There is no query engine binary; the client
diff --git a/packages/db/package.json b/packages/db/package.json
index 03165419..80d57015 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -15,6 +15,7 @@
"./fields-shape": "./src/fields-shape.ts",
"./fx": "./src/fx.ts",
"./images": "./src/images.ts",
+ "./idempotency": "./src/idempotency.ts",
"./safe-fetch": "./src/safe-fetch.ts",
"./settings": "./src/settings.ts",
"./workspace": "./src/workspace.ts"
@@ -30,7 +31,7 @@
"db:seed": "bun scripts/require-local-db.ts db:seed && prisma db seed",
"db:studio": "prisma studio",
"test": "bun test",
- "dev": "prisma generate --watch",
+ "dev:prepare": "bun scripts/prepare-dev.ts",
"lint": "biome check .",
"postinstall": "prisma generate",
"clean": "rm -rf .turbo node_modules src/generated"
diff --git a/packages/db/prisma/migrations/20260803210000_agent_builder_foundation/migration.sql b/packages/db/prisma/migrations/20260803210000_agent_builder_foundation/migration.sql
new file mode 100644
index 00000000..fd834dd7
--- /dev/null
+++ b/packages/db/prisma/migrations/20260803210000_agent_builder_foundation/migration.sql
@@ -0,0 +1,294 @@
+CREATE TYPE "AgentConversationKind" AS ENUM ('RECORD', 'BUILDER');
+CREATE TYPE "AgentDefinitionStatus" AS ENUM ('DRAFT', 'DEPLOYING', 'LIVE', 'PAUSED', 'ARCHIVED', 'DELETED');
+CREATE TYPE "AgentVersionStatus" AS ENUM ('DRAFT', 'VALIDATING', 'READY', 'DEPLOYED', 'REJECTED');
+CREATE TYPE "AgentTriggerType" AS ENUM ('MANUAL', 'SCHEDULE', 'EVENT', 'WEBHOOK');
+CREATE TYPE "AgentRunStatus" AS ENUM ('QUEUED', 'RUNNING', 'WAITING_FOR_APPROVAL', 'SUCCEEDED', 'FAILED', 'CANCELLED');
+CREATE TYPE "AgentActionStatus" AS ENUM ('PLANNED', 'RUNNING', 'SUCCEEDED', 'FAILED', 'CANCELLED');
+CREATE TYPE "AgentConversationShareScope" AS ENUM ('WORKSPACE_LINK');
+CREATE TYPE "AgentConversationSubmissionStatus" AS ENUM ('PENDING', 'SENDING', 'ACCEPTED', 'FAILED', 'CANCELLED');
+
+CREATE TYPE "AgentResponseRating" AS ENUM ('UP', 'DOWN');
+
+ALTER TABLE "agentConversation"
+ADD COLUMN "kind" "AgentConversationKind" NOT NULL DEFAULT 'RECORD',
+ADD COLUMN "agentId" TEXT,
+ADD COLUMN "updatedAt" TIMESTAMP(3),
+ADD COLUMN "lastAssistantAt" TIMESTAMP(3),
+ADD COLUMN "lastReadAt" TIMESTAMP(3);
+
+ALTER TABLE "agentConversation"
+ALTER COLUMN "sessionId" DROP NOT NULL;
+
+UPDATE "agentConversation"
+SET "updatedAt" = "lastMessageAt";
+
+ALTER TABLE "agentConversation"
+ALTER COLUMN "updatedAt" SET NOT NULL;
+
+CREATE TABLE "agentDefinition" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "status" "AgentDefinitionStatus" NOT NULL DEFAULT 'DRAFT',
+ "createdById" TEXT NOT NULL,
+ "currentVersionId" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ "archivedAt" TIMESTAMP(3),
+ "deletedAt" TIMESTAMP(3),
+
+ CONSTRAINT "agentDefinition_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "agentVersion" (
+ "id" TEXT NOT NULL,
+ "agentId" TEXT NOT NULL,
+ "number" INTEGER NOT NULL,
+ "status" "AgentVersionStatus" NOT NULL DEFAULT 'DRAFT',
+ "instructions" TEXT NOT NULL,
+ "manifest" JSONB NOT NULL,
+ "modelId" TEXT NOT NULL,
+ "sandboxPolicy" JSONB NOT NULL,
+ "validation" JSONB,
+ "sourceConversationId" TEXT,
+ "createdById" TEXT NOT NULL,
+ "deploymentId" TEXT,
+ "approvedAt" TIMESTAMP(3),
+ "deployedAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "agentVersion_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "agentTrigger" (
+ "id" TEXT NOT NULL,
+ "agentId" TEXT NOT NULL,
+ "versionId" TEXT NOT NULL,
+ "type" "AgentTriggerType" NOT NULL,
+ "name" TEXT NOT NULL,
+ "config" JSONB NOT NULL,
+ "createdById" TEXT NOT NULL,
+ "enabled" BOOLEAN NOT NULL DEFAULT false,
+ "nextRunAt" TIMESTAMP(3),
+ "lastRunAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "agentTrigger_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "agentRun" (
+ "id" TEXT NOT NULL,
+ "agentId" TEXT NOT NULL,
+ "versionId" TEXT NOT NULL,
+ "triggerId" TEXT,
+ "initiatedById" TEXT,
+ "triggerType" "AgentTriggerType" NOT NULL,
+ "status" "AgentRunStatus" NOT NULL DEFAULT 'QUEUED',
+ "principalId" TEXT,
+ "sessionId" TEXT,
+ "idempotencyKey" TEXT NOT NULL,
+ "correlationId" TEXT NOT NULL,
+ "input" JSONB,
+ "result" JSONB,
+ "summary" TEXT,
+ "modelId" TEXT,
+ "inputTokens" INTEGER,
+ "outputTokens" INTEGER,
+ "costUsd" DECIMAL(12,6),
+ "errorCode" TEXT,
+ "errorMessage" TEXT,
+ "nextEventSequence" INTEGER NOT NULL DEFAULT 0,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "startedAt" TIMESTAMP(3),
+ "finishedAt" TIMESTAMP(3),
+
+ CONSTRAINT "agentRun_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "agentRunEvent" (
+ "id" TEXT NOT NULL,
+ "runId" TEXT NOT NULL,
+ "sequence" INTEGER NOT NULL,
+ "type" TEXT NOT NULL,
+ "data" JSONB NOT NULL,
+ "emittedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "agentRunEvent_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "agentAction" (
+ "id" TEXT NOT NULL,
+ "agentId" TEXT NOT NULL,
+ "runId" TEXT NOT NULL,
+ "type" TEXT NOT NULL,
+ "provider" TEXT NOT NULL,
+ "targetType" TEXT,
+ "targetId" TEXT,
+ "targetLabel" TEXT,
+ "summary" TEXT NOT NULL,
+ "metadata" JSONB,
+ "status" "AgentActionStatus" NOT NULL DEFAULT 'PLANNED',
+ "idempotencyKey" TEXT NOT NULL,
+ "requestHash" TEXT,
+ "externalId" TEXT,
+ "attemptCount" INTEGER NOT NULL DEFAULT 0,
+ "errorCode" TEXT,
+ "errorMessage" TEXT,
+ "plannedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "startedAt" TIMESTAMP(3),
+ "completedAt" TIMESTAMP(3),
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "agentAction_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "agentAuditEvent" (
+ "id" TEXT NOT NULL,
+ "agentId" TEXT NOT NULL,
+ "versionId" TEXT,
+ "actorUserId" TEXT,
+ "type" TEXT NOT NULL,
+ "actorType" TEXT NOT NULL,
+ "actorId" TEXT,
+ "summary" TEXT NOT NULL,
+ "before" JSONB,
+ "after" JSONB,
+ "requestId" TEXT,
+ "emittedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "agentAuditEvent_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "agentConversationShare" (
+ "id" TEXT NOT NULL,
+ "conversationId" TEXT NOT NULL,
+ "createdById" TEXT NOT NULL,
+ "scope" "AgentConversationShareScope" NOT NULL DEFAULT 'WORKSPACE_LINK',
+ "tokenHash" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "expiresAt" TIMESTAMP(3),
+ "revokedAt" TIMESTAMP(3),
+
+ CONSTRAINT "agentConversationShare_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "agentConversationSubmission" (
+ "id" TEXT NOT NULL,
+ "conversationId" TEXT NOT NULL,
+ "submittedById" TEXT NOT NULL,
+ "clientRequestId" TEXT NOT NULL,
+ "message" JSONB NOT NULL,
+ "status" "AgentConversationSubmissionStatus" NOT NULL DEFAULT 'PENDING',
+ "attemptCount" INTEGER NOT NULL DEFAULT 0,
+ "errorCode" TEXT,
+ "errorMessage" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "sentAt" TIMESTAMP(3),
+ "acceptedAt" TIMESTAMP(3),
+
+ CONSTRAINT "agentConversationSubmission_pkey" PRIMARY KEY ("id")
+);
+
+CREATE TABLE "agentConversationFeedback" (
+ "id" TEXT NOT NULL,
+ "conversationId" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "messageId" TEXT NOT NULL,
+ "rating" "AgentResponseRating" NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "agentConversationFeedback_pkey" PRIMARY KEY ("id")
+);
+
+CREATE UNIQUE INDEX "agentDefinition_currentVersionId_key" ON "agentDefinition"("currentVersionId");
+CREATE UNIQUE INDEX "agentDefinition_currentVersionId_id_key" ON "agentDefinition"("currentVersionId", "id");
+CREATE INDEX "agentDefinition_status_updatedAt_idx" ON "agentDefinition"("status", "updatedAt");
+CREATE INDEX "agentDefinition_createdById_createdAt_idx" ON "agentDefinition"("createdById", "createdAt");
+
+CREATE UNIQUE INDEX "agentVersion_agentId_number_key" ON "agentVersion"("agentId", "number");
+CREATE UNIQUE INDEX "agentVersion_id_agentId_key" ON "agentVersion"("id", "agentId");
+CREATE INDEX "agentVersion_agentId_createdAt_idx" ON "agentVersion"("agentId", "createdAt");
+CREATE INDEX "agentVersion_status_createdAt_idx" ON "agentVersion"("status", "createdAt");
+
+CREATE INDEX "agentTrigger_agentId_enabled_idx" ON "agentTrigger"("agentId", "enabled");
+CREATE INDEX "agentTrigger_enabled_nextRunAt_idx" ON "agentTrigger"("enabled", "nextRunAt");
+CREATE INDEX "agentTrigger_versionId_idx" ON "agentTrigger"("versionId");
+CREATE UNIQUE INDEX "agentTrigger_id_agentId_key" ON "agentTrigger"("id", "agentId");
+
+CREATE UNIQUE INDEX "agentRun_sessionId_key" ON "agentRun"("sessionId");
+CREATE UNIQUE INDEX "agentRun_idempotencyKey_key" ON "agentRun"("idempotencyKey");
+CREATE UNIQUE INDEX "agentRun_correlationId_key" ON "agentRun"("correlationId");
+CREATE INDEX "agentRun_agentId_createdAt_idx" ON "agentRun"("agentId", "createdAt");
+CREATE INDEX "agentRun_versionId_createdAt_idx" ON "agentRun"("versionId", "createdAt");
+CREATE INDEX "agentRun_status_createdAt_idx" ON "agentRun"("status", "createdAt");
+CREATE INDEX "agentRun_triggerId_createdAt_idx" ON "agentRun"("triggerId", "createdAt");
+CREATE UNIQUE INDEX "agentRun_id_agentId_key" ON "agentRun"("id", "agentId");
+
+CREATE UNIQUE INDEX "agentRunEvent_runId_sequence_key" ON "agentRunEvent"("runId", "sequence");
+CREATE INDEX "agentRunEvent_runId_emittedAt_idx" ON "agentRunEvent"("runId", "emittedAt");
+
+CREATE UNIQUE INDEX "agentAction_idempotencyKey_key" ON "agentAction"("idempotencyKey");
+CREATE INDEX "agentAction_agentId_plannedAt_idx" ON "agentAction"("agentId", "plannedAt");
+CREATE INDEX "agentAction_runId_plannedAt_idx" ON "agentAction"("runId", "plannedAt");
+CREATE INDEX "agentAction_provider_externalId_idx" ON "agentAction"("provider", "externalId");
+CREATE INDEX "agentAction_status_plannedAt_idx" ON "agentAction"("status", "plannedAt");
+
+CREATE INDEX "agentAuditEvent_agentId_emittedAt_idx" ON "agentAuditEvent"("agentId", "emittedAt");
+CREATE INDEX "agentAuditEvent_versionId_emittedAt_idx" ON "agentAuditEvent"("versionId", "emittedAt");
+CREATE INDEX "agentAuditEvent_actorUserId_emittedAt_idx" ON "agentAuditEvent"("actorUserId", "emittedAt");
+CREATE INDEX "agentAuditEvent_type_emittedAt_idx" ON "agentAuditEvent"("type", "emittedAt");
+
+CREATE UNIQUE INDEX "agentAuditEvent_agentId_type_requestId_key" ON "agentAuditEvent"("agentId", "type", "requestId");
+
+CREATE UNIQUE INDEX "agentConversationShare_tokenHash_key" ON "agentConversationShare"("tokenHash");
+CREATE INDEX "agentConversationShare_conversationId_revokedAt_idx" ON "agentConversationShare"("conversationId", "revokedAt");
+
+CREATE UNIQUE INDEX "agentConversationSubmission_clientRequestId_key" ON "agentConversationSubmission"("clientRequestId");
+CREATE INDEX "agentConversationSubmission_conversationId_createdAt_idx" ON "agentConversationSubmission"("conversationId", "createdAt");
+CREATE INDEX "agentConversationSubmission_status_createdAt_idx" ON "agentConversationSubmission"("status", "createdAt");
+
+CREATE UNIQUE INDEX "agentConversationFeedback_conversationId_userId_messageId_key" ON "agentConversationFeedback"("conversationId", "userId", "messageId");
+
+CREATE INDEX "agentConversationFeedback_conversationId_createdAt_idx" ON "agentConversationFeedback"("conversationId", "createdAt");
+
+CREATE INDEX "agentConversation_userId_kind_lastMessageAt_idx" ON "agentConversation"("userId", "kind", "lastMessageAt");
+CREATE INDEX "agentConversation_agentId_lastMessageAt_idx" ON "agentConversation"("agentId", "lastMessageAt");
+
+ALTER TABLE "agentDefinition" ADD CONSTRAINT "agentDefinition_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentDefinition" ADD CONSTRAINT "agentDefinition_currentVersionId_id_fkey" FOREIGN KEY ("currentVersionId", "id") REFERENCES "agentVersion"("id", "agentId") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+ALTER TABLE "agentVersion" ADD CONSTRAINT "agentVersion_agentId_fkey" FOREIGN KEY ("agentId") REFERENCES "agentDefinition"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentVersion" ADD CONSTRAINT "agentVersion_sourceConversationId_fkey" FOREIGN KEY ("sourceConversationId") REFERENCES "agentConversation"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ALTER TABLE "agentVersion" ADD CONSTRAINT "agentVersion_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+ALTER TABLE "agentConversation" ADD CONSTRAINT "agentConversation_agentId_fkey" FOREIGN KEY ("agentId") REFERENCES "agentDefinition"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+ALTER TABLE "agentTrigger" ADD CONSTRAINT "agentTrigger_agentId_fkey" FOREIGN KEY ("agentId") REFERENCES "agentDefinition"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentTrigger" ADD CONSTRAINT "agentTrigger_versionId_agentId_fkey" FOREIGN KEY ("versionId", "agentId") REFERENCES "agentVersion"("id", "agentId") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentTrigger" ADD CONSTRAINT "agentTrigger_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+ALTER TABLE "agentRun" ADD CONSTRAINT "agentRun_agentId_fkey" FOREIGN KEY ("agentId") REFERENCES "agentDefinition"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentRun" ADD CONSTRAINT "agentRun_versionId_agentId_fkey" FOREIGN KEY ("versionId", "agentId") REFERENCES "agentVersion"("id", "agentId") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentRun" ADD CONSTRAINT "agentRun_triggerId_agentId_fkey" FOREIGN KEY ("triggerId", "agentId") REFERENCES "agentTrigger"("id", "agentId") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentRun" ADD CONSTRAINT "agentRun_initiatedById_fkey" FOREIGN KEY ("initiatedById") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+ALTER TABLE "agentRunEvent" ADD CONSTRAINT "agentRunEvent_runId_fkey" FOREIGN KEY ("runId") REFERENCES "agentRun"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+ALTER TABLE "agentAction" ADD CONSTRAINT "agentAction_agentId_fkey" FOREIGN KEY ("agentId") REFERENCES "agentDefinition"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentAction" ADD CONSTRAINT "agentAction_runId_agentId_fkey" FOREIGN KEY ("runId", "agentId") REFERENCES "agentRun"("id", "agentId") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+ALTER TABLE "agentAuditEvent" ADD CONSTRAINT "agentAuditEvent_agentId_fkey" FOREIGN KEY ("agentId") REFERENCES "agentDefinition"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentAuditEvent" ADD CONSTRAINT "agentAuditEvent_versionId_agentId_fkey" FOREIGN KEY ("versionId", "agentId") REFERENCES "agentVersion"("id", "agentId") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "agentAuditEvent" ADD CONSTRAINT "agentAuditEvent_actorUserId_fkey" FOREIGN KEY ("actorUserId") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+ALTER TABLE "agentConversationShare" ADD CONSTRAINT "agentConversationShare_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "agentConversation"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+ALTER TABLE "agentConversationShare" ADD CONSTRAINT "agentConversationShare_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+ALTER TABLE "agentConversationSubmission" ADD CONSTRAINT "agentConversationSubmission_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "agentConversation"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+ALTER TABLE "agentConversationSubmission" ADD CONSTRAINT "agentConversationSubmission_submittedById_fkey" FOREIGN KEY ("submittedById") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+ALTER TABLE "agentConversationFeedback" ADD CONSTRAINT "agentConversationFeedback_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "agentConversation"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+ALTER TABLE "agentConversationFeedback" ADD CONSTRAINT "agentConversationFeedback_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/db/prisma/migrations/20260804160000_agent_conversation_command_type/migration.sql b/packages/db/prisma/migrations/20260804160000_agent_conversation_command_type/migration.sql
new file mode 100644
index 00000000..3d85d0a3
--- /dev/null
+++ b/packages/db/prisma/migrations/20260804160000_agent_conversation_command_type/migration.sql
@@ -0,0 +1,8 @@
+CREATE TYPE "AgentConversationCommandType" AS ENUM ('CHAT', 'CREATE_AGENT');
+
+ALTER TABLE "agentConversationSubmission"
+ADD COLUMN "commandType" "AgentConversationCommandType" NOT NULL DEFAULT 'CHAT';
+
+UPDATE "agentConversationSubmission"
+SET "commandType" = 'CREATE_AGENT'
+WHERE "message"->>'text' ~* '^\s*/create\s+agent(?:\s|$)';
diff --git a/packages/db/prisma/migrations/20260804210000_agent_builder_artifacts/migration.sql b/packages/db/prisma/migrations/20260804210000_agent_builder_artifacts/migration.sql
new file mode 100644
index 00000000..91a65697
--- /dev/null
+++ b/packages/db/prisma/migrations/20260804210000_agent_builder_artifacts/migration.sql
@@ -0,0 +1,25 @@
+CREATE TYPE "AgentBuilderArtifactStatus" AS ENUM ('WRITING', 'READY');
+
+CREATE TABLE "agentBuilderArtifact" (
+ "id" TEXT NOT NULL,
+ "conversationId" TEXT,
+ "versionId" TEXT,
+ "path" TEXT NOT NULL,
+ "language" TEXT NOT NULL,
+ "content" TEXT NOT NULL,
+ "previousContent" TEXT,
+ "revision" INTEGER NOT NULL,
+ "status" "AgentBuilderArtifactStatus" NOT NULL DEFAULT 'WRITING',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "agentBuilderArtifact_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "agentBuilderArtifact_owner_present" CHECK ("conversationId" IS NOT NULL OR "versionId" IS NOT NULL)
+);
+
+CREATE UNIQUE INDEX "agentBuilderArtifact_conversation_path_revision_key" ON "agentBuilderArtifact"("conversationId", "path", "revision") WHERE "conversationId" IS NOT NULL;
+CREATE UNIQUE INDEX "agentBuilderArtifact_version_path_revision_key" ON "agentBuilderArtifact"("versionId", "path", "revision") WHERE "versionId" IS NOT NULL;
+CREATE INDEX "agentBuilderArtifact_conversationId_createdAt_idx" ON "agentBuilderArtifact"("conversationId", "createdAt");
+CREATE INDEX "agentBuilderArtifact_versionId_path_idx" ON "agentBuilderArtifact"("versionId", "path");
+
+ALTER TABLE "agentBuilderArtifact" ADD CONSTRAINT "agentBuilderArtifact_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "agentConversation"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ALTER TABLE "agentBuilderArtifact" ADD CONSTRAINT "agentBuilderArtifact_versionId_fkey" FOREIGN KEY ("versionId") REFERENCES "agentVersion"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/packages/db/prisma/migrations/20260805130000_builder_submission_concurrency/migration.sql b/packages/db/prisma/migrations/20260805130000_builder_submission_concurrency/migration.sql
new file mode 100644
index 00000000..f32edffc
--- /dev/null
+++ b/packages/db/prisma/migrations/20260805130000_builder_submission_concurrency/migration.sql
@@ -0,0 +1,5 @@
+ALTER TABLE "agentConversationSubmission"
+ADD COLUMN "inputRequestId" TEXT;
+
+CREATE UNIQUE INDEX "agentConversationSubmission_conversationId_inputRequestId_key"
+ON "agentConversationSubmission"("conversationId", "inputRequestId");
diff --git a/packages/db/prisma/migrations/20260805140000_single_active_conversation_share/migration.sql b/packages/db/prisma/migrations/20260805140000_single_active_conversation_share/migration.sql
new file mode 100644
index 00000000..9206d47d
--- /dev/null
+++ b/packages/db/prisma/migrations/20260805140000_single_active_conversation_share/migration.sql
@@ -0,0 +1,19 @@
+WITH ranked_shares AS (
+ SELECT
+ id,
+ ROW_NUMBER() OVER (
+ PARTITION BY "conversationId"
+ ORDER BY "createdAt" DESC, id DESC
+ ) AS position
+ FROM "agentConversationShare"
+ WHERE "revokedAt" IS NULL
+)
+UPDATE "agentConversationShare" AS share
+SET "revokedAt" = NOW()
+FROM ranked_shares
+WHERE share.id = ranked_shares.id
+ AND ranked_shares.position > 1;
+
+CREATE UNIQUE INDEX "agentConversationShare_one_active_per_conversation"
+ON "agentConversationShare"("conversationId")
+WHERE "revokedAt" IS NULL;
diff --git a/packages/db/prisma/migrations/20260805220000_conversation_attachments/migration.sql b/packages/db/prisma/migrations/20260805220000_conversation_attachments/migration.sql
new file mode 100644
index 00000000..126811fd
--- /dev/null
+++ b/packages/db/prisma/migrations/20260805220000_conversation_attachments/migration.sql
@@ -0,0 +1,85 @@
+CREATE TABLE "agentConversationAttachment" (
+ "id" TEXT NOT NULL,
+ "submissionId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "mediaType" TEXT NOT NULL,
+ "size" INTEGER NOT NULL,
+ "content" BYTEA NOT NULL,
+ "position" INTEGER NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "agentConversationAttachment_pkey" PRIMARY KEY ("id")
+);
+
+CREATE INDEX "agentConversationAttachment_submissionId_position_idx"
+ON "agentConversationAttachment"("submissionId", "position");
+
+ALTER TABLE "agentConversationAttachment"
+ADD CONSTRAINT "agentConversationAttachment_submissionId_fkey"
+FOREIGN KEY ("submissionId") REFERENCES "agentConversationSubmission"("id")
+ON DELETE CASCADE ON UPDATE CASCADE;
+
+WITH legacy_attachments AS (
+ SELECT
+ submission.id AS "submissionId",
+ attachment.value,
+ attachment.ordinality,
+ 'legacy_' || md5(submission.id || ':' || attachment.ordinality::text) AS id
+ FROM "agentConversationSubmission" AS submission
+ CROSS JOIN LATERAL jsonb_array_elements(
+ CASE
+ WHEN jsonb_typeof(submission.message -> 'attachments') = 'array'
+ THEN submission.message -> 'attachments'
+ ELSE '[]'::jsonb
+ END
+ ) WITH ORDINALITY AS attachment(value, ordinality)
+ WHERE attachment.value ? 'contentBase64'
+ AND attachment.value ->> 'contentBase64' <> ''
+ AND attachment.value ->> 'contentBase64' ~ '^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$'
+)
+INSERT INTO "agentConversationAttachment" (
+ "id",
+ "submissionId",
+ "name",
+ "mediaType",
+ "size",
+ "content",
+ "position"
+)
+SELECT
+ id,
+ "submissionId",
+ left(COALESCE(NULLIF(value ->> 'name', ''), 'attachment'), 180),
+ left(COALESCE(NULLIF(value ->> 'type', ''), 'application/octet-stream'), 120),
+ octet_length(decode(value ->> 'contentBase64', 'base64')),
+ decode(value ->> 'contentBase64', 'base64'),
+ ordinality - 1
+FROM legacy_attachments;
+
+UPDATE "agentConversationSubmission" AS submission
+SET message = jsonb_set(
+ submission.message,
+ '{attachments}',
+ (
+ SELECT COALESCE(
+ jsonb_agg(
+ CASE
+ WHEN stored.id IS NOT NULL THEN jsonb_build_object(
+ 'id', stored.id,
+ 'name', stored.name,
+ 'type', stored."mediaType",
+ 'size', stored.size
+ )
+ ELSE attachment.value
+ END
+ ORDER BY attachment.ordinality
+ ),
+ '[]'::jsonb
+ )
+ FROM jsonb_array_elements(submission.message -> 'attachments')
+ WITH ORDINALITY AS attachment(value, ordinality)
+ LEFT JOIN "agentConversationAttachment" AS stored
+ ON stored.id = 'legacy_' || md5(submission.id || ':' || attachment.ordinality::text)
+ )
+)
+WHERE jsonb_typeof(submission.message -> 'attachments') = 'array';
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 7034d2c1..fa33726f 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -9,6 +9,7 @@ generator client {
moduleFormat = "esm"
generatedFileExtension = "ts"
importFileExtension = ""
+ previewFeatures = ["partialIndexes"]
}
model User {
@@ -31,6 +32,15 @@ model User {
conversations AgentConversation[] @relation("ConversationOwner")
fieldValues FieldValue[] @relation("FieldValueUser")
+ createdAgentDefinitions AgentDefinition[] @relation("AgentDefinitionCreator")
+ createdAgentVersions AgentVersion[] @relation("AgentVersionCreator")
+ createdAgentTriggers AgentTrigger[] @relation("AgentTriggerCreator")
+ initiatedAgentRuns AgentRun[] @relation("AgentRunInitiator")
+ agentAuditEvents AgentAuditEvent[] @relation("AgentAuditActor")
+ conversationShares AgentConversationShare[] @relation("ConversationShareCreator")
+ conversationSubmissions AgentConversationSubmission[] @relation("ConversationSubmissionAuthor")
+ conversationFeedback AgentConversationFeedback[] @relation("ConversationFeedbackAuthor")
+
members Member[]
invitations Invitation[]
@@ -135,6 +145,79 @@ enum RecordSource {
CALENDAR
}
+enum AgentConversationKind {
+ RECORD
+ BUILDER
+}
+
+enum AgentDefinitionStatus {
+ DRAFT
+ DEPLOYING
+ LIVE
+ PAUSED
+ ARCHIVED
+ DELETED
+}
+
+enum AgentVersionStatus {
+ DRAFT
+ VALIDATING
+ READY
+ DEPLOYED
+ REJECTED
+}
+
+enum AgentBuilderArtifactStatus {
+ WRITING
+ READY
+}
+
+enum AgentTriggerType {
+ MANUAL
+ SCHEDULE
+ EVENT
+ WEBHOOK
+}
+
+enum AgentRunStatus {
+ QUEUED
+ RUNNING
+ WAITING_FOR_APPROVAL
+ SUCCEEDED
+ FAILED
+ CANCELLED
+}
+
+enum AgentActionStatus {
+ PLANNED
+ RUNNING
+ SUCCEEDED
+ FAILED
+ CANCELLED
+}
+
+enum AgentConversationShareScope {
+ WORKSPACE_LINK
+}
+
+enum AgentConversationSubmissionStatus {
+ PENDING
+ SENDING
+ ACCEPTED
+ FAILED
+ CANCELLED
+}
+
+enum AgentConversationCommandType {
+ CHAT
+ CREATE_AGENT
+}
+
+enum AgentResponseRating {
+ UP
+ DOWN
+}
+
model Company {
id String @id @default(cuid())
name String
@@ -355,6 +438,8 @@ model AgentEvent {
model AgentConversation {
id String @id @default(cuid())
+ kind AgentConversationKind @default(RECORD)
+
contactId String?
contact Contact? @relation(fields: [contactId], references: [id], onDelete: Cascade)
companyId String?
@@ -365,22 +450,385 @@ model AgentConversation {
userId String
user User @relation("ConversationOwner", fields: [userId], references: [id], onDelete: Cascade)
- sessionId String @unique
+ agentId String?
+ agent AgentDefinition? @relation(fields: [agentId], references: [id], onDelete: SetNull)
+
+ sessionId String? @unique
continuationToken String?
streamIndex Int @default(0)
title String?
messageCount Int @default(0)
- createdAt DateTime @default(now())
- lastMessageAt DateTime @default(now())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ lastMessageAt DateTime @default(now())
+ lastAssistantAt DateTime?
+ lastReadAt DateTime?
+
+ shares AgentConversationShare[]
+ submissions AgentConversationSubmission[]
+ feedback AgentConversationFeedback[]
+ createdVersions AgentVersion[] @relation("AgentVersionSourceConversation")
+ builderArtifacts AgentBuilderArtifact[]
@@index([contactId, lastMessageAt])
@@index([companyId, lastMessageAt])
@@index([dealId, lastMessageAt])
+ @@index([userId, kind, lastMessageAt])
+ @@index([agentId, lastMessageAt])
@@map("agentConversation")
}
+model AgentConversationFeedback {
+ id String @id @default(cuid())
+
+ conversationId String
+ conversation AgentConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
+
+ userId String
+ user User @relation("ConversationFeedbackAuthor", fields: [userId], references: [id], onDelete: Cascade)
+
+ messageId String
+ rating AgentResponseRating
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([conversationId, userId, messageId])
+ @@index([conversationId, createdAt])
+ @@map("agentConversationFeedback")
+}
+
+model AgentConversationShare {
+ id String @id @default(cuid())
+
+ conversationId String
+ conversation AgentConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
+
+ createdById String
+ createdBy User @relation("ConversationShareCreator", fields: [createdById], references: [id], onDelete: Cascade)
+
+ scope AgentConversationShareScope @default(WORKSPACE_LINK)
+ tokenHash String @unique
+
+ createdAt DateTime @default(now())
+ expiresAt DateTime?
+ revokedAt DateTime?
+
+ @@unique([conversationId], map: "agentConversationShare_one_active_per_conversation", where: { revokedAt: null })
+ @@index([conversationId, revokedAt])
+ @@map("agentConversationShare")
+}
+
+model AgentConversationSubmission {
+ id String @id @default(cuid())
+
+ conversationId String
+ conversation AgentConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
+
+ submittedById String
+ submittedBy User @relation("ConversationSubmissionAuthor", fields: [submittedById], references: [id], onDelete: Restrict)
+
+ clientRequestId String @unique
+ inputRequestId String?
+ commandType AgentConversationCommandType @default(CHAT)
+ message Json
+ status AgentConversationSubmissionStatus @default(PENDING)
+ attemptCount Int @default(0)
+
+ errorCode String?
+ errorMessage String?
+
+ createdAt DateTime @default(now())
+ sentAt DateTime?
+ acceptedAt DateTime?
+
+ attachments AgentConversationAttachment[]
+
+ @@unique([conversationId, inputRequestId])
+ @@index([conversationId, createdAt])
+ @@index([status, createdAt])
+ @@map("agentConversationSubmission")
+}
+
+model AgentConversationAttachment {
+ id String @id @default(cuid())
+
+ submissionId String
+ submission AgentConversationSubmission @relation(fields: [submissionId], references: [id], onDelete: Cascade)
+
+ name String
+ mediaType String
+ size Int
+ content Bytes
+ position Int
+
+ createdAt DateTime @default(now())
+
+ @@index([submissionId, position])
+ @@map("agentConversationAttachment")
+}
+
+model AgentDefinition {
+ id String @id @default(cuid())
+
+ name String
+ description String?
+ status AgentDefinitionStatus @default(DRAFT)
+
+ createdById String
+ createdBy User @relation("AgentDefinitionCreator", fields: [createdById], references: [id], onDelete: Restrict)
+
+ currentVersionId String? @unique
+ currentVersion AgentVersion? @relation("CurrentAgentVersion", fields: [currentVersionId, id], references: [id, agentId], onDelete: Restrict)
+
+ versions AgentVersion[] @relation("AgentVersions")
+ triggers AgentTrigger[]
+ runs AgentRun[]
+ actions AgentAction[]
+ auditEvents AgentAuditEvent[]
+ conversations AgentConversation[]
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ archivedAt DateTime?
+ deletedAt DateTime?
+
+ @@unique([currentVersionId, id])
+ @@index([status, updatedAt])
+ @@index([createdById, createdAt])
+ @@map("agentDefinition")
+}
+
+model AgentVersion {
+ id String @id @default(cuid())
+
+ agentId String
+ agent AgentDefinition @relation("AgentVersions", fields: [agentId], references: [id], onDelete: Restrict)
+
+ number Int
+ status AgentVersionStatus @default(DRAFT)
+
+ instructions String
+ manifest Json
+ modelId String
+ sandboxPolicy Json
+ validation Json?
+
+ sourceConversationId String?
+ sourceConversation AgentConversation? @relation("AgentVersionSourceConversation", fields: [sourceConversationId], references: [id], onDelete: SetNull)
+
+ createdById String
+ createdBy User @relation("AgentVersionCreator", fields: [createdById], references: [id], onDelete: Restrict)
+
+ deploymentId String?
+ approvedAt DateTime?
+ deployedAt DateTime?
+ createdAt DateTime @default(now())
+
+ currentFor AgentDefinition? @relation("CurrentAgentVersion")
+ triggers AgentTrigger[]
+ runs AgentRun[]
+ auditEvents AgentAuditEvent[]
+ builderArtifacts AgentBuilderArtifact[]
+
+ @@unique([agentId, number])
+ @@unique([id, agentId])
+ @@index([agentId, createdAt])
+ @@index([status, createdAt])
+ @@map("agentVersion")
+}
+
+model AgentBuilderArtifact {
+ id String @id @default(cuid())
+
+ conversationId String?
+ conversation AgentConversation? @relation(fields: [conversationId], references: [id], onDelete: SetNull)
+
+ versionId String?
+ version AgentVersion? @relation(fields: [versionId], references: [id], onDelete: SetNull)
+
+ path String
+ language String
+ content String
+ previousContent String?
+ revision Int
+ status AgentBuilderArtifactStatus @default(WRITING)
+ createdAt DateTime @default(now())
+
+ @@unique([conversationId, path, revision], map: "agentBuilderArtifact_conversation_path_revision_key", where: { conversationId: { not: null } })
+ @@unique([versionId, path, revision], map: "agentBuilderArtifact_version_path_revision_key", where: { versionId: { not: null } })
+ @@index([conversationId, createdAt])
+ @@index([versionId, path])
+ @@map("agentBuilderArtifact")
+}
+
+model AgentTrigger {
+ id String @id @default(cuid())
+
+ agentId String
+ agent AgentDefinition @relation(fields: [agentId], references: [id], onDelete: Restrict)
+
+ versionId String
+ version AgentVersion @relation(fields: [versionId, agentId], references: [id, agentId], onDelete: Restrict)
+
+ type AgentTriggerType
+ name String
+ config Json
+
+ createdById String
+ createdBy User @relation("AgentTriggerCreator", fields: [createdById], references: [id], onDelete: Restrict)
+
+ enabled Boolean @default(false)
+ nextRunAt DateTime?
+ lastRunAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ runs AgentRun[]
+
+ @@unique([id, agentId])
+ @@index([agentId, enabled])
+ @@index([enabled, nextRunAt])
+ @@index([versionId])
+ @@map("agentTrigger")
+}
+
+model AgentRun {
+ id String @id @default(cuid())
+
+ agentId String
+ agent AgentDefinition @relation(fields: [agentId], references: [id], onDelete: Restrict)
+
+ versionId String
+ version AgentVersion @relation(fields: [versionId, agentId], references: [id, agentId], onDelete: Restrict)
+
+ triggerId String?
+ trigger AgentTrigger? @relation(fields: [triggerId, agentId], references: [id, agentId], onDelete: Restrict)
+
+ initiatedById String?
+ initiatedBy User? @relation("AgentRunInitiator", fields: [initiatedById], references: [id], onDelete: SetNull)
+
+ triggerType AgentTriggerType
+ status AgentRunStatus @default(QUEUED)
+ principalId String?
+ sessionId String? @unique
+ idempotencyKey String @unique
+ correlationId String @unique
+
+ input Json?
+ result Json?
+ summary String?
+
+ modelId String?
+ inputTokens Int?
+ outputTokens Int?
+ costUsd Decimal? @db.Decimal(12, 6)
+
+ errorCode String?
+ errorMessage String?
+
+ nextEventSequence Int @default(0)
+
+ createdAt DateTime @default(now())
+ startedAt DateTime?
+ finishedAt DateTime?
+
+ events AgentRunEvent[]
+ actions AgentAction[]
+
+ @@unique([id, agentId])
+ @@index([agentId, createdAt])
+ @@index([versionId, createdAt])
+ @@index([status, createdAt])
+ @@index([triggerId, createdAt])
+ @@map("agentRun")
+}
+
+model AgentRunEvent {
+ id String @id @default(cuid())
+
+ runId String
+ run AgentRun @relation(fields: [runId], references: [id], onDelete: Restrict)
+
+ sequence Int
+ type String
+ data Json
+ emittedAt DateTime @default(now())
+
+ @@unique([runId, sequence])
+ @@index([runId, emittedAt])
+ @@map("agentRunEvent")
+}
+
+model AgentAction {
+ id String @id @default(cuid())
+
+ agentId String
+ agent AgentDefinition @relation(fields: [agentId], references: [id], onDelete: Restrict)
+
+ runId String
+ run AgentRun @relation(fields: [runId, agentId], references: [id, agentId], onDelete: Restrict)
+
+ type String
+ provider String
+ targetType String?
+ targetId String?
+ targetLabel String?
+ summary String
+ metadata Json?
+
+ status AgentActionStatus @default(PLANNED)
+ idempotencyKey String @unique
+ requestHash String?
+ externalId String?
+ attemptCount Int @default(0)
+
+ errorCode String?
+ errorMessage String?
+
+ plannedAt DateTime @default(now())
+ startedAt DateTime?
+ completedAt DateTime?
+ updatedAt DateTime @updatedAt
+
+ @@index([agentId, plannedAt])
+ @@index([runId, plannedAt])
+ @@index([provider, externalId])
+ @@index([status, plannedAt])
+ @@map("agentAction")
+}
+
+model AgentAuditEvent {
+ id String @id @default(cuid())
+
+ agentId String
+ agent AgentDefinition @relation(fields: [agentId], references: [id], onDelete: Restrict)
+
+ versionId String?
+ version AgentVersion? @relation(fields: [versionId, agentId], references: [id, agentId], onDelete: Restrict)
+
+ actorUserId String?
+ actorUser User? @relation("AgentAuditActor", fields: [actorUserId], references: [id], onDelete: SetNull)
+
+ type String
+ actorType String
+ actorId String?
+ summary String
+ before Json?
+ after Json?
+ requestId String?
+ emittedAt DateTime @default(now())
+
+ @@unique([agentId, type, requestId])
+ @@index([agentId, emittedAt])
+ @@index([versionId, emittedAt])
+ @@index([actorUserId, emittedAt])
+ @@index([type, emittedAt])
+ @@map("agentAuditEvent")
+}
+
model Deal {
id String @id @default(cuid())
conversations AgentConversation[]
diff --git a/packages/db/scripts/prepare-dev.ts b/packages/db/scripts/prepare-dev.ts
new file mode 100644
index 00000000..7ff09458
--- /dev/null
+++ b/packages/db/scripts/prepare-dev.ts
@@ -0,0 +1,52 @@
+import { join } from "node:path";
+
+const directory = join(import.meta.dir, "..");
+
+await run([process.execPath, "scripts/require-local-db.ts", "dev"]);
+const [migration, generation] = await Promise.all([
+ execute([process.execPath, "run", "prisma", "migrate", "deploy"]),
+ execute([process.execPath, "run", "prisma", "generate"]),
+]);
+
+if (migration !== 0) process.exit(migration);
+if (generation !== 0) process.exit(generation);
+
+const drift = await execute([
+ process.execPath,
+ "run",
+ "prisma",
+ "migrate",
+ "diff",
+ "--from-config-datasource",
+ "--to-schema",
+ "prisma/schema.prisma",
+ "--exit-code",
+]);
+
+if (drift === 2) {
+ console.error(
+ "The database and Prisma schema differ. Reconcile the migration history with `bun run db:migrate` before starting dev.",
+ );
+ process.exit(1);
+}
+
+if (drift !== 0) process.exit(drift);
+
+console.log("Database migrations and generated Prisma client are ready.");
+
+async function run(command: string[]): Promise<void> {
+ const exitCode = await execute(command);
+ if (exitCode !== 0) process.exit(exitCode);
+}
+
+async function execute(command: string[]): Promise<number> {
+ const child = Bun.spawn(command, {
+ cwd: directory,
+ env: process.env,
+ stdin: "inherit",
+ stdout: "inherit",
+ stderr: "inherit",
+ });
+
+ return child.exited;
+}
diff --git a/packages/db/src/idempotency.ts b/packages/db/src/idempotency.ts
new file mode 100644
index 00000000..4c7ac99c
--- /dev/null
+++ b/packages/db/src/idempotency.ts
@@ -0,0 +1,10 @@
+import type { Prisma } from "./generated/prisma/client";
+
+export async function lockIdempotencyKey(
+ tx: Prisma.TransactionClient,
+ key: string,
+): Promise<void> {
+ await tx.$queryRaw<Array<{ locked: boolean }>>`
+ SELECT pg_advisory_xact_lock(hashtextextended(${key}, 0)) IS NULL AS locked
+ `;
+}
diff --git a/packages/db/src/workspace.ts b/packages/db/src/workspace.ts
index c7053329..c3a7ffc7 100644
--- a/packages/db/src/workspace.ts
+++ b/packages/db/src/workspace.ts
@@ -10,6 +10,9 @@ export const MAX_SLUG = 48;
export const RESERVED_SLUGS: readonly string[] = [
"_next",
"api",
+ "agent",
+ "agents",
+ "chat",
"companies",
"contacts",
"deals",
diff --git a/packages/db/turbo.json b/packages/db/turbo.json
index 2037c345..76cf20af 100644
--- a/packages/db/turbo.json
+++ b/packages/db/turbo.json
@@ -7,10 +7,17 @@
"outputs": ["src/generated/**"],
"passThroughEnv": ["DATABASE_URL"]
},
- "dev": {
+ "dev:prepare": {
"cache": false,
- "persistent": true,
- "passThroughEnv": ["DATABASE_URL"]
+ "inputs": [
+ "prisma/schema.prisma",
+ "prisma/migrations/**",
+ "prisma.config.ts",
+ "scripts/prepare-dev.ts",
+ "scripts/require-local-db.ts"
+ ],
+ "outputs": ["src/generated/**"],
+ "passThroughEnv": ["ALLOW_REMOTE_DB", "DATABASE_URL"]
},
"db:generate": {
"inputs": ["$TURBO_DEFAULT$", "prisma/**"],
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index eaac876e..bb608fd1 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -79,13 +79,14 @@ export function loadRootEnv(): void {
if (!root) return;
const merged: Record<string, string> = {};
+ const runtimeFs = process.getBuiltinModule("node:fs");
for (const file of FILES) {
- const path = join(root, file);
- if (!existsSync(path)) continue;
-
try {
- Object.assign(merged, parseEnv(readFileSync(path, "utf8")));
+ Object.assign(
+ merged,
+ parseEnv(runtimeFs.readFileSync(join(root, file), "utf8")),
+ );
} catch {}
}
diff --git a/packages/env/src/load.ts b/packages/env/src/load.ts
index 322f6b9e..48a11bab 100644
--- a/packages/env/src/load.ts
+++ b/packages/env/src/load.ts
@@ -1,3 +1,4 @@
-import { loadRootEnv } from "./index";
-
-loadRootEnv();
+if (process.env.NEXT_RUNTIME === undefined) {
+ const { loadRootEnv } = await import("./index");
+ loadRootEnv();
+}
diff --git a/turbo.json b/turbo.json
index 7b99d88b..a7cd31f1 100644
--- a/turbo.json
+++ b/turbo.json
@@ -87,6 +87,7 @@
"dependsOn": ["topo", "^build"]
},
"dev": {
+ "dependsOn": ["^dev:prepare"],
"cache": false,
"persistent": true
}