347 lines · 19.5 KBRaw
| 1 | import { listAgentRuns } from "../agent-runs.ts"; |
| 2 | import { openHostedAgents } from "../agents.ts"; |
| 3 | import { now } from "../auth.ts"; |
| 4 | import { defaultRef, imageType, isBinary, lastChanges, listRefs, loadCommits, loadFile, loadTree, locate, readFileAt, tipCommit } from "../browse.ts"; |
| 5 | import { codeMapAt, codeMapSummaryAt } from "../code-maps.ts"; |
| 6 | import { isCommitHash } from "../contract/links.ts"; |
| 7 | import { commitDetail, rememberReads } from "../diff.ts"; |
| 8 | import type { Outcome } from "../contract/common.ts"; |
| 9 | import type { Pull, Repo, RepoSettings } from "../contract/handles.ts"; |
| 10 | import type { RepoSummary } from "../contract/views.ts"; |
| 11 | import { ANONYMOUS, recordEvent, repoStream, taskStream, withPushers } from "../events.ts"; |
| 12 | import { readRefs, receivePack, ZERO_OID, type Refs as GitRefs } from "../git.ts"; |
| 13 | import { pusher, type PushMessage } from "../pushes.ts"; |
| 14 | import { pushRef } from "../gitwrite.ts"; |
| 15 | import { deliverMentions, onPull } from "../mentions.ts"; |
| 16 | import { conflict, firstInvalid, invalid, ok, raise } from "../outcomes.ts"; |
| 17 | import { Policy } from "../policy.ts"; |
| 18 | import { descriptionError, repoFacts, toSummary as repoSummary, type ProvisionInput, type RepoRecord } from "../repos.ts"; |
| 19 | import { decidePermission, pendingPermissions } from "../permissions.ts"; |
| 20 | import * as pulls from "../pulls.ts"; |
| 21 | import { bodyError, titleError } from "../text.ts"; |
| 22 | import { cachedChanges, type Deps } from "./context.ts"; |
| 23 | import { openPull } from "./pull.ts"; |
| 24 | import { openCiSettings, openRepoCi, startPullCi } from "./ci.ts"; |
| 25 | |
| 26 | /** A session counts as online while it has called the origin within this window. */ |
| 27 | export const AGENT_ONLINE_SECONDS = 300; |
| 28 | /** A session on a machine whose daemon is connected stays online, idle, this long after its last call. */ |
| 29 | export const AGENT_IDLE_SECONDS = 60 * 60; |
| 30 | |
| 31 | type Provision = (input: ProvisionInput, create: (id: string) => Promise<unknown>, event: "repo.forked", data: Record<string, string>, owner?: string) => Promise<Outcome<RepoSummary>>; |
| 32 | |
| 33 | export function openRepo(deps: Deps, policy: Policy, record: RepoRecord, provision: Provision): Repo { |
| 34 | const { env, ctx } = deps; |
| 35 | const db = env.DB; |
| 36 | const facts = repoFacts(record); |
| 37 | |
| 38 | let artifacts: Promise<ArtifactsRepo> | undefined; |
| 39 | let advertised: Promise<GitRefs> | undefined; |
| 40 | const handle = () => (artifacts ??= env.ARTIFACTS.get(record.artifacts_name).then((opened) => rememberReads(opened, record.id))); |
| 41 | const gitRefs = () => (advertised ??= handle().then(readRefs)); |
| 42 | |
| 43 | async function at<T>(segments: readonly string[], load: (handle: ArtifactsRepo, ref: string, path: string[]) => Promise<T | null>) { |
| 44 | const opened = await handle().catch(() => raise("not_found", "The repository is not ready yet.")); |
| 45 | const found = await locate(gitRefs(), [...segments], (ref, path) => load(opened, ref, path)); |
| 46 | return found ?? raise("not_found", `Nothing at ${segments.join("/")} in ${record.full_name}.`); |
| 47 | } |
| 48 | |
| 49 | const usesOf = async (): Promise<{ pulls: Map<string, number>; agents: Map<string, string> }> => { |
| 50 | const at = now(); |
| 51 | const [pullRows, agentRows] = await Promise.all([ |
| 52 | 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 }>(), |
| 53 | db |
| 54 | .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 > ?") |
| 55 | .bind(record.id, at, at - AGENT_IDLE_SECONDS) |
| 56 | .all<{ branch: string; runtime: string }>(), |
| 57 | ]); |
| 58 | return { |
| 59 | pulls: new Map(pullRows.results.flatMap((row) => [[row.base_ref, row.number], [row.head_ref, row.number]] as const)), |
| 60 | agents: new Map(agentRows.results.map((row) => [row.branch, row.runtime] as const)), |
| 61 | }; |
| 62 | }; |
| 63 | |
| 64 | return { |
| 65 | summary: repoSummary(record, policy, deps.origin), |
| 66 | |
| 67 | async permissions() { |
| 68 | return policy.person ? pendingPermissions(db, record.id, policy.person.id) : []; |
| 69 | }, |
| 70 | |
| 71 | async latest(task) { |
| 72 | const taskId = task ? await db.prepare("SELECT id FROM tasks WHERE repo_id = ? AND number = ?").bind(record.id, task).first<number>("id") : null; |
| 73 | const row = await db |
| 74 | .prepare("SELECT max(id) AS latest FROM events WHERE stream IN (?, ?)") |
| 75 | .bind(repoStream(record.id), taskId === null ? repoStream(record.id) : taskStream(taskId)) |
| 76 | .first<number | null>("latest"); |
| 77 | return row ?? 0; |
| 78 | }, |
| 79 | |
| 80 | async decidePermission(session, requestId, behavior) { |
| 81 | 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."); |
| 82 | await env.REPO_HUB.get(env.REPO_HUB.idFromName(record.id)).decide(session, requestId, behavior).catch(() => undefined); |
| 83 | return ok(); |
| 84 | }, |
| 85 | |
| 86 | async agents() { |
| 87 | if (!policy.member) return []; |
| 88 | const at = now(); |
| 89 | const { results } = await db |
| 90 | .prepare( |
| 91 | `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 |
| 92 | 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 |
| 93 | 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 > ?) |
| 94 | ORDER BY s.last_seen_at DESC`, |
| 95 | ) |
| 96 | .bind(record.id, at, at - AGENT_IDLE_SECONDS, at - AGENT_ONLINE_SECONDS) |
| 97 | .all<{ id: string; runtime: string; created_at: number; last_seen_at: number; machine: string | null; branch: string | null; person_id: string; person_name: string }>(); |
| 98 | return results.map((row) => ({ |
| 99 | session: row.id, |
| 100 | runtime: row.runtime, |
| 101 | onBehalfOf: { id: row.person_id, name: row.person_name }, |
| 102 | branch: row.branch, |
| 103 | since: row.created_at, |
| 104 | lastSeen: row.last_seen_at, |
| 105 | machine: row.machine, |
| 106 | })); |
| 107 | }, |
| 108 | |
| 109 | async home() { |
| 110 | const opened = await handle().catch((error) => { |
| 111 | console.error("repository not ready", record.artifacts_name, error); |
| 112 | return null; |
| 113 | }); |
| 114 | if (!opened) return { kind: "preparing" }; |
| 115 | |
| 116 | const speculative = loadTree(opened, record.full_name, record.default_branch, []).catch(() => null); |
| 117 | const refs = await gitRefs(); |
| 118 | const ref = defaultRef(refs); |
| 119 | if (ref && ref !== record.default_branch) ctx.waitUntil(db.prepare("UPDATE repos SET default_branch = ? WHERE id = ?").bind(ref, record.id).run()); |
| 120 | const tree = ref && (ref === record.default_branch ? await speculative : (await Promise.all([speculative, loadTree(opened, record.full_name, ref, [])]))[1]); |
| 121 | if (!ref || !tree) { |
| 122 | await speculative; |
| 123 | return { kind: "empty" }; |
| 124 | } |
| 125 | return { kind: "tree", refs: listRefs(refs), tree }; |
| 126 | }, |
| 127 | |
| 128 | async refs() { |
| 129 | await handle().catch(() => raise("not_found", "The repository is not ready yet.")); |
| 130 | return listRefs(await gitRefs()); |
| 131 | }, |
| 132 | |
| 133 | async branches() { |
| 134 | const [opened, refs] = await Promise.all([handle().catch(() => raise("not_found", "The repository is not ready yet.")), gitRefs()]); |
| 135 | const base = defaultRef(refs); |
| 136 | const uses = policy.member ? await usesOf() : { pulls: new Map<string, number>(), agents: new Map<string, string>() }; |
| 137 | // ponytail: one log call for each branch. Page the list when a repository has hundreds of branches. |
| 138 | const list = await Promise.all( |
| 139 | [...refs.branches.keys()].map(async (name) => ({ |
| 140 | name, |
| 141 | isDefault: name === base, |
| 142 | commit: await tipCommit(opened, name).catch(() => null), |
| 143 | pull: uses.pulls.get(name) ?? null, |
| 144 | agent: uses.agents.get(name) ?? null, |
| 145 | })), |
| 146 | ); |
| 147 | return list.sort((a, b) => Number(b.isDefault) - Number(a.isDefault) || (b.commit?.committedAt ?? 0) - (a.commit?.committedAt ?? 0)); |
| 148 | }, |
| 149 | |
| 150 | async deleteBranch(name) { |
| 151 | if (policy.actor.kind !== "human" || !policy.canWriteRepo(facts)) return invalid("Only a person with write access can delete a branch."); |
| 152 | const [opened, refs] = await Promise.all([handle(), gitRefs()]); |
| 153 | const tip = refs.branches.get(name); |
| 154 | if (!tip) return invalid(`No branch named "${name}".`); |
| 155 | if (name === defaultRef(refs)) return invalid(`${name} is the default branch. It cannot be deleted.`); |
| 156 | const uses = await usesOf(); |
| 157 | const pull = uses.pulls.get(name); |
| 158 | if (pull) return invalid(`Pull request #${pull} uses ${name}. Merge or close it first.`); |
| 159 | if (uses.agents.has(name)) return invalid(`An agent works on ${name} now. Wait until the agent releases the branch.`); |
| 160 | const ref = `refs/heads/${name}`; |
| 161 | const deleted = await receivePack(opened, [`${tip} ${ZERO_OID} ${ref}`], [], new Uint8Array()).catch(() => null); |
| 162 | if (deleted?.refs.get(ref) !== null) return invalid(`Couldn't delete ${name}. If the branch just moved, reload and try again.`); |
| 163 | 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)); |
| 164 | return ok(); |
| 165 | }, |
| 166 | |
| 167 | async tree(segments) { |
| 168 | return (await at(segments, (opened, ref, path) => loadTree(opened, record.full_name, ref, path))).data; |
| 169 | }, |
| 170 | |
| 171 | async file(segments) { |
| 172 | return (await at(segments, (opened, ref, path) => loadFile(opened, record.full_name, ref, path))).data; |
| 173 | }, |
| 174 | |
| 175 | async raw(segments) { |
| 176 | const found = await at(segments, (opened, ref, path) => readFileAt(opened, ref, path)); |
| 177 | const name = found.path[found.path.length - 1]; |
| 178 | const bytes = new Uint8Array(await found.data.arrayBuffer()); |
| 179 | const contentType = imageType(name) ?? (isBinary(bytes) ? "application/octet-stream" : "text/plain; charset=utf-8"); |
| 180 | return { name, contentType, body: new Response(bytes).body!, cacheable: record.visibility === "public" }; |
| 181 | }, |
| 182 | |
| 183 | async history(segments, page) { |
| 184 | const number = Math.max(1, Number(page?.cursor) || 1); |
| 185 | const found = await at(segments, (opened, ref) => loadCommits(opened, ref, number)); |
| 186 | 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 } }; |
| 187 | }, |
| 188 | |
| 189 | async lastChanges(segments) { |
| 190 | const found = await at(segments, (opened, ref, path) => lastChanges(opened, ref, path)); |
| 191 | return { asOf: now(), changes: found.data }; |
| 192 | }, |
| 193 | |
| 194 | async compare(base, head) { |
| 195 | const [opened, refs] = await Promise.all([handle(), gitRefs()]); |
| 196 | const baseTip = refs.branches.get(base); |
| 197 | const headTip = refs.branches.get(head); |
| 198 | if (!baseTip || !headTip) raise("not_found", `No branch named "${baseTip ? head : base}" in ${record.full_name}.`); |
| 199 | return cachedChanges(deps, record.id, opened, baseTip, headTip); |
| 200 | }, |
| 201 | |
| 202 | async pulls(query) { |
| 203 | if (!policy.member) raise("sign_in_required", "Sign in to see pull requests."); |
| 204 | const found = await pulls.listPulls(db, record.id, query.status); |
| 205 | return { items: found.items.filter((row) => policy.canOpenPull(record.full_name, { head: row.head_ref })).map(pulls.toPullSummary), counts: found.counts }; |
| 206 | }, |
| 207 | |
| 208 | async pull(number) { |
| 209 | const row = await pulls.findPull(db, record.id, number); |
| 210 | if (!row || !policy.canOpenPull(record.full_name, { head: row.head_ref })) raise("not_found", `No pull request #${number} in ${record.full_name}.`); |
| 211 | return openPull(deps, policy, row, facts, record.namespace_id, handle, gitRefs); |
| 212 | }, |
| 213 | |
| 214 | async openPull(input) { |
| 215 | const person = policy.person ?? raise("sign_in_required", "Sign in to open a pull request."); |
| 216 | const title = input.title.trim(); |
| 217 | const body = input.body.trim(); |
| 218 | const textProblem = firstInvalid({ title: titleError(title), body: bodyError(body) }); |
| 219 | if (textProblem) return textProblem; |
| 220 | if (input.base === input.head) return invalid("Choose two different branches.", "head"); |
| 221 | if (!policy.canOpenPull(record.full_name, { head: input.head })) return invalid("You can only open pull requests from your branch.", "head"); |
| 222 | const [opened, refs] = await Promise.all([handle(), gitRefs()]); |
| 223 | const baseTip = refs.branches.get(input.base); |
| 224 | const headTip = refs.branches.get(input.head); |
| 225 | if (!baseTip || !headTip) return invalid(`No branch named "${baseTip ? input.head : input.base}".`, baseTip ? "head" : "base"); |
| 226 | 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>("number"); |
| 227 | if (existing) return invalid(`Pull request #${existing} already proposes ${input.head} into ${input.base}.`, "head"); |
| 228 | if (!(await cachedChanges(deps, record.id, opened, baseTip, headTip)).commits.length) return invalid(`${input.base} already contains every commit on ${input.head}.`, "head"); |
| 229 | const created = await pulls.createPull(db, policy.actor, { repoId: record.id, title, body, authorId: person.id, base: input.base, head: input.head }); |
| 230 | if (created.kind === "already_open") return conflict(`A pull request already proposes ${input.head} into ${input.base}.`, "head"); |
| 231 | startPullCi(deps, policy, record, { number: created.number, base: input.base, head: input.head, sha: headTip }); |
| 232 | return ok(pulls.toPullSummary((await pulls.findPull(db, record.id, created.number))!)); |
| 233 | }, |
| 234 | |
| 235 | async handOff({ title, body, session }) { |
| 236 | const person = policy.person; |
| 237 | if (policy.actor.kind !== "human" || !person || !policy.canWriteRepo(facts)) return invalid("Only a person with write access can hand work to an agent."); |
| 238 | const agent = (await this.agents()).find((candidate) => candidate.session === session); |
| 239 | if (!agent) return invalid("Choose an agent that is online in this repository.", "agent"); |
| 240 | const [opened, refs] = await Promise.all([handle(), gitRefs()]); |
| 241 | const base = defaultRef(refs); |
| 242 | const tip = base ? refs.branches.get(base) : undefined; |
| 243 | if (!base || !tip) return invalid(`${record.full_name} has no commits yet. Push a first commit, then hand off the work.`); |
| 244 | const head = pulls.freshBranchName(title, refs.branches, base); |
| 245 | const ref = `refs/heads/${head}`; |
| 246 | const pushed = await pushRef(opened, ref, ZERO_OID, tip, []); |
| 247 | if (!pushed.ok) return invalid(`Couldn't create ${head}: ${pushed.reason}.`); |
| 248 | await recordEvent(db, policy.actor, repoStream(record.id), "repo.pushed", { updates: [{ ref, from: null, to: tip }] }, now()).run(); |
| 249 | const briefing = [`@agent/${session}`, title, body].filter(Boolean).join("\n\n"); |
| 250 | const created = await pulls.createPull(db, policy.actor, { repoId: record.id, title, body: briefing, authorId: person.id, base, head }); |
| 251 | if (created.kind === "already_open") return conflict(`A pull request already proposes ${head} into ${base}.`); |
| 252 | startPullCi(deps, policy, record, { number: created.number, base, head, sha: tip }); |
| 253 | const fresh = (await pulls.findPull(db, record.id, created.number))!; |
| 254 | await deliverMentions(env, ctx, policy.actor, onPull(fresh), pulls.mentionText(fresh, deps.origin, briefing), null, { assign: true }); |
| 255 | return ok({ pull: created.number, agent }); |
| 256 | }, |
| 257 | |
| 258 | async codeMap(ref) { |
| 259 | const [opened, refs] = await Promise.all([handle().catch(() => raise("not_found", "The repository is not ready yet.")), gitRefs()]); |
| 260 | const name = ref ?? defaultRef(refs); |
| 261 | if (!name) return raise("not_found", `${record.full_name} has no commits yet.`); |
| 262 | const commit = refs.branches.get(name) ?? refs.tags.get(name) ?? (isCommitHash(name) ? name : null); |
| 263 | if (!commit) return raise("not_found", `No branch, tag or commit named ${name} in ${record.full_name}.`); |
| 264 | return { ref: name, map: await codeMapSummaryAt(env, ctx, record.id, opened, commit) }; |
| 265 | }, |
| 266 | |
| 267 | async codeGraph(commit) { |
| 268 | if (!isCommitHash(commit)) return raise("not_found", `${commit} is not a commit hash.`); |
| 269 | const opened = await handle().catch(() => raise("not_found", "The repository is not ready yet.")); |
| 270 | return codeMapAt(env, ctx, record.id, opened, commit); |
| 271 | }, |
| 272 | |
| 273 | async commit(hash) { |
| 274 | if (!/^[0-9a-f]{40}$/.test(hash)) raise("not_found", "Commit not found."); |
| 275 | return (await commitDetail(await handle(), hash)) ?? raise("not_found", "Commit not found."); |
| 276 | }, |
| 277 | |
| 278 | async fork(input) { |
| 279 | const values = { name: input.name.trim(), description: input.description.trim(), visibility: input.visibility, forkOf: record.id }; |
| 280 | return provision( |
| 281 | values, |
| 282 | async (id) => { |
| 283 | const source = await handle(); |
| 284 | await source.fork(id, { description: values.description || undefined }); |
| 285 | }, |
| 286 | "repo.forked", |
| 287 | { from: record.full_name }, |
| 288 | input.owner, |
| 289 | ); |
| 290 | }, |
| 291 | |
| 292 | async settings() { |
| 293 | if (!policy.canAdminRepo(facts)) raise("not_found", "Only admins can change repository settings."); |
| 294 | return openRepoSettings(env, policy, record); |
| 295 | }, |
| 296 | |
| 297 | ci: () => openRepoCi(env, policy, record), |
| 298 | |
| 299 | async hostedAgents() { |
| 300 | if (!policy.member) raise("not_found", "Only members see a repository's agents."); |
| 301 | return openHostedAgents(env, policy, record.namespace_id, record.id, policy.canAdminRepo(facts)); |
| 302 | }, |
| 303 | |
| 304 | async agentRuns(open) { |
| 305 | if (!policy.member) raise("not_found", "Only members see a repository's agents."); |
| 306 | return listAgentRuns(db, record.id, open); |
| 307 | }, |
| 308 | }; |
| 309 | } |
| 310 | |
| 311 | function openRepoSettings(env: Env, policy: Policy, record: RepoRecord): RepoSettings { |
| 312 | const db = env.DB; |
| 313 | return { |
| 314 | description: record.description, |
| 315 | visibility: record.visibility, |
| 316 | ci: openCiSettings(env, policy, record), |
| 317 | |
| 318 | async update(changes) { |
| 319 | const description = changes.description?.trim() ?? record.description; |
| 320 | const visibility = changes.visibility ?? record.visibility; |
| 321 | const descriptionProblem = firstInvalid({ description: descriptionError(description) }); |
| 322 | if (descriptionProblem) return descriptionProblem; |
| 323 | if (description === record.description && visibility === record.visibility) return ok(); |
| 324 | |
| 325 | const at = now(); |
| 326 | const changed = { ...(description !== record.description ? { description } : {}), ...(visibility !== record.visibility ? { visibility } : {}) }; |
| 327 | await db.batch([ |
| 328 | db.prepare("UPDATE repos SET description = ?, visibility = ? WHERE id = ?").bind(description, visibility, record.id), |
| 329 | recordEvent(db, policy.actor, repoStream(record.id), "repo.updated", changed, at), |
| 330 | ]); |
| 331 | if (visibility === "private" && record.visibility !== "private") await env.REPO_HUB.get(env.REPO_HUB.idFromName(record.id)).disconnect(ANONYMOUS).catch(() => undefined); |
| 332 | return ok(); |
| 333 | }, |
| 334 | |
| 335 | async delete(confirmName) { |
| 336 | if (confirmName !== record.full_name) return invalid("The confirmation didn't match the repository name.", "confirm"); |
| 337 | await db.batch([ |
| 338 | db.prepare("DELETE FROM events WHERE stream IN (SELECT 'task:' || id FROM tasks WHERE repo_id = ?)").bind(record.id), |
| 339 | db.prepare("DELETE FROM events WHERE stream IN (SELECT 'pull:' || id FROM pulls WHERE repo_id = ?)").bind(record.id), |
| 340 | db.prepare("DELETE FROM repos WHERE id = ?").bind(record.id), |
| 341 | recordEvent(db, policy.actor, repoStream(record.id), "repo.deleted", { name: record.full_name }, now()), |
| 342 | ]); |
| 343 | await env.ARTIFACTS.delete(record.artifacts_name).catch((error) => console.error(`storage ${record.artifacts_name} of deleted repo ${record.full_name} not removed`, error)); |
| 344 | return ok(); |
| 345 | }, |
| 346 | }; |
| 347 | } |