import type { SecretScope } from "@refs/ci"; import { now } from "./auth.ts"; import type { HostedAgents } from "./contract/handles.ts"; import type { HostedAgent, ModelProvider } from "./contract/views.ts"; import { isProvider, sealer, testModel, type ModelChoice } from "./models.ts"; import { invalid, ok, problem } from "./outcomes.ts"; import type { Policy } from "./policy.ts"; const REVIEWER_INSTRUCTIONS = `Review the change in this pull request. - Find real problems: bugs, security holes, broken callers, lost data, missing error handling at trust boundaries, race conditions. - Read the code around each change. Use the code map tools to see who calls a changed symbol and whether the change breaks them. - If the person asked a specific question, answer it first. - Give each finding as one list item: \`path:line\`, what breaks, and the fix, in one or two lines. - Put the most severe finding first. Report only what you checked. Leave out style and naming unless asked. - If you find no real problem, say so in one sentence.`; const SECURITY_INSTRUCTIONS = `Look for security holes in the change in this pull request. - Check each trust boundary that the change touches: requests, form input, webhooks, queue messages, tokens, files and model output. - 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. - Follow tainted input with the code map tools to the place where it is used. - If the person asked a specific question, answer it first. - Give each finding as one list item: \`path:line\`, how an attacker uses it, and the fix, in one or two lines. - Put the most severe finding first. Report only holes that you can show in the code, not general advice. - If you find no hole, say so in one sentence.`; const TESTS_INSTRUCTIONS = `Check the tests of the change in this pull request. - Find changed behavior that no test covers: new branches, error paths, edge cases and changed callers. - Find tests that pass for the wrong reason: weak assertions, mocks that hide the change, or tests that do not run the changed code. - Read the existing tests first, and name the test file where each new test belongs. - If the person asked a specific question, answer it first. - 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. - Put the most risky gap first. Leave out tests for trivial code. - If the tests cover the change well, say so in one sentence.`; const PERF_INSTRUCTIONS = `Look for performance problems in the change in this pull request. - Find work that grows with the data: queries in a loop, a missing index, full scans, quadratic loops, and unbounded lists or reads. - 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. - Use the code map tools to see how often a changed function is called and on which path. - If the person asked a specific question, answer it first. - Give each finding as one list item: \`path:line\`, the cost and when it hurts, and the fix, in one or two lines. - Put the largest cost first. Leave out micro-optimizations. - If you find no real problem, say so in one sentence.`; const EXPLAIN_INSTRUCTIONS = `Explain the change in this pull request, or answer the question about the code. - If the person asked a question, answer it directly, first. - Otherwise say what the change does and why, in plain words, for a reader who did not write it. - Use the code map tools to show where the changed code is used and what else it affects. - Point to the two or three places that a reviewer must read first, as \`path:line\`. - Do not judge the change, and do not list problems unless the person asks.`; const DOCS_INSTRUCTIONS = `Check that the docs match the change in this pull request. - Find the docs, README files, comments on public APIs, and help text that describe the changed behavior. - Find docs that the change makes wrong, and new behavior that a person or an agent can use but no doc describes. - Check that the labels, commands and option names in the docs match the code. - If the person asked a specific question, answer it first. - 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. - If the docs match the change, say so in one sentence.`; export const BUILTIN_AGENTS: readonly { readonly handle: string; readonly description: string; readonly instructions: string }[] = [ { handle: "reviewer", description: "Reviews the pull request and lists real problems, the most severe first.", instructions: REVIEWER_INSTRUCTIONS }, { handle: "security", description: "Looks for security holes: missing checks, injection, leaked secrets.", instructions: SECURITY_INSTRUCTIONS }, { handle: "tests", description: "Finds changed behavior that no test covers, and weak tests.", instructions: TESTS_INSTRUCTIONS }, { handle: "perf", description: "Finds slow paths: queries in loops, extra round trips, unbounded work.", instructions: PERF_INSTRUCTIONS }, { handle: "explain", description: "Explains what the change does, or answers a question about the code.", instructions: EXPLAIN_INSTRUCTIONS }, { handle: "docs", description: "Finds docs that the change makes wrong or leaves out.", instructions: DOCS_INSTRUCTIONS }, ]; const HANDLE = /^[a-z][a-z0-9-]{1,31}$/; const RESERVED = new Set(["agent", "all", "everyone", "here", "refs"]); const MENTION = /(^|[^\w@/.-])@([a-z][a-z0-9-]{1,31})(?![\w/-])/g; const MAX_DESCRIPTION = 200; const MAX_INSTRUCTIONS = 8000; /** The handles `@name` that `text` mentions outside code. A mention inside a code block or inline code is an example, not a request. */ export function mentionedHandles(text: string): string[] { const prose = text.replace(/```[\s\S]*?```/g, "").replace(/`[^`\n]*`/g, ""); return [...new Set([...prose.matchAll(MENTION)].map((match) => match[2]).filter((handle) => !RESERVED.has(handle)))]; } interface Row { id: string; repo_id: string | null; handle: string; description: string; instructions: string; provider: ModelProvider | null; model: string | null; ciphertext: string | null; wrapped_key: string | null; key_hint: string | null; updated_at: number; } const agentId = (namespaceId: string, repoId: string | null, handle: string) => `${namespaceId}:${repoId ?? "*"}:${handle}`; const keyScope = (id: string): SecretScope => ({ owner: `agent:${id}`, environment: null, name: "model-key" }); async function rows(db: D1Database, namespaceId: string, repoId: string | null): Promise { const { results } = await db .prepare("SELECT * FROM hosted_agents WHERE namespace_id = ? AND (repo_id IS NULL OR repo_id = ?) ORDER BY handle") .bind(namespaceId, repoId) .all(); return results; } /** Every agent at a namespace or repository: the repository's own first, then the namespace's, then the built-in ones. */ export async function listAgents(db: D1Database, namespaceId: string, repoId: string | null): Promise { const found = await rows(db, namespaceId, repoId); const own = found.filter((row) => row.repo_id !== null); const shared = found.filter((row) => row.repo_id === null); const taken = (handles: readonly Row[], handle: string) => handles.some((row) => row.handle === handle); const view = (row: Row, scope: "namespace" | "repo", replaced: boolean): HostedAgent => ({ handle: row.handle, scope, description: row.description, instructions: row.instructions, model: row.provider && row.model ? { provider: row.provider, model: row.model, keyHint: row.key_hint ?? "" } : null, updatedAt: row.updated_at, replaced, }); return [ ...own.map((row) => view(row, "repo", false)), ...shared.map((row) => view(row, "namespace", taken(own, row.handle))), ...BUILTIN_AGENTS.map((agent): HostedAgent => ({ ...agent, scope: "builtin", model: null, updatedAt: null, replaced: taken(own, agent.handle) || taken(shared, agent.handle) })), ]; } export interface ResolvedAgent { readonly handle: string; readonly instructions: string; readonly choice: ModelChoice | null; } /** The agent that `@handle` means in a repository, with its key opened, or null when there is none. */ export async function resolveAgent(env: Env, namespaceId: string, repoId: string, handle: string): Promise { 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") .bind(namespaceId, handle, repoId) .first(); if (!row) { const builtin = BUILTIN_AGENTS.find((agent) => agent.handle === handle); return builtin ? { handle, instructions: builtin.instructions, choice: null } : null; } return { handle, instructions: row.instructions, choice: await openChoice(env, row) }; } async function openChoice(env: Env, row: Row): Promise { if (!row.provider || !row.model || !row.ciphertext || !row.wrapped_key) return null; const box = await sealer(env); if (!box) throw new Error("Model keys are not set up on this server. Ask the operator to set CI_SECRETS_KEY."); const key = await box.open({ ciphertext: row.ciphertext, wrappedKey: row.wrapped_key }, keyScope(row.id)).catch(() => { throw new Error(`The key of @${row.handle} could not be opened. An admin must save it again on the Agents page.`); }); return { provider: row.provider, model: row.model, key }; } /** The agents of a namespace (`repoId` null) or of one repository. Only a person with `canEdit` changes them, never an agent. */ export function openHostedAgents(env: Env, policy: Policy, namespaceId: string, repoId: string | null, canEdit: boolean): HostedAgents { const db = env.DB; const editable = canEdit && policy.actor.kind === "human"; const deny = () => problem("invalid", "Only admins can change agents."); return { canEdit: editable, list: () => listAgents(db, namespaceId, repoId), async save(input) { if (!editable) return deny(); const handle = input.handle.trim().replace(/^@/, "").toLowerCase(); if (!HANDLE.test(handle)) return invalid("A handle is 2–32 characters: lowercase letters, digits and -, starting with a letter.", "handle"); if (RESERVED.has(handle)) return invalid(`@${handle} is reserved. Choose another handle.`, "handle"); const description = input.description.trim(); if (description.length > MAX_DESCRIPTION) return invalid(`A description is at most ${MAX_DESCRIPTION} characters.`, "description"); const instructions = input.instructions.trim(); if (!instructions || instructions.length > MAX_INSTRUCTIONS) return invalid(`Instructions are 1–${MAX_INSTRUCTIONS} characters.`, "instructions"); const id = agentId(namespaceId, repoId, handle); let model: { provider: ModelProvider; model: string; key: string } | null = null; if (input.provider) { if (!isProvider(input.provider)) return invalid("Choose a provider from the list.", "provider"); const name = input.model.trim(); if (!/^[\w.:/@-]{1,200}$/.test(name)) return invalid("Enter the model ID that the provider uses, for example claude-sonnet-5-5.", "model"); let key = input.key.trim(); if (!key) { const saved = await db.prepare("SELECT * FROM hosted_agents WHERE id = ? AND provider = ?").bind(id, input.provider).first(); if (!saved) return invalid("Paste the API key.", "key"); key = (await openChoice(env, saved))!.key; } if (!/^\S{8,500}$/.test(key)) return invalid("Paste the whole API key.", "key"); model = { provider: input.provider, model: name, key }; const failed = await testModel(env, model); if (failed) return invalid(failed, "key"); } const box = model && (await sealer(env)); if (model && !box) return problem("unavailable", "Model keys are not set up on this server yet. Ask the operator to set CI_SECRETS_KEY."); const sealed = model && box ? await box.seal(model.key, keyScope(id)) : null; await db .prepare( `INSERT INTO hosted_agents (id, namespace_id, repo_id, handle, description, instructions, provider, model, ciphertext, wrapped_key, key_hint, updated_by, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 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`, ) .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()) .run(); return ok(); }, async remove(handle) { if (!editable) return deny(); await db.prepare("DELETE FROM hosted_agents WHERE id = ?").bind(agentId(namespaceId, repoId, handle)).run(); return ok(); }, }; }