mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 18:26:40 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A responsibility shows the skills of the agents doing its work. People cannot say which skills a responsibility needs. > - The maintainer chose to file skills under responsibilities like projects, tasks and routines. > - Agents also need to set a skill's catalog details without rewriting its SKILL.md. > - This pull request lets people and agents file, move and remove company skills under a responsibility, and adds `update_skill_details`. > - The benefit is that a responsibility lists the skills it needs, beside the skills its agents already hold. ## Linked Issues or Issue Description Refs #22253, #22261 and #22274; this pull request is stacked on them. **Subsystem affected** Database (`responsibility_links`), shared types and validators, server responsibility service and routes, Dashboard versions, native runner tools, and the responsibility page UI. **Problem or motivation** Skills under a responsibility are only computed from the agents doing its work. A person cannot record that "Hiring needs interviewing", and an agent cannot file a skill when it maps work for a person. **Proposed solution** Add a nullable `skill_id` to `responsibility_links` and allow it as the one target of a link. Show filed and computed skills together. Let the file, unfile, lookup and link routes and tools take skills. Keep filed skills in Dashboard versions so undo covers them. Add a small live tool for a skill's tagline and categories. **Alternatives considered** Keeping skills computed only, and giving the skill to the agent that runs the responsibility, was the other option. It was not chosen. Extending `update_skill` would change its scenario contract, whose mock needs `markdown`, so the details tool is separate. ## What Changed - Review fixes: the default responsibility view's Skills "+" adds an existing skill, removes a filed one, or opens an agent's skills page. A newest Dashboard version without a skill list is upgraded in place, so the first skill filed after it is undone. Undo files again, or removes, only skills the restoring person can see. A read scope without a skill condition sees no filed skill. `update_skill_details` with only `skillId` is a no-op, as its schema allows. - Migration `0499`: add `responsibility_links.skill_id` (FK to `company_skills`, on delete cascade). Widen the single-target check to four targets. Add a unique `(responsibility_id, skill_id)` index and a `skill_id` index. The migration is idempotent and online-compatible (NOT VALID then VALIDATE, and the indexes are built CONCURRENTLY). It is listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`. - Shared: `ResponsibilityLink.skillId`; `ResponsibilitySkillSummary.linkId` and `computed`; `skillId` in the link and lookup schemas; `skill` in `RESPONSIBILITY_FILE_ITEM_KINDS`; optional `skillIds` in Dashboard snapshot links. - Server: filing checks the reader's skill visibility (`skillAccessService`). The detail merges filed and computed skills into one card each. Lookup accepts `skillId`. Dashboard capture, restore and summary include filed skills. A version without `skillIds` leaves filed skills as they are when it is restored. - Tools: `file_under_responsibility`, `remove_from_responsibility` and `find_responsibilities_for` accept `kind: "skill"`. `get_responsibility` returns `linkId` and `computed` for each skill. Add `update_skill_details` (tagline and categories). - UI: the responsibility page has "Add existing skill". A filed skill shows "Filed here" and a remove button. Computed skills keep their holders. ## Verification - Server: the `responsibilit*` tests (new: file, find, move and unfile a skill; one card for a skill that is both filed and computed; undo of a filed skill from the Dashboard history), `skill-tools.test.ts` (new `update_skill_details` cases), `responsibility-tools`, `routine-tools`, `routines-routes`, `paperclip-runner-tool-authority`, `runner-api` and `openapi-routes`: 24 files, 2723 tests passed. - UI: responsibility page and component tests (16 files, 158 tests, including a new filed-skill test) pass. `pnpm --filter @paperclipai/ui typecheck` passed. - `@paperclipai/db` `check:migrations` passes and reports the override. The snapshot drift test passes. `tsc` passes for `db`, `shared` and the server layers. - Runner: catalog and semantic-tool tests (317) pass. All generator checks pass. ## Risks - The migration changes a check constraint on `responsibility_links`. The replacement accepts every row that the old check accepted. It is swapped as NOT VALID and then validated. The previous release never sets `skill_id`. - Deleting a company skill removes its links (cascade). - Filed skills follow the reader's skill visibility. A skill the reader may not see is not listed. ## 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> Co-authored-by: Paperclip <noreply@paperclip.ing>
210 lines
15 KiB
TypeScript
210 lines
15 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { z } from "zod";
|
|
import { buildOpenApiDocument } from "../../routes/openapi.js";
|
|
import { badRequest, notFound } from "../../errors.js";
|
|
import { runnerApiReference } from "./runner-api-reference.js";
|
|
import { CAPABILITY_SEMANTIC_TOOL_CATALOG } from "../../vendor/paperclip-runner/index.js";
|
|
|
|
type Json = Record<string, any>;
|
|
export interface RunnerApiOperation {
|
|
operationId: string;
|
|
method: string;
|
|
path: string;
|
|
summary: string;
|
|
description: string;
|
|
parameters: Json[];
|
|
requestBody?: Json;
|
|
responses: Json;
|
|
authorization: Json;
|
|
transport: "rest" | "protocol";
|
|
dedicatedTools: string[];
|
|
allowedModes: string[];
|
|
skillReference?: { section: string; description?: string; examples?: { body: unknown }[] };
|
|
dedicatedToolGuidance: string;
|
|
dedicatedToolCapabilities?: { name: string; description: string; supportedParameters: string[] }[];
|
|
runnerRestrictions?: string[];
|
|
callPolicy: "rest" | "protocol";
|
|
}
|
|
|
|
const METHODS = new Set(["get", "post", "put", "patch", "delete", "head", "options"]);
|
|
const SYNONYMS: Record<string, string> = {
|
|
task: "issue", tasks: "issues", employee: "agent", employees: "agents",
|
|
hire: "agent", hiring: "agents", expense: "cost", expenses: "costs",
|
|
cron: "routines", schedule: "routines", recurring: "routines",
|
|
blocker: "dependencies", blockers: "dependencies", files: "attachments",
|
|
};
|
|
|
|
// Function words carry no resource meaning; scoring them let any summary that
|
|
// happens to say "for" or "the" outrank the operation a query names.
|
|
const SEARCH_FUNCTION_WORDS = new Set(["a", "an", "the", "for", "of", "to", "in", "on", "at", "by", "with", "and", "or", "from"]);
|
|
|
|
function words(text: string): string[] {
|
|
return text.toLowerCase().split(/[^a-z0-9]+/).filter((word) => word.length > 0 && !SEARCH_FUNCTION_WORDS.has(word))
|
|
.flatMap((word) => [word, ...(SYNONYMS[word] ? [SYNONYMS[word]] : [])])
|
|
.map((word) => word.length > 3 && word.endsWith("s") ? word.slice(0, -1) : word);
|
|
}
|
|
|
|
function dedicatedTools(method: string, path: string): string[] {
|
|
if (method === "POST" && path === "/api/agents/me/chat/messages") return ["send_chat_message"];
|
|
if (/\/companies\/\{[^}]+\}\/workflows$/.test(path)) return method === "GET" ? ["list_workflows"] : method === "POST" ? ["create_workflow"] : [];
|
|
if (/\/workflows\/\{[^}]+\}$/.test(path)) return method === "GET" ? ["read_workflow"] : method === "PATCH" ? ["update_workflow"] : [];
|
|
if (/\/issues\/\{[^}]+\}\/title$/.test(path) && method === "PUT") return ["set_task_title"];
|
|
if (/\/agents\/\{[^}]+\}\/instructions-bundle\/file$/.test(path)) return method === "GET" ? ["read_agent_instructions"] : method === "PUT" ? ["update_agent_instructions"] : [];
|
|
if (/\/agents\/\{[^}]+\}\/instructions-bundle\/history$/.test(path) && method === "GET") return ["get_agent_instruction_history"];
|
|
if (/\/agents\/\{[^}]+\}\/instructions-bundle\/revision\/\{[^}]+\}$/.test(path) && method === "GET") return ["read_agent_instructions"];
|
|
if (/\/agents\/\{[^}]+\}\/instructions-bundle\/restore$/.test(path) && method === "POST") return ["restore_agent_instructions"];
|
|
if (/\/companies\/\{[^}]+\}\/skills$/.test(path) && method === "POST") return ["create_skill"];
|
|
if (/\/companies\/\{[^}]+\}\/skills\/\{[^}]+\}\/files$/.test(path) && method === "PATCH") return ["update_skill"];
|
|
if (/\/companies\/\{[^}]+\}\/skills\/\{[^}]+\}$/.test(path) && method === "PATCH") return ["update_skill_details"];
|
|
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\/\{[^}]+\}\/routines$/.test(path) && method === "GET") return ["list_routines"];
|
|
if (/\/routines\/\{[^}]+\}$/.test(path) && method === "PATCH") return ["update_routine"];
|
|
if (/\/routines\/\{[^}]+\}\/triggers$/.test(path) && method === "POST") return ["update_routine"];
|
|
if (/\/routine-triggers\/\{[^}]+\}$/.test(path) && method === "PATCH") return ["update_routine"];
|
|
if (/\/companies\/\{[^}]+\}\/responsibilities$/.test(path)) return method === "GET" ? ["list_responsibilities"] : method === "POST" ? ["create_responsibility"] : [];
|
|
if (/\/companies\/\{[^}]+\}\/responsibility-areas$/.test(path)) return method === "GET" ? ["list_responsibilities"] : method === "POST" ? ["create_area"] : [];
|
|
if (/\/responsibility-areas\/\{[^}]+\}$/.test(path)) return method === "PATCH" ? ["update_area"] : method === "DELETE" ? ["delete_area"] : [];
|
|
if (/\/responsibilities\/\{[^}]+\}$/.test(path)) {
|
|
return method === "GET" ? ["get_responsibility"] : method === "PATCH" ? ["update_responsibility"] : method === "DELETE" ? ["delete_responsibility"] : [];
|
|
}
|
|
if (/\/responsibilities\/\{[^}]+\}\/(file|links)$/.test(path) && method === "POST") return ["file_under_responsibility"];
|
|
if (/\/responsibilities\/\{[^}]+\}\/(unfile|links\/\{[^}]+\})$/.test(path)) return method === "POST" || method === "DELETE" ? ["remove_from_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"];
|
|
if (/\/cases\/\{[^}]+\}$/.test(path)) return method === "GET" ? ["read_case"] : method === "PATCH" ? ["update_case"] : [];
|
|
if (/\/issues$/.test(path)) return method === "GET" ? ["search_tasks"] : ["create_task"];
|
|
if (/\/issues\/\{[^}]+\}$/.test(path)) return method === "GET" ? ["get_task_context"] : ["reassign_task", "set_dependencies", "finish_task", "block_task", "request_review"];
|
|
if (/\/agents$/.test(path) && method === "GET") return ["list_agents"];
|
|
if (/\/agents\/(me|\{[^}]+\})$/.test(path) && method === "GET") return ["get_agent"];
|
|
if (/\/approvals$/.test(path) && method === "GET") return ["list_approvals"];
|
|
if (/\/approvals\/\{[^}]+\}/.test(path) && method === "GET") return ["get_approval", "get_approval_context"];
|
|
return [];
|
|
}
|
|
|
|
// Descriptions and schemas are documentation, never authorization. Routes remain
|
|
// authoritative, including conditional role, company and resource checks.
|
|
export function buildRunnerApiCatalog(document: Json = buildOpenApiDocument()): RunnerApiOperation[] {
|
|
function dereference(value: any, seen = new Set<string>()): any {
|
|
if (Array.isArray(value)) return value.map((entry) => dereference(entry, seen));
|
|
if (!value || typeof value !== "object") return value;
|
|
if (typeof value.$ref === "string" && value.$ref.startsWith("#/")) {
|
|
if (seen.has(value.$ref)) return { description: `Recursive schema: ${value.$ref}` };
|
|
const target = value.$ref.slice(2).split("/").reduce((node: any, key: string) => node?.[key.replace(/~1/g, "/").replace(/~0/g, "~")], document);
|
|
if (!target) throw new Error(`Unresolved API schema: ${value.$ref}`);
|
|
return dereference(target, new Set([...seen, value.$ref]));
|
|
}
|
|
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, dereference(entry, seen)]));
|
|
}
|
|
const result: RunnerApiOperation[] = [];
|
|
for (const [path, item] of Object.entries<Json>(document.paths)) {
|
|
for (const [verb, operation] of Object.entries<Json>(item)) {
|
|
if (!METHODS.has(verb)) continue;
|
|
const method = verb.toUpperCase();
|
|
const conversationalConfirmation = method === "POST"
|
|
&& /^\/api\/issues\/\{[^}]+\}\/interactions\/\{[^}]+\}\/resolve-from-comment$/.test(path);
|
|
const taskTitleUpdate = method === "PUT" && /^\/api\/issues\/\{[^}]+\}\/title$/.test(path);
|
|
// Computes an install plan without saving it, so read-only modes may call it.
|
|
const readOnlyPreview = method === "POST" && path === "/api/companies/{companyId}/teams/catalog/{catalogId}/preview";
|
|
const skillReference = runnerApiReference[`${method} ${path.replace(/\{[^}]+\}/g, "{}")}`];
|
|
const protocol = operation["x-paperclip-transport"] === "protocol" || (operation["x-paperclip-transport"] !== "rest" && (!path.startsWith("/api/") || /\/(oauth|auth|runtime-tools|mcp|ws)(\/|$)/.test(path)
|
|
|| /\/(claude-login|login-sessions|start-authorization|finalize-oauth-access)(\/|$)/.test(path)
|
|
|| /event-stream|websocket/i.test(JSON.stringify(operation.responses))));
|
|
result.push({
|
|
operationId: `${method} ${path}`, method, path,
|
|
summary: operation.summary ?? `${method} ${path}`,
|
|
description: operation.description ?? "",
|
|
parameters: dereference([...(item.parameters ?? []), ...(operation.parameters ?? [])]),
|
|
...(operation.requestBody ? { requestBody: dereference(operation.requestBody) } : {}),
|
|
responses: dereference(operation.responses ?? {}),
|
|
authorization: operation["x-paperclip-authorization"] ?? { actor: "board_or_agent" },
|
|
transport: protocol ? "protocol" : "rest",
|
|
callPolicy: protocol ? "protocol" : "rest",
|
|
dedicatedTools: dedicatedTools(method, path),
|
|
dedicatedToolCapabilities: dedicatedTools(method, path).flatMap(name => {
|
|
const descriptor = CAPABILITY_SEMANTIC_TOOL_CATALOG.find(tool => tool.operationId === name);
|
|
return descriptor ? [{ name, description: descriptor.description, supportedParameters: Object.keys((descriptor.inputSchema as Json).properties ?? {}) }] : [];
|
|
}),
|
|
runnerRestrictions: ["Active run and assignment must remain authorized.",
|
|
conversationalConfirmation
|
|
? "This records an ordinary conversational confirmation under existing resolver permissions. It cannot decide governed approvals or impersonate the user."
|
|
: "The HTTP route enforces the same endpoint, payload, company, resource and approval permissions as agent REST access."],
|
|
dedicatedToolGuidance: dedicatedTools(method, path).includes("hire_agent")
|
|
? "Prefer hire_agent for native teammate identity and persona fields. It fixes the reportsTo and source task context and inherits the caller's native runtime. Additional API fields use the route's existing agent permissions."
|
|
: "Prefer an available dedicated tool for its supported fields. call_api supports the route's other operations and fields under the same agent permissions.",
|
|
allowedModes: operation["x-paperclip-connection-management"] ? (method === "GET" ? ["standard", "ask", "planning"] : ["standard"]) : method !== "GET" && (path.endsWith("/case-handoffs") || /\/handoffs\//.test(path)) ? ["standard"]
|
|
: method === "GET" || method === "HEAD" || taskTitleUpdate || readOnlyPreview ? ["standard", "ask", "planning", "skill_test"]
|
|
: conversationalConfirmation ? ["standard", "planning", "skill_test"] : ["standard", "skill_test"],
|
|
...(skillReference ? { skillReference } : {}),
|
|
});
|
|
}
|
|
}
|
|
for (const [path, summary, actor] of [
|
|
["/api/companies/{companyId}/events/ws", "Live company events WebSocket; use the existing event client", "board_or_agent"],
|
|
["/api/runner/v1/connect/{runId}", "Authenticated runner PRP WebSocket; runner-owned transport", "runner"],
|
|
["/api/environment-custom-image-setup-sessions/{sessionId}/terminal/ws", "Image setup terminal WebSocket; use the existing terminal client", "board"],
|
|
]) {
|
|
if (result.some(operation => operation.path === path)) continue;
|
|
result.push({ operationId: `GET ${path}`, method: "GET", path, summary,
|
|
description: "WebSocket upgrade. Not callable through call_api.",
|
|
parameters: [...path.matchAll(/\{([^}]+)\}/g)].map(match => ({ in: "path", name: match[1], required: true, schema: { type: "string" } })),
|
|
responses: { "101": { description: "Switching Protocols" } }, authorization: { actor },
|
|
transport: "protocol", callPolicy: "protocol", dedicatedTools: [], dedicatedToolGuidance: "Use the existing protocol client.", allowedModes: [],
|
|
});
|
|
}
|
|
return result.sort((a, b) => a.operationId.localeCompare(b.operationId));
|
|
}
|
|
|
|
let cached: RunnerApiOperation[] | undefined;
|
|
let cachedDigest: string | undefined;
|
|
export function runnerApiCatalog(): RunnerApiOperation[] { return cached ??= buildRunnerApiCatalog(); }
|
|
export function runnerApiOperation(id: string): RunnerApiOperation {
|
|
const operation = runnerApiCatalog().find((entry) => entry.operationId === id);
|
|
if (!operation) throw notFound("Unknown API operation; use search_api to discover its exact operationId");
|
|
return operation;
|
|
}
|
|
|
|
/**
|
|
* Catalog text names company pages as /<prefix>/...; a model can copy that
|
|
* placeholder verbatim into a link. When the caller's company prefix is known,
|
|
* hand back real paths. Returns a copy; the shared catalog is never mutated.
|
|
*/
|
|
export function withCompanyPagePaths<T>(value: T, prefix: string | null | undefined): T {
|
|
if (!prefix || !/^[A-Za-z0-9]+$/.test(prefix)) return value;
|
|
return JSON.parse(JSON.stringify(value).replaceAll("/<prefix>/", `/${prefix}/`)) as T;
|
|
}
|
|
|
|
export const runnerApiSearchSchema = z.object({ query: z.string().trim().min(1).max(500), limit: z.number().int().min(1).max(10).default(5), cursor: z.string().max(200).optional() }).strict();
|
|
export function searchRunnerApi(value: unknown) {
|
|
const parsed = runnerApiSearchSchema.safeParse(value);
|
|
if (!parsed.success) throw badRequest("Invalid API search query or limit");
|
|
const input = parsed.data;
|
|
const { query, limit } = input;
|
|
const catalog = runnerApiCatalog();
|
|
cachedDigest ??= createHash("sha256").update(JSON.stringify(catalog)).digest("hex");
|
|
const fingerprint = createHash("sha256").update(cachedDigest).update(query).digest("hex").slice(0, 16);
|
|
let offset = 0;
|
|
if (input.cursor) {
|
|
const match = /^([a-f0-9]{16}):(\d+)$/.exec(input.cursor);
|
|
if (!match || match[1] !== fingerprint) throw badRequest("Search cursor belongs to a different query or catalog");
|
|
offset = Number(match[2]);
|
|
if (!Number.isSafeInteger(offset)) throw badRequest("Invalid search cursor");
|
|
}
|
|
const exact = catalog.find((entry) => entry.operationId.toLowerCase() === query.trim().toLowerCase());
|
|
const terms = [...new Set(words(query))];
|
|
const matches = exact ? [exact] : catalog.map((entry) => {
|
|
const title = new Set(words(`${entry.method} ${entry.path} ${entry.summary}`));
|
|
const description = new Set(words(`${entry.description} ${entry.skillReference?.description ?? ""} ${entry.skillReference?.section ?? ""}`));
|
|
return { entry, score: terms.reduce((sum, word) => sum + (title.has(word) ? 5 : description.has(word) ? 1 : 0), 0) };
|
|
}).filter(({ score }) => score > 0).sort((a, b) => b.score - a.score || a.entry.operationId.localeCompare(b.entry.operationId)).map(({ entry }) => entry);
|
|
const results = matches.slice(offset, offset + limit);
|
|
return {
|
|
results, total: matches.length,
|
|
nextCursor: offset + limit < matches.length ? `${fingerprint}:${offset + limit}` : null,
|
|
guidance: "Prefer an available dedicated tool when it supports the required operation and parameters. API permissions still apply. Protocol endpoints require their existing clients. Ask and Plan permit reads and active-task title updates; Plan also permits conversational confirmation recording. Check each operation's allowedModes.",
|
|
};
|
|
}
|