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