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 { Router } from "express";
|
2026-03-03 08:45:26 -06:00
|
|
|
import type { Db } from "@paperclipai/db";
|
2026-03-14 22:00:12 -05:00
|
|
|
import {
|
|
|
|
|
createCostEventSchema,
|
|
|
|
|
createFinanceEventSchema,
|
|
|
|
|
resolveBudgetIncidentSchema,
|
|
|
|
|
updateBudgetSchema,
|
|
|
|
|
upsertBudgetPolicySchema,
|
|
|
|
|
} from "@paperclipai/shared";
|
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 { validate } from "../middleware/validate.js";
|
2026-03-14 22:00:12 -05:00
|
|
|
import {
|
|
|
|
|
budgetService,
|
|
|
|
|
costService,
|
|
|
|
|
financeService,
|
|
|
|
|
companyService,
|
|
|
|
|
agentService,
|
2026-03-16 08:12:50 -05:00
|
|
|
heartbeatService,
|
2026-03-14 22:00:12 -05:00
|
|
|
logActivity,
|
|
|
|
|
} from "../services/index.js";
|
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 { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
|
2026-03-08 16:35:14 +05:30
|
|
|
import { fetchAllQuotaWindows } from "../services/quota-windows.js";
|
2026-03-08 20:56:13 +05:30
|
|
|
import { badRequest } from "../errors.js";
|
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-04-10 22:26:21 -05:00
|
|
|
export function parseCostDateRange(query: Record<string, unknown>) {
|
|
|
|
|
const fromRaw = query.from as string | undefined;
|
|
|
|
|
const toRaw = query.to as string | undefined;
|
|
|
|
|
const from = fromRaw ? new Date(fromRaw) : undefined;
|
|
|
|
|
const to = toRaw ? new Date(toRaw) : undefined;
|
|
|
|
|
if (from && isNaN(from.getTime())) throw badRequest("invalid 'from' date");
|
|
|
|
|
if (to && isNaN(to.getTime())) throw badRequest("invalid 'to' date");
|
|
|
|
|
return (from || to) ? { from, to } : undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function parseCostLimit(query: Record<string, unknown>) {
|
|
|
|
|
const raw = Array.isArray(query.limit) ? query.limit[0] : query.limit;
|
|
|
|
|
if (raw == null || raw === "") return 100;
|
|
|
|
|
const limit = typeof raw === "number" ? raw : Number.parseInt(String(raw), 10);
|
|
|
|
|
if (!Number.isFinite(limit) || limit <= 0 || limit > 500) {
|
|
|
|
|
throw badRequest("invalid 'limit' value");
|
|
|
|
|
}
|
|
|
|
|
return limit;
|
|
|
|
|
}
|
|
|
|
|
|
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 costRoutes(db: Db) {
|
|
|
|
|
const router = Router();
|
2026-03-16 08:12:50 -05:00
|
|
|
const heartbeat = heartbeatService(db);
|
|
|
|
|
const budgetHooks = {
|
|
|
|
|
cancelWorkForScope: heartbeat.cancelBudgetScopeWork,
|
|
|
|
|
};
|
|
|
|
|
const costs = costService(db, budgetHooks);
|
2026-03-14 22:00:12 -05:00
|
|
|
const finance = financeService(db);
|
2026-03-16 08:12:50 -05:00
|
|
|
const budgets = budgetService(db, budgetHooks);
|
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 companies = companyService(db);
|
|
|
|
|
const agents = agentService(db);
|
|
|
|
|
|
|
|
|
|
router.post("/companies/:companyId/cost-events", validate(createCostEventSchema), async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
|
|
|
|
|
|
|
|
|
if (req.actor.type === "agent" && req.actor.agentId !== req.body.agentId) {
|
|
|
|
|
res.status(403).json({ error: "Agent can only report its own costs" });
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const event = await costs.createEvent(companyId, {
|
|
|
|
|
...req.body,
|
|
|
|
|
occurredAt: new Date(req.body.occurredAt),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const actor = getActorInfo(req);
|
|
|
|
|
await logActivity(db, {
|
|
|
|
|
companyId,
|
|
|
|
|
actorType: actor.actorType,
|
|
|
|
|
actorId: actor.actorId,
|
|
|
|
|
agentId: actor.agentId,
|
|
|
|
|
action: "cost.reported",
|
|
|
|
|
entityType: "cost_event",
|
|
|
|
|
entityId: event.id,
|
|
|
|
|
details: { costCents: event.costCents, model: event.model },
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
res.status(201).json(event);
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-14 22:00:12 -05:00
|
|
|
router.post("/companies/:companyId/finance-events", validate(createFinanceEventSchema), async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
|
|
|
|
assertBoard(req);
|
|
|
|
|
|
|
|
|
|
const event = await finance.createEvent(companyId, {
|
|
|
|
|
...req.body,
|
|
|
|
|
occurredAt: new Date(req.body.occurredAt),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const actor = getActorInfo(req);
|
|
|
|
|
await logActivity(db, {
|
|
|
|
|
companyId,
|
|
|
|
|
actorType: actor.actorType,
|
|
|
|
|
actorId: actor.actorId,
|
|
|
|
|
agentId: actor.agentId,
|
|
|
|
|
action: "finance_event.reported",
|
|
|
|
|
entityType: "finance_event",
|
|
|
|
|
entityId: event.id,
|
|
|
|
|
details: {
|
|
|
|
|
amountCents: event.amountCents,
|
|
|
|
|
biller: event.biller,
|
|
|
|
|
eventKind: event.eventKind,
|
|
|
|
|
direction: event.direction,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
res.status(201).json(event);
|
|
|
|
|
});
|
|
|
|
|
|
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
|
|
|
router.get("/companies/:companyId/costs/summary", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
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 summary = await costs.summary(companyId, range);
|
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
|
|
|
res.json(summary);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
router.get("/companies/:companyId/costs/by-agent", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
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 rows = await costs.byAgent(companyId, range);
|
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
|
|
|
res.json(rows);
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-08 20:56:13 +05:30
|
|
|
router.get("/companies/:companyId/costs/by-agent-model", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
2026-03-08 20:56:13 +05:30
|
|
|
const rows = await costs.byAgentModel(companyId, range);
|
|
|
|
|
res.json(rows);
|
|
|
|
|
});
|
|
|
|
|
|
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
|
|
|
router.get("/companies/:companyId/costs/by-provider", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
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 rows = await costs.byProvider(companyId, range);
|
|
|
|
|
res.json(rows);
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-14 22:00:12 -05:00
|
|
|
router.get("/companies/:companyId/costs/by-biller", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
2026-03-14 22:00:12 -05:00
|
|
|
const rows = await costs.byBiller(companyId, range);
|
|
|
|
|
res.json(rows);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
router.get("/companies/:companyId/costs/finance-summary", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
2026-03-14 22:00:12 -05:00
|
|
|
const summary = await finance.summary(companyId, range);
|
|
|
|
|
res.json(summary);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
router.get("/companies/:companyId/costs/finance-by-biller", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
2026-03-14 22:00:12 -05:00
|
|
|
const rows = await finance.byBiller(companyId, range);
|
|
|
|
|
res.json(rows);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
router.get("/companies/:companyId/costs/finance-by-kind", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
2026-03-14 22:00:12 -05:00
|
|
|
const rows = await finance.byKind(companyId, range);
|
|
|
|
|
res.json(rows);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
router.get("/companies/:companyId/costs/finance-events", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
|
|
|
|
const limit = parseCostLimit(req.query);
|
2026-03-14 22:00:12 -05:00
|
|
|
const rows = await finance.list(companyId, range, limit);
|
|
|
|
|
res.json(rows);
|
|
|
|
|
});
|
|
|
|
|
|
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
|
|
|
router.get("/companies/:companyId/costs/window-spend", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
|
|
|
|
const rows = await costs.windowSpend(companyId);
|
|
|
|
|
res.json(rows);
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-08 16:35:14 +05:30
|
|
|
router.get("/companies/:companyId/costs/quota-windows", async (req, res) => {
|
2026-03-08 19:04:27 +05:30
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-03-08 16:35:14 +05:30
|
|
|
assertBoard(req);
|
2026-03-08 19:18:04 +05:30
|
|
|
// validate companyId resolves to a real company so the "__none__" sentinel
|
|
|
|
|
// and any forged ids are rejected before we touch provider credentials
|
|
|
|
|
const company = await companies.getById(companyId);
|
|
|
|
|
if (!company) {
|
|
|
|
|
res.status(404).json({ error: "Company not found" });
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-03-08 16:35:14 +05:30
|
|
|
const results = await fetchAllQuotaWindows();
|
|
|
|
|
res.json(results);
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-14 22:00:12 -05:00
|
|
|
router.get("/companies/:companyId/budgets/overview", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
|
|
|
|
const overview = await budgets.overview(companyId);
|
|
|
|
|
res.json(overview);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
router.post(
|
|
|
|
|
"/companies/:companyId/budgets/policies",
|
|
|
|
|
validate(upsertBudgetPolicySchema),
|
|
|
|
|
async (req, res) => {
|
|
|
|
|
assertBoard(req);
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
|
|
|
|
const summary = await budgets.upsertPolicy(companyId, req.body, req.actor.userId ?? "board");
|
|
|
|
|
res.json(summary);
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
router.post(
|
|
|
|
|
"/companies/:companyId/budget-incidents/:incidentId/resolve",
|
|
|
|
|
validate(resolveBudgetIncidentSchema),
|
|
|
|
|
async (req, res) => {
|
|
|
|
|
assertBoard(req);
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
const incidentId = req.params.incidentId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
|
|
|
|
const incident = await budgets.resolveIncident(companyId, incidentId, req.body, req.actor.userId ?? "board");
|
|
|
|
|
res.json(incident);
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
|
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
|
|
|
router.get("/companies/:companyId/costs/by-project", async (req, res) => {
|
|
|
|
|
const companyId = req.params.companyId as string;
|
|
|
|
|
assertCompanyAccess(req, companyId);
|
2026-04-10 22:26:21 -05:00
|
|
|
const range = parseCostDateRange(req.query);
|
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 rows = await costs.byProject(companyId, range);
|
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
|
|
|
res.json(rows);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
router.patch("/companies/:companyId/budgets", validate(updateBudgetSchema), async (req, res) => {
|
|
|
|
|
assertBoard(req);
|
|
|
|
|
const companyId = req.params.companyId as string;
|
2026-03-16 15:41:48 -05:00
|
|
|
assertCompanyAccess(req, companyId);
|
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 companies.update(companyId, { budgetMonthlyCents: req.body.budgetMonthlyCents });
|
|
|
|
|
if (!company) {
|
|
|
|
|
res.status(404).json({ error: "Company not found" });
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await logActivity(db, {
|
|
|
|
|
companyId,
|
|
|
|
|
actorType: "user",
|
|
|
|
|
actorId: req.actor.userId ?? "board",
|
|
|
|
|
action: "company.budget_updated",
|
|
|
|
|
entityType: "company",
|
|
|
|
|
entityId: companyId,
|
|
|
|
|
details: { budgetMonthlyCents: req.body.budgetMonthlyCents },
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-14 22:00:12 -05:00
|
|
|
await budgets.upsertPolicy(
|
|
|
|
|
companyId,
|
|
|
|
|
{
|
|
|
|
|
scopeType: "company",
|
|
|
|
|
scopeId: companyId,
|
|
|
|
|
amount: req.body.budgetMonthlyCents,
|
|
|
|
|
windowKind: "calendar_month_utc",
|
|
|
|
|
},
|
|
|
|
|
req.actor.userId ?? "board",
|
|
|
|
|
);
|
|
|
|
|
|
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
|
|
|
res.json(company);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
router.patch("/agents/:agentId/budgets", validate(updateBudgetSchema), async (req, res) => {
|
|
|
|
|
const agentId = req.params.agentId as string;
|
|
|
|
|
const agent = await agents.getById(agentId);
|
|
|
|
|
if (!agent) {
|
|
|
|
|
res.status(404).json({ error: "Agent not found" });
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-16 15:41:48 -05:00
|
|
|
assertCompanyAccess(req, agent.companyId);
|
Harden API route authorization boundaries (#4122)
## Thinking Path
> - Paperclip orchestrates AI agents for zero-human companies.
> - The REST API is the control-plane boundary for companies, agents,
plugins, adapters, costs, invites, and issue mutations.
> - Several routes still relied on broad board or company access checks
without consistently enforcing the narrower actor, company, and
active-checkout boundaries those operations require.
> - That can allow agents or non-admin users to mutate sensitive
resources outside the intended governance path.
> - This pull request hardens the route authorization layer and adds
regression coverage for the audited API surfaces.
> - The benefit is tighter multi-company isolation, safer plugin and
adapter administration, and stronger enforcement of active issue
ownership.
## What Changed
- Added route-level authorization checks for budgets, plugin
administration/scoped routes, adapter management, company import/export,
direct agent creation, invite test resolution, and issue mutation/write
surfaces.
- Enforced active checkout ownership for agent-authenticated issue
mutations, while preserving explicit management overrides for permitted
managers.
- Restricted sensitive adapter and plugin management operations to
instance-admin or properly scoped actors.
- Tightened company portability and invite probing routes so agents
cannot cross company boundaries.
- Updated access constants and the Company Access UI copy for the new
active-checkout management grant.
- Added focused regression tests covering cross-company denial, agent
self-mutation denial, admin-only operations, and active checkout
ownership.
- Rebased the branch onto `public-gh/master` and fixed validation
fallout from the rebase: heartbeat-context route ordering and a company
import/export e2e fixture that now opts out of direct-hire approval
before using direct agent creation.
- Updated onboarding and signoff e2e setup to create seed agents through
`/agent-hires` plus board approval, so they remain compatible with the
approval-gated new-agent default.
- Addressed Greptile feedback by removing a duplicate company export API
alias, avoiding N+1 reporting-chain lookups in active-checkout override
checks, allowing agent mutations on unassigned `in_progress` issues, and
blocking NAT64 invite-probe targets.
## Verification
- `pnpm exec vitest run
server/src/__tests__/issues-goal-context-routes.test.ts
cli/src/__tests__/company-import-export-e2e.test.ts`
- `pnpm exec vitest run server/src/__tests__/plugin-routes-authz.test.ts
server/src/__tests__/adapter-routes-authz.test.ts
server/src/__tests__/agent-permissions-routes.test.ts
server/src/__tests__/company-portability-routes.test.ts
server/src/__tests__/costs-service.test.ts
server/src/__tests__/invite-test-resolution-route.test.ts
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
server/src/__tests__/agent-adapter-validation-routes.test.ts`
- `pnpm exec vitest run
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`
- `pnpm exec vitest run
server/src/__tests__/invite-test-resolution-route.test.ts`
- `pnpm -r typecheck`
- `pnpm --filter server typecheck`
- `pnpm --filter ui typecheck`
- `pnpm build`
- `pnpm test:e2e -- tests/e2e/onboarding.spec.ts
tests/e2e/signoff-policy.spec.ts`
- `pnpm test:e2e -- tests/e2e/signoff-policy.spec.ts`
- `pnpm test:run` was also run. It failed under default full-suite
parallelism with two order-dependent failures in
`plugin-routes-authz.test.ts` and `routines-e2e.test.ts`; both files
passed when rerun directly together with `pnpm exec vitest run
server/src/__tests__/plugin-routes-authz.test.ts
server/src/__tests__/routines-e2e.test.ts`.
## Risks
- Medium risk: this changes authorization behavior across multiple
sensitive API surfaces, so callers that depended on broad board/company
access may now receive `403` or `409` until they use the correct
governance path.
- Direct agent creation now respects the company-level board-approval
requirement; integrations that need pending hires should use
`/api/companies/:companyId/agent-hires`.
- Active in-progress issue mutations now require checkout ownership or
an explicit management override, which may reveal workflow assumptions
in older automation.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
OpenAI Codex, GPT-5 coding agent, tool-using workflow with local shell,
Git, GitHub CLI, and repository tests.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [ ] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-20 10:56:48 -05:00
|
|
|
assertBoard(req);
|
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 updated = await agents.update(agentId, { budgetMonthlyCents: req.body.budgetMonthlyCents });
|
|
|
|
|
if (!updated) {
|
|
|
|
|
res.status(404).json({ error: "Agent not found" });
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const actor = getActorInfo(req);
|
|
|
|
|
await logActivity(db, {
|
|
|
|
|
companyId: updated.companyId,
|
|
|
|
|
actorType: actor.actorType,
|
|
|
|
|
actorId: actor.actorId,
|
|
|
|
|
agentId: actor.agentId,
|
|
|
|
|
action: "agent.budget_updated",
|
|
|
|
|
entityType: "agent",
|
|
|
|
|
entityId: updated.id,
|
|
|
|
|
details: { budgetMonthlyCents: updated.budgetMonthlyCents },
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-14 22:00:12 -05:00
|
|
|
await budgets.upsertPolicy(
|
|
|
|
|
updated.companyId,
|
|
|
|
|
{
|
|
|
|
|
scopeType: "agent",
|
|
|
|
|
scopeId: updated.id,
|
|
|
|
|
amount: updated.budgetMonthlyCents,
|
|
|
|
|
windowKind: "calendar_month_utc",
|
|
|
|
|
},
|
|
|
|
|
req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
|
|
|
|
);
|
|
|
|
|
|
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
|
|
|
res.json(updated);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return router;
|
|
|
|
|
}
|