Files
PaperClipAI/server/src/routes/built-in-agents.ts
T
DottaandClaude Opus 5.5 6383eb8033 fix(authz): require board authority for agent budget changes on every route (#20213)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Budgets stop agent spending. The budget hard stop is a control-plane
invariant
> - The budget routes (`PATCH /api/agents/:id/budgets`, `PATCH
/api/companies/:id/budgets`) are board-only
> - `PATCH /api/agents/:id` also accepts `budgetMonthlyCents`, and the
configuration service writes the agent budget policy from it. That route
had no board check for the field
> - So an agent, such as a CEO, a manager or the agent itself, can
change a monthly budget without a board user. This is a second route
around a board-only control, like the pause bypass that #20164 fixed
> - This pull request applies the budget route authority to every route
that writes an agent budget, and gives agents the final board-only
denial with a link to the budget page (#20151)
> - The benefit is that only the board changes budgets, and an agent
that asks gets a final answer that it can pass to the person

## Linked Issues or Issue Description

Refs #17857 (earlier fix, now in conflict with master; this PR rebases
it and adds the budget page link). Refs #20164 and #20151 (same pattern
for PATCH status and board-only denials).

**What happened**

An agent can send `PATCH /api/agents/{id}` with `budgetMonthlyCents`.
The route accepts it, and the configuration service writes the agent
budget policy. This works for the agent's own budget and, with update
permission, for other agents. The same field also reaches budget policy
through a configuration rollback, direct agent creation, an immediate
hire and a built-in agent provision. A chat eval
(`budgets-costs.resolve-budget`) found the route.

**Expected behavior**

Only a board user can change an active budget, as on the dedicated
budget routes. An agent gets `403` with code `board_access_required`.
The denial says it is final and links the agent's budget tab
(`/<prefix>/agents/<id>/budgets`) or the company budgets page
(`/<prefix>/activity/budgets`). An agent can still propose a budget in a
hire that waits for board approval. The approving board user activates
it.

**Steps to reproduce**

1. On master, authenticate as an agent of a company (for example the
CEO).
2. Send `PATCH /api/agents/{agentId}` with body `{"budgetMonthlyCents":
5000}`, for its own id or for another agent.
3. See `200`. The agent budget policy changes with no board action.
4. The new route tests reproduce this: on master source they fail with
`expected 200 to be 403`.

## What Changed

- `PATCH /api/agents/:id`: a changed `budgetMonthlyCents` requires a
board actor. An unchanged amount with other edits still works.
- Configuration rollback: a rollback that changes the budget requires a
board actor.
- `POST /api/companies/:id/agents` and an immediate `agent-hires`: a
positive budget requires a board actor. A hire that needs board approval
keeps the proposed budget and does not activate it before approval.
- Built-in agent provision: a budget override requires a board actor.
- `prepareAgentConfiguration` rejects an agent-originated budget change
again (defense in depth). An agent rollback with an unchanged amount
does not rewrite the policy.
- Board writes keep the actual operator identity. The initial hire
budget is saved in the hire transaction.
- `assertBoard` and `boardAccessRequired` take an optional board page.
Budget denials link the agent's budget tab or the company budgets page,
not the general agent profile.
- Agent access map updated.
- This includes the four commits of #17857 (f970f6b01f, 8c06aba41c,
e5682d22fa, b6cd49d4b6), rebased onto master with the conflicts
resolved, then squashed.

## Verification

- Red on master source, same tests: 12 budget tests fail. The PATCH
tests fail with `expected 200 to be 403` for the agent's own budget and
for a CEO on another agent. Built-in provision fails with `expected 200
to be 403`. Creation and immediate hire fail with `expected 201 to be
403`.
- Green with the fix: `cd server && npx vitest run
src/__tests__/agent-permissions-routes.test.ts
src/__tests__/built-in-agent-routes.test.ts
src/__tests__/built-in-agents.test.ts
src/__tests__/agent-hire-idempotency-routes.test.ts
src/__tests__/board-access-denial.test.ts
src/__tests__/agent-budget-configuration.test.ts`: 222 passed.
- `src/modules/agent-lifecycle/__tests__/lifecycle.test.ts` (embedded
Postgres): 76 passed.
- `agent-skills-routes`, `agent-adapter-validation-routes`,
`openapi-routes`, `agent-cross-tenant-authz-routes`: 275 passed.
- `node scripts/check-maps.mjs`: passed. `git diff --check`: passed.
- Server `tsc --noEmit`: no errors in changed files. One error in
`native-session-executor.ts` comes from a linked runner build in the
local worktree, not from this change. CI runs the full typecheck.

## Risks

- Agent clients that set an active budget directly now get `403`. They
must propose the budget in an approval-gated hire, or ask a board user.
- Agent creation with no budget or a zero budget is not changed. Pending
hire budgets do not activate before approval.
- Trusted internal plugin provisioning keeps its prior behavior and gets
no board identity.
- No schema or migration change.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code
execution, in Claude Code. The rebased commits from #17857 were first
written with OpenAI `gpt-6.1-sol` through Codex.

## 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
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 02:50:16 -06:00

320 lines
12 KiB
TypeScript

import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import { builtInAgentEmptyMutationSchema, builtInAgentProvisionSchema, builtInAgentResetSchema } from "@paperclipai/shared";
import { validate } from "../middleware/validate.js";
import { forbidden, notFound } from "../errors.js";
import { accessService, instanceSettingsService, logActivity } from "../services/index.js";
import { builtInAgentService } from "../services/built-in-agents.js";
import { authorizationDeniedDetails } from "../services/authorization.js";
import { assertBoard, assertCompanyAccess, COMPANY_BUDGETS_PAGE, getActorInfo } from "./authz.js";
import type { BuiltInAgentState } from "../services/built-in-agents.js";
const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function formatScheduleLabel(trigger: { cronExpression: string; timezone: string } | undefined) {
if (!trigger) return "Weekly schedule";
const parts = trigger.cronExpression.trim().split(/\s+/);
const [minute, hour, , , dayOfWeek] = parts;
const weekdayIndex = dayOfWeek ? Number(dayOfWeek) : Number.NaN;
if (
parts.length === 5
&& /^\d+$/.test(minute ?? "")
&& /^\d+$/.test(hour ?? "")
&& Number.isInteger(weekdayIndex)
&& weekdayIndex >= 0
&& weekdayIndex < WEEKDAY_LABELS.length
) {
return `Weekly · ${WEEKDAY_LABELS[weekdayIndex]} ${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")} ${trigger.timezone}`;
}
return `Weekly · ${trigger.timezone}`;
}
function redactBuiltInAgentListState(state: BuiltInAgentState): BuiltInAgentState {
const definition = {
...state.definition,
defaultInstructions: state.definition.defaultInstructions ? "[file-backed]" : "",
bundle: state.definition.bundle
? {
stockVersion: state.definition.bundle.stockVersion,
instructions: {
entryFile: state.definition.bundle.instructions.entryFile,
files: Object.keys(state.definition.bundle.instructions.files),
},
skill: {
skillKey: state.definition.bundle.skill.skillKey,
displayName: state.definition.bundle.skill.displayName,
slug: state.definition.bundle.skill.slug,
canonicalKey: state.definition.bundle.skill.canonicalKey,
files: Object.keys(state.definition.bundle.skill.files),
},
routine: {
routineKey: state.definition.bundle.routine.routineKey,
title: state.definition.bundle.routine.title,
status: state.definition.bundle.routine.status,
triggerCount: state.definition.bundle.routine.triggers.length,
scheduleLabel: formatScheduleLabel(state.definition.bundle.routine.triggers[0]),
},
}
: undefined,
} as BuiltInAgentState["definition"];
if (!state.agent) return { ...state, definition };
return {
...state,
definition,
agent: {
...state.agent,
adapterConfig: {},
runtimeConfig: {},
},
};
}
export function builtInAgentRoutes(db: Db) {
const router = Router();
const access = accessService(db);
const svc = builtInAgentService(db);
const settings = instanceSettingsService(db);
async function assertBuiltInAgentsEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableBuiltInAgents !== true) {
throw notFound("Built-in agents are not enabled");
}
}
async function assertCanProvisionBuiltInAgents(req: Request, companyId: string) {
assertCompanyAccess(req, companyId);
const decision = await access.decide({
actor: req.actor,
action: "agents:create",
resource: { type: "company", companyId },
});
if (decision.allowed) return;
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
async function assertCanControlBuiltInRoutine(req: Request, companyId: string) {
assertCompanyAccess(req, companyId);
if (req.actor.type !== "board") {
throw forbidden("Only board operators can control built-in routines.");
}
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return;
const allowed = await access.canUser(companyId, req.actor.userId, "tasks:assign");
if (!allowed) {
throw forbidden("Missing permission: tasks:assign");
}
}
async function logBuiltInAgentMutation(
req: Request,
input: {
companyId: string;
action:
| "built_in_agent.provision_requested"
| "built_in_agent.reconcile"
| "built_in_agent.reset"
| "built_in_agent.routine_schedule_enabled"
| "built_in_agent.routine_schedule_disabled"
| "built_in_agent.routine_run_triggered"
| "approval.created";
key: string;
agentId: string | null;
status: string;
approvalId?: string | null;
routineKey?: string | null;
routineRunId?: string | null;
},
) {
const actor = getActorInfo(req);
await logActivity(db, {
companyId: input.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
action: input.action,
entityType: input.action === "approval.created" ? "approval" : "agent",
entityId: input.action === "approval.created" ? input.approvalId ?? input.key : input.agentId ?? input.key,
...(actor.agentId ? { agentId: actor.agentId } : {}),
...(actor.runId ? { runId: actor.runId } : {}),
details: {
key: input.key,
status: input.status,
approvalId: input.approvalId ?? null,
routineKey: input.routineKey ?? null,
routineRunId: input.routineRunId ?? null,
},
});
}
router.get("/companies/:companyId/built-in-agents", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
await assertBuiltInAgentsEnabled();
const states = await svc.list(companyId);
res.json(states.map(redactBuiltInAgentListState));
});
router.get("/companies/:companyId/built-in-agents/:key/status", async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
assertCompanyAccess(req, companyId);
await assertBuiltInAgentsEnabled();
res.json(redactBuiltInAgentListState(await svc.get(companyId, key)));
});
router.post("/companies/:companyId/built-in-agents/:key/reconcile", validate(builtInAgentEmptyMutationSchema), async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
await assertBuiltInAgentsEnabled();
await assertCanProvisionBuiltInAgents(req, companyId);
const state = await svc.ensure(companyId, key);
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.reconcile",
key,
agentId: state.agentId,
status: state.status,
});
res.json(redactBuiltInAgentListState(state));
});
router.post(
"/companies/:companyId/built-in-agents/:key/provision",
validate(builtInAgentProvisionSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
await assertBuiltInAgentsEnabled();
await assertCanProvisionBuiltInAgents(req, companyId);
const actor = getActorInfo(req);
if (req.body.budgetMonthlyCents !== undefined) assertBoard(req, COMPANY_BUDGETS_PAGE);
const result = await svc.provision(companyId, key, req.body, {
requestedByAgentId: actor.actorType === "agent" ? actor.actorId : null,
requestedByUserId: actor.actorType === "user" ? actor.actorId : null,
});
const { state, approval } = result;
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.provision_requested",
key,
agentId: state.agentId,
status: state.status,
});
if (approval) {
await logBuiltInAgentMutation(req, {
companyId,
action: "approval.created",
key,
agentId: state.agentId,
status: approval.status,
approvalId: approval.id,
});
}
res.status(approval ? 202 : 200).json(redactBuiltInAgentListState({ ...state, approval }));
},
);
router.post("/companies/:companyId/built-in-agents/:key/reset", validate(builtInAgentResetSchema), async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
await assertBuiltInAgentsEnabled();
await assertCanProvisionBuiltInAgents(req, companyId);
const state = await svc.reset(companyId, key, req.body, req.actor);
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.reset",
key,
agentId: state.agentId,
status: state.status,
});
res.json(redactBuiltInAgentListState(state));
});
router.post(
"/companies/:companyId/built-in-agents/:key/routines/:routineKey/enable",
validate(builtInAgentEmptyMutationSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
const routineKey = req.params.routineKey as string;
await assertBuiltInAgentsEnabled();
assertCompanyAccess(req, companyId);
await assertCanControlBuiltInRoutine(req, companyId);
const actor = getActorInfo(req);
const state = await svc.enableRoutineSchedule(companyId, key, routineKey, {
agentId: actor.actorType === "agent" ? actor.actorId : null,
userId: actor.actorType === "user" ? actor.actorId : null,
runId: actor.runId ?? null,
});
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.routine_schedule_enabled",
key,
agentId: state.agentId,
status: state.status,
routineKey,
});
res.json(redactBuiltInAgentListState(state));
},
);
router.post(
"/companies/:companyId/built-in-agents/:key/routines/:routineKey/disable",
validate(builtInAgentEmptyMutationSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
const routineKey = req.params.routineKey as string;
await assertBuiltInAgentsEnabled();
assertCompanyAccess(req, companyId);
await assertCanControlBuiltInRoutine(req, companyId);
const actor = getActorInfo(req);
const state = await svc.disableRoutineSchedule(companyId, key, routineKey, {
agentId: actor.actorType === "agent" ? actor.actorId : null,
userId: actor.actorType === "user" ? actor.actorId : null,
runId: actor.runId ?? null,
});
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.routine_schedule_disabled",
key,
agentId: state.agentId,
status: state.status,
routineKey,
});
res.json(redactBuiltInAgentListState(state));
},
);
router.post(
"/companies/:companyId/built-in-agents/:key/routines/:routineKey/run",
validate(builtInAgentEmptyMutationSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
const routineKey = req.params.routineKey as string;
await assertBuiltInAgentsEnabled();
assertCompanyAccess(req, companyId);
const current = await svc.get(companyId, key);
await assertCanControlBuiltInRoutine(req, companyId);
const actor = getActorInfo(req);
const run = await svc.runRoutine(companyId, key, routineKey, {
agentId: actor.actorType === "agent" ? actor.actorId : null,
userId: actor.actorType === "user" ? actor.actorId : null,
runId: actor.runId ?? null,
});
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.routine_run_triggered",
key,
agentId: current.agentId,
status: current.status,
routineKey,
routineRunId: run.id,
});
res.status(202).json(run);
},
);
return router;
}