Skip to content
refs
420 lines · 18.1 KBRaw
1import type { Grant, Person, Role } from "./actor.ts";
2import type { Id, Outcome, Page, PageRequest } from "./common.ts";
3import type { CiSettings, NamespaceSecrets, RepoCi } from "./ci.ts";
4import type { TimelineItem } from "./events.ts";
5import type {
6 AccessToken,
7 AgentConsentView,
8 AgentGrant,
9 BranchSummary,
10 Choice,
11 ChangeSet,
12 CodeMapState,
13 CodeMapSummary,
14 PullCodeMap,
15 CommitDetail,
16 CommitSummary,
17 LineRange,
18 Mergeability,
19 PullCounts,
20 PullBranch,
21 PullDetail,
22 PullSummary,
23 File,
24 Invitation,
25 Label,
26 LabelColor,
27 LabelWithUsage,
28 LastChanges,
29 Location,
30 Member,
31 MentionState,
32 OnlineAgent,
33 PermissionRequest,
34 Org,
35 RawFile,
36 RefList,
37 ReviewThread,
38 RepoSummary,
39 TaskCounts,
40 TaskDetail,
41 TaskStatus,
42 TaskSummary,
43 Tree,
44 Viewer,
45 Visibility,
46 AdminOverview,
47 NamespaceRef,
48 HostedAgent,
49 AgentRunView,
50} from "./views.ts";
51
52/**
53 * The backend's entire public surface. Everything a caller can do starts here, and
54 * every permission check happens behind it: a handle only exists if the actor may use it.
55 */
56export interface Backend {
57 /**
58 * Resolves the request's session cookie or access token, then opens a handle bound to that actor. Anonymous requests get an anonymous handle.
59 * Namespace-wide work (repositories, tasks, labels, members) happens in `namespace`, or in the viewer's own namespace when it is omitted.
60 */
61 refs(request: Request, namespace?: string): Promise<Refs>;
62 /** Operations that happen before there is a signed-in actor. */
63 gate(): Gate;
64 /** Serves a Git smart-HTTP request, or returns null when the request is not a Git URL. */
65 git(request: Request): Promise<Response | null>;
66 /** Serves a ref protocol request under `/api/`, or returns null for any other URL. */
67 api(request: Request): Promise<Response | null>;
68 /** Upgrades `/<repo>/live` to a socket on the repository's hub, or returns null for any other request. */
69 live(request: Request): Promise<Response | null>;
70 /** The OAuth consent step for an agent client, such as Claude Code or Codex, asking to act for the signed-in human. */
71 agentConsent(request: Request): AgentConsent;
72}
73
74/** A consent step either continues, or ends in a redirect back to the client. Send `headers` with the response. */
75export type ConsentStep<T> = Outcome<T | { readonly redirectTo: string; readonly headers: Headers }>;
76
77export interface AgentConsent {
78 /** Throws `sign_in_required` unless a human is signed in with a browser session. */
79 begin(): Promise<ConsentStep<{ readonly view: AgentConsentView; readonly headers: Headers }>>;
80 approve(handle: string): Promise<ConsentStep<{ readonly redirectTo: string; readonly headers: Headers }>>;
81 deny(handle: string): Promise<ConsentStep<{ readonly redirectTo: string; readonly headers: Headers }>>;
82}
83
84export interface Session {
85 readonly token: string;
86 readonly maxAge: number;
87}
88
89export interface SignUpInput {
90 readonly name: string;
91 /** The person's own namespace, created with the account. */
92 readonly handle: string;
93 readonly email: string;
94 readonly password: string;
95 /** The client address, used to rate-limit attempts. */
96 readonly ip: string;
97}
98
99export interface SignInInput {
100 readonly email: string;
101 readonly password: string;
102 /** The client address, used to rate-limit attempts. */
103 readonly ip: string;
104}
105
106export interface Gate {
107 /** Creates the account and its namespace, and signs the person in. */
108 signUp(input: SignUpInput): Promise<Outcome<Session>>;
109 signIn(input: SignInInput): Promise<Outcome<Session>>;
110 /** Emails a one-hour reset link when the address has an account. Succeeds either way, so it does not reveal who has an account. */
111 requestPasswordReset(input: { readonly email: string; readonly ip: string }): Promise<Outcome>;
112 /** Sets a new password from a reset link, ends every other session, and signs the person in. The link works once. */
113 resetPassword(input: { readonly token: string; readonly password: string }): Promise<Outcome<Session>>;
114 signOut(sessionToken: string): Promise<void>;
115 /** Throws `not_found` when the token is unknown, used or expired. */
116 invitation(token: string): Promise<PendingInvitation>;
117}
118
119export interface PendingInvitation {
120 readonly org: Org;
121 readonly email: string;
122 readonly role: Role;
123 /** True when the invited email already has an account, which joins by signing in and calling `Refs.acceptInvitation`. */
124 readonly existingAccount: boolean;
125 /** Creates the account with its username and personal namespace, then joins the inviting namespace. */
126 accept(input: { readonly name: string; readonly handle: string; readonly password: string }): Promise<Outcome<Session>>;
127}
128
129export interface NewRepo {
130 readonly name: string;
131 readonly description: string;
132 readonly visibility: Visibility;
133 /** Copy an existing public HTTPS Git repository instead of starting empty. */
134 readonly importFrom?: string;
135 /** Without `importFrom`: start with a first commit of AGENTS.md, CLAUDE.md and README.md that set agents up for refs, instead of empty. */
136 readonly setUp?: boolean;
137 /** The slug of a namespace the viewer belongs to. Defaults to the handle's namespace for new repositories, and to the viewer's own account for forks. */
138 readonly owner?: string;
139}
140
141export interface NewOrganization {
142 readonly slug: string;
143 readonly name: string;
144}
145
146export interface TaskQuery {
147 readonly status: TaskStatus;
148 readonly repo?: string;
149 readonly label?: string;
150 readonly assignee?: "me" | Id;
151 readonly page?: PageRequest;
152}
153
154export interface NewTask {
155 readonly title: string;
156 readonly body: string;
157 readonly repo: string;
158 readonly assignee: Id | null;
159 readonly labels: readonly Id[];
160}
161
162/**
163 * Everything the current actor can reach. Anonymous actors can read public repositories
164 * and nothing else; any method that needs more throws `sign_in_required`.
165 */
166export interface Refs {
167 readonly viewer: Viewer;
168 repos(): Promise<RepoSummary[]>;
169 /** Throws `not_found` when the repository is missing or the actor may not see it. */
170 repo(name: string): Promise<Repo>;
171 createRepo(input: NewRepo): Promise<Outcome<RepoSummary>>;
172 /** Creates an organization owned by the signed-in person. Its slug shares one space with usernames. */
173 createOrganization(input: NewOrganization): Promise<Outcome<NamespaceRef>>;
174 /** Joins the invitation's namespace as the signed-in person, whose email must be the invited one. Throws `not_found` when the token is unknown, used or expired. */
175 acceptInvitation(token: string): Promise<Outcome<NamespaceRef>>;
176 tasks(query: TaskQuery): Promise<{ readonly page: Page<TaskSummary>; readonly counts: TaskCounts }>;
177 /**
178 * Throws `not_found` when the task is missing or outside the actor's grant. A task that was
179 * transferred is still found by its old repository and number; `detail` then holds its
180 * current location, so callers can redirect.
181 */
182 task(repo: string, number: number): Promise<Task>;
183 createTask(input: NewTask): Promise<Outcome<TaskSummary>>;
184 /** The repositories, people and labels a task can be linked to. */
185 taskChoices(): Promise<{ readonly repos: Choice[]; readonly people: Choice[]; readonly labels: Label[] }>;
186 labels(): Promise<Labels>;
187 /** Throws `sign_in_required` for anonymous actors. */
188 me(): Promise<Me>;
189 /** Throws `not_found` unless the actor may manage members. */
190 members(): Promise<Members>;
191 /** Usage across the whole service. Only the service's admins (ADMIN_EMAILS) get it; everyone else gets `not_found`. */
192 adminOverview(): Promise<AdminOverview>;
193 /** Throws `not_found` unless the actor is an owner or admin of the namespace. */
194 namespaceSecrets(): Promise<NamespaceSecrets>;
195 namespaceAgents(): Promise<HostedAgents>;
196 /** A narrower handle for the same actor. Grants only ever intersect, so this can never widen access. */
197 attenuate(grant: Grant): Refs;
198}
199
200export type RepoHome =
201 | { readonly kind: "preparing" }
202 | { readonly kind: "empty" }
203 | { readonly kind: "tree"; readonly refs: RefList; readonly tree: Tree };
204
205/**
206 * One repository the actor can see. Paths are passed as the URL segments after the view
207 * (for example `["feature", "x", "src", "app.ts"]`); the handle works out which part is
208 * the branch, tag or commit and which part is the path.
209 */
210export interface Repo {
211 readonly summary: RepoSummary;
212 home(): Promise<RepoHome>;
213 refs(): Promise<RefList>;
214 /** Every branch, the default branch first, then the newest commit first. */
215 branches(): Promise<BranchSummary[]>;
216 /** Deletes a branch. Refused for the default branch, and while an open pull request or an agent uses the branch. */
217 deleteBranch(name: string): Promise<Outcome>;
218 /** Each throws `not_found` when the ref or path does not exist. */
219 tree(at: readonly string[]): Promise<Tree>;
220 file(at: readonly string[]): Promise<File>;
221 raw(at: readonly string[]): Promise<RawFile>;
222 history(at: readonly string[], page?: PageRequest): Promise<{ readonly location: Location; readonly page: Page<CommitSummary> }>;
223 lastChanges(at: readonly string[]): Promise<LastChanges>;
224 /** What merging `head` into `base` would change. Both are branch names. */
225 compare(base: string, head: string): Promise<ChangeSet>;
226 pulls(query: PullQuery): Promise<{ readonly items: PullSummary[]; readonly counts: PullCounts }>;
227 /** Throws `not_found` when the pull request is missing or outside the actor's grant. */
228 pull(number: number): Promise<Pull>;
229 openPull(input: NewPull): Promise<Outcome<PullSummary>>;
230 commit(hash: string): Promise<CommitDetail>;
231 /** Whether the code map at a branch, a tag or a commit (the default branch when `ref` is absent) is ready. Starts building it when it is not. Throws `not_found` when the ref does not exist. */
232 codeMap(ref?: string): Promise<{ readonly ref: string; readonly map: CodeMapSummary }>;
233 /** The full code map of one commit. Commits never change, so a ready map can be cached for good. */
234 codeGraph(commit: string): Promise<CodeMapState>;
235 /** Agent sessions connected to this repository right now, idle or on a branch. Empty for anonymous viewers. */
236 agents(): Promise<OnlineAgent[]>;
237 /** Tool approvals agents on this repository are waiting for. */
238 permissions(): Promise<PermissionRequest[]>;
239 /** The newest event on this repository, and on one of its tasks if given. Changes whenever a page showing them should refresh. */
240 latest(task?: number): Promise<number>;
241 /** Answers one; only the agent's own human may. */
242 decidePermission(session: Id, requestId: string, behavior: "allow" | "deny"): Promise<Outcome>;
243 fork(input: Omit<NewRepo, "importFrom">): Promise<Outcome<RepoSummary>>;
244 /** Throws `not_found` unless the actor may administer this repository. */
245 settings(): Promise<RepoSettings>;
246 ci(): RepoCi;
247 hostedAgents(): Promise<HostedAgents>;
248 /** The recent runs of hosted agents here. `open` also loads the steps of that finished run. */
249 agentRuns(open: Id | null): Promise<AgentRunView[]>;
250}
251
252export interface RepoSettings {
253 readonly description: string;
254 readonly visibility: Visibility;
255 update(changes: { readonly description?: string; readonly visibility?: Visibility }): Promise<Outcome>;
256 /** Permanently deletes the repository and its history. `confirmName` must equal the repository's name. */
257 delete(confirmName: string): Promise<Outcome>;
258 readonly ci: CiSettings;
259}
260
261/**
262 * A task is a plain tracker item. It has no link to agent sessions, branches, pull requests or decisions:
263 * agents do not take tasks, and nothing outside the task changes it.
264 */
265export interface Task {
266 readonly detail: TaskDetail;
267 timeline(): Promise<TimelineItem[]>;
268 /** Adds a comment. With `then`, also closes or reopens the task in the same change. */
269 comment(body: string, then?: TaskStatus): Promise<Outcome>;
270 setStatus(status: TaskStatus): Promise<Outcome>;
271 rename(title: string): Promise<Outcome>;
272 describe(body: string): Promise<Outcome>;
273 assign(person: Id | null): Promise<Outcome>;
274 /** Moves the task to another repository, where it takes the next number. Its old address keeps resolving to it. */
275 transfer(repo: string): Promise<Outcome<{ readonly repo: string; readonly number: number }>>;
276 setLabels(labels: readonly Id[]): Promise<Outcome>;
277 editComment(comment: Id, body: string): Promise<Outcome>;
278 deleteComment(comment: Id): Promise<Outcome>;
279}
280
281export interface PullQuery {
282 /** `closed` lists closed and merged pull requests. */
283 readonly status: "open" | "closed";
284}
285
286export interface NewPull {
287 readonly title: string;
288 readonly body: string;
289 readonly base: string;
290 readonly head: string;
291}
292
293export interface ReviewCommentInput {
294 readonly revision: string;
295 readonly path: string;
296 readonly range: LineRange;
297 readonly body: string;
298 readonly assign?: boolean;
299}
300
301export interface SteerInput {
302 readonly revision: string;
303 readonly decision: string;
304 readonly body: string;
305 readonly assign?: boolean;
306}
307
308const REVIEW_VERDICTS = ["comment", "approve", "request-changes"] as const;
309export type ReviewVerdict = (typeof REVIEW_VERDICTS)[number];
310
311export function isReviewVerdict(value: string): value is ReviewVerdict {
312 return (REVIEW_VERDICTS as readonly string[]).includes(value);
313}
314
315export interface ReviewInput {
316 readonly revision: string;
317 readonly verdict: ReviewVerdict;
318 readonly body: string;
319}
320
321export interface BranchInput {
322 /** The commit the new branch starts at: the pull request's merge base or one of its commits. */
323 readonly from: string;
324 readonly title: string;
325 /** What the agents should try from there. Mentioned agents receive it, and take the new branch with `assign`. */
326 readonly instruction: string;
327 readonly assign?: boolean;
328}
329
330export interface Pull {
331 readonly detail: PullDetail;
332 timeline(): Promise<TimelineItem[]>;
333 /** While open, the live branches; once merged or closed, the commits they pointed at then. Throws `not_found` when an open pull request's branch is gone. */
334 changes(): Promise<ChangeSet>;
335 /** The head commit's code map and the lines each changed file changed, so the map can mark them. */
336 codeMap(): Promise<PullCodeMap>;
337 /**
338 * With `then`, also closes or reopens the pull request in the same change. Agents it mentions receive it;
339 * with `assign`, they also take the pull request's head branch.
340 */
341 comment(body: string, then?: "open" | "closed", assign?: boolean): Promise<Outcome>;
342 /** Starts a review thread on a range of lines in one file of the diff at `revision`. Fails when `revision` is no longer the head. */
343 reviewComment(input: ReviewCommentInput): Promise<Outcome<{ readonly thread: number }>>;
344 /** Starts a review thread on one of the decision records in the diff at `revision`. */
345 steer(input: SteerInput): Promise<Outcome<{ readonly thread: number }>>;
346 /** A human's verdict on the diff at `revision`, posted as a comment. Fails when `revision` is no longer the head. */
347 review(input: ReviewInput): Promise<Outcome>;
348 threads(): Promise<ReviewThread[]>;
349 /**
350 * Explores another path from a point in this pull request's reasoning: a new branch, named from the title, that
351 * starts at `from`, and a pull request for it into the same base. Only people with write access may branch.
352 */
353 branch(input: BranchInput): Promise<Outcome<{ readonly pull: number }>>;
354 /** Pull requests branched from this one. */
355 branches(): Promise<PullBranch[]>;
356 /** Agents mentioned in the reply receive it with the thread's lines; their answer comes back into the thread. */
357 replyToThread(thread: number, body: string, assign?: boolean): Promise<Outcome>;
358 mergeability(): Promise<Mergeability>;
359 /**
360 * Merges the head into the base with a merge commit, as the person merging. Only a human with write access may
361 * merge. Fails without changing anything when files conflict or the base moved since the check.
362 */
363 merge(): Promise<Outcome<{ readonly commit: string }>>;
364 /** Only a human with write access may resolve or reopen a thread. */
365 resolveThread(thread: number): Promise<Outcome>;
366 reopenThread(thread: number): Promise<Outcome>;
367 /** Delivery state of agent mentions made in this pull request's comments. */
368 mentions(): Promise<MentionState[]>;
369 /** Tool approvals agents working on the head branch are waiting for. */
370 permissions(): Promise<PermissionRequest[]>;
371 setStatus(status: "open" | "closed"): Promise<Outcome>;
372 rename(title: string): Promise<Outcome>;
373}
374
375export interface LabelInput {
376 readonly name: string;
377 readonly color: LabelColor;
378 readonly description: string;
379}
380
381export interface Labels {
382 list(): Promise<LabelWithUsage[]>;
383 create(input: LabelInput): Promise<Outcome<Label>>;
384 update(label: Id, input: LabelInput): Promise<Outcome<Label>>;
385 delete(label: Id): Promise<Outcome>;
386}
387
388export interface Me {
389 readonly person: Person;
390 tokens(): Promise<AccessToken[]>;
391 /** `secret` is returned once and never stored in readable form. */
392 createToken(name: string): Promise<Outcome<{ readonly token: AccessToken; readonly secret: string }>>;
393 revokeToken(token: Id): Promise<Outcome>;
394 /** Agent clients this person has authorized over OAuth. */
395 agentGrants(): Promise<AgentGrant[]>;
396 revokeAgentGrant(grant: Id): Promise<Outcome>;
397}
398
399/** The hosted agents of a namespace or a repository. Everyone who can see them can mention them; admins change them. */
400export interface HostedAgents {
401 readonly canEdit: boolean;
402 list(): Promise<HostedAgent[]>;
403 /**
404 * Adds or changes an agent at this level. With a provider, the key is tested with one small request first, and a key
405 * that fails is not stored. An empty key keeps the saved key of the same provider.
406 */
407 save(input: { readonly handle: string; readonly description: string; readonly instructions: string; readonly provider: string; readonly model: string; readonly key: string }): Promise<Outcome>;
408 remove(handle: string): Promise<Outcome>;
409}
410
411export interface Members {
412 /** The roles this actor may hand out. */
413 readonly invitableRoles: readonly Role[];
414 list(): Promise<Member[]>;
415 invitations(): Promise<Invitation[]>;
416 /** `link` is returned once; only its hash is stored. */
417 /** `invitee` is an email address or the username of an existing person. */
418 invite(input: { readonly invitee: string; readonly role: Role }): Promise<Outcome<{ readonly invitation: Invitation; readonly link: string }>>;
419 revokeInvitation(invitation: Id): Promise<Outcome>;
420}