Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions packages/db/src/migrations/0071_agent_blueprints.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
CREATE TABLE "agent_blueprints" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"name" text NOT NULL,
"description" text,
"role" text DEFAULT 'general' NOT NULL,
"title" text,
"icon" text,
"capabilities" text,
"tags" text[] DEFAULT '{}' NOT NULL,
"adapter_type" text DEFAULT 'process' NOT NULL,
"adapter_config" jsonb DEFAULT '{}' NOT NULL,
"runtime_config" jsonb DEFAULT '{}' NOT NULL,
"budget_monthly_cents" integer DEFAULT 0 NOT NULL,
"permissions" jsonb DEFAULT '{}' NOT NULL,
"instructions_content" text,
"metadata" jsonb,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE INDEX "agent_blueprints_role_idx" ON "agent_blueprints" USING btree ("role");
--> statement-breakpoint
CREATE INDEX "agent_blueprints_name_idx" ON "agent_blueprints" USING btree ("name");
10 changes: 10 additions & 0 deletions packages/db/src/migrations/0072_blueprint_lineage.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- Add lineage tracking columns to agent_blueprints and agents

ALTER TABLE "agent_blueprints"
ADD COLUMN "source_agent_id" uuid,
ADD COLUMN "source_blueprint_id" uuid;

ALTER TABLE "agents"
ADD COLUMN "tags" text[] DEFAULT '{}' NOT NULL,
ADD COLUMN "source_blueprint_id" uuid
REFERENCES "agent_blueprints"("id") ON DELETE SET NULL;
14 changes: 14 additions & 0 deletions packages/db/src/migrations/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,20 @@
"when": 1776780004000,
"tag": "0070_active_run_output_watchdog",
"breakpoints": true
},
{
"idx": 71,
"version": "7",
"when": 1776960000000,
"tag": "0071_agent_blueprints",
"breakpoints": true
},
{
"idx": 72,
"version": "7",
"when": 1776960300000,
"tag": "0072_blueprint_lineage",
"breakpoints": true
}
]
}
38 changes: 38 additions & 0 deletions packages/db/src/schema/agent_blueprints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {
pgTable,
uuid,
text,
integer,
timestamp,
jsonb,
index,
} from "drizzle-orm/pg-core";

export const agentBlueprints = pgTable(
"agent_blueprints",
{
id: uuid("id").primaryKey().defaultRandom(),
name: text("name").notNull(),
description: text("description"),
role: text("role").notNull().default("general"),
title: text("title"),
icon: text("icon"),
capabilities: text("capabilities"),
tags: text("tags").array().notNull().default([]),
adapterType: text("adapter_type").notNull().default("process"),
adapterConfig: jsonb("adapter_config").$type<Record<string, unknown>>().notNull().default({}),
runtimeConfig: jsonb("runtime_config").$type<Record<string, unknown>>().notNull().default({}),
budgetMonthlyCents: integer("budget_monthly_cents").notNull().default(0),
permissions: jsonb("permissions").$type<Record<string, unknown>>().notNull().default({}),
instructionsContent: text("instructions_content"),
metadata: jsonb("metadata").$type<Record<string, unknown>>(),
sourceAgentId: uuid("source_agent_id"),
sourceBlueprintId: uuid("source_blueprint_id"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => ({
roleIdx: index("agent_blueprints_role_idx").on(table.role),
nameIdx: index("agent_blueprints_name_idx").on(table.name),
}),
);
3 changes: 3 additions & 0 deletions packages/db/src/schema/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
} from "drizzle-orm/pg-core";
import { companies } from "./companies.js";
import { environments } from "./environments.js";
import { agentBlueprints } from "./agent_blueprints.js";

export const agents = pgTable(
"agents",
Expand All @@ -27,6 +28,8 @@ export const agents = pgTable(
adapterConfig: jsonb("adapter_config").$type<Record<string, unknown>>().notNull().default({}),
runtimeConfig: jsonb("runtime_config").$type<Record<string, unknown>>().notNull().default({}),
defaultEnvironmentId: uuid("default_environment_id").references(() => environments.id, { onDelete: "set null" }),
tags: text("tags").array().notNull().default([]),
sourceBlueprintId: uuid("source_blueprint_id").references(() => agentBlueprints.id, { onDelete: "set null" }),
budgetMonthlyCents: integer("budget_monthly_cents").notNull().default(0),
spentMonthlyCents: integer("spent_monthly_cents").notNull().default(0),
pauseReason: text("pause_reason"),
Expand Down
1 change: 1 addition & 0 deletions packages/db/src/schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,4 @@ export { pluginDatabaseNamespaces, pluginMigrations } from "./plugin_database.js
export { pluginJobs, pluginJobRuns } from "./plugin_jobs.js";
export { pluginWebhookDeliveries } from "./plugin_webhooks.js";
export { pluginLogs } from "./plugin_logs.js";
export { agentBlueprints } from "./agent_blueprints.js";
7 changes: 7 additions & 0 deletions packages/shared/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -863,6 +863,13 @@ export {
type ListPluginState,
} from "./validators/index.js";

export {
createAgentBlueprintSchema,
updateAgentBlueprintSchema,
type CreateAgentBlueprint,
type UpdateAgentBlueprint,
} from "./validators/index.js";

export { API_PREFIX, API } from "./api.js";
export { normalizeAgentUrlKey, deriveAgentUrlKey, isUuidLike } from "./agent-url-key.js";
export { deriveProjectUrlKey, normalizeProjectUrlKey, hasNonAsciiContent } from "./project-url-key.js";
Expand Down
2 changes: 2 additions & 0 deletions packages/shared/src/types/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,12 @@ export interface Agent {
status: AgentStatus;
reportsTo: string | null;
capabilities: string | null;
tags: string[];
adapterType: AgentAdapterType;
adapterConfig: Record<string, unknown>;
runtimeConfig: Record<string, unknown>;
defaultEnvironmentId?: string | null;
sourceBlueprintId: string | null;
budgetMonthlyCents: number;
spentMonthlyCents: number;
pauseReason: PauseReason | null;
Expand Down
30 changes: 30 additions & 0 deletions packages/shared/src/validators/agent-blueprint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { z } from "zod";
import { AGENT_ROLES, AGENT_ICON_NAMES } from "../constants.js";
import { agentAdapterTypeSchema } from "../adapter-type.js";

export const createAgentBlueprintSchema = z.object({
name: z.string().min(1),
description: z.string().optional().nullable(),
role: z.enum(AGENT_ROLES).optional().default("general"),
title: z.string().optional().nullable(),
icon: z.enum(AGENT_ICON_NAMES).optional().nullable(),
capabilities: z.string().optional().nullable(),
tags: z.array(z.string().min(1)).optional().default([]),
adapterType: agentAdapterTypeSchema,
adapterConfig: z.record(z.unknown()).optional().default({}),
runtimeConfig: z.record(z.unknown()).optional().default({}),
budgetMonthlyCents: z.number().int().nonnegative().optional().default(0),
permissions: z.record(z.unknown()).optional().default({}),
instructionsContent: z.string().optional().nullable(),
metadata: z.record(z.unknown()).optional().nullable(),
sourceAgentId: z.string().uuid().optional().nullable(),
sourceBlueprintId: z.string().uuid().optional().nullable(),
});

export type CreateAgentBlueprint = z.infer<typeof createAgentBlueprintSchema>;

export const updateAgentBlueprintSchema = createAgentBlueprintSchema
.omit({ sourceAgentId: true, sourceBlueprintId: true })
.partial();

export type UpdateAgentBlueprint = z.infer<typeof updateAgentBlueprintSchema>;
2 changes: 2 additions & 0 deletions packages/shared/src/validators/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export const createAgentSchema = z.object({
icon: z.enum(AGENT_ICON_NAMES).optional().nullable(),
reportsTo: z.string().uuid().optional().nullable(),
capabilities: z.string().optional().nullable(),
tags: z.array(z.string().min(1)).optional().default([]),
desiredSkills: z.array(z.string().min(1)).optional(),
adapterType: agentAdapterTypeSchema,
adapterConfig: adapterConfigSchema.optional().default({}),
Expand All @@ -66,6 +67,7 @@ export type CreateAgent = z.infer<typeof createAgentSchema>;
export const createAgentHireSchema = createAgentSchema.extend({
sourceIssueId: z.string().uuid().optional().nullable(),
sourceIssueIds: z.array(z.string().uuid()).optional(),
sourceBlueprintId: z.string().uuid().optional().nullable(),
});

export type CreateAgentHire = z.infer<typeof createAgentHireSchema>;
Expand Down
6 changes: 6 additions & 0 deletions packages/shared/src/validators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,3 +380,9 @@ export {
type SetPluginState,
type ListPluginState,
} from "./plugin.js";
export {
createAgentBlueprintSchema,
updateAgentBlueprintSchema,
type CreateAgentBlueprint,
type UpdateAgentBlueprint,
} from "./agent-blueprint.js";
2 changes: 2 additions & 0 deletions server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { llmRoutes } from "./routes/llms.js";
import { authRoutes } from "./routes/auth.js";
import { assetRoutes } from "./routes/assets.js";
import { accessRoutes } from "./routes/access.js";
import { agentBlueprintRoutes } from "./routes/agent-blueprints.js";
import { pluginRoutes } from "./routes/plugins.js";
import { adapterRoutes } from "./routes/adapters.js";
import { pluginUiStaticRoutes } from "./routes/plugin-ui-static.js";
Expand Down Expand Up @@ -210,6 +211,7 @@ export async function createApp(
api.use(sidebarBadgeRoutes(db));
api.use(sidebarPreferenceRoutes(db));
api.use(inboxDismissalRoutes(db));
api.use(agentBlueprintRoutes(db));
api.use(instanceSettingsRoutes(db));
if (opts.databaseBackupService) {
api.use(instanceDatabaseBackupRoutes(opts.databaseBackupService));
Expand Down
63 changes: 63 additions & 0 deletions server/src/routes/agent-blueprints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { Router } from "express";
import type { Db } from "@paperclipai/db";
import {
createAgentBlueprintSchema,
updateAgentBlueprintSchema,
} from "@paperclipai/shared";
import { validate } from "../middleware/validate.js";
import { assertBoard, assertAuthenticated } from "./authz.js";
import { notFound } from "../errors.js";
import { agentBlueprintService } from "../services/agent-blueprints.js";

export function agentBlueprintRoutes(db: Db) {
const router = Router();
const svc = agentBlueprintService(db);

// Read endpoints are open to both board users and agents (agents need to
// query blueprints when the CEO is asked to hire from a template).
router.get("/blueprints", async (req, res) => {
assertAuthenticated(req);
const search = typeof req.query.search === "string" ? req.query.search : undefined;
const role = typeof req.query.role === "string" ? req.query.role : undefined;
res.json(await svc.list({ search, role }));
});

router.get("/blueprints/:id", async (req, res) => {
assertAuthenticated(req);
const blueprint = await svc.get(req.params.id as string);
if (!blueprint) throw notFound("Blueprint not found");
res.json(blueprint);
});

router.post(
"/blueprints",
validate(createAgentBlueprintSchema),
async (req, res) => {
assertBoard(req);
const blueprint = await svc.create(req.body);
res.status(201).json(blueprint);
},
);

router.patch(
"/blueprints/:id",
validate(updateAgentBlueprintSchema),
async (req, res) => {
assertBoard(req);
const existing = await svc.get(req.params.id as string);
if (!existing) throw notFound("Blueprint not found");
const updated = await svc.update(req.params.id as string, req.body);
res.json(updated);
Comment thread
chewieglass-labs marked this conversation as resolved.
},
);

router.delete("/blueprints/:id", async (req, res) => {
assertBoard(req);
const existing = await svc.get(req.params.id as string);
if (!existing) throw notFound("Blueprint not found");
await svc.delete(req.params.id as string);
res.status(204).end();
});

return router;
}
1 change: 1 addition & 0 deletions server/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ export { llmRoutes } from "./llms.js";
export { accessRoutes } from "./access.js";
export { instanceSettingsRoutes } from "./instance-settings.js";
export { instanceDatabaseBackupRoutes } from "./instance-database-backups.js";
export { agentBlueprintRoutes } from "./agent-blueprints.js";
93 changes: 93 additions & 0 deletions server/src/services/agent-blueprints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import type { Db } from "@paperclipai/db";
import { agentBlueprints } from "@paperclipai/db";
import { and, asc, eq, ilike, or } from "drizzle-orm";
import type { CreateAgentBlueprint, UpdateAgentBlueprint } from "@paperclipai/shared";

export function agentBlueprintService(db: Db) {
return {
async list(opts?: { search?: string; role?: string }) {
const conditions = [];
if (opts?.role) {
conditions.push(eq(agentBlueprints.role, opts.role));
}
if (opts?.search) {
const q = `%${opts.search}%`;
conditions.push(
or(
ilike(agentBlueprints.name, q),
ilike(agentBlueprints.description, q),
ilike(agentBlueprints.capabilities, q),
),
);
}
return db
.select()
.from(agentBlueprints)
.where(conditions.length > 0 ? and(...conditions) : undefined)
.orderBy(asc(agentBlueprints.name));
},

async get(id: string) {
const [row] = await db
.select()
.from(agentBlueprints)
.where(eq(agentBlueprints.id, id));
return row ?? null;
},

async create(input: CreateAgentBlueprint) {
const [row] = await db
.insert(agentBlueprints)
.values({
name: input.name,
description: input.description ?? null,
role: input.role ?? "general",
title: input.title ?? null,
icon: input.icon ?? null,
capabilities: input.capabilities ?? null,
tags: input.tags ?? [],
adapterType: input.adapterType,
adapterConfig: input.adapterConfig ?? {},
runtimeConfig: input.runtimeConfig ?? {},
budgetMonthlyCents: input.budgetMonthlyCents ?? 0,
permissions: input.permissions ?? {},
instructionsContent: input.instructionsContent ?? null,
metadata: input.metadata ?? null,
sourceAgentId: input.sourceAgentId ?? null,
sourceBlueprintId: input.sourceBlueprintId ?? null,
})
.returning();
return row!;
},

async update(id: string, input: UpdateAgentBlueprint) {
const patch: Partial<typeof agentBlueprints.$inferInsert> = {};
if (input.name !== undefined) patch.name = input.name;
if (input.description !== undefined) patch.description = input.description ?? null;
if (input.role !== undefined) patch.role = input.role;
if (input.title !== undefined) patch.title = input.title ?? null;
if (input.icon !== undefined) patch.icon = input.icon ?? null;
if (input.capabilities !== undefined) patch.capabilities = input.capabilities ?? null;
if (input.tags !== undefined) patch.tags = input.tags;
if (input.adapterType !== undefined) patch.adapterType = input.adapterType;
if (input.adapterConfig !== undefined) patch.adapterConfig = input.adapterConfig;
if (input.runtimeConfig !== undefined) patch.runtimeConfig = input.runtimeConfig;
if (input.budgetMonthlyCents !== undefined) patch.budgetMonthlyCents = input.budgetMonthlyCents;
if (input.permissions !== undefined) patch.permissions = input.permissions;
if (input.instructionsContent !== undefined) patch.instructionsContent = input.instructionsContent ?? null;
if (input.metadata !== undefined) patch.metadata = input.metadata ?? null;
patch.updatedAt = new Date();

Comment thread
chewieglass-labs marked this conversation as resolved.
const [row] = await db
.update(agentBlueprints)
.set(patch)
.where(eq(agentBlueprints.id, id))
.returning();
return row ?? null;
},

async delete(id: string) {
await db.delete(agentBlueprints).where(eq(agentBlueprints.id, id));
},
};
}
Loading
Loading