Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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