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