The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Query } from "@distilled.cloud/core/query"; |
| 2 | import * as GraphQL from "@distilled.cloud/github/GraphQL"; |
| 3 | import * as Issues from "@distilled.cloud/github/issues"; |
| 4 | import * as Pulls from "@distilled.cloud/github/pulls"; |
| 5 | import * as Repos from "@distilled.cloud/github/repos"; |
| 6 | import { isResolved } from "alchemy/Diff"; |
| 7 | import * as Provider from "alchemy/Provider"; |
| 8 | import { Resource } from "alchemy/Resource"; |
| 9 | import { dedent } from "alchemy/Util/dedent"; |
| 10 | import * as Data from "effect/Data"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import { withBaseUrl, gitHubBaseUrlChanged } from "./BaseUrl.ts"; |
| 14 | import type * as GitHub from "./Providers.ts"; |
| 15 | |
| 16 | export class PullRequestUnexpectedResponse extends Data.TaggedError( |
| 17 | "PullRequestUnexpectedResponse", |
| 18 | )<{ |
| 19 | readonly message: string; |
| 20 | readonly cause?: unknown; |
| 21 | }> {} |
| 22 | |
| 23 | export interface PullRequestProps { |
| 24 | /** |
| 25 | * Repository owner (user or organization). |
| 26 | */ |
| 27 | owner: string; |
| 28 | |
| 29 | /** |
| 30 | * Repository name. |
| 31 | */ |
| 32 | repository: string; |
| 33 | |
| 34 | /** |
| 35 | * Pull request title. |
| 36 | */ |
| 37 | title: string; |
| 38 | |
| 39 | /** |
| 40 | * Pull request body (supports GitHub Markdown). |
| 41 | * |
| 42 | * The body is automatically dedented, so you can use indented template |
| 43 | * literals without worrying about leading whitespace. Accepts |
| 44 | * `Output<string>` at the call site via `Output.interpolate` to embed |
| 45 | * resource attributes that are not yet resolved. |
| 46 | */ |
| 47 | body?: string; |
| 48 | |
| 49 | /** |
| 50 | * The name of the branch where your changes are implemented (the source). |
| 51 | */ |
| 52 | head: string; |
| 53 | |
| 54 | /** |
| 55 | * The name of the branch you want the changes pulled into (the target). |
| 56 | */ |
| 57 | base: string; |
| 58 | |
| 59 | /** |
| 60 | * State of the pull request. Use "open" to reopen a closed PR or "closed" |
| 61 | * to close an open PR. Note: only the PR owner, repo owner, or user with |
| 62 | * push access can close PRs. |
| 63 | * @default "open" |
| 64 | */ |
| 65 | state?: "open" | "closed"; |
| 66 | |
| 67 | /** |
| 68 | * Whether the pull request is a draft. |
| 69 | * @default false |
| 70 | */ |
| 71 | draft?: boolean; |
| 72 | |
| 73 | /** |
| 74 | * Labels to attach to the pull request. The provided list fully replaces |
| 75 | * any existing labels. |
| 76 | */ |
| 77 | labels?: string[]; |
| 78 | |
| 79 | /** |
| 80 | * Assignees (user logins) to assign to the pull request. The provided list |
| 81 | * fully replaces existing assignees. |
| 82 | */ |
| 83 | assignees?: string[]; |
| 84 | |
| 85 | /** |
| 86 | * Reviewers (user logins) to request reviews from. The provided list fully |
| 87 | * replaces existing review requests. |
| 88 | */ |
| 89 | reviewers?: string[]; |
| 90 | |
| 91 | /** |
| 92 | * Team slugs (for organization repos) to request reviews from. |
| 93 | */ |
| 94 | teamReviewers?: string[]; |
| 95 | |
| 96 | /** |
| 97 | * Milestone number to assign to the pull request. Use `null` to remove |
| 98 | * milestone. |
| 99 | */ |
| 100 | milestone?: number | null; |
| 101 | |
| 102 | /** |
| 103 | * Whether maintainers of the base repository can modify the pull |
| 104 | * request's head branch. This does not change the pull request author. |
| 105 | */ |
| 106 | maintainerCanModify?: boolean; |
| 107 | |
| 108 | /** |
| 109 | * Override the GitHub host or API base URL for this resource only (e.g. |
| 110 | * `github.example.com` for GitHub Enterprise). Falls back to |
| 111 | * `GitHub.providers({ baseUrl })`, then to the host resolved by the auth |
| 112 | * provider. Changing it replaces the resource — the same name on a |
| 113 | * different GitHub instance is a different physical resource. |
| 114 | */ |
| 115 | baseUrl?: string; |
| 116 | } |
| 117 | |
| 118 | export interface PullRequest extends Resource< |
| 119 | "GitHub.PullRequest", |
| 120 | PullRequestProps, |
| 121 | { |
| 122 | /** |
| 123 | * The numeric ID of the pull request in GitHub. |
| 124 | */ |
| 125 | prNumber: number; |
| 126 | |
| 127 | /** |
| 128 | * GraphQL node ID of the pull request. |
| 129 | */ |
| 130 | nodeId: string; |
| 131 | |
| 132 | /** |
| 133 | * URL to view the pull request in a browser. |
| 134 | */ |
| 135 | htmlUrl: string; |
| 136 | |
| 137 | /** |
| 138 | * State of the pull request (open or closed). |
| 139 | */ |
| 140 | state: "open" | "closed"; |
| 141 | |
| 142 | /** |
| 143 | * Whether the pull request is merged. |
| 144 | */ |
| 145 | merged: boolean; |
| 146 | |
| 147 | /** |
| 148 | * Whether the pull request is a draft. |
| 149 | */ |
| 150 | draft: boolean; |
| 151 | |
| 152 | /** |
| 153 | * ISO-8601 timestamp of when the pull request was created. |
| 154 | */ |
| 155 | createdAt: string; |
| 156 | |
| 157 | /** |
| 158 | * ISO-8601 timestamp of the last update. |
| 159 | */ |
| 160 | updatedAt: string; |
| 161 | }, |
| 162 | never, |
| 163 | GitHub.Providers |
| 164 | > {} |
| 165 | |
| 166 | /** |
| 167 | * A GitHub pull request. |
| 168 | * |
| 169 | * `PullRequest` manages the lifecycle of a pull request in a repository. PRs |
| 170 | * are created on the first deploy and updated in place on subsequent deploys |
| 171 | * when properties change. By default, pull requests are retained on |
| 172 | * destruction to preserve history — set `destroy()` to opt in to closure. |
| 173 | * |
| 174 | * Authentication is resolved via the GitHub `Credentials` service supplied by |
| 175 | * `GitHub.providers()` (env, stored PAT, `gh` CLI, or OAuth). The token needs |
| 176 | * `repo` scope for private repositories or `public_repo` for public ones. |
| 177 | * |
| 178 | * ### Creating Pull Requests |
| 179 | * **Example:** Create a Basic Pull Request |
| 180 | * ```typescript |
| 181 | * const pr = yield* GitHub.PullRequest("feature-pr", { |
| 182 | * owner: "my-org", |
| 183 | * repository: "my-repo", |
| 184 | * title: "Add new feature", |
| 185 | * body: "## Changes\n\nThis PR adds...", |
| 186 | * head: "feature-branch", |
| 187 | * base: "main", |
| 188 | * }) |
| 189 | * ``` |
| 190 | * |
| 191 | * **Example:** Draft Pull Request with Reviewers |
| 192 | * ```typescript |
| 193 | * const pr = yield* GitHub.PullRequest("draft-pr", { |
| 194 | * owner: "my-org", |
| 195 | * repository: "my-repo", |
| 196 | * title: "WIP: New feature", |
| 197 | * body: "Work in progress...", |
| 198 | * head: "feature-branch", |
| 199 | * base: "main", |
| 200 | * draft: true, |
| 201 | * reviewers: ["reviewer1", "reviewer2"], |
| 202 | * teamReviewers: ["platform-team"], |
| 203 | * }) |
| 204 | * ``` |
| 205 | * |
| 206 | * ### Updating Pull Requests |
| 207 | * Deploy with the same logical ID and different properties to update the |
| 208 | * existing PR in place rather than creating a new one. |
| 209 | * |
| 210 | * **Example:** Update PR State |
| 211 | * ```typescript |
| 212 | * const pr = yield* GitHub.PullRequest("completed-pr", { |
| 213 | * owner: "my-org", |
| 214 | * repository: "my-repo", |
| 215 | * title: "Add new feature", |
| 216 | * body: "Completed and ready to merge.", |
| 217 | * head: "feature-branch", |
| 218 | * base: "main", |
| 219 | * state: "closed", |
| 220 | * }) |
| 221 | * ``` |
| 222 | * |
| 223 | * ### Pull Request with Labels and Milestone |
| 224 | * **Example:** Organized Pull Request |
| 225 | * ```typescript |
| 226 | * const pr = yield* GitHub.PullRequest("release-pr", { |
| 227 | * owner: "my-org", |
| 228 | * repository: "my-repo", |
| 229 | * title: "Release v1.0", |
| 230 | * body: "Release notes...", |
| 231 | * head: "release-1.0", |
| 232 | * base: "main", |
| 233 | * labels: ["release", "v1.0"], |
| 234 | * milestone: 1, |
| 235 | * }) |
| 236 | * ``` |
| 237 | * |
| 238 | * ### Infrastructure Deployment PRs |
| 239 | * A common pattern is creating PRs for infrastructure changes that require |
| 240 | * review before merging. |
| 241 | * |
| 242 | * **Example:** Infrastructure Change PR |
| 243 | * ```typescript |
| 244 | * yield* GitHub.PullRequest("infra-update", { |
| 245 | * owner: "my-org", |
| 246 | * repository: "my-repo", |
| 247 | * title: "Update infrastructure configuration", |
| 248 | * body: Output.interpolate` |
| 249 | * ## Infrastructure Changes |
| 250 | * |
| 251 | * **Database:** ${database.endpoint} |
| 252 | * **Cache:** ${cache.endpoint} |
| 253 | * |
| 254 | * Requires approval before deployment. |
| 255 | * `, |
| 256 | * head: "infra-updates", |
| 257 | * base: "main", |
| 258 | * labels: ["infrastructure"], |
| 259 | * reviewers: ["infrastructure-lead"], |
| 260 | * }) |
| 261 | * ``` |
| 262 | * |
| 263 | * @resource |
| 264 | * @product Pull Request |
| 265 | */ |
| 266 | export const PullRequest = Resource<PullRequest>("GitHub.PullRequest", { |
| 267 | defaultRemovalPolicy: "retain", |
| 268 | }); |
| 269 | |
| 270 | export const PullRequestProvider = () => |
| 271 | Provider.succeed(PullRequest, { |
| 272 | stables: ["prNumber", "nodeId"], |
| 273 | |
| 274 | // A PR belongs to (host, owner, repository, head, base) — changing any |
| 275 | // of these replaces the resource: a fresh PR is created with the new |
| 276 | // configuration, and the old one is retained by default. |
| 277 | diff: Effect.fn(function* ({ news, olds }) { |
| 278 | if (!isResolved(news)) return; |
| 279 | if (olds === undefined) return; |
| 280 | if ( |
| 281 | news.owner !== olds.owner || |
| 282 | news.repository !== olds.repository || |
| 283 | news.head !== olds.head || |
| 284 | news.base !== olds.base || |
| 285 | (yield* gitHubBaseUrlChanged(olds, news)) |
| 286 | ) { |
| 287 | return { action: "replace" }; |
| 288 | } |
| 289 | }), |
| 290 | |
| 291 | reconcile: Effect.fn( |
| 292 | function* ({ news, output }) { |
| 293 | const scope = { owner: news.owner, repo: news.repository }; |
| 294 | const body = news.body === undefined ? undefined : dedent(news.body); |
| 295 | const getPull = (number: number) => |
| 296 | Pulls.get({ ...scope, pull_number: number }).pipe( |
| 297 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 298 | ); |
| 299 | const findOpen = () => |
| 300 | Pulls.list({ |
| 301 | ...scope, |
| 302 | head: news.head.includes(":") ? news.head : `${news.owner}:${news.head}`, |
| 303 | base: news.base, |
| 304 | state: "open", |
| 305 | per_page: 100, |
| 306 | }).pipe(Effect.map((pulls) => pulls[0]?.number)); |
| 307 | let number = output?.prNumber; |
| 308 | let observed = number === undefined ? undefined : yield* getPull(number); |
| 309 | if (observed === undefined) { |
| 310 | number = yield* findOpen(); |
| 311 | if (number === undefined) { |
| 312 | number = yield* Pulls.create({ |
| 313 | ...scope, |
| 314 | title: news.title, |
| 315 | body, |
| 316 | head: news.head, |
| 317 | base: news.base, |
| 318 | draft: news.draft, |
| 319 | maintainer_can_modify: news.maintainerCanModify, |
| 320 | }).pipe( |
| 321 | Effect.map((pull) => pull.number), |
| 322 | // A 422 is a create race (an open PR already joins head and base). |
| 323 | Effect.catchTag("UnprocessableEntity", (error) => |
| 324 | findOpen().pipe( |
| 325 | Effect.flatMap((existing) => |
| 326 | existing === undefined ? Effect.fail(error) : Effect.succeed(existing), |
| 327 | ), |
| 328 | ), |
| 329 | ), |
| 330 | ); |
| 331 | } |
| 332 | observed = yield* getPull(number); |
| 333 | } |
| 334 | if (observed === undefined) { |
| 335 | return yield* new PullRequestUnexpectedResponse({ |
| 336 | message: "Pull request disappeared during reconciliation", |
| 337 | }); |
| 338 | } |
| 339 | const state = news.state ?? "open"; |
| 340 | const draft = news.draft ?? false; |
| 341 | const draftChanged = draft !== (observed.draft ?? false); |
| 342 | const syncState = draftChanged ? "open" : state; |
| 343 | if ( |
| 344 | observed.title !== news.title || |
| 345 | (body !== undefined && (observed.body ?? "") !== body) || |
| 346 | observed.state !== syncState || |
| 347 | (news.maintainerCanModify !== undefined && |
| 348 | observed.maintainer_can_modify !== news.maintainerCanModify) |
| 349 | ) { |
| 350 | yield* Pulls.update({ |
| 351 | ...scope, |
| 352 | pull_number: observed.number, |
| 353 | title: news.title, |
| 354 | body, |
| 355 | state: syncState, |
| 356 | maintainer_can_modify: news.maintainerCanModify, |
| 357 | }); |
| 358 | } |
| 359 | // GitHub only permits draft transitions while a pull request is open, |
| 360 | // and only through GraphQL. |
| 361 | if (draftChanged) { |
| 362 | yield* (draft ? convertToDraft : markReadyForReview)(observed.node_id); |
| 363 | } |
| 364 | yield* syncPullRequestMeta(news, observed.number); |
| 365 | if (draftChanged && state === "closed") { |
| 366 | yield* Pulls.update({ ...scope, pull_number: observed.number, state: "closed" }); |
| 367 | } |
| 368 | const final = yield* getPull(observed.number); |
| 369 | if (final === undefined) { |
| 370 | return yield* new PullRequestUnexpectedResponse({ |
| 371 | message: "Pull request disappeared after reconciliation", |
| 372 | }); |
| 373 | } |
| 374 | return attributes(final); |
| 375 | }, |
| 376 | (effect, { news }) => effect.pipe(withBaseUrl(news.baseUrl)), |
| 377 | ), |
| 378 | |
| 379 | // Enumerate every pull request across the repositories the token can see. |
| 380 | list: Effect.fn(function* () { |
| 381 | const repos = yield* Stream.runCollect( |
| 382 | Repos.listForAuthenticatedUser.items({ per_page: 100 }), |
| 383 | ); |
| 384 | const perRepo = yield* Effect.forEach( |
| 385 | repos, |
| 386 | (repo) => |
| 387 | Stream.runCollect( |
| 388 | Pulls.list.items({ |
| 389 | owner: repo.owner.login, |
| 390 | repo: repo.name, |
| 391 | state: "all", |
| 392 | per_page: 100, |
| 393 | }), |
| 394 | ).pipe( |
| 395 | Effect.map((pulls) => |
| 396 | pulls.map((pr) => ({ |
| 397 | prNumber: pr.number, |
| 398 | nodeId: pr.node_id, |
| 399 | htmlUrl: pr.html_url, |
| 400 | state: pr.state as "open" | "closed", |
| 401 | merged: pr.merged_at !== null, |
| 402 | draft: pr.draft ?? false, |
| 403 | createdAt: pr.created_at, |
| 404 | updatedAt: pr.updated_at, |
| 405 | })), |
| 406 | ), |
| 407 | Effect.catchTag(["Forbidden", "NotFound"], () => Effect.succeed([])), |
| 408 | ), |
| 409 | { concurrency: 10 }, |
| 410 | ); |
| 411 | return perRepo.flat(); |
| 412 | }), |
| 413 | |
| 414 | delete: Effect.fn( |
| 415 | function* ({ olds, output }) { |
| 416 | const pull = { owner: olds.owner, repo: olds.repository, pull_number: output.prNumber }; |
| 417 | |
| 418 | // GitHub preserves pull request history; destruction closes it. |
| 419 | const observed = yield* Pulls.get(pull).pipe( |
| 420 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 421 | ); |
| 422 | if (observed?.state === "open") { |
| 423 | yield* Pulls.update({ ...pull, state: "closed" }).pipe( |
| 424 | Effect.catchTag("NotFound", () => Effect.void), |
| 425 | ); |
| 426 | } |
| 427 | }, |
| 428 | (effect, { olds }) => effect.pipe(withBaseUrl(olds.baseUrl)), |
| 429 | ), |
| 430 | }); |
| 431 | |
| 432 | const attributes = (data: Pulls.PullRequest) => ({ |
| 433 | prNumber: data.number, |
| 434 | nodeId: data.node_id, |
| 435 | htmlUrl: data.html_url, |
| 436 | state: data.state as "open" | "closed", |
| 437 | merged: data.merged, |
| 438 | draft: data.draft ?? false, |
| 439 | createdAt: data.created_at, |
| 440 | updatedAt: data.updated_at, |
| 441 | }); |
| 442 | |
| 443 | const sameNames = (left: string[], right: string[]) => |
| 444 | JSON.stringify([...new Set(left)].sort()) === JSON.stringify([...new Set(right)].sort()); |
| 445 | |
| 446 | const convertToDraft = Query.fn( |
| 447 | (pullRequestId: string) => |
| 448 | GraphQL.GitHub.convertPullRequestToDraft({ input: { pullRequestId } }).pullRequest.id, |
| 449 | ); |
| 450 | |
| 451 | const markReadyForReview = Query.fn( |
| 452 | (pullRequestId: string) => |
| 453 | GraphQL.GitHub.markPullRequestReadyForReview({ input: { pullRequestId } }).pullRequest.id, |
| 454 | ); |
| 455 | |
| 456 | const syncPullRequestMeta = Effect.fn(function* (props: PullRequestProps, prNumber: number) { |
| 457 | const scope = { owner: props.owner, repo: props.repository }; |
| 458 | const issue = { ...scope, issue_number: prNumber }; |
| 459 | const data = yield* Issues.get(issue); |
| 460 | const labels = data.labels.map((label) => |
| 461 | typeof label === "string" ? label : (label.name ?? ""), |
| 462 | ); |
| 463 | if (props.labels !== undefined && !sameNames(labels, props.labels)) { |
| 464 | yield* Issues.setLabels({ ...issue, body: { labels: props.labels } }); |
| 465 | } |
| 466 | const assignees = data.assignees?.map((user) => user.login) ?? []; |
| 467 | if (props.assignees !== undefined && !sameNames(assignees, props.assignees)) { |
| 468 | yield* Issues.update({ ...issue, assignees: props.assignees }); |
| 469 | } |
| 470 | if (props.milestone !== undefined && (data.milestone?.number ?? null) !== props.milestone) { |
| 471 | yield* Issues.update({ ...issue, milestone: props.milestone }); |
| 472 | } |
| 473 | if (props.reviewers !== undefined || props.teamReviewers !== undefined) { |
| 474 | const pull = { ...scope, pull_number: prNumber }; |
| 475 | const current = yield* Pulls.listRequestedReviewers(pull); |
| 476 | const users = current.users.map((user) => user.login); |
| 477 | const teams = current.teams.map((team) => team.slug); |
| 478 | const removeUsers = |
| 479 | props.reviewers === undefined ? [] : users.filter((user) => !props.reviewers!.includes(user)); |
| 480 | const removeTeams = |
| 481 | props.teamReviewers === undefined |
| 482 | ? [] |
| 483 | : teams.filter((team) => !props.teamReviewers!.includes(team)); |
| 484 | if (removeUsers.length || removeTeams.length) { |
| 485 | yield* Pulls.removeRequestedReviewers({ |
| 486 | ...pull, |
| 487 | reviewers: removeUsers, |
| 488 | team_reviewers: removeTeams, |
| 489 | }); |
| 490 | } |
| 491 | const addUsers = (props.reviewers ?? []).filter((user) => !users.includes(user)); |
| 492 | const addTeams = (props.teamReviewers ?? []).filter((team) => !teams.includes(team)); |
| 493 | if (addUsers.length || addTeams.length) { |
| 494 | yield* Pulls.requestReviewers({ |
| 495 | ...pull, |
| 496 | reviewers: addUsers, |
| 497 | team_reviewers: addTeams, |
| 498 | }); |
| 499 | } |
| 500 | } |
| 501 | }); |