Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

1,065 linesCodeBlameRaw
1import type { ActionsApi } from "./actions";
2import type { AiApi } from "./ai";
3import type { BillingAdminApi, BillingApi } from "./billing";
4import type { DeploymentsApi } from "./deployments";
5import type { ProjectsApi } from "./projects";
6import type { EventsApi } from "./events";
7import type { IdentityAdminApi, IdentityApi } from "./identity";
8import type { IntegrationsApi } from "./integrations";
9import type { PackagesApi } from "./packages";
10import type { WebhooksApi } from "./webhooks";
11import type { RepoPath, ReposApi } from "./repos";
12import type { CommentScope, PullDetail, Thread, WorkApi } from "./work";
13import type { Result } from "./result";
14import type { RunnersAdminApi, RunnersApi } from "./runners";
15
16/** A service binding, as far as these clients need it. */
17export type ServiceBinding = {
18 fetch(input: string, init?: RequestInit): Promise<Response>;
19};
20
21/**
22 * Calls a method on a service that speaks the JSON protocol used by the
23 * Rust services: `POST /rpc/<method>` with the arguments as the body.
24 */
25async function rpc<T>(
26 service: ServiceBinding,
27 method: string,
28 args: object,
29): Promise<T> {
30 // The hostname is ignored; a service binding always reaches its service.
31 const response = await service.fetch(`https://service/rpc/${method}`, {
32 method: "POST",
33 headers: { "content-type": "application/json" },
34 body: JSON.stringify(args),
35 });
36 if (!response.ok) {
37 throw new Error(`${method} failed with status ${response.status}`);
38 }
39 return (await response.json()) as T;
40}
41
42/** The thread's fields as the work service reads them. */
43function threadArgs(thread: Thread): { repo: RepoPath | null; workspace: string; number: number } {
44 return "repo" in thread
45 ? { repo: thread.repo, workspace: "", number: thread.number }
46 : { repo: null, workspace: thread.workspace, number: thread.number };
47}
48
49export function identityClient(service: ServiceBinding): IdentityApi {
50 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
51 return {
52 register: (username, email, password, inviteCode, client, emailProof) =>
53 call("register", {
54 username,
55 email,
56 password,
57 invite_code: inviteCode ?? null,
58 email_proof: emailProof ?? null,
59 client: client ?? null,
60 }),
61 signIn: (username, password, client) => call("sign_in", { username, password, client: client ?? null }),
62 twoFactorSignIn: (challenge, code, client) => call("two_factor_sign_in", { challenge, code, client: client ?? null }),
63 signOut: (sessionToken) => call("sign_out", { sessionToken }),
64 resendVerification: (user) => call("resend_verification", { user }),
65 verifyEmail: (token) => call("verify_email", { token }),
66 requestPasswordReset: (email, client) => call("request_password_reset", { email, client: client ?? null }),
67 resetPassword: (token, password) =>
68 call("reset_password", { token, password }),
69 deviceStart: (clientName) => call("device_start", { clientName }),
70 deviceLookup: (userCode) => call("device_lookup", { userCode }),
71 deviceResolve: (userCode, user, approve) =>
72 call("device_resolve", { userCode, user, approve }),
73 deviceClaim: (deviceCode) => call("device_claim", { deviceCode }),
74 oauthAuthorize: (user, approval) => call("oauth_authorize", { user, ...approval }),
75 oauthExchange: (code, codeVerifier, clientId, redirectUri) =>
76 call("oauth_exchange", { code, codeVerifier, clientId, redirectUri }),
77 oauthRefresh: (refreshToken, clientId) =>
78 call("oauth_refresh", { refreshToken, clientId }),
79 listOAuthGrants: (user) => call("list_oauth_grants", { user }),
80 revokeOAuthGrant: (user, id) => call("revoke_oauth_grant", { user, id }),
81 updateOAuthGrant: (user, id, grant) =>
82 call("update_oauth_grant", { user, id, scopes: grant.scopes }),
83 createWorkspace: (user, slug, name) => call("create_workspace", { user, slug, name }),
84 getWorkspace: (slug) => call("get_workspace", { slug }),
85 workspaceResidency: (slug) => call("workspace_residency", { slug }),
86 setWorkspaceResidency: (actor, slug, residency) => call("set_workspace_residency", { actor, slug, residency }),
87 listMembers: (slug, viewer) => call("list_members", { slug, viewer }),
88 addMember: (actor, slug, username) => call("add_member", { actor, slug, username }),
89 removeMember: (actor, slug, username) =>
90 call("remove_member", { actor, slug, username, surface: "web" }),
91 updateMember: (actor, slug, username, change) =>
92 call("update_member", { actor, slug, username, role: change.role ?? null, org_roles: change.org_roles ?? null, surface: "web" }),
93 transferOwnership: (actor, slug, username) => call("transfer_ownership", { actor, slug, username, surface: "web" }),
94 leaveWorkspace: (user, slug) => call("leave_workspace", { user, slug, surface: "web" }),
95 setMemberPrivileges: (actor, slug, change) => call("set_member_privileges", { actor, slug, privileges: change, surface: "web" }),
96 setTwoFactorRequirement: (actor, slug, required) =>
97 call("set_two_factor_requirement", { actor, slug, required, surface: "web" }),
98 updateWorkspace: (actor, slug, details) =>
99 call("update_workspace", { actor, slug, ...details }),
100 renameWorkspace: (actor, slug, newSlug) => call("rename_workspace", { actor, slug, newSlug }),
101 checkWorkspaceRename: (actor, slug, newSlug) =>
102 call("check_workspace_rename", { actor, slug, newSlug }),
103 resolveSlug: (slug) => call("resolve_slug", { slug }),
104 deleteWorkspace: (actor, slug, confirm) => call("delete_workspace", { actor, slug, confirm }),
105 checkWorkspaceDeletion: (actor, slug) => call("check_workspace_deletion", { actor, slug }),
106 setWorkspaceAvatar: (actor, slug, image) => call("set_workspace_avatar", { actor, slug, image }),
107 setUserAvatar: (user, image) => call("set_user_avatar", { user, image }),
108 listWorkspaceTokens: (slug, viewer) => call("list_workspace_tokens", { slug, viewer }),
109 removeWorkspaceToken: (actor, slug, id) =>
110 call("remove_workspace_token", { actor, slug, id }),
111 createToken: (actor, input) =>
112 call("create_token", {
113 actor,
114 owner: input.owner ?? null,
115 name: input.name,
116 description: input.description ?? null,
117 ttl_seconds: input.ttlSeconds,
118 workspace: input.workspace,
119 repository_selection: input.repositorySelection,
120 repositories: input.repositories,
121 permissions: input.permissions,
122 website: input.website ?? false,
123 }),
124 updateToken: (actor, id, change, owner) =>
125 call("update_token", {
126 actor,
127 id,
128 owner: owner ?? null,
129 name: change.name ?? null,
130 description: change.description ?? null,
131 repository_selection: change.repositorySelection ?? null,
132 repositories: change.repositories ?? null,
133 permissions: change.permissions ?? null,
134 website: change.website ?? null,
135 }),
136 regenerateToken: (actor, id, ttlSeconds, owner) =>
137 call("regenerate_token", { actor, id, owner: owner ?? null, ttl_seconds: ttlSeconds ?? null }),
138 getTokenPolicy: (slug, viewer) => call("get_token_policy", { slug, viewer }),
139 setTokenPolicy: (actor, slug, change) =>
140 call("set_token_policy", {
141 actor,
142 slug,
143 allow_tokens_for_all_workspaces: change.allowTokensForAllWorkspaces ?? null,
144 allow_tokens_for_this_workspace: change.allowTokensForThisWorkspace ?? null,
145 require_approval: change.requireApproval ?? null,
146 max_lifetime_days: change.maxLifetimeDays ?? null,
147 forbid_no_expiry: change.forbidNoExpiry ?? null,
148 surface: "web",
149 }),
150 listMemberTokens: (actor, slug, filter = {}) =>
151 call("list_member_tokens", { actor, slug, status: filter.status ?? null }),
152 reviewTokenRequest: (actor, slug, id, approve, reason) =>
153 call("review_token_request", { actor, slug, id, approve, reason: reason ?? null, surface: "web" }),
154 revokeMemberToken: (actor, slug, id, reason) =>
155 call("revoke_member_token", { actor, slug, id, reason: reason ?? null, surface: "web" }),
156 userForSession: (sessionToken) => call("user_for_session", { sessionToken }),
157 listInvites: (user) => call("list_invites", { user }),
158 createInvite: (user, invite) =>
159 call("create_invite", {
160 user,
161 email: invite.email,
162 message: invite.message ?? null,
163 join: invite.join ?? null,
164 join_role: invite.join ? (invite.joinRole ?? null) : null,
165 surface: "web",
166 }),
167 revokeInvite: (user, id) => call("revoke_invite", { user, id }),
168 resendInvite: (user, id) => call("resend_invite", { user, id }),
169 checkInvite: (code, client, options = {}) =>
170 call("check_invite", {
171 code,
172 client: client ?? null,
173 viewer: options.viewer ?? null,
174 any_status: options.anyStatus ?? false,
175 email_proof: options.emailProof ?? null,
176 }),
177 acceptInvite: (user, code) => call("accept_invite", { user, code }),
178 inviteMember: (actor, slug, who) =>
179 call("invite_member", { actor, slug, email: who.email ?? "", username: who.username ?? null, role: who.role ?? null, message: who.message ?? null }),
180 listInvitations: (user) => call("list_invitations", { user }),
181 acceptInvitation: (user, id) => call("accept_invitation", { user, id, surface: "web" }),
182 declineInvitation: (user, id) => call("decline_invitation", { user, id, surface: "web" }),
183 findPeople: (query, limit) => call("find_people", { query, limit: limit ?? null }),
184 workspaceInvites: (slug, viewer) => call("workspace_invites", { slug, viewer }),
185 revokeWorkspaceInvite: (actor, slug, id) => call("revoke_workspace_invite", { actor, slug, id }),
186 resendWorkspaceInvite: (actor, slug, id) => call("resend_workspace_invite", { actor, slug, id }),
187 userForGitCredentials: (username, secret) =>
188 call("user_for_git_credentials", { username, secret }),
189 userForAccessToken: (token) => call("user_for_access_token", { token }),
190 userForSshKey: (fingerprint) => call("user_for_ssh_key", { fingerprint }),
191 userByUsername: (username) => call("user_by_username", { username }),
192 usernames: (ids) => call("usernames", { ids }),
193 accounts: (ids) => call("accounts", { ids }),
194 usersForAudience: (ids) => call("users_for_audience", { ids }),
195 profile: (username) => call("profile", { username }),
196 updateProfile: (actor, fields) => call("update_profile", { actor, ...fields }),
197 profileWorkspaces: (username, viewer, publicIn) =>
198 call("profile_workspaces", { username, viewer, public: publicIn }),
199 dockPins: (user, workspace) => call("dock_pins", { user, workspace }),
200 setDockPins: (user, workspace, apps) => call("set_dock_pins", { user, workspace, apps }),
201 onboarding: (user, workspace) => call("onboarding", { user, workspace }),
202 setOnboarding: (user, workspace, change) => call("set_onboarding", { user, workspace, change }),
203 soundSettings: (user) => call("sound_settings", { user }),
204 setSoundSettings: (user, change) => call("set_sound_settings", { user, change }),
205 listSshKeys: (user) => call("list_ssh_keys", { user }),
206 addSshKey: (user, title, publicKey) =>
207 call("add_ssh_key", { user, title, publicKey }),
208 removeSshKey: (user, id) => call("remove_ssh_key", { user, id }),
209 listAccessTokens: (user) => call("list_access_tokens", { user }),
210 createAccessToken: (user, name, ttlSeconds, grant) =>
211 call("create_access_token", {
212 user,
213 name,
214 ttlSeconds,
215 scopes: grant?.scopes ?? null,
216 listed: grant?.listed ?? false,
217 }),
218 removeAccessToken: (user, id) => call("remove_access_token", { user, id }),
219 createRunCredential: (input) => call("create_run_credential", input),
220 bindRunCredentials: (tokenHashes, runId) => call("bind_run_credentials", { tokenHashes, runId }),
221 revokeRunCredentials: (target) => call("revoke_run_credentials", target),
222 // Who has access to a repository; see access.ts.
223 repoAccess: (owner, name, viewer) => call("repo_access", { viewer, path: { namespace: owner, name } }),
224 addCollaborator: (actor, owner, name, invitee, role) =>
225 call("add_collaborator", { actor, path: { namespace: owner, name }, invitee, role }),
226 setCollaboratorRole: (actor, owner, name, username, role) =>
227 call("set_collaborator_role", { actor, path: { namespace: owner, name }, username, role }),
228 removeCollaborator: (actor, owner, name, username) =>
229 call("remove_collaborator", { actor, path: { namespace: owner, name }, username }),
230 collaboratorPermission: (viewer, owner, name, username) =>
231 call("collaborator_permission", { viewer, path: { namespace: owner, name }, username }),
232 myRepoInvitations: (user) => call("my_repo_invitations", { user }),
233 respondRepoInvitation: (user, id, accept) => call("respond_repo_invitation", { user, id, accept }),
234 revokeRepoInvitation: (actor, owner, name, id) =>
235 call("revoke_repo_invitation", { actor, path: { namespace: owner, name }, id }),
236 setBasePermission: (actor, slug, base) => call("set_base_permission", { actor, slug, base_permission: base }),
237 outsideCollaborators: (viewer, slug) => call("outside_collaborators", { viewer, slug }),
238 // A repository's deploy keys; see deploy-keys.ts.
239 listDeployKeys: (viewer, owner, name) => call("list_deploy_keys", { viewer, path: { namespace: owner, name } }),
240 addDeployKey: (actor, owner, name, key) =>
241 call("add_deploy_key", { actor, path: { namespace: owner, name }, title: key.title, key: key.key, read_only: key.readOnly }),
242 removeDeployKey: (actor, owner, name, id) => call("remove_deploy_key", { actor, path: { namespace: owner, name }, id }),
243 // Teams; see teams.ts.
244 listTeams: (viewer, workspace, query) => call("list_teams", { viewer, workspace, query: query ?? null }),
245 getTeam: (viewer, workspace, team) => call("get_team", { viewer, workspace, team }),
246 createTeam: (actor, workspace, team) => call("create_team", { actor, workspace, ...team }),
247 setTeamCreation: (actor, slug, setting) => call("set_team_creation", { actor, slug, team_creation: setting }),
248 updateTeam: (actor, workspace, team, changes) => call("update_team", { actor, workspace, team, ...changes }),
249 deleteTeam: (actor, workspace, team) => call("delete_team", { actor, workspace, team }),
250 teamMembers: (viewer, workspace, team, includeChildTeams) =>
251 call("team_members", { viewer, workspace, team, include_child_teams: includeChildTeams ?? false }),
252 setTeamMember: (actor, workspace, team, username, role) =>
253 call("set_team_member", { actor, workspace, team, username, role }),
254 removeTeamMember: (actor, workspace, team, username) =>
255 call("remove_team_member", { actor, workspace, team, username }),
256 childTeams: (viewer, workspace, team) => call("child_teams", { viewer, workspace, team }),
257 teamRepos: (viewer, workspace, team) => call("team_repos", { viewer, workspace, team }),
258 setTeamRepo: (actor, workspace, team, owner, name, role) =>
259 call("set_team_repo", { actor, workspace, team, repo: { namespace: owner, name }, role }),
260 removeTeamRepo: (actor, workspace, team, owner, name) =>
261 call("remove_team_repo", { actor, workspace, team, repo: { namespace: owner, name } }),
262 userTeams: (viewer, workspace, username) => call("user_teams", { viewer, workspace, username }),
263 teamMemberships: (viewer, workspace) => call("team_memberships", { viewer, workspace }),
264 // People; see people.ts.
265 peopleDirectory: (viewer, workspace) => call("people_directory", { viewer, workspace }),
266 setMemberProfile: (actor, workspace, username, changes) => call("set_member_profile", { actor, workspace, username, ...changes }),
267 };
268}
269
270/**
271 * The slug a renamed workspace has now, for a `workspace.renamed` handler:
272 * asked of identity by the workspace's id, so that renames delivered twice
273 * or out of order converge. Falls back to the event's `to`.
274 */
275export async function currentWorkspaceSlug(
276 identity: ServiceBinding,
277 renamed: { workspaceId: string; to: string },
278): Promise<string> {
279 const names = await identityClient(identity).usernames([renamed.workspaceId]);
280 return names[renamed.workspaceId] ?? renamed.to;
281}
282
283/** The slugs whose rows move to `current`: the two a rename names, less `current`. */
284export function staleSlugs(renamed: { from: string; to: string }, current: string): string[] {
285 return [...new Set([renamed.from, renamed.to])].filter((slug) => slug !== current);
286}
287
288/**
289 * Where a transferred repository is now, as `namespace/name`, for a
290 * `repo.transferred` handler: asked of repos by id, so transfers delivered
291 * twice or out of order converge. Falls back to the event's destination.
292 */
293export async function currentRepoPath(
294 repos: ServiceBinding,
295 transferred: { repoId: string; name: string; to: string },
296): Promise<string> {
297 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: transferred.repoId });
298 return path ? `${path.namespace}/${path.name}` : `${transferred.to}/${transferred.name}`;
299}
300
301/** The paths whose rows move to `current`: the two a transfer names, less `current`. */
302export function stalePaths(transferred: { name: string; from: string; to: string }, current: string): string[] {
303 return [...new Set([transferred.from, transferred.to].map((ns) => `${ns}/${transferred.name}`))].filter(
304 (path) => path !== current,
305 );
306}
307
308/**
309 * A repository's path change, from `repo.transferred` or `repo.renamed`,
310 * read the same way: the two paths (`namespace/name`) the event names, old
311 * then new. Null for any other event.
312 */
313export type RepoMove = { repoId: string; paths: [string, string] };
314
315export function repoMove(event: { type: string; data: unknown }): RepoMove | null {
316 const data = event.data as Record<string, string>;
317 if (event.type === "repo.transferred") {
318 return { repoId: data.repoId!, paths: [`${data.from}/${data.name}`, `${data.to}/${data.name}`] };
319 }
320 if (event.type === "repo.renamed") {
321 return { repoId: data.repoId!, paths: [`${data.namespace}/${data.from}`, `${data.namespace}/${data.to}`] };
322 }
323 return null;
324}
325
326/**
327 * Where a moved repository is now, as `namespace/name`: asked of repos by
328 * id, so moves delivered twice or out of order converge. Falls back to the
329 * event's new path.
330 */
331export async function currentMovedPath(repos: ServiceBinding, move: RepoMove): Promise<string> {
332 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: move.repoId });
333 return path ? `${path.namespace}/${path.name}` : move.paths[1];
334}
335
336/** The paths whose rows move to `current`: the two a move names, less `current`. */
337export function staleMovedPaths(move: RepoMove, current: string): string[] {
338 return [...new Set(move.paths)].filter((path) => path !== current);
339}
340
341/** Staff-only identity. Only sudo binds to it; see `IdentityAdminApi`. */
342export function identityAdminClient(service: ServiceBinding): IdentityAdminApi {
343 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
344 return {
345 growth: () => call("admin_growth", {}),
346 workspaces: (query) => call("admin_workspaces", { query: query ?? null }),
347 workspace: (slug) => call("admin_workspace", { slug }),
348 sso: (slug) => call("admin_sso", { slug }),
349 invites: (query, options = {}) => call("admin_invites", { query: query ?? null, to_g1t: options.toG1t ?? false }),
350 grantInvites: (username, amount, note, staff) => call("admin_grant_invites", { username, amount, note, staff }),
351 revokeInvite: (id, staff) => call("admin_revoke_invite", { id, staff }),
352 suspendUser: (name, suspend, reason, staff) => call("admin_suspend_user", { name, suspend, reason, staff }),
353 suspendWorkspace: (name, suspend, reason, staff) => call("admin_suspend_workspace", { name, suspend, reason, staff }),
354 blockedDomains: () => call("admin_blocked_domains", {}),
355 blockDomain: (domain, block, reason, staff) => call("admin_block_domain", { domain, block, reason, staff }),
356 deletedWorkspaces: () => call("admin_deleted_workspaces", {}),
357 restoreWorkspace: (workspaceId, staff) => call("admin_restore_workspace", { workspaceId, staff }),
358 purgeWorkspace: (workspaceId, staff, confirm) => call("admin_purge_workspace", { workspaceId, staff, confirm }),
359 aliases: () => call("admin_aliases", {}),
360 setAlias: (alias, workspace, note, staff) => call("admin_set_alias", { alias, workspace, note, staff }),
361 removeAlias: (alias, reason, staff) => call("admin_remove_alias", { alias, reason, staff }),
362 };
363}
364
365export function reposClient(service: ServiceBinding): ReposApi {
366 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
367 return {
368 get: (path, viewer) => call("get", { path, viewer }),
369 getById: (id, viewer) => call("get_by_id", { id, viewer }),
370 readable: (ids, viewer) => call("readable", { ids, viewer }),
371 publicNamespaces: (ownerId) => call("public_namespaces", { ownerId }),
372 list: (viewer, options = {}) => call("list", { viewer, ...options }),
373 create: (owner, input) => call("create", { owner, ...input }),
374 update: (actor, path, changes) => call("update", { actor, path, ...changes }),
375 transfer: (actor, path, to) => call("transfer", { actor, path, to }),
376 delete: (actor, path, confirm) => call("delete", { actor, path, confirm }),
377 deleted: (viewer, namespace) => call("deleted", { viewer, namespace }),
378 restore: (actor, path) => call("restore", { actor, path }),
379 purge: (actor, path, confirm) => call("purge", { actor, path, confirm }),
380 rename: (actor, path, name) => call("rename", { actor, path, name }),
381 archive: (actor, path, archived) => call("archive", { actor, path, archived }),
382 setVisibility: (actor, path, isPrivate, confirm) => call("set_visibility", { actor, path, isPrivate, confirm }),
383 setDefaultBranch: (actor, path, branch) => call("set_default_branch", { actor, path, branch }),
384 renameBranch: (actor, path, from, to) => call("rename_branch", { actor, path, from, to }),
385 createBranch: (actor, path, name, from = "") => call("create_branch", { actor, path, name, from }),
386 removeBranch: (actor, path, branch, head) => call("remove_branch", { actor, path, branch, head }),
387 resolveBranch: (repoId, branch) => call("resolve_branch", { repoId, branch }),
388 statusById: (id) => call("status_by_id", { id }),
389 storageOptions: () => call("storage_options", {}),
390 resolvePath: (path) => call("resolve_path", { path }),
391 tree: (path, viewer, ref, treePath) =>
392 call("tree", { path, viewer, ref, treePath }),
393 blob: (path, viewer, ref, filePath) =>
394 call("blob", { path, viewer, ref, filePath }),
395 log: (path, viewer, ref, limit) => call("log", { path, viewer, ref, limit }),
396 blame: (path, viewer, ref, filePath) => call("blame", { path, viewer, ref, filePath }),
397 forkForPull: (sourceId, pullId, actor) =>
398 call("fork_for_pull", { sourceId, pullId, actor }),
399 fork: (actor, path, input) => call("fork", { actor, path, ...input }),
400 forks: (path, viewer, limit) => call("forks", { path, viewer, limit: limit ?? null }),
401 syncFork: (actor, path, branch) => call("sync_fork", { actor, path, branch: branch ?? null }),
402 detachFork: (actor, path) => call("detach_fork", { actor, path }),
403 gitAccess: (path, viewer, service) =>
404 call("git_access", { path, viewer, service }),
405 branches: (path, viewer) => call("branches", { path, viewer }),
406 pathById: (id) => call("path_by_id", { id }),
407 lastCommits: (path, viewer, ref, treePath) => call("last_commits", { path, viewer, ref, treePath }),
408 branchDrift: (path, viewer, base, heads) => call("branch_drift", { path, viewer, base, heads }),
409 tags: (path, viewer) => call("tags", { path, viewer }),
410 about: (path, viewer) => call("about", { path, viewer }),
411 languages: (path, viewer) => call("languages", { path, viewer }),
412 contributors: (path, viewer) => call("contributors", { path, viewer }),
413 license: (path, viewer) => call("license", { path, viewer }),
414 stars: (path, viewer) => call("stars", { path, viewer }),
415 star: (actor, path, starred) => call("star", { path, actor, starred }),
416 stargazers: (path, viewer, page) => call("stargazers", { path, viewer, page: page ?? null }),
417 starred: (username, viewer) => call("starred", { username, viewer }),
418 releases: (path, viewer) => call("releases", { path, viewer }),
419 release: (path, viewer, which) => call("release", { path, viewer, id: which.id ?? null, tag: which.tag ?? null, latest: which.latest ?? false }),
420 createRelease: (actor, path, release) => call("create_release", { path, actor, ...release }),
421 updateRelease: (actor, path, id, change) => call("update_release", { path, actor, id, ...change }),
422 deleteRelease: (actor, path, id) => call("delete_release", { path, actor, id }),
423 listFiles: (repoId, ref, limit, options) => call("list_files", { repoId, ref, skipDirs: [], limit, links: options?.links ?? false }),
424 openArchiveToken: (path, token) => call("open_archive_token", { path, token }),
425 rawBlobs: (repoId, hashes, maxBytes) => call("raw_blobs", { repoId, hashes, maxBytes }),
426 rawFile: (repoId, ref, path, maxBytes) => call("raw_file", { repoId, ref, path, maxBytes }),
427 commitFile: (repo, actor, file) => call("commit_file", { repo, actor, ...file }),
428 land: (sourceId, actor, branch) => call("land", { sourceId, actor, branch }),
429 compare: (repoId, viewer, base, head, baseBranch, paths, targetId) =>
430 call("compare", { repoId, viewer, base, head, baseBranch, paths: paths ?? null, ...(targetId ? { targetId } : {}) }),
431 claimBackups: (limit, maxRunning) => call("claim_backups", { limit, maxRunning }),
432 // The sandbox's own calls are snake_case (they come through the API).
433 failBackup: (jobId, token, error) => call("backup_fail", { job_id: jobId, token, error }),
434 };
435}
436
437/**
438 * `PullDetail`'s own fields that the work service writes in snake_case:
439 * `g1t_contracts::work::PullDetail` has no camelCase renaming, though what
440 * it holds (`Pull`, `CheckRun` and the rest) does. Each with its name here.
441 */
442const PULL_DETAIL_FIELDS = [
443 ["earlier_checks", "earlierChecks"],
444 ["required_checks", "requiredChecks"],
445 ["code_owners", "codeOwners"],
446] as const;
447
448/**
449 * A pull request's detail as the work service sent it, with its own fields
450 * in the camelCase this package uses: read at the edge, by `workClient`'s
451 * `getPull`. Either spelling is taken, so a service that already sends
452 * camelCase reads the same.
453 */
454export function pullDetailFromWire(raw: Record<string, unknown>): PullDetail {
455 const detail: Record<string, unknown> = { ...raw };
456 for (const [snake, camel] of PULL_DETAIL_FIELDS) {
457 if (snake in detail) {
458 if (!(camel in detail)) detail[camel] = detail[snake];
459 delete detail[snake];
460 }
461 }
462 return detail as PullDetail;
463}
464
465/** A comment's scope as the work service reads it. */
466function commentScope(scope: CommentScope): { repo: RepoPath | null; workspace: string } {
467 return "repo" in scope ? { repo: scope.repo, workspace: "" } : { repo: null, workspace: scope.workspace };
468}
469
470export function workClient(service: ServiceBinding): WorkApi {
471 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
472 return {
473 // Work items are numbered in a workspace; their arguments are
474 // snake_case, as the Rust service reads them.
475 openWorkItem: (actor, input) =>
476 call("open_work_item", {
477 actor,
478 workspace: input.workspace ?? "",
479 repo: input.repo ?? null,
480 targets: input.targets ?? [],
481 title: input.title,
482 body: input.body,
483 labels: input.labels ?? [],
484 milestone: input.milestone ?? null,
485 }),
486 listWorkItems: (workspace, viewer, filter = {}) =>
487 call("list_work_items", {
488 workspace,
489 viewer,
490 repo: filter.repo ?? null,
491 role: filter.role ?? null,
492 state: filter.state ?? null,
493 label: filter.label ?? null,
494 milestone: filter.milestone ?? null,
495 assignee: filter.assignee ?? null,
496 }),
497 getWorkItem: (workspace, number, viewer) => call("get_work_item", { workspace, number, viewer }),
498 updateWorkItem: (actor, workspace, number, input) =>
499 call("update_work_item", { actor, workspace, number, ...input }),
500 closeWorkItem: (actor, workspace, number, reason, by) =>
501 call("close_work_item", {
502 actor,
503 workspace,
504 number,
505 reason: reason ?? null,
506 ...(by ? { repo: by.repo, commit: by.commit } : {}),
507 }),
508 reopenWorkItem: (actor, workspace, number) => call("reopen_work_item", { actor, workspace, number }),
509 linkWorkItem: (actor, workspace, number, repo, role = "target") =>
510 call("link_work_item", { actor, workspace, number, repo, role }),
511 unlinkWorkItem: (actor, workspace, number, repo) => call("unlink_work_item", { actor, workspace, number, repo }),
512 resolveRef: (viewer, context, number) =>
513 call("resolve_ref", {
514 viewer,
515 number,
516 ...("repo" in context ? { repo: context.repo, workspace: "" } : { repo: null, workspace: context.workspace }),
517 }),
518 migrateWorkItems: () => call("migrate_work_items", {}),
519 closedByCommit: (repo, commit, viewer) => call("closed_by_commit", { repo, commit, viewer }),
520 listLabels: (workspace, viewer) => call("list_labels", { workspace, viewer }),
521 saveLabel: (actor, workspace, label) => call("save_label", { actor, workspace, ...label }),
522 deleteLabel: (actor, workspace, name) => call("delete_label", { actor, workspace, name }),
523 addDefaultLabels: (actor, workspace) => call("add_default_labels", { actor, workspace }),
524 setLabels: (actor, thread, labels, change = "set") =>
525 call("set_labels", { actor, ...threadArgs(thread), labels, change }),
526 listMilestones: (workspace, viewer, state) => call("list_milestones", { workspace, viewer, state }),
527 getMilestone: (workspace, number, viewer) => call("get_milestone", { workspace, number, viewer }),
528 saveMilestone: (actor, workspace, milestone) => call("save_milestone", { actor, workspace, ...milestone }),
529 deleteMilestone: (actor, workspace, number) => call("delete_milestone", { actor, workspace, number }),
530 counts: (repo, viewer) => call("counts", { repo, viewer }),
531 addComment: (actor, thread, comment) => call("add_comment", { actor, ...threadArgs(thread), ...comment }),
532 editComment: (actor, scope, commentId, body) =>
533 call("edit_comment", { actor, ...commentScope(scope), commentId, body }),
534 deleteComment: (actor, scope, commentId) => call("delete_comment", { actor, ...commentScope(scope), commentId }),
535 react: (actor, thread, reaction) => call("react", { actor, ...threadArgs(thread), ...reaction }),
536 reportChecks: (runId, token, report) =>
537 call("report_checks", { runId, token, ...report }),
538 startMergecheck: (pullId) => call("start_mergecheck", { pullId }),
539 failMergecheck: (pullId, token, error) => call("report_mergecheck", { pullId, token, error }),
540 advance: (pullId) => call("advance", { pullId }),
541 managedPulls: (repoId) => call("managed_pulls", { repoId }),
542 queue: (repo, viewer) => call("queue", { repo, viewer }),
543 queueBuild: (repoId) => call("queue_build", { repoId }),
544 failQueue: (entryId, token, error) => call("report_queue", { entryId, token, error }),
545 removeFromQueue: (actor, repo, number) => call("remove_from_queue", { actor, repo, number }),
546 getSettings: (repo, viewer) => call("get_settings", { repo, viewer }),
547 // Rulesets travel in snake_case (rules.ts).
548 listRulesets: (owner, viewer, includeParents = false) =>
549 call("list_rulesets", { viewer, ...owner, include_parents: includeParents }),
550 getRuleset: (owner, id, viewer) => call("get_ruleset", { viewer, ...owner, id }),
551 saveRuleset: (actor, owner, ruleset, id) => call("save_ruleset", { actor, ...owner, id: id ?? null, ruleset }),
552 deleteRuleset: (actor, owner, id) => call("delete_ruleset", { actor, ...owner, id }),
553 effectiveRules: (repo, name, viewer, target = "branch") => call("effective_rules", { viewer, repo, name, target }),
554 ruleEvaluations: (owner, viewer, filter = {}) => call("rule_evaluations", { viewer, ...owner, ...filter }),
555 seenChecks: (repo, viewer) => call("seen_checks", { repo, viewer }),
556 commitChecks: (repo, viewer, shas) => call("commit_checks", { repo, viewer, shas }),
557 getCheckRun: (repo, id, viewer) => call("get_check_run", { repo, id, viewer }),
558 checkRunAnnotations: (repo, id, viewer) => call("check_run_annotations", { repo, id, viewer }),
559 requestCheckAction: (actor, repo, id, identifier) => call("request_check_action", { actor, repo, id, identifier }),
560 rerequestCheckRun: (actor, repo, id) => call("rerequest_check_run", { actor, repo, id }),
561 codeownersErrors: (repo, viewer, ref) => call("codeowners_errors", { repo, viewer, ref: ref ?? null }),
562 updateSettings: (actor, repo, settings) =>
563 call("update_settings", { actor, repo, settings }),
564 openPull: (actor, repo, input) => call("open_pull", { actor, repo, ...input }),
565 listPulls: (repo, viewer, state, filter = {}) => call("list_pulls", { repo, viewer, state, ...filter }),
566 deliveryInsights: (repoIds, viewer, from, until) => call("delivery_insights", { repoIds, viewer, from, until }),
567 workspaceSignals: (args, viewer) => call("workspace_signals", { ...args, viewer }),
568 pullsForRepos: (repoIds, viewer, limit) => call("pulls_for_repos", { repoIds, viewer, limit }),
569 // Its own fields arrive in snake_case: read into camelCase here.
570 getPull: (repo, number, viewer) =>
571 call<Result<Record<string, unknown>>>("get_pull", { repo, number, viewer }).then(
572 (found): Result<PullDetail> => (found.ok ? { ok: true, value: pullDetailFromWire(found.value) } : found),
573 ),
574 updatePull: (actor, repo, number, changes) =>
575 call("update_pull", { actor, repo, number, ...changes }),
576 catchUpPull: (actor, repo, number, options = {}) => call("catch_up_pull", { actor, repo, number, ...options }),
577 setAutoMerge: (actor, repo, number, enabled, options = {}) =>
578 call("set_auto_merge", { actor, repo, number, enabled, ...options }),
579 mergeChoices: (viewer, repo, number) => call("merge_choices", { viewer, repo, number }),
580 deleteHeadBranch: (actor, repo, number) => call("delete_head_branch", { actor, repo, number }),
581 restoreHeadBranch: (actor, repo, number) => call("restore_head_branch", { actor, repo, number }),
582 commitComments: (viewer, repo, commit, page) =>
583 call("commit_comments", { viewer, repo, commit: commit ?? null, page: page ?? null }),
584 addCommitComment: (actor, repo, commit, body, at) =>
585 call("add_commit_comment", { actor, repo, commit, body, path: at?.path ?? null, line: at?.line ?? null }),
586 editCommitComment: (actor, repo, id, body) => call("edit_commit_comment", { actor, repo, id, body }),
587 deleteCommitComment: (actor, repo, id) => call("delete_commit_comment", { actor, repo, id }),
588 readyPull: (actor, repo, number, summary) =>
589 call("ready_pull", { actor, repo, number, summary }),
590 closePull: (actor, repo, number) => call("close_pull", { actor, repo, number }),
591 reopenPull: (actor, repo, number) => call("reopen_pull", { actor, repo, number }),
592 convertPullToDraft: (actor, repo, number) => call("convert_pull_to_draft", { actor, repo, number }),
593 mergePull: (actor, repo, number, options = {}) =>
594 call("merge_pull", { actor, repo, number, ...options }),
595 listActivePulls: (viewer) => call("list_active_pulls", { viewer }),
596 byAuthor: (username, viewer, filter = {}) => call("by_author", { username, viewer, ...filter }),
597 contributions: (username, viewer) => call("contributions", { username, viewer }),
598 appendSession: (actor, repo, number, entries) =>
599 call("append_session", { actor, repo, number, entries }),
600 readSession: (repo, number, viewer, afterSeq = 0) =>
601 call("read_session", { repo, number, viewer, afterSeq }),
602 // Coordination: harness sessions, claims, a work item's whole context
603 // and decision records. Their arguments are snake_case, as the Rust
604 // service reads them; what comes back is camelCase.
605 getWork: (workspace, number, viewer) => call("get_work", { workspace, number, viewer }),
606 listClaims: (workspace, viewer, filter = {}) =>
607 call("list_claims", {
608 workspace,
609 viewer,
610 repo: filter.repo ?? null,
611 state: filter.state ?? null,
612 item: filter.item ?? null,
613 }),
614 listWorkSessions: (repo, viewer, filter = {}) =>
615 call("list_work_sessions", {
616 repo,
617 viewer,
618 state: filter.state ?? null,
619 item: filter.item ?? null,
620 pull: filter.pull ?? null,
621 path: filter.path ?? null,
622 subagents: filter.subagents ?? false,
623 }),
624 getWorkSession: (repo, id, viewer, afterSeq = 0) =>
625 call("get_work_session", { repo, id, viewer, after_seq: afterSeq }),
626 listWorkspaceSessions: (workspace, viewer, filter = {}) =>
627 call("list_workspace_sessions", {
628 workspace,
629 viewer,
630 shown: filter.shown ?? "recent",
631 kind: filter.kind ?? null,
632 harness: filter.harness ?? null,
633 person: filter.person ?? null,
634 repo: filter.repo ?? null,
635 item: filter.item ?? null,
636 subagents: filter.subagents ?? false,
637 sessions_only: filter.sessionsOnly ?? false,
638 limit: filter.limit ?? null,
639 }),
640 getWorkspaceSession: (workspace, id, viewer, afterSeq = 0) =>
641 call("get_workspace_session", { workspace, id, viewer, after_seq: afterSeq }),
642 endWorkSession: (actor, repo, id) => call("end_session", { actor, repo, id, by_hand: true }),
643 titleWorkSession: (actor, repo, id, title) => call("title_session", { actor, repo, id, title }),
644 pullSessions: (repo, viewer, numbers) => call("pull_sessions", { repo, viewer, numbers }),
645 listDecisions: (thread, viewer) => call("list_decisions", { ...threadArgs(thread), viewer }),
646 };
647}
648
649export function billingClient(service: ServiceBinding): BillingApi {
650 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
651 return {
652 status: () => call("status", {}),
653 account: (workspace, viewer) => call("account", { workspace, viewer }),
654 ledger: (workspace, viewer) => call("ledger", { workspace, viewer }),
655 credits: (workspace, viewer) => call("credits", { workspace, viewer }),
656 statement: (workspace, viewer, month = null, group = "day") => call("statement", { workspace, viewer, month, group }),
657 statementEntries: (workspace, viewer, filter) =>
658 call("statement_entries", {
659 workspace,
660 viewer,
661 month: filter.month,
662 kind: filter.kind,
663 day: filter.day ?? null,
664 project: filter.project ?? null,
665 before: filter.before ?? null,
666 }),
667 usage: (workspace, viewer, since) => call("usage", { workspace, viewer, since }),
668 checkout: (actor, workspace, amountCents, returnUrl, method = "card") =>
669 call("checkout", { actor, workspace, amountCents, returnUrl, method }),
670 confirm: (workspace, viewer, session) => call("confirm", { workspace, viewer, session }),
671 trial: (workspace, exempt) => call("trial", { workspace, exempt }),
672 features: (workspace, viewer) => call("features", { workspace, viewer }),
673 subscribe: (actor, workspace, feature, returnUrl) =>
674 call("subscribe", { actor, workspace, feature, returnUrl }),
675 confirmSubscription: (workspace, viewer, session) =>
676 call("confirm_subscription", { workspace, viewer, session }),
677 cancelSubscription: (actor, workspace, feature, resume = false) =>
678 call("cancel_subscription", { actor, workspace, feature, resume }),
679 convertToPaid: (actor, workspace, returnUrl) => call("convert_to_paid", { actor, workspace, returnUrl }),
680 hasFeature: (workspace, feature) => call("has_feature", { workspace, feature }),
681 freeWorkspaces: (workspaces) => call("free_workspaces", { workspaces }),
682 chargeFeature: (charge) => call("charge_feature", charge),
683 billingPortal: (actor, workspace, returnUrl) => call("billing_portal", { actor, workspace, return_url: returnUrl }),
684 recordSandbox: (usage) => call("record_sandbox", usage),
685 limit: (workspace, viewer) => call("limit", { workspace, viewer }),
686 checkLimit: (workspace) => call("check_limit", { workspace }),
687 prices: () => call("prices", {}),
688 notePending: (workspace, source, costMicros, detail = null, month = null) =>
689 call("note_pending", { workspace, source, costMicros, detail, ...(month ? { month } : {}) }),
690 usageMeters: (workspace, viewer) => call("usage_meters", { workspace, viewer }),
691 setSpendLimit: (actor, workspace, spendLimitMicros, useFullLimit = false, raiseOnce = false) =>
692 call("set_spend_limit", { actor, workspace, spendLimitMicros, use_full_limit: useFullLimit, raise_once: raiseOnce }),
693 invoices: (workspace, viewer) => call("invoices", { workspace, viewer }),
694 entitlements: (workspace) => call("entitlements", { workspace }),
695 reserve: (reservation) => call("reserve", reservation),
696 settle: (reservationId, actualMicros) => call("settle", { reservationId, actualMicros }),
697 cardCheck: (actor, workspace, returnUrl) => call("card_check", { actor, workspace, returnUrl }),
698 confirmCardCheck: (workspace, viewer, session) => call("confirm_card_check", { workspace, viewer, session }),
699 requestLimit: (actor, workspace, request) => call("request_limit", { actor, workspace, ...request }),
700 limitRequests: (workspace, viewer) => call("limit_requests", { workspace, viewer }),
701 confirmSpike: (actor, workspace, keepGoing) => call("confirm_spike", { actor, workspace, keepGoing }),
702 usageReport: (workspace, viewer, range) =>
703 call("usage_report", { workspace, viewer, from: range.from, until: range.until, products: range.products ?? [], projects: range.projects ?? [] }),
704 setBudget: (actor, workspace, budget) => call("set_budget", { actor, workspace, ...budget }),
705 billingDetails: (workspace, viewer) => call("billing_details", { workspace, viewer }),
706 setBillingDetails: (actor, workspace, details) => call("set_billing_details", { actor, workspace, ...details }),
707 };
708}
709
710export function billingAdminClient(service: ServiceBinding): BillingAdminApi {
711 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
712 return {
713 accounts: (query) => call("admin_accounts", { query: query ?? null }),
714 account: (id) => call("admin_account", { id }),
715 setTerms: (id, terms, by) => call("admin_set_terms", { id, terms, by }),
716 setAllowances: (id, allowances, note, by) => call("admin_set_allowances", { id, allowances, note, by }),
717 complimentary: (workspace) => call("admin_complimentary", { workspace }),
718 setComplimentary: (workspace, terms, note, by) =>
719 call("admin_set_complimentary", {
720 workspace,
721 allowance_micros: terms.allowanceMicros,
722 unlimited: terms.unlimited,
723 fee_cents: terms.feeCents,
724 charge_past_allowance: terms.chargePastAllowance,
725 note,
726 by,
727 }),
728 endComplimentary: (workspace, note, by) => call("admin_end_complimentary", { workspace, note, by }),
729 createEnterprise: (name, workspaces, by) => call("admin_create_enterprise", { name, workspaces, by }),
730 attach: (workspace, account, by) => call("admin_attach", { workspace, account, by }),
731 credit: (workspace, amountMicros, note, by, options = { kind: "goodwill" }) =>
732 call("admin_credit", {
733 workspace,
734 amount_micros: amountMicros,
735 note,
736 by,
737 kind: options.kind,
738 expires_at: options.expiresAt ?? null,
739 refund_for: options.refundFor ?? null,
740 refund_day: options.refundDay ?? null,
741 }),
742 credits: (filter = {}) =>
743 call("admin_credits", {
744 workspace: filter.workspace ?? null,
745 kind: filter.kind ?? null,
746 month: filter.month ?? null,
747 by: filter.by ?? null,
748 }),
749 revokeCredit: (id, note, by) => call("admin_revoke_credit", { id, note, by }),
750 resetBilling: (workspace, confirm, note, by) => call("admin_reset_billing", { workspace, confirm, note, by }),
751 detachTestStripe: (a) =>
752 call("admin_detach_test_stripe", {
753 workspace: a.workspace ?? null,
754 exclude: a.exclude ?? null,
755 dry_run: a.dryRun,
756 cancel_at_stripe: a.cancelAtStripe ?? false,
757 confirm: a.confirm ?? "",
758 by: a.by,
759 }),
760 billingLink: (workspace, by) => call("admin_billing_link", { workspace, by }),
761 stripe: (fix = false, by) => call("admin_stripe", { fix, by: by ?? null }),
762 enterpriseBilling: (id, email, by) => call("admin_enterprise_billing", { id, email, by }),
763 enterpriseAddress: (id, address, taxIdType, taxId, by) => call("admin_enterprise_address", { id, address, taxIdType, taxId, by }),
764 invoiceEnterprise: (id, by) => call("admin_invoice_enterprise", { id, by }),
765 accountsFor: (workspaces) => call("admin_accounts", { query: null, workspaces }),
766 signals: () => call("admin_signals", {}),
767 overview: () => call("admin_overview", {}),
768 sales: (workspace) => call("admin_sales", { workspace }),
769 setSales: (workspace, record, by) =>
770 call("admin_set_sales", {
771 workspace,
772 stage: record.stage,
773 owner: record.owner ?? null,
774 next_step: record.nextStep ?? null,
775 next_at: record.nextAt ?? null,
776 by,
777 }),
778 addNote: (workspace, text, by) => call("admin_add_note", { workspace, text, by }),
779 workspaceInvoices: (workspace) => call("admin_workspace_invoices", { workspace }),
780 allInvoices: (filter = {}) => call("admin_invoices", { status: filter.status ?? null, month: filter.month ?? null }),
781 audit: (filter = {}) =>
782 call("admin_audit", { by: filter.by ?? null, action: filter.action ?? null, before: filter.before ?? null }),
783 limitRequests: (status = "open") => call("admin_limit_requests", { status }),
784 decideLimitRequest: (id, decision, amountMicros, note, by) =>
785 call("admin_decide_limit_request", { id, decision, amount_micros: amountMicros, note, by }),
786 overages: () => call("admin_overages", {}),
787 goodwill: (workspace, amountMicros, reason, by, day = null, requestKey = null) =>
788 call("admin_goodwill", { workspace, amount_micros: amountMicros, reason, by, day, request_key: requestKey }),
789 velocity: () => call("admin_velocity", {}),
790 recordPayment: (workspace, amountMicros, reference, note, by) =>
791 call("admin_record_payment", { workspace, amount_micros: amountMicros, reference, note, by }),
792 costs: (days) => call("admin_costs", { days: days ?? null }),
793 costAlerts: () => call("admin_cost_alerts", {}),
794 spendCaps: () => call("admin_spend_caps", {}),
795 liftBreaker: (note, by) => call("admin_lift_breaker", { note, by }),
796 platformGuard: () => call("admin_platform_guard", {}),
797 setPause: (level, paused, note, by) => call("admin_set_pause", { level, paused, note, by }),
798 decideProposal: (id, decision, note, by) => call("admin_decide_proposal", { id, decision, note, by }),
799 setCostSettings: (settings, by) => call("admin_set_cost_settings", { settings, by }),
800 setCostMapping: (mapping, by) =>
801 call("admin_set_cost_mapping", {
802 product: mapping.product,
803 meter: mapping.meter,
804 bucket: mapping.bucket ?? "",
805 price_meter: mapping.priceMeter ?? null,
806 own_meter: mapping.ownMeter ?? null,
807 scale_to_own: mapping.scaleToOwn ?? false,
808 drift_percent: mapping.driftPercent ?? null,
809 note: mapping.note ?? "",
810 remove: mapping.remove ?? false,
811 by,
812 }),
813 runCosts: (by) => call("admin_run_costs", { by }),
814 };
815}
816
817export function eventsClient(service: ServiceBinding): EventsApi {
818 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
819 return {
820 publish: (events) => call("publish", { events }),
821 list: (query) => call("list", query),
822 activityDigest: (args) => call("activity_digest", args),
823 };
824}
825
826export function integrationsClient(service: ServiceBinding): IntegrationsApi {
827 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
828 return {
829 list: (workspace, viewer) => call("list", { workspace, viewer }),
830 connect: (actor, workspace, input) => call("connect", { actor, workspace, ...input }),
831 update: (actor, workspace, id, input) => call("update", { actor, workspace, id, ...input }),
832 disconnect: (actor, workspace, id) => call("disconnect", { actor, workspace, id }),
833 test: (actor, workspace, id) => call("test", { actor, workspace, id }),
834 deliveries: (workspace, viewer, id) => call("deliveries", { workspace, viewer, id }),
835 resolve: (workspace, viewer, reference) => call("resolve", { workspace, viewer, reference }),
836 import: (actor, workspace, reference, options) =>
837 call("import", { actor, workspace, reference, repo: options?.repo ?? null, targets: options?.targets ?? [] }),
838 links: (workspace, number) => call("links", { workspace, number }),
839 };
840}
841
842/**
843 * A workspace's AI providers and Ask g1t. Kept by the integrations service,
844 * so it is built on the same binding, with its own methods.
845 */
846export function aiClient(service: ServiceBinding): AiApi {
847 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
848 return {
849 list: (workspace, viewer) => call("ai_list", { workspace, viewer }),
850 add: (actor, workspace, input) => call("ai_add", { actor, workspace, ...input }),
851 update: (actor, workspace, id, input) => call("ai_update", { actor, workspace, id, ...input }),
852 remove: (actor, workspace, id) => call("ai_remove", { actor, workspace, id }),
853 test: (actor, workspace, id) => call("ai_test", { actor, workspace, id }),
854 askSettings: (workspace, viewer) => call("ask_settings", { workspace, viewer }),
855 setAskSettings: (actor, workspace, providerId, model) =>
856 call("set_ask_settings", { actor, workspace, provider_id: providerId, model }),
857 // Streamed: the response itself, not its parsed body.
858 ask: (actor, workspace, messages, page, signal) =>
859 service.fetch("https://service/rpc/ask", {
860 method: "POST",
861 headers: { "content-type": "application/json" },
862 body: JSON.stringify({ actor, workspace, messages, page }),
863 signal,
864 }),
865 };
866}
867
868export function webhooksClient(service: ServiceBinding): WebhooksApi {
869 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
870 return {
871 list: (viewer, owner) => call("list", { viewer, ...owner }),
872 create: (actor, owner, input) => call("create", { actor, ...owner, ...input }),
873 update: (actor, owner, id, input) => call("update", { actor, ...owner, id, ...input }),
874 delete: (actor, owner, id) => call("delete", { actor, ...owner, id }),
875 ping: (actor, owner, id) => call("ping", { actor, ...owner, id }),
876 deliveries: (viewer, owner, id) => call("deliveries", { viewer, ...owner, id }),
877 redeliver: (actor, owner, deliveryId) => call("redeliver", { actor, ...owner, deliveryId }),
878 };
879}
880
881export function actionsClient(service: ServiceBinding): ActionsApi {
882 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
883 return {
884 workflows: (repo, viewer) => call("workflows", { repo, viewer }),
885 runs: (repo, viewer, filter = {}) => call("runs", { repo, viewer, ...filter }),
886 run: (repo, viewer, id, attempt) => call("run", { repo, viewer, id, attempt: attempt ?? null }),
887 logs: (repo, viewer, job, after = 0) => call("logs", { repo, viewer, job, after }),
888 summaries: (repo, viewer, id, attempt) => call("summaries", { repo, viewer, id, attempt: attempt ?? null }),
889 jobLogText: (repo, viewer, job) => call("job_log_text", { repo, viewer, job }),
890 runLogs: (repo, viewer, id, attempt) => call("run_logs", { repo, viewer, id, attempt: attempt ?? null }),
891 dispatch: (actor, repo, workflow, ref, inputs) => call("dispatch", { actor, repo, workflow, ref, inputs }),
892 cancel: (actor, repo, id, force = false) => call("cancel", { actor, repo, id, force }),
893 rerun: (actor, repo, id, failedOnly = false, options = {}) =>
894 call("rerun", { actor, repo, id, failed_only: failedOnly, job: options.job ?? null, debug: options.debug ?? false }),
895 setWorkflowEnabled: (actor, repo, workflow, enabled) =>
896 call("set_workflow_enabled", { actor, repo, workflow, enabled }),
897 settings: (actor, owner, kind) => call("settings", { actor, ...owner, kind }),
898 setSetting: (actor, owner, kind, name, value, options = {}) =>
899 call("set_setting", { actor, ...owner, kind, name, value, ...options }),
900 deleteSetting: (actor, owner, kind, name, id) => call("delete_setting", { actor, ...owner, kind, name, id }),
901 approveRun: (actor, repo, id) => call("approve_run", { actor, repo, id }),
902 pendingDeployments: (repo, viewer, id) => call("pending_deployments", { repo, viewer, id }),
903 reviewDeployments: (actor, repo, id, state, environments = [], comment) =>
904 call("review_deployments", { actor, repo, id, state, environments, comment: comment ?? null }),
905 actionsSettings: (repo, viewer) => call("actions_settings", { repo, viewer }),
906 setActionsSettings: (actor, repo, change) => call("set_actions_settings", { actor, repo, ...change }),
907 workspaceActionsSettings: (workspace, viewer) => call("workspace_actions_settings", { workspace, viewer }),
908 setWorkspaceActionsSettings: (actor, workspace, change) =>
909 call("set_workspace_actions_settings", { actor, workspace, ...change }),
910 workspaceManagedWorkflows: (workspace, viewer) => call("workspace_managed_workflows", { workspace, viewer }),
911 setWorkspaceManagedWorkflow: (actor, workspace, name, change, create = false) =>
912 call("set_workspace_managed_workflow", { actor, workspace, name, create, ...change }),
913 removeWorkspaceManagedWorkflow: (actor, workspace, name) =>
914 call("remove_workspace_managed_workflow", { actor, workspace, name }),
915 environments: (repo, viewer) => call("environments", { repo, viewer }),
916 setEnvironment: (actor, repo, name, change) => call("set_environment", { actor, repo, name, ...change }),
917 deleteEnvironment: (actor, repo, name) => call("delete_environment", { actor, repo, name }),
918 artifacts: (repo, viewer, filter = {}) => call("artifacts", { repo, viewer, ...filter }),
919 artifactDownload: (repo, viewer, by) => call("artifact_download", { repo, viewer, ...by }),
920 deleteArtifact: (actor, repo, id) => call("delete_artifact", { actor, repo, id }),
921 artifactRetention: (repo, viewer, days) => call("artifact_retention", { repo, viewer, days }),
922 };
923}
924
925
926/** Staff-only self-hosted runners, on the actions service: only sudo calls it. */
927export function runnersAdminClient(service: ServiceBinding): RunnersAdminApi {
928 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
929 return {
930 list: (workspace) => call("admin_runners", { workspace }),
931 remove: (workspace, id, staff) => call("admin_remove_runners", { workspace, id, staff }),
932 };
933}
934
935/** Self-hosted runners, kept by the actions service. */
936export function runnersClient(service: ServiceBinding): RunnersApi {
937 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
938 return {
939 stuck: (viewer) => call("stuck_jobs", { viewer }),
940 activity: (actor, workspace) => call("runner_activity", { actor, workspace }),
941 list: (actor, owner) => call("runners", { actor, ...owner }),
942 createToken: (actor, owner, group) => call("create_registration_token", { actor, ...owner, group }),
943 remove: (actor, owner, id) => call("remove_runner", { actor, ...owner, id }),
944 groups: (actor, workspace) => call("runner_groups", { actor, workspace }),
945 setGroup: (actor, workspace, group) => call("set_runner_group", { actor, workspace, ...group }),
946 deleteGroup: (actor, workspace, id) => call("delete_runner_group", { actor, workspace, id }),
947 settings: (actor, owner) => call("runner_settings", { actor, ...owner }),
948 setSettings: (actor, owner, change) => call("set_runner_settings", { actor, ...owner, ...change }),
949 reportDesktop: (actor, report) => call("report_desktop", { actor, ...report }),
950 desktops: (actor, workspace) => call("desktop_runners", { actor, workspace }),
951 };
952}
953
954export function deploymentsClient(service: ServiceBinding): DeploymentsApi {
955 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
956 return {
957 settings: (project, viewer) => call("settings", { project, viewer }),
958 updateSettings: (actor, project, changes) => call("update_settings", { actor, project, changes }),
959 list: (project, viewer) => call("list", { project, viewer }),
960 get: (project, id, viewer) => call("get", { project, id, viewer }),
961 redeploy: (actor, project, branch) => call("redeploy", { actor, project, branch }),
962 takeDown: (actor, project, branch) => call("take_down", { actor, project, branch }),
963 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
964 usage: (workspace, viewer) => call("usage", { workspace, viewer }),
965 domains: (project, viewer) => call("domains", { project, viewer }),
966 addDomain: (actor, project, hostname, options = {}) =>
967 call("add_domain", { actor, project, hostname, twin: !!options.twin }),
968 removeDomain: (actor, project, id) => call("remove_domain", { actor, project, id }),
969 refreshDomain: (actor, project, id) => call("refresh_domain", { actor, project, id }),
970 repoDeployments: (repo, viewer, filter = {}) => call("list_deployments", { repo, viewer, ...filter }),
971 repoDeployment: (repo, id, viewer) => call("get_deployment", { repo, id, viewer }),
972 environments: (repo, viewer) => call("list_environments", { repo, viewer }),
973 createDeployment: (actor, repo, input) => call("create_deployment", { repo, actor, ...input }),
974 createDeploymentStatus: (actor, repo, id, input) => call("create_deployment_status", { repo, actor, id, ...input }),
975 shipped: (workspace, viewer, repos) => call("shipped", { workspace, viewer, repos }),
976 };
977}
978
979/** Packages: the registries beside the code (services/packages). */
980export function packagesClient(service: ServiceBinding): PackagesApi {
981 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
982 return {
983 list: (workspace, viewer, filter = {}) =>
984 call("list_packages", {
985 workspace,
986 viewer,
987 ecosystem: filter.ecosystem ?? null,
988 repo_id: filter.repoId ?? null,
989 query: filter.query ?? null,
990 }),
991 get: (workspace, ecosystem, name, viewer) => call("get_package", { workspace, ecosystem, name, viewer }),
992 deleteVersion: (actor, workspace, ecosystem, name, version, surface) =>
993 call("delete_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
994 deletePackage: (actor, workspace, ecosystem, name, surface) =>
995 call("delete_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
996 set: (actor, workspace, ecosystem, name, change, surface) =>
997 call("set_package", {
998 actor,
999 workspace,
1000 ecosystem,
1001 name,
1002 visibility: change.visibility ?? null,
1003 link: change.link ?? null,
1004 unlink: change.unlink ?? false,
1005 inherit_access: change.inheritAccess ?? null,
1006 surface: surface ?? null,
1007 }),
1008 settings: (workspace, ecosystem, name, viewer) => call("package_settings", { workspace, ecosystem, name, viewer }),
1009 deleted: (workspace, viewer) => call("deleted_packages", { workspace, viewer }),
1010 restorePackage: (actor, workspace, ecosystem, name, surface) =>
1011 call("restore_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
1012 restoreVersion: (actor, workspace, ecosystem, name, version, surface) =>
1013 call("restore_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
1014 setAccess: (actor, workspace, ecosystem, name, who, role, surface) =>
1015 call("set_package_access", {
1016 actor,
1017 workspace,
1018 ecosystem,
1019 name,
1020 user: "user" in who ? who.user : null,
1021 team: "team" in who ? who.team : null,
1022 role,
1023 surface: surface ?? null,
1024 }),
1025 removeAccess: (actor, workspace, ecosystem, name, who, surface) =>
1026 call("remove_package_access", {
1027 actor,
1028 workspace,
1029 ecosystem,
1030 name,
1031 user: "user" in who ? who.user : null,
1032 team: "team" in who ? who.team : null,
1033 surface: surface ?? null,
1034 }),
1035 setActionsAccess: (actor, workspace, ecosystem, name, repo, role, surface) =>
1036 call("set_actions_access", { actor, workspace, ecosystem, name, repo, role, surface: surface ?? null }),
1037 removeActionsAccess: (actor, workspace, ecosystem, name, repo, surface) =>
1038 call("remove_actions_access", { actor, workspace, ecosystem, name, repo, surface: surface ?? null }),
1039 storage: (workspace) => call("storage", { workspace }),
1040 storageAll: () => call("storage_all", {}),
1041 syncComposer: (repoId) => call("sync_composer", { repo_id: repoId }),
1042 };
1043}
1044
1045export function projectsClient(service: ServiceBinding): ProjectsApi {
1046 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
1047 return {
1048 list: (workspace, viewer) => call("list", { workspace, viewer }),
1049 get: (workspace, slug, viewer) => call("get", { workspace, slug, viewer }),
1050 byRepo: (repoId) => call("by_repo", { repoId }),
1051 describe: (actor, repoId, description) => call("describe", { actor, repoId, description }),
1052 descriptions: (repoIds) => (repoIds.length ? call("descriptions", { repoIds }) : Promise.resolve({})),
1053 create: (actor, workspace, input) => call("create", { actor, workspace, input }),
1054 update: (actor, workspace, slug, changes) => call("update", { actor, workspace, slug, changes }),
1055 setProductionImage: (actor, workspace, slug, change) => call("set_production_image", { actor, workspace, slug, change }),
1056 externalProductions: () => call("external_productions", {}),
1057 deploymentsChanged: (projectId, enabled) => call("deployments_changed", { projectId, enabled }),
1058 shortcuts: (workspace, viewer) => call("shortcuts", { workspace, viewer }),
1059 pin: (actor, workspace, slug, position) => call("pin", { actor, workspace, slug, position: position ?? null }),
1060 unpin: (actor, workspace, slug) => call("unpin", { actor, workspace, slug }),
1061 reorderPins: (actor, workspace, slugs) => call("reorder_pins", { actor, workspace, slugs }),
1062 visited: (actor, projectId) => call("visited", { actor, projectId }),
1063 publicLinks: (repos) => call("public_links", { repos }),
1064 };
1065}