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