Skip to content
refs
History
422 lines · 17.9 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 WaitlistEntry,
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 namespace the person wants, created when they leave the waitlist. */
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 /** Admins get a session and their namespace at once; everyone else joins the waitlist and gets no session. */
108 signUp(input: SignUpInput): Promise<Outcome<{ readonly session: Session | null }>>;
109 signIn(input: SignInInput): Promise<Outcome<Session>>;
110 signOut(sessionToken: string): Promise<void>;
111 /** Throws `not_found` when the token is unknown, used or expired. */
112 invitation(token: string): Promise<PendingInvitation>;
113}
114
115export interface PendingInvitation {
116 readonly org: Org;
117 readonly email: string;
118 readonly role: Role;
119 /** True when the invited email already has an account, which joins by signing in and calling `Refs.acceptInvitation`. */
120 readonly existingAccount: boolean;
121 /** Creates the account with its username and personal namespace, then joins the inviting namespace. */
122 accept(input: { readonly name: string; readonly handle: string; readonly password: string }): Promise<Outcome<Session>>;
123}
124
125export interface NewRepo {
126 readonly name: string;
127 readonly description: string;
128 readonly visibility: Visibility;
129 /** Copy an existing public HTTPS Git repository instead of starting empty. */
130 readonly importFrom?: string;
131 /** Without `importFrom`: start with a first commit of AGENTS.md, CLAUDE.md and README.md that set agents up for refs, instead of empty. */
132 readonly setUp?: boolean;
133 /** 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. */
134 readonly owner?: string;
135}
136
137export interface NewOrganization {
138 readonly slug: string;
139 readonly name: string;
140}
141
142export interface TaskQuery {
143 readonly status: TaskStatus;
144 readonly repo?: string;
145 readonly label?: string;
146 readonly assignee?: "me" | Id;
147 readonly page?: PageRequest;
148}
149
150export interface NewTask {
151 readonly title: string;
152 readonly body: string;
153 readonly repo: string;
154 readonly assignee: Id | null;
155 readonly labels: readonly Id[];
156}
157
158/**
159 * Everything the current actor can reach. Anonymous actors can read public repositories
160 * and nothing else; any method that needs more throws `sign_in_required`.
161 */
162export interface Refs {
163 readonly viewer: Viewer;
164 repos(): Promise<RepoSummary[]>;
165 /** Throws `not_found` when the repository is missing or the actor may not see it. */
166 repo(name: string): Promise<Repo>;
167 createRepo(input: NewRepo): Promise<Outcome<RepoSummary>>;
168 /** Creates an organization owned by the signed-in person. Its slug shares one space with usernames. */
169 createOrganization(input: NewOrganization): Promise<Outcome<NamespaceRef>>;
170 /** 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. */
171 acceptInvitation(token: string): Promise<Outcome<NamespaceRef>>;
172 tasks(query: TaskQuery): Promise<{ readonly page: Page<TaskSummary>; readonly counts: TaskCounts }>;
173 /**
174 * Throws `not_found` when the task is missing or outside the actor's grant. A task that was
175 * transferred is still found by its old repository and number; `detail` then holds its
176 * current location, so callers can redirect.
177 */
178 task(repo: string, number: number): Promise<Task>;
179 createTask(input: NewTask): Promise<Outcome<TaskSummary>>;
180 /** The repositories, people and labels a task can be linked to. */
181 taskChoices(): Promise<{ readonly repos: Choice[]; readonly people: Choice[]; readonly labels: Label[] }>;
182 labels(): Promise<Labels>;
183 /** Throws `sign_in_required` for anonymous actors. */
184 me(): Promise<Me>;
185 /** Throws `not_found` unless the actor may manage members. */
186 members(): Promise<Members>;
187 /** People waiting for an account. Only the service's admins (ADMIN_EMAILS) get this handle. */
188 waitlist(): Promise<Waitlist>;
189 /** Throws `not_found` unless the actor is an owner or admin of the namespace. */
190 namespaceSecrets(): Promise<NamespaceSecrets>;
191 namespaceAgents(): Promise<HostedAgents>;
192 /** A narrower handle for the same actor. Grants only ever intersect, so this can never widen access. */
193 attenuate(grant: Grant): Refs;
194}
195
196export type RepoHome =
197 | { readonly kind: "preparing" }
198 | { readonly kind: "empty" }
199 | { readonly kind: "tree"; readonly refs: RefList; readonly tree: Tree };
200
201/**
202 * One repository the actor can see. Paths are passed as the URL segments after the view
203 * (for example `["feature", "x", "src", "app.ts"]`); the handle works out which part is
204 * the branch, tag or commit and which part is the path.
205 */
206export interface Repo {
207 readonly summary: RepoSummary;
208 home(): Promise<RepoHome>;
209 refs(): Promise<RefList>;
210 /** Every branch, the default branch first, then the newest commit first. */
211 branches(): Promise<BranchSummary[]>;
212 /** Deletes a branch. Refused for the default branch, and while an open pull request or an agent uses the branch. */
213 deleteBranch(name: string): Promise<Outcome>;
214 /** Each throws `not_found` when the ref or path does not exist. */
215 tree(at: readonly string[]): Promise<Tree>;
216 file(at: readonly string[]): Promise<File>;
217 raw(at: readonly string[]): Promise<RawFile>;
218 history(at: readonly string[], page?: PageRequest): Promise<{ readonly location: Location; readonly page: Page<CommitSummary> }>;
219 lastChanges(at: readonly string[]): Promise<LastChanges>;
220 /** What merging `head` into `base` would change. Both are branch names. */
221 compare(base: string, head: string): Promise<ChangeSet>;
222 pulls(query: PullQuery): Promise<{ readonly items: PullSummary[]; readonly counts: PullCounts }>;
223 /** Throws `not_found` when the pull request is missing or outside the actor's grant. */
224 pull(number: number): Promise<Pull>;
225 openPull(input: NewPull): Promise<Outcome<PullSummary>>;
226 commit(hash: string): Promise<CommitDetail>;
227 /** 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. */
228 codeMap(ref?: string): Promise<{ readonly ref: string; readonly map: CodeMapSummary }>;
229 /** The full code map of one commit. Commits never change, so a ready map can be cached for good. */
230 codeGraph(commit: string): Promise<CodeMapState>;
231 /** Agent sessions connected to this repository right now, idle or on a branch. Empty for anonymous viewers. */
232 agents(): Promise<OnlineAgent[]>;
233 /** Tool approvals agents on this repository are waiting for. */
234 permissions(): Promise<PermissionRequest[]>;
235 /** The newest event on this repository, and on one of its tasks if given. Changes whenever a page showing them should refresh. */
236 latest(task?: number): Promise<number>;
237 /** Answers one; only the agent's own human may. */
238 decidePermission(session: Id, requestId: string, behavior: "allow" | "deny"): Promise<Outcome>;
239 fork(input: Omit<NewRepo, "importFrom">): Promise<Outcome<RepoSummary>>;
240 /** Throws `not_found` unless the actor may administer this repository. */
241 settings(): Promise<RepoSettings>;
242 ci(): RepoCi;
243 hostedAgents(): Promise<HostedAgents>;
244 /** The recent runs of hosted agents here. `open` also loads the steps of that finished run. */
245 agentRuns(open: Id | null): Promise<AgentRunView[]>;
246}
247
248export interface RepoSettings {
249 readonly description: string;
250 readonly visibility: Visibility;
251 update(changes: { readonly description?: string; readonly visibility?: Visibility }): Promise<Outcome>;
252 /** Permanently deletes the repository and its history. `confirmName` must equal the repository's name. */
253 delete(confirmName: string): Promise<Outcome>;
254 readonly ci: CiSettings;
255}
256
257/**
258 * A task is a plain tracker item. It has no link to agent sessions, branches, pull requests or decisions:
259 * agents do not take tasks, and nothing outside the task changes it.
260 */
261export interface Task {
262 readonly detail: TaskDetail;
263 timeline(): Promise<TimelineItem[]>;
264 /** Adds a comment. With `then`, also closes or reopens the task in the same change. */
265 comment(body: string, then?: TaskStatus): Promise<Outcome>;
266 setStatus(status: TaskStatus): Promise<Outcome>;
267 rename(title: string): Promise<Outcome>;
268 describe(body: string): Promise<Outcome>;
269 assign(person: Id | null): Promise<Outcome>;
270 /** Moves the task to another repository, where it takes the next number. Its old address keeps resolving to it. */
271 transfer(repo: string): Promise<Outcome<{ readonly repo: string; readonly number: number }>>;
272 setLabels(labels: readonly Id[]): Promise<Outcome>;
273 editComment(comment: Id, body: string): Promise<Outcome>;
274 deleteComment(comment: Id): Promise<Outcome>;
275}
276
277export interface PullQuery {
278 /** `closed` lists closed and merged pull requests. */
279 readonly status: "open" | "closed";
280}
281
282export interface NewPull {
283 readonly title: string;
284 readonly body: string;
285 readonly base: string;
286 readonly head: string;
287}
288
289export interface ReviewCommentInput {
290 readonly revision: string;
291 readonly path: string;
292 readonly range: LineRange;
293 readonly body: string;
294 readonly assign?: boolean;
295}
296
297export interface SteerInput {
298 readonly revision: string;
299 readonly decision: string;
300 readonly body: string;
301 readonly assign?: boolean;
302}
303
304const REVIEW_VERDICTS = ["comment", "approve", "request-changes"] as const;
305export type ReviewVerdict = (typeof REVIEW_VERDICTS)[number];
306
307export function isReviewVerdict(value: string): value is ReviewVerdict {
308 return (REVIEW_VERDICTS as readonly string[]).includes(value);
309}
310
311export interface ReviewInput {
312 readonly revision: string;
313 readonly verdict: ReviewVerdict;
314 readonly body: string;
315}
316
317export interface BranchInput {
318 /** The commit the new branch starts at: the pull request's merge base or one of its commits. */
319 readonly from: string;
320 readonly title: string;
321 /** What the agents should try from there. Mentioned agents receive it, and take the new branch with `assign`. */
322 readonly instruction: string;
323 readonly assign?: boolean;
324}
325
326export interface Pull {
327 readonly detail: PullDetail;
328 timeline(): Promise<TimelineItem[]>;
329 /** 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. */
330 changes(): Promise<ChangeSet>;
331 /** The head commit's code map and the lines each changed file changed, so the map can mark them. */
332 codeMap(): Promise<PullCodeMap>;
333 /**
334 * With `then`, also closes or reopens the pull request in the same change. Agents it mentions receive it;
335 * with `assign`, they also take the pull request's head branch.
336 */
337 comment(body: string, then?: "open" | "closed", assign?: boolean): Promise<Outcome>;
338 /** 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. */
339 reviewComment(input: ReviewCommentInput): Promise<Outcome<{ readonly thread: number }>>;
340 /** Starts a review thread on one of the decision records in the diff at `revision`. */
341 steer(input: SteerInput): Promise<Outcome<{ readonly thread: number }>>;
342 /** A human's verdict on the diff at `revision`, posted as a comment. Fails when `revision` is no longer the head. */
343 review(input: ReviewInput): Promise<Outcome>;
344 threads(): Promise<ReviewThread[]>;
345 /**
346 * Explores another path from a point in this pull request's reasoning: a new branch, named from the title, that
347 * starts at `from`, and a pull request for it into the same base. Only people with write access may branch.
348 */
349 branch(input: BranchInput): Promise<Outcome<{ readonly pull: number }>>;
350 /** Pull requests branched from this one. */
351 branches(): Promise<PullBranch[]>;
352 /** Agents mentioned in the reply receive it with the thread's lines; their answer comes back into the thread. */
353 replyToThread(thread: number, body: string, assign?: boolean): Promise<Outcome>;
354 mergeability(): Promise<Mergeability>;
355 /**
356 * Merges the head into the base with a merge commit, as the person merging. Only a human with write access may
357 * merge. Fails without changing anything when files conflict or the base moved since the check.
358 */
359 merge(): Promise<Outcome<{ readonly commit: string }>>;
360 /** Only a human with write access may resolve or reopen a thread. */
361 resolveThread(thread: number): Promise<Outcome>;
362 reopenThread(thread: number): Promise<Outcome>;
363 /** Delivery state of agent mentions made in this pull request's comments. */
364 mentions(): Promise<MentionState[]>;
365 /** Tool approvals agents working on the head branch are waiting for. */
366 permissions(): Promise<PermissionRequest[]>;
367 setStatus(status: "open" | "closed"): Promise<Outcome>;
368 rename(title: string): Promise<Outcome>;
369}
370
371export interface LabelInput {
372 readonly name: string;
373 readonly color: LabelColor;
374 readonly description: string;
375}
376
377export interface Labels {
378 list(): Promise<LabelWithUsage[]>;
379 create(input: LabelInput): Promise<Outcome<Label>>;
380 update(label: Id, input: LabelInput): Promise<Outcome<Label>>;
381 delete(label: Id): Promise<Outcome>;
382}
383
384export interface Me {
385 readonly person: Person;
386 tokens(): Promise<AccessToken[]>;
387 /** `secret` is returned once and never stored in readable form. */
388 createToken(name: string): Promise<Outcome<{ readonly token: AccessToken; readonly secret: string }>>;
389 revokeToken(token: Id): Promise<Outcome>;
390 /** Agent clients this person has authorized over OAuth. */
391 agentGrants(): Promise<AgentGrant[]>;
392 revokeAgentGrant(grant: Id): Promise<Outcome>;
393}
394
395/** The hosted agents of a namespace or a repository. Everyone who can see them can mention them; admins change them. */
396export interface HostedAgents {
397 readonly canEdit: boolean;
398 list(): Promise<HostedAgent[]>;
399 /**
400 * Adds or changes an agent at this level. With a provider, the key is tested with one small request first, and a key
401 * that fails is not stored. An empty key keeps the saved key of the same provider.
402 */
403 save(input: { readonly handle: string; readonly description: string; readonly instructions: string; readonly provider: string; readonly model: string; readonly key: string }): Promise<Outcome>;
404 remove(handle: string): Promise<Outcome>;
405}
406
407export interface Waitlist {
408 list(): Promise<WaitlistEntry[]>;
409 /** Activates the person and creates their namespace. A conflict means someone took their handle first. */
410 approve(user: Id): Promise<Outcome>;
411}
412
413export interface Members {
414 /** The roles this actor may hand out. */
415 readonly invitableRoles: readonly Role[];
416 list(): Promise<Member[]>;
417 invitations(): Promise<Invitation[]>;
418 /** `link` is returned once; only its hash is stored. */
419 /** `invitee` is an email address or the username of an existing person. */
420 invite(input: { readonly invitee: string; readonly role: Role }): Promise<Outcome<{ readonly invitation: Invitation; readonly link: string }>>;
421 revokeInvitation(invitation: Id): Promise<Outcome>;
422}