mirror of
https://github.com/alkimake/paperclip.git
synced 2026-06-17 03:10:38 +09:00
Agent management: hire endpoint with permission gates and pending_approval status, config revision tracking with rollback, agent duplicate route, permission CRUD. Block pending_approval agents from auth, heartbeat, and assignments. Approvals: revision request/resubmit flow, approval comments CRUD, issue-approval linking, auto-wake agents on approval decisions with context snapshot. Costs: per-agent breakdown, period filtering (month/week/day/all), cost by agent list endpoint. Adapters: agentConfigurationDoc on all adapters, /llms/agent-configuration.txt reflection routes. Inject PAPERCLIP_APPROVAL_ID, PAPERCLIP_APPROVAL_STATUS, PAPERCLIP_LINKED_ISSUE_IDS into adapter environments. Sidebar badges endpoint for pending approval/inbox counts. Dashboard and company settings extensions. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
145 lines
4.9 KiB
TypeScript
145 lines
4.9 KiB
TypeScript
import { and, desc, eq, gte, isNotNull, lte, sql } from "drizzle-orm";
|
|
import type { Db } from "@paperclip/db";
|
|
import { agents, companies, costEvents } from "@paperclip/db";
|
|
import { notFound, unprocessable } from "../errors.js";
|
|
|
|
export interface CostDateRange {
|
|
from?: Date;
|
|
to?: Date;
|
|
}
|
|
|
|
export function costService(db: Db) {
|
|
return {
|
|
createEvent: async (companyId: string, data: Omit<typeof costEvents.$inferInsert, "companyId">) => {
|
|
const agent = await db
|
|
.select()
|
|
.from(agents)
|
|
.where(eq(agents.id, data.agentId))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!agent) throw notFound("Agent not found");
|
|
if (agent.companyId !== companyId) {
|
|
throw unprocessable("Agent does not belong to company");
|
|
}
|
|
|
|
const event = await db
|
|
.insert(costEvents)
|
|
.values({ ...data, companyId })
|
|
.returning()
|
|
.then((rows) => rows[0]);
|
|
|
|
await db
|
|
.update(agents)
|
|
.set({
|
|
spentMonthlyCents: sql`${agents.spentMonthlyCents} + ${event.costCents}`,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(agents.id, event.agentId));
|
|
|
|
await db
|
|
.update(companies)
|
|
.set({
|
|
spentMonthlyCents: sql`${companies.spentMonthlyCents} + ${event.costCents}`,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(companies.id, companyId));
|
|
|
|
const updatedAgent = await db
|
|
.select()
|
|
.from(agents)
|
|
.where(eq(agents.id, event.agentId))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (
|
|
updatedAgent &&
|
|
updatedAgent.budgetMonthlyCents > 0 &&
|
|
updatedAgent.spentMonthlyCents >= updatedAgent.budgetMonthlyCents &&
|
|
updatedAgent.status !== "paused" &&
|
|
updatedAgent.status !== "terminated"
|
|
) {
|
|
await db
|
|
.update(agents)
|
|
.set({ status: "paused", updatedAt: new Date() })
|
|
.where(eq(agents.id, updatedAgent.id));
|
|
}
|
|
|
|
return event;
|
|
},
|
|
|
|
summary: async (companyId: string, range?: CostDateRange) => {
|
|
const company = await db
|
|
.select()
|
|
.from(companies)
|
|
.where(eq(companies.id, companyId))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!company) throw notFound("Company not found");
|
|
|
|
const conditions: ReturnType<typeof eq>[] = [eq(costEvents.companyId, companyId)];
|
|
if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));
|
|
if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));
|
|
|
|
const [{ total }] = await db
|
|
.select({
|
|
total: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::int`,
|
|
})
|
|
.from(costEvents)
|
|
.where(and(...conditions));
|
|
|
|
const spendCents = Number(total);
|
|
const utilization =
|
|
company.budgetMonthlyCents > 0
|
|
? (spendCents / company.budgetMonthlyCents) * 100
|
|
: 0;
|
|
|
|
return {
|
|
companyId,
|
|
spendCents,
|
|
budgetCents: company.budgetMonthlyCents,
|
|
utilizationPercent: Number(utilization.toFixed(2)),
|
|
};
|
|
},
|
|
|
|
byAgent: async (companyId: string, range?: CostDateRange) => {
|
|
const conditions: ReturnType<typeof eq>[] = [eq(costEvents.companyId, companyId)];
|
|
if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));
|
|
if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));
|
|
|
|
return db
|
|
.select({
|
|
agentId: costEvents.agentId,
|
|
agentName: agents.name,
|
|
agentStatus: agents.status,
|
|
costCents: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::int`,
|
|
inputTokens: sql<number>`coalesce(sum(${costEvents.inputTokens}), 0)::int`,
|
|
outputTokens: sql<number>`coalesce(sum(${costEvents.outputTokens}), 0)::int`,
|
|
})
|
|
.from(costEvents)
|
|
.leftJoin(agents, eq(costEvents.agentId, agents.id))
|
|
.where(and(...conditions))
|
|
.groupBy(costEvents.agentId, agents.name, agents.status)
|
|
.orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`));
|
|
},
|
|
|
|
byProject: async (companyId: string, range?: CostDateRange) => {
|
|
const conditions: ReturnType<typeof eq>[] = [
|
|
eq(costEvents.companyId, companyId),
|
|
isNotNull(costEvents.projectId),
|
|
];
|
|
if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));
|
|
if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));
|
|
|
|
return db
|
|
.select({
|
|
projectId: costEvents.projectId,
|
|
costCents: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::int`,
|
|
inputTokens: sql<number>`coalesce(sum(${costEvents.inputTokens}), 0)::int`,
|
|
outputTokens: sql<number>`coalesce(sum(${costEvents.outputTokens}), 0)::int`,
|
|
})
|
|
.from(costEvents)
|
|
.where(and(...conditions))
|
|
.groupBy(costEvents.projectId)
|
|
.orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`));
|
|
},
|
|
};
|
|
}
|