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