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.

g1t.sh
996 linesCodeBlameRaw
1import type { ActionsApi } from "./actions";
2import type { BillingAdminApi, BillingApi } from "./billing";
3import type { DeploymentsApi } from "./deployments";
4import type { ProjectsApi } from "./projects";
5import type { EventsApi } from "./events";
6import type { IdentityAdminApi, IdentityApi } from "./identity";
7import type { IntegrationsApi } from "./integrations";
8import type { PackagesApi } from "./packages";
9import type { WebhooksApi } from "./webhooks";
10import type { ReposApi } from "./repos";
11import type { PullDetail, WorkApi } from "./work";
12import type { Result } from "./result";
13import type { RunnerComputerApi } from "./runner";
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 checkInvite: (code, client, options = {}) =>
151 call("check_invite", {
152 code,
153 client: client ?? null,
154 viewer: options.viewer ?? null,
155 any_status: options.anyStatus ?? false,
156 email_proof: options.emailProof ?? null,
157 }),
158 acceptInvite: (user, code) => call("accept_invite", { user, code }),
159 inviteMember: (actor, slug, who) =>
160 call("invite_member", { actor, slug, email: who.email ?? "", username: who.username ?? null, role: who.role ?? null, message: who.message ?? null }),
161 listInvitations: (user) => call("list_invitations", { user }),
162 acceptInvitation: (user, id) => call("accept_invitation", { user, id, surface: "web" }),
163 declineInvitation: (user, id) => call("decline_invitation", { user, id, surface: "web" }),
164 findPeople: (query, limit) => call("find_people", { query, limit: limit ?? null }),
165 workspaceInvites: (slug, viewer) => call("workspace_invites", { slug, viewer }),
166 revokeWorkspaceInvite: (actor, slug, id) => call("revoke_workspace_invite", { actor, slug, id }),
167 resendWorkspaceInvite: (actor, slug, id) => call("resend_workspace_invite", { actor, slug, id }),
168 userForGitCredentials: (username, secret) =>
169 call("user_for_git_credentials", { username, secret }),
170 userForAccessToken: (token) => call("user_for_access_token", { token }),
171 userForSshKey: (fingerprint) => call("user_for_ssh_key", { fingerprint }),
172 userByUsername: (username) => call("user_by_username", { username }),
173 usernames: (ids) => call("usernames", { ids }),
174 usersForAudience: (ids) => call("users_for_audience", { ids }),
175 profile: (username) => call("profile", { username }),
176 updateProfile: (actor, fields) => call("update_profile", { actor, ...fields }),
177 profileWorkspaces: (username, viewer, publicIn) =>
178 call("profile_workspaces", { username, viewer, public: publicIn }),
179 dockPins: (user, workspace) => call("dock_pins", { user, workspace }),
180 setDockPins: (user, workspace, apps) => call("set_dock_pins", { user, workspace, apps }),
181 soundSettings: (user) => call("sound_settings", { user }),
182 setSoundSettings: (user, change) => call("set_sound_settings", { user, change }),
183 listSshKeys: (user) => call("list_ssh_keys", { user }),
184 addSshKey: (user, title, publicKey) =>
185 call("add_ssh_key", { user, title, publicKey }),
186 removeSshKey: (user, id) => call("remove_ssh_key", { user, id }),
187 listAccessTokens: (user) => call("list_access_tokens", { user }),
188 createAccessToken: (user, name, ttlSeconds, grant) =>
189 call("create_access_token", {
190 user,
191 name,
192 ttlSeconds,
193 scopes: grant?.scopes ?? null,
194 listed: grant?.listed ?? false,
195 }),
196 createAgentToken: (onBehalfOf, scope, ttlSeconds) =>
197 call("create_agent_token", { onBehalfOf, scope, ttlSeconds }),
198 removeAccessToken: (user, id) => call("remove_access_token", { user, id }),
199 createRunCredential: (input) => call("create_run_credential", input),
200 bindRunCredentials: (tokenHashes, runId) => call("bind_run_credentials", { tokenHashes, runId }),
201 revokeRunCredentials: (target) => call("revoke_run_credentials", target),
202 // Who has access to a repository; see access.ts.
203 repoAccess: (owner, name, viewer) => call("repo_access", { viewer, path: { namespace: owner, name } }),
204 addCollaborator: (actor, owner, name, invitee, role) =>
205 call("add_collaborator", { actor, path: { namespace: owner, name }, invitee, role }),
206 setCollaboratorRole: (actor, owner, name, username, role) =>
207 call("set_collaborator_role", { actor, path: { namespace: owner, name }, username, role }),
208 removeCollaborator: (actor, owner, name, username) =>
209 call("remove_collaborator", { actor, path: { namespace: owner, name }, username }),
210 collaboratorPermission: (viewer, owner, name, username) =>
211 call("collaborator_permission", { viewer, path: { namespace: owner, name }, username }),
212 myRepoInvitations: (user) => call("my_repo_invitations", { user }),
213 respondRepoInvitation: (user, id, accept) => call("respond_repo_invitation", { user, id, accept }),
214 revokeRepoInvitation: (actor, owner, name, id) =>
215 call("revoke_repo_invitation", { actor, path: { namespace: owner, name }, id }),
216 setBasePermission: (actor, slug, base) => call("set_base_permission", { actor, slug, base_permission: base }),
217 outsideCollaborators: (viewer, slug) => call("outside_collaborators", { viewer, slug }),
218 // A repository's deploy keys; see deploy-keys.ts.
219 listDeployKeys: (viewer, owner, name) => call("list_deploy_keys", { viewer, path: { namespace: owner, name } }),
220 addDeployKey: (actor, owner, name, key) =>
221 call("add_deploy_key", { actor, path: { namespace: owner, name }, title: key.title, key: key.key, read_only: key.readOnly }),
222 removeDeployKey: (actor, owner, name, id) => call("remove_deploy_key", { actor, path: { namespace: owner, name }, id }),
223 // Teams; see teams.ts.
224 listTeams: (viewer, workspace, query) => call("list_teams", { viewer, workspace, query: query ?? null }),
225 getTeam: (viewer, workspace, team) => call("get_team", { viewer, workspace, team }),
226 createTeam: (actor, workspace, team) => call("create_team", { actor, workspace, ...team }),
227 setTeamCreation: (actor, slug, setting) => call("set_team_creation", { actor, slug, team_creation: setting }),
228 updateTeam: (actor, workspace, team, changes) => call("update_team", { actor, workspace, team, ...changes }),
229 deleteTeam: (actor, workspace, team) => call("delete_team", { actor, workspace, team }),
230 teamMembers: (viewer, workspace, team, includeChildTeams) =>
231 call("team_members", { viewer, workspace, team, include_child_teams: includeChildTeams ?? false }),
232 setTeamMember: (actor, workspace, team, username, role) =>
233 call("set_team_member", { actor, workspace, team, username, role }),
234 removeTeamMember: (actor, workspace, team, username) =>
235 call("remove_team_member", { actor, workspace, team, username }),
236 childTeams: (viewer, workspace, team) => call("child_teams", { viewer, workspace, team }),
237 teamRepos: (viewer, workspace, team) => call("team_repos", { viewer, workspace, team }),
238 setTeamRepo: (actor, workspace, team, owner, name, role) =>
239 call("set_team_repo", { actor, workspace, team, repo: { namespace: owner, name }, role }),
240 removeTeamRepo: (actor, workspace, team, owner, name) =>
241 call("remove_team_repo", { actor, workspace, team, repo: { namespace: owner, name } }),
242 userTeams: (viewer, workspace, username) => call("user_teams", { viewer, workspace, username }),
243 teamMemberships: (viewer, workspace) => call("team_memberships", { viewer, workspace }),
244 teamAgents: (viewer, workspace, team) => call("team_agents", { viewer, workspace, team }),
245 setTeamAgent: (actor, workspace, team, agentId) => call("set_team_agent", { actor, workspace, team, agent_id: agentId }),
246 removeTeamAgent: (actor, workspace, team, agentId) => call("remove_team_agent", { actor, workspace, team, agent_id: agentId }),
247 agentTeams: (workspace, agentId) => call("agent_teams", { workspace, agent_id: agentId }),
248 teamAgentIndex: (workspace) => call("team_agent_index", { workspace }),
249 adoptAgentTeams: (workspaceId, agents) => call("adopt_agent_teams", { workspace_id: workspaceId, agents }),
250 // People; see people.ts.
251 peopleDirectory: (viewer, workspace) => call("people_directory", { viewer, workspace }),
252 setMemberProfile: (actor, workspace, username, changes) => call("set_member_profile", { actor, workspace, username, ...changes }),
253 };
254}
255
256/**
257 * The slug a renamed workspace has now, for a `workspace.renamed` handler:
258 * asked of identity by the workspace's id, so that renames delivered twice
259 * or out of order converge. Falls back to the event's `to`.
260 */
261export async function currentWorkspaceSlug(
262 identity: ServiceBinding,
263 renamed: { workspaceId: string; to: string },
264): Promise<string> {
265 const names = await identityClient(identity).usernames([renamed.workspaceId]);
266 return names[renamed.workspaceId] ?? renamed.to;
267}
268
269/** The slugs whose rows move to `current`: the two a rename names, less `current`. */
270export function staleSlugs(renamed: { from: string; to: string }, current: string): string[] {
271 return [...new Set([renamed.from, renamed.to])].filter((slug) => slug !== current);
272}
273
274/**
275 * Where a transferred repository is now, as `namespace/name`, for a
276 * `repo.transferred` handler: asked of repos by id, so transfers delivered
277 * twice or out of order converge. Falls back to the event's destination.
278 */
279export async function currentRepoPath(
280 repos: ServiceBinding,
281 transferred: { repoId: string; name: string; to: string },
282): Promise<string> {
283 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: transferred.repoId });
284 return path ? `${path.namespace}/${path.name}` : `${transferred.to}/${transferred.name}`;
285}
286
287/** The paths whose rows move to `current`: the two a transfer names, less `current`. */
288export function stalePaths(transferred: { name: string; from: string; to: string }, current: string): string[] {
289 return [...new Set([transferred.from, transferred.to].map((ns) => `${ns}/${transferred.name}`))].filter(
290 (path) => path !== current,
291 );
292}
293
294/**
295 * A repository's path change, from `repo.transferred` or `repo.renamed`,
296 * read the same way: the two paths (`namespace/name`) the event names, old
297 * then new. Null for any other event.
298 */
299export type RepoMove = { repoId: string; paths: [string, string] };
300
301export function repoMove(event: { type: string; data: unknown }): RepoMove | null {
302 const data = event.data as Record<string, string>;
303 if (event.type === "repo.transferred") {
304 return { repoId: data.repoId!, paths: [`${data.from}/${data.name}`, `${data.to}/${data.name}`] };
305 }
306 if (event.type === "repo.renamed") {
307 return { repoId: data.repoId!, paths: [`${data.namespace}/${data.from}`, `${data.namespace}/${data.to}`] };
308 }
309 return null;
310}
311
312/**
313 * Where a moved repository is now, as `namespace/name`: asked of repos by
314 * id, so moves delivered twice or out of order converge. Falls back to the
315 * event's new path.
316 */
317export async function currentMovedPath(repos: ServiceBinding, move: RepoMove): Promise<string> {
318 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: move.repoId });
319 return path ? `${path.namespace}/${path.name}` : move.paths[1];
320}
321
322/** The paths whose rows move to `current`: the two a move names, less `current`. */
323export function staleMovedPaths(move: RepoMove, current: string): string[] {
324 return [...new Set(move.paths)].filter((path) => path !== current);
325}
326
327/** Staff-only identity. Only sudo binds to it; see `IdentityAdminApi`. */
328export function identityAdminClient(service: ServiceBinding): IdentityAdminApi {
329 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
330 return {
331 workspaces: (query) => call("admin_workspaces", { query: query ?? null }),
332 workspace: (slug) => call("admin_workspace", { slug }),
333 invites: (query) => call("admin_invites", { query: query ?? null }),
334 revokeInvite: (id, staff) => call("admin_revoke_invite", { id, staff }),
335 suspendUser: (name, suspend, reason, staff) => call("admin_suspend_user", { name, suspend, reason, staff }),
336 suspendWorkspace: (name, suspend, reason, staff) => call("admin_suspend_workspace", { name, suspend, reason, staff }),
337 blockedDomains: () => call("admin_blocked_domains", {}),
338 blockDomain: (domain, block, reason, staff) => call("admin_block_domain", { domain, block, reason, staff }),
339 deletedWorkspaces: () => call("admin_deleted_workspaces", {}),
340 restoreWorkspace: (workspaceId, staff) => call("admin_restore_workspace", { workspaceId, staff }),
341 purgeWorkspace: (workspaceId, staff, confirm) => call("admin_purge_workspace", { workspaceId, staff, confirm }),
342 aliases: () => call("admin_aliases", {}),
343 setAlias: (alias, workspace, note, staff) => call("admin_set_alias", { alias, workspace, note, staff }),
344 removeAlias: (alias, reason, staff) => call("admin_remove_alias", { alias, reason, staff }),
345 };
346}
347
348export function reposClient(service: ServiceBinding): ReposApi {
349 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
350 return {
351 get: (path, viewer) => call("get", { path, viewer }),
352 getById: (id, viewer) => call("get_by_id", { id, viewer }),
353 readable: (ids, viewer) => call("readable", { ids, viewer }),
354 publicNamespaces: (ownerId) => call("public_namespaces", { ownerId }),
355 list: (viewer, options = {}) => call("list", { viewer, ...options }),
356 create: (owner, input) => call("create", { owner, ...input }),
357 update: (actor, path, changes) => call("update", { actor, path, ...changes }),
358 transfer: (actor, path, to) => call("transfer", { actor, path, to }),
359 delete: (actor, path, confirm) => call("delete", { actor, path, confirm }),
360 deleted: (viewer, namespace) => call("deleted", { viewer, namespace }),
361 restore: (actor, path) => call("restore", { actor, path }),
362 purge: (actor, path, confirm) => call("purge", { actor, path, confirm }),
363 rename: (actor, path, name) => call("rename", { actor, path, name }),
364 archive: (actor, path, archived) => call("archive", { actor, path, archived }),
365 setVisibility: (actor, path, isPrivate, confirm) => call("set_visibility", { actor, path, isPrivate, confirm }),
366 setDefaultBranch: (actor, path, branch) => call("set_default_branch", { actor, path, branch }),
367 renameBranch: (actor, path, from, to) => call("rename_branch", { actor, path, from, to }),
368 createBranch: (actor, path, name, from = "") => call("create_branch", { actor, path, name, from }),
369 removeBranch: (actor, path, branch, head) => call("remove_branch", { actor, path, branch, head }),
370 resolveBranch: (repoId, branch) => call("resolve_branch", { repoId, branch }),
371 statusById: (id) => call("status_by_id", { id }),
372 storageOptions: () => call("storage_options", {}),
373 resolvePath: (path) => call("resolve_path", { path }),
374 tree: (path, viewer, ref, treePath) =>
375 call("tree", { path, viewer, ref, treePath }),
376 blob: (path, viewer, ref, filePath) =>
377 call("blob", { path, viewer, ref, filePath }),
378 log: (path, viewer, ref, limit) => call("log", { path, viewer, ref, limit }),
379 blame: (path, viewer, ref, filePath) => call("blame", { path, viewer, ref, filePath }),
380 forkForPull: (sourceId, pullId, actor) =>
381 call("fork_for_pull", { sourceId, pullId, actor }),
382 gitAccess: (path, viewer, service) =>
383 call("git_access", { path, viewer, service }),
384 branches: (path, viewer) => call("branches", { path, viewer }),
385 lastCommits: (path, viewer, ref, treePath) => call("last_commits", { path, viewer, ref, treePath }),
386 branchDrift: (path, viewer, base, heads) => call("branch_drift", { path, viewer, base, heads }),
387 tags: (path, viewer) => call("tags", { path, viewer }),
388 about: (path, viewer) => call("about", { path, viewer }),
389 languages: (path, viewer) => call("languages", { path, viewer }),
390 contributors: (path, viewer) => call("contributors", { path, viewer }),
391 license: (path, viewer) => call("license", { path, viewer }),
392 stars: (path, viewer) => call("stars", { path, viewer }),
393 star: (actor, path, starred) => call("star", { path, actor, starred }),
394 stargazers: (path, viewer, page) => call("stargazers", { path, viewer, page: page ?? null }),
395 starred: (username, viewer) => call("starred", { username, viewer }),
396 releases: (path, viewer) => call("releases", { path, viewer }),
397 release: (path, viewer, which) => call("release", { path, viewer, id: which.id ?? null, tag: which.tag ?? null, latest: which.latest ?? false }),
398 createRelease: (actor, path, release) => call("create_release", { path, actor, ...release }),
399 updateRelease: (actor, path, id, change) => call("update_release", { path, actor, id, ...change }),
400 deleteRelease: (actor, path, id) => call("delete_release", { path, actor, id }),
401 listFiles: (repoId, ref, limit, options) => call("list_files", { repoId, ref, skipDirs: [], limit, links: options?.links ?? false }),
402 openArchiveToken: (path, token) => call("open_archive_token", { path, token }),
403 rawBlobs: (repoId, hashes, maxBytes) => call("raw_blobs", { repoId, hashes, maxBytes }),
404 rawFile: (repoId, ref, path, maxBytes) => call("raw_file", { repoId, ref, path, maxBytes }),
405 commitFile: (repo, actor, file) => call("commit_file", { repo, actor, ...file }),
406 land: (sourceId, actor, branch) => call("land", { sourceId, actor, branch }),
407 compare: (repoId, viewer, base, head, baseBranch) => call("compare", { repoId, viewer, base, head, baseBranch }),
408 claimBackups: (limit, maxRunning) => call("claim_backups", { limit, maxRunning }),
409 // The sandbox's own calls are snake_case (they come through the API).
410 failBackup: (jobId, token, error) => call("backup_fail", { job_id: jobId, token, error }),
411 };
412}
413
414/**
415 * `PullDetail`'s own fields that the work service writes in snake_case:
416 * `g1t_contracts::work::PullDetail` has no camelCase renaming, though what
417 * it holds (`Pull`, `CheckRun` and the rest) does. Each with its name here.
418 */
419const PULL_DETAIL_FIELDS = [
420 ["review_pending", "reviewPending"],
421 ["earlier_checks", "earlierChecks"],
422 ["required_checks", "requiredChecks"],
423 ["code_owners", "codeOwners"],
424] as const;
425
426/**
427 * A pull request's detail as the work service sent it, with its own fields
428 * in the camelCase this package uses: read at the edge, by `workClient`'s
429 * `getPull`. Either spelling is taken, so a service that already sends
430 * camelCase reads the same.
431 */
432export function pullDetailFromWire(raw: Record<string, unknown>): PullDetail {
433 const detail: Record<string, unknown> = { ...raw };
434 for (const [snake, camel] of PULL_DETAIL_FIELDS) {
435 if (snake in detail) {
436 if (!(camel in detail)) detail[camel] = detail[snake];
437 delete detail[snake];
438 }
439 }
440 if (typeof detail.reviewPending !== "boolean") detail.reviewPending = false;
441 return detail as PullDetail;
442}
443
444export function workClient(service: ServiceBinding): WorkApi {
445 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
446 return {
447 openIssue: (actor, repo, input) => call("open_issue", { actor, repo, ...input }),
448 delegateIssue: (actor, repo, input) => call("delegate_issue", { actor, repo, ...input }),
449 listIssues: (repo, viewer, filter = {}) => call("list_issues", { repo, viewer, ...filter }),
450 getIssue: (repo, number, viewer) => call("get_issue", { repo, number, viewer }),
451 updateIssue: (actor, repo, number, input) =>
452 call("update_issue", { actor, repo, number, ...input }),
453 closeIssue: (actor, repo, number, reason) =>
454 call("close_issue", { actor, repo, number, reason }),
455 reopenIssue: (actor, repo, number) => call("reopen_issue", { actor, repo, number }),
456 listLabels: (repo, viewer) => call("list_labels", { repo, viewer }),
457 saveLabel: (actor, repo, label) => call("save_label", { actor, repo, ...label }),
458 deleteLabel: (actor, repo, name) => call("delete_label", { actor, repo, name }),
459 addDefaultLabels: (actor, repo) => call("add_default_labels", { actor, repo }),
460 setLabels: (actor, repo, number, labels, change = "set") =>
461 call("set_labels", { actor, repo, number, labels, change }),
462 listMilestones: (repo, viewer, state) => call("list_milestones", { repo, viewer, state }),
463 getMilestone: (repo, number, viewer) => call("get_milestone", { repo, number, viewer }),
464 saveMilestone: (actor, repo, milestone) => call("save_milestone", { actor, repo, ...milestone }),
465 deleteMilestone: (actor, repo, number) => call("delete_milestone", { actor, repo, number }),
466 counts: (repo, viewer) => call("counts", { repo, viewer }),
467 addComment: (actor, repo, number, comment) =>
468 call("add_comment", { actor, repo, number, ...comment }),
469 editComment: (actor, repo, commentId, body) => call("edit_comment", { actor, repo, commentId, body }),
470 deleteComment: (actor, repo, commentId) => call("delete_comment", { actor, repo, commentId }),
471 workspaceAgentComment: (repo, number, agent, actingFor, body) =>
472 call("workspace_agent_comment", { repo, number, agent, acting_for: actingFor, body }),
473 workspaceAgentReview: (repo, number, agent, actingFor, verdict, body) =>
474 call("workspace_agent_review", { repo, number, agent, acting_for: actingFor, verdict, body }),
475 startChecks: (pullId) => call("start_checks", { pullId }),
476 reportChecks: (runId, token, report) =>
477 call("report_checks", { runId, token, ...report }),
478 startReview: (pullId) => call("start_review", { pullId }),
479 failReview: (runId, token, error) => call("report_review", { runId, token, error }),
480 startMergecheck: (pullId) => call("start_mergecheck", { pullId }),
481 failMergecheck: (pullId, token, error) => call("report_mergecheck", { pullId, token, error }),
482 advance: (pullId) => call("advance", { pullId }),
483 stall: (pullId, reason) => call("stall", { pullId, reason }),
484 managedPulls: (repoId) => call("managed_pulls", { repoId }),
485 queue: (repo, viewer) => call("queue", { repo, viewer }),
486 queueBuild: (repoId) => call("queue_build", { repoId }),
487 failQueue: (entryId, token, error) => call("report_queue", { entryId, token, error }),
488 removeFromQueue: (actor, repo, number) => call("remove_from_queue", { actor, repo, number }),
489 messageAgent: (actor, repo, number, body) => call("message_agent", { actor, repo, number, body }),
490 catchUpJob: (pullId) => call("catch_up_job", { pullId }),
491 wakeForMessages: (pullId) => call("wake_for_messages", { pullId }),
492 getSettings: (repo, viewer) => call("get_settings", { repo, viewer }),
493 // Rulesets travel in snake_case (rules.ts).
494 listRulesets: (owner, viewer, includeParents = false) =>
495 call("list_rulesets", { viewer, ...owner, include_parents: includeParents }),
496 getRuleset: (owner, id, viewer) => call("get_ruleset", { viewer, ...owner, id }),
497 saveRuleset: (actor, owner, ruleset, id) => call("save_ruleset", { actor, ...owner, id: id ?? null, ruleset }),
498 deleteRuleset: (actor, owner, id) => call("delete_ruleset", { actor, ...owner, id }),
499 effectiveRules: (repo, name, viewer, target = "branch") => call("effective_rules", { viewer, repo, name, target }),
500 ruleEvaluations: (owner, viewer, filter = {}) => call("rule_evaluations", { viewer, ...owner, ...filter }),
501 seenChecks: (repo, viewer) => call("seen_checks", { repo, viewer }),
502 commitChecks: (repo, viewer, shas) => call("commit_checks", { repo, viewer, shas }),
503 getCheckRun: (repo, id, viewer) => call("get_check_run", { repo, id, viewer }),
504 checkRunAnnotations: (repo, id, viewer) => call("check_run_annotations", { repo, id, viewer }),
505 requestCheckAction: (actor, repo, id, identifier) => call("request_check_action", { actor, repo, id, identifier }),
506 rerequestCheckRun: (actor, repo, id) => call("rerequest_check_run", { actor, repo, id }),
507 codeownersErrors: (repo, viewer, ref) => call("codeowners_errors", { repo, viewer, ref: ref ?? null }),
508 updateSettings: (actor, repo, settings) =>
509 call("update_settings", { actor, repo, settings }),
510 openPull: (actor, repo, input) => call("open_pull", { actor, repo, ...input }),
511 listPulls: (repo, viewer, state, filter = {}) => call("list_pulls", { repo, viewer, state, ...filter }),
512 pullsForRepos: (repoIds, viewer, limit) => call("pulls_for_repos", { repoIds, viewer, limit }),
513 // Its own fields arrive in snake_case: read into camelCase here.
514 getPull: (repo, number, viewer) =>
515 call<Result<Record<string, unknown>>>("get_pull", { repo, number, viewer }).then(
516 (found): Result<PullDetail> => (found.ok ? { ok: true, value: pullDetailFromWire(found.value) } : found),
517 ),
518 updatePull: (actor, repo, number, changes) =>
519 call("update_pull", { actor, repo, number, ...changes }),
520 catchUpPull: (actor, repo, number) => call("catch_up_pull", { actor, repo, number }),
521 readyPull: (actor, repo, number, summary) =>
522 call("ready_pull", { actor, repo, number, summary }),
523 closePull: (actor, repo, number) => call("close_pull", { actor, repo, number }),
524 reopenPull: (actor, repo, number) => call("reopen_pull", { actor, repo, number }),
525 convertPullToDraft: (actor, repo, number) => call("convert_pull_to_draft", { actor, repo, number }),
526 mergePull: (actor, repo, number, options = {}) =>
527 call("merge_pull", { actor, repo, number, ...options }),
528 listActivePulls: (viewer) => call("list_active_pulls", { viewer }),
529 byAuthor: (username, viewer, filter = {}) => call("by_author", { username, viewer, ...filter }),
530 contributions: (username, viewer) => call("contributions", { username, viewer }),
531 startPlan: (actor, repo, brief) => call("start_plan", { actor, repo, brief }),
532 failPlan: (planId, token, error) => call("report_plan", { planId, token, error }),
533 getPlan: (repo, viewer, id) => call("get_plan", { repo, viewer, id }),
534 listPlans: (repo, viewer) => call("list_plans", { repo, viewer }),
535 applyPlan: (actor, repo, id, options = {}) =>
536 call("apply_plan", { actor, repo, id, ...options }),
537 queueIssue: (actor, repo, number, queued) =>
538 call("queue_issue", { actor, repo, number, queued }),
539 readyIssues: (repoId) => call("ready_issues", { repoId }),
540 listAssignedIssues: (viewer) => call("list_assigned_issues", { viewer }),
541 appendSession: (actor, repo, number, entries) =>
542 call("append_session", { actor, repo, number, entries }),
543 readSession: (repo, number, viewer, afterSeq = 0) =>
544 call("read_session", { repo, number, viewer, afterSeq }),
545 };
546}
547
548export function billingClient(service: ServiceBinding): BillingApi {
549 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
550 return {
551 status: () => call("status", {}),
552 account: (workspace, viewer) => call("account", { workspace, viewer }),
553 ledger: (workspace, viewer) => call("ledger", { workspace, viewer }),
554 credits: (workspace, viewer) => call("credits", { workspace, viewer }),
555 statement: (workspace, viewer, month = null, group = "day") => call("statement", { workspace, viewer, month, group }),
556 statementEntries: (workspace, viewer, filter) =>
557 call("statement_entries", {
558 workspace,
559 viewer,
560 month: filter.month,
561 kind: filter.kind,
562 day: filter.day ?? null,
563 project: filter.project ?? null,
564 before: filter.before ?? null,
565 }),
566 usage: (workspace, viewer, since) => call("usage", { workspace, viewer, since }),
567 tokenUsage: (workspace, viewer, options = {}) =>
568 call("token_usage", { workspace, viewer, person: options.person ?? null, days: options.days ?? null }),
569 recordTokens: (usage) => call("record_tokens", usage),
570 gatewayModels: () => call("gateway_models", {}),
571 modelDefaults: () => call("model_defaults", {}),
572 recordDiscovery: (provider, models, by, error = null) => call("record_discovery", { provider, models, by, error }),
573 gatewayAdmit: (workspace) => call("gateway_admit", { workspace }),
574 recordGateway: (record) => call("record_gateway", record),
575 gatewayRequests: (workspace, viewer, options = {}) =>
576 call("gateway_requests", { workspace, viewer, limit: options.limit ?? null, before: options.before ?? null }),
577 checkout: (actor, workspace, amountCents, returnUrl, method = "card") =>
578 call("checkout", { actor, workspace, amountCents, returnUrl, method }),
579 confirm: (workspace, viewer, session) => call("confirm", { workspace, viewer, session }),
580 canStart: (workspace) => call("can_start", { workspace }),
581 trial: (workspace, exempt) => call("trial", { workspace, exempt }),
582 startRun: (run) => call("start_run", run),
583 features: (workspace, viewer) => call("features", { workspace, viewer }),
584 subscribe: (actor, workspace, feature, returnUrl) =>
585 call("subscribe", { actor, workspace, feature, returnUrl }),
586 confirmSubscription: (workspace, viewer, session) =>
587 call("confirm_subscription", { workspace, viewer, session }),
588 cancelSubscription: (actor, workspace, feature, resume = false) =>
589 call("cancel_subscription", { actor, workspace, feature, resume }),
590 hasFeature: (workspace, feature) => call("has_feature", { workspace, feature }),
591 freeWorkspaces: (workspaces) => call("free_workspaces", { workspaces }),
592 chargeFeature: (charge) => call("charge_feature", charge),
593 billingPortal: (actor, workspace, returnUrl) => call("billing_portal", { actor, workspace, return_url: returnUrl }),
594 recordSandbox: (usage) => call("record_sandbox", usage),
595 limit: (workspace, viewer) => call("limit", { workspace, viewer }),
596 checkLimit: (workspace) => call("check_limit", { workspace }),
597 prices: () => call("prices", {}),
598 notePending: (workspace, source, costMicros, detail = null) => call("note_pending", { workspace, source, costMicros, detail }),
599 usageMeters: (workspace, viewer) => call("usage_meters", { workspace, viewer }),
600 setSpendLimit: (actor, workspace, spendLimitMicros, useFullLimit = false, raiseOnce = false) =>
601 call("set_spend_limit", { actor, workspace, spendLimitMicros, use_full_limit: useFullLimit, raise_once: raiseOnce }),
602 invoices: (workspace, viewer) => call("invoices", { workspace, viewer }),
603 entitlements: (workspace) => call("entitlements", { workspace }),
604 reserve: (reservation) => call("reserve", reservation),
605 settle: (reservationId, actualMicros) => call("settle", { reservationId, actualMicros }),
606 cardCheck: (actor, workspace, returnUrl) => call("card_check", { actor, workspace, returnUrl }),
607 confirmCardCheck: (workspace, viewer, session) => call("confirm_card_check", { workspace, viewer, session }),
608 requestLimit: (actor, workspace, request) => call("request_limit", { actor, workspace, ...request }),
609 limitRequests: (workspace, viewer) => call("limit_requests", { workspace, viewer }),
610 confirmSpike: (actor, workspace, keepGoing) => call("confirm_spike", { actor, workspace, keepGoing }),
611 setCaps: (actor, workspace, caps) => call("set_caps", { actor, workspace, ...caps }),
612 usageReport: (workspace, viewer, range) =>
613 call("usage_report", { workspace, viewer, from: range.from, until: range.until, products: range.products ?? [], projects: range.projects ?? [] }),
614 aiCredit: (workspace, viewer) => call("ai_credit", { workspace, viewer }),
615 buyAiCredit: (actor, workspace, amountCents, returnUrl) => call("buy_ai_credit", { actor, workspace, amountCents, returnUrl }),
616 confirmAiCredit: (workspace, viewer, session) => call("confirm_ai_credit", { workspace, viewer, session }),
617 setAiReload: (actor, workspace, reload) => call("set_ai_reload", { actor, workspace, ...reload }),
618 setBudget: (actor, workspace, budget) => call("set_budget", { actor, workspace, ...budget }),
619 billingDetails: (workspace, viewer) => call("billing_details", { workspace, viewer }),
620 setBillingDetails: (actor, workspace, details) => call("set_billing_details", { actor, workspace, ...details }),
621 };
622}
623
624export function billingAdminClient(service: ServiceBinding): BillingAdminApi {
625 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
626 return {
627 accounts: (query) => call("admin_accounts", { query: query ?? null }),
628 account: (id) => call("admin_account", { id }),
629 setTerms: (id, terms, by) => call("admin_set_terms", { id, terms, by }),
630 setAllowances: (id, allowances, note, by) => call("admin_set_allowances", { id, allowances, note, by }),
631 createEnterprise: (name, workspaces, by) => call("admin_create_enterprise", { name, workspaces, by }),
632 attach: (workspace, account, by) => call("admin_attach", { workspace, account, by }),
633 credit: (workspace, amountMicros, note, by, options = { kind: "goodwill" }) =>
634 call("admin_credit", {
635 workspace,
636 amount_micros: amountMicros,
637 note,
638 by,
639 kind: options.kind,
640 expires_at: options.expiresAt ?? null,
641 refund_for: options.refundFor ?? null,
642 refund_day: options.refundDay ?? null,
643 }),
644 credits: (filter = {}) =>
645 call("admin_credits", {
646 workspace: filter.workspace ?? null,
647 kind: filter.kind ?? null,
648 month: filter.month ?? null,
649 by: filter.by ?? null,
650 }),
651 revokeCredit: (id, note, by) => call("admin_revoke_credit", { id, note, by }),
652 resetBilling: (workspace, confirm, note, by) => call("admin_reset_billing", { workspace, confirm, note, by }),
653 billingLink: (workspace, by) => call("admin_billing_link", { workspace, by }),
654 stripe: (fix = false, by) => call("admin_stripe", { fix, by: by ?? null }),
655 enterpriseBilling: (id, email, by) => call("admin_enterprise_billing", { id, email, by }),
656 enterpriseAddress: (id, address, taxIdType, taxId, by) => call("admin_enterprise_address", { id, address, taxIdType, taxId, by }),
657 invoiceEnterprise: (id, by) => call("admin_invoice_enterprise", { id, by }),
658 accountsFor: (workspaces) => call("admin_accounts", { query: null, workspaces }),
659 signals: () => call("admin_signals", {}),
660 overview: () => call("admin_overview", {}),
661 sales: (workspace) => call("admin_sales", { workspace }),
662 setSales: (workspace, record, by) =>
663 call("admin_set_sales", {
664 workspace,
665 stage: record.stage,
666 owner: record.owner ?? null,
667 next_step: record.nextStep ?? null,
668 next_at: record.nextAt ?? null,
669 by,
670 }),
671 addNote: (workspace, text, by) => call("admin_add_note", { workspace, text, by }),
672 workspaceInvoices: (workspace) => call("admin_workspace_invoices", { workspace }),
673 allInvoices: (filter = {}) => call("admin_invoices", { status: filter.status ?? null, month: filter.month ?? null }),
674 audit: (filter = {}) =>
675 call("admin_audit", { by: filter.by ?? null, action: filter.action ?? null, before: filter.before ?? null }),
676 limitRequests: (status = "open") => call("admin_limit_requests", { status }),
677 decideLimitRequest: (id, decision, amountMicros, note, by) =>
678 call("admin_decide_limit_request", { id, decision, amount_micros: amountMicros, note, by }),
679 overages: () => call("admin_overages", {}),
680 goodwill: (workspace, amountMicros, reason, by, day = null) =>
681 call("admin_goodwill", { workspace, amount_micros: amountMicros, reason, by, day }),
682 velocity: () => call("admin_velocity", {}),
683 recordPayment: (workspace, amountMicros, reference, note, by) =>
684 call("admin_record_payment", { workspace, amount_micros: amountMicros, reference, note, by }),
685 costs: (days) => call("admin_costs", { days: days ?? null }),
686 costAlerts: () => call("admin_cost_alerts", {}),
687 spendCaps: () => call("admin_spend_caps", {}),
688 liftBreaker: (note, by) => call("admin_lift_breaker", { note, by }),
689 platformGuard: () => call("admin_platform_guard", {}),
690 setPause: (level, paused, note, by) => call("admin_set_pause", { level, paused, note, by }),
691 decideProposal: (id, decision, note, by) => call("admin_decide_proposal", { id, decision, note, by }),
692 setCostSettings: (settings, by) => call("admin_set_cost_settings", { settings, by }),
693 setCostMapping: (mapping, by) =>
694 call("admin_set_cost_mapping", {
695 product: mapping.product,
696 meter: mapping.meter,
697 bucket: mapping.bucket ?? "",
698 price_meter: mapping.priceMeter ?? null,
699 own_meter: mapping.ownMeter ?? null,
700 scale_to_own: mapping.scaleToOwn ?? false,
701 drift_percent: mapping.driftPercent ?? null,
702 note: mapping.note ?? "",
703 remove: mapping.remove ?? false,
704 by,
705 }),
706 runCosts: (by) => call("admin_run_costs", { by }),
707 models: () => call("admin_models", {}),
708 decideModel: (model, decision, details, reason, by) =>
709 call("admin_decide_model", {
710 model,
711 decision,
712 name: details.name ?? null,
713 tier_hint: details.tierHint ?? null,
714 prices: details.prices
715 ? {
716 input_micros: details.prices.inputMicros,
717 output_micros: details.prices.outputMicros,
718 cache_read_micros: details.prices.cacheReadMicros,
719 cache_write_micros: details.prices.cacheWriteMicros,
720 cache_write_1h_micros: details.prices.cacheWrite1hMicros,
721 threshold: details.prices.threshold,
722 over_input_micros: details.prices.overInputMicros,
723 over_output_micros: details.prices.overOutputMicros,
724 over_cache_read_micros: details.prices.overCacheReadMicros,
725 over_cache_write_micros: details.prices.overCacheWriteMicros,
726 over_cache_write_1h_micros: details.prices.overCacheWrite1hMicros,
727 }
728 : null,
729 reason,
730 by,
731 }),
732 setModelDefault: (purpose, value, reason, by) =>
733 call("admin_set_model_default", {
734 purpose,
735 model: value.model ?? null,
736 tier: value.tier ?? null,
737 effort: value.effort ?? null,
738 reason,
739 by,
740 }),
741 };
742}
743
744export function eventsClient(service: ServiceBinding): EventsApi {
745 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
746 return {
747 publish: (events) => call("publish", { events }),
748 list: (query) => call("list", query),
749 activityDigest: (args) => call("activity_digest", args),
750 };
751}
752
753export function integrationsClient(service: ServiceBinding): IntegrationsApi {
754 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
755 return {
756 list: (workspace, viewer) => call("list", { workspace, viewer }),
757 connect: (actor, workspace, input) => call("connect", { actor, workspace, ...input }),
758 update: (actor, workspace, id, input) => call("update", { actor, workspace, id, ...input }),
759 disconnect: (actor, workspace, id) => call("disconnect", { actor, workspace, id }),
760 test: (actor, workspace, id) => call("test", { actor, workspace, id }),
761 deliveries: (workspace, viewer, id) => call("deliveries", { workspace, viewer, id }),
762 resolve: (workspace, viewer, reference) => call("resolve", { workspace, viewer, reference }),
763 references: (workspace, text, limit) => call("references", { workspace, text, limit }),
764 import: (actor, repo, reference, assign) => call("import", { actor, repo, reference, assign }),
765 comment: (actor, workspace, reference, text, link) => call("comment", { actor, workspace, reference, text, link }),
766 close: (actor, workspace, reference, text, link) => call("close", { actor, workspace, reference, text, link }),
767 links: (repo, number) => call("links", { repo, number }),
768 modelProvider: (workspace) => call("model_provider", { workspace }),
769 openModelSession: (run) => call("open_model_session", run),
770 modelUpstream: (token) => call("model_upstream", { token }),
771 gatewayUpstream: (workspace) => call("gateway_upstream", { workspace }),
772 gatewayProviders: (workspace) => call("gateway_providers", { workspace }),
773 closeModelSessions: (tokenHashes) => call("close_model_sessions", { token_hashes: tokenHashes }),
774 capModelSessions: (tokenHashes, capMicros) => call("cap_model_sessions", { token_hashes: tokenHashes, cap_micros: capMicros }),
775 routes: (workspace, viewer) => call("routes", { workspace, viewer }),
776 setRoutes: (actor, workspace, routes) => call("set_routes", { actor, workspace, routes }),
777 };
778}
779
780export function webhooksClient(service: ServiceBinding): WebhooksApi {
781 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
782 return {
783 list: (viewer, owner) => call("list", { viewer, ...owner }),
784 create: (actor, owner, input) => call("create", { actor, ...owner, ...input }),
785 update: (actor, owner, id, input) => call("update", { actor, ...owner, id, ...input }),
786 delete: (actor, owner, id) => call("delete", { actor, ...owner, id }),
787 ping: (actor, owner, id) => call("ping", { actor, ...owner, id }),
788 deliveries: (viewer, owner, id) => call("deliveries", { viewer, ...owner, id }),
789 redeliver: (actor, owner, deliveryId) => call("redeliver", { actor, ...owner, deliveryId }),
790 };
791}
792
793export function actionsClient(service: ServiceBinding): ActionsApi {
794 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
795 return {
796 workflows: (repo, viewer) => call("workflows", { repo, viewer }),
797 runs: (repo, viewer, filter = {}) => call("runs", { repo, viewer, ...filter }),
798 run: (repo, viewer, id, attempt) => call("run", { repo, viewer, id, attempt: attempt ?? null }),
799 logs: (repo, viewer, job, after = 0) => call("logs", { repo, viewer, job, after }),
800 summaries: (repo, viewer, id, attempt) => call("summaries", { repo, viewer, id, attempt: attempt ?? null }),
801 jobLogText: (repo, viewer, job) => call("job_log_text", { repo, viewer, job }),
802 runLogs: (repo, viewer, id, attempt) => call("run_logs", { repo, viewer, id, attempt: attempt ?? null }),
803 dispatch: (actor, repo, workflow, ref, inputs) => call("dispatch", { actor, repo, workflow, ref, inputs }),
804 cancel: (actor, repo, id, force = false) => call("cancel", { actor, repo, id, force }),
805 rerun: (actor, repo, id, failedOnly = false, options = {}) =>
806 call("rerun", { actor, repo, id, failed_only: failedOnly, job: options.job ?? null, debug: options.debug ?? false }),
807 setWorkflowEnabled: (actor, repo, workflow, enabled) =>
808 call("set_workflow_enabled", { actor, repo, workflow, enabled }),
809 settings: (actor, owner, kind) => call("settings", { actor, ...owner, kind }),
810 setSetting: (actor, owner, kind, name, value, options = {}) =>
811 call("set_setting", { actor, ...owner, kind, name, value, ...options }),
812 deleteSetting: (actor, owner, kind, name, id) => call("delete_setting", { actor, ...owner, kind, name, id }),
813 approveRun: (actor, repo, id) => call("approve_run", { actor, repo, id }),
814 pendingDeployments: (repo, viewer, id) => call("pending_deployments", { repo, viewer, id }),
815 reviewDeployments: (actor, repo, id, state, environments = [], comment) =>
816 call("review_deployments", { actor, repo, id, state, environments, comment: comment ?? null }),
817 actionsSettings: (repo, viewer) => call("actions_settings", { repo, viewer }),
818 setActionsSettings: (actor, repo, change) => call("set_actions_settings", { actor, repo, ...change }),
819 workspaceActionsSettings: (workspace, viewer) => call("workspace_actions_settings", { workspace, viewer }),
820 setWorkspaceActionsSettings: (actor, workspace, change) =>
821 call("set_workspace_actions_settings", { actor, workspace, ...change }),
822 workspaceManagedWorkflows: (workspace, viewer) => call("workspace_managed_workflows", { workspace, viewer }),
823 setWorkspaceManagedWorkflow: (actor, workspace, name, change, create = false) =>
824 call("set_workspace_managed_workflow", { actor, workspace, name, create, ...change }),
825 removeWorkspaceManagedWorkflow: (actor, workspace, name) =>
826 call("remove_workspace_managed_workflow", { actor, workspace, name }),
827 environments: (repo, viewer) => call("environments", { repo, viewer }),
828 setEnvironment: (actor, repo, name, change) => call("set_environment", { actor, repo, name, ...change }),
829 deleteEnvironment: (actor, repo, name) => call("delete_environment", { actor, repo, name }),
830 artifacts: (repo, viewer, filter = {}) => call("artifacts", { repo, viewer, ...filter }),
831 artifactDownload: (repo, viewer, by) => call("artifact_download", { repo, viewer, ...by }),
832 deleteArtifact: (actor, repo, id) => call("delete_artifact", { actor, repo, id }),
833 artifactRetention: (repo, viewer, days) => call("artifact_retention", { repo, viewer, days }),
834 };
835}
836
837
838/** Staff-only self-hosted runners, on the actions service: only sudo calls it. */
839export function runnersAdminClient(service: ServiceBinding): RunnersAdminApi {
840 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
841 return {
842 list: (workspace) => call("admin_runners", { workspace }),
843 remove: (workspace, id, staff) => call("admin_remove_runners", { workspace, id, staff }),
844 };
845}
846
847/** Self-hosted runners, kept by the actions service. */
848export function runnersClient(service: ServiceBinding): RunnersApi {
849 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
850 return {
851 stuck: (viewer) => call("stuck_jobs", { viewer }),
852 activity: (actor, workspace) => call("runner_activity", { actor, workspace }),
853 list: (actor, owner) => call("runners", { actor, ...owner }),
854 createToken: (actor, owner, group) => call("create_registration_token", { actor, ...owner, group }),
855 remove: (actor, owner, id) => call("remove_runner", { actor, ...owner, id }),
856 groups: (actor, workspace) => call("runner_groups", { actor, workspace }),
857 setGroup: (actor, workspace, group) => call("set_runner_group", { actor, workspace, ...group }),
858 deleteGroup: (actor, workspace, id) => call("delete_runner_group", { actor, workspace, id }),
859 settings: (actor, owner) => call("runner_settings", { actor, ...owner }),
860 setSettings: (actor, owner, change) => call("set_runner_settings", { actor, ...owner, ...change }),
861 reportDesktop: (actor, report) => call("report_desktop", { actor, ...report }),
862 desktops: (actor, workspace) => call("desktop_runners", { actor, workspace }),
863 };
864}
865
866export function deploymentsClient(service: ServiceBinding): DeploymentsApi {
867 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
868 return {
869 settings: (project, viewer) => call("settings", { project, viewer }),
870 updateSettings: (actor, project, changes) => call("update_settings", { actor, project, changes }),
871 list: (project, viewer) => call("list", { project, viewer }),
872 get: (project, id, viewer) => call("get", { project, id, viewer }),
873 redeploy: (actor, project, branch) => call("redeploy", { actor, project, branch }),
874 takeDown: (actor, project, branch) => call("take_down", { actor, project, branch }),
875 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
876 usage: (workspace, viewer) => call("usage", { workspace, viewer }),
877 domains: (project, viewer) => call("domains", { project, viewer }),
878 addDomain: (actor, project, hostname, options = {}) =>
879 call("add_domain", { actor, project, hostname, twin: !!options.twin }),
880 removeDomain: (actor, project, id) => call("remove_domain", { actor, project, id }),
881 refreshDomain: (actor, project, id) => call("refresh_domain", { actor, project, id }),
882 repoDeployments: (repo, viewer, filter = {}) => call("list_deployments", { repo, viewer, ...filter }),
883 repoDeployment: (repo, id, viewer) => call("get_deployment", { repo, id, viewer }),
884 environments: (repo, viewer) => call("list_environments", { repo, viewer }),
885 createDeployment: (actor, repo, input) => call("create_deployment", { repo, actor, ...input }),
886 createDeploymentStatus: (actor, repo, id, input) => call("create_deployment_status", { repo, actor, id, ...input }),
887 };
888}
889
890/** Packages: the registries beside the code (services/packages). */
891export function packagesClient(service: ServiceBinding): PackagesApi {
892 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
893 return {
894 list: (workspace, viewer, filter = {}) =>
895 call("list_packages", {
896 workspace,
897 viewer,
898 ecosystem: filter.ecosystem ?? null,
899 repo_id: filter.repoId ?? null,
900 query: filter.query ?? null,
901 }),
902 get: (workspace, ecosystem, name, viewer) => call("get_package", { workspace, ecosystem, name, viewer }),
903 deleteVersion: (actor, workspace, ecosystem, name, version, surface) =>
904 call("delete_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
905 deletePackage: (actor, workspace, ecosystem, name, surface) =>
906 call("delete_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
907 set: (actor, workspace, ecosystem, name, change, surface) =>
908 call("set_package", {
909 actor,
910 workspace,
911 ecosystem,
912 name,
913 visibility: change.visibility ?? null,
914 link: change.link ?? null,
915 unlink: change.unlink ?? false,
916 inherit_access: change.inheritAccess ?? null,
917 surface: surface ?? null,
918 }),
919 settings: (workspace, ecosystem, name, viewer) => call("package_settings", { workspace, ecosystem, name, viewer }),
920 deleted: (workspace, viewer) => call("deleted_packages", { workspace, viewer }),
921 restorePackage: (actor, workspace, ecosystem, name, surface) =>
922 call("restore_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
923 restoreVersion: (actor, workspace, ecosystem, name, version, surface) =>
924 call("restore_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
925 setAccess: (actor, workspace, ecosystem, name, who, role, surface) =>
926 call("set_package_access", {
927 actor,
928 workspace,
929 ecosystem,
930 name,
931 user: "user" in who ? who.user : null,
932 team: "team" in who ? who.team : null,
933 role,
934 surface: surface ?? null,
935 }),
936 removeAccess: (actor, workspace, ecosystem, name, who, surface) =>
937 call("remove_package_access", {
938 actor,
939 workspace,
940 ecosystem,
941 name,
942 user: "user" in who ? who.user : null,
943 team: "team" in who ? who.team : null,
944 surface: surface ?? null,
945 }),
946 setActionsAccess: (actor, workspace, ecosystem, name, repo, role, surface) =>
947 call("set_actions_access", { actor, workspace, ecosystem, name, repo, role, surface: surface ?? null }),
948 removeActionsAccess: (actor, workspace, ecosystem, name, repo, surface) =>
949 call("remove_actions_access", { actor, workspace, ecosystem, name, repo, surface: surface ?? null }),
950 storage: (workspace) => call("storage", { workspace }),
951 storageAll: () => call("storage_all", {}),
952 syncComposer: (repoId) => call("sync_composer", { repo_id: repoId }),
953 };
954}
955
956export function projectsClient(service: ServiceBinding): ProjectsApi {
957 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
958 return {
959 list: (workspace, viewer) => call("list", { workspace, viewer }),
960 get: (workspace, slug, viewer) => call("get", { workspace, slug, viewer }),
961 byRepo: (repoId) => call("by_repo", { repoId }),
962 create: (actor, workspace, input) => call("create", { actor, workspace, input }),
963 update: (actor, workspace, slug, changes) => call("update", { actor, workspace, slug, changes }),
964 setProductionImage: (actor, workspace, slug, change) => call("set_production_image", { actor, workspace, slug, change }),
965 externalProductions: () => call("external_productions", {}),
966 deploymentsChanged: (projectId, enabled) => call("deployments_changed", { projectId, enabled }),
967 shortcuts: (workspace, viewer) => call("shortcuts", { workspace, viewer }),
968 pin: (actor, workspace, slug, position) => call("pin", { actor, workspace, slug, position: position ?? null }),
969 unpin: (actor, workspace, slug) => call("unpin", { actor, workspace, slug }),
970 reorderPins: (actor, workspace, slugs) => call("reorder_pins", { actor, workspace, slugs }),
971 visited: (actor, projectId) => call("visited", { actor, projectId }),
972 publicLinks: (repos) => call("public_links", { repos }),
973 };
974}
975
976/**
977 * An agent's own computer, on the runner (services/runner `AgentComputer`):
978 * what the agents service calls for a session's `run_command` and file
979 * tools, and for the Computer tab. Arguments and answers are snake_case.
980 */
981export function runnerComputerClient(service: ServiceBinding): RunnerComputerApi {
982 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
983 return {
984 computerStatus: (agentId) => call("computer_status", { agent_id: agentId }),
985 computerWake: (args) => call("computer_wake", args),
986 computerExec: (args) => call("computer_exec", args),
987 computerReadFile: (args) => call("computer_read_file", args),
988 computerWriteFile: (args) => call("computer_write_file", args),
989 computerSleep: (agentId) => call("computer_sleep", { agent_id: agentId }),
990 computerReset: (agentId) => call("computer_reset", { agent_id: agentId }),
991 computerForget: (agentId) => call("computer_forget", { agent_id: agentId }),
992 computerKeep: (agentId) => call("computer_keep", { agent_id: agentId }),
993 computerErase: (agentId) => call("computer_erase", { agent_id: agentId }),
994 computerCommands: (agentId, sessionId) => call("computer_commands", { agent_id: agentId, session_id: sessionId ?? null }),
995 };
996}