mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-10 12:37:55 +01:00
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>
This commit is contained in:
1 parent
b1049b174e
commit
6383eb8033
14 files changed
+226
-41
No files matched your search
@@ -83,7 +83,7 @@ An unfinished record keeps compatibility status `paused` with a
|
||||
`setup` hold and cannot receive API keys or authenticate with keys or JWTs.
|
||||
Its standard grants apply at hire. Authorized completion retries recover the
|
||||
same record and approval without changing the submitted configuration.
|
||||
Normal agent-authored hiring keeps its existing approval policy.
|
||||
Normal agent-authored hiring keeps its existing approval policy. A pending hire may propose a budget, but only board approval activates that policy. Direct creation or an immediate hire with a positive budget requires a board actor.
|
||||
|
||||
An agent-owned plugin may prepare the draft and leave its lifecycle in
|
||||
`verifying` while that setup hold remains. Only bounded Core-issued setup probes
|
||||
@@ -212,6 +212,8 @@ CLI.
|
||||
Policy: Agent creation/configuration uses action grants, resource policies and change
|
||||
consent; some controls require a board actor.
|
||||
|
||||
Changes to the legacy `budgetMonthlyCents` field and built-in provision budget overrides require a board actor, including budget-changing rollbacks.
|
||||
|
||||
The roster intent preserves unrelated settings, rejects stale model/connection
|
||||
previews and harness changes, and checks the full execution configuration under
|
||||
the lifecycle write lock. It uses the same configuration, company, credential,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import type { AgentConfigurationRecord } from "../lib/agent-records.js";
|
||||
import { prepareAgentConfiguration } from "../services/agent-configuration.js";
|
||||
|
||||
const existing = { id: "agent", companyId: "company", status: "idle", budgetMonthlyCents: 500 } as AgentConfigurationRecord;
|
||||
// Preparation queues retention work through the database before reading the patch.
|
||||
const fakeDb = () => ({ execute: async () => [] }) as unknown as Db;
|
||||
describe("budget authority in configuration preparation", () => {
|
||||
it("rejects agent-originated budget changes before persistence or policy audit", async () => {
|
||||
const db = fakeDb();
|
||||
await expect(prepareAgentConfiguration(db, existing, { budgetMonthlyCents: 5000 }, { recordRevision: { createdByAgentId: "ceo" } })).rejects.toMatchObject({ status: 403 });
|
||||
await expect(prepareAgentConfiguration(db, existing, { budgetMonthlyCents: 0 }, { recordRevision: { createdByAgentId: "ceo" } })).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
it("removes an unchanged legacy budget from agent rollback so it cannot rewrite policy or invent a board actor", async () => {
|
||||
expect(await prepareAgentConfiguration(fakeDb(), existing, { budgetMonthlyCents: 500 }, { recordRevision: { createdByAgentId: "ceo", source: "rollback" } })).toEqual({});
|
||||
});
|
||||
it("preserves the actual board-authorized amount for the existing policy writer", async () => {
|
||||
expect(await prepareAgentConfiguration(fakeDb(), existing, { budgetMonthlyCents: 5000 }, { recordRevision: { createdByUserId: "operator-user" } })).toEqual({ budgetMonthlyCents: 5000 });
|
||||
});
|
||||
});
|
||||
@@ -185,11 +185,11 @@ describeEmbeddedPostgres("agent hire idempotency within a run", () => {
|
||||
// Same identity, corrected configuration: the agent meant a different hire.
|
||||
const corrected = await request(app)
|
||||
.post(`/api/companies/${company.id}/agent-hires`)
|
||||
.send({ name: "Sam", role: "engineer", adapterType: "process", budgetMonthlyCents: 5000 });
|
||||
.send({ name: "Sam", role: "engineer", adapterType: "process", title: "Store Builder" });
|
||||
expect(corrected.status, JSON.stringify(corrected.body)).toBe(201);
|
||||
expect(corrected.body.idempotent).toBeUndefined();
|
||||
expect(corrected.body.agent?.id).not.toBe(first.body.agent?.id);
|
||||
expect(corrected.body.agent?.budgetMonthlyCents).toBe(5000);
|
||||
expect(corrected.body.agent?.title).toBe("Store Builder");
|
||||
});
|
||||
|
||||
it("still creates a distinct agent for a different hire in the same run", async () => {
|
||||
|
||||
@@ -2642,6 +2642,80 @@ describe("agent permission routes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["its own budget", agentId, 0],
|
||||
["its own budget", agentId, 5000],
|
||||
["another agent's budget as a CEO", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", 5000],
|
||||
])("budget authority: PATCH /agents/:id never lets an agent change %s (%s, %i)", async (_case, actorAgentId, amount) => {
|
||||
mockAgentService.getById.mockImplementation(async (id: string) => id === agentId
|
||||
? { ...baseAgent, budgetMonthlyCents: 500 }
|
||||
: { ...baseAgent, id, role: "ceo", permissions: { canCreateAgents: true } });
|
||||
const app = createApp({ type: "agent", agentId: actorAgentId, companyId, source: "agent_key", runId: "run-1" });
|
||||
const response = await requestApp(app, url => request(url).patch(`/api/agents/${agentId}`).send({ budgetMonthlyCents: amount }));
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(403);
|
||||
expect(response.body.code).toBe("board_access_required");
|
||||
expect(response.body.remediation).toContain("this denial is final");
|
||||
expect(response.body.remediation).toContain(`[Open the agent's budget](/<prefix>/agents/${agentId}/budgets)`);
|
||||
expect(mockAgentService.update).not.toHaveBeenCalled();
|
||||
expect(mockBudgetService.upsertPolicy).not.toHaveBeenCalled();
|
||||
expect(mockLogActivity).not.toHaveBeenCalled();
|
||||
});
|
||||
it("budget authority: a configuration rollback never lets an agent restore a different budget", async () => {
|
||||
mockAgentService.getById.mockResolvedValue({ ...baseAgent, budgetMonthlyCents: 500 });
|
||||
mockAgentService.getConfigRevision.mockResolvedValue({
|
||||
id: "33333333-3333-4333-8333-333333333333",
|
||||
afterConfig: { adapterType: "process", adapterConfig: {}, runtimeConfig: {}, budgetMonthlyCents: 50000 },
|
||||
});
|
||||
const app = createApp({ type: "agent", agentId, companyId, source: "agent_key", runId: "run-1" });
|
||||
const response = await requestApp(app, url => request(url).post(`/api/agents/${agentId}/config-revisions/33333333-3333-4333-8333-333333333333/rollback`));
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(403);
|
||||
expect(response.body.code).toBe("board_access_required");
|
||||
expect(response.body.remediation).toContain(`[Open the agent's budget](/<prefix>/agents/${agentId}/budgets)`);
|
||||
expect(mockAgentService.rollbackConfigRevision).not.toHaveBeenCalled();
|
||||
});
|
||||
it("budget authority: accepts an unchanged legacy amount with an unrelated title edit", async () => {
|
||||
const app = createApp({ type: "agent", agentId, companyId, source: "agent_key" });
|
||||
const response = await requestApp(app, url => request(url).patch(`/api/agents/${agentId}`).send({ budgetMonthlyCents: 0, title: "New title" }));
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockAgentService.update).toHaveBeenCalled();
|
||||
});
|
||||
it.each(["agents", "agent-hires"])("budget authority: rejects agent immediate creation budgets through %s", async route => {
|
||||
mockAccessService.hasPermission.mockResolvedValue(true);
|
||||
const app = createApp({ type: "agent", agentId, companyId, source: "agent_key" });
|
||||
const response = await requestApp(app, url => request(url).post(`/api/companies/${companyId}/${route}`).send({ name: "New employee", role: "engineer", adapterType: "process", budgetMonthlyCents: 5000 }));
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(403);
|
||||
expect(response.body.code).toBe("board_access_required");
|
||||
expect(response.body.remediation).toContain("[Open budgets](/<prefix>/activity/budgets)");
|
||||
expect(mockAgentService.create).not.toHaveBeenCalled();
|
||||
expect(mockBudgetService.upsertPolicy).not.toHaveBeenCalled();
|
||||
expect(mockLogActivity).not.toHaveBeenCalled();
|
||||
});
|
||||
it("budget authority: preserves a proposed budget without applying a policy before approval", async () => {
|
||||
mockAccessService.hasPermission.mockResolvedValue(true);
|
||||
mockAgentService.create.mockResolvedValue({ ...baseAgent, status: "pending_approval", budgetMonthlyCents: 5000 });
|
||||
mockApprovalService.create.mockResolvedValue({ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", status: "pending", type: "hire_agent", companyId });
|
||||
const app = createApp({ type: "agent", agentId, companyId, source: "agent_key" }, { requireBoardApprovalForNewAgents: true });
|
||||
const response = await requestApp(app, url => request(url).post(`/api/companies/${companyId}/agent-hires`).send({ name: "Proposed employee", role: "engineer", adapterType: "process", budgetMonthlyCents: 5000 }));
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body.approval.status).toBe("pending");
|
||||
expect(mockApprovalService.create).toHaveBeenCalledWith(companyId, expect.objectContaining({ payload: expect.objectContaining({ budgetMonthlyCents: 5000 }) }));
|
||||
expect(mockBudgetService.upsertPolicy).not.toHaveBeenCalled();
|
||||
});
|
||||
it("budget authority: forwards the actual board identity on legacy updates", async () => {
|
||||
const app = createApp({ type: "board", userId: "operator-user", source: "session", companyIds: [companyId] });
|
||||
const response = await requestApp(app, url => request(url).patch(`/api/agents/${agentId}`).send({ budgetMonthlyCents: 5000 }));
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockAgentService.update).toHaveBeenCalledWith(agentId, expect.objectContaining({ budgetMonthlyCents: 5000 }), expect.objectContaining({ recordRevision: expect.objectContaining({ createdByUserId: "operator-user", createdByAgentId: null }) }));
|
||||
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ actorType: "user", actorId: "operator-user", agentId: null }));
|
||||
});
|
||||
it.each(["agents", "agent-hires"])("budget authority: records the real board actor for immediate %s budgets", async route => {
|
||||
mockAgentService.create.mockResolvedValue({ ...baseAgent, budgetMonthlyCents: 5000 });
|
||||
const app = createApp({ type: "board", userId: "operator-user", source: "local_implicit", companyIds: [companyId] });
|
||||
const response = await requestApp(app, url => request(url).post(`/api/companies/${companyId}/${route}`).send({ name: "New employee", role: "engineer", adapterType: "process", budgetMonthlyCents: 5000 }));
|
||||
expect(response.status).toBe(201);
|
||||
expect(mockAgentService.create).toHaveBeenCalledWith(companyId, expect.objectContaining({ budgetMonthlyCents: 5000 }), expect.objectContaining({ createdByUserId: "operator-user" }));
|
||||
expect(mockBudgetService.upsertPolicy).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects heartbeat cancellation outside the caller company scope", async () => {
|
||||
mockHeartbeatService.getRun.mockResolvedValue({
|
||||
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
|
||||
@@ -204,6 +204,16 @@ describe("built-in agent routes", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it.each([0, 5000])("rejects an agent budget override through built-in provision (%s)", async budgetMonthlyCents => {
|
||||
const app = await createApp({ type: "agent", agentId: "agent-1", companyId, source: "agent_key" });
|
||||
const response = await request(app).post(`/api/companies/${companyId}/built-in-agents/briefs/provision`).send({ budgetMonthlyCents });
|
||||
expect(response.status).toBe(403);
|
||||
expect(response.body.code).toBe("board_access_required");
|
||||
expect(response.body.remediation).toContain("[Open budgets](/<prefix>/activity/budgets)");
|
||||
expect(mockBuiltInAgentService.provision).not.toHaveBeenCalled();
|
||||
expect(mockLogActivity).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("denies provision when agents:create is not allowed", async () => {
|
||||
mockAccessService.decide.mockResolvedValue(denyDecision());
|
||||
const app = await createApp({
|
||||
@@ -372,6 +382,7 @@ describe("built-in agent routes", () => {
|
||||
const app = await createApp({
|
||||
type: "agent",
|
||||
agentId: "manager-agent",
|
||||
runId: "native-request-run",
|
||||
companyId,
|
||||
source: "agent_key",
|
||||
});
|
||||
@@ -395,6 +406,7 @@ describe("built-in agent routes", () => {
|
||||
actorType: "agent",
|
||||
actorId: "manager-agent",
|
||||
action: "approval.created",
|
||||
runId: "native-request-run",
|
||||
entityId: "approval-1",
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -266,6 +266,14 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
])).toThrow("defaultAdapterType must be allowed");
|
||||
});
|
||||
|
||||
it("retains the actual operator on a provisioned existing agent budget", async () => {
|
||||
const companyId = await seedCompany({ requireApproval: false });
|
||||
const svc = builtInAgentService(db);
|
||||
const original = await svc.ensure(companyId, "briefs");
|
||||
await svc.provision(companyId, "briefs", { budgetMonthlyCents: 5000 }, { requestedByUserId: "budget-operator" });
|
||||
expect(await db.select().from(budgetPolicies).where(eq(budgetPolicies.scopeId, original.agentId!))).toMatchObject([{ amount: 5000, createdByUserId: "budget-operator" }]);
|
||||
});
|
||||
|
||||
it.each([{ platform: "linux", architecture: "x64" }, { platform: "linux", architecture: "arm64" }, { platform: "darwin", architecture: "arm64" }, { platform: "darwin", architecture: "x64" }])("lazily provisions one agent per company/key and updates the same row on setup ($platform/$architecture)", async ({ platform, architecture }) => {
|
||||
runnerTarget.platform = platform;
|
||||
runnerTarget.architecture = architecture;
|
||||
|
||||
@@ -89,6 +89,7 @@ export type AgentConfigurationPatch = Partial<Pick<typeof agents.$inferInsert, t
|
||||
export type AgentHireRecord = Pick<typeof agents.$inferSelect, "id" | "companyId" | "adapterType" | "adapterConfig" | "permissions" | "metadata" | "status">;
|
||||
|
||||
export interface CreateAgentOptions {
|
||||
initialBudgetPolicyUserId?: string;
|
||||
setupOnly?: boolean;
|
||||
setupAgentId?: string;
|
||||
runnerResolved?: boolean;
|
||||
|
||||
@@ -357,6 +357,49 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
expect((await current(setupId)).lifecycleHolds).toContain("setup");
|
||||
});
|
||||
|
||||
it("saves the immediate hire budget and actual operator audit in its transaction", async () => {
|
||||
const agent = await createAgentLifecycle(db).requestHire(companyId, { name: "Capped hire", adapterType: "process", budgetMonthlyCents: 5000 }, { createdByUserId: "operator-user", initialBudgetPolicyUserId: "operator-user" });
|
||||
expect(await db.select().from(budgetPolicies).where(eq(budgetPolicies.scopeId, agent.id))).toMatchObject([{ amount: 5000 }]);
|
||||
const audit = await db.select().from(activityLog).where(and(eq(activityLog.companyId, companyId), eq(activityLog.action, "budget.policy_upserted")));
|
||||
expect(audit).toMatchObject([{ actorType: "user", actorId: "operator-user", agentId: null }]);
|
||||
});
|
||||
|
||||
it("preserves trusted no-user provisioning without inventing initial board authority", async () => {
|
||||
const agent = await createAgentLifecycle(db).requestHire(companyId, { name: "Internal declared budget", budgetMonthlyCents: 5000 });
|
||||
expect(agent.budgetMonthlyCents).toBe(5000);
|
||||
expect(await db.select().from(budgetPolicies).where(eq(budgetPolicies.scopeId, agent.id))).toHaveLength(0);
|
||||
expect(await db.select().from(activityLog).where(and(eq(activityLog.companyId, companyId), eq(activityLog.action, "budget.policy_upserted")))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("credits only the approving operator for a positive-budget approval without a precreated agent", async () => {
|
||||
const approval = await approvalService(db).create(companyId, { type: "hire_agent", requestedByUserId: "requester", payload: { name: "Approved cap", role: "engineer", budgetMonthlyCents: 5000 } });
|
||||
await approvalService(db).approve(approval.id, "approver");
|
||||
expect(await db.select().from(budgetPolicies).where(eq(budgetPolicies.companyId, companyId))).toMatchObject([{ amount: 5000, createdByUserId: "approver" }]);
|
||||
expect(await db.select().from(activityLog).where(and(eq(activityLog.companyId, companyId), eq(activityLog.action, "budget.policy_upserted")))).toMatchObject([{ actorType: "user", actorId: "approver" }]);
|
||||
});
|
||||
|
||||
it("does not activate a proposed hire budget before human approval", async () => {
|
||||
const agent = await createAgentLifecycle(db).requestHire(companyId, { name: "Proposed cap", status: "pending_approval", budgetMonthlyCents: 5000 }, { createdByUserId: "operator-user", initialBudgetPolicyUserId: "operator-user" });
|
||||
expect(agent.budgetMonthlyCents).toBe(5000);
|
||||
expect(await db.select().from(budgetPolicies).where(eq(budgetPolicies.scopeId, agent.id))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("rolls back the hire, grants, policy and audit together when its initial budget write fails", async () => {
|
||||
const effects = createAgentLifecycleEffects();
|
||||
const setAgentBudget = vi.fn(async (...args: Parameters<typeof effects.setAgentBudget>) => {
|
||||
await effects.setAgentBudget(...args);
|
||||
throw new Error("Initial budget failed");
|
||||
});
|
||||
const lifecycle = createLifecycleCommands(db, { ...effects, setAgentBudget });
|
||||
await expect(lifecycle.requestHire(companyId, { name: "Budget rollback", adapterType: "process", budgetMonthlyCents: 5000 }, { createdByUserId: "operator-user", initialBudgetPolicyUserId: "operator-user" }))
|
||||
.rejects.toThrow("Initial budget failed");
|
||||
expect(setAgentBudget).toHaveBeenCalledWith(expect.anything(), expect.any(Array), companyId, expect.any(String), 5000, "operator-user");
|
||||
expect(await db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(0);
|
||||
expect(await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId))).toHaveLength(0);
|
||||
expect(await db.select().from(budgetPolicies).where(eq(budgetPolicies.companyId, companyId))).toHaveLength(0);
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, companyId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("rolls back a hire and its grants when hire initialization fails", async () => {
|
||||
const effects = createAgentLifecycleEffects();
|
||||
const lifecycle = createLifecycleCommands(db, { ...effects,
|
||||
|
||||
@@ -13,7 +13,7 @@ export function agentRecords(db: Db, effects: LifecycleEffects) {
|
||||
getById,
|
||||
create: async (companyId: string, data: CreateAgentData, options?: CreateAgentOptions) => {
|
||||
if (Object.keys(data).some(key => key.startsWith("lifecycle"))) throw conflict("Lifecycle fields belong to the lifecycle module");
|
||||
return effects.transaction(db, companyId, async (txDb) => {
|
||||
return effects.transaction(db, companyId, async (txDb, publications) => {
|
||||
const tx = txDb;
|
||||
const setupId = options?.setupAgentId ?? (options?.setupOnly ? data.id : undefined);
|
||||
const [setup] = setupId ? await tx.select().from(agents).where(eq(agents.id, setupId)).for("update") : [];
|
||||
@@ -60,6 +60,10 @@ export function agentRecords(db: Db, effects: LifecycleEffects) {
|
||||
.returning()
|
||||
.then((rows) => rows[0]);
|
||||
await effects.initializeHire(txDb, created, options);
|
||||
if (!options?.setupOnly && status !== "pending_approval" && status !== "terminated"
|
||||
&& created.budgetMonthlyCents > 0 && options?.initialBudgetPolicyUserId) {
|
||||
await effects.setAgentBudget(txDb, publications, companyId, created.id, created.budgetMonthlyCents, options.initialBudgetPolicyUserId);
|
||||
}
|
||||
if (!options?.setupOnly && created.status !== "pending_approval" && created.status !== "terminated") {
|
||||
await effects.recordCreation(txDb, companyId, created.id);
|
||||
}
|
||||
|
||||
+25
-24
@@ -140,7 +140,7 @@ import {
|
||||
import { badRequest, conflict, forbidden, HttpError, notFound, unprocessable } from "../errors.js";
|
||||
import { ONBOARDING_FIRST_TASK_SKILL_KEY, PAPERCLIP_CORE_SKILL_KEYS } from "../services/company-skills.js";
|
||||
import { createRunSecretRedactionRegistry } from "../services/run-secret-redaction.js";
|
||||
import { assertAuthenticated, assertBoard, assertCompanyAccess, assertInstanceAdmin, buildActorSecretContext, getAccessibleResource, getActorInfo, hasCompanyAccess } from "./authz.js";
|
||||
import { agentBudgetPage, assertAuthenticated, assertBoard, assertCompanyAccess, COMPANY_BUDGETS_PAGE, assertInstanceAdmin, buildActorSecretContext, getAccessibleResource, getActorInfo, hasCompanyAccess } from "./authz.js";
|
||||
import { runAdapterLoginStartSpine } from "./adapter-login-route-spine.js";
|
||||
import { isLoginCommandSupportedAdapterType } from "../services/login-command.js";
|
||||
import {
|
||||
@@ -4315,6 +4315,9 @@ export function agentRoutes(
|
||||
if (!rollbackConfig) {
|
||||
throw unprocessable("Invalid revision snapshot");
|
||||
}
|
||||
if (typeof rollbackConfig.budgetMonthlyCents === "number" && rollbackConfig.budgetMonthlyCents !== existing.budgetMonthlyCents) {
|
||||
assertBoard(req, agentBudgetPage(existing.id));
|
||||
}
|
||||
assertProviderTraceSettingTransition(
|
||||
req,
|
||||
rollbackConfig.runtimeConfig,
|
||||
@@ -4447,6 +4450,19 @@ export function agentRoutes(
|
||||
const handleAgentHire = async (req: Request, res: Response) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCanCreateAgentsForCompany(req, companyId, { hiring: true });
|
||||
const company = await db
|
||||
.select()
|
||||
.from(companies)
|
||||
.where(eq(companies.id, companyId))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!company) {
|
||||
res.status(404).json({ error: "Company not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Budgets are board-only. An agent may propose one in a hire that waits for
|
||||
// board approval; the approving operator then activates it.
|
||||
if (!company.requireBoardApprovalForNewAgents && req.body.budgetMonthlyCents > 0) assertBoard(req, COMPANY_BUDGETS_PAGE);
|
||||
const sourceIssueIds = parseSourceIssueIds(req.body);
|
||||
const {
|
||||
desiredSkills: requestedDesiredSkills,
|
||||
@@ -4610,16 +4626,6 @@ export function agentRoutes(
|
||||
allowedSandboxProviders: allowedSandboxProvidersForAgent(hireInput.adapterType),
|
||||
});
|
||||
|
||||
const company = await db
|
||||
.select()
|
||||
.from(companies)
|
||||
.where(eq(companies.id, companyId))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!company) {
|
||||
res.status(404).json({ error: "Company not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Idempotency within a run: if this run already created a hire from this
|
||||
// exact request, return that hire instead of creating a duplicate. The
|
||||
// creating agent cannot pause or delete its own hire (board-only), so a
|
||||
@@ -4671,6 +4677,7 @@ export function agentRoutes(
|
||||
{
|
||||
...(setupAgentId ? { setupAgentId } : {}),
|
||||
createdByUserId: req.actor.type === "board" ? req.actor.userId : null,
|
||||
...(req.actor.type === "board" && req.body.budgetMonthlyCents > 0 ? { initialBudgetPolicyUserId: getActorInfo(req).actorId } : {}),
|
||||
runnerResolved: true,
|
||||
responsibleUserId: responsibleUserForAiRequest(req),
|
||||
aiConnectionInstall: managedHireConnection ? { ...managedHireConnection, createdByUserId: responsibleUserForAiRequest(req) } : undefined,
|
||||
@@ -4831,6 +4838,7 @@ export function agentRoutes(
|
||||
router.post("/companies/:companyId/agents", validate(createAgentSchema), async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCanCreateAgentsForCompany(req, companyId, { hiring: true });
|
||||
if (req.body.budgetMonthlyCents > 0) assertBoard(req, COMPANY_BUDGETS_PAGE);
|
||||
|
||||
const company = await db
|
||||
.select()
|
||||
@@ -4952,6 +4960,7 @@ export function agentRoutes(
|
||||
{
|
||||
...(setupId ? { setupOnly: true } : {}),
|
||||
createdByUserId: req.actor.type === "board" ? req.actor.userId : null,
|
||||
...(req.actor.type === "board" && req.body.budgetMonthlyCents > 0 ? { initialBudgetPolicyUserId: getActorInfo(req).actorId } : {}),
|
||||
runnerResolved: true,
|
||||
responsibleUserId: responsibleUserForAiRequest(req),
|
||||
aiConnectionInstall: managedConnection ? { ...managedConnection, createdByUserId: responsibleUserForAiRequest(req) } : undefined,
|
||||
@@ -5014,19 +5023,6 @@ export function agentRoutes(
|
||||
);
|
||||
await builtInAgentService(db).ensureCompanyDefaultAgentGrants(companyId);
|
||||
|
||||
if (agent.budgetMonthlyCents > 0) {
|
||||
await budgets.upsertPolicy(
|
||||
companyId,
|
||||
{
|
||||
scopeType: "agent",
|
||||
scopeId: agent.id,
|
||||
amount: agent.budgetMonthlyCents,
|
||||
windowKind: "calendar_month_utc",
|
||||
},
|
||||
actor.actorType === "user" ? actor.actorId : null,
|
||||
);
|
||||
}
|
||||
|
||||
res.status(201).json({ ...redactAgentRowForResponse(agent), ...(configurationWarnings.length ? { configurationWarnings } : {}) });
|
||||
});
|
||||
|
||||
@@ -5523,6 +5519,11 @@ export function agentRoutes(
|
||||
const id = req.params.id as string;
|
||||
const existing = await getAccessibleResource(req, res, svc.getById(id), "Agent not found");
|
||||
if (!existing) return;
|
||||
// A budget change is the board-only budget control (PATCH /agents/:id/budgets),
|
||||
// so PATCH is never a way around it.
|
||||
if (hasOwn(req.body as object, "budgetMonthlyCents") && req.body.budgetMonthlyCents !== existing.budgetMonthlyCents) {
|
||||
assertBoard(req, agentBudgetPage(existing.id));
|
||||
}
|
||||
|
||||
if (hasOwn(req.body as object, "permissions")) {
|
||||
res.status(422).json({ error: "Use /api/agents/:id/permissions for permission changes" });
|
||||
|
||||
@@ -44,13 +44,22 @@ const AGENT_PROFILE_TABS: Record<string, [string, string]> = {
|
||||
"runtime-state": ["harness settings", "runtime"],
|
||||
};
|
||||
|
||||
/** A board page as [label, path], where the path keeps <prefix> for the agent to fill. */
|
||||
export type BoardControlPage = [label: string, path: string];
|
||||
|
||||
/** Budgets are board-only. These pages hold the budget controls behind any route that writes one. */
|
||||
export const COMPANY_BUDGETS_PAGE: BoardControlPage = ["budgets", "/<prefix>/activity/budgets"];
|
||||
export function agentBudgetPage(agentId: string): BoardControlPage {
|
||||
return [`the agent's ${AGENT_PROFILE_TABS.budgets![0]}`, `/<prefix>/agents/${agentId}/${AGENT_PROFILE_TABS.budgets![1]}`];
|
||||
}
|
||||
|
||||
// The board page that holds the control behind a board-only API route, when one
|
||||
// is known. Paths keep <prefix> for the agent to fill from its own task identifier.
|
||||
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
const BOARD_CONTROL_PAGES: Array<[RegExp, (match: RegExpExecArray, req: Request) => [string, string] | null]> = [
|
||||
[/^\/(?:companies\/[^/]+\/)?secrets?(?:[-/]|$)/, () => ["company secrets", "/<prefix>/company/settings/secrets"]],
|
||||
[/^\/companies\/[^/]+\/(?:budgets|budget-incidents|costs)(?:\/|$)/, () => ["budgets", "/<prefix>/activity/budgets"]],
|
||||
[/^\/companies\/[^/]+\/(?:budgets|budget-incidents|costs)(?:\/|$)/, () => COMPANY_BUDGETS_PAGE],
|
||||
[/^\/companies\/[^/]+\/(?:prompt-injection-prevention|decision-model)(?:\/|$)/, () => ["connection settings", "/<prefix>/company/settings/connections"]],
|
||||
[/^\/companies\/[^/]+\/(?:members|invites|join-requests)(?:\/|$)/, () => ["company members", "/<prefix>/company/settings/members"]],
|
||||
[/^\/companies\/[^/]+\/(?:tools\/)?gateways(?:\/|$)|^\/tool-gateway\//, () => ["tool gateways", "/<prefix>/apps/gateways"]],
|
||||
@@ -105,9 +114,9 @@ function boardControlPage(req: Request) {
|
||||
* A board-only denial. Agents get a final, actionable remediation so they hand the
|
||||
* action to the person instead of searching other routes for one that does not exist.
|
||||
*/
|
||||
export function boardAccessRequired(req: Request) {
|
||||
export function boardAccessRequired(req: Request, controlPage?: BoardControlPage) {
|
||||
if (req.actor.type !== "agent") return forbidden("Board access required");
|
||||
const page = boardControlPage(req);
|
||||
const page = controlPage ?? boardControlPage(req);
|
||||
const scope = PLUGIN_ROUTE.test(deniedApiPath(req)) ? `${PLUGIN_ADMINISTRATION_SCOPE} ` : "";
|
||||
const where = page
|
||||
? `They can do it in the Paperclip web app: link [Open ${page[0]}](${page[1]}), with this conversation's company prefix as <prefix>.`
|
||||
@@ -118,9 +127,13 @@ export function boardAccessRequired(req: Request) {
|
||||
});
|
||||
}
|
||||
|
||||
export function assertBoard(req: Request) {
|
||||
/**
|
||||
* Board-only check. Pass `controlPage` when the board control lives on a different
|
||||
* page from the one the route path implies, e.g. a budget field on a general route.
|
||||
*/
|
||||
export function assertBoard(req: Request, controlPage?: BoardControlPage) {
|
||||
if (req.actor.type !== "board") {
|
||||
throw boardAccessRequired(req);
|
||||
throw boardAccessRequired(req, controlPage);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ 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 { assertCompanyAccess, getActorInfo } from "./authz.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"];
|
||||
@@ -186,6 +186,7 @@ export function builtInAgentRoutes(db: Db) {
|
||||
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,
|
||||
|
||||
@@ -11,7 +11,7 @@ import { and, eq } from "drizzle-orm";
|
||||
import { assets, agentConfigRevisions, agentTaskSessions, agentRuntimeState, type Db } from "@paperclipai/db";
|
||||
import { normalizeAgentUrlKey } from "@paperclipai/shared";
|
||||
import { normalizePaperclipRunnerAdapterConfig } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { conflict, notFound, unprocessable } from "../errors.js";
|
||||
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
||||
import { agentRecordQueries, type UpdateAgentOptions, type AgentConfigurationPatch, type AgentConfigurationRecord, isPlainRecord, buildConfigSnapshot,
|
||||
hasConfigPatchFields, changedPendingApprovalConfigFields, diffConfigSnapshot, jsonEqual } from "../lib/agent-records.js";
|
||||
import { CEO_HIRING_DENIAL_KEY, ceoHiringDenial, normalizeAgentPermissions } from "../lib/agent-permissions.js";
|
||||
@@ -22,6 +22,9 @@ import { clearPrimaryAgent } from "./primary-agent.js";
|
||||
import { budgetServiceInTransaction } from "./budgets.js";
|
||||
|
||||
export async function prepareAgentConfiguration(db: Db, existing: AgentConfigurationRecord, data: AgentConfigurationPatch, options?: UpdateAgentOptions): Promise<AgentConfigurationPatch> {
|
||||
if (options?.recordRevision?.createdByAgentId && data.budgetMonthlyCents !== undefined && data.budgetMonthlyCents !== existing.budgetMonthlyCents) {
|
||||
throw forbidden("Only board operators can change agent budgets");
|
||||
}
|
||||
await notifyAttentionRetentionWork(db, { companyId: existing.companyId });
|
||||
const id = existing.id;
|
||||
const { ensureManager, assertNoCycle, assertCompanyShortnameAvailable, assertBuiltInAgentMetadataMutationAllowed } = agentRecordQueries(db);
|
||||
@@ -65,6 +68,7 @@ export async function prepareAgentConfiguration(db: Db, existing: AgentConfigura
|
||||
}
|
||||
}
|
||||
const normalizedPatch = { ...data } as AgentConfigurationPatch;
|
||||
if (options?.recordRevision?.createdByAgentId) delete normalizedPatch.budgetMonthlyCents;
|
||||
if (data.permissions !== undefined) {
|
||||
// Only the permissions control records a CEO hiring restriction. Keep an
|
||||
// existing one unless this write turns hiring on, and never take one from input.
|
||||
|
||||
@@ -1732,7 +1732,7 @@ export function builtInAgentService(db: Db) {
|
||||
companyId: string,
|
||||
key: string,
|
||||
input: BuiltInAgentProvisionInput = {},
|
||||
options: { isRaceRetry?: boolean; createdByUserId?: string | null } = {},
|
||||
options: { isRaceRetry?: boolean; createdByUserId?: string | null; createdByAgentId?: string | null } = {},
|
||||
) {
|
||||
const definition = requireBuiltInAgentDefinition(key);
|
||||
await ensureCompany(companyId);
|
||||
@@ -1800,7 +1800,7 @@ export function builtInAgentService(db: Db) {
|
||||
}
|
||||
const updated = await agentSvc.update(existing.id, patch, {
|
||||
allowBuiltInAgentMetadata: true,
|
||||
recordRevision: { source: "built-in-agent:ensure" },
|
||||
recordRevision: { source: "built-in-agent:ensure", createdByUserId: options.createdByUserId, createdByAgentId: options.createdByAgentId },
|
||||
});
|
||||
if (!updated) throw notFound("Built-in agent not found");
|
||||
if (existingPendingApproval) {
|
||||
@@ -1835,13 +1835,14 @@ export function builtInAgentService(db: Db) {
|
||||
permissions: definition.defaultPermissions ?? {},
|
||||
spentMonthlyCents: 0,
|
||||
lastHeartbeatAt: null,
|
||||
}, { allowBuiltInAgentMetadata: true, createdByUserId: options.createdByUserId ?? null }) as Agent;
|
||||
}, { allowBuiltInAgentMetadata: true, createdByUserId: options.createdByUserId ?? null,
|
||||
...(options.createdByUserId && resolvedInput.budgetMonthlyCents ? { initialBudgetPolicyUserId: options.createdByUserId } : {}) }) as Agent;
|
||||
} catch (error) {
|
||||
// Lost the provisioning race: a concurrent writer inserted the row first
|
||||
// and the partial unique index rejected ours. Re-run once; the winning
|
||||
// row now exists, so we take the update path instead of inserting again.
|
||||
if (!options.isRaceRetry && isBuiltInAgentMarkerConflict(error)) {
|
||||
return ensure(companyId, key, input, { isRaceRetry: true, createdByUserId: options.createdByUserId });
|
||||
return ensure(companyId, key, input, { isRaceRetry: true, createdByUserId: options.createdByUserId, createdByAgentId: options.createdByAgentId });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
@@ -1874,7 +1875,7 @@ export function builtInAgentService(db: Db) {
|
||||
const definition = requireBuiltInAgentDefinition(key);
|
||||
const company = await ensureCompany(companyId);
|
||||
if (!company.requireBoardApprovalForNewAgents) {
|
||||
return { state: await ensure(companyId, key, input, { createdByUserId: actor.requestedByUserId ?? null }), approval: null };
|
||||
return { state: await ensure(companyId, key, input, { createdByUserId: actor.requestedByUserId ?? null, createdByAgentId: actor.requestedByAgentId ?? null }), approval: null };
|
||||
}
|
||||
await assertKnownBuiltInAgentModel(definition, input);
|
||||
|
||||
@@ -1906,7 +1907,7 @@ export function builtInAgentService(db: Db) {
|
||||
// it does when board approval is not required, instead of dead-ending on a
|
||||
// fresh board-approval requirement the operator can never satisfy.
|
||||
if (providesAdapterSetup && (existing.metadata?.paperclipBuiltInSetupRequired === true || !hasCompleteAdapterConfig(existing.adapterType, existing.adapterConfig))) {
|
||||
return { state: await ensure(companyId, key, input), approval: null };
|
||||
return { state: await ensure(companyId, key, input, { createdByUserId: actor.requestedByUserId ?? null, createdByAgentId: actor.requestedByAgentId ?? null }), approval: null };
|
||||
}
|
||||
|
||||
// Changing the adapter of an already-configured (`ready`/`paused`)
|
||||
|
||||
Reference in new issue
Block a user