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
1,430 linesCodeBlameRaw
1//! The OpenAPI document, generated from the same list the routes are.
2//!
3//! The docs site builds its API reference from a copy of this document,
4//! `apps/docs/src/data/openapi.json`. A test keeps the copy current: run
5//! `G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi` to rewrite it.
6
7use g1t_contracts::scopes::scope_for;
8use serde_json::{Map, Value, json};
9
10use crate::about::AboutOp;
11use crate::run_artifacts::ArtifactsOp;
12use crate::archives::ArchiveOp;
13use crate::customize::CustomizeOp;
14use crate::deploy_keys::DeployKeysOp;
15use crate::mirrors::MirrorsOp;
16use crate::deployments::DeploymentsOp;
17use crate::packages::PackagesOp;
18use crate::folios::FoliosOp;
19use crate::protection::ProtectionOp;
20use crate::token_policy::TokenOp;
21use crate::operations::Op;
22use crate::checks::ChecksOp;
23use crate::rules::RulesOp;
24use crate::security::SecurityOp;
25use crate::rest::{ROUTES, Route};
26
27/// The sections of the API reference: a name, what it covers, and its
28/// operations in the order a reader meets them.
29const SECTIONS: &[(&str, &str, &[Op])] = &[
30 (
31 "Accounts",
32 "Signing in from a tool, who a token acts as, and your email addresses.",
33 &[Op::Whoami, Op::ListEmails, Op::AddEmail, Op::ConfirmEmail, Op::RemoveEmail, Op::UpdateEmailSettings],
34 ),
35 (
36 "Notifications",
37 "Your inbox: a thread for each thing you were told about (an issue, a pull request, a workflow on a branch, a deployment), why you were told, and what you subscribe to and watch. Your own: personal tokens and sessions only.",
38 &[
39 Op::ListNotifications,
40 Op::MarkNotificationsRead,
41 Op::GetNotificationThread,
42 Op::MarkThreadRead,
43 Op::MarkThreadDone,
44 Op::SaveThread,
45 Op::SnoozeThread,
46 Op::GetThreadSubscription,
47 Op::SetThreadSubscription,
48 Op::DeleteThreadSubscription,
49 Op::GetRepoSubscription,
50 Op::SetRepoSubscription,
51 Op::DeleteRepoSubscription,
52 Op::ListWatchedRepos,
53 ],
54 ),
55 (
56 "Pinned projects",
57 "The projects you keep at the top of a workspace's sidebar, in your order, up to eight a workspace. Your own: personal tokens and sessions only.",
58 &[Op::ListPinnedProjects, Op::PinProject, Op::UnpinProject, Op::ReorderPinnedProjects],
59 ),
60 (
61 "Projects",
62 "A project is what a workspace builds and runs, from a repository or a root directory in one. Each says what it is, where it runs and where to find it: its homepage, docs and other links.",
63 &[Op::ListProjects, Op::GetProject, Op::UpdateProject],
64 ),
65 (
66 "Workspaces",
67 "A workspace owns repositories and is the first part of their address. People and agents work in workspaces.",
68 &[Op::GetWorkspace, Op::CreateWorkspace, Op::UpdateWorkspace, Op::DeleteWorkspace],
69 ),
70 (
71 "Personal access tokens",
72 "A workspace's rules for its members' personal access tokens: whether tokens made for all of a member's workspaces reach it, whether tokens may be made for it alone and wait for an owner's approval, and how long a token may last; the tokens that reach it, approving or denying the ones that wait, and revoking one there. Owners only, as people.",
73 &[
74 Op::Tokens(TokenOp::GetTokenPolicy),
75 Op::Tokens(TokenOp::SetTokenPolicy),
76 Op::Tokens(TokenOp::ListMemberTokens),
77 Op::Tokens(TokenOp::ListTokenRequests),
78 Op::Tokens(TokenOp::ReviewTokenRequest),
79 Op::Tokens(TokenOp::RevokeMemberToken),
80 ],
81 ),
82 (
83 "Members",
84 "A workspace's members and owners: who belongs to it, their roles (owner or member, with billing manager and security manager on top), handing it to another member, and leaving it.",
85 &[Op::ListMembers, Op::UpdateMember, Op::RemoveMember, Op::TransferOwnership, Op::LeaveWorkspace],
86 ),
87 (
88 "Invites",
89 "While g1t is invite-only, every new account needs an invite. Your invites, inviting people into a workspace by username or email, and answering the invitations to workspaces sent to you.",
90 &[
91 Op::ListInvites,
92 Op::CreateInvite,
93 Op::RevokeInvite,
94 Op::ListWorkspaceInvites,
95 Op::InviteMember,
96 Op::RevokeWorkspaceInvite,
97 Op::ListInvitations,
98 Op::AcceptInvitation,
99 Op::DeclineInvitation,
100 ],
101 ),
102 (
103 "Billing",
104 "A workspace's usage, its budget, its AI credit, its invoices and its AI Gateway requests. Members read them; owners change the budget and buy credit, as people. g1t's agents never change billing.",
105 &[
106 Op::GetUsage,
107 Op::GetBudget,
108 Op::SetBudget,
109 Op::GetAiCredit,
110 Op::BuyAiCredit,
111 Op::ListInvoices,
112 Op::GetBillingDetails,
113 Op::ListGatewayRequests,
114 ],
115 ),
116 (
117 "Repositories",
118 "A repository, how it handles pull requests, and its timeline: renaming, archiving, moving and deleting it; and its files at a branch, tag or commit as a tarball or zipball.",
119 &[
120 Op::ListRepos,
121 Op::CreateRepo,
122 Op::GetRepo,
123 Op::Archives(ArchiveOp::DownloadTarball),
124 Op::Archives(ArchiveOp::DownloadZipball),
125 Op::UpdateRepo,
126 Op::RenameRepo,
127 Op::RenameBranch,
128 Op::SetRepoVisibility,
129 Op::ArchiveRepo,
130 Op::UnarchiveRepo,
131 Op::TransferRepo,
132 Op::DeleteRepo,
133 Op::ListDeletedRepos,
134 Op::RestoreRepo,
135 Op::PurgeRepo,
136 Op::GetRepoSettings,
137 Op::UpdateRepoSettings,
138 Op::ListCheckNames,
139 Op::GetCodeownersErrors,
140 Op::ListEvents,
141 ],
142 ),
143 (
144 "Repository insights",
145 "What a repository's default branch says about it, read in the background and kept by commit: the languages it is written in, who made it, and its license.",
146 &[Op::About(AboutOp::GetLanguages), Op::About(AboutOp::ListContributors), Op::About(AboutOp::GetLicense)],
147 ),
148 (
149 "Stars",
150 "Starring a repository, to keep it and to say you like it: who starred one, and what you starred.",
151 &[
152 Op::About(AboutOp::ListStargazers),
153 Op::About(AboutOp::ListStarred),
154 Op::About(AboutOp::CheckStarred),
155 Op::About(AboutOp::Star),
156 Op::About(AboutOp::Unstar),
157 ],
158 ),
159 (
160 "Releases",
161 "A release is a tag published with a title and notes. The latest is the newest published one that is neither a draft nor a prerelease.",
162 &[
163 Op::About(AboutOp::ListReleases),
164 Op::About(AboutOp::CreateRelease),
165 Op::About(AboutOp::GetLatestRelease),
166 Op::About(AboutOp::GetReleaseByTag),
167 Op::About(AboutOp::GetRelease),
168 Op::About(AboutOp::UpdateRelease),
169 Op::About(AboutOp::DeleteRelease),
170 ],
171 ),
172 (
173 "Access",
174 "Who can do what in a repository: repository roles, people given a role on one repository (outside collaborators when they are not members), invitations, a workspace's base permission, and deploy keys: SSH keys that reach one repository.",
175 &[
176 Op::ListCollaborators,
177 Op::AddCollaborator,
178 Op::UpdateCollaborator,
179 Op::RemoveCollaborator,
180 Op::GetCollaboratorPermission,
181 Op::ListRepoInvitations,
182 Op::RevokeRepoInvitation,
183 Op::ListMyRepoInvitations,
184 Op::AcceptRepoInvitation,
185 Op::DeclineRepoInvitation,
186 Op::SetBasePermission,
187 Op::ListOutsideCollaborators,
188 Op::DeployKeys(DeployKeysOp::ListDeployKeys),
189 Op::DeployKeys(DeployKeysOp::GetDeployKey),
190 Op::DeployKeys(DeployKeysOp::CreateDeployKey),
191 Op::DeployKeys(DeployKeysOp::DeleteDeployKey),
192 ],
193 ),
194 (
195 "Mirroring",
196 "A repository's links to copies of it on other hosts: a mirror stands by as a read-only copy of a remote that leads, until someone takes over on g1t and later hands back, or moves it to g1t for good. A repository g1t leads can be mirrored to other hosts.",
197 &[
198 Op::Mirrors(MirrorsOp::GetMirror),
199 Op::Mirrors(MirrorsOp::GetHandBackPlan),
200 Op::Mirrors(MirrorsOp::TakeOver),
201 Op::Mirrors(MirrorsOp::SetCiFailover),
202 Op::Mirrors(MirrorsOp::HandBack),
203 Op::Mirrors(MirrorsOp::MoveToG1t),
204 Op::Mirrors(MirrorsOp::SyncMirror),
205 Op::Mirrors(MirrorsOp::AddRemote),
206 Op::Mirrors(MirrorsOp::UpdateRemote),
207 Op::Mirrors(MirrorsOp::RemoveRemote),
208 ],
209 ),
210 (
211 "Teams",
212 "Groups of a workspace's members: given a role on repositories together, mentioned together as @workspace/team, and asked to review together. Any member may create a team; the workspace's owners and the team's maintainers manage it.",
213 &[
214 Op::ListTeams,
215 Op::CreateTeam,
216 Op::GetTeam,
217 Op::UpdateTeam,
218 Op::DeleteTeam,
219 Op::ListTeamMembers,
220 Op::SetTeamMember,
221 Op::RemoveTeamMember,
222 Op::ListChildTeams,
223 Op::ListTeamRepos,
224 Op::SetTeamRepo,
225 Op::RemoveTeamRepo,
226 Op::SetTeamReviewAssignment,
227 Op::ListUserTeams,
228 ],
229 ),
230 (
231 "Security",
232 "Secrets found in what is pushed and in a repository's history, and dependencies with known vulnerabilities: listing the alerts, and dismissing or reopening them.",
233 &[Op::ListSecurityAlerts, Op::DismissSecurityAlert, Op::ReopenSecurityAlert],
234 ),
235 (
236 "Secret scanning",
237 "Secrets found in pushes and history, where each one is, pushing past push protection with a reason (and asking for approval when the workspace delegates bypasses), checking with a secret's issuer whether it still works, and custom patterns.",
238 &[
239 Op::Security(SecurityOp::ListSecretAlerts),
240 Op::Security(SecurityOp::GetSecretAlert),
241 Op::Security(SecurityOp::UpdateSecretAlert),
242 Op::Security(SecurityOp::ListSecretLocations),
243 Op::Security(SecurityOp::BypassPushProtection),
244 Op::Security(SecurityOp::CheckSecretValidity),
245 Op::Security(SecurityOp::ListBypassRequests),
246 Op::Security(SecurityOp::ReviewBypassRequest),
247 Op::Security(SecurityOp::ListCustomPatterns),
248 Op::Security(SecurityOp::CreateCustomPattern),
249 Op::Security(SecurityOp::UpdateCustomPattern),
250 Op::Security(SecurityOp::DeleteCustomPattern),
251 Op::Security(SecurityOp::DryRunCustomPattern),
252 ],
253 ),
254 (
255 "Code scanning",
256 "Results of static analysis tools, uploaded as SARIF: alerts on the default branch, the analyses that made them, uploads, and putting g1t on an alert to fix it.",
257 &[
258 Op::Security(SecurityOp::ListCodeAlerts),
259 Op::Security(SecurityOp::GetCodeAlert),
260 Op::Security(SecurityOp::UpdateCodeAlert),
261 Op::Security(SecurityOp::ListAnalyses),
262 Op::Security(SecurityOp::UploadSarif),
263 Op::Security(SecurityOp::GetSarifUpload),
264 Op::Security(SecurityOp::FixAlert),
265 ],
266 ),
267 (
268 "Supply chain",
269 "What a repository depends on: vulnerability alerts, the dependency graph, an SPDX SBOM of it, and comparing two commits' dependencies as dependency review does.",
270 &[
271 Op::Security(SecurityOp::ListVulnerabilityAlerts),
272 Op::Security(SecurityOp::GetVulnerabilityAlert),
273 Op::Security(SecurityOp::UpdateVulnerabilityAlert),
274 Op::Security(SecurityOp::GetDependencyGraph),
275 Op::Security(SecurityOp::GetSbom),
276 Op::Security(SecurityOp::CompareDependencies),
277 ],
278 ),
279 (
280 "Security settings",
281 "When pull request checks fail, dependency review's policy, delegated bypass and validity checks, and a workspace's security overview.",
282 &[
283 Op::Security(SecurityOp::GetSettings),
284 Op::Security(SecurityOp::UpdateSettings),
285 Op::Security(SecurityOp::GetWorkspaceSettings),
286 Op::Security(SecurityOp::UpdateWorkspaceSettings),
287 Op::Security(SecurityOp::GetOverview),
288 ],
289 ),
290 (
291 "Security advisories",
292 "What a repository says about vulnerabilities in what it ships: advisories drafted, published and withdrawn by its maintainers, and the vulnerability reports people send them privately when the repository takes them.",
293 &[
294 Op::Security(SecurityOp::ListAdvisories),
295 Op::Security(SecurityOp::CreateAdvisory),
296 Op::Security(SecurityOp::GetAdvisory),
297 Op::Security(SecurityOp::UpdateAdvisory),
298 Op::Security(SecurityOp::SetAdvisoryState),
299 Op::Security(SecurityOp::ListReports),
300 Op::Security(SecurityOp::ReportVulnerability),
301 Op::Security(SecurityOp::ReviewReport),
302 ],
303 ),
304 (
305 "Rules",
306 "Rulesets: what may happen to a repository's branches and tags and what a pull request needs before it merges, for a repository or across a workspace; the rules that hold for one branch; and how they judged each push and merge, with insights.",
307 &[
308 Op::Rules(RulesOp::ListRepoRulesets),
309 Op::Rules(RulesOp::CreateRepoRuleset),
310 Op::Rules(RulesOp::GetRepoRuleset),
311 Op::Rules(RulesOp::UpdateRepoRuleset),
312 Op::Rules(RulesOp::DeleteRepoRuleset),
313 Op::Rules(RulesOp::GetBranchRules),
314 Op::Rules(RulesOp::ListRuleEvaluations),
315 Op::Rules(RulesOp::ListWorkspaceRulesets),
316 Op::Rules(RulesOp::CreateWorkspaceRuleset),
317 Op::Rules(RulesOp::GetWorkspaceRuleset),
318 Op::Rules(RulesOp::UpdateWorkspaceRuleset),
319 Op::Rules(RulesOp::DeleteWorkspaceRuleset),
320 Op::Rules(RulesOp::ListWorkspaceRuleEvaluations),
321 ],
322 ),
323 (
324 "Checks",
325 "What CI, integrations and g1t Actions say about a commit, in the shapes CI tools already send: statuses (a state per context) and check runs (a lifecycle, a conclusion, a Markdown report, annotations on lines and buttons), grouped per reporter into check suites. g1t Actions jobs are check runs too. Required checks are met by either.",
326 &[
327 Op::Checks(ChecksOp::CreateCommitStatus),
328 Op::Checks(ChecksOp::ListCommitStatuses),
329 Op::Checks(ChecksOp::GetCombinedStatus),
330 Op::Checks(ChecksOp::CreateCheckRun),
331 Op::Checks(ChecksOp::UpdateCheckRun),
332 Op::Checks(ChecksOp::GetCheckRun),
333 Op::Checks(ChecksOp::ListCheckRunAnnotations),
334 Op::Checks(ChecksOp::RerequestCheckRun),
335 Op::Checks(ChecksOp::ListCheckRunsForRef),
336 Op::Checks(ChecksOp::ListCheckSuitesForRef),
337 Op::Checks(ChecksOp::GetCheckSuite),
338 Op::Checks(ChecksOp::RerequestCheckSuite),
339 ],
340 ),
341 (
342 "Issues",
343 "What should change in a repository, with labels and comments. Issues and pull requests share one sequence of numbers.",
344 &[
345 Op::ListIssues,
346 Op::CreateIssue,
347 Op::GetIssue,
348 Op::UpdateIssue,
349 Op::CloseIssue,
350 Op::ReopenIssue,
351 Op::AssignIssue,
352 Op::Delegate,
353 Op::AddComment,
354 Op::EditComment,
355 Op::DeleteComment,
356 Op::ListIssueLabels,
357 Op::AddIssueLabels,
358 Op::SetIssueLabels,
359 Op::RemoveIssueLabels,
360 ],
361 ),
362 (
363 "Labels and milestones",
364 "A repository's labels, which issues and pull requests carry by name, and its milestones, which gather them under a goal and a due date.",
365 &[
366 Op::ListLabels,
367 Op::CreateLabel,
368 Op::UpdateLabel,
369 Op::DeleteLabel,
370 Op::AddDefaultLabels,
371 Op::ListMilestones,
372 Op::CreateMilestone,
373 Op::GetMilestone,
374 Op::UpdateMilestone,
375 Op::DeleteMilestone,
376 ],
377 ),
378 (
379 "Plans",
380 "An outcome turned into the issues that would get there, with the order they must merge in.",
381 &[Op::PlanWork, Op::GetPlan, Op::ApplyPlan],
382 ),
383 (
384 "Pull requests",
385 "A proposed change in its own fork or on a branch. Several can be made for one issue; the one merged resolves it.",
386 &[
387 Op::ListPullRequests,
388 Op::CreatePullRequest,
389 Op::GetPullRequest,
390 Op::UpdatePullRequest,
391 Op::GetPullRequestChanges,
392 Op::MarkPullRequestReady,
393 Op::ConvertPullRequestToDraft,
394 Op::RequestReviewers,
395 Op::RemoveRequestedReviewers,
396 Op::ReviewPullRequest,
397 Op::MergePullRequest,
398 Op::ClosePullRequest,
399 Op::ReopenPullRequest,
400 Op::GetMergeQueue,
401 Op::MessageAgent,
402 Op::AnswerMessage,
403 Op::TakeMessages,
404 ],
405 ),
406 (
407 "Sessions",
408 "The record of how a pull request was made: prompts, reasoning and the tools that ran.",
409 &[Op::ReadSession, Op::RecordSession],
410 ),
411 (
412 "Memory",
413 "What agents and people learned that the next agent should know, for one project or across a workspace. Members and g1t's agents only; never a secret.",
414 &[Op::Remember, Op::Recall],
415 ),
416 (
417 "Search",
418 "One search across all of g1t: repositories, code, issues, pull requests, people and workspaces. Public content for everyone, and private content in workspaces you belong to.",
419 &[Op::Search],
420 ),
421 (
422 "Context",
423 "A workspace's context hub: a catalog of what it builds and runs, built from its repositories, deployments and integrations, and one search across the catalog, docs, issues, pull requests and memory.",
424 &[Op::SearchContext, Op::GetEntity],
425 ),
426 (
427 "Actions",
428 "GitHub Actions workflows in .g1t/workflows, their runs, and their jobs' logs.",
429 &[
430 Op::ListWorkflows,
431 Op::ListWorkflowRuns,
432 Op::GetWorkflowRun,
433 Op::GetJobLogs,
434 Op::DispatchWorkflow,
435 Op::CancelWorkflowRun,
436 Op::RerunWorkflowRun,
437 Op::UpdateWorkflow,
438 Op::Artifacts(ArtifactsOp::ListArtifacts),
439 Op::Artifacts(ArtifactsOp::ListRunArtifacts),
440 Op::Artifacts(ArtifactsOp::GetArtifact),
441 Op::Artifacts(ArtifactsOp::DownloadArtifact),
442 Op::Artifacts(ArtifactsOp::DeleteArtifact),
443 Op::Artifacts(ArtifactsOp::GetArtifactRetention),
444 Op::Artifacts(ArtifactsOp::SetArtifactRetention),
445 ],
446 ),
447 (
448 "Packages",
449 "A workspace's packages in every registry: their versions and download counts, deleting and restoring them within 30 days, their visibility and repository, the people and teams with a role on them, and which repositories' workflows may use them (Manage Actions access). A package is named by its type and its name, URL-encoded where it holds a slash.",
450 &[
451 Op::Packages(PackagesOp::ListPackages),
452 Op::Packages(PackagesOp::GetPackage),
453 Op::Packages(PackagesOp::UpdatePackage),
454 Op::Packages(PackagesOp::DeletePackage),
455 Op::Packages(PackagesOp::RestorePackage),
456 Op::Packages(PackagesOp::ListVersions),
457 Op::Packages(PackagesOp::GetVersion),
458 Op::Packages(PackagesOp::DeleteVersion),
459 Op::Packages(PackagesOp::RestoreVersion),
460 Op::Packages(PackagesOp::LinkPackage),
461 Op::Packages(PackagesOp::UnlinkPackage),
462 Op::Packages(PackagesOp::ListAccess),
463 Op::Packages(PackagesOp::SetAccess),
464 Op::Packages(PackagesOp::RemoveAccess),
465 Op::Packages(PackagesOp::ListActionsAccess),
466 Op::Packages(PackagesOp::SetActionsAccess),
467 Op::Packages(PackagesOp::RemoveActionsAccess),
468 ],
469 ),
470 (
471 "Deployments",
472 "A repository's deployments wherever they run: reported from any CI with these routes, made by g1t Actions jobs with an `environment:`, or built on g1t.page. Each has statuses, shows on its commit as the check `deploy / <environment>`, and belongs to an environment.",
473 &[
474 Op::Deployments(DeploymentsOp::ListDeployments),
475 Op::Deployments(DeploymentsOp::CreateDeployment),
476 Op::Deployments(DeploymentsOp::GetDeployment),
477 Op::Deployments(DeploymentsOp::ListDeploymentStatuses),
478 Op::Deployments(DeploymentsOp::CreateDeploymentStatus),
479 Op::Deployments(DeploymentsOp::ListEnvironments),
480 Op::Deployments(DeploymentsOp::GetEnvironment),
481 Op::Deployments(DeploymentsOp::StartDeploymentBuild),
482 ],
483 ),
484 (
485 "Run protection",
486 "What keeps workflow runs safe: environments' protection rules (required reviewers, a wait timer, which branches may deploy) and the reviews of the jobs they hold, approving a pull request's run from outside, what a job's token gets when its workflow writes no `permissions:`, and repository_dispatch, which a job's own token may send.",
487 &[
488 Op::Protection(ProtectionOp::UpdateEnvironment),
489 Op::Protection(ProtectionOp::DeleteEnvironment),
490 Op::Protection(ProtectionOp::GetPendingDeployments),
491 Op::Protection(ProtectionOp::ReviewPendingDeployments),
492 Op::Protection(ProtectionOp::ApproveWorkflowRun),
493 Op::Protection(ProtectionOp::GetWorkflowPermissions),
494 Op::Protection(ProtectionOp::SetWorkflowPermissions),
495 Op::Protection(ProtectionOp::GetForkPrApproval),
496 Op::Protection(ProtectionOp::SetForkPrApproval),
497 Op::Protection(ProtectionOp::GetActionsAccess),
498 Op::Protection(ProtectionOp::SetActionsAccess),
499 Op::Protection(ProtectionOp::CreateRepositoryDispatch),
500 Op::Protection(ProtectionOp::GetWorkspaceWorkflowPermissions),
501 Op::Protection(ProtectionOp::SetWorkspaceWorkflowPermissions),
502 Op::Protection(ProtectionOp::ListWorkspaceManagedWorkflows),
503 Op::Protection(ProtectionOp::CreateWorkspaceManagedWorkflow),
504 Op::Protection(ProtectionOp::UpdateWorkspaceManagedWorkflow),
505 Op::Protection(ProtectionOp::DeleteWorkspaceManagedWorkflow),
506 ],
507 ),
508 (
509 "Secrets and variables",
510 "Values that workflows and deployments read, per repository or for a whole workspace, with a row per environment.",
511 &[
512 Op::ListActionsSecrets,
513 Op::SetActionsSecret,
514 Op::DeleteActionsSecret,
515 Op::ListActionsVariables,
516 Op::SetActionsVariable,
517 Op::DeleteActionsVariable,
518 ],
519 ),
520 (
521 "Runners",
522 "Self-hosted runners: your own machines, which run your workflow jobs (and, if you choose, your agents' work) for $0 of g1t compute. They register with a short-lived token and only ever connect out.",
523 &[
524 Op::ListRunners,
525 Op::CreateRunnerRegistrationToken,
526 Op::RemoveRunner,
527 Op::ListRunnerGroups,
528 Op::CreateRunnerGroup,
529 Op::UpdateRunnerGroup,
530 Op::DeleteRunnerGroup,
531 Op::GetRunnerSettings,
532 Op::UpdateRunnerSettings,
533 ],
534 ),
535 (
536 "Agents' computers",
537 "Each workspace agent has a computer of its own on g1t cloud: a persistent home its sessions run commands on, which sleeps when idle and is saved as it was. Its state and recent commands, and waking, sleeping and resetting it.",
538 &[
539 Op::GetAgentComputer,
540 Op::WakeAgentComputer,
541 Op::SleepAgentComputer,
542 Op::ResetAgentComputer,
543 Op::ListAgentComputerCommands,
544 ],
545 ),
546 (
547 "Webhooks",
548 "Signed HTTPS requests sent to your own address as things happen, for a repository or a whole workspace.",
549 &[
550 Op::ListWebhooks,
551 Op::CreateWebhook,
552 Op::UpdateWebhook,
553 Op::DeleteWebhook,
554 Op::PingWebhook,
555 Op::ListWebhookDeliveries,
556 Op::RedeliverWebhook,
557 ],
558 ),
559 (
560 "Integrations",
561 "A workspace's connections to outside systems: model providers, alert sources and issue trackers.",
562 &[
563 Op::ListIntegrations,
564 Op::ConnectIntegration,
565 Op::UpdateIntegration,
566 Op::DisconnectIntegration,
567 Op::TestIntegration,
568 Op::GetModelRoutes,
569 Op::SetModelRoutes,
570 Op::GetContext,
571 Op::ImportIssue,
572 ],
573 ),
574 (
575 "Customize",
576 "What shapes how a workspace's agents work, in the formats Claude Code reads: the marketplaces it reads plugins from, what Discover lists, the plugins it installed (their skills, subagents and remote MCP servers reach g1t's agents; the rest reaches Claude Code on a runner), and its connectors: MCP servers connected once, then given to every agent, a team or one agent. The bundle is what a job's Claude Code loads on a runner.",
577 &[
578 Op::Customize(CustomizeOp::ListMarketplaces),
579 Op::Customize(CustomizeOp::AddMarketplace),
580 Op::Customize(CustomizeOp::RemoveMarketplace),
581 Op::Customize(CustomizeOp::RefreshMarketplace),
582 Op::Customize(CustomizeOp::Discover),
583 Op::Customize(CustomizeOp::ListPlugins),
584 Op::Customize(CustomizeOp::GetPlugin),
585 Op::Customize(CustomizeOp::InstallPlugin),
586 Op::Customize(CustomizeOp::SetPluginEnabled),
587 Op::Customize(CustomizeOp::UninstallPlugin),
588 Op::Customize(CustomizeOp::UpdatePlugin),
589 Op::Customize(CustomizeOp::ListPluginAgents),
590 Op::Customize(CustomizeOp::ListConnectors),
591 Op::Customize(CustomizeOp::GetConnector),
592 Op::Customize(CustomizeOp::AddConnector),
593 Op::Customize(CustomizeOp::SetConnectorKey),
594 Op::Customize(CustomizeOp::RemoveConnector),
595 Op::Customize(CustomizeOp::RefreshConnector),
596 Op::Customize(CustomizeOp::GrantConnector),
597 Op::Customize(CustomizeOp::RevokeConnector),
598 Op::Customize(CustomizeOp::Bundle),
599 ],
600 ),
601 (
602 "Artifacts",
603 "A workspace's docs, slides, designs and dashboards (Artifacts mode): listing and searching the ones you can open, reading and editing their content in Markdown, making, moving, trashing and restoring them, their versions, and who can open them. Each answers for your own role on it. Not workflow runs' artifacts, which are under Actions. Slides, designs and dashboards answer that they are not here yet.",
604 &[
605 Op::Folios(FoliosOp::List),
606 Op::Folios(FoliosOp::Search),
607 Op::Folios(FoliosOp::Get),
608 Op::Folios(FoliosOp::GetContent),
609 Op::Folios(FoliosOp::ListVersions),
610 Op::Folios(FoliosOp::GetAccess),
611 Op::Folios(FoliosOp::ListTemplates),
612 Op::Folios(FoliosOp::ListSpaces),
613 Op::Folios(FoliosOp::QueryDataset),
614 Op::Folios(FoliosOp::Create),
615 Op::Folios(FoliosOp::Update),
616 Op::Folios(FoliosOp::Edit),
617 Op::Folios(FoliosOp::Trash),
618 Op::Folios(FoliosOp::Restore),
619 Op::Folios(FoliosOp::RestoreVersion),
620 Op::Folios(FoliosOp::SetAccess),
621 Op::Folios(FoliosOp::Purge),
622 ],
623 ),
624];
625
626/// The section of the API reference an operation is listed under.
627fn tag(op: Op) -> &'static str {
628 SECTIONS
629 .iter()
630 .find(|(_, _, ops)| ops.contains(&op))
631 .map_or("Repositories", |(name, _, _)| name)
632}
633
634/// What an operation's page is called, as a short sentence.
635fn title(op: Op) -> &'static str {
636 match op {
637 Op::Whoami => "Get the current user",
638 Op::GetWorkspace => "Get a workspace",
639 Op::CreateWorkspace => "Create a workspace",
640 Op::DeleteWorkspace => "Delete a workspace",
641 Op::UpdateWorkspace => "Update a workspace",
642 Op::ListMembers => "List a workspace's members",
643 Op::UpdateMember => "Change a member's role",
644 Op::RemoveMember => "Remove a member",
645 Op::TransferOwnership => "Transfer a workspace's ownership",
646 Op::LeaveWorkspace => "Leave a workspace",
647 Op::ListEmails => "List your email addresses",
648 Op::AddEmail => "Add an email address",
649 Op::ConfirmEmail => "Confirm an email address",
650 Op::RemoveEmail => "Remove an email address",
651 Op::UpdateEmailSettings => "Change your email settings",
652 Op::ListInvites => "List your invites",
653 Op::CreateInvite => "Create an invite",
654 Op::RevokeInvite => "Revoke an invite",
655 Op::ListWorkspaceInvites => "List a workspace's invites",
656 Op::InviteMember => "Invite someone to a workspace",
657 Op::ListInvitations => "List your workspace invitations",
658 Op::AcceptInvitation => "Accept a workspace invitation",
659 Op::DeclineInvitation => "Decline a workspace invitation",
660 Op::RevokeWorkspaceInvite => "Revoke a workspace's invite",
661 Op::TransferRepo => "Transfer a repository",
662 Op::RenameRepo => "Rename a repository",
663 Op::RenameBranch => "Rename a branch",
664 Op::ArchiveRepo => "Archive a repository",
665 Op::UnarchiveRepo => "Unarchive a repository",
666 Op::SetRepoVisibility => "Change a repository's visibility",
667 Op::DeleteRepo => "Delete a repository",
668 Op::ListDeletedRepos => "List recently deleted repositories",
669 Op::RestoreRepo => "Restore a deleted repository",
670 Op::PurgeRepo => "Purge a deleted repository",
671 Op::ListRepos => "List repositories",
672 Op::GetRepo => "Get a repository",
673 Op::CreateRepo => "Create a repository",
674 Op::UpdateRepo => "Update a repository",
675 Op::GetRepoSettings => "Get repository settings",
676 Op::UpdateRepoSettings => "Update repository settings",
677 Op::ListCheckNames => "List check names",
678 Op::GetMergeQueue => "Get the merge queue",
679 Op::MessageAgent => "Message an agent",
680 Op::AnswerMessage => "Answer a message",
681 Op::TakeMessages => "Take new messages",
682 Op::Remember => "Remember something",
683 Op::Recall => "Recall memory",
684 Op::SearchContext => "Search the context hub",
685 Op::GetEntity => "Get a catalog entry",
686 Op::Search => "Search g1t",
687 Op::ListIssues => "List issues",
688 Op::GetIssue => "Get an issue",
689 Op::CreateIssue => "Create an issue",
690 Op::UpdateIssue => "Update an issue",
691 Op::CloseIssue => "Close an issue",
692 Op::ReopenIssue => "Reopen an issue",
693 Op::AssignIssue => "Assign an issue to g1t",
694 Op::Delegate => "Put an agent on it",
695 Op::PlanWork => "Plan work",
696 Op::GetPlan => "Get a plan",
697 Op::ApplyPlan => "Apply a plan",
698 Op::ListLabels => "List labels",
699 Op::CreateLabel => "Create a label",
700 Op::UpdateLabel => "Update a label",
701 Op::DeleteLabel => "Delete a label",
702 Op::AddDefaultLabels => "Add the default labels",
703 Op::ListIssueLabels => "List an issue's labels",
704 Op::AddIssueLabels => "Add labels to an issue",
705 Op::SetIssueLabels => "Set an issue's labels",
706 Op::RemoveIssueLabels => "Remove labels from an issue",
707 Op::ListMilestones => "List milestones",
708 Op::GetMilestone => "Get a milestone",
709 Op::CreateMilestone => "Create a milestone",
710 Op::UpdateMilestone => "Update a milestone",
711 Op::DeleteMilestone => "Delete a milestone",
712 Op::UpdatePullRequest => "Update a pull request",
713 Op::AddComment => "Add a comment",
714 Op::EditComment => "Edit a comment",
715 Op::DeleteComment => "Delete a comment",
716 Op::ReviewPullRequest => "Review a pull request",
717 Op::ListPullRequests => "List pull requests",
718 Op::GetPullRequest => "Get a pull request",
719 Op::CreatePullRequest => "Create a pull request",
720 Op::RecordSession => "Record session entries",
721 Op::ReadSession => "Read a session",
722 Op::MarkPullRequestReady => "Mark a pull request ready",
723 Op::ClosePullRequest => "Close a pull request",
724 Op::ReopenPullRequest => "Reopen a pull request",
725 Op::ConvertPullRequestToDraft => "Convert a pull request to a draft",
726 Op::GetPullRequestChanges => "Get a pull request's changes",
727 Op::MergePullRequest => "Merge a pull request",
728 Op::ListEvents => "List repository events",
729 Op::ListIntegrations => "List integrations",
730 Op::ConnectIntegration => "Connect an integration",
731 Op::UpdateIntegration => "Update an integration",
732 Op::DisconnectIntegration => "Disconnect an integration",
733 Op::TestIntegration => "Test an integration",
734 Op::GetContext => "Look up a ticket",
735 Op::ImportIssue => "Import an issue",
736 Op::GetModelRoutes => "Get model routes",
737 Op::SetModelRoutes => "Set model routes",
738 Op::ListWebhooks => "List webhooks",
739 Op::CreateWebhook => "Create a webhook",
740 Op::UpdateWebhook => "Update a webhook",
741 Op::DeleteWebhook => "Delete a webhook",
742 Op::PingWebhook => "Ping a webhook",
743 Op::ListWebhookDeliveries => "List webhook deliveries",
744 Op::RedeliverWebhook => "Redeliver a webhook delivery",
745 Op::ListWorkflows => "List workflows",
746 Op::ListWorkflowRuns => "List workflow runs",
747 Op::GetWorkflowRun => "Get a workflow run",
748 Op::GetJobLogs => "Get a job's log",
749 Op::DispatchWorkflow => "Run a workflow",
750 Op::CancelWorkflowRun => "Cancel a workflow run",
751 Op::RerunWorkflowRun => "Re-run a workflow run",
752 Op::UpdateWorkflow => "Turn a workflow on or off",
753 Op::ListActionsSecrets => "List secrets",
754 Op::SetActionsSecret => "Set a secret",
755 Op::DeleteActionsSecret => "Delete a secret",
756 Op::ListActionsVariables => "List variables",
757 Op::SetActionsVariable => "Set a variable",
758 Op::DeleteActionsVariable => "Delete a variable",
759 Op::ListRunners => "List self-hosted runners",
760 Op::ListRunnerGroups => "List runner groups",
761 Op::GetAgentComputer => "Get an agent's computer",
762 Op::WakeAgentComputer => "Wake an agent's computer",
763 Op::SleepAgentComputer => "Put an agent's computer to sleep",
764 Op::ResetAgentComputer => "Reset an agent's computer",
765 Op::ListAgentComputerCommands => "List an agent's computer's commands",
766 Op::GetRunnerSettings => "Get runner settings",
767 Op::CreateRunnerRegistrationToken => "Create a runner registration token",
768 Op::RemoveRunner => "Remove a self-hosted runner",
769 Op::CreateRunnerGroup => "Create a runner group",
770 Op::UpdateRunnerGroup => "Change a runner group",
771 Op::DeleteRunnerGroup => "Delete a runner group",
772 Op::UpdateRunnerSettings => "Change runner settings",
773 Op::ListCollaborators => "List who has access",
774 Op::AddCollaborator => "Add a collaborator",
775 Op::UpdateCollaborator => "Change a collaborator's role",
776 Op::RemoveCollaborator => "Remove a collaborator",
777 Op::GetCollaboratorPermission => "Get someone's permission",
778 Op::ListRepoInvitations => "List a repository's invitations",
779 Op::RevokeRepoInvitation => "Revoke a repository invitation",
780 Op::ListMyRepoInvitations => "List your repository invitations",
781 Op::AcceptRepoInvitation => "Accept a repository invitation",
782 Op::DeclineRepoInvitation => "Decline a repository invitation",
783 Op::SetBasePermission => "Set the base permission",
784 Op::ListOutsideCollaborators => "List outside collaborators",
785 Op::ListSecurityAlerts => "List security alerts",
786 Op::DismissSecurityAlert => "Dismiss a security alert",
787 Op::ReopenSecurityAlert => "Reopen a security alert",
788 Op::ListNotifications => "List notifications",
789 Op::MarkNotificationsRead => "Mark notifications read",
790 Op::GetNotificationThread => "Get a thread",
791 Op::MarkThreadRead => "Mark a thread read",
792 Op::MarkThreadDone => "Mark a thread done",
793 Op::SaveThread => "Save a thread",
794 Op::SnoozeThread => "Snooze a thread",
795 Op::GetThreadSubscription => "Get a thread subscription",
796 Op::SetThreadSubscription => "Set a thread subscription",
797 Op::DeleteThreadSubscription => "Unsubscribe from a thread",
798 Op::GetRepoSubscription => "Get how you watch a repository",
799 Op::SetRepoSubscription => "Watch a repository",
800 Op::DeleteRepoSubscription => "Stop watching a repository",
801 Op::ListWatchedRepos => "List repositories you watch",
802 Op::ListPinnedProjects => "List your pinned projects",
803 Op::GetUsage => "Get a workspace's usage",
804 Op::GetBudget => "Get a workspace's budget",
805 Op::SetBudget => "Change a workspace's budget",
806 Op::GetAiCredit => "Get a workspace's AI credit",
807 Op::BuyAiCredit => "Buy AI credit",
808 Op::ListInvoices => "List a workspace's invoices",
809 Op::GetBillingDetails => "Get a workspace's billing details",
810 Op::ListGatewayRequests => "List a workspace's AI Gateway requests",
811 Op::PinProject => "Pin a project",
812 Op::UnpinProject => "Unpin a project",
813 Op::ReorderPinnedProjects => "Reorder your pinned projects",
814 Op::ListProjects => "List a workspace's projects",
815 Op::GetProject => "Get a project",
816 Op::UpdateProject => "Update a project",
817 Op::ListTeams => "List teams",
818 Op::GetTeam => "Get a team",
819 Op::CreateTeam => "Create a team",
820 Op::UpdateTeam => "Update a team",
821 Op::DeleteTeam => "Delete a team",
822 Op::ListTeamMembers => "List a team's members",
823 Op::SetTeamMember => "Add or change a team member",
824 Op::RemoveTeamMember => "Remove a team member",
825 Op::ListChildTeams => "List child teams",
826 Op::ListTeamRepos => "List a team's repositories",
827 Op::SetTeamRepo => "Give a team a role on a repository",
828 Op::RemoveTeamRepo => "Remove a team from a repository",
829 Op::SetTeamReviewAssignment => "Set a team's review assignment",
830 Op::ListUserTeams => "List someone's teams",
831 Op::RequestReviewers => "Request reviewers",
832 Op::RemoveRequestedReviewers => "Remove requested reviewers",
833 Op::GetCodeownersErrors => "List CODEOWNERS errors",
834 Op::Security(op) => op.title(),
835 Op::Rules(op) => op.title(),
836 Op::Checks(op) => op.title(),
837 Op::About(op) => op.title(),
838 Op::Deployments(op) => op.title(),
839 Op::Protection(op) => op.title(),
840 Op::Tokens(op) => op.title(),
841 Op::Artifacts(op) => op.title(),
842 Op::Archives(op) => op.title(),
843 Op::DeployKeys(op) => op.title(),
844 Op::Mirrors(op) => op.title(),
845 Op::Packages(op) => op.title(),
846 Op::Folios(op) => op.title(),
847 Op::Customize(op) => op.title(),
848 }
849}
850
851/// Why an operation can be refused with `402 payment_required`, if it
852/// can: the ones that start an agent, when the workspace has no credit,
853/// and the ones that make a repository private in a workspace, when a free
854/// workspace's private storage has no room for it.
855fn may_need_payment(op: Op) -> Option<&'static str> {
856 match op {
857 Op::AssignIssue | Op::PlanWork | Op::ApplyPlan => Some("The workspace has no agent credit."),
858 Op::WakeAgentComputer => Some("The workspace's plan refuses compute: it is paused, or over its limit."),
859 Op::UpdateRepo | Op::SetRepoVisibility | Op::TransferRepo => Some(
860 "A free workspace's private storage has no room for this private repository.",
861 ),
862 _ => None,
863 }
864}
865
866/// What the reference says beyond each operation's own description, keyed
867/// by operation id, written by hand from what the services return: `notes`
868/// (Markdown, added to the description) and example `params` (path),
869/// `query`, `request` (body) and `response`.
870const REFERENCE: &str = include_str!("reference.json");
871
872fn examples() -> Map<String, Value> {
873 match serde_json::from_str(REFERENCE) {
874 Ok(Value::Object(examples)) => examples,
875 _ => Map::new(),
876 }
877}
878
879/// `/repos/:owner/:name` as OpenAPI writes it: `/repos/{owner}/{name}`.
880fn openapi_path(route: &Route) -> String {
881 route
882 .path
883 .split('/')
884 .map(|segment| match segment.strip_prefix(':') {
885 Some(name) => format!("{{{name}}}"),
886 None => segment.to_owned(),
887 })
888 .collect::<Vec<_>>()
889 .join("/")
890}
891
892fn error_response(description: &str) -> Value {
893 json!({
894 "description": description,
895 "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } },
896 })
897}
898
899/// A parameter in the path or the query, described by the operation's
900/// input schema where it has the same name.
901fn parameter(name: &str, place: &str, required: bool, schema: Option<&Value>) -> Value {
902 let mut schema = schema.cloned().unwrap_or_else(|| json!({ "type": "string" }));
903 let description = match name {
904 "owner" => Some(Value::from("The workspace that owns the repository.")),
905 "name" => Some(Value::from("The repository's name.")),
906 _ => schema.as_object_mut().and_then(|schema| schema.remove("description")),
907 };
908 let mut parameter = json!({
909 "name": name,
910 "in": place,
911 "required": required,
912 "schema": schema,
913 });
914 if let Some(description) = description {
915 parameter["description"] = description;
916 }
917 parameter
918}
919
920/// The operation id of a route. An operation reached at a workspace's
921/// address as well as a repository's is documented once for each, with its
922/// own id; GitHub's alternative addresses for one operation keep GitHub's
923/// names.
924fn operation_id(route: &Route) -> String {
925 let op = route.op;
926 let base = match (route.method, route.path.rsplit('/').next().unwrap_or_default()) {
927 ("PUT", "enable") => "enable_workflow".to_owned(),
928 ("PUT", "disable") => "disable_workflow".to_owned(),
929 ("POST", "rerun-failed-jobs") => "rerun_failed_jobs".to_owned(),
930 ("POST", "rerun") if route.path.contains("/jobs/:job/") => "rerun_job".to_owned(),
931 ("POST", "force-cancel") => "force_cancel_workflow_run".to_owned(),
932 ("GET", ":attempt") => "get_workflow_run_attempt".to_owned(),
933 ("PATCH", ":setting") => "update_actions_variable".to_owned(),
934 ("GET", "runs") if route.path.contains("/workflows/:workflow/") => "list_runs_of_workflow".to_owned(),
935 // One repository's notifications, and an issue's subscription by
936 // its number rather than a thread's id.
937 (_, "notifications") if route.path.starts_with("/repos/") => match op {
938 Op::ListNotifications => "list_repo_notifications".to_owned(),
939 _ => "mark_repo_notifications_read".to_owned(),
940 },
941 (method, "subscription") if route.path.contains("/issues/:number/") => match method {
942 "GET" => "get_issue_subscription".to_owned(),
943 "PUT" => "set_issue_subscription".to_owned(),
944 _ => "delete_issue_subscription".to_owned(),
945 },
946 // One label off an issue, by its name in the path.
947 ("DELETE", ":label") if route.path.contains("/issues/:number/") => "remove_issue_label".to_owned(),
948 ("DELETE", "saved") => "unsave_thread".to_owned(),
949 ("DELETE", "snooze") => "unsnooze_thread".to_owned(),
950 _ => op.name().to_owned(),
951 };
952 if route.path.starts_with("/workspaces/") && ROUTES.iter().any(|other| other.op == op && other.path.starts_with("/repos/")) {
953 format!("{base}_for_workspace")
954 } else {
955 base
956 }
957}
958
959/// The summary of a route: its operation's title, or for one of GitHub's
960/// alternative addresses, what that address does.
961fn summary(route: &Route, id: &str) -> String {
962 let base = match id.trim_end_matches("_for_workspace") {
963 "enable_workflow" => "Turn a workflow on",
964 "disable_workflow" => "Turn a workflow off",
965 "rerun_failed_jobs" => "Re-run failed jobs",
966 "rerun_job" => "Re-run a job",
967 "force_cancel_workflow_run" => "Force-cancel a workflow run",
968 "get_workflow_run_attempt" => "Get a workflow run attempt",
969 "update_actions_variable" => "Update a variable",
970 "list_runs_of_workflow" => "List a workflow's runs",
971 "list_repo_notifications" => "List a repository's notifications",
972 "mark_repo_notifications_read" => "Mark a repository's notifications read",
973 "get_issue_subscription" => "Get your subscription to an issue",
974 "set_issue_subscription" => "Subscribe to an issue",
975 "delete_issue_subscription" => "Unsubscribe from an issue",
976 "unsave_thread" => "Unsave a thread",
977 "unsnooze_thread" => "Bring a snoozed thread back",
978 _ => title(route.op),
979 };
980 if id.ends_with("_for_workspace") {
981 format!("{base} for a workspace")
982 } else {
983 base.to_owned()
984 }
985}
986
987fn operation(route: &Route) -> Value {
988 let op = route.op;
989 let path_params: Vec<&str> = route.params().collect();
990 // `owner` and `name` in the path stand for the operation's `repo` input,
991 // so a `name` in the body, such as a check run's, is the body's own.
992 let stands_for_repo =
993 |name: &str| matches!(name, "owner" | "name") && path_params.contains(&"owner") && path_params.contains(&"name");
994 let covered = |name: &str| name == "repo" || (path_params.contains(&name) && !stands_for_repo(name));
995 let all_properties = op.properties();
996 let mut properties = all_properties.clone();
997 properties.retain(|name, _| !covered(name));
998 let required: Vec<String> = op
999 .required()
1000 .into_iter()
1001 .filter(|name| !covered(name))
1002 .collect();
1003
1004 let mut parameters: Vec<Value> = path_params
1005 .iter()
1006 .map(|name| parameter(name, "path", true, if stands_for_repo(name) { None } else { all_properties.get(*name) }))
1007 .collect();
1008 let mut body = Value::Null;
1009 if route.method == "GET" {
1010 for (name, key) in route.query {
1011 parameters.push(parameter(
1012 name,
1013 "query",
1014 required.iter().any(|required| required == key),
1015 properties.get(*key),
1016 ));
1017 }
1018 } else if !properties.is_empty() {
1019 let mut schema = json!({ "type": "object", "properties": properties });
1020 if !required.is_empty() {
1021 schema["required"] = json!(required);
1022 }
1023 body = json!({
1024 "required": !required.is_empty(),
1025 "content": { "application/json": { "schema": schema } },
1026 });
1027 }
1028
1029 let id = operation_id(route);
1030 let mut responses = Map::new();
1031 if route.no_content() {
1032 responses.insert("204".into(), json!({ "description": "Success. There is no body." }));
1033 } else {
1034 responses.insert(
1035 "200".into(),
1036 json!({
1037 "description": "Success.",
1038 "content": { "application/json": { "schema": {} } },
1039 }),
1040 );
1041 }
1042 responses.insert(
1043 "401".into(),
1044 error_response("A token is required, or the one sent is not valid."),
1045 );
1046 if let Some(reason) = may_need_payment(op) {
1047 responses.insert("402".into(), error_response(reason));
1048 }
1049 responses.insert(
1050 "403".into(),
1051 error_response("Signed in, but not allowed to do this: the role you have is not enough, or the token lacks the scope it needs, which `needed_scope` names."),
1052 );
1053 if !matches!(op, Op::Whoami | Op::ListRepos | Op::Search) {
1054 responses.insert("404".into(), error_response("It does not exist, or you cannot see it."));
1055 }
1056 if route.method != "GET" {
1057 responses.insert(
1058 "409".into(),
1059 error_response("The request conflicts with the current state."),
1060 );
1061 }
1062 if op != Op::Whoami {
1063 responses.insert("422".into(), error_response("The input is not valid."));
1064 }
1065 // Public data can be read without a token; everything else needs one.
1066 let scope: Vec<&str> = scope_for(op.name()).map(|scope| scope.as_str()).into_iter().collect();
1067 let security = if op.needs_user() {
1068 json!([{ "token": scope }])
1069 } else {
1070 json!([{ "token": scope }, {}])
1071 };
1072 let (tool, action) = crate::tools::TOOLS
1073 .iter()
1074 .find_map(|tool| {
1075 tool.actions
1076 .iter()
1077 .find(|action| action.op == op)
1078 .map(|action| (tool.name, action.name))
1079 })
1080 .unwrap_or_default();
1081 let mut described = json!({
1082 "operationId": id,
1083 "tags": [tag(op)],
1084 "summary": summary(route, &id),
1085 "description": op.description(),
1086 "x-operation": op.name(),
1087 "x-mcp-tool": tool,
1088 "x-mcp-action": action,
1089 "x-scope": scope.first().copied(),
1090 "security": security,
1091 "parameters": parameters,
1092 "responses": responses,
1093 });
1094 if !body.is_null() {
1095 described["requestBody"] = body;
1096 }
1097 described
1098}
1099
1100/// Entries for device sign-in, which is not an operation.
1101fn onboarding() -> Map<String, Value> {
1102 let paths = json!({
1103 "/device/code": {
1104 "post": {
1105 "operationId": "device_code",
1106 "tags": ["Accounts"],
1107 "summary": "Start signing in",
1108 "description": "Begins a device sign-in. Show the person `verification_uri_complete` and have them open it in a browser, where they sign in or register and approve the code. Then poll `/device/token`.",
1109 "security": [],
1110 "requestBody": {
1111 "content": { "application/json": { "schema": {
1112 "type": "object",
1113 "properties": {
1114 "client_name": {
1115 "type": "string",
1116 "description": "What is asking, shown to the person approving. For example, Claude Code.",
1117 },
1118 },
1119 } } },
1120 },
1121 "responses": { "200": {
1122 "description": "The codes for this sign-in.",
1123 "content": { "application/json": { "schema": {
1124 "type": "object",
1125 "properties": {
1126 "device_code": { "type": "string", "description": "Secret. Send it to /device/token." },
1127 "user_code": { "type": "string", "description": "Shown to the person, like WDJB-MJHT." },
1128 "verification_uri": { "type": "string" },
1129 "verification_uri_complete": {
1130 "type": "string",
1131 "description": "The link to give the person; it carries the code.",
1132 },
1133 "expires_in": { "type": "integer", "description": "Seconds until the codes expire." },
1134 "interval": { "type": "integer", "description": "Seconds to wait between polls." },
1135 },
1136 } } },
1137 } },
1138 },
1139 },
1140 "/device/token": {
1141 "post": {
1142 "operationId": "device_token",
1143 "tags": ["Accounts"],
1144 "summary": "Finish signing in",
1145 "description": "Asks whether the person has approved. Poll no faster than the interval. The token is returned once.",
1146 "security": [],
1147 "requestBody": {
1148 "required": true,
1149 "content": { "application/json": { "schema": {
1150 "type": "object",
1151 "required": ["device_code"],
1152 "properties": { "device_code": { "type": "string" } },
1153 } } },
1154 },
1155 "responses": { "200": {
1156 "description": "The state of the sign-in.",
1157 "content": { "application/json": { "schema": {
1158 "type": "object",
1159 "required": ["status"],
1160 "properties": {
1161 "status": { "type": "string", "enum": ["pending", "approved", "denied", "expired"] },
1162 "token": { "type": "string", "description": "Present when approved." },
1163 "username": { "type": "string", "description": "Lowercased: what the account is found and linked by." },
1164 "display_username": { "type": "string", "description": "The username as its owner wrote it; the same as username when they chose no case." },
1165 "verified": {
1166 "type": "boolean",
1167 "description": "Whether the account's email is confirmed.",
1168 },
1169 },
1170 } } },
1171 } },
1172 },
1173 },
1174 });
1175 match paths {
1176 Value::Object(paths) => paths,
1177 _ => Map::new(),
1178 }
1179}
1180
1181
1182/// Puts each operation's examples, where it has them, into its request
1183/// and response. Path and query values go under `x-example-params` and
1184/// `x-example-query`, which tools that build a request can use.
1185fn attach_examples(paths: &mut Map<String, Value>) {
1186 let examples = examples();
1187 for methods in paths.values_mut() {
1188 let Some(methods) = methods.as_object_mut() else { continue };
1189 for operation in methods.values_mut() {
1190 let id = operation["operationId"].as_str().unwrap_or_default().to_owned();
1191 let name = operation["x-operation"].as_str().unwrap_or_default().to_owned();
1192 let Some(example) = examples.get(&id).or_else(|| examples.get(&name)) else {
1193 continue;
1194 };
1195 if let Some(notes) = example.get("notes").and_then(Value::as_str) {
1196 let description = operation["description"].as_str().unwrap_or_default();
1197 operation["description"] = json!(format!("{description}\n\n{notes}"));
1198 }
1199 if let Some(response) = example.get("response") {
1200 let content = &mut operation["responses"]["200"]["content"]["application/json"];
1201 if content.is_object() {
1202 content["example"] = response.clone();
1203 }
1204 }
1205 if let Some(request) = example.get("request") {
1206 let content = &mut operation["requestBody"]["content"]["application/json"];
1207 if content.is_object() {
1208 content["example"] = request.clone();
1209 }
1210 }
1211 for (key, extension) in [("params", "x-example-params"), ("query", "x-example-query")] {
1212 if let Some(values) = example.get(key) {
1213 operation[extension] = values.clone();
1214 }
1215 }
1216 }
1217 }
1218}
1219
1220pub fn document() -> Value {
1221 let mut paths = onboarding();
1222 for route in ROUTES {
1223 let entry = paths
1224 .entry(openapi_path(route))
1225 .or_insert_with(|| json!({}));
1226 entry[route.method.to_lowercase()] = operation(route);
1227 }
1228 attach_examples(&mut paths);
1229 let tags: Vec<Value> = SECTIONS
1230 .iter()
1231 .map(|(name, description, ops)| {
1232 json!({
1233 "name": name,
1234 "description": description,
1235 // The section's operations in reading order, by MCP tool name.
1236 "x-tools": ops.iter().map(|op| op.name()).collect::<Vec<_>>(),
1237 })
1238 })
1239 .collect();
1240 let codes = ["unauthenticated", "payment_required", "forbidden", "not_found", "conflict", "invalid"];
1241 json!({
1242 "openapi": "3.1.0",
1243 "info": {
1244 "title": "g1t API",
1245 "version": "1",
1246 "description": "The REST API for g1t, a git forge built for agents. The same operations are available to agents as MCP tools at https://mcp.g1t.sh. Every name in a request or response body is `snake_case`; names you chose, such as a workflow's inputs or a secret's name, are returned as you wrote them.",
1247 "license": { "name": "MIT", "identifier": "MIT" },
1248 },
1249 "servers": [{ "url": "https://api.g1t.sh" }],
1250 "security": [{ "token": [] }, {}],
1251 "tags": tags,
1252 "paths": paths,
1253 "components": {
1254 "securitySchemes": {
1255 "token": {
1256 "type": "http",
1257 "scheme": "bearer",
1258 "description": "An access token, `g1t_…`. Public data needs none. Each operation names the scope a token needs for it; see https://docs.g1t.sh/guides/authentication/#scopes.",
1259 },
1260 },
1261 "schemas": {
1262 "Error": {
1263 "type": "object",
1264 "required": ["error"],
1265 "properties": {
1266 "error": {
1267 "type": "object",
1268 "required": ["code", "message"],
1269 "properties": {
1270 "code": { "type": "string", "enum": codes },
1271 "message": { "type": "string" },
1272 "needed_scope": {
1273 "type": "string",
1274 "description": "On a 403 for an access token without the scope the call needs: that scope, such as `issues:write`.",
1275 },
1276 },
1277 },
1278 },
1279 },
1280 },
1281 },
1282 })
1283}
1284
1285#[cfg(test)]
1286mod tests {
1287 use super::*;
1288
1289 #[test]
1290 fn every_route_is_documented_once() {
1291 let document = document();
1292 let mut ids = Vec::new();
1293 for (_, methods) in document["paths"].as_object().unwrap() {
1294 for (_, operation) in methods.as_object().unwrap() {
1295 ids.push(operation["operationId"].as_str().unwrap().to_owned());
1296 }
1297 }
1298 for op in Op::ALL {
1299 assert_eq!(
1300 ids.iter().filter(|id| *id == op.name()).count(),
1301 1,
1302 "{}",
1303 op.name()
1304 );
1305 }
1306 let mut unique = ids.clone();
1307 unique.sort();
1308 unique.dedup();
1309 assert_eq!(unique.len(), ids.len(), "operation ids repeat");
1310 }
1311
1312 #[test]
1313 fn path_and_query_inputs_are_not_repeated_in_the_body() {
1314 let document = document();
1315 let merge = &document["paths"]["/repos/{owner}/{name}/pulls/{number}/merge"]["post"];
1316 let body = &merge["requestBody"]["content"]["application/json"]["schema"]["properties"];
1317 assert!(body.get("keep_issue_open").is_some());
1318 assert!(body.get("repo").is_none() && body.get("number").is_none());
1319 let list = &document["paths"]["/repos"]["get"];
1320 assert_eq!(list["parameters"][0]["name"], "q");
1321 assert!(list.get("requestBody").is_none());
1322 }
1323
1324 #[test]
1325 fn every_operation_is_in_one_section() {
1326 for op in Op::ALL {
1327 let sections = SECTIONS
1328 .iter()
1329 .filter(|(_, _, ops)| ops.contains(&op))
1330 .count();
1331 assert_eq!(sections, 1, "{}", op.name());
1332 }
1333 }
1334
1335 #[test]
1336 fn titles_read_as_sentences() {
1337 assert_eq!(title(Op::CreateIssue), "Create an issue");
1338 assert_eq!(title(Op::Whoami), "Get the current user");
1339 }
1340
1341 #[test]
1342 fn every_operation_has_an_example_response() {
1343 let examples = examples();
1344 assert!(!examples.is_empty(), "reference.json does not parse");
1345 let document = document();
1346 let mut known = Vec::new();
1347 for (path, methods) in document["paths"].as_object().unwrap() {
1348 for (method, operation) in methods.as_object().unwrap() {
1349 known.push(operation["operationId"].as_str().unwrap().to_owned());
1350 // Nothing to show for a success without a body.
1351 if operation["responses"]["204"].is_object() {
1352 continue;
1353 }
1354 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
1355 assert!(!example.is_null(), "{method} {path} has no example response");
1356 }
1357 }
1358 for id in examples.keys() {
1359 assert!(known.contains(id), "reference.json names {id}, which is not an operation");
1360 }
1361 }
1362
1363 #[test]
1364 fn example_requests_send_only_what_the_body_takes() {
1365 let document = document();
1366 for (path, methods) in document["paths"].as_object().unwrap() {
1367 for (method, operation) in methods.as_object().unwrap() {
1368 let content = &operation["requestBody"]["content"]["application/json"];
1369 let Some(example) = content["example"].as_object() else { continue };
1370 let properties = &content["schema"]["properties"];
1371 for key in example.keys() {
1372 assert!(!properties[key].is_null(), "{method} {path}: {key} is not in the body");
1373 }
1374 }
1375 }
1376 }
1377
1378 /// The docs site's copy of the document. Run with `G1T_WRITE_OPENAPI=1`
1379 /// to rewrite it after changing an operation.
1380 #[test]
1381 fn the_docs_copy_is_current() {
1382 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../docs/src/data/openapi.json");
1383 let current = serde_json::to_string_pretty(&document()).unwrap() + "\n";
1384 if std::env::var_os("G1T_WRITE_OPENAPI").is_some() {
1385 std::fs::write(path, &current).unwrap();
1386 return;
1387 }
1388 let copy = std::fs::read_to_string(path).unwrap_or_default().replace("\r\n", "\n");
1389 assert!(
1390 copy == current,
1391 "apps/docs/src/data/openapi.json is out of date: run G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi"
1392 );
1393 }
1394
1395 /// The reference shows responses as they are sent: `snake_case`.
1396 #[test]
1397 fn example_responses_are_snake_case() {
1398 let document = document();
1399 for (path, methods) in document["paths"].as_object().unwrap() {
1400 for (method, operation) in methods.as_object().unwrap() {
1401 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
1402 let leaked = g1t_kit::wire::camel_case_keys(example);
1403 assert!(leaked.is_empty(), "{method} {path} shows {leaked:?}");
1404 }
1405 }
1406 }
1407
1408 /// Examples never hold anything that reads as a real credential, which
1409 /// secret scanners rightly flag in a public repository: they end in `…`
1410 /// after the prefix, as `whsec_…` and `g1t_…` do.
1411 #[test]
1412 fn examples_hold_no_real_looking_secrets() {
1413 let prefixes = ["whsec_", "g1t_", "g1tr_", "g1trt_", "sk_live_", "sk_test_", "ghp_", "github_pat_", "xoxb-", "AKIA"];
1414 for (line, text) in REFERENCE.lines().enumerate() {
1415 for prefix in prefixes {
1416 let mut rest = text;
1417 while let Some(at) = rest.find(prefix) {
1418 let after = &rest[at + prefix.len()..];
1419 let run = after.chars().take_while(|c| c.is_ascii_alphanumeric()).count();
1420 assert!(
1421 run < 12,
1422 "reference.json line {}: `{prefix}` followed by {run} characters reads as a real secret; write `{prefix}…`",
1423 line + 1
1424 );
1425 rest = after;
1426 }
1427 }
1428 }
1429 }
1430}