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,064 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 pullsForRepos: (repoIds, viewer, limit) => call("pulls_for_repos", { repoIds, viewer, limit }),
568 // Its own fields arrive in snake_case: read into camelCase here.
569 getPull: (repo, number, viewer) =>
570 call<Result<Record<string, unknown>>>("get_pull", { repo, number, viewer }).then(
571 (found): Result<PullDetail> => (found.ok ? { ok: true, value: pullDetailFromWire(found.value) } : found),
572 ),
573 updatePull: (actor, repo, number, changes) =>
574 call("update_pull", { actor, repo, number, ...changes }),
575 catchUpPull: (actor, repo, number, options = {}) => call("catch_up_pull", { actor, repo, number, ...options }),
576 setAutoMerge: (actor, repo, number, enabled, options = {}) =>
577 call("set_auto_merge", { actor, repo, number, enabled, ...options }),
578 mergeChoices: (viewer, repo, number) => call("merge_choices", { viewer, repo, number }),
579 deleteHeadBranch: (actor, repo, number) => call("delete_head_branch", { actor, repo, number }),
580 restoreHeadBranch: (actor, repo, number) => call("restore_head_branch", { actor, repo, number }),
581 commitComments: (viewer, repo, commit, page) =>
582 call("commit_comments", { viewer, repo, commit: commit ?? null, page: page ?? null }),
583 addCommitComment: (actor, repo, commit, body, at) =>
584 call("add_commit_comment", { actor, repo, commit, body, path: at?.path ?? null, line: at?.line ?? null }),
585 editCommitComment: (actor, repo, id, body) => call("edit_commit_comment", { actor, repo, id, body }),
586 deleteCommitComment: (actor, repo, id) => call("delete_commit_comment", { actor, repo, id }),
587 readyPull: (actor, repo, number, summary) =>
588 call("ready_pull", { actor, repo, number, summary }),
589 closePull: (actor, repo, number) => call("close_pull", { actor, repo, number }),
590 reopenPull: (actor, repo, number) => call("reopen_pull", { actor, repo, number }),
591 convertPullToDraft: (actor, repo, number) => call("convert_pull_to_draft", { actor, repo, number }),
592 mergePull: (actor, repo, number, options = {}) =>
593 call("merge_pull", { actor, repo, number, ...options }),
594 listActivePulls: (viewer) => call("list_active_pulls", { viewer }),
595 byAuthor: (username, viewer, filter = {}) => call("by_author", { username, viewer, ...filter }),
596 contributions: (username, viewer) => call("contributions", { username, viewer }),
597 appendSession: (actor, repo, number, entries) =>
598 call("append_session", { actor, repo, number, entries }),
599 readSession: (repo, number, viewer, afterSeq = 0) =>
600 call("read_session", { repo, number, viewer, afterSeq }),
601 // Coordination: harness sessions, claims, a work item's whole context
602 // and decision records. Their arguments are snake_case, as the Rust
603 // service reads them; what comes back is camelCase.
604 getWork: (workspace, number, viewer) => call("get_work", { workspace, number, viewer }),
605 listClaims: (workspace, viewer, filter = {}) =>
606 call("list_claims", {
607 workspace,
608 viewer,
609 repo: filter.repo ?? null,
610 state: filter.state ?? null,
611 item: filter.item ?? null,
612 }),
613 listWorkSessions: (repo, viewer, filter = {}) =>
614 call("list_work_sessions", {
615 repo,
616 viewer,
617 state: filter.state ?? null,
618 item: filter.item ?? null,
619 pull: filter.pull ?? null,
620 path: filter.path ?? null,
621 subagents: filter.subagents ?? false,
622 }),
623 getWorkSession: (repo, id, viewer, afterSeq = 0) =>
624 call("get_work_session", { repo, id, viewer, after_seq: afterSeq }),
625 listWorkspaceSessions: (workspace, viewer, filter = {}) =>
626 call("list_workspace_sessions", {
627 workspace,
628 viewer,
629 shown: filter.shown ?? "recent",
630 kind: filter.kind ?? null,
631 harness: filter.harness ?? null,
632 person: filter.person ?? null,
633 repo: filter.repo ?? null,
634 item: filter.item ?? null,
635 subagents: filter.subagents ?? false,
636 sessions_only: filter.sessionsOnly ?? false,
637 limit: filter.limit ?? null,
638 }),
639 getWorkspaceSession: (workspace, id, viewer, afterSeq = 0) =>
640 call("get_workspace_session", { workspace, id, viewer, after_seq: afterSeq }),
641 endWorkSession: (actor, repo, id) => call("end_session", { actor, repo, id, by_hand: true }),
642 titleWorkSession: (actor, repo, id, title) => call("title_session", { actor, repo, id, title }),
643 pullSessions: (repo, viewer, numbers) => call("pull_sessions", { repo, viewer, numbers }),
644 listDecisions: (thread, viewer) => call("list_decisions", { ...threadArgs(thread), viewer }),
645 };
646}
647
648export function billingClient(service: ServiceBinding): BillingApi {
649 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
650 return {
651 status: () => call("status", {}),
652 account: (workspace, viewer) => call("account", { workspace, viewer }),
653 ledger: (workspace, viewer) => call("ledger", { workspace, viewer }),
654 credits: (workspace, viewer) => call("credits", { workspace, viewer }),
655 statement: (workspace, viewer, month = null, group = "day") => call("statement", { workspace, viewer, month, group }),
656 statementEntries: (workspace, viewer, filter) =>
657 call("statement_entries", {
658 workspace,
659 viewer,
660 month: filter.month,
661 kind: filter.kind,
662 day: filter.day ?? null,
663 project: filter.project ?? null,
664 before: filter.before ?? null,
665 }),
666 usage: (workspace, viewer, since) => call("usage", { workspace, viewer, since }),
667 checkout: (actor, workspace, amountCents, returnUrl, method = "card") =>
668 call("checkout", { actor, workspace, amountCents, returnUrl, method }),
669 confirm: (workspace, viewer, session) => call("confirm", { workspace, viewer, session }),
670 trial: (workspace, exempt) => call("trial", { workspace, exempt }),
671 features: (workspace, viewer) => call("features", { workspace, viewer }),
672 subscribe: (actor, workspace, feature, returnUrl) =>
673 call("subscribe", { actor, workspace, feature, returnUrl }),
674 confirmSubscription: (workspace, viewer, session) =>
675 call("confirm_subscription", { workspace, viewer, session }),
676 cancelSubscription: (actor, workspace, feature, resume = false) =>
677 call("cancel_subscription", { actor, workspace, feature, resume }),
678 convertToPaid: (actor, workspace, returnUrl) => call("convert_to_paid", { actor, workspace, returnUrl }),
679 hasFeature: (workspace, feature) => call("has_feature", { workspace, feature }),
680 freeWorkspaces: (workspaces) => call("free_workspaces", { workspaces }),
681 chargeFeature: (charge) => call("charge_feature", charge),
682 billingPortal: (actor, workspace, returnUrl) => call("billing_portal", { actor, workspace, return_url: returnUrl }),
683 recordSandbox: (usage) => call("record_sandbox", usage),
684 limit: (workspace, viewer) => call("limit", { workspace, viewer }),
685 checkLimit: (workspace) => call("check_limit", { workspace }),
686 prices: () => call("prices", {}),
687 notePending: (workspace, source, costMicros, detail = null, month = null) =>
688 call("note_pending", { workspace, source, costMicros, detail, ...(month ? { month } : {}) }),
689 usageMeters: (workspace, viewer) => call("usage_meters", { workspace, viewer }),
690 setSpendLimit: (actor, workspace, spendLimitMicros, useFullLimit = false, raiseOnce = false) =>
691 call("set_spend_limit", { actor, workspace, spendLimitMicros, use_full_limit: useFullLimit, raise_once: raiseOnce }),
692 invoices: (workspace, viewer) => call("invoices", { workspace, viewer }),
693 entitlements: (workspace) => call("entitlements", { workspace }),
694 reserve: (reservation) => call("reserve", reservation),
695 settle: (reservationId, actualMicros) => call("settle", { reservationId, actualMicros }),
696 cardCheck: (actor, workspace, returnUrl) => call("card_check", { actor, workspace, returnUrl }),
697 confirmCardCheck: (workspace, viewer, session) => call("confirm_card_check", { workspace, viewer, session }),
698 requestLimit: (actor, workspace, request) => call("request_limit", { actor, workspace, ...request }),
699 limitRequests: (workspace, viewer) => call("limit_requests", { workspace, viewer }),
700 confirmSpike: (actor, workspace, keepGoing) => call("confirm_spike", { actor, workspace, keepGoing }),
701 usageReport: (workspace, viewer, range) =>
702 call("usage_report", { workspace, viewer, from: range.from, until: range.until, products: range.products ?? [], projects: range.projects ?? [] }),
703 setBudget: (actor, workspace, budget) => call("set_budget", { actor, workspace, ...budget }),
704 billingDetails: (workspace, viewer) => call("billing_details", { workspace, viewer }),
705 setBillingDetails: (actor, workspace, details) => call("set_billing_details", { actor, workspace, ...details }),
706 };
707}
708
709export function billingAdminClient(service: ServiceBinding): BillingAdminApi {
710 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
711 return {
712 accounts: (query) => call("admin_accounts", { query: query ?? null }),
713 account: (id) => call("admin_account", { id }),
714 setTerms: (id, terms, by) => call("admin_set_terms", { id, terms, by }),
715 setAllowances: (id, allowances, note, by) => call("admin_set_allowances", { id, allowances, note, by }),
716 complimentary: (workspace) => call("admin_complimentary", { workspace }),
717 setComplimentary: (workspace, terms, note, by) =>
718 call("admin_set_complimentary", {
719 workspace,
720 allowance_micros: terms.allowanceMicros,
721 unlimited: terms.unlimited,
722 fee_cents: terms.feeCents,
723 charge_past_allowance: terms.chargePastAllowance,
724 note,
725 by,
726 }),
727 endComplimentary: (workspace, note, by) => call("admin_end_complimentary", { workspace, note, by }),
728 createEnterprise: (name, workspaces, by) => call("admin_create_enterprise", { name, workspaces, by }),
729 attach: (workspace, account, by) => call("admin_attach", { workspace, account, by }),
730 credit: (workspace, amountMicros, note, by, options = { kind: "goodwill" }) =>
731 call("admin_credit", {
732 workspace,
733 amount_micros: amountMicros,
734 note,
735 by,
736 kind: options.kind,
737 expires_at: options.expiresAt ?? null,
738 refund_for: options.refundFor ?? null,
739 refund_day: options.refundDay ?? null,
740 }),
741 credits: (filter = {}) =>
742 call("admin_credits", {
743 workspace: filter.workspace ?? null,
744 kind: filter.kind ?? null,
745 month: filter.month ?? null,
746 by: filter.by ?? null,
747 }),
748 revokeCredit: (id, note, by) => call("admin_revoke_credit", { id, note, by }),
749 resetBilling: (workspace, confirm, note, by) => call("admin_reset_billing", { workspace, confirm, note, by }),
750 detachTestStripe: (a) =>
751 call("admin_detach_test_stripe", {
752 workspace: a.workspace ?? null,
753 exclude: a.exclude ?? null,
754 dry_run: a.dryRun,
755 cancel_at_stripe: a.cancelAtStripe ?? false,
756 confirm: a.confirm ?? "",
757 by: a.by,
758 }),
759 billingLink: (workspace, by) => call("admin_billing_link", { workspace, by }),
760 stripe: (fix = false, by) => call("admin_stripe", { fix, by: by ?? null }),
761 enterpriseBilling: (id, email, by) => call("admin_enterprise_billing", { id, email, by }),
762 enterpriseAddress: (id, address, taxIdType, taxId, by) => call("admin_enterprise_address", { id, address, taxIdType, taxId, by }),
763 invoiceEnterprise: (id, by) => call("admin_invoice_enterprise", { id, by }),
764 accountsFor: (workspaces) => call("admin_accounts", { query: null, workspaces }),
765 signals: () => call("admin_signals", {}),
766 overview: () => call("admin_overview", {}),
767 sales: (workspace) => call("admin_sales", { workspace }),
768 setSales: (workspace, record, by) =>
769 call("admin_set_sales", {
770 workspace,
771 stage: record.stage,
772 owner: record.owner ?? null,
773 next_step: record.nextStep ?? null,
774 next_at: record.nextAt ?? null,
775 by,
776 }),
777 addNote: (workspace, text, by) => call("admin_add_note", { workspace, text, by }),
778 workspaceInvoices: (workspace) => call("admin_workspace_invoices", { workspace }),
779 allInvoices: (filter = {}) => call("admin_invoices", { status: filter.status ?? null, month: filter.month ?? null }),
780 audit: (filter = {}) =>
781 call("admin_audit", { by: filter.by ?? null, action: filter.action ?? null, before: filter.before ?? null }),
782 limitRequests: (status = "open") => call("admin_limit_requests", { status }),
783 decideLimitRequest: (id, decision, amountMicros, note, by) =>
784 call("admin_decide_limit_request", { id, decision, amount_micros: amountMicros, note, by }),
785 overages: () => call("admin_overages", {}),
786 goodwill: (workspace, amountMicros, reason, by, day = null, requestKey = null) =>
787 call("admin_goodwill", { workspace, amount_micros: amountMicros, reason, by, day, request_key: requestKey }),
788 velocity: () => call("admin_velocity", {}),
789 recordPayment: (workspace, amountMicros, reference, note, by) =>
790 call("admin_record_payment", { workspace, amount_micros: amountMicros, reference, note, by }),
791 costs: (days) => call("admin_costs", { days: days ?? null }),
792 costAlerts: () => call("admin_cost_alerts", {}),
793 spendCaps: () => call("admin_spend_caps", {}),
794 liftBreaker: (note, by) => call("admin_lift_breaker", { note, by }),
795 platformGuard: () => call("admin_platform_guard", {}),
796 setPause: (level, paused, note, by) => call("admin_set_pause", { level, paused, note, by }),
797 decideProposal: (id, decision, note, by) => call("admin_decide_proposal", { id, decision, note, by }),
798 setCostSettings: (settings, by) => call("admin_set_cost_settings", { settings, by }),
799 setCostMapping: (mapping, by) =>
800 call("admin_set_cost_mapping", {
801 product: mapping.product,
802 meter: mapping.meter,
803 bucket: mapping.bucket ?? "",
804 price_meter: mapping.priceMeter ?? null,
805 own_meter: mapping.ownMeter ?? null,
806 scale_to_own: mapping.scaleToOwn ?? false,
807 drift_percent: mapping.driftPercent ?? null,
808 note: mapping.note ?? "",
809 remove: mapping.remove ?? false,
810 by,
811 }),
812 runCosts: (by) => call("admin_run_costs", { by }),
813 };
814}
815
816export function eventsClient(service: ServiceBinding): EventsApi {
817 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
818 return {
819 publish: (events) => call("publish", { events }),
820 list: (query) => call("list", query),
821 activityDigest: (args) => call("activity_digest", args),
822 };
823}
824
825export function integrationsClient(service: ServiceBinding): IntegrationsApi {
826 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
827 return {
828 list: (workspace, viewer) => call("list", { workspace, viewer }),
829 connect: (actor, workspace, input) => call("connect", { actor, workspace, ...input }),
830 update: (actor, workspace, id, input) => call("update", { actor, workspace, id, ...input }),
831 disconnect: (actor, workspace, id) => call("disconnect", { actor, workspace, id }),
832 test: (actor, workspace, id) => call("test", { actor, workspace, id }),
833 deliveries: (workspace, viewer, id) => call("deliveries", { workspace, viewer, id }),
834 resolve: (workspace, viewer, reference) => call("resolve", { workspace, viewer, reference }),
835 import: (actor, workspace, reference, options) =>
836 call("import", { actor, workspace, reference, repo: options?.repo ?? null, targets: options?.targets ?? [] }),
837 links: (workspace, number) => call("links", { workspace, number }),
838 };
839}
840
841/**
842 * A workspace's AI providers and Ask g1t. Kept by the integrations service,
843 * so it is built on the same binding, with its own methods.
844 */
845export function aiClient(service: ServiceBinding): AiApi {
846 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
847 return {
848 list: (workspace, viewer) => call("ai_list", { workspace, viewer }),
849 add: (actor, workspace, input) => call("ai_add", { actor, workspace, ...input }),
850 update: (actor, workspace, id, input) => call("ai_update", { actor, workspace, id, ...input }),
851 remove: (actor, workspace, id) => call("ai_remove", { actor, workspace, id }),
852 test: (actor, workspace, id) => call("ai_test", { actor, workspace, id }),
853 askSettings: (workspace, viewer) => call("ask_settings", { workspace, viewer }),
854 setAskSettings: (actor, workspace, providerId, model) =>
855 call("set_ask_settings", { actor, workspace, provider_id: providerId, model }),
856 // Streamed: the response itself, not its parsed body.
857 ask: (actor, workspace, messages, page, signal) =>
858 service.fetch("https://service/rpc/ask", {
859 method: "POST",
860 headers: { "content-type": "application/json" },
861 body: JSON.stringify({ actor, workspace, messages, page }),
862 signal,
863 }),
864 };
865}
866
867export function webhooksClient(service: ServiceBinding): WebhooksApi {
868 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
869 return {
870 list: (viewer, owner) => call("list", { viewer, ...owner }),
871 create: (actor, owner, input) => call("create", { actor, ...owner, ...input }),
872 update: (actor, owner, id, input) => call("update", { actor, ...owner, id, ...input }),
873 delete: (actor, owner, id) => call("delete", { actor, ...owner, id }),
874 ping: (actor, owner, id) => call("ping", { actor, ...owner, id }),
875 deliveries: (viewer, owner, id) => call("deliveries", { viewer, ...owner, id }),
876 redeliver: (actor, owner, deliveryId) => call("redeliver", { actor, ...owner, deliveryId }),
877 };
878}
879
880export function actionsClient(service: ServiceBinding): ActionsApi {
881 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
882 return {
883 workflows: (repo, viewer) => call("workflows", { repo, viewer }),
884 runs: (repo, viewer, filter = {}) => call("runs", { repo, viewer, ...filter }),
885 run: (repo, viewer, id, attempt) => call("run", { repo, viewer, id, attempt: attempt ?? null }),
886 logs: (repo, viewer, job, after = 0) => call("logs", { repo, viewer, job, after }),
887 summaries: (repo, viewer, id, attempt) => call("summaries", { repo, viewer, id, attempt: attempt ?? null }),
888 jobLogText: (repo, viewer, job) => call("job_log_text", { repo, viewer, job }),
889 runLogs: (repo, viewer, id, attempt) => call("run_logs", { repo, viewer, id, attempt: attempt ?? null }),
890 dispatch: (actor, repo, workflow, ref, inputs) => call("dispatch", { actor, repo, workflow, ref, inputs }),
891 cancel: (actor, repo, id, force = false) => call("cancel", { actor, repo, id, force }),
892 rerun: (actor, repo, id, failedOnly = false, options = {}) =>
893 call("rerun", { actor, repo, id, failed_only: failedOnly, job: options.job ?? null, debug: options.debug ?? false }),
894 setWorkflowEnabled: (actor, repo, workflow, enabled) =>
895 call("set_workflow_enabled", { actor, repo, workflow, enabled }),
896 settings: (actor, owner, kind) => call("settings", { actor, ...owner, kind }),
897 setSetting: (actor, owner, kind, name, value, options = {}) =>
898 call("set_setting", { actor, ...owner, kind, name, value, ...options }),
899 deleteSetting: (actor, owner, kind, name, id) => call("delete_setting", { actor, ...owner, kind, name, id }),
900 approveRun: (actor, repo, id) => call("approve_run", { actor, repo, id }),
901 pendingDeployments: (repo, viewer, id) => call("pending_deployments", { repo, viewer, id }),
902 reviewDeployments: (actor, repo, id, state, environments = [], comment) =>
903 call("review_deployments", { actor, repo, id, state, environments, comment: comment ?? null }),
904 actionsSettings: (repo, viewer) => call("actions_settings", { repo, viewer }),
905 setActionsSettings: (actor, repo, change) => call("set_actions_settings", { actor, repo, ...change }),
906 workspaceActionsSettings: (workspace, viewer) => call("workspace_actions_settings", { workspace, viewer }),
907 setWorkspaceActionsSettings: (actor, workspace, change) =>
908 call("set_workspace_actions_settings", { actor, workspace, ...change }),
909 workspaceManagedWorkflows: (workspace, viewer) => call("workspace_managed_workflows", { workspace, viewer }),
910 setWorkspaceManagedWorkflow: (actor, workspace, name, change, create = false) =>
911 call("set_workspace_managed_workflow", { actor, workspace, name, create, ...change }),
912 removeWorkspaceManagedWorkflow: (actor, workspace, name) =>
913 call("remove_workspace_managed_workflow", { actor, workspace, name }),
914 environments: (repo, viewer) => call("environments", { repo, viewer }),
915 setEnvironment: (actor, repo, name, change) => call("set_environment", { actor, repo, name, ...change }),
916 deleteEnvironment: (actor, repo, name) => call("delete_environment", { actor, repo, name }),
917 artifacts: (repo, viewer, filter = {}) => call("artifacts", { repo, viewer, ...filter }),
918 artifactDownload: (repo, viewer, by) => call("artifact_download", { repo, viewer, ...by }),
919 deleteArtifact: (actor, repo, id) => call("delete_artifact", { actor, repo, id }),
920 artifactRetention: (repo, viewer, days) => call("artifact_retention", { repo, viewer, days }),
921 };
922}
923
924
925/** Staff-only self-hosted runners, on the actions service: only sudo calls it. */
926export function runnersAdminClient(service: ServiceBinding): RunnersAdminApi {
927 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
928 return {
929 list: (workspace) => call("admin_runners", { workspace }),
930 remove: (workspace, id, staff) => call("admin_remove_runners", { workspace, id, staff }),
931 };
932}
933
934/** Self-hosted runners, kept by the actions service. */
935export function runnersClient(service: ServiceBinding): RunnersApi {
936 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
937 return {
938 stuck: (viewer) => call("stuck_jobs", { viewer }),
939 activity: (actor, workspace) => call("runner_activity", { actor, workspace }),
940 list: (actor, owner) => call("runners", { actor, ...owner }),
941 createToken: (actor, owner, group) => call("create_registration_token", { actor, ...owner, group }),
942 remove: (actor, owner, id) => call("remove_runner", { actor, ...owner, id }),
943 groups: (actor, workspace) => call("runner_groups", { actor, workspace }),
944 setGroup: (actor, workspace, group) => call("set_runner_group", { actor, workspace, ...group }),
945 deleteGroup: (actor, workspace, id) => call("delete_runner_group", { actor, workspace, id }),
946 settings: (actor, owner) => call("runner_settings", { actor, ...owner }),
947 setSettings: (actor, owner, change) => call("set_runner_settings", { actor, ...owner, ...change }),
948 reportDesktop: (actor, report) => call("report_desktop", { actor, ...report }),
949 desktops: (actor, workspace) => call("desktop_runners", { actor, workspace }),
950 };
951}
952
953export function deploymentsClient(service: ServiceBinding): DeploymentsApi {
954 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
955 return {
956 settings: (project, viewer) => call("settings", { project, viewer }),
957 updateSettings: (actor, project, changes) => call("update_settings", { actor, project, changes }),
958 list: (project, viewer) => call("list", { project, viewer }),
959 get: (project, id, viewer) => call("get", { project, id, viewer }),
960 redeploy: (actor, project, branch) => call("redeploy", { actor, project, branch }),
961 takeDown: (actor, project, branch) => call("take_down", { actor, project, branch }),
962 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
963 usage: (workspace, viewer) => call("usage", { workspace, viewer }),
964 domains: (project, viewer) => call("domains", { project, viewer }),
965 addDomain: (actor, project, hostname, options = {}) =>
966 call("add_domain", { actor, project, hostname, twin: !!options.twin }),
967 removeDomain: (actor, project, id) => call("remove_domain", { actor, project, id }),
968 refreshDomain: (actor, project, id) => call("refresh_domain", { actor, project, id }),
969 repoDeployments: (repo, viewer, filter = {}) => call("list_deployments", { repo, viewer, ...filter }),
970 repoDeployment: (repo, id, viewer) => call("get_deployment", { repo, id, viewer }),
971 environments: (repo, viewer) => call("list_environments", { repo, viewer }),
972 createDeployment: (actor, repo, input) => call("create_deployment", { repo, actor, ...input }),
973 createDeploymentStatus: (actor, repo, id, input) => call("create_deployment_status", { repo, actor, id, ...input }),
974 shipped: (workspace, viewer, repos) => call("shipped", { workspace, viewer, repos }),
975 };
976}
977
978/** Packages: the registries beside the code (services/packages). */
979export function packagesClient(service: ServiceBinding): PackagesApi {
980 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
981 return {
982 list: (workspace, viewer, filter = {}) =>
983 call("list_packages", {
984 workspace,
985 viewer,
986 ecosystem: filter.ecosystem ?? null,
987 repo_id: filter.repoId ?? null,
988 query: filter.query ?? null,
989 }),
990 get: (workspace, ecosystem, name, viewer) => call("get_package", { workspace, ecosystem, name, viewer }),
991 deleteVersion: (actor, workspace, ecosystem, name, version, surface) =>
992 call("delete_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
993 deletePackage: (actor, workspace, ecosystem, name, surface) =>
994 call("delete_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
995 set: (actor, workspace, ecosystem, name, change, surface) =>
996 call("set_package", {
997 actor,
998 workspace,
999 ecosystem,
1000 name,
1001 visibility: change.visibility ?? null,
1002 link: change.link ?? null,
1003 unlink: change.unlink ?? false,
1004 inherit_access: change.inheritAccess ?? null,
1005 surface: surface ?? null,
1006 }),
1007 settings: (workspace, ecosystem, name, viewer) => call("package_settings", { workspace, ecosystem, name, viewer }),
1008 deleted: (workspace, viewer) => call("deleted_packages", { workspace, viewer }),
1009 restorePackage: (actor, workspace, ecosystem, name, surface) =>
1010 call("restore_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
1011 restoreVersion: (actor, workspace, ecosystem, name, version, surface) =>
1012 call("restore_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
1013 setAccess: (actor, workspace, ecosystem, name, who, role, surface) =>
1014 call("set_package_access", {
1015 actor,
1016 workspace,
1017 ecosystem,
1018 name,
1019 user: "user" in who ? who.user : null,
1020 team: "team" in who ? who.team : null,
1021 role,
1022 surface: surface ?? null,
1023 }),
1024 removeAccess: (actor, workspace, ecosystem, name, who, surface) =>
1025 call("remove_package_access", {
1026 actor,
1027 workspace,
1028 ecosystem,
1029 name,
1030 user: "user" in who ? who.user : null,
1031 team: "team" in who ? who.team : null,
1032 surface: surface ?? null,
1033 }),
1034 setActionsAccess: (actor, workspace, ecosystem, name, repo, role, surface) =>
1035 call("set_actions_access", { actor, workspace, ecosystem, name, repo, role, surface: surface ?? null }),
1036 removeActionsAccess: (actor, workspace, ecosystem, name, repo, surface) =>
1037 call("remove_actions_access", { actor, workspace, ecosystem, name, repo, surface: surface ?? null }),
1038 storage: (workspace) => call("storage", { workspace }),
1039 storageAll: () => call("storage_all", {}),
1040 syncComposer: (repoId) => call("sync_composer", { repo_id: repoId }),
1041 };
1042}
1043
1044export function projectsClient(service: ServiceBinding): ProjectsApi {
1045 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
1046 return {
1047 list: (workspace, viewer) => call("list", { workspace, viewer }),
1048 get: (workspace, slug, viewer) => call("get", { workspace, slug, viewer }),
1049 byRepo: (repoId) => call("by_repo", { repoId }),
1050 describe: (actor, repoId, description) => call("describe", { actor, repoId, description }),
1051 descriptions: (repoIds) => (repoIds.length ? call("descriptions", { repoIds }) : Promise.resolve({})),
1052 create: (actor, workspace, input) => call("create", { actor, workspace, input }),
1053 update: (actor, workspace, slug, changes) => call("update", { actor, workspace, slug, changes }),
1054 setProductionImage: (actor, workspace, slug, change) => call("set_production_image", { actor, workspace, slug, change }),
1055 externalProductions: () => call("external_productions", {}),
1056 deploymentsChanged: (projectId, enabled) => call("deployments_changed", { projectId, enabled }),
1057 shortcuts: (workspace, viewer) => call("shortcuts", { workspace, viewer }),
1058 pin: (actor, workspace, slug, position) => call("pin", { actor, workspace, slug, position: position ?? null }),
1059 unpin: (actor, workspace, slug) => call("unpin", { actor, workspace, slug }),
1060 reorderPins: (actor, workspace, slugs) => call("reorder_pins", { actor, workspace, slugs }),
1061 visited: (actor, projectId) => call("visited", { actor, projectId }),
1062 publicLinks: (repos) => call("public_links", { repos }),
1063 };
1064}