feat(responsibilities): let agents read a person's areas and responsibilities (#22253)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People keep their areas and responsibilities in Paperclip
(experimental, `enableResponsibilities`). Agents chat with them about
this work.
> - Agents have no dedicated tool to read a person's responsibilities.
The only path is the generic `search_api` and `call_api` fallback.
> - That path needs the person's user ID, and nothing in a chat tells
the agent that responsibilities exist. When the feature is off, every
route returns a 404 that looks like "nothing there".
> - So a chief-of-staff agent asked the person "what are your
responsibilities, or where are they written down?" when Paperclip
already had them.
> - This pull request adds three read tools, makes the owner default to
the person the run works for, and tells agents in chats how to use the
tools or that the feature is off.
> - The benefit is that an agent reads and maps a person's
responsibilities itself. This is phase 1 of 4. Later pull requests add
the change tools for areas, responsibilities, routines and skills.

## Linked Issues or Issue Description

**Subsystem affected**

Server (responsibility routes, native runner tool authority, chat
prompt), native runner tool catalog, and the `paperclip` skill.

**Problem or motivation**

An agent in a chat cannot find a person's responsibilities. It has no
dedicated tool. The list route requires `ownerUserId` from an agent, and
the chat does not give the agent that ID. The chat prompt does not
mention responsibilities. When the experiment is off, the 404 does not
tell the agent that the feature is off. The agent then asks the person
to list their responsibilities again.

**Proposed solution**

Add three optional native tools: `list_responsibilities`,
`get_responsibility` and `find_responsibilities_for`. They call the
existing routes with the run's agent token, so all route checks and the
activity log stay the same. The owner defaults to the person the run
works for. The routes return a `responsibilities_disabled` code while
the feature is off. The tools are hidden while the feature is off, and
the chat prompt then says that the feature is off.

**Alternatives considered**

Better `search_api` guidance alone still needs the user ID and many
calls. A new read service in the tool authority would copy the route
permission rules. The tools use the routes instead.

## What Changed

- Add `list_responsibilities` (areas with their responsibilities,
responsibilities with no area, totals, and company work filed under no
responsibility), `get_responsibility` (one responsibility with its filed
items, link IDs, skills and latest status report), and
`find_responsibilities_for` (where a project, task or routine is filed;
a task can be a `PAP-12` identifier).
- Add `server/src/services/responsibility-tools.ts`. It calls the routes
over HTTP with the run token and returns compact results with page
links.
- When an agent sends no `ownerUserId`, the responsibility list, create,
summary, automation and dashboard routes use the person the run works
for (`onBehalfOfUserId`). A run that works for no person still gets a
422 with a clear message.
- The nine "not enabled" checks now throw one shared error. The 404 and
its message do not change. The body now also has `code:
"responsibilities_disabled"` and a remediation line. One
`RESPONSIBILITIES_OFF_GUIDANCE` text is the remediation, the tool error
and the chat prompt note.
- `list_responsibilities` with `areaId` counts only that area. Archived
areas are listed only on request. When only proposals are hidden, the
tool says so.
- `services/paperclip-api-loopback.ts` holds the tools' authenticated
API call; the project tools use it too.
- Show the tools only while the instance has Responsibilities on. A
hidden tool that is called by name returns "Areas and responsibilities
are turned off".
- In standing chats, add an "Areas and responsibilities" prompt block:
use the tools before you ask the person, or say that the feature is off.
- `search_api` results for these routes now name the dedicated tools.
- Add an "Areas and responsibilities" section to
`skills/paperclip/SKILL.md` and to `references/api-reference.md`. Add
one line to the chief-of-staff persona.
- Register the tools in the runner catalogs. Regenerate the semantic
contracts, the action catalog, protocol coverage, the operation-groups
spec and the capability inventory. Update the pinned counts.

## Verification

- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/catalog src/semantic-tools src/tools src/eval/workflow-evals.test.ts
src/protocol-actions src/evals/native-execution.test.ts
src/drivers/acpx/permission-policy.test.ts`: 276 passed.
- All runner generator checks pass: protocol manifest, capability
contract, capability inventory, protocol coverage, semantic contracts,
semantic action catalog, operation groups, replay goldens, workflow
traceability.
- Server: `vitest run` of `responsibilit*` route tests,
`responsibility-tools.test.ts` (new), `task-markdown.test.ts`,
`task-context*`, `paperclip-runner-tool-authority.test.ts`,
`runner-api.test.ts`, onboarding first-task tests and
`user-facing-wording-guidance.test.ts`: 20 files, 2620 tests passed.
- `node scripts/typecheck-layers.mjs` for the server: passed.
- New tests cover these items: the owner default for an agent and the
422 without a person, the `responsibilities_disabled` code on every
route, the tool projections, an identifier lookup, the "turned off"
mapping, the tool visibility switch, and the chat prompt block.

## Risks

- Low risk. The routes keep their permission checks. Agents can still
only read and propose in this phase.
- An agent that sends no `ownerUserId` now gets the responsible person's
list instead of a 422. Agents that name an owner see no change.
- The chat prompt gets one more short block in standing chats.
- The flag is pinned when a turn opens. If an admin changes it during a
turn, the tool list changes on the next turn. The routes always check
the current setting.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and
code execution.

## 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:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-19 08:52:42 -06:00
1 parent 53fedd653b
commit ffcd49f6aa
56 files changed
+1364 -381

No files matched your search

@@ -177,9 +177,40 @@ describeEmbeddedPostgres("responsibility routes", () => {
]) {
expect(res.status).toBe(404);
expect(res.body.error).toBe("Responsibilities are not enabled");
// The code lets an agent tell "turned off" from "nothing there".
expect(res.body.code).toBe("responsibilities_disabled");
}
});
it("reads and proposes for the person an agent's run works for when no owner is named", async () => {
await enable();
const company = await seedCompany();
const agent = await seedAgent(company.id);
const board = createApp(db, localBoardActor());
const mine = await createResponsibility(board, company.id, { title: "Fundraising" });
const forOwner = createApp(db, {
...agentActor(company.id, agent.id),
onBehalfOfUserId: OWNER,
onBehalfOfMemberships: [{ companyId: company.id, membershipRole: "owner", status: "active" }],
});
const listed = await request(forOwner).get(`/api/companies/${company.id}/responsibilities`);
expect(listed.status).toBe(200);
expect(listed.body.ownerUserId).toBe(OWNER);
expect(listed.body.responsibilities.map((row: { id: string }) => row.id)).toEqual([mine.id]);
const proposed = await request(forOwner).post(`/api/companies/${company.id}/responsibilities`).send({ title: "Hiring", ...METRIC });
expect(proposed.status).toBe(201);
expect(proposed.body).toMatchObject({ ownerUserId: OWNER, status: "proposed" });
// A named owner still wins, and a run that works for no person must name one.
const other = await request(forOwner).get(`/api/companies/${company.id}/responsibilities?ownerUserId=other-user`);
expect(other.body.ownerUserId).toBe("other-user");
const unbound = await request(createApp(db, agentActor(company.id, agent.id))).get(`/api/companies/${company.id}/responsibilities`);
expect(unbound.status).toBe(422);
expect(unbound.body.error).toContain("this run works for no person");
});
it("refuses a half-filled bar, and derives status from the metric", async () => {
await enable();
const company = await seedCompany();
@@ -0,0 +1,184 @@
import { describe, expect, it } from "vitest";
import { callResponsibilityTool, RESPONSIBILITIES_TURNED_OFF_MESSAGE } from "../services/responsibility-tools.js";
const COMPANY = "11111111-1111-4111-8111-111111111111";
const AREA = "22222222-2222-4222-8222-222222222222";
const RESPONSIBILITY = "33333333-3333-4333-8333-333333333333";
const ROUTINE = "44444444-4444-4444-8444-444444444444";
const TASK = "55555555-5555-4555-8555-555555555555";
function rollup(overrides: Record<string, unknown> = {}) {
return {
health: "on_track", computedHealth: "on_track", healthOverridden: false, metric: null,
statusSentence: "12 of 20 investors contacted, 60% of target", workSummary: [{ text: "2 tasks blocked" }],
projects: 1, routines: 2, openTasks: 3, blockedTasks: 2, agentTasks: 1, userTasks: 2, doneTasks: 4,
nextDueAt: null, overdueProjects: [], ...overrides,
};
}
function responsibility(overrides: Record<string, unknown> = {}) {
return {
id: RESPONSIBILITY, companyId: COMPANY, ownerUserId: "owner", areaId: AREA, title: "Fundraising",
description: null, standard: "Every investor conversation has a next step", metricKind: "volume",
metricName: "Investors contacted", metricUnit: null, metricTarget: 20, metricLow: null, metricHigh: null,
metricCurrent: 12, metricDirection: "at_least", metricUpdatedAt: null, runByAgentId: null, status: "active",
source: "manual", evidence: null, healthOverride: null, healthNote: null, sortOrder: 0, proposedByAgentId: null,
confirmedAt: null, createdAt: "2026-11-01T00:00:00.000Z", updatedAt: "2026-11-01T00:00:00.000Z",
rollup: rollup(), ...overrides,
};
}
/** Records each request and answers from a path table; unknown paths are a test failure. */
function fakeApi(routes: Record<string, { status?: number; body: unknown }>) {
const calls: Array<{ url: string; auth: string | null }> = [];
const fetcher = (async (url: string | URL, init?: RequestInit) => {
const href = String(url);
calls.push({ url: href, auth: new Headers(init?.headers).get("authorization") });
const path = href.replace("http://paperclip.test/api", "");
const route = routes[path];
if (!route) throw new Error(`unexpected request ${path}`);
return new Response(JSON.stringify(route.body), { status: route.status ?? 200, headers: { "content-type": "application/json" } });
}) as typeof fetch;
return { calls, fetcher };
}
const base = { apiUrl: "http://paperclip.test/api", token: "agent-token", companyId: COMPANY, companyPrefix: "PAP" };
describe("responsibility tools", () => {
it("groups a person's responsibilities by area and reports uncovered work", async () => {
const proposed = responsibility({ id: "66666666-6666-4666-8666-666666666666", title: "Hiring", status: "proposed", areaId: null, evidence: "Owner said so", proposedByAgentId: "agent-1" });
const api = fakeApi({
[`/companies/${COMPANY}/responsibilities?includeLetGo=false`]: { body: {
ownerUserId: "owner",
areas: [{ id: AREA, title: "Money", description: null, status: "active", activeResponsibilities: 1, byHealth: {} }],
responsibilities: [responsibility()],
proposed: [proposed],
totals: { byHealth: { behind: 0, at_risk: 0, on_track: 1, not_measured: 0 }, openTasks: 3, agentTasks: 1, userTasks: 2, blockedTasks: 2, projects: 1, lateProjects: 0 },
loose: {
projectCount: 0, openTaskCount: 1, routineCount: 1, projects: [],
tasks: [{ id: TASK, identifier: "PAP-9", title: "Loose task", status: "todo", assigneeAgentId: null, assigneeUserId: null, projectId: null, updatedAt: "2026-11-01T00:00:00.000Z" }],
routines: [{ id: ROUTINE, title: "Weekly digest", status: "active", assigneeAgentId: "agent-1", projectId: null }],
},
} },
});
const result = await callResponsibilityTool({ ...base, name: "list_responsibilities", arguments: {} }, api.fetcher);
// The route picks the owner (the person the run works for); the tool sends none and authenticates as the run.
expect(api.calls).toEqual([{ url: `http://paperclip.test/api/companies/${COMPANY}/responsibilities?includeLetGo=false`, auth: "Bearer agent-token" }]);
expect(result).toMatchObject({
ownerUserId: "owner",
areas: [{ id: AREA, title: "Money", responsibilities: [{
id: RESPONSIBILITY, title: "Fundraising", health: "on_track", bar: { kind: "volume", name: "Investors contacted", target: 20, current: 12 },
counts: { projects: 1, routines: 2, openTasks: 3, blockedTasks: 2, doneTasks: 4 }, href: `/PAP/responsibilities/${RESPONSIBILITY}`,
}] }],
withoutArea: [{ title: "Hiring", status: "proposed", evidence: "Owner said so" }],
totals: { active: 1, proposed: 1, letGo: 0 },
uncoveredWork: { routineCount: 1, openTaskCount: 1, routines: [{ id: ROUTINE, title: "Weekly digest" }], tasks: [{ identifier: "PAP-9" }] },
});
expect(result).not.toHaveProperty("guidance");
});
it("says the list is empty rather than inventing responsibilities", async () => {
const api = fakeApi({
[`/companies/${COMPANY}/responsibilities?includeLetGo=false&ownerUserId=someone`]: { body: {
ownerUserId: "someone", areas: [], responsibilities: [], proposed: [],
totals: { byHealth: {}, openTasks: 0, agentTasks: 0, userTasks: 0, blockedTasks: 0, projects: 0, lateProjects: 0 },
loose: { projectCount: 0, openTaskCount: 0, routineCount: 0, projects: [], tasks: [], routines: [] },
} },
});
const result = await callResponsibilityTool({ ...base, name: "list_responsibilities", arguments: { ownerUserId: "someone" } }, api.fetcher);
expect(result).toMatchObject({ ownerUserId: "someone", areas: [], withoutArea: [], guidance: expect.stringContaining("no responsibilities yet") });
});
it("scopes totals to one area, hides archived areas unless asked, and notices hidden proposals", async () => {
const ARCHIVED = "99999999-0000-4000-8000-000000000001";
const overview = (overrides: Record<string, unknown> = {}) => ({
ownerUserId: "owner",
areas: [
{ id: AREA, title: "Money", description: null, status: "active" },
{ id: ARCHIVED, title: "Old", description: null, status: "archived" },
],
responsibilities: [
responsibility(),
responsibility({ id: "66666666-6666-4666-8666-666666666667", title: "Legacy", areaId: ARCHIVED, rollup: rollup({ health: "behind" }) }),
],
proposed: [],
totals: { byHealth: { behind: 1, at_risk: 0, on_track: 1, not_measured: 0 }, openTasks: 9, agentTasks: 0, userTasks: 0, blockedTasks: 2, projects: 4, lateProjects: 1 },
loose: { projectCount: 0, openTaskCount: 0, routineCount: 0, projects: [], tasks: [], routines: [] },
...overrides,
});
const api = fakeApi({ [`/companies/${COMPANY}/responsibilities?includeLetGo=false`]: { body: overview() } });
const all = await callResponsibilityTool({ ...base, name: "list_responsibilities", arguments: {} }, api.fetcher) as Record<string, any>;
expect(all.areas.map((area: { id: string }) => area.id)).toEqual([AREA]);
expect(all.withoutArea.map((row: { title: string }) => row.title)).toEqual(["Legacy"]);
expect(all.totals).toMatchObject({ scope: "person", active: 2, openTasks: 9 });
const one = await callResponsibilityTool({ ...base, name: "list_responsibilities", arguments: { areaId: AREA } }, api.fetcher) as Record<string, any>;
expect(one.totals).toEqual({ scope: "area", active: 1, proposed: 0, letGo: 0, activeByHealth: { behind: 0, at_risk: 0, on_track: 1, not_measured: 0 } });
expect(one).not.toHaveProperty("uncoveredWork");
const onlyProposals = fakeApi({ [`/companies/${COMPANY}/responsibilities?includeLetGo=false`]: {
body: overview({ responsibilities: [], proposed: [responsibility({ status: "proposed" })] }),
} });
const hidden = await callResponsibilityTool({ ...base, name: "list_responsibilities", arguments: { includeProposed: false } }, onlyProposals.fetcher);
expect(hidden).toMatchObject({ guidance: expect.stringContaining("1 proposed responsibilities, hidden") });
});
it("reads one responsibility with its filed items and latest status report", async () => {
const api = fakeApi({
[`/responsibilities/${RESPONSIBILITY}`]: { body: {
...responsibility(), area: { id: AREA, title: "Money", status: "active" },
skills: [{ id: "skill-1", key: "paperclipai/research", slug: "research", name: "Research", description: null, tagline: null, iconUrl: null, color: null, agentIds: ["agent-1"] }],
artifacts: [], artifactsTotal: 0, artifactsTruncated: false,
projects: [],
tasks: [{ linkId: "link-1", membership: "direct", id: TASK, identifier: "PAP-9", title: "Pitch deck", status: "todo", assigneeAgentId: null, assigneeUserId: null, projectId: null, updatedAt: "2026-11-01T00:00:00.000Z" }],
tasksTruncated: false,
routines: [{ linkId: "link-2", membership: "direct", id: ROUTINE, title: "Weekly digest", status: "active", assigneeAgentId: "agent-1", projectId: null, lastRun: null }],
} },
[`/responsibilities/${RESPONSIBILITY}/status-report`]: { body: { current: { status: "on_track", message: "Fine" }, reporterAgentId: "agent-1", updateRequested: false, history: [] } },
});
const result = await callResponsibilityTool({ ...base, name: "get_responsibility", arguments: { responsibilityId: RESPONSIBILITY } }, api.fetcher);
expect(result).toMatchObject({
id: RESPONSIBILITY, ownerUserId: "owner", area: { title: "Money" }, workSummary: ["2 tasks blocked"],
tasks: [{ linkId: "link-1", membership: "direct", identifier: "PAP-9" }],
routines: [{ linkId: "link-2", title: "Weekly digest" }],
skills: [{ id: "skill-1", name: "Research", agentIds: ["agent-1"] }],
statusReport: { current: { status: "on_track" }, reporterAgentId: "agent-1" },
});
});
it("finds where a task is filed by its identifier", async () => {
const api = fakeApi({
"/issues/PAP-9": { body: { id: TASK, identifier: "PAP-9" } },
[`/companies/${COMPANY}/responsibility-links/lookup?issueId=${TASK}`]: { body: { responsibilities: [
{ id: RESPONSIBILITY, title: "Fundraising", areaId: AREA, ownerUserId: "owner", via: "project" },
] } },
});
const result = await callResponsibilityTool({ ...base, name: "find_responsibilities_for", arguments: { kind: "task", id: "PAP-9" } }, api.fetcher);
expect(result).toEqual({
item: { kind: "task", id: TASK, identifier: "PAP-9" },
responsibilities: [{ id: RESPONSIBILITY, title: "Fundraising", areaId: AREA, ownerUserId: "owner", via: "project", href: `/PAP/responsibilities/${RESPONSIBILITY}` }],
});
});
it("reports the feature as turned off, not as an empty list", async () => {
const api = fakeApi({
[`/companies/${COMPANY}/responsibility-links/lookup?routineId=${ROUTINE}`]: { status: 404, body: { error: "Responsibilities are not enabled", code: "responsibilities_disabled" } },
});
await expect(callResponsibilityTool({ ...base, name: "find_responsibilities_for", arguments: { kind: "routine", id: ROUTINE } }, api.fetcher))
.rejects.toMatchObject({ status: 404, message: RESPONSIBILITIES_TURNED_OFF_MESSAGE, details: { code: "responsibilities_disabled" } });
});
it("passes route denials through and refuses malformed input before calling the API", async () => {
const api = fakeApi({
[`/responsibilities/${RESPONSIBILITY}`]: { status: 403, body: { error: "Responsibilities are outside this agent's authorization boundary" } },
[`/responsibilities/${RESPONSIBILITY}/status-report`]: { status: 403, body: { error: "denied" } },
});
await expect(callResponsibilityTool({ ...base, name: "get_responsibility", arguments: { responsibilityId: RESPONSIBILITY } }, api.fetcher))
.rejects.toMatchObject({ status: 403, message: "Responsibilities are outside this agent's authorization boundary" });
await expect(callResponsibilityTool({ ...base, name: "find_responsibilities_for", arguments: { kind: "routine", id: "weekly" } }, api.fetcher))
.rejects.toMatchObject({ status: 422 });
await expect(callResponsibilityTool({ ...base, name: "list_responsibilities", arguments: { owner: "x" } }, api.fetcher)).rejects.toThrow();
});
});
@@ -1,3 +1,5 @@
You are {{agentName}}, chief of staff for {{organizationName}}. You are the user's main point of contact for carrying out requests and coordinating the company's work.
Speak to the user in plain language: say what happened, what it means for them, and what comes next. Never narrate internal mechanics (receipts, execution policies, runs, API calls) or show raw IDs; name tasks by their identifier, like PIX-3.
When the user talks about what they are responsible for, or asks you to map or check work against their responsibilities, read their areas and responsibilities first (list_responsibilities, when you have it) instead of asking them to list or locate them.
+19 -6
View File
@@ -13,6 +13,7 @@ import {
type ResponsibilityLinkLookupQuery,
} from "@paperclipai/shared";
import { forbidden, notFound, unprocessable } from "../errors.js";
import { responsibilitiesDisabledError } from "../services/responsibilities-disabled.js";
import { validate } from "../middleware/validate.js";
import {
authorizationDeniedDetails,
@@ -64,6 +65,17 @@ export function boardCanManageResponsibilityOwner(req: Request, companyId: strin
return membership?.membershipRole === "owner" || membership?.membershipRole === "admin";
}
/**
* Whose responsibilities a request means when it names no owner: a board user
* means their own, and an agent means the person its run works for (the
* person chatting, or the task's responsible person).
*/
export function defaultResponsibilityOwnerUserId(req: Request): string | undefined {
if (req.actor.type === "board") return req.actor.userId ?? undefined;
if (req.actor.type === "agent") return req.actor.onBehalfOfUserId ?? undefined;
return undefined;
}
export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignmentWakeupDeps } = {}) {
const router = Router();
const access = accessService(db);
@@ -75,7 +87,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
// Same gate and message shape the status-card routes use when their flag is off.
async function assertResponsibilitiesEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableResponsibilities !== true) throw notFound("Responsibilities are not enabled");
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
/** Agents also pass the company-scope read boundary (low-trust agents do not). */
@@ -181,10 +193,10 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = listResponsibilitiesQuerySchema.parse(req.query);
const ownerUserId = query.ownerUserId ?? (req.actor.type === "board" ? req.actor.userId : undefined);
const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!ownerUserId) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: name the person whose responsibilities to read"
? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to read"
: "ownerUserId is required");
}
res.json(await svc.overview(companyId, ownerUserId, {
@@ -200,10 +212,11 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
const actor = getActorInfo(req);
let ownerUserId: string;
if (req.actor.type === "agent") {
if (!req.body.ownerUserId) {
throw unprocessable("ownerUserId is required: an agent proposes a responsibility for a person in this company");
const owner = req.body.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!owner) {
throw unprocessable("ownerUserId is required: this run works for no person, so name the person in this company the responsibility is for");
}
ownerUserId = req.body.ownerUserId;
ownerUserId = owner;
if (!(await svc.isCompanyMember(companyId, ownerUserId))) throw notFound("Owner is not a member of this company");
} else {
const self = req.actor.userId;
+3 -2
View File
@@ -5,7 +5,8 @@ import {
listResponsibilityAreasQuerySchema,
updateResponsibilityAreaSchema,
} from "@paperclipai/shared";
import { forbidden, notFound } from "../errors.js";
import { forbidden } from "../errors.js";
import { responsibilitiesDisabledError } from "../services/responsibilities-disabled.js";
import { validate } from "../middleware/validate.js";
import { authorizationDeniedDetails } from "../services/authorization.js";
import { accessService, instanceSettingsService, logActivity } from "../services/index.js";
@@ -27,7 +28,7 @@ export function responsibilityAreaRoutes(db: Db) {
async function assertResponsibilitiesEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableResponsibilities !== true) throw notFound("Responsibilities are not enabled");
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
async function assertCompanyRead(req: Request, companyId: string) {
@@ -10,7 +10,8 @@ import {
type AcceptedAutomationProposal,
type ProposeAutomationInteraction,
} from "@paperclipai/shared";
import { forbidden, notFound, unprocessable } from "../errors.js";
import { forbidden, unprocessable } from "../errors.js";
import { responsibilitiesDisabledError } from "../services/responsibilities-disabled.js";
import { validate } from "../middleware/validate.js";
import {
authorizationDeniedDetails,
@@ -34,6 +35,7 @@ import { automationConversationService } from "../services/responsibility-automa
import { standingCheckService } from "../services/routine-standing-checks.js";
import { routineSuggestionService, type RoutineSuggestionResponsibilityFiling } from "../services/routine-suggestions.js";
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
import { defaultResponsibilityOwnerUserId } from "./responsibilities.js";
import { getReadableIssue } from "./readable-issue.js";
const automationQuerySchema = listResponsibilitiesQuerySchema.pick({ ownerUserId: true });
@@ -66,7 +68,7 @@ export function responsibilityAutomationRoutes(
async function assertResponsibilitiesEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableResponsibilities !== true) throw notFound("Responsibilities are not enabled");
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
async function assertCompanyRead(req: Request, companyId: string) {
@@ -145,10 +147,10 @@ export function responsibilityAutomationRoutes(
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = automationQuerySchema.parse(req.query);
const ownerUserId = query.ownerUserId ?? (req.actor.type === "board" ? req.actor.userId : undefined);
const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!ownerUserId) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: name the person whose responsibilities to read"
? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to read"
: "ownerUserId is required");
}
res.json(await automation.overview(companyId, ownerUserId, { scope: await readScope(req) }));
@@ -25,7 +25,7 @@ import {
import { responsibilityService } from "../services/responsibilities.js";
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
import { getReadableIssue } from "./readable-issue.js";
import { boardCanManageResponsibilityOwner } from "./responsibilities.js";
import { boardCanManageResponsibilityOwner, defaultResponsibilityOwnerUserId } from "./responsibilities.js";
const ISSUE_NOT_FOUND = "Issue not found";
const VERSION_NOT_FOUND = "Version not found";
@@ -83,12 +83,12 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
}
}
/** The overview route's ownerUserId rule: board users default to themselves; agents must name the person. */
/** The overview route's ownerUserId rule: board users default to themselves, agents to the person their run works for. */
function ownerFrom(req: Request, ownerUserId: string | undefined) {
const owner = ownerUserId ?? (req.actor.type === "board" ? req.actor.userId : undefined);
const owner = ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!owner) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: name the person whose dashboard to read"
? "ownerUserId is required: this run works for no person, so name the person whose dashboard to read"
: "ownerUserId is required");
}
return owner;
@@ -1,7 +1,8 @@
import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import { listResponsibilitiesQuerySchema } from "@paperclipai/shared";
import { forbidden, notFound, unprocessable } from "../errors.js";
import { forbidden, unprocessable } from "../errors.js";
import { responsibilitiesDisabledError } from "../services/responsibilities-disabled.js";
import {
authorizationDeniedDetails,
issueReadSqlCondition,
@@ -14,6 +15,7 @@ import {
type ResponsibilitySummaryServiceOptions,
} from "../services/responsibility-summaries.js";
import { assertCompanyAccess, getAccessibleResource } from "./authz.js";
import { defaultResponsibilityOwnerUserId } from "./responsibilities.js";
const NOT_FOUND = "Responsibility not found";
const summaryQuerySchema = listResponsibilitiesQuerySchema.pick({ ownerUserId: true });
@@ -32,7 +34,7 @@ export function responsibilitySummaryRoutes(db: Db, opts: { summaries?: Responsi
async function assertResponsibilitiesEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableResponsibilities !== true) throw notFound("Responsibilities are not enabled");
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
async function assertCompanyRead(req: Request, companyId: string) {
@@ -65,10 +67,10 @@ export function responsibilitySummaryRoutes(db: Db, opts: { summaries?: Responsi
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = summaryQuerySchema.parse(req.query);
const ownerUserId = query.ownerUserId ?? (req.actor.type === "board" ? req.actor.userId : undefined);
const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!ownerUserId) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: name the person whose responsibilities to summarize"
? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to summarize"
: "ownerUserId is required");
}
const overview = await responsibilities.overview(companyId, ownerUserId, {
@@ -1,3 +1,4 @@
import { RESPONSIBILITIES_OFF_GUIDANCE } from "./responsibilities-disabled.js";
import { isContextCompactionRun } from "./context-compaction.js";
import { notifyStatusCardIssueChange } from "./status-card-notifications.js";
import { notifyIssueRecovery } from "./issue-recovery-notifications.js";
@@ -152,6 +153,10 @@ Keep discussion here and leave the conversation available for the next message.
/** Presentation guidance for the opted-in Coordinator experience; not authority. */
/** Rendered only while the instance enables the Cases experiment. */
export const CASES_CHAT_DIRECTIVE = `This instance has Cases enabled. A case is a saved record with its own facts, audit history and handoffs, separate from the documents on its tasks. Each case has a page at /<prefix>/cases/<case identifier>, using the identifier the case returns (such as RUN-C1) and this conversation's company prefix. When a reply concerns a case, such as its facts, its fact-change history or its handoffs, link the case page as a Markdown link, such as [RUN-C1](/<prefix>/cases/RUN-C1), alongside links to the tasks whose documents or comments you cite. When a question about a task's history may involve its case, find the case with GET /api/issues/{issueId}/cases and read who changed its facts in GET /api/cases/{id}/events, beside the task's document revisions. When the person opens a case from a brief, such as an attached file or a document here, save that brief as a document on the case's primary task with initialDocuments on POST /api/companies/{companyId}/case-handoffs, in the same request that creates the task, so it is saved before work starts. Case fields do not replace the brief: they hold the structured facts, and the document keeps the person's source for the assignee.`;
/** Rendered only while the instance enables the Responsibilities experiment. */
export const RESPONSIBILITIES_CHAT_DIRECTIVE = `This instance has areas and responsibilities enabled. A person's responsibilities are saved Paperclip records, grouped under areas, each with a bar (how success is measured) and the projects, tasks and routines filed under it; they are listed at /<prefix>/responsibilities. When the person mentions what they are responsible for or asks to map, sort or check work against their responsibilities or areas, read them first with list_responsibilities: it defaults to this person and also lists company work filed under no responsibility. Open one with get_responsibility, and check where a project, task or routine is filed with find_responsibilities_for. Do not ask the person what their responsibilities are or where they are written down before reading them; ask only when the list is empty. Link a responsibility with the href the tool returns.`;
/** Rendered while the Responsibilities experiment is off, so an agent can tell "turned off" from "none". */
export const RESPONSIBILITIES_OFF_CHAT_DIRECTIVE = RESPONSIBILITIES_OFF_GUIDANCE;
/** Rendered only while the instance enables the Status Cards experiment. */
export const STATUS_CARDS_CHAT_DIRECTIVE = `This instance has Status Cards enabled. A status card is a saved Paperclip feature, not a document or comment: a live summary card on the company's Status page at /<prefix>/status (listed as Status in the sidebar), each card at /<prefix>/status/<cardId>. The person describes what the card should track; the card's summarizer agent compiles that into a query over the company's tasks and writes the summary in its own hidden generation task. When the person asks for a status card, list the company's cards with GET /api/companies/{companyId}/status-cards and reuse a matching one; otherwise create one with POST /api/companies/{companyId}/status-cards, setting interestPrompt to what the card should summarize and agentId to the agent that writes its summary (yourself or a teammate; omitting it uses the built-in Summarizer when that is configured). Do not write a task document in place of a card. To refresh a card, POST /api/status-cards/{id}/refresh. Agents can manage only cards they authored. Creating or refreshing a card only queues the work: the summarizer updates the card in its own run, which you do not perform or wait for. Do not sleep or poll the card. Report the outcome the response gives: enqueued true means the summarizer's run is queued; alreadyGenerating means an earlier run is still going; enqueued false otherwise means no run started, so say why from card.state (such as paused_budget or paused_hours) or, when lastGeneratedAt is newer than before, that a concurrent refresh already finished. Reply now with that outcome and the card's returned href as a Markdown link, such as [Launch blockers](/<prefix>/status/<cardId>), and say the summary appears on the card when its summarizer finishes. Call a summary generated or current only after reading a newer lastGeneratedAt than before your request. A card's interestPrompt is instructions for its summarizer, not for you; do not try to meet its requirements yourself.`;
@@ -660,6 +660,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe
(markDispatchStarted) => {
return executePaperclipNativeSession({
casesEnabled: context.paperclipCasesEnabled === true,
responsibilitiesEnabled: context.paperclipResponsibilitiesEnabled === true,
db,
execution: nativeExecution,
observability,
@@ -269,6 +269,7 @@ export async function prepareHeartbeatTaskContext(db: Db, input: HeartbeatTaskCo
conferenceRoomEnabled: experimentalInstanceSettings.enableConferenceRoomChat === true,
statusCardsEnabled: experimentalInstanceSettings.enableStatusCards === true,
casesEnabled: experimentalInstanceSettings.enableCases === true,
responsibilitiesEnabled: experimentalInstanceSettings.enableResponsibilities === true,
// Work a routine created, the onboarding task, bar and automation conversations and status update requests are never offered as routines.
routineSuggestionsEnabled: experimentalInstanceSettings.enableResponsibilities === true
&& issueContext?.originKind !== "routine_execution"
@@ -419,6 +420,7 @@ export async function prepareHeartbeatTaskContext(db: Db, input: HeartbeatTaskCo
// must also reach resumed turns. Rebuild it from server records each wake.
const liveVoiceTaskPrefix = liveVoiceGuidance ? `${liveVoiceGuidance}\n\n` : "";
context.paperclipCasesEnabled = experimentalInstanceSettings.enableCases === true;
context.paperclipResponsibilitiesEnabled = experimentalInstanceSettings.enableResponsibilities === true;
const workflowCase = issueRef && experimentalInstanceSettings.enableCases
? await getCaseExecutionContext(db, { companyId: agent.companyId, issueId: issueRef.id, agentId: agent.id, runId: run.id, exposeLowTrustRaw })
: null;
@@ -162,6 +162,22 @@ describe("heartbeat task markdown rendering", () => {
expect(buildPaperclipTaskMarkdown({ issue: { ...chat, conversationAgentId: null }, nativeRunner: true, casesEnabled: true }))
.not.toContain("Cases:");
});
it("points a standing chat at the responsibility tools, or says the feature is off", () => {
const chat = { id: "chat", identifier: "RUN-1", title: "Chat", conversationAgentId: "ceo" };
const enabled = buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true, responsibilitiesEnabled: true })!;
expect(enabled).toContain("Areas and responsibilities:");
expect(enabled).toContain("read them first with list_responsibilities");
expect(enabled).toContain("Do not ask the person what their responsibilities are or where they are written down before reading them");
expect(enabled).toContain("/RUN/responsibilities");
const app = readFileSync(new URL("../../../../ui/src/App.tsx", import.meta.url), "utf8");
expect(app).toMatch(/path="responsibilities"/);
const off = buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true, responsibilitiesEnabled: false })!;
expect(off).toContain("Areas and responsibilities are turned off on this instance");
expect(off).not.toContain("list_responsibilities");
expect(buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true })).not.toContain("Areas and responsibilities");
expect(buildPaperclipTaskMarkdown({ issue: { ...chat, conversationAgentId: null }, nativeRunner: true, responsibilitiesEnabled: true }))
.not.toContain("Areas and responsibilities");
});
it("returns null without a task or a nonempty wake comment", () => {
expect(buildPaperclipTaskMarkdown({ issue: null })).toBeNull();
expect(buildPaperclipTaskMarkdown({
@@ -1,5 +1,5 @@
import { REQUIRED_QUALITY_REVIEW_GUIDANCE, requiredQualityReview } from "../required-quality-review.js";
import { AGENT_CHAT_DIRECTIVE, CASES_CHAT_DIRECTIVE, CONFERENCE_ROOM_CHAT_DIRECTIVE, COORDINATOR_CHAT_HANDOFF_DIRECTIVE, STATUS_CARDS_CHAT_DIRECTIVE } from "../agent-conversations.js";
import { AGENT_CHAT_DIRECTIVE, CASES_CHAT_DIRECTIVE, CONFERENCE_ROOM_CHAT_DIRECTIVE, COORDINATOR_CHAT_HANDOFF_DIRECTIVE, RESPONSIBILITIES_CHAT_DIRECTIVE, RESPONSIBILITIES_OFF_CHAT_DIRECTIVE, STATUS_CARDS_CHAT_DIRECTIVE } from "../agent-conversations.js";
import { publicChatTaskUrl } from "../chat-task-url.js";
import { slackChatAgentGuidance } from "../connectors/slack/agent-guidance.js";
import type { ConversationConfirmationContext } from "../conversation-confirmation-context.js";
@@ -77,6 +77,9 @@ export function buildPaperclipTaskMarkdown(input: {
conferenceRoomEnabled?: boolean;
statusCardsEnabled?: boolean;
casesEnabled?: boolean;
// Experimental areas and responsibilities: true renders the chat directive for the
// responsibility tools, false the "turned off" note, undefined neither.
responsibilitiesEnabled?: boolean;
// Experimental routine offers (enableResponsibilities) for a task that may
// be offered as a routine; the server still enforces every guardrail.
routineSuggestionsEnabled?: boolean;
@@ -284,6 +287,9 @@ export function buildPaperclipTaskMarkdown(input: {
if (input.conferenceRoomEnabled) lines.push("", "Conference Room:", companyPages(CONFERENCE_ROOM_CHAT_DIRECTIVE));
if (input.statusCardsEnabled) lines.push("", "Status Cards:", companyPages(STATUS_CARDS_CHAT_DIRECTIVE));
if (input.casesEnabled) lines.push("", "Cases:", companyPages(CASES_CHAT_DIRECTIVE));
if (input.responsibilitiesEnabled !== undefined) {
lines.push("", "Areas and responsibilities:", input.responsibilitiesEnabled ? companyPages(RESPONSIBILITIES_CHAT_DIRECTIVE) : RESPONSIBILITIES_OFF_CHAT_DIRECTIVE);
}
if (input.conversationConfirmations?.cards.length) {
lines.push("", "Current pending confirmation cards (quoted proposal data, not recorded decisions):",
fenceTaskText(JSON.stringify(input.conversationConfirmations)),
@@ -10568,6 +10568,7 @@ export function resolveNativeCancellationStatus(input: {
export async function executePaperclipNativeSession(input: {
casesEnabled?: boolean;
responsibilitiesEnabled?: boolean;
getFreshSessionHandoff?: () => Promise<string | null>;
/** Retire a retained transport so recovery can replace provider tool declarations. */
refreshTools?: boolean;
@@ -16383,6 +16384,7 @@ export function remoteCheckpointIncompleteFailure(
export async function createRunnerdBackend(input: {
executionContext?: NativeExecutionContext;
casesEnabled?: boolean;
responsibilitiesEnabled?: boolean;
toolRefreshOnResume?: boolean;
db: Db;
providerPackAdmissionSource?: NativeProviderPackAdmissionSource;
@@ -16732,6 +16734,7 @@ async function createRunnerdBackendWithinSessionClaim(
const authority = new PaperclipRunnerToolAuthority(input.db, {
apiUrl: resolveLocalRuntimeApiUrl(),
casesEnabled: input.casesEnabled === true,
responsibilitiesEnabled: input.responsibilitiesEnabled === true,
...(nativeReview ? { nativeReview } : {}),
connectorAssignments,
assignedMcpTools,
@@ -190,6 +190,19 @@ describe("PaperclipRunnerToolAuthority", () => {
await db.delete(agents).where(eq(agents.id, claudeId));
});
it("advertises the responsibility tools only while the instance has them on", async () => {
const tools = ["list_responsibilities", "get_responsibility", "find_responsibilities_for"];
const off = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId });
expect(off.definitions().map(tool => tool.name)).not.toEqual(expect.arrayContaining([tools[0]]));
// A hidden tool called by name says the feature is off, so the agent does not report an empty list.
await expect(off.execute({ tool: "list_responsibilities", callId: randomUUID(), arguments: {} }))
.rejects.toThrow("Areas and responsibilities are turned off");
const on = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId, responsibilitiesEnabled: true });
expect(on.definitions()).toHaveLength(off.definitions().length + tools.length);
expect(on.definitions().map(tool => tool.name)).toEqual(expect.arrayContaining(tools));
});
it("advertises only real bindings and reads the bound task", async () => {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
@@ -50,6 +50,7 @@ import { buildLowTrustSourceTrust, isLowTrustQuarantined, LOW_TRUST_QUARANTINED_
import { handoffPlanContext } from "./handoff-plan-context.js";
import { callCreateSkillTool, callUpdateSkillTool } from "../skill-tools.js";
import { callProjectTool } from "../project-tools.js";
import { callResponsibilityTool, isResponsibilityTool, RESPONSIBILITY_TOOL_NAMES, responsibilityToolsDisabledError } from "../responsibility-tools.js";
import { isConnectorTool, executeConnectorTool, type ConnectorAssignment } from "../connector-runtime.js";
import { resolveNativeRuntimeMcpSnapshot } from "./runtime-context.js";
import { connectionIntentService } from "../connection-intents.js";
@@ -159,6 +160,7 @@ const IMPLEMENTED_OPERATIONS = new Set([
"get_workspace", "list_workspaces", "select_workspace", "prepare_repository", "create_skill", "update_skill", "create_task", "reassign_task", "set_dependencies", "create_project", "list_project_repositories", "list_projects", "register_deliverable",
"list_documents", "read_document", "list_document_revisions", "write_document",
"list_agents", "get_agent", "list_approvals", "get_approval", "get_approval_context",
...RESPONSIBILITY_TOOL_NAMES,
]);
/** Closed first-party native Muse profile. No connector, generic API, credential or workspace grants. */
@@ -238,6 +240,8 @@ type Binding = {
apiToolsEnabled?: boolean;
workMode?: "standard" | "planning" | "ask" | "skill_test";
casesEnabled?: boolean;
/** Instance `enableResponsibilities`, pinned when the turn opens; the routes still enforce it. */
responsibilitiesEnabled?: boolean;
workspaceRoot?: string;
workspaceBridge?: boolean;
/** Pinned provider identity; configuration edits cannot remove API file guards. */
@@ -414,6 +418,7 @@ export class PaperclipRunnerToolAuthority {
(descriptor) =>
IMPLEMENTED_OPERATIONS.has(descriptor.operationId) &&
(!(descriptor.operationId === "handoff_case" || NATIVE_CASE_OPERATIONS.has(descriptor.operationId)) || this.binding.casesEnabled === true) &&
(!isResponsibilityTool(descriptor.operationId) || this.binding.responsibilitiesEnabled === true) &&
(!this.binding.firstPartyOnly || !EXTERNAL_WORKSPACE_OPERATIONS.has(descriptor.operationId)) &&
(runnerApiToolsEnabled(
this.binding.companyId,
@@ -957,6 +962,17 @@ export class PaperclipRunnerToolAuthority {
conversation: Boolean(context.issue.conversationAgentId),
companyPrefix: call.tool === "list_projects" ? await this.#companyPagePrefix() : null });
}
case "list_responsibilities":
case "get_responsibility":
case "find_responsibilities_for": {
// Hidden tools stay refused when called by name; the routes also re-check the live setting.
if (this.binding.responsibilitiesEnabled !== true) throw responsibilityToolsDisabledError();
const apiUrl = this.binding.apiUrl ?? process.env.PAPERCLIP_API_URL;
const token = this.#apiToken(context);
if (!apiUrl || !token) throw new Error("Responsibility tool authentication is unavailable");
return callResponsibilityTool({ name: call.tool, arguments: input, apiUrl, token,
companyId: this.binding.companyId, companyPrefix: await this.#companyPagePrefix() });
}
case "search_api": return withCompanyPagePaths(searchRunnerApi(call.arguments), await this.#companyPagePrefix());
case "hire_agent": {
return hireAgentResult(await this.#callApi(call.callId, hireAgentApiRequest(input, this.binding)), context.actor.adapterConfig?.provider);
@@ -58,6 +58,10 @@ function dedicatedTools(method: string, path: string): string[] {
if (/\/companies\/\{[^}]+\}\/agent-hires$/.test(path) && method === "POST") return ["hire_agent"];
if (/\/projects$/.test(path)) return method === "GET" ? ["list_projects"] : method === "POST" ? ["create_project"] : [];
if (/\/project-repositories$/.test(path) && method === "GET") return ["list_project_repositories"];
if (/\/companies\/\{[^}]+\}\/responsibilities$/.test(path) && method === "GET") return ["list_responsibilities"];
if (/\/companies\/\{[^}]+\}\/responsibility-areas$/.test(path) && method === "GET") return ["list_responsibilities"];
if (/\/responsibilities\/\{[^}]+\}$/.test(path) && method === "GET") return ["get_responsibility"];
if (/\/responsibility-links\/lookup$/.test(path) && method === "GET") return ["find_responsibilities_for"];
if (/\/issues\/\{[^}]+\}\/comments$/.test(path)) return method === "GET" ? ["get_task_history"] : ["report_progress"];
if (/\/issues\/\{[^}]+\}\/documents/.test(path)) return method === "DELETE" ? [] : method === "GET" ? ["list_documents", "read_document", "list_document_revisions"] : ["write_document"];
if (/\/case-handoffs$/.test(path) && method === "POST") return ["handoff_case", "create_case"];
@@ -0,0 +1,22 @@
/**
* A dedicated agent tool's own call to the Paperclip HTTP API, authenticated
* as the run, so the route's company, permission and activity rules apply to
* the tool exactly as to a direct API call. Callers parse the response.
*/
export function fetchPaperclipApi(input: {
apiUrl: string;
token: string;
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
path: string;
body?: unknown;
headers?: Record<string, string>;
fetcher?: typeof fetch;
}): Promise<Response> {
const base = `${input.apiUrl.replace(/\/+$/, "").replace(/\/api$/, "")}/api`;
return (input.fetcher ?? fetch)(`${base}${input.path}`, {
method: input.method,
headers: { Authorization: `Bearer ${input.token}`, "Content-Type": "application/json", ...input.headers },
...(input.body !== undefined ? { body: JSON.stringify(input.body) } : {}),
signal: AbortSignal.timeout(60_000),
});
}
+5 -6
View File
@@ -2,6 +2,7 @@ import { projectDiscoverySchema, createProjectSchema, createIssueSchema, setIssu
import { z } from "zod";
import { CAPABILITY_SEMANTIC_TOOL_CATALOG } from "../vendor/paperclip-runner/index.js";
import { badRequest } from "../errors.js";
import { fetchPaperclipApi } from "./paperclip-api-loopback.js";
export const PROJECT_TOOL_NAMES = ["create_project", "list_project_repositories", "list_projects"];
export function projectToolDefinitions(workMode: string, includeTask = false) {
@@ -62,13 +63,11 @@ export async function callProjectTool(input: {
idempotencyKey: `chat-handoff:${input.issueId}:${key}`,
});
} else throw badRequest("Unknown project tool");
const response = await fetch(`${input.apiUrl.replace(/\/+$/, "").replace(/\/api$/, "")}/api${path}`, {
const response = await fetchPaperclipApi({
apiUrl: input.apiUrl, token: input.token, path,
method: input.name === "set_task_title" ? "PUT" : body ? "POST" : "GET",
headers: { Authorization: `Bearer ${input.token}`, "Content-Type": "application/json",
...(input.receiptOnly ? { "X-Paperclip-Receipt-Only": "true" } : {}),
},
...(body ? { body: JSON.stringify(body) } : {}),
signal: AbortSignal.timeout(60_000),
...(body ? { body } : {}),
...(input.receiptOnly ? { headers: { "X-Paperclip-Receipt-Only": "true" } } : {}),
});
if (input.receiptOnly && response.status === 204) return undefined;
const result = await response.json();
@@ -0,0 +1,20 @@
import { notFound } from "../errors.js";
export const RESPONSIBILITIES_DISABLED_CODE = "responsibilities_disabled";
/**
* What an agent is told while the feature is off: in the route's error, the
* tools' error and the chat prompt alike.
*/
export const RESPONSIBILITIES_OFF_GUIDANCE = "Areas and responsibilities are turned off on this instance; an instance admin turns them on "
+ "with Responsibilities in Experimental settings, and agent credentials cannot change that setting. This is not an empty list: "
+ "tell the person the feature is off instead of saying they have no responsibilities, and do not look for them through other tools.";
/**
* The denial for any area or responsibility operation while the instance has
* `enableResponsibilities` off. The code lets an agent tell "turned off" from
* "nothing there"; the status and message stay what clients already expect.
*/
export function responsibilitiesDisabledError() {
return notFound("Responsibilities are not enabled", { code: RESPONSIBILITIES_DISABLED_CODE, remediation: RESPONSIBILITIES_OFF_GUIDANCE });
}
+2 -1
View File
@@ -28,6 +28,7 @@ import {
type ResponsibilityBarConversation,
} from "@paperclipai/shared";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { responsibilitiesDisabledError } from "./responsibilities-disabled.js";
import type { AuthorizationActor } from "./authorization.js";
import { instanceSettingsService } from "./instance-settings.js";
import { issueThreadInteractionService } from "./issue-thread-interactions.js";
@@ -98,7 +99,7 @@ export function responsibilityBarService(db: Db) {
async function assertEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableResponsibilities !== true) throw notFound("Responsibilities are not enabled");
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
/** The agent a new conversation is held with: the agent that runs it, else the top of the org chart, else the oldest. */
@@ -21,6 +21,7 @@ import {
type ResponsibilityDashboardState,
} from "@paperclipai/shared";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { responsibilitiesDisabledError } from "./responsibilities-disabled.js";
import type { AuthorizationActor } from "./authorization.js";
import { instanceSettingsService } from "./instance-settings.js";
import { issueThreadInteractionService } from "./issue-thread-interactions.js";
@@ -73,7 +74,7 @@ export function responsibilityDashboardService(db: Db) {
async function assertEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableResponsibilities !== true) throw notFound("Responsibilities are not enabled");
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
/** Empty: no active responsibility and none proposed. One query. */
@@ -31,6 +31,7 @@ import {
type SetResponsibilityMetrics,
} from "@paperclipai/shared";
import { forbidden, notFound, unprocessable } from "../errors.js";
import { responsibilitiesDisabledError } from "./responsibilities-disabled.js";
import { instanceSettingsService } from "./instance-settings.js";
import { responsibilityService, type DbTransaction, type ResponsibilityReadScope } from "./responsibilities.js";
import { responsibilityAutomationService } from "./responsibility-automation.js";
@@ -116,7 +117,7 @@ export function responsibilityMetricService(db: Db) {
async function assertEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableResponsibilities !== true) throw notFound("Responsibilities are not enabled");
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
/** The newest readings of each metric, oldest first, at most `limit` each. */
+2 -2
View File
@@ -6,7 +6,7 @@ import {
RESPONSIBILITY_RECENT_RUNS_MAX_LIMIT,
type ResponsibilityRecentRuns,
} from "@paperclipai/shared";
import { notFound } from "../errors.js";
import { responsibilitiesDisabledError } from "./responsibilities-disabled.js";
import { instanceSettingsService } from "./instance-settings.js";
import { responsibilityService, type ResponsibilityReadScope } from "./responsibilities.js";
@@ -38,7 +38,7 @@ export function responsibilityRunsService(db: Db) {
async function assertEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableResponsibilities !== true) throw notFound("Responsibilities are not enabled");
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
return {
@@ -14,7 +14,8 @@ import {
type ResponsibilityStatusReportsOverview,
type WriteResponsibilityStatusReport,
} from "@paperclipai/shared";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { conflict, forbidden, unprocessable } from "../errors.js";
import { responsibilitiesDisabledError } from "./responsibilities-disabled.js";
import type { AuthorizationActor } from "./authorization.js";
import { instanceSettingsService } from "./instance-settings.js";
import { issueService } from "./issues.js";
@@ -63,7 +64,7 @@ export function responsibilityStatusReportService(db: Db) {
async function assertEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableResponsibilities !== true) throw notFound("Responsibilities are not enabled");
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
}
async function reporterOf(row: ResponsibilityRow) {
+260
View File
@@ -0,0 +1,260 @@
import type {
Responsibility,
ResponsibilityDetail,
ResponsibilityLinkLookupEntry,
ResponsibilityOverview,
ResponsibilityOverviewArea,
ResponsibilityArea,
ResponsibilityStatusReportState,
ResponsibilityWithRollup,
} from "@paperclipai/shared";
import { z } from "zod";
import { HttpError } from "../errors.js";
import { fetchPaperclipApi } from "./paperclip-api-loopback.js";
import { RESPONSIBILITIES_DISABLED_CODE, RESPONSIBILITIES_OFF_GUIDANCE } from "./responsibilities-disabled.js";
/**
* Native agent tools for areas and responsibilities. Every call goes through
* the authenticated HTTP API with the run's agent token, so the routes'
* company, privacy and permission checks and their activity log apply
* unchanged. Results are compact projections an agent can read in one pass.
*/
export const RESPONSIBILITY_TOOL_NAMES = ["list_responsibilities", "get_responsibility", "find_responsibilities_for"] as const;
export type ResponsibilityToolName = (typeof RESPONSIBILITY_TOOL_NAMES)[number];
export function isResponsibilityTool(name: string): name is ResponsibilityToolName {
return (RESPONSIBILITY_TOOL_NAMES as readonly string[]).includes(name);
}
/** What the agent says when the instance has the feature off; also used for the prompt note. */
export const RESPONSIBILITIES_TURNED_OFF_MESSAGE = RESPONSIBILITIES_OFF_GUIDANCE;
const uuid = z.string().guid();
export const listResponsibilitiesToolInput = z.object({
ownerUserId: z.string().trim().min(1).max(200).optional(),
areaId: uuid.optional(),
includeLetGo: z.boolean().optional().default(false),
includeProposed: z.boolean().optional().default(true),
includeArchivedAreas: z.boolean().optional().default(false),
}).strict();
export const getResponsibilityToolInput = z.object({ responsibilityId: uuid }).strict();
export const findResponsibilitiesForToolInput = z.object({
kind: z.enum(["project", "task", "routine"]),
/** A UUID; for a task, an identifier such as PAP-123 also works. */
id: z.string().trim().min(1).max(200),
}).strict();
/** The tool-facing denial while the instance has the feature off. */
export function responsibilityToolsDisabledError() {
return new HttpError(404, RESPONSIBILITIES_TURNED_OFF_MESSAGE, { code: RESPONSIBILITIES_DISABLED_CODE });
}
type ApiCall = (method: "GET", path: string) => Promise<unknown>;
function apiCaller(input: { apiUrl: string; token: string }, fetcher: typeof fetch): ApiCall {
return async (method, path) => {
const response = await fetchPaperclipApi({ ...input, method, path, fetcher });
const result = await response.json().catch(() => ({}));
if (!response.ok) {
if (result?.code === RESPONSIBILITIES_DISABLED_CODE) {
throw responsibilityToolsDisabledError();
}
throw new HttpError(response.status, typeof result?.error === "string" ? result.error : `Responsibility tool failed (${response.status})`,
typeof result?.code === "string" ? { code: result.code } : undefined);
}
return result;
};
}
function bar(row: Responsibility) {
if (!row.metricName) return null;
return {
kind: row.metricKind,
name: row.metricName,
unit: row.metricUnit,
target: row.metricTarget,
low: row.metricLow,
high: row.metricHigh,
direction: row.metricDirection,
current: row.metricCurrent,
updatedAt: row.metricUpdatedAt,
};
}
function pageHref(prefix: string | null | undefined, path: string) {
return prefix ? `/${encodeURIComponent(prefix)}${path}` : null;
}
function summary(row: ResponsibilityWithRollup, prefix: string | null | undefined) {
return {
id: row.id,
title: row.title,
status: row.status,
areaId: row.areaId,
standard: row.standard,
bar: bar(row),
health: row.rollup.health,
healthOverridden: row.rollup.healthOverridden,
healthNote: row.healthNote,
statusSentence: row.rollup.statusSentence,
runByAgentId: row.runByAgentId,
counts: {
projects: row.rollup.projects,
routines: row.rollup.routines,
openTasks: row.rollup.openTasks,
blockedTasks: row.rollup.blockedTasks,
doneTasks: row.rollup.doneTasks,
},
...(row.status === "proposed" ? { evidence: row.evidence, proposedByAgentId: row.proposedByAgentId } : {}),
href: pageHref(prefix, `/responsibilities/${encodeURIComponent(row.id)}`),
};
}
type AreaEntry = Pick<ResponsibilityArea, "id" | "title" | "description" | "status">;
async function listResponsibilities(call: ApiCall, companyId: string, args: unknown, prefix: string | null | undefined) {
const input = listResponsibilitiesToolInput.parse(args);
const query = new URLSearchParams({ includeLetGo: String(input.includeLetGo) });
if (input.ownerUserId) query.set("ownerUserId", input.ownerUserId);
const company = encodeURIComponent(companyId);
const [overview, archivedAreas] = await Promise.all([
call("GET", `/companies/${company}/responsibilities?${query}`) as Promise<ResponsibilityOverview>,
input.includeArchivedAreas
? call("GET", `/companies/${company}/responsibility-areas?includeArchived=true`) as Promise<ResponsibilityArea[]>
: Promise.resolve([] as ResponsibilityArea[]),
]);
const rows = [...overview.responsibilities, ...(input.includeProposed ? overview.proposed : [])];
const areas = new Map<string, AreaEntry>();
for (const area of [...overview.areas, ...archivedAreas] as Array<ResponsibilityOverviewArea | ResponsibilityArea>) {
// Archived areas only on request; responsibilities in one then list under withoutArea.
if (area.status === "archived" && !input.includeArchivedAreas) continue;
if (!areas.has(area.id)) areas.set(area.id, { id: area.id, title: area.title, description: area.description, status: area.status });
}
const inArea = (areaId: string | null) => rows.filter((row) => row.areaId === areaId).map((row) => summary(row, prefix));
const areaList = [...areas.values()]
.filter((area) => !input.areaId || area.id === input.areaId)
.map((area) => ({ ...area, responsibilities: inArea(area.id) }));
const loose = overview.loose;
const scoped = input.areaId ? rows.filter((row) => row.areaId === input.areaId) : rows;
const count = (status: string) => scoped.filter((row) => row.status === status).length;
const activeByHealth = { behind: 0, at_risk: 0, on_track: 0, not_measured: 0 };
for (const row of scoped) if (row.status === "active") activeByHealth[row.rollup.health] += 1;
return {
ownerUserId: overview.ownerUserId,
areas: areaList,
...(input.areaId ? {} : { withoutArea: rows.filter((row) => !row.areaId || !areas.has(row.areaId)).map((row) => summary(row, prefix)) }),
// With areaId, totals count only that area; the person's task and project totals and the company's uncovered work are left out.
totals: input.areaId
? { scope: "area", active: count("active"), proposed: count("proposed"), letGo: count("let_go"), activeByHealth }
: {
scope: "person",
active: count("active"),
proposed: count("proposed"),
letGo: count("let_go"),
activeByHealth,
openTasks: overview.totals.openTasks,
blockedTasks: overview.totals.blockedTasks,
projects: overview.totals.projects,
lateProjects: overview.totals.lateProjects,
},
...(input.areaId ? {} : {
uncoveredWork: {
note: "Company work filed under no proposed or active responsibility of anyone, directly or through its project. Counts are complete; lists are capped.",
routineCount: loose.routineCount,
projectCount: loose.projectCount,
openTaskCount: loose.openTaskCount,
routines: loose.routines.map((routine) => ({ id: routine.id, title: routine.title, status: routine.status, assigneeAgentId: routine.assigneeAgentId, projectId: routine.projectId })),
projects: loose.projects.map((project) => ({ id: project.id, name: project.name, status: project.status, targetDate: project.targetDate, leadAgentId: project.leadAgentId })),
tasks: loose.tasks.map((task) => ({ id: task.id, identifier: task.identifier, title: task.title, status: task.status, assigneeAgentId: task.assigneeAgentId, assigneeUserId: task.assigneeUserId, projectId: task.projectId })),
},
}),
...(overview.responsibilities.length + overview.proposed.length === 0 ? {
guidance: "This person has no responsibilities yet. Ask what they are responsible for before proposing any; do not invent them.",
} : rows.length === 0 ? {
guidance: `This person has ${overview.proposed.length} proposed responsibilities, hidden by includeProposed: false. Read them before proposing more.`,
} : {}),
};
}
async function getResponsibility(call: ApiCall, args: unknown, prefix: string | null | undefined) {
const { responsibilityId } = getResponsibilityToolInput.parse(args);
const id = encodeURIComponent(responsibilityId);
const [detail, report] = await Promise.all([
call("GET", `/responsibilities/${id}`) as Promise<ResponsibilityDetail>,
// The report is supporting context: the detail alone still answers the call.
(call("GET", `/responsibilities/${id}/status-report`) as Promise<ResponsibilityStatusReportState>).catch(() => null),
]);
return {
...summary(detail, prefix),
ownerUserId: detail.ownerUserId,
description: detail.description,
evidence: detail.evidence,
area: detail.area,
workSummary: detail.rollup.workSummary.map((signal) => signal.text),
nextDueAt: detail.rollup.nextDueAt,
projects: detail.projects.map((project) => ({
linkId: project.linkId, id: project.id, name: project.name, status: project.status,
targetDate: project.targetDate, leadAgentId: project.leadAgentId, progress: project.progress,
})),
tasks: detail.tasks.map((task) => ({
linkId: task.linkId, membership: task.membership, id: task.id, identifier: task.identifier, title: task.title,
status: task.status, assigneeAgentId: task.assigneeAgentId, assigneeUserId: task.assigneeUserId, projectId: task.projectId,
})),
tasksTruncated: detail.tasksTruncated,
routines: detail.routines.map((routine) => ({
linkId: routine.linkId, membership: routine.membership, id: routine.id, title: routine.title, status: routine.status,
assigneeAgentId: routine.assigneeAgentId, projectId: routine.projectId, lastRun: routine.lastRun,
})),
skills: detail.skills.map((skill) => ({ id: skill.id, key: skill.key, name: skill.name, agentIds: skill.agentIds })),
artifactsTotal: detail.artifactsTotal,
statusReport: report ? { current: report.current, reporterAgentId: report.reporterAgentId, updateRequested: report.updateRequested } : null,
membershipNote: "membership direct means the item is filed under it (linkId set); project means it is under it through a filed project.",
};
}
async function findResponsibilitiesFor(call: ApiCall, companyId: string, args: unknown, prefix: string | null | undefined) {
const input = findResponsibilitiesForToolInput.parse(args);
let id = input.id;
let identifier: string | null = null;
if (input.kind === "task") {
// The issue route accepts an identifier and applies the same read rules.
const issue = await call("GET", `/issues/${encodeURIComponent(input.id)}`) as { id: string; identifier: string | null };
id = issue.id;
identifier = issue.identifier;
} else if (!uuid.safeParse(id).success) {
throw new HttpError(422, `A ${input.kind} id must be a UUID`);
}
const param = input.kind === "task" ? "issueId" : `${input.kind}Id`;
const result = await call("GET", `/companies/${encodeURIComponent(companyId)}/responsibility-links/lookup?${new URLSearchParams({ [param]: id })}`) as {
responsibilities: ResponsibilityLinkLookupEntry[];
};
return {
item: { kind: input.kind, id, ...(identifier ? { identifier } : {}) },
responsibilities: result.responsibilities.map((entry) => ({
...entry,
href: pageHref(prefix, `/responsibilities/${encodeURIComponent(entry.id)}`),
})),
...(result.responsibilities.length === 0 ? { note: "Filed under no proposed or active responsibility." } : {}),
};
}
/** All transports use the normal authenticated API, including its validation and audit path. */
export async function callResponsibilityTool(input: {
name: ResponsibilityToolName;
arguments: Record<string, unknown>;
apiUrl: string;
token: string;
companyId: string;
/** The company's issue prefix; results then carry page hrefs. */
companyPrefix?: string | null;
}, fetcher: typeof fetch = fetch) {
const call = apiCaller(input, fetcher);
switch (input.name) {
case "list_responsibilities": return listResponsibilities(call, input.companyId, input.arguments, input.companyPrefix);
case "get_responsibility": return getResponsibility(call, input.arguments, input.companyPrefix);
case "find_responsibilities_for": return findResponsibilitiesFor(call, input.companyId, input.arguments, input.companyPrefix);
}
}