Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
import { and, desc, eq, gte, isNotNull, lte, sql } from "drizzle-orm";
|
2026-03-03 08:45:26 -06:00
|
|
|
import type { Db } from "@paperclipai/db";
|
|
|
|
|
import { activityLog, agents, companies, costEvents, heartbeatRuns, issues, projects } from "@paperclipai/db";
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
import { notFound, unprocessable } from "../errors.js";
|
|
|
|
|
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
export interface CostDateRange {
|
|
|
|
|
from?: Date;
|
|
|
|
|
to?: Date;
|
|
|
|
|
}
|
|
|
|
|
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
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;
|
|
|
|
|
},
|
|
|
|
|
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
summary: async (companyId: string, range?: CostDateRange) => {
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
const company = await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(companies)
|
|
|
|
|
.where(eq(companies.id, companyId))
|
|
|
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
|
|
|
|
|
|
if (!company) throw notFound("Company not found");
|
|
|
|
|
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
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);
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
const utilization =
|
|
|
|
|
company.budgetMonthlyCents > 0
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
? (spendCents / company.budgetMonthlyCents) * 100
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
: 0;
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
companyId,
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
spendCents,
|
|
|
|
|
budgetCents: company.budgetMonthlyCents,
|
|
|
|
|
utilizationPercent: Number(utilization.toFixed(2)),
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
};
|
|
|
|
|
},
|
|
|
|
|
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
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));
|
|
|
|
|
|
2026-02-25 21:35:44 -06:00
|
|
|
const costRows = await db
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
.select({
|
|
|
|
|
agentId: costEvents.agentId,
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
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`,
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
})
|
|
|
|
|
.from(costEvents)
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
.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`));
|
2026-02-25 21:35:44 -06:00
|
|
|
|
|
|
|
|
const runConditions: ReturnType<typeof eq>[] = [eq(heartbeatRuns.companyId, companyId)];
|
|
|
|
|
if (range?.from) runConditions.push(gte(heartbeatRuns.finishedAt, range.from));
|
|
|
|
|
if (range?.to) runConditions.push(lte(heartbeatRuns.finishedAt, range.to));
|
|
|
|
|
|
|
|
|
|
const runRows = await db
|
|
|
|
|
.select({
|
|
|
|
|
agentId: heartbeatRuns.agentId,
|
|
|
|
|
apiRunCount:
|
|
|
|
|
sql<number>`coalesce(sum(case when coalesce((${heartbeatRuns.usageJson} ->> 'billingType'), 'unknown') = 'api' then 1 else 0 end), 0)::int`,
|
|
|
|
|
subscriptionRunCount:
|
|
|
|
|
sql<number>`coalesce(sum(case when coalesce((${heartbeatRuns.usageJson} ->> 'billingType'), 'unknown') = 'subscription' then 1 else 0 end), 0)::int`,
|
|
|
|
|
subscriptionInputTokens:
|
|
|
|
|
sql<number>`coalesce(sum(case when coalesce((${heartbeatRuns.usageJson} ->> 'billingType'), 'unknown') = 'subscription' then coalesce((${heartbeatRuns.usageJson} ->> 'inputTokens')::int, 0) else 0 end), 0)::int`,
|
|
|
|
|
subscriptionOutputTokens:
|
|
|
|
|
sql<number>`coalesce(sum(case when coalesce((${heartbeatRuns.usageJson} ->> 'billingType'), 'unknown') = 'subscription' then coalesce((${heartbeatRuns.usageJson} ->> 'outputTokens')::int, 0) else 0 end), 0)::int`,
|
|
|
|
|
})
|
|
|
|
|
.from(heartbeatRuns)
|
|
|
|
|
.where(and(...runConditions))
|
|
|
|
|
.groupBy(heartbeatRuns.agentId);
|
|
|
|
|
|
|
|
|
|
const runRowsByAgent = new Map(runRows.map((row) => [row.agentId, row]));
|
|
|
|
|
return costRows.map((row) => {
|
|
|
|
|
const runRow = runRowsByAgent.get(row.agentId);
|
|
|
|
|
return {
|
|
|
|
|
...row,
|
|
|
|
|
apiRunCount: runRow?.apiRunCount ?? 0,
|
|
|
|
|
subscriptionRunCount: runRow?.subscriptionRunCount ?? 0,
|
|
|
|
|
subscriptionInputTokens: runRow?.subscriptionInputTokens ?? 0,
|
|
|
|
|
subscriptionOutputTokens: runRow?.subscriptionOutputTokens ?? 0,
|
|
|
|
|
};
|
|
|
|
|
});
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
},
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
|
feat(ui): add resource and usage dashboard (/usage route)
adds a new /usage page that lets board operators see how much each ai
provider is consuming across any date window, with per-model breakdowns,
rolling 5h/24h/7d burn windows, weekly budget bars, and a deficit notch
when projected spend is on track to exceed the monthly budget.
- new GET /companies/:id/costs/by-provider endpoint aggregates cost events
by provider + model with pro-rated billing type splits from heartbeat runs
- new GET /companies/:id/costs/window-spend endpoint returns rolling window
spend (5h, 24h, 7d) per provider with no schema changes
- QuotaBar: reusable boxed-border progress bar with green/yellow/red
threshold fill colors and optional deficit notch
- ProviderQuotaCard: per-provider card showing budget allocation bars,
rolling windows, subscription usage, and model breakdown with token/cost
share overlays
- Usage page: date preset toggles (mtd, 7d, 30d, ytd, all, custom),
provider tabs, 30s polling plus ws invalidation on cost_event
- custom date range blocks queries until both dates are selected and
treats boundaries as local-time (not utc midnight) so full days are
included regardless of timezone
- query key to timestamp is floored to the nearest minute to prevent
cache churn on every 30s refetch tick
2026-03-08 03:18:37 +05:30
|
|
|
byProvider: 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));
|
|
|
|
|
|
|
|
|
|
const costRows = await db
|
|
|
|
|
.select({
|
|
|
|
|
provider: costEvents.provider,
|
|
|
|
|
model: costEvents.model,
|
|
|
|
|
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.provider, costEvents.model)
|
|
|
|
|
.orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`));
|
|
|
|
|
|
|
|
|
|
const runConditions: ReturnType<typeof eq>[] = [eq(heartbeatRuns.companyId, companyId)];
|
2026-03-08 03:35:23 +05:30
|
|
|
if (range?.from) runConditions.push(gte(heartbeatRuns.startedAt, range.from));
|
|
|
|
|
if (range?.to) runConditions.push(lte(heartbeatRuns.startedAt, range.to));
|
feat(ui): add resource and usage dashboard (/usage route)
adds a new /usage page that lets board operators see how much each ai
provider is consuming across any date window, with per-model breakdowns,
rolling 5h/24h/7d burn windows, weekly budget bars, and a deficit notch
when projected spend is on track to exceed the monthly budget.
- new GET /companies/:id/costs/by-provider endpoint aggregates cost events
by provider + model with pro-rated billing type splits from heartbeat runs
- new GET /companies/:id/costs/window-spend endpoint returns rolling window
spend (5h, 24h, 7d) per provider with no schema changes
- QuotaBar: reusable boxed-border progress bar with green/yellow/red
threshold fill colors and optional deficit notch
- ProviderQuotaCard: per-provider card showing budget allocation bars,
rolling windows, subscription usage, and model breakdown with token/cost
share overlays
- Usage page: date preset toggles (mtd, 7d, 30d, ytd, all, custom),
provider tabs, 30s polling plus ws invalidation on cost_event
- custom date range blocks queries until both dates are selected and
treats boundaries as local-time (not utc midnight) so full days are
included regardless of timezone
- query key to timestamp is floored to the nearest minute to prevent
cache churn on every 30s refetch tick
2026-03-08 03:18:37 +05:30
|
|
|
|
|
|
|
|
const runRows = await db
|
|
|
|
|
.select({
|
|
|
|
|
agentId: heartbeatRuns.agentId,
|
|
|
|
|
apiRunCount:
|
|
|
|
|
sql<number>`coalesce(sum(case when coalesce((${heartbeatRuns.usageJson} ->> 'billingType'), 'unknown') = 'api' then 1 else 0 end), 0)::int`,
|
|
|
|
|
subscriptionRunCount:
|
|
|
|
|
sql<number>`coalesce(sum(case when coalesce((${heartbeatRuns.usageJson} ->> 'billingType'), 'unknown') = 'subscription' then 1 else 0 end), 0)::int`,
|
|
|
|
|
subscriptionInputTokens:
|
|
|
|
|
sql<number>`coalesce(sum(case when coalesce((${heartbeatRuns.usageJson} ->> 'billingType'), 'unknown') = 'subscription' then coalesce((${heartbeatRuns.usageJson} ->> 'inputTokens')::int, 0) else 0 end), 0)::int`,
|
|
|
|
|
subscriptionOutputTokens:
|
|
|
|
|
sql<number>`coalesce(sum(case when coalesce((${heartbeatRuns.usageJson} ->> 'billingType'), 'unknown') = 'subscription' then coalesce((${heartbeatRuns.usageJson} ->> 'outputTokens')::int, 0) else 0 end), 0)::int`,
|
|
|
|
|
})
|
|
|
|
|
.from(heartbeatRuns)
|
|
|
|
|
.where(and(...runConditions))
|
|
|
|
|
.groupBy(heartbeatRuns.agentId);
|
|
|
|
|
|
|
|
|
|
// aggregate run billing splits across all agents (runs don't carry model info so we can't go per-model)
|
|
|
|
|
const totals = runRows.reduce(
|
|
|
|
|
(acc, r) => ({
|
|
|
|
|
apiRunCount: acc.apiRunCount + r.apiRunCount,
|
|
|
|
|
subscriptionRunCount: acc.subscriptionRunCount + r.subscriptionRunCount,
|
|
|
|
|
subscriptionInputTokens: acc.subscriptionInputTokens + r.subscriptionInputTokens,
|
|
|
|
|
subscriptionOutputTokens: acc.subscriptionOutputTokens + r.subscriptionOutputTokens,
|
|
|
|
|
}),
|
|
|
|
|
{ apiRunCount: 0, subscriptionRunCount: 0, subscriptionInputTokens: 0, subscriptionOutputTokens: 0 },
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// pro-rate billing split across models by token share
|
|
|
|
|
const totalTokens = costRows.reduce((s, r) => s + r.inputTokens + r.outputTokens, 0);
|
|
|
|
|
|
|
|
|
|
return costRows.map((row) => {
|
|
|
|
|
const rowTokens = row.inputTokens + row.outputTokens;
|
|
|
|
|
const share = totalTokens > 0 ? rowTokens / totalTokens : 0;
|
|
|
|
|
return {
|
|
|
|
|
provider: row.provider,
|
|
|
|
|
model: row.model,
|
|
|
|
|
costCents: row.costCents,
|
|
|
|
|
inputTokens: row.inputTokens,
|
|
|
|
|
outputTokens: row.outputTokens,
|
|
|
|
|
apiRunCount: Math.round(totals.apiRunCount * share),
|
|
|
|
|
subscriptionRunCount: Math.round(totals.subscriptionRunCount * share),
|
|
|
|
|
subscriptionInputTokens: Math.round(totals.subscriptionInputTokens * share),
|
|
|
|
|
subscriptionOutputTokens: Math.round(totals.subscriptionOutputTokens * share),
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* aggregates cost_events by provider for each of three rolling windows:
|
|
|
|
|
* last 5 hours, last 24 hours, last 7 days.
|
|
|
|
|
* purely internal consumption data, no external rate-limit sources.
|
|
|
|
|
*/
|
|
|
|
|
windowSpend: async (companyId: string) => {
|
|
|
|
|
const windows = [
|
|
|
|
|
{ label: "5h", hours: 5 },
|
|
|
|
|
{ label: "24h", hours: 24 },
|
|
|
|
|
{ label: "7d", hours: 168 },
|
|
|
|
|
] as const;
|
|
|
|
|
|
|
|
|
|
const results = await Promise.all(
|
|
|
|
|
windows.map(async ({ label, hours }) => {
|
|
|
|
|
const since = new Date(Date.now() - hours * 60 * 60 * 1000);
|
|
|
|
|
const rows = await db
|
|
|
|
|
.select({
|
|
|
|
|
provider: costEvents.provider,
|
|
|
|
|
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(
|
|
|
|
|
eq(costEvents.companyId, companyId),
|
|
|
|
|
gte(costEvents.occurredAt, since),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.groupBy(costEvents.provider)
|
|
|
|
|
.orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`));
|
|
|
|
|
|
|
|
|
|
return rows.map((row) => ({
|
|
|
|
|
provider: row.provider,
|
|
|
|
|
window: label as string,
|
|
|
|
|
windowHours: hours,
|
|
|
|
|
costCents: row.costCents,
|
|
|
|
|
inputTokens: row.inputTokens,
|
|
|
|
|
outputTokens: row.outputTokens,
|
|
|
|
|
}));
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return results.flat();
|
|
|
|
|
},
|
|
|
|
|
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
byProject: async (companyId: string, range?: CostDateRange) => {
|
2026-02-20 13:47:21 -06:00
|
|
|
const issueIdAsText = sql<string>`${issues.id}::text`;
|
|
|
|
|
const runProjectLinks = db
|
|
|
|
|
.selectDistinctOn([activityLog.runId, issues.projectId], {
|
2026-02-25 21:35:44 -06:00
|
|
|
runId: activityLog.runId,
|
|
|
|
|
projectId: issues.projectId,
|
2026-02-20 13:47:21 -06:00
|
|
|
})
|
|
|
|
|
.from(activityLog)
|
|
|
|
|
.innerJoin(
|
|
|
|
|
issues,
|
|
|
|
|
and(
|
|
|
|
|
eq(activityLog.entityType, "issue"),
|
|
|
|
|
eq(activityLog.entityId, issueIdAsText),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(activityLog.companyId, companyId),
|
|
|
|
|
eq(issues.companyId, companyId),
|
|
|
|
|
isNotNull(activityLog.runId),
|
|
|
|
|
isNotNull(issues.projectId),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.orderBy(activityLog.runId, issues.projectId, desc(activityLog.createdAt))
|
|
|
|
|
.as("run_project_links");
|
|
|
|
|
|
|
|
|
|
const conditions: ReturnType<typeof eq>[] = [eq(heartbeatRuns.companyId, companyId)];
|
|
|
|
|
if (range?.from) conditions.push(gte(heartbeatRuns.finishedAt, range.from));
|
|
|
|
|
if (range?.to) conditions.push(lte(heartbeatRuns.finishedAt, range.to));
|
|
|
|
|
|
|
|
|
|
const costCentsExpr = sql<number>`coalesce(sum(round(coalesce((${heartbeatRuns.usageJson} ->> 'costUsd')::numeric, 0) * 100)), 0)::int`;
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
|
|
|
|
|
return db
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
.select({
|
2026-02-20 13:47:21 -06:00
|
|
|
projectId: runProjectLinks.projectId,
|
|
|
|
|
projectName: projects.name,
|
|
|
|
|
costCents: costCentsExpr,
|
|
|
|
|
inputTokens: sql<number>`coalesce(sum(coalesce((${heartbeatRuns.usageJson} ->> 'inputTokens')::int, 0)), 0)::int`,
|
|
|
|
|
outputTokens: sql<number>`coalesce(sum(coalesce((${heartbeatRuns.usageJson} ->> 'outputTokens')::int, 0)), 0)::int`,
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
})
|
2026-02-20 13:47:21 -06:00
|
|
|
.from(runProjectLinks)
|
|
|
|
|
.innerJoin(heartbeatRuns, eq(runProjectLinks.runId, heartbeatRuns.id))
|
|
|
|
|
.innerJoin(projects, eq(runProjectLinks.projectId, projects.id))
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
.where(and(...conditions))
|
2026-02-20 13:47:21 -06:00
|
|
|
.groupBy(runProjectLinks.projectId, projects.name)
|
|
|
|
|
.orderBy(desc(costCentsExpr));
|
Implement agent hiring, approval workflows, config revisions, LLM reflection, and sidebar badges
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>
2026-02-19 13:02:41 -06:00
|
|
|
},
|
Add server routes for companies, approvals, costs, and dashboard
New routes: companies, approvals, costs, dashboard, authz. New
services: companies, approvals, costs, dashboard, heartbeat,
activity-log. Add auth middleware and structured error handling.
Expand existing agent and issue routes with richer CRUD operations.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 09:07:27 -06:00
|
|
|
};
|
|
|
|
|
}
|