import { openHostedAgents } from "../agents.ts"; import { starterFiles, writeFirstCommit } from "../starter.ts"; import { now, pendingInvite, sha256 } from "../auth.ts"; import type { Grant, Person } from "../contract/actor.ts"; import type { Outcome } from "../contract/common.ts"; import type { Members, NewRepo, NewTask, Refs, Repo, TaskQuery } from "../contract/handles.ts"; import type { Label, NamespaceRef, RepoSummary } from "../contract/views.ts"; import { recordEvent, repoStream } from "../events.ts"; import type { Actor } from "../contract/actor.ts"; import { conflict, firstInvalid, invalid, ok, problem, raise } from "../outcomes.ts"; import { Policy } from "../policy.ts"; import { openNamespaceSecrets } from "./ci.ts"; import { descriptionError, findRepoRecord, findRepoRecordById, namespacePolicy, importUrlError, listRepoRecords, provisionRepo, repoFacts, repoNameError, slugError, toSummary as repoSummary, type Namespace, type ProvisionInput, type RepoRecord } from "../repos.ts"; import * as tasks from "../tasks.ts"; import { openMe } from "./account.ts"; import { adminOverview } from "./admin.ts"; import { adminEmails, type Deps } from "./context.ts"; import { handleTaken } from "./gate.ts"; import { openLabels, openMembers } from "./organization.ts"; import { openRepo } from "./repo.ts"; import { openTask } from "./task.ts"; /** A repository as an agent sees it, for the MCP tools that act through the same rules as the web. */ export function agentRepo(env: Env, ctx: Pick, origin: string, actor: Actor, name: string): Promise { return openRefs({ env, ctx: ctx as ExecutionContext, origin }, new Policy(actor, null), null, []).repo(name); } export function openRefs(deps: Deps, policy: Policy, home: Namespace | null, mine: readonly Namespace[]): Refs { const { env } = deps; const db = env.DB; const actor = policy.actor; const signedIn = (): Person => policy.person ?? raise("sign_in_required", "Sign in to continue."); const member = (): { person: Person; namespace: Namespace } => { const person = signedIn(); if (!home || !policy.member) raise("not_found", "Only members of this namespace can do that."); return { person, namespace: home }; }; const policyFor = (record: RepoRecord): Promise => (record.namespace_id === home?.id ? Promise.resolve(policy) : namespacePolicy(db, policy, record.namespace_id)); async function visibleRepo(name: string): Promise { const record = await findRepoRecord(db, name); if (!record || !(await policyFor(record)).canSeeRepo(repoFacts(record))) raise("not_found", `No repository named "${name}".`); return record; } /** 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. */ async function setUpRepo(name: string, person: { readonly name: string; readonly email: string }): Promise { const record = (await findRepoRecord(db, name))!; const files = starterFiles({ repo: record.full_name, name: record.name, description: record.description, origin: deps.origin, branch: record.default_branch }); const at = now(); 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) })); if (!written.ok) return console.error(`set-up commit not written for ${record.full_name}: ${written.reason}`); await recordEvent(db, actor, repoStream(record.id), "repo.pushed", { updates: [{ ref: `refs/heads/${record.default_branch}`, from: null, to: written.commit }] }, at).run(); } async function provision(input: ProvisionInput, create: (id: string) => Promise, event: "repo.created" | "repo.forked" | "repo.imported", data: Record, owner?: string): Promise> { signedIn(); const target = owner ? mine.find((namespace) => namespace.slug === owner.toLowerCase()) : event === "repo.forked" ? mine[0] : home; if (!target) return invalid("Choose a namespace you belong to.", "owner"); const targetPolicy = target.id === home?.id ? policy : await namespacePolicy(db, policy, target.id); if (!targetPolicy.canCreateRepos()) return invalid(`You can't create repositories in ${target.slug}.`, "owner"); const inputProblem = firstInvalid({ name: repoNameError(input.name), description: descriptionError(input.description) }); if (inputProblem) return inputProblem; const created = await provisionRepo(db, actor, target.id, input, create); if ("error" in created) { return problem(created.conflict ? "conflict" : "unavailable", created.error, created.conflict ? "name" : undefined); } await recordEvent(db, actor, repoStream(created.id), event, { name: input.name, ...data } as never, now()).run(); return ok(repoSummary((await findRepoRecordById(db, created.id))!, targetPolicy, deps.origin)); } const refs: Refs = { viewer: { namespace: home && { slug: home.slug, name: home.name, kind: home.kind }, namespaces: mine.map(({ slug, name, kind }) => ({ slug, name, kind })), person: policy.person, agent: actor.kind === "agent" ? actor.agent : null, can: { createRepos: policy.canCreateRepos(), manageMembers: policy.canManageMembers(), manageCiSecrets: policy.canManageCiSecrets(), manageLabels: policy.canManageLabels(), useTasks: policy.canUseTasks(), viewAdmin: actor.kind === "human" && adminEmails(env).has(actor.person.email.toLowerCase()) }, }, async repos() { if (!home) return []; return (await listRepoRecords(db, home.id)).filter((record) => policy.canSeeRepo(repoFacts(record))).map((record) => repoSummary(record, policy, deps.origin)); }, async repo(name) { const record = await visibleRepo(name); return openRepo(deps, await policyFor(record), record, provision); }, async createRepo(input: NewRepo) { const description = input.description.trim(); const values = { name: input.name.trim(), description, visibility: input.visibility }; if (!input.importFrom) { const outcome = await provision(values, (id) => env.ARTIFACTS.create(id, { description: description || undefined, setDefaultBranch: "main" }), "repo.created", { visibility: input.visibility }, input.owner); if (outcome.ok && input.setUp && policy.person) await setUpRepo(outcome.value.name, policy.person); return outcome; } const url = input.importFrom.trim(); const urlProblem = importUrlError(url); if (urlProblem) return invalid(urlProblem, "importFrom"); return provision({ ...values, importUrl: url }, (id) => env.ARTIFACTS.import({ source: { url }, target: { name: id, opts: { description: description || undefined } } }), "repo.imported", { url }, input.owner); }, async acceptInvitation(token) { const person = signedIn(); if (actor.kind !== "human") raise("not_found", "Only people accept invitations."); const invite = await pendingInvite(db, token); if (!invite) raise("not_found", "This invitation is invalid, has expired, or was already used."); if (invite.email.toLowerCase() !== person.email.toLowerCase()) return invalid(`This invitation is for ${invite.email}. Sign in with that account to accept it.`); const tokenHash = await sha256(token); const at = now(); const [joined] = await db.batch([ db .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 > ?") .bind(person.id, at, tokenHash, at), db.prepare("UPDATE invitations SET status = 'accepted' WHERE token_hash = ? AND status = 'pending'").bind(tokenHash), ]); const namespace = (await db.prepare("SELECT slug, name, kind FROM namespaces WHERE id = ?").bind(invite.namespace_id).first())!; if (joined.meta.changes) { await recordEvent(db, actor, "org", "member.joined", { person: { id: person.id, name: person.name }, role: invite.role }, at).run(); } return ok(namespace); }, async createOrganization(input) { const person = signedIn(); if (actor.kind !== "human") raise("not_found", "Only people create organizations."); const slug = input.slug.trim().toLowerCase(); const name = input.name.trim() || slug; const slugProblem = slugError(slug); if (slugProblem) return invalid(slugProblem, "slug"); if (name.length > 64) return invalid("Display names are at most 64 characters.", "name"); if (await handleTaken(db, slug)) return problem("conflict", `"${slug}" is taken.`, "slug"); const id = crypto.randomUUID(); const at = now(); try { await db.batch([ db.prepare("INSERT INTO namespaces (id, slug, name, kind, created_at) VALUES (?, ?, ?, 'org', ?)").bind(id, slug, name, at), db.prepare("INSERT INTO memberships (namespace_id, user_id, role, created_at) VALUES (?, ?, 'owner', ?)").bind(id, person.id, at), ]); } catch { return problem("conflict", `"${slug}" was just taken.`, "slug"); } return ok({ slug, name, kind: "org" }); }, async tasks(query: TaskQuery) { const { person, namespace } = member(); const repo = query.repo ? await visibleRepo(query.repo) : null; return tasks.listTasks(db, { namespaceId: namespace.id, status: query.status, repoId: repo?.id, label: query.label, assigneeId: query.assignee === "me" ? person.id : query.assignee, cursor: query.page?.cursor, limit: query.page?.limit, }); }, async task(repoName, number) { signedIn(); const repo = await visibleRepo(repoName); const repoPolicy = await policyFor(repo); const record = await tasks.findTaskRecord(db, repo.id, number); if (!record || !repoPolicy.canOpenTask(record.repo_name)) raise("not_found", `No task #${number} in ${repoName}.`); return openTask(deps, repoPolicy, record, visibleRepo); }, async createTask(input: NewTask) { const author = signedIn(); const title = input.title.trim(); const body = input.body.trim(); const textProblem = firstInvalid({ title: tasks.titleError(title), body: tasks.bodyError(body) }); if (textProblem) return textProblem; const repo = await findRepoRecord(db, input.repo); const repoPolicy = repo && (await policyFor(repo)); if (!repo || !repoPolicy?.member || !repoPolicy.canSeeRepo(repoFacts(repo))) return invalid("Choose a repository.", "repo"); if (input.assignee && !(await tasks.memberName(db, repo.id, input.assignee))) return invalid("Choose a member to assign.", "assignee"); const created = await tasks.createTaskRecord(db, actor, { repoId: repo.id, title, body, authorId: author.id, assigneeId: input.assignee, labelIds: input.labels }); const record = (await tasks.findTaskRecord(db, repo.id, created.number))!; const extras = await tasks.taskExtras(db, record.id); return ok(tasks.toSummary(record, extras.labels, extras.comments)); }, async taskChoices() { const { namespace } = member(); const [repos, people, labels] = await Promise.all([ refs.repos(), 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 }>(), db.prepare("SELECT id, name, color, description FROM labels WHERE namespace_id = ? ORDER BY name COLLATE NOCASE").bind(namespace.id).all