Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubPullRequestProvider.ts

744 lines26.9 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";
3import * as Cache from "effect/Cache";
4import * as Duration from "effect/Duration";
5import * as Equal from "effect/Equal";
6import * as Exit from "effect/Exit";
7import * as Hash from "effect/Hash";
8import * as Effect from "effect/Effect";
9import type {
10 PullRequestActor,
11 PullRequestCapabilities,
12 PullRequestCheck,
13 PullRequestReaction,
14 PullRequestViewerPermissions,
15} from "@t3tools/contracts";
16​
17import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
18import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
19import {
20 PullRequestProviderError,
21 type PullRequestProviderFailure,
22 type ProviderChangeRequestActivity,
23 type ProviderChangeRequestDetail,
24 type PullRequestProviderApi,
25 type ProviderRepositoryRef,
26} from "@t3tools/source-control-core/server/PullRequestProvider";
27import type {
28 GitHubRepositoryAccess,
29 GitHubViewerAccess,
30 GitHubWorkflowRunApproval,
31} from "./gitHubPullRequestJson.ts";
32import { definition } from "../shared/definition.ts";
33​
34const CAPABILITIES: PullRequestCapabilities = {
35 diff: true,
36 comment: true,
37 actions: [...definition.changeRequestActions],
38 mergeMethods: ["merge", "squash", "rebase"],
39 deleteBranch: true,
40 updateMethods: ["merge", "rebase"],
41 search: true,
42 reactions: true,
43 viewedFiles: "host",
44 review: {
45 inlineComment: true,
46 rangeComment: true,
47 reply: true,
48 resolve: true,
49 verdicts: ["comment", "approve", "request-changes"],
50 },
51 reviewers: { request: true, listCandidates: true },
52 edit: { changeRequest: true, comment: true },
53 stacks: true,
54 stackActions: true,
55 labels: true,
56 // Statuses and check runs land on the head commit itself and are read whole, so an empty list
57 // after a push is CI that never started rather than a read that saw nothing.
58 checksAlwaysReport: true,
59};
60​
61const UNAVAILABLE_REQUIREMENT = {
62 missing:
63 "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI (https://cli.github.com/) and run `gh auth login`.",
64 unauthenticated:
65 "GitHub has no working credential for this host. Run `gh auth login`, or check the account and hosts in Settings → Source Control.",
66};
67​
68/**
69 * Asking somebody else for a review needs write access, which is the one thing here an author
70 * cannot do on their own pull request: GitHub shows an outside contributor the reviewer control
71 * and refuses the request behind it.
72 */
73export function gitHubViewerPermissions(
74 access: GitHubViewerAccess & Pick<GitHubRepositoryAccess, "autoMergeAllowed">,
75): PullRequestViewerPermissions {
76 return {
77 ...(access.canWrite ? { stackRebase: true } : {}),
78 actions: [
79 ...(access.canDeleteBranch === true ? (["delete-branch"] as const) : []),
80 // Keep disabling available if the repository has since turned auto-merge off.
81 ...(access.canWrite
82 ? ([
83 "merge",
84 ...(access.autoMergeAllowed && access.canMergeNow !== true
85 ? (["enable-auto-merge"] as const)
86 : []),
87 "disable-auto-merge",
88 "revert",
89 "approve-workflows",
90 ] as const)
91 : []),
92 ...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
93 ...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
94 ],
95 comment: true,
96 resolve: access.canWrite || access.didAuthor,
97 // Authors may comment on their own PRs, but GitHub rejects their approvals and change requests.
98 verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
99 requestReviewers: access.canWrite,
100 ...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
101 labels: access.canTriage,
102 };
104​
105function gitHubProviderFailure(
106 error: GitHubPullRequestApi.GitHubPullRequestApiError,
107): PullRequestProviderFailure {
108 switch (error._tag) {
109 case "GitHubCliMissingError":
110 return { reason: "missing-tool" };
111 case "GitHubNotSignedInError":
112 case "GitHubHostDisabledError":
113 case "GitHubApiAuthenticationError":
114 return { reason: "unauthenticated" };
115 case "GitHubApiRateLimitError":
116 return {
117 reason: "rate-limited",
118 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
119 };
120 case "SourceControlRateLimitPausedError":
121 return { reason: "rate-limited", retryAt: error.retryAt };
122 case "GitHubApiNotFoundError":
123 return { reason: "not-found" };
124 default:
125 return { reason: "failed" };
126 }
128​
129function withAvatar(
130 actor: PullRequestActor | null,
131 avatarsByLogin: ReadonlyMap<string, string>,
132 host: string,
133 botLogins?: ReadonlySet<string>,
134): PullRequestActor | null {
135 if (actor === null) return actor;
136 if (botLogins?.has(actor.login)) actor = { ...actor, isBot: true };
137 if (actor.avatarUrl !== null) return actor;
138 const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
139 return avatarUrl === null ? actor : { ...actor, avatarUrl };
141​
142function withWorkflowApprovals(
143 checks: ReadonlyArray<PullRequestCheck>,
144 runs: ReadonlyArray<GitHubWorkflowRunApproval>,
145 unavailable: boolean,
146): ReadonlyArray<PullRequestCheck> {
147 const representedRunIds = new Set<number>();
148 for (const check of checks) {
149 if (check.status !== "action-required" || check.url === null) continue;
150 const id = check.url.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1];
151 if (id !== undefined) representedRunIds.add(Number(id));
152 }
153 const approvalChecks = runs
154 .filter((run) => !representedRunIds.has(run.id))
155 .map((run): PullRequestCheck => ({
156 name: run.name,
157 status: "action-required",
158 description: "A maintainer must approve this workflow before it can run.",
159 url: run.url,
160 }));
161 return [
162 ...checks,
163 ...approvalChecks,
164 ...(unavailable
165 ? [
166 {
167 name: "Workflow approval status",
168 status: "action-required" as const,
169 description: "GitHub could not determine whether workflows are awaiting approval.",
170 url: null,
171 },
172 ]
173 : []),
174 ];
176​
177/** App logins have no profile page; guessed avatar URLs 404. */
178export function loginAvatarUrl(login: string, host: string): string | null {
179 return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
181​
182// Whether search covers a repository changes only when the repository is renamed or moved.
183const SEARCH_COVERAGE_TTL = Duration.hours(1);
184const SEARCH_COVERAGE_CAPACITY = 4096;
185const SEARCH_COVERAGE_CONCURRENCY = 4;
186​
187/**
188 * Whether GitHub search covers a repository. `cwd` only says where to ask, so equality ignores
189 * it and `lookup`, and every checkout of a repository shares one answer.
190 */
191class SearchCoverage {
192 readonly key: string;
193 readonly lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>;
194​
195 constructor(
196 host: string,
197 repository: string,
198 lookup: Effect.Effect<boolean, GitHubPullRequestApi.GitHubPullRequestApiError>,
199 ) {
200 this.key = `${host.toLowerCase()}\n${repository.trim().toLowerCase()}`;
201 this.lookup = lookup;
202 }
203​
204 [Equal.symbol](that: unknown): boolean {
205 return that instanceof SearchCoverage && that.key === this.key;
206 }
207 [Hash.symbol](): number {
208 return Hash.string(this.key);
209 }
211​
212const rendersEmpty = (body: string): boolean =>
213 body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
214​
215export const make = Effect.gen(function* () {
216 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
217​
218 // GitHub does not index every repository for search: a renamed one answers for its old name
219 // with silence rather than with an error. Where search has any pull request for a repository it
220 // covers it, so its silence on a page is a real empty answer; any other the caller reads on its
221 // own. A failed check is not kept.
222 const searchCoverage = yield* Cache.makeWith((request: SearchCoverage) => request.lookup, {
223 capacity: SEARCH_COVERAGE_CAPACITY,
224 timeToLive: (exit) => (Exit.isSuccess(exit) ? SEARCH_COVERAGE_TTL : Duration.zero),
225 });
226 const coverageOf = (
227 input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],
228 repository: string,
229 ) =>
230 new SearchCoverage(
231 input.host,
232 repository,
233 Effect.suspend(() =>
234 cli.searchPullRequests({
235 cwd: input.cwd,
236 host: input.host,
237 repositories: [repository],
238 state: "all",
239 involvement: "all",
240 viewer: input.viewer,
241 limit: 1,
242 }),
243 ).pipe(Effect.map((batch) => batch.items.length > 0)),
244 );
245 const unresolvedBySearch = Effect.fn("GitHubPullRequestProvider.unresolvedBySearch")(function* (
246 input: Parameters<NonNullable<PullRequestProviderApi["listChangeRequestsAcross"]>>[0],
247 batch: GitHubPullRequestApi.GitHubPullRequestSearchBatch,
248 ) {
249 // A repository a page has rows for is covered without asking.
250 yield* Effect.forEach(
251 batch.items,
252 (item) => Cache.set(searchCoverage, coverageOf(input, item.repository), true),
253 { discard: true },
254 );
255 const answered = new Set(batch.items.map((item) => item.repository.trim().toLowerCase()));
256 const silent = input.repositories.filter(
257 (repository) => !answered.has(repository.trim().toLowerCase()),
258 );
259 // A truncated first slice can be silent about a covered repository whose rows are just
260 // older than the cut, so it vouches for none. Past the first slice silence from a covered
261 // repository means its rows are older rather than absent.
262 if (input.cursor === undefined && batch.truncated) return silent;
263 return yield* Effect.filter(
264 silent,
265 (repository) =>
266 Cache.get(searchCoverage, coverageOf(input, repository)).pipe(
267 Effect.map((covered) => !covered),
268 Effect.orElseSucceed(() => true),
269 ),
270 { concurrency: SEARCH_COVERAGE_CONCURRENCY },
271 );
272 });
273​
274 const fail = (operation: string) => (error: GitHubPullRequestApi.GitHubPullRequestApiError) =>
275 new PullRequestProviderError({
276 provider: SourceControlProviderKind.make("github"),
277 operation,
278 ...gitHubProviderFailure(error),
279 detail: error.message,
280 cause: error,
281 });
282​
283 const readChecks = (input: ProviderRepositoryRef & { readonly number: number }) =>
284 cli.getPullRequestDetail(input).pipe(
285 Effect.flatMap((pullRequest) =>
286 (pullRequest.state !== "open" || pullRequest.isCrossRepository !== true
287 ? Effect.succeed({
288 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
289 unavailable: false,
290 })
291 : pullRequest.headSha == null || pullRequest.headRepositoryOwner == null
292 ? Effect.succeed({
293 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
294 unavailable: true,
295 })
296 : cli
297 .listWorkflowRunsRequiringApproval({
298 ...input,
299 headSha: pullRequest.headSha,
300 headBranch: pullRequest.headBranch,
301 headRepositoryOwner: pullRequest.headRepositoryOwner,
302 isCrossRepository: true,
303 })
304 .pipe(
305 Effect.matchEffect({
306 onFailure: (error) =>
307 error._tag === "GitHubApiRateLimitError" ||
308 error._tag === "SourceControlRateLimitPausedError"
309 ? Effect.fail(error)
310 : Effect.succeed({
311 runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
312 unavailable: true,
313 }),
314 onSuccess: (runs) => Effect.succeed({ runs, unavailable: false }),
315 }),
316 )
317 ).pipe(
318 Effect.map((workflowApprovals) => ({
319 ...pullRequest,
320 author: withAvatar(pullRequest.author, new Map(), input.host),
321 checks: withWorkflowApprovals(
322 pullRequest.checks,
323 workflowApprovals.runs,
324 workflowApprovals.unavailable,
325 ),
326 ...(workflowApprovals.unavailable
327 ? {}
328 : { workflowApprovalsRequired: workflowApprovals.runs.length }),
329 })),
330 ),
331 ),
332 );
333​
334 const provider: PullRequestProviderApi = {
335 kind: SourceControlProviderKind.make("github"),
336 capabilities: CAPABILITIES,
337 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
338 readsPublicHostWithoutCheckout: true,
339 mergeMessageRewrite: removeAgentCredits,
340 getRoutingIdentity: (input) =>
341 cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
342 withVerifiedCredential: (input, use) =>
343 cli
344 .withVerifiedCredential(input, (identity) => use(identity).pipe(Effect.result))
345 .pipe(Effect.mapError(fail("routeIdentity")), Effect.flatMap(Effect.fromResult)),
346​
347 getViewer: (input) =>
348 cli
349 .getViewerLogin({ cwd: input.cwd, host: input.host ?? "github.com" })
350 .pipe(Effect.mapError(fail("getViewer"))),
351​
352 listChangeRequests: (input) =>
353 cli
354 .listPullRequests({
355 cwd: input.cwd,
356 repository: input.repository,
357 host: input.host,
358 state: input.state,
359 involvement: input.involvement,
360 viewer: input.viewer,
361 limit: input.limit,
362 query: input.query,
363 cursor: input.cursor,
364 filters: input.filters,
365 })
366 .pipe(
367 Effect.mapError(fail("listChangeRequests")),
368 Effect.flatMap((page) =>
369 cli
370 .listActorAvatars({
371 cwd: input.cwd,
372 repository: input.repository,
373 host: input.host,
374 ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
375 })
376 .pipe(
377 Effect.orElseSucceed(() => new Map<string, string>()),
378 Effect.map((avatarsByLogin) => ({
379 ...page,
380 items: page.items.map((item) => ({
381 ...item,
382 author: withAvatar(item.author, avatarsByLogin, input.host),
383 })),
384 })),
385 ),
386 ),
387 ),
388​
389 listChangeRequestsAcross: (input) =>
390 cli
391 .searchPullRequests({
392 cwd: input.cwd,
393 host: input.host,
394 repositories: input.repositories,
395 state: input.state,
396 involvement: input.involvement,
397 viewer: input.viewer,
398 limit: input.limit,
399 query: input.query,
400 cursor: input.cursor,
401 filters: input.filters,
402 })
403 .pipe(
404 Effect.mapError(fail("listChangeRequestsAcross")),
405 Effect.flatMap((batch) =>
406 Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({
407 truncated: batch.truncated,
408 items: batch.items.map((item) => ({
409 ...item,
410 author: withAvatar(item.author, new Map<string, string>(), input.host),
411 })),
412 unresolved,
413 })),
414 ),
415 ),
416​
417 listChangeRequestStats: (input) =>
418 cli
419 .listPullRequestStats({
420 cwd: input.cwd,
421 host: input.host,
422 changeRequests: input.changeRequests,
423 })
424 .pipe(Effect.mapError(fail("listChangeRequestStats"))),
425​
426 getChangeRequestSummary: (input) =>
427 cli.getPullRequestSummary(input).pipe(
428 Effect.map((summary) => ({
429 ...summary,
430 ...(summary.author === undefined
431 ? {}
432 : { author: withAvatar(summary.author, new Map(), input.host) }),
433 })),
434 Effect.mapError(fail("getChangeRequestSummary")),
435 ),
436​
437 getChangeRequestStack: (input) =>
438 cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
439​
440 getChangeRequestWatchFingerprint: (input) =>
441 cli
442 .getPullRequestWatchFingerprint(input)
443 .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
444​
445 getChangeRequestPreview: (input) =>
446 cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
447​
448 getChangeRequestChecks: (input) =>
449 cli.revalidateChecks(input, readChecks(input)).pipe(
450 Effect.map(({ state, checks }) => ({ state, checks })),
451 Effect.mapError(fail("getChangeRequestChecks")),
452 ),
453​
454 getChangeRequest: (input) =>
455 readChecks(input).pipe(
456 Effect.map((pullRequest): ProviderChangeRequestDetail => ({
457 ...pullRequest,
458 author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
459 reviewers: [
460 ...pullRequest.reviewRequestLogins.map((login) => ({
461 login,
462 name: null,
463 avatarUrl: null,
464 })),
465 ...pullRequest.reviewRequestTeams,
466 ],
467 mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
468 viewerPermissions: gitHubViewerPermissions({
469 ...pullRequest.viewerAccess,
470 canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
471 }),
472 baseComparison:
473 pullRequest.comparison === null || pullRequest.comparison.behindBy === null
474 ? "unknown"
475 : pullRequest.comparison.behindBy > 0
476 ? "behind"
477 : "up-to-date",
478 ...(pullRequest.comparison?.behindBy == null
479 ? {}
480 : { behindBy: pullRequest.comparison.behindBy }),
481 })),
482 Effect.mapError(fail("getChangeRequest")),
483 ),
484​
485 getChangeRequestActivity: (input) =>
486 Effect.all(
487 [
488 cli.getPullRequestActivity(input),
489 cli.listReviewThreadComments(input).pipe(
490 Effect.orElseSucceed(() => ({
491 comments: [],
492 dismissalsByReviewId: new Map<string, string>(),
493 reactions: [],
494 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
495 editedAtById: new Map<string, string>(),
496 reviewThreads: [],
497 commentCount: 0,
498 truncated: true,
499 reviewThreadsTruncated: true,
500 reviewers: [],
501 avatarsByLogin: new Map<string, string>(),
502 botLogins: new Set<string>(),
503 commits: [],
504 viewer: { canUpdate: true, didAuthor: false },
505 })),
506 ),
507 ],
508 { concurrency: 2 },
509 ).pipe(
510 Effect.mapError(fail("getChangeRequestActivity")),
511 Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => {
512 const commitStats = new Map(
513 pullRequest.commits.map(({ oid, additions, deletions }) => [
514 oid,
515 additions === undefined ? {} : { additions, deletions },
516 ]),
517 );
518 return {
519 author: withAvatar(
520 pullRequest.author,
521 reviewThreads.avatarsByLogin,
522 input.host,
523 reviewThreads.botLogins,
524 ),
525 reviewers: reviewThreads.reviewers,
526 reactions: reviewThreads.reactions,
527 commits: (reviewThreads.commits.length > 0
528 ? reviewThreads.commits
529 : pullRequest.commits
530 ).map((commit) => ({
531 ...commit,
532 ...commitStats.get(commit.oid),
533 authors: commit.authors?.map(
534 (author) =>
535 withAvatar(
536 author,
537 reviewThreads.avatarsByLogin,
538 input.host,
539 reviewThreads.botLogins,
540 ) ?? author,
541 ),
542 })),
543 comments: [...pullRequest.comments, ...reviewThreads.comments]
544 .map((comment) => ({
545 ...comment,
546 // Dismissal reasons live on timeline events; HTML-only bot reviews need that fallback too.
547 body:
548 comment.kind === "review" &&
549 comment.reviewState?.toUpperCase() === "DISMISSED" &&
550 rendersEmpty(comment.body)
551 ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
552 : comment.body,
553 author: withAvatar(
554 comment.author,
555 reviewThreads.avatarsByLogin,
556 input.host,
557 reviewThreads.botLogins,
558 ),
559 reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
560 editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
561 }))
562 .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
563 commentCount: pullRequest.comments.length + reviewThreads.commentCount,
564 commentsTruncated: reviewThreads.truncated,
565 reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
566 reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
567 ...thread,
568 comments: thread.comments.map((comment) => ({
569 ...comment,
570 author: withAvatar(
571 comment.author,
572 reviewThreads.avatarsByLogin,
573 input.host,
574 reviewThreads.botLogins,
575 ),
576 })),
577 })),
578 };
579 }),
580 ),
581​
582 getReviewThreadComments: (input) =>
583 cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
584​
585 getViewerPermissions: (input) => {
586 const lightAccess = cli
587 .getViewerAccess({ ...input, allowReserve: true })
588 .pipe(Effect.map((access) => gitHubViewerPermissions(access)));
589 if (input.includeUpdateBranch === false) {
590 return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
591 }
592 return cli.getPullRequestDetail(input).pipe(
593 Effect.provideService(SourceControlRateLimit.Interactive, true),
594 Effect.map((pullRequest) =>
595 gitHubViewerPermissions({
596 ...pullRequest.viewerAccess,
597 canUpdateBranch:
598 pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
599 }),
600 ),
601 Effect.catchIf(
602 (error) =>
603 error._tag !== "GitHubApiRateLimitError" &&
604 error._tag !== "SourceControlRateLimitPausedError",
605 () => lightAccess,
606 ),
607 Effect.mapError(fail("getViewerPermissions")),
608 );
609 },
610​
611 getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
612​
613 getDiffFileContents: (input) =>
614 cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
615​
616 getFilesViewed: (input) =>
617 cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
618​
619 getFileStats: (input) =>
620 cli.getPullRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
621 setFilesViewed: (input) =>
622 cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
623​
624 listReviewerCandidates: (input) =>
625 cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
626​
627 setReviewerRequest: (input) =>
628 cli
629 .setReviewerRequest({
630 cwd: input.cwd,
631 repository: input.repository,
632 host: input.host,
633 number: input.number,
634 reviewers: input.reviewers,
635 requested: input.requested,
636 })
637 .pipe(Effect.mapError(fail("setReviewerRequest"))),
638​
639 listLabelCandidates: (input) =>
640 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
641​
642 listRepositoryLabels: (input) =>
643 cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),
644​
645 searchRepositoryAuthors: (input) =>
646 cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
647​
648 setLabels: (input) =>
649 cli
650 .setLabels({
651 cwd: input.cwd,
652 repository: input.repository,
653 host: input.host,
654 number: input.number,
655 labels: input.labels,
656 applied: input.applied,
657 })
658 .pipe(Effect.mapError(fail("setLabels"))),
659​
660 runAction: (input) =>
661 cli
662 .runPullRequestAction({
663 cwd: input.cwd,
664 repository: input.repository,
665 host: input.host,
666 number: input.number,
667 action: input.action,
668 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
669 ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
670 ...(input.expectedStackHeads === undefined
671 ? {}
672 : { expectedStackHeads: input.expectedStackHeads }),
673 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
674 ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
675 })
676 .pipe(Effect.mapError(fail("runAction"))),
677​
678 updateChangeRequest: (input) =>
679 cli
680 .updatePullRequest({
681 cwd: input.cwd,
682 repository: input.repository,
683 host: input.host,
684 number: input.number,
685 ...(input.title === undefined ? {} : { title: input.title }),
686 ...(input.body === undefined ? {} : { body: input.body }),
687 })
688 .pipe(Effect.mapError(fail("updateChangeRequest"))),
689​
690 comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
691​
692 updateComment: (input) =>
693 cli
694 .updateComment({
695 cwd: input.cwd,
696 repository: input.repository,
697 host: input.host,
698 number: input.number,
699 commentId: input.commentId,
700 kind: input.kind,
701 body: input.body,
702 })
703 .pipe(Effect.mapError(fail("updateComment"))),
704​
705 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
706​
707 replyToThread: (input) =>
708 cli
709 .replyToReviewThread({
710 cwd: input.cwd,
711 repository: input.repository,
712 host: input.host,
713 threadId: input.threadId,
714 body: input.body,
715 })
716 .pipe(Effect.mapError(fail("replyToThread"))),
717​
718 setReaction: (input) =>
719 cli
720 .setReaction({
721 cwd: input.cwd,
722 repository: input.repository,
723 host: input.host,
724 number: input.number,
725 ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
726 content: input.content,
727 reacted: input.reacted,
728 })
729 .pipe(Effect.mapError(fail("setReaction"))),
730​
731 setThreadResolution: (input) =>
732 cli
733 .setReviewThreadResolution({
734 cwd: input.cwd,
735 repository: input.repository,
736 host: input.host,
737 threadId: input.threadId,
738 resolved: input.resolved,
739 })
740 .pipe(Effect.mapError(fail("setThreadResolution"))),
741 };
742​
743 return provider;
744});