mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 19:08:33 +01:00
## Thinking Path > - Paperclip manages AI agents and their work. > - The new runner gives agents dedicated tools for common tasks. > - Some API operations and parameters have no dedicated tool. > - Agents need a controlled way to find and use those operations. > - This pull request adds API search and calls through the real server routes. > - Existing tools remain the preferred path. The new tools are disabled by default. > - Paired tests measure correctness, tool choice, cost and time. ## Linked Issues or Issue Description **Subsystem affected** Paperclip Runner contracts, production tool authority and the server API catalog. **Problem or motivation** The runner cannot use much of the API described by the old Paperclip skill. A generic HTTP client would also let agents bypass runner control rules. **Proposed solution** Add `search_api` and `call_api`. Resolve calls from the mounted API catalog. Use server-held, run-bound credentials. Preserve route checks and runner lifecycle rules. Keep the tools disabled until an operator enables selected companies. **Alternatives considered** A dedicated tool for every endpoint would add a large initial prompt. An unrestricted HTTP tool would weaken authorization and replay controls. **Roadmap alignment** This extends the native runner tooling. The repository owner requested this design and implementation. The roadmap and related open PRs were checked. No duplicate API escape-hatch PR was found. ## What Changed - Register two compact fallback tools in canonical contracts and provider projections. - Build deterministic API discovery from OpenAPI, mounted experimental routes and the old skill reference. - Execute bounded JSON, text, file and download requests through authenticated HTTP routes. - Recheck active runs, company access and work modes. Block runner lifecycle, scheduling, credential and approval bypasses. Keep routine annotation collaboration available. - Retain mutation receipts. Report uncertain outcomes without blindly repeating writes. - Add a company rollout gate and a durable eval worker with complete cost accounting checks. - Record child-task creation in the activity log with the agent and run. - Add contract, authorization, file, replay and real runnerd/PRP/HTTP tests. - Document rollout gates and paid coverage limits. The companion eval repository retains immutable attempts and reports. ## Verification - Final app commit `da58370524c3626a744eec20164397c5fb6ba9ef`: all 32 checks passed; the unrelated Storybook visual check was skipped. Greptile 5/5; no unresolved review threads. - Full Linux build and recursive typecheck passed. Repository tests were run by project and serialized shard; all 143 serialized server suites passed. - Runner TypeScript: 1,599 passed, two skipped. Rust release: 451 passing test reports. Conformance and replay parity passed. The required API check passed 837 tests, including runnerd → PRP → authority → real HTTP. - Bindings cannot enable API tools without the explicit deployment flag. Unit and real-authority tests prove the default-off boundary. - The standalone API check builds and stages its own binary. It passed after existing staged and debug binaries were removed from the test container. - UI and CLI tests passed. Initial environment failures (missing jq, Docker overlay file identity, and parallel linker memory pressure) and focused passing reruns are retained. The macOS full runner suite has platform-specific failures; Linux is the qualified full-check platform. - Eval harness: 27 tests passed; existing CI discovery ran 86 tests with two unrelated skips. Credential export rejection is tested against the actual report command. - Luna and OpenRouter Sonnet each passed 60 common-workflow runs: ten workflows, three repetitions per arm, zero unnecessary API fallback. - Sonnet passed 11 selected capability/contract cases after fixes. Gemini passed three smoke cases. DeepSeek exceeded the 120-second limit and remains unqualified. - Luna's two cost flags received focused follow-up. The original flags and a later n=1 latency flag remain visible. Sonnet had no cost or latency increase above 20%. - The catalog contains 785 entries; 58 were exercised across all stages. Most operation probes remain unrun and some need additional fixtures. Authored probes do not establish successful coverage. - Total conservative accounted cost: $9.875960. Active paid-campaign time: 88.16/90 minutes. No missing accounting. Later security and harness fixes have provider-free verification; no paid validation is claimed for those revisions. - Inspect the [qualification report](https://github.com/paperclipai/paperclip-evals/blob/codex/seach-call-api-tools/evals/runner-api-tools/reports/2026-09-07-production/READINESS.md) and [verification record](https://github.com/paperclipai/paperclip-evals/blob/codex/seach-call-api-tools/evals/runner-api-tools/reports/2026-09-07-production/verification.json). ## Risks - This is a broad authenticated API surface. Keep the default-off gate until an operator selects initial rollout companies. - Paid coverage is incomplete. Small regression samples do not prove all workflows are unchanged. - A timeout or server failure can follow a committed mutation. The result reports an unknown outcome and requires state inspection. - The new definitions add prompt tokens. The report retains cost flags and cache variation. - No database migration is required. - Repository rules require code-owner approval before merge. Technical CI and automated review are complete. ## Model Used OpenAI Codex based on GPT-6 assisted with code, tests and review. The exact serving model ID and context window are not exposed in this session. It used reasoning, tool calls and code execution. Eval models: `gpt-5.6-luna` with low reasoning, `openrouter/anthropic/claude-sonnet-5`, `openrouter/google/gemini-3.8-flash`, and `openrouter/deepseek/deepseek-v4-flash-0731`. Attempts retain runtime versions, model identity, usage and source provenance. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
157 lines
9.9 KiB
TypeScript
157 lines
9.9 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 { runnerApiRestriction } from "./runner-api-policy.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" | "restricted" | "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(text: string): string[] {
|
|
return text.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
|
|
.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 (/\/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 (/\/issues$/.test(path)) return method === "GET" ? ["search_tasks"] : ["create_task"];
|
|
if (/\/issues\/\{[^}]+\}$/.test(path)) return method === "GET" ? ["get_task_context"] : ["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 restriction = runnerApiRestriction(method, path);
|
|
const skillReference = runnerApiReference[`${method} ${path.replace(/\{[^}]+\}/g, "{}")}`];
|
|
const protocol = !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" : restriction ? "restricted" : "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: [...(restriction ? [restriction] : []), "Active run and assignment must remain authorized.", "Cannot replace checkout, completion, task status/ownership changes, approval decisions, or runner execution control. Dedicated tools retain their existing permissions."],
|
|
dedicatedToolGuidance: "Use an available dedicated tool for its supported fields. Inspect that tool's advertised schema; call_api may be used for additional API fields, subject to lifecycle restrictions.",
|
|
allowedModes: method === "GET" || method === "HEAD" ? ["standard", "ask", "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;
|
|
}
|
|
|
|
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 only reads through call_api.",
|
|
};
|
|
}
|