diff --git a/maps/agent-access-map/agents.md b/maps/agent-access-map/agents.md index 8b8c24511bb..96f9550ca37 100644 --- a/maps/agent-access-map/agents.md +++ b/maps/agent-access-map/agents.md @@ -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, diff --git a/server/src/__tests__/agent-budget-configuration.test.ts b/server/src/__tests__/agent-budget-configuration.test.ts new file mode 100644 index 00000000000..4f2ff10c8d1 --- /dev/null +++ b/server/src/__tests__/agent-budget-configuration.test.ts @@ -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 }); + }); +}); diff --git a/server/src/__tests__/agent-hire-idempotency-routes.test.ts b/server/src/__tests__/agent-hire-idempotency-routes.test.ts index 8d2740f40ff..282cae1da5d 100644 --- a/server/src/__tests__/agent-hire-idempotency-routes.test.ts +++ b/server/src/__tests__/agent-hire-idempotency-routes.test.ts @@ -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 () => { diff --git a/server/src/__tests__/agent-permissions-routes.test.ts b/server/src/__tests__/agent-permissions-routes.test.ts index 555bc23ccd1..132e8dee1af 100644 --- a/server/src/__tests__/agent-permissions-routes.test.ts +++ b/server/src/__tests__/agent-permissions-routes.test.ts @@ -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](//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](//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](//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", diff --git a/server/src/__tests__/built-in-agent-routes.test.ts b/server/src/__tests__/built-in-agent-routes.test.ts index e51166f2ba4..b6d985b4170 100644 --- a/server/src/__tests__/built-in-agent-routes.test.ts +++ b/server/src/__tests__/built-in-agent-routes.test.ts @@ -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](//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", })); }); diff --git a/server/src/__tests__/built-in-agents.test.ts b/server/src/__tests__/built-in-agents.test.ts index c43f911d6e7..e6989b1798b 100644 --- a/server/src/__tests__/built-in-agents.test.ts +++ b/server/src/__tests__/built-in-agents.test.ts @@ -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; diff --git a/server/src/lib/agent-records.ts b/server/src/lib/agent-records.ts index b9a7bb702f7..9a075a860a9 100644 --- a/server/src/lib/agent-records.ts +++ b/server/src/lib/agent-records.ts @@ -89,6 +89,7 @@ export type AgentConfigurationPatch = Partial; export interface CreateAgentOptions { + initialBudgetPolicyUserId?: string; setupOnly?: boolean; setupAgentId?: string; runnerResolved?: boolean; diff --git a/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts b/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts index 2502fae80cf..42b2e7c0bdf 100644 --- a/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts @@ -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) => { + 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, diff --git a/server/src/modules/agent-lifecycle/adapters/records.ts b/server/src/modules/agent-lifecycle/adapters/records.ts index cdc85e7297a..1cce960c54c 100644 --- a/server/src/modules/agent-lifecycle/adapters/records.ts +++ b/server/src/modules/agent-lifecycle/adapters/records.ts @@ -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); } diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index e95253f8cbd..59fe094d2ed 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -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" }); diff --git a/server/src/routes/authz.ts b/server/src/routes/authz.ts index 444dfc7ed58..b8d4dcd5fb4 100644 --- a/server/src/routes/authz.ts +++ b/server/src/routes/authz.ts @@ -44,13 +44,22 @@ const AGENT_PROFILE_TABS: Record = { "runtime-state": ["harness settings", "runtime"], }; +/** A board page as [label, path], where the path keeps 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", "//activity/budgets"]; +export function agentBudgetPage(agentId: string): BoardControlPage { + return [`the agent's ${AGENT_PROFILE_TABS.budgets![0]}`, `//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 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", "//company/settings/secrets"]], - [/^\/companies\/[^/]+\/(?:budgets|budget-incidents|costs)(?:\/|$)/, () => ["budgets", "//activity/budgets"]], + [/^\/companies\/[^/]+\/(?:budgets|budget-incidents|costs)(?:\/|$)/, () => COMPANY_BUDGETS_PAGE], [/^\/companies\/[^/]+\/(?:prompt-injection-prevention|decision-model)(?:\/|$)/, () => ["connection settings", "//company/settings/connections"]], [/^\/companies\/[^/]+\/(?:members|invites|join-requests)(?:\/|$)/, () => ["company members", "//company/settings/members"]], [/^\/companies\/[^/]+\/(?:tools\/)?gateways(?:\/|$)|^\/tool-gateway\//, () => ["tool gateways", "//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 .` @@ -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); } } diff --git a/server/src/routes/built-in-agents.ts b/server/src/routes/built-in-agents.ts index c881ae9c93f..ee1529197bf 100644 --- a/server/src/routes/built-in-agents.ts +++ b/server/src/routes/built-in-agents.ts @@ -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, diff --git a/server/src/services/agent-configuration.ts b/server/src/services/agent-configuration.ts index 3dfc40e4048..0a2a0185bd4 100644 --- a/server/src/services/agent-configuration.ts +++ b/server/src/services/agent-configuration.ts @@ -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 { + 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. diff --git a/server/src/services/built-in-agents.ts b/server/src/services/built-in-agents.ts index ecd6a1dd111..fac7ac6faf5 100644 --- a/server/src/services/built-in-agents.ts +++ b/server/src/services/built-in-agents.ts @@ -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`)