mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-12 14:19:00 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The board controls which agents can hire, with the "Can create
agents" permission on each agent
> - A CEO agent with that permission turned off could still hire,
because the CEO role allowed hiring before the server read the saved
permission
> - In chat, a CEO agent asked to hire then created the agent through
the `hire_agent` tool, against the board's policy
> - This pull request makes the saved permission decide, and uses the
CEO role only for old rows that never saved a value
> - It also tells a denied agent that the denial is final and where a
person can act
> - The benefit is that the permissions page and the server now agree,
and the board can trust a hiring denial
## Linked Issues or Issue Description
**What happened**
A board user turned off "Can create agents" for a CEO agent. Then the
user asked the CEO in chat to hire a QA engineer. The CEO called
`hire_agent` (`POST /api/companies/{companyId}/agent-hires`). The server
returned 201 and created the agent. The legacy creator rule allowed any
agent with `role: "ceo"` before it read `permissions.canCreateAgents`.
**Expected behavior**
An explicit `canCreateAgents: false` denies hiring for every role,
including CEO. The agent gets a 403 that says the denial is final, and
it sends the person to the hire form or to its permissions page.
**Steps to reproduce**
1. Create a company with a CEO agent.
2. On the CEO's permissions page, turn off "Can create agents".
3. In chat with the CEO, send "Hire a QA engineer named Morgan."
4. See that a new agent named Morgan exists.
Found by the chat eval case `agents.hire-denied`. Related: #19614 (chat
eval harness).
## What Changed
- `canCreateAgentsLegacy` (authorization) uses the role-aware permission
normalization. A CEO keeps hiring unless the board recorded a hiring
denial.
- New `ceoHiringDeniedBy` record in `permissions` (`{ actorType,
actorId, at }`). `PATCH /agents/:id/permissions` writes it when an
authorized actor saves a CEO's hiring as off (an earlier record is
kept). The page shows the effective value, so a saved off is the board's
choice. Turning the toggle off also removes an explicit `agents:create`
grant. A saved `canCreateAgents: false` restricts a CEO only together
with this record.
- Reads report the effective value. A CEO row with no value, or with an
unrecorded false, shows hiring on. A CEO with a recorded denial shows it
off.
- Create and hire inputs cannot supply the record. Configuration updates
keep an existing record unless they turn hiring on. Company export keeps
a CEO's recorded denial, and import restores it, stamped by the
importing user.
- `PATCH /agents/:id/permissions`: an agent actor needs `agents:create`
to change `canCreateAgents`. A denied CEO cannot restore hiring for
itself or grant it to another agent.
- `assertCanCreateAgentsForCompany` adds a final, actionable sentence to
an agent's `agents:create` denial on hiring routes only (`POST /agents`,
`POST /agent-hires`, the hiring toggle on `PATCH /permissions`).
- `POST /api/companies/:companyId/imports/apply` (CEO-safe import): an
agent import that would create agents needs an `agents:create` decision
before any write. Before, any CEO agent could create agents this way.
Import also removes an existing `agents:create` grant when it restores a
CEO's denial.
- Chat guidance tells the agent to link `/<prefix>/agents/new` and its
own `/permissions` page when it cannot hire.
- Regression tests: authorization (a recorded denial is honored; an
unrecorded false keeps CEO hiring), normalization, route tests (denial
text, self-escalation, the record is written only when a CEO is turned
off), service tests for the permission and configuration write paths,
chat guidance text.
### Why a recorded denial and not a plain false
These normal paths save `canCreateAgents: false` on a CEO without a
board choice:
- The permissions page posts the full object. Before this change, a
legacy CEO row with `{}` was read as false, so saving any other toggle
stored false.
- A company import that updates an existing agent normalizes the
manifest permissions in the "stored" context. A manifest without the
field stores false. Export drops false values, so this is common.
- Low-trust creation stores false. If the trust preset later changes to
standard, the false remains.
These paths store true or nothing for a CEO: onboarding seed
(`requestHire`, create context: true), teams-catalog and import creation
(create context: true; the bundled catalog sets true only for a CTO),
built-in agents (no CEO roles), migrations and seed data (no writes to
this field).
A plain-false rule would remove hiring from those CEOs. With the record,
existing data keeps today's behavior, and no data migration is
necessary.
## Verification
- `cd server && npx vitest run
src/__tests__/agent-permissions-service.test.ts
src/__tests__/authorization-service.test.ts
src/__tests__/agent-permissions-routes.test.ts
src/__tests__/agent-conversations.test.ts` passes (244 tests).
- `teams-catalog-service`, `company-portability` and `built-in-agents`
tests pass (189 tests).
- Red check: the new authorization test fails without the
`authorization.ts` change.
- `npx tsc --noEmit -p server` passes.
- End to end: the chat eval `agents.hire-denied` on the OpenCode runner.
The baseline run (Actions run 42478870236) created Morgan through
`hire_agent`. With this fix (Actions run 42480936881), the agent got the
403, created no agent, and linked the hire form and its permissions
page. The eval clicked the rendered hire-form link.
## Risks
- Behavior change: a CEO whose hiring the board turns off after this
change can no longer hire.
- A CEO that already has a saved false keeps hiring until a board user
turns it off again on the permissions page. The page now shows such a
CEO as on, so the board can see and change it.
- A request that creates a CEO with `canCreateAgents: false` does not
restrict it. The board must turn hiring off on the permissions page.
- A CEO agent whose hiring is denied can no longer import a package that
creates agents. A board user can still import it.
- Other CEO special cases are not hiring routes: `issues.ts` lets a CEO
link approvals to issues, and `agents.ts` gives a CEO task assignment.
`teams-catalog.ts` and `llms.ts` read the normalized permissions, so
they follow the same effective value.
- The denial text is longer. No existing test compares this route's
exact error text.
## Model Used
- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code
execution in Claude Code.
## 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>
288 lines
10 KiB
TypeScript
288 lines
10 KiB
TypeScript
import { notifyAttentionRetentionWork } from "./retention-work-notifications.js";
|
|
import { type BudgetServiceHooks } from "./budgets.js";
|
|
|
|
import { and, desc, eq, inArray } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { agents, agentConfigRevisions, agentApiKeys, heartbeatRuns } from "@paperclipai/db";
|
|
import { isUuidLike, normalizeAgentApiKeyScope, normalizeAgentUrlKey, type AgentApiKeyScope } from "@paperclipai/shared";
|
|
|
|
import { conflict, notFound, unprocessable } from "../errors.js";
|
|
|
|
import { normalizeAgentPermissions } from "../lib/agent-permissions.js";
|
|
|
|
import {
|
|
agentRecordQueries,
|
|
hashToken,
|
|
createToken,
|
|
containsRedactedMarker,
|
|
configPatchFromSnapshot,
|
|
} from "../lib/agent-records.js";
|
|
import { createAgentLifecycle } from "./agent-lifecycle.js";
|
|
|
|
export { hasAgentShortnameCollision, deduplicateAgentName } from "../lib/agent-records.js";
|
|
|
|
export function agentService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
|
|
const {
|
|
normalizeAgentRows,
|
|
listCompanyAgentRows,
|
|
hydrateAgentSpend,
|
|
getById
|
|
} = agentRecordQueries(db);
|
|
const updateAgent = (...args: Parameters<ReturnType<typeof createAgentLifecycle>["updateConfiguration"]>) =>
|
|
createAgentLifecycle(db, budgetHooks).updateConfiguration(...args);
|
|
return {
|
|
list: async (companyId: string, options?: { includeTerminated?: boolean }) => {
|
|
const allCompanyRows = await listCompanyAgentRows(companyId);
|
|
const rows = options?.includeTerminated
|
|
? allCompanyRows
|
|
: allCompanyRows.filter((row) => row.status !== "terminated");
|
|
const hydrated = await hydrateAgentSpend(rows);
|
|
return normalizeAgentRows(hydrated, allCompanyRows);
|
|
},
|
|
|
|
getById,
|
|
|
|
updatePermissions: async (id: string, permissions: Record<string, unknown> & { canCreateAgents: boolean }) => {
|
|
const existing = await getById(id);
|
|
if (!existing) return null;
|
|
if (existing.status === "pending_approval") {
|
|
throw conflict("Pending approval agent permissions cannot be changed before board approval", {
|
|
code: "pending_approval_agent_config_frozen",
|
|
agentId: id,
|
|
fields: ["permissions"],
|
|
});
|
|
}
|
|
|
|
const updated = await db.transaction(async tx => {
|
|
await notifyAttentionRetentionWork(tx, { companyId: existing.companyId });
|
|
return tx
|
|
.update(agents)
|
|
.set({
|
|
permissions: normalizeAgentPermissions({ ...existing.permissions, ...permissions }, { role: existing.role }),
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(agents.id, id))
|
|
.returning()
|
|
.then((rows) => rows[0] ?? null);
|
|
});
|
|
|
|
return updated ? getById(updated.id) : null;
|
|
},
|
|
|
|
listConfigRevisions: async (id: string) =>
|
|
db
|
|
.select()
|
|
.from(agentConfigRevisions)
|
|
.where(eq(agentConfigRevisions.agentId, id))
|
|
.orderBy(desc(agentConfigRevisions.createdAt)),
|
|
|
|
getConfigRevision: async (id: string, revisionId: string) =>
|
|
db
|
|
.select()
|
|
.from(agentConfigRevisions)
|
|
.where(and(eq(agentConfigRevisions.agentId, id), eq(agentConfigRevisions.id, revisionId)))
|
|
.then((rows) => rows[0] ?? null),
|
|
|
|
rollbackConfigRevision: async (
|
|
id: string,
|
|
revisionId: string,
|
|
actor: { agentId?: string | null; userId?: string | null },
|
|
) => {
|
|
const revision = await db
|
|
.select()
|
|
.from(agentConfigRevisions)
|
|
.where(and(eq(agentConfigRevisions.agentId, id), eq(agentConfigRevisions.id, revisionId)))
|
|
.then((rows) => rows[0] ?? null);
|
|
if (!revision) return null;
|
|
if (containsRedactedMarker(revision.afterConfig)) {
|
|
throw unprocessable("Cannot roll back a revision that contains redacted secret values");
|
|
}
|
|
|
|
const patch = configPatchFromSnapshot(revision.afterConfig);
|
|
return updateAgent(id, patch, {
|
|
recordRevision: {
|
|
createdByAgentId: actor.agentId ?? null,
|
|
createdByUserId: actor.userId ?? null,
|
|
source: "rollback",
|
|
rolledBackFromRevisionId: revision.id,
|
|
},
|
|
});
|
|
},
|
|
|
|
createApiKey: async (
|
|
id: string,
|
|
name: string,
|
|
scope: AgentApiKeyScope = { kind: "standard" },
|
|
options?: { responsibleUserId?: string | null },
|
|
) => {
|
|
const existing = await getById(id);
|
|
if (!existing) throw notFound("Agent not found");
|
|
if (existing.lifecycleHolds?.includes("setup")) {
|
|
throw conflict("Finish agent setup before creating keys");
|
|
}
|
|
if (existing.status === "pending_approval") {
|
|
throw conflict("Cannot create keys for pending approval agents");
|
|
}
|
|
if (existing.status === "terminated") {
|
|
throw conflict("Cannot create keys for terminated agents");
|
|
}
|
|
|
|
const token = createToken();
|
|
const keyHash = hashToken(token);
|
|
const created = await db
|
|
.insert(agentApiKeys)
|
|
.values({
|
|
agentId: id,
|
|
companyId: existing.companyId,
|
|
name,
|
|
keyHash,
|
|
responsibleUserId: options?.responsibleUserId?.trim() || null,
|
|
scopeConfig: scope.kind === "standard" ? null : scope,
|
|
})
|
|
.returning()
|
|
.then((rows) => rows[0]);
|
|
|
|
return {
|
|
id: created.id,
|
|
name: created.name,
|
|
scope: normalizeAgentApiKeyScope(created.scopeConfig),
|
|
responsibleUserId: created.responsibleUserId,
|
|
token,
|
|
createdAt: created.createdAt,
|
|
};
|
|
},
|
|
|
|
listKeys: (id: string) =>
|
|
db
|
|
.select({
|
|
id: agentApiKeys.id,
|
|
name: agentApiKeys.name,
|
|
responsibleUserId: agentApiKeys.responsibleUserId,
|
|
scopeConfig: agentApiKeys.scopeConfig,
|
|
createdAt: agentApiKeys.createdAt,
|
|
revokedAt: agentApiKeys.revokedAt,
|
|
})
|
|
.from(agentApiKeys)
|
|
.where(eq(agentApiKeys.agentId, id))
|
|
.then((rows) => rows.map((row) => ({
|
|
id: row.id,
|
|
name: row.name,
|
|
scope: normalizeAgentApiKeyScope(row.scopeConfig),
|
|
responsibleUserId: row.responsibleUserId,
|
|
createdAt: row.createdAt,
|
|
revokedAt: row.revokedAt,
|
|
}))),
|
|
|
|
getKeyById: async (keyId: string) =>
|
|
db
|
|
.select({
|
|
id: agentApiKeys.id,
|
|
agentId: agentApiKeys.agentId,
|
|
companyId: agentApiKeys.companyId,
|
|
name: agentApiKeys.name,
|
|
responsibleUserId: agentApiKeys.responsibleUserId,
|
|
scopeConfig: agentApiKeys.scopeConfig,
|
|
createdAt: agentApiKeys.createdAt,
|
|
revokedAt: agentApiKeys.revokedAt,
|
|
})
|
|
.from(agentApiKeys)
|
|
.where(eq(agentApiKeys.id, keyId))
|
|
.then((rows) => {
|
|
const row = rows[0] ?? null;
|
|
return row
|
|
? {
|
|
...row,
|
|
scope: normalizeAgentApiKeyScope(row.scopeConfig),
|
|
}
|
|
: null;
|
|
}),
|
|
|
|
revokeKey: async (agentId: string, keyId: string) => {
|
|
const rows = await db
|
|
.update(agentApiKeys)
|
|
.set({ revokedAt: new Date() })
|
|
.where(and(eq(agentApiKeys.id, keyId), eq(agentApiKeys.agentId, agentId)))
|
|
.returning();
|
|
return rows[0] ?? null;
|
|
},
|
|
|
|
orgForCompany: async (companyId: string) => {
|
|
const allCompanyRows = await listCompanyAgentRows(companyId);
|
|
const rows = allCompanyRows.filter((row) => row.status !== "terminated");
|
|
const normalizedRows = normalizeAgentRows(rows, allCompanyRows);
|
|
const byManager = new Map<string | null, typeof normalizedRows>();
|
|
for (const row of normalizedRows) {
|
|
const key = row.reportsTo && rows.some((candidate) => candidate.id === row.reportsTo) ? row.reportsTo : null;
|
|
const group = byManager.get(key) ?? [];
|
|
group.push(row);
|
|
byManager.set(key, group);
|
|
}
|
|
|
|
const build = (managerId: string | null): Array<Record<string, unknown>> => {
|
|
const members = byManager.get(managerId) ?? [];
|
|
return members.map((member) => ({
|
|
...member,
|
|
reports: build(member.id),
|
|
}));
|
|
};
|
|
|
|
return build(null);
|
|
},
|
|
|
|
getChainOfCommand: async (agentId: string) => {
|
|
const chain: { id: string; name: string; role: string; title: string | null }[] = [];
|
|
const visited = new Set<string>([agentId]);
|
|
const start = await getById(agentId);
|
|
let currentId = start?.reportsTo ?? null;
|
|
while (currentId && !visited.has(currentId) && chain.length < 50) {
|
|
visited.add(currentId);
|
|
const mgr = await getById(currentId);
|
|
if (!mgr) break;
|
|
chain.push({ id: mgr.id, name: mgr.name, role: mgr.role, title: mgr.title ?? null });
|
|
currentId = mgr.reportsTo ?? null;
|
|
}
|
|
return chain;
|
|
},
|
|
|
|
runningForAgent: (agentId: string) =>
|
|
db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(and(eq(heartbeatRuns.agentId, agentId), inArray(heartbeatRuns.status, ["queued", "running"]))),
|
|
|
|
resolveByReference: async (companyId: string, reference: string) => {
|
|
const raw = reference.trim();
|
|
if (raw.length === 0) {
|
|
return { agent: null, ambiguous: false } as const;
|
|
}
|
|
|
|
if (isUuidLike(raw)) {
|
|
const byId = await getById(raw);
|
|
if (!byId || byId.companyId !== companyId) {
|
|
return { agent: null, ambiguous: false } as const;
|
|
}
|
|
return { agent: byId, ambiguous: false } as const;
|
|
}
|
|
|
|
const urlKey = normalizeAgentUrlKey(raw);
|
|
if (!urlKey) {
|
|
return { agent: null, ambiguous: false } as const;
|
|
}
|
|
|
|
const rows = await db.select().from(agents).where(eq(agents.companyId, companyId));
|
|
const matches = normalizeAgentRows(rows, rows)
|
|
.filter((agent) => agent.urlKey === urlKey && agent.status !== "terminated");
|
|
if (matches.length === 1) {
|
|
return { agent: matches[0] ?? null, ambiguous: false } as const;
|
|
}
|
|
if (matches.length > 1) {
|
|
return { agent: null, ambiguous: true } as const;
|
|
}
|
|
return { agent: null, ambiguous: false } as const;
|
|
},
|
|
update: updateAgent,
|
|
remove: (id: string) => createAgentLifecycle(db, budgetHooks).purgeAgent(id),
|
|
clearError: (id: string) => createAgentLifecycle(db, budgetHooks).clearError(id),
|
|
};
|
|
}
|