216 lines · 13.1 KBRaw
| 1 | import type { SecretScope } from "@refs/ci"; |
| 2 | import { now } from "./auth.ts"; |
| 3 | import type { HostedAgents } from "./contract/handles.ts"; |
| 4 | import type { HostedAgent, ModelProvider } from "./contract/views.ts"; |
| 5 | import { isProvider, sealer, testModel, type ModelChoice } from "./models.ts"; |
| 6 | import { invalid, ok, problem } from "./outcomes.ts"; |
| 7 | import type { Policy } from "./policy.ts"; |
| 8 | |
| 9 | const REVIEWER_INSTRUCTIONS = `Review the change in this pull request. |
| 10 | |
| 11 | - Find real problems: bugs, security holes, broken callers, lost data, missing error handling at trust boundaries, race conditions. |
| 12 | - Read the code around each change. Use the code map tools to see who calls a changed symbol and whether the change breaks them. |
| 13 | - If the person asked a specific question, answer it first. |
| 14 | - Give each finding as one list item: \`path:line\`, what breaks, and the fix, in one or two lines. |
| 15 | - Put the most severe finding first. Report only what you checked. Leave out style and naming unless asked. |
| 16 | - If you find no real problem, say so in one sentence.`; |
| 17 | |
| 18 | const SECURITY_INSTRUCTIONS = `Look for security holes in the change in this pull request. |
| 19 | |
| 20 | - Check each trust boundary that the change touches: requests, form input, webhooks, queue messages, tokens, files and model output. |
| 21 | - Look for missing authentication or permission checks, injection (SQL, HTML, shell, path), secrets in code or logs, unsafe redirects, and data that one user can read or change for another. |
| 22 | - Follow tainted input with the code map tools to the place where it is used. |
| 23 | - If the person asked a specific question, answer it first. |
| 24 | - Give each finding as one list item: \`path:line\`, how an attacker uses it, and the fix, in one or two lines. |
| 25 | - Put the most severe finding first. Report only holes that you can show in the code, not general advice. |
| 26 | - If you find no hole, say so in one sentence.`; |
| 27 | |
| 28 | const TESTS_INSTRUCTIONS = `Check the tests of the change in this pull request. |
| 29 | |
| 30 | - Find changed behavior that no test covers: new branches, error paths, edge cases and changed callers. |
| 31 | - Find tests that pass for the wrong reason: weak assertions, mocks that hide the change, or tests that do not run the changed code. |
| 32 | - Read the existing tests first, and name the test file where each new test belongs. |
| 33 | - If the person asked a specific question, answer it first. |
| 34 | - Give each finding as one list item: \`path:line\` of the code, the case that is not tested, and the test to add, in one or two lines. |
| 35 | - Put the most risky gap first. Leave out tests for trivial code. |
| 36 | - If the tests cover the change well, say so in one sentence.`; |
| 37 | |
| 38 | const PERF_INSTRUCTIONS = `Look for performance problems in the change in this pull request. |
| 39 | |
| 40 | - Find work that grows with the data: queries in a loop, a missing index, full scans, quadratic loops, and unbounded lists or reads. |
| 41 | - Find extra round trips: sequential awaits that can run together, requests that one batch can replace, and repeated work that a cache or a stored value removes. |
| 42 | - Use the code map tools to see how often a changed function is called and on which path. |
| 43 | - If the person asked a specific question, answer it first. |
| 44 | - Give each finding as one list item: \`path:line\`, the cost and when it hurts, and the fix, in one or two lines. |
| 45 | - Put the largest cost first. Leave out micro-optimizations. |
| 46 | - If you find no real problem, say so in one sentence.`; |
| 47 | |
| 48 | const EXPLAIN_INSTRUCTIONS = `Explain the change in this pull request, or answer the question about the code. |
| 49 | |
| 50 | - If the person asked a question, answer it directly, first. |
| 51 | - Otherwise say what the change does and why, in plain words, for a reader who did not write it. |
| 52 | - Use the code map tools to show where the changed code is used and what else it affects. |
| 53 | - Point to the two or three places that a reviewer must read first, as \`path:line\`. |
| 54 | - Do not judge the change, and do not list problems unless the person asks.`; |
| 55 | |
| 56 | const DOCS_INSTRUCTIONS = `Check that the docs match the change in this pull request. |
| 57 | |
| 58 | - Find the docs, README files, comments on public APIs, and help text that describe the changed behavior. |
| 59 | - Find docs that the change makes wrong, and new behavior that a person or an agent can use but no doc describes. |
| 60 | - Check that the labels, commands and option names in the docs match the code. |
| 61 | - If the person asked a specific question, answer it first. |
| 62 | - Give each finding as one list item: the doc \`path:line\`, what is wrong or missing, and the text to change, in one or two lines. |
| 63 | - If the docs match the change, say so in one sentence.`; |
| 64 | |
| 65 | export const BUILTIN_AGENTS: readonly { readonly handle: string; readonly description: string; readonly instructions: string }[] = [ |
| 66 | { handle: "reviewer", description: "Reviews the pull request and lists real problems, the most severe first.", instructions: REVIEWER_INSTRUCTIONS }, |
| 67 | { handle: "security", description: "Looks for security holes: missing checks, injection, leaked secrets.", instructions: SECURITY_INSTRUCTIONS }, |
| 68 | { handle: "tests", description: "Finds changed behavior that no test covers, and weak tests.", instructions: TESTS_INSTRUCTIONS }, |
| 69 | { handle: "perf", description: "Finds slow paths: queries in loops, extra round trips, unbounded work.", instructions: PERF_INSTRUCTIONS }, |
| 70 | { handle: "explain", description: "Explains what the change does, or answers a question about the code.", instructions: EXPLAIN_INSTRUCTIONS }, |
| 71 | { handle: "docs", description: "Finds docs that the change makes wrong or leaves out.", instructions: DOCS_INSTRUCTIONS }, |
| 72 | ]; |
| 73 | |
| 74 | const HANDLE = /^[a-z][a-z0-9-]{1,31}$/; |
| 75 | const RESERVED = new Set(["agent", "all", "everyone", "here", "refs"]); |
| 76 | const MENTION = /(^|[^\w@/.-])@([a-z][a-z0-9-]{1,31})(?![\w/-])/g; |
| 77 | const MAX_DESCRIPTION = 200; |
| 78 | const MAX_INSTRUCTIONS = 8000; |
| 79 | |
| 80 | /** The handles `@name` that `text` mentions outside code. A mention inside a code block or inline code is an example, not a request. */ |
| 81 | export function mentionedHandles(text: string): string[] { |
| 82 | const prose = text.replace(/```[\s\S]*?```/g, "").replace(/`[^`\n]*`/g, ""); |
| 83 | return [...new Set([...prose.matchAll(MENTION)].map((match) => match[2]).filter((handle) => !RESERVED.has(handle)))]; |
| 84 | } |
| 85 | |
| 86 | interface Row { |
| 87 | id: string; |
| 88 | repo_id: string | null; |
| 89 | handle: string; |
| 90 | description: string; |
| 91 | instructions: string; |
| 92 | provider: ModelProvider | null; |
| 93 | model: string | null; |
| 94 | ciphertext: string | null; |
| 95 | wrapped_key: string | null; |
| 96 | key_hint: string | null; |
| 97 | updated_at: number; |
| 98 | } |
| 99 | |
| 100 | const agentId = (namespaceId: string, repoId: string | null, handle: string) => `${namespaceId}:${repoId ?? "*"}:${handle}`; |
| 101 | const keyScope = (id: string): SecretScope => ({ owner: `agent:${id}`, environment: null, name: "model-key" }); |
| 102 | |
| 103 | async function rows(db: D1Database, namespaceId: string, repoId: string | null): Promise<Row[]> { |
| 104 | const { results } = await db |
| 105 | .prepare("SELECT * FROM hosted_agents WHERE namespace_id = ? AND (repo_id IS NULL OR repo_id = ?) ORDER BY handle") |
| 106 | .bind(namespaceId, repoId) |
| 107 | .all<Row>(); |
| 108 | return results; |
| 109 | } |
| 110 | |
| 111 | /** Every agent at a namespace or repository: the repository's own first, then the namespace's, then the built-in ones. */ |
| 112 | export async function listAgents(db: D1Database, namespaceId: string, repoId: string | null): Promise<HostedAgent[]> { |
| 113 | const found = await rows(db, namespaceId, repoId); |
| 114 | const own = found.filter((row) => row.repo_id !== null); |
| 115 | const shared = found.filter((row) => row.repo_id === null); |
| 116 | const taken = (handles: readonly Row[], handle: string) => handles.some((row) => row.handle === handle); |
| 117 | const view = (row: Row, scope: "namespace" | "repo", replaced: boolean): HostedAgent => ({ |
| 118 | handle: row.handle, |
| 119 | scope, |
| 120 | description: row.description, |
| 121 | instructions: row.instructions, |
| 122 | model: row.provider && row.model ? { provider: row.provider, model: row.model, keyHint: row.key_hint ?? "" } : null, |
| 123 | updatedAt: row.updated_at, |
| 124 | replaced, |
| 125 | }); |
| 126 | return [ |
| 127 | ...own.map((row) => view(row, "repo", false)), |
| 128 | ...shared.map((row) => view(row, "namespace", taken(own, row.handle))), |
| 129 | ...BUILTIN_AGENTS.map((agent): HostedAgent => ({ ...agent, scope: "builtin", model: null, updatedAt: null, replaced: taken(own, agent.handle) || taken(shared, agent.handle) })), |
| 130 | ]; |
| 131 | } |
| 132 | |
| 133 | export interface ResolvedAgent { |
| 134 | readonly handle: string; |
| 135 | readonly instructions: string; |
| 136 | readonly choice: ModelChoice | null; |
| 137 | } |
| 138 | |
| 139 | /** The agent that `@handle` means in a repository, with its key opened, or null when there is none. */ |
| 140 | export async function resolveAgent(env: Env, namespaceId: string, repoId: string, handle: string): Promise<ResolvedAgent | null> { |
| 141 | const row = await env.DB.prepare("SELECT * FROM hosted_agents WHERE namespace_id = ? AND handle = ? AND (repo_id IS NULL OR repo_id = ?) ORDER BY repo_id IS NULL LIMIT 1") |
| 142 | .bind(namespaceId, handle, repoId) |
| 143 | .first<Row>(); |
| 144 | if (!row) { |
| 145 | const builtin = BUILTIN_AGENTS.find((agent) => agent.handle === handle); |
| 146 | return builtin ? { handle, instructions: builtin.instructions, choice: null } : null; |
| 147 | } |
| 148 | return { handle, instructions: row.instructions, choice: await openChoice(env, row) }; |
| 149 | } |
| 150 | |
| 151 | async function openChoice(env: Env, row: Row): Promise<ModelChoice | null> { |
| 152 | if (!row.provider || !row.model || !row.ciphertext || !row.wrapped_key) return null; |
| 153 | const box = await sealer(env); |
| 154 | if (!box) throw new Error("Model keys are not set up on this server. Ask the operator to set CI_SECRETS_KEY."); |
| 155 | const key = await box.open({ ciphertext: row.ciphertext, wrappedKey: row.wrapped_key }, keyScope(row.id)).catch(() => { |
| 156 | throw new Error(`The key of @${row.handle} could not be opened. An admin must save it again on the Agents page.`); |
| 157 | }); |
| 158 | return { provider: row.provider, model: row.model, key }; |
| 159 | } |
| 160 | |
| 161 | /** The agents of a namespace (`repoId` null) or of one repository. Only a person with `canEdit` changes them, never an agent. */ |
| 162 | export function openHostedAgents(env: Env, policy: Policy, namespaceId: string, repoId: string | null, canEdit: boolean): HostedAgents { |
| 163 | const db = env.DB; |
| 164 | const editable = canEdit && policy.actor.kind === "human"; |
| 165 | const deny = () => problem("invalid", "Only admins can change agents."); |
| 166 | return { |
| 167 | canEdit: editable, |
| 168 | |
| 169 | list: () => listAgents(db, namespaceId, repoId), |
| 170 | |
| 171 | async save(input) { |
| 172 | if (!editable) return deny(); |
| 173 | const handle = input.handle.trim().replace(/^@/, "").toLowerCase(); |
| 174 | if (!HANDLE.test(handle)) return invalid("A handle is 2–32 characters: lowercase letters, digits and -, starting with a letter.", "handle"); |
| 175 | if (RESERVED.has(handle)) return invalid(`@${handle} is reserved. Choose another handle.`, "handle"); |
| 176 | const description = input.description.trim(); |
| 177 | if (description.length > MAX_DESCRIPTION) return invalid(`A description is at most ${MAX_DESCRIPTION} characters.`, "description"); |
| 178 | const instructions = input.instructions.trim(); |
| 179 | if (!instructions || instructions.length > MAX_INSTRUCTIONS) return invalid(`Instructions are 1–${MAX_INSTRUCTIONS} characters.`, "instructions"); |
| 180 | const id = agentId(namespaceId, repoId, handle); |
| 181 | let model: { provider: ModelProvider; model: string; key: string } | null = null; |
| 182 | if (input.provider) { |
| 183 | if (!isProvider(input.provider)) return invalid("Choose a provider from the list.", "provider"); |
| 184 | const name = input.model.trim(); |
| 185 | if (!/^[\w.:/@-]{1,200}$/.test(name)) return invalid("Enter the model ID that the provider uses, for example claude-sonnet-5-5.", "model"); |
| 186 | let key = input.key.trim(); |
| 187 | if (!key) { |
| 188 | const saved = await db.prepare("SELECT * FROM hosted_agents WHERE id = ? AND provider = ?").bind(id, input.provider).first<Row>(); |
| 189 | if (!saved) return invalid("Paste the API key.", "key"); |
| 190 | key = (await openChoice(env, saved))!.key; |
| 191 | } |
| 192 | if (!/^\S{8,500}$/.test(key)) return invalid("Paste the whole API key.", "key"); |
| 193 | model = { provider: input.provider, model: name, key }; |
| 194 | const failed = await testModel(env, model); |
| 195 | if (failed) return invalid(failed, "key"); |
| 196 | } |
| 197 | const box = model && (await sealer(env)); |
| 198 | if (model && !box) return problem("unavailable", "Model keys are not set up on this server yet. Ask the operator to set CI_SECRETS_KEY."); |
| 199 | const sealed = model && box ? await box.seal(model.key, keyScope(id)) : null; |
| 200 | await db |
| 201 | .prepare( |
| 202 | `INSERT INTO hosted_agents (id, namespace_id, repo_id, handle, description, instructions, provider, model, ciphertext, wrapped_key, key_hint, updated_by, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| 203 | ON CONFLICT (id) DO UPDATE SET description = excluded.description, instructions = excluded.instructions, provider = excluded.provider, model = excluded.model, ciphertext = excluded.ciphertext, wrapped_key = excluded.wrapped_key, key_hint = excluded.key_hint, updated_by = excluded.updated_by, updated_at = excluded.updated_at`, |
| 204 | ) |
| 205 | .bind(id, namespaceId, repoId, handle, description, instructions, model?.provider ?? null, model?.model ?? null, sealed?.ciphertext ?? null, sealed?.wrappedKey ?? null, model ? model.key.slice(-4) : null, policy.person!.id, now()) |
| 206 | .run(); |
| 207 | return ok(); |
| 208 | }, |
| 209 | |
| 210 | async remove(handle) { |
| 211 | if (!editable) return deny(); |
| 212 | await db.prepare("DELETE FROM hosted_agents WHERE id = ?").bind(agentId(namespaceId, repoId, handle)).run(); |
| 213 | return ok(); |
| 214 | }, |
| 215 | }; |
| 216 | } |