248 lines · 13.7 KBRaw
| 1 | import { openHostedAgents } from "../agents.ts"; |
| 2 | import { starterFiles, writeFirstCommit } from "../starter.ts"; |
| 3 | import { now, pendingInvite, sha256 } from "../auth.ts"; |
| 4 | import type { Grant, Person } from "../contract/actor.ts"; |
| 5 | import type { Outcome } from "../contract/common.ts"; |
| 6 | import type { Members, NewRepo, NewTask, Refs, Repo, TaskQuery } from "../contract/handles.ts"; |
| 7 | import type { Label, NamespaceRef, RepoSummary } from "../contract/views.ts"; |
| 8 | import { captureAccountEvent, captureRepositoryEvent } from "../analytics.ts"; |
| 9 | import { recordEvent, repoStream } from "../events.ts"; |
| 10 | import type { Actor } from "../contract/actor.ts"; |
| 11 | import { conflict, firstInvalid, invalid, ok, problem, raise } from "../outcomes.ts"; |
| 12 | import { Policy } from "../policy.ts"; |
| 13 | import { openNamespaceSecrets } from "./ci.ts"; |
| 14 | import { descriptionError, findRepoRecord, findRepoRecordById, namespacePolicy, importUrlError, listRepoRecords, provisionRepo, repoFacts, repoNameError, slugError, toSummary as repoSummary, type Namespace, type ProvisionInput, type RepoRecord } from "../repos.ts"; |
| 15 | import * as tasks from "../tasks.ts"; |
| 16 | import { openMe, openWaitlist } from "./account.ts"; |
| 17 | import { adminEmails, type Deps } from "./context.ts"; |
| 18 | import { handleTaken } from "./gate.ts"; |
| 19 | import { openLabels, openMembers } from "./organization.ts"; |
| 20 | import { openRepo } from "./repo.ts"; |
| 21 | import { openTask } from "./task.ts"; |
| 22 | |
| 23 | /** A repository as an agent sees it, for the MCP tools that act through the same rules as the web. */ |
| 24 | export function agentRepo(env: Env, ctx: Pick<ExecutionContext, "waitUntil">, origin: string, actor: Actor, name: string): Promise<Repo> { |
| 25 | return openRefs({ env, ctx: ctx as ExecutionContext, origin }, new Policy(actor, null), null, []).repo(name); |
| 26 | } |
| 27 | |
| 28 | export function openRefs(deps: Deps, policy: Policy, home: Namespace | null, mine: readonly Namespace[]): Refs { |
| 29 | const { env } = deps; |
| 30 | const db = env.DB; |
| 31 | const actor = policy.actor; |
| 32 | |
| 33 | const signedIn = (): Person => policy.person ?? raise("sign_in_required", "Sign in to continue."); |
| 34 | const member = (): { person: Person; namespace: Namespace } => { |
| 35 | const person = signedIn(); |
| 36 | if (!home || !policy.member) raise("not_found", "Only members of this namespace can do that."); |
| 37 | return { person, namespace: home }; |
| 38 | }; |
| 39 | |
| 40 | const policyFor = (record: RepoRecord): Promise<Policy> => (record.namespace_id === home?.id ? Promise.resolve(policy) : namespacePolicy(db, policy, record.namespace_id)); |
| 41 | |
| 42 | async function visibleRepo(name: string): Promise<RepoRecord> { |
| 43 | const record = await findRepoRecord(db, name); |
| 44 | if (!record || !(await policyFor(record)).canSeeRepo(repoFacts(record))) raise("not_found", `No repository named "${name}".`); |
| 45 | return record; |
| 46 | } |
| 47 | |
| 48 | /** Gives a new, empty repository its first commit: the files that set agents up for refs. A failure leaves it empty, as if not asked. */ |
| 49 | async function setUpRepo(name: string, person: { readonly name: string; readonly email: string }): Promise<void> { |
| 50 | const record = (await findRepoRecord(db, name))!; |
| 51 | const files = starterFiles({ repo: record.full_name, name: record.name, description: record.description, origin: deps.origin }); |
| 52 | const at = now(); |
| 53 | const written = await writeFirstCommit(await env.ARTIFACTS.get(record.artifacts_name), record.default_branch, files, person, at, `Set up ${record.full_name} for agents on refs\n\nDecision: none`).catch((error: unknown) => ({ ok: false as const, reason: String(error) })); |
| 54 | if (!written.ok) return console.error(`set-up commit not written for ${record.full_name}: ${written.reason}`); |
| 55 | await recordEvent(db, actor, repoStream(record.id), "repo.pushed", { updates: [{ ref: `refs/heads/${record.default_branch}`, from: null, to: written.commit }] }, at).run(); |
| 56 | } |
| 57 | |
| 58 | async function provision(input: ProvisionInput, create: (id: string) => Promise<unknown>, event: "repo.created" | "repo.forked" | "repo.imported", data: Record<string, string>, owner?: string): Promise<Outcome<RepoSummary>> { |
| 59 | signedIn(); |
| 60 | const target = owner ? mine.find((namespace) => namespace.slug === owner.toLowerCase()) : event === "repo.forked" ? mine[0] : home; |
| 61 | if (!target) return invalid("Choose a namespace you belong to.", "owner"); |
| 62 | const targetPolicy = target.id === home?.id ? policy : await namespacePolicy(db, policy, target.id); |
| 63 | if (!targetPolicy.canCreateRepos()) return invalid(`You can't create repositories in ${target.slug}.`, "owner"); |
| 64 | const inputProblem = firstInvalid({ name: repoNameError(input.name), description: descriptionError(input.description) }); |
| 65 | if (inputProblem) return inputProblem; |
| 66 | |
| 67 | const created = await provisionRepo(db, actor, target.id, input, create); |
| 68 | const entryPath: "import" | "fork" | "new_project" = event === "repo.imported" ? "import" : event === "repo.forked" ? "fork" : "new_project"; |
| 69 | const measurement = { |
| 70 | namespaceId: target.id, |
| 71 | namespaceKind: target.kind, |
| 72 | visibility: input.visibility, |
| 73 | entryPath, |
| 74 | importUrl: input.importUrl, |
| 75 | }; |
| 76 | if ("error" in created) { |
| 77 | captureRepositoryEvent(env, deps.ctx, actor, { ...measurement, name: "repo.provision_failed", reason: created.conflict ? "conflict" : "storage_unavailable" }); |
| 78 | return problem(created.conflict ? "conflict" : "unavailable", created.error, created.conflict ? "name" : undefined); |
| 79 | } |
| 80 | await recordEvent(db, actor, repoStream(created.id), event, { name: input.name, ...data } as never, now()).run(); |
| 81 | captureRepositoryEvent(env, deps.ctx, actor, { ...measurement, name: event, repoId: created.id }); |
| 82 | return ok(repoSummary((await findRepoRecordById(db, created.id))!, targetPolicy, deps.origin)); |
| 83 | } |
| 84 | |
| 85 | const refs: Refs = { |
| 86 | viewer: { |
| 87 | namespace: home && { slug: home.slug, name: home.name, kind: home.kind }, |
| 88 | namespaces: mine.map(({ slug, name, kind }) => ({ slug, name, kind })), |
| 89 | person: policy.person, |
| 90 | agent: actor.kind === "agent" ? actor.agent : null, |
| 91 | can: { createRepos: policy.canCreateRepos(), manageMembers: policy.canManageMembers(), manageCiSecrets: policy.canManageCiSecrets(), manageLabels: policy.canManageLabels(), useTasks: policy.canUseTasks(), reviewWaitlist: actor.kind === "human" && adminEmails(env).has(actor.person.email.toLowerCase()) }, |
| 92 | }, |
| 93 | |
| 94 | async repos() { |
| 95 | if (!home) return []; |
| 96 | return (await listRepoRecords(db, home.id)).filter((record) => policy.canSeeRepo(repoFacts(record))).map((record) => repoSummary(record, policy, deps.origin)); |
| 97 | }, |
| 98 | |
| 99 | async repo(name) { |
| 100 | const record = await visibleRepo(name); |
| 101 | return openRepo(deps, await policyFor(record), record, provision); |
| 102 | }, |
| 103 | |
| 104 | async createRepo(input: NewRepo) { |
| 105 | const description = input.description.trim(); |
| 106 | const values = { name: input.name.trim(), description, visibility: input.visibility }; |
| 107 | if (!input.importFrom) { |
| 108 | const outcome = await provision(values, (id) => env.ARTIFACTS.create(id, { description: description || undefined, setDefaultBranch: "main" }), "repo.created", { visibility: input.visibility }, input.owner); |
| 109 | if (outcome.ok && input.setUp && policy.person) await setUpRepo(outcome.value.name, policy.person); |
| 110 | return outcome; |
| 111 | } |
| 112 | const url = input.importFrom.trim(); |
| 113 | const urlProblem = importUrlError(url); |
| 114 | if (urlProblem) return invalid(urlProblem, "importFrom"); |
| 115 | return provision({ ...values, importUrl: url }, (id) => env.ARTIFACTS.import({ source: { url }, target: { name: id, opts: { description: description || undefined } } }), "repo.imported", { url }, input.owner); |
| 116 | }, |
| 117 | |
| 118 | async acceptInvitation(token) { |
| 119 | const person = signedIn(); |
| 120 | if (actor.kind !== "human") raise("not_found", "Only people accept invitations."); |
| 121 | const invite = await pendingInvite(db, token); |
| 122 | if (!invite) raise("not_found", "This invitation is invalid, has expired, or was already used."); |
| 123 | if (invite.email.toLowerCase() !== person.email.toLowerCase()) return invalid(`This invitation is for ${invite.email}. Sign in with that account to accept it.`); |
| 124 | const tokenHash = await sha256(token); |
| 125 | const at = now(); |
| 126 | const [joined] = await db.batch([ |
| 127 | db |
| 128 | .prepare("INSERT OR IGNORE INTO memberships (namespace_id, user_id, role, created_at) SELECT namespace_id, ?, role, ? FROM invitations WHERE token_hash = ? AND status = 'pending' AND expires_at > ?") |
| 129 | .bind(person.id, at, tokenHash, at), |
| 130 | db.prepare("UPDATE invitations SET status = 'accepted' WHERE token_hash = ? AND status = 'pending'").bind(tokenHash), |
| 131 | ]); |
| 132 | const namespace = (await db.prepare("SELECT slug, name, kind FROM namespaces WHERE id = ?").bind(invite.namespace_id).first<NamespaceRef>())!; |
| 133 | if (joined.meta.changes) { |
| 134 | await recordEvent(db, actor, "org", "member.joined", { person: { id: person.id, name: person.name }, role: invite.role }, at).run(); |
| 135 | captureAccountEvent(env, deps.ctx, { name: "member.joined", userId: person.id, namespaceId: invite.namespace_id, role: invite.role, joinPath: "existing_account" }); |
| 136 | } |
| 137 | return ok(namespace); |
| 138 | }, |
| 139 | |
| 140 | async createOrganization(input) { |
| 141 | const person = signedIn(); |
| 142 | if (actor.kind !== "human") raise("not_found", "Only people create organizations."); |
| 143 | const slug = input.slug.trim().toLowerCase(); |
| 144 | const name = input.name.trim() || slug; |
| 145 | const slugProblem = slugError(slug); |
| 146 | if (slugProblem) return invalid(slugProblem, "slug"); |
| 147 | if (name.length > 64) return invalid("Display names are at most 64 characters.", "name"); |
| 148 | if (await handleTaken(db, slug)) return problem("conflict", `"${slug}" is taken.`, "slug"); |
| 149 | const id = crypto.randomUUID(); |
| 150 | const at = now(); |
| 151 | try { |
| 152 | await db.batch([ |
| 153 | db.prepare("INSERT INTO namespaces (id, slug, name, kind, created_at) VALUES (?, ?, ?, 'org', ?)").bind(id, slug, name, at), |
| 154 | db.prepare("INSERT INTO memberships (namespace_id, user_id, role, created_at) VALUES (?, ?, 'owner', ?)").bind(id, person.id, at), |
| 155 | ]); |
| 156 | } catch { |
| 157 | return problem("conflict", `"${slug}" was just taken.`, "slug"); |
| 158 | } |
| 159 | return ok({ slug, name, kind: "org" }); |
| 160 | }, |
| 161 | |
| 162 | async tasks(query: TaskQuery) { |
| 163 | const { person, namespace } = member(); |
| 164 | const repo = query.repo ? await visibleRepo(query.repo) : null; |
| 165 | return tasks.listTasks(db, { |
| 166 | namespaceId: namespace.id, |
| 167 | status: query.status, |
| 168 | repoId: repo?.id, |
| 169 | label: query.label, |
| 170 | assigneeId: query.assignee === "me" ? person.id : query.assignee, |
| 171 | cursor: query.page?.cursor, |
| 172 | limit: query.page?.limit, |
| 173 | }); |
| 174 | }, |
| 175 | |
| 176 | async task(repoName, number) { |
| 177 | signedIn(); |
| 178 | const repo = await visibleRepo(repoName); |
| 179 | const repoPolicy = await policyFor(repo); |
| 180 | const record = await tasks.findTaskRecord(db, repo.id, number); |
| 181 | if (!record || !repoPolicy.canOpenTask(record.repo_name)) raise("not_found", `No task #${number} in ${repoName}.`); |
| 182 | return openTask(deps, repoPolicy, record, visibleRepo); |
| 183 | }, |
| 184 | |
| 185 | async createTask(input: NewTask) { |
| 186 | const author = signedIn(); |
| 187 | const title = input.title.trim(); |
| 188 | const body = input.body.trim(); |
| 189 | const textProblem = firstInvalid({ title: tasks.titleError(title), body: tasks.bodyError(body) }); |
| 190 | if (textProblem) return textProblem; |
| 191 | |
| 192 | const repo = await findRepoRecord(db, input.repo); |
| 193 | const repoPolicy = repo && (await policyFor(repo)); |
| 194 | if (!repo || !repoPolicy?.member || !repoPolicy.canSeeRepo(repoFacts(repo))) return invalid("Choose a repository.", "repo"); |
| 195 | if (input.assignee && !(await tasks.memberName(db, repo.id, input.assignee))) return invalid("Choose a member to assign.", "assignee"); |
| 196 | |
| 197 | const created = await tasks.createTaskRecord(db, actor, { repoId: repo.id, title, body, authorId: author.id, assigneeId: input.assignee, labelIds: input.labels }); |
| 198 | const record = (await tasks.findTaskRecord(db, repo.id, created.number))!; |
| 199 | const extras = await tasks.taskExtras(db, record.id); |
| 200 | return ok(tasks.toSummary(record, extras.labels, extras.comments)); |
| 201 | }, |
| 202 | |
| 203 | async taskChoices() { |
| 204 | const { namespace } = member(); |
| 205 | const [repos, people, labels] = await Promise.all([ |
| 206 | refs.repos(), |
| 207 | db.prepare("SELECT u.id, u.name FROM users u JOIN memberships m ON m.user_id = u.id WHERE m.namespace_id = ? ORDER BY u.name COLLATE NOCASE").bind(namespace.id).all<{ id: string; name: string }>(), |
| 208 | db.prepare("SELECT id, name, color, description FROM labels WHERE namespace_id = ? ORDER BY name COLLATE NOCASE").bind(namespace.id).all<Label>(), |
| 209 | ]); |
| 210 | return { repos: repos.map((repo) => ({ id: repo.name, name: repo.name })), people: people.results, labels: labels.results }; |
| 211 | }, |
| 212 | |
| 213 | async labels() { |
| 214 | signedIn(); |
| 215 | return openLabels(db, policy, member().namespace.id); |
| 216 | }, |
| 217 | |
| 218 | async me() { |
| 219 | return openMe(env, signedIn()); |
| 220 | }, |
| 221 | |
| 222 | async namespaceSecrets() { |
| 223 | if (!policy.canManageCiSecrets()) raise("not_found", "Only owners and admins can manage CI secrets."); |
| 224 | return openNamespaceSecrets(env, policy, member().namespace); |
| 225 | }, |
| 226 | |
| 227 | async namespaceAgents() { |
| 228 | if (!policy.canManageCiSecrets()) raise("not_found", "Only owners and admins can manage agents."); |
| 229 | return openHostedAgents(env, policy, member().namespace.id, null, true); |
| 230 | }, |
| 231 | |
| 232 | async members() { |
| 233 | if (!policy.canManageMembers()) raise("not_found", "Members are managed by admins."); |
| 234 | return openMembers(deps, policy, member().namespace); |
| 235 | }, |
| 236 | |
| 237 | async waitlist() { |
| 238 | const person = signedIn(); |
| 239 | if (actor.kind !== "human" || !adminEmails(env).has(person.email.toLowerCase())) raise("not_found", "The waitlist is for admins."); |
| 240 | return openWaitlist(env, deps.ctx); |
| 241 | }, |
| 242 | |
| 243 | attenuate(grant: Grant) { |
| 244 | return openRefs(deps, policy.narrowed(grant), home, mine); |
| 245 | }, |
| 246 | }; |
| 247 | return refs; |
| 248 | } |