import { listAgentRuns } from "../agent-runs.ts"; import { openHostedAgents } from "../agents.ts"; import { now } from "../auth.ts"; import { defaultRef, imageType, isBinary, lastChanges, listRefs, loadCommits, loadFile, loadTree, locate, readFileAt, tipCommit } from "../browse.ts"; import { codeMapAt, codeMapSummaryAt } from "../code-maps.ts"; import { isCommitHash } from "../contract/links.ts"; import { commitDetail, rememberReads } from "../diff.ts"; import type { Outcome } from "../contract/common.ts"; import type { Pull, Repo, RepoSettings } from "../contract/handles.ts"; import type { RepoSummary } from "../contract/views.ts"; import { ANONYMOUS, recordEvent, repoStream, taskStream, withPushers } from "../events.ts"; import { readRefs, receivePack, ZERO_OID, type Refs as GitRefs } from "../git.ts"; import { pusher, type PushMessage } from "../pushes.ts"; import { pushRef } from "../gitwrite.ts"; import { deliverMentions, onPull } from "../mentions.ts"; import { conflict, firstInvalid, invalid, ok, raise } from "../outcomes.ts"; import { Policy } from "../policy.ts"; import { descriptionError, repoFacts, toSummary as repoSummary, type ProvisionInput, type RepoRecord } from "../repos.ts"; import { decidePermission, pendingPermissions } from "../permissions.ts"; import * as pulls from "../pulls.ts"; import { bodyError, titleError } from "../text.ts"; import { cachedChanges, type Deps } from "./context.ts"; import { openPull } from "./pull.ts"; import { openCiSettings, openRepoCi, startPullCi } from "./ci.ts"; /** A session counts as online while it has called the origin within this window. */ export const AGENT_ONLINE_SECONDS = 300; /** A session on a machine whose daemon is connected stays online, idle, this long after its last call. */ export const AGENT_IDLE_SECONDS = 60 * 60; type Provision = (input: ProvisionInput, create: (id: string) => Promise, event: "repo.forked", data: Record, owner?: string) => Promise>; export function openRepo(deps: Deps, policy: Policy, record: RepoRecord, provision: Provision): Repo { const { env, ctx } = deps; const db = env.DB; const facts = repoFacts(record); let artifacts: Promise | undefined; let advertised: Promise | undefined; const handle = () => (artifacts ??= env.ARTIFACTS.get(record.artifacts_name).then((opened) => rememberReads(opened, record.id))); const gitRefs = () => (advertised ??= handle().then(readRefs)); async function at(segments: readonly string[], load: (handle: ArtifactsRepo, ref: string, path: string[]) => Promise) { const opened = await handle().catch(() => raise("not_found", "The repository is not ready yet.")); const found = await locate(gitRefs(), [...segments], (ref, path) => load(opened, ref, path)); return found ?? raise("not_found", `Nothing at ${segments.join("/")} in ${record.full_name}.`); } const usesOf = async (): Promise<{ pulls: Map; agents: Map }> => { const at = now(); const [pullRows, agentRows] = await Promise.all([ db.prepare("SELECT number, base_ref, head_ref FROM pulls WHERE repo_id = ? AND status = 'open' ORDER BY number DESC").bind(record.id).all<{ number: number; base_ref: string; head_ref: string }>(), db .prepare("SELECT branch, runtime FROM agent_sessions WHERE repo_id = ? AND branch IS NOT NULL AND ended_at IS NULL AND status = 'running' AND expires_at > ? AND last_seen_at > ?") .bind(record.id, at, at - AGENT_IDLE_SECONDS) .all<{ branch: string; runtime: string }>(), ]); return { pulls: new Map(pullRows.results.flatMap((row) => [[row.base_ref, row.number], [row.head_ref, row.number]] as const)), agents: new Map(agentRows.results.map((row) => [row.branch, row.runtime] as const)), }; }; return { summary: repoSummary(record, policy, deps.origin), async permissions() { return policy.person ? pendingPermissions(db, record.id, policy.person.id) : []; }, async latest(task) { const taskId = task ? await db.prepare("SELECT id FROM tasks WHERE repo_id = ? AND number = ?").bind(record.id, task).first("id") : null; const row = await db .prepare("SELECT max(id) AS latest FROM events WHERE stream IN (?, ?)") .bind(repoStream(record.id), taskId === null ? repoStream(record.id) : taskStream(taskId)) .first("latest"); return row ?? 0; }, async decidePermission(session, requestId, behavior) { if (!(await decidePermission(db, policy.actor, record.id, session, requestId, behavior))) return invalid("Only the agent's own human can answer this, and only while it is waiting."); await env.REPO_HUB.get(env.REPO_HUB.idFromName(record.id)).decide(session, requestId, behavior).catch(() => undefined); return ok(); }, async agents() { if (!policy.member) return []; const at = now(); const { results } = await db .prepare( `SELECT s.id, s.runtime, s.created_at, s.last_seen_at, s.machine, s.branch, u.id AS person_id, u.name AS person_name FROM agent_sessions s JOIN users u ON u.id = s.user_id LEFT JOIN machines m ON m.user_id = s.user_id AND m.name = s.machine WHERE s.repo_id = ? AND s.parent_session IS NULL AND s.ended_at IS NULL AND s.status = 'running' AND s.expires_at > ? AND s.mcp_session IS NOT NULL AND ((m.connected = 1 AND s.last_seen_at > ?) OR s.last_seen_at > ?) ORDER BY s.last_seen_at DESC`, ) .bind(record.id, at, at - AGENT_IDLE_SECONDS, at - AGENT_ONLINE_SECONDS) .all<{ id: string; runtime: string; created_at: number; last_seen_at: number; machine: string | null; branch: string | null; person_id: string; person_name: string }>(); return results.map((row) => ({ session: row.id, runtime: row.runtime, onBehalfOf: { id: row.person_id, name: row.person_name }, branch: row.branch, since: row.created_at, lastSeen: row.last_seen_at, machine: row.machine, })); }, async home() { const opened = await handle().catch((error) => { console.error("repository not ready", record.artifacts_name, error); return null; }); if (!opened) return { kind: "preparing" }; const speculative = loadTree(opened, record.full_name, record.default_branch, []).catch(() => null); const refs = await gitRefs(); const ref = defaultRef(refs); if (ref && ref !== record.default_branch) ctx.waitUntil(db.prepare("UPDATE repos SET default_branch = ? WHERE id = ?").bind(ref, record.id).run()); const tree = ref && (ref === record.default_branch ? await speculative : (await Promise.all([speculative, loadTree(opened, record.full_name, ref, [])]))[1]); if (!ref || !tree) { await speculative; return { kind: "empty" }; } return { kind: "tree", refs: listRefs(refs), tree }; }, async refs() { await handle().catch(() => raise("not_found", "The repository is not ready yet.")); return listRefs(await gitRefs()); }, async branches() { const [opened, refs] = await Promise.all([handle().catch(() => raise("not_found", "The repository is not ready yet.")), gitRefs()]); const base = defaultRef(refs); const uses = policy.member ? await usesOf() : { pulls: new Map(), agents: new Map() }; // ponytail: one log call for each branch. Page the list when a repository has hundreds of branches. const list = await Promise.all( [...refs.branches.keys()].map(async (name) => ({ name, isDefault: name === base, commit: await tipCommit(opened, name).catch(() => null), pull: uses.pulls.get(name) ?? null, agent: uses.agents.get(name) ?? null, })), ); return list.sort((a, b) => Number(b.isDefault) - Number(a.isDefault) || (b.commit?.committedAt ?? 0) - (a.commit?.committedAt ?? 0)); }, async deleteBranch(name) { if (policy.actor.kind !== "human" || !policy.canWriteRepo(facts)) return invalid("Only a person with write access can delete a branch."); const [opened, refs] = await Promise.all([handle(), gitRefs()]); const tip = refs.branches.get(name); if (!tip) return invalid(`No branch named "${name}".`); if (name === defaultRef(refs)) return invalid(`${name} is the default branch. It cannot be deleted.`); const uses = await usesOf(); const pull = uses.pulls.get(name); if (pull) return invalid(`Pull request #${pull} uses ${name}. Merge or close it first.`); if (uses.agents.has(name)) return invalid(`An agent works on ${name} now. Wait until the agent releases the branch.`); const ref = `refs/heads/${name}`; const deleted = await receivePack(opened, [`${tip} ${ZERO_OID} ${ref}`], [], new Uint8Array()).catch(() => null); if (deleted?.refs.get(ref) !== null) return invalid(`Couldn't delete ${name}. If the branch just moved, reload and try again.`); await env.PUSHES.send({ repoId: record.id, actor: pusher(policy.actor), updates: [{ ref, from: tip, to: null }], at: now() } satisfies PushMessage).catch((error) => console.error(`branch deletion not queued for repo ${record.id}`, error)); return ok(); }, async tree(segments) { return (await at(segments, (opened, ref, path) => loadTree(opened, record.full_name, ref, path))).data; }, async file(segments) { return (await at(segments, (opened, ref, path) => loadFile(opened, record.full_name, ref, path))).data; }, async raw(segments) { const found = await at(segments, (opened, ref, path) => readFileAt(opened, ref, path)); const name = found.path[found.path.length - 1]; const bytes = new Uint8Array(await found.data.arrayBuffer()); const contentType = imageType(name) ?? (/\.svg$/i.test(name) ? "image/svg+xml" : undefined) ?? (isBinary(bytes) ? "application/octet-stream" : "text/plain; charset=utf-8"); return { name, contentType, body: new Response(bytes).body!, cacheable: record.visibility === "public" }; }, async history(segments, page) { const number = Math.max(1, Number(page?.cursor) || 1); const found = await at(segments, (opened, ref) => loadCommits(opened, ref, number)); return { location: { ref: found.ref, path: found.path }, page: { items: await withPushers(db, record.id, found.data.commits), next: found.data.hasOlder ? String(number + 1) : null } }; }, async lastChanges(segments) { const found = await at(segments, (opened, ref, path) => lastChanges(opened, ref, path)); return { asOf: now(), changes: found.data }; }, async compare(base, head) { const [opened, refs] = await Promise.all([handle(), gitRefs()]); const baseTip = refs.branches.get(base); const headTip = refs.branches.get(head); if (!baseTip || !headTip) raise("not_found", `No branch named "${baseTip ? head : base}" in ${record.full_name}.`); return cachedChanges(deps, record.id, opened, baseTip, headTip); }, async pulls(query) { if (!policy.member) raise("sign_in_required", "Sign in to see pull requests."); const found = await pulls.listPulls(db, record.id, query.status); return { items: found.items.filter((row) => policy.canOpenPull(record.full_name, { head: row.head_ref })).map(pulls.toPullSummary), counts: found.counts }; }, async pull(number) { const row = await pulls.findPull(db, record.id, number); if (!row || !policy.canOpenPull(record.full_name, { head: row.head_ref })) raise("not_found", `No pull request #${number} in ${record.full_name}.`); return openPull(deps, policy, row, facts, record.namespace_id, handle, gitRefs); }, async openPull(input) { const person = policy.person ?? raise("sign_in_required", "Sign in to open a pull request."); const title = input.title.trim(); const body = input.body.trim(); const textProblem = firstInvalid({ title: titleError(title), body: bodyError(body) }); if (textProblem) return textProblem; if (input.base === input.head) return invalid("Choose two different branches.", "head"); if (!policy.canOpenPull(record.full_name, { head: input.head })) return invalid("You can only open pull requests from your branch.", "head"); const [opened, refs] = await Promise.all([handle(), gitRefs()]); const baseTip = refs.branches.get(input.base); const headTip = refs.branches.get(input.head); if (!baseTip || !headTip) return invalid(`No branch named "${baseTip ? input.head : input.base}".`, baseTip ? "head" : "base"); const existing = await db.prepare("SELECT number FROM pulls WHERE repo_id = ? AND base_ref = ? AND head_ref = ? AND status = 'open'").bind(record.id, input.base, input.head).first("number"); if (existing) return invalid(`Pull request #${existing} already proposes ${input.head} into ${input.base}.`, "head"); if (!(await cachedChanges(deps, record.id, opened, baseTip, headTip)).commits.length) return invalid(`${input.base} already contains every commit on ${input.head}.`, "head"); const created = await pulls.createPull(db, policy.actor, { repoId: record.id, title, body, authorId: person.id, base: input.base, head: input.head }); if (created.kind === "already_open") return conflict(`A pull request already proposes ${input.head} into ${input.base}.`, "head"); startPullCi(deps, policy, record, { number: created.number, base: input.base, head: input.head, sha: headTip }); return ok(pulls.toPullSummary((await pulls.findPull(db, record.id, created.number))!)); }, async handOff({ title, body, session }) { const person = policy.person; if (policy.actor.kind !== "human" || !person || !policy.canWriteRepo(facts)) return invalid("Only a person with write access can hand work to an agent."); const agent = (await this.agents()).find((candidate) => candidate.session === session); if (!agent) return invalid("Choose an agent that is online in this repository.", "agent"); const [opened, refs] = await Promise.all([handle(), gitRefs()]); const base = defaultRef(refs); const tip = base ? refs.branches.get(base) : undefined; if (!base || !tip) return invalid(`${record.full_name} has no commits yet. Push a first commit, then hand off the work.`); const head = pulls.freshBranchName(title, refs.branches, base); const ref = `refs/heads/${head}`; const pushed = await pushRef(opened, ref, ZERO_OID, tip, []); if (!pushed.ok) return invalid(`Couldn't create ${head}: ${pushed.reason}.`); await recordEvent(db, policy.actor, repoStream(record.id), "repo.pushed", { updates: [{ ref, from: null, to: tip }] }, now()).run(); const briefing = [`@agent/${session}`, title, body].filter(Boolean).join("\n\n"); const created = await pulls.createPull(db, policy.actor, { repoId: record.id, title, body: briefing, authorId: person.id, base, head }); if (created.kind === "already_open") return conflict(`A pull request already proposes ${head} into ${base}.`); startPullCi(deps, policy, record, { number: created.number, base, head, sha: tip }); const fresh = (await pulls.findPull(db, record.id, created.number))!; await deliverMentions(env, ctx, policy.actor, onPull(fresh), pulls.mentionText(fresh, deps.origin, briefing), null, { assign: true }); return ok({ pull: created.number, agent }); }, async codeMap(ref) { const [opened, refs] = await Promise.all([handle().catch(() => raise("not_found", "The repository is not ready yet.")), gitRefs()]); const name = ref ?? defaultRef(refs); if (!name) return raise("not_found", `${record.full_name} has no commits yet.`); const commit = refs.branches.get(name) ?? refs.tags.get(name) ?? (isCommitHash(name) ? name : null); if (!commit) return raise("not_found", `No branch, tag or commit named ${name} in ${record.full_name}.`); return { ref: name, map: await codeMapSummaryAt(env, ctx, record.id, opened, commit) }; }, async codeGraph(commit) { if (!isCommitHash(commit)) return raise("not_found", `${commit} is not a commit hash.`); const opened = await handle().catch(() => raise("not_found", "The repository is not ready yet.")); return codeMapAt(env, ctx, record.id, opened, commit); }, async commit(hash) { if (!/^[0-9a-f]{40}$/.test(hash)) raise("not_found", "Commit not found."); return (await commitDetail(await handle(), hash)) ?? raise("not_found", "Commit not found."); }, async fork(input) { const values = { name: input.name.trim(), description: input.description.trim(), visibility: input.visibility, forkOf: record.id }; return provision( values, async (id) => { const source = await handle(); await source.fork(id, { description: values.description || undefined }); }, "repo.forked", { from: record.full_name }, input.owner, ); }, async settings() { if (!policy.canAdminRepo(facts)) raise("not_found", "Only admins can change repository settings."); return openRepoSettings(env, policy, record); }, ci: () => openRepoCi(env, policy, record), async hostedAgents() { if (!policy.member) raise("not_found", "Only members see a repository's agents."); return openHostedAgents(env, policy, record.namespace_id, record.id, policy.canAdminRepo(facts)); }, async agentRuns(open) { if (!policy.member) raise("not_found", "Only members see a repository's agents."); return listAgentRuns(db, record.id, open); }, }; } function openRepoSettings(env: Env, policy: Policy, record: RepoRecord): RepoSettings { const db = env.DB; return { description: record.description, visibility: record.visibility, ci: openCiSettings(env, policy, record), async update(changes) { const description = changes.description?.trim() ?? record.description; const visibility = changes.visibility ?? record.visibility; const descriptionProblem = firstInvalid({ description: descriptionError(description) }); if (descriptionProblem) return descriptionProblem; if (description === record.description && visibility === record.visibility) return ok(); const at = now(); const changed = { ...(description !== record.description ? { description } : {}), ...(visibility !== record.visibility ? { visibility } : {}) }; await db.batch([ db.prepare("UPDATE repos SET description = ?, visibility = ? WHERE id = ?").bind(description, visibility, record.id), recordEvent(db, policy.actor, repoStream(record.id), "repo.updated", changed, at), ]); if (visibility === "private" && record.visibility !== "private") await env.REPO_HUB.get(env.REPO_HUB.idFromName(record.id)).disconnect(ANONYMOUS).catch(() => undefined); return ok(); }, async delete(confirmName) { if (confirmName !== record.full_name) return invalid("The confirmation didn't match the repository name.", "confirm"); await db.batch([ db.prepare("DELETE FROM events WHERE stream IN (SELECT 'task:' || id FROM tasks WHERE repo_id = ?)").bind(record.id), db.prepare("DELETE FROM events WHERE stream IN (SELECT 'pull:' || id FROM pulls WHERE repo_id = ?)").bind(record.id), db.prepare("DELETE FROM repos WHERE id = ?").bind(record.id), recordEvent(db, policy.actor, repoStream(record.id), "repo.deleted", { name: record.full_name }, now()), ]); await env.ARTIFACTS.delete(record.artifacts_name).catch((error) => console.error(`storage ${record.artifacts_name} of deleted repo ${record.full_name} not removed`, error)); return ok(); }, }; }