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